diff --git a/src/com/zebraimaging/ZebraInputHandler.java b/src/com/zebraimaging/ZebraInputHandler.java index 10abc1936a..e5aac3bdb1 100644 --- a/src/com/zebraimaging/ZebraInputHandler.java +++ b/src/com/zebraimaging/ZebraInputHandler.java @@ -14,163 +14,158 @@ * not expected to create instances of this class directly or call its methods. To use it, specify it as the * gov.nasa.worldwind.avkey.InputHandlerClassName in the WorldWind configuration file. */ -public class ZebraInputHandler extends AWTInputHandler -{ - /** All instantiations of this class are stored for internal retrieval. */ +public class ZebraInputHandler extends AWTInputHandler { + + /** + * All instantiations of this class are stored for internal retrieval. + */ private static List instances = new ArrayList(); private static Timer repaintContextsTimer = null; - - final static TimerTask repaintContextsTask = new TimerTask() - { - public void run() - { - Iterator itr = instances.iterator(); - while (itr.hasNext()) - { - ZebraInputHandler h = itr.next(); - if (h.NeedsRefresh() == true) - { - h.SetRefresh(false); - h.getWorldWindow().redraw(); - } - } - } - }; - - private long hwnd = 0; - private boolean arGL2Present = false; + + final static TimerTask repaintContextsTask = new TimerTask() { + public void run() { + Iterator itr = instances.iterator(); + while (itr.hasNext()) { + ZebraInputHandler h = itr.next(); + if (h.NeedsRefresh() == true) { + h.SetRefresh(false); + h.getWorldWindow().redraw(); + } + } + } + }; + + private long hwnd = 0; + private boolean arGL2Present = false; private boolean refresh = false; - - public ZebraInputHandler() - { + + public ZebraInputHandler() { /** - * Attempt to load zebraIntegrator. If it's not found, assume we're either: - * (a) Not connected to the Zebra UPSD Dynamic Display. - * (b) Not using the Zebra integration tools. + * Attempt to load zebraIntegrator. If it's not found, assume we're either: (a) Not connected to the Zebra UPSD + * Dynamic Display. (b) Not using the Zebra integration tools. */ - try - { + try { System.loadLibrary("arGL2Integrator"); arGL2Present = true; instances.add(this); System.out.println("Loaded arGL2Integrator successfully"); - } - catch (UnsatisfiedLinkError e) - { + } catch (UnsatisfiedLinkError e) { System.out.println("FAILED to load arGL2Integrator.dll"); } - - if (repaintContextsTimer == null) - { - repaintContextsTimer = new Timer(); - repaintContextsTimer.scheduleAtFixedRate(repaintContextsTask, 0, 10); + + if (repaintContextsTimer == null) { + repaintContextsTimer = new Timer(); + repaintContextsTimer.scheduleAtFixedRate(repaintContextsTask, 0, 10); } } - private synchronized void SetRefresh(boolean value) - { - refresh = value; + private synchronized void SetRefresh(boolean value) { + refresh = value; } - - private synchronized boolean NeedsRefresh() - { - return refresh; - } - - public void keyPressed(KeyEvent e) - { + + private synchronized boolean NeedsRefresh() { + return refresh; + } + + public void keyPressed(KeyEvent e) { boolean consumed = false; - if (arGL2Present) + if (arGL2Present) { consumed = zebraKeyPressed(getGLCanvasHandle(), e.getKeyCode()); - if (consumed == true) + } + if (consumed == true) { e.consume(); - else + } else { super.keyPressed(e); + } } - public void keyReleased(KeyEvent e) - { + public void keyReleased(KeyEvent e) { boolean consumed = false; - if (arGL2Present) + if (arGL2Present) { consumed = zebraKeyReleased(getGLCanvasHandle(), e.getKeyCode()); - if (consumed == true) + } + if (consumed == true) { e.consume(); - else + } else { super.keyReleased(e); + } } - public void mouseClicked(MouseEvent e) - { + public void mouseClicked(MouseEvent e) { boolean consumed = false; - if (arGL2Present) + if (arGL2Present) { consumed = zebraMouseReleased(getGLCanvasHandle(), e.getButton(), e.getX(), e.getY()); - if (consumed == true) + } + if (consumed == true) { e.consume(); - else + } else { super.mouseClicked(e); + } } - public void mousePressed(MouseEvent e) - { + public void mousePressed(MouseEvent e) { boolean consumed = false; - if (arGL2Present) + if (arGL2Present) { consumed = zebraMousePressed(getGLCanvasHandle(), e.getButton(), e.getX(), e.getY()); - if (consumed == true) + } + if (consumed == true) { e.consume(); - else + } else { super.mousePressed(e); + } } - public void mouseReleased(MouseEvent e) - { + public void mouseReleased(MouseEvent e) { boolean consumed = false; - if (arGL2Present) + if (arGL2Present) { consumed = zebraMouseReleased(getGLCanvasHandle(), e.getButton(), e.getX(), e.getY()); - if (consumed == true) + } + if (consumed == true) { e.consume(); - else + } else { super.mouseReleased(e); + } } - public void mouseDragged(MouseEvent e) - { - /** The mouseDragged event does not populate the button field of MouseEvent. Therefore it must be done manually. */ + public void mouseDragged(MouseEvent e) { + /** + * The mouseDragged event does not populate the button field of MouseEvent. Therefore it must be done manually. + */ int button = 0; button = (e.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) == InputEvent.BUTTON1_DOWN_MASK ? 1 : button; button = (e.getModifiersEx() & InputEvent.BUTTON2_DOWN_MASK) == InputEvent.BUTTON2_DOWN_MASK ? 2 : button; button = (e.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) == InputEvent.BUTTON3_DOWN_MASK ? 3 : button; boolean consumed = false; - if (arGL2Present) + if (arGL2Present) { consumed = zebraMouseMoved(getGLCanvasHandle(), button, e.getX(), e.getY()); - if (consumed == true) + } + if (consumed == true) { e.consume(); - else + } else { super.mouseDragged(e); + } } - public void mouseWheelMoved(MouseWheelEvent e) - { + public void mouseWheelMoved(MouseWheelEvent e) { boolean consumed = false; - if (arGL2Present) + if (arGL2Present) { consumed = zebraMouseWheel(getGLCanvasHandle(), e.getWheelRotation()); - if (consumed == true) + } + if (consumed == true) { e.consume(); - else + } else { super.mouseWheelMoved(e); + } } - private long getGLCanvasHandle() - { + private long getGLCanvasHandle() { /** - * Returns the win32 HWND handle of the GLCanvas component by calling native - * C++ code in arGL2Integrator. + * Returns the win32 HWND handle of the GLCanvas component by calling native C++ code in arGL2Integrator. */ - if (hwnd == 0) - { + if (hwnd == 0) { WorldWindow ww = this.getWorldWindow(); - if (ww != null) - { + if (ww != null) { WorldWindowGLCanvas wwgl = (WorldWindowGLCanvas) ww; GLCanvas glc = wwgl; Canvas cv = glc; @@ -182,52 +177,46 @@ private long getGLCanvasHandle() return hwnd; } - private static ZebraInputHandler getInstance(long hwnd) - { + private static ZebraInputHandler getInstance(long hwnd) { Iterator itr = instances.iterator(); - while (itr.hasNext()) - { + while (itr.hasNext()) { ZebraInputHandler h = itr.next(); - if (h.hwnd == hwnd) + if (h.hwnd == hwnd) { return h; + } } return null; } // Java static methods executed by arGL2Integrator.dll via JNI - - public static void forceRepaint(long hwnd) - { - /** Force the instance of the ZebraViewInputHandler class to redraw it's associated OpenGL window. */ + public static void forceRepaint(long hwnd) { + /** + * Force the instance of the ZebraViewInputHandler class to redraw it's associated OpenGL window. + */ ZebraInputHandler h = getInstance(hwnd); - if (h != null) - { - h.SetRefresh(true); - //h.refresh = true; + if (h != null) { + h.SetRefresh(true); + //h.refresh = true; } } - public static double[] getModelviewMatrix(long hwnd) - { + public static double[] getModelviewMatrix(long hwnd) { double[] matrix = new double[16]; ZebraInputHandler h = getInstance(hwnd); - if (h != null) - { + if (h != null) { h.getWorldWindow().getView().getModelviewMatrix().toArray(matrix, 0, false); } return matrix; } - public static double[] getProjectionMatrix(long hwnd) - { + public static double[] getProjectionMatrix(long hwnd) { double[] matrix = new double[16]; ZebraInputHandler h = getInstance(hwnd); - if (h != null) - { + if (h != null) { h.getWorldWindow().getView().getProjectionMatrix().toArray(matrix, 0, false); } @@ -235,7 +224,6 @@ public static double[] getProjectionMatrix(long hwnd) } // Methods imported from the zebra's arGL2Integrator.dll library and executed by java - public native boolean zebraKeyPressed(long hwnd, int keyCode); public native boolean zebraKeyReleased(long hwnd, int keyCode); diff --git a/src/config/DataFileStore.xml b/src/config/DataFileStore.xml index 18a366bb2c..df3cc5df37 100644 --- a/src/config/DataFileStore.xml +++ b/src/config/DataFileStore.xml @@ -1,15 +1,15 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> +~ WorldWind data-file store configuration +~ +~ $Id: DataFileStore.xml 1171 2013-02-11 21:45:02Z dcollins $ +--> diff --git a/src/config/Earth/AlaskaFAASectionals.xml b/src/config/Earth/AlaskaFAASectionals.xml index 965d33c4c8..ca6897df99 100644 --- a/src/config/Earth/AlaskaFAASectionals.xml +++ b/src/config/Earth/AlaskaFAASectionals.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/AsterWCS.xml b/src/config/Earth/AsterWCS.xml index 6d784176a9..aaa8f180c6 100644 --- a/src/config/Earth/AsterWCS.xml +++ b/src/config/Earth/AsterWCS.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/BMNG256.xml b/src/config/Earth/BMNG256.xml index 484025bdc4..cb1009a6ab 100644 --- a/src/config/Earth/BMNG256.xml +++ b/src/config/Earth/BMNG256.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/BMNGWMSLayer.xml b/src/config/Earth/BMNGWMSLayer.xml index b4134a4dc3..5b9095dd98 100644 --- a/src/config/Earth/BMNGWMSLayer.xml +++ b/src/config/Earth/BMNGWMSLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/BMNGWMSLayer2.xml b/src/config/Earth/BMNGWMSLayer2.xml index 37b2f121c4..6ba949741b 100644 --- a/src/config/Earth/BMNGWMSLayer2.xml +++ b/src/config/Earth/BMNGWMSLayer2.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/BingImagery.xml b/src/config/Earth/BingImagery.xml index d5d05e01de..7e56fba966 100644 --- a/src/config/Earth/BingImagery.xml +++ b/src/config/Earth/BingImagery.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/CountryBoundariesLayer.xml b/src/config/Earth/CountryBoundariesLayer.xml index 2d35da8431..0045b31247 100644 --- a/src/config/Earth/CountryBoundariesLayer.xml +++ b/src/config/Earth/CountryBoundariesLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/EarthAtNightLayer.xml b/src/config/Earth/EarthAtNightLayer.xml index a65b7b02c6..7793df1dad 100644 --- a/src/config/Earth/EarthAtNightLayer.xml +++ b/src/config/Earth/EarthAtNightLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/EarthElevationModelAsBil16.xml b/src/config/Earth/EarthElevationModelAsBil16.xml index 3f0d849a82..e1a21c72cd 100644 --- a/src/config/Earth/EarthElevationModelAsBil16.xml +++ b/src/config/Earth/EarthElevationModelAsBil16.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/EarthElevationModelAsBil32.xml b/src/config/Earth/EarthElevationModelAsBil32.xml index 112cf1a9e4..505a25fde9 100644 --- a/src/config/Earth/EarthElevationModelAsBil32.xml +++ b/src/config/Earth/EarthElevationModelAsBil32.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/EarthElevations2.xml b/src/config/Earth/EarthElevations2.xml index befe3943d0..d47bdf96e3 100644 --- a/src/config/Earth/EarthElevations2.xml +++ b/src/config/Earth/EarthElevations2.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/EarthElevations256.xml b/src/config/Earth/EarthElevations256.xml index ffc5bfb037..b97fd28e76 100644 --- a/src/config/Earth/EarthElevations256.xml +++ b/src/config/Earth/EarthElevations256.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> @@ -44,9 +44,9 @@ - - - + + + \ No newline at end of file diff --git a/src/config/Earth/EarthMergedElevationModel.xml b/src/config/Earth/EarthMergedElevationModel.xml index 8f1b38738f..caed8ff437 100644 --- a/src/config/Earth/EarthMergedElevationModel.xml +++ b/src/config/Earth/EarthMergedElevationModel.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/Landsat256.xml b/src/config/Earth/Landsat256.xml index f04f1c8a30..fed10070e8 100644 --- a/src/config/Earth/Landsat256.xml +++ b/src/config/Earth/Landsat256.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/LandsatI3WMSLayer.xml b/src/config/Earth/LandsatI3WMSLayer.xml index 45acaf6b28..d227b4cc45 100644 --- a/src/config/Earth/LandsatI3WMSLayer.xml +++ b/src/config/Earth/LandsatI3WMSLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/LandsatI3WMSLayer2.xml b/src/config/Earth/LandsatI3WMSLayer2.xml index 367188765a..1d1c323f52 100644 --- a/src/config/Earth/LandsatI3WMSLayer2.xml +++ b/src/config/Earth/LandsatI3WMSLayer2.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/MSVirtualEarthAerialLayer.xml b/src/config/Earth/MSVirtualEarthAerialLayer.xml index fd3c482370..db676a7002 100644 --- a/src/config/Earth/MSVirtualEarthAerialLayer.xml +++ b/src/config/Earth/MSVirtualEarthAerialLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/MSVirtualEarthHybridLayer.xml b/src/config/Earth/MSVirtualEarthHybridLayer.xml index 217171b2c7..4adbd8284f 100644 --- a/src/config/Earth/MSVirtualEarthHybridLayer.xml +++ b/src/config/Earth/MSVirtualEarthHybridLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/MSVirtualEarthRoadsLayer.xml b/src/config/Earth/MSVirtualEarthRoadsLayer.xml index 77c8fe43e8..24aeee1da3 100644 --- a/src/config/Earth/MSVirtualEarthRoadsLayer.xml +++ b/src/config/Earth/MSVirtualEarthRoadsLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/OpenStreetMap.xml b/src/config/Earth/OpenStreetMap.xml index 20a67004c0..fdad2e25ba 100644 --- a/src/config/Earth/OpenStreetMap.xml +++ b/src/config/Earth/OpenStreetMap.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> @@ -47,8 +47,8 @@ false true - - + + diff --git a/src/config/Earth/USDANAIPUSGSWMSImageLayer.xml b/src/config/Earth/USDANAIPUSGSWMSImageLayer.xml index bc8f0a7fd4..75fbdac60d 100644 --- a/src/config/Earth/USDANAIPUSGSWMSImageLayer.xml +++ b/src/config/Earth/USDANAIPUSGSWMSImageLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/USDANAIPWMSImageLayer.xml b/src/config/Earth/USDANAIPWMSImageLayer.xml index 9e10e97f66..33c0c0dbf0 100644 --- a/src/config/Earth/USDANAIPWMSImageLayer.xml +++ b/src/config/Earth/USDANAIPWMSImageLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/USGSDigitalOrthoLayer.xml b/src/config/Earth/USGSDigitalOrthoLayer.xml index dc53027c6a..d4aad12dfc 100644 --- a/src/config/Earth/USGSDigitalOrthoLayer.xml +++ b/src/config/Earth/USGSDigitalOrthoLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/USGSNAIPPlusLayer.xml b/src/config/Earth/USGSNAIPPlusLayer.xml index 2693f0666b..830950bd39 100644 --- a/src/config/Earth/USGSNAIPPlusLayer.xml +++ b/src/config/Earth/USGSNAIPPlusLayer.xml @@ -1,10 +1,10 @@ +~ Copyright (C) 2016 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> USGS NAIP Plus Earth/USGS NAIP Plus diff --git a/src/config/Earth/USGSTNMTopoLargeLayer.xml b/src/config/Earth/USGSTNMTopoLargeLayer.xml index 8505378d52..04a6e92332 100644 --- a/src/config/Earth/USGSTNMTopoLargeLayer.xml +++ b/src/config/Earth/USGSTNMTopoLargeLayer.xml @@ -1,10 +1,10 @@ +~ Copyright (C) 2016 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> USGS Topo Base Map Large Scale diff --git a/src/config/Earth/USGSTNMTopoLayer.xml b/src/config/Earth/USGSTNMTopoLayer.xml index e24178e013..768eb0d0b9 100644 --- a/src/config/Earth/USGSTNMTopoLayer.xml +++ b/src/config/Earth/USGSTNMTopoLayer.xml @@ -1,10 +1,10 @@ +~ Copyright (C) 2016 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> USGS Topo Base Map diff --git a/src/config/Earth/USGSTopoHighResLayer.xml b/src/config/Earth/USGSTopoHighResLayer.xml index 51492b21bd..5a5cb048ac 100644 --- a/src/config/Earth/USGSTopoHighResLayer.xml +++ b/src/config/Earth/USGSTopoHighResLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/USGSTopoLowResLayer.xml b/src/config/Earth/USGSTopoLowResLayer.xml index 1d2fbebaea..81aae0e425 100644 --- a/src/config/Earth/USGSTopoLowResLayer.xml +++ b/src/config/Earth/USGSTopoLowResLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/USGSTopoMedResLayer.xml b/src/config/Earth/USGSTopoMedResLayer.xml index 5d54d4c40c..d5909f3fd8 100644 --- a/src/config/Earth/USGSTopoMedResLayer.xml +++ b/src/config/Earth/USGSTopoMedResLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/Earth/USGSUrbanAreaOrthoLayer.xml b/src/config/Earth/USGSUrbanAreaOrthoLayer.xml index 33861a3775..e63ba2d6fc 100644 --- a/src/config/Earth/USGSUrbanAreaOrthoLayer.xml +++ b/src/config/Earth/USGSUrbanAreaOrthoLayer.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> @@ -51,10 +51,10 @@ - - - - - + + + + + \ No newline at end of file diff --git a/src/config/Earth/WorldBordersShapefile.xml b/src/config/Earth/WorldBordersShapefile.xml index 27f94dd53b..82d97bb5fe 100644 --- a/src/config/Earth/WorldBordersShapefile.xml +++ b/src/config/Earth/WorldBordersShapefile.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2014 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/WMSLayerTemplate.xml b/src/config/WMSLayerTemplate.xml index 317b82f17e..ed3f3ae501 100644 --- a/src/config/WMSLayerTemplate.xml +++ b/src/config/WMSLayerTemplate.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/worldwind.layers.xml b/src/config/worldwind.layers.xml index 25389a6b7e..28b91df7c0 100644 --- a/src/config/worldwind.layers.xml +++ b/src/config/worldwind.layers.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/config/worldwind.xml b/src/config/worldwind.xml index 55624061cc..b7a0c8cc76 100644 --- a/src/config/worldwind.xml +++ b/src/config/worldwind.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> @@ -94,10 +94,10 @@ +See https://goworldwind.org/developers-guide/symbology/tactical-symbols/#offline-use for more information on how +to configure a local symbol repository. +Examples: http://myserver.com/milstd2525/ (web server) + jar:file:milstd2525-symbols.zip! (local zip archive) --> \ No newline at end of file diff --git a/src/gov/nasa/worldwind/AbstractSceneController.java b/src/gov/nasa/worldwind/AbstractSceneController.java index cc057c551e..7ce103c14b 100644 --- a/src/gov/nasa/worldwind/AbstractSceneController.java +++ b/src/gov/nasa/worldwind/AbstractSceneController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.avlist.AVKey; @@ -25,8 +24,8 @@ * @author tag * @version $Id: AbstractSceneController.java 2442 2014-11-19 22:50:42Z tgaskins $ */ -public abstract class AbstractSceneController extends WWObjectImpl implements SceneController -{ +public abstract class AbstractSceneController extends WWObjectImpl implements SceneController { + protected Model model; protected View view; protected double verticalExaggeration = 1d; @@ -78,85 +77,88 @@ public abstract class AbstractSceneController extends WWObjectImpl implements Sc * keeping a reference to it does not leak memory. */ protected SurfaceObjectTileBuilder surfaceObjectTileBuilder = new SurfaceObjectTileBuilder(); - /** The display name for the surface object tile count performance statistic. */ + /** + * The display name for the surface object tile count performance statistic. + */ protected static final String SURFACE_OBJECT_TILE_COUNT_NAME = "Surface Object Tiles"; protected ClutterFilter clutterFilter = new BasicClutterFilter(); //protected Map groupingFilters = new HashMap(); protected boolean deferOrderedRendering; - public AbstractSceneController() - { + public AbstractSceneController() { this.setVerticalExaggeration(Configuration.getDoubleValue(AVKey.VERTICAL_EXAGGERATION, 1d)); } - public void reinitialize() - { - if (this.textRendererCache != null) + public void reinitialize() { + if (this.textRendererCache != null) { this.textRendererCache.dispose(); + } this.textRendererCache = new TextRendererCache(); } - /** Releases resources associated with this scene controller. */ - public void dispose() - { - if (this.lastPickedObjects != null) + /** + * Releases resources associated with this scene controller. + */ + public void dispose() { + if (this.lastPickedObjects != null) { this.lastPickedObjects.clear(); + } this.lastPickedObjects = null; - if (this.lastObjectsInPickRect != null) + if (this.lastObjectsInPickRect != null) { this.lastObjectsInPickRect.clear(); + } this.lastObjectsInPickRect = null; - if (this.dc != null) + if (this.dc != null) { this.dc.dispose(); + } - if (this.textRendererCache != null) + if (this.textRendererCache != null) { this.textRendererCache.dispose(); + } } - public GpuResourceCache getGpuResourceCache() - { + public GpuResourceCache getGpuResourceCache() { return this.gpuResourceCache; } - public void setGpuResourceCache(GpuResourceCache gpuResourceCache) - { + public void setGpuResourceCache(GpuResourceCache gpuResourceCache) { this.gpuResourceCache = gpuResourceCache; } - public TextRendererCache getTextRendererCache() - { + public TextRendererCache getTextRendererCache() { return textRendererCache; } - public Model getModel() - { + public Model getModel() { return this.model; } - public View getView() - { + public View getView() { return this.view; } - public void setModel(Model model) - { - if (this.model != null) + public void setModel(Model model) { + if (this.model != null) { this.model.removePropertyChangeListener(this); - if (model != null) + } + if (model != null) { model.addPropertyChangeListener(this); + } Model oldModel = this.model; this.model = model; this.firePropertyChange(AVKey.MODEL, oldModel, model); } - public void setView(View view) - { - if (this.view != null) + public void setView(View view) { + if (this.view != null) { this.view.removePropertyChangeListener(this); - if (view != null) + } + if (view != null) { view.addPropertyChangeListener(this); + } View oldView = this.view; this.view = view; @@ -164,133 +166,127 @@ public void setView(View view) this.firePropertyChange(AVKey.VIEW, oldView, view); } - public void setVerticalExaggeration(double verticalExaggeration) - { + public void setVerticalExaggeration(double verticalExaggeration) { Double oldVE = this.verticalExaggeration; this.verticalExaggeration = verticalExaggeration; this.firePropertyChange(AVKey.VERTICAL_EXAGGERATION, oldVE, verticalExaggeration); } - public double getVerticalExaggeration() - { + public double getVerticalExaggeration() { return this.verticalExaggeration; } - /** {@inheritDoc} */ - public void setPickPoint(Point pickPoint) - { + /** + * {@inheritDoc} + */ + public void setPickPoint(Point pickPoint) { this.pickPoint = pickPoint; } - /** {@inheritDoc} */ - public Point getPickPoint() - { + /** + * {@inheritDoc} + */ + public Point getPickPoint() { return this.pickPoint; } - /** {@inheritDoc} */ - public void setPickRectangle(Rectangle pickRect) - { + /** + * {@inheritDoc} + */ + public void setPickRectangle(Rectangle pickRect) { this.pickRect = pickRect; } - /** {@inheritDoc} */ - public Rectangle getPickRectangle() - { + /** + * {@inheritDoc} + */ + public Rectangle getPickRectangle() { return this.pickRect; } - /** {@inheritDoc} */ - public PickedObjectList getPickedObjectList() - { + /** + * {@inheritDoc} + */ + public PickedObjectList getPickedObjectList() { return this.lastPickedObjects; } - protected void setPickedObjectList(PickedObjectList pol) - { + protected void setPickedObjectList(PickedObjectList pol) { this.lastPickedObjects = pol; } - /** {@inheritDoc} */ - public PickedObjectList getObjectsInPickRectangle() - { + /** + * {@inheritDoc} + */ + public PickedObjectList getObjectsInPickRectangle() { return this.lastObjectsInPickRect; } - public void setDeepPickEnabled(boolean tf) - { + public void setDeepPickEnabled(boolean tf) { this.deepPick = tf; } - public boolean isDeepPickEnabled() - { + public boolean isDeepPickEnabled() { return this.deepPick; } - public SectorGeometryList getTerrain() - { + public SectorGeometryList getTerrain() { return this.dc.getSurfaceGeometry(); } - public DrawContext getDrawContext() - { + public DrawContext getDrawContext() { return this.dc; } - public double getFramesPerSecond() - { + public double getFramesPerSecond() { return this.framesPerSecond; } - public double getFrameTime() - { + public double getFrameTime() { return this.frameTime; } - public void setPerFrameStatisticsKeys(Set keys) - { + public void setPerFrameStatisticsKeys(Set keys) { this.perFrameStatisticsKeys.clear(); - if (keys == null) + if (keys == null) { return; + } - for (String key : keys) - { - if (key != null) + for (String key : keys) { + if (key != null) { this.perFrameStatisticsKeys.add(key); + } } } - public Collection getPerFrameStatistics() - { + public Collection getPerFrameStatistics() { return perFrameStatistics; } - public Collection getRenderingExceptions() - { + public Collection getRenderingExceptions() { return this.renderingExceptions; } - public ScreenCreditController getScreenCreditController() - { + public ScreenCreditController getScreenCreditController() { return screenCreditController; } - public void setScreenCreditController(ScreenCreditController screenCreditController) - { + public void setScreenCreditController(ScreenCreditController screenCreditController) { this.screenCreditController = screenCreditController; } - /** {@inheritDoc} */ - public GLRuntimeCapabilities getGLRuntimeCapabilities() - { + /** + * {@inheritDoc} + */ + public GLRuntimeCapabilities getGLRuntimeCapabilities() { return this.glRuntimeCaps; } - /** {@inheritDoc} */ - public void setGLRuntimeCapabilities(GLRuntimeCapabilities capabilities) - { - if (capabilities == null) - { + /** + * {@inheritDoc} + */ + public void setGLRuntimeCapabilities(GLRuntimeCapabilities capabilities) { + if (capabilities == null) { String message = Logging.getMessage("nullValue.GLRuntimeCapabilitiesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -300,14 +296,12 @@ public void setGLRuntimeCapabilities(GLRuntimeCapabilities capabilities) } @Override - public ClutterFilter getClutterFilter() - { + public ClutterFilter getClutterFilter() { return clutterFilter; } @Override - public void setClutterFilter(ClutterFilter clutterFilter) - { + public void setClutterFilter(ClutterFilter clutterFilter) { this.clutterFilter = clutterFilter; } // @@ -379,18 +373,15 @@ public void setClutterFilter(ClutterFilter clutterFilter) // } // } - public boolean isDeferOrderedRendering() - { + public boolean isDeferOrderedRendering() { return deferOrderedRendering; } - public void setDeferOrderedRendering(boolean deferOrderedRendering) - { + public void setDeferOrderedRendering(boolean deferOrderedRendering) { this.deferOrderedRendering = deferOrderedRendering; } - public int repaint() - { + public int repaint() { this.frameTime = System.currentTimeMillis(); this.perFrameStatistics.clear(); @@ -413,29 +404,28 @@ public int repaint() this.dc.setPerFrameStatistic(PerformanceStatistic.PICK_TIME, "Pick Time (ms)", (int) this.pickTime); Set perfKeys = dc.getPerFrameStatisticsKeys(); - if (perfKeys == null) + if (perfKeys == null) { return dc.getRedrawRequested(); + } - if (perfKeys.contains(PerformanceStatistic.MEMORY_CACHE) || perfKeys.contains(PerformanceStatistic.ALL)) - { + if (perfKeys.contains(PerformanceStatistic.MEMORY_CACHE) || perfKeys.contains(PerformanceStatistic.ALL)) { this.dc.setPerFrameStatistics(WorldWind.getMemoryCacheSet().getPerformanceStatistics()); } - if (perfKeys.contains(PerformanceStatistic.TEXTURE_CACHE) || perfKeys.contains(PerformanceStatistic.ALL)) - { - if (dc.getTextureCache() != null) + if (perfKeys.contains(PerformanceStatistic.TEXTURE_CACHE) || perfKeys.contains(PerformanceStatistic.ALL)) { + if (dc.getTextureCache() != null) { this.dc.setPerFrameStatistic(PerformanceStatistic.TEXTURE_CACHE, - "Texture Cache size (Kb)", this.dc.getTextureCache().getUsedCapacity() / 1000); + "Texture Cache size (Kb)", this.dc.getTextureCache().getUsedCapacity() / 1000); + } } - if (perfKeys.contains(PerformanceStatistic.JVM_HEAP) || perfKeys.contains(PerformanceStatistic.ALL)) - { + if (perfKeys.contains(PerformanceStatistic.JVM_HEAP) || perfKeys.contains(PerformanceStatistic.ALL)) { long totalMemory = Runtime.getRuntime().totalMemory(); this.dc.setPerFrameStatistic(PerformanceStatistic.JVM_HEAP, - "JVM total memory (Kb)", totalMemory / 1000); + "JVM total memory (Kb)", totalMemory / 1000); this.dc.setPerFrameStatistic(PerformanceStatistic.JVM_HEAP_USED, - "JVM used memory (Kb)", (totalMemory - Runtime.getRuntime().freeMemory()) / 1000); + "JVM used memory (Kb)", (totalMemory - Runtime.getRuntime().freeMemory()) / 1000); } return dc.getRedrawRequested(); @@ -443,8 +433,7 @@ public int repaint() abstract protected void doRepaint(DrawContext dc); - protected void initializeDrawContext(DrawContext dc) - { + protected void initializeDrawContext(DrawContext dc) { dc.initialize(GLContext.getCurrent()); dc.setGLRuntimeCapabilities(this.glRuntimeCaps); dc.setPerFrameStatisticsKeys(this.perFrameStatisticsKeys, this.perFrameStatistics); @@ -464,8 +453,7 @@ protected void initializeDrawContext(DrawContext dc) long frameTimeStamp = System.currentTimeMillis(); // Ensure that the frame time stamps differ between frames. This is necessary on machines with low-resolution // JVM clocks or that are so fast that they render under 1 millisecond. - if (frameTimeStamp == dc.getFrameTimeStamp()) - { + if (frameTimeStamp == dc.getFrameTimeStamp()) { ++frameTimeStamp; } dc.setFrameTimeStamp(frameTimeStamp); @@ -473,23 +461,22 @@ protected void initializeDrawContext(DrawContext dc) this.setValue(AVKey.FRAME_TIMESTAMP, frameTimeStamp); } - protected Point getViewportCenter(DrawContext dc) - { + protected Point getViewportCenter(DrawContext dc) { View view = dc.getView(); - if (view == null) + if (view == null) { return null; + } Rectangle viewport = view.getViewport(); - if (viewport == null) + if (viewport == null) { return null; + } return new Point((int) (viewport.getCenterX() + 0.5), (int) (viewport.getCenterY() + 0.5)); } - protected void initializeFrame(DrawContext dc) - { - if (dc.getGLContext() == null) - { + protected void initializeFrame(DrawContext dc) { + if (dc.getGLContext() == null) { String message = Logging.getMessage("BasicSceneController.GLContextNullStartRedisplay"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -510,15 +497,13 @@ protected void initializeFrame(DrawContext dc) gl.glEnable(GL.GL_DEPTH_TEST); } - protected void clearFrame(DrawContext dc) - { + protected void clearFrame(DrawContext dc) { Color cc = dc.getClearColor(); dc.getGL().glClearColor(cc.getRed(), cc.getGreen(), cc.getBlue(), cc.getAlpha()); dc.getGL().glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); } - protected void finalizeFrame(DrawContext dc) - { + protected void finalizeFrame(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glMatrixMode(GL2.GL_MODELVIEW); @@ -532,63 +517,51 @@ protected void finalizeFrame(DrawContext dc) // checkGLErrors(dc); } - protected void applyView(DrawContext dc) - { - if (dc.getView() != null) + protected void applyView(DrawContext dc) { + if (dc.getView() != null) { dc.getView().apply(dc); + } // // this.resetGroupingFilters(); } - protected void createPickFrustum(DrawContext dc) - { + protected void createPickFrustum(DrawContext dc) { dc.addPickPointFrustum(); dc.addPickRectangleFrustum(); } - protected void createTerrain(DrawContext dc) - { - if (dc.getSurfaceGeometry() == null) - { - if (dc.getModel() != null && dc.getModel().getGlobe() != null) - { + protected void createTerrain(DrawContext dc) { + if (dc.getSurfaceGeometry() == null) { + if (dc.getModel() != null && dc.getModel().getGlobe() != null) { SectorGeometryList sgl = dc.getModel().getGlobe().tessellate(dc); dc.setSurfaceGeometry(sgl); dc.setVisibleSector(sgl.getSector()); } - if (dc.getSurfaceGeometry() == null) - { + if (dc.getSurfaceGeometry() == null) { Logging.logger().warning("generic.NoSurfaceGeometry"); dc.setPerFrameStatistic(PerformanceStatistic.TERRAIN_TILE_COUNT, "Terrain Tiles", 0); // keep going because some layers, etc. may have meaning w/o surface geometry } dc.setPerFrameStatistic(PerformanceStatistic.TERRAIN_TILE_COUNT, "Terrain Tiles", - dc.getSurfaceGeometry().size()); + dc.getSurfaceGeometry().size()); } } - protected void preRender(DrawContext dc) - { - try - { + protected void preRender(DrawContext dc) { + try { dc.setPreRenderMode(true); // Pre-render the layers. - if (dc.getLayers() != null) - { - for (Layer layer : dc.getLayers()) - { - try - { + if (dc.getLayers() != null) { + for (Layer layer : dc.getLayers()) { + try { dc.setCurrentLayer(layer); layer.preRender(dc); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("SceneController.ExceptionWhilePreRenderingLayer", - (layer != null ? layer.getClass().getName() : Logging.getMessage("term.unknown"))); + (layer != null ? layer.getClass().getName() : Logging.getMessage("term.unknown"))); Logging.logger().log(Level.SEVERE, message, e); // Don't abort; continue on to the next layer. } @@ -599,68 +572,60 @@ protected void preRender(DrawContext dc) // Pre-render the deferred/ordered surface renderables. this.preRenderOrderedSurfaceRenderables(dc); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, Logging.getMessage("BasicSceneController.ExceptionDuringPreRendering"), - e); - } - finally - { + e); + } finally { dc.setPreRenderMode(false); } } - protected void pickTerrain(DrawContext dc) - { - if (dc.isPickingMode() && dc.getVisibleSector() != null && dc.getSurfaceGeometry() != null && - dc.getSurfaceGeometry().size() > 0) - { + protected void pickTerrain(DrawContext dc) { + if (dc.isPickingMode() && dc.getVisibleSector() != null && dc.getSurfaceGeometry() != null + && dc.getSurfaceGeometry().size() > 0) { this.pickPoints.clear(); - if (dc.getPickPoint() != null) + if (dc.getPickPoint() != null) { this.pickPoints.add(dc.getPickPoint()); + } Point vpc = dc.getViewportCenterScreenPoint(); - if (vpc != null && dc.getViewportCenterPosition() == null) + if (vpc != null && dc.getViewportCenterPosition() == null) { this.pickPoints.add(vpc); + } - if (this.pickPoints.size() == 0) + if (this.pickPoints.size() == 0) { return; + } List pickedObjects = dc.getSurfaceGeometry().pick(dc, this.pickPoints); - if (pickedObjects == null || pickedObjects.size() == 0) + if (pickedObjects == null || pickedObjects.size() == 0) { return; + } - for (PickedObject po : pickedObjects) - { - if (po == null) + for (PickedObject po : pickedObjects) { + if (po == null) { continue; - if (po.getPickPoint().equals(dc.getPickPoint())) + } + if (po.getPickPoint().equals(dc.getPickPoint())) { dc.addPickedObject(po); - else if (po.getPickPoint().equals(vpc)) + } else if (po.getPickPoint().equals(vpc)) { dc.setViewportCenterPosition((Position) po.getObject()); + } } } } - protected void pickLayers(DrawContext dc) - { - if (dc.getLayers() != null) - { - for (Layer layer : dc.getLayers()) - { - try - { - if (layer != null && layer.isPickEnabled()) - { + protected void pickLayers(DrawContext dc) { + if (dc.getLayers() != null) { + for (Layer layer : dc.getLayers()) { + try { + if (layer != null && layer.isPickEnabled()) { dc.setCurrentLayer(layer); layer.pick(dc, dc.getPickPoint()); } - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("SceneController.ExceptionWhilePickingInLayer", - (layer != null ? layer.getClass().getName() : Logging.getMessage("term.unknown"))); + (layer != null ? layer.getClass().getName() : Logging.getMessage("term.unknown"))); Logging.logger().log(Level.SEVERE, message, e); // Don't abort; continue on to the next layer. } @@ -670,36 +635,30 @@ protected void pickLayers(DrawContext dc) } } - protected void resolveTopPick(DrawContext dc) - { + protected void resolveTopPick(DrawContext dc) { // Resolve the top object at the pick point, if the pick point is enabled. - if (dc.getPickPoint() != null) + if (dc.getPickPoint() != null) { this.doResolveTopPick(dc, dc.getPickPoint()); + } // Resolve the top objects in the pick rectangle, if the pick rectangle is enabled. - if (dc.getPickRectangle() != null && !dc.getPickRectangle().isEmpty()) + if (dc.getPickRectangle() != null && !dc.getPickRectangle().isEmpty()) { this.doResolveTopPick(dc, dc.getPickRectangle()); + } } - protected void doResolveTopPick(DrawContext dc, Point pickPoint) - { + protected void doResolveTopPick(DrawContext dc, Point pickPoint) { PickedObjectList pol = dc.getPickedObjects(); - if (pol != null && pol.size() == 1) - { + if (pol != null && pol.size() == 1) { // If there is only one picked object, then it must be the top object so we're done. pol.get(0).setOnTop(); - } - else if (pol != null && pol.size() > 1) - { + } else if (pol != null && pol.size() > 1) { // If there is more than one picked object, then find the picked object corresponding to the top color at // the pick point, and mark it as on top int colorCode = dc.getPickColorAtPoint(pickPoint); - if (colorCode != 0) - { - for (PickedObject po : pol) - { - if (po != null && po.getColorCode() == colorCode) - { + if (colorCode != 0) { + for (PickedObject po : pol) { + if (po != null && po.getColorCode() == colorCode) { po.setOnTop(); break; // No need to check the remaining picked objects. } @@ -708,20 +667,15 @@ else if (pol != null && pol.size() > 1) } } - protected void doResolveTopPick(DrawContext dc, Rectangle pickRect) - { + protected void doResolveTopPick(DrawContext dc, Rectangle pickRect) { PickedObjectList pol = dc.getObjectsInPickRectangle(); - if (pol != null && pol.size() == 1) - { + if (pol != null && pol.size() == 1) { // If there is only one picked object, then it must be the top object so we're done. pol.get(0).setOnTop(); - } - else if (pol != null && pol.size() > 1) - { + } else if (pol != null && pol.size() > 1) { int[] minAndMaxColorCodes = null; - for (PickedObject po : pol) - { + for (PickedObject po : pol) { int colorCode = po.getColorCode(); // Put all of the eligible picked objects in a map to provide constant time access to a picked object @@ -734,30 +688,30 @@ else if (pol != null && pol.size() > 1) // Keep track of the minimum and maximum color codes of the scene's picked objects. These values are // used to cull the number of colors that the draw context must consider with identifying the unique // pick colors in the specified screen rectangle. - if (minAndMaxColorCodes == null) - minAndMaxColorCodes = new int[] {colorCode, colorCode}; - else - { - if (minAndMaxColorCodes[0] > colorCode) + if (minAndMaxColorCodes == null) { + minAndMaxColorCodes = new int[]{colorCode, colorCode}; + } else { + if (minAndMaxColorCodes[0] > colorCode) { minAndMaxColorCodes[0] = colorCode; - if (minAndMaxColorCodes[1] < colorCode) + } + if (minAndMaxColorCodes[1] < colorCode) { minAndMaxColorCodes[1] = colorCode; + } } } // If there is more than one picked object, then find the picked objects corresponding to each of the top // colors in the pick rectangle, and mark them all as on top. int[] colorCodes = dc.getPickColorsInRectangle(pickRect, minAndMaxColorCodes); - if (colorCodes != null && colorCodes.length > 0) - { + if (colorCodes != null && colorCodes.length > 0) { // Find the top picked object for each unique color code, if any, and mark it as on top. - for (int colorCode : colorCodes) - { + for (int colorCode : colorCodes) { if (colorCode != 0) // This should never happen, but we check anyway. { PickedObject po = this.pickableObjects.get(colorCode); - if (po != null) + if (po != null) { po.setOnTop(); + } } } } @@ -768,47 +722,41 @@ else if (pol != null && pol.size() > 1) } } - protected void pick(DrawContext dc) - { + protected void pick(DrawContext dc) { this.pickTime = System.currentTimeMillis(); this.lastPickedObjects = null; this.lastObjectsInPickRect = null; - try - { + try { dc.enablePickingMode(); this.pickTerrain(dc); this.doNonTerrainPick(dc); - if (this.isDeferOrderedRendering()) + if (this.isDeferOrderedRendering()) { return; + } this.resolveTopPick(dc); this.lastPickedObjects = new PickedObjectList(dc.getPickedObjects()); this.lastObjectsInPickRect = new PickedObjectList(dc.getObjectsInPickRectangle()); - if (this.isDeepPickEnabled() && - (this.lastPickedObjects.hasNonTerrainObjects() || this.lastObjectsInPickRect.hasNonTerrainObjects())) - { + if (this.isDeepPickEnabled() + && (this.lastPickedObjects.hasNonTerrainObjects() || this.lastObjectsInPickRect.hasNonTerrainObjects())) { this.doDeepPick(dc); } - } - catch (Throwable e) - { + } catch (Throwable e) { Logging.logger().log(Level.SEVERE, Logging.getMessage("BasicSceneController.ExceptionDuringPick"), e); - } - finally - { + } finally { dc.disablePickingMode(); this.pickTime = System.currentTimeMillis() - this.pickTime; } } - protected void doNonTerrainPick(DrawContext dc) - { + protected void doNonTerrainPick(DrawContext dc) { // Don't do the pick if there's no current pick point and no current pick rectangle. - if (dc.getPickPoint() == null && (dc.getPickRectangle() == null || dc.getPickRectangle().isEmpty())) + if (dc.getPickPoint() == null && (dc.getPickRectangle() == null || dc.getPickRectangle().isEmpty())) { return; + } // Pick against the layers. this.pickLayers(dc); @@ -816,26 +764,26 @@ protected void doNonTerrainPick(DrawContext dc) // Pick against the deferred/ordered surface renderables. this.pickOrderedSurfaceRenderables(dc); - if (this.isDeferOrderedRendering()) + if (this.isDeferOrderedRendering()) { return; + } // Pick against the screen credits. - if (this.screenCreditController != null) + if (this.screenCreditController != null) { this.screenCreditController.pick(dc, dc.getPickPoint()); + } // Pick against the deferred/ordered renderables. dc.setOrderedRenderingMode(true); // dc.applyGroupingFilters(); dc.applyClutterFilter(); - while (dc.peekOrderedRenderables() != null) - { + while (dc.peekOrderedRenderables() != null) { dc.pollOrderedRenderables().pick(dc, dc.getPickPoint()); } dc.setOrderedRenderingMode(false); } - protected void doDeepPick(DrawContext dc) - { + protected void doDeepPick(DrawContext dc) { PickedObjectList currentPickedObjects = this.lastPickedObjects; PickedObjectList currentObjectsInPickRect = this.lastObjectsInPickRect; @@ -845,60 +793,52 @@ protected void doDeepPick(DrawContext dc) this.lastPickedObjects = this.mergePickedObjectLists(currentPickedObjects, dc.getPickedObjects()); this.lastObjectsInPickRect = this.mergePickedObjectLists(currentObjectsInPickRect, - dc.getObjectsInPickRectangle()); + dc.getObjectsInPickRectangle()); } - protected PickedObjectList mergePickedObjectLists(PickedObjectList listA, PickedObjectList listB) - { - if (listA == null || listB == null || !listA.hasNonTerrainObjects() || !listB.hasNonTerrainObjects()) + protected PickedObjectList mergePickedObjectLists(PickedObjectList listA, PickedObjectList listB) { + if (listA == null || listB == null || !listA.hasNonTerrainObjects() || !listB.hasNonTerrainObjects()) { return listA; + } - for (PickedObject pb : listB) - { - if (pb.isTerrain()) + for (PickedObject pb : listB) { + if (pb.isTerrain()) { continue; + } boolean common = false; // cannot modify listA within its iterator, so use a flag to indicate commonality - for (PickedObject pa : listA) - { - if (pa.isTerrain()) + for (PickedObject pa : listA) { + if (pa.isTerrain()) { continue; + } - if (pa.getObject() == pb.getObject()) - { + if (pa.getObject() == pb.getObject()) { common = true; break; } } - if (!common) + if (!common) { listA.add(pb); + } } return listA; } - protected void draw(DrawContext dc) - { - try - { + protected void draw(DrawContext dc) { + try { // Draw the layers. - if (dc.getLayers() != null) - { - for (Layer layer : dc.getLayers()) - { - try - { - if (layer != null) - { + if (dc.getLayers() != null) { + for (Layer layer : dc.getLayers()) { + try { + if (layer != null) { dc.setCurrentLayer(layer); layer.render(dc); } - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("SceneController.ExceptionWhileRenderingLayer", - (layer != null ? layer.getClass().getName() : Logging.getMessage("term.unknown"))); + (layer != null ? layer.getClass().getName() : Logging.getMessage("term.unknown"))); Logging.logger().log(Level.SEVERE, message, e); // Don't abort; continue on to the next layer. } @@ -910,47 +850,43 @@ protected void draw(DrawContext dc) // Draw the deferred/ordered surface renderables. this.drawOrderedSurfaceRenderables(dc); - if (this.isDeferOrderedRendering()) + if (this.isDeferOrderedRendering()) { return; + } - if (this.screenCreditController != null) + if (this.screenCreditController != null) { this.screenCreditController.render(dc); + } // Draw the deferred/ordered renderables. dc.setOrderedRenderingMode(true); // dc.applyGroupingFilters(); dc.applyClutterFilter(); - while (dc.peekOrderedRenderables() != null) - { - try - { + while (dc.peekOrderedRenderables() != null) { + try { dc.pollOrderedRenderables().render(dc); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.WARNING, - Logging.getMessage("BasicSceneController.ExceptionDuringRendering"), e); + Logging.getMessage("BasicSceneController.ExceptionDuringRendering"), e); } } dc.setOrderedRenderingMode(false); // Draw the diagnostic displays. - if (dc.getSurfaceGeometry() != null && dc.getModel() != null && (dc.getModel().isShowWireframeExterior() || - dc.getModel().isShowWireframeInterior() || dc.getModel().isShowTessellationBoundingVolumes())) - { + if (dc.getSurfaceGeometry() != null && dc.getModel() != null && (dc.getModel().isShowWireframeExterior() + || dc.getModel().isShowWireframeInterior() || dc.getModel().isShowTessellationBoundingVolumes())) { Model model = dc.getModel(); float[] previousColor = new float[4]; GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glGetFloatv(GL2.GL_CURRENT_COLOR, previousColor, 0); - for (SectorGeometry sg : dc.getSurfaceGeometry()) - { - if (model.isShowWireframeInterior() || model.isShowWireframeExterior()) + for (SectorGeometry sg : dc.getSurfaceGeometry()) { + if (model.isShowWireframeInterior() || model.isShowWireframeExterior()) { sg.renderWireframe(dc, model.isShowWireframeInterior(), model.isShowWireframeExterior()); + } - if (model.isShowTessellationBoundingVolumes()) - { + if (model.isShowTessellationBoundingVolumes()) { gl.glColor3d(1, 0, 0); sg.renderBoundingVolume(dc); } @@ -958,9 +894,7 @@ protected void draw(DrawContext dc) gl.glColor4fv(previousColor, 0); } - } - catch (Throwable e) - { + } catch (Throwable e) { Logging.logger().log(Level.SEVERE, Logging.getMessage("BasicSceneController.ExceptionDuringRendering"), e); } } @@ -973,12 +907,10 @@ protected void draw(DrawContext dc) * @param dc the relevant DrawContext */ @SuppressWarnings({"UNUSED_SYMBOL", "UnusedDeclaration"}) - protected void checkGLErrors(DrawContext dc) - { + protected void checkGLErrors(DrawContext dc) { GL gl = dc.getGL(); - for (int err = gl.glGetError(); err != GL.GL_NO_ERROR; err = gl.glGetError()) - { + for (int err = gl.glGetError(); err != GL.GL_NO_ERROR; err = gl.glGetError()) { String msg = dc.getGLU().gluErrorString(err); msg += err; Logging.logger().severe(msg); @@ -988,11 +920,10 @@ protected void checkGLErrors(DrawContext dc) //**************************************************************// //******************** Ordered Surface Renderable ************// //**************************************************************// - - protected void preRenderOrderedSurfaceRenderables(DrawContext dc) - { - if (dc.getOrderedSurfaceRenderables().isEmpty()) + protected void preRenderOrderedSurfaceRenderables(DrawContext dc) { + if (dc.getOrderedSurfaceRenderables().isEmpty()) { return; + } dc.setOrderedRenderingMode(true); @@ -1002,45 +933,40 @@ protected void preRenderOrderedSurfaceRenderables(DrawContext dc) // PreRender the individual deferred/ordered surface renderables. int logCount = 0; - while (dc.getOrderedSurfaceRenderables().peek() != null) - { - try - { + while (dc.getOrderedSurfaceRenderables().peek() != null) { + try { OrderedRenderable or = dc.getOrderedSurfaceRenderables().poll(); - if (or instanceof PreRenderable) + if (or instanceof PreRenderable) { ((PreRenderable) or).preRender(dc); - } - catch (Exception e) - { + } + } catch (Exception e) { Logging.logger().log(Level.WARNING, - Logging.getMessage("BasicSceneController.ExceptionDuringPreRendering"), e); + Logging.getMessage("BasicSceneController.ExceptionDuringPreRendering"), e); // Limit how many times we log a problem. - if (++logCount > Logging.getMaxMessageRepeatCount()) + if (++logCount > Logging.getMaxMessageRepeatCount()) { break; + } } } dc.setOrderedRenderingMode(false); } - protected void pickOrderedSurfaceRenderables(DrawContext dc) - { + protected void pickOrderedSurfaceRenderables(DrawContext dc) { dc.setOrderedRenderingMode(true); // Pick the individual deferred/ordered surface renderables. We don't use the composite representation of // SurfaceObjects because we need to distinguish between individual objects. Therefore we let each object handle // drawing and resolving picking. - while (dc.getOrderedSurfaceRenderables().peek() != null) - { + while (dc.getOrderedSurfaceRenderables().peek() != null) { dc.getOrderedSurfaceRenderables().poll().pick(dc, dc.getPickPoint()); } dc.setOrderedRenderingMode(false); } - protected void drawOrderedSurfaceRenderables(DrawContext dc) - { + protected void drawOrderedSurfaceRenderables(DrawContext dc) { dc.setOrderedRenderingMode(true); // Draw the composite representation of the SurfaceObjects created during preRendering. @@ -1051,16 +977,12 @@ protected void drawOrderedSurfaceRenderables(DrawContext dc) // SurfaceObject.render during preRendering, SurfaceObjects should not add themselves to the ordered surface // renderable queue for rendering. We assume this queue is not populated with SurfaceObjects that participated // in the composite representation created during preRender. - while (dc.getOrderedSurfaceRenderables().peek() != null) - { - try - { + while (dc.getOrderedSurfaceRenderables().peek() != null) { + try { dc.getOrderedSurfaceRenderables().poll().render(dc); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.WARNING, - Logging.getMessage("BasicSceneController.ExceptionDuringRendering"), e); + Logging.getMessage("BasicSceneController.ExceptionDuringRendering"), e); } } @@ -1071,8 +993,7 @@ protected void drawOrderedSurfaceRenderables(DrawContext dc) * Builds a composite representation for all {@link gov.nasa.worldwind.render.SurfaceObject} instances in the draw * context's ordered surface renderable queue. While building the composite representation this invokes {@link * gov.nasa.worldwind.render.SurfaceObject#render(gov.nasa.worldwind.render.DrawContext)} in ordered rendering mode. - * This does nothing if the ordered surface renderable queue is empty, or if it does not contain any - * SurfaceObjects. + * This does nothing if the ordered surface renderable queue is empty, or if it does not contain any SurfaceObjects. *

* This method is called during the preRender phase, and is therefore free to modify the framebuffer contents to * create the composite representation. @@ -1081,10 +1002,8 @@ protected void drawOrderedSurfaceRenderables(DrawContext dc) * * @see gov.nasa.worldwind.render.DrawContext#getOrderedSurfaceRenderables() */ - protected void buildCompositeSurfaceObjects(DrawContext dc) - { - if (dc.getOrderedSurfaceRenderables().size() > 0) - { + protected void buildCompositeSurfaceObjects(DrawContext dc) { + if (dc.getOrderedSurfaceRenderables().size() > 0) { this.surfaceObjectTileBuilder.buildTiles(dc, dc.getOrderedSurfaceRenderables()); } } @@ -1097,21 +1016,20 @@ protected void buildCompositeSurfaceObjects(DrawContext dc) * * @param dc The drawing context containing the surface objects who's composite representation is drawn. */ - protected void drawCompositeSurfaceObjects(DrawContext dc) - { + protected void drawCompositeSurfaceObjects(DrawContext dc) { int tileCount = this.surfaceObjectTileBuilder.getTileCount(dc); - if (tileCount == 0) + if (tileCount == 0) { return; + } - int attributeMask = - GL2.GL_COLOR_BUFFER_BIT // For alpha test enable, blend enable, alpha func, blend func, blend ref. + int attributeMask + = GL2.GL_COLOR_BUFFER_BIT // For alpha test enable, blend enable, alpha func, blend func, blend ref. | GL2.GL_POLYGON_BIT; // For cull face enable, cull face, polygon mode. GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushAttrib(gl, attributeMask); - try - { + try { gl.glEnable(GL.GL_BLEND); gl.glEnable(GL.GL_CULL_FACE); gl.glCullFace(GL.GL_BACK); @@ -1120,9 +1038,7 @@ protected void drawCompositeSurfaceObjects(DrawContext dc) dc.getGeographicSurfaceTileRenderer().renderTiles(dc, this.surfaceObjectTileBuilder.getTiles(dc)); dc.setPerFrameStatistic(PerformanceStatistic.IMAGE_TILE_COUNT, SURFACE_OBJECT_TILE_COUNT_NAME, tileCount); - } - finally - { + } finally { ogsh.pop(gl); this.surfaceObjectTileBuilder.clearTiles(dc); } diff --git a/src/gov/nasa/worldwind/BasicFactory.java b/src/gov/nasa/worldwind/BasicFactory.java index 6238b1b43f..b6ce1b3486 100644 --- a/src/gov/nasa/worldwind/BasicFactory.java +++ b/src/gov/nasa/worldwind/BasicFactory.java @@ -22,30 +22,27 @@ * @author tag * @version $Id: BasicFactory.java 2072 2014-06-21 21:20:25Z tgaskins $ */ -public class BasicFactory implements Factory -{ +public class BasicFactory implements Factory { + /** * Static method to create an object from a factory and configuration source. * - * @param factoryKey the key identifying the factory in {@link Configuration}. + * @param factoryKey the key identifying the factory in {@link Configuration}. * @param configSource the configuration source. May be any of the types listed for {@link * #createFromConfigSource(Object, gov.nasa.worldwind.avlist.AVList)} * * @return a new instance of the requested object. * * @throws IllegalArgumentException if the factory key is null, or if the configuration source is null or an empty - * string. + * string. */ - public static Object create(String factoryKey, Object configSource) - { - if (factoryKey == null) - { + public static Object create(String factoryKey, Object configSource) { + if (factoryKey == null) { String message = Logging.getMessage("generic.FactoryKeyIsNull"); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(configSource)) - { + if (WWUtil.isEmpty(configSource)) { String message = Logging.getMessage("generic.ConfigurationSourceIsInvalid", configSource); throw new IllegalArgumentException(message); } @@ -58,27 +55,24 @@ public static Object create(String factoryKey, Object configSource) * Static method to create an object from a factory, a configuration source, and an optional configuration parameter * list. * - * @param factoryKey the key identifying the factory in {@link Configuration}. + * @param factoryKey the key identifying the factory in {@link Configuration}. * @param configSource the configuration source. May be any of the types listed for {@link * #createFromConfigSource(Object, gov.nasa.worldwind.avlist.AVList)} - * @param params key-value parameters to override or supplement the information provided in the specified - * configuration source. May be null. + * @param params key-value parameters to override or supplement the information provided in the specified + * configuration source. May be null. * * @return a new instance of the requested object. * * @throws IllegalArgumentException if the factory key is null, or if the configuration source is null or an empty - * string. + * string. */ - public static Object create(String factoryKey, Object configSource, AVList params) - { - if (factoryKey == null) - { + public static Object create(String factoryKey, Object configSource, AVList params) { + if (factoryKey == null) { String message = Logging.getMessage("generic.FactoryKeyIsNull"); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(configSource)) - { + if (WWUtil.isEmpty(configSource)) { String message = Logging.getMessage("generic.ConfigurationSourceIsInvalid", configSource); throw new IllegalArgumentException(message); } @@ -97,20 +91,18 @@ public static Object create(String factoryKey, Object configSource, AVList param *

* * @param configSource the configuration source. See above for supported types. - * @param params key-value parameters to override or supplement the information provided in the specified - * configuration source. May be null. + * @param params key-value parameters to override or supplement the information provided in the specified + * configuration source. May be null. * * @return the new object. * * @throws IllegalArgumentException if the configuration source is null or an empty string. - * @throws WWUnrecognizedException if the source type is unrecognized. - * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is - * included as the {@link Exception#initCause(Throwable)}. + * @throws WWUnrecognizedException if the source type is unrecognized. + * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is + * included as the {@link Exception#initCause(Throwable)}. */ - public Object createFromConfigSource(Object configSource, AVList params) - { - if (WWUtil.isEmpty(configSource)) - { + public Object createFromConfigSource(Object configSource, AVList params) { + if (WWUtil.isEmpty(configSource)) { String message = Logging.getMessage("generic.ConfigurationSourceIsInvalid", configSource); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -118,25 +110,20 @@ public Object createFromConfigSource(Object configSource, AVList params) Object o = null; - try - { - if (configSource instanceof Element) - { + try { + if (configSource instanceof Element) { o = this.doCreateFromElement((Element) configSource, params); - } - else if (configSource instanceof OGCCapabilities) + } else if (configSource instanceof OGCCapabilities) { o = this.doCreateFromCapabilities((OGCCapabilities) configSource, params); - else if (configSource instanceof WCS100Capabilities) + } else if (configSource instanceof WCS100Capabilities) { o = this.doCreateFromCapabilities((WCS100Capabilities) configSource, params); - else - { + } else { Document doc = WWXML.openDocument(configSource); - if (doc != null) + if (doc != null) { o = this.doCreateFromElement(doc.getDocumentElement(), params); + } } - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.CreationFromConfigurationFileFailed", configSource); throw new WWRuntimeException(msg, e); } @@ -149,26 +136,22 @@ else if (configSource instanceof WCS100Capabilities) * layer descriptions. * * @param capsFileName the path to the capabilities file. The file must be either an absolute path or a relative - * path available on the classpath. The file contents must be a valid OGC capabilities - * document. - * @param params a list of configuration properties. These properties override any specified in the - * capabilities document. The list should contain the {@link AVKey#LAYER_NAMES} property for - * services that define layer, indicating which named layers described in the capabilities - * document to create. If this argumet is null or contains no layers, the first named layer is - * used. + * path available on the classpath. The file contents must be a valid OGC capabilities document. + * @param params a list of configuration properties. These properties override any specified in the capabilities + * document. The list should contain the {@link AVKey#LAYER_NAMES} property for services that define layer, + * indicating which named layers described in the capabilities document to create. If this argumet is null or + * contains no layers, the first named layer is used. * * @return the requested object. * * @throws IllegalArgumentException if the file name is null or empty. - * @throws IllegalStateException if the capabilites document contains no named layer definitions. - * @throws WWRuntimeException if an error occurs while opening, reading or parsing the capabilities document. - * The exception indicating the source of the failure is included as the {@link + * @throws IllegalStateException if the capabilites document contains no named layer definitions. + * @throws WWRuntimeException if an error occurs while opening, reading or parsing the capabilities document. The + * exception indicating the source of the failure is included as the {@link * Exception#initCause(Throwable)}. */ - public Object createFromCapabilities(String capsFileName, AVList params) - { - if (WWUtil.isEmpty(capsFileName)) - { + public Object createFromCapabilities(String capsFileName, AVList params) { + if (WWUtil.isEmpty(capsFileName)) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -176,12 +159,9 @@ public Object createFromCapabilities(String capsFileName, AVList params) WMSCapabilities caps = new WMSCapabilities(capsFileName); - try - { + try { caps.parse(); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { String message = Logging.getMessage("generic.CannotParseCapabilities", capsFileName); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); @@ -191,39 +171,34 @@ public Object createFromCapabilities(String capsFileName, AVList params) } /** - * Implemented by subclasses to perform the actual object creation. This default implementation always returns - * null. + * Implemented by subclasses to perform the actual object creation. This default implementation always returns null. * - * @param caps the capabilities document. + * @param caps the capabilities document. * @param params a list of configuration properties. These properties override any specified in the capabilities - * document. The list should contain the {@link AVKey#LAYER_NAMES} property for services that define - * layers, indicating which named layers described in the capabilities document to create. If this - * argumet is null or contains no layers, the first named layer is used. + * document. The list should contain the {@link AVKey#LAYER_NAMES} property for services that define layers, + * indicating which named layers described in the capabilities document to create. If this argumet is null or + * contains no layers, the first named layer is used. * * @return the requested object. */ - protected Object doCreateFromCapabilities(OGCCapabilities caps, AVList params) - { + protected Object doCreateFromCapabilities(OGCCapabilities caps, AVList params) { return null; } /** - * Implemented by subclasses to perform the actual object creation. This default implementation always returns - * null. + * Implemented by subclasses to perform the actual object creation. This default implementation always returns null. * - * @param caps the capabilities document. + * @param caps the capabilities document. * @param params a list of configuration properties. These properties override any specified in the capabilities - * document. + * document. * * @return the requested object. */ - protected Object doCreateFromCapabilities(WCS100Capabilities caps, AVList params) - { + protected Object doCreateFromCapabilities(WCS100Capabilities caps, AVList params) { return null; } - protected Object doCreateFromElement(Element domElement, AVList params) throws Exception - { + protected Object doCreateFromElement(Element domElement, AVList params) throws Exception { return null; } } diff --git a/src/gov/nasa/worldwind/BasicModel.java b/src/gov/nasa/worldwind/BasicModel.java index e7d4b74851..4251302a3e 100644 --- a/src/gov/nasa/worldwind/BasicModel.java +++ b/src/gov/nasa/worldwind/BasicModel.java @@ -23,19 +23,19 @@ * @author Tom Gaskins * @version $Id: BasicModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicModel extends WWObjectImpl implements Model -{ +public class BasicModel extends WWObjectImpl implements Model { + private Globe globe; private LayerList layers; private boolean showWireframeInterior = false; private boolean showWireframeExterior = false; private boolean showTessellationBoundingVolumes = false; - public BasicModel() - { + public BasicModel() { String globeName = Configuration.getStringValue(AVKey.GLOBE_CLASS_NAME); - if (globeName == null) + if (globeName == null) { return; + } this.setGlobe((Globe) WorldWind.createComponent(globeName)); @@ -43,25 +43,22 @@ public BasicModel() // configuration. LayerList layers = null; String layerNames = Configuration.getStringValue(AVKey.LAYERS_CLASS_NAMES); - if (layerNames != null) - { + if (layerNames != null) { // Usage of this deprecated method is intentional. It provides backwards compatibility for deprecated // functionality. //noinspection deprecation layers = this.createLayersFromProperties(layerNames); - } - else - { + } else { Element el = Configuration.getElement("./LayerList"); - if (el != null) + if (el != null) { layers = this.createLayersFromElement(el); + } } this.setLayers(layers != null ? layers : new LayerList(/*empty list*/)); // an empty list is ok } - public BasicModel(Globe globe, LayerList layers) - { + public BasicModel(Globe globe, LayerList layers) { this.setGlobe(globe); this.setLayers(layers != null ? layers : new LayerList(/*empty list*/)); // an empty list is ok } @@ -73,21 +70,22 @@ public BasicModel(Globe globe, LayerList layers) * * @return a new layer list matching the specified description. */ - protected LayerList createLayersFromElement(Element element) - { + protected LayerList createLayersFromElement(Element element) { Object o = BasicFactory.create(AVKey.LAYER_FACTORY, element); - if (o instanceof LayerList) + if (o instanceof LayerList) { return (LayerList) o; + } - if (o instanceof Layer) - return new LayerList(new Layer[] {(Layer) o}); + if (o instanceof Layer) { + return new LayerList(new Layer[]{(Layer) o}); + } - if (o instanceof LayerList[]) - { + if (o instanceof LayerList[]) { LayerList[] lists = (LayerList[]) o; - if (lists.length > 0) + if (lists.length > 0) { return LayerList.collapseLists((LayerList[]) o); + } } return null; @@ -103,25 +101,20 @@ protected LayerList createLayersFromElement(Element element) * @deprecated Use {@link #createLayersFromElement(org.w3c.dom.Element)} instead. */ @Deprecated - protected LayerList createLayersFromProperties(String layerNames) - { + protected LayerList createLayersFromProperties(String layerNames) { LayerList layers = new LayerList(); - if (layerNames == null) + if (layerNames == null) { return null; + } String[] names = layerNames.split(","); - for (String name : names) - { - try - { - if (name.length() > 0) - { + for (String name : names) { + try { + if (name.length() > 0) { Layer l = (Layer) WorldWind.createComponent(name); layers.add(l); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.WARNING, Logging.getMessage("BasicModel.LayerNotFound", name), e); } } @@ -132,112 +125,123 @@ protected LayerList createLayersFromProperties(String layerNames) /** * Specifies the model's globe. * - * @param globe the model's new globe. May be null, in which case the current globe will be detached from the - * model. + * @param globe the model's new globe. May be null, in which case the current globe will be detached from the model. */ - public void setGlobe(Globe globe) - { + public void setGlobe(Globe globe) { // don't raise an exception if globe == null. In that case, we are disassociating the model from any globe //remove property change listener "this" from the current globe. - if (this.globe != null) + if (this.globe != null) { this.globe.removePropertyChangeListener(this); + } // if the new globe is not null, add "this" as a property change listener. - if (globe != null) + if (globe != null) { globe.addPropertyChangeListener(this); + } Globe old = this.globe; this.globe = globe; this.firePropertyChange(AVKey.GLOBE, old, this.globe); } - /** {@inheritDoc} */ - public void setLayers(LayerList layers) - { + /** + * {@inheritDoc} + */ + public void setLayers(LayerList layers) { // don't raise an exception if layers == null. In that case, we are disassociating the model from any layer set - if (this.layers != null) + if (this.layers != null) { this.layers.removePropertyChangeListener(this); - if (layers != null) + } + if (layers != null) { layers.addPropertyChangeListener(this); + } LayerList old = this.layers; this.layers = layers; this.firePropertyChange(AVKey.LAYERS, old, this.layers); } - /** {@inheritDoc} */ - public Globe getGlobe() - { + /** + * {@inheritDoc} + */ + public Globe getGlobe() { return this.globe; } - /** {@inheritDoc} */ - public LayerList getLayers() - { + /** + * {@inheritDoc} + */ + public LayerList getLayers() { return this.layers; } - /** {@inheritDoc} */ - public void setShowWireframeInterior(boolean show) - { + /** + * {@inheritDoc} + */ + public void setShowWireframeInterior(boolean show) { this.showWireframeInterior = show; } - /** {@inheritDoc} */ - public void setShowWireframeExterior(boolean show) - { + /** + * {@inheritDoc} + */ + public void setShowWireframeExterior(boolean show) { this.showWireframeExterior = show; } - /** {@inheritDoc} */ - public boolean isShowWireframeInterior() - { + /** + * {@inheritDoc} + */ + public boolean isShowWireframeInterior() { return this.showWireframeInterior; } - /** {@inheritDoc} */ - public boolean isShowWireframeExterior() - { + /** + * {@inheritDoc} + */ + public boolean isShowWireframeExterior() { return this.showWireframeExterior; } - /** {@inheritDoc} */ - public boolean isShowTessellationBoundingVolumes() - { + /** + * {@inheritDoc} + */ + public boolean isShowTessellationBoundingVolumes() { return showTessellationBoundingVolumes; } - /** {@inheritDoc} */ - public void setShowTessellationBoundingVolumes(boolean showTessellationBoundingVolumes) - { + /** + * {@inheritDoc} + */ + public void setShowTessellationBoundingVolumes(boolean showTessellationBoundingVolumes) { this.showTessellationBoundingVolumes = showTessellationBoundingVolumes; } - /** {@inheritDoc} */ - public Extent getExtent() - { + /** + * {@inheritDoc} + */ + public Extent getExtent() { // See if the layers have it. LayerList layers = BasicModel.this.getLayers(); - if (layers != null) - { - for (Object layer1 : layers) - { + if (layers != null) { + for (Object layer1 : layers) { Layer layer = (Layer) layer1; Extent e = (Extent) layer.getValue(AVKey.EXTENT); - if (e != null) + if (e != null) { return e; + } } } // See if the Globe has it. Globe globe = this.getGlobe(); - if (globe != null) - { + if (globe != null) { Extent e = globe.getExtent(); - if (e != null) + if (e != null) { return e; + } } return null; @@ -251,21 +255,14 @@ public Extent getExtent() * @param msg The message that was received. */ @Override - public void onMessage(Message msg) - { - if (this.getLayers() != null) - { - for (Layer layer : this.getLayers()) - { - try - { - if (layer != null) - { + public void onMessage(Message msg) { + if (this.getLayers() != null) { + for (Layer layer : this.getLayers()) { + try { + if (layer != null) { layer.onMessage(msg); } - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionInvokingMessageListener"); Logging.logger().log(Level.SEVERE, message, e); // Don't abort; continue on to the next layer. @@ -273,4 +270,4 @@ public void onMessage(Message msg) } } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/BasicSceneController.java b/src/gov/nasa/worldwind/BasicSceneController.java index fffeeb960a..af91f47182 100644 --- a/src/gov/nasa/worldwind/BasicSceneController.java +++ b/src/gov/nasa/worldwind/BasicSceneController.java @@ -14,29 +14,25 @@ * @author Tom Gaskins * @version $Id: BasicSceneController.java 2249 2014-08-21 20:13:30Z dcollins $ */ -public class BasicSceneController extends AbstractSceneController -{ +public class BasicSceneController extends AbstractSceneController { + SectorGeometryList sglC, sglL, sglR; Sector visibleSectorC, visibleSectorL, visibleSectorR; - public void doRepaint(DrawContext dc) - { + public void doRepaint(DrawContext dc) { this.initializeFrame(dc); - try - { - if (dc.getGlobe() instanceof Globe2D && ((Globe2D)dc.getGlobe()).isContinuous()) + try { + if (dc.getGlobe() instanceof Globe2D && ((Globe2D) dc.getGlobe()).isContinuous()) { this.do2DContiguousRepaint(dc); - else + } else { this.doNormalRepaint(dc); - } - finally - { + } + } finally { this.finalizeFrame(dc); } } - protected void doNormalRepaint(DrawContext dc) - { + protected void doNormalRepaint(DrawContext dc) { this.applyView(dc); this.createPickFrustum(dc); this.createTerrain(dc); @@ -47,8 +43,7 @@ protected void doNormalRepaint(DrawContext dc) this.draw(dc); } - protected void do2DContiguousRepaint(DrawContext dc) - { + protected void do2DContiguousRepaint(DrawContext dc) { ((Globe2D) dc.getGlobe()).setOffset(0); this.applyView(dc); @@ -61,12 +56,10 @@ protected void do2DContiguousRepaint(DrawContext dc) this.draw2DContiguous(dc); } - protected void makeCurrent(DrawContext dc, int offset) - { + protected void makeCurrent(DrawContext dc, int offset) { ((Globe2D) dc.getGlobe()).setOffset(offset); - switch (offset) - { + switch (offset) { case -1: dc.setSurfaceGeometry(this.sglL); dc.setVisibleSector(this.visibleSectorL); @@ -82,13 +75,11 @@ protected void makeCurrent(DrawContext dc, int offset) } } - protected void createTerrain2DContinuous(DrawContext dc) - { + protected void createTerrain2DContinuous(DrawContext dc) { this.sglC = null; this.visibleSectorC = null; ((Globe2D) dc.getGlobe()).setOffset(0); - if (dc.getGlobe().intersects(dc.getView().getFrustumInModelCoordinates())) - { + if (dc.getGlobe().intersects(dc.getView().getFrustumInModelCoordinates())) { this.sglC = dc.getModel().getGlobe().tessellate(dc); this.visibleSectorC = this.sglC.getSector(); } @@ -96,8 +87,7 @@ protected void createTerrain2DContinuous(DrawContext dc) this.sglR = null; this.visibleSectorR = null; ((Globe2D) dc.getGlobe()).setOffset(1); - if (dc.getGlobe().intersects(dc.getView().getFrustumInModelCoordinates())) - { + if (dc.getGlobe().intersects(dc.getView().getFrustumInModelCoordinates())) { this.sglR = dc.getModel().getGlobe().tessellate(dc); this.visibleSectorR = this.sglR.getSector(); } @@ -105,26 +95,22 @@ protected void createTerrain2DContinuous(DrawContext dc) this.sglL = null; this.visibleSectorL = null; ((Globe2D) dc.getGlobe()).setOffset(-1); - if (dc.getGlobe().intersects(dc.getView().getFrustumInModelCoordinates())) - { + if (dc.getGlobe().intersects(dc.getView().getFrustumInModelCoordinates())) { this.sglL = dc.getModel().getGlobe().tessellate(dc); this.visibleSectorL = this.sglL.getSector(); } } - protected void draw2DContiguous(DrawContext dc) - { + protected void draw2DContiguous(DrawContext dc) { String drawing = ""; - if (this.sglC != null) - { + if (this.sglC != null) { drawing += " 0 "; this.makeCurrent(dc, 0); this.setDeferOrderedRendering(this.sglL != null || this.sglR != null); this.draw(dc); } - if (this.sglR != null) - { + if (this.sglR != null) { drawing += " 1 "; this.makeCurrent(dc, 1); this.setDeferOrderedRendering(this.sglL != null); @@ -133,8 +119,7 @@ protected void draw2DContiguous(DrawContext dc) this.setDeferOrderedRendering(false); - if (this.sglL != null) - { + if (this.sglL != null) { drawing += " -1 "; this.makeCurrent(dc, -1); this.draw(dc); @@ -142,38 +127,31 @@ protected void draw2DContiguous(DrawContext dc) // System.out.println("DRAWING " + drawing); } - protected void preRender2DContiguous(DrawContext dc) - { - if (this.sglC != null) - { + protected void preRender2DContiguous(DrawContext dc) { + if (this.sglC != null) { this.makeCurrent(dc, 0); this.preRender(dc); } - if (this.sglR != null) - { + if (this.sglR != null) { this.makeCurrent(dc, 1); this.preRender(dc); } - if (this.sglL != null) - { + if (this.sglL != null) { this.makeCurrent(dc, -1); this.preRender(dc); } } - protected void pick2DContiguous(DrawContext dc) - { - if (this.sglC != null) - { + protected void pick2DContiguous(DrawContext dc) { + if (this.sglC != null) { this.makeCurrent(dc, 0); this.setDeferOrderedRendering(this.sglL != null || this.sglR != null); this.pick(dc); } - if (this.sglR != null) - { + if (this.sglR != null) { this.makeCurrent(dc, 1); this.setDeferOrderedRendering(this.sglL != null); this.pick(dc); @@ -181,8 +159,7 @@ protected void pick2DContiguous(DrawContext dc) this.setDeferOrderedRendering(false); - if (this.sglL != null) - { + if (this.sglL != null) { this.makeCurrent(dc, -1); this.pick(dc); } diff --git a/src/gov/nasa/worldwind/Configuration.java b/src/gov/nasa/worldwind/Configuration.java index e82441f120..cd16465f51 100644 --- a/src/gov/nasa/worldwind/Configuration.java +++ b/src/gov/nasa/worldwind/Configuration.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.avlist.AVKey; @@ -30,15 +29,15 @@ * registers all the information there. The information can subsequently be retrieved via the class' various * getValue methods. Many WorldWind start-up objects query this information to determine the classes to * create. For example, the first WorldWind object created by an application is typically a {@link - * gov.nasa.worldwind.awt.WorldWindowGLCanvas}. During construction that class causes WorldWind's internal classes to - * be constructed, using the names of those classes drawn from the Configuration singleton, this class. + * gov.nasa.worldwind.awt.WorldWindowGLCanvas}. During construction that class causes WorldWind's internal classes to be + * constructed, using the names of those classes drawn from the Configuration singleton, this class. *

- * The default WorldWind configuration document is config/worldwind.xml. This can be changed by setting - * the Java property gov.nasa.worldwind.config.file to a different file name or a valid URL prior to - * creating any WorldWind object or invoking any static methods of WorldWind classes, including the Configuration - * class. When an application specifies a different configuration location it typically does so in its main method prior - * to using WorldWind. If a file is specified its location must be on the classpath. (The contents of application and - * WorldWind jar files are typically on the classpath, in which case the configuration file may be in the jar file.) + * The default WorldWind configuration document is config/worldwind.xml. This can be changed by setting the + * Java property gov.nasa.worldwind.config.file to a different file name or a valid URL prior to creating + * any WorldWind object or invoking any static methods of WorldWind classes, including the Configuration class. When an + * application specifies a different configuration location it typically does so in its main method prior to using + * WorldWind. If a file is specified its location must be on the classpath. (The contents of application and WorldWind + * jar files are typically on the classpath, in which case the configuration file may be in the jar file.) *

* Additionally, an application may set another Java property, gov.nasa.worldwind.app.config.document, to a * file name or URL whose contents contain configuration values to override those of the primary configuration document. @@ -63,6 +62,7 @@ */ public class Configuration // Singleton { + public static final String DEFAULT_LOGGER_NAME = "gov.nasa.worldwind"; private static final String CONFIG_PROPERTIES_FILE_NAME = "config/worldwind.properties"; @@ -75,48 +75,42 @@ public class Configuration // Singleton private static Configuration ourInstance = new Configuration(); - private static Configuration getInstance() - { + private static Configuration getInstance() { return ourInstance; } private final Properties properties; private final ArrayList configDocs = new ArrayList(); - /** Private constructor invoked only internally. */ - private Configuration() - { + /** + * Private constructor invoked only internally. + */ + private Configuration() { this.properties = initializeDefaults(); // Load the app's configuration if there is one - try - { + try { String appConfigLocation = System.getProperty(CONFIG_APP_DOCUMENT_KEY); - if (appConfigLocation != null) + if (appConfigLocation != null) { this.loadConfigDoc(System.getProperty(CONFIG_APP_DOCUMENT_KEY)); // Load app's config first - } - catch (Exception e) - { + } + } catch (Exception e) { Logging.logger(DEFAULT_LOGGER_NAME).log(Level.WARNING, "Configuration.ConfigNotFound", - System.getProperty(CONFIG_APP_DOCUMENT_KEY)); + System.getProperty(CONFIG_APP_DOCUMENT_KEY)); // Don't stop if the app config file can't be found or parsed } - try - { + try { // Load the default configuration this.loadConfigDoc(System.getProperty(CONFIG_WW_DOCUMENT_KEY, CONFIG_WW_DOCUMENT_NAME)); // Load config properties, ensuring that the app's config takes precedence over wwj's - for (int i = this.configDocs.size() - 1; i >= 0; i--) - { + for (int i = this.configDocs.size() - 1; i >= 0; i--) { this.loadConfigProperties(this.configDocs.get(i)); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger(DEFAULT_LOGGER_NAME).log(Level.WARNING, "Configuration.ConfigNotFound", - System.getProperty(CONFIG_WW_DOCUMENT_KEY)); + System.getProperty(CONFIG_WW_DOCUMENT_KEY)); } // To support old-style configuration, read an existing config properties file and give the properties @@ -124,124 +118,106 @@ private Configuration() this.initializeCustom(); } - private void loadConfigDoc(String configLocation) - { - if (!WWUtil.isEmpty(configLocation)) - { + private void loadConfigDoc(String configLocation) { + if (!WWUtil.isEmpty(configLocation)) { Document doc = WWXML.openDocument(configLocation); - if (doc != null) - { + if (doc != null) { this.configDocs.add(doc); // this.loadConfigProperties(doc); } } } - private void insertConfigDoc(String configLocation) - { - if (!WWUtil.isEmpty(configLocation)) - { + private void insertConfigDoc(String configLocation) { + if (!WWUtil.isEmpty(configLocation)) { Document doc = WWXML.openDocument(configLocation); - if (doc != null) - { + if (doc != null) { this.configDocs.add(0, doc); this.loadConfigProperties(doc); } } } - private void loadConfigProperties(Document doc) - { - try - { + private void loadConfigProperties(Document doc) { + try { XPath xpath = WWXML.makeXPath(); NodeList nodes = (NodeList) xpath.evaluate("/WorldWindConfiguration/Property", doc, XPathConstants.NODESET); - if (nodes == null || nodes.getLength() == 0) + if (nodes == null || nodes.getLength() == 0) { return; + } - for (int i = 0; i < nodes.getLength(); i++) - { + for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String prop = xpath.evaluate("@name", node); String value = xpath.evaluate("@value", node); if (WWUtil.isEmpty(prop))// || WWUtil.isEmpty(value)) + { continue; + } this.properties.setProperty(prop, value); } - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { Logging.logger(DEFAULT_LOGGER_NAME).log(Level.WARNING, "XML.ParserConfigurationException"); } } - private Properties initializeDefaults() - { + private Properties initializeDefaults() { Properties defaults = new Properties(); java.util.TimeZone tz = java.util.Calendar.getInstance().getTimeZone(); - if (tz != null) + if (tz != null) { defaults.setProperty(AVKey.INITIAL_LONGITUDE, - Double.toString( - Angle.fromDegrees(180.0 * tz.getOffset(System.currentTimeMillis()) / (12.0 * 3.6e6)).degrees)); + Double.toString( + Angle.fromDegrees(180.0 * tz.getOffset(System.currentTimeMillis()) / (12.0 * 3.6e6)).degrees)); + } return defaults; } - private void initializeCustom() - { + private void initializeCustom() { // IMPORTANT NOTE: Always use the single argument version of Logging.logger in this method because the non-arg // method assumes an instance of Configuration already exists. String configFileName = System.getProperty(CONFIG_FILE_PROPERTY_KEY, CONFIG_PROPERTIES_FILE_NAME); - try - { + try { java.io.InputStream propsStream = null; File file = new File(configFileName); - if (file.exists()) - { - try - { + if (file.exists()) { + try { propsStream = new FileInputStream(file); - } - catch (FileNotFoundException e) - { + } catch (FileNotFoundException e) { Logging.logger(DEFAULT_LOGGER_NAME).log(Level.FINEST, "Configuration.LocalConfigFileNotFound", - configFileName); + configFileName); } } - if (propsStream == null) - { + if (propsStream == null) { propsStream = this.getClass().getResourceAsStream("/" + configFileName); } - if (propsStream != null) + if (propsStream != null) { this.properties.load(propsStream); - } - // Use a named logger in all the catch statements below to prevent Logger from calling back into + } + } // Use a named logger in all the catch statements below to prevent Logger from calling back into // Configuration when this Configuration instance is not yet fully instantiated. - catch (IOException e) - { + catch (IOException e) { Logging.logger(DEFAULT_LOGGER_NAME).log(Level.SEVERE, "Configuration.ExceptionReadingPropsFile", e); } } - public static void insertConfigurationDocument(String fileName) - { + public static void insertConfigurationDocument(String fileName) { getInstance().insertConfigDoc(fileName); } /** * Return as a string the value associated with a specified key. * - * @param key the key for the desired value. + * @param key the key for the desired value. * @param defaultValue the value to return if the key does not exist. * * @return the value associated with the key, or the specified default value if the key does not exist. */ - public static synchronized String getStringValue(String key, String defaultValue) - { + public static synchronized String getStringValue(String key, String defaultValue) { String v = getStringValue(key); return v != null ? v : defaultValue; } @@ -253,8 +229,7 @@ public static synchronized String getStringValue(String key, String defaultValue * * @return the value associated with the key, or null if the key does not exist. */ - public static synchronized String getStringValue(String key) - { + public static synchronized String getStringValue(String key) { Object o = getInstance().properties.getProperty(key); return o != null ? o.toString() : null; } @@ -262,14 +237,13 @@ public static synchronized String getStringValue(String key) /** * Return as an Integer the value associated with a specified key. * - * @param key the key for the desired value. + * @param key the key for the desired value. * @param defaultValue the value to return if the key does not exist. * * @return the value associated with the key, or the specified default value if the key does not exist or is not an - * Integer or string representation of an Integer. + * Integer or string representation of an Integer. */ - public static synchronized Integer getIntegerValue(String key, Integer defaultValue) - { + public static synchronized Integer getIntegerValue(String key, Integer defaultValue) { Integer v = getIntegerValue(key); return v != null ? v : defaultValue; } @@ -280,20 +254,17 @@ public static synchronized Integer getIntegerValue(String key, Integer defaultVa * @param key the key for the desired value. * * @return the value associated with the key, or null if the key does not exist or is not an Integer or string - * representation of an Integer. + * representation of an Integer. */ - public static synchronized Integer getIntegerValue(String key) - { + public static synchronized Integer getIntegerValue(String key) { String v = getStringValue(key); - if (v == null) + if (v == null) { return null; + } - try - { + try { return Integer.parseInt(v); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.SEVERE, "Configuration.ConversionError", v); return null; } @@ -302,14 +273,13 @@ public static synchronized Integer getIntegerValue(String key) /** * Return as an Long the value associated with a specified key. * - * @param key the key for the desired value. + * @param key the key for the desired value. * @param defaultValue the value to return if the key does not exist. * * @return the value associated with the key, or the specified default value if the key does not exist or is not a - * Long or string representation of a Long. + * Long or string representation of a Long. */ - public static synchronized Long getLongValue(String key, Long defaultValue) - { + public static synchronized Long getLongValue(String key, Long defaultValue) { Long v = getLongValue(key); return v != null ? v : defaultValue; } @@ -320,20 +290,17 @@ public static synchronized Long getLongValue(String key, Long defaultValue) * @param key the key for the desired value. * * @return the value associated with the key, or null if the key does not exist or is not a Long or string - * representation of a Long. + * representation of a Long. */ - public static synchronized Long getLongValue(String key) - { + public static synchronized Long getLongValue(String key) { String v = getStringValue(key); - if (v == null) + if (v == null) { return null; + } - try - { + try { return Long.parseLong(v); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.SEVERE, "Configuration.ConversionError", v); return null; } @@ -342,14 +309,13 @@ public static synchronized Long getLongValue(String key) /** * Return as an Double the value associated with a specified key. * - * @param key the key for the desired value. + * @param key the key for the desired value. * @param defaultValue the value to return if the key does not exist. * * @return the value associated with the key, or the specified default value if the key does not exist or is not an - * Double or string representation of an Double. + * Double or string representation of an Double. */ - public static synchronized Double getDoubleValue(String key, Double defaultValue) - { + public static synchronized Double getDoubleValue(String key, Double defaultValue) { Double v = getDoubleValue(key); return v != null ? v : defaultValue; } @@ -360,20 +326,17 @@ public static synchronized Double getDoubleValue(String key, Double defaultValue * @param key the key for the desired value. * * @return the value associated with the key, or null if the key does not exist or is not an Double or string - * representation of an Double. + * representation of an Double. */ - public static synchronized Double getDoubleValue(String key) - { + public static synchronized Double getDoubleValue(String key) { String v = getStringValue(key); - if (v == null) + if (v == null) { return null; + } - try - { + try { return Double.parseDouble(v); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.SEVERE, "Configuration.ConversionError", v); return null; } @@ -385,14 +348,13 @@ public static synchronized Double getDoubleValue(String key) * Valid values for true are '1' or anything that starts with 't' or 'T'. ie. 'true', 'True', 't' Valid values for * false are '0' or anything that starts with 'f' or 'F'. ie. 'false', 'False', 'f' * - * @param key the key for the desired value. + * @param key the key for the desired value. * @param defaultValue the value to return if the key does not exist. * * @return the value associated with the key, or the specified default value if the key does not exist or is not a - * Boolean or string representation of an Boolean. + * Boolean or string representation of an Boolean. */ - public static synchronized Boolean getBooleanValue(String key, Boolean defaultValue) - { + public static synchronized Boolean getBooleanValue(String key, Boolean defaultValue) { Boolean v = getBooleanValue(key); return v != null ? v : defaultValue; } @@ -406,24 +368,19 @@ public static synchronized Boolean getBooleanValue(String key, Boolean defaultVa * @param key the key for the desired value. * * @return the value associated with the key, or null if the key does not exist or is not a Boolean or string - * representation of an Boolean. + * representation of an Boolean. */ - public static synchronized Boolean getBooleanValue(String key) - { + public static synchronized Boolean getBooleanValue(String key) { String v = getStringValue(key); - if (v == null) + if (v == null) { return null; + } - if (v.trim().toUpperCase().startsWith("T") || v.trim().equals("1")) - { + if (v.trim().toUpperCase().startsWith("T") || v.trim().equals("1")) { return true; - } - else if (v.trim().toUpperCase().startsWith("F") || v.trim().equals("0")) - { + } else if (v.trim().toUpperCase().startsWith("F") || v.trim().equals("0")) { return false; - } - else - { + } else { Logging.logger().log(Level.SEVERE, "Configuration.ConversionError", v); return null; } @@ -436,8 +393,7 @@ else if (v.trim().toUpperCase().startsWith("F") || v.trim().equals("0")) * * @return true if the key exists, otherwise false. */ - public static synchronized boolean hasKey(String key) - { + public static synchronized boolean hasKey(String key) { return getInstance().properties.contains(key); } @@ -446,8 +402,7 @@ public static synchronized boolean hasKey(String key) * * @param key the key of interest. */ - public static synchronized void removeKey(String key) - { + public static synchronized void removeKey(String key) { getInstance().properties.remove(key); } @@ -455,23 +410,20 @@ public static synchronized void removeKey(String key) * Adds a key and value to the configuration, or changes the value associated with the key if the key is already in * the configuration. * - * @param key the key to set. + * @param key the key to set. * @param value the value to associate with the key. */ - public static synchronized void setValue(String key, Object value) - { + public static synchronized void setValue(String key, Object value) { getInstance().properties.put(key, value.toString()); } // OS, user, and run-time specific system properties. // - /** * Returns the path to the application's current working directory. * * @return the absolute path to the application's current working directory. */ - public static String getCurrentWorkingDirectory() - { + public static String getCurrentWorkingDirectory() { String dir = System.getProperty("user.dir"); return (dir != null) ? dir : "."; } @@ -481,8 +433,7 @@ public static String getCurrentWorkingDirectory() * * @return the absolute path to the application user's home directory. */ - public static String getUserHomeDirectory() - { + public static String getUserHomeDirectory() { String dir = System.getProperty("user.home"); return (dir != null) ? dir : "."; } @@ -492,8 +443,7 @@ public static String getUserHomeDirectory() * * @return the absolute path to the operating system's temporary directory. */ - public static String getSystemTempDirectory() - { + public static String getSystemTempDirectory() { String dir = System.getProperty("java.io.tmpdir"); return (dir != null) ? dir : "."; } @@ -503,31 +453,22 @@ public static String getSystemTempDirectory() * system on which the Java Virtual Machine is running. The following table provides the path for all supported * operating systems: * - *
Mapping
Operating SystemPath
Mac OS X~/Library/Application - * Support
Windows~\\Application Data
Linux, Unix, - * Solaris~/
+ * Operating SystemPath Mac OS X~/Library/Application Support + * Windows~\\Application Data Linux, Unix, Solaris~/ * * @return the absolute path to the current user's application data directory. */ - public static String getCurrentUserAppDataDirectory() - { - if (isMacOS()) - { + public static String getCurrentUserAppDataDirectory() { + if (isMacOS()) { // Return a path that Mac OS X has designated for app-specific data and support files. See the following URL // for details: // http://developer.apple.com/library/mac/#documentation/FileManagement/Conceptual/FileSystemProgrammingGUide/MacOSXDirectories/MacOSXDirectories.html#//apple_ref/doc/uid/TP40010672-CH10-SW1 return getUserHomeDirectory() + "/Library/Application Support"; - } - else if (isWindowsOS()) - { + } else if (isWindowsOS()) { return getUserHomeDirectory() + "\\Application Data"; - } - else if (isLinuxOS() || isUnixOS() || isSolarisOS()) - { + } else if (isLinuxOS() || isUnixOS() || isSolarisOS()) { return getUserHomeDirectory(); - } - else - { + } else { String msg = Logging.getMessage("generic.UnknownOperatingSystem"); Logging.logger().fine(msg); return null; @@ -539,8 +480,7 @@ else if (isLinuxOS() || isUnixOS() || isSolarisOS()) * * @return true if the operating system is a Mac operating system, otherwise false. */ - public static boolean isMacOS() - { + public static boolean isMacOS() { String osName = System.getProperty("os.name"); return osName != null && osName.toLowerCase().contains("mac"); } @@ -550,8 +490,7 @@ public static boolean isMacOS() * * @return true if the operating system is a Windows operating system, otherwise false. */ - public static boolean isWindowsOS() - { + public static boolean isWindowsOS() { String osName = System.getProperty("os.name"); return osName != null && osName.toLowerCase().contains("windows"); } @@ -561,8 +500,7 @@ public static boolean isWindowsOS() * * @return true if the operating system is a Windows XP operating system, otherwise false. */ - public static boolean isWindowsXPOS() - { + public static boolean isWindowsXPOS() { String osName = System.getProperty("os.name"); return osName != null && osName.toLowerCase().contains("windows") && osName.contains("xp"); } @@ -572,8 +510,7 @@ public static boolean isWindowsXPOS() * * @return true if the operating system is a Windows Vista operating system, otherwise false. */ - public static boolean isWindowsVistaOS() - { + public static boolean isWindowsVistaOS() { String osName = System.getProperty("os.name"); return osName != null && osName.toLowerCase().contains("windows") && osName.contains("vista"); } @@ -583,8 +520,7 @@ public static boolean isWindowsVistaOS() * * @return true if the operating system is a Windows Vista operating system, otherwise false. */ - public static boolean isWindows7OS() - { + public static boolean isWindows7OS() { String osName = System.getProperty("os.name"); return osName != null && osName.toLowerCase().contains("windows") && osName.contains("7"); } @@ -594,8 +530,7 @@ public static boolean isWindows7OS() * * @return true if the operating system is a Linux operating system, otherwise false. */ - public static boolean isLinuxOS() - { + public static boolean isLinuxOS() { String osName = System.getProperty("os.name"); return osName != null && osName.toLowerCase().contains("linux"); } @@ -605,8 +540,7 @@ public static boolean isLinuxOS() * * @return true if the operating system is a Unix operating system, otherwise false. */ - public static boolean isUnixOS() - { + public static boolean isUnixOS() { String osName = System.getProperty("os.name"); return osName != null && osName.toLowerCase().contains("unix"); } @@ -616,8 +550,7 @@ public static boolean isUnixOS() * * @return true if the operating system is a Solaris operating system, otherwise false. */ - public static boolean isSolarisOS() - { + public static boolean isSolarisOS() { String osName = System.getProperty("os.name"); return osName != null && osName.toLowerCase().contains("solaris"); } @@ -627,18 +560,15 @@ public static boolean isSolarisOS() * * @return the Java virtual machine version. */ - public static float getJavaVersion() - { + public static float getJavaVersion() { float ver = 0f; String s = System.getProperty("java.specification.version"); - if (null == s || s.length() == 0) + if (null == s || s.length() == 0) { s = System.getProperty("java.version"); - try - { - ver = Float.parseFloat(s.trim()); } - catch (NumberFormatException ignore) - { + try { + ver = Float.parseFloat(s.trim()); + } catch (NumberFormatException ignore) { } return ver; } @@ -652,8 +582,7 @@ public static float getJavaVersion() * * @return the highest compatible OpenGL profile. */ - public static GLProfile getMaxCompatibleGLProfile() - { + public static GLProfile getMaxCompatibleGLProfile() { return GLProfile.getMaxFixedFunc(true); // Favor a hardware rasterizer. } @@ -665,8 +594,7 @@ public static GLProfile getMaxCompatibleGLProfile() * * @return a new capabilities instance identifying required graphics features. */ - public static GLCapabilities getRequiredGLCapabilities() - { + public static GLCapabilities getRequiredGLCapabilities() { GLCapabilities caps = new GLCapabilities(getMaxCompatibleGLProfile()); caps.setAlphaBits(8); @@ -678,8 +606,9 @@ public static GLCapabilities getRequiredGLCapabilities() // Determine whether we should request a stereo canvas String stereo = System.getProperty(AVKey.STEREO_MODE); - if ("device".equals(stereo)) + if ("device".equals(stereo)) { caps.setStereo(true); + } return caps; } @@ -693,20 +622,16 @@ public static GLCapabilities getRequiredGLCapabilities() * * @throws NullPointerException if the XPath expression is null. */ - public static Element getElement(String xpathExpression) - { + public static Element getElement(String xpathExpression) { XPath xpath = WWXML.makeXPath(); - for (Document doc : getInstance().configDocs) - { - try - { + for (Document doc : getInstance().configDocs) { + try { Node node = (Node) xpath.evaluate(xpathExpression, doc.getDocumentElement(), XPathConstants.NODE); - if (node != null) + if (node != null) { return (Element) node; - } - catch (XPathExpressionException e) - { + } + } catch (XPathExpressionException e) { return null; } } diff --git a/src/gov/nasa/worldwind/Disposable.java b/src/gov/nasa/worldwind/Disposable.java index 276ef2d47c..006ffeaa85 100644 --- a/src/gov/nasa/worldwind/Disposable.java +++ b/src/gov/nasa/worldwind/Disposable.java @@ -3,15 +3,16 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; /** * @author tag * @version $Id: Disposable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Disposable -{ - /** Disposes of any internal resources allocated by the object. */ +public interface Disposable { + + /** + * Disposes of any internal resources allocated by the object. + */ public void dispose(); } diff --git a/src/gov/nasa/worldwind/Exportable.java b/src/gov/nasa/worldwind/Exportable.java index fa43390610..cc99257f5c 100644 --- a/src/gov/nasa/worldwind/Exportable.java +++ b/src/gov/nasa/worldwind/Exportable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import java.io.IOException; @@ -24,8 +23,8 @@ * @author pabercrombie * @version $Id: Exportable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Exportable -{ +public interface Exportable { + /** * Returned by {@link #isExportFormatSupported(String)} if the object does support export to the given format. */ @@ -58,16 +57,15 @@ public interface Exportable * Exports the object to a format. * * @param mimeType Desired export format. Call {@link #isExportFormatSupported(String)} to make sure that the object - * supports the format before trying to export, or be prepared to handle {@code + * supports the format before trying to export, or be prepared to handle {@code * UnsupportedOperationException}. - * @param output Object that will receive the exported data. The type of this object depends on the export format. - * All formats should support {@code java.io.OutputStream}. Text based format (for example, XML - * formats) should also support {@code java.io.Writer}. Certain formats may also support other - * object types. + * @param output Object that will receive the exported data. The type of this object depends on the export format. + * All formats should support {@code java.io.OutputStream}. Text based format (for example, XML formats) should also + * support {@code java.io.Writer}. Certain formats may also support other object types. * - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. * @throws UnsupportedOperationException if the format is not supported by this object, or if the {@code output} - * argument is not of a supported type. + * argument is not of a supported type. * @see #isExportFormatSupported(String) */ void export(String mimeType, Object output) throws IOException, UnsupportedOperationException; diff --git a/src/gov/nasa/worldwind/Factory.java b/src/gov/nasa/worldwind/Factory.java index 20f5aa4c74..7c419d6303 100644 --- a/src/gov/nasa/worldwind/Factory.java +++ b/src/gov/nasa/worldwind/Factory.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.avlist.AVList; @@ -14,22 +13,21 @@ * @author tag * @version $Id: Factory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Factory -{ +public interface Factory { + /** * Creates an object from a general configuration source. * * @param configSource the configuration source. - * @param params properties to apply during object creation. + * @param params properties to apply during object creation. * * @return the new object. * * @throws IllegalArgumentException if the configuration source is null or an empty string. - * @throws gov.nasa.worldwind.exception.WWUnrecognizedException - * if the type of source or some object-specific value is unrecognized. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if object creation fails. The exception indicating the source of the failure is - * included as the {@link Exception#initCause(Throwable)}. + * @throws gov.nasa.worldwind.exception.WWUnrecognizedException if the type of source or some object-specific value + * is unrecognized. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if object creation fails. The exception indicating the + * source of the failure is included as the {@link Exception#initCause(Throwable)}. */ Object createFromConfigSource(Object configSource, AVList params); } diff --git a/src/gov/nasa/worldwind/Locatable.java b/src/gov/nasa/worldwind/Locatable.java index 0c671c4ef6..ab7e6e05fd 100644 --- a/src/gov/nasa/worldwind/Locatable.java +++ b/src/gov/nasa/worldwind/Locatable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.geom.Position; @@ -12,7 +11,7 @@ * @author tag * @version $Id: Locatable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Locatable -{ +public interface Locatable { + public Position getPosition(); } diff --git a/src/gov/nasa/worldwind/Model.java b/src/gov/nasa/worldwind/Model.java index 8273931c6e..bd39530d90 100644 --- a/src/gov/nasa/worldwind/Model.java +++ b/src/gov/nasa/worldwind/Model.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.globes.Globe; @@ -17,8 +16,8 @@ * @author Tom Gaskins * @version $Id: Model.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Model extends WWObject -{ +public interface Model extends WWObject { + /** * Returns the bounding sphere in Cartesian world coordinates of the model. * @@ -43,8 +42,7 @@ public interface Model extends WWObject /** * Specifies the model's globe. * - * @param globe the model's new globe. May be null, in which case the current globe will be detached from the - * model. + * @param globe the model's new globe. May be null, in which case the current globe will be detached from the model. */ void setGlobe(Globe globe); @@ -52,7 +50,7 @@ public interface Model extends WWObject * Specifies the model's layers. * * @param layers the model's new layers. May be null, in which case the current layers will be detached from the - * model. + * model. */ void setLayers(LayerList layers); diff --git a/src/gov/nasa/worldwind/Movable.java b/src/gov/nasa/worldwind/Movable.java index 5109fb1201..96ee4902d3 100644 --- a/src/gov/nasa/worldwind/Movable.java +++ b/src/gov/nasa/worldwind/Movable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.geom.Position; @@ -16,8 +15,8 @@ * @author tag * @version $Id: Movable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Movable -{ +public interface Movable { + /** * A position associated with the object that indicates its aggregate geographic position. The chosen position * varies among implementers of this interface. For objects defined by a list of positions, the reference position diff --git a/src/gov/nasa/worldwind/Movable2.java b/src/gov/nasa/worldwind/Movable2.java index b1d7fb4deb..c2dbfa337d 100644 --- a/src/gov/nasa/worldwind/Movable2.java +++ b/src/gov/nasa/worldwind/Movable2.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.geom.Position; @@ -13,8 +12,8 @@ * @author tag * @version $Id: Movable2.java 2291 2014-08-30 21:38:47Z tgaskins $ */ -public interface Movable2 -{ +public interface Movable2 { + /** * A position associated with the object that indicates its aggregate geographic position. The chosen position * varies among implementers of this interface. For objects defined by a list of positions, the reference position diff --git a/src/gov/nasa/worldwind/Restorable.java b/src/gov/nasa/worldwind/Restorable.java index ea3d0c9eb5..602843f637 100644 --- a/src/gov/nasa/worldwind/Restorable.java +++ b/src/gov/nasa/worldwind/Restorable.java @@ -3,18 +3,17 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; /** - * Restorable is an interface for describing the current state of an object, and restoring an object's - * state. Object state descriptions will be formatted as an XML document string. This allows the state description - * to be located in a file, reside in a database, or be passed over a network. + * Restorable is an interface for describing the current state of an object, and restoring an object's state. Object + * state descriptions will be formatted as an XML document string. This allows the state description to be located in a + * file, reside in a database, or be passed over a network. *

* The exact structure of the XML document is the responsibility of the implementation. However, to encourage data - * sharing between similar implementations, each implementation of Restorable should design - * restoreState to accept and ignore unknown structures in state documents. Otherwise, implementations - * should clearly document how they will behave when encountering an unknown structure. + * sharing between similar implementations, each implementation of Restorable should design restoreState to + * accept and ignore unknown structures in state documents. Otherwise, implementations should clearly document how they + * will behave when encountering an unknown structure. *

* See the WorldWideWeb Consortium's (W3C) documentation on * Extensible Markup Language (XML) 1.1 for information on XML. @@ -22,12 +21,12 @@ * @author dcollins * @version $Id: Restorable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Restorable -{ +public interface Restorable { + /** * Returns an XML document string describing the object's state. This state can be restored later by calling * restoreState and passing the XML document. - * + * * @return an XML document string describing the object's state. */ String getRestorableState(); diff --git a/src/gov/nasa/worldwind/SceneController.java b/src/gov/nasa/worldwind/SceneController.java index a6a663ada9..35808220aa 100644 --- a/src/gov/nasa/worldwind/SceneController.java +++ b/src/gov/nasa/worldwind/SceneController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.cache.GpuResourceCache; @@ -19,8 +18,8 @@ * @author Tom Gaskins * @version $Id: SceneController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface SceneController extends WWObject, Disposable -{ +public interface SceneController extends WWObject, Disposable { + /** * Indicates the scene controller's model. This returns null if the scene controller has no model. * @@ -55,7 +54,7 @@ public interface SceneController extends WWObject, Disposable * Cause the window to regenerate the frame, including pick resolution. * * @return if greater than zero, the window should be automatically repainted again at the indicated number of - * milliseconds from this method's return. + * milliseconds from this method's return. */ int repaint(); @@ -86,7 +85,7 @@ public interface SceneController extends WWObject, Disposable * during the most recent call to repaint. * * @return the list of picked objects intersecting the pick rectangle, or null if no objects are currently - * intersecting the rectangle. + * intersecting the rectangle. */ PickedObjectList getObjectsInPickRectangle(); @@ -215,7 +214,9 @@ public interface SceneController extends WWObject, Disposable */ DrawContext getDrawContext(); - /** Reinitializes the scene controller. */ + /** + * Reinitializes the scene controller. + */ void reinitialize(); /** @@ -232,7 +233,7 @@ public interface SceneController extends WWObject, Disposable * the model of this screen controller. * * @param screenCreditRenderer the screen credit controller. May be null, in which case screen credits are not - * displayed. + * displayed. */ void setScreenCreditController(ScreenCreditController screenCreditRenderer); diff --git a/src/gov/nasa/worldwind/StereoOptionSceneController.java b/src/gov/nasa/worldwind/StereoOptionSceneController.java index 48779398de..a80db538f1 100644 --- a/src/gov/nasa/worldwind/StereoOptionSceneController.java +++ b/src/gov/nasa/worldwind/StereoOptionSceneController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.avlist.AVKey; @@ -31,8 +30,8 @@ * @author tag * @version $Id: StereoOptionSceneController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class StereoOptionSceneController extends BasicSceneController implements StereoSceneController -{ +public class StereoOptionSceneController extends BasicSceneController implements StereoSceneController { + /** * The default focus angle. May be specified in the WorldWind configuration file as the * gov.nasa.worldwind.StereoFocusAngle property. The default if not specified in the configuration is @@ -40,15 +39,25 @@ public class StereoOptionSceneController extends BasicSceneController implements */ protected static final double DEFAULT_FOCUS_ANGLE = Configuration.getDoubleValue(AVKey.STEREO_FOCUS_ANGLE, 1.6); - /** The current stereo mode. May not be set to null; use {@link AVKey#STEREO_MODE_NONE} instead. */ + /** + * The current stereo mode. May not be set to null; use {@link AVKey#STEREO_MODE_NONE} instead. + */ protected String stereoMode = AVKey.STEREO_MODE_NONE; - /** The angle between eyes. Larger angles give increased 3D effect. */ + /** + * The angle between eyes. Larger angles give increased 3D effect. + */ protected Angle focusAngle = Angle.fromDegrees(DEFAULT_FOCUS_ANGLE); - /** Indicates whether left and right eye positions are swapped. */ + /** + * Indicates whether left and right eye positions are swapped. + */ protected boolean swapEyes = false; - /** Indicates the GL drawable capabilities. Non-null only after this scene controller draws once. */ + /** + * Indicates the GL drawable capabilities. Non-null only after this scene controller draws once. + */ protected GLCapabilitiesImmutable capabilities; - /** Indicates whether hardware device stereo is available. Valid only after this scene controller draws once. */ + /** + * Indicates whether hardware device stereo is available. Valid only after this scene controller draws once. + */ protected boolean hardwareStereo = false; /** * Indicates whether stereo is being applied, either because a stereo device is being used or a stereo mode is in @@ -57,27 +66,27 @@ public class StereoOptionSceneController extends BasicSceneController implements */ protected boolean inStereo = false; - /** Constructs an instance and initializes its stereo mode to */ - public StereoOptionSceneController() - { + /** + * Constructs an instance and initializes its stereo mode to + */ + public StereoOptionSceneController() { String stereo = System.getProperty(AVKey.STEREO_MODE); - if ("redblue".equalsIgnoreCase(stereo)) + if ("redblue".equalsIgnoreCase(stereo)) { this.setStereoMode(AVKey.STEREO_MODE_RED_BLUE); - else if ("device".equalsIgnoreCase(stereo)) + } else if ("device".equalsIgnoreCase(stereo)) { this.setStereoMode(AVKey.STEREO_MODE_DEVICE); + } } - public void setStereoMode(String mode) - { + public void setStereoMode(String mode) { this.stereoMode = mode != null ? mode : AVKey.STEREO_MODE_NONE; // If device-implemented stereo is used, stereo is considered always in effect no matter what the stereo mode. this.inStereo = this.isHardwareStereo() || AVKey.STEREO_MODE_RED_BLUE.equals(this.stereoMode); } - public String getStereoMode() - { + public String getStereoMode() { return this.stereoMode; } @@ -86,28 +95,23 @@ public String getStereoMode() * * @param a the left-right eye direction difference. If null, the angle is set to 0. */ - public void setFocusAngle(Angle a) - { + public void setFocusAngle(Angle a) { this.focusAngle = a != null ? a : Angle.ZERO; } - public Angle getFocusAngle() - { + public Angle getFocusAngle() { return this.focusAngle; } - public void setSwapEyes(boolean swapEyes) - { + public void setSwapEyes(boolean swapEyes) { this.swapEyes = swapEyes; } - public boolean isSwapEyes() - { + public boolean isSwapEyes() { return this.swapEyes; } - public boolean isHardwareStereo() - { + public boolean isHardwareStereo() { return this.hardwareStereo; } @@ -118,25 +122,21 @@ public boolean isHardwareStereo() * returns true even if the stereo mode is {@link AVKey#STEREO_MODE_NONE}. In this case, individual stereo images * are drawn for left and right eyes in order to prevent a blurred scene. */ - public boolean isInStereo() - { + public boolean isInStereo() { return this.inStereo; } @Override - protected void draw(DrawContext dc) - { + protected void draw(DrawContext dc) { // Capture the capabilities actually in use. - if (this.capabilities == null) - { + if (this.capabilities == null) { this.capabilities = dc.getGLContext().getGLDrawable().getChosenGLCapabilities(); this.hardwareStereo = this.capabilities.getStereo(); this.inStereo = this.isHardwareStereo() ? true : this.isInStereo(); } // If stereo isn't to be applied, just draw and return. - if (!isInStereo()) - { + if (!isInStereo()) { super.draw(dc); return; } @@ -145,14 +145,16 @@ protected void draw(DrawContext dc) // work correctly (temporary hack) View dcView = dc.getView(); Boolean pitchInRange = (dcView.getPitch().compareTo(Angle.fromDegrees(50)) > 0 - && dcView.getPitch().compareTo(Angle.POS90) < 0); + && dcView.getPitch().compareTo(Angle.POS90) < 0); - if (AVKey.STEREO_MODE_DEVICE.equals(this.stereoMode) && this.isHardwareStereo() && pitchInRange) + if (AVKey.STEREO_MODE_DEVICE.equals(this.stereoMode) && this.isHardwareStereo() && pitchInRange) { this.doDrawToStereoDevice(dc); - else if (AVKey.STEREO_MODE_RED_BLUE.equals(this.stereoMode) && pitchInRange) + } else if (AVKey.STEREO_MODE_RED_BLUE.equals(this.stereoMode) && pitchInRange) { this.doDrawStereoRedBlue(dc); - else // AVKey.STEREO_MODE_NONE + } else // AVKey.STEREO_MODE_NONE + { this.doDrawStereoNone(dc); + } } /** @@ -163,8 +165,7 @@ else if (AVKey.STEREO_MODE_RED_BLUE.equals(this.stereoMode) && pitchInRange) * * @param dc the current draw context. */ - protected void doDrawStereoNone(DrawContext dc) - { + protected void doDrawStereoNone(DrawContext dc) { // If running on a stereo device but want to draw a normal image, both buffers must be filled or the // display will be blurry. @@ -184,27 +185,26 @@ protected void doDrawStereoNone(DrawContext dc) * * @param dc the current draw context. */ - protected void doDrawStereoRedBlue(DrawContext dc) - { + protected void doDrawStereoRedBlue(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. View dcView = dc.getView(); // Draw the left eye - if (this.isSwapEyes()) - { - if (this.isHardwareStereo()) + if (this.isSwapEyes()) { + if (this.isHardwareStereo()) { gl.glDrawBuffer(GL2.GL_BACK_RIGHT); + } gl.glColorMask(false, true, true, true); // right eye in green/blue - } - else - { - if (this.isHardwareStereo()) + } else { + if (this.isHardwareStereo()) { gl.glDrawBuffer(GL2.GL_BACK_LEFT); + } gl.glColorMask(true, false, false, true); // left eye in red only } - if (this.isHardwareStereo()) + if (this.isHardwareStereo()) { gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + } super.draw(dc); @@ -214,28 +214,25 @@ protected void doDrawStereoRedBlue(DrawContext dc) dcView.apply(dc); // Draw the right eye frame green and blue only - try - { + try { gl.glClear(GL.GL_DEPTH_BUFFER_BIT); - if (this.isSwapEyes()) - { - if (this.isHardwareStereo()) + if (this.isSwapEyes()) { + if (this.isHardwareStereo()) { gl.glDrawBuffer(GL2.GL_BACK_RIGHT); + } gl.glColorMask(true, false, false, true); // right eye in red only - } - else - { - if (this.isHardwareStereo()) + } else { + if (this.isHardwareStereo()) { gl.glDrawBuffer(GL2.GL_BACK_LEFT); + } gl.glColorMask(false, true, true, true); // right eye in green/blue } - if (this.isHardwareStereo()) + if (this.isHardwareStereo()) { gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + } super.draw(dc); - } - finally - { + } finally { // Restore the original view heading dcView.setHeading(viewHeading); dcView.apply(dc); @@ -249,16 +246,16 @@ protected void doDrawStereoRedBlue(DrawContext dc) * * @param dc the current draw context. */ - protected void doDrawToStereoDevice(DrawContext dc) - { + protected void doDrawToStereoDevice(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. View dcView = dc.getView(); // Draw the left eye - if (this.isSwapEyes()) + if (this.isSwapEyes()) { gl.glDrawBuffer(GL2.GL_BACK_RIGHT); - else + } else { gl.glDrawBuffer(GL2.GL_BACK_LEFT); + } gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); super.draw(dc); @@ -269,18 +266,16 @@ protected void doDrawToStereoDevice(DrawContext dc) dcView.apply(dc); // Draw the right eye - try - { - if (this.isSwapEyes()) + try { + if (this.isSwapEyes()) { gl.glDrawBuffer(GL2.GL_BACK_LEFT); - else + } else { gl.glDrawBuffer(GL2.GL_BACK_RIGHT); + } gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); super.draw(dc); - } - finally - { + } finally { // Restore the original view heading dcView.setHeading(viewHeading); dcView.apply(dc); diff --git a/src/gov/nasa/worldwind/StereoSceneController.java b/src/gov/nasa/worldwind/StereoSceneController.java index 9fded8448c..30005d1c95 100644 --- a/src/gov/nasa/worldwind/StereoSceneController.java +++ b/src/gov/nasa/worldwind/StereoSceneController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.geom.Angle; @@ -17,8 +16,8 @@ * @author Tom Gaskins * @version $Id: StereoSceneController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface StereoSceneController extends SceneController -{ +public interface StereoSceneController extends SceneController { + /** * Specifies the technique used to provide a stereo effect. Defined options are {@link * gov.nasa.worldwind.avlist.AVKey#STEREO_MODE_DEVICE} to request device supported stereo, {@link @@ -39,7 +38,7 @@ public interface StereoSceneController extends SceneController * Indicates the current stereo mode of this controller. * * @return the current stereo mode. See this class' description for the possible modes. This method does not return - * null. If a null mode was passed to {@link #setStereoMode(String)}, this instance's mode was set to {@link + * null. If a null mode was passed to {@link #setStereoMode(String)}, this instance's mode was set to {@link * gov.nasa.worldwind.avlist.AVKey#STEREO_MODE_NONE}. */ public String getStereoMode(); diff --git a/src/gov/nasa/worldwind/Version.java b/src/gov/nasa/worldwind/Version.java index 351da32149..36ec9cac8f 100644 --- a/src/gov/nasa/worldwind/Version.java +++ b/src/gov/nasa/worldwind/Version.java @@ -3,48 +3,41 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; /** * @author tag * @version $Id: Version.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Version -{ +public class Version { + private static final String MAJOR_VALUE = "2"; private static final String MINOR_VALUE = "1"; private static final String DOT_VALUE = "0"; private static final String versionNumber = "v" + MAJOR_VALUE + "." + MINOR_VALUE + "." + DOT_VALUE; private static final String versionName = "NASA WorldWind Java"; - public static String getVersion() - { + public static String getVersion() { return versionName + " " + versionNumber; } - public static String getVersionName() - { + public static String getVersionName() { return versionName; } - public static String getVersionNumber() - { + public static String getVersionNumber() { return versionNumber; } - public static String getVersionMajorNumber() - { + public static String getVersionMajorNumber() { return MAJOR_VALUE; } - public static String getVersionMinorNumber() - { + public static String getVersionMinorNumber() { return MINOR_VALUE; } - public static String getVersionDotNumber() - { + public static String getVersionDotNumber() { return DOT_VALUE; } } diff --git a/src/gov/nasa/worldwind/View.java b/src/gov/nasa/worldwind/View.java index d8400b550a..285f0fba0c 100644 --- a/src/gov/nasa/worldwind/View.java +++ b/src/gov/nasa/worldwind/View.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.animation.Animator; @@ -25,34 +24,36 @@ * The following methods return state values updated in the most recent call to apply.

    *
  • getEyePosition
  • getEyePoint
  • getUpVector
  • getForwardVector
  • *
  • getModelviewMatrix
  • getViewport
  • getFrustum
  • getFrustumInModelCoordinates
  • - *
  • getProjectionMatrix
+ *
  • getProjectionMatrix
  • *

    * The following methods return computed values using state that was updated in the most recent call to * apply.

    • project
    • unproject
    • computeRayFromScreenPoint
    • *
    • computePositionFromScreenPoint
    • computePixelSizeAtDistance
    • computeHorizonDistance
    - * + * * * @author Paul Collins * @version $Id: View.java 1171 2013-02-11 21:45:02Z dcollins $ * @see gov.nasa.worldwind.view.orbit.OrbitView */ -public interface View extends WWObject, Restorable -{ +public interface View extends WWObject, Restorable { final String VIEW_STOPPED = "gov.nasa.worldwind.View.ViewStopped"; - /** Stops any movement associated with this View. */ + /** + * Stops any movement associated with this View. + */ void stopMovement(); /** * Returns the current geographic coordinates of this view's eye position, as computed for the most recent model * traversal. *

    - * Note: The value returned is not necessarily the value specified to {@link #setEyePosition(gov.nasa.worldwind.geom.Position)} - * but is the eye position corresponding to this view's most recently applied state. + * Note: The value returned is not necessarily the value specified to + * {@link #setEyePosition(gov.nasa.worldwind.geom.Position)} but is the eye position corresponding to this view's + * most recently applied state. * * @return the position of the eye corresponding to the most recent application of this view, or null if the view - * has not yet been applied. + * has not yet been applied. */ Position getEyePosition(); @@ -69,8 +70,9 @@ public interface View extends WWObject, Restorable * Returns the current geographic coordinates of this view's eye position, as determined from this view's current * parameters. *

    - * Note: The value returned is not necessarily the value specified to {@link #setEyePosition(gov.nasa.worldwind.geom.Position)} - * but is the eye position corresponding to this view's current parameters. + * Note: The value returned is not necessarily the value specified to + * {@link #setEyePosition(gov.nasa.worldwind.geom.Position)} but is the eye position corresponding to this view's + * current parameters. * * @return the position of the eye corresponding to the current parameters of this view. */ @@ -83,20 +85,20 @@ public interface View extends WWObject, Restorable * Specifically, implementations must determine what the up direction will be given these parameters, and apply * these parameters in a meaningful way. * - * @param eyePosition Position of they eye. + * @param eyePosition Position of they eye. * @param centerPosition Position of the screen center. */ void setOrientation(Position eyePosition, Position centerPosition); /** - * Sets the heading of the view. The implementation may interpret this command in whatever way it chooses. + * Sets the heading of the view. The implementation may interpret this command in whatever way it chooses. * * @param heading The direction to aim the view in degrees */ void setHeading(Angle heading); /** - * Sets the pitch of the view. The implementation may interpret pitch as it chooses + * Sets the pitch of the view. The implementation may interpret pitch as it chooses * * @param pitch The pitch of the view. */ @@ -195,7 +197,7 @@ public interface View extends WWObject, Restorable * @param fieldOfView the horizontal field-of-view angle. * * @throws IllegalArgumentException If the implementation supports field-of-view, and fieldOfView is - * null. + * null. */ void setFieldOfView(Angle fieldOfView); @@ -208,7 +210,7 @@ public interface View extends WWObject, Restorable java.awt.Rectangle getViewport(); /** - * Returns the near clipping plane distance, in eye coordinates. Implementations of the View interface + * Returns the near clipping plane distance, in eye coordinates. Implementations of the View interface * are not required to have a method for setting the near and far distance. Applications that need to control the * near and far clipping distances can derive from {@link gov.nasa.worldwind.view.orbit.BasicOrbitView} or {@link * gov.nasa.worldwind.view.firstperson.BasicFlyView} @@ -265,7 +267,7 @@ public interface View extends WWObject, Restorable * @param dc the current WorldWind DrawContext on which View will apply its state. * * @throws IllegalArgumentException If dc is null, or if the Globe or GL - * instances in dc are null. + * instances in dc are null. */ void apply(DrawContext dc); @@ -284,7 +286,7 @@ public interface View extends WWObject, Restorable /** * Maps a Point in screen coordinates to a Point in model coordinates. The input x and y - * are relative to the lower left hand screen corner, while z is the screen depth-coordinate. If the screen point + * are relative to the lower left hand screen corner, while z is the screen depth-coordinate. If the screen point * cannot be successfully mapped, this will return null. * * @param windowPoint the window coordinate Point to project. @@ -303,13 +305,13 @@ public interface View extends WWObject, Restorable * popReferenceCenter} after rendering is complete. Note that calls to {@link #getModelviewMatrix} will not return * reference-center model-view matrix, but the original matrix. * - * @param dc the current WorldWind drawing context on which new model-view state will be applied. + * @param dc the current WorldWind drawing context on which new model-view state will be applied. * @param referenceCenter the location to become the new world origin. * * @return a new model-view matrix with origin is at referenceCenter, or null if this method failed. * * @throws IllegalArgumentException if referenceCenter is null, if dc is null, or if the - * Globe or GL instances in dc are null. + * Globe or GL instances in dc are null. */ Matrix pushReferenceCenter(DrawContext dc, Vec4 referenceCenter); @@ -319,20 +321,20 @@ public interface View extends WWObject, Restorable * @param dc the current WorldWind drawing context on which the original matrix will be restored. * * @throws IllegalArgumentException if dc is null, or if the Globe or GL - * instances in dc are null. + * instances in dc are null. */ void popReferenceCenter(DrawContext dc); /** * Sets the reference center matrix without pushing the stack. * - * @param dc the drawing context. + * @param dc the drawing context. * @param referenceCenter the new reference center * * @return a new model-view matrix with origin is at referenceCenter, or null if this method failed. * * @throws IllegalArgumentException if referenceCenter is null, if dc is null, or if the - * Globe or GL instances in dc are null. + * Globe or GL instances in dc are null. * @see #pushReferenceCenter(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.geom.Vec4) */ Matrix setReferenceCenter(DrawContext dc, Vec4 referenceCenter); @@ -345,7 +347,7 @@ public interface View extends WWObject, Restorable * @param y the vertical coordinate originating from the top of View's projection plane. * * @return a line beginning at the View's eye point and passing through (x, y) transformed into model - * space. + * space. */ Line computeRayFromScreenPoint(double x, double y); @@ -366,7 +368,7 @@ public interface View extends WWObject, Restorable * question. This computation assumes that pixels dimensions are square, and therefore returns a single dimension. * * @param distance the distance in meters from the eye point. This value must be positive but is otherwise - * unbounded. + * unbounded. * * @return the dimension of a pixel in meters at the given distance. * @@ -397,14 +399,16 @@ public interface View extends WWObject, Restorable */ ViewInputHandler getViewInputHandler(); - /** Stops any animations that are active in this View */ + /** + * Stops any animations that are active in this View + */ void stopAnimations(); /** - * Animate to the specified position. The implementation is expected to animate the View to look at - * the given position from the given elevation. + * Animate to the specified position. The implementation is expected to animate the View to look at the + * given position from the given elevation. * - * @param position The position to animate to. + * @param position The position to animate to. * @param elevation The elevation to look at the position from. */ void goTo(Position position, double elevation); @@ -432,7 +436,7 @@ public interface View extends WWObject, Restorable /** * Add an animator to the View. This method does not start the {@link - * gov.nasa.worldwind.animation.Animator}. Starting the {@link gov.nasa.worldwind.animation.Animator} is the + * gov.nasa.worldwind.animation.Animator}. Starting the {@link gov.nasa.worldwind.animation.Animator} is the * responsibility of the application. * * @param animator the {@link gov.nasa.worldwind.animation.Animator} to be added diff --git a/src/gov/nasa/worldwind/WWObject.java b/src/gov/nasa/worldwind/WWObject.java index fe93b76dee..70672c9d0f 100644 --- a/src/gov/nasa/worldwind/WWObject.java +++ b/src/gov/nasa/worldwind/WWObject.java @@ -3,20 +3,18 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.avlist.AVList; import gov.nasa.worldwind.event.MessageListener; /** - * An interface provided by the major WorldWind components to provide attribute-value list management and - * property change management. Classifies implementers as property-change listeners, allowing them to receive - * property-change events. + * An interface provided by the major WorldWind components to provide attribute-value list management and property + * change management. Classifies implementers as property-change listeners, allowing them to receive property-change + * events. * * @author Tom Gaskins * @version $Id: WWObject.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WWObject extends AVList, java.beans.PropertyChangeListener, MessageListener -{ +public interface WWObject extends AVList, java.beans.PropertyChangeListener, MessageListener { } diff --git a/src/gov/nasa/worldwind/WWObjectImpl.java b/src/gov/nasa/worldwind/WWObjectImpl.java index eb70be95e2..765d41324f 100644 --- a/src/gov/nasa/worldwind/WWObjectImpl.java +++ b/src/gov/nasa/worldwind/WWObjectImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.avlist.AVListImpl; @@ -17,30 +16,27 @@ * @author Tom Gaskins * @version $Id: WWObjectImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWObjectImpl extends AVListImpl implements WWObject -{ +public class WWObjectImpl extends AVListImpl implements WWObject { + /** * Constructs a new WWObjectImpl. */ - public WWObjectImpl() - { + public WWObjectImpl() { } - public WWObjectImpl(Object source) - { + public WWObjectImpl(Object source) { super(source); } /** - * The property change listener for this instance. - * Receives property change notifications that this instance has registered with other property change notifiers. + * The property change listener for this instance. Receives property change notifications that this + * instance has registered with other property change notifiers. + * * @param propertyChangeEvent the event * @throws IllegalArgumentException if propertyChangeEvent is null */ - public void propertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent == null) - { + public void propertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) { + if (propertyChangeEvent == null) { String msg = Logging.getMessage("nullValue.PropertyChangeEventIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -50,9 +46,10 @@ public void propertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) super.firePropertyChange(propertyChangeEvent); } - /** Empty implementation of MessageListener. */ - public void onMessage(Message message) - { + /** + * Empty implementation of MessageListener. + */ + public void onMessage(Message message) { // Empty implementation } } diff --git a/src/gov/nasa/worldwind/WorldWind.java b/src/gov/nasa/worldwind/WorldWind.java index 4b10a24957..816574f9f1 100644 --- a/src/gov/nasa/worldwind/WorldWind.java +++ b/src/gov/nasa/worldwind/WorldWind.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.avlist.AVKey; @@ -22,8 +21,8 @@ * @author Tom Gaskins * @version $Id: WorldWind.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public final class WorldWind -{ +public final class WorldWind { + public static final String SHUTDOWN_EVENT = "gov.nasa.worldwind.ShutDown"; // Altitude modes @@ -59,13 +58,12 @@ private WorldWind() // Singleton, prevent public instantiation. this.initialize(); } - private void initialize() - { + private void initialize() { this.wwo = new WWObjectImpl(); this.remoteRetrievalService = (RetrievalService) createConfigurationComponent( - AVKey.RETRIEVAL_SERVICE_CLASS_NAME); + AVKey.RETRIEVAL_SERVICE_CLASS_NAME); this.localRetrievalService = (RetrievalService) createConfigurationComponent( - AVKey.RETRIEVAL_SERVICE_CLASS_NAME); + AVKey.RETRIEVAL_SERVICE_CLASS_NAME); this.taskService = (TaskService) createConfigurationComponent(AVKey.TASK_SERVICE_CLASS_NAME); this.dataFileStore = (FileStore) createConfigurationComponent(AVKey.DATA_FILE_STORE_CLASS_NAME); this.memoryCacheSet = (MemoryCacheSet) createConfigurationComponent(AVKey.MEMORY_CACHE_SET_CLASS_NAME); @@ -77,20 +75,25 @@ private void initialize() IIORegistry.getDefaultInstance().registerServiceProvider(GeotiffImageReaderSpi.inst()); } - private void dispose() - { - if (this.taskService != null) + private void dispose() { + if (this.taskService != null) { this.taskService.shutdown(true); - if (this.remoteRetrievalService != null) + } + if (this.remoteRetrievalService != null) { this.remoteRetrievalService.shutdown(true); - if (this.localRetrievalService != null) + } + if (this.localRetrievalService != null) { this.localRetrievalService.shutdown(true); - if (this.memoryCacheSet != null) + } + if (this.memoryCacheSet != null) { this.memoryCacheSet.clear(); - if (this.sessionCache != null) + } + if (this.sessionCache != null) { this.sessionCache.clear(); - if (this.scheduledTaskService != null) + } + if (this.scheduledTaskService != null) { this.scheduledTaskService.shutdown(true); + } } /** @@ -105,45 +108,37 @@ private void dispose() *

    * WorldWind can continue to be used after calling this method. */ - public static synchronized void shutDown() - { + public static synchronized void shutDown() { instance.wwo.firePropertyChange(SHUTDOWN_EVENT, null, -1); instance.dispose(); instance = new WorldWind(); } - public static MemoryCacheSet getMemoryCacheSet() - { + public static MemoryCacheSet getMemoryCacheSet() { return instance.memoryCacheSet; } - public static synchronized MemoryCache getMemoryCache(String key) - { + public static synchronized MemoryCache getMemoryCache(String key) { return instance.memoryCacheSet.getCache(key); } - public static FileStore getDataFileStore() - { + public static FileStore getDataFileStore() { return instance.dataFileStore; } - public static RetrievalService getRetrievalService() - { + public static RetrievalService getRetrievalService() { return instance.remoteRetrievalService; } - public static RetrievalService getRemoteRetrievalService() - { + public static RetrievalService getRemoteRetrievalService() { return instance.remoteRetrievalService; } - public static RetrievalService getLocalRetrievalService() - { + public static RetrievalService getLocalRetrievalService() { return instance.localRetrievalService; } - public static TaskService getTaskService() - { + public static TaskService getTaskService() { return instance.taskService; } @@ -153,18 +148,15 @@ public static TaskService getTaskService() * * @return the scheduled task service. */ - public static ScheduledTaskService getScheduledTaskService() - { + public static ScheduledTaskService getScheduledTaskService() { return instance.scheduledTaskService; } - public static NetworkStatus getNetworkStatus() - { + public static NetworkStatus getNetworkStatus() { return instance.networkStatus; } - public static SessionCache getSessionCache() - { + public static SessionCache getSessionCache() { return instance.sessionCache; } @@ -175,8 +167,7 @@ public static SessionCache getSessionCache() * * @see NetworkStatus */ - public static boolean isOfflineMode() - { + public static boolean isOfflineMode() { return getNetworkStatus().isOfflineMode(); } @@ -188,8 +179,7 @@ public static boolean isOfflineMode() * * @see NetworkStatus */ - public static void setOfflineMode(boolean offlineMode) - { + public static void setOfflineMode(boolean offlineMode) { getNetworkStatus().setOfflineMode(offlineMode); } @@ -198,29 +188,22 @@ public static void setOfflineMode(boolean offlineMode) * * @return the new component * - * @throws WWRuntimeException if the Object could not be created + * @throws WWRuntimeException if the Object could not be created * @throws IllegalArgumentException if className is null or zero length */ - public static Object createComponent(String className) throws WWRuntimeException - { - if (className == null || className.length() == 0) - { + public static Object createComponent(String className) throws WWRuntimeException { + if (className == null || className.length() == 0) { Logging.logger().severe("nullValue.ClassNameIsNull"); throw new IllegalArgumentException(Logging.getMessage("nullValue.ClassNameIsNull")); } - try - { + try { Class c = Class.forName(className.trim()); return c.newInstance(); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, "WorldWind.ExceptionCreatingComponent", className); throw new WWRuntimeException(Logging.getMessage("WorldWind.ExceptionCreatingComponent", className), e); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(Level.SEVERE, "WorldWind.ErrorCreatingComponent", className); throw new WWRuntimeException(Logging.getMessage("WorldWind.ErrorCreatingComponent", className), t); } @@ -231,86 +214,70 @@ public static Object createComponent(String className) throws WWRuntimeException * * @return the new component * - * @throws IllegalStateException if no name could be found which corresponds to classNameKey + * @throws IllegalStateException if no name could be found which corresponds to classNameKey * @throws IllegalArgumentException if classNameKey is null - * @throws WWRuntimeException if the component could not be created + * @throws WWRuntimeException if the component could not be created */ public static Object createConfigurationComponent(String classNameKey) - throws IllegalStateException, IllegalArgumentException - { - if (classNameKey == null || classNameKey.length() == 0) - { + throws IllegalStateException, IllegalArgumentException { + if (classNameKey == null || classNameKey.length() == 0) { Logging.logger().severe("nullValue.ClassNameKeyNullZero"); throw new IllegalArgumentException(Logging.getMessage("nullValue.ClassNameKeyNullZero")); } String name = Configuration.getStringValue(classNameKey); - if (name == null) - { + if (name == null) { Logging.logger().log(Level.SEVERE, "WorldWind.NoClassNameInConfigurationForKey", classNameKey); throw new WWRuntimeException( - Logging.getMessage("WorldWind.NoClassNameInConfigurationForKey", classNameKey)); + Logging.getMessage("WorldWind.NoClassNameInConfigurationForKey", classNameKey)); } - try - { + try { return WorldWind.createComponent(name.trim()); - } - catch (Throwable e) - { + } catch (Throwable e) { Logging.logger().log(Level.SEVERE, "WorldWind.UnableToCreateClassForConfigurationKey", name); throw new IllegalStateException( - Logging.getMessage("WorldWind.UnableToCreateClassForConfigurationKey", name), e); + Logging.getMessage("WorldWind.UnableToCreateClassForConfigurationKey", name), e); } } - public static void setValue(String key, Object value) - { + public static void setValue(String key, Object value) { instance.wwo.setValue(key, value); } - public static void setValue(String key, String value) - { + public static void setValue(String key, String value) { instance.wwo.setValue(key, value); } - public static Object getValue(String key) - { + public static Object getValue(String key) { return instance.wwo.getValue(key); } - public static String getStringValue(String key) - { + public static String getStringValue(String key) { return instance.wwo.getStringValue(key); } - public static boolean hasKey(String key) - { + public static boolean hasKey(String key) { return instance.wwo.hasKey(key); } - public static void removeKey(String key) - { + public static void removeKey(String key) { instance.wwo.removeKey(key); } - public static void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public static void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { instance.wwo.addPropertyChangeListener(propertyName, listener); } - public static void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public static void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { instance.wwo.removePropertyChangeListener(propertyName, listener); } - public static void addPropertyChangeListener(PropertyChangeListener listener) - { + public static void addPropertyChangeListener(PropertyChangeListener listener) { instance.wwo.addPropertyChangeListener(listener); } - public static void removePropertyChangeListener(PropertyChangeListener listener) - { + public static void removePropertyChangeListener(PropertyChangeListener listener) { instance.wwo.removePropertyChangeListener(listener); } } diff --git a/src/gov/nasa/worldwind/WorldWindow.java b/src/gov/nasa/worldwind/WorldWindow.java index 809e167ece..0900398d43 100644 --- a/src/gov/nasa/worldwind/WorldWindow.java +++ b/src/gov/nasa/worldwind/WorldWindow.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.avlist.AVList; @@ -22,8 +21,8 @@ * @author Tom Gaskins * @version $Id: WorldWindow.java 2047 2014-06-06 22:48:33Z tgaskins $ */ -public interface WorldWindow extends AVList -{ +public interface WorldWindow extends AVList { + /** * Sets the model to display in this window. If null is specified for the model, the current model, if * any, is disassociated with the window. @@ -60,7 +59,7 @@ public interface WorldWindow extends AVList * view, the current view, if any, is disassociated with the window. * * @param model the model to display. May benull. - * @param view the view to use to display this window's model. May benull. + * @param view the view to use to display this window's model. May benull. */ void setModelAndView(Model model, View view); @@ -68,7 +67,7 @@ public interface WorldWindow extends AVList * Returns the scene controller associated with this instance. * * @return The scene controller associated with the instance, or null if no scene controller is - * associated. + * associated. */ SceneController getSceneController(); @@ -95,7 +94,7 @@ public interface WorldWindow extends AVList * Sets the input handler to use for this instance. * * @param inputHandler The input handler to use for this WorldWindow. May by null if null - * is specified, the current input handler, if any, is disassociated with the WorldWindow. + * is specified, the current input handler, if any, is disassociated with the WorldWindow. */ void setInputHandler(InputHandler inputHandler); @@ -152,8 +151,8 @@ public interface WorldWindow extends AVList void redraw(); /** - * Immediately repaints the WorldWindow without waiting for a window system repaint event. This is not the - * preferred way to cause a repaint, but is provided for the rare cases that require it. + * Immediately repaints the WorldWindow without waiting for a window system repaint event. This is not the preferred + * way to cause a repaint, but is provided for the rare cases that require it. */ void redrawNow(); @@ -175,9 +174,9 @@ public interface WorldWindow extends AVList PickedObjectList getObjectsAtCurrentPosition(); /** - * Returns the WorldWind objects intersecting the current selection box. The list of objects in the selection box - * is determined each time the WorldWindow is repainted. This method returns the list of objects determined when - * the most recent repaint was performed. + * Returns the WorldWind objects intersecting the current selection box. The list of objects in the selection box is + * determined each time the WorldWindow is repainted. This method returns the list of objects determined when the + * most recent repaint was performed. * * @return The list of objects intersecting the selection box, or null if no objects are in the box. */ @@ -211,8 +210,7 @@ public interface WorldWindow extends AVList Collection getPerFrameStatistics(); // TODO: move the constants from AVKey to this interface. /** - * Causes resources used by the WorldWindow to be freed. The WorldWindow cannot be used once this method is - * called. + * Causes resources used by the WorldWindow to be freed. The WorldWindow cannot be used once this method is called. */ void shutdown(); @@ -249,8 +247,8 @@ public interface WorldWindow extends AVList * Specifies whether to reinitialize the GPU resource cache when this window is reinitialized. A value of * true indicates that the GPU resource cache this window is using should be cleared when its init() * method is called, typically when re-parented. Set this to false when this window is sharing context - * with other windows and is likely to be re-parented. It prevents the flashing caused by clearing and - * re-populating the GPU resource cache during re-parenting. The default value is true. + * with other windows and is likely to be re-parented. It prevents the flashing caused by clearing and re-populating + * the GPU resource cache during re-parenting. The default value is true. * * @param enableGpuCacheReinitialization true to enable reinitialization, otherwise false. */ diff --git a/src/gov/nasa/worldwind/WorldWindowGLAutoDrawable.java b/src/gov/nasa/worldwind/WorldWindowGLAutoDrawable.java index a32ad3e5db..3f09289add 100644 --- a/src/gov/nasa/worldwind/WorldWindowGLAutoDrawable.java +++ b/src/gov/nasa/worldwind/WorldWindowGLAutoDrawable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import com.jogamp.opengl.util.texture.TextureIO; @@ -32,8 +31,8 @@ * @author Tom Gaskins * @version $Id: WorldWindowGLAutoDrawable.java 2047 2014-06-06 22:48:33Z tgaskins $ */ -public class WorldWindowGLAutoDrawable extends WorldWindowImpl implements WorldWindowGLDrawable, GLEventListener -{ +public class WorldWindowGLAutoDrawable extends WorldWindowImpl implements WorldWindowGLDrawable, GLEventListener { + /** * Default time in milliseconds that the view must remain unchanged before the {@link View#VIEW_STOPPED} message is * sent. @@ -45,7 +44,9 @@ public class WorldWindowGLAutoDrawable extends WorldWindowImpl implements WorldW private boolean shuttingDown = false; private Timer redrawTimer; private boolean firstInit = true; - /** Time in milliseconds that the view must remain unchanged before the {@link View#VIEW_STOPPED} message is sent. */ + /** + * Time in milliseconds that the view must remain unchanged before the {@link View#VIEW_STOPPED} message is sent. + */ protected long viewStopTime = DEFAULT_VIEW_STOP_TIME; /** * The most recent View modelView ID. @@ -53,27 +54,29 @@ public class WorldWindowGLAutoDrawable extends WorldWindowImpl implements WorldW * @see gov.nasa.worldwind.View#getViewStateID() */ protected long lastViewID; - /** Schedule task to send the {@link View#VIEW_STOPPED} message after the view stop time elapses. */ + /** + * Schedule task to send the {@link View#VIEW_STOPPED} message after the view stop time elapses. + */ protected ScheduledFuture viewRefreshTask; protected boolean enableGpuCacheReinitialization = true; - /** Construct a new WorldWindowGLCanvas for a specified {@link GLDrawable}. */ - public WorldWindowGLAutoDrawable() - { + /** + * Construct a new WorldWindowGLCanvas for a specified {@link GLDrawable}. + */ + public WorldWindowGLAutoDrawable() { SceneController sc = this.getSceneController(); - if (sc != null) + if (sc != null) { sc.addPropertyChangeListener(this); + } } /** * Indicates the amount of time, in milliseconds, that the View must remain unchanged before a {@link * View#VIEW_STOPPED} event is triggered. * - * @return Time in milliseconds that the View must must remain unchanged before the view stopped event is - * triggered. + * @return Time in milliseconds that the View must must remain unchanged before the view stopped event is triggered. */ - public long getViewStopTime() - { + public long getViewStopTime() { return this.viewStopTime; } @@ -82,17 +85,14 @@ public long getViewStopTime() * View#VIEW_STOPPED} event is triggered. * * @param time Time in milliseconds that the View must must remain unchanged before the view stopped event is - * triggered. + * triggered. */ - public void setViewStopTime(long time) - { + public void setViewStopTime(long time) { this.viewStopTime = time; } - public void initDrawable(GLAutoDrawable glAutoDrawable) - { - if (glAutoDrawable == null) - { + public void initDrawable(GLAutoDrawable glAutoDrawable) { + if (glAutoDrawable == null) { String msg = Logging.getMessage("nullValue.DrawableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -104,21 +104,17 @@ public void initDrawable(GLAutoDrawable glAutoDrawable) } @Override - public boolean isEnableGpuCacheReinitialization() - { + public boolean isEnableGpuCacheReinitialization() { return enableGpuCacheReinitialization; } @Override - public void setEnableGpuCacheReinitialization(boolean enableGpuCacheReinitialization) - { + public void setEnableGpuCacheReinitialization(boolean enableGpuCacheReinitialization) { this.enableGpuCacheReinitialization = enableGpuCacheReinitialization; } - public void initGpuResourceCache(GpuResourceCache cache) - { - if (cache == null) - { + public void initGpuResourceCache(GpuResourceCache cache) { + if (cache == null) { String msg = Logging.getMessage("nullValue.GpuResourceCacheIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -127,40 +123,36 @@ public void initGpuResourceCache(GpuResourceCache cache) this.setGpuResourceCache(cache); } - public void endInitialization() - { + public void endInitialization() { initializeCreditsController(); this.dashboard = new DashboardController(this, (Component) this.drawable); } - protected void initializeCreditsController() - { + protected void initializeCreditsController() { new ScreenCreditController((WorldWindow) this.drawable); } @Override - public void shutdown() - { + public void shutdown() { this.shuttingDown = true; this.redrawNow(); // Invokes a repaint, where the rest of the shutdown work is done. } - protected void doShutdown() - { + protected void doShutdown() { super.shutdown(); this.drawable.removeGLEventListener(this); - if (this.dashboard != null) + if (this.dashboard != null) { this.dashboard.dispose(); - if (this.viewRefreshTask != null) + } + if (this.viewRefreshTask != null) { this.viewRefreshTask.cancel(false); + } this.shuttingDown = false; } @Override - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent == null) - { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + if (propertyChangeEvent == null) { String msg = Logging.getMessage("nullValue.PropertyChangeEventIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -169,24 +161,20 @@ public void propertyChange(PropertyChangeEvent propertyChangeEvent) this.redraw(); // Queue a JOGL display request. } - public GLContext getContext() - { + public GLContext getContext() { return this.drawable.getContext(); } - protected boolean isGLContextCompatible(GLContext context) - { + protected boolean isGLContextCompatible(GLContext context) { return context != null && context.isGL2(); } - protected String[] getRequiredOglFunctions() - { - return new String[] {"glActiveTexture", "glClientActiveTexture"}; + protected String[] getRequiredOglFunctions() { + return new String[]{"glActiveTexture", "glClientActiveTexture"}; } - protected String[] getRequiredOglExtensions() - { - return new String[] {}; + protected String[] getRequiredOglExtensions() { + return new String[]{}; } /** @@ -194,37 +182,32 @@ protected String[] getRequiredOglExtensions() * * @param glAutoDrawable the drawable */ - public void init(GLAutoDrawable glAutoDrawable) - { - if (!this.isGLContextCompatible(glAutoDrawable.getContext())) - { + public void init(GLAutoDrawable glAutoDrawable) { + if (!this.isGLContextCompatible(glAutoDrawable.getContext())) { String msg = Logging.getMessage("WorldWindowGLAutoDrawable.IncompatibleGLContext", - glAutoDrawable.getContext()); + glAutoDrawable.getContext()); this.callRenderingExceptionListeners(new WWAbsentRequirementException(msg)); } - for (String funcName : this.getRequiredOglFunctions()) - { - if (!glAutoDrawable.getGL().isFunctionAvailable(funcName)) - { + for (String funcName : this.getRequiredOglFunctions()) { + if (!glAutoDrawable.getGL().isFunctionAvailable(funcName)) { //noinspection ThrowableInstanceNeverThrown this.callRenderingExceptionListeners(new WWAbsentRequirementException(funcName + " not available")); } } - for (String extName : this.getRequiredOglExtensions()) - { - if (!glAutoDrawable.getGL().isExtensionAvailable(extName)) - { + for (String extName : this.getRequiredOglExtensions()) { + if (!glAutoDrawable.getGL().isExtensionAvailable(extName)) { //noinspection ThrowableInstanceNeverThrown this.callRenderingExceptionListeners(new WWAbsentRequirementException(extName + " not available")); } } - if (this.firstInit) + if (this.firstInit) { this.firstInit = false; - else if (this.enableGpuCacheReinitialization) + } else if (this.enableGpuCacheReinitialization) { this.reinitialize(glAutoDrawable); + } // Disables use of the OpenGL extension GL_ARB_texture_rectangle by JOGL's Texture creation utility. // @@ -244,11 +227,11 @@ else if (this.enableGpuCacheReinitialization) } @SuppressWarnings({"UnusedParameters"}) - protected void reinitialize(GLAutoDrawable glAutoDrawable) - { + protected void reinitialize(GLAutoDrawable glAutoDrawable) { // Clear the gpu resource cache if the window is reinitializing, most likely with a new gl hardware context. - if (this.getGpuResourceCache() != null) + if (this.getGpuResourceCache() != null) { this.getGpuResourceCache().clear(); + } this.getSceneController().reinitialize(); } @@ -271,8 +254,7 @@ protected void reinitialize(GLAutoDrawable glAutoDrawable) * @param glAutoDrawable the drawable */ @Override - public void dispose(GLAutoDrawable glAutoDrawable) - { + public void dispose(GLAutoDrawable glAutoDrawable) { } /** @@ -282,28 +264,21 @@ public void dispose(GLAutoDrawable glAutoDrawable) * * @throws IllegalStateException if no {@link SceneController} exists for this canvas */ - public void display(GLAutoDrawable glAutoDrawable) - { + public void display(GLAutoDrawable glAutoDrawable) { // Performing shutdown here in order to do so with a current GL context for GL resource disposal. - if (this.shuttingDown) - { - try - { + if (this.shuttingDown) { + try { this.doShutdown(); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, Logging.getMessage( - "WorldWindowGLCanvas.ExceptionWhileShuttingDownWorldWindow"), e); + "WorldWindowGLCanvas.ExceptionWhileShuttingDownWorldWindow"), e); } return; } - try - { + try { SceneController sc = this.getSceneController(); - if (sc == null) - { + if (sc == null) { String msg = Logging.getMessage("WorldWindowGLCanvas.ScnCntrllerNullOnRepaint"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -316,25 +291,18 @@ public void display(GLAutoDrawable glAutoDrawable) PickedObject selectionAtStart = this.getCurrentSelection(); PickedObjectList boxSelectionAtStart = this.getCurrentBoxSelection(); - try - { + try { this.callRenderingListeners(new RenderingEvent(this.drawable, RenderingEvent.BEFORE_RENDERING)); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, - Logging.getMessage("WorldWindowGLAutoDrawable.ExceptionDuringGLEventListenerDisplay"), e); + Logging.getMessage("WorldWindowGLAutoDrawable.ExceptionDuringGLEventListenerDisplay"), e); } int redrawDelay = this.doDisplay(); - if (redrawDelay > 0) - { - if (this.redrawTimer == null) - { - this.redrawTimer = new Timer(redrawDelay, new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + if (redrawDelay > 0) { + if (this.redrawTimer == null) { + this.redrawTimer = new Timer(redrawDelay, new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { redraw(); redrawTimer = null; } @@ -344,35 +312,33 @@ public void actionPerformed(ActionEvent actionEvent) } } - try - { + try { this.callRenderingListeners(new RenderingEvent(this.drawable, RenderingEvent.BEFORE_BUFFER_SWAP)); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, - Logging.getMessage("WorldWindowGLAutoDrawable.ExceptionDuringGLEventListenerDisplay"), e); + Logging.getMessage("WorldWindowGLAutoDrawable.ExceptionDuringGLEventListenerDisplay"), e); } this.doSwapBuffers(this.drawable); Double frameTime = sc.getFrameTime(); - if (frameTime != null) + if (frameTime != null) { this.setValue(PerformanceStatistic.FRAME_TIME, frameTime); + } Double frameRate = sc.getFramesPerSecond(); - if (frameRate != null) + if (frameRate != null) { this.setValue(PerformanceStatistic.FRAME_RATE, frameRate); + } // Dispatch the rendering exceptions accumulated by the SceneController during this frame to our // RenderingExceptionListeners. Iterable renderingExceptions = sc.getRenderingExceptions(); - if (renderingExceptions != null) - { - for (Throwable t : renderingExceptions) - { - if (t != null) + if (renderingExceptions != null) { + for (Throwable t : renderingExceptions) { + if (t != null) { this.callRenderingExceptionListeners(t); + } } } @@ -384,59 +350,48 @@ public void actionPerformed(ActionEvent actionEvent) // start != null, end == null: something was selected but no longer is -- notify // start != null, end != null, start != end: something new was selected -- notify // start != null, end != null, start == end: same thing is selected -- don't notify - Position positionAtEnd = this.getCurrentPosition(); - if (positionAtStart != null || positionAtEnd != null) - { + if (positionAtStart != null || positionAtEnd != null) { // call the listener if both are not null or positions are the same - if (positionAtStart != null && positionAtEnd != null) - { - if (!positionAtStart.equals(positionAtEnd)) + if (positionAtStart != null && positionAtEnd != null) { + if (!positionAtStart.equals(positionAtEnd)) { this.callPositionListeners(new PositionEvent(this.drawable, sc.getPickPoint(), - positionAtStart, positionAtEnd)); - } - else - { + positionAtStart, positionAtEnd)); + } + } else { this.callPositionListeners(new PositionEvent(this.drawable, sc.getPickPoint(), - positionAtStart, positionAtEnd)); + positionAtStart, positionAtEnd)); } } PickedObject selectionAtEnd = this.getCurrentSelection(); - if (selectionAtStart != null || selectionAtEnd != null) - { + if (selectionAtStart != null || selectionAtEnd != null) { this.callSelectListeners(new SelectEvent(this.drawable, SelectEvent.ROLLOVER, - sc.getPickPoint(), sc.getPickedObjectList())); + sc.getPickPoint(), sc.getPickedObjectList())); } PickedObjectList boxSelectionAtEnd = this.getCurrentBoxSelection(); - if (boxSelectionAtStart != null || boxSelectionAtEnd != null) - { + if (boxSelectionAtStart != null || boxSelectionAtEnd != null) { this.callSelectListeners(new SelectEvent(this.drawable, SelectEvent.BOX_ROLLOVER, - sc.getPickRectangle(), sc.getObjectsInPickRectangle())); + sc.getPickRectangle(), sc.getObjectsInPickRectangle())); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, Logging.getMessage( - "WorldWindowGLCanvas.ExceptionAttemptingRepaintWorldWindow"), e); + "WorldWindowGLCanvas.ExceptionAttemptingRepaintWorldWindow"), e); } } /** * Determine if the view has changed since the previous frame. If the view has changed, schedule a task that will - * send a {@link View#VIEW_STOPPED} to the Model if the view does not change for {@link #viewStopTime} - * milliseconds. + * send a {@link View#VIEW_STOPPED} to the Model if the view does not change for {@link #viewStopTime} milliseconds. * * @see #getViewStopTime() */ - protected void checkForViewChange() - { + protected void checkForViewChange() { long viewId = this.getView().getViewStateID(); // Determine if the view has changed since the previous frame. - if (viewId != this.lastViewID) - { + if (viewId != this.lastViewID) { // View has changed, capture the new viewStateID this.lastViewID = viewId; @@ -449,10 +404,9 @@ protected void checkForViewChange() * Performs the actual repaint. Provided so that subclasses may override the repaint steps. * * @return if greater than zero, the window should be automatically repainted again at the indicated number of - * milliseconds from this method's return. + * milliseconds from this method's return. */ - protected int doDisplay() - { + protected int doDisplay() { return this.getSceneController().repaint(); } @@ -461,8 +415,7 @@ protected int doDisplay() * * @param drawable the window's associated drawable. */ - protected void doSwapBuffers(GLAutoDrawable drawable) - { + protected void doSwapBuffers(GLAutoDrawable drawable) { drawable.swapBuffers(); } @@ -471,23 +424,22 @@ protected void doSwapBuffers(GLAutoDrawable drawable) * * @param glAutoDrawable the drawable */ - public void reshape(GLAutoDrawable glAutoDrawable, int x, int y, int w, int h) - { + public void reshape(GLAutoDrawable glAutoDrawable, int x, int y, int w, int h) { // This is apparently necessary to enable the WWJ canvas to resize correctly with JSplitPane. ((Component) glAutoDrawable).setMinimumSize(new Dimension(0, 0)); } @Override - public void redraw() - { - if (this.drawable != null) + public void redraw() { + if (this.drawable != null) { ((AWTGLAutoDrawable) this.drawable).repaint(); + } } - public void redrawNow() - { - if (this.drawable != null) + public void redrawNow() { + if (this.drawable != null) { this.drawable.display(); + } } /** @@ -498,33 +450,27 @@ public void redrawNow() * * @param delay Delay in milliseconds until the task runs. */ - protected void scheduleViewStopTask(long delay) - { - Runnable viewStoppedTask = new Runnable() - { - public void run() - { + protected void scheduleViewStopTask(long delay) { + Runnable viewStoppedTask = new Runnable() { + public void run() { // Call onMessage on the EDT with a VIEW_STOP message - EventQueue.invokeLater(new Runnable() - { - public void run() - { + EventQueue.invokeLater(new Runnable() { + public void run() { WorldWindowGLAutoDrawable.this.onMessage( - new Message(View.VIEW_STOPPED, WorldWindowGLAutoDrawable.this)); + new Message(View.VIEW_STOPPED, WorldWindowGLAutoDrawable.this)); } }); } }; // Cancel the previous view stop task - if (this.viewRefreshTask != null) - { + if (this.viewRefreshTask != null) { this.viewRefreshTask.cancel(false); } // Schedule the task for execution in delay milliseconds this.viewRefreshTask = WorldWind.getScheduledTaskService() - .addScheduledTask(viewStoppedTask, delay, TimeUnit.MILLISECONDS); + .addScheduledTask(viewStoppedTask, delay, TimeUnit.MILLISECONDS); } /** @@ -535,11 +481,9 @@ public void run() * @param msg Message event. */ @Override - public void onMessage(Message msg) - { + public void onMessage(Message msg) { Model model = this.getModel(); - if (model != null) - { + if (model != null) { model.onMessage(msg); } } diff --git a/src/gov/nasa/worldwind/WorldWindowGLDrawable.java b/src/gov/nasa/worldwind/WorldWindowGLDrawable.java index a8105cf6ca..d94ad72269 100644 --- a/src/gov/nasa/worldwind/WorldWindowGLDrawable.java +++ b/src/gov/nasa/worldwind/WorldWindowGLDrawable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import gov.nasa.worldwind.cache.*; @@ -14,8 +13,8 @@ * @author tag * @version $Id: WorldWindowGLDrawable.java 1855 2014-02-28 23:01:02Z tgaskins $ */ -public interface WorldWindowGLDrawable extends WorldWindow -{ +public interface WorldWindowGLDrawable extends WorldWindow { + void initDrawable(GLAutoDrawable glAutoDrawable); void initGpuResourceCache(GpuResourceCache cache); diff --git a/src/gov/nasa/worldwind/WorldWindowImpl.java b/src/gov/nasa/worldwind/WorldWindowImpl.java index c73a0fa52c..25d6d5b558 100644 --- a/src/gov/nasa/worldwind/WorldWindowImpl.java +++ b/src/gov/nasa/worldwind/WorldWindowImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind; import com.jogamp.nativewindow.ScalableSurface; @@ -26,286 +25,247 @@ * @author Tom Gaskins * @version $Id: WorldWindowImpl.java 1855 2014-02-28 23:01:02Z tgaskins $ */ -public abstract class WorldWindowImpl extends WWObjectImpl implements WorldWindow -{ +public abstract class WorldWindowImpl extends WWObjectImpl implements WorldWindow { + private SceneController sceneController; private final EventListenerList eventListeners = new EventListenerList(); private InputHandler inputHandler; protected GpuResourceCache gpuResourceCache; - public WorldWindowImpl() - { + public WorldWindowImpl() { this.sceneController = (SceneController) WorldWind.createConfigurationComponent( - AVKey.SCENE_CONTROLLER_CLASS_NAME); + AVKey.SCENE_CONTROLLER_CLASS_NAME); // Set up to initiate a repaint whenever a file is retrieved and added to the local file store. WorldWind.getDataFileStore().addPropertyChangeListener(this); } /** - * Causes resources used by the WorldWindow to be freed. The WorldWindow cannot be used once this method is - * called. An OpenGL context for the window must be current. + * Causes resources used by the WorldWindow to be freed. The WorldWindow cannot be used once this method is called. + * An OpenGL context for the window must be current. */ - public void shutdown() - { + public void shutdown() { WorldWind.getDataFileStore().removePropertyChangeListener(this); - if (this.inputHandler != null) - { + if (this.inputHandler != null) { this.inputHandler.dispose(); this.inputHandler = new NoOpInputHandler(); } // Clear the texture cache - if (this.getGpuResourceCache() != null) + if (this.getGpuResourceCache() != null) { this.getGpuResourceCache().clear(); + } // Dispose all the layers // TODO: Need per-window dispose for layers - if (this.getModel() != null && this.getModel().getLayers() != null) - { - for (Layer layer : this.getModel().getLayers()) - { - try - { + if (this.getModel() != null && this.getModel().getLayers() != null) { + for (Layer layer : this.getModel().getLayers()) { + try { layer.dispose(); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.SEVERE, Logging.getMessage( - "WorldWindowGLCanvas.ExceptionWhileShuttingDownWorldWindow"), e); + "WorldWindowGLCanvas.ExceptionWhileShuttingDownWorldWindow"), e); } } } SceneController sc = this.getSceneController(); - if (sc != null) + if (sc != null) { sc.dispose(); + } } - public GpuResourceCache getGpuResourceCache() - { + public GpuResourceCache getGpuResourceCache() { return this.gpuResourceCache; } - public void setGpuResourceCache(GpuResourceCache gpuResourceCache) - { + public void setGpuResourceCache(GpuResourceCache gpuResourceCache) { this.gpuResourceCache = gpuResourceCache; this.sceneController.setGpuResourceCache(this.gpuResourceCache); } - public void setModel(Model model) - { + public void setModel(Model model) { // model can be null, that's ok - it indicates no model. - if (this.sceneController != null) + if (this.sceneController != null) { this.sceneController.setModel(model); + } } - public Model getModel() - { + public Model getModel() { return this.sceneController != null ? this.sceneController.getModel() : null; } - public void setView(View view) - { + public void setView(View view) { // view can be null, that's ok - it indicates no view. - if (this.sceneController != null) + if (this.sceneController != null) { this.sceneController.setView(view); + } } - public View getView() - { + public View getView() { return this.sceneController != null ? this.sceneController.getView() : null; } - public void setModelAndView(Model model, View view) - { + public void setModelAndView(Model model, View view) { this.setModel(model); this.setView(view); } - public SceneController getSceneController() - { + public SceneController getSceneController() { return this.sceneController; } - public void setSceneController(SceneController sc) - { - if (sc != null && this.getSceneController() != null) - { + public void setSceneController(SceneController sc) { + if (sc != null && this.getSceneController() != null) { sc.setGpuResourceCache(this.sceneController.getGpuResourceCache()); } this.sceneController = sc; } - public InputHandler getInputHandler() - { + public InputHandler getInputHandler() { return this.inputHandler; } - public void setInputHandler(InputHandler inputHandler) - { + public void setInputHandler(InputHandler inputHandler) { this.inputHandler = inputHandler; } - public void redraw() - { + public void redraw() { } - public void redrawNow() - { + public void redrawNow() { } - public void setPerFrameStatisticsKeys(Set keys) - { - if (this.sceneController != null) + public void setPerFrameStatisticsKeys(Set keys) { + if (this.sceneController != null) { this.sceneController.setPerFrameStatisticsKeys(keys); + } } - public Collection getPerFrameStatistics() - { - if (this.sceneController == null || this.sceneController.getPerFrameStatistics() == null) + public Collection getPerFrameStatistics() { + if (this.sceneController == null || this.sceneController.getPerFrameStatistics() == null) { return new ArrayList(0); + } return this.sceneController.getPerFrameStatistics(); } - public PickedObjectList getObjectsAtCurrentPosition() - { + public PickedObjectList getObjectsAtCurrentPosition() { return null; } - public PickedObjectList getObjectsInSelectionBox() - { + public PickedObjectList getObjectsInSelectionBox() { return null; } - public Position getCurrentPosition() - { - if (this.sceneController == null) + public Position getCurrentPosition() { + if (this.sceneController == null) { return null; + } PickedObjectList pol = this.getSceneController().getPickedObjectList(); - if (pol == null || pol.size() < 1) + if (pol == null || pol.size() < 1) { return null; + } Position p = null; PickedObject top = pol.getTopPickedObject(); - if (top != null && top.hasPosition()) + if (top != null && top.hasPosition()) { p = top.getPosition(); - else if (pol.getTerrainObject() != null) + } else if (pol.getTerrainObject() != null) { p = pol.getTerrainObject().getPosition(); + } return p; } - protected PickedObject getCurrentSelection() - { - if (this.sceneController == null) + protected PickedObject getCurrentSelection() { + if (this.sceneController == null) { return null; + } PickedObjectList pol = this.getSceneController().getPickedObjectList(); - if (pol == null || pol.size() < 1) + if (pol == null || pol.size() < 1) { return null; + } PickedObject top = pol.getTopPickedObject(); return top.isTerrain() ? null : top; } - protected PickedObjectList getCurrentBoxSelection() - { - if (this.sceneController == null) + protected PickedObjectList getCurrentBoxSelection() { + if (this.sceneController == null) { return null; + } PickedObjectList pol = this.sceneController.getObjectsInPickRectangle(); return pol != null && pol.size() > 0 ? pol : null; } - public void addRenderingListener(RenderingListener listener) - { + public void addRenderingListener(RenderingListener listener) { this.eventListeners.add(RenderingListener.class, listener); } - public void removeRenderingListener(RenderingListener listener) - { + public void removeRenderingListener(RenderingListener listener) { this.eventListeners.remove(RenderingListener.class, listener); } - protected void callRenderingListeners(RenderingEvent event) - { - for (RenderingListener listener : this.eventListeners.getListeners(RenderingListener.class)) - { + protected void callRenderingListeners(RenderingEvent event) { + for (RenderingListener listener : this.eventListeners.getListeners(RenderingListener.class)) { listener.stageChanged(event); } } - public void addPositionListener(PositionListener listener) - { + public void addPositionListener(PositionListener listener) { this.eventListeners.add(PositionListener.class, listener); } - public void removePositionListener(PositionListener listener) - { + public void removePositionListener(PositionListener listener) { this.eventListeners.remove(PositionListener.class, listener); } - protected void callPositionListeners(final PositionEvent event) - { - EventQueue.invokeLater(new Runnable() - { - public void run() - { - for (PositionListener listener : eventListeners.getListeners(PositionListener.class)) - { + protected void callPositionListeners(final PositionEvent event) { + EventQueue.invokeLater(new Runnable() { + public void run() { + for (PositionListener listener : eventListeners.getListeners(PositionListener.class)) { listener.moved(event); } } }); } - public void addSelectListener(SelectListener listener) - { + public void addSelectListener(SelectListener listener) { this.eventListeners.add(SelectListener.class, listener); } - public void removeSelectListener(SelectListener listener) - { + public void removeSelectListener(SelectListener listener) { this.eventListeners.remove(SelectListener.class, listener); } - protected void callSelectListeners(final SelectEvent event) - { - EventQueue.invokeLater(new Runnable() - { - public void run() - { - for (SelectListener listener : eventListeners.getListeners(SelectListener.class)) - { + protected void callSelectListeners(final SelectEvent event) { + EventQueue.invokeLater(new Runnable() { + public void run() { + for (SelectListener listener : eventListeners.getListeners(SelectListener.class)) { listener.selected(event); } } }); } - public void addRenderingExceptionListener(RenderingExceptionListener listener) - { + public void addRenderingExceptionListener(RenderingExceptionListener listener) { this.eventListeners.add(RenderingExceptionListener.class, listener); } - public void removeRenderingExceptionListener(RenderingExceptionListener listener) - { + public void removeRenderingExceptionListener(RenderingExceptionListener listener) { this.eventListeners.remove(RenderingExceptionListener.class, listener); } - protected void callRenderingExceptionListeners(final Throwable exception) - { - EventQueue.invokeLater(new Runnable() - { - public void run() - { + protected void callRenderingExceptionListeners(final Throwable exception) { + EventQueue.invokeLater(new Runnable() { + public void run() { for (RenderingExceptionListener listener : eventListeners.getListeners( - RenderingExceptionListener.class)) - { + RenderingExceptionListener.class)) { listener.exceptionThrown(exception); } } @@ -314,37 +274,31 @@ public void run() private static final long FALLBACK_TEXTURE_CACHE_SIZE = 60000000; - public static GpuResourceCache createGpuResourceCache() - { + public static GpuResourceCache createGpuResourceCache() { long cacheSize = Configuration.getLongValue(AVKey.TEXTURE_CACHE_SIZE, FALLBACK_TEXTURE_CACHE_SIZE); return new BasicGpuResourceCache((long) (0.8 * cacheSize), cacheSize); } /** - * Configures JOGL's surface pixel scaling on the specified - * ScalableSurface to ensure backward compatibility with - * WorldWind applications developed prior to JOGL pixel scaling's - * introduction.This method is used by GLCanvas and - * GLJPanel to effectively disable JOGL's surface pixel scaling - * by requesting a 1:1 scale.

    - * Since v2.2.0, JOGL defaults to using high-dpi pixel scales where - * possible. This causes WorldWind screen elements such as placemarks, the - * compass, the world map, the view controls, and the scale bar (plus many - * more) to appear smaller than they are intended to on screen. The high-dpi - * default also has the effect of degrading WorldWind rendering performance. + * Configures JOGL's surface pixel scaling on the specified ScalableSurface to ensure backward + * compatibility with WorldWind applications developed prior to JOGL pixel scaling's introduction.This method is + * used by GLCanvas and GLJPanel to effectively disable JOGL's surface pixel scaling by + * requesting a 1:1 scale.

    + * Since v2.2.0, JOGL defaults to using high-dpi pixel scales where possible. This causes WorldWind screen elements + * such as placemarks, the compass, the world map, the view controls, and the scale bar (plus many more) to appear + * smaller than they are intended to on screen. The high-dpi default also has the effect of degrading WorldWind + * rendering performance. * * @param surface The surface to configure. */ - public static void configureIdentityPixelScale(ScalableSurface surface) - { - if (surface == null) - { + public static void configureIdentityPixelScale(ScalableSurface surface) { + if (surface == null) { String message = Logging.getMessage("nullValue.SurfaceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - float[] identityScale = new float[] {ScalableSurface.IDENTITY_PIXELSCALE, ScalableSurface.IDENTITY_PIXELSCALE}; + float[] identityScale = new float[]{ScalableSurface.IDENTITY_PIXELSCALE, ScalableSurface.IDENTITY_PIXELSCALE}; surface.setSurfaceScale(identityScale); } } diff --git a/src/gov/nasa/worldwind/animation/AngleAnimator.java b/src/gov/nasa/worldwind/animation/AngleAnimator.java index 3125354726..0f55c1566a 100644 --- a/src/gov/nasa/worldwind/animation/AngleAnimator.java +++ b/src/gov/nasa/worldwind/animation/AngleAnimator.java @@ -12,13 +12,11 @@ * @author jym * @version $Id: AngleAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ - /** - * Animates angles, via an interpolator. {@link #begin} and {@link #end} values can be reset - * once the animation is already in motion. + * Animates angles, via an interpolator. {@link #begin} and {@link #end} values can be reset once the animation is + * already in motion. */ -public class AngleAnimator extends BasicAnimator -{ +public class AngleAnimator extends BasicAnimator { /** * The angle the animation begins at. @@ -29,8 +27,7 @@ public class AngleAnimator extends BasicAnimator */ protected Angle end; /** - * The @link gov.nasa.worldwind.util.PropertyAccessor used to modify - * the data value being animated. + * The @link gov.nasa.worldwind.util.PropertyAccessor used to modify the data value being animated. */ protected final PropertyAccessor.AngleAccessor propertyAccessor; @@ -40,34 +37,30 @@ public class AngleAnimator extends BasicAnimator * @param interpolator the {@link gov.nasa.worldwind.animation.Interpolator} * @param begin angle the animation begins at * @param end The angle the animation ends at. - * @param propertyAccessor The {@link gov.nasa.worldwind.util.PropertyAccessor} used to modify - * the data value being animated. + * @param propertyAccessor The {@link gov.nasa.worldwind.util.PropertyAccessor} used to modify the data value being + * animated. */ public AngleAnimator(Interpolator interpolator, - Angle begin, Angle end, - PropertyAccessor.AngleAccessor propertyAccessor) - { - super(interpolator); - if (interpolator == null) - { - this.interpolator = new ScheduledInterpolator(10000); - } - if (begin == null || end == null) - { - String message = Logging.getMessage("nullValue.AngleIsNull"); - Logging.logger().severe(message); - throw new IllegalArgumentException(message); - } - if (propertyAccessor == null) - { - String message = Logging.getMessage("nullValue.ViewPropertyAccessorIsNull"); - Logging.logger().severe(message); - throw new IllegalArgumentException(message); - } + Angle begin, Angle end, + PropertyAccessor.AngleAccessor propertyAccessor) { + super(interpolator); + if (interpolator == null) { + this.interpolator = new ScheduledInterpolator(10000); + } + if (begin == null || end == null) { + String message = Logging.getMessage("nullValue.AngleIsNull"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } + if (propertyAccessor == null) { + String message = Logging.getMessage("nullValue.ViewPropertyAccessorIsNull"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } - this.begin = begin; - this.end = end; - this.propertyAccessor = propertyAccessor; + this.begin = begin; + this.end = end; + this.propertyAccessor = propertyAccessor; } /** @@ -75,8 +68,7 @@ public AngleAnimator(Interpolator interpolator, * * @param begin the new {@link #begin} value. */ - public void setBegin(Angle begin) - { + public void setBegin(Angle begin) { this.begin = begin; } @@ -85,8 +77,7 @@ public void setBegin(Angle begin) * * @param end the new {@link #end} value. */ - public void setEnd(Angle end) - { + public void setEnd(Angle end) { this.end = end; } @@ -95,9 +86,8 @@ public void setEnd(Angle end) * * @return the current {@link #begin} value. */ - public Angle getBegin() - { - return this.begin; + public Angle getBegin() { + return this.begin; } /** @@ -105,52 +95,48 @@ public Angle getBegin() * * @return the current {@link #end} value. */ - public Angle getEnd() - { - return this.end; + public Angle getEnd() { + return this.end; } /** * Get the {@link gov.nasa.worldwind.util.PropertyAccessor} in use by this animation - * + * * @return the {@link gov.nasa.worldwind.util.PropertyAccessor} in use by this animation */ - public PropertyAccessor.AngleAccessor getPropertyAccessor() - { - return this.propertyAccessor; + public PropertyAccessor.AngleAccessor getPropertyAccessor() { + return this.propertyAccessor; } /** - * Set the value being animated via the {@link gov.nasa.worldwind.util.PropertyAccessor} - * using the passed interpolant. This implementation just does a straight liner interpolation - * between the {@link #begin} and {@link #end} values. + * Set the value being animated via the {@link gov.nasa.worldwind.util.PropertyAccessor} using the passed + * interpolant. This implementation just does a straight liner interpolation between the {@link #begin} and + * {@link #end} values. * * @param interpolant the interpolant used to generate the next value that will be set by the * {@link gov.nasa.worldwind.util.PropertyAccessor} */ - protected void setImpl(double interpolant) - { + protected void setImpl(double interpolant) { Angle newValue = this.nextAngle(interpolant); - if (newValue == null) - return; + if (newValue == null) { + return; + } boolean success = this.propertyAccessor.setAngle(newValue); - if (!success) - { - flagLastStateInvalid(); + if (!success) { + flagLastStateInvalid(); } - if (interpolant >= 1) + if (interpolant >= 1) { this.stop(); + } } @SuppressWarnings({"UnusedDeclaration"}) - private Angle nextAngle(double interpolant) - { + private Angle nextAngle(double interpolant) { - return Angle.mix( - interpolant, - this.begin, - this.end); + return Angle.mix( + interpolant, + this.begin, + this.end); - } } diff --git a/src/gov/nasa/worldwind/animation/AnimationController.java b/src/gov/nasa/worldwind/animation/AnimationController.java index 5eef377394..4cc4dc5e2f 100644 --- a/src/gov/nasa/worldwind/animation/AnimationController.java +++ b/src/gov/nasa/worldwind/animation/AnimationController.java @@ -8,24 +8,20 @@ import java.util.*; /** - * The AnimationController class is a convenience class for managing a - * group of Animators. + * The AnimationController class is a convenience class for managing a group of Animators. * * @author jym * @version $Id: AnimationController.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class AnimationController extends - HashMap -{ + HashMap { /** * Starts all of the Animators in the map */ - public void startAnimations() - { + public void startAnimations() { Collection animators = this.values(); - for (Animator a : animators) - { + for (Animator a : animators) { a.start(); } } @@ -33,11 +29,9 @@ public void startAnimations() /** * Stops all of the Animators in the map */ - public void stopAnimations() - { + public void stopAnimations() { Collection animators = this.values(); - for (Animator a : animators) - { + for (Animator a : animators) { a.stop(); } @@ -48,32 +42,29 @@ public void stopAnimations() * * @param animationName the name of the animation to be started. */ - public void startAnimation(Object animationName) - { + public void startAnimation(Object animationName) { this.get(animationName).start(); } /** * Stops the Animator associated with animationName + * * @param animationName the name of the animation to be stopped */ - public void stopAnimation(Object animationName) - { + public void stopAnimation(Object animationName) { this.get(animationName).stop(); } /** * Stops all Animators in the map. + * * @return true if any Animator was started, false otherwise */ - public boolean stepAnimators() - { + public boolean stepAnimators() { boolean didStep = false; Collection animators = this.values(); - for (Animator a : animators) - { - if (a.hasNext()) - { + for (Animator a : animators) { + if (a.hasNext()) { didStep = true; a.next(); } @@ -84,22 +75,18 @@ public boolean stepAnimators() /** * Returns true if the controller has any active Animations - * + * * @return true if there are any active animations in this CompountAnimation */ - public boolean hasActiveAnimation() - { + public boolean hasActiveAnimation() { Collection animators = this.values(); - for (Animator a : animators) - { - if (a.hasNext()) - { + for (Animator a : animators) { + if (a.hasNext()) { return true; } } return false; } - } diff --git a/src/gov/nasa/worldwind/animation/AnimationSupport.java b/src/gov/nasa/worldwind/animation/AnimationSupport.java index aa65d2a9d8..56f661c093 100644 --- a/src/gov/nasa/worldwind/animation/AnimationSupport.java +++ b/src/gov/nasa/worldwind/animation/AnimationSupport.java @@ -12,13 +12,12 @@ * @author jym * @version $Id: AnimationSupport.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AnimationSupport -{ +public class AnimationSupport { /** - * Calcualte a scaled time based on the great circle distance between two points. The time is calulated by - * interpolating between the minLengthMillis and the maxLengthMillis using the ratio - * of the spherical distance between the given positions over 180 degrees. + * Calcualte a scaled time based on the great circle distance between two points. The time is calulated by + * interpolating between the minLengthMillis and the maxLengthMillis using the ratio of + * the spherical distance between the given positions over 180 degrees. * * @param beginLatLon The first geographic position * @param endLatLon The second geographio position @@ -28,8 +27,7 @@ public class AnimationSupport */ public static long getScaledTimeMillisecs( LatLon beginLatLon, LatLon endLatLon, - long minTimeMillis, long maxTimeMillis) - { + long minTimeMillis, long maxTimeMillis) { Angle sphericalDistance = LatLon.greatCircleDistance(beginLatLon, endLatLon); double scaleFactor = angularRatio(sphericalDistance, Angle.POS180); return (long) mixDouble(scaleFactor, minTimeMillis, maxTimeMillis); @@ -47,9 +45,8 @@ public static long getScaledTimeMillisecs( * @return the scaled time in milliseconds */ public static long getScaledTimeMillisecs( - Angle begin, Angle end, Angle max, - long minTimeMillisecs, long maxTimeMillisecs) - { + Angle begin, Angle end, Angle max, + long minTimeMillisecs, long maxTimeMillisecs) { Angle angularDistance = begin.angularDistanceTo(end); double scaleFactor = angularRatio(angularDistance, max); return (long) mixDouble(scaleFactor, minTimeMillisecs, maxTimeMillisecs); @@ -66,9 +63,8 @@ public static long getScaledTimeMillisecs( * @return the scaled time in milliseconds */ public static long getScaledTimeMillisecs( - double beginZoom, double endZoom, - long minTimeMillisecs, long maxTimeMillisecs) - { + double beginZoom, double endZoom, + long minTimeMillisecs, long maxTimeMillisecs) { double scaleFactor = Math.abs(endZoom - beginZoom) / Math.max(endZoom, beginZoom); // Clamp scaleFactor to range [0, 1]. scaleFactor = clampDouble(scaleFactor, 0.0, 1.0); @@ -78,14 +74,13 @@ public static long getScaledTimeMillisecs( /** * Calculate the angular ratio between two angles + * * @param x The numerator * @param y The denominator * @return The angular ratio of x/y */ - public static double angularRatio(Angle x, Angle y) - { - if (x == null || y == null) - { + public static double angularRatio(Angle x, Angle y) { + if (x == null || y == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -103,12 +98,12 @@ public static double angularRatio(Angle x, Angle y) * @param value2 The maximum value of the range * @return the interpolated value */ - public static double mixDouble(double amount, double value1, double value2) - { - if (amount < 0) + public static double mixDouble(double amount, double value1, double value2) { + if (amount < 0) { return value1; - else if (amount > 1) + } else if (amount > 1) { return value2; + } return value1 * (1.0 - amount) + value2 * amount; } @@ -120,8 +115,7 @@ else if (amount > 1) * @param max the maximum * @return the clamped value */ - public static double clampDouble(double value, double min, double max) - { + public static double clampDouble(double value, double min, double max) { return value < min ? min : (value > max ? max : value); } @@ -130,19 +124,18 @@ public static double clampDouble(double value, double min, double max) * * @param amount The value to normalize * @param startAmount The lower end of the range - * @param stopAmount The upper end of the range + * @param stopAmount The upper end of the range * @return the normalized interpolant */ public static double interpolantNormalized(double amount, double startAmount, - double stopAmount) - { - if (amount < startAmount) + double stopAmount) { + if (amount < startAmount) { return 0.0; - else if (amount > stopAmount) + } else if (amount > stopAmount) { return 1.0; - if ((stopAmount - startAmount) == 0) - { - return(1.0); + } + if ((stopAmount - startAmount) == 0) { + return (1.0); } return (amount - startAmount) / (stopAmount - startAmount); } @@ -154,12 +147,10 @@ else if (amount > stopAmount) * @param smoothingIterations the number of smoothing iterations * @return the smoothed interpolant */ - public static double interpolantSmoothed(double interpolant, int smoothingIterations) - { + public static double interpolantSmoothed(double interpolant, int smoothingIterations) { // Apply iterative hermite smoothing. double smoothed = interpolant; - for (int i = 0; i < smoothingIterations; i++) - { + for (int i = 0; i < smoothingIterations; i++) { smoothed = smoothed * smoothed * (3.0 - 2.0 * smoothed); } return smoothed; @@ -167,6 +158,7 @@ public static double interpolantSmoothed(double interpolant, int smoothingIterat /** * Calculate a normalized, smoothed interpolant + * * @param interpolant the unsmoothed, unnormalized interpolant * @param startInterpolant the lower end of interpolant range * @param stopInterpolant the higher end of the interpolant range @@ -174,8 +166,7 @@ public static double interpolantSmoothed(double interpolant, int smoothingIterat * @return the normalized, smoothed interpolant */ public static double basicInterpolant(double interpolant, double startInterpolant, double stopInterpolant, - int maxSmoothing) - { + int maxSmoothing) { double normalizedInterpolant = interpolantNormalized(interpolant, startInterpolant, stopInterpolant); return interpolantSmoothed(normalizedInterpolant, maxSmoothing); } diff --git a/src/gov/nasa/worldwind/animation/Animator.java b/src/gov/nasa/worldwind/animation/Animator.java index 389fea0400..e134feceb5 100644 --- a/src/gov/nasa/worldwind/animation/Animator.java +++ b/src/gov/nasa/worldwind/animation/Animator.java @@ -9,27 +9,26 @@ * @author jym * @version $Id: Animator.java 1171 2013-02-11 21:45:02Z dcollins $ */ - /** - * The Animator interface provides a way to iterate through a series of values. It can be used with - * a simple interpolation function, or something more elaborate. The PropertyAccessor class and its + * The Animator interface provides a way to iterate through a series of values. It can be used with a + * simple interpolation function, or something more elaborate. The PropertyAccessor class and its * interfaces can be used to agnostically attach to data members of any class. -*/ -public interface Animator -{ + */ +public interface Animator { + /** - * Iterates to the next value. The implementation is expected to apply that next value to the property - * it is attached to. + * Iterates to the next value. The implementation is expected to apply that next value to the property it is + * attached to. */ void next(); /** - * Starts the Animator. The implemenation should return true from hasNext + * Starts the Animator. The implemenation should return true from hasNext */ void start(); /** - * Stops the Animator. The implmenentation should return false from hasNext + * Stops the Animator. The implmenentation should return false from hasNext */ void stop(); @@ -42,6 +41,7 @@ public interface Animator /** * Set the value of the attached property to the value associated with this interpolant value. + * * @param interpolant A value between 0 and 1. */ void set(double interpolant); diff --git a/src/gov/nasa/worldwind/animation/BasicAnimator.java b/src/gov/nasa/worldwind/animation/BasicAnimator.java index cff870e8a1..d18c07a402 100644 --- a/src/gov/nasa/worldwind/animation/BasicAnimator.java +++ b/src/gov/nasa/worldwind/animation/BasicAnimator.java @@ -9,63 +9,56 @@ * @author jym * @version $Id: BasicAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ - /** * A base class for an interpolating Animator. */ -public class BasicAnimator implements Animator -{ +public class BasicAnimator implements Animator { + private boolean stopOnInvalidState = false; private boolean lastStateValid = true; private boolean hasNext = true; /** - * Used to drive the animators next value based on the interpolant returned by the - * Interpolator's next interpolant + * Used to drive the animators next value based on the interpolant returned by the Interpolator's next + * interpolant */ protected Interpolator interpolator; /** - * Constructs a BasicAnimator. Sets the Animator's Interpolator to - * null. + * Constructs a BasicAnimator. Sets the Animator's Interpolator to + * null. */ - public BasicAnimator() - { + public BasicAnimator() { interpolator = null; } /** - * Constructs a BasicAnimator. The next method will use the passed + * Constructs a BasicAnimator. The next method will use the passed * Interpolator to retrieve the interpolant * - * @param interpolator The Interpolator to be used to get the interpolant for - * setting the next value. + * @param interpolator The Interpolator to be used to get the interpolant for setting the next value. */ - public BasicAnimator(Interpolator interpolator) - { + public BasicAnimator(Interpolator interpolator) { this.interpolator = interpolator; } /** - * Calls the set method with the next interpolant as determined - * by the interpolator member. + * Calls the set method with the next interpolant as determined by the + * interpolator member. */ - public void next() - { + public void next() { set(this.interpolator.nextInterpolant()); } /** - * Calls the setImpl method with the interpolant value. Deriving classes are expected to - * implement the desired action of a set operation in thier setImpl method. + * Calls the setImpl method with the interpolant value. Deriving classes are expected to implement the desired + * action of a set operation in thier setImpl method. * * @param interpolant A value between 0 and 1. */ - public void set(double interpolant) - { + public void set(double interpolant) { this.setImpl(interpolant); - if (isStopOnInvalidState() && !isLastStateValid()) - { + if (isStopOnInvalidState() && !isLastStateValid()) { this.stop(); } } @@ -75,55 +68,47 @@ public void set(double interpolant) * * @return true if the Animator has more elements */ - public boolean hasNext() - { + public boolean hasNext() { return this.hasNext; } /** * Starts the Animator, hasNext will now return true */ - public void start() - { + public void start() { this.hasNext = true; } /** * Stops the Animator, hasNext will now return false */ - public void stop() - { + public void stop() { this.hasNext = false; } /** - * No-op intended to be overrided by deriving classes. Deriving classes are expected to - * implement the desired action of a set operation in this method. + * No-op intended to be overrided by deriving classes. Deriving classes are expected to implement the desired action + * of a set operation in this method. * * @param interpolant A value between 0 and 1. */ - protected void setImpl(double interpolant) - { + protected void setImpl(double interpolant) { } - public void setStopOnInvalidState(boolean stop) - { - this.stopOnInvalidState = stop; + public void setStopOnInvalidState(boolean stop) { + this.stopOnInvalidState = stop; } - public boolean isStopOnInvalidState() - { - return this.stopOnInvalidState; + public boolean isStopOnInvalidState() { + return this.stopOnInvalidState; } - protected void flagLastStateInvalid() - { - this.lastStateValid = false; + protected void flagLastStateInvalid() { + this.lastStateValid = false; } - protected boolean isLastStateValid() - { - return this.lastStateValid; + protected boolean isLastStateValid() { + return this.lastStateValid; } } diff --git a/src/gov/nasa/worldwind/animation/CompoundAnimator.java b/src/gov/nasa/worldwind/animation/CompoundAnimator.java index ff6d8df5cc..bec6674efd 100644 --- a/src/gov/nasa/worldwind/animation/CompoundAnimator.java +++ b/src/gov/nasa/worldwind/animation/CompoundAnimator.java @@ -10,22 +10,22 @@ import java.util.Arrays; /** - * A group of two or more {@link Animator}s. Can be used to animate more than one value at a time, driven by a - * single {@link Interpolator}. + * A group of two or more {@link Animator}s. Can be used to animate more than one value at a time, driven by a single + * {@link Interpolator}. * * @author jym * @version $Id: CompoundAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CompoundAnimator extends BasicAnimator -{ +public class CompoundAnimator extends BasicAnimator { + protected Animator[] animators; /** * Construct a CompoundAnimator with the given {@link Interpolator} + * * @param interpolator the {@link Interpolator} to use to drive the animation. */ - public CompoundAnimator(Interpolator interpolator) - { + public CompoundAnimator(Interpolator interpolator) { super(interpolator); this.animators = null; } @@ -36,15 +36,13 @@ public CompoundAnimator(Interpolator interpolator) * @param interpolator The {@link Interpolator} to use to drive the {@link Animator}s * @param animators The {@link Animator}s that will be driven by this {@link CompoundAnimator} */ - public CompoundAnimator(Interpolator interpolator, Animator... animators) - { + public CompoundAnimator(Interpolator interpolator, Animator... animators) { super(interpolator); - if (animators == null) - { - String message = Logging.getMessage("nullValue.ArrayIsNull"); - Logging.logger().severe(message); - throw new IllegalArgumentException(message); - } + if (animators == null) { + String message = Logging.getMessage("nullValue.ArrayIsNull"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } int numAnimators = animators.length; this.animators = new Animator[numAnimators]; @@ -53,10 +51,10 @@ public CompoundAnimator(Interpolator interpolator, Animator... animators) /** * Set the {@link Animator}s to be driven by this {@link CompoundAnimator} + * * @param animators the {@link Animator}s to be driven by this {@link CompoundAnimator} */ - public void setAnimators(Animator... animators) - { + public void setAnimators(Animator... animators) { int numAnimators = animators.length; this.animators = new Animator[numAnimators]; System.arraycopy(animators, 0, this.animators, 0, numAnimators); @@ -64,10 +62,10 @@ public void setAnimators(Animator... animators) /** * Get an {@link Iterable} list of the {@link Animator} + * * @return the list of {@link Animator}s */ - public final Iterable getAnimators() - { + public final Iterable getAnimators() { return Arrays.asList(this.animators); } @@ -76,22 +74,17 @@ public final Iterable getAnimators() * * @param interpolant A value between 0 and 1. */ - protected void setImpl(double interpolant) - { + protected void setImpl(double interpolant) { boolean allStopped = true; - for (Animator a : animators) - { - if (a != null) - { - if (a.hasNext()) - { + for (Animator a : animators) { + if (a != null) { + if (a.hasNext()) { allStopped = false; a.set(interpolant); } } } - if (allStopped) - { + if (allStopped) { this.stop(); } } diff --git a/src/gov/nasa/worldwind/animation/DoubleAnimator.java b/src/gov/nasa/worldwind/animation/DoubleAnimator.java index bb33a91405..f7099ad264 100644 --- a/src/gov/nasa/worldwind/animation/DoubleAnimator.java +++ b/src/gov/nasa/worldwind/animation/DoubleAnimator.java @@ -13,82 +13,72 @@ * @author jym * @version $Id: DoubleAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DoubleAnimator extends BasicAnimator -{ +public class DoubleAnimator extends BasicAnimator { + protected double begin; protected double end; protected final PropertyAccessor.DoubleAccessor propertyAccessor; public DoubleAnimator(Interpolator interpolator, - double begin, double end, - PropertyAccessor.DoubleAccessor propertyAccessor) - { - super(interpolator); - if (interpolator == null) - { - this.interpolator = new ScheduledInterpolator(10000); - } - - if (propertyAccessor == null) - { - String message = Logging.getMessage("nullValue.ViewPropertyAccessorIsNull"); - Logging.logger().severe(message); - throw new IllegalArgumentException(message); - } + double begin, double end, + PropertyAccessor.DoubleAccessor propertyAccessor) { + super(interpolator); + if (interpolator == null) { + this.interpolator = new ScheduledInterpolator(10000); + } + + if (propertyAccessor == null) { + String message = Logging.getMessage("nullValue.ViewPropertyAccessorIsNull"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); + } - this.begin = begin; - this.end = end; - this.propertyAccessor = propertyAccessor; + this.begin = begin; + this.end = end; + this.propertyAccessor = propertyAccessor; } - public void setBegin(Double begin) - { + public void setBegin(Double begin) { this.begin = begin; } - public void setEnd(Double end) - { + public void setEnd(Double end) { this.end = end; } - public final Double getBegin() - { - return this.begin; + public final Double getBegin() { + return this.begin; } - public final Double getEnd() - { - return this.end; + public final Double getEnd() { + return this.end; } - public final PropertyAccessor.DoubleAccessor getPropertyAccessor() - { - return this.propertyAccessor; + public final PropertyAccessor.DoubleAccessor getPropertyAccessor() { + return this.propertyAccessor; } - protected void setImpl(double interpolant) - { - Double newValue = this.nextDouble(interpolant); - if (newValue == null) - return; + protected void setImpl(double interpolant) { + Double newValue = this.nextDouble(interpolant); + if (newValue == null) { + return; + } - boolean success = this.propertyAccessor.setDouble(newValue); - if (!success) - { - this.flagLastStateInvalid(); - } - if (interpolant >= 1.0) - this.stop(); + boolean success = this.propertyAccessor.setDouble(newValue); + if (!success) { + this.flagLastStateInvalid(); + } + if (interpolant >= 1.0) { + this.stop(); + } } @SuppressWarnings({"UnusedDeclaration"}) - public Double nextDouble(double interpolant) - { - return AnimationSupport.mixDouble( - interpolant, - this.begin, - this.end); + public Double nextDouble(double interpolant) { + return AnimationSupport.mixDouble( + interpolant, + this.begin, + this.end); } - } diff --git a/src/gov/nasa/worldwind/animation/Interpolator.java b/src/gov/nasa/worldwind/animation/Interpolator.java index d20b820004..87c2bcbecf 100644 --- a/src/gov/nasa/worldwind/animation/Interpolator.java +++ b/src/gov/nasa/worldwind/animation/Interpolator.java @@ -9,14 +9,14 @@ * @author jym * @version $Id: Interpolator.java 1171 2013-02-11 21:45:02Z dcollins $ */ - /** * An interface for generating interpolants. */ -public interface Interpolator -{ +public interface Interpolator { + /** * Returns the next interpolant + * * @return a value between 0 and 1 that represents the next position of the interpolant. */ double nextInterpolant(); diff --git a/src/gov/nasa/worldwind/animation/MoveToDoubleAnimator.java b/src/gov/nasa/worldwind/animation/MoveToDoubleAnimator.java index 303f3d0d1a..00f0e5084c 100644 --- a/src/gov/nasa/worldwind/animation/MoveToDoubleAnimator.java +++ b/src/gov/nasa/worldwind/animation/MoveToDoubleAnimator.java @@ -9,35 +9,35 @@ /** * Animates the value to the specified end position, using the specified smoothing, until the value is within the - * specified minEpsilon of the end value. For each frame the animator interpolates between the current value and the + * specified minEpsilon of the end value. For each frame the animator interpolates between the current value and the * target(end) value using (1.0-smoothing) as the interpolant, until the difference between the current * value and the target(end) value is less than the minEpsilon value. * * @author jym * @version $Id: MoveToDoubleAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MoveToDoubleAnimator extends DoubleAnimator -{ +public class MoveToDoubleAnimator extends DoubleAnimator { + /** * The amount of delta between the end value and the current value that is required to stop the animation. Defaults * to .001. */ protected double minEpsilon = 1e-3; - /** The amount of smoothing. A number between 0 and 1. The higher the number the greater the smoothing. */ + /** + * The amount of smoothing. A number between 0 and 1. The higher the number the greater the smoothing. + */ protected double smoothing = .9; /** * Construct a {@link MoveToDoubleAnimator} * - * @param end The target value, the value to animate to. - * @param smoothing The smoothing factor. A number between 0 and 1. The higher the number the greater the - * smoothing. + * @param end The target value, the value to animate to. + * @param smoothing The smoothing factor. A number between 0 and 1. The higher the number the greater the smoothing. * @param propertyAccessor The accessor used to access the animated value. */ public MoveToDoubleAnimator( - Double end, double smoothing, - PropertyAccessor.DoubleAccessor propertyAccessor) - { + Double end, double smoothing, + PropertyAccessor.DoubleAccessor propertyAccessor) { super(null, 0, end, propertyAccessor); this.interpolator = null; this.smoothing = smoothing; @@ -46,17 +46,16 @@ public MoveToDoubleAnimator( /** * Construct a {@link MoveToDoubleAnimator} * - * @param end The target value, the value to animate to. - * @param smoothing smoothing The smoothing factor. A number between 0 and 1. The higher the number the - * greater the smoothing. - * @param minEpsilon The minimum difference between the current value and the target value that triggers the - * end of the animation. Defaults to .001. + * @param end The target value, the value to animate to. + * @param smoothing smoothing The smoothing factor. A number between 0 and 1. The higher the number the greater the + * smoothing. + * @param minEpsilon The minimum difference between the current value and the target value that triggers the end of + * the animation. Defaults to .001. * @param propertyAccessor The double accessor used to access the animated value. */ public MoveToDoubleAnimator( - Double end, double smoothing, double minEpsilon, - PropertyAccessor.DoubleAccessor propertyAccessor) - { + Double end, double smoothing, double minEpsilon, + PropertyAccessor.DoubleAccessor propertyAccessor) { super(null, 0, end, propertyAccessor); this.interpolator = null; this.smoothing = smoothing; @@ -64,28 +63,26 @@ public MoveToDoubleAnimator( } /** - * Set the value to the next value in the animation. This interpolates between the current value and the target + * Set the value to the next value in the animation. This interpolates between the current value and the target * value using 1.0-smoothing as the interpolant. */ - public void next() - { - if (hasNext()) + public void next() { + if (hasNext()) { set(1.0 - smoothing); + } } /** * Get the next value using the given interpolantto perform a linear interplation. between the current value and the * target(end) value. * - * @param interpolant The inerpolant to be used to perform the interpolation. A number between 0 and 1. + * @param interpolant The inerpolant to be used to perform the interpolation. A number between 0 and 1. * * @return the interpolated value. */ - public Double nextDouble(double interpolant) - { + public Double nextDouble(double interpolant) { double newValue = (1 - interpolant) * propertyAccessor.getDouble() + interpolant * this.end; - if (Math.abs(newValue - propertyAccessor.getDouble()) < minEpsilon) - { + if (Math.abs(newValue - propertyAccessor.getDouble()) < minEpsilon) { this.stop(); return (null); } diff --git a/src/gov/nasa/worldwind/animation/MoveToPositionAnimator.java b/src/gov/nasa/worldwind/animation/MoveToPositionAnimator.java index e86b1966ef..ef2fcc098f 100644 --- a/src/gov/nasa/worldwind/animation/MoveToPositionAnimator.java +++ b/src/gov/nasa/worldwind/animation/MoveToPositionAnimator.java @@ -12,52 +12,47 @@ * @author jym * @version $Id: MoveToPositionAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MoveToPositionAnimator extends PositionAnimator -{ +public class MoveToPositionAnimator extends PositionAnimator { protected double positionMinEpsilon = 1e-9; protected double smoothing = .9; protected boolean useSmoothing = true; public MoveToPositionAnimator( - Position begin, - Position end, - double smoothing, - PropertyAccessor.PositionAccessor propertyAccessor) - { + Position begin, + Position end, + double smoothing, + PropertyAccessor.PositionAccessor propertyAccessor) { super(null, begin, end, propertyAccessor); this.interpolator = null; this.smoothing = smoothing; } - public void next() - { - if (hasNext()) - set(1.0-smoothing); + public void next() { + if (hasNext()) { + set(1.0 - smoothing); + } } - public Position nextPosition(double interpolant) - { + public Position nextPosition(double interpolant) { Position nextPosition = this.end; Position curCenter = this.propertyAccessor.getPosition(); double latlonDifference = LatLon.greatCircleDistance(nextPosition, curCenter).degrees; double elevDifference = Math.abs(nextPosition.getElevation() - curCenter.getElevation()); boolean stopMoving = Math.max(latlonDifference, elevDifference) < this.positionMinEpsilon; - if (!stopMoving) - { + if (!stopMoving) { interpolant = 1 - this.smoothing; nextPosition = new Position( - Angle.mix(interpolant, curCenter.getLatitude(), this.end.getLatitude()), - Angle.mix(interpolant, curCenter.getLongitude(), this.end.getLongitude()), - (1 - interpolant) * curCenter.getElevation() + interpolant * this.end.getElevation()); + Angle.mix(interpolant, curCenter.getLatitude(), this.end.getLatitude()), + Angle.mix(interpolant, curCenter.getLongitude(), this.end.getLongitude()), + (1 - interpolant) * curCenter.getElevation() + interpolant * this.end.getElevation()); } // If target is close, cancel future value changes. - if (stopMoving) - { + if (stopMoving) { this.stop(); - return(null); + return (null); } return nextPosition; } diff --git a/src/gov/nasa/worldwind/animation/PositionAnimator.java b/src/gov/nasa/worldwind/animation/PositionAnimator.java index 14645e7518..030b2d7347 100644 --- a/src/gov/nasa/worldwind/animation/PositionAnimator.java +++ b/src/gov/nasa/worldwind/animation/PositionAnimator.java @@ -12,86 +12,73 @@ * @author jym * @version $Id: PositionAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PositionAnimator extends BasicAnimator -{ - +public class PositionAnimator extends BasicAnimator { + protected Position begin; protected Position end; protected final PropertyAccessor.PositionAccessor propertyAccessor; public PositionAnimator( - Interpolator interpolator, - Position begin, - Position end, - PropertyAccessor.PositionAccessor propertyAccessor) - { + Interpolator interpolator, + Position begin, + Position end, + PropertyAccessor.PositionAccessor propertyAccessor) { super(interpolator); - if (interpolator == null) - { - this.interpolator = new ScheduledInterpolator(10000); + if (interpolator == null) { + this.interpolator = new ScheduledInterpolator(10000); } - if (begin == null || end == null) - { - String message = Logging.getMessage("nullValue.PositionIsNull"); - Logging.logger().severe(message); - throw new IllegalArgumentException(message); + if (begin == null || end == null) { + String message = Logging.getMessage("nullValue.PositionIsNull"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); } - if (propertyAccessor == null) - { - String message = Logging.getMessage("nullValue.ViewPropertyAccessorIsNull"); - Logging.logger().severe(message); - throw new IllegalArgumentException(message); + if (propertyAccessor == null) { + String message = Logging.getMessage("nullValue.ViewPropertyAccessorIsNull"); + Logging.logger().severe(message); + throw new IllegalArgumentException(message); } this.begin = begin; this.end = end; this.propertyAccessor = propertyAccessor; } - - public void setBegin(Position begin) - { + + public void setBegin(Position begin) { this.begin = begin; } - public void setEnd(Position end) - { + public void setEnd(Position end) { this.end = end; } - public Position getBegin() - { + public Position getBegin() { return this.begin; } - public Position getEnd() - { + public Position getEnd() { return this.end; } - public PropertyAccessor.PositionAccessor getPropertyAccessor() - { + public PropertyAccessor.PositionAccessor getPropertyAccessor() { return this.propertyAccessor; } - protected void setImpl(double interpolant) - { + protected void setImpl(double interpolant) { Position newValue = this.nextPosition(interpolant); - if (newValue == null) - return; + if (newValue == null) { + return; + } boolean success = this.propertyAccessor.setPosition(newValue); - if (!success) - { - this.flagLastStateInvalid(); + if (!success) { + this.flagLastStateInvalid(); } - if (interpolant >= 1) - { + if (interpolant >= 1) { this.stop(); } } - protected Position nextPosition(double interpolant) - { + protected Position nextPosition(double interpolant) { return Position.interpolateGreatCircle(interpolant, this.begin, this.end); } } diff --git a/src/gov/nasa/worldwind/animation/RotateToAngleAnimator.java b/src/gov/nasa/worldwind/animation/RotateToAngleAnimator.java index 28af521c68..3352e1fa3d 100644 --- a/src/gov/nasa/worldwind/animation/RotateToAngleAnimator.java +++ b/src/gov/nasa/worldwind/animation/RotateToAngleAnimator.java @@ -12,42 +12,40 @@ * @author jym * @version $Id: RotateToAngleAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RotateToAngleAnimator extends AngleAnimator -{ +public class RotateToAngleAnimator extends AngleAnimator { + private double minEpsilon = 1e-4; private double smoothing = .9; + public RotateToAngleAnimator( - Angle begin, Angle end, double smoothing, - PropertyAccessor.AngleAccessor propertyAccessor) - { + Angle begin, Angle end, double smoothing, + PropertyAccessor.AngleAccessor propertyAccessor) { super(null, begin, end, propertyAccessor); this.smoothing = smoothing; } - public void next() - { - if (hasNext()) - set(1.0-smoothing); + public void next() { + if (hasNext()) { + set(1.0 - smoothing); + } } - protected void setImpl(double interpolant) - { + protected void setImpl(double interpolant) { Angle newValue = this.nextAngle(interpolant); - if (newValue == null) - return; + if (newValue == null) { + return; + } boolean success = this.propertyAccessor.setAngle(newValue); - if (!success) - { - flagLastStateInvalid(); + if (!success) { + flagLastStateInvalid(); } - if (interpolant >= 1) + if (interpolant >= 1) { this.stop(); + } } @SuppressWarnings({"UnusedDeclaration"}) - public Angle nextAngle(double interpolant) - { - + public Angle nextAngle(double interpolant) { Angle nextAngle = this.end; Angle curAngle = this.propertyAccessor.getAngle(); @@ -55,14 +53,11 @@ public Angle nextAngle(double interpolant) double difference = Math.abs(nextAngle.subtract(curAngle).degrees); boolean stopMoving = difference < this.minEpsilon; - if (stopMoving) - { + if (stopMoving) { this.stop(); - } - else - { + } else { nextAngle = Angle.mix(interpolant, curAngle, this.end); } - return(nextAngle); + return (nextAngle); } } diff --git a/src/gov/nasa/worldwind/animation/ScheduledInterpolator.java b/src/gov/nasa/worldwind/animation/ScheduledInterpolator.java index bd6fc666fd..6d4dfc0503 100644 --- a/src/gov/nasa/worldwind/animation/ScheduledInterpolator.java +++ b/src/gov/nasa/worldwind/animation/ScheduledInterpolator.java @@ -13,41 +13,36 @@ * @author jym * @version $Id: ScheduledInterpolator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScheduledInterpolator implements Interpolator -{ +public class ScheduledInterpolator implements Interpolator { + private long startTime = -1; private final long length; - public ScheduledInterpolator(long lengthMillis) - { + public ScheduledInterpolator(long lengthMillis) { this(null, lengthMillis); } - public ScheduledInterpolator(Date startTime, long lengthMillis) - { - if (lengthMillis < 0) - { + public ScheduledInterpolator(Date startTime, long lengthMillis) { + if (lengthMillis < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", lengthMillis); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (startTime != null) + if (startTime != null) { this.startTime = startTime.getTime(); + } this.length = lengthMillis; } - public ScheduledInterpolator(Date startTime, Date stopTime) - { - if (startTime == null || stopTime == null) - { + public ScheduledInterpolator(Date startTime, Date stopTime) { + if (startTime == null || stopTime == null) { String message = Logging.getMessage("nullValue.DateIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (startTime.after(stopTime)) - { + if (startTime.after(stopTime)) { String message = Logging.getMessage("generic.ArgumentOutOfRange", startTime); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -57,17 +52,17 @@ public ScheduledInterpolator(Date startTime, Date stopTime) this.length = stopTime.getTime() - startTime.getTime(); } - public double nextInterpolant() - { - + public double nextInterpolant() { long currentTime = System.currentTimeMillis(); // When no start time is specified, begin counting time on the first run. - if (this.startTime < 0) + if (this.startTime < 0) { this.startTime = currentTime; + } // Exit when current time is before starting time. - if (currentTime < this.startTime) + if (currentTime < this.startTime) { return 0; + } long elapsedTime = currentTime - this.startTime; double unclampedInterpolant = ((double) elapsedTime) / ((double) this.length); diff --git a/src/gov/nasa/worldwind/animation/SmoothInterpolator.java b/src/gov/nasa/worldwind/animation/SmoothInterpolator.java index d6d9fbc499..b54c857fa9 100644 --- a/src/gov/nasa/worldwind/animation/SmoothInterpolator.java +++ b/src/gov/nasa/worldwind/animation/SmoothInterpolator.java @@ -9,38 +9,33 @@ * @author jym * @version $Id: SmoothInterpolator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SmoothInterpolator extends ScheduledInterpolator -{ +public class SmoothInterpolator extends ScheduledInterpolator { + private boolean useMidZoom = true; private final int MAX_SMOOTHING = 3; private final double START = this.useMidZoom ? 0.0 : 0.6; private final double STOP = 1.0; - public SmoothInterpolator(long lengthMillis) - { + public SmoothInterpolator(long lengthMillis) { super(lengthMillis); } - public double nextInterpolant() - { + public double nextInterpolant() { double interpolant = super.nextInterpolant(); return basicInterpolant(interpolant, - this.START, this.STOP, this.MAX_SMOOTHING); + this.START, this.STOP, this.MAX_SMOOTHING); } protected static double basicInterpolant(double interpolant, double startInterpolant, - double stopInterpolant, - int maxSmoothing) - { + double stopInterpolant, + int maxSmoothing) { double normalizedInterpolant = AnimationSupport.interpolantNormalized(interpolant, startInterpolant, - stopInterpolant); + stopInterpolant); return AnimationSupport.interpolantSmoothed(normalizedInterpolant, maxSmoothing); } - // ============== Helper Functions ======================= // // ============== Helper Functions ======================= // // ============== Helper Functions ======================= // - + // ============== Helper Functions ======================= // // Map amount range [startAmount, stopAmount] to [0, 1] when amount is inside range. - } diff --git a/src/gov/nasa/worldwind/avlist/AVKey.java b/src/gov/nasa/worldwind/avlist/AVKey.java index 127d58ea91..ba68b57e0d 100644 --- a/src/gov/nasa/worldwind/avlist/AVKey.java +++ b/src/gov/nasa/worldwind/avlist/AVKey.java @@ -72,7 +72,7 @@ public interface AVKey // TODO: Eliminate unused constants, if any final String DATA_CACHE_NAME = "gov.nasa.worldwind.avkey.DataCacheNameKey"; final String DATA_FILE_STORE_CLASS_NAME = "gov.nasa.worldwind.avkey.DataFileStoreClassName"; final String DATA_FILE_STORE_CONFIGURATION_FILE_NAME - = "gov.nasa.worldwind.avkey.DataFileStoreConfigurationFileName"; + = "gov.nasa.worldwind.avkey.DataFileStoreConfigurationFileName"; final String DATASET_NAME = "gov.nasa.worldwind.avkey.DatasetNameKey"; final String DATA_RASTER_READER_FACTORY_CLASS_NAME = "gov.nasa.worldwind.avkey.DataRasterReaderFactoryClassName"; final String DATASET_TYPE = "gov.nasa.worldwind.avkey.DatasetTypeKey"; @@ -85,9 +85,9 @@ public interface AVKey // TODO: Eliminate unused constants, if any final String DATA_TYPE = "gov.nasa.worldwind.avkey.DataType"; final String DELETE_CACHE_ON_EXIT = "gov.nasa.worldwind.avkey.DeleteCacheOnExit"; /** - * Indicates the WorldWind scene's worst-case depth resolution, in meters. This is typically interpreted by the - * View as the desired resolution at the scene's maximum drawing distance. In this case, the resolution closer to - * the viewer's eye point is significantly better then the worst-case resolution. Decreasing this value enables the + * Indicates the WorldWind scene's worst-case depth resolution, in meters. This is typically interpreted by the View + * as the desired resolution at the scene's maximum drawing distance. In this case, the resolution closer to the + * viewer's eye point is significantly better then the worst-case resolution. Decreasing this value enables the * viewer to get closer to 3D shapes positioned above the terrain at the coast of potential rendering artifacts * between shapes that are places closely together or close to the terrain. */ @@ -296,8 +296,10 @@ public interface AVKey // TODO: Eliminate unused constants, if any final String PIXEL_FORMAT = "gov.nasa.worldwind.avkey.PixelFormat"; final String PIXEL_HEIGHT = "gov.nasa.worldwind.avkey.PixelHeight"; final String PIXEL_WIDTH = "gov.nasa.worldwind.avkey.PixelWidth"; - - /** @deprecated Use {@link #DATA_TYPE} instead.. */ + + /** + * @deprecated Use {@link #DATA_TYPE} instead.. + */ @Deprecated final String PIXEL_TYPE = AVKey.DATA_TYPE; @@ -353,14 +355,18 @@ public interface AVKey // TODO: Eliminate unused constants, if any final String REPEAT_XY = "gov.nasa.worldwind.avkey.RepeatXY"; final String RESIZE = "gov.nasa.worldwind.avkey.Resize"; - /** On window resize, scales the item to occupy a constant relative size of the viewport. */ + /** + * On window resize, scales the item to occupy a constant relative size of the viewport. + */ final String RESIZE_STRETCH = "gov.nasa.worldwind.CompassLayer.ResizeStretch"; /** * On window resize, scales the item to occupy a constant relative size of the viewport, but not larger than the * item's inherent size scaled by the layer's item scale factor. */ final String RESIZE_SHRINK_ONLY = "gov.nasa.worldwind.CompassLayer.ResizeShrinkOnly"; - /** Does not modify the item size when the window changes size. */ + /** + * Does not modify the item size when the window changes size. + */ final String RESIZE_KEEP_FIXED_SIZE = "gov.nasa.worldwind.CompassLayer.ResizeKeepFixedSize"; final String RETAIN_LEVEL_ZERO_TILES = "gov.nasa.worldwind.avkey.RetainLevelZeroTiles"; final String RETRIEVAL_POOL_SIZE = "gov.nasa.worldwind.avkey.RetrievalPoolSize"; @@ -457,8 +463,8 @@ public interface AVKey // TODO: Eliminate unused constants, if any final String TILED_IMAGERY = "gov.nasa.worldwind.avkey.TiledImagery"; final String TILED_ELEVATIONS = "gov.nasa.worldwind.avkey.TiledElevations"; final String TILED_RASTER_PRODUCER_CACHE_SIZE = "gov.nasa.worldwind.avkey.TiledRasterProducerCacheSize"; - final String TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD = - "gov.nasa.worldwind.avkey.TiledRasterProducerLargeDatasetThreshold"; + final String TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD + = "gov.nasa.worldwind.avkey.TiledRasterProducerLargeDatasetThreshold"; final String TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL = "gov.nasa.worldwind.avkey.TiledRasterProducer.LimitMaxLevel"; final String TILT = "gov.nasa.worldwind.avkey.Tilt"; final String TITLE = "gov.nasa.worldwind.avkey.Title"; diff --git a/src/gov/nasa/worldwind/avlist/AVList.java b/src/gov/nasa/worldwind/avlist/AVList.java index ee7e189c30..8aa635789e 100644 --- a/src/gov/nasa/worldwind/avlist/AVList.java +++ b/src/gov/nasa/worldwind/avlist/AVList.java @@ -13,18 +13,18 @@ * @author Tom Gaskins * @version $Id: AVList.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AVList -{ +public interface AVList { + /** * Adds a key/value pair to the list. Replaces an existing key/value pair if the list already contains the key. * - * @param key the attribute name. May not be null. + * @param key the attribute name. May not be null. * @param value the attribute value. May be null, in which case any existing value for the key is - * removed from the collection. + * removed from the collection. * - * @return previous value associated with specified key, or null if there was no mapping for key. A null return can - * also indicate that the map previously associated null with the specified key, if the implementation - * supports null values. + * @return previous value associated with specified key, or null if there was no mapping for key. A null return can + * also indicate that the map previously associated null with the specified key, if the implementation supports null + * values. * * @throws NullPointerException if key is null. */ @@ -63,8 +63,8 @@ public interface AVList * @return the attribute value if one exists in the collection, otherwise null. * * @throws NullPointerException if key is null. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if the value in the collection is not a String type. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if the value in the collection is not a + * String type. */ String getStringValue(String key); @@ -87,7 +87,7 @@ public interface AVList * * @param key the attribute name. May not be null. * - * @return previous value associated with specified key, or null if there was no mapping for key. + * @return previous value associated with specified key, or null if there was no mapping for key. * * @throws NullPointerException if key is null. */ @@ -97,7 +97,7 @@ public interface AVList * Adds a property change listener for the specified key. * * @param propertyName the key to associate the listener with. - * @param listener the listener to associate with the key. + * @param listener the listener to associate with the key. * * @throws IllegalArgumentException if either propertyName or listener is null * @see java.beans.PropertyChangeSupport @@ -108,7 +108,7 @@ public interface AVList * Removes a property change listener associated with the specified key. * * @param propertyName the key associated with the change listener. - * @param listener the listener to remove. + * @param listener the listener to remove. * * @throws IllegalArgumentException if either propertyName or listener is null * @see java.beans.PropertyChangeSupport @@ -140,8 +140,8 @@ public interface AVList * odValue and newValue are equal and non-null. * * @param propertyName the key - * @param oldValue the value associated with the key before the even causing the firing. - * @param newValue the new value associated with the key. + * @param oldValue the value associated with the key before the even causing the firing. + * @param newValue the new value associated with the key. * * @throws IllegalArgumentException if propertyName is null * @see java.beans.PropertyChangeSupport diff --git a/src/gov/nasa/worldwind/avlist/AVListImpl.java b/src/gov/nasa/worldwind/avlist/AVListImpl.java index 19e3135793..7f74e34e78 100644 --- a/src/gov/nasa/worldwind/avlist/AVListImpl.java +++ b/src/gov/nasa/worldwind/avlist/AVListImpl.java @@ -24,17 +24,18 @@ * @author Tom Gaskins * @version $Id: AVListImpl.java 2255 2014-08-22 17:36:32Z tgaskins $ */ -public class AVListImpl implements AVList -{ +public class AVListImpl implements AVList { + // Identifies the property change support instance in the avlist private static final String PROPERTY_CHANGE_SUPPORT = "avlist.PropertyChangeSupport"; // To avoid unnecessary overhead, this object's hash map is created only if needed. private Map avList; - /** Creates an empty attribute-value list. */ - public AVListImpl() - { + /** + * Creates an empty attribute-value list. + */ + public AVListImpl() { } /** @@ -42,21 +43,18 @@ public AVListImpl() * * @param sourceBean The bean to be given as the source for any events. */ - public AVListImpl(Object sourceBean) - { - if (sourceBean != null) + public AVListImpl(Object sourceBean) { + if (sourceBean != null) { this.setValue(PROPERTY_CHANGE_SUPPORT, new PropertyChangeSupport(sourceBean)); + } } - private boolean hasAvList() - { + private boolean hasAvList() { return this.avList != null; } - private Map createAvList() - { - if (!this.hasAvList()) - { + private Map createAvList() { + if (!this.hasAvList()) { // The map type used must accept null values. java.util.concurrent.ConcurrentHashMap does not. this.avList = new java.util.HashMap(1); } @@ -64,64 +62,54 @@ private Map createAvList() return this.avList; } - private Map avList(boolean createIfNone) - { - if (createIfNone && !this.hasAvList()) + private Map avList(boolean createIfNone) { + if (createIfNone && !this.hasAvList()) { this.createAvList(); + } return this.avList; } - synchronized public Object getValue(String key) - { - if (key == null) - { + synchronized public Object getValue(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.AttributeKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.hasAvList()) + if (this.hasAvList()) { return this.avList.get(key); + } return null; } - synchronized public Collection getValues() - { + synchronized public Collection getValues() { return this.hasAvList() ? this.avList.values() : this.createAvList().values(); } - synchronized public Set> getEntries() - { + synchronized public Set> getEntries() { return this.hasAvList() ? this.avList.entrySet() : this.createAvList().entrySet(); } - synchronized public String getStringValue(String key) - { - if (key == null) - { + synchronized public String getStringValue(String key) { + if (key == null) { String msg = Logging.getMessage("nullValue.AttributeKeyIsNull"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - try - { + try { Object value = this.getValue(key); return value != null ? value.toString() : null; - } - catch (ClassCastException e) - { + } catch (ClassCastException e) { String msg = Logging.getMessage("AVAAccessibleImpl.AttributeValueForKeyIsNotAString", key); Logging.logger().severe(msg); throw new WWRuntimeException(msg, e); } } - synchronized public Object setValue(String key, Object value) - { - if (key == null) - { + synchronized public Object setValue(String key, Object value) { + if (key == null) { String message = Logging.getMessage("nullValue.AttributeKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -130,28 +118,23 @@ synchronized public Object setValue(String key, Object value) return this.avList(true).put(key, value); } - synchronized public AVList setValues(AVList list) - { - if (list == null) - { + synchronized public AVList setValues(AVList list) { + if (list == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Set> entries = list.getEntries(); - for (Map.Entry entry : entries) - { + for (Map.Entry entry : entries) { this.setValue(entry.getKey(), entry.getValue()); } return this; } - synchronized public boolean hasKey(String key) - { - if (key == null) - { + synchronized public boolean hasKey(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -160,10 +143,8 @@ synchronized public boolean hasKey(String key) return this.hasAvList() && this.avList.containsKey(key); } - synchronized public Object removeKey(String key) - { - if (key == null) - { + synchronized public Object removeKey(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,12 +153,10 @@ synchronized public Object removeKey(String key) return this.hasKey(key) ? this.avList.remove(key) : null; } - synchronized public AVList copy() - { + synchronized public AVList copy() { AVListImpl clone = new AVListImpl(); - if (this.avList != null) - { + if (this.avList != null) { clone.createAvList(); clone.avList.putAll(this.avList); } @@ -185,18 +164,16 @@ synchronized public AVList copy() return clone; } - synchronized public AVList clearList() - { - if (this.hasAvList()) + synchronized public AVList clearList() { + if (this.hasAvList()) { this.avList.clear(); + } return this; } - synchronized protected PropertyChangeSupport getChangeSupport() - { + synchronized protected PropertyChangeSupport getChangeSupport() { Object pcs = this.getValue(PROPERTY_CHANGE_SUPPORT); - if (pcs == null || !(pcs instanceof PropertyChangeSupport)) - { + if (pcs == null || !(pcs instanceof PropertyChangeSupport)) { pcs = new PropertyChangeSupport(this); this.setValue(PROPERTY_CHANGE_SUPPORT, pcs); } @@ -204,16 +181,13 @@ synchronized protected PropertyChangeSupport getChangeSupport() return (PropertyChangeSupport) pcs; } - synchronized public void addPropertyChangeListener(String propertyName, java.beans.PropertyChangeListener listener) - { - if (propertyName == null) - { + synchronized public void addPropertyChangeListener(String propertyName, java.beans.PropertyChangeListener listener) { + if (propertyName == null) { String msg = Logging.getMessage("nullValue.PropertyNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (listener == null) - { + if (listener == null) { String msg = Logging.getMessage("nullValue.ListenerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -222,16 +196,13 @@ synchronized public void addPropertyChangeListener(String propertyName, java.bea } synchronized public void removePropertyChangeListener(String propertyName, - java.beans.PropertyChangeListener listener) - { - if (propertyName == null) - { + java.beans.PropertyChangeListener listener) { + if (propertyName == null) { String msg = Logging.getMessage("nullValue.PropertyNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (listener == null) - { + if (listener == null) { String msg = Logging.getMessage("nullValue.ListenerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -239,10 +210,8 @@ synchronized public void removePropertyChangeListener(String propertyName, this.getChangeSupport().removePropertyChangeListener(propertyName, listener); } - synchronized public void addPropertyChangeListener(java.beans.PropertyChangeListener listener) - { - if (listener == null) - { + synchronized public void addPropertyChangeListener(java.beans.PropertyChangeListener listener) { + if (listener == null) { String msg = Logging.getMessage("nullValue.ListenerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -250,10 +219,8 @@ synchronized public void addPropertyChangeListener(java.beans.PropertyChangeList this.getChangeSupport().addPropertyChangeListener(listener); } - synchronized public void removePropertyChangeListener(java.beans.PropertyChangeListener listener) - { - if (listener == null) - { + synchronized public void removePropertyChangeListener(java.beans.PropertyChangeListener listener) { + if (listener == null) { String msg = Logging.getMessage("nullValue.ListenerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -261,10 +228,8 @@ synchronized public void removePropertyChangeListener(java.beans.PropertyChangeL this.getChangeSupport().removePropertyChangeListener(listener); } - public void firePropertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent == null) - { + public void firePropertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) { + if (propertyChangeEvent == null) { String msg = Logging.getMessage("nullValue.PropertyChangeEventIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -272,10 +237,8 @@ public void firePropertyChange(java.beans.PropertyChangeEvent propertyChangeEven this.getChangeSupport().firePropertyChange(propertyChangeEvent); } - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { - if (propertyName == null) - { + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + if (propertyName == null) { String msg = Logging.getMessage("nullValue.PropertyNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -284,125 +247,114 @@ public void firePropertyChange(String propertyName, Object oldValue, Object newV } // Static AVList utilities. - public static String getStringValue(AVList avList, String key, String defaultValue) - { + public static String getStringValue(AVList avList, String key, String defaultValue) { String v = getStringValue(avList, key); return v != null ? v : defaultValue; } - public static String getStringValue(AVList avList, String key) - { - try - { + public static String getStringValue(AVList avList, String key) { + try { return avList.getStringValue(key); - } - catch (Exception e) - { + } catch (Exception e) { return null; } } - public static Integer getIntegerValue(AVList avList, String key, Integer defaultValue) - { + public static Integer getIntegerValue(AVList avList, String key, Integer defaultValue) { Integer v = getIntegerValue(avList, key); return v != null ? v : defaultValue; } - public static Integer getIntegerValue(AVList avList, String key) - { + public static Integer getIntegerValue(AVList avList, String key) { Object o = avList.getValue(key); - if (o == null) + if (o == null) { return null; + } - if (o instanceof Integer) + if (o instanceof Integer) { return (Integer) o; + } String v = getStringValue(avList, key); - if (v == null) + if (v == null) { return null; + } - try - { + try { return Integer.parseInt(v); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.SEVERE, "Configuration.ConversionError", v); return null; } } - public static Long getLongValue(AVList avList, String key, Long defaultValue) - { + public static Long getLongValue(AVList avList, String key, Long defaultValue) { Long v = getLongValue(avList, key); return v != null ? v : defaultValue; } - public static Long getLongValue(AVList avList, String key) - { + public static Long getLongValue(AVList avList, String key) { Object o = avList.getValue(key); - if (o == null) + if (o == null) { return null; + } - if (o instanceof Long) + if (o instanceof Long) { return (Long) o; + } String v = getStringValue(avList, key); - if (v == null) + if (v == null) { return null; + } - try - { + try { return Long.parseLong(v); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.SEVERE, "Configuration.ConversionError", v); return null; } } - public static Double getDoubleValue(AVList avList, String key, Double defaultValue) - { + public static Double getDoubleValue(AVList avList, String key, Double defaultValue) { Double v = getDoubleValue(avList, key); return v != null ? v : defaultValue; } - public static Double getDoubleValue(AVList avList, String key) - { + public static Double getDoubleValue(AVList avList, String key) { Object o = avList.getValue(key); - if (o == null) + if (o == null) { return null; + } - if (o instanceof Double) + if (o instanceof Double) { return (Double) o; + } String v = getStringValue(avList, key); - if (v == null) + if (v == null) { return null; + } - try - { + try { return Double.parseDouble(v); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.SEVERE, "Configuration.ConversionError", v); return null; } } public void getRestorableStateForAVPair(String key, Object value, RestorableSupport rs, - RestorableSupport.StateObject context) - { - if (value == null) + RestorableSupport.StateObject context) { + if (value == null) { return; + } - if (key.equals(PROPERTY_CHANGE_SUPPORT)) + if (key.equals(PROPERTY_CHANGE_SUPPORT)) { return; + } - if (rs == null) - { + if (rs == null) { String message = Logging.getMessage("nullValue.RestorableStateIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -411,31 +363,29 @@ public void getRestorableStateForAVPair(String key, Object value, RestorableSupp rs.addStateValueAsString(context, key, value.toString()); } - public static Boolean getBooleanValue(AVList avList, String key, Boolean defaultValue) - { + public static Boolean getBooleanValue(AVList avList, String key, Boolean defaultValue) { Boolean v = getBooleanValue(avList, key); return v != null ? v : defaultValue; } - public static Boolean getBooleanValue(AVList avList, String key) - { + public static Boolean getBooleanValue(AVList avList, String key) { Object o = avList.getValue(key); - if (o == null) + if (o == null) { return null; + } - if (o instanceof Boolean) + if (o instanceof Boolean) { return (Boolean) o; + } String v = getStringValue(avList, key); - if (v == null) + if (v == null) { return null; + } - try - { + try { return Boolean.parseBoolean(v); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.SEVERE, "Configuration.ConversionError", v); return null; } diff --git a/src/gov/nasa/worldwind/awt/AWTInputHandler.java b/src/gov/nasa/worldwind/awt/AWTInputHandler.java index c52d2fda80..4f49c84f32 100644 --- a/src/gov/nasa/worldwind/awt/AWTInputHandler.java +++ b/src/gov/nasa/worldwind/awt/AWTInputHandler.java @@ -22,9 +22,9 @@ * @version $Id: AWTInputHandler.java 2258 2014-08-22 22:08:33Z dcollins $ */ public class AWTInputHandler extends WWObjectImpl - implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener, FocusListener, InputHandler, - Disposable -{ + implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener, FocusListener, InputHandler, + Disposable { + protected WorldWindow wwd = null; protected EventListenerList eventListeners = new EventListenerList(); protected java.awt.Point mousePoint = new java.awt.Point(); @@ -33,15 +33,12 @@ public class AWTInputHandler extends WWObjectImpl protected boolean isHovering = false; protected boolean isDragging = false; protected boolean forceRedrawOnMousePressed = Configuration.getBooleanValue(AVKey.REDRAW_ON_MOUSE_PRESSED, false); - protected javax.swing.Timer hoverTimer = new javax.swing.Timer(600, new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { - if (AWTInputHandler.this.pickMatches(AWTInputHandler.this.hoverObjects)) - { + protected javax.swing.Timer hoverTimer = new javax.swing.Timer(600, new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { + if (AWTInputHandler.this.pickMatches(AWTInputHandler.this.hoverObjects)) { AWTInputHandler.this.isHovering = true; AWTInputHandler.this.callSelectListeners(new SelectEvent(AWTInputHandler.this.wwd, - SelectEvent.HOVER, mousePoint, AWTInputHandler.this.hoverObjects)); + SelectEvent.HOVER, mousePoint, AWTInputHandler.this.hoverObjects)); AWTInputHandler.this.hoverTimer.stop(); } } @@ -49,44 +46,40 @@ public void actionPerformed(ActionEvent actionEvent) // Delegate handler for View. protected SelectListener selectListener; - public AWTInputHandler() - { + public AWTInputHandler() { } - public void dispose() - { + public void dispose() { this.hoverTimer.stop(); this.hoverTimer = null; this.setEventSource(null); - if (this.hoverObjects != null) + if (this.hoverObjects != null) { this.hoverObjects.clear(); + } this.hoverObjects = null; - if (this.objectsAtButtonPress != null) + if (this.objectsAtButtonPress != null) { this.objectsAtButtonPress.clear(); + } this.objectsAtButtonPress = null; } - public void setEventSource(WorldWindow newWorldWindow) - { - if (newWorldWindow != null && !(newWorldWindow instanceof Component)) - { + public void setEventSource(WorldWindow newWorldWindow) { + if (newWorldWindow != null && !(newWorldWindow instanceof Component)) { String message = Logging.getMessage("Awt.AWTInputHandler.EventSourceNotAComponent"); Logging.logger().finer(message); throw new IllegalArgumentException(message); } - if (newWorldWindow == this.wwd) - { + if (newWorldWindow == this.wwd) { return; } this.eventListeners = new EventListenerList(); // make orphans of listener references - if (this.wwd != null) - { + if (this.wwd != null) { Component c = (Component) this.wwd; c.removeKeyListener(this); c.removeMouseMotionListener(this); @@ -94,16 +87,17 @@ public void setEventSource(WorldWindow newWorldWindow) c.removeMouseWheelListener(this); c.removeFocusListener(this); - if (this.selectListener != null) + if (this.selectListener != null) { this.wwd.removeSelectListener(this.selectListener); + } - if (this.wwd.getSceneController() != null) + if (this.wwd.getSceneController() != null) { this.wwd.getSceneController().removePropertyChangeListener(AVKey.VIEW, this); + } } this.wwd = newWorldWindow; - if (this.wwd == null) - { + if (this.wwd == null) { return; } @@ -115,209 +109,171 @@ public void setEventSource(WorldWindow newWorldWindow) c.addMouseWheelListener(this); c.addFocusListener(this); - this.selectListener = new SelectListener() - { - public void selected(SelectEvent event) - { - if (event.getEventAction().equals(SelectEvent.ROLLOVER)) - { + this.selectListener = new SelectListener() { + public void selected(SelectEvent event) { + if (event.getEventAction().equals(SelectEvent.ROLLOVER)) { doHover(true); } } }; this.wwd.addSelectListener(this.selectListener); - if (this.wwd.getSceneController() != null) + if (this.wwd.getSceneController() != null) { this.wwd.getSceneController().addPropertyChangeListener(AVKey.VIEW, this); + } } - public void removeHoverSelectListener() - { + public void removeHoverSelectListener() { hoverTimer.stop(); hoverTimer = null; this.wwd.removeSelectListener(selectListener); } - public WorldWindow getEventSource() - { + public WorldWindow getEventSource() { return this.wwd; } - public void setHoverDelay(int delay) - { + public void setHoverDelay(int delay) { this.hoverTimer.setDelay(delay); } - public int getHoverDelay() - { + public int getHoverDelay() { return this.hoverTimer.getDelay(); } - public boolean isSmoothViewChanges() - { + public boolean isSmoothViewChanges() { return this.wwd.getView().getViewInputHandler().isEnableSmoothing(); } - public void setSmoothViewChanges(boolean smoothViewChanges) - { + public void setSmoothViewChanges(boolean smoothViewChanges) { this.wwd.getView().getViewInputHandler().setEnableSmoothing(smoothViewChanges); } - public boolean isLockViewHeading() - { + public boolean isLockViewHeading() { return this.wwd.getView().getViewInputHandler().isLockHeading(); } - public void setLockViewHeading(boolean lockHeading) - { + public void setLockViewHeading(boolean lockHeading) { this.wwd.getView().getViewInputHandler().setLockHeading(lockHeading); } - public boolean isStopViewOnFocusLost() - { + public boolean isStopViewOnFocusLost() { return this.wwd.getView().getViewInputHandler().isStopOnFocusLost(); } - public void setStopViewOnFocusLost(boolean stopView) - { + public void setStopViewOnFocusLost(boolean stopView) { this.wwd.getView().getViewInputHandler().setStopOnFocusLost(stopView); } - protected WorldWindow getWorldWindow() - { + protected WorldWindow getWorldWindow() { return wwd; } - protected Point getMousePoint() - { + protected Point getMousePoint() { return mousePoint; } - protected void setMousePoint(Point mousePoint) - { + protected void setMousePoint(Point mousePoint) { this.mousePoint = mousePoint; } - protected boolean isHovering() - { + protected boolean isHovering() { return isHovering; } - protected void setHovering(boolean hovering) - { + protected void setHovering(boolean hovering) { isHovering = hovering; } - protected PickedObjectList getHoverObjects() - { + protected PickedObjectList getHoverObjects() { return hoverObjects; } - protected void setHoverObjects(PickedObjectList hoverObjects) - { + protected void setHoverObjects(PickedObjectList hoverObjects) { this.hoverObjects = hoverObjects; } - protected PickedObjectList getObjectsAtButtonPress() - { + protected PickedObjectList getObjectsAtButtonPress() { return objectsAtButtonPress; } - protected void setObjectsAtButtonPress(PickedObjectList objectsAtButtonPress) - { + protected void setObjectsAtButtonPress(PickedObjectList objectsAtButtonPress) { this.objectsAtButtonPress = objectsAtButtonPress; } - public boolean isForceRedrawOnMousePressed() - { + public boolean isForceRedrawOnMousePressed() { return forceRedrawOnMousePressed; } - public void setForceRedrawOnMousePressed(boolean forceRedrawOnMousePressed) - { + public void setForceRedrawOnMousePressed(boolean forceRedrawOnMousePressed) { this.forceRedrawOnMousePressed = forceRedrawOnMousePressed; } -/* + + /* public ViewInputHandler getViewInputHandler() { return viewInputHandler; } - */ + */ - public void keyTyped(KeyEvent keyEvent) - { - if (this.wwd == null) - { + public void keyTyped(KeyEvent keyEvent) { + if (this.wwd == null) { return; } - if (keyEvent == null) - { + if (keyEvent == null) { return; } this.callKeyTypedListeners(keyEvent); - if (!keyEvent.isConsumed()) - { + if (!keyEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().keyTyped(keyEvent); } } - public void keyPressed(KeyEvent keyEvent) - { - if (this.wwd == null) - { + public void keyPressed(KeyEvent keyEvent) { + if (this.wwd == null) { return; } - if (keyEvent == null) - { + if (keyEvent == null) { return; } this.callKeyPressedListeners(keyEvent); - if (!keyEvent.isConsumed()) - { + if (!keyEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().keyPressed(keyEvent); } } - public void keyReleased(KeyEvent keyEvent) - { - if (this.wwd == null) - { + public void keyReleased(KeyEvent keyEvent) { + if (this.wwd == null) { return; } - if (keyEvent == null) - { + if (keyEvent == null) { return; } this.callKeyReleasedListeners(keyEvent); - if (!keyEvent.isConsumed()) - { + if (!keyEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().keyReleased(keyEvent); } } - public void mouseClicked(final MouseEvent mouseEvent) - { - if (this.wwd == null) - { + public void mouseClicked(final MouseEvent mouseEvent) { + if (this.wwd == null) { return; } - if (this.wwd.getView() == null) - { + if (this.wwd.getView() == null) { return; } - if (mouseEvent == null) - { + if (mouseEvent == null) { return; } @@ -326,48 +282,35 @@ public void mouseClicked(final MouseEvent mouseEvent) this.callMouseClickedListeners(mouseEvent); if (pickedObjects != null && pickedObjects.getTopPickedObject() != null - && !pickedObjects.getTopPickedObject().isTerrain()) - { + && !pickedObjects.getTopPickedObject().isTerrain()) { // Something is under the cursor, so it's deemed "selected". - if (MouseEvent.BUTTON1 == mouseEvent.getButton()) - { - if (mouseEvent.getClickCount() <= 1) - { + if (MouseEvent.BUTTON1 == mouseEvent.getButton()) { + if (mouseEvent.getClickCount() <= 1) { this.callSelectListeners(new SelectEvent(this.wwd, SelectEvent.LEFT_CLICK, - mouseEvent, pickedObjects)); - } - else - { + mouseEvent, pickedObjects)); + } else { this.callSelectListeners(new SelectEvent(this.wwd, SelectEvent.LEFT_DOUBLE_CLICK, - mouseEvent, pickedObjects)); + mouseEvent, pickedObjects)); } - } - else if (MouseEvent.BUTTON3 == mouseEvent.getButton()) - { + } else if (MouseEvent.BUTTON3 == mouseEvent.getButton()) { this.callSelectListeners(new SelectEvent(this.wwd, SelectEvent.RIGHT_CLICK, - mouseEvent, pickedObjects)); + mouseEvent, pickedObjects)); } this.wwd.getView().firePropertyChange(AVKey.VIEW, null, this.wwd.getView()); - } - else - { - if (!mouseEvent.isConsumed()) - { + } else { + if (!mouseEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().mouseClicked(mouseEvent); } } } - public void mousePressed(MouseEvent mouseEvent) - { - if (this.wwd == null) - { + public void mousePressed(MouseEvent mouseEvent) { + if (this.wwd == null) { return; } - if (mouseEvent == null) - { + if (mouseEvent == null) { return; } @@ -381,37 +324,34 @@ public void mousePressed(MouseEvent mouseEvent) // If the mouse point has changed then we need to set a new pick point, and redraw the scene because the current // picked object list may not reflect the current mouse position. - if (mousePointChanged && this.wwd.getSceneController() != null) + if (mousePointChanged && this.wwd.getSceneController() != null) { this.wwd.getSceneController().setPickPoint(this.mousePoint); + } - if (this.isForceRedrawOnMousePressed() || mousePointChanged) + if (this.isForceRedrawOnMousePressed() || mousePointChanged) { this.wwd.redrawNow(); + } this.objectsAtButtonPress = this.wwd.getObjectsAtCurrentPosition(); this.callMousePressedListeners(mouseEvent); if (this.objectsAtButtonPress != null && objectsAtButtonPress.getTopPickedObject() != null - && !this.objectsAtButtonPress.getTopPickedObject().isTerrain()) - { + && !this.objectsAtButtonPress.getTopPickedObject().isTerrain()) { // Something is under the cursor, so it's deemed "selected". - if (MouseEvent.BUTTON1 == mouseEvent.getButton()) - { + if (MouseEvent.BUTTON1 == mouseEvent.getButton()) { this.callSelectListeners(new SelectEvent(this.wwd, SelectEvent.LEFT_PRESS, - mouseEvent, this.objectsAtButtonPress)); - } - else if (MouseEvent.BUTTON3 == mouseEvent.getButton()) - { + mouseEvent, this.objectsAtButtonPress)); + } else if (MouseEvent.BUTTON3 == mouseEvent.getButton()) { this.callSelectListeners(new SelectEvent(this.wwd, SelectEvent.RIGHT_PRESS, - mouseEvent, this.objectsAtButtonPress)); + mouseEvent, this.objectsAtButtonPress)); } // Initiate a repaint. this.wwd.getView().firePropertyChange(AVKey.VIEW, null, this.wwd.getView()); } - if (!mouseEvent.isConsumed()) - { + if (!mouseEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().mousePressed(mouseEvent); } @@ -420,43 +360,35 @@ else if (MouseEvent.BUTTON3 == mouseEvent.getButton()) // mouse on the GLJPanel, causing GLJPanel to take the focus in the same manner as GLCanvas. Note that focus is // passed only when the user clicks the primary mouse button. See // http://issues.worldwind.arc.nasa.gov/jira/browse/WWJ-272. - if (MouseEvent.BUTTON1 == mouseEvent.getButton() && this.wwd instanceof GLJPanel) - { + if (MouseEvent.BUTTON1 == mouseEvent.getButton() && this.wwd instanceof GLJPanel) { ((GLJPanel) this.wwd).requestFocusInWindow(); } } - public void mouseReleased(MouseEvent mouseEvent) - { - if (this.wwd == null) - { + public void mouseReleased(MouseEvent mouseEvent) { + if (this.wwd == null) { return; } - if (mouseEvent == null) - { + if (mouseEvent == null) { return; } this.mousePoint = mouseEvent.getPoint(); this.callMouseReleasedListeners(mouseEvent); - if (!mouseEvent.isConsumed()) - { + if (!mouseEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().mouseReleased(mouseEvent); } this.doHover(true); this.cancelDrag(); } - public void mouseEntered(MouseEvent mouseEvent) - { - if (this.wwd == null) - { + public void mouseEntered(MouseEvent mouseEvent) { + if (this.wwd == null) { return; } - if (mouseEvent == null) - { + if (mouseEvent == null) { return; } @@ -466,15 +398,12 @@ public void mouseEntered(MouseEvent mouseEvent) this.cancelDrag(); } - public void mouseExited(MouseEvent mouseEvent) - { - if (this.wwd == null) - { + public void mouseExited(MouseEvent mouseEvent) { + if (this.wwd == null) { return; } - if (mouseEvent == null) - { + if (mouseEvent == null) { return; } @@ -482,8 +411,7 @@ public void mouseExited(MouseEvent mouseEvent) this.wwd.getView().getViewInputHandler().mouseExited(mouseEvent); // Enqueue a redraw to update the current position and selection. - if (this.wwd.getSceneController() != null) - { + if (this.wwd.getSceneController() != null) { this.wwd.getSceneController().setPickPoint(null); this.wwd.redraw(); } @@ -492,13 +420,12 @@ public void mouseExited(MouseEvent mouseEvent) this.cancelDrag(); } - public void mouseDragged(MouseEvent mouseEvent) - { - if (this.wwd == null) + public void mouseDragged(MouseEvent mouseEvent) { + if (this.wwd == null) { return; + } - if (mouseEvent == null) - { + if (mouseEvent == null) { return; } @@ -506,150 +433,127 @@ public void mouseDragged(MouseEvent mouseEvent) this.mousePoint = mouseEvent.getPoint(); this.callMouseDraggedListeners(mouseEvent); - if ((MouseEvent.BUTTON1_DOWN_MASK & mouseEvent.getModifiersEx()) != 0) - { + if ((MouseEvent.BUTTON1_DOWN_MASK & mouseEvent.getModifiersEx()) != 0) { PickedObjectList pickedObjects = this.objectsAtButtonPress; if (this.isDragging - || (pickedObjects != null && pickedObjects.getTopPickedObject() != null - && !pickedObjects.getTopPickedObject().isTerrain())) - { + || (pickedObjects != null && pickedObjects.getTopPickedObject() != null + && !pickedObjects.getTopPickedObject().isTerrain())) { this.isDragging = true; DragSelectEvent selectEvent = new DragSelectEvent(this.wwd, SelectEvent.DRAG, mouseEvent, pickedObjects, - prevMousePoint); + prevMousePoint); this.callSelectListeners(selectEvent); // If no listener consumed the event, then cancel the drag. - if (!selectEvent.isConsumed()) + if (!selectEvent.isConsumed()) { this.cancelDrag(); + } } } - if (!this.isDragging) - { - if (!mouseEvent.isConsumed()) - { + if (!this.isDragging) { + if (!mouseEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().mouseDragged(mouseEvent); } } // Redraw to update the current position and selection. - if (this.wwd.getSceneController() != null) - { + if (this.wwd.getSceneController() != null) { this.wwd.getSceneController().setPickPoint(mouseEvent.getPoint()); this.wwd.redraw(); } } - public void mouseMoved(MouseEvent mouseEvent) - { - if (this.wwd == null) - { + public void mouseMoved(MouseEvent mouseEvent) { + if (this.wwd == null) { return; } - if (mouseEvent == null) - { + if (mouseEvent == null) { return; } this.mousePoint = mouseEvent.getPoint(); this.callMouseMovedListeners(mouseEvent); - if (!mouseEvent.isConsumed()) - { + if (!mouseEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().mouseMoved(mouseEvent); } // Redraw to update the current position and selection. - if (this.wwd.getSceneController() != null) - { + if (this.wwd.getSceneController() != null) { this.wwd.getSceneController().setPickPoint(mouseEvent.getPoint()); this.wwd.redraw(); } } - public void mouseWheelMoved(MouseWheelEvent mouseWheelEvent) - { - if (this.wwd == null) - { + public void mouseWheelMoved(MouseWheelEvent mouseWheelEvent) { + if (this.wwd == null) { return; } - if (mouseWheelEvent == null) - { + if (mouseWheelEvent == null) { return; } this.callMouseWheelMovedListeners(mouseWheelEvent); - if (!mouseWheelEvent.isConsumed()) + if (!mouseWheelEvent.isConsumed()) { this.wwd.getView().getViewInputHandler().mouseWheelMoved(mouseWheelEvent); + } } - public void focusGained(FocusEvent focusEvent) - { - if (this.wwd == null) - { + public void focusGained(FocusEvent focusEvent) { + if (this.wwd == null) { return; } - if (focusEvent == null) - { + if (focusEvent == null) { return; } this.wwd.getView().getViewInputHandler().focusGained(focusEvent); } - public void focusLost(FocusEvent focusEvent) - { - if (this.wwd == null) - { + public void focusLost(FocusEvent focusEvent) { + if (this.wwd == null) { return; } - if (focusEvent == null) - { + if (focusEvent == null) { return; } this.wwd.getView().getViewInputHandler().focusLost(focusEvent); } - protected boolean isPickListEmpty(PickedObjectList pickList) - { + protected boolean isPickListEmpty(PickedObjectList pickList) { return pickList == null || pickList.size() < 1; } - protected void doHover(boolean reset) - { + protected void doHover(boolean reset) { PickedObjectList pickedObjects = this.wwd.getObjectsAtCurrentPosition(); - if (!(this.isPickListEmpty(this.hoverObjects) || this.isPickListEmpty(pickedObjects))) - { + if (!(this.isPickListEmpty(this.hoverObjects) || this.isPickListEmpty(pickedObjects))) { PickedObject hover = this.hoverObjects.getTopPickedObject(); PickedObject last = pickedObjects.getTopPickedObject(); - Object oh = hover == null ? null : hover.getObject() != null ? hover.getObject() : - hover.getParentLayer() != null ? hover.getParentLayer() : null; - Object ol = last == null ? null : last.getObject() != null ? last.getObject() : - last.getParentLayer() != null ? last.getParentLayer() : null; - if (oh != null && ol != null && oh.equals(ol)) - { + Object oh = hover == null ? null : hover.getObject() != null ? hover.getObject() + : hover.getParentLayer() != null ? hover.getParentLayer() : null; + Object ol = last == null ? null : last.getObject() != null ? last.getObject() + : last.getParentLayer() != null ? last.getParentLayer() : null; + if (oh != null && ol != null && oh.equals(ol)) { return; // object picked is the hover object. don't do anything but wait for the timer to expire. } } this.cancelHover(); - if (!reset) - { + if (!reset) { return; } if ((pickedObjects != null) - && (pickedObjects.getTopObject() != null) - && pickedObjects.getTopPickedObject().isTerrain()) - { + && (pickedObjects.getTopObject() != null) + && pickedObjects.getTopPickedObject().isTerrain()) { return; } @@ -657,10 +561,8 @@ protected void doHover(boolean reset) this.hoverTimer.restart(); } - protected void cancelHover() - { - if (this.isHovering) - { + protected void cancelHover() { + if (this.isHovering) { this.callSelectListeners(new SelectEvent(this.wwd, SelectEvent.HOVER, this.mousePoint, null)); } @@ -669,207 +571,162 @@ protected void cancelHover() this.hoverTimer.stop(); } - protected boolean pickMatches(PickedObjectList pickedObjects) - { - if (this.isPickListEmpty(this.wwd.getObjectsAtCurrentPosition()) || this.isPickListEmpty(pickedObjects)) - { + protected boolean pickMatches(PickedObjectList pickedObjects) { + if (this.isPickListEmpty(this.wwd.getObjectsAtCurrentPosition()) || this.isPickListEmpty(pickedObjects)) { return false; } PickedObject lastTop = this.wwd.getObjectsAtCurrentPosition().getTopPickedObject(); - if (null != lastTop && lastTop.isTerrain()) - { + if (null != lastTop && lastTop.isTerrain()) { return false; } PickedObject newTop = pickedObjects.getTopPickedObject(); //noinspection SimplifiableIfStatement - if (lastTop == null || newTop == null || lastTop.getObject() == null || newTop.getObject() == null) - { + if (lastTop == null || newTop == null || lastTop.getObject() == null || newTop.getObject() == null) { return false; } return lastTop.getObject().equals(newTop.getObject()); } - protected void cancelDrag() - { - if (this.isDragging) - { + protected void cancelDrag() { + if (this.isDragging) { this.callSelectListeners(new DragSelectEvent(this.wwd, SelectEvent.DRAG_END, null, - this.objectsAtButtonPress, this.mousePoint)); + this.objectsAtButtonPress, this.mousePoint)); } this.isDragging = false; } - public void addSelectListener(SelectListener listener) - { + public void addSelectListener(SelectListener listener) { this.eventListeners.add(SelectListener.class, listener); } - public void removeSelectListener(SelectListener listener) - { + public void removeSelectListener(SelectListener listener) { this.eventListeners.remove(SelectListener.class, listener); } - protected void callSelectListeners(SelectEvent event) - { - for (SelectListener listener : this.eventListeners.getListeners(SelectListener.class)) - { + protected void callSelectListeners(SelectEvent event) { + for (SelectListener listener : this.eventListeners.getListeners(SelectListener.class)) { listener.selected(event); } } - public void addKeyListener(KeyListener listener) - { + public void addKeyListener(KeyListener listener) { this.eventListeners.add(KeyListener.class, listener); } - public void removeKeyListener(KeyListener listener) - { + public void removeKeyListener(KeyListener listener) { this.eventListeners.remove(KeyListener.class, listener); } - public void addMouseListener(MouseListener listener) - { + public void addMouseListener(MouseListener listener) { this.eventListeners.add(MouseListener.class, listener); } - public void removeMouseListener(MouseListener listener) - { + public void removeMouseListener(MouseListener listener) { this.eventListeners.remove(MouseListener.class, listener); } - public void addMouseMotionListener(MouseMotionListener listener) - { + public void addMouseMotionListener(MouseMotionListener listener) { this.eventListeners.add(MouseMotionListener.class, listener); } - public void removeMouseMotionListener(MouseMotionListener listener) - { + public void removeMouseMotionListener(MouseMotionListener listener) { this.eventListeners.remove(MouseMotionListener.class, listener); } - public void addMouseWheelListener(MouseWheelListener listener) - { + public void addMouseWheelListener(MouseWheelListener listener) { this.eventListeners.add(MouseWheelListener.class, listener); } - public void removeMouseWheelListener(MouseWheelListener listener) - { + public void removeMouseWheelListener(MouseWheelListener listener) { this.eventListeners.remove(MouseWheelListener.class, listener); } - protected void callKeyPressedListeners(KeyEvent event) - { - for (KeyListener listener : this.eventListeners.getListeners(KeyListener.class)) - { + protected void callKeyPressedListeners(KeyEvent event) { + for (KeyListener listener : this.eventListeners.getListeners(KeyListener.class)) { listener.keyPressed(event); } } - protected void callKeyReleasedListeners(KeyEvent event) - { - for (KeyListener listener : this.eventListeners.getListeners(KeyListener.class)) - { + protected void callKeyReleasedListeners(KeyEvent event) { + for (KeyListener listener : this.eventListeners.getListeners(KeyListener.class)) { listener.keyReleased(event); } } - protected void callKeyTypedListeners(KeyEvent event) - { - for (KeyListener listener : this.eventListeners.getListeners(KeyListener.class)) - { + protected void callKeyTypedListeners(KeyEvent event) { + for (KeyListener listener : this.eventListeners.getListeners(KeyListener.class)) { listener.keyTyped(event); } } - protected void callMousePressedListeners(MouseEvent event) - { - for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) - { + protected void callMousePressedListeners(MouseEvent event) { + for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) { listener.mousePressed(event); } } - protected void callMouseReleasedListeners(MouseEvent event) - { - for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) - { + protected void callMouseReleasedListeners(MouseEvent event) { + for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) { listener.mouseReleased(event); } } - protected void callMouseClickedListeners(MouseEvent event) - { - for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) - { + protected void callMouseClickedListeners(MouseEvent event) { + for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) { listener.mouseClicked(event); } } - protected void callMouseDraggedListeners(MouseEvent event) - { - for (MouseMotionListener listener : this.eventListeners.getListeners(MouseMotionListener.class)) - { + protected void callMouseDraggedListeners(MouseEvent event) { + for (MouseMotionListener listener : this.eventListeners.getListeners(MouseMotionListener.class)) { listener.mouseDragged(event); } } - protected void callMouseMovedListeners(MouseEvent event) - { - for (MouseMotionListener listener : this.eventListeners.getListeners(MouseMotionListener.class)) - { + protected void callMouseMovedListeners(MouseEvent event) { + for (MouseMotionListener listener : this.eventListeners.getListeners(MouseMotionListener.class)) { listener.mouseMoved(event); } } - protected void callMouseWheelMovedListeners(MouseWheelEvent event) - { - for (MouseWheelListener listener : this.eventListeners.getListeners(MouseWheelListener.class)) - { + protected void callMouseWheelMovedListeners(MouseWheelEvent event) { + for (MouseWheelListener listener : this.eventListeners.getListeners(MouseWheelListener.class)) { listener.mouseWheelMoved(event); } } - protected void callMouseEnteredListeners(MouseEvent event) - { - for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) - { + protected void callMouseEnteredListeners(MouseEvent event) { + for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) { listener.mouseEntered(event); } } - protected void callMouseExitedListeners(MouseEvent event) - { - for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) - { + protected void callMouseExitedListeners(MouseEvent event) { + for (MouseListener listener : this.eventListeners.getListeners(MouseListener.class)) { listener.mouseExited(event); } } - public void propertyChange(PropertyChangeEvent event) - { - if (this.wwd == null) - { + public void propertyChange(PropertyChangeEvent event) { + if (this.wwd == null) { return; } - if (this.wwd.getView() == null) - { + if (this.wwd.getView() == null) { return; } - if (event == null) - { + if (event == null) { return; } - if (event.getPropertyName().equals(AVKey.VIEW) && - (event.getSource() == this.getWorldWindow().getSceneController())) - { + if (event.getPropertyName().equals(AVKey.VIEW) + && (event.getSource() == this.getWorldWindow().getSceneController())) { this.wwd.getView().getViewInputHandler().setWorldWindow(this.wwd); } } diff --git a/src/gov/nasa/worldwind/awt/AbstractViewInputHandler.java b/src/gov/nasa/worldwind/awt/AbstractViewInputHandler.java index 0e6dd8842a..fb6cf7c416 100644 --- a/src/gov/nasa/worldwind/awt/AbstractViewInputHandler.java +++ b/src/gov/nasa/worldwind/awt/AbstractViewInputHandler.java @@ -19,8 +19,8 @@ * @author dcollins * @version $Id: AbstractViewInputHandler.java 2251 2014-08-21 21:17:46Z dcollins $ */ -public abstract class AbstractViewInputHandler implements ViewInputHandler, java.beans.PropertyChangeListener -{ +public abstract class AbstractViewInputHandler implements ViewInputHandler, java.beans.PropertyChangeListener { + protected WorldWindow wwd; protected ViewInputAttributes attributes; protected ViewInputAttributes.ActionAttributesMap mouseActionMap; @@ -67,21 +67,20 @@ public abstract class AbstractViewInputHandler implements ViewInputHandler, java protected static final String SCALE_FUNC_ZOOM = "ScaleFuncZoom"; protected static final String SCALE_FUNC_ZOOM_EXP = "ScaleFuncZoomExp"; - protected int[] modifierList = - { - KeyEvent.ALT_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK, - KeyEvent.ALT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK, - KeyEvent.ALT_DOWN_MASK | KeyEvent.META_DOWN_MASK, - KeyEvent.SHIFT_DOWN_MASK, - KeyEvent.CTRL_DOWN_MASK, - KeyEvent.META_DOWN_MASK, - KeyEvent.ALT_DOWN_MASK, - 0 - }; + protected int[] modifierList + = { + KeyEvent.ALT_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK, + KeyEvent.ALT_DOWN_MASK | KeyEvent.CTRL_DOWN_MASK, + KeyEvent.ALT_DOWN_MASK | KeyEvent.META_DOWN_MASK, + KeyEvent.SHIFT_DOWN_MASK, + KeyEvent.CTRL_DOWN_MASK, + KeyEvent.META_DOWN_MASK, + KeyEvent.ALT_DOWN_MASK, + 0 + }; protected final int NUM_MODIFIERS = 8; - public AbstractViewInputHandler() - { + public AbstractViewInputHandler() { this.enableSmoothing = true; this.lockHeading = true; this.stopOnFocusLost = true; @@ -92,8 +91,8 @@ public AbstractViewInputHandler() this.keyActionMap = this.attributes.getActionMap(ViewInputAttributes.DEVICE_KEYBOARD); this.keyModsActionMap = this.attributes.getModifierActionMap(ViewInputAttributes.DEVICE_KEYBOARD); this.mouseModsActionMap = this.attributes.getModifierActionMap(ViewInputAttributes.DEVICE_MOUSE); - this.mouseWheelModsActionMap = - this.attributes.getModifierActionMap(ViewInputAttributes.DEVICE_MOUSE_WHEEL); + this.mouseWheelModsActionMap + = this.attributes.getModifierActionMap(ViewInputAttributes.DEVICE_MOUSE_WHEEL); } @@ -104,33 +103,30 @@ public AbstractViewInputHandler() * @return the WorldWindow this ViewInputHandler is listening to, and will modify in response to * events. */ - public WorldWindow getWorldWindow() - { + public WorldWindow getWorldWindow() { return this.wwd; } /** * Sets the WorldWindow this ViewInputHandler should listen to for input events, and should modify in - * response to those events. If the parameter newWorldWindow is null, then this ViewInputHandler - * will do nothing. + * response to those events. If the parameter newWorldWindow is null, then this ViewInputHandler will + * do nothing. * * @param newWorldWindow the WorldWindow to listen on, and modify in response to events. */ - public void setWorldWindow(WorldWindow newWorldWindow) - { - if (newWorldWindow == this.wwd) + public void setWorldWindow(WorldWindow newWorldWindow) { + if (newWorldWindow == this.wwd) { return; + } - if (this.wwd != null) - { + if (this.wwd != null) { //this.wwd.removeRenderingListener(this); this.wwd.getSceneController().removePropertyChangeListener(this); } this.wwd = newWorldWindow; - if (this.wwd != null) - { + if (this.wwd != null) { //this.wwd.addRenderingListener(this); this.wwd.getSceneController().addPropertyChangeListener(this); } @@ -141,15 +137,13 @@ public void setWorldWindow(WorldWindow newWorldWindow) * * @return values that are be used to transform raw input into view movement. */ - public ViewInputAttributes getAttributes() - { + public ViewInputAttributes getAttributes() { return this.attributes; } /** - * Sets the values that will be used to transform raw input events into view movements. ViewInputAttributes - * define a calibration value for each combination of device and action, and a general sensitivity value - * for each device. + * Sets the values that will be used to transform raw input events into view movements. ViewInputAttributes define a + * calibration value for each combination of device and action, and a general sensitivity value for each device. * * @param attributes values that will be used to transform raw input into view movement. * @@ -157,10 +151,8 @@ public ViewInputAttributes getAttributes() * * @see ViewInputAttributes */ - public void setAttributes(ViewInputAttributes attributes) - { - if (attributes == null) - { + public void setAttributes(ViewInputAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -174,20 +166,18 @@ public void setAttributes(ViewInputAttributes attributes) * * @return true if the view will movements are smoothed; false otherwise. */ - public boolean isEnableSmoothing() - { + public boolean isEnableSmoothing() { return this.enableSmoothing; } /** - * Sets whether the ViewInputHandler should smooth view movements in response to input events. A value of true - * will cause the ViewInputHandler to delegate decisions about whether to smooth a certain input event to its + * Sets whether the ViewInputHandler should smooth view movements in response to input events. A value of true will + * cause the ViewInputHandler to delegate decisions about whether to smooth a certain input event to its * {@link ViewInputAttributes}. A value of false will disable all smoothing. * * @param enable true to smooth view movements; false otherwise. */ - public void setEnableSmoothing(boolean enable) - { + public void setEnableSmoothing(boolean enable) { this.enableSmoothing = enable; } @@ -196,20 +186,18 @@ public void setEnableSmoothing(boolean enable) * * @return true if the view's heading will stay the same unless explicity changed; false otherwise. */ - public boolean isLockHeading() - { + public boolean isLockHeading() { return this.lockHeading; } /** - * Sets whether the view's heading should stay the same unless explicitly changed. For example, moving forward - * along a great arc would suggest a change in position and heading. If the heading had been locked, the - * ViewInputHandler will move forward in a way that doesn't change the heading. + * Sets whether the view's heading should stay the same unless explicitly changed. For example, moving forward along + * a great arc would suggest a change in position and heading. If the heading had been locked, the ViewInputHandler + * will move forward in a way that doesn't change the heading. * * @param lock true if the view's heading should stay the same unless explicity changed; false otherwise. */ - public void setLockHeading(boolean lock) - { + public void setLockHeading(boolean lock) { this.lockHeading = lock; } @@ -218,8 +206,7 @@ public void setLockHeading(boolean lock) * * @return true if the view will stop when the WorldWindow looses focus; false otherwise. */ - public boolean isStopOnFocusLost() - { + public boolean isStopOnFocusLost() { return this.stopOnFocusLost; } @@ -228,41 +215,37 @@ public boolean isStopOnFocusLost() * * @param stop true if the view should stop when the WorldWindow looses focus; false otherwise. */ - public void setStopOnFocusLost(boolean stop) - { + public void setStopOnFocusLost(boolean stop) { this.stopOnFocusLost = stop; } /** - * Returns the factor that dampens view movement when the user pans drags the cursor in a way that could - * cause an abrupt transition. + * Returns the factor that dampens view movement when the user pans drags the cursor in a way that + * could cause an abrupt transition. * * @return factor dampening view movement when a mouse drag event would cause an abrupt transition. * @see #setDragSlopeFactor */ - public double getDragSlopeFactor() - { + public double getDragSlopeFactor() { return this.dragSlopeFactor; } /** - * Sets the factor that dampens view movement when a mouse drag event would cause an abrupt - * transition. The drag slope is the ratio of screen pixels to Cartesian distance moved, measured by the previous - * and current mouse points. As drag slope gets larger, it becomes more difficult to operate the view. This - * typically happens while dragging over and around the horizon, where movement of a few pixels can cause the view - * to move many kilometers. This factor is the amount of damping applied to the view movement in such - * cases. Setting factor to zero will disable this behavior, while setting factor to a - * positive value may dampen the effects of mouse dragging. + * Sets the factor that dampens view movement when a mouse drag event would cause an abrupt transition. + * The drag slope is the ratio of screen pixels to Cartesian distance moved, measured by the previous and current + * mouse points. As drag slope gets larger, it becomes more difficult to operate the view. This typically happens + * while dragging over and around the horizon, where movement of a few pixels can cause the view to move many + * kilometers. This factor is the amount of damping applied to the view movement in such cases. Setting + * factor to zero will disable this behavior, while setting factor to a positive value may + * dampen the effects of mouse dragging. * * @param factor dampening view movement when a mouse drag event would cause an abrupt transition. Must be greater * than or equal to zero. * * @throws IllegalArgumentException if factor is less than zero. */ - public void setDragSlopeFactor(double factor) - { - if (factor < 0) - { + public void setDragSlopeFactor(double factor) { + if (factor < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "factor < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -271,68 +254,54 @@ public void setDragSlopeFactor(double factor) this.dragSlopeFactor = factor; } - protected long getPerFrameInputInterval() - { + protected long getPerFrameInputInterval() { return this.perFrameInputInterval; } - protected void setPerFrameInputInterval(long milliseconds) - { + protected void setPerFrameInputInterval(long milliseconds) { this.perFrameInputInterval = milliseconds; } - protected View getView() - { + protected View getView() { return (this.wwd != null) ? this.wwd.getView() : null; } //**************************************************************// //******************** AWT Event Support *********************// //**************************************************************// - - protected boolean isWorldWindowFocusOwner() - { + protected boolean isWorldWindowFocusOwner() { return this.wwdFocusOwner; } - protected void setWorldWindowFocusOwner(boolean focusOwner) - { + protected void setWorldWindowFocusOwner(boolean focusOwner) { this.wwdFocusOwner = focusOwner; } - protected Point getMousePoint() - { + protected Point getMousePoint() { return this.mousePoint; } - protected Point getLastMousePoint() - { + protected Point getLastMousePoint() { return this.lastMousePoint; } - protected void updateMousePoint(MouseEvent e) - { + protected void updateMousePoint(MouseEvent e) { this.lastMousePoint = this.mousePoint; this.mousePoint = new Point(e.getPoint()); } - protected Position getSelectedPosition() - { + protected Position getSelectedPosition() { return this.selectedPosition; } - protected void setSelectedPosition(Position position) - { + protected void setSelectedPosition(Position position) { this.selectedPosition = position; } - protected Position computeSelectedPosition() - { + protected Position computeSelectedPosition() { PickedObjectList pickedObjects = this.wwd.getObjectsAtCurrentPosition(); - if (pickedObjects != null) - { - if (pickedObjects.getTerrainObject() != null) - { + if (pickedObjects != null) { + if (pickedObjects.getTerrainObject() != null) { return pickedObjects.getTerrainObject().getPosition(); } } @@ -342,9 +311,7 @@ protected Position computeSelectedPosition() //**************************************************************// //******************** View Change Events ********************// //**************************************************************// - - protected void onStopView() - { + protected void onStopView() { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { @@ -357,9 +324,7 @@ protected void onStopView() //**************************************************************// //******************** Key Events ****************************// //**************************************************************// - - public void keyTyped(KeyEvent e) - { + public void keyTyped(KeyEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -373,8 +338,7 @@ public void keyTyped(KeyEvent e) this.keyEventState.keyTyped(e); } - public void keyPressed(KeyEvent e) - { + public void keyPressed(KeyEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -389,8 +353,7 @@ public void keyPressed(KeyEvent e) this.handleKeyPressed(e); } - public void keyReleased(KeyEvent e) - { + public void keyReleased(KeyEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -406,32 +369,26 @@ public void keyReleased(KeyEvent e) } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleKeyPressed(KeyEvent e) - { + protected void handleKeyPressed(KeyEvent e) { // Determine whether or not the current key state would have generated a view change event. // If so, issue a repaint event to give the per-frame input a chance to run. - if (this.handlePerFrameKeyState(this.keyEventState, QUERY_EVENTS)) - { + if (this.handlePerFrameKeyState(this.keyEventState, QUERY_EVENTS)) { View view = this.getView(); - if (view != null) - { + if (view != null) { view.firePropertyChange(AVKey.VIEW, null, view); } } } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleKeyReleased(KeyEvent e) - { + protected void handleKeyReleased(KeyEvent e) { } //**************************************************************// //******************** Mouse Events **************************// //**************************************************************// - - public void mouseClicked(MouseEvent e) - { + public void mouseClicked(MouseEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -445,8 +402,7 @@ public void mouseClicked(MouseEvent e) this.handleMouseClicked(e); } - public void mousePressed(MouseEvent e) - { + public void mousePressed(MouseEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -464,8 +420,7 @@ public void mousePressed(MouseEvent e) this.handleMousePressed(e); } - public void mouseReleased(MouseEvent e) - { + public void mouseReleased(MouseEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -482,9 +437,8 @@ public void mouseReleased(MouseEvent e) this.handleMouseReleased(e); } - public void mouseEntered(MouseEvent e) - { - if (this.wwd == null) // include this test to ensure any derived implementation performs it + public void mouseEntered(MouseEvent e) { + if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; } @@ -496,8 +450,7 @@ public void mouseEntered(MouseEvent e) } } - public void mouseExited(MouseEvent e) - { + public void mouseExited(MouseEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -511,36 +464,29 @@ public void mouseExited(MouseEvent e) } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleMouseClicked(MouseEvent e) - { + protected void handleMouseClicked(MouseEvent e) { } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleMousePressed(MouseEvent e) - { + protected void handleMousePressed(MouseEvent e) { // Determine whether or not the current key state would have generated a view change event. // If so, issue a repaint event to give the per-frame input a chance to run. - if (this.handlePerFrameMouseState(this.keyEventState, QUERY_EVENTS)) - { + if (this.handlePerFrameMouseState(this.keyEventState, QUERY_EVENTS)) { View view = this.getView(); - if (view != null) - { + if (view != null) { view.firePropertyChange(AVKey.VIEW, null, view); } } } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleMouseReleased(MouseEvent e) - { + protected void handleMouseReleased(MouseEvent e) { } //**************************************************************// //******************** Mouse Motion Events *******************// //**************************************************************// - - public void mouseDragged(MouseEvent e) - { + public void mouseDragged(MouseEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -555,8 +501,7 @@ public void mouseDragged(MouseEvent e) this.handleMouseDragged(e); } - public void mouseMoved(MouseEvent e) - { + public void mouseMoved(MouseEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -572,21 +517,17 @@ public void mouseMoved(MouseEvent e) } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleMouseDragged(MouseEvent e) - { + protected void handleMouseDragged(MouseEvent e) { } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleMouseMoved(MouseEvent e) - { + protected void handleMouseMoved(MouseEvent e) { } //**************************************************************// //******************** Mouse Wheel Events ********************// //**************************************************************// - - public void mouseWheelMoved(MouseWheelEvent e) - { + public void mouseWheelMoved(MouseWheelEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -601,16 +542,13 @@ public void mouseWheelMoved(MouseWheelEvent e) } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleMouseWheelMoved(MouseWheelEvent e) - { + protected void handleMouseWheelMoved(MouseWheelEvent e) { } //**************************************************************// //******************** Focus Events **************************// //**************************************************************// - - public void focusGained(FocusEvent e) - { + public void focusGained(FocusEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -625,8 +563,7 @@ public void focusGained(FocusEvent e) this.handleFocusGained(e); } - public void focusLost(FocusEvent e) - { + public void focusLost(FocusEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -643,23 +580,20 @@ public void focusLost(FocusEvent e) } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleFocusGained(FocusEvent e) - { + protected void handleFocusGained(FocusEvent e) { } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleFocusLost(FocusEvent e) - { - if (this.isStopOnFocusLost()) + protected void handleFocusLost(FocusEvent e) { + if (this.isStopOnFocusLost()) { this.onStopView(); + } } - public void apply() - { + public void apply() { // Process per-frame input only when the WorldWindow is the focus owner. - if (!this.isWorldWindowFocusOwner()) - { + if (!this.isWorldWindowFocusOwner()) { return; } @@ -667,8 +601,7 @@ public void apply() // balance the input response of high and low framerate applications. long now = System.currentTimeMillis(); long interval = now - this.lastPerFrameInputTime; - if (interval >= this.getPerFrameInputInterval()) - { + if (interval >= this.getPerFrameInputInterval()) { this.handlePerFrameKeyState(this.keyEventState, GENERATE_EVENTS); this.handlePerFrameMouseState(this.keyEventState, GENERATE_EVENTS); this.handlePerFrameAnimation(GENERATE_EVENTS); @@ -679,43 +612,36 @@ public void apply() // Determine whether or not the current key state would have generated a view change event. If so, issue // a repaint event to give the per-frame input a chance to run again. - if (this.handlePerFrameKeyState(this.keyEventState, QUERY_EVENTS) || - this.handlePerFrameMouseState(this.keyEventState, QUERY_EVENTS) || - this.handlePerFrameAnimation(QUERY_EVENTS)) - { + if (this.handlePerFrameKeyState(this.keyEventState, QUERY_EVENTS) + || this.handlePerFrameMouseState(this.keyEventState, QUERY_EVENTS) + || this.handlePerFrameAnimation(QUERY_EVENTS)) { this.getWorldWindow().redraw(); } } - public void viewApplied() - { + public void viewApplied() { } // Interpret the current key state according to the specified target. If the target is KEY_POLL_GENERATE_EVENTS, // then the the key state will generate any appropriate view change events. If the target is KEY_POLL_QUERY_EVENTS, // then the key state will not generate events, and this will return whether or not any view change events would // have been generated. - protected boolean handlePerFrameKeyState(KeyEventState keys, String target) - { + protected boolean handlePerFrameKeyState(KeyEventState keys, String target) { return false; } - protected boolean handlePerFrameMouseState(KeyEventState keys, String target) - { + protected boolean handlePerFrameMouseState(KeyEventState keys, String target) { return false; } - protected boolean handlePerFrameAnimation(String target) - { + protected boolean handlePerFrameAnimation(String target) { return false; } //**************************************************************// //******************** Property Change Events ****************// //**************************************************************// - - public void propertyChange(java.beans.PropertyChangeEvent e) - { + public void propertyChange(java.beans.PropertyChangeEvent e) { if (this.wwd == null) // include this test to ensure any derived implementation performs it { return; @@ -730,22 +656,19 @@ public void propertyChange(java.beans.PropertyChangeEvent e) } @SuppressWarnings({"UnusedDeclaration"}) - protected void handlePropertyChange(java.beans.PropertyChangeEvent e) - { + protected void handlePropertyChange(java.beans.PropertyChangeEvent e) { } //**************************************************************// //******************** Raw Input Transformation **************// //**************************************************************// - // Translates raw user input into a change in value, according to the specified device and action attributes. // The input is scaled by the action attribute range (depending on eye position), then scaled by the device // sensitivity. protected double rawInputToChangeInValue(double rawInput, - ViewInputAttributes.DeviceAttributes deviceAttributes, ViewInputAttributes.ActionAttributes actionAttributes, - String scaleFunc) - { + ViewInputAttributes.DeviceAttributes deviceAttributes, ViewInputAttributes.ActionAttributes actionAttributes, + String scaleFunc) { double value = rawInput; double[] range = actionAttributes.getValues(); @@ -755,36 +678,28 @@ protected double rawInputToChangeInValue(double rawInput, return value; } - protected double getScaledValue(double minValue, double maxValue, String scaleFunc) - { - if (scaleFunc == null) - { + protected double getScaledValue(double minValue, double maxValue, String scaleFunc) { + if (scaleFunc == null) { return minValue; } double t = 0.0; - if (scaleFunc.startsWith(SCALE_FUNC_EYE_ALTITUDE)) - { + if (scaleFunc.startsWith(SCALE_FUNC_EYE_ALTITUDE)) { t = this.evaluateScaleFuncEyeAltitude(); - } - else if (scaleFunc.startsWith(SCALE_FUNC_ZOOM)) - { + } else if (scaleFunc.startsWith(SCALE_FUNC_ZOOM)) { t = this.evaluateScaleFuncZoom(); } - if (scaleFunc.toLowerCase().endsWith("exp")) - { + if (scaleFunc.toLowerCase().endsWith("exp")) { t = Math.pow(2.0, t) - 1.0; } return minValue * (1.0 - t) + maxValue * t; } - protected double evaluateScaleFuncEyeAltitude() - { + protected double evaluateScaleFuncEyeAltitude() { View view = this.getView(); - if (view == null) - { + if (view == null) { return 0.0; } @@ -795,16 +710,13 @@ protected double evaluateScaleFuncEyeAltitude() return (t < 0 ? 0 : (t > 1 ? 1 : t)); } - protected double evaluateScaleFuncZoom() - { + protected double evaluateScaleFuncZoom() { View view = this.getView(); - if (view == null) - { + if (view == null) { return 0.0; } - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { double radius = this.wwd.getModel().getGlobe().getRadius(); double t = ((OrbitView) view).getZoom() / (3.0 * radius); return (t < 0 ? 0 : (t > 1 ? 1 : t)); @@ -813,13 +725,10 @@ protected double evaluateScaleFuncZoom() return 0.0; } - protected double getScaleValueElevation( - ViewInputAttributes.DeviceAttributes deviceAttributes, ViewInputAttributes.ActionAttributes actionAttributes) - { + ViewInputAttributes.DeviceAttributes deviceAttributes, ViewInputAttributes.ActionAttributes actionAttributes) { View view = this.getView(); - if (view == null) - { + if (view == null) { return 0.0; } @@ -828,40 +737,34 @@ protected double getScaleValueElevation( Position eyePos = view.getEyePosition(); double radius = this.wwd.getModel().getGlobe().getRadius(); double surfaceElevation = this.wwd.getModel().getGlobe().getElevation(eyePos.getLatitude(), - eyePos.getLongitude()); + eyePos.getLongitude()); double t = getScaleValue(range[0], range[1], - eyePos.getElevation() - surfaceElevation, 3.0 * radius, true); - t *= deviceAttributes.getSensitivity(); + eyePos.getElevation() - surfaceElevation, 3.0 * radius, true); + t *= deviceAttributes.getSensitivity(); return t; } protected double getScaleValue(double minValue, double maxValue, - double value, double range, boolean isExp) - { + double value, double range, boolean isExp) { double t = value / range; t = t < 0 ? 0 : (t > 1 ? 1 : t); - if (isExp) - { + if (isExp) { t = Math.pow(2.0, t) - 1.0; } - return(minValue * (1.0 - t) + maxValue * t); + return (minValue * (1.0 - t) + maxValue * t); } //**************************************************************// //******************** Utility Methods ***********************// //**************************************************************// - - protected Vec4 computeSelectedPointAt(Point point) - { - if (this.getSelectedPosition() == null) - { + protected Vec4 computeSelectedPointAt(Point point) { + if (this.getSelectedPosition() == null) { return null; } View view = this.getView(); - if (view == null) - { + if (view == null) { return null; } @@ -869,8 +772,7 @@ protected Vec4 computeSelectedPointAt(Point point) // essentially dragging along the inside of a sphere, and the effects of dragging are reversed. To the user // this behavior appears unpredictable. double elevation = this.getSelectedPosition().getElevation(); - if (view.getEyePosition().getElevation() <= elevation) - { + if (view.getEyePosition().getElevation() <= elevation) { return null; } @@ -878,18 +780,14 @@ protected Vec4 computeSelectedPointAt(Point point) // same proportions as the actual Globe. This will simulate dragging the selected position more accurately. Line ray = view.computeRayFromScreenPoint(point.getX(), point.getY()); Intersection[] intersections = this.wwd.getModel().getGlobe().intersect(ray, elevation); - if (intersections == null || intersections.length == 0) - { + if (intersections == null || intersections.length == 0) { return null; } return ray.nearestIntersectionPoint(intersections); } - - - protected LatLon getChangeInLocation(Point point1, Point point2, Vec4 vec1, Vec4 vec2) - { + protected LatLon getChangeInLocation(Point point1, Point point2, Vec4 vec1, Vec4 vec2) { // Modify the distance we'll actually travel based on the slope of world distance travelled to screen // distance travelled . A large slope means the user made a small change in screen space which resulted // in a large change in world space. We want to reduce the impact of that change to something reasonable. @@ -906,11 +804,9 @@ protected LatLon getChangeInLocation(Point point1, Point point2, Vec4 vec1, Vec4 return pos1.subtract(adjustedLocation); } - public double computeDragSlope(Point point1, Point point2, Vec4 vec1, Vec4 vec2) - { + public double computeDragSlope(Point point1, Point point2, Vec4 vec1, Vec4 vec2) { View view = this.getView(); - if (view == null) - { + if (view == null) { return 0.0; } @@ -926,59 +822,57 @@ public double computeDragSlope(Point point1, Point point2, Vec4 vec1, Vec4 vec2) // Return the ratio of world distance to screen distance. double slope = vec1.distanceTo3(vec2) / (pixelDistance * pixelSize); - if (slope < 1.0) + if (slope < 1.0) { slope = 1.0; + } return slope - 1.0; } - protected static Point constrainToSourceBounds(Point point, Object source) - { - if (point == null) + protected static Point constrainToSourceBounds(Point point, Object source) { + if (point == null) { return null; + } - if (!(source instanceof Component)) + if (!(source instanceof Component)) { return point; + } Component c = (Component) source; int x = (int) point.getX(); - if (x < 0) + if (x < 0) { x = 0; - if (x > c.getWidth()) + } + if (x > c.getWidth()) { x = c.getWidth(); + } int y = (int) point.getY(); - if (y < 0) + if (y < 0) { y = 0; - if (y > c.getHeight()) + } + if (y > c.getHeight()) { y = c.getHeight(); + } return new Point(x, y); } - - - public Point getMouseDownPoint() - { + public Point getMouseDownPoint() { return mouseDownPoint; } - public void setMouseDownPoint(Point mouseDownPoint) - { + public void setMouseDownPoint(Point mouseDownPoint) { this.mouseDownPoint = mouseDownPoint; } - protected void setMouseDownView(View mouseDownView) - { - if (mouseDownView != null) - { + protected void setMouseDownView(View mouseDownView) { + if (mouseDownView != null) { this.mouseDownModelview = mouseDownView.getModelviewMatrix(); this.mouseDownProjection = mouseDownView.getProjectionMatrix(); this.mouseDownViewport = mouseDownView.getViewport(); - } - else - { + } else { this.mouseDownModelview = null; this.mouseDownProjection = null; this.mouseDownViewport = null; diff --git a/src/gov/nasa/worldwind/awt/BasicViewInputHandler.java b/src/gov/nasa/worldwind/awt/BasicViewInputHandler.java index 4661447e46..09b45e7042 100644 --- a/src/gov/nasa/worldwind/awt/BasicViewInputHandler.java +++ b/src/gov/nasa/worldwind/awt/BasicViewInputHandler.java @@ -16,66 +16,59 @@ * @author dcollins * @version $Id: BasicViewInputHandler.java 2251 2014-08-21 21:17:46Z dcollins $ */ -public abstract class BasicViewInputHandler extends AbstractViewInputHandler -{ +public abstract class BasicViewInputHandler extends AbstractViewInputHandler { + protected abstract void onMoveTo(Position focalPosition, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttribs); + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttribs); protected abstract void onHorizontalTranslateRel(double forwardInput, double sideInput, - double sideInputFromMouseDown, double forwardInputFromMouseDown, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes); + double sideInputFromMouseDown, double forwardInputFromMouseDown, + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes); protected abstract void onVerticalTranslate(double translateChange, double totalTranslateChange, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes); + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes); protected abstract void onRotateView(double headingInput, double pitchInput, - double totalHeadingInput, double totalPitchInput, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes); + double totalHeadingInput, double totalPitchInput, + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes); protected abstract void onResetHeading(ViewInputAttributes.ActionAttributes actionAttribs); protected abstract void onResetHeadingPitchRoll(ViewInputAttributes.ActionAttributes actionAttribs); - public class RotateActionListener extends ViewInputActionHandler - { + public class RotateActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { java.util.List keyList = viewAction.getKeyActions(); double headingInput = 0; double pitchInput = 0; for (Object k : keyList) { - ViewInputAttributes.ActionAttributes.KeyAction keyAction = - (ViewInputAttributes.ActionAttributes.KeyAction) k; - if (keys.isKeyDown(keyAction.keyCode)) - { - if (keyAction.direction == ViewInputAttributes.ActionAttributes.KeyAction.KA_DIR_X) - { + ViewInputAttributes.ActionAttributes.KeyAction keyAction + = (ViewInputAttributes.ActionAttributes.KeyAction) k; + if (keys.isKeyDown(keyAction.keyCode)) { + if (keyAction.direction == ViewInputAttributes.ActionAttributes.KeyAction.KA_DIR_X) { headingInput += keyAction.sign; - } - else - { + } else { pitchInput += keyAction.sign; } } } - - if (headingInput == 0 && pitchInput == 0) - { + + if (headingInput == 0 && pitchInput == 0) { return false; } //noinspection StringEquality - if (target == GENERATE_EVENTS) - { + if (target == GENERATE_EVENTS) { - ViewInputAttributes.DeviceAttributes deviceAttributes = - inputHandler.getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_KEYBOARD); + ViewInputAttributes.DeviceAttributes deviceAttributes + = inputHandler.getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_KEYBOARD); onRotateView(headingInput, pitchInput, headingInput, pitchInput, deviceAttributes, viewAction); @@ -84,114 +77,98 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEv } } - public class HorizontalTransActionListener extends ViewInputActionHandler - { + public class HorizontalTransActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { double forwardInput = 0; double sideInput = 0; java.util.List keyList = viewAction.getKeyActions(); for (Object k : keyList) { - ViewInputAttributes.ActionAttributes.KeyAction keyAction = - (ViewInputAttributes.ActionAttributes.KeyAction) k; - if (keys.isKeyDown(keyAction.keyCode)) - { - if (keyAction.direction == ViewInputAttributes.ActionAttributes.KeyAction.KA_DIR_X) - { + ViewInputAttributes.ActionAttributes.KeyAction keyAction + = (ViewInputAttributes.ActionAttributes.KeyAction) k; + if (keys.isKeyDown(keyAction.keyCode)) { + if (keyAction.direction == ViewInputAttributes.ActionAttributes.KeyAction.KA_DIR_X) { sideInput += keyAction.sign; - } - else - { + } else { forwardInput += keyAction.sign; } } } - if (forwardInput == 0 && sideInput == 0) - { + if (forwardInput == 0 && sideInput == 0) { return false; } - //noinspection StringEquality - if (target == GENERATE_EVENTS) - { + if (target == GENERATE_EVENTS) { onHorizontalTranslateRel(forwardInput, sideInput, forwardInput, sideInput, - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_KEYBOARD),viewAction); + getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_KEYBOARD), viewAction); } return true; } - } - public class VerticalTransActionListener extends ViewInputActionHandler - { + public class VerticalTransActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { double transInput = 0; java.util.List keyList = viewAction.getKeyActions(); for (Object k : keyList) { - ViewInputAttributes.ActionAttributes.KeyAction keyAction = - (ViewInputAttributes.ActionAttributes.KeyAction) k; + ViewInputAttributes.ActionAttributes.KeyAction keyAction + = (ViewInputAttributes.ActionAttributes.KeyAction) k; - if (keys.isKeyDown(keyAction.keyCode)) + if (keys.isKeyDown(keyAction.keyCode)) { transInput += keyAction.sign; + } } - if (transInput == 0) - { + if (transInput == 0) { return false; } //noinspection StringEquality - if (target == GENERATE_EVENTS) - { - - ViewInputAttributes.DeviceAttributes deviceAttributes = - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_KEYBOARD); - + if (target == GENERATE_EVENTS) { + + ViewInputAttributes.DeviceAttributes deviceAttributes + = getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_KEYBOARD); + onVerticalTranslate(transInput, transInput, deviceAttributes, viewAction); } return true; } - } - public class RotateMouseActionListener extends ViewInputActionHandler - { + public class RotateMouseActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction) - { - + ViewInputAttributes.ActionAttributes viewAction) { + boolean handleThisEvent = false; java.util.List buttonList = viewAction.getMouseActions(); for (Object b : buttonList) { - ViewInputAttributes.ActionAttributes.MouseAction buttonAction = - (ViewInputAttributes.ActionAttributes.MouseAction) b; - if ((keys.getMouseModifiersEx() & buttonAction.mouseButton) != 0) - { + ViewInputAttributes.ActionAttributes.MouseAction buttonAction + = (ViewInputAttributes.ActionAttributes.MouseAction) b; + if ((keys.getMouseModifiersEx() & buttonAction.mouseButton) != 0) { handleThisEvent = true; } } - if (!handleThisEvent) - { + if (!handleThisEvent) { return false; } Point point = constrainToSourceBounds(getMousePoint(), getWorldWindow()); Point lastPoint = constrainToSourceBounds(getLastMousePoint(), getWorldWindow()); Point mouseDownPoint = constrainToSourceBounds(getMouseDownPoint(), getWorldWindow()); - if (point == null || lastPoint == null) - { + if (point == null || lastPoint == null) { return false; } @@ -202,89 +179,80 @@ public boolean inputActionPerformed(KeyEventState keys, String target, int totalHeadingInput = totalMovement.x; int totalPitchInput = totalMovement.y; - ViewInputAttributes.DeviceAttributes deviceAttributes = - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); + ViewInputAttributes.DeviceAttributes deviceAttributes + = getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); onRotateView(headingInput, pitchInput, totalHeadingInput, totalPitchInput, - deviceAttributes, viewAction); + deviceAttributes, viewAction); return true; } - public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) - { + java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) { boolean handleThisEvent = false; java.util.List buttonList = viewAction.getMouseActions(); for (Object b : buttonList) { - ViewInputAttributes.ActionAttributes.MouseAction buttonAction = - (ViewInputAttributes.ActionAttributes.MouseAction) b; - if ((mouseEvent.getModifiersEx() & buttonAction.mouseButton) != 0) - { - handleThisEvent = true; + ViewInputAttributes.ActionAttributes.MouseAction buttonAction + = (ViewInputAttributes.ActionAttributes.MouseAction) b; + if ((mouseEvent.getModifiersEx() & buttonAction.mouseButton) != 0) { + handleThisEvent = true; } } - if (!handleThisEvent) - { + if (!handleThisEvent) { return false; } Point point = constrainToSourceBounds(getMousePoint(), getWorldWindow()); Point lastPoint = constrainToSourceBounds(getLastMousePoint(), getWorldWindow()); Point mouseDownPoint = constrainToSourceBounds(getMouseDownPoint(), getWorldWindow()); - if (point == null || lastPoint == null) - { + if (point == null || lastPoint == null) { return false; } Point movement = ViewUtil.subtract(point, lastPoint); int headingInput = movement.x; int pitchInput = movement.y; - if (mouseDownPoint == null) + if (mouseDownPoint == null) { mouseDownPoint = lastPoint; + } Point totalMovement = ViewUtil.subtract(point, mouseDownPoint); int totalHeadingInput = totalMovement.x; int totalPitchInput = totalMovement.y; - - - ViewInputAttributes.DeviceAttributes deviceAttributes = - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); + ViewInputAttributes.DeviceAttributes deviceAttributes + = getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); onRotateView(headingInput, pitchInput, totalHeadingInput, totalPitchInput, - deviceAttributes, viewAction); + deviceAttributes, viewAction); return true; } } - public class HorizTransMouseActionListener extends ViewInputActionHandler - { + public class HorizTransMouseActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed( - KeyEventState keys, String target, ViewInputAttributes.ActionAttributes viewAction) - { - + KeyEventState keys, String target, ViewInputAttributes.ActionAttributes viewAction) { + boolean handleThisEvent = false; java.util.List buttonList = viewAction.getMouseActions(); for (Object b : buttonList) { - ViewInputAttributes.ActionAttributes.MouseAction buttonAction = - (ViewInputAttributes.ActionAttributes.MouseAction) b; - if ((keys.getMouseModifiersEx() & buttonAction.mouseButton) != 0) - { + ViewInputAttributes.ActionAttributes.MouseAction buttonAction + = (ViewInputAttributes.ActionAttributes.MouseAction) b; + if ((keys.getMouseModifiersEx() & buttonAction.mouseButton) != 0) { handleThisEvent = true; } } - if (!handleThisEvent) - { + if (!handleThisEvent) { return false; } - if (target == GENERATE_EVENTS) - { + if (target == GENERATE_EVENTS) { Point point = constrainToSourceBounds(getMousePoint(), getWorldWindow()); Point lastPoint = constrainToSourceBounds(getLastMousePoint(), getWorldWindow()); Point mouseDownPoint = constrainToSourceBounds(getMouseDownPoint(), getWorldWindow()); Point movement = ViewUtil.subtract(point, lastPoint); - if (point == null || lastPoint == null) + if (point == null || lastPoint == null) { return false; + } int forwardInput = movement.y; int sideInput = -movement.x; @@ -292,39 +260,35 @@ public boolean inputActionPerformed( int totalForward = totalMovement.y; int totalSide = -totalMovement.x; - ViewInputAttributes.DeviceAttributes deviceAttributes = - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); + ViewInputAttributes.DeviceAttributes deviceAttributes + = getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); onHorizontalTranslateRel(forwardInput, sideInput, totalForward, totalSide, deviceAttributes, - viewAction); + viewAction); } - return(true); + return (true); } public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) - { + java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) { boolean handleThisEvent = false; java.util.List buttonList = viewAction.getMouseActions(); for (Object b : buttonList) { - ViewInputAttributes.ActionAttributes.MouseAction buttonAction = - (ViewInputAttributes.ActionAttributes.MouseAction) b; - if ((mouseEvent.getModifiersEx() & buttonAction.mouseButton) != 0) - { + ViewInputAttributes.ActionAttributes.MouseAction buttonAction + = (ViewInputAttributes.ActionAttributes.MouseAction) b; + if ((mouseEvent.getModifiersEx() & buttonAction.mouseButton) != 0) { handleThisEvent = true; } } - if (!handleThisEvent) - { + if (!handleThisEvent) { return false; } Point point = constrainToSourceBounds(getMousePoint(), getWorldWindow()); Point lastPoint = constrainToSourceBounds(getLastMousePoint(), getWorldWindow()); Point mouseDownPoint = constrainToSourceBounds(getMouseDownPoint(), getWorldWindow()); - if (point == null || lastPoint == null || mouseDownPoint == null) - { - return(false); + if (point == null || lastPoint == null || mouseDownPoint == null) { + return (false); } Point movement = ViewUtil.subtract(point, lastPoint); int forwardInput = movement.y; @@ -334,42 +298,37 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, int totalForward = totalMovement.y; int totalSide = -totalMovement.x; - ViewInputAttributes.DeviceAttributes deviceAttributes = - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); + ViewInputAttributes.DeviceAttributes deviceAttributes + = getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); onHorizontalTranslateRel(forwardInput, sideInput, totalForward, totalSide, deviceAttributes, - viewAction); + viewAction); - return(true); + return (true); } } + public class VertTransMouseActionListener extends ViewInputActionHandler { - public class VertTransMouseActionListener extends ViewInputActionHandler - { public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) - { + java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) { boolean handleThisEvent = false; java.util.List buttonList = viewAction.getMouseActions(); for (java.lang.Object b : buttonList) { - ViewInputAttributes.ActionAttributes.MouseAction buttonAction = - (ViewInputAttributes.ActionAttributes.MouseAction) b; - if ((mouseEvent.getModifiersEx() & buttonAction.mouseButton) != 0) - { + ViewInputAttributes.ActionAttributes.MouseAction buttonAction + = (ViewInputAttributes.ActionAttributes.MouseAction) b; + if ((mouseEvent.getModifiersEx() & buttonAction.mouseButton) != 0) { handleThisEvent = true; } } - if (!handleThisEvent) - { + if (!handleThisEvent) { return false; } Point point = constrainToSourceBounds(getMousePoint(), getWorldWindow()); Point lastPoint = constrainToSourceBounds(getLastMousePoint(), getWorldWindow()); Point mouseDownPoint = constrainToSourceBounds(getMouseDownPoint(), getWorldWindow()); - if (point == null || lastPoint == null || mouseDownPoint == null) - { + if (point == null || lastPoint == null || mouseDownPoint == null) { return false; } @@ -378,37 +337,32 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, Point totalMovement = ViewUtil.subtract(point, mouseDownPoint); int totalTranslationInput = totalMovement.y; - - ViewInputAttributes.DeviceAttributes deviceAttributes = - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); + ViewInputAttributes.DeviceAttributes deviceAttributes + = getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); onVerticalTranslate((double) translationInput, totalTranslationInput, deviceAttributes, viewAction); return true; } public boolean inputActionPerformed( - KeyEventState keys, String target, ViewInputAttributes.ActionAttributes viewAction) - { + KeyEventState keys, String target, ViewInputAttributes.ActionAttributes viewAction) { boolean handleThisEvent = false; java.util.List buttonList = viewAction.getMouseActions(); for (java.lang.Object b : buttonList) { - ViewInputAttributes.ActionAttributes.MouseAction buttonAction = - (ViewInputAttributes.ActionAttributes.MouseAction) b; - if ((keys.getMouseModifiersEx() & buttonAction.mouseButton) != 0) - { + ViewInputAttributes.ActionAttributes.MouseAction buttonAction + = (ViewInputAttributes.ActionAttributes.MouseAction) b; + if ((keys.getMouseModifiersEx() & buttonAction.mouseButton) != 0) { handleThisEvent = true; } } - if (!handleThisEvent) - { + if (!handleThisEvent) { return false; } Point point = constrainToSourceBounds(getMousePoint(), getWorldWindow()); Point lastPoint = constrainToSourceBounds(getLastMousePoint(), getWorldWindow()); Point mouseDownPoint = constrainToSourceBounds(getMouseDownPoint(), getWorldWindow()); - if (point == null || lastPoint == null) - { + if (point == null || lastPoint == null) { return false; } @@ -417,37 +371,32 @@ public boolean inputActionPerformed( Point totalMovement = ViewUtil.subtract(point, mouseDownPoint); int totalTranslationInput = totalMovement.y; - - ViewInputAttributes.DeviceAttributes deviceAttributes = - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); + ViewInputAttributes.DeviceAttributes deviceAttributes + = getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE); onVerticalTranslate((double) translationInput, totalTranslationInput, deviceAttributes, viewAction); return true; } } - public class MoveToMouseActionListener extends ViewInputActionHandler - { + public class MoveToMouseActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) - { + java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) { boolean handleThisEvent = false; java.util.List buttonList = viewAction.getMouseActions(); for (Object b : buttonList) { - ViewInputAttributes.ActionAttributes.MouseAction buttonAction = - (ViewInputAttributes.ActionAttributes.MouseAction) b; - if ((mouseEvent.getButton() == buttonAction.mouseButton)) - { + ViewInputAttributes.ActionAttributes.MouseAction buttonAction + = (ViewInputAttributes.ActionAttributes.MouseAction) b; + if ((mouseEvent.getButton() == buttonAction.mouseButton)) { handleThisEvent = true; } } - if (!handleThisEvent) - { + if (!handleThisEvent) { return false; } Position pos = computeSelectedPosition(); - if (pos == null) - { + if (pos == null) { return false; } @@ -456,18 +405,15 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, } } - public class ResetHeadingActionListener extends ViewInputActionHandler - { + public class ResetHeadingActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java.awt.event.KeyEvent event, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { java.util.List keyList = viewAction.getKeyActions(); - for (Object k : keyList) - { - ViewInputAttributes.ActionAttributes.KeyAction keyAction = - (ViewInputAttributes.ActionAttributes.KeyAction) k; - if (event.getKeyCode() == keyAction.keyCode) - { + for (Object k : keyList) { + ViewInputAttributes.ActionAttributes.KeyAction keyAction + = (ViewInputAttributes.ActionAttributes.KeyAction) k; + if (event.getKeyCode() == keyAction.keyCode) { onResetHeading(viewAction); return true; } @@ -477,18 +423,15 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java. } - public class ResetHeadingPitchActionListener extends ViewInputActionHandler - { + public class ResetHeadingPitchActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java.awt.event.KeyEvent event, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { java.util.List keyList = viewAction.getKeyActions(); - for (Object k : keyList) - { - ViewInputAttributes.ActionAttributes.KeyAction keyAction = - (ViewInputAttributes.ActionAttributes.KeyAction) k; - if (event.getKeyCode() == keyAction.keyCode) - { + for (Object k : keyList) { + ViewInputAttributes.ActionAttributes.KeyAction keyAction + = (ViewInputAttributes.ActionAttributes.KeyAction) k; + if (event.getKeyCode() == keyAction.keyCode) { onResetHeadingPitchRoll(viewAction); return true; } @@ -497,37 +440,33 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java. } } - public class StopViewActionListener extends ViewInputActionHandler - { + public class StopViewActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java.awt.event.KeyEvent event, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { java.util.List keyList = viewAction.getKeyActions(); - for (Object k : keyList) - { - ViewInputAttributes.ActionAttributes.KeyAction keyAction = - (ViewInputAttributes.ActionAttributes.KeyAction) k; - if (event.getKeyCode() == keyAction.keyCode) - { + for (Object k : keyList) { + ViewInputAttributes.ActionAttributes.KeyAction keyAction + = (ViewInputAttributes.ActionAttributes.KeyAction) k; + if (event.getKeyCode() == keyAction.keyCode) { onStopView(); return true; } } return false; } - + } - public class VertTransMouseWheelActionListener extends ViewInputActionHandler - { + public class VertTransMouseWheelActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseWheelEvent mouseWheelEvent, ViewInputAttributes.ActionAttributes viewAction) - { + java.awt.event.MouseWheelEvent mouseWheelEvent, ViewInputAttributes.ActionAttributes viewAction) { double zoomInput = mouseWheelEvent.getWheelRotation(); - ViewInputAttributes.DeviceAttributes deviceAttributes = - getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE_WHEEL); + ViewInputAttributes.DeviceAttributes deviceAttributes + = getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_MOUSE_WHEEL); onVerticalTranslate(zoomInput, zoomInput, deviceAttributes, viewAction); return true; @@ -535,80 +474,77 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, } } - - - public BasicViewInputHandler() - { + public BasicViewInputHandler() { ViewInputAttributes.ActionAttributes actionAttrs; // Get action maps for mouse and keyboard // ----------------------------------Key Rotation -------------------------------------------- RotateActionListener rotateActionListener = new RotateActionListener(); this.getAttributes().setActionListener( - ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROTATE_KEYS, rotateActionListener); + ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROTATE_KEYS, rotateActionListener); this.getAttributes().setActionListener( - ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROTATE_SLOW, rotateActionListener); + ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROTATE_SLOW, rotateActionListener); this.getAttributes().setActionListener( - ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROTATE_KEYS_SHIFT, rotateActionListener); + ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROTATE_KEYS_SHIFT, rotateActionListener); this.getAttributes().setActionListener( - ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROTATE_KEYS_SHIFT_SLOW, rotateActionListener); + ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROTATE_KEYS_SHIFT_SLOW, rotateActionListener); // ----------------------------------Key Vertical Translation -------------------------------- VerticalTransActionListener vertActionsListener = new VerticalTransActionListener(); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_CTRL); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_CTRL); actionAttrs.setActionListener(vertActionsListener); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_SLOW_CTRL); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_SLOW_CTRL); actionAttrs.setActionListener(vertActionsListener); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS); actionAttrs.setActionListener(vertActionsListener); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_SLOW); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_SLOW); actionAttrs.setActionListener(vertActionsListener); // ----------------------------------Key Horizontal Translation ------------------------------ HorizontalTransActionListener horizTransActionListener = new HorizontalTransActionListener(); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_HORIZONTAL_TRANS_KEYS); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_HORIZONTAL_TRANS_KEYS); actionAttrs.setActionListener(horizTransActionListener); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE_SLOW); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE_SLOW); actionAttrs.setActionListener(horizTransActionListener); // -------------------------------- Mouse Rotation ------------------------------------------- RotateMouseActionListener rotateMouseListener = new RotateMouseActionListener(); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( - ViewInputAttributes.VIEW_ROTATE); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( + ViewInputAttributes.VIEW_ROTATE); actionAttrs.setMouseActionListener(rotateMouseListener); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( - ViewInputAttributes.VIEW_ROTATE_SHIFT); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( + ViewInputAttributes.VIEW_ROTATE_SHIFT); actionAttrs.setMouseActionListener(rotateMouseListener); // ----------------------------- Mouse Horizontal Translation -------------------------------- - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( - ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( + ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE); actionAttrs.setMouseActionListener(new HorizTransMouseActionListener()); // ----------------------------- Mouse Vertical Translation ---------------------------------- VertTransMouseActionListener vertTransListener = new VertTransMouseActionListener(); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE); actionAttrs.setMouseActionListener(vertTransListener); - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE_CTRL); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE_CTRL); actionAttrs.setMouseActionListener(vertTransListener); // Move to mouse @@ -617,175 +553,136 @@ public BasicViewInputHandler() actionAttrs.setMouseActionListener(new MoveToMouseActionListener()); // Reset Heading - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_RESET_HEADING); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_RESET_HEADING); actionAttrs.setActionListener(new ResetHeadingActionListener()); // Reset Heading and Pitch - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_RESET_HEADING_PITCH_ROLL); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_RESET_HEADING_PITCH_ROLL); actionAttrs.setActionListener(new ResetHeadingPitchActionListener()); // Stop View - actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ViewInputAttributes.VIEW_STOP_VIEW); + actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ViewInputAttributes.VIEW_STOP_VIEW); actionAttrs.setActionListener(new StopViewActionListener()); - // Mouse Wheel vertical translate actionAttrs = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE_WHEEL).getActionAttributes( - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE); + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE); actionAttrs.setMouseActionListener(new VertTransMouseWheelActionListener()); - - - } - public void apply() - { + public void apply() { super.apply(); } //**************************************************************// //******************** Key Events ****************************// //**************************************************************// - protected void handleKeyPressed(KeyEvent e) - { + protected void handleKeyPressed(KeyEvent e) { boolean eventHandled = false; - - Integer modifier = e.getModifiersEx(); - for (int i = 0; i < NUM_MODIFIERS; i++) - { - if ((((modifier & this.modifierList[i]) == this.modifierList[i]))) - { - ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) - keyModsActionMap.get(this.modifierList[i]); + Integer modifier = e.getModifiersEx(); + for (int i = 0; i < NUM_MODIFIERS; i++) { + if ((((modifier & this.modifierList[i]) == this.modifierList[i]))) { + ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) keyModsActionMap.get(this.modifierList[i]); eventHandled = callActionListListeners(e, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_PRESS, actionList); + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_PRESS, actionList); } } - if (!eventHandled) - { - super.handleKeyPressed(e); + if (!eventHandled) { + super.handleKeyPressed(e); } - } //**************************************************************// //******************** Mouse Events **************************// //**************************************************************// - protected void handleMouseClicked(MouseEvent e) - { + protected void handleMouseClicked(MouseEvent e) { boolean eventHandled = false; - - Integer modifier = e.getModifiersEx(); - for (int i = 0; i < NUM_MODIFIERS; i++) - { - if ((((modifier & this.modifierList[i]) == this.modifierList[i]))) - { - ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) - mouseModsActionMap.get(this.modifierList[i]); + Integer modifier = e.getModifiersEx(); + for (int i = 0; i < NUM_MODIFIERS; i++) { + if ((((modifier & this.modifierList[i]) == this.modifierList[i]))) { + ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) mouseModsActionMap.get(this.modifierList[i]); eventHandled = callMouseActionListListeners(e, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_PRESS, actionList); + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_PRESS, actionList); } } - if (!eventHandled) - { + if (!eventHandled) { super.handleMouseClicked(e); } } - protected void handleMouseWheelMoved(MouseWheelEvent e) - { + protected void handleMouseWheelMoved(MouseWheelEvent e) { boolean eventHandled = false; // TODO : Make this conditional look like handleMouseDragged - Integer modifier = e.getModifiersEx(); - for (int i = 0; i < NUM_MODIFIERS; i++) - { - if ((((modifier & this.modifierList[i]) == this.modifierList[i]))) - { - ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) - mouseWheelModsActionMap.get(this.modifierList[i]); + Integer modifier = e.getModifiersEx(); + for (int i = 0; i < NUM_MODIFIERS; i++) { + if ((((modifier & this.modifierList[i]) == this.modifierList[i]))) { + ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) mouseWheelModsActionMap.get(this.modifierList[i]); eventHandled = callMouseWheelActionListListeners(e, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_DRAG, actionList); + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_DRAG, actionList); } } - if (!eventHandled) - { + if (!eventHandled) { super.handleMouseWheelMoved(e); } } - - //**************************************************************// //******************** Mouse Motion Events *******************// //**************************************************************// - protected void handleMouseDragged(MouseEvent e) - { + protected void handleMouseDragged(MouseEvent e) { - int modifier = e.getModifiersEx(); + int modifier = e.getModifiersEx(); - for (int i = 0; i < NUM_MODIFIERS; i++) - { - if ((((modifier & this.modifierList[i]) == this.modifierList[i]))) - { - ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) - mouseModsActionMap.get(this.modifierList[i]); + for (int i = 0; i < NUM_MODIFIERS; i++) { + if ((((modifier & this.modifierList[i]) == this.modifierList[i]))) { + ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) mouseModsActionMap.get(this.modifierList[i]); if (callMouseActionListListeners(e, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_DRAG, actionList)) - { + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_DRAG, actionList)) { return; } } } - - } - + } //**************************************************************// //******************** Rendering Events **********************// //**************************************************************// - // Interpret the current key state according to the specified target. If the target is KEY_POLL_GENERATE_EVENTS, // then the the key state will generate any appropriate view change events. If the target is KEY_POLL_QUERY_EVENTS, // then the key state will not generate events, and this will return whether or not any view change events would // have been generated. - protected boolean handlePerFrameKeyState(KeyEventState keys, String target) - { + protected boolean handlePerFrameKeyState(KeyEventState keys, String target) { - if (keys.getNumKeysDown() == 0) - { + if (keys.getNumKeysDown() == 0) { return false; } boolean isKeyEventTrigger = false; + Integer modifier = keys.getModifiersEx(); + for (int i = 0; i < NUM_MODIFIERS; i++) { + if (((modifier & this.modifierList[i]) == this.modifierList[i])) { - Integer modifier = keys.getModifiersEx(); - for (int i = 0; i < NUM_MODIFIERS; i++) - { - if (((modifier & this.modifierList[i]) == this.modifierList[i])) - { - - ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) - keyModsActionMap.get(this.modifierList[i]); + ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) keyModsActionMap.get(this.modifierList[i]); isKeyEventTrigger = callActionListListeners(keys, target, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN, actionList); + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN, actionList); break; } } @@ -793,54 +690,42 @@ protected boolean handlePerFrameKeyState(KeyEventState keys, String target) return isKeyEventTrigger; } - protected boolean handlePerFrameMouseState(KeyEventState keys, String target) - { + protected boolean handlePerFrameMouseState(KeyEventState keys, String target) { boolean eventHandled = false; - if (keys.getNumButtonsDown() == 0) - { + if (keys.getNumButtonsDown() == 0) { return false; } + Integer modifier = keys.getModifiersEx(); - Integer modifier = keys.getModifiersEx(); + for (int i = 0; i < NUM_MODIFIERS; i++) { + if (((modifier & this.modifierList[i]) == this.modifierList[i])) { - for (int i = 0; i < NUM_MODIFIERS; i++) - { - if (((modifier & this.modifierList[i]) == this.modifierList[i])) - { - - ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) - mouseModsActionMap.get(this.modifierList[i]); + ViewInputAttributes.ActionAttributesList actionList = (ViewInputAttributes.ActionAttributesList) mouseModsActionMap.get(this.modifierList[i]); if (callActionListListeners(keys, target, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN, actionList)) - { - + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN, actionList)) { + return true; } } } - - return(eventHandled); + + return (eventHandled); } protected boolean callMouseActionListListeners(MouseEvent e, - ViewInputAttributes.ActionAttributes.ActionTrigger trigger, - ViewInputAttributes.ActionAttributesList actionList) - { + ViewInputAttributes.ActionAttributes.ActionTrigger trigger, + ViewInputAttributes.ActionAttributesList actionList) { boolean eventHandled = false; - if (actionList != null) - { - for (ViewInputAttributes.ActionAttributes actionAttr : actionList) - { - if (actionAttr.getMouseActionListener() == null || - actionAttr.getActionTrigger() != trigger) - { + if (actionList != null) { + for (ViewInputAttributes.ActionAttributes actionAttr : actionList) { + if (actionAttr.getMouseActionListener() == null + || actionAttr.getActionTrigger() != trigger) { continue; } - if (actionAttr.getMouseActionListener().inputActionPerformed(this, e, actionAttr)) - { + if (actionAttr.getMouseActionListener().inputActionPerformed(this, e, actionAttr)) { eventHandled = true; } } @@ -850,21 +735,16 @@ protected boolean callMouseActionListListeners(MouseEvent e, } protected boolean callMouseWheelActionListListeners(MouseWheelEvent e, - ViewInputAttributes.ActionAttributes.ActionTrigger trigger, - ViewInputAttributes.ActionAttributesList actionList) - { + ViewInputAttributes.ActionAttributes.ActionTrigger trigger, + ViewInputAttributes.ActionAttributesList actionList) { boolean eventHandled = false; - if (actionList != null) - { - for (ViewInputAttributes.ActionAttributes actionAttr : actionList) - { - if (actionAttr.getMouseActionListener() == null || - actionAttr.getActionTrigger() != trigger) - { + if (actionList != null) { + for (ViewInputAttributes.ActionAttributes actionAttr : actionList) { + if (actionAttr.getMouseActionListener() == null + || actionAttr.getActionTrigger() != trigger) { continue; } - if (actionAttr.getMouseActionListener().inputActionPerformed(this, e, actionAttr)) - { + if (actionAttr.getMouseActionListener().inputActionPerformed(this, e, actionAttr)) { eventHandled = true; } } @@ -874,21 +754,16 @@ protected boolean callMouseWheelActionListListeners(MouseWheelEvent e, } protected boolean callActionListListeners(KeyEvent e, - ViewInputAttributes.ActionAttributes.ActionTrigger trigger, - ViewInputAttributes.ActionAttributesList actionList) - { + ViewInputAttributes.ActionAttributes.ActionTrigger trigger, + ViewInputAttributes.ActionAttributesList actionList) { boolean eventHandled = false; - if (actionList != null) - { - for (ViewInputAttributes.ActionAttributes actionAttr : actionList) - { - if (actionAttr.getActionListener() == null || - actionAttr.getActionTrigger() != trigger) - { + if (actionList != null) { + for (ViewInputAttributes.ActionAttributes actionAttr : actionList) { + if (actionAttr.getActionListener() == null + || actionAttr.getActionTrigger() != trigger) { continue; } - if (actionAttr.getActionListener().inputActionPerformed(this, e, actionAttr)) - { + if (actionAttr.getActionListener().inputActionPerformed(this, e, actionAttr)) { eventHandled = true; } } @@ -897,21 +772,16 @@ protected boolean callActionListListeners(KeyEvent e, } protected boolean callActionListListeners(KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes.ActionTrigger trigger, - ViewInputAttributes.ActionAttributesList actionList) - { + ViewInputAttributes.ActionAttributes.ActionTrigger trigger, + ViewInputAttributes.ActionAttributesList actionList) { boolean eventHandled = false; - if (actionList != null) - { - for (ViewInputAttributes.ActionAttributes actionAttr : actionList) - { - if (actionAttr.getActionTrigger() != trigger) - { + if (actionList != null) { + for (ViewInputAttributes.ActionAttributes actionAttr : actionList) { + if (actionAttr.getActionTrigger() != trigger) { continue; } - if (callActionListener(keys, target, actionAttr)) - { + if (callActionListener(keys, target, actionAttr)) { eventHandled = true; } @@ -921,17 +791,14 @@ protected boolean callActionListListeners(KeyEventState keys, String target, return eventHandled; } - protected boolean callActionListener (KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes action) - { + protected boolean callActionListener(KeyEventState keys, String target, + ViewInputAttributes.ActionAttributes action) { - if (action.getActionListener() != null) - { - return(action.getActionListener().inputActionPerformed(this, keys, target, action)); + if (action.getActionListener() != null) { + return (action.getActionListener().inputActionPerformed(this, keys, target, action)); } - if (action.getMouseActionListener() != null) - { - return(action.getMouseActionListener().inputActionPerformed(keys, target, action)); + if (action.getMouseActionListener() != null) { + return (action.getMouseActionListener().inputActionPerformed(keys, target, action)); } return false; @@ -940,20 +807,16 @@ protected boolean callActionListener (KeyEventState keys, String target, //**************************************************************// //******************** Property Change Events ****************// //**************************************************************// - - protected void handlePropertyChange(java.beans.PropertyChangeEvent e) - { + protected void handlePropertyChange(java.beans.PropertyChangeEvent e) { super.handlePropertyChange(e); - //noinspection StringEquality - if (e.getPropertyName() == View.VIEW_STOPPED) - { + //noinspection StringEquality + if (e.getPropertyName() == View.VIEW_STOPPED) { this.handleViewStopped(); } } - protected void handleViewStopped() - { + protected void handleViewStopped() { } } diff --git a/src/gov/nasa/worldwind/awt/KeyEventState.java b/src/gov/nasa/worldwind/awt/KeyEventState.java index 86889c05b7..f16e016810 100644 --- a/src/gov/nasa/worldwind/awt/KeyEventState.java +++ b/src/gov/nasa/worldwind/awt/KeyEventState.java @@ -12,34 +12,29 @@ * @author dcollins * @version $Id: KeyEventState.java 2193 2014-08-01 23:33:16Z dcollins $ */ -public class KeyEventState implements KeyListener, MouseListener -{ - protected static class InputState - { +public class KeyEventState implements KeyListener, MouseListener { + + protected static class InputState { protected int eventType; protected int keyOrButtonCode; protected long timestamp; - public InputState(int eventType, int keyOrButtonCode, long timestamp) - { + public InputState(int eventType, int keyOrButtonCode, long timestamp) { this.eventType = eventType; this.keyOrButtonCode = keyOrButtonCode; this.timestamp = timestamp; } - public int getEventType() - { + public int getEventType() { return this.eventType; } - public int getKeyOrButtonCode() - { + public int getKeyOrButtonCode() { return this.keyOrButtonCode; } - public long getTimestamp() - { + public long getTimestamp() { return this.timestamp; } } @@ -50,84 +45,68 @@ public long getTimestamp() protected int mouseModifiers; protected int mouseModifiersEx; - public KeyEventState() - { + public KeyEventState() { } - public boolean isKeyDown(int keyCode) - { + public boolean isKeyDown(int keyCode) { InputState state = this.getKeyState(keyCode); return state != null && state.getEventType() == KeyEvent.KEY_PRESSED; } - public int keyState(int keyCode) - { + public int keyState(int keyCode) { InputState state = this.getKeyState(keyCode); return state != null && state.getEventType() == KeyEvent.KEY_PRESSED ? 1 : 0; } - public int getNumKeysDown() - { - if (keyStateMap.isEmpty()) - { - return(0); + public int getNumKeysDown() { + if (keyStateMap.isEmpty()) { + return (0); } int numKeys = 0; - for (Object o : this.keyStateMap.keySet()) - { + for (Object o : this.keyStateMap.keySet()) { //Integer key = (KeyEvent) o; InputState is = this.keyStateMap.get(o); - if (is.getEventType() == KeyEvent.KEY_PRESSED) - { + if (is.getEventType() == KeyEvent.KEY_PRESSED) { numKeys++; } } - return(numKeys); + return (numKeys); } - public int getNumButtonsDown() - { - if (keyStateMap.isEmpty()) - { - return(0); + public int getNumButtonsDown() { + if (keyStateMap.isEmpty()) { + return (0); } int numKeys = 0; - for (Object o : this.keyStateMap.keySet()) - { + for (Object o : this.keyStateMap.keySet()) { //Integer key = (KeyEvent) o; InputState is = this.keyStateMap.get(o); - if (is.getEventType() == MouseEvent.MOUSE_PRESSED) - { + if (is.getEventType() == MouseEvent.MOUSE_PRESSED) { numKeys++; } } - return(numKeys); + return (numKeys); } - public int getModifiers() - { + public int getModifiers() { return this.modifiers; } - public int getModifiersEx() - { + public int getModifiersEx() { return this.modifiersEx; } - public int getMouseModifiers() - { + public int getMouseModifiers() { return this.mouseModifiers; } - public int getMouseModifiersEx() - { + public int getMouseModifiersEx() { return this.mouseModifiersEx; } - public void clearKeyState() - { + public void clearKeyState() { this.keyStateMap.clear(); this.modifiers = 0; this.modifiersEx = 0; @@ -136,26 +115,23 @@ public void clearKeyState() } @Override - public void keyTyped(KeyEvent e) - { + public void keyTyped(KeyEvent e) { } @Override - public void keyPressed(KeyEvent e) - { + public void keyPressed(KeyEvent e) { this.onKeyEvent(e, KeyEvent.KEY_PRESSED); } @Override - public void keyReleased(KeyEvent e) - { + public void keyReleased(KeyEvent e) { this.removeKeyState(e); } - protected void onKeyEvent(KeyEvent e, int eventType) - { - if (e == null) + protected void onKeyEvent(KeyEvent e, int eventType) { + if (e == null) { return; + } long timestamp = this.getTimeStamp(e, eventType, this.keyStateMap.get(e.getKeyCode())); this.setKeyState(e.getKeyCode(), new InputState(eventType, e.getKeyCode(), timestamp)); @@ -164,80 +140,67 @@ protected void onKeyEvent(KeyEvent e, int eventType) } @Override - public void mouseClicked(java.awt.event.MouseEvent mouseEvent) - { + public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { } @Override - public void mousePressed(java.awt.event.MouseEvent e) - { + public void mousePressed(java.awt.event.MouseEvent e) { long timestamp = this.getTimeStamp(e, MouseEvent.MOUSE_PRESSED, this.keyStateMap.get(e.getModifiersEx())); this.setKeyState(e.getButton(), new InputState(MouseEvent.MOUSE_PRESSED, e.getButton(), timestamp)); this.setMouseModifiers(e.getModifiers()); this.setMouseModifiersEx(e.getModifiersEx()); } - public void mouseReleased(java.awt.event.MouseEvent e) - { + public void mouseReleased(java.awt.event.MouseEvent e) { this.keyStateMap.remove(e.getButton()); this.setMouseModifiers(0); this.setMouseModifiersEx(0); } - public void mouseEntered(java.awt.event.MouseEvent mouseEvent) - { + public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } - public void mouseExited(java.awt.event.MouseEvent mouseEvent) - { - + public void mouseExited(java.awt.event.MouseEvent mouseEvent) { + } - protected InputState getKeyState(int keyCode) - { + protected InputState getKeyState(int keyCode) { return this.keyStateMap.get(keyCode); } - protected void setKeyState(int keyCode, InputState state) - { + protected void setKeyState(int keyCode, InputState state) { this.keyStateMap.put(keyCode, state); } - protected void setModifiers(int modifiers) - { + protected void setModifiers(int modifiers) { this.modifiers = modifiers; } - protected void setModifiersEx(int modifiersEx) - { + protected void setModifiersEx(int modifiersEx) { this.modifiersEx = modifiersEx; } - protected void setMouseModifiersEx(int modifiersEx) - { + protected void setMouseModifiersEx(int modifiersEx) { this.mouseModifiersEx = modifiersEx; } - protected void setMouseModifiers(int modifiers) - { + protected void setMouseModifiers(int modifiers) { this.mouseModifiers = modifiers; } - - protected void removeKeyState(KeyEvent e) { this.keyStateMap.remove(e.getKeyCode()); this.setModifiers(e.getModifiers()); this.setModifiersEx(e.getModifiersEx()); } - protected long getTimeStamp(InputEvent e, int eventType, InputState currentState) - { + protected long getTimeStamp(InputEvent e, int eventType, InputState currentState) { // If the current state for this input event type exists and is not null, then keep the current timestamp. - if (currentState != null && currentState.getEventType() == eventType) + if (currentState != null && currentState.getEventType() == eventType) { return currentState.getTimestamp(); + } // Otherwise return the InputEvent's timestamp. return e.getWhen(); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/awt/KeyInputActionHandler.java b/src/gov/nasa/worldwind/awt/KeyInputActionHandler.java index 1bbb8da755..be640ec9f4 100644 --- a/src/gov/nasa/worldwind/awt/KeyInputActionHandler.java +++ b/src/gov/nasa/worldwind/awt/KeyInputActionHandler.java @@ -9,11 +9,12 @@ * @author jym * @version $Id: KeyInputActionHandler.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface KeyInputActionHandler -{ +public interface KeyInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction); + ViewInputAttributes.ActionAttributes viewAction); + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java.awt.event.KeyEvent event, - ViewInputAttributes.ActionAttributes viewAction); + ViewInputAttributes.ActionAttributes viewAction); } diff --git a/src/gov/nasa/worldwind/awt/MouseInputActionHandler.java b/src/gov/nasa/worldwind/awt/MouseInputActionHandler.java index b34153d96f..7fc86b0be5 100644 --- a/src/gov/nasa/worldwind/awt/MouseInputActionHandler.java +++ b/src/gov/nasa/worldwind/awt/MouseInputActionHandler.java @@ -9,13 +9,13 @@ * @author jym * @version $Id: MouseInputActionHandler.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MouseInputActionHandler -{ +public interface MouseInputActionHandler { + public boolean inputActionPerformed(KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction); + ViewInputAttributes.ActionAttributes viewAction); public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction); + java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction); public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java.awt.event.MouseWheelEvent mouseWheelEvent, ViewInputAttributes.ActionAttributes viewAction); diff --git a/src/gov/nasa/worldwind/awt/ViewInputActionHandler.java b/src/gov/nasa/worldwind/awt/ViewInputActionHandler.java index d2229ba88c..99ef9151af 100644 --- a/src/gov/nasa/worldwind/awt/ViewInputActionHandler.java +++ b/src/gov/nasa/worldwind/awt/ViewInputActionHandler.java @@ -11,35 +11,30 @@ * @author jym * @version $Id: ViewInputActionHandler.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ViewInputActionHandler implements KeyInputActionHandler, MouseInputActionHandler -{ +public class ViewInputActionHandler implements KeyInputActionHandler, MouseInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { return false; } public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEvent event, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { return false; } public boolean inputActionPerformed(KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { return false; } public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) - { + java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) { return false; } public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseWheelEvent mouseWheelEvent, ViewInputAttributes.ActionAttributes viewAction) - { + java.awt.event.MouseWheelEvent mouseWheelEvent, ViewInputAttributes.ActionAttributes viewAction) { return false; } } diff --git a/src/gov/nasa/worldwind/awt/ViewInputAttributes.java b/src/gov/nasa/worldwind/awt/ViewInputAttributes.java index 0c248527ab..b948072c1e 100644 --- a/src/gov/nasa/worldwind/awt/ViewInputAttributes.java +++ b/src/gov/nasa/worldwind/awt/ViewInputAttributes.java @@ -15,48 +15,41 @@ * @author dcollins * @version $Id: ViewInputAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ViewInputAttributes -{ - public class DeviceModifierMap extends HashMap - { +public class ViewInputAttributes { + + public class DeviceModifierMap extends HashMap { } - public class ActionAttributesList extends ArrayList - { + public class ActionAttributesList extends ArrayList { } - public static class ActionAttributes - { - public KeyInputActionHandler getActionListener() - { + public static class ActionAttributes { + + public KeyInputActionHandler getActionListener() { return actionListener; } - public void setActionListener(KeyInputActionHandler actionListener) - { + public void setActionListener(KeyInputActionHandler actionListener) { this.actionListener = actionListener; } - public MouseInputActionHandler getMouseActionListener() - { + public MouseInputActionHandler getMouseActionListener() { return mouseActionListener; } - public void setMouseActionListener(MouseInputActionHandler mouseActionListener) - { + public void setMouseActionListener(MouseInputActionHandler mouseActionListener) { this.mouseActionListener = mouseActionListener; } - public enum ActionTrigger - { + public enum ActionTrigger { ON_PRESS, ON_DRAG, ON_KEY_DOWN, ON_RELEASE } - public static class KeyAction - { + public static class KeyAction { + public static final int KA_DIR_X = 0; public static final int KA_DIR_Y = 1; public static final int KA_DIR_Z = 2; @@ -65,20 +58,18 @@ public static class KeyAction public int sign; public int direction; - public KeyAction(int key, int direction, int sign) - { + public KeyAction(int key, int direction, int sign) { this.keyCode = key; this.sign = sign; this.direction = direction; } } - public static class MouseAction - { + public static class MouseAction { + public int mouseButton; - public MouseAction(int mouseButton) - { + public MouseAction(int mouseButton) { this.mouseButton = mouseButton; } } @@ -96,9 +87,8 @@ public MouseAction(int mouseButton) private MouseInputActionHandler mouseActionListener; public ActionAttributes(ActionAttributes.KeyAction[] keyActions, ActionTrigger trigger, - int modifier, double minValue, double maxValue, - boolean enableSmoothing, double smoothingValue) - { + int modifier, double minValue, double maxValue, + boolean enableSmoothing, double smoothingValue) { this.setValues(minValue, maxValue); this.setEnableSmoothing(enableSmoothing); this.setSmoothingValue(smoothingValue); @@ -109,8 +99,7 @@ public ActionAttributes(ActionAttributes.KeyAction[] keyActions, ActionTrigger t } public ActionAttributes(ActionAttributes.MouseAction[] mouseActions, ActionTrigger trigger, - double minValue, double maxValue, boolean enableSmoothing, double smoothingValue) - { + double minValue, double maxValue, boolean enableSmoothing, double smoothingValue) { this.setValues(minValue, maxValue); this.setEnableSmoothing(enableSmoothing); this.setSmoothingValue(smoothingValue); @@ -119,17 +108,14 @@ public ActionAttributes(ActionAttributes.MouseAction[] mouseActions, ActionTrigg keyActions = null; } - public ActionAttributes(double minValue, double maxValue, boolean enableSmoothing, double smoothingValue) - { + public ActionAttributes(double minValue, double maxValue, boolean enableSmoothing, double smoothingValue) { this.setValues(minValue, maxValue); this.setEnableSmoothing(enableSmoothing); this.setSmoothingValue(smoothingValue); } - public ActionAttributes(ActionAttributes attributes) - { - if (attributes == null) - { + public ActionAttributes(ActionAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -143,21 +129,17 @@ public ActionAttributes(ActionAttributes attributes) this.setActionTrigger(attributes.getActionTrigger()); } - public double[] getValues() - { - return new double[] {this.minValue, this.maxValue}; + public double[] getValues() { + return new double[]{this.minValue, this.maxValue}; } - public void setValues(double minValue, double maxValue) - { - if (minValue <= 0) - { + public void setValues(double minValue, double maxValue) { + if (minValue <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "minValue <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (maxValue <= 0) - { + if (maxValue <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "maxValue <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -167,32 +149,26 @@ public void setValues(double minValue, double maxValue) this.maxValue = maxValue; } - public void setValue(double value) - { + public void setValue(double value) { this.setValues(value, value); } - public boolean isEnableSmoothing() - { + public boolean isEnableSmoothing() { return this.enableSmoothing; } - public void setEnableSmoothing(boolean enable) - { + public void setEnableSmoothing(boolean enable) { this.enableSmoothing = enable; } - public double getSmoothingValue() - { + public double getSmoothingValue() { return this.smoothingValue; } - public void setSmoothingValue(double smoothingValue) - { - if (smoothingValue < 0 || smoothingValue >= 1.0) - { + public void setSmoothingValue(double smoothingValue) { + if (smoothingValue < 0 || smoothingValue >= 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", - "smoothingValue < 0 || smoothingValue >= 1"); + "smoothingValue < 0 || smoothingValue >= 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -200,76 +176,62 @@ public void setSmoothingValue(double smoothingValue) this.smoothingValue = smoothingValue; } - public void setKeyCodeModifier(int modifier) - { + public void setKeyCodeModifier(int modifier) { this.keyCodeModifier = modifier; } - public int getKeyCodeModifier() - { + public int getKeyCodeModifier() { return (this.keyCodeModifier); } - public java.util.List getKeyActions() - { + public java.util.List getKeyActions() { return (this.keyActions); } - public void setKeyActions(KeyAction[] keyActions) - { + public void setKeyActions(KeyAction[] keyActions) { this.keyActions = Arrays.asList(keyActions); } - public void setKeyActions(java.util.List keyActions) - { + public void setKeyActions(java.util.List keyActions) { this.keyActions = keyActions; } - public java.util.List getMouseActions() - { + public java.util.List getMouseActions() { return (this.mouseActions); } - public void setMouseActions(MouseAction[] mouseActions) - { + public void setMouseActions(MouseAction[] mouseActions) { this.mouseActions = Arrays.asList(mouseActions); } - public void setMouseActions(java.util.List mouseActions) - { + public void setMouseActions(java.util.List mouseActions) { this.mouseActions = mouseActions; } - public ActionTrigger getActionTrigger() - { + public ActionTrigger getActionTrigger() { return this.actionTrigger; } - public void setActionTrigger(ActionTrigger actionTrigger) - { + public void setActionTrigger(ActionTrigger actionTrigger) { this.actionTrigger = actionTrigger; } - public static ActionAttributes.MouseAction createMouseActionAttribute(int mouseButton) - { + public static ActionAttributes.MouseAction createMouseActionAttribute(int mouseButton) { ActionAttributes.MouseAction mouseAction = new ActionAttributes.MouseAction(mouseButton); return (mouseAction); } } - public static class DeviceAttributes - { + public static class DeviceAttributes { + private double sensitivity; - public DeviceAttributes(double sensitivity) - { + public DeviceAttributes(double sensitivity) { this.setSensitivity(sensitivity); } - public DeviceAttributes(DeviceAttributes attributes) - { - if (attributes == null) - { + public DeviceAttributes(DeviceAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -278,15 +240,12 @@ public DeviceAttributes(DeviceAttributes attributes) this.sensitivity = attributes.sensitivity; } - public double getSensitivity() - { + public double getSensitivity() { return this.sensitivity; } - public void setSensitivity(double sensitivity) - { - if (sensitivity <= 0) - { + public void setSensitivity(double sensitivity) { + if (sensitivity <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "sensitivity <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -296,18 +255,15 @@ public void setSensitivity(double sensitivity) } } - public static class ActionAttributesMap - { + public static class ActionAttributesMap { + private Map actionMap = new HashMap(); - public ActionAttributesMap() - { + public ActionAttributesMap() { } - public ActionAttributes getActionAttributes(Object actionKey) - { - if (actionKey == null) - { + public ActionAttributes getActionAttributes(Object actionKey) { + if (actionKey == null) { String message = Logging.getMessage("nullValue.ActionKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -316,16 +272,13 @@ public ActionAttributes getActionAttributes(Object actionKey) return this.actionMap.get(actionKey); } - public void setActionAttributes(Object actionKey, ActionAttributes attributes) - { - if (actionKey == null) - { + public void setActionAttributes(Object actionKey, ActionAttributes attributes) { + if (actionKey == null) { String message = Logging.getMessage("nullValue.ActionKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -378,169 +331,169 @@ public void setActionAttributes(Object actionKey, ActionAttributes attributes) public static final String VIEW_ROLL_KEYS = "gov.nasa.worldwind.ViewRollKeys"; // Reset Heading - private static final ActionAttributes.KeyAction DEFAULT_RESET_HEADING_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_N, ActionAttributes.KeyAction.KA_DIR_X, 1); - public static final ActionAttributes.KeyAction[] resetHeadingEvents = - { - DEFAULT_RESET_HEADING_KEY_ACT - }; + private static final ActionAttributes.KeyAction DEFAULT_RESET_HEADING_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_N, ActionAttributes.KeyAction.KA_DIR_X, 1); + public static final ActionAttributes.KeyAction[] resetHeadingEvents + = { + DEFAULT_RESET_HEADING_KEY_ACT + }; // Reset Heading, Pitch, and Roll - private static final ActionAttributes.KeyAction DEFAULT_RESET_HEADING_PITCH_ROLL_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_R, ActionAttributes.KeyAction.KA_DIR_X, 1); - public static final ActionAttributes.KeyAction[] resetHeadingPitchRollEvents = - { - DEFAULT_RESET_HEADING_PITCH_ROLL_KEY_ACT - }; + private static final ActionAttributes.KeyAction DEFAULT_RESET_HEADING_PITCH_ROLL_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_R, ActionAttributes.KeyAction.KA_DIR_X, 1); + public static final ActionAttributes.KeyAction[] resetHeadingPitchRollEvents + = { + DEFAULT_RESET_HEADING_PITCH_ROLL_KEY_ACT + }; // Stop view - private static final ActionAttributes.KeyAction DEFAULT_STOP_VIEW_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_SPACE, ActionAttributes.KeyAction.KA_DIR_X, 1); - public static final ActionAttributes.KeyAction[] stopViewEvents = - { - DEFAULT_STOP_VIEW_KEY_ACT - }; + private static final ActionAttributes.KeyAction DEFAULT_STOP_VIEW_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_SPACE, ActionAttributes.KeyAction.KA_DIR_X, 1); + public static final ActionAttributes.KeyAction[] stopViewEvents + = { + DEFAULT_STOP_VIEW_KEY_ACT + }; // MoveTo Events - private static final ActionAttributes.MouseAction DEFAULT_MOVETO_MOUSE_MODS = - new ActionAttributes.MouseAction(MouseEvent.BUTTON1); - public static final ActionAttributes.MouseAction[] moveToMouseEvents = - { - DEFAULT_MOVETO_MOUSE_MODS - }; + private static final ActionAttributes.MouseAction DEFAULT_MOVETO_MOUSE_MODS + = new ActionAttributes.MouseAction(MouseEvent.BUTTON1); + public static final ActionAttributes.MouseAction[] moveToMouseEvents + = { + DEFAULT_MOVETO_MOUSE_MODS + }; // Horizontal Translation mouse events - private static final ActionAttributes.MouseAction DEFAULT_HORIZONTAL_TRANSLATE_MOUSE_MODS = - new ActionAttributes.MouseAction(MouseEvent.BUTTON1_DOWN_MASK); - public static final ActionAttributes.MouseAction[] horizontalTransMouseEvents = - { - DEFAULT_HORIZONTAL_TRANSLATE_MOUSE_MODS - }; + private static final ActionAttributes.MouseAction DEFAULT_HORIZONTAL_TRANSLATE_MOUSE_MODS + = new ActionAttributes.MouseAction(MouseEvent.BUTTON1_DOWN_MASK); + public static final ActionAttributes.MouseAction[] horizontalTransMouseEvents + = { + DEFAULT_HORIZONTAL_TRANSLATE_MOUSE_MODS + }; // Horizontal Translation keyboard events - private static final ActionAttributes.KeyAction DEFAULT_HORIZONTAL_TRANSLEFT_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_LEFT, ActionAttributes.KeyAction.KA_DIR_X, -1); - private static final ActionAttributes.KeyAction DEFAULT_HORIZONTAL_TRANSRIGHT_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_RIGHT, ActionAttributes.KeyAction.KA_DIR_X, 1); - private static final ActionAttributes.KeyAction DEFAULT_HORIZONTAL_TRANSUP_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_UP, ActionAttributes.KeyAction.KA_DIR_Y, 1); - private static final ActionAttributes.KeyAction DEFAULT_HORIZONTAL_TRANSDOWN_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_DOWN, ActionAttributes.KeyAction.KA_DIR_Y, -1); - public static final ActionAttributes.KeyAction[] horizontalTransKeyEvents = - { - DEFAULT_HORIZONTAL_TRANSLEFT_KEY_ACT, - DEFAULT_HORIZONTAL_TRANSRIGHT_KEY_ACT, - DEFAULT_HORIZONTAL_TRANSUP_KEY_ACT, - DEFAULT_HORIZONTAL_TRANSDOWN_KEY_ACT - }; + private static final ActionAttributes.KeyAction DEFAULT_HORIZONTAL_TRANSLEFT_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_LEFT, ActionAttributes.KeyAction.KA_DIR_X, -1); + private static final ActionAttributes.KeyAction DEFAULT_HORIZONTAL_TRANSRIGHT_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_RIGHT, ActionAttributes.KeyAction.KA_DIR_X, 1); + private static final ActionAttributes.KeyAction DEFAULT_HORIZONTAL_TRANSUP_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_UP, ActionAttributes.KeyAction.KA_DIR_Y, 1); + private static final ActionAttributes.KeyAction DEFAULT_HORIZONTAL_TRANSDOWN_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_DOWN, ActionAttributes.KeyAction.KA_DIR_Y, -1); + public static final ActionAttributes.KeyAction[] horizontalTransKeyEvents + = { + DEFAULT_HORIZONTAL_TRANSLEFT_KEY_ACT, + DEFAULT_HORIZONTAL_TRANSRIGHT_KEY_ACT, + DEFAULT_HORIZONTAL_TRANSUP_KEY_ACT, + DEFAULT_HORIZONTAL_TRANSDOWN_KEY_ACT + }; // Vertical Translation Mouse Events - private static final ActionAttributes.MouseAction DEFAULT_VERTICAL_TRANSLATE_MOUSE_MODS = - new ActionAttributes.MouseAction(MouseEvent.BUTTON2_DOWN_MASK); - public static final ActionAttributes.MouseAction[] verticalTransMouseEvents = - { - DEFAULT_VERTICAL_TRANSLATE_MOUSE_MODS - }; - private static final ActionAttributes.MouseAction DEFAULT_VERTICAL_TRANSLATE_MOUSE_MODS_CTRL = - new ActionAttributes.MouseAction(MouseEvent.BUTTON1_DOWN_MASK); - public static final ActionAttributes.MouseAction[] verticalTransMouseEventsCtrl = - { - DEFAULT_VERTICAL_TRANSLATE_MOUSE_MODS_CTRL - }; + private static final ActionAttributes.MouseAction DEFAULT_VERTICAL_TRANSLATE_MOUSE_MODS + = new ActionAttributes.MouseAction(MouseEvent.BUTTON2_DOWN_MASK); + public static final ActionAttributes.MouseAction[] verticalTransMouseEvents + = { + DEFAULT_VERTICAL_TRANSLATE_MOUSE_MODS + }; + private static final ActionAttributes.MouseAction DEFAULT_VERTICAL_TRANSLATE_MOUSE_MODS_CTRL + = new ActionAttributes.MouseAction(MouseEvent.BUTTON1_DOWN_MASK); + public static final ActionAttributes.MouseAction[] verticalTransMouseEventsCtrl + = { + DEFAULT_VERTICAL_TRANSLATE_MOUSE_MODS_CTRL + }; // Vertical Translation Key Events - private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSUP_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_UP, - ActionAttributes.KeyAction.KA_DIR_Z, -1); - private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSDOWN_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_DOWN, - ActionAttributes.KeyAction.KA_DIR_Z, 1); - public static final ActionAttributes.KeyAction[] verticalTransKeyEventsCtrl = - { - DEFAULT_VERTICAL_TRANSUP_KEY_ACT, - DEFAULT_VERTICAL_TRANSDOWN_KEY_ACT - }; - - private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSUP_ADDKEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_ADD, - ActionAttributes.KeyAction.KA_DIR_Z, -1); - private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSDOWN_EQUALSKEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_EQUALS, - ActionAttributes.KeyAction.KA_DIR_Z, -1); - private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSUP_SUBTKEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_SUBTRACT, - ActionAttributes.KeyAction.KA_DIR_Z, 1); - private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSDOWN_MINUSKEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_MINUS, - ActionAttributes.KeyAction.KA_DIR_Z, 1); - public static final ActionAttributes.KeyAction[] verticalTransKeyEvents = - { - DEFAULT_VERTICAL_TRANSUP_ADDKEY_ACT, - DEFAULT_VERTICAL_TRANSDOWN_EQUALSKEY_ACT, - DEFAULT_VERTICAL_TRANSUP_SUBTKEY_ACT, - DEFAULT_VERTICAL_TRANSDOWN_MINUSKEY_ACT - }; - private static final ActionAttributes.MouseAction DEFAULT_VERTICAL_TRANSLATE_MOUSE_WHEEL_MODS = - new ActionAttributes.MouseAction(MouseEvent.MOUSE_WHEEL); - public static final ActionAttributes.MouseAction[] verticalTransMouseWheelEvents = - { - DEFAULT_VERTICAL_TRANSLATE_MOUSE_WHEEL_MODS - }; - - private static final ActionAttributes.MouseAction DEFAULT_ROTATE_MOUSE_MODS = - new ActionAttributes.MouseAction(MouseEvent.BUTTON3_DOWN_MASK); - - public static final ActionAttributes.MouseAction[] rotateMouseEvents = - { - DEFAULT_ROTATE_MOUSE_MODS - }; - private static final ActionAttributes.MouseAction DEFAULT_ROTATE_MOUSE_MODS_SHIFT = - new ActionAttributes.MouseAction(MouseEvent.BUTTON1_DOWN_MASK); - public static final ActionAttributes.MouseAction[] rotateMouseEventsShift = - { - DEFAULT_ROTATE_MOUSE_MODS_SHIFT - }; + private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSUP_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_UP, + ActionAttributes.KeyAction.KA_DIR_Z, -1); + private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSDOWN_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_DOWN, + ActionAttributes.KeyAction.KA_DIR_Z, 1); + public static final ActionAttributes.KeyAction[] verticalTransKeyEventsCtrl + = { + DEFAULT_VERTICAL_TRANSUP_KEY_ACT, + DEFAULT_VERTICAL_TRANSDOWN_KEY_ACT + }; + + private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSUP_ADDKEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_ADD, + ActionAttributes.KeyAction.KA_DIR_Z, -1); + private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSDOWN_EQUALSKEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_EQUALS, + ActionAttributes.KeyAction.KA_DIR_Z, -1); + private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSUP_SUBTKEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_SUBTRACT, + ActionAttributes.KeyAction.KA_DIR_Z, 1); + private static final ActionAttributes.KeyAction DEFAULT_VERTICAL_TRANSDOWN_MINUSKEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_MINUS, + ActionAttributes.KeyAction.KA_DIR_Z, 1); + public static final ActionAttributes.KeyAction[] verticalTransKeyEvents + = { + DEFAULT_VERTICAL_TRANSUP_ADDKEY_ACT, + DEFAULT_VERTICAL_TRANSDOWN_EQUALSKEY_ACT, + DEFAULT_VERTICAL_TRANSUP_SUBTKEY_ACT, + DEFAULT_VERTICAL_TRANSDOWN_MINUSKEY_ACT + }; + private static final ActionAttributes.MouseAction DEFAULT_VERTICAL_TRANSLATE_MOUSE_WHEEL_MODS + = new ActionAttributes.MouseAction(MouseEvent.MOUSE_WHEEL); + public static final ActionAttributes.MouseAction[] verticalTransMouseWheelEvents + = { + DEFAULT_VERTICAL_TRANSLATE_MOUSE_WHEEL_MODS + }; + + private static final ActionAttributes.MouseAction DEFAULT_ROTATE_MOUSE_MODS + = new ActionAttributes.MouseAction(MouseEvent.BUTTON3_DOWN_MASK); + + public static final ActionAttributes.MouseAction[] rotateMouseEvents + = { + DEFAULT_ROTATE_MOUSE_MODS + }; + private static final ActionAttributes.MouseAction DEFAULT_ROTATE_MOUSE_MODS_SHIFT + = new ActionAttributes.MouseAction(MouseEvent.BUTTON1_DOWN_MASK); + public static final ActionAttributes.MouseAction[] rotateMouseEventsShift + = { + DEFAULT_ROTATE_MOUSE_MODS_SHIFT + }; // Rotation Keyboard events - private static final ActionAttributes.KeyAction DEFAULT_ROTATE_HEADINGLEFT_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_LEFT, - ActionAttributes.KeyAction.KA_DIR_X, -1); - private static final ActionAttributes.KeyAction DEFAULT_ROTATE_HEADINGRIGHT_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_RIGHT, - ActionAttributes.KeyAction.KA_DIR_X, 1); - private static final ActionAttributes.KeyAction DEFAULT_ROTATE_PITCHUP_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_UP, - ActionAttributes.KeyAction.KA_DIR_Y, -1); - private static final ActionAttributes.KeyAction DEFAULT_ROTATE_PITCHDOWN_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_DOWN, - ActionAttributes.KeyAction.KA_DIR_Y, 1); - public static final ActionAttributes.KeyAction[] rotationKeyEvents = - { - DEFAULT_ROTATE_HEADINGLEFT_KEY_ACT, - DEFAULT_ROTATE_HEADINGRIGHT_KEY_ACT, - DEFAULT_ROTATE_PITCHUP_KEY_ACT, - DEFAULT_ROTATE_PITCHDOWN_KEY_ACT - }; + private static final ActionAttributes.KeyAction DEFAULT_ROTATE_HEADINGLEFT_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_LEFT, + ActionAttributes.KeyAction.KA_DIR_X, -1); + private static final ActionAttributes.KeyAction DEFAULT_ROTATE_HEADINGRIGHT_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_RIGHT, + ActionAttributes.KeyAction.KA_DIR_X, 1); + private static final ActionAttributes.KeyAction DEFAULT_ROTATE_PITCHUP_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_UP, + ActionAttributes.KeyAction.KA_DIR_Y, -1); + private static final ActionAttributes.KeyAction DEFAULT_ROTATE_PITCHDOWN_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_DOWN, + ActionAttributes.KeyAction.KA_DIR_Y, 1); + public static final ActionAttributes.KeyAction[] rotationKeyEvents + = { + DEFAULT_ROTATE_HEADINGLEFT_KEY_ACT, + DEFAULT_ROTATE_HEADINGRIGHT_KEY_ACT, + DEFAULT_ROTATE_PITCHUP_KEY_ACT, + DEFAULT_ROTATE_PITCHDOWN_KEY_ACT + }; // Roll Keyboard events. Use CTRL-Left and CTRL-Right to change roll. - protected static final ActionAttributes.KeyAction DEFAULT_ROTATE_ROLLUP_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_LEFT, - ActionAttributes.KeyAction.KA_DIR_Y, 1); - protected static final ActionAttributes.KeyAction DEFAULT_ROTATE_ROLLDOWN_KEY_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_RIGHT, - ActionAttributes.KeyAction.KA_DIR_Y, -1); - public static final ActionAttributes.KeyAction[] rollKeyEvents = - { - DEFAULT_ROTATE_ROLLUP_KEY_ACT, - DEFAULT_ROTATE_ROLLDOWN_KEY_ACT - }; - - private static final ActionAttributes.KeyAction DEFAULT_ROTATE_PITCHUP_KEY_PAGE_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_PAGE_UP, - ActionAttributes.KeyAction.KA_DIR_Y, -1); - private static final ActionAttributes.KeyAction DEFAULT_ROTATE_PITCHDOWN_KEY_PAGE_ACT = - new ActionAttributes.KeyAction(KeyEvent.VK_PAGE_DOWN, - ActionAttributes.KeyAction.KA_DIR_Y, 1); - public static final ActionAttributes.KeyAction[] rotationKeyEventsPage = - { - DEFAULT_ROTATE_PITCHUP_KEY_PAGE_ACT, - DEFAULT_ROTATE_PITCHDOWN_KEY_PAGE_ACT - }; + protected static final ActionAttributes.KeyAction DEFAULT_ROTATE_ROLLUP_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_LEFT, + ActionAttributes.KeyAction.KA_DIR_Y, 1); + protected static final ActionAttributes.KeyAction DEFAULT_ROTATE_ROLLDOWN_KEY_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_RIGHT, + ActionAttributes.KeyAction.KA_DIR_Y, -1); + public static final ActionAttributes.KeyAction[] rollKeyEvents + = { + DEFAULT_ROTATE_ROLLUP_KEY_ACT, + DEFAULT_ROTATE_ROLLDOWN_KEY_ACT + }; + + private static final ActionAttributes.KeyAction DEFAULT_ROTATE_PITCHUP_KEY_PAGE_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_PAGE_UP, + ActionAttributes.KeyAction.KA_DIR_Y, -1); + private static final ActionAttributes.KeyAction DEFAULT_ROTATE_PITCHDOWN_KEY_PAGE_ACT + = new ActionAttributes.KeyAction(KeyEvent.VK_PAGE_DOWN, + ActionAttributes.KeyAction.KA_DIR_Y, 1); + public static final ActionAttributes.KeyAction[] rotationKeyEventsPage + = { + DEFAULT_ROTATE_PITCHUP_KEY_PAGE_ACT, + DEFAULT_ROTATE_PITCHDOWN_KEY_PAGE_ACT + }; public static final boolean DEFAULT_MOVE_TO_SMOOTHING_ENABLED = true; public static final boolean DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_ENABLED = true; @@ -556,15 +509,15 @@ public void setActionAttributes(Object actionKey, ActionAttributes attributes) public static final double DEFAULT_MOUSE_MOVE_TO_MIN_VALUE = 0.95; // [0, 1] smoothing value public static final double DEFAULT_MOUSE_MOVE_TO_MAX_VALUE = 0.90; // [0, 1] smoothing value public static final double DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MIN_VALUE = 0.00001; - // Speed in degrees per mouse movement + // Speed in degrees per mouse movement public static final double DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MAX_VALUE = 0.2; - // Speed in degrees per mouse movement + // Speed in degrees per mouse movement public static final double DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE = 0.003; // Speed in log-meters per mouse movement // MouseWheel/Action calibration values. public static final double DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE = 0.1; - // Speed in log-meters per wheel movement + // Speed in log-meters per wheel movement public static final double DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_OSX = 0.01; - // Speed in log-meters per wheel movement + // Speed in log-meters per wheel movement // Device sensitivity defaults. public static final double DEFAULT_KEY_SENSITIVITY = 1.0; // Scalar multiplier @@ -594,17 +547,14 @@ public void setActionAttributes(Object actionKey, ActionAttributes attributes) // that they are interested in, and only act on those keys. private Map deviceModActionMap = new HashMap(); - public ViewInputAttributes() - { + public ViewInputAttributes() { this.setDefaultDeviceAttributes(); this.setDeviceModifierActionMaps(); } - public ActionAttributesMap getActionMap(Object deviceKey) - { - if (deviceKey == null) - { + public ActionAttributesMap getActionMap(Object deviceKey) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -613,16 +563,13 @@ public ActionAttributesMap getActionMap(Object deviceKey) return this.deviceActionMap.get(deviceKey); } - public void setActionMap(Object deviceKey, ActionAttributesMap map) - { - if (deviceKey == null) - { + public void setActionMap(Object deviceKey, ActionAttributesMap map) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (map == null) - { + if (map == null) { String message = Logging.getMessage("nullValue.MapIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -631,8 +578,7 @@ public void setActionMap(Object deviceKey, ActionAttributesMap map) this.deviceActionMap.put(deviceKey, map); } - public void addModifierAction(Object device, Integer modifier, ActionAttributes action) - { + public void addModifierAction(Object device, Integer modifier, ActionAttributes action) { this.addModifierActionList(device, modifier); DeviceModifierMap modActionMap = this.getModifierActionMap(device); @@ -641,56 +587,43 @@ public void addModifierAction(Object device, Integer modifier, ActionAttributes actionList.add(action); } - public void setValues(Object device, Object action, double minValue, double maxValue) - { + public void setValues(Object device, Object action, double minValue, double maxValue) { ActionAttributes actionAttrs = getActionAttributes(device, action); - if (actionAttrs == null) - { + if (actionAttrs == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); - } - else - { + } else { actionAttrs.setValues(minValue, maxValue); } } - public void setActionTrigger(Object device, Object action, ActionAttributes.ActionTrigger trigger) - { + public void setActionTrigger(Object device, Object action, ActionAttributes.ActionTrigger trigger) { ActionAttributes actionAttrs = getActionAttributes(device, action); - if (actionAttrs == null) - { + if (actionAttrs == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); - } - else - { + } else { actionAttrs.setActionTrigger(trigger); } } - public void addModifierActionList(Object device, Integer modifier) - { + public void addModifierActionList(Object device, Integer modifier) { DeviceModifierMap deviceActionMap = this.getModifierActionMap(device); - if (deviceActionMap == null) - { + if (deviceActionMap == null) { deviceActionMap = new DeviceModifierMap(); this.setModifierActionMap(device, deviceActionMap); } ArrayList modifierList = deviceActionMap.get(modifier); - if (modifierList == null) - { + if (modifierList == null) { deviceActionMap.put(modifier, new ActionAttributesList()); } } - public List getModifierActionList(Object device, Integer modifier) - { + public List getModifierActionList(Object device, Integer modifier) { Map deviceModActionMap = this.getModifierActionMap(device); - if (deviceModActionMap == null) - { + if (deviceModActionMap == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -698,10 +631,8 @@ public List getModifierActionList(Object device, Integer modifier) return (deviceModActionMap.get(modifier)); } - public DeviceAttributes getDeviceAttributes(Object deviceKey) - { - if (deviceKey == null) - { + public DeviceAttributes getDeviceAttributes(Object deviceKey) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -710,16 +641,13 @@ public DeviceAttributes getDeviceAttributes(Object deviceKey) return this.deviceMap.get(deviceKey); } - public void setDeviceAttributes(Object deviceKey, DeviceAttributes attributes) - { - if (deviceKey == null) - { + public void setDeviceAttributes(Object deviceKey, DeviceAttributes attributes) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -728,10 +656,8 @@ public void setDeviceAttributes(Object deviceKey, DeviceAttributes attributes) this.deviceMap.put(deviceKey, attributes); } - public DeviceModifierMap getModifierActionMap(Object deviceKey) - { - if (deviceKey == null) - { + public DeviceModifierMap getModifierActionMap(Object deviceKey) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -740,16 +666,13 @@ public DeviceModifierMap getModifierActionMap(Object deviceKey) return this.deviceModActionMap.get(deviceKey); } - public void setModifierActionMap(Object deviceKey, DeviceModifierMap map) - { - if (deviceKey == null) - { + public void setModifierActionMap(Object deviceKey, DeviceModifierMap map) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (map == null) - { + if (map == null) { String message = Logging.getMessage("nullValue.MapIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -758,39 +681,34 @@ public void setModifierActionMap(Object deviceKey, DeviceModifierMap map) this.deviceModActionMap.put(deviceKey, map); } - public ActionAttributes getActionAttributes(Object deviceKey, Object actionKey) - { - if (deviceKey == null) - { + public ActionAttributes getActionAttributes(Object deviceKey, Object actionKey) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (actionKey == null) - { + if (actionKey == null) { String message = Logging.getMessage("nullValue.ActionKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } ActionAttributesMap map = this.getActionMap(deviceKey); - if (map == null) + if (map == null) { return null; + } return map.getActionAttributes(actionKey); } public void addAction(Object deviceKey, Integer modifier, Object actionKey, - ActionAttributes actionAttrs) - { - if (deviceKey == null) - { + ActionAttributes actionAttrs) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (actionKey == null) - { + if (actionKey == null) { String message = Logging.getMessage("nullValue.ActionKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -800,8 +718,7 @@ public void addAction(Object deviceKey, Integer modifier, Object actionKey, // Get the Device -> Action map ActionAttributesMap deviceActionMap = this.getActionMap(deviceKey); - if (deviceActionMap == null) - { + if (deviceActionMap == null) { deviceActionMap = new ActionAttributesMap(); this.setActionMap(deviceKey, deviceActionMap); } @@ -810,62 +727,50 @@ public void addAction(Object deviceKey, Integer modifier, Object actionKey, } public void setMouseActionAttributes(String actionName, int modifier, ActionAttributes.ActionTrigger trigger, - ActionAttributes.MouseAction[] mouseActions, - double minValue, double maxValue, boolean smoothingEnabled, double smoothingValue) - { + ActionAttributes.MouseAction[] mouseActions, + double minValue, double maxValue, boolean smoothingEnabled, double smoothingValue) { ActionAttributes actionAttrs = this.getActionAttributes(DEVICE_MOUSE, actionName); - if (actionAttrs != null) - { + if (actionAttrs != null) { actionAttrs.setValues(minValue, maxValue); actionAttrs.setMouseActions(mouseActions); actionAttrs.setActionTrigger(trigger); actionAttrs.setEnableSmoothing(smoothingEnabled); actionAttrs.setSmoothingValue(smoothingValue); - } - else - { + } else { this.addAction(DEVICE_MOUSE, modifier, actionName, - new ActionAttributes(mouseActions, trigger, - minValue, maxValue, - smoothingEnabled, smoothingValue)); + new ActionAttributes(mouseActions, trigger, + minValue, maxValue, + smoothingEnabled, smoothingValue)); } } - public void setActionListener(Object deviceKey, Object actionKey, ViewInputActionHandler listener) - { - if (deviceKey == null) - { + public void setActionListener(Object deviceKey, Object actionKey, ViewInputActionHandler listener) { + if (deviceKey == null) { String message = Logging.getMessage("nullValue.DeviceKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (actionKey == null) - { + if (actionKey == null) { String message = Logging.getMessage("nullValue.ActionKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } ActionAttributesMap deviceActionMap = this.getActionMap(deviceKey); - if (deviceActionMap == null) - { + if (deviceActionMap == null) { String message = Logging.getMessage("nullValue.DeviceNotDefined"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } ActionAttributes actions = deviceActionMap.getActionAttributes(actionKey); - if (actions == null) - { + if (actions == null) { String message = Logging.getMessage("nullValue.DeviceActionNotDefined"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (actions.getMouseActions() != null) - { + if (actions.getMouseActions() != null) { actions.setMouseActionListener(listener); - } - else if (actions.getKeyActions() != null) - { + } else if (actions.getKeyActions() != null) { actions.setActionListener(listener); } } @@ -873,150 +778,143 @@ else if (actions.getKeyActions() != null) //**************************************************************// //******************** Default Attributes ********************// //**************************************************************// - - protected void setDefaultDeviceAttributes() - { + protected void setDefaultDeviceAttributes() { this.setDeviceAttributes(DEVICE_KEYBOARD, new DeviceAttributes(DEFAULT_KEY_SENSITIVITY)); this.setDeviceAttributes(DEVICE_MOUSE, new DeviceAttributes(DEFAULT_MOUSE_SENSITIVITY)); this.setDeviceAttributes(DEVICE_MOUSE_WHEEL, new DeviceAttributes(DEFAULT_MOUSE_WHEEL_SENSITIVITY)); } - protected void setDeviceModifierActionMaps() - { + protected void setDeviceModifierActionMaps() { // Mouse Wheel Vertical Translation Event - if (Configuration.isMacOS()) - { + if (Configuration.isMacOS()) { this.addAction(DEVICE_MOUSE_WHEEL, ActionAttributes.NO_MODIFIER, VIEW_VERTICAL_TRANSLATE, - new ActionAttributes(verticalTransMouseWheelEvents, ActionAttributes.ActionTrigger.ON_DRAG, - DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_OSX, DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_OSX, - DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); - } - else - { + new ActionAttributes(verticalTransMouseWheelEvents, ActionAttributes.ActionTrigger.ON_DRAG, + DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_OSX, DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_OSX, + DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); + } else { this.addAction(DEVICE_MOUSE_WHEEL, ActionAttributes.NO_MODIFIER, VIEW_VERTICAL_TRANSLATE, - new ActionAttributes(verticalTransMouseWheelEvents, ActionAttributes.ActionTrigger.ON_DRAG, - DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE, DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE, - DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); + new ActionAttributes(verticalTransMouseWheelEvents, ActionAttributes.ActionTrigger.ON_DRAG, + DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE, DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE, + DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); } // Mouse Button Move To Events this.addAction(DEVICE_MOUSE, ActionAttributes.NO_MODIFIER, VIEW_MOVE_TO, - new ActionAttributes(moveToMouseEvents, ActionAttributes.ActionTrigger.ON_PRESS, - DEFAULT_MOUSE_MOVE_TO_MIN_VALUE, DEFAULT_MOUSE_MOVE_TO_MAX_VALUE, - DEFAULT_MOVE_TO_SMOOTHING_ENABLED, DEFAULT_MOVE_TO_SMOOTHING_VALUE)); + new ActionAttributes(moveToMouseEvents, ActionAttributes.ActionTrigger.ON_PRESS, + DEFAULT_MOUSE_MOVE_TO_MIN_VALUE, DEFAULT_MOUSE_MOVE_TO_MAX_VALUE, + DEFAULT_MOVE_TO_SMOOTHING_ENABLED, DEFAULT_MOVE_TO_SMOOTHING_VALUE)); this.addAction(DEVICE_MOUSE, KeyEvent.ALT_DOWN_MASK, VIEW_MOVE_TO_SLOW, - this.makeSlowActionAttributes(this.getActionAttributes( - DEVICE_MOUSE, VIEW_MOVE_TO), DEFAULT_SLOW_VALUE)); + this.makeSlowActionAttributes(this.getActionAttributes( + DEVICE_MOUSE, VIEW_MOVE_TO), DEFAULT_SLOW_VALUE)); // Mouse Button Rotate Events this.addAction(DEVICE_MOUSE, ActionAttributes.NO_MODIFIER, VIEW_ROTATE, - new ActionAttributes(rotateMouseEvents, ActionAttributes.ActionTrigger.ON_DRAG, - DEFAULT_MOUSE_ROTATE_MIN_VALUE, DEFAULT_MOUSE_ROTATE_MAX_VALUE, - DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); + new ActionAttributes(rotateMouseEvents, ActionAttributes.ActionTrigger.ON_DRAG, + DEFAULT_MOUSE_ROTATE_MIN_VALUE, DEFAULT_MOUSE_ROTATE_MAX_VALUE, + DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); this.addAction(DEVICE_MOUSE, KeyEvent.SHIFT_DOWN_MASK, VIEW_ROTATE_SHIFT, - new ActionAttributes(rotateMouseEventsShift, ActionAttributes.ActionTrigger.ON_DRAG, - DEFAULT_MOUSE_ROTATE_MIN_VALUE, DEFAULT_MOUSE_ROTATE_MAX_VALUE, - DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); + new ActionAttributes(rotateMouseEventsShift, ActionAttributes.ActionTrigger.ON_DRAG, + DEFAULT_MOUSE_ROTATE_MIN_VALUE, DEFAULT_MOUSE_ROTATE_MAX_VALUE, + DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); // Mouse Button Horizontal Translate Events this.addAction(DEVICE_MOUSE, ActionAttributes.NO_MODIFIER, VIEW_HORIZONTAL_TRANSLATE, - new ActionAttributes(horizontalTransMouseEvents, ActionAttributes.ActionTrigger.ON_DRAG, - DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MIN_VALUE, DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MAX_VALUE, - DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_VALUE)); + new ActionAttributes(horizontalTransMouseEvents, ActionAttributes.ActionTrigger.ON_DRAG, + DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MIN_VALUE, DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MAX_VALUE, + DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_VALUE)); // Mouse Button Vertical Translate Events this.addAction(DEVICE_MOUSE, ActionAttributes.NO_MODIFIER, VIEW_VERTICAL_TRANSLATE, - new ActionAttributes(verticalTransMouseEvents, ActionAttributes.ActionTrigger.ON_DRAG, - DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, - DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); + new ActionAttributes(verticalTransMouseEvents, ActionAttributes.ActionTrigger.ON_DRAG, + DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, + DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); this.addAction(DEVICE_MOUSE, KeyEvent.CTRL_DOWN_MASK, VIEW_VERTICAL_TRANSLATE_CTRL, - new ActionAttributes(verticalTransMouseEventsCtrl, ActionAttributes.ActionTrigger.ON_DRAG, - DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, - DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); + new ActionAttributes(verticalTransMouseEventsCtrl, ActionAttributes.ActionTrigger.ON_DRAG, + DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, + DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); this.addAction(DEVICE_MOUSE, KeyEvent.META_DOWN_MASK, VIEW_VERTICAL_TRANSLATE_CTRL, - new ActionAttributes(verticalTransMouseEventsCtrl, ActionAttributes.ActionTrigger.ON_DRAG, - DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, - DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); + new ActionAttributes(verticalTransMouseEventsCtrl, ActionAttributes.ActionTrigger.ON_DRAG, + DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, DEFAULT_MOUSE_VERTICAL_TRANSLATE_VALUE, + DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); // Keyboard Rotation Actions this.addAction(DEVICE_KEYBOARD, KeyEvent.SHIFT_DOWN_MASK, VIEW_ROTATE_KEYS_SHIFT, - new ActionAttributes(rotationKeyEvents, ActionAttributes.ActionTrigger.ON_KEY_DOWN, - KeyEvent.SHIFT_DOWN_MASK, - DEFAULT_KEY_ROTATE_MIN_VALUE, DEFAULT_KEY_ROTATE_MAX_VALUE, - DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); + new ActionAttributes(rotationKeyEvents, ActionAttributes.ActionTrigger.ON_KEY_DOWN, + KeyEvent.SHIFT_DOWN_MASK, + DEFAULT_KEY_ROTATE_MIN_VALUE, DEFAULT_KEY_ROTATE_MAX_VALUE, + DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); this.addAction(DEVICE_KEYBOARD, ActionAttributes.NO_MODIFIER, VIEW_ROTATE_KEYS, - new ActionAttributes(rotationKeyEventsPage, ActionAttributes.ActionTrigger.ON_KEY_DOWN, - ActionAttributes.NO_MODIFIER, - DEFAULT_KEY_ROTATE_MIN_VALUE, DEFAULT_KEY_ROTATE_MAX_VALUE, - DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); + new ActionAttributes(rotationKeyEventsPage, ActionAttributes.ActionTrigger.ON_KEY_DOWN, + ActionAttributes.NO_MODIFIER, + DEFAULT_KEY_ROTATE_MIN_VALUE, DEFAULT_KEY_ROTATE_MAX_VALUE, + DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); this.addAction(DEVICE_KEYBOARD, KeyEvent.SHIFT_DOWN_MASK | KeyEvent.ALT_DOWN_MASK, VIEW_ROTATE_KEYS_SHIFT_SLOW, - this.makeSlowActionAttributes(this.getActionAttributes( - DEVICE_KEYBOARD, VIEW_ROTATE_KEYS_SHIFT), DEFAULT_SLOW_VALUE)); + this.makeSlowActionAttributes(this.getActionAttributes( + DEVICE_KEYBOARD, VIEW_ROTATE_KEYS_SHIFT), DEFAULT_SLOW_VALUE)); this.addAction(DEVICE_KEYBOARD, KeyEvent.ALT_DOWN_MASK, VIEW_ROTATE_SLOW, - this.makeSlowActionAttributes(this.getActionAttributes( - DEVICE_KEYBOARD, VIEW_ROTATE_KEYS), DEFAULT_SLOW_VALUE)); + this.makeSlowActionAttributes(this.getActionAttributes( + DEVICE_KEYBOARD, VIEW_ROTATE_KEYS), DEFAULT_SLOW_VALUE)); // Keyboard Roll Actions this.addAction(DEVICE_KEYBOARD, KeyEvent.CTRL_DOWN_MASK, VIEW_ROLL_KEYS, - new ActionAttributes(rollKeyEvents, ActionAttributes.ActionTrigger.ON_KEY_DOWN, - KeyEvent.CTRL_DOWN_MASK, - DEFAULT_KEY_ROLL_MIN_VALUE, DEFAULT_KEY_ROLL_MAX_VALUE, - DEFAULT_ROLL_SMOOTHING_ENABLED, DEFAULT_ROLL_SMOOTHING_VALUE)); + new ActionAttributes(rollKeyEvents, ActionAttributes.ActionTrigger.ON_KEY_DOWN, + KeyEvent.CTRL_DOWN_MASK, + DEFAULT_KEY_ROLL_MIN_VALUE, DEFAULT_KEY_ROLL_MAX_VALUE, + DEFAULT_ROLL_SMOOTHING_ENABLED, DEFAULT_ROLL_SMOOTHING_VALUE)); // Keyboard Horizontal Translation Actions this.addAction(DEVICE_KEYBOARD, ActionAttributes.NO_MODIFIER, VIEW_HORIZONTAL_TRANS_KEYS, - new ActionAttributes(horizontalTransKeyEvents, ActionAttributes.ActionTrigger.ON_KEY_DOWN, 0, - DEFAULT_KEY_HORIZONTAL_TRANSLATE_MIN_VALUE, DEFAULT_KEY_HORIZONTAL_TRANSLATE_MAX_VALUE, - DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_VALUE)); + new ActionAttributes(horizontalTransKeyEvents, ActionAttributes.ActionTrigger.ON_KEY_DOWN, 0, + DEFAULT_KEY_HORIZONTAL_TRANSLATE_MIN_VALUE, DEFAULT_KEY_HORIZONTAL_TRANSLATE_MAX_VALUE, + DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_HORIZONTAL_TRANSLATE_SMOOTHING_VALUE)); this.addAction(DEVICE_KEYBOARD, KeyEvent.ALT_DOWN_MASK, VIEW_HORIZONTAL_TRANSLATE_SLOW, - this.makeSlowActionAttributes(this.getActionAttributes( - DEVICE_KEYBOARD, VIEW_HORIZONTAL_TRANS_KEYS), DEFAULT_SLOW_VALUE)); + this.makeSlowActionAttributes(this.getActionAttributes( + DEVICE_KEYBOARD, VIEW_HORIZONTAL_TRANS_KEYS), DEFAULT_SLOW_VALUE)); // Vertical Translation Actions this.addAction(DEVICE_KEYBOARD, ActionAttributes.NO_MODIFIER, VIEW_VERTICAL_TRANS_KEYS, - new ActionAttributes(verticalTransKeyEvents, ActionAttributes.ActionTrigger.ON_KEY_DOWN, 0, - DEFAULT_KEY_VERTICAL_TRANSLATE_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_VALUE, - DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); + new ActionAttributes(verticalTransKeyEvents, ActionAttributes.ActionTrigger.ON_KEY_DOWN, 0, + DEFAULT_KEY_VERTICAL_TRANSLATE_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_VALUE, + DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); this.addAction(DEVICE_KEYBOARD, KeyEvent.ALT_DOWN_MASK, VIEW_VERTICAL_TRANS_KEYS_SLOW, - this.makeSlowActionAttributes(this.getActionAttributes( - DEVICE_KEYBOARD, VIEW_VERTICAL_TRANS_KEYS), DEFAULT_SLOW_VALUE)); + this.makeSlowActionAttributes(this.getActionAttributes( + DEVICE_KEYBOARD, VIEW_VERTICAL_TRANS_KEYS), DEFAULT_SLOW_VALUE)); this.addAction(DEVICE_KEYBOARD, KeyEvent.CTRL_DOWN_MASK, VIEW_VERTICAL_TRANS_KEYS_CTRL, - new ActionAttributes(verticalTransKeyEventsCtrl, ActionAttributes.ActionTrigger.ON_KEY_DOWN, - (KeyEvent.CTRL_DOWN_MASK), - DEFAULT_KEY_VERTICAL_TRANSLATE_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_VALUE, - DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); + new ActionAttributes(verticalTransKeyEventsCtrl, ActionAttributes.ActionTrigger.ON_KEY_DOWN, + (KeyEvent.CTRL_DOWN_MASK), + DEFAULT_KEY_VERTICAL_TRANSLATE_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_VALUE, + DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_ENABLED, DEFAULT_VERTICAL_TRANSLATE_SMOOTHING_VALUE)); this.addAction(DEVICE_KEYBOARD, KeyEvent.META_DOWN_MASK, VIEW_VERTICAL_TRANS_KEYS_META, - this.getActionAttributes(DEVICE_KEYBOARD, VIEW_VERTICAL_TRANS_KEYS)); + this.getActionAttributes(DEVICE_KEYBOARD, VIEW_VERTICAL_TRANS_KEYS)); this.addAction(DEVICE_KEYBOARD, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK, - VIEW_VERTICAL_TRANS_KEYS_SLOW_CTRL, - this.makeSlowActionAttributes(this.getActionAttributes( - DEVICE_KEYBOARD, VIEW_VERTICAL_TRANS_KEYS_CTRL), DEFAULT_SLOW_VALUE)); + VIEW_VERTICAL_TRANS_KEYS_SLOW_CTRL, + this.makeSlowActionAttributes(this.getActionAttributes( + DEVICE_KEYBOARD, VIEW_VERTICAL_TRANS_KEYS_CTRL), DEFAULT_SLOW_VALUE)); this.addAction(DEVICE_KEYBOARD, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK, - VIEW_VERTICAL_TRANS_KEYS_SLOW_META, - this.makeSlowActionAttributes(this.getActionAttributes( - DEVICE_KEYBOARD, VIEW_VERTICAL_TRANS_KEYS_CTRL), DEFAULT_SLOW_VALUE)); + VIEW_VERTICAL_TRANS_KEYS_SLOW_META, + this.makeSlowActionAttributes(this.getActionAttributes( + DEVICE_KEYBOARD, VIEW_VERTICAL_TRANS_KEYS_CTRL), DEFAULT_SLOW_VALUE)); // Reset Heading Action this.addAction(DEVICE_KEYBOARD, ActionAttributes.NO_MODIFIER, VIEW_RESET_HEADING, - new ActionAttributes(resetHeadingEvents, ActionAttributes.ActionTrigger.ON_PRESS, 0, - DEFAULT_KEY_ROTATE_MIN_VALUE, DEFAULT_KEY_ROTATE_MAX_VALUE, - DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); + new ActionAttributes(resetHeadingEvents, ActionAttributes.ActionTrigger.ON_PRESS, 0, + DEFAULT_KEY_ROTATE_MIN_VALUE, DEFAULT_KEY_ROTATE_MAX_VALUE, + DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); // Reset Heading, Pitch, and Roll Action this.addAction(DEVICE_KEYBOARD, ActionAttributes.NO_MODIFIER, VIEW_RESET_HEADING_PITCH_ROLL, - new ActionAttributes(resetHeadingPitchRollEvents, ActionAttributes.ActionTrigger.ON_PRESS, 0, - DEFAULT_KEY_ROTATE_MIN_VALUE, DEFAULT_KEY_ROTATE_MAX_VALUE, - DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); + new ActionAttributes(resetHeadingPitchRollEvents, ActionAttributes.ActionTrigger.ON_PRESS, 0, + DEFAULT_KEY_ROTATE_MIN_VALUE, DEFAULT_KEY_ROTATE_MAX_VALUE, + DEFAULT_ROTATE_SMOOTHING_ENABLED, DEFAULT_ROTATE_SMOOTHING_VALUE)); // Stop View Action this.addAction(DEVICE_KEYBOARD, ActionAttributes.NO_MODIFIER, VIEW_STOP_VIEW, - new ActionAttributes(stopViewEvents, ActionAttributes.ActionTrigger.ON_PRESS, 0, - 0.1, 0.1, false, 0.1)); + new ActionAttributes(stopViewEvents, ActionAttributes.ActionTrigger.ON_PRESS, 0, + 0.1, 0.1, false, 0.1)); } - protected ActionAttributes makeSlowActionAttributes(ActionAttributes attributes, double slowCoefficient) - { + protected ActionAttributes makeSlowActionAttributes(ActionAttributes attributes, double slowCoefficient) { ActionAttributes slowAttributes = new ActionAttributes(attributes); double[] values = attributes.getValues(); slowAttributes.setValues(values[0] * slowCoefficient, values[1] * slowCoefficient); diff --git a/src/gov/nasa/worldwind/awt/ViewInputHandler.java b/src/gov/nasa/worldwind/awt/ViewInputHandler.java index a87eb56a7a..1c8f32c0a8 100644 --- a/src/gov/nasa/worldwind/awt/ViewInputHandler.java +++ b/src/gov/nasa/worldwind/awt/ViewInputHandler.java @@ -17,8 +17,8 @@ * @version $Id: ViewInputHandler.java 1171 2013-02-11 21:45:02Z dcollins $ */ public interface ViewInputHandler - extends KeyListener, MouseListener, MouseMotionListener, MouseWheelListener, FocusListener -{ + extends KeyListener, MouseListener, MouseMotionListener, MouseWheelListener, FocusListener { + /** * Return the WorldWindow this ViewInputHandler is listening to for input events, and will modify in * response to those events @@ -30,8 +30,8 @@ public interface ViewInputHandler /** * Sets the WorldWindow this ViewInputHandler should listen to for input events, and should modify in - * response to those events. If the parameter newWorldWindow is null, then this ViewInputHandler - * will do nothing. + * response to those events. If the parameter newWorldWindow is null, then this ViewInputHandler will + * do nothing. * * @param newWorldWindow the WorldWindow to listen on, and modify in response to events. */ @@ -45,9 +45,8 @@ public interface ViewInputHandler ViewInputAttributes getAttributes(); /** - * Sets the values that will be used to transform raw input events into view movements. ViewInputAttributes - * define a calibration value for each combination of device and action, and a general sensitivity value - * for each device. + * Sets the values that will be used to transform raw input events into view movements. ViewInputAttributes define a + * calibration value for each combination of device and action, and a general sensitivity value for each device. * * @param attributes values that will be used to transform raw input into view movement. * @@ -65,8 +64,8 @@ public interface ViewInputHandler boolean isEnableSmoothing(); /** - * Sets whether the ViewInputHandler should smooth view movements in response to input events. A value of true - * will cause the ViewInputHandler to delegate decisions about whether to smooth a certain input event to its + * Sets whether the ViewInputHandler should smooth view movements in response to input events. A value of true will + * cause the ViewInputHandler to delegate decisions about whether to smooth a certain input event to its * {@link ViewInputAttributes}. A value of false will disable all smoothing. * * @param enable true to smooth view movements; false otherwise. @@ -81,9 +80,9 @@ public interface ViewInputHandler boolean isLockHeading(); /** - * Sets whether the view's heading should stay the same unless explicitly changed. For example, moving forward - * along a great arc would suggest a change in position and heading. If the heading had been locked, the - * ViewInputHandler will move forward in a way that doesn't change the heading. + * Sets whether the view's heading should stay the same unless explicitly changed. For example, moving forward along + * a great arc would suggest a change in position and heading. If the heading had been locked, the ViewInputHandler + * will move forward in a way that doesn't change the heading. * * @param lock true if the view's heading should stay the same unless explicity changed; false otherwise. */ @@ -104,8 +103,8 @@ public interface ViewInputHandler void setStopOnFocusLost(boolean stop); /** - * Returns the factor that dampens view movement when the user pans drags the cursor in a way that could - * cause an abrupt transition. + * Returns the factor that dampens view movement when the user pans drags the cursor in a way that + * could cause an abrupt transition. * * @return factor dampening view movement when a mouse drag event would cause an abrupt transition. * @see #setDragSlopeFactor @@ -113,13 +112,13 @@ public interface ViewInputHandler double getDragSlopeFactor(); /** - * Sets the factor that dampens view movement when a mouse drag event would cause an abrupt - * transition. The drag slope is the ratio of screen pixels to Cartesian distance moved, measured by the previous - * and current mouse points. As drag slope gets larger, it becomes more difficult to operate the view. This - * typically happens while dragging over and around the horizon, where movement of a few pixels can cause the view - * to move many kilometers. This factor is the amount of damping applied to the view movement in such - * cases. Setting factor to zero will disable this behavior, while setting factor to a - * positive value may dampen the effects of mouse dragging. + * Sets the factor that dampens view movement when a mouse drag event would cause an abrupt transition. + * The drag slope is the ratio of screen pixels to Cartesian distance moved, measured by the previous and current + * mouse points. As drag slope gets larger, it becomes more difficult to operate the view. This typically happens + * while dragging over and around the horizon, where movement of a few pixels can cause the view to move many + * kilometers. This factor is the amount of damping applied to the view movement in such cases. Setting + * factor to zero will disable this behavior, while setting factor to a positive value may + * dampen the effects of mouse dragging. * * @param factor dampening view movement when a mouse drag event would cause an abrupt transition. Must be greater * than or equal to zero. @@ -129,21 +128,20 @@ public interface ViewInputHandler void setDragSlopeFactor(double factor); /** - * Compute the drag slope the given screen and world coordinates. The drag slope is the ratio of - * screen pixels to Cartesian distance moved, measured by the previous and current mouse points. + * Compute the drag slope the given screen and world coordinates. The drag slope is the ratio of screen pixels to + * Cartesian distance moved, measured by the previous and current mouse points. * * @param point1 The previous mouse coordinate. * @param point2 The current mouse coordinate. * @param vec1 The first cartesian world space coordinate. * @param vec2 The second cartesion world space coordinate. - * @return the ratio of - * screen pixels to Cartesian distance moved. + * @return the ratio of screen pixels to Cartesian distance moved. */ double computeDragSlope(Point point1, Point point2, Vec4 vec1, Vec4 vec2); /** - * Animate to the specified position. The implementation is expected to animate the View to look - * at the given position from the given elevation. + * Animate to the specified position. The implementation is expected to animate the View to look at the + * given position from the given elevation. * * @param lookAtPos The position to animate the view to look at. * @param elevation The elevation to look at the position from. @@ -157,15 +155,16 @@ public interface ViewInputHandler /** * Determine if there are any animations active in the View. + * * @return true if there are active animations, false otherwise. */ boolean isAnimating(); /** - * Add an {@link gov.nasa.worldwind.animation.Animator} to this ViewInputHandler. - * This method does not start the {@link gov.nasa.worldwind.animation.Animator}. Starting the - * {@link gov.nasa.worldwind.animation.Animator} is the responsibility of the application. - * This method is here primarily for use by the {@link gov.nasa.worldwind.View}. Applications should call + * Add an {@link gov.nasa.worldwind.animation.Animator} to this ViewInputHandler. This method does not + * start the {@link gov.nasa.worldwind.animation.Animator}. Starting the + * {@link gov.nasa.worldwind.animation.Animator} is the responsibility of the application. This method is here + * primarily for use by the {@link gov.nasa.worldwind.View}. Applications should call * {@link gov.nasa.worldwind.View#addAnimator(gov.nasa.worldwind.animation.Animator)} to add an animtion to the * view. * diff --git a/src/gov/nasa/worldwind/awt/WorldWindowGLCanvas.java b/src/gov/nasa/worldwind/awt/WorldWindowGLCanvas.java index 66c77f610c..6197f964d9 100644 --- a/src/gov/nasa/worldwind/awt/WorldWindowGLCanvas.java +++ b/src/gov/nasa/worldwind/awt/WorldWindowGLCanvas.java @@ -29,8 +29,9 @@ * components. A discussion of doing so is in the Heavyweight and Lightweight Issues section of the "JOGL User's Guide". All that's typically necessary is * to invoke the following methods of the indicated Swing classes: {@link javax.swing.ToolTipManager#setLightWeightPopupEnabled(boolean)}, - * {@link javax.swing.JPopupMenu#setLightWeightPopupEnabled(boolean)} and {@link javax.swing.JPopupMenu#setLightWeightPopupEnabled(boolean)}. - * These methods should be invoked within a static block within an application's main class. + * {@link javax.swing.JPopupMenu#setLightWeightPopupEnabled(boolean)} and + * {@link javax.swing.JPopupMenu#setLightWeightPopupEnabled(boolean)}. These methods should be invoked within a + * static block within an application's main class. *

    * This class is capable of supporting stereo devices. To cause a stereo device to be selected and used, specify the * Java VM property "gov.nasa.worldwind.stereo.mode=device" prior to creating an instance of this class. A stereo @@ -53,18 +54,20 @@ * @author Tom Gaskins * @version $Id: WorldWindowGLCanvas.java 2924 2015-03-26 01:32:02Z tgaskins $ */ -public class WorldWindowGLCanvas extends GLCanvas implements WorldWindow, PropertyChangeListener -{ - /** The drawable to which {@link WorldWindow} methods are delegated. */ +public class WorldWindowGLCanvas extends GLCanvas implements WorldWindow, PropertyChangeListener { + + /** + * The drawable to which {@link WorldWindow} methods are delegated. + */ protected final WorldWindowGLDrawable wwd; // WorldWindow interface delegates to wwd - /** Constructs a new WorldWindowGLCanvas on the default graphics device. */ - public WorldWindowGLCanvas() - { + /** + * Constructs a new WorldWindowGLCanvas on the default graphics device. + */ + public WorldWindowGLCanvas() { super(Configuration.getRequiredGLCapabilities(), new BasicGLCapabilitiesChooser(), null); - try - { + try { this.wwd = ((WorldWindowGLDrawable) WorldWind.createConfigurationComponent(AVKey.WORLD_WINDOW_CLASS_NAME)); this.wwd.initDrawable(this); this.wwd.addPropertyChangeListener(this); @@ -74,9 +77,7 @@ public WorldWindowGLCanvas() WorldWind.addPropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); WorldWindowImpl.configureIdentityPixelScale(this); this.wwd.endInitialization(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Awt.WorldWindowGLSurface.UnabletoCreateWindow"); Logging.logger().severe(message); throw new WWRuntimeException(message, e); @@ -91,30 +92,28 @@ public WorldWindowGLCanvas() * * @see GLCanvas#GLCanvas(GLCapabilitiesImmutable, GLCapabilitiesChooser, GraphicsDevice) */ - public WorldWindowGLCanvas(WorldWindow shareWith) - { + public WorldWindowGLCanvas(WorldWindow shareWith) { super(Configuration.getRequiredGLCapabilities(), new BasicGLCapabilitiesChooser(), null); - if (shareWith != null) + if (shareWith != null) { this.setSharedAutoDrawable((WorldWindowGLCanvas) shareWith); + } - try - { + try { this.wwd = ((WorldWindowGLDrawable) WorldWind.createConfigurationComponent(AVKey.WORLD_WINDOW_CLASS_NAME)); this.wwd.initDrawable(this); this.wwd.addPropertyChangeListener(this); - if (shareWith != null) + if (shareWith != null) { this.wwd.initGpuResourceCache(shareWith.getGpuResourceCache()); - else + } else { this.wwd.initGpuResourceCache(WorldWindowImpl.createGpuResourceCache()); + } this.createView(); this.createDefaultInputHandler(); WorldWind.addPropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); WorldWindowImpl.configureIdentityPixelScale(this); this.wwd.endInitialization(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Awt.WorldWindowGLSurface.UnabletoCreateWindow"); Logging.logger().severe(message); throw new WWRuntimeException(message, e); @@ -126,35 +125,33 @@ public WorldWindowGLCanvas(WorldWindow shareWith) * with another WorldWindow. * * @param shareWith a WorldWindow with which to share graphics resources. - * @param device the GraphicsDevice on which to create the window. May be null, in which case the - * default screen device of the local {@link GraphicsEnvironment} is used. + * @param device the GraphicsDevice on which to create the window. May be null, in which case the + * default screen device of the local {@link GraphicsEnvironment} is used. * * @see GLCanvas#GLCanvas(GLCapabilitiesImmutable, GLCapabilitiesChooser, GraphicsDevice) */ - public WorldWindowGLCanvas(WorldWindow shareWith, java.awt.GraphicsDevice device) - { + public WorldWindowGLCanvas(WorldWindow shareWith, java.awt.GraphicsDevice device) { super(Configuration.getRequiredGLCapabilities(), new BasicGLCapabilitiesChooser(), device); - if (shareWith != null) + if (shareWith != null) { this.setSharedContext(shareWith.getContext()); + } - try - { + try { this.wwd = ((WorldWindowGLDrawable) WorldWind.createConfigurationComponent(AVKey.WORLD_WINDOW_CLASS_NAME)); this.wwd.initDrawable(this); this.wwd.addPropertyChangeListener(this); - if (shareWith != null) + if (shareWith != null) { this.wwd.initGpuResourceCache(shareWith.getGpuResourceCache()); - else + } else { this.wwd.initGpuResourceCache(WorldWindowImpl.createGpuResourceCache()); + } this.createView(); this.createDefaultInputHandler(); WorldWind.addPropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); WorldWindowImpl.configureIdentityPixelScale(this); this.wwd.endInitialization(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Awt.WorldWindowGLSurface.UnabletoCreateWindow"); Logging.logger().severe(message); throw new WWRuntimeException(message, e); @@ -166,303 +163,262 @@ public WorldWindowGLCanvas(WorldWindow shareWith, java.awt.GraphicsDevice device * shares graphics resources with another WorldWindow. * * @param shareWith a WorldWindow with which to share graphics resources. - * @param device the GraphicsDevice on which to create the window. May be null, in which case the - * default screen device of the local {@link GraphicsEnvironment} is used. + * @param device the GraphicsDevice on which to create the window. May be null, in which case the + * default screen device of the local {@link GraphicsEnvironment} is used. * @param capabilities a capabilities object indicating the OpenGL rendering context's capabilities. May be null, in - * which case a default set of capabilities is used. - * @param chooser a chooser object that customizes the specified capabilities. May be null, in which case a - * default chooser is used. + * which case a default set of capabilities is used. + * @param chooser a chooser object that customizes the specified capabilities. May be null, in which case a default + * chooser is used. * * @see GLCanvas#GLCanvas(GLCapabilitiesImmutable, GLCapabilitiesChooser, GraphicsDevice) */ public WorldWindowGLCanvas(WorldWindow shareWith, java.awt.GraphicsDevice device, - GLCapabilities capabilities, GLCapabilitiesChooser chooser) - { + GLCapabilities capabilities, GLCapabilitiesChooser chooser) { super(capabilities, chooser, device); - if (shareWith != null) + if (shareWith != null) { this.setSharedContext(shareWith.getContext()); + } - try - { + try { this.wwd = ((WorldWindowGLDrawable) WorldWind.createConfigurationComponent(AVKey.WORLD_WINDOW_CLASS_NAME)); this.wwd.initDrawable(this); - if (shareWith != null) + if (shareWith != null) { this.wwd.initGpuResourceCache(shareWith.getGpuResourceCache()); - else + } else { this.wwd.initGpuResourceCache(WorldWindowImpl.createGpuResourceCache()); + } this.createView(); this.createDefaultInputHandler(); WorldWind.addPropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); WorldWindowImpl.configureIdentityPixelScale(this); this.wwd.endInitialization(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Awt.WorldWindowGLSurface.UnabletoCreateWindow"); Logging.logger().severe(message); throw new WWRuntimeException(message, e); } } - public void propertyChange(PropertyChangeEvent evt) - { - if(this.wwd == evt.getSource()) + public void propertyChange(PropertyChangeEvent evt) { + if (this.wwd == evt.getSource()) { this.firePropertyChange(evt); + } //noinspection StringEquality - if (evt.getPropertyName() == WorldWind.SHUTDOWN_EVENT) + if (evt.getPropertyName() == WorldWind.SHUTDOWN_EVENT) { this.shutdown(); + } } - public void shutdown() - { + public void shutdown() { WorldWind.removePropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); this.wwd.shutdown(); } @Override - public boolean isEnableGpuCacheReinitialization() - { + public boolean isEnableGpuCacheReinitialization() { return this.wwd.isEnableGpuCacheReinitialization(); } @Override - public void setEnableGpuCacheReinitialization(boolean enableGpuCacheReinitialization) - { + public void setEnableGpuCacheReinitialization(boolean enableGpuCacheReinitialization) { this.wwd.setEnableGpuCacheReinitialization(enableGpuCacheReinitialization); } - /** Constructs and attaches the {@link View} for this WorldWindow. */ - protected void createView() - { + /** + * Constructs and attaches the {@link View} for this WorldWindow. + */ + protected void createView() { this.setView((View) WorldWind.createConfigurationComponent(AVKey.VIEW_CLASS_NAME)); } - /** Constructs and attaches the {@link InputHandler} for this WorldWindow. */ - protected void createDefaultInputHandler() - { + /** + * Constructs and attaches the {@link InputHandler} for this WorldWindow. + */ + protected void createDefaultInputHandler() { this.setInputHandler((InputHandler) WorldWind.createConfigurationComponent(AVKey.INPUT_HANDLER_CLASS_NAME)); } - public InputHandler getInputHandler() - { + public InputHandler getInputHandler() { return this.wwd.getInputHandler(); } - public void setInputHandler(InputHandler inputHandler) - { - if (this.wwd.getInputHandler() != null) + public void setInputHandler(InputHandler inputHandler) { + if (this.wwd.getInputHandler() != null) { this.wwd.getInputHandler().setEventSource(null); // remove this window as a source of events - + } this.wwd.setInputHandler(inputHandler != null ? inputHandler : new NoOpInputHandler()); - if (inputHandler != null) + if (inputHandler != null) { inputHandler.setEventSource(this); + } } - public SceneController getSceneController() - { + public SceneController getSceneController() { return this.wwd.getSceneController(); } - public void setSceneController(SceneController sceneController) - { + public void setSceneController(SceneController sceneController) { this.wwd.setSceneController(sceneController); } - public GpuResourceCache getGpuResourceCache() - { + public GpuResourceCache getGpuResourceCache() { return this.wwd.getGpuResourceCache(); } - public void redraw() - { + public void redraw() { this.repaint(); } - public void redrawNow() - { + public void redrawNow() { this.wwd.redrawNow(); } - public void setModel(Model model) - { + public void setModel(Model model) { // null models are permissible this.wwd.setModel(model); } - public Model getModel() - { + public Model getModel() { return this.wwd.getModel(); } - public void setView(View view) - { + public void setView(View view) { // null views are permissible - if (view != null) + if (view != null) { this.wwd.setView(view); + } } - public View getView() - { + public View getView() { return this.wwd.getView(); } - public void setModelAndView(Model model, View view) - { // null models/views are permissible + public void setModelAndView(Model model, View view) { // null models/views are permissible this.setModel(model); this.setView(view); } - public void addRenderingListener(RenderingListener listener) - { + public void addRenderingListener(RenderingListener listener) { this.wwd.addRenderingListener(listener); } - public void removeRenderingListener(RenderingListener listener) - { + public void removeRenderingListener(RenderingListener listener) { this.wwd.removeRenderingListener(listener); } - public void addSelectListener(SelectListener listener) - { + public void addSelectListener(SelectListener listener) { this.wwd.getInputHandler().addSelectListener(listener); this.wwd.addSelectListener(listener); } - public void removeSelectListener(SelectListener listener) - { + public void removeSelectListener(SelectListener listener) { this.wwd.getInputHandler().removeSelectListener(listener); this.wwd.removeSelectListener(listener); } - public void addPositionListener(PositionListener listener) - { + public void addPositionListener(PositionListener listener) { this.wwd.addPositionListener(listener); } - public void removePositionListener(PositionListener listener) - { + public void removePositionListener(PositionListener listener) { this.wwd.removePositionListener(listener); } - public void addRenderingExceptionListener(RenderingExceptionListener listener) - { + public void addRenderingExceptionListener(RenderingExceptionListener listener) { this.wwd.addRenderingExceptionListener(listener); } - public void removeRenderingExceptionListener(RenderingExceptionListener listener) - { + public void removeRenderingExceptionListener(RenderingExceptionListener listener) { this.wwd.removeRenderingExceptionListener(listener); } - public Position getCurrentPosition() - { + public Position getCurrentPosition() { return this.wwd.getCurrentPosition(); } - public PickedObjectList getObjectsAtCurrentPosition() - { + public PickedObjectList getObjectsAtCurrentPosition() { return this.wwd.getSceneController() != null ? this.wwd.getSceneController().getPickedObjectList() : null; } - public PickedObjectList getObjectsInSelectionBox() - { + public PickedObjectList getObjectsInSelectionBox() { return this.wwd.getSceneController() != null ? this.wwd.getSceneController().getObjectsInPickRectangle() : null; } - public Object setValue(String key, Object value) - { + public Object setValue(String key, Object value) { return this.wwd.setValue(key, value); } - public AVList setValues(AVList avList) - { + public AVList setValues(AVList avList) { return this.wwd.setValues(avList); } - public Object getValue(String key) - { + public Object getValue(String key) { return this.wwd.getValue(key); } - public Collection getValues() - { + public Collection getValues() { return this.wwd.getValues(); } - public Set> getEntries() - { + public Set> getEntries() { return this.wwd.getEntries(); } - public String getStringValue(String key) - { + public String getStringValue(String key) { return this.wwd.getStringValue(key); } - public boolean hasKey(String key) - { + public boolean hasKey(String key) { return this.wwd.hasKey(key); } - public Object removeKey(String key) - { + public Object removeKey(String key) { return this.wwd.removeKey(key); } @Override - public synchronized void addPropertyChangeListener(PropertyChangeListener listener) - { + public synchronized void addPropertyChangeListener(PropertyChangeListener listener) { super.addPropertyChangeListener(listener); } @Override - public synchronized void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public synchronized void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { super.addPropertyChangeListener(propertyName, listener); } @Override - public synchronized void removePropertyChangeListener(PropertyChangeListener listener) - { + public synchronized void removePropertyChangeListener(PropertyChangeListener listener) { super.removePropertyChangeListener(listener); } @Override - public synchronized void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public synchronized void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { super.removePropertyChangeListener(propertyName, listener); } @Override - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { super.firePropertyChange(propertyName, oldValue, newValue); } - public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) { this.wwd.firePropertyChange(propertyChangeEvent); } - public AVList copy() - { + public AVList copy() { return this.wwd.copy(); } - public AVList clearList() - { + public AVList clearList() { return this.wwd.clearList(); } - public void setPerFrameStatisticsKeys(Set keys) - { + public void setPerFrameStatisticsKeys(Set keys) { this.wwd.setPerFrameStatisticsKeys(keys); } - public Collection getPerFrameStatistics() - { + public Collection getPerFrameStatistics() { return this.wwd.getPerFrameStatistics(); } } diff --git a/src/gov/nasa/worldwind/awt/WorldWindowGLJPanel.java b/src/gov/nasa/worldwind/awt/WorldWindowGLJPanel.java index 1840a87637..ad3ee86f78 100644 --- a/src/gov/nasa/worldwind/awt/WorldWindowGLJPanel.java +++ b/src/gov/nasa/worldwind/awt/WorldWindowGLJPanel.java @@ -52,18 +52,20 @@ * @author Tom Gaskins * @version $Id: WorldWindowGLJPanel.java 2047 2014-06-06 22:48:33Z tgaskins $ */ -public class WorldWindowGLJPanel extends GLJPanel implements WorldWindow, PropertyChangeListener -{ - /** The drawable to which {@link WorldWindow} methods are delegated. */ +public class WorldWindowGLJPanel extends GLJPanel implements WorldWindow, PropertyChangeListener { + + /** + * The drawable to which {@link WorldWindow} methods are delegated. + */ protected final WorldWindowGLDrawable wwd; // WorldWindow interface delegates to wwd - /** Constructs a new WorldWindowGLCanvas window on the default graphics device. */ - public WorldWindowGLJPanel() - { + /** + * Constructs a new WorldWindowGLCanvas window on the default graphics device. + */ + public WorldWindowGLJPanel() { super(Configuration.getRequiredGLCapabilities(), new BasicGLCapabilitiesChooser()); - try - { + try { this.wwd = ((WorldWindowGLDrawable) WorldWind.createConfigurationComponent(AVKey.WORLD_WINDOW_CLASS_NAME)); this.wwd.initDrawable(this); this.wwd.addPropertyChangeListener(this); @@ -73,9 +75,7 @@ public WorldWindowGLJPanel() WorldWind.addPropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); WorldWindowImpl.configureIdentityPixelScale(this); this.wwd.endInitialization(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Awt.WorldWindowGLSurface.UnabletoCreateWindow"); Logging.logger().severe(message); throw new WWRuntimeException(message, e); @@ -90,30 +90,28 @@ public WorldWindowGLJPanel() * * @see GLJPanel#GLJPanel(GLCapabilitiesImmutable, GLCapabilitiesChooser) */ - public WorldWindowGLJPanel(WorldWindow shareWith) - { + public WorldWindowGLJPanel(WorldWindow shareWith) { super(Configuration.getRequiredGLCapabilities(), new BasicGLCapabilitiesChooser()); - if (shareWith != null) + if (shareWith != null) { this.setSharedContext(shareWith.getContext()); + } - try - { + try { this.wwd = ((WorldWindowGLDrawable) WorldWind.createConfigurationComponent(AVKey.WORLD_WINDOW_CLASS_NAME)); this.wwd.initDrawable(this); this.wwd.addPropertyChangeListener(this); - if (shareWith != null) + if (shareWith != null) { this.wwd.initGpuResourceCache(shareWith.getGpuResourceCache()); - else + } else { this.wwd.initGpuResourceCache(WorldWindowImpl.createGpuResourceCache()); + } this.createView(); this.createDefaultInputHandler(); WorldWind.addPropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); WorldWindowImpl.configureIdentityPixelScale(this); this.wwd.endInitialization(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Awt.WorldWindowGLSurface.UnabletoCreateWindow"); Logging.logger().severe(message); throw new WWRuntimeException(message, e); @@ -125,303 +123,262 @@ public WorldWindowGLJPanel(WorldWindow shareWith) * WorldWindow and whose capabilities are chosen via a specified {@link GLCapabilities} object and a * {@link GLCapabilitiesChooser}. * - * @param shareWith a WorldWindow with which to share graphics resources. + * @param shareWith a WorldWindow with which to share graphics resources. * @param capabilities a capabilities object indicating the OpenGL rendering context's capabilities. May be null, in - * which case a default set of capabilities is used. - * @param chooser a chooser object that customizes the specified capabilities. May be null, in which case a - * default chooser is used. + * which case a default set of capabilities is used. + * @param chooser a chooser object that customizes the specified capabilities. May be null, in which case a default + * chooser is used. * * @see GLJPanel#GLJPanel(GLCapabilitiesImmutable, GLCapabilitiesChooser) */ public WorldWindowGLJPanel(WorldWindow shareWith, GLCapabilities capabilities, - GLCapabilitiesChooser chooser) - { + GLCapabilitiesChooser chooser) { super(capabilities, chooser); - if (shareWith != null) + if (shareWith != null) { this.setSharedContext(shareWith.getContext()); + } - try - { + try { this.wwd = ((WorldWindowGLDrawable) WorldWind.createConfigurationComponent(AVKey.WORLD_WINDOW_CLASS_NAME)); this.wwd.initDrawable(this); this.wwd.addPropertyChangeListener(this); - if (shareWith != null) + if (shareWith != null) { this.wwd.initGpuResourceCache(shareWith.getGpuResourceCache()); - else + } else { this.wwd.initGpuResourceCache(WorldWindowImpl.createGpuResourceCache()); + } this.createView(); this.createDefaultInputHandler(); WorldWind.addPropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); WorldWindowImpl.configureIdentityPixelScale(this); this.wwd.endInitialization(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Awt.WorldWindowGLSurface.UnabletoCreateWindow"); Logging.logger().severe(message); throw new WWRuntimeException(message, e); } } - public void propertyChange(PropertyChangeEvent evt) - { - if(this.wwd == evt.getSource()) + public void propertyChange(PropertyChangeEvent evt) { + if (this.wwd == evt.getSource()) { this.firePropertyChange(evt); + } //noinspection StringEquality - if (evt.getPropertyName() == WorldWind.SHUTDOWN_EVENT) + if (evt.getPropertyName() == WorldWind.SHUTDOWN_EVENT) { this.shutdown(); + } } - public void shutdown() - { + public void shutdown() { WorldWind.removePropertyChangeListener(WorldWind.SHUTDOWN_EVENT, this); this.wwd.shutdown(); } @Override - public boolean isEnableGpuCacheReinitialization() - { + public boolean isEnableGpuCacheReinitialization() { return this.wwd.isEnableGpuCacheReinitialization(); } @Override - public void setEnableGpuCacheReinitialization(boolean enableGpuCacheReinitialization) - { + public void setEnableGpuCacheReinitialization(boolean enableGpuCacheReinitialization) { this.wwd.setEnableGpuCacheReinitialization(enableGpuCacheReinitialization); } - /** Constructs and attaches the {@link View} for this WorldWindow. */ - protected void createView() - { + /** + * Constructs and attaches the {@link View} for this WorldWindow. + */ + protected void createView() { this.setView((View) WorldWind.createConfigurationComponent(AVKey.VIEW_CLASS_NAME)); } - /** Constructs and attaches the {@link InputHandler} for this WorldWindow. */ - protected void createDefaultInputHandler() - { + /** + * Constructs and attaches the {@link InputHandler} for this WorldWindow. + */ + protected void createDefaultInputHandler() { this.setInputHandler((InputHandler) WorldWind.createConfigurationComponent(AVKey.INPUT_HANDLER_CLASS_NAME)); } - public InputHandler getInputHandler() - { + public InputHandler getInputHandler() { return this.wwd.getInputHandler(); } - public void setInputHandler(InputHandler inputHandler) - { - if (this.wwd.getInputHandler() != null) + public void setInputHandler(InputHandler inputHandler) { + if (this.wwd.getInputHandler() != null) { this.wwd.getInputHandler().setEventSource(null); // remove this window as a source of events - + } this.wwd.setInputHandler(inputHandler != null ? inputHandler : new NoOpInputHandler()); - if (inputHandler != null) + if (inputHandler != null) { inputHandler.setEventSource(this); + } } - public SceneController getSceneController() - { + public SceneController getSceneController() { return this.wwd.getSceneController(); } - public void setSceneController(SceneController sceneController) - { + public void setSceneController(SceneController sceneController) { this.wwd.setSceneController(sceneController); } - public GpuResourceCache getGpuResourceCache() - { + public GpuResourceCache getGpuResourceCache() { return this.wwd.getGpuResourceCache(); } - public void redraw() - { + public void redraw() { this.repaint(); } - public void redrawNow() - { + public void redrawNow() { this.wwd.redrawNow(); } - public void setModel(Model model) - { + public void setModel(Model model) { // null models are permissible this.wwd.setModel(model); } - public Model getModel() - { + public Model getModel() { return this.wwd.getModel(); } - public void setView(View view) - { + public void setView(View view) { // null views are permissible - if (view != null) + if (view != null) { this.wwd.setView(view); + } } - public View getView() - { + public View getView() { return this.wwd.getView(); } - public void setModelAndView(Model model, View view) - { // null models/views are permissible + public void setModelAndView(Model model, View view) { // null models/views are permissible this.setModel(model); this.setView(view); } - public void addRenderingListener(RenderingListener listener) - { + public void addRenderingListener(RenderingListener listener) { this.wwd.addRenderingListener(listener); } - public void removeRenderingListener(RenderingListener listener) - { + public void removeRenderingListener(RenderingListener listener) { this.wwd.removeRenderingListener(listener); } - public void addSelectListener(SelectListener listener) - { + public void addSelectListener(SelectListener listener) { this.wwd.getInputHandler().addSelectListener(listener); this.wwd.addSelectListener(listener); } - public void removeSelectListener(SelectListener listener) - { + public void removeSelectListener(SelectListener listener) { this.wwd.getInputHandler().removeSelectListener(listener); this.wwd.removeSelectListener(listener); } - public void addPositionListener(PositionListener listener) - { + public void addPositionListener(PositionListener listener) { this.wwd.addPositionListener(listener); } - public void removePositionListener(PositionListener listener) - { + public void removePositionListener(PositionListener listener) { this.wwd.removePositionListener(listener); } - public void addRenderingExceptionListener(RenderingExceptionListener listener) - { + public void addRenderingExceptionListener(RenderingExceptionListener listener) { this.wwd.addRenderingExceptionListener(listener); } - public void removeRenderingExceptionListener(RenderingExceptionListener listener) - { + public void removeRenderingExceptionListener(RenderingExceptionListener listener) { this.wwd.removeRenderingExceptionListener(listener); } - public Position getCurrentPosition() - { + public Position getCurrentPosition() { return this.wwd.getCurrentPosition(); } - public PickedObjectList getObjectsAtCurrentPosition() - { + public PickedObjectList getObjectsAtCurrentPosition() { return this.wwd.getSceneController() != null ? this.wwd.getSceneController().getPickedObjectList() : null; } - public PickedObjectList getObjectsInSelectionBox() - { + public PickedObjectList getObjectsInSelectionBox() { return this.wwd.getSceneController() != null ? this.wwd.getSceneController().getObjectsInPickRectangle() : null; } - public Object setValue(String key, Object value) - { + public Object setValue(String key, Object value) { return this.wwd.setValue(key, value); } - public AVList setValues(AVList avList) - { + public AVList setValues(AVList avList) { return this.wwd.setValues(avList); } - public Object getValue(String key) - { + public Object getValue(String key) { return this.wwd.getValue(key); } - public Collection getValues() - { + public Collection getValues() { return this.wwd.getValues(); } - public Set> getEntries() - { + public Set> getEntries() { return this.wwd.getEntries(); } - public String getStringValue(String key) - { + public String getStringValue(String key) { return this.wwd.getStringValue(key); } - public boolean hasKey(String key) - { + public boolean hasKey(String key) { return this.wwd.hasKey(key); } - public Object removeKey(String key) - { + public Object removeKey(String key) { return this.wwd.removeKey(key); } @Override - public synchronized void addPropertyChangeListener(PropertyChangeListener listener) - { + public synchronized void addPropertyChangeListener(PropertyChangeListener listener) { super.addPropertyChangeListener(listener); } @Override - public synchronized void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public synchronized void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { super.addPropertyChangeListener(propertyName, listener); } @Override - public synchronized void removePropertyChangeListener(PropertyChangeListener listener) - { + public synchronized void removePropertyChangeListener(PropertyChangeListener listener) { super.removePropertyChangeListener(listener); } @Override - public synchronized void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public synchronized void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { super.removePropertyChangeListener(propertyName, listener); } @Override - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { super.firePropertyChange(propertyName, oldValue, newValue); } - public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) { this.wwd.firePropertyChange(propertyChangeEvent); } - public AVList copy() - { + public AVList copy() { return this.wwd.copy(); } - public AVList clearList() - { + public AVList clearList() { return this.wwd.clearList(); } - public void setPerFrameStatisticsKeys(Set keys) - { + public void setPerFrameStatisticsKeys(Set keys) { this.wwd.setPerFrameStatisticsKeys(keys); } - public Collection getPerFrameStatistics() - { + public Collection getPerFrameStatistics() { return this.wwd.getPerFrameStatistics(); } } diff --git a/src/gov/nasa/worldwind/cache/AbstractFileStore.java b/src/gov/nasa/worldwind/cache/AbstractFileStore.java index 4243b9fc2f..4a207bc4be 100644 --- a/src/gov/nasa/worldwind/cache/AbstractFileStore.java +++ b/src/gov/nasa/worldwind/cache/AbstractFileStore.java @@ -15,74 +15,63 @@ * @author tag * @version $Id: AbstractFileStore.java 2190 2014-08-01 21:54:20Z pabercrombie $ */ -public abstract class AbstractFileStore extends WWObjectImpl implements FileStore -{ - protected static class StoreLocation extends AVListImpl - { +public abstract class AbstractFileStore extends WWObjectImpl implements FileStore { + + protected static class StoreLocation extends AVListImpl { + protected boolean markWhenUsed = false; - public StoreLocation(java.io.File file, boolean isInstall) - { + public StoreLocation(java.io.File file, boolean isInstall) { this.setValue(AVKey.FILE_STORE_LOCATION, file); this.setValue(AVKey.INSTALLED, isInstall); } - public StoreLocation(java.io.File file) - { + public StoreLocation(java.io.File file) { this(file, false); } - public java.io.File getFile() - { + public java.io.File getFile() { Object o = this.getValue(AVKey.FILE_STORE_LOCATION); return (o != null && o instanceof java.io.File) ? (java.io.File) o : null; } - public void setFile(java.io.File file) - { + public void setFile(java.io.File file) { this.setValue(AVKey.FILE_STORE_LOCATION, file); } - public boolean isInstall() - { + public boolean isInstall() { Object o = this.getValue(AVKey.INSTALLED); return (o != null && o instanceof Boolean) ? (Boolean) o : false; } - public void setInstall(boolean isInstall) - { + public void setInstall(boolean isInstall) { this.setValue(AVKey.INSTALLED, isInstall); } - public boolean isMarkWhenUsed() - { + public boolean isMarkWhenUsed() { return markWhenUsed; } - public void setMarkWhenUsed(boolean markWhenUsed) - { + public void setMarkWhenUsed(boolean markWhenUsed) { this.markWhenUsed = markWhenUsed; } } // Retrieval could be occurring on several threads when the app adds a read location, so protect the list of read // locations from concurrent modification. - protected final java.util.List readLocations = - new java.util.concurrent.CopyOnWriteArrayList(); + protected final java.util.List readLocations + = new java.util.concurrent.CopyOnWriteArrayList(); protected StoreLocation writeLocation = null; private final Object fileLock = new Object(); //**************************************************************// //******************** File Store Configuration **************// //**************************************************************// + protected void initialize(java.io.InputStream xmlConfigStream) { + javax.xml.parsers.DocumentBuilderFactory docBuilderFactory + = javax.xml.parsers.DocumentBuilderFactory.newInstance(); - protected void initialize(java.io.InputStream xmlConfigStream) - { - javax.xml.parsers.DocumentBuilderFactory docBuilderFactory = - javax.xml.parsers.DocumentBuilderFactory.newInstance(); - - try - { + try { javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); org.w3c.dom.Document doc = docBuilder.parse(xmlConfigStream); @@ -91,52 +80,41 @@ protected void initialize(java.io.InputStream xmlConfigStream) this.buildWritePaths(doc); this.buildReadPaths(doc); - if (this.writeLocation == null) - { + if (this.writeLocation == null) { Logging.logger().warning("FileStore.NoWriteLocation"); } - if (this.readLocations.size() == 0) - { + if (this.readLocations.size() == 0) { // This should not happen because the writable location is added to the read list, but check nonetheless String message = Logging.getMessage("FileStore.NoReadLocations"); Logging.logger().severe(message); throw new IllegalStateException(message); } - } - catch (javax.xml.parsers.ParserConfigurationException e) - { + } catch (javax.xml.parsers.ParserConfigurationException e) { String message = Logging.getMessage("FileStore.ExceptionReadingConfigurationFile"); Logging.logger().severe(message); throw new IllegalStateException(message, e); - } - catch (org.xml.sax.SAXException e) - { + } catch (org.xml.sax.SAXException e) { String message = Logging.getMessage("FileStore.ExceptionReadingConfigurationFile"); Logging.logger().severe(message); throw new IllegalStateException(message, e); - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { String message = Logging.getMessage("FileStore.ExceptionReadingConfigurationFile"); Logging.logger().severe(message); throw new IllegalStateException(message, e); } } - protected void buildReadPaths(org.w3c.dom.Node dataFileStoreNode) - { + protected void buildReadPaths(org.w3c.dom.Node dataFileStoreNode) { javax.xml.xpath.XPathFactory pathFactory = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath pathFinder = pathFactory.newXPath(); - try - { + try { org.w3c.dom.NodeList locationNodes = (org.w3c.dom.NodeList) pathFinder.evaluate( - "/dataFileStore/readLocations/location", - dataFileStoreNode.getFirstChild(), - javax.xml.xpath.XPathConstants.NODESET); - for (int i = 0; i < locationNodes.getLength(); i++) - { + "/dataFileStore/readLocations/location", + dataFileStoreNode.getFirstChild(), + javax.xml.xpath.XPathConstants.NODESET); + for (int i = 0; i < locationNodes.getLength(); i++) { org.w3c.dom.Node location = locationNodes.item(i); String prop = pathFinder.evaluate("@property", location); String wwDir = pathFinder.evaluate("@wwDir", location); @@ -145,23 +123,22 @@ protected void buildReadPaths(org.w3c.dom.Node dataFileStoreNode) String isMarkWhenUsed = pathFinder.evaluate("@isMarkWhenUsed", location); String path = buildLocationPath(prop, append, wwDir); - if (path == null) - { + if (path == null) { Logging.logger().log(Level.WARNING, "FileStore.LocationInvalid", - prop != null ? prop : Logging.getMessage("generic.Unknown")); + prop != null ? prop : Logging.getMessage("generic.Unknown")); continue; } StoreLocation oldStore = this.storeLocationFor(path); if (oldStore != null) // filter out duplicates + { continue; + } // Even paths that don't exist or are otherwise problematic are added to the list because they may // become readable during the session. E.g., removable media. So add them to the search list. - java.io.File pathFile = new java.io.File(path); - if (pathFile.exists() && !pathFile.isDirectory()) - { + if (pathFile.exists() && !pathFile.isDirectory()) { Logging.logger().log(Level.WARNING, "FileStore.LocationIsFile", pathFile.getPath()); } @@ -171,14 +148,13 @@ protected void buildReadPaths(org.w3c.dom.Node dataFileStoreNode) // If the input parameter "markWhenUsed" is null or empty, then the StoreLocation should keep its // default value. Otherwise the store location value is set to true when the input parameter contains // "t", and is set to false otherwise. - if (isMarkWhenUsed != null && isMarkWhenUsed.length() > 0) + if (isMarkWhenUsed != null && isMarkWhenUsed.length() > 0) { newStore.setMarkWhenUsed(isMarkWhenUsed.toLowerCase().contains("t")); + } this.readLocations.add(newStore); } - } - catch (javax.xml.xpath.XPathExpressionException e) - { + } catch (javax.xml.xpath.XPathExpressionException e) { String message = Logging.getMessage("FileStore.ExceptionReadingConfigurationFile"); Logging.logger().severe(message); throw new IllegalStateException(message, e); @@ -186,19 +162,16 @@ protected void buildReadPaths(org.w3c.dom.Node dataFileStoreNode) } @SuppressWarnings({"ResultOfMethodCallIgnored"}) - protected void buildWritePaths(org.w3c.dom.Node dataFileCacheNode) - { + protected void buildWritePaths(org.w3c.dom.Node dataFileCacheNode) { javax.xml.xpath.XPathFactory pathFactory = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath pathFinder = pathFactory.newXPath(); - try - { + try { org.w3c.dom.NodeList locationNodes = (org.w3c.dom.NodeList) pathFinder.evaluate( - "/dataFileStore/writeLocations/location", - dataFileCacheNode.getFirstChild(), - javax.xml.xpath.XPathConstants.NODESET); - for (int i = 0; i < locationNodes.getLength(); i++) - { + "/dataFileStore/writeLocations/location", + dataFileCacheNode.getFirstChild(), + javax.xml.xpath.XPathConstants.NODESET); + for (int i = 0; i < locationNodes.getLength(); i++) { org.w3c.dom.Node location = locationNodes.item(i); String prop = pathFinder.evaluate("@property", location); String wwDir = pathFinder.evaluate("@wwDir", location); @@ -206,30 +179,28 @@ protected void buildWritePaths(org.w3c.dom.Node dataFileCacheNode) String create = pathFinder.evaluate("@create", location); String path = buildLocationPath(prop, append, wwDir); - if (path == null) - { + if (path == null) { Logging.logger().log(Level.WARNING, "FileStore.LocationInvalid", - prop != null ? prop : Logging.getMessage("generic.Unknown")); + prop != null ? prop : Logging.getMessage("generic.Unknown")); continue; } Logging.logger().log(Level.FINER, "FileStore.AttemptingWriteDir", path); java.io.File pathFile = new java.io.File(path); - if (!pathFile.exists() && create != null && (create.contains("t") || create.contains("T"))) - { + if (!pathFile.exists() && create != null && (create.contains("t") || create.contains("T"))) { Logging.logger().log(Level.FINER, "FileStore.MakingDirsFor", path); pathFile.mkdirs(); } - if (pathFile.isDirectory() && pathFile.canWrite() && pathFile.canRead()) - { + if (pathFile.isDirectory() && pathFile.canWrite() && pathFile.canRead()) { Logging.logger().log(Level.FINER, "FileStore.WriteLocationSuccessful", path); this.writeLocation = new StoreLocation(pathFile); // Remove the writable location from search path if it already exists. StoreLocation oldLocation = this.storeLocationFor(path); - if (oldLocation != null) + if (oldLocation != null) { this.readLocations.remove(oldLocation); + } // Writable location is always first in search path. this.readLocations.add(0, this.writeLocation); @@ -237,91 +208,79 @@ protected void buildWritePaths(org.w3c.dom.Node dataFileCacheNode) break; // only need one } } - } - catch (javax.xml.xpath.XPathExpressionException e) - { + } catch (javax.xml.xpath.XPathExpressionException e) { String message = Logging.getMessage("FileStore.ExceptionReadingConfigurationFile"); Logging.logger().severe(message); throw new IllegalStateException(message, e); } } - protected static String buildLocationPath(String property, String append, String wwDir) - { + protected static String buildLocationPath(String property, String append, String wwDir) { String path = propertyToPath(property); - if (append != null && append.length() != 0) + if (append != null && append.length() != 0) { path = WWIO.appendPathPart(path, append.trim()); + } - if (wwDir != null && wwDir.length() != 0) + if (wwDir != null && wwDir.length() != 0) { path = WWIO.appendPathPart(path, wwDir.trim()); + } return path; } - protected static String propertyToPath(String propName) - { - if (propName == null || propName.length() == 0) + protected static String propertyToPath(String propName) { + if (propName == null || propName.length() == 0) { return null; + } String prop = System.getProperty(propName); - if (prop != null) + if (prop != null) { return prop; + } - if (propName.equalsIgnoreCase("gov.nasa.worldwind.platform.alluser.store")) + if (propName.equalsIgnoreCase("gov.nasa.worldwind.platform.alluser.store")) { return determineAllUserLocation(); + } - if (propName.equalsIgnoreCase("gov.nasa.worldwind.platform.user.store")) + if (propName.equalsIgnoreCase("gov.nasa.worldwind.platform.user.store")) { return determineSingleUserLocation(); + } return null; } - protected static String determineAllUserLocation() - { - if (gov.nasa.worldwind.Configuration.isMacOS()) - { + protected static String determineAllUserLocation() { + if (gov.nasa.worldwind.Configuration.isMacOS()) { return "/Library/Caches"; - } - else if (gov.nasa.worldwind.Configuration.isWindowsOS()) - { + } else if (gov.nasa.worldwind.Configuration.isWindowsOS()) { String path = System.getenv("ALLUSERSPROFILE"); - if (path == null) - { + if (path == null) { Logging.logger().severe("generic.AllUsersWindowsProfileNotKnown"); return null; } return path + (Configuration.isWindows7OS() ? "" : "\\Application Data"); - } - else if (gov.nasa.worldwind.Configuration.isLinuxOS() || gov.nasa.worldwind.Configuration.isUnixOS() - || gov.nasa.worldwind.Configuration.isSolarisOS()) - { + } else if (gov.nasa.worldwind.Configuration.isLinuxOS() || gov.nasa.worldwind.Configuration.isUnixOS() + || gov.nasa.worldwind.Configuration.isSolarisOS()) { return "/var/cache/"; - } - else - { + } else { Logging.logger().warning("generic.UnknownOperatingSystem"); return null; } } - protected static String determineSingleUserLocation() - { + protected static String determineSingleUserLocation() { String home = getUserHomeDir(); - if (home == null) - { + if (home == null) { Logging.logger().warning("generic.UsersHomeDirectoryNotKnown"); return null; } String path = null; - if (gov.nasa.worldwind.Configuration.isMacOS()) - { + if (gov.nasa.worldwind.Configuration.isMacOS()) { path = "/Library/Caches"; - } - else if (gov.nasa.worldwind.Configuration.isWindowsOS()) - { + } else if (gov.nasa.worldwind.Configuration.isWindowsOS()) { // This produces an incorrect path with duplicate parts, // like "C:\Users\PatC:\Users\Pat\Application Data". //path = System.getenv("USERPROFILE"); @@ -333,83 +292,71 @@ else if (gov.nasa.worldwind.Configuration.isWindowsOS()) //path += "\\Application Data"; path = "\\Application Data"; - } - else if (gov.nasa.worldwind.Configuration.isLinuxOS() || gov.nasa.worldwind.Configuration.isUnixOS() - || gov.nasa.worldwind.Configuration.isSolarisOS()) - { + } else if (gov.nasa.worldwind.Configuration.isLinuxOS() || gov.nasa.worldwind.Configuration.isUnixOS() + || gov.nasa.worldwind.Configuration.isSolarisOS()) { path = "/var/cache/"; - } - else - { + } else { Logging.logger().fine("generic.UnknownOperatingSystem"); } - if (path == null) + if (path == null) { return null; + } return home + path; } - protected static String getUserHomeDir() - { + protected static String getUserHomeDir() { return System.getProperty("user.home"); } //**************************************************************// //******************** File Store Locations ******************// //**************************************************************// - - public java.util.List getLocations() - { + public java.util.List getLocations() { java.util.ArrayList locations = new java.util.ArrayList(); - for (StoreLocation location : this.readLocations) - { + for (StoreLocation location : this.readLocations) { locations.add(location.getFile()); } return locations; } - public java.io.File getWriteLocation() - { + public java.io.File getWriteLocation() { return (this.writeLocation != null) ? this.writeLocation.getFile() : null; } - public void addLocation(String newPath, boolean isInstall) - { + public void addLocation(String newPath, boolean isInstall) { this.addLocation(this.readLocations.size(), newPath, isInstall); } - public void addLocation(int index, String newPath, boolean isInstall) - { - if (newPath == null || newPath.length() == 0) - { + public void addLocation(int index, String newPath, boolean isInstall) { + if (newPath == null || newPath.length() == 0) { String message = Logging.getMessage("nullValue.FileStorePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (index < 0) - { + if (index < 0) { String message = Logging.getMessage("generic.InvalidIndex", index); Logging.logger().fine(message); throw new IllegalArgumentException(message); } StoreLocation oldLocation = this.storeLocationFor(newPath); - if (oldLocation != null) + if (oldLocation != null) { this.readLocations.remove(oldLocation); + } - if (index > 0 && index > this.readLocations.size()) + if (index > 0 && index > this.readLocations.size()) { index = this.readLocations.size(); + } java.io.File newFile = new java.io.File(newPath); StoreLocation newLocation = new StoreLocation(newFile, isInstall); this.readLocations.add(index, newLocation); } - public void removeLocation(String path) - { - if (path == null || path.length() == 0) - { + public void removeLocation(String path) { + if (path == null || path.length() == 0) { String message = Logging.getMessage("nullValue.FileStorePathIsNull"); Logging.logger().severe(message); // Just warn and return. @@ -418,10 +365,11 @@ public void removeLocation(String path) StoreLocation location = this.storeLocationFor(path); if (location == null) // Path is not part of this FileStore. + { return; + } - if (location.equals(this.writeLocation)) - { + if (location.equals(this.writeLocation)) { String message = Logging.getMessage("FileStore.CannotRemoveWriteLocation", path); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -430,10 +378,8 @@ public void removeLocation(String path) this.readLocations.remove(location); } - public boolean isInstallLocation(String path) - { - if (path == null || path.length() == 0) - { + public boolean isInstallLocation(String path) { + if (path == null || path.length() == 0) { String message = Logging.getMessage("nullValue.FileStorePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -443,14 +389,13 @@ public boolean isInstallLocation(String path) return location != null && location.isInstall(); } - protected StoreLocation storeLocationFor(String path) - { + protected StoreLocation storeLocationFor(String path) { java.io.File file = new java.io.File(path); - for (StoreLocation location : this.readLocations) - { - if (file.equals(location.getFile())) + for (StoreLocation location : this.readLocations) { + if (file.equals(location.getFile())) { return location; + } } return null; @@ -459,86 +404,81 @@ protected StoreLocation storeLocationFor(String path) //**************************************************************// //******************** File Store Contents *******************// //**************************************************************// - - public boolean containsFile(String fileName) - { - if (fileName == null) + public boolean containsFile(String fileName) { + if (fileName == null) { return false; + } - for (StoreLocation location : this.readLocations) - { + for (StoreLocation location : this.readLocations) { java.io.File dir = location.getFile(); java.io.File file; - if (fileName.startsWith(dir.getAbsolutePath())) + if (fileName.startsWith(dir.getAbsolutePath())) { file = new java.io.File(fileName); - else + } else { file = makeAbsoluteFile(dir, fileName); + } - if (file.exists()) + if (file.exists()) { return true; + } } return false; } /** - * @param fileName the name of the file to find + * @param fileName the name of the file to find * @param checkClassPath if true, the class path is first searched for the file, otherwise the class - * path is not searched unless it's one of the explicit paths in the cache search directories + * path is not searched unless it's one of the explicit paths in the cache search directories * * @return a handle to the requested file if it exists in the cache, otherwise null * * @throws IllegalArgumentException if fileName is null */ - public java.net.URL findFile(String fileName, boolean checkClassPath) - { - if (fileName == null) - { + public java.net.URL findFile(String fileName, boolean checkClassPath) { + if (fileName == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (checkClassPath) - { + if (checkClassPath) { java.net.URL url = this.getClass().getClassLoader().getResource(fileName); - if (url != null) + if (url != null) { return url; + } // Check for a thread context class loader. This allows the file store to find resources in a case // in which different parts of the application are handled by different class loaders. ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - if (tccl != null) - { + if (tccl != null) { url = tccl.getResource(fileName); - if (url != null) + if (url != null) { return url; + } } } - for (StoreLocation location : this.readLocations) - { + for (StoreLocation location : this.readLocations) { java.io.File dir = location.getFile(); - if (!dir.exists()) + if (!dir.exists()) { continue; + } java.io.File file = new java.io.File(makeAbsolutePath(dir, fileName)); - if (file.exists()) - { - try - { - if (location.isMarkWhenUsed()) + if (file.exists()) { + try { + if (location.isMarkWhenUsed()) { markFileUsed(file); - else + } else { markFileUsed(file.getParentFile()); + } return file.toURI().toURL(); - } - catch (java.net.MalformedURLException e) - { + } catch (java.net.MalformedURLException e) { Logging.logger().log(Level.SEVERE, - Logging.getMessage("FileStore.ExceptionCreatingURLForFile", file.getPath()), e); + Logging.getMessage("FileStore.ExceptionCreatingURLForFile", file.getPath()), e); } } } @@ -547,22 +487,25 @@ public java.net.URL findFile(String fileName, boolean checkClassPath) } @SuppressWarnings({"ResultOfMethodCallIgnored"}) - protected static void markFileUsed(java.io.File file) - { - if (file == null) + protected static void markFileUsed(java.io.File file) { + if (file == null) { return; + } long currentTime = System.currentTimeMillis(); - if (file.canWrite()) + if (file.canWrite()) { file.setLastModified(currentTime); + } - if (file.isDirectory()) + if (file.isDirectory()) { return; + } java.io.File parent = file.getParentFile(); - if (parent != null && parent.canWrite()) + if (parent != null && parent.canWrite()) { parent.setLastModified(currentTime); + } } /** @@ -572,17 +515,14 @@ protected static void markFileUsed(java.io.File file) * * @throws IllegalArgumentException if fileName is null */ - public java.io.File newFile(String fileName) - { - if (fileName == null) - { + public java.io.File newFile(String fileName) { + if (fileName == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.writeLocation != null) - { + if (this.writeLocation != null) { String fullPath = makeAbsolutePath(this.writeLocation.getFile(), fileName); java.io.File file = new java.io.File(fullPath); boolean canCreateFile = false; @@ -591,18 +531,17 @@ public java.io.File newFile(String fileName) // file.getParentFile() does not exist, and become immediately suspended. A second thread may then create // the parent and ancestor directories. When the first thread wakes up, file.getParentFile().mkdirs() // fails, resulting in an erroneous log message: The log reports that the file cannot be created. - synchronized (this.fileLock) - { - if (file.getParentFile().exists()) + synchronized (this.fileLock) { + if (file.getParentFile().exists()) { canCreateFile = true; - else if (file.getParentFile().mkdirs()) + } else if (file.getParentFile().mkdirs()) { canCreateFile = true; + } } - if (canCreateFile) + if (canCreateFile) { return file; - else - { + } else { String msg = Logging.getMessage("generic.CannotCreateFile", fullPath); Logging.logger().severe(msg); } @@ -613,60 +552,51 @@ else if (file.getParentFile().mkdirs()) /** * @param url the "file:" URL of the file to remove from the file store. Only files in the writable WorldWind disk - * cache or temp file directory are removed by this method. + * cache or temp file directory are removed by this method. * * @throws IllegalArgumentException if url is null */ @SuppressWarnings({"ResultOfMethodCallIgnored"}) - public void removeFile(java.net.URL url) - { - if (url == null) - { + public void removeFile(java.net.URL url) { + if (url == null) { String msg = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - try - { + try { java.io.File file = new java.io.File(url.toURI()); // This block of code must be synchronized for proper operation. A thread may check that the file exists, // and become immediately suspended. A second thread may then delete that file. When the first thread // wakes up, file.delete() fails. - synchronized (this.fileLock) - { - if (file.exists()) - { + synchronized (this.fileLock) { + if (file.exists()) { // Don't remove files outside the cache or temp directory. String parent = file.getParent(); if (!(parent.startsWith(this.getWriteLocation().getPath()) - || parent.startsWith(Configuration.getSystemTempDirectory()))) + || parent.startsWith(Configuration.getSystemTempDirectory()))) { return; + } file.delete(); } } - } - catch (java.net.URISyntaxException e) - { + } catch (java.net.URISyntaxException e) { Logging.logger().log(Level.SEVERE, Logging.getMessage("FileStore.ExceptionRemovingFile", url.toString()), - e); + e); } } - protected static java.io.File makeAbsoluteFile(java.io.File file, String fileName) - { + protected static java.io.File makeAbsoluteFile(java.io.File file, String fileName) { return new java.io.File(file.getAbsolutePath() + "/" + fileName); } - protected static String makeAbsolutePath(java.io.File dir, String fileName) - { + protected static String makeAbsolutePath(java.io.File dir, String fileName) { return dir.getAbsolutePath() + "/" + fileName; } - protected static String normalizeFileStoreName(String fileName) - { + protected static String normalizeFileStoreName(String fileName) { // Convert all file separators to forward slashes, and strip any leading or trailing file separators // from the path. String normalizedName = fileName.replaceAll("\\\\", "/"); @@ -676,15 +606,14 @@ protected static String normalizeFileStoreName(String fileName) return normalizedName; } - protected static String storePathForFile(StoreLocation location, java.io.File file) - { + protected static String storePathForFile(StoreLocation location, java.io.File file) { String path = file.getPath(); - if (location != null) - { + if (location != null) { String locationPath = location.getFile().getPath(); - if (path.startsWith(locationPath)) + if (path.startsWith(locationPath)) { path = path.substring(locationPath.length(), path.length()); + } } return path; @@ -693,11 +622,8 @@ protected static String storePathForFile(StoreLocation location, java.io.File fi //**************************************************************// //******************** File Store Content Discovery **********// //**************************************************************// - - public String[] listFileNames(String pathName, FileStoreFilter filter) - { - if (filter == null) - { + public String[] listFileNames(String pathName, FileStoreFilter filter) { + if (filter == null) { String msg = Logging.getMessage("nullValue.FilterIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -707,10 +633,8 @@ public String[] listFileNames(String pathName, FileStoreFilter filter) return this.doListFileNames(pathName, filter, false, false); } - public String[] listAllFileNames(String pathName, FileStoreFilter filter) - { - if (filter == null) - { + public String[] listAllFileNames(String pathName, FileStoreFilter filter) { + if (filter == null) { String msg = Logging.getMessage("nullValue.FilterIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -720,10 +644,8 @@ public String[] listAllFileNames(String pathName, FileStoreFilter filter) return this.doListFileNames(pathName, filter, true, false); } - public String[] listTopFileNames(String pathName, FileStoreFilter filter) - { - if (filter == null) - { + public String[] listTopFileNames(String pathName, FileStoreFilter filter) { + if (filter == null) { String msg = Logging.getMessage("nullValue.FilterIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -734,33 +656,35 @@ public String[] listTopFileNames(String pathName, FileStoreFilter filter) } protected String[] doListFileNames(String pathName, FileStoreFilter filter, boolean recurse, - boolean exitBranchOnFirstMatch) - { + boolean exitBranchOnFirstMatch) { java.util.ArrayList nameList = null; - for (StoreLocation location : this.readLocations) - { + for (StoreLocation location : this.readLocations) { // If the path name is null, then just search from the root of each location. Otherwise search from the // named cache path. java.io.File dir = location.getFile(); - if (pathName != null) + if (pathName != null) { dir = new java.io.File(makeAbsolutePath(dir, pathName)); + } // Either the location does not exists, or the speciifed path does not exist under that location. In either // case we skip searching this location. - if (!dir.exists()) + if (!dir.exists()) { continue; + } // Lazily initialize the list of file names. If no location contains the specified path, then the list is // not created, and this method will return null. - if (nameList == null) + if (nameList == null) { nameList = new java.util.ArrayList(); + } this.doListFileNames(location, dir, filter, recurse, exitBranchOnFirstMatch, nameList); } - if (nameList == null) + if (nameList == null) { return null; + } String[] names = new String[nameList.size()]; nameList.toArray(names); @@ -768,47 +692,44 @@ protected String[] doListFileNames(String pathName, FileStoreFilter filter, bool } protected void doListFileNames(StoreLocation location, java.io.File dir, FileStoreFilter filter, - boolean recurse, boolean exitBranchOnFirstMatch, java.util.Collection names) - { + boolean recurse, boolean exitBranchOnFirstMatch, java.util.Collection names) { java.util.ArrayList subDirs = new java.util.ArrayList(); // Search the children of the specified directory. If the child is a directory, append it to the list of sub // directories to search later. Otherwise, try to list the file as a match. If the file is a match and // exitBranchOnFirstMatch is true, then exit this branch without considering any other files. This has the // effect of choosing files closest to the search root. - for (java.io.File childFile : dir.listFiles()) - { - if (childFile == null) + for (java.io.File childFile : dir.listFiles()) { + if (childFile == null) { continue; + } - if (childFile.isDirectory()) - { + if (childFile.isDirectory()) { subDirs.add(childFile); - } - else - { - if (this.listFile(location, childFile, filter, names) && exitBranchOnFirstMatch) + } else { + if (this.listFile(location, childFile, filter, names) && exitBranchOnFirstMatch) { return; + } } } - if (!recurse) + if (!recurse) { return; + } // Recursively search each sub-directory. If exitBranchOnFirstMatch is true, then we did not find a match under // this directory. - for (java.io.File childDir : subDirs) - { + for (java.io.File childDir : subDirs) { this.doListFileNames(location, childDir, filter, recurse, exitBranchOnFirstMatch, names); } } protected boolean listFile(StoreLocation location, java.io.File file, FileStoreFilter filter, - java.util.Collection names) - { + java.util.Collection names) { String fileName = storePathForFile(location, file); - if (fileName == null) + if (fileName == null) { return false; + } String normalizedName = normalizeFileStoreName(fileName); return this.listFileName(location, normalizedName, filter, names); @@ -816,10 +737,10 @@ protected boolean listFile(StoreLocation location, java.io.File file, FileStoreF @SuppressWarnings({"UnusedDeclaration"}) protected boolean listFileName(StoreLocation location, String fileName, FileStoreFilter filter, - java.util.Collection names) - { - if (!filter.accept(this, fileName)) + java.util.Collection names) { + if (!filter.accept(this, fileName)) { return false; + } names.add(fileName); return true; diff --git a/src/gov/nasa/worldwind/cache/BasicDataFileStore.java b/src/gov/nasa/worldwind/cache/BasicDataFileStore.java index 923c692716..1bd9675a5b 100644 --- a/src/gov/nasa/worldwind/cache/BasicDataFileStore.java +++ b/src/gov/nasa/worldwind/cache/BasicDataFileStore.java @@ -22,23 +22,29 @@ * @author Tom Gaskins * @version $Id: BasicDataFileStore.java 1950 2014-04-20 18:52:47Z tgaskins $ */ -public class BasicDataFileStore extends AbstractFileStore -{ - /** The number of milliseconds to wait before a retrieval request for the same file can be reissued. */ +public class BasicDataFileStore extends AbstractFileStore { + + /** + * The number of milliseconds to wait before a retrieval request for the same file can be reissued. + */ protected static final long TIMEOUT = (long) 5e3; - /** The default content types used to determine an unknown file format in requestFile. */ + /** + * The default content types used to determine an unknown file format in requestFile. + */ protected static final List DEFAULT_CACHE_CONTENT_TYPES = Arrays.asList( - "application/vnd.google-earth.kml+xml", - "application/vnd.google-earth.kmz", - "model/collada+xml", - "image/dds", - "image/gif", - "image/jpeg", - "image/jpg", - "image/png" + "application/vnd.google-earth.kml+xml", + "application/vnd.google-earth.kmz", + "model/collada+xml", + "image/dds", + "image/gif", + "image/jpeg", + "image/jpg", + "image/png" ); - /** The map of cached entries. */ + /** + * The map of cached entries. + */ protected BasicMemoryCache db = new BasicMemoryCache((long) 3e5, (long) 5e5); /** * Absent-resource list to keep track of resources that were requested by requestFile but failed. The default list @@ -67,13 +73,11 @@ public class BasicDataFileStore extends AbstractFileStore * Create an instance. * * @throws IllegalStateException if the configuration file name cannot be determined from {@link Configuration} or - * the configuration file cannot be found. + * the configuration file cannot be found. */ - public BasicDataFileStore() - { + public BasicDataFileStore() { String configPath = Configuration.getStringValue(AVKey.DATA_FILE_STORE_CONFIGURATION_FILE_NAME); - if (configPath == null) - { + if (configPath == null) { String message = Logging.getMessage("FileStore.NoConfiguration"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -81,26 +85,20 @@ public BasicDataFileStore() java.io.InputStream is = null; File configFile = new File(configPath); - if (configFile.exists()) - { - try - { + if (configFile.exists()) { + try { is = new FileInputStream(configFile); - } - catch (FileNotFoundException e) - { + } catch (FileNotFoundException e) { String message = Logging.getMessage("FileStore.LocalConfigFileNotFound", configPath); Logging.logger().finest(message); } } - if (is == null) - { + if (is == null) { is = this.getClass().getClassLoader().getResourceAsStream(configPath); } - if (is == null) - { + if (is == null) { String message = Logging.getMessage("FileStore.ConfigurationNotFound", configPath); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -114,10 +112,8 @@ public BasicDataFileStore() * * @param directoryPath the directory to manage as a file store. */ - public BasicDataFileStore(File directoryPath) - { - if (directoryPath == null) - { + public BasicDataFileStore(File directoryPath) { + if (directoryPath == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -133,21 +129,19 @@ public BasicDataFileStore(File directoryPath) } @Override - protected void initialize(InputStream xmlConfigStream) - { + protected void initialize(InputStream xmlConfigStream) { super.initialize(xmlConfigStream); String s = Configuration.getStringValue(AVKey.CACHE_CONTENT_TYPES); - if (s != null) - { + if (s != null) { this.cacheContentTypes.clear(); String[] contentTypes = s.split(","); - for (String type : contentTypes) - { + for (String type : contentTypes) { type = type.trim(); - if (!WWUtil.isEmpty(type)) + if (!WWUtil.isEmpty(type)) { this.cacheContentTypes.add(type); + } } } } @@ -157,8 +151,7 @@ protected void initialize(InputStream xmlConfigStream) * * @return the file store's absent-resource list. */ - protected AbsentResourceList getAbsentResourceList() - { + protected AbsentResourceList getAbsentResourceList() { return this.absentResources; } @@ -167,32 +160,33 @@ protected AbsentResourceList getAbsentResourceList() * * @return the file store's list of content types. */ - protected List getCacheContentTypes() - { + protected List getCacheContentTypes() { return this.cacheContentTypes; } - public String getContentType(String address) - { - if (address == null) + public String getContentType(String address) { + if (address == null) { return null; + } DBEntry entry = (DBEntry) this.db.getObject(address); return entry != null ? entry.contentType : null; } - public long getExpirationTime(String address) - { - if (address == null) + public long getExpirationTime(String address) { + if (address == null) { return 0; + } DBEntry entry = (DBEntry) this.db.getObject(address); return entry != null ? entry.expiration : 0; } - /** Holds information for entries in the cache database. */ - protected static class DBEntry implements Cacheable - { + /** + * Holds information for entries in the cache database. + */ + protected static class DBEntry implements Cacheable { + protected final static int NONE = 0; protected final static int PENDING = 1; protected final static int LOCAL = 2; @@ -204,33 +198,31 @@ protected static class DBEntry implements Cacheable protected long lastUpdateTime; protected int state; - public DBEntry(String name) - { + public DBEntry(String name) { this.name = name; this.state = NONE; this.lastUpdateTime = System.currentTimeMillis(); } - public long getSizeInBytes() - { + public long getSizeInBytes() { return 40 + (name != null ? 2 * name.length() : 0); } } - /** {@inheritDoc} */ - public synchronized void removeFile(String address) - { - if (address == null) - { + /** + * {@inheritDoc} + */ + public synchronized void removeFile(String address) { + if (address == null) { String message = Logging.getMessage("nullValue.AddressIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } DBEntry entry = (DBEntry) this.db.getObject(address); - if (entry == null) + if (entry == null) { return; // Nothing to delete - + } // Delete the cache file this.removeFile(entry.localUrl); @@ -238,11 +230,11 @@ public synchronized void removeFile(String address) this.db.remove(address); } - /** {@inheritDoc} */ - public synchronized URL requestFile(String address) - { - if (address == null) - { + /** + * {@inheritDoc} + */ + public synchronized URL requestFile(String address) { + if (address == null) { String message = Logging.getMessage("nullValue.AddressIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -253,31 +245,33 @@ public synchronized URL requestFile(String address) return this.requestFile(address, true); } - /** {@inheritDoc} */ - public synchronized URL requestFile(String address, boolean cacheRemoteFile) - { - if (address == null) - { + /** + * {@inheritDoc} + */ + public synchronized URL requestFile(String address, boolean cacheRemoteFile) { + if (address == null) { String message = Logging.getMessage("nullValue.AddressIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.getAbsentResourceList().isResourceAbsent(address)) + if (this.getAbsentResourceList().isResourceAbsent(address)) { return null; + } DBEntry entry = (DBEntry) this.db.getObject(address); - if (entry != null) - { + if (entry != null) { long now = System.currentTimeMillis(); boolean expired = entry.expiration != 0 && now > entry.expiration; // Return the resource if it is local and has not expired. - if (entry.state == DBEntry.LOCAL && !expired) + if (entry.state == DBEntry.LOCAL && !expired) { return entry.localUrl; + } - if (entry.state == DBEntry.PENDING && (now - entry.lastUpdateTime <= TIMEOUT)) + if (entry.state == DBEntry.PENDING && (now - entry.lastUpdateTime <= TIMEOUT)) { return null; + } } URL url = WWIO.makeURL(address); // this may or may not make a URL, depending on address type @@ -285,44 +279,44 @@ public synchronized URL requestFile(String address, boolean cacheRemoteFile) // If the address is already a URL in the "file" scheme, we can just use return this URL. Otherwise, // attempt to find a local file for the address. - if (url != null && "file".equalsIgnoreCase(url.getProtocol())) + if (url != null && "file".equalsIgnoreCase(url.getProtocol())) { localUrl = url; - else + } else { localUrl = this.getLocalFileUrl(address, url, cacheRemoteFile); // Don't look for temp files in the cache. - + } if (localUrl != null) // file exists if local URL is non-null + { return localUrl; + } // If the address' URL is not null but the file was not found locally, try to make it local. Store the retrieved // file in the cache if cacheRemoteFile is true, otherwise store it in a temporary location. - if (url != null && !this.getAbsentResourceList().isResourceAbsent(address)) + if (url != null && !this.getAbsentResourceList().isResourceAbsent(address)) { this.makeLocal(address, url, cacheRemoteFile); - else if (url == null) + } else if (url == null) { this.getAbsentResourceList().markResourceAbsent(address); // no URL for address and not a local file - + } return null; } /** * Returns a file from the cache, the local file system or the classpath if the file exists. The specified address * may be a jar URL. See {@link java.net.JarURLConnection} for a description of jar URLs. If - * searchLocalCache is true this looks for the file in the WorldWind cache, otherwise - * this only looks for the file in the local file system and the classpath. + * searchLocalCache is true this looks for the file in the WorldWind cache, otherwise this + * only looks for the file in the local file system and the classpath. * - * @param address the name used to identify the cached file. - * @param retrievalUrl the URL to obtain the file if it is not in the cache. Used only to determine a location - * to search in the local cache. May be null. + * @param address the name used to identify the cached file. + * @param retrievalUrl the URL to obtain the file if it is not in the cache. Used only to determine a location to + * search in the local cache. May be null. * @param searchLocalCache true to look for the file in the WorldWind cache, otherwise - * false. + * false. * * @return the requested file if it exists, otherwise null. * * @throws IllegalArgumentException if the specified address is null. */ - protected synchronized URL getLocalFileUrl(String address, URL retrievalUrl, boolean searchLocalCache) - { - if (address == null) - { + protected synchronized URL getLocalFileUrl(String address, URL retrievalUrl, boolean searchLocalCache) { + if (address == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -330,15 +324,12 @@ protected synchronized URL getLocalFileUrl(String address, URL retrievalUrl, boo URL cacheFileUrl = null; - if (address.trim().startsWith("jar:")) - { + if (address.trim().startsWith("jar:")) { URL jarUrl = WWIO.makeURL(address); // retrieval URL may be other than the address' URL - if (WWIO.isLocalJarAddress(jarUrl)) - { - if (this.getJarLength(jarUrl) > 0) + if (WWIO.isLocalJarAddress(jarUrl)) { + if (this.getJarLength(jarUrl) > 0) { cacheFileUrl = jarUrl; - else - { + } else { getAbsentResourceList().markResourceAbsent(address); return null; } @@ -346,18 +337,15 @@ protected synchronized URL getLocalFileUrl(String address, URL retrievalUrl, boo } String addressProtocol = retrievalUrl != null ? retrievalUrl.getProtocol() : null; - if (cacheFileUrl == null && (addressProtocol == null || addressProtocol.equals("file"))) - { + if (cacheFileUrl == null && (addressProtocol == null || addressProtocol.equals("file"))) { File f = new File(address); - if (f.exists()) - try - { + if (f.exists()) { + try { cacheFileUrl = f.toURI().toURL(); // makes a file URL - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { // The toURL call shouldn't fail, but continue on if it does. } + } } // If the address is a file, look for the file in the classpath and WorldWind disk cache. We perform this step @@ -365,13 +353,13 @@ protected synchronized URL getLocalFileUrl(String address, URL retrievalUrl, boo // We need to ensure that the address is not a network address (HTTP, etc.) because the getResource call in // findFile will attempt to retrieve from that URL on the thread that called this method, which might be the EDT // (See WWJ-434). - if (cacheFileUrl == null && (addressProtocol == null || addressProtocol.equals("file"))) + if (cacheFileUrl == null && (addressProtocol == null || addressProtocol.equals("file"))) { cacheFileUrl = WorldWind.getDataFileStore().findFile(address, true); + } // Look for the file in the WorldWind disk cache by creating a cache path from the file's address. We ignore this // step if searchLocalCache is false. - if (cacheFileUrl == null && retrievalUrl != null && searchLocalCache) - { + if (cacheFileUrl == null && retrievalUrl != null && searchLocalCache) { String cachePath = this.makeCachePath(retrievalUrl, null); cacheFileUrl = WorldWind.getDataFileStore().findFile(cachePath, true); @@ -382,20 +370,18 @@ protected synchronized URL getLocalFileUrl(String address, URL retrievalUrl, boo // and located it in the cache. Note that if the address has a suffix but is simply not in the cache, we do // not attempt to locate it by guessing its content type. String suffix = WWIO.getSuffix(cachePath); - if (cacheFileUrl == null && (suffix == null || suffix.length() > 4)) - { - for (String contentType : this.getCacheContentTypes()) - { + if (cacheFileUrl == null && (suffix == null || suffix.length() > 4)) { + for (String contentType : this.getCacheContentTypes()) { String pathWithSuffix = cachePath + WWIO.makeSuffixForMimeType(contentType); cacheFileUrl = WorldWind.getDataFileStore().findFile(pathWithSuffix, true); - if (cacheFileUrl != null) + if (cacheFileUrl != null) { break; + } } } } - if (cacheFileUrl != null) - { + if (cacheFileUrl != null) { DBEntry entry = new DBEntry(address); entry.localUrl = cacheFileUrl; entry.state = DBEntry.LOCAL; @@ -418,14 +404,10 @@ protected synchronized URL getLocalFileUrl(String address, URL retrievalUrl, boo * * @return the jar file's content length, or -1 if a connection to the URL can't be formed or queried. */ - protected int getJarLength(URL jarUrl) - { - try - { + protected int getJarLength(URL jarUrl) { + try { return jarUrl.openConnection().getContentLength(); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.JarOpenFailed", jarUrl.toString()); Logging.logger().log(java.util.logging.Level.WARNING, message, e); @@ -437,15 +419,15 @@ protected int getJarLength(URL jarUrl) * Retrieves a specified file and either adds it to the cache or saves it in a temporary file, depending on the * value of saveInLocalCache. * - * @param address the name used to identify the cached file. - * @param url the URL to obtain the file. + * @param address the name used to identify the cached file. + * @param url the URL to obtain the file. * @param saveInLocalCache true to add the file to the cache, or false to save it in a - * temporary location. + * temporary location. */ - protected synchronized void makeLocal(String address, URL url, boolean saveInLocalCache) - { - if (WorldWind.getNetworkStatus().isHostUnavailable(url) || !WorldWind.getRetrievalService().isAvailable()) + protected synchronized void makeLocal(String address, URL url, boolean saveInLocalCache) { + if (WorldWind.getNetworkStatus().isHostUnavailable(url) || !WorldWind.getRetrievalService().isAvailable()) { return; + } DBEntry newEntry = new DBEntry(address); this.db.add(address, newEntry); @@ -453,64 +435,61 @@ protected synchronized void makeLocal(String address, URL url, boolean saveInLoc Retriever retriever = URLRetriever.createRetriever(url, new PostProcessor(address, url, saveInLocalCache)); - if (retriever != null && !WorldWind.getRetrievalService().contains(retriever)) + if (retriever != null && !WorldWind.getRetrievalService().contains(retriever)) { WorldWind.getRetrievalService().runRetriever(retriever); + } } - protected class PostProcessor extends AbstractRetrievalPostProcessor - { + protected class PostProcessor extends AbstractRetrievalPostProcessor { + protected String address; protected URL retrievalUrl; protected URL localFileUrl = null; protected File outputFile = null; protected boolean saveInLocalCache; - public PostProcessor(String address, URL url, boolean saveInLocalCache) - { + public PostProcessor(String address, URL url, boolean saveInLocalCache) { this.address = address; this.retrievalUrl = url; this.saveInLocalCache = saveInLocalCache; } @Override - protected boolean overwriteExistingFile() - { + protected boolean overwriteExistingFile() { return true; } - protected File doGetOutputFile() - { + protected File doGetOutputFile() { // Create the output file once and cache the result to avoid creating unused temporary files. If this // PostProcessor's saveInLocalCache method is false, then make makeOutputFile creates a unique temporary // file on each call. Since this method is potentially called multiple times by // AbstractRetrievalPostProcessor, we call makeOutputFile at most one time so that only one temporary output // file is created. - if (this.outputFile == null) + if (this.outputFile == null) { this.outputFile = this.makeOutputFile(); + } return this.outputFile; } - protected File makeOutputFile() - { + protected File makeOutputFile() { File file; String path = makeCachePath(this.retrievalUrl, this.getRetriever().getContentType()); - if (this.saveInLocalCache && path.length() <= WWIO.MAX_FILE_PATH_LENGTH) + if (this.saveInLocalCache && path.length() <= WWIO.MAX_FILE_PATH_LENGTH) { file = WorldWind.getDataFileStore().newFile(path); - else + } else { file = BasicDataFileStore.this.makeTempFile(this.retrievalUrl, this.getRetriever().getContentType()); + } - if (file == null) + if (file == null) { return null; + } - try - { + try { this.localFileUrl = file.toURI().toURL(); return file; - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { String message = Logging.getMessage("generic.MalformedURL", file.toURI()); Logging.logger().finest(message); return null; @@ -518,36 +497,34 @@ protected File makeOutputFile() } @Override - protected boolean saveBuffer() throws IOException - { + protected boolean saveBuffer() throws IOException { boolean tf = super.saveBuffer(); BasicDataFileStore.this.updateEntry(this.address, this.localFileUrl, - this.getRetriever().getExpirationTime()); + this.getRetriever().getExpirationTime()); return tf; } @Override - protected ByteBuffer handleSuccessfulRetrieval() - { + protected ByteBuffer handleSuccessfulRetrieval() { ByteBuffer buffer = super.handleSuccessfulRetrieval(); firePropertyChange( - new PropertyChangeEvent(BasicDataFileStore.this, AVKey.RETRIEVAL_STATE_SUCCESSFUL, this.retrievalUrl, - this.localFileUrl)); + new PropertyChangeEvent(BasicDataFileStore.this, AVKey.RETRIEVAL_STATE_SUCCESSFUL, this.retrievalUrl, + this.localFileUrl)); return buffer; } @Override - protected void markResourceAbsent() - { + protected void markResourceAbsent() { BasicDataFileStore.this.getAbsentResourceList().markResourceAbsent(this.address); } - /** {@inheritDoc} Overridden to save text files in the cache. */ + /** + * {@inheritDoc} Overridden to save text files in the cache. + */ @Override - protected ByteBuffer handleTextContent() throws IOException - { + protected ByteBuffer handleTextContent() throws IOException { this.saveBuffer(); return this.getRetriever().getBuffer(); @@ -557,16 +534,16 @@ protected ByteBuffer handleTextContent() throws IOException /** * Updates a cache entry with information available once the file is retrieved. * - * @param address the name used to identify the file in the cache. + * @param address the name used to identify the file in the cache. * @param localFileUrl the path to the local copy of the file. - * @param expiration time (in milliseconds since the Epoch) at which this entry expires, or zero to indicate that - * there is no expiration time. + * @param expiration time (in milliseconds since the Epoch) at which this entry expires, or zero to indicate that + * there is no expiration time. */ - protected synchronized void updateEntry(String address, URL localFileUrl, long expiration) - { + protected synchronized void updateEntry(String address, URL localFileUrl, long expiration) { DBEntry entry = (DBEntry) this.db.getObject(address); - if (entry == null) + if (entry == null) { return; + } entry.state = DBEntry.LOCAL; entry.localUrl = localFileUrl; @@ -578,15 +555,15 @@ protected synchronized void updateEntry(String address, URL localFileUrl, long e /** * Makes a path to the file in the cache from the file's URL and content type. * - * @param url the URL to obtain the file. + * @param url the URL to obtain the file. * @param contentType the mime type of the file's contents. * * @return a path name. */ - protected String makeCachePath(URL url, String contentType) - { - if ("jar".equals(url.getProtocol())) + protected String makeCachePath(URL url, String contentType) { + if ("jar".equals(url.getProtocol())) { return this.makeJarURLCachePath(url, contentType); + } return this.makeGenericURLCachePath(url, contentType); } @@ -616,19 +593,17 @@ protected String makeCachePath(URL url, String contentType) * anyone using the same machine. If the query string is empty after removing any private parameters, it is ignored * and only the path part of the URL is used as the filename. * - * @param url the URL to obtain the file. + * @param url the URL to obtain the file. * @param contentType the mime type of the file's contents. * * @return a path name. */ - protected String makeGenericURLCachePath(URL url, String contentType) - { + protected String makeGenericURLCachePath(URL url, String contentType) { String host = WWIO.replaceIllegalFileNameCharacters(url.getHost()); String path = WWIO.replaceIllegalFileNameCharacters(url.getPath()); String filename = path; - if (!WWUtil.isEmpty(url.getQuery())) - { + if (!WWUtil.isEmpty(url.getQuery())) { // Remove private query parameters from the query string, and replace any illegal filename characters with // an underscore. This avoids exposing private parameters to other users by writing them to the cache as // part of the cache name. @@ -637,8 +612,7 @@ protected String makeGenericURLCachePath(URL url, String contentType) // If the query string is not empty after removing private parameters and illegal filename characters, we // use it as part of the cache name by appending it to the path part. - if (!WWUtil.isEmpty(query)) - { + if (!WWUtil.isEmpty(query)) { filename = path + "_" + query; } } @@ -648,8 +622,9 @@ protected String makeGenericURLCachePath(URL url, String contentType) // the same hash folder name can be re-created from the same address. If two URLs have the same hash string, // both URLs are stored under the same hash folder and are differentiated by their filenames. String hashString = String.valueOf(Math.abs(filename.hashCode())); - if (hashString.length() > 4) + if (hashString.length() > 4) { hashString = hashString.substring(0, 4); + } StringBuilder sb = new StringBuilder(); sb.append(host); @@ -659,8 +634,9 @@ protected String makeGenericURLCachePath(URL url, String contentType) sb.append(filename); String suffix = this.makeSuffix(filename, contentType); - if (suffix != null) + if (suffix != null) { sb.append(suffix); + } return sb.toString(); } @@ -674,13 +650,12 @@ protected String makeGenericURLCachePath(URL url, String contentType) * Where host is the path to the JAR file, path is the file's path within the JAR archive, * and suffix is either the path's suffix or a suffix created from the specified content type. * - * @param jarURL the URL to obtain the file. This URL is assumed to have the "jar" protocol. + * @param jarURL the URL to obtain the file. This URL is assumed to have the "jar" protocol. * @param contentType the mime type of the file's contents. * * @return a path name. */ - protected String makeJarURLCachePath(URL jarURL, String contentType) - { + protected String makeJarURLCachePath(URL jarURL, String contentType) { String innerAddress = jarURL.getPath(); URL innerUrl = WWIO.makeURL(innerAddress); String host = WWIO.replaceIllegalFileNameCharacters(innerUrl.getHost()); @@ -692,8 +667,9 @@ protected String makeJarURLCachePath(URL jarURL, String contentType) sb.append(path); String suffix = this.makeSuffix(path, contentType); - if (suffix != null) + if (suffix != null) { sb.append(suffix); + } return sb.toString(); } @@ -703,32 +679,30 @@ protected String makeJarURLCachePath(URL jarURL, String contentType) * not persist a mapping of retrieved URLs to temp files, this deletes the returned temp file when the current Java * Virtual Machine terminates. * - * @param url the URL to be associated with the temp file. Used only to determine an appropriate suffix. + * @param url the URL to be associated with the temp file. Used only to determine an appropriate suffix. * @param contentType the mime type of the file contents. Used to determine the file's suffix. * * @return a temporary file, or null if a file could not be created. */ - protected File makeTempFile(URL url, String contentType) - { + protected File makeTempFile(URL url, String contentType) { // Use a suffix based on the content type if the content type and the URL's suffix do not match. Otherwise // attempt to use the URL's suffix. If neither of these attempts produce a non-null suffix, File.createTmpFile // uses the default suffix ".tmp". String suffix = this.makeSuffix(url.toString(), contentType); // null if the URL suffix and content type match. - if (suffix == null) + if (suffix == null) { suffix = WWIO.getSuffix(url.toString()); + } // Ensure that the suffix starts with the "." character. - if (!suffix.startsWith(".")) + if (!suffix.startsWith(".")) { suffix = "." + suffix; + } - try - { + try { File file = File.createTempFile("wwfs", suffix); // Uses the default suffix ".tmp" if this suffix is null. file.deleteOnExit(); return file; - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.CannotCreateTempFile"); Logging.logger().fine(message); return null; @@ -740,14 +714,13 @@ protected File makeTempFile(URL url, String contentType) * specified content type, then this method returns null. Otherwise the method determines and returns a suffix for * the specified content type. * - * @param path the path whose suffix is to be validated if it exists. + * @param path the path whose suffix is to be validated if it exists. * @param contentType the mime type of the data associated with the path. * * @return a suffix appropriate to the content type, or null if the specified path already has an appropriate - * suffix. + * suffix. */ - protected String makeSuffix(String path, String contentType) - { + protected String makeSuffix(String path, String contentType) { // If the cache path does not end in a suffix that matches the specified content type, we append the appropriate // suffix. If the content type is not known, we do not append any suffix. If the caller does not know the // content type used to create a cache file path, it must attempt to use known mime types until it finds a @@ -757,13 +730,15 @@ protected String makeSuffix(String path, String contentType) // The suffix returned by makeSuffixForMimeType is always ".jpg" for a JPEG mime type. We must convert any // existing using "jpeg" to "jpg" to correctly match against the suffix created from the content type. - if (existingSuffix != null && existingSuffix.equalsIgnoreCase("jpeg")) + if (existingSuffix != null && existingSuffix.equalsIgnoreCase("jpeg")) { existingSuffix = "jpg"; + } - if (suffix != null && (existingSuffix == null || !existingSuffix.equalsIgnoreCase(suffix.substring(1)))) + if (suffix != null && (existingSuffix == null || !existingSuffix.equalsIgnoreCase(suffix.substring(1)))) { return suffix; - else + } else { return null; + } } /** @@ -779,12 +754,12 @@ protected String makeSuffix(String path, String contentType) * @param queryString the query string to examine. * * @return a new string with the private query parameters removed. This string is empty if the query string is - * empty, or if the query string contains only private parameters. + * empty, or if the query string contains only private parameters. */ - protected String removePrivateQueryParameters(String queryString) - { - if (WWUtil.isEmpty(queryString)) + protected String removePrivateQueryParameters(String queryString) { + if (WWUtil.isEmpty(queryString)) { return queryString; + } // Remove the "connectid" query parameter, its corresponding value, and any trailing parameter delimiter. We // specify the regular expression directive "(?i)" to enable case-insensitive matching. The regular expression @@ -793,8 +768,9 @@ protected String removePrivateQueryParameters(String queryString) // If we removed the query string's last parameter, we need to clean up the trailing delimiter from the previous // query parameter. - if (s.endsWith("&")) + if (s.endsWith("&")) { s = s.substring(0, s.length() - 1); + } return s; } diff --git a/src/gov/nasa/worldwind/cache/BasicGpuResourceCache.java b/src/gov/nasa/worldwind/cache/BasicGpuResourceCache.java index ef9bda4b7a..40287f0864 100644 --- a/src/gov/nasa/worldwind/cache/BasicGpuResourceCache.java +++ b/src/gov/nasa/worldwind/cache/BasicGpuResourceCache.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.cache; import com.jogamp.opengl.util.texture.Texture; @@ -26,48 +25,41 @@ * @author tag * @version $Id: BasicGpuResourceCache.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicGpuResourceCache implements GpuResourceCache -{ - public static class CacheEntry implements Cacheable - { +public class BasicGpuResourceCache implements GpuResourceCache { + + public static class CacheEntry implements Cacheable { + protected final String resourceType; protected final Object resource; protected long resourceSize; - public CacheEntry(Object resource, String resourceType) - { + public CacheEntry(Object resource, String resourceType) { this.resource = resource; this.resourceType = resourceType; } - public CacheEntry(Object resource, String resourceType, long size) - { + public CacheEntry(Object resource, String resourceType, long size) { this.resource = resource; this.resourceType = resourceType; this.resourceSize = size; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return this.resourceSize; } } protected final BasicMemoryCache resources; - public BasicGpuResourceCache(long loWater, long hiWater) - { + public BasicGpuResourceCache(long loWater, long hiWater) { this.resources = new BasicMemoryCache(loWater, hiWater); this.resources.setName("GPU Resource Cache"); - this.resources.addCacheListener(new MemoryCache.CacheListener() - { - public void entryRemoved(Object key, Object clientObject) - { + this.resources.addCacheListener(new MemoryCache.CacheListener() { + public void entryRemoved(Object key, Object clientObject) { onEntryRemoved(key, clientObject); } - public void removalException(Throwable e, Object key, Object clientObject) - { + public void removalException(Throwable e, Object key, Object clientObject) { String msg = Logging.getMessage("BasicMemoryCache.ExceptionFromRemovalListener", e.getMessage()); Logging.logger().log(Level.INFO, msg); } @@ -75,108 +67,92 @@ public void removalException(Throwable e, Object key, Object clientObject) } @SuppressWarnings({"UnusedParameters"}) - protected void onEntryRemoved(Object key, Object clientObject) - { + protected void onEntryRemoved(Object key, Object clientObject) { GLContext context = GLContext.getCurrent(); - if (context == null || context.getGL() == null) + if (context == null || context.getGL() == null) { return; + } if (!(clientObject instanceof CacheEntry)) // shouldn't be null or wrong type, but check anyway + { return; + } CacheEntry entry = (CacheEntry) clientObject; GL2 gl = context.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (entry.resourceType == TEXTURE) - { + if (entry.resourceType == TEXTURE) { // Unbind a tile's texture when the tile leaves the cache. ((Texture) entry.resource).destroy(gl); - } - else if (entry.resourceType == VBO_BUFFERS) - { + } else if (entry.resourceType == VBO_BUFFERS) { int[] ids = (int[]) entry.resource; gl.glDeleteBuffers(ids.length, ids, 0); - } - else if (entry.resourceType == DISPLAY_LISTS) - { + } else if (entry.resourceType == DISPLAY_LISTS) { // Delete display list ids. They're in a two-element int array, with the id at 0 and the count at 1 int[] ids = (int[]) entry.resource; gl.glDeleteLists(ids[0], ids[1]); } } - public void put(Object key, Texture texture) - { + public void put(Object key, Texture texture) { CacheEntry te = this.createCacheEntry(texture, TEXTURE); this.resources.add(key, te); } - public void put(Object key, Object resource, String resourceType, long size) - { + public void put(Object key, Object resource, String resourceType, long size) { CacheEntry te = this.createCacheEntry(resource, resourceType, size); this.resources.add(key, te); } - protected CacheEntry createCacheEntry(Object resource, String resourceType) - { + protected CacheEntry createCacheEntry(Object resource, String resourceType) { CacheEntry entry = new CacheEntry(resource, resourceType); entry.resourceSize = this.computeEntrySize(entry); return entry; } - protected CacheEntry createCacheEntry(Object resource, String resourceType, long size) - { + protected CacheEntry createCacheEntry(Object resource, String resourceType, long size) { CacheEntry entry = new CacheEntry(resource, resourceType, size); entry.resourceSize = size; return entry; } - public Object get(Object key) - { + public Object get(Object key) { CacheEntry entry = (CacheEntry) this.resources.getObject(key); return entry != null ? entry.resource : null; } - public Texture getTexture(Object key) - { + public Texture getTexture(Object key) { CacheEntry entry = (CacheEntry) this.resources.getObject(key); return entry != null && entry.resourceType == TEXTURE ? (Texture) entry.resource : null; } - public void remove(Object key) - { + public void remove(Object key) { this.resources.remove(key); } - public int getNumObjects() - { + public int getNumObjects() { return this.resources.getNumObjects(); } - public long getCapacity() - { + public long getCapacity() { return this.resources.getCapacity(); } - public long getUsedCapacity() - { + public long getUsedCapacity() { return this.resources.getUsedCapacity(); } - public long getFreeCapacity() - { + public long getFreeCapacity() { return this.resources.getFreeCapacity(); } - public boolean contains(Object key) - { + public boolean contains(Object key) { return this.resources.contains(key); } - public void clear() - { + public void clear() { this.resources.clear(); } @@ -189,8 +165,7 @@ public void clear() * * @param newCapacity the new capacity of the cache. */ - public synchronized void setCapacity(long newCapacity) - { + public synchronized void setCapacity(long newCapacity) { this.resources.setCapacity(newCapacity); } @@ -204,8 +179,7 @@ public synchronized void setCapacity(long newCapacity) * * @param loWater the new low water level in bytes. */ - public synchronized void setLowWater(long loWater) - { + public synchronized void setLowWater(long loWater) { this.resources.setLowWater(loWater); } @@ -215,28 +189,27 @@ public synchronized void setLowWater(long loWater) * * @return the low water level in bytes. */ - public long getLowWater() - { + public long getLowWater() { return this.resources.getLowWater(); } - protected long computeEntrySize(CacheEntry entry) - { - if (entry.resourceType == TEXTURE) + protected long computeEntrySize(CacheEntry entry) { + if (entry.resourceType == TEXTURE) { return this.computeTextureSize(entry); + } return 0; } - protected long computeTextureSize(CacheEntry entry) - { + protected long computeTextureSize(CacheEntry entry) { Texture texture = (Texture) entry.resource; long size = texture.getEstimatedMemorySize(); // JOGL returns a zero estimated memory size for some textures, so calculate a size ourselves. - if (size < 1) + if (size < 1) { size = texture.getHeight() * texture.getWidth() * 4; + } return size; } diff --git a/src/gov/nasa/worldwind/cache/BasicMemoryCache.java b/src/gov/nasa/worldwind/cache/BasicMemoryCache.java index a2c3c2eefe..484e392327 100644 --- a/src/gov/nasa/worldwind/cache/BasicMemoryCache.java +++ b/src/gov/nasa/worldwind/cache/BasicMemoryCache.java @@ -13,27 +13,24 @@ * @author Eric Dalgliesh * @version $Id: BasicMemoryCache.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicMemoryCache implements MemoryCache -{ - protected static class CacheEntry implements Comparable - { +public class BasicMemoryCache implements MemoryCache { + + protected static class CacheEntry implements Comparable { + Object key; Object clientObject; protected long lastUsed; protected long clientObjectSize; - CacheEntry(Object key, Object clientObject, long clientObjectSize) - { + CacheEntry(Object key, Object clientObject, long clientObjectSize) { this.key = key; this.clientObject = clientObject; this.lastUsed = System.nanoTime(); this.clientObjectSize = clientObjectSize; } - public int compareTo(CacheEntry that) - { - if (that == null) - { + public int compareTo(CacheEntry that) { + if (that == null) { String msg = Logging.getMessage("nullValue.CacheEntryIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -42,8 +39,7 @@ public int compareTo(CacheEntry that) return this.lastUsed < that.lastUsed ? -1 : this.lastUsed == that.lastUsed ? 0 : 1; } - public String toString() - { + public String toString() { return key.toString() + " " + clientObject.toString() + " " + lastUsed + " " + clientObjectSize; } } @@ -60,11 +56,10 @@ public String toString() /** * Constructs a new cache using capacity for maximum size, and loWater for the low water. * - * @param loWater the low water level. + * @param loWater the low water level. * @param capacity the maximum capacity. */ - public BasicMemoryCache(long loWater, long capacity) - { + public BasicMemoryCache(long loWater, long capacity) { this.entries = new java.util.concurrent.ConcurrentHashMap(); this.listeners = new java.util.concurrent.CopyOnWriteArrayList(); this.capacity.set(capacity); @@ -72,51 +67,51 @@ public BasicMemoryCache(long loWater, long capacity) this.currentUsedCapacity.set((long) 0); } - /** @return the number of objects currently stored in this cache. */ - public int getNumObjects() - { + /** + * @return the number of objects currently stored in this cache. + */ + public int getNumObjects() { return this.entries.size(); } - /** @return the capacity of the cache. */ - public long getCapacity() - { + /** + * @return the capacity of the cache. + */ + public long getCapacity() { return this.capacity.get(); } - /** @return the number of cache units that the cache currently holds. */ - public long getUsedCapacity() - { + /** + * @return the number of cache units that the cache currently holds. + */ + public long getUsedCapacity() { return this.currentUsedCapacity.get(); } - /** @return the amount of free space left in the cache (in cache units). */ - public long getFreeCapacity() - { + /** + * @return the amount of free space left in the cache (in cache units). + */ + public long getFreeCapacity() { return Math.max(this.capacity.get() - this.currentUsedCapacity.get(), 0); } - public void setName(String name) - { + public void setName(String name) { this.name = name != null ? name : ""; } - public String getName() - { + public String getName() { return name; } /** - * Adds a cache listener, MemoryCache listeners are used to notify classes when an item is removed from the cache. + * Adds a cache listener, MemoryCache listeners are used to notify classes when an item is removed from the cache. * * @param listener The new CacheListener. * * @throws IllegalArgumentException is listener is null. */ - public void addCacheListener(MemoryCache.CacheListener listener) - { - if (listener == null) - { + public void addCacheListener(MemoryCache.CacheListener listener) { + if (listener == null) { String message = Logging.getMessage("BasicMemoryCache.nullListenerAdded"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -131,10 +126,8 @@ public void addCacheListener(MemoryCache.CacheListener listener) * * @throws IllegalArgumentException if listener is null. */ - public void removeCacheListener(MemoryCache.CacheListener listener) - { - if (listener == null) - { + public void removeCacheListener(MemoryCache.CacheListener listener) { + if (listener == null) { String message = Logging.getMessage("BasicMemoryCache.nullListenerRemoved"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -151,8 +144,7 @@ public void removeCacheListener(MemoryCache.CacheListener listener) * * @param newCapacity the new capacity of the cache. */ - public void setCapacity(long newCapacity) - { + public void setCapacity(long newCapacity) { // this.makeSpace(this.capacity - newCapacity); this.capacity.set(newCapacity); } @@ -167,10 +159,8 @@ public void setCapacity(long newCapacity) * * @param loWater the new low water level. */ - public void setLowWater(long loWater) - { - if (loWater < this.capacity.get() && loWater >= 0) - { + public void setLowWater(long loWater) { + if (loWater < this.capacity.get() && loWater >= 0) { this.lowWater = loWater; } } @@ -181,8 +171,7 @@ public void setLowWater(long loWater) * * @return the low water level. */ - public long getLowWater() - { + public long getLowWater() { return this.lowWater; } @@ -199,17 +188,14 @@ public long getLowWater() * * @throws IllegalArgumentException if key is null. */ - public boolean contains(Object key) - { - if (key == null) - { + public boolean contains(Object key) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - synchronized (this.lock) - { + synchronized (this.lock) { return this.entries.containsKey(key); } } @@ -218,22 +204,19 @@ public boolean contains(Object key) * Adds an object to the cache. The add fails if the object or key is null, or if the size is zero, negative or * greater than the maximmum capacity. * - * @param key The unique reference key that identifies this object. - * @param clientObject The actual object to be cached. + * @param key The unique reference key that identifies this object. + * @param clientObject The actual object to be cached. * @param clientObjectSize The size of the object in cache units. * * @return returns true if clientObject was added, false otherwise. */ - public boolean add(Object key, Object clientObject, long clientObjectSize) - { + public boolean add(Object key, Object clientObject, long clientObjectSize) { long cap = this.capacity.get(); - if (key == null || clientObject == null || clientObjectSize <= 0 || clientObjectSize > cap) - { + if (key == null || clientObject == null || clientObjectSize <= 0 || clientObjectSize > cap) { String message = Logging.getMessage("BasicMemoryCache.CacheItemNotAdded"); - if (clientObjectSize > cap) - { + if (clientObjectSize > cap) { message += " - " + Logging.getMessage("BasicMemoryCache.ItemTooLargeForCache"); } @@ -247,16 +230,14 @@ public boolean add(Object key, Object clientObject, long clientObjectSize) BasicMemoryCache.CacheEntry entry = new BasicMemoryCache.CacheEntry(key, clientObject, clientObjectSize); - synchronized (this.lock) - { + synchronized (this.lock) { CacheEntry existing = this.entries.get(key); if (existing != null) // replacing { this.removeEntry(existing); } - if (this.currentUsedCapacity.get() + clientObjectSize > cap) - { + if (this.currentUsedCapacity.get() + clientObjectSize > cap) { this.makeSpace(clientObjectSize); } @@ -267,8 +248,7 @@ public boolean add(Object key, Object clientObject, long clientObjectSize) return true; } - public boolean add(Object key, Cacheable clientObject) - { + public boolean add(Object key, Cacheable clientObject) { return this.add(key, clientObject, clientObject.getSizeInBytes()); } @@ -280,20 +260,18 @@ public boolean add(Object key, Cacheable clientObject) * * @throws IllegalArgumentException if key is null. */ - public void remove(Object key) - { - if (key == null) - { + public void remove(Object key) { + if (key == null) { Logging.logger().finer("nullValue.KeyIsNull"); return; } - synchronized (this.lock) - { + synchronized (this.lock) { CacheEntry entry = this.entries.get(key); - if (entry != null) + if (entry != null) { this.removeEntry(entry); + } } } @@ -307,22 +285,20 @@ public void remove(Object key) * * @throws IllegalArgumentException if key is null. */ - public Object getObject(Object key) - { - if (key == null) - { + public Object getObject(Object key) { + if (key == null) { Logging.logger().finer("nullValue.KeyIsNull"); return null; } CacheEntry entry; // don't need to lock because call is atomic - synchronized (this.lock) - { + synchronized (this.lock) { entry = this.entries.get(key); - if (entry == null) + if (entry == null) { return null; + } entry.lastUsed = System.nanoTime(); // nanoTime overflows once every 292 years // which will result in a slowing of the cache @@ -332,13 +308,12 @@ public Object getObject(Object key) return entry.clientObject; } - /** Empties the cache. */ - public void clear() - { - synchronized (this.lock) - { - for (CacheEntry entry : this.entries.values()) - { + /** + * Empties the cache. + */ + public void clear() { + synchronized (this.lock) { + for (CacheEntry entry : this.entries.values()) { this.removeEntry(entry); } } @@ -358,14 +333,10 @@ protected void removeEntry(CacheEntry entry) // MUST BE CALLED WITHIN SYNCHRONIZ { this.currentUsedCapacity.addAndGet(-entry.clientObjectSize); - for (MemoryCache.CacheListener listener : this.listeners) - { - try - { + for (MemoryCache.CacheListener listener : this.listeners) { + try { listener.entryRemoved(entry.key, entry.clientObject); - } - catch (Exception e) - { + } catch (Exception e) { listener.removalException(e, entry.key, entry.clientObject); } } @@ -380,17 +351,16 @@ protected void removeEntry(CacheEntry entry) // MUST BE CALLED WITHIN SYNCHRONIZ */ private void makeSpace(long spaceRequired) // MUST BE CALLED WITHIN SYNCHRONIZED { - if (spaceRequired > this.capacity.get() || spaceRequired < 0) + if (spaceRequired > this.capacity.get() || spaceRequired < 0) { return; + } CacheEntry[] timeOrderedEntries = new CacheEntry[this.entries.size()]; java.util.Arrays.sort(this.entries.values().toArray(timeOrderedEntries)); // TODO int i = 0; - while (this.getFreeCapacity() < spaceRequired || this.getUsedCapacity() > this.lowWater) - { - if (i < timeOrderedEntries.length) - { + while (this.getFreeCapacity() < spaceRequired || this.getUsedCapacity() > this.lowWater) { + if (i < timeOrderedEntries.length) { this.removeEntry(timeOrderedEntries[i++]); } } @@ -403,24 +373,19 @@ private void makeSpace(long spaceRequired) // MUST BE CALLED WITHIN SYNCHRONIZED * @return a String representation of this object. */ @Override - public String toString() - { + public String toString() { return "MemoryCache " + this.name + " max size = " + this.getCapacity() + " current size = " - + this.currentUsedCapacity.get() + " number of items: " + this.getNumObjects(); + + this.currentUsedCapacity.get() + " number of items: " + this.getNumObjects(); } @Override - protected void finalize() throws Throwable - { - try - { + protected void finalize() throws Throwable { + try { // clear doesn't throw any checked exceptions // but this is in case of an unchecked exception // basically, we don't want to exit without calling super.finalize this.clear(); - } - finally - { + } finally { super.finalize(); } } diff --git a/src/gov/nasa/worldwind/cache/BasicMemoryCacheSet.java b/src/gov/nasa/worldwind/cache/BasicMemoryCacheSet.java index f0cdd0f026..766da22a13 100644 --- a/src/gov/nasa/worldwind/cache/BasicMemoryCacheSet.java +++ b/src/gov/nasa/worldwind/cache/BasicMemoryCacheSet.java @@ -14,22 +14,19 @@ * @author tag * @version $Id: BasicMemoryCacheSet.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicMemoryCacheSet implements MemoryCacheSet -{ +public class BasicMemoryCacheSet implements MemoryCacheSet { + private ConcurrentHashMap caches = new ConcurrentHashMap(); - public synchronized boolean containsCache(String key) - { + public synchronized boolean containsCache(String key) { return this.caches.containsKey(key); } - public synchronized MemoryCache getCache(String cacheKey) - { + public synchronized MemoryCache getCache(String cacheKey) { MemoryCache cache = this.caches.get(cacheKey); - if (cache == null) - { - String message = Logging.getMessage("MemoryCacheSet.CacheDoesNotExist", cacheKey); + if (cache == null) { + String message = Logging.getMessage("MemoryCacheSet.CacheDoesNotExist", cacheKey); Logging.logger().severe(message); throw new IllegalStateException(message); } @@ -37,22 +34,18 @@ public synchronized MemoryCache getCache(String cacheKey) return cache; } - public Map getAllCaches() - { + public Map getAllCaches() { return this.caches; } - public synchronized MemoryCache addCache(String key, MemoryCache cache) - { - if (this.containsCache(key)) - { + public synchronized MemoryCache addCache(String key, MemoryCache cache) { + if (this.containsCache(key)) { String message = Logging.getMessage("MemoryCacheSet.CacheAlreadyExists"); Logging.logger().fine(message); throw new IllegalStateException(message); } - if (cache == null) - { + if (cache == null) { String message = Logging.getMessage("nullValue.CacheIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -63,22 +56,18 @@ public synchronized MemoryCache addCache(String key, MemoryCache cache) return cache; } - public synchronized void clear() - { - for (MemoryCache cache : this.caches.values()) - { + public synchronized void clear() { + for (MemoryCache cache : this.caches.values()) { cache.clear(); } } - public Collection getPerformanceStatistics() - { + public Collection getPerformanceStatistics() { ArrayList stats = new ArrayList(); - for (MemoryCache cache : this.caches.values()) - { + for (MemoryCache cache : this.caches.values()) { stats.add(new PerformanceStatistic(PerformanceStatistic.MEMORY_CACHE, "Cache Size (Kb): " + cache.getName(), - cache.getUsedCapacity() / 1000)); + cache.getUsedCapacity() / 1000)); } return stats; diff --git a/src/gov/nasa/worldwind/cache/BasicRasterServerCache.java b/src/gov/nasa/worldwind/cache/BasicRasterServerCache.java index 4dc8655a75..9557d38986 100644 --- a/src/gov/nasa/worldwind/cache/BasicRasterServerCache.java +++ b/src/gov/nasa/worldwind/cache/BasicRasterServerCache.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.cache; import gov.nasa.worldwind.util.Logging; @@ -16,7 +15,6 @@ * @author Lado Garakanidze * @version $Id: BasicRasterServerCache.java 1171 2013-02-11 21:45:02Z dcollins $ */ - /** * The BasicRasterServerCache is an implementation of the memory cache that is specific to store maximum * possible cacheable items, until the heap size allows. Once the memory limit is hit, it will drop ALL cached items. @@ -29,8 +27,8 @@ * cached content will be released. This approach allows to use almost entire available heap memory to cache rasters and * release memory when more memory is needed to the application itself. */ -public class BasicRasterServerCache extends BasicMemoryCache -{ +public class BasicRasterServerCache extends BasicMemoryCache { + protected static final int DEFAULT_INACCESSIBLE_MEMORY_SIZE = 100 * 1024 * 1024; protected static final long DEFAULT_PRUNER_THREAD_TIMEOUT_MSEC = 5000L; // 20 secs = 20,000 milli-seconds protected static final long DEFAULT_LEAST_RECENTLY_USED_TIMEOUT_NSEC = 20000000000L; @@ -48,28 +46,24 @@ public class BasicRasterServerCache extends BasicMemoryCache * Constructs a new cache which uses entire memory, but will immediately drop all cached entries ones there is a * need for more memory by anyone else. */ - public BasicRasterServerCache() - { + public BasicRasterServerCache() { super(0L, - Runtime.getRuntime().freeMemory() + Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory()); + Runtime.getRuntime().freeMemory() + Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory()); new Thread(new MemoryMonitorThread()).start(); new Thread(new CachePrunerThread()).start(); } - public BasicRasterServerCache(int inaccessibleMemorySize) - { + public BasicRasterServerCache(int inaccessibleMemorySize) { this(); this.inaccessibleMemorySize.set(inaccessibleMemorySize); } @Override - public boolean add(Object key, Object clientObject, long clientObjectSize) - { + public boolean add(Object key, Object clientObject, long clientObjectSize) { BasicMemoryCache.CacheEntry entry = new BasicMemoryCache.CacheEntry(key, clientObject, clientObjectSize); - synchronized (this.lock) - { + synchronized (this.lock) { this.removeExpiredEntries(); CacheEntry existing = this.entries.get(key); @@ -86,68 +80,53 @@ public boolean add(Object key, Object clientObject, long clientObjectSize) return true; } - protected void updateMemorySemaphore() - { - try - { - if (this.lowMemorySemaphore == null || null == this.lowMemorySemaphore.get()) + protected void updateMemorySemaphore() { + try { + if (this.lowMemorySemaphore == null || null == this.lowMemorySemaphore.get()) { this.lowMemorySemaphore = new SoftReference(new byte[this.inaccessibleMemorySize.get()], - this.queue); - } - catch (Throwable t) - { + this.queue); + } + } catch (Throwable t) { Logging.logger().finest(t.getMessage()); } } - public long getLeastRecentUseTimeout() - { + public long getLeastRecentUseTimeout() { return this.timeoutLeastRecentUseInNanoSeconds; } - public void setLeastRecentUseTimeout(long nanoSeconds) - { + public void setLeastRecentUseTimeout(long nanoSeconds) { this.timeoutLeastRecentUseInNanoSeconds = nanoSeconds; } - protected void removeExpiredEntries() - { - if (this.entries.size() == 0) + protected void removeExpiredEntries() { + if (this.entries.size() == 0) { return; + } - if (this.removalLock.tryLock()) - { - try - { + if (this.removalLock.tryLock()) { + try { CacheEntry[] timeOrderedEntries = new CacheEntry[this.entries.size()]; java.util.Arrays.sort(this.entries.values().toArray(timeOrderedEntries)); - for (CacheEntry entry : timeOrderedEntries) - { - if (null != entry && (System.nanoTime() - entry.lastUsed) > this.getLeastRecentUseTimeout()) - { + for (CacheEntry entry : timeOrderedEntries) { + if (null != entry && (System.nanoTime() - entry.lastUsed) > this.getLeastRecentUseTimeout()) { this.removeEntry(entry); } } - } - finally - { + } finally { this.removalLock.unlock(); } } } - private class MemoryMonitorThread implements Runnable - { - public void run() - { - try - { - for (; ;) - { + private class MemoryMonitorThread implements Runnable { + + public void run() { + try { + for (;;) { Reference ref = queue.remove(); - if (null != ref) - { + if (null != ref) { ref.clear(); // clear the soft reference clear(); // drop entire cache @@ -156,37 +135,28 @@ public void run() // System.gc(); } } - } - catch (InterruptedException ignore) - { - } - finally - { - if (Thread.currentThread().isInterrupted()) + } catch (InterruptedException ignore) { + } finally { + if (Thread.currentThread().isInterrupted()) { Thread.interrupted(); + } } } } - private class CachePrunerThread implements Runnable - { - public void run() - { - try - { - for (; ;) - { + private class CachePrunerThread implements Runnable { + + public void run() { + try { + for (;;) { Thread.sleep(DEFAULT_PRUNER_THREAD_TIMEOUT_MSEC); removeExpiredEntries(); } - } - catch (InterruptedException ignore) - { - } - finally - { - if (Thread.currentThread().isInterrupted()) + } catch (InterruptedException ignore) { + } finally { + if (Thread.currentThread().isInterrupted()) { Thread.interrupted(); + } } } } diff --git a/src/gov/nasa/worldwind/cache/BasicSessionCache.java b/src/gov/nasa/worldwind/cache/BasicSessionCache.java index 8953d02786..31e173b51e 100644 --- a/src/gov/nasa/worldwind/cache/BasicSessionCache.java +++ b/src/gov/nasa/worldwind/cache/BasicSessionCache.java @@ -22,8 +22,8 @@ * @author dcollins * @version $Id: BasicSessionCache.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicSessionCache implements SessionCache -{ +public class BasicSessionCache implements SessionCache { + protected static final int DEFAULT_CAPACITY = 8; protected BoundedHashMap entries; @@ -35,10 +35,8 @@ public class BasicSessionCache implements SessionCache * * @throws IllegalArgumentException if capacity is negative. */ - public BasicSessionCache(int capacity) - { - if (capacity < 0) - { + public BasicSessionCache(int capacity) { + if (capacity < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "capacity < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -47,9 +45,10 @@ public BasicSessionCache(int capacity) this.entries = new BoundedHashMap(capacity); } - /** Creates a BasicSessionCache with the default capacity. */ - public BasicSessionCache() - { + /** + * Creates a BasicSessionCache with the default capacity. + */ + public BasicSessionCache() { this(DEFAULT_CAPACITY); } @@ -58,8 +57,7 @@ public BasicSessionCache() * * @return maximum number of entries in the cache. */ - public synchronized int getCapacity() - { + public synchronized int getCapacity() { return this.entries.getCapacity(); } @@ -71,10 +69,8 @@ public synchronized int getCapacity() * * @throws IllegalArgumentException if capacity is negative. */ - public synchronized void setCapacity(int capacity) - { - if (capacity < 0) - { + public synchronized void setCapacity(int capacity) { + if (capacity < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "capacity < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -88,8 +84,7 @@ public synchronized void setCapacity(int capacity) * * @return number of cached entries. */ - public synchronized int getEntryCount() - { + public synchronized int getEntryCount() { return this.entries.size(); } @@ -99,8 +94,7 @@ public synchronized int getEntryCount() * * @return a {@link java.util.Set} view of the keys contained in the cache. */ - public synchronized java.util.Set getKeySet() - { + public synchronized java.util.Set getKeySet() { return java.util.Collections.unmodifiableSet(this.entries.keySet()); } @@ -113,10 +107,8 @@ public synchronized java.util.Set getKeySet() * * @throws IllegalArgumentException if the key is null. */ - public synchronized boolean contains(Object key) - { - if (key == null) - { + public synchronized boolean contains(Object key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -135,10 +127,8 @@ public synchronized boolean contains(Object key) * * @throws IllegalArgumentException if the key is null. */ - public synchronized Object get(Object key) - { - if (key == null) - { + public synchronized Object get(Object key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -151,15 +141,13 @@ public synchronized Object get(Object key) * Adds an entry in the cache with a specified key and value. If the cache size after adding the new entry is * greater than its capacity, this evicts the eldest entry in the cache. * - * @param key the entry's key. A null value is not permitted. + * @param key the entry's key. A null value is not permitted. * @param value the entry's value. A null value is permitted. * * @throws IllegalArgumentException if the key is null. */ - public synchronized void put(Object key, Object value) - { - if (key == null) - { + public synchronized void put(Object key, Object value) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -176,10 +164,8 @@ public synchronized void put(Object key, Object value) * * @return a reference to the removed entry's value, or null of no entry matches the specified key. */ - public synchronized Object remove(Object key) - { - if (key == null) - { + public synchronized Object remove(Object key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -188,9 +174,10 @@ public synchronized Object remove(Object key) return this.entries.remove(key); } - /** Removes all entries from the cache. */ - public synchronized void clear() - { + /** + * Removes all entries from the cache. + */ + public synchronized void clear() { this.entries.clear(); } } diff --git a/src/gov/nasa/worldwind/cache/Cacheable.java b/src/gov/nasa/worldwind/cache/Cacheable.java index c3db412c65..e2dc083b81 100644 --- a/src/gov/nasa/worldwind/cache/Cacheable.java +++ b/src/gov/nasa/worldwind/cache/Cacheable.java @@ -3,14 +3,13 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.cache; + /** * @author Tom Gaskins * @version $Id: Cacheable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Cacheable -{ +public interface Cacheable { // TODO: search for size queries that do not used this interface and change them to do so. // currently (22 Nov 2006), only BasicElevationModel.addTileToCache(Tile, ShortBuffer) does not use Cacheable diff --git a/src/gov/nasa/worldwind/cache/FileStore.java b/src/gov/nasa/worldwind/cache/FileStore.java index 3db8b02787..77352da2cb 100644 --- a/src/gov/nasa/worldwind/cache/FileStore.java +++ b/src/gov/nasa/worldwind/cache/FileStore.java @@ -13,8 +13,8 @@ * @author Tom Gaskins * @version $Id: FileStore.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface FileStore extends WWObject -{ +public interface FileStore extends WWObject { + /** * Returns the locations that the file store will look for files. * @@ -32,10 +32,10 @@ public interface FileStore extends WWObject /** * Adds a location to search when files are requested from the file store. * - * @param newPath the location to add. If the location already exists in the list of read locations its entry is - * removed and a new entry is added to the end of the search list. + * @param newPath the location to add. If the location already exists in the list of read locations its entry is + * removed and a new entry is added to the end of the search list. * @param isInstall indicates whether the location is an "installed data" location and therefore not subject to - * automatic removal of its contents. + * automatic removal of its contents. * * @throws IllegalArgumentException if the specified path is null or empty. */ @@ -45,10 +45,10 @@ public interface FileStore extends WWObject * Adds a location to search when files are requested from the file store and specifies its location in the search * order. * - * @param index the location in the search list at which to add the new location. - * @param newPath the location to add. + * @param index the location in the search list at which to add the new location. + * @param newPath the location to add. * @param isInstall indicates whether the location is an installed-data location and therefore not subject to - * automatic removal of its contents. + * automatic removal of its contents. * * @throws IllegalArgumentException if the specified path is null or empty or the specified index is less than 0. */ @@ -81,16 +81,16 @@ public interface FileStore extends WWObject * @param fileName the file in question. * * @return true if the file store contains the file, false if the file store does not contain the file or the - * specified path is null. + * specified path is null. */ boolean containsFile(String fileName); /** * Searches the file store for a specified file and returns a reference to it if it is. * - * @param fileName the file to search for, identified by a path relative to the root of the file store. + * @param fileName the file to search for, identified by a path relative to the root of the file store. * @param checkClassPath if true, the current classpath is first searched for the file, otherwise the classpath is - * not searched. + * not searched. * * @return a URL addressing the file if it is found. * @@ -136,7 +136,7 @@ public interface FileStore extends WWObject * store. Returned names are relative pointers to a file in the store; they are not necessarily a file system path. * * @param pathName relative path in the file store to search, or null to search the entire file store. - * @param filter a file filter. + * @param filter a file filter. * * @return an array of file store names. Returns null if the path does not exist in the file store. * @@ -152,7 +152,7 @@ public interface FileStore extends WWObject * store; they are not necessarily a file system path. * * @param pathName relative path in the file store to search, or null to search the entire file store. - * @param filter a file filter. + * @param filter a file filter. * * @return an array of file store names. Returns null if the path does not exist in the file store. * @@ -169,7 +169,7 @@ public interface FileStore extends WWObject * store; they are not necessarily a file system path. * * @param pathName relative path in the file store to search, or null to search the entire file store. - * @param filter a file filter. + * @param filter a file filter. * * @return an array of file store names. Returns null if the path does not exist in the file store. * @@ -192,7 +192,7 @@ public interface FileStore extends WWObject * @param address the file's address. If null, zero is returned. * * @return The expiration time of the file, in milliseconds since the Epoch (January 1, 1970, 00:00:00 GMT). Zero - * indicates that there is no expiration time. + * indicates that there is no expiration time. */ long getExpirationTime(String address); @@ -205,7 +205,7 @@ public interface FileStore extends WWObject * @param address the file address: either a local file, a URL, or a path relative to the root of the file store. * * @return the file's URL if it exists locally or is a remote file that has been retrieved, otherwise - * null. + * null. * * @throws IllegalArgumentException if the address is null. */ @@ -215,8 +215,8 @@ public interface FileStore extends WWObject * Requests a file and specifies whether to store retrieved files in the cache or in a temporary location. If the * file exists locally, including as a resource on the classpath, this returns a {@link URL} to the * file. Otherwise if the specified address is a URL to a remote location, this initiates a request for the file and - * returns null. When the request succeeds the file is stored either in the local WorldWind cache or - * in a temporary location and subsequent invocations of this method return a URL to the retrieved file. + * returns null. When the request succeeds the file is stored either in the local WorldWind cache or in + * a temporary location and subsequent invocations of this method return a URL to the retrieved file. *

    * The cacheRemoteFile parameter specifies whether to store a retrieved remote file in the WorldWind * cache or in a temporary location. This parameter has no effect if the file exists locally. The temporary location @@ -226,13 +226,12 @@ public interface FileStore extends WWObject * If a remote file is requested multiple times with different values for cacheRemoteFile, it is * undefined whether the retrieved file is stored in the WorldWind cache or in a temporary location. * - * @param address the file address: either a local file, a URL, or a path relative to the root of the file - * store. + * @param address the file address: either a local file, a URL, or a path relative to the root of the file store. * @param cacheRemoteFile true to store remote files in the WorldWind cache, or false to - * store remote files in a temporary location. Has no effect if the address is a local file. + * store remote files in a temporary location. Has no effect if the address is a local file. * * @return the file's URL if it exists locally or is a remote file that has been retrieved, otherwise - * null. + * null. * * @throws IllegalArgumentException if the address is null. */ diff --git a/src/gov/nasa/worldwind/cache/FileStoreFilter.java b/src/gov/nasa/worldwind/cache/FileStoreFilter.java index da566d651a..690d5bea1e 100644 --- a/src/gov/nasa/worldwind/cache/FileStoreFilter.java +++ b/src/gov/nasa/worldwind/cache/FileStoreFilter.java @@ -11,13 +11,13 @@ * @author dcollins * @version $Id: FileStoreFilter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface FileStoreFilter -{ +public interface FileStoreFilter { + /** * Returns whether or not this filter accepts the file name under a specified FileStore. * * @param fileStore the FileStore containing the named file path. - * @param fileName the named file path in question. + * @param fileName the named file path in question. * * @return true if the file name should be accepted; false otherwise. */ diff --git a/src/gov/nasa/worldwind/cache/GpuResourceCache.java b/src/gov/nasa/worldwind/cache/GpuResourceCache.java index c33dac15e3..757e786b5a 100644 --- a/src/gov/nasa/worldwind/cache/GpuResourceCache.java +++ b/src/gov/nasa/worldwind/cache/GpuResourceCache.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.cache; import com.jogamp.opengl.util.texture.Texture; @@ -16,9 +15,11 @@ * @author tag * @version $Id: GpuResourceCache.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface GpuResourceCache -{ - /** Identifies resources as textures. Corresponding object must be of type {@link Texture}. */ +public interface GpuResourceCache { + + /** + * Identifies resources as textures. Corresponding object must be of type {@link Texture}. + */ public static final String TEXTURE = "gov.nasa.worldwind.cache.GpuResourceCache.Texture"; /** @@ -35,10 +36,10 @@ public interface GpuResourceCache /** * Adds a new resource to this cache. * - * @param key the key identifying the resource. - * @param resource the resource cached. + * @param key the key identifying the resource. + * @param resource the resource cached. * @param resourceType the type of resource, one of the resource-type constants described above. - * @param size the size of the resource, expressed as the number of bytes it requires on the GPU. + * @param size the size of the resource, expressed as the number of bytes it requires on the GPU. * * @see #put(Object, com.jogamp.opengl.util.texture.Texture) */ @@ -47,7 +48,7 @@ public interface GpuResourceCache /** * Add a resource to this cache. * - * @param key the key identifying the resource. + * @param key the key identifying the resource. * @param texture the resource to add to this cache. * * @throws IllegalArgumentException if either argument is null. @@ -79,7 +80,7 @@ public interface GpuResourceCache * * @param key the texture resource's key. * - * @return the texture resource associated with the key, or null if the key is not found in the cache. + * @return the texture resource associated with the key, or null if the key is not found in the cache. * * @throws IllegalArgumentException if the key is null. */ @@ -94,7 +95,9 @@ public interface GpuResourceCache */ void remove(Object key); - /** Removes all entries from this cache. */ + /** + * Removes all entries from this cache. + */ void clear(); /** @@ -115,7 +118,7 @@ public interface GpuResourceCache * Indicates the amount of memory used by cached objects in this cache. * * @return the number of bytes of memory used by objects in this cache, as determined by the size associated with - * each resource. + * each resource. * * @see #getCapacity() */ @@ -136,7 +139,7 @@ public interface GpuResourceCache * its low water level is reached. * * @param newCapacity the number of bytes allowed for the cache's resources. Values less than or equal to 0 are - * ignored and cause no change to this cache's capacity. + * ignored and cause no change to this cache's capacity. * * @see #setLowWater(long) */ @@ -147,7 +150,7 @@ public interface GpuResourceCache * existing resources are removed until the amount of memory used is at or below the low water size. * * @param loWater the size to reduce this cache to when added resources would exceed the cache's capacity. Values - * less than or equal to 0 are ignored and cause no change to this cache's low water size. + * less than or equal to 0 are ignored and cause no change to this cache's low water size. * * @see #setCapacity(long) * @see #remove(Object) @@ -162,4 +165,4 @@ public interface GpuResourceCache * @see #setLowWater(long) */ long getLowWater(); -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/cache/MemoryCache.java b/src/gov/nasa/worldwind/cache/MemoryCache.java index aa52b9bf28..cced2fc2bf 100644 --- a/src/gov/nasa/worldwind/cache/MemoryCache.java +++ b/src/gov/nasa/worldwind/cache/MemoryCache.java @@ -9,8 +9,8 @@ * @author Eric Dalgliesh * @version $Id: MemoryCache.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MemoryCache -{ +public interface MemoryCache { + void setName(String name); String getName(); @@ -20,13 +20,13 @@ public interface MemoryCache * removal of an entry from the cache. A client may need to know a removal instigated by the cache occurred in order * to adjust its own state or to free resources associated with the removed entry. */ - public interface CacheListener - { + public interface CacheListener { + /** * Called just after an entry has been removed from the cache. Listeners should deallocate any resources that * won't be deallocated by normal garbage collection. * - * @param key the entry's cache key. + * @param key the entry's cache key. * @param clientObject the cached object. */ public void entryRemoved(Object key, Object clientObject); @@ -34,8 +34,8 @@ public interface CacheListener /** * Called when an exception occurs within the {@link #entryRemoved(Object, Object)} call. * - * @param exception the exception that occurred. - * @param key the entry's cache key. + * @param exception the exception that occurred. + * @param key the entry's cache key. * @param clientObject the cached object. */ public void removalException(Throwable exception, Object key, Object clientObject); @@ -57,8 +57,8 @@ public interface CacheListener void removeCacheListener(CacheListener listener); /** - * Discovers whether or not this cache contains the object referenced by key . Currently no interface exists - * to discover if an object resides in the cache by referencing itself. + * Discovers whether or not this cache contains the object referenced by key . Currently no interface + * exists to discover if an object resides in the cache by referencing itself. * * @param key the key which the object is referenced by. * @@ -76,9 +76,9 @@ public interface CacheListener *

    * This method should be declared synchronized when it is implemented. * - * @param key an object used to reference the cached item. + * @param key an object used to reference the cached item. * @param clientObject the item to be cached. - * @param objectSize the size of the item in cache units. + * @param objectSize the size of the item in cache units. * * @return true if object was added, false otherwise. */ @@ -90,7 +90,7 @@ public interface CacheListener *

    * This method should be declared synchronized when it is implemented. * - * @param key an object used to reference the cached item. + * @param key an object used to reference the cached item. * @param clientObject the item to be cached. * * @return true if object was added, false otherwise. @@ -128,7 +128,6 @@ public interface CacheListener /* *************************************************************************/ // capacity related accessors - /** * Retrieve the number of items stored in the MemoryCache. * @@ -169,7 +168,6 @@ public interface CacheListener /* *******************************************************************************/ //capacity related mutators - /** * Sets the new low water capacity value for this MemoryCache. When a MemoryCache runs out * of free space, it must remove some items if it wishes to add any more. It continues removing items until the low diff --git a/src/gov/nasa/worldwind/cache/MemoryCacheSet.java b/src/gov/nasa/worldwind/cache/MemoryCacheSet.java index e9b69bac8d..81367caf82 100644 --- a/src/gov/nasa/worldwind/cache/MemoryCacheSet.java +++ b/src/gov/nasa/worldwind/cache/MemoryCacheSet.java @@ -13,8 +13,8 @@ * @author tag * @version $Id: MemoryCacheSet.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MemoryCacheSet -{ +public interface MemoryCacheSet { + boolean containsCache(String key); MemoryCache getCache(String cacheKey); diff --git a/src/gov/nasa/worldwind/cache/SessionCache.java b/src/gov/nasa/worldwind/cache/SessionCache.java index 17b81ed4d0..c5a57e2d85 100644 --- a/src/gov/nasa/worldwind/cache/SessionCache.java +++ b/src/gov/nasa/worldwind/cache/SessionCache.java @@ -16,8 +16,8 @@ * @author dcollins * @version $Id: SessionCache.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface SessionCache -{ +public interface SessionCache { + /** * Returns the maximum number of entries in the cache. * @@ -68,7 +68,7 @@ public interface SessionCache /** * Adds an entry in the cache with a specified key and value. * - * @param key the entry's key. + * @param key the entry's key. * @param value the entry's value. */ void put(Object key, Object value); diff --git a/src/gov/nasa/worldwind/cache/ShapeDataCache.java b/src/gov/nasa/worldwind/cache/ShapeDataCache.java index 7ff3a0e660..893f02da1b 100644 --- a/src/gov/nasa/worldwind/cache/ShapeDataCache.java +++ b/src/gov/nasa/worldwind/cache/ShapeDataCache.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.cache; import gov.nasa.worldwind.avlist.AVListImpl; @@ -25,36 +24,49 @@ * @author tag * @version $Id: ShapeDataCache.java 2152 2014-07-16 00:00:33Z tgaskins $ */ -public class ShapeDataCache implements Iterable -{ - public static class ShapeDataCacheEntry extends AVListImpl - { - /** Determines whether the cache entry has expired. */ +public class ShapeDataCache implements Iterable { + + public static class ShapeDataCacheEntry extends AVListImpl { + + /** + * Determines whether the cache entry has expired. + */ protected TimedExpirySupport timer; - /** Indicates the last time, in milliseconds, the entry was requested or added. */ + /** + * Indicates the last time, in milliseconds, the entry was requested or added. + */ protected long lastUsed = System.currentTimeMillis(); - /** Identifies the associated globe's state at the time the entry was created. */ + /** + * Identifies the associated globe's state at the time the entry was created. + */ protected GlobeStateKey globeStateKey; - /** Indicates the vertical exaggeration in effect when the entry was cached. */ + /** + * Indicates the vertical exaggeration in effect when the entry was cached. + */ protected double verticalExaggeration; - /** Indicates the associated shape's extent, in model coordinates relative to the associated globe. */ + /** + * Indicates the associated shape's extent, in model coordinates relative to the associated globe. + */ protected Extent extent; - /** Indicates the eye distance of the shape in the globe-relative coordinate system. */ + /** + * Indicates the eye distance of the shape in the globe-relative coordinate system. + */ protected double eyeDistance; - /** Indicates the eye distance current when the cache entry's remaining time was last adjusted. */ + /** + * Indicates the eye distance current when the cache entry's remaining time was last adjusted. + */ protected double timerAdjustedEyeDistance; /** * Constructs an entry using the globe and vertical exaggeration of a specified draw context. * - * @param dc the draw context. Must contain a globe. + * @param dc the draw context. Must contain a globe. * @param minExpiryTime the minimum expiration duration, in milliseconds. * @param maxExpiryTime the maximum expiration duration, in milliseconds. * * @throws IllegalArgumentException if the draw context is null. */ - public ShapeDataCacheEntry(DrawContext dc, long minExpiryTime, long maxExpiryTime) - { + public ShapeDataCacheEntry(DrawContext dc, long minExpiryTime, long maxExpiryTime) { this.timer = new TimedExpirySupport(Math.max(minExpiryTime, 0), Math.max(maxExpiryTime, 0)); this.globeStateKey = dc != null ? dc.getGlobe().getGlobeStateKey() : null; this.verticalExaggeration = dc != null ? dc.getVerticalExaggeration() : 1d; @@ -68,10 +80,9 @@ public ShapeDataCacheEntry(DrawContext dc, long minExpiryTime, long maxExpiryTim * * @return true if the shape is valid, otherwise false. */ - public boolean isValid(DrawContext dc) - { + public boolean isValid(DrawContext dc) { return this.verticalExaggeration == dc.getVerticalExaggeration() - && (this.globeStateKey != null && globeStateKey.equals(dc.getGlobe().getGlobeStateKey(dc))); + && (this.globeStateKey != null && globeStateKey.equals(dc.getGlobe().getGlobeStateKey(dc))); } /** @@ -81,8 +92,7 @@ public boolean isValid(DrawContext dc) * * @return true if the entry has expired, otherwise false. */ - public boolean isExpired(DrawContext dc) - { + public boolean isExpired(DrawContext dc) { return dc != null ? timer.isExpired(dc) : timer.isExpired(System.currentTimeMillis()); } @@ -91,8 +101,7 @@ public boolean isExpired(DrawContext dc) * * @param isExpired true to expire the entry, otherwise false. */ - public void setExpired(boolean isExpired) - { + public void setExpired(boolean isExpired) { this.timer.setExpired(isExpired); } @@ -103,8 +112,7 @@ public void setExpired(boolean isExpired) * * @throws IllegalArgumentException if the draw context is null. */ - public void restartTimer(DrawContext dc) - { + public void restartTimer(DrawContext dc) { this.timer.restart(dc); } @@ -115,21 +123,23 @@ public void restartTimer(DrawContext dc) * 50%. This has no effect if the cached eye distance is unknown, or if the expiration time has already been * reached. * - * @param dc the current draw context. + * @param dc the current draw context. * @param newEyeDistance the current eye distance. */ - public void adjustTimer(DrawContext dc, double newEyeDistance) - { + public void adjustTimer(DrawContext dc, double newEyeDistance) { if (this.timerAdjustedEyeDistance == 0) // do nothing, there's previous eye distance to compare with + { return; + } if (this.timer.isExpired(dc)) // do nothing, the timer has already expired + { return; + } double oldPixelSize = dc.getView().computePixelSizeAtDistance(this.timerAdjustedEyeDistance); double newPixelSize = dc.getView().computePixelSizeAtDistance(newEyeDistance); - if (newPixelSize < oldPixelSize / 2) - { + if (newPixelSize < oldPixelSize / 2) { long remainingTime = this.timer.getExpiryTime() - dc.getFrameTimeStamp(); this.timer.setExpiryTime(dc.getFrameTimeStamp() + remainingTime / 2); this.timerAdjustedEyeDistance = newEyeDistance; @@ -141,8 +151,7 @@ public void adjustTimer(DrawContext dc, double newEyeDistance) * * @return this entry's eye distance, in meters. */ - public double getEyeDistance() - { + public double getEyeDistance() { return eyeDistance; } @@ -151,8 +160,7 @@ public double getEyeDistance() * * @param eyeDistance the eye distance, in meters. */ - public void setEyeDistance(double eyeDistance) - { + public void setEyeDistance(double eyeDistance) { this.eyeDistance = eyeDistance; this.timerAdjustedEyeDistance = eyeDistance; // reset the eye distance used by adjustTimer } @@ -162,8 +170,7 @@ public void setEyeDistance(double eyeDistance) * * @return this entry's extent. */ - public Extent getExtent() - { + public Extent getExtent() { return this.extent; } @@ -172,8 +179,7 @@ public Extent getExtent() * * @param extent the new extent. May be null. */ - public void setExtent(Extent extent) - { + public void setExtent(Extent extent) { this.extent = extent; } @@ -182,8 +188,7 @@ public void setExtent(Extent extent) * * @return this entry's expiration timer. */ - public TimedExpirySupport getTimer() - { + public TimedExpirySupport getTimer() { return timer; } @@ -192,8 +197,7 @@ public TimedExpirySupport getTimer() * * @param timer the new expiration timer. */ - public void setTimer(TimedExpirySupport timer) - { + public void setTimer(TimedExpirySupport timer) { this.timer = timer; } @@ -202,8 +206,7 @@ public void setTimer(TimedExpirySupport timer) * * @return this entry's globe state key. */ - public GlobeStateKey getGlobeStateKey() - { + public GlobeStateKey getGlobeStateKey() { return globeStateKey; } @@ -212,47 +215,45 @@ public GlobeStateKey getGlobeStateKey() * * @param globeStateKey the new globe state key. */ - public void setGlobeStateKey(GlobeStateKey globeStateKey) - { + public void setGlobeStateKey(GlobeStateKey globeStateKey) { this.globeStateKey = globeStateKey; } /** - * Indicates this entry's vertical exaggeration, captured when the entry was constructed or when explicitly - * set. + * Indicates this entry's vertical exaggeration, captured when the entry was constructed or when explicitly set. * * @return this entry's vertical exaggeration. */ - public double getVerticalExaggeration() - { + public double getVerticalExaggeration() { return verticalExaggeration; } - public void setVerticalExaggeration(double verticalExaggeration) - { + public void setVerticalExaggeration(double verticalExaggeration) { this.verticalExaggeration = verticalExaggeration; } } // usually only 1, but few at most - /** This cache's map of entries. Typically one entry per open window. */ + /** + * This cache's map of entries. Typically one entry per open window. + */ protected HashMap entries = new HashMap(1); - /** The maximum number of milliseconds an entry may remain in the cache without being used. */ + /** + * The maximum number of milliseconds an entry may remain in the cache without being used. + */ protected long maxTimeSinceLastUsed; /** * Construct a cache with a specified entry lifetime. * * @param maxTimeSinceLastUsed the maximum number of milliseconds an entry may remain in the cache without being - * used. + * used. */ - public ShapeDataCache(long maxTimeSinceLastUsed) - { + public ShapeDataCache(long maxTimeSinceLastUsed) { this.maxTimeSinceLastUsed = maxTimeSinceLastUsed; } - public Iterator iterator() - { + public Iterator iterator() { return this.entries.values().iterator(); } @@ -261,10 +262,10 @@ public Iterator iterator() * * @param entry the entry to add. If null, the cache remains unchanged. */ - public void addEntry(ShapeDataCacheEntry entry) - { - if (entry == null) + public void addEntry(ShapeDataCacheEntry entry) { + if (entry == null) { return; + } this.entries.put(entry.globeStateKey, entry); entry.lastUsed = System.currentTimeMillis(); @@ -280,17 +281,18 @@ public void addEntry(ShapeDataCacheEntry entry) * * @return the entry if it exists, otherwise null. */ - public ShapeDataCacheEntry getEntry(Globe globe) - { + public ShapeDataCacheEntry getEntry(Globe globe) { long now = System.currentTimeMillis(); // this.removeDeadEntries(now); - if (globe == null) + if (globe == null) { return null; + } ShapeDataCacheEntry entry = this.entries.get(globe.getGlobeStateKey()); - if (entry != null) + if (entry != null) { entry.lastUsed = now; + } return entry; } @@ -300,26 +302,25 @@ public ShapeDataCacheEntry getEntry(Globe globe) * * @param isExpired the expiration state. */ - public void setAllExpired(boolean isExpired) - { - for (ShapeDataCacheEntry entry : this.entries.values()) - { + public void setAllExpired(boolean isExpired) { + for (ShapeDataCacheEntry entry : this.entries.values()) { entry.setExpired(isExpired); } } - /** Set to null the extent field of all entries in this cache. */ - public void clearExtents() - { - for (ShapeDataCacheEntry entry : this.entries.values()) - { + /** + * Set to null the extent field of all entries in this cache. + */ + public void clearExtents() { + for (ShapeDataCacheEntry entry : this.entries.values()) { entry.setExtent(null); } } - /** Remove all entries from this cache. */ - public void removeAllEntries() - { + /** + * Remove all entries from this cache. + */ + public void removeAllEntries() { this.entries.clear(); } // diff --git a/src/gov/nasa/worldwind/data/AbstractDataRaster.java b/src/gov/nasa/worldwind/data/AbstractDataRaster.java index 337738a0fa..6ef7285a88 100644 --- a/src/gov/nasa/worldwind/data/AbstractDataRaster.java +++ b/src/gov/nasa/worldwind/data/AbstractDataRaster.java @@ -15,36 +15,31 @@ * @author Lado Garakanidze * @version $Id: AbstractDataRaster.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractDataRaster extends AVListImpl implements DataRaster -{ +public abstract class AbstractDataRaster extends AVListImpl implements DataRaster { + protected int width = 0; protected int height = 0; - protected AbstractDataRaster() - { + protected AbstractDataRaster() { super(); } - protected AbstractDataRaster(int width, int height, Sector sector) throws IllegalArgumentException - { + protected AbstractDataRaster(int width, int height, Sector sector) throws IllegalArgumentException { super(); - if (width < 0) - { + if (width < 0) { String message = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("generic.InvalidHeight", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().finest(message); // throw new IllegalArgumentException(message); @@ -54,8 +49,7 @@ protected AbstractDataRaster(int width, int height, Sector sector) throws Illega this.width = width; this.height = height; - if (null != sector) - { + if (null != sector) { this.setValue(AVKey.SECTOR, sector); } @@ -63,61 +57,48 @@ protected AbstractDataRaster(int width, int height, Sector sector) throws Illega this.setValue(AVKey.HEIGHT, height); } - protected AbstractDataRaster(int width, int height, Sector sector, AVList list) throws IllegalArgumentException - { + protected AbstractDataRaster(int width, int height, Sector sector, AVList list) throws IllegalArgumentException { this(width, height, sector); - if (null != list) - { - for (Map.Entry entry : list.getEntries()) - { + if (null != list) { + for (Map.Entry entry : list.getEntries()) { this.setValue(entry.getKey(), entry.getValue()); } } } - public int getWidth() - { + public int getWidth() { return this.width; } - public int getHeight() - { + public int getHeight() { return this.height; } - public Sector getSector() - { - if (this.hasKey(AVKey.SECTOR)) - { + public Sector getSector() { + if (this.hasKey(AVKey.SECTOR)) { return (Sector) this.getValue(AVKey.SECTOR); } return null; } @Override - public Object setValue(String key, Object value) - { - if (null == key) - { + public Object setValue(String key, Object value) { + if (null == key) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Do not allow to change existing WIDTH or HEIGHT - if (this.hasKey(key)) - { - if (AVKey.WIDTH.equals(key) && this.getWidth() != (Integer) value) - { + if (this.hasKey(key)) { + if (AVKey.WIDTH.equals(key) && this.getWidth() != (Integer) value) { String message = Logging.getMessage("generic.AttemptToChangeReadOnlyProperty", key); Logging.logger().finest(message); // relax restriction, just log and continue // throw new IllegalArgumentException(message); return this; - } - else if (AVKey.HEIGHT.equals(key) && this.getHeight() != (Integer) value) - { + } else if (AVKey.HEIGHT.equals(key) && this.getHeight() != (Integer) value) { String message = Logging.getMessage("generic.AttemptToChangeReadOnlyProperty", key); Logging.logger().finest(message); // relax restriction, just log and continue @@ -128,10 +109,9 @@ else if (AVKey.HEIGHT.equals(key) && this.getHeight() != (Integer) value) return super.setValue(key, value); } - protected java.awt.Rectangle computeClipRect(Sector clipSector, DataRaster clippedRaster) - { + protected java.awt.Rectangle computeClipRect(Sector clipSector, DataRaster clippedRaster) { java.awt.geom.AffineTransform geographicToRaster = this.computeGeographicToRasterTransform( - clippedRaster.getWidth(), clippedRaster.getHeight(), clippedRaster.getSector()); + clippedRaster.getWidth(), clippedRaster.getHeight(), clippedRaster.getSector()); java.awt.geom.Point2D geoPoint = new java.awt.geom.Point2D.Double(); java.awt.geom.Point2D ul = new java.awt.geom.Point2D.Double(); @@ -152,21 +132,20 @@ protected java.awt.Rectangle computeClipRect(Sector clipSector, DataRaster clipp } protected java.awt.geom.AffineTransform computeSourceToDestTransform( - int sourceWidth, int sourceHeight, Sector sourceSector, - int destWidth, int destHeight, Sector destSector) - { + int sourceWidth, int sourceHeight, Sector sourceSector, + int destWidth, int destHeight, Sector destSector) { // Compute the the transform from source to destination coordinates. In this computation a pixel is assumed // to cover a finite area. double ty = destHeight * -(sourceSector.getMaxLatitude().degrees - destSector.getMaxLatitude().degrees) - / destSector.getDeltaLatDegrees(); + / destSector.getDeltaLatDegrees(); double tx = destWidth * (sourceSector.getMinLongitude().degrees - destSector.getMinLongitude().degrees) - / destSector.getDeltaLonDegrees(); + / destSector.getDeltaLonDegrees(); double sy = ((double) destHeight / (double) sourceHeight) - * (sourceSector.getDeltaLatDegrees() / destSector.getDeltaLatDegrees()); + * (sourceSector.getDeltaLatDegrees() / destSector.getDeltaLatDegrees()); double sx = ((double) destWidth / (double) sourceWidth) - * (sourceSector.getDeltaLonDegrees() / destSector.getDeltaLonDegrees()); + * (sourceSector.getDeltaLonDegrees() / destSector.getDeltaLonDegrees()); java.awt.geom.AffineTransform transform = new java.awt.geom.AffineTransform(); transform.translate(tx, ty); @@ -174,8 +153,7 @@ protected java.awt.geom.AffineTransform computeSourceToDestTransform( return transform; } - protected java.awt.geom.AffineTransform computeGeographicToRasterTransform(int width, int height, Sector sector) - { + protected java.awt.geom.AffineTransform computeGeographicToRasterTransform(int width, int height, Sector sector) { // Compute the the transform from geographic to raster coordinates. In this computation a pixel is assumed // to cover a finite area. @@ -191,13 +169,12 @@ protected java.awt.geom.AffineTransform computeGeographicToRasterTransform(int w return transform; } - public DataRaster getSubRaster(int width, int height, Sector sector, AVList params) - { + public DataRaster getSubRaster(int width, int height, Sector sector, AVList params) { params = (null == params) ? new AVListImpl() : params; // copy parent raster keys/values; only those key/value will be copied that do exist in the parent raster // AND does NOT exist in the requested raster - String[] keysToCopy = new String[] { + String[] keysToCopy = new String[]{ AVKey.DATA_TYPE, AVKey.MISSING_DATA_SIGNAL, AVKey.BYTE_ORDER, AVKey.PIXEL_FORMAT, AVKey.ELEVATION_UNIT }; WWUtil.copyValues(this, params, keysToCopy, false); @@ -213,74 +190,65 @@ public DataRaster getSubRaster(int width, int height, Sector sector, AVList para * Reads the specified region of interest (ROI) with given extent, width, and height, and type * * @param params Required parameters are: - *

    - * AVKey.HEIGHT as Integer, specifies a height of the desired ROI AVKey.WIDTH as Integer, specifies a - * width of the desired ROI AVKey.SECTOR as Sector, specifies an extent of the desired ROI - *

    - * Optional parameters are: - *

    - * AVKey.BAND_ORDER as array of integers, examples: for RGBA image: new int[] { 0, 1, 2, 3 }, or for - * ARGB image: new int[] { 3, 0, 1, 2 } or if you want only RGB bands of the RGBA image: new int[] { - * 0, 1, 2 } or only Intensity (4th) band of the specific aerial image: new int[] { 3 } + *

    + * AVKey.HEIGHT as Integer, specifies a height of the desired ROI AVKey.WIDTH as Integer, specifies a width of the + * desired ROI AVKey.SECTOR as Sector, specifies an extent of the desired ROI + *

    + * Optional parameters are: + *

    + * AVKey.BAND_ORDER as array of integers, examples: for RGBA image: new int[] { 0, 1, 2, 3 }, or for ARGB image: new + * int[] { 3, 0, 1, 2 } or if you want only RGB bands of the RGBA image: new int[] { 0, 1, 2 } or only Intensity + * (4th) band of the specific aerial image: new int[] { 3 } * * @return DataRaster (BufferedImageRaster for imagery or ByteBufferDataRaster for elevations) */ - public DataRaster getSubRaster(AVList params) - { - if (null == params) - { + public DataRaster getSubRaster(AVList params) { + if (null == params) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!params.hasKey(AVKey.WIDTH)) - { + if (!params.hasKey(AVKey.WIDTH)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.WIDTH); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int roiWidth = (Integer) params.getValue(AVKey.WIDTH); - if (roiWidth <= 0) - { + if (roiWidth <= 0) { String message = Logging.getMessage("generic.InvalidWidth", roiWidth); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!params.hasKey(AVKey.HEIGHT)) - { + if (!params.hasKey(AVKey.HEIGHT)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.HEIGHT); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int roiHeight = (Integer) params.getValue(AVKey.HEIGHT); - if (roiHeight <= 0) - { + if (roiHeight <= 0) { String message = Logging.getMessage("generic.InvalidHeight", roiHeight); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!params.hasKey(AVKey.SECTOR)) - { + if (!params.hasKey(AVKey.SECTOR)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Sector roiSector = (Sector) params.getValue(AVKey.SECTOR); - if (null == roiSector || Sector.EMPTY_SECTOR.equals(roiSector)) - { + if (null == roiSector || Sector.EMPTY_SECTOR.equals(roiSector)) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (Sector.EMPTY_SECTOR.equals(roiSector)) - { + if (Sector.EMPTY_SECTOR.equals(roiSector)) { String message = Logging.getMessage("nullValue.SectorGeometryIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -288,7 +256,7 @@ public DataRaster getSubRaster(AVList params) // copy parent raster keys/values; only those key/value will be copied that do exist in the parent raster // AND does NOT exist in the requested raster - String[] keysToCopy = new String[] { + String[] keysToCopy = new String[]{ AVKey.DATA_TYPE, AVKey.MISSING_DATA_SIGNAL, AVKey.BYTE_ORDER, AVKey.PIXEL_FORMAT, AVKey.ELEVATION_UNIT }; WWUtil.copyValues(this, params, keysToCopy, false); diff --git a/src/gov/nasa/worldwind/data/AbstractDataRasterReader.java b/src/gov/nasa/worldwind/data/AbstractDataRasterReader.java index 8406cd606b..8b15c4a065 100644 --- a/src/gov/nasa/worldwind/data/AbstractDataRasterReader.java +++ b/src/gov/nasa/worldwind/data/AbstractDataRasterReader.java @@ -18,8 +18,8 @@ * @author dcollins * @version $Id: AbstractDataRasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractDataRasterReader extends AVListImpl implements DataRasterReader -{ +public abstract class AbstractDataRasterReader extends AVListImpl implements DataRasterReader { + protected abstract boolean doCanRead(Object source, AVList params); protected abstract DataRaster[] doRead(Object source, AVList params) throws java.io.IOException; @@ -30,8 +30,7 @@ public abstract class AbstractDataRasterReader extends AVListImpl implements Dat protected final String[] mimeTypes; protected final String[] suffixes; - public AbstractDataRasterReader(String description, String[] mimeTypes, String[] suffixes) - { + public AbstractDataRasterReader(String description, String[] mimeTypes, String[] suffixes) { this.description = description; this.mimeTypes = Arrays.copyOf(mimeTypes, mimeTypes.length); this.suffixes = Arrays.copyOf(suffixes, suffixes.length); @@ -39,64 +38,64 @@ public AbstractDataRasterReader(String description, String[] mimeTypes, String[] this.setValue(AVKey.SERVICE_NAME, AVKey.SERVICE_NAME_OFFLINE); } - public AbstractDataRasterReader(String[] mimeTypes, String[] suffixes) - { + public AbstractDataRasterReader(String[] mimeTypes, String[] suffixes) { this(descriptionFromSuffixes(suffixes), mimeTypes, suffixes); } - protected AbstractDataRasterReader(String description) - { + protected AbstractDataRasterReader(String description) { this(description, new String[0], new String[0]); } - /** {@inheritDoc} */ - public String getDescription() - { + /** + * {@inheritDoc} + */ + public String getDescription() { return this.description; } - public String[] getMimeTypes() - { + public String[] getMimeTypes() { String[] copy = new String[mimeTypes.length]; System.arraycopy(mimeTypes, 0, copy, 0, mimeTypes.length); return copy; } - /** {@inheritDoc} */ - public String[] getSuffixes() - { + /** + * {@inheritDoc} + */ + public String[] getSuffixes() { String[] copy = new String[suffixes.length]; System.arraycopy(suffixes, 0, copy, 0, suffixes.length); return copy; } - /** {@inheritDoc} */ - public boolean canRead(Object source, AVList params) - { - if (source == null) + /** + * {@inheritDoc} + */ + public boolean canRead(Object source, AVList params) { + if (source == null) { return false; + } //noinspection SimplifiableIfStatement - if (!this.canReadSuffix(source)) + if (!this.canReadSuffix(source)) { return false; + } return this.doCanRead(source, params); } - protected boolean canReadSuffix(Object source) - { + protected boolean canReadSuffix(Object source) { // If the source has no path, we cannot return failure, so return that the test passed. String path = WWIO.getSourcePath(source); - if (path == null) + if (path == null) { return true; + } // If the source has a suffix, then we return success if this reader supports the suffix. String pathSuffix = WWIO.getSuffix(path); boolean matchesAny = false; - for (String suffix : suffixes) - { - if (suffix.equalsIgnoreCase(pathSuffix)) - { + for (String suffix : suffixes) { + if (suffix.equalsIgnoreCase(pathSuffix)) { matchesAny = true; break; } @@ -104,11 +103,11 @@ protected boolean canReadSuffix(Object source) return matchesAny; } - /** {@inheritDoc} */ - public DataRaster[] read(Object source, AVList params) throws java.io.IOException - { - if (!this.canRead(source, params)) - { + /** + * {@inheritDoc} + */ + public DataRaster[] read(Object source, AVList params) throws java.io.IOException { + if (!this.canRead(source, params)) { String message = Logging.getMessage("DataRaster.CannotRead", source); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -117,79 +116,82 @@ public DataRaster[] read(Object source, AVList params) throws java.io.IOExceptio return this.doRead(source, params); } - /** {@inheritDoc} */ - public AVList readMetadata(Object source, AVList params) throws java.io.IOException - { - if (!this.canRead(source, params)) - { + /** + * {@inheritDoc} + */ + public AVList readMetadata(Object source, AVList params) throws java.io.IOException { + if (!this.canRead(source, params)) { String message = Logging.getMessage("DataRaster.CannotRead", source); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } this.doReadMetadata(source, params); String message = this.validateMetadata(source, params); - if (message != null) + if (message != null) { throw new java.io.IOException(message); + } return params; } - protected String validateMetadata(Object source, AVList params) - { + protected String validateMetadata(Object source, AVList params) { StringBuilder sb = new StringBuilder(); Object o = (params != null) ? params.getValue(AVKey.WIDTH) : null; - if (o == null || !(o instanceof Integer)) + if (o == null || !(o instanceof Integer)) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("WorldFile.NoSizeSpecified", source)); + } o = (params != null) ? params.getValue(AVKey.HEIGHT) : null; - if (o == null || !(o instanceof Integer)) + if (o == null || !(o instanceof Integer)) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("WorldFile.NoSizeSpecified", source)); + } o = (params != null) ? params.getValue(AVKey.SECTOR) : null; - if (o == null || !(o instanceof Sector)) + if (o == null || !(o instanceof Sector)) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("WorldFile.NoSectorSpecified", source)); + } - if (sb.length() == 0) + if (sb.length() == 0) { return null; + } return sb.toString(); } - /** {@inheritDoc} */ - public boolean isImageryRaster(Object source, AVList params) - { - if (params != null && AVKey.IMAGE.equals(params.getStringValue(AVKey.PIXEL_FORMAT))) + /** + * {@inheritDoc} + */ + public boolean isImageryRaster(Object source, AVList params) { + if (params != null && AVKey.IMAGE.equals(params.getStringValue(AVKey.PIXEL_FORMAT))) { return true; + } - try - { + try { AVList metadata = this.readMetadata(source, params); return metadata != null && AVKey.IMAGE.equals(metadata.getStringValue(AVKey.PIXEL_FORMAT)); - } - catch (IOException e) - { + } catch (IOException e) { return false; } } - /** {@inheritDoc} */ - public boolean isElevationsRaster(Object source, AVList params) - { - if (params != null && AVKey.ELEVATION.equals(params.getStringValue(AVKey.PIXEL_FORMAT))) + /** + * {@inheritDoc} + */ + public boolean isElevationsRaster(Object source, AVList params) { + if (params != null && AVKey.ELEVATION.equals(params.getStringValue(AVKey.PIXEL_FORMAT))) { return true; + } - try - { + try { AVList metadata = this.readMetadata(source, params); return metadata != null && AVKey.ELEVATION.equals(metadata.getStringValue(AVKey.PIXEL_FORMAT)); - } - catch (IOException e) - { + } catch (IOException e) { return false; } } @@ -197,14 +199,12 @@ public boolean isElevationsRaster(Object source, AVList params) //**************************************************************// //******************** Utilities *****************************// //**************************************************************// - - private static String descriptionFromSuffixes(String[] suffixes) - { + private static String descriptionFromSuffixes(String[] suffixes) { StringBuilder sb = new StringBuilder(); - for (String suffix : suffixes) - { - if (sb.length() > 0) + for (String suffix : suffixes) { + if (sb.length() > 0) { sb.append(", "); + } sb.append("*.").append(suffix.toLowerCase()); } return sb.toString(); diff --git a/src/gov/nasa/worldwind/data/AbstractDataRasterWriter.java b/src/gov/nasa/worldwind/data/AbstractDataRasterWriter.java index 1e0b5e3bb4..ad9746b27f 100644 --- a/src/gov/nasa/worldwind/data/AbstractDataRasterWriter.java +++ b/src/gov/nasa/worldwind/data/AbstractDataRasterWriter.java @@ -11,18 +11,18 @@ * @author dcollins * @version $Id: AbstractDataRasterWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractDataRasterWriter implements DataRasterWriter -{ +public abstract class AbstractDataRasterWriter implements DataRasterWriter { + protected final String[] mimeTypes; - protected final String[] suffixes; + protected final String[] suffixes; /** * Constructor + * * @param mimeTypes MIME types as array ofStrings * @param suffixes Suffixes (extensions) as array ofStrings */ - public AbstractDataRasterWriter(String[] mimeTypes, String[] suffixes) - { + public AbstractDataRasterWriter(String[] mimeTypes, String[] suffixes) { this.mimeTypes = this.copyAndConvertToLowerCase(mimeTypes); this.suffixes = this.copyAndConvertToLowerCase(suffixes); } @@ -30,59 +30,56 @@ public AbstractDataRasterWriter(String[] mimeTypes, String[] suffixes) /** * Default constructor */ - public AbstractDataRasterWriter() - { + public AbstractDataRasterWriter() { this.mimeTypes = null; this.suffixes = null; } - /** {@inheritDoc} */ - public boolean canWrite(DataRaster raster, String formatSuffix, java.io.File file) - { - if (formatSuffix == null) + /** + * {@inheritDoc} + */ + public boolean canWrite(DataRaster raster, String formatSuffix, java.io.File file) { + if (formatSuffix == null) { return false; + } formatSuffix = WWUtil.stripLeadingPeriod(formatSuffix); - if( null != this.suffixes && this.suffixes.length > 0 ) - { + if (null != this.suffixes && this.suffixes.length > 0) { boolean matchesAny = false; - for (String suffix : this.suffixes) - { - if (suffix.equalsIgnoreCase(formatSuffix)) - { + for (String suffix : this.suffixes) { + if (suffix.equalsIgnoreCase(formatSuffix)) { matchesAny = true; break; } } //noinspection SimplifiableIfStatement - if (!matchesAny) + if (!matchesAny) { return false; + } } return this.doCanWrite(raster, formatSuffix, file); } - /** {@inheritDoc} */ - public void write(DataRaster raster, String formatSuffix, java.io.File file) throws java.io.IOException - { - if (raster == null) - { + /** + * {@inheritDoc} + */ + public void write(DataRaster raster, String formatSuffix, java.io.File file) throws java.io.IOException { + if (raster == null) { String message = Logging.getMessage("nullValue.RasterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (formatSuffix == null) - { + if (formatSuffix == null) { String message = Logging.getMessage("nullValue.FormatSuffixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } formatSuffix = WWUtil.stripLeadingPeriod(formatSuffix); - if (!this.canWrite(raster, formatSuffix, file)) - { + if (!this.canWrite(raster, formatSuffix, file)) { String message = Logging.getMessage("DataRaster.CannotWrite", raster, formatSuffix, file); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -98,21 +95,21 @@ public void write(DataRaster raster, String formatSuffix, java.io.File file) thr //**************************************************************// //******************** Utilities *****************************// //**************************************************************// - /** * Clones string array and also converts clones to lower case * * @param array string array * @return cloned string array */ - protected String[] copyAndConvertToLowerCase(String[] array) - { - if( null == array ) + protected String[] copyAndConvertToLowerCase(String[] array) { + if (null == array) { return null; + } String[] copy = new String[array.length]; - for (int i = 0; i < array.length; i++) + for (int i = 0; i < array.length; i++) { copy[i] = array[i].toLowerCase(); + } return copy; } diff --git a/src/gov/nasa/worldwind/data/AbstractDataStoreProducer.java b/src/gov/nasa/worldwind/data/AbstractDataStoreProducer.java index 1be49da194..551033170c 100644 --- a/src/gov/nasa/worldwind/data/AbstractDataStoreProducer.java +++ b/src/gov/nasa/worldwind/data/AbstractDataStoreProducer.java @@ -15,54 +15,48 @@ * @author dcollins * @version $Id: AbstractDataStoreProducer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractDataStoreProducer extends WWObjectImpl implements DataStoreProducer -{ - public static class SourceInfo extends AVListImpl - { +public abstract class AbstractDataStoreProducer extends WWObjectImpl implements DataStoreProducer { + + public static class SourceInfo extends AVListImpl { + public Object source; - public SourceInfo(Object source, AVList params) - { + public SourceInfo(Object source, AVList params) { this.source = source; - if (null != params) + if (null != params) { this.setValues(params); + } } } private AVList params; - private java.util.List dataSourceList = - Collections.synchronizedList(new java.util.ArrayList()); + private java.util.List dataSourceList + = Collections.synchronizedList(new java.util.ArrayList()); private java.util.List productionResults = new java.util.ArrayList(); private boolean isStopped = false; protected AVList productionParams = null; - public AbstractDataStoreProducer() - { + public AbstractDataStoreProducer() { } - public AVList getProductionParameters() - { + public AVList getProductionParameters() { return this.productionParams; } - public AVList getStoreParameters() - { + public AVList getStoreParameters() { return this.params; } - public void setStoreParameters(AVList parameters) - { - if (parameters == null) - { + public void setStoreParameters(AVList parameters) { + if (parameters == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String message = this.validateProductionParameters(parameters); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -70,27 +64,24 @@ public void setStoreParameters(AVList parameters) this.params = parameters; } - public Iterable getDataSources() - { + public Iterable getDataSources() { ArrayList list = new ArrayList(); - for (SourceInfo info : this.dataSourceList) - { + for (SourceInfo info : this.dataSourceList) { list.add(info.source); } return list; } - public boolean acceptsDataSource(Object source, AVList params) - { - if (source == null || this.isStopped()) + public boolean acceptsDataSource(Object source, AVList params) { + if (source == null || this.isStopped()) { return false; + } String message = this.validateDataSource(source, params); //noinspection RedundantIfStatement - if (message != null) - { + if (message != null) { // TODO garakl Do we want to log these files which we do not have readers for? // Logging.logger().finest(message); return false; @@ -99,21 +90,18 @@ public boolean acceptsDataSource(Object source, AVList params) return true; } - public boolean containsDataSource(Object source) - { - for (SourceInfo info : this.dataSourceList) - { - if (info.source != null ? info.source.equals(source) : (source == null)) + public boolean containsDataSource(Object source) { + for (SourceInfo info : this.dataSourceList) { + if (info.source != null ? info.source.equals(source) : (source == null)) { return true; + } } return false; } - public void offerDataSource(Object source, AVList params) - { - if (source == null) - { + public void offerDataSource(Object source, AVList params) { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -121,8 +109,7 @@ public void offerDataSource(Object source, AVList params) params = (null == params) ? new AVListImpl() : params.copy(); String message = this.validateDataSource(source, params); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -130,58 +117,50 @@ public void offerDataSource(Object source, AVList params) this.dataSourceList.add(new SourceInfo(source, params)); } - public void offerAllDataSources(Iterable sources) - { - if (sources == null) - { + public void offerAllDataSources(Iterable sources) { + if (sources == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (Object source : sources) - { + for (Object source : sources) { this.offerDataSource(source, null); } } - public void removeDataSource(Object source) - { - if (source == null) - { + public void removeDataSource(Object source) { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); return; // Warn but don't throw an exception. } Iterator iter = this.dataSourceList.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return; + } - for (SourceInfo info = iter.next(); iter.hasNext(); info = iter.next()) - { - if (info.source != null && info.source.equals(source)) + for (SourceInfo info = iter.next(); iter.hasNext(); info = iter.next()) { + if (info.source != null && info.source.equals(source)) { iter.remove(); + } } } - public void removeAllDataSources() - { + public void removeAllDataSources() { this.dataSourceList.clear(); } - public void startProduction() throws Exception - { - if (this.isStopped()) - { + public void startProduction() throws Exception { + if (this.isStopped()) { String message = Logging.getMessage("DataStoreProducer.Stopped"); Logging.logger().warning(message); return; } String message = this.validateProductionParameters(this.params); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalStateException(message); } @@ -189,33 +168,27 @@ public void startProduction() throws Exception this.doStartProduction(this.params); } - public synchronized void stopProduction() - { + public synchronized void stopProduction() { this.isStopped = true; } - protected synchronized boolean isStopped() - { + protected synchronized boolean isStopped() { return this.isStopped; } - public Iterable getProductionResults() - { + public Iterable getProductionResults() { return java.util.Collections.unmodifiableList(this.productionResults); } - public void removeProductionState() - { + public void removeProductionState() { // Left as an optional operation for subclasses to define. } - protected java.util.List getDataSourceList() - { + protected java.util.List getDataSourceList() { return this.dataSourceList; } - protected java.util.List getProductionResultsList() - { + protected java.util.List getProductionResultsList() { return this.productionResults; } diff --git a/src/gov/nasa/worldwind/data/BILRasterReader.java b/src/gov/nasa/worldwind/data/BILRasterReader.java index 7b6c5befb1..0a238e20be 100644 --- a/src/gov/nasa/worldwind/data/BILRasterReader.java +++ b/src/gov/nasa/worldwind/data/BILRasterReader.java @@ -16,41 +16,33 @@ * @author dcollins * @version $Id: BILRasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BILRasterReader extends AbstractDataRasterReader -{ - private static final String[] bilMimeTypes = new String[] - {"image/bil", "application/bil", "application/bil16", "application/bil32"}; +public class BILRasterReader extends AbstractDataRasterReader { - private static final String[] bilSuffixes = new String[] - {"bil", "bil16", "bil32", "bil.gz", "bil16.gz", "bil32.gz"}; + private static final String[] bilMimeTypes = new String[]{"image/bil", "application/bil", "application/bil16", "application/bil32"}; + + private static final String[] bilSuffixes = new String[]{"bil", "bil16", "bil32", "bil.gz", "bil16.gz", "bil32.gz"}; private boolean mapLargeFiles = false; private long largeFileThreshold = 16777216L; // 16 megabytes - public BILRasterReader() - { + public BILRasterReader() { super(bilMimeTypes, bilSuffixes); } - public boolean isMapLargeFiles() - { + public boolean isMapLargeFiles() { return this.mapLargeFiles; } - public void setMapLargeFiles(boolean mapLargeFiles) - { + public void setMapLargeFiles(boolean mapLargeFiles) { this.mapLargeFiles = mapLargeFiles; } - public long getLargeFileThreshold() - { + public long getLargeFileThreshold() { return this.largeFileThreshold; } - public void setLargeFileThreshold(long largeFileThreshold) - { - if (largeFileThreshold < 0L) - { + public void setLargeFileThreshold(long largeFileThreshold) { + if (largeFileThreshold < 0L) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "largeFileThreshold < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -59,29 +51,23 @@ public void setLargeFileThreshold(long largeFileThreshold) this.largeFileThreshold = largeFileThreshold; } - protected boolean doCanRead(Object source, AVList params) - { - if (!(source instanceof java.io.File) && !(source instanceof java.net.URL)) - { + protected boolean doCanRead(Object source, AVList params) { + if (!(source instanceof java.io.File) && !(source instanceof java.net.URL)) { return false; } // If the data source doesn't already have all the necessary metadata, then we determine whether or not // the missing metadata can be read. String error = this.validateMetadata(source, params); - if (!WWUtil.isEmpty(error)) - { - if (!WorldFile.hasWorldFiles(source)) - { + if (!WWUtil.isEmpty(error)) { + if (!WorldFile.hasWorldFiles(source)) { Logging.logger().fine(error); return false; } } - if (null != params) - { - if (!params.hasKey(AVKey.PIXEL_FORMAT)) - { + if (null != params) { + if (!params.hasKey(AVKey.PIXEL_FORMAT)) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); } } @@ -89,14 +75,12 @@ protected boolean doCanRead(Object source, AVList params) return true; } - protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOException - { + protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOException { java.nio.ByteBuffer byteBuffer = this.readElevations(source); // If the parameter list is null, or doesn't already have all the necessary metadata, then we copy the parameter // list and attempt to populate the copy with any missing metadata. - if (this.validateMetadata(source, params) != null) - { + if (this.validateMetadata(source, params) != null) { // Copy the parameter list to insulate changes from the caller. params = (params != null) ? params.copy() : new AVListImpl(); params.setValue(AVKey.FILE_SIZE, byteBuffer.capacity()); @@ -107,69 +91,56 @@ protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOExc int height = (Integer) params.getValue(AVKey.HEIGHT); Sector sector = (Sector) params.getValue(AVKey.SECTOR); - if (!params.hasKey(AVKey.PIXEL_FORMAT)) - { + if (!params.hasKey(AVKey.PIXEL_FORMAT)) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); } ByteBufferRaster raster = new ByteBufferRaster(width, height, sector, byteBuffer, params); ElevationsUtil.rectify(raster); - return new DataRaster[] { raster }; + return new DataRaster[]{raster}; } - protected void doReadMetadata(Object source, AVList params) throws java.io.IOException - { - if (this.validateMetadata(source, params) != null) - { + protected void doReadMetadata(Object source, AVList params) throws java.io.IOException { + if (this.validateMetadata(source, params) != null) { WorldFile.readWorldFiles(source, params); } } - protected String validateMetadata(Object source, AVList params) - { + protected String validateMetadata(Object source, AVList params) { StringBuilder sb = new StringBuilder(); String message = super.validateMetadata(source, params); - if (message != null) - { + if (message != null) { sb.append(message); } Object o = (params != null) ? params.getValue(AVKey.BYTE_ORDER) : null; - if (o == null || !(o instanceof String)) - { + if (o == null || !(o instanceof String)) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("WorldFile.NoByteOrderSpecified", source)); } o = (params != null) ? params.getValue(AVKey.PIXEL_FORMAT) : null; - if (o == null) - { + if (o == null) { sb.append(sb.length() > 0 ? ", " : "").append( - Logging.getMessage("WorldFile.NoPixelFormatSpecified", source)); - } - else if (!AVKey.ELEVATION.equals(o)) - { + Logging.getMessage("WorldFile.NoPixelFormatSpecified", source)); + } else if (!AVKey.ELEVATION.equals(o)) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("WorldFile.InvalidPixelFormat", source)); } o = (params != null) ? params.getValue(AVKey.DATA_TYPE) : null; - if (o == null) - { + if (o == null) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("WorldFile.NoDataTypeSpecified", source)); } - if (sb.length() == 0) - { + if (sb.length() == 0) { return null; } return sb.toString(); } - private java.nio.ByteBuffer readElevations(Object source) throws java.io.IOException - { - if (!(source instanceof java.io.File) && !(source instanceof java.net.URL)) - { + private java.nio.ByteBuffer readElevations(Object source) throws java.io.IOException { + if (!(source instanceof java.io.File) && !(source instanceof java.net.URL)) { String message = Logging.getMessage("DataRaster.CannotRead", source); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -178,33 +149,23 @@ private java.nio.ByteBuffer readElevations(Object source) throws java.io.IOExcep File file = (source instanceof java.io.File) ? (File) source : null; java.net.URL url = (source instanceof java.net.URL) ? (java.net.URL) source : null; - if (null == file && "file".equalsIgnoreCase(url.getProtocol())) - { + if (null == file && "file".equalsIgnoreCase(url.getProtocol())) { file = new File(url.getFile()); } - if (null != file) - { + if (null != file) { // handle .bil.zip, .bil16.zip, and .bil32.gz files - if (file.getName().toLowerCase().endsWith(".zip")) - { + if (file.getName().toLowerCase().endsWith(".zip")) { return WWIO.readZipEntryToBuffer(file, null); - } - // handle bil.gz, bil16.gz, and bil32.gz files - else if (file.getName().toLowerCase().endsWith(".gz")) - { + } // handle bil.gz, bil16.gz, and bil32.gz files + else if (file.getName().toLowerCase().endsWith(".gz")) { return WWIO.readGZipFileToBuffer(file); - } - else if (!this.isMapLargeFiles() || (this.getLargeFileThreshold() > file.length())) - { + } else if (!this.isMapLargeFiles() || (this.getLargeFileThreshold() > file.length())) { return WWIO.readFileToBuffer(file); - } - else - { + } else { return WWIO.mapFile(file); } - } - else // (source instanceof java.net.URL) + } else // (source instanceof java.net.URL) { return WWIO.readURLContentToBuffer(url); } diff --git a/src/gov/nasa/worldwind/data/BILRasterWriter.java b/src/gov/nasa/worldwind/data/BILRasterWriter.java index 51460183b5..7faf137c6b 100644 --- a/src/gov/nasa/worldwind/data/BILRasterWriter.java +++ b/src/gov/nasa/worldwind/data/BILRasterWriter.java @@ -16,52 +16,44 @@ * @author dcollins * @version $Id: BILRasterWriter.java 1514 2013-07-22 23:17:23Z dcollins $ */ -public class BILRasterWriter extends AbstractDataRasterWriter -{ - protected static final String[] bilMimeTypes = new String[] {"image/bil"}; - protected static final String[] bilSuffixes = new String[] {"bil"}; +public class BILRasterWriter extends AbstractDataRasterWriter { + + protected static final String[] bilMimeTypes = new String[]{"image/bil"}; + protected static final String[] bilSuffixes = new String[]{"bil"}; protected boolean writeGeoreferenceFiles; - public BILRasterWriter(boolean writeGeoreferenceFiles) - { + public BILRasterWriter(boolean writeGeoreferenceFiles) { super(bilMimeTypes, bilSuffixes); this.writeGeoreferenceFiles = writeGeoreferenceFiles; } - public BILRasterWriter() - { + public BILRasterWriter() { this(true); // Enable writing georeference files by default. } - public boolean isWriteGeoreferenceFiles() - { + public boolean isWriteGeoreferenceFiles() { return this.writeGeoreferenceFiles; } - public void setWriteGeoreferenceFiles(boolean writeGeoreferenceFiles) - { + public void setWriteGeoreferenceFiles(boolean writeGeoreferenceFiles) { this.writeGeoreferenceFiles = writeGeoreferenceFiles; } - protected boolean doCanWrite(DataRaster raster, String formatSuffix, File file) - { + protected boolean doCanWrite(DataRaster raster, String formatSuffix, File file) { return (raster != null) && (raster instanceof ByteBufferRaster); } - protected void doWrite(DataRaster raster, String formatSuffix, File file) throws IOException - { + protected void doWrite(DataRaster raster, String formatSuffix, File file) throws IOException { this.writeRaster(raster, file); - if (this.isWriteGeoreferenceFiles()) - { + if (this.isWriteGeoreferenceFiles()) { AVList worldFileParams = new AVListImpl(); this.initWorldFileParams(raster, worldFileParams); String message = this.validate(worldFileParams, raster); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new java.io.IOException(message); } @@ -74,8 +66,7 @@ protected void doWrite(DataRaster raster, String formatSuffix, File file) throws } } - protected void writeRaster(DataRaster raster, java.io.File file) throws java.io.IOException - { + protected void writeRaster(DataRaster raster, java.io.File file) throws java.io.IOException { ByteBufferRaster byteBufferRaster = (ByteBufferRaster) raster; java.nio.ByteBuffer byteBuffer = byteBufferRaster.getByteBuffer(); @@ -84,8 +75,7 @@ protected void writeRaster(DataRaster raster, java.io.File file) throws java.io. WWIO.saveBuffer(byteBuffer, file, forceFilesystemWrite); } - protected void writeWorldFile(AVList values, java.io.File file) throws java.io.IOException - { + protected void writeWorldFile(AVList values, java.io.File file) throws java.io.IOException { Sector sector = (Sector) values.getValue(AVKey.SECTOR); int[] size = (int[]) values.getValue(WorldFile.WORLD_FILE_IMAGE_SIZE); @@ -97,8 +87,7 @@ protected void writeWorldFile(AVList values, java.io.File file) throws java.io.I double yLocation = sector.getMaxLatitude().degrees; java.io.PrintWriter out = new java.io.PrintWriter(file); - try - { + try { out.println(xPixelSize); out.println(xCoeff); //noinspection SuspiciousNameCombination @@ -108,32 +97,29 @@ protected void writeWorldFile(AVList values, java.io.File file) throws java.io.I out.println(xLocation); //noinspection SuspiciousNameCombination out.println(yLocation); - } - finally - { + } finally { out.close(); } } - protected void writeHdrFile(AVList values, java.io.File file) throws java.io.IOException - { + protected void writeHdrFile(AVList values, java.io.File file) throws java.io.IOException { int[] size = (int[]) values.getValue(WorldFile.WORLD_FILE_IMAGE_SIZE); Object byteOrder = values.getValue(AVKey.BYTE_ORDER); Object dataType = values.getValue(AVKey.DATA_TYPE); int nBits = 0; - if (AVKey.INT8.equals(dataType)) + if (AVKey.INT8.equals(dataType)) { nBits = 8; - else if (AVKey.INT16.equals(dataType)) + } else if (AVKey.INT16.equals(dataType)) { nBits = 16; - else if (AVKey.INT32.equals(dataType) || AVKey.FLOAT32.equals(dataType)) + } else if (AVKey.INT32.equals(dataType) || AVKey.FLOAT32.equals(dataType)) { nBits = 32; + } int rowBytes = size[0] * (nBits / 8); java.io.PrintWriter out = new java.io.PrintWriter(file); - try - { + try { out.append("BYTEORDER ").println(AVKey.BIG_ENDIAN.equals(byteOrder) ? "M" : "I"); out.append("LAYOUT ").println("BIL"); out.append("NROWS ").println(size[1]); @@ -147,17 +133,15 @@ else if (AVKey.INT32.equals(dataType) || AVKey.FLOAT32.equals(dataType)) // This code expects the string "gov.nasa.worldwind.avkey.MissingDataValue", which now corresponds to the // key MISSING_DATA_REPLACEMENT. Object o = values.getValue(AVKey.MISSING_DATA_REPLACEMENT); - if (o != null) + if (o != null) { out.append("NODATA ").println(o); - } - finally - { + } + } finally { out.close(); } } - protected void initWorldFileParams(DataRaster raster, AVList worldFileParams) - { + protected void initWorldFileParams(DataRaster raster, AVList worldFileParams) { ByteBufferRaster byteBufferRaster = (ByteBufferRaster) raster; int[] size = new int[2]; @@ -173,63 +157,68 @@ protected void initWorldFileParams(DataRaster raster, AVList worldFileParams) worldFileParams.setValue(AVKey.DATA_TYPE, getDataType(byteBufferRaster.getBuffer())); double d = byteBufferRaster.getTransparentValue(); - if (d != Double.MAX_VALUE) + if (d != Double.MAX_VALUE) { worldFileParams.setValue(AVKey.MISSING_DATA_REPLACEMENT, d); + } } - private static Object getDataType(BufferWrapper buffer) - { + private static Object getDataType(BufferWrapper buffer) { Object dataType = null; - if (buffer instanceof BufferWrapper.ByteBufferWrapper) + if (buffer instanceof BufferWrapper.ByteBufferWrapper) { dataType = AVKey.INT8; - else if (buffer instanceof BufferWrapper.ShortBufferWrapper) + } else if (buffer instanceof BufferWrapper.ShortBufferWrapper) { dataType = AVKey.INT16; - else if (buffer instanceof BufferWrapper.IntBufferWrapper) + } else if (buffer instanceof BufferWrapper.IntBufferWrapper) { dataType = AVKey.INT32; - else if (buffer instanceof BufferWrapper.FloatBufferWrapper) + } else if (buffer instanceof BufferWrapper.FloatBufferWrapper) { dataType = AVKey.FLOAT32; + } return dataType; } - private static Object getByteOrder(java.nio.ByteBuffer byteBuffer) - { + private static Object getByteOrder(java.nio.ByteBuffer byteBuffer) { return java.nio.ByteOrder.LITTLE_ENDIAN.equals(byteBuffer.order()) ? AVKey.LITTLE_ENDIAN : AVKey.BIG_ENDIAN; } - protected String validate(AVList worldFileParams, Object dataSource) - { + protected String validate(AVList worldFileParams, Object dataSource) { StringBuilder sb = new StringBuilder(); Object o = worldFileParams.getValue(WorldFile.WORLD_FILE_IMAGE_SIZE); - if (o == null || !(o instanceof int[])) + if (o == null || !(o instanceof int[])) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("WorldFile.NoSizeSpecified", dataSource)); + } o = worldFileParams.getValue(AVKey.SECTOR); - if (o == null || !(o instanceof Sector)) + if (o == null || !(o instanceof Sector)) { sb.append(sb.length() > 0 ? ", " : "").append( - Logging.getMessage("WorldFile.NoSectorSpecified", dataSource)); + Logging.getMessage("WorldFile.NoSectorSpecified", dataSource)); + } o = worldFileParams.getValue(AVKey.BYTE_ORDER); - if (o == null || !(o instanceof String)) + if (o == null || !(o instanceof String)) { sb.append(sb.length() > 0 ? ", " : "").append( - Logging.getMessage("WorldFile.NoByteOrderSpecified", dataSource)); + Logging.getMessage("WorldFile.NoByteOrderSpecified", dataSource)); + } o = worldFileParams.getValue(AVKey.PIXEL_FORMAT); - if (o == null) + if (o == null) { sb.append(sb.length() > 0 ? ", " : "").append( - Logging.getMessage("WorldFile.NoPixelFormatSpecified", dataSource)); - else if (!AVKey.ELEVATION.equals(o)) + Logging.getMessage("WorldFile.NoPixelFormatSpecified", dataSource)); + } else if (!AVKey.ELEVATION.equals(o)) { sb.append(sb.length() > 0 ? ", " : "").append( - Logging.getMessage("WorldFile.InvalidPixelFormat", dataSource)); + Logging.getMessage("WorldFile.InvalidPixelFormat", dataSource)); + } o = worldFileParams.getValue(AVKey.DATA_TYPE); - if (o == null) + if (o == null) { sb.append(sb.length() > 0 ? ", " : "").append( - Logging.getMessage("WorldFile.NoDataTypeSpecified", dataSource)); + Logging.getMessage("WorldFile.NoDataTypeSpecified", dataSource)); + } - if (sb.length() == 0) + if (sb.length() == 0) { return null; + } return sb.toString(); } diff --git a/src/gov/nasa/worldwind/data/BasicDataRasterReaderFactory.java b/src/gov/nasa/worldwind/data/BasicDataRasterReaderFactory.java index 01857a1c2a..5dae2ee5e3 100644 --- a/src/gov/nasa/worldwind/data/BasicDataRasterReaderFactory.java +++ b/src/gov/nasa/worldwind/data/BasicDataRasterReaderFactory.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.avlist.AVList; @@ -19,7 +18,7 @@ * {@link gov.nasa.worldwind.data.GeotiffRasterReader} * {@link gov.nasa.worldwind.data.BILRasterReader} * {@link gov.nasa.worldwind.data.ImageIORasterReader} - + * * *

    * To specify a different factory, set the {@link gov.nasa.worldwind.avlist.AVKey#DATA_RASTER_READER_FACTORY_CLASS_NAME} @@ -30,31 +29,32 @@ * @author tag * @version $Id: BasicDataRasterReaderFactory.java 1511 2013-07-17 17:34:00Z dcollins $ */ -public class BasicDataRasterReaderFactory implements DataRasterReaderFactory -{ - /** The default list of readers. */ - protected DataRasterReader[] readers = new DataRasterReader[] - { - // NOTE: Update the javadoc above if this list changes. - new RPFRasterReader(), - new DTEDRasterReader(), - new GDALDataRasterReader(), - new GeotiffRasterReader(), - new BILRasterReader(), - new ImageIORasterReader(), - }; +public class BasicDataRasterReaderFactory implements DataRasterReaderFactory { + + /** + * The default list of readers. + */ + protected DataRasterReader[] readers = new DataRasterReader[]{ + // NOTE: Update the javadoc above if this list changes. + new RPFRasterReader(), + new DTEDRasterReader(), + new GDALDataRasterReader(), + new GeotiffRasterReader(), + new BILRasterReader(), + new ImageIORasterReader(),}; - /** {@inheritDoc} */ - public DataRasterReader[] getReaders() - { + /** + * {@inheritDoc} + */ + public DataRasterReader[] getReaders() { return readers; } - /** {@inheritDoc} */ - public DataRasterReader findReaderFor(Object source, AVList params) - { - if (source == null) - { + /** + * {@inheritDoc} + */ + public DataRasterReader findReaderFor(Object source, AVList params) { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -63,27 +63,26 @@ public DataRasterReader findReaderFor(Object source, AVList params) return findReaderFor(source, params, readers); } - /** {@inheritDoc} */ - public DataRasterReader findReaderFor(Object source, AVList params, DataRasterReader[] readers) - { - if (source == null) - { + /** + * {@inheritDoc} + */ + public DataRasterReader findReaderFor(Object source, AVList params, DataRasterReader[] readers) { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (readers == null) - { + if (readers == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (DataRasterReader reader : readers) - { - if (reader != null && reader.canRead(source, params)) + for (DataRasterReader reader : readers) { + if (reader != null && reader.canRead(source, params)) { return reader; + } } return null; diff --git a/src/gov/nasa/worldwind/data/BasicRasterServer.java b/src/gov/nasa/worldwind/data/BasicRasterServer.java index 38e3c18c91..8c1e6fa0eb 100644 --- a/src/gov/nasa/worldwind/data/BasicRasterServer.java +++ b/src/gov/nasa/worldwind/data/BasicRasterServer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.*; @@ -25,13 +24,12 @@ * @author Lado Garakanidze * @version $Id: BasicRasterServer.java 2813 2015-02-18 23:35:24Z tgaskins $ */ - /** * BasicRasterServer maintains a list of data sources and their properties in the BasicRasterServerCache and is used to * compose (mosaic) a data raster of the given region of interest from data sources. */ -public class BasicRasterServer extends WWObjectImpl implements RasterServer -{ +public class BasicRasterServer extends WWObjectImpl implements RasterServer { + protected java.util.List dataRasterList = new java.util.ArrayList(); protected DataRasterReaderFactory readerFactory; @@ -43,38 +41,33 @@ public class BasicRasterServer extends WWObjectImpl implements RasterServer * accompanies layer description XML file), reads sector of each source and maintains a list of data sources, their * properties, * - * @param o the RasterServer.xml source to read. May by a {@link java.io.File}, a file path, a URL or an - * {@link org.w3c.dom.Element} + * @param o the RasterServer.xml source to read. May by a {@link java.io.File}, a file path, a URL or an + * {@link org.w3c.dom.Element} * @param params optional metadata associated with the data source that might be useful to the BasicRasterServer. */ - public BasicRasterServer(Object o, AVList params) - { + public BasicRasterServer(Object o, AVList params) { super(); - if (null != params) - { + if (null != params) { this.setValues(params); } - try - { + try { this.readerFactory = (DataRasterReaderFactory) WorldWind.createConfigurationComponent( - AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); - } - catch (Exception e) - { + AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); + } catch (Exception e) { this.readerFactory = new BasicDataRasterReaderFactory(); } this.init(o); } - /** Returns an instance of the MemoryCache that contains DataRasters and their properties + /** + * Returns an instance of the MemoryCache that contains DataRasters and their properties * - * @return an instance of the MemoryCache that contains DataRasters and their properties + * @return an instance of the MemoryCache that contains DataRasters and their properties */ - public MemoryCache getCache() - { + public MemoryCache getCache() { return cache; } @@ -83,15 +76,12 @@ public MemoryCache getCache() * * @return true, if the DataRaster list is not empty */ - public boolean hasDataRasters() - { + public boolean hasDataRasters() { return (this.dataRasterList.size() > 0); } - protected void init(Object o) - { - if (null == o) - { + protected void init(Object o) { + if (null == o) { String message = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -111,14 +101,10 @@ protected void init(Object o) // Logging.logger().severe(message); // throw new IllegalArgumentException(message); // } - RasterServerConfiguration config = new RasterServerConfiguration(o); - try - { + try { config.parse(); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { String message = Logging.getMessage("generic.InvalidDataSource", ""); message += "\n" + e.getMessage(); Logging.logger().severe(message); @@ -127,24 +113,20 @@ protected void init(Object o) this.extractProperties(config); - if( this.readRasterSources(config) ) - { + if (this.readRasterSources(config)) { // success, all raster sources are available - String message = Logging.getMessage("generic.DataSetAvailable", this.getDataSetName() ); + String message = Logging.getMessage("generic.DataSetAvailable", this.getDataSetName()); Logging.logger().finest(message); - } - else - { + } else { // some (or all) required source rasters are not available (either missing or unreadable) // and therefore the dataset may not generate high resolution on-the-fly - String message = Logging.getMessage("generic.DataSetLimitedAvailability", this.getDataSetName() ); + String message = Logging.getMessage("generic.DataSetLimitedAvailability", this.getDataSetName()); Logging.logger().severe(message); } } - protected String getDataSetName() - { - return AVListImpl.getStringValue( this, AVKey.DATASET_NAME, "" ); + protected String getDataSetName() { + return AVListImpl.getStringValue(this, AVKey.DATASET_NAME, ""); } /** @@ -152,13 +134,11 @@ protected String getDataSetName() * * @return DataSet's pixel format (AVKey.IMAGE or AVKey.ELEVATION), or empty string if not set */ - protected String getDataSetPixelFormat() - { - return AVListImpl.getStringValue( this, AVKey.PIXEL_FORMAT, "" ); + protected String getDataSetPixelFormat() { + return AVListImpl.getStringValue(this, AVKey.PIXEL_FORMAT, ""); } - protected void setDataSetPixelFormat(String pixelFormat) - { + protected void setDataSetPixelFormat(String pixelFormat) { this.setValue(AVKey.PIXEL_FORMAT, pixelFormat); } @@ -167,13 +147,12 @@ protected void setDataSetPixelFormat(String pixelFormat) * * @param config Parsed configuration document. */ - protected void extractProperties(RasterServerConfiguration config) - { - for (Map.Entry prop : config.getProperties().entrySet()) - { + protected void extractProperties(RasterServerConfiguration config) { + for (Map.Entry prop : config.getProperties().entrySet()) { this.setValue(prop.getKey(), prop.getValue()); } } + /** * Reads XML document and extracts raster sources * @@ -182,8 +161,7 @@ protected void extractProperties(RasterServerConfiguration config) * @return TRUE, if all raster sources are available, FALSE otherwise * */ - protected boolean readRasterSources(RasterServerConfiguration config) - { + protected boolean readRasterSources(RasterServerConfiguration config) { long startTime = System.currentTimeMillis(); boolean hasUnavailableRasterSources = false; @@ -191,23 +169,19 @@ protected boolean readRasterSources(RasterServerConfiguration config) int numSources = 0; Sector extent = null; - try - { + try { List sources = config.getSources(); - if (sources == null || sources.size() == 0) - { + if (sources == null || sources.size() == 0) { return false; } numSources = sources.size(); for (RasterServerConfiguration.Source source : sources) { Thread.yield(); - try - { + try { String rasterSourcePath = source.getPath(); - if (WWUtil.isEmpty(rasterSourcePath)) - { + if (WWUtil.isEmpty(rasterSourcePath)) { continue; } @@ -216,120 +190,95 @@ protected boolean readRasterSources(RasterServerConfiguration config) // normalize rasterSourcePath = rasterSourceFile.getAbsolutePath(); - if( !rasterSourceFile.exists() ) - { + if (!rasterSourceFile.exists()) { hasUnavailableRasterSources = true; - String reason = Logging.getMessage("generic.FileDoesNotExists", rasterSourcePath ); + String reason = Logging.getMessage("generic.FileDoesNotExists", rasterSourcePath); Logging.logger().warning(reason); continue; } - if( !rasterSourceFile.canRead() ) - { + if (!rasterSourceFile.canRead()) { hasUnavailableRasterSources = true; - String reason = Logging.getMessage("generic.FileNoReadPermission", rasterSourcePath ); + String reason = Logging.getMessage("generic.FileNoReadPermission", rasterSourcePath); Logging.logger().warning(reason); continue; } DataRasterReader rasterReader = this.findDataRasterReader(rasterSourceFile, rasterMetadata); - if (null == rasterReader) - { + if (null == rasterReader) { hasUnavailableRasterSources = true; String reason = Logging.getMessage("generic.UnknownFileFormatOrMatchingReaderNotFound", - rasterSourcePath ); + rasterSourcePath); Logging.logger().warning(reason); continue; } Sector sector = source.getSector(); - if (null == sector) - { + if (null == sector) { rasterReader.readMetadata(rasterSourceFile, rasterMetadata); Object o = rasterMetadata.getValue(AVKey.SECTOR); sector = (o instanceof Sector) ? (Sector) o : null; - } - else - { + } else { rasterMetadata.setValue(AVKey.SECTOR, sector); } Object rasterPixelFormat = rasterMetadata.getValue(AVKey.PIXEL_FORMAT); String datasetPixelFormat = this.getDataSetPixelFormat(); - if( !WWUtil.isEmpty(datasetPixelFormat) ) - { + if (!WWUtil.isEmpty(datasetPixelFormat)) { // verify all data rasters are the same type - we do not allow to mix elevations and imagery - if (!datasetPixelFormat.equals(rasterPixelFormat)) - { + if (!datasetPixelFormat.equals(rasterPixelFormat)) { hasUnavailableRasterSources = true; - String reason = Logging.getMessage("generic.UnexpectedRasterType", rasterSourcePath ); + String reason = Logging.getMessage("generic.UnexpectedRasterType", rasterSourcePath); Logging.logger().warning(reason); continue; } - } - else - { - if( AVKey.IMAGE.equals(rasterPixelFormat) || AVKey.ELEVATION.equals(rasterPixelFormat) ) - { - this.setDataSetPixelFormat( (String)rasterPixelFormat ); - } - else - { + } else { + if (AVKey.IMAGE.equals(rasterPixelFormat) || AVKey.ELEVATION.equals(rasterPixelFormat)) { + this.setDataSetPixelFormat((String) rasterPixelFormat); + } else { hasUnavailableRasterSources = true; - String reason = Logging.getMessage("generic.UnknownFileFormat", rasterSourcePath ); + String reason = Logging.getMessage("generic.UnknownFileFormat", rasterSourcePath); Logging.logger().warning(reason); continue; } } - if (null != sector) - { + if (null != sector) { extent = Sector.union(extent, sector); this.dataRasterList.add( - new CachedDataRaster(rasterSourceFile, rasterMetadata, rasterReader, this.getCache()) + new CachedDataRaster(rasterSourceFile, rasterMetadata, rasterReader, this.getCache()) ); - } - else - { + } else { hasUnavailableRasterSources = true; - String reason = Logging.getMessage("generic.NoSectorSpecified", rasterSourcePath ); + String reason = Logging.getMessage("generic.NoSectorSpecified", rasterSourcePath); Logging.logger().warning(reason); } - } - catch (Throwable t) - { + } catch (Throwable t) { String message = t.getMessage(); message = (WWUtil.isEmpty(message)) ? t.getCause().getMessage() : message; Logging.logger().log(java.util.logging.Level.WARNING, message, t); } } - if (null != extent && extent.getDeltaLatDegrees() > 0d && extent.getDeltaLonDegrees() > 0d) - { + if (null != extent && extent.getDeltaLatDegrees() > 0d && extent.getDeltaLonDegrees() > 0d) { this.setValue(AVKey.SECTOR, extent); } - } - catch (Throwable t) - { + } catch (Throwable t) { String message = t.getMessage(); message = (WWUtil.isEmpty(message)) ? t.getCause().getMessage() : message; Logging.logger().log(java.util.logging.Level.SEVERE, message, t); - } - finally - { + } finally { Logging.logger().finest(this.getStringValue(AVKey.DISPLAY_NAME) + ": " + numSources - + " files in " + (System.currentTimeMillis() - startTime) + " milli-seconds"); + + " files in " + (System.currentTimeMillis() - startTime) + " milli-seconds"); } return !hasUnavailableRasterSources; } - protected DataRasterReader findDataRasterReader(Object source, AVList params) - { - if (source == null) - { + protected DataRasterReader findDataRasterReader(Object source, AVList params) { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -338,19 +287,14 @@ protected DataRasterReader findDataRasterReader(Object source, AVList params) params = (null == params) ? new AVListImpl() : params; DataRasterReader reader = this.readerFactory.findReaderFor(source, params); - if (reader == null) - { + if (reader == null) { return null; } - if (!params.hasKey(AVKey.PIXEL_FORMAT)) - { - try - { + if (!params.hasKey(AVKey.PIXEL_FORMAT)) { + try { reader.readMetadata(source, params); - } - catch (Exception e) - { + } catch (Exception e) { // Reading the input source's metadata caused an exception. This exception does not prevent us from // determining if the source represents elevation data, but we want to make a note of it. Therefore we // log the exception with level FINE. @@ -362,8 +306,7 @@ protected DataRasterReader findDataRasterReader(Object source, AVList params) return reader; } - public Sector getSector() - { + public Sector getSector() { return (this.hasKey(AVKey.SECTOR)) ? (Sector) this.getValue(AVKey.SECTOR) : null; } @@ -371,44 +314,38 @@ public Sector getSector() * Composes a DataRaster of the given width and height for the specific geographic region of interest (ROI). * * @param reqParams This is a required parameter, must not be null or empty; Must contain AVKey.WIDTH, AVKey.HEIGHT, - * and AVKey.SECTOR values. - *

    - * Optional keys are: AVKey.PIXEL_FORMAT (AVKey.ELEVATION | AVKey.IMAGE) AVKey.DATA_TYPE - * AVKey.BYTE_ORDER (AVKey.BIG_ENDIAN | AVKey.LITTLE_ENDIAN ) + * and AVKey.SECTOR values. + *

    + * Optional keys are: AVKey.PIXEL_FORMAT (AVKey.ELEVATION | AVKey.IMAGE) AVKey.DATA_TYPE AVKey.BYTE_ORDER + * (AVKey.BIG_ENDIAN | AVKey.LITTLE_ENDIAN ) * * @return a DataRaster for the requested ROI * - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if there is no intersection of the source rasters with the requested ROI or the - * source format is unknown or not supported by currently loaded drivers + * @throws gov.nasa.worldwind.exception.WWRuntimeException if there is no intersection of the source rasters with + * the requested ROI or the source format is unknown or not supported by currently loaded drivers * @throws IllegalArgumentException if any of the required parameters or values are missing */ - public DataRaster composeRaster(AVList reqParams) throws IllegalArgumentException, WWRuntimeException - { + public DataRaster composeRaster(AVList reqParams) throws IllegalArgumentException, WWRuntimeException { DataRaster reqRaster; - if (null == reqParams) - { + if (null == reqParams) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!reqParams.hasKey(AVKey.WIDTH)) - { + if (!reqParams.hasKey(AVKey.WIDTH)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.WIDTH); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!reqParams.hasKey(AVKey.HEIGHT)) - { + if (!reqParams.hasKey(AVKey.HEIGHT)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.HEIGHT); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = reqParams.getValue(AVKey.SECTOR); - if (null == o || !(o instanceof Sector)) - { + if (null == o || !(o instanceof Sector)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -416,55 +353,44 @@ public DataRaster composeRaster(AVList reqParams) throws IllegalArgumentExceptio Sector reqSector = (Sector) o; Sector rasterExtent = this.getSector(); - if (!reqSector.intersects(rasterExtent)) - { + if (!reqSector.intersects(rasterExtent)) { String message = Logging.getMessage("generic.SectorRequestedOutsideCoverageArea", reqSector, rasterExtent); Logging.logger().finest(message); throw new WWRuntimeException(message); } - try - { + try { int reqWidth = (Integer) reqParams.getValue(AVKey.WIDTH); int reqHeight = (Integer) reqParams.getValue(AVKey.HEIGHT); - if (!reqParams.hasKey(AVKey.BYTE_ORDER)) - { + if (!reqParams.hasKey(AVKey.BYTE_ORDER)) { reqParams.setValue(AVKey.BYTE_ORDER, AVKey.BIG_ENDIAN); } // check if this Raster Server serves elevations or imagery - if (AVKey.ELEVATION.equals(this.getStringValue(AVKey.PIXEL_FORMAT))) - { + if (AVKey.ELEVATION.equals(this.getStringValue(AVKey.PIXEL_FORMAT))) { reqParams.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); - if (!reqParams.hasKey(AVKey.DATA_TYPE)) - { + if (!reqParams.hasKey(AVKey.DATA_TYPE)) { reqParams.setValue(AVKey.DATA_TYPE, AVKey.INT16); } reqRaster = new ByteBufferRaster(reqWidth, reqHeight, reqSector, reqParams); - } - else if (AVKey.IMAGE.equals(this.getStringValue(AVKey.PIXEL_FORMAT))) - { + } else if (AVKey.IMAGE.equals(this.getStringValue(AVKey.PIXEL_FORMAT))) { reqParams.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); reqRaster = new BufferedImageRaster(reqWidth, reqHeight, Transparency.TRANSLUCENT, reqSector); - } - else - { + } else { String msg = Logging.getMessage("generic.UnrecognizedSourceType", this.getValue(AVKey.PIXEL_FORMAT)); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } int numIntersectedRasters = 0; - for (DataRaster raster : this.dataRasterList) - { + for (DataRaster raster : this.dataRasterList) { Sector rasterSector = raster.getSector(); Sector overlap = reqSector.intersection(rasterSector); // SKIP, if not intersection, or intersects only on edges - if (null == overlap || overlap.getDeltaLatDegrees() == 0d || overlap.getDeltaLonDegrees() == 0d) - { + if (null == overlap || overlap.getDeltaLatDegrees() == 0d || overlap.getDeltaLonDegrees() == 0d) { continue; } @@ -472,19 +398,14 @@ else if (AVKey.IMAGE.equals(this.getStringValue(AVKey.PIXEL_FORMAT))) numIntersectedRasters++; } - if (numIntersectedRasters == 0) - { + if (numIntersectedRasters == 0) { String message = Logging.getMessage("generic.SectorRequestedOutsideCoverageArea", reqSector, ""); Logging.logger().finest(message); throw new WWRuntimeException(message); } - } - catch (WWRuntimeException wwe) - { + } catch (WWRuntimeException wwe) { throw wwe; - } - catch (Throwable t) - { + } catch (Throwable t) { String message = t.getMessage(); message = (WWUtil.isEmpty(message)) ? t.getCause().getMessage() : message; Logging.logger().log(java.util.logging.Level.FINE, message, t); @@ -499,81 +420,61 @@ else if (AVKey.IMAGE.equals(this.getStringValue(AVKey.PIXEL_FORMAT))) * requested file format (AVKey.IMAGE_FORMAT) and returns as a ByteBuffer * * @param params This is a required parameter, must not be null or empty; Must contain AVKey.WIDTH, AVKey.HEIGHT, - * AVKey.SECTOR, and AVKey.IMAGE_FORMAT (mime type) values. Supported mime types are: "image/png", - * "image/jpeg", "image/dds". - *

    - * Optional keys are: AVKey.PIXEL_FORMAT (AVKey.ELEVATION | AVKey.IMAGE) AVKey.DATA_TYPE - * AVKey.BYTE_ORDER (AVKey.BIG_ENDIAN | AVKey.LITTLE_ENDIAN ) + * AVKey.SECTOR, and AVKey.IMAGE_FORMAT (mime type) values. Supported mime types are: "image/png", "image/jpeg", + * "image/dds". + *

    + * Optional keys are: AVKey.PIXEL_FORMAT (AVKey.ELEVATION | AVKey.IMAGE) AVKey.DATA_TYPE AVKey.BYTE_ORDER + * (AVKey.BIG_ENDIAN | AVKey.LITTLE_ENDIAN ) * * @return a DataRaster for the requested ROI * - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if there is no intersection of the source rasters with the requested ROI or the - * source format is unknown or not supported by currently loaded drivers + * @throws gov.nasa.worldwind.exception.WWRuntimeException if there is no intersection of the source rasters with + * the requested ROI or the source format is unknown or not supported by currently loaded drivers * @throws IllegalArgumentException if any of the required parameters or values are missing */ - public ByteBuffer getRasterAsByteBuffer(AVList params) - { + public ByteBuffer getRasterAsByteBuffer(AVList params) { // request may contain a specific file format, different from a default file format String format = (null != params && params.hasKey(AVKey.IMAGE_FORMAT)) - ? params.getStringValue(AVKey.IMAGE_FORMAT) : this.getStringValue(AVKey.IMAGE_FORMAT); - if (WWUtil.isEmpty(format)) - { + ? params.getStringValue(AVKey.IMAGE_FORMAT) : this.getStringValue(AVKey.IMAGE_FORMAT); + if (WWUtil.isEmpty(format)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.IMAGE_FORMAT); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (this.dataRasterList.isEmpty()) - { + if (this.dataRasterList.isEmpty()) { String message = Logging.getMessage("generic.NoImagesAvailable"); Logging.logger().finest(message); throw new WWRuntimeException(message); } - try - { + try { DataRaster raster = this.composeRaster(params); - if (raster instanceof BufferedImageRaster) - { - if ("image/png".equalsIgnoreCase(format)) - { + if (raster instanceof BufferedImageRaster) { + if ("image/png".equalsIgnoreCase(format)) { return ImageUtil.asPNG(raster); - } - else if ("image/jpeg".equalsIgnoreCase(format) || "image/jpg".equalsIgnoreCase(format)) - { + } else if ("image/jpeg".equalsIgnoreCase(format) || "image/jpg".equalsIgnoreCase(format)) { return ImageUtil.asJPEG(raster); } - if ("image/dds".equalsIgnoreCase(format)) - { + if ("image/dds".equalsIgnoreCase(format)) { return DDSCompressor.compressImage(((BufferedImageRaster) raster).getBufferedImage()); - } - else - { + } else { String msg = Logging.getMessage("generic.UnknownFileFormat", format); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } - } - else if (raster instanceof ByteBufferRaster) - { + } else if (raster instanceof ByteBufferRaster) { // Elevations as BIL16 or as BIL32 are stored in the simple ByteBuffer object return ((ByteBufferRaster) raster).getByteBuffer(); - } - else - { + } else { String msg = Logging.getMessage("generic.UnexpectedRasterType", raster.getClass().getName()); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } - } - catch (WWRuntimeException wwe) - { + } catch (WWRuntimeException wwe) { Logging.logger().finest(wwe.getMessage()); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = t.getMessage(); message = (WWUtil.isEmpty(message)) ? t.getCause().getMessage() : message; Logging.logger().log(java.util.logging.Level.SEVERE, message, t); @@ -582,4 +483,3 @@ else if (raster instanceof ByteBufferRaster) return null; } } - diff --git a/src/gov/nasa/worldwind/data/BufferWrapperRaster.java b/src/gov/nasa/worldwind/data/BufferWrapperRaster.java index 9eba4a842e..d38977406b 100644 --- a/src/gov/nasa/worldwind/data/BufferWrapperRaster.java +++ b/src/gov/nasa/worldwind/data/BufferWrapperRaster.java @@ -15,24 +15,21 @@ * @author dcollins * @version $Id: BufferWrapperRaster.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BufferWrapperRaster extends AbstractDataRaster implements Cacheable, Disposable -{ +public class BufferWrapperRaster extends AbstractDataRaster implements Cacheable, Disposable { + protected BufferWrapper buffer; - public BufferWrapperRaster(int width, int height, Sector sector, BufferWrapper buffer, AVList list) - { + public BufferWrapperRaster(int width, int height, Sector sector, BufferWrapper buffer, AVList list) { super(width, height, sector, list); - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int expectedValues = width * height; - if (buffer.length() < expectedValues) - { + if (buffer.length() < expectedValues) { String message = Logging.getMessage("generic.BufferSize", "buffer.length() < " + expectedValues); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -41,29 +38,23 @@ public BufferWrapperRaster(int width, int height, Sector sector, BufferWrapper b this.buffer = buffer; } - public BufferWrapperRaster(int width, int height, Sector sector, BufferWrapper buffer) - { + public BufferWrapperRaster(int width, int height, Sector sector, BufferWrapper buffer) { this(width, height, sector, buffer, null); } - public BufferWrapper getBuffer() - { + public BufferWrapper getBuffer() { return this.buffer; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return this.buffer.getSizeInBytes(); } - public void dispose() - { + public void dispose() { } - public double getDoubleAtPosition(int row, int col) - { - if ((row < 0) || (col < 0) || (row > (this.getHeight() - 1)) || (col > (this.getWidth() - 1))) - { + public double getDoubleAtPosition(int row, int col) { + if ((row < 0) || (col < 0) || (row > (this.getHeight() - 1)) || (col > (this.getWidth() - 1))) { String message = Logging.getMessage("generic.ArgumentOutOfRange", String.format("%d, %d", row, col)); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -72,10 +63,8 @@ public double getDoubleAtPosition(int row, int col) return this.getBuffer().getDouble(indexFor(col, row)); } - public void setDoubleAtPosition(int row, int col, double value) - { - if ((row < 0) || (col < 0) || (row > (this.getHeight() - 1)) || (col > (this.getWidth() - 1))) - { + public void setDoubleAtPosition(int row, int col, double value) { + if ((row < 0) || (col < 0) || (row > (this.getHeight() - 1)) || (col > (this.getWidth() - 1))) { String message = Logging.getMessage("generic.ArgumentOutOfRange", String.format("%d, %d", row, col)); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -84,19 +73,17 @@ public void setDoubleAtPosition(int row, int col, double value) this.getBuffer().putDouble(indexFor(col, row), value); } - public double getTransparentValue() - { - if (this.hasKey(AVKey.MISSING_DATA_SIGNAL)) - { + public double getTransparentValue() { + if (this.hasKey(AVKey.MISSING_DATA_SIGNAL)) { Object o = this.getValue(AVKey.MISSING_DATA_SIGNAL); - if (null != o && o instanceof Double) + if (null != o && o instanceof Double) { return (Double) o; + } } return Double.MAX_VALUE; } - public void setTransparentValue(double transparentValue) - { + public void setTransparentValue(double transparentValue) { this.setValue(AVKey.MISSING_DATA_SIGNAL, transparentValue); } @@ -106,10 +93,9 @@ public void setTransparentValue(double transparentValue) * missing-data. * * @return a two-element array containing this raster's extreme values, or null if none exist. Entry 0 contains the - * minimum value; entry 1 contains the maximum value. + * minimum value; entry 1 contains the maximum value. */ - public double[] getExtremes() - { + public double[] getExtremes() { // Create local variables to store the raster's dimensions and missing data signal to eliminate any overhead in // the loops below. int width = this.getWidth(); @@ -122,22 +108,25 @@ public double[] getExtremes() // Allocate a buffer to hold the extreme values. double[] extremes = null; - for (int j = 0; j < height; j++) - { + for (int j = 0; j < height; j++) { this.get(0, j, width, buffer, 0); // Get the row starting at (0, j). - for (int i = 0; i < width; i++) - { + for (int i = 0; i < width; i++) { if (buffer[i] == missingDataSignal) // Ignore values marked as missing-data. + { continue; + } - if (extremes == null) + if (extremes == null) { extremes = WWUtil.defaultMinMix(); + } - if (extremes[0] > buffer[i]) + if (extremes[0] > buffer[i]) { extremes[0] = buffer[i]; - if (extremes[1] < buffer[i]) + } + if (extremes[1] < buffer[i]) { extremes[1] = buffer[i]; + } } } @@ -145,31 +134,26 @@ public double[] getExtremes() return extremes; } - public void fill(double value) - { + public void fill(double value) { int width = this.getWidth(); int height = this.getHeight(); double[] samples = new double[width]; java.util.Arrays.fill(samples, value); // Fill each row of this raster with the clear color. - for (int j = 0; j < height; j++) - { + for (int j = 0; j < height; j++) { this.put(0, j, samples, 0, width); } } - public void drawOnTo(DataRaster canvas) - { - if (canvas == null) - { + public void drawOnTo(DataRaster canvas) { + if (canvas == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!(canvas instanceof BufferWrapperRaster)) - { + if (!(canvas instanceof BufferWrapperRaster)) { String message = Logging.getMessage("DataRaster.IncompatibleRaster", canvas); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -179,8 +163,7 @@ public void drawOnTo(DataRaster canvas) } @Override - DataRaster doGetSubRaster(int width, int height, Sector sector, AVList params) - { + DataRaster doGetSubRaster(int width, int height, Sector sector, AVList params) { DataRaster canvas = this.createSubRaster(width, height, sector, params); this.drawOnTo(canvas); return canvas; @@ -194,23 +177,22 @@ DataRaster doGetSubRaster(int width, int height, Sector sector, AVList params) * This returns a {@link gov.nasa.worldwind.util.BufferWrapper.ByteBufferWrapper}, a subclass of * BufferWrapperRaster backed by a ByteBuffer. * - * @param width the width of the sub-raster, in pixels. + * @param width the width of the sub-raster, in pixels. * @param height the height of the sub-raster, in pixels. * @param sector the sector the sub-raster occupies. * @param params the parameters associated with the sub-raster. * * @return a new sub-raster initialized with the specified width, height, - * sector and params. + * sector and params. */ - protected BufferWrapperRaster createSubRaster(int width, int height, Sector sector, AVList params) - { + protected BufferWrapperRaster createSubRaster(int width, int height, Sector sector, AVList params) { return new ByteBufferRaster(width, height, sector, params); } - protected void doDrawOnTo(BufferWrapperRaster canvas) - { - if (!this.getSector().intersects(canvas.getSector())) + protected void doDrawOnTo(BufferWrapperRaster canvas) { + if (!this.getSector().intersects(canvas.getSector())) { return; + } int thisWidth = this.getWidth(); int thisHeight = this.getHeight(); @@ -220,8 +202,8 @@ protected void doDrawOnTo(BufferWrapperRaster canvas) // Compute the transform from the canvas' coordinate system to this raster's coordinate system. java.awt.geom.AffineTransform canvasToThis = this.computeSourceToDestTransform( - canvasWidth, canvasHeight, canvas.getSector(), - thisWidth, thisHeight, this.getSector()); + canvasWidth, canvasHeight, canvas.getSector(), + thisWidth, thisHeight, this.getSector()); /// Compute the region of the destination raster to be be clipped by the specified clipping sector. If no // clipping sector is specified, then perform no clipping. We compute the clip region for the destination @@ -235,15 +217,16 @@ protected void doDrawOnTo(BufferWrapperRaster canvas) // Precompute the interpolation values for each transformed x- and y-coordinate. InterpolantLookupTable lut = this.createLookupTable( - canvasWidth, canvasHeight, // lookup table dimensions - 0, thisWidth - 1, 0, thisHeight - 1, // lookup table xMin, xMax, yMin, yMax - canvasToThis); // lookup transform + canvasWidth, canvasHeight, // lookup table dimensions + 0, thisWidth - 1, 0, thisHeight - 1, // lookup table xMin, xMax, yMin, yMax + canvasToThis); // lookup transform // If the lookup table is null, then no values in the canvas fall within this raster's bounds. This means // either the two rasters do not intersect or that this raster fits entirely between two x-coordinates or two // y-coordinates (or both) in the canvas. In either case, we do not rasterize any contribution from this raster // into the canvas, and simply exit. - if (lut == null) + if (lut == null) { return; + } // Allocate space to hold the lookup table parameters. double[] xParams = new double[3]; @@ -263,11 +246,9 @@ protected void doDrawOnTo(BufferWrapperRaster canvas) double xf, yf; // Iterate over each canvas row, filling canvas pixels with samples from this raster. - for (int j = clipRect.y; j <= (clipRect.y + clipRect.height); j++) - { + for (int j = clipRect.y; j <= (clipRect.y + clipRect.height); j++) { // If the interpolant lookup table has an entry for "j", then process this row. - if (lut.getInterpolantY(j, yParams)) - { + if (lut.getInterpolantY(j, yParams)) { y1 = (int) yParams[0]; y2 = (int) yParams[1]; yf = yParams[2]; @@ -278,11 +259,9 @@ protected void doDrawOnTo(BufferWrapperRaster canvas) canvas.get(0, j, canvasWidth, canvasSamples, 0); // Iterate over each canvas column, sampling canvas pixels. - for (int i = clipRect.x; i <= (clipRect.x + clipRect.width); i++) - { + for (int i = clipRect.x; i <= (clipRect.x + clipRect.width); i++) { // If the interpolant lookup table has an entry for "i", then process this column. - if (lut.getInterpolantX(i, xParams)) - { + if (lut.getInterpolantX(i, xParams)) { x1 = (int) xParams[0] - xParamMin; x2 = (int) xParams[1] - xParamMin; xf = xParams[2]; @@ -298,41 +277,37 @@ protected void doDrawOnTo(BufferWrapperRaster canvas) } } - protected void get(int x, int y, int length, double[] buffer, int pos) - { + protected void get(int x, int y, int length, double[] buffer, int pos) { int index = this.indexFor(x, y); this.getBuffer().getDouble(index, buffer, pos, length); } - protected void put(int x, int y, double[] buffer, int pos, int length) - { + protected void put(int x, int y, double[] buffer, int pos, int length) { int index = this.indexFor(x, y); this.getBuffer().putDouble(index, buffer, pos, length); } - protected final int indexFor(int x, int y) - { + protected final int indexFor(int x, int y) { // Map raster coordinates to buffer coordinates. return x + y * this.getWidth(); } @Override protected java.awt.geom.AffineTransform computeSourceToDestTransform( - int sourceWidth, int sourceHeight, Sector sourceSector, - int destWidth, int destHeight, Sector destSector) - { + int sourceWidth, int sourceHeight, Sector sourceSector, + int destWidth, int destHeight, Sector destSector) { // Compute the the transform from source to destination coordinates. In this computation a pixel is assumed // to have no dimension. We measure the distance between pixels rather than some pixel dimension. double ty = (destHeight - 1) * -(sourceSector.getMaxLatitude().degrees - destSector.getMaxLatitude().degrees) - / destSector.getDeltaLatDegrees(); + / destSector.getDeltaLatDegrees(); double tx = (destWidth - 1) * (sourceSector.getMinLongitude().degrees - destSector.getMinLongitude().degrees) - / destSector.getDeltaLonDegrees(); + / destSector.getDeltaLonDegrees(); double sy = ((double) (destHeight - 1) / (double) (sourceHeight - 1)) - * (sourceSector.getDeltaLatDegrees() / destSector.getDeltaLatDegrees()); + * (sourceSector.getDeltaLatDegrees() / destSector.getDeltaLatDegrees()); double sx = ((double) (destWidth - 1) / (double) (sourceWidth - 1)) - * (sourceSector.getDeltaLonDegrees() / destSector.getDeltaLonDegrees()); + * (sourceSector.getDeltaLonDegrees() / destSector.getDeltaLonDegrees()); java.awt.geom.AffineTransform transform = new java.awt.geom.AffineTransform(); transform.translate(tx, ty); @@ -341,8 +316,7 @@ protected java.awt.geom.AffineTransform computeSourceToDestTransform( } @Override - protected java.awt.geom.AffineTransform computeGeographicToRasterTransform(int width, int height, Sector sector) - { + protected java.awt.geom.AffineTransform computeGeographicToRasterTransform(int width, int height, Sector sector) { // Compute the the transform from geographic to raster coordinates. In this computation a pixel is assumed // to have no dimension. We measure the distance between pixels rather than some pixel dimension. @@ -359,8 +333,7 @@ protected java.awt.geom.AffineTransform computeGeographicToRasterTransform(int w } protected static void sample(double[] source, int x1, int x2, double xf, int y1, int y2, double yf, int width, - double transparent, double[] dest, int destPos) - { + double transparent, double[] dest, int destPos) { double ul = source[x1 + y1 * width]; double ll = source[x1 + y2 * width]; double lr = source[x2 + y2 * width]; @@ -368,25 +341,23 @@ protected static void sample(double[] source, int x1, int x2, double xf, int y1, // If all four sample values are not transparent (or missing), then write the interpolated value to the // destination buffer. - if ((ul != transparent) && (ur != transparent) && (lr != transparent) && (ll != transparent)) - { - dest[destPos] = - ((1.0 - xf) * (1.0 - yf) * ul) + if ((ul != transparent) && (ur != transparent) && (lr != transparent) && (ll != transparent)) { + dest[destPos] + = ((1.0 - xf) * (1.0 - yf) * ul) + ((1.0 - xf) * (yf) * ll) + ((xf) * (yf) * lr) + ((xf) * (1.0 - yf) * ur); } } - protected static class InterpolantLookupTable - { + protected static class InterpolantLookupTable { + protected int width; protected int height; protected double[] xParams; protected double[] yParams; - public InterpolantLookupTable(int width, int height) - { + public InterpolantLookupTable(int width, int height) { this.width = width; this.height = height; this.xParams = new double[3 * width]; @@ -395,48 +366,43 @@ public InterpolantLookupTable(int width, int height) java.util.Arrays.fill(this.yParams, -1d); } - public final boolean getInterpolantX(int x, double[] params) - { + public final boolean getInterpolantX(int x, double[] params) { params[0] = this.xParams[3 * x]; params[1] = this.xParams[3 * x + 1]; params[2] = this.xParams[3 * x + 2]; return params[0] != -1d; } - public final boolean getInterpolantY(int y, double[] params) - { + public final boolean getInterpolantY(int y, double[] params) { params[0] = this.yParams[3 * y]; params[1] = this.yParams[3 * y + 1]; params[2] = this.yParams[3 * y + 2]; return params[0] != -1d; } - public final void computeRangeX(double[] params) - { + public final void computeRangeX(double[] params) { computeInterpolantRange(this.xParams, this.width, params); } - public final void computeRangeY(double[] params) - { + public final void computeRangeY(double[] params) { computeInterpolantRange(this.yParams, this.height, params); } - protected static void computeInterpolantRange(double[] params, int size, double[] result) - { + protected static void computeInterpolantRange(double[] params, int size, double[] result) { double min = Double.MAX_VALUE; double max = -Double.MIN_VALUE; int index; - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { index = 3 * i; - if (params[index] != -1d) - { + if (params[index] != -1d) { // Compute the minimum first parameter (x1 or y1). - if (params[index] < min) + if (params[index] < min) { min = params[index]; + } // Compute the maximum second parameters (x2 or y2). - if (params[index + 1] > max) + if (params[index + 1] > max) { max = params[index + 1]; + } } } result[0] = min; @@ -445,8 +411,7 @@ protected static void computeInterpolantRange(double[] params, int size, double[ } protected InterpolantLookupTable createLookupTable(int width, int height, - double xMin, double xMax, double yMin, double yMax, java.awt.geom.AffineTransform lookupTransform) - { + double xMin, double xMax, double yMin, double yMax, java.awt.geom.AffineTransform lookupTransform) { // Compute the interpolation values for each transformed x- and y-coordinate. This assumes that the transform // is composed of translations and scales (no rotations or shears). Therefore the transformed coordinates of // each row or column would be identical. @@ -462,13 +427,11 @@ protected InterpolantLookupTable createLookupTable(int width, int height, double x, y; int index; - for (int i = 0; i < width; i++) - { + for (int i = 0; i < width; i++) { canvasPoint.setLocation(i, 0); lookupTransform.transform(canvasPoint, thisPoint); x = thisPoint.getX(); - if (((x - xMin) > threshold) && ((xMax - x) > threshold)) - { + if (((x - xMin) > threshold) && ((xMax - x) > threshold)) { x = (x < xMin) ? xMin : ((x > xMax) ? xMax : x); index = 3 * i; lut.xParams[index] = Math.floor(x); @@ -479,13 +442,11 @@ protected InterpolantLookupTable createLookupTable(int width, int height, } } - for (int j = 0; j < height; j++) - { + for (int j = 0; j < height; j++) { canvasPoint.setLocation(0, j); lookupTransform.transform(canvasPoint, thisPoint); y = thisPoint.getY(); - if (((y - yMin) > threshold) && ((yMax - y) > threshold)) - { + if (((y - yMin) > threshold) && ((yMax - y) > threshold)) { y = (y < yMin) ? yMin : ((y > yMax) ? yMax : y); index = 3 * j; lut.yParams[index] = Math.floor(y); @@ -496,8 +457,7 @@ protected InterpolantLookupTable createLookupTable(int width, int height, } } - if (haveXParam && haveYParam) - { + if (haveXParam && haveYParam) { return lut; } diff --git a/src/gov/nasa/worldwind/data/BufferedImageRaster.java b/src/gov/nasa/worldwind/data/BufferedImageRaster.java index 86ecedf272..cd449f049b 100644 --- a/src/gov/nasa/worldwind/data/BufferedImageRaster.java +++ b/src/gov/nasa/worldwind/data/BufferedImageRaster.java @@ -21,24 +21,21 @@ * @author dcollins * @version $Id: BufferedImageRaster.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BufferedImageRaster extends AbstractDataRaster implements Cacheable, Disposable -{ +public class BufferedImageRaster extends AbstractDataRaster implements Cacheable, Disposable { + private java.awt.image.BufferedImage bufferedImage; private java.awt.Graphics2D g2d; - public BufferedImageRaster(Sector sector, java.awt.image.BufferedImage bufferedImage) - { + public BufferedImageRaster(Sector sector, java.awt.image.BufferedImage bufferedImage) { this(sector, bufferedImage, null); } - public BufferedImageRaster(Sector sector, java.awt.image.BufferedImage bufferedImage, AVList list) - { + public BufferedImageRaster(Sector sector, java.awt.image.BufferedImage bufferedImage, AVList list) { super((null != bufferedImage) ? bufferedImage.getWidth() : 0, - (null != bufferedImage) ? bufferedImage.getHeight() : 0, - sector, list); + (null != bufferedImage) ? bufferedImage.getHeight() : 0, + sector, list); - if (bufferedImage == null) - { + if (bufferedImage == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -47,18 +44,15 @@ public BufferedImageRaster(Sector sector, java.awt.image.BufferedImage bufferedI this.bufferedImage = bufferedImage; } - public BufferedImageRaster(int width, int height, int transparency, Sector sector) - { + public BufferedImageRaster(int width, int height, int transparency, Sector sector) { super(width, height, sector); - if (width < 1) - { + if (width < 1) { String message = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 1) - { + if (height < 1) { String message = Logging.getMessage("generic.InvalidHeight", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -67,33 +61,27 @@ public BufferedImageRaster(int width, int height, int transparency, Sector secto this.bufferedImage = ImageUtil.createCompatibleImage(width, height, transparency); } - public java.awt.image.BufferedImage getBufferedImage() - { + public java.awt.image.BufferedImage getBufferedImage() { return this.bufferedImage; } - public java.awt.Graphics2D getGraphics() - { - if (this.g2d == null) - { + public java.awt.Graphics2D getGraphics() { + if (this.g2d == null) { this.g2d = this.bufferedImage.createGraphics(); // Enable bilinear interpolation. this.g2d.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, - java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR); + java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR); } return g2d; } - public void drawOnTo(DataRaster canvas) - { - if (canvas == null) - { + public void drawOnTo(DataRaster canvas) { + if (canvas == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!(canvas instanceof BufferedImageRaster)) - { + if (!(canvas instanceof BufferedImageRaster)) { String message = Logging.getMessage("DataRaster.IncompatibleRaster", canvas); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -102,10 +90,8 @@ public void drawOnTo(DataRaster canvas) this.doDrawOnTo((BufferedImageRaster) canvas); } - public void fill(java.awt.Color color) - { - if (color == null) - { + public void fill(java.awt.Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -115,28 +101,22 @@ public void fill(java.awt.Color color) // Keep track of the previous color. java.awt.Color prevColor = g2d.getColor(); - try - { + try { // Fill the raster with the specified color. g2d.setColor(color); g2d.fillRect(0, 0, this.getWidth(), this.getHeight()); - } - finally - { + } finally { // Restore the previous color. g2d.setColor(prevColor); } } - public long getSizeInBytes() - { + public long getSizeInBytes() { long size = 0L; java.awt.image.Raster raster = this.bufferedImage.getRaster(); - if (raster != null) - { + if (raster != null) { java.awt.image.DataBuffer db = raster.getDataBuffer(); - if (db != null) - { + if (db != null) { size = sizeOfDataBuffer(db); } } @@ -155,17 +135,13 @@ public long getSizeInBytes() // Logging.logger().log(java.util.logging.Level.FINEST, t.getMessage(), t); // } // } - - public void dispose() - { - if (this.g2d != null) - { + public void dispose() { + if (this.g2d != null) { this.g2d.dispose(); this.g2d = null; } - if (this.bufferedImage != null) - { + if (this.bufferedImage != null) { this.bufferedImage.flush(); this.bufferedImage = null; } @@ -267,19 +243,15 @@ public void dispose() // } // } // } - - protected void doDrawOnTo(BufferedImageRaster canvas) - { + protected void doDrawOnTo(BufferedImageRaster canvas) { Sector sector = this.getSector(); - if (null == sector) - { + if (null == sector) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!sector.intersects(canvas.getSector())) - { + if (!sector.intersects(canvas.getSector())) { return; } @@ -288,14 +260,13 @@ protected void doDrawOnTo(BufferedImageRaster canvas) java.awt.Composite prevComposite = null; java.lang.Object prevInterpolation = null, prevAntialiasing = null; - try - { + try { int canvasWidth = canvas.getWidth(); int canvasHeight = canvas.getHeight(); // Apply the transform that correctly maps the image onto the canvas. java.awt.geom.AffineTransform transform = this.computeSourceToDestTransform( - this.getWidth(), this.getHeight(), this.getSector(), canvasWidth, canvasHeight, canvas.getSector()); + this.getWidth(), this.getHeight(), this.getSector(), canvasWidth, canvasHeight, canvas.getSector()); AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR); Rectangle2D rect = op.getBounds2D(this.getBufferedImage()); @@ -303,8 +274,7 @@ protected void doDrawOnTo(BufferedImageRaster canvas) int clipWidth = (int) Math.ceil((rect.getMaxX() >= canvasWidth) ? canvasWidth : rect.getMaxX()); int clipHeight = (int) Math.ceil((rect.getMaxY() >= canvasHeight) ? canvasHeight : rect.getMaxY()); - if (clipWidth <= 0 || clipHeight <= 0) - { + if (clipWidth <= 0 || clipHeight <= 0) { return; } @@ -321,60 +291,53 @@ protected void doDrawOnTo(BufferedImageRaster canvas) g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.drawImage(this.getBufferedImage(), transform, null); - } -// catch (java.awt.image.ImagingOpException ioe) -// { -// // If we catch a ImagingOpException, then the transformed image has a width or height of 0. -// // This indicates that there is no intersection between the source image and the canvas, -// // or the intersection is smaller than one pixel. -// } -// catch (java.awt.image.RasterFormatException rfe) -// { -// // If we catch a RasterFormatException, then the transformed image has a width or height of 0. -// // This indicates that there is no intersection between the source image and the canvas, -// // or the intersection is smaller than one pixel. -// } - catch (Throwable t) - { + } // catch (java.awt.image.ImagingOpException ioe) + // { + // // If we catch a ImagingOpException, then the transformed image has a width or height of 0. + // // This indicates that there is no intersection between the source image and the canvas, + // // or the intersection is smaller than one pixel. + // } + // catch (java.awt.image.RasterFormatException rfe) + // { + // // If we catch a RasterFormatException, then the transformed image has a width or height of 0. + // // This indicates that there is no intersection between the source image and the canvas, + // // or the intersection is smaller than one pixel. + // } + catch (Throwable t) { String reason = WWUtil.extractExceptionReason(t); Logging.logger().log(java.util.logging.Level.SEVERE, reason, t); - } - finally - { + } finally { // Restore the previous clip, composite, and transform. - try - { - if (null != g2d) - { - if (null != prevClip) + try { + if (null != g2d) { + if (null != prevClip) { g2d.setClip(prevClip); + } - if (null != prevComposite) + if (null != prevComposite) { g2d.setComposite(prevComposite); + } - if (null != prevInterpolation) + if (null != prevInterpolation) { g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, prevInterpolation); + } - if (null != prevAntialiasing) + if (null != prevAntialiasing) { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, prevAntialiasing); + } } - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(java.util.logging.Level.FINEST, WWUtil.extractExceptionReason(t), t); } } } - private static long sizeOfDataBuffer(java.awt.image.DataBuffer dataBuffer) - { + private static long sizeOfDataBuffer(java.awt.image.DataBuffer dataBuffer) { return sizeOfElement(dataBuffer.getDataType()) * dataBuffer.getSize(); } - private static long sizeOfElement(int dataType) - { - switch (dataType) - { + private static long sizeOfElement(int dataType) { + switch (dataType) { case java.awt.image.DataBuffer.TYPE_BYTE: return (Byte.SIZE / 8); case java.awt.image.DataBuffer.TYPE_DOUBLE: @@ -392,58 +355,45 @@ private static long sizeOfElement(int dataType) return 0L; } - public static DataRaster wrap(BufferedImage image, AVList params) - { - if (null == image) - { + public static DataRaster wrap(BufferedImage image, AVList params) { + if (null == image) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == params) - { + if (null == params) { String msg = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (params.hasKey(AVKey.WIDTH)) - { + if (params.hasKey(AVKey.WIDTH)) { int width = (Integer) params.getValue(AVKey.WIDTH); - if (width != image.getWidth()) - { + if (width != image.getWidth()) { String msg = Logging.getMessage("generic.InvalidWidth", "" + width + "!=" + image.getWidth()); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - } - else - { + } else { params.setValue(AVKey.WIDTH, image.getWidth()); } - if (params.hasKey(AVKey.HEIGHT)) - { + if (params.hasKey(AVKey.HEIGHT)) { int height = (Integer) params.getValue(AVKey.HEIGHT); - if (height != image.getHeight()) - { + if (height != image.getHeight()) { String msg = Logging.getMessage("generic.InvalidHeight", "" + height + "!=" + image.getHeight()); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - } - else - { + } else { params.setValue(AVKey.HEIGHT, image.getHeight()); } Sector sector = null; - if (params.hasKey(AVKey.SECTOR)) - { + if (params.hasKey(AVKey.SECTOR)) { Object o = params.getValue(AVKey.SECTOR); - if (o instanceof Sector) - { + if (o instanceof Sector) { sector = (Sector) o; } } @@ -451,75 +401,61 @@ public static DataRaster wrap(BufferedImage image, AVList params) return new BufferedImageRaster(sector, image, params); } - public static DataRaster wrapAsGeoreferencedRaster(BufferedImage image, AVList params) - { - if (null == image) - { + public static DataRaster wrapAsGeoreferencedRaster(BufferedImage image, AVList params) { + if (null == image) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == params) - { + if (null == params) { String msg = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (params.hasKey(AVKey.WIDTH)) - { + if (params.hasKey(AVKey.WIDTH)) { int width = (Integer) params.getValue(AVKey.WIDTH); - if (width != image.getWidth()) - { + if (width != image.getWidth()) { String msg = Logging.getMessage("generic.InvalidWidth", "" + width + "!=" + image.getWidth()); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } } - if (params.hasKey(AVKey.HEIGHT)) - { + if (params.hasKey(AVKey.HEIGHT)) { int height = (Integer) params.getValue(AVKey.HEIGHT); - if (height != image.getHeight()) - { + if (height != image.getHeight()) { String msg = Logging.getMessage("generic.InvalidHeight", "" + height + "!=" + image.getHeight()); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } } - if (!params.hasKey(AVKey.SECTOR)) - { + if (!params.hasKey(AVKey.SECTOR)) { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } Sector sector = (Sector) params.getValue(AVKey.SECTOR); - if (null == sector) - { + if (null == sector) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!params.hasKey(AVKey.COORDINATE_SYSTEM)) - { + if (!params.hasKey(AVKey.COORDINATE_SYSTEM)) { // assume Geodetic Coordinate System params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC); } String cs = params.getStringValue(AVKey.COORDINATE_SYSTEM); - if (!params.hasKey(AVKey.PROJECTION_EPSG_CODE)) - { - if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { + if (!params.hasKey(AVKey.PROJECTION_EPSG_CODE)) { + if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { // assume WGS84 params.setValue(AVKey.PROJECTION_EPSG_CODE, GeoTiff.GCS.WGS_84); - } - else - { + } else { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PROJECTION_EPSG_CODE); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); @@ -528,15 +464,11 @@ public static DataRaster wrapAsGeoreferencedRaster(BufferedImage image, AVList p // if PIXEL_WIDTH is specified, we are not overriding it because UTM images // will have different pixel size - if (!params.hasKey(AVKey.PIXEL_WIDTH)) - { - if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { + if (!params.hasKey(AVKey.PIXEL_WIDTH)) { + if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { double pixelWidth = sector.getDeltaLonDegrees() / (double) image.getWidth(); params.setValue(AVKey.PIXEL_WIDTH, pixelWidth); - } - else - { + } else { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PIXEL_WIDTH); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); @@ -545,49 +477,39 @@ public static DataRaster wrapAsGeoreferencedRaster(BufferedImage image, AVList p // if PIXEL_HEIGHT is specified, we are not overriding it // because UTM images will have different pixel size - if (!params.hasKey(AVKey.PIXEL_HEIGHT)) - { - if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { + if (!params.hasKey(AVKey.PIXEL_HEIGHT)) { + if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { double pixelHeight = sector.getDeltaLatDegrees() / (double) image.getHeight(); params.setValue(AVKey.PIXEL_HEIGHT, pixelHeight); - } - else - { + } else { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PIXEL_HEIGHT); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } } - if (!params.hasKey(AVKey.PIXEL_FORMAT)) - { + if (!params.hasKey(AVKey.PIXEL_FORMAT)) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); - } - else if (!AVKey.IMAGE.equals(params.getStringValue(AVKey.PIXEL_FORMAT))) - { + } else if (!AVKey.IMAGE.equals(params.getStringValue(AVKey.PIXEL_FORMAT))) { String msg = Logging.getMessage("generic.UnknownValueForKey", - params.getStringValue(AVKey.PIXEL_FORMAT), AVKey.PIXEL_FORMAT); + params.getStringValue(AVKey.PIXEL_FORMAT), AVKey.PIXEL_FORMAT); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!params.hasKey(AVKey.ORIGIN) && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { + if (!params.hasKey(AVKey.ORIGIN) && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { // set UpperLeft corner as the origin, if not specified LatLon origin = new LatLon(sector.getMaxLatitude(), sector.getMinLongitude()); params.setValue(AVKey.ORIGIN, origin); } - if (!params.hasKey(AVKey.DATE_TIME)) - { + if (!params.hasKey(AVKey.DATE_TIME)) { // add NUL (\0) termination as required by TIFF v6 spec (20 bytes length) String timestamp = String.format("%1$tY:%1$tm:%1$td %tT\0", Calendar.getInstance()); params.setValue(AVKey.DATE_TIME, timestamp); } - if (!params.hasKey(AVKey.VERSION)) - { + if (!params.hasKey(AVKey.VERSION)) { params.setValue(AVKey.VERSION, Version.getVersion()); } @@ -598,8 +520,7 @@ else if (!AVKey.IMAGE.equals(params.getStringValue(AVKey.PIXEL_FORMAT))) } @Override - DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSector, AVList roiParams) - { + DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSector, AVList roiParams) { int transparency = java.awt.image.BufferedImage.TRANSLUCENT; // TODO: make configurable BufferedImageRaster canvas = new BufferedImageRaster(roiWidth, roiHeight, transparency, roiSector); this.drawOnTo(canvas); diff --git a/src/gov/nasa/worldwind/data/ByteBufferRaster.java b/src/gov/nasa/worldwind/data/ByteBufferRaster.java index b380222d62..a85af4faa8 100644 --- a/src/gov/nasa/worldwind/data/ByteBufferRaster.java +++ b/src/gov/nasa/worldwind/data/ByteBufferRaster.java @@ -17,12 +17,11 @@ * @author dcollins * @version $Id: ByteBufferRaster.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ByteBufferRaster extends BufferWrapperRaster -{ +public class ByteBufferRaster extends BufferWrapperRaster { + private java.nio.ByteBuffer byteBuffer; - public ByteBufferRaster(int width, int height, Sector sector, java.nio.ByteBuffer byteBuffer, AVList list) - { + public ByteBufferRaster(int width, int height, Sector sector, java.nio.ByteBuffer byteBuffer, AVList list) { super(width, height, sector, BufferWrapper.wrap(byteBuffer, list), list); this.byteBuffer = byteBuffer; @@ -30,36 +29,29 @@ public ByteBufferRaster(int width, int height, Sector sector, java.nio.ByteBuffe this.validateParameters(list); } - private void validateParameters(AVList list) throws IllegalArgumentException - { + private void validateParameters(AVList list) throws IllegalArgumentException { this.doValidateParameters(list); } - protected void doValidateParameters(AVList list) throws IllegalArgumentException - { + protected void doValidateParameters(AVList list) throws IllegalArgumentException { } - public ByteBufferRaster(int width, int height, Sector sector, AVList params) - { + public ByteBufferRaster(int width, int height, Sector sector, AVList params) { this(width, height, sector, createCompatibleBuffer(width, height, params), params); } - public static java.nio.ByteBuffer createCompatibleBuffer(int width, int height, AVList params) - { - if (width < 1) - { + public static java.nio.ByteBuffer createCompatibleBuffer(int width, int height, AVList params) { + if (width < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 1) - { + if (height < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -68,35 +60,32 @@ public static java.nio.ByteBuffer createCompatibleBuffer(int width, int height, Object dataType = params.getValue(AVKey.DATA_TYPE); int sizeOfDataType = 0; - if (AVKey.INT8.equals(dataType)) + if (AVKey.INT8.equals(dataType)) { sizeOfDataType = (Byte.SIZE / 8); - else if (AVKey.INT16.equals(dataType)) + } else if (AVKey.INT16.equals(dataType)) { sizeOfDataType = (Short.SIZE / 8); - else if (AVKey.INT32.equals(dataType)) + } else if (AVKey.INT32.equals(dataType)) { sizeOfDataType = (Integer.SIZE / 8); - else if (AVKey.FLOAT32.equals(dataType)) + } else if (AVKey.FLOAT32.equals(dataType)) { sizeOfDataType = (Float.SIZE / 8); + } int sizeInBytes = sizeOfDataType * width * height; return java.nio.ByteBuffer.allocate(sizeInBytes); } - public java.nio.ByteBuffer getByteBuffer() - { + public java.nio.ByteBuffer getByteBuffer() { return this.byteBuffer; } - public static DataRaster createGeoreferencedRaster(AVList params) - { - if (null == params) - { + public static DataRaster createGeoreferencedRaster(AVList params) { + if (null == params) { String msg = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (!params.hasKey(AVKey.WIDTH)) - { + if (!params.hasKey(AVKey.WIDTH)) { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.WIDTH); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); @@ -104,15 +93,13 @@ public static DataRaster createGeoreferencedRaster(AVList params) int width = (Integer) params.getValue(AVKey.WIDTH); - if (!(width > 0)) - { + if (!(width > 0)) { String msg = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (!params.hasKey(AVKey.HEIGHT)) - { + if (!params.hasKey(AVKey.HEIGHT)) { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.HEIGHT); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); @@ -120,44 +107,36 @@ public static DataRaster createGeoreferencedRaster(AVList params) int height = (Integer) params.getValue(AVKey.HEIGHT); - if (!(height > 0)) - { + if (!(height > 0)) { String msg = Logging.getMessage("generic.InvalidWidth", height); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (!params.hasKey(AVKey.SECTOR)) - { + if (!params.hasKey(AVKey.SECTOR)) { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } Sector sector = (Sector) params.getValue(AVKey.SECTOR); - if (null == sector) - { + if (null == sector) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!params.hasKey(AVKey.COORDINATE_SYSTEM)) - { + if (!params.hasKey(AVKey.COORDINATE_SYSTEM)) { // assume Geodetic Coordinate System params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC); } String cs = params.getStringValue(AVKey.COORDINATE_SYSTEM); - if (!params.hasKey(AVKey.PROJECTION_EPSG_CODE)) - { - if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { + if (!params.hasKey(AVKey.PROJECTION_EPSG_CODE)) { + if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { // assume WGS84 params.setValue(AVKey.PROJECTION_EPSG_CODE, GeoTiff.GCS.WGS_84); - } - else - { + } else { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PROJECTION_EPSG_CODE); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); @@ -166,15 +145,11 @@ public static DataRaster createGeoreferencedRaster(AVList params) // if PIXEL_WIDTH is specified, we are not overriding it because UTM images // will have different pixel size - if (!params.hasKey(AVKey.PIXEL_WIDTH)) - { - if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { + if (!params.hasKey(AVKey.PIXEL_WIDTH)) { + if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { double pixelWidth = sector.getDeltaLonDegrees() / (double) width; params.setValue(AVKey.PIXEL_WIDTH, pixelWidth); - } - else - { + } else { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PIXEL_WIDTH); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); @@ -183,80 +158,65 @@ public static DataRaster createGeoreferencedRaster(AVList params) // if PIXEL_HEIGHT is specified, we are not overriding it // because UTM images will have different pixel size - if (!params.hasKey(AVKey.PIXEL_HEIGHT)) - { - if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { + if (!params.hasKey(AVKey.PIXEL_HEIGHT)) { + if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { double pixelHeight = sector.getDeltaLatDegrees() / (double) height; params.setValue(AVKey.PIXEL_HEIGHT, pixelHeight); - } - else - { + } else { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PIXEL_HEIGHT); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } } - if (!params.hasKey(AVKey.PIXEL_FORMAT)) - { + if (!params.hasKey(AVKey.PIXEL_FORMAT)) { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PIXEL_FORMAT); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); - } - else - { + } else { String pixelFormat = params.getStringValue(AVKey.PIXEL_FORMAT); - if (!AVKey.ELEVATION.equals(pixelFormat) && !AVKey.IMAGE.equals(pixelFormat)) - { + if (!AVKey.ELEVATION.equals(pixelFormat) && !AVKey.IMAGE.equals(pixelFormat)) { String msg = Logging.getMessage("generic.UnknownValueForKey", pixelFormat, AVKey.PIXEL_FORMAT); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } } - if (!params.hasKey(AVKey.DATA_TYPE)) - { + if (!params.hasKey(AVKey.DATA_TYPE)) { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.DATA_TYPE); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } // validate elevation parameters - if (AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT))) - { + if (AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT))) { String type = params.getStringValue(AVKey.DATA_TYPE); - if (!AVKey.FLOAT32.equals(type) && !AVKey.INT16.equals(type)) - { + if (!AVKey.FLOAT32.equals(type) && !AVKey.INT16.equals(type)) { String msg = Logging.getMessage("generic.UnknownValueForKey", type, AVKey.DATA_TYPE); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } } - if (!params.hasKey(AVKey.ORIGIN) && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { + if (!params.hasKey(AVKey.ORIGIN) && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { // set UpperLeft corner as the origin, if not specified LatLon origin = new LatLon(sector.getMaxLatitude(), sector.getMinLongitude()); params.setValue(AVKey.ORIGIN, origin); } - if (!params.hasKey(AVKey.BYTE_ORDER)) - { + if (!params.hasKey(AVKey.BYTE_ORDER)) { String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.BYTE_ORDER); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (!params.hasKey(AVKey.DATE_TIME)) - { + if (!params.hasKey(AVKey.DATE_TIME)) { // add NUL (\0) termination as required by TIFF v6 spec (20 bytes length) String timestamp = String.format("%1$tY:%1$tm:%1$td %tT\0", Calendar.getInstance()); params.setValue(AVKey.DATE_TIME, timestamp); } - if (!params.hasKey(AVKey.VERSION)) - { + if (!params.hasKey(AVKey.VERSION)) { params.setValue(AVKey.VERSION, Version.getVersion()); } diff --git a/src/gov/nasa/worldwind/data/CachedDataRaster.java b/src/gov/nasa/worldwind/data/CachedDataRaster.java index da2c5531d4..cdff967be6 100644 --- a/src/gov/nasa/worldwind/data/CachedDataRaster.java +++ b/src/gov/nasa/worldwind/data/CachedDataRaster.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.avlist.*; @@ -25,10 +24,9 @@ * @author Lado Garakanidze * @version $Id: CachedDataRaster.java 3037 2015-04-17 23:08:47Z tgaskins $ */ -public class CachedDataRaster extends AVListImpl implements DataRaster -{ - protected enum ErrorHandlerMode - { +public class CachedDataRaster extends AVListImpl implements DataRaster { + + protected enum ErrorHandlerMode { ALLOW_EXCEPTIONS, DISABLE_EXCEPTIONS } @@ -41,35 +39,32 @@ protected enum ErrorHandlerMode protected final Object rasterUsageLock = new Object(); protected final Object rasterRetrievalLock = new Object(); - protected String[] requiredKeys = new String[] {AVKey.SECTOR, AVKey.PIXEL_FORMAT}; + protected String[] requiredKeys = new String[]{AVKey.SECTOR, AVKey.PIXEL_FORMAT}; /** * Create a cached data raster. * * @param source the location of the local file, expressed as either a String path, a File, or a file URL. * @param params metadata as AVList, it is expected to next parameters: AVKey.WIDTH, AVKey.HEIGHT, AVKey.SECTOR, - * AVKey.PIXEL_FORMAT. - *

    - * If any of these keys is missing, there will be an attempt made to retrieve missign metadata from - * the source using the reader. + * AVKey.PIXEL_FORMAT. + *

    + * If any of these keys is missing, there will be an attempt made to retrieve missign metadata from the source using + * the reader. * @param reader A reference to a DataRasterReader instance - * @param cache A reference to a MemoryCache instance + * @param cache A reference to a MemoryCache instance * - * @throws java.io.IOException thrown if there is an error to read metadata from the source + * @throws java.io.IOException thrown if there is an error to read metadata from the source * @throws IllegalArgumentException thrown when a source or a reader are null */ public CachedDataRaster(Object source, AVList params, DataRasterReader reader, MemoryCache cache) - throws java.io.IOException, IllegalArgumentException - { - if (source == null) - { + throws java.io.IOException, IllegalArgumentException { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (reader == null) - { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -83,75 +78,63 @@ public CachedDataRaster(Object source, AVList params, DataRasterReader reader, M this.setValues(params.copy()); this.rasterCache = cache; - if (this.rasterCache != null) - { + if (this.rasterCache != null) { this.cacheListener = new CacheListener(this.dataSource); this.rasterCache.addCacheListener(this.cacheListener); } } protected void assembleMetadata(Object source, AVList params, DataRasterReader reader) - throws java.io.IOException, IllegalArgumentException - { - if (!this.hasRequiredMetadata(params, ErrorHandlerMode.DISABLE_EXCEPTIONS)) - { - if (!reader.canRead(source, params)) - { + throws java.io.IOException, IllegalArgumentException { + if (!this.hasRequiredMetadata(params, ErrorHandlerMode.DISABLE_EXCEPTIONS)) { + if (!reader.canRead(source, params)) { String message = Logging.getMessage("DataRaster.CannotRead", source); Logging.logger().severe(message); throw new java.io.IOException(message); } - if (!this.hasRequiredMetadata(params, ErrorHandlerMode.DISABLE_EXCEPTIONS)) - { + if (!this.hasRequiredMetadata(params, ErrorHandlerMode.DISABLE_EXCEPTIONS)) { reader.readMetadata(source, params); this.hasRequiredMetadata(params, ErrorHandlerMode.ALLOW_EXCEPTIONS); } } } - protected String[] getRequiredKeysList() - { + protected String[] getRequiredKeysList() { return this.requiredKeys; } /** * Validates if params (AVList) has all required keys. * - * @param params AVList of key/value pairs + * @param params AVList of key/value pairs * @param throwException specifies weather to throw exception when a key/value is missing, or just return false. * * @return TRUE, if all required keys are present in the params list, or both params and required keys are empty, - * otherwise returns FALSE (if throwException is false) + * otherwise returns FALSE (if throwException is false) * * @throws IllegalArgumentException If a key/value is missing and throwException is set to TRUE */ protected boolean hasRequiredMetadata(AVList params, ErrorHandlerMode throwException) - throws IllegalArgumentException - { + throws IllegalArgumentException { String[] keys = this.getRequiredKeysList(); - if (null == params || params.getEntries().size() == 0) - { + if (null == params || params.getEntries().size() == 0) { // return TRUE if required keys is empty, otherwise return FALSE return (null == keys || keys.length == 0); } - if (null != keys && keys.length > 0) - { - for (String key : keys) - { + if (null != keys && keys.length > 0) { + for (String key : keys) { Object value = params.getValue(key); - if (WWUtil.isEmpty(value)) - { - if (throwException == ErrorHandlerMode.ALLOW_EXCEPTIONS) - { + if (WWUtil.isEmpty(value)) { + if (throwException == ErrorHandlerMode.ALLOW_EXCEPTIONS) { String message = Logging.getMessage("generic.MissingRequiredParameter", key); Logging.logger().finest(message); throw new IllegalArgumentException(message); - } - else + } else { return false; + } } } } @@ -159,84 +142,73 @@ protected boolean hasRequiredMetadata(AVList params, ErrorHandlerMode throwExcep return true; } - public int getWidth() - { + public int getWidth() { Object o = this.getValue(AVKey.WIDTH); - if (null != o && o instanceof Integer) + if (null != o && o instanceof Integer) { return (Integer) o; + } throw new WWRuntimeException(Logging.getMessage("generic.MissingRequiredParameter", AVKey.WIDTH)); } - public int getHeight() - { + public int getHeight() { Object o = this.getValue(AVKey.HEIGHT); - if (null != o && o instanceof Integer) + if (null != o && o instanceof Integer) { return (Integer) o; + } throw new WWRuntimeException(Logging.getMessage("generic.MissingRequiredParameter", AVKey.HEIGHT)); } - public Sector getSector() - { + public Sector getSector() { Object o = this.getValue(AVKey.SECTOR); - if (null != o && o instanceof Sector) + if (null != o && o instanceof Sector) { return (Sector) o; + } throw new WWRuntimeException(Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR)); } - public Object getDataSource() - { + public Object getDataSource() { return this.dataSource; } - public AVList getParams() - { + public AVList getParams() { return this.getMetadata(); } - public AVList getMetadata() - { + public AVList getMetadata() { return this.copy(); } - public DataRasterReader getDataRasterReader() - { + public DataRasterReader getDataRasterReader() { return this.dataReader; } - public void dispose() - { + public void dispose() { String message = Logging.getMessage("generic.ExceptionWhileDisposing", this.dataSource); Logging.logger().severe(message); throw new IllegalStateException(message); } - protected DataRaster[] getDataRasters() throws IOException, WWRuntimeException - { - synchronized (this.rasterRetrievalLock) - { + protected DataRaster[] getDataRasters() throws IOException, WWRuntimeException { + synchronized (this.rasterRetrievalLock) { DataRaster[] rasters = (this.rasterCache != null) - ? (DataRaster[]) this.rasterCache.getObject(this.dataSource) : null; + ? (DataRaster[]) this.rasterCache.getObject(this.dataSource) : null; - if (null != rasters) + if (null != rasters) { return rasters; + } // prevent an attempt to re-read rasters which failed to load - if (this.rasterCache == null || !this.rasterCache.contains(this.dataSource)) - { + if (this.rasterCache == null || !this.rasterCache.contains(this.dataSource)) { long memoryDelta = 0L; - try - { + try { AVList rasterParams = this.copy(); - try - { + try { long before = getTotalUsedMemory(); rasters = this.dataReader.read(this.getDataSource(), rasterParams); memoryDelta = getTotalUsedMemory() - before; - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { Logging.logger().finest(this.composeExceptionReason(e)); this.releaseMemory(); // let's retry after the finalization and GC @@ -245,30 +217,25 @@ protected DataRaster[] getDataRasters() throws IOException, WWRuntimeException rasters = this.dataReader.read(this.getDataSource(), rasterParams); memoryDelta = getTotalUsedMemory() - before; } - } - catch (Throwable t) - { + } catch (Throwable t) { disposeRasters(rasters); // cleanup in case of exception rasters = null; String message = Logging.getMessage("DataRaster.CannotRead", this.composeExceptionReason(t)); Logging.logger().severe(message); throw new WWRuntimeException(message); - } - finally - { + } finally { // Add rasters to the cache, even if "rasters" is null to prevent multiple failed reads. - if (this.rasterCache != null) - { + if (this.rasterCache != null) { long totalBytes = getSizeInBytes(rasters); totalBytes = (memoryDelta > totalBytes) ? memoryDelta : totalBytes; - if (totalBytes > 0L) + if (totalBytes > 0L) { this.rasterCache.add(this.dataSource, rasters, totalBytes); + } } } } - if (null == rasters || rasters.length == 0) - { + if (null == rasters || rasters.length == 0) { String message = Logging.getMessage("generic.CannotCreateRaster", this.getDataSource()); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -278,55 +245,39 @@ protected DataRaster[] getDataRasters() throws IOException, WWRuntimeException } } - public void drawOnTo(DataRaster canvas) - { - synchronized (this.rasterUsageLock) - { - try - { + public void drawOnTo(DataRaster canvas) { + synchronized (this.rasterUsageLock) { + try { DataRaster[] rasters; - try - { + try { rasters = this.getDataRasters(); - for (DataRaster raster : rasters) - { + for (DataRaster raster : rasters) { raster.drawOnTo(canvas); } - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { Logging.logger().finest(this.composeExceptionReason(e)); this.releaseMemory(); rasters = this.getDataRasters(); - for (DataRaster raster : rasters) - { + for (DataRaster raster : rasters) { raster.drawOnTo(canvas); } } - } - catch (Throwable t) - { + } catch (Throwable t) { String reason = this.composeExceptionReason(t); Logging.logger().log(Level.SEVERE, reason, t); } } } - public DataRaster getSubRaster(AVList params) - { - synchronized (this.rasterUsageLock) - { - try - { + public DataRaster getSubRaster(AVList params) { + synchronized (this.rasterUsageLock) { + try { DataRaster[] rasters; - try - { + try { rasters = this.getDataRasters(); return rasters[0].getSubRaster(params); - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { Logging.logger().finest(this.composeExceptionReason(e)); this.releaseMemory(); @@ -334,9 +285,7 @@ public DataRaster getSubRaster(AVList params) rasters = this.getDataRasters(); return rasters[0].getSubRaster(params); } - } - catch (Throwable t) - { + } catch (Throwable t) { String reason = this.composeExceptionReason(t); Logging.logger().log(Level.SEVERE, reason, t); } @@ -347,10 +296,10 @@ public DataRaster getSubRaster(AVList params) } } - public DataRaster getSubRaster(int width, int height, Sector sector, AVList params) - { - if (null == params) + public DataRaster getSubRaster(int width, int height, Sector sector, AVList params) { + if (null == params) { params = new AVListImpl(); + } params.setValue(AVKey.WIDTH, width); params.setValue(AVKey.HEIGHT, height); @@ -359,10 +308,10 @@ public DataRaster getSubRaster(int width, int height, Sector sector, AVList para return this.getSubRaster(params); } - protected void releaseMemory() - { - if (this.rasterCache != null) + protected void releaseMemory() { + if (this.rasterCache != null) { this.rasterCache.clear(); + } System.runFinalization(); @@ -371,79 +320,68 @@ protected void releaseMemory() Thread.yield(); } - protected String composeExceptionReason(Throwable t) - { + protected String composeExceptionReason(Throwable t) { StringBuffer sb = new StringBuffer(); - if (null != this.dataSource) + if (null != this.dataSource) { sb.append(this.dataSource).append(" : "); + } sb.append(WWUtil.extractExceptionReason(t)); return sb.toString(); } - protected long getSizeInBytes(DataRaster[] rasters) - { + protected long getSizeInBytes(DataRaster[] rasters) { long totalBytes = 0L; - if (rasters != null) - { - for (DataRaster raster : rasters) - { - if (raster != null && raster instanceof Cacheable) + if (rasters != null) { + for (DataRaster raster : rasters) { + if (raster != null && raster instanceof Cacheable) { totalBytes += ((Cacheable) raster).getSizeInBytes(); + } } } return totalBytes; } - protected static void disposeRasters(DataRaster[] rasters) - { - if (rasters != null) - { - for (DataRaster raster : rasters) - { + protected static void disposeRasters(DataRaster[] rasters) { + if (rasters != null) { + for (DataRaster raster : rasters) { raster.dispose(); } } } - private static class CacheListener implements MemoryCache.CacheListener - { + private static class CacheListener implements MemoryCache.CacheListener { + private Object key; - private CacheListener(Object key) - { + private CacheListener(Object key) { this.key = key; } - public void entryRemoved(Object key, Object clientObject) - { - if (key != this.key) + public void entryRemoved(Object key, Object clientObject) { + if (key != this.key) { return; + } - if (clientObject == null || !(clientObject instanceof DataRaster[])) - { + if (clientObject == null || !(clientObject instanceof DataRaster[])) { String message = MessageFormat.format("Cannot dispose {0}", clientObject); Logging.logger().warning(message); return; } - try - { + try { disposeRasters((DataRaster[]) clientObject); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileDisposing", clientObject); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - public void removalException(Throwable t, Object key, Object clientObject) - { + public void removalException(Throwable t, Object key, Object clientObject) { String reason = t.getMessage(); reason = (WWUtil.isEmpty(reason) && null != t.getCause()) ? t.getCause().getMessage() : reason; String msg = Logging.getMessage("BasicMemoryCache.ExceptionFromRemovalListener", reason); @@ -451,8 +389,7 @@ public void removalException(Throwable t, Object key, Object clientObject) } } - protected static long getTotalUsedMemory() - { + protected static long getTotalUsedMemory() { Runtime runtime = Runtime.getRuntime(); return (runtime.totalMemory() - runtime.freeMemory()); } diff --git a/src/gov/nasa/worldwind/data/DDSRasterReader.java b/src/gov/nasa/worldwind/data/DDSRasterReader.java index 92832c2fb8..c6656ddc78 100644 --- a/src/gov/nasa/worldwind/data/DDSRasterReader.java +++ b/src/gov/nasa/worldwind/data/DDSRasterReader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.avlist.AVKey; @@ -21,35 +20,27 @@ * @author Lado Garakanidze * @version $Id: DDSRasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class DDSRasterReader extends AbstractDataRasterReader { -public class DDSRasterReader extends AbstractDataRasterReader -{ protected static final String[] ddsMimeTypes = new String[]{"image/dds"}; protected static final String[] ddsSuffixes = new String[]{"dds"}; - public DDSRasterReader() - { + public DDSRasterReader() { super(ddsMimeTypes, ddsSuffixes); } @Override - protected boolean doCanRead(Object source, AVList params) - { - try - { + protected boolean doCanRead(Object source, AVList params) { + try { DDSHeader header = DDSHeader.readFrom(source); - if (null != header && header.getWidth() > 0 && header.getHeight() > 0) - { - if (null != params && !params.hasKey(AVKey.PIXEL_FORMAT)) - { + if (null != header && header.getWidth() > 0 && header.getHeight() > 0) { + if (null != params && !params.hasKey(AVKey.PIXEL_FORMAT)) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); } return true; } - } - catch (Exception e) - { + } catch (Exception e) { String message = e.getMessage(); message = (null == message && null != e.getCause()) ? e.getCause().getMessage() : message; Logging.logger().log(Level.FINEST, message, e); @@ -58,10 +49,8 @@ protected boolean doCanRead(Object source, AVList params) } @Override - protected DataRaster[] doRead(Object source, AVList params) throws IOException - { - if (null == params || !params.hasKey(AVKey.SECTOR)) - { + protected DataRaster[] doRead(Object source, AVList params) throws IOException { + if (null == params || !params.hasKey(AVKey.SECTOR)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -69,21 +58,15 @@ protected DataRaster[] doRead(Object source, AVList params) throws IOException DataRaster raster = null; - try - { + try { DDSDecompressor decompressor = new DDSDecompressor(); raster = decompressor.decompress(source, params); - if (null != raster) - { + if (null != raster) { raster.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); } - } - catch (WWRuntimeException wwe) - { + } catch (WWRuntimeException wwe) { throw new IOException(wwe.getMessage()); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = t.getMessage(); message = (WWUtil.isEmpty(message) && null != t.getCause()) ? t.getCause().getMessage() : message; Logging.logger().log(Level.FINEST, message, t); @@ -94,20 +77,15 @@ protected DataRaster[] doRead(Object source, AVList params) throws IOException } @Override - protected void doReadMetadata(Object source, AVList params) throws IOException - { - try - { + protected void doReadMetadata(Object source, AVList params) throws IOException { + try { DDSHeader header = DDSHeader.readFrom(source); - if (null != header && null != params) - { + if (null != header && null != params) { params.setValue(AVKey.WIDTH, header.getWidth()); params.setValue(AVKey.HEIGHT, header.getHeight()); params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); } - } - catch (Exception e) - { + } catch (Exception e) { String message = e.getMessage(); message = (WWUtil.isEmpty(message) && null != e.getCause()) ? e.getCause().getMessage() : message; Logging.logger().log(Level.FINEST, message, e); diff --git a/src/gov/nasa/worldwind/data/DDSRasterWriter.java b/src/gov/nasa/worldwind/data/DDSRasterWriter.java index 60427b90d8..86720359a1 100644 --- a/src/gov/nasa/worldwind/data/DDSRasterWriter.java +++ b/src/gov/nasa/worldwind/data/DDSRasterWriter.java @@ -15,26 +15,23 @@ * @author dcollins * @version $Id: DDSRasterWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DDSRasterWriter extends AbstractDataRasterWriter -{ +public class DDSRasterWriter extends AbstractDataRasterWriter { + protected static final String[] ddsMimeTypes = {"image/dds"}; protected static final String[] ddsSuffixes = {"dds"}; - public DDSRasterWriter() - { + public DDSRasterWriter() { super(ddsMimeTypes, ddsSuffixes); } - protected boolean doCanWrite(DataRaster raster, String formatSuffix, File file) - { + protected boolean doCanWrite(DataRaster raster, String formatSuffix, File file) { return (raster != null) && (raster instanceof BufferedImageRaster); } - protected void doWrite(DataRaster raster, String formatSuffix, File file) throws IOException - { + protected void doWrite(DataRaster raster, String formatSuffix, File file) throws IOException { BufferedImageRaster bufferedImageRaster = (BufferedImageRaster) raster; java.awt.image.BufferedImage image = bufferedImageRaster.getBufferedImage(); - + java.nio.ByteBuffer byteBuffer = DDSCompressor.compressImage(image); // Do not force changes to the underlying filesystem. This drastically improves write performance. boolean forceFilesystemWrite = false; diff --git a/src/gov/nasa/worldwind/data/DTEDRasterReader.java b/src/gov/nasa/worldwind/data/DTEDRasterReader.java index c8441119bf..314c92984a 100644 --- a/src/gov/nasa/worldwind/data/DTEDRasterReader.java +++ b/src/gov/nasa/worldwind/data/DTEDRasterReader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.avlist.*; @@ -16,40 +15,32 @@ * @author Lado Garakanidze * @version $Id: DTEDRasterReader.java 3037 2015-04-17 23:08:47Z tgaskins $ */ +public class DTEDRasterReader extends AbstractDataRasterReader { -public class DTEDRasterReader extends AbstractDataRasterReader -{ - protected static final String[] dtedMimeTypes = new String[] { + protected static final String[] dtedMimeTypes = new String[]{ "application/dted", "application/dt0", "application/dted-0", "application/dt1", "application/dted-1", - "application/dt2", "application/dted-2", - }; + "application/dt2", "application/dted-2",}; - protected static final String[] dtedSuffixes = new String[] - {"dt0", "dt1", "dt2"}; + protected static final String[] dtedSuffixes = new String[]{"dt0", "dt1", "dt2"}; - public DTEDRasterReader() - { + public DTEDRasterReader() { super(dtedMimeTypes, dtedSuffixes); } @Override - protected boolean doCanRead(Object source, AVList params) - { + protected boolean doCanRead(Object source, AVList params) { File file = this.getFile(source); - if (null == file) - { + if (null == file) { return false; } // Assume that a proper suffix reliably identifies a DTED file. Otherwise the file will have to be loaded // to determine that, and there are often tens of thousands of DTED files, which causes raster server start-up // times to be excessive. - if (this.canReadSuffix(source)) - { - if (null != params) - { + if (this.canReadSuffix(source)) { + if (null != params) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); // we know that DTED is elevation data } @@ -57,21 +48,16 @@ protected boolean doCanRead(Object source, AVList params) } boolean canRead = false; - try - { + try { AVList metadata = DTED.readMetadata(file); - if (null != metadata) - { - if (null != params) - { + if (null != metadata) { + if (null != params) { params.setValues(metadata); } canRead = AVKey.ELEVATION.equals(metadata.getValue(AVKey.PIXEL_FORMAT)); } - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().finest(t.getMessage()); canRead = false; } @@ -80,11 +66,9 @@ protected boolean doCanRead(Object source, AVList params) } @Override - protected DataRaster[] doRead(Object source, AVList params) throws IOException - { + protected DataRaster[] doRead(Object source, AVList params) throws IOException { File file = this.getFile(source); - if (null == file) - { + if (null == file) { String message = Logging.getMessage("generic.UnrecognizedSourceTypeOrUnavailableSource", source); Logging.logger().severe(message); throw new IOException(message); @@ -93,52 +77,41 @@ protected DataRaster[] doRead(Object source, AVList params) throws IOException // This may be the first time the file has been opened, so pass the metadata list to the read method // in order to update that list with the file's metadata. DataRaster raster = DTED.read(file, params); - if (raster instanceof ByteBufferRaster) + if (raster instanceof ByteBufferRaster) { ElevationsUtil.rectify((ByteBufferRaster) raster); + } - return new DataRaster[] {raster}; + return new DataRaster[]{raster}; } @Override - protected void doReadMetadata(Object source, AVList params) throws IOException - { + protected void doReadMetadata(Object source, AVList params) throws IOException { File file = this.getFile(source); - if (null == file) - { + if (null == file) { String message = Logging.getMessage("generic.UnrecognizedSourceTypeOrUnavailableSource", source); Logging.logger().severe(message); throw new IOException(message); } AVList metadata = DTED.readMetadata(file); - if (null != metadata && null != params) - { + if (null != metadata && null != params) { params.setValues(metadata); } } - protected File getFile(Object source) - { - if (null == source) - { + protected File getFile(Object source) { + if (null == source) { return null; - } - else if (source instanceof java.io.File) - { + } else if (source instanceof java.io.File) { return (File) source; - } - else if (source instanceof java.net.URL) - { + } else if (source instanceof java.net.URL) { return WWIO.convertURLToFile((java.net.URL) source); - } - else - { + } else { return null; } } - protected String validateMetadata(Object source, AVList params) - { + protected String validateMetadata(Object source, AVList params) { // Don't validate anything so we can avoid reading the metadata at start-up. Assume that the // sector will come from the config file and that the pixel type is specified in doCanRead above. return null; diff --git a/src/gov/nasa/worldwind/data/DataRaster.java b/src/gov/nasa/worldwind/data/DataRaster.java index c0ed391320..9115d86b19 100644 --- a/src/gov/nasa/worldwind/data/DataRaster.java +++ b/src/gov/nasa/worldwind/data/DataRaster.java @@ -12,15 +12,14 @@ // TODO: Document the conditions determining when the sub-raster methods would fail and its response when the input // sector is not fully within the raster's sector. Also do so appropriately in the implementing classes. // What's the response from getSubRegion if a necessary projection can't be performed? - /** * Represents a raster of imagery or elevations. * * @author dcollins * @version $Id: DataRaster.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface DataRaster extends AVList, Disposable -{ +public interface DataRaster extends AVList, Disposable { + /** * Returns the raster's width in raster units. * @@ -55,13 +54,13 @@ public interface DataRaster extends AVList, Disposable * even if this raster does not. * * @param params a list of parameters that specify the width, height and sector of the region to return. Specify - * these values using {@link gov.nasa.worldwind.avlist.AVKey#WIDTH}, {@link + * these values using {@link gov.nasa.worldwind.avlist.AVKey#WIDTH}, {@link * gov.nasa.worldwind.avlist.AVKey#HEIGHT} and {@link gov.nasa.worldwind.avlist.AVKey#SECTOR}. * * @return the requested raster, or null if the raster could not be created. * * @throws IllegalArgumentException if the specified parameter list is missing the width, height or sector keys or - * any of those values are invalid. + * any of those values are invalid. */ DataRaster getSubRaster(AVList params); @@ -69,11 +68,11 @@ public interface DataRaster extends AVList, Disposable * Returns a portion of this raster as another raster. The returned raster conforms to EPSG:4326 even if this raster * does not. * - * @param width the width to make the returned sub-raster. + * @param width the width to make the returned sub-raster. * @param height the height to make the returned sub-raster. * @param sector the sector to copy. * @param params a list of parameters that specify the width, height and sector of the region to return. Specify - * these values using {@link gov.nasa.worldwind.avlist.AVKey#WIDTH}, {@link + * these values using {@link gov.nasa.worldwind.avlist.AVKey#WIDTH}, {@link * gov.nasa.worldwind.avlist.AVKey#HEIGHT} and {@link gov.nasa.worldwind.avlist.AVKey#SECTOR}. * * @return the requested raster, or null if the raster could not be created. diff --git a/src/gov/nasa/worldwind/data/DataRasterReader.java b/src/gov/nasa/worldwind/data/DataRasterReader.java index bee5b00b53..1481b3c5b5 100644 --- a/src/gov/nasa/worldwind/data/DataRasterReader.java +++ b/src/gov/nasa/worldwind/data/DataRasterReader.java @@ -12,20 +12,19 @@ * @author dcollins * @version $Id: DataRasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface DataRasterReader extends AVList -{ +public interface DataRasterReader extends AVList { + String getDescription(); // TODO: remove String[] getSuffixes(); // TODO: remove /** - * Indicates whether this reader can read a specified data source. - * The source may be one of the following: + * Indicates whether this reader can read a specified data source. The source may be one of the following: *

      - *
    • {@link java.io.File}
    • - *
    • {@link String}
    • - *
    • {@link java.io.InputStream}
    • - *
    • {@link java.net.URL}
    • + *
    • {@link java.io.File}
    • + *
    • {@link String}
    • + *
    • {@link java.io.InputStream}
    • + *
    • {@link java.net.URL}
    • *
    * * @param source the source to examine. @@ -36,19 +35,18 @@ public interface DataRasterReader extends AVList boolean canRead(Object source, AVList params); /** - * Reads and returns the DataRaster instances from a data source. - * The source may be one of the following: - * The source may be one of the following: + * Reads and returns the DataRaster instances from a data source. The source may be one of the following: The source + * may be one of the following: *
      - *
    • {@link java.io.File}
    • - *
    • {@link String}
    • - *
    • {@link java.io.InputStream}
    • - *
    • {@link java.net.URL}
    • + *
    • {@link java.io.File}
    • + *
    • {@link String}
    • + *
    • {@link java.io.InputStream}
    • + *
    • {@link java.net.URL}
    • *
    * * @param source the source to read. * @param params parameters required by certain reader implementations. May be null for most readers. If non-null, - * the metadata is added to this list, and the list reference is the return value of this method. + * the metadata is added to this list, and the list reference is the return value of this method. * * @return the list of metadata read from the data source. The list is empty if the data source has no metadata. * @@ -57,20 +55,19 @@ public interface DataRasterReader extends AVList DataRaster[] read(Object source, AVList params) throws java.io.IOException; /** - * Reads and returns the metadata from a data source. - * The source may be one of the following: + * Reads and returns the metadata from a data source. The source may be one of the following: *
      - *
    • {@link java.io.File}
    • - *
    • {@link String}
    • - *
    • {@link java.io.InputStream}
    • - *
    • {@link java.net.URL}
    • + *
    • {@link java.io.File}
    • + *
    • {@link String}
    • + *
    • {@link java.io.InputStream}
    • + *
    • {@link java.net.URL}
    • *
    * * TODO: Why would the caller specify parameters to this method? * * @param source the source to examine. * @param params parameters required by certain reader implementations. May be null for most readers. If non-null, - * the metadata is added to this list, and the list reference is the return value of this method. + * the metadata is added to this list, and the list reference is the return value of this method. * * @return the list of metadata read from the data source. The list is empty if the data source has no metadata. * @@ -79,14 +76,13 @@ public interface DataRasterReader extends AVList AVList readMetadata(Object source, AVList params) throws java.io.IOException; /** - * Indicates whether a data source is imagery. - * TODO: Identify when parameters must be passed. - * The source may be one of the following: + * Indicates whether a data source is imagery. TODO: Identify when parameters must be passed. The source may be one + * of the following: *
      - *
    • {@link java.io.File}
    • - *
    • {@link String}
    • - *
    • {@link java.io.InputStream}
    • - *
    • {@link java.net.URL}
    • + *
    • {@link java.io.File}
    • + *
    • {@link String}
    • + *
    • {@link java.io.InputStream}
    • + *
    • {@link java.net.URL}
    • *
    * * @param source the source to examine. @@ -97,22 +93,21 @@ public interface DataRasterReader extends AVList boolean isImageryRaster(Object source, AVList params); /** - * Indicates whether a data source is elevation data. - * TODO: Identify when parameters must be passed. + * Indicates whether a data source is elevation data. TODO: Identify when parameters must be passed. * * The source may be one of the following: *
      - *
    • {@link java.io.File}
    • - *
    • {@link String}
    • - *
    • {@link java.io.InputStream}
    • - *
    • {@link java.net.URL}
    • + *
    • {@link java.io.File}
    • + *
    • {@link String}
    • + *
    • {@link java.io.InputStream}
    • + *
    • {@link java.net.URL}
    • *
    * * @param source the source to examine. - * @param params parameters required by certain reader implementations. May be null for most readers. - * TODO: Identify when parameters must be passed. + * @param params parameters required by certain reader implementations. May be null for most readers. TODO: Identify + * when parameters must be passed. * * @return true if the source is elevation data, otherwise false. */ boolean isElevationsRaster(Object source, AVList params); -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/data/DataRasterReaderFactory.java b/src/gov/nasa/worldwind/data/DataRasterReaderFactory.java index a61b2cb1f1..75d24be38a 100644 --- a/src/gov/nasa/worldwind/data/DataRasterReaderFactory.java +++ b/src/gov/nasa/worldwind/data/DataRasterReaderFactory.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.avlist.AVList; @@ -12,22 +11,22 @@ * @author Lado Garakanidze * @version $Id: DataRasterReaderFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface DataRasterReaderFactory -{ +public interface DataRasterReaderFactory { + /** * Search the list of available data raster readers for one that will read a specified data source. The * determination is based on both the data type and the data source reference; some readers may be able to open data * of the corresponding type but not as, for example, an InputStream or a URL. *

    * The list of readers searched is determined by the DataRasterReaderFactory associated with the current {@link - * gov.nasa.worldwind.Configuration}, as specified by the {@link gov.nasa.worldwind.avlist.AVKey#DATA_RASTER_READER_FACTORY_CLASS_NAME}. - * If no factory is specified in the configuration, {@link gov.nasa.worldwind.data.BasicDataRasterReaderFactory} is - * used. + * gov.nasa.worldwind.Configuration}, as specified by the + * {@link gov.nasa.worldwind.avlist.AVKey#DATA_RASTER_READER_FACTORY_CLASS_NAME}. If no factory is specified in the + * configuration, {@link gov.nasa.worldwind.data.BasicDataRasterReaderFactory} is used. * * @param source the source to read. May by a {@link java.io.File}, a file path, a URL or an {@link * java.io.InputStream}. * @param params optional metadata associated with the data source that might be useful in determining the data - * reader. TODO: How does the caller determine which parameters are necessary or useful? + * reader. TODO: How does the caller determine which parameters are necessary or useful? * * @return a data reader for the specified source, or null if no reader can be found. * @@ -40,10 +39,10 @@ public interface DataRasterReaderFactory * is based on both the data type and the data source reference; some readers may be able to open data of the * corresponding type but not as, for example, an InputStream or a URL. * - * @param source the source to read. May by a {@link java.io.File}, a file path, a URL or an {@link + * @param source the source to read. May by a {@link java.io.File}, a file path, a URL or an {@link * java.io.InputStream}. - * @param params optional metadata associated with the data source that might be useful in determining the data - * reader. + * @param params optional metadata associated with the data source that might be useful in determining the data + * reader. * @param readers the list of readers to search. * * @return a data reader for the specified source, or null if no reader can be found. diff --git a/src/gov/nasa/worldwind/data/DataRasterWriter.java b/src/gov/nasa/worldwind/data/DataRasterWriter.java index 04d22fe8e5..cd0fce8ec5 100644 --- a/src/gov/nasa/worldwind/data/DataRasterWriter.java +++ b/src/gov/nasa/worldwind/data/DataRasterWriter.java @@ -6,16 +6,16 @@ package gov.nasa.worldwind.data; /** - * DataRasterWriter is a common interface for objects - * which can write a data raster in a particular file format. + * DataRasterWriter is a common interface for objects which can write a data raster in a particular file + * format. * * @author dcollins * @version $Id: DataRasterWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface DataRasterWriter -{ +public interface DataRasterWriter { + /** - * Checks if a data raster could be written to a File the given format. + * Checks if a data raster could be written to a File the given format. * * @param raster a data raster to be written to a File in the given format. * @param formatSuffix a String containing the format suffix @@ -26,8 +26,8 @@ public interface DataRasterWriter boolean canWrite(DataRaster raster, String formatSuffix, java.io.File file); /** - * Writes an data raster to a File in the given format. - * If there is already a File present, its contents are discarded. + * Writes an data raster to a File in the given format. If there is already a File present, its + * contents are discarded. * * @param raster a data raster to be written * @param formatSuffix a String containing the format suffix diff --git a/src/gov/nasa/worldwind/data/DataStoreProducer.java b/src/gov/nasa/worldwind/data/DataStoreProducer.java index 38c7adff90..64192c259f 100644 --- a/src/gov/nasa/worldwind/data/DataStoreProducer.java +++ b/src/gov/nasa/worldwind/data/DataStoreProducer.java @@ -12,8 +12,8 @@ * @author dcollins * @version $Id: DataStoreProducer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface DataStoreProducer extends WWObject -{ +public interface DataStoreProducer extends WWObject { + AVList getStoreParameters(); void setStoreParameters(AVList parameters); diff --git a/src/gov/nasa/worldwind/data/GDAL.java b/src/gov/nasa/worldwind/data/GDAL.java index 3a395aaf07..8d1576b339 100644 --- a/src/gov/nasa/worldwind/data/GDAL.java +++ b/src/gov/nasa/worldwind/data/GDAL.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.exception.WWRuntimeException; @@ -19,9 +18,8 @@ * @author Lado Garakanidze * @version $Id: GDAL.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class GDAL { -public class GDAL -{ public static final int GT_SIZE = 6; public static final int GT_0_ORIGIN_LON = 0; @@ -31,40 +29,37 @@ public class GDAL public static final int GT_4_ROTATION_Y = 4; public static final int GT_5_PIXEL_HEIGHT = 5; - private GDAL() - { + private GDAL() { } - public static java.awt.geom.Point2D[] computeCornersFromGeotransform(double[] gt, int width, int height) - { - if (null == gt || gt.length != GDAL.GT_SIZE) + public static java.awt.geom.Point2D[] computeCornersFromGeotransform(double[] gt, int width, int height) { + if (null == gt || gt.length != GDAL.GT_SIZE) { return null; + } - if (gt[GDAL.GT_5_PIXEL_HEIGHT] > 0) + if (gt[GDAL.GT_5_PIXEL_HEIGHT] > 0) { gt[GDAL.GT_5_PIXEL_HEIGHT] = -gt[GDAL.GT_5_PIXEL_HEIGHT]; + } - java.awt.geom.Point2D[] corners = new java.awt.geom.Point2D[] - { - getGeoPointForRasterPoint(gt, 0, height), - getGeoPointForRasterPoint(gt, width, height), - getGeoPointForRasterPoint(gt, width, 0), - getGeoPointForRasterPoint(gt, 0, 0) - }; + java.awt.geom.Point2D[] corners = new java.awt.geom.Point2D[]{ + getGeoPointForRasterPoint(gt, 0, height), + getGeoPointForRasterPoint(gt, width, height), + getGeoPointForRasterPoint(gt, width, 0), + getGeoPointForRasterPoint(gt, 0, 0) + }; return corners; } - public static java.awt.geom.Point2D getGeoPointForRasterPoint(double[] gt, int x, int y) - { + public static java.awt.geom.Point2D getGeoPointForRasterPoint(double[] gt, int x, int y) { java.awt.geom.Point2D geoPoint = null; - if (null != gt && gt.length == 6) - { + if (null != gt && gt.length == 6) { double easting = gt[GDAL.GT_0_ORIGIN_LON] + gt[GDAL.GT_1_PIXEL_WIDTH] * (double) x - + gt[GDAL.GT_2_ROTATION_X] * (double) y; + + gt[GDAL.GT_2_ROTATION_X] * (double) y; double northing = gt[GDAL.GT_3_ORIGIN_LAT] + gt[GDAL.GT_4_ROTATION_Y] * (double) x - + gt[GDAL.GT_5_PIXEL_HEIGHT] * (double) y; + + gt[GDAL.GT_5_PIXEL_HEIGHT] * (double) y; geoPoint = new java.awt.geom.Point2D.Double(easting, northing); } @@ -72,35 +67,31 @@ public static java.awt.geom.Point2D getGeoPointForRasterPoint(double[] gt, int x return geoPoint; } - public static class Area - { + public static class Area { + protected SpatialReference srs; protected java.awt.geom.Point2D[] corners = null; protected Sector bbox = null; // its a sector for Geodetic rasters, and a BoundingBox for projected rasters - public Area(SpatialReference srs, Dataset ds) throws IllegalArgumentException - { - if (null == ds) - { + public Area(SpatialReference srs, Dataset ds) throws IllegalArgumentException { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == srs) - { + if (null == srs) { String wkt = ds.GetProjectionRef(); - if (null != wkt && wkt.length() > 0) + if (null != wkt && wkt.length() > 0) { srs = new SpatialReference(wkt); + } - if (null == srs) - { + if (null == srs) { String message = Logging.getMessage("nullValue.SpatialReferenceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } } - if (srs.IsGeographic() == 0 && srs.IsProjected() == 0) - { + if (srs.IsGeographic() == 0 && srs.IsProjected() == 0) { String message = Logging.getMessage("generic.UnexpectedCoordinateSystem", srs.ExportToWkt()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -119,45 +110,39 @@ public Area(SpatialReference srs, Dataset ds) throws IllegalArgumentException /** * calculates a Geodetic bounding box * - * @param srs A Spatial Reference, must not be null and not LOCAL (aka SCREEN) Coordinate System + * @param srs A Spatial Reference, must not be null and not LOCAL (aka SCREEN) Coordinate System * @param corners An array of 2D geographic points (java.awt.geom.Point2D) * * @return Sector * * @throws IllegalArgumentException if any of the parameters are null - * @throws WWRuntimeException in case of geo-transformation errors + * @throws WWRuntimeException in case of geo-transformation errors */ public static Sector calcBoundingSector(SpatialReference srs, java.awt.geom.Point2D[] corners) - throws IllegalArgumentException, WWRuntimeException - { - if (null == srs) - { + throws IllegalArgumentException, WWRuntimeException { + if (null == srs) { String message = Logging.getMessage("nullValue.SpatialReferenceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == corners) - { + if (null == corners) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Sector bbox = null; - try - { + try { double minx = Double.MAX_VALUE, maxx = -Double.MAX_VALUE; double miny = Double.MAX_VALUE, maxy = -Double.MAX_VALUE; CoordinateTransformation ct = new CoordinateTransformation(srs, GDALUtils.createGeographicSRS()); - for (java.awt.geom.Point2D corner : corners) - { + for (java.awt.geom.Point2D corner : corners) { double[] point = ct.TransformPoint(corner.getX(), corner.getY()); - if (null != point) - { + if (null != point) { minx = (point[0] < minx) ? point[0] : minx; maxx = (point[0] > maxx) ? point[0] : maxx; miny = (point[1] < miny) ? point[1] : miny; @@ -165,9 +150,7 @@ public static Sector calcBoundingSector(SpatialReference srs, java.awt.geom.Poin } } bbox = Sector.fromDegrees(miny, maxy, minx, maxx); - } - catch (Throwable t) - { + } catch (Throwable t) { String error = GDALUtils.getErrorMessage(); String reason = (null != error && error.length() > 0) ? error : t.getMessage(); String message = Logging.getMessage("generic.ExceptionWhileTransformation", reason); @@ -178,16 +161,13 @@ public static Sector calcBoundingSector(SpatialReference srs, java.awt.geom.Poin } protected Area(SpatialReference srs, double minY, double maxY, double minX, double maxX) - throws IllegalArgumentException - { - if (null == srs) - { + throws IllegalArgumentException { + if (null == srs) { String message = Logging.getMessage("nullValue.SpatialReferenceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (srs.IsGeographic() == 0 && srs.IsProjected() == 0) - { + if (srs.IsGeographic() == 0 && srs.IsProjected() == 0) { String message = Logging.getMessage("generic.UnexpectedCoordinateSystem", srs.ExportToWkt()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -196,16 +176,14 @@ protected Area(SpatialReference srs, double minY, double maxY, double minX, doub this.srs = srs.Clone(); this.makeCorners(minY, maxY, minX, maxX); - if (this.srs.IsGeographic() > 0) - { + if (this.srs.IsGeographic() > 0) { this.bbox = Sector.fromDegrees(minY, maxY, minX, maxX); - } - else + } else { this.bbox = calcBoundingSector(this.srs, this.corners); + } } - protected void makeCorners(double minY, double maxY, double minX, double maxX) - { + protected void makeCorners(double minY, double maxY, double minX, double maxX) { double xWest, yNorth, xEast, ySouth; xWest = Math.min(minX, maxX); @@ -213,31 +191,27 @@ protected void makeCorners(double minY, double maxY, double minX, double maxX) ySouth = Math.min(minY, maxY); yNorth = Math.max(minY, maxY); - this.corners = new java.awt.geom.Point2D[] { + this.corners = new java.awt.geom.Point2D[]{ new java.awt.geom.Point2D.Double(xWest, ySouth), // SW corner new java.awt.geom.Point2D.Double(xEast, ySouth), // SE corner new java.awt.geom.Point2D.Double(xEast, yNorth), // NE corner - new java.awt.geom.Point2D.Double(xWest, yNorth) // NW corner + new java.awt.geom.Point2D.Double(xWest, yNorth) // NW corner }; } - public Area(SpatialReference srs, Sector sector) throws IllegalArgumentException - { - if (null == sector) - { + public Area(SpatialReference srs, Sector sector) throws IllegalArgumentException { + if (null == sector) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == srs) - { + if (null == srs) { String message = Logging.getMessage("nullValue.SpatialReferenceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (srs.IsGeographic() == 0 && srs.IsProjected() == 0) - { + if (srs.IsGeographic() == 0 && srs.IsProjected() == 0) { String message = Logging.getMessage("generic.UnexpectedCoordinateSystem", srs.ExportToWkt()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -250,11 +224,9 @@ public Area(SpatialReference srs, Sector sector) throws IllegalArgumentException CoordinateTransformation ct = new CoordinateTransformation(geodetic, this.srs); double minX = Double.MAX_VALUE, maxX = -Double.MAX_VALUE, minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE; - for (LatLon ll : sector.getCorners()) - { + for (LatLon ll : sector.getCorners()) { double[] point = ct.TransformPoint(ll.getLongitude().degrees, ll.getLatitude().degrees); - if (null != point) - { + if (null != point) { minX = (point[0] < minX) ? point[0] : minX; maxX = (point[0] > maxX) ? point[0] : maxX; minY = (point[1] < minY) ? point[1] : minY; @@ -264,80 +236,66 @@ public Area(SpatialReference srs, Sector sector) throws IllegalArgumentException this.makeCorners(minY, maxY, minX, maxX); } - public boolean isGeographic() - { + public boolean isGeographic() { return (null != this.srs && this.srs.IsGeographic() > 0); } - public boolean isProjected() - { + public boolean isProjected() { return (null != this.srs && this.srs.IsProjected() > 0); } - public SpatialReference getSpatialReference() - { + public SpatialReference getSpatialReference() { return this.srs.Clone(); } - public Sector getSector() - { + public Sector getSector() { return this.bbox; } - public Area getBoundingArea() - { + public Area getBoundingArea() { return new Area(this.srs.Clone(), this.getMinY(), this.getMaxY(), this.getMinX(), this.getMaxX()); } - public java.awt.geom.Point2D[] getCorners() - { + public java.awt.geom.Point2D[] getCorners() { return this.corners.clone(); } @Override - public String toString() - { + public String toString() { StringBuffer sb = new StringBuffer("Area { "); - for (java.awt.geom.Point2D corner : this.corners) - { + for (java.awt.geom.Point2D corner : this.corners) { sb.append('(').append(corner.getX()).append(',').append(corner.getY()).append(") "); } sb.append('}'); return sb.toString(); } - public double getMinX() - { + public double getMinX() { return GDAL.getMinX(this.corners); } - public double getMaxX() - { + public double getMaxX() { return GDAL.getMaxX(this.corners); } - public double getMinY() - { + public double getMinY() { return GDAL.getMinY(this.corners); } - public double getMaxY() - { + public double getMaxY() { return GDAL.getMaxY(this.corners); } - public Area intersection(Sector sector) throws WWRuntimeException - { + public Area intersection(Sector sector) throws WWRuntimeException { return this.intersection(new Area(this.srs, sector)); } - public Area intersection(Area that) throws WWRuntimeException - { - if (null == that) + public Area intersection(Area that) throws WWRuntimeException { + if (null == that) { return null; + } - if (this.srs.IsSame(that.getSpatialReference()) == 0) - { + if (this.srs.IsSame(that.getSpatialReference()) == 0) { String message = Logging.getMessage("generic.SectorMismatch", this, that); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -345,51 +303,56 @@ public Area intersection(Area that) throws WWRuntimeException double minY = Math.max(this.getMinY(), that.getMinY()); double maxY = Math.min(this.getMaxY(), that.getMaxY()); - if (minY > maxY) + if (minY > maxY) { return null; + } double minX = Math.max(this.getMinX(), that.getMinX()); double maxX = Math.min(this.getMaxX(), that.getMaxX()); - if (minX > maxX) + if (minX > maxX) { return null; + } return new Area(this.srs.Clone(), minY, maxY, minX, maxX); } - public boolean contains(Area that) throws WWRuntimeException - { - if (null == that) + public boolean contains(Area that) throws WWRuntimeException { + if (null == that) { return false; + } - if (this.srs.IsSame(that.getSpatialReference()) == 0) - { + if (this.srs.IsSame(that.getSpatialReference()) == 0) { String message = Logging.getMessage("generic.SectorMismatch", this, that); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (that.getMinX() < this.getMinX()) + if (that.getMinX() < this.getMinX()) { return false; - if (that.getMaxX() > this.getMaxX()) + } + if (that.getMaxX() > this.getMaxX()) { return false; - if (that.getMinY() < this.getMinY()) + } + if (that.getMinY() < this.getMinY()) { return false; - if (that.getMaxY() > this.getMaxY()) + } + if (that.getMaxY() > this.getMaxY()) { return false; + } return true; } - public java.awt.geom.AffineTransform computeGeoToRasterTransform(int width, int height) - { + public java.awt.geom.AffineTransform computeGeoToRasterTransform(int width, int height) { double ty = -this.getMaxY(); double tx = -this.getMinX(); double deltaX = this.getMaxX() - this.getMinX(); double deltaY = this.getMaxY() - this.getMinY(); - if (deltaX == 0d || deltaY == 0d) + if (deltaX == 0d || deltaY == 0d) { return null; + } double sy = -(height / deltaY); double sx = (width / deltaX); @@ -401,17 +364,15 @@ public java.awt.geom.AffineTransform computeGeoToRasterTransform(int width, int } public java.awt.Rectangle computeClipRect(int rasterWidth, int rasterHeight, Area clipArea) - throws IllegalArgumentException - { - if (null == clipArea) - { + throws IllegalArgumentException { + if (null == clipArea) { String message = Logging.getMessage("nullValue.AreaIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - java.awt.geom.AffineTransform geoToRaster = - this.computeGeoToRasterTransform(rasterWidth, rasterHeight); + java.awt.geom.AffineTransform geoToRaster + = this.computeGeoToRasterTransform(rasterWidth, rasterHeight); java.awt.geom.Point2D geoPoint = new java.awt.geom.Point2D.Double(); java.awt.geom.Point2D ul = new java.awt.geom.Point2D.Double(); @@ -432,10 +393,8 @@ public java.awt.Rectangle computeClipRect(int rasterWidth, int rasterHeight, Are } } - public static AffineTransform getAffineTransform(Dataset ds) throws IllegalArgumentException - { - if (null == ds) - { + public static AffineTransform getAffineTransform(Dataset ds) throws IllegalArgumentException { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -445,39 +404,34 @@ public static AffineTransform getAffineTransform(Dataset ds) throws IllegalArgum ds.GetGeoTransform(gt); return new AffineTransform( - gt[GDAL.GT_1_PIXEL_WIDTH], - gt[GDAL.GT_4_ROTATION_Y], gt[GDAL.GT_2_ROTATION_X], - ((gt[GDAL.GT_5_PIXEL_HEIGHT] > 0) ? -gt[GDAL.GT_5_PIXEL_HEIGHT] : gt[GDAL.GT_5_PIXEL_HEIGHT]), - gt[GDAL.GT_0_ORIGIN_LON], gt[GDAL.GT_3_ORIGIN_LAT]); + gt[GDAL.GT_1_PIXEL_WIDTH], + gt[GDAL.GT_4_ROTATION_Y], gt[GDAL.GT_2_ROTATION_X], + ((gt[GDAL.GT_5_PIXEL_HEIGHT] > 0) ? -gt[GDAL.GT_5_PIXEL_HEIGHT] : gt[GDAL.GT_5_PIXEL_HEIGHT]), + gt[GDAL.GT_0_ORIGIN_LON], gt[GDAL.GT_3_ORIGIN_LAT]); } public static AffineTransform getAffineTransform(Dataset ds, int newWidth, int newHeight) - throws IllegalArgumentException - { - if (null == ds) - { + throws IllegalArgumentException { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newWidth <= 0) - { + if (newWidth <= 0) { String message = Logging.getMessage("generic.InvalidWidth", newWidth); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newHeight <= 0) - { + if (newHeight <= 0) { String message = Logging.getMessage("generic.InvalidHeight", newHeight); Logging.logger().severe(message); throw new IllegalArgumentException(message); } AffineTransform atx = getAffineTransform(ds); - if (null != atx) - { + if (null != atx) { double sy = ((double) ds.getRasterYSize() / (double) newHeight); double sx = ((double) ds.getRasterXSize() / (double) newWidth); atx.scale(sx, sy); @@ -497,72 +451,60 @@ public static AffineTransform getAffineTransform(Dataset ds, int newWidth, int n // dy, gt[GDAL.GT_0_ORIGIN_LON], gt[GDAL.GT_3_ORIGIN_LAT] ); } - public static double getMinX(java.awt.geom.Point2D[] points) throws IllegalArgumentException - { - if (null == points) - { + public static double getMinX(java.awt.geom.Point2D[] points) throws IllegalArgumentException { + if (null == points) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } double min = Double.MAX_VALUE; - for (java.awt.geom.Point2D point : points) - { + for (java.awt.geom.Point2D point : points) { min = (point.getX() < min) ? point.getX() : min; } return min; } - public static double getMaxX(java.awt.geom.Point2D[] points) throws IllegalArgumentException - { - if (null == points) - { + public static double getMaxX(java.awt.geom.Point2D[] points) throws IllegalArgumentException { + if (null == points) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } double max = -Double.MAX_VALUE; - for (java.awt.geom.Point2D point : points) - { + for (java.awt.geom.Point2D point : points) { max = (point.getX() > max) ? point.getX() : max; } return max; } - public static double getMinY(java.awt.geom.Point2D[] points) throws IllegalArgumentException - { - if (null == points) - { + public static double getMinY(java.awt.geom.Point2D[] points) throws IllegalArgumentException { + if (null == points) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } double min = Double.MAX_VALUE; - for (java.awt.geom.Point2D point : points) - { + for (java.awt.geom.Point2D point : points) { min = (point.getY() < min) ? point.getY() : min; } return min; } - public static double getMaxY(java.awt.geom.Point2D[] points) throws IllegalArgumentException - { - if (null == points) - { + public static double getMaxY(java.awt.geom.Point2D[] points) throws IllegalArgumentException { + if (null == points) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } double max = -Double.MAX_VALUE; - for (java.awt.geom.Point2D point : points) - { + for (java.awt.geom.Point2D point : points) { max = (point.getY() > max) ? point.getY() : max; } diff --git a/src/gov/nasa/worldwind/data/GDALDataRaster.java b/src/gov/nasa/worldwind/data/GDALDataRaster.java index f1753c8828..57b25780c3 100644 --- a/src/gov/nasa/worldwind/data/GDALDataRaster.java +++ b/src/gov/nasa/worldwind/data/GDALDataRaster.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.Configuration; @@ -26,9 +25,8 @@ * @author Lado Garakanidze * @version $Id: GDALDataRaster.java 2678 2015-01-24 22:07:39Z tgaskins $ */ +public class GDALDataRaster extends AbstractDataRaster implements Cacheable { -public class GDALDataRaster extends AbstractDataRaster implements Cacheable -{ protected Dataset dsVRT = null; protected SpatialReference srs; protected File srcFile = null; @@ -37,8 +35,7 @@ public class GDALDataRaster extends AbstractDataRaster implements Cacheable protected static final int DEFAULT_MAX_RASTER_SIZE_LIMIT = 3072; - protected static int getMaxRasterSizeLimit() - { + protected static int getMaxRasterSizeLimit() { return DEFAULT_MAX_RASTER_SIZE_LIMIT; } @@ -48,44 +45,36 @@ protected static int getMaxRasterSizeLimit() * @param source the location of the local file, expressed as either a String path, a File, or a file URL. * * @throws IllegalArgumentException if the source is null - * @throws FileNotFoundException if the source (File) does not exist + * @throws FileNotFoundException if the source (File) does not exist */ - public GDALDataRaster(Object source) throws IllegalArgumentException, FileNotFoundException - { + public GDALDataRaster(Object source) throws IllegalArgumentException, FileNotFoundException { this(source, false); } /** * Opens a data raster * - * @param source the location of the local file, expressed as either a String path, a File, or a file - * URL. + * @param source the location of the local file, expressed as either a String path, a File, or a file URL. * @param quickReadingMode if quick reading mode is enabled GDAL will not spend much time on heavy calculations, - * like for example calculating Min/Max for entire elevation raster + * like for example calculating Min/Max for entire elevation raster * * @throws IllegalArgumentException if the source is null - * @throws FileNotFoundException if the source (File) does not exist + * @throws FileNotFoundException if the source (File) does not exist */ public GDALDataRaster(Object source, boolean quickReadingMode) - throws IllegalArgumentException, FileNotFoundException - { + throws IllegalArgumentException, FileNotFoundException { super(); File file = WWIO.getFileForLocalAddress(source); - if (null == file) - { + if (null == file) { String message; - if (null != source) - { + if (null != source) { message = Logging.getMessage("generic.UnrecognizedSourceType", source.getClass().getName()); - } - else - { + } else { message = Logging.getMessage("nullValue.SourceIsNull"); } - if (!quickReadingMode) - { + if (!quickReadingMode) { Logging.logger().finest(message); } @@ -94,22 +83,20 @@ public GDALDataRaster(Object source, boolean quickReadingMode) this.srcFile = file; String name = this.srcFile.getName(); - if (null != name && name.length() > 0) - { + if (null != name && name.length() > 0) { this.setValue(AVKey.DATASET_NAME, name); this.setValue(AVKey.DISPLAY_NAME, name); this.setValue(AVKey.FILE, this.srcFile); } Dataset ds = GDALUtils.open(file, quickReadingMode); - if (ds == null) - { + if (ds == null) { String message = GDALUtils.getErrorMessage(); - if( WWUtil.isEmpty(message) ) + if (WWUtil.isEmpty(message)) { message = Logging.getMessage("nullValue.DataSetIsNull"); + } - if (!quickReadingMode) - { + if (!quickReadingMode) { Logging.logger().severe(message); } throw new IllegalArgumentException(message); @@ -127,19 +114,15 @@ public GDALDataRaster(Object source, boolean quickReadingMode) * * @throws IllegalArgumentException if the Sector is null */ - public void setSector(Sector sector) throws IllegalArgumentException - { - if (null == sector) - { + public void setSector(Sector sector) throws IllegalArgumentException { + if (null == sector) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (!this.hasKey(AVKey.COORDINATE_SYSTEM) - || AVKey.COORDINATE_SYSTEM_UNKNOWN.equals(this.getValue(AVKey.COORDINATE_SYSTEM)) - ) - { + || AVKey.COORDINATE_SYSTEM_UNKNOWN.equals(this.getValue(AVKey.COORDINATE_SYSTEM))) { this.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC); } @@ -150,25 +133,20 @@ public void setSector(Sector sector) throws IllegalArgumentException this.area = new GDAL.Area(this.srs, sector); this.setValue(AVKey.GDAL_AREA, this.area); - if (this.width > 0) - { + if (this.width > 0) { double dx = sector.getDeltaLonDegrees() / this.width; this.setValue(AVKey.PIXEL_WIDTH, dx); } - if (this.height > 0) - { + if (this.height > 0) { double dy = sector.getDeltaLatDegrees() / this.height; this.setValue(AVKey.PIXEL_WIDTH, dy); } - if (this.dsVRT != null) - { - if (!"VRT".equalsIgnoreCase(this.dsVRT.GetDriver().getShortName())) - { + if (this.dsVRT != null) { + if (!"VRT".equalsIgnoreCase(this.dsVRT.GetDriver().getShortName())) { Driver vrt = gdal.GetDriverByName("VRT"); - if (null != vrt) - { + if (null != vrt) { this.dsVRT = vrt.CreateCopy("", this.dsVRT); } } @@ -177,21 +155,18 @@ public void setSector(Sector sector) throws IllegalArgumentException this.dsVRT.SetGeoTransform(gt); String error = GDALUtils.getErrorMessage(); - if (error != null) - { + if (error != null) { String message = Logging.getMessage("gdal.InternalError", error); Logging.logger().severe(message); // throw new WWRuntimeException( message ); } - if (null != this.srs) - { + if (null != this.srs) { this.dsVRT.SetProjection(srs.ExportToWkt()); } error = GDALUtils.getErrorMessage(); - if (error != null) - { + if (error != null) { String message = Logging.getMessage("gdal.InternalError", error); Logging.logger().severe(message); // throw new WWRuntimeException( message ); @@ -201,42 +176,33 @@ public void setSector(Sector sector) throws IllegalArgumentException } } - protected SpatialReference readSpatialReference(Dataset ds) - { - if (null == ds) - { + protected SpatialReference readSpatialReference(Dataset ds) { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new WWRuntimeException(message); } String proj = ds.GetProjectionRef(); - if (null == proj || 0 == proj.length()) - { + if (null == proj || 0 == proj.length()) { proj = ds.GetProjection(); } - if ((null == proj || 0 == proj.length()) && null != this.srcFile) - { + if ((null == proj || 0 == proj.length()) && null != this.srcFile) { // check if there is a corresponding .PRJ (or .prj file) String pathToPrjFile = WWIO.replaceSuffix(this.srcFile.getAbsolutePath(), ".prj"); File prjFile = new File(pathToPrjFile); - if (!prjFile.exists() && Configuration.isUnixOS()) - { + if (!prjFile.exists() && Configuration.isUnixOS()) { pathToPrjFile = WWIO.replaceSuffix(this.srcFile.getAbsolutePath(), ".PRJ"); prjFile = new File(pathToPrjFile); } - try - { - if (prjFile.exists()) - { + try { + if (prjFile.exists()) { proj = WWIO.readTextFile(prjFile); } - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.UnknownProjection", proj); Logging.logger().severe(message); } @@ -244,13 +210,11 @@ protected SpatialReference readSpatialReference(Dataset ds) SpatialReference srs = null; - if (!WWUtil.isEmpty(proj)) - { + if (!WWUtil.isEmpty(proj)) { srs = new SpatialReference(proj); } - if ((null == srs || srs.IsLocal() == 1) && this.hasKey(AVKey.SPATIAL_REFERENCE_WKT)) - { + if ((null == srs || srs.IsLocal() == 1) && this.hasKey(AVKey.SPATIAL_REFERENCE_WKT)) { proj = this.getStringValue(AVKey.SPATIAL_REFERENCE_WKT); srs = new SpatialReference(proj); } @@ -258,12 +222,10 @@ protected SpatialReference readSpatialReference(Dataset ds) return srs; } - public GDALDataRaster(Dataset ds) throws IllegalArgumentException - { + public GDALDataRaster(Dataset ds) throws IllegalArgumentException { super(); - if (null == ds) - { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -285,12 +247,11 @@ public GDALDataRaster(Dataset ds) throws IllegalArgumentException * AVKey.SECTOR - in case of Geographic CS, contains a regular Geographic Sector defined by lat/lon coordinates of * corners in case of Projected CS, contains a bounding box of the area * - * @param ds GDAL's Dataset + * @param ds GDAL's Dataset * @param quickReadingMode if quick reading mode is enabled GDAL will not spend much time on heavy calculations, - * like for example calculating Min/Max for entire elevation raster + * like for example calculating Min/Max for entire elevation raster */ - protected void init(Dataset ds, boolean quickReadingMode) - { + protected void init(Dataset ds, boolean quickReadingMode) { String srcWKT = null; AVList extParams = new AVListImpl(); @@ -299,8 +260,7 @@ protected void init(Dataset ds, boolean quickReadingMode) this.setValues(params); this.srs = this.readSpatialReference(ds); - if (null != this.srs) - { + if (null != this.srs) { srcWKT = this.srs.ExportToWkt(); this.setValue(AVKey.SPATIAL_REFERENCE_WKT, this.srs.ExportToWkt()); } @@ -319,10 +279,8 @@ protected void init(Dataset ds, boolean quickReadingMode) proj = (null == proj || 0 == proj.length()) ? ds.GetProjection() : proj; if ((null == proj || 0 == proj.length()) - && (srcWKT == null || 0 == srcWKT.length()) - && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(this.getValue(AVKey.COORDINATE_SYSTEM)) - ) - { // this is a case where file has GEODETIC GeoTranform matrix but does not have CS or PROJECTION data + && (srcWKT == null || 0 == srcWKT.length()) + && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(this.getValue(AVKey.COORDINATE_SYSTEM))) { // this is a case where file has GEODETIC GeoTranform matrix but does not have CS or PROJECTION data this.srs = GDALUtils.createGeographicSRS(); srcWKT = this.srs.ExportToWkt(); this.setValue(AVKey.SPATIAL_REFERENCE_WKT, this.srs.ExportToWkt()); @@ -334,40 +292,30 @@ protected void init(Dataset ds, boolean quickReadingMode) // most real drivers do not support overriding properties // However, JP2 files are 3 times slow when wrapped in the VRT dataset // therefore, we only wrap in to VRT when needed - if ((null == proj || 0 == proj.length()) && (null != srcWKT && 0 < srcWKT.length())) - { - try - { + if ((null == proj || 0 == proj.length()) && (null != srcWKT && 0 < srcWKT.length())) { + try { Driver vrt = gdal.GetDriverByName("VRT"); - if (null != vrt) - { + if (null != vrt) { Dataset dsWarp = vrt.CreateCopy("", ds); dsWarp.SetProjection(srcWKT); this.dsVRT = dsWarp; - } - else - { + } else { String message = Logging.getMessage("gdal.InternalError", GDALUtils.getErrorMessage()); Logging.logger().severe(message); throw new WWRuntimeException(message); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.SEVERE, e.getMessage(), e); } } } - public AVList getMetadata() - { + public AVList getMetadata() { return this.copy(); } - public void drawOnTo(DataRaster canvas) - { - if (canvas == null) - { + public void drawOnTo(DataRaster canvas) { + if (canvas == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -376,17 +324,14 @@ public void drawOnTo(DataRaster canvas) this.doDrawOnTo(canvas); } - protected void doDrawOnTo(DataRaster canvas) - { - try - { + protected void doDrawOnTo(DataRaster canvas) { + try { Sector imageSector = this.getSector(); Sector canvasSector = canvas.getSector(); Sector overlap = null; - if ( null == imageSector || null == canvasSector || !this.intersects(canvasSector) - || null == (overlap = imageSector.intersection(canvasSector))) - { + if (null == imageSector || null == canvasSector || !this.intersects(canvasSector) + || null == (overlap = imageSector.intersection(canvasSector))) { String msg = Logging.getMessage("generic.SectorRequestedOutsideCoverageArea", canvasSector, imageSector); Logging.logger().finest(msg); return; @@ -396,8 +341,7 @@ protected void doDrawOnTo(DataRaster canvas) // clipping sector is specified, then perform no clipping. We compute the clip region for the destination // raster because this region is used by AWT to limit which pixels are rasterized to the destination. java.awt.Rectangle clipRect = this.computeClipRect(overlap, canvas); - if (null == clipRect || clipRect.width == 0 || clipRect.height == 0 ) - { + if (null == clipRect || clipRect.width == 0 || clipRect.height == 0) { return; } @@ -405,72 +349,64 @@ protected void doDrawOnTo(DataRaster canvas) // copy parent raster keys/values; only those key/value will be copied that do exist in the parent raster // AND does NOT exist in the requested raster - String[] keysToCopy = new String[] { + String[] keysToCopy = new String[]{ AVKey.DATA_TYPE, AVKey.MISSING_DATA_SIGNAL, AVKey.BYTE_ORDER, AVKey.PIXEL_FORMAT, AVKey.ELEVATION_UNIT }; WWUtil.copyValues(this, params, keysToCopy, false); - DataRaster raster = this.doGetSubRaster(clipRect.width, clipRect.height, overlap, params ); + DataRaster raster = this.doGetSubRaster(clipRect.width, clipRect.height, overlap, params); raster.drawOnTo(canvas); - } - catch (WWRuntimeException wwe) - { + } catch (WWRuntimeException wwe) { Logging.logger().severe(wwe.getMessage()); - } - catch (Exception e) - { + } catch (Exception e) { String message = this.composeExceptionReason(e); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - protected String composeExceptionReason(Throwable t) - { + protected String composeExceptionReason(Throwable t) { StringBuilder sb = new StringBuilder(); - if (null != t.getMessage()) + if (null != t.getMessage()) { sb.append(t.getMessage()); - else if (null != t.getCause()) + } else if (null != t.getCause()) { sb.append(t.getCause().getMessage()); + } - if (sb.length() > 0) + if (sb.length() > 0) { sb.append(" : "); + } - if (null != this.srcFile) + if (null != this.srcFile) { sb.append(this.srcFile); + } return sb.toString(); } - public void dispose() - { - if (this.dsVRT != null) - { + public void dispose() { + if (this.dsVRT != null) { this.dsVRT.delete(); this.dsVRT = null; } this.clearList(); - if (this.srcFile != null) - { + if (this.srcFile != null) { this.srcFile = null; } this.srs = null; } - protected Dataset createMaskDataset(int width, int height, Sector sector) - { - if (width <= 0) - { + protected Dataset createMaskDataset(int width, int height, Sector sector) { + if (width <= 0) { String message = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("generic.InvalidHeight", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -485,8 +421,7 @@ protected Dataset createMaskDataset(int width, int height, Sector sector) band.SetNoDataValue(missingSignal); band.Fill(missingSignal); - if (null != sector) - { + if (null != sector) { SpatialReference t_srs = GDALUtils.createGeographicSRS(); String t_srs_wkt = t_srs.ExportToWkt(); ds.SetProjection(t_srs_wkt); @@ -503,47 +438,40 @@ protected Dataset createMaskDataset(int width, int height, Sector sector) * dataset from an overview, and/or we may clip only the requested area. This will accelerate reprojection (if * needed), because the reporjection will be done on much smaller dataset. * - * @param reqWidth width of the requested area + * @param reqWidth width of the requested area * @param reqHeight height of the requested area * @param reqSector sector of the requested area * * @return a dataset with the best suitable raster for the request */ - protected Dataset getBestSuitedDataset(int reqWidth, int reqHeight, Sector reqSector) - { - if (reqWidth <= 0) - { + protected Dataset getBestSuitedDataset(int reqWidth, int reqHeight, Sector reqSector) { + if (reqWidth <= 0) { String message = Logging.getMessage("generic.InvalidWidth", reqWidth); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (reqHeight <= 0) - { + if (reqHeight <= 0) { String message = Logging.getMessage("generic.InvalidHeight", reqHeight); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (reqSector == null) - { + if (reqSector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == this.dsVRT) - { + if (null == this.dsVRT) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (null == this.area) - { + if (null == this.area) { return this.dsVRT; } Sector extent = this.getSector(); - if (!this.intersects(reqSector)) - { + if (!this.intersects(reqSector)) { String msg = Logging.getMessage("generic.SectorRequestedOutsideCoverageArea", reqSector, extent); Logging.logger().finest(msg); throw new WWRuntimeException(msg); @@ -551,8 +479,7 @@ protected Dataset getBestSuitedDataset(int reqWidth, int reqHeight, Sector reqSe Object cs = this.getValue(AVKey.COORDINATE_SYSTEM); if (null == cs - || (!AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs) && !AVKey.COORDINATE_SYSTEM_PROJECTED.equals(cs))) - { + || (!AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs) && !AVKey.COORDINATE_SYSTEM_PROJECTED.equals(cs))) { String msg = (null == cs) ? "generic.UnspecifiedCoordinateSystem" : "generic.UnsupportedCoordinateSystem"; String reason = Logging.getMessage(msg, cs); Logging.logger().finest(Logging.getMessage("generic.CannotCreateRaster", reason)); @@ -563,14 +490,12 @@ protected Dataset getBestSuitedDataset(int reqWidth, int reqHeight, Sector reqSe double reqHeightRes = Math.abs(reqSector.getDeltaLatDegrees() / (double) reqHeight); int bandCount = this.dsVRT.getRasterCount(); - if (bandCount == 0) - { + if (bandCount == 0) { return this.dsVRT; } Band firstBand = this.dsVRT.GetRasterBand(1); - if (null == firstBand) - { + if (null == firstBand) { return this.dsVRT; } @@ -584,70 +509,57 @@ protected Dataset getBestSuitedDataset(int reqWidth, int reqHeight, Sector reqSe int srcHeight = this.getHeight(); int srcWidth = this.getWidth(); - for (int i = 0; i < firstBand.GetOverviewCount(); i++) - { + for (int i = 0; i < firstBand.GetOverviewCount(); i++) { Band overview = firstBand.GetOverview(i); - if (null == overview) - { + if (null == overview) { continue; } int w = overview.getXSize(); int h = overview.getYSize(); - if (0 == h || 0 == w) - { + if (0 == h || 0 == w) { continue; } // double ovWidthRes = Math.abs(extent.getDeltaLonDegrees() / (double) w); double ovHeightRes = Math.abs(extent.getDeltaLatDegrees() / (double) h); - if (ovHeightRes <= reqHeightRes /*&& ovWidthRes <= reqWidthRes*/) - { + if (ovHeightRes <= reqHeightRes /*&& ovWidthRes <= reqWidthRes*/) { bestOverviewIdx = i; srcWidth = w; srcHeight = h; continue; - } - else - { + } else { break; } } - if (!isNorthUpRaster) - { + if (!isNorthUpRaster) { // It is a non-Northup oriented raster (raster with rotation coefficients in the GT matrix) - if (bestOverviewIdx == -1) - { + if (bestOverviewIdx == -1) { // no overviews, working with a full resolution raster srcHeight = this.getHeight(); srcWidth = this.getWidth(); - for (int i = 0; true; i++) - { + for (int i = 0; true; i++) { double scale = Math.pow(2, i); double h = Math.floor(this.getHeight() / scale); double w = Math.floor(this.getWidth() / scale); double ovWidthRes = Math.abs(extent.getDeltaLonDegrees() / w); double ovHeightRes = Math.abs(extent.getDeltaLatDegrees() / h); - if (ovHeightRes <= reqHeightRes && ovWidthRes <= reqWidthRes) - { + if (ovHeightRes <= reqHeightRes && ovWidthRes <= reqWidthRes) { srcWidth = (int) w; srcHeight = (int) h; continue; - } - else - { + } else { break; } } } - if (srcHeight > getMaxRasterSizeLimit() || srcWidth > getMaxRasterSizeLimit()) - { + if (srcHeight > getMaxRasterSizeLimit() || srcWidth > getMaxRasterSizeLimit()) { return this.dsVRT; } @@ -659,29 +571,24 @@ protected Dataset getBestSuitedDataset(int reqWidth, int reqHeight, Sector reqSe return (null != ds) ? ds : this.dsVRT; } - if (bestOverviewIdx == -1) - { + if (bestOverviewIdx == -1) { // no overview was found, will use image's source bands srcWidth = this.getWidth(); srcHeight = this.getHeight(); // return this.dsVRT; - } - else - { + } else { String msg = Logging.getMessage("gdal.UseOverviewRaster", srcWidth, srcHeight, reqWidth, reqHeight); Logging.logger().finest(msg); } return this.buildNorthUpDatasetFromOverview(reqSector, reqWidth, reqHeight, bestOverviewIdx, srcWidth, - srcHeight); + srcHeight); } protected Dataset buildNorthUpDatasetFromOverview(Sector reqSector, int reqWidth, int reqHeight, - int bestOverviewIdx, int srcWidth, int srcHeight) - { + int bestOverviewIdx, int srcWidth, int srcHeight) { GDAL.Area cropArea = this.area.intersection(new GDAL.Area(this.srs, reqSector).getBoundingArea()); - if (null == cropArea) - { + if (null == cropArea) { String msg = Logging.getMessage("generic.SectorRequestedOutsideCoverageArea", reqSector, this.area); Logging.logger().finest(msg); throw new WWRuntimeException(msg); @@ -708,28 +615,24 @@ protected Dataset buildNorthUpDatasetFromOverview(Sector reqSector, int reqWidth clipHeight = (clipHeight > srcHeight) ? srcHeight : clipHeight; Driver drv = gdal.GetDriverByName("MEM"); - if (null == drv) - { + if (null == drv) { return this.dsVRT; } int bandCount = this.dsVRT.getRasterCount(); - if (bandCount == 0) - { + if (bandCount == 0) { return this.dsVRT; } Band firstBand = this.dsVRT.GetRasterBand(1); - if (null == firstBand) - { + if (null == firstBand) { return this.dsVRT; } int dataType = firstBand.GetRasterDataType(); Dataset ds = drv.Create("cropped", reqWidth, reqHeight, bandCount, dataType); - if (this.srs != null) - { + if (this.srs != null) { ds.SetProjection(this.srs.ExportToWkt()); } @@ -748,32 +651,27 @@ protected Dataset buildNorthUpDatasetFromOverview(Sector reqSector, int reqWidth data.order(ByteOrder.nativeOrder()); Double nodata = this.hasKey(AVKey.MISSING_DATA_SIGNAL) ? (Double) this.getValue(AVKey.MISSING_DATA_SIGNAL) - : null; + : null; - for (int i = 0; i < bandCount; i++) - { + for (int i = 0; i < bandCount; i++) { Band srcBand = this.dsVRT.GetRasterBand(i + 1); - if (null == srcBand) - { + if (null == srcBand) { continue; } Band ovBand = (bestOverviewIdx == -1) ? srcBand : srcBand.GetOverview(bestOverviewIdx); - if (null == ovBand) - { + if (null == ovBand) { continue; } Band destBand = ds.GetRasterBand(i + 1); - if (null != nodata) - { + if (null != nodata) { destBand.SetNoDataValue(nodata); } int colorInt = srcBand.GetColorInterpretation(); destBand.SetColorInterpretation(colorInt); - if (colorInt == gdalconst.GCI_PaletteIndex) - { + if (colorInt == gdalconst.GCI_PaletteIndex) { destBand.SetColorTable(srcBand.GetColorTable()); } @@ -787,22 +685,18 @@ protected Dataset buildNorthUpDatasetFromOverview(Sector reqSector, int reqWidth return ds; } - protected Dataset buildNonNorthUpDatasetFromOverview(int bestOverviewIdx, int destWidth, int destHeight) - { - if (null == this.dsVRT) - { + protected Dataset buildNonNorthUpDatasetFromOverview(int bestOverviewIdx, int destWidth, int destHeight) { + if (null == this.dsVRT) { return null; } Driver drv = gdal.GetDriverByName("MEM"); - if (null == drv) - { + if (null == drv) { return null; } Band firstBand = this.dsVRT.GetRasterBand(1); - if (null == firstBand) - { + if (null == firstBand) { return null; } @@ -814,11 +708,10 @@ protected Dataset buildNonNorthUpDatasetFromOverview(int bestOverviewIdx, int de data.order(ByteOrder.nativeOrder()); Double nodata = this.hasKey(AVKey.MISSING_DATA_SIGNAL) ? (Double) this.getValue(AVKey.MISSING_DATA_SIGNAL) - : null; + : null; Dataset ds = drv.Create("overview", destWidth, destHeight, bandCount, destDataType); - if (this.srs != null) - { + if (this.srs != null) { ds.SetProjection(this.srs.ExportToWkt()); } @@ -834,36 +727,31 @@ protected Dataset buildNonNorthUpDatasetFromOverview(int bestOverviewIdx, int de ds.SetGeoTransform(gt); - for (int i = 0; i < bandCount; i++) - { + for (int i = 0; i < bandCount; i++) { Band srcBand = this.dsVRT.GetRasterBand(i + 1); - if (null == srcBand) - { + if (null == srcBand) { continue; } Band ovBand = (bestOverviewIdx == -1) ? srcBand : srcBand.GetOverview(bestOverviewIdx); - if (null == ovBand) - { + if (null == ovBand) { continue; } Band destBand = ds.GetRasterBand(i + 1); - if (null != nodata) - { + if (null != nodata) { destBand.SetNoDataValue(nodata); } int colorInt = srcBand.GetColorInterpretation(); destBand.SetColorInterpretation(colorInt); - if (colorInt == gdalconst.GCI_PaletteIndex) - { + if (colorInt == gdalconst.GCI_PaletteIndex) { destBand.SetColorTable(srcBand.GetColorTable()); } data.rewind(); ovBand.ReadRaster_Direct(0, 0, ovBand.getXSize(), ovBand.getYSize(), - destWidth, destHeight, destDataType, data); + destWidth, destHeight, destDataType, data); data.rewind(); destBand.WriteRaster_Direct(0, 0, destWidth, destHeight, destDataType, data); @@ -872,17 +760,14 @@ protected Dataset buildNonNorthUpDatasetFromOverview(int bestOverviewIdx, int de return ds; } - protected Dataset createCompatibleDataset(int width, int height, Sector sector, AVList destParams) - { - if (width <= 0) - { + protected Dataset createCompatibleDataset(int width, int height, Sector sector, AVList destParams) { + if (width <= 0) { String message = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("generic.InvalidHeight", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -893,101 +778,82 @@ protected Dataset createCompatibleDataset(int width, int height, Sector sector, Band srcBand1 = this.dsVRT.GetRasterBand(1); int bandDataType = srcBand1.getDataType(); - int[] bandColorInt = new int[] {gdalconst.GCI_RedBand, gdalconst.GCI_GreenBand, + int[] bandColorInt = new int[]{gdalconst.GCI_RedBand, gdalconst.GCI_GreenBand, gdalconst.GCI_BlueBand, gdalconst.GCI_AlphaBand}; int destNumOfBands = 4; // RGBA by default String pixelFormat = this.getStringValue(AVKey.PIXEL_FORMAT); String colorFormat = this.getStringValue(AVKey.IMAGE_COLOR_FORMAT); - if (AVKey.ELEVATION.equals(pixelFormat)) - { + if (AVKey.ELEVATION.equals(pixelFormat)) { destNumOfBands = 1; - bandColorInt = new int[] {gdalconst.GCI_GrayIndex}; - } - else if (AVKey.IMAGE.equals(pixelFormat) && AVKey.GRAYSCALE.equals(colorFormat)) - { - bandColorInt = new int[] {gdalconst.GCI_GrayIndex, gdalconst.GCI_AlphaBand}; + bandColorInt = new int[]{gdalconst.GCI_GrayIndex}; + } else if (AVKey.IMAGE.equals(pixelFormat) && AVKey.GRAYSCALE.equals(colorFormat)) { + bandColorInt = new int[]{gdalconst.GCI_GrayIndex, gdalconst.GCI_AlphaBand}; destNumOfBands = 2; // Y + alpha - } - else if (AVKey.IMAGE.equals(pixelFormat) && AVKey.COLOR.equals(colorFormat)) - { - bandColorInt = new int[] { + } else if (AVKey.IMAGE.equals(pixelFormat) && AVKey.COLOR.equals(colorFormat)) { + bandColorInt = new int[]{ gdalconst.GCI_RedBand, gdalconst.GCI_GreenBand, gdalconst.GCI_BlueBand, gdalconst.GCI_AlphaBand}; - if (AVKey.INT16.equals(this.getValue(AVKey.DATA_TYPE)) && srcNumOfBands > 3) - { + if (AVKey.INT16.equals(this.getValue(AVKey.DATA_TYPE)) && srcNumOfBands > 3) { destNumOfBands = 3; // ignore 4th band which is some kind of infra-red - } - else if (srcNumOfBands >= 3) - { + } else if (srcNumOfBands >= 3) { destNumOfBands = 4; // RGBA - } - else - { + } else { destNumOfBands = 1; // indexed 256 color image (like CADRG) - bandColorInt = new int[] {gdalconst.GCI_PaletteIndex}; + bandColorInt = new int[]{gdalconst.GCI_PaletteIndex}; } } Dataset ds = drvMem.Create("roi", width, height, destNumOfBands, bandDataType); // Double nodata = this.calcNoDataForDestinationRaster(destParams); - Double missingDataSignal = AVListImpl.getDoubleValue( this, AVKey.MISSING_DATA_SIGNAL, null); - Double minValue = AVListImpl.getDoubleValue( this, AVKey.ELEVATION_MIN, null ); - Double maxValue = AVListImpl.getDoubleValue( this, AVKey.ELEVATION_MAX, null ); + Double missingDataSignal = AVListImpl.getDoubleValue(this, AVKey.MISSING_DATA_SIGNAL, null); + Double minValue = AVListImpl.getDoubleValue(this, AVKey.ELEVATION_MIN, null); + Double maxValue = AVListImpl.getDoubleValue(this, AVKey.ELEVATION_MAX, null); missingDataSignal = AVListImpl.getDoubleValue(destParams, AVKey.MISSING_DATA_REPLACEMENT, missingDataSignal); - for (int i = 0; i < destNumOfBands; i++) - { + for (int i = 0; i < destNumOfBands; i++) { Band band = ds.GetRasterBand(i + 1); - if ( missingDataSignal != null) - { - band.SetNoDataValue( missingDataSignal ); + if (missingDataSignal != null) { + band.SetNoDataValue(missingDataSignal); } Band srcBand = (i < srcNumOfBands) ? this.dsVRT.GetRasterBand(i + 1) : null; int colorInt = gdalconst.GCI_Undefined; - if (null != srcBand) - { + if (null != srcBand) { colorInt = srcBand.GetColorInterpretation(); - if (colorInt == gdalconst.GCI_Undefined) - { + if (colorInt == gdalconst.GCI_Undefined) { colorInt = bandColorInt[i]; } band.SetColorInterpretation(colorInt); - if (colorInt == gdalconst.GCI_PaletteIndex) - { + if (colorInt == gdalconst.GCI_PaletteIndex) { band.SetColorTable(srcBand.GetColorTable()); } - } - else - { + } else { colorInt = bandColorInt[i]; band.SetColorInterpretation(colorInt); } - if (colorInt == gdalconst.GCI_AlphaBand) - { + if (colorInt == gdalconst.GCI_AlphaBand) { band.Fill((double) GDALUtils.ALPHA_MASK); } - if (null != missingDataSignal && colorInt == gdalconst.GCI_GrayIndex) - { + if (null != missingDataSignal && colorInt == gdalconst.GCI_GrayIndex) { band.Fill(missingDataSignal); - if( null != srcBand && minValue != null && maxValue != null ) - band.SetStatistics( minValue, maxValue, 0d, 0d); + if (null != srcBand && minValue != null && maxValue != null) { + band.SetStatistics(minValue, maxValue, 0d, 0d); + } } } - if (null != sector) - { + if (null != sector) { SpatialReference t_srs = GDALUtils.createGeographicSRS(); String t_srs_wkt = t_srs.ExportToWkt(); ds.SetProjection(t_srs_wkt); @@ -995,7 +861,7 @@ else if (srcNumOfBands >= 3) ds.SetGeoTransform(GDALUtils.calcGetGeoTransform(sector, width, height)); } - String[] keysToCopy = new String[] { + String[] keysToCopy = new String[]{ AVKey.RASTER_BAND_ACTUAL_BITS_PER_PIXEL, AVKey.RASTER_BAND_MAX_PIXEL_VALUE }; @@ -1009,29 +875,31 @@ else if (srcNumOfBands >= 3) * Builds a writable data raster for the requested region of interest (ROI) * * @param params Required parameters are: - *

    AVKey.HEIGHT as Integer, specifies a height of the desired ROI - *

    AVKey.WIDTH as Integer, specifies a width of the desired ROI - *

    AVKey.SECTOR as Sector, specifies an extent of the desired ROI - *

    - * Optional parameters are: - *

    AVKey.BAND_ORDER as array of integers, examples: for RGBA image: new int[] { 0, 1, 2, 3 }, or - * for ARGB image: new int[] { 3, 0, 1, 2 } , or if you want only RGB bands of the RGBA image: new - * int[] {0, 1, 2 }, or only Intensity (4th) band of the specific aerial image: new int[] { 3 } + *

    + * AVKey.HEIGHT as Integer, specifies a height of the desired ROI + *

    + * AVKey.WIDTH as Integer, specifies a width of the desired ROI + *

    + * AVKey.SECTOR as Sector, specifies an extent of the desired ROI + *

    + * Optional parameters are: + *

    + * AVKey.BAND_ORDER as array of integers, examples: for RGBA image: new int[] { 0, 1, 2, 3 }, or for ARGB image: new + * int[] { 3, 0, 1, 2 } , or if you want only RGB bands of the RGBA image: new int[] {0, 1, 2 }, or only Intensity + * (4th) band of the specific aerial image: new int[] { 3 } * * @return A writable data raster: BufferedImageRaster (if the source dataset is imagery) or ByteBufferRaster (if - * the source dataset is elevations) + * the source dataset is elevations) */ @Override - public DataRaster getSubRaster(AVList params) - { - if (params.hasKey(AVKey.BANDS_ORDER)) - { + public DataRaster getSubRaster(AVList params) { + if (params.hasKey(AVKey.BANDS_ORDER)) { GDALUtils.extractBandOrder(this.dsVRT, params); } // copy parent raster keys/values; only those key/value will be copied that do exist in the parent raster // AND does NOT exist in the requested raster - String[] keysToCopy = new String[] { + String[] keysToCopy = new String[]{ AVKey.DATA_TYPE, AVKey.MISSING_DATA_SIGNAL, AVKey.BYTE_ORDER, AVKey.PIXEL_FORMAT, AVKey.ELEVATION_UNIT }; WWUtil.copyValues(this, params, keysToCopy, false); @@ -1039,23 +907,19 @@ public DataRaster getSubRaster(AVList params) return super.getSubRaster(params); } - protected DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSector, AVList roiParams) - { - synchronized (this.usageLock) - { + protected DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSector, AVList roiParams) { + synchronized (this.usageLock) { Dataset destDS = null; Dataset maskDS = null; Dataset srcDS = null; DataRaster raster = null; - try - { + try { gdal.PushErrorHandler("CPLQuietErrorHandler"); roiParams = (null == roiParams) ? new AVListImpl() : roiParams; - if (null != roiSector) - { + if (null != roiSector) { roiParams.setValue(AVKey.SECTOR, roiSector); } @@ -1063,11 +927,9 @@ protected DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSecto roiParams.setValue(AVKey.HEIGHT, roiHeight); if (null == roiSector - || Sector.EMPTY_SECTOR.equals(roiSector) - || !this.hasKey(AVKey.COORDINATE_SYSTEM) - || AVKey.COORDINATE_SYSTEM_UNKNOWN.equals(this.getValue(AVKey.COORDINATE_SYSTEM)) - ) - { + || Sector.EMPTY_SECTOR.equals(roiSector) + || !this.hasKey(AVKey.COORDINATE_SYSTEM) + || AVKey.COORDINATE_SYSTEM_UNKNOWN.equals(this.getValue(AVKey.COORDINATE_SYSTEM))) { // return the entire data raster return GDALUtils.composeDataRaster(this.dsVRT, roiParams); } @@ -1088,11 +950,10 @@ protected DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSecto long start = System.currentTimeMillis(); srcDS = this.getBestSuitedDataset(roiWidth, roiHeight, roiSector); - if (srcDS == this.dsVRT) - { + if (srcDS == this.dsVRT) { String message = Logging.getMessage("gdal.UseFullResolutionRaster", this.getWidth(), - this.getHeight(), - roiWidth, roiHeight); + this.getHeight(), + roiWidth, roiHeight); Logging.logger().finest(message); } @@ -1100,43 +961,36 @@ protected DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSecto start = System.currentTimeMillis(); - if (this.srs != null) - { + if (this.srs != null) { String s_srs_wkt = this.srs.ExportToWkt(); gdal.ReprojectImage(srcDS, destDS, s_srs_wkt, t_srs_wkt, gdalconst.GRA_Bilinear); projTime = System.currentTimeMillis() - start; start = System.currentTimeMillis(); - if (null != maskDS) - { + if (null != maskDS) { gdal.ReprojectImage(srcDS, maskDS, s_srs_wkt, t_srs_wkt, gdalconst.GRA_NearestNeighbour); } maskTime = System.currentTimeMillis() - start; - } - else - { + } else { gdal.ReprojectImage(srcDS, destDS); projTime = System.currentTimeMillis() - start; start = System.currentTimeMillis(); - if (null != maskDS) - { + if (null != maskDS) { gdal.ReprojectImage(srcDS, maskDS); } maskTime = System.currentTimeMillis() - start; } String error = GDALUtils.getErrorMessage(); - if (error != null) - { + if (error != null) { String message = Logging.getMessage("gdal.InternalError", error); Logging.logger().severe(message); // throw new WWRuntimeException( message ); } - if (null != maskDS) - { + if (null != maskDS) { roiParams.setValue(AVKey.GDAL_MASK_DATASET, maskDS); } @@ -1145,26 +999,21 @@ protected DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSecto long composeTime = System.currentTimeMillis() - start; Logging.logger().finest("doGetSubRaster(): [" + roiWidth + "x" + roiHeight + "] - " - + " totalTime = " + (System.currentTimeMillis() - totalTime) - + " msec { Cropping = " + cropTime + " msec, Reprojection = " + projTime - + " msec, Masking = " + maskTime + " msec, Composing = " + composeTime + " msec }"); - } - finally - { + + " totalTime = " + (System.currentTimeMillis() - totalTime) + + " msec { Cropping = " + cropTime + " msec, Reprojection = " + projTime + + " msec, Masking = " + maskTime + " msec, Composing = " + composeTime + " msec }"); + } finally { gdal.PopErrorHandler(); - if (null != maskDS) - { + if (null != maskDS) { maskDS.delete(); } - if (null != destDS && destDS != this.dsVRT) - { + if (null != destDS && destDS != this.dsVRT) { destDS.delete(); } - if (null != srcDS && srcDS != this.dsVRT) - { + if (null != srcDS && srcDS != this.dsVRT) { srcDS.delete(); } } @@ -1172,17 +1021,13 @@ protected DataRaster doGetSubRaster(int roiWidth, int roiHeight, Sector roiSecto } } - protected static Band findAlphaBand(Dataset ds) - { - if (null != ds) - { + protected static Band findAlphaBand(Dataset ds) { + if (null != ds) { // search backward int bandCount = ds.getRasterCount(); - for (int i = bandCount; i > 0; i--) - { + for (int i = bandCount; i > 0; i--) { Band band = ds.GetRasterBand(i); - if (band.GetColorInterpretation() == gdalconst.GCI_AlphaBand) - { + if (band.GetColorInterpretation() == gdalconst.GCI_AlphaBand) { return band; } } @@ -1190,10 +1035,8 @@ protected static Band findAlphaBand(Dataset ds) return null; } - protected static String convertAVListToString(AVList list) - { - if (null == list) - { + protected static String convertAVListToString(AVList list) { + if (null == list) { return ""; } @@ -1201,16 +1044,14 @@ protected static String convertAVListToString(AVList list) Vector keys = new Vector(); Set> entries = list.getEntries(); - for (Map.Entry entry : entries) - { + for (Map.Entry entry : entries) { keys.add(entry.getKey()); } // sort keys Collections.sort(keys); - for (String key : keys) - { + for (String key : keys) { sb.append("\n").append(key).append("=").append(list.getValue(key)); } sb.append("\n};"); @@ -1219,31 +1060,24 @@ protected static String convertAVListToString(AVList list) } @Override - public String toString() - { + public String toString() { return "GDALDataRaster " + convertAVListToString(this); } - protected boolean intersects(Sector reqSector) - { - if (null != reqSector) - { - if (null != this.area) - { + protected boolean intersects(Sector reqSector) { + if (null != reqSector) { + if (null != this.area) { return (null != this.area.intersection(reqSector)); - } - else - { + } else { return reqSector.intersects(this.getSector()); } } return false; } - public long getSizeInBytes() - { + public long getSizeInBytes() { // this is empiric number; on average GDALDataRaster object takes between 30K-131KB // we need to provide a non-zero length to make sure it will be added to the memory cache return 2048L; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/data/GDALDataRasterReader.java b/src/gov/nasa/worldwind/data/GDALDataRasterReader.java index ce28105f0c..a4ad2bf1b8 100644 --- a/src/gov/nasa/worldwind/data/GDALDataRasterReader.java +++ b/src/gov/nasa/worldwind/data/GDALDataRasterReader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.avlist.*; @@ -18,26 +17,23 @@ * @author Lado Garakanidze * @version $Id: GDALDataRasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class GDALDataRasterReader extends AbstractDataRasterReader { -public class GDALDataRasterReader extends AbstractDataRasterReader -{ // Extract list of mime types supported by GDAL - protected static final String[] mimeTypes = new String[] { + protected static final String[] mimeTypes = new String[]{ "image/jp2", "image/jpeg2000", "image/jpeg2000-image", "image/x-jpeg2000-image", "image/x-mrsid-image", "image/jpeg", "image/png", "image/bmp", "image/tif" }; // TODO Extract list of extensions supported by GDAL - protected static final String[] suffixes = new String[] { + protected static final String[] suffixes = new String[]{ "jp2", "sid", "ntf", "nitf", "JP2", "SID", "NTF", "NITF", - - "jpg", "jpe", "jpeg", /* "image/jpeg" */ - "png", /* "image/png" */ - "bmp", /* "image/bmp" */ - "TIF", "TIFF", "GTIF", "GTIFF", "tif", "tiff", "gtif", "gtiff", /* "image/tif" */ - + "jpg", "jpe", "jpeg", /* "image/jpeg" */ + "png", /* "image/png" */ + "bmp", /* "image/bmp" */ + "TIF", "TIFF", "GTIF", "GTIFF", "tif", "tiff", "gtif", "gtiff", /* "image/tif" */ // Elevations // DTED @@ -45,32 +41,26 @@ public class GDALDataRasterReader extends AbstractDataRasterReader "asc", "adf", "dem" }; - public GDALDataRasterReader() - { + public GDALDataRasterReader() { super("GDAL-based Data Raster Reader", mimeTypes, suffixes); } @Override - public boolean canRead(Object source, AVList params) - { + public boolean canRead(Object source, AVList params) { // RPF imagery cannot be identified by a small set of suffixes or mime types, so we override the standard // suffix comparison behavior here. return this.doCanRead(source, params); } @Override - protected boolean doCanRead(Object source, AVList params) - { - if (WWUtil.isEmpty(source)) - { + protected boolean doCanRead(Object source, AVList params) { + if (WWUtil.isEmpty(source)) { return false; } - if (null == params) - { + if (null == params) { File file = WWIO.getFileForLocalAddress(source); - if (null == file) - { + if (null == file) { return false; } @@ -79,21 +69,15 @@ protected boolean doCanRead(Object source, AVList params) boolean canOpen = false; GDALDataRaster raster = null; - try - { + try { raster = new GDALDataRaster(source, true); // read data raster quietly params.setValues(raster.getMetadata()); canOpen = true; - } - catch (Throwable t) - { + } catch (Throwable t) { // we purposely ignore any exception here, this should be a very quiet mode canOpen = false; - } - finally - { - if (null != raster) - { + } finally { + if (null != raster) { raster.dispose(); raster = null; } @@ -103,57 +87,45 @@ protected boolean doCanRead(Object source, AVList params) } @Override - protected DataRaster[] doRead(Object source, AVList params) throws IOException - { + protected DataRaster[] doRead(Object source, AVList params) throws IOException { GDALDataRaster raster = this.readDataRaster(source, false); - if (null != raster && null != params) - { + if (null != raster && null != params) { params.setValues(raster.getMetadata()); - WWUtil.copyValues(params, raster, new String[] {AVKey.SECTOR}, false); + WWUtil.copyValues(params, raster, new String[]{AVKey.SECTOR}, false); } - return (null == raster) ? null : new DataRaster[] {raster}; + return (null == raster) ? null : new DataRaster[]{raster}; } @Override - protected void doReadMetadata(Object source, AVList params) throws IOException - { + protected void doReadMetadata(Object source, AVList params) throws IOException { GDALDataRaster raster = this.readDataRaster(source, true); - if (null != raster && null != params) - { + if (null != raster && null != params) { params.setValues(raster.getMetadata()); - WWUtil.copyValues(params, raster, new String[] {AVKey.SECTOR}, false); + WWUtil.copyValues(params, raster, new String[]{AVKey.SECTOR}, false); raster.dispose(); } } - protected GDALDataRaster readDataRaster(Object source, boolean quickReadingMode) throws IOException - { - if (null == source) - { + protected GDALDataRaster readDataRaster(Object source, boolean quickReadingMode) throws IOException { + if (null == source) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { GDALDataRaster raster = new GDALDataRaster(source, quickReadingMode); - if (null == raster) - { + if (null == raster) { String message = Logging.getMessage("generic.CannotOpenFile", GDALUtils.getErrorMessage()); Logging.logger().severe(message); throw new WWRuntimeException(message); } return raster; - } - catch (WWRuntimeException wwre) - { + } catch (WWRuntimeException wwre) { throw wwre; - } - catch (Throwable t) - { + } catch (Throwable t) { String message = Logging.getMessage("generic.CannotOpenFile", GDALUtils.getErrorMessage()); Logging.logger().log(Level.SEVERE, message, t); throw new WWRuntimeException(t); diff --git a/src/gov/nasa/worldwind/data/GDALMetadata.java b/src/gov/nasa/worldwind/data/GDALMetadata.java index 272cd2fd26..a0ff40eb08 100644 --- a/src/gov/nasa/worldwind/data/GDALMetadata.java +++ b/src/gov/nasa/worldwind/data/GDALMetadata.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.avlist.*; @@ -18,9 +17,8 @@ * @author Lado Garakanidze * @version $ */ +public class GDALMetadata { -public class GDALMetadata -{ protected static final String NITF_ONAME = "NITF_ONAME"; protected static final String NITF_ISORCE = "NITF_ISORCE"; protected static final String NITF_IREP = "NITF_IREP"; @@ -28,60 +26,47 @@ public class GDALMetadata protected static final String NITF_FBKGC = "NITF_FBKGC"; protected static final String NITF_DYNAMIC_RANGE = "NITF_USE00A_DYNAMIC_RANGE"; - protected GDALMetadata() - { + protected GDALMetadata() { } public static AVList extractExtendedAndFormatSpecificMetadata(Dataset ds, AVList extParams, AVList params) - throws IllegalArgumentException, WWRuntimeException - { - if (null == ds) - { + throws IllegalArgumentException, WWRuntimeException { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == extParams) - { + if (null == extParams) { extParams = new AVListImpl(); } - try - { + try { Hashtable dict = ds.GetMetadata_Dict(""); - if (null != dict) - { + if (null != dict) { Enumeration keys = dict.keys(); - while (keys.hasMoreElements()) - { + while (keys.hasMoreElements()) { Object o = keys.nextElement(); - if (null != o && o instanceof String) - { + if (null != o && o instanceof String) { String key = (String) o; Object value = dict.get(key); - if (!WWUtil.isEmpty(value)) - { + if (!WWUtil.isEmpty(value)) { extParams.setValue(key, value); } } } } - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(java.util.logging.Level.FINE, t.getMessage(), t); } return mapExtendedMetadata(ds, extParams, params); } - static protected AVList mapExtendedMetadata(Dataset ds, AVList extParams, AVList params) - { + static protected AVList mapExtendedMetadata(Dataset ds, AVList extParams, AVList params) { params = (null == params) ? new AVListImpl() : params; - if (null == extParams) - { + if (null == extParams) { return params; } @@ -89,64 +74,53 @@ static protected AVList mapExtendedMetadata(Dataset ds, AVList extParams, AVList String drvName = (null != ds) ? ds.GetDriver().getShortName() : ""; - if ("NITF".equals(drvName)) - { + if ("NITF".equals(drvName)) { mapNITFMetadata(extParams, params); } return params; } - protected static void mapNITFMetadata(AVList extParams, AVList params) - { - if (extParams.hasKey(NITF_ONAME)) - { + protected static void mapNITFMetadata(AVList extParams, AVList params) { + if (extParams.hasKey(NITF_ONAME)) { // values: GeoEye, DigitalGlobe } - if (extParams.hasKey(NITF_ISORCE)) - { + if (extParams.hasKey(NITF_ISORCE)) { // values: GEOEYE1,DigitalGlobe } - if (extParams.hasKey(NITF_IREP)) - { + if (extParams.hasKey(NITF_IREP)) { // values: RGB/LUT/MONO/MULTI } // Extract Actual Bit-Per-Pixel - if (extParams.hasKey(NITF_ABPP)) - { + if (extParams.hasKey(NITF_ABPP)) { Object o = extParams.getValue(NITF_ABPP); - if (!WWUtil.isEmpty(o) && o instanceof String) - { + if (!WWUtil.isEmpty(o) && o instanceof String) { Integer abpp = WWUtil.convertStringToInteger((String) o); - if (null != abpp) + if (null != abpp) { params.setValue(AVKey.RASTER_BAND_ACTUAL_BITS_PER_PIXEL, abpp); + } } } - if (extParams.hasKey(NITF_DYNAMIC_RANGE)) - { + if (extParams.hasKey(NITF_DYNAMIC_RANGE)) { Object o = extParams.getValue(NITF_DYNAMIC_RANGE); - if (!WWUtil.isEmpty(o) && o instanceof String) - { + if (!WWUtil.isEmpty(o) && o instanceof String) { Double maxPixelValue = WWUtil.convertStringToDouble((String) o); - if (null != maxPixelValue) + if (null != maxPixelValue) { params.setValue(AVKey.RASTER_BAND_MAX_PIXEL_VALUE, maxPixelValue); + } } } - if (extParams.hasKey(NITF_FBKGC)) - { + if (extParams.hasKey(NITF_FBKGC)) { Object o = extParams.getValue(NITF_FBKGC); - if (!WWUtil.isEmpty(o) && o instanceof String) - { - try - { + if (!WWUtil.isEmpty(o) && o instanceof String) { + try { String[] s = ((String) o).split(","); - if (null != s) - { + if (null != s) { // if( s.length == 3 ) // { // Color bgc = new Color( Integer.parseInt(s[0]), Integer.parseInt(s[1]), Integer.parseInt(s[2]), 0xFF ); @@ -159,9 +133,7 @@ protected static void mapNITFMetadata(AVList extParams, AVList params) // params.setValue(AVKey.MISSING_DATA_SIGNAL, (double)color ); // } } - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.CannotCreateColor", o); Logging.logger().severe(msg); } @@ -169,168 +141,134 @@ protected static void mapNITFMetadata(AVList extParams, AVList params) } } - public static AVList convertToWorldWind(AVList extParams, AVList destParams) - { - if (null == destParams) - { + public static AVList convertToWorldWind(AVList extParams, AVList destParams) { + if (null == destParams) { destParams = new AVListImpl(); } - if (null == extParams) - { + if (null == extParams) { return destParams; } String proj = null, zone = null, ellps = null, datum = null, units = null; Integer epsg = null; - if (extParams.hasKey("GEOTIFF_CHAR__ProjectedCSTypeGeoKey")) - { + if (extParams.hasKey("GEOTIFF_CHAR__ProjectedCSTypeGeoKey")) { proj = extParams.getStringValue("GEOTIFF_CHAR__ProjectedCSTypeGeoKey"); proj = (null != proj) ? proj.toUpperCase() : null; int idx = (null != proj) ? proj.indexOf("ZONE_") : -1; - if (idx != -1) - { + if (idx != -1) { zone = proj.substring(idx + 5, proj.length()); zone = (null != zone) ? zone.toUpperCase() : null; } } - if (null == proj && extParams.hasKey("IMG__PROJECTION_NAME")) - { + if (null == proj && extParams.hasKey("IMG__PROJECTION_NAME")) { proj = extParams.getStringValue("IMG__PROJECTION_NAME"); proj = (null != proj) ? proj.toUpperCase() : null; } - if (null == zone && extParams.hasKey("IMG__PROJECTION_ZONE")) - { + if (null == zone && extParams.hasKey("IMG__PROJECTION_ZONE")) { zone = extParams.getStringValue("IMG__PROJECTION_ZONE"); zone = (null != zone) ? zone.toUpperCase() : null; } - if (null != proj && proj.contains("UTM")) - { + if (null != proj && proj.contains("UTM")) { destParams.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_PROJECTED); destParams.setValue(AVKey.PROJECTION_NAME, AVKey.PROJECTION_UTM); - if (null != zone) - { - if (zone.endsWith("N")) - { + if (null != zone) { + if (zone.endsWith("N")) { destParams.setValue(AVKey.PROJECTION_HEMISPHERE, AVKey.NORTH); zone = zone.substring(0, zone.length() - 1); - } - else if (zone.endsWith("S")) - { + } else if (zone.endsWith("S")) { destParams.setValue(AVKey.PROJECTION_HEMISPHERE, AVKey.SOUTH); zone = zone.substring(0, zone.length() - 1); } Integer i = WWUtil.makeInteger(zone.trim()); - if (i != null && i >= 1 && i <= 60) - { + if (i != null && i >= 1 && i <= 60) { destParams.setValue(AVKey.PROJECTION_ZONE, i); } } } - if (extParams.hasKey("IMG__SPHEROID_NAME")) - { + if (extParams.hasKey("IMG__SPHEROID_NAME")) { String s = extParams.getStringValue("IMG__SPHEROID_NAME"); - if (s != null) - { + if (s != null) { s = s.toUpperCase(); - if (s.contains("WGS") && s.contains("84")) - { + if (s.contains("WGS") && s.contains("84")) { ellps = datum = "WGS84"; destParams.setValue(AVKey.PROJECTION_DATUM, datum); } } } - if (extParams.hasKey("IMG__HORIZONTAL_UNITS")) - { + if (extParams.hasKey("IMG__HORIZONTAL_UNITS")) { String s = extParams.getStringValue("IMG__HORIZONTAL_UNITS"); - if (s != null) - { + if (s != null) { s = s.toLowerCase(); - if (s.contains("meter") || s.contains("metre")) - { + if (s.contains("meter") || s.contains("metre")) { units = AVKey.UNIT_METER; } - if (s.contains("feet") || s.contains("foot")) - { + if (s.contains("feet") || s.contains("foot")) { units = AVKey.UNIT_FOOT; } - if (null != units) - { + if (null != units) { destParams.setValue(AVKey.PROJECTION_UNITS, units); } } } - if (extParams.hasKey("GEOTIFF_NUM__3072__ProjectedCSTypeGeoKey")) - { + if (extParams.hasKey("GEOTIFF_NUM__3072__ProjectedCSTypeGeoKey")) { String s = extParams.getStringValue("GEOTIFF_NUM__3072__ProjectedCSTypeGeoKey"); - if (s != null) - { + if (s != null) { epsg = WWUtil.makeInteger(s.trim()); } } - if (null == epsg && extParams.hasKey("GEO__ProjectedCSTypeGeoKey")) - { + if (null == epsg && extParams.hasKey("GEO__ProjectedCSTypeGeoKey")) { String s = extParams.getStringValue("GEO__ProjectedCSTypeGeoKey"); - if (s != null) - { + if (s != null) { epsg = WWUtil.makeInteger(s.trim()); } } - if (null != epsg) - { + if (null != epsg) { destParams.setValue(AVKey.PROJECTION_EPSG_CODE, epsg); } StringBuffer proj4 = new StringBuffer(); - if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(destParams.getValue(AVKey.COORDINATE_SYSTEM))) - { + if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(destParams.getValue(AVKey.COORDINATE_SYSTEM))) { // +proj=utm +zone=38 +ellps=WGS84 +datum=WGS84 +units=m - if (AVKey.PROJECTION_UTM.equals(destParams.getValue(AVKey.PROJECTION_NAME))) - { + if (AVKey.PROJECTION_UTM.equals(destParams.getValue(AVKey.PROJECTION_NAME))) { proj4.append("+proj=utm"); } - if (destParams.hasKey(AVKey.PROJECTION_ZONE)) - { + if (destParams.hasKey(AVKey.PROJECTION_ZONE)) { proj4.append(" +zone=").append(destParams.getValue(AVKey.PROJECTION_ZONE)); } - if (destParams.hasKey(AVKey.PROJECTION_DATUM)) - { + if (destParams.hasKey(AVKey.PROJECTION_DATUM)) { proj4.append(" +ellps=").append(destParams.getValue(AVKey.PROJECTION_DATUM)); proj4.append(" +datum=").append(destParams.getValue(AVKey.PROJECTION_DATUM)); } - if (destParams.hasKey(AVKey.PROJECTION_UNITS)) - { + if (destParams.hasKey(AVKey.PROJECTION_UNITS)) { proj4.append(" +units=").append( - AVKey.UNIT_METER.equals(destParams.getValue(AVKey.PROJECTION_UNITS)) ? "m" : "f" + AVKey.UNIT_METER.equals(destParams.getValue(AVKey.PROJECTION_UNITS)) ? "m" : "f" ); } - try - { + try { SpatialReference srs = new SpatialReference(); srs.ImportFromProj4(proj4.toString()); destParams.setValue(AVKey.SPATIAL_REFERENCE_WKT, srs.ExportToWkt()); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(java.util.logging.Level.FINEST, t.getMessage(), t); } } diff --git a/src/gov/nasa/worldwind/data/GeotiffRasterReader.java b/src/gov/nasa/worldwind/data/GeotiffRasterReader.java index 6ca9630d98..37be13c57a 100644 --- a/src/gov/nasa/worldwind/data/GeotiffRasterReader.java +++ b/src/gov/nasa/worldwind/data/GeotiffRasterReader.java @@ -15,67 +15,55 @@ * @author dcollins * @version $Id: GeotiffRasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeotiffRasterReader extends AbstractDataRasterReader -{ +public class GeotiffRasterReader extends AbstractDataRasterReader { + private static final String[] geotiffMimeTypes = {"image/tiff", "image/geotiff"}; private static final String[] geotiffSuffixes = {"tif", "tiff", "gtif", "tif.zip", "tiff.zip", "tif.gz", "tiff.gz"}; - public GeotiffRasterReader() - { + public GeotiffRasterReader() { super(geotiffMimeTypes, geotiffSuffixes); } - protected boolean doCanRead(Object source, AVList params) - { + protected boolean doCanRead(Object source, AVList params) { String path = WWIO.getSourcePath(source); - if (path == null) - { + if (path == null) { return false; } GeotiffReader reader = null; - try - { + try { reader = new GeotiffReader(path); boolean isGeoTiff = reader.isGeotiff(0); - if (!isGeoTiff) - { + if (!isGeoTiff) { isGeoTiff = WorldFile.hasWorldFiles(source); } return isGeoTiff; - } - catch (Exception e) - { + } catch (Exception e) { // Intentionally ignoring exceptions. return false; - } - finally - { - if (reader != null) - { + } finally { + if (reader != null) { reader.close(); } } } - protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOException - { + protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOException { String path = WWIO.getSourcePath(source); - if (path == null) - { + if (path == null) { String message = Logging.getMessage("DataRaster.CannotRead", source); Logging.logger().severe(message); throw new java.io.IOException(message); } AVList metadata = new AVListImpl(); - if (null != params) + if (null != params) { metadata.setValues(params); + } GeotiffReader reader = null; DataRaster[] rasters = null; - try - { + try { this.readMetadata(source, metadata); reader = new GeotiffReader(path); @@ -83,44 +71,35 @@ protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOExc rasters = reader.readDataRaster(); - if (null != rasters) - { - String[] keysToCopy = new String[] {AVKey.SECTOR}; - for (DataRaster raster : rasters) - { + if (null != rasters) { + String[] keysToCopy = new String[]{AVKey.SECTOR}; + for (DataRaster raster : rasters) { WWUtil.copyValues(metadata, raster, keysToCopy, false); } } - } - finally - { - if (reader != null) - { + } finally { + if (reader != null) { reader.close(); } } return rasters; } - protected void doReadMetadata(Object source, AVList params) throws java.io.IOException - { + protected void doReadMetadata(Object source, AVList params) throws java.io.IOException { String path = WWIO.getSourcePath(source); - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull", source); Logging.logger().severe(message); throw new java.io.IOException(message); } GeotiffReader reader = null; - try - { + try { reader = new GeotiffReader(path); reader.copyMetadataTo(params); boolean isGeoTiff = reader.isGeotiff(0); - if (!isGeoTiff && params.hasKey(AVKey.WIDTH) && params.hasKey(AVKey.HEIGHT)) - { + if (!isGeoTiff && params.hasKey(AVKey.WIDTH) && params.hasKey(AVKey.HEIGHT)) { int[] size = new int[2]; size[0] = (Integer) params.getValue(AVKey.WIDTH); @@ -131,16 +110,12 @@ protected void doReadMetadata(Object source, AVList params) throws java.io.IOExc WorldFile.readWorldFiles(source, params); Object o = params.getValue(AVKey.SECTOR); - if (o == null || !(o instanceof Sector)) - { + if (o == null || !(o instanceof Sector)) { ImageUtil.calcBoundingBoxForUTM(params); } } - } - finally - { - if (reader != null) - { + } finally { + if (reader != null) { reader.close(); } } diff --git a/src/gov/nasa/worldwind/data/GeotiffRasterWriter.java b/src/gov/nasa/worldwind/data/GeotiffRasterWriter.java index 0ac58b3259..7da5fadffd 100644 --- a/src/gov/nasa/worldwind/data/GeotiffRasterWriter.java +++ b/src/gov/nasa/worldwind/data/GeotiffRasterWriter.java @@ -14,32 +14,27 @@ * @author Lado Garakanidze * @version $Id: GeotiffRasterWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeotiffRasterWriter extends AbstractDataRasterWriter -{ +public class GeotiffRasterWriter extends AbstractDataRasterWriter { + protected static final String[] geotiffMimeTypes = {"image/tiff", "image/geotiff"}; protected static final String[] geotiffSuffixes = {"tif", "tiff", "gtif"}; - public GeotiffRasterWriter() - { + public GeotiffRasterWriter() { super(geotiffMimeTypes, geotiffSuffixes); } - protected boolean doCanWrite(DataRaster raster, String formatSuffix, File file) - { + protected boolean doCanWrite(DataRaster raster, String formatSuffix, File file) { return (raster != null) && (raster instanceof BufferedImageRaster || raster instanceof BufferWrapperRaster); } - protected void doWrite(DataRaster raster, String formatSuffix, File file) throws IOException - { - if (null == file) - { + protected void doWrite(DataRaster raster, String formatSuffix, File file) throws IOException { + if (null == file) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == raster) - { + if (null == raster) { String message = Logging.getMessage("nullValue.RasterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -47,15 +42,13 @@ protected void doWrite(DataRaster raster, String formatSuffix, File file) throws GeotiffWriter writer = null; - try - { + try { writer = new GeotiffWriter(file); writer.write(raster); - } - finally - { - if (null != writer) + } finally { + if (null != writer) { writer.close(); + } } } } diff --git a/src/gov/nasa/worldwind/data/ImageIORasterReader.java b/src/gov/nasa/worldwind/data/ImageIORasterReader.java index 8fd695d8aa..bcbad57277 100644 --- a/src/gov/nasa/worldwind/data/ImageIORasterReader.java +++ b/src/gov/nasa/worldwind/data/ImageIORasterReader.java @@ -19,38 +19,32 @@ * @author dcollins * @version $Id: ImageIORasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ImageIORasterReader extends AbstractDataRasterReader -{ - static - { +public class ImageIORasterReader extends AbstractDataRasterReader { + + static { javax.imageio.spi.IIORegistry.getDefaultInstance().registerServiceProvider(GeotiffImageReaderSpi.inst()); } private boolean generateMipMaps; - public ImageIORasterReader(boolean generateMipMaps) - { + public ImageIORasterReader(boolean generateMipMaps) { super(javax.imageio.ImageIO.getReaderMIMETypes(), getImageIOReaderSuffixes()); this.generateMipMaps = generateMipMaps; } - public ImageIORasterReader() - { + public ImageIORasterReader() { this(false); } - public boolean isGenerateMipMaps() - { + public boolean isGenerateMipMaps() { return this.generateMipMaps; } - public void setGenerateMipMaps(boolean generateMipMaps) - { + public void setGenerateMipMaps(boolean generateMipMaps) { this.generateMipMaps = generateMipMaps; } - protected boolean doCanRead(Object source, AVList params) - { + protected boolean doCanRead(Object source, AVList params) { // Determine whether or not the data source can be read. //if (!this.canReadImage(source)) // return false; @@ -58,32 +52,27 @@ protected boolean doCanRead(Object source, AVList params) // If the data source doesn't already have all the necessary metadata, then we determine whether or not // the missing metadata can be read. Object o = (params != null) ? params.getValue(AVKey.SECTOR) : null; - if (o == null || !(o instanceof Sector)) - { - if (!this.canReadWorldFiles(source)) - { + if (o == null || !(o instanceof Sector)) { + if (!this.canReadWorldFiles(source)) { return false; } } - if (null != params && !params.hasKey(AVKey.PIXEL_FORMAT)) - { + if (null != params && !params.hasKey(AVKey.PIXEL_FORMAT)) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); } return true; } - protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOException - { + protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOException { javax.imageio.stream.ImageInputStream iis = createInputStream(source); java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(iis); image = ImageUtil.toCompatibleImage(image); // If the data source doesn't already have all the necessary metadata, then we attempt to read the metadata. Object o = (params != null) ? params.getValue(AVKey.SECTOR) : null; - if (o == null || !(o instanceof Sector)) - { + if (o == null || !(o instanceof Sector)) { AVList values = new AVListImpl(); values.setValue(AVKey.IMAGE, image); this.readWorldFiles(source, values); @@ -93,35 +82,27 @@ protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOExc return new DataRaster[]{this.createRaster((Sector) o, image)}; } - protected void doReadMetadata(Object source, AVList params) throws java.io.IOException - { + protected void doReadMetadata(Object source, AVList params) throws java.io.IOException { Object width = params.getValue(AVKey.WIDTH); Object height = params.getValue(AVKey.HEIGHT); - if (width == null || height == null || !(width instanceof Integer) || !(height instanceof Integer)) - { + if (width == null || height == null || !(width instanceof Integer) || !(height instanceof Integer)) { this.readImageDimension(source, params); } Object sector = params.getValue(AVKey.SECTOR); - if (sector == null || !(sector instanceof Sector)) - { + if (sector == null || !(sector instanceof Sector)) { this.readWorldFiles(source, params); } - if (!params.hasKey(AVKey.PIXEL_FORMAT)) - { + if (!params.hasKey(AVKey.PIXEL_FORMAT)) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); } } - protected DataRaster createRaster(Sector sector, java.awt.image.BufferedImage image) - { - if (this.isGenerateMipMaps()) - { + protected DataRaster createRaster(Sector sector, java.awt.image.BufferedImage image) { + if (this.isGenerateMipMaps()) { return new MipMappedBufferedImageRaster(sector, image); - } - else - { + } else { return new BufferedImageRaster(sector, image); } } @@ -159,24 +140,17 @@ protected DataRaster createRaster(Sector sector, java.awt.image.BufferedImage im // // return true; //} - - private boolean canReadWorldFiles(Object source) - { - if (!(source instanceof java.io.File)) - { + private boolean canReadWorldFiles(Object source) { + if (!(source instanceof java.io.File)) { return false; } - try - { + try { java.io.File[] worldFiles = WorldFile.getWorldFiles((java.io.File) source); - if (worldFiles == null || worldFiles.length == 0) - { + if (worldFiles == null || worldFiles.length == 0) { return false; } - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { // Not interested in logging the exception, we only want to report the failure to read. return false; } @@ -184,14 +158,11 @@ private boolean canReadWorldFiles(Object source) return true; } - private void readImageDimension(Object source, AVList params) throws java.io.IOException - { + private void readImageDimension(Object source, AVList params) throws java.io.IOException { javax.imageio.stream.ImageInputStream iis = createInputStream(source); javax.imageio.ImageReader reader = readerFor(iis); - try - { - if (reader == null) - { + try { + if (reader == null) { String message = Logging.getMessage("generic.UnrecognizedImageSourceType", source); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -202,21 +173,16 @@ private void readImageDimension(Object source, AVList params) throws java.io.IOE int height = reader.getHeight(0); params.setValue(AVKey.WIDTH, width); params.setValue(AVKey.HEIGHT, height); - } - finally - { - if (reader != null) - { + } finally { + if (reader != null) { reader.dispose(); } iis.close(); } } - private void readWorldFiles(Object source, AVList params) throws java.io.IOException - { - if (!(source instanceof java.io.File)) - { + private void readWorldFiles(Object source, AVList params) throws java.io.IOException { + if (!(source instanceof java.io.File)) { String message = Logging.getMessage("DataRaster.CannotRead", source); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -225,17 +191,14 @@ private void readWorldFiles(Object source, AVList params) throws java.io.IOExcep // If an image is not specified in the metadata values, then attempt to construct the image size from other // parameters. Object o = params.getValue(AVKey.IMAGE); - if (o == null || !(o instanceof java.awt.image.BufferedImage)) - { + if (o == null || !(o instanceof java.awt.image.BufferedImage)) { o = params.getValue(WorldFile.WORLD_FILE_IMAGE_SIZE); - if (o == null || !(o instanceof int[])) - { + if (o == null || !(o instanceof int[])) { // If the image size is specified in the parameters WIDTH and HEIGHT, then translate them to the // WORLD_FILE_IMAGE_SIZE parameter. Object width = params.getValue(AVKey.WIDTH); Object height = params.getValue(AVKey.HEIGHT); - if (width != null && height != null && width instanceof Integer && height instanceof Integer) - { + if (width != null && height != null && width instanceof Integer && height instanceof Integer) { int[] size = new int[]{(Integer) width, (Integer) height}; params.setValue(WorldFile.WORLD_FILE_IMAGE_SIZE, size); } @@ -246,38 +209,28 @@ private void readWorldFiles(Object source, AVList params) throws java.io.IOExcep WorldFile.decodeWorldFiles(worldFiles, params); } - private static javax.imageio.stream.ImageInputStream createInputStream(Object source) throws java.io.IOException - { + private static javax.imageio.stream.ImageInputStream createInputStream(Object source) throws java.io.IOException { // ImageIO can create an ImageInputStream automatically from a File references or a standard I/O InputStream // reference. If the data source is a URL, or a string file path, then we must open an input stream ourselves. Object input = source; - if (source instanceof java.net.URL) - { + if (source instanceof java.net.URL) { input = ((java.net.URL) source).openStream(); - } - else if (source instanceof CharSequence) - { + } else if (source instanceof CharSequence) { input = openInputStream(source.toString()); } return javax.imageio.ImageIO.createImageInputStream(input); } - private static java.io.InputStream openInputStream(String path) throws java.io.IOException - { + private static java.io.InputStream openInputStream(String path) throws java.io.IOException { Object streamOrException = WWIO.getFileOrResourceAsStream(path, null); - if (streamOrException == null) - { + if (streamOrException == null) { return null; - } - else if (streamOrException instanceof java.io.IOException) - { + } else if (streamOrException instanceof java.io.IOException) { throw (java.io.IOException) streamOrException; - } - else if (streamOrException instanceof Exception) - { + } else if (streamOrException instanceof Exception) { String message = Logging.getMessage("generic.ExceptionAttemptingToReadImageFile", path); Logging.logger().log(java.util.logging.Level.SEVERE, message, streamOrException); throw new java.io.IOException(message); @@ -286,33 +239,26 @@ else if (streamOrException instanceof Exception) return (java.io.InputStream) streamOrException; } - private static javax.imageio.ImageReader readerFor(javax.imageio.stream.ImageInputStream iis) - { + private static javax.imageio.ImageReader readerFor(javax.imageio.stream.ImageInputStream iis) { java.util.Iterator readers = javax.imageio.ImageIO.getImageReaders(iis); - if (!readers.hasNext()) - { + if (!readers.hasNext()) { return null; } return readers.next(); } - private static String[] getImageIOReaderSuffixes() - { + private static String[] getImageIOReaderSuffixes() { java.util.Iterator iter; - try - { + try { iter = javax.imageio.spi.IIORegistry.getDefaultInstance().getServiceProviders( javax.imageio.spi.ImageReaderSpi.class, true); - } - catch (Exception e) - { + } catch (Exception e) { return new String[0]; } java.util.Set set = new java.util.HashSet(); - while (iter.hasNext()) - { + while (iter.hasNext()) { javax.imageio.spi.ImageReaderSpi spi = iter.next(); String[] names = spi.getFileSuffixes(); set.addAll(java.util.Arrays.asList(names)); diff --git a/src/gov/nasa/worldwind/data/ImageIORasterWriter.java b/src/gov/nasa/worldwind/data/ImageIORasterWriter.java index b437837c13..353ff6cab2 100644 --- a/src/gov/nasa/worldwind/data/ImageIORasterWriter.java +++ b/src/gov/nasa/worldwind/data/ImageIORasterWriter.java @@ -16,64 +16,55 @@ * @author dcollins * @version $Id: ImageIORasterWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ImageIORasterWriter extends AbstractDataRasterWriter -{ +public class ImageIORasterWriter extends AbstractDataRasterWriter { + private boolean writeGeoreferenceFiles; - public ImageIORasterWriter(boolean writeGeoreferenceFiles) - { + public ImageIORasterWriter(boolean writeGeoreferenceFiles) { super(javax.imageio.ImageIO.getWriterMIMETypes(), getImageIOWriterSuffixes()); this.writeGeoreferenceFiles = writeGeoreferenceFiles; } - public ImageIORasterWriter() - { + public ImageIORasterWriter() { this(true); // Enable writing georeference files by default. } - public boolean isWriteGeoreferenceFiles() - { + public boolean isWriteGeoreferenceFiles() { return this.writeGeoreferenceFiles; } - public void setWriteGeoreferenceFiles(boolean writeGeoreferenceFiles) - { + public void setWriteGeoreferenceFiles(boolean writeGeoreferenceFiles) { this.writeGeoreferenceFiles = writeGeoreferenceFiles; } - protected boolean doCanWrite(DataRaster raster, String formatSuffix, java.io.File file) - { + protected boolean doCanWrite(DataRaster raster, String formatSuffix, java.io.File file) { return (raster != null) && (raster instanceof BufferedImageRaster); } - protected void doWrite(DataRaster raster, String formatSuffix, java.io.File file) throws java.io.IOException - { + protected void doWrite(DataRaster raster, String formatSuffix, java.io.File file) throws java.io.IOException { this.writeImage(raster, formatSuffix, file); - if (this.isWriteGeoreferenceFiles()) - { + if (this.isWriteGeoreferenceFiles()) { AVList worldFileParams = new AVListImpl(); this.initWorldFileParams(raster, worldFileParams); - + java.io.File dir = file.getParentFile(); String base = WWIO.replaceSuffix(file.getName(), ""); String suffix = WWIO.getSuffix(file.getName()); String worldFileSuffix = this.suffixForWorldFile(suffix); - this.writeImageMetadata(new java.io.File(dir, base + "." + worldFileSuffix), worldFileParams); + this.writeImageMetadata(new java.io.File(dir, base + "." + worldFileSuffix), worldFileParams); } } - protected void writeImage(DataRaster raster, String formatSuffix, java.io.File file) throws java.io.IOException - { + protected void writeImage(DataRaster raster, String formatSuffix, java.io.File file) throws java.io.IOException { BufferedImageRaster bufferedImageRaster = (BufferedImageRaster) raster; java.awt.image.BufferedImage image = bufferedImageRaster.getBufferedImage(); javax.imageio.ImageIO.write(image, formatSuffix, file); } - protected void writeImageMetadata(java.io.File file, AVList values) throws java.io.IOException - { + protected void writeImageMetadata(java.io.File file, AVList values) throws java.io.IOException { Sector sector = (Sector) values.getValue(AVKey.SECTOR); int[] size = (int[]) values.getValue(WorldFile.WORLD_FILE_IMAGE_SIZE); @@ -85,8 +76,7 @@ protected void writeImageMetadata(java.io.File file, AVList values) throws java. double yLocation = sector.getMaxLatitude().degrees + (yPixelSize * .5); java.io.PrintWriter out = new java.io.PrintWriter(file); - try - { + try { out.println(xPixelSize); out.println(xCoeff); //noinspection SuspiciousNameCombination @@ -96,18 +86,16 @@ protected void writeImageMetadata(java.io.File file, AVList values) throws java. out.println(xLocation); //noinspection SuspiciousNameCombination out.println(yLocation); - } - finally - { + } finally { out.close(); } } - protected String suffixForWorldFile(String suffix) - { + protected String suffixForWorldFile(String suffix) { int length = suffix.length(); - if (length < 2) + if (length < 2) { return ""; + } StringBuilder sb = new StringBuilder(); sb.append(Character.toLowerCase(suffix.charAt(0))); @@ -117,8 +105,7 @@ protected String suffixForWorldFile(String suffix) return sb.toString(); } - protected void initWorldFileParams(DataRaster raster, AVList worldFileParams) - { + protected void initWorldFileParams(DataRaster raster, AVList worldFileParams) { int[] size = new int[2]; size[0] = raster.getWidth(); size[1] = raster.getHeight(); @@ -128,22 +115,17 @@ protected void initWorldFileParams(DataRaster raster, AVList worldFileParams) worldFileParams.setValue(AVKey.SECTOR, sector); } - private static String[] getImageIOWriterSuffixes() - { + private static String[] getImageIOWriterSuffixes() { java.util.Iterator iter; - try - { + try { iter = javax.imageio.spi.IIORegistry.getDefaultInstance().getServiceProviders( - javax.imageio.spi.ImageWriterSpi.class, true); - } - catch (Exception e) - { + javax.imageio.spi.ImageWriterSpi.class, true); + } catch (Exception e) { return new String[0]; } java.util.Set set = new java.util.HashSet(); - while (iter.hasNext()) - { + while (iter.hasNext()) { javax.imageio.spi.ImageWriterSpi spi = iter.next(); String[] names = spi.getFileSuffixes(); set.addAll(java.util.Arrays.asList(names)); diff --git a/src/gov/nasa/worldwind/data/MipMappedBufferedImageRaster.java b/src/gov/nasa/worldwind/data/MipMappedBufferedImageRaster.java index 4d9fc0c4a4..e01ac96aee 100644 --- a/src/gov/nasa/worldwind/data/MipMappedBufferedImageRaster.java +++ b/src/gov/nasa/worldwind/data/MipMappedBufferedImageRaster.java @@ -12,27 +12,25 @@ * @author dcollins * @version $Id: MipMappedBufferedImageRaster.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MipMappedBufferedImageRaster extends BufferedImageRaster -{ +public class MipMappedBufferedImageRaster extends BufferedImageRaster { + protected BufferedImageRaster[] levelRasters; /** * Creates a mipmapped version of a BufferedImageRaster from a single BufferedImage instance. * * @param sector A sector - * @param image BufferedImage + * @param image BufferedImage */ - public MipMappedBufferedImageRaster(Sector sector, java.awt.image.BufferedImage image) - { + public MipMappedBufferedImageRaster(Sector sector, java.awt.image.BufferedImage image) { super(sector, image); int maxLevel = ImageUtil.getMaxMipmapLevel(image.getWidth(), image.getHeight()); java.awt.image.BufferedImage[] levelImages = ImageUtil.buildMipmaps(image, - java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE, maxLevel); + java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE, maxLevel); this.levelRasters = new BufferedImageRaster[1 + maxLevel]; - for (int i = 0; i <= maxLevel; i++) - { + for (int i = 0; i <= maxLevel; i++) { this.levelRasters[i] = new BufferedImageRaster(sector, levelImages[i]); } } @@ -43,54 +41,44 @@ public MipMappedBufferedImageRaster(Sector sector, java.awt.image.BufferedImage * @param sector A sector * @param images An array of BufferedImages */ - public MipMappedBufferedImageRaster(Sector sector, java.awt.image.BufferedImage[] images) - { + public MipMappedBufferedImageRaster(Sector sector, java.awt.image.BufferedImage[] images) { super(sector, (null != images && images.length > 0) ? images[0] : null); - if (null == sector) - { + if (null == sector) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == images || images.length == 0) - { + if (null == images || images.length == 0) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.levelRasters = new BufferedImageRaster[images.length]; - for (int i = 0; i < images.length; i++) - { + for (int i = 0; i < images.length; i++) { this.levelRasters[i] = new BufferedImageRaster(sector, images[i]); } } - public long getSizeInBytes() - { + public long getSizeInBytes() { long sizeInBytes = 0L; - for (BufferedImageRaster raster : this.levelRasters) - { + for (BufferedImageRaster raster : this.levelRasters) { sizeInBytes += raster.getSizeInBytes(); } return sizeInBytes; } - public void dispose() - { - for (BufferedImageRaster raster : this.levelRasters) - { + public void dispose() { + for (BufferedImageRaster raster : this.levelRasters) { raster.dispose(); } } - protected void doDrawOnTo(BufferedImageRaster canvas) - { - if (!this.getSector().intersects(canvas.getSector())) - { + protected void doDrawOnTo(BufferedImageRaster canvas) { + if (!this.getSector().intersects(canvas.getSector())) { return; } @@ -98,11 +86,10 @@ protected void doDrawOnTo(BufferedImageRaster canvas) raster.doDrawOnTo(canvas); } - protected BufferedImageRaster chooseRasterForCanvas(BufferedImageRaster canvas) - { + protected BufferedImageRaster chooseRasterForCanvas(BufferedImageRaster canvas) { int level = this.computeMipmapLevel( - this.getWidth(), this.getHeight(), this.getSector(), - canvas.getWidth(), canvas.getHeight(), canvas.getSector()); + this.getWidth(), this.getHeight(), this.getSector(), + canvas.getWidth(), canvas.getHeight(), canvas.getSector()); int maxLevel = this.levelRasters.length - 1; level = (int) WWMath.clamp(level, 0, maxLevel); @@ -111,16 +98,14 @@ protected BufferedImageRaster chooseRasterForCanvas(BufferedImageRaster canvas) } protected int computeMipmapLevel(int sourceWidth, int sourceHeight, Sector sourceSector, - int destWidth, int destHeight, Sector destSector) - { + int destWidth, int destHeight, Sector destSector) { double sy = ((double) sourceHeight / (double) destHeight) - * (destSector.getDeltaLatDegrees() / sourceSector.getDeltaLatDegrees()); + * (destSector.getDeltaLatDegrees() / sourceSector.getDeltaLatDegrees()); double sx = ((double) sourceWidth / (double) destWidth) - * (destSector.getDeltaLonDegrees() / sourceSector.getDeltaLonDegrees()); + * (destSector.getDeltaLonDegrees() / sourceSector.getDeltaLonDegrees()); double scale = Math.max(sx, sy); - if (scale < 1) - { + if (scale < 1) { return 0; } diff --git a/src/gov/nasa/worldwind/data/RPFRasterReader.java b/src/gov/nasa/worldwind/data/RPFRasterReader.java index 9f37f896f3..36e6e1673a 100644 --- a/src/gov/nasa/worldwind/data/RPFRasterReader.java +++ b/src/gov/nasa/worldwind/data/RPFRasterReader.java @@ -15,44 +15,41 @@ * @author dcollins * @version $Id: RPFRasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFRasterReader extends AbstractDataRasterReader -{ - public RPFRasterReader() - { +public class RPFRasterReader extends AbstractDataRasterReader { + + public RPFRasterReader() { super("RPF Imagery"); } - public boolean canRead(Object source, AVList params) - { - if (source == null) + public boolean canRead(Object source, AVList params) { + if (source == null) { return false; + } // RPF imagery cannot be identified by a small set of suffixes or mime types, so we override the standard // suffix comparison behavior here. - return this.doCanRead(source, params); } - protected boolean doCanRead(Object source, AVList params) - { - if (!(source instanceof java.io.File)) + protected boolean doCanRead(Object source, AVList params) { + if (!(source instanceof java.io.File)) { return false; + } java.io.File file = (java.io.File) source; String filename = file.getName().toUpperCase(); boolean canRead = RPFFrameFilename.isFilename(filename); - if (canRead && null != params && !params.hasKey(AVKey.PIXEL_FORMAT)) + if (canRead && null != params && !params.hasKey(AVKey.PIXEL_FORMAT)) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); + } return canRead; } - protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOException - { - if (!(source instanceof java.io.File)) - { + protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOException { + if (!(source instanceof java.io.File)) { String message = Logging.getMessage("DataRaster.CannotRead", source); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -60,20 +57,15 @@ protected DataRaster[] doRead(Object source, AVList params) throws java.io.IOExc java.io.File file = (java.io.File) source; RPFFrameFilename filename = RPFFrameFilename.parseFilename(file.getName().toUpperCase()); - if (filename.getZoneCode() == '9' || filename.getZoneCode() == 'J') - { + if (filename.getZoneCode() == '9' || filename.getZoneCode() == 'J') { return this.readPolarImage(source, filename); - } - else - { + } else { return this.readNonPolarImage(source, params); } } - protected void doReadMetadata(Object source, AVList params) throws java.io.IOException - { - if (!(source instanceof java.io.File)) - { + protected void doReadMetadata(Object source, AVList params) throws java.io.IOException { + if (!(source instanceof java.io.File)) { String message = Logging.getMessage("DataRaster.CannotRead", source); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -84,22 +76,22 @@ protected void doReadMetadata(Object source, AVList params) throws java.io.IOExc Object width = params.getValue(AVKey.WIDTH); Object height = params.getValue(AVKey.HEIGHT); - if (width == null || height == null || !(width instanceof Integer) || !(height instanceof Integer)) - { + if (width == null || height == null || !(width instanceof Integer) || !(height instanceof Integer)) { rpfFile = RPFImageFile.load(file); this.readFileSize(rpfFile, params); } Object sector = params.getValue(AVKey.SECTOR); - if (sector == null || !(sector instanceof Sector)) + if (sector == null || !(sector instanceof Sector)) { this.readFileSector(file, rpfFile, params); + } - if (!params.hasKey(AVKey.PIXEL_FORMAT)) + if (!params.hasKey(AVKey.PIXEL_FORMAT)) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); + } } - private DataRaster[] readNonPolarImage(Object source, AVList params) throws java.io.IOException - { + private DataRaster[] readNonPolarImage(Object source, AVList params) throws java.io.IOException { // TODO: break the raster along the international dateline, if necessary // Nonpolar images need no special processing. We convert it to a compatible image type to improve performance. @@ -111,19 +103,17 @@ private DataRaster[] readNonPolarImage(Object source, AVList params) throws java // If the data source doesn't already have all the necessary metadata, then we attempt to read the metadata. Object o = (params != null) ? params.getValue(AVKey.SECTOR) : null; - if (o == null || !(o instanceof Sector)) - { + if (o == null || !(o instanceof Sector)) { AVList values = new AVListImpl(); this.readFileSector(file, rpfFile, values); o = values.getValue(AVKey.SECTOR); } DataRaster raster = new BufferedImageRaster((Sector) o, image); - return new DataRaster[] {raster}; + return new DataRaster[]{raster}; } - private DataRaster[] readPolarImage(Object source, RPFFrameFilename filename) throws java.io.IOException - { + private DataRaster[] readPolarImage(Object source, RPFFrameFilename filename) throws java.io.IOException { java.io.File file = (java.io.File) source; RPFImageFile rpfFile = RPFImageFile.load(file); @@ -132,61 +122,54 @@ private DataRaster[] readPolarImage(Object source, RPFFrameFilename filename) th // This is a polar image. We must project it's raster and bounding sector into Geographic/WGS84. RPFDataSeries ds = RPFDataSeries.dataSeriesFor(filename.getDataSeriesCode()); RPFFrameTransform tx = RPFFrameTransform.createFrameTransform(filename.getZoneCode(), - ds.rpfDataType, ds.scaleOrGSD); + ds.rpfDataType, ds.scaleOrGSD); RPFFrameTransform.RPFImage[] images = tx.deproject(filename.getFrameNumber(), image); DataRaster[] rasters = new DataRaster[images.length]; - for (int i = 0; i < images.length; i++) - { + for (int i = 0; i < images.length; i++) { java.awt.image.BufferedImage compatibleImage = ImageUtil.toCompatibleImage(images[i].getImage()); rasters[i] = new BufferedImageRaster(images[i].getSector(), compatibleImage); } return rasters; } - private void readFileSize(RPFImageFile rpfFile, AVList values) - { + private void readFileSize(RPFImageFile rpfFile, AVList values) { int width = rpfFile.getImageSegment().numSignificantCols; int height = rpfFile.getImageSegment().numSignificantRows; values.setValue(AVKey.WIDTH, width); values.setValue(AVKey.HEIGHT, height); } - private void readFileSector(java.io.File file, RPFImageFile rpfFile, AVList values) - { + private void readFileSector(java.io.File file, RPFImageFile rpfFile, AVList values) { // We'll first attempt to compute the Sector, if possible, from the filename (if it exists) by using // the conventions for CADRG and CIB filenames. It has been observed that for polar frame files in // particular that coverage information in the file itself is sometimes unreliable. Sector sector = this.sectorFromFilename(file); // If the sector cannot be computed from the filename, then get it from the RPF file headers. - if (sector == null) + if (sector == null) { sector = this.sectorFromHeader(file, rpfFile); + } values.setValue(AVKey.SECTOR, sector); } - private Sector sectorFromFilename(java.io.File file) - { + private Sector sectorFromFilename(java.io.File file) { Sector sector = null; - try - { + try { // Parse the filename, using the conventions for CADRG and CIB filenames. RPFFrameFilename rpfFilename = RPFFrameFilename.parseFilename(file.getName().toUpperCase()); // Get the dataseries associated with that code. RPFDataSeries ds = RPFDataSeries.dataSeriesFor(rpfFilename.getDataSeriesCode()); // If the scale or GSD associated with the dataseries is valid, then proceed computing the georeferencing // information from the filename. Otherwise return null. - if (ds.scaleOrGSD > 0d) - { + if (ds.scaleOrGSD > 0d) { // Create a transform to compute coverage information. RPFFrameTransform tx = RPFFrameTransform.createFrameTransform( - rpfFilename.getZoneCode(), ds.rpfDataType, ds.scaleOrGSD); + rpfFilename.getZoneCode(), ds.rpfDataType, ds.scaleOrGSD); // Get coverage information from the transform. sector = tx.computeFrameCoverage(rpfFilename.getFrameNumber()); } - } - catch (Exception e) - { + } catch (Exception e) { // Computing the file's coverage failed. Log the condition and return null. // This at allows the coverage to be re-computed at a later time. String message = String.format("Exception while computing file sector: %s", file); @@ -196,16 +179,15 @@ private Sector sectorFromFilename(java.io.File file) return sector; } - private Sector sectorFromHeader(java.io.File file, RPFFile rpfFile) - { + private Sector sectorFromHeader(java.io.File file, RPFFile rpfFile) { Sector sector; - try - { - if (rpfFile == null) + try { + if (rpfFile == null) { rpfFile = RPFImageFile.load(file); + } NITFSImageSegment imageSegment = (NITFSImageSegment) rpfFile.getNITFSSegment( - NITFSSegmentType.IMAGE_SEGMENT); + NITFSSegmentType.IMAGE_SEGMENT); RPFFrameFileComponents comps = imageSegment.getUserDefinedImageSubheader().getRPFFrameFileComponents(); Angle minLat = comps.swLowerleft.getLatitude(); Angle maxLat = comps.neUpperRight.getLatitude(); @@ -213,18 +195,14 @@ private Sector sectorFromHeader(java.io.File file, RPFFile rpfFile) Angle maxLon = comps.neUpperRight.getLongitude(); // This sector spans the longitude boundary. In order to render this sector, // we must adjust the longitudes such that minLon 0) - { + if (Angle.crossesLongitudeBoundary(minLon, maxLon)) { + if (minLon.compareTo(maxLon) > 0) { double degrees = 360 + maxLon.degrees; maxLon = Angle.fromDegrees(degrees); } } sector = new Sector(minLat, maxLat, minLon, maxLon); - } - catch (Exception e) - { + } catch (Exception e) { // Computing the file's coverage failed. Log the condition and return null. // This at allows the coverage to be re-computed at a later time. String message = String.format("Exception while getting file sector: %s", file); diff --git a/src/gov/nasa/worldwind/data/RasterServer.java b/src/gov/nasa/worldwind/data/RasterServer.java index 0a596d5b48..b413816004 100644 --- a/src/gov/nasa/worldwind/data/RasterServer.java +++ b/src/gov/nasa/worldwind/data/RasterServer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.avlist.AVList; @@ -15,15 +14,15 @@ * @author tag * @version $Id: RasterServer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface RasterServer -{ +public interface RasterServer { + /** * Composes a Raster and returns as ByteBuffer in the requested format (image or elevation) * * @param params Required parameters in params: - *

    - * AVKey.WIDTH - the height of the requested raster AVKey.HEIGHT - the height of the requested raster - * AVKey.SECTOR - a regular Geographic Sector defined by lat/lon coordinates of corners + *

    + * AVKey.WIDTH - the height of the requested raster AVKey.HEIGHT - the height of the requested raster AVKey.SECTOR - + * a regular Geographic Sector defined by lat/lon coordinates of corners * * @return ByteBuffer of the requested file format */ diff --git a/src/gov/nasa/worldwind/data/RasterServerConfiguration.java b/src/gov/nasa/worldwind/data/RasterServerConfiguration.java index f69e5ec37c..07075c2f56 100644 --- a/src/gov/nasa/worldwind/data/RasterServerConfiguration.java +++ b/src/gov/nasa/worldwind/data/RasterServerConfiguration.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.data; import gov.nasa.worldwind.geom.Sector; @@ -21,35 +20,30 @@ * @author tag * @version $Id: RasterServerConfiguration.java 2813 2015-02-18 23:35:24Z tgaskins $ */ -public class RasterServerConfiguration extends AbstractXMLEventParser -{ - protected static class Property extends AbstractXMLEventParser - { - public Property(String namespaceURI) - { +public class RasterServerConfiguration extends AbstractXMLEventParser { + + protected static class Property extends AbstractXMLEventParser { + + public Property(String namespaceURI) { super(namespaceURI); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public String getValue() - { + public String getValue() { return (String) this.getField("value"); } } - protected static class RasterSector extends AbstractXMLEventParser - { - public RasterSector(String namespaceURI) - { + protected static class RasterSector extends AbstractXMLEventParser { + + public RasterSector(String namespaceURI) { super(namespaceURI); } - public Sector getSector() - { + public Sector getSector() { AbstractXMLEventParser corner = (AbstractXMLEventParser) this.getField("SouthWest"); AbstractXMLEventParser latLon = (AbstractXMLEventParser) corner.getField("LatLon"); Double minLat = Double.valueOf((String) latLon.getField("latitude")); @@ -61,68 +55,58 @@ public Sector getSector() Double maxLat = Double.valueOf((String) latLon.getField("latitude")); Double maxLon = Double.valueOf((String) latLon.getField("longitude")); - if (units.equals("radians")) + if (units.equals("radians")) { return Sector.fromRadians(minLat, maxLat, minLon, maxLon); - else + } else { return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); + } } } - protected static class Corner extends AbstractXMLEventParser - { - public Corner(String namespaceURI) - { + protected static class Corner extends AbstractXMLEventParser { + + public Corner(String namespaceURI) { super(namespaceURI); } } - public static class Source extends AbstractXMLEventParser - { - public Source(String namespaceURI) - { + public static class Source extends AbstractXMLEventParser { + + public Source(String namespaceURI) { super(namespaceURI); } - public String getPath() - { + public String getPath() { return (String) this.getField("path"); } - public String getType() - { + public String getType() { return (String) this.getField("type"); } - public Sector getSector() - { + public Sector getSector() { return ((RasterSector) this.getField("Sector")).getSector(); } } - protected static class Sources extends AbstractXMLEventParser - { + protected static class Sources extends AbstractXMLEventParser { + protected ArrayList sources = new ArrayList(); - public Sources(String namespaceURI) - { + public Sources(String namespaceURI) { super(namespaceURI); } - public ArrayList getSources() - { + public ArrayList getSources() { return this.sources; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Source")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Source")) { Source s = (Source) ctx.getParser(event).parse(ctx, event); this.sources.add(s); - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } @@ -135,8 +119,7 @@ protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Ob protected HashMap properties = new HashMap(); - public RasterServerConfiguration(Object docSource) - { + public RasterServerConfiguration(Object docSource) { super(namespaceURI); this.eventReader = this.createReader(docSource); @@ -144,63 +127,53 @@ public RasterServerConfiguration(Object docSource) this.initialize(); } - protected void initialize() - { + protected void initialize() { this.parserContext = this.createParserContext(this.eventReader); } - protected XMLEventReader createReader(Object docSource) - { + protected XMLEventReader createReader(Object docSource) { return WWXML.openEventReader(docSource); } - protected XMLEventParserContext createParserContext(XMLEventReader reader) - { + protected XMLEventParserContext createParserContext(XMLEventReader reader) { this.parserContext = new BasicXMLEventParserContext(reader); this.parserContext.setDefaultNamespaceURI(this.getNamespaceURI()); return this.parserContext; } - public XMLEventParserContext getParserContext() - { + public XMLEventParserContext getParserContext() { return this.parserContext; } - public String getVersion() - { + public String getVersion() { return (String) this.getField("version"); } - public Sector getSector() - { + public Sector getSector() { RasterSector sector = (RasterSector) this.getField("Sector"); return sector != null ? sector.getSector() : null; } - public HashMap getProperties() - { + public HashMap getProperties() { return this.properties; } - public ArrayList getSources() - { + public ArrayList getSources() { return ((Sources) this.getField("Sources")).getSources(); } - public RasterServerConfiguration parse(Object... args) throws XMLStreamException - { + public RasterServerConfiguration parse(Object... args) throws XMLStreamException { XMLEventParserContext ctx = this.parserContext; QName capsName = new QName(this.getNamespaceURI(), "RasterServer"); - for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isStartElement() && event.asStartElement().getName().equals(capsName)) - { + if (event.isStartElement() && event.asStartElement().getName().equals(capsName)) { // Parse the attributes in order to get the version number in order to determine the namespaces. this.doParseEventAttributes(ctx, event); ctx.setDefaultNamespaceURI(this.getNamespaceURI()); @@ -217,40 +190,35 @@ public RasterServerConfiguration parse(Object... args) throws XMLStreamException } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Property")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Property")) { Property p = (Property) ctx.getParser(event).parse(ctx, event); this.properties.put(p.getName(), p.getValue()); - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } - protected void registerParsers(XMLEventParserContext ctx) - { + protected void registerParsers(XMLEventParserContext ctx) { ctx.registerParser(new QName(this.getNamespaceURI(), "Property"), - new Property(this.getNamespaceURI())); + new Property(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "LatLon"), - new AttributesOnlyXMLEventParser(this.getNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "SouthWest"), - new Corner(this.getNamespaceURI())); + new Corner(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "NorthEast"), - new Corner(this.getNamespaceURI())); + new Corner(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "Sector"), - new RasterSector(this.getNamespaceURI())); + new RasterSector(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "Source"), - new Source(this.getNamespaceURI())); + new Source(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "Sources"), - new Sources(this.getNamespaceURI())); + new Sources(this.getNamespaceURI())); } } diff --git a/src/gov/nasa/worldwind/data/TiledElevationProducer.java b/src/gov/nasa/worldwind/data/TiledElevationProducer.java index 17982b7547..5dc717e4e6 100644 --- a/src/gov/nasa/worldwind/data/TiledElevationProducer.java +++ b/src/gov/nasa/worldwind/data/TiledElevationProducer.java @@ -18,8 +18,8 @@ * @author dcollins * @version $Id: TiledElevationProducer.java 3042 2015-04-21 23:25:59Z tgaskins $ */ -public class TiledElevationProducer extends TiledRasterProducer -{ +public class TiledElevationProducer extends TiledRasterProducer { + // Extreme elevations computed during production. protected double[] extremes = null; // Default production parameter values. @@ -28,21 +28,18 @@ public class TiledElevationProducer extends TiledRasterProducer // Statically reference the readers used to for unknown data sources. This drastically improves the performance of // reading large quantities of sources. Since the readers are invoked from a single thread, they can be // safely re-used. - protected static DataRasterReader[] readers = new DataRasterReader[] - { - new DTEDRasterReader(), - new GDALDataRasterReader(), - new BILRasterReader(), - new GeotiffRasterReader() - }; - - public TiledElevationProducer(MemoryCache cache, int writeThreadPoolSize) - { + protected static DataRasterReader[] readers = new DataRasterReader[]{ + new DTEDRasterReader(), + new GDALDataRasterReader(), + new BILRasterReader(), + new GeotiffRasterReader() + }; + + public TiledElevationProducer(MemoryCache cache, int writeThreadPoolSize) { super(cache, writeThreadPoolSize); } - public TiledElevationProducer() - { + public TiledElevationProducer() { super(); } @@ -54,23 +51,20 @@ public TiledElevationProducer() * @throws Exception if production fails for any reason. */ @Override - protected void doStartProduction(AVList parameters) throws Exception - { + protected void doStartProduction(AVList parameters) throws Exception { this.extremes = null; super.doStartProduction(parameters); } - public String getDataSourceDescription() - { + public String getDataSourceDescription() { StringBuilder sb = new StringBuilder(); sb.append(Logging.getMessage("TiledElevationProducer.Description")); sb.append(" (").append(super.getDataSourceDescription()).append(")"); return sb.toString(); } - protected DataRaster createDataRaster(int width, int height, Sector sector, AVList params) - { + protected DataRaster createDataRaster(int width, int height, Sector sector, AVList params) { // Create a BIL elevation raster to hold the tile's data. AVList bufferParams = new AVListImpl(); bufferParams.setValue(AVKey.DATA_TYPE, params.getValue(AVKey.DATA_TYPE)); @@ -81,8 +75,7 @@ protected DataRaster createDataRaster(int width, int height, Sector sector, AVLi // This code expects the string "gov.nasa.worldwind.avkey.MissingDataValue", which now corresponds to the key // MISSING_DATA_REPLACEMENT. Object o = params.getValue(AVKey.MISSING_DATA_REPLACEMENT); - if (o != null && o instanceof Double) - { + if (o != null && o instanceof Double) { Double missingDataValue = (Double) o; bufferRaster.fill(missingDataValue); bufferRaster.setTransparentValue(missingDataValue); @@ -91,73 +84,58 @@ protected DataRaster createDataRaster(int width, int height, Sector sector, AVLi return bufferRaster; } - protected DataRasterReader[] getDataRasterReaders() - { + protected DataRasterReader[] getDataRasterReaders() { return readers; } - protected DataRasterWriter[] getDataRasterWriters() - { - return new DataRasterWriter[] - { - // Configure the BIL writer to disable writing of georeference files. Georeferencing files are redundant - // for tiled elevations. The elevation format is defined in the data configuration file, and each - // tile's georeferencing information is implicit in the tile structure. - new BILRasterWriter(true) // TODO: debugging change - }; + protected DataRasterWriter[] getDataRasterWriters() { + return new DataRasterWriter[]{ + // Configure the BIL writer to disable writing of georeference files. Georeferencing files are redundant + // for tiled elevations. The elevation format is defined in the data configuration file, and each + // tile's georeferencing information is implicit in the tile structure. + new BILRasterWriter(true) // TODO: debugging change + }; } - protected String validateDataSource(Object source, AVList params) - { + protected String validateDataSource(Object source, AVList params) { // TiledElevationProducer does not accept null data sources. - if (source == null) - { + if (source == null) { return Logging.getMessage("nullValue.SourceIsNull"); } // TiledElevationProducer accepts BufferWrapperRaster as a data source. If the data source is a DataRaster, then // check that it's a BufferWrapperRaster. - if (source instanceof DataRaster) - { + if (source instanceof DataRaster) { DataRaster raster = (DataRaster) source; - if (!(raster instanceof BufferWrapperRaster)) - { + if (!(raster instanceof BufferWrapperRaster)) { return Logging.getMessage("TiledRasterProducer.UnrecognizedDataSource", raster); } String s = this.validateDataSourceParams(raster, String.valueOf(raster)); - if (s != null) - { + if (s != null) { return s; } - } - // For any other data source, attempt to find a reader for the data source. If the reader know's the data + } // For any other data source, attempt to find a reader for the data source. If the reader know's the data // source's raster type, then check that it's elevation data. - else - { + else { DataRasterReader reader = this.getReaderFactory().findReaderFor(source, params, - this.getDataRasterReaders()); - if (reader == null) - { + this.getDataRasterReaders()); + if (reader == null) { return Logging.getMessage("TiledRasterProducer.UnrecognizedDataSource", source); } // Copy the parameter list to insulate changes from the caller. params = (params != null) ? params.copy() : new AVListImpl(); - try - { + try { reader.readMetadata(source, params); - } - catch (IOException e) - { + } catch (IOException e) { return Logging.getMessage("TiledRasterProducer.ExceptionWhileReading", source, e.getMessage()); } String s = this.validateDataSourceParams(params, String.valueOf(source)); - if (s != null) - { + if (s != null) { return s; } } @@ -165,113 +143,92 @@ protected String validateDataSource(Object source, AVList params) return null; } - protected String validateDataSourceParams(AVList params, String name) - { - if (params.hasKey(AVKey.PIXEL_FORMAT) && params.getValue(AVKey.PIXEL_FORMAT) != AVKey.ELEVATION) - { + protected String validateDataSourceParams(AVList params, String name) { + if (params.hasKey(AVKey.PIXEL_FORMAT) && params.getValue(AVKey.PIXEL_FORMAT) != AVKey.ELEVATION) { return Logging.getMessage("TiledRasterProducer.UnrecognizedRasterType", - params.getValue(AVKey.PIXEL_FORMAT), name); + params.getValue(AVKey.PIXEL_FORMAT), name); } if (params.hasKey(AVKey.COORDINATE_SYSTEM) - && params.getValue(AVKey.COORDINATE_SYSTEM) != AVKey.COORDINATE_SYSTEM_GEOGRAPHIC - && params.getValue(AVKey.COORDINATE_SYSTEM) != AVKey.COORDINATE_SYSTEM_PROJECTED - ) - - { + && params.getValue(AVKey.COORDINATE_SYSTEM) != AVKey.COORDINATE_SYSTEM_GEOGRAPHIC + && params.getValue(AVKey.COORDINATE_SYSTEM) != AVKey.COORDINATE_SYSTEM_PROJECTED) { return Logging.getMessage("TiledRasterProducer.UnrecognizedCoordinateSystem", - params.getValue(AVKey.COORDINATE_SYSTEM), name); + params.getValue(AVKey.COORDINATE_SYSTEM), name); } if (params.hasKey(AVKey.ELEVATION_UNIT) - && params.getValue(AVKey.ELEVATION_UNIT) != AVKey.UNIT_METER - && params.getValue(AVKey.ELEVATION_UNIT) != AVKey.UNIT_FOOT - ) - { + && params.getValue(AVKey.ELEVATION_UNIT) != AVKey.UNIT_METER + && params.getValue(AVKey.ELEVATION_UNIT) != AVKey.UNIT_FOOT) { return Logging.getMessage("TiledElevationProducer.UnrecognizedElevationUnit", - params.getValue(AVKey.ELEVATION_UNIT), name); + params.getValue(AVKey.ELEVATION_UNIT), name); } - if (params.getValue(AVKey.SECTOR) == null) - { + if (params.getValue(AVKey.SECTOR) == null) { return Logging.getMessage("TiledRasterProducer.NoSector", name); } return null; } - protected void initProductionParameters(AVList params) - { + protected void initProductionParameters(AVList params) { // Preserve backward compatibility with previous versions of TiledElevationProducer. If the caller specified a // format suffix parameter, use it to compute the image format properties. This gives priority to the format // suffix property to ensure applications which use format suffix continue to work. - if (params.getValue(AVKey.FORMAT_SUFFIX) != null) - { + if (params.getValue(AVKey.FORMAT_SUFFIX) != null) { String s = WWIO.makeMimeTypeForSuffix(params.getValue(AVKey.FORMAT_SUFFIX).toString()); - if (s != null) - { + if (s != null) { params.setValue(AVKey.IMAGE_FORMAT, s); - params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, new String[] {s}); + params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, new String[]{s}); } } - if (params.getValue(AVKey.PIXEL_FORMAT) == null) - { + if (params.getValue(AVKey.PIXEL_FORMAT) == null) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); } // Use the default image format if none exists. - if (params.getValue(AVKey.IMAGE_FORMAT) == null) - { + if (params.getValue(AVKey.IMAGE_FORMAT) == null) { params.setValue(AVKey.IMAGE_FORMAT, DEFAULT_IMAGE_FORMAT); } // Compute the available image formats if none exists. - if (params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) == null) - { + if (params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) == null) { params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, - new String[] {params.getValue(AVKey.IMAGE_FORMAT).toString()}); + new String[]{params.getValue(AVKey.IMAGE_FORMAT).toString()}); } // Compute the format suffix if none exists. - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) - { + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { params.setValue(AVKey.FORMAT_SUFFIX, - WWIO.makeSuffixForMimeType(params.getValue(AVKey.IMAGE_FORMAT).toString())); + WWIO.makeSuffixForMimeType(params.getValue(AVKey.IMAGE_FORMAT).toString())); } // Compute the data type from the image format. - if (params.getValue(AVKey.DATA_TYPE) == null && params.getValue(AVKey.IMAGE_FORMAT) != null) - { + if (params.getValue(AVKey.DATA_TYPE) == null && params.getValue(AVKey.IMAGE_FORMAT) != null) { String s = WWIO.makeDataTypeForMimeType(params.getValue(AVKey.IMAGE_FORMAT).toString()); - if (s != null) - { + if (s != null) { params.setValue(AVKey.DATA_TYPE, s); } } // Use the default data type if none exists. - if (params.getValue(AVKey.DATA_TYPE) == null) - { + if (params.getValue(AVKey.DATA_TYPE) == null) { params.setValue(AVKey.DATA_TYPE, AVKey.INT16); } // Use the default byte order if none exists. - if (params.getValue(AVKey.BYTE_ORDER) == null) - { + if (params.getValue(AVKey.BYTE_ORDER) == null) { params.setValue(AVKey.BYTE_ORDER, AVKey.LITTLE_ENDIAN); } // This code expects the string "gov.nasa.worldwind.avkey.MissingDataValue", which now corresponds to the key // MISSING_DATA_REPLACEMENT. - if (params.getValue(AVKey.MISSING_DATA_REPLACEMENT) == null) - { + if (params.getValue(AVKey.MISSING_DATA_REPLACEMENT) == null) { params.setValue(AVKey.MISSING_DATA_REPLACEMENT, DEFAULT_MISSING_DATA_SIGNAL); } } - protected LatLon computeRasterTileDelta(int tileWidth, int tileHeight, Iterable rasters) - { + protected LatLon computeRasterTileDelta(int tileWidth, int tileHeight, Iterable rasters) { LatLon pixelSize = this.computeSmallestPixelSize(rasters); // Compute the tile size in latitude and longitude, given a raster's sector and dimension, and the tile // dimensions. In this computation a pixel is assumed to have no dimension. We measure the distance between @@ -281,25 +238,23 @@ protected LatLon computeRasterTileDelta(int tileWidth, int tileHeight, Iterable< return LatLon.fromDegrees(latDelta, lonDelta); } - protected LatLon computeRasterPixelSize(DataRaster raster) - { + protected LatLon computeRasterPixelSize(DataRaster raster) { // Compute the raster's pixel dimension in latitude and longitude. In this computation a pixel is assumed to // have no dimension. We measure the distance between pixels rather than some pixel dimension. return LatLon.fromDegrees( - raster.getSector().getDeltaLatDegrees() / (raster.getHeight() - 1), - raster.getSector().getDeltaLonDegrees() / (raster.getWidth() - 1)); + raster.getSector().getDeltaLatDegrees() / (raster.getHeight() - 1), + raster.getSector().getDeltaLonDegrees() / (raster.getWidth() - 1)); } /** * Overridden to compute the extreme elevations prior to installing a tile in the filesystem. * - * @param tile the tile to install to the filesystem. + * @param tile the tile to install to the filesystem. * @param tileRaster the raster containing the raster's data content. - * @param params the installation parameters. + * @param params the installation parameters. */ @Override - protected void installTileRasterLater(LevelSet levelSet, Tile tile, DataRaster tileRaster, AVList params) - { + protected void installTileRasterLater(LevelSet levelSet, Tile tile, DataRaster tileRaster, AVList params) { // There used to be code here to update the extremes only when processing tiles in the highest-resolution // level. But that caused the extremes not to be determined at all when a full pyramid isn't generated. We // now update the extremes for every tile, not just the highest resolution ones. @@ -308,10 +263,8 @@ protected void installTileRasterLater(LevelSet levelSet, Tile tile, DataRaster t super.installTileRasterLater(levelSet, tile, tileRaster, params); } - protected void updateExtremeElevations(DataRaster raster) - { - if (!(raster instanceof BufferWrapperRaster)) - { + protected void updateExtremeElevations(DataRaster raster) { + if (!(raster instanceof BufferWrapperRaster)) { String message = Logging.getMessage("DataRaster.IncompatibleRaster", raster); Logging.logger().severe(message); return; @@ -319,34 +272,26 @@ protected void updateExtremeElevations(DataRaster raster) // Compute the raster's extreme elevations. If the returned array is null, the tile is either empty or contains // only missing data values. In either case, this tile does not contribute to the overall extreme elevations. - - if (this.extremes == null) - { + if (this.extremes == null) { this.extremes = WWUtil.defaultMinMix(); } double[] tileExtremes = new double[2]; - if (raster.hasKey(AVKey.ELEVATION_MIN) && raster.hasKey(AVKey.ELEVATION_MAX)) - { + if (raster.hasKey(AVKey.ELEVATION_MIN) && raster.hasKey(AVKey.ELEVATION_MAX)) { tileExtremes[0] = (Double) raster.getValue(AVKey.ELEVATION_MAX); tileExtremes[1] = (Double) raster.getValue(AVKey.ELEVATION_MIN); - } - else - { + } else { tileExtremes = ((BufferWrapperRaster) raster).getExtremes(); - if (tileExtremes == null || tileExtremes.length < 2) - { + if (tileExtremes == null || tileExtremes.length < 2) { return; } } - if (this.extremes[0] > tileExtremes[0]) - { + if (this.extremes[0] > tileExtremes[0]) { this.extremes[0] = tileExtremes[0]; } - if (this.extremes[1] < tileExtremes[1]) - { + if (this.extremes[1] < tileExtremes[1]) { this.extremes[1] = tileExtremes[1]; } } @@ -362,19 +307,16 @@ protected void updateExtremeElevations(DataRaster raster) * @return the configuration document, or null if the parameter list is null or does not contain the required * parameters. */ - protected Document createConfigDoc(AVList params) - { + protected Document createConfigDoc(AVList params) { AVList configParams = params.copy(); // Determine a default display name if none exists. - if (configParams.getValue(AVKey.DISPLAY_NAME) == null) - { + if (configParams.getValue(AVKey.DISPLAY_NAME) == null) { configParams.setValue(AVKey.DISPLAY_NAME, params.getValue(AVKey.DATASET_NAME)); } // Set the SERVICE_NAME and NETWORK_RETRIEVAL_ENABLED parameters to indicate this dataset is offline. - if (configParams.getValue(AVKey.SERVICE_NAME) == null) - { + if (configParams.getValue(AVKey.SERVICE_NAME) == null) { configParams.setValue(AVKey.SERVICE_NAME, AVKey.SERVICE_NAME_OFFLINE); } @@ -390,15 +332,13 @@ protected Document createConfigDoc(AVList params) // values ELEVATION_MIN and ELEVATION_MAX. If the extremes array is null or has length less than 2, the imported // elevations are either empty or contain only missing data values. In either case we cannot determine the // extreme values. - if (this.extremes != null && this.extremes.length >= 2) - { + if (this.extremes != null && this.extremes.length >= 2) { configParams.setValue(AVKey.ELEVATION_MIN, this.extremes[0]); configParams.setValue(AVKey.ELEVATION_MAX, this.extremes[1]); } // Return a configuration file for a BasicElevationModel. BasicElevationModel is the standard WWJ component // which consumes tiled elevation data. - return BasicElevationModel.createBasicElevationModelConfigDocument(configParams); } } diff --git a/src/gov/nasa/worldwind/data/TiledImageProducer.java b/src/gov/nasa/worldwind/data/TiledImageProducer.java index ea782c8c54..ef56a36aff 100644 --- a/src/gov/nasa/worldwind/data/TiledImageProducer.java +++ b/src/gov/nasa/worldwind/data/TiledImageProducer.java @@ -18,185 +18,160 @@ * @author dcollins * @version $Id: TiledImageProducer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TiledImageProducer extends TiledRasterProducer -{ +public class TiledImageProducer extends TiledRasterProducer { + protected static final String DEFAULT_IMAGE_FORMAT = "image/png"; protected static final String DEFAULT_TEXTURE_FORMAT = "image/dds"; // Statically reference the readers used to for unknown data sources. This drastically improves the performance of // reading large quantities of sources. Since the readers are invoked from a single thread, they can be // safely re-used. - protected static DataRasterReader[] readers = new DataRasterReader[] - { - new RPFRasterReader(), - new GDALDataRasterReader(), - new ImageIORasterReader(), - new GeotiffRasterReader() - }; - - public TiledImageProducer(MemoryCache cache, int writeThreadPoolSize) - { + protected static DataRasterReader[] readers = new DataRasterReader[]{ + new RPFRasterReader(), + new GDALDataRasterReader(), + new ImageIORasterReader(), + new GeotiffRasterReader() + }; + + public TiledImageProducer(MemoryCache cache, int writeThreadPoolSize) { super(cache, writeThreadPoolSize); } - public TiledImageProducer() - { + public TiledImageProducer() { super(); } - public String getDataSourceDescription() - { + public String getDataSourceDescription() { StringBuilder sb = new StringBuilder(); sb.append(Logging.getMessage("TiledImageProducer.Description")); sb.append(" (").append(super.getDataSourceDescription()).append(")"); return sb.toString(); } - protected DataRaster createDataRaster(int width, int height, Sector sector, AVList params) - { + protected DataRaster createDataRaster(int width, int height, Sector sector, AVList params) { int transparency = java.awt.image.BufferedImage.TRANSLUCENT; // TODO: make configurable //noinspection UnnecessaryLocalVariable BufferedImageRaster raster = new BufferedImageRaster(width, height, transparency, sector); return raster; } - protected DataRasterReader[] getDataRasterReaders() - { + protected DataRasterReader[] getDataRasterReaders() { return readers; } - protected DataRasterWriter[] getDataRasterWriters() - { - return new DataRasterWriter[] - { - // Configure the ImageIO writer to disable writing of georeference files. Georeferencing files are - // redundant for tiled images. The image format is defined in the data configuration file, and each - // tile's georeferencing information is implicit in the tile structure. - new ImageIORasterWriter(false), - new DDSRasterWriter() - }; + protected DataRasterWriter[] getDataRasterWriters() { + return new DataRasterWriter[]{ + // Configure the ImageIO writer to disable writing of georeference files. Georeferencing files are + // redundant for tiled images. The image format is defined in the data configuration file, and each + // tile's georeferencing information is implicit in the tile structure. + new ImageIORasterWriter(false), + new DDSRasterWriter() + }; } - protected String validateDataSource(Object source, AVList params) - { + protected String validateDataSource(Object source, AVList params) { // TiledImageProducer does not accept null data sources. - if (source == null) + if (source == null) { return Logging.getMessage("nullValue.SourceIsNull"); + } // TiledRasterProducer accepts BufferedImageRaster as a data source. If the data source is a DataRaster, then // check that it's a BufferedImageRaster. // TODO garakl DataSource as a source? What about GDALDataRaster - if (source instanceof DataRaster) - { + if (source instanceof DataRaster) { DataRaster raster = (DataRaster) source; - if (!(raster instanceof BufferedImageRaster)) + if (!(raster instanceof BufferedImageRaster)) { return Logging.getMessage("TiledRasterProducer.UnrecognizedDataSource", raster); + } String s = this.validateDataSourceParams(raster, String.valueOf(raster)); - if (s != null) + if (s != null) { return s; - } - // For any other data source, attempt to find a reader for the data source. If the reader knows the data + } + } // For any other data source, attempt to find a reader for the data source. If the reader knows the data // source's raster type, then check that it's a color image or a monochromatic image. - else - { + else { params = (params == null) ? new AVListImpl() : params; DataRasterReader reader = this.getReaderFactory().findReaderFor(source, params, - this.getDataRasterReaders()); + this.getDataRasterReaders()); - if (reader == null) - { + if (reader == null) { return Logging.getMessage("TiledRasterProducer.UnrecognizedDataSource", source); - } - else if (reader instanceof RPFRasterReader) - { + } else if (reader instanceof RPFRasterReader) { // RPF rasters are geo-referenced, so we may skip the validation return null; } String errMsg = this.validateDataSourceParams(params, String.valueOf(source)); - if (!WWUtil.isEmpty(errMsg)) - { - try - { + if (!WWUtil.isEmpty(errMsg)) { + try { reader.readMetadata(source, params); errMsg = this.validateDataSourceParams(params, String.valueOf(source)); - } - catch (IOException e) - { + } catch (IOException e) { return Logging.getMessage("TiledRasterProducer.ExceptionWhileReading", source, e.getMessage()); } } - if (!WWUtil.isEmpty(errMsg)) + if (!WWUtil.isEmpty(errMsg)) { return errMsg; + } } return null; } - protected String validateDataSourceParams(AVList params, String name) - { - if (params.hasKey(AVKey.PIXEL_FORMAT) && params.getValue(AVKey.PIXEL_FORMAT) != AVKey.IMAGE) - { + protected String validateDataSourceParams(AVList params, String name) { + if (params.hasKey(AVKey.PIXEL_FORMAT) && params.getValue(AVKey.PIXEL_FORMAT) != AVKey.IMAGE) { return Logging.getMessage("TiledRasterProducer.UnrecognizedRasterType", - params.getValue(AVKey.PIXEL_FORMAT), name); + params.getValue(AVKey.PIXEL_FORMAT), name); } if (params.hasKey(AVKey.COORDINATE_SYSTEM) - && params.getValue(AVKey.COORDINATE_SYSTEM) != AVKey.COORDINATE_SYSTEM_GEOGRAPHIC - && params.getValue(AVKey.COORDINATE_SYSTEM) != AVKey.COORDINATE_SYSTEM_PROJECTED - ) - { + && params.getValue(AVKey.COORDINATE_SYSTEM) != AVKey.COORDINATE_SYSTEM_GEOGRAPHIC + && params.getValue(AVKey.COORDINATE_SYSTEM) != AVKey.COORDINATE_SYSTEM_PROJECTED) { return Logging.getMessage("TiledRasterProducer.UnrecognizedCoordinateSystem", - params.getValue(AVKey.COORDINATE_SYSTEM), name); + params.getValue(AVKey.COORDINATE_SYSTEM), name); } - if (params.getValue(AVKey.SECTOR) == null) + if (params.getValue(AVKey.SECTOR) == null) { return Logging.getMessage("TiledRasterProducer.NoSector", name); + } return null; } - protected void initProductionParameters(AVList params) - { + protected void initProductionParameters(AVList params) { // Preserve backward compatibility with previous versions of TiledImageProducer. If the caller specified a // format suffix parameter, use it to compute the image format properties. This gives priority to the format // suffix property to ensure applications which use format suffix continue to work. - if (params.getValue(AVKey.FORMAT_SUFFIX) != null) - { + if (params.getValue(AVKey.FORMAT_SUFFIX) != null) { String s = WWIO.makeMimeTypeForSuffix(params.getValue(AVKey.FORMAT_SUFFIX).toString()); - if (s != null) - { + if (s != null) { params.setValue(AVKey.IMAGE_FORMAT, s); - params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, new String[] {s}); + params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, new String[]{s}); } } - if (params.getValue(AVKey.PIXEL_FORMAT) == null) - { + if (params.getValue(AVKey.PIXEL_FORMAT) == null) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); } // Use the default image format if none exists. - if (params.getValue(AVKey.IMAGE_FORMAT) == null) - { + if (params.getValue(AVKey.IMAGE_FORMAT) == null) { params.setValue(AVKey.IMAGE_FORMAT, DEFAULT_IMAGE_FORMAT); } // Compute the available image formats if none exists. - if (params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) == null) - { + if (params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) == null) { params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, - new String[] {params.getValue(AVKey.IMAGE_FORMAT).toString()}); + new String[]{params.getValue(AVKey.IMAGE_FORMAT).toString()}); } // Compute the format suffix if none exists. - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) - { + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { params.setValue(AVKey.FORMAT_SUFFIX, - WWIO.makeSuffixForMimeType(params.getValue(AVKey.IMAGE_FORMAT).toString())); + WWIO.makeSuffixForMimeType(params.getValue(AVKey.IMAGE_FORMAT).toString())); } } @@ -209,19 +184,20 @@ protected void initProductionParameters(AVList params) * @param params the parameters which describe a Layer configuration document's contents. * * @return the configuration document, or null if the parameter list is null or does not contain the required - * parameters. + * parameters. */ - protected Document createConfigDoc(AVList params) - { + protected Document createConfigDoc(AVList params) { AVList configParams = params.copy(); // Determine a default display name if none exists. - if (configParams.getValue(AVKey.DISPLAY_NAME) == null) + if (configParams.getValue(AVKey.DISPLAY_NAME) == null) { configParams.setValue(AVKey.DISPLAY_NAME, params.getValue(AVKey.DATASET_NAME)); + } // Set the SERVICE_NAME and NETWORK_RETRIEVAL_ENABLED parameters to indicate this dataset is offline. - if (configParams.getValue(AVKey.SERVICE_NAME) == null) + if (configParams.getValue(AVKey.SERVICE_NAME) == null) { configParams.setValue(AVKey.SERVICE_NAME, AVKey.SERVICE_NAME_OFFLINE); + } configParams.setValue(AVKey.NETWORK_RETRIEVAL_ENABLED, Boolean.FALSE); @@ -236,7 +212,6 @@ protected Document createConfigDoc(AVList params) // Return a configuration file for a TiledImageLayer. TiledImageLayer is the standard WWJ component which // consumes and renders tiled imagery. - return BasicTiledImageLayer.createTiledImageLayerConfigDocument(configParams); } } diff --git a/src/gov/nasa/worldwind/data/TiledRasterProducer.java b/src/gov/nasa/worldwind/data/TiledRasterProducer.java index 492d750fa4..9b0822795e 100644 --- a/src/gov/nasa/worldwind/data/TiledRasterProducer.java +++ b/src/gov/nasa/worldwind/data/TiledRasterProducer.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: TiledRasterProducer.java 3043 2015-04-22 20:56:26Z tgaskins $ */ -public abstract class TiledRasterProducer extends AbstractDataStoreProducer -{ +public abstract class TiledRasterProducer extends AbstractDataStoreProducer { + private static final long DEFAULT_TILED_RASTER_PRODUCER_CACHE_SIZE = 300000000L; // ~300 megabytes private static final int DEFAULT_TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD = 3000; // 3000 pixels private static final int DEFAULT_WRITE_THREAD_POOL_SIZE = 2; @@ -44,16 +44,13 @@ public abstract class TiledRasterProducer extends AbstractDataStoreProducer private DataRasterReaderFactory readerFactory; - public TiledRasterProducer(MemoryCache cache, int writeThreadPoolSize) - { - if (cache == null) - { + public TiledRasterProducer(MemoryCache cache, int writeThreadPoolSize) { + if (cache == null) { String message = Logging.getMessage("nullValue.CacheIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (writeThreadPoolSize < 1) - { + if (writeThreadPoolSize < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "writeThreadPoolSize < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -63,93 +60,81 @@ public TiledRasterProducer(MemoryCache cache, int writeThreadPoolSize) this.tileWriteService = this.createDefaultTileWriteService(writeThreadPoolSize); this.tileWriteSemaphore = new java.util.concurrent.Semaphore(writeThreadPoolSize, true); - try - { + try { readerFactory = (DataRasterReaderFactory) WorldWind.createConfigurationComponent( - AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); - } - catch (Exception e) - { + AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); + } catch (Exception e) { readerFactory = new BasicDataRasterReaderFactory(); } } - public TiledRasterProducer() - { + public TiledRasterProducer() { this(createDefaultCache(), DEFAULT_WRITE_THREAD_POOL_SIZE); } - public Iterable getDataRasters() - { + public Iterable getDataRasters() { return this.dataRasterList; } - protected DataRasterReaderFactory getReaderFactory() - { + protected DataRasterReaderFactory getReaderFactory() { return this.readerFactory; } // TODO: this describes the file types the producer will read. Make that more clear in the method name. - - public String getDataSourceDescription() - { + public String getDataSourceDescription() { DataRasterReader[] readers = this.getDataRasterReaders(); - if (readers == null || readers.length < 1) + if (readers == null || readers.length < 1) { return ""; + } // Collect all the unique format suffixes available in all readers. If a reader does not publish any // format suffixes, then collect it's description. java.util.Set suffixSet = new java.util.TreeSet(); java.util.Set descriptionSet = new java.util.TreeSet(); - for (DataRasterReader reader : readers) - { + for (DataRasterReader reader : readers) { String description = reader.getDescription(); String[] names = reader.getSuffixes(); - if (names != null && names.length > 0) + if (names != null && names.length > 0) { suffixSet.addAll(java.util.Arrays.asList(names)); - else + } else { descriptionSet.add(description); + } } // Create a string representation of the format suffixes (or description if no suffixes are available) for // all readers. StringBuilder sb = new StringBuilder(); - for (String suffix : suffixSet) - { - if (sb.length() > 0) + for (String suffix : suffixSet) { + if (sb.length() > 0) { sb.append(", "); + } sb.append("*.").append(suffix); } - for (String description : descriptionSet) - { - if (sb.length() > 0) + for (String description : descriptionSet) { + if (sb.length() > 0) { sb.append(", "); + } sb.append(description); } return sb.toString(); } - public void removeProductionState() - { + public void removeProductionState() { java.io.File installLocation = this.installLocationFor(this.getStoreParameters()); - if (installLocation == null || !installLocation.exists()) - { + if (installLocation == null || !installLocation.exists()) { String message = Logging.getMessage("TiledRasterProducer.NoInstallLocation", - this.getStoreParameters().getValue(AVKey.DATASET_NAME)); + this.getStoreParameters().getValue(AVKey.DATASET_NAME)); Logging.logger().warning(message); return; } - try - { + try { WWIO.deleteDirectory(installLocation); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("TiledRasterProducer.ExceptionRemovingProductionState", - this.getStoreParameters().getValue(AVKey.DATASET_NAME)); + this.getStoreParameters().getValue(AVKey.DATASET_NAME)); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } @@ -160,23 +145,19 @@ public void removeProductionState() protected abstract DataRasterWriter[] getDataRasterWriters(); - protected MemoryCache getCache() - { + protected MemoryCache getCache() { return this.rasterCache; } - protected java.util.concurrent.ExecutorService getTileWriteService() - { + protected java.util.concurrent.ExecutorService getTileWriteService() { return this.tileWriteService; } - protected java.util.concurrent.Semaphore getTileWriteSemaphore() - { + protected java.util.concurrent.Semaphore getTileWriteSemaphore() { return this.tileWriteSemaphore; } - protected void doStartProduction(AVList parameters) throws Exception - { + protected void doStartProduction(AVList parameters) throws Exception { // Copy production parameters to prevent changes to caller's reference. this.productionParams = parameters.copy(); this.initProductionParameters(this.productionParams); @@ -199,44 +180,47 @@ protected void doStartProduction(AVList parameters) throws Exception // Install the data descriptor for this tiled raster set. this.installConfigFile(this.productionParams); - if (AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER.equals(this.productionParams.getValue(AVKey.SERVICE_NAME))) - { + if (AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER.equals(this.productionParams.getValue(AVKey.SERVICE_NAME))) { this.installRasterServerConfigFile(this.productionParams); } } - protected String validateProductionParameters(AVList parameters) - { + protected String validateProductionParameters(AVList parameters) { StringBuilder sb = new StringBuilder(); Object o = parameters.getValue(AVKey.FILE_STORE_LOCATION); - if (o == null || !(o instanceof String) || ((String) o).length() < 1) + if (o == null || !(o instanceof String) || ((String) o).length() < 1) { sb.append((sb.length() > 0 ? ", " : "")).append(Logging.getMessage("term.fileStoreLocation")); + } o = parameters.getValue(AVKey.DATA_CACHE_NAME); - if (o == null || !(o instanceof String) || ((String) o).length() == 0) + if (o == null || !(o instanceof String) || ((String) o).length() == 0) { sb.append((sb.length() > 0 ? ", " : "")).append(Logging.getMessage("term.fileStoreFolder")); + } o = parameters.getValue(AVKey.DATASET_NAME); - if (o == null || !(o instanceof String) || ((String) o).length() < 1) + if (o == null || !(o instanceof String) || ((String) o).length() < 1) { sb.append((sb.length() > 0 ? ", " : "")).append(Logging.getMessage("term.datasetName")); + } - if (sb.length() == 0) + if (sb.length() == 0) { return null; + } return Logging.getMessage("DataStoreProducer.InvalidDataStoreParamters", sb.toString()); } - protected java.io.File installLocationFor(AVList params) - { + protected java.io.File installLocationFor(AVList params) { String fileStoreLocation = params.getStringValue(AVKey.FILE_STORE_LOCATION); String dataCacheName = params.getStringValue(AVKey.DATA_CACHE_NAME); - if (fileStoreLocation == null || dataCacheName == null) + if (fileStoreLocation == null || dataCacheName == null) { return null; + } String path = WWIO.appendPathPart(fileStoreLocation, dataCacheName); - if (path == null || path.length() == 0) + if (path == null || path.length() == 0) { return null; + } return new java.io.File(path); } @@ -244,36 +228,32 @@ protected java.io.File installLocationFor(AVList params) //**************************************************************// //******************** LevelSet Assembly *********************// //**************************************************************// - protected abstract void initProductionParameters(AVList params); - protected void initLevelSetParameters(AVList params) - { + protected void initLevelSetParameters(AVList params) { int largeThreshold = Configuration.getIntegerValue(AVKey.TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD, - DEFAULT_TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD); + DEFAULT_TILED_RASTER_PRODUCER_LARGE_DATASET_THRESHOLD); boolean isDataSetLarge = this.isDataSetLarge(this.dataRasterList, largeThreshold); Sector sector = (Sector) params.getValue(AVKey.SECTOR); - if (sector == null) - { + if (sector == null) { // Compute a sector that bounds the data rasters. Make sure the sector does not exceed the limits of // latitude and longitude. sector = this.computeBoundingSector(this.dataRasterList); - if (sector != null) + if (sector != null) { sector = sector.intersection(Sector.FULL_SPHERE); + } params.setValue(AVKey.SECTOR, sector); } Integer tileWidth = (Integer) params.getValue(AVKey.TILE_WIDTH); - if (tileWidth == null) - { + if (tileWidth == null) { tileWidth = isDataSetLarge ? DEFAULT_TILE_WIDTH_AND_HEIGHT : DEFAULT_SINGLE_LEVEL_TILE_WIDTH_AND_HEIGHT; params.setValue(AVKey.TILE_WIDTH, tileWidth); } Integer tileHeight = (Integer) params.getValue(AVKey.TILE_HEIGHT); - if (tileHeight == null) - { + if (tileHeight == null) { tileHeight = isDataSetLarge ? DEFAULT_TILE_WIDTH_AND_HEIGHT : DEFAULT_SINGLE_LEVEL_TILE_WIDTH_AND_HEIGHT; params.setValue(AVKey.TILE_HEIGHT, tileHeight); } @@ -282,8 +262,7 @@ protected void initLevelSetParameters(AVList params) LatLon desiredLevelZeroDelta = this.computeDesiredTileDelta(sector); Integer numLevels = (Integer) params.getValue(AVKey.NUM_LEVELS); - if (numLevels == null) - { + if (numLevels == null) { // If the data set is large, then use compute a number of levels for the full pyramid. Otherwise use a // single level. numLevels = isDataSetLarge ? this.computeNumLevels(desiredLevelZeroDelta, rasterTileDelta) : 1; @@ -291,33 +270,29 @@ protected void initLevelSetParameters(AVList params) } Integer numEmptyLevels = (Integer) params.getValue(AVKey.NUM_EMPTY_LEVELS); - if (numEmptyLevels == null) - { + if (numEmptyLevels == null) { numEmptyLevels = 0; params.setValue(AVKey.NUM_EMPTY_LEVELS, numEmptyLevels); } LatLon levelZeroTileDelta = (LatLon) params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA); - if (levelZeroTileDelta == null) - { + if (levelZeroTileDelta == null) { double scale = Math.pow(2d, numLevels - 1); levelZeroTileDelta = LatLon.fromDegrees( - scale * rasterTileDelta.getLatitude().degrees, - scale * rasterTileDelta.getLongitude().degrees); + scale * rasterTileDelta.getLatitude().degrees, + scale * rasterTileDelta.getLongitude().degrees); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, levelZeroTileDelta); } LatLon tileOrigin = (LatLon) params.getValue(AVKey.TILE_ORIGIN); - if (tileOrigin == null) - { + if (tileOrigin == null) { tileOrigin = new LatLon(sector.getMinLatitude(), sector.getMinLongitude()); params.setValue(AVKey.TILE_ORIGIN, tileOrigin); } // If the default or caller-specified values define a level set that does not fit in the limits of latitude // and longitude, then we re-define the level set parameters using values known to fit in those limits. - if (!this.isWithinLatLonLimits(sector, levelZeroTileDelta, tileOrigin)) - { + if (!this.isWithinLatLonLimits(sector, levelZeroTileDelta, tileOrigin)) { levelZeroTileDelta = this.computeIntegralLevelZeroTileDelta(levelZeroTileDelta); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, levelZeroTileDelta); @@ -329,28 +304,24 @@ protected void initLevelSetParameters(AVList params) } } - protected LatLon computeIntegralLevelZeroTileDelta(LatLon originalDelta) - { + protected LatLon computeIntegralLevelZeroTileDelta(LatLon originalDelta) { // Find a level zero tile delta that's an integral factor of each dimension. double latDelta = Math.ceil(originalDelta.latitude.degrees); double lonDelta = Math.ceil(originalDelta.longitude.degrees); - while (180 % latDelta != 0) - { + while (180 % latDelta != 0) { --latDelta; } - while (360 % lonDelta != 0) - { + while (360 % lonDelta != 0) { --lonDelta; } return LatLon.fromDegrees(latDelta, lonDelta); } - protected boolean isDataSetLarge(Iterable rasters, int largeThreshold) - { + protected boolean isDataSetLarge(Iterable rasters, int largeThreshold) { Sector sector = this.computeBoundingSector(rasters); LatLon pixelSize = this.computeSmallestPixelSize(rasters); int sectorWidth = (int) Math.ceil(sector.getDeltaLonDegrees() / pixelSize.getLongitude().degrees); @@ -358,35 +329,31 @@ protected boolean isDataSetLarge(Iterable rasters, int lar return (sectorWidth >= largeThreshold) || (sectorHeight >= largeThreshold); } - protected boolean isWithinLatLonLimits(Sector sector, LatLon tileDelta, LatLon tileOrigin) - { + protected boolean isWithinLatLonLimits(Sector sector, LatLon tileDelta, LatLon tileOrigin) { double minLat = Math.floor((sector.getMinLatitude().degrees - tileOrigin.getLatitude().degrees) - / tileDelta.getLatitude().degrees); + / tileDelta.getLatitude().degrees); minLat = tileOrigin.getLatitude().degrees + minLat * tileDelta.getLatitude().degrees; double maxLat = Math.ceil((sector.getMaxLatitude().degrees - tileOrigin.getLatitude().degrees) - / tileDelta.getLatitude().degrees); + / tileDelta.getLatitude().degrees); maxLat = tileOrigin.getLatitude().degrees + maxLat * tileDelta.getLatitude().degrees; double minLon = Math.floor((sector.getMinLongitude().degrees - tileOrigin.getLongitude().degrees) - / tileDelta.getLongitude().degrees); + / tileDelta.getLongitude().degrees); minLon = tileOrigin.getLongitude().degrees + minLon * tileDelta.getLongitude().degrees; double maxLon = Math.ceil((sector.getMaxLongitude().degrees - tileOrigin.getLongitude().degrees) - / tileDelta.getLongitude().degrees); + / tileDelta.getLongitude().degrees); maxLon = tileOrigin.getLongitude().degrees + maxLon * tileDelta.getLongitude().degrees; return Sector.fromDegrees(minLat, maxLat, minLon, maxLon).isWithinLatLonLimits(); } - protected Sector computeBoundingSector(Iterable rasters) - { + protected Sector computeBoundingSector(Iterable rasters) { Sector sector = null; - for (DataRaster raster : rasters) - { + for (DataRaster raster : rasters) { sector = (sector != null) ? raster.getSector().union(sector) : raster.getSector(); } return sector; } - protected LatLon computeRasterTileDelta(int tileWidth, int tileHeight, Iterable rasters) - { + protected LatLon computeRasterTileDelta(int tileWidth, int tileHeight, Iterable rasters) { LatLon pixelSize = this.computeSmallestPixelSize(rasters); // Compute the tile size in latitude and longitude, given a raster's sector and dimension, and the tile // dimensions. In this computation a pixel is assumed to cover a finite area. @@ -395,52 +362,50 @@ protected LatLon computeRasterTileDelta(int tileWidth, int tileHeight, Iterable< return LatLon.fromDegrees(latDelta, lonDelta); } - protected LatLon computeDesiredTileDelta(Sector sector) - { + protected LatLon computeDesiredTileDelta(Sector sector) { double levelZeroLat = Math.min(sector.getDeltaLatDegrees(), DEFAULT_LEVEL_ZERO_TILE_DELTA); double levelZeroLon = Math.min(sector.getDeltaLonDegrees(), DEFAULT_LEVEL_ZERO_TILE_DELTA); return LatLon.fromDegrees(levelZeroLat, levelZeroLon); } - protected LatLon computeRasterPixelSize(DataRaster raster) - { + protected LatLon computeRasterPixelSize(DataRaster raster) { // Compute the raster's pixel dimension in latitude and longitude. In this computation a pixel is assumed to // cover a finite area. return LatLon.fromDegrees( - raster.getSector().getDeltaLatDegrees() / raster.getHeight(), - raster.getSector().getDeltaLonDegrees() / raster.getWidth()); + raster.getSector().getDeltaLatDegrees() / raster.getHeight(), + raster.getSector().getDeltaLonDegrees() / raster.getWidth()); } - protected LatLon computeSmallestPixelSize(Iterable rasters) - { + protected LatLon computeSmallestPixelSize(Iterable rasters) { // Find the smallest pixel dimensions in the given rasters. double smallestLat = Double.MAX_VALUE; double smallestLon = Double.MAX_VALUE; - for (DataRaster raster : rasters) - { + for (DataRaster raster : rasters) { LatLon curSize = this.computeRasterPixelSize(raster); - if (smallestLat > curSize.getLatitude().degrees) + if (smallestLat > curSize.getLatitude().degrees) { smallestLat = curSize.getLatitude().degrees; - if (smallestLon > curSize.getLongitude().degrees) + } + if (smallestLon > curSize.getLongitude().degrees) { smallestLon = curSize.getLongitude().degrees; + } } return LatLon.fromDegrees(smallestLat, smallestLon); } - protected int computeNumLevels(LatLon levelZeroDelta, LatLon lastLevelDelta) - { + protected int computeNumLevels(LatLon levelZeroDelta, LatLon lastLevelDelta) { // Compute the number of levels needed to achieve the given last level tile delta, starting from the given // level zero tile delta. double numLatLevels = 1 + WWMath.logBase2(levelZeroDelta.getLatitude().getDegrees()) - - WWMath.logBase2(lastLevelDelta.getLatitude().getDegrees()); + - WWMath.logBase2(lastLevelDelta.getLatitude().getDegrees()); double numLonLevels = 1 + WWMath.logBase2(levelZeroDelta.getLongitude().getDegrees()) - - WWMath.logBase2(lastLevelDelta.getLongitude().getDegrees()); + - WWMath.logBase2(lastLevelDelta.getLongitude().getDegrees()); // Compute the maximum number of levels needed, but limit the number of levels to positive integers greater // than or equal to one. int numLevels = (int) Math.ceil(Math.max(numLatLevels, numLonLevels)); - if (numLevels < 1) + if (numLevels < 1) { numLevels = 1; + } return numLevels; } @@ -448,18 +413,17 @@ protected int computeNumLevels(LatLon levelZeroDelta, LatLon lastLevelDelta) //**************************************************************// //******************** DataRaster Assembly *******************// //**************************************************************// - - protected void assembleDataRasters() throws Exception - { + protected void assembleDataRasters() throws Exception { // Exit if the caller has instructed us to stop production. - if (this.isStopped()) + if (this.isStopped()) { return; + } - for (SourceInfo info : this.getDataSourceList()) - { + for (SourceInfo info : this.getDataSourceList()) { // Exit if the caller has instructed us to stop production. - if (this.isStopped()) + if (this.isStopped()) { break; + } Thread.sleep(0); @@ -469,35 +433,29 @@ protected void assembleDataRasters() throws Exception } } - protected void assembleDataSource(Object source, AVList params) throws Exception - { - if (source instanceof DataRaster) - { + protected void assembleDataSource(Object source, AVList params) throws Exception { + if (source instanceof DataRaster) { this.dataRasterList.add((DataRaster) source); - } - else - { + } else { DataRasterReader reader = this.readerFactory.findReaderFor(source, params, this.getDataRasterReaders()); this.dataRasterList.add(new CachedDataRaster(source, params, reader, this.getCache())); } } - protected static MemoryCache createDefaultCache() - { + protected static MemoryCache createDefaultCache() { long cacheSize = Configuration.getLongValue(AVKey.TILED_RASTER_PRODUCER_CACHE_SIZE, - DEFAULT_TILED_RASTER_PRODUCER_CACHE_SIZE); + DEFAULT_TILED_RASTER_PRODUCER_CACHE_SIZE); return new BasicMemoryCache((long) (0.8 * cacheSize), cacheSize); } //**************************************************************// //******************** LevelSet Installation *****************// //**************************************************************// - - protected void installLevelSet(LevelSet levelSet, AVList params) throws java.io.IOException - { + protected void installLevelSet(LevelSet levelSet, AVList params) throws java.io.IOException { // Exit if the caller has instructed us to stop production. - if (this.isStopped()) + if (this.isStopped()) { return; + } // Setup the progress parameters. this.calculateTileCount(levelSet, params); @@ -518,24 +476,24 @@ protected void installLevelSet(LevelSet levelSet, AVList params) throws java.io. buildLoop: { Angle p1 = Tile.computeRowLatitude(firstRow, dLat, latOrigin); - for (int row = firstRow; row <= lastRow; row++) - { + for (int row = firstRow; row <= lastRow; row++) { Angle p2 = p1.add(dLat); Angle t1 = Tile.computeColumnLongitude(firstCol, dLon, lonOrigin); - for (int col = firstCol; col <= lastCol; col++) - { + for (int col = firstCol; col <= lastCol; col++) { // Exit if the caller has instructed us to stop production. Thread.yield(); - if (this.isStopped()) + if (this.isStopped()) { break buildLoop; + } Angle t2 = t1.add(dLon); Tile tile = new Tile(new Sector(p1, p2, t1, t2), level, row, col); DataRaster tileRaster = this.createTileRaster(levelSet, tile, params); // Write the top-level tile raster to disk. - if (tileRaster != null) + if (tileRaster != null) { this.installTileRasterLater(levelSet, tile, tileRaster, params); + } t1 = t2; } @@ -544,22 +502,19 @@ protected void installLevelSet(LevelSet levelSet, AVList params) throws java.io. } } - protected DataRaster createTileRaster(LevelSet levelSet, Tile tile, AVList params) throws java.io.IOException - { + protected DataRaster createTileRaster(LevelSet levelSet, Tile tile, AVList params) throws java.io.IOException { // Exit if the caller has instructed us to stop production. - if (this.isStopped()) + if (this.isStopped()) { return null; + } DataRaster tileRaster; // If we have reached the final level, then create a tile raster from the original data sources. - if (this.isFinalLevel(levelSet, tile.getLevelNumber(), params)) - { + if (this.isFinalLevel(levelSet, tile.getLevelNumber(), params)) { tileRaster = this.drawDataSources(levelSet, tile, this.dataRasterList, params); - } - // Otherwise, recursively create a tile raster from the next level's tile rasters. - else - { + } // Otherwise, recursively create a tile raster from the next level's tile rasters. + else { tileRaster = this.drawDescendants(levelSet, tile, params); } @@ -569,28 +524,25 @@ protected DataRaster createTileRaster(LevelSet levelSet, Tile tile, AVList param } protected DataRaster drawDataSources(LevelSet levelSet, Tile tile, Iterable dataRasters, AVList params) - throws java.io.IOException - { + throws java.io.IOException { DataRaster tileRaster = null; // Find the data sources that intersect this tile and intersect the LevelSet sector. java.util.ArrayList intersectingRasters = new java.util.ArrayList(); - for (DataRaster raster : dataRasters) - { - if (raster.getSector().intersects(tile.getSector()) && raster.getSector().intersects(levelSet.getSector())) + for (DataRaster raster : dataRasters) { + if (raster.getSector().intersects(tile.getSector()) && raster.getSector().intersects(levelSet.getSector())) { intersectingRasters.add(raster); + } } // If any data sources intersect this tile, and the tile's level is not empty, then we attempt to read those // sources and render them into this tile. - if (!intersectingRasters.isEmpty() && !tile.getLevel().isEmpty()) - { + if (!intersectingRasters.isEmpty() && !tile.getLevel().isEmpty()) { // Create the tile raster to render into. tileRaster = this.createDataRaster(tile.getLevel().getTileWidth(), tile.getLevel().getTileHeight(), - tile.getSector(), params); + tile.getSector(), params); // Render each data source raster into the tile raster. - for (DataRaster raster : intersectingRasters) - { + for (DataRaster raster : intersectingRasters) { raster.drawOnTo(tileRaster); } } @@ -603,24 +555,20 @@ protected DataRaster drawDataSources(LevelSet levelSet, Tile tile, IterablemaxNumOfLevels - the actual maximum numbers of levels. + * Extracts a maximum level limit from the AVList if the AVList contains + * AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL. This method requires maxNumOfLevels - the actual + * maximum numbers of levels. *

    * The AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL could specify multiple things: *

    @@ -705,8 +650,7 @@ protected boolean isFinalLevel(LevelSet levelSet, int levelNumber, AVList params * levels will be 70% of the actual maximum numbers of levels maxNumOfLevels. *

    * If the type of the value of the AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL is Integer, it should contain an - * integer number between 0 (for level 0 only) and the actual maximum numbers of levels - * maxNumOfLevels. + * integer number between 0 (for level 0 only) and the actual maximum numbers of levels maxNumOfLevels. *

    * It is also possible to specify the limit as percents, in this case the type of the * AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL value must be "String", have a numeric value as text and the "%" @@ -716,50 +660,34 @@ protected boolean isFinalLevel(LevelSet levelSet, int levelNumber, AVList params * The value will be correctly extracted and compared with the maxNumOfLevels. Valid values must be * smaller or equal to maxNumOfLevels. * - * @param params AVList that may contain AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL property + * @param params AVList that may contain AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL property * @param maxNumOfLevels The actual maximum numbers of levels * * @return A limit of numbers of levels that should producer generate. */ - protected int extractMaxLevelLimit(AVList params, int maxNumOfLevels) - { - if (null != params && params.hasKey(AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL)) - { + protected int extractMaxLevelLimit(AVList params, int maxNumOfLevels) { + if (null != params && params.hasKey(AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL)) { Object o = params.getValue(AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL); - if (o instanceof Integer) - { + if (o instanceof Integer) { int limit = (Integer) o; return (limit <= maxNumOfLevels) ? limit : maxNumOfLevels; - } - else if (o instanceof String) - { + } else if (o instanceof String) { String strLimit = (String) o; - if ("Auto".equalsIgnoreCase(strLimit)) - { + if ("Auto".equalsIgnoreCase(strLimit)) { return (int) Math.floor(0.5d * (double) maxNumOfLevels); // 0.5 = half, 0.6 = 60% - } - else if (strLimit.endsWith("%")) - { - try - { + } else if (strLimit.endsWith("%")) { + try { float percent = Float.parseFloat(strLimit.substring(0, strLimit.length() - 1)); int limit = (int) Math.floor(percent * (double) maxNumOfLevels / 100d); return (limit <= maxNumOfLevels) ? limit : maxNumOfLevels; - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().finest(WWUtil.extractExceptionReason(t)); } - } - else - { - try - { + } else { + try { int limit = Integer.parseInt(strLimit); return (limit <= maxNumOfLevels) ? limit : maxNumOfLevels; - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().finest(WWUtil.extractExceptionReason(t)); } } @@ -772,22 +700,18 @@ else if (strLimit.endsWith("%")) //**************************************************************// //******************** Tile Installation *********************// //**************************************************************// - - protected java.util.concurrent.ExecutorService createDefaultTileWriteService(int threadPoolSize) - { + protected java.util.concurrent.ExecutorService createDefaultTileWriteService(int threadPoolSize) { // TODO: comment // Create a fixed thread pool, but provide a callback to release a tile write permit when a task completes. return new java.util.concurrent.ThreadPoolExecutor( - // Fixed size thread pool. - threadPoolSize, threadPoolSize, - // This value is irrelevant, as threads only terminated when the executor is shutdown. - 0L, java.util.concurrent.TimeUnit.MILLISECONDS, - // Provide an unbounded work queue. - new java.util.concurrent.LinkedBlockingQueue()) - { - protected void afterExecute(Runnable runnable, Throwable t) - { + // Fixed size thread pool. + threadPoolSize, threadPoolSize, + // This value is irrelevant, as threads only terminated when the executor is shutdown. + 0L, java.util.concurrent.TimeUnit.MILLISECONDS, + // Provide an unbounded work queue. + new java.util.concurrent.LinkedBlockingQueue()) { + protected void afterExecute(Runnable runnable, Throwable t) { // Invoke the superclass routine, then release a tile write permit. super.afterExecute(runnable, t); TiledRasterProducer.this.installTileRasterComplete(); @@ -796,25 +720,20 @@ protected void afterExecute(Runnable runnable, Throwable t) } protected void installTileRasterLater(final LevelSet levelSet, final Tile tile, final DataRaster tileRaster, - final AVList params) - { + final AVList params) { // TODO: comment // Try to acquire a permit from the tile write semaphore. this.getTileWriteSemaphore().acquireUninterruptibly(); // We've acquired the permit, now execute the installTileRaster() routine in a different thread. - this.getTileWriteService().execute(new Runnable() - { - public void run() - { - try - { + this.getTileWriteService().execute(new Runnable() { + public void run() { + try { installTileRaster(tile, tileRaster, params); // Dispose the data raster. - if (tileRaster instanceof Disposable) + if (tileRaster instanceof Disposable) { ((Disposable) tileRaster).dispose(); - } - catch (Throwable t) - { + } + } catch (Throwable t) { String message = Logging.getMessage("generic.ExceptionWhileWriting", tile); Logging.logger().log(java.util.logging.Level.SEVERE, message, t); } @@ -822,59 +741,46 @@ public void run() }); } - protected void installTileRasterComplete() - { + protected void installTileRasterComplete() { // TODO: comment this.getTileWriteSemaphore().release(); } - protected void waitForInstallTileTasks() - { + protected void waitForInstallTileTasks() { // TODO: comment - try - { + try { java.util.concurrent.ExecutorService service = this.getTileWriteService(); service.shutdown(); // Block this thread until the executor has completed. - while (!service.awaitTermination(1000L, java.util.concurrent.TimeUnit.MILLISECONDS)) - { + while (!service.awaitTermination(1000L, java.util.concurrent.TimeUnit.MILLISECONDS)) { Thread.sleep(5L); } - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { String msg = Logging.getMessage("generic.interrupted", this.getClass().getName(), - "waitForInstallTileTasks()"); + "waitForInstallTileTasks()"); Logging.logger().finest(msg); // Don't swallow interrupts; instead, restore the interrupted status Thread.currentThread().interrupt(); } } - protected void installTileRaster(Tile tile, DataRaster tileRaster, AVList params) throws java.io.IOException - { + protected void installTileRaster(Tile tile, DataRaster tileRaster, AVList params) throws java.io.IOException { java.io.File installLocation; // Compute the install location of the tile. Object result = this.installLocationForTile(params, tile); - if (result instanceof java.io.File) - { + if (result instanceof java.io.File) { installLocation = (java.io.File) result; - } - else - { + } else { String message = result.toString(); Logging.logger().severe(message); throw new java.io.IOException(message); } - synchronized (this.fileLock) - { + synchronized (this.fileLock) { java.io.File dir = installLocation.getParentFile(); - if (!dir.exists()) - { - if (!dir.mkdirs()) - { + if (!dir.exists()) { + if (!dir.mkdirs()) { String message = Logging.getMessage("generic.CannotCreateFile", dir); Logging.logger().warning(message); } @@ -886,45 +792,42 @@ protected void installTileRaster(Tile tile, DataRaster tileRaster, AVList params DataRasterWriter[] writers = this.getDataRasterWriters(); Object writer = this.findWriterFor(tileRaster, formatSuffix, installLocation, writers); - if (writer instanceof DataRasterWriter) - { - try - { + if (writer instanceof DataRasterWriter) { + try { ((DataRasterWriter) writer).write(tileRaster, formatSuffix, installLocation); - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { String message = Logging.getMessage("generic.ExceptionWhileWriting", installLocation); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } } - protected Object installLocationForTile(AVList installParams, Tile tile) - { + protected Object installLocationForTile(AVList installParams, Tile tile) { String path = null; String s = installParams.getStringValue(AVKey.FILE_STORE_LOCATION); - if (s != null) + if (s != null) { path = WWIO.appendPathPart(path, s); + } s = tile.getPath(); - if (s != null) + if (s != null) { path = WWIO.appendPathPart(path, s); + } - if (path == null || path.length() < 1) + if (path == null || path.length() < 1) { return Logging.getMessage("TiledRasterProducer.InvalidTile", tile); + } return new java.io.File(path); } protected Object findWriterFor(DataRaster raster, String formatSuffix, java.io.File destination, - DataRasterWriter[] writers) - { - for (DataRasterWriter writer : writers) - { - if (writer.canWrite(raster, formatSuffix, destination)) + DataRasterWriter[] writers) { + for (DataRasterWriter writer : writers) { + if (writer.canWrite(raster, formatSuffix, destination)) { return writer; + } } // No writer maching this DataRaster/formatSuffix. @@ -934,7 +837,6 @@ protected Object findWriterFor(DataRaster raster, String formatSuffix, java.io.F //**************************************************************// //******************** Config File Installation **************// //**************************************************************// - /** * Returns a configuration document which describes the tiled data produced by this TiledRasterProducer. The * document's contents are derived from the specified parameter list, and depend on the concrete subclass' @@ -953,36 +855,34 @@ protected Object findWriterFor(DataRaster raster, String formatSuffix, java.io.F * location, configuration filename, and configuration file contents are derived from the specified parameter list. * This throws an exception if the configuration file cannot be installed for any reason. *

    - * The parameter list must contain at least the following keys: + * The parameter list must contain at least the following keys:
    * *
    Required Keys
    Key
    {@link gov.nasa.worldwind.avlist.AVKey#FILE_STORE_LOCATION}
    {@link * gov.nasa.worldwind.avlist.AVKey#DATA_CACHE_NAME}
    {@link * gov.nasa.worldwind.avlist.AVKey#DATASET_NAME}
    * * @param params the parameters which describe the install location, the configuration filename, and the - * configuration file contents. + * configuration file contents. * - * @throws Exception if the configuration file cannot be installed for any reason. + * @throws Exception if the configuration file cannot be installed for any reason. * @throws IllegalArgumentException if the parameter list is null. */ - protected void installConfigFile(AVList params) throws Exception - { - if (params == null) - { + protected void installConfigFile(AVList params) throws Exception { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Exit if the caller has instructed us to stop production. - if (this.isStopped()) + if (this.isStopped()) { return; + } File configFile = this.getConfigFileInstallLocation(params); - if (configFile == null) - { + if (configFile == null) { String message = Logging.getMessage("TiledRasterProducer.NoConfigFileInstallLocation", - params.getValue(AVKey.DATASET_NAME)); + params.getValue(AVKey.DATASET_NAME)); Logging.logger().severe(message); throw new WWRuntimeException(message); } @@ -990,13 +890,10 @@ protected void installConfigFile(AVList params) throws Exception // Synchronize construction of the config file's parent directories. One or more tile installation tasks may be // running when this code executes. This synchronizes construction of common parent directories between with the // tile installation tasks. - synchronized (this.fileLock) - { + synchronized (this.fileLock) { java.io.File dir = configFile.getParentFile(); - if (!dir.exists()) - { - if (!dir.mkdirs()) - { + if (!dir.exists()) { + if (!dir.mkdirs()) { String message = Logging.getMessage("generic.CannotCreateFile", dir); Logging.logger().warning(message); } @@ -1004,20 +901,16 @@ protected void installConfigFile(AVList params) throws Exception } Document configDoc = this.createConfigDoc(params); - if (configDoc == null) - { + if (configDoc == null) { String message = Logging.getMessage("TiledRasterProducer.CannotCreateConfigDoc", - params.getValue(AVKey.DATASET_NAME)); + params.getValue(AVKey.DATASET_NAME)); Logging.logger().severe(message); throw new WWRuntimeException(message); } - try - { + try { WWXML.saveDocumentToFile(configDoc, configFile.getAbsolutePath()); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("TiledRasterProducer.CannotWriteConfigFile", configFile); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -1029,7 +922,7 @@ protected void installConfigFile(AVList params) throws Exception /** * Returns the location of the configuration file which describes the tiled data produced by this * TiledRasterProducer. The install location is derived from the specified parameter list. This returns null if the - * parameter list is null, or if it does not contain any of the following keys: + * parameter list is null, or if it does not contain any of the following keys:
    * *
    Required Keys
    Key
    {@link gov.nasa.worldwind.avlist.AVKey#FILE_STORE_LOCATION}
    {@link * gov.nasa.worldwind.avlist.AVKey#DATA_CACHE_NAME}
    {@link @@ -1040,30 +933,33 @@ protected void installConfigFile(AVList params) throws Exception * @return the configuration file install location, or null if the parameter list is null or does not contain the * required parameters. */ - protected File getConfigFileInstallLocation(AVList params) - { - if (params == null) + protected File getConfigFileInstallLocation(AVList params) { + if (params == null) { return null; + } String fileStoreLocation = params.getStringValue(AVKey.FILE_STORE_LOCATION); - if (fileStoreLocation != null) + if (fileStoreLocation != null) { fileStoreLocation = WWIO.stripTrailingSeparator(fileStoreLocation); + } - if (WWUtil.isEmpty(fileStoreLocation)) + if (WWUtil.isEmpty(fileStoreLocation)) { return null; + } String cacheName = DataConfigurationUtils.getDataConfigFilename(params, ".xml"); - if (cacheName != null) + if (cacheName != null) { cacheName = WWIO.stripLeadingSeparator(cacheName); + } - if (WWUtil.isEmpty(cacheName)) + if (WWUtil.isEmpty(cacheName)) { return null; + } return new File(fileStoreLocation + File.separator + cacheName); } - protected void installRasterServerConfigFile(AVList productionParams) - { + protected void installRasterServerConfigFile(AVList productionParams) { File configFile = this.getConfigFileInstallLocation(productionParams); String configFilePath = configFile.getAbsolutePath().replace(".xml", ".RasterServer.xml"); @@ -1072,44 +968,32 @@ protected void installRasterServerConfigFile(AVList productionParams) WWXML.setTextAttribute(root, "version", "1.0"); Sector extent = null; - if (productionParams.hasKey(AVKey.SECTOR)) - { + if (productionParams.hasKey(AVKey.SECTOR)) { Object o = productionParams.getValue(AVKey.SECTOR); - if (null != o && o instanceof Sector) - { + if (null != o && o instanceof Sector) { extent = (Sector) o; } } - if (null != extent) - { + if (null != extent) { WWXML.appendSector(root, "Sector", extent); - } - else - { + } else { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().severe(message); throw new WWRuntimeException(message); } Element sources = configDoc.createElementNS(null, "Sources"); - for (DataRaster raster : this.getDataRasters()) - { - if (raster instanceof CachedDataRaster) - { - try - { + for (DataRaster raster : this.getDataRasters()) { + if (raster instanceof CachedDataRaster) { + try { this.appendSource(sources, (CachedDataRaster) raster); - } - catch (Throwable t) - { + } catch (Throwable t) { String reason = WWUtil.extractExceptionReason(t); Logging.logger().warning(reason); } - } - else - { + } else { String message = Logging.getMessage("TiledRasterProducer.UnrecognizedRasterType", - raster.getClass().getName(), raster.getStringValue(AVKey.DATASET_NAME)); + raster.getClass().getName(), raster.getStringValue(AVKey.DATASET_NAME)); Logging.logger().severe(message); throw new WWRuntimeException(message); } @@ -1128,24 +1012,20 @@ protected void installRasterServerConfigFile(AVList productionParams) WWXML.saveDocumentToFile(configDoc, configFilePath); } - protected void appendProperties(Element context, AVList properties) - { - if (null == context || properties == null) - { + protected void appendProperties(Element context, AVList properties) { + if (null == context || properties == null) { return; } StringBuilder sb = new StringBuilder(); // add properties - for (Map.Entry entry : properties.getEntries()) - { + for (Map.Entry entry : properties.getEntries()) { sb.setLength(0); String key = entry.getKey(); sb.append(properties.getValue(key)); String value = sb.toString(); - if (WWUtil.isEmpty(key) || WWUtil.isEmpty(value)) - { + if (WWUtil.isEmpty(key) || WWUtil.isEmpty(value)) { continue; } @@ -1155,19 +1035,16 @@ protected void appendProperties(Element context, AVList properties) } } - protected void appendSource(Element sources, CachedDataRaster raster) throws WWRuntimeException - { + protected void appendSource(Element sources, CachedDataRaster raster) throws WWRuntimeException { Object o = raster.getDataSource(); - if (WWUtil.isEmpty(o)) - { + if (WWUtil.isEmpty(o)) { String message = Logging.getMessage("nullValue.DataSourceIsNull"); Logging.logger().fine(message); throw new WWRuntimeException(message); } File f = WWIO.getFileForLocalAddress(o); - if (WWUtil.isEmpty(f)) - { + if (WWUtil.isEmpty(f)) { String message = Logging.getMessage("TiledRasterProducer.UnrecognizedDataSource", o); Logging.logger().fine(message); throw new WWRuntimeException(message); @@ -1178,25 +1055,21 @@ protected void appendSource(Element sources, CachedDataRaster raster) throws WWR WWXML.setTextAttribute(source, "path", f.getAbsolutePath()); AVList params = raster.getParams(); - if (null == params) - { + if (null == params) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().fine(message); throw new WWRuntimeException(message); } Sector sector = raster.getSector(); - if (null == sector && params.hasKey(AVKey.SECTOR)) - { + if (null == sector && params.hasKey(AVKey.SECTOR)) { o = params.getValue(AVKey.SECTOR); - if (o instanceof Sector) - { + if (o instanceof Sector) { sector = (Sector) o; } } - if (null != sector) - { + if (null != sector) { WWXML.appendSector(source, "Sector", sector); } } @@ -1204,14 +1077,11 @@ protected void appendSource(Element sources, CachedDataRaster raster) throws WWR //**************************************************************// //******************** Progress ******************************// //**************************************************************// - - protected void calculateTileCount(LevelSet levelSet, AVList params) - { + protected void calculateTileCount(LevelSet levelSet, AVList params) { Sector sector = levelSet.getSector(); this.tileCount = 0; - for (Level level : levelSet.getLevels()) - { + for (Level level : levelSet.getLevels()) { Angle dLat = level.getTileDelta().getLatitude(); Angle dLon = level.getTileDelta().getLongitude(); Angle latOrigin = levelSet.getTileOrigin().getLatitude(); @@ -1222,19 +1092,18 @@ protected void calculateTileCount(LevelSet levelSet, AVList params) int lastCol = Tile.computeColumn(dLon, sector.getMaxLongitude(), lonOrigin); this.tileCount += (lastRow - firstRow + 1) * (lastCol - firstCol + 1); - if (this.isFinalLevel(levelSet, level.getLevelNumber(), params)) + if (this.isFinalLevel(levelSet, level.getLevelNumber(), params)) { break; + } } } - protected void startProgress() - { + protected void startProgress() { this.tile = 0; this.firePropertyChange(AVKey.PROGRESS, null, 0d); } - protected void updateProgress() - { + protected void updateProgress() { double oldProgress = this.tile / (double) this.tileCount; double newProgress = ++this.tile / (double) this.tileCount; this.firePropertyChange(AVKey.PROGRESS, oldProgress, newProgress); diff --git a/src/gov/nasa/worldwind/data/WWDotNetLayerSetConverter.java b/src/gov/nasa/worldwind/data/WWDotNetLayerSetConverter.java index b15793aa7b..d3823ac99f 100644 --- a/src/gov/nasa/worldwind/data/WWDotNetLayerSetConverter.java +++ b/src/gov/nasa/worldwind/data/WWDotNetLayerSetConverter.java @@ -20,13 +20,13 @@ * @author dcollins * @version $Id: WWDotNetLayerSetConverter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWDotNetLayerSetConverter extends AbstractDataStoreProducer -{ +public class WWDotNetLayerSetConverter extends AbstractDataStoreProducer { + protected static final String DEFAULT_IMAGE_FORMAT = "image/png"; protected static final String DEFAULT_TEXTURE_FORMAT = "image/dds"; - protected static class ProductionState - { + protected static class ProductionState { + // Production parameters. AVList productionParams; // Progress counters. @@ -36,28 +36,23 @@ protected static class ProductionState int[] numInstalledFiles; } - public WWDotNetLayerSetConverter() - { + public WWDotNetLayerSetConverter() { } - public String getDataSourceDescription() - { + public String getDataSourceDescription() { return Logging.getMessage("WWDotNetLayerSetConverter.Description"); } - public void removeProductionState() - { + public void removeProductionState() { Iterable dataSources = this.getDataSourceList(); AVList params = this.getStoreParameters(); - for (SourceInfo info : dataSources) - { + for (SourceInfo info : dataSources) { this.removeLayerSet(info.source, params); } } - protected void doStartProduction(AVList parameters) throws Exception - { + protected void doStartProduction(AVList parameters) throws Exception { this.getProductionResultsList().clear(); Iterable dataSources = this.getDataSourceList(); ProductionState productionState = new ProductionState(); @@ -67,103 +62,99 @@ protected void doStartProduction(AVList parameters) throws Exception // Set the progress parameters for the current data sources. this.setProgressParameters(dataSources, productionState); - if (this.isStopped()) + if (this.isStopped()) { return; + } - for (SourceInfo info : dataSources) - { - if (this.isStopped()) + for (SourceInfo info : dataSources) { + if (this.isStopped()) { return; + } productionState.curSource++; this.convertLayerSet(info.source, productionState); } } - protected void initProductionParameters(AVList params, ProductionState productionState) - { + protected void initProductionParameters(AVList params, ProductionState productionState) { // Preserve backward compatibility with previous verisons of WWDotNetLayerSetConverter. If the caller specified // a format suffix parameter, use it to compute the image format properties. This gives priority to the format // suffix property to ensure applications which use format suffix continue to work. - if (params.getValue(AVKey.FORMAT_SUFFIX) != null) - { + if (params.getValue(AVKey.FORMAT_SUFFIX) != null) { String s = WWIO.makeMimeTypeForSuffix(params.getValue(AVKey.FORMAT_SUFFIX).toString()); - if (s != null) - { + if (s != null) { params.setValue(AVKey.IMAGE_FORMAT, s); - params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, new String[] {s}); + params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, new String[]{s}); } } // Use the default image format if none exists. - if (params.getValue(AVKey.IMAGE_FORMAT) == null) + if (params.getValue(AVKey.IMAGE_FORMAT) == null) { params.setValue(AVKey.IMAGE_FORMAT, DEFAULT_IMAGE_FORMAT); + } // Compute the available image formats if none exists. - if (params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) == null) - { + if (params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) == null) { params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, - new String[] {params.getValue(AVKey.IMAGE_FORMAT).toString()}); + new String[]{params.getValue(AVKey.IMAGE_FORMAT).toString()}); } // Compute the format suffix if none exists. - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) - { + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { params.setValue(AVKey.FORMAT_SUFFIX, - WWIO.makeSuffixForMimeType(params.getValue(AVKey.IMAGE_FORMAT).toString())); + WWIO.makeSuffixForMimeType(params.getValue(AVKey.IMAGE_FORMAT).toString())); } productionState.productionParams = params; } - protected String validateProductionParameters(AVList parameters) - { + protected String validateProductionParameters(AVList parameters) { StringBuilder sb = new StringBuilder(); Object o = parameters.getValue(AVKey.FILE_STORE_LOCATION); - if (o == null || !(o instanceof String) || ((String) o).length() < 1) + if (o == null || !(o instanceof String) || ((String) o).length() < 1) { sb.append((sb.length() > 0 ? ", " : "")).append(Logging.getMessage("term.fileStoreLocation")); + } o = parameters.getValue(AVKey.DATA_CACHE_NAME); // It's okay if the cache path is empty, but if specified it must be a String. - if (o != null && !(o instanceof String)) + if (o != null && !(o instanceof String)) { sb.append((sb.length() > 0 ? ", " : "")).append(Logging.getMessage("term.fileStoreFolder")); + } - if (sb.length() == 0) + if (sb.length() == 0) { return null; + } return Logging.getMessage("DataStoreProducer.InvalidDataStoreParamters", sb.toString()); } - protected String validateDataSource(Object source, AVList params) - { + protected String validateDataSource(Object source, AVList params) { File file = this.getSourceConfigFile(source); - if (file == null) + if (file == null) { return Logging.getMessage("WWDotNetLayerSetConverter.NoSourceLocation"); + } // Open the document in question as an XML event stream. Since we're only interested in testing the document // element, we avoiding any unecessary overhead incurred from parsing the entire document as a DOM. XMLEventReader eventReader = null; - try - { + try { eventReader = WWXML.openEventReader(file); - if (eventReader == null) + if (eventReader == null) { return Logging.getMessage("WWDotNetLayerSetConverter.CannotReadLayerSetConfigFile", file); + } // Get the first start element event, if any exists, then determine if it represents a LayerSet // configuration document. XMLEvent event = WWXML.nextStartElementEvent(eventReader); - if (event == null || !DataConfigurationUtils.isWWDotNetLayerSetConfigEvent(event)) + if (event == null || !DataConfigurationUtils.isWWDotNetLayerSetConfigEvent(event)) { return Logging.getMessage("WWDotNetLayerSetConverter.FileNotLayerSet", file); - } - catch (Exception e) - { + } + } catch (Exception e) { Logging.logger().fine(Logging.getMessage("generic.ExceptionAttemptingToParseXml", file)); return Logging.getMessage("WWDotNetLayerSetConverter.CannotReadLayerSetConfigFile", file); - } - finally - { + } finally { WWXML.closeEventReader(eventReader, file.getPath()); } @@ -171,28 +162,22 @@ protected String validateDataSource(Object source, AVList params) return null; } - protected Document readLayerSetDocument(Object source) - { + protected Document readLayerSetDocument(Object source) { Document doc = null; - try - { + try { doc = WWXML.openDocument(source); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", source); Logging.logger().fine(message); } - if (doc == null) - { + if (doc == null) { String message = Logging.getMessage("WWDotNetLayerSetConverter.CannotReadLayerSetConfigFile", source); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (!DataConfigurationUtils.isWWDotNetLayerSetConfigDocument(doc.getDocumentElement())) - { + if (!DataConfigurationUtils.isWWDotNetLayerSetConfigDocument(doc.getDocumentElement())) { String message = Logging.getMessage("WWDotNetLayerSetConverter.FileNotLayerSet", source); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -204,63 +189,54 @@ protected Document readLayerSetDocument(Object source) //**************************************************************// //******************** LayerSet Installation *****************// //**************************************************************// - - protected void convertLayerSet(Object source, ProductionState productionState) throws Exception - { + protected void convertLayerSet(Object source, ProductionState productionState) throws Exception { File sourceConfigFile = this.getSourceConfigFile(source); - if (sourceConfigFile == null) - { + if (sourceConfigFile == null) { String message = Logging.getMessage("WWDotNetLayerSetConverter.NoSourceLocation"); Logging.logger().severe(message); throw new WWRuntimeException(message); } File sourceDataFile = sourceConfigFile.getParentFile(); - if (sourceDataFile == null) - { + if (sourceDataFile == null) { String message = Logging.getMessage("WWDotNetLayerSetConverter.FileWithoutParent", sourceConfigFile); Logging.logger().severe(message); throw new WWRuntimeException(message); } File destConfigFile = this.getDestConfigFile(productionState.productionParams); - if (destConfigFile == null) - { + if (destConfigFile == null) { String message = Logging.getMessage("WWDotNetLayerSetConverter.NoInstallLocation", sourceConfigFile); Logging.logger().severe(message); throw new WWRuntimeException(message); } File destDataFile = destConfigFile.getParentFile(); - if (destDataFile == null) - { + if (destDataFile == null) { String message = Logging.getMessage("WWDotNetLayerSetConverter.FileWithoutParent", destConfigFile); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (WWIO.isAncestorOf(sourceDataFile, destDataFile) || WWIO.isAncestorOf(destDataFile, sourceDataFile)) - { + if (WWIO.isAncestorOf(sourceDataFile, destDataFile) || WWIO.isAncestorOf(destDataFile, sourceDataFile)) { String message = Logging.getMessage("WWDotNetLayerSetConverter.CannotInstallToSelf", sourceDataFile, - destDataFile); + destDataFile); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (this.isStopped()) + if (this.isStopped()) { return; + } Document sourceConfigDoc = this.readLayerSetDocument(sourceConfigFile); - try - { + try { String imageFormat = productionState.productionParams.getStringValue(AVKey.IMAGE_FORMAT); productionState.numSourceFiles[productionState.curSource] = this.countWWDotNetFiles(sourceDataFile); this.copyWWDotNetDiretory(sourceDataFile, destDataFile, imageFormat, productionState); - } - catch (Exception e) - { + } catch (Exception e) { // Back out all file system changes made so far. WWIO.deleteDirectory(destDataFile); @@ -269,17 +245,15 @@ protected void convertLayerSet(Object source, ProductionState productionState) t throw new WWRuntimeException(message); } - if (this.isStopped()) + if (this.isStopped()) { return; + } Document destConfigDoc; - try - { + try { destConfigDoc = this.createDestConfigDoc(sourceConfigDoc, productionState.productionParams); WWXML.saveDocumentToFile(destConfigDoc, destConfigFile.getAbsolutePath()); - } - catch (Exception e) - { + } catch (Exception e) { // Back out all file system changes made so far. WWIO.deleteDirectory(destDataFile); //noinspection ResultOfMethodCallIgnored @@ -290,69 +264,73 @@ protected void convertLayerSet(Object source, ProductionState productionState) t throw new WWRuntimeException(message); } - if (this.isStopped()) + if (this.isStopped()) { return; + } this.getProductionResultsList().add(destConfigDoc); } - protected File getSourceConfigFile(Object source) - { - if (source instanceof File) - { + protected File getSourceConfigFile(Object source) { + if (source instanceof File) { return (File) source; - } - else if (source instanceof String && !WWUtil.isEmpty(source)) - { + } else if (source instanceof String && !WWUtil.isEmpty(source)) { return new File((String) source); } return null; } - protected File getDestConfigFile(AVList installParams) - { + protected File getDestConfigFile(AVList installParams) { String fileStoreLocation = installParams.getStringValue(AVKey.FILE_STORE_LOCATION); - if (fileStoreLocation != null) + if (fileStoreLocation != null) { fileStoreLocation = WWIO.stripTrailingSeparator(fileStoreLocation); + } - if (WWUtil.isEmpty(fileStoreLocation)) + if (WWUtil.isEmpty(fileStoreLocation)) { return null; + } String cacheName = DataConfigurationUtils.getDataConfigFilename(installParams, ".xml"); - if (cacheName != null) + if (cacheName != null) { cacheName = WWIO.stripLeadingSeparator(cacheName); + } - if (WWUtil.isEmpty(cacheName)) + if (WWUtil.isEmpty(cacheName)) { return null; + } return new File(fileStoreLocation + File.separator + cacheName); } - protected Document createDestConfigDoc(Document layerSetDoc, AVList installParams) - { + protected Document createDestConfigDoc(Document layerSetDoc, AVList installParams) { AVList params = new AVListImpl(); // Extract configuration parameters from the LayerSet document. DataConfigurationUtils.getWWDotNetLayerSetConfigParams(layerSetDoc.getDocumentElement(), params); // Override the LayerSet's display name with the name used by the converter. - if (installParams.getValue(AVKey.DISPLAY_NAME) != null) + if (installParams.getValue(AVKey.DISPLAY_NAME) != null) { params.setValue(AVKey.DISPLAY_NAME, installParams.getValue(AVKey.DISPLAY_NAME)); + } // Override the LayerSet's cache name with the cache name used by the converter. - if (installParams.getValue(AVKey.DATA_CACHE_NAME) != null) + if (installParams.getValue(AVKey.DATA_CACHE_NAME) != null) { params.setValue(AVKey.DATA_CACHE_NAME, installParams.getValue(AVKey.DATA_CACHE_NAME)); + } // Override the LayerSet's image format and available image format parameters with values used by the converter. - if (installParams.getValue(AVKey.IMAGE_FORMAT) != null) + if (installParams.getValue(AVKey.IMAGE_FORMAT) != null) { params.setValue(AVKey.IMAGE_FORMAT, installParams.getValue(AVKey.IMAGE_FORMAT)); - if (installParams.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) != null) + } + if (installParams.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) != null) { params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, installParams.getValue(AVKey.AVAILABLE_IMAGE_FORMATS)); + } // Override the LayerSet's format suffix with the suffix used by the converter. - if (installParams.getValue(AVKey.FORMAT_SUFFIX) != null) + if (installParams.getValue(AVKey.FORMAT_SUFFIX) != null) { params.setValue(AVKey.FORMAT_SUFFIX, installParams.getValue(AVKey.FORMAT_SUFFIX)); + } // Set the texture format to DDS. If the texture data is already in DDS format, this parameter is benign. params.setValue(AVKey.TEXTURE_FORMAT, DEFAULT_TEXTURE_FORMAT); @@ -363,72 +341,75 @@ protected Document createDestConfigDoc(Document layerSetDoc, AVList installParam //**************************************************************// //******************** Imagery Installation ******************// //**************************************************************// - private void copyWWDotNetDiretory(java.io.File source, java.io.File destination, String installMimeType, - ProductionState productionState) throws java.io.IOException - { - if (this.isStopped()) + ProductionState productionState) throws java.io.IOException { + if (this.isStopped()) { return; + } - if (!destination.exists()) - { + if (!destination.exists()) { //noinspection ResultOfMethodCallIgnored destination.mkdirs(); } - if (!destination.exists()) - { + if (!destination.exists()) { String message = Logging.getMessage("generic.CannotCreateFile", destination); Logging.logger().severe(message); throw new java.io.IOException(message); } java.io.File[] fileList = source.listFiles(); - if (fileList == null) + if (fileList == null) { return; + } java.util.List childFiles = new java.util.ArrayList(); java.util.List childDirs = new java.util.ArrayList(); - for (java.io.File child : fileList) - { + for (java.io.File child : fileList) { if (child == null) // Don't allow null subfiles. + { continue; + } if (child.isHidden()) // Ignore hidden files. + { continue; + } - if (child.isDirectory()) + if (child.isDirectory()) { childDirs.add(child); - else + } else { childFiles.add(child); + } } - for (java.io.File childFile : childFiles) - { - if (this.isStopped()) + for (java.io.File childFile : childFiles) { + if (this.isStopped()) { break; + } - if (!isWWDotNetFile(childFile)) + if (!isWWDotNetFile(childFile)) { continue; + } java.io.File destFile = makeWWJavaFile(destination, childFile.getName(), installMimeType); this.installWWDotNetFile(childFile, destFile, productionState); - if (!destFile.exists()) - { + if (!destFile.exists()) { String message = Logging.getMessage("generic.CannotCreateFile", destFile); Logging.logger().severe(message); throw new java.io.IOException(message); } } - for (java.io.File childDir : childDirs) - { - if (this.isStopped()) + for (java.io.File childDir : childDirs) { + if (this.isStopped()) { break; + } - if (!isWWDotNetDirectory(childDir)) + if (!isWWDotNetDirectory(childDir)) { continue; + } java.io.File destDir = makeWWJavaDirectory(destination, childDir.getName()); this.copyWWDotNetDiretory(childDir, destDir, installMimeType, productionState); @@ -436,14 +417,12 @@ private void copyWWDotNetDiretory(java.io.File source, java.io.File destination, } private void installWWDotNetFile(java.io.File source, java.io.File destination, ProductionState productionState) - throws java.io.IOException - { + throws java.io.IOException { // Bypass file installation if: // (a) destination is newer than source, and // (b) source and destination have identical size. if (destination.exists() && source.lastModified() >= destination.lastModified() - && source.length() == destination.length()) - { + && source.length() == destination.length()) { return; } @@ -451,20 +430,14 @@ private void installWWDotNetFile(java.io.File source, java.io.File destination, String destinationSuffix = WWIO.getSuffix(destination.getName()); // Source and destination types match. Copy the source file directly. - if (sourceSuffix.equalsIgnoreCase(destinationSuffix)) - { + if (sourceSuffix.equalsIgnoreCase(destinationSuffix)) { WWIO.copyFile(source, destination); - } - // Destination type is different. Convert the source file and write the converstion to the destionation. - else - { - if (destinationSuffix.equalsIgnoreCase("dds")) - { + } // Destination type is different. Convert the source file and write the converstion to the destionation. + else { + if (destinationSuffix.equalsIgnoreCase("dds")) { java.nio.ByteBuffer sourceBuffer = DDSCompressor.compressImageFile(source); WWIO.saveBuffer(sourceBuffer, destination); - } - else - { + } else { java.awt.image.BufferedImage sourceImage = javax.imageio.ImageIO.read(source); javax.imageio.ImageIO.write(sourceImage, destinationSuffix, destination); } @@ -473,24 +446,24 @@ private void installWWDotNetFile(java.io.File source, java.io.File destination, this.updateProgress(productionState); } - private static java.io.File makeWWJavaDirectory(java.io.File dir, String dirname) - { + private static java.io.File makeWWJavaDirectory(java.io.File dir, String dirname) { return new java.io.File(dir, WWIO.stripLeadingZeros(dirname)); } - private static java.io.File makeWWJavaFile(java.io.File dir, String filename, String installMimeType) - { + private static java.io.File makeWWJavaFile(java.io.File dir, String filename, String installMimeType) { // If the filename does not match the standard pattern, then return a file with that name. String[] tokens = filename.split("[._]"); - if (tokens == null || tokens.length < 3 || tokens[0].length() < 1 || tokens[1].length() < 1) + if (tokens == null || tokens.length < 3 || tokens[0].length() < 1 || tokens[1].length() < 1) { return new java.io.File(dir, filename); + } // If an installation type is specified, override the file extension with the new type. - if (installMimeType != null) + if (installMimeType != null) { tokens[2] = WWIO.makeSuffixForMimeType(installMimeType); - // Otherwise keep the existing extension. Add a leading '.' so that both cases can be handled transparently. - else if (tokens[2].length() > 1) + } // Otherwise keep the existing extension. Add a leading '.' so that both cases can be handled transparently. + else if (tokens[2].length() > 1) { tokens[2] = "." + tokens[2]; + } // If the filename is "000n_000m.foo", then the contents of tokens[] are: // tokens[0] = "000n" @@ -502,14 +475,12 @@ else if (tokens[2].length() > 1) return new java.io.File(dir, sb.toString()); } - private static boolean isWWDotNetDirectory(java.io.File file) - { + private static boolean isWWDotNetDirectory(java.io.File file) { String pattern = "\\d+"; return file.getName().matches(pattern); } - private static boolean isWWDotNetFile(java.io.File file) - { + private static boolean isWWDotNetFile(java.io.File file) { String pattern = "\\d+[_]\\d+[.]\\w+"; return file.getName().matches(pattern); } @@ -517,43 +488,46 @@ private static boolean isWWDotNetFile(java.io.File file) //**************************************************************// //******************** Progress and Verification *************// //**************************************************************// - - private int countWWDotNetFiles(java.io.File source) - { + private int countWWDotNetFiles(java.io.File source) { int count = 0; java.io.File[] fileList = source.listFiles(); - if (fileList == null) + if (fileList == null) { return count; + } java.util.List childFiles = new java.util.ArrayList(); java.util.List childDirs = new java.util.ArrayList(); - for (java.io.File child : fileList) - { + for (java.io.File child : fileList) { if (child == null) // Don't allow null subfiles. + { continue; + } if (child.isHidden()) // Ignore hidden files. + { continue; + } - if (child.isDirectory()) + if (child.isDirectory()) { childDirs.add(child); - else + } else { childFiles.add(child); + } } - for (java.io.File childFile : childFiles) - { - if (!isWWDotNetFile(childFile)) + for (java.io.File childFile : childFiles) { + if (!isWWDotNetFile(childFile)) { continue; + } count++; } - for (java.io.File childDir : childDirs) - { - if (!isWWDotNetDirectory(childDir)) + for (java.io.File childDir : childDirs) { + if (!isWWDotNetDirectory(childDir)) { continue; + } count += countWWDotNetFiles(childDir); } @@ -564,13 +538,10 @@ private int countWWDotNetFiles(java.io.File source) //**************************************************************// //******************** Progress Parameters *******************// //**************************************************************// - - protected void setProgressParameters(Iterable dataSources, ProductionState productionState) - { + protected void setProgressParameters(Iterable dataSources, ProductionState productionState) { int numSources = 0; //noinspection UnusedDeclaration - for (Object o : dataSources) - { + for (Object o : dataSources) { numSources++; } @@ -580,8 +551,7 @@ protected void setProgressParameters(Iterable dataSources, ProductionState pr productionState.numInstalledFiles = new int[numSources]; } - private void updateProgress(ProductionState productionState) - { + private void updateProgress(ProductionState productionState) { double oldProgress = this.computeProgress(productionState); productionState.numInstalledFiles[productionState.curSource]++; double newProgress = this.computeProgress(productionState); @@ -589,13 +559,11 @@ private void updateProgress(ProductionState productionState) this.firePropertyChange(AVKey.PROGRESS, oldProgress, newProgress); } - private double computeProgress(ProductionState productionState) - { + private double computeProgress(ProductionState productionState) { double progress = 0.0; - for (int i = 0; i <= productionState.curSource; i++) - { - progress += (productionState.numInstalledFiles[i] / - (double) productionState.numSourceFiles[i]) * (1.0 / (double) productionState.numSources); + for (int i = 0; i <= productionState.curSource; i++) { + progress += (productionState.numInstalledFiles[i] + / (double) productionState.numSourceFiles[i]) * (1.0 / (double) productionState.numSources); } return progress; } @@ -603,41 +571,33 @@ private double computeProgress(ProductionState productionState) //**************************************************************// //******************** LayerSet Removal **********************// //**************************************************************// - - protected void removeLayerSet(Object source, AVList params) - { + protected void removeLayerSet(Object source, AVList params) { File sourceConfigFile = this.getSourceConfigFile(source); - if (sourceConfigFile == null) - { + if (sourceConfigFile == null) { String message = Logging.getMessage("WWDotNetLayerSetConverter.NoSourceLocation"); Logging.logger().warning(message); return; } File destConfigFile = this.getDestConfigFile(params); - if (destConfigFile == null) - { + if (destConfigFile == null) { String message = Logging.getMessage("WWDotNetLayerSetConverter.NoInstallLocation", sourceConfigFile); Logging.logger().warning(message); return; } File destDataFile = destConfigFile.getParentFile(); - if (destDataFile == null) - { + if (destDataFile == null) { String message = Logging.getMessage("WWDotNetLayerSetConverter.FileWithoutParent", destConfigFile); Logging.logger().warning(message); return; } - try - { + try { WWIO.deleteDirectory(destDataFile); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("WWDotNetLayerSetConverter.ExceptionRemovingProductionState", - sourceConfigFile); + sourceConfigFile); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } diff --git a/src/gov/nasa/worldwind/data/package-info.java b/src/gov/nasa/worldwind/data/package-info.java index 0c4979cd5e..959c219aef 100644 --- a/src/gov/nasa/worldwind/data/package-info.java +++ b/src/gov/nasa/worldwind/data/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

    * This package provides classes for converting raw data sources into a form which can be used by standard WorldWind @@ -40,7 +39,7 @@ * formatted data. * * -

    + *

    * {@link gov.nasa.worldwind.data.DataStoreProducer} provides a common interface for converting raw data sources into a * form which can be used by standard WorldWind components. There are three concrete implementations of * DataStoreProducer: @@ -55,7 +54,7 @@ * structure into the WorldWind Java tile cache structure. * * -

    + *

    * Data Configuration Documents are a common mechanism and file format for describing a WorldWind * component's configuration. While data configuration documents are not part of the gov.nasa.worldwind.data package, * they are used as a configuration exchange mechanism by the classes in gov.nasa.worldwind.data. For example, @@ -74,7 +73,7 @@ * * * -

    Supported Formats

    + *

    Supported Formats

    *
      *
    • ADF - A proprietary BINARY format developed by ESRI for ARC/INFO GRID rasters stored in workspaces (INFO * directory, *.adf) @@ -94,7 +93,8 @@ *
    • *
    • CIB - Controlled Image Base format for ortho-photos (rectified grayscale aerial images), RPF and NITFS compliant *
    • - *
    • COASP - Defence R&D Canada (DRDC) designed data raster format for Configurable Airborne SAR Processor (*.coasp) + *
    • COASP - Defence R&D Canada (DRDC) designed data raster format for Configurable Airborne SAR Processor + * (*.coasp) *
    • *
    • COSAR - "COmplex SAR", Annotated Binary Matrix (TerraSAR-X), plain binary image raster, limited to 4GB size * (*.cosar) @@ -154,7 +154,7 @@ *
    • TER - Terragen terrain file format to store a one band of Int16 elevation values (*.ter, *.terrain)
    • *
    • TIFF - Tagged Image File Format (TIFF) and GeoTIFF (*.tif, *.tiff, *.gtif)
    • * -
    • AirSAR, AirSAR Polarimetric Image, AirSAR
    • + *
    • AirSAR, AirSAR Polarimetric Image, AirSAR
    • *
    • BT, VTP .bt (Binary Terrain) 1.3 Format, BT
    • *
    • CEOS, CEOS Image, CEOS
    • *
    • COASP, DRDC COASP SAR Processor Raster, COASP
    • @@ -174,7 +174,7 @@ *
    • GenBin, Generic Binary (.hdr Labelled), GenBin
    • *
    • GSC, GSC Geogrid, GSC
    • * -
    • HFA, Erdas Imagine Images (.img)A
    • + *
    • HFA, Erdas Imagine Images (.img)A
    • *
    • IDA, Image Data and Analysis, IDA
    • *
    • ILWIS, ILWIS Raster Map, ILWIS
    • *
    • INGR, Intergraph Raster, INGR
    • @@ -189,7 +189,7 @@
    • HFA, Erdas Imagine Images (.img)A
    • *
    • PCIDSK, PCIDSK Database File, PCIDSK
    • *
    • PDS, NASA Planetary Data System, PDS
    • * -
    • RMF, Raster Matrix Format, RMF
    • + *
    • RMF, Raster Matrix Format, RMF
    • *
    • RS2, RadarSat 2 XML Product, RS2
    • *
    • RST, Idrisi Raster A.1, RST
    • *
    • SAGA, SAGA GIS Binary Grid (.sdat), SAGA
    • @@ -201,13 +201,13 @@
    • HFA, Erdas Imagine Images (.img)A
    • *
    • TSX, TerraSAR-X Product, TSX
    • *
    • XPM, X11 PixMap Format, XPM
    • * -
    + * * - + * * * * -

    Supported Projections

    + *

    Supported Projections

    *
      *
    • Albers Equal-Area Conic
    • *
    • Azimuthal Equidistant
    • @@ -253,27 +253,27 @@
    • HFA, Erdas Imagine Images (.img)A
    • *
    • VanDerGrinten
    • *
    * - + * * * * -

    Deploying WorldWind's GDAL Libraries

    + *

    Deploying WorldWind's GDAL Libraries

    * - The open-source GDAL and PROJ4 libraries are used to import many of WorldWind's supported data formats. WorldWind + * The open-source GDAL and PROJ4 libraries are used to import many of WorldWind's supported data formats. WorldWind * uses GDAL version 1.7.2 and PROJ4 version ?.? along with LizardTech's Decode SDK version 7.0.0.2167 for MrSID * support. * * -

    Supported Platforms

    + *

    Supported Platforms

    * - GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows 32 and Windows 64. Support for Linux + * GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows 32 and Windows 64. Support for Linux * 32-bit and 64-bit, and Solaris are expected in the very near future. If the GDAL library cannot be found, data import * operates without it but supports only a limited set of formats and projections, in particular, GeoTIFF, JPEG, PNG, * BIL and DTED, and either EPSG:4326f (WGS84, latitude/longitude), or UTM. * *

    GDAL Library Locations

    * - To simplify deployment, GDAL + PRO4 + MrSID bundles are provided as a single dynamic library with all dependent + * To simplify deployment, GDAL + PRO4 + MrSID bundles are provided as a single dynamic library with all dependent * libraries included. There is one such library per platform, each located in * lib-external/gdal/platform, as follows: *
      @@ -286,18 +286,18 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * the current path, and if no GDAL bundle was found, will try to locate the GDAL bundle in the sub-folders. * * -

      Deploying with Java Web Start

      + *

      Deploying with Java Web Start

      * - Instructions for using the WorldWind GDAL libraries with a Java Web Start application are available at + * Instructions for using the WorldWind GDAL libraries with a Java Web Start application are available at * https://goworldwind.org/getting-started/. * * * * * -

      Common Use Case Examples

      + *

      Common Use Case Examples

      * - The following examples demonstrate the most common use cases which the classes in gov.nasa.worldwind.data are + * The following examples demonstrate the most common use cases which the classes in gov.nasa.worldwind.data are * designed to address. Additionally, several examples demonstrate data management use cases using data configuration * documents. These examples constitute an overview of how to convert raw data sources into a form which can be consumed * by WorldWind components, then manage the data in its converted form. @@ -355,7 +355,7 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * * * - + * *

      * Example 2: Converting Georeferenced Elevation Data to the WorldWind Tile Structure * @@ -365,7 +365,7 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * {@link gov.nasa.worldwind.data.TiledImageProducer} with {@link gov.nasa.worldwind.data.TiledElevationProducer}. * * - + * *

      * Example 3: Converting WorldWind .NET LayerSets to the WorldWind Java Tile Structure * @@ -375,7 +375,7 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * {@link gov.nasa.worldwind.data.TiledImageProducer} with {@link gov.nasa.worldwind.data.WWDotNetLayerSetConverter}. * * - + * *

      * Example 4: Reading Data Configuration Documents from the File System *

      @@ -392,7 +392,7 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * *
      * - + * *

      * Example 5: Reading Data Configuration Documents from the WorldWind FileStore * @@ -420,7 +420,7 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * * * - + * *

      * Example 6: Writing Data Configuration Documents *

      @@ -460,7 +460,7 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * *
      * - + * *

      * Example 7: Searching for Data Configuration Documents in the File System *

      @@ -483,7 +483,7 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * *
      * - + * *

      * Example 8: Searching for Data Configuration Documents in the WorldWind FileStore * @@ -534,7 +534,7 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * * * - + * *

      * Example 9: Creating WorldWind Components from Data Configuration Documents *

      @@ -582,11 +582,11 @@ GDAL and PROJ4 have been incorporated for MacOSX (Snow Leopard, 64-bit), Windows * *
      * - + * * * * -

      DataDescriptor Porting Guide

      + *

      DataDescriptor Porting Guide

      * DataDescriptor has been replaced with data configuration documents. This guide explains why DataDescriptor has been * replaced, provides information on backward compatability with data configuration, and outlines how to update code * which uses DataDescriptor. diff --git a/src/gov/nasa/worldwind/drag/DragContext.java b/src/gov/nasa/worldwind/drag/DragContext.java index 7aaee7d66f..31a38d4e1f 100644 --- a/src/gov/nasa/worldwind/drag/DragContext.java +++ b/src/gov/nasa/worldwind/drag/DragContext.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.drag; import gov.nasa.worldwind.*; @@ -16,8 +15,8 @@ /** * Provides information about mouse inputs and {@link WorldWindow} state for use in dragging operations. */ -public class DragContext -{ +public class DragContext { + /** * In accordance with the AWT screen coordinates the top left point of the window is the origin. */ @@ -45,8 +44,7 @@ public class DragContext */ protected View view; /** - * The current drag state, which can be one of the three following values: - * {@link gov.nasa.worldwind.avlist.AVKey#DRAG_BEGIN}, {@link gov.nasa.worldwind.avlist.AVKey#DRAG_CHANGE}, + * The current drag state, which can be one of the three following values: {@link gov.nasa.worldwind.avlist.AVKey#DRAG_BEGIN}, {@link gov.nasa.worldwind.avlist.AVKey#DRAG_CHANGE}, * {@link gov.nasa.worldwind.avlist.AVKey#DRAG_ENDED}. */ protected String dragState; @@ -54,8 +52,7 @@ public class DragContext /** * Creates a new {@link DragContext} instance. */ - public DragContext() - { + public DragContext() { } /** @@ -63,8 +60,7 @@ public DragContext() * * @return the current screen point. */ - public Point getPoint() - { + public Point getPoint() { return point; } @@ -75,10 +71,8 @@ public Point getPoint() * * @throws IllegalArgumentException if the point is null. */ - public void setPoint(Point point) - { - if (point == null) - { + public void setPoint(Point point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -92,8 +86,7 @@ public void setPoint(Point point) * * @return the previous point. */ - public Point getPreviousPoint() - { + public Point getPreviousPoint() { return previousPoint; } @@ -104,10 +97,8 @@ public Point getPreviousPoint() * * @throws IllegalArgumentException if the previousPoint is null. */ - public void setPreviousPoint(Point previousPoint) - { - if (previousPoint == null) - { + public void setPreviousPoint(Point previousPoint) { + if (previousPoint == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -122,8 +113,7 @@ public void setPreviousPoint(Point previousPoint) * * @return the initial screen point. */ - public Point getInitialPoint() - { + public Point getInitialPoint() { return initialPoint; } @@ -134,10 +124,8 @@ public Point getInitialPoint() * * @throws IllegalArgumentException if the initialPoint is null. */ - public void setInitialPoint(Point initialPoint) - { - if (initialPoint == null) - { + public void setInitialPoint(Point initialPoint) { + if (initialPoint == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -151,8 +139,7 @@ public void setInitialPoint(Point initialPoint) * * @return the current {@link SceneController}. */ - public SceneController getSceneController() - { + public SceneController getSceneController() { return sceneController; } @@ -163,10 +150,8 @@ public SceneController getSceneController() * * @throws IllegalArgumentException if the scene controller is null. */ - public void setSceneController(SceneController sceneController) - { - if (sceneController == null) - { + public void setSceneController(SceneController sceneController) { + if (sceneController == null) { String msg = Logging.getMessage("nullValue.SceneControllerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -180,8 +165,7 @@ public void setSceneController(SceneController sceneController) * * @return the current {@link Globe}. */ - public Globe getGlobe() - { + public Globe getGlobe() { return globe; } @@ -192,10 +176,8 @@ public Globe getGlobe() * * @throws IllegalArgumentException if the globe is null. */ - public void setGlobe(Globe globe) - { - if (globe == null) - { + public void setGlobe(Globe globe) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -209,8 +191,7 @@ public void setGlobe(Globe globe) * * @return the current {@link View}. */ - public View getView() - { + public View getView() { return view; } @@ -221,10 +202,8 @@ public View getView() * * @throws IllegalArgumentException if the view is null. */ - public void setView(View view) - { - if (view == null) - { + public void setView(View view) { + if (view == null) { String msg = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -238,8 +217,7 @@ public void setView(View view) * * @return the drag state. */ - public String getDragState() - { + public String getDragState() { return dragState; } @@ -251,18 +229,15 @@ public String getDragState() * * @throws IllegalArgumentException if the drag state is null or not one of the three states defined for dragging. */ - public void setDragState(String dragState) - { - if (dragState == null) - { + public void setDragState(String dragState) { + if (dragState == null) { String msg = Logging.getMessage("nullValue.DragStateIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } if (!dragState.equals(AVKey.DRAG_BEGIN) && !dragState.equals(AVKey.DRAG_CHANGE) - && !dragState.equals(AVKey.DRAG_ENDED)) - { + && !dragState.equals(AVKey.DRAG_ENDED)) { String msg = Logging.getMessage("generic.UnknownDragState", dragState); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -270,4 +245,4 @@ public void setDragState(String dragState) this.dragState = dragState; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/drag/Draggable.java b/src/gov/nasa/worldwind/drag/Draggable.java index 0837745cc9..675506811e 100644 --- a/src/gov/nasa/worldwind/drag/Draggable.java +++ b/src/gov/nasa/worldwind/drag/Draggable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.drag; /** @@ -11,8 +10,8 @@ * Draggable#drag(DragContext)} method includes information on the screen coordinates and the state of the * {@link gov.nasa.worldwind.WorldWindow}. */ -public interface Draggable -{ +public interface Draggable { + /** * Indicates whether the object is enabled for dragging. * diff --git a/src/gov/nasa/worldwind/drag/DraggableSupport.java b/src/gov/nasa/worldwind/drag/DraggableSupport.java index e8caabcb57..61382b15d4 100644 --- a/src/gov/nasa/worldwind/drag/DraggableSupport.java +++ b/src/gov/nasa/worldwind/drag/DraggableSupport.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.drag; import gov.nasa.worldwind.*; @@ -18,8 +17,8 @@ * Utility functions which support dragging operations on objects implementing the {@link Movable} or {@link Movable2} * interface. */ -public class DraggableSupport -{ +public class DraggableSupport { + /** * The {@link DraggableSupport#computeRelativePoint(Line, Globe, SceneController, double)} method uses a numeric * search method to determine the coordinates of the desired position. The numeric solver will stop at a defined @@ -76,23 +75,20 @@ public class DraggableSupport * Provides persistence of initial values of a drag operation to increase dragging precision and provide better * dragging behavior. * - * @param dragObject the object to be dragged. + * @param dragObject the object to be dragged. * @param altitudeMode the altitude mode. * * @throws IllegalArgumentException if the object is null. */ - public DraggableSupport(Object dragObject, int altitudeMode) - { - if (dragObject == null) - { + public DraggableSupport(Object dragObject, int altitudeMode) { + if (dragObject == null) { String msg = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (altitudeMode != WorldWind.ABSOLUTE && altitudeMode != WorldWind.CLAMP_TO_GROUND && - altitudeMode != WorldWind.RELATIVE_TO_GROUND && altitudeMode != WorldWind.CONSTANT) - { + if (altitudeMode != WorldWind.ABSOLUTE && altitudeMode != WorldWind.CLAMP_TO_GROUND + && altitudeMode != WorldWind.RELATIVE_TO_GROUND && altitudeMode != WorldWind.CONSTANT) { String msg = Logging.getMessage("generic.InvalidAltitudeMode", altitudeMode); Logging.logger().warning(msg); } @@ -113,34 +109,33 @@ public DraggableSupport(Object dragObject, int altitudeMode) * * @throws IllegalArgumentException if the {@link DragContext} is null. */ - public void dragScreenSizeConstant(DragContext dragContext) - { - if (dragContext == null) - { + public void dragScreenSizeConstant(DragContext dragContext) { + if (dragContext == null) { String msg = Logging.getMessage("nullValue.DragContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Position referencePosition = this.getReferencePosition(); - if (referencePosition == null) + if (referencePosition == null) { return; + } - if (dragContext.getDragState().equals(AVKey.DRAG_BEGIN)) - { + if (dragContext.getDragState().equals(AVKey.DRAG_BEGIN)) { this.initialScreenPointOffset = this.computeScreenOffsetFromReferencePosition( - referencePosition, - dragContext); + referencePosition, + dragContext); } - if (this.initialScreenPointOffset == null) + if (this.initialScreenPointOffset == null) { return; + } double referenceAltitude = referencePosition.getAltitude(); Vec4 currentPoint = new Vec4( - dragContext.getPoint().getX(), - dragContext.getPoint().getY() + dragContext.getPoint().getX(), + dragContext.getPoint().getY() ); // Apply the screen coordinate move to the current screen point @@ -148,20 +143,22 @@ public void dragScreenSizeConstant(DragContext dragContext) // Project the new screen point back through the globe to find a new reference position Line ray = dragContext.getView().computeRayFromScreenPoint( - moveToScreenCoordinates.getX(), - moveToScreenCoordinates.getY() + moveToScreenCoordinates.getX(), + moveToScreenCoordinates.getY() ); - if (ray == null) + if (ray == null) { return; + } Vec4 moveToGlobeCoordinates = this.computeGlobeIntersection( - ray, - referenceAltitude, - true, - dragContext.getGlobe(), - dragContext.getSceneController()); - if (moveToGlobeCoordinates == null) + ray, + referenceAltitude, + true, + dragContext.getGlobe(), + dragContext.getSceneController()); + if (moveToGlobeCoordinates == null) { return; + } Position moveTo = dragContext.getGlobe().computePositionFromPoint(moveToGlobeCoordinates); @@ -178,60 +175,63 @@ public void dragScreenSizeConstant(DragContext dragContext) * * @throws IllegalArgumentException if the {@link DragContext} is null. */ - public void dragGlobeSizeConstant(DragContext dragContext) - { - if (dragContext == null) - { + public void dragGlobeSizeConstant(DragContext dragContext) { + if (dragContext == null) { String msg = Logging.getMessage("nullValue.DragContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Position referencePosition = this.getReferencePosition(); - if (referencePosition == null) + if (referencePosition == null) { return; + } - if (dragContext.getDragState().equals(AVKey.DRAG_BEGIN)) - { + if (dragContext.getDragState().equals(AVKey.DRAG_BEGIN)) { this.initialEllipsoidalReferencePoint = dragContext.getGlobe() - .computeEllipsoidalPointFromPosition(referencePosition); + .computeEllipsoidalPointFromPosition(referencePosition); this.initialEllipsoidalScreenPoint = this.computeEllipsoidalPointFromScreen( - dragContext, - dragContext.getInitialPoint(), - referencePosition.getAltitude(), - false); + dragContext, + dragContext.getInitialPoint(), + referencePosition.getAltitude(), + false); } - if (this.initialEllipsoidalReferencePoint == null || this.initialEllipsoidalScreenPoint == null) + if (this.initialEllipsoidalReferencePoint == null || this.initialEllipsoidalScreenPoint == null) { return; + } double referenceAltitude = referencePosition.getAltitude(); Vec4 currentScreenPoint = new Vec4( - dragContext.getPoint().getX(), - dragContext.getPoint().getY() + dragContext.getPoint().getX(), + dragContext.getPoint().getY() ); Line ray = dragContext.getView() - .computeRayFromScreenPoint(currentScreenPoint.getX(), currentScreenPoint.getY()); - if (ray == null) + .computeRayFromScreenPoint(currentScreenPoint.getX(), currentScreenPoint.getY()); + if (ray == null) { return; + } Vec4 currentPoint = this.computeGlobeIntersection( - ray, - referenceAltitude, - false, - dragContext.getGlobe(), - dragContext.getSceneController()); - if (currentPoint == null) + ray, + referenceAltitude, + false, + dragContext.getGlobe(), + dragContext.getSceneController()); + if (currentPoint == null) { return; + } Position currentPosition = dragContext.getGlobe().computePositionFromPoint(currentPoint); - if (currentPosition == null) + if (currentPosition == null) { return; + } Vec4 currentEllipsoidalPoint = dragContext.getGlobe().computeEllipsoidalPointFromPosition(currentPosition); - if (currentEllipsoidalPoint == null) + if (currentEllipsoidalPoint == null) { return; + } Vec4 rotationAxis = this.initialEllipsoidalScreenPoint.cross3(currentEllipsoidalPoint).normalize3(); Angle rotationAngle = this.initialEllipsoidalScreenPoint.angleBetween3(currentEllipsoidalPoint); @@ -239,9 +239,10 @@ public void dragGlobeSizeConstant(DragContext dragContext) Vec4 dragObjectReferenceMoveToEllipsoidalPoint = this.initialEllipsoidalReferencePoint.transformBy3(rotation); Position moveToInterim = dragContext.getGlobe() - .computePositionFromEllipsoidalPoint(dragObjectReferenceMoveToEllipsoidalPoint); - if (moveToInterim == null) + .computePositionFromEllipsoidalPoint(dragObjectReferenceMoveToEllipsoidalPoint); + if (moveToInterim == null) { return; + } Position moveTo = new Position(moveToInterim, referenceAltitude); @@ -255,8 +256,7 @@ public void dragGlobeSizeConstant(DragContext dragContext) * * @return the step limit. */ - public int getStepLimit() - { + public int getStepLimit() { return this.stepLimit; } @@ -268,8 +268,7 @@ public int getStepLimit() * * @param stepLimit the step limit to set for the solver method. */ - public void setStepLimit(int stepLimit) - { + public void setStepLimit(int stepLimit) { this.stepLimit = stepLimit; } @@ -281,8 +280,7 @@ public void setStepLimit(int stepLimit) * * @return the convergence threshold. */ - public double getConvergenceThreshold() - { + public double getConvergenceThreshold() { return this.convergenceThreshold; } @@ -294,8 +292,7 @@ public double getConvergenceThreshold() * * @param convergenceThreshold the convergence threshold to use for the solver. */ - public void setConvergenceThreshold(double convergenceThreshold) - { + public void setConvergenceThreshold(double convergenceThreshold) { this.convergenceThreshold = convergenceThreshold; } @@ -304,8 +301,7 @@ public void setConvergenceThreshold(double convergenceThreshold) * * @return the altitude mode. */ - public int getAltitudeMode() - { + public int getAltitudeMode() { return this.altitudeMode; } @@ -314,11 +310,9 @@ public int getAltitudeMode() * * @param altitudeMode the altitude mode to use for dragging calculations. */ - public void setAltitudeMode(int altitudeMode) - { - if (altitudeMode != WorldWind.ABSOLUTE && altitudeMode != WorldWind.CLAMP_TO_GROUND && - altitudeMode != WorldWind.RELATIVE_TO_GROUND && altitudeMode != WorldWind.CONSTANT) - { + public void setAltitudeMode(int altitudeMode) { + if (altitudeMode != WorldWind.ABSOLUTE && altitudeMode != WorldWind.CLAMP_TO_GROUND + && altitudeMode != WorldWind.RELATIVE_TO_GROUND && altitudeMode != WorldWind.CONSTANT) { String msg = Logging.getMessage("generic.InvalidAltitudeMode", altitudeMode); Logging.logger().warning(msg); } @@ -328,32 +322,32 @@ public void setAltitudeMode(int altitudeMode) /** * Determines the cartesian coordinate of a screen point given the altitude mode. * - * @param dragContext the current {@link DragContext} of the dragging event. - * @param screenPoint the {@link Point} of the screen to determine the position. - * @param altitude the altitude in meters. + * @param dragContext the current {@link DragContext} of the dragging event. + * @param screenPoint the {@link Point} of the screen to determine the position. + * @param altitude the altitude in meters. * @param utilizeSearchMethod if the altitude mode is {@link WorldWind#RELATIVE_TO_GROUND}, this determines if the - * search method will be used to determine the position, please see the {@link - * DraggableSupport#computeRelativePoint(Line, Globe, SceneController, double)} for more - * information. + * search method will be used to determine the position, please see the {@link + * DraggableSupport#computeRelativePoint(Line, Globe, SceneController, double)} for more information. * * @return the cartesian coordinates using an ellipsoidal globe, or null if a position could not be determined. */ protected Vec4 computeEllipsoidalPointFromScreen(DragContext dragContext, Point screenPoint, double altitude, - boolean utilizeSearchMethod) - { + boolean utilizeSearchMethod) { Line ray = dragContext.getView().computeRayFromScreenPoint(screenPoint.getX(), screenPoint.getY()); Vec4 globePoint = this.computeGlobeIntersection( - ray, - altitude, - utilizeSearchMethod, - dragContext.getGlobe(), - dragContext.getSceneController()); - if (globePoint == null) + ray, + altitude, + utilizeSearchMethod, + dragContext.getGlobe(), + dragContext.getSceneController()); + if (globePoint == null) { return null; + } Position screenPosition = dragContext.getGlobe().computePositionFromPoint(globePoint); - if (screenPosition == null) + if (screenPosition == null) { return null; + } return dragContext.getGlobe().computeEllipsoidalPointFromPosition(screenPosition); } @@ -365,50 +359,45 @@ protected Vec4 computeEllipsoidalPointFromScreen(DragContext dragContext, Point * will return null. * * @param dragObjectReferencePosition the {@link Movable} or {@link Movable2} reference position {@link Position}. - * @param dragContext the current {@link DragContext} of this drag event. + * @param dragContext the current {@link DragContext} of this drag event. * * @return a {@link Vec4} containing the x and y offsets in screen coordinates from the reference position and the * previous screen point. */ protected Vec4 computeScreenOffsetFromReferencePosition(Position dragObjectReferencePosition, - DragContext dragContext) - { + DragContext dragContext) { Vec4 dragObjectPoint; - if (dragContext.getGlobe() instanceof Globe2D) - { + if (dragContext.getGlobe() instanceof Globe2D) { dragObjectPoint = dragContext.getGlobe().computePointFromPosition( - new Position(dragObjectReferencePosition, 0.0)); - } - else - { + new Position(dragObjectReferencePosition, 0.0)); + } else { // If the altitude mode is ABSOLUTE, or not recognized as a standard WorldWind altitude mode, use the // ABSOLUTE method as the default - if (this.altitudeMode == WorldWind.ABSOLUTE || - (this.altitudeMode != WorldWind.RELATIVE_TO_GROUND && this.altitudeMode != WorldWind.CLAMP_TO_GROUND - && this.altitudeMode != WorldWind.CONSTANT)) - { + if (this.altitudeMode == WorldWind.ABSOLUTE + || (this.altitudeMode != WorldWind.RELATIVE_TO_GROUND && this.altitudeMode != WorldWind.CLAMP_TO_GROUND + && this.altitudeMode != WorldWind.CONSTANT)) { dragObjectPoint = dragContext.getGlobe().computePointFromPosition(dragObjectReferencePosition); - } - else // Should be any one of the remaining WorldWind altitude modes: CLAMP, RELATIVE, CONSTANT + } else // Should be any one of the remaining WorldWind altitude modes: CLAMP, RELATIVE, CONSTANT { dragObjectPoint = dragContext.getSceneController().getTerrain() - .getSurfacePoint(dragObjectReferencePosition); + .getSurfacePoint(dragObjectReferencePosition); } } - if (dragObjectPoint == null) + if (dragObjectPoint == null) { return null; + } Vec4 dragObjectScreenPoint = dragContext.getView().project(dragObjectPoint); - if (dragObjectScreenPoint == null) + if (dragObjectScreenPoint == null) { return null; + } Vec4 screenPointOffset = new Vec4( - dragContext.getInitialPoint().getX() - dragObjectScreenPoint.getX(), - dragContext.getInitialPoint().getY() - ( - dragContext.getView().getViewport().getHeight() - - dragObjectScreenPoint.getY() - 1.0) + dragContext.getInitialPoint().getX() - dragObjectScreenPoint.getX(), + dragContext.getInitialPoint().getY() - (dragContext.getView().getViewport().getHeight() + - dragObjectScreenPoint.getY() - 1.0) ); return screenPointOffset; @@ -422,12 +411,12 @@ protected Vec4 computeScreenOffsetFromReferencePosition(Position dragObjectRefer * @return the reference {@link Movable#getReferencePosition()} or {@link Movable2#getReferencePosition()}, or null * if the object didn't implement either interface. */ - protected Position getReferencePosition() - { - if (this.dragObject instanceof Movable2) + protected Position getReferencePosition() { + if (this.dragObject instanceof Movable2) { return ((Movable2) this.dragObject).getReferencePosition(); - else if (this.dragObject instanceof Movable) + } else if (this.dragObject instanceof Movable) { return ((Movable) this.dragObject).getReferencePosition(); + } return null; } @@ -438,36 +427,31 @@ else if (this.dragObject instanceof Movable) * implement either, it is ignored. * * @param movePosition the {@link Position} to provide to the {@link Movable2#moveTo} method. - * @param globe the globe reference, may be null if the object only implements the {@link Movable} - * interface. + * @param globe the globe reference, may be null if the object only implements the {@link Movable} interface. */ - protected void doMove(Position movePosition, Globe globe) - { - if (this.dragObject instanceof Movable2) - { - if (globe == null) - { + protected void doMove(Position movePosition, Globe globe) { + if (this.dragObject instanceof Movable2) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } ((Movable2) this.dragObject).moveTo(globe, movePosition); - } - else if (this.dragObject instanceof Movable) + } else if (this.dragObject instanceof Movable) { ((Movable) this.dragObject).moveTo(movePosition); + } } /** * Computes the intersection of the provided {@link Line} with the {@link Globe} while accounting for the altitude * mode. If a {@link Globe2D} is specified, then the intersection is calculated using the globe objects method. * - * @param ray the {@link Line} to calculate the intersection of the {@link Globe}. - * @param altitude the altitude mode for the intersection calculation. + * @param ray the {@link Line} to calculate the intersection of the {@link Globe}. + * @param altitude the altitude mode for the intersection calculation. * @param useSearchMethod if the altitude mode is {@link WorldWind#RELATIVE_TO_GROUND}, this determines if the - * search method will be used to determine the position, please see the {@link - * DraggableSupport#computeRelativePoint(Line, Globe, SceneController, double)} for more - * information. - * @param globe the {@link Globe} to intersect. + * search method will be used to determine the position, please see the {@link + * DraggableSupport#computeRelativePoint(Line, Globe, SceneController, double)} for more information. + * @param globe the {@link Globe} to intersect. * @param sceneController if an altitude mode other than {@link WorldWind#ABSOLUTE} is specified, the {@link * SceneController} which will provide terrain information. * @@ -475,66 +459,52 @@ else if (this.dragObject instanceof Movable) * the intersection couldn't be calculated. */ protected Vec4 - computeGlobeIntersection(Line ray, double altitude, boolean useSearchMethod, Globe globe, - SceneController sceneController) - { + computeGlobeIntersection(Line ray, double altitude, boolean useSearchMethod, Globe globe, + SceneController sceneController) { Intersection[] intersections; - if (globe instanceof Globe2D) - { + if (globe instanceof Globe2D) { // Utilize the globe intersection method for a Globe2D as it best describes the appearance and the // terrain intersection method returns null when crossing the dateline on a Globe2D intersections = globe.intersect(ray, 0.0); - } - else if (this.altitudeMode == WorldWind.ABSOLUTE) - { + } else if (this.altitudeMode == WorldWind.ABSOLUTE) { // Accounts for the object being visually placed on the surface in a Globe2D Globe intersections = globe.intersect(ray, altitude); - } - else if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND || this.altitudeMode == WorldWind.CONSTANT) - { + } else if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND || this.altitudeMode == WorldWind.CONSTANT) { intersections = sceneController.getTerrain().intersect(ray); - } - else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) { // If an object is RELATIVE_TO_GROUND but has an altitude close to 0.0, use CLAMP_TO_GROUND method - if (altitude < 1.0) - { + if (altitude < 1.0) { intersections = sceneController.getTerrain().intersect(ray); - } - else - { + } else { // When an object maintains a constant screen size independent of globe orientation or eye location, // the dragger attempts to determine the position by testing different points of the ray for a // matching altitude above elevation. The method is only used in objects maintain a constant screen // size as the effects are less pronounced in globe constant features. - if (useSearchMethod) - { + if (useSearchMethod) { Vec4 intersectionPoint = this.computeRelativePoint(ray, globe, sceneController, altitude); // In the event the computeRelativePoint fails with the numeric approach it falls back to a // ellipsoidal intersection. Need to check if the result of that calculation was also null, // indicating the screen point doesn't intersect with the globe. - if (intersectionPoint != null) - intersections = new Intersection[] {new Intersection(intersectionPoint, false)}; - else + if (intersectionPoint != null) { + intersections = new Intersection[]{new Intersection(intersectionPoint, false)}; + } else { intersections = null; - } - else - { + } + } else { intersections = globe.intersect(ray, altitude); } } - } - else - { + } else { // If the altitude mode isn't recognized, the ABSOLUTE determination method is used as a fallback/default intersections = globe.intersect(ray, altitude); } - if ((intersections != null) && (intersections.length > 0)) + if ((intersections != null) && (intersections.length > 0)) { return intersections[0].getIntersectionPoint(); - else + } else { return null; + } } /** @@ -545,26 +515,23 @@ else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) * find a position within the {@code stepLimit} or within the {@code convergenceThreshold} it will provide an * intersection with the ellipsoid at the provided altitude. * - * @param ray the {@link Line} from the eye point and direction in globe coordinates. - * @param globe the current {@link Globe}. + * @param ray the {@link Line} from the eye point and direction in globe coordinates. + * @param globe the current {@link Globe}. * @param sceneController the current {@link SceneController}. - * @param altitude the target altitude. + * @param altitude the target altitude. * * @return a {@link Vec4} of the point in globe coordinates. */ - protected Vec4 computeRelativePoint(Line ray, Globe globe, SceneController sceneController, double altitude) - { + protected Vec4 computeRelativePoint(Line ray, Globe globe, SceneController sceneController, double altitude) { // Calculate the intersection of ray with the terrain Intersection[] intersections = sceneController.getTerrain().intersect(ray); - if (intersections != null) - { + if (intersections != null) { Vec4 eye = ray.getOrigin(); Vec4 surface = intersections[0].getIntersectionPoint(); double maxDifference = eye.getLength3() - surface.getLength3(); // Account for extremely zoomed out instances - if (maxDifference > (5 * altitude)) - { + if (maxDifference > (5 * altitude)) { double mixAmount = (5 * altitude) / maxDifference; eye = Vec4.mix3(mixAmount, surface, eye); // maxDifference = eye.getLength3() - surface.getLength3(); @@ -585,32 +552,32 @@ protected Vec4 computeRelativePoint(Line ray, Globe globe, SceneController scene double pointAlt; Vec4 intersectionPoint; - for (int i = 0; i < this.stepLimit; i++) - { + for (int i = 0; i < this.stepLimit; i++) { intersectionPoint = Vec4.mix3(mixPoint, surface, eye); Position pointPos = globe.computePositionFromPoint(intersectionPoint); pointAlt = globe.getElevation(pointPos.getLatitude(), pointPos.getLongitude()); pointAlt = pointPos.getElevation() - pointAlt; - if (Math.abs(pointAlt - altitude) < this.convergenceThreshold) - { + if (Math.abs(pointAlt - altitude) < this.convergenceThreshold) { return intersectionPoint; } - if (altitude < pointAlt) + if (altitude < pointAlt) { mixHigh = mixPoint; - else + } else { mixLow = mixPoint; + } mixPoint = (mixHigh + mixLow) / 2.0; } } intersections = globe.intersect(ray, altitude); - if (intersections != null && (intersections.length > 0)) + if (intersections != null && (intersections.length > 0)) { return intersections[0].getIntersectionPoint(); + } return null; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/event/BulkRetrievalEvent.java b/src/gov/nasa/worldwind/event/BulkRetrievalEvent.java index 422764834a..2b9d2b706b 100644 --- a/src/gov/nasa/worldwind/event/BulkRetrievalEvent.java +++ b/src/gov/nasa/worldwind/event/BulkRetrievalEvent.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.event; import gov.nasa.worldwind.retrieve.BulkRetrievable; @@ -15,12 +14,16 @@ * @version $Id: BulkRetrievalEvent.java 1171 2013-02-11 21:45:02Z dcollins $ * @see gov.nasa.worldwind.retrieve.BulkRetrievable */ -public class BulkRetrievalEvent extends WWEvent -{ - /** Constant indicating retrieval failure. */ +public class BulkRetrievalEvent extends WWEvent { + + /** + * Constant indicating retrieval failure. + */ public static String RETRIEVAL_FAILED = "gov.nasa.worldwind.retrieve.BulkRetrievable.RetrievalFailed"; - /** Constant indicating retrieval success. */ + /** + * Constant indicating retrieval success. + */ public static String RETRIEVAL_SUCCEEDED = "gov.nasa.worldwind.retrieve.BulkRetrievable.RetrievalSucceeded"; protected String eventType; @@ -29,14 +32,13 @@ public class BulkRetrievalEvent extends WWEvent /** * Creates a new event. * - * @param source the event source, typically either a tiled image layer, elevation model or placename layer. + * @param source the event source, typically either a tiled image layer, elevation model or placename layer. * @param eventType indicates success or failure. One of {@link #RETRIEVAL_SUCCEEDED} or {@link #RETRIEVAL_FAILED}. - * @param item the cache location of the item whose retrieval succeeded or failed. + * @param item the cache location of the item whose retrieval succeeded or failed. * * @see gov.nasa.worldwind.retrieve.BulkRetrievable */ - public BulkRetrievalEvent(BulkRetrievable source, String eventType, String item) - { + public BulkRetrievalEvent(BulkRetrievable source, String eventType, String item) { super(source); this.eventType = eventType; @@ -50,8 +52,7 @@ public BulkRetrievalEvent(BulkRetrievable source, String eventType, String item) * * @see gov.nasa.worldwind.retrieve.BulkRetrievable */ - public BulkRetrievable getSource() - { + public BulkRetrievable getSource() { return super.getSource() instanceof BulkRetrievable ? (BulkRetrievable) super.getSource() : null; } @@ -60,8 +61,7 @@ public BulkRetrievable getSource() * * @return the event type. */ - public String getEventType() - { + public String getEventType() { return eventType; } @@ -70,8 +70,7 @@ public String getEventType() * * @return the filestore location of the item. */ - public String getItem() - { + public String getItem() { return item; } } diff --git a/src/gov/nasa/worldwind/event/BulkRetrievalListener.java b/src/gov/nasa/worldwind/event/BulkRetrievalListener.java index 7b574a683c..9ce3cb1ed9 100644 --- a/src/gov/nasa/worldwind/event/BulkRetrievalListener.java +++ b/src/gov/nasa/worldwind/event/BulkRetrievalListener.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.event; import java.util.EventListener; @@ -14,13 +13,13 @@ * @author tag * @version $Id: BulkRetrievalListener.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface BulkRetrievalListener extends EventListener -{ +public interface BulkRetrievalListener extends EventListener { + /** * A bulk-download event occurred, either a succes, a failure or an extended event. * * @param event the event that occurred. - * @see gov.nasa.worldwind.retrieve.BulkRetrievable + * @see gov.nasa.worldwind.retrieve.BulkRetrievable */ void eventOccurred(BulkRetrievalEvent event); } diff --git a/src/gov/nasa/worldwind/event/DragSelectEvent.java b/src/gov/nasa/worldwind/event/DragSelectEvent.java index a5469bbaa7..9740639c6a 100644 --- a/src/gov/nasa/worldwind/event/DragSelectEvent.java +++ b/src/gov/nasa/worldwind/event/DragSelectEvent.java @@ -16,13 +16,12 @@ * @author tag * @version $Id: DragSelectEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DragSelectEvent extends SelectEvent -{ +public class DragSelectEvent extends SelectEvent { + private final java.awt.Point previousPickPoint; public DragSelectEvent(Object source, String eventAction, MouseEvent mouseEvent, PickedObjectList pickedObjects, - java.awt.Point previousPickPoint) - { + java.awt.Point previousPickPoint) { super(source, eventAction, mouseEvent, pickedObjects); this.previousPickPoint = previousPickPoint; } @@ -32,8 +31,7 @@ public DragSelectEvent(Object source, String eventAction, MouseEvent mouseEvent, * * @return the screen position of the event just prior to this one. */ - public java.awt.Point getPreviousPickPoint() - { + public java.awt.Point getPreviousPickPoint() { return this.previousPickPoint; } } diff --git a/src/gov/nasa/worldwind/event/InputHandler.java b/src/gov/nasa/worldwind/event/InputHandler.java index 874f5d20fe..173746fff7 100644 --- a/src/gov/nasa/worldwind/event/InputHandler.java +++ b/src/gov/nasa/worldwind/event/InputHandler.java @@ -14,8 +14,8 @@ * @author tag * @version $Id: InputHandler.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface InputHandler extends AVList, java.beans.PropertyChangeListener -{ +public interface InputHandler extends AVList, java.beans.PropertyChangeListener { + void setEventSource(WorldWindow newWorldWindow); WorldWindow getEventSource(); diff --git a/src/gov/nasa/worldwind/event/Message.java b/src/gov/nasa/worldwind/event/Message.java index 03b280d957..d52073c064 100644 --- a/src/gov/nasa/worldwind/event/Message.java +++ b/src/gov/nasa/worldwind/event/Message.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.event; /** @@ -12,33 +11,35 @@ * @author pabercrombie * @version $Id: Message.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Message extends WWEvent -{ - /** Message name. */ +public class Message extends WWEvent { + + /** + * Message name. + */ protected String name; - /** Time at which the message was sent. */ + /** + * Time at which the message was sent. + */ protected long when; /** * Create a message. The message will be timestamped with the current system time. * - * @param name The name of the message. + * @param name The name of the message. * @param source The object that generated the message. */ - public Message(String name, Object source) - { + public Message(String name, Object source) { this(name, source, System.currentTimeMillis()); } /** * Create a message, with a timestamp. * - * @param name The name of the message. + * @param name The name of the message. * @param source The object that generated the message. - * @param when The timestamp to apply to the message. + * @param when The timestamp to apply to the message. */ - public Message(String name, Object source, long when) - { + public Message(String name, Object source, long when) { super(source); this.name = name; this.when = when; @@ -49,8 +50,7 @@ public Message(String name, Object source, long when) * * @return The message name. */ - public String getName() - { + public String getName() { return this.name; } @@ -59,8 +59,7 @@ public String getName() * * @return Time, in milliseconds since the Epoch, at which the message was sent. */ - public long getWhen() - { + public long getWhen() { return this.when; } } diff --git a/src/gov/nasa/worldwind/event/MessageListener.java b/src/gov/nasa/worldwind/event/MessageListener.java index 57e5f0caa1..03edb8c925 100644 --- a/src/gov/nasa/worldwind/event/MessageListener.java +++ b/src/gov/nasa/worldwind/event/MessageListener.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.event; /** @@ -12,8 +11,8 @@ * @author pabercrombie * @version $Id: MessageListener.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MessageListener -{ +public interface MessageListener { + /** * Invoked when a message is received. * diff --git a/src/gov/nasa/worldwind/event/NoOpInputHandler.java b/src/gov/nasa/worldwind/event/NoOpInputHandler.java index c9529322db..7042f856a9 100644 --- a/src/gov/nasa/worldwind/event/NoOpInputHandler.java +++ b/src/gov/nasa/worldwind/event/NoOpInputHandler.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.event; import gov.nasa.worldwind.*; @@ -16,76 +15,59 @@ * @author tag * @version $Id: NoOpInputHandler.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NoOpInputHandler extends WWObjectImpl implements InputHandler -{ - public void setEventSource(WorldWindow newWorldWindow) - { +public class NoOpInputHandler extends WWObjectImpl implements InputHandler { + + public void setEventSource(WorldWindow newWorldWindow) { } - public WorldWindow getEventSource() - { + public WorldWindow getEventSource() { return null; } - public void setHoverDelay(int delay) - { + public void setHoverDelay(int delay) { } - public int getHoverDelay() - { + public int getHoverDelay() { return 0; } - public void addSelectListener(SelectListener listener) - { + public void addSelectListener(SelectListener listener) { } - public void removeSelectListener(SelectListener listener) - { + public void removeSelectListener(SelectListener listener) { } - public void addKeyListener(KeyListener listener) - { + public void addKeyListener(KeyListener listener) { } - public void removeKeyListener(KeyListener listener) - { + public void removeKeyListener(KeyListener listener) { } - public void addMouseListener(MouseListener listener) - { + public void addMouseListener(MouseListener listener) { } - public void removeMouseListener(MouseListener listener) - { + public void removeMouseListener(MouseListener listener) { } - public void addMouseMotionListener(MouseMotionListener listener) - { + public void addMouseMotionListener(MouseMotionListener listener) { } - public void removeMouseMotionListener(MouseMotionListener listener) - { + public void removeMouseMotionListener(MouseMotionListener listener) { } - public void addMouseWheelListener(MouseWheelListener listener) - { + public void addMouseWheelListener(MouseWheelListener listener) { } - public void removeMouseWheelListener(MouseWheelListener listener) - { + public void removeMouseWheelListener(MouseWheelListener listener) { } - public void dispose() - { + public void dispose() { } - public boolean isForceRedrawOnMousePressed() - { + public boolean isForceRedrawOnMousePressed() { return false; } - public void setForceRedrawOnMousePressed(boolean forceRedrawOnMousePressed) - { + public void setForceRedrawOnMousePressed(boolean forceRedrawOnMousePressed) { } } diff --git a/src/gov/nasa/worldwind/event/PositionEvent.java b/src/gov/nasa/worldwind/event/PositionEvent.java index 1f8f0875e8..4562e13c95 100644 --- a/src/gov/nasa/worldwind/event/PositionEvent.java +++ b/src/gov/nasa/worldwind/event/PositionEvent.java @@ -11,41 +11,36 @@ * @author tag * @version $Id: PositionEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PositionEvent extends WWEvent -{ +public class PositionEvent extends WWEvent { + private final java.awt.Point screenPoint; private final Position position; private final Position previousPosition; - public PositionEvent(Object source, java.awt.Point screenPoint, Position previousPosition, Position position) - { + public PositionEvent(Object source, java.awt.Point screenPoint, Position previousPosition, Position position) { super(source); this.screenPoint = screenPoint; this.position = position; this.previousPosition = previousPosition; } - public java.awt.Point getScreenPoint() - { + public java.awt.Point getScreenPoint() { return screenPoint; } - public Position getPosition() - { + public Position getPosition() { return position; } - public Position getPreviousPosition() - { + public Position getPreviousPosition() { return previousPosition; } @Override - public String toString() - { + public String toString() { return this.getClass().getName() + " " - + (this.previousPosition != null ? this.previousPosition : "null") - + " --> " - + (this.position != null ? this.position : "null"); + + (this.previousPosition != null ? this.previousPosition : "null") + + " --> " + + (this.position != null ? this.position : "null"); } } diff --git a/src/gov/nasa/worldwind/event/PositionListener.java b/src/gov/nasa/worldwind/event/PositionListener.java index 5e00cc24ba..a9b486ce72 100644 --- a/src/gov/nasa/worldwind/event/PositionListener.java +++ b/src/gov/nasa/worldwind/event/PositionListener.java @@ -11,7 +11,7 @@ * @author tag * @version $Id: PositionListener.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface PositionListener extends EventListener -{ +public interface PositionListener extends EventListener { + public void moved(PositionEvent event); } diff --git a/src/gov/nasa/worldwind/event/RenderingEvent.java b/src/gov/nasa/worldwind/event/RenderingEvent.java index 2b693884ec..39919eef08 100644 --- a/src/gov/nasa/worldwind/event/RenderingEvent.java +++ b/src/gov/nasa/worldwind/event/RenderingEvent.java @@ -11,29 +11,26 @@ * @author tag * @version $Id: RenderingEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RenderingEvent extends WWEvent -{ +public class RenderingEvent extends WWEvent { + public static final String BEFORE_RENDERING = "gov.nasa.worldwind.RenderingEvent.BeforeRendering"; public static final String BEFORE_BUFFER_SWAP = "gov.nasa.worldwind.RenderingEvent.BeforeBufferSwap"; public static final String AFTER_BUFFER_SWAP = "gov.nasa.worldwind.RenderingEvent.AfterBufferSwap"; private String stage; - public RenderingEvent(Object source, String stage) - { + public RenderingEvent(Object source, String stage) { super(source); this.stage = stage; } - public String getStage() - { + public String getStage() { return this.stage != null ? this.stage : "gov.nasa.worldwind.RenderingEvent.UnknownStage"; } @Override - public String toString() - { + public String toString() { return this.getClass().getName() + " " - + (this.stage != null ? this.stage : Logging.getMessage("generic.Unknown")); + + (this.stage != null ? this.stage : Logging.getMessage("generic.Unknown")); } } diff --git a/src/gov/nasa/worldwind/event/RenderingExceptionListener.java b/src/gov/nasa/worldwind/event/RenderingExceptionListener.java index f513c8a1c1..0e6bdac78c 100644 --- a/src/gov/nasa/worldwind/event/RenderingExceptionListener.java +++ b/src/gov/nasa/worldwind/event/RenderingExceptionListener.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.event; import java.util.*; @@ -12,7 +11,7 @@ * @author tag * @version $Id: RenderingExceptionListener.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface RenderingExceptionListener extends EventListener -{ +public interface RenderingExceptionListener extends EventListener { + public void exceptionThrown(Throwable t); } diff --git a/src/gov/nasa/worldwind/event/RenderingListener.java b/src/gov/nasa/worldwind/event/RenderingListener.java index 3fae5d5108..b79dacdb24 100644 --- a/src/gov/nasa/worldwind/event/RenderingListener.java +++ b/src/gov/nasa/worldwind/event/RenderingListener.java @@ -11,7 +11,7 @@ * @author tag * @version $Id: RenderingListener.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface RenderingListener extends EventListener -{ +public interface RenderingListener extends EventListener { + public void stageChanged(RenderingEvent event); } diff --git a/src/gov/nasa/worldwind/event/SelectEvent.java b/src/gov/nasa/worldwind/event/SelectEvent.java index 6eaf348b83..8bf1bb6769 100644 --- a/src/gov/nasa/worldwind/event/SelectEvent.java +++ b/src/gov/nasa/worldwind/event/SelectEvent.java @@ -16,7 +16,8 @@ * This class signals that an object or terrain is under the cursor and identifies that object and the operation that * caused the signal. See the Field Summary for a description of the possible operations. When a SelectEvent * occurs, all select event listeners registered with the associated {@link gov.nasa.worldwind.WorldWindow} are called. - * Select event listeners are registered by calling {@link gov.nasa.worldwind.WorldWindow#addSelectListener(SelectListener)}. + * Select event listeners are registered by calling + * {@link gov.nasa.worldwind.WorldWindow#addSelectListener(SelectListener)}. *

      * A ROLLOVER SelectEvent is generated every frame when the cursor is over a visible object either because * the user moved it there or because the WorldWindow was repainted and a visible object was found to be under the @@ -44,17 +45,27 @@ * @version $Id: SelectEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ @SuppressWarnings({"StringEquality"}) -public class SelectEvent extends WWEvent -{ - /** The user clicked the left mouse button while the cursor was over picked object. */ +public class SelectEvent extends WWEvent { + + /** + * The user clicked the left mouse button while the cursor was over picked object. + */ public static final String LEFT_CLICK = "gov.nasa.worldwind.SelectEvent.LeftClick"; - /** The user double-clicked the left mouse button while the cursor was over picked object. */ + /** + * The user double-clicked the left mouse button while the cursor was over picked object. + */ public static final String LEFT_DOUBLE_CLICK = "gov.nasa.worldwind.SelectEvent.LeftDoubleClick"; - /** The user clicked the right mouse button while the cursor was over picked object. */ + /** + * The user clicked the right mouse button while the cursor was over picked object. + */ public static final String RIGHT_CLICK = "gov.nasa.worldwind.SelectEvent.RightClick"; - /** The user pressed the left mouse button while the cursor was over picked object. */ + /** + * The user pressed the left mouse button while the cursor was over picked object. + */ public static final String LEFT_PRESS = "gov.nasa.worldwind.SelectEvent.LeftPress"; - /** The user pressed the right mouse button while the cursor was over picked object. */ + /** + * The user pressed the right mouse button while the cursor was over picked object. + */ public static final String RIGHT_PRESS = "gov.nasa.worldwind.SelectEvent.RightPress"; /** * The cursor has moved over the picked object and become stationary, or has moved off the object of the most recent @@ -66,9 +77,13 @@ public class SelectEvent extends WWEvent * the picked object will be null. */ public static final String ROLLOVER = "gov.nasa.worldwind.SelectEvent.Rollover"; - /** The user is attempting to drag the picked object. */ + /** + * The user is attempting to drag the picked object. + */ public static final String DRAG = "gov.nasa.worldwind.SelectEvent.Drag"; - /** The user has stopped dragging the picked object. */ + /** + * The user has stopped dragging the picked object. + */ public static final String DRAG_END = "gov.nasa.worldwind.SelectEvent.DragEnd"; /** * The user has selected one or more of objects using a selection box. A box rollover event is generated every frame @@ -85,8 +100,7 @@ public class SelectEvent extends WWEvent private final MouseEvent mouseEvent; private final PickedObjectList pickedObjects; - public SelectEvent(Object source, String eventAction, MouseEvent mouseEvent, PickedObjectList pickedObjects) - { + public SelectEvent(Object source, String eventAction, MouseEvent mouseEvent, PickedObjectList pickedObjects) { super(source); this.eventAction = eventAction; this.pickPoint = mouseEvent != null ? mouseEvent.getPoint() : null; @@ -95,8 +109,7 @@ public SelectEvent(Object source, String eventAction, MouseEvent mouseEvent, Pic this.pickedObjects = pickedObjects; } - public SelectEvent(Object source, String eventAction, Point pickPoint, PickedObjectList pickedObjects) - { + public SelectEvent(Object source, String eventAction, Point pickPoint, PickedObjectList pickedObjects) { super(source); this.eventAction = eventAction; this.pickPoint = pickPoint; @@ -105,8 +118,7 @@ public SelectEvent(Object source, String eventAction, Point pickPoint, PickedObj this.pickedObjects = pickedObjects; } - public SelectEvent(Object source, String eventAction, Rectangle pickRectangle, PickedObjectList pickedObjects) - { + public SelectEvent(Object source, String eventAction, Rectangle pickRectangle, PickedObjectList pickedObjects) { super(source); this.eventAction = eventAction; this.pickPoint = null; @@ -116,51 +128,43 @@ public SelectEvent(Object source, String eventAction, Rectangle pickRectangle, P } @Override - public void consume() - { + public void consume() { super.consume(); - if (this.getMouseEvent() != null) + if (this.getMouseEvent() != null) { this.getMouseEvent().consume(); + } } - public String getEventAction() - { + public String getEventAction() { return this.eventAction != null ? this.eventAction : "gov.nasa.worldwind.SelectEvent.UnknownEventAction"; } - public Point getPickPoint() - { + public Point getPickPoint() { return this.pickPoint; } - public Rectangle getPickRectangle() - { + public Rectangle getPickRectangle() { return this.pickRect; } - public MouseEvent getMouseEvent() - { + public MouseEvent getMouseEvent() { return this.mouseEvent; } - public boolean hasObjects() - { + public boolean hasObjects() { return this.pickedObjects != null && this.pickedObjects.size() > 0; } - public PickedObjectList getObjects() - { + public PickedObjectList getObjects() { return this.pickedObjects; } - public PickedObject getTopPickedObject() - { + public PickedObject getTopPickedObject() { return this.hasObjects() ? this.pickedObjects.getTopPickedObject() : null; } - public Object getTopObject() - { + public Object getTopObject() { PickedObject tpo = this.getTopPickedObject(); return tpo != null ? tpo.getObject() : null; } @@ -172,8 +176,7 @@ public Object getTopObject() * * @return a new list of the picked objects marked as on top, or null if nothing is marked as on top. */ - public List getAllTopPickedObjects() - { + public List getAllTopPickedObjects() { return this.hasObjects() ? this.pickedObjects.getAllTopPickedObjects() : null; } @@ -183,70 +186,59 @@ public List getAllTopPickedObjects() * any picked objects marked as on top. * * @return a new list of the objects associated with a picked object marked as on top, or null if - * nothing is marked as on top. + * nothing is marked as on top. */ - public List getAllTopObjects() - { + public List getAllTopObjects() { return this.hasObjects() ? this.pickedObjects.getAllTopObjects() : null; } - public boolean isRollover() - { + public boolean isRollover() { return this.getEventAction() == ROLLOVER; } - public boolean isHover() - { + public boolean isHover() { return this.getEventAction() == HOVER; } - public boolean isDragEnd() - { + public boolean isDragEnd() { return this.getEventAction() == DRAG_END; } - public boolean isDrag() - { + public boolean isDrag() { return this.getEventAction() == DRAG; } - public boolean isRightPress() - { + public boolean isRightPress() { return this.getEventAction() == RIGHT_PRESS; } - public boolean isRightClick() - { + public boolean isRightClick() { return this.getEventAction() == RIGHT_CLICK; } - public boolean isLeftDoubleClick() - { + public boolean isLeftDoubleClick() { return this.getEventAction() == LEFT_DOUBLE_CLICK; } - public boolean isLeftClick() - { + public boolean isLeftClick() { return this.getEventAction() == LEFT_CLICK; } - public boolean isLeftPress() - { + public boolean isLeftPress() { return this.getEventAction() == LEFT_PRESS; } - public boolean isBoxSelect() - { + public boolean isBoxSelect() { return this.getEventAction() == BOX_ROLLOVER; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(this.getClass().getName() + " " - + (this.eventAction != null ? this.eventAction : Logging.getMessage("generic.Unknown"))); - if (this.pickedObjects != null && this.pickedObjects.getTopObject() != null) + + (this.eventAction != null ? this.eventAction : Logging.getMessage("generic.Unknown"))); + if (this.pickedObjects != null && this.pickedObjects.getTopObject() != null) { sb.append(", ").append(this.pickedObjects.getTopObject().getClass().getName()); + } return sb.toString(); } diff --git a/src/gov/nasa/worldwind/event/SelectListener.java b/src/gov/nasa/worldwind/event/SelectListener.java index 4c52a5ea38..7ffc68761a 100644 --- a/src/gov/nasa/worldwind/event/SelectListener.java +++ b/src/gov/nasa/worldwind/event/SelectListener.java @@ -11,7 +11,7 @@ * @author tag * @version $Id: SelectListener.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface SelectListener extends EventListener -{ +public interface SelectListener extends EventListener { + public void selected(SelectEvent event); } diff --git a/src/gov/nasa/worldwind/event/WWEvent.java b/src/gov/nasa/worldwind/event/WWEvent.java index b820d69178..5f7bd394df 100644 --- a/src/gov/nasa/worldwind/event/WWEvent.java +++ b/src/gov/nasa/worldwind/event/WWEvent.java @@ -17,9 +17,11 @@ * @author dcollins * @version $Id: WWEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWEvent extends EventObject -{ - /** Denotes whether or not the event has been consumed. Initially {@code false}. */ +public class WWEvent extends EventObject { + + /** + * Denotes whether or not the event has been consumed. Initially {@code false}. + */ protected boolean consumed; /** @@ -29,8 +31,7 @@ public class WWEvent extends EventObject * * @throws IllegalArgumentException if the source is {@code null}. */ - public WWEvent(Object source) - { + public WWEvent(Object source) { super(source); } @@ -38,8 +39,7 @@ public WWEvent(Object source) * Consumes the event so it will not be processed in the default manner by the source which originated it. This does * nothing if the event cannot be consumed. */ - public void consume() - { + public void consume() { this.consumed = true; } @@ -51,8 +51,7 @@ public void consume() * * @return {@code true} if the event has been consumed, and {@code false} otherwise. */ - public boolean isConsumed() - { + public boolean isConsumed() { return this.consumed; } } diff --git a/src/gov/nasa/worldwind/exception/NoItemException.java b/src/gov/nasa/worldwind/exception/NoItemException.java index 7178ad17f1..1c8447b45e 100644 --- a/src/gov/nasa/worldwind/exception/NoItemException.java +++ b/src/gov/nasa/worldwind/exception/NoItemException.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.exception; /** @@ -12,10 +11,9 @@ * @author tag * @version $Id: NoItemException.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NoItemException extends WWRuntimeException -{ - public NoItemException(String string) - { +public class NoItemException extends WWRuntimeException { + + public NoItemException(String string) { super(string); } } diff --git a/src/gov/nasa/worldwind/exception/ServiceException.java b/src/gov/nasa/worldwind/exception/ServiceException.java index c6559cb132..c5e4f9f46b 100644 --- a/src/gov/nasa/worldwind/exception/ServiceException.java +++ b/src/gov/nasa/worldwind/exception/ServiceException.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.exception; /** @@ -12,10 +11,9 @@ * @author tag * @version $Id: ServiceException.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ServiceException extends WWRuntimeException -{ - public ServiceException(String message) - { +public class ServiceException extends WWRuntimeException { + + public ServiceException(String message) { super(message); } } diff --git a/src/gov/nasa/worldwind/exception/WWAbsentRequirementException.java b/src/gov/nasa/worldwind/exception/WWAbsentRequirementException.java index ac374574a5..00a3d6fcd8 100644 --- a/src/gov/nasa/worldwind/exception/WWAbsentRequirementException.java +++ b/src/gov/nasa/worldwind/exception/WWAbsentRequirementException.java @@ -3,31 +3,26 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.exception; /** * @author tag * @version $Id: WWAbsentRequirementException.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWAbsentRequirementException extends WWRuntimeException -{ - public WWAbsentRequirementException() - { +public class WWAbsentRequirementException extends WWRuntimeException { + + public WWAbsentRequirementException() { } - public WWAbsentRequirementException(String s) - { + public WWAbsentRequirementException(String s) { super(s); } - public WWAbsentRequirementException(String s, Throwable throwable) - { + public WWAbsentRequirementException(String s, Throwable throwable) { super(s, throwable); } - public WWAbsentRequirementException(Throwable throwable) - { + public WWAbsentRequirementException(Throwable throwable) { super(throwable); } } diff --git a/src/gov/nasa/worldwind/exception/WWRuntimeException.java b/src/gov/nasa/worldwind/exception/WWRuntimeException.java index 0189f913ee..db67d2057c 100644 --- a/src/gov/nasa/worldwind/exception/WWRuntimeException.java +++ b/src/gov/nasa/worldwind/exception/WWRuntimeException.java @@ -9,24 +9,20 @@ * @author Tom Gaskins * @version $Id: WWRuntimeException.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWRuntimeException extends RuntimeException -{ - public WWRuntimeException() - { +public class WWRuntimeException extends RuntimeException { + + public WWRuntimeException() { } - public WWRuntimeException(String s) - { + public WWRuntimeException(String s) { super(s); } - public WWRuntimeException(String s, Throwable throwable) - { + public WWRuntimeException(String s, Throwable throwable) { super(s, throwable); } - public WWRuntimeException(Throwable throwable) - { + public WWRuntimeException(Throwable throwable) { super(throwable); } } diff --git a/src/gov/nasa/worldwind/exception/WWTimeoutException.java b/src/gov/nasa/worldwind/exception/WWTimeoutException.java index 3040fea1a7..1bf6859962 100644 --- a/src/gov/nasa/worldwind/exception/WWTimeoutException.java +++ b/src/gov/nasa/worldwind/exception/WWTimeoutException.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.exception; /** @@ -12,10 +11,9 @@ * @author tag * @version $Id: WWTimeoutException.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWTimeoutException extends WWRuntimeException -{ - public WWTimeoutException(String message) - { +public class WWTimeoutException extends WWRuntimeException { + + public WWTimeoutException(String message) { super(message); } } diff --git a/src/gov/nasa/worldwind/exception/WWUnrecognizedException.java b/src/gov/nasa/worldwind/exception/WWUnrecognizedException.java index f964e70d9f..8cd9ef7e90 100644 --- a/src/gov/nasa/worldwind/exception/WWUnrecognizedException.java +++ b/src/gov/nasa/worldwind/exception/WWUnrecognizedException.java @@ -11,15 +11,14 @@ * @author tag * @version $Id: WWUnrecognizedException.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWUnrecognizedException extends WWRuntimeException -{ +public class WWUnrecognizedException extends WWRuntimeException { + /** * Construct an exception with a message string. * * @param msg the message. */ - public WWUnrecognizedException(String msg) - { + public WWUnrecognizedException(String msg) { super(msg); } @@ -27,10 +26,9 @@ public WWUnrecognizedException(String msg) * Construct an exception with a message string and a intial-cause exception. * * @param msg the message. - * @param t the exception causing this exception. + * @param t the exception causing this exception. */ - public WWUnrecognizedException(String msg, Throwable t) - { + public WWUnrecognizedException(String msg, Throwable t) { super(msg, t); } } diff --git a/src/gov/nasa/worldwind/formats/csv/CSVReader.java b/src/gov/nasa/worldwind/formats/csv/CSVReader.java index 1645f9669d..933c5b545f 100644 --- a/src/gov/nasa/worldwind/formats/csv/CSVReader.java +++ b/src/gov/nasa/worldwind/formats/csv/CSVReader.java @@ -16,37 +16,32 @@ * @author tag * @version $Id: CSVReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CSVReader implements Track, TrackSegment -{ +public class CSVReader implements Track, TrackSegment { + private List tracks = new ArrayList(); private List segments = new ArrayList(); private List points = new ArrayList(); private String name; // private int lineNumber = 0; - public CSVReader() - { + public CSVReader() { this.tracks.add(this); this.segments.add(this); } - public List getSegments() - { + public List getSegments() { return this.segments; } - public String getName() - { + public String getName() { return this.name; } - public int getNumPoints() - { + public int getNumPoints() { return this.points.size(); } - public List getPoints() - { + public List getPoints() { return this.points; } @@ -55,10 +50,8 @@ public List getPoints() * @throws IllegalArgumentException if path is null * @throws java.io.IOException If there are issues reading from the file. */ - public void readFile(String path) throws IOException - { - if (path == null) - { + public void readFile(String path) throws IOException { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -67,8 +60,7 @@ public void readFile(String path) throws IOException this.name = path; java.io.File file = new java.io.File(path); - if (!file.exists()) - { + if (!file.exists()) { String msg = Logging.getMessage("generic.FileNotFound", path); Logging.logger().severe(msg); throw new FileNotFoundException(path); @@ -84,10 +76,8 @@ public void readFile(String path) throws IOException * @throws IllegalArgumentException if stream is null * @throws java.io.IOException If there are issues reading the stream. */ - public void readStream(InputStream stream, String name) throws IOException - { - if (stream == null) - { + public void readStream(InputStream stream, String name) throws IOException { + if (stream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -97,64 +87,50 @@ public void readStream(InputStream stream, String name) throws IOException this.doReadStream(stream); } - public List getTracks() - { + public List getTracks() { return this.tracks; } - public Iterator getTrackPositionIterator() - { - return new Iterator() - { + public Iterator getTrackPositionIterator() { + return new Iterator() { private TrackPointIterator trackPoints = new TrackPointIteratorImpl(CSVReader.this.tracks); - public boolean hasNext() - { + public boolean hasNext() { return this.trackPoints.hasNext(); } - public Position next() - { + public Position next() { return this.trackPoints.next().getPosition(); } - public void remove() - { + public void remove() { this.trackPoints.remove(); } }; } - private void doReadStream(InputStream stream) - { + private void doReadStream(InputStream stream) { String sentence; Scanner scanner = new Scanner(stream); - try - { - do - { + try { + do { sentence = scanner.nextLine(); - if (sentence != null) - { + if (sentence != null) { // ++this.lineNumber; this.parseLine(sentence); } } while (sentence != null); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { //noinspection UnnecessaryReturnStatement return; } } - private void parseLine(String sentence) - { + private void parseLine(String sentence) { // try // { - if ( sentence.trim().length() > 0) - { + if (sentence.trim().length() > 0) { CSVTrackPoint point = new CSVTrackPoint(sentence.split(",")); this.points.add(point); } diff --git a/src/gov/nasa/worldwind/formats/csv/CSVTrackPoint.java b/src/gov/nasa/worldwind/formats/csv/CSVTrackPoint.java index cdc651bc9d..1c989fc583 100644 --- a/src/gov/nasa/worldwind/formats/csv/CSVTrackPoint.java +++ b/src/gov/nasa/worldwind/formats/csv/CSVTrackPoint.java @@ -13,8 +13,8 @@ * @author tag * @version $Id: CSVTrackPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CSVTrackPoint implements TrackPoint -{ +public class CSVTrackPoint implements TrackPoint { + String time = ""; private double latitude; private double longitude; @@ -24,16 +24,13 @@ public class CSVTrackPoint implements TrackPoint * @param words The point coordinate values. * @throws IllegalArgumentException if words is null or has length less than 1 */ - public CSVTrackPoint(String[] words) - { - if (words == null) - { + public CSVTrackPoint(String[] words) { + if (words == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (words.length < 2) - { + if (words.length < 2) { String msg = Logging.getMessage("generic.ArrayInvalidLength", words.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -42,47 +39,46 @@ public CSVTrackPoint(String[] words) this.doValues(words); } - private void doValues(String[] words) - { + private void doValues(String[] words) { this.latitude = this.parseLatitude(words[1]); this.longitude = this.parseLongitude(words[2]); - if (words.length > 3) + if (words.length > 3) { this.altitude = this.parseElevation(words[3], "M"); + } } - private double parseLatitude(String angle) - { + private double parseLatitude(String angle) { return angle.length() == 0 ? 0 : Double.parseDouble(angle); } - private double parseLongitude(String angle) - { + private double parseLongitude(String angle) { return angle.length() == 0 ? 0 : Double.parseDouble(angle); } - private double parseElevation(String alt, String units) - { + private double parseElevation(String alt, String units) { return alt.length() == 0 ? 0 : Double.parseDouble(alt) * unitsToMeters(units); } - private double unitsToMeters(String units) - { + private double unitsToMeters(String units) { double f; if (units.equals("M")) // meters + { f = 1d; - else if (units.equals("f")) // feet + } else if (units.equals("f")) // feet + { f = 3.2808399; - else if (units.equals("F")) // fathoms + } else if (units.equals("F")) // fathoms + { f = 0.5468066528; - else + } else { f = 1d; + } return f; } - public double getLatitude() - { + public double getLatitude() { return latitude; } @@ -90,10 +86,8 @@ public double getLatitude() * @param latitude The latitude value. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 */ - public void setLatitude(double latitude) - { - if (latitude > 90 || latitude < -90) - { + public void setLatitude(double latitude) { + if (latitude > 90 || latitude < -90) { String msg = Logging.getMessage("generic.AngleOutOfRange", latitude); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -102,8 +96,7 @@ public void setLatitude(double latitude) this.latitude = latitude; } - public double getLongitude() - { + public double getLongitude() { return longitude; } @@ -111,10 +104,8 @@ public double getLongitude() * @param longitude The new longitude value. * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 */ - public void setLongitude(double longitude) - { - if (longitude > 180 || longitude < -180) - { + public void setLongitude(double longitude) { + if (longitude > 180 || longitude < -180) { String msg = Logging.getMessage("generic.AngleOutOfRange", longitude); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -123,15 +114,12 @@ public void setLongitude(double longitude) this.longitude = longitude; } - public Position getPosition() - { + public Position getPosition() { return Position.fromDegrees(this.latitude, this.longitude, this.altitude); } - public void setPosition(Position position) - { - if (position == null) - { + public void setPosition(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -142,30 +130,25 @@ public void setPosition(Position position) this.altitude = position.getElevation(); } - public double getElevation() - { + public double getElevation() { return this.altitude; } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.altitude = elevation; } - public String getTime() - { + public String getTime() { return null; } - public void setTime(String time) - { + public void setTime(String time) { this.time = time; } @Override - public String toString() - { + public String toString() { return String.format("(%10.8f\u00B0, %11.8f\u00B0, %10.4g m, %s)", this.latitude, this.longitude, - this.altitude, this.time); + this.altitude, this.time); } } diff --git a/src/gov/nasa/worldwind/formats/csv/CSVWriter.java b/src/gov/nasa/worldwind/formats/csv/CSVWriter.java index 4db063863b..9d95f9d289 100644 --- a/src/gov/nasa/worldwind/formats/csv/CSVWriter.java +++ b/src/gov/nasa/worldwind/formats/csv/CSVWriter.java @@ -14,15 +14,13 @@ * @author dcollins * @version $Id: CSVWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CSVWriter -{ +public class CSVWriter { + private final java.io.PrintWriter printWriter; private int lineNumber = 0; - public CSVWriter(String path) throws java.io.IOException - { - if (path == null) - { + public CSVWriter(String path) throws java.io.IOException { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -31,10 +29,8 @@ public CSVWriter(String path) throws java.io.IOException this.printWriter = new java.io.PrintWriter(new java.io.BufferedWriter(new java.io.FileWriter(path))); } - public CSVWriter(java.io.OutputStream stream) throws java.io.IOException - { - if (stream == null) - { + public CSVWriter(java.io.OutputStream stream) throws java.io.IOException { + if (stream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -43,47 +39,40 @@ public CSVWriter(java.io.OutputStream stream) throws java.io.IOException this.printWriter = new java.io.PrintWriter(new java.io.BufferedWriter(new java.io.OutputStreamWriter(stream))); } - public void writeTrack(Track track) - { - if (track == null) - { + public void writeTrack(Track track) { + if (track == null) { String msg = Logging.getMessage("nullValue.TrackIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - doWriteTrack(track,this.printWriter); + doWriteTrack(track, this.printWriter); doFlush(); } - public void close() - { + public void close() { doFlush(); this.printWriter.close(); } - private void doWriteTrack(Track track, java.io.PrintWriter out) - { - if (track != null && track.getSegments() != null) - { - for (TrackSegment ts : track.getSegments()) + private void doWriteTrack(Track track, java.io.PrintWriter out) { + if (track != null && track.getSegments() != null) { + for (TrackSegment ts : track.getSegments()) { doWriteTrackSegment(ts, out); + } } } - private void doWriteTrackSegment(TrackSegment segment, java.io.PrintWriter out) - { - if (segment != null && segment.getPoints() != null) - { - for (TrackPoint tp : segment.getPoints()) + private void doWriteTrackSegment(TrackSegment segment, java.io.PrintWriter out) { + if (segment != null && segment.getPoints() != null) { + for (TrackPoint tp : segment.getPoints()) { doWriteTrackPoint(tp, out); + } } } - private void doWriteTrackPoint(TrackPoint point, java.io.PrintWriter out) - { - if (point != null) - { + private void doWriteTrackPoint(TrackPoint point, java.io.PrintWriter out) { + if (point != null) { int lineNum = this.lineNumber++; out.print(lineNum); out.print(","); @@ -98,8 +87,7 @@ private void doWriteTrackPoint(TrackPoint point, java.io.PrintWriter out) } } - private void doFlush() - { + private void doFlush() { this.printWriter.flush(); } } diff --git a/src/gov/nasa/worldwind/formats/dds/AlphaBlockDXT3.java b/src/gov/nasa/worldwind/formats/dds/AlphaBlockDXT3.java index b43803fa7d..a91912bae1 100644 --- a/src/gov/nasa/worldwind/formats/dds/AlphaBlockDXT3.java +++ b/src/gov/nasa/worldwind/formats/dds/AlphaBlockDXT3.java @@ -11,14 +11,14 @@ * are tightly packed into 64 bits in the DXT file as follows, where the value aN represents the Nth alpha value in * hexadecimal notation: *

      - * | 63-56 | 55-48 | 47-40 | 39-32 | 31-24 | 23-16 | 15-8 | 7-0 | - * | aFaE | aDaC | aBaA | a9a8 | a7a6 | a5a4 | a3a2 | a1a0 | + * | 63-56 | 55-48 | 47-40 | 39-32 | 31-24 | 23-16 | 15-8 | 7-0 | | aFaE | aDaC | aBaA | a9a8 | a7a6 | a5a4 | a3a2 | + * a1a0 | * * @author dcollins * @version $Id: AlphaBlockDXT3.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AlphaBlockDXT3 -{ +public class AlphaBlockDXT3 { + /** * The 4x4 block of 4 bit alpha values stored as a 64 bit long number. */ @@ -27,12 +27,10 @@ public class AlphaBlockDXT3 /** * Creates a new DXT2/DXT3 alpha block with all alpha values set to 0. */ - public AlphaBlockDXT3() - { + public AlphaBlockDXT3() { } - public AlphaBlockDXT3(long alphaValueMask) - { + public AlphaBlockDXT3(long alphaValueMask) { this.alphaValueMask = alphaValueMask; } @@ -41,8 +39,7 @@ public AlphaBlockDXT3(long alphaValueMask) * * @return 4x4 block of 4 bit alpha values. */ - public long getAlphaValueMask() - { + public long getAlphaValueMask() { return this.alphaValueMask; } @@ -51,8 +48,7 @@ public long getAlphaValueMask() * * @param valueMask 4x4 block of 4 bit alpha values. */ - public void setAlphaValueMask(long valueMask) - { + public void setAlphaValueMask(long valueMask) { this.alphaValueMask = valueMask; } } diff --git a/src/gov/nasa/worldwind/formats/dds/BasicColorBlockExtractor.java b/src/gov/nasa/worldwind/formats/dds/BasicColorBlockExtractor.java index 447caacbdd..fd3f9bdbeb 100644 --- a/src/gov/nasa/worldwind/formats/dds/BasicColorBlockExtractor.java +++ b/src/gov/nasa/worldwind/formats/dds/BasicColorBlockExtractor.java @@ -13,43 +13,39 @@ * unpredictable behavior. Acces to methods of this class must be synchronized by the caller. * * @see java.awt.image.BufferedImage - * + * * @author dcollins * @version $Id: BasicColorBlockExtractor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicColorBlockExtractor implements ColorBlockExtractor -{ +public class BasicColorBlockExtractor implements ColorBlockExtractor { + protected int width; protected int height; protected java.awt.image.BufferedImage image; private int[] buffer; - protected static int[] remainder = - { - 0, 0, 0, 0, - 0, 1, 0, 1, - 0, 1, 2, 0, - 0, 1, 2, 3, - }; + protected static int[] remainder + = { + 0, 0, 0, 0, + 0, 1, 0, 1, + 0, 1, 2, 0, + 0, 1, 2, 3,}; /** - * Creates a BasicColorBlockExtrator which will draw its data from the BufferedImage. - * The BufferedImage may be of any type, so long as a call to image.getRGB() will - * succeed. + * Creates a BasicColorBlockExtrator which will draw its data from the BufferedImage. The + * BufferedImage may be of any type, so long as a call to image.getRGB() will succeed. * * @param image the image to draw data from. * * @throws IllegalArgumentException if image is null. */ - public BasicColorBlockExtractor(java.awt.image.BufferedImage image) - { - if (image == null) - { + public BasicColorBlockExtractor(java.awt.image.BufferedImage image) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - + this.width = image.getWidth(); this.height = image.getHeight(); this.image = image; @@ -61,21 +57,20 @@ public BasicColorBlockExtractor(java.awt.image.BufferedImage image) * * @return image data is drawn from. */ - public java.awt.image.BufferedImage getImage() - { + public java.awt.image.BufferedImage getImage() { return this.image; } /** * Extracts a 4x4 block of pixel data at the specified coordinate (x, y), and places the data in the - * specified colorBlock. If the coordinate (x, y) with the image, but the entire 4x4 - * block is not, this will either truncate the block to fit the image, or copy nearby pixels to fill the block. If - * the attributes specify that color components should be premultiplied by alpha, this extactor will + * specified colorBlock. If the coordinate (x, y) with the image, but the entire 4x4 block + * is not, this will either truncate the block to fit the image, or copy nearby pixels to fill the block. If the + * attributes specify that color components should be premultiplied by alpha, this extactor will * perform the premultiplication operation on the incoming colors. *

      - * Access to this method must be synchronized by the caller. This method is frequenty invoked by the DXT - * compressor, so in order to reduce garbage each instance of this class has unsynchronized properties that are - * reused during each call. + * Access to this method must be synchronized by the caller. This method is frequenty invoked by the DXT compressor, + * so in order to reduce garbage each instance of this class has unsynchronized properties that are reused during + * each call. * * @param attributes the DXT compression attributes which may affect how colors are accessed. * @param x horizontal coordinate origin to extract pixel data from. @@ -84,16 +79,13 @@ public java.awt.image.BufferedImage getImage() * * @throws IllegalArgumentException if either attributes or colorBlock is null. */ - public void extractColorBlock4x4(DXTCompressionAttributes attributes, int x, int y, ColorBlock4x4 colorBlock) - { - if (attributes == null) - { + public void extractColorBlock4x4(DXTCompressionAttributes attributes, int x, int y, ColorBlock4x4 colorBlock) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (colorBlock == null) - { + if (colorBlock == null) { String message = Logging.getMessage("nullValue.ColorBlockIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -101,7 +93,6 @@ public void extractColorBlock4x4(DXTCompressionAttributes attributes, int x, int // Image blocks that are smaller than 4x4 are handled by repeating the image pixels that intersect the // requested block range. - int bw = Math.min(this.width - x, 4); int bh = Math.min(this.height - y, 4); int bxOffset = 4 * (bw - 1); @@ -113,8 +104,7 @@ public void extractColorBlock4x4(DXTCompressionAttributes attributes, int x, int // 8888 ARGB int, where the color components are not considered to be premultiplied. this.image.getRGB(x, y, bw, bh, this.buffer, 0, 4); - for (int j = 0; j < 4; j++) - { + for (int j = 0; j < 4; j++) { by = remainder[byOffset + j]; bx = remainder[bxOffset]; @@ -130,17 +120,14 @@ public void extractColorBlock4x4(DXTCompressionAttributes attributes, int x, int int32ToColor32(this.buffer[bx + by * 4], colorBlock.color[blockPos++]); } - if (attributes.isPremultiplyAlpha()) - { - for (int i = 0; i < 16; i++) - { + if (attributes.isPremultiplyAlpha()) { + for (int i = 0; i < 16; i++) { premultiplyAlpha(colorBlock.color[i]); } } } - protected static void int32ToColor32(int int32, Color32 color) - { + protected static void int32ToColor32(int int32, Color32 color) { // Unpack a 32 bit 8888 ARGB integer into the destination color. The components are assumed to be tightly // packed in the integer as follows: // @@ -153,15 +140,13 @@ protected static void int32ToColor32(int int32, Color32 color) color.b = (0xFF & (int32)); } - protected static void premultiplyAlpha(Color32 color) - { + protected static void premultiplyAlpha(Color32 color) { color.r = div255(color.r * color.a); color.g = div255(color.g * color.a); color.b = div255(color.b * color.a); } - private static int div255(int a) - { + private static int div255(int a) { return (a + (a >> 8) + 128) >> 8; } } diff --git a/src/gov/nasa/worldwind/formats/dds/BlockDXT1.java b/src/gov/nasa/worldwind/formats/dds/BlockDXT1.java index d1cc04be6e..7c0b9cd3da 100644 --- a/src/gov/nasa/worldwind/formats/dds/BlockDXT1.java +++ b/src/gov/nasa/worldwind/formats/dds/BlockDXT1.java @@ -8,22 +8,22 @@ /** * BlockDXT1 is a data structure representing the compressed color values in a single 64 bit DXT1 block. * The DXT1 block contains two explicit 16 bit colors (quantized as RGB 565), which define one or two additional - * implicit colors. If the first color is greater than the second, then two additional colors are defined for a total - * of four. The two colors are defined as color2=(2*color0 + 1*color1)/3, and color3=(1*color0 + 2*color1)/3. If the - * first color is less than the second color, then one additional color is defined for a total of three colors, and the - * fourth color is interpreted as transparent black. Finally, the block contains 4x4 2 bit indices into the array of - * four colors (one of which may be transparent black). + * implicit colors. If the first color is greater than the second, then two additional colors are defined for a total of + * four. The two colors are defined as color2=(2*color0 + 1*color1)/3, and color3=(1*color0 + 2*color1)/3. If the first + * color is less than the second color, then one additional color is defined for a total of three colors, and the fourth + * color is interpreted as transparent black. Finally, the block contains 4x4 2 bit indices into the array of four + * colors (one of which may be transparent black). *

      - * From http://msdn.microsoft.com/en-us/library/bb204843(VS.85).aspx: - * If 64-bit blocks - that is, format DXT1 - are used for the texture, it is possible to mix the opaque and 1-bit alpha - * formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer - * magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels. + * From http://msdn.microsoft.com/en-us/library/bb204843(VS.85).aspx: If 64-bit blocks - that is, format DXT1 - are used + * for the texture, it is possible to mix the opaque and 1-bit alpha formats on a per-block basis within the same + * texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed + * uniquely for each block of 16 texels. * * @author dcollins * @version $Id: BlockDXT1.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BlockDXT1 -{ +public class BlockDXT1 { + /** * The first color stored as a 16 bit 565 RGB color. */ @@ -40,12 +40,10 @@ public class BlockDXT1 /** * Creates a new DXT1 color block with colors and indices set to 0. */ - public BlockDXT1() - { + public BlockDXT1() { } - public BlockDXT1(int color0, int color1, long colorIndexMask) - { + public BlockDXT1(int color0, int color1, long colorIndexMask) { this.color0 = color0; this.color1 = color1; this.colorIndexMask = colorIndexMask; @@ -56,8 +54,7 @@ public BlockDXT1(int color0, int color1, long colorIndexMask) * * @return 16 bit 565 RGB color. */ - public int getColor0() - { + public int getColor0() { return this.color0; } @@ -66,8 +63,7 @@ public int getColor0() * * @param color0 16 bit 565 RGB color. */ - public void setColor0(int color0) - { + public void setColor0(int color0) { this.color0 = color0; } @@ -76,8 +72,7 @@ public void setColor0(int color0) * * @return 16 bit 565 RGB color. */ - public int getColor1() - { + public int getColor1() { return this.color1; } @@ -86,8 +81,7 @@ public int getColor1() * * @param color1 16 bit 565 RGB color. */ - public void setColor1(int color1) - { + public void setColor1(int color1) { this.color1 = color1; } @@ -96,8 +90,7 @@ public void setColor1(int color1) * * @return 4x4 block of 2 bit indices. */ - public long getColorIndexMask() - { + public long getColorIndexMask() { return this.colorIndexMask; } @@ -106,8 +99,7 @@ public long getColorIndexMask() * * @param indexMask 4x4 block of 2 bit indices. */ - public void setColorIndexMask(long indexMask) - { + public void setColorIndexMask(long indexMask) { this.colorIndexMask = indexMask; } } diff --git a/src/gov/nasa/worldwind/formats/dds/BlockDXT1Compressor.java b/src/gov/nasa/worldwind/formats/dds/BlockDXT1Compressor.java index aaff2e34f9..e767710699 100644 --- a/src/gov/nasa/worldwind/formats/dds/BlockDXT1Compressor.java +++ b/src/gov/nasa/worldwind/formats/dds/BlockDXT1Compressor.java @@ -11,14 +11,13 @@ * Compressor for DXT1 color blocks. This class is not thread safe. Unsynchronized access will result in unpredictable * behavior. Access to methods of this class must be synchronized by the caller. *

      - * Documentation on the DXT1 format is available at http://msdn.microsoft.com/en-us/library/bb694531.aspx under - * the name "BC1". + * Documentation on the DXT1 format is available at http://msdn.microsoft.com/en-us/library/bb694531.aspx under the name + * "BC1". * * @author dcollins * @version $Id: BlockDXT1Compressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BlockDXT1Compressor -{ +public class BlockDXT1Compressor { // Implementation based on the paper "Real-Time DXT Compression" by J.M.P van Waveren // http://www.intel.com/cd/ids/developer/asmo-na/eng/324337.htm // and on the NVidia Texture Tools @@ -31,21 +30,19 @@ public class BlockDXT1Compressor /** * Creates a new DXT1 block compressor. */ - public BlockDXT1Compressor() - { + public BlockDXT1Compressor() { this.minColor = new Color32(); this.maxColor = new Color32(); this.palette = new Color32[4]; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { this.palette[i] = new Color32(); } } /** - * Compress the 4x4 color block into a DXT1 block using four colors. This method ignores transparency and - * guarantees that the DXT1 block will use four colors. + * Compress the 4x4 color block into a DXT1 block using four colors. This method ignores transparency and guarantees + * that the DXT1 block will use four colors. *

      * Access to this method must be synchronized by the caller. This method is frequently invoked by the DXT * compressor, so in order to reduce garbage each instance of this class has unsynchronized properties that are @@ -57,22 +54,18 @@ public BlockDXT1Compressor() * * @throws IllegalArgumentException if either colorBlock or dxtBlock are null. */ - public void compressBlockDXT1(ColorBlock4x4 colorBlock, DXTCompressionAttributes attributes, BlockDXT1 dxtBlock) - { - if (colorBlock == null) - { + public void compressBlockDXT1(ColorBlock4x4 colorBlock, DXTCompressionAttributes attributes, BlockDXT1 dxtBlock) { + if (colorBlock == null) { String message = Logging.getMessage("nullValue.ColorBlockIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dxtBlock == null) - { + if (dxtBlock == null) { String message = Logging.getMessage("nullValue.DXTBlockIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -82,8 +75,7 @@ public void compressBlockDXT1(ColorBlock4x4 colorBlock, DXTCompressionAttributes int color0 = short565FromColor32(this.maxColor); int color1 = short565FromColor32(this.minColor); - if (color0 < color1) - { + if (color0 < color1) { int tmp = color0; color0 = color1; color1 = tmp; @@ -107,25 +99,21 @@ public void compressBlockDXT1(ColorBlock4x4 colorBlock, DXTCompressionAttributes * @param colorBlock the 4x4 color block to compress. * @param attributes attributes that will control the compression. * @param dxtBlock the DXT1 block that will receive the compressed data. - * + * * @throws IllegalArgumentException if either colorBlock or dxtBlock are null. */ - public void compressBlockDXT1a(ColorBlock4x4 colorBlock, DXTCompressionAttributes attributes, BlockDXT1 dxtBlock) - { - if (colorBlock == null) - { + public void compressBlockDXT1a(ColorBlock4x4 colorBlock, DXTCompressionAttributes attributes, BlockDXT1 dxtBlock) { + if (colorBlock == null) { String message = Logging.getMessage("nullValue.ColorBlockIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dxtBlock == null) - { + if (dxtBlock == null) { String message = Logging.getMessage("nullValue.DXTBlockIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -135,8 +123,7 @@ public void compressBlockDXT1a(ColorBlock4x4 colorBlock, DXTCompressionAttribute int color0 = short565FromColor32(this.maxColor); int color1 = short565FromColor32(this.minColor); - if (color0 < color1) - { + if (color0 < color1) { int tmp = color0; color0 = color1; color1 = tmp; @@ -151,23 +138,17 @@ public void compressBlockDXT1a(ColorBlock4x4 colorBlock, DXTCompressionAttribute } protected void chooseMinMaxColors(ColorBlock4x4 block, DXTCompressionAttributes attributes, - Color32 minColor, Color32 maxColor) - { + Color32 minColor, Color32 maxColor) { //noinspection StringEquality - if (attributes.getColorBlockCompressionType() == DXTCompressionAttributes.COLOR_BLOCK_COMPRESSION_BBOX) - { + if (attributes.getColorBlockCompressionType() == DXTCompressionAttributes.COLOR_BLOCK_COMPRESSION_BBOX) { findMinMaxColorsBox(block, minColor, maxColor); selectDiagonal(block, minColor, maxColor); insetBox(minColor, maxColor); - } - else //noinspection StringEquality - if (attributes.getColorBlockCompressionType() == DXTCompressionAttributes.COLOR_BLOCK_COMPRESSION_EUCLIDEAN_DISTANCE) - { + } else //noinspection StringEquality + if (attributes.getColorBlockCompressionType() == DXTCompressionAttributes.COLOR_BLOCK_COMPRESSION_EUCLIDEAN_DISTANCE) { findMinMaxColorsEuclideanDistance(block, minColor, maxColor); - } - else //noinspection StringEquality - if (attributes.getColorBlockCompressionType() == DXTCompressionAttributes.COLOR_BLOCK_COMPRESSION_LUMINANCE_DISTANCE) - { + } else //noinspection StringEquality + if (attributes.getColorBlockCompressionType() == DXTCompressionAttributes.COLOR_BLOCK_COMPRESSION_LUMINANCE_DISTANCE) { // Default to using euclidean distance to compute the min and max palette colors. findMinMaxColorsLuminanceDistance(block, minColor, maxColor); } @@ -176,9 +157,7 @@ protected void chooseMinMaxColors(ColorBlock4x4 block, DXTCompressionAttributes //**************************************************************// //******************** Color Block Palette Assembly **********// //**************************************************************// - - protected static void computeColorPalette3(int color0, int color1, Color32[] palette) - { + protected static void computeColorPalette3(int color0, int color1, Color32[] palette) { // Assign 16 bit 565 values to the color palette. We want to find the closest match to the hardware computed // colors, and the hardware will be computing the colors using 16 bit 565 values. The second color is 1/2 on // the line between max and min. The third color is considered to be transparent black. Computations of the @@ -200,8 +179,7 @@ protected static void computeColorPalette3(int color0, int color1, Color32[] pal palette[3].b = 0; } - protected static void computeColorPalette4(int color0, int color1, Color32[] palette) - { + protected static void computeColorPalette4(int color0, int color1, Color32[] palette) { // Assign 16 bit 565 values to the color palette. We want to find the closest match to the hardware computed // colors, and the hardware will be computing the colors using 16 bit 565 values. The second color is 1/3 on // the line between max and min. The third color is 2/3 on the line between max and min. Computations of the @@ -223,8 +201,7 @@ protected static void computeColorPalette4(int color0, int color1, Color32[] pal } protected static long computePaletteIndices3(ColorBlock4x4 block, DXTCompressionAttributes attributes, - Color32[] palette) - { + Color32[] palette) { // This implementation is based on code available in the nvidia-texture-tools project: // http://code.google.com/p/nvidia-texture-tools/ // @@ -237,28 +214,19 @@ protected static long computePaletteIndices3(ColorBlock4x4 block, DXTCompression long mask = 0L; long index; - for (int i = 0; i < 16; i++) - { + for (int i = 0; i < 16; i++) { int d0 = colorDistanceSquared(palette[0], block.color[i]); int d1 = colorDistanceSquared(palette[1], block.color[i]); int d2 = colorDistanceSquared(palette[2], block.color[i]); // TODO: implement bit twiddle as in computePaletteIndex4 to avoid conditional branching - - if (block.color[i].a < alphaThreshold) - { + if (block.color[i].a < alphaThreshold) { index = 3; - } - else if (d0 < d1 && d0 < d2) - { + } else if (d0 < d1 && d0 < d2) { index = 0; - } - else if (d1 < d2) - { + } else if (d1 < d2) { index = 1; - } - else - { + } else { index = 2; } @@ -268,8 +236,7 @@ else if (d1 < d2) return mask; } - protected static long computePaletteIndices4(ColorBlock4x4 block, Color32[] palette) - { + protected static long computePaletteIndices4(ColorBlock4x4 block, Color32[] palette) { // This implementation is based on the paper by J.M.P. van Waveren: // http://cache-www.intel.com/cd/00/00/32/43/324337_324337.pdf // @@ -281,8 +248,7 @@ protected static long computePaletteIndices4(ColorBlock4x4 block, Color32[] pale long mask = 0L; long index; - for (int i = 0; i < 16; i++) - { + for (int i = 0; i < 16; i++) { int d0 = colorDistanceSquared(palette[0], block.color[i]); int d1 = colorDistanceSquared(palette[1], block.color[i]); int d2 = colorDistanceSquared(palette[2], block.color[i]); @@ -293,7 +259,7 @@ protected static long computePaletteIndices4(ColorBlock4x4 block, Color32[] pale int b2 = greaterThan(d0, d2); int b3 = greaterThan(d1, d3); int b4 = greaterThan(d2, d3); - + int x0 = b1 & b2; int x1 = b0 & b3; int x2 = b0 & b4; @@ -309,29 +275,24 @@ protected static long computePaletteIndices4(ColorBlock4x4 block, Color32[] pale //**************************************************************// //******************** Color Block Box Fitting ***************// //**************************************************************// - - protected static void findMinMaxColorsBox(ColorBlock4x4 block, Color32 minColor, Color32 maxColor) - { + protected static void findMinMaxColorsBox(ColorBlock4x4 block, Color32 minColor, Color32 maxColor) { minColor.r = minColor.g = minColor.b = 255; maxColor.r = maxColor.g = maxColor.b = 0; - for (int i = 0; i < 16; i++) - { + for (int i = 0; i < 16; i++) { minColorComponents(minColor, block.color[i], minColor); maxColorComponents(maxColor, block.color[i], maxColor); } } - protected static void selectDiagonal(ColorBlock4x4 block, Color32 minColor, Color32 maxColor) - { + protected static void selectDiagonal(ColorBlock4x4 block, Color32 minColor, Color32 maxColor) { int centerR = (minColor.r + maxColor.r) / 2; int centerG = (minColor.g + maxColor.g) / 2; int centerB = (minColor.b + maxColor.b) / 2; int cvx = 0; int cvy = 0; - for (int i = 0; i < 16; i++) - { + for (int i = 0; i < 16; i++) { int tx = block.color[i].r - centerR; int ty = block.color[i].g - centerG; int tz = block.color[i].b - centerB; @@ -345,15 +306,13 @@ protected static void selectDiagonal(ColorBlock4x4 block, Color32 minColor, Colo int x1 = maxColor.r; int y1 = maxColor.g; - if (cvx < 0) - { + if (cvx < 0) { int tmp = x0; x0 = x1; x1 = tmp; } - if (cvy < 0) - { + if (cvy < 0) { int tmp = y0; y0 = y1; y1 = tmp; @@ -365,8 +324,7 @@ protected static void selectDiagonal(ColorBlock4x4 block, Color32 minColor, Colo maxColor.g = y1; } - protected static void insetBox(Color32 minColor, Color32 maxColor) - { + protected static void insetBox(Color32 minColor, Color32 maxColor) { int insetR = (maxColor.r - minColor.r) >> 4; int insetG = (maxColor.g - minColor.g) >> 4; int insetB = (maxColor.b - minColor.b) >> 4; @@ -383,20 +341,15 @@ protected static void insetBox(Color32 minColor, Color32 maxColor) //**************************************************************// //******************** Color Block Euclidean Distance ********// //**************************************************************// - - protected static void findMinMaxColorsEuclideanDistance(ColorBlock4x4 block, Color32 minColor, Color32 maxColor) - { + protected static void findMinMaxColorsEuclideanDistance(ColorBlock4x4 block, Color32 minColor, Color32 maxColor) { double maxDistance = -1.0; int minIndex = 0; int maxIndex = 0; - - for (int i = 0; i < 15; i++) - { - for (int j = i + 1; j < 16; j++) - { + + for (int i = 0; i < 15; i++) { + for (int j = i + 1; j < 16; j++) { double d = colorDistanceSquared(block.color[i], block.color[j]); - if (d > maxDistance) - { + if (d > maxDistance) { minIndex = i; maxIndex = j; maxDistance = d; @@ -411,24 +364,19 @@ protected static void findMinMaxColorsEuclideanDistance(ColorBlock4x4 block, Col //**************************************************************// //******************** Color Block Luminance Distance ********// //**************************************************************// - - protected static void findMinMaxColorsLuminanceDistance(ColorBlock4x4 block, Color32 minColor, Color32 maxColor) - { + protected static void findMinMaxColorsLuminanceDistance(ColorBlock4x4 block, Color32 minColor, Color32 maxColor) { int minLuminance = Integer.MAX_VALUE; int maxLuminance = -1; int minIndex = 0; int maxIndex = 0; - for (int i = 0; i < 16; i++) - { + for (int i = 0; i < 16; i++) { int luminance = colorLuminance(block.color[i]); - if (luminance < minLuminance) - { + if (luminance < minLuminance) { minIndex = i; minLuminance = luminance; } - if (luminance > maxLuminance) - { + if (luminance > maxLuminance) { maxIndex = i; maxLuminance = luminance; } @@ -441,9 +389,7 @@ protected static void findMinMaxColorsLuminanceDistance(ColorBlock4x4 block, Col //**************************************************************// //******************** Color Arithmetic **********************// //**************************************************************// - - protected static int short565FromColor32(Color32 color) - { + protected static int short565FromColor32(Color32 color) { // Quantize a 32 bit RGB color to a 16 bit 565 RGB color. Taken from an algorithm shared on the Molly Rocket // forum by member "ryg": // https://mollyrocket.com/forums/viewtopic.php?t=392 @@ -451,8 +397,7 @@ protected static int short565FromColor32(Color32 color) return (mul8bit(color.r, 31) << 11) + (mul8bit(color.g, 63) << 5) + (mul8bit(color.b, 31)); } - protected static void short565ToColor32(int color16, Color32 color) - { + protected static void short565ToColor32(int color16, Color32 color) { // Dequantize a 16 bit 565 RGB color to a 32 bit RGB color. Taken from an algorithm shared on the Molly Rocket // forum by member "ryg": // https://mollyrocket.com/forums/viewtopic.php?t=392 @@ -467,50 +412,43 @@ protected static void short565ToColor32(int color16, Color32 color) color.b = (b << 3) | (b >> 2); } - private static int mul8bit(int a, int b) - { + private static int mul8bit(int a, int b) { int t = a * b + 128; return (t + (t >> 8)) >> 8; } - protected static int colorLuminance(Color32 c) - { + protected static int colorLuminance(Color32 c) { return c.r + c.g + 2 * c.b; } - protected static int colorDistanceSquared(Color32 c1, Color32 c2) - { + protected static int colorDistanceSquared(Color32 c1, Color32 c2) { return (c1.r - c2.r) * (c1.r - c2.r) - + (c1.g - c2.g) * (c1.g - c2.g) - + (c1.b - c2.b) * (c1.b - c2.b); + + (c1.g - c2.g) * (c1.g - c2.g) + + (c1.b - c2.b) * (c1.b - c2.b); } - protected static void maxColorComponents(Color32 c1, Color32 c2, Color32 max) - { + protected static void maxColorComponents(Color32 c1, Color32 c2, Color32 max) { max.a = (c1.a > c2.a) ? c1.a : c2.a; max.r = (c1.r > c2.r) ? c1.r : c2.r; max.g = (c1.g > c2.g) ? c1.g : c2.g; max.b = (c1.b > c2.b) ? c1.b : c2.b; } - protected static void minColorComponents(Color32 c1, Color32 c2, Color32 min) - { + protected static void minColorComponents(Color32 c1, Color32 c2, Color32 min) { min.a = (c1.a > c2.a) ? c2.a : c1.a; min.r = (c1.r > c2.r) ? c2.r : c1.r; min.g = (c1.g > c2.g) ? c2.g : c1.g; min.b = (c1.b > c2.b) ? c2.b : c1.b; } - protected static void copyColorComponents(Color32 src, Color32 dest) - { + protected static void copyColorComponents(Color32 src, Color32 dest) { dest.a = src.a; dest.r = src.r; dest.g = src.g; dest.b = src.b; } - protected static int greaterThan(int a, int b) - { + protected static int greaterThan(int a, int b) { // Exploit the properties of Java's two's complement integer to quickly return a binary value representing // whether or not a is greater than b. If a is greater than b, than b-a will be a negative value, and the // 32nd bit will be a one. Otherwise, b-a will be a positive value or zero, and the 32nd bit will be a zero. diff --git a/src/gov/nasa/worldwind/formats/dds/BlockDXT3.java b/src/gov/nasa/worldwind/formats/dds/BlockDXT3.java index 67c54d959e..a20f186cb2 100644 --- a/src/gov/nasa/worldwind/formats/dds/BlockDXT3.java +++ b/src/gov/nasa/worldwind/formats/dds/BlockDXT3.java @@ -8,17 +8,17 @@ /** * BlockDXT3 is a data structure representing the compressed alpha and color values in a single DXT2/DXT3 * block. The DXT3 block contains a 64 bit alpha block, and a 64 bit color block, stored here as the properties - * alphaBlock and colorBlock. The 64 bit alpha block contains 4x4 alpha values quantized - * into 4 bits. The 64 bit color block is formatted exactly like the DXT1 color block, except that the color block - * always represents four colors, regardless of the color ordering in the DXT1 block. + * alphaBlock and colorBlock. The 64 bit alpha block contains 4x4 alpha values quantized into + * 4 bits. The 64 bit color block is formatted exactly like the DXT1 color block, except that the color block always + * represents four colors, regardless of the color ordering in the DXT1 block. * * @author dcollins * @version $Id: BlockDXT3.java 1171 2013-02-11 21:45:02Z dcollins $ * @see AlphaBlockDXT3 * @see BlockDXT1 */ -public class BlockDXT3 -{ +public class BlockDXT3 { + /** * The DXT2/DXT3 alpha block. */ @@ -31,14 +31,12 @@ public class BlockDXT3 /** * Creates a new DXT2/DXT3 alpha block with all alpha and color values set to 0. */ - public BlockDXT3() - { + public BlockDXT3() { this.alphaBlock = new AlphaBlockDXT3(); this.colorBlock = new BlockDXT1(); } - public BlockDXT3(long alphaValueMask, int color0, int color1, long colorIndexMask) - { + public BlockDXT3(long alphaValueMask, int color0, int color1, long colorIndexMask) { this.alphaBlock = new AlphaBlockDXT3(alphaValueMask); this.colorBlock = new BlockDXT1(color0, color1, colorIndexMask); } @@ -48,8 +46,7 @@ public BlockDXT3(long alphaValueMask, int color0, int color1, long colorIndexMas * * @return DXT2/DXT3 alpha block. */ - public AlphaBlockDXT3 getAlphaBlock() - { + public AlphaBlockDXT3 getAlphaBlock() { return this.alphaBlock; } @@ -58,8 +55,7 @@ public AlphaBlockDXT3 getAlphaBlock() * * @param alphaBlock DXT2/DXT3 alpha block. */ - public void setAlphaBlock(AlphaBlockDXT3 alphaBlock) - { + public void setAlphaBlock(AlphaBlockDXT3 alphaBlock) { this.alphaBlock = alphaBlock; } @@ -68,8 +64,7 @@ public void setAlphaBlock(AlphaBlockDXT3 alphaBlock) * * @return DXT1 color block. */ - public BlockDXT1 getColorBlock() - { + public BlockDXT1 getColorBlock() { return this.colorBlock; } @@ -78,8 +73,7 @@ public BlockDXT1 getColorBlock() * * @param colorBlock DXT1 color block. */ - public void setColorBlock(BlockDXT1 colorBlock) - { + public void setColorBlock(BlockDXT1 colorBlock) { this.colorBlock = colorBlock; } } diff --git a/src/gov/nasa/worldwind/formats/dds/BlockDXT3Compressor.java b/src/gov/nasa/worldwind/formats/dds/BlockDXT3Compressor.java index 2143792f82..fcd1265208 100644 --- a/src/gov/nasa/worldwind/formats/dds/BlockDXT3Compressor.java +++ b/src/gov/nasa/worldwind/formats/dds/BlockDXT3Compressor.java @@ -11,14 +11,13 @@ * Compressor for DXT2/DXT3 alpha and color blocks. This class is not thread safe. Unsynchronized access will result in * unpredictable behavior. Access to methods of this class must be synchronized by the caller. *

      - * Documentation on the DXT2/DXT3 format is available at http://msdn.microsoft.com/en-us/library/bb694531.aspx under - * the name "BC2". + * Documentation on the DXT2/DXT3 format is available at http://msdn.microsoft.com/en-us/library/bb694531.aspx under the + * name "BC2". * * @author dcollins * @version $Id: BlockDXT3Compressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BlockDXT3Compressor -{ +public class BlockDXT3Compressor { // Implementation based on the NVidia Texture Tools // http://code.google.com/p/nvidia-texture-tools/ @@ -27,8 +26,7 @@ public class BlockDXT3Compressor /** * Creates a new DXT2/DXT3 block compressor. */ - public BlockDXT3Compressor() - { + public BlockDXT3Compressor() { this.dxt1Compressor = new BlockDXT1Compressor(); } @@ -43,25 +41,21 @@ public BlockDXT3Compressor() * * @param colorBlock the 4x4 color block to compress. * @param attributes attributes that will control the compression. - * @param dxtBlock the DXT2/DXT3 block that will receive the compressed data. + * @param dxtBlock the DXT2/DXT3 block that will receive the compressed data. * @throws IllegalArgumentException if either colorBlock or dxtBlock are null. */ - public void compressBlockDXT3(ColorBlock4x4 colorBlock, DXTCompressionAttributes attributes, BlockDXT3 dxtBlock) - { - if (colorBlock == null) - { + public void compressBlockDXT3(ColorBlock4x4 colorBlock, DXTCompressionAttributes attributes, BlockDXT3 dxtBlock) { + if (colorBlock == null) { String message = Logging.getMessage("nullValue.ColorBlockIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dxtBlock == null) - { + if (dxtBlock == null) { String message = Logging.getMessage("nullValue.DXTBlockIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,17 +70,14 @@ public void compressBlockDXT3(ColorBlock4x4 colorBlock, DXTCompressionAttributes this.compressBlockDXT3a(colorBlock, dxtBlock.alphaBlock); } - protected void compressBlockDXT3a(ColorBlock4x4 colorBlock, AlphaBlockDXT3 dxtBlock) - { + protected void compressBlockDXT3a(ColorBlock4x4 colorBlock, AlphaBlockDXT3 dxtBlock) { dxtBlock.alphaValueMask = computeAlphaValueMask(colorBlock); } //**************************************************************// //******************** Alpha Block Assembly ******************// //**************************************************************// - - protected static long computeAlphaValueMask(ColorBlock4x4 colorBlock) - { + protected static long computeAlphaValueMask(ColorBlock4x4 colorBlock) { // Alpha is encoded as 4 bit values. Each pair of values will be packed into one byte. The first value goes // in bits 0-4, and the second value goes in bits 5-8. The resultant 64 bit value is structured so that when // converted to little endian ordering, the alpha values will be in the correct order. Here's what the @@ -98,8 +89,7 @@ protected static long computeAlphaValueMask(ColorBlock4x4 colorBlock) long bitmask = 0L; - for (int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { int a0 = 0xF & alpha4FromAlpha8(colorBlock.color[2 * i].a); int a1 = 0xF & alpha4FromAlpha8(colorBlock.color[2 * i + 1].a); long mask10 = (a1 << 4) | a0; @@ -112,9 +102,7 @@ protected static long computeAlphaValueMask(ColorBlock4x4 colorBlock) //**************************************************************// //******************** Alpha Arithmetic **********************// //**************************************************************// - - protected static int alpha4FromAlpha8(int alpha8) - { + protected static int alpha4FromAlpha8(int alpha8) { // Quantizes an 8 bit alpha value into 4 bits. To reduce rounding error, this will compare the three nearest // 4 bit values and choose the closest one. @@ -130,19 +118,16 @@ protected static int alpha4FromAlpha8(int alpha8) int d1 = alphaDistanceSquared(q1, alpha8); int d2 = alphaDistanceSquared(q2, alpha8); - if (d0 < d1 && d0 < d2) - { + if (d0 < d1 && d0 < d2) { return q0 >> 4; } - if (d1 < d2) - { + if (d1 < d2) { return q1 >> 4; } return q2 >> 4; } - protected static int alphaDistanceSquared(int a0, int a1) - { + protected static int alphaDistanceSquared(int a0, int a1) { return (a0 - a1) * (a0 - a1); } } diff --git a/src/gov/nasa/worldwind/formats/dds/Color24.java b/src/gov/nasa/worldwind/formats/dds/Color24.java index 80eafe9b3e..2f555684e5 100644 --- a/src/gov/nasa/worldwind/formats/dds/Color24.java +++ b/src/gov/nasa/worldwind/formats/dds/Color24.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.dds; /** @@ -12,9 +11,8 @@ * @author Lado Garakanidze * @version $Id: Color24.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class Color24 { -public class Color24 -{ /** * The red color component. */ @@ -31,25 +29,21 @@ public class Color24 /** * Creates a 24 bit 888 RGB color with all values set to 0. */ - public Color24() - { + public Color24() { this.r = this.g = this.b = 0; } - public Color24(int r, int g, int b) - { + public Color24(int r, int g, int b) { this.r = r; this.g = g; this.b = b; } - public int getPixel888() - { + public int getPixel888() { return (this.r << 16 | this.g << 8 | this.b); } - public static Color24 fromPixel565(int pixel) - { + public static Color24 fromPixel565(int pixel) { Color24 color = new Color24(); color.r = (int) (((long) pixel) & 0xf800) >>> 8; @@ -59,8 +53,7 @@ public static Color24 fromPixel565(int pixel) return color; } - public static Color24 multiplyAlpha(Color24 color, int alpha) - { + public static Color24 multiplyAlpha(Color24 color, int alpha) { Color24 result = new Color24(); double alphaF = alpha / 256.0; @@ -72,8 +65,7 @@ public static Color24 multiplyAlpha(Color24 color, int alpha) return result; } - public static Color24[] expandLookupTable(short minColor, short maxColor) - { + public static Color24[] expandLookupTable(short minColor, short maxColor) { Color24 colorMin = Color24.fromPixel565(minColor); Color24 colorMax = Color24.fromPixel565(maxColor); diff --git a/src/gov/nasa/worldwind/formats/dds/Color32.java b/src/gov/nasa/worldwind/formats/dds/Color32.java index 6107fa0818..c3bbb7a199 100644 --- a/src/gov/nasa/worldwind/formats/dds/Color32.java +++ b/src/gov/nasa/worldwind/formats/dds/Color32.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: Color32.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Color32 extends Color24 -{ +public class Color32 extends Color24 { + /** * The alpha component. */ @@ -21,22 +21,18 @@ public class Color32 extends Color24 /** * Creates a 32 bit 8888 ARGB color with all values set to 0. */ - public Color32() - { + public Color32() { super(); this.a = 0; } - public Color32(int a, int r, int g, int b) - { + public Color32(int a, int r, int g, int b) { super(r, g, b); this.a = a; } - public static Color32 multiplyAlpha(Color32 color) - { - if (null == color) - { + public static Color32 multiplyAlpha(Color32 color) { + if (null == color) { return null; } diff --git a/src/gov/nasa/worldwind/formats/dds/ColorBlock4x4.java b/src/gov/nasa/worldwind/formats/dds/ColorBlock4x4.java index 0462b68a5e..93bcc473de 100644 --- a/src/gov/nasa/worldwind/formats/dds/ColorBlock4x4.java +++ b/src/gov/nasa/worldwind/formats/dds/ColorBlock4x4.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: ColorBlock4x4.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ColorBlock4x4 -{ +public class ColorBlock4x4 { + /** * The 4x4 color values stored as an array of length 16. This property is publicly exposed, so its contents are * mutable. It is declared final to prevent a caller form reassigning the array reference. @@ -20,13 +20,11 @@ public class ColorBlock4x4 public final Color32[] color = new Color32[16]; /** - * Creates a 4x4 color block with the color values initialized to non-null references. - * Initially all color values are set to 0. + * Creates a 4x4 color block with the color values initialized to non-null references. Initially all color values + * are set to 0. */ - public ColorBlock4x4() - { - for (int i = 0; i < 16; i++) - { + public ColorBlock4x4() { + for (int i = 0; i < 16; i++) { this.color[i] = new Color32(); } } @@ -37,8 +35,7 @@ public ColorBlock4x4() * @param index the color index to return. * @return color value at the index. */ - public Color32 getColor(int index) - { + public Color32 getColor(int index) { return this.color[index]; } @@ -48,8 +45,7 @@ public Color32 getColor(int index) * @param index the color index to set. * @param color new color value at the specified index. */ - public void setColor(int index, Color32 color) - { + public void setColor(int index, Color32 color) { this.color[index] = color; } } diff --git a/src/gov/nasa/worldwind/formats/dds/ColorBlockExtractor.java b/src/gov/nasa/worldwind/formats/dds/ColorBlockExtractor.java index 069029915c..1336a4f758 100644 --- a/src/gov/nasa/worldwind/formats/dds/ColorBlockExtractor.java +++ b/src/gov/nasa/worldwind/formats/dds/ColorBlockExtractor.java @@ -15,12 +15,12 @@ * @author dcollins * @version $Id: ColorBlockExtractor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface ColorBlockExtractor -{ +public interface ColorBlockExtractor { + /** * Extracts a 4x4 block of pixel data at the specified coordinate (x, y), and places the data in the - * specified colorBlock. If the coordinate (x, y) with the image, but the entire 4x4 - * block is not, this will either truncate the block to fit the image, or copy nearby pixels to fill the block. + * specified colorBlock. If the coordinate (x, y) with the image, but the entire 4x4 block + * is not, this will either truncate the block to fit the image, or copy nearby pixels to fill the block. * * @param attributes the DXT compression attributes which may affect how colors are accessed. * @param x horizontal coordinate origin to extract pixel data from. diff --git a/src/gov/nasa/worldwind/formats/dds/DDSCompressor.java b/src/gov/nasa/worldwind/formats/dds/DDSCompressor.java index 87fabdf718..5324e1a6fa 100644 --- a/src/gov/nasa/worldwind/formats/dds/DDSCompressor.java +++ b/src/gov/nasa/worldwind/formats/dds/DDSCompressor.java @@ -21,11 +21,12 @@ * @author dcollins * @version $Id: DDSCompressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DDSCompressor -{ - /** Creates a new DDSCompressor, but otherwise does nothing. */ - public DDSCompressor() - { +public class DDSCompressor { + + /** + * Creates a new DDSCompressor, but otherwise does nothing. + */ + public DDSCompressor() { } /** @@ -37,35 +38,31 @@ public DDSCompressor() * stream is not in a format understood by ImageIO. * * @param inputStream image stream to convert to the DDS file format. - * @param attributes attributes that control the compression. + * @param attributes attributes that control the compression. * * @return little endian ordered ByteBuffer containing the DDS file bytes, or null if the stream is not - * in a format understood by ImageIO. + * in a format understood by ImageIO. * - * @throws java.io.IOException if stream is in a format understood by ImageIO, but the image data - * cannot be read by ImageIO. + * @throws java.io.IOException if stream is in a format understood by ImageIO, but the image data + * cannot be read by ImageIO. * @throws IllegalArgumentException if either the stream or the attributes are null. */ public static java.nio.ByteBuffer compressImageStream(java.io.InputStream inputStream, - DXTCompressionAttributes attributes) throws java.io.IOException - { - if (inputStream == null) - { + DXTCompressionAttributes attributes) throws java.io.IOException { + if (inputStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(inputStream); - if (image == null) - { + if (image == null) { return null; } @@ -83,16 +80,14 @@ public static java.nio.ByteBuffer compressImageStream(java.io.InputStream inputS * @param inputStream image stream to convert to the DDS file format. * * @return little endian ordered ByteBuffer containing the DDS file bytes, or null if the stream is not - * in a format understood by ImageIO. + * in a format understood by ImageIO. * - * @throws java.io.IOException if stream is in a format understood by ImageIO, but the image data - * cannot be read by ImageIO. + * @throws java.io.IOException if stream is in a format understood by ImageIO, but the image data + * cannot be read by ImageIO. * @throws IllegalArgumentException if stream is null. */ - public static java.nio.ByteBuffer compressImageStream(java.io.InputStream inputStream) throws java.io.IOException - { - if (inputStream == null) - { + public static java.nio.ByteBuffer compressImageStream(java.io.InputStream inputStream) throws java.io.IOException { + if (inputStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,27 +105,24 @@ public static java.nio.ByteBuffer compressImageStream(java.io.InputStream inputS * imageBuffer are not in a format understood by ImageIO. * * @param imageBuffer image file data to convert to the DDS file format. - * @param attributes attributes that control the compression. + * @param attributes attributes that control the compression. * * @return little endian ordered ByteBuffer containing the DDS file bytes, or null if the imageBuffer - * is not in a format understood by ImageIO. + * is not in a format understood by ImageIO. * - * @throws java.io.IOException if the bytes in imageBuffer are in a format understood by ImageIO, - * but the image data cannot be read by ImageIO. + * @throws java.io.IOException if the bytes in imageBuffer are in a format understood by ImageIO, but + * the image data cannot be read by ImageIO. * @throws IllegalArgumentException if either imageBuffer or attributes are null. */ public static java.nio.ByteBuffer compressImageBuffer(java.nio.ByteBuffer imageBuffer, - DXTCompressionAttributes attributes) throws java.io.IOException - { - if (imageBuffer == null) - { + DXTCompressionAttributes attributes) throws java.io.IOException { + if (imageBuffer == null) { String message = Logging.getMessage("nullValue.Image"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -142,24 +134,22 @@ public static java.nio.ByteBuffer compressImageBuffer(java.nio.ByteBuffer imageB /** * Convenience method to convert the specified imageBuffer to DDS according to the default attributes. - * The bytes in imageBuffer must be readable by {@link javax.imageio.ImageIO#read(java.io.InputStream)}. - * Once the image data is read, this is equivalent to calling {#compressImage(java.awt.image.BufferedImage)} with - * the BufferedImage created by ImageIO. This returns null if the bytes inimageBuffer are not in a - * format understood by ImageIO. + * The bytes in imageBuffer must be readable by + * {@link javax.imageio.ImageIO#read(java.io.InputStream)}. Once the image data is read, this is equivalent to + * calling {#compressImage(java.awt.image.BufferedImage)} with the BufferedImage created by ImageIO. This returns + * null if the bytes inimageBuffer are not in a format understood by ImageIO. * * @param imageBuffer image file data to convert to the DDS file format. * * @return little endian ordered ByteBuffer containing the DDS file bytes, or null if the imageBuffer - * is not in a format understood by ImageIO. + * is not in a format understood by ImageIO. * - * @throws java.io.IOException if the bytes in imageBuffer are in a format understood by ImageIO, - * but the image data cannot be read by ImageIO. + * @throws java.io.IOException if the bytes in imageBuffer are in a format understood by ImageIO, but + * the image data cannot be read by ImageIO. * @throws IllegalArgumentException if imageBuffer is null. */ - public static java.nio.ByteBuffer compressImageBuffer(java.nio.ByteBuffer imageBuffer) throws java.io.IOException - { - if (imageBuffer == null) - { + public static java.nio.ByteBuffer compressImageBuffer(java.nio.ByteBuffer imageBuffer) throws java.io.IOException { + if (imageBuffer == null) { String message = Logging.getMessage("nullValue.Image"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -170,51 +160,45 @@ public static java.nio.ByteBuffer compressImageBuffer(java.nio.ByteBuffer imageB /** * Convenience method to convert the specified image file to DDS according to the specified compression - * attributes. The file must be readable by {@link javax.imageio.ImageIO#read(java.io.File)}. - * Once the file is read, this is equivalent to calling {#compressImage(java.awt.image.BufferedImage, - * gov.nasa.worldwind.formats.dds.DXTCompressionAttributes)} with the BufferedImage created by ImageIO and the - * specified attributes This returns null if the file is not in a format understood by - * ImageIO. + * attributes. The file must be readable by + * {@link javax.imageio.ImageIO#read(java.io.File)}. Once the file is read, this is equivalent to calling + * {#compressImage(java.awt.image.BufferedImage, gov.nasa.worldwind.formats.dds.DXTCompressionAttributes)} with the + * BufferedImage created by ImageIO and the specified attributes This returns null if the + * file is not in a format understood by ImageIO. * - * @param file image file to convert to the DDS file format. + * @param file image file to convert to the DDS file format. * @param attributes attributes that control the compression. * * @return little endian ordered ByteBuffer containing the DDS file bytes, or null if the file is not - * in a format understood by ImageIO. + * in a format understood by ImageIO. * - * @throws java.io.IOException if file is in a format understood by ImageIO, but the image data - * cannot be read by ImageIO. + * @throws java.io.IOException if file is in a format understood by ImageIO, but the image data cannot + * be read by ImageIO. * @throws IllegalArgumentException if either the file or the attributes are null, if the - * file does not exist, or if read permission is not allowed on the - * file. + * file does not exist, or if read permission is not allowed on the file. */ public static java.nio.ByteBuffer compressImageFile(java.io.File file, DXTCompressionAttributes attributes) - throws java.io.IOException - { - if (file == null) - { + throws java.io.IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists() || !file.canRead()) - { + if (!file.exists() || !file.canRead()) { String message = Logging.getMessage("DDSConverter.NoFileOrNoPermission"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(file); - if (image == null) - { + if (image == null) { return null; } @@ -231,24 +215,21 @@ public static java.nio.ByteBuffer compressImageFile(java.io.File file, DXTCompre * @param file image file to convert to the DDS file format. * * @return little endian ordered ByteBuffer containing the DDS file bytes, or null if the file is not - * in a format understood by ImageIO. + * in a format understood by ImageIO. * - * @throws java.io.IOException if file is in a format understood by ImageIO, but the image data - * cannot be read by ImageIO. + * @throws java.io.IOException if file is in a format understood by ImageIO, but the image data cannot + * be read by ImageIO. * @throws IllegalArgumentException if file is null, does not exist, or read permission is not allowed - * on the file. + * on the file. */ - public static java.nio.ByteBuffer compressImageFile(java.io.File file) throws java.io.IOException - { - if (file == null) - { + public static java.nio.ByteBuffer compressImageFile(java.io.File file) throws java.io.IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists() || !file.canRead()) - { + if (!file.exists() || !file.canRead()) { String message = Logging.getMessage("DDSConverter.NoFileOrNoPermission"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -259,42 +240,38 @@ public static java.nio.ByteBuffer compressImageFile(java.io.File file) throws ja /** * Convenience method to convert the specified image url to DDS according to the specified compression - * attributes. The url must be readable by {@link javax.imageio.ImageIO#read(java.net.URL)}. - * Once the url is read, this is equivalent to calling {#compressImage(java.awt.image.BufferedImage, - * gov.nasa.worldwind.formats.dds.DXTCompressionAttributes)} with the BufferedImage created by ImageIO and the - * specified attributes This returns null if the url is not in a format understood by - * ImageIO. + * attributes. The url must be readable by + * {@link javax.imageio.ImageIO#read(java.net.URL)}. Once the url is read, this is equivalent to + * calling {#compressImage(java.awt.image.BufferedImage, gov.nasa.worldwind.formats.dds.DXTCompressionAttributes)} + * with the BufferedImage created by ImageIO and the specified attributes This returns null if the + * url is not in a format understood by ImageIO. * - * @param url image URL to convert to the DDS file format. + * @param url image URL to convert to the DDS file format. * @param attributes attributes that control the compression. * * @return little endian ordered ByteBuffer containing the DDS file bytes, or null if the url is not in - * a format understood by ImageIO. + * a format understood by ImageIO. * - * @throws java.io.IOException if url is in a format understood by ImageIO, but the image data - * cannot be read by ImageIO. + * @throws java.io.IOException if url is in a format understood by ImageIO, but the image data cannot + * be read by ImageIO. * @throws IllegalArgumentException if either the url or the attributes are null. */ public static java.nio.ByteBuffer compressImageURL(java.net.URL url, DXTCompressionAttributes attributes) - throws java.io.IOException - { - if (url == null) - { + throws java.io.IOException { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(url); - if (image == null) - { + if (image == null) { return null; } @@ -312,16 +289,14 @@ public static java.nio.ByteBuffer compressImageURL(java.net.URL url, DXTCompress * @param url image URL to convert to the DDS file format. * * @return little endian ordered ByteBuffer containing the DDS file bytes, or null if the url is not in - * a format understood by ImageIO. + * a format understood by ImageIO. * - * @throws java.io.IOException if url is in a format understood by ImageIO, but the image data - * cannot be read by ImageIO. + * @throws java.io.IOException if url is in a format understood by ImageIO, but the image data cannot + * be read by ImageIO. * @throws IllegalArgumentException if url is null. */ - public static java.nio.ByteBuffer compressImageURL(java.net.URL url) throws java.io.IOException - { - if (url == null) - { + public static java.nio.ByteBuffer compressImageURL(java.net.URL url) throws java.io.IOException { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -339,18 +314,15 @@ public static java.nio.ByteBuffer compressImageURL(java.net.URL url) throws java * @return little endian ordered ByteBuffer containing the dds file bytes. * * @throws IllegalArgumentException if image is null, or if image has non power of two - * dimensions. + * dimensions. */ - public static java.nio.ByteBuffer compressImage(java.awt.image.BufferedImage image) - { - if (image == null) - { + public static java.nio.ByteBuffer compressImage(java.awt.image.BufferedImage image) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!WWMath.isPowerOfTwo(image.getWidth()) || !WWMath.isPowerOfTwo(image.getHeight())) - { + if (!WWMath.isPowerOfTwo(image.getWidth()) || !WWMath.isPowerOfTwo(image.getHeight())) { String message = Logging.getMessage("generic.InvalidImageSize", image.getWidth(), image.getHeight()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -363,15 +335,15 @@ public static java.nio.ByteBuffer compressImage(java.awt.image.BufferedImage ima /** * Returns the default compression attributes. The default DXT compression attributes are defined as follows: - * + *
      Default Attributes
      AttributeValue
      Build Mipmapstrue
      + * *
      Default Attributes
      AttributeValue
      Build Mipmapstrue
      Premultiply Alphatrue
      DXT FormatLet DDSCompressor choose optimal * format.
      Enable DXT1 Alphafalse
      DXT1 Alpha * Threshold128
      Compression AlgorithmEuclidean Distance
      * * @return the default compression attributes. */ - public static DXTCompressionAttributes getDefaultCompressionAttributes() - { + public static DXTCompressionAttributes getDefaultCompressionAttributes() { DXTCompressionAttributes attributes = new DXTCompressionAttributes(); attributes.setBuildMipmaps(true); // Always build mipmaps. attributes.setPremultiplyAlpha(true); // Always create premultiplied alpha format files.. @@ -385,30 +357,26 @@ public static DXTCompressionAttributes getDefaultCompressionAttributes() * one automatically from the image type. If no choice can be made from the image type, we default to using a DXT3 * compressor. * - * @param image image to convert to the DDS file format. + * @param image image to convert to the DDS file format. * @param attributes attributes that control the compression. * * @return buffer little endian ordered ByteBuffer containing the dds file bytes. * * @throws IllegalArgumentException if either image or attributes are null, or if - * image has non power of two dimensions. + * image has non power of two dimensions. */ - public java.nio.ByteBuffer compressImage(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes) - { - if (image == null) - { + public java.nio.ByteBuffer compressImage(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!WWMath.isPowerOfTwo(image.getWidth()) || !WWMath.isPowerOfTwo(image.getHeight())) - { + if (!WWMath.isPowerOfTwo(image.getWidth()) || !WWMath.isPowerOfTwo(image.getHeight())) { String message = Logging.getMessage("generic.InvalidImageSize", image.getWidth(), image.getHeight()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -422,31 +390,27 @@ public java.nio.ByteBuffer compressImage(java.awt.image.BufferedImage image, DXT * Converts the specified image to DDS using the DXT1 codec, and otherwise according to the * attributes. * - * @param image image to convert to the DDS file format using the DXT1 codec. + * @param image image to convert to the DDS file format using the DXT1 codec. * @param attributes attributes that control the compression. * * @return buffer little endian ordered ByteBuffer containing the dds file bytes. * * @throws IllegalArgumentException if either image or attributes are null, or if - * image has non power of two dimensions. + * image has non power of two dimensions. */ public java.nio.ByteBuffer compressImageDXT1(java.awt.image.BufferedImage image, - DXTCompressionAttributes attributes) - { - if (image == null) - { + DXTCompressionAttributes attributes) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!WWMath.isPowerOfTwo(image.getWidth()) || !WWMath.isPowerOfTwo(image.getHeight())) - { + if (!WWMath.isPowerOfTwo(image.getWidth()) || !WWMath.isPowerOfTwo(image.getHeight())) { String message = Logging.getMessage("generic.InvalidImageSize", image.getWidth(), image.getHeight()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -460,31 +424,27 @@ public java.nio.ByteBuffer compressImageDXT1(java.awt.image.BufferedImage image, * Converts the specified image to DDS using the DXT3 codec, and otherwise according to the * attributes. * - * @param image image to convert to the DDS file format using the DXT3 codec. + * @param image image to convert to the DDS file format using the DXT3 codec. * @param attributes attributes that control the compression. * * @return buffer little endian ordered ByteBuffer containing the dds file bytes. * * @throws IllegalArgumentException if either image or attributes are null, or if - * image has non power of two dimensions. + * image has non power of two dimensions. */ public java.nio.ByteBuffer compressImageDXT3(java.awt.image.BufferedImage image, - DXTCompressionAttributes attributes) - { - if (image == null) - { + DXTCompressionAttributes attributes) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!WWMath.isPowerOfTwo(image.getWidth()) || !WWMath.isPowerOfTwo(image.getHeight())) - { + if (!WWMath.isPowerOfTwo(image.getWidth()) || !WWMath.isPowerOfTwo(image.getHeight())) { String message = Logging.getMessage("generic.InvalidImageSize", image.getWidth(), image.getHeight()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -495,8 +455,7 @@ public java.nio.ByteBuffer compressImageDXT3(java.awt.image.BufferedImage image, } protected java.nio.ByteBuffer doCompressImage(DXTCompressor compressor, java.awt.image.BufferedImage image, - DXTCompressionAttributes attributes) - { + DXTCompressionAttributes attributes) { // Create the DDS header structure that describes the specified image, compressor, and compression attributes. DDSHeader header = this.createDDSHeader(compressor, image, attributes); @@ -507,20 +466,16 @@ protected java.nio.ByteBuffer doCompressImage(DXTCompressor compressor, java.awt java.awt.image.BufferedImage[] mipMapLevels = null; int fileSize = 4 + header.getSize(); - if (attributes.isBuildMipmaps()) - { + if (attributes.isBuildMipmaps()) { mipMapLevels = this.buildMipMaps(image, attributes); - for (java.awt.image.BufferedImage mipMapImage : mipMapLevels) - { + for (java.awt.image.BufferedImage mipMapImage : mipMapLevels) { fileSize += compressor.getCompressedSize(mipMapImage, attributes); } header.setFlags(header.getFlags() - | DDSConstants.DDSD_MIPMAPCOUNT); + | DDSConstants.DDSD_MIPMAPCOUNT); header.setMipMapCount(mipMapLevels.length); - } - else - { + } else { fileSize += compressor.getCompressedSize(image, attributes); } @@ -535,14 +490,10 @@ protected java.nio.ByteBuffer doCompressImage(DXTCompressor compressor, java.awt // Write the compressed DXT blocks to the DDS file. If the attributes specify to build mip maps, then we write // each mip map level to the DDS file, starting with level 0 and ending with level N. Otherwise, we write a // single image to the DDS file. - if (mipMapLevels == null) - { + if (mipMapLevels == null) { compressor.compressImage(image, attributes, buffer); - } - else - { - for (java.awt.image.BufferedImage mipMapImage : mipMapLevels) - { + } else { + for (java.awt.image.BufferedImage mipMapImage : mipMapLevels) { compressor.compressImage(mipMapImage, attributes, buffer); } } @@ -551,40 +502,30 @@ protected java.nio.ByteBuffer doCompressImage(DXTCompressor compressor, java.awt return buffer; } - protected DXTCompressor getDXTCompressor(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes) - { + protected DXTCompressor getDXTCompressor(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes) { // If the caller specified a DXT format in the attributes, then we return a compressor matching that format. // Otherwise, we choose one automatically from the image type. If no choice can be made from the image type, // we default to using a DXT3 compressor. - if (attributes.getDXTFormat() == DDSConstants.D3DFMT_DXT1) - { + if (attributes.getDXTFormat() == DDSConstants.D3DFMT_DXT1) { return new DXT1Compressor(); - } - else if (attributes.getDXTFormat() == DDSConstants.D3DFMT_DXT2 - || attributes.getDXTFormat() == DDSConstants.D3DFMT_DXT3) - { + } else if (attributes.getDXTFormat() == DDSConstants.D3DFMT_DXT2 + || attributes.getDXTFormat() == DDSConstants.D3DFMT_DXT3) { return new DXT3Compressor(); - } - else if (!image.getColorModel().hasAlpha()) - { + } else if (!image.getColorModel().hasAlpha()) { return new DXT1Compressor(); - } - else - { + } else { return new DXT3Compressor(); } } - protected java.nio.ByteBuffer createBuffer(int size) - { + protected java.nio.ByteBuffer createBuffer(int size) { return java.nio.ByteBuffer.allocateDirect(size); } @SuppressWarnings({"UnusedDeclaration"}) protected java.awt.image.BufferedImage[] buildMipMaps(java.awt.image.BufferedImage image, - DXTCompressionAttributes attributes) - { + DXTCompressionAttributes attributes) { // Build the mipmap chain using a premultiplied alpha image format. This is necessary to ensure that // transparent colors do not bleed into the opaque colors. For example, without premultiplied alpha the colors // in a totally transparent pixel may contribute when one mipmap level is filtered (with either a box or a @@ -603,20 +544,19 @@ protected java.awt.image.BufferedImage[] buildMipMaps(java.awt.image.BufferedIma } protected DDSHeader createDDSHeader(DXTCompressor compressor, java.awt.image.BufferedImage image, - DXTCompressionAttributes attributes) - { + DXTCompressionAttributes attributes) { DDSPixelFormat pixelFormat = new DDSPixelFormat(); pixelFormat.setFlags(pixelFormat.getFlags() - | DDSConstants.DDPF_FOURCC); + | DDSConstants.DDPF_FOURCC); pixelFormat.setFourCC(compressor.getDXTFormat()); DDSHeader header = new DDSHeader(); header.setFlags(header.getFlags() - | DDSConstants.DDSD_WIDTH - | DDSConstants.DDSD_HEIGHT - | DDSConstants.DDSD_LINEARSIZE - | DDSConstants.DDSD_PIXELFORMAT - | DDSConstants.DDSD_CAPS); + | DDSConstants.DDSD_WIDTH + | DDSConstants.DDSD_HEIGHT + | DDSConstants.DDSD_LINEARSIZE + | DDSConstants.DDSD_PIXELFORMAT + | DDSConstants.DDSD_CAPS); header.setWidth(image.getWidth()); header.setHeight(image.getHeight()); header.setLinearSize(compressor.getCompressedSize(image, attributes)); @@ -627,13 +567,13 @@ protected DDSHeader createDDSHeader(DXTCompressor compressor, java.awt.image.Buf } /** - * Documentation on the DDS header format is available at http://msdn.microsoft.com/en-us/library/bb943982(VS.85).aspx + * Documentation on the DDS header format is available at + * http://msdn.microsoft.com/en-us/library/bb943982(VS.85).aspx * * @param header header structure to write. * @param buffer buffer that receives the header structure bytes. */ - protected void writeDDSHeader(DDSHeader header, java.nio.ByteBuffer buffer) - { + protected void writeDDSHeader(DDSHeader header, java.nio.ByteBuffer buffer) { int pos = buffer.position(); buffer.putInt(header.getSize()); // dwSize @@ -655,13 +595,13 @@ protected void writeDDSHeader(DDSHeader header, java.nio.ByteBuffer buffer) } /** - * Documentation on the DDS pixel format is available at http://msdn.microsoft.com/en-us/library/bb943984(VS.85).aspx + * Documentation on the DDS pixel format is available at + * http://msdn.microsoft.com/en-us/library/bb943984(VS.85).aspx * * @param pixelFormat pixel format structure to write. - * @param buffer buffer that receives the pixel format structure bytes. + * @param buffer buffer that receives the pixel format structure bytes. */ - protected void writeDDSPixelFormat(DDSPixelFormat pixelFormat, java.nio.ByteBuffer buffer) - { + protected void writeDDSPixelFormat(DDSPixelFormat pixelFormat, java.nio.ByteBuffer buffer) { int pos = buffer.position(); buffer.putInt(pixelFormat.getSize()); // dwSize diff --git a/src/gov/nasa/worldwind/formats/dds/DDSConstants.java b/src/gov/nasa/worldwind/formats/dds/DDSConstants.java index 8614a1a182..7499b4435f 100644 --- a/src/gov/nasa/worldwind/formats/dds/DDSConstants.java +++ b/src/gov/nasa/worldwind/formats/dds/DDSConstants.java @@ -12,8 +12,8 @@ * @author dcollins * @version $Id: DDSConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DDSConstants -{ +public class DDSConstants { + public static final int DDS_SIGNATURE_SIZE = 4; public static final int DDS_HEADER_SIZE = 124; public static final int DDS_PIXEL_FORMAT_SIZE = 32; @@ -21,7 +21,6 @@ public class DDSConstants public static final int DDS_DATA_OFFSET = DDS_SIGNATURE_SIZE + DDS_HEADER_SIZE; - public static final int DDPF_FOURCC = 0x0004; public static final int DDSCAPS_TEXTURE = 0x1000; public static final int DDSD_CAPS = 0x0001; @@ -40,11 +39,10 @@ public class DDSConstants // A DWORD (magic number) containing the four character code value 'DDS ' (0x20534444) public static final int MAGIC = makeFourCC('D', 'D', 'S', ' '); - public static int makeFourCC(char ch0, char ch1, char ch2, char ch3) - { + public static int makeFourCC(char ch0, char ch1, char ch2, char ch3) { return (((int) ch0)) - | (((int) ch1) << 8) - | (((int) ch2) << 16) - | (((int) ch3) << 24); + | (((int) ch1) << 8) + | (((int) ch2) << 16) + | (((int) ch3) << 24); } } diff --git a/src/gov/nasa/worldwind/formats/dds/DDSDecompressor.java b/src/gov/nasa/worldwind/formats/dds/DDSDecompressor.java index 35ee494598..d0afbdb73a 100644 --- a/src/gov/nasa/worldwind/formats/dds/DDSDecompressor.java +++ b/src/gov/nasa/worldwind/formats/dds/DDSDecompressor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.dds; import gov.nasa.worldwind.avlist.AVKey; @@ -29,16 +28,15 @@ * @author Lado Garakanidze * @version $Id: DDSDecompressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class DDSDecompressor { -public class DDSDecompressor -{ - public DDSDecompressor() - { + public DDSDecompressor() { } /** - * Reconstructs image raster from a DDS source. The source type may be one of the following:

      • {@link java.net.URL}
      • {@link + * Reconstructs image raster from a DDS source. The source type may be one of the following: + *
        • {@link java.net.URL}
        • {@link * java.net.URI}
        • {@link java.io.File}
        • {@link String} containing a valid URL description, a valid * URI description, or a valid path to a local file.
        * @@ -47,37 +45,31 @@ public DDSDecompressor() * @return MipMappedBufferedImageRaster if the DDS source contains mipmaps, otherwise returns a BufferedImageRaster * @throws Exception when source or params is null */ - public DataRaster decompress(Object source, AVList params) throws Exception - { + public DataRaster decompress(Object source, AVList params) throws Exception { return this.doDecompress(source, params); } - protected DataRaster doDecompress(Object source, AVList params) throws Exception - { - if (null == params || !params.hasKey(AVKey.SECTOR)) - { + protected DataRaster doDecompress(Object source, AVList params) throws Exception { + if (null == params || !params.hasKey(AVKey.SECTOR)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().severe(message); throw new WWRuntimeException(message); } File file = WWIO.getFileForLocalAddress(source); - if (null == file) - { + if (null == file) { String message = Logging.getMessage("generic.UnrecognizedSourceType", source.getClass().getName()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file.getAbsolutePath()); Logging.logger().severe(message); throw new FileNotFoundException(message); } - if (!file.canRead()) - { + if (!file.canRead()) { String message = Logging.getMessage("generic.FileNoReadPermission", file.getAbsolutePath()); Logging.logger().severe(message); throw new IOException(message); @@ -87,8 +79,7 @@ protected DataRaster doDecompress(Object source, AVList params) throws Exception FileChannel channel = null; DataRaster raster = null; - try - { + try { raf = new RandomAccessFile(file, "r"); channel = raf.getChannel(); @@ -100,8 +91,7 @@ protected DataRaster doDecompress(Object source, AVList params) throws Exception int width = header.getWidth(); int height = header.getHeight(); - if (!WWMath.isPowerOfTwo(width) || !WWMath.isPowerOfTwo(height)) - { + if (!WWMath.isPowerOfTwo(width) || !WWMath.isPowerOfTwo(height)) { String message = Logging.getMessage("generic.InvalidImageSize", width, height); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -111,8 +101,7 @@ protected DataRaster doDecompress(Object source, AVList params) throws Exception // int ddsFlags = header.getFlags(); DDSPixelFormat pixelFormat = header.getPixelFormat(); - if (null == pixelFormat) - { + if (null == pixelFormat) { String reason = Logging.getMessage("generic.MissingRequiredParameter", "DDSD_PIXELFORMAT"); String message = Logging.getMessage("generic.InvalidImageFormat", reason); Logging.logger().severe(message); @@ -122,17 +111,13 @@ protected DataRaster doDecompress(Object source, AVList params) throws Exception DXTDecompressor decompressor = null; int dxtFormat = pixelFormat.getFourCC(); - if (dxtFormat == DDSConstants.D3DFMT_DXT3) - { + if (dxtFormat == DDSConstants.D3DFMT_DXT3) { decompressor = new DXT3Decompressor(); - } - else if (dxtFormat == DDSConstants.D3DFMT_DXT1) - { + } else if (dxtFormat == DDSConstants.D3DFMT_DXT1) { decompressor = new DXT1Decompressor(); } - if (null == decompressor) - { + if (null == decompressor) { String message = Logging.getMessage("generic.UnsupportedCodec", dxtFormat); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -141,29 +126,24 @@ else if (dxtFormat == DDSConstants.D3DFMT_DXT1) Sector sector = (Sector) params.getValue(AVKey.SECTOR); params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); - if (mipMapCount == 0) - { + if (mipMapCount == 0) { // read max resolution raster buffer.position(DDSConstants.DDS_DATA_OFFSET); BufferedImage image = decompressor.decompress(buffer, header.getWidth(), header.getHeight()); raster = new BufferedImageRaster(sector, image, params); - } - else if (mipMapCount > 0) - { + } else if (mipMapCount > 0) { ArrayList list = new ArrayList(); int mmLength = header.getLinearSize(); int mmOffset = DDSConstants.DDS_DATA_OFFSET; - for (int i = 0; i < mipMapCount; i++) - { + for (int i = 0; i < mipMapCount; i++) { int zoomOut = (int) Math.pow(2d, (double) i); int mmWidth = header.getWidth() / zoomOut; int mmHeight = header.getHeight() / zoomOut; - if (mmWidth < 4 || mmHeight < 4) - { + if (mmWidth < 4 || mmHeight < 4) { break; } @@ -182,26 +162,21 @@ else if (mipMapCount > 0) } return raster; - } - finally - { + } finally { String name = (null != file) ? file.getAbsolutePath() : ((null != source) ? source.toString() : "unknown"); WWIO.closeStream(channel, name); WWIO.closeStream(raf, name); } } - protected java.nio.MappedByteBuffer mapFile(FileChannel channel, long offset, long length) throws Exception - { - if (null == channel || !channel.isOpen()) - { + protected java.nio.MappedByteBuffer mapFile(FileChannel channel, long offset, long length) throws Exception { + if (null == channel || !channel.isOpen()) { String message = Logging.getMessage("nullValue.ChannelIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (channel.size() < (offset + length)) - { + if (channel.size() < (offset + length)) { String reason = channel.size() + " < " + (offset + length); String message = Logging.getMessage("generic.LengthIsInvalid", reason); Logging.logger().severe(message); diff --git a/src/gov/nasa/worldwind/formats/dds/DDSHeader.java b/src/gov/nasa/worldwind/formats/dds/DDSHeader.java index 3a5d2805aa..fbb9f411ba 100644 --- a/src/gov/nasa/worldwind/formats/dds/DDSHeader.java +++ b/src/gov/nasa/worldwind/formats/dds/DDSHeader.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: DDSHeader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DDSHeader -{ +public class DDSHeader { + protected final int size = DDSConstants.DDS_HEADER_SIZE; protected int flags; protected int width; @@ -38,8 +38,7 @@ public class DDSHeader protected int caps4; //protected int reserved2; // Unused - public DDSHeader() - { + public DDSHeader() { this.pixelFormat = new DDSPixelFormat(); } @@ -48,80 +47,64 @@ public DDSHeader() * * @return header size in bytes. */ - public final int getSize() - { + public final int getSize() { return this.size; } - public int getFlags() - { + public int getFlags() { return this.flags; } - public void setFlags(int flags) - { + public void setFlags(int flags) { this.flags = flags; } - public int getWidth() - { + public int getWidth() { return this.width; } - public void setWidth(int width) - { + public void setWidth(int width) { this.width = width; } - public int getHeight() - { + public int getHeight() { return this.height; } - public void setHeight(int height) - { + public void setHeight(int height) { this.height = height; } - public int getLinearSize() - { + public int getLinearSize() { return this.linearSize; } - public void setLinearSize(int size) - { + public void setLinearSize(int size) { this.linearSize = size; } - public int getDepth() - { + public int getDepth() { return this.depth; } - public void setDepth(int depth) - { + public void setDepth(int depth) { this.depth = depth; } - public int getMipMapCount() - { + public int getMipMapCount() { return this.mipMapCount; } - public void setMipMapCount(int mipMapCount) - { + public void setMipMapCount(int mipMapCount) { this.mipMapCount = mipMapCount; } - public DDSPixelFormat getPixelFormat() - { + public DDSPixelFormat getPixelFormat() { return this.pixelFormat; } - public void setPixelFormat(DDSPixelFormat pixelFormat) - { - if (pixelFormat == null) - { + public void setPixelFormat(DDSPixelFormat pixelFormat) { + if (pixelFormat == null) { String message = Logging.getMessage("nullValue.PixelFormatIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -130,55 +113,45 @@ public void setPixelFormat(DDSPixelFormat pixelFormat) this.pixelFormat = pixelFormat; } - public int getCaps() - { + public int getCaps() { return this.caps; } - public void setCaps(int caps) - { + public void setCaps(int caps) { this.caps = caps; } - public int getCaps2() - { + public int getCaps2() { return this.caps2; } - public void setCaps2(int caps) - { + public void setCaps2(int caps) { this.caps2 = caps; } - public int getCaps3() - { + public int getCaps3() { return this.caps3; } - public void setCaps3(int caps) - { + public void setCaps3(int caps) { this.caps3 = caps; } - public int getCaps4() - { + public int getCaps4() { return this.caps4; } - public void setCaps4(int caps) - { + public void setCaps4(int caps) { this.caps4 = caps; } - public static DDSHeader readFrom(Object source) throws Exception - { + public static DDSHeader readFrom(Object source) throws Exception { boolean sourceIsInputStream = (null != source && source instanceof InputStream); InputStream inputStream = WWIO.openStream(source); ReadableByteChannel channel = Channels.newChannel(WWIO.getBufferedInputStream(inputStream)); - try - { + try { int size = DDSConstants.DDS_SIGNATURE_SIZE + DDSConstants.DDS_HEADER_SIZE; ByteBuffer buffer = ByteBuffer.allocate(size); @@ -186,11 +159,8 @@ public static DDSHeader readFrom(Object source) throws Exception WWIO.readChannelToBuffer(channel, buffer); return DDSHeader.readFrom(buffer); - } - finally - { - if (!sourceIsInputStream) - { + } finally { + if (!sourceIsInputStream) { WWIO.closeStream(inputStream, ((null != source) ? source.toString() : "unknown")); } } @@ -202,25 +172,21 @@ public static DDSHeader readFrom(Object source) throws Exception * @param buffer The buffer to read from * @return DDSHeader * @throws IllegalArgumentException if the ByteBuffer is null - * @throws IOException if the buffer length or content is invalid + * @throws IOException if the buffer length or content is invalid */ - public static DDSHeader readFrom(ByteBuffer buffer) throws IllegalArgumentException, IOException - { - if (null == buffer) - { + public static DDSHeader readFrom(ByteBuffer buffer) throws IllegalArgumentException, IOException { + if (null == buffer) { String message = Logging.getMessage("nullValue.BufferNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer.order() != ByteOrder.LITTLE_ENDIAN) - { + if (buffer.order() != ByteOrder.LITTLE_ENDIAN) { buffer.order(ByteOrder.LITTLE_ENDIAN); } int ddsHeaderSize = DDSConstants.DDS_SIGNATURE_SIZE + DDSConstants.DDS_HEADER_SIZE; - if (buffer.remaining() < ddsHeaderSize) - { + if (buffer.remaining() < ddsHeaderSize) { String reason = buffer.remaining() + " < " + ddsHeaderSize; String message = Logging.getMessage("generic.LengthIsInvalid", reason); Logging.logger().severe(message); @@ -228,16 +194,14 @@ public static DDSHeader readFrom(ByteBuffer buffer) throws IllegalArgumentExcept } int signature = buffer.getInt(); - if (DDSConstants.MAGIC != signature) - { + if (DDSConstants.MAGIC != signature) { String message = Logging.getMessage("generic.UnknownFileFormat", signature); Logging.logger().fine(message); throw new IOException(message); } int dwSize = buffer.getInt(); - if (dwSize != DDSConstants.DDS_HEADER_SIZE) - { + if (dwSize != DDSConstants.DDS_HEADER_SIZE) { String message = Logging.getMessage("generic.UnknownContentType", dwSize); Logging.logger().fine(message); throw new IOException(message); @@ -258,8 +222,7 @@ public static DDSHeader readFrom(ByteBuffer buffer) throws IllegalArgumentExcept DDSPixelFormat pixelFormat = new DDSPixelFormat(); dwSize = buffer.getInt(); - if (dwSize != DDSConstants.DDS_PIXEL_FORMAT_SIZE) - { + if (dwSize != DDSConstants.DDS_PIXEL_FORMAT_SIZE) { String message = Logging.getMessage("generic.UnknownContentType", dwSize); Logging.logger().fine(message); throw new IOException(message); diff --git a/src/gov/nasa/worldwind/formats/dds/DDSPixelFormat.java b/src/gov/nasa/worldwind/formats/dds/DDSPixelFormat.java index ef8fd41327..acd3c50eb4 100644 --- a/src/gov/nasa/worldwind/formats/dds/DDSPixelFormat.java +++ b/src/gov/nasa/worldwind/formats/dds/DDSPixelFormat.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: DDSPixelFormat.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DDSPixelFormat -{ +public class DDSPixelFormat { + protected final int size = DDSConstants.DDS_PIXEL_FORMAT_SIZE; protected int flags; protected int fourCC; @@ -22,8 +22,7 @@ public class DDSPixelFormat protected int bBitMask; protected int aBitMask; - public DDSPixelFormat() - { + public DDSPixelFormat() { } /** @@ -31,78 +30,63 @@ public DDSPixelFormat() * * @return pixel format structure size in bytes. */ - public final int getSize() - { + public final int getSize() { return this.size; } - public int getFlags() - { + public int getFlags() { return this.flags; } - public void setFlags(int flags) - { + public void setFlags(int flags) { this.flags = flags; } - public int getFourCC() - { + public int getFourCC() { return this.fourCC; } - public void setFourCC(int fourCC) - { + public void setFourCC(int fourCC) { this.fourCC = fourCC; } - public int getRGBBitCount() - { + public int getRGBBitCount() { return this.rgbBitCount; } - public void setRGBBitCount(int bitCount) - { + public void setRGBBitCount(int bitCount) { this.rgbBitCount = bitCount; } - public int getRBitMask() - { + public int getRBitMask() { return this.rBitMask; } - public void setRBitMask(int rBitMask) - { + public void setRBitMask(int rBitMask) { this.rBitMask = rBitMask; } - public int getGBitMask() - { + public int getGBitMask() { return this.gBitMask; } - public void setGBitMask(int gBitMask) - { + public void setGBitMask(int gBitMask) { this.gBitMask = gBitMask; } - public int getBBitMask() - { + public int getBBitMask() { return this.bBitMask; } - public void setBBitMask(int bBitMask) - { + public void setBBitMask(int bBitMask) { this.bBitMask = bBitMask; } - public int getABitMask() - { + public int getABitMask() { return this.aBitMask; } - public void setABitMask(int aBitMask) - { + public void setABitMask(int aBitMask) { this.aBitMask = aBitMask; } } diff --git a/src/gov/nasa/worldwind/formats/dds/DXT1Compressor.java b/src/gov/nasa/worldwind/formats/dds/DXT1Compressor.java index d548ee1965..439622de26 100644 --- a/src/gov/nasa/worldwind/formats/dds/DXT1Compressor.java +++ b/src/gov/nasa/worldwind/formats/dds/DXT1Compressor.java @@ -11,34 +11,28 @@ * @author dcollins * @version $Id: DXT1Compressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DXT1Compressor implements DXTCompressor -{ - public DXT1Compressor() - { +public class DXT1Compressor implements DXTCompressor { + + public DXT1Compressor() { } - public int getDXTFormat() - { + public int getDXTFormat() { return DDSConstants.D3DFMT_DXT1; } - public int getCompressedSize(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes) - { - if (image == null) - { + public int getCompressedSize(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // TODO: comment, provide documentation reference - int width = Math.max(image.getWidth(), 4); int height = Math.max(image.getHeight(), 4); @@ -46,22 +40,18 @@ public int getCompressedSize(java.awt.image.BufferedImage image, DXTCompressionA } public void compressImage(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes, - java.nio.ByteBuffer buffer) - { - if (image == null) - { + java.nio.ByteBuffer buffer) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -69,7 +59,6 @@ public void compressImage(java.awt.image.BufferedImage image, DXTCompressionAttr // If it is determined that the image and block have no alpha component, then we compress with DXT1 using a // four color palette. Otherwise, we use the three color palette (with the fourth color as transparent black). - ColorBlock4x4 colorBlock = new ColorBlock4x4(); ColorBlockExtractor colorBlockExtractor = this.getColorBlockExtractor(image); @@ -83,18 +72,13 @@ public void compressImage(java.awt.image.BufferedImage image, DXTCompressionAttr boolean enableAlpha = attributes.isEnableDXT1Alpha(); int alphaThreshold = attributes.getDXT1AlphaThreshold(); - for (int j = 0; j < height; j += 4) - { - for (int i = 0; i < width; i += 4) - { + for (int j = 0; j < height; j += 4) { + for (int i = 0; i < width; i += 4) { colorBlockExtractor.extractColorBlock4x4(attributes, i, j, colorBlock); - if (enableAlpha && imageHasAlpha && blockHasDXT1Alpha(colorBlock, alphaThreshold)) - { + if (enableAlpha && imageHasAlpha && blockHasDXT1Alpha(colorBlock, alphaThreshold)) { dxt1Compressor.compressBlockDXT1a(colorBlock, attributes, dxt1Block); - } - else - { + } else { dxt1Compressor.compressBlockDXT1(colorBlock, attributes, dxt1Block); } @@ -105,15 +89,12 @@ public void compressImage(java.awt.image.BufferedImage image, DXTCompressionAttr } } - protected boolean blockHasDXT1Alpha(ColorBlock4x4 colorBlock, int alphaThreshold) - { + protected boolean blockHasDXT1Alpha(ColorBlock4x4 colorBlock, int alphaThreshold) { // DXT1 provides support for binary alpha. Therefore we determine treat a color block as needing alpha support // if any of the alpha values are less than a certain threshold. - for (int i = 0; i < 16; i++) - { - if (colorBlock.color[i].a < alphaThreshold) - { + for (int i = 0; i < 16; i++) { + if (colorBlock.color[i].a < alphaThreshold) { return true; } } @@ -121,8 +102,7 @@ protected boolean blockHasDXT1Alpha(ColorBlock4x4 colorBlock, int alphaThreshold return false; } - protected ColorBlockExtractor getColorBlockExtractor(java.awt.image.BufferedImage image) - { + protected ColorBlockExtractor getColorBlockExtractor(java.awt.image.BufferedImage image) { return new BasicColorBlockExtractor(image); } } diff --git a/src/gov/nasa/worldwind/formats/dds/DXT1Decompressor.java b/src/gov/nasa/worldwind/formats/dds/DXT1Decompressor.java index 1de01979eb..8a8f84ed36 100644 --- a/src/gov/nasa/worldwind/formats/dds/DXT1Decompressor.java +++ b/src/gov/nasa/worldwind/formats/dds/DXT1Decompressor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.dds; import gov.nasa.worldwind.util.Logging; @@ -18,58 +17,47 @@ * @author Lado Garakanidze * @version $Id: DXT1Decompressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class DXT1Decompressor implements DXTDecompressor { -public class DXT1Decompressor implements DXTDecompressor -{ public static final int DXT1_BLOCK_SIZE = 4; - public DXT1Decompressor() - { + public DXT1Decompressor() { } - public BufferedImage decompress(ByteBuffer buffer, int width, int height) throws IOException, IllegalArgumentException - { - if (null == buffer) - { + public BufferedImage decompress(ByteBuffer buffer, int width, int height) throws IOException, IllegalArgumentException { + if (null == buffer) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (width <= 0 || height <= 0) - { + if (width <= 0 || height <= 0) { String message = Logging.getMessage("generic.InvalidImageSize", width, height); Logging.logger().fine(message); throw new IllegalArgumentException(message); } // TODO check buffer's remaining with image size - return this.decodeDxt1Buffer(buffer, width, height); } protected BufferedImage decodeDxt1Buffer(ByteBuffer buffer, int width, int height) - throws IllegalArgumentException, IOException - { - if (null == buffer) - { + throws IllegalArgumentException, IOException { + if (null == buffer) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (width < DXT1_BLOCK_SIZE || height < DXT1_BLOCK_SIZE) - { + if (width < DXT1_BLOCK_SIZE || height < DXT1_BLOCK_SIZE) { String message = Logging.getMessage("generic.InvalidImageSize", width, height); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - try - { - if (buffer.order() != ByteOrder.LITTLE_ENDIAN) - { + try { + if (buffer.order() != ByteOrder.LITTLE_ENDIAN) { buffer.order(ByteOrder.LITTLE_ENDIAN); } @@ -81,18 +69,15 @@ protected BufferedImage decodeDxt1Buffer(ByteBuffer buffer, int width, int heigh BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - for (int row = 0; row < numTilesHigh; row++) - { - for (int col = 0; col < numTilesWide; col++) - { + for (int row = 0; row < numTilesHigh; row++) { + for (int col = 0; col < numTilesWide; col++) { short minColor = buffer.getShort(); short maxColor = buffer.getShort(); int colorIndexMask = buffer.getInt(); Color24[] lookupTable = Color24.expandLookupTable(minColor, maxColor); - for (int k = DXT1_BLOCK_SIZE * DXT1_BLOCK_SIZE - 1; k >= 0; k--) - { + for (int k = DXT1_BLOCK_SIZE * DXT1_BLOCK_SIZE - 1; k >= 0; k--) { int h = k / DXT1_BLOCK_SIZE, w = k % DXT1_BLOCK_SIZE; int pixelIndex = h * width + (col * DXT1_BLOCK_SIZE + w); @@ -105,9 +90,7 @@ protected BufferedImage decodeDxt1Buffer(ByteBuffer buffer, int width, int heigh result.setRGB(0, row * DXT1_BLOCK_SIZE, width, DXT1_BLOCK_SIZE, pixels, 0, width); } return result; - } - catch (Throwable t) - { + } catch (Throwable t) { String message = t.getMessage(); message = (null == message) ? t.getCause().getMessage() : message; Logging.logger().log(Level.FINEST, message, t); diff --git a/src/gov/nasa/worldwind/formats/dds/DXT3Compressor.java b/src/gov/nasa/worldwind/formats/dds/DXT3Compressor.java index 747d7e0e87..cdd8c1d6a8 100644 --- a/src/gov/nasa/worldwind/formats/dds/DXT3Compressor.java +++ b/src/gov/nasa/worldwind/formats/dds/DXT3Compressor.java @@ -11,57 +11,47 @@ * @author dcollins * @version $Id: DXT3Compressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DXT3Compressor implements DXTCompressor -{ - public DXT3Compressor() - { +public class DXT3Compressor implements DXTCompressor { + + public DXT3Compressor() { } - public int getDXTFormat() - { + public int getDXTFormat() { return DDSConstants.D3DFMT_DXT3; } - public int getCompressedSize(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes) - { - if (image == null) - { + public int getCompressedSize(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // TODO: comment, provide documentation reference - int width = Math.max(image.getWidth(), 4); int height = Math.max(image.getHeight(), 4); - + return (width * height); } - + public void compressImage(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes, - java.nio.ByteBuffer buffer) - { - if (image == null) - { + java.nio.ByteBuffer buffer) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,10 +66,8 @@ public void compressImage(java.awt.image.BufferedImage image, DXTCompressionAttr int width = image.getWidth(); int height = image.getHeight(); - for (int j = 0; j < height; j += 4) - { - for (int i = 0; i < width; i += 4) - { + for (int j = 0; j < height; j += 4) { + for (int i = 0; i < width; i += 4) { colorBlockExtractor.extractColorBlock4x4(attributes, i, j, colorBlock); dxt3Compressor.compressBlockDXT3(colorBlock, attributes, dxt3Block); @@ -94,8 +82,7 @@ public void compressImage(java.awt.image.BufferedImage image, DXTCompressionAttr } } - protected ColorBlockExtractor getColorBlockExtractor(java.awt.image.BufferedImage image) - { + protected ColorBlockExtractor getColorBlockExtractor(java.awt.image.BufferedImage image) { return new BasicColorBlockExtractor(image); } } diff --git a/src/gov/nasa/worldwind/formats/dds/DXT3Decompressor.java b/src/gov/nasa/worldwind/formats/dds/DXT3Decompressor.java index 88025b9793..aee2a165fc 100644 --- a/src/gov/nasa/worldwind/formats/dds/DXT3Decompressor.java +++ b/src/gov/nasa/worldwind/formats/dds/DXT3Decompressor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.dds; import gov.nasa.worldwind.util.Logging; @@ -18,58 +17,47 @@ * @author Lado Garakanidze * @version $Id: DXT3Decompressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class DXT3Decompressor implements DXTDecompressor { -public class DXT3Decompressor implements DXTDecompressor -{ public static final int DXT3_BLOCK_SIZE = 4; - public DXT3Decompressor() - { + public DXT3Decompressor() { } - public BufferedImage decompress(ByteBuffer buffer, int width, int height) throws IOException, IllegalArgumentException - { - if (null == buffer) - { + public BufferedImage decompress(ByteBuffer buffer, int width, int height) throws IOException, IllegalArgumentException { + if (null == buffer) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (width <= 0 || height <= 0) - { + if (width <= 0 || height <= 0) { String message = Logging.getMessage("generic.InvalidImageSize", width, height); Logging.logger().fine(message); throw new IllegalArgumentException(message); } // TODO check buffer's remaining with image size - return this.decodeDxt3Buffer(buffer, width, height); } protected BufferedImage decodeDxt3Buffer(ByteBuffer buffer, int width, int height) - throws IllegalArgumentException, IOException - { - if (null == buffer) - { + throws IllegalArgumentException, IOException { + if (null == buffer) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (width < DXT3_BLOCK_SIZE || height < DXT3_BLOCK_SIZE) - { + if (width < DXT3_BLOCK_SIZE || height < DXT3_BLOCK_SIZE) { String message = Logging.getMessage("generic.InvalidImageSize", width, height); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - try - { - if (buffer.order() != ByteOrder.LITTLE_ENDIAN) - { + try { + if (buffer.order() != ByteOrder.LITTLE_ENDIAN) { buffer.order(ByteOrder.LITTLE_ENDIAN); } @@ -81,10 +69,8 @@ protected BufferedImage decodeDxt3Buffer(ByteBuffer buffer, int width, int heigh BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); - for (int row = 0; row < numTilesHigh; row++) - { - for (int col = 0; col < numTilesWide; col++) - { + for (int row = 0; row < numTilesHigh; row++) { + for (int col = 0; col < numTilesWide; col++) { long alphaData = buffer.getLong(); short minColor = buffer.getShort(); short maxColor = buffer.getShort(); @@ -92,8 +78,7 @@ protected BufferedImage decodeDxt3Buffer(ByteBuffer buffer, int width, int heigh Color24[] lookupTable = Color24.expandLookupTable(minColor, maxColor); - for (int k = DXT3_BLOCK_SIZE * DXT3_BLOCK_SIZE - 1; k >= 0; k--) - { + for (int k = DXT3_BLOCK_SIZE * DXT3_BLOCK_SIZE - 1; k >= 0; k--) { int alpha = (int) (alphaData >>> (k * 4)) & 0xF; // Alphas are just 4 bits per pixel alpha <<= 4; @@ -101,7 +86,6 @@ protected BufferedImage decodeDxt3Buffer(ByteBuffer buffer, int width, int heigh // No need to multiply alpha, it is already pre-multiplied // Color24 color = Color24.multiplyAlpha(lookupTable[colorIndex], alpha ); - Color24 color = lookupTable[colorIndex]; int pixel8888 = (alpha << 24) | color.getPixel888(); @@ -115,9 +99,7 @@ protected BufferedImage decodeDxt3Buffer(ByteBuffer buffer, int width, int heigh result.setRGB(0, row * DXT3_BLOCK_SIZE, width, DXT3_BLOCK_SIZE, pixels, 0, width); } return result; - } - catch (Throwable t) - { + } catch (Throwable t) { String message = t.getMessage(); message = (null == message) ? t.getCause().getMessage() : message; Logging.logger().log(Level.FINEST, message, t); diff --git a/src/gov/nasa/worldwind/formats/dds/DXTCompressionAttributes.java b/src/gov/nasa/worldwind/formats/dds/DXTCompressionAttributes.java index 6e5462c610..647bd77ff6 100644 --- a/src/gov/nasa/worldwind/formats/dds/DXTCompressionAttributes.java +++ b/src/gov/nasa/worldwind/formats/dds/DXTCompressionAttributes.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: DXTCompressionAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DXTCompressionAttributes -{ +public class DXTCompressionAttributes { + public static final String COLOR_BLOCK_COMPRESSION_BBOX = "ColorBlockCompressionBBox"; public static final String COLOR_BLOCK_COMPRESSION_EUCLIDEAN_DISTANCE = "ColorBlockCompressionEuclideanDistance"; public static final String COLOR_BLOCK_COMPRESSION_LUMINANCE_DISTANCE = "ColorBlockCompressionLuminanceDistance"; @@ -24,8 +24,7 @@ public class DXTCompressionAttributes protected static final int DEFAULT_DXT1_TRANSPARENCY_THRESHOLD = 128; - public DXTCompressionAttributes() - { + public DXTCompressionAttributes() { this.buildMipmaps = true; this.premultiplyAlpha = true; this.dxtFormat = 0; @@ -34,63 +33,51 @@ public DXTCompressionAttributes() this.colorBlockCompressionType = COLOR_BLOCK_COMPRESSION_EUCLIDEAN_DISTANCE; } - public boolean isBuildMipmaps() - { + public boolean isBuildMipmaps() { return this.buildMipmaps; } - public void setBuildMipmaps(boolean buildMipmaps) - { + public void setBuildMipmaps(boolean buildMipmaps) { this.buildMipmaps = buildMipmaps; } - public boolean isPremultiplyAlpha() - { + public boolean isPremultiplyAlpha() { return this.premultiplyAlpha; } - public void setPremultiplyAlpha(boolean premultiplyAlpha) - { + public void setPremultiplyAlpha(boolean premultiplyAlpha) { this.premultiplyAlpha = premultiplyAlpha; } - public int getDXTFormat() - { + public int getDXTFormat() { return this.dxtFormat; } - public void setDXTFormat(int format) - { + public void setDXTFormat(int format) { this.dxtFormat = format; } - public boolean isEnableDXT1Alpha() - { + public boolean isEnableDXT1Alpha() { return this.enableDXT1Alpha; } - public void setEnableDXT1Alpha(boolean enable) - { + public void setEnableDXT1Alpha(boolean enable) { this.enableDXT1Alpha = enable; } - public int getDXT1AlphaThreshold() - { + public int getDXT1AlphaThreshold() { return this.dxt1AlphaThreshold; } - public void setDXT1AlphaThreshold(int threshold) - { + public void setDXT1AlphaThreshold(int threshold) { this.dxt1AlphaThreshold = threshold; } - public String getColorBlockCompressionType() - { + public String getColorBlockCompressionType() { return this.colorBlockCompressionType; } - public void setColorBlockCompressionType(String compressionType) - { + public void setColorBlockCompressionType(String compressionType) { this.colorBlockCompressionType = compressionType; } } diff --git a/src/gov/nasa/worldwind/formats/dds/DXTCompressor.java b/src/gov/nasa/worldwind/formats/dds/DXTCompressor.java index c502924fe8..4d8efaaef5 100644 --- a/src/gov/nasa/worldwind/formats/dds/DXTCompressor.java +++ b/src/gov/nasa/worldwind/formats/dds/DXTCompressor.java @@ -8,12 +8,12 @@ /** * The DXTCompressor interface will compress an in-memory image using one of the DXT block compression * schemes. The details of each block compression scheme is handled by the implementation. - * + * * @author dcollins * @version $Id: DXTCompressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface DXTCompressor -{ +public interface DXTCompressor { + /** * Returns the DXT format constant associated with this compressor. * @@ -35,8 +35,8 @@ public interface DXTCompressor int getCompressedSize(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes); /** - * Encodes the specified image image into a compressed DXT codec, and writes the compressed bytes - * to the specified buffer. The buffer should be allocated with enough space to hold the compressed + * Encodes the specified image image into a compressed DXT codec, and writes the compressed bytes to + * the specified buffer. The buffer should be allocated with enough space to hold the compressed * output. The correct size should be computed by calling getCompressedSize(image, attributes). * * @param image the image to compress. @@ -44,9 +44,9 @@ public interface DXTCompressor * @param buffer the buffer that will receive the compressed output. * * @see #getCompressedSize(java.awt.image.BufferedImage, DXTCompressionAttributes) - * @throws IllegalArgumentException if any of image, attributes, or - * buffer are null. + * @throws IllegalArgumentException if any of image, attributes, or buffer + * are null. */ void compressImage(java.awt.image.BufferedImage image, DXTCompressionAttributes attributes, - java.nio.ByteBuffer buffer); + java.nio.ByteBuffer buffer); } diff --git a/src/gov/nasa/worldwind/formats/dds/DXTDecompressor.java b/src/gov/nasa/worldwind/formats/dds/DXTDecompressor.java index 6b38e6ccf8..5cd58b627b 100644 --- a/src/gov/nasa/worldwind/formats/dds/DXTDecompressor.java +++ b/src/gov/nasa/worldwind/formats/dds/DXTDecompressor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.dds; import java.io.IOException; @@ -12,17 +11,16 @@ * @author Lado Garakanidze * @version $Id: DXTDecompressor.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public interface DXTDecompressor { -public interface DXTDecompressor -{ /** * Decompress DXT1, DXT3 and DXT3A encoded rasters * * @param buffer The buffer to decompress. - * @param width must be a positive and power of two (4, 8, 16, 32, 64, 128, 512, etc ) + * @param width must be a positive and power of two (4, 8, 16, 32, 64, 128, 512, etc ) * @param height must be a positive and power of two (4, 8, 16, 32, 64, 128, 512, etc ) * @return java.awt.image.BufferedImage instance - * @throws IOException if there is a problem while reading from buffer or decompression + * @throws IOException if there is a problem while reading from buffer or decompression * @throws IllegalArgumentException if any input parameter is null or invalid */ java.awt.image.BufferedImage decompress(java.nio.ByteBuffer buffer, int width, int height) diff --git a/src/gov/nasa/worldwind/formats/dds/StandaloneDDSConverter.java b/src/gov/nasa/worldwind/formats/dds/StandaloneDDSConverter.java index 88f1f0615d..1de07ecc4d 100644 --- a/src/gov/nasa/worldwind/formats/dds/StandaloneDDSConverter.java +++ b/src/gov/nasa/worldwind/formats/dds/StandaloneDDSConverter.java @@ -15,115 +15,95 @@ * @author Tom Gaskins * @version $Id: StandaloneDDSConverter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class StandaloneDDSConverter -{ - private static void convertToDDS(File file) throws IOException - { - if (file == null) - { +public class StandaloneDDSConverter { + + private static void convertToDDS(File file) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists() || !file.canRead()) - { + if (!file.exists() || !file.canRead()) { String message = Logging.getMessage("DDSConverter.NoFileOrNoPermission"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (file.isDirectory()) + if (file.isDirectory()) { convertDirectory(file, new String[]{".jpg", "png"}); - else + } else { convertFile(file); + } } - private static void convertDirectory(File dir, final String[] suffixes) - { + private static void convertDirectory(File dir, final String[] suffixes) { System.out.printf("===== Converting Directory %s\n", dir.getPath()); - File[] files = dir.listFiles(new FileFilter() - { - public boolean accept(File file) - { - for (String suffix : suffixes) - { - if (file.getPath().endsWith(suffix)) + File[] files = dir.listFiles(new FileFilter() { + public boolean accept(File file) { + for (String suffix : suffixes) { + if (file.getPath().endsWith(suffix)) { return true; + } } return false; } }); - if (files != null) - { - for (File file : files) - { - try - { + if (files != null) { + for (File file : files) { + try { convertFile(file); - } - catch (Exception e) - { + } catch (Exception e) { System.out.printf("Exception converting %s, skipping file\n", file.getPath()); e.printStackTrace(); } } } - File[] directories = dir.listFiles(new FileFilter() - { - public boolean accept(File file) - { + File[] directories = dir.listFiles(new FileFilter() { + public boolean accept(File file) { return file.isDirectory(); } }); - if (directories != null) - { - for (File directory : directories) - { + if (directories != null) { + for (File directory : directories) { convertDirectory(directory, suffixes); } } } - private static void convertFile(File file) throws IOException - { + private static void convertFile(File file) throws IOException { System.out.printf("Converting File %s\n", file.getPath()); ByteBuffer buffer = DDSCompressor.compressImageFile(file); File newFile = new File(WWIO.replaceSuffix(file.getPath(), ".dds")); WWIO.saveBuffer(buffer, newFile); } - public static void main(String[] args) - { + public static void main(String[] args) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setMultiSelectionEnabled(true); - + int status = fileChooser.showOpenDialog(null); - if (status != JFileChooser.APPROVE_OPTION) + if (status != JFileChooser.APPROVE_OPTION) { return; - + } + File[] files = fileChooser.getSelectedFiles(); - if (files == null) - { + if (files == null) { System.out.println("No files selected"); return; } - for (File file : files) - { - try - { + for (File file : files) { + try { convertToDDS(file); - } - catch (IOException e) - { + } catch (IOException e) { System.out.printf("Exception converting input file %s, skipping file\n", file.getPath()); e.printStackTrace(); } diff --git a/src/gov/nasa/worldwind/formats/dted/DTED.java b/src/gov/nasa/worldwind/formats/dted/DTED.java index 3a01233480..70d66f2760 100644 --- a/src/gov/nasa/worldwind/formats/dted/DTED.java +++ b/src/gov/nasa/worldwind/formats/dted/DTED.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.dted; import gov.nasa.worldwind.avlist.*; @@ -20,9 +19,8 @@ * @author Lado Garakanidze * @version $Id: DTED.java 3037 2015-04-17 23:08:47Z tgaskins $ */ +public class DTED { -public class DTED -{ protected static final int REC_HEADER_SIZE = 8; // 8 bytes protected static final int REC_CHKSUM_SIZE = Integer.SIZE / Byte.SIZE; // 4 bytes (32bit integer) @@ -39,28 +37,23 @@ public class DTED protected static final int DTED_MIN_VALUE = -12000; protected static final int DTED_MAX_VALUE = 9000; - protected DTED() - { + protected DTED() { } - protected static RandomAccessFile open(File file) throws IOException, IllegalArgumentException - { - if (null == file) - { + protected static RandomAccessFile open(File file) throws IOException, IllegalArgumentException { + if (null == file) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file.getAbsolutePath()); Logging.logger().severe(message); throw new IOException(message); } - if (!file.canRead()) - { + if (!file.canRead()) { String message = Logging.getMessage("generic.FileNoReadPermission", file.getAbsolutePath()); Logging.logger().severe(message); throw new IOException(message); @@ -69,28 +62,21 @@ protected static RandomAccessFile open(File file) throws IOException, IllegalArg return new RandomAccessFile(file, "r"); } - protected static void close(RandomAccessFile file) - { - if (null != file) - { - try - { + protected static void close(RandomAccessFile file) { + if (null != file) { + try { file.close(); - } - catch (Exception ex) - { + } catch (Exception ex) { Logging.logger().finest(ex.getMessage()); } } } - public static AVList readMetadata(File file) throws IOException - { + public static AVList readMetadata(File file) throws IOException { AVList metadata = null; RandomAccessFile sourceFile = null; - try - { + try { sourceFile = open(file); FileChannel channel = sourceFile.getChannel(); @@ -100,22 +86,18 @@ public static AVList readMetadata(File file) throws IOException readUHL(channel, DTED_UHL_OFFSET, metadata); readDSI(channel, DTED_DSI_OFFSET, metadata); readACC(channel, DTED_ACC_OFFSET, metadata); - } - finally - { + } finally { close(sourceFile); } return metadata; } - public static DataRaster read(File file, AVList metadata) throws IOException - { + public static DataRaster read(File file, AVList metadata) throws IOException { DataRaster raster = null; RandomAccessFile sourceFile = null; - try - { + try { sourceFile = open(file); FileChannel channel = sourceFile.getChannel(); @@ -125,19 +107,17 @@ public static DataRaster read(File file, AVList metadata) throws IOException readACC(channel, DTED_ACC_OFFSET, metadata); raster = readElevations(channel, DTED_DATA_OFFSET, metadata); - } - finally - { + } finally { close(sourceFile); } return raster; } - protected static DataRaster readElevations(FileChannel theChannel, long offset, AVList metadata) throws IOException - { - if (null == theChannel) + protected static DataRaster readElevations(FileChannel theChannel, long offset, AVList metadata) throws IOException { + if (null == theChannel) { return null; + } ByteBufferRaster raster = (ByteBufferRaster) ByteBufferRaster.createGeoreferencedRaster(metadata); @@ -152,32 +132,27 @@ protected static DataRaster readElevations(FileChannel theChannel, long offset, double max = -Double.MAX_VALUE; ByteBuffer bb = ByteBuffer.allocate(recordSize).order(ByteOrder.BIG_ENDIAN); - for (int x = 0; x < width; x++) - { + for (int x = 0; x < width; x++) { theChannel.read(bb); bb.flip(); int dataChkSum = 0; for (int i = 0; i < recordSize - REC_CHKSUM_SIZE; - i++) // include header and elevations, exclude checksum itself + i++) // include header and elevations, exclude checksum itself { dataChkSum += 0xFF & bb.get(i); } ShortBuffer data = bb.asShortBuffer(); - for (int i = 0; i < height; i++) - { + for (int i = 0; i < height; i++) { double elev = (double) data.get(i + 4); // skip 4 shorts of header int y = height - i - 1; - if (elev != DTED_NODATA_VALUE && elev >= DTED_MIN_VALUE && elev <= DTED_MAX_VALUE) - { + if (elev != DTED_NODATA_VALUE && elev >= DTED_MIN_VALUE && elev <= DTED_MAX_VALUE) { raster.setDoubleAtPosition(y, x, elev); min = (elev < min) ? elev : min; max = (elev > max) ? elev : max; - } - else - { + } else { // Interpret null DTED values and values outside the practical range of [-12000,+9000] as missing // data. See MIL-PRF-89020B sections 3.11.2 and 3.11.3. raster.setDoubleAtPosition(y, x, DTED_NODATA_VALUE); @@ -189,8 +164,7 @@ protected static DataRaster readElevations(FileChannel theChannel, long offset, int expectedChkSum = (0xFFFF & hi) << 16 | (0xFFFF & lo); - if (expectedChkSum != dataChkSum) - { + if (expectedChkSum != dataChkSum) { String message = Logging.getMessage("DTED.DataRecordChecksumError", expectedChkSum, dataChkSum); Logging.logger().severe(message); throw new IOException(message); @@ -203,10 +177,8 @@ protected static DataRaster readElevations(FileChannel theChannel, long offset, return raster; } - protected static Angle readAngle(String angle) throws IOException - { - if (null == angle) - { + protected static Angle readAngle(String angle) throws IOException { + if (null == angle) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IOException(message); @@ -215,8 +187,7 @@ protected static Angle readAngle(String angle) throws IOException // let's separate DDDMMSSH with spaces and use a standard Angle.fromDMS() method StringBuffer sb = new StringBuffer(angle.trim()); int length = sb.length(); - switch (length) - { + switch (length) { case 7: // 0123456789 // DD MM SS H @@ -247,39 +218,39 @@ protected static Angle readAngle(String angle) throws IOException return null; } - protected static Integer readLevel(String dtedLevel) - { - if (null == dtedLevel) + protected static Integer readLevel(String dtedLevel) { + if (null == dtedLevel) { return null; + } dtedLevel = dtedLevel.trim(); - if (!dtedLevel.startsWith("DTED") || dtedLevel.length() != 5) + if (!dtedLevel.startsWith("DTED") || dtedLevel.length() != 5) { return null; + } return (dtedLevel.charAt(4) - '0'); } - protected static String readClassLevel(String code) - { - if (null != code) - { + protected static String readClassLevel(String code) { + if (null != code) { code = code.trim(); - if ("U".equalsIgnoreCase(code)) + if ("U".equalsIgnoreCase(code)) { return AVKey.CLASS_LEVEL_UNCLASSIFIED; - else if ("R".equalsIgnoreCase(code)) + } else if ("R".equalsIgnoreCase(code)) { return AVKey.CLASS_LEVEL_RESTRICTED; - else if ("C".equalsIgnoreCase(code)) + } else if ("C".equalsIgnoreCase(code)) { return AVKey.CLASS_LEVEL_CONFIDENTIAL; - else if ("S".equalsIgnoreCase(code)) + } else if ("S".equalsIgnoreCase(code)) { return AVKey.CLASS_LEVEL_SECRET; + } } return null; } - protected static void readACC(FileChannel theChannel, long offset, AVList metadata) throws IOException - { - if (null == theChannel) + protected static void readACC(FileChannel theChannel, long offset, AVList metadata) throws IOException { + if (null == theChannel) { return; + } theChannel.position(offset); @@ -289,8 +260,7 @@ protected static void readACC(FileChannel theChannel, long offset, AVList metada bb.flip(); String id = new String(acc, 0, 3); - if (!"ACC".equalsIgnoreCase(id)) - { + if (!"ACC".equalsIgnoreCase(id)) { String reason = Logging.getMessage("DTED.UnexpectedRecordId", id, "ACC"); String message = Logging.getMessage("DTED.BadFileFormat", reason); Logging.logger().severe(message); @@ -298,10 +268,10 @@ protected static void readACC(FileChannel theChannel, long offset, AVList metada } } - protected static void readUHL(FileChannel theChannel, long offset, AVList metadata) throws IOException - { - if (null == theChannel) + protected static void readUHL(FileChannel theChannel, long offset, AVList metadata) throws IOException { + if (null == theChannel) { return; + } theChannel.position(offset); @@ -311,8 +281,7 @@ protected static void readUHL(FileChannel theChannel, long offset, AVList metada bb.flip(); String id = new String(uhl, 0, 3); - if (!"UHL".equalsIgnoreCase(id)) - { + if (!"UHL".equalsIgnoreCase(id)) { String reason = Logging.getMessage("DTED.UnexpectedRecordId", id, "UHL"); String message = Logging.getMessage("DTED.BadFileFormat", reason); Logging.logger().severe(message); @@ -355,7 +324,6 @@ protected static void readUHL(FileChannel theChannel, long offset, AVList metada // in DTED the original is always lower left (South-West) corner // and each file always contains 1" x 1" degrees tile // also, we should account 1 pixel overlap and half pixel shift - Sector sector = Sector.fromDegrees(lat.degrees, lat.degrees + 1d, lon.degrees, lon.degrees + 1d); metadata.setValue(AVKey.SECTOR, sector); @@ -364,8 +332,9 @@ protected static void readUHL(FileChannel theChannel, long offset, AVList metada metadata.setValue(AVKey.ORIGIN, wwOrigin); String classLevel = readClassLevel(new String(uhl, 32, 3)); - if (null != classLevel) + if (null != classLevel) { metadata.setValue(AVKey.CLASS_LEVEL, classLevel); + } // String sLonInterval = new String(uhl, 20, 4); // String sLatInterval = new String(uhl, 24, 4); @@ -375,10 +344,10 @@ protected static void readUHL(FileChannel theChannel, long offset, AVList metada // String sReserved = new String( uhl, 56, 24 ); } - protected static void readDSI(FileChannel theChannel, long offset, AVList metadata) throws IOException - { - if (null == theChannel) + protected static void readDSI(FileChannel theChannel, long offset, AVList metadata) throws IOException { + if (null == theChannel) { return; + } theChannel.position(offset); theChannel.position(offset); @@ -389,28 +358,27 @@ protected static void readDSI(FileChannel theChannel, long offset, AVList metada bb.flip(); String id = new String(dsi, 0, 3); - if (!"DSI".equalsIgnoreCase(id)) - { + if (!"DSI".equalsIgnoreCase(id)) { String reason = Logging.getMessage("DTED.UnexpectedRecordId", id, "DSI"); String message = Logging.getMessage("DTED.BadFileFormat", reason); Logging.logger().severe(message); throw new IOException(message); } - if (!metadata.hasKey(AVKey.CLASS_LEVEL)) - { + if (!metadata.hasKey(AVKey.CLASS_LEVEL)) { String classLevel = readClassLevel(new String(dsi, 3, 1)); - if (null != classLevel) + if (null != classLevel) { metadata.setValue(AVKey.CLASS_LEVEL, classLevel); + } } Integer level = readLevel(new String(dsi, 59, 5)); - if (null != level) + if (null != level) { metadata.setValue(AVKey.DTED_LEVEL, level); + } // Technically, there is no need to read next parameters because: // they are redundant (same data we get from UHL), and WW has no use for them - // String uniqueRef = new String(dsi, 64, 15); // String reserved = new String(dsi, 79, 8); // String verticalDatum = new String(dsi, 141, 3); diff --git a/src/gov/nasa/worldwind/formats/gcps/GCPSReader.java b/src/gov/nasa/worldwind/formats/gcps/GCPSReader.java index ff66da7111..948f350ee6 100644 --- a/src/gov/nasa/worldwind/formats/gcps/GCPSReader.java +++ b/src/gov/nasa/worldwind/formats/gcps/GCPSReader.java @@ -11,23 +11,19 @@ * @author dcollins * @version $Id: GCPSReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GCPSReader -{ +public class GCPSReader { + private String delimiter = "[\\s]"; - public GCPSReader() - { + public GCPSReader() { } - public String getDelimiter() - { + public String getDelimiter() { return this.delimiter; } - public void setDelimiter(String delimiter) - { - if (delimiter == null || delimiter.length() == 0) - { + public void setDelimiter(String delimiter) { + if (delimiter == null || delimiter.length() == 0) { String message = Logging.getMessage("nullValue.DelimiterIsNullOrEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -36,33 +32,29 @@ public void setDelimiter(String delimiter) this.delimiter = delimiter; } - public static java.io.File getGCPSFileFor(java.io.File file) - { - if (file == null) - { + public static java.io.File getGCPSFileFor(java.io.File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.io.File parent = file.getParentFile(); - if (parent == null) + if (parent == null) { return null; + } String tabFilename = WWIO.replaceSuffix(file.getName(), ".gcps"); // The file already has a TAB extension. Rather than returning a self reference, we return null to deonte that // a TAB file does not associate with itself. - if (file.getName().equalsIgnoreCase(tabFilename)) - { + if (file.getName().equalsIgnoreCase(tabFilename)) { return null; } // Find the first sibling with the matching filename, and TAB extension. - for (java.io.File child : parent.listFiles()) - { - if (!child.equals(file) && child.getName().equalsIgnoreCase(tabFilename)) - { + for (java.io.File child : parent.listFiles()) { + if (!child.equals(file) && child.getName().equalsIgnoreCase(tabFilename)) { return child; } } @@ -70,193 +62,152 @@ public static java.io.File getGCPSFileFor(java.io.File file) return null; } - public boolean canRead(java.io.File file) - { - if (file == null || !file.exists() || !file.canRead()) + public boolean canRead(java.io.File file) { + if (file == null || !file.exists() || !file.canRead()) { return false; + } java.io.FileReader fileReader = null; - try - { + try { fileReader = new java.io.FileReader(file); RasterControlPointList controlPoints = new RasterControlPointList(); return this.doCanRead(fileReader, controlPoints); - } - catch (Exception ignored) - { + } catch (Exception ignored) { return false; - } - finally - { + } finally { //noinspection EmptyCatchBlock - try - { - if (fileReader != null) + try { + if (fileReader != null) { fileReader.close(); - } - catch (java.io.IOException e) - { + } + } catch (java.io.IOException e) { } } } - public boolean canRead(String path) - { - if (path == null) + public boolean canRead(String path) { + if (path == null) { return false; + } Object streamOrException = WWIO.getFileOrResourceAsStream(path, this.getClass()); - if (streamOrException == null || streamOrException instanceof Exception) + if (streamOrException == null || streamOrException instanceof Exception) { return false; + } java.io.InputStream stream = (java.io.InputStream) streamOrException; - try - { + try { java.io.InputStreamReader streamReader = new java.io.InputStreamReader(stream); RasterControlPointList controlPoints = new RasterControlPointList(); return this.doCanRead(streamReader, controlPoints); - } - catch (Exception ignored) - { + } catch (Exception ignored) { return false; - } - finally - { - try - { + } finally { + try { stream.close(); - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { String message = Logging.getMessage("generic.ExceptionClosingStream", stream); Logging.logger().severe(message); } } } - - public RasterControlPointList read(java.io.File file) throws java.io.IOException - { - if (file == null) - { + + public RasterControlPointList read(java.io.File file) throws java.io.IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.canRead()) - { + if (!file.canRead()) { String message = Logging.getMessage("generic.FileNoReadPermission", file); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.io.FileReader fileReader = null; - try - { + try { fileReader = new java.io.FileReader(file); RasterControlPointList controlPoints = new RasterControlPointList(); this.doRead(fileReader, controlPoints); return controlPoints; - } - finally - { - try - { - if (fileReader != null) + } finally { + try { + if (fileReader != null) { fileReader.close(); - } - catch (java.io.IOException e) - { + } + } catch (java.io.IOException e) { String message = Logging.getMessage("generic.ExceptionClosingStream", file); Logging.logger().severe(message); } } } - public RasterControlPointList read(String path) throws java.io.IOException - { - if (path == null) - { + public RasterControlPointList read(String path) throws java.io.IOException { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object streamOrException = WWIO.getFileOrResourceAsStream(path, this.getClass()); - if (streamOrException == null || streamOrException instanceof Exception) - { + if (streamOrException == null || streamOrException instanceof Exception) { String message = Logging.getMessage("generic.ExceptionAttemptingToReadFile", - (streamOrException != null) ? streamOrException : path); + (streamOrException != null) ? streamOrException : path); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.io.InputStream stream = (java.io.InputStream) streamOrException; - try - { + try { java.io.InputStreamReader streamReader = new java.io.InputStreamReader(stream); RasterControlPointList controlPoints = new RasterControlPointList(); this.doRead(streamReader, controlPoints); return controlPoints; - } - finally - { - try - { + } finally { + try { stream.close(); - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { String message = Logging.getMessage("generic.ExceptionClosingStream", stream); Logging.logger().severe(message); } } } - protected boolean doCanRead(java.io.Reader reader, RasterControlPointList controlPoints) - { - if (reader == null) - { + protected boolean doCanRead(java.io.Reader reader, RasterControlPointList controlPoints) { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { java.io.BufferedReader br = new java.io.BufferedReader(reader); String line = this.nextLine(br); java.util.regex.Pattern pattern = this.createPattern(); return pattern.matcher(line).matches(); - } - catch (Exception e) - { + } catch (Exception e) { return false; } } - protected void doRead(java.io.Reader reader, RasterControlPointList controlPoints) throws java.io.IOException - { - if (reader == null) - { + protected void doRead(java.io.Reader reader, RasterControlPointList controlPoints) throws java.io.IOException { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -267,16 +218,13 @@ protected void doRead(java.io.Reader reader, RasterControlPointList controlPoint } protected void readControlPoints(java.io.BufferedReader reader, RasterControlPointList controlPoints) - throws java.io.IOException - { - if (reader == null) - { + throws java.io.IOException { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -286,8 +234,7 @@ protected void readControlPoints(java.io.BufferedReader reader, RasterControlPoi String line; java.util.regex.Matcher matcher; - while ((line = this.nextLine(reader)) != null && (matcher = pattern.matcher(line)).matches()) - { + while ((line = this.nextLine(reader)) != null && (matcher = pattern.matcher(line)).matches()) { String swx = matcher.group(1); String swy = matcher.group(2); String srx = matcher.group(3); @@ -298,17 +245,15 @@ protected void readControlPoints(java.io.BufferedReader reader, RasterControlPoi Double rx = parseDouble(srx); Double ry = parseDouble(sry); - if (wx != null && wy != null && rx != null && ry != null) - { - RasterControlPointList.ControlPoint controlPoint = - new RasterControlPointList.ControlPoint(wx, wy, rx, ry); + if (wx != null && wy != null && rx != null && ry != null) { + RasterControlPointList.ControlPoint controlPoint + = new RasterControlPointList.ControlPoint(wx, wy, rx, ry); controlPoints.add(controlPoint); } } } - protected java.util.regex.Pattern createPattern() - { + protected java.util.regex.Pattern createPattern() { String delim = this.getDelimiter(); StringBuilder sb = new StringBuilder(); @@ -323,29 +268,24 @@ protected java.util.regex.Pattern createPattern() return java.util.regex.Pattern.compile(sb.toString()); } - protected String nextLine(java.io.BufferedReader reader) throws java.io.IOException - { + protected String nextLine(java.io.BufferedReader reader) throws java.io.IOException { // Read until the next non-whitespace line. String line; - while ((line = reader.readLine()) != null && line.trim().length() == 0) - { + while ((line = reader.readLine()) != null && line.trim().length() == 0) { } return (line != null) ? line.trim() : null; } - private static Double parseDouble(String s) - { - if (s == null || s.length() == 0) + private static Double parseDouble(String s) { + if (s == null || s.length() == 0) { return null; + } - try - { + try { return Double.parseDouble(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONConstants.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONConstants.java index 3a544f5451..8af2a6571e 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONConstants.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONConstants.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: GeoJSONConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface GeoJSONConstants -{ +public interface GeoJSONConstants { + final String FIELD_TYPE = "type"; final String FIELD_CRS = "crs"; final String FIELD_BBOX = "bbox"; diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONCoordinateParser.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONCoordinateParser.java index 3dfe635b5c..0c3523aefa 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONCoordinateParser.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONCoordinateParser.java @@ -17,23 +17,20 @@ * @author dcollins * @version $Id: GeoJSONCoordinateParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONCoordinateParser extends GeoJSONEventParser -{ +public class GeoJSONCoordinateParser extends GeoJSONEventParser { + protected static final int INITIAL_POSITION_BUFFER_CAPACITY = 2; protected DoubleBuffer posBuffer; protected int startPos; protected int endPos; - public GeoJSONCoordinateParser() - { + public GeoJSONCoordinateParser() { } @Override - protected Object parseArray(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isStartArray()) - { + protected Object parseArray(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isStartArray()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -43,17 +40,11 @@ protected Object parseArray(JSONEventParserContext ctx, JSONEvent event) throws // This array may either represent a single tuple, or a complex array of tuples or arrays. We peek at the next // event to determine if this array is a simple tuple or a complex structure. - - if (nextEvent != null && nextEvent.isNumericValue()) - { + if (nextEvent != null && nextEvent.isNumericValue()) { return this.parseSimpleArray(ctx, event); - } - else if (nextEvent != null && nextEvent.isStartArray()) - { + } else if (nextEvent != null && nextEvent.isStartArray()) { return this.parseComplexArray(ctx, event); - } - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnexpectedEvent", event)); return null; } @@ -62,21 +53,16 @@ else if (nextEvent != null && nextEvent.isStartArray()) //**************************************************************// //******************** Position Parsing **********************// //**************************************************************// - - protected void startPositionArray() - { + protected void startPositionArray() { this.startPos = (this.posBuffer != null) ? this.posBuffer.position() : 0; } - protected void endPositionArray() - { + protected void endPositionArray() { this.endPos = (this.posBuffer != null) ? this.posBuffer.position() : 0; } - protected int parsePosition(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isStartArray()) - { + protected int parsePosition(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isStartArray()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -85,24 +71,25 @@ protected int parsePosition(JSONEventParserContext ctx, JSONEvent event) throws int numRead = 0; // The first iteration consumes the position's start array event. - for (event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isEndArray()) + if (event.isEndArray()) { break; + } - if (!event.isNumericValue()) - { + if (!event.isNumericValue()) { Logging.logger().warning(Logging.getMessage("generic.UnexpectedEvent", event)); continue; } - if (this.posBuffer == null) + if (this.posBuffer == null) { this.posBuffer = this.allocatePositionBuffer(INITIAL_POSITION_BUFFER_CAPACITY); - else if (this.posBuffer.remaining() == 0) + } else if (this.posBuffer.remaining() == 0) { this.expandPositionBuffer(1 + this.posBuffer.capacity()); + } this.posBuffer.put(event.asNumericValue()); numRead++; @@ -111,32 +98,27 @@ else if (this.posBuffer.remaining() == 0) return numRead; } - protected Object resolvePositionArray(int positionSize) - { - if (this.posBuffer == null || this.startPos == this.endPos) + protected Object resolvePositionArray(int positionSize) { + if (this.posBuffer == null || this.startPos == this.endPos) { return null; + } return new GeoJSONPositionArray(positionSize, this.posBuffer, this.startPos, this.endPos); } - protected DoubleBuffer allocatePositionBuffer(int capacity) - { + protected DoubleBuffer allocatePositionBuffer(int capacity) { return Buffers.newDirectDoubleBuffer(capacity); } - protected void expandPositionBuffer(int minCapacity) - { + protected void expandPositionBuffer(int minCapacity) { int newCapacity = 2 * this.posBuffer.capacity(); // If the new capacity overflows the range of 32-bit integers, then use the largest 32-bit integer. - if (newCapacity < 0) - { + if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; - } - // If the new capacity is still not large enough for the minimum capacity specified, then just use the minimum + } // If the new capacity is still not large enough for the minimum capacity specified, then just use the minimum // capacity specified. - else if (newCapacity < minCapacity) - { + else if (newCapacity < minCapacity) { newCapacity = minCapacity; } @@ -147,11 +129,8 @@ else if (newCapacity < minCapacity) //**************************************************************// //******************** Simple Array Parsing ******************// //**************************************************************// - - protected Object parseSimpleArray(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isStartArray()) - { + protected Object parseSimpleArray(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isStartArray()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -167,11 +146,8 @@ protected Object parseSimpleArray(JSONEventParserContext ctx, JSONEvent event) t //**************************************************************// //******************** Complex Array Parsing *****************// //**************************************************************// - - protected Object parseComplexArray(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isStartArray()) - { + protected Object parseComplexArray(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isStartArray()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -180,10 +156,8 @@ protected Object parseComplexArray(JSONEventParserContext ctx, JSONEvent event) // This array may either represent an array of tuples or an array of arrays. We advance to the first child // array's start element and peek at its first value to determine which. Both parseArrayOfPositions() and // parseArrayOfArrays() expect to start at the first child array's start element. - event = ctx.nextEvent(); - if (event == null || !event.isStartArray()) - { + if (event == null || !event.isStartArray()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -191,23 +165,18 @@ protected Object parseComplexArray(JSONEventParserContext ctx, JSONEvent event) JSONEvent peek = ctx.peek(); - if (peek != null && peek.isNumericValue()) + if (peek != null && peek.isNumericValue()) { return this.parseArrayOfPositions(ctx, event); - - else if (peek != null && peek.isStartArray()) + } else if (peek != null && peek.isStartArray()) { return this.parseArrayOfArrays(ctx, event); - - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnexpectedEvent", peek)); return null; } } - protected Object parseArrayOfPositions(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isStartArray()) - { + protected Object parseArrayOfPositions(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isStartArray()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -218,20 +187,22 @@ protected Object parseArrayOfPositions(JSONEventParserContext ctx, JSONEvent eve // Assume that we start parsing at a position's start array element. We let parsePosition() consume the // position's start element. - for (; ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (; ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isEndArray()) + if (event.isEndArray()) { break; + } int numRead = this.parsePosition(ctx, event); // Compute the size of a position in this array. Assume that the number of coordinates in the first position // is consistent with the remaining positions in this array. - if (posSize < 0) + if (posSize < 0) { posSize = numRead; + } } this.endPositionArray(); @@ -239,10 +210,8 @@ protected Object parseArrayOfPositions(JSONEventParserContext ctx, JSONEvent eve return this.resolvePositionArray(posSize); } - protected Object parseArrayOfArrays(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isStartArray()) - { + protected Object parseArrayOfArrays(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isStartArray()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -252,20 +221,23 @@ protected Object parseArrayOfArrays(JSONEventParserContext ctx, JSONEvent event) // Assume that we start parsing at a child array's start array element. We let parseComplexArray() consume the // child array's start element. - for (; ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (; ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isEndArray()) + if (event.isEndArray()) { break; + } Object o = this.parseComplexArray(ctx, event); - if (o == null) + if (o == null) { continue; + } - if (list == null) + if (list == null) { list = new ArrayList(); + } list.add(o); } @@ -273,34 +245,26 @@ protected Object parseArrayOfArrays(JSONEventParserContext ctx, JSONEvent event) return this.resolveArrayOfArrays(list); } - protected Object resolveArrayOfArrays(List list) - { - if (list == null || list.size() == 0) + protected Object resolveArrayOfArrays(List list) { + if (list == null || list.size() == 0) { return null; + } - if (list.get(0) instanceof GeoJSONPositionArray) - { + if (list.get(0) instanceof GeoJSONPositionArray) { GeoJSONPositionArray[] a = new GeoJSONPositionArray[list.size()]; - for (int i = 0; i < list.size(); i++) - { + for (int i = 0; i < list.size(); i++) { a[i] = (GeoJSONPositionArray) list.get(i); } return a; - } - else if (list.get(0) instanceof List) - { + } else if (list.get(0) instanceof List) { GeoJSONPositionArray[][] a = new GeoJSONPositionArray[list.size()][]; - for (int i = 0; i < list.size(); i++) - { - for (int j = 0; j < ((List) list.get(i)).size(); j++) - { + for (int i = 0; i < list.size(); i++) { + for (int j = 0; j < ((List) list.get(i)).size(); j++) { a[i][j] = (GeoJSONPositionArray) ((List) list.get(i)).get(j); } } return a; - } - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnexpectedObjectType", list.get(0))); return null; } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONDoc.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONDoc.java index bf0804bccb..bc2288511e 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONDoc.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONDoc.java @@ -14,22 +14,19 @@ * @author dcollins * @version $Id: GeoJSONDoc.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONDoc extends JSONDoc -{ - public GeoJSONDoc(Object source) - { +public class GeoJSONDoc extends JSONDoc { + + public GeoJSONDoc(Object source) { super(source); } @Override - protected JSONEventParserContext createEventParserContext(JsonParser parser) throws IOException - { + protected JSONEventParserContext createEventParserContext(JsonParser parser) throws IOException { return new GeoJSONEventParserContext(parser); } @Override - protected JSONEventParser createRootObjectParser() throws IOException - { + protected JSONEventParser createRootObjectParser() throws IOException { return new GeoJSONEventParser(); } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONEventParser.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONEventParser.java index c99c8c1ccf..d4c76049c7 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONEventParser.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONEventParser.java @@ -11,59 +11,49 @@ * @author dcollins * @version $Id: GeoJSONEventParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONEventParser extends BasicJSONEventParser -{ - public GeoJSONEventParser() - { +public class GeoJSONEventParser extends BasicJSONEventParser { + + public GeoJSONEventParser() { } - protected Object resolveObject(JSONEventParserContext ctx, JSONEvent event) - { - if (this.fields == null) + protected Object resolveObject(JSONEventParserContext ctx, JSONEvent event) { + if (this.fields == null) { return super.resolveObject(ctx, event); + } Object type = this.fields.getValue(GeoJSONConstants.FIELD_TYPE); - if (GeoJSONConstants.TYPE_POINT.equals(type)) + if (GeoJSONConstants.TYPE_POINT.equals(type)) { return new GeoJSONPoint(this.fields); - - else if (GeoJSONConstants.TYPE_MULTI_POINT.equals(type)) + } else if (GeoJSONConstants.TYPE_MULTI_POINT.equals(type)) { return new GeoJSONMultiPoint(this.fields); - - else if (GeoJSONConstants.TYPE_LINE_STRING.equals(type)) + } else if (GeoJSONConstants.TYPE_LINE_STRING.equals(type)) { return new GeoJSONLineString(this.fields); - - else if (GeoJSONConstants.TYPE_MULTI_LINE_STRING.equals(type)) + } else if (GeoJSONConstants.TYPE_MULTI_LINE_STRING.equals(type)) { return new GeoJSONMultiLineString(this.fields); - - else if (GeoJSONConstants.TYPE_POLYGON.equals(type)) + } else if (GeoJSONConstants.TYPE_POLYGON.equals(type)) { return new GeoJSONPolygon(this.fields); - - else if (GeoJSONConstants.TYPE_MULTI_POLYGON.equals(type)) + } else if (GeoJSONConstants.TYPE_MULTI_POLYGON.equals(type)) { return new GeoJSONMultiPolygon(this.fields); - - else if (GeoJSONConstants.TYPE_GEOMETRY_COLLECTION.equals(type)) + } else if (GeoJSONConstants.TYPE_GEOMETRY_COLLECTION.equals(type)) { return new GeoJSONGeometryCollection(this.fields); - - else if (GeoJSONConstants.TYPE_FEATURE.equals(type)) + } else if (GeoJSONConstants.TYPE_FEATURE.equals(type)) { return new GeoJSONFeature(this.fields); - - else if (GeoJSONConstants.TYPE_FEATURE_COLLECTION.equals(type)) + } else if (GeoJSONConstants.TYPE_FEATURE_COLLECTION.equals(type)) { return new GeoJSONFeatureCollection(this.fields); - - else + } else { return super.resolveObject(ctx, event); + } } @SuppressWarnings({"SuspiciousToArrayCall"}) @Override - protected Object resolveArray(JSONEventParserContext ctx, JSONEvent event) - { - if (GeoJSONConstants.FIELD_FEATURES.equals(ctx.getCurrentFieldName())) + protected Object resolveArray(JSONEventParserContext ctx, JSONEvent event) { + if (GeoJSONConstants.FIELD_FEATURES.equals(ctx.getCurrentFieldName())) { return this.array.toArray(new GeoJSONFeature[this.array.size()]); - - else if (GeoJSONConstants.FIELD_GEOMETRIES.equals(ctx.getCurrentFieldName())) + } else if (GeoJSONConstants.FIELD_GEOMETRIES.equals(ctx.getCurrentFieldName())) { return this.array.toArray(new GeoJSONFeature[this.array.size()]); + } return super.resolveArray(ctx, event); } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONEventParserContext.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONEventParserContext.java index ad02cd0b6b..94b0446e83 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONEventParserContext.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONEventParserContext.java @@ -14,22 +14,19 @@ * @author dcollins * @version $Id: GeoJSONEventParserContext.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONEventParserContext extends BasicJSONEventParserContext -{ - public GeoJSONEventParserContext(JsonParser parser) throws IOException - { +public class GeoJSONEventParserContext extends BasicJSONEventParserContext { + + public GeoJSONEventParserContext(JsonParser parser) throws IOException { super(parser); this.registerEventParsers(); } @Override - public JSONEventParser getUnrecognizedParser() - { + public JSONEventParser getUnrecognizedParser() { return new GeoJSONEventParser(); } - protected void registerEventParsers() - { + protected void registerEventParsers() { this.registerParser(GeoJSONConstants.FIELD_COORDINATES, new GeoJSONCoordinateParser()); } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONFeature.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONFeature.java index 619c5ccac4..0dd9251058 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONFeature.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONFeature.java @@ -11,26 +11,22 @@ * @author dcollins * @version $Id: GeoJSONFeature.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONFeature extends GeoJSONObject -{ - public GeoJSONFeature(AVList fields) - { +public class GeoJSONFeature extends GeoJSONObject { + + public GeoJSONFeature(AVList fields) { super(fields); } @Override - public boolean isFeature() - { + public boolean isFeature() { return true; } - public GeoJSONGeometry getGeometry() - { + public GeoJSONGeometry getGeometry() { return (GeoJSONGeometry) this.getValue(GeoJSONConstants.FIELD_GEOMETRY); } - public AVList getProperties() - { + public AVList getProperties() { return (AVList) this.getValue(GeoJSONConstants.FIELD_PROPERTIES); } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONFeatureCollection.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONFeatureCollection.java index ad3fada00e..8b06b21adc 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONFeatureCollection.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONFeatureCollection.java @@ -11,21 +11,18 @@ * @author dcollins * @version $Id: GeoJSONFeatureCollection.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONFeatureCollection extends GeoJSONObject -{ - public GeoJSONFeatureCollection(AVList fields) - { +public class GeoJSONFeatureCollection extends GeoJSONObject { + + public GeoJSONFeatureCollection(AVList fields) { super(fields); } @Override - public boolean isFeatureCollection() - { + public boolean isFeatureCollection() { return true; } - public GeoJSONFeature[] getFeatures() - { + public GeoJSONFeature[] getFeatures() { return (GeoJSONFeature[]) this.getValue(GeoJSONConstants.FIELD_FEATURES); } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONGeometry.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONGeometry.java index 16c310d58f..9aaa803b51 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONGeometry.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONGeometry.java @@ -11,16 +11,14 @@ * @author dcollins * @version $Id: GeoJSONGeometry.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class GeoJSONGeometry extends GeoJSONObject -{ - protected GeoJSONGeometry(AVList fields) - { +public abstract class GeoJSONGeometry extends GeoJSONObject { + + protected GeoJSONGeometry(AVList fields) { super(fields); } @Override - public boolean isGeometry() - { + public boolean isGeometry() { return true; } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONGeometryCollection.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONGeometryCollection.java index 657ffb5993..8541ae8bde 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONGeometryCollection.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONGeometryCollection.java @@ -11,21 +11,18 @@ * @author dcollins * @version $Id: GeoJSONGeometryCollection.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONGeometryCollection extends GeoJSONGeometry -{ - public GeoJSONGeometryCollection(AVList fields) - { +public class GeoJSONGeometryCollection extends GeoJSONGeometry { + + public GeoJSONGeometryCollection(AVList fields) { super(fields); } @Override - public boolean isGeometryCollection() - { + public boolean isGeometryCollection() { return true; } - public GeoJSONGeometry[] getGeometries() - { + public GeoJSONGeometry[] getGeometries() { return (GeoJSONGeometry[]) this.getValue(GeoJSONConstants.FIELD_GEOMETRIES); } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONLineString.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONLineString.java index 40adef3c1e..6ec70d07b3 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONLineString.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONLineString.java @@ -11,21 +11,18 @@ * @author dcollins * @version $Id: GeoJSONLineString.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONLineString extends GeoJSONGeometry -{ - public GeoJSONLineString(AVList fields) - { +public class GeoJSONLineString extends GeoJSONGeometry { + + public GeoJSONLineString(AVList fields) { super(fields); } @Override - public boolean isLineString() - { + public boolean isLineString() { return true; } - public GeoJSONPositionArray getCoordinates() - { + public GeoJSONPositionArray getCoordinates() { return (GeoJSONPositionArray) this.getValue(GeoJSONConstants.FIELD_COORDINATES); } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiLineString.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiLineString.java index d1e33b5cf4..2ba5ac0690 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiLineString.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiLineString.java @@ -11,32 +11,27 @@ * @author dcollins * @version $Id: GeoJSONMultiLineString.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONMultiLineString extends GeoJSONGeometry -{ - public GeoJSONMultiLineString(AVList fields) - { +public class GeoJSONMultiLineString extends GeoJSONGeometry { + + public GeoJSONMultiLineString(AVList fields) { super(fields); } @Override - public boolean isMultiLineString() - { + public boolean isMultiLineString() { return true; } - public int getLineStringCount() - { + public int getLineStringCount() { GeoJSONPositionArray array = this.getCoordinates(0); return array != null ? array.length() : 0; } - public GeoJSONPositionArray[] getCoordinates() - { + public GeoJSONPositionArray[] getCoordinates() { return (GeoJSONPositionArray[]) this.getValue(GeoJSONConstants.FIELD_COORDINATES); } - public GeoJSONPositionArray getCoordinates(int lineString) - { + public GeoJSONPositionArray getCoordinates(int lineString) { GeoJSONPositionArray[] array = this.getCoordinates(); return array != null ? array[lineString] : null; } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiPoint.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiPoint.java index fa5e9e3847..43e093c4c5 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiPoint.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiPoint.java @@ -12,32 +12,27 @@ * @author dcollins * @version $Id: GeoJSONMultiPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONMultiPoint extends GeoJSONGeometry -{ - public GeoJSONMultiPoint(AVList fields) - { +public class GeoJSONMultiPoint extends GeoJSONGeometry { + + public GeoJSONMultiPoint(AVList fields) { super(fields); } @Override - public boolean isMultiPoint() - { + public boolean isMultiPoint() { return true; } - public GeoJSONPositionArray getCoordinates() - { + public GeoJSONPositionArray getCoordinates() { return (GeoJSONPositionArray) this.getValue(GeoJSONConstants.FIELD_COORDINATES); } - public int getPointCount() - { + public int getPointCount() { GeoJSONPositionArray array = this.getCoordinates(); return array != null ? array.length() : 0; } - public Position getPosition(int point) - { + public Position getPosition(int point) { GeoJSONPositionArray array = this.getCoordinates(); return array != null ? array.getPosition(point) : null; } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiPolygon.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiPolygon.java index 061eb62784..de5ee0328b 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiPolygon.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONMultiPolygon.java @@ -13,56 +13,47 @@ * @author dcollins * @version $Id: GeoJSONMultiPolygon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONMultiPolygon extends GeoJSONGeometry -{ - public GeoJSONMultiPolygon(AVList fields) - { +public class GeoJSONMultiPolygon extends GeoJSONGeometry { + + public GeoJSONMultiPolygon(AVList fields) { super(fields); } @Override - public boolean isMultiPolygon() - { + public boolean isMultiPolygon() { return true; } - public GeoJSONPositionArray[][] getCoordinates() - { + public GeoJSONPositionArray[][] getCoordinates() { return (GeoJSONPositionArray[][]) this.getValue(GeoJSONConstants.FIELD_COORDINATES); } - public int getPolygonCount() - { + public int getPolygonCount() { GeoJSONPositionArray[][] array = this.getCoordinates(); return array != null ? array.length : 0; } - public int getInteriorRingCount(int polygon) - { + public int getInteriorRingCount(int polygon) { GeoJSONPositionArray[] array = this.getCoordinates(polygon); return array != null && array.length > 1 ? array.length - 1 : 0; } - public GeoJSONPositionArray[] getCoordinates(int polygon) - { + public GeoJSONPositionArray[] getCoordinates(int polygon) { GeoJSONPositionArray[][] array = this.getCoordinates(); return array != null && array.length > 0 ? array[polygon] : null; } - public GeoJSONPositionArray getExteriorRing(int polygon) - { + public GeoJSONPositionArray getExteriorRing(int polygon) { GeoJSONPositionArray[] array = this.getCoordinates(polygon); return array != null && array.length > 0 ? array[0] : null; } - public GeoJSONPositionArray getInteriorRing(int polygon, int ring) - { + public GeoJSONPositionArray getInteriorRing(int polygon, int ring) { GeoJSONPositionArray[] array = this.getCoordinates(polygon); return array != null && array.length > 1 ? array[1 + ring] : null; } - public GeoJSONPositionArray[] getInteriorRings(int polygon) - { + public GeoJSONPositionArray[] getInteriorRings(int polygon) { GeoJSONPositionArray[] array = this.getCoordinates(polygon); return array != null && array.length > 1 ? Arrays.copyOfRange(array, 1, array.length) : null; } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONObject.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONObject.java index fb459aab4b..eb26662c6d 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONObject.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONObject.java @@ -11,131 +11,107 @@ * @author dcollins * @version $Id: GeoJSONObject.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONObject extends AVListImpl -{ - public GeoJSONObject(AVList fields) - { - if (fields != null) +public class GeoJSONObject extends AVListImpl { + + public GeoJSONObject(AVList fields) { + if (fields != null) { this.setValues(fields); + } } - public String getType() - { + public String getType() { return (String) this.getValue(GeoJSONConstants.FIELD_TYPE); } - public AVList getCRS() - { + public AVList getCRS() { return (AVList) this.getValue(GeoJSONConstants.FIELD_CRS); } - public Object[] getBoundingBox() - { + public Object[] getBoundingBox() { return (Object[]) this.getValue(GeoJSONConstants.FIELD_BBOX); } - public boolean isGeometry() - { + public boolean isGeometry() { return false; } - public boolean isGeometryCollection() - { + public boolean isGeometryCollection() { return false; } - public boolean isFeature() - { + public boolean isFeature() { return false; } - public boolean isFeatureCollection() - { + public boolean isFeatureCollection() { return false; } - public boolean isPoint() - { + public boolean isPoint() { return false; } - public boolean isMultiPoint() - { + public boolean isMultiPoint() { return false; } - public boolean isLineString() - { + public boolean isLineString() { return false; } - public boolean isMultiLineString() - { + public boolean isMultiLineString() { return false; } - public boolean isPolygon() - { + public boolean isPolygon() { return false; } - public boolean isMultiPolygon() - { + public boolean isMultiPolygon() { return false; } - public GeoJSONGeometry asGeometry() - { + public GeoJSONGeometry asGeometry() { return (GeoJSONGeometry) this; } - public GeoJSONGeometryCollection asGeometryCollection() - { + public GeoJSONGeometryCollection asGeometryCollection() { return (GeoJSONGeometryCollection) this; } - public GeoJSONFeature asFeature() - { + public GeoJSONFeature asFeature() { return (GeoJSONFeature) this; } - public GeoJSONFeatureCollection asFeatureCollection() - { + public GeoJSONFeatureCollection asFeatureCollection() { return (GeoJSONFeatureCollection) this; } - public GeoJSONPoint asPoint() - { + public GeoJSONPoint asPoint() { return (GeoJSONPoint) this; } - public GeoJSONMultiPoint asMultiPoint() - { + public GeoJSONMultiPoint asMultiPoint() { return (GeoJSONMultiPoint) this; } - public GeoJSONLineString asLineString() - { + public GeoJSONLineString asLineString() { return (GeoJSONLineString) this; } - public GeoJSONMultiLineString asMultiLineString() - { + public GeoJSONMultiLineString asMultiLineString() { return (GeoJSONMultiLineString) this; } - public GeoJSONPolygon asPolygon() - { + public GeoJSONPolygon asPolygon() { return (GeoJSONPolygon) this; } - public GeoJSONMultiPolygon asMultiPolygon() - { + public GeoJSONMultiPolygon asMultiPolygon() { return (GeoJSONMultiPolygon) this; } - public String toString() - { + public String toString() { Object o = this.getValue(GeoJSONConstants.FIELD_TYPE); return o != null ? o.toString() : super.toString(); } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONPoint.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONPoint.java index 9d95c095ab..a91160ca08 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONPoint.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONPoint.java @@ -12,27 +12,23 @@ * @author dcollins * @version $Id: GeoJSONPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONPoint extends GeoJSONGeometry -{ - public GeoJSONPoint(AVList fields) - { +public class GeoJSONPoint extends GeoJSONGeometry { + + public GeoJSONPoint(AVList fields) { super(fields); } @Override - public boolean isPoint() - { + public boolean isPoint() { return true; } - public Position getPosition() - { + public Position getPosition() { GeoJSONPositionArray array = this.getCoordinates(); return array != null ? array.getPosition(0) : null; } - protected GeoJSONPositionArray getCoordinates() - { + protected GeoJSONPositionArray getCoordinates() { return (GeoJSONPositionArray) this.getValue(GeoJSONConstants.FIELD_COORDINATES); } } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONPolygon.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONPolygon.java index c4cb0b9010..30543719b8 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONPolygon.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONPolygon.java @@ -13,44 +13,37 @@ * @author dcollins * @version $Id: GeoJSONPolygon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONPolygon extends GeoJSONGeometry -{ - public GeoJSONPolygon(AVList fields) - { +public class GeoJSONPolygon extends GeoJSONGeometry { + + public GeoJSONPolygon(AVList fields) { super(fields); } @Override - public boolean isPolygon() - { + public boolean isPolygon() { return true; } - public int getInteriorRingCount() - { + public int getInteriorRingCount() { GeoJSONPositionArray[] array = this.getCoordinates(); return array != null && array.length > 1 ? array.length - 1 : 0; } - public GeoJSONPositionArray[] getCoordinates() - { + public GeoJSONPositionArray[] getCoordinates() { return (GeoJSONPositionArray[]) this.getValue(GeoJSONConstants.FIELD_COORDINATES); } - public GeoJSONPositionArray getExteriorRing() - { + public GeoJSONPositionArray getExteriorRing() { GeoJSONPositionArray[] array = this.getCoordinates(); return array != null && array.length > 0 ? array[0] : null; } - public GeoJSONPositionArray getInteriorRing(int ring) - { + public GeoJSONPositionArray getInteriorRing(int ring) { GeoJSONPositionArray[] array = this.getCoordinates(); return array != null && array.length > 1 ? array[1 + ring] : null; } - public GeoJSONPositionArray[] getInteriorRings() - { + public GeoJSONPositionArray[] getInteriorRings() { GeoJSONPositionArray[] array = this.getCoordinates(); return array != null && array.length > 1 ? Arrays.copyOfRange(array, 1, array.length) : null; } diff --git a/src/gov/nasa/worldwind/formats/geojson/GeoJSONPositionArray.java b/src/gov/nasa/worldwind/formats/geojson/GeoJSONPositionArray.java index beb0e93a96..a8fa2cde3a 100644 --- a/src/gov/nasa/worldwind/formats/geojson/GeoJSONPositionArray.java +++ b/src/gov/nasa/worldwind/formats/geojson/GeoJSONPositionArray.java @@ -15,24 +15,21 @@ * @author dcollins * @version $Id: GeoJSONPositionArray.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoJSONPositionArray implements Iterable -{ +public class GeoJSONPositionArray implements Iterable { + protected int positionSize; protected DoubleBuffer buffer; protected int startPos; protected int endPos; - public GeoJSONPositionArray(int positionSize, DoubleBuffer buffer, int startPos, int endPos) - { - if (positionSize < 2) - { + public GeoJSONPositionArray(int positionSize, DoubleBuffer buffer, int startPos, int endPos) { + if (positionSize < 2) { String message = Logging.getMessage("generic.InvalidTupleSize", positionSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -44,48 +41,41 @@ public GeoJSONPositionArray(int positionSize, DoubleBuffer buffer, int startPos, this.endPos = endPos; } - public int length() - { + public int length() { return (this.endPos - this.startPos) / this.positionSize; } - public Position getPosition(int index) - { + public Position getPosition(int index) { // GeoJSON coordinates are stored as lon,lat or lon,lat,altitude. int pos = this.startPos + this.positionSize * index; - return (this.positionSize >= 3) ? - Position.fromDegrees(this.buffer.get(pos + 1), this.buffer.get(pos), this.buffer.get(pos + 2)) : - Position.fromDegrees(this.buffer.get(pos + 1), this.buffer.get(pos)); + return (this.positionSize >= 3) + ? Position.fromDegrees(this.buffer.get(pos + 1), this.buffer.get(pos), this.buffer.get(pos + 2)) + : Position.fromDegrees(this.buffer.get(pos + 1), this.buffer.get(pos)); } - public Iterator iterator() - { + public Iterator iterator() { return new PositionIterator(this); } - protected static class PositionIterator implements Iterator - { + protected static class PositionIterator implements Iterator { + protected GeoJSONPositionArray array; protected int index; - public PositionIterator(GeoJSONPositionArray array) - { + public PositionIterator(GeoJSONPositionArray array) { this.array = array; this.index = 0; } - public boolean hasNext() - { + public boolean hasNext() { return this.index < this.array.length(); } - public Position next() - { + public Position next() { return this.array.getPosition(this.index++); } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } } diff --git a/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java b/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java index 6abc170a25..3ec11ee1b3 100644 --- a/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java +++ b/src/gov/nasa/worldwind/formats/georss/GeoRSSParser.java @@ -22,31 +22,28 @@ * @author tag * @version $Id: GeoRSSParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class GeoRSSParser { -public class GeoRSSParser -{ public static final String GEORSS_URI = "http://www.georss.org/georss"; public static final String GML_URI = "http://www.opengis.net/gml"; - public static List parseFragment(String fragmentString, NamespaceContext nsc) - { + public static List parseFragment(String fragmentString, NamespaceContext nsc) { return parseShapes(fixNamespaceQualification(fragmentString)); } - public static List parseShapes(String docString) - { - if (docString == null) - { + public static List parseShapes(String docString) { + if (docString == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (docString.length() < 1) // avoid empty strings + { return null; + } - try - { + try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); @@ -54,55 +51,44 @@ public static List parseShapes(String docString) List shapes = parseShapes(doc); - if (shapes == null || shapes.size() < 1) - { + if (shapes == null || shapes.size() < 1) { Logging.logger().log(Level.WARNING, "GeoRSS.NoShapes", docString); return null; } return shapes; - } - catch (ParserConfigurationException e) - { + } catch (ParserConfigurationException e) { String message = Logging.getMessage("GeoRSS.ParserConfigurationException"); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("GeoRSS.IOExceptionParsing", docString); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); - } - catch (SAXException e) - { + } catch (SAXException e) { String message = Logging.getMessage("GeoRSS.IOExceptionParsing", docString); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - private static String fixNamespaceQualification(String xmlString) - { + private static String fixNamespaceQualification(String xmlString) { String lcaseString = xmlString.toLowerCase(); StringBuffer qualifiers = new StringBuffer(); - if (lcaseString.contains("georss:") && !lcaseString.contains(GEORSS_URI)) - { + if (lcaseString.contains("georss:") && !lcaseString.contains(GEORSS_URI)) { qualifiers.append(" xmlns:georss=\""); qualifiers.append(GEORSS_URI); qualifiers.append("\""); } - if (lcaseString.contains("gml:") && !lcaseString.contains(GML_URI)) - { + if (lcaseString.contains("gml:") && !lcaseString.contains(GML_URI)) { qualifiers.append(" xmlns:gml=\""); qualifiers.append(GML_URI); qualifiers.append("\""); } - if (qualifiers.length() > 0) - { + if (qualifiers.length() > 0) { StringBuffer sb = new StringBuffer(); sb.append(" parseShapes(File file) - { - if (file == null) - { + public static List parseShapes(File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(false); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); @@ -152,38 +134,29 @@ public static List parseShapes(File file) List shapes = parseShapes(doc); - if (shapes == null || shapes.size() < 1) - { + if (shapes == null || shapes.size() < 1) { Logging.logger().log(Level.WARNING, "GeoRSS.NoShapes", file.getPath()); return null; } return shapes; - } - catch (ParserConfigurationException e) - { + } catch (ParserConfigurationException e) { String message = Logging.getMessage("GeoRSS.ParserConfigurationException"); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("GeoRSS.IOExceptionParsing", file.getPath()); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); - } - catch (SAXException e) - { + } catch (SAXException e) { String message = Logging.getMessage("GeoRSS.IOExceptionParsing", file.getPath()); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - public static List parseShapes(Document xmlDoc) - { - if (xmlDoc == null) - { + public static List parseShapes(Document xmlDoc) { + if (xmlDoc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -194,108 +167,110 @@ public static List parseShapes(Document xmlDoc) // Shapes NodeList nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "where"); - if (nodes != null && nodes.getLength() > 0) + if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); + } nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "point"); - if (nodes != null && nodes.getLength() > 0) + if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); + } nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "line"); - if (nodes != null && nodes.getLength() > 0) + if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); + } nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "polygon"); - if (nodes != null && nodes.getLength() > 0) + if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); + } nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "box"); - if (nodes != null && nodes.getLength() > 0) + if (nodes != null && nodes.getLength() > 0) { addNodes(shapeNodes, nodes); + } // Attributes nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "radius"); - if (nodes != null && nodes.getLength() > 0) + if (nodes != null && nodes.getLength() > 0) { addNodes(attributeNodes, nodes); + } nodes = xmlDoc.getElementsByTagNameNS(GEORSS_URI, "elev"); - if (nodes != null && nodes.getLength() > 0) + if (nodes != null && nodes.getLength() > 0) { addNodes(attributeNodes, nodes); + } ArrayList shapes = new ArrayList(); - if (shapeNodes.size() < 1) + if (shapeNodes.size() < 1) { return null; // No warning here. Let the calling method inform of this case. - - for (Node node : shapeNodes) - { + } + for (Node node : shapeNodes) { Renderable shape = null; String localName = node.getLocalName(); - if (localName.equals("point")) + if (localName.equals("point")) { shape = makePointShape(node, attributeNodes); - - else if (localName.equals("where")) + } else if (localName.equals("where")) { shape = makeWhereShape(node); - - else if (localName.equals("line")) + } else if (localName.equals("line")) { shape = makeLineShape(node, attributeNodes); - - else if (localName.equals("polygon")) + } else if (localName.equals("polygon")) { shape = makePolygonShape(node, attributeNodes); - - else if (localName.equals("box")) + } else if (localName.equals("box")) { shape = makeBoxShape(node, attributeNodes); + } - if (shape != null) + if (shape != null) { shapes.add(shape); + } } return shapes; } - private static void addNodes(ArrayList nodeList, NodeList nodes) - { - for (int i = 0; i < nodes.getLength(); i++) - { + private static void addNodes(ArrayList nodeList, NodeList nodes) { + for (int i = 0; i < nodes.getLength(); i++) { nodeList.add(nodes.item(i)); } } - private static Renderable makeWhereShape(Node node) - { + private static Renderable makeWhereShape(Node node) { Node typeNode = findChildByLocalName(node, "Polygon"); - if (typeNode != null) + if (typeNode != null) { return makeGMLPolygonShape(typeNode); + } typeNode = findChildByLocalName(node, "Envelope"); - if (typeNode != null) + if (typeNode != null) { return makeGMLEnvelopeShape(typeNode); + } typeNode = findChildByLocalName(node, "LineString"); - if (typeNode != null) + if (typeNode != null) { return makeGMLineStringShape(typeNode); + } typeNode = findChildByLocalName(node, "Point"); - if (typeNode != null) + if (typeNode != null) { return makeGMLPointShape(typeNode); + } Logging.logger().log(Level.WARNING, "GeoRSS.MissingElementContent", "where"); return null; } - private static Renderable makeGMLPolygonShape(Node node) - { + private static Renderable makeGMLPolygonShape(Node node) { Node n = findChildByLocalName(node, "exterior"); - if (n == null) - { + if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElement", "exterior"); return null; } n = findChildByLocalName(n, "LinearRing"); - if (n == null) - { + if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElement", "LinearRing"); return null; } @@ -303,83 +278,69 @@ private static Renderable makeGMLPolygonShape(Node node) return makePolygonShape(n, null); } - private static Renderable makePolygonShape(Node node, Iterable attrs) - { + private static Renderable makePolygonShape(Node node, Iterable attrs) { String valuesString = node.getTextContent(); - if (valuesString == null) - { + if (valuesString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.NoCoordinates", node.getLocalName()); return null; } ArrayList values = getDoubleValues(valuesString); - if (values.size() < 8 || values.size() % 2 != 0) - { + if (values.size() < 8 || values.size() % 2 != 0) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", node.getLocalName()); return null; } ArrayList positions = new ArrayList<>(); - for (int i = 0; i < values.size(); i += 2) - { + for (int i = 0; i < values.size(); i += 2) { positions.add(LatLon.fromDegrees(values.get(i), values.get(i + 1))); } double elevation = attrs != null ? getElevation(node, attrs) : 0d; - if (elevation != 0) - { + if (elevation != 0) { Polyline pl = new Polyline(positions, elevation); pl.setFilled(true); pl.setPathType(Polyline.GREAT_CIRCLE); return pl; - } - else - { + } else { return new SurfacePolygon(positions); } } - private static Renderable makeGMLEnvelopeShape(Node node) - { + private static Renderable makeGMLEnvelopeShape(Node node) { Node n = findChildByLocalName(node, "lowerCorner"); - if (n == null) - { + if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElement", " lowerCorner"); return null; } String lowerCornerString = n.getTextContent(); - if (lowerCornerString == null) - { + if (lowerCornerString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " lowerCorner"); return null; } n = findChildByLocalName(node, "upperCorner"); - if (n == null) - { + if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " upperCorner"); return null; } String upperCornerString = n.getTextContent(); - if (upperCornerString == null) - { + if (upperCornerString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " upperCorner"); return null; } ArrayList lv = getDoubleValues(lowerCornerString); - if (lv.size() != 2) - { + if (lv.size() != 2) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " lowerCorner"); return null; } ArrayList uv = getDoubleValues(upperCornerString); - if (uv.size() != 2) - { + if (uv.size() != 2) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", " upperCorner"); return null; } @@ -387,35 +348,31 @@ private static Renderable makeGMLEnvelopeShape(Node node) return new SurfaceSector(Sector.fromDegrees(lv.get(0), uv.get(0), lv.get(1), uv.get(1))); } - private static Renderable makeBoxShape(Node node, Iterable attrs) - { + private static Renderable makeBoxShape(Node node, Iterable attrs) { String valuesString = node.getTextContent(); - if (valuesString == null) - { + if (valuesString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.NoCoordinates", node.getLocalName()); return null; } ArrayList p = getDoubleValues(valuesString); - if (p.size() != 4) - { + if (p.size() != 4) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", node.getLocalName()); return null; } double elevation = getElevation(node, attrs); - if (elevation != 0) + if (elevation != 0) { return new Quadrilateral(LatLon.fromDegrees(p.get(0), p.get(1)), - LatLon.fromDegrees(p.get(2), p.get(3)), elevation); - else + LatLon.fromDegrees(p.get(2), p.get(3)), elevation); + } else { return new SurfaceSector(Sector.fromDegrees(p.get(0), p.get(2), p.get(1), p.get(3))); + } } - private static Renderable makeGMLineStringShape(Node node) - { + private static Renderable makeGMLineStringShape(Node node) { Node n = findChildByLocalName(node, "posList"); - if (n == null) - { + if (n == null) { Logging.logger().log(Level.WARNING, "GeoRSS.MissingElement", "posList"); return null; } @@ -423,102 +380,90 @@ private static Renderable makeGMLineStringShape(Node node) return makeLineShape(n, null); } - private static Renderable makeLineShape(Node node, Iterable attrs) - { + private static Renderable makeLineShape(Node node, Iterable attrs) { String valuesString = node.getTextContent(); - if (valuesString == null) - { + if (valuesString == null) { Logging.logger().log(Level.WARNING, "GeoRSS.NoCoordinates", node.getLocalName()); return null; } ArrayList values = getDoubleValues(valuesString); - if (values.size() < 4) - { + if (values.size() < 4) { Logging.logger().log(Level.WARNING, "GeoRSS.InvalidCoordinateCount", node.getLocalName()); return null; } ArrayList positions = new ArrayList(); - for (int i = 0; i < values.size(); i += 2) - { + for (int i = 0; i < values.size(); i += 2) { positions.add(LatLon.fromDegrees(values.get(i), values.get(i + 1))); } double elevation = attrs != null ? getElevation(node, attrs) : 0d; - if (elevation != 0) - { + if (elevation != 0) { Polyline pl = new Polyline(positions, elevation); pl.setPathType(Polyline.GREAT_CIRCLE); return pl; - } - else - { + } else { return new Polyline(positions, 0); } } @SuppressWarnings({"UnusedDeclaration"}) - private static Renderable makeGMLPointShape(Node node) - { + private static Renderable makeGMLPointShape(Node node) { return null; // No shape provided for points. Expect app to use icons. } @SuppressWarnings({"UnusedDeclaration"}) - private static Renderable makePointShape(Node node, Iterable attrs) - { + private static Renderable makePointShape(Node node, Iterable attrs) { return null; // No shape provided for points. Expect app to use icons. } - private static Node findChildByLocalName(Node parent, String localName) - { + private static Node findChildByLocalName(Node parent, String localName) { NodeList children = parent.getChildNodes(); - if (children == null || children.getLength() < 1) + if (children == null || children.getLength() < 1) { return null; + } - for (int i = 0; i < children.getLength(); i++) - { + for (int i = 0; i < children.getLength(); i++) { String ln = children.item(i).getLocalName(); - if (ln != null && ln.equals(localName)) + if (ln != null && ln.equals(localName)) { return children.item(i); + } } return null; } - private static Node findSiblingAttribute(String attrName, Iterable attribs, Node shapeNode) - { - for (Node attrib : attribs) - { - if (!attrib.getLocalName().equals(attrName)) + private static Node findSiblingAttribute(String attrName, Iterable attribs, Node shapeNode) { + for (Node attrib : attribs) { + if (!attrib.getLocalName().equals(attrName)) { continue; + } - if (attrib.getParentNode().equals(shapeNode.getParentNode())) + if (attrib.getParentNode().equals(shapeNode.getParentNode())) { return attrib; + } } return null; } - private static ArrayList getDoubleValues(String stringValues) - { + private static ArrayList getDoubleValues(String stringValues) { String[] tokens = stringValues.trim().split("[ ,\n]"); - if (tokens.length < 1) + if (tokens.length < 1) { return null; + } ArrayList arl = new ArrayList(); - for (String s : tokens) - { - if (s == null || s.length() < 1) + for (String s : tokens) { + if (s == null || s.length() < 1) { continue; + } double d; - try - { + try { d = Double.parseDouble(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.SEVERE, "GeoRSS.NumberFormatException", s); continue; } @@ -529,21 +474,16 @@ private static ArrayList getDoubleValues(String stringValues) return arl; } - private static double getElevation(Node shapeNode, Iterable attrs) - { + private static double getElevation(Node shapeNode, Iterable attrs) { double elevation = 0d; Node elevNode = findSiblingAttribute("elev", attrs, shapeNode); - if (elevNode != null) - { + if (elevNode != null) { ArrayList ev = getDoubleValues(elevNode.getTextContent()); - if (ev != null && ev.size() > 0) - { + if (ev != null && ev.size() > 0) { elevation = ev.get(0); - } - else - { - Logging.logger().log(Level.WARNING, "GeoRSS.MissingElementContent", "elev"); + } else { + Logging.logger().log(Level.WARNING, "GeoRSS.MissingElementContent", "elev"); } } diff --git a/src/gov/nasa/worldwind/formats/gpx/ElementParser.java b/src/gov/nasa/worldwind/formats/gpx/ElementParser.java index 2ebeef0068..e7088b3c06 100644 --- a/src/gov/nasa/worldwind/formats/gpx/ElementParser.java +++ b/src/gov/nasa/worldwind/formats/gpx/ElementParser.java @@ -11,8 +11,8 @@ * @author tag * @version $Id: ElementParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ElementParser -{ +public class ElementParser { + protected final String elementName; protected ElementParser currentElement = null; protected String currentCharacters = null; @@ -21,10 +21,8 @@ public class ElementParser * @param elementName the element's name, may not be null * @throws IllegalArgumentException if elementName is null */ - protected ElementParser(String elementName) - { - if (elementName == null) - { + protected ElementParser(String elementName) { + if (elementName == null) { String msg = Logging.getMessage("nullValue.ElementNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -33,8 +31,7 @@ protected ElementParser(String elementName) this.elementName = elementName; } - public String getElementName() - { + public String getElementName() { return this.elementName; } @@ -49,37 +46,33 @@ public String getElementName() * @throws IllegalArgumentException if any argument is null */ public void startElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { - if (uri == null) - { + throws org.xml.sax.SAXException { + if (uri == null) { String msg = Logging.getMessage("nullValue.URIIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (lname == null) - { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (qname == null) - { + if (qname == null) { String msg = Logging.getMessage("nullValue.QNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (attributes == null) - { + if (attributes == null) { String msg = Logging.getMessage("nullValue.org.xml.sax.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.currentElement != null) + if (this.currentElement != null) { this.currentElement.startElement(uri, lname, qname, attributes); - else + } else { this.doStartElement(uri, lname, qname, attributes); + } } /** @@ -88,34 +81,30 @@ public void startElement(String uri, String lname, String qname, org.xml.sax.Att * @param uri Element URI. * @param lname Element lname. * @param qname Element qname. - * @throws org.xml.sax.SAXException if a parsing error occurs. + * @throws org.xml.sax.SAXException if a parsing error occurs. * @throws IllegalArgumentException if any argument is null */ - public void endElement(String uri, String lname, String qname) throws org.xml.sax.SAXException - { - if (uri == null) - { + public void endElement(String uri, String lname, String qname) throws org.xml.sax.SAXException { + if (uri == null) { String msg = Logging.getMessage("nullValue.URIIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (lname == null) - { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (qname == null) - { + if (qname == null) { String msg = Logging.getMessage("nullValue.QNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.currentElement != null) - { + if (this.currentElement != null) { this.currentElement.endElement(uri, lname, qname); - if (lname.equalsIgnoreCase(this.currentElement.elementName)) + if (lname.equalsIgnoreCase(this.currentElement.elementName)) { this.currentElement = null; + } } this.doEndElement(uri, lname, qname); @@ -124,12 +113,10 @@ public void endElement(String uri, String lname, String qname) throws org.xml.sa } protected void doStartElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { + throws org.xml.sax.SAXException { } - protected void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException - { + protected void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException { } /** @@ -138,38 +125,34 @@ protected void doEndElement(String uri, String lname, String qname) throws org.x * @param length The length of the data. * @throws IllegalArgumentException if data has length less than 1 */ - public void characters(char[] data, int start, int length) - { - if (data == null) - { + public void characters(char[] data, int start, int length) { + if (data == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (data.length < 1) - { + if (data.length < 1) { String msg = Logging.getMessage("generic.ArrayInvalidLength", data.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (start < 0) - { + if (start < 0) { String msg = Logging.getMessage("generic.indexOutOfRange", start); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (start + length > data.length) - { + if (start + length > data.length) { String msg = Logging.getMessage("generic.indexOutOfRange", start + length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.currentElement != null) + if (this.currentElement != null) { this.currentElement.characters(data, start, length); - else if (this.currentCharacters != null) + } else if (this.currentCharacters != null) { this.currentCharacters += new String(data, start, length); - else + } else { this.currentCharacters = new String(data, start, length); + } } } diff --git a/src/gov/nasa/worldwind/formats/gpx/GpxReader.java b/src/gov/nasa/worldwind/formats/gpx/GpxReader.java index c58874a06e..2b58b6b806 100644 --- a/src/gov/nasa/worldwind/formats/gpx/GpxReader.java +++ b/src/gov/nasa/worldwind/formats/gpx/GpxReader.java @@ -17,11 +17,11 @@ */ public class GpxReader // TODO: I18N, proper exception handling, remove stack-trace prints { + private javax.xml.parsers.SAXParser parser; private java.util.List tracks = new java.util.ArrayList(); - public GpxReader() throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException - { + public GpxReader() throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); @@ -31,21 +31,18 @@ public GpxReader() throws javax.xml.parsers.ParserConfigurationException, org.xm /** * @param path The file spec to read from. * @throws IllegalArgumentException if path is null - * @throws java.io.IOException if no file exists at the location specified by path + * @throws java.io.IOException if no file exists at the location specified by path * @throws org.xml.sax.SAXException if a parsing error occurs. */ - public void readFile(String path) throws java.io.IOException, org.xml.sax.SAXException - { - if (path == null) - { + public void readFile(String path) throws java.io.IOException, org.xml.sax.SAXException { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } java.io.File file = new java.io.File(path); - if (!file.exists()) - { + if (!file.exists()) { String msg = Logging.getMessage("generic.FileNotFound", path); Logging.logger().severe(msg); throw new java.io.FileNotFoundException(path); @@ -61,10 +58,8 @@ public void readFile(String path) throws java.io.IOException, org.xml.sax.SAXExc * @throws java.io.IOException if a problem is encountered reading the stream. * @throws org.xml.sax.SAXException if a parsing error occurs. */ - public void readStream(java.io.InputStream stream) throws java.io.IOException, org.xml.sax.SAXException - { - if (stream == null) - { + public void readStream(java.io.InputStream stream) throws java.io.IOException, org.xml.sax.SAXException { + if (stream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -73,62 +68,51 @@ public void readStream(java.io.InputStream stream) throws java.io.IOException, o this.doRead(stream); } - public java.util.List getTracks() - { + public java.util.List getTracks() { return this.tracks; } - public Iterator getTrackPositionIterator() - { - return new Iterator() - { + public Iterator getTrackPositionIterator() { + return new Iterator() { private TrackPointIterator trackPoints = new TrackPointIteratorImpl(GpxReader.this.tracks); - public boolean hasNext() - { + public boolean hasNext() { return this.trackPoints.hasNext(); } - public Position next() - { + public Position next() { return this.trackPoints.next().getPosition(); } - public void remove() - { + public void remove() { this.trackPoints.remove(); } }; } - private void doRead(java.io.InputStream fis) throws java.io.IOException, org.xml.sax.SAXException - { + private void doRead(java.io.InputStream fis) throws java.io.IOException, org.xml.sax.SAXException { this.parser.parse(fis, new Handler()); } - private class Handler extends org.xml.sax.helpers.DefaultHandler - { + private class Handler extends org.xml.sax.helpers.DefaultHandler { // this is a private class used solely by the containing class, so no validation occurs in it. private gov.nasa.worldwind.formats.gpx.ElementParser currentElement = null; @Override - public void warning(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException - { + public void warning(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException { saxParseException.printStackTrace(); super.warning(saxParseException); } @Override - public void error(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException - { + public void error(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException { saxParseException.printStackTrace(); super.error(saxParseException); } @Override - public void fatalError(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException - { + public void fatalError(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException { saxParseException.printStackTrace(); super.fatalError(saxParseException); } @@ -137,28 +121,22 @@ public void fatalError(org.xml.sax.SAXParseException saxParseException) throws o @Override public void startElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { - if (this.firstElement) - { - if (!lname.equalsIgnoreCase("gpx")) + throws org.xml.sax.SAXException { + if (this.firstElement) { + if (!lname.equalsIgnoreCase("gpx")) { throw new IllegalArgumentException(Logging.getMessage("formats.notGPX", uri)); - else + } else { this.firstElement = false; + } } - if (this.currentElement != null) - { + if (this.currentElement != null) { this.currentElement.startElement(uri, lname, qname, attributes); - } - else if (lname.equalsIgnoreCase("trk")) - { + } else if (lname.equalsIgnoreCase("trk")) { GpxTrack track = new GpxTrack(uri, lname, qname, attributes); this.currentElement = track; GpxReader.this.tracks.add(track); - } - else if (lname.equalsIgnoreCase("rte")) - { + } else if (lname.equalsIgnoreCase("rte")) { GpxRoute route = new GpxRoute(uri, lname, qname, attributes); this.currentElement = route; GpxReader.this.tracks.add(route); @@ -166,22 +144,21 @@ else if (lname.equalsIgnoreCase("rte")) } @Override - public void endElement(String uri, String lname, String qname) throws org.xml.sax.SAXException - { - if (this.currentElement != null) - { + public void endElement(String uri, String lname, String qname) throws org.xml.sax.SAXException { + if (this.currentElement != null) { this.currentElement.endElement(uri, lname, qname); - if (lname.equalsIgnoreCase(this.currentElement.getElementName())) + if (lname.equalsIgnoreCase(this.currentElement.getElementName())) { this.currentElement = null; + } } } @Override - public void characters(char[] data, int start, int length) throws org.xml.sax.SAXException - { - if (this.currentElement != null) + public void characters(char[] data, int start, int length) throws org.xml.sax.SAXException { + if (this.currentElement != null) { this.currentElement.characters(data, start, length); + } } } } diff --git a/src/gov/nasa/worldwind/formats/gpx/GpxRoute.java b/src/gov/nasa/worldwind/formats/gpx/GpxRoute.java index 4f4cf54695..fcfef4fe61 100644 --- a/src/gov/nasa/worldwind/formats/gpx/GpxRoute.java +++ b/src/gov/nasa/worldwind/formats/gpx/GpxRoute.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.gpx; import gov.nasa.worldwind.tracks.Track; @@ -18,89 +17,75 @@ * @author tag * @version $Id: GpxRoute.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GpxRoute extends gov.nasa.worldwind.formats.gpx.ElementParser implements Track, TrackSegment -{ +public class GpxRoute extends gov.nasa.worldwind.formats.gpx.ElementParser implements Track, TrackSegment { + private String name; private java.util.List points = new java.util.ArrayList(); @SuppressWarnings({"UnusedDeclaration"}) - public GpxRoute(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - { + public GpxRoute(String uri, String lname, String qname, org.xml.sax.Attributes attributes) { super("rte"); // dont' validate uri, lname, qname or attributes as they aren't used. } - public List getSegments() - { + public List getSegments() { return Arrays.asList((TrackSegment) this); } - public String getName() - { + public String getName() { return this.name; } - public int getNumPoints() - { + public int getNumPoints() { return this.points.size(); } - public java.util.List getPoints() - { + public java.util.List getPoints() { return this.points; } @Override public void doStartElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { - if (lname == null) - { + throws org.xml.sax.SAXException { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (uri == null) - { + if (uri == null) { String msg = Logging.getMessage("nullValue.URIIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (qname == null) - { + if (qname == null) { String msg = Logging.getMessage("nullValue.QNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (attributes == null) - { + if (attributes == null) { String msg = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (lname.equalsIgnoreCase("rtept")) - { + if (lname.equalsIgnoreCase("rtept")) { this.currentElement = new GpxRoutePoint(uri, lname, qname, attributes); this.points.add((TrackPoint) this.currentElement); } } - + @Override - public void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException - { + public void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException { // don't validate uri or qname - they aren't used - if (lname == null) - { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - - if (lname.equalsIgnoreCase("name")) - { + + if (lname.equalsIgnoreCase("name")) { this.name = this.currentCharacters; } } diff --git a/src/gov/nasa/worldwind/formats/gpx/GpxRoutePoint.java b/src/gov/nasa/worldwind/formats/gpx/GpxRoutePoint.java index bfb9a4953b..ddb2600211 100644 --- a/src/gov/nasa/worldwind/formats/gpx/GpxRoutePoint.java +++ b/src/gov/nasa/worldwind/formats/gpx/GpxRoutePoint.java @@ -3,17 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.gpx; /** * @author tag * @version $Id: GpxRoutePoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GpxRoutePoint extends GpxTrackPoint -{ - public GpxRoutePoint(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - { +public class GpxRoutePoint extends GpxTrackPoint { + + public GpxRoutePoint(String uri, String lname, String qname, org.xml.sax.Attributes attributes) { super("rtept", uri, lname, qname, attributes); } } diff --git a/src/gov/nasa/worldwind/formats/gpx/GpxTrack.java b/src/gov/nasa/worldwind/formats/gpx/GpxTrack.java index a800db32fc..220f5cde9b 100644 --- a/src/gov/nasa/worldwind/formats/gpx/GpxTrack.java +++ b/src/gov/nasa/worldwind/formats/gpx/GpxTrack.java @@ -12,44 +12,40 @@ * @author tag * @version $Id: GpxTrack.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GpxTrack extends gov.nasa.worldwind.formats.gpx.ElementParser implements Track -{ +public class GpxTrack extends gov.nasa.worldwind.formats.gpx.ElementParser implements Track { + private String name; private int numPoints = -1; - private java.util.List segments = - new java.util.ArrayList(); + private java.util.List segments + = new java.util.ArrayList(); @SuppressWarnings({"UNUSED_SYMBOL", "UnusedDeclaration"}) - public GpxTrack(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - { + public GpxTrack(String uri, String lname, String qname, org.xml.sax.Attributes attributes) { super("trk"); // don't validate uri, lname, qname or attributes - they aren't used. } - public java.util.List getSegments() - { + public java.util.List getSegments() { return segments; } - public String getName() - { + public String getName() { return name; } - public int getNumPoints() - { - if (this.segments == null) + public int getNumPoints() { + if (this.segments == null) { return 0; + } - if (this.numPoints >= 0) + if (this.numPoints >= 0) { return this.numPoints; + } this.numPoints = 0; - for (TrackSegment segment : this.segments) - { + for (TrackSegment segment : this.segments) { //noinspection UNUSED_SYMBOL,UnusedDeclaration - for (TrackPoint point : segment.getPoints()) - { + for (TrackPoint point : segment.getPoints()) { ++this.numPoints; } } @@ -67,36 +63,30 @@ public int getNumPoints() */ @Override public void doStartElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { + throws org.xml.sax.SAXException { // don't validate uri, qname or attributes - they aren't used - if (lname == null) - { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (qname == null) - { + if (qname == null) { String msg = Logging.getMessage("nullValue.QNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (uri == null) - { + if (uri == null) { String msg = Logging.getMessage("nullValue.URIIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (attributes == null) - { + if (attributes == null) { String msg = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (lname.equalsIgnoreCase("trkSeg")) - { + if (lname.equalsIgnoreCase("trkSeg")) { this.currentElement = new GpxTrackSegment(uri, lname, qname, attributes); this.segments.add((TrackSegment) this.currentElement); } @@ -110,17 +100,14 @@ public void doStartElement(String uri, String lname, String qname, org.xml.sax.A * @throws org.xml.sax.SAXException if a parsing error occurs. */ @Override - public void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException - { + public void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException { // don't validate uri or qname - they aren't used - if (lname == null) - { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (lname.equalsIgnoreCase("name")) - { + if (lname.equalsIgnoreCase("name")) { this.name = this.currentCharacters; } } diff --git a/src/gov/nasa/worldwind/formats/gpx/GpxTrackPoint.java b/src/gov/nasa/worldwind/formats/gpx/GpxTrackPoint.java index 66081b35e4..fed9058bde 100644 --- a/src/gov/nasa/worldwind/formats/gpx/GpxTrackPoint.java +++ b/src/gov/nasa/worldwind/formats/gpx/GpxTrackPoint.java @@ -13,42 +13,34 @@ * @author tag * @version $Id: GpxTrackPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GpxTrackPoint extends gov.nasa.worldwind.formats.gpx.ElementParser implements TrackPoint -{ +public class GpxTrackPoint extends gov.nasa.worldwind.formats.gpx.ElementParser implements TrackPoint { + private double latitude; private double longitude; private double elevation; private String time; - - public GpxTrackPoint(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - { + + public GpxTrackPoint(String uri, String lname, String qname, org.xml.sax.Attributes attributes) { this("trkpt", uri, lname, qname, attributes); } @SuppressWarnings({"UnusedDeclaration"}) - protected GpxTrackPoint(String pointType, String uri, String lname, String qname, org.xml.sax.Attributes attributes) - { + protected GpxTrackPoint(String pointType, String uri, String lname, String qname, org.xml.sax.Attributes attributes) { super(pointType); //don't validate uri, lname or qname - they aren't used. - - if (attributes == null) - { + if (attributes == null) { String msg = Logging.getMessage("nullValue.org.xml.sax.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (int i = 0; i < attributes.getLength(); i++) - { + for (int i = 0; i < attributes.getLength(); i++) { String attrName = attributes.getLocalName(i); String attrValue = attributes.getValue(i); - if (attrName.equalsIgnoreCase("lat")) - { + if (attrName.equalsIgnoreCase("lat")) { this.latitude = Double.parseDouble(attrValue); - } - else if (attrName.equalsIgnoreCase("lon")) - { + } else if (attrName.equalsIgnoreCase("lon")) { this.longitude = Double.parseDouble(attrValue); } } @@ -56,8 +48,7 @@ else if (attrName.equalsIgnoreCase("lon")) @Override public void doStartElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { + throws org.xml.sax.SAXException { //don't perform validation here - no parameters are actually used } @@ -69,28 +60,22 @@ public void doStartElement(String uri, String lname, String qname, org.xml.sax.A * @throws org.xml.sax.SAXException if a parsing error occurs. */ @Override - public void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException - { - if (lname == null) - { + public void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // don't validate uri or qname - they aren't used. - if (lname.equalsIgnoreCase("ele")) - { + if (lname.equalsIgnoreCase("ele")) { this.elevation = Double.parseDouble(this.currentCharacters); - } - else if (lname.equalsIgnoreCase("time")) - { + } else if (lname.equalsIgnoreCase("time")) { this.time = this.currentCharacters.trim(); } } - public double getLatitude() - { + public double getLatitude() { return latitude; } @@ -98,10 +83,8 @@ public double getLatitude() * @param latitude The new latitude. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 */ - public void setLatitude(double latitude) - { - if (latitude > 90 || latitude < -90) - { + public void setLatitude(double latitude) { + if (latitude > 90 || latitude < -90) { String msg = Logging.getMessage("generic.AngleOutOfRange", latitude); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -110,8 +93,7 @@ public void setLatitude(double latitude) this.latitude = latitude; } - public double getLongitude() - { + public double getLongitude() { return longitude; } @@ -119,10 +101,8 @@ public double getLongitude() * @param longitude The new longitude. * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 */ - public void setLongitude(double longitude) - { - if (longitude > 180 || longitude < -180) - { + public void setLongitude(double longitude) { + if (longitude > 180 || longitude < -180) { String msg = Logging.getMessage("generic.AngleOutOfRange", longitude); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -131,25 +111,20 @@ public void setLongitude(double longitude) this.longitude = longitude; } - public double getElevation() - { + public double getElevation() { return elevation; } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.elevation = elevation; } - public Position getPosition() - { + public Position getPosition() { return Position.fromDegrees(this.latitude, this.longitude, this.elevation); } - public void setPosition(Position position) - { - if (position == null) - { + public void setPosition(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -160,8 +135,7 @@ public void setPosition(Position position) this.elevation = position.getElevation(); } - public String getTime() - { + public String getTime() { return time; } @@ -169,10 +143,8 @@ public String getTime() * @param time The new time. * @throws IllegalArgumentException if time is null */ - public void setTime(String time) - { - if (time == null) - { + public void setTime(String time) { + if (time == null) { String msg = Logging.getMessage("nullValue.TimeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -181,9 +153,8 @@ public void setTime(String time) } @Override - public String toString() - { + public String toString() { return String.format("(%10.6f\u00B0, %11.6f\u00B0, %10.4g m, %s)", this.latitude, this.longitude, - this.elevation, this.time); + this.elevation, this.time); } } diff --git a/src/gov/nasa/worldwind/formats/gpx/GpxTrackSegment.java b/src/gov/nasa/worldwind/formats/gpx/GpxTrackSegment.java index 11b81268ee..8c513b80c0 100644 --- a/src/gov/nasa/worldwind/formats/gpx/GpxTrackSegment.java +++ b/src/gov/nasa/worldwind/formats/gpx/GpxTrackSegment.java @@ -13,20 +13,18 @@ * @version $Id: GpxTrackSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class GpxTrackSegment extends gov.nasa.worldwind.formats.gpx.ElementParser - implements TrackSegment -{ - private java.util.List points = - new java.util.ArrayList(); + implements TrackSegment { - public GpxTrackSegment(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - { + private java.util.List points + = new java.util.ArrayList(); + + public GpxTrackSegment(String uri, String lname, String qname, org.xml.sax.Attributes attributes) { super("trkseg"); // dont' validate uri, lname, qname or attributes as they aren't used. } - public java.util.List getPoints() - { + public java.util.List getPoints() { return this.points; } @@ -40,36 +38,30 @@ public java.util.List getPoints() */ @Override public void doStartElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { - if (lname == null) - { + throws org.xml.sax.SAXException { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (uri == null) - { + if (uri == null) { String msg = Logging.getMessage("nullValue.URIIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (qname == null) - { + if (qname == null) { String msg = Logging.getMessage("nullValue.QNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (attributes == null) - { + if (attributes == null) { String msg = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (lname.equalsIgnoreCase("trkpt")) - { + if (lname.equalsIgnoreCase("trkpt")) { this.currentElement = new gov.nasa.worldwind.formats.gpx.GpxTrackPoint(uri, lname, qname, attributes); this.points.add((TrackPoint) this.currentElement); } diff --git a/src/gov/nasa/worldwind/formats/gpx/GpxWriter.java b/src/gov/nasa/worldwind/formats/gpx/GpxWriter.java index 3cc79fe83e..aeb64bd094 100644 --- a/src/gov/nasa/worldwind/formats/gpx/GpxWriter.java +++ b/src/gov/nasa/worldwind/formats/gpx/GpxWriter.java @@ -14,15 +14,13 @@ * @author dcollins * @version $Id: GpxWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GpxWriter -{ +public class GpxWriter { + private final org.w3c.dom.Document doc; private final javax.xml.transform.Result result; - public GpxWriter(String path) throws java.io.IOException, javax.xml.parsers.ParserConfigurationException - { - if (path == null) - { + public GpxWriter(String path) throws java.io.IOException, javax.xml.parsers.ParserConfigurationException { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -34,10 +32,8 @@ public GpxWriter(String path) throws java.io.IOException, javax.xml.parsers.Pars createGpxDocument(this.doc); } - public GpxWriter(java.io.OutputStream stream) throws java.io.IOException, javax.xml.parsers.ParserConfigurationException - { - if (stream == null) - { + public GpxWriter(java.io.OutputStream stream) throws java.io.IOException, javax.xml.parsers.ParserConfigurationException { + if (stream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -49,10 +45,8 @@ public GpxWriter(java.io.OutputStream stream) throws java.io.IOException, javax. createGpxDocument(this.doc); } - public void writeTrack(Track track) throws javax.xml.transform.TransformerException - { - if (track == null) - { + public void writeTrack(Track track) throws javax.xml.transform.TransformerException { + if (track == null) { String msg = Logging.getMessage("nullValue.TrackIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -62,20 +56,18 @@ public void writeTrack(Track track) throws javax.xml.transform.TransformerExcept doFlush(); } - public void close() - { + public void close() { // Intentionally left blank, // as a placeholder for future functionality. } - private void createGpxDocument(org.w3c.dom.Document doc) - { + private void createGpxDocument(org.w3c.dom.Document doc) { // Create the GPX document root when the document // doesn't already have a root element. - if (doc != null) - { - if (doc.getDocumentElement() != null) + if (doc != null) { + if (doc.getDocumentElement() != null) { doc.removeChild(doc.getDocumentElement()); + } doc.setXmlStandalone(false); @@ -86,50 +78,43 @@ private void createGpxDocument(org.w3c.dom.Document doc) } } - private void doWriteTrack(Track track, org.w3c.dom.Element elem) - { - if (track != null) - { + private void doWriteTrack(Track track, org.w3c.dom.Element elem) { + if (track != null) { org.w3c.dom.Element trk = this.doc.createElement("trk"); - if (track.getName() != null) - { + if (track.getName() != null) { org.w3c.dom.Element name = this.doc.createElement("name"); org.w3c.dom.Text nameText = this.doc.createTextNode(track.getName()); name.appendChild(nameText); trk.appendChild(name); } - if (track.getSegments() != null) - { - for (TrackSegment ts : track.getSegments()) + if (track.getSegments() != null) { + for (TrackSegment ts : track.getSegments()) { doWriteTrackSegment(ts, trk); + } } elem.appendChild(trk); } } - private void doWriteTrackSegment(TrackSegment segment, org.w3c.dom.Element elem) - { - if (segment != null) - { + private void doWriteTrackSegment(TrackSegment segment, org.w3c.dom.Element elem) { + if (segment != null) { org.w3c.dom.Element trkseg = this.doc.createElement("trkseg"); - if (segment.getPoints() != null) - { - for (TrackPoint tp : segment.getPoints()) + if (segment.getPoints() != null) { + for (TrackPoint tp : segment.getPoints()) { doWriteTrackPoint(tp, trkseg); + } } elem.appendChild(trkseg); } } - private void doWriteTrackPoint(TrackPoint point, org.w3c.dom.Element elem) - { - if (point != null) - { + private void doWriteTrackPoint(TrackPoint point, org.w3c.dom.Element elem) { + if (point != null) { org.w3c.dom.Element trkpt = this.doc.createElement("trkpt"); trkpt.setAttribute("lat", Double.toString(point.getLatitude())); trkpt.setAttribute("lon", Double.toString(point.getLongitude())); @@ -139,8 +124,7 @@ private void doWriteTrackPoint(TrackPoint point, org.w3c.dom.Element elem) ele.appendChild(eleText); trkpt.appendChild(ele); - if (point.getTime() != null) - { + if (point.getTime() != null) { org.w3c.dom.Element time = this.doc.createElement("time"); org.w3c.dom.Text timeText = this.doc.createTextNode(point.getTime()); time.appendChild(timeText); @@ -151,8 +135,7 @@ private void doWriteTrackPoint(TrackPoint point, org.w3c.dom.Element elem) } } - private void doFlush() throws javax.xml.transform.TransformerException - { + private void doFlush() throws javax.xml.transform.TransformerException { javax.xml.transform.TransformerFactory factory = javax.xml.transform.TransformerFactory.newInstance(); javax.xml.transform.Transformer transformer = factory.newTransformer(); javax.xml.transform.Source source = new javax.xml.transform.dom.DOMSource(this.doc); diff --git a/src/gov/nasa/worldwind/formats/json/BasicJSONEvent.java b/src/gov/nasa/worldwind/formats/json/BasicJSONEvent.java index 4d31443264..edc968f071 100644 --- a/src/gov/nasa/worldwind/formats/json/BasicJSONEvent.java +++ b/src/gov/nasa/worldwind/formats/json/BasicJSONEvent.java @@ -14,23 +14,20 @@ * @author dcollins * @version $Id: BasicJSONEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicJSONEvent implements JSONEvent -{ +public class BasicJSONEvent implements JSONEvent { + protected final JsonToken token; protected final String fieldName; protected final Object scalarValue; - public BasicJSONEvent(JsonParser parser, JsonToken token, String fieldName) throws IOException - { - if (parser == null) - { + public BasicJSONEvent(JsonParser parser, JsonToken token, String fieldName) throws IOException { + if (parser == null) { String message = Logging.getMessage("nullValue.ParserIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (token == null) - { + if (token == null) { String message = Logging.getMessage("nullValue.TokenIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -39,91 +36,70 @@ public BasicJSONEvent(JsonParser parser, JsonToken token, String fieldName) thro this.token = token; this.fieldName = fieldName; - if (this.token.isScalarValue()) - { - if (this.token == JsonToken.VALUE_NULL) + if (this.token.isScalarValue()) { + if (this.token == JsonToken.VALUE_NULL) { this.scalarValue = null; - - else if (this.token == JsonToken.VALUE_STRING) + } else if (this.token == JsonToken.VALUE_STRING) { this.scalarValue = parser.getText(); - - else if (this.token == JsonToken.VALUE_NUMBER_INT) + } else if (this.token == JsonToken.VALUE_NUMBER_INT) { this.scalarValue = parser.getIntValue(); - - else if (this.token == JsonToken.VALUE_NUMBER_FLOAT) + } else if (this.token == JsonToken.VALUE_NUMBER_FLOAT) { this.scalarValue = parser.getDoubleValue(); - - else if (this.token == JsonToken.VALUE_TRUE || token == JsonToken.VALUE_FALSE) + } else if (this.token == JsonToken.VALUE_TRUE || token == JsonToken.VALUE_FALSE) { this.scalarValue = parser.getBooleanValue(); - - else if (this.token == JsonToken.VALUE_EMBEDDED_OBJECT) + } else if (this.token == JsonToken.VALUE_EMBEDDED_OBJECT) { this.scalarValue = parser.getEmbeddedObject(); - - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnexpectedEvent", this.token)); this.scalarValue = null; } - } - else - { + } else { this.scalarValue = null; } } - public boolean isStartObject() - { + public boolean isStartObject() { return this.token == JsonToken.START_OBJECT; } - public boolean isEndObject() - { + public boolean isEndObject() { return this.token == JsonToken.END_OBJECT; } - public boolean isStartArray() - { + public boolean isStartArray() { return this.token == JsonToken.START_ARRAY; } - public boolean isEndArray() - { + public boolean isEndArray() { return this.token == JsonToken.END_ARRAY; } - public boolean isFieldName() - { + public boolean isFieldName() { return this.token == JsonToken.FIELD_NAME; } - public boolean isScalarValue() - { + public boolean isScalarValue() { return this.token.isScalarValue(); } - public boolean isNumericValue() - { + public boolean isNumericValue() { return this.token == JsonToken.VALUE_NUMBER_INT || this.token == JsonToken.VALUE_NUMBER_FLOAT; } - public String getFieldName() - { + public String getFieldName() { return this.fieldName; } - public Object asScalarValue() - { + public Object asScalarValue() { return this.scalarValue; } - public double asNumericValue() - { + public double asNumericValue() { return ((Number) this.scalarValue).doubleValue(); } @Override - public String toString() - { + public String toString() { return this.token.asString(); } } diff --git a/src/gov/nasa/worldwind/formats/json/BasicJSONEventParser.java b/src/gov/nasa/worldwind/formats/json/BasicJSONEventParser.java index 885379efad..ce9d32aca1 100644 --- a/src/gov/nasa/worldwind/formats/json/BasicJSONEventParser.java +++ b/src/gov/nasa/worldwind/formats/json/BasicJSONEventParser.java @@ -15,58 +15,47 @@ * @author dcollins * @version $Id: BasicJSONEventParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicJSONEventParser implements JSONEventParser -{ +public class BasicJSONEventParser implements JSONEventParser { + protected AVList fields; protected List array; - public BasicJSONEventParser() - { + public BasicJSONEventParser() { } - public Object parse(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (ctx == null) - { + public Object parse(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (ctx == null) { String message = Logging.getMessage("nullValue.ParserContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (event == null) - { + if (event == null) { String message = Logging.getMessage("nullValue.EventIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (event.isStartObject()) + if (event.isStartObject()) { return this.parseObject(ctx, event); - - else if (event.isStartArray()) + } else if (event.isStartArray()) { return this.parseArray(ctx, event); - - else if (event.isScalarValue()) + } else if (event.isScalarValue()) { return this.parseScalarContent(ctx, event); - - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnexpectedEvent", event)); return null; } } - protected JSONEventParser allocate(JSONEventParserContext ctx, JSONEvent event) - { - if (ctx == null) - { + protected JSONEventParser allocate(JSONEventParserContext ctx, JSONEvent event) { + if (ctx == null) { String message = Logging.getMessage("nullValue.ParserContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (event == null) - { + if (event == null) { String message = Logging.getMessage("nullValue.EventIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -78,38 +67,32 @@ protected JSONEventParser allocate(JSONEventParserContext ctx, JSONEvent event) //**************************************************************// //******************** Object Parsing ************************// //**************************************************************// - - protected Object parseObject(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isStartObject()) - { + protected Object parseObject(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isStartObject()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isEndObject()) + if (event.isEndObject()) { break; - - else if (event.isFieldName()) + } else if (event.isFieldName()) { this.parseObjectField(ctx, event); - - else + } else { Logging.logger().warning(Logging.getMessage("generic.UnexpectedEvent", event)); + } } return this.resolveObject(ctx, event); } - protected void parseObjectField(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isFieldName()) - { + protected void parseObjectField(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isFieldName()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -117,62 +100,53 @@ protected void parseObjectField(JSONEventParserContext ctx, JSONEvent event) thr ctx.pushFieldName(event.getFieldName()); - if (ctx.hasNext()) - { + if (ctx.hasNext()) { JSONEvent valueEvent = ctx.nextEvent(); - if (valueEvent.isStartObject() || valueEvent.isStartArray()) + if (valueEvent.isStartObject() || valueEvent.isStartArray()) { this.addFieldContent(ctx, this.parseComplexContent(ctx, valueEvent)); - - else if (valueEvent.isScalarValue()) + } else if (valueEvent.isScalarValue()) { this.addFieldContent(ctx, this.parseScalarContent(ctx, valueEvent)); - - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnexpectedEvent", valueEvent)); } - } - else - { + } else { this.addFieldContent(ctx, null); } ctx.popFieldName(); } - protected void addFieldContent(JSONEventParserContext ctx, Object value) - { - if (this.fields == null) + protected void addFieldContent(JSONEventParserContext ctx, Object value) { + if (this.fields == null) { this.fields = new AVListImpl(); + } this.fields.setValue(ctx.getCurrentFieldName(), value); } - protected Object resolveObject(JSONEventParserContext ctx, JSONEvent event) - { + protected Object resolveObject(JSONEventParserContext ctx, JSONEvent event) { return this.fields; } //**************************************************************// //******************** Array Parsing *************************// //**************************************************************// - - protected Object parseArray(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (!event.isStartArray()) - { + protected Object parseArray(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (!event.isStartArray()) { String message = Logging.getMessage("generic.InvalidEvent", event); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isEndArray()) + if (event.isEndArray()) { break; + } this.parseArrayEntry(ctx, event); } @@ -180,50 +154,43 @@ protected Object parseArray(JSONEventParserContext ctx, JSONEvent event) throws return this.resolveArray(ctx, event); } - protected void parseArrayEntry(JSONEventParserContext ctx, JSONEvent event) throws IOException - { - if (event.isStartObject() || event.isStartArray()) + protected void parseArrayEntry(JSONEventParserContext ctx, JSONEvent event) throws IOException { + if (event.isStartObject() || event.isStartArray()) { this.addArrayEntry(this.parseComplexContent(ctx, event)); - - else if (event.isScalarValue()) + } else if (event.isScalarValue()) { this.addArrayEntry(this.parseScalarContent(ctx, event)); - - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnexpectedEvent", event)); } } - protected void addArrayEntry(Object o) - { - if (this.array == null) + protected void addArrayEntry(Object o) { + if (this.array == null) { this.array = new ArrayList(); + } this.array.add(o); } - protected Object resolveArray(JSONEventParserContext ctx, JSONEvent event) - { + protected Object resolveArray(JSONEventParserContext ctx, JSONEvent event) { return this.array.toArray(new Object[this.array.size()]); } //**************************************************************// //******************** Content Parsing ************************// //**************************************************************// - - protected Object parseComplexContent(JSONEventParserContext ctx, JSONEvent event) throws IOException - { + protected Object parseComplexContent(JSONEventParserContext ctx, JSONEvent event) throws IOException { JSONEventParser parser = this.allocate(ctx, event); - if (parser == null) + if (parser == null) { parser = ctx.getUnrecognizedParser(); + } return (parser != null) ? parser.parse(ctx, event) : null; } @SuppressWarnings({"UnusedDeclaration"}) - protected Object parseScalarContent(JSONEventParserContext ctx, JSONEvent event) throws IOException - { + protected Object parseScalarContent(JSONEventParserContext ctx, JSONEvent event) throws IOException { return event.asScalarValue(); } } diff --git a/src/gov/nasa/worldwind/formats/json/BasicJSONEventParserContext.java b/src/gov/nasa/worldwind/formats/json/BasicJSONEventParserContext.java index ea0bd9cadc..5c4add8809 100644 --- a/src/gov/nasa/worldwind/formats/json/BasicJSONEventParserContext.java +++ b/src/gov/nasa/worldwind/formats/json/BasicJSONEventParserContext.java @@ -15,18 +15,16 @@ * @author dcollins * @version $Id: BasicJSONEventParserContext.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicJSONEventParserContext implements JSONEventParserContext -{ +public class BasicJSONEventParserContext implements JSONEventParserContext { + protected JsonParser parser; protected boolean hasNext; protected JSONEvent nextEvent; protected Deque fieldNameStack = new ArrayDeque(); protected Map parsers = new HashMap(); - public BasicJSONEventParserContext(JsonParser parser) throws IOException - { - if (parser == null) - { + public BasicJSONEventParserContext(JsonParser parser) throws IOException { + if (parser == null) { String message = Logging.getMessage("nullValue.ParserIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -36,32 +34,26 @@ public BasicJSONEventParserContext(JsonParser parser) throws IOException this.advance(); // Initializes hasNext and nextEvent. } - public boolean hasNext() - { + public boolean hasNext() { return this.hasNext; } - public JSONEvent nextEvent() throws IOException - { + public JSONEvent nextEvent() throws IOException { JSONEvent e = this.nextEvent; this.advance(); return e; } - public JSONEvent peek() - { + public JSONEvent peek() { return this.nextEvent; } - public String getCurrentFieldName() - { + public String getCurrentFieldName() { return this.fieldNameStack.peek(); } - public void pushFieldName(String name) - { - if (name == null) - { + public void pushFieldName(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -70,50 +62,38 @@ public void pushFieldName(String name) this.fieldNameStack.push(name); } - public void popFieldName() - { + public void popFieldName() { this.fieldNameStack.pop(); } - public JSONEventParser allocate(JSONEvent event) - { + public JSONEventParser allocate(JSONEvent event) { return this.parsers.get(this.getCurrentFieldName()); // HashMap accepts the null key. } - public JSONEventParser getUnrecognizedParser() - { + public JSONEventParser getUnrecognizedParser() { return new BasicJSONEventParser(); } - public void registerParser(String fieldName, BasicJSONEventParser parser) - { + public void registerParser(String fieldName, BasicJSONEventParser parser) { this.parsers.put(fieldName, parser); } - protected void advance() throws IOException - { + protected void advance() throws IOException { this.parser.nextToken(); - if (!this.parser.hasCurrentToken()) - { + if (!this.parser.hasCurrentToken()) { this.hasNext = false; this.nextEvent = null; - } - else - { + } else { this.hasNext = true; this.nextEvent = this.createEvent(this.parser.getCurrentToken()); } } - protected JSONEvent createEvent(JsonToken token) throws IOException - { - if (token == JsonToken.VALUE_NUMBER_INT || token == JsonToken.VALUE_NUMBER_FLOAT) - { + protected JSONEvent createEvent(JsonToken token) throws IOException { + if (token == JsonToken.VALUE_NUMBER_INT || token == JsonToken.VALUE_NUMBER_FLOAT) { return new NumericValueJSONEvent(this.parser.getCurrentName(), this.parser.getDoubleValue()); - } - else - { + } else { return new BasicJSONEvent(this.parser, token, this.parser.getCurrentName()); } } diff --git a/src/gov/nasa/worldwind/formats/json/JSONDoc.java b/src/gov/nasa/worldwind/formats/json/JSONDoc.java index b7712f44d0..8a502ada6f 100644 --- a/src/gov/nasa/worldwind/formats/json/JSONDoc.java +++ b/src/gov/nasa/worldwind/formats/json/JSONDoc.java @@ -15,66 +15,56 @@ * @author dcollins * @version $Id: JSONDoc.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class JSONDoc implements Closeable -{ +public class JSONDoc implements Closeable { + protected JsonParser jsonParser; protected Object rootObject; protected String displayName; - public JSONDoc(Object source) - { - if (WWUtil.isEmpty(source)) - { + public JSONDoc(Object source) { + if (WWUtil.isEmpty(source)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { this.displayName = WWIO.getSourcePath(source); this.initialize(source); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileReading", this.displayName); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - protected void initialize(Object source) throws Exception - { + protected void initialize(Object source) throws Exception { JsonFactory factory = new JsonFactory(); this.jsonParser = factory.createJsonParser(WWIO.openStream(source)); } - public Object getRootObject() - { + public Object getRootObject() { return this.rootObject; } - public void parse() throws IOException - { - if (this.jsonParser == null) - { + public void parse() throws IOException { + if (this.jsonParser == null) { Logging.logger().warning(Logging.getMessage("generic.ParserUninitialized", this.displayName)); return; } JSONEventParserContext ctx = this.createEventParserContext(this.jsonParser); - if (ctx == null) - { + if (ctx == null) { Logging.logger().warning(Logging.getMessage("generic.CannotParse", this.displayName)); return; } - if (!ctx.hasNext()) + if (!ctx.hasNext()) { return; + } JSONEventParser rootParser = this.createRootObjectParser(); - if (rootParser == null) - { + if (rootParser == null) { Logging.logger().warning(Logging.getMessage("generic.CannotParse", this.displayName)); return; } @@ -82,22 +72,18 @@ public void parse() throws IOException this.rootObject = rootParser.parse(ctx, ctx.nextEvent()); } - public void close() - { - if (this.jsonParser != null) - { + public void close() { + if (this.jsonParser != null) { WWIO.closeStream(this.jsonParser, this.displayName); this.jsonParser = null; } } - protected JSONEventParserContext createEventParserContext(JsonParser parser) throws IOException - { + protected JSONEventParserContext createEventParserContext(JsonParser parser) throws IOException { return new BasicJSONEventParserContext(parser); } - protected JSONEventParser createRootObjectParser() throws IOException - { + protected JSONEventParser createRootObjectParser() throws IOException { return new BasicJSONEventParser(); } } diff --git a/src/gov/nasa/worldwind/formats/json/JSONEvent.java b/src/gov/nasa/worldwind/formats/json/JSONEvent.java index 343cc309ab..485cebfb0c 100644 --- a/src/gov/nasa/worldwind/formats/json/JSONEvent.java +++ b/src/gov/nasa/worldwind/formats/json/JSONEvent.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: JSONEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface JSONEvent -{ +public interface JSONEvent { + boolean isStartObject(); boolean isEndObject(); diff --git a/src/gov/nasa/worldwind/formats/json/JSONEventParser.java b/src/gov/nasa/worldwind/formats/json/JSONEventParser.java index 9dbffd5bf5..54a9a0d78b 100644 --- a/src/gov/nasa/worldwind/formats/json/JSONEventParser.java +++ b/src/gov/nasa/worldwind/formats/json/JSONEventParser.java @@ -11,7 +11,7 @@ * @author dcollins * @version $Id: JSONEventParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface JSONEventParser -{ +public interface JSONEventParser { + Object parse(JSONEventParserContext ctx, JSONEvent event) throws IOException; } diff --git a/src/gov/nasa/worldwind/formats/json/JSONEventParserContext.java b/src/gov/nasa/worldwind/formats/json/JSONEventParserContext.java index 6fca56437d..8f751bf25e 100644 --- a/src/gov/nasa/worldwind/formats/json/JSONEventParserContext.java +++ b/src/gov/nasa/worldwind/formats/json/JSONEventParserContext.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: JSONEventParserContext.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface JSONEventParserContext -{ +public interface JSONEventParserContext { + boolean hasNext(); JSONEvent nextEvent() throws IOException; diff --git a/src/gov/nasa/worldwind/formats/json/NumericValueJSONEvent.java b/src/gov/nasa/worldwind/formats/json/NumericValueJSONEvent.java index 62052d9e20..a6a29e4ec4 100644 --- a/src/gov/nasa/worldwind/formats/json/NumericValueJSONEvent.java +++ b/src/gov/nasa/worldwind/formats/json/NumericValueJSONEvent.java @@ -11,70 +11,58 @@ * @author dcollins * @version $Id: NumericValueJSONEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NumericValueJSONEvent implements JSONEvent -{ +public class NumericValueJSONEvent implements JSONEvent { + protected final String fieldName; protected final double numericValue; - public NumericValueJSONEvent(String fieldName, double value) throws IOException - { + public NumericValueJSONEvent(String fieldName, double value) throws IOException { this.fieldName = fieldName; this.numericValue = value; } - public boolean isStartObject() - { + public boolean isStartObject() { return false; } - public boolean isEndObject() - { + public boolean isEndObject() { return false; } - public boolean isStartArray() - { + public boolean isStartArray() { return false; } - public boolean isEndArray() - { + public boolean isEndArray() { return false; } - public boolean isFieldName() - { + public boolean isFieldName() { return false; } - public boolean isScalarValue() - { + public boolean isScalarValue() { return true; } - public boolean isNumericValue() - { + public boolean isNumericValue() { return true; } - public String getFieldName() - { + public String getFieldName() { return this.fieldName; } - public Object asScalarValue() - { + public Object asScalarValue() { return this.numericValue; } - public double asNumericValue() - { + public double asNumericValue() { return this.numericValue; } @Override - public String toString() - { + public String toString() { return String.valueOf(this.numericValue); } } diff --git a/src/gov/nasa/worldwind/formats/nitfs/CompressionLookupRecord.java b/src/gov/nasa/worldwind/formats/nitfs/CompressionLookupRecord.java index c96e4882de..80c2f7d40a 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/CompressionLookupRecord.java +++ b/src/gov/nasa/worldwind/formats/nitfs/CompressionLookupRecord.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; import gov.nasa.worldwind.formats.rpf.RPFColorMap; @@ -12,65 +11,60 @@ * @author Lado Garakanidze * @version $Id: CompressionLookupRecord.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class CompressionLookupRecord -{ - public int getTableID() - { +class CompressionLookupRecord { + + public int getTableID() { return this.tableID; } - public int getNumOfRecords() - { + public int getNumOfRecords() { return this.numOfRecords; } - public int getNumOfValuesPerRecord() - { + public int getNumOfValuesPerRecord() { return this.numOfValuesPerRecord; } - public int getValueBitLength() - { + public int getValueBitLength() { return this.valueBitLength; } - public short getBytesPerRecord() - { + public short getBytesPerRecord() { return this.bytesPerRecord; } - public byte[] copyValues(byte [] dest, int destOffset, int idx, int len) - { - if(len != this.bytesPerRecord) + public byte[] copyValues(byte[] dest, int destOffset, int idx, int len) { + if (len != this.bytesPerRecord) { throw new NITFSRuntimeException("NITFSReader.AttemptToCopyWithInvalidSizeOfRecord"); - if(idx >= this.numOfRecords) + } + if (idx >= this.numOfRecords) { throw new NITFSRuntimeException("NITFSReader.AttemptToCopyOutOfBoundsAtSource"); - if(null == dest) + } + if (null == dest) { throw new NITFSRuntimeException("NITFSReader.AttemptCopyToIvalidDestination"); - if(dest.length < destOffset + len) + } + if (dest.length < destOffset + len) { throw new NITFSRuntimeException("NITFSReader.AttemptToCopyOutOfBoundsAtDestination"); + } System.arraycopy(lut, idx * this.bytesPerRecord, dest, destOffset, this.bytesPerRecord); return dest; } + private int tableID; + private int numOfRecords; + private int numOfValuesPerRecord; + private int valueBitLength; + private int tableLocation; + private short bytesPerRecord; - private int tableID; - private int numOfRecords; - private int numOfValuesPerRecord; - private int valueBitLength; - private int tableLocation; - private short bytesPerRecord; - - private byte[] lut; + private byte[] lut; public CompressionLookupRecord(java.nio.ByteBuffer buffer, - int compressionLookupSubsectionLocation, - RPFColorMap[] colormaps // TODO update LUT with the color mapped values to gain performance - ) - - { + int compressionLookupSubsectionLocation, + RPFColorMap[] colormaps // TODO update LUT with the color mapped values to gain performance + ) { this.tableID = NITFSUtil.getUShort(buffer); this.numOfRecords = (int) NITFSUtil.getUInt(buffer); this.numOfValuesPerRecord = NITFSUtil.getUShort(buffer); @@ -78,8 +72,8 @@ public CompressionLookupRecord(java.nio.ByteBuffer buffer, this.tableLocation = (int) (NITFSUtil.getUInt(buffer) + compressionLookupSubsectionLocation); int saveOffset = buffer.position(); - this.bytesPerRecord = (short) (this.numOfValuesPerRecord * this.valueBitLength/8L); - this.lut = new byte[ this.numOfRecords * this.bytesPerRecord ]; + this.bytesPerRecord = (short) (this.numOfValuesPerRecord * this.valueBitLength / 8L); + this.lut = new byte[this.numOfRecords * this.bytesPerRecord]; buffer.position(this.tableLocation); buffer.get(this.lut, 0, this.numOfRecords * this.bytesPerRecord); diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSDataExtensionSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSDataExtensionSegment.java index a18639f7a6..ea7b1cc220 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSDataExtensionSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSDataExtensionSegment.java @@ -3,18 +3,17 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; + /** * @author Lado Garakanidze * @version $Id: NITFSDataExtensionSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class NITFSDataExtensionSegment extends NITFSSegment -{ +class NITFSDataExtensionSegment extends NITFSSegment { + public NITFSDataExtensionSegment(java.nio.ByteBuffer buffer, - int headerStartOffset, int headerLength, - int dataStartOffset, int dataLength) - { + int headerStartOffset, int headerLength, + int dataStartOffset, int dataLength) { super(NITFSSegmentType.DATA_EXTENSION_SEGMENT, buffer, headerStartOffset, headerLength, dataStartOffset, dataLength); } } diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSExtendedHeaderSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSExtendedHeaderSegment.java index 8df9843639..a884b6e1c3 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSExtendedHeaderSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSExtendedHeaderSegment.java @@ -3,15 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; + /** * @author Lado Garakanidze * @version $Id: NITFSExtendedHeaderSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ class NITFSExtendedHeaderSegment extends NITFSSegment { - public NITFSExtendedHeaderSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) - { + + public NITFSExtendedHeaderSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) { super(NITFSSegmentType.EXTENDED_HEADER_SEGMENT, buffer, headerStartOffset, headerLength, dataStartOffset, dataLength); this.restoreBufferPosition(); diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSFileHeader.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSFileHeader.java index 402f10bc97..15f79b0d49 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSFileHeader.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSFileHeader.java @@ -3,270 +3,233 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; /** * @author Lado Garakanidze * @version $Id: NITFSFileHeader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NITFSFileHeader -{ - private String headerID; - private String version; - private String specialType; - private int headerLength; - private int fileLength; +public class NITFSFileHeader { + + private String headerID; + private String version; + private String specialType; + private int headerLength; + private int fileLength; private boolean isVersion0210; - private short complexityLevel ; - private String originationStationId; - private String dateTime; - private String title ; - - private String FSCLAS ; - private String FSCLSY ; - private String FSCODE ; - private String FSCTLH ; - private String FSREL ; - private String FSDCTP ; - private String FSDCDT ; - private String FSDCXM ; - private String FSDG ; - private String FSDGDT ; - private String FSCLTX ; - private String FSCATP ; - private String FSCAUT ; - private String FSCRSN ; - private String FSSRDT ; - private String FSCTLN ; - private String FSDWNG ; - private String FSDEVT ; - private String FSCOP ; - private String FSCPYS ; - private String ENCRYP ; - private String FBKGC ; - private String ONAME ; - private String OPHONE ; - - public NITFSFileHeader(java.nio.ByteBuffer buffer) - { + private short complexityLevel; + private String originationStationId; + private String dateTime; + private String title; + + private String FSCLAS; + private String FSCLSY; + private String FSCODE; + private String FSCTLH; + private String FSREL; + private String FSDCTP; + private String FSDCDT; + private String FSDCXM; + private String FSDG; + private String FSDGDT; + private String FSCLTX; + private String FSCATP; + private String FSCAUT; + private String FSCRSN; + private String FSSRDT; + private String FSCTLN; + private String FSDWNG; + private String FSDEVT; + private String FSCOP; + private String FSCPYS; + private String ENCRYP; + private String FBKGC; + private String ONAME; + private String OPHONE; + + public NITFSFileHeader(java.nio.ByteBuffer buffer) { parseFileHeaderInfo(buffer); } - private void parseFileHeaderInfo(java.nio.ByteBuffer buffer) - { + private void parseFileHeaderInfo(java.nio.ByteBuffer buffer) { this.headerID = NITFSUtil.getString(buffer, 0, 4); - this.version = NITFSUtil.getString(buffer, 5); + this.version = NITFSUtil.getString(buffer, 5); this.isVersion0210 = "02.10".equals(version); this.complexityLevel = NITFSUtil.getShortNumeric(buffer, 2); this.specialType = NITFSUtil.getString(buffer, 4); // offset 11, size 4 this.originationStationId = NITFSUtil.getString(buffer, 10); // offset 15, size 10 this.dateTime = NITFSUtil.getString(buffer, 14); // offset 25, size 14 - this.title = NITFSUtil.getString(buffer, 80); // offset 39, size 80 + this.title = NITFSUtil.getString(buffer, 80); // offset 39, size 80 - this.FSCLAS = NITFSUtil.getString(buffer, 1); // offset 119, size 1 - this.FSCLSY = (isVersion0210 ? NITFSUtil.getString(buffer, 2) : ""); // offset 120, size 2 - this.FSCODE = NITFSUtil.getString(buffer, isVersion0210 ? 11 : 40); - this.FSCTLH = NITFSUtil.getString(buffer, isVersion0210 ? 2 : 40); - this.FSREL = NITFSUtil.getString(buffer, isVersion0210 ? 20 : 40); + this.FSCLAS = NITFSUtil.getString(buffer, 1); // offset 119, size 1 + this.FSCLSY = (isVersion0210 ? NITFSUtil.getString(buffer, 2) : ""); // offset 120, size 2 + this.FSCODE = NITFSUtil.getString(buffer, isVersion0210 ? 11 : 40); + this.FSCTLH = NITFSUtil.getString(buffer, isVersion0210 ? 2 : 40); + this.FSREL = NITFSUtil.getString(buffer, isVersion0210 ? 20 : 40); - this.FSDCTP = (isVersion0210 ? NITFSUtil.getString(buffer, 2) : ""); - this.FSDCDT = (isVersion0210 ? NITFSUtil.getString(buffer, 8) : ""); // offset 157/ - this.FSDCXM = (isVersion0210 ? NITFSUtil.getString(buffer, 4) : ""); // offset 165/ - this.FSDG = (isVersion0210 ? NITFSUtil.getString(buffer, 1) : ""); // offset 169/ - this.FSDGDT = (isVersion0210 ? NITFSUtil.getString(buffer, 8) : ""); // oofset 170/ - this.FSCLTX = (isVersion0210 ? NITFSUtil.getString(buffer, 43) : ""); // offset 178/ - this.FSCATP = (isVersion0210 ? NITFSUtil.getString(buffer, 1) : ""); // offset 221/ + this.FSDCTP = (isVersion0210 ? NITFSUtil.getString(buffer, 2) : ""); + this.FSDCDT = (isVersion0210 ? NITFSUtil.getString(buffer, 8) : ""); // offset 157/ + this.FSDCXM = (isVersion0210 ? NITFSUtil.getString(buffer, 4) : ""); // offset 165/ + this.FSDG = (isVersion0210 ? NITFSUtil.getString(buffer, 1) : ""); // offset 169/ + this.FSDGDT = (isVersion0210 ? NITFSUtil.getString(buffer, 8) : ""); // oofset 170/ + this.FSCLTX = (isVersion0210 ? NITFSUtil.getString(buffer, 43) : ""); // offset 178/ + this.FSCATP = (isVersion0210 ? NITFSUtil.getString(buffer, 1) : ""); // offset 221/ - this.FSCAUT = NITFSUtil.getString(buffer, isVersion0210 ? 40 : 20); // offset 222/240 + this.FSCAUT = NITFSUtil.getString(buffer, isVersion0210 ? 40 : 20); // offset 222/240 - this.FSCRSN = (isVersion0210 ? NITFSUtil.getString(buffer, 1) : ""); // offset 262/ - this.FSSRDT = (isVersion0210 ? NITFSUtil.getString(buffer, 8) : ""); // offset 263/ - this.FSCTLN = NITFSUtil.getString(buffer, isVersion0210 ? 15 : 20); // offset 271/260 - this.FSDWNG = (isVersion0210) ? "" : NITFSUtil.getString(buffer, 6); // offset /280 + this.FSCRSN = (isVersion0210 ? NITFSUtil.getString(buffer, 1) : ""); // offset 262/ + this.FSSRDT = (isVersion0210 ? NITFSUtil.getString(buffer, 8) : ""); // offset 263/ + this.FSCTLN = NITFSUtil.getString(buffer, isVersion0210 ? 15 : 20); // offset 271/260 + this.FSDWNG = (isVersion0210) ? "" : NITFSUtil.getString(buffer, 6); // offset /280 - this.FSDEVT = (!isVersion0210 && "999998".equals(FSDWNG)) // offset /286 - ? NITFSUtil.getString(buffer, 40) : ""; + this.FSDEVT = (!isVersion0210 && "999998".equals(FSDWNG)) // offset /286 + ? NITFSUtil.getString(buffer, 40) : ""; - this.FSCOP = NITFSUtil.getString(buffer, 5); // offset 286/+40 + this.FSCOP = NITFSUtil.getString(buffer, 5); // offset 286/+40 this.FSCPYS = NITFSUtil.getString(buffer, 5); // offset 291/+40 this.ENCRYP = NITFSUtil.getString(buffer, 1); // offset 296/+40 - this.FBKGC = (isVersion0210 ? NITFSUtil.getString(buffer, 297, 3) : ""); // offset 297/ - this.ONAME = NITFSUtil.getString(buffer, isVersion0210 ? 24 : 27); // offset 300/297(+40) + this.FBKGC = (isVersion0210 ? NITFSUtil.getString(buffer, 297, 3) : ""); // offset 297/ + this.ONAME = NITFSUtil.getString(buffer, isVersion0210 ? 24 : 27); // offset 300/297(+40) this.OPHONE = NITFSUtil.getString(buffer, 18); // offset 324(+40) this.fileLength = NITFSUtil.getNumeric(buffer, 12); // offset 342(+40) this.headerLength = NITFSUtil.getNumeric(buffer, 6); // offset 352(+40) - } - - public String getHeaderID() - { + } + + public String getHeaderID() { return this.headerID; } - public String getVersion() - { + public String getVersion() { return this.version; } - public boolean isVersion0210() - { + public boolean isVersion0210() { return this.isVersion0210; } - public short getComplexityLevel() - { + public short getComplexityLevel() { return this.complexityLevel; } - public String getSpecialType() - { + public String getSpecialType() { return this.specialType; } - public String getOriginationStationId() - { + public String getOriginationStationId() { return this.originationStationId; } - public String getDateTime() - { + public String getDateTime() { return this.dateTime; } - public String getTitle() - { + public String getTitle() { return this.title; } - public int getHeaderLength() - { + public int getHeaderLength() { return this.headerLength; } - public String getFSCLAS() - { + public String getFSCLAS() { return this.FSCLAS; } - public String getFSCLSY() - { + public String getFSCLSY() { return this.FSCLSY; } - public String getFSCODE() - { + public String getFSCODE() { return this.FSCODE; } - public String getFSCTLH() - { + public String getFSCTLH() { return this.FSCTLH; } - public String getFSREL() - { + public String getFSREL() { return this.FSREL; } - public String getFSDCTP() - { + public String getFSDCTP() { return this.FSDCTP; } - public String getFSDCDT() - { + public String getFSDCDT() { return this.FSDCDT; } - public String getFSDCXM() - { + public String getFSDCXM() { return this.FSDCXM; } - public String getFSDG() - { + public String getFSDG() { return this.FSDG; } - public String getFSDGDT() - { + public String getFSDGDT() { return this.FSDGDT; } - public String getFSCLTX() - { + public String getFSCLTX() { return this.FSCLTX; } - public String getFSCATP() - { + public String getFSCATP() { return this.FSCATP; } - public String getFSCAUT() - { + public String getFSCAUT() { return this.FSCAUT; } - public String getFSCRSN() - { + public String getFSCRSN() { return this.FSCRSN; } - public String getFSSRDT() - { + public String getFSSRDT() { return this.FSSRDT; } - public String getFSCTLN() - { + public String getFSCTLN() { return this.FSCTLN; } - public String getFSDWNG() - { + public String getFSDWNG() { return this.FSDWNG; } - public String getFSDEVT() - { + public String getFSDEVT() { return this.FSDEVT; } - public String getFSCOP() - { + public String getFSCOP() { return this.FSCOP; } - public String getFSCPYS() - { + public String getFSCPYS() { return this.FSCPYS; } - public String getENCRYP() - { + public String getENCRYP() { return this.ENCRYP; } - public String getFBKGC() - { + public String getFBKGC() { return this.FBKGC; } - public String getONAME() - { + public String getONAME() { return this.ONAME; } - public String getOPHONE() - { + public String getOPHONE() { return this.OPHONE; } - public int getFileLength() - { + public int getFileLength() { return this.fileLength; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSImageBand.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSImageBand.java index 5b56a0992b..6afef4430d 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSImageBand.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSImageBand.java @@ -3,15 +3,14 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; /** * @author Lado Garakanidze * @version $Id: NITFSImageBand.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class NITFSImageBand -{ +class NITFSImageBand { + private String representation; private String significanceForImageCategory; private String imageFilterCondition; @@ -24,44 +23,36 @@ class NITFSImageBand private boolean isGrayImage; private boolean hasTransparentEntry; - public boolean isGrayImage() - { + public boolean isGrayImage() { return this.isGrayImage; } - public boolean isHasTransparentEntry() - { + public boolean isHasTransparentEntry() { return this.hasTransparentEntry; } - public String getRepresentation() - { + public String getRepresentation() { return this.representation; } - public short getNumOfLookupTables() - { + public short getNumOfLookupTables() { return this.numOfLookupTables; } - public short getNumOfLookupTableEntries() - { + public short getNumOfLookupTableEntries() { return this.numOfLookupTableEntries; } - public NITFSImageBand(java.nio.ByteBuffer buffer) - { + public NITFSImageBand(java.nio.ByteBuffer buffer) { this.representation = NITFSUtil.getString(buffer, 2); this.significanceForImageCategory = NITFSUtil.getString(buffer, 6); this.imageFilterCondition = NITFSUtil.getString(buffer, 1); this.stdImageFilterCode = NITFSUtil.getString(buffer, 3); this.numOfLookupTables = NITFSUtil.getShortNumeric(buffer, 1); this.numOfLookupTableEntries = NITFSUtil.getShortNumeric(buffer, 5); - if (0 < this.numOfLookupTables && 0 < this.numOfLookupTableEntries) - { + if (0 < this.numOfLookupTables && 0 < this.numOfLookupTableEntries) { this.lut = new byte[this.numOfLookupTables][this.numOfLookupTableEntries]; - for (int j = 0; j < this.numOfLookupTables; j++) - { + for (int j = 0; j < this.numOfLookupTables; j++) { buffer.get(this.lut[j], 0, this.numOfLookupTableEntries); } } @@ -77,62 +68,48 @@ public NITFSImageBand(java.nio.ByteBuffer buffer) * * @return true of the color code is a reserved color code, and false otherwise. */ - public final boolean isReservedApplicationCode(int colorIndex) - { + public final boolean isReservedApplicationCode(int colorIndex) { // The color code is an application-specific reserved code if exceeds the color lookup table size. return colorIndex >= this.numOfLookupTableEntries; } - public final int lookupR5G6B5(int colorIndex) - { + public final int lookupR5G6B5(int colorIndex) { int r, g, b; - if (3 == this.numOfLookupTables) - { + if (3 == this.numOfLookupTables) { r = (0x00FF & this.lut[0][colorIndex]) >> 3; g = (0x00FF & this.lut[1][colorIndex]) >> 2; b = (0x00FF & this.lut[2][colorIndex]) >> 3; - } - else - { - int gray = 0x00FF & this.lut[0][ colorIndex ]; + } else { + int gray = 0x00FF & this.lut[0][colorIndex]; r = gray >> 3; g = gray >> 2; b = gray >> 3; } - return 0x00FFFF & ((r << 11) | (g << 5) | b ); + return 0x00FFFF & ((r << 11) | (g << 5) | b); } - - public final int lookupRGB(int colorIndex) - { + public final int lookupRGB(int colorIndex) { int r, g, b; - if (3 == this.numOfLookupTables) - { + if (3 == this.numOfLookupTables) { r = (0x00FF & this.lut[0][colorIndex]); g = (0x00FF & this.lut[1][colorIndex]); b = (0x00FF & this.lut[2][colorIndex]); + } else { + r = g = b = 0x00FF & this.lut[0][colorIndex]; } - else - { - r = g = b = 0x00FF & this.lut[0][ colorIndex ]; - } - return (int) (0x00FFFFFFL & (long)((r << 16) | (g << 8) | b )); + return (int) (0x00FFFFFFL & (long) ((r << 16) | (g << 8) | b)); } - public final int lookupGray(int colorIndex) - { + public final int lookupGray(int colorIndex) { - if (3 == this.numOfLookupTables) - { + if (3 == this.numOfLookupTables) { int r = (0x00FF & this.lut[0][colorIndex]); int g = (0x00FF & this.lut[1][colorIndex]); int b = (0x00FF & this.lut[2][colorIndex]); - return (30 * r + 59 * g + 11 * b)/100; - } - else - { + return (30 * r + 59 * g + 11 * b) / 100; + } else { return (0x00FF & this.lut[0][colorIndex]); } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSImageSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSImageSegment.java index df5594d9c3..b248059784 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSImageSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSImageSegment.java @@ -14,9 +14,9 @@ * @author Lado Garakanidze * @version $Id: NITFSImageSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NITFSImageSegment extends NITFSSegment -{ - public static final String[] SupportedFormats = { "CIB", "CADRG", "ADRG" }; +public class NITFSImageSegment extends NITFSSegment { + + public static final String[] SupportedFormats = {"CIB", "CADRG", "ADRG"}; // [ nitf identification , security, structure fields] public String partType; public String imageID; @@ -31,14 +31,14 @@ public class NITFSImageSegment extends NITFSSegment public String securityCtrlNum; public String ISDWNG; // image security downgrade public String ISDEVT; // downgrading event - public short encryption; + public short encryption; public String imageSource; - public int numSignificantRows; - public int numSignificantCols; + public int numSignificantRows; + public int numSignificantCols; public String pixelValueType; public String imageRepresentation; public String imageCategory; - public short bitsPerPixelPerBand; + public short bitsPerPixelPerBand; public String pixelJustification; public String imageCoordSystem; // [ nitf image geographic location ] @@ -48,90 +48,83 @@ public class NITFSImageSegment extends NITFSSegment // [ nitf image compression structure ] public String imageCompression; public String compressionRateCode; - public short NBANDS; // number of bands { 1 for MONO and RGB/LUT, 3 for RGB; + public short NBANDS; // number of bands { 1 for MONO and RGB/LUT, 3 for RGB; // [ nitfs image bands ] public NITFSImageBand[] imageBands; // [ nitf image table structure fields ] - public short imageSyncCode; // ISYNC { 0 - No sync code, 1 - sync code } - public String imageMode; // IMODE { B, P, R, S } - public short numOfBlocksPerRow; // NBPR { 0001~9999 } - public short numOfBlocksPerCol; // NBPC { 0001~9999 } - public short numOfPixelsPerBlockH; // NPPBH { 0001~8192 } - public short numOfPixelsPerBlockV; // NPPBV { 0001~8192 } - public short numOfBitsPerPixelPerBand; // NBPP { 01~96 } - public short displayLevel; // IDLVL { 001~999 } - public short attachmentLevel; // IALVL { 001~998 } + public short imageSyncCode; // ISYNC { 0 - No sync code, 1 - sync code } + public String imageMode; // IMODE { B, P, R, S } + public short numOfBlocksPerRow; // NBPR { 0001~9999 } + public short numOfBlocksPerCol; // NBPC { 0001~9999 } + public short numOfPixelsPerBlockH; // NPPBH { 0001~8192 } + public short numOfPixelsPerBlockV; // NPPBV { 0001~8192 } + public short numOfBitsPerPixelPerBand; // NBPP { 01~96 } + public short displayLevel; // IDLVL { 001~999 } + public short attachmentLevel; // IALVL { 001~998 } // [ nitfs image location ] - public short imageRowOffset; // ILOC { -0001 ~ +9999 } - public short imageColOffset; // + public short imageRowOffset; // ILOC { -0001 ~ +9999 } + public short imageColOffset; // // [ nitf image magnification ] - public String imageMagnification; // IMAG - public short userDefinedSubheaderLength; + public String imageMagnification; // IMAG + public short userDefinedSubheaderLength; // [ nitf user-defined image subheader ] private UserDefinedImageSubheader userDefSubheader; // [ nitf-rpf image display parameter sub-header ] - private long numOfImageRows; - private long numOfImageCodesPerRow; - private short imageCodeBitLength; + private long numOfImageRows; + private long numOfImageCodesPerRow; + private short imageCodeBitLength; // [ nitf rpf compression section ] // [ nitf-rpf compression section sub-header ] - private int compressionAlgorithmID; - private int numOfCompressionLookupOffsetRecords; - private int numOfCompressionParameterOffsetRecords; + private int compressionAlgorithmID; + private int numOfCompressionLookupOffsetRecords; + private int numOfCompressionParameterOffsetRecords; // [ nitf rpf compression lookup sub-section ] - private long compressionLookupOffsetTableOffset; - private int compressionLookupTableOffsetRecordLength; - + private long compressionLookupOffsetTableOffset; + private int compressionLookupTableOffsetRecordLength; // [ nitf-rpf mask subsection ] - private int subframeSequenceRecordLength; - private int transparencySequenceRecordLength; - private int transparentOutputPixelCodeLength; - private int transparentOutputPixelCode; - private int[] subFrameOffsets = null; + private int subframeSequenceRecordLength; + private int transparencySequenceRecordLength; + private int transparentOutputPixelCodeLength; + private int transparentOutputPixelCode; + private int[] subFrameOffsets = null; private boolean hasTransparentPixels = false; private boolean hasMaskedSubframes = false; - public static String[] getSupportedFormats() - { + public static String[] getSupportedFormats() { return SupportedFormats; } - public boolean hasTransparentPixels() - { + public boolean hasTransparentPixels() { return this.hasTransparentPixels; } - public boolean hasMaskedSubframes() - { + public boolean hasMaskedSubframes() { return this.hasMaskedSubframes; } private CompressionLookupRecord[] compressionLUTS; - public UserDefinedImageSubheader getUserDefinedImageSubheader() - { + public UserDefinedImageSubheader getUserDefinedImageSubheader() { return userDefSubheader; } - public RPFFrameFileComponents getRPFFrameFileComponents() - { + public RPFFrameFileComponents getRPFFrameFileComponents() { return (null != userDefSubheader) ? userDefSubheader.getRPFFrameFileComponents() : null; } - public NITFSImageSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength,int dataStartOffset, int dataLength) - { + public NITFSImageSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) { super(NITFSSegmentType.IMAGE_SEGMENT, buffer, headerStartOffset, headerLength, dataStartOffset, dataLength); int saveOffset = buffer.position(); - buffer.position( headerStartOffset ); + buffer.position(headerStartOffset); // do not change order of parsing this.parseIdentificationSecurityStructureFields(buffer); this.parseImageGeographicLocation(buffer); @@ -147,19 +140,17 @@ public NITFSImageSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int buffer.position(saveOffset); // last line - restore buffer's position } - private void decompressBlock4x4(byte[][] block4x4, short code) - { + private void decompressBlock4x4(byte[][] block4x4, short code) { this.compressionLUTS[0].copyValues(block4x4[0], 0, code, 4); this.compressionLUTS[1].copyValues(block4x4[1], 0, code, 4); this.compressionLUTS[2].copyValues(block4x4[2], 0, code, 4); this.compressionLUTS[3].copyValues(block4x4[3], 0, code, 4); } - private void decompressBlock16(byte[] block16, short code) - { - this.compressionLUTS[0].copyValues(block16, 0, code, 4); - this.compressionLUTS[1].copyValues(block16, 4, code, 4); - this.compressionLUTS[2].copyValues(block16, 8, code, 4); + private void decompressBlock16(byte[] block16, short code) { + this.compressionLUTS[0].copyValues(block16, 0, code, 4); + this.compressionLUTS[1].copyValues(block16, 4, code, 4); + this.compressionLUTS[2].copyValues(block16, 8, code, 4); this.compressionLUTS[3].copyValues(block16, 12, code, 4); } @@ -168,7 +159,7 @@ public int[] getImagePixelsAsArray(int[] pixels, RPFImageType imageType) throws RPFLocationSection componentLocationTable = rpfComponents.componentLocationTable; int spatialDataSubsectionLocation = componentLocationTable.getSpatialDataSubsectionLocation(); - super.buffer.position( spatialDataSubsectionLocation ); + super.buffer.position(spatialDataSubsectionLocation); int band = 0; // for(int band = 0; band < rpfComponents.numOfSpectralBandTables; band++) NITFSImageBand imageBand = this.imageBands[band]; @@ -182,73 +173,57 @@ public int[] getImagePixelsAsArray(int[] pixels, RPFImageType imageType) throws int subFrameOffset; short subFrameIdx = 0; - for (int subFrameH = 0; subFrameH < this.numOfBlocksPerCol; subFrameH++) - { - for (int subFrameW = 0; subFrameW < this.numOfBlocksPerRow; subFrameW++, subFrameIdx++ ) - { + for (int subFrameH = 0; subFrameH < this.numOfBlocksPerCol; subFrameH++) { + for (int subFrameW = 0; subFrameW < this.numOfBlocksPerRow; subFrameW++, subFrameIdx++) { int blockY = (int) (subFrameH * rpfComponents.numOfOutputRowsPerSubframe); int blockX = (int) (subFrameW * rpfComponents.numOfOutputColumnsPerSubframe); - if(hasMaskedSubframes) - { + if (hasMaskedSubframes) { subFrameOffset = this.subFrameOffsets[subFrameIdx]; - if( -1 == subFrameOffset) - { // this is a masked / empty subframe + if (-1 == subFrameOffset) { // this is a masked / empty subframe continue; - } - else - { - super.buffer.position( spatialDataSubsectionLocation + subFrameOffset ); + } else { + super.buffer.position(spatialDataSubsectionLocation + subFrameOffset); } } - for (int row = 0; row < this.numOfImageRows; row++) - { + for (int row = 0; row < this.numOfImageRows; row++) { int qy = blockY + row * 4; super.buffer.get(rowBytes, 0, rowSize); // short[] codes = new short[(int) this.numOfImageCodesPerRow]; - for (int i = 0, cidx = 0, bidx = 0; i < (int) this.numOfImageCodesPerRow / 2; i++) - { + for (int i = 0, cidx = 0, bidx = 0; i < (int) this.numOfImageCodesPerRow / 2; i++) { aa = (short) ((0x00FF & (short) rowBytes[bidx++]) << 4); - ab = (short) (0x00FF & (short) rowBytes[bidx++]); - bb = (short) (0x00FF & (short) rowBytes[bidx++]); + ab = (short) (0x00FF & (short) rowBytes[bidx++]); + bb = (short) (0x00FF & (short) rowBytes[bidx++]); codes[cidx++] = (short) (aa | ((0x00F0 & ab) >> 4)); codes[cidx++] = (short) (bb | ((0x000F & ab) << 8)); } - for (int col = 0; col < this.numOfImageCodesPerRow; col++) - { - if (hasTransparentPixels) - { - if (4095 == codes[col]) - { // this is a transparent kernel - continue; + for (int col = 0; col < this.numOfImageCodesPerRow; col++) { + if (hasTransparentPixels) { + if (4095 == codes[col]) { // this is a transparent kernel + continue; } } - this.decompressBlock4x4( block4x4, codes[col] ); + this.decompressBlock4x4(block4x4, codes[col]); int qx = blockX + col * 4; - for (int h = 0; h < 4; h++) - { - for (int w = 0; w < 4; w++) - { + for (int h = 0; h < 4; h++) { + for (int w = 0; w < 4; w++) { colorCode = 0x00FF & block4x4[h][w]; - if (hasTransparentPixels) - { - if (this.transparentOutputPixelCode == colorCode) - { // this is a transparent pixel + if (hasTransparentPixels) { + if (this.transparentOutputPixelCode == colorCode) { // this is a transparent pixel continue; } } - if (imageBand.isReservedApplicationCode(colorCode)) - { + if (imageBand.isReservedApplicationCode(colorCode)) { // This is a reserved color code used to define an application-specific overlay. We // don't know the meaning of application overlay codes, therefore we treat them as // transparent or background pixels. @@ -256,15 +231,14 @@ public int[] getImagePixelsAsArray(int[] pixels, RPFImageType imageType) throws } rgbColor = imageBand.lookupRGB(colorCode); - switch (imageType) - { + switch (imageType) { case IMAGE_TYPE_ALPHA_RGB: rgbColor = 0xFF000000 + rgbColor; break; - //case IMAGE_TYPE_GRAY: - // break; - //case IMAGE_TYPE_RGB: - // break; + //case IMAGE_TYPE_GRAY: + // break; + //case IMAGE_TYPE_RGB: + // break; case IMAGE_TYPE_GRAY_ALPHA: rgbColor = (rgbColor << 8) + 0xFF; break; @@ -286,18 +260,19 @@ public int[] getImagePixelsAsArray(int[] pixels, RPFImageType imageType) throws private void validateImage() throws NITFSRuntimeException { RPFFrameFileComponents rpfComponents = this.getRPFFrameFileComponents(); - if(1 != this.compressionAlgorithmID ) + if (1 != this.compressionAlgorithmID) { throw new NITFSRuntimeException("NITFSReader.UnsupportedCompressionAlgorithm"); - if( ! "B".equals(this.imageMode) ) + } + if (!"B".equals(this.imageMode)) { throw new NITFSRuntimeException("NITFSReader.UnsupportedImageMode"); - if( 1 != rpfComponents.numOfSpectralGroups ) + } + if (1 != rpfComponents.numOfSpectralGroups) { throw new NITFSRuntimeException("NITFSReader.UnsupportedNumberOfSpectralGroups."); - if( 12 != this.imageCodeBitLength ) + } + if (12 != this.imageCodeBitLength) { throw new NITFSRuntimeException("NITFSReader.UnsupportedImageCodeBitLength."); + } - - - } private void parseRPFMaskSubsection(java.nio.ByteBuffer buffer) throws NITFSRuntimeException { @@ -310,119 +285,107 @@ private void parseRPFMaskSubsection(java.nio.ByteBuffer buffer) throws NITFSRunt this.transparencySequenceRecordLength = NITFSUtil.getUShort(buffer); this.transparentOutputPixelCodeLength = NITFSUtil.getUShort(buffer); - if( 0 != this.transparentOutputPixelCodeLength ) - { + if (0 != this.transparentOutputPixelCodeLength) { String bitstr = NITFSUtil.getBitString(buffer, this.transparentOutputPixelCodeLength); this.transparentOutputPixelCode = Integer.parseInt(bitstr, 2); } // parse [ nitf-rpf subframe mask table ] - if(-1 != subframeMaskTableOffset || 0 < this.subframeSequenceRecordLength) - { + if (-1 != subframeMaskTableOffset || 0 < this.subframeSequenceRecordLength) { // seek to [ subframe mask table offset ] - if (-1 != subframeMaskTableOffset) + if (-1 != subframeMaskTableOffset) { buffer.position(maskSubsectionPos + subframeMaskTableOffset); + } RPFFrameFileComponents rpfComponents = this.getRPFFrameFileComponents(); - subFrameOffsets = new int[ this.numOfBlocksPerCol * this.numOfBlocksPerRow ]; + subFrameOffsets = new int[this.numOfBlocksPerCol * this.numOfBlocksPerRow]; // parse [ nitf-rpf subframe mask table ] int idx = 0; - for(int group = 0 ; group < rpfComponents.numOfSpectralGroups; group++ ) - { - for(int row = 0 ; row < this.numOfBlocksPerCol; row++ ) - { - for(int col = 0 ; col < this.numOfBlocksPerRow; col++ ) + for (int group = 0; group < rpfComponents.numOfSpectralGroups; group++) { + for (int row = 0; row < this.numOfBlocksPerCol; row++) { + for (int col = 0; col < this.numOfBlocksPerRow; col++) { subFrameOffsets[idx++] = (int) NITFSUtil.getUInt(buffer); + } } } - } - else - { + } else { this.subFrameOffsets = null; } // parse [ nitf-rpf transparency mask table ] - if (-1 != transparencyMaskTableOffset || 0 < this.transparencySequenceRecordLength) - { + if (-1 != transparencyMaskTableOffset || 0 < this.transparencySequenceRecordLength) { } this.hasMaskedSubframes = (null != this.subFrameOffsets && 0 < this.subFrameOffsets.length); this.hasTransparentPixels = (0 < this.transparencySequenceRecordLength || 0 < this.transparentOutputPixelCodeLength); } - private void parseImageData(java.nio.ByteBuffer buffer) throws NITFSRuntimeException { RPFLocationSection componentLocationTable = this.getRPFFrameFileComponents().componentLocationTable; buffer.position(this.dataStartOffset); long spatialDataOffset = NITFSUtil.getUInt(buffer); - if(0 < componentLocationTable.getMaskSubsectionLength()) - { + if (0 < componentLocationTable.getMaskSubsectionLength()) { // parse nitf-rpf mask subsection - buffer.position( componentLocationTable.getMaskSubsectionLocation() ); + buffer.position(componentLocationTable.getMaskSubsectionLocation()); this.parseRPFMaskSubsection(buffer); } - if(0 < componentLocationTable.getImageDisplayParametersSubheaderLength()) - { // parse [ nitf-rpf image display parameter sub-header ] - buffer.position( componentLocationTable.getImageDisplayParametersSubheaderLocation() ); + if (0 < componentLocationTable.getImageDisplayParametersSubheaderLength()) { // parse [ nitf-rpf image display parameter sub-header ] + buffer.position(componentLocationTable.getImageDisplayParametersSubheaderLocation()); this.parseImageDisplayParametersSubheader(buffer); - } - else + } else { throw new NITFSRuntimeException("NITFSReader.ImageDisplayParametersSubheaderNotFound"); + } // [ nitf rpf compression section ] - if(0 < componentLocationTable.getCompressionSectionSubheaderLength()) - { // parse [ nitf-rpf compression section sub-header ] - buffer.position( componentLocationTable.getCompressionSectionSubheaderLocation() ); + if (0 < componentLocationTable.getCompressionSectionSubheaderLength()) { // parse [ nitf-rpf compression section sub-header ] + buffer.position(componentLocationTable.getCompressionSectionSubheaderLocation()); this.parseRPFCompressionSectionSubheader(buffer); - } - else + } else { throw new NITFSRuntimeException("NITFSReader.RPFCompressionSectionSubheaderNotFound"); + } // [ nitf rpf compression lookup sub-section ] - if(0 < componentLocationTable.getCompressionLookupSubsectionLength()) - { - buffer.position( componentLocationTable.getCompressionLookupSubsectionLocation() ); + if (0 < componentLocationTable.getCompressionLookupSubsectionLength()) { + buffer.position(componentLocationTable.getCompressionLookupSubsectionLocation()); this.parseRPFCompressionLookupSubsection(buffer); - } - else + } else { throw new NITFSRuntimeException("NITFSReader.RPFCompressionLookupSubsectionNotFound"); + } // [ nitf rpf compression parameter subsection ] - if(0 < componentLocationTable.getCompressionParameterSubsectionLength()) + if (0 < componentLocationTable.getCompressionParameterSubsectionLength()) { throw new NITFSRuntimeException("NITFSReader.RPFCompressionParameterSubsectionNotImplemented"); + } // [ nitf rpf spatial data subsection ] - if(0 < componentLocationTable.getSpatialDataSubsectionLength()) - { + if (0 < componentLocationTable.getSpatialDataSubsectionLength()) { - buffer.position( componentLocationTable.getSpatialDataSubsectionLocation() ); + buffer.position(componentLocationTable.getSpatialDataSubsectionLocation()); this.parseRPFSpatialDataSubsection(buffer); - } - else + } else { throw new NITFSRuntimeException("NITFSReader.RPFSpatialDataSubsectionNotFound"); + } } private void parseRPFSpatialDataSubsection(java.nio.ByteBuffer buffer) throws NITFSRuntimeException { - } private void parseRPFCompressionLookupSubsection(java.nio.ByteBuffer buffer) - throws NITFSRuntimeException { + throws NITFSRuntimeException { int compressionLookupSubsectionLocation = buffer.position(); // [ nitf rpf compression lookup sub-section ] this.compressionLookupOffsetTableOffset = NITFSUtil.getUInt(buffer); this.compressionLookupTableOffsetRecordLength = NITFSUtil.getUShort(buffer); this.compressionLUTS = new CompressionLookupRecord[this.numOfCompressionLookupOffsetRecords]; - for(int i = 0 ; i < this.numOfCompressionLookupOffsetRecords; i++) - { - this.compressionLUTS[i] = new CompressionLookupRecord( buffer, - compressionLookupSubsectionLocation, - this.getRPFFrameFileComponents().rpfColorMaps); + for (int i = 0; i < this.numOfCompressionLookupOffsetRecords; i++) { + this.compressionLUTS[i] = new CompressionLookupRecord(buffer, + compressionLookupSubsectionLocation, + this.getRPFFrameFileComponents().rpfColorMaps); } } @@ -439,23 +402,23 @@ private void parseImageDisplayParametersSubheader(java.nio.ByteBuffer buffer) th this.numOfImageCodesPerRow = NITFSUtil.getUInt(buffer); this.imageCodeBitLength = NITFSUtil.getByteAsShort(buffer); } - + private void parseImageSubheaders(java.nio.ByteBuffer buffer) throws NITFSRuntimeException { this.userDefinedSubheaderLength = NITFSUtil.getShortNumeric(buffer, 5); - if (0 == this.userDefinedSubheaderLength) - { + if (0 == this.userDefinedSubheaderLength) { this.userDefSubheader = null; return; } - + this.userDefSubheader = new UserDefinedImageSubheader(buffer); } + private void parseImageLocation(java.nio.ByteBuffer buffer) throws NITFSRuntimeException { this.imageRowOffset = NITFSUtil.getShortNumeric(buffer, 5); this.imageColOffset = NITFSUtil.getShortNumeric(buffer, 5); // [ nitf image magnification ] this.imageMagnification = NITFSUtil.getString(buffer, 4); - } + } private void parseImageTableStructure(java.nio.ByteBuffer buffer) throws NITFSRuntimeException { this.imageSyncCode = NITFSUtil.getShortNumeric(buffer, 1); @@ -470,34 +433,34 @@ private void parseImageTableStructure(java.nio.ByteBuffer buffer) throws NITFSRu } private void parseImageBands(java.nio.ByteBuffer buffer) throws NITFSRuntimeException { - if(0 == this.NBANDS) + if (0 == this.NBANDS) { throw new NITFSRuntimeException("NITFSReader.InvalidNumberOfImageBands"); + } this.imageBands = new NITFSImageBand[this.NBANDS]; - for(int i = 0 ; i < this.NBANDS; i++) + for (int i = 0; i < this.NBANDS; i++) { this.imageBands[i] = new NITFSImageBand(buffer); + } } - private void parseImageCompressionStructure(java.nio.ByteBuffer buffer) - { + + private void parseImageCompressionStructure(java.nio.ByteBuffer buffer) { this.imageCompression = NITFSUtil.getString(buffer, 2); this.compressionRateCode = NITFSUtil.getString(buffer, 4); this.NBANDS = NITFSUtil.getShortNumeric(buffer, 1); } - private void parseCommentRecords(java.nio.ByteBuffer buffer) - { + private void parseCommentRecords(java.nio.ByteBuffer buffer) { int numCommentRecords = NITFSUtil.getShortNumeric(buffer, 1); - if(0 < numCommentRecords) - { + if (0 < numCommentRecords) { this.imageCommentRecords = new String[numCommentRecords]; - for(int i = 0; i < numCommentRecords; i++) + for (int i = 0; i < numCommentRecords; i++) { this.imageCommentRecords[i] = NITFSUtil.getString(buffer, 80); - } - else + } + } else { this.imageCommentRecords = null; + } } - private void parseImageGeographicLocation(java.nio.ByteBuffer buffer) - { + private void parseImageGeographicLocation(java.nio.ByteBuffer buffer) { // [ nitf image geographic location ] // four lat/lon coordinates encoded as ddmmssXdddmmssY // (some CADRG files encode coordinates as ddmmssXddmmssY0) @@ -509,8 +472,7 @@ private void parseImageGeographicLocation(java.nio.ByteBuffer buffer) double deg, min, sec, lat, lon; double sixty = 60.0; this.imageCoords = new LatLon[4]; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { buffer.get(dst, 0, coordLen); dstBuffer = ByteBuffer.wrap(dst, 0, coordLen); @@ -520,8 +482,9 @@ private void parseImageGeographicLocation(java.nio.ByteBuffer buffer) sec = (double) NITFSUtil.getShortNumeric(dstBuffer, 2); hemisphere = NITFSUtil.getString(dstBuffer, 1); lat = deg + (min + (sec / sixty)) / sixty; // decimal latitude - if("S".equals(hemisphere)) + if ("S".equals(hemisphere)) { lat *= -1.0; + } // parse longitude [ dddmmssY ] int londegLen = dst[14] != 0 ? 3 : 2; // handle the case when longitude is encoded as ddmmssY @@ -530,8 +493,9 @@ private void parseImageGeographicLocation(java.nio.ByteBuffer buffer) sec = (double) NITFSUtil.getShortNumeric(dstBuffer, 2); hemisphere = NITFSUtil.getString(dstBuffer, 1); lon = deg + (min + (sec / sixty)) / sixty; // decimal longitude - if("W".equals(hemisphere)) + if ("W".equals(hemisphere)) { lon *= -1.0; + } // TODO Do not waste time on this calculations - the same info is repeated in the [ rpf coverage section ] // TODO zz: garakl: convert to LatLon according to the CoordinateSystem @@ -541,24 +505,24 @@ private void parseImageGeographicLocation(java.nio.ByteBuffer buffer) } private void parseIdentificationSecurityStructureFields(java.nio.ByteBuffer buffer) - throws NITFSRuntimeException { + throws NITFSRuntimeException { // [ nitf identification , security, structure fields] this.partType = NITFSUtil.getString(buffer, 2); - if(!"IM".equals(this.partType)) + if (!"IM".equals(this.partType)) { throw new NITFSRuntimeException("NITFSReader.UnexpectedSegmentType", this.partType); + } this.imageID = NITFSUtil.getString(buffer, 10); boolean isSupportedFormat = false; - for(String s : SupportedFormats) - { - if(0 == s.compareTo(this.imageID)) - { + for (String s : SupportedFormats) { + if (0 == s.compareTo(this.imageID)) { isSupportedFormat = true; break; } } - if(!isSupportedFormat) + if (!isSupportedFormat) { throw new NITFSRuntimeException("NITFSReader.UnsupportedImageFormat", this.imageID); + } this.dateTime = NITFSUtil.getString(buffer, 14); this.targetID = NITFSUtil.getString(buffer, 17); @@ -571,7 +535,7 @@ private void parseIdentificationSecurityStructureFields(java.nio.ByteBuffer buff this.securityCtrlNum = NITFSUtil.getString(buffer, 20); // ISCTLN this.ISDWNG = NITFSUtil.getString(buffer, 6); this.ISDEVT = "999998".equals(this.ISDWNG) ? NITFSUtil.getString(buffer, 40) : ""; - + this.encryption = NITFSUtil.getShortNumeric(buffer, 1); this.imageSource = NITFSUtil.getString(buffer, 42); this.numSignificantRows = NITFSUtil.getNumeric(buffer, 8); @@ -584,5 +548,4 @@ private void parseIdentificationSecurityStructureFields(java.nio.ByteBuffer buff this.imageCoordSystem = NITFSUtil.getString(buffer, 1); } - } diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSLabelSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSLabelSegment.java index df52dda2f8..42cd81a1a6 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSLabelSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSLabelSegment.java @@ -3,16 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; + /** * @author Lado Garakanidze * @version $Id: NITFSLabelSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class NITFSLabelSegment extends NITFSSegment -{ - public NITFSLabelSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) - { +class NITFSLabelSegment extends NITFSSegment { + + public NITFSLabelSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) { super(NITFSSegmentType.LABEL_SEGMENT, buffer, headerStartOffset, headerLength, dataStartOffset, dataLength); this.restoreBufferPosition(); diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSMessage.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSMessage.java index 71976776cf..0b9b40b1dd 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSMessage.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSMessage.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; import gov.nasa.worldwind.formats.rpf.RPFUserDefinedHeaderSegment; @@ -15,30 +14,26 @@ * @author Lado Garakanidze * @version $Id: NITFSMessage.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NITFSMessage -{ - private java.nio.ByteBuffer buffer; - private NITFSFileHeader fileHeader; - private java.util.ArrayList segments = new java.util.ArrayList(); +public class NITFSMessage { + private java.nio.ByteBuffer buffer; + private NITFSFileHeader fileHeader; + private java.util.ArrayList segments = new java.util.ArrayList(); - public NITFSSegment getSegment( NITFSSegmentType segmentType ) - { - for(NITFSSegment seg : segments) - { - if(null != seg && seg.segmentType.equals(segmentType)) + public NITFSSegment getSegment(NITFSSegmentType segmentType) { + for (NITFSSegment seg : segments) { + if (null != seg && seg.segmentType.equals(segmentType)) { return seg; + } } return null; } - public NITFSFileHeader getNITFSFileHeader() - { + public NITFSFileHeader getNITFSFileHeader() { return this.fileHeader; } - private NITFSMessage(java.nio.ByteBuffer buffer) - { + private NITFSMessage(java.nio.ByteBuffer buffer) { this.buffer = buffer; this.fileHeader = new NITFSFileHeader(buffer); @@ -46,8 +41,7 @@ private NITFSMessage(java.nio.ByteBuffer buffer) this.readSegments(); } - private void readSegments() - { + private void readSegments() { int saveOffset = this.buffer.position(); int nextSegmentOffset = this.fileHeader.getHeaderLength(); @@ -65,14 +59,13 @@ private void readSegments() nextSegmentOffset = parseSegment(NITFSSegmentType.RESERVED_EXTENSION_SEGMENT, nextSegmentOffset); // parse User Defined Header Description (UDHD) Group NITFSUserDefinedHeaderSegment userHeaderSeg = new RPFUserDefinedHeaderSegment(this.buffer); - this.segments.add( userHeaderSeg ); + this.segments.add(userHeaderSeg); nextSegmentOffset += userHeaderSeg.headerLength + userHeaderSeg.dataLength; // parse Extended Header Description Group nextSegmentOffset = parseSegment(NITFSSegmentType.EXTENDED_HEADER_SEGMENT, nextSegmentOffset); // let's read each header - for(NITFSSegment segment : segments) - { + for (NITFSSegment segment : segments) { // // String segId = NITFSUtil.getString(buffer, segment.headerStartOffset, 2); @@ -80,51 +73,48 @@ private void readSegments() } } - private int parseSegment(NITFSSegmentType segType, int nextSegmentOffset) - { + private int parseSegment(NITFSSegmentType segType, int nextSegmentOffset) { int headerLengthSize = segType.getHeaderLengthSize(); int dataLengthSize = segType.getDataLengthSize(); int numOfSegments = Integer.parseInt(NITFSUtil.getString(this.buffer, 3)); - for (int i = 0; i < numOfSegments; i++) - { + for (int i = 0; i < numOfSegments; i++) { int segHeaderLength = Integer.parseInt(NITFSUtil.getString(this.buffer, headerLengthSize)); int seqDataLength = Integer.parseInt(NITFSUtil.getString(this.buffer, dataLengthSize)); int saveOffset = this.buffer.position(); // pass buffer to NITFSSegment to parse their headers' contents NITFSSegment segment; - switch (segType) - { + switch (segType) { case IMAGE_SEGMENT: segment = new NITFSImageSegment(this.buffer, nextSegmentOffset, segHeaderLength, - nextSegmentOffset + segHeaderLength, seqDataLength); + nextSegmentOffset + segHeaderLength, seqDataLength); break; case SYMBOL_SEGMENT: segment = new NITFSSymbolSegment(this.buffer, nextSegmentOffset, segHeaderLength, - nextSegmentOffset + segHeaderLength, seqDataLength); + nextSegmentOffset + segHeaderLength, seqDataLength); break; case LABEL_SEGMENT: segment = new NITFSLabelSegment(this.buffer, nextSegmentOffset, segHeaderLength, - nextSegmentOffset + segHeaderLength, seqDataLength); + nextSegmentOffset + segHeaderLength, seqDataLength); break; case TEXT_SEGMENT: segment = new NITFSTextSegment(this.buffer, nextSegmentOffset, segHeaderLength, - nextSegmentOffset + segHeaderLength, seqDataLength); + nextSegmentOffset + segHeaderLength, seqDataLength); break; case DATA_EXTENSION_SEGMENT: segment = new NITFSDataExtensionSegment(this.buffer, nextSegmentOffset, segHeaderLength, - nextSegmentOffset + segHeaderLength, seqDataLength); + nextSegmentOffset + segHeaderLength, seqDataLength); break; case RESERVED_EXTENSION_SEGMENT: segment = new NITFSReservedExtensionSegment(this.buffer, nextSegmentOffset, segHeaderLength, - nextSegmentOffset + segHeaderLength, seqDataLength); + nextSegmentOffset + segHeaderLength, seqDataLength); break; case USER_DEFINED_HEADER_SEGMENT: segment = new RPFUserDefinedHeaderSegment(this.buffer); break; case EXTENDED_HEADER_SEGMENT: // // throw exception - wrong parser for EXTENDED_HEADER_SEGMENT segment = new NITFSExtendedHeaderSegment(this.buffer, nextSegmentOffset, segHeaderLength, - nextSegmentOffset + segHeaderLength, seqDataLength); + nextSegmentOffset + segHeaderLength, seqDataLength); break; default: @@ -139,16 +129,14 @@ private int parseSegment(NITFSSegmentType segType, int nextSegmentOffset) return nextSegmentOffset; } - public static NITFSMessage load(java.io.File file) throws java.io.IOException - { + public static NITFSMessage load(java.io.File file) throws java.io.IOException { validateImageFile(file); java.nio.ByteBuffer roBuffer = NITFSUtil.readEntireFile(file).asReadOnlyBuffer(); // check if it is a NITFS format file (NITF or NSIF - for NATO Secondary Imagery Format) String fmtId = NITFSUtil.getString(roBuffer, 0, 4); - if( 0 != "NITF".compareTo(fmtId) && 0 != "NSIF".compareTo(fmtId)) - { + if (0 != "NITF".compareTo(fmtId) && 0 != "NSIF".compareTo(fmtId)) { throw new NITFSRuntimeException("NITFSReader.UnknownOrUnsupportedNITFSFormat", file.getCanonicalPath()); } @@ -156,15 +144,13 @@ public static NITFSMessage load(java.io.File file) throws java.io.IOException } private static void validateImageFile(java.io.File file) - throws IOException, IllegalArgumentException, NITFSRuntimeException { - if (null == file) - { + throws IOException, IllegalArgumentException, NITFSRuntimeException { + if (null == file) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists() || !file.canRead()) - { + if (!file.exists() || !file.canRead()) { throw new NITFSRuntimeException("NITFSReader.NoFileOrNoPermission", file.getCanonicalPath()); } } diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSReservedExtensionSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSReservedExtensionSegment.java index 64351a2fce..2c3cccd94a 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSReservedExtensionSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSReservedExtensionSegment.java @@ -3,16 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; + /** * @author Lado Garakanidze * @version $Id: NITFSReservedExtensionSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NITFSReservedExtensionSegment extends NITFSSegment -{ - public NITFSReservedExtensionSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) - { +public class NITFSReservedExtensionSegment extends NITFSSegment { + + public NITFSReservedExtensionSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) { super(NITFSSegmentType.RESERVED_EXTENSION_SEGMENT, buffer, headerStartOffset, headerLength, dataStartOffset, dataLength); this.restoreBufferPosition(); diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSRuntimeException.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSRuntimeException.java index ece5b262f2..574ac61373 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSRuntimeException.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSRuntimeException.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; import gov.nasa.worldwind.util.Logging; @@ -12,47 +11,40 @@ * @author Lado Garakanidze * @version $Id: NITFSRuntimeException.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public final class NITFSRuntimeException extends java.lang.RuntimeException -{ - public NITFSRuntimeException() - { +public final class NITFSRuntimeException extends java.lang.RuntimeException { + + public NITFSRuntimeException() { super(); } - public NITFSRuntimeException(String messageID) - { + public NITFSRuntimeException(String messageID) { super(Logging.getMessage(messageID)); log(this.getMessage()); } - public NITFSRuntimeException(String messageID, String params) - { + public NITFSRuntimeException(String messageID, String params) { super(Logging.getMessage(messageID) + params); log(this.getMessage()); } - public NITFSRuntimeException(Throwable throwable) - { + public NITFSRuntimeException(Throwable throwable) { super(throwable); log(this.getMessage()); } - public NITFSRuntimeException(String messageID, Throwable throwable) - { + public NITFSRuntimeException(String messageID, Throwable throwable) { super(Logging.getMessage(messageID), throwable); log(this.getMessage()); } - public NITFSRuntimeException(String messageID, String params, Throwable throwable) - { + public NITFSRuntimeException(String messageID, String params, Throwable throwable) { super(Logging.getMessage(messageID) + params, throwable); log(this.getMessage()); } // TODO: Calling the logger from here causes the wrong method to be listed in the log record. Must call the // logger from the site with the problem and generating the exception. - private void log(String s) - { + private void log(String s) { Logging.logger().fine(s); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSSegment.java index 496ebd278b..31b93f65a7 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSSegment.java @@ -3,26 +3,25 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; + /** * @author Lado Garakanidze * @version $Id: NITFSSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NITFSSegment -{ +public class NITFSSegment { + protected java.nio.ByteBuffer buffer; protected NITFSSegmentType segmentType; protected int savedBufferOffset; - + protected int headerStartOffset; protected int headerLength; protected int dataStartOffset; protected int dataLength; public NITFSSegment(NITFSSegmentType segmentType, java.nio.ByteBuffer buffer, - int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) - { + int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) { this.buffer = buffer; this.segmentType = segmentType; this.headerStartOffset = headerStartOffset; @@ -32,9 +31,7 @@ public NITFSSegment(NITFSSegmentType segmentType, java.nio.ByteBuffer buffer, this.savedBufferOffset = buffer.position(); } - protected void restoreBufferPosition() - { + protected void restoreBufferPosition() { this.buffer.position(this.savedBufferOffset); } } - diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSSegmentType.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSSegmentType.java index 49ce68e211..9ab881fa3b 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSSegmentType.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSSegmentType.java @@ -3,32 +3,35 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; + /** * @author Lado Garakanidze * @version $Id: NITFSSegmentType.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public enum NITFSSegmentType -{ - IMAGE_SEGMENT (6, 10), - SYMBOL_SEGMENT (4, 6), - LABEL_SEGMENT (4, 3), - TEXT_SEGMENT (4, 5), - DATA_EXTENSION_SEGMENT (4, 9), - RESERVED_EXTENSION_SEGMENT (4, 7), - USER_DEFINED_HEADER_SEGMENT (0, 0), - EXTENDED_HEADER_SEGMENT (0, 0); +public enum NITFSSegmentType { + IMAGE_SEGMENT(6, 10), + SYMBOL_SEGMENT(4, 6), + LABEL_SEGMENT(4, 3), + TEXT_SEGMENT(4, 5), + DATA_EXTENSION_SEGMENT(4, 9), + RESERVED_EXTENSION_SEGMENT(4, 7), + USER_DEFINED_HEADER_SEGMENT(0, 0), + EXTENDED_HEADER_SEGMENT(0, 0); private final int fieldHeaderLengthSize; private final int fieldDataLengthSize; - private NITFSSegmentType(int fieldHeaderLengthSize, int fieldDataLengthSize) - { + private NITFSSegmentType(int fieldHeaderLengthSize, int fieldDataLengthSize) { this.fieldHeaderLengthSize = fieldHeaderLengthSize; this.fieldDataLengthSize = fieldDataLengthSize; } - public int getHeaderLengthSize() { return fieldHeaderLengthSize; } - public int getDataLengthSize() { return fieldDataLengthSize; } + public int getHeaderLengthSize() { + return fieldHeaderLengthSize; + } + + public int getDataLengthSize() { + return fieldDataLengthSize; + } } diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSSymbolSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSSymbolSegment.java index e721f42db3..6a2b0cb466 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSSymbolSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSSymbolSegment.java @@ -3,16 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; + /** * @author Lado Garakanidze * @version $Id: NITFSSymbolSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NITFSSymbolSegment extends NITFSSegment -{ - public NITFSSymbolSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) - { +public class NITFSSymbolSegment extends NITFSSegment { + + public NITFSSymbolSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) { super(NITFSSegmentType.SYMBOL_SEGMENT, buffer, headerStartOffset, headerLength, dataStartOffset, dataLength); this.restoreBufferPosition(); diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSTextSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSTextSegment.java index b9da384503..cc74c6ecd5 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSTextSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSTextSegment.java @@ -3,16 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; + /** * @author Lado Garakanidze * @version $Id: NITFSTextSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class NITFSTextSegment extends NITFSSegment -{ - public NITFSTextSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) - { +class NITFSTextSegment extends NITFSSegment { + + public NITFSTextSegment(java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) { super(NITFSSegmentType.TEXT_SEGMENT, buffer, headerStartOffset, headerLength, dataStartOffset, dataLength); this.restoreBufferPosition(); diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSUserDefinedHeaderSegment.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSUserDefinedHeaderSegment.java index 9aaa1cd211..3ae4302af1 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSUserDefinedHeaderSegment.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSUserDefinedHeaderSegment.java @@ -3,20 +3,18 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; /** * @author Lado Garakanidze * @version $Id: NITFSUserDefinedHeaderSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class NITFSUserDefinedHeaderSegment extends NITFSSegment -{ - protected int overflow; - protected String dataTag; +public abstract class NITFSUserDefinedHeaderSegment extends NITFSSegment { + + protected int overflow; + protected String dataTag; - public NITFSUserDefinedHeaderSegment(java.nio.ByteBuffer buffer) - { + public NITFSUserDefinedHeaderSegment(java.nio.ByteBuffer buffer) { super(NITFSSegmentType.USER_DEFINED_HEADER_SEGMENT, buffer, 0, 0, 0, 0); this.headerLength = Integer.parseInt(NITFSUtil.getString(buffer, 5)); diff --git a/src/gov/nasa/worldwind/formats/nitfs/NITFSUtil.java b/src/gov/nasa/worldwind/formats/nitfs/NITFSUtil.java index b5118b0c47..6670f15bed 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/NITFSUtil.java +++ b/src/gov/nasa/worldwind/formats/nitfs/NITFSUtil.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; import java.io.*; @@ -14,13 +13,11 @@ * @author Lado Garakanidze * @version $Id: NITFSUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NITFSUtil -{ - public static String getString(java.nio.ByteBuffer buffer, int offset, int len) - { +public class NITFSUtil { + + public static String getString(java.nio.ByteBuffer buffer, int offset, int len) { String s = ""; - if (null != buffer && buffer.capacity() >= offset + len) - { + if (null != buffer && buffer.capacity() >= offset + len) { byte[] dest = new byte[len]; buffer.position(offset); buffer.get(dest, 0, len); @@ -29,11 +26,9 @@ public static String getString(java.nio.ByteBuffer buffer, int offset, int len) return s; } - public static String getString(java.nio.ByteBuffer buffer, int len) - { + public static String getString(java.nio.ByteBuffer buffer, int len) { String s = ""; - if (null != buffer && buffer.remaining() >= len) - { + if (null != buffer && buffer.remaining() >= len) { byte[] dest = new byte[len]; buffer.get(dest, 0, len); s = new String(dest).trim(); @@ -41,11 +36,9 @@ public static String getString(java.nio.ByteBuffer buffer, int len) return s; } - public static int getNumeric(java.nio.ByteBuffer buffer, int len) - { + public static int getNumeric(java.nio.ByteBuffer buffer, int len) { String s = ""; - if (null != buffer && buffer.remaining() >= len) - { + if (null != buffer && buffer.remaining() >= len) { byte[] dest = new byte[len]; buffer.get(dest, 0, len); s = new String(dest); @@ -53,11 +46,9 @@ public static int getNumeric(java.nio.ByteBuffer buffer, int len) return Integer.parseInt(s); } - public static short getShortNumeric(java.nio.ByteBuffer buffer, int len) - { + public static short getShortNumeric(java.nio.ByteBuffer buffer, int len) { String s = ""; - if (null != buffer && buffer.remaining() >= len) - { + if (null != buffer && buffer.remaining() >= len) { byte[] dest = new byte[len]; buffer.get(dest, 0, len); s = new String(dest); @@ -65,38 +56,31 @@ public static short getShortNumeric(java.nio.ByteBuffer buffer, int len) return (short) (0xFFFF & Integer.parseInt(s)); } - public static boolean getBoolean(java.nio.ByteBuffer buffer) - { + public static boolean getBoolean(java.nio.ByteBuffer buffer) { return !((byte) 0 == buffer.get()); // 0 = false, non-zero = true } - public static short getByteAsShort(java.nio.ByteBuffer buffer) - { + public static short getByteAsShort(java.nio.ByteBuffer buffer) { return (short) (0xFF & buffer.get()); } - public static int getUShort(java.nio.ByteBuffer buffer) - { + public static int getUShort(java.nio.ByteBuffer buffer) { return 0xFFFF & buffer.getShort(); } - public static long getUInt(java.nio.ByteBuffer buffer) - { + public static long getUInt(java.nio.ByteBuffer buffer) { return 0xFFFFFFFFL & (long) buffer.getInt(); } - public static String getBitString(java.nio.ByteBuffer buffer, int lenBits) - { + public static String getBitString(java.nio.ByteBuffer buffer, int lenBits) { String s = ""; int len = (int) Math.ceil(lenBits / (double) Byte.SIZE); - if (null != buffer && buffer.remaining() >= len) - { + if (null != buffer && buffer.remaining() >= len) { byte[] dest = new byte[len]; buffer.get(dest, 0, len); char[] bits = new char[lenBits]; - for (int i = 0; i < lenBits; i++) - { + for (int i = 0; i < lenBits; i++) { int mask = 0x1 << (Byte.SIZE - (i % Byte.SIZE) - 1); // U+0030 : unicode zero // U+0031 : unicode one @@ -109,67 +93,58 @@ public static String getBitString(java.nio.ByteBuffer buffer, int lenBits) private static final int PAGE_SIZE = 4096; - - public static java.nio.ByteBuffer readEntireFile(java.io.File file) throws java.io.IOException - { + public static java.nio.ByteBuffer readEntireFile(java.io.File file) throws java.io.IOException { return readFileToBuffer(file); // return memoryMapFile(file); // return readFile(file); } - private static java.nio.ByteBuffer readFileToBuffer(java.io.File file) throws IOException - { + private static java.nio.ByteBuffer readFileToBuffer(java.io.File file) throws IOException { FileInputStream is = new FileInputStream(file); - try - { + try { FileChannel fc = is.getChannel(); java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate((int) fc.size()); - for (int count = 0; count >= 0 && buffer.hasRemaining();) - { + for (int count = 0; count >= 0 && buffer.hasRemaining();) { count = fc.read(buffer); } buffer.flip(); return buffer; - } - finally - { + } finally { is.close(); } } @SuppressWarnings({"UnusedDeclaration"}) - private static java.nio.ByteBuffer readFile(java.io.File file) throws java.io.IOException - { + private static java.nio.ByteBuffer readFile(java.io.File file) throws java.io.IOException { java.io.FileInputStream fis = new java.io.FileInputStream(file); java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(PAGE_SIZE); java.nio.channels.ReadableByteChannel channel = java.nio.channels.Channels.newChannel(fis); int count = 0; - while (count >= 0) - { + while (count >= 0) { count = channel.read(buffer); - if (count > 0 && !buffer.hasRemaining()) - { + if (count > 0 && !buffer.hasRemaining()) { java.nio.ByteBuffer biggerBuffer = java.nio.ByteBuffer.allocate(buffer.limit() + PAGE_SIZE); biggerBuffer.put((java.nio.ByteBuffer) buffer.rewind()); buffer = biggerBuffer; } } - if (buffer != null) + if (buffer != null) { buffer.flip(); + } return buffer; } @SuppressWarnings({"UnusedDeclaration"}) - private static java.nio.ByteBuffer memoryMapFile(java.io.File file) throws IOException - { + private static java.nio.ByteBuffer memoryMapFile(java.io.File file) throws IOException { FileChannel roChannel = new RandomAccessFile(file, "r").getChannel(); long fileSize = roChannel.size(); MappedByteBuffer mapFile = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize); - if (!mapFile.isLoaded()) + if (!mapFile.isLoaded()) { mapFile.load(); + } roChannel.close(); return mapFile; } diff --git a/src/gov/nasa/worldwind/formats/nitfs/UserDefinedImageSubheader.java b/src/gov/nasa/worldwind/formats/nitfs/UserDefinedImageSubheader.java index 017cec8a39..4d21ff2a35 100644 --- a/src/gov/nasa/worldwind/formats/nitfs/UserDefinedImageSubheader.java +++ b/src/gov/nasa/worldwind/formats/nitfs/UserDefinedImageSubheader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.nitfs; import gov.nasa.worldwind.formats.rpf.RPFFrameFileComponents; @@ -12,45 +11,41 @@ * @author Lado Garakanidze * @version $Id: UserDefinedImageSubheader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class UserDefinedImageSubheader -{ - public short getOverflow() - { +public class UserDefinedImageSubheader { + + public short getOverflow() { return this.overflow; } - public String getTag() - { + public String getTag() { return this.tag; } - public int getDataLength() - { + public int getDataLength() { return this.dataLength; } - public RPFFrameFileComponents getRPFFrameFileComponents() - { + public RPFFrameFileComponents getRPFFrameFileComponents() { return this.rpfFrameFileComponents; } private RPFFrameFileComponents rpfFrameFileComponents = null; - private short overflow; - private String tag; - private int dataLength; + private short overflow; + private String tag; + private int dataLength; public UserDefinedImageSubheader(java.nio.ByteBuffer buffer) throws NITFSRuntimeException { this.overflow = NITFSUtil.getShortNumeric(buffer, 3); this.tag = NITFSUtil.getString(buffer, 6); this.dataLength = NITFSUtil.getShortNumeric(buffer, 5); - if(0 < this.dataLength) - { - if( RPFFrameFileComponents.DATA_TAG.equals(tag) ) + if (0 < this.dataLength) { + if (RPFFrameFileComponents.DATA_TAG.equals(tag)) { this.rpfFrameFileComponents = new RPFFrameFileComponents(buffer); - else + } else { throw new NITFSRuntimeException("NITFSReader.UnknownOrUnsupportedUserDefinedImageSubheader"); + } } } } diff --git a/src/gov/nasa/worldwind/formats/nmea/NmeaReader.java b/src/gov/nasa/worldwind/formats/nmea/NmeaReader.java index cc71650229..5233ed2031 100644 --- a/src/gov/nasa/worldwind/formats/nmea/NmeaReader.java +++ b/src/gov/nasa/worldwind/formats/nmea/NmeaReader.java @@ -16,39 +16,34 @@ * @author Tom Gaskins * @version $Id: NmeaReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NmeaReader implements Track, TrackSegment -{ +public class NmeaReader implements Track, TrackSegment { + private java.util.List tracks = new java.util.ArrayList(); - private java.util.List segments = - new java.util.ArrayList(); - private java.util.List points = - new java.util.ArrayList(); + private java.util.List segments + = new java.util.ArrayList(); + private java.util.List points + = new java.util.ArrayList(); private String name; private int sentenceNumber = 0; - public NmeaReader() - { + public NmeaReader() { this.tracks.add(this); this.segments.add(this); } - public java.util.List getSegments() - { + public java.util.List getSegments() { return this.segments; } - public String getName() - { + public String getName() { return this.name; } - public int getNumPoints() - { + public int getNumPoints() { return this.points.size(); } - public java.util.List getPoints() - { + public java.util.List getPoints() { return this.points; } @@ -57,10 +52,8 @@ public java.util.List getPoints() * @throws IllegalArgumentException if path is null * @throws java.io.IOException if a read error occurs. */ - public void readFile(String path) throws java.io.IOException - { - if (path == null) - { + public void readFile(String path) throws java.io.IOException { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -69,8 +62,7 @@ public void readFile(String path) throws java.io.IOException this.name = path; java.io.File file = new java.io.File(path); - if (!file.exists()) - { + if (!file.exists()) { String msg = Logging.getMessage("generic.FileNotFound", path); Logging.logger().severe(msg); throw new java.io.FileNotFoundException(path); @@ -79,8 +71,9 @@ public void readFile(String path) throws java.io.IOException java.io.FileInputStream fis = new java.io.FileInputStream(file); this.doReadStream(fis); - if (this.tracks.isEmpty() || this.tracks.get(0).getNumPoints() == 0) + if (this.tracks.isEmpty() || this.tracks.get(0).getNumPoints() == 0) { throw new IllegalArgumentException(Logging.getMessage("formats.notNMEA", path)); + } // java.nio.ByteBuffer buffer = this.doReadFile(fis); // this.parseBuffer(buffer); } @@ -91,10 +84,8 @@ public void readFile(String path) throws java.io.IOException * @throws IllegalArgumentException if stream is null * @throws java.io.IOException if a read error occurs. */ - public void readStream(java.io.InputStream stream, String name) throws java.io.IOException - { - if (stream == null) - { + public void readStream(java.io.InputStream stream, String name) throws java.io.IOException { + if (stream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -104,56 +95,42 @@ public void readStream(java.io.InputStream stream, String name) throws java.io.I this.doReadStream(stream); } - public java.util.List getTracks() - { + public java.util.List getTracks() { return this.tracks; } - public Iterator getTrackPositionIterator() - { - return new Iterator() - { + public Iterator getTrackPositionIterator() { + return new Iterator() { private TrackPointIterator trackPoints = new TrackPointIteratorImpl(NmeaReader.this.tracks); - public boolean hasNext() - { + public boolean hasNext() { return this.trackPoints.hasNext(); } - public Position next() - { + public Position next() { return this.trackPoints.next().getPosition(); } - public void remove() - { + public void remove() { this.trackPoints.remove(); } }; } - private void doReadStream(java.io.InputStream stream) - { + private void doReadStream(java.io.InputStream stream) { String sentence; - try - { - do - { + try { + do { sentence = this.readSentence(stream); - if (sentence != null) - { + if (sentence != null) { ++this.sentenceNumber; this.parseSentence(sentence); } } while (sentence != null); - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { e.printStackTrace(); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { e.printStackTrace(); } } @@ -199,69 +176,63 @@ private void doReadStream(java.io.InputStream stream) // } // } - private String readSentence(java.io.InputStream stream) throws java.io.IOException, InterruptedException - { + private String readSentence(java.io.InputStream stream) throws java.io.IOException, InterruptedException { StringBuilder sb = null; boolean endOfSentence = false; - while (!endOfSentence && !Thread.currentThread().isInterrupted()) - { + while (!endOfSentence && !Thread.currentThread().isInterrupted()) { int b = stream.read(); - if (b < 0) + if (b < 0) { return null; - else if (b == 0) + } else if (b == 0) { Thread.sleep(200); - else if (b == '$') + } else if (b == '$') { sb = new StringBuilder(100); - else if (b == '\r') + } else if (b == '\r') { endOfSentence = true; - else if (sb != null) + } else if (sb != null) { sb.append((char) b); + } } // TODO: check checksum return sb != null ? sb.toString() : null; } - private String readSentence(java.nio.ByteBuffer buffer) - { + private String readSentence(java.nio.ByteBuffer buffer) { StringBuilder sb = new StringBuilder(100); boolean endOfSentence = false; - while (!endOfSentence) - { + while (!endOfSentence) { byte b = buffer.get(); - if (b == '\r') + if (b == '\r') { endOfSentence = true; - else + } else { sb.append((char) b); + } } return sb.toString(); } - private void parseSentence(String sentence) - { + private void parseSentence(String sentence) { String[] words = sentence.split("[,*]"); - if (words[0].equalsIgnoreCase("GPGGA")) + if (words[0].equalsIgnoreCase("GPGGA")) { this.doTrackPoint(words); + } // else if (words[0].equalsIgnoreCase("GPRMC")) // this.doTrackPoint(words); } - private void doTrackPoint(String[] words) - { - try - { + private void doTrackPoint(String[] words) { + try { gov.nasa.worldwind.formats.nmea.NmeaTrackPoint point = new gov.nasa.worldwind.formats.nmea.NmeaTrackPoint( - words); + words); this.points.add(point); - } - catch (Exception e) - { + } catch (Exception e) { System.out.printf("Exception %s at sentence number %d for %s\n", - e.getMessage(), this.sentenceNumber, this.name); + e.getMessage(), this.sentenceNumber, this.name); } } } diff --git a/src/gov/nasa/worldwind/formats/nmea/NmeaTrackPoint.java b/src/gov/nasa/worldwind/formats/nmea/NmeaTrackPoint.java index 0a20eddbbd..4f4e41e589 100644 --- a/src/gov/nasa/worldwind/formats/nmea/NmeaTrackPoint.java +++ b/src/gov/nasa/worldwind/formats/nmea/NmeaTrackPoint.java @@ -13,8 +13,8 @@ * @author tag * @version $Id: NmeaTrackPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NmeaTrackPoint implements TrackPoint -{ +public class NmeaTrackPoint implements TrackPoint { + private double latitude; private double longitude; private double altitude; @@ -25,36 +25,32 @@ public class NmeaTrackPoint implements TrackPoint * @param words The track point words to parse. * @throws IllegalArgumentException if words is null or has length less than 1 */ - public NmeaTrackPoint(String[] words) - { - if (words == null) - { + public NmeaTrackPoint(String[] words) { + if (words == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (words.length < 1) - { + if (words.length < 1) { String msg = Logging.getMessage("generic.ArrayInvalidLength", words.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (words[0].equalsIgnoreCase("GPGGA")) + if (words[0].equalsIgnoreCase("GPGGA")) { this.doGGA(words); - else if (words[0].equalsIgnoreCase("GPRMC")) + } else if (words[0].equalsIgnoreCase("GPRMC")) { this.doRMC(words); + } } /** * @param words * @throws IllegalArgumentException if words is null or has length less than 6 */ - private void doGGA(String[] words) - { + private void doGGA(String[] words) { // words won't be null, but it could be the wrong length - if (words.length < 6) - { + if (words.length < 6) { String msg = Logging.getMessage("generic.ArrayInvalidLength", words.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -63,20 +59,21 @@ private void doGGA(String[] words) this.time = words[1]; this.latitude = this.parseLatitude(words[2], words[3]); this.longitude = this.parseLongitude(words[4], words[5]); - if (words.length >= 11) + if (words.length >= 11) { this.altitude = this.parseElevation(words[9], words[10]); - if (words.length >= 13) + } + if (words.length >= 13) { this.geoidHeight = this.parseElevation(words[11], words[12]); + } } - private void doRMC(String[] words) - { + private void doRMC(String[] words) { } - private double parseLatitude(String angle, String direction) - { - if (angle.length() == 0) + private double parseLatitude(String angle, String direction) { + if (angle.length() == 0) { return 0; + } double minutes = angle.length() > 2 ? Double.parseDouble(angle.substring(2, angle.length())) : 0d; double degrees = Double.parseDouble(angle.substring(0, 2)) + minutes / 60d; @@ -84,10 +81,10 @@ private double parseLatitude(String angle, String direction) return direction.equalsIgnoreCase("S") ? -degrees : degrees; } - private double parseLongitude(String angle, String direction) - { - if (angle.length() == 0) + private double parseLongitude(String angle, String direction) { + if (angle.length() == 0) { return 0; + } double minutes = angle.length() > 3 ? Double.parseDouble(angle.substring(3, angle.length())) : 0d; double degrees = Double.parseDouble(angle.substring(0, 3)) + minutes / 60d; @@ -95,32 +92,34 @@ private double parseLongitude(String angle, String direction) return direction.equalsIgnoreCase("W") ? -degrees : degrees; } - private double parseElevation(String height, String units) - { - if (height.length() == 0) + private double parseElevation(String height, String units) { + if (height.length() == 0) { return 0; + } return Double.parseDouble(height) * unitsToMeters(units); } - private double unitsToMeters(String units) - { + private double unitsToMeters(String units) { double f; if (units.equals("M")) // meters + { f = 1d; - else if (units.equals("f")) // feet + } else if (units.equals("f")) // feet + { f = 3.2808399; - else if (units.equals("F")) // fathoms + } else if (units.equals("F")) // fathoms + { f = 0.5468066528; - else + } else { f = 1d; + } return f; } - public double getLatitude() - { + public double getLatitude() { return latitude; } @@ -128,10 +127,8 @@ public double getLatitude() * @param latitude The new latitude. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 */ - public void setLatitude(double latitude) - { - if (latitude > 90 || latitude < -90) - { + public void setLatitude(double latitude) { + if (latitude > 90 || latitude < -90) { String msg = Logging.getMessage("generic.AngleOutOfRange", latitude); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -140,8 +137,7 @@ public void setLatitude(double latitude) this.latitude = latitude; } - public double getLongitude() - { + public double getLongitude() { return longitude; } @@ -149,10 +145,8 @@ public double getLongitude() * @param longitude The new longitude. * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 */ - public void setLongitude(double longitude) - { - if (longitude > 180 || longitude < -180) - { + public void setLongitude(double longitude) { + if (longitude > 180 || longitude < -180) { String msg = Logging.getMessage("generic.AngleOutOfRange", longitude); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -161,15 +155,12 @@ public void setLongitude(double longitude) this.longitude = longitude; } - public Position getPosition() - { + public Position getPosition() { return Position.fromDegrees(this.latitude, this.longitude, this.altitude); } - public void setPosition(Position position) - { - if (position == null) - { + public void setPosition(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -180,31 +171,26 @@ public void setPosition(Position position) this.altitude = position.getElevation(); } - public double getElevation() - { + public double getElevation() { return this.altitude + this.geoidHeight; } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.altitude = elevation; this.geoidHeight = 0; } - public String getTime() - { + public String getTime() { return time; } - public void setTime(String time) - { + public void setTime(String time) { this.time = time; } @Override - public String toString() - { + public String toString() { return String.format("(%10.8f\u00B0, %11.8f\u00B0, %10.4g m, %10.4g m, %s)", this.latitude, this.longitude, - this.altitude, this.geoidHeight, this.time); + this.altitude, this.geoidHeight, this.time); } } diff --git a/src/gov/nasa/worldwind/formats/nmea/NmeaWriter.java b/src/gov/nasa/worldwind/formats/nmea/NmeaWriter.java index 5211724bda..28a8ddc2d3 100644 --- a/src/gov/nasa/worldwind/formats/nmea/NmeaWriter.java +++ b/src/gov/nasa/worldwind/formats/nmea/NmeaWriter.java @@ -14,29 +14,25 @@ * @author dcollins * @version $Id: NmeaWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NmeaWriter -{ +public class NmeaWriter { + private final java.io.PrintStream printStream; private final String encoding; @SuppressWarnings({"UnusedDeclaration"}) private int sentenceNumber = 0; private static final String DEFAULT_ENCODING = "US-ASCII"; - public NmeaWriter(String path) throws java.io.IOException - { + public NmeaWriter(String path) throws java.io.IOException { this(path, DEFAULT_ENCODING); } - public NmeaWriter(String path, String encoding) throws java.io.IOException - { - if (path == null) - { + public NmeaWriter(String path, String encoding) throws java.io.IOException { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (encoding == null) - { + if (encoding == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -44,47 +40,40 @@ public NmeaWriter(String path, String encoding) throws java.io.IOException this.encoding = encoding; this.printStream = new java.io.PrintStream( - new java.io.BufferedOutputStream(new java.io.FileOutputStream(path)), - false, // Disable autoflush. - this.encoding); // Character mapping from 16-bit UTF characters to bytes. + new java.io.BufferedOutputStream(new java.io.FileOutputStream(path)), + false, // Disable autoflush. + this.encoding); // Character mapping from 16-bit UTF characters to bytes. } - public NmeaWriter(java.io.OutputStream stream) throws java.io.IOException - { - this(stream, DEFAULT_ENCODING); + public NmeaWriter(java.io.OutputStream stream) throws java.io.IOException { + this(stream, DEFAULT_ENCODING); } - public NmeaWriter(java.io.OutputStream stream, String encoding) throws java.io.IOException - { - if (stream == null) - { + public NmeaWriter(java.io.OutputStream stream, String encoding) throws java.io.IOException { + if (stream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (encoding == null) - { + if (encoding == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - + this.encoding = encoding; this.printStream = new java.io.PrintStream( - new java.io.BufferedOutputStream(stream), - false, // Disable autoflush. - this.encoding); // Character mapping from 16-bit UTF characters to bytes. + new java.io.BufferedOutputStream(stream), + false, // Disable autoflush. + this.encoding); // Character mapping from 16-bit UTF characters to bytes. } - public final String getEncoding() - { + public final String getEncoding() { return this.encoding; } - public void writeTrack(Track track) - { - if (track == null) - { + public void writeTrack(Track track) { + if (track == null) { String msg = Logging.getMessage("nullValue.TrackIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -94,55 +83,46 @@ public void writeTrack(Track track) doFlush(); } - public void close() - { + public void close() { doFlush(); this.printStream.close(); } - private void doWriteTrack(Track track, java.io.PrintStream out) - { - if (track != null && track.getSegments() != null) - { - for (TrackSegment ts : track.getSegments()) + private void doWriteTrack(Track track, java.io.PrintStream out) { + if (track != null && track.getSegments() != null) { + for (TrackSegment ts : track.getSegments()) { doWriteTrackSegment(ts, out); + } } } - private void doWriteTrackSegment(TrackSegment segment, java.io.PrintStream out) - { - if (segment != null && segment.getPoints() != null) - { - for (TrackPoint tp : segment.getPoints()) - { - if (tp instanceof NmeaTrackPoint) + private void doWriteTrackSegment(TrackSegment segment, java.io.PrintStream out) { + if (segment != null && segment.getPoints() != null) { + for (TrackPoint tp : segment.getPoints()) { + if (tp instanceof NmeaTrackPoint) { doWriteNmeaTrackPoint((NmeaTrackPoint) tp, out); - else + } else { doWriteTrackPoint(tp, out); + } } } } - private void doWriteTrackPoint(TrackPoint point, java.io.PrintStream out) - { - if (point != null) - { + private void doWriteTrackPoint(TrackPoint point, java.io.PrintStream out) { + if (point != null) { writeGGASentence(point.getTime(), point.getLatitude(), point.getLongitude(), point.getElevation(), 0, out); } } - private void doWriteNmeaTrackPoint(NmeaTrackPoint point, java.io.PrintStream out) - { - if (point != null) - { + private void doWriteNmeaTrackPoint(NmeaTrackPoint point, java.io.PrintStream out) { + if (point != null) { // TODO: separate elevation and geoid-height writeGGASentence(point.getTime(), point.getLatitude(), point.getLongitude(), point.getElevation(), 0, out); } } private void writeGGASentence(String time, double lat, double lon, double altitude, double geoidHeight, - java.io.PrintStream out) - { + java.io.PrintStream out) { this.sentenceNumber++; // Documentation for NMEA Standard 0183 // taken from http://www.gpsinformation.org/dale/nmea.htm#GGA @@ -164,11 +144,11 @@ private void writeGGASentence(String time, double lat, double lon, double altitu // 1 = GPS fix (SPS) // 2 = DGPS fix // 3 = PPS fix - // 4 = Real Time Kinematic - // 5 = Float RTK + // 4 = Real Time Kinematic + // 5 = Float RTK // 6 = estimated (dead reckoning) (2.3 feature) - // 7 = Manual input mode - // 8 = Simulation mode + // 7 = Manual input mode + // 8 = Simulation mode sb.append(""); // Intentionally left blank. sb.append(","); // Number of satellites being tracked @@ -200,53 +180,45 @@ private void writeGGASentence(String time, double lat, double lon, double altitu doFlush(); } - private String formatTime(String time) - { + private String formatTime(String time) { // Format time as "HHMMSS" return (time != null) ? time : ""; } - private String formatLatitude(double degrees) - { + private String formatLatitude(double degrees) { int d = (int) Math.floor(Math.abs(degrees)); double m = 60 * (Math.abs(degrees) - d); // Format latitude as "DDMM.MMM[N|S]" return String.format("%02d%06.3f,%s", d, m, degrees < 0 ? "S" : "N"); } - private String formatLongitude(double degrees) - { + private String formatLongitude(double degrees) { int d = (int) Math.floor(Math.abs(degrees)); double m = 60 * (Math.abs(degrees) - d); // Format longitude as "DDDMM.MMM[N|S]" return String.format("%03d%06.3f,%s", d, m, degrees < 0 ? "W" : "E"); } - private String formatElevation(double metersElevation) - { + private String formatElevation(double metersElevation) { // Format elevation with 1 digit of precision. // This provides decimeter resolution. return String.format("%.1f,M", metersElevation); } - private String formatChecksum(int checksum) - { + private String formatChecksum(int checksum) { return Integer.toHexString(checksum); } - private int computeChecksum(CharSequence s, int start, int end) - { + private int computeChecksum(CharSequence s, int start, int end) { int chksum = 0; - for (int i = start; i < end; i++) - { + for (int i = start; i < end; i++) { int c = 0xFF & (int) s.charAt(i); chksum ^= c; } return chksum; } - private void doFlush() - { + private void doFlush() { this.printStream.flush(); } } diff --git a/src/gov/nasa/worldwind/formats/rpf/Base34Converter.java b/src/gov/nasa/worldwind/formats/rpf/Base34Converter.java index b72f4ed606..5dc4e21576 100644 --- a/src/gov/nasa/worldwind/formats/rpf/Base34Converter.java +++ b/src/gov/nasa/worldwind/formats/rpf/Base34Converter.java @@ -11,33 +11,29 @@ * @author dcollins * @version $Id: Base34Converter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class Base34Converter -{ +class Base34Converter { + /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - private static final char[] BASE34_ALPHABET ={ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; + /* [Section A.3.6, MIL-PRF-89041A] */ + private static final char[] BASE34_ALPHABET = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - public static char[] valueOf(int i, char[] dest, int offset, int count) - { - if (dest == null) - { + /* [Section A.3.6, MIL-PRF-89041A] */ + public static char[] valueOf(int i, char[] dest, int offset, int count) { + if (dest == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (offset < 0 || count < 0 || (offset + count) >= dest.length) - { + if (offset < 0 || count < 0 || (offset + count) >= dest.length) { String message = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().fine(message); throw new IndexOutOfBoundsException(message); } - for (int digit = count + offset - 1; digit >= offset; digit--) - { + for (int digit = count + offset - 1; digit >= offset; digit--) { dest[digit] = BASE34_ALPHABET[i % 34]; i /= 34; } @@ -45,37 +41,32 @@ public static char[] valueOf(int i, char[] dest, int offset, int count) } /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - public static int parseChars(char[] src, int offset, int count) - { - if (src == null) - { + /* [Section A.3.6, MIL-PRF-89041A] */ + public static int parseChars(char[] src, int offset, int count) { + if (src == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (offset < 0 || count < 0 || (offset + count) >= src.length) - { + if (offset < 0 || count < 0 || (offset + count) >= src.length) { String message = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().fine(message); throw new IndexOutOfBoundsException(message); } int i = 0; - for (int digit = offset; digit < offset + count; digit++) - { + for (int digit = offset; digit < offset + count; digit++) { int index; char charUpper = Character.toUpperCase(src[digit]); - if (charUpper >= '0' && charUpper <= '9') + if (charUpper >= '0' && charUpper <= '9') { index = charUpper - '0'; - else if (charUpper >= 'A' && charUpper <= 'H') + } else if (charUpper >= 'A' && charUpper <= 'H') { index = 10 + charUpper - 'A'; - else if (charUpper >= 'J' && charUpper <= 'N') + } else if (charUpper >= 'J' && charUpper <= 'N') { index = 18 + charUpper - 'J'; - else if (charUpper >= 'P' && charUpper <= 'Z') + } else if (charUpper >= 'P' && charUpper <= 'Z') { index = 23 + charUpper - 'P'; - else - { + } else { String message = Logging.getMessage("Base34Converter.Base34Error"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -85,29 +76,26 @@ else if (charUpper >= 'P' && charUpper <= 'Z') return i; } - public static boolean isBase34(char[] src, int offset, int count) - { - if (src == null) - { + public static boolean isBase34(char[] src, int offset, int count) { + if (src == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (offset < 0 || count < 0 || (offset + count) >= src.length) - { + if (offset < 0 || count < 0 || (offset + count) >= src.length) { String message = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().fine(message); throw new IndexOutOfBoundsException(message); } - for (int digit = offset; digit < offset + count; digit++) - { + for (int digit = offset; digit < offset + count; digit++) { char charUpper = Character.toUpperCase(src[digit]); if (!(charUpper >= '0' && charUpper <= '9') - && !(charUpper >= 'A' && charUpper <= 'H') - && !(charUpper >= 'J' && charUpper <= 'N') - && !(charUpper >= 'P' && charUpper <= 'Z')) + && !(charUpper >= 'A' && charUpper <= 'H') + && !(charUpper >= 'J' && charUpper <= 'N') + && !(charUpper >= 'P' && charUpper <= 'Z')) { return false; + } } return true; } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFBoundingRectangleSection.java b/src/gov/nasa/worldwind/formats/rpf/RPFBoundingRectangleSection.java index e8481b1a0f..5860a5f0f9 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFBoundingRectangleSection.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFBoundingRectangleSection.java @@ -15,7 +15,6 @@ * @author brownrigg * @version $Id: RPFBoundingRectangleSection.java 1171 2013-02-11 21:45:02Z dcollins $ */ - public class RPFBoundingRectangleSection { public RPFBoundingRectangleSection(ByteBuffer buffer) { @@ -32,8 +31,9 @@ public List getBoundingRecords() { } private void parseBoundsRecords(ByteBuffer buffer) { - for (int i=0; i bndRectRecords = - new ArrayList(); + private ArrayList bndRectRecords + = new ArrayList(); } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFColorMap.java b/src/gov/nasa/worldwind/formats/rpf/RPFColorMap.java index 23bfc704d3..42ec43d932 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFColorMap.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFColorMap.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; import gov.nasa.worldwind.formats.nitfs.*; @@ -12,59 +11,49 @@ * @author lado * @version $Id: RPFColorMap.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFColorMap -{ - public int getTableID() - { +public class RPFColorMap { + + public int getTableID() { return tableID; } - public int getHistogramRecordLength() - { + public int getHistogramRecordLength() { return histogramRecordLength; } - public int getHistogramTableOffset() - { - return (int)(0xFFFFFFFFL & histogramTableOffset); + public int getHistogramTableOffset() { + return (int) (0xFFFFFFFFL & histogramTableOffset); } - public int getNumOfColorRecords() - { - return (int)(0xFFFFFFFFL & numOfColorRecords); + public int getNumOfColorRecords() { + return (int) (0xFFFFFFFFL & numOfColorRecords); } - public int getColorElementLength() - { - return (int)(0xFFFFFFFFL & colorElementLength); + public int getColorElementLength() { + return (int) (0xFFFFFFFFL & colorElementLength); } - public byte getColor(int colorRec, int bytePosition) - { - long idx = colorRec * this.getNumOfColorRecords() * getColorElementLength() + bytePosition ; - return this.colorMap[(int)idx]; + public byte getColor(int colorRec, int bytePosition) { + long idx = colorRec * this.getNumOfColorRecords() * getColorElementLength() + bytePosition; + return this.colorMap[(int) idx]; } - - - public byte[] getColorMap() - { + public byte[] getColorMap() { return this.colorMap; } - private byte[] colorMap; + private byte[] colorMap; // private byte[] histogramMap; - private int tableID; - private long numOfColorRecords; + private int tableID; + private long numOfColorRecords; - private short colorElementLength; - private int histogramRecordLength; - private long colorTableOffset; - private long histogramTableOffset; + private short colorElementLength; + private int histogramRecordLength; + private long colorTableOffset; + private long histogramTableOffset; - public RPFColorMap(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) - { + public RPFColorMap(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) { this.parseRPFColorOffsetRecord(buffer); // now let's load color map and histogram int saveOffset = buffer.position(); @@ -74,37 +63,38 @@ public RPFColorMap(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) buffer.position(saveOffset); } - private void parseRPFColorOffsetRecord(java.nio.ByteBuffer buffer) - { - this.tableID = NITFSUtil.getUShort(buffer); - this.numOfColorRecords = NITFSUtil.getUInt(buffer); - this.colorElementLength = NITFSUtil.getByteAsShort(buffer); - this.histogramRecordLength = NITFSUtil.getUShort(buffer); - this.colorTableOffset = NITFSUtil.getUInt(buffer); - this.histogramTableOffset = NITFSUtil.getUInt(buffer); + private void parseRPFColorOffsetRecord(java.nio.ByteBuffer buffer) { + this.tableID = NITFSUtil.getUShort(buffer); + this.numOfColorRecords = NITFSUtil.getUInt(buffer); + this.colorElementLength = NITFSUtil.getByteAsShort(buffer); + this.histogramRecordLength = NITFSUtil.getUShort(buffer); + this.colorTableOffset = NITFSUtil.getUInt(buffer); + this.histogramTableOffset = NITFSUtil.getUInt(buffer); } - private void loadColorMaps(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) - { - if (0 == this.numOfColorRecords) + private void loadColorMaps(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) { + if (0 == this.numOfColorRecords) { throw new NITFSRuntimeException("NITFSReader.InvalidNumberOfColorRecords"); - if (0 == this.colorElementLength) + } + if (0 == this.colorElementLength) { throw new NITFSRuntimeException("NITFSReader.InvalidLengthOfColorRecordElement"); + } buffer.position((int) (colormapSubsectionOffset + this.colorTableOffset)); - int mapLength = (int)(this.numOfColorRecords * this.colorElementLength); + int mapLength = (int) (this.numOfColorRecords * this.colorElementLength); this.colorMap = new byte[mapLength]; buffer.get(this.colorMap, 0, mapLength); } - private void loadHistogram(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) - { - if (0 == this.numOfColorRecords) + private void loadHistogram(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) { + if (0 == this.numOfColorRecords) { throw new NITFSRuntimeException("NITFSReader.InvalidNumberOfColorRecords"); - if (0 == this.histogramRecordLength) + } + if (0 == this.histogramRecordLength) { throw new NITFSRuntimeException("NITFSReader.InvalidLengthOfHistogramRecordElement"); + } // skip the loading of the histogram table, just increment a position in the buffer buffer.position((int) (colormapSubsectionOffset + this.histogramTableOffset - + (this.numOfColorRecords * this.histogramRecordLength))); + + (this.numOfColorRecords * this.histogramRecordLength))); } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFCrawler.java b/src/gov/nasa/worldwind/formats/rpf/RPFCrawler.java index f58388c3bc..907b60f4a3 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFCrawler.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFCrawler.java @@ -16,27 +16,25 @@ * @author dcollins * @version $Id: RPFCrawler.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFCrawler -{ +public class RPFCrawler { + public static final String RPF_DIRECTORY = "RPF"; public static final String RPF_OVERVIEW_EXTENSION = ".OVR"; public static final String RPF_TOC_EXTENSION = ".TOC"; - public static interface RPFCrawlerListener - { + public static interface RPFCrawlerListener { + void fileFound(File file, boolean isTOCFile); void finished(); } - public abstract static class RPFGrouper implements RPFCrawlerListener - { + public abstract static class RPFGrouper implements RPFCrawlerListener { + private final RPFFrameProperty groupType; - public RPFGrouper(RPFFrameProperty groupType) - { - if (groupType == null) - { + public RPFGrouper(RPFFrameProperty groupType) { + if (groupType == null) { String message = Logging.getMessage("nullValue.RPFFramePropertyTypeIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -46,79 +44,69 @@ public RPFGrouper(RPFFrameProperty groupType) public abstract void addToGroup(Object groupKey, File rpfFile, RPFFrameFilename rpfFrameFilename); - public void fileFound(File file, boolean isTOCFile) - { - if (isTOCFile) + public void fileFound(File file, boolean isTOCFile) { + if (isTOCFile) { fileFoundTOC(file); - else + } else { fileFoundRPF(file); + } } - private void fileFoundTOC(File file) - { + private void fileFoundTOC(File file) { RPFTOCFile rpftocFile = null; - try - { + try { rpftocFile = RPFTOCFile.load(file); - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().fine(e.getMessage()); } - if (rpftocFile == null) + if (rpftocFile == null) { return; + } List rpfRecords = extractRPFRecords(rpftocFile); - if (rpfRecords == null || rpfRecords.isEmpty()) + if (rpfRecords == null || rpfRecords.isEmpty()) { return; + } RPFFrameFilename firstFrameFilename = null; - try - { + try { firstFrameFilename = RPFFrameFilename.parseFilename(rpfRecords.get(0).getFrameFileName()); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("RPFCrawler.ExceptionParsingFilename", file.getPath()); Logging.logger().log(FINE, message, e); } - if (firstFrameFilename == null) + if (firstFrameFilename == null) { return; + } Object groupKey = this.groupType.getValue(firstFrameFilename); - for (RPFFrameFileIndexSection.RPFFrameFileIndexRecord record : rpfRecords) - { + for (RPFFrameFileIndexSection.RPFFrameFileIndexRecord record : rpfRecords) { String filePath = createAbsolutePath(file.getParentFile().getAbsolutePath(), record.getPathname(), - record.getFrameFileName()); + record.getFrameFileName()); RPFFrameFilename rpfFrameFilename = rpfFrameFilenameFor(file); this.addToGroup(groupKey, new File(filePath), rpfFrameFilename); } } - private void fileFoundRPF(File file) - { + private void fileFoundRPF(File file) { RPFFrameFilename rpfFrameFilename = rpfFrameFilenameFor(file); - if (rpfFrameFilename == null) + if (rpfFrameFilename == null) { return; + } Object groupKey = this.groupType.getValue(rpfFrameFilename); this.addToGroup(groupKey, file, rpfFrameFilename); } - public void finished() - { + public void finished() { } - private RPFFrameFilename rpfFrameFilenameFor(File file) - { + private RPFFrameFilename rpfFrameFilenameFor(File file) { RPFFrameFilename rpfFrameFilename = null; - try - { + try { rpfFrameFilename = RPFFrameFilename.parseFilename(file.getName().toUpperCase()); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("RPFCrawler.ExceptionParsingFilename", file.getPath()); Logging.logger().log(FINE, message, e); } @@ -126,35 +114,29 @@ private RPFFrameFilename rpfFrameFilenameFor(File file) } } - private static class RPFRunner implements Runnable - { + private static class RPFRunner implements Runnable { + private final RPFCrawler context; private final File directory; private final RPFCrawlerListener listener; private final boolean tocFileSearch; - public RPFRunner(RPFCrawler context, File directory, RPFCrawlerListener listener, boolean tocFileSearch) - { + public RPFRunner(RPFCrawler context, File directory, RPFCrawlerListener listener, boolean tocFileSearch) { this.context = context; this.directory = directory; this.listener = listener; this.tocFileSearch = tocFileSearch; } - public void run() - { + public void run() { this.context.process(this.directory, listener, tocFileSearch, true); this.context.threadLock.lock(); - try - { - if (this.context.thread != this.context.deadThread) - { + try { + if (this.context.thread != this.context.deadThread) { listener.finished(); this.context.thread = this.context.deadThread; } - } - finally - { + } finally { this.context.threadLock.unlock(); } } @@ -164,51 +146,46 @@ public void run() private final Lock threadLock = new ReentrantLock(); private volatile Thread thread = null; - public RPFCrawler() - { + public RPFCrawler() { } - private static String createAbsolutePath(String... pathElem) - { + private static String createAbsolutePath(String... pathElem) { StringBuilder sb = new StringBuilder(); - for (String str : pathElem) - { - if (str != null && str.length() > 0) - { + for (String str : pathElem) { + if (str != null && str.length() > 0) { int startIndex = 0; - if (str.startsWith("./") || str.startsWith(".\\")) + if (str.startsWith("./") || str.startsWith(".\\")) { startIndex = 1; - else if (!str.startsWith("/") && !str.startsWith("\\")) + } else if (!str.startsWith("/") && !str.startsWith("\\")) { sb.append(File.separatorChar); + } int endIndex; - if (str.endsWith("/") || str.endsWith("\\")) + if (str.endsWith("/") || str.endsWith("\\")) { endIndex = str.length() - 1; - else + } else { endIndex = str.length(); + } sb.append(str, startIndex, endIndex); } } - if (sb.length() <= 0) + if (sb.length() <= 0) { return null; + } return sb.toString(); } - private static List extractRPFRecords(RPFTOCFile tocFile) - { + private static List extractRPFRecords(RPFTOCFile tocFile) { List rpfFiles - = new LinkedList(); + = new LinkedList(); if (tocFile != null - && tocFile.getFrameFileIndexSection() != null - && tocFile.getFrameFileIndexSection().getFrameFileIndexTable() != null - && tocFile.getFrameFileIndexSection().getFrameFileIndexTable().size() > 0) - { + && tocFile.getFrameFileIndexSection() != null + && tocFile.getFrameFileIndexSection().getFrameFileIndexTable() != null + && tocFile.getFrameFileIndexSection().getFrameFileIndexTable().size() > 0) { for (RPFFrameFileIndexSection.RPFFrameFileIndexRecord frameFileIndexRecord - : tocFile.getFrameFileIndexSection().getFrameFileIndexTable()) - { + : tocFile.getFrameFileIndexSection().getFrameFileIndexTable()) { if (frameFileIndexRecord != null - && frameFileIndexRecord.getFrameFileName() != null - && !frameFileIndexRecord.getFrameFileName().toUpperCase().endsWith(RPF_OVERVIEW_EXTENSION)) - { + && frameFileIndexRecord.getFrameFileName() != null + && !frameFileIndexRecord.getFrameFileName().toUpperCase().endsWith(RPF_OVERVIEW_EXTENSION)) { rpfFiles.add(frameFileIndexRecord); } } @@ -216,131 +193,114 @@ private static List extractRPF return rpfFiles; } - private static boolean isRPFDirectory(File file) - { + private static boolean isRPFDirectory(File file) { return RPF_DIRECTORY.compareToIgnoreCase(file.getName()) == 0; } - private static boolean isRPFFile(File file) - { + private static boolean isRPFFile(File file) { return RPFFrameFilename.isFilename(file.getName().toUpperCase()); } - private static boolean isTOCFile(File file) - { + private static boolean isTOCFile(File file) { return file.getName().toUpperCase().endsWith(RPF_TOC_EXTENSION); } - private void process(File file, RPFCrawlerListener listener, boolean tocFileSearch, boolean inOwnThread) - { + private void process(File file, RPFCrawlerListener listener, boolean tocFileSearch, boolean inOwnThread) { this.threadLock.lock(); - try - { - if (inOwnThread && this.thread == deadThread) + try { + if (inOwnThread && this.thread == deadThread) { return; - } - finally - { + } + } finally { this.threadLock.unlock(); } File[] children = file.listFiles(); - if (tocFileSearch) - { - if (children == null) + if (tocFileSearch) { + if (children == null) { return; - if (isRPFDirectory(file)) + } + if (isRPFDirectory(file)) { this.searchForTOC(children, listener, inOwnThread); - else + } else { this.searchForDirectory(children, listener, true, inOwnThread); - } - else - { - if (RPFFrameFilename.isFilename(file.getName().toUpperCase())) + } + } else { + if (RPFFrameFilename.isFilename(file.getName().toUpperCase())) { listener.fileFound(file, false); - if (children == null) + } + if (children == null) { return; + } this.searchForRPF(children, listener, inOwnThread); } } - private void searchForTOC(File[] contents, RPFCrawlerListener listener, boolean inOwnThread) - { - for (File file : contents) - { + private void searchForTOC(File[] contents, RPFCrawlerListener listener, boolean inOwnThread) { + for (File file : contents) { this.threadLock.lock(); - try - { - if (inOwnThread && this.thread == deadThread) + try { + if (inOwnThread && this.thread == deadThread) { return; - } - finally - { + } + } finally { this.threadLock.unlock(); } - if (isTOCFile(file)) + if (isTOCFile(file)) { listener.fileFound(file, true); + } } } private void searchForDirectory(File[] contents, RPFCrawlerListener listener, boolean tocFileSearch, - boolean inOwnThread) - { - for (File file : contents) - { + boolean inOwnThread) { + for (File file : contents) { this.threadLock.lock(); - try - { - if (inOwnThread && this.thread == deadThread) + try { + if (inOwnThread && this.thread == deadThread) { return; - } - finally - { + } + } finally { this.threadLock.unlock(); } - if (file.isDirectory()) + if (file.isDirectory()) { this.process(file, listener, tocFileSearch, inOwnThread); + } } } - private void searchForRPF(File[] contents, RPFCrawlerListener listener, boolean inOwnThread) - { - for (File file : contents) - { + private void searchForRPF(File[] contents, RPFCrawlerListener listener, boolean inOwnThread) { + for (File file : contents) { this.threadLock.lock(); - try - { - if (inOwnThread && this.thread == deadThread) + try { + if (inOwnThread && this.thread == deadThread) { return; - } - finally - { + } + } finally { this.threadLock.unlock(); } - if (isRPFFile(file)) + if (isRPFFile(file)) { listener.fileFound(file, false); - else if (file.isDirectory()) + } else if (file.isDirectory()) { this.process(file, listener, false, inOwnThread); + } } } - public File[] invoke(File directory, boolean tocFileSearch) - { + public File[] invoke(File directory, boolean tocFileSearch) { File validDir = this.validateDirectory(directory); final Collection results = new ArrayList(); - this.process(validDir, new RPFCrawlerListener() - { - public void fileFound(File file, boolean isTOCFile) - { - if (file.exists()) + this.process(validDir, new RPFCrawlerListener() { + public void fileFound(File file, boolean isTOCFile) { + if (file.exists()) { results.add(file); + } } - public void finished() - { + public void finished() { } }, tocFileSearch, false); File[] tocFileArray = new File[results.size()]; @@ -348,19 +308,15 @@ public void finished() return tocFileArray; } - public void invoke(File directory, RPFCrawlerListener listener, boolean tocFileSearch) - { + public void invoke(File directory, RPFCrawlerListener listener, boolean tocFileSearch) { File validDir = this.validateDirectory(directory); this.process(validDir, listener, tocFileSearch, false); } - public void start(File directory, RPFCrawlerListener listener, boolean tocFileSearch) - { + public void start(File directory, RPFCrawlerListener listener, boolean tocFileSearch) { this.threadLock.lock(); - try - { - if (this.thread != null || this.thread == deadThread) - { + try { + if (this.thread != null || this.thread == deadThread) { String message = Logging.getMessage("RPFCrawler.BadStart"); Logging.logger().fine(message); throw new IllegalStateException(message); @@ -368,42 +324,32 @@ public void start(File directory, RPFCrawlerListener listener, boolean tocFileSe File validDir = this.validateDirectory(directory); this.thread = new Thread(new RPFRunner(this, validDir, listener, tocFileSearch)); this.thread.start(); - } - finally - { + } finally { this.threadLock.unlock(); } } - public void stop() - { + public void stop() { this.threadLock.lock(); - try - { + try { this.thread = deadThread; - } - finally - { + } finally { this.threadLock.unlock(); } } - private File validateDirectory(File directory) - { - if (directory == null) - { + private File validateDirectory(File directory) { + if (directory == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } String path = directory.getAbsolutePath(); - if (!path.endsWith("/") && !path.endsWith("\\")) - { + if (!path.endsWith("/") && !path.endsWith("\\")) { path = path + File.separatorChar; directory = new File(path); } - if (!directory.exists()) - { + if (!directory.exists()) { String message = Logging.getMessage("generic.FileNotFound", directory.getPath()); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFDataSeries.java b/src/gov/nasa/worldwind/formats/rpf/RPFDataSeries.java index 5ce4406228..0558b94b0e 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFDataSeries.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFDataSeries.java @@ -13,8 +13,7 @@ * @author dcollins * @version $Id: RPFDataSeries.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public enum RPFDataSeries -{ +public enum RPFDataSeries { /* [Section 5.1.4, MIL-STD-2411-1] */ DATA_SERIES_GN("GN", "GNC", "1:5,000,000", "Global Navigation Chart", "CADRG", 5000000), DATA_SERIES_JN("JN", "JNC", "1:2,000,000", "Jet Navigation Chart", "CADRG", 2000000), @@ -51,8 +50,8 @@ public enum RPFDataSeries DATA_SERIES_TQ("TQ", "TLM24", "1:24,000", "Topographic Line Map 1:24,000 scale", "CADRG", 24000), DATA_SERIES_HA("HA", "HA", "Various", "Harbor and Approach Charts", "CADRG", -1), DATA_SERIES_CO("CO", "CO", "Various", "Coastal Charts", "CADRG", -1), - DATA_SERIES_OA("OA", "OPAREA", "Various", "Naval Range Operating Area Chart","CADRG", -1), - DATA_SERIES_CG("CG", "CG", "Various", "City Graphics", "CADRG", -1), + DATA_SERIES_OA("OA", "OPAREA", "Various", "Naval Range Operating Area Chart", "CADRG", -1), + DATA_SERIES_CG("CG", "CG", "Various", "City Graphics", "CADRG", -1), DATA_SERIES_C1("C1", "CG", "1:10,000", "City Graphics", "CADRG", 10000), DATA_SERIES_C2("C2", "CG", "1:10,560", "City Graphics", "CADRG", 10560), DATA_SERIES_C3("C3", "CG", "1:11,000", "City Graphics", "CADRG", 11000), @@ -78,7 +77,7 @@ public enum RPFDataSeries DATA_SERIES_CR("CR", "CG", "1:26,000", "City Graphics", "CADRG", 26000), DATA_SERIES_CS("CS", "CG", "1:35,000", "City Graphics", "CADRG", 35000), DATA_SERIES_CT("CT", "CG", "1:36,000", "City Graphics", "CADRG", 36000), - DATA_SERIES_CM("CM", "CM", "Various", "Combat Charts", "CADRG", -1), + DATA_SERIES_CM("CM", "CM", "Various", "Combat Charts", "CADRG", -1), DATA_SERIES_A1("A1", "CM", "1:10,000", "Combat Charts, 1:10,000 scale", "CADRG", 10000), DATA_SERIES_A2("A2", "CM", "1:25,000", "Combat Charts, 1:25,000 scale", "CADRG", 25000), DATA_SERIES_A3("A3", "CM", "1:50,000", "Combat Charts, 1:50,000 scale", "CADRG", 50000), @@ -97,8 +96,7 @@ public enum RPFDataSeries DATA_SERIES_D1("D1", "---", "100m", "Elevation Data from DTED level 1", "CDTED", 100.0), DATA_SERIES_D2("D1", "---", "30m", "Elevation Data from DTED level 2", "CDTED", 30.0), /* [Chart.php] */ - DATA_SERIES_TF("TF", "---", "1:250000", "Transit Fly (UK)", "CADRG", 250000), - ; + DATA_SERIES_TF("TF", "---", "1:250000", "Transit Fly (UK)", "CADRG", 250000),; public final String seriesCode; public final String seriesAbbreviation; @@ -108,8 +106,7 @@ public enum RPFDataSeries public final double scaleOrGSD; private RPFDataSeries(String seriesCode, String seriesAbbreviation, String scaleOrResolution, String dataSeries, - String rpfDataType, double scaleOrGSD) - { + String rpfDataType, double scaleOrGSD) { this.rpfDataType = rpfDataType; this.seriesCode = seriesCode; this.seriesAbbreviation = seriesAbbreviation; @@ -120,32 +117,26 @@ private RPFDataSeries(String seriesCode, String seriesAbbreviation, String scale private static Map enumConstantDirectory = null; - private static synchronized Map enumConstantDirectory() - { - if (enumConstantDirectory == null) - { + private static synchronized Map enumConstantDirectory() { + if (enumConstantDirectory == null) { RPFDataSeries[] universe = RPFDataSeries.class.getEnumConstants(); enumConstantDirectory = new HashMap(2 * universe.length); - for (RPFDataSeries dataSeries : universe) - { + for (RPFDataSeries dataSeries : universe) { enumConstantDirectory.put(dataSeries.seriesCode, dataSeries); } } return enumConstantDirectory; } - public static RPFDataSeries dataSeriesFor(String seriesCode) - { - if (seriesCode == null) - { + public static RPFDataSeries dataSeriesFor(String seriesCode) { + if (seriesCode == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } RPFDataSeries dataSeries = enumConstantDirectory().get(seriesCode); - if (dataSeries == null) - { + if (dataSeries == null) { String message = Logging.getMessage("generic.EnumNotFound", seriesCode); Logging.logger().fine(message); throw new EnumConstantNotPresentException(RPFDataSeries.class, message); @@ -153,10 +144,8 @@ public static RPFDataSeries dataSeriesFor(String seriesCode) return dataSeries; } - public static boolean isDataSeriesCode(String seriesCode) - { - if (seriesCode == null) - { + public static boolean isDataSeriesCode(String seriesCode) { + if (seriesCode == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -168,32 +157,27 @@ public static boolean isDataSeriesCode(String seriesCode) // ============== RPF Data Types ======================= // // ============== RPF Data Types ======================= // // ============== RPF Data Types ======================= // - private static final String CADRG_DATA_TYPE = "CADRG"; private static final String CIB_DATA_TYPE = "CIB"; private static String[] RPF_DATA_TYPES = {"CADRG", "CIB"}; - public static boolean isRPFDataType(String rpfDataType) - { - if (rpfDataType == null) - { + public static boolean isRPFDataType(String rpfDataType) { + if (rpfDataType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - for (String s : RPF_DATA_TYPES) - { - if (s.equalsIgnoreCase(rpfDataType)) + for (String s : RPF_DATA_TYPES) { + if (s.equalsIgnoreCase(rpfDataType)) { return true; + } } return false; } - public static boolean isCADRGDataType(String rpfDataType) - { - if (rpfDataType == null) - { + public static boolean isCADRGDataType(String rpfDataType) { + if (rpfDataType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -202,10 +186,8 @@ public static boolean isCADRGDataType(String rpfDataType) return CADRG_DATA_TYPE.equalsIgnoreCase(rpfDataType); } - public static boolean isCIBDataType(String rpfDataType) - { - if (rpfDataType == null) - { + public static boolean isCIBDataType(String rpfDataType) { + if (rpfDataType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -214,10 +196,8 @@ public static boolean isCIBDataType(String rpfDataType) return CIB_DATA_TYPE.equalsIgnoreCase(rpfDataType); } - public static boolean isCADRGDataSeries(String seriesCode) - { - if (seriesCode == null) - { + public static boolean isCADRGDataSeries(String seriesCode) { + if (seriesCode == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -227,10 +207,8 @@ public static boolean isCADRGDataSeries(String seriesCode) return isCADRGDataType(dataSeries.rpfDataType); } - public static boolean isCIBDataSeries(String seriesCode) - { - if (seriesCode == null) - { + public static boolean isCIBDataSeries(String seriesCode) { + if (seriesCode == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFile.java b/src/gov/nasa/worldwind/formats/rpf/RPFFile.java index 44c8a1de62..f0aaf40791 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFile.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFile.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; import gov.nasa.worldwind.formats.nitfs.*; @@ -14,28 +13,24 @@ * @author lado * @version $Id: RPFFile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFFile -{ +public class RPFFile { + private NITFSMessage nitfsMsg; - private java.io.File rpfFile; + private java.io.File rpfFile; - public File getFile() - { + public File getFile() { return this.rpfFile; } - public NITFSFileHeader getNITFSFileHeader() - { + public NITFSFileHeader getNITFSFileHeader() { return (null != nitfsMsg) ? nitfsMsg.getNITFSFileHeader() : null; } - public NITFSSegment getNITFSSegment(NITFSSegmentType segmentType) - { + public NITFSSegment getNITFSSegment(NITFSSegmentType segmentType) { return (null != nitfsMsg) ? nitfsMsg.getSegment(segmentType) : null; } - protected RPFFile(java.io.File rpfFile) throws IOException - { + protected RPFFile(java.io.File rpfFile) throws IOException { this.rpfFile = rpfFile; this.nitfsMsg = NITFSMessage.load(rpfFile); } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFileComponents.java b/src/gov/nasa/worldwind/formats/rpf/RPFFileComponents.java index 85dcccd348..6386be92d9 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFileComponents.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFileComponents.java @@ -3,48 +3,42 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; + /** * @author Lado Garakanidze * @version $Id: RPFFileComponents.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFFileComponents -{ - private java.nio.ByteBuffer buffer; +public class RPFFileComponents { + + private java.nio.ByteBuffer buffer; private RPFHeaderSection headerSection; private RPFLocationSection locationSection; - public RPFFileComponents(java.nio.ByteBuffer buffer) - { + public RPFFileComponents(java.nio.ByteBuffer buffer) { this.buffer = buffer; this.headerSection = new RPFHeaderSection(buffer); buffer.position(this.headerSection.locationSectionLocation); this.locationSection = new RPFLocationSection(buffer); - + } - public RPFHeaderSection getRPFHeaderSection() - { + public RPFHeaderSection getRPFHeaderSection() { return this.headerSection; } - public RPFFrameFileIndexSection getRPFFrameFileIndexSection() - { - if( 0 < locationSection.getFrameFileIndexSectionSubheaderLength()) - { + public RPFFrameFileIndexSection getRPFFrameFileIndexSection() { + if (0 < locationSection.getFrameFileIndexSectionSubheaderLength()) { this.buffer.position(locationSection.getFrameFileIndexSectionSubheaderLocation()); return new RPFFrameFileIndexSection(buffer); } return null; } - public RPFBoundingRectangleSection getRPFBoundingRectangleSection() - { - if (0 < locationSection.getBoundaryRectangleSectionSubheaderLength()) - { + public RPFBoundingRectangleSection getRPFBoundingRectangleSection() { + if (0 < locationSection.getBoundaryRectangleSectionSubheaderLength()) { this.buffer.position(locationSection.getBoundaryRectangleSectionSubheaderLocation()); return new RPFBoundingRectangleSection(buffer); } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFrameFileComponents.java b/src/gov/nasa/worldwind/formats/rpf/RPFFrameFileComponents.java index f8d5c6b7c6..8921dce150 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFrameFileComponents.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFrameFileComponents.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; import gov.nasa.worldwind.formats.nitfs.*; @@ -13,8 +12,8 @@ * @author lado * @version $Id: RPFFrameFileComponents.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFFrameFileComponents -{ +public class RPFFrameFileComponents { + public static final String DATA_TAG = "RPFIMG"; // [ rpf location section ] @@ -39,7 +38,6 @@ public class RPFFrameFileComponents public int colormapGrayscaleOffsetRecordLength; // [ rpf color converter subsection ] - // [ rpf image description subheader ] public int numOfSpectralGroups; public int numOfSubframeTables; @@ -55,36 +53,36 @@ public class RPFFrameFileComponents // [ rpf related images section ] public RelatedImagesSection relatedImagesSection = null; - public RPFFrameFileComponents(java.nio.ByteBuffer buffer) - { + public RPFFrameFileComponents(java.nio.ByteBuffer buffer) { this.componentLocationTable = new RPFLocationSection(buffer); - if (0 < this.componentLocationTable.getCoverageSectionSubheaderLength()) + if (0 < this.componentLocationTable.getCoverageSectionSubheaderLength()) { this.parseRPFCoverageSection(buffer); + } - if (0 < this.componentLocationTable.getColorGrayscaleSectionSubheaderLength()) + if (0 < this.componentLocationTable.getColorGrayscaleSectionSubheaderLength()) { this.parseColorGrayscaleSection(buffer); + } - if (0 < this.componentLocationTable.getColormapSubsectionLength()) + if (0 < this.componentLocationTable.getColormapSubsectionLength()) { this.parseColormapSubSection(buffer); + } - if (0 < this.componentLocationTable.getColorConverterSubsectionLength()) + if (0 < this.componentLocationTable.getColorConverterSubsectionLength()) { this.parseColorConverterSubsection(buffer); + } - if (0 < this.componentLocationTable.getImageDescriptionSubheaderLength()) - { + if (0 < this.componentLocationTable.getImageDescriptionSubheaderLength()) { buffer.position(this.componentLocationTable.getImageDescriptionSubheaderLocation()); this.parseImageDescriptionSubheader(buffer); } - if (0 < this.componentLocationTable.getRelatedImagesSectionSubheaderLength()) - { + if (0 < this.componentLocationTable.getRelatedImagesSectionSubheaderLength()) { buffer.position(this.componentLocationTable.getRelatedImagesSectionSubheaderLocation()); this.relatedImagesSection = new RelatedImagesSection(buffer); } } - private void parseImageDescriptionSubheader(java.nio.ByteBuffer buffer) - { + private void parseImageDescriptionSubheader(java.nio.ByteBuffer buffer) { this.numOfSpectralGroups = NITFSUtil.getUShort(buffer); this.numOfSubframeTables = NITFSUtil.getUShort(buffer); this.numOfSpectralBandTables = NITFSUtil.getUShort(buffer); @@ -97,34 +95,29 @@ private void parseImageDescriptionSubheader(java.nio.ByteBuffer buffer) this.transparencyMaskTableOffset = NITFSUtil.getUInt(buffer); } - private void parseColorConverterSubsection(java.nio.ByteBuffer buffer) - { + private void parseColorConverterSubsection(java.nio.ByteBuffer buffer) { buffer.position(this.componentLocationTable.getColorConverterSubsectionLocation()); // if (0 < this.numOfColorConverterOffsetRecords) // throw new NITFSRuntimeException("NITFSReader.NotImplemented.ColorConvertorSubsectionReader"); } - private void parseColormapSubSection(java.nio.ByteBuffer buffer) - { + private void parseColormapSubSection(java.nio.ByteBuffer buffer) { buffer.position(this.componentLocationTable.getColormapSubsectionLocation()); this.colormapOffsetTableOffset = NITFSUtil.getUInt(buffer); this.colormapGrayscaleOffsetRecordLength = NITFSUtil.getUShort(buffer); // read color / grayscale AND histogram records; builds a ColorMap (LUT) - if (0 < this.numOfColorGrayscaleOffsetRecords) - { + if (0 < this.numOfColorGrayscaleOffsetRecords) { rpfColorMaps = new RPFColorMap[this.numOfColorGrayscaleOffsetRecords]; - for (int i = 0; i < this.numOfColorGrayscaleOffsetRecords; i++) - { + for (int i = 0; i < this.numOfColorGrayscaleOffsetRecords; i++) { rpfColorMaps[i] = new RPFColorMap(buffer, this.componentLocationTable.getColormapSubsectionLocation()); } - } - else + } else { throw new NITFSRuntimeException("NITFSReader.InvalidNumberOfRPFColorGrayscaleRecords"); + } } - private void parseColorGrayscaleSection(java.nio.ByteBuffer buffer) - { + private void parseColorGrayscaleSection(java.nio.ByteBuffer buffer) { buffer.position(this.componentLocationTable.getColorGrayscaleSectionSubheaderLocation()); this.numOfColorGrayscaleOffsetRecords = NITFSUtil.getByteAsShort(buffer); @@ -132,8 +125,7 @@ private void parseColorGrayscaleSection(java.nio.ByteBuffer buffer) this.externalColorGrayscaleFilename = NITFSUtil.getString(buffer, 12); } - private void parseRPFCoverageSection(java.nio.ByteBuffer buffer) - { + private void parseRPFCoverageSection(java.nio.ByteBuffer buffer) { buffer.position(this.componentLocationTable.getCoverageSectionSubheaderLocation()); this.nwUpperLeft = LatLon.fromDegrees(buffer.getDouble(), buffer.getDouble()); @@ -147,15 +139,14 @@ private void parseRPFCoverageSection(java.nio.ByteBuffer buffer) this.horizontalIntervalLongitude = buffer.getDouble(); } - public class RelatedImagesSection - { + public class RelatedImagesSection { + // [ rpf related images section subheader ] public long relatedImageDescriptionTableOffset; public int numOfRelatedImageDescriptionRecords; public int relatedImageDescriptionRecordLength; - public RelatedImagesSection(java.nio.ByteBuffer buffer) - { + public RelatedImagesSection(java.nio.ByteBuffer buffer) { this.relatedImageDescriptionTableOffset = NITFSUtil.getUInt(buffer); this.numOfRelatedImageDescriptionRecords = NITFSUtil.getUShort(buffer); this.relatedImageDescriptionRecordLength = NITFSUtil.getUShort(buffer); diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFrameFileIndexSection.java b/src/gov/nasa/worldwind/formats/rpf/RPFFrameFileIndexSection.java index 729767c78f..519d49bbab 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFrameFileIndexSection.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFrameFileIndexSection.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; import gov.nasa.worldwind.formats.nitfs.*; @@ -14,8 +13,8 @@ * @author Lado Garakanidze * @version $Id: RPFFrameFileIndexSection.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFFrameFileIndexSection -{ +public class RPFFrameFileIndexSection { + // [ frame file index section subheader ] private String highestSecurityClassification; private long frameFileIndexTableOffset; @@ -24,39 +23,32 @@ public class RPFFrameFileIndexSection private int frameFileIndexRecordLength; // [ frame file index subsection ] - // [ frame file index table ] private ArrayList frameFileIndexTable = new ArrayList(); // [ pathname table ] // private ArrayList pathnameTable = new ArrayList(); - public String getHighestSecurityClassification() - { + public String getHighestSecurityClassification() { return highestSecurityClassification; } - public long getFrameFileIndexTableOffset() - { + public long getFrameFileIndexTableOffset() { return frameFileIndexTableOffset; } - public long getNumOfFrameFileIndexRecords() - { + public long getNumOfFrameFileIndexRecords() { return numOfFrameFileIndexRecords; } - public int getNumOfPathnameRecords() - { + public int getNumOfPathnameRecords() { return numOfPathnameRecords; } - public int getFrameFileIndexRecordLength() - { + public int getFrameFileIndexRecordLength() { return frameFileIndexRecordLength; } - public List getFrameFileIndexTable() - { + public List getFrameFileIndexTable() { return frameFileIndexTable; } @@ -64,9 +56,7 @@ public List getFrameFileIndexTable() // { // return pathnameTable; // } - - public RPFFrameFileIndexSection(java.nio.ByteBuffer buffer) - { + public RPFFrameFileIndexSection(java.nio.ByteBuffer buffer) { // [ frame file index section subheader ] this.highestSecurityClassification = NITFSUtil.getString(buffer, 1); this.frameFileIndexTableOffset = NITFSUtil.getUInt(buffer); @@ -77,90 +67,75 @@ public RPFFrameFileIndexSection(java.nio.ByteBuffer buffer) this.parseFrameFileIndexAndPathnameTables(buffer); } - private void parseFrameFileIndexAndPathnameTables(java.nio.ByteBuffer buffer) - { + private void parseFrameFileIndexAndPathnameTables(java.nio.ByteBuffer buffer) { int theSectionOffset = buffer.position(); Hashtable pathnames = new Hashtable(); - for (int i = 0; i < this.numOfFrameFileIndexRecords; i++) - { + for (int i = 0; i < this.numOfFrameFileIndexRecords; i++) { this.frameFileIndexTable.add(new RPFFrameFileIndexRecord(buffer)); } - for (int i = 0; i < this.numOfPathnameRecords; i++) - { + for (int i = 0; i < this.numOfPathnameRecords; i++) { int relOffset = buffer.position() - theSectionOffset; int len = NITFSUtil.getUShort(buffer); pathnames.put(relOffset, NITFSUtil.getString(buffer, len)); } - if (0 < this.frameFileIndexTable.size() && 0 < pathnames.size()) - { // update pathname field in every RPFFrameFileIndexRecord - for (RPFFrameFileIndexRecord rec : this.frameFileIndexTable) - { + if (0 < this.frameFileIndexTable.size() && 0 < pathnames.size()) { // update pathname field in every RPFFrameFileIndexRecord + for (RPFFrameFileIndexRecord rec : this.frameFileIndexTable) { int offset = (int) rec.getPathnameRecordOffset(); - if (pathnames.containsKey(offset)) + if (pathnames.containsKey(offset)) { rec.setPathname(pathnames.get(offset)); - else + } else { throw new NITFSRuntimeException("NITFSReader.CorrespondingPathnameWasNotFound"); + } } } } - public class RPFFrameFileIndexRecord - { - public int getBoundaryRectangleRecordNumber() - { + public class RPFFrameFileIndexRecord { + + public int getBoundaryRectangleRecordNumber() { return boundaryRectangleRecordNumber; } - public int getFrameLocationRowNumber() - { + public int getFrameLocationRowNumber() { return frameLocationRowNumber; } - public int getFrameLocationColumnNumber() - { + public int getFrameLocationColumnNumber() { return frameLocationColumnNumber; } - public String getFrameFileName() - { + public String getFrameFileName() { return frameFileName; } - public String getGeoLocation() - { + public String getGeoLocation() { return geoLocation; } - public String getSecurityClass() - { + public String getSecurityClass() { return securityClass; } - public String getSecurityCountryCode() - { + public String getSecurityCountryCode() { return securityCountryCode; } - public String getSecurityReleaseMark() - { + public String getSecurityReleaseMark() { return securityReleaseMark; } - public long getPathnameRecordOffset() - { + public long getPathnameRecordOffset() { return pathnameRecordOffset; } - public String getPathname() - { + public String getPathname() { return pathname; } - public void setPathname(String pathname) - { + public void setPathname(String pathname) { this.pathname = pathname; } @@ -175,8 +150,7 @@ public void setPathname(String pathname) private String securityReleaseMark; private String pathname; // this field is not part of the NITFS spec - public RPFFrameFileIndexRecord(java.nio.ByteBuffer buffer) - { + public RPFFrameFileIndexRecord(java.nio.ByteBuffer buffer) { this.boundaryRectangleRecordNumber = NITFSUtil.getUShort(buffer); this.frameLocationRowNumber = NITFSUtil.getUShort(buffer); this.frameLocationColumnNumber = NITFSUtil.getUShort(buffer); diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFrameFilename.java b/src/gov/nasa/worldwind/formats/rpf/RPFFrameFilename.java index bf266a44cd..dd78c7a565 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFrameFilename.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFrameFilename.java @@ -31,8 +31,7 @@ * @author dcollins * @version $Id: RPFFrameFilename.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFFrameFilename -{ +public class RPFFrameFilename { // TODO: use nitfs-rpf naming convention private final String dataSeriesCode; @@ -46,8 +45,7 @@ public class RPFFrameFilename private static final int FILENAME_LENGTH = 12; - private RPFFrameFilename(String dataSeriesCode, int frameNumber, char producerId, int version, char zoneCode) - { + private RPFFrameFilename(String dataSeriesCode, int frameNumber, char producerId, int version, char zoneCode) { this.dataSeriesCode = dataSeriesCode; this.frameNumber = frameNumber; this.producerId = producerId; @@ -56,23 +54,20 @@ private RPFFrameFilename(String dataSeriesCode, int frameNumber, char producerId } /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - public static RPFFrameFilename parseFilename(String filename) - { - if (filename == null) - { + /* [Section A.3.6, MIL-PRF-89041A] */ + public static RPFFrameFilename parseFilename(String filename) { + if (filename == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (filename.length() != FILENAME_LENGTH) - { + if (filename.length() != FILENAME_LENGTH) { String message = Logging.getMessage("RPFFrameFilename.BadFilenameLength", filename); Logging.logger().fine(message); throw new RPFFrameFilenameFormatException(message); } - char[] buffer = new char[FILENAME_LENGTH]; + char[] buffer = new char[FILENAME_LENGTH]; filename.getChars(0, FILENAME_LENGTH, buffer, 0); char producerId = buffer[7]; @@ -82,21 +77,17 @@ public static RPFFrameFilename parseFilename(String filename) // Default to CADRG filename structure. int frameChars = 5; int versionChars = 2; - if (RPFDataSeries.isCIBDataSeries(dataSeriesCode)) - { + if (RPFDataSeries.isCIBDataSeries(dataSeriesCode)) { frameChars = 6; versionChars = 1; } int frameNumber; int version; - try - { + try { frameNumber = Base34Converter.parseChars(buffer, 0, frameChars); version = Base34Converter.parseChars(buffer, frameChars, versionChars); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { String message = Logging.getMessage("RPFFrameFilename.IntegerNotParsed"); Logging.logger().fine(message); throw new RPFFrameFilenameFormatException(message, e); @@ -106,14 +97,12 @@ public static RPFFrameFilename parseFilename(String filename) } /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - private static void toCharArray(RPFFrameFilename frameFilename, char[] dest) - { + /* [Section A.3.6, MIL-PRF-89041A] */ + private static void toCharArray(RPFFrameFilename frameFilename, char[] dest) { // Default to CARDG filename strucutre. int frameChars = 5; int versionChars = 2; - if (RPFDataSeries.isCIBDataSeries(frameFilename.dataSeriesCode)) - { + if (RPFDataSeries.isCIBDataSeries(frameFilename.dataSeriesCode)) { frameChars = 6; versionChars = 1; } @@ -126,38 +115,41 @@ private static void toCharArray(RPFFrameFilename frameFilename, char[] dest) dest[11] = frameFilename.zoneCode; } - public final boolean equals(Object o) - { - if (this == o) + public final boolean equals(Object o) { + if (this == o) { return true; - if (o == null || o.getClass() != this.getClass()) + } + if (o == null || o.getClass() != this.getClass()) { return false; + } final RPFFrameFilename that = (RPFFrameFilename) o; - if (Character.toUpperCase(this.zoneCode) != Character.toUpperCase(that.zoneCode)) + if (Character.toUpperCase(this.zoneCode) != Character.toUpperCase(that.zoneCode)) { return false; - if (this.frameNumber != that.frameNumber) + } + if (this.frameNumber != that.frameNumber) { return false; - if (this.dataSeriesCode != null ? !this.dataSeriesCode.equalsIgnoreCase(that.dataSeriesCode) : that.dataSeriesCode != null) + } + if (this.dataSeriesCode != null ? !this.dataSeriesCode.equalsIgnoreCase(that.dataSeriesCode) : that.dataSeriesCode != null) { return false; - if (Character.toUpperCase(this.producerId) != Character.toUpperCase(that.producerId)) + } + if (Character.toUpperCase(this.producerId) != Character.toUpperCase(that.producerId)) { return false; + } //noinspection RedundantIfStatement - if (this.version != that.version) + if (this.version != that.version) { return false; + } return true; } - public final String getDataSeriesCode() - { + public final String getDataSeriesCode() { return this.dataSeriesCode; } - public final String getFilename() - { - if (this.filename == null) - { + public final String getFilename() { + if (this.filename == null) { char[] buffer = new char[FILENAME_LENGTH]; toCharArray(this, buffer); this.filename = new String(buffer); @@ -165,38 +157,34 @@ public final String getFilename() return this.filename; } - public final int getFrameNumber() - { + public final int getFrameNumber() { return this.frameNumber; } - public final char getProducerId() - { + public final char getProducerId() { return this.producerId; } - public final int getVersion() - { + public final int getVersion() { return this.version; } - public final char getZoneCode() - { + public final char getZoneCode() { return this.zoneCode; } - public int hashCode() - { - if (this.hashCode < 0) + public int hashCode() { + if (this.hashCode < 0) { this.hashCode = this.computeHash(); + } return this.hashCode; } - private int computeHash() - { + private int computeHash() { int hash = 0; - if (this.dataSeriesCode != null) + if (this.dataSeriesCode != null) { hash = this.dataSeriesCode.hashCode(); + } hash = 29 * hash + frameNumber; hash = 29 * hash + (int) producerId; hash = 29 * hash + version; @@ -204,39 +192,42 @@ private int computeHash() return hash; } - public static boolean isFilename(String str) - { - if (str == null) - { + public static boolean isFilename(String str) { + if (str == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (str.length() != FILENAME_LENGTH) + if (str.length() != FILENAME_LENGTH) { return false; + } char[] buffer = new char[FILENAME_LENGTH]; str.getChars(0, 12, buffer, 0); - if (!Base34Converter.isBase34(buffer, 0, 7)) + if (!Base34Converter.isBase34(buffer, 0, 7)) { return false; - if (!RPFProducer.isProducerId(buffer[7])) + } + if (!RPFProducer.isProducerId(buffer[7])) { return false; - if ('.' != buffer[8]) + } + if ('.' != buffer[8]) { return false; + } String seriesCode = str.substring(9, 11); - if (!RPFDataSeries.isDataSeriesCode(seriesCode)) + if (!RPFDataSeries.isDataSeriesCode(seriesCode)) { return false; + } //noinspection RedundantIfStatement - if (!RPFZone.isZoneCode(buffer[11])) + if (!RPFZone.isZoneCode(buffer[11])) { return false; + } return true; } - public final String toString() - { + public final String toString() { return this.getFilename(); } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFrameFilenameFormatException.java b/src/gov/nasa/worldwind/formats/rpf/RPFFrameFilenameFormatException.java index dc327b5d6d..8e310c3d05 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFrameFilenameFormatException.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFrameFilenameFormatException.java @@ -9,24 +9,20 @@ * @author dcollins * @version $Id: RPFFrameFilenameFormatException.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFFrameFilenameFormatException extends IllegalArgumentException -{ - public RPFFrameFilenameFormatException() - { +public class RPFFrameFilenameFormatException extends IllegalArgumentException { + + public RPFFrameFilenameFormatException() { } - public RPFFrameFilenameFormatException(String message) - { + public RPFFrameFilenameFormatException(String message) { super(message); } - public RPFFrameFilenameFormatException(String message, Throwable cause) - { + public RPFFrameFilenameFormatException(String message, Throwable cause) { super(message, cause); } - public RPFFrameFilenameFormatException(Throwable cause) - { + public RPFFrameFilenameFormatException(Throwable cause) { super(cause); } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFrameProperty.java b/src/gov/nasa/worldwind/formats/rpf/RPFFrameProperty.java index ae7e4ba7d7..321a27a5bc 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFrameProperty.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFrameProperty.java @@ -9,50 +9,44 @@ * @author dcollins * @version $Id: RPFFrameProperty.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public enum RPFFrameProperty -{ - DATA_SERIES - { - public Object getValue(RPFFrameFilename frameFilename) - { - if (frameFilename == null) +public enum RPFFrameProperty { + DATA_SERIES { + public Object getValue(RPFFrameFilename frameFilename) { + if (frameFilename == null) { return null; + } return frameFilename.getDataSeriesCode(); } }, - FRAME_NUMBER - { - public Object getValue(RPFFrameFilename frameFilename) - { - if (frameFilename == null) + FRAME_NUMBER { + public Object getValue(RPFFrameFilename frameFilename) { + if (frameFilename == null) { return null; + } return frameFilename.getFrameNumber(); } }, - PRODUCER - { - public Object getValue(RPFFrameFilename frameFilename) - { - if (frameFilename == null) + PRODUCER { + public Object getValue(RPFFrameFilename frameFilename) { + if (frameFilename == null) { return null; + } return frameFilename.getProducerId(); } }, - VERSION - { - public Object getValue(RPFFrameFilename frameFilename) - { - if (frameFilename == null) + VERSION { + public Object getValue(RPFFrameFilename frameFilename) { + if (frameFilename == null) { return null; + } return frameFilename.getVersion(); } }, - ZONE - { - public Object getValue(RPFFrameFilename frameFilename) - { - if (frameFilename == null) + ZONE { + public Object getValue(RPFFrameFilename frameFilename) { + if (frameFilename == null) { return null; + } return frameFilename.getZoneCode(); } }; diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFrameStructure.java b/src/gov/nasa/worldwind/formats/rpf/RPFFrameStructure.java index c68622c795..5523d58a52 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFrameStructure.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFrameStructure.java @@ -9,18 +9,16 @@ * @author dcollins * @version $Id: RPFFrameStructure.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class RPFFrameStructure -{ +class RPFFrameStructure { + static final int PIXEL_ROWS_PER_FRAME = 1536; static final int SUBFRAME_ROWS_PER_FRAME = 6; - public final int getPixelRowsPerFrame() - { + public final int getPixelRowsPerFrame() { return PIXEL_ROWS_PER_FRAME; } - public final int getSubframeRowsPerFrame() - { + public final int getSubframeRowsPerFrame() { return SUBFRAME_ROWS_PER_FRAME; } @@ -29,42 +27,40 @@ public final int getSubframeRowsPerFrame() private static final int[] EAST_WEST_PIXEL_SPACING_CONSTANT = { 369664, 302592, 245760, 199168, 163328, 137216, 110080, 82432}; private static final int[] EQUATORWARD_NOMINAL_BOUNDARY = { - 0, 32, 48, 56, 64, 68, 72, 76, 80}; + 0, 32, 48, 56, 64, 68, 72, 76, 80}; private static final int[] POLEWARD_NOMINAL_BOUNDARY = { 32, 48, 56, 64, 68, 72, 76, 80, 90}; - static int eastWestPixelSpacingConstant(char zoneCode) - { + static int eastWestPixelSpacingConstant(char zoneCode) { int index = RPFZone.indexFor(zoneCode) % 9; - if (index < 0) + if (index < 0) { return -1; + } return EAST_WEST_PIXEL_SPACING_CONSTANT[index]; } - static int northSouthPixelSpacingConstant() - { + static int northSouthPixelSpacingConstant() { return NORTH_SOUTH_PIXEL_SPACING_CONSTANT; } - static int equatorwardNominalBoundary(char zoneCode) - { + static int equatorwardNominalBoundary(char zoneCode) { return nominalBoundary(zoneCode, EQUATORWARD_NOMINAL_BOUNDARY); } - static int polewardNominalBoundary(char zoneCode) - { + static int polewardNominalBoundary(char zoneCode) { return nominalBoundary(zoneCode, POLEWARD_NOMINAL_BOUNDARY); } - private static int nominalBoundary(char zoneCode, int[] boundaryArray) - { + private static int nominalBoundary(char zoneCode, int[] boundaryArray) { int index = RPFZone.indexFor(zoneCode) % 9; - if (index < 0) + if (index < 0) { return -1; + } - if (!RPFZone.isZoneInUpperHemisphere(zoneCode)) + if (!RPFZone.isZoneInUpperHemisphere(zoneCode)) { return 0 - boundaryArray[index]; + } return boundaryArray[index]; } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFFrameTransform.java b/src/gov/nasa/worldwind/formats/rpf/RPFFrameTransform.java index b4c45968d7..95174f201b 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFFrameTransform.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFFrameTransform.java @@ -15,28 +15,23 @@ * @author dcollins * @version $Id: RPFFrameTransform.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class RPFFrameTransform -{ - RPFFrameTransform() - { +public abstract class RPFFrameTransform { + + RPFFrameTransform() { } - public static RPFFrameTransform createFrameTransform(char zoneCode, String rpfDataType, double resolution) - { - if (!RPFZone.isZoneCode(zoneCode)) - { + public static RPFFrameTransform createFrameTransform(char zoneCode, String rpfDataType, double resolution) { + if (!RPFZone.isZoneCode(zoneCode)) { String message = Logging.getMessage("RPFZone.UnknownZoneCode", zoneCode); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) - { + if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) { String message = Logging.getMessage("RPFDataSeries.UnkownDataType", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (resolution < 0) - { + if (resolution < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", resolution); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -45,15 +40,11 @@ public static RPFFrameTransform createFrameTransform(char zoneCode, String rpfDa return newFrameTransform(zoneCode, rpfDataType, resolution); } - private static RPFFrameTransform newFrameTransform(char zoneCode, String rpfDataType, double resolution) - { + private static RPFFrameTransform newFrameTransform(char zoneCode, String rpfDataType, double resolution) { boolean isNonpolarZone = !RPFZone.isPolarZone(zoneCode); - if (isNonpolarZone) - { + if (isNonpolarZone) { return RPFNonpolarFrameTransform.createNonpolarFrameTransform(zoneCode, rpfDataType, resolution); - } - else - { + } else { return RPFPolarFrameTransform.createPolarFrameTransform(zoneCode, rpfDataType, resolution); } } @@ -73,54 +64,47 @@ private static RPFFrameTransform newFrameTransform(char zoneCode, String rpfData public abstract RPFImage[] deproject(int frameNumber, BufferedImage frame); /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - static int frameNumber(int row, int column, int columnFrames) - { + /* [Section A.3.6, MIL-PRF-89041A] */ + static int frameNumber(int row, int column, int columnFrames) { return column + row * columnFrames; } /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - static int maxFrameNumber(int rowFrames, int columnFrames) - { + /* [Section A.3.6, MIL-PRF-89041A] */ + static int maxFrameNumber(int rowFrames, int columnFrames) { return (rowFrames * columnFrames) - 1; } /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - static int frameRow(int frameNumber, int columnFrames) - { + /* [Section A.3.6, MIL-PRF-89041A] */ + static int frameRow(int frameNumber, int columnFrames) { return (int) (frameNumber / (double) columnFrames); } /* [Section 30.6, MIL-C-89038] */ - /* [Section A.3.6, MIL-PRF-89041A] */ - static int frameColumn(int frameNumber, int frameRow, int columnFrames) - { + /* [Section A.3.6, MIL-PRF-89041A] */ + static int frameColumn(int frameNumber, int frameRow, int columnFrames) { return frameNumber - (frameRow * columnFrames); } // // A class to bundle the results of deprojection -- a BufferedImage and its Sector. // - public class RPFImage - { + public class RPFImage { + public Sector sector; public BufferedImage image; - RPFImage(Sector sector, BufferedImage image) - { + RPFImage(Sector sector, BufferedImage image) { this.sector = sector; this.image = image; } - public Sector getSector() - { + public Sector getSector() { return this.sector; } - public BufferedImage getImage() - { + public BufferedImage getImage() { return this.image; } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFHeaderSection.java b/src/gov/nasa/worldwind/formats/rpf/RPFHeaderSection.java index f80ed79572..4e08b574a5 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFHeaderSection.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFHeaderSection.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; import gov.nasa.worldwind.formats.nitfs.NITFSUtil; @@ -12,23 +11,22 @@ * @author Lado Garakanidze * @version $Id: RPFHeaderSection.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class RPFHeaderSection -{ +class RPFHeaderSection { + public static final String DATA_TAG = "RPFHDR"; - public boolean endianIndicator; - public short headerLength; - public String filename; - public short updateIndicator; // new | replacement | update - public String govSpecNumber; - public String govSpecDate; - public String securityClass; - public String securityCountryCode; - public String securityReleaseMark; - public int locationSectionLocation; + public boolean endianIndicator; + public short headerLength; + public String filename; + public short updateIndicator; // new | replacement | update + public String govSpecNumber; + public String govSpecDate; + public String securityClass; + public String securityCountryCode; + public String securityReleaseMark; + public int locationSectionLocation; - public RPFHeaderSection(java.nio.ByteBuffer buffer) - { + public RPFHeaderSection(java.nio.ByteBuffer buffer) { this.endianIndicator = ((byte) 0 != buffer.get()); // reads 1 byte, 0 for big endian this.headerLength = buffer.getShort(); // reads 2 bytes this.filename = NITFSUtil.getString(buffer, 12); diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFImageFile.java b/src/gov/nasa/worldwind/formats/rpf/RPFImageFile.java index 0b10523604..ae5437631e 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFImageFile.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFImageFile.java @@ -17,31 +17,25 @@ * @author lado * @version $Id: RPFImageFile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFImageFile extends RPFFile -{ +public class RPFImageFile extends RPFFile { + private NITFSImageSegment imageSegment = null; private UserDefinedImageSubheader imageSubheader = null; private RPFFrameFileComponents rpfFrameFileComponents = null; - public RPFFrameFileComponents getRPFFrameFileComponents() - { + public RPFFrameFileComponents getRPFFrameFileComponents() { return this.rpfFrameFileComponents; } - public UserDefinedImageSubheader getImageSubheader() - { + public UserDefinedImageSubheader getImageSubheader() { return this.imageSubheader; } - public NITFSImageSegment getImageSegment() - { + public NITFSImageSegment getImageSegment() { return this.imageSegment; } - - - private RPFImageFile(java.io.File rpfFile) throws java.io.IOException, NITFSRuntimeException - { + private RPFImageFile(java.io.File rpfFile) throws java.io.IOException, NITFSRuntimeException { super(rpfFile); this.imageSegment = (NITFSImageSegment) this.getNITFSSegment(NITFSSegmentType.IMAGE_SEGMENT); @@ -51,18 +45,19 @@ private RPFImageFile(java.io.File rpfFile) throws java.io.IOException, NITFSRunt this.rpfFrameFileComponents = this.imageSubheader.getRPFFrameFileComponents(); } - private void validateRPFImage() throws NITFSRuntimeException - { - if ( null == this.imageSegment ) + private void validateRPFImage() throws NITFSRuntimeException { + if (null == this.imageSegment) { throw new NITFSRuntimeException("NITFSReader.ImageSegmentWasNotFound"); - if( null == this.imageSegment.getUserDefinedImageSubheader()) + } + if (null == this.imageSegment.getUserDefinedImageSubheader()) { throw new NITFSRuntimeException("NITFSReader.UserDefinedImageSubheaderWasNotFound"); - if( null == this.imageSegment.getUserDefinedImageSubheader().getRPFFrameFileComponents()) + } + if (null == this.imageSegment.getUserDefinedImageSubheader().getRPFFrameFileComponents()) { throw new NITFSRuntimeException("NITFSReader.RPFFrameFileComponentsWereNotFoundInUserDefinedImageSubheader"); + } } - public int[] getImagePixelsAsArray(int[] dest, RPFImageType imageType) - { + public int[] getImagePixelsAsArray(int[] dest, RPFImageType imageType) { //IntBuffer buffer = IntBuffer.wrap(dest); //this.getImagePixelsAsBuffer(buffer, imageType); this.getImageSegment().getImagePixelsAsArray(dest, imageType); @@ -75,16 +70,15 @@ public int[] getImagePixelsAsArray(int[] dest, RPFImageType imageType) // this.imageSegment.getImagePixelsAsArray(dest, imageType); // return dest; //} - - public BufferedImage getBufferedImage() - { - if (null == this.imageSegment) + public BufferedImage getBufferedImage() { + if (null == this.imageSegment) { return null; + } BufferedImage bimage = new BufferedImage( - this.getImageSegment().numSignificantCols, - this.getImageSegment().numSignificantRows, - BufferedImage.TYPE_INT_ARGB); + this.getImageSegment().numSignificantCols, + this.getImageSegment().numSignificantRows, + BufferedImage.TYPE_INT_ARGB); WritableRaster raster = bimage.getRaster(); java.awt.image.DataBufferInt dataBuffer = (java.awt.image.DataBufferInt) raster.getDataBuffer(); @@ -95,11 +89,11 @@ public BufferedImage getBufferedImage() return bimage; } - public boolean hasTransparentAreas() - { + public boolean hasTransparentAreas() { //noinspection SimplifiableIfStatement - if(null != this.imageSegment) + if (null != this.imageSegment) { return (this.imageSegment.hasTransparentPixels() || this.imageSegment.hasMaskedSubframes()); + } return false; } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFImageType.java b/src/gov/nasa/worldwind/formats/rpf/RPFImageType.java index 89de9abda2..7536d9e843 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFImageType.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFImageType.java @@ -3,14 +3,13 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; + /** * @author lado * @version $Id: RPFImageType.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public enum RPFImageType -{ +public enum RPFImageType { IMAGE_TYPE_RGB, IMAGE_TYPE_RGB_ALPHA, IMAGE_TYPE_ALPHA_RGB, diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFLocationSection.java b/src/gov/nasa/worldwind/formats/rpf/RPFLocationSection.java index 0279a79e65..961f2d551d 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFLocationSection.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFLocationSection.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; import gov.nasa.worldwind.formats.nitfs.*; @@ -12,292 +11,285 @@ * @author Lado Garakanidze * @version $Id: RPFLocationSection.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFLocationSection -{ - private java.util.Hashtable table = - new java.util.Hashtable(); - - public int getHeaderComponentLocation() - { - return this.getLocation(128); - } - public int getHeaderComponentLength() - { - return this.getLength(128); - } - public int getLocationComponentLocation() - { - return this.getLocation(129); - } - public int getLocationComponentLength() - { - return this.getLength(129); - } - public int getCoverageSectionSubheaderLocation() - { - return this.getLocation(130); - } - public int getCoverageSectionSubheaderLength() - { - return this.getLength(130); - } - public int getCompressionSectionSubheaderLocation() - { - return this.getLocation(131); - } - public int getCompressionSectionSubheaderLength() - { - return this.getLength(131); - } - public int getCompressionLookupSubsectionLocation() - { - return this.getLocation(132); - } - public int getCompressionLookupSubsectionLength() - { - return this.getLength(132); - } - public int getCompressionParameterSubsectionLocation() - { - return this.getLocation(133); - } - public int getCompressionParameterSubsectionLength() - { - return this.getLength(133); - } - public int getColorGrayscaleSectionSubheaderLocation() - { - return this.getLocation(134); - } - public int getColorGrayscaleSectionSubheaderLength() - { - return this.getLength(134); - } - public int getColormapSubsectionLocation() - { - return this.getLocation(135); - } - public int getColormapSubsectionLength() - { - return this.getLength(135); - } - public int getImageDescriptionSubheaderLocation() - { - return this.getLocation(136); - } - public int getImageDescriptionSubheaderLength() - { - return this.getLength(136); - } - public int getImageDisplayParametersSubheaderLocation() - { - return this.getLocation(137); - } - public int getImageDisplayParametersSubheaderLength() - { - return this.getLength(137); - } - public int getMaskSubsectionLocation() - { - return this.getLocation(138); - } - public int getMaskSubsectionLength() - { - return this.getLength(138); - } - public int getColorConverterSubsectionLocation() - { - return this.getLocation(139); - } - public int getColorConverterSubsectionLength() - { - return this.getLength(139); - } +public class RPFLocationSection { - public int getSpatialDataSubsectionLocation() - { - return this.getLocation(140); - } - public int getSpatialDataSubsectionLength() - { - return this.getLength(140); - } - public int getAttributeSectionSubheaderLocation() - { - return this.getLocation(141); - } - public int getAttributeSectionSubheaderLength() - { - return this.getLength(141); - } - public int getAttributeSubsectionLocation() - { - return this.getLocation(142); - } - public int getAttributeSubsectionLength() - { - return this.getLength(142); - } - public int getExplicitArealCoverageTableLocation() - { - return this.getLocation(143); - } - public int getExplicitArealCoverageTableLength() - { - return this.getLength(143); - } - public int getRelatedImagesSectionSubheaderLocation() - { - return this.getLocation(144); - } - public int getRelatedImagesSectionSubheaderLength() - { - return this.getLength(144); - } - public int getRelatedImagesSubsectionLocation() - { - return this.getLocation(145); - } - public int getRelatedImagesSubsectionLength() - { - return this.getLength(145); - } - public int getReplaceUpdateSectionSubheaderLocation() - { - return this.getLocation(146); - } - public int getReplaceUpdateSectionSubheaderLength() - { - return this.getLength(146); - } - public int getReplaceUpdateTableLocation() - { - return this.getLocation(147); - } - public int getReplaceUpdateTableLength() - { - return this.getLength(147); - } - public int getBoundaryRectangleSectionSubheaderLocation() - { - return this.getLocation(148); - } - public int getBoundaryRectangleSectionSubheaderLength() - { - return this.getLength(148); - } - public int getBoundaryRectangleTableLocation() - { - return this.getLocation(149); - } - public int getBoundaryRectangleTableLength() - { - return this.getLength(149); - } - public int getFrameFileIndexSectionSubheaderLocation() - { - return this.getLocation(150); - } - public int getFrameFileIndexSectionSubheaderLength() - { - return this.getLength(150); - } - public int getFrameFileIndexSubsectionLocation() - { - return this.getLocation(151); - } - public int getFrameFileIndexSubsectionLength() - { - return this.getLength(151); - } - public int getColorTableIndexSectionSubheaderLocation() - { - return this.getLocation(152); - } - public int getColorTableIndexSectionSubheaderLength() - { - return this.getLength(152); - } - public int getColorTableIndexRecordLocation() - { - return this.getLocation(153); - } - public int getColorTableIndexRecordLength() - { - return this.getLength(153); + private java.util.Hashtable table + = new java.util.Hashtable(); + + public int getHeaderComponentLocation() { + return this.getLocation(128); + } + + public int getHeaderComponentLength() { + return this.getLength(128); + } + + public int getLocationComponentLocation() { + return this.getLocation(129); + } + + public int getLocationComponentLength() { + return this.getLength(129); + } + + public int getCoverageSectionSubheaderLocation() { + return this.getLocation(130); + } + + public int getCoverageSectionSubheaderLength() { + return this.getLength(130); + } + + public int getCompressionSectionSubheaderLocation() { + return this.getLocation(131); + } + + public int getCompressionSectionSubheaderLength() { + return this.getLength(131); + } + + public int getCompressionLookupSubsectionLocation() { + return this.getLocation(132); + } + + public int getCompressionLookupSubsectionLength() { + return this.getLength(132); + } + + public int getCompressionParameterSubsectionLocation() { + return this.getLocation(133); + } + + public int getCompressionParameterSubsectionLength() { + return this.getLength(133); + } + + public int getColorGrayscaleSectionSubheaderLocation() { + return this.getLocation(134); + } + + public int getColorGrayscaleSectionSubheaderLength() { + return this.getLength(134); + } + + public int getColormapSubsectionLocation() { + return this.getLocation(135); + } + + public int getColormapSubsectionLength() { + return this.getLength(135); + } + + public int getImageDescriptionSubheaderLocation() { + return this.getLocation(136); + } + + public int getImageDescriptionSubheaderLength() { + return this.getLength(136); + } + + public int getImageDisplayParametersSubheaderLocation() { + return this.getLocation(137); + } + + public int getImageDisplayParametersSubheaderLength() { + return this.getLength(137); + } + + public int getMaskSubsectionLocation() { + return this.getLocation(138); + } + + public int getMaskSubsectionLength() { + return this.getLength(138); + } + + public int getColorConverterSubsectionLocation() { + return this.getLocation(139); + } + + public int getColorConverterSubsectionLength() { + return this.getLength(139); + } + + public int getSpatialDataSubsectionLocation() { + return this.getLocation(140); + } + + public int getSpatialDataSubsectionLength() { + return this.getLength(140); + } + + public int getAttributeSectionSubheaderLocation() { + return this.getLocation(141); + } + + public int getAttributeSectionSubheaderLength() { + return this.getLength(141); + } + + public int getAttributeSubsectionLocation() { + return this.getLocation(142); + } + + public int getAttributeSubsectionLength() { + return this.getLength(142); + } + + public int getExplicitArealCoverageTableLocation() { + return this.getLocation(143); + } + + public int getExplicitArealCoverageTableLength() { + return this.getLength(143); + } + + public int getRelatedImagesSectionSubheaderLocation() { + return this.getLocation(144); + } + + public int getRelatedImagesSectionSubheaderLength() { + return this.getLength(144); + } + + public int getRelatedImagesSubsectionLocation() { + return this.getLocation(145); + } + + public int getRelatedImagesSubsectionLength() { + return this.getLength(145); + } + + public int getReplaceUpdateSectionSubheaderLocation() { + return this.getLocation(146); + } + + public int getReplaceUpdateSectionSubheaderLength() { + return this.getLength(146); + } + + public int getReplaceUpdateTableLocation() { + return this.getLocation(147); + } + + public int getReplaceUpdateTableLength() { + return this.getLength(147); + } + + public int getBoundaryRectangleSectionSubheaderLocation() { + return this.getLocation(148); + } + + public int getBoundaryRectangleSectionSubheaderLength() { + return this.getLength(148); + } + + public int getBoundaryRectangleTableLocation() { + return this.getLocation(149); + } + + public int getBoundaryRectangleTableLength() { + return this.getLength(149); + } + + public int getFrameFileIndexSectionSubheaderLocation() { + return this.getLocation(150); + } + + public int getFrameFileIndexSectionSubheaderLength() { + return this.getLength(150); + } + + public int getFrameFileIndexSubsectionLocation() { + return this.getLocation(151); + } + + public int getFrameFileIndexSubsectionLength() { + return this.getLength(151); + } + + public int getColorTableIndexSectionSubheaderLocation() { + return this.getLocation(152); + } + + public int getColorTableIndexSectionSubheaderLength() { + return this.getLength(152); + } + + public int getColorTableIndexRecordLocation() { + return this.getLocation(153); + } + + public int getColorTableIndexRecordLength() { + return this.getLength(153); + } + // because of lack of "unsigned" in java, we store UINT as int, and UINT as long + public int locationSectionLength; + public long componentLocationTableOffset; + public int numOfComponentLocationRecords; + public int componentLocationRecordLength; + public long componentAggregateLength; + + public RPFLocationSection(java.nio.ByteBuffer buffer) { + this.locationSectionLength = NITFSUtil.getUShort(buffer); + this.componentLocationTableOffset = NITFSUtil.getUInt(buffer); + this.numOfComponentLocationRecords = NITFSUtil.getUShort(buffer); + this.componentLocationRecordLength = NITFSUtil.getUShort(buffer); + this.componentAggregateLength = NITFSUtil.getUInt(buffer); + + if (this.numOfComponentLocationRecords < 2) { + throw new NITFSRuntimeException("NITFSReader:InvalidNumberOfComponentLocationRecords"); } - // because of lack of "unsigned" in java, we store UINT as int, and UINT as long - public int locationSectionLength; - public long componentLocationTableOffset; - public int numOfComponentLocationRecords; - public int componentLocationRecordLength; - public long componentAggregateLength; - - public RPFLocationSection(java.nio.ByteBuffer buffer) - { - this.locationSectionLength = NITFSUtil.getUShort(buffer); - this.componentLocationTableOffset = NITFSUtil.getUInt(buffer); - this.numOfComponentLocationRecords = NITFSUtil.getUShort(buffer); - this.componentLocationRecordLength = NITFSUtil.getUShort(buffer); - this.componentAggregateLength = NITFSUtil.getUInt(buffer); - - if (this.numOfComponentLocationRecords < 2) - throw new NITFSRuntimeException("NITFSReader:InvalidNumberOfComponentLocationRecords"); - - for (int i = 0; i < this.numOfComponentLocationRecords; i++) - { - int id = NITFSUtil.getUShort(buffer); - table.put(id, new ComponentLocationRecord(id, - NITFSUtil.getUInt(buffer), // read uint:4 as "length" - NITFSUtil.getUInt(buffer) // read uint:4 as "location" - )); - } + + for (int i = 0; i < this.numOfComponentLocationRecords; i++) { + int id = NITFSUtil.getUShort(buffer); + table.put(id, new ComponentLocationRecord(id, + NITFSUtil.getUInt(buffer), // read uint:4 as "length" + NITFSUtil.getUInt(buffer) // read uint:4 as "location" + )); + } + } + + private int getLocation(int componentID) { + ComponentLocationRecord rec = this.getRecord(componentID); + return (int) ((null != rec) ? (0xFFFFFFFFL & rec.getLocation()) : 0); + } + + private int getLength(int componentID) { + ComponentLocationRecord rec = this.getRecord(componentID); + return (int) ((null != rec) ? (0xFFFFFFFFL & rec.getLength()) : 0); + } + + private ComponentLocationRecord getRecord(int componentID) { + if (table.containsKey(componentID)) { + return table.get(componentID); } + return null; + } + + public class ComponentLocationRecord { - private int getLocation(int componentID) - { - ComponentLocationRecord rec = this.getRecord(componentID); - return (int) ((null != rec) ? (0xFFFFFFFFL & rec.getLocation()) : 0); + private int id; + private long length; + private long location; + + public int getId() { + return id; } - private int getLength(int componentID) - { - ComponentLocationRecord rec = this.getRecord(componentID); - return (int) ((null != rec) ? (0xFFFFFFFFL & rec.getLength()) : 0); + + public long getLength() { + return length; } - private ComponentLocationRecord getRecord(int componentID) - { - if(table.containsKey(componentID)) - return table.get(componentID); - return null; + + public long getLocation() { + return location; } - public class ComponentLocationRecord - { - private int id; - private long length; - private long location; - - public int getId() - { - return id; - } - - public long getLength() - { - return length; - } - - public long getLocation() - { - return location; - } - - public ComponentLocationRecord(int id, long length, long location) - { - this.id = id; - this.length = length; - this.location = location; - } + public ComponentLocationRecord(int id, long length, long location) { + this.id = id; + this.length = length; + this.location = location; } + } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFNonpolarFrameStructure.java b/src/gov/nasa/worldwind/formats/rpf/RPFNonpolarFrameStructure.java index 95ab524c09..f13d88c06d 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFNonpolarFrameStructure.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFNonpolarFrameStructure.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: RPFNonpolarFrameStructure.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class RPFNonpolarFrameStructure extends RPFFrameStructure -{ +class RPFNonpolarFrameStructure extends RPFFrameStructure { + private final int northSouthPixelConstant; private final int eastWestPixelConstant; private final double polewardExtent; @@ -21,10 +21,9 @@ class RPFNonpolarFrameStructure extends RPFFrameStructure private final int longitudinalFrames; private RPFNonpolarFrameStructure( - int northSouthPixelConstant, int eastWestPixelConstant, - double polewardExtent, double equatorwardExtent, - int latitudinalFrames, int longitudinalFrames) - { + int northSouthPixelConstant, int eastWestPixelConstant, + double polewardExtent, double equatorwardExtent, + int latitudinalFrames, int longitudinalFrames) { this.northSouthPixelConstant = northSouthPixelConstant; this.eastWestPixelConstant = eastWestPixelConstant; this.polewardExtent = polewardExtent; @@ -33,98 +32,80 @@ private RPFNonpolarFrameStructure( this.longitudinalFrames = longitudinalFrames; } - public static RPFNonpolarFrameStructure computeStructure(char zoneCode, String rpfDataType, double resolution) - { - if (!RPFZone.isZoneCode(zoneCode)) - { + public static RPFNonpolarFrameStructure computeStructure(char zoneCode, String rpfDataType, double resolution) { + if (!RPFZone.isZoneCode(zoneCode)) { String message = Logging.getMessage("RPFZone.UnknownZoneCode", zoneCode); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) - { + if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) { String message = Logging.getMessage("RPFDataSeries.UnkownDataType", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (resolution < 0) - { + if (resolution < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } // Constant zone properties. - int ewPixelSpacingConst = eastWestPixelSpacingConstant(zoneCode); int nsPixelSpacingConst = northSouthPixelSpacingConstant(); int equatorwardNominalBound = equatorwardNominalBoundary(zoneCode); int polewardNominalBound = polewardNominalBoundary(zoneCode); // Scale/GSD specific zone properties. - int nsPixelConst, ewPixelConst; - if (RPFDataSeries.isCADRGDataType(rpfDataType)) - { + if (RPFDataSeries.isCADRGDataType(rpfDataType)) { nsPixelConst = northSouthPixelConstant_CADRG(nsPixelSpacingConst, resolution); ewPixelConst = eastWestPixelConstant_CADRG(ewPixelSpacingConst, resolution); - } - else if (RPFDataSeries.isCIBDataType(rpfDataType)) - { + } else if (RPFDataSeries.isCIBDataType(rpfDataType)) { nsPixelConst = northSouthPixelConstant_CIB(nsPixelSpacingConst, resolution); ewPixelConst = eastWestPixelConstant_CIB(ewPixelSpacingConst, resolution); - } - else - { + } else { nsPixelConst = -1; ewPixelConst = -1; } double polewardExtent = polewardExtent(polewardNominalBound, nsPixelConst, PIXEL_ROWS_PER_FRAME); double equatorwardExtent = equatorwardExtent(equatorwardNominalBound, nsPixelConst, PIXEL_ROWS_PER_FRAME); - + int latFrames = latitudinalFrames(polewardExtent, equatorwardExtent, nsPixelConst, PIXEL_ROWS_PER_FRAME); int lonFrames = longitudinalFrames(ewPixelConst, PIXEL_ROWS_PER_FRAME); - + return new RPFNonpolarFrameStructure( - nsPixelConst, ewPixelConst, - polewardExtent, equatorwardExtent, - latFrames, lonFrames); + nsPixelConst, ewPixelConst, + polewardExtent, equatorwardExtent, + latFrames, lonFrames); } - public final int getNorthSouthPixelConstant() - { + public final int getNorthSouthPixelConstant() { return this.northSouthPixelConstant; } - public final int getEastWestPixelConstant() - { + public final int getEastWestPixelConstant() { return this.eastWestPixelConstant; } - public final double getPolewardExtent() - { + public final double getPolewardExtent() { return this.polewardExtent; } - public final double getEquatorwardExtent() - { + public final double getEquatorwardExtent() { return this.equatorwardExtent; } - public final int getLatitudinalFrames() - { + public final int getLatitudinalFrames() { return this.latitudinalFrames; } - public final int getLongitudinalFrames() - { + public final int getLongitudinalFrames() { return this.longitudinalFrames; } /* [Section 60.1.1, MIL-C-89038] */ - private static int northSouthPixelConstant_CADRG(double northSouthPixelConstant, double scale) - { + private static int northSouthPixelConstant_CADRG(double northSouthPixelConstant, double scale) { double S = 1000000d / scale; double tmp = northSouthPixelConstant * S; tmp = 512d * (int) Math.ceil(tmp / 512d); @@ -134,8 +115,7 @@ private static int northSouthPixelConstant_CADRG(double northSouthPixelConstant, } /* [Section 60.1.2, MIL-C-89038] */ - private static int eastWestPixelConstant_CADRG(double eastWestPixelSpacingConstant, double scale) - { + private static int eastWestPixelConstant_CADRG(double eastWestPixelSpacingConstant, double scale) { double S = 1000000d / scale; double tmp = eastWestPixelSpacingConstant * S; tmp = 512d * (int) Math.ceil(tmp / 512d); @@ -145,8 +125,7 @@ private static int eastWestPixelConstant_CADRG(double eastWestPixelSpacingConsta /* [Section A.5.1.1, MIL-PRF-89041A] */ private static int northSouthPixelConstant_CIB(double northSouthPixelSpacingConstant, - double groundSampleDistance) - { + double groundSampleDistance) { double S = 100d / groundSampleDistance; double tmp = northSouthPixelSpacingConstant * S; tmp = 512d * (int) Math.ceil(tmp / 512d); @@ -156,54 +135,48 @@ private static int northSouthPixelConstant_CIB(double northSouthPixelSpacingCons /* [Section A.5.1.1, MIL-PRF-89041A] */ private static int eastWestPixelConstant_CIB(double eastWestPixelSpacingConstant, - double groundSampleDistance) - { + double groundSampleDistance) { double S = 100d / groundSampleDistance; double tmp = eastWestPixelSpacingConstant * S; return 512 * (int) Math.ceil(tmp / 512d); } /* [Section 60.1.5.b, MIL-C-89038] */ - /* [Section A.5.1.2.b, MIL-PRF-89041A] */ + /* [Section A.5.1.2.b, MIL-PRF-89041A] */ private static double polewardExtent(double polewardNominalBoundary, double northSouthPixelConstant, - double pixelRowsPerFrame) - { + double pixelRowsPerFrame) { double nsPixelsPerDegree = northSouthPixelConstant / 90d; return Math.signum(polewardNominalBoundary) - * clamp(Math.ceil(nsPixelsPerDegree * Math.abs(polewardNominalBoundary) / pixelRowsPerFrame) - * pixelRowsPerFrame / nsPixelsPerDegree, 0, 90); + * clamp(Math.ceil(nsPixelsPerDegree * Math.abs(polewardNominalBoundary) / pixelRowsPerFrame) + * pixelRowsPerFrame / nsPixelsPerDegree, 0, 90); } /* [Section 60.1.5.c, MIL-C-89038] */ - /* [Section A.5.1.2.c, MIL-PRF-89041A] */ + /* [Section A.5.1.2.c, MIL-PRF-89041A] */ private static double equatorwardExtent(double equatorwardNominalBoundary, double northSouthPixelConstant, - double pixelRowsPerFrame) - { + double pixelRowsPerFrame) { double nsPixelsPerDegree = northSouthPixelConstant / 90d; return Math.signum(equatorwardNominalBoundary) - * clamp((int) (nsPixelsPerDegree * Math.abs(equatorwardNominalBoundary) / pixelRowsPerFrame) - * pixelRowsPerFrame / nsPixelsPerDegree, 0, 90); + * clamp((int) (nsPixelsPerDegree * Math.abs(equatorwardNominalBoundary) / pixelRowsPerFrame) + * pixelRowsPerFrame / nsPixelsPerDegree, 0, 90); } /* [Section 60.1.6, MIL-PRF-89038] */ - /* [Section A.5.1.3, MIL-PRF-89041A] */ - private static int latitudinalFrames(double polewardExtentDegrees, double equatorwardExtentDegrees, - double northSouthPixelConstant, double pixelRowsPerFrame) - { + /* [Section A.5.1.3, MIL-PRF-89041A] */ + private static int latitudinalFrames(double polewardExtentDegrees, double equatorwardExtentDegrees, + double northSouthPixelConstant, double pixelRowsPerFrame) { double nsPixelsPerDegree = northSouthPixelConstant / 90d; double extent = Math.abs(polewardExtentDegrees - equatorwardExtentDegrees); return (int) Math.round(extent * nsPixelsPerDegree / pixelRowsPerFrame); } /* [Section 60.1.7, MIL-C-89038] */ - /* [Section A.5.1.4, MIL-PRF-89041A] */ - private static int longitudinalFrames(double eastWestPixelConstant, double pixelRowsPerFrame) - { + /* [Section A.5.1.4, MIL-PRF-89041A] */ + private static int longitudinalFrames(double eastWestPixelConstant, double pixelRowsPerFrame) { return (int) Math.ceil(eastWestPixelConstant / pixelRowsPerFrame); } - private static double clamp(double x, double min, double max) - { + private static double clamp(double x, double min, double max) { return (x < min) ? min : ((x > max) ? max : x); } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFNonpolarFrameTransform.java b/src/gov/nasa/worldwind/formats/rpf/RPFNonpolarFrameTransform.java index f71b25c7f3..c6ded345e2 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFNonpolarFrameTransform.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFNonpolarFrameTransform.java @@ -16,93 +16,77 @@ * @version $Id: RPFNonpolarFrameTransform.java 1171 2013-02-11 21:45:02Z dcollins $ */ @SuppressWarnings({"UnusedDeclaration"}) -class RPFNonpolarFrameTransform extends RPFFrameTransform -{ +class RPFNonpolarFrameTransform extends RPFFrameTransform { + private final char zoneCode; private final String rpfDataType; private final double resolution; private final RPFNonpolarFrameStructure frameStructure; private RPFNonpolarFrameTransform(char zoneCode, String rpfDataType, double resolution, - RPFNonpolarFrameStructure frameStructure) - { + RPFNonpolarFrameStructure frameStructure) { this.zoneCode = zoneCode; this.rpfDataType = rpfDataType; this.resolution = resolution; this.frameStructure = frameStructure; } - static RPFNonpolarFrameTransform createNonpolarFrameTransform(char zoneCode, String rpfDataType, double resolution) - { - if (!RPFZone.isZoneCode(zoneCode)) - { + static RPFNonpolarFrameTransform createNonpolarFrameTransform(char zoneCode, String rpfDataType, double resolution) { + if (!RPFZone.isZoneCode(zoneCode)) { String message = Logging.getMessage("RPFZone.UnknownZoneCode", zoneCode); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) - { + if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) { String message = Logging.getMessage("RPFDataSeries.UnkownDataType", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (resolution < 0) - { + if (resolution < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - RPFNonpolarFrameStructure frameStructure = RPFNonpolarFrameStructure.computeStructure( - zoneCode, rpfDataType, resolution); + zoneCode, rpfDataType, resolution); return new RPFNonpolarFrameTransform(zoneCode, rpfDataType, resolution, frameStructure); } - public final char getZoneCode() - { + public final char getZoneCode() { return this.zoneCode; } - public final String getRpfDataType() - { + public final String getRpfDataType() { return this.rpfDataType; } - public final double getResolution() - { + public final double getResolution() { return this.resolution; } - public final RPFFrameStructure getFrameStructure() - { + public final RPFFrameStructure getFrameStructure() { return this.frameStructure; } - public int getFrameNumber(int row, int column) - { + public int getFrameNumber(int row, int column) { return frameNumber(row, column, this.frameStructure.getLongitudinalFrames()); } - public int getMaximumFrameNumber() - { + public int getMaximumFrameNumber() { return maxFrameNumber(this.frameStructure.getLatitudinalFrames(), this.frameStructure.getLongitudinalFrames()); } - public int getRows() - { + public int getRows() { return this.frameStructure.getLatitudinalFrames(); } - public int getColumns() - { + public int getColumns() { return this.frameStructure.getLongitudinalFrames(); } - public LatLon computeFrameOrigin(int frameNumber) - { - if (frameNumber < 0 || frameNumber > getMaximumFrameNumber()) - { + public LatLon computeFrameOrigin(int frameNumber) { + if (frameNumber < 0 || frameNumber > getMaximumFrameNumber()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", frameNumber); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -111,22 +95,20 @@ public LatLon computeFrameOrigin(int frameNumber) int row = frameRow(frameNumber, this.frameStructure.getLongitudinalFrames()); int col = frameColumn(frameNumber, row, this.frameStructure.getLongitudinalFrames()); - double zoneLat = RPFZone.isZoneInUpperHemisphere(this.zoneCode) ? - this.frameStructure.getEquatorwardExtent() : this.frameStructure.getPolewardExtent(); + double zoneLat = RPFZone.isZoneInUpperHemisphere(this.zoneCode) + ? this.frameStructure.getEquatorwardExtent() : this.frameStructure.getPolewardExtent(); double n = frameOriginLatitude(row, this.frameStructure.getNorthSouthPixelConstant(), - this.frameStructure.getPixelRowsPerFrame(), zoneLat); + this.frameStructure.getPixelRowsPerFrame(), zoneLat); double w = frameOriginLongitude(col, this.frameStructure.getEastWestPixelConstant(), - this.frameStructure.getPixelRowsPerFrame()); + this.frameStructure.getPixelRowsPerFrame()); return LatLon.fromDegrees(n, w); } - public Sector computeFrameCoverage(int frameNumber) - { + public Sector computeFrameCoverage(int frameNumber) { int maxFrameNumber = maxFrameNumber(this.frameStructure.getLatitudinalFrames(), - this.frameStructure.getLongitudinalFrames()); - if (frameNumber < 0 || frameNumber > maxFrameNumber) - { + this.frameStructure.getLongitudinalFrames()); + if (frameNumber < 0 || frameNumber > maxFrameNumber) { String message = Logging.getMessage("generic.ArgumentOutOfRange", frameNumber); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -135,15 +117,15 @@ public Sector computeFrameCoverage(int frameNumber) int row = frameRow(frameNumber, this.frameStructure.getLongitudinalFrames()); int col = frameColumn(frameNumber, row, this.frameStructure.getLongitudinalFrames()); - double zoneLat = RPFZone.isZoneInUpperHemisphere(this.zoneCode) ? - this.frameStructure.getEquatorwardExtent() : this.frameStructure.getPolewardExtent(); + double zoneLat = RPFZone.isZoneInUpperHemisphere(this.zoneCode) + ? this.frameStructure.getEquatorwardExtent() : this.frameStructure.getPolewardExtent(); double n = frameOriginLatitude(row, this.frameStructure.getNorthSouthPixelConstant(), - this.frameStructure.getPixelRowsPerFrame(), zoneLat); + this.frameStructure.getPixelRowsPerFrame(), zoneLat); double s = n - frameDeltaLatitude(this.frameStructure.getNorthSouthPixelConstant(), this.frameStructure.getPixelRowsPerFrame()); double w = frameOriginLongitude(col, this.frameStructure.getEastWestPixelConstant(), - this.frameStructure.getPixelRowsPerFrame()); + this.frameStructure.getPixelRowsPerFrame()); double e = w + frameDeltaLongitude(this.frameStructure.getEastWestPixelConstant(), this.frameStructure.getPixelRowsPerFrame()); //e = normalizedDegreesLongitude(e); @@ -212,71 +194,60 @@ public RPFImage[] deproject(int frameNumber, BufferedImage frame) { //} /* [Section 30.2.1 MIL-C-89038 ] */ - private static double pixelLatitude_CADRG(double latFrameOrigin, int row, double northSouthPixelConstant) - { + private static double pixelLatitude_CADRG(double latFrameOrigin, int row, double northSouthPixelConstant) { return latFrameOrigin - (90d / northSouthPixelConstant) * row; } /* [Section 30.2.2 MIL-C-89038] */ - private static double pixelLongitude_CADRG(double lonFrameOrigin, int col, double eastWestPixelConstant) - { + private static double pixelLongitude_CADRG(double lonFrameOrigin, int col, double eastWestPixelConstant) { return lonFrameOrigin + (360d / eastWestPixelConstant) * col; } /* [Section A.3.2.1 MIL-PRF-89041A] */ - private static double pixelLatitude_CIB(double latFrameOrigin, int row, double northSouthPixelConstant) - { + private static double pixelLatitude_CIB(double latFrameOrigin, int row, double northSouthPixelConstant) { return latFrameOrigin - (90d / northSouthPixelConstant) * (row + 0.5); } /* [Section A.3.2.2 MIL-PRF-89041A] */ - private static double pixelLongitude_CIB(double lonFrameOrigin, int col, double eastWestPixelConstant) - { + private static double pixelLongitude_CIB(double lonFrameOrigin, int col, double eastWestPixelConstant) { return lonFrameOrigin + (360d / eastWestPixelConstant) * (col + 0.5); } /* [Section 30.3.1, MIL-C-89038] */ - /* [Section A.3.3.1, MIL-PRF-89041A] */ + /* [Section A.3.3.1, MIL-PRF-89041A] */ private static int frameRow(double latitude, double northSouthPixelConstant, double pixelRowsPerFrame, - double zoneOriginLatitude) - { + double zoneOriginLatitude) { return (int) (((latitude - zoneOriginLatitude) / 90d) * (northSouthPixelConstant / pixelRowsPerFrame)); } /* [Section 30.3.1, MIL-C-89038] */ - /* [Section A.3.3.1, MIL-PRF-89041A] */ + /* [Section A.3.3.1, MIL-PRF-89041A] */ private static double frameOriginLatitude(int row, double northSouthPixelConstant, double pixelRowsPerFrame, - double zoneOriginLatitude) - { + double zoneOriginLatitude) { return (90d / northSouthPixelConstant) * pixelRowsPerFrame * (row + 1) + zoneOriginLatitude; } /* [Section 30.3.2, MIL-C-89038] */ - /* [Section A.3.3.2, MIL-PRF-89041A] */ - private static int frameColumn(double longitude, double eastWestPixelConstant, double pixelRowsPerFrame) - { + /* [Section A.3.3.2, MIL-PRF-89041A] */ + private static int frameColumn(double longitude, double eastWestPixelConstant, double pixelRowsPerFrame) { return (int) (((longitude + 180d) / 360d) * (eastWestPixelConstant / pixelRowsPerFrame)); } /* [Section 30.3.2, MIL-C-89038] */ - /* [Section A.3.3.2, MIL-PRF-89041A] */ - private static double frameOriginLongitude(int column, double eastWestPixelConstant, double pixelRowsPerFrame) - { + /* [Section A.3.3.2, MIL-PRF-89041A] */ + private static double frameOriginLongitude(int column, double eastWestPixelConstant, double pixelRowsPerFrame) { return (360d / eastWestPixelConstant) * pixelRowsPerFrame * column - 180d; } - private static double frameDeltaLatitude(double northSouthPixelConstant, double pixelRowsPerFrame) - { + private static double frameDeltaLatitude(double northSouthPixelConstant, double pixelRowsPerFrame) { return (90d / northSouthPixelConstant) * pixelRowsPerFrame; } - private static double frameDeltaLongitude(double eastWestPixelConstant, double pixelRowsPerFrame) - { + private static double frameDeltaLongitude(double eastWestPixelConstant, double pixelRowsPerFrame) { return (360d / eastWestPixelConstant) * pixelRowsPerFrame; } - private static double normalizedDegreesLongitude(double degrees) - { + private static double normalizedDegreesLongitude(double degrees) { double lon = degrees % 360; return lon > 180 ? lon - 360 : lon < -180 ? 360 + lon : lon; } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFPolarFrameStructure.java b/src/gov/nasa/worldwind/formats/rpf/RPFPolarFrameStructure.java index 426ed4b7e1..7b7bd80551 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFPolarFrameStructure.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFPolarFrameStructure.java @@ -11,62 +11,52 @@ * @author dcollins * @version $Id: RPFPolarFrameStructure.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class RPFPolarFrameStructure extends RPFFrameStructure -{ +class RPFPolarFrameStructure extends RPFFrameStructure { + private final int polarPixelConstant; private final double polewardExtent; private final double equatorwardExtent; private final int polarFrames; private RPFPolarFrameStructure( - int polarPixelConstant, - double polewardExtent, double equatorwardExtent, - int polarFrames) - { + int polarPixelConstant, + double polewardExtent, double equatorwardExtent, + int polarFrames) { this.polarPixelConstant = polarPixelConstant; this.polewardExtent = polewardExtent; this.equatorwardExtent = equatorwardExtent; this.polarFrames = polarFrames; } - public static RPFPolarFrameStructure computeStructure(char zoneCode, String rpfDataType, double resolution) - { - if (!RPFZone.isZoneCode(zoneCode)) - { + public static RPFPolarFrameStructure computeStructure(char zoneCode, String rpfDataType, double resolution) { + if (!RPFZone.isZoneCode(zoneCode)) { String message = Logging.getMessage("RPFZone.UnknownZoneCode", zoneCode); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) - { + if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) { String message = Logging.getMessage("RPFDataSeries.UnkownDataType", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (resolution < 0) - { + if (resolution < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } int nsPixelSpacingConst = northSouthPixelSpacingConstant(); - + int polarPixelConst, polarFrames; - if (RPFDataSeries.isCADRGDataType(rpfDataType)) - { + if (RPFDataSeries.isCADRGDataType(rpfDataType)) { polarPixelConst = polarPixelConstant_CADRG(nsPixelSpacingConst, resolution); polarFrames = polarFrames_CADRG(polarPixelConst); - } - else if (RPFDataSeries.isCIBDataType(rpfDataType)) - { + } else if (RPFDataSeries.isCIBDataType(rpfDataType)) { int nsPixelConst = northSouthPixelConstant_CIB(nsPixelSpacingConst, resolution); polarPixelConst = polarPixelConstant_CIB(nsPixelConst); polarFrames = polarFrames_CIB(polarPixelConst); - } - else - { + } else { polarPixelConst = -1; polarFrames = -1; } @@ -74,38 +64,32 @@ else if (RPFDataSeries.isCIBDataType(rpfDataType)) double polewardExtent = polewardExtent(polewardNominalBoundary(zoneCode)); double equatorwardExtent = equatorwardExtent(equatorwardNominalBoundary(zoneCode)); - return new RPFPolarFrameStructure( - polarPixelConst, - polewardExtent, equatorwardExtent, - polarFrames); + polarPixelConst, + polewardExtent, equatorwardExtent, + polarFrames); } - public final int getPolarPixelConstant() - { + public final int getPolarPixelConstant() { return this.polarPixelConstant; } - public final double getPolewardExtent() - { + public final double getPolewardExtent() { return this.polewardExtent; } - public final double getEquatorwardExtent() - { + public final double getEquatorwardExtent() { return this.equatorwardExtent; } - public final int getPolarFrames() - { + public final int getPolarFrames() { return this.polarFrames; } // TODO: include supporting sources for CADRG in docs /* [Section A.5.1.1, MIL-PRF-89041A] */ - private static int northSouthPixelConstant_CIB(double northSouthPixelSpacingConstant, double groundSampleDistance) - { + private static int northSouthPixelConstant_CIB(double northSouthPixelSpacingConstant, double groundSampleDistance) { double S = 100d / groundSampleDistance; double tmp = northSouthPixelSpacingConstant * S; tmp = 512d * (int) Math.ceil(tmp / 512d); @@ -114,8 +98,7 @@ private static int northSouthPixelConstant_CIB(double northSouthPixelSpacingCons } /* [Section 60.2.1, MIL-C-89038] */ - private static int polarPixelConstant_CADRG(double northSouthPixelSpacingConstant, double scale) - { + private static int polarPixelConstant_CADRG(double northSouthPixelSpacingConstant, double scale) { double S = 1000000d / scale; double tmp = northSouthPixelSpacingConstant * S; tmp = 512d * (int) Math.ceil(tmp / 512d); @@ -126,47 +109,44 @@ private static int polarPixelConstant_CADRG(double northSouthPixelSpacingConstan } /* [Section A.5.2.1, MIL-PRF-89041A */ - private static int polarPixelConstant_CIB(double northSouthPixelConstant) - { + private static int polarPixelConstant_CIB(double northSouthPixelConstant) { double tmp = northSouthPixelConstant * 20d / 90d; tmp = 512d * (int) Math.round(tmp / 512d); return (int) (tmp * 90d / 20d); } /* [Section 60.2.3, MIL-C-89038] */ - private static int polarFrames_CADRG(double polarPixelConstant) - { + private static int polarFrames_CADRG(double polarPixelConstant) { double tmp = polarPixelConstant * 20d / 360d; tmp /= 256d; tmp /= 6d; tmp = Math.ceil(tmp); - if (((int) tmp) % 2 == 0) + if (((int) tmp) % 2 == 0) { tmp = tmp + 1; + } return (int) tmp; } /* [Section A.5.2.2, MIL-PRF-89041A] */ - private static int polarFrames_CIB(double polarPixelConstant) - { + private static int polarFrames_CIB(double polarPixelConstant) { double tmp = polarPixelConstant * 20d / 90d; tmp /= 256d; tmp += 4d; tmp /= 6d; tmp = Math.ceil(tmp); - if (((int) tmp) % 2 == 0) + if (((int) tmp) % 2 == 0) { tmp = tmp + 1; + } return (int) tmp; } /* [Section A.5.2.3, MIL-PRF-89041A] */ - private static double polewardExtent(double polewardNominalBoundary) - { + private static double polewardExtent(double polewardNominalBoundary) { return polewardNominalBoundary; } /* [Section A.5.2.3, MIL-PRF-89041A] */ - private static double equatorwardExtent(double equatorwardNominalBoundary) - { + private static double equatorwardExtent(double equatorwardNominalBoundary) { return equatorwardNominalBoundary; } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFPolarFrameTransform.java b/src/gov/nasa/worldwind/formats/rpf/RPFPolarFrameTransform.java index 96cc81fbd4..2e39aa3c23 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFPolarFrameTransform.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFPolarFrameTransform.java @@ -16,8 +16,8 @@ * @version $Id: RPFPolarFrameTransform.java 1171 2013-02-11 21:45:02Z dcollins $ */ @SuppressWarnings({"UnusedDeclaration"}) -class RPFPolarFrameTransform extends RPFFrameTransform -{ +class RPFPolarFrameTransform extends RPFFrameTransform { + private final char zoneCode; private final String rpfDataType; private final double resolution; @@ -27,94 +27,79 @@ class RPFPolarFrameTransform extends RPFFrameTransform private static final PixelTransformer southernPixels = new SouthPixelTransformer(); private RPFPolarFrameTransform(char zoneCode, String rpfDataType, double resolution, - RPFPolarFrameStructure frameStructure) - { + RPFPolarFrameStructure frameStructure) { this.zoneCode = zoneCode; this.rpfDataType = rpfDataType; this.resolution = resolution; this.frameStructure = frameStructure; } - static RPFPolarFrameTransform createPolarFrameTransform(char zoneCode, String rpfDataType, double resolution) - { - if (!RPFZone.isZoneCode(zoneCode)) - { + static RPFPolarFrameTransform createPolarFrameTransform(char zoneCode, String rpfDataType, double resolution) { + if (!RPFZone.isZoneCode(zoneCode)) { String message = Logging.getMessage("RPFZone.UnknownZoneCode", zoneCode); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) - { + if (rpfDataType == null || !RPFDataSeries.isRPFDataType(rpfDataType)) { String message = Logging.getMessage("RPFDataSeries.UnkownDataType", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (resolution < 0) - { + if (resolution < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", rpfDataType); Logging.logger().fine(message); throw new IllegalArgumentException(message); } RPFPolarFrameStructure frameStructure = RPFPolarFrameStructure.computeStructure( - zoneCode, rpfDataType, resolution); + zoneCode, rpfDataType, resolution); return new RPFPolarFrameTransform(zoneCode, rpfDataType, resolution, frameStructure); } - public final char getZoneCode() - { + public final char getZoneCode() { return this.zoneCode; } - public final String getRpfDataType() - { + public final String getRpfDataType() { return this.rpfDataType; } - public final double getResolution() - { + public final double getResolution() { return this.resolution; } - public final RPFFrameStructure getFrameStructure() - { + public final RPFFrameStructure getFrameStructure() { return this.frameStructure; } - public int getFrameNumber(int row, int column) - { + public int getFrameNumber(int row, int column) { return frameNumber(row, column, this.frameStructure.getPolarFrames()); } - public int getMaximumFrameNumber() - { + public int getMaximumFrameNumber() { return maxFrameNumber(this.frameStructure.getPolarFrames(), this.frameStructure.getPolarFrames()); } - public int getRows() - { + public int getRows() { return this.frameStructure.getPolarFrames(); } - public int getColumns() - { + public int getColumns() { return this.frameStructure.getPolarFrames(); } - public LatLon computeFrameOrigin(int frameNumber) - { + public LatLon computeFrameOrigin(int frameNumber) { - if (frameNumber < 0 || frameNumber > getMaximumFrameNumber()) - { + if (frameNumber < 0 || frameNumber > getMaximumFrameNumber()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", frameNumber); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int originX = pixelColumn(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int originY = pixelRow(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); double lat, lon; PixelTransformer pt = (this.zoneCode == '9') ? northernPixels : southernPixels; @@ -124,25 +109,23 @@ public LatLon computeFrameOrigin(int frameNumber) return LatLon.fromDegrees(lat, lon); } - public Sector computeFrameCoverage(int frameNumber) - { + public Sector computeFrameCoverage(int frameNumber) { int maxFrameNumber = getMaximumFrameNumber(); - if (frameNumber < 0 || frameNumber > maxFrameNumber) - { + if (frameNumber < 0 || frameNumber > maxFrameNumber) { String message = Logging.getMessage("generic.ArgumentOutOfRange", frameNumber); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int minX = pixelColumn(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int maxY = pixelRow(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int maxX = pixelColumn(this.frameStructure.getPixelRowsPerFrame(), frameNumber, - this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); + this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); int minY = pixelRow(this.frameStructure.getPixelRowsPerFrame(), frameNumber, - this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); + this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); // we'll need these below... int midX = (minX + maxX) / 2; @@ -200,10 +183,8 @@ public Sector computeFrameCoverage(int frameNumber) return Sector.fromDegrees(bounds.minLat, bounds.maxLat, bounds.minLon, bounds.maxLon); } - public RPFImage[] deproject(int frameNumber, BufferedImage frame) - { - if (frame == null) - { + public RPFImage[] deproject(int frameNumber, BufferedImage frame) { + if (frame == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -212,19 +193,17 @@ public RPFImage[] deproject(int frameNumber, BufferedImage frame) PixelTransformer pt = (this.zoneCode == '9') ? northernPixels : southernPixels; RPFImage[] images; - if (isDatelineSpanningFrame(frameNumber, pt)) - { - if (pt == northernPixels) + if (isDatelineSpanningFrame(frameNumber, pt)) { + if (pt == northernPixels) { images = deprojectNorthernDatelineFrames(frameNumber, frame, pt); - else + } else { images = deprojectSouthernDatelineFrames(frameNumber, frame, pt); - } - else - { + } + } else { // non-dateline spanning frames are more straightforward... Sector sector = computeFrameCoverage(frameNumber); BufferedImage destImage = new BufferedImage(frame.getWidth(), frame.getHeight(), - BufferedImage.TYPE_4BYTE_ABGR); + BufferedImage.TYPE_4BYTE_ABGR); resampleFrameFile(sector, frame, destImage, frameNumber, pt); images = new RPFImage[1]; images[0] = new RPFImage(sector, destImage); @@ -233,39 +212,34 @@ public RPFImage[] deproject(int frameNumber, BufferedImage frame) return images; } - private RPFImage[] deprojectNorthernDatelineFrames(int frameNumber, BufferedImage frame, PixelTransformer pt) - { + private RPFImage[] deprojectNorthernDatelineFrames(int frameNumber, BufferedImage frame, PixelTransformer pt) { // We have to split this frame at the dateline. RPFImage[] images = new RPFImage[2]; // Compute a tight bounds for western half... int minX = pixelColumn(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int maxX = pixelColumn(this.frameStructure.getPixelRowsPerFrame(), frameNumber, - this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); + this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); int minY = pixelRow(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int maxY = pixelRow(this.frameStructure.getPixelRowsPerFrame(), frameNumber, - this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); + this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); int midX = (minX + maxX) / 2; int midY = (minY + maxY) / 2; // Below we are using knowledge about the frames that make up the upper 1/2 part of the middle // column, and which borders and edges constitute the extrema... - MinMaxLatLon bndsWest = new MinMaxLatLon(); bndsWest.minLon = -180.; // center-most frame is different... - if (isCenterFrame(frameNumber)) - { + if (isCenterFrame(frameNumber)) { bndsWest.maxLon = 0.; // here max lat is at center of frame bndsWest.maxLat = pt.pixel2Latitude(midX, midY, this.frameStructure.getPolarPixelConstant()); // min lat is at an arbitrary corner... bndsWest.minLat = pt.pixel2Latitude(minX, minY, this.frameStructure.getPolarPixelConstant()); - } - else - { + } else { // min lat is one of the upper corners... bndsWest.minLat = pt.pixel2Latitude(minX, minY, this.frameStructure.getPolarPixelConstant()); // max lat is center of bottom edge... @@ -284,13 +258,10 @@ private RPFImage[] deprojectNorthernDatelineFrames(int frameNumber, BufferedImag bndsEast.minLat = bndsWest.minLat; bndsEast.maxLat = bndsWest.maxLat; // max lon is LR corner, unless we're center frame... - if (isCenterFrame(frameNumber)) - { + if (isCenterFrame(frameNumber)) { bndsEast.minLon = 0.; bndsEast.maxLon = 180.; - } - else - { + } else { bndsEast.minLon = pt.pixel2Longitude(maxX, maxY); bndsEast.maxLon = 180.; } @@ -302,39 +273,34 @@ private RPFImage[] deprojectNorthernDatelineFrames(int frameNumber, BufferedImag return images; } - private RPFImage[] deprojectSouthernDatelineFrames(int frameNumber, BufferedImage frame, PixelTransformer pt) - { + private RPFImage[] deprojectSouthernDatelineFrames(int frameNumber, BufferedImage frame, PixelTransformer pt) { // We have to split this frame at the dateline. RPFImage[] images = new RPFImage[2]; // Compute a tight bounds for western half... int minX = pixelColumn(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int maxX = pixelColumn(this.frameStructure.getPixelRowsPerFrame(), frameNumber, - this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); + this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); int minY = pixelRow(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int maxY = pixelRow(this.frameStructure.getPixelRowsPerFrame(), frameNumber, - this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); + this.frameStructure.getPixelRowsPerFrame(), this.frameStructure.getPolarFrames()); int midX = (minX + maxX) / 2; int midY = (minY + maxY) / 2; // Below we are using knowledge about the frames that make up the lower 1/2 part of the middle // column, and which borders and edges constitute the extrema... - MinMaxLatLon bndsWest = new MinMaxLatLon(); bndsWest.minLon = -180.; // center-most frame is different... - if (isCenterFrame(frameNumber)) - { + if (isCenterFrame(frameNumber)) { bndsWest.maxLon = 0.; // here max lat is at center of frame bndsWest.maxLat = pt.pixel2Latitude(midX, midY, this.frameStructure.getPolarPixelConstant()); // min lat is at an arbitrary corner... bndsWest.minLat = pt.pixel2Latitude(minX, minY, this.frameStructure.getPolarPixelConstant()); - } - else - { + } else { // min lat is one of the lower corners... bndsWest.minLat = pt.pixel2Latitude(minX, maxY, this.frameStructure.getPolarPixelConstant()); // max lat is center of top edge... @@ -353,13 +319,10 @@ private RPFImage[] deprojectSouthernDatelineFrames(int frameNumber, BufferedImag bndsEast.minLat = bndsWest.minLat; bndsEast.maxLat = bndsWest.maxLat; // max lon is LR corner, unless we're center frame... - if (isCenterFrame(frameNumber)) - { + if (isCenterFrame(frameNumber)) { bndsEast.minLon = 0.; bndsEast.maxLon = 180.; - } - else - { + } else { bndsEast.minLon = pt.pixel2Longitude(maxX, minY); bndsEast.maxLon = 180.; } @@ -372,12 +335,11 @@ private RPFImage[] deprojectSouthernDatelineFrames(int frameNumber, BufferedImag } private void resampleFrameFile(Sector sector, BufferedImage srcImage, BufferedImage destImage, int frameNumber, - PixelTransformer pt) - { + PixelTransformer pt) { int frameULX = pixelColumn(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int frameULY = pixelRow(0, frameNumber, this.frameStructure.getPixelRowsPerFrame(), - this.frameStructure.getPolarFrames()); + this.frameStructure.getPolarFrames()); int width = destImage.getWidth(); int height = destImage.getHeight(); @@ -392,11 +354,9 @@ private void resampleFrameFile(Sector sector, BufferedImage srcImage, BufferedIm int srcWidth = srcImage.getWidth(); int srcHeight = srcImage.getHeight(); - for (int y = 0; y < height; y++) - { + for (int y = 0; y < height; y++) { double lat = minLat + y * deltaLat; - for (int x = 0; x < width; x++) - { + for (int x = 0; x < width; x++) { double lon = minLon + x * deltaLon; int pixelX = pt.latLon2X(lat, lon, polarConstant); @@ -404,45 +364,44 @@ private void resampleFrameFile(Sector sector, BufferedImage srcImage, BufferedIm int i = pixelX - frameULX; int j = frameULY - pixelY; - if (i < 0 || i >= srcWidth || j < 0 || j >= srcHeight) + if (i < 0 || i >= srcWidth || j < 0 || j >= srcHeight) { continue; + } int color = srcImage.getRGB(i, j); // Remove black trim known to be present in these maps.... - if ((color & 0x00FFFFFF) == 0) + if ((color & 0x00FFFFFF) == 0) { color = 0; + } destImage.setRGB(x, height - 1 - y, color); } } } - private boolean isDatelineSpanningFrame(int frameNumber, PixelTransformer pt) - { + private boolean isDatelineSpanningFrame(int frameNumber, PixelTransformer pt) { // By definition, the center column of the polar frame grid... int row = frameNumber / getColumns(); int col = frameNumber % getColumns(); - if (pt == northernPixels) - return (row >= (getRows()/2) && col == (getColumns() / 2)); - else - return (row <= (getRows()/2) && col == (getColumns() / 2)); + if (pt == northernPixels) { + return (row >= (getRows() / 2) && col == (getColumns() / 2)); + } else { + return (row <= (getRows() / 2) && col == (getColumns() / 2)); + } } - private boolean isCenterFrame(int frameNumber) - { + private boolean isCenterFrame(int frameNumber) { int row = frameNumber / getRows(); int col = frameNumber % getColumns(); return (row == (getRows() / 2) && col == (getColumns() / 2)); } - private static int pixelRow(int rowInFrame, int frameNumber, int pixelsPerFrameRow, int numFrames) - { + private static int pixelRow(int rowInFrame, int frameNumber, int pixelsPerFrameRow, int numFrames) { int row = frameRow(frameNumber, numFrames); return ((row + 1) * pixelsPerFrameRow - rowInFrame) - (numFrames * pixelsPerFrameRow / 2); } - private static int pixelColumn(int colInFrame, int frameNumber, int pixelsPerFrameRow, int numFrames) - { + private static int pixelColumn(int colInFrame, int frameNumber, int pixelsPerFrameRow, int numFrames) { int row = frameRow(frameNumber, numFrames); int col = frameColumn(frameNumber, row, numFrames); return (col * pixelsPerFrameRow + colInFrame) - (numFrames * pixelsPerFrameRow / 2); @@ -452,8 +411,8 @@ private static int pixelColumn(int colInFrame, int frameNumber, int pixelsPerFra // The pixel<-->lat/lon calculations vary slight between north and south poles. We'll hide that // with this notion of a PixelTransformer and these classes below. // - private interface PixelTransformer - { + private interface PixelTransformer { + public double pixel2Latitude(int x, int y, double polarPixelConstant); public double pixel2Longitude(int x, int y); @@ -463,66 +422,62 @@ private interface PixelTransformer public int latLon2Y(double lat, double lon, double polarPixelConstant); } - private static class NorthPixelTransformer implements PixelTransformer - { + private static class NorthPixelTransformer implements PixelTransformer { + /* [Section 30.4.1, MIL-C-89038] */ - public double pixel2Latitude(int x, int y, double polarPixelConstant) - { + public double pixel2Latitude(int x, int y, double polarPixelConstant) { return 90. - (Math.sqrt(x * x + y * y) / (polarPixelConstant / 360.)); } /* [Section 30.4.1, MIL-C-89038] */ - public double pixel2Longitude(int x, int y) - { - if (x == 0 && y > 0) + public double pixel2Longitude(int x, int y) { + if (x == 0 && y > 0) { return 180.; + } - if (x == 0 && y <= 0) + if (x == 0 && y <= 0) { return 0.; + } double lambda = Math.acos(-y / Math.sqrt(x * x + y * y)) * 180 / Math.PI; return (x > 0) ? lambda : -lambda; } - public int latLon2X(double lat, double lon, double polarPixelConstant) - { + public int latLon2X(double lat, double lon, double polarPixelConstant) { return (int) (polarPixelConstant / 360. * (90. - lat) * Math.sin(lon * Math.PI / 180.)); } - public int latLon2Y(double lat, double lon, double polarPixelConstant) - { + public int latLon2Y(double lat, double lon, double polarPixelConstant) { return (int) (-polarPixelConstant / 360. * (90. - lat) * Math.cos(lon * Math.PI / 180.)); } } - private static class SouthPixelTransformer implements PixelTransformer - { + private static class SouthPixelTransformer implements PixelTransformer { + /* [Section 30.4.2, MIL-C-89038] */ - public double pixel2Latitude(int x, int y, double polarPixelConstant) - { + public double pixel2Latitude(int x, int y, double polarPixelConstant) { return -90. + (Math.sqrt(x * x + y * y) / (polarPixelConstant / 360.)); } /* [Section 30.4.2, MIL-C-89038] */ - public double pixel2Longitude(int x, int y) - { - if (x == 0 && y > 0) + public double pixel2Longitude(int x, int y) { + if (x == 0 && y > 0) { return 0.; + } - if (x == 0 && y <= 0) + if (x == 0 && y <= 0) { return 180.; + } double lambda = Math.acos(y / Math.sqrt(x * x + y * y)) * 180 / Math.PI; return (x > 0) ? lambda : -lambda; } - public int latLon2X(double lat, double lon, double polarPixelConstant) - { + public int latLon2X(double lat, double lon, double polarPixelConstant) { return (int) (polarPixelConstant / 360. * (90. + lat) * Math.sin(lon * Math.PI / 180.)); } - public int latLon2Y(double lat, double lon, double polarPixelConstant) - { + public int latLon2Y(double lat, double lon, double polarPixelConstant) { return (int) (polarPixelConstant / 360. * (90. + lat) * Math.cos(lon * Math.PI / 180.)); } } @@ -530,31 +485,34 @@ public int latLon2Y(double lat, double lon, double polarPixelConstant) // // A little helper class to eliminate some of the tedium of finding bounds of a polar sector. // - private class MinMaxLatLon - { + private class MinMaxLatLon { + double minLon, minLat, maxLon, maxLat; - public MinMaxLatLon() - { + public MinMaxLatLon() { minLon = minLat = Double.MAX_VALUE; maxLon = maxLat = -Double.MAX_VALUE; } - public void setMinMax(double lat, double lon) - { - if (lon < this.minLon) + public void setMinMax(double lat, double lon) { + if (lon < this.minLon) { this.minLon = lon; - if (lat < this.minLat) + } + if (lat < this.minLat) { this.minLat = lat; - if (lon > this.maxLon) + } + if (lon > this.maxLon) { this.maxLon = lon; - if (lat > this.maxLat) + } + if (lat > this.maxLat) { this.maxLat = lat; + } // We can't get -180 out of the pixel->longitude calculations as defined in the spec. // But if a polar sector contains 180, it also contains -180. - if (lon == 180) + if (lon == 180) { setMinMax(lat, -lon); + } } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFProducer.java b/src/gov/nasa/worldwind/formats/rpf/RPFProducer.java index d474344c5a..bc21cff4e6 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFProducer.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFProducer.java @@ -11,8 +11,7 @@ * @author dcollins * @version $Id: RPFProducer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public enum RPFProducer -{ +public enum RPFProducer { /* [Section 5.2.1, MIL-STD-2411-1] */ PRODUCER_1('1', "AFACC", "Air Force Air Combat Command"), PRODUCER_2('2', "AFESC", "Air Force Electronic Systems Center"), @@ -30,16 +29,14 @@ public enum RPFProducer PRODUCER_E('E', "Non-NIMA DCHUM (DCHMD)", "DoD producer of Digital CHUM file otherthan NIMA "), PRODUCER_F('F', "Non-US DCHUM (DCHMF)", "Non-US (foreign)producer of Digital CHUMfiles"), PRODUCER_G('G', "Non-DoD DCHUM (DCHMG)", "US producer of Digital CHUM files outsideDoD"), - PRODUCER_H('H', "IMG2RPF", "Non-specified, Imagery formatted to RPF"), -// PRODUCER_?('I'-'Z', "", "Reserved for future standardization"), + PRODUCER_H('H', "IMG2RPF", "Non-specified, Imagery formatted to RPF"), // PRODUCER_?('I'-'Z', "", "Reserved for future standardization"), ; public final Character id; public final String producerCode; public final String producer; - private RPFProducer(Character id, String producerCode, String producer) - { + private RPFProducer(Character id, String producerCode, String producer) { this.id = id; this.producer = producer; this.producerCode = producerCode; @@ -47,33 +44,28 @@ private RPFProducer(Character id, String producerCode, String producer) private static RPFProducer[] enumConstantAlphabet = null; - private static synchronized RPFProducer[] enumConstantAlphabet() - { - if (enumConstantAlphabet == null) - { + private static synchronized RPFProducer[] enumConstantAlphabet() { + if (enumConstantAlphabet == null) { RPFProducer[] universe = RPFProducer.class.getEnumConstants(); enumConstantAlphabet = new RPFProducer[36]; - for (RPFProducer producer : universe) - { + for (RPFProducer producer : universe) { enumConstantAlphabet[indexFor(producer.id)] = producer; } } return enumConstantAlphabet; } - private static int indexFor(Character id) - { - if (id >= '0' && id <= '9') + private static int indexFor(Character id) { + if (id >= '0' && id <= '9') { return id - '0'; - else if (id >= 'A' && id <= 'Z') + } else if (id >= 'A' && id <= 'Z') { return 10 + id - 'A'; + } return -1; } - public static boolean isProducerId(Character id) - { - if (id == null) - { + public static boolean isProducerId(Character id) { + if (id == null) { String message = Logging.getMessage("nullValue.CharacterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -83,10 +75,8 @@ public static boolean isProducerId(Character id) return (index >= 0) && (index < alphabet.length) && (alphabet[index] != null); } - public static RPFProducer producerFor(Character id) - { - if (id == null) - { + public static RPFProducer producerFor(Character id) { + if (id == null) { String message = Logging.getMessage("nullValue.CharacterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -94,8 +84,7 @@ public static RPFProducer producerFor(Character id) RPFProducer producer; RPFProducer[] alphabet = enumConstantAlphabet(); int index = indexFor(Character.toUpperCase(id)); - if (index < 0 || index >= alphabet.length || (producer = alphabet[index]) == null) - { + if (index < 0 || index >= alphabet.length || (producer = alphabet[index]) == null) { String message = Logging.getMessage("generic.EnumNotFound", id); Logging.logger().severe(message); throw new EnumConstantNotPresentException(RPFZone.class, message); diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFTOCFile.java b/src/gov/nasa/worldwind/formats/rpf/RPFTOCFile.java index 9723dbc62c..153620b65a 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFTOCFile.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFTOCFile.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; import gov.nasa.worldwind.formats.nitfs.NITFSRuntimeException; @@ -15,41 +14,39 @@ * @author Lado Garakanidze * @version $Id: RPFTOCFile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFTOCFile extends RPFFile -{ +public class RPFTOCFile extends RPFFile { + private RPFFileComponents rpfFileComponents; - public RPFHeaderSection getHeaderSection() - { + public RPFHeaderSection getHeaderSection() { return (null != this.rpfFileComponents) ? this.rpfFileComponents.getRPFHeaderSection() : null; } - public RPFFrameFileIndexSection getFrameFileIndexSection() - { + public RPFFrameFileIndexSection getFrameFileIndexSection() { return (null != this.rpfFileComponents) ? this.rpfFileComponents.getRPFFrameFileIndexSection() : null; } - public RPFFileComponents getRPFFileComponents() - { + public RPFFileComponents getRPFFileComponents() { return this.rpfFileComponents; } protected RPFTOCFile(java.io.File rpfFile) throws IOException, NITFSRuntimeException { super(rpfFile); - RPFUserDefinedHeaderSegment segment = - (RPFUserDefinedHeaderSegment)this.getNITFSSegment( NITFSSegmentType.USER_DEFINED_HEADER_SEGMENT); + RPFUserDefinedHeaderSegment segment + = (RPFUserDefinedHeaderSegment) this.getNITFSSegment(NITFSSegmentType.USER_DEFINED_HEADER_SEGMENT); - if(null == segment) + if (null == segment) { throw new NITFSRuntimeException("NITFSReader.UserDefinedHeaderSegmentWasNotFound"); + } this.rpfFileComponents = segment.getRPFFileComponents(); - if(null == this.rpfFileComponents) + if (null == this.rpfFileComponents) { throw new NITFSRuntimeException("NITFSReader.RPFFileComponents.Were.Not.Found.In.UserDefinedHeaderSegment"); + } } - public static RPFTOCFile load(java.io.File tocFile) throws java.io.IOException - { + public static RPFTOCFile load(java.io.File tocFile) throws java.io.IOException { return new RPFTOCFile(tocFile); } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFUserDefinedHeaderSegment.java b/src/gov/nasa/worldwind/formats/rpf/RPFUserDefinedHeaderSegment.java index 9542db67ae..6e6009dcbf 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFUserDefinedHeaderSegment.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFUserDefinedHeaderSegment.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.rpf; import gov.nasa.worldwind.formats.nitfs.*; @@ -12,25 +11,22 @@ * @author Lado Garakanidze * @version $Id: RPFUserDefinedHeaderSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFUserDefinedHeaderSegment extends NITFSUserDefinedHeaderSegment -{ +public class RPFUserDefinedHeaderSegment extends NITFSUserDefinedHeaderSegment { + private RPFFileComponents components; - public RPFUserDefinedHeaderSegment(java.nio.ByteBuffer buffer) - { + public RPFUserDefinedHeaderSegment(java.nio.ByteBuffer buffer) { super(buffer); - if( RPFHeaderSection.DATA_TAG.equals(this.dataTag) ) - { + if (RPFHeaderSection.DATA_TAG.equals(this.dataTag)) { this.components = new RPFFileComponents(buffer); - } - else + } else { throw new NITFSRuntimeException("NITFSReader.RPFHeaderNotFoundInUserDefinedSegment", this.dataTag); + } this.restoreBufferPosition(); } - public RPFFileComponents getRPFFileComponents() - { + public RPFFileComponents getRPFFileComponents() { return this.components; } } diff --git a/src/gov/nasa/worldwind/formats/rpf/RPFZone.java b/src/gov/nasa/worldwind/formats/rpf/RPFZone.java index 4083403c19..b7a7ae484f 100644 --- a/src/gov/nasa/worldwind/formats/rpf/RPFZone.java +++ b/src/gov/nasa/worldwind/formats/rpf/RPFZone.java @@ -11,8 +11,7 @@ * @author dcollins * @version $Id: RPFZone.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public enum RPFZone -{ +public enum RPFZone { /* [Table III, Section 70, MIL-A-89007] */ ZONE_1('1'), ZONE_2('2'), @@ -31,73 +30,59 @@ public enum RPFZone ZONE_F('F'), ZONE_G('G'), ZONE_H('H'), - ZONE_J('J'), - ; + ZONE_J('J'),; public final char zoneCode; - private RPFZone(char zoneCode) - { + private RPFZone(char zoneCode) { this.zoneCode = zoneCode; } - public static boolean isZoneCode(char c) - { + public static boolean isZoneCode(char c) { char upperChar = Character.toUpperCase(c); return ((upperChar >= '1' && upperChar <= '9') || (upperChar >= 'A' && upperChar <= 'H') || (upperChar == 'J')); } - static int indexFor(char zoneCode) - { + static int indexFor(char zoneCode) { final int NUM_START_INDEX = 0; final int ALPHA_START_INDEX = 9; int index = -1; char upperChar = Character.toUpperCase(zoneCode); - if (upperChar >= '1' && upperChar <= '9') - { + if (upperChar >= '1' && upperChar <= '9') { index = NUM_START_INDEX + upperChar - '1'; - } - else if (upperChar >= 'A' && upperChar <= 'H') - { + } else if (upperChar >= 'A' && upperChar <= 'H') { index = ALPHA_START_INDEX + upperChar - 'A'; - } - else if (upperChar == 'J') - { + } else if (upperChar == 'J') { index = ALPHA_START_INDEX + upperChar - 'A' - 1; } return index; } - static boolean isZoneInUpperHemisphere(char zoneCode) - { + static boolean isZoneInUpperHemisphere(char zoneCode) { char upperChar = Character.toUpperCase(zoneCode); return (upperChar >= '1' && upperChar <= '9'); } - static boolean isPolarZone(char zoneCode) - { + static boolean isPolarZone(char zoneCode) { char upperChar = Character.toUpperCase(zoneCode); return (upperChar == '9') || (upperChar == 'J'); } - public static RPFZone zoneFor(char zoneCode) - { + public static RPFZone zoneFor(char zoneCode) { RPFZone[] alphabet = enumConstantAlphabet(); int index = indexFor(zoneCode); - if (index < 0 || index >= alphabet.length) - { + if (index < 0 || index >= alphabet.length) { String message = Logging.getMessage("generic.EnumNotFound", zoneCode); Logging.logger().fine(message); throw new EnumConstantNotPresentException(RPFZone.class, message); } RPFZone zone = alphabet[index]; - if (zone == null) - { + if (zone == null) { String message = Logging.getMessage("generic.EnumNotFound", zoneCode); Logging.logger().fine(message); throw new EnumConstantNotPresentException(RPFZone.class, message); @@ -108,14 +93,11 @@ public static RPFZone zoneFor(char zoneCode) private static RPFZone[] enumConstantAlphabet = null; - private static synchronized RPFZone[] enumConstantAlphabet() - { - if (enumConstantAlphabet == null) - { + private static synchronized RPFZone[] enumConstantAlphabet() { + if (enumConstantAlphabet == null) { RPFZone[] universe = RPFZone.class.getEnumConstants(); enumConstantAlphabet = new RPFZone[universe.length]; - for (RPFZone zone : universe) - { + for (RPFZone zone : universe) { enumConstantAlphabet[indexFor(zone.zoneCode)] = zone; } } diff --git a/src/gov/nasa/worldwind/formats/shapefile/DBaseField.java b/src/gov/nasa/worldwind/formats/shapefile/DBaseField.java index c95fa5498e..05c73c6957 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/DBaseField.java +++ b/src/gov/nasa/worldwind/formats/shapefile/DBaseField.java @@ -14,8 +14,8 @@ * @author Patrick Murris * @version $Id: DBaseField.java 1867 2014-03-14 18:52:11Z dcollins $ */ -public class DBaseField -{ +public class DBaseField { + public static final String TYPE_CHAR = "DBase.FieldTypeChar"; public static final String TYPE_NUMBER = "DBase.FieldTypeNumber"; public static final String TYPE_DATE = "DBase.FieldTypeDate"; @@ -28,17 +28,14 @@ public class DBaseField private int length; private int decimals; - public DBaseField(DBaseFile dbaseFile, ByteBuffer buffer) - { - if (dbaseFile == null) - { + public DBaseField(DBaseFile dbaseFile, ByteBuffer buffer) { + if (dbaseFile == null) { String message = Logging.getMessage("nullValue.DBaseFileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -47,28 +44,23 @@ public DBaseField(DBaseFile dbaseFile, ByteBuffer buffer) this.readFromBuffer(dbaseFile, buffer); } - public String getName() - { + public String getName() { return this.name; } - public String getType() - { + public String getType() { return this.type; } - public int getLength() - { + public int getLength() { return this.length; } - public int getDecimals() - { + public int getDecimals() { return this.decimals; } - protected void readFromBuffer(DBaseFile dbaseFile, ByteBuffer buffer) - { + protected void readFromBuffer(DBaseFile dbaseFile, ByteBuffer buffer) { buffer.order(ByteOrder.LITTLE_ENDIAN); int pos = buffer.position(); @@ -79,8 +71,7 @@ protected void readFromBuffer(DBaseFile dbaseFile, ByteBuffer buffer) this.typeCode = (char) buffer.get(); this.type = getFieldType(this.typeCode); - if (this.type == null) - { + if (this.type == null) { String message = Logging.getMessage("SHP.UnsupportedDBaseFieldType", this.typeCode); Logging.logger().log(java.util.logging.Level.SEVERE, message); throw new WWRuntimeException(message); @@ -95,10 +86,8 @@ protected void readFromBuffer(DBaseFile dbaseFile, ByteBuffer buffer) buffer.position(pos + DBaseFile.FIELD_DESCRIPTOR_LENGTH); // move to next field } - public static String getFieldType(char type) - { - switch (type) - { + public static String getFieldType(char type) { + switch (type) { case 'C': return TYPE_CHAR; case 'D': @@ -115,8 +104,7 @@ public static String getFieldType(char type) } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.name); sb.append("(").append(this.typeCode).append(")"); diff --git a/src/gov/nasa/worldwind/formats/shapefile/DBaseFile.java b/src/gov/nasa/worldwind/formats/shapefile/DBaseFile.java index c2517d1344..3e9e14fb4b 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/DBaseFile.java +++ b/src/gov/nasa/worldwind/formats/shapefile/DBaseFile.java @@ -19,19 +19,19 @@ * @author Patrick Murris * @version $Id: DBaseFile.java 2257 2014-08-22 18:02:19Z tgaskins $ */ -public class DBaseFile extends AVListImpl -{ +public class DBaseFile extends AVListImpl { + protected static final int FIXED_HEADER_LENGTH = 32; protected static final int FIELD_DESCRIPTOR_LENGTH = 32; - protected static String[] DBASE_CONTENT_TYPES = - { - "application/dbase", - "application/dbf", - "application/octet-stream" - }; - - protected static class Header - { + protected static String[] DBASE_CONTENT_TYPES + = { + "application/dbase", + "application/dbf", + "application/octet-stream" + }; + + protected static class Header { + public int fileCode; public Date lastModificationDate; public int numberOfRecords; @@ -48,134 +48,108 @@ protected static class Header protected int numRecordsRead; protected ByteBuffer recordBuffer; - public DBaseFile(Object source) - { - if (source == null || WWUtil.isEmpty(source)) - { + public DBaseFile(Object source) { + if (source == null || WWUtil.isEmpty(source)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { this.setValue(AVKey.DISPLAY_NAME, source.toString()); - if (source instanceof File) + if (source instanceof File) { this.initializeFromFile((File) source); - else if (source instanceof URL) + } else if (source instanceof URL) { this.initializeFromURL((URL) source); - else if (source instanceof InputStream) + } else if (source instanceof InputStream) { this.initializeFromStream((InputStream) source); - else if (source instanceof String) + } else if (source instanceof String) { this.initializeFromPath((String) source); - else - { + } else { String message = Logging.getMessage("generic.UnrecognizedSourceType", source); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("SHP.ExceptionAttemptingToReadDBase", - this.getStringValue(AVKey.DISPLAY_NAME)); + this.getStringValue(AVKey.DISPLAY_NAME)); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - public DBaseFile(InputStream is) - { - if (is == null) - { + public DBaseFile(InputStream is) { + if (is == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { this.setValue(AVKey.DISPLAY_NAME, is.toString()); this.initializeFromStream(is); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("SHP.ExceptionAttemptingToReadDBase", - this.getStringValue(AVKey.DISPLAY_NAME)); + this.getStringValue(AVKey.DISPLAY_NAME)); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - public Date getLastModificationDate() - { + public Date getLastModificationDate() { return this.header.lastModificationDate; } - public int getNumberOfRecords() - { + public int getNumberOfRecords() { return this.header.numberOfRecords; } - public int getHeaderLength() - { + public int getHeaderLength() { return this.header.headerLength; } - public int getRecordLength() - { + public int getRecordLength() { return this.header.recordLength; } - public int getNumberOfFields() - { + public int getNumberOfFields() { return (this.header.headerLength - 1 - FIXED_HEADER_LENGTH) / FIELD_DESCRIPTOR_LENGTH; } - public DBaseField[] getFields() - { + public DBaseField[] getFields() { return this.fields; } - public boolean hasNext() - { + public boolean hasNext() { return this.open && this.numRecordsRead < this.header.numberOfRecords; } - public DBaseRecord nextRecord() - { - if (!this.open) - { + public DBaseRecord nextRecord() { + if (!this.open) { String message = Logging.getMessage("SHP.DBaseFileClosed", this.getStringValue(AVKey.DISPLAY_NAME)); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.getNumberOfRecords() <= 0 || this.numRecordsRead >= this.getNumberOfRecords()) - { + if (this.getNumberOfRecords() <= 0 || this.numRecordsRead >= this.getNumberOfRecords()) { String message = Logging.getMessage("SHP.NoRecords", this.getStringValue(AVKey.DISPLAY_NAME)); Logging.logger().severe(message); throw new IllegalStateException(message); } - try - { + try { return this.readNextRecord(); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("SHP.ExceptionAttemptingToReadDBaseRecord", - this.getStringValue(AVKey.DISPLAY_NAME)); + this.getStringValue(AVKey.DISPLAY_NAME)); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - public void close() - { - if (this.channel != null) - { + public void close() { + if (this.channel != null) { WWIO.closeStream(this.channel, null); this.channel = null; } @@ -187,11 +161,8 @@ public void close() //**************************************************************// //******************** Initialization ************************// //**************************************************************// - - protected void initializeFromFile(File file) throws IOException - { - if (!file.exists()) - { + protected void initializeFromFile(File file) throws IOException { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file.getPath()); Logging.logger().severe(message); throw new FileNotFoundException(message); @@ -202,15 +173,13 @@ protected void initializeFromFile(File file) throws IOException this.initialize(); } - protected void initializeFromURL(URL url) throws IOException - { + protected void initializeFromURL(URL url) throws IOException { // Opening the Shapefile URL as a URL connection. Throw an IOException if the URL connection cannot be opened, // or if it's an invalid Shapefile connection. URLConnection connection = url.openConnection(); String message = this.validateURLConnection(connection, DBASE_CONTENT_TYPES); - if (message != null) - { + if (message != null) { throw new IOException(message); } @@ -218,24 +187,20 @@ protected void initializeFromURL(URL url) throws IOException this.initialize(); } - protected void initializeFromStream(InputStream stream) throws IOException - { + protected void initializeFromStream(InputStream stream) throws IOException { this.channel = Channels.newChannel(WWIO.getBufferedInputStream(stream)); this.initialize(); } - protected void initializeFromPath(String path) throws IOException - { + protected void initializeFromPath(String path) throws IOException { File file = new File(path); - if (file.exists()) - { + if (file.exists()) { this.initializeFromFile(file); return; } URL url = WWIO.makeURL(path); - if (url != null) - { + if (url != null) { this.initializeFromURL(url); return; } @@ -245,37 +210,32 @@ protected void initializeFromPath(String path) throws IOException throw new IllegalArgumentException(message); } - protected void initialize() throws IOException - { + protected void initialize() throws IOException { this.header = this.readHeader(); this.fields = this.readFields(); this.open = true; } - protected String validateURLConnection(URLConnection connection, String[] acceptedContentTypes) - { - try - { - if (connection instanceof HttpURLConnection && - ((HttpURLConnection) connection).getResponseCode() != HttpURLConnection.HTTP_OK) - { + protected String validateURLConnection(URLConnection connection, String[] acceptedContentTypes) { + try { + if (connection instanceof HttpURLConnection + && ((HttpURLConnection) connection).getResponseCode() != HttpURLConnection.HTTP_OK) { return Logging.getMessage("HTTP.ResponseCode", ((HttpURLConnection) connection).getResponseCode(), - connection.getURL()); + connection.getURL()); } - } - catch (Exception e) - { + } catch (Exception e) { return Logging.getMessage("URLRetriever.ErrorOpeningConnection", connection.getURL()); } String contentType = connection.getContentType(); - if (WWUtil.isEmpty(contentType)) + if (WWUtil.isEmpty(contentType)) { return null; + } - for (String type : acceptedContentTypes) - { - if (contentType.trim().toLowerCase().startsWith(type)) + for (String type : acceptedContentTypes) { + if (contentType.trim().toLowerCase().startsWith(type)) { return null; + } } // Return an exception if the content type does not match the expected type. @@ -285,7 +245,6 @@ protected String validateURLConnection(URLConnection connection, String[] accept //**************************************************************// //******************** Header ********************************// //**************************************************************// - /** * Reads the {@link Header} from this DBaseFile. This file is assumed to have a header. * @@ -293,14 +252,12 @@ protected String validateURLConnection(URLConnection connection, String[] accept * * @throws IOException if the header cannot be read for any reason. */ - protected Header readHeader() throws IOException - { + protected Header readHeader() throws IOException { // Read header fixed portion. ByteBuffer buffer = ByteBuffer.allocate(FIXED_HEADER_LENGTH); WWIO.readChannelToBuffer(this.channel, buffer); - if (buffer.remaining() < FIXED_HEADER_LENGTH) - { + if (buffer.remaining() < FIXED_HEADER_LENGTH) { // Let the caller catch and log the message. throw new WWRuntimeException(Logging.getMessage("generic.InvalidFileLength", buffer.remaining())); } @@ -318,16 +275,14 @@ protected Header readHeader() throws IOException * * @return a {@link Header} instances. */ - protected Header readHeaderFromBuffer(ByteBuffer buffer) - { + protected Header readHeaderFromBuffer(ByteBuffer buffer) { int pos = buffer.position(); buffer.order(ByteOrder.LITTLE_ENDIAN); // Read file code - first byte int fileCode = buffer.get(); - if (fileCode > 5) - { + if (fileCode > 5) { // Let the caller catch and log the message. throw new WWUnrecognizedException(Logging.getMessage("SHP.UnrecognizedDBaseFile", fileCode)); } @@ -364,7 +319,6 @@ protected Header readHeaderFromBuffer(ByteBuffer buffer) //**************************************************************// //******************** Fields ********************************// //**************************************************************// - /** * Reads the {@link DBaseField} descriptions from this DBaseFile. This file is assumed to have one or more fields * available. @@ -373,8 +327,7 @@ protected Header readHeaderFromBuffer(ByteBuffer buffer) * * @throws IOException if the fields cannot be read for any reason. */ - protected DBaseField[] readFields() throws IOException - { + protected DBaseField[] readFields() throws IOException { int fieldsLength = this.header.headerLength - FIXED_HEADER_LENGTH; ByteBuffer buffer = ByteBuffer.allocate(fieldsLength); WWIO.readChannelToBuffer(this.channel, buffer); @@ -389,19 +342,17 @@ protected DBaseField[] readFields() throws IOException * The buffer current position is assumed to be set at the start of the sequence and will be set to the end of the * sequence after this method has completed. * - * @param buffer the DBaseField sequence {@link java.nio.ByteBuffer} to read from. + * @param buffer the DBaseField sequence {@link java.nio.ByteBuffer} to read from. * @param numFields the number of DBaseFields to read. * * @return an array of {@link DBaseField} instances. */ - protected DBaseField[] readFieldsFromBuffer(ByteBuffer buffer, int numFields) - { + protected DBaseField[] readFieldsFromBuffer(ByteBuffer buffer, int numFields) { int pos = buffer.position(); DBaseField[] fields = new DBaseField[numFields]; - for (int i = 0; i < numFields; i++) - { + for (int i = 0; i < numFields; i++) { fields[i] = new DBaseField(this, buffer); } @@ -414,7 +365,6 @@ protected DBaseField[] readFieldsFromBuffer(ByteBuffer buffer, int numFields) //**************************************************************// //******************** Records *******************************// //**************************************************************// - /** * Reads the next {@link DBaseRecord} instance from this DBaseFile. This file is assumed to have one or more * remaining records available. @@ -423,11 +373,11 @@ protected DBaseField[] readFieldsFromBuffer(ByteBuffer buffer, int numFields) * * @throws IOException if the record cannot be read for any reason. */ - protected DBaseRecord readNextRecord() throws IOException - { + protected DBaseRecord readNextRecord() throws IOException { // Allocate a buffer to hold the record content. - if (this.recordBuffer == null) + if (this.recordBuffer == null) { this.recordBuffer = ByteBuffer.allocate(this.getRecordLength()); + } // Read the record content. this.recordBuffer.limit(this.getRecordLength()); @@ -444,68 +394,61 @@ protected DBaseRecord readNextRecord() throws IOException * The buffer current position is assumed to be set at the start of the record and will be set to the start of the * next record after this method has completed. * - * @param buffer the DBase record {@link java.nio.ByteBuffer} to read from. + * @param buffer the DBase record {@link java.nio.ByteBuffer} to read from. * @param recordNumber the record's sequence number. * * @return a {@link DBaseRecord} instance. */ - protected DBaseRecord readRecordFromBuffer(ByteBuffer buffer, int recordNumber) - { + protected DBaseRecord readRecordFromBuffer(ByteBuffer buffer, int recordNumber) { return new DBaseRecord(this, buffer, recordNumber); } //**************************************************************// //******************** String Parsing ************************// //**************************************************************// - - protected int readZeroTerminatedString(ByteBuffer buffer, byte[] bytes, int maxLength) - { - if (maxLength <= 0) + protected int readZeroTerminatedString(ByteBuffer buffer, byte[] bytes, int maxLength) { + if (maxLength <= 0) { return 0; + } buffer.get(bytes, 0, maxLength); int length; - for (length = 0; length < maxLength && bytes[length] != 0; length++) - { + for (length = 0; length < maxLength && bytes[length] != 0; length++) { } return length; } - protected String decodeString(byte[] bytes, int length) - { - if (length <= 0) + protected String decodeString(byte[] bytes, int length) { + if (length <= 0) { return null; + } - try - { + try { return new String(bytes, 0, length, "UTF-8"); - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { return new String(bytes, 0, length); } } - protected boolean isStringEmpty(byte[] bytes, int length) - { + protected boolean isStringEmpty(byte[] bytes, int length) { return length <= 0 - || isArrayFilled(bytes, length, (byte) 0x20) // Space character. - || isArrayFilled(bytes, length, (byte) 0x2A); // Asterisk character. + || isArrayFilled(bytes, length, (byte) 0x20) // Space character. + || isArrayFilled(bytes, length, (byte) 0x2A); // Asterisk character. } - protected static boolean isArrayFilled(byte[] bytes, int length, byte fillValue) - { - if (length <= 0) + protected static boolean isArrayFilled(byte[] bytes, int length, byte fillValue) { + if (length <= 0) { return false; + } - for (int i = 0; i < length; i++) - { - if (bytes[i] != fillValue) + for (int i = 0; i < length; i++) { + if (bytes[i] != fillValue) { return false; + } } return true; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/shapefile/DBaseRecord.java b/src/gov/nasa/worldwind/formats/shapefile/DBaseRecord.java index afcf0b7da3..bd467974b6 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/DBaseRecord.java +++ b/src/gov/nasa/worldwind/formats/shapefile/DBaseRecord.java @@ -16,23 +16,20 @@ * @author Patrick Murris * @version $Id: DBaseRecord.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DBaseRecord extends AVListImpl -{ +public class DBaseRecord extends AVListImpl { + private boolean deleted = false; private int recordNumber; private static final DateFormat dateformat = new SimpleDateFormat("yyyyMMdd"); - public DBaseRecord(DBaseFile dbaseFile, ByteBuffer buffer, int recordNumber) - { - if (dbaseFile == null) - { + public DBaseRecord(DBaseFile dbaseFile, ByteBuffer buffer, int recordNumber) { + if (dbaseFile == null) { String message = Logging.getMessage("nullValue.DBaseFileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -41,19 +38,16 @@ public DBaseRecord(DBaseFile dbaseFile, ByteBuffer buffer, int recordNumber) this.readFromBuffer(dbaseFile, buffer, recordNumber); } - public boolean isDeleted() - { + public boolean isDeleted() { return this.deleted; } - public int getRecordNumber() - { + public int getRecordNumber() { return this.recordNumber; } @SuppressWarnings({"StringEquality"}) - protected void readFromBuffer(DBaseFile dbaseFile, ByteBuffer buffer, int recordNumber) - { + protected void readFromBuffer(DBaseFile dbaseFile, ByteBuffer buffer, int recordNumber) { buffer.order(ByteOrder.LITTLE_ENDIAN); // Set parent DBaseFile and record number. @@ -65,57 +59,46 @@ protected void readFromBuffer(DBaseFile dbaseFile, ByteBuffer buffer, int record // Create a buffer to hold the field values. int maxFieldLength = 0; - for (DBaseField field : dbaseFile.getFields()) - { - if (maxFieldLength < field.getLength()) + for (DBaseField field : dbaseFile.getFields()) { + if (maxFieldLength < field.getLength()) { maxFieldLength = field.getLength(); + } } // Read field values. DBaseField[] fields = dbaseFile.getFields(); byte[] bytes = new byte[maxFieldLength]; - for (DBaseField field : fields) - { + for (DBaseField field : fields) { int numRead = dbaseFile.readZeroTerminatedString(buffer, bytes, field.getLength()); // Add a null entry for this field if the field's value is null or the empty string. This enables // applications to treat the DBaseRecord a standard AVList without any knowledge of the DBase file's field // keys. Specifically, DBaseRecord.hasKey() returns true for all fields. - if (dbaseFile.isStringEmpty(bytes, numRead)) - { + if (dbaseFile.isStringEmpty(bytes, numRead)) { this.setValue(field.getName(), null); continue; } String value = dbaseFile.decodeString(bytes, numRead).trim(); - try - { - if (field.getType() == DBaseField.TYPE_BOOLEAN) - { + try { + if (field.getType() == DBaseField.TYPE_BOOLEAN) { this.setValue(field.getName(), value.equalsIgnoreCase("T") || value.equalsIgnoreCase("Y")); - } - else if (field.getType() == DBaseField.TYPE_CHAR) - { + } else if (field.getType() == DBaseField.TYPE_CHAR) { this.setValue(field.getName(), value); - } - else if (field.getType() == DBaseField.TYPE_DATE) - { + } else if (field.getType() == DBaseField.TYPE_DATE) { this.setValue(field.getName(), dateformat.parse(value)); - } - else if (field.getType() == DBaseField.TYPE_NUMBER) - { + } else if (field.getType() == DBaseField.TYPE_NUMBER) { // Parse the field value as a decimal number. Double.parseDouble ignores any leading or trailing // whitespace. - if (field.getDecimals() > 0) + if (field.getDecimals() > 0) { this.setValue(field.getName(), Double.valueOf(value)); - else + } else { this.setValue(field.getName(), Long.valueOf(value)); + } } - } - catch (Exception e) - { + } catch (Exception e) { // Log warning but keep reading. Logging.logger().log(Level.WARNING, Logging.getMessage("SHP.FieldParsingError", field, value), e); } diff --git a/src/gov/nasa/worldwind/formats/shapefile/Shapefile.java b/src/gov/nasa/worldwind/formats/shapefile/Shapefile.java index a736703126..78c3d6da0a 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/Shapefile.java +++ b/src/gov/nasa/worldwind/formats/shapefile/Shapefile.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.shapefile; import com.jogamp.common.nio.Buffers; @@ -25,10 +24,12 @@ /** * Parses an ESRI Shapefile (.shp) and provides access to its contents. For details on the Shapefile format see the ESRI - * documentation at http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf. + * documentation at + * http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf. *

        * The Shapefile provides a streaming interface for parsing a Shapefile's contents. The streaming interface enables - * applications to read Shapefiles that do not fit in memory. A typical usage pattern is as follows:

        
        + * applications to read Shapefiles that do not fit in memory. A typical usage pattern is as follows:
        + * 
        
          * Object source = "MyShapefile.shp";
          * Shapefile sf = new Shapefile(source);
          * try
        @@ -67,10 +68,12 @@
          * Shapefile gives priority to the AVList if an accompanying projection file is available and AVList projection
          * parameters are specified. If an accompanying projection file is available, the Shapefile attempts to parse the
          * projection file as an OGC coordinate system encoded in well-known text format. For details, see the OGC Coordinate
        - * Transform Service (CT) specification at http://www.opengeospatial.org/standards/ct.
        - * The Shapefile expects the AVList specifying its coordinate system parameters to contain the following properties:
        + * Transform Service (CT) specification at
        + * http://www.opengeospatial.org/standards/ct. The Shapefile
        + * expects the AVList specifying its coordinate system parameters to contain the following properties:
          * 
        • {@link gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM} - either {@link - * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_GEOGRAPHIC} or {@link gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_PROJECTED}.
        • + * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_GEOGRAPHIC} or + * {@link gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_PROJECTED}. *
        • {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_ZONE} - the UTM zone (if coordinate system projection is UTM); * an integer in the range 1-60.
        • {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_HEMISPHERE} - the UTM * hemisphere (if coordinate system is UTM); either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link @@ -78,16 +81,16 @@ *

          * Subclasses can override how the Shapefile reads and interprets its coordinate system. Override {@link * #readCoordinateSystem()} and {@link #validateCoordinateSystem(gov.nasa.worldwind.avlist.AVList)} to change how the - * Shapefile parses an accompanying projection file and validates the coordinate system parameters. Override - * {@link #readBoundingRectangle(java.nio.ByteBuffer)} - * and {@link #readPoints(gov.nasa.worldwind.formats.shapefile.ShapefileRecord,java.nio.ByteBuffer)} to change how the + * Shapefile parses an accompanying projection file and validates the coordinate system parameters. Override + * {@link #readBoundingRectangle(java.nio.ByteBuffer)} and + * {@link #readPoints(gov.nasa.worldwind.formats.shapefile.ShapefileRecord,java.nio.ByteBuffer)} to change how the * Shapefile's point coordinates are interpreted according to its coordinate system. * * @author Patrick Murris * @version $Id: Shapefile.java 3426 2015-09-30 23:19:16Z dcollins $ */ -public class Shapefile extends AVListImpl implements Closeable, Exportable -{ +public class Shapefile extends AVListImpl implements Closeable, Exportable { + protected static final int FILE_CODE = 0x0000270A; protected static final int HEADER_LENGTH = 100; @@ -96,22 +99,22 @@ public class Shapefile extends AVListImpl implements Closeable, Exportable protected static final String ATTRIBUTE_FILE_SUFFIX = ".dbf"; protected static final String PROJECTION_FILE_SUFFIX = ".prj"; - protected static final String[] SHAPE_CONTENT_TYPES = - { - "application/shp", - "application/octet-stream" - }; - protected static final String[] INDEX_CONTENT_TYPES = - { - "application/shx", - "application/octet-stream" - }; - protected static final String[] PROJECTION_CONTENT_TYPES = - { - "application/prj", - "application/octet-stream", - "text/plain" - }; + protected static final String[] SHAPE_CONTENT_TYPES + = { + "application/shp", + "application/octet-stream" + }; + protected static final String[] INDEX_CONTENT_TYPES + = { + "application/shx", + "application/octet-stream" + }; + protected static final String[] PROJECTION_CONTENT_TYPES + = { + "application/prj", + "application/octet-stream", + "text/plain" + }; public static final String SHAPE_NULL = "gov.nasa.worldwind.formats.shapefile.Shapefile.ShapeNull"; public static final String SHAPE_POINT = "gov.nasa.worldwind.formats.shapefile.Shapefile.ShapePoint"; @@ -132,21 +135,21 @@ public class Shapefile extends AVListImpl implements Closeable, Exportable public static final String SHAPE_MULTI_PATCH = "gov.nasa.worldwind.formats.shapefile.Shapefile.ShapeMultiPatch"; protected static List measureTypes = new ArrayList(Arrays.asList( - Shapefile.SHAPE_POINT_M, Shapefile.SHAPE_POINT_Z, - Shapefile.SHAPE_MULTI_POINT_M, Shapefile.SHAPE_MULTI_POINT_Z, - Shapefile.SHAPE_POLYLINE_M, Shapefile.SHAPE_POLYLINE_Z, - Shapefile.SHAPE_POLYGON_M, Shapefile.SHAPE_POLYGON_Z + Shapefile.SHAPE_POINT_M, Shapefile.SHAPE_POINT_Z, + Shapefile.SHAPE_MULTI_POINT_M, Shapefile.SHAPE_MULTI_POINT_Z, + Shapefile.SHAPE_POLYLINE_M, Shapefile.SHAPE_POLYLINE_Z, + Shapefile.SHAPE_POLYGON_M, Shapefile.SHAPE_POLYGON_Z )); protected static List zTypes = new ArrayList(Arrays.asList( - Shapefile.SHAPE_POINT_Z, - Shapefile.SHAPE_MULTI_POINT_Z, - Shapefile.SHAPE_POLYLINE_Z, - Shapefile.SHAPE_POLYGON_Z + Shapefile.SHAPE_POINT_Z, + Shapefile.SHAPE_MULTI_POINT_Z, + Shapefile.SHAPE_POLYLINE_Z, + Shapefile.SHAPE_POLYGON_Z )); - protected static class Header - { + protected static class Header { + public int fileCode = FILE_CODE; public int fileLength; public int version; @@ -194,41 +197,35 @@ protected static class Header * @param params parameter list describing metadata about the Shapefile, such as its map projection. * * @throws IllegalArgumentException if the source is null or an empty string. - * @throws WWRuntimeException if the shapefile cannot be opened for any reason, or if the shapefile's - * coordinate system is unsupported. + * @throws WWRuntimeException if the shapefile cannot be opened for any reason, or if the shapefile's coordinate + * system is unsupported. */ - public Shapefile(Object source, AVList params) - { - if (source == null || WWUtil.isEmpty(source)) - { + public Shapefile(Object source, AVList params) { + if (source == null || WWUtil.isEmpty(source)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { this.setValue(AVKey.DISPLAY_NAME, source.toString()); - if (source instanceof File) + if (source instanceof File) { this.initializeFromFile((File) source, params); - else if (source instanceof URL) + } else if (source instanceof URL) { this.initializeFromURL((URL) source, params); - else if (source instanceof InputStream) + } else if (source instanceof InputStream) { this.initializeFromStreams((InputStream) source, null, null, null, params); - else if (source instanceof String) + } else if (source instanceof String) { this.initializeFromPath((String) source, params); - else - { + } else { String message = Logging.getMessage("generic.UnrecognizedSourceType", source); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("SHP.ExceptionAttemptingToReadShapefile", - this.getValue(AVKey.DISPLAY_NAME)); + this.getValue(AVKey.DISPLAY_NAME)); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } @@ -250,10 +247,9 @@ else if (source instanceof String) * @param source the source of the shapefile. * * @throws IllegalArgumentException if the source is null or an empty string. - * @throws WWRuntimeException if the shapefile cannot be opened for any reason. + * @throws WWRuntimeException if the shapefile cannot be opened for any reason. */ - public Shapefile(Object source) - { + public Shapefile(Object source) { this(source, null); } @@ -270,29 +266,24 @@ public Shapefile(Object source) * @param shxStream the index file stream, can be null. * @param dbfStream the attribute file stream, can be null. * @param prjStream the projection file stream, can be null. - * @param params parameter list describing metadata about the Shapefile, such as its map projection. + * @param params parameter list describing metadata about the Shapefile, such as its map projection. * * @throws IllegalArgumentException if the shapefile geometry stream shpStream is null. - * @throws WWRuntimeException if the shapefile cannot be opened for any reason, or if the shapefile's - * coordinate system is unsupported. + * @throws WWRuntimeException if the shapefile cannot be opened for any reason, or if the shapefile's coordinate + * system is unsupported. */ public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfStream, InputStream prjStream, - AVList params) - { - if (shpStream == null) - { + AVList params) { + if (shpStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { this.setValue(AVKey.DISPLAY_NAME, shpStream.toString()); this.initializeFromStreams(shpStream, shxStream, dbfStream, prjStream, params); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("SHP.ExceptionAttemptingToReadShapefile", shpStream); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); @@ -314,11 +305,10 @@ public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfSt * @param prjStream the projection file stream, can be null. * * @throws IllegalArgumentException if the shapefile geometry stream shpStream is null. - * @throws WWRuntimeException if the shapefile cannot be opened for any reason, or if the shapefile's - * coordinate system is unsupported. + * @throws WWRuntimeException if the shapefile cannot be opened for any reason, or if the shapefile's coordinate + * system is unsupported. */ - public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfStream, InputStream prjStream) - { + public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfStream, InputStream prjStream) { this(shpStream, shxStream, dbfStream, prjStream, null); } @@ -334,14 +324,13 @@ public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfSt * @param shpStream the shapefile geometry file stream. * @param shxStream the index file stream, can be null. * @param dbfStream the attribute file stream, can be null. - * @param params parameter list describing metadata about the Shapefile, such as its map projection. + * @param params parameter list describing metadata about the Shapefile, such as its map projection. * * @throws IllegalArgumentException if the shapefile geometry stream shpStream is null. - * @throws WWRuntimeException if the shapefile cannot be opened for any reason, or if the shapefile's - * coordinate system is unsupported. + * @throws WWRuntimeException if the shapefile cannot be opened for any reason, or if the shapefile's coordinate + * system is unsupported. */ - public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfStream, AVList params) - { + public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfStream, AVList params) { this(shpStream, shxStream, dbfStream, null, params); } @@ -357,10 +346,9 @@ public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfSt * @param dbfStream the attribute file stream, can be null. * * @throws IllegalArgumentException if the shapefile geometry stream shpStream is null. - * @throws WWRuntimeException if the shapefile cannot be opened for any reason. + * @throws WWRuntimeException if the shapefile cannot be opened for any reason. */ - public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfStream) - { + public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfStream) { this(shpStream, shxStream, dbfStream, null, null); } @@ -369,8 +357,7 @@ public Shapefile(InputStream shpStream, InputStream shxStream, InputStream dbfSt * * @return the shapefile's version field, or -1 to denote the Shapefile failed to open. */ - public int getVersion() - { + public int getVersion() { return this.header != null ? this.header.version : -1; } @@ -379,8 +366,7 @@ public int getVersion() * * @return the raw shapefile's length in bytes, or -1 to denote the Shapefile failed to open. */ - public int getLength() - { + public int getLength() { return this.header != null ? this.header.fileLength : -1; } @@ -393,10 +379,9 @@ public int getLength() * #SHAPE_POLYGON_Z}

        • {@link #SHAPE_MULTI_PATCH}
        * * @return the shapefile's shape type: null if the Shapefile failed to open, othersise a symbolic constants denoting - * the type. + * the type. */ - public String getShapeType() - { + public String getShapeType() { return this.header != null ? this.header.shapeType : null; } @@ -408,8 +393,7 @@ public String getShapeType() * * @return the shapefile's bounding rectangle, or null to denote the Shapefile failed to open. */ - public double[] getBoundingRectangle() - { + public double[] getBoundingRectangle() { return this.header != null ? this.header.boundingRectangle : null; } @@ -418,8 +402,7 @@ public double[] getBoundingRectangle() * * @return the number of records in the shapefile, or -1 to denote an unknown number of records. */ - public int getNumberOfRecords() - { + public int getNumberOfRecords() { return this.index != null ? this.index.length / 2 : -1; } @@ -428,8 +411,7 @@ public int getNumberOfRecords() * * @return the underlying {@link CompoundVecBuffer}. */ - public CompoundVecBuffer getPointBuffer() - { + public CompoundVecBuffer getPointBuffer() { return this.pointBuffer; } @@ -438,16 +420,15 @@ public CompoundVecBuffer getPointBuffer() * has no associated attributes. * * @return a set containing the unique attribute names of this shapefile's records, or null if there are no - * attributes. + * attributes. */ - public Set getAttributeNames() - { - if (this.attributeFile == null) + public Set getAttributeNames() { + if (this.attributeFile == null) { return null; + } HashSet set = new HashSet(); - for (DBaseField field : this.attributeFile.getFields()) - { + for (DBaseField field : this.attributeFile.getFields()) { set.add(field.getName()); } @@ -460,24 +441,27 @@ public Set getAttributeNames() * * @return true if the Shapefile has a more records; false otherwise. */ - public boolean hasNext() - { - if (!this.open || this.header == null) + public boolean hasNext() { + if (!this.open || this.header == null) { return false; + } int contentLength = this.header.fileLength - HEADER_LENGTH; return this.numBytesRead < contentLength; } /** - * Reads the Shapefile's next record and returns the result as a new {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord}. - * The record's type depends on the Shapefile's type, and is one of the following:
        • {@link + * Reads the Shapefile's next record and returns the result as a new + * {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord}. The record's type depends on the Shapefile's type, + * and is one of the following:
          • {@link * gov.nasa.worldwind.formats.shapefile.ShapefileRecordPoint} if type is {@link #SHAPE_POINT}, {@link - * #SHAPE_POINT_M} or {@link #SHAPE_POINT_Z}.
          • {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecordMultiPoint} - * if type is {@link #SHAPE_MULTI_POINT}, {@link #SHAPE_MULTI_POINT_M} or {@link #SHAPE_MULTI_POINT_Z}.
          • + * #SHAPE_POINT_M} or {@link #SHAPE_POINT_Z}. + *
          • {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecordMultiPoint} if type is + * {@link #SHAPE_MULTI_POINT}, {@link #SHAPE_MULTI_POINT_M} or {@link #SHAPE_MULTI_POINT_Z}.
          • *
          • {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecordPolyline} if type is {@link #SHAPE_POLYLINE}, - * {@link #SHAPE_POLYLINE_M} or {@link #SHAPE_POLYLINE_Z}.
          • {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecordPolygon} - * if type is {@link #SHAPE_POLYGON}, {@link #SHAPE_POLYGON_M} or {@link #SHAPE_POLYGON_Z}.
          + * {@link #SHAPE_POLYLINE_M} or {@link #SHAPE_POLYLINE_Z}.
        • + *
        • {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecordPolygon} if type is + * {@link #SHAPE_POLYGON}, {@link #SHAPE_POLYGON_M} or {@link #SHAPE_POLYGON_Z}.
        *

        * This throws an exception if the JVM cannot allocate enough memory to hold the buffer used to store the record's * point coordinates. @@ -485,13 +469,11 @@ public boolean hasNext() * @return the Shapefile's next record. * * @throws IllegalStateException if the Shapefile is closed or if the Shapefile has no more records. - * @throws WWRuntimeException if an exception occurs while reading the record. + * @throws WWRuntimeException if an exception occurs while reading the record. * @see #getShapeType() */ - public ShapefileRecord nextRecord() - { - if (!this.open) - { + public ShapefileRecord nextRecord() { + if (!this.open) { String message = Logging.getMessage("SHP.ShapefileClosed", this.getStringValue(AVKey.DISPLAY_NAME)); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -505,22 +487,18 @@ public ShapefileRecord nextRecord() } int contentLength = this.header.fileLength - HEADER_LENGTH; - if (contentLength <= 0 || this.numBytesRead >= contentLength) - { + if (contentLength <= 0 || this.numBytesRead >= contentLength) { String message = Logging.getMessage("SHP.NoRecords", this.getStringValue(AVKey.DISPLAY_NAME)); Logging.logger().severe(message); throw new IllegalStateException(message); } ShapefileRecord record; - try - { + try { record = this.readNextRecord(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("SHP.ExceptionAttemptingToReadShapefileRecord", - this.getStringValue(AVKey.DISPLAY_NAME)); + this.getStringValue(AVKey.DISPLAY_NAME)); Logging.logger().log(Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } @@ -539,28 +517,23 @@ record = this.readNextRecord(); * #getShapeType()}

      • {@link #getBoundingRectangle()}
      • {@link #getNumberOfRecords()}
      • {@link * #getPointBuffer()}
      • */ - public void close() - { - if (this.shpChannel != null) - { + public void close() { + if (this.shpChannel != null) { WWIO.closeStream(this.shpChannel, null); this.shpChannel = null; } - if (this.shxChannel != null) - { + if (this.shxChannel != null) { WWIO.closeStream(this.shxChannel, null); this.shxChannel = null; } - if (this.prjChannel != null) - { + if (this.prjChannel != null) { WWIO.closeStream(this.prjChannel, null); this.prjChannel = null; } - if (this.attributeFile != null) - { + if (this.attributeFile != null) { this.attributeFile.close(); this.attributeFile = null; } @@ -576,8 +549,7 @@ public void close() * * @return true if the shapefile's points should be normalized; false otherwise. */ - protected boolean isNormalizePoints() - { + protected boolean isNormalizePoints() { return this.normalizePoints; } @@ -585,21 +557,17 @@ protected boolean isNormalizePoints() * Specifies if the shapefile's point coordinates should be normalized. Defaults to false. * * @param normalizePoints true if the shapefile's points should be normalized; false - * otherwise. + * otherwise. */ - protected void setNormalizePoints(boolean normalizePoints) - { + protected void setNormalizePoints(boolean normalizePoints) { this.normalizePoints = normalizePoints; } //**************************************************************// //******************** Initialization ************************// //**************************************************************// - - protected void initializeFromFile(File file, AVList params) throws IOException - { - if (!file.exists()) - { + protected void initializeFromFile(File file, AVList params) throws IOException { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file.getPath()); Logging.logger().severe(message); throw new FileNotFoundException(message); @@ -610,37 +578,36 @@ protected void initializeFromFile(File file, AVList params) throws IOException // file. Although we never change the file's bytes on disk, the file must be accessible for reading and writing // to use copy-on-write mode. Therefore files locked for writing and files stored on a read-only device // (e.g. CD, DVD) cannot be memory mapped. - if (file.canRead() && file.canWrite()) - { - try - { + if (file.canRead() && file.canWrite()) { + try { // Memory map the Shapefile in copy-on-write mode. this.mappedShpBuffer = WWIO.mapFile(file, FileChannel.MapMode.PRIVATE); Logging.logger().finer(Logging.getMessage("SHP.MemoryMappingEnabled", file.getPath())); - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().log(Level.WARNING, - Logging.getMessage("SHP.ExceptionAttemptingToMemoryMap", file.getPath()), e); + Logging.getMessage("SHP.ExceptionAttemptingToMemoryMap", file.getPath()), e); } } // If attempting to memory map the Shapefile failed, fall back on opening the file as a generic stream. Throw an // IOException if the file cannot be opened via stream. - if (this.mappedShpBuffer == null) + if (this.mappedShpBuffer == null) { this.shpChannel = Channels.newChannel(new BufferedInputStream(new FileInputStream(file))); + } // Attempt to open the optional index and projection files associated with the Shapefile. Ignore exceptions // thrown while attempting to open these optional resource streams. We wrap each source InputStream in a // BufferedInputStream because this increases read performance, even when the stream is wrapped in an NIO // Channel. InputStream shxStream = this.getFileStream(WWIO.replaceSuffix(file.getPath(), INDEX_FILE_SUFFIX)); - if (shxStream != null) + if (shxStream != null) { this.shxChannel = Channels.newChannel(WWIO.getBufferedInputStream(shxStream)); + } InputStream prjStream = this.getFileStream(WWIO.replaceSuffix(file.getPath(), PROJECTION_FILE_SUFFIX)); - if (prjStream != null) + if (prjStream != null) { this.prjChannel = Channels.newChannel(WWIO.getBufferedInputStream(prjStream)); + } // Initialize the Shapefile before opening its associated attributes file. This avoids opening the attributes // file if an exception is thrown while opening the Shapefile. @@ -649,28 +616,22 @@ protected void initializeFromFile(File file, AVList params) throws IOException // Open the shapefile attribute source as a DBaseFile. We let the DBaseFile determine how to handle source File. File dbfFile = new File(WWIO.replaceSuffix(file.getPath(), ATTRIBUTE_FILE_SUFFIX)); - if (dbfFile.exists()) - { - try - { + if (dbfFile.exists()) { + try { this.attributeFile = new DBaseFile(dbfFile); - } - catch (Exception e) - { + } catch (Exception e) { // Exception already logged by DBaseFile constructor. } } } - protected void initializeFromURL(URL url, AVList params) throws IOException - { + protected void initializeFromURL(URL url, AVList params) throws IOException { // Opening the Shapefile URL as a URL connection. Throw an IOException if the URL connection cannot be opened, // or if it's an invalid Shapefile connection. URLConnection connection = url.openConnection(); String message = this.validateURLConnection(connection, SHAPE_CONTENT_TYPES); - if (message != null) - { + if (message != null) { throw new IOException(message); } @@ -681,30 +642,28 @@ protected void initializeFromURL(URL url, AVList params) throws IOException // invalid. We wrap each source InputStream in a BufferedInputStream because this increases read performance, // even when the stream is wrapped in an NIO Channel. URLConnection shxConnection = this.getURLConnection(WWIO.replaceSuffix(url.toString(), INDEX_FILE_SUFFIX)); - if (shxConnection != null) - { + if (shxConnection != null) { message = this.validateURLConnection(shxConnection, INDEX_CONTENT_TYPES); - if (message != null) + if (message != null) { Logging.logger().warning(message); - else - { + } else { InputStream shxStream = this.getURLStream(shxConnection); - if (shxStream != null) + if (shxStream != null) { this.shxChannel = Channels.newChannel(WWIO.getBufferedInputStream(shxStream)); + } } } URLConnection prjConnection = this.getURLConnection(WWIO.replaceSuffix(url.toString(), PROJECTION_FILE_SUFFIX)); - if (prjConnection != null) - { + if (prjConnection != null) { message = this.validateURLConnection(prjConnection, PROJECTION_CONTENT_TYPES); - if (message != null) + if (message != null) { Logging.logger().warning(message); - else - { + } else { InputStream prjStream = this.getURLStream(prjConnection); - if (prjStream != null) + if (prjStream != null) { this.prjChannel = Channels.newChannel(WWIO.getBufferedInputStream(prjStream)); + } } } @@ -715,34 +674,32 @@ protected void initializeFromURL(URL url, AVList params) throws IOException // Open the shapefile attribute source as a DBaseFile. We let the DBaseFile determine how to handle source URL. URL dbfURL = WWIO.makeURL(WWIO.replaceSuffix(url.toString(), ATTRIBUTE_FILE_SUFFIX)); - if (dbfURL != null) - { - try - { + if (dbfURL != null) { + try { this.attributeFile = new DBaseFile(dbfURL); - } - catch (Exception e) - { + } catch (Exception e) { // Exception already logged by DBaseFile constructor. } } } protected void initializeFromStreams(InputStream shpStream, InputStream shxStream, InputStream dbfStream, - InputStream prjStream, AVList params) throws IOException - { + InputStream prjStream, AVList params) throws IOException { // Create Channels for the collection of resources used by the Shapefile reader. We wrap each source InputStream // in a BufferedInputStream because this increases read performance, even when the stream is wrapped in an NIO // Channel. - if (shpStream != null) + if (shpStream != null) { this.shpChannel = Channels.newChannel(WWIO.getBufferedInputStream(shpStream)); + } - if (shxStream != null) + if (shxStream != null) { this.shxChannel = Channels.newChannel(WWIO.getBufferedInputStream(shxStream)); + } - if (prjStream != null) + if (prjStream != null) { this.prjChannel = Channels.newChannel(WWIO.getBufferedInputStream(prjStream)); + } // Initialize the Shapefile before opening its associated attributes file. This avoids opening the attributes // file if an exception is thrown while opening the Shapefile. @@ -750,31 +707,24 @@ protected void initializeFromStreams(InputStream shpStream, InputStream shxStrea // Open the shapefile attribute source as a DBaseFile. We let the DBaseFile determine how to handle its source // InputStream. - if (dbfStream != null) - { - try - { + if (dbfStream != null) { + try { this.attributeFile = new DBaseFile(dbfStream); - } - catch (Exception e) - { + } catch (Exception e) { // Exception already logged by DBaseFile constructor. } } } - protected void initializeFromPath(String path, AVList params) throws IOException - { + protected void initializeFromPath(String path, AVList params) throws IOException { File file = new File(path); - if (file.exists()) - { + if (file.exists()) { this.initializeFromFile(file, params); return; } URL url = WWIO.makeURL(path); - if (url != null) - { + if (url != null) { this.initializeFromURL(url, params); return; } @@ -789,30 +739,26 @@ protected void initializeFromPath(String path, AVList params) throws IOException * available), validates the Shapefile's coordinate system, and reads the Shapefile's header. * * @param params arameter list describing metadata about the Shapefile, such as its map projection, or null to - * specify no additional parameters. + * specify no additional parameters. * * @throws IOException if an error occurs while reading the Shapefile's header. */ - protected void initialize(AVList params) throws IOException - { + protected void initialize(AVList params) throws IOException { // Attempt to read this Shapefile's projection resource, and set any projection parameters parsed from that // resource. If reading the projection resource fails, log the exception and continue. - try - { + try { AVList csParams = this.readCoordinateSystem(); - if (csParams != null) + if (csParams != null) { this.setValues(csParams); - } - catch (IOException e) - { + } + } catch (IOException e) { Logging.logger().log(Level.WARNING, - Logging.getMessage("SHP.ExceptionAttemptingToReadProjection", this.getStringValue(AVKey.DISPLAY_NAME)), e); + Logging.getMessage("SHP.ExceptionAttemptingToReadProjection", this.getStringValue(AVKey.DISPLAY_NAME)), e); } // Set the Shapefile's caller specified parameters. We do this after reading the projection parameters to give // the caller's parameters priority over the projection parameters. - if (params != null) - { + if (params != null) { this.setValues(params); } @@ -821,8 +767,7 @@ protected void initialize(AVList params) throws IOException // about what the coordinates represent. Throw a WWRuntimeException if the projection is either invalid or // unsupported. Subsequent attempts to query the Shapefile's header data or read its records cause an exception. String message = this.validateCoordinateSystem(this); - if (message != null) - { + if (message != null) { throw new WWRuntimeException(message); } @@ -830,14 +775,11 @@ protected void initialize(AVList params) throws IOException // continue. We read the index after reading any projection information and assigning the caller specified // parameters. This ensures that any coordinates in the header are converted according to the Shapefile's // coordinate system. - try - { + try { this.index = this.readIndex(); - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().log(Level.WARNING, - Logging.getMessage("SHP.ExceptionAttemptingToReadIndex", this.getStringValue(AVKey.DISPLAY_NAME)), e); + Logging.getMessage("SHP.ExceptionAttemptingToReadIndex", this.getStringValue(AVKey.DISPLAY_NAME)), e); } // Read this Shapefile's header and flag the Shapefile as open. We read the header after reading any projection @@ -850,67 +792,51 @@ protected void initialize(AVList params) throws IOException this.setNormalizePoints(this.header.normalizePoints); } - protected InputStream getFileStream(String path) - { - try - { + protected InputStream getFileStream(String path) { + try { return new FileInputStream(path); - } - catch (Exception e) - { + } catch (Exception e) { return null; } } - protected URLConnection getURLConnection(String urlString) - { - try - { + protected URLConnection getURLConnection(String urlString) { + try { URL url = new URL(urlString); return url.openConnection(); - } - catch (Exception e) - { + } catch (Exception e) { return null; } } - protected InputStream getURLStream(URLConnection connection) - { - try - { + protected InputStream getURLStream(URLConnection connection) { + try { return connection.getInputStream(); - } - catch (Exception e) - { + } catch (Exception e) { return null; } } - protected String validateURLConnection(URLConnection connection, String[] acceptedContentTypes) - { - try - { - if (connection instanceof HttpURLConnection && - ((HttpURLConnection) connection).getResponseCode() != HttpURLConnection.HTTP_OK) - { + protected String validateURLConnection(URLConnection connection, String[] acceptedContentTypes) { + try { + if (connection instanceof HttpURLConnection + && ((HttpURLConnection) connection).getResponseCode() != HttpURLConnection.HTTP_OK) { return Logging.getMessage("HTTP.ResponseCode", ((HttpURLConnection) connection).getResponseCode(), - connection.getURL()); + connection.getURL()); } - } - catch (Exception e) - { + } catch (Exception e) { return Logging.getMessage("URLRetriever.ErrorOpeningConnection", connection.getURL()); } String contentType = connection.getContentType(); - if (WWUtil.isEmpty(contentType)) + if (WWUtil.isEmpty(contentType)) { return null; + } - for (String type : acceptedContentTypes) - { - if (contentType.trim().toLowerCase().startsWith(type)) + for (String type : acceptedContentTypes) { + if (contentType.trim().toLowerCase().startsWith(type)) { return null; + } } // Return an exception if the content type does not match the expected type. @@ -920,7 +846,6 @@ protected String validateURLConnection(URLConnection connection, String[] accept //**************************************************************// //******************** Header ********************************// //**************************************************************// - /** * Reads the {@link Header} from this Shapefile. This file is assumed to have a header. * @@ -928,21 +853,16 @@ protected String validateURLConnection(URLConnection connection, String[] accept * * @throws IOException if the header cannot be read for any reason. */ - protected Header readHeader() throws IOException - { + protected Header readHeader() throws IOException { ByteBuffer buffer; - if (this.mappedShpBuffer != null) - { + if (this.mappedShpBuffer != null) { buffer = this.mappedShpBuffer; - } - else - { + } else { buffer = ByteBuffer.allocate(HEADER_LENGTH); WWIO.readChannelToBuffer(this.shpChannel, buffer); } - if (buffer.remaining() < HEADER_LENGTH) - { + if (buffer.remaining() < HEADER_LENGTH) { // Let the caller catch and log the message. throw new WWRuntimeException(Logging.getMessage("generic.InvalidFileLength", buffer.remaining())); } @@ -962,20 +882,17 @@ protected Header readHeader() throws IOException * * @throws IOException if the header cannot be read for any reason. */ - protected Header readHeaderFromBuffer(ByteBuffer buffer) throws IOException - { + protected Header readHeaderFromBuffer(ByteBuffer buffer) throws IOException { Header header = null; // Save the buffer's current position. int pos = buffer.position(); - try - { + try { // Read file code - first 4 bytes, big endian buffer.order(ByteOrder.BIG_ENDIAN); int fileCode = buffer.getInt(); - if (fileCode != FILE_CODE) - { + if (fileCode != FILE_CODE) { // Let the caller catch and log the message. throw new WWUnrecognizedException(Logging.getMessage("SHP.UnrecognizedShapefile", fileCode)); } @@ -996,8 +913,7 @@ protected Header readHeaderFromBuffer(ByteBuffer buffer) throws IOException // Check whether the shape type is supported String shapeType = getShapeType(type); - if (shapeType == null) - { + if (shapeType == null) { // Let the caller catch and log the message. throw new WWRuntimeException(Logging.getMessage("SHP.UnsupportedShapeType", type)); } @@ -1009,9 +925,7 @@ protected Header readHeaderFromBuffer(ByteBuffer buffer) throws IOException header.shapeType = shapeType; header.boundingRectangle = rect.coords; header.normalizePoints = rect.isNormalized; - } - finally - { + } finally { // Move to the end of the header. buffer.position(pos + HEADER_LENGTH); } @@ -1022,7 +936,6 @@ protected Header readHeaderFromBuffer(ByteBuffer buffer) throws IOException //**************************************************************// //******************** Index *********************************// //**************************************************************// - /** * Reads the Shapefile's accompanying index file and return the indices as an array of integers. Each array element * represents the byte offset of the i'th record from the start of the Shapefile. This returns null if @@ -1030,22 +943,23 @@ protected Header readHeaderFromBuffer(ByteBuffer buffer) throws IOException * memory to hold the index. * * @return the Shapefile's record offset index, or null if the Shapefile has no accompanying index - * file, if the index file is empty, or if the index cannot be allocated. + * file, if the index file is empty, or if the index cannot be allocated. * * @throws IOException if an exception occurs during reading. */ - protected int[] readIndex() throws IOException - { + protected int[] readIndex() throws IOException { // The Shapefile index resource is optional. Return null if we don't have a stream to an index resource. - if (this.shxChannel == null) + if (this.shxChannel == null) { return null; + } ByteBuffer buffer = ByteBuffer.allocate(HEADER_LENGTH); WWIO.readChannelToBuffer(this.shxChannel, buffer); // Return null if the index is empty or is smaller than the minimum required size. - if (buffer.remaining() < HEADER_LENGTH) + if (buffer.remaining() < HEADER_LENGTH) { return null; + } Header indexHeader = this.readHeaderFromBuffer(buffer); int numRecords = (indexHeader.fileLength - HEADER_LENGTH) / 8; @@ -1053,17 +967,14 @@ protected int[] readIndex() throws IOException int indexLength = 8 * numRecords; // 8 bytes per record. int[] array; - try - { + try { buffer = ByteBuffer.allocate(indexLength); array = new int[numElements]; - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { // Log a warning that we could not allocate enough memory to hold the Shapefile index. Shapefile parsing // can continue without the optional index, so we catch the exception and return immediately. Logging.logger().log(Level.WARNING, - Logging.getMessage("SHP.OutOfMemoryAllocatingIndex", this.getStringValue(AVKey.DISPLAY_NAME)), e); + Logging.getMessage("SHP.OutOfMemoryAllocatingIndex", this.getStringValue(AVKey.DISPLAY_NAME)), e); return null; } @@ -1072,8 +983,7 @@ protected int[] readIndex() throws IOException buffer.asIntBuffer().get(array); - for (int i = 0; i < numElements; i++) - { + for (int i = 0; i < numElements; i++) { array[i] *= 2; // Convert indices from 16-bit words to byte indices. } @@ -1083,32 +993,33 @@ protected int[] readIndex() throws IOException //**************************************************************// //******************** Coordinate System *********************// //**************************************************************// - /** * Reads the Shapefile's accompanying projection file as an OGC coordinate system encoded in well-known text format, * and returns the coordinate system parameters. This returns null if this Shapefile has no * accompanying projection file or if the projection file is empty. For details, see the OGC Coordinate Transform - * Service (CT) specification at http://www.opengeospatial.org/standards/ct. + * Service (CT) specification at + * http://www.opengeospatial.org/standards/ct. * * @return coordinate system parameters parsed from the projection file, or null if this Shapefile has - * no accompanying projection file or the projection file is empty. + * no accompanying projection file or the projection file is empty. * * @throws IOException if an exception occurs during reading. */ - protected AVList readCoordinateSystem() throws IOException - { + protected AVList readCoordinateSystem() throws IOException { // The Shapefile projection resource is optional. Return the parameter list unchanged if we don't have a stream // to a projection resource. - if (this.prjChannel == null) + if (this.prjChannel == null) { return null; + } // Read the Shapefile's associated projection to a String, using the default character encoding. Decode the // projection text as an OGC coordinate system formatted as well-known text. String text = WWIO.readChannelToString(this.prjChannel, null); // Return null if the projection file is empty. - if (WWUtil.isEmpty(text)) + if (WWUtil.isEmpty(text)) { return null; + } return WorldFile.decodeOGCCoordinateSystemWKT(text, null); } @@ -1121,26 +1032,18 @@ protected AVList readCoordinateSystem() throws IOException * * @return a non-empty string if the coordinate system parameters are invalid; null otherwise. */ - protected String validateCoordinateSystem(AVList params) - { + protected String validateCoordinateSystem(AVList params) { Object o = params.getValue(AVKey.COORDINATE_SYSTEM); - if (!this.hasKey(AVKey.COORDINATE_SYSTEM)) - { + if (!this.hasKey(AVKey.COORDINATE_SYSTEM)) { Logging.logger().warning( - Logging.getMessage("generic.UnspecifiedCoordinateSystem", this.getStringValue(AVKey.DISPLAY_NAME))); + Logging.getMessage("generic.UnspecifiedCoordinateSystem", this.getStringValue(AVKey.DISPLAY_NAME))); return null; - } - else if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(o)) - { + } else if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(o)) { return null; - } - else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) - { + } else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) { return this.validateProjection(params); - } - else - { + } else { return Logging.getMessage("generic.UnsupportedCoordinateSystem", o); } } @@ -1153,32 +1056,30 @@ else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) * * @return a non-empty string if the projection parameters are invalid; null otherwise. */ - protected String validateProjection(AVList params) - { + protected String validateProjection(AVList params) { Object proj = params.getValue(AVKey.PROJECTION_NAME); - if (AVKey.PROJECTION_UTM.equals(proj)) - { + if (AVKey.PROJECTION_UTM.equals(proj)) { StringBuilder sb = new StringBuilder(); // Validate the UTM zone. Object o = params.getValue(AVKey.PROJECTION_ZONE); - if (o == null) + if (o == null) { sb.append(Logging.getMessage("generic.ZoneIsMissing")); - else if (!(o instanceof Integer) || ((Integer) o) < 1 || ((Integer) o) > 60) + } else if (!(o instanceof Integer) || ((Integer) o) < 1 || ((Integer) o) > 60) { sb.append(Logging.getMessage("generic.ZoneIsInvalid", o)); + } // Validate the UTM hemisphere. o = params.getValue(AVKey.PROJECTION_HEMISPHERE); - if (o == null) + if (o == null) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("generic.HemisphereIsMissing")); - else if (!o.equals(AVKey.NORTH) && !o.equals(AVKey.SOUTH)) + } else if (!o.equals(AVKey.NORTH) && !o.equals(AVKey.SOUTH)) { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("generic.HemisphereIsInvalid", o)); + } return sb.length() > 0 ? sb.toString() : null; - } - else - { + } else { return Logging.getMessage("generic.UnsupportedProjection", proj); } } @@ -1186,7 +1087,6 @@ else if (!o.equals(AVKey.NORTH) && !o.equals(AVKey.SOUTH)) //**************************************************************// //******************** Shape Records *************************// //**************************************************************// - /** * Reads the next {@link ShapefileRecord} instance from this Shapefile. This file is assumed to have one or more * remaining records available. @@ -1195,12 +1095,10 @@ else if (!o.equals(AVKey.NORTH) && !o.equals(AVKey.SOUTH)) * * @throws IOException if the record cannot be read for any reason. */ - protected ShapefileRecord readNextRecord() throws IOException - { + protected ShapefileRecord readNextRecord() throws IOException { ByteBuffer buffer; - if (this.mappedShpBuffer != null) - { + if (this.mappedShpBuffer != null) { // Save the mapped buffer's current position and limit. int pos = this.mappedShpBuffer.position(); @@ -1217,12 +1115,11 @@ protected ShapefileRecord readNextRecord() throws IOException this.numBytesRead += recordLength; buffer = this.mappedShpBuffer; - } - else - { + } else { // Allocate a buffer to hold the record header. - if (this.recordHeaderBuffer == null) + if (this.recordHeaderBuffer == null) { this.recordHeaderBuffer = ByteBuffer.allocate(ShapefileRecord.RECORD_HEADER_LENGTH); + } // Read the header bytes. this.recordHeaderBuffer.clear(); @@ -1235,8 +1132,9 @@ protected ShapefileRecord readNextRecord() throws IOException int recordLength = ShapefileRecord.RECORD_HEADER_LENGTH + contentLength; // Allocate a buffer to hold the record content. - if (this.recordContentBuffer == null || this.recordContentBuffer.capacity() < recordLength) + if (this.recordContentBuffer == null || this.recordContentBuffer.capacity() < recordLength) { this.recordContentBuffer = ByteBuffer.allocate(recordLength); + } this.recordContentBuffer.limit(recordLength); this.recordContentBuffer.rewind(); @@ -1249,15 +1147,13 @@ protected ShapefileRecord readNextRecord() throws IOException } ShapefileRecord record; - try - { + try { record = this.readRecordFromBuffer(buffer); - } - finally - { + } finally { // Restore the mapped buffer's limit to its capacity. - if (this.mappedShpBuffer != null) + if (this.mappedShpBuffer != null) { this.mappedShpBuffer.limit(this.mappedShpBuffer.capacity()); + } } return record; @@ -1274,15 +1170,12 @@ record = this.readRecordFromBuffer(buffer); * * @return a {@link ShapefileRecord} instance. */ - protected ShapefileRecord readRecordFromBuffer(ByteBuffer buffer) - { + protected ShapefileRecord readRecordFromBuffer(ByteBuffer buffer) { ShapefileRecord record = this.createRecord(buffer); - if (record != null) - { + if (record != null) { // Read the record's attribute data. - if (this.attributeFile != null && this.attributeFile.hasNext()) - { + if (this.attributeFile != null && this.attributeFile.hasNext()) { record.setAttributes(this.attributeFile.nextRecord()); } } @@ -1308,31 +1201,21 @@ protected ShapefileRecord readRecordFromBuffer(ByteBuffer buffer) * @param buffer the buffer containing the record's content. * * @return a new {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord} instance, null if the - * record's shape type is not one of the recognized types. + * record's shape type is not one of the recognized types. */ - protected ShapefileRecord createRecord(ByteBuffer buffer) - { + protected ShapefileRecord createRecord(ByteBuffer buffer) { String shapeType = this.readRecordShapeType(buffer); // Select proper record class - if (isPointType(shapeType)) - { + if (isPointType(shapeType)) { return this.createPoint(buffer); - } - else if (isMultiPointType(shapeType)) - { + } else if (isMultiPointType(shapeType)) { return this.createMultiPoint(buffer); - } - else if (isPolylineType(shapeType)) - { + } else if (isPolylineType(shapeType)) { return this.createPolyline(buffer); - } - else if (isPolygonType(shapeType)) - { + } else if (isPolygonType(shapeType)) { return this.createPolygon(buffer); - } - else if (isNullType(shapeType)) - { + } else if (isNullType(shapeType)) { return this.createNull(buffer); } @@ -1349,8 +1232,7 @@ else if (isNullType(shapeType)) * * @return a new point {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord}. */ - protected ShapefileRecord createNull(ByteBuffer buffer) - { + protected ShapefileRecord createNull(ByteBuffer buffer) { return new ShapefileRecordNull(this, buffer); } @@ -1364,14 +1246,12 @@ protected ShapefileRecord createNull(ByteBuffer buffer) * * @return a new point {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord}. */ - protected ShapefileRecord createPoint(ByteBuffer buffer) - { + protected ShapefileRecord createPoint(ByteBuffer buffer) { return new ShapefileRecordPoint(this, buffer); } /** - * Returns a new multi-point {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord} from the specified - * buffer. + * Returns a new multi-point {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord} from the specified buffer. *

        * The buffer current position is assumed to be set at the start of the record and will be set to the start of the * next record after this method has completed. @@ -1380,8 +1260,7 @@ protected ShapefileRecord createPoint(ByteBuffer buffer) * * @return a new point {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord}. */ - protected ShapefileRecord createMultiPoint(ByteBuffer buffer) - { + protected ShapefileRecord createMultiPoint(ByteBuffer buffer) { return new ShapefileRecordMultiPoint(this, buffer); } @@ -1395,8 +1274,7 @@ protected ShapefileRecord createMultiPoint(ByteBuffer buffer) * * @return a new point {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord}. */ - protected ShapefileRecord createPolyline(ByteBuffer buffer) - { + protected ShapefileRecord createPolyline(ByteBuffer buffer) { return new ShapefileRecordPolyline(this, buffer); } @@ -1410,8 +1288,7 @@ protected ShapefileRecord createPolyline(ByteBuffer buffer) * * @return a new point {@link gov.nasa.worldwind.formats.shapefile.ShapefileRecord}. */ - protected ShapefileRecord createPolygon(ByteBuffer buffer) - { + protected ShapefileRecord createPolygon(ByteBuffer buffer) { return new ShapefileRecordPolygon(this, buffer); } @@ -1422,16 +1299,14 @@ protected ShapefileRecord createPolygon(ByteBuffer buffer) * * @return the record's shape type. */ - protected String readRecordShapeType(ByteBuffer buffer) - { + protected String readRecordShapeType(ByteBuffer buffer) { // Read shape type - little endian buffer.order(ByteOrder.LITTLE_ENDIAN); int type = buffer.getInt(buffer.position() + 2 * 4); // skip record number and length as ints String shapeType = this.getShapeType(type); - if (shapeType == null) - { + if (shapeType == null) { // Let the caller catch and log the exception. throw new WWRuntimeException(Logging.getMessage("SHP.UnsupportedShapeType", type)); } @@ -1446,11 +1321,9 @@ protected String readRecordShapeType(ByteBuffer buffer) * * @return the mapped shape type. */ - protected String getShapeType(int type) - { + protected String getShapeType(int type) { // Cases commented out indicate shape types not implemented - switch (type) - { + switch (type) { case 0: return SHAPE_NULL; case 1: @@ -1482,7 +1355,6 @@ protected String getShapeType(int type) // case 31: // return SHAPE_MULTI_PATCH; - default: return null; // unsupported shape type } @@ -1491,45 +1363,38 @@ protected String getShapeType(int type) //**************************************************************// //******************** Point Data ****************************// //**************************************************************// - /** * Add point coordinates to the Shapefile starting at the buffer's positions and ending at the specified number of * points, and returns an address to the point coordinates in the Shapefile's backing point buffer. Points are read * as (X,Y) pairs of 64-bit floating point numbers. This throws an exception if the JVM cannot allocate enough * memory to hold the Shapefile's backing point buffer. * - * @param record the record associated with the point coordinates, may be null. - * @param buffer the buffer to read points from. + * @param record the record associated with the point coordinates, may be null. + * @param buffer the buffer to read points from. * @param numPoints the number of (X,Y) pairs to read. * * @return the point's address in the Shapefile's backing point buffer. */ - protected int addPoints(ShapefileRecord record, ByteBuffer buffer, int numPoints) - { + protected int addPoints(ShapefileRecord record, ByteBuffer buffer, int numPoints) { DoubleBuffer pointBuffer; // Read the point data, keeping track of the start and end of the point data. int pos = buffer.position(); int limit = buffer.position() + 2 * WWBufferUtil.SIZEOF_DOUBLE * numPoints; - try - { + try { // Set the buffer's limit to include the number of bytes required to hold 2 double precision values for each // point, then read the point data between the buffer's current position and limit. buffer.limit(limit); pointBuffer = this.readPoints(record, buffer); - } - finally - { + } finally { // Restore the buffer's limit to its original value, and set its position at the end of the point data. buffer.clear(); buffer.position(limit); } // Add the point data to the Shapefile's internal point buffer. - if (this.mappedShpBuffer != null) - { - if (this.pointBuffer == null) - { + if (this.mappedShpBuffer != null) { + if (this.pointBuffer == null) { // Create a VecBufferBlocks to hold this Shapefile's point data. Shapefile points are 2-tuples stored in // IEEE 64-bit floating point format, in little endian byte order. ByteBuffer buf = this.mappedShpBuffer.duplicate(); @@ -1540,29 +1405,23 @@ protected int addPoints(ShapefileRecord record, ByteBuffer buffer, int numPoints // Add the point's byte range to the VecBufferBlocks. return ((VecBufferBlocks) this.pointBuffer).addBlock(pos, limit - 1); - } - else - { - if (this.pointBuffer == null) - { + } else { + if (this.pointBuffer == null) { // Create a CompoundVecBuffer to hold this Shapefile's point data. int totalPointsEstimate = this.computeNumberOfPointsEstimate(); DoubleBuffer doubleBuffer; - try - { + try { doubleBuffer = Buffers.newDirectDoubleBuffer(2 * totalPointsEstimate); - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { // Let the caller catch and log the exception. If we cannot allocate enough memory to hold the // point buffer, we throw an exception indicating that the read operation should be terminated. throw new WWRuntimeException(Logging.getMessage("SHP.OutOfMemoryAllocatingPointBuffer", - this.getStringValue(AVKey.DISPLAY_NAME)), e); + this.getStringValue(AVKey.DISPLAY_NAME)), e); } this.pointBuffer = new VecBufferSequence( - new VecBuffer(2, new BufferWrapper.DoubleBufferWrapper(doubleBuffer))); + new VecBuffer(2, new BufferWrapper.DoubleBufferWrapper(doubleBuffer))); } // Append the point coordinates to the VecBufferSequence. @@ -1577,8 +1436,7 @@ protected int addPoints(ShapefileRecord record, ByteBuffer buffer, int numPoints * @return a liberal estimate of the number of points in the shapefile. */ @SuppressWarnings({"StringEquality"}) - protected int computeNumberOfPointsEstimate() - { + protected int computeNumberOfPointsEstimate() { // Compute the header overhead, subtract it from the file size, then divide by point size to get the estimate. // The Parts array is not included in the overhead, so the estimate will be slightly greater than the number of // points needed if the shape is a type with a Parts array. Measure values and ranges are also not included in @@ -1588,36 +1446,36 @@ protected int computeNumberOfPointsEstimate() final int numRecords = this.getNumberOfRecords(); // Return very liberal estimate based on file size if num records unknown. - if (numRecords < 0) + if (numRecords < 0) { return (this.getLength() - HEADER_LENGTH) / 16; // num X, Y tuples that can fit in the file length - + } int overhead = HEADER_LENGTH + numRecords * 12; //12 bytes per record for record header and record shape type String shapeType = this.getShapeType(); - if (shapeType == SHAPE_POINT || shapeType == SHAPE_POINT_M) + if (shapeType == SHAPE_POINT || shapeType == SHAPE_POINT_M) { return (this.getLength() - overhead) / 16; // 16 = two doubles, X and Y - - if (shapeType == SHAPE_MULTI_POINT || shapeType == SHAPE_MULTI_POINT_M) - // Add 32 bytes per record for bounding box + 4 bytes for one int per record + } + if (shapeType == SHAPE_MULTI_POINT || shapeType == SHAPE_MULTI_POINT_M) // Add 32 bytes per record for bounding box + 4 bytes for one int per record + { return (this.getLength() - (overhead + numRecords * (32 + 4))) / 16; // 16 = two doubles, X and Y - + } if (shapeType == SHAPE_POLYLINE || shapeType == SHAPE_POLYGON - || shapeType == SHAPE_POLYLINE_M || shapeType == SHAPE_POLYGON_M) - // Add 32 bytes per record for bounding box + 8 bytes for two ints per record + || shapeType == SHAPE_POLYLINE_M || shapeType == SHAPE_POLYGON_M) // Add 32 bytes per record for bounding box + 8 bytes for two ints per record + { return (this.getLength() - (overhead + numRecords * (32 + 8))) / 16; // 16 = two doubles, X and Y - - if (shapeType == SHAPE_POINT_Z) + } + if (shapeType == SHAPE_POINT_Z) { return (this.getLength() - overhead) / 24; // 24 = three doubles, X, Y, Z - - if (shapeType == SHAPE_MULTI_POINT_Z) - // Add 48 bytes per record for bounding box + 4 bytes for one int per record + } + if (shapeType == SHAPE_MULTI_POINT_Z) // Add 48 bytes per record for bounding box + 4 bytes for one int per record + { return (this.getLength() - (overhead + numRecords * (48 + 4))) / 24; // 24 = three doubles, X, Y, Z - - if (shapeType == SHAPE_POLYLINE_Z || shapeType == SHAPE_POLYGON_Z) - // Add 48 bytes per record for bounding box + 8 bytes for two ints per record + } + if (shapeType == SHAPE_POLYLINE_Z || shapeType == SHAPE_POLYGON_Z) // Add 48 bytes per record for bounding box + 8 bytes for two ints per record + { return (this.getLength() - (overhead + numRecords * (48 + 8))) / 24; // 24 = three doubles, X, Y and Z - + } // The shape type should have been checked before calling this method, so we shouldn't reach this code. // Let the caller catch and log the exception. throw new WWRuntimeException(Logging.getMessage("SHP.UnsupportedShapeType", shapeType)); @@ -1639,24 +1497,20 @@ protected int computeNumberOfPointsEstimate() * * @throws WWRuntimeException if the Shapefile's coordinate system is unsupported. */ - protected DoubleBuffer readPoints(ShapefileRecord record, ByteBuffer buffer) - { - if (buffer == null || !buffer.hasRemaining()) + protected DoubleBuffer readPoints(ShapefileRecord record, ByteBuffer buffer) { + if (buffer == null || !buffer.hasRemaining()) { return null; + } Object o = this.getValue(AVKey.COORDINATE_SYSTEM); - if (!this.hasKey(AVKey.COORDINATE_SYSTEM)) + if (!this.hasKey(AVKey.COORDINATE_SYSTEM)) { return this.readUnspecifiedPoints(record, buffer); - - else if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(o)) + } else if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(o)) { return this.readGeographicPoints(record, buffer); - - else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) + } else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) { return this.readProjectedPoints(record, buffer); - - else - { + } else { // The Shapefile's coordinate system is unsupported. This should never happen because the coordinate system // is validated during initialization, but we check anyway. Let the caller catch and log the message. throw new WWRuntimeException(Logging.getMessage("generic.UnsupportedCoordinateSystem", o)); @@ -1673,8 +1527,7 @@ else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) * @return a buffer containing the point coordinates. */ @SuppressWarnings({"UnusedDeclaration"}) - protected DoubleBuffer readUnspecifiedPoints(ShapefileRecord record, ByteBuffer buffer) - { + protected DoubleBuffer readUnspecifiedPoints(ShapefileRecord record, ByteBuffer buffer) { // Create a view of the buffer as a doubles. return buffer.asDoubleBuffer(); } @@ -1689,14 +1542,12 @@ protected DoubleBuffer readUnspecifiedPoints(ShapefileRecord record, ByteBuffer * * @return a buffer containing the geographic point coordinates. */ - protected DoubleBuffer readGeographicPoints(ShapefileRecord record, ByteBuffer buffer) - { + protected DoubleBuffer readGeographicPoints(ShapefileRecord record, ByteBuffer buffer) { // Create a view of the buffer as a doubles. DoubleBuffer doubleBuffer = buffer.asDoubleBuffer(); // Normalize the buffer of geographic point coordinates if the record is flagged as needing normalization. - if (record != null && record.isNormalizePoints()) - { + if (record != null && record.isNormalizePoints()) { WWUtil.normalizeGeographicCoordinates(doubleBuffer); doubleBuffer.rewind(); } @@ -1718,12 +1569,10 @@ protected DoubleBuffer readGeographicPoints(ShapefileRecord record, ByteBuffer b * @throws WWRuntimeException if the Shapefile's projection is unsupported. */ @SuppressWarnings({"UnusedDeclaration"}) - protected DoubleBuffer readProjectedPoints(ShapefileRecord record, ByteBuffer buffer) - { + protected DoubleBuffer readProjectedPoints(ShapefileRecord record, ByteBuffer buffer) { Object o = this.getValue(AVKey.PROJECTION_NAME); - if (AVKey.PROJECTION_UTM.equals(o)) - { + if (AVKey.PROJECTION_UTM.equals(o)) { // The Shapefile's coordinate system is UTM. Convert the UTM coordinates to geographic. The zone and hemisphere // parameters have already been validated in validateBounds. Integer zone = (Integer) this.getValue(AVKey.PROJECTION_ZONE); @@ -1735,9 +1584,7 @@ protected DoubleBuffer readProjectedPoints(ShapefileRecord record, ByteBuffer bu doubleBuffer.rewind(); return doubleBuffer; - } - else - { + } else { // The Shapefile's coordinate system projection is unsupported. This should never happen because the // projection is validated during initialization, but we check anyway. Let the caller catch and log the // message. @@ -1748,7 +1595,6 @@ protected DoubleBuffer readProjectedPoints(ShapefileRecord record, ByteBuffer bu //**************************************************************// //******************** Bounding Rectangle ********************// //**************************************************************// - /** * Stores a bounding rectangle's coordinates, and if the coordinates are normalized. If isNormalized is * true, this indicates that the original coordinate values are out of range and required @@ -1756,39 +1602,38 @@ protected DoubleBuffer readProjectedPoints(ShapefileRecord record, ByteBuffer bu * coordinates normalized. Normalization is rarely needed, and this enables the shapefile to normalize only point * coordinates associated with records that require it. */ - protected static class BoundingRectangle - { - /** Four-element array of the bounding rectangle's coordinates, ordered as follows: (minY, maxY, minX, maxX). */ + protected static class BoundingRectangle { + + /** + * Four-element array of the bounding rectangle's coordinates, ordered as follows: (minY, maxY, minX, maxX). + */ public double[] coords; - /** True if the coordinates are normalized, and false otherwise. */ + /** + * True if the coordinates are normalized, and false otherwise. + */ public boolean isNormalized; } /** * Returns a bounding rectangle from the specified buffer. This reads four doubles and interprets them as a bounding * rectangle in the following order: (minX, minY, maxX, maxY). The returned rectangle's coordinates are interpreted - * according to the Shapefile's coordinate system. This throws a {@link gov.nasa.worldwind.exception.WWRuntimeException} - * if the coordinate system is unsupported. + * according to the Shapefile's coordinate system. This throws a + * {@link gov.nasa.worldwind.exception.WWRuntimeException} if the coordinate system is unsupported. * * @param buffer the buffer to read from. * * @return a bounding rectangle with coordinates from the specified buffer. */ - protected BoundingRectangle readBoundingRectangle(ByteBuffer buffer) - { + protected BoundingRectangle readBoundingRectangle(ByteBuffer buffer) { Object o = this.getValue(AVKey.COORDINATE_SYSTEM); - if (!this.hasKey(AVKey.COORDINATE_SYSTEM)) + if (!this.hasKey(AVKey.COORDINATE_SYSTEM)) { return this.readUnspecifiedBoundingRectangle(buffer); - - else if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(o)) + } else if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(o)) { return this.readGeographicBoundingRectangle(buffer); - - else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) + } else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) { return this.readProjectedBoundingRectangle(buffer); - - else - { + } else { // The Shapefile's coordinate system is unsupported. This should never happen because the coordinate system // is validated during initialization, but we check anyway. Let the caller catch and log the message. throw new WWRuntimeException(Logging.getMessage("generic.UnsupportedCoordinateSystem", o)); @@ -1803,10 +1648,9 @@ else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(o)) * @param buffer the buffer to read bounding rectangle coordinates from. * * @return a bounding rectangle with coordinates from the specified buffer. The rectangle's coordinates are ordered - * as follows: (minY, maxY, minX, maxX). + * as follows: (minY, maxY, minX, maxX). */ - protected BoundingRectangle readUnspecifiedBoundingRectangle(ByteBuffer buffer) - { + protected BoundingRectangle readUnspecifiedBoundingRectangle(ByteBuffer buffer) { // Read the bounding rectangle coordinates in the following order: minY, maxY, minX, maxX. BoundingRectangle rect = new BoundingRectangle(); rect.coords = this.readBoundingRectangleCoordinates(buffer); @@ -1823,44 +1667,42 @@ protected BoundingRectangle readUnspecifiedBoundingRectangle(ByteBuffer buffer) * @param buffer the buffer to read bounding rectangle coordinates from. * * @return a bounding rectangle with coordinates from the specified buffer. The rectangle's coordinates are ordered - * as follows: (minLat, maxLat, minLon, maxLon). + * as follows: (minLat, maxLat, minLon, maxLon). */ - protected BoundingRectangle readGeographicBoundingRectangle(ByteBuffer buffer) - { + protected BoundingRectangle readGeographicBoundingRectangle(ByteBuffer buffer) { // Read the bounding rectangle coordinates in the following order: minLat, maxLat, minLon, maxLon. BoundingRectangle rect = new BoundingRectangle(); rect.coords = this.readBoundingRectangleCoordinates(buffer); // The bounding rectangle's min latitude exceeds -90. Set the min latitude to -90. Correct the max latitude if // the normalized min latitude is greater than the max latitude. - if (rect.coords[0] < -90) - { + if (rect.coords[0] < -90) { double normalizedLat = Angle.normalizedLatitude(Angle.fromDegrees(rect.coords[0])).degrees; rect.coords[0] = -90; rect.isNormalized = true; - if (rect.coords[1] < normalizedLat) + if (rect.coords[1] < normalizedLat) { rect.coords[1] = normalizedLat; + } } // The bounding rectangle's max latitude exceeds +90. Set the max latitude to +90. Correct the min latitude if // the normalized max latitude is less than the min latitude. - if (rect.coords[1] > 90) - { + if (rect.coords[1] > 90) { double normalizedLat = Angle.normalizedLatitude(Angle.fromDegrees(rect.coords[1])).degrees; rect.coords[1] = 90; rect.isNormalized = true; - if (rect.coords[0] > normalizedLat) + if (rect.coords[0] > normalizedLat) { rect.coords[0] = normalizedLat; + } } // The bounding rectangle's longitudes exceed +-180, therefore the rectangle spans the international // dateline. Set the longitude bound to (-180, 180) to contain the dateline spanning rectangle. - if (rect.coords[2] < -180 || rect.coords[3] > 180) - { + if (rect.coords[2] < -180 || rect.coords[3] > 180) { rect.coords[2] = -180; rect.coords[3] = 180; rect.isNormalized = true; @@ -1879,16 +1721,14 @@ protected BoundingRectangle readGeographicBoundingRectangle(ByteBuffer buffer) * @param buffer the buffer to read bounding rectangle coordinates from. * * @return a bounding rectangle with coordinates from the specified buffer. The rectangle's coordinates are ordered - * as follows: (minLat, maxLat, minLon, maxLon). + * as follows: (minLat, maxLat, minLon, maxLon). * * @throws WWRuntimeException if the Shapefile's projection is unsupported. */ - protected BoundingRectangle readProjectedBoundingRectangle(ByteBuffer buffer) - { + protected BoundingRectangle readProjectedBoundingRectangle(ByteBuffer buffer) { Object o = this.getValue(AVKey.PROJECTION_NAME); - if (AVKey.PROJECTION_UTM.equals(o)) - { + if (AVKey.PROJECTION_UTM.equals(o)) { // Read the bounding rectangle coordinates in the following order: minEast, minNorth, maxEast, maxNorth. double[] coords = ShapefileUtils.readDoubleArray(buffer, 4); // Convert the UTM bounding rectangle to a geographic bounding rectangle. The zone and hemisphere parameters @@ -1900,9 +1740,7 @@ protected BoundingRectangle readProjectedBoundingRectangle(ByteBuffer buffer) BoundingRectangle rect = new BoundingRectangle(); rect.coords = sector.toArrayDegrees(); return rect; - } - else - { + } else { // The Shapefile's coordinate system projection is unsupported. This should never happen because the // projection is validated during initialization, but we check anyway. Let the caller catch and log the // message. @@ -1919,8 +1757,7 @@ protected BoundingRectangle readProjectedBoundingRectangle(ByteBuffer buffer) * * @return a four-element array ordered as follows: (minY, maxY, minX, maxX). */ - protected double[] readBoundingRectangleCoordinates(ByteBuffer buffer) - { + protected double[] readBoundingRectangleCoordinates(ByteBuffer buffer) { // Read the bounding rectangle coordinates in the following order: minX, minY, maxX, maxY. double minx = buffer.getDouble(); double miny = buffer.getDouble(); @@ -1928,13 +1765,12 @@ protected double[] readBoundingRectangleCoordinates(ByteBuffer buffer) double maxy = buffer.getDouble(); // Return an array with bounding rectangle coordinates in the following order: minY, maxY, minX, maxX. - return new double[] {miny, maxy, minx, maxx}; + return new double[]{miny, maxy, minx, maxx}; } //**************************************************************// //******************** Static Utilities **********************// //**************************************************************// - /** * Indicates whether a specified shape type may contain optional measure values. * @@ -1944,10 +1780,8 @@ protected double[] readBoundingRectangleCoordinates(ByteBuffer buffer) * * @throws IllegalArgumentException if shapeType is null. */ - public static boolean isMeasureType(String shapeType) - { - if (shapeType == null) - { + public static boolean isMeasureType(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1965,10 +1799,8 @@ public static boolean isMeasureType(String shapeType) * * @throws IllegalArgumentException if shapeType is null. */ - public static boolean isZType(String shapeType) - { - if (shapeType == null) - { + public static boolean isZType(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1986,10 +1818,8 @@ public static boolean isZType(String shapeType) * * @throws IllegalArgumentException if shapeType is null. */ - public static boolean isNullType(String shapeType) - { - if (shapeType == null) - { + public static boolean isNullType(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2008,17 +1838,15 @@ public static boolean isNullType(String shapeType) * * @throws IllegalArgumentException if shapeType is null. */ - public static boolean isPointType(String shapeType) - { - if (shapeType == null) - { + public static boolean isPointType(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return shapeType.equals(Shapefile.SHAPE_POINT) || shapeType.equals(Shapefile.SHAPE_POINT_Z) - || shapeType.equals(Shapefile.SHAPE_POINT_M); + || shapeType.equals(Shapefile.SHAPE_POINT_M); } /** @@ -2031,17 +1859,15 @@ public static boolean isPointType(String shapeType) * * @throws IllegalArgumentException if shapeType is null. */ - public static boolean isMultiPointType(String shapeType) - { - if (shapeType == null) - { + public static boolean isMultiPointType(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return shapeType.equals(Shapefile.SHAPE_MULTI_POINT) || shapeType.equals(Shapefile.SHAPE_MULTI_POINT_Z) - || shapeType.equals(Shapefile.SHAPE_MULTI_POINT_M); + || shapeType.equals(Shapefile.SHAPE_MULTI_POINT_M); } /** @@ -2054,17 +1880,15 @@ public static boolean isMultiPointType(String shapeType) * * @throws IllegalArgumentException if shapeType is null. */ - public static boolean isPolylineType(String shapeType) - { - if (shapeType == null) - { + public static boolean isPolylineType(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return shapeType.equals(Shapefile.SHAPE_POLYLINE) || shapeType.equals(Shapefile.SHAPE_POLYLINE_Z) - || shapeType.equals(Shapefile.SHAPE_POLYLINE_M); + || shapeType.equals(Shapefile.SHAPE_POLYLINE_M); } /** @@ -2075,109 +1899,92 @@ public static boolean isPolylineType(String shapeType) * * @return true if the shape type is a polygon type. */ - public static boolean isPolygonType(String shapeType) - { - if (shapeType == null) - { + public static boolean isPolygonType(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return shapeType.equals(Shapefile.SHAPE_POLYGON) || shapeType.equals(Shapefile.SHAPE_POLYGON_Z) - || shapeType.equals(Shapefile.SHAPE_POLYGON_M); + || shapeType.equals(Shapefile.SHAPE_POLYGON_M); } - public String isExportFormatSupported(String mimeType) - { - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) + public String isExportFormatSupported(String mimeType) { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { return FORMAT_SUPPORTED; + } return Arrays.binarySearch(SHAPE_CONTENT_TYPES, mimeType) >= 0 ? FORMAT_SUPPORTED : FORMAT_NOT_SUPPORTED; } - public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException - { - if (mimeType == null) - { + public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException { + if (mimeType == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output == null) - { + if (output == null) { String message = Logging.getMessage("nullValue.OutputBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { this.doExport(mimeType, output); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { Logging.logger().throwing(getClass().getName(), "export", e); throw new IOException(e); } } - protected void doExport(String mimeType, Object output) throws IOException, XMLStreamException - { + protected void doExport(String mimeType, Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); } - if (KMLConstants.KML_MIME_TYPE.equals(mimeType)) + if (KMLConstants.KML_MIME_TYPE.equals(mimeType)) { exportAsKML(xmlWriter); - else + } else { exportAsXML(xmlWriter); + } xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } - protected void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { xmlWriter.writeStartElement("Shapefile"); xmlWriter.writeCharacters("\n"); - while (this.hasNext()) - { - try - { + while (this.hasNext()) { + try { ShapefileRecord nr = this.nextRecord(); - if (nr == null) + if (nr == null) { continue; + } nr.exportAsXML(xmlWriter); xmlWriter.writeCharacters("\n"); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Export.Exception.ShapefileRecord"); Logging.logger().log(Level.WARNING, message, e); @@ -2188,20 +1995,16 @@ protected void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStr xmlWriter.writeEndElement(); // Shapefile } - protected void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { - while (this.hasNext()) - { - try - { + protected void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { + while (this.hasNext()) { + try { ShapefileRecord nr = this.nextRecord(); - if (nr == null) + if (nr == null) { continue; + } nr.exportAsKML(xmlWriter); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("Export.Exception.ShapefileRecord"); Logging.logger().log(Level.WARNING, message, e); @@ -2210,10 +2013,8 @@ protected void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStr } } - public void printInfo(boolean printCoordinates) - { - while (this.hasNext()) - { + public void printInfo(boolean printCoordinates) { + while (this.hasNext()) { this.nextRecord().printInfo(printCoordinates); } } diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileExtrudedPolygons.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileExtrudedPolygons.java index f28b7d5553..e1f521d524 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileExtrudedPolygons.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileExtrudedPolygons.java @@ -25,10 +25,10 @@ * @author dcollins * @version $Id: ShapefileExtrudedPolygons.java 2324 2014-09-17 20:25:35Z dcollins $ */ -public class ShapefileExtrudedPolygons extends ShapefileRenderable implements OrderedRenderable -{ - public static class Record extends ShapefileRenderable.Record - { +public class ShapefileExtrudedPolygons extends ShapefileRenderable implements OrderedRenderable { + + public static class Record extends ShapefileRenderable.Record { + // Record properties. protected Double height; // may be null // Data structures supporting drawing. @@ -36,29 +36,24 @@ public static class Record extends ShapefileRenderable.Record protected IntBuffer interiorIndices; protected IntBuffer outlineIndices; - public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefileRecord) - { + public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefileRecord) { super(shapefileRenderable, shapefileRecord); this.height = ShapefileUtils.extractHeightAttribute(shapefileRecord); // may be null } - public Double getHeight() - { + public Double getHeight() { return this.height; } - public List intersect(Line line, Terrain terrain) throws InterruptedException - { - if (line == null) - { + public List intersect(Line line, Terrain terrain) throws InterruptedException { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (terrain == null) - { + if (terrain == null) { String msg = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -71,14 +66,14 @@ public List intersect(Line line, Terrain terrain) throws Interrupt ArrayList intersections = new ArrayList(); ((ShapefileExtrudedPolygons) this.shapefileRenderable).intersectTileRecord(line, terrain, this, - intersections); + intersections); return intersections.size() > 0 ? intersections : null; } } - protected static class RecordGroup - { + protected static class RecordGroup { + // Record group properties. public final ShapeAttributes attributes; public ArrayList records = new ArrayList(); @@ -88,14 +83,13 @@ protected static class RecordGroup public Range outlineIndexRange = new Range(0, 0); public Object vboKey = new Object(); - public RecordGroup(ShapeAttributes attributes) - { + public RecordGroup(ShapeAttributes attributes) { this.attributes = attributes; } } - protected static class Tile - { + protected static class Tile { + // Tile properties. public final Sector sector; public final int level; @@ -108,69 +102,60 @@ protected static class Tile public ShapeData currentData; public IntersectionData intersectionData = new IntersectionData(); - public Tile(Sector sector, int level) - { + public Tile(Sector sector, int level) { this.sector = sector; this.level = level; } } - protected static class ShapeData extends ShapeDataCache.ShapeDataCacheEntry - { + protected static class ShapeData extends ShapeDataCache.ShapeDataCacheEntry { + public FloatBuffer vertices; public Vec4 referencePoint; public Matrix transformMatrix; public Object vboKey = new Object(); public boolean vboExpired; - public ShapeData(DrawContext dc, long minExpiryTime, long maxExpiryTime) - { + public ShapeData(DrawContext dc, long minExpiryTime, long maxExpiryTime) { super(dc, minExpiryTime, maxExpiryTime); } } - protected static class IntersectionData extends ShapeData - { + protected static class IntersectionData extends ShapeData { + protected Terrain terrain; protected boolean tessellationValid; - public IntersectionData() - { + public IntersectionData() { super(null, 0, 0); } - public boolean isValid(Terrain terrain) - { + public boolean isValid(Terrain terrain) { return this.terrain == terrain - && this.verticalExaggeration == terrain.getVerticalExaggeration() - && (this.globeStateKey != null && globeStateKey.equals(terrain.getGlobe().getGlobeStateKey())); + && this.verticalExaggeration == terrain.getVerticalExaggeration() + && (this.globeStateKey != null && globeStateKey.equals(terrain.getGlobe().getGlobeStateKey())); } - public void invalidate() - { + public void invalidate() { this.terrain = null; this.verticalExaggeration = 1; this.globeStateKey = null; this.tessellationValid = false; } - public Terrain getTerrain() - { + public Terrain getTerrain() { return this.terrain; } - public void setTerrain(Terrain terrain) - { + public void setTerrain(Terrain terrain) { this.terrain = terrain; } - public boolean isTessellationValid() - { + public boolean isTessellationValid() { return this.tessellationValid; } - public void setTessellationValid(boolean valid) - { + public void setTessellationValid(boolean valid) { this.tessellationValid = valid; } } @@ -206,10 +191,8 @@ public void setTessellationValid(boolean valid) * * @throws IllegalArgumentException if the shapefile is null. */ - public ShapefileExtrudedPolygons(Shapefile shapefile) - { - if (shapefile == null) - { + public ShapefileExtrudedPolygons(Shapefile shapefile) { + if (shapefile == null) { String msg = Logging.getMessage("nullValue.ShapefileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -225,21 +208,19 @@ public ShapefileExtrudedPolygons(Shapefile shapefile) * delegate enables callbacks during creation of each ShapefileRenderable.Record. See {@link AttributeDelegate} for * more information. * - * @param shapefile The shapefile to display. - * @param normalAttrs The normal attributes for each ShapefileRenderable.Record. May be null to use the - * default attributes. - * @param highlightAttrs The highlight attributes for each ShapefileRenderable.Record. May be null to use the - * default highlight attributes. + * @param shapefile The shapefile to display. + * @param normalAttrs The normal attributes for each ShapefileRenderable.Record. May be null to use the default + * attributes. + * @param highlightAttrs The highlight attributes for each ShapefileRenderable.Record. May be null to use the + * default highlight attributes. * @param attributeDelegate Optional callback for configuring each ShapefileRenderable.Record's shape attributes and - * key-value attributes. May be null. + * key-value attributes. May be null. * * @throws IllegalArgumentException if the shapefile is null. */ public ShapefileExtrudedPolygons(Shapefile shapefile, ShapeAttributes normalAttrs, ShapeAttributes highlightAttrs, - ShapefileRenderable.AttributeDelegate attributeDelegate) - { - if (shapefile == null) - { + ShapefileRenderable.AttributeDelegate attributeDelegate) { + if (shapefile == null) { String msg = Logging.getMessage("nullValue.ShapefileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -249,14 +230,12 @@ public ShapefileExtrudedPolygons(Shapefile shapefile, ShapeAttributes normalAttr } @Override - protected void assembleRecords(Shapefile shapefile) - { + protected void assembleRecords(Shapefile shapefile) { this.rootTile = new Tile(this.sector, 0); super.assembleRecords(shapefile); - if (this.mustSplitTile(this.rootTile)) - { + if (this.mustSplitTile(this.rootTile)) { this.splitTile(this.rootTile); } @@ -264,21 +243,18 @@ protected void assembleRecords(Shapefile shapefile) } @Override - protected boolean mustAssembleRecord(ShapefileRecord shapefileRecord) - { + protected boolean mustAssembleRecord(ShapefileRecord shapefileRecord) { return super.mustAssembleRecord(shapefileRecord) - && (shapefileRecord.isPolylineRecord() - || shapefileRecord.isPolygonRecord()); // accept both polyline and polygon records + && (shapefileRecord.isPolylineRecord() + || shapefileRecord.isPolygonRecord()); // accept both polyline and polygon records } @Override - protected void assembleRecord(ShapefileRecord shapefileRecord) - { + protected void assembleRecord(ShapefileRecord shapefileRecord) { Record record = this.createRecord(shapefileRecord); this.addRecord(shapefileRecord, record); - if (record.height != null && this.maxHeight < record.height) - { + if (record.height != null && this.maxHeight < record.height) { this.maxHeight = record.height; } @@ -286,18 +262,15 @@ protected void assembleRecord(ShapefileRecord shapefileRecord) record.tile = this.rootTile; } - protected ShapefileExtrudedPolygons.Record createRecord(ShapefileRecord shapefileRecord) - { + protected ShapefileExtrudedPolygons.Record createRecord(ShapefileRecord shapefileRecord) { return new ShapefileExtrudedPolygons.Record(this, shapefileRecord); } - protected boolean mustSplitTile(Tile tile) - { + protected boolean mustSplitTile(Tile tile) { return tile.level < this.tileMaxLevel && tile.records.size() > this.tileMaxCapacity; } - protected void splitTile(Tile tile) - { + protected void splitTile(Tile tile) { // Create four child tiles by subdividing the tile's sector in latitude and longitude. Sector[] childSectors = tile.sector.subdivide(); tile.children = new Tile[4]; @@ -310,13 +283,10 @@ protected void splitTile(Tile tile) // include records that are marked as not visible, as recomputing the tile tree for record visibility changes // would be expensive. Iterator iterator = tile.records.iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Record record = iterator.next(); - for (int i = 0; i < 4; i++) - { - if (tile.children[i].sector.contains(record.sector)) - { + for (int i = 0; i < 4; i++) { + if (tile.children[i].sector.contains(record.sector)) { tile.children[i].records.add(record); // add it to the child record.tile = tile.children[i]; // assign the record's tile iterator.remove(); // remove it from the parent @@ -328,10 +298,8 @@ protected void splitTile(Tile tile) // Recursively split child tiles as necessary, moving their records into each child's descendants. The recursive // split stops when a child tile reaches a maximum level, or when the number of records contained within the // tile is small enough. - for (int i = 0; i < 4; i++) - { - if (this.mustSplitTile(tile.children[i])) - { + for (int i = 0; i < 4; i++) { + if (this.mustSplitTile(tile.children[i])) { this.splitTile(tile.children[i]); } @@ -340,8 +308,7 @@ protected void splitTile(Tile tile) } @Override - protected void recordDidChange(ShapefileRenderable.Record record) - { + protected void recordDidChange(ShapefileRenderable.Record record) { Tile tile = ((ShapefileExtrudedPolygons.Record) record).tile; if (tile != null) // tile is null when attributes are specified during construction { @@ -349,77 +316,74 @@ protected void recordDidChange(ShapefileRenderable.Record record) } } - public double getDefaultHeight() - { + public double getDefaultHeight() { return this.defaultHeight; } - public void setDefaultHeight(double defaultHeight) - { + public void setDefaultHeight(double defaultHeight) { this.defaultHeight = defaultHeight; this.invalidateAllTileGeometry(); } - public double getDefaultBaseDepth() - { + public double getDefaultBaseDepth() { return this.defaultBaseDepth; } - public void setDefaultBaseDepth(double defaultBaseDepth) - { + public void setDefaultBaseDepth(double defaultBaseDepth) { this.defaultBaseDepth = defaultBaseDepth; this.invalidateAllTileGeometry(); } @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return 0; } @Override - public void pick(DrawContext dc, Point pickPoint) - { - if (dc == null) - { + public void pick(DrawContext dc, Point pickPoint) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.visible) + if (!this.visible) { return; + } if (this.rootTile == null) // Shapefile is empty or contains only null records. + { return; + } this.pickOrderedSurfaceRenderable(dc, pickPoint); // pick is called during ordered rendering } @Override - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.visible) + if (!this.visible) { return; + } if (this.rootTile == null) // Shapefile is empty or contains only null records. + { return; + } - if (dc.isOrderedRenderingMode()) + if (dc.isOrderedRenderingMode()) { this.drawOrderedSurfaceRenderable(dc); - else + } else { this.makeOrderedSurfaceRenderable(dc); + } } - protected void makeOrderedSurfaceRenderable(DrawContext dc) - { + protected void makeOrderedSurfaceRenderable(DrawContext dc) { this.assembleTiles(dc); // performs a visibility test against the top level tile if (this.currentTiles.isEmpty()) // don't add an ordered renderable when there's nothing to draw @@ -431,18 +395,15 @@ protected void makeOrderedSurfaceRenderable(DrawContext dc) dc.addOrderedSurfaceRenderable(this); } - protected void assembleTiles(DrawContext dc) - { + protected void assembleTiles(DrawContext dc) { this.currentTiles.clear(); this.addTileOrDescendants(dc, this.rootTile); } - protected void addTileOrDescendants(DrawContext dc, Tile tile) - { + protected void addTileOrDescendants(DrawContext dc, Tile tile) { // Get or create the tile's current shape data, which holds the rendered geometry for the current draw context. tile.currentData = (ShapeData) tile.dataCache.getEntry(dc.getGlobe()); - if (tile.currentData == null) - { + if (tile.currentData == null) { tile.currentData = new ShapeData(dc, 3000, 9000); tile.dataCache.addEntry(tile.currentData); } @@ -450,23 +411,19 @@ protected void addTileOrDescendants(DrawContext dc, Tile tile) // Determine whether or not the tile is visible. If the tile is not visible, then neither are the tile's records // or the tile's children. Note that a tile with no records may have children, so we can't use the tile's record // count as a determination of whether or not to test its children. - if (!this.isTileVisible(dc, tile)) - { + if (!this.isTileVisible(dc, tile)) { return; } // Add the tile to the list of tiles to draw, regenerating the tile's geometry and the tile's attribute groups // as necessary. - if (tile.records.size() > 0) - { + if (tile.records.size() > 0) { this.adjustTileExpiration(dc, tile); // reduce the remaining expiration time as the eye distance decreases - if (this.mustRegenerateTileGeometry(dc, tile)) - { + if (this.mustRegenerateTileGeometry(dc, tile)) { this.regenerateTileGeometry(dc, tile); } - if (this.mustAssembleTileAttributeGroups(tile)) - { + if (this.mustAssembleTileAttributeGroups(tile)) { this.assembleTileAttributeGroups(tile); } @@ -474,50 +431,41 @@ protected void addTileOrDescendants(DrawContext dc, Tile tile) } // Process the tile's children, if any. - if (tile.children != null) - { - for (Tile childTile : tile.children) - { + if (tile.children != null) { + for (Tile childTile : tile.children) { this.addTileOrDescendants(dc, childTile); } } } - protected boolean isTileVisible(DrawContext dc, Tile tile) - { + protected boolean isTileVisible(DrawContext dc, Tile tile) { Extent extent = this.makeTileExtent(dc.getTerrain(), tile); - if (dc.isSmall(extent, 1)) - { + if (dc.isSmall(extent, 1)) { return false; } - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(extent); } return dc.getView().getFrustumInModelCoordinates().intersects(extent); } - protected boolean mustRegenerateTileGeometry(DrawContext dc, Tile tile) - { + protected boolean mustRegenerateTileGeometry(DrawContext dc, Tile tile) { return tile.currentData.isExpired(dc) || !tile.currentData.isValid(dc); } - protected void adjustTileExpiration(DrawContext dc, Tile tile) - { + protected void adjustTileExpiration(DrawContext dc, Tile tile) { // If the new eye distance is significantly closer than cached data's the current eye distance, reduce the // timer's remaining time by 50%. This reduction is performed only once each time the timer is reset. - if (tile.currentData.referencePoint != null) - { + if (tile.currentData.referencePoint != null) { double newEyeDistance = dc.getView().getEyePoint().distanceTo3(tile.currentData.referencePoint); tile.currentData.adjustTimer(dc, newEyeDistance); } } - protected void invalidateTileGeometry(Tile tile) - { + protected void invalidateTileGeometry(Tile tile) { tile.dataCache.setAllExpired(true); // force the tile vertices to be regenerated synchronized (tile) // synchronize access to tile intersection data @@ -526,31 +474,26 @@ protected void invalidateTileGeometry(Tile tile) } } - protected void invalidateAllTileGeometry() - { + protected void invalidateAllTileGeometry() { Queue tileQueue = new ArrayDeque(); tileQueue.add(this.rootTile); - while (!tileQueue.isEmpty()) - { + while (!tileQueue.isEmpty()) { Tile tile = tileQueue.poll(); this.invalidateTileGeometry(tile); - if (tile.children != null) - { + if (tile.children != null) { tileQueue.addAll(Arrays.asList(tile.children)); } } } - protected void regenerateTileGeometry(DrawContext dc, Tile tile) - { + protected void regenerateTileGeometry(DrawContext dc, Tile tile) { ShapeData shapeData = tile.currentData; // Synchronize simultaneous tile updates between rendering, intersect and Record.intersect. Access to this // instance's coordinate buffer must be synchronized. - synchronized (this) - { + synchronized (this) { this.tessellateTile(dc.getTerrain(), tile, shapeData); } @@ -560,8 +503,7 @@ protected void regenerateTileGeometry(DrawContext dc, Tile tile) shapeData.restartTimer(dc); } - protected Extent makeTileExtent(Terrain terrain, Tile tile) - { + protected Extent makeTileExtent(Terrain terrain, Tile tile) { // Compute the tile's minimum and maximum height as height above and below the extreme elevations in the tile's // sector. We use the overall maximum height of all records in order to ensure that a tile's extent includes its // descendants when the parent tile's max height is less than its descendants. @@ -572,20 +514,17 @@ protected Extent makeTileExtent(Terrain terrain, Tile tile) // Compute the tile's extent for the specified terrain. Associated the shape data's extent with the terrain in // order to determine when it becomes invalid. return Sector.computeBoundingBox(terrain.getGlobe(), terrain.getVerticalExaggeration(), tile.sector, - minHeight, maxHeight); + minHeight, maxHeight); } - protected void tessellateTile(Terrain terrain, Tile tile, ShapeData shapeData) - { + protected void tessellateTile(Terrain terrain, Tile tile, ShapeData shapeData) { // Allocate the model coordinate vertices to hold the upper and lower points for all records in the tile. The // records in the tile never changes, so the number of vertices in the tile never changes. int vertexStride = 3; FloatBuffer vertices = shapeData.vertices; - if (vertices == null) - { + if (vertices == null) { int numPoints = 0; - for (Record record : tile.records) - { + for (Record record : tile.records) { numPoints += record.numberOfPoints; } @@ -600,8 +539,7 @@ protected void tessellateTile(Terrain terrain, Tile tile, ShapeData shapeData) // are marked as not visible, as recomputing the vertices and indices for record visibility changes would be // expensive. The tessellated interior and outline indices are generated only once, since each record's indices // never change. - for (Record record : tile.records) - { + for (Record record : tile.records) { double height = record.height != null ? record.height : this.defaultHeight; double depth = this.defaultBaseDepth; double NdotR = 0; @@ -612,13 +550,11 @@ protected void tessellateTile(Terrain terrain, Tile tile, ShapeData shapeData) this.tess.setPolygonNormal(0, 0, 1); // tessellate in geographic coordinates this.tess.beginPolygon(); - for (int i = 0; i < record.getBoundaryCount(); i++) - { + for (int i = 0; i < record.getBoundaryCount(); i++) { this.tess.beginContour(); VecBuffer points = record.getBoundaryPoints(i); - for (int j = 0; j < points.getSize(); j++) - { + for (int j = 0; j < points.getSize(); j++) { points.get(j, location); Vec4 p = terrain.getSurfacePoint(Angle.fromDegrees(location[1]), Angle.fromDegrees(location[0]), 0); @@ -664,10 +600,10 @@ protected void tessellateTile(Terrain terrain, Tile tile, ShapeData shapeData) shapeData.vboExpired = true; } - protected void assembleRecordIndices(PolygonTessellator tessellator, Record record) - { - if (!tessellator.isEnabled()) + protected void assembleRecordIndices(PolygonTessellator tessellator, Record record) { + if (!tessellator.isEnabled()) { return; + } // Get the tessellated interior and boundary indices, representing a triangle tessellation and line segment // tessellation of the record's top vertices. Flip each buffer in order to limit the buffer range we use to @@ -686,8 +622,7 @@ protected void assembleRecordIndices(PolygonTessellator tessellator, Record reco // Fill the triangle index buffer with a triangle tessellation using two triangles to connect the top and bottom // vertices at each boundary line. Fill the line index buffer with a horizontal line for each boundary line // segment, and a vertical line at the first vertex of each boundary line segment. - for (int i = tessBoundary.position(); i < tessBoundary.limit(); i += 2) - { + for (int i = tessBoundary.position(); i < tessBoundary.limit(); i += 2) { int top1 = tessBoundary.get(i); int top2 = tessBoundary.get(i + 1); int bot1 = top1 + 1; // top and bottom vertices are adjacent @@ -712,18 +647,15 @@ protected void assembleRecordIndices(PolygonTessellator tessellator, Record reco record.outlineIndices = (IntBuffer) outlineIndices.rewind(); } - protected boolean mustAssembleTileAttributeGroups(Tile tile) - { + protected boolean mustAssembleTileAttributeGroups(Tile tile) { return tile.attributeGroups.isEmpty(); } - protected void invalidateTileAttributeGroups(Tile tile) - { + protected void invalidateTileAttributeGroups(Tile tile) { tile.attributeGroups.clear(); } - protected void assembleTileAttributeGroups(Tile tile) - { + protected void assembleTileAttributeGroups(Tile tile) { tile.attributeGroups.clear(); // Assemble the tile's records into groups with common attributes. Attributes are grouped by reference using an @@ -732,10 +664,11 @@ protected void assembleTileAttributeGroups(Tile tile) // may change without re-assembling these groups. However, changes to a record's visibility state, highlight // state, normal attributes reference and highlight attributes reference invalidate this grouping. Map attrMap = new IdentityHashMap(); - for (Record record : tile.records) - { + for (Record record : tile.records) { if (!record.isVisible()) // ignore records marked as not visible + { continue; + } ShapeAttributes attrs = this.determineActiveAttributes(record); RecordGroup group = attrMap.get(attrs); @@ -755,8 +688,7 @@ protected void assembleTileAttributeGroups(Tile tile) // Make the indices for each record group. We take care to make indices for both the interior and the outline, // regardless of the current state of Attributes.isDrawInterior and Attributes.isDrawOutline. This enable these // properties change state without needing to re-assemble these groups. - for (RecordGroup group : tile.attributeGroups) - { + for (RecordGroup group : tile.attributeGroups) { int indexCount = group.interiorIndexRange.length + group.outlineIndexRange.length; IntBuffer indices = Buffers.newDirectIntBuffer(indexCount); @@ -780,16 +712,13 @@ protected void assembleTileAttributeGroups(Tile tile) } } - protected void pickOrderedSurfaceRenderable(DrawContext dc, Point pickPoint) - { - try - { + protected void pickOrderedSurfaceRenderable(DrawContext dc, Point pickPoint) { + try { this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); this.beginDrawing(dc); - for (Tile tile : this.currentTiles) - { + for (Tile tile : this.currentTiles) { Color color = dc.getUniquePickColor(); dc.getGL().getGL2().glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); this.pickSupport.addPickableObject(color.getRGB(), tile); @@ -798,48 +727,38 @@ protected void pickOrderedSurfaceRenderable(DrawContext dc, Point pickPoint) // TODO: Pick rectangle support PickedObject po = this.pickSupport.getTopObject(dc, pickPoint); // resolve the picked tile, if any - if (po != null) - { + if (po != null) { this.pickSupport.clearPickList(); this.drawTileInUniqueColors(dc, (Tile) po.getObject()); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); // resolve the picked records, if any } - } - finally - { + } finally { this.endDrawing(dc); this.pickSupport.endPicking(dc); this.pickSupport.clearPickList(); } } - protected void drawOrderedSurfaceRenderable(DrawContext dc) - { - try - { + protected void drawOrderedSurfaceRenderable(DrawContext dc) { + try { this.beginDrawing(dc); - for (Tile tile : this.currentTiles) - { - if (dc.isPickingMode()) - { + for (Tile tile : this.currentTiles) { + if (dc.isPickingMode()) { Color color = dc.getUniquePickColor(); dc.getGL().getGL2().glColor3ub((byte) color.getRed(), (byte) color.getGreen(), - (byte) color.getBlue()); + (byte) color.getBlue()); this.pickSupport.addPickableObject(color.getRGB(), tile); } this.drawTile(dc, tile); } - } - finally - { + } finally { this.endDrawing(dc); } } - protected void beginDrawing(DrawContext dc) - { + protected void beginDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glEnable(GL.GL_CULL_FACE); gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); // all drawing uses vertex arrays @@ -847,8 +766,7 @@ protected void beginDrawing(DrawContext dc) gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); gl.glEnable(GL.GL_LINE_SMOOTH); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); @@ -856,8 +774,7 @@ protected void beginDrawing(DrawContext dc) } } - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glDisable(GL.GL_CULL_FACE); gl.glDisableClientState(GL2.GL_VERTEX_ARRAY); @@ -866,30 +783,26 @@ protected void endDrawing(DrawContext dc) gl.glLineWidth(1); gl.glPopMatrix(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glDisable(GL.GL_BLEND); gl.glDisable(GL.GL_LINE_SMOOTH); gl.glBlendFunc(GL.GL_ONE, GL.GL_ZERO); gl.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_DONT_CARE); } - if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) - { + if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); } } - protected void drawTile(DrawContext dc, Tile tile) - { + protected void drawTile(DrawContext dc, Tile tile) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. ShapeData shapeData = tile.currentData; int[] vboId = null; boolean useVbo = dc.getGLRuntimeCapabilities().isUseVertexBufferObject(); - if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(shapeData.vboKey)) == null) - { + if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(shapeData.vboKey)) == null) { long vboSize = 4 * shapeData.vertices.remaining(); // 4 bytes for each float vertex component vboId = new int[1]; gl.glGenBuffers(1, vboId, 0); @@ -897,19 +810,14 @@ protected void drawTile(DrawContext dc, Tile tile) gl.glBufferData(GL.GL_ARRAY_BUFFER, vboSize, shapeData.vertices, GL.GL_STATIC_DRAW); gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0); dc.getGpuResourceCache().put(shapeData.vboKey, vboId, GpuResourceCache.VBO_BUFFERS, vboSize); - } - else if (useVbo) - { + } else if (useVbo) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboId[0]); - if (shapeData.vboExpired) - { + if (shapeData.vboExpired) { gl.glBufferSubData(GL.GL_ARRAY_BUFFER, 0, 4 * shapeData.vertices.remaining(), shapeData.vertices); shapeData.vboExpired = false; } gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0); - } - else - { + } else { gl.glVertexPointer(3, GL.GL_FLOAT, 0, shapeData.vertices); } @@ -917,87 +825,70 @@ else if (useVbo) modelview.toArray(this.matrixArray, 0, false); gl.glLoadMatrixd(this.matrixArray, 0); - for (RecordGroup attrGroup : tile.attributeGroups) - { + for (RecordGroup attrGroup : tile.attributeGroups) { this.drawTileAttributeGroup(dc, attrGroup); } } - protected void drawTileAttributeGroup(DrawContext dc, RecordGroup attributeGroup) - { + protected void drawTileAttributeGroup(DrawContext dc, RecordGroup attributeGroup) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int[] vboId = null; boolean useVbo = dc.getGLRuntimeCapabilities().isUseVertexBufferObject(); - if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(attributeGroup.vboKey)) == null) - { + if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(attributeGroup.vboKey)) == null) { long vboSize = 4 * attributeGroup.indices.remaining(); // 4 bytes for each unsigned int index vboId = new int[1]; gl.glGenBuffers(1, vboId, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboId[0]); gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, vboSize, attributeGroup.indices, GL.GL_STATIC_DRAW); dc.getGpuResourceCache().put(attributeGroup.vboKey, vboId, GpuResourceCache.VBO_BUFFERS, vboSize); - } - else if (useVbo) - { + } else if (useVbo) { gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboId[0]); } - if (attributeGroup.attributes.isDrawInterior()) - { - if (!dc.isPickingMode()) - { + if (attributeGroup.attributes.isDrawInterior()) { + if (!dc.isPickingMode()) { float[] color = this.colorFloatArray; attributeGroup.attributes.getInteriorMaterial().getDiffuse().getRGBColorComponents(color); gl.glColor3f(color[0], color[1], color[2]); } - if (useVbo) - { + if (useVbo) { gl.glDrawElements(GL.GL_TRIANGLES, attributeGroup.interiorIndexRange.length, GL.GL_UNSIGNED_INT, - 4 * attributeGroup.interiorIndexRange.location); - } - else - { + 4 * attributeGroup.interiorIndexRange.location); + } else { gl.glDrawElements(GL.GL_TRIANGLES, attributeGroup.interiorIndexRange.length, GL.GL_UNSIGNED_INT, - attributeGroup.indices.position(attributeGroup.interiorIndexRange.location)); + attributeGroup.indices.position(attributeGroup.interiorIndexRange.location)); attributeGroup.indices.rewind(); } } - if (attributeGroup.attributes.isDrawOutline()) - { + if (attributeGroup.attributes.isDrawOutline()) { gl.glLineWidth((float) attributeGroup.attributes.getOutlineWidth()); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { float[] color = this.colorFloatArray; attributeGroup.attributes.getOutlineMaterial().getDiffuse().getRGBColorComponents(color); gl.glColor3f(color[0], color[1], color[2]); } - if (useVbo) - { + if (useVbo) { gl.glDrawElements(GL.GL_LINES, attributeGroup.outlineIndexRange.length, GL.GL_UNSIGNED_INT, - 4 * attributeGroup.outlineIndexRange.location); - } - else - { + 4 * attributeGroup.outlineIndexRange.location); + } else { gl.glDrawElements(GL.GL_LINES, attributeGroup.outlineIndexRange.length, GL.GL_UNSIGNED_INT, - attributeGroup.indices.position(attributeGroup.outlineIndexRange.location)); + attributeGroup.indices.position(attributeGroup.outlineIndexRange.location)); attributeGroup.indices.rewind(); } } } - protected void drawTileInUniqueColors(DrawContext dc, Tile tile) - { + protected void drawTileInUniqueColors(DrawContext dc, Tile tile) { GL2 gl = dc.getGL().getGL2(); ShapeData shapeData = tile.currentData; int pickColorsSize = shapeData.vertices.remaining(); // 1 RGB color for each XYZ vertex - if (this.pickColors == null || this.pickColors.capacity() < pickColorsSize) - { + if (this.pickColors == null || this.pickColors.capacity() < pickColorsSize) { this.pickColors = Buffers.newDirectByteBuffer(pickColorsSize); dc.getGpuResourceCache().remove(this.pickColorsVboKey); // remove any associated VBO from GPU memory } @@ -1006,29 +897,23 @@ protected void drawTileInUniqueColors(DrawContext dc, Tile tile) ByteBuffer colors; int[] vboId = null; boolean useVbo = dc.getGLRuntimeCapabilities().isUseVertexBufferObject(); - if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(this.pickColorsVboKey)) == null) - { + if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(this.pickColorsVboKey)) == null) { vboId = new int[1]; gl.glGenBuffers(1, vboId, 0); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboId[0]); gl.glBufferData(GL.GL_ARRAY_BUFFER, this.pickColors.remaining(), this.pickColors, GL2.GL_DYNAMIC_DRAW); dc.getGpuResourceCache().put(this.pickColorsVboKey, vboId, GpuResourceCache.VBO_BUFFERS, - this.pickColors.remaining()); + this.pickColors.remaining()); colors = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL.GL_WRITE_ONLY); - } - else if (useVbo) - { + } else if (useVbo) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboId[0]); colors = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL.GL_WRITE_ONLY); - } - else - { + } else { colors = pickColors; } byte[] vertexColors = this.colorByteArray; - for (Record record : tile.records) - { + for (Record record : tile.records) { // Get a unique pick color for the record, and add it to the list of pickable objects. We must generate a // color for every record, regardless of its visibility, since the tile's color array must match the // tile's vertex array, which includes invisible records. @@ -1045,32 +930,25 @@ else if (useVbo) vertexColors[5] = vertexColors[2]; // Add the unique color for the top and bottom vertices of the record. - for (int i = 0; i < record.numberOfPoints; i++) - { + for (int i = 0; i < record.numberOfPoints; i++) { colors.put(vertexColors); } } colors.flip(); - try - { + try { gl.glEnableClientState(GL2.GL_COLOR_ARRAY); - if (useVbo) - { + if (useVbo) { gl.glUnmapBuffer(GL.GL_ARRAY_BUFFER); gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, 0); - } - else - { + } else { gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, colors); } this.drawTile(dc, tile); - } - finally - { + } finally { gl.glDisableClientState(GL2.GL_COLOR_ARRAY); } } @@ -1080,27 +958,24 @@ else if (useVbo) * record's geometry is created relative to the specified terrain rather than the terrain used during rendering, * which may be at lower level of detail than required for accurate intersection determination. * - * @param line the line to intersect. + * @param line the line to intersect. * @param terrain the {@link Terrain} to use when computing each record's geometry. * * @return a list of intersections identifying where the line intersects this shapefile's records, or null if the - * line does not intersect any record. + * line does not intersect any record. * * @throws IllegalArgumentException if any argument is null. - * @throws InterruptedException if the operation is interrupted. + * @throws InterruptedException if the operation is interrupted. * @see Terrain */ - public List intersect(Line line, Terrain terrain) throws InterruptedException - { - if (line == null) - { + public List intersect(Line line, Terrain terrain) throws InterruptedException { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (terrain == null) - { + if (terrain == null) { String msg = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1112,13 +987,11 @@ public List intersect(Line line, Terrain terrain) throws Interrupt return intersections.size() > 0 ? intersections : null; } - protected void intersectTileOrDescendants(Line line, Terrain terrain, Tile tile, List results) - { + protected void intersectTileOrDescendants(Line line, Terrain terrain, Tile tile, List results) { // Regenerate the tile's intersection geometry as necessary. Synchronized simultaneous read/write access to the // tile's intersection data between calls to intersect or Record.intersect on separate threads. ShapeData shapeData; - synchronized (tile) - { + synchronized (tile) { shapeData = this.prepareTileIntersectionData(line, terrain, tile); } @@ -1130,11 +1003,9 @@ protected void intersectTileOrDescendants(Line line, Terrain terrain, Tile tile, // Intersect the line with the tile's records. Translate the line from model coordinates to tile local // coordinates in order to perform this operation once on the line, rather than many times for each tile vertex. // Intersection points are translated back into model coordinates. - if (tile.records.size() > 0) - { + if (tile.records.size() > 0) { Line localLine = new Line(line.getOrigin().subtract3(shapeData.referencePoint), line.getDirection()); - for (Record record : tile.records) - { + for (Record record : tile.records) { if (record.isVisible()) // records marked as not visible don't intersect anything { this.intersectRecordInterior(localLine, terrain, record, shapeData, results); @@ -1143,22 +1014,18 @@ protected void intersectTileOrDescendants(Line line, Terrain terrain, Tile tile, } // Intersect the line with the tile's children, if any. - if (tile.children != null) - { - for (Tile childTile : tile.children) - { + if (tile.children != null) { + for (Tile childTile : tile.children) { this.intersectTileOrDescendants(line, terrain, childTile, results); } } } - protected void intersectTileRecord(Line line, Terrain terrain, Record record, List results) - { + protected void intersectTileRecord(Line line, Terrain terrain, Record record, List results) { // Regenerate the tile's intersection geometry as necessary. Synchronized simultaneous read/write access to the // tile's intersection data between calls to intersect or Record.intersect on separate threads. ShapeData shapeData; - synchronized (record.tile) - { + synchronized (record.tile) { shapeData = this.prepareTileIntersectionData(line, terrain, record.tile); } @@ -1173,15 +1040,13 @@ protected void intersectTileRecord(Line line, Terrain terrain, Record record, Li this.intersectRecordInterior(localLine, terrain, record, shapeData, results); } - protected ShapeData prepareTileIntersectionData(Line line, Terrain terrain, Tile tile) - { + protected ShapeData prepareTileIntersectionData(Line line, Terrain terrain, Tile tile) { // Force regeneration of the tile's intersection extent and intersection geometry when the specified terrain // changes. We regenerate the extent now and flag the geometry as invalid in order to force its regeneration // later. This is necessary since we want to avoid regenerating the geometry when the line does not intersect // the tile's extent. IntersectionData shapeData = tile.intersectionData; - if (!shapeData.isValid(terrain)) - { + if (!shapeData.isValid(terrain)) { shapeData.setExtent(this.makeTileExtent(terrain, tile)); // regenerate the intersection extent shapeData.setTessellationValid(false); // force regeneration of the intersection geometry shapeData.setTerrain(terrain); @@ -1193,18 +1058,15 @@ protected ShapeData prepareTileIntersectionData(Line line, Terrain terrain, Tile // extent, then it cannot intersect the tile's records or the tile's children. Note that a tile with no records // may have children, so we can't use the tile's record count as a determination of whether or not to test its // children. - if (!shapeData.getExtent().intersects(line)) - { + if (!shapeData.getExtent().intersects(line)) { return null; } // Regenerate the tile's intersection geometry as necessary. Suppress tessellation of tiles with no records. // Synchronize simultaneous tile updates between rendering, intersect and Record.intersect. Access to this // instance's coordinate buffer must be synchronized. - if (tile.records.size() > 0 && !shapeData.isTessellationValid()) - { - synchronized (this) - { + if (tile.records.size() > 0 && !shapeData.isTessellationValid()) { + synchronized (this) { this.tessellateTile(terrain, tile, shapeData); } @@ -1215,16 +1077,13 @@ protected ShapeData prepareTileIntersectionData(Line line, Terrain terrain, Tile } protected void intersectRecordInterior(Line localLine, Terrain terrain, Record record, ShapeData shapeData, - List results) - { + List results) { FloatBuffer vertices = shapeData.vertices; IntBuffer indices = record.interiorIndices; List recordIntersections = Triangle.intersectTriangles(localLine, vertices, indices); - if (recordIntersections != null) - { - for (Intersection intersection : recordIntersections) - { + if (recordIntersections != null) { + for (Intersection intersection : recordIntersections) { // Translate the intersection point from tile local coordinates to model coordinates. Vec4 pt = intersection.getIntersectionPoint().add3(shapeData.referencePoint); intersection.setIntersectionPoint(pt); @@ -1241,4 +1100,4 @@ protected void intersectRecordInterior(Line localLine, Terrain terrain, Record r } } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileLayerFactory.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileLayerFactory.java index dd3c102501..4c59d4b04a 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileLayerFactory.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileLayerFactory.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.shapefile; import gov.nasa.worldwind.*; @@ -57,15 +56,15 @@ * @author tag * @version $Id: ShapefileLayerFactory.java 2348 2014-09-25 23:35:46Z dcollins $ */ -public class ShapefileLayerFactory implements Factory, ShapefileRenderable.AttributeDelegate -{ +public class ShapefileLayerFactory implements Factory, ShapefileRenderable.AttributeDelegate { + /** * Defines an interface for receiving notifications when shapefile parsing completes or encounters an exception. * This interface's methods are executed on a separate thread created by the factory. Implementations must * synchronize access to objects that are not thread safe. */ - public interface CompletionCallback - { + public interface CompletionCallback { + /** * Called when shapefile parsing and geometry conversion completes. Always called before the factory's thread * terminates. Executed on a separate thread created by the factory. @@ -95,8 +94,7 @@ public interface CompletionCallback * * @return The mappings. */ - public AVList getDBaseMappings() - { + public AVList getDBaseMappings() { return dBaseMappings; } @@ -108,8 +106,7 @@ public AVList getDBaseMappings() * * @param dBaseMappings The mappings. May be null, in which case no mapping occurs. */ - public void setDBaseMappings(AVList dBaseMappings) - { + public void setDBaseMappings(AVList dBaseMappings) { this.dBaseMappings = dBaseMappings; } @@ -118,8 +115,7 @@ public void setDBaseMappings(AVList dBaseMappings) * * @return The normal attributes assigned to non-point shapes. */ - public ShapeAttributes getNormalShapeAttributes() - { + public ShapeAttributes getNormalShapeAttributes() { return normalShapeAttributes; } @@ -128,8 +124,7 @@ public ShapeAttributes getNormalShapeAttributes() * * @param normalShapeAttributes The normal attributes assigned to non-point shapes. */ - public void setNormalShapeAttributes(ShapeAttributes normalShapeAttributes) - { + public void setNormalShapeAttributes(ShapeAttributes normalShapeAttributes) { this.normalShapeAttributes = normalShapeAttributes; } @@ -138,8 +133,7 @@ public void setNormalShapeAttributes(ShapeAttributes normalShapeAttributes) * * @return The highlight attributes assigned to non-point shapes. */ - public ShapeAttributes getHighlightShapeAttributes() - { + public ShapeAttributes getHighlightShapeAttributes() { return highlightShapeAttributes; } @@ -148,8 +142,7 @@ public ShapeAttributes getHighlightShapeAttributes() * * @param highlightShapeAttributes The highlight attributes assigned to non-point shapes. */ - public void setHighlightShapeAttributes(ShapeAttributes highlightShapeAttributes) - { + public void setHighlightShapeAttributes(ShapeAttributes highlightShapeAttributes) { this.highlightShapeAttributes = highlightShapeAttributes; } @@ -158,8 +151,7 @@ public void setHighlightShapeAttributes(ShapeAttributes highlightShapeAttributes * * @return The normal attributes assigned to point shapes. */ - public PointPlacemarkAttributes getNormalPointAttributes() - { + public PointPlacemarkAttributes getNormalPointAttributes() { return normalPointAttributes; } @@ -168,8 +160,7 @@ public PointPlacemarkAttributes getNormalPointAttributes() * * @param normalPointAttributes The normal attributes assigned to point shapes. */ - public void setNormalPointAttributes(PointPlacemarkAttributes normalPointAttributes) - { + public void setNormalPointAttributes(PointPlacemarkAttributes normalPointAttributes) { this.normalPointAttributes = normalPointAttributes; } @@ -178,8 +169,7 @@ public void setNormalPointAttributes(PointPlacemarkAttributes normalPointAttribu * * @return The highlight attributes assigned to point shapes. */ - public PointPlacemarkAttributes getHighlightPointAttributes() - { + public PointPlacemarkAttributes getHighlightPointAttributes() { return highlightPointAttributes; } @@ -188,8 +178,7 @@ public PointPlacemarkAttributes getHighlightPointAttributes() * * @param highlightPointAttributes The highlight attributes assigned to point shapes. */ - public void setHighlightPointAttributes(PointPlacemarkAttributes highlightPointAttributes) - { + public void setHighlightPointAttributes(PointPlacemarkAttributes highlightPointAttributes) { this.highlightPointAttributes = highlightPointAttributes; } @@ -198,8 +187,7 @@ public void setHighlightPointAttributes(PointPlacemarkAttributes highlightPointA * * @return The attribute delegate called for each shapefile record. */ - public ShapefileRenderable.AttributeDelegate getAttributeDelegate() - { + public ShapefileRenderable.AttributeDelegate getAttributeDelegate() { return this.attributeDelegate; } @@ -212,31 +200,29 @@ public ShapefileRenderable.AttributeDelegate getAttributeDelegate() * * @param attributeDelegate The attribute delegate to call for each shapefile record. */ - public void setAttributeDelegate(ShapefileRenderable.AttributeDelegate attributeDelegate) - { + public void setAttributeDelegate(ShapefileRenderable.AttributeDelegate attributeDelegate) { this.attributeDelegate = attributeDelegate; } /** * Applies this factory's DBase attribute mapping and default rendering attributes to the specified records. If an - * attribute delegate has been specified using {@link #setAttributeDelegate(gov.nasa.worldwind.formats.shapefile.ShapefileRenderable.AttributeDelegate)}, - * this calls the attribute delegate before exiting. + * attribute delegate has been specified using + * {@link #setAttributeDelegate(gov.nasa.worldwind.formats.shapefile.ShapefileRenderable.AttributeDelegate)}, this + * calls the attribute delegate before exiting. * - * @param shapefileRecord The shapefile record used to create the ShapefileRenderable.Record. + * @param shapefileRecord The shapefile record used to create the ShapefileRenderable.Record. * @param renderableRecord The ShapefileRenderable.Record to assign attributes for. */ @Override - public void assignAttributes(ShapefileRecord shapefileRecord, ShapefileRenderable.Record renderableRecord) - { - if (this.dBaseMappings != null) - { + public void assignAttributes(ShapefileRecord shapefileRecord, ShapefileRenderable.Record renderableRecord) { + if (this.dBaseMappings != null) { AVList mappings = this.applyMappings(shapefileRecord.getAttributes(), this.dBaseMappings); - if (mappings != null) + if (mappings != null) { renderableRecord.setValues(mappings); + } } - if (this.attributeDelegate != null) - { + if (this.attributeDelegate != null) { this.attributeDelegate.assignAttributes(shapefileRecord, renderableRecord); } } @@ -257,20 +243,18 @@ public void assignAttributes(ShapefileRecord shapefileRecord, ShapefileRenderabl * and specify a completion callback. * * @param configSource the configuration source. See above for supported types. - * @param params Key/value pairs to associate with the created layer. Values specified here override - * corresponding values specified within the configuration element. + * @param params Key/value pairs to associate with the created layer. Values specified here override corresponding + * values specified within the configuration element. * * @return a Layer, as described by the XML configuration file. * * @throws IllegalArgumentException if the configuration file name is null or an empty string. - * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is - * included as the {@link Exception#initCause(Throwable)}. + * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is + * included as the {@link Exception#initCause(Throwable)}. */ @Override - public Object createFromConfigSource(Object configSource, AVList params) - { - if (WWUtil.isEmpty(configSource)) - { + public Object createFromConfigSource(Object configSource, AVList params) { + if (WWUtil.isEmpty(configSource)) { String message = Logging.getMessage("generic.ConfigurationSourceIsInvalid", configSource); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -297,21 +281,18 @@ public Object createFromConfigSource(Object configSource, AVList params) * completion method before the separate thread terminates. * * @param configSource the configuration source. See above for supported types. - * @param params Key/value pairs to associate with the created layer. Values specified here override - * corresponding values specified within the configuration element. - * @param callback a callback to notify when shapefile parsing completes or encounters an exception. May be - * null. + * @param params Key/value pairs to associate with the created layer. Values specified here override corresponding + * values specified within the configuration element. + * @param callback a callback to notify when shapefile parsing completes or encounters an exception. May be null. * * @return a Layer, as described by the XML configuration file. * * @throws IllegalArgumentException if the configuration file name is null or an empty string. - * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is - * included as the {@link Exception#initCause(Throwable)}. + * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is + * included as the {@link Exception#initCause(Throwable)}. */ - public Object createFromConfigSource(Object configSource, AVList params, CompletionCallback callback) - { - if (WWUtil.isEmpty(configSource)) - { + public Object createFromConfigSource(Object configSource, AVList params, CompletionCallback callback) { + if (WWUtil.isEmpty(configSource)) { String message = Logging.getMessage("generic.ConfigurationSourceIsInvalid", configSource); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -319,21 +300,16 @@ public Object createFromConfigSource(Object configSource, AVList params, Complet Object o = null; - try - { - if (configSource instanceof Element) - { + try { + if (configSource instanceof Element) { o = this.doCreateFromElement((Element) configSource, params, callback); - } - else - { + } else { Document doc = WWXML.openDocument(configSource); - if (doc != null) + if (doc != null) { o = this.doCreateFromElement(doc.getDocumentElement(), params, callback); + } } - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.CreationFromConfigurationFileFailed", configSource); throw new WWRuntimeException(msg, e); } @@ -361,13 +337,11 @@ public Object createFromConfigSource(Object configSource, AVList params, Complet * @return a Layer that renders the shapefile's contents. * * @throws IllegalArgumentException if the shapefile file name is null or an empty string. - * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is - * included as the {@link Exception#initCause(Throwable)}. + * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is + * included as the {@link Exception#initCause(Throwable)}. */ - public Object createFromShapefileSource(Object shapefileSource) - { - if (WWUtil.isEmpty(shapefileSource)) - { + public Object createFromShapefileSource(Object shapefileSource) { + if (WWUtil.isEmpty(shapefileSource)) { String message = Logging.getMessage("generic.ShapefileSourceIsInvalid", shapefileSource); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -394,19 +368,16 @@ public Object createFromShapefileSource(Object shapefileSource) * factory completes execution. * * @param shapefileSource the shapefile source. See above for supported types. - * @param callback a callback to notify when shapefile parsing completes or encounters an exception. May be - * null. + * @param callback a callback to notify when shapefile parsing completes or encounters an exception. May be null. * * @return a Layer that renders the shapefile's contents. * * @throws IllegalArgumentException if the shapefile file name is null or an empty string. - * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is - * included as the {@link Exception#initCause(Throwable)}. + * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is + * included as the {@link Exception#initCause(Throwable)}. */ - public Object createFromShapefileSource(Object shapefileSource, CompletionCallback callback) - { - if (WWUtil.isEmpty(shapefileSource)) - { + public Object createFromShapefileSource(Object shapefileSource, CompletionCallback callback) { + if (WWUtil.isEmpty(shapefileSource)) { String message = Logging.getMessage("generic.ShapefileSourceIsInvalid", shapefileSource); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -414,12 +385,9 @@ public Object createFromShapefileSource(Object shapefileSource, CompletionCallba Object o; - try - { + try { o = this.doCreateFromShapefile(shapefileSource, callback); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.CreationFromShapefileSourceFailed", shapefileSource); throw new WWRuntimeException(msg, e); } @@ -433,27 +401,26 @@ public Object createFromShapefileSource(Object shapefileSource, CompletionCallba * shape attributes to assign to created shapes, and layer properties. * * @param domElement an XML element describing the layer. - * @param params any properties to apply when creating the layer. - * @param callback A callback to notify when shapefile parsing completes or encounters an exception. May be null. + * @param params any properties to apply when creating the layer. + * @param callback A callback to notify when shapefile parsing completes or encounters an exception. May be null. * * @return a Layer, as described by the specified description. * * @throws Exception if an exception occurs during creation. */ protected Object doCreateFromElement(Element domElement, AVList params, CompletionCallback callback) - throws Exception - { + throws Exception { String shapefileLocation = WWXML.getText(domElement, "ShapefileLocation"); - if (WWUtil.isEmpty(shapefileLocation)) - { + if (WWUtil.isEmpty(shapefileLocation)) { String msg = Logging.getMessage("SHP.ShapefileLocationUnspecified"); throw new WWRuntimeException(msg); } RenderableLayer layer = new RenderableLayer(); - if (params == null) + if (params == null) { params = new AVListImpl(); + } // Common layer properties. AbstractLayer.getLayerConfigParams(domElement, params); @@ -477,20 +444,24 @@ protected Object doCreateFromElement(Element domElement, AVList params, Completi this.setHighlightPointAttributes(element != null ? this.collectPointAttributes(element) : null); Double d = (Double) params.getValue(AVKey.OPACITY); - if (d != null) + if (d != null) { layer.setOpacity(d); + } d = (Double) params.getValue(AVKey.MAX_ACTIVE_ALTITUDE); - if (d != null) + if (d != null) { layer.setMaxActiveAltitude(d); + } d = (Double) params.getValue(AVKey.MIN_ACTIVE_ALTITUDE); - if (d != null) + if (d != null) { layer.setMinActiveAltitude(d); + } Boolean b = (Boolean) params.getValue(AVKey.PICK_ENABLED); - if (b != null) + if (b != null) { layer.setPickEnabled(b); + } this.createShapefileLayer(shapefileLocation, layer, callback); @@ -504,15 +475,13 @@ protected Object doCreateFromElement(Element domElement, AVList params, Completi * resource on the classpath, or a string representation of a URL * * @param shapefileSource the shapefile source. See above for supported types. - * @param callback A callback to notify when shapefile parsing completes or encounters an exception. May be - * null. + * @param callback A callback to notify when shapefile parsing completes or encounters an exception. May be null. * * @return a Layer that renders the shapefile's contents. * * @throws Exception if an exception occurs during creation. */ - protected Object doCreateFromShapefile(Object shapefileSource, CompletionCallback callback) throws Exception - { + protected Object doCreateFromShapefile(Object shapefileSource, CompletionCallback callback) throws Exception { RenderableLayer layer = new RenderableLayer(); this.createShapefileLayer(shapefileSource, layer, callback); @@ -521,69 +490,61 @@ protected Object doCreateFromShapefile(Object shapefileSource, CompletionCallbac } protected void createShapefileLayer(final Object shapefileSource, final RenderableLayer layer, - final CompletionCallback callback) - { - WorldWind.getScheduledTaskService().addTask(new Runnable() - { + final CompletionCallback callback) { + WorldWind.getScheduledTaskService().addTask(new Runnable() { @Override - public void run() - { + public void run() { Shapefile shp = null; - try - { + try { shp = loadShapefile(shapefileSource); assembleShapefileLayer(shp, layer); - } - catch (Exception e) - { - if (callback != null) + } catch (Exception e) { + if (callback != null) { callback.exception(e); - } - finally - { - if (callback != null) + } + } finally { + if (callback != null) { callback.completion(layer); + } if (shapefileSource != shp) // close the shapefile if we created it + { WWIO.closeStream(shp, shapefileSource.toString()); + } } } }); } - protected Shapefile loadShapefile(Object shapefileSource) - { + protected Shapefile loadShapefile(Object shapefileSource) { return (shapefileSource instanceof Shapefile) ? (Shapefile) shapefileSource : new Shapefile(shapefileSource); } - protected void assembleShapefileLayer(Shapefile shp, RenderableLayer layer) - { + protected void assembleShapefileLayer(Shapefile shp, RenderableLayer layer) { this.addRenderablesForShapefile(shp, layer); this.addPropertiesForShapefile(shp, layer); } - protected AVList collectDBaseMappings(Element domElement, XPath xpath) - { - try - { + protected AVList collectDBaseMappings(Element domElement, XPath xpath) { + try { Element[] elements = WWXML.getElements(domElement, "AttributeMapping", xpath); - if (elements == null || elements.length == 0) + if (elements == null || elements.length == 0) { return null; + } AVList attrMappings = new AVListImpl(); - for (Element el : elements) - { + for (Element el : elements) { String prop = xpath.evaluate("@attributeName", el); String value = xpath.evaluate("@mapToKey", el); - if (WWUtil.isEmpty(prop) || WWUtil.isEmpty(value)) + if (WWUtil.isEmpty(prop) || WWUtil.isEmpty(value)) { continue; + } attrMappings.setValue(prop, value); } return attrMappings; - } - catch (XPathExpressionException e) // should not occur, but log just if it does + } catch (XPathExpressionException e) // should not occur, but log just if it does { String message = Logging.getMessage("XML.InvalidXPathExpression", "internal expression"); Logging.logger().log(java.util.logging.Level.WARNING, message, e); @@ -591,119 +552,121 @@ protected AVList collectDBaseMappings(Element domElement, XPath xpath) } } - protected PointPlacemarkAttributes collectPointAttributes(Element attrElement) - { + protected PointPlacemarkAttributes collectPointAttributes(Element attrElement) { XPathFactory xpFactory = XPathFactory.newInstance(); XPath xpath = xpFactory.newXPath(); PointPlacemarkAttributes attributes = new PointPlacemarkAttributes(); String imageAddress = WWXML.getText(attrElement, "ImageAddress", xpath); - if (!WWUtil.isEmpty(imageAddress)) + if (!WWUtil.isEmpty(imageAddress)) { attributes.setImageAddress(imageAddress); + } Double scale = WWXML.getDouble(attrElement, "Scale", xpath); - if (scale != null) + if (scale != null) { attributes.setScale(scale); + } Color imageColor = WWXML.getColor(attrElement, "ImageColor", xpath); - if (imageColor != null) + if (imageColor != null) { attributes.setImageColor(imageColor); + } Double width = WWXML.getDouble(attrElement, "LineWidth", xpath); - if (width != null) + if (width != null) { attributes.setLineWidth(width); + } Double labelScale = WWXML.getDouble(attrElement, "LabelScale", xpath); - if (labelScale != null) + if (labelScale != null) { attributes.setLabelScale(labelScale); + } Color labelColor = WWXML.getColor(attrElement, "LabelColor", xpath); - if (labelColor != null) + if (labelColor != null) { attributes.setLabelMaterial(new Material(labelColor)); + } Color lineColor = WWXML.getColor(attrElement, "LineColor", xpath); - if (lineColor != null) + if (lineColor != null) { attributes.setLabelMaterial(new Material(lineColor)); + } Boolean tf = WWXML.getBoolean(attrElement, "UsePointAsDefaultImage", xpath); - if (tf != null) + if (tf != null) { attributes.setUsePointAsDefaultImage(tf); + } return attributes; } - protected ShapeAttributes collectShapeAttributes(Element attrElement) - { + protected ShapeAttributes collectShapeAttributes(Element attrElement) { XPathFactory xpFactory = XPathFactory.newInstance(); XPath xpath = xpFactory.newXPath(); ShapeAttributes shapeAttributes = new BasicShapeAttributes(); Boolean tf = WWXML.getBoolean(attrElement, "DrawInterior", xpath); - if (tf != null) + if (tf != null) { shapeAttributes.setDrawInterior(tf); + } tf = WWXML.getBoolean(attrElement, "DrawOutline", xpath); - if (tf != null) + if (tf != null) { shapeAttributes.setDrawOutline(tf); + } Double opacity = WWXML.getDouble(attrElement, "InteriorOpacity", xpath); - if (opacity != null) + if (opacity != null) { shapeAttributes.setInteriorOpacity(opacity); + } opacity = WWXML.getDouble(attrElement, "OutlineOpacity", xpath); - if (opacity != null) + if (opacity != null) { shapeAttributes.setOutlineOpacity(opacity); + } Double width = WWXML.getDouble(attrElement, "OutlineWidth", xpath); - if (opacity != null) + if (opacity != null) { shapeAttributes.setOutlineWidth(width); + } Color color = WWXML.getColor(attrElement, "InteriorColor", xpath); - if (color != null) + if (color != null) { shapeAttributes.setInteriorMaterial(new Material(color)); + } color = WWXML.getColor(attrElement, "OutlineColor", xpath); - if (color != null) + if (color != null) { shapeAttributes.setOutlineMaterial(new Material(color)); + } return shapeAttributes; } - protected void addRenderablesForShapefile(Shapefile shp, RenderableLayer layer) - { - if (Shapefile.isPointType(shp.getShapeType())) - { + protected void addRenderablesForShapefile(Shapefile shp, RenderableLayer layer) { + if (Shapefile.isPointType(shp.getShapeType())) { this.addRenderablesForPoints(shp, layer); - } - else if (Shapefile.isMultiPointType(shp.getShapeType())) - { + } else if (Shapefile.isMultiPointType(shp.getShapeType())) { this.addRenderablesForMultiPoints(shp, layer); - } - else if (Shapefile.isPolylineType(shp.getShapeType())) - { + } else if (Shapefile.isPolylineType(shp.getShapeType())) { this.addRenderablesForPolylines(shp, layer); - } - else if (Shapefile.isPolygonType(shp.getShapeType())) - { + } else if (Shapefile.isPolygonType(shp.getShapeType())) { this.addRenderablesForPolygons(shp, layer); - } - else - { + } else { String msg = Logging.getMessage("generic.UnrecognizedShapeType", shp.getShapeType()); throw new WWRuntimeException(msg); } } - protected void addRenderablesForPoints(Shapefile shp, RenderableLayer layer) - { - while (shp.hasNext()) - { + protected void addRenderablesForPoints(Shapefile shp, RenderableLayer layer) { + while (shp.hasNext()) { ShapefileRecord record = shp.nextRecord(); - if (!Shapefile.isPointType(record.getShapeType())) + if (!Shapefile.isPointType(record.getShapeType())) { continue; + } AVList mappings = this.applyMappings(record.getAttributes(), this.dBaseMappings); @@ -712,102 +675,93 @@ protected void addRenderablesForPoints(Shapefile shp, RenderableLayer layer) } } - protected void addRenderablesForMultiPoints(Shapefile shp, RenderableLayer layer) - { - while (shp.hasNext()) - { + protected void addRenderablesForMultiPoints(Shapefile shp, RenderableLayer layer) { + while (shp.hasNext()) { ShapefileRecord record = shp.nextRecord(); - if (!Shapefile.isMultiPointType(record.getShapeType())) + if (!Shapefile.isMultiPointType(record.getShapeType())) { continue; + } AVList mappings = this.applyMappings(record.getAttributes(), this.dBaseMappings); Iterable iterable = ((ShapefileRecordMultiPoint) record).getPoints(0); - for (double[] point : iterable) - { + for (double[] point : iterable) { layer.addRenderable( - this.createPoint(record, point[1], point[0], mappings)); + this.createPoint(record, point[1], point[0], mappings)); } } } @SuppressWarnings({"UnusedDeclaration"}) - protected Renderable createPoint(ShapefileRecord record, double latDegrees, double lonDegrees, AVList mappings) - { + protected Renderable createPoint(ShapefileRecord record, double latDegrees, double lonDegrees, AVList mappings) { PointPlacemark placemark = new PointPlacemark(Position.fromDegrees(latDegrees, lonDegrees, 0)); placemark.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - if (this.normalPointAttributes != null) + if (this.normalPointAttributes != null) { placemark.setAttributes(this.normalPointAttributes); - if (this.highlightPointAttributes != null) + } + if (this.highlightPointAttributes != null) { placemark.setHighlightAttributes(this.highlightPointAttributes); + } - if (mappings != null) + if (mappings != null) { placemark.setValues(mappings); + } return placemark; } - protected void addRenderablesForPolylines(Shapefile shp, RenderableLayer layer) - { + protected void addRenderablesForPolylines(Shapefile shp, RenderableLayer layer) { ShapefilePolylines shape = new ShapefilePolylines(shp, this.normalShapeAttributes, - this.highlightShapeAttributes, this); + this.highlightShapeAttributes, this); layer.addRenderable(shape); } - protected void addRenderablesForPolygons(Shapefile shp, RenderableLayer layer) - { - if (ShapefileUtils.hasHeightAttribute(shp)) - { + protected void addRenderablesForPolygons(Shapefile shp, RenderableLayer layer) { + if (ShapefileUtils.hasHeightAttribute(shp)) { this.addRenderablesForExtrudedPolygons(shp, layer); - } - else - { + } else { this.addRenderablesForSurfacePolygons(shp, layer); } } - protected void addRenderablesForSurfacePolygons(Shapefile shp, RenderableLayer layer) - { + protected void addRenderablesForSurfacePolygons(Shapefile shp, RenderableLayer layer) { ShapefilePolygons shape = new ShapefilePolygons(shp, this.normalShapeAttributes, - this.highlightShapeAttributes, this); + this.highlightShapeAttributes, this); layer.addRenderable(shape); } - protected void addRenderablesForExtrudedPolygons(Shapefile shp, RenderableLayer layer) - { + protected void addRenderablesForExtrudedPolygons(Shapefile shp, RenderableLayer layer) { ShapefileExtrudedPolygons shape = new ShapefileExtrudedPolygons(shp, this.normalShapeAttributes, - this.highlightShapeAttributes, this); + this.highlightShapeAttributes, this); layer.addRenderable(shape); } - protected AVList applyMappings(DBaseRecord attrRecord, AVList attrMappings) - { - if (attrRecord == null || attrMappings == null) + protected AVList applyMappings(DBaseRecord attrRecord, AVList attrMappings) { + if (attrRecord == null || attrMappings == null) { return null; + } AVList mappings = new AVListImpl(); - for (Map.Entry mapping : attrMappings.getEntries()) - { + for (Map.Entry mapping : attrMappings.getEntries()) { Object attrValue = attrRecord.getValue(mapping.getKey()); - if (attrValue != null) + if (attrValue != null) { mappings.setValue((String) mapping.getValue(), attrValue); + } } return mappings.getEntries().size() > 0 ? mappings : null; } - protected void addPropertiesForShapefile(Shapefile shp, RenderableLayer layer) - { + protected void addPropertiesForShapefile(Shapefile shp, RenderableLayer layer) { if (layer.getValue(AVKey.DISPLAY_NAME) == null) // use the shapefile's display name when the layer is unnamed { layer.setValue(AVKey.DISPLAY_NAME, shp.getValue(AVKey.DISPLAY_NAME)); } - if (shp.getBoundingRectangle() != null) - { + if (shp.getBoundingRectangle() != null) { layer.setValue(AVKey.SECTOR, Sector.fromDegrees(shp.getBoundingRectangle())); } } diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefilePolygons.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefilePolygons.java index b3574151f5..d5e7f81f73 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefilePolygons.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefilePolygons.java @@ -28,58 +28,53 @@ * @author dcollins * @version $Id: ShapefilePolygons.java 3053 2015-04-28 19:15:46Z dcollins $ */ -public class ShapefilePolygons extends ShapefileRenderable implements OrderedRenderable, PreRenderable, Combinable -{ - public static class Record extends ShapefileRenderable.Record - { +public class ShapefilePolygons extends ShapefileRenderable implements OrderedRenderable, PreRenderable, Combinable { + + public static class Record extends ShapefileRenderable.Record { + protected double[][] boundaryEffectiveArea; protected boolean[] boundaryCrossesAntimeridian; - public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefileRecord) - { + public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefileRecord) { super(shapefileRenderable, shapefileRecord); } - protected double[] getBoundaryEffectiveArea(int boundaryIndex) - { + protected double[] getBoundaryEffectiveArea(int boundaryIndex) { return this.boundaryEffectiveArea != null ? this.boundaryEffectiveArea[boundaryIndex] : null; } - protected boolean isBoundaryCrossesAntimeridian(int boundaryIndex) - { + protected boolean isBoundaryCrossesAntimeridian(int boundaryIndex) { return this.boundaryCrossesAntimeridian != null && this.boundaryCrossesAntimeridian[boundaryIndex]; } } - protected static class RecordGroup - { + protected static class RecordGroup { + protected final ShapeAttributes attributes; protected IntBuffer indices; protected Range interiorIndexRange = new Range(0, 0); protected Range outlineIndexRange = new Range(0, 0); protected ArrayList recordIndices = new ArrayList(); - public RecordGroup(ShapeAttributes attributes) - { + public RecordGroup(ShapeAttributes attributes) { this.attributes = attributes; } } - protected static class RecordIndices - { + protected static class RecordIndices { + protected final int ordinal; protected Range vertexRange = new Range(0, 0); protected IntBuffer interiorIndices; protected IntBuffer outlineIndices; - public RecordIndices(int ordinal) - { + public RecordIndices(int ordinal) { this.ordinal = ordinal; } } - protected static class ShapefileTile implements OrderedRenderable, SurfaceRenderable - { + protected static class ShapefileTile implements OrderedRenderable, SurfaceRenderable { + // Properties that define the tile. protected final ShapefileRenderable shape; protected final Sector sector; @@ -89,40 +84,33 @@ protected static class ShapefileTile implements OrderedRenderable, SurfaceRender protected ShapefileGeometry geometry; protected final Object nullGeometryStateKey = new Object(); - public ShapefileTile(ShapefileRenderable shape, Sector sector, double resolution) - { + public ShapefileTile(ShapefileRenderable shape, Sector sector, double resolution) { this.shape = shape; this.sector = sector; this.resolution = resolution; } - public ShapefileRenderable getShape() - { + public ShapefileRenderable getShape() { return this.shape; } - public Sector getSector() - { + public Sector getSector() { return this.sector; } - public double getResolution() - { + public double getResolution() { return this.resolution; } - public ShapefileGeometry getGeometry() - { + public ShapefileGeometry getGeometry() { return this.geometry; } - public void setGeometry(ShapefileGeometry geometry) - { + public void setGeometry(ShapefileGeometry geometry) { this.geometry = geometry; } - public ShapefileTile[] subdivide() - { + public ShapefileTile[] subdivide() { Sector[] sectors = this.sector.subdivide(); ShapefileTile[] tiles = new ShapefileTile[4]; tiles[0] = new ShapefileTile(this.shape, sectors[0], this.resolution / 2); @@ -134,51 +122,46 @@ public ShapefileTile[] subdivide() } @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return 0; } @Override - public List getSectors(DrawContext dc) - { + public List getSectors(DrawContext dc) { return Arrays.asList(this.sector); } @Override - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { } @Override - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { return this.geometry != null ? new ShapefileGeometryStateKey(this.geometry) : this.nullGeometryStateKey; } @Override - public void render(DrawContext dc) - { + public void render(DrawContext dc) { ((ShapefilePolygons) this.shape).render(dc, this); } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } ShapefileTile that = (ShapefileTile) o; return this.shape.equals(that.shape) - && this.sector.equals(that.sector) - && this.resolution == that.resolution; + && this.sector.equals(that.sector) + && this.resolution == that.resolution; } @Override - public int hashCode() - { + public int hashCode() { long temp = this.resolution != +0.0d ? Double.doubleToLongBits(this.resolution) : 0L; int result; result = this.shape.hashCode(); @@ -188,8 +171,8 @@ public int hashCode() } } - protected static class ShapefileGeometry implements Runnable, Cacheable, Comparable - { + protected static class ShapefileGeometry implements Runnable, Cacheable, Comparable { + // Properties that define the geometry. protected final ShapefileRenderable shape; protected final Sector sector; @@ -208,34 +191,25 @@ protected static class ShapefileGeometry implements Runnable, Cacheable, Compara protected ArrayList attributeGroups = new ArrayList(); protected long attributeStateID; - public ShapefileGeometry(ShapefileRenderable shape, Sector sector, double resolution) - { + public ShapefileGeometry(ShapefileRenderable shape, Sector sector, double resolution) { this.shape = shape; this.sector = sector; this.resolution = resolution; } @Override - public void run() - { - try - { + public void run() { + try { ((ShapefilePolygons) this.shape).tessellate(this); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhileTessellating", this.shape); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); - } - finally - { - if (this.memoryCache != null && this.memoryCacheKey != null) - { + } finally { + if (this.memoryCache != null && this.memoryCacheKey != null) { this.memoryCache.add(this.memoryCacheKey, this); } - if (this.listener != null) - { + if (this.listener != null) { this.listener.propertyChange(new PropertyChangeEvent(this, AVKey.REPAINT, null, null)); } @@ -247,34 +221,32 @@ public void run() } @Override - public long getSizeInBytes() - { + public long getSizeInBytes() { return 244 + this.sector.getSizeInBytes() + (this.vertices != null ? 4 * this.vertices.remaining() : 0); } @Override - public int compareTo(ShapefileGeometry that) - { + public int compareTo(ShapefileGeometry that) { return Double.compare(this.priority, that.priority); } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } ShapefileGeometry that = (ShapefileGeometry) o; return this.shape.equals(that.shape) - && this.sector.equals(that.sector) - && this.resolution == that.resolution; + && this.sector.equals(that.sector) + && this.resolution == that.resolution; } @Override - public int hashCode() - { + public int hashCode() { long temp = this.resolution != +0.0d ? Double.doubleToLongBits(this.resolution) : 0L; int result; result = this.shape.hashCode(); @@ -284,41 +256,39 @@ public int hashCode() } } - protected static class ShapefileGeometryStateKey - { + protected static class ShapefileGeometryStateKey { + protected final ShapefileGeometry geometry; protected final long attributeStateID; protected final ShapeAttributes[] attributeGroups; - public ShapefileGeometryStateKey(ShapefileGeometry geom) - { + public ShapefileGeometryStateKey(ShapefileGeometry geom) { this.geometry = geom; this.attributeStateID = geom.attributeStateID; this.attributeGroups = new ShapeAttributes[geom.attributeGroups.size()]; - for (int i = 0; i < this.attributeGroups.length; i++) - { + for (int i = 0; i < this.attributeGroups.length; i++) { this.attributeGroups[i] = geom.attributeGroups.get(i).attributes.copy(); } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } ShapefileGeometryStateKey that = (ShapefileGeometryStateKey) o; return this.geometry.equals(that.geometry) - && this.attributeStateID == that.attributeStateID - && Arrays.equals(this.attributeGroups, that.attributeGroups); + && this.attributeStateID == that.attributeStateID + && Arrays.equals(this.attributeGroups, that.attributeGroups); } @Override - public int hashCode() - { + public int hashCode() { int result = this.geometry.hashCode(); result = 31 * result + (int) (this.attributeStateID ^ (this.attributeStateID >>> 32)); result = 31 * result + Arrays.hashCode(this.attributeGroups); @@ -326,10 +296,8 @@ public int hashCode() } } - static - { - if (!WorldWind.getMemoryCacheSet().containsCache(ShapefileGeometry.class.getName())) - { + static { + if (!WorldWind.getMemoryCacheSet().containsCache(ShapefileGeometry.class.getName())) { long size = Configuration.getLongValue(AVKey.SHAPEFILE_GEOMETRY_CACHE_SIZE, (long) 50e6); // default 50MB MemoryCache cache = new BasicMemoryCache((long) (0.8 * size), size); cache.setName("Shapefile Geometry"); @@ -353,7 +321,7 @@ public int hashCode() protected PickSupport pickSupport = new PickSupport(); protected HashMap pickColorMap = new HashMap(); protected SurfaceObjectTileBuilder pickTileBuilder = new SurfaceObjectTileBuilder(new Dimension(512, 512), - GL2.GL_RGBA8, false, false); + GL2.GL_RGBA8, false, false); protected ByteBuffer pickColors; protected Layer layer; protected double[] matrixArray = new double[16]; @@ -370,10 +338,8 @@ public int hashCode() * * @throws IllegalArgumentException if the shapefile is null. */ - public ShapefilePolygons(Shapefile shapefile) - { - if (shapefile == null) - { + public ShapefilePolygons(Shapefile shapefile) { + if (shapefile == null) { String msg = Logging.getMessage("nullValue.ShapefileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -389,21 +355,19 @@ public ShapefilePolygons(Shapefile shapefile) * enables callbacks during creation of each ShapefileRenderable.Record. See {@link * gov.nasa.worldwind.formats.shapefile.ShapefileRenderable.AttributeDelegate} for more information. * - * @param shapefile The shapefile to display. - * @param normalAttrs The normal attributes for each ShapefileRenderable.Record. May be null to use the - * default attributes. - * @param highlightAttrs The highlight attributes for each ShapefileRenderable.Record. May be null to use the - * default highlight attributes. + * @param shapefile The shapefile to display. + * @param normalAttrs The normal attributes for each ShapefileRenderable.Record. May be null to use the default + * attributes. + * @param highlightAttrs The highlight attributes for each ShapefileRenderable.Record. May be null to use the + * default highlight attributes. * @param attributeDelegate Optional callback for configuring each ShapefileRenderable.Record's shape attributes and - * key-value attributes. May be null. + * key-value attributes. May be null. * * @throws IllegalArgumentException if the shapefile is null. */ public ShapefilePolygons(Shapefile shapefile, ShapeAttributes normalAttrs, ShapeAttributes highlightAttrs, - AttributeDelegate attributeDelegate) - { - if (shapefile == null) - { + AttributeDelegate attributeDelegate) { + if (shapefile == null) { String msg = Logging.getMessage("nullValue.ShapefileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -413,8 +377,7 @@ public ShapefilePolygons(Shapefile shapefile, ShapeAttributes normalAttrs, Shape } @Override - protected void assembleRecords(Shapefile shapefile) - { + protected void assembleRecords(Shapefile shapefile) { // Store the shapefile records in a quad tree with eight levels. This depth provides fast access to records in // regions much smaller than the shapefile's sector while avoiding a lot of overhead in building the quad tree. this.recordTree = new BasicQuadTree(8, this.sector, null); @@ -422,29 +385,25 @@ protected void assembleRecords(Shapefile shapefile) } @Override - protected boolean mustAssembleRecord(ShapefileRecord shapefileRecord) - { + protected boolean mustAssembleRecord(ShapefileRecord shapefileRecord) { return super.mustAssembleRecord(shapefileRecord) - && (shapefileRecord.isPolylineRecord() - || shapefileRecord.isPolygonRecord()); // accept both polyline and polygon records + && (shapefileRecord.isPolylineRecord() + || shapefileRecord.isPolygonRecord()); // accept both polyline and polygon records } @Override - protected void assembleRecord(ShapefileRecord shapefileRecord) - { + protected void assembleRecord(ShapefileRecord shapefileRecord) { ShapefilePolygons.Record record = this.createRecord(shapefileRecord); this.addRecord(shapefileRecord, record); this.recordTree.add(record, record.sector.asDegreesArray()); } @Override - protected void recordDidChange(ShapefileRenderable.Record record) - { + protected void recordDidChange(ShapefileRenderable.Record record) { this.recordStateID++; } - protected ShapefilePolygons.Record createRecord(ShapefileRecord shapefileRecord) - { + protected ShapefilePolygons.Record createRecord(ShapefileRecord shapefileRecord) { return new ShapefilePolygons.Record(this, shapefileRecord); } @@ -455,8 +414,7 @@ protected ShapefilePolygons.Record createRecord(ShapefileRecord shapefileRecord) * * @see #setDetailHint(double) */ - public double getDetailHint() - { + public double getDetailHint() { return this.detailHint; } @@ -475,16 +433,14 @@ public double getDetailHint() * altitude. Such scales significantly decrease performance. * * @param detailHint the degree to modify the default relationship of shape resolution to screen resolution with - * changing view altitudes. Values greater than 1 increase the resolution. Values less than zero - * decrease the resolution. The default value is 0. + * changing view altitudes. Values greater than 1 increase the resolution. Values less than zero decrease the + * resolution. The default value is 0. */ - public void setDetailHint(double detailHint) - { + public void setDetailHint(double detailHint) { this.detailHint = detailHint; } - protected double getDetailFactor() - { + protected double getDetailFactor() { return this.detailHintOrigin + this.getDetailHint(); } @@ -494,8 +450,7 @@ protected double getDetailFactor() * * @return the outline line width used during picking. */ - public int getOutlinePickWidth() - { + public int getOutlinePickWidth() { return this.outlinePickWidth; } @@ -509,10 +464,8 @@ public int getOutlinePickWidth() * * @throws IllegalArgumentException if the width is less than 0. */ - public void setOutlinePickWidth(int outlinePickWidth) - { - if (outlinePickWidth < 0) - { + public void setOutlinePickWidth(int outlinePickWidth) { + if (outlinePickWidth < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -522,51 +475,50 @@ public void setOutlinePickWidth(int outlinePickWidth) } @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return 0; // ordered surface renderables don't use eye distance } @Override - public void preRender(DrawContext dc) - { - if (dc == null) - { + public void preRender(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.visible) + if (!this.visible) { return; + } if (this.getRecordCount() == 0) // shapefile is empty or contains only null records + { return; + } Extent extent = Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), this.sector); - if (!dc.getView().getFrustumInModelCoordinates().intersects(extent)) + if (!dc.getView().getFrustumInModelCoordinates().intersects(extent)) { return; + } - if (dc.isSmall(extent, 1)) + if (dc.isSmall(extent, 1)) { return; + } this.layer = dc.getCurrentLayer(); // Assemble the tiles used for rendering, then add those tiles to the scene controller's list of renderables to // draw into the scene's shared surface tiles. this.assembleTiles(dc); - for (ShapefileTile tile : this.currentTiles) - { + for (ShapefileTile tile : this.currentTiles) { dc.addOrderedSurfaceRenderable(tile); } // Assemble the tiles used for picking, then build a set of surface object tiles containing unique colors for // each record. - if (dc.getCurrentLayer().isPickEnabled()) - { - try - { + if (dc.getCurrentLayer().isPickEnabled()) { + try { // Setup the draw context state and GL state for creating pick tiles. dc.enablePickingMode(); this.pickSupport.beginPicking(dc); @@ -574,9 +526,7 @@ public void preRender(DrawContext dc) this.assembleTiles(dc); this.pickTileBuilder.setForceTileUpdates(true); this.pickTileBuilder.buildTiles(dc, this.currentTiles); - } - finally - { + } finally { // Clear pick color map in order to use different pick colors for each globe. this.pickColorMap.clear(); // Restore the draw context state and GL state. @@ -590,37 +540,34 @@ public void preRender(DrawContext dc) } @Override - public void pick(DrawContext dc, Point pickPoint) - { - if (dc == null) - { + public void pick(DrawContext dc, Point pickPoint) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.visible) + if (!this.visible) { return; + } if (this.getRecordCount() == 0) // shapefile is empty or contains only null records + { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { this.pickSupport.beginPicking(dc); gl.glEnable(GL.GL_CULL_FACE); dc.getGeographicSurfaceTileRenderer().setUseImageTilePickColors(true); dc.getGeographicSurfaceTileRenderer().renderTiles(dc, this.pickTileBuilder.getTiles(dc)); - for (PickedObject po : this.pickTileBuilder.getPickCandidates(dc)) - { + for (PickedObject po : this.pickTileBuilder.getPickCandidates(dc)) { this.pickSupport.addPickableObject(po); // transfer picked objects captured during pre rendering } - } - finally - { + } finally { dc.getGeographicSurfaceTileRenderer().setUseImageTilePickColors(false); gl.glDisable(GL.GL_CULL_FACE); this.pickSupport.endPicking(dc); @@ -631,66 +578,62 @@ public void pick(DrawContext dc, Point pickPoint) } @Override - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.visible) + if (!this.visible) { return; + } if (this.getRecordCount() == 0) // shapefile is empty or contains only null records + { return; + } - if (dc.isPickingMode() && this.pickTileBuilder.getTileCount(dc) > 0) - { + if (dc.isPickingMode() && this.pickTileBuilder.getTileCount(dc) > 0) { dc.addOrderedSurfaceRenderable(this); // perform the pick during ordered surface rendering } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void combine(CombineContext cc) - { - if (cc == null) - { + public void combine(CombineContext cc) { + if (cc == null) { String msg = Logging.getMessage("nullValue.CombineContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (cc.isBoundingSectorMode()) + if (cc.isBoundingSectorMode()) { this.combineBounds(cc); - else + } else { this.combineContours(cc); + } } - protected void assembleTiles(DrawContext dc) - { + protected void assembleTiles(DrawContext dc) { this.currentTiles.clear(); - if (this.topLevelTiles.size() == 0) - { + if (this.topLevelTiles.size() == 0) { this.createTopLevelTiles(); } - for (ShapefileTile tile : this.topLevelTiles) - { + for (ShapefileTile tile : this.topLevelTiles) { this.currentAncestorTile = null; - if (this.isTileVisible(dc, tile)) - { + if (this.isTileVisible(dc, tile)) { this.addTileOrDescendants(dc, tile); } } } - protected void createTopLevelTiles() - { + protected void createTopLevelTiles() { Angle latDelta = Angle.fromDegrees(45); Angle lonDelta = Angle.fromDegrees(45); double resolution = latDelta.radians / 512; @@ -701,12 +644,10 @@ protected void createTopLevelTiles() int lastCol = Tile.computeColumn(lonDelta, this.sector.getMaxLongitude(), Angle.NEG180); Angle p1 = Tile.computeRowLatitude(firstRow, latDelta, Angle.NEG90); - for (int row = firstRow; row <= lastRow; row++) - { + for (int row = firstRow; row <= lastRow; row++) { Angle p2 = p1.add(latDelta); Angle t1 = Tile.computeColumnLongitude(firstCol, lonDelta, Angle.NEG180); - for (int col = firstCol; col <= lastCol; col++) - { + for (int col = firstCol; col <= lastCol; col++) { Angle t2 = t1.add(lonDelta); this.topLevelTiles.add(new ShapefileTile(this, new Sector(p1, p2, t1, t2), resolution)); t1 = t2; @@ -715,60 +656,47 @@ protected void createTopLevelTiles() } } - protected boolean isTileVisible(DrawContext dc, ShapefileTile tile) - { + protected boolean isTileVisible(DrawContext dc, ShapefileTile tile) { Extent extent = Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), tile.sector); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(extent); } return dc.getView().getFrustumInModelCoordinates().intersects(extent); } - protected void addTileOrDescendants(DrawContext dc, ShapefileTile tile) - { + protected void addTileOrDescendants(DrawContext dc, ShapefileTile tile) { ShapefileGeometry geom = this.lookupGeometry(tile); tile.setGeometry(geom); // may be null - if (this.meetsRenderCriteria(dc, tile)) - { + if (this.meetsRenderCriteria(dc, tile)) { this.addTile(dc, tile); return; } ShapefileTile previousAncestorTile = null; - try - { - if (tile.getGeometry() != null) - { + try { + if (tile.getGeometry() != null) { previousAncestorTile = this.currentAncestorTile; this.currentAncestorTile = tile; } ShapefileTile[] children = tile.subdivide(); - for (ShapefileTile child : children) - { - if (child.sector.intersects(this.sector) && this.isTileVisible(dc, child)) - { + for (ShapefileTile child : children) { + if (child.sector.intersects(this.sector) && this.isTileVisible(dc, child)) { this.addTileOrDescendants(dc, child); } } - } - finally - { - if (previousAncestorTile != null) - { + } finally { + if (previousAncestorTile != null) { this.currentAncestorTile = previousAncestorTile; } } } - protected void addTile(DrawContext dc, ShapefileTile tile) - { - if (tile.getGeometry() == null) - { + protected void addTile(DrawContext dc, ShapefileTile tile) { + if (tile.getGeometry() == null) { this.requestGeometry(dc, tile); // request the tile's geometry if (this.currentAncestorTile != null) // try to use the ancestor's geometry @@ -778,13 +706,17 @@ protected void addTile(DrawContext dc, ShapefileTile tile) } if (tile.getGeometry() == null) // no tile geometry, no ancestor geometry + { return; + } if (tile.getGeometry().vertexCount == 0) // don't use empty geometry + { return; + } if (this.mustAssembleAttributeGroups( - tile.getGeometry())) // build geometry attribute groups on the rendering thread + tile.getGeometry())) // build geometry attribute groups on the rendering thread { this.assembleAttributeGroups(tile.getGeometry()); } @@ -792,13 +724,11 @@ protected void addTile(DrawContext dc, ShapefileTile tile) this.currentTiles.add(tile); } - protected boolean meetsRenderCriteria(DrawContext dc, ShapefileTile tile) - { + protected boolean meetsRenderCriteria(DrawContext dc, ShapefileTile tile) { return !this.needToSplit(dc, tile); } - protected boolean needToSplit(DrawContext dc, ShapefileTile tile) - { + protected boolean needToSplit(DrawContext dc, ShapefileTile tile) { // Compute the resolution in meters of the specified tile. Take care to convert from the radians to meters by // multiplying by the globe's radius, not the length of a Cartesian point. Using the length of a Cartesian point // is incorrect when the globe is flat. @@ -829,13 +759,11 @@ protected boolean needToSplit(DrawContext dc, ShapefileTile tile) return resolutionMeters > scaledEyeDistanceMeters; } - protected ShapefileGeometry lookupGeometry(ShapefileTile tile) - { + protected ShapefileGeometry lookupGeometry(ShapefileTile tile) { return (ShapefileGeometry) this.cache.getObject(tile); // corresponds to the key used in requestGeometry } - protected void requestGeometry(DrawContext dc, ShapefileTile tile) - { + protected void requestGeometry(DrawContext dc, ShapefileTile tile) { Vec4 eyePoint = dc.getView().getEyePoint(); Vec4 centroid = tile.sector.computeCenterPoint(dc.getGlobe(), dc.getVerticalExaggeration()); @@ -848,13 +776,12 @@ protected void requestGeometry(DrawContext dc, ShapefileTile tile) this.requestQueue.offer(geom); } - protected void sendRequests() - { + protected void sendRequests() { Runnable request; - while ((request = this.requestQueue.poll()) != null) - { - if (WorldWind.getTaskService().isFull()) + while ((request = this.requestQueue.poll()) != null) { + if (WorldWind.getTaskService().isFull()) { break; + } WorldWind.getTaskService().addTask(request); } @@ -862,13 +789,13 @@ protected void sendRequests() this.requestQueue.clear(); // clear any remaining requests } - protected void tessellate(ShapefileGeometry geom) - { + protected void tessellate(ShapefileGeometry geom) { // Get the records intersecting the geometry's sector. The implementation of getItemsInRegion may return entries // outside the requested sector, so we cull them further in the loop below. Set intersectingRecords = this.recordTree.getItemsInRegion(geom.sector, null); - if (intersectingRecords.isEmpty()) + if (intersectingRecords.isEmpty()) { return; + } // Compute the minimum effective area for an entire record based on the geometry resolution. This suppresses // records that degenerate to one or two points. @@ -882,7 +809,7 @@ protected void tessellate(ShapefileGeometry geom) PolygonTessellator2 tess = new PolygonTessellator2(); // TODO: Consider using a ThreadLocal property. tess.setPolygonNormal(0, 0, 1); // tessellate in geographic coordinates tess.setPolygonClipCoords(geom.sector.getMinLongitude().degrees, geom.sector.getMaxLongitude().degrees, - geom.sector.getMinLatitude().degrees, geom.sector.getMaxLatitude().degrees); + geom.sector.getMinLatitude().degrees, geom.sector.getMaxLatitude().degrees); tess.setVertexStride(2); tess.setVertexOffset(-xOffset, -yOffset, 0); @@ -890,21 +817,21 @@ protected void tessellate(ShapefileGeometry geom) // and meeting the geometry's resolution criteria. This may include records that are marked as not visible, as // recomputing the vertices and indices for record visibility changes would be expensive. We exclude non visible // records later in the relative less expensive routine assembleAttributeGroups. - for (Record record : intersectingRecords) - { - if (!record.sector.intersects(geom.sector)) + for (Record record : intersectingRecords) { + if (!record.sector.intersects(geom.sector)) { continue; // the record quadtree may return entries outside the sector passed to getItemsInRegion - + } double effectiveArea = record.sector.getDeltaLatRadians() * record.sector.getDeltaLonRadians(); - if (effectiveArea < minEffectiveArea) + if (effectiveArea < minEffectiveArea) { continue; // ignore records that don't meet the resolution criteria - + } this.computeRecordMetrics(record, generalizer); this.tessellateRecord(geom, record, tess); } - if (tess.getVertexCount() == 0 || geom.recordIndices.size() == 0) + if (tess.getVertexCount() == 0 || geom.recordIndices.size() == 0) { return; + } FloatBuffer vertices = Buffers.newDirectFloatBuffer(2 * tess.getVertexCount()); tess.getVertices(vertices); @@ -914,18 +841,17 @@ protected void tessellate(ShapefileGeometry geom) geom.vertexOffset = new Vec4(xOffset, yOffset, 0); } - protected void computeRecordMetrics(Record record, PolylineGeneralizer generalizer) - { + protected void computeRecordMetrics(Record record, PolylineGeneralizer generalizer) { synchronized (record) // synchronize access to checking and computing a record's effective area { - if (record.boundaryEffectiveArea != null) + if (record.boundaryEffectiveArea != null) { return; + } record.boundaryEffectiveArea = new double[record.getBoundaryCount()][]; record.boundaryCrossesAntimeridian = new boolean[record.getBoundaryCount()]; - for (int i = 0; i < record.getBoundaryCount(); i++) - { + for (int i = 0; i < record.getBoundaryCount(); i++) { VecBuffer boundaryCoords = record.getBoundaryPoints(i); double[] coord = new double[2]; // lon, lat double[] prevCoord = new double[2]; // prevlon, prevlat @@ -933,14 +859,12 @@ protected void computeRecordMetrics(Record record, PolylineGeneralizer generaliz generalizer.reset(); generalizer.beginPolyline(); - for (int j = 0; j < boundaryCoords.getSize(); j++) - { + for (int j = 0; j < boundaryCoords.getSize(); j++) { boundaryCoords.get(j, coord); generalizer.addVertex(coord[0], coord[1], 0); // lon, lat, 0 - if (j > 0 && Math.signum(prevCoord[0]) != Math.signum(coord[0]) && - Math.abs(prevCoord[0] - coord[0]) > 180) - { + if (j > 0 && Math.signum(prevCoord[0]) != Math.signum(coord[0]) + && Math.abs(prevCoord[0] - coord[0]) > 180) { record.boundaryCrossesAntimeridian[i] = true; } @@ -955,8 +879,7 @@ protected void computeRecordMetrics(Record record, PolylineGeneralizer generaliz } } - protected void tessellateRecord(ShapefileGeometry geom, Record record, final PolygonTessellator2 tess) - { + protected void tessellateRecord(ShapefileGeometry geom, Record record, final PolygonTessellator2 tess) { // Compute the minimum effective area for a vertex based on the geometry resolution. We convert the resolution // from radians to square degrees. This ensures the units are consistent with the vertex effective area computed // by PolylineGeneralizer, which adopts the units of the source data (degrees). @@ -966,25 +889,20 @@ protected void tessellateRecord(ShapefileGeometry geom, Record record, final Pol tess.resetIndices(); // clear indices from previous records, but retain the accumulated vertices tess.beginPolygon(); - for (int i = 0; i < record.getBoundaryCount(); i++) - { - this.tessellateBoundary(record, i, minEffectiveArea, new TessBoundaryCallback() - { + for (int i = 0; i < record.getBoundaryCount(); i++) { + this.tessellateBoundary(record, i, minEffectiveArea, new TessBoundaryCallback() { @Override - public void beginBoundary() - { + public void beginBoundary() { tess.beginContour(); } @Override - public void vertex(double degreesLatitude, double degreesLongitude) - { + public void vertex(double degreesLatitude, double degreesLongitude) { tess.addVertex(degreesLongitude, degreesLatitude, 0); } @Override - public void endBoundary() - { + public void endBoundary() { tess.endContour(); } }); @@ -994,7 +912,9 @@ public void endBoundary() Range range = tess.getPolygonVertexRange(); if (range.length == 0) // this should never happen, but we check anyway + { return; + } IntBuffer interiorIndices = IntBuffer.allocate(tess.getInteriorIndexCount()); IntBuffer outlineIndices = IntBuffer.allocate(tess.getBoundaryIndexCount()); @@ -1009,13 +929,11 @@ public void endBoundary() geom.recordIndices.add(ri); } - protected boolean mustAssembleAttributeGroups(ShapefileGeometry geom) - { + protected boolean mustAssembleAttributeGroups(ShapefileGeometry geom) { return geom.attributeGroups.size() == 0 || geom.attributeStateID != this.recordStateID; } - protected void assembleAttributeGroups(ShapefileGeometry geom) - { + protected void assembleAttributeGroups(ShapefileGeometry geom) { geom.attributeGroups.clear(); geom.attributeStateID = this.recordStateID; @@ -1025,11 +943,12 @@ protected void assembleAttributeGroups(ShapefileGeometry geom) // may change without re-assembling these groups. However, changes to a record's visibility state, highlight // state, normal attributes reference and highlight attributes reference invalidate this grouping. Map attrMap = new IdentityHashMap(); - for (RecordIndices ri : geom.recordIndices) - { + for (RecordIndices ri : geom.recordIndices) { ShapefileRenderable.Record record = this.getRecord(ri.ordinal); if (!record.isVisible()) // ignore records marked as not visible + { continue; + } ShapeAttributes attrs = this.determineActiveAttributes(record); RecordGroup group = attrMap.get(attrs); @@ -1049,8 +968,7 @@ protected void assembleAttributeGroups(ShapefileGeometry geom) // Make the indices for each record group. We take care to make indices for both the interior and the outline, // regardless of the current state of Attributes.isDrawInterior and Attributes.isDrawOutline. This enable these // properties change state without needing to re-assemble these groups. - for (RecordGroup group : geom.attributeGroups) - { + for (RecordGroup group : geom.attributeGroups) { int indexCount = group.interiorIndexRange.length + group.outlineIndexRange.length; IntBuffer indices = Buffers.newDirectIntBuffer(indexCount); @@ -1074,37 +992,30 @@ protected void assembleAttributeGroups(ShapefileGeometry geom) } } - protected void render(DrawContext dc, ShapefileTile tile) - { - try - { + protected void render(DrawContext dc, ShapefileTile tile) { + try { this.beginDrawing(dc); this.draw(dc, tile); - } - finally - { + } finally { this.endDrawing(dc); } } - protected void beginDrawing(DrawContext dc) - { + protected void beginDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glDisable(GL.GL_DEPTH_TEST); gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); // all drawing uses vertex arrays gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); gl.glEnable(GL.GL_LINE_SMOOTH); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); } } - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glEnable(GL.GL_DEPTH_TEST); gl.glDisableClientState(GL2.GL_VERTEX_ARRAY); @@ -1114,22 +1025,19 @@ protected void endDrawing(DrawContext dc) gl.glPopMatrix(); Arrays.fill(this.clipPlaneArray, 0); - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { gl.glDisable(GL2.GL_CLIP_PLANE0 + i); gl.glClipPlane(GL2.GL_CLIP_PLANE0 + i, this.clipPlaneArray, 4 * i); } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glDisable(GL.GL_BLEND); gl.glDisable(GL.GL_LINE_SMOOTH); gl.glBlendFunc(GL.GL_ONE, GL.GL_ZERO); } } - protected void draw(DrawContext dc, ShapefileTile tile) - { + protected void draw(DrawContext dc, ShapefileTile tile) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. ShapefileGeometry geom = tile.getGeometry(); @@ -1142,8 +1050,7 @@ protected void draw(DrawContext dc, ShapefileTile tile) this.applyClipSector(dc, tile.sector, geom.vertexOffset); // clip rasterization to the tile's sector - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.applyPickColors(dc, geom); // setup per-vertex colors to display records in unique pick colors } @@ -1153,39 +1060,33 @@ protected void draw(DrawContext dc, ShapefileTile tile) } } - protected void applyClipSector(DrawContext dc, Sector sector, Vec4 vertexOffset) - { + protected void applyClipSector(DrawContext dc, Sector sector, Vec4 vertexOffset) { fillArray4(this.clipPlaneArray, 0, 1, 0, 0, -(sector.getMinLongitude().degrees - vertexOffset.x)); fillArray4(this.clipPlaneArray, 4, -1, 0, 0, sector.getMaxLongitude().degrees - vertexOffset.x); fillArray4(this.clipPlaneArray, 8, 0, 1, 0, -(sector.getMinLatitude().degrees - vertexOffset.y)); fillArray4(this.clipPlaneArray, 12, 0, -1, 0, sector.getMaxLatitude().degrees - vertexOffset.y); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { gl.glEnable(GL2.GL_CLIP_PLANE0 + i); gl.glClipPlane(GL2.GL_CLIP_PLANE0 + i, this.clipPlaneArray, 4 * i); } } - protected void applyPickColors(DrawContext dc, ShapefileGeometry geom) - { + protected void applyPickColors(DrawContext dc, ShapefileGeometry geom) { SurfaceTileDrawContext sdc = (SurfaceTileDrawContext) dc.getValue(AVKey.SURFACE_TILE_DRAW_CONTEXT); - if (this.pickColors == null || this.pickColors.capacity() < 3 * geom.vertexCount) - { + if (this.pickColors == null || this.pickColors.capacity() < 3 * geom.vertexCount) { this.pickColors = Buffers.newDirectByteBuffer(3 * geom.vertexCount); } this.pickColors.clear(); - for (RecordIndices ri : geom.recordIndices) - { + for (RecordIndices ri : geom.recordIndices) { // Assign each record a unique RGB color. Generate vertex colors for every record - regardless of its // visibility - since the tile's color array must match the tile's vertex array. Keep a map of record // ordinals to pick colors in order to avoid drawing records in more than one unique color. Color color = this.pickColorMap.get(ri.ordinal); - if (color == null) - { + if (color == null) { color = dc.getUniquePickColor(); this.pickColorMap.put(ri.ordinal, color); } @@ -1196,8 +1097,7 @@ protected void applyPickColors(DrawContext dc, ShapefileGeometry geom) sdc.addPickCandidate(new PickedObject(color.getRGB(), record)); // Add the unique color each vertex of the record. - for (int i = 0; i < ri.vertexRange.length; i++) - { + for (int i = 0; i < ri.vertexRange.length; i++) { this.pickColors.put((byte) color.getRed()).put((byte) color.getGreen()).put((byte) color.getBlue()); } } @@ -1207,74 +1107,63 @@ protected void applyPickColors(DrawContext dc, ShapefileGeometry geom) gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, this.pickColors.flip()); } - protected void drawAttributeGroup(DrawContext dc, RecordGroup attributeGroup) - { + protected void drawAttributeGroup(DrawContext dc, RecordGroup attributeGroup) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. ShapeAttributes attrs = attributeGroup.attributes; - if (attrs.isDrawInterior() && (dc.isPickingMode() || attrs.getInteriorOpacity() > 0)) - { - if (!dc.isPickingMode()) - { + if (attrs.isDrawInterior() && (dc.isPickingMode() || attrs.getInteriorOpacity() > 0)) { + if (!dc.isPickingMode()) { Color rgb = attrs.getInteriorMaterial().getDiffuse(); double alpha = attrs.getInteriorOpacity() * 255 + 0.5; gl.glColor4ub((byte) rgb.getRed(), (byte) rgb.getGreen(), (byte) rgb.getBlue(), (byte) alpha); } gl.glDrawElements(GL.GL_TRIANGLES, attributeGroup.interiorIndexRange.length, GL.GL_UNSIGNED_INT, - attributeGroup.indices.position(attributeGroup.interiorIndexRange.location)); + attributeGroup.indices.position(attributeGroup.interiorIndexRange.location)); attributeGroup.indices.rewind(); } - if (attrs.isDrawOutline() && (dc.isPickingMode() || attrs.getOutlineOpacity() > 0)) - { - if (!dc.isPickingMode()) - { + if (attrs.isDrawOutline() && (dc.isPickingMode() || attrs.getOutlineOpacity() > 0)) { + if (!dc.isPickingMode()) { Color rgb = attrs.getOutlineMaterial().getDiffuse(); double alpha = attrs.getOutlineOpacity() * 255 + 0.5; gl.glColor4ub((byte) rgb.getRed(), (byte) rgb.getGreen(), (byte) rgb.getBlue(), (byte) alpha); gl.glLineWidth((float) attrs.getOutlineWidth()); - } - else - { + } else { gl.glLineWidth((float) Math.max(attrs.getOutlineWidth(), this.getOutlinePickWidth())); } gl.glDrawElements(GL.GL_LINES, attributeGroup.outlineIndexRange.length, GL.GL_UNSIGNED_INT, - attributeGroup.indices.position(attributeGroup.outlineIndexRange.location)); + attributeGroup.indices.position(attributeGroup.outlineIndexRange.location)); attributeGroup.indices.rewind(); } } - protected static void fillArray4(double[] array, int offset, double x, double y, double z, double w) - { + protected static void fillArray4(double[] array, int offset, double x, double y, double z, double w) { array[0 + offset] = x; array[1 + offset] = y; array[2 + offset] = z; array[3 + offset] = w; } - protected void combineBounds(CombineContext cc) - { + protected void combineBounds(CombineContext cc) { cc.addBoundingSector(this.sector); } - protected void combineContours(CombineContext cc) - { - if (!cc.getSector().intersects(this.sector)) + protected void combineContours(CombineContext cc) { + if (!cc.getSector().intersects(this.sector)) { return; // the shapefile does not intersect the region of interest - + } this.doCombineContours(cc); } - protected void doCombineContours(CombineContext cc) - { + protected void doCombineContours(CombineContext cc) { // Get the records intersecting the context's sector. The implementation of getItemsInRegion may return entries // outside the requested sector, so we cull them further in the loop below. Set intersectingRecords = this.recordTree.getItemsInRegion(cc.getSector(), null); - if (intersectingRecords.isEmpty()) + if (intersectingRecords.isEmpty()) { return; // no records in the context's sector - + } // Compute the minimum effective area for a vertex based on the context's resolution. We convert the resolution // from radians to square degrees. This ensures the units are consistent with the vertex effective area computed // by PolylineGeneralizer, which adopts the units of the source data (degrees). @@ -1289,8 +1178,7 @@ protected void doCombineContours(CombineContext cc) // order is greater than one due to two records overlapping. GLUtessellator tess = GLU.gluNewTess(); - try - { + try { GLUtessellatorCallback cb = new GLUTessellatorSupport.RecursiveCallback(cc.getTessellator()); GLU.gluTessCallback(tess, GLU.GLU_TESS_BEGIN, cb); GLU.gluTessCallback(tess, GLU.GLU_TESS_VERTEX, cb); @@ -1301,66 +1189,56 @@ protected void doCombineContours(CombineContext cc) GLU.gluTessNormal(tess, 0, 0, 1); GLU.gluTessBeginPolygon(tess, null); - for (Record record : intersectingRecords) - { - if (!record.isVisible()) + for (Record record : intersectingRecords) { + if (!record.isVisible()) { continue; // ignore records marked as not visible - - if (!record.sector.intersects(cc.getSector())) + } + if (!record.sector.intersects(cc.getSector())) { continue; // the record quadtree may return entries outside the sector passed to getItemsInRegion - + } double effectiveArea = record.sector.getDeltaLatDegrees() * record.sector.getDeltaLonDegrees(); - if (effectiveArea < minEffectiveArea) + if (effectiveArea < minEffectiveArea) { continue; // ignore records that don't meet the resolution criteria - + } this.computeRecordMetrics(record, generalizer); this.doCombineRecord(tess, cc.getSector(), minEffectiveArea, record); } - } - finally - { + } finally { GLU.gluTessEndPolygon(tess); GLU.gluDeleteTess(tess); } } - protected void doCombineRecord(GLUtessellator tess, Sector sector, double minEffectiveArea, Record record) - { - for (int i = 0; i < record.getBoundaryCount(); i++) - { + protected void doCombineRecord(GLUtessellator tess, Sector sector, double minEffectiveArea, Record record) { + for (int i = 0; i < record.getBoundaryCount(); i++) { this.doCombineBoundary(tess, sector, minEffectiveArea, record, i); } } protected void doCombineBoundary(GLUtessellator tess, Sector sector, double minEffectiveArea, Record record, - int boundaryIndex) - { + int boundaryIndex) { final ClippingTessellator clipTess = new ClippingTessellator(tess, sector); - this.tessellateBoundary(record, boundaryIndex, minEffectiveArea, new TessBoundaryCallback() - { + this.tessellateBoundary(record, boundaryIndex, minEffectiveArea, new TessBoundaryCallback() { @Override - public void beginBoundary() - { + public void beginBoundary() { clipTess.beginContour(); } @Override - public void vertex(double degreesLatitude, double degreesLongitude) - { + public void vertex(double degreesLatitude, double degreesLongitude) { clipTess.addVertex(degreesLatitude, degreesLongitude); } @Override - public void endBoundary() - { + public void endBoundary() { clipTess.endContour(); } }); } - protected interface TessBoundaryCallback - { + protected interface TessBoundaryCallback { + void beginBoundary(); void vertex(double degreesLatitude, double degreesLongitude); @@ -1368,35 +1246,29 @@ protected interface TessBoundaryCallback void endBoundary(); } - protected void tessellateBoundary(Record record, int boundaryIndex, double minEffectiveArea, TessBoundaryCallback callback) - { + protected void tessellateBoundary(Record record, int boundaryIndex, double minEffectiveArea, TessBoundaryCallback callback) { VecBuffer boundaryCoords = record.getBoundaryPoints(boundaryIndex); double[] boundaryEffectiveArea = record.getBoundaryEffectiveArea(boundaryIndex); double[] coord = new double[2]; - if (!record.isBoundaryCrossesAntimeridian(boundaryIndex)) - { + if (!record.isBoundaryCrossesAntimeridian(boundaryIndex)) { callback.beginBoundary(); - for (int j = 0; j < boundaryCoords.getSize(); j++) - { - if (boundaryEffectiveArea[j] < minEffectiveArea) + for (int j = 0; j < boundaryCoords.getSize(); j++) { + if (boundaryEffectiveArea[j] < minEffectiveArea) { continue; // ignore vertices that don't meet the resolution criteria - + } boundaryCoords.get(j, coord); // lon, lat callback.vertex(coord[1], coord[0]); // lat, lon } callback.endBoundary(); - } - else - { + } else { // Copy the boundary locations into a list of LatLon instances in order to utilize existing code that // handles locations that cross the antimeridian. ArrayList locations = new ArrayList(); - for (int j = 0; j < boundaryCoords.getSize(); j++) - { - if (boundaryEffectiveArea[j] < minEffectiveArea) + for (int j = 0; j < boundaryCoords.getSize(); j++) { + if (boundaryEffectiveArea[j] < minEffectiveArea) { continue; // ignore vertices that don't meet the resolution criteria - + } boundaryCoords.get(j, coord); // lon, lat locations.add(LatLon.fromDegrees(coord[1], coord[0])); // lat, lon } @@ -1405,19 +1277,15 @@ protected void tessellateBoundary(Record record, int boundaryIndex, double minEf if (pole != null) // wrap the boundary around the pole and along the antimeridian { callback.beginBoundary(); - for (LatLon location : LatLon.cutLocationsAlongDateLine(locations, pole, null)) - { + for (LatLon location : LatLon.cutLocationsAlongDateLine(locations, pole, null)) { callback.vertex(location.latitude.degrees, location.longitude.degrees); } callback.endBoundary(); - } - else // tessellate on both sides of the antimeridian + } else // tessellate on both sides of the antimeridian { - for (List antimeridianLocations : LatLon.repeatLocationsAroundDateline(locations)) - { + for (List antimeridianLocations : LatLon.repeatLocationsAroundDateline(locations)) { callback.beginBoundary(); - for (LatLon location : antimeridianLocations) - { + for (LatLon location : antimeridianLocations) { callback.vertex(location.latitude.degrees, location.longitude.degrees); } callback.endBoundary(); diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefilePolylines.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefilePolylines.java index f8d20f29bf..b9c61790e8 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefilePolylines.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefilePolylines.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.shapefile; import com.jogamp.common.nio.Buffers; @@ -25,22 +24,21 @@ * @author dcollins * @version $Id: ShapefilePolylines.java 2303 2014-09-14 22:33:36Z dcollins $ */ -public class ShapefilePolylines extends ShapefileRenderable implements OrderedRenderable, PreRenderable -{ - public static class Record extends ShapefileRenderable.Record - { +public class ShapefilePolylines extends ShapefileRenderable implements OrderedRenderable, PreRenderable { + + public static class Record extends ShapefileRenderable.Record { + // Data structures supporting drawing. protected Tile tile; protected IntBuffer outlineIndices; - public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefileRecord) - { + public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefileRecord) { super(shapefileRenderable, shapefileRecord); } } - protected static class RecordGroup - { + protected static class RecordGroup { + // Record group properties. public final ShapeAttributes attributes; public ArrayList records = new ArrayList(); @@ -49,14 +47,13 @@ protected static class RecordGroup public Range outlineIndexRange = new Range(0, 0); public Object vboKey = new Object(); - public RecordGroup(ShapeAttributes attributes) - { + public RecordGroup(ShapeAttributes attributes) { this.attributes = attributes; } } - protected static class Tile implements OrderedRenderable, SurfaceRenderable - { + protected static class Tile implements OrderedRenderable, SurfaceRenderable { + // Tile properties. public ShapefileRenderable shapefileRenderable; public final Sector sector; @@ -73,78 +70,70 @@ protected static class Tile implements OrderedRenderable, SurfaceRenderable public Matrix transformMatrix; public Object vboKey = new Object(); - public Tile(ShapefileRenderable shapefileRenderable, Sector sector, int level) - { + public Tile(ShapefileRenderable shapefileRenderable, Sector sector, int level) { this.shapefileRenderable = shapefileRenderable; this.sector = sector; this.level = level; } @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return 0; // distance from eye is irrelevant for ordered surface renderables } @Override - public List getSectors(DrawContext dc) - { + public List getSectors(DrawContext dc) { return Arrays.asList(this.sector); } @Override - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { return new TileStateKey(this); } @Override - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { } @Override - public void render(DrawContext dc) - { + public void render(DrawContext dc) { ((ShapefilePolylines) this.shapefileRenderable).renderTile(dc, this); } } - protected static class TileStateKey - { + protected static class TileStateKey { + protected Tile tile; protected long attributeStateID; protected ShapeAttributes[] attributeGroups; - public TileStateKey(Tile tile) - { + public TileStateKey(Tile tile) { this.tile = tile; this.attributeStateID = tile.attributeStateID; this.attributeGroups = new ShapeAttributes[tile.attributeGroups.size()]; - for (int i = 0; i < this.attributeGroups.length; i++) - { + for (int i = 0; i < this.attributeGroups.length; i++) { this.attributeGroups[i] = tile.attributeGroups.get(i).attributes.copy(); } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } TileStateKey that = (TileStateKey) o; return this.tile.equals(that.tile) - && this.attributeStateID == that.attributeStateID - && Arrays.equals(this.attributeGroups, that.attributeGroups); + && this.attributeStateID == that.attributeStateID + && Arrays.equals(this.attributeGroups, that.attributeGroups); } @Override - public int hashCode() - { + public int hashCode() { int result = this.tile.hashCode(); result = 31 * result + (int) (this.attributeStateID ^ (this.attributeStateID >>> 32)); result = 31 * result + Arrays.hashCode(this.attributeGroups); @@ -152,7 +141,9 @@ public int hashCode() } } - /** The default outline pick width. */ + /** + * The default outline pick width. + */ protected static final int DEFAULT_OUTLINE_PICK_WIDTH = 10; // Tile quadtree structures. @@ -170,7 +161,7 @@ public int hashCode() protected Layer pickLayer; protected PickSupport pickSupport = new PickSupport(); protected SurfaceObjectTileBuilder pickTileBuilder = new SurfaceObjectTileBuilder(new Dimension(512, 512), - GL2.GL_RGBA8, false, false); + GL2.GL_RGBA8, false, false); protected ByteBuffer pickColors; protected Object pickColorsVboKey = new Object(); @@ -185,10 +176,8 @@ public int hashCode() * * @throws IllegalArgumentException if the shapefile is null. */ - public ShapefilePolylines(Shapefile shapefile) - { - if (shapefile == null) - { + public ShapefilePolylines(Shapefile shapefile) { + if (shapefile == null) { String msg = Logging.getMessage("nullValue.ShapefileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -204,21 +193,19 @@ public ShapefilePolylines(Shapefile shapefile) * enables callbacks during creation of each ShapefileRenderable.Record. See {@link * gov.nasa.worldwind.formats.shapefile.ShapefileRenderable.AttributeDelegate} for more information. * - * @param shapefile The shapefile to display. - * @param normalAttrs The normal attributes for each ShapefileRenderable.Record. May be null to use the - * default attributes. - * @param highlightAttrs The highlight attributes for each ShapefileRenderable.Record. May be null to use the - * default highlight attributes. + * @param shapefile The shapefile to display. + * @param normalAttrs The normal attributes for each ShapefileRenderable.Record. May be null to use the default + * attributes. + * @param highlightAttrs The highlight attributes for each ShapefileRenderable.Record. May be null to use the + * default highlight attributes. * @param attributeDelegate Optional callback for configuring each ShapefileRenderable.Record's shape attributes and - * key-value attributes. May be null. + * key-value attributes. May be null. * * @throws IllegalArgumentException if the shapefile is null. */ public ShapefilePolylines(Shapefile shapefile, ShapeAttributes normalAttrs, ShapeAttributes highlightAttrs, - AttributeDelegate attributeDelegate) - { - if (shapefile == null) - { + AttributeDelegate attributeDelegate) { + if (shapefile == null) { String msg = Logging.getMessage("nullValue.ShapefileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -233,8 +220,7 @@ public ShapefilePolylines(Shapefile shapefile, ShapeAttributes normalAttrs, Shap * * @return the outline line width used during picking. */ - public int getOutlinePickWidth() - { + public int getOutlinePickWidth() { return this.outlinePickWidth; } @@ -248,10 +234,8 @@ public int getOutlinePickWidth() * * @throws IllegalArgumentException if the width is less than 0. */ - public void setOutlinePickWidth(int outlinePickWidth) - { - if (outlinePickWidth < 0) - { + public void setOutlinePickWidth(int outlinePickWidth) { + if (outlinePickWidth < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -261,83 +245,76 @@ public void setOutlinePickWidth(int outlinePickWidth) } @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return 0; } @Override - public void preRender(DrawContext dc) - { - if (dc == null) - { + public void preRender(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.visible) + if (!this.visible) { return; + } if (this.getRecordCount() == 0) // Shapefile is empty or contains only null records. + { return; + } // Assemble the tiles used for rendering, then cause those tiles to be drawn into the scene controller's // composite surface object tiles. this.assembleTiles(dc); - for (Tile tile : this.currentTiles) - { + for (Tile tile : this.currentTiles) { dc.addOrderedSurfaceRenderable(tile); } // Assemble the tiles used for picking, then build a set of surface object tiles containing unique colors for // each record. - if (dc.getCurrentLayer().isPickEnabled()) - { - try - { + if (dc.getCurrentLayer().isPickEnabled()) { + try { dc.enablePickingMode(); this.assembleTiles(dc); this.pickSupport.clearPickList(); this.pickTileBuilder.setForceTileUpdates(true); // force pick tiles to update with new pick colors this.pickTileBuilder.buildTiles(dc, this.currentTiles); // draw tiles and add candidates to pickSupport - } - finally - { + } finally { dc.disablePickingMode(); } } } @Override - public void pick(DrawContext dc, Point pickPoint) - { - if (dc == null) - { + public void pick(DrawContext dc, Point pickPoint) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.visible) + if (!this.visible) { return; + } int recordCount = this.getRecordCount(); if (recordCount == 0) // Shapefile is empty or contains only null records. + { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { // pick list cleared in preRender this.pickSupport.beginPicking(dc); gl.glEnable(GL.GL_CULL_FACE); dc.getGeographicSurfaceTileRenderer().setUseImageTilePickColors(true); dc.getGeographicSurfaceTileRenderer().renderTiles(dc, this.pickTileBuilder.getTiles(dc)); - } - finally - { + } finally { dc.getGeographicSurfaceTileRenderer().setUseImageTilePickColors(false); gl.glDisable(GL.GL_CULL_FACE); this.pickSupport.endPicking(dc); @@ -347,37 +324,35 @@ public void pick(DrawContext dc, Point pickPoint) } @Override - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.visible) + if (!this.visible) { return; + } if (this.getRecordCount() == 0) // Shapefile is empty or contains only null records. + { return; + } - if (dc.isPickingMode() && this.pickTileBuilder.getTileCount(dc) > 0) - { + if (dc.isPickingMode() && this.pickTileBuilder.getTileCount(dc) > 0) { this.pickLayer = dc.getCurrentLayer(); dc.addOrderedSurfaceRenderable(this); // perform the pick during ordered surface rendering } } @Override - protected void assembleRecords(Shapefile shapefile) - { + protected void assembleRecords(Shapefile shapefile) { this.rootTile = new Tile(this, this.sector, 0); super.assembleRecords(shapefile); - if (this.mustSplitTile(this.rootTile)) - { + if (this.mustSplitTile(this.rootTile)) { this.splitTile(this.rootTile); } @@ -385,16 +360,14 @@ protected void assembleRecords(Shapefile shapefile) } @Override - protected boolean mustAssembleRecord(ShapefileRecord shapefileRecord) - { + protected boolean mustAssembleRecord(ShapefileRecord shapefileRecord) { return super.mustAssembleRecord(shapefileRecord) - && (shapefileRecord.isPolylineRecord() - || shapefileRecord.isPolygonRecord()); // accept both polyline and polygon records + && (shapefileRecord.isPolylineRecord() + || shapefileRecord.isPolygonRecord()); // accept both polyline and polygon records } @Override - protected void assembleRecord(ShapefileRecord shapefileRecord) - { + protected void assembleRecord(ShapefileRecord shapefileRecord) { Record record = this.createRecord(shapefileRecord); this.addRecord(shapefileRecord, record); @@ -402,14 +375,12 @@ protected void assembleRecord(ShapefileRecord shapefileRecord) record.tile = this.rootTile; } - protected ShapefilePolylines.Record createRecord(ShapefileRecord shapefileRecord) - { + protected ShapefilePolylines.Record createRecord(ShapefileRecord shapefileRecord) { return new ShapefilePolylines.Record(this, shapefileRecord); } @Override - protected void recordDidChange(ShapefileRenderable.Record record) - { + protected void recordDidChange(ShapefileRenderable.Record record) { Tile tile = ((ShapefilePolylines.Record) record).tile; if (tile != null) // tile is null when attributes are specified during construction { @@ -417,13 +388,11 @@ protected void recordDidChange(ShapefileRenderable.Record record) } } - protected boolean mustSplitTile(Tile tile) - { + protected boolean mustSplitTile(Tile tile) { return tile.level < this.tileMaxLevel && tile.records.size() > this.tileMaxCapacity; } - protected void splitTile(Tile tile) - { + protected void splitTile(Tile tile) { // Create four child tiles by subdividing the tile's sector in latitude and longitude. Sector[] childSectors = tile.sector.subdivide(); tile.children = new Tile[4]; @@ -436,13 +405,10 @@ protected void splitTile(Tile tile) // include records that are marked as not visible, as recomputing the tile tree for record visibility changes // would be expensive. Iterator iterator = tile.records.iterator(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Record record = iterator.next(); - for (int i = 0; i < 4; i++) - { - if (tile.children[i].sector.contains(record.sector)) - { + for (int i = 0; i < 4; i++) { + if (tile.children[i].sector.contains(record.sector)) { tile.children[i].records.add(record); // add it to the child record.tile = tile.children[i]; // assign the record's tile iterator.remove(); // remove it from the parent @@ -454,10 +420,8 @@ protected void splitTile(Tile tile) // Recursively split child tiles as necessary, moving their records into each child's descendants. The recursive // split stops when a child tile reaches a maximum level, or when the number of records contained within the // tile is small enough. - for (int i = 0; i < 4; i++) - { - if (this.mustSplitTile(tile.children[i])) - { + for (int i = 0; i < 4; i++) { + if (this.mustSplitTile(tile.children[i])) { this.splitTile(tile.children[i]); } @@ -465,33 +429,27 @@ protected void splitTile(Tile tile) } } - protected void assembleTiles(DrawContext dc) - { + protected void assembleTiles(DrawContext dc) { this.currentTiles.clear(); this.addTileOrDescendants(dc, this.rootTile); } - protected void addTileOrDescendants(DrawContext dc, Tile tile) - { + protected void addTileOrDescendants(DrawContext dc, Tile tile) { // Determine whether or not the tile is visible. If the tile is not visible, then neither are the tile's records // or the tile's children. Note that a tile with no records may have children, so we can't use the tile's record // count as a determination of whether or not to test its children. - if (!this.isTileVisible(dc, tile)) - { + if (!this.isTileVisible(dc, tile)) { return; } // Add the tile to the list of tiles to draw, regenerating the tile's geometry and the tile's attribute groups // as necessary. - if (tile.records.size() > 0) - { - if (this.mustRegenerateTileGeometry(tile)) - { + if (tile.records.size() > 0) { + if (this.mustRegenerateTileGeometry(tile)) { this.regenerateTileGeometry(tile); } - if (this.mustAssembleTileAttributeGroups(tile)) - { + if (this.mustAssembleTileAttributeGroups(tile)) { this.assembleTileAttributeGroups(tile); } @@ -499,47 +457,38 @@ protected void addTileOrDescendants(DrawContext dc, Tile tile) } // Process the tile's children, if any. - if (tile.children != null) - { - for (Tile childTile : tile.children) - { + if (tile.children != null) { + for (Tile childTile : tile.children) { this.addTileOrDescendants(dc, childTile); } } } - protected boolean isTileVisible(DrawContext dc, Tile tile) - { + protected boolean isTileVisible(DrawContext dc, Tile tile) { Extent extent = Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), tile.sector); - if (dc.isSmall(extent, 1)) - { + if (dc.isSmall(extent, 1)) { return false; } - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(extent); } return dc.getView().getFrustumInModelCoordinates().intersects(extent); } - protected boolean mustRegenerateTileGeometry(Tile tile) - { + protected boolean mustRegenerateTileGeometry(Tile tile) { return tile.vertices == null; } - protected void regenerateTileGeometry(Tile tile) - { + protected void regenerateTileGeometry(Tile tile) { this.tessellateTile(tile); } - protected void tessellateTile(Tile tile) - { + protected void tessellateTile(Tile tile) { int numPoints = 0; - for (Record record : tile.records) - { + for (Record record : tile.records) { numPoints += record.numberOfPoints; } @@ -555,17 +504,14 @@ protected void tessellateTile(Tile tile) // Generate the geographic coordinate vertices and indices for all records in the tile. This may include records // that are marked as not visible, as recomputing the vertices and indices for record visibility changes would // be expensive. The tessellated indices are generated only once, since each record's indices never change. - for (Record record : tile.records) - { + for (Record record : tile.records) { this.tess.reset(); - for (int i = 0; i < record.getBoundaryCount(); i++) - { + for (int i = 0; i < record.getBoundaryCount(); i++) { this.tess.beginPolyline(); VecBuffer points = record.getBoundaryPoints(i); - for (int j = 0; j < points.getSize(); j++) - { + for (int j = 0; j < points.getSize(); j++) { points.get(j, location); double x = location[0]; // map longitude to x double y = location[1]; // map latitude to y @@ -595,8 +541,7 @@ protected void tessellateTile(Tile tile) tile.transformMatrix = Matrix.fromTranslation(rp.x, rp.y, rp.z); } - protected void assembleRecordIndices(PolylineTessellator tessellator, Record record) - { + protected void assembleRecordIndices(PolylineTessellator tessellator, Record record) { // Get the tessellated boundary indices representing a line segment tessellation of the record parts. // Flip each buffer in order to limit the buffer range we use to values added during tessellation. IntBuffer tessBoundary = (IntBuffer) tessellator.getIndices().flip(); @@ -608,18 +553,15 @@ protected void assembleRecordIndices(PolylineTessellator tessellator, Record rec record.outlineIndices = (IntBuffer) outlineIndices.rewind(); } - protected void invalidateTileAttributeGroups(Tile tile) - { + protected void invalidateTileAttributeGroups(Tile tile) { tile.attributeGroups.clear(); } - protected boolean mustAssembleTileAttributeGroups(Tile tile) - { + protected boolean mustAssembleTileAttributeGroups(Tile tile) { return tile.attributeGroups.isEmpty(); } - protected void assembleTileAttributeGroups(Tile tile) - { + protected void assembleTileAttributeGroups(Tile tile) { tile.attributeGroups.clear(); tile.attributeStateID++; @@ -629,10 +571,11 @@ protected void assembleTileAttributeGroups(Tile tile) // without re-assembling these groups. However, changes to a record's visibility state, highlight state, normal // attributes reference and highlight attributes reference invalidate this grouping. HashMap attrMap = new HashMap(); - for (Record record : tile.records) - { + for (Record record : tile.records) { if (!record.isVisible()) // ignore records marked as not visible + { continue; + } ShapeAttributes attrs = this.determineActiveAttributes(record); RecordGroup group = attrMap.get(attrs); @@ -651,8 +594,7 @@ protected void assembleTileAttributeGroups(Tile tile) // Make the indices for each record group. We take care to make indices for both the interior and the outline, // regardless of the current state of Attributes.isDrawInterior and Attributes.isDrawOutline. This enable these // properties change state without needing to re-assemble these groups. - for (RecordGroup group : tile.attributeGroups) - { + for (RecordGroup group : tile.attributeGroups) { int indexCount = group.outlineIndexRange.length; IntBuffer indices = Buffers.newDirectIntBuffer(indexCount); @@ -669,44 +611,34 @@ protected void assembleTileAttributeGroups(Tile tile) } } - protected void renderTile(DrawContext dc, Tile tile) - { + protected void renderTile(DrawContext dc, Tile tile) { this.beginDrawing(dc); - try - { - if (dc.isPickingMode()) - { + try { + if (dc.isPickingMode()) { this.drawTileInUniqueColors(dc, tile); - } - else - { + } else { this.drawTile(dc, tile); } - } - finally - { + } finally { this.endDrawing(dc); } } - protected void beginDrawing(DrawContext dc) - { + protected void beginDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glDisable(GL.GL_DEPTH_TEST); gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); // all drawing uses vertex arrays gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); gl.glEnable(GL.GL_LINE_SMOOTH); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); } } - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glEnable(GL.GL_DEPTH_TEST); gl.glDisableClientState(GL2.GL_VERTEX_ARRAY); @@ -714,28 +646,24 @@ protected void endDrawing(DrawContext dc) gl.glLineWidth(1); gl.glPopMatrix(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glDisable(GL.GL_BLEND); gl.glDisable(GL.GL_LINE_SMOOTH); gl.glBlendFunc(GL.GL_ONE, GL.GL_ZERO); } - if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) - { + if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); } } - protected void drawTile(DrawContext dc, Tile tile) - { + protected void drawTile(DrawContext dc, Tile tile) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int[] vboId = null; boolean useVbo = dc.getGLRuntimeCapabilities().isUseVertexBufferObject(); - if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(tile.vboKey)) == null) - { + if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(tile.vboKey)) == null) { long vboSize = 4 * tile.vertices.remaining(); // 4 bytes for each float vertex component vboId = new int[1]; gl.glGenBuffers(1, vboId, 0); @@ -743,14 +671,10 @@ protected void drawTile(DrawContext dc, Tile tile) gl.glBufferData(GL.GL_ARRAY_BUFFER, vboSize, tile.vertices, GL.GL_STATIC_DRAW); gl.glVertexPointer(tile.vertexStride, GL.GL_FLOAT, 0, 0); dc.getGpuResourceCache().put(tile.vboKey, vboId, GpuResourceCache.VBO_BUFFERS, vboSize); - } - else if (useVbo) - { + } else if (useVbo) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboId[0]); gl.glVertexPointer(tile.vertexStride, GL.GL_FLOAT, 0, 0); - } - else - { + } else { gl.glVertexPointer(tile.vertexStride, GL.GL_FLOAT, 0, tile.vertices); } @@ -759,66 +683,57 @@ else if (useVbo) modelview.toArray(this.matrixArray, 0, false); gl.glLoadMatrixd(this.matrixArray, 0); - for (RecordGroup attrGroup : tile.attributeGroups) - { + for (RecordGroup attrGroup : tile.attributeGroups) { this.drawTileAttributeGroup(dc, attrGroup); } } - protected void drawTileAttributeGroup(DrawContext dc, RecordGroup attributeGroup) - { + protected void drawTileAttributeGroup(DrawContext dc, RecordGroup attributeGroup) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. ShapeAttributes attrs = attributeGroup.attributes; - if (!attrs.isDrawOutline()) + if (!attrs.isDrawOutline()) { return; + } int[] vboId = null; boolean useVbo = dc.getGLRuntimeCapabilities().isUseVertexBufferObject(); - if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(attributeGroup.vboKey)) == null) - { + if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(attributeGroup.vboKey)) == null) { long vboSize = 4 * attributeGroup.indices.remaining(); // 4 bytes for each unsigned int index vboId = new int[1]; gl.glGenBuffers(1, vboId, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboId[0]); gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, vboSize, attributeGroup.indices, GL.GL_STATIC_DRAW); dc.getGpuResourceCache().put(attributeGroup.vboKey, vboId, GpuResourceCache.VBO_BUFFERS, vboSize); - } - else if (useVbo) - { + } else if (useVbo) { gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboId[0]); } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { float[] color = this.colorFloatArray; attrs.getOutlineMaterial().getDiffuse().getRGBComponents(color); gl.glColor4f(color[0], color[1], color[2], color[3]); } - if (dc.isPickingMode() && attrs.getOutlineWidth() < this.getOutlinePickWidth()) + if (dc.isPickingMode() && attrs.getOutlineWidth() < this.getOutlinePickWidth()) { gl.glLineWidth(this.getOutlinePickWidth()); - else + } else { gl.glLineWidth((float) attrs.getOutlineWidth()); + } - if (useVbo) - { + if (useVbo) { gl.glDrawElements(GL.GL_LINES, attributeGroup.indices.remaining(), GL.GL_UNSIGNED_INT, 0); - } - else - { + } else { gl.glDrawElements(GL.GL_LINES, attributeGroup.indices.remaining(), GL.GL_UNSIGNED_INT, - attributeGroup.indices); + attributeGroup.indices); } } - protected void drawTileInUniqueColors(DrawContext dc, Tile tile) - { + protected void drawTileInUniqueColors(DrawContext dc, Tile tile) { GL2 gl = dc.getGL().getGL2(); int pickColorsSize = 3 * (tile.vertices.remaining() / tile.vertexStride); // 1 RGB color for each XY vertex - if (this.pickColors == null || this.pickColors.capacity() < pickColorsSize) - { + if (this.pickColors == null || this.pickColors.capacity() < pickColorsSize) { this.pickColors = Buffers.newDirectByteBuffer(pickColorsSize); dc.getGpuResourceCache().remove(this.pickColorsVboKey); // remove any associated VBO from GPU memory } @@ -827,29 +742,23 @@ protected void drawTileInUniqueColors(DrawContext dc, Tile tile) ByteBuffer colors; int[] vboId = null; boolean useVbo = dc.getGLRuntimeCapabilities().isUseVertexBufferObject(); - if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(this.pickColorsVboKey)) == null) - { + if (useVbo && (vboId = (int[]) dc.getGpuResourceCache().get(this.pickColorsVboKey)) == null) { vboId = new int[1]; gl.glGenBuffers(1, vboId, 0); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboId[0]); gl.glBufferData(GL.GL_ARRAY_BUFFER, this.pickColors.remaining(), this.pickColors, GL2.GL_DYNAMIC_DRAW); dc.getGpuResourceCache().put(this.pickColorsVboKey, vboId, GpuResourceCache.VBO_BUFFERS, - this.pickColors.remaining()); + this.pickColors.remaining()); colors = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL.GL_WRITE_ONLY); - } - else if (useVbo) - { + } else if (useVbo) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboId[0]); colors = gl.glMapBuffer(GL.GL_ARRAY_BUFFER, GL.GL_WRITE_ONLY); - } - else - { + } else { colors = pickColors; } byte[] vertexColors = this.colorByteArray; - for (Record record : tile.records) - { + for (Record record : tile.records) { // Assign each record a unique RGB color. Generate vertex colors for every record - regardless of its // visibility - since the tile's color array must match the tile's vertex array. Color color = dc.getUniquePickColor(); @@ -859,33 +768,26 @@ else if (useVbo) vertexColors[2] = (byte) color.getBlue(); // Add the unique color each vertex of the record. - for (int i = 0; i < record.numberOfPoints; i++) - { + for (int i = 0; i < record.numberOfPoints; i++) { colors.put(vertexColors, 0, 3); } } colors.flip(); - try - { + try { this.pickSupport.beginPicking(dc); gl.glEnableClientState(GL2.GL_COLOR_ARRAY); - if (useVbo) - { + if (useVbo) { gl.glUnmapBuffer(GL.GL_ARRAY_BUFFER); gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, 0); - } - else - { + } else { gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, colors); } this.drawTile(dc, tile); - } - finally - { + } finally { gl.glDisableClientState(GL2.GL_COLOR_ARRAY); this.pickSupport.endPicking(dc); } diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecord.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecord.java index ec4b55a965..4f4de66a65 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecord.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecord.java @@ -20,8 +20,8 @@ * @author Patrick Murris * @version $Id: ShapefileRecord.java 2303 2014-09-14 22:33:36Z dcollins $ */ -public abstract class ShapefileRecord -{ +public abstract class ShapefileRecord { + protected Shapefile shapeFile; protected int recordNumber; protected int contentLengthInBytes; @@ -30,15 +30,17 @@ public abstract class ShapefileRecord protected int numberOfParts; protected int numberOfPoints; protected int firstPartNumber; - /** Indicates if the record's point coordinates should be normalized. Defaults to false. */ + /** + * Indicates if the record's point coordinates should be normalized. Defaults to false. + */ protected boolean normalizePoints; protected static final int RECORD_HEADER_LENGTH = 8; protected static List measureTypes = new ArrayList(Arrays.asList( - Shapefile.SHAPE_POINT_M, Shapefile.SHAPE_POINT_Z, - Shapefile.SHAPE_MULTI_POINT_M, Shapefile.SHAPE_MULTI_POINT_Z, - Shapefile.SHAPE_POLYLINE_M, Shapefile.SHAPE_POLYLINE_Z, - Shapefile.SHAPE_POLYGON_M, Shapefile.SHAPE_POLYGON_Z + Shapefile.SHAPE_POINT_M, Shapefile.SHAPE_POINT_Z, + Shapefile.SHAPE_MULTI_POINT_M, Shapefile.SHAPE_MULTI_POINT_Z, + Shapefile.SHAPE_POLYLINE_M, Shapefile.SHAPE_POLYLINE_Z, + Shapefile.SHAPE_POLYGON_M, Shapefile.SHAPE_POLYGON_Z )); /** @@ -46,23 +48,20 @@ public abstract class ShapefileRecord * the start of the record, and will be the start of the next record when the constructor returns. * * @param shapeFile the parent {@link Shapefile}. - * @param buffer the shapefile record {@link java.nio.ByteBuffer} to read from. + * @param buffer the shapefile record {@link java.nio.ByteBuffer} to read from. * * @throws IllegalArgumentException if any argument is null or otherwise invalid. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if the record's shape type does not match that of the shapefile. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if the record's shape type does not match that of the + * shapefile. */ - public ShapefileRecord(Shapefile shapeFile, ByteBuffer buffer) - { - if (shapeFile == null) - { + public ShapefileRecord(Shapefile shapeFile, ByteBuffer buffer) { + if (shapeFile == null) { String message = Logging.getMessage("nullValue.ShapefileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -70,12 +69,9 @@ public ShapefileRecord(Shapefile shapeFile, ByteBuffer buffer) // Save the buffer's current position. int pos = buffer.position(); - try - { + try { this.readFromBuffer(shapeFile, buffer); - } - finally - { + } finally { // Move to the end of the record. buffer.position(pos + this.contentLengthInBytes + RECORD_HEADER_LENGTH); } @@ -86,8 +82,7 @@ public ShapefileRecord(Shapefile shapeFile, ByteBuffer buffer) * * @return the shapefile containing this record. */ - public Shapefile getShapeFile() - { + public Shapefile getShapeFile() { return this.shapeFile; } @@ -96,8 +91,7 @@ public Shapefile getShapeFile() * * @return the record's ordinal position in the shapefile. */ - public int getRecordNumber() - { + public int getRecordNumber() { return this.recordNumber; } @@ -106,8 +100,7 @@ public int getRecordNumber() * * @return the record' shape type. See {@link Shapefile} for a list of the defined shape types. */ - public String getShapeType() - { + public String getShapeType() { return this.shapeType; } @@ -116,8 +109,7 @@ public String getShapeType() * * @return the record's attributes. */ - public DBaseRecord getAttributes() - { + public DBaseRecord getAttributes() { return this.attributes; } @@ -126,8 +118,7 @@ public DBaseRecord getAttributes() * * @param attributes the shapefile's attributes. May be null. */ - public void setAttributes(DBaseRecord attributes) - { + public void setAttributes(DBaseRecord attributes) { this.attributes = attributes; } @@ -136,8 +127,7 @@ public void setAttributes(DBaseRecord attributes) * * @return the number of parts in the record. */ - public int getNumberOfParts() - { + public int getNumberOfParts() { return this.numberOfParts; } @@ -146,8 +136,7 @@ public int getNumberOfParts() * * @return the first part number in the record. */ - public int getFirstPartNumber() - { + public int getFirstPartNumber() { return this.firstPartNumber; } @@ -156,8 +145,7 @@ public int getFirstPartNumber() * * @return the last part number in the record. */ - public int getLastPartNumber() - { + public int getLastPartNumber() { return this.firstPartNumber + this.numberOfParts - 1; } @@ -166,8 +154,7 @@ public int getLastPartNumber() * * @return the number of points in the record. */ - public int getNumberOfPoints() - { + public int getNumberOfPoints() { return this.numberOfPoints; } @@ -178,10 +165,8 @@ public int getNumberOfPoints() * * @return the number of points in the specified part. */ - public int getNumberOfPoints(int partNumber) - { - if (partNumber < 0 || partNumber >= this.getNumberOfParts()) - { + public int getNumberOfPoints(int partNumber) { + if (partNumber < 0 || partNumber >= this.getNumberOfParts()) { String message = Logging.getMessage("generic.indexOutOfRange", partNumber); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -197,12 +182,10 @@ public int getNumberOfPoints(int partNumber) * @param partNumber the part for which to return the point buffer. * * @return the buffer holding the part's points. The points are ordered X0,Y0,X1,Y1,...Xn-1,Yn-1, where "n" is the - * number of points in the part. + * number of points in the part. */ - public VecBuffer getPointBuffer(int partNumber) - { - if (partNumber < 0 || partNumber >= this.getNumberOfParts()) - { + public VecBuffer getPointBuffer(int partNumber) { + if (partNumber < 0 || partNumber >= this.getNumberOfParts()) { String message = Logging.getMessage("generic.indexOutOfRange", partNumber); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -221,8 +204,7 @@ public VecBuffer getPointBuffer(int partNumber) * * @return a CompoundVecBuffer that holds this record's coordinate data. */ - public CompoundVecBuffer getCompoundPointBuffer() - { + public CompoundVecBuffer getCompoundPointBuffer() { return this.getShapeFile().getPointBuffer().slice(this.getFirstPartNumber(), this.getLastPartNumber()); } @@ -234,8 +216,7 @@ public CompoundVecBuffer getCompoundPointBuffer() * coordinate system is geographic, the elements can be interpreted as angular degrees in the order minimum * latitude, maximum latitude, minimum longitude, and maximum longitude. * - * @return the record's bounding rectangle, or null to indicate that this record does not have a bounding - * rectangle. + * @return the record's bounding rectangle, or null to indicate that this record does not have a bounding rectangle. */ public abstract double[] getBoundingRectangle(); @@ -245,7 +226,7 @@ public CompoundVecBuffer getCompoundPointBuffer() * constructor returns. * * @param shapefile the containing {@link Shapefile}. - * @param buffer the shapefile record {@link java.nio.ByteBuffer} to read from. + * @param buffer the shapefile record {@link java.nio.ByteBuffer} to read from. */ protected abstract void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer); @@ -254,10 +235,9 @@ public CompoundVecBuffer getCompoundPointBuffer() * be the start of the record and will be the start of the next record when the constructor returns. * * @param shapefile the containing {@link Shapefile}. - * @param buffer the shapefile record {@link java.nio.ByteBuffer} to read from. + * @param buffer the shapefile record {@link java.nio.ByteBuffer} to read from. */ - protected void readFromBuffer(Shapefile shapefile, ByteBuffer buffer) - { + protected void readFromBuffer(Shapefile shapefile, ByteBuffer buffer) { // Read record number and record length - big endian. buffer.order(ByteOrder.BIG_ENDIAN); this.recordNumber = buffer.getInt(); @@ -281,26 +261,23 @@ protected void readFromBuffer(Shapefile shapefile, ByteBuffer buffer) * is not {@link Shapefile#SHAPE_NULL}. Records of type SHAPE_NULL are always valid, and * may appear in any Shapefile. *

        - * For details, see the ESRI Shapefile specification at , - * pages 4 and 5. + * For details, see the ESRI Shapefile specification at + * , pages 4 and 5. * * @param shapefile the shapefile. * @param shapeType the record's shape type. * - * @throws WWRuntimeException if the shape types do not match. + * @throws WWRuntimeException if the shape types do not match. * @throws IllegalArgumentException if the specified shape type is null. */ - protected void validateShapeType(Shapefile shapefile, String shapeType) - { - if (shapeType == null) - { + protected void validateShapeType(Shapefile shapefile, String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!shapeType.equals(shapefile.getShapeType()) && !shapeType.equals(Shapefile.SHAPE_NULL)) - { + if (!shapeType.equals(shapefile.getShapeType()) && !shapeType.equals(Shapefile.SHAPE_NULL)) { String message = Logging.getMessage("SHP.UnsupportedShapeType", shapeType); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -313,8 +290,7 @@ protected void validateShapeType(Shapefile shapefile, String shapeType) * * @return true if the record may contain measure values. */ - protected boolean isMeasureType() - { + protected boolean isMeasureType() { return Shapefile.isMeasureType(this.getShapeType()); } @@ -323,8 +299,7 @@ protected boolean isMeasureType() * * @return true if the record is a type containing Z values. */ - protected boolean isZType() - { + protected boolean isZType() { return Shapefile.isZType(this.getShapeType()); } @@ -334,8 +309,7 @@ protected boolean isZType() * * @return true if this is a null record, otherwise false. */ - public boolean isNullRecord() - { + public boolean isNullRecord() { return false; } @@ -345,8 +319,7 @@ public boolean isNullRecord() * * @return true if this is a point record, otherwise false. */ - public boolean isPointRecord() - { + public boolean isPointRecord() { return false; } @@ -356,8 +329,7 @@ public boolean isPointRecord() * * @return true if this is a multi point record, otherwise false. */ - public boolean isMultiPointRecord() - { + public boolean isMultiPointRecord() { return false; } @@ -367,8 +339,7 @@ public boolean isMultiPointRecord() * * @return true if this is a polyline record, otherwise false. */ - public boolean isPolylineRecord() - { + public boolean isPolylineRecord() { return false; } @@ -378,8 +349,7 @@ public boolean isPolylineRecord() * * @return true if this is a polygon record, otherwise false. */ - public boolean isPolygonRecord() - { + public boolean isPolygonRecord() { return false; } @@ -389,8 +359,7 @@ public boolean isPolygonRecord() * * @return this record cast as a ShapefileRecordNull. */ - public ShapefileRecordNull asNullRecord() - { + public ShapefileRecordNull asNullRecord() { return (ShapefileRecordNull) this; } @@ -400,8 +369,7 @@ public ShapefileRecordNull asNullRecord() * * @return this record cast as a ShapefileRecordPoint. */ - public ShapefileRecordPoint asPointRecord() - { + public ShapefileRecordPoint asPointRecord() { return (ShapefileRecordPoint) this; } @@ -411,8 +379,7 @@ public ShapefileRecordPoint asPointRecord() * * @return this record cast as a ShapefileRecordMultiPoint. */ - public ShapefileRecordMultiPoint asMultiPointRecord() - { + public ShapefileRecordMultiPoint asMultiPointRecord() { return (ShapefileRecordMultiPoint) this; } @@ -422,8 +389,7 @@ public ShapefileRecordMultiPoint asMultiPointRecord() * * @return this record cast as a ShapefileRecordPolyline. */ - public ShapefileRecordPolyline asPolylineRecord() - { + public ShapefileRecordPolyline asPolylineRecord() { return (ShapefileRecordPolyline) this; } @@ -433,8 +399,7 @@ public ShapefileRecordPolyline asPolylineRecord() * * @return this record cast as a ShapefileRecordPolygon. */ - public ShapefileRecordPolygon asPolygonRecord() - { + public ShapefileRecordPolygon asPolygonRecord() { return (ShapefileRecordPolygon) this; } @@ -443,8 +408,7 @@ public ShapefileRecordPolygon asPolygonRecord() * * @return true if the record's points should be normalized; false otherwise. */ - public boolean isNormalizePoints() - { + public boolean isNormalizePoints() { return this.normalizePoints; } @@ -452,17 +416,14 @@ public boolean isNormalizePoints() * Specifies if the record's point coordinates should be normalized. Defaults to false. * * @param normalizePoints true if the record's points should be normalized; false - * otherwise. + * otherwise. */ - public void setNormalizePoints(boolean normalizePoints) - { + public void setNormalizePoints(boolean normalizePoints) { this.normalizePoints = normalizePoints; } - public void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { - if (xmlWriter == null) - { + public void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -476,8 +437,7 @@ public void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStream xmlWriter.writeAttribute("points", Integer.toString(this.getNumberOfPoints())); xmlWriter.writeCharacters("\n"); - for (Map.Entry a : this.getAttributes().getEntries()) - { + for (Map.Entry a : this.getAttributes().getEntries()) { xmlWriter.writeStartElement("Attribute"); xmlWriter.writeAttribute("name", a.getKey() != null ? a.getKey().toString() : ""); @@ -487,11 +447,9 @@ public void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStream xmlWriter.writeCharacters("\n"); } - if (this.getNumberOfParts() > 0) - { + if (this.getNumberOfParts() > 0) { VecBuffer vb = this.getPointBuffer(0); - for (LatLon ll : vb.getLocations()) - { + for (LatLon ll : vb.getLocations()) { xmlWriter.writeStartElement("Point"); xmlWriter.writeAttribute("x", Double.toString(ll.getLatitude().degrees)); xmlWriter.writeAttribute("y", Double.toString(ll.getLongitude().degrees)); @@ -501,7 +459,6 @@ public void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStream } // TODO: export record-type specific fields - xmlWriter.writeEndElement(); // Record } @@ -511,39 +468,37 @@ public void exportAsXML(XMLStreamWriter xmlWriter) throws IOException, XMLStream * * @param xmlWriter Writer to receive KML. * - * @throws IOException If an exception occurs while writing the KML + * @throws IOException If an exception occurs while writing the KML * @throws XMLStreamException If an exception occurs while exporting the data. */ - public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { } - public void printInfo(boolean printCoordinates) - { + public void printInfo(boolean printCoordinates) { System.out.printf("%d, %s: %d parts, %d points", this.getRecordNumber(), this.getShapeType(), - this.getNumberOfParts(), this.getNumberOfPoints()); - for (Map.Entry a : this.getAttributes().getEntries()) - { - if (a.getKey() != null) + this.getNumberOfParts(), this.getNumberOfPoints()); + for (Map.Entry a : this.getAttributes().getEntries()) { + if (a.getKey() != null) { System.out.printf(", %s", a.getKey()); - if (a.getValue() != null) + } + if (a.getValue() != null) { System.out.printf(", %s", a.getValue()); + } } System.out.println(); System.out.print("\tAttributes: "); - for (Map.Entry entry : this.getAttributes().getEntries()) - { + for (Map.Entry entry : this.getAttributes().getEntries()) { System.out.printf("%s = %s, ", entry.getKey(), entry.getValue()); } System.out.println(); - if (!printCoordinates) + if (!printCoordinates) { return; + } VecBuffer vb = this.getPointBuffer(0); - for (LatLon ll : vb.getLocations()) - { + for (LatLon ll : vb.getLocations()) { System.out.printf("\t%f, %f\n", ll.getLatitude().degrees, ll.getLongitude().degrees); } } diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordMultiPoint.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordMultiPoint.java index 76c53356ed..777ab24efa 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordMultiPoint.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordMultiPoint.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.shapefile; import javax.xml.stream.*; @@ -11,35 +10,37 @@ import java.nio.ByteBuffer; /** - * Represents a Shapefile record with a multi point shape type. Multi-point shapes represent a set of x,y coordinate + * Represents a Shapefile record with a multi point shape type. Multi-point shapes represent a set of x,y coordinate * pairs. *

        * Multi-points may have optional z-coordinates or m-coordinates that accompany each x,y coordinate pair. If a * Multi-point has z-coordinates, then {@link #getZValues()} returns a non-null array of - * values. If a Multi-point has m-coordinates, then {@link #getMValues()} returns a non-null + * values. If a Multi-point has m-coordinates, then {@link #getMValues()} returns a non-null * array of values. * * @author tag * @version $Id: ShapefileRecordMultiPoint.java 2303 2014-09-14 22:33:36Z dcollins $ */ -public class ShapefileRecordMultiPoint extends ShapefileRecord -{ +public class ShapefileRecordMultiPoint extends ShapefileRecord { + protected double[] boundingRectangle; protected double[] zRange; // non-null only for Z types protected double[] zValues; // non-null only for Z types protected double[] mRange; // will be null if no measures protected double[] mValues; // will be null if no measures - /** {@inheritDoc} */ - public ShapefileRecordMultiPoint(Shapefile shapeFile, ByteBuffer buffer) - { + /** + * {@inheritDoc} + */ + public ShapefileRecordMultiPoint(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isMultiPointRecord() - { + public boolean isMultiPointRecord() { return true; } @@ -51,8 +52,7 @@ public boolean isMultiPointRecord() * * @return an {@link Iterable} over the points X and Y coordinates. */ - public Iterable getPoints(int partNumber) - { + public Iterable getPoints(int partNumber) { return this.getPointBuffer(partNumber).getCoords(); } @@ -61,8 +61,7 @@ public Iterable getPoints(int partNumber) * * @return the shape's Z range. The range minimum is at index 0, the maximum at index 1. */ - public double[] getZRange() - { + public double[] getZRange() { return this.zRange; } @@ -71,8 +70,7 @@ public double[] getZRange() * * @return the shape's Z values. */ - public double[] getZValues() - { + public double[] getZValues() { return this.zValues; } @@ -80,10 +78,9 @@ public double[] getZValues() * Returns the shape's optional measure range. * * @return the shape's measure range, or null if no measures are in the record. The range minimum is at index 0, the - * maximum at index 1. + * maximum at index 1. */ - public double[] getMRange() - { + public double[] getMRange() { return this.mRange; } @@ -92,50 +89,53 @@ public double[] getMRange() * * @return the shape's measure values, or null if no measures are in the record. */ - public double[] getMValues() - { + public double[] getMValues() { return this.mValues; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public double[] getBoundingRectangle() - { + public double[] getBoundingRectangle() { return this.boundingRectangle != null ? this.boundingRectangle : null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) - { + protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) { // Read the bounding rectangle. Shapefile.BoundingRectangle rect = shapefile.readBoundingRectangle(buffer); this.boundingRectangle = rect.coords; // Specify that the record's points should be normalized if the bounding rectangle is normalized. Ignore the // shapefile's normalizePoints property to avoid normalizing records that don't need it. - if (rect.isNormalized) + if (rect.isNormalized) { this.setNormalizePoints(true); + } // Read the number of points. this.numberOfParts = 1; this.numberOfPoints = buffer.getInt(); this.firstPartNumber = -1; - if (this.numberOfPoints > 0) - { + if (this.numberOfPoints > 0) { // Add the record's points to the Shapefile's point buffer, and record this record's part offset in the // Shapefile's point buffer. this.firstPartNumber = shapefile.addPoints(this, buffer, this.numberOfPoints); } // Read the optional Z value. - if (this.isZType()) + if (this.isZType()) { this.readZ(buffer); + } // Read the optional measure value. - if (this.isMeasureType()) + if (this.isMeasureType()) { this.readOptionalMeasures(buffer); + } } /** @@ -143,8 +143,7 @@ protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) * * @param buffer the record buffer to read from. */ - protected void readZ(ByteBuffer buffer) - { + protected void readZ(ByteBuffer buffer) { this.zRange = ShapefileUtils.readDoubleArray(buffer, 2); this.zValues = ShapefileUtils.readDoubleArray(buffer, this.getNumberOfPoints()); } @@ -154,11 +153,9 @@ protected void readZ(ByteBuffer buffer) * * @param buffer the record buffer to read from. */ - protected void readOptionalMeasures(ByteBuffer buffer) - { + protected void readOptionalMeasures(ByteBuffer buffer) { // Measure values are optional. - if (buffer.hasRemaining() && (buffer.limit() - buffer.position()) >= (this.getNumberOfPoints() * 8)) - { + if (buffer.hasRemaining() && (buffer.limit() - buffer.position()) >= (this.getNumberOfPoints() * 8)) { this.mRange = ShapefileUtils.readDoubleArray(buffer, 2); this.mValues = ShapefileUtils.readDoubleArray(buffer, this.getNumberOfPoints()); } @@ -169,13 +166,11 @@ protected void readOptionalMeasures(ByteBuffer buffer) * * @param xmlWriter XML writer to receive the generated KML. * - * @throws javax.xml.stream.XMLStreamException - * If an exception occurs while writing the KML + * @throws javax.xml.stream.XMLStreamException If an exception occurs while writing the KML * @throws java.io.IOException If an exception occurs while exporting the data. */ @Override - public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { xmlWriter.writeStartElement("Placemark"); xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(Integer.toString(this.getRecordNumber())); @@ -190,13 +185,13 @@ public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStream double[] zValues = this.getZValues(); int index = 0; - for (double[] point : points) - { + for (double[] point : points) { xmlWriter.writeStartElement("Point"); double z = 0.0; - if (zValues != null && index < zValues.length) + if (zValues != null && index < zValues.length) { z = zValues[index]; + } xmlWriter.writeStartElement("altitudeMode"); xmlWriter.writeCharacters(altitudeMode); diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordNull.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordNull.java index 599422247f..4f6c64dc58 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordNull.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordNull.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.shapefile; import java.nio.ByteBuffer; @@ -15,32 +14,36 @@ * @author tag * @version $Id: ShapefileRecordNull.java 2303 2014-09-14 22:33:36Z dcollins $ */ -public class ShapefileRecordNull extends ShapefileRecord -{ - /** {@inheritDoc} */ - public ShapefileRecordNull(Shapefile shapeFile, ByteBuffer buffer) - { +public class ShapefileRecordNull extends ShapefileRecord { + + /** + * {@inheritDoc} + */ + public ShapefileRecordNull(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isNullRecord() - { + public boolean isNullRecord() { return true; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public double[] getBoundingRectangle() - { + public double[] getBoundingRectangle() { return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) - { + protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) { this.numberOfParts = 0; this.numberOfPoints = 0; } diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPoint.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPoint.java index c6c87df29e..e5495ca51a 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPoint.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPoint.java @@ -21,21 +21,23 @@ * @author Patrick Murris * @version $Id: ShapefileRecordPoint.java 2303 2014-09-14 22:33:36Z dcollins $ */ -public class ShapefileRecordPoint extends ShapefileRecord -{ +public class ShapefileRecordPoint extends ShapefileRecord { + protected Double z; // non-null only for Z types protected Double m; // non-null only for Measure types with measures specified - /** {@inheritDoc} */ - public ShapefileRecordPoint(Shapefile shapeFile, ByteBuffer buffer) - { + /** + * {@inheritDoc} + */ + public ShapefileRecordPoint(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isPointRecord() - { + public boolean isPointRecord() { return true; } @@ -44,8 +46,7 @@ public boolean isPointRecord() * * @return the point X and Y coordinates. */ - public double[] getPoint() - { + public double[] getPoint() { VecBuffer vb = this.getPointBuffer(0); return vb.get(0, new double[vb.getCoordsPerVec()]); } @@ -55,8 +56,7 @@ public double[] getPoint() * * @return the shape's Z value. */ - public Double getZ() - { + public Double getZ() { return this.z; } @@ -65,26 +65,28 @@ public Double getZ() * * @return the shape's measure, or null if no measure is in the record. */ - public Double getM() - { + public Double getM() { return this.m; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public double[] getBoundingRectangle() - { + public double[] getBoundingRectangle() { return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) - { + protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) { // Specify that the record's points should be normalized if the shapefile itself is marked as needing // normalization. - if (shapefile.isNormalizePoints()) + if (shapefile.isNormalizePoints()) { this.setNormalizePoints(true); + } // Store the number of parts and the number of points (always 1). this.numberOfParts = 1; @@ -95,12 +97,14 @@ protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) this.firstPartNumber = shapefile.addPoints(this, buffer, 1); // Read the optional Z value. - if (this.isZType()) + if (this.isZType()) { this.readZ(buffer); + } // Read the optional measure value. - if (this.isMeasureType()) + if (this.isMeasureType()) { this.readOptionalMeasure(buffer); + } } /** @@ -108,8 +112,7 @@ protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) * * @param buffer the record to read from. */ - protected void readZ(ByteBuffer buffer) - { + protected void readZ(ByteBuffer buffer) { double[] zArray = ShapefileUtils.readDoubleArray(buffer, 1); this.z = zArray[0]; } @@ -119,11 +122,9 @@ protected void readZ(ByteBuffer buffer) * * @param buffer the record buffer to read from. */ - protected void readOptionalMeasure(ByteBuffer buffer) - { + protected void readOptionalMeasure(ByteBuffer buffer) { // Measure values are optional. - if (buffer.hasRemaining() && (buffer.limit() - buffer.position()) >= 8) - { + if (buffer.hasRemaining() && (buffer.limit() - buffer.position()) >= 8) { double[] mArray = ShapefileUtils.readDoubleArray(buffer, 1); this.m = mArray[0]; } @@ -135,11 +136,10 @@ protected void readOptionalMeasure(ByteBuffer buffer) * @param xmlWriter XML writer to receive the generated KML. * * @throws XMLStreamException If an exception occurs while writing the KML - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. */ @Override - public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { xmlWriter.writeStartElement("Placemark"); xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(Integer.toString(this.getRecordNumber())); @@ -152,8 +152,7 @@ public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStream double[] point = this.getPoint(); Double z = this.getZ(); - if (z == null) - { + if (z == null) { z = 0.0; altitudeMode = "clampToGround"; } diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolygon.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolygon.java index d713d98322..fa8db78dbd 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolygon.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolygon.java @@ -22,24 +22,26 @@ * rings defining holes in the polygon have a counter-clockwise winding order. *

        * Polygons may have optional z-coordinates or m-coordinates that accompany each coordinate pair. If a Polygon has - * z-coordinates, then {@link #getZValues()} returns a non-null array of values. If a Polygon + * z-coordinates, then {@link #getZValues()} returns a non-null array of values. If a Polygon * has m-coordinates, then {@link #getMValues()} returns a non-null array of values. * * @author Patrick Murris * @version $Id: ShapefileRecordPolygon.java 2303 2014-09-14 22:33:36Z dcollins $ */ -public class ShapefileRecordPolygon extends ShapefileRecordPolyline -{ - /** {@inheritDoc} */ - public ShapefileRecordPolygon(Shapefile shapeFile, ByteBuffer buffer) - { +public class ShapefileRecordPolygon extends ShapefileRecordPolyline { + + /** + * {@inheritDoc} + */ + public ShapefileRecordPolygon(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isPolygonRecord() - { + public boolean isPolygonRecord() { return true; } @@ -49,21 +51,18 @@ public boolean isPolygonRecord() * * @param xmlWriter XML writer to receive the generated KML. * - * @throws javax.xml.stream.XMLStreamException - * If an exception occurs while writing the KML + * @throws javax.xml.stream.XMLStreamException If an exception occurs while writing the KML * @throws java.io.IOException If an exception occurs while exporting the data. */ @Override - public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { Iterable outerBoundary = null; List> innerBoundaries = new ArrayList>(); // If the polygon has a "height" attribute, export as an extruded polygon. Double height = ShapefileUtils.extractHeightAttribute(this); - for (int i = 0; i < this.getNumberOfParts(); i++) - { + for (int i = 0; i < this.getNumberOfParts(); i++) { // Although the shapefile spec says that inner and outer boundaries can be listed in any order, it's // assumed here that inner boundaries are at least listed adjacent to their outer boundary, either // before or after it. The below code accumulates inner boundaries into the polygon until an @@ -72,35 +71,27 @@ public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStream // polygon is started. VecBuffer buffer = this.getCompoundPointBuffer().subBuffer(i); - if (WWMath.computeWindingOrderOfLocations(buffer.getLocations()).equals(AVKey.CLOCKWISE)) - { - if (outerBoundary == null) - { + if (WWMath.computeWindingOrderOfLocations(buffer.getLocations()).equals(AVKey.CLOCKWISE)) { + if (outerBoundary == null) { outerBoundary = buffer.getLocations(); - } - else - { + } else { this.exportPolygonAsKML(xmlWriter, outerBoundary, innerBoundaries, height); outerBoundary = this.getCompoundPointBuffer().getLocations(); innerBoundaries.clear(); } - } - else - { + } else { innerBoundaries.add(buffer.getLocations()); } } - if (outerBoundary != null && outerBoundary.iterator().hasNext()) - { + if (outerBoundary != null && outerBoundary.iterator().hasNext()) { this.exportPolygonAsKML(xmlWriter, outerBoundary, innerBoundaries, height); } } protected void exportPolygonAsKML(XMLStreamWriter xmlWriter, Iterable outerBoundary, - List> innerBoundaries, Double height) throws IOException, XMLStreamException - { + List> innerBoundaries, Double height) throws IOException, XMLStreamException { xmlWriter.writeStartElement("Placemark"); xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(Integer.toString(this.getRecordNumber())); @@ -109,16 +100,13 @@ protected void exportPolygonAsKML(XMLStreamWriter xmlWriter, Iterable innerBoundary : innerBoundaries) - { + for (Iterable innerBoundary : innerBoundaries) { xmlWriter.writeStartElement("innerBoundaryIs"); KMLExportUtil.exportBoundaryAsLinearRing(xmlWriter, innerBoundary, height); xmlWriter.writeEndElement(); // innerBoundaryIs diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolyline.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolyline.java index 3dd5591b80..edca40eaa3 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolyline.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRecordPolyline.java @@ -19,30 +19,32 @@ * sequence of two or more points. *

        * Polylines may have optional z-coordinates or m-coordinates that accompany each coordinate pair. If a Polyline has - * z-coordinates, then {@link #getZValues()} returns a non-null array of values. If a - * Polyline has m-coordinates, then {@link #getMValues()} returns a non-null array of values. + * z-coordinates, then {@link #getZValues()} returns a non-null array of values. If a Polyline + * has m-coordinates, then {@link #getMValues()} returns a non-null array of values. * * @author Patrick Murris * @version $Id: ShapefileRecordPolyline.java 2303 2014-09-14 22:33:36Z dcollins $ */ -public class ShapefileRecordPolyline extends ShapefileRecord -{ +public class ShapefileRecordPolyline extends ShapefileRecord { + protected double[] boundingRectangle; protected double[] zRange; // non-null only for Z types protected double[] zValues; // non-null only for Z types protected double[] mRange; // will be null if no measures protected double[] mValues; // will be null if no measures - /** {@inheritDoc} */ - public ShapefileRecordPolyline(Shapefile shapeFile, ByteBuffer buffer) - { + /** + * {@inheritDoc} + */ + public ShapefileRecordPolyline(Shapefile shapeFile, ByteBuffer buffer) { super(shapeFile, buffer); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isPolylineRecord() - { + public boolean isPolylineRecord() { return true; } @@ -53,8 +55,7 @@ public boolean isPolylineRecord() * * @return an {@link Iterable} over the points X and Y coordinates. */ - public Iterable getPoints(int partNumber) - { + public Iterable getPoints(int partNumber) { return this.getPointBuffer(partNumber).getCoords(); } @@ -63,8 +64,7 @@ public Iterable getPoints(int partNumber) * * @return the shape's Z range. The range minimum is at index 0, the maximum at index 1. */ - public double[] getZRange() - { + public double[] getZRange() { return this.zRange; } @@ -73,8 +73,7 @@ public double[] getZRange() * * @return the shape's Z values. */ - public double[] getZValues() - { + public double[] getZValues() { return this.zValues; } @@ -82,10 +81,9 @@ public double[] getZValues() * Returns the shape's optional measure range. * * @return the shape's measure range, or null if no measures are in the record. The range minimum is at index 0, the - * maximum at index 1. + * maximum at index 1. */ - public double[] getMRange() - { + public double[] getMRange() { return this.mRange; } @@ -94,62 +92,65 @@ public double[] getMRange() * * @return the shape's measure values, or null if no measures are in the record. */ - public double[] getMValues() - { + public double[] getMValues() { return this.mValues; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public double[] getBoundingRectangle() - { + public double[] getBoundingRectangle() { return this.boundingRectangle != null ? this.boundingRectangle : null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) - { + protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) { // Read the bounding rectangle. Shapefile.BoundingRectangle rect = shapefile.readBoundingRectangle(buffer); this.boundingRectangle = rect.coords; // Specify that the record's points should be normalized if the bounding rectangle is normalized. Ignore the // shapefile's normalizePoints property to avoid normalizing records that don't need it. - if (rect.isNormalized) + if (rect.isNormalized) { this.setNormalizePoints(true); + } // Read the number of parts and the number of points. this.numberOfParts = buffer.getInt(); this.numberOfPoints = buffer.getInt(); this.firstPartNumber = -1; - if (this.numberOfParts > 0 && this.numberOfPoints > 0) - { + if (this.numberOfParts > 0 && this.numberOfPoints > 0) { // Read the part positions. int[] partPositions = ShapefileUtils.readIntArray(buffer, this.numberOfParts); - for (int i = 0; i < this.numberOfParts; i++) - { + for (int i = 0; i < this.numberOfParts; i++) { int length = (i == this.numberOfParts - 1) ? this.numberOfPoints - partPositions[i] - : partPositions[i + 1] - partPositions[i]; + : partPositions[i + 1] - partPositions[i]; // Add the record's points to the Shapefile's point buffer, and record this record's part offset in the // Shapefile's point buffer. int offset = shapefile.addPoints(this, buffer, length); - if (this.firstPartNumber < 0) + if (this.firstPartNumber < 0) { this.firstPartNumber = offset; + } } } // Read the optional Z value. - if (this.isZType()) + if (this.isZType()) { this.readZ(buffer); + } // Read the optional measure value. - if (this.isMeasureType()) + if (this.isMeasureType()) { this.readOptionalMeasures(buffer); + } } /** @@ -157,8 +158,7 @@ protected void doReadFromBuffer(Shapefile shapefile, ByteBuffer buffer) * * @param buffer the record buffer to read from. */ - protected void readZ(ByteBuffer buffer) - { + protected void readZ(ByteBuffer buffer) { this.zRange = ShapefileUtils.readDoubleArray(buffer, 2); this.zValues = ShapefileUtils.readDoubleArray(buffer, this.getNumberOfPoints()); } @@ -168,11 +168,9 @@ protected void readZ(ByteBuffer buffer) * * @param buffer the record buffer to read from. */ - protected void readOptionalMeasures(ByteBuffer buffer) - { + protected void readOptionalMeasures(ByteBuffer buffer) { // Measure values are optional. - if (buffer.hasRemaining() && (buffer.limit() - buffer.position()) >= (this.getNumberOfPoints() * 8)) - { + if (buffer.hasRemaining() && (buffer.limit() - buffer.position()) >= (this.getNumberOfPoints() * 8)) { this.mRange = ShapefileUtils.readDoubleArray(buffer, 2); this.mValues = ShapefileUtils.readDoubleArray(buffer, this.getNumberOfPoints()); } @@ -183,15 +181,12 @@ protected void readOptionalMeasures(ByteBuffer buffer) * * @param xmlWriter XML writer to receive the generated KML. * - * @throws javax.xml.stream.XMLStreamException - * If an exception occurs while writing the KML + * @throws javax.xml.stream.XMLStreamException If an exception occurs while writing the KML * @throws java.io.IOException If an exception occurs while exporting the data. */ @Override - public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { - for (int i = 0; i < this.getNumberOfParts(); i++) - { + public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { + for (int i = 0; i < this.getNumberOfParts(); i++) { xmlWriter.writeStartElement("Placemark"); xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(Integer.toString(this.getRecordNumber())); @@ -212,16 +207,16 @@ public void exportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStream int index = 0; VecBuffer pointBuffer = this.getPointBuffer(i); - for (LatLon latLon : pointBuffer.getLocations()) - { + for (LatLon latLon : pointBuffer.getLocations()) { double z = 0.0; - if (zValues != null && index < zValues.length) + if (zValues != null && index < zValues.length) { z = zValues[index]; + } xmlWriter.writeCharacters(String.format(Locale.US, "%f,%f,%f ", - latLon.getLongitude().getDegrees(), - latLon.getLatitude().getDegrees(), - z)); + latLon.getLongitude().getDegrees(), + latLon.getLatitude().getDegrees(), + z)); index++; } diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRenderable.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRenderable.java index 37abf6af21..d961fcc558 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileRenderable.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileRenderable.java @@ -18,8 +18,8 @@ * @version $Id: ShapefileRenderable.java 3232 2015-06-20 04:08:11Z dcollins $ */ public abstract class ShapefileRenderable extends WWObjectImpl - implements Renderable, Iterable -{ + implements Renderable, Iterable { + /** * AttributeDelegate provides an entry point for configuring a ShapefileRenderable.Record's shape attributes and * key-value attributes during ShapefileRenderable construction. In particular, the dBASE attributes associated with @@ -29,8 +29,8 @@ public abstract class ShapefileRenderable extends WWObjectImpl * the ShapefileRenderable.Record passed to these methods, but should not modify the ShapefileRenderable without * synchronizing access with the thread used to create the ShapefileRenderable. */ - public interface AttributeDelegate - { + public interface AttributeDelegate { + /** * Entry point for configuring a ShapefileRenderable.Record's shape attributes and key-value attributes during * ShapefileRenderable construction. The ShapefileRecord's dBASE attributes are available only during the @@ -40,14 +40,14 @@ public interface AttributeDelegate * not modify the ShapefileRenderable without synchronizing access with the thread used to create the * ShapefileRenderable. * - * @param shapefileRecord The shapefile record used to create the ShapefileRenderable.Record. + * @param shapefileRecord The shapefile record used to create the ShapefileRenderable.Record. * @param renderableRecord The ShapefileRenderable.Record to assign attributes for. */ void assignAttributes(ShapefileRecord shapefileRecord, ShapefileRenderable.Record renderableRecord); } - public static class Record extends AVListImpl implements Highlightable - { + public static class Record extends AVListImpl implements Highlightable { + // Record properties. protected ShapefileRenderable shapefileRenderable; protected Sector sector; @@ -62,17 +62,14 @@ public static class Record extends AVListImpl implements Highlightable protected int numberOfParts; protected int numberOfPoints; - public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefileRecord) - { - if (shapefileRenderable == null) - { + public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefileRecord) { + if (shapefileRenderable == null) { String msg = Logging.getMessage("nullValue.RenderableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (shapefileRecord == null) - { + if (shapefileRecord == null) { String msg = Logging.getMessage("nullValue.RecordIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -80,95 +77,77 @@ public Record(ShapefileRenderable shapefileRenderable, ShapefileRecord shapefile this.shapefileRenderable = shapefileRenderable; this.sector = shapefileRecord.getBoundingRectangle() != null ? Sector.fromDegrees( - shapefileRecord.getBoundingRectangle()) : null; + shapefileRecord.getBoundingRectangle()) : null; this.pointBuffer = shapefileRecord.getShapeFile().getPointBuffer(); this.firstPartNumber = shapefileRecord.getFirstPartNumber(); this.numberOfParts = shapefileRecord.getNumberOfParts(); this.numberOfPoints = shapefileRecord.getNumberOfPoints(); } - public ShapefileRenderable getShapefileRenderable() - { + public ShapefileRenderable getShapefileRenderable() { return this.shapefileRenderable; } - public Sector getSector() - { + public Sector getSector() { return this.sector; } - public int getOrdinal() - { + public int getOrdinal() { return this.ordinal; } - public boolean isVisible() - { + public boolean isVisible() { return this.visible; } - public void setVisible(boolean visible) - { - if (this.visible != visible) - { + public void setVisible(boolean visible) { + if (this.visible != visible) { this.visible = visible; this.shapefileRenderable.recordDidChange(this); } } @Override - public boolean isHighlighted() - { + public boolean isHighlighted() { return this.highlighted; } @Override - public void setHighlighted(boolean highlighted) - { - if (this.highlighted != highlighted) - { + public void setHighlighted(boolean highlighted) { + if (this.highlighted != highlighted) { this.highlighted = highlighted; this.shapefileRenderable.recordDidChange(this); } } - public ShapeAttributes getAttributes() - { + public ShapeAttributes getAttributes() { return this.normalAttrs; } - public void setAttributes(ShapeAttributes normalAttrs) - { - if (this.normalAttrs != normalAttrs) - { + public void setAttributes(ShapeAttributes normalAttrs) { + if (this.normalAttrs != normalAttrs) { this.normalAttrs = normalAttrs; this.shapefileRenderable.recordDidChange(this); } } - public ShapeAttributes getHighlightAttributes() - { + public ShapeAttributes getHighlightAttributes() { return this.highlightAttrs; } - public void setHighlightAttributes(ShapeAttributes highlightAttrs) - { - if (this.highlightAttrs != highlightAttrs) - { + public void setHighlightAttributes(ShapeAttributes highlightAttrs) { + if (this.highlightAttrs != highlightAttrs) { this.highlightAttrs = highlightAttrs; this.shapefileRenderable.recordDidChange(this); } } - public int getBoundaryCount() - { + public int getBoundaryCount() { return this.numberOfParts; } - public VecBuffer getBoundaryPoints(int index) - { - if (index < 0 || index >= this.numberOfParts) - { + public VecBuffer getBoundaryPoints(int index) { + if (index < 0 || index >= this.numberOfParts) { String msg = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -180,10 +159,8 @@ public VecBuffer getBoundaryPoints(int index) } } - public Iterable getBoundaryPositions(int index) - { - if (index < 0 || index >= this.numberOfParts) - { + public Iterable getBoundaryPositions(int index) { + if (index < 0 || index >= this.numberOfParts) { String msg = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -205,8 +182,7 @@ public Iterable getBoundaryPositions(int index) protected static ShapeAttributes defaultAttributes; protected static ShapeAttributes defaultHighlightAttributes; - static - { + static { defaultAttributes = new BasicShapeAttributes(); defaultAttributes.setInteriorMaterial(Material.LIGHT_GRAY); defaultAttributes.setOutlineMaterial(Material.DARK_GRAY); @@ -222,20 +198,21 @@ public Iterable getBoundaryPositions(int index) * delegate enables callbacks during creation of each ShapefileRenderable.Record. See {@link AttributeDelegate} for * more information. * - * @param shapefile The shapefile to display. - * @param normalAttrs The normal attributes for each ShapefileRenderable.Record. May be null to use the - * default attributes. - * @param highlightAttrs The highlight attributes for each ShapefileRenderable.Record. May be null to use the - * default highlight attributes. + * @param shapefile The shapefile to display. + * @param normalAttrs The normal attributes for each ShapefileRenderable.Record. May be null to use the default + * attributes. + * @param highlightAttrs The highlight attributes for each ShapefileRenderable.Record. May be null to use the + * default highlight attributes. * @param attributeDelegate Optional callback for configuring each ShapefileRenderable.Record's shape attributes and - * key-value attributes. May be null. + * key-value attributes. May be null. */ protected void init(Shapefile shapefile, ShapeAttributes normalAttrs, ShapeAttributes highlightAttrs, - ShapefileRenderable.AttributeDelegate attributeDelegate) - { + ShapefileRenderable.AttributeDelegate attributeDelegate) { double[] boundingRect = shapefile.getBoundingRectangle(); if (boundingRect == null) // suppress record assembly for empty shapefiles + { return; + } this.sector = Sector.fromDegrees(boundingRect); this.initNormalAttrs = normalAttrs; @@ -244,16 +221,13 @@ protected void init(Shapefile shapefile, ShapeAttributes normalAttrs, ShapeAttri this.assembleRecords(shapefile); } - protected void assembleRecords(Shapefile shapefile) - { + protected void assembleRecords(Shapefile shapefile) { this.records = new ArrayList(); - while (shapefile.hasNext()) - { + while (shapefile.hasNext()) { ShapefileRecord shapefileRecord = shapefile.nextRecord(); - if (this.mustAssembleRecord(shapefileRecord)) - { + if (this.mustAssembleRecord(shapefileRecord)) { this.assembleRecord(shapefileRecord); } } @@ -261,49 +235,42 @@ protected void assembleRecords(Shapefile shapefile) this.records.trimToSize(); // Reduce memory overhead from unused ArrayList capacity. } - protected boolean mustAssembleRecord(ShapefileRecord shapefileRecord) - { + protected boolean mustAssembleRecord(ShapefileRecord shapefileRecord) { return shapefileRecord.getNumberOfParts() > 0 - && shapefileRecord.getNumberOfPoints() > 0 - && !shapefileRecord.isNullRecord(); + && shapefileRecord.getNumberOfPoints() > 0 + && !shapefileRecord.isNullRecord(); } - protected void assembleRecord(ShapefileRecord shapefileRecord) - { + protected void assembleRecord(ShapefileRecord shapefileRecord) { ShapefileRenderable.Record renderableRecord = new ShapefileRenderable.Record(this, shapefileRecord); this.addRecord(shapefileRecord, renderableRecord); } - protected void addRecord(ShapefileRecord shapefileRecord, ShapefileRenderable.Record renderableRecord) - { + protected void addRecord(ShapefileRecord shapefileRecord, ShapefileRenderable.Record renderableRecord) { renderableRecord.setAttributes(this.initNormalAttrs); renderableRecord.setHighlightAttributes(this.initHighlightAttrs); renderableRecord.ordinal = this.records.size(); this.records.add(renderableRecord); - if (this.initAttributeDelegate != null) - { + if (this.initAttributeDelegate != null) { this.initAttributeDelegate.assignAttributes(shapefileRecord, renderableRecord); } } - public Sector getSector() - { + public Sector getSector() { return this.sector; } - public int getRecordCount() - { - if (this.records == null) + public int getRecordCount() { + if (this.records == null) { return 0; + } return this.records.size(); } - public ShapefileRenderable.Record getRecord(int ordinal) - { - if (this.records == null || ordinal < 0 || ordinal >= this.records.size()) - { + public ShapefileRenderable.Record getRecord(int ordinal) { + if (this.records == null || ordinal < 0 || ordinal >= this.records.size()) { String msg = Logging.getMessage("generic.indexOutOfRange", ordinal); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -313,42 +280,33 @@ public ShapefileRenderable.Record getRecord(int ordinal) } @Override - public Iterator iterator() - { - if (this.records == null) + public Iterator iterator() { + if (this.records == null) { return Collections.emptyList().iterator(); + } return this.records.iterator(); } - public boolean isVisible() - { + public boolean isVisible() { return this.visible; } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.visible = visible; } - protected void recordDidChange(ShapefileRenderable.Record record) - { + protected void recordDidChange(ShapefileRenderable.Record record) { // Intentionally left empty. May be overridden by subclass. } - protected ShapeAttributes determineActiveAttributes(ShapefileRenderable.Record record) - { - if (record.highlighted) - { + protected ShapeAttributes determineActiveAttributes(ShapefileRenderable.Record record) { + if (record.highlighted) { return record.highlightAttrs != null ? record.highlightAttrs : defaultHighlightAttributes; - } - else if (record.normalAttrs != null) - { + } else if (record.normalAttrs != null) { return record.normalAttrs; - } - else - { + } else { return defaultAttributes; } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/shapefile/ShapefileUtils.java b/src/gov/nasa/worldwind/formats/shapefile/ShapefileUtils.java index 7a0e6212cc..2b714cae23 100644 --- a/src/gov/nasa/worldwind/formats/shapefile/ShapefileUtils.java +++ b/src/gov/nasa/worldwind/formats/shapefile/ShapefileUtils.java @@ -19,12 +19,10 @@ * @author Patrick Murris * @version $Id: ShapefileUtils.java 2068 2014-06-20 21:33:09Z dcollins $ */ -public class ShapefileUtils -{ - public static Shapefile openZippedShapefile(File file) - { - if (file == null) - { +public class ShapefileUtils { + + public static Shapefile openZippedShapefile(File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -33,43 +31,32 @@ public static Shapefile openZippedShapefile(File file) InputStream shpStream = null, shxStream = null, dbfStream = null, prjStream = null; ZipFile zipFile; - try - { + try { zipFile = new ZipFile(file); Enumeration zipEntries = zipFile.entries(); - while (zipEntries.hasMoreElements()) - { + while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); - if (entry == null) + if (entry == null) { continue; + } - if (entry.getName().toLowerCase().endsWith(Shapefile.SHAPE_FILE_SUFFIX)) - { + if (entry.getName().toLowerCase().endsWith(Shapefile.SHAPE_FILE_SUFFIX)) { shpStream = zipFile.getInputStream(entry); - } - else if (entry.getName().toLowerCase().endsWith(Shapefile.INDEX_FILE_SUFFIX)) - { + } else if (entry.getName().toLowerCase().endsWith(Shapefile.INDEX_FILE_SUFFIX)) { shxStream = zipFile.getInputStream(entry); - } - else if (entry.getName().toLowerCase().endsWith(Shapefile.ATTRIBUTE_FILE_SUFFIX)) - { + } else if (entry.getName().toLowerCase().endsWith(Shapefile.ATTRIBUTE_FILE_SUFFIX)) { dbfStream = zipFile.getInputStream(entry); - } - else if (entry.getName().toLowerCase().endsWith(Shapefile.PROJECTION_FILE_SUFFIX)) - { + } else if (entry.getName().toLowerCase().endsWith(Shapefile.PROJECTION_FILE_SUFFIX)) { prjStream = zipFile.getInputStream(entry); } } - } - catch (Exception e) - { + } catch (Exception e) { throw new WWRuntimeException( - Logging.getMessage("generic.ExceptionAttemptingToReadFrom", file.getPath()), e); + Logging.getMessage("generic.ExceptionAttemptingToReadFrom", file.getPath()), e); } - if (shpStream == null) - { + if (shpStream == null) { String message = Logging.getMessage("SHP.UnrecognizedShapefile", file.getPath()); Logging.logger().severe(message); throw new WWUnrecognizedException(message); @@ -81,25 +68,22 @@ else if (entry.getName().toLowerCase().endsWith(Shapefile.PROJECTION_FILE_SUFFIX /** * Reads and returns an array of integers from a byte buffer. * - * @param buffer the byte buffer to read from. + * @param buffer the byte buffer to read from. * @param numEntries the number of integers to read. * * @return the integers read. * * @throws IllegalArgumentException if the specified buffer reference is null. */ - public static int[] readIntArray(ByteBuffer buffer, int numEntries) - { - if (buffer == null) - { + public static int[] readIntArray(ByteBuffer buffer, int numEntries) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int[] array = new int[numEntries]; - for (int i = 0; i < numEntries; i++) - { + for (int i = 0; i < numEntries; i++) { array[i] = buffer.getInt(); } @@ -109,25 +93,22 @@ public static int[] readIntArray(ByteBuffer buffer, int numEntries) /** * Reads and returns an array of doubles from a byte buffer. * - * @param buffer the byte buffer to read from. + * @param buffer the byte buffer to read from. * @param numEntries the number of doubles to read. * * @return the doubles read. * * @throws IllegalArgumentException if the specified buffer reference is null. */ - public static double[] readDoubleArray(ByteBuffer buffer, int numEntries) - { - if (buffer == null) - { + public static double[] readDoubleArray(ByteBuffer buffer, int numEntries) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } double[] array = new double[numEntries]; - for (int i = 0; i < numEntries; i++) - { + for (int i = 0; i < numEntries; i++) { array[i] = buffer.getDouble(); } @@ -141,23 +122,25 @@ public static double[] readDoubleArray(ByteBuffer buffer, int numEntries) * * @return the height value if a height attribute is found, otherwise null. */ - public static Double extractHeightAttribute(ShapefileRecord record) - { - if (record.getAttributes() == null) + public static Double extractHeightAttribute(ShapefileRecord record) { + if (record.getAttributes() == null) { return null; + } - for (Map.Entry attr : record.getAttributes().getEntries()) - { + for (Map.Entry attr : record.getAttributes().getEntries()) { String hKey = attr.getKey().trim().toLowerCase(); - if (!(hKey.equals("height") || hKey.equals("hgt"))) + if (!(hKey.equals("height") || hKey.equals("hgt"))) { continue; + } Object o = attr.getValue(); - if (o instanceof Number) + if (o instanceof Number) { return ((Number) o).doubleValue(); + } - if (o instanceof String) + if (o instanceof String) { return WWUtil.convertStringToDouble(o.toString()); + } } return null; @@ -170,16 +153,14 @@ public static Double extractHeightAttribute(ShapefileRecord record) * * @return true if the shapefile's records contain a height attribute, otherwise false. */ - public static boolean hasHeightAttribute(Shapefile shapefile) - { + public static boolean hasHeightAttribute(Shapefile shapefile) { Set attrNames = shapefile.getAttributeNames(); - if (attrNames == null) + if (attrNames == null) { return false; + } - for (String name : attrNames) - { - if (name.equalsIgnoreCase("height") || name.equalsIgnoreCase("hgt")) - { + for (String name : attrNames) { + if (name.equalsIgnoreCase("height") || name.equalsIgnoreCase("hgt")) { return true; } } diff --git a/src/gov/nasa/worldwind/formats/tab/TABRasterReader.java b/src/gov/nasa/worldwind/formats/tab/TABRasterReader.java index bb8d35c4a7..dac51fbd1b 100644 --- a/src/gov/nasa/worldwind/formats/tab/TABRasterReader.java +++ b/src/gov/nasa/worldwind/formats/tab/TABRasterReader.java @@ -9,15 +9,14 @@ import gov.nasa.worldwind.util.*; /** - * Reader for the MapInfo TAB file format. - * Documentation on the MapInfo TAB format can be found here: + * Reader for the MapInfo TAB file format. Documentation on the MapInfo TAB format can be found here: * https://en.wikipedia.org/wiki/MapInfo_TAB_format * * @author dcollins * @version $Id: TABRasterReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TABRasterReader -{ +public class TABRasterReader { + public static final String VERSION = "TABRaster.Version"; public static final String CHARSET = "TABRaster.Charset"; public static final String TYPE = "TABRaster.Type"; @@ -32,7 +31,7 @@ public class TABRasterReader public static final String RASTER_STYLE_GRID_VALUE = "TABRaster.RasterStyleGridValue"; public static final String RASTER_STYLE_TRANSPARENT_COLOR_VALUE = "TABRaster.TransparentColorValue"; public static final String RASTER_STYLE_TRANSLUCENT_ALPHA_VALUE = "TABRaster.TranslucentAlphaValue"; - + protected static final String TAG_DEFINITION = "Definition"; protected static final String TAG_FILE = "File"; protected static final String TAG_HEADER_TABLE = "!table"; @@ -50,37 +49,32 @@ public class TABRasterReader protected static final int RASTER_STYLE_ID_TRANSPARENT_COLOR_VALUE = 7; protected static final int RASTER_STYLE_ID_TRANSLUCENT_ALPHA_VALUE = 8; - public TABRasterReader() - { + public TABRasterReader() { } - public static java.io.File getTABFileFor(java.io.File file) - { - if (file == null) - { + public static java.io.File getTABFileFor(java.io.File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.io.File parent = file.getParentFile(); - if (parent == null) + if (parent == null) { return null; + } String tabFilename = WWIO.replaceSuffix(file.getName(), ".tab"); // The file already has a TAB extension. Rather than returning a self reference, we return null to deonte that // a TAB file does not associate with itself. - if (file.getName().equalsIgnoreCase(tabFilename)) - { + if (file.getName().equalsIgnoreCase(tabFilename)) { return null; } // Find the first sibling with the matching filename, and TAB extension. - for (java.io.File child : parent.listFiles()) - { - if (!child.equals(file) && child.getName().equalsIgnoreCase(tabFilename)) - { + for (java.io.File child : parent.listFiles()) { + if (!child.equals(file) && child.getName().equalsIgnoreCase(tabFilename)) { return child; } } @@ -88,172 +82,139 @@ public static java.io.File getTABFileFor(java.io.File file) return null; } - public boolean canRead(java.io.File file) - { - if (file == null || !file.exists() || !file.canRead()) + public boolean canRead(java.io.File file) { + if (file == null || !file.exists() || !file.canRead()) { return false; + } java.io.FileReader fileReader = null; - try - { + try { fileReader = new java.io.FileReader(file); RasterControlPointList controlPoints = new RasterControlPointList(); return this.doCanRead(fileReader, controlPoints); - } - catch (Exception ignored) - { + } catch (Exception ignored) { return false; - } - finally - { + } finally { //noinspection EmptyCatchBlock - try - { - if (fileReader != null) + try { + if (fileReader != null) { fileReader.close(); - } - catch (java.io.IOException e) - { + } + } catch (java.io.IOException e) { } } } - public boolean canRead(String path) - { - if (path == null) + public boolean canRead(String path) { + if (path == null) { return false; + } Object streamOrException = WWIO.getFileOrResourceAsStream(path, this.getClass()); - if (streamOrException == null || streamOrException instanceof Exception) + if (streamOrException == null || streamOrException instanceof Exception) { return false; + } java.io.InputStream stream = (java.io.InputStream) streamOrException; - try - { + try { java.io.InputStreamReader streamReader = new java.io.InputStreamReader(stream); RasterControlPointList controlPoints = new RasterControlPointList(); return this.doCanRead(streamReader, controlPoints); - } - catch (Exception ignored) - { + } catch (Exception ignored) { return false; - } - finally - { + } finally { WWIO.closeStream(stream, path); } } - public RasterControlPointList read(java.io.File file) throws java.io.IOException - { - if (file == null) - { + public RasterControlPointList read(java.io.File file) throws java.io.IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.canRead()) - { + if (!file.canRead()) { String message = Logging.getMessage("generic.FileNoReadPermission", file); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.io.FileReader fileReader = null; - try - { + try { fileReader = new java.io.FileReader(file); RasterControlPointList controlPoints = new RasterControlPointList(); this.doRead(fileReader, file.getParent(), controlPoints); return controlPoints; - } - finally - { + } finally { WWIO.closeStream(fileReader, file.getPath()); } } - public RasterControlPointList read(String path) throws java.io.IOException - { - if (path == null) - { + public RasterControlPointList read(String path) throws java.io.IOException { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object streamOrException = WWIO.getFileOrResourceAsStream(path, this.getClass()); - if (streamOrException == null || streamOrException instanceof Exception) - { + if (streamOrException == null || streamOrException instanceof Exception) { String message = Logging.getMessage("generic.ExceptionAttemptingToReadFile", - (streamOrException != null) ? streamOrException : path); + (streamOrException != null) ? streamOrException : path); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.io.InputStream stream = (java.io.InputStream) streamOrException; - try - { + try { java.io.InputStreamReader streamReader = new java.io.InputStreamReader(stream); String workingDirectory = WWIO.getParentFilePath(path); - + RasterControlPointList controlPoints = new RasterControlPointList(); this.doRead(streamReader, workingDirectory, controlPoints); return controlPoints; - } - finally - { + } finally { WWIO.closeStream(stream, path); } } - protected boolean doCanRead(java.io.Reader reader, RasterControlPointList controlPoints) - { - if (reader == null) - { + protected boolean doCanRead(java.io.Reader reader, RasterControlPointList controlPoints) { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { java.io.BufferedReader br = new java.io.BufferedReader(reader); this.readHeader(br, controlPoints); String s = this.validateHeaderValues(controlPoints); return (s == null); - } - catch (Exception e) - { + } catch (Exception e) { return false; } } protected void doRead(java.io.Reader reader, String workingDirectory, RasterControlPointList controlPoints) - throws java.io.IOException - { - if (reader == null) - { + throws java.io.IOException { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -264,16 +225,14 @@ protected void doRead(java.io.Reader reader, String workingDirectory, RasterCont this.readDefinitionTable(br, workingDirectory, controlPoints); String s = this.validateHeaderValues(controlPoints); - if (s != null) - { + if (s != null) { String message = Logging.getMessage("TABReader.MissingHeaderValues", s); Logging.logger().severe(message); throw new java.io.IOException(message); } s = this.validateRasterControlPoints(controlPoints); - if (s != null) - { + if (s != null) { String message = Logging.getMessage("TABReader.MissingRasterData", s); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -281,73 +240,64 @@ protected void doRead(java.io.Reader reader, String workingDirectory, RasterCont } protected void readHeader(java.io.BufferedReader reader, RasterControlPointList controlPoints) - throws java.io.IOException - { - if (reader == null) - { + throws java.io.IOException { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String line = this.skipToHeader(reader); - if (line == null || !line.equalsIgnoreCase(TAG_HEADER_TABLE)) - { + if (line == null || !line.equalsIgnoreCase(TAG_HEADER_TABLE)) { String message = Logging.getMessage("TABReader.InvalidMagicString", line); Logging.logger().severe(message); throw new java.io.IOException(message); } line = this.nextLine(reader); - if (line != null && line.startsWith(TAG_HEADER_VERSION)) - { - if (controlPoints.getValue(VERSION) == null) + if (line != null && line.startsWith(TAG_HEADER_VERSION)) { + if (controlPoints.getValue(VERSION) == null) { setProperty(line, VERSION, controlPoints); + } } line = this.nextLine(reader); - if (line != null && line.startsWith(TAG_HEADER_CHARSET)) - { - if (controlPoints.getValue(CHARSET) == null) + if (line != null && line.startsWith(TAG_HEADER_CHARSET)) { + if (controlPoints.getValue(CHARSET) == null) { setProperty(line, CHARSET, controlPoints); + } } } protected void readDefinitionTable(java.io.BufferedReader reader, String workingDirectory, - RasterControlPointList controlPoints) throws java.io.IOException - { - if (reader == null) - { + RasterControlPointList controlPoints) throws java.io.IOException { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String line = this.skipToDefinition(reader); - if (line == null || !line.equalsIgnoreCase(TAG_TABLE)) + if (line == null || !line.equalsIgnoreCase(TAG_TABLE)) { return; + } line = this.nextLine(reader); - if (line != null && line.startsWith(TAG_FILE)) - { + if (line != null && line.startsWith(TAG_FILE)) { if (controlPoints.getStringValue(IMAGE_PATH) == null - || controlPoints.getStringValue(IMAGE_PATH).length() == 0) - { + || controlPoints.getStringValue(IMAGE_PATH).length() == 0) { String[] tokens = line.split(" ", 2); - if (tokens.length >= 2 && tokens[1] != null) - { + if (tokens.length >= 2 && tokens[1] != null) { String pathname = stripQuotes(tokens[1].trim()); controlPoints.setValue(IMAGE_PATH, WWIO.appendPathPart(workingDirectory, pathname)); } @@ -355,10 +305,10 @@ protected void readDefinitionTable(java.io.BufferedReader reader, String working } line = this.nextLine(reader); - if (line != null && line.startsWith(TAG_TYPE)) - { - if (controlPoints.getValue(TYPE) == null) + if (line != null && line.startsWith(TAG_TYPE)) { + if (controlPoints.getValue(TYPE) == null) { setProperty(line, TYPE, controlPoints); + } } this.readControlPoints(reader, controlPoints); @@ -367,28 +317,24 @@ protected void readDefinitionTable(java.io.BufferedReader reader, String working } protected void readControlPoints(java.io.BufferedReader reader, RasterControlPointList controlPoints) - throws java.io.IOException - { - if (reader == null) - { + throws java.io.IOException { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.util.regex.Pattern pattern = java.util.regex.Pattern.compile( - "[(](.+)[,](.+)[)].+[(](.+)[,](.+)[)][\\s]+.+[\\s]+[\"\']?(.+)[\"\']?[,]?"); + "[(](.+)[,](.+)[)].+[(](.+)[,](.+)[)][\\s]+.+[\\s]+[\"\']?(.+)[\"\']?[,]?"); String line; java.util.regex.Matcher matcher; - while ((line = this.nextLine(reader)) != null && (matcher = pattern.matcher(line)).matches()) - { + while ((line = this.nextLine(reader)) != null && (matcher = pattern.matcher(line)).matches()) { String swx = matcher.group(1); String swy = matcher.group(2); String srx = matcher.group(3); @@ -400,10 +346,9 @@ protected void readControlPoints(java.io.BufferedReader reader, RasterControlPoi Double rx = WWUtil.convertStringToDouble(srx); Double ry = WWUtil.convertStringToDouble(sry); - if (wx != null && wy != null && rx != null && ry != null) - { - RasterControlPointList.ControlPoint controlPoint = - new RasterControlPointList.ControlPoint(wx, wy, rx, ry); + if (wx != null && wy != null && rx != null && ry != null) { + RasterControlPointList.ControlPoint controlPoint + = new RasterControlPointList.ControlPoint(wx, wy, rx, ry); controlPoint.setValue(LABEL, label); controlPoints.add(controlPoint); } @@ -411,16 +356,13 @@ protected void readControlPoints(java.io.BufferedReader reader, RasterControlPoi } protected void readCoordSys(java.io.BufferedReader reader, RasterControlPointList controlPoints) - throws java.io.IOException - { - if (reader == null) - { + throws java.io.IOException { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -431,10 +373,8 @@ protected void readCoordSys(java.io.BufferedReader reader, RasterControlPointLis @SuppressWarnings({"UnusedDeclaration"}) protected void readRasterStyle(java.io.BufferedReader reader, RasterControlPointList controlPoints) - throws java.io.IOException - { - if (controlPoints == null) - { + throws java.io.IOException { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.RasterControlPointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -443,106 +383,106 @@ protected void readRasterStyle(java.io.BufferedReader reader, RasterControlPoint // TODO } - protected String skipToHeader(java.io.BufferedReader reader) throws java.io.IOException - { + protected String skipToHeader(java.io.BufferedReader reader) throws java.io.IOException { return this.nextLine(reader); } - protected String skipToDefinition(java.io.BufferedReader reader) throws java.io.IOException - { + protected String skipToDefinition(java.io.BufferedReader reader) throws java.io.IOException { String line = this.nextLine(reader); - if (line == null || line.length() == 0) + if (line == null || line.length() == 0) { return null; + } String[] tokens = line.split(" ", 2); - if (tokens.length < 2) + if (tokens.length < 2) { return null; + } return (tokens[1] != null) ? tokens[1].trim() : null; } - protected String nextLine(java.io.BufferedReader reader) throws java.io.IOException - { + protected String nextLine(java.io.BufferedReader reader) throws java.io.IOException { // Read until the next non-whitespace line. String line; - while ((line = reader.readLine()) != null && line.trim().length() == 0) - { + while ((line = reader.readLine()) != null && line.trim().length() == 0) { } return (line != null) ? line.trim() : null; } - protected String validateHeaderValues(AVList values) - { + protected String validateHeaderValues(AVList values) { StringBuilder sb = new StringBuilder(); String s = values.getStringValue(VERSION); - if (s == null || s.length() == 0) - { - if (sb.length() > 0) + if (s == null || s.length() == 0) { + if (sb.length() > 0) { sb.append(", "); + } sb.append(Logging.getMessage("term.version")); } s = values.getStringValue(CHARSET); - if (s == null || s.length() == 0) - { - if (sb.length() > 0) + if (s == null || s.length() == 0) { + if (sb.length() > 0) { sb.append(", "); + } sb.append(Logging.getMessage("term.charset")); } - if (sb.length() > 0) + if (sb.length() > 0) { return sb.toString(); + } return null; } - protected String validateRasterControlPoints(RasterControlPointList controlPoints) - { + protected String validateRasterControlPoints(RasterControlPointList controlPoints) { StringBuilder sb = new StringBuilder(); - if (controlPoints.getStringValue(IMAGE_PATH) == null && controlPoints.getStringValue(IMAGE_PATH).length() == 0) - { - if (sb.length() > 0) + if (controlPoints.getStringValue(IMAGE_PATH) == null && controlPoints.getStringValue(IMAGE_PATH).length() == 0) { + if (sb.length() > 0) { sb.append(", "); + } sb.append(Logging.getMessage("TABReader.MissingOrInvalidFileName", - controlPoints.getStringValue(IMAGE_PATH))); + controlPoints.getStringValue(IMAGE_PATH))); } - if (controlPoints.size() < 3) - { - if (sb.length() > 0) + if (controlPoints.size() < 3) { + if (sb.length() > 0) { sb.append(", "); + } sb.append(Logging.getMessage("TABReader.NotEnoughControlPoints", controlPoints.size())); } - if (sb.length() > 0) + if (sb.length() > 0) { return sb.toString(); + } return null; } - private static String stripQuotes(String s) - { - if (s.startsWith("\"") || s.startsWith("\'")) + private static String stripQuotes(String s) { + if (s.startsWith("\"") || s.startsWith("\'")) { s = s.substring(1, s.length()); - if (s.endsWith("\"") || s.endsWith("\'")) + } + if (s.endsWith("\"") || s.endsWith("\'")) { s = s.substring(0, s.length() - 1); + } return s; } - private static void setProperty(String line, String key, AVList values) - { + private static void setProperty(String line, String key, AVList values) { String[] tokens = line.split(" ", 2); - if (tokens == null || tokens.length < 2) + if (tokens == null || tokens.length < 2) { return; + } String value = tokens[1]; - if (value == null || value.trim().length() == 0) + if (value == null || value.trim().length() == 0) { return; + } values.setValue(key, value.trim()); } diff --git a/src/gov/nasa/worldwind/formats/tiff/BaselineTiff.java b/src/gov/nasa/worldwind/formats/tiff/BaselineTiff.java index 9dbf43ec7b..ec6c3c11ed 100644 --- a/src/gov/nasa/worldwind/formats/tiff/BaselineTiff.java +++ b/src/gov/nasa/worldwind/formats/tiff/BaselineTiff.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.tiff; import gov.nasa.worldwind.util.Logging; @@ -14,8 +13,8 @@ * @author Lado Garakanidze * @version $Id: BaselineTiff.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class BaselineTiff -{ +class BaselineTiff { + public int width = Tiff.Undefined; public int height = Tiff.Undefined; public int samplesPerPixel = Tiff.Undefined; @@ -33,25 +32,19 @@ class BaselineTiff public String softwareVersion = null; public String dateTime = null; - private BaselineTiff() - { + private BaselineTiff() { } - public static BaselineTiff extract(TiffIFDEntry[] ifd, TIFFReader tiffReader) - { - if (null == ifd || null == tiffReader) - { + public static BaselineTiff extract(TiffIFDEntry[] ifd, TIFFReader tiffReader) { + if (null == ifd || null == tiffReader) { return null; } BaselineTiff tiff = new BaselineTiff(); - for (TiffIFDEntry entry : ifd) - { - try - { - switch (entry.tag) - { + for (TiffIFDEntry entry : ifd) { + try { + switch (entry.tag) { // base TIFF tags case Tiff.Tag.IMAGE_WIDTH: tiff.width = (int) entry.asLong(); @@ -109,9 +102,7 @@ public static BaselineTiff extract(TiffIFDEntry[] ifd, TIFFReader tiffReader) tiff.maxSampleValue = entry.asShort(); break; } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().finest(e.toString()); } } @@ -119,8 +110,7 @@ public static BaselineTiff extract(TiffIFDEntry[] ifd, TIFFReader tiffReader) } @Override - public String toString() - { + public String toString() { StringBuffer sb = new StringBuffer("{ "); sb.append("width=").append(this.width).append(", "); sb.append("height=").append(this.height).append(", "); @@ -130,27 +120,23 @@ public String toString() sb.append("planarConfig=").append(this.planarConfig).append(", "); sb.append("sampleFormat=( "); - if (null != this.sampleFormat) - { - for (int i = 0; i < this.sampleFormat.length; i++) - { + if (null != this.sampleFormat) { + for (int i = 0; i < this.sampleFormat.length; i++) { sb.append(this.sampleFormat[i]).append(" "); } - } - else + } else { sb.append(" NULL "); + } sb.append("), "); sb.append("bitsPerSample=( "); - if (null != this.bitsPerSample) - { - for (int i = 0; i < this.bitsPerSample.length; i++) - { + if (null != this.bitsPerSample) { + for (int i = 0; i < this.bitsPerSample.length; i++) { sb.append(this.bitsPerSample[i]).append(" "); } - } - else + } else { sb.append(" NULL "); + } sb.append("), "); sb.append("displayName=").append(this.displayName).append(", "); diff --git a/src/gov/nasa/worldwind/formats/tiff/GeoCodec.java b/src/gov/nasa/worldwind/formats/tiff/GeoCodec.java index c1cf744669..790a8f9aa5 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeoCodec.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeoCodec.java @@ -17,8 +17,8 @@ * @author brownrigg * @version $Id: GeoCodec.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class GeoCodec -{ +class GeoCodec { + private HashMap geoKeys = null; // Collection of ModelTiePoints. @@ -35,9 +35,7 @@ class GeoCodec private double[] doubleParams; // raw double parameters array private byte[] asciiParams; // raw ascii parameters array - - public GeoCodec() - { + public GeoCodec() { } @@ -47,29 +45,24 @@ public GeoCodec() * @param values A 6-tuple representing a Geotiff ModelTiePoint. * @throws IllegalArgumentException if values not a multiple of 6. */ - public void addModelTiePoints(double[] values) throws IllegalArgumentException - { - if (values == null || values.length == 0 || (values.length % 6) != 0) - { + public void addModelTiePoints(double[] values) throws IllegalArgumentException { + if (values == null || values.length == 0 || (values.length % 6) != 0) { String message = Logging.getMessage("GeoCodec.BadTiePoints"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } - for (int i = 0; i < values.length; i += 6) - { + for (int i = 0; i < values.length; i += 6) { addModelTiePoint(values[i], values[i + 1], values[i + 2], values[i + 3], values[i + 4], values[i + 5]); } } - public void addModelTiePoint(double i, double j, double k, double x, double y, double z) - { + public void addModelTiePoint(double i, double j, double k, double x, double y, double z) { ModelTiePoint t = new ModelTiePoint(i, j, k, x, y, z); this.tiePoints.add(t); } - public ModelTiePoint[] getTiePoints() - { + public ModelTiePoint[] getTiePoints() { ModelTiePoint[] tiePoints = new ModelTiePoint[this.tiePoints.size()]; return this.tiePoints.toArray(tiePoints); } @@ -80,32 +73,27 @@ public ModelTiePoint[] getTiePoints() * @param values The ModelPixelScale values. * @throws IllegalArgumentException if values is not of length 3. */ - public void setModelPixelScale(double[] values) - { - if (values == null || values.length != 3) - { + public void setModelPixelScale(double[] values) { + if (values == null || values.length != 3) { String message = Logging.getMessage("GeoCodec.BadPixelValues"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } - this.setModelPixelScale( values[0], values[1], values[2] ); + this.setModelPixelScale(values[0], values[1], values[2]); } - public void setModelPixelScale(double xScale, double yScale, double zScale) - { + public void setModelPixelScale(double xScale, double yScale, double zScale) { this.xScale = xScale; this.yScale = yScale; this.zScale = zScale; } - public double getModelPixelScaleX() - { + public double getModelPixelScaleX() { return this.xScale; } - public double getModelPixelScaleY() - { + public double getModelPixelScaleY() { return this.yScale; } @@ -115,33 +103,28 @@ public double getModelPixelScaleY() * @param matrix A logical 4x4 matrix, in row-major order. * @throws IllegalArgumentException if matrix is not of length 16. */ - public void setModelTransformation(double[] matrix) throws IllegalArgumentException - { - if (matrix == null || matrix.length != 16) - { + public void setModelTransformation(double[] matrix) throws IllegalArgumentException { + if (matrix == null || matrix.length != 16) { String message = Logging.getMessage("GeoCodec.BadMatrix"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } - this.setModelTransformation( Matrix.fromArray(matrix, 0, true) ); + this.setModelTransformation(Matrix.fromArray(matrix, 0, true)); } - public void setModelTransformation(Matrix matrix) - { + public void setModelTransformation(Matrix matrix) { this.modelTransform = matrix; // There could be only ModelTransformation (34264) or ModelTiePoints (33922) & ModelPixelScale(3355) // If we are here, we have ModelTransformation, // so let's calculate ModelTiePoints of the image origin (0,0) - - Matrix tp = this.modelTransform.multiply( Matrix.fromTranslation( 0d, 0d, 0d )); - this.addModelTiePoint( 0d, 0d, 0d, tp.m14, tp.m24, tp.m34 ); + Matrix tp = this.modelTransform.multiply(Matrix.fromTranslation(0d, 0d, 0d)); + this.addModelTiePoint(0d, 0d, 0d, tp.m14, tp.m24, tp.m34); // Now, since ModelTiePoints (33922) & ModelPixelScale(3355) always go together // let's set ModelPixelScale values - - this.setModelPixelScale( matrix.m11 , matrix.m22, 0d ); + this.setModelPixelScale(matrix.m11, matrix.m22, 0d); } /** @@ -151,18 +134,17 @@ public void setModelTransformation(Matrix matrix) * upper-left corner [2] is x coordinate of lower-right corner [3] is y coordinate of lower-right corner Note that * coordinate units are those of the underlying modeling transformation, and are not guaranteed to be in lon/lat. * - * @param width Width of a hypothetical image. + * @param width Width of a hypothetical image. * @param height Height of a hypothetical image. * @return Returns xUL, yUL, xLR, yLR of bounding box. * @throws UnsupportedOperationException if georeferencing can not be computed. */ - public double[] getBoundingBox(int width, int height) throws UnsupportedOperationException - { + public double[] getBoundingBox(int width, int height) throws UnsupportedOperationException { double[] bbox = new double[4]; double[] pnt = getXYAtPixel(0, 0); bbox[0] = pnt[0]; bbox[1] = pnt[1]; - pnt = getXYAtPixel( height, width); + pnt = getXYAtPixel(height, width); bbox[2] = pnt[0]; bbox[3] = pnt[1]; return bbox; @@ -174,20 +156,18 @@ public double[] getBoundingBox(int width, int height) throws UnsupportedOperatio *

        * TODO: Also throws UnsupportedOperationException if this is anything other than a "simple" georeferenced mapping, * meaning that there's a single tie-point known about the point 0,0, we know the inter-pixel spacing, and there's - * no rotation of the image required. Geo referencing may also be specified via a general 4x4 matrix, or by a list + * no rotation of the image required. Geo referencing may also be specified via a general 4x4 matrix, or by a list * if tie-points, implying a rubbersheeting transformation. These two cases remain to be implemented. *

        * * @param row pixel-row index * @param col pixel-column index * @return double[2] containing x,y coordinate of pixel in modelling coordinate units. - * @throws IllegalArgumentException if row or column outside image bounds. + * @throws IllegalArgumentException if row or column outside image bounds. * @throws UnsupportedOperationException if georeferencing can not be determined. */ - public double[] getXYAtPixel(int row, int col) throws UnsupportedOperationException - { - if (this.tiePoints.size() == 0 ) - { + public double[] getXYAtPixel(int row, int col) throws UnsupportedOperationException { + if (this.tiePoints.size() == 0) { String message = Logging.getMessage("GeotiffReader.NotSimpleGeotiff"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); @@ -210,22 +190,18 @@ public double[] getXYAtPixel(int row, int col) throws UnsupportedOperationExcept * @return Array of int values associated with the key, or null if the key was not found. * @throws IllegalArgumentException Thrown if the key does not embody integer values. */ - public int[] getGeoKeyAsInts(int key) throws IllegalArgumentException - { + public int[] getGeoKeyAsInts(int key) throws IllegalArgumentException { int[] vals = null; GeoKeyEntry entry; - if (this.geoKeys != null && (entry = this.geoKeys.get(key)) != null) - { - if (entry.array != this.shortParams) - { + if (this.geoKeys != null && (entry = this.geoKeys.get(key)) != null) { + if (entry.array != this.shortParams) { String message = Logging.getMessage("GeoCodec.NotIntegerKey", key); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } vals = new int[entry.count]; - for (int i = 0; i < vals.length; i++) - { + for (int i = 0; i < vals.length; i++) { vals[i] = 0xffff & (int) this.shortParams[entry.offset + i]; } } @@ -236,52 +212,47 @@ public int[] getGeoKeyAsInts(int key) throws IllegalArgumentException /* * Returns true if the given key is a GeoKey in this file; false otherwise. */ - public boolean hasGeoKey(int key) - { + public boolean hasGeoKey(int key) { return (this.geoKeys != null && this.geoKeys.get(key) != null); } // // Package visibility. Not generally intended for use by end users. // - void setGeokeys(short[] keys) - { + void setGeokeys(short[] keys) { // Decode the geokey entries into our internal management structure. Recall that the keys are organized as // entries of 4 shorts, where the first 4-tuple contains versioning and the number of geokeys to follow. // The remaining entries look very much like regular Tiff tags. - if (keys != null && keys.length > 4) - { + if (keys != null && keys.length > 4) { this.shortParams = new short[keys.length]; System.arraycopy(keys, 0, this.shortParams, 0, keys.length); int numKeys = keys[3]; this.geoKeys = new HashMap(); int i = 0; - for (int k = 0; k < numKeys; k++ ) - { + for (int k = 0; k < numKeys; k++) { i += 4; int tag = 0x0000ffff & keys[i]; int tagLoc = 0x0000ffff & keys[i + 1]; - if (tagLoc == 0) - { + if (tagLoc == 0) { // value is in the 4th field of this entry... this.geoKeys.put(tag, new GeoKeyEntry(tag, 1, i + 3, this.shortParams)); - } - else - { + } else { // in this case, one or more values are given relative to one of the params arrays... Object sourceArray = null; - if (tagLoc == GeoTiff.Tag.GEO_KEY_DIRECTORY) + if (tagLoc == GeoTiff.Tag.GEO_KEY_DIRECTORY) { sourceArray = this.shortParams; - else if (tagLoc == GeoTiff.Tag.GEO_DOUBLE_PARAMS) + } else if (tagLoc == GeoTiff.Tag.GEO_DOUBLE_PARAMS) { sourceArray = this.doubleParams; - else if (tagLoc == GeoTiff.Tag.GEO_ASCII_PARAMS) + } else if (tagLoc == GeoTiff.Tag.GEO_ASCII_PARAMS) { sourceArray = this.asciiParams; + } - if (sourceArray != null) + if (sourceArray != null) { this.geoKeys.put(tag, new GeoKeyEntry(tag, 0x0000ffff & keys[i + 2], - 0x0000ffff & keys[i + 3], sourceArray)); + 0x0000ffff & keys[i + 3], sourceArray)); + } } } } @@ -290,8 +261,7 @@ else if (tagLoc == GeoTiff.Tag.GEO_ASCII_PARAMS) // // Package visibility. Not generally intended for use by end users. // - void setDoubleParams(double[] params) - { + void setDoubleParams(double[] params) { this.doubleParams = new double[params.length]; System.arraycopy(params, 0, this.doubleParams, 0, params.length); } @@ -299,8 +269,7 @@ void setDoubleParams(double[] params) // // Package visibility. Not generally intended for use by end users. // - void setAsciiParams(byte[] params) - { + void setAsciiParams(byte[] params) { this.asciiParams = new byte[params.length]; System.arraycopy(params, 0, this.asciiParams, 0, params.length); } @@ -309,13 +278,12 @@ void setAsciiParams(byte[] params) * A class to bundle up ModelTiePoints. From the Geotiff spec, a ModelTiePoint is a 6-tuple that is an * association of the pixel to the model coordinate . * - */ - public class ModelTiePoint - { + */ + public class ModelTiePoint { + public double i, j, k, x, y, z; - public ModelTiePoint(double i, double j, double k, double x, double y, double z) - { + public ModelTiePoint(double i, double j, double k, double x, double y, double z) { this.i = i; this.j = j; this.k = k; @@ -324,23 +292,19 @@ public ModelTiePoint(double i, double j, double k, double x, double y, double z) this.z = z; } - public double getRow() - { + public double getRow() { return this.j; } - public double getColumn() - { + public double getColumn() { return this.i; } - public double getX() - { + public double getX() { return this.x; } - public double getY() - { + public double getY() { return this.y; } } @@ -348,15 +312,14 @@ public double getY() /* * A little class that we use to manage GeoKeys. */ - private class GeoKeyEntry - { + private class GeoKeyEntry { + int tag; int count; int offset; Object array; // a reference to one of the short/double/asciiParams arrays - GeoKeyEntry(int tag, int count, int offset, Object array) - { + GeoKeyEntry(int tag, int count, int offset, Object array) { this.tag = tag; this.count = count; this.offset = offset; diff --git a/src/gov/nasa/worldwind/formats/tiff/GeoTiff.java b/src/gov/nasa/worldwind/formats/tiff/GeoTiff.java index abece78ad2..2b58b98af3 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeoTiff.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeoTiff.java @@ -9,76 +9,99 @@ * @author Lado Garakanidze * @version $Id: GeoTiff.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class GeoTiff -{ - public static final int Undefined = 0; +public abstract class GeoTiff { + + public static final int Undefined = 0; public static final int UserDefined = 32767; - + // Geotiff extension tags - public interface Tag - { - public static final int MODEL_PIXELSCALE = 33550; - public static final int MODEL_TIEPOINT = 33922; - public static final int MODEL_TRANSFORMATION = 34264; - public static final int GEO_KEY_DIRECTORY = 34735; - public static final int GEO_DOUBLE_PARAMS = 34736; - public static final int GEO_ASCII_PARAMS = 34737; - - public static final int GDAL_NODATA = 42113; + public interface Tag { + + public static final int MODEL_PIXELSCALE = 33550; + public static final int MODEL_TIEPOINT = 33922; + public static final int MODEL_TRANSFORMATION = 34264; + public static final int GEO_KEY_DIRECTORY = 34735; + public static final int GEO_DOUBLE_PARAMS = 34736; + public static final int GEO_ASCII_PARAMS = 34737; + + public static final int GDAL_NODATA = 42113; } + public interface GeoKeyHeader { - public interface GeoKeyHeader - { public static final int KeyDirectoryVersion = 1; public static final int KeyRevision = 1; public static final int MinorRevision = 0; - + } - public interface GeoKey - { - public static final int ModelType = 1024; // see GeoTiff.ModelType values - public static final int RasterType = 1025; // see GeoTiff.RasterType values + public interface GeoKey { - public static final int GeographicType = 2048; // see GeoTiff.GCS for values or Section 6.3.2.1 Codes + public static final int ModelType = 1024; // see GeoTiff.ModelType values + public static final int RasterType = 1025; // see GeoTiff.RasterType values + + public static final int GeographicType = 2048; // see GeoTiff.GCS for values or Section 6.3.2.1 Codes // GeoKey Requirements for User-Defined geographic CS: - public static final int GeogCitation = 2049; // ASCII - public static final int GeogGeodeticDatum = 2050; // SHORT, See section 6.3.2.2 Geodetic Datum Codes - public static final int GeogPrimeMeridian = 2051; // SHORT, Section 6.3.2.4 Codes - public static final int GeogLinearUnits = 2052; // Double, See GeoTiff.Unit.Liner or Section 6.3.1.3 Codes - public static final int GeogLinearUnitSize = 2053; // Double, meters - public static final int GeogAngularUnits = 2054; // Short, See GeoTiff.Units.Angular or Section 6.3.1.4 Codes - public static final int GeogAngularUnitSize = 2055; // Double, radians - public static final int GeogEllipsoid = 2056; // Short, See Section 6.3.2.3 Codes - public static final int GeogAzimuthUnits = 2060; // Short, Section 6.3.1.4 Codes - public static final int GeogPrimeMeridianLong = 2061; // DOUBLE, See GeoTiff.Units.Angular + public static final int GeogCitation = 2049; // ASCII + public static final int GeogGeodeticDatum = 2050; // SHORT, See section 6.3.2.2 Geodetic Datum Codes + public static final int GeogPrimeMeridian = 2051; // SHORT, Section 6.3.2.4 Codes + public static final int GeogLinearUnits = 2052; // Double, See GeoTiff.Unit.Liner or Section 6.3.1.3 Codes + public static final int GeogLinearUnitSize = 2053; // Double, meters + public static final int GeogAngularUnits = 2054; // Short, See GeoTiff.Units.Angular or Section 6.3.1.4 Codes + public static final int GeogAngularUnitSize = 2055; // Double, radians + public static final int GeogEllipsoid = 2056; // Short, See Section 6.3.2.3 Codes + public static final int GeogAzimuthUnits = 2060; // Short, Section 6.3.1.4 Codes + public static final int GeogPrimeMeridianLong = 2061; // DOUBLE, See GeoTiff.Units.Angular // 6.2.3 Projected CS Parameter Keys - public static final int ProjectedCSType = 3072; /* Section 6.3.3.1 codes */ - public static final int PCSCitation = 3073; /* documentation */ - public static final int Projection = 3074; /* Section 6.3.3.2 codes */ - public static final int ProjCoordTrans = 3075; /* Section 6.3.3.3 codes */ - public static final int ProjLinearUnits = 3076; /* Section 6.3.1.3 codes */ - public static final int ProjLinearUnitSize = 3077; /* meters */ - public static final int ProjStdParallel1 = 3078; /* GeogAngularUnit */ - public static final int ProjStdParallel2 = 3079; /* GeogAngularUnit */ - public static final int ProjNatOriginLong = 3080; /* GeogAngularUnit */ - public static final int ProjNatOriginLat = 3081; /* GeogAngularUnit */ - public static final int ProjFalseEasting = 3082; /* ProjLinearUnits */ - public static final int ProjFalseNorthing = 3083; /* ProjLinearUnits */ - public static final int ProjFalseOriginLong = 3084; /* GeogAngularUnit */ - public static final int ProjFalseOriginLat = 3085; /* GeogAngularUnit */ - public static final int ProjFalseOriginEasting = 3086; /* ProjLinearUnits */ - public static final int ProjFalseOriginNorthing = 3087; /* ProjLinearUnits */ - public static final int ProjCenterLong = 3088; /* GeogAngularUnit */ - public static final int ProjCenterLat = 3089; /* GeogAngularUnit */ - public static final int ProjCenterEasting = 3090; /* ProjLinearUnits */ - public static final int ProjCenterNorthing = 3091; /* ProjLinearUnits */ - public static final int ProjScaleAtNatOrigin = 3092; /* ratio */ - public static final int ProjScaleAtCenter = 3093; /* ratio */ - public static final int ProjAzimuthAngle = 3094; /* GeogAzimuthUnit */ - public static final int ProjStraightVertPoleLong = 3095; /* GeogAngularUnit */ + public static final int ProjectedCSType = 3072; + /* Section 6.3.3.1 codes */ + public static final int PCSCitation = 3073; + /* documentation */ + public static final int Projection = 3074; + /* Section 6.3.3.2 codes */ + public static final int ProjCoordTrans = 3075; + /* Section 6.3.3.3 codes */ + public static final int ProjLinearUnits = 3076; + /* Section 6.3.1.3 codes */ + public static final int ProjLinearUnitSize = 3077; + /* meters */ + public static final int ProjStdParallel1 = 3078; + /* GeogAngularUnit */ + public static final int ProjStdParallel2 = 3079; + /* GeogAngularUnit */ + public static final int ProjNatOriginLong = 3080; + /* GeogAngularUnit */ + public static final int ProjNatOriginLat = 3081; + /* GeogAngularUnit */ + public static final int ProjFalseEasting = 3082; + /* ProjLinearUnits */ + public static final int ProjFalseNorthing = 3083; + /* ProjLinearUnits */ + public static final int ProjFalseOriginLong = 3084; + /* GeogAngularUnit */ + public static final int ProjFalseOriginLat = 3085; + /* GeogAngularUnit */ + public static final int ProjFalseOriginEasting = 3086; + /* ProjLinearUnits */ + public static final int ProjFalseOriginNorthing = 3087; + /* ProjLinearUnits */ + public static final int ProjCenterLong = 3088; + /* GeogAngularUnit */ + public static final int ProjCenterLat = 3089; + /* GeogAngularUnit */ + public static final int ProjCenterEasting = 3090; + /* ProjLinearUnits */ + public static final int ProjCenterNorthing = 3091; + /* ProjLinearUnits */ + public static final int ProjScaleAtNatOrigin = 3092; + /* ratio */ + public static final int ProjScaleAtCenter = 3093; + /* ratio */ + public static final int ProjAzimuthAngle = 3094; + /* GeogAzimuthUnit */ + public static final int ProjStraightVertPoleLong = 3095; + /* GeogAngularUnit */ // Aliases: public static final int ProjStdParallel = ProjStdParallel1; public static final int ProjOriginLong = ProjNatOriginLong; @@ -86,143 +109,138 @@ public interface GeoKey public static final int ProjScaleAtOrigin = ProjScaleAtNatOrigin; // 6.2.4 Vertical CS Keys - public static final int VerticalCSType = 4096; /* Section 6.3.4.1 codes */ - public static final int VerticalCitation = 4097; /* ASCII */ - public static final int VerticalDatum = 4098; /* Section 6.3.4.2 codes */ - public static final int VerticalUnits = 4099; /* Section 6.3.1.3 codes */ + public static final int VerticalCSType = 4096; + /* Section 6.3.4.1 codes */ + public static final int VerticalCitation = 4097; + /* ASCII */ + public static final int VerticalDatum = 4098; + /* Section 6.3.4.2 codes */ + public static final int VerticalUnits = 4099; + /* Section 6.3.1.3 codes */ } - public interface ModelType - { - public static final int Undefined = 0; - public static final int Projected = 1; - public static final int Geographic = 2; - public static final int Geocentric = 3; + public interface ModelType { + + public static final int Undefined = 0; + public static final int Projected = 1; + public static final int Geographic = 2; + public static final int Geocentric = 3; public static final int UserDefined = 32767; public static final int DEFAULT = Geographic; } - public interface RasterType - { - public static final int Undefined = 0; // highly not recomended to use - public static final int RasterPixelIsArea = 1; - public static final int RasterPixelIsPoint = 2; - public static final int UserDefined = 32767; // highly not recomended to use + public interface RasterType { + + public static final int Undefined = 0; // highly not recomended to use + public static final int RasterPixelIsArea = 1; + public static final int RasterPixelIsPoint = 2; + public static final int UserDefined = 32767; // highly not recomended to use } + public interface Unit { - public interface Unit - { - public static final int Undefined = 0; + public static final int Undefined = 0; public static final int UserDefined = 32767; //6.3.1.3 Linear Units Codes - public interface Linear - { - public static final int Meter = 9001; - public static final int Foot = 9002; - public static final int Foot_US_Survey = 9003; - public static final int Foot_Modified_American = 9004; - public static final int Foot_Clarke = 9005; - public static final int Foot_Indian = 9006; - public static final int Link = 9007; - public static final int Link_Benoit = 9008; - public static final int Link_Sears = 9009; - public static final int Chain_Benoit = 9010; - public static final int Chain_Sears = 9011; - public static final int Yard_Sears = 9012; - public static final int Yard_Indian = 9013; - public static final int Fathom = 9014; + public interface Linear { + + public static final int Meter = 9001; + public static final int Foot = 9002; + public static final int Foot_US_Survey = 9003; + public static final int Foot_Modified_American = 9004; + public static final int Foot_Clarke = 9005; + public static final int Foot_Indian = 9006; + public static final int Link = 9007; + public static final int Link_Benoit = 9008; + public static final int Link_Sears = 9009; + public static final int Chain_Benoit = 9010; + public static final int Chain_Sears = 9011; + public static final int Yard_Sears = 9012; + public static final int Yard_Indian = 9013; + public static final int Fathom = 9014; public static final int Mile_International_Nautical = 9015; } // 6.3.1.4 Angular Units Codes // These codes shall be used for any key that requires specification of an angular unit of measurement. - public interface Angular - { - public static final int Angular_Radian = 9101; - public static final int Angular_Degree = 9102; - public static final int Angular_Arc_Minute = 9103; - public static final int Angular_Arc_Second = 9104; - public static final int Angular_Grad = 9105; - public static final int Angular_Gon = 9106; - public static final int Angular_DMS = 9107; - public static final int Angular_DMS_Hemisphere = 9108; + public interface Angular { + + public static final int Angular_Radian = 9101; + public static final int Angular_Degree = 9102; + public static final int Angular_Arc_Minute = 9103; + public static final int Angular_Arc_Second = 9104; + public static final int Angular_Grad = 9105; + public static final int Angular_Gon = 9106; + public static final int Angular_DMS = 9107; + public static final int Angular_DMS_Hemisphere = 9108; } } // Geogrphic Coordinate System (GCS) - public interface GCS - { - public static final int Undefined = 0; + public interface GCS { + + public static final int Undefined = 0; public static final int UserDefined = 32767; - public static final int NAD_83 = 4269; - public static final int WGS_72 = 4322; - public static final int WGS_72BE = 4324; - public static final int WGS_84 = 4326; + public static final int NAD_83 = 4269; + public static final int WGS_72 = 4322; + public static final int WGS_72BE = 4324; + public static final int WGS_84 = 4326; public static final int DEFAULT = WGS_84; } // Geogrphic Coordinate System Ellipsoid (GCSE) - public interface GCSE - { + public interface GCSE { + public static final int WGS_84 = 4030; } // Projected Coordinate System (PCS) - public interface PCS - { - public static final int Undefined = 0; + public interface PCS { + + public static final int Undefined = 0; public static final int UserDefined = 32767; } - public enum ProjectedCS - { - Undefined( 0, 0, "Undefined"); + public enum ProjectedCS { + Undefined(0, 0, "Undefined"); private String name; - private int epsg; - private int datum; + private int epsg; + private int datum; - private ProjectedCS(int epsg, int datum, String name ) - { + private ProjectedCS(int epsg, int datum, String name) { this.name = name; this.epsg = epsg; this.datum = datum; } - public int getEPSG() - { + public int getEPSG() { return this.epsg; } - public int getDatum() - { + public int getDatum() { return this.datum; } - public String getName() - { + public String getName() { return this.name; } } - - // Vertical Coordinate System (VCS) - public interface VCS - { + public interface VCS { // [ 1, 4999] = Reserved // [ 5000, 5099] = EPSG Ellipsoid Vertical CS Codes // [ 5100, 5199] = EPSG Orthometric Vertical CS Codes // [ 5200, 5999] = Reserved EPSG // [ 6000, 32766] = Reserved // [32768, 65535] = Private User Implementations - - public static final int Undefined = 0; + + public static final int Undefined = 0; public static final int UserDefined = 32767; public static final int Airy_1830_ellipsoid = 5001; @@ -264,8 +282,7 @@ public interface VCS public static final int Yellow_Sea_1956 = 5104; public static final int Baltic_Sea = 5105; public static final int Caspian_Sea = 5106; - + public static final int DEFAULT = Undefined; } } - diff --git a/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReader.java b/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReader.java index b90ab87fec..ec70d14fc0 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReader.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.tiff; import javax.imageio.*; @@ -21,78 +20,74 @@ * @author brownrigg * @version $Id: GeotiffImageReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeotiffImageReader extends ImageReader -{ +public class GeotiffImageReader extends ImageReader { - public GeotiffImageReader(ImageReaderSpi provider) - { + public GeotiffImageReader(ImageReaderSpi provider) { super(provider); } @Override - public int getNumImages(boolean allowSearch) throws IOException - { + public int getNumImages(boolean allowSearch) throws IOException { // TODO: This should allow for multiple images that may be present. For now, we'll ignore all but first. return 1; } @Override - public int getWidth(int imageIndex) throws IOException - { - if (imageIndex < 0 || imageIndex >= getNumImages(true)) + public int getWidth(int imageIndex) throws IOException { + if (imageIndex < 0 || imageIndex >= getNumImages(true)) { throw new IllegalArgumentException( - this.getClass().getName() + ".getWidth(): illegal imageIndex: " + imageIndex); + this.getClass().getName() + ".getWidth(): illegal imageIndex: " + imageIndex); + } - if (ifds.size() == 0) + if (ifds.size() == 0) { readIFDs(); - + } + TiffIFDEntry widthEntry = getByTag(ifds.get(imageIndex), Tiff.Tag.IMAGE_WIDTH); return (int) widthEntry.asLong(); } @Override - public int getHeight(int imageIndex) throws IOException - { - if (imageIndex < 0 || imageIndex >= getNumImages(true)) + public int getHeight(int imageIndex) throws IOException { + if (imageIndex < 0 || imageIndex >= getNumImages(true)) { throw new IllegalArgumentException( - this.getClass().getName() + ".getHeight(): illegal imageIndex: " + imageIndex); + this.getClass().getName() + ".getHeight(): illegal imageIndex: " + imageIndex); + } - if (ifds.size() == 0) + if (ifds.size() == 0) { readIFDs(); + } TiffIFDEntry heightEntry = getByTag(ifds.get(imageIndex), Tiff.Tag.IMAGE_LENGTH); return (int) heightEntry.asLong(); } @Override - public Iterator getImageTypes(int imageIndex) throws IOException - { + public Iterator getImageTypes(int imageIndex) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public IIOMetadata getStreamMetadata() throws IOException - { + public IIOMetadata getStreamMetadata() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public IIOMetadata getImageMetadata(int imageIndex) throws IOException - { + public IIOMetadata getImageMetadata(int imageIndex) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException - { + public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException { // TODO: For this first implementation, we are completely ignoring the ImageReadParam given to us. // Our target functionality is not the entire ImageIO, but only that needed to support the static // read method ImageIO.read("myImage.tif"). // TODO: more generally, the following test should reflect that more than one image is possible in a Tiff. - if (imageIndex != 0) + if (imageIndex != 0) { throw new IllegalArgumentException( - this.getClass().getName() + ".read(): illegal imageIndex: " + imageIndex); + this.getClass().getName() + ".read(): illegal imageIndex: " + imageIndex); + } readIFDs(); @@ -110,10 +105,8 @@ public BufferedImage read(int imageIndex, ImageReadParam param) throws IOExcepti TiffIFDEntry sampleFormatEntry = null; TiffIFDEntry[] ifd = ifds.get(imageIndex); - for (TiffIFDEntry entry : ifd) - { - switch (entry.tag) - { + for (TiffIFDEntry entry : ifd) { + switch (entry.tag) { case Tiff.Tag.IMAGE_WIDTH: widthEntry = entry; break; @@ -151,10 +144,11 @@ public BufferedImage read(int imageIndex, ImageReadParam param) throws IOExcepti } // Check that we have the mandatory tags present... - if (widthEntry == null || lengthEntry == null || samplesPerPixelEntry == null || photoInterpEntry == null || - stripOffsetsEntry == null || stripCountsEntry == null || rowsPerStripEntry == null - || planarConfigEntry == null) + if (widthEntry == null || lengthEntry == null || samplesPerPixelEntry == null || photoInterpEntry == null + || stripOffsetsEntry == null || stripCountsEntry == null || rowsPerStripEntry == null + || planarConfigEntry == null) { throw new IIOException(this.getClass().getName() + ".read(): unable to decipher image organization"); + } int width = (int) widthEntry.asLong(); int height = (int) lengthEntry.asLong(); @@ -172,136 +166,125 @@ public BufferedImage read(int imageIndex, ImageReadParam param) throws IOExcepti // // TODO: This isn't terribly robust; we know how to deal with a few specific types... // - - if (samplesPerPixel == 1 && bitsPerSample.length == 1 && bitsPerSample[0] == 16) - { + if (samplesPerPixel == 1 && bitsPerSample.length == 1 && bitsPerSample[0] == 16) { // 16-bit grayscale (typical of elevation data, for example)... - long sampleFormat = - (sampleFormatEntry != null) ? sampleFormatEntry.asLong() : Tiff.SampleFormat.UNSIGNED; - int dataBuffType = - (sampleFormat == Tiff.SampleFormat.SIGNED) ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT; + long sampleFormat + = (sampleFormatEntry != null) ? sampleFormatEntry.asLong() : Tiff.SampleFormat.UNSIGNED; + int dataBuffType + = (sampleFormat == Tiff.SampleFormat.SIGNED) ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT; colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), bitsPerSample, false, - false, Transparency.OPAQUE, dataBuffType); + false, Transparency.OPAQUE, dataBuffType); int[] offsets = new int[]{0}; ComponentSampleModel sampleModel = new ComponentSampleModel(dataBuffType, width, height, 1, width, offsets); short[][] imageData = readPlanar16(width, height, samplesPerPixel, stripOffsets, stripCounts, rowsPerStrip); - DataBuffer dataBuff = (dataBuffType == DataBuffer.TYPE_SHORT) ? - new DataBufferShort(imageData, width * height, offsets) : - new DataBufferUShort(imageData, width * height, offsets); + DataBuffer dataBuff = (dataBuffType == DataBuffer.TYPE_SHORT) + ? new DataBufferShort(imageData, width * height, offsets) + : new DataBufferUShort(imageData, width * height, offsets); raster = Raster.createWritableRaster(sampleModel, dataBuff, new Point(0, 0)); - } - else if (samplesPerPixel == 1 && bitsPerSample.length == 1 && bitsPerSample[0] == 32 && - sampleFormatEntry != null && sampleFormatEntry.asLong() == Tiff.SampleFormat.IEEEFLOAT) - { + } else if (samplesPerPixel == 1 && bitsPerSample.length == 1 && bitsPerSample[0] == 32 + && sampleFormatEntry != null && sampleFormatEntry.asLong() == Tiff.SampleFormat.IEEEFLOAT) { // 32-bit grayscale (typical of elevation data, for example)... colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), bitsPerSample, false, - false, Transparency.OPAQUE, DataBuffer.TYPE_FLOAT); + false, Transparency.OPAQUE, DataBuffer.TYPE_FLOAT); int[] offsets = new int[]{0}; ComponentSampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_FLOAT, width, height, 1, width, - offsets); + offsets); float[][] imageData = readPlanarFloat32(width, height, samplesPerPixel, stripOffsets, stripCounts, - rowsPerStrip); + rowsPerStrip); DataBuffer dataBuff = new DataBufferFloat(imageData, width * height, offsets); raster = Raster.createWritableRaster(sampleModel, dataBuff, new Point(0, 0)); - } - else - { + } else { // make sure a DataBufferByte is going to do the trick - for (int bits : bitsPerSample) - { - if (bits != 8) - throw new IIOException(this.getClass().getName() + ".read(): only expecting 8 bits/sample; found " + - bits); + for (int bits : bitsPerSample) { + if (bits != 8) { + throw new IIOException(this.getClass().getName() + ".read(): only expecting 8 bits/sample; found " + + bits); + } } // byte image data; could be RGB-component, grayscale, or indexed-color. // Set up an appropriate ColorModel... colorModel = null; - if (samplesPerPixel > 1) - { + if (samplesPerPixel > 1) { int transparency = Transparency.OPAQUE; boolean hasAlpha = false; - if (samplesPerPixel == 4) - { + if (samplesPerPixel == 4) { transparency = Transparency.TRANSLUCENT; hasAlpha = true; } colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), bitsPerSample, - hasAlpha, - false, transparency, DataBuffer.TYPE_BYTE); - } - else - { + hasAlpha, + false, transparency, DataBuffer.TYPE_BYTE); + } else { // grayscale or indexed-color? - if (photoInterp == Tiff.Photometric.Color_Palette) - { + if (photoInterp == Tiff.Photometric.Color_Palette) { // indexed... - if (colorMapEntry == null) + if (colorMapEntry == null) { throw new IIOException( - this.getClass().getName() + ".read(): no ColorMap found for indexed image type"); + this.getClass().getName() + ".read(): no ColorMap found for indexed image type"); + } byte[][] cmap = readColorMap(colorMapEntry); colorModel = new IndexColorModel(bitsPerSample[0], (int) colorMapEntry.count / 3, cmap[0], cmap[1], - cmap[2]); - } - else - { + cmap[2]); + } else { // grayscale... colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), bitsPerSample, - false, - false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); + false, + false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); } } int[] bankOffsets = new int[samplesPerPixel]; - for (int i = 0; i < samplesPerPixel; i++) - { + for (int i = 0; i < samplesPerPixel; i++) { bankOffsets[i] = i; } int[] offsets = new int[(planarConfig == Tiff.PlanarConfiguration.CHUNKY) ? 1 : samplesPerPixel]; - for (int i = 0; i < offsets.length; i++) - { + for (int i = 0; i < offsets.length; i++) { offsets[i] = 0; } // construct the right SampleModel... ComponentSampleModel sampleModel; - if (samplesPerPixel == 1) + if (samplesPerPixel == 1) { sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, width, height, 1, width, bankOffsets); - else - sampleModel = (planarConfig == Tiff.PlanarConfiguration.CHUNKY) ? - new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, samplesPerPixel, - width * samplesPerPixel, bankOffsets) : - new BandedSampleModel(DataBuffer.TYPE_BYTE, width, height, width, bankOffsets, offsets); + } else { + sampleModel = (planarConfig == Tiff.PlanarConfiguration.CHUNKY) + ? new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, samplesPerPixel, + width * samplesPerPixel, bankOffsets) + : new BandedSampleModel(DataBuffer.TYPE_BYTE, width, height, width, bankOffsets, offsets); + } // Get the image data and make our Raster... byte[][] imageData; - if (planarConfig == Tiff.PlanarConfiguration.CHUNKY) + if (planarConfig == Tiff.PlanarConfiguration.CHUNKY) { imageData = readPixelInterleaved8(width, height, samplesPerPixel, stripOffsets, stripCounts); - else + } else { imageData = readPlanar8(width, height, samplesPerPixel, stripOffsets, stripCounts, rowsPerStrip); + } DataBufferByte dataBuff = new DataBufferByte(imageData, width * height, offsets); raster = Raster.createWritableRaster(sampleModel, dataBuff, new Point(0, 0)); } - /**************************************/ + /** + * *********************************** + */ decodeGeotiffInfo(); - /**************************************/ + /** + * *********************************** + */ // Finally, put it all together to get our BufferedImage... return new BufferedImage(colorModel, raster, false, null); } - private void decodeGeotiffInfo() throws IOException - { + private void decodeGeotiffInfo() throws IOException { readIFDs(); TiffIFDEntry[] ifd = ifds.get(0); - for (TiffIFDEntry entry : ifd) - { - switch (entry.tag) - { + for (TiffIFDEntry entry : ifd) { + switch (entry.tag) { case GeoTiff.Tag.MODEL_PIXELSCALE: geoPixelScale = readDoubles(entry); break; @@ -326,37 +309,28 @@ private void decodeGeotiffInfo() throws IOException * Coordinates reading all the ImageFileDirectories in a Tiff file (there's typically only one). * */ - private void readIFDs() throws IOException - { - if (this.theStream != null) + private void readIFDs() throws IOException { + if (this.theStream != null) { return; + } - if (super.input == null || !(super.input instanceof ImageInputStream)) - { + if (super.input == null || !(super.input instanceof ImageInputStream)) { throw new IIOException(this.getClass().getName() + ": null/invalid ImageInputStream"); } this.theStream = (ImageInputStream) super.input; // determine byte ordering... byte[] ifh = new byte[2]; // Tiff image-file header - try - { + try { theStream.readFully(ifh); - if (ifh[0] == 0x4D && ifh[1] == 0x4D) - { + if (ifh[0] == 0x4D && ifh[1] == 0x4D) { theStream.setByteOrder(ByteOrder.BIG_ENDIAN); - } - else if (ifh[0] == 0x49 && ifh[1] == 0x49) - { + } else if (ifh[0] == 0x49 && ifh[1] == 0x49) { theStream.setByteOrder(ByteOrder.LITTLE_ENDIAN); - } - else - { + } else { throw new IOException(); } - } - catch (IOException ex) - { + } catch (IOException ex) { throw new IIOException(this.getClass().getName() + ": error reading signature"); } @@ -370,16 +344,13 @@ else if (ifh[0] == 0x49 && ifh[1] == 0x49) * Reads an ImageFileDirectory and places it in our list. Calls itself recursively if additional * IFDs are indicated. * - */ - private void readIFD(long offset) throws IIOException - { - try - { + */ + private void readIFD(long offset) throws IIOException { + try { theStream.seek(offset); int numEntries = theStream.readUnsignedShort(); TiffIFDEntry[] ifd = new TiffIFDEntry[numEntries]; - for (int i = 0; i < numEntries; i++) - { + for (int i = 0; i < numEntries; i++) { int tag = theStream.readUnsignedShort(); int type = theStream.readUnsignedShort(); long count = theStream.readUnsignedInt(); @@ -389,23 +360,19 @@ private void readIFD(long offset) throws IIOException int upper = theStream.readUnsignedShort(); int lower = theStream.readUnsignedShort(); valoffset = (0xffff & upper) << 16 | (0xffff & lower); - } - else + } else { valoffset = theStream.readUnsignedInt(); + } ifd[i] = new TiffIFDEntry(tag, type, count, valoffset); } ifds.add(ifd); - /****** TODO: UNCOMMENT; IN GENERAL, THERE CAN BE MORE THAN ONE IFD IN A TIFF FILE - long nextIFDOffset = theStream.readUnsignedInt(); - if (nextIFDOffset > 0) - readIFD(nextIFDOffset); + /** + * **** TODO: UNCOMMENT; IN GENERAL, THERE CAN BE MORE THAN ONE IFD IN A TIFF FILE long nextIFDOffset = + * theStream.readUnsignedInt(); if (nextIFDOffset > 0) readIFD(nextIFDOffset); */ - - } - catch (Exception ex) - { + } catch (Exception ex) { throw new IIOException("Error reading Tiff IFD: " + ex.getMessage()); } } @@ -413,18 +380,17 @@ private void readIFD(long offset) throws IIOException /* * Reads BYTE image data organized as a singular image plane (and pixel interleaved, in the case of color images). * - */ + */ private byte[][] readPixelInterleaved8(int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts) throws IOException - { + long[] stripOffsets, long[] stripCounts) throws IOException { byte[][] data = new byte[1][width * height * samplesPerPixel]; int offset = 0; - for (int i = 0; i < stripOffsets.length; i++) - { + for (int i = 0; i < stripOffsets.length; i++) { this.theStream.seek(stripOffsets[i]); int len = (int) stripCounts[i]; - if ((offset + len) >= data[0].length) + if ((offset + len) >= data[0].length) { len = data[0].length - offset; + } this.theStream.readFully(data[0], offset, len); offset += stripCounts[i]; } @@ -436,23 +402,21 @@ private byte[][] readPixelInterleaved8(int width, int height, int samplesPerPixe * */ private byte[][] readPlanar8(int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException - { + long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException { byte[][] data = new byte[samplesPerPixel][width * height]; int band = 0; int offset = 0; int numRows = 0; - for (int i = 0; i < stripOffsets.length; i++) - { + for (int i = 0; i < stripOffsets.length; i++) { this.theStream.seek(stripOffsets[i]); int len = (int) stripCounts[i]; - if ((offset + len) >= data[band].length) + if ((offset + len) >= data[band].length) { len = data[band].length - offset; + } this.theStream.readFully(data[band], offset, len); offset += stripCounts[i]; numRows += rowsPerStrip; - if (numRows >= height) - { + if (numRows >= height) { ++band; numRows = 0; offset = 0; @@ -467,23 +431,21 @@ private byte[][] readPlanar8(int width, int height, int samplesPerPixel, * */ private short[][] readPlanar16(int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException - { + long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException { short[][] data = new short[samplesPerPixel][width * height]; int band = 0; int offset = 0; int numRows = 0; - for (int i = 0; i < stripOffsets.length; i++) - { + for (int i = 0; i < stripOffsets.length; i++) { this.theStream.seek(stripOffsets[i]); int len = (int) stripCounts[i] / Short.SIZE; // strip-counts are in bytes, we're reading shorts... - if ((offset + len) >= data[band].length) + if ((offset + len) >= data[band].length) { len = data[band].length - offset; + } this.theStream.readFully(data[band], offset, len); offset += stripCounts[i] / Short.SIZE; numRows += rowsPerStrip; - if (numRows >= height) - { + if (numRows >= height) { ++band; numRows = 0; offset = 0; @@ -498,23 +460,21 @@ private short[][] readPlanar16(int width, int height, int samplesPerPixel, * */ private float[][] readPlanarFloat32(int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException - { + long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException { float[][] data = new float[samplesPerPixel][width * height]; int band = 0; int offset = 0; int numRows = 0; - for (int i = 0; i < stripOffsets.length; i++) - { + for (int i = 0; i < stripOffsets.length; i++) { this.theStream.seek(stripOffsets[i]); int len = (int) stripCounts[i] / Float.SIZE; // strip-counts are in bytes, we're reading floats... - if ((offset + len) >= data[band].length) + if ((offset + len) >= data[band].length) { len = data[band].length - offset; + } this.theStream.readFully(data[band], offset, len); offset += stripCounts[i] / Float.SIZE; numRows += rowsPerStrip; - if (numRows >= height) - { + if (numRows >= height) { ++band; numRows = 0; offset = 0; @@ -528,8 +488,7 @@ private float[][] readPlanarFloat32(int width, int height, int samplesPerPixel, * Reads a ColorMap. * */ - private byte[][] readColorMap(TiffIFDEntry colorMapEntry) throws IOException - { + private byte[][] readColorMap(TiffIFDEntry colorMapEntry) throws IOException { // NOTE: TIFF gives total number of cmap values, which is 3 times the size of cmap table... int numEntries = (int) colorMapEntry.count / 3; short[][] tmp = new short[3][numEntries]; @@ -544,10 +503,8 @@ private byte[][] readColorMap(TiffIFDEntry colorMapEntry) throws IOException // TIFF gives a ColorMap composed of unsigned shorts. Java's IndexedColorModel wants unsigned bytes. // Something's got to give somewhere...we'll do our best. byte[][] cmap = new byte[3][numEntries]; - for (int i = 0; i < 3; i++) - { - for (int j = 0; j < numEntries; j++) - { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < numEntries; j++) { cmap[i][j] = (byte) (0x00ff & tmp[i][j]); } } @@ -559,16 +516,14 @@ private byte[][] readColorMap(TiffIFDEntry colorMapEntry) throws IOException * Reads and returns an array of doubles from the file. * */ - private double[] readDoubles(TiffIFDEntry entry) throws IOException - { + private double[] readDoubles(TiffIFDEntry entry) throws IOException { double[] doubles = new double[(int) entry.count]; this.theStream.seek(entry.asOffset()); this.theStream.readFully(doubles, 0, doubles.length); return doubles; } - private void readGeoKeys(TiffIFDEntry entry) throws IOException - { + private void readGeoKeys(TiffIFDEntry entry) throws IOException { short[] keyValRec = new short[4]; this.theStream.seek(entry.asLong()); @@ -580,16 +535,14 @@ private void readGeoKeys(TiffIFDEntry entry) throws IOException this.theStream.readFully(keyValRec, 0, numKeys * 4); int j = 0; - for (int i = 0; i < numKeys * 4; i += 4) - { + for (int i = 0; i < numKeys * 4; i += 4) { GeoKey key = new GeoKey(); key.key = keyValRec[i]; - if (keyValRec[i + 1] == 0) + if (keyValRec[i + 1] == 0) { key.value = new Integer(keyValRec[i + 3]); - else - { + } else { // TODO: This isn't quite right.... - key.value = getByTag(ifds.get(0), (0x0000ffff & keyValRec[i + 1])); + key.value = getByTag(ifds.get(0), (0x0000ffff & keyValRec[i + 1])); } geoKeys[j++] = key; } @@ -599,12 +552,9 @@ private void readGeoKeys(TiffIFDEntry entry) throws IOException * Returns the (first!) IFD-Entry with the given tag, or null if not found. * */ - private TiffIFDEntry getByTag(TiffIFDEntry[] ifds, int tag) - { - for (TiffIFDEntry ifd : ifds) - { - if (ifd.tag == tag) - { + private TiffIFDEntry getByTag(TiffIFDEntry[] ifds, int tag) { + for (TiffIFDEntry ifd : ifds) { + if (ifd.tag == tag) { return ifd; } } @@ -613,29 +563,24 @@ private TiffIFDEntry getByTag(TiffIFDEntry[] ifds, int tag) /* * Utility method intended to read the array of StripOffsets or StripByteCounts. - */ - private long[] getStripsArray(TiffIFDEntry stripsEntry) throws IOException - { + */ + private long[] getStripsArray(TiffIFDEntry stripsEntry) throws IOException { long[] offsets = new long[(int) stripsEntry.count]; - if (stripsEntry.count == 1) - { + if (stripsEntry.count == 1) { // this is a special case, and it *does* happen! offsets[0] = stripsEntry.asLong(); - } - else - { + } else { long fileOffset = stripsEntry.asLong(); this.theStream.seek(fileOffset); - if (stripsEntry.type == Tiff.Type.SHORT) - for (int i = 0; i < stripsEntry.count; i++) - { + if (stripsEntry.type == Tiff.Type.SHORT) { + for (int i = 0; i < stripsEntry.count; i++) { offsets[i] = this.theStream.readUnsignedShort(); } - else - for (int i = 0; i < stripsEntry.count; i++) - { + } else { + for (int i = 0; i < stripsEntry.count; i++) { offsets[i] = this.theStream.readUnsignedInt(); } + } } return offsets; } @@ -647,30 +592,26 @@ private long[] getStripsArray(TiffIFDEntry stripsEntry) throws IOException * to go track them down elsewhere in the file. Finally, as bitsPerSample is optional for bilevel images, * we'll return something sane if this tag is absent. */ - private int[] getBitsPerSample(TiffIFDEntry entry) throws IOException - { - if (entry == null) - { + private int[] getBitsPerSample(TiffIFDEntry entry) throws IOException { + if (entry == null) { return new int[]{1}; } // the default according to the Tiff6.0 spec. - if (entry.count == 1) - { + if (entry.count == 1) { return new int[]{(int) entry.asLong()}; } long[] tmp = getStripsArray(entry); int[] bits = new int[tmp.length]; - for (int i = 0; i < tmp.length; i++) - { + for (int i = 0; i < tmp.length; i++) { bits[i] = (int) tmp[i]; } return bits; } - private class GeoKey - { + private class GeoKey { + short key; Object value; } diff --git a/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReaderSpi.java b/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReaderSpi.java index 33fd117d6f..95baae413b 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReaderSpi.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeotiffImageReaderSpi.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.tiff; import gov.nasa.worldwind.Version; @@ -20,56 +19,50 @@ * @author brownrigg * @version $Id: GeotiffImageReaderSpi.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeotiffImageReaderSpi extends ImageReaderSpi -{ +public class GeotiffImageReaderSpi extends ImageReaderSpi { - public static GeotiffImageReaderSpi inst() - { - if (theInstance == null) + public static GeotiffImageReaderSpi inst() { + if (theInstance == null) { theInstance = new GeotiffImageReaderSpi(); + } return theInstance; } - private GeotiffImageReaderSpi() - { + private GeotiffImageReaderSpi() { super(vendorName, version, names, suffixes, mimeTypes, - readerClassname, new Class[] {ImageInputStream.class}, - null, false, null, null, null, null, - false, null, null, null, null); + readerClassname, new Class[]{ImageInputStream.class}, + null, false, null, null, null, null, + false, null, null, null, null); } @Override - public boolean canDecodeInput(Object source) throws IOException - { - if (source == null || !(source instanceof ImageInputStream)) + public boolean canDecodeInput(Object source) throws IOException { + if (source == null || !(source instanceof ImageInputStream)) { return false; + } ImageInputStream inp = (ImageInputStream) source; byte[] ifh = new byte[8]; // Tiff image-file header - try - { + try { inp.mark(); inp.readFully(ifh); inp.reset(); - } - catch (IOException ex) - { + } catch (IOException ex) { return false; } - return (ifh[0] == 0x4D && ifh[1] == 0x4D && ifh[2] == 0x00 && ifh[3] == 0x2A) || // big-endian - (ifh[0] == 0x49 && ifh[1] == 0x49 && ifh[2] == 0x2A && ifh[3] == 0x00); // little-endian + return (ifh[0] == 0x4D && ifh[1] == 0x4D && ifh[2] == 0x00 && ifh[3] == 0x2A) + || // big-endian + (ifh[0] == 0x49 && ifh[1] == 0x49 && ifh[2] == 0x2A && ifh[3] == 0x00); // little-endian } @Override - public ImageReader createReaderInstance(Object extension) throws IOException - { + public ImageReader createReaderInstance(Object extension) throws IOException { return new GeotiffImageReader(this); } @Override - public String getDescription(Locale locale) - { + public String getDescription(Locale locale) { return "NASA WorldWind Geotiff Image Reader"; } diff --git a/src/gov/nasa/worldwind/formats/tiff/GeotiffMetaData.java b/src/gov/nasa/worldwind/formats/tiff/GeotiffMetaData.java index 3e595fa507..7f7368b1c5 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeotiffMetaData.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeotiffMetaData.java @@ -14,10 +14,8 @@ * @author brownrigg * @version $Id: GeotiffMetaData.java 1171 2013-02-11 21:45:02Z dcollins $ */ - public class GeotiffMetaData extends IIOMetadata { - public boolean isReadOnly() { return false; //To change body of implemented methods use File | Settings | File Templates. } diff --git a/src/gov/nasa/worldwind/formats/tiff/GeotiffMetadataFormat.java b/src/gov/nasa/worldwind/formats/tiff/GeotiffMetadataFormat.java index 361c56ccde..81fadcb91d 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeotiffMetadataFormat.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeotiffMetadataFormat.java @@ -12,10 +12,12 @@ * @author brownrigg * @version $Id: GeotiffMetadataFormat.java 1171 2013-02-11 21:45:02Z dcollins $ */ - public class GeotiffMetadataFormat extends IIOMetadataFormatImpl { - public GeotiffMetadataFormat() { super(null,0); } + public GeotiffMetadataFormat() { + super(null, 0); + } + public boolean canNodeAppear(String elementName, ImageTypeSpecifier imageType) { return false; //To change body of implemented methods use File | Settings | File Templates. } diff --git a/src/gov/nasa/worldwind/formats/tiff/GeotiffReader.java b/src/gov/nasa/worldwind/formats/tiff/GeotiffReader.java index f8dad56f85..307ad7abee 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeotiffReader.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeotiffReader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.tiff; import gov.nasa.worldwind.Disposable; @@ -25,8 +24,8 @@ * @author brownrigg * @version $Id: GeotiffReader.java 3289 2015-06-30 15:55:33Z tgaskins $ */ -public class GeotiffReader implements Disposable -{ +public class GeotiffReader implements Disposable { + private TIFFReader tiffReader = null; private String sourceFilename; @@ -38,8 +37,7 @@ public class GeotiffReader implements Disposable private ArrayList tiffIFDs = null; private ArrayList metadata = null; - public GeotiffReader(String sourceFilename) throws IOException - { + public GeotiffReader(String sourceFilename) throws IOException { this.sourceFilename = sourceFilename; this.sourceFile = new RandomAccessFile(sourceFilename, "r"); this.theChannel = this.sourceFile.getChannel(); @@ -49,34 +47,27 @@ public GeotiffReader(String sourceFilename) throws IOException readTiffHeaders(); } - public GeotiffReader(File sourceFile) throws IOException - { + public GeotiffReader(File sourceFile) throws IOException { this(sourceFile.getAbsolutePath()); } - protected AVList getMetadata(int imageIndex) throws IOException - { + protected AVList getMetadata(int imageIndex) throws IOException { this.checkImageIndex(imageIndex); AVList values = this.metadata.get(imageIndex); return (null != values) ? values.copy() : null; } - public AVList copyMetadataTo(int imageIndex, AVList values) throws IOException - { + public AVList copyMetadataTo(int imageIndex, AVList values) throws IOException { AVList list = this.getMetadata(imageIndex); - if (null != values) - { + if (null != values) { values.setValues(list); - } - else - { + } else { values = list; } return values; } - public AVList copyMetadataTo(AVList list) throws IOException - { + public AVList copyMetadataTo(AVList list) throws IOException { return this.copyMetadataTo(0, list); } @@ -84,75 +75,60 @@ public AVList copyMetadataTo(AVList list) throws IOException // { // return this.getMetadata(0); // } - - public void close() - { - try - { + public void close() { + try { this.sourceFile.close(); - } - catch (Exception ex) - { /* best effort */ } + } catch (Exception ex) { + /* best effort */ } } - public int getNumImages() throws IOException - { + public int getNumImages() throws IOException { return (this.tiffIFDs != null) ? this.tiffIFDs.size() : 0; } - public int getWidth(int imageIndex) throws IOException - { + public int getWidth(int imageIndex) throws IOException { checkImageIndex(imageIndex); AVList values = this.metadata.get(imageIndex); return (values.hasKey(AVKey.WIDTH)) ? (Integer) values.getValue(AVKey.WIDTH) : 0; } - public int getHeight(int imageIndex) throws IOException - { + public int getHeight(int imageIndex) throws IOException { checkImageIndex(imageIndex); AVList values = this.metadata.get(imageIndex); return (values.hasKey(AVKey.HEIGHT)) ? (Integer) values.getValue(AVKey.HEIGHT) : 0; } - public DataRaster[] readDataRaster() throws IOException - { + public DataRaster[] readDataRaster() throws IOException { int num = this.getNumImages(); - if (num <= 0) - { + if (num <= 0) { return null; } DataRaster[] rasters = new DataRaster[num]; - for (int i = 0; i < num; i++) - { + for (int i = 0; i < num; i++) { rasters[i] = this.doRead(i); } return rasters; } - public DataRaster readDataRaster(int imageIndex) throws IOException - { + public DataRaster readDataRaster(int imageIndex) throws IOException { checkImageIndex(imageIndex); return this.doRead(imageIndex); } - public BufferedImage read() throws IOException - { + public BufferedImage read() throws IOException { return this.read(0); } - public BufferedImage read(int imageIndex) throws IOException - { + public BufferedImage read(int imageIndex) throws IOException { DataRaster raster = this.doRead(imageIndex); - if (null == raster) - { + if (null == raster) { return null; } - if (raster instanceof BufferedImageRaster) - { + if (raster instanceof BufferedImageRaster) { return ((BufferedImageRaster) raster).getBufferedImage(); } @@ -161,20 +137,17 @@ public BufferedImage read(int imageIndex) throws IOException throw new IOException(message); } - public boolean isGeotiff(int imageIndex) throws IOException - { + public boolean isGeotiff(int imageIndex) throws IOException { AVList values = this.metadata.get(imageIndex); return (null != values && values.hasKey(AVKey.COORDINATE_SYSTEM)); } - public DataRaster doRead(int imageIndex) throws IOException - { + public DataRaster doRead(int imageIndex) throws IOException { checkImageIndex(imageIndex); AVList values = this.metadata.get(imageIndex); // Extract the various IFD tags we need to read this image. We want to loop over the tag set once, instead // multiple times if we simply used our general getByTag() method. - long[] stripOffsets = null; byte[][] cmap = null; long[] stripCounts = null; @@ -185,68 +158,58 @@ public DataRaster doRead(int imageIndex) throws IOException BaselineTiff tiff = BaselineTiff.extract(ifd, this.tiffReader); - if (null == tiff) - { + if (null == tiff) { String message = Logging.getMessage("GeotiffReader.BadGeotiff"); Logging.logger().severe(message); throw new IOException(message); } - if (tiff.width <= 0) - { + if (tiff.width <= 0) { String msg = Logging.getMessage("GeotiffReader.InvalidIFDEntryValue", tiff.width, - "width", Tiff.Tag.IMAGE_WIDTH); + "width", Tiff.Tag.IMAGE_WIDTH); Logging.logger().severe(msg); throw new IOException(msg); } - if (tiff.height <= 0) - { + if (tiff.height <= 0) { String msg = Logging.getMessage("GeotiffReader.InvalidIFDEntryValue", tiff.height, - "height", Tiff.Tag.IMAGE_LENGTH); + "height", Tiff.Tag.IMAGE_LENGTH); Logging.logger().severe(msg); throw new IOException(msg); } - if (tiff.samplesPerPixel <= Tiff.Undefined) - { + if (tiff.samplesPerPixel <= Tiff.Undefined) { String msg = Logging.getMessage("GeotiffReader.InvalidIFDEntryValue", tiff.samplesPerPixel, - "samplesPerPixel", Tiff.Tag.SAMPLES_PER_PIXEL); + "samplesPerPixel", Tiff.Tag.SAMPLES_PER_PIXEL); Logging.logger().severe(msg); throw new IOException(msg); } - if (tiff.photometric <= Tiff.Photometric.Undefined || tiff.photometric > Tiff.Photometric.YCbCr) - { + if (tiff.photometric <= Tiff.Photometric.Undefined || tiff.photometric > Tiff.Photometric.YCbCr) { String msg = Logging.getMessage("GeotiffReader.InvalidIFDEntryValue", tiff.photometric, - "PhotoInterpretation", Tiff.Tag.PHOTO_INTERPRETATION); + "PhotoInterpretation", Tiff.Tag.PHOTO_INTERPRETATION); Logging.logger().severe(msg); throw new IOException(msg); } - if (tiff.rowsPerStrip <= Tiff.Undefined) - { + if (tiff.rowsPerStrip <= Tiff.Undefined) { String msg = Logging.getMessage("GeotiffReader.InvalidIFDEntryValue", tiff.rowsPerStrip, - "RowsPerStrip", Tiff.Tag.ROWS_PER_STRIP); + "RowsPerStrip", Tiff.Tag.ROWS_PER_STRIP); Logging.logger().fine(msg); tiff.rowsPerStrip = Integer.MAX_VALUE; } if (tiff.planarConfig != Tiff.PlanarConfiguration.PLANAR - && tiff.planarConfig != Tiff.PlanarConfiguration.CHUNKY) - { + && tiff.planarConfig != Tiff.PlanarConfiguration.CHUNKY) { String msg = Logging.getMessage("GeotiffReader.InvalidIFDEntryValue", tiff.planarConfig, - "PhotoInterpretation", Tiff.Tag.PHOTO_INTERPRETATION); + "PhotoInterpretation", Tiff.Tag.PHOTO_INTERPRETATION); Logging.logger().severe(msg); throw new IOException(msg); } - for (TiffIFDEntry entry : ifd) - { - try - { - switch (entry.tag) - { + for (TiffIFDEntry entry : ifd) { + try { + switch (entry.tag) { case Tiff.Tag.STRIP_OFFSETS: stripOffsets = entry.getAsLongs(); break; @@ -259,22 +222,18 @@ public DataRaster doRead(int imageIndex) throws IOException cmap = this.tiffReader.readColorMap(entry); break; } - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().finest(e.toString()); } } - if (null == stripOffsets || 0 == stripOffsets.length) - { + if (null == stripOffsets || 0 == stripOffsets.length) { String message = Logging.getMessage("GeotiffReader.MissingRequiredTag", "StripOffsets"); Logging.logger().severe(message); throw new IOException(message); } - if (null == stripCounts || 0 == stripCounts.length) - { + if (null == stripCounts || 0 == stripCounts.length) { String message = Logging.getMessage("GeotiffReader.MissingRequiredTag", "StripCounts"); Logging.logger().severe(message); throw new IOException(message); @@ -282,25 +241,20 @@ public DataRaster doRead(int imageIndex) throws IOException TiffIFDEntry notToday = getByTag(ifd, Tiff.Tag.COMPRESSION); boolean lzwCompressed = false; - if (notToday != null && notToday.asLong() == Tiff.Compression.LZW) - { + if (notToday != null && notToday.asLong() == Tiff.Compression.LZW) { lzwCompressed = true; TiffIFDEntry predictorEntry = getByTag(ifd, Tiff.Tag.TIFF_PREDICTOR); - if ((predictorEntry != null) && (predictorEntry.asLong() != 0)) - { + if ((predictorEntry != null) && (predictorEntry.asLong() != 0)) { tiffDifferencing = true; } - } - else if (notToday != null && notToday.asLong() != Tiff.Compression.NONE) - { + } else if (notToday != null && notToday.asLong() != Tiff.Compression.NONE) { String message = Logging.getMessage("GeotiffReader.CompressionFormatNotSupported"); Logging.logger().severe(message); throw new IOException(message); } notToday = getByTag(ifd, Tiff.Tag.TILE_WIDTH); - if (notToday != null) - { + if (notToday != null) { String message = Logging.getMessage("GeotiffReader.NoTiled"); Logging.logger().severe(message); throw new IOException(message); @@ -310,123 +264,95 @@ else if (notToday != null && notToday.asLong() != Tiff.Compression.NONE) // int sampleFormat = (null != tiff.sampleFormat) ? tiff.sampleFormat[0] : Tiff.Undefined; // int bitsPerSample = (null != tiff.bitsPerSample) ? tiff.bitsPerSample[0] : Tiff.Undefined; - if (values.getValue(AVKey.PIXEL_FORMAT) == AVKey.ELEVATION) - { + if (values.getValue(AVKey.PIXEL_FORMAT) == AVKey.ELEVATION) { ByteBufferRaster raster = new ByteBufferRaster(tiff.width, tiff.height, - (Sector) values.getValue(AVKey.SECTOR), values); + (Sector) values.getValue(AVKey.SECTOR), values); - if (raster.getValue(AVKey.DATA_TYPE) == AVKey.INT8) - { + if (raster.getValue(AVKey.DATA_TYPE) == AVKey.INT8) { byte[][] data = this.tiffReader.readPlanar8(tiff.width, tiff.height, tiff.samplesPerPixel, - stripOffsets, stripCounts, tiff.rowsPerStrip); + stripOffsets, stripCounts, tiff.rowsPerStrip); int next = 0; - for (int y = 0; y < tiff.height; y++) - { - for (int x = 0; x < tiff.width; x++) - { + for (int y = 0; y < tiff.height; y++) { + for (int x = 0; x < tiff.width; x++) { raster.setDoubleAtPosition(y, x, (double) data[0][next++]); } } - } - else if (raster.getValue(AVKey.DATA_TYPE) == AVKey.INT16) - { + } else if (raster.getValue(AVKey.DATA_TYPE) == AVKey.INT16) { short[][] data = this.tiffReader.readPlanar16(tiff.width, tiff.height, tiff.samplesPerPixel, - stripOffsets, stripCounts, tiff.rowsPerStrip); + stripOffsets, stripCounts, tiff.rowsPerStrip); int next = 0; - for (int y = 0; y < tiff.height; y++) - { - for (int x = 0; x < tiff.width; x++) - { - raster.setDoubleAtPosition(y, x, (double) data[0][next++] ); + for (int y = 0; y < tiff.height; y++) { + for (int x = 0; x < tiff.width; x++) { + raster.setDoubleAtPosition(y, x, (double) data[0][next++]); } } - } - else if (raster.getValue(AVKey.DATA_TYPE) == AVKey.FLOAT32) - { + } else if (raster.getValue(AVKey.DATA_TYPE) == AVKey.FLOAT32) { float[][] data = this.tiffReader.readPlanarFloat32(tiff.width, tiff.height, tiff.samplesPerPixel, - stripOffsets, stripCounts, tiff.rowsPerStrip); + stripOffsets, stripCounts, tiff.rowsPerStrip); int next = 0; - for (int y = 0; y < tiff.height; y++) - { - for (int x = 0; x < tiff.width; x++) - { + for (int y = 0; y < tiff.height; y++) { + for (int x = 0; x < tiff.width; x++) { raster.setDoubleAtPosition(y, x, (double) data[0][next++]); } } - } - else - { + } else { String message = Logging.getMessage("Geotiff.UnsupportedDataTypeRaster", tiff.toString()); Logging.logger().severe(message); throw new IOException(message); } - ElevationsUtil.rectify( raster ); + ElevationsUtil.rectify(raster); return raster; - } - else if (values.getValue(AVKey.PIXEL_FORMAT) == AVKey.IMAGE - && values.getValue(AVKey.IMAGE_COLOR_FORMAT) == AVKey.GRAYSCALE) - { + } else if (values.getValue(AVKey.PIXEL_FORMAT) == AVKey.IMAGE + && values.getValue(AVKey.IMAGE_COLOR_FORMAT) == AVKey.GRAYSCALE) { BufferedImage grayImage = null; - if (values.getValue(AVKey.DATA_TYPE) == AVKey.INT8) - { + if (values.getValue(AVKey.DATA_TYPE) == AVKey.INT8) { byte[][] image = this.tiffReader.readPlanar8(tiff.width, tiff.height, tiff.samplesPerPixel, - stripOffsets, stripCounts, tiff.rowsPerStrip); + stripOffsets, stripCounts, tiff.rowsPerStrip); grayImage = new BufferedImage(tiff.width, tiff.height, BufferedImage.TYPE_BYTE_GRAY); WritableRaster wrRaster = grayImage.getRaster(); int next = 0; - for (int y = 0; y < tiff.height; y++) - { - for (int x = 0; x < tiff.width; x++) - { + for (int y = 0; y < tiff.height; y++) { + for (int x = 0; x < tiff.width; x++) { wrRaster.setSample(x, y, 0, 0xFF & (int) (image[0][next++])); } } - } - else if (values.getValue(AVKey.DATA_TYPE) == AVKey.INT16 && tiff.samplesPerPixel == 1) - { + } else if (values.getValue(AVKey.DATA_TYPE) == AVKey.INT16 && tiff.samplesPerPixel == 1) { short[][] image = this.tiffReader.readPlanar16(tiff.width, tiff.height, tiff.samplesPerPixel, - stripOffsets, stripCounts, tiff.rowsPerStrip); + stripOffsets, stripCounts, tiff.rowsPerStrip); grayImage = new BufferedImage(tiff.width, tiff.height, BufferedImage.TYPE_USHORT_GRAY); WritableRaster wrRaster = grayImage.getRaster(); int next = 0; - for (int y = 0; y < tiff.height; y++) - { - for (int x = 0; x < tiff.width; x++) - { + for (int y = 0; y < tiff.height; y++) { + for (int x = 0; x < tiff.width; x++) { wrRaster.setSample(x, y, 0, 0xFFFF & (int) (image[0][next++])); } } - } - else if (values.getValue(AVKey.DATA_TYPE) == AVKey.INT16 && tiff.samplesPerPixel > 1) - { + } else if (values.getValue(AVKey.DATA_TYPE) == AVKey.INT16 && tiff.samplesPerPixel > 1) { short[] image = this.tiffReader.read16bitPixelInterleavedImage(imageIndex, tiff.width, tiff.height, - tiff.samplesPerPixel, stripOffsets, stripCounts, tiff.rowsPerStrip); + tiff.samplesPerPixel, stripOffsets, stripCounts, tiff.rowsPerStrip); grayImage = new BufferedImage(tiff.width, tiff.height, BufferedImage.TYPE_USHORT_GRAY); WritableRaster wrRaster = grayImage.getRaster(); int next = 0; - for (int y = 0; y < tiff.height; y++) - { - for (int x = 0; x < tiff.width; x++) - { + for (int y = 0; y < tiff.height; y++) { + for (int x = 0; x < tiff.width; x++) { wrRaster.setSample(x, y, 0, 0xFFFF & (int) (image[next++])); } } } - if (null == grayImage) - { + if (null == grayImage) { String message = Logging.getMessage("Geotiff.UnsupportedDataTypeRaster", tiff.toString()); Logging.logger().severe(message); throw new IOException(message); @@ -434,103 +360,80 @@ else if (values.getValue(AVKey.DATA_TYPE) == AVKey.INT16 && tiff.samplesPerPixel grayImage = ImageUtil.toCompatibleImage(grayImage); return BufferedImageRaster.wrap(grayImage, values); - } - else if (values.getValue(AVKey.PIXEL_FORMAT) == AVKey.IMAGE - && values.getValue(AVKey.IMAGE_COLOR_FORMAT) == AVKey.COLOR) - { + } else if (values.getValue(AVKey.PIXEL_FORMAT) == AVKey.IMAGE + && values.getValue(AVKey.IMAGE_COLOR_FORMAT) == AVKey.COLOR) { ColorModel colorModel = null; WritableRaster raster; BufferedImage colorImage; // make sure a DataBufferByte is going to do the trick - for (int bits : tiff.bitsPerSample) - { - if (bits != 8) - { + for (int bits : tiff.bitsPerSample) { + if (bits != 8) { String message = Logging.getMessage("GeotiffReader.Not8bit", bits); Logging.logger().warning(message); throw new IOException(message); } } - if (tiff.photometric == Tiff.Photometric.Color_RGB) - { + if (tiff.photometric == Tiff.Photometric.Color_RGB) { int transparency = Transparency.OPAQUE; boolean hasAlpha = false; - if (tiff.samplesPerPixel == Tiff.SamplesPerPixel.RGB) - { + if (tiff.samplesPerPixel == Tiff.SamplesPerPixel.RGB) { transparency = Transparency.OPAQUE; hasAlpha = false; - } - else if (tiff.samplesPerPixel == Tiff.SamplesPerPixel.RGBA) - { + } else if (tiff.samplesPerPixel == Tiff.SamplesPerPixel.RGBA) { transparency = Transparency.TRANSLUCENT; hasAlpha = true; } colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), tiff.bitsPerSample, - hasAlpha, false, transparency, DataBuffer.TYPE_BYTE); - } - else if (tiff.photometric == Tiff.Photometric.Color_Palette) - { + hasAlpha, false, transparency, DataBuffer.TYPE_BYTE); + } else if (tiff.photometric == Tiff.Photometric.Color_Palette) { colorModel = new IndexColorModel(tiff.bitsPerSample[0], cmap[0].length, cmap[0], cmap[1], cmap[2]); - } - else if (tiff.photometric == Tiff.Photometric.CMYK) - { + } else if (tiff.photometric == Tiff.Photometric.CMYK) { // colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_), tiff.bitsPerSample, // false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); } int[] bankOffsets = new int[tiff.samplesPerPixel]; - for (int i = 0; i < tiff.samplesPerPixel; i++) - { + for (int i = 0; i < tiff.samplesPerPixel; i++) { bankOffsets[i] = i; } int[] offsets = new int[(tiff.planarConfig == Tiff.PlanarConfiguration.CHUNKY) ? 1 : tiff.samplesPerPixel]; - for (int i = 0; i < offsets.length; i++) - { + for (int i = 0; i < offsets.length; i++) { offsets[i] = 0; } // construct the right SampleModel... ComponentSampleModel sampleModel; - if (tiff.samplesPerPixel == Tiff.SamplesPerPixel.MONOCHROME) - { + if (tiff.samplesPerPixel == Tiff.SamplesPerPixel.MONOCHROME) { sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, tiff.width, tiff.height, 1, tiff.width, - bankOffsets); - } - else - { - sampleModel = (tiff.planarConfig == Tiff.PlanarConfiguration.CHUNKY) ? - new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, tiff.width, tiff.height, tiff.samplesPerPixel, - tiff.width * tiff.samplesPerPixel, bankOffsets) : - new BandedSampleModel(DataBuffer.TYPE_BYTE, tiff.width, tiff.height, tiff.width, bankOffsets, - offsets); + bankOffsets); + } else { + sampleModel = (tiff.planarConfig == Tiff.PlanarConfiguration.CHUNKY) + ? new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, tiff.width, tiff.height, tiff.samplesPerPixel, + tiff.width * tiff.samplesPerPixel, bankOffsets) + : new BandedSampleModel(DataBuffer.TYPE_BYTE, tiff.width, tiff.height, tiff.width, bankOffsets, + offsets); } // Get the image data and make our Raster... byte[][] imageData; - if (tiff.planarConfig == Tiff.PlanarConfiguration.CHUNKY) - { - if (lzwCompressed && (tiff.samplesPerPixel > 2)) - { + if (tiff.planarConfig == Tiff.PlanarConfiguration.CHUNKY) { + if (lzwCompressed && (tiff.samplesPerPixel > 2)) { imageData = new byte[1][tiff.width * tiff.height * tiff.samplesPerPixel]; imageData[0] = this.tiffReader.readLZWCompressed(tiff.width, tiff.height, offset, - tiff.samplesPerPixel, tiffDifferencing, stripOffsets, stripCounts); - } - else - { + tiff.samplesPerPixel, tiffDifferencing, stripOffsets, stripCounts); + } else { imageData = this.tiffReader.readPixelInterleaved8(tiff.width, tiff.height, tiff.samplesPerPixel, - stripOffsets, stripCounts); + stripOffsets, stripCounts); } - } - else - { + } else { imageData = this.tiffReader.readPlanar8(tiff.width, tiff.height, tiff.samplesPerPixel, stripOffsets, - stripCounts, tiff.rowsPerStrip); + stripCounts, tiff.rowsPerStrip); } DataBufferByte dataBuff = new DataBufferByte(imageData, tiff.width * tiff.height, offsets); @@ -538,8 +441,7 @@ else if (tiff.photometric == Tiff.Photometric.CMYK) colorImage = new BufferedImage(colorModel, raster, false, null); - if (null == colorImage) - { + if (null == colorImage) { String message = Logging.getMessage("Geotiff.UnsupportedDataTypeRaster", tiff.toString()); Logging.logger().severe(message); throw new IOException(message); @@ -561,11 +463,8 @@ else if (tiff.photometric == Tiff.Photometric.CMYK) * * @throws java.io.IOException if data type is not supported or unknown */ - - private void repackageGeoReferencingTags() throws IOException - { - for (int i = 0; i < this.getNumImages(); i++) - { + private void repackageGeoReferencingTags() throws IOException { + for (int i = 0; i < this.getNumImages(); i++) { TiffIFDEntry[] ifd = tiffIFDs.get(i); AVList values = this.metadata.get(i); @@ -575,23 +474,20 @@ private void repackageGeoReferencingTags() throws IOException BaselineTiff tiff = BaselineTiff.extract(ifd, this.tiffReader); - if (null == tiff) - { + if (null == tiff) { String message = Logging.getMessage("GeotiffReader.BadGeotiff"); Logging.logger().severe(message); throw new IOException(message); } - if (tiff.width == Tiff.Undefined) - { + if (tiff.width == Tiff.Undefined) { String message = Logging.getMessage("generic.InvalidWidth", tiff.width); Logging.logger().severe(message); throw new IOException(message); } values.setValue(AVKey.WIDTH, tiff.width); - if (tiff.height == Tiff.Undefined) - { + if (tiff.height == Tiff.Undefined) { String message = Logging.getMessage("generic.InvalidHeight", tiff.height); Logging.logger().severe(message); throw new IOException(message); @@ -601,103 +497,72 @@ private void repackageGeoReferencingTags() throws IOException int sampleFormat = (null != tiff.sampleFormat) ? tiff.sampleFormat[0] : Tiff.Undefined; int bitsPerSample = (null != tiff.bitsPerSample) ? tiff.bitsPerSample[0] : Tiff.Undefined; - if (null != tiff.displayName) - { + if (null != tiff.displayName) { values.setValue(AVKey.DISPLAY_NAME, tiff.displayName); } - if (null != tiff.imageDescription) - { + if (null != tiff.imageDescription) { values.setValue(AVKey.DESCRIPTION, tiff.imageDescription); } - if (null != tiff.softwareVersion) - { + if (null != tiff.softwareVersion) { values.setValue(AVKey.VERSION, tiff.softwareVersion); } - if (null != tiff.dateTime) - { + if (null != tiff.dateTime) { values.setValue(AVKey.DATE_TIME, tiff.dateTime); } - if (tiff.photometric == Tiff.Photometric.Color_RGB) - { + if (tiff.photometric == Tiff.Photometric.Color_RGB) { values.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); values.setValue(AVKey.IMAGE_COLOR_FORMAT, AVKey.COLOR); values.setValue(AVKey.DATA_TYPE, AVKey.INT8); - } - else if (tiff.photometric == Tiff.Photometric.CMYK) - { + } else if (tiff.photometric == Tiff.Photometric.CMYK) { values.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); values.setValue(AVKey.IMAGE_COLOR_FORMAT, AVKey.COLOR); values.setValue(AVKey.DATA_TYPE, AVKey.INT8); - } - else if (tiff.photometric == Tiff.Photometric.Color_Palette) - { + } else if (tiff.photometric == Tiff.Photometric.Color_Palette) { values.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); values.setValue(AVKey.IMAGE_COLOR_FORMAT, AVKey.COLOR); values.setValue(AVKey.DATA_TYPE, AVKey.INT8); - } - else if (tiff.samplesPerPixel == Tiff.SamplesPerPixel.MONOCHROME) - { // Tiff.Photometric.Grayscale_BlackIsZero or Tiff.Photometric.Grayscale_WhiteIsZero - if (sampleFormat == Tiff.SampleFormat.SIGNED) - { + } else if (tiff.samplesPerPixel == Tiff.SamplesPerPixel.MONOCHROME) { // Tiff.Photometric.Grayscale_BlackIsZero or Tiff.Photometric.Grayscale_WhiteIsZero + if (sampleFormat == Tiff.SampleFormat.SIGNED) { values.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); - if (bitsPerSample == Short.SIZE) - { + if (bitsPerSample == Short.SIZE) { values.setValue(AVKey.DATA_TYPE, AVKey.INT16); - } - else if (bitsPerSample == Byte.SIZE) - { + } else if (bitsPerSample == Byte.SIZE) { values.setValue(AVKey.DATA_TYPE, AVKey.INT8); - } - else if (bitsPerSample == Integer.SIZE) - { + } else if (bitsPerSample == Integer.SIZE) { values.setValue(AVKey.DATA_TYPE, AVKey.INT32); } - } - else if (sampleFormat == Tiff.SampleFormat.IEEEFLOAT) - { + } else if (sampleFormat == Tiff.SampleFormat.IEEEFLOAT) { values.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); - if (bitsPerSample == Float.SIZE) - { + if (bitsPerSample == Float.SIZE) { values.setValue(AVKey.DATA_TYPE, AVKey.FLOAT32); } - } - else if (sampleFormat == Tiff.SampleFormat.UNSIGNED) - { + } else if (sampleFormat == Tiff.SampleFormat.UNSIGNED) { values.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); values.setValue(AVKey.IMAGE_COLOR_FORMAT, AVKey.GRAYSCALE); - if (bitsPerSample == Short.SIZE) - { + if (bitsPerSample == Short.SIZE) { values.setValue(AVKey.DATA_TYPE, AVKey.INT16); - } - else if (bitsPerSample == Byte.SIZE) - { + } else if (bitsPerSample == Byte.SIZE) { values.setValue(AVKey.DATA_TYPE, AVKey.INT8); - } - else if (bitsPerSample == Integer.SIZE) - { + } else if (bitsPerSample == Integer.SIZE) { values.setValue(AVKey.DATA_TYPE, AVKey.INT32); } } } - if (!values.hasKey(AVKey.PIXEL_FORMAT) || !values.hasKey(AVKey.DATA_TYPE)) - { + if (!values.hasKey(AVKey.PIXEL_FORMAT) || !values.hasKey(AVKey.DATA_TYPE)) { String message = Logging.getMessage("Geotiff.UnsupportedDataTypeRaster", tiff.toString()); Logging.logger().severe(message); // throw new IOException(message); } // geo keys - for (TiffIFDEntry entry : ifd) - { - try - { - switch (entry.tag) - { + for (TiffIFDEntry entry : ifd) { + try { + switch (entry.tag) { case GeoTiff.Tag.GDAL_NODATA: Double d = Double.parseDouble(this.tiffReader.readString(entry)); values.setValue(AVKey.MISSING_DATA_SIGNAL, d); @@ -735,9 +600,7 @@ else if (bitsPerSample == Integer.SIZE) this.gc.setAsciiParams(this.tiffReader.readBytes(entry)); break; } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().finest(e.toString()); } } @@ -750,16 +613,12 @@ else if (bitsPerSample == Integer.SIZE) * Coordinates reading all the ImageFileDirectories in a Tiff file (there's typically only one). * */ - - private void readTiffHeaders() throws IOException - { - if (this.tiffIFDs != null) - { + private void readTiffHeaders() throws IOException { + if (this.tiffIFDs != null) { return; } - if (this.theChannel == null) - { + if (this.theChannel == null) { String message = Logging.getMessage("GeotiffReader.NullInputFile", this.sourceFilename); Logging.logger().severe(message); throw new IOException(message); @@ -774,10 +633,9 @@ private void readTiffHeaders() throws IOException byte b1 = array[1]; ByteOrder byteOrder = (b0 == 0x4D && b1 == 0x4D) ? ByteOrder.BIG_ENDIAN - : ((b0 == 0x49 && b1 == 0x49) ? ByteOrder.LITTLE_ENDIAN : null); + : ((b0 == 0x49 && b1 == 0x49) ? ByteOrder.LITTLE_ENDIAN : null); - if (null == byteOrder) - { + if (null == byteOrder) { String message = Logging.getMessage("GeotiffReader.BadTiffSig"); Logging.logger().severe(message); throw new IOException(message); @@ -801,19 +659,16 @@ private void readTiffHeaders() throws IOException this.repackageGeoReferencingTags(); } - private void processGeoKeys(int imageIndex) throws IOException - { + private void processGeoKeys(int imageIndex) throws IOException { this.checkImageIndex(imageIndex); AVList values = this.metadata.get(imageIndex); if (null == values - || null == this.gc - || !this.gc.hasGeoKey(GeoTiff.GeoKey.ModelType) - || !values.hasKey(AVKey.WIDTH) - || !values.hasKey(AVKey.HEIGHT) - ) - { + || null == this.gc + || !this.gc.hasGeoKey(GeoTiff.GeoKey.ModelType) + || !values.hasKey(AVKey.WIDTH) + || !values.hasKey(AVKey.HEIGHT)) { return; } @@ -821,43 +676,33 @@ private void processGeoKeys(int imageIndex) throws IOException int height = (Integer) values.getValue(AVKey.HEIGHT); // geo-tiff spec requires the VerticalCSType to be present for elevations (but ignores its value) - if (this.gc.hasGeoKey(GeoTiff.GeoKey.VerticalCSType)) - { + if (this.gc.hasGeoKey(GeoTiff.GeoKey.VerticalCSType)) { values.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); } - if (this.gc.hasGeoKey(GeoTiff.GeoKey.VerticalUnits)) - { + if (this.gc.hasGeoKey(GeoTiff.GeoKey.VerticalUnits)) { int[] v = this.gc.getGeoKeyAsInts(GeoTiff.GeoKey.VerticalUnits); int units = (null != v && v.length > 0) ? v[0] : GeoTiff.Undefined; - if (units == GeoTiff.Unit.Linear.Meter) - { + if (units == GeoTiff.Unit.Linear.Meter) { values.setValue(AVKey.ELEVATION_UNIT, AVKey.UNIT_METER); - } - else if (units == GeoTiff.Unit.Linear.Foot) - { + } else if (units == GeoTiff.Unit.Linear.Foot) { values.setValue(AVKey.ELEVATION_UNIT, AVKey.UNIT_FOOT); } } - if (this.gc.hasGeoKey(GeoTiff.GeoKey.RasterType)) - { + if (this.gc.hasGeoKey(GeoTiff.GeoKey.RasterType)) { int[] v = this.gc.getGeoKeyAsInts(GeoTiff.GeoKey.RasterType); int rasterType = (null != v && v.length > 0) ? v[0] : GeoTiff.Undefined; - if (rasterType == GeoTiff.RasterType.RasterPixelIsArea) - { + if (rasterType == GeoTiff.RasterType.RasterPixelIsArea) { values.setValue(AVKey.RASTER_PIXEL, AVKey.RASTER_PIXEL_IS_AREA); - } - else if (rasterType == GeoTiff.RasterType.RasterPixelIsPoint) - { + } else if (rasterType == GeoTiff.RasterType.RasterPixelIsPoint) { values.setValue(AVKey.RASTER_PIXEL, AVKey.RASTER_PIXEL_IS_POINT); } } - if (this.gc.hasGeoKey(GeoTiff.GeoKey.GeogAngularUnits)) - { + if (this.gc.hasGeoKey(GeoTiff.GeoKey.GeogAngularUnits)) { // int[] v = this.gc.getGeoKeyAsInts( GeoTiff.GeoKey.GeogAngularUnits ); // int unit = ( null != v && v.length > 0 ) ? v[0] : GeoTiff.Undefined; // @@ -869,46 +714,36 @@ else if (rasterType == GeoTiff.RasterType.RasterPixelIsPoint) // AVKey.PROJECTION_DESC Optional, // AVKey.PROJECTION_NAME Optional, // AVKey.PROJECTION_UNITS Optional, - int gtModelTypeGeoKey = GeoTiff.ModelType.Undefined; - if (this.gc.hasGeoKey(GeoTiff.GeoKey.ModelType)) - { + if (this.gc.hasGeoKey(GeoTiff.GeoKey.ModelType)) { int[] gkValues = this.gc.getGeoKeyAsInts(GeoTiff.GeoKey.ModelType); - if (null != gkValues && gkValues.length > 0) - { + if (null != gkValues && gkValues.length > 0) { gtModelTypeGeoKey = gkValues[0]; } } - if (gtModelTypeGeoKey == GeoTiff.ModelType.Geographic) - { + if (gtModelTypeGeoKey == GeoTiff.ModelType.Geographic) { values.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC); int epsg = GeoTiff.GCS.Undefined; - if (this.gc.hasGeoKey(GeoTiff.GeoKey.GeographicType)) - { + if (this.gc.hasGeoKey(GeoTiff.GeoKey.GeographicType)) { int[] gkValues = this.gc.getGeoKeyAsInts(GeoTiff.GeoKey.GeographicType); - if (null != gkValues && gkValues.length > 0) - { + if (null != gkValues && gkValues.length > 0) { epsg = gkValues[0]; } } - if (epsg != GeoTiff.GCS.Undefined) - { + if (epsg != GeoTiff.GCS.Undefined) { values.setValue(AVKey.PROJECTION_EPSG_CODE, epsg); } // TODO Assumes WGS84(4326)- should we check for this ? - double[] bbox = this.gc.getBoundingBox(width, height); values.setValue(AVKey.SECTOR, Sector.fromDegrees(bbox[3], bbox[1], bbox[0], bbox[2])); values.setValue(AVKey.ORIGIN, LatLon.fromDegrees(bbox[1], bbox[0])); - } - else if (gtModelTypeGeoKey == GeoTiff.ModelType.Projected) - { + } else if (gtModelTypeGeoKey == GeoTiff.ModelType.Projected) { values.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_PROJECTED); int projection = GeoTiff.PCS.Undefined; @@ -916,22 +751,17 @@ else if (gtModelTypeGeoKey == GeoTiff.ModelType.Projected) int zone; int[] vals = null; - if (this.gc.hasGeoKey(GeoTiff.GeoKey.Projection)) - { + if (this.gc.hasGeoKey(GeoTiff.GeoKey.Projection)) { vals = this.gc.getGeoKeyAsInts(GeoTiff.GeoKey.Projection); - } - else if (this.gc.hasGeoKey(GeoTiff.GeoKey.ProjectedCSType)) - { + } else if (this.gc.hasGeoKey(GeoTiff.GeoKey.ProjectedCSType)) { vals = this.gc.getGeoKeyAsInts(GeoTiff.GeoKey.ProjectedCSType); } - if (null != vals && vals.length > 0) - { + if (null != vals && vals.length > 0) { projection = vals[0]; } - if (projection != GeoTiff.PCS.Undefined) - { + if (projection != GeoTiff.PCS.Undefined) { values.setValue(AVKey.PROJECTION_EPSG_CODE, projection); } @@ -941,54 +771,44 @@ else if (this.gc.hasGeoKey(GeoTiff.GeoKey.ProjectedCSType)) from http://www.remotesensing.org/geotiff/spec/geotiff6.html#6.3.3.2 UTM (North) Format: 160zz UTM (South) Format: 161zz - */ - if ((projection >= 16100) && (projection <= 16199)) //UTM Zone South + */ + if ((projection >= 16100) && (projection <= 16199)) //UTM Zone South { hemi = AVKey.SOUTH; zone = projection - 16100; - } - else if ((projection >= 16000) && (projection <= 16099)) //UTM Zone North + } else if ((projection >= 16000) && (projection <= 16099)) //UTM Zone North { hemi = AVKey.NORTH; zone = projection - 16000; - } - else if ((projection >= 26900) && (projection <= 26999)) //UTM : NAD83 + } else if ((projection >= 26900) && (projection <= 26999)) //UTM : NAD83 { hemi = AVKey.NORTH; zone = projection - 26900; - } - else if ((projection >= 32201) && (projection <= 32260)) //UTM : WGS72 N + } else if ((projection >= 32201) && (projection <= 32260)) //UTM : WGS72 N { hemi = AVKey.NORTH; zone = projection - 32200; - } - else if ((projection >= 32301) && (projection <= 32360)) //UTM : WGS72 S + } else if ((projection >= 32301) && (projection <= 32360)) //UTM : WGS72 S { hemi = AVKey.SOUTH; zone = projection - 32300; - } - else if ((projection >= 32401) && (projection <= 32460)) //UTM : WGS72BE N + } else if ((projection >= 32401) && (projection <= 32460)) //UTM : WGS72BE N { hemi = AVKey.NORTH; zone = projection - 32400; - } - else if ((projection >= 32501) && (projection <= 32560)) //UTM : WGS72BE S + } else if ((projection >= 32501) && (projection <= 32560)) //UTM : WGS72BE S { hemi = AVKey.SOUTH; zone = projection - 32500; - } - else if ((projection >= 32601) && (projection <= 32660)) //UTM : WGS84 N + } else if ((projection >= 32601) && (projection <= 32660)) //UTM : WGS84 N { hemi = AVKey.NORTH; zone = projection - 32600; - } - else if ((projection >= 32701) && (projection <= 32760)) //UTM : WGS84 S + } else if ((projection >= 32701) && (projection <= 32760)) //UTM : WGS84 S { hemi = AVKey.SOUTH; zone = projection - 32700; - } - else - { + } else { String message = Logging.getMessage("generic.UnknownProjection", projection); Logging.logger().severe(message); // throw new IOException(message); @@ -1006,8 +826,7 @@ else if ((projection >= 32701) && (projection <= 32760)) //UTM : WGS84 S //shift to center GeoCodec.ModelTiePoint[] tps = this.gc.getTiePoints(); - if (null != tps && tps.length > imageIndex) - { + if (null != tps && tps.length > imageIndex) { GeoCodec.ModelTiePoint tp = tps[imageIndex]; double xD = tp.getX() + (pixelScaleX / 2d); @@ -1018,9 +837,7 @@ else if ((projection >= 32701) && (projection <= 32760)) //UTM : WGS84 S } values.setValue(AVKey.SECTOR, ImageUtil.calcBoundingBoxForUTM(values)); - } - else - { + } else { String msg = Logging.getMessage("Geotiff.UnknownGeoKeyValue", gtModelTypeGeoKey, GeoTiff.GeoKey.ModelType); Logging.logger().severe(msg); // throw new IOException(msg); @@ -1035,27 +852,21 @@ else if ((projection >= 32701) && (projection <= 32760)) //UTM : WGS84 S * Calls itself recursively if additional IFDs are indicated. * */ - - private void readIFD(int numEntries) throws IOException - { - try - { - if (null == this.tiffIFDs) - { + private void readIFD(int numEntries) throws IOException { + try { + if (null == this.tiffIFDs) { this.tiffIFDs = new ArrayList(); } java.util.List ifd = new ArrayList(); - for (int i = 0; i < numEntries; i++) - { + for (int i = 0; i < numEntries; i++) { ifd.add(TIFFIFDFactory.create(this.theChannel, this.tiffReader.getByteOrder())); } TiffIFDEntry[] array = ifd.toArray(new TiffIFDEntry[ifd.size()]); this.tiffIFDs.add(array); - if (null == this.metadata) - { + if (null == this.metadata) { this.metadata = new ArrayList(); } this.metadata.add(new AVListImpl()); @@ -1066,17 +877,14 @@ private void readIFD(int numEntries) throws IOException // If there's another IFD in this file, go get it (recursively)... long nextIFDOffset = TIFFReader.getUnsignedInt(bb); - if (nextIFDOffset > 0) - { + if (nextIFDOffset > 0) { this.theChannel.position(nextIFDOffset); bb.clear().limit(2); this.theChannel.read(bb); bb.flip(); readIFD(bb.getShort()); } - } - catch (Exception ex) - { + } catch (Exception ex) { String message = Logging.getMessage("GeotiffReader.BadIFD", ex.getMessage()); Logging.logger().severe(message); throw new IOException(message); @@ -1086,14 +894,10 @@ private void readIFD(int numEntries) throws IOException /* * Returns the (first!) IFD-Entry with the given tag, or null if not found. * - */ - - private TiffIFDEntry getByTag(TiffIFDEntry[] ifd, int tag) - { - for (TiffIFDEntry anIfd : ifd) - { - if (anIfd.tag == tag) - { + */ + private TiffIFDEntry getByTag(TiffIFDEntry[] ifd, int tag) { + for (TiffIFDEntry anIfd : ifd) { + if (anIfd.tag == tag) { return anIfd; } } @@ -1105,11 +909,8 @@ private TiffIFDEntry getByTag(TiffIFDEntry[] ifd, int tag) * We throw an IllegalArgumentException if the index is not valid, otherwise, silently return. * */ - - private void checkImageIndex(int imageIndex) throws IOException - { - if (imageIndex < 0 || imageIndex >= getNumImages()) - { + private void checkImageIndex(int imageIndex) throws IOException { + if (imageIndex < 0 || imageIndex >= getNumImages()) { String message = Logging.getMessage("GeotiffReader.BadImageIndex", imageIndex, 0, getNumImages()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1120,24 +921,19 @@ private void checkImageIndex(int imageIndex) throws IOException * Make sure we release this resource... * */ - public void dispose() - { - try - { + public void dispose() { + try { WWIO.closeStream(this.theChannel, this.sourceFilename); WWIO.closeStream(this.sourceFile, this.sourceFilename); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = t.getMessage(); message = (WWUtil.isEmpty(message)) ? t.getCause().getMessage() : message; Logging.logger().log(java.util.logging.Level.FINEST, message, t); } } - protected void finalize() throws Throwable - { + protected void finalize() throws Throwable { this.dispose(); super.finalize(); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/tiff/GeotiffWriter.java b/src/gov/nasa/worldwind/formats/tiff/GeotiffWriter.java index 5c5d469ea9..e17a68ec67 100644 --- a/src/gov/nasa/worldwind/formats/tiff/GeotiffWriter.java +++ b/src/gov/nasa/worldwind/formats/tiff/GeotiffWriter.java @@ -22,9 +22,8 @@ * @author Lado Garakanidze * @version $Id: GeotiffWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class GeotiffWriter { -public class GeotiffWriter -{ private RandomAccessFile targetFile; private FileChannel theChannel; @@ -34,10 +33,8 @@ public class GeotiffWriter private static final int BufferedImage_TYPE_ELEVATION_SHORT16 = 9001; private static final int BufferedImage_TYPE_ELEVATION_FLOAT32 = 9002; - public GeotiffWriter(String filename) throws IOException - { - if (null == filename || 0 == filename.trim().length()) - { + public GeotiffWriter(String filename) throws IOException { + if (null == filename || 0 == filename.trim().length()) { String msg = Logging.getMessage("generic.FileNameIsMissing"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -47,10 +44,8 @@ public GeotiffWriter(String filename) throws IOException commonInitializer(new File(filename)); } - public GeotiffWriter(File file) throws IOException - { - if (null == file) - { + public GeotiffWriter(File file) throws IOException { + if (null == file) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -62,14 +57,12 @@ public GeotiffWriter(File file) throws IOException // // Merely consolidates the error checking for the ctors in one place. // - - private void commonInitializer(File file) throws IOException - { + private void commonInitializer(File file) throws IOException { File parent = file.getParentFile(); - if (parent == null) + if (parent == null) { parent = new File(System.getProperty("user.dir")); - if (!parent.canWrite()) - { + } + if (!parent.canWrite()) { String msg = Logging.getMessage("generic.FolderNoWritePermission", parent.getAbsolutePath()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -79,50 +72,39 @@ private void commonInitializer(File file) throws IOException this.theChannel = this.targetFile.getChannel(); } - public void close() - { - try - { + public void close() { + try { this.targetFile.close(); - } - catch (Exception ex) - { /* best effort */ } + } catch (Exception ex) { + /* best effort */ } } - public void write(BufferedImage image) throws IOException - { + public void write(BufferedImage image) throws IOException { this.write(image, null); } - public void write(DataRaster raster) throws IOException, IllegalArgumentException - { - if (null == raster) - { + public void write(DataRaster raster) throws IOException, IllegalArgumentException { + if (null == raster) { String msg = Logging.getMessage("nullValue.RasterIsNull"); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (!(raster.getWidth() > 0)) - { + if (!(raster.getWidth() > 0)) { String msg = Logging.getMessage("generic.InvalidWidth", raster.getWidth()); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (!(raster.getHeight() > 0)) - { + if (!(raster.getHeight() > 0)) { String msg = Logging.getMessage("generic.InvalidHeight", raster.getHeight()); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (raster instanceof BufferedImageRaster) - { + if (raster instanceof BufferedImageRaster) { this.write(((BufferedImageRaster) raster).getBufferedImage(), raster); - } - else if (raster instanceof BufferWrapperRaster) - { + } else if (raster instanceof BufferWrapperRaster) { this.writeRaster((BufferWrapperRaster) raster); } } @@ -191,32 +173,25 @@ If CS is Geodetic and EPSG code is not specified, a default WGS84 (4326) will be if not specified, default for images is RASTER_PIXEL_IS_AREA, and AVKey.RASTER_PIXEL_IS_POINT for elevations - */ - - public void write(BufferedImage image, AVList params) throws IOException - { - if (image == null) - { + */ + public void write(BufferedImage image, AVList params) throws IOException { + if (image == null) { String msg = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (0 == image.getWidth() || 0 == image.getHeight()) - { + if (0 == image.getWidth() || 0 == image.getHeight()) { String msg = Logging.getMessage("generic.InvalidImageSize", image.getWidth(), image.getHeight()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (null == params || 0 == params.getValues().size()) - { + if (null == params || 0 == params.getValues().size()) { String reason = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().finest(Logging.getMessage("GeotiffWriter.GeoKeysMissing", reason)); params = new AVListImpl(); - } - else - { + } else { this.validateParameters(params, image.getWidth(), image.getHeight()); } @@ -224,13 +199,11 @@ public void write(BufferedImage image, AVList params) throws IOException int type = image.getType(); // handle CUSTOM type which comes from our GeoTiffreader (for now) - if (BufferedImage.TYPE_CUSTOM == type) - { + if (BufferedImage.TYPE_CUSTOM == type) { int numColorComponents = 0, numComponents = 0, pixelSize = 0, dataType = 0, csType = 0; boolean hasAlpha = false; - if (null != image.getColorModel()) - { + if (null != image.getColorModel()) { ColorModel cm = image.getColorModel(); numColorComponents = cm.getNumColorComponents(); @@ -239,66 +212,51 @@ public void write(BufferedImage image, AVList params) throws IOException hasAlpha = cm.hasAlpha(); ColorSpace cs = cm.getColorSpace(); - if (null != cs) + if (null != cs) { csType = cs.getType(); + } } - if (null != image.getSampleModel()) - { + if (null != image.getSampleModel()) { SampleModel sm = image.getSampleModel(); dataType = sm.getDataType(); } - if (dataType == DataBuffer.TYPE_FLOAT && pixelSize == Float.SIZE && numComponents == 1) - { + if (dataType == DataBuffer.TYPE_FLOAT && pixelSize == Float.SIZE && numComponents == 1) { type = BufferedImage_TYPE_ELEVATION_FLOAT32; - } - else if (dataType == DataBuffer.TYPE_SHORT && pixelSize == Short.SIZE && numComponents == 1) - { + } else if (dataType == DataBuffer.TYPE_SHORT && pixelSize == Short.SIZE && numComponents == 1) { type = BufferedImage_TYPE_ELEVATION_SHORT16; - } - else if (ColorSpace.CS_GRAY == csType && pixelSize == Byte.SIZE) - { + } else if (ColorSpace.CS_GRAY == csType && pixelSize == Byte.SIZE) { type = BufferedImage.TYPE_BYTE_GRAY; - } - else if (dataType == DataBuffer.TYPE_USHORT && ColorSpace.CS_GRAY == csType && pixelSize == Short.SIZE) - { + } else if (dataType == DataBuffer.TYPE_USHORT && ColorSpace.CS_GRAY == csType && pixelSize == Short.SIZE) { type = BufferedImage.TYPE_USHORT_GRAY; - } - else if (ColorSpace.TYPE_RGB == csType && pixelSize == 3 * Byte.SIZE && numColorComponents == 3) - { + } else if (ColorSpace.TYPE_RGB == csType && pixelSize == 3 * Byte.SIZE && numColorComponents == 3) { type = BufferedImage.TYPE_3BYTE_BGR; - } - else if (ColorSpace.TYPE_RGB == csType && hasAlpha && pixelSize == 4 * Byte.SIZE && numComponents == 4) - { + } else if (ColorSpace.TYPE_RGB == csType && hasAlpha && pixelSize == 4 * Byte.SIZE && numComponents == 4) { type = BufferedImage.TYPE_4BYTE_ABGR; } } - switch (type) - { + switch (type) { case BufferedImage.TYPE_3BYTE_BGR: case BufferedImage.TYPE_4BYTE_ABGR: case BufferedImage.TYPE_4BYTE_ABGR_PRE: case BufferedImage.TYPE_INT_RGB: case BufferedImage.TYPE_INT_BGR: case BufferedImage.TYPE_INT_ARGB: - case BufferedImage.TYPE_INT_ARGB_PRE: - { + case BufferedImage.TYPE_INT_ARGB_PRE: { this.writeColorImage(image, params); } break; case BufferedImage.TYPE_USHORT_GRAY: - case BufferedImage.TYPE_BYTE_GRAY: - { + case BufferedImage.TYPE_BYTE_GRAY: { this.writeGrayscaleImage(image, params); } break; case BufferedImage_TYPE_ELEVATION_SHORT16: - case BufferedImage_TYPE_ELEVATION_FLOAT32: - { + case BufferedImage_TYPE_ELEVATION_FLOAT32: { String msg = Logging.getMessage("GeotiffWriter.FeatureNotImplementedd", type); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -306,8 +264,7 @@ else if (ColorSpace.TYPE_RGB == csType && hasAlpha && pixelSize == 4 * Byte.SIZE // break; case BufferedImage.TYPE_CUSTOM: - default: - { + default: { ColorModel cm = image.getColorModel(); SampleModel sm = image.getSampleModel(); @@ -328,8 +285,7 @@ else if (ColorSpace.TYPE_RGB == csType && hasAlpha && pixelSize == 4 * Byte.SIZE } } - private void writeColorImage(BufferedImage image, AVList params) throws IOException - { + private void writeColorImage(BufferedImage image, AVList params) throws IOException { int numBands = image.getRaster().getNumBands(); long offset; @@ -343,14 +299,12 @@ private void writeColorImage(BufferedImage image, AVList params) throws IOExcept ByteBuffer dataBuff = ByteBuffer.allocateDirect(numCols * numBands); Raster rast = image.getRaster(); - for (int i = 0; i < numRows; i++) - { + for (int i = 0; i < numRows; i++) { stripOffsets[i] = (int) this.theChannel.position(); stripCounts[i] = numCols * numBands; int[] rowData = rast.getPixels(0, i, image.getWidth(), 1, (int[]) null); dataBuff.clear(); - for (int j = 0; j < numCols * numBands; j++) - { + for (int j = 0; j < numCols * numBands; j++) { putUnsignedByte(dataBuff, rowData[j]); } dataBuff.flip(); @@ -374,8 +328,7 @@ private void writeColorImage(BufferedImage image, AVList params) throws IOExcept offset = this.theChannel.position(); short[] bps = new short[numBands]; - for (int i = 0; i < numBands; i++) - { + for (int i = 0; i < numBands; i++) { bps[i] = Tiff.BitsPerSample.MONOCHROME_BYTE; } this.theChannel.write(ByteBuffer.wrap(this.getBytes(bps))); @@ -383,8 +336,7 @@ private void writeColorImage(BufferedImage image, AVList params) throws IOExcept offset = this.theChannel.position(); dataBuff = ByteBuffer.allocateDirect(stripOffsets.length * INTEGER_SIZEOF); - for (int stripOffset : stripOffsets) - { + for (int stripOffset : stripOffsets) { dataBuff.putInt(stripOffset); } dataBuff.flip(); @@ -395,8 +347,7 @@ private void writeColorImage(BufferedImage image, AVList params) throws IOExcept offset = this.theChannel.position(); dataBuff.clear(); // stripOffsets and stripCounts are same length by design; can reuse the ByteBuffer... - for (int stripCount : stripCounts) - { + for (int stripCount : stripCounts) { dataBuff.putInt(stripCount); } dataBuff.flip(); @@ -411,13 +362,11 @@ private void writeColorImage(BufferedImage image, AVList params) throws IOExcept // // We only support 8-bit and 16-bit currently (Tiff spec allows for 4 bit/sample). // - - private void writeGrayscaleImage(BufferedImage image, AVList params) throws IOException - { + private void writeGrayscaleImage(BufferedImage image, AVList params) throws IOException { int type = image.getType(); int bitsPerSample = (BufferedImage.TYPE_USHORT_GRAY == type) - ? Tiff.BitsPerSample.MONOCHROME_UINT16 : Tiff.BitsPerSample.MONOCHROME_UINT8; + ? Tiff.BitsPerSample.MONOCHROME_UINT16 : Tiff.BitsPerSample.MONOCHROME_UINT8; int numBands = image.getSampleModel().getNumBands(); // well, numBands for GrayScale images must be 1 @@ -434,24 +383,18 @@ private void writeGrayscaleImage(BufferedImage image, AVList params) throws IOEx ByteBuffer dataBuff = ByteBuffer.allocateDirect(numCols * bytesPerSample); Raster rast = image.getRaster(); - for (int i = 0; i < numRows; i++) - { + for (int i = 0; i < numRows; i++) { stripOffsets[i] = (int) this.theChannel.position(); stripCounts[i] = numCols * bytesPerSample; int[] rowData = rast.getPixels(0, i, image.getWidth(), 1, (int[]) null); dataBuff.clear(); - if (BufferedImage.TYPE_USHORT_GRAY == type) - { - for (int j = 0; j < numCols * numBands; j++) - { + if (BufferedImage.TYPE_USHORT_GRAY == type) { + for (int j = 0; j < numCols * numBands; j++) { this.putUnsignedShort(dataBuff, rowData[j]); } - } - else if (BufferedImage.TYPE_BYTE_GRAY == type) - { - for (int j = 0; j < numCols * numBands; j++) - { + } else if (BufferedImage.TYPE_BYTE_GRAY == type) { + for (int j = 0; j < numCols * numBands; j++) { this.putUnsignedByte(dataBuff, rowData[j]); } } @@ -468,13 +411,12 @@ else if (BufferedImage.TYPE_BYTE_GRAY == type) ifds.add(new TiffIFDEntry(Tiff.Tag.BITS_PER_SAMPLE, Tiff.Type.SHORT, 1, bitsPerSample)); ifds.add(new TiffIFDEntry(Tiff.Tag.COMPRESSION, Tiff.Type.LONG, 1, Tiff.Compression.NONE)); ifds.add(new TiffIFDEntry(Tiff.Tag.PHOTO_INTERPRETATION, Tiff.Type.SHORT, 1, - Tiff.Photometric.Grayscale_BlackIsZero)); + Tiff.Photometric.Grayscale_BlackIsZero)); ifds.add(new TiffIFDEntry(Tiff.Tag.SAMPLE_FORMAT, Tiff.Type.SHORT, 1, Tiff.SampleFormat.UNSIGNED)); long offset = this.theChannel.position(); dataBuff = ByteBuffer.allocateDirect(stripOffsets.length * INTEGER_SIZEOF); - for (int stripOffset : stripOffsets) - { + for (int stripOffset : stripOffsets) { dataBuff.putInt(stripOffset); } dataBuff.flip(); @@ -487,8 +429,7 @@ else if (BufferedImage.TYPE_BYTE_GRAY == type) offset = this.theChannel.position(); dataBuff.clear(); // stripOffsets and stripCounts are same length by design; can reuse the ByteBuffer... - for (int stripCount : stripCounts) - { + for (int stripCount : stripCounts) { dataBuff.putInt(stripCount); } dataBuff.flip(); @@ -500,8 +441,7 @@ else if (BufferedImage.TYPE_BYTE_GRAY == type) this.writeIFDs(ifds); } - private void writeTiffHeader() throws IOException - { + private void writeTiffHeader() throws IOException { // A TIFF file begins with an 8-byte image file header, containing the following information: // // Bytes 0-1: The byte order used within the file. @@ -513,15 +453,13 @@ private void writeTiffHeader() throws IOException // that further identifies the file as a TIFF file. The byte order depends on the value of Bytes 0-1. // // Bytes 4-7 The offset (in bytes) of the first IFD. - byte[] tiffHeader = new byte[] {0x4D, 0x4D, 0, 42, 0, 0, 0, 0}; + byte[] tiffHeader = new byte[]{0x4D, 0x4D, 0, 42, 0, 0, 0, 0}; // we'll patch up int16 (last 4 bytes) later after writing the image... this.theChannel.write(ByteBuffer.wrap(tiffHeader)); } - private void appendGeoTiff(ArrayList ifds, AVList params) throws IOException, IllegalArgumentException - { - if (null == params || 0 == params.getEntries().size()) - { + private void appendGeoTiff(ArrayList ifds, AVList params) throws IOException, IllegalArgumentException { + if (null == params || 0 == params.getEntries().size()) { String reason = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().finest(Logging.getMessage("GeotiffWriter.GeoKeysMissing", reason)); return; @@ -529,11 +467,9 @@ private void appendGeoTiff(ArrayList ifds, AVList params) throws I long offset = this.theChannel.position(); - if (params.hasKey(AVKey.DISPLAY_NAME)) - { + if (params.hasKey(AVKey.DISPLAY_NAME)) { String value = params.getStringValue(AVKey.DISPLAY_NAME); - if (null != value && 0 < value.trim().length()) - { + if (null != value && 0 < value.trim().length()) { offset = this.theChannel.position(); byte[] bytes = value.trim().getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); @@ -541,11 +477,9 @@ private void appendGeoTiff(ArrayList ifds, AVList params) throws I } } - if (params.hasKey(AVKey.DESCRIPTION)) - { + if (params.hasKey(AVKey.DESCRIPTION)) { String value = params.getStringValue(AVKey.DESCRIPTION); - if (null != value && 0 < value.trim().length()) - { + if (null != value && 0 < value.trim().length()) { offset = this.theChannel.position(); byte[] bytes = value.trim().getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); @@ -553,11 +487,9 @@ private void appendGeoTiff(ArrayList ifds, AVList params) throws I } } - if (params.hasKey(AVKey.VERSION)) - { + if (params.hasKey(AVKey.VERSION)) { String value = params.getStringValue(AVKey.VERSION); - if (null != value && 0 < value.trim().length()) - { + if (null != value && 0 < value.trim().length()) { offset = this.theChannel.position(); byte[] bytes = value.trim().getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); @@ -565,11 +497,9 @@ private void appendGeoTiff(ArrayList ifds, AVList params) throws I } } - if (params.hasKey(AVKey.DATE_TIME)) - { + if (params.hasKey(AVKey.DATE_TIME)) { String value = params.getStringValue(AVKey.DATE_TIME); - if (null != value && 0 < value.trim().length()) - { + if (null != value && 0 < value.trim().length()) { offset = this.theChannel.position(); byte[] bytes = value.getBytes(); this.theChannel.write(ByteBuffer.wrap(bytes)); @@ -577,24 +507,20 @@ private void appendGeoTiff(ArrayList ifds, AVList params) throws I } } - if (params.hasKey(AVKey.SECTOR)) - { - if (params.hasKey(AVKey.PIXEL_WIDTH) && params.hasKey(AVKey.PIXEL_HEIGHT)) - { + if (params.hasKey(AVKey.SECTOR)) { + if (params.hasKey(AVKey.PIXEL_WIDTH) && params.hasKey(AVKey.PIXEL_HEIGHT)) { offset = this.theChannel.position(); - double[] values = new double[] - { - (Double) params.getValue(AVKey.PIXEL_WIDTH), - (Double) params.getValue(AVKey.PIXEL_HEIGHT), - isElevation(params) ? 1d : 0d - }; + double[] values = new double[]{ + (Double) params.getValue(AVKey.PIXEL_WIDTH), + (Double) params.getValue(AVKey.PIXEL_HEIGHT), + isElevation(params) ? 1d : 0d + }; byte[] bytes = this.getBytes(values); this.theChannel.write(ByteBuffer.wrap(bytes)); ifds.add(new TiffIFDEntry(GeoTiff.Tag.MODEL_PIXELSCALE, Tiff.Type.DOUBLE, values.length, offset)); } - if (params.hasKey(AVKey.WIDTH) && params.hasKey(AVKey.HEIGHT)) - { + if (params.hasKey(AVKey.WIDTH) && params.hasKey(AVKey.HEIGHT)) { offset = this.theChannel.position(); double w = (Integer) params.getValue(AVKey.WIDTH); @@ -602,13 +528,11 @@ private void appendGeoTiff(ArrayList ifds, AVList params) throws I Sector sec = (Sector) params.getValue(AVKey.SECTOR); - double[] values = new double[] - { // i , j, k=0, x, y, z=0 - 0d, 0d, 0d, sec.getMinLongitude().degrees, sec.getMaxLatitude().degrees, 0d, - w - 1, 0d, 0d, sec.getMaxLongitude().degrees, sec.getMaxLatitude().degrees, 0d, - w - 1, h - 1, 0d, sec.getMaxLongitude().degrees, sec.getMinLatitude().degrees, 0d, - 0d, h - 1, 0d, sec.getMinLongitude().degrees, sec.getMinLatitude().degrees, 0d, - }; + double[] values = new double[]{ // i , j, k=0, x, y, z=0 + 0d, 0d, 0d, sec.getMinLongitude().degrees, sec.getMaxLatitude().degrees, 0d, + w - 1, 0d, 0d, sec.getMaxLongitude().degrees, sec.getMaxLatitude().degrees, 0d, + w - 1, h - 1, 0d, sec.getMaxLongitude().degrees, sec.getMinLatitude().degrees, 0d, + 0d, h - 1, 0d, sec.getMinLongitude().degrees, sec.getMinLatitude().degrees, 0d,}; byte[] bytes = this.getBytes(values); this.theChannel.write(ByteBuffer.wrap(bytes)); @@ -616,14 +540,12 @@ private void appendGeoTiff(ArrayList ifds, AVList params) throws I } // Tiff.Tag.MODEL_TRANSFORMATION excludes Tiff.Tag.MODEL_TIEPOINT & Tiff.Tag.MODEL_PIXELSCALE - - if (params.hasKey(AVKey.MISSING_DATA_SIGNAL) || params.hasKey(AVKey.MISSING_DATA_REPLACEMENT)) - { + if (params.hasKey(AVKey.MISSING_DATA_SIGNAL) || params.hasKey(AVKey.MISSING_DATA_REPLACEMENT)) { offset = this.theChannel.position(); Object nodata = params.hasKey(AVKey.MISSING_DATA_SIGNAL) - ? params.getValue(AVKey.MISSING_DATA_SIGNAL) - : params.getValue(AVKey.MISSING_DATA_REPLACEMENT); + ? params.getValue(AVKey.MISSING_DATA_SIGNAL) + : params.getValue(AVKey.MISSING_DATA_REPLACEMENT); String value = "" + nodata + "\0"; byte[] bytes = value.getBytes(); @@ -631,26 +553,21 @@ private void appendGeoTiff(ArrayList ifds, AVList params) throws I ifds.add(new TiffIFDEntry(GeoTiff.Tag.GDAL_NODATA, Tiff.Type.ASCII, bytes.length, offset)); } - if (params.hasKey(AVKey.COORDINATE_SYSTEM)) - { + if (params.hasKey(AVKey.COORDINATE_SYSTEM)) { String cs = params.getStringValue(AVKey.COORDINATE_SYSTEM); - if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) - { - if (isElevation(params)) + if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) { + if (isElevation(params)) { this.writeGeographicElevationGeoKeys(ifds, params); - else + } else { this.writeGeographicImageGeoKeys(ifds, params); - } - else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(cs)) - { + } + } else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(cs)) { String msg = Logging.getMessage("GeotiffWriter.FeatureNotImplementedd", cs); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); // TODO extract PCS (Projection Coordinate System) - } - else - { + } else { String msg = Logging.getMessage("GeotiffWriter.UnknownCoordinateSystem", cs); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -659,63 +576,55 @@ else if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(cs)) } } - protected void validateParameters(AVList list, int srcWidth, int srcHeight) throws IllegalArgumentException - { - if (null == list || 0 == list.getValues().size()) - { + protected void validateParameters(AVList list, int srcWidth, int srcHeight) throws IllegalArgumentException { + if (null == list || 0 == list.getValues().size()) { String reason = Logging.getMessage("nullValue.AVListIsNull"); String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", reason); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (!(srcWidth > 0 && srcHeight > 0)) - { + if (!(srcWidth > 0 && srcHeight > 0)) { String msg = Logging.getMessage("generic.InvalidImageSize", srcWidth, srcHeight); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } - if (list.hasKey(AVKey.WIDTH)) - { + if (list.hasKey(AVKey.WIDTH)) { int width = (Integer) list.getValue(AVKey.WIDTH); - if (width != srcWidth) - { + if (width != srcWidth) { String msg = Logging.getMessage("GeotiffWriter.ImageWidthMismatch", width, srcWidth); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - } - else + } else { list.setValue(AVKey.WIDTH, srcWidth); + } - if (list.hasKey(AVKey.HEIGHT)) - { + if (list.hasKey(AVKey.HEIGHT)) { int height = (Integer) list.getValue(AVKey.HEIGHT); - if (height != srcHeight) - { + if (height != srcHeight) { String msg = Logging.getMessage("GeotiffWriter.ImageHeightMismatch", height, srcHeight); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - } - else + } else { list.setValue(AVKey.HEIGHT, srcHeight); + } Sector sector = null; - if (list.hasKey(AVKey.SECTOR)) + if (list.hasKey(AVKey.SECTOR)) { sector = (Sector) list.getValue(AVKey.SECTOR); + } - if (null == sector) - { + if (null == sector) { String msg = Logging.getMessage("GeotiffWriter.NoSectorSpecified"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!list.hasKey(AVKey.COORDINATE_SYSTEM)) - { + if (!list.hasKey(AVKey.COORDINATE_SYSTEM)) { String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.COORDINATE_SYSTEM); Logging.logger().finest(msg); // throw new IllegalArgumentException(msg); @@ -724,15 +633,11 @@ protected void validateParameters(AVList list, int srcWidth, int srcHeight) thro list.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC); } - if (!list.hasKey(AVKey.PROJECTION_EPSG_CODE)) - { - if (isGeographic(list)) - { + if (!list.hasKey(AVKey.PROJECTION_EPSG_CODE)) { + if (isGeographic(list)) { // assume WGS84 list.setValue(AVKey.PROJECTION_EPSG_CODE, GeoTiff.GCS.WGS_84); - } - else - { + } else { String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.PROJECTION_EPSG_CODE); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); @@ -741,15 +646,11 @@ protected void validateParameters(AVList list, int srcWidth, int srcHeight) thro // if PIXEL_WIDTH is specified, we are not overriding it because UTM images // will have different pixel size - if (!list.hasKey(AVKey.PIXEL_WIDTH)) - { - if (isGeographic(list)) - { + if (!list.hasKey(AVKey.PIXEL_WIDTH)) { + if (isGeographic(list)) { double pixelWidth = sector.getDeltaLonDegrees() / (double) srcWidth; list.setValue(AVKey.PIXEL_WIDTH, pixelWidth); - } - else - { + } else { String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.PIXEL_WIDTH); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); @@ -758,32 +659,24 @@ protected void validateParameters(AVList list, int srcWidth, int srcHeight) thro // if PIXEL_HEIGHT is specified, we are not overriding it // because UTM images will have different pixel size - if (!list.hasKey(AVKey.PIXEL_HEIGHT)) - { - if (isGeographic(list)) - { + if (!list.hasKey(AVKey.PIXEL_HEIGHT)) { + if (isGeographic(list)) { double pixelHeight = sector.getDeltaLatDegrees() / (double) srcHeight; list.setValue(AVKey.PIXEL_HEIGHT, pixelHeight); - } - else - { + } else { String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.PIXEL_HEIGHT); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } } - if (!list.hasKey(AVKey.PIXEL_FORMAT)) - { + if (!list.hasKey(AVKey.PIXEL_FORMAT)) { String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.PIXEL_FORMAT); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); - } - else - { + } else { String pixelFormat = list.getStringValue(AVKey.PIXEL_FORMAT); - if (!AVKey.ELEVATION.equals(pixelFormat) && !AVKey.IMAGE.equals(pixelFormat)) - { + if (!AVKey.ELEVATION.equals(pixelFormat) && !AVKey.IMAGE.equals(pixelFormat)) { String msg = Logging.getMessage("Geotiff.UnknownGeoKeyValue", pixelFormat, AVKey.PIXEL_FORMAT); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -791,116 +684,98 @@ protected void validateParameters(AVList list, int srcWidth, int srcHeight) thro } // validate elevation parameters - if (AVKey.ELEVATION.equals(list.getValue(AVKey.PIXEL_FORMAT))) - { - if (!list.hasKey(AVKey.DATA_TYPE)) - { + if (AVKey.ELEVATION.equals(list.getValue(AVKey.PIXEL_FORMAT))) { + if (!list.hasKey(AVKey.DATA_TYPE)) { String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.DATA_TYPE); Logging.logger().finest(msg); throw new IllegalArgumentException(msg); } String type = list.getStringValue(AVKey.DATA_TYPE); - if (!AVKey.FLOAT32.equals(type) && !AVKey.INT16.equals(type)) - { + if (!AVKey.FLOAT32.equals(type) && !AVKey.INT16.equals(type)) { String msg = Logging.getMessage("Geotiff.UnknownGeoKeyValue", type, AVKey.DATA_TYPE); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } } - if (!list.hasKey(AVKey.ORIGIN)) - { + if (!list.hasKey(AVKey.ORIGIN)) { // set UpperLeft corner as the origin, if not specified LatLon origin = new LatLon(sector.getMaxLatitude(), sector.getMinLongitude()); list.setValue(AVKey.ORIGIN, origin); } if (list.hasKey(AVKey.BYTE_ORDER) - && !AVKey.BIG_ENDIAN.equals(list.getStringValue(AVKey.BYTE_ORDER)) - ) - { + && !AVKey.BIG_ENDIAN.equals(list.getStringValue(AVKey.BYTE_ORDER))) { String msg = Logging.getMessage("generic.UnrecognizedByteOrder", list.getStringValue(AVKey.BYTE_ORDER)); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!list.hasKey(AVKey.DATE_TIME)) - { + if (!list.hasKey(AVKey.DATE_TIME)) { // add NUL (\0) termination as required by TIFF v6 spec (20 bytes length) String timestamp = String.format("%1$tY:%1$tm:%1$td %tT\0", Calendar.getInstance()); list.setValue(AVKey.DATE_TIME, timestamp); } - if (!list.hasKey(AVKey.VERSION)) - { + if (!list.hasKey(AVKey.VERSION)) { list.setValue(AVKey.VERSION, Version.getVersion()); } } - private static boolean isElevation(AVList params) - { + private static boolean isElevation(AVList params) { return (null != params - && params.hasKey(AVKey.PIXEL_FORMAT) - && AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT)) - ); + && params.hasKey(AVKey.PIXEL_FORMAT) + && AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT))); } - private static boolean isImage(AVList params) - { + private static boolean isImage(AVList params) { return (null != params - && params.hasKey(AVKey.PIXEL_FORMAT) - && AVKey.IMAGE.equals(params.getValue(AVKey.PIXEL_FORMAT)) - ); + && params.hasKey(AVKey.PIXEL_FORMAT) + && AVKey.IMAGE.equals(params.getValue(AVKey.PIXEL_FORMAT))); } - private static boolean isGeographic(AVList params) - { + private static boolean isGeographic(AVList params) { return (null != params - && params.hasKey(AVKey.COORDINATE_SYSTEM) - && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(params.getValue(AVKey.COORDINATE_SYSTEM)) - ); + && params.hasKey(AVKey.COORDINATE_SYSTEM) + && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(params.getValue(AVKey.COORDINATE_SYSTEM))); } - private static boolean isProjected(AVList params) - { + private static boolean isProjected(AVList params) { return (null != params - && params.hasKey(AVKey.COORDINATE_SYSTEM) - && AVKey.COORDINATE_SYSTEM_PROJECTED.equals(params.getValue(AVKey.COORDINATE_SYSTEM)) - ); + && params.hasKey(AVKey.COORDINATE_SYSTEM) + && AVKey.COORDINATE_SYSTEM_PROJECTED.equals(params.getValue(AVKey.COORDINATE_SYSTEM))); } - private void writeGeographicImageGeoKeys(ArrayList ifds, AVList params) throws IOException - { + private void writeGeographicImageGeoKeys(ArrayList ifds, AVList params) throws IOException { long offset = this.theChannel.position(); - if (isImage(params) && isGeographic(params)) - { + if (isImage(params) && isGeographic(params)) { int epsg = GeoTiff.GCS.WGS_84; - if (params.hasKey(AVKey.PROJECTION_EPSG_CODE)) + if (params.hasKey(AVKey.PROJECTION_EPSG_CODE)) { epsg = (Integer) params.getValue(AVKey.PROJECTION_EPSG_CODE); + } - short[] values = new short[] - { - // GeoKeyDirectory header - GeoTiff.GeoKeyHeader.KeyDirectoryVersion, - GeoTiff.GeoKeyHeader.KeyRevision, - GeoTiff.GeoKeyHeader.MinorRevision, - 0, // IMPORTANT!! we will update count below, after the array initialization - // end of header - - - // geo keys array - - /* key 1 */ - GeoTiff.GeoKey.ModelType, 0, 1, GeoTiff.ModelType.Geographic, - /* key 2 */ - GeoTiff.GeoKey.RasterType, 0, 1, (short) (0xFFFF & GeoTiff.RasterType.RasterPixelIsArea), - /* key 3 */ - GeoTiff.GeoKey.GeographicType, 0, 1, (short) (0xFFFF & epsg), - /* key 4 */ - GeoTiff.GeoKey.GeogAngularUnits, 0, 1, GeoTiff.Unit.Angular.Angular_Degree - }; + short[] values = new short[]{ + // GeoKeyDirectory header + GeoTiff.GeoKeyHeader.KeyDirectoryVersion, + GeoTiff.GeoKeyHeader.KeyRevision, + GeoTiff.GeoKeyHeader.MinorRevision, + 0, // IMPORTANT!! we will update count below, after the array initialization + // end of header - + + // geo keys array + + /* key 1 */ + GeoTiff.GeoKey.ModelType, 0, 1, GeoTiff.ModelType.Geographic, + /* key 2 */ + GeoTiff.GeoKey.RasterType, 0, 1, (short) (0xFFFF & GeoTiff.RasterType.RasterPixelIsArea), + /* key 3 */ + GeoTiff.GeoKey.GeographicType, 0, 1, (short) (0xFFFF & epsg), + /* key 4 */ + GeoTiff.GeoKey.GeogAngularUnits, 0, 1, GeoTiff.Unit.Angular.Angular_Degree + }; // IMPORTANT!! update count - number of geokeys values[3] = (short) (values.length / 4); @@ -911,54 +786,52 @@ private void writeGeographicImageGeoKeys(ArrayList ifds, AVList pa } } - private void writeGeographicElevationGeoKeys(ArrayList ifds, AVList params) throws IOException - { + private void writeGeographicElevationGeoKeys(ArrayList ifds, AVList params) throws IOException { long offset = this.theChannel.position(); - if (isElevation(params) && isGeographic(params)) - { + if (isElevation(params) && isGeographic(params)) { int epsg = GeoTiff.GCS.WGS_84; - if (params.hasKey(AVKey.PROJECTION_EPSG_CODE)) + if (params.hasKey(AVKey.PROJECTION_EPSG_CODE)) { epsg = (Integer) params.getValue(AVKey.PROJECTION_EPSG_CODE); + } int elevUnits = GeoTiff.Unit.Linear.Meter; - if (params.hasKey(AVKey.ELEVATION_UNIT)) - { - if (AVKey.UNIT_FOOT.equals(params.getValue(AVKey.ELEVATION_UNIT))) + if (params.hasKey(AVKey.ELEVATION_UNIT)) { + if (AVKey.UNIT_FOOT.equals(params.getValue(AVKey.ELEVATION_UNIT))) { elevUnits = GeoTiff.Unit.Linear.Foot; + } } int rasterType = GeoTiff.RasterType.RasterPixelIsArea; if (params.hasKey(AVKey.RASTER_PIXEL) - && AVKey.RASTER_PIXEL_IS_POINT.equals(params.getValue(AVKey.RASTER_PIXEL))) + && AVKey.RASTER_PIXEL_IS_POINT.equals(params.getValue(AVKey.RASTER_PIXEL))) { rasterType = GeoTiff.RasterType.RasterPixelIsPoint; + } - short[] values = new short[] - { - // GeoKeyDirectory header - GeoTiff.GeoKeyHeader.KeyDirectoryVersion, - GeoTiff.GeoKeyHeader.KeyRevision, - GeoTiff.GeoKeyHeader.MinorRevision, - 0, // IMPORTANT!! we will update count below, after the array initialization - // end of header - - - // geo keys array - - /* key 1 */ - GeoTiff.GeoKey.ModelType, 0, 1, GeoTiff.ModelType.Geographic, - /* key 2 */ - // TODO: Replace GeoTiff.RasterType.RasterPixelIsPoint - GeoTiff.GeoKey.RasterType, 0, 1, (short) (0xFFFF & rasterType), - /* key 3 */ - GeoTiff.GeoKey.GeographicType, 0, 1, (short) (0xFFFF & epsg), - /* key 4 */ - GeoTiff.GeoKey.GeogAngularUnits, 0, 1, GeoTiff.Unit.Angular.Angular_Degree, - /* key 5 */ - GeoTiff.GeoKey.VerticalCSType, 0, 1, GeoTiff.VCS.WGS_84_ellipsoid, - /* key 6 */ - GeoTiff.GeoKey.VerticalUnits, 0, 1, (short) (0xFFFF & elevUnits), - }; + short[] values = new short[]{ + // GeoKeyDirectory header + GeoTiff.GeoKeyHeader.KeyDirectoryVersion, + GeoTiff.GeoKeyHeader.KeyRevision, + GeoTiff.GeoKeyHeader.MinorRevision, + 0, // IMPORTANT!! we will update count below, after the array initialization + // end of header - + + // geo keys array + + /* key 1 */ + GeoTiff.GeoKey.ModelType, 0, 1, GeoTiff.ModelType.Geographic, + /* key 2 */ + // TODO: Replace GeoTiff.RasterType.RasterPixelIsPoint + GeoTiff.GeoKey.RasterType, 0, 1, (short) (0xFFFF & rasterType), + /* key 3 */ + GeoTiff.GeoKey.GeographicType, 0, 1, (short) (0xFFFF & epsg), + /* key 4 */ + GeoTiff.GeoKey.GeogAngularUnits, 0, 1, GeoTiff.Unit.Angular.Angular_Degree, + /* key 5 */ + GeoTiff.GeoKey.VerticalCSType, 0, 1, GeoTiff.VCS.WGS_84_ellipsoid, + /* key 6 */ + GeoTiff.GeoKey.VerticalUnits, 0, 1, (short) (0xFFFF & elevUnits),}; // IMPORTANT!! update count - number of geokeys values[3] = (short) (values.length / 4); @@ -969,8 +842,7 @@ private void writeGeographicElevationGeoKeys(ArrayList ifds, AVLis } } - private void writeIFDs(List ifds) throws IOException - { + private void writeIFDs(List ifds) throws IOException { long offset = this.theChannel.position(); // This is supposed to start on a word boundary, via decree of the spec. @@ -989,19 +861,17 @@ private void writeIFDs(List ifds) throws IOException this.theChannel.write(dataBuff); dataBuff.clear(); - for (TiffIFDEntry ifd : ifds) - { + for (TiffIFDEntry ifd : ifds) { putUnsignedShort(dataBuff, ifd.tag); putUnsignedShort(dataBuff, ifd.type); putUnsignedInt(dataBuff, ifd.count); - if (ifd.type == Tiff.Type.SHORT && ifd.count == 1) - { + if (ifd.type == Tiff.Type.SHORT && ifd.count == 1) { // these get packed in the first few bytes... putUnsignedShort(dataBuff, (int) ifd.valOffset); dataBuff.putShort((short) 0); - } - else + } else { putUnsignedInt(dataBuff, ifd.valOffset); + } } dataBuff.flip(); this.theChannel.write(dataBuff); @@ -1020,73 +890,57 @@ private void writeIFDs(List ifds) throws IOException this.theChannel.write(dataBuff); } - private void putUnsignedByte(ByteBuffer buff, int value) - { + private void putUnsignedByte(ByteBuffer buff, int value) { buff.put((byte) (value & 0xff)); } - private void putUnsignedShort(ByteBuffer buff, int value) - { + private void putUnsignedShort(ByteBuffer buff, int value) { buff.putShort((short) (value & 0xffff)); } - private void putUnsignedInt(ByteBuffer buff, long value) - { + private void putUnsignedInt(ByteBuffer buff, long value) { buff.putInt((int) (value & 0xffffffffL)); } - private byte[] getBytes(double[] array) - { - try - { + private byte[] getBytes(double[] array) { + try { ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); DataOutputStream datastream = new DataOutputStream(bytestream); - for (double n : array) - { + for (double n : array) { datastream.writeDouble(n); } datastream.flush(); return bytestream.toByteArray(); - } - catch (IOException ioe) - { + } catch (IOException ioe) { Logging.logger().finest(ioe.getMessage()); } return null; } - private byte[] getBytes(short[] array) - { - try - { + private byte[] getBytes(short[] array) { + try { ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); DataOutputStream datastream = new DataOutputStream(bytestream); - for (short n : array) - { + for (short n : array) { datastream.writeShort(n); } datastream.flush(); return bytestream.toByteArray(); - } - catch (IOException ioe) - { + } catch (IOException ioe) { Logging.logger().finest(ioe.getMessage()); } return null; } - public void writeRaster(BufferWrapperRaster raster) throws IOException, IllegalArgumentException - { - if (raster == null) - { + public void writeRaster(BufferWrapperRaster raster) throws IOException, IllegalArgumentException { + if (raster == null) { String msg = Logging.getMessage("nullValue.RasterIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (0 == raster.getWidth() || 0 == raster.getHeight()) - { + if (0 == raster.getWidth() || 0 == raster.getHeight()) { String msg = Logging.getMessage("generic.InvalidImageSize", raster.getWidth(), raster.getHeight()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1096,67 +950,50 @@ public void writeRaster(BufferWrapperRaster raster) throws IOException, IllegalA int bitsPerSample, samplesPerPixel, sampleFormat, photometric, numBands; - if (AVKey.ELEVATION.equals(raster.getValue(AVKey.PIXEL_FORMAT))) - { - if (AVKey.FLOAT32.equals(raster.getValue(AVKey.DATA_TYPE))) - { + if (AVKey.ELEVATION.equals(raster.getValue(AVKey.PIXEL_FORMAT))) { + if (AVKey.FLOAT32.equals(raster.getValue(AVKey.DATA_TYPE))) { numBands = 1; samplesPerPixel = Tiff.SamplesPerPixel.MONOCHROME; sampleFormat = Tiff.SampleFormat.IEEEFLOAT; photometric = Tiff.Photometric.Grayscale_BlackIsZero; bitsPerSample = Tiff.BitsPerSample.ELEVATIONS_FLOAT32; - } - else if (AVKey.INT16.equals(raster.getValue(AVKey.DATA_TYPE))) - { + } else if (AVKey.INT16.equals(raster.getValue(AVKey.DATA_TYPE))) { numBands = 1; samplesPerPixel = Tiff.SamplesPerPixel.MONOCHROME; sampleFormat = Tiff.SampleFormat.SIGNED; photometric = Tiff.Photometric.Grayscale_BlackIsZero; bitsPerSample = Tiff.BitsPerSample.ELEVATIONS_INT16; - } - else - { + } else { String msg = Logging.getMessage("GeotiffWriter.UnsupportedType", raster.getValue(AVKey.DATA_TYPE)); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - } - else if (AVKey.IMAGE.equals(raster.getValue(AVKey.PIXEL_FORMAT))) - { - if (AVKey.INT8.equals(raster.getValue(AVKey.DATA_TYPE))) - { + } else if (AVKey.IMAGE.equals(raster.getValue(AVKey.PIXEL_FORMAT))) { + if (AVKey.INT8.equals(raster.getValue(AVKey.DATA_TYPE))) { numBands = 1; samplesPerPixel = Tiff.SamplesPerPixel.MONOCHROME; sampleFormat = Tiff.SampleFormat.UNSIGNED; photometric = Tiff.Photometric.Grayscale_BlackIsZero; bitsPerSample = Tiff.BitsPerSample.MONOCHROME_UINT8; - } - else if (AVKey.INT16.equals(raster.getValue(AVKey.DATA_TYPE))) - { + } else if (AVKey.INT16.equals(raster.getValue(AVKey.DATA_TYPE))) { numBands = 1; samplesPerPixel = Tiff.SamplesPerPixel.MONOCHROME; sampleFormat = Tiff.SampleFormat.UNSIGNED; photometric = Tiff.Photometric.Grayscale_BlackIsZero; bitsPerSample = Tiff.BitsPerSample.MONOCHROME_UINT16; - } - else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) - { + } else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) { numBands = 3; // TODO check ALPHA / Transparency samplesPerPixel = Tiff.SamplesPerPixel.RGB; sampleFormat = Tiff.SampleFormat.UNSIGNED; photometric = Tiff.Photometric.Color_RGB; bitsPerSample = Tiff.BitsPerSample.RGB; - } - else - { + } else { String msg = Logging.getMessage("GeotiffWriter.UnsupportedType", raster.getValue(AVKey.DATA_TYPE)); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - } - else - { + } else { String msg = Logging.getMessage("GeotiffWriter.UnsupportedType", raster.getValue(AVKey.PIXEL_FORMAT)); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1176,20 +1013,16 @@ else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) ByteBuffer dataBuff = ByteBuffer.allocateDirect(numCols * bytesPerSample); - switch (bitsPerSample) - { + switch (bitsPerSample) { // case Tiff.BitsPerSample.MONOCHROME_BYTE: - case Tiff.BitsPerSample.MONOCHROME_UINT8: - { - for (int y = 0; y < numRows; y++) - { + case Tiff.BitsPerSample.MONOCHROME_UINT8: { + for (int y = 0; y < numRows; y++) { stripOffsets[y] = (int) this.theChannel.position(); stripCounts[y] = numCols * bytesPerSample; dataBuff.clear(); - for (int x = 0; x < numCols * numBands; x++) - { + for (int x = 0; x < numCols * numBands; x++) { dataBuff.put(srcBuffer.getByte(x + y * numCols)); } @@ -1200,17 +1033,14 @@ else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) break; // case Tiff.BitsPerSample.MONOCHROME_UINT16: - case Tiff.BitsPerSample.ELEVATIONS_INT16: - { - for (int y = 0; y < numRows; y++) - { + case Tiff.BitsPerSample.ELEVATIONS_INT16: { + for (int y = 0; y < numRows; y++) { stripOffsets[y] = (int) this.theChannel.position(); stripCounts[y] = numCols * bytesPerSample; dataBuff.clear(); - for (int x = 0; x < numCols * numBands; x++) - { + for (int x = 0; x < numCols * numBands; x++) { dataBuff.putShort(srcBuffer.getShort(x + y * numCols)); } @@ -1220,17 +1050,14 @@ else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) } break; - case Tiff.BitsPerSample.ELEVATIONS_FLOAT32: - { - for (int y = 0; y < numRows; y++) - { + case Tiff.BitsPerSample.ELEVATIONS_FLOAT32: { + for (int y = 0; y < numRows; y++) { stripOffsets[y] = (int) this.theChannel.position(); stripCounts[y] = numCols * bytesPerSample; dataBuff.clear(); - for (int x = 0; x < numCols * numBands; x++) - { + for (int x = 0; x < numCols * numBands; x++) { dataBuff.putFloat(srcBuffer.getFloat(x + y * numCols)); } @@ -1240,17 +1067,14 @@ else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) } break; - case Tiff.BitsPerSample.RGB: - { - for (int y = 0; y < numRows; y++) - { + case Tiff.BitsPerSample.RGB: { + for (int y = 0; y < numRows; y++) { stripOffsets[y] = (int) this.theChannel.position(); stripCounts[y] = numCols * bytesPerSample; dataBuff.clear(); - for (int x = 0; x < numCols; x++) - { + for (int x = 0; x < numCols; x++) { int color = srcBuffer.getInt(x + y * numCols); byte red = (byte) (0xFF & (color >> 16)); byte green = (byte) (0xFF & (color >> 8)); @@ -1274,18 +1098,16 @@ else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) ifds.add(new TiffIFDEntry(Tiff.Tag.IMAGE_LENGTH, Tiff.Type.LONG, 1, numRows)); long offset = this.theChannel.position(); - if (Tiff.BitsPerSample.RGB == bitsPerSample) - { + if (Tiff.BitsPerSample.RGB == bitsPerSample) { short[] bps = new short[numBands]; - for (int i = 0; i < numBands; i++) - { + for (int i = 0; i < numBands; i++) { bps[i] = Tiff.BitsPerSample.MONOCHROME_BYTE; } this.theChannel.write(ByteBuffer.wrap(this.getBytes(bps))); ifds.add(new TiffIFDEntry(Tiff.Tag.BITS_PER_SAMPLE, Tiff.Type.SHORT, numBands, offset)); - } - else + } else { ifds.add(new TiffIFDEntry(Tiff.Tag.BITS_PER_SAMPLE, Tiff.Type.SHORT, 1, bitsPerSample)); + } ifds.add(new TiffIFDEntry(Tiff.Tag.COMPRESSION, Tiff.Type.LONG, 1, Tiff.Compression.NONE)); ifds.add(new TiffIFDEntry(Tiff.Tag.PHOTO_INTERPRETATION, Tiff.Type.SHORT, 1, photometric)); @@ -1296,8 +1118,7 @@ else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) offset = this.theChannel.position(); dataBuff = ByteBuffer.allocateDirect(stripOffsets.length * INTEGER_SIZEOF); - for (int stripOffset : stripOffsets) - { + for (int stripOffset : stripOffsets) { dataBuff.putInt(stripOffset); } dataBuff.flip(); @@ -1308,8 +1129,7 @@ else if (AVKey.INT32.equals(raster.getValue(AVKey.DATA_TYPE))) offset = this.theChannel.position(); dataBuff.clear(); // stripOffsets and stripCounts are same length by design; can reuse the ByteBuffer... - for (int stripCount : stripCounts) - { + for (int stripCount : stripCounts) { dataBuff.putInt(stripCount); } dataBuff.flip(); diff --git a/src/gov/nasa/worldwind/formats/tiff/TIFFIFDFactory.java b/src/gov/nasa/worldwind/formats/tiff/TIFFIFDFactory.java index 828271d3a3..ec5f2dff8e 100644 --- a/src/gov/nasa/worldwind/formats/tiff/TIFFIFDFactory.java +++ b/src/gov/nasa/worldwind/formats/tiff/TIFFIFDFactory.java @@ -15,93 +15,74 @@ * @author Lado Garakanidze * @version $Id: TIFFIFDFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class TIFFIFDFactory -{ +class TIFFIFDFactory { + public static int MASK_USHORT = 0xFFFF; public static long MASK_UINT = 0xFFFFFFFFL; - private TIFFIFDFactory() - { + private TIFFIFDFactory() { } - public static TiffIFDEntry create(FileChannel fc, ByteOrder tiffFileOrder) - { - if( null == fc ) + public static TiffIFDEntry create(FileChannel fc, ByteOrder tiffFileOrder) { + if (null == fc) { return null; + } long savedPosition = 0; + ByteBuffer header = ByteBuffer.wrap(new byte[12]).order(tiffFileOrder); - ByteBuffer header = ByteBuffer.wrap(new byte[12]).order( tiffFileOrder ); - - try - { - fc.read( header ); + try { + fc.read(header); header.flip(); - int tag = getUnsignedShort( header ); - int type = getUnsignedShort( header ); - long count = getUnsignedInt( header ); - + int tag = getUnsignedShort(header); + int type = getUnsignedShort(header); + long count = getUnsignedInt(header); // To save time and space the Value Offset contains the Value instead of pointing to // the Value if and only if the Value fits into 4 bytes. If the Value is shorter than 4 bytes, // it is left-justified within the 4-byte Value Offset, i.e., stored in the lowernumbered bytes. // Whether the Value fits within 4 bytes is determined by the Type and Count of the field. - - if ( type == Tiff.Type.SHORT && count == 1 ) - { + if (type == Tiff.Type.SHORT && count == 1) { // these get packed left-justified in the bytes... - int upper = getUnsignedShort( header ); - int lower = getUnsignedShort( header ); + int upper = getUnsignedShort(header); + int lower = getUnsignedShort(header); long value = (MASK_USHORT & upper) << 16 | (MASK_USHORT & lower); - return new TiffIFDEntry(tag, type, value ); - } - else if( count == 1 && (type == Tiff.Type.LONG || type == Tiff.Type.FLOAT)) - { + return new TiffIFDEntry(tag, type, value); + } else if (count == 1 && (type == Tiff.Type.LONG || type == Tiff.Type.FLOAT)) { long value = header.getInt(); - return new TiffIFDEntry(tag, type, value ); - } - else - { - long offset = getUnsignedInt( header ); - int size = MASK_USHORT & (int)calcSize( type, count ); - - if( size > 0L ) - { - ByteBuffer data = ByteBuffer.allocateDirect( size ).order( tiffFileOrder ); + return new TiffIFDEntry(tag, type, value); + } else { + long offset = getUnsignedInt(header); + int size = MASK_USHORT & (int) calcSize(type, count); + + if (size > 0L) { + ByteBuffer data = ByteBuffer.allocateDirect(size).order(tiffFileOrder); savedPosition = fc.position(); - fc.position( offset ); - fc.read( data ); + fc.position(offset); + fc.read(data); data.flip(); - fc.position( savedPosition ); + fc.position(savedPosition); savedPosition = 0; - return new TiffIFDEntry(tag, type, count, offset, data ); + return new TiffIFDEntry(tag, type, count, offset, data); + } else { + return new TiffIFDEntry(tag, type, count, offset); } - else - return new TiffIFDEntry(tag, type, count, offset ); } - } - catch(Exception e) - { - Logging.logger().finest( e.getMessage() ); - - } - finally - { - if( savedPosition != 0 && fc != null ) - { - try - { - fc.position( savedPosition ); - } - catch(Exception e2) - { - Logging.logger().finest( e2.getMessage() ); + } catch (Exception e) { + Logging.logger().finest(e.getMessage()); + + } finally { + if (savedPosition != 0 && fc != null) { + try { + fc.position(savedPosition); + } catch (Exception e2) { + Logging.logger().finest(e2.getMessage()); } } } @@ -109,11 +90,8 @@ else if( count == 1 && (type == Tiff.Type.LONG || type == Tiff.Type.FLOAT)) return null; } - - private static long calcSize(int type, long count) - { - switch( type ) - { + private static long calcSize(int type, long count) { + switch (type) { case Tiff.Type.BYTE: case Tiff.Type.SBYTE: case Tiff.Type.ASCII: @@ -143,13 +121,11 @@ private static long calcSize(int type, long count) } } - private static int getUnsignedShort(ByteBuffer bb) - { + private static int getUnsignedShort(ByteBuffer bb) { return MASK_USHORT & (int) bb.getShort(); } - private static long getUnsignedInt(ByteBuffer bb) - { + private static long getUnsignedInt(ByteBuffer bb) { return MASK_UINT & bb.getInt(); } diff --git a/src/gov/nasa/worldwind/formats/tiff/TIFFReader.java b/src/gov/nasa/worldwind/formats/tiff/TIFFReader.java index 2000de600f..1450988c1d 100644 --- a/src/gov/nasa/worldwind/formats/tiff/TIFFReader.java +++ b/src/gov/nasa/worldwind/formats/tiff/TIFFReader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.tiff; import gov.nasa.worldwind.util.Logging; @@ -19,8 +18,8 @@ * @author Lado Garakanidze * @version $Id: TIFFReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class TIFFReader -{ +class TIFFReader { + private static final int CLEAR_CODE = 256; private static final int EOI_CODE = 257; @@ -29,50 +28,41 @@ class TIFFReader private static final int INTEGER_SIZEOF = Integer.SIZE / Byte.SIZE; private static final int SHORT_SIZEOF = Short.SIZE / Byte.SIZE; - private FileChannel theChannel; - private ByteOrder tiffFileOrder; + private ByteOrder tiffFileOrder; - public TIFFReader( FileChannel fileChannel, ByteOrder byteOrder ) - { + public TIFFReader(FileChannel fileChannel, ByteOrder byteOrder) { this.theChannel = fileChannel; this.tiffFileOrder = byteOrder; } - public TIFFReader( FileChannel fileChannel ) - { - this( fileChannel,ByteOrder.BIG_ENDIAN ); + public TIFFReader(FileChannel fileChannel) { + this(fileChannel, ByteOrder.BIG_ENDIAN); } - public void setByteOrder(ByteOrder byteOrder) - { + public void setByteOrder(ByteOrder byteOrder) { this.tiffFileOrder = byteOrder; } - public ByteOrder getByteOrder() - { + public ByteOrder getByteOrder() { return this.tiffFileOrder; } - /* + /* * * - */ + */ public byte[] readLZWCompressed(int width, int height, long offset, int samplesPerPixel, - boolean differencing, long[] stripOffsets, long[] stripCounts) - throws IOException - { + boolean differencing, long[] stripOffsets, long[] stripCounts) + throws IOException { this.theChannel.position(offset); byte[] pixels = new byte[width * height * samplesPerPixel]; int base = 0; - for (int i = 0; i < stripOffsets.length; i++) - { - if (i > 0) - { + for (int i = 0; i < stripOffsets.length; i++) { + if (i > 0) { long skip = stripOffsets[i] - stripOffsets[i - 1] - stripCounts[i - 1]; - if (skip > 0) - { + if (skip > 0) { //in.skip(skip); this.theChannel.position(this.theChannel.position() + skip); } @@ -80,23 +70,20 @@ public byte[] readLZWCompressed(int width, int height, long offset, int samplesP byte[] byteArray = new byte[(int) stripCounts[i]]; ByteBuffer bBuffer = ByteBuffer.wrap(byteArray); int read = 0, left = byteArray.length; - while (left > 0) - { + while (left > 0) { long r = this.theChannel.read(bBuffer); - if (r == -1) - { + if (r == -1) { break; } read += r; left -= r; } byteArray = lzwUncompress(byteArray, (width * samplesPerPixel)); - if (differencing) - { - for (int b = 0; b < byteArray.length; b++) - { - if (b / samplesPerPixel % width == 0) + if (differencing) { + for (int b = 0; b < byteArray.length; b++) { + if (b / samplesPerPixel % width == 0) { continue; + } byteArray[b] += byteArray[b - samplesPerPixel]; } } @@ -104,11 +91,11 @@ public byte[] readLZWCompressed(int width, int height, long offset, int samplesP int bytesToRead = byteArray.length; bytesToRead = bytesToRead - (bytesToRead % width); int pmax = base + bytesToRead; - if (pmax > width * height * samplesPerPixel) + if (pmax > width * height * samplesPerPixel) { pmax = width * height * samplesPerPixel; + } - for (int j = base; j < pmax; j++) - { + for (int j = base; j < pmax; j++) { pixels[j] = byteArray[k++]; } @@ -118,12 +105,10 @@ public byte[] readLZWCompressed(int width, int height, long offset, int samplesP return pixels; } - - - public byte[] lzwUncompress(byte[] input, int rowNumPixels) - { - if (input == null || input.length == 0) + public byte[] lzwUncompress(byte[] input, int rowNumPixels) { + if (input == null || input.length == 0) { return input; + } byte[][] symbolTable = new byte[4096][1]; int bitsToRead = 9; //default int nextSymbol = 258; @@ -133,33 +118,29 @@ public byte[] lzwUncompress(byte[] input, int rowNumPixels) ByteBuffer out = java.nio.ByteBuffer.allocate(rowNumPixels); CodeReader bb = new CodeReader(input); - while (true) - { + while (true) { code = bb.getCode(bitsToRead); - if (code == EOI_CODE || code == -1) + if (code == EOI_CODE || code == -1) { break; - if (code == CLEAR_CODE) - { + } + if (code == CLEAR_CODE) { // initialize symbol table - for (int i = 0; i < 256; i++) - { + for (int i = 0; i < 256; i++) { symbolTable[i][0] = (byte) i; } nextSymbol = 258; bitsToRead = 9; code = bb.getCode(bitsToRead); - if (code == EOI_CODE || code == -1) + if (code == EOI_CODE || code == -1) { break; + } out.put(symbolTable[code]); oldCode = code; - } - else - { - if (code < nextSymbol) - { + } else { + if (code < nextSymbol) { out.put(symbolTable[code]); ByteBuffer symbol = java.nio.ByteBuffer.allocate((symbolTable[oldCode].length + 1)); symbol.put(symbolTable[oldCode]); @@ -167,9 +148,7 @@ public byte[] lzwUncompress(byte[] input, int rowNumPixels) symbolTable[nextSymbol] = symbol.array(); oldCode = code; nextSymbol++; - } - else - { + } else { int size = symbolTable[oldCode].length + 1; ByteBuffer symbol = java.nio.ByteBuffer.allocate(size); symbol.put(symbolTable[oldCode]); @@ -182,16 +161,13 @@ public byte[] lzwUncompress(byte[] input, int rowNumPixels) oldCode = code; nextSymbol++; } - if (nextSymbol == 511) - { + if (nextSymbol == 511) { bitsToRead = 10; } - if (nextSymbol == 1023) - { + if (nextSymbol == 1023) { bitsToRead = 11; } - if (nextSymbol == 2047) - { + if (nextSymbol == 2047) { bitsToRead = 12; } } @@ -204,18 +180,17 @@ public byte[] lzwUncompress(byte[] input, int rowNumPixels) * */ public byte[][] readPixelInterleaved8(int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts) throws IOException - { + long[] stripOffsets, long[] stripCounts) throws IOException { byte[][] data = new byte[1][width * height * samplesPerPixel]; int offset = 0; ByteBuffer buff = ByteBuffer.wrap(data[0]); - for (int i = 0; i < stripOffsets.length; i++) - { + for (int i = 0; i < stripOffsets.length; i++) { this.theChannel.position(stripOffsets[i]); int len = (int) stripCounts[i]; - if ((offset + len) >= data[0].length) + if ((offset + len) >= data[0].length) { len = data[0].length - offset; + } buff.limit(offset + len); this.theChannel.read(buff); offset += stripCounts[i]; @@ -227,28 +202,26 @@ public byte[][] readPixelInterleaved8(int width, int height, int samplesPerPixel /* * Reads BYTE image data organized as separate image planes. * - */ + */ public byte[][] readPlanar8(int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException - { + long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException { byte[][] data = new byte[samplesPerPixel][width * height]; int band = 0; int offset = 0; int numRows = 0; ByteBuffer buff = ByteBuffer.wrap(data[band]); - for (int i = 0; i < stripOffsets.length; i++) - { + for (int i = 0; i < stripOffsets.length; i++) { this.theChannel.position(stripOffsets[i]); int len = (int) stripCounts[i]; - if ((offset + len) >= data[band].length) + if ((offset + len) >= data[band].length) { len = data[band].length - offset; + } buff.limit(offset + len); this.theChannel.read(buff); offset += stripCounts[i]; numRows += rowsPerStrip; - if (numRows >= height && band < (data.length - 1)) - { + if (numRows >= height && band < (data.length - 1)) { buff = ByteBuffer.wrap(data[++band]); numRows = 0; offset = 0; @@ -258,63 +231,57 @@ public byte[][] readPlanar8(int width, int height, int samplesPerPixel, return data; } -/* + /* * Reads SHORT image data organized as PIXEL interleaved * b1p1, b2p1, b3p1, b4p1, b1p2, b2p2, b3p2, b4p2, b1p3, ... * */ public short[] read16bitPixelInterleavedImage(int band, int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException - { + long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException { short[] data = new short[width * height]; int numRows = 0; ByteBuffer buff = null; int dataOffset = 0; - for (int i = 0; i < stripOffsets.length; i++) - { - this.theChannel.position( stripOffsets[i] ); + for (int i = 0; i < stripOffsets.length; i++) { + this.theChannel.position(stripOffsets[i]); int stripSize = (int) stripCounts[i]; - if( null == buff || buff.capacity() < stripSize ) - { - buff = ByteBuffer.allocateDirect( stripSize ); - buff.order( this.getByteOrder() ); + if (null == buff || buff.capacity() < stripSize) { + buff = ByteBuffer.allocateDirect(stripSize); + buff.order(this.getByteOrder()); } buff.clear().rewind(); - buff.limit( stripSize ); + buff.limit(stripSize); - this.theChannel.read( buff ); + this.theChannel.read(buff); buff.flip(); ShortBuffer sb = buff.asShortBuffer(); int b = 0; - while(sb.hasRemaining()) - { - if( band == (b++ % samplesPerPixel )) - { - data[ dataOffset] = (short)(0xFFFF & sb.get()); + while (sb.hasRemaining()) { + if (band == (b++ % samplesPerPixel)) { + data[dataOffset] = (short) (0xFFFF & sb.get()); dataOffset++; - } - else + } else { sb.get(); + } } } return data; } -/* + /* * Reads SHORT image data organized as separate image planes. * */ public short[][] readPlanar16(int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException - { + long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException { short[][] data = new short[samplesPerPixel][width * height]; int band = 0; int numRows = 0; @@ -322,17 +289,16 @@ public short[][] readPlanar16(int width, int height, int samplesPerPixel, ByteBuffer buff = ByteBuffer.allocateDirect(width * height * SHORT_SIZEOF); buff.order(this.getByteOrder()); - for (int i = 0; i < stripOffsets.length; i++) - { + for (int i = 0; i < stripOffsets.length; i++) { this.theChannel.position(stripOffsets[i]); int len = (int) stripCounts[i]; - if ((buff.position() + len) > data[band].length * SHORT_SIZEOF) + if ((buff.position() + len) > data[band].length * SHORT_SIZEOF) { len = data[band].length * SHORT_SIZEOF - buff.position(); + } buff.limit(buff.position() + len); this.theChannel.read(buff); numRows += rowsPerStrip; - if (numRows >= height) - { + if (numRows >= height) { buff.flip(); ShortBuffer sbuff = buff.asShortBuffer(); sbuff.get(data[band]); @@ -350,8 +316,7 @@ public short[][] readPlanar16(int width, int height, int samplesPerPixel, * */ public float[][] readPlanarFloat32(int width, int height, int samplesPerPixel, - long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException - { + long[] stripOffsets, long[] stripCounts, long rowsPerStrip) throws IOException { float[][] data = new float[samplesPerPixel][width * height]; int band = 0; int numRows = 0; @@ -359,17 +324,16 @@ public float[][] readPlanarFloat32(int width, int height, int samplesPerPixel, ByteBuffer buff = ByteBuffer.allocateDirect(width * height * FLOAT_SIZEOF); buff.order(this.getByteOrder()); - for (int i = 0; i < stripOffsets.length; i++) - { + for (int i = 0; i < stripOffsets.length; i++) { this.theChannel.position(stripOffsets[i]); int len = (int) stripCounts[i]; - if ((buff.position() + len) >= data[band].length * FLOAT_SIZEOF) + if ((buff.position() + len) >= data[band].length * FLOAT_SIZEOF) { len = data[band].length * FLOAT_SIZEOF - buff.position(); + } buff.limit(buff.position() + len); this.theChannel.read(buff); numRows += rowsPerStrip; - if (numRows >= height) - { + if (numRows >= height) { buff.flip(); FloatBuffer fbuff = buff.asFloatBuffer(); fbuff.get(data[band]); @@ -386,10 +350,8 @@ public float[][] readPlanarFloat32(int width, int height, int samplesPerPixel, * Reads a ColorMap. * */ - public byte[][] readColorMap(TiffIFDEntry colorMapEntry) throws IOException - { - if (null == colorMapEntry) - { + public byte[][] readColorMap(TiffIFDEntry colorMapEntry) throws IOException { + if (null == colorMapEntry) { String message = Logging.getMessage("GeotiffReader.MissingColormap"); Logging.logger().severe(message); throw new IOException(message); @@ -414,12 +376,10 @@ public byte[][] readColorMap(TiffIFDEntry colorMapEntry) throws IOException // TIFF gives a ColorMap composed of unsigned shorts. Java's IndexedColorModel wants unsigned bytes. // Something's got to give somewhere...we'll do our best. byte[][] cmap = new byte[3][numEntries]; - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { buff = ByteBuffer.wrap(tmp[i]); buff.order(this.getByteOrder()); - for (int j = 0; j < numEntries; j++) - { + for (int j = 0; j < numEntries; j++) { cmap[i][j] = (byte) (0x00ff & buff.getShort()); } } @@ -427,22 +387,19 @@ public byte[][] readColorMap(TiffIFDEntry colorMapEntry) throws IOException return cmap; } - public static int getUnsignedShort(ByteBuffer b) - { + public static int getUnsignedShort(ByteBuffer b) { return 0xffff & (int) b.getShort(); } - public static long getUnsignedInt(ByteBuffer b) - { - return 0xffffffffL & (long)b.getInt(); + public static long getUnsignedInt(ByteBuffer b) { + return 0xffffffffL & (long) b.getInt(); } /* * Reads and returns an array of bytes from the file. * */ - public byte[] readBytes(TiffIFDEntry entry) throws IOException - { + public byte[] readBytes(TiffIFDEntry entry) throws IOException { byte[] bytes = new byte[(int) entry.count]; ByteBuffer buff = ByteBuffer.wrap(bytes); this.theChannel.position(entry.asOffset()); @@ -450,17 +407,12 @@ public byte[] readBytes(TiffIFDEntry entry) throws IOException return bytes; } - public String readString(TiffIFDEntry entry) - { - try - { - if( null != entry && entry.type == Tiff.Type.ASCII ) - { - return new String( this.readBytes( entry )); + public String readString(TiffIFDEntry entry) { + try { + if (null != entry && entry.type == Tiff.Type.ASCII) { + return new String(this.readBytes(entry)); } - } - catch(Exception e) - { + } catch (Exception e) { Logging.logger().severe(e.getMessage()); } return null; @@ -506,22 +458,20 @@ public String readString(TiffIFDEntry entry) // // return offsets; // } + //Inner class for reading individual codes during decompression + private class CodeReader { - //Inner class for reading individual codes during decompression - private class CodeReader - { private int currentByte; private int currentBit; private byte[] byteBuffer; private int bufferLength; - private int[] backMask = new int[] {0x0000, 0x0001, 0x0003, 0x0007, + private int[] backMask = new int[]{0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F}; - private int[] frontMask = new int[] {0x0000, 0x0080, 0x00C0, 0x00E0, + private int[] frontMask = new int[]{0x0000, 0x0080, 0x00C0, 0x00E0, 0x00F0, 0x00F8, 0x00FC, 0x00FE}; private boolean atEof; - public CodeReader(byte[] byteBuffer) - { + public CodeReader(byte[] byteBuffer) { //todo validate byteBuffer this.byteBuffer = byteBuffer; currentByte = 0; @@ -529,17 +479,16 @@ public CodeReader(byte[] byteBuffer) bufferLength = byteBuffer.length; } - public int getCode(int numBitsToRead) - { - if (numBitsToRead < 0) + public int getCode(int numBitsToRead) { + if (numBitsToRead < 0) { return 0; - if (atEof) + } + if (atEof) { return -1; //end of file + } int returnCode = 0; - while (numBitsToRead != 0 && !atEof) - { - if (numBitsToRead >= 8 - currentBit) - { + while (numBitsToRead != 0 && !atEof) { + if (numBitsToRead >= 8 - currentBit) { if (currentBit == 0) //get first { returnCode = returnCode << 8; @@ -547,18 +496,14 @@ public int getCode(int numBitsToRead) returnCode += (cb < 0 ? 256 + cb : cb); numBitsToRead -= 8; currentByte++; - } - else - { + } else { returnCode = returnCode << (8 - currentBit); returnCode += ((int) byteBuffer[currentByte]) & backMask[8 - currentBit]; numBitsToRead -= (8 - currentBit); currentBit = 0; currentByte++; } - } - else - { + } else { returnCode = returnCode << numBitsToRead; int cb = ((int) byteBuffer[currentByte]); cb = (cb < 0 ? 256 + cb : cb); @@ -566,7 +511,7 @@ public int getCode(int numBitsToRead) currentBit += numBitsToRead; numBitsToRead = 0; } - if (currentByte == bufferLength) //at eof + if (currentByte == bufferLength) //at eof { atEof = true; return returnCode; diff --git a/src/gov/nasa/worldwind/formats/tiff/Tiff.java b/src/gov/nasa/worldwind/formats/tiff/Tiff.java index 1e149d965a..6545bd0dbe 100644 --- a/src/gov/nasa/worldwind/formats/tiff/Tiff.java +++ b/src/gov/nasa/worldwind/formats/tiff/Tiff.java @@ -9,12 +9,12 @@ * @author Lado Garakanidze * @version $Id: Tiff.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Tiff -{ +public interface Tiff { + public static final int Undefined = 0; - public interface Type - { + public interface Type { + public static final int BYTE = 1; public static final int ASCII = 2; public static final int SHORT = 3; @@ -29,8 +29,8 @@ public interface Type public static final int DOUBLE = 12; } - public interface Tag - { + public interface Tag { + // Baseline Tiff 6.0 tags... public static final int IMAGE_WIDTH = 256; public static final int IMAGE_LENGTH = 257; @@ -72,8 +72,8 @@ public interface Tag } // The orientation of the image with respect to the rows and columns. - public interface Orientation - { + public interface Orientation { + // 1 = The 0th row represents the visual top of the image, // and the 0th column represents the visual left-hand side. public static final int Row0_IS_TOP__Col0_IS_LHS = 1; @@ -105,8 +105,8 @@ public interface Orientation public static final int DEFAULT = Row0_IS_TOP__Col0_IS_LHS; } - public interface BitsPerSample - { + public interface BitsPerSample { + public static final int MONOCHROME_BYTE = 8; public static final int MONOCHROME_UINT8 = 8; public static final int MONOCHROME_UINT16 = 16; @@ -117,8 +117,8 @@ public interface BitsPerSample public static final int CMYK = 32; } - public interface SamplesPerPixel - { + public interface SamplesPerPixel { + public static final int MONOCHROME = 1; public static final int RGB = 3; public static final int RGBA = 4; @@ -127,8 +127,8 @@ public interface SamplesPerPixel } // The color space of the image data - public interface Photometric - { + public interface Photometric { + public static final int Undefined = -1; // 0 = WhiteIsZero @@ -186,16 +186,16 @@ public interface Photometric // There is no default for PhotometricInterpretation, and it is required. } - public interface Compression - { + public interface Compression { + public static final int NONE = 1; public static final int LZW = 5; public static final int JPEG = 6; public static final int PACKBITS = 32773; } - public interface PlanarConfiguration - { + public interface PlanarConfiguration { + // CHUNKY // The component values for each pixel are stored contiguously. // The order of the components within the pixel is specified by PhotometricInterpretation. @@ -219,15 +219,15 @@ public interface PlanarConfiguration public static final int DEFAULT = CHUNKY; } - public interface ResolutionUnit - { + public interface ResolutionUnit { + public static final int NONE = 1; public static final int INCH = 2; public static final int CENTIMETER = 3; } - public interface SampleFormat - { + public interface SampleFormat { + public static final int UNSIGNED = 1; public static final int SIGNED = 2; public static final int IEEEFLOAT = 3; diff --git a/src/gov/nasa/worldwind/formats/tiff/TiffIFDEntry.java b/src/gov/nasa/worldwind/formats/tiff/TiffIFDEntry.java index ffdafb3f9f..7cf0321ce9 100644 --- a/src/gov/nasa/worldwind/formats/tiff/TiffIFDEntry.java +++ b/src/gov/nasa/worldwind/formats/tiff/TiffIFDEntry.java @@ -17,6 +17,7 @@ * @version $Id: TiffIFDEntry.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class TiffIFDEntry implements Comparable { + private ByteBuffer data = null; public TiffIFDEntry(int tag, int type, long count, long valOffset) throws IllegalArgumentException { @@ -36,14 +37,16 @@ public TiffIFDEntry(int tag, int type, long count, long valOffset, ByteBuffer da } public long asLong() throws IllegalStateException { - if (this.type != Tiff.Type.SHORT && this.type != Tiff.Type.LONG) + if (this.type != Tiff.Type.SHORT && this.type != Tiff.Type.LONG) { throw new IllegalStateException("Attempt to access Tiff IFD-entry as int: tag/type=" + Long.toHexString(tag) + "/" + type); + } - if (this.type == Tiff.Type.SHORT && this.count == 1) + if (this.type == Tiff.Type.SHORT && this.count == 1) { return 0xFFFFL & (valOffset >> 16); - else + } else { return valOffset; + } } public Double getAsDouble() throws IOException { @@ -62,15 +65,17 @@ public Double getAsDouble() throws IOException { case Tiff.Type.FLOAT: { float[] values = this.getFloats(); - if (null != values) + if (null != values) { value = (double) values[0]; + } } break; case Tiff.Type.DOUBLE: { double[] values = this.getDoubles(); - if (null != values) + if (null != values) { value = values[0]; + } } break; } @@ -86,12 +91,13 @@ public int asShort() throws IllegalStateException { } if (this.count > 0) { - if (this.count == 1) + if (this.count == 1) { return 0xFFFF & (int) (valOffset >> 16L); - else { + } else { int[] values = this.getShortsAsInts(); - if (null != values && values.length > 0) + if (null != values && values.length > 0) { return values[0]; + } } } @@ -109,8 +115,9 @@ public int asShort(int index) throws IllegalStateException { if (this.count > index) { int[] values = this.getShortsAsInts(); - if (null != values && values.length > index) + if (null != values && values.length > index) { return values[index]; + } } String message = Logging.getMessage("generic.indexOutOfRange", this.count); @@ -125,8 +132,9 @@ public int[] getShortsAsInts() { throw new IllegalArgumentException(message); } - if (this.count == 1) + if (this.count == 1) { return new int[]{this.asShort()}; + } if (this.count > 0 && null != this.data) { int[] array = new int[(int) this.count]; @@ -151,7 +159,6 @@ public long[] getAsLongs() { throw new IllegalArgumentException(message); } - if (this.count == 1) { return new long[]{this.asLong()}; } else if (this.count > 1 && null != this.data) { @@ -185,8 +192,9 @@ public short[] getShorts() { throw new IllegalArgumentException(message); } - if (this.count == 1) + if (this.count == 1) { return new short[]{(short) this.asShort()}; + } if (this.count > 0 && null != this.data) { ShortBuffer sb = ((ByteBuffer) this.data.rewind()).asShortBuffer(); @@ -206,7 +214,6 @@ public short[] getShorts() { * Reads and returns an array of doubles from the file. * */ - public double[] getDoubles() throws IOException { if (this.type != Tiff.Type.DOUBLE) { String message = Logging.getMessage("GeotiffReader.InvalidType", "double", this.tag, this.type); @@ -214,8 +221,9 @@ public double[] getDoubles() throws IOException { throw new IllegalArgumentException(message); } - if (this.count == 0 || null == this.data) + if (this.count == 0 || null == this.data) { return null; + } DoubleBuffer db = ((ByteBuffer) this.data.rewind()).asDoubleBuffer(); this.data.rewind(); @@ -236,16 +244,18 @@ public float[] getFloats() throws IOException { throw new IllegalArgumentException(message); } - if (this.count == 0) + if (this.count == 0) { return null; + } if (this.count == 1) { int num = (int) (0xFFFFFFFFL & this.valOffset); return new float[]{Float.intBitsToFloat(num)}; } - if (null == this.data) + if (null == this.data) { return null; + } FloatBuffer db = ((ByteBuffer) this.data.rewind()).asFloatBuffer(); this.data.rewind(); @@ -266,8 +276,9 @@ public String asString() { throw new IllegalArgumentException(message); } - if (this.count != 1 || null == this.data) + if (this.count != 1 || null == this.data) { return null; + } CharBuffer cbuf = ((ByteBuffer) this.data.rewind()).asCharBuffer(); return cbuf.toString(); @@ -277,7 +288,6 @@ public String asString() { // 2 = ASCII 8-bit byte that contains a 7-bit ASCII code; the last byte must be NUL (binary zero). // 3 = SHORT 16-bit (2-byte) unsigned integer. // 4 = LONG 32-bit (4-byte) unsigned integer. - public long asOffset() { return valOffset; } @@ -293,16 +303,18 @@ public int compareTo(TiffIFDEntry o) { final int EQUAL = 0; final int AFTER = 1; - if (this == o) + if (this == o) { return EQUAL; + } if (o != null) { - if (this.tag < o.tag) + if (this.tag < o.tag) { return BEFORE; - else if (this.tag > o.tag) + } else if (this.tag > o.tag) { return AFTER; - else + } else { return EQUAL; + } } return AFTER; diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymAbbreviationProvider.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymAbbreviationProvider.java index 2dd51fb8c6..7985f4ad03 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymAbbreviationProvider.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymAbbreviationProvider.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.vpf; import gov.nasa.worldwind.exception.WWRuntimeException; @@ -16,29 +15,26 @@ * @author Patrick Murris * @version $Id: GeoSymAbbreviationProvider.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymAbbreviationProvider -{ +public class GeoSymAbbreviationProvider { + private HashMap> abbreviationTables; - public GeoSymAbbreviationProvider(String filePath) - { + public GeoSymAbbreviationProvider(String filePath) { this.initialize(filePath); } - public String getAbbreviation(int tableId, int abbreviationId) - { + public String getAbbreviation(int tableId, int abbreviationId) { HashMap table = this.abbreviationTables.get(tableId); - if (table == null) + if (table == null) { return null; + } return table.get(abbreviationId); } - protected void initialize(String filePath) - { + protected void initialize(String filePath) { InputStream inputStream = WWIO.openFileOrResourceStream(filePath, this.getClass()); - if (inputStream == null) - { + if (inputStream == null) { String message = Logging.getMessage("generic.ExceptionWhileReading", filePath); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -47,34 +43,29 @@ protected void initialize(String filePath) readTables(new Scanner(inputStream)); } - protected void readTables(Scanner scanner) - { + protected void readTables(Scanner scanner) { this.abbreviationTables = new HashMap>(); HashMap table = null; String s; // Skip header - while (!(scanner.nextLine()).equals(";")) - { + while (!(scanner.nextLine()).equals(";")) { } // Read tables - while (scanner.hasNextLine()) - { + while (scanner.hasNextLine()) { s = scanner.nextLine().trim(); - if (s.length() == 0) + if (s.length() == 0) { continue; + } - if (s.endsWith(":")) - { + if (s.endsWith(":")) { // Table ID Integer id = Integer.parseInt(s.split(":")[0]); table = new HashMap(); this.abbreviationTables.put(id, table); - } - else - { + } else { // Table record String[] tokens = s.split("[|]"); Integer id = Integer.parseInt(tokens[0]); diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymAssignment.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymAssignment.java index 9c6b5d4206..57cf43b7bd 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymAssignment.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymAssignment.java @@ -13,32 +13,28 @@ * @author dcollins * @version $Id: GeoSymAssignment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymAssignment -{ +public class GeoSymAssignment { + protected String filePath; protected Map tableMap = new HashMap(); - protected static String[] tableNames = - { - GeoSymConstants.ATTRIBUTE_EXPRESSION_FILE, - GeoSymConstants.CODE_VALUE_DESCRIPTION_FILE, - GeoSymConstants.COLOR_ASSIGNMENT_FILE, - GeoSymConstants.FULL_SYMBOL_ASSIGNMENT_FILE, - GeoSymConstants.SIMPLIFIED_SYMBOL_ASSIGNMENT_FILE, - //GeoSymConstants.TEXT_ABBREVIATIONS_ASSIGNMENT_FILE, // Has a unique file format. See MIL-DTL-89045 3.5.3.1.3.4 - GeoSymConstants.TEXT_LABEL_CHARACTERISTICS_FILE, - GeoSymConstants.TEXT_LABEL_JOIN_FILE, - GeoSymConstants.TEXT_LABEL_LOCATION_FILE, - }; - - public GeoSymAssignment() - { + protected static String[] tableNames + = { + GeoSymConstants.ATTRIBUTE_EXPRESSION_FILE, + GeoSymConstants.CODE_VALUE_DESCRIPTION_FILE, + GeoSymConstants.COLOR_ASSIGNMENT_FILE, + GeoSymConstants.FULL_SYMBOL_ASSIGNMENT_FILE, + GeoSymConstants.SIMPLIFIED_SYMBOL_ASSIGNMENT_FILE, + //GeoSymConstants.TEXT_ABBREVIATIONS_ASSIGNMENT_FILE, // Has a unique file format. See MIL-DTL-89045 3.5.3.1.3.4 + GeoSymConstants.TEXT_LABEL_CHARACTERISTICS_FILE, + GeoSymConstants.TEXT_LABEL_JOIN_FILE, + GeoSymConstants.TEXT_LABEL_LOCATION_FILE,}; + + public GeoSymAssignment() { } - public static GeoSymAssignment fromFile(String filePath) - { - if (filePath == null) - { + public static GeoSymAssignment fromFile(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -49,20 +45,18 @@ public static GeoSymAssignment fromFile(String filePath) GeoSymTableReader reader = new GeoSymTableReader(); - for (String name : tableNames) - { + for (String name : tableNames) { GeoSymTable table = reader.read(getTablePath(filePath, name)); - if (table != null) + if (table != null) { assignment.putTable(name, table); + } } return assignment; } - public static boolean isGeoSymAssignment(String filePath) - { - if (filePath == null) - { + public static boolean isGeoSymAssignment(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -70,24 +64,21 @@ public static boolean isGeoSymAssignment(String filePath) GeoSymTableReader reader = new GeoSymTableReader(); - for (String name : tableNames) - { - if (!reader.canRead(getTablePath(filePath, name))) + for (String name : tableNames) { + if (!reader.canRead(getTablePath(filePath, name))) { return false; + } } return true; } - public String getFilePath() - { + public String getFilePath() { return this.filePath; } - public GeoSymTable getTable(String name) - { - if (name == null) - { + public GeoSymTable getTable(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -96,10 +87,8 @@ public GeoSymTable getTable(String name) return this.tableMap.get(name); } - public void putTable(String name, GeoSymTable table) - { - if (name == null) - { + public void putTable(String name, GeoSymTable table) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -108,8 +97,7 @@ public void putTable(String name, GeoSymTable table) this.tableMap.put(name, table); } - protected static String getTablePath(String filePath, String tableName) - { + protected static String getTablePath(String filePath, String tableName) { StringBuilder sb = new StringBuilder(); sb.append(filePath); sb.append("/"); diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeConverter.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeConverter.java index c2ffe7996d..269717a2dc 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeConverter.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeConverter.java @@ -28,16 +28,16 @@ * @author dcollins * @version $Id: GeoSymAttributeConverter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymAttributeConverter -{ +public class GeoSymAttributeConverter { + protected static String TYPE_POINT = "Point"; protected static String TYPE_LINE_PLAIN = "LinePlain"; protected static String TYPE_LINE_COMPLEX = "LineComplex"; protected static String TYPE_AREA_PLAIN = "AreaPlain"; protected static String TYPE_AREA_PATTERN = "AreaPattern"; - protected static class CGMFile - { + protected static class CGMFile { + protected File file; protected String content; protected String type; @@ -60,28 +60,26 @@ protected static class CGMFile protected int stippleFactor = 0; protected String edgeVis = ""; - public CGMFile(File file) - { + public CGMFile(File file) { this.file = file; processCGMFile(file); // TODO: process line stipple pattern - if (this.type.equals(TYPE_LINE_COMPLEX)) + if (this.type.equals(TYPE_LINE_COMPLEX)) { this.processStipplePattern(); + } } - protected void processCGMFile(File file) - { + protected void processCGMFile(File file) { this.content = readTextFile(file).replaceAll("\r", ""); String[] lines = this.content.split("\n"); String CGMLine = ""; - for (String line : lines) - { - if (!line.endsWith(";")) + for (String line : lines) { + if (!line.endsWith(";")) { line = line.trim() + " "; + } CGMLine += line; - if (CGMLine.endsWith(";")) - { + if (CGMLine.endsWith(";")) { this.processCGMLine(CGMLine); CGMLine = ""; } @@ -90,150 +88,131 @@ protected void processCGMFile(File file) this.type = getType(); } - protected void processCGMLine(String line) - { - if (line.startsWith("LINE ")) - { - if (getNumValues(line) == 4) + protected void processCGMLine(String line) { + if (line.startsWith("LINE ")) { + if (getNumValues(line) == 4) { this.lineCount++; - else + } else { this.polylineCount++; - } - else if (line.startsWith("CIRCLE ")) + } + } else if (line.startsWith("CIRCLE ")) { this.shapeCount++; - else if (line.startsWith("ELLIPARC ")) + } else if (line.startsWith("ELLIPARC ")) { this.shapeCount++; - else if (line.startsWith("POLYGONSET ")) + } else if (line.startsWith("POLYGONSET ")) { this.shapeCount++; - else if (line.startsWith("POLYGON ")) - { + } else if (line.startsWith("POLYGON ")) { this.polygonCount++; - if (getNumValues(line) == 12) + if (getNumValues(line) == 12) { this.pentagonCount++; - } - else if (line.startsWith("PATTABLE ")) - { + } + } else if (line.startsWith("PATTABLE ")) { this.patternCount++; this.patternTable = getIntegerValues(line); - } - else if (line.startsWith("LINECOLR ")) + } else if (line.startsWith("LINECOLR ")) { this.lineColorIndex = getIntegerValue(line); - else if (line.startsWith("FILLCOLR ")) + } else if (line.startsWith("FILLCOLR ")) { this.fillColorIndex = getIntegerValue(line); - else if (line.startsWith("LINEWIDTH ")) + } else if (line.startsWith("LINEWIDTH ")) { this.lineWidth = getIntegerValue(line); - else if (line.contains("LineComponentElement")) + } else if (line.contains("LineComponentElement")) { this.lineElementCount++; - else if (line.startsWith("EDGEVIS ")) + } else if (line.startsWith("EDGEVIS ")) { this.edgeVis = getStringValue(line); - else if (line.startsWith("COLRTABLE ")) + } else if (line.startsWith("COLRTABLE ")) { this.colorTable = getIntegerValues(line); - else if (line.startsWith("COLRTABLE ")) + } else if (line.startsWith("COLRTABLE ")) { this.colorTable = getIntegerValues(line); - else if (line.startsWith("SCALEMODE ")) + } else if (line.startsWith("SCALEMODE ")) { this.scale = getScaleValue(line); + } } - protected int getIntegerValue(String line) - { + protected int getIntegerValue(String line) { return Integer.parseInt(getStringValue(line)); } - protected int[] getIntegerValues(String line) - { + protected int[] getIntegerValues(String line) { line = line.substring(0, line.length() - 1); // remove end line ";" String[] values = line.split(" "); int[] ints = new int[values.length - 1]; int idx = 0; - for (int i = 1; i < values.length; i++) - { - if (values[i].length() > 0) + for (int i = 1; i < values.length; i++) { + if (values[i].length() > 0) { ints[idx++] = Integer.parseInt(values[i]); + } } return ints; } - protected String getStringValue(String line) - { + protected String getStringValue(String line) { line = line.substring(0, line.length() - 1); // remove end line ";" return line.split(" ")[1]; } - protected double getScaleValue(String line) - { + protected double getScaleValue(String line) { line = line.substring(0, line.length() - 1); // remove end line ";" String[] values = line.split(" "); return Double.parseDouble(values[2]); } - protected int getNumValues(String line) - { + protected int getNumValues(String line) { return line.split(" ").length - 1; } - protected String getColor(int idx) - { - if (idx < 0 || idx * 3 + 3 > this.colorTable.length - 1) + protected String getColor(int idx) { + if (idx < 0 || idx * 3 + 3 > this.colorTable.length - 1) { return "#FFFFFF"; + } String color = String.format("#%02x%02x%02x", this.colorTable[idx * 3 + 1], this.colorTable[idx * 3 + 2], - this.colorTable[idx * 3 + 3]); - if (color.length() > 7) + this.colorTable[idx * 3 + 3]); + if (color.length() > 7) { System.out.println( - "Color error: idx: " + idx + ", color: " + color + ", components: " + String.format("%d %d %d", - this.colorTable[idx * 3 + 1], this.colorTable[idx * 3 + 2], this.colorTable[idx * 3 + 3])); + "Color error: idx: " + idx + ", color: " + color + ", components: " + String.format("%d %d %d", + this.colorTable[idx * 3 + 1], this.colorTable[idx * 3 + 2], this.colorTable[idx * 3 + 3])); + } return color; } - protected String getType() - { - if (this.patternCount > 0) + protected String getType() { + if (this.patternCount > 0) { return TYPE_AREA_PATTERN; - else if (this.polygonCount == 1 && this.pentagonCount == 1 && this.edgeVis.equals("OFF") - && this.lineCount == 0 && this.polylineCount == 0 && this.shapeCount == 0) + } else if (this.polygonCount == 1 && this.pentagonCount == 1 && this.edgeVis.equals("OFF") + && this.lineCount == 0 && this.polylineCount == 0 && this.shapeCount == 0) { return TYPE_AREA_PLAIN; - else if (this.lineElementCount > 0) + } else if (this.lineElementCount > 0) { return TYPE_LINE_COMPLEX; - else if (this.lineCount == 1 && this.polylineCount == 0 && this.shapeCount == 0 && this.polygonCount == 0) + } else if (this.lineCount == 1 && this.polylineCount == 0 && this.shapeCount == 0 && this.polygonCount == 0) { return TYPE_LINE_PLAIN; - else + } else { return TYPE_POINT; + } } - protected void processStipplePattern() - { + protected void processStipplePattern() { //String elementType = ""; double elementLength = 0; double totalLength = 0; ArrayList lengths = new ArrayList(); String[] lines = this.content.split("\n"); // Gather pattern segments - for (String line : lines) - { - if (line.contains("Component.1.Element")) - { - if (elementLength > 0) - { + for (String line : lines) { + if (line.contains("Component.1.Element")) { + if (elementLength > 0) { lengths.add(elementLength); totalLength += elementLength; elementLength = 0; } - } - else if (line.startsWith("APSATTR \"ElementType\"")) - { + } else if (line.startsWith("APSATTR \"ElementType\"")) { //elementType = getLastValue(line); - } - else if (line.startsWith("APSATTR \"ElementLength\"")) - { + } else if (line.startsWith("APSATTR \"ElementLength\"")) { elementLength = Double.parseDouble(getLastValue(line)); - } - else if (line.contains("Component.2") || line.startsWith("BEGAPS \"IC_ViewportTable\"")) - { + } else if (line.contains("Component.2") || line.startsWith("BEGAPS \"IC_ViewportTable\"")) { break; } } // Gather last pattern portion if any - if (elementLength > 0) - { + if (elementLength > 0) { lengths.add(elementLength); totalLength += elementLength; } @@ -242,20 +221,18 @@ else if (line.contains("Component.2") || line.startsWith("BEGAPS \"IC_ViewportTa double bitLength = totalLength / 16; String bitMask = ""; char bit = '1'; - for (Double d : lengths) - { + for (Double d : lengths) { int bits = (int) Math.round(d / bitLength); - for (int i = 0; i < bits; i++) - { + for (int i = 0; i < bits; i++) { bitMask += bit; } bit = bit == '1' ? '0' : '1'; } // Padd or trim the bit mask to 16 bits - if (bitMask.length() == 0 || !bitMask.contains("0") || !bitMask.contains("1")) + if (bitMask.length() == 0 || !bitMask.contains("0") || !bitMask.contains("1")) { bitMask = "1111110001111000"; // default mask - while (bitMask.length() < 16) - { + } + while (bitMask.length() < 16) { bitMask += bitMask.substring(bitMask.length() - 1); } bitMask = bitMask.substring(0, 16); @@ -269,36 +246,33 @@ else if (line.contains("Component.2") || line.startsWith("BEGAPS \"IC_ViewportTa //System.out.println(""); } - protected String getLastValue(String line) - { + protected String getLastValue(String line) { String[] tokens = line.replaceAll("\"", "").replaceAll(";", "").split("\\s"); return tokens[tokens.length - 1]; } - protected BufferedImage getPattern() - { - if (this.patternTable == null) + protected BufferedImage getPattern() { + if (this.patternTable == null) { return null; + } Color color = Color.decode(getColor(this.fillColorIndex)); int width = this.patternTable[1]; int height = this.patternTable[2]; int idx = 4; // bit data start BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - if (this.patternTable[idx++] > 0) + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (this.patternTable[idx++] > 0) { image.setRGB(x, y, color.getRGB()); + } } } return image; } - public String toRecordString() - { + public String toRecordString() { String code = this.file.getName().split("\\.")[0]; String type = this.type; String lineWidth = ""; @@ -307,33 +281,27 @@ public String toRecordString() String stippleFactor = ""; String fillColor = ""; - if (this.type.equals(TYPE_AREA_PATTERN) || this.type.equals(TYPE_AREA_PLAIN)) - { + if (this.type.equals(TYPE_AREA_PATTERN) || this.type.equals(TYPE_AREA_PLAIN)) { // Set fill color for patterns too as a backup fillColor = getColor(this.fillColorIndex); - } - else if (this.type.equals(TYPE_LINE_PLAIN) || this.type.equals(TYPE_LINE_COMPLEX)) - { + } else if (this.type.equals(TYPE_LINE_PLAIN) || this.type.equals(TYPE_LINE_COMPLEX)) { // Use .5 if no line width found lineWidth = this.lineWidth > 0 ? String.format("%.1f", this.lineWidth * this.scale).replace(',', '.') - : ".5"; + : ".5"; // Use fill color if no line color found lineColor = this.lineColorIndex >= 0 ? getColor(this.lineColorIndex) : getColor(this.fillColorIndex); - if (this.type.equals(TYPE_LINE_COMPLEX)) - { + if (this.type.equals(TYPE_LINE_COMPLEX)) { stipplePattern = String.format("#%04x", this.stipplePattern); stippleFactor = "" + this.stippleFactor; } } return String.format("%s,%s,%s,%s,%s,%s,%s", code, type, lineWidth, lineColor, stipplePattern, - stippleFactor, fillColor); + stippleFactor, fillColor); } - public String readTextFile(File file) - { - if (file == null) - { + public String readTextFile(File file) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -342,24 +310,18 @@ public String readTextFile(File file) StringBuilder sb = new StringBuilder(); BufferedReader reader = null; - try - { + try { reader = new BufferedReader(new FileReader(file)); String line; - while ((line = reader.readLine()) != null) - { + while ((line = reader.readLine()) != null) { sb.append(line); sb.append(System.getProperty("line.separator")); // add back line separator } - } - catch (IOException e) - { + } catch (IOException e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToReadFile", file.getPath()); Logging.logger().log(java.util.logging.Level.SEVERE, msg); return null; - } - finally - { + } finally { WWIO.closeStream(reader, file.getPath()); } @@ -367,10 +329,8 @@ public String readTextFile(File file) } } - public static void main(String[] args) - { - if (args == null || args.length == 0) - { + public static void main(String[] args) { + if (args == null || args.length == 0) { printUsage(); return; } @@ -378,8 +338,7 @@ public static void main(String[] args) File[] cgmFiles = new File(args[0]).listFiles(); PrintStream outAttrs = null; - try - { + try { File outFile = new File(OUT_ATTRS_PATH); //noinspection ResultOfMethodCallIgnored outFile.getParentFile().mkdirs(); @@ -387,31 +346,27 @@ public static void main(String[] args) outAttrs = new PrintStream(new FileOutputStream(outFile)); // CSV Output outAttrs.println("# GeoSym line and area attributes"); outAttrs.println( - "# GeoSym code, Feature type, Line width, Line color, Stipple pattern, Stipple factor, Fill color"); + "# GeoSym code, Feature type, Line width, Line color, Stipple pattern, Stipple factor, Fill color"); outAttrs.println("#"); - for (File file : cgmFiles) - { - if (file.getName().toUpperCase().endsWith(".CGM")) - { + for (File file : cgmFiles) { + if (file.getName().toUpperCase().endsWith(".CGM")) { CGMFile cgmf = new CGMFile(file); - if (!cgmf.type.equals(TYPE_POINT)) + if (!cgmf.type.equals(TYPE_POINT)) { outAttrs.println(cgmf.toRecordString()); + } - if (cgmf.type.equals(TYPE_AREA_PATTERN)) + if (cgmf.type.equals(TYPE_AREA_PATTERN)) { writeAreaPattern(cgmf); + } } } System.out.println("Done."); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); - } - finally - { + } finally { WWIO.closeStream(outAttrs, OUT_ATTRS_PATH); } } @@ -420,8 +375,7 @@ public static void main(String[] args) protected static final String OUT_ATTRS_PATH = OUT_DIR + "/geosym/symasgn/ascii/geosym-line-area-attr.csv"; protected static final String OUT_PATTERNS_PATH = OUT_DIR + "/geosym/graphics/bin"; - protected static void printUsage() - { + protected static void printUsage() { System.out.println("GeoSymAttributeConverter"); System.out.println(); System.out.println("Converts GeoSym line attributes, area attributes, and area patterns into a form usable by"); @@ -430,23 +384,19 @@ protected static void printUsage() System.out.println("containing area patterns for VPF area shapes."); System.out.println(); System.out.println( - "Usage: java -cp worldwind.jar gov.nasa.worldwind.formats.vpf.GeoSymAttributeConverter [full path to \"GeoSymEd2Final/GRAPHICS/CTEXT\"]"); + "Usage: java -cp worldwind.jar gov.nasa.worldwind.formats.vpf.GeoSymAttributeConverter [full path to \"GeoSymEd2Final/GRAPHICS/CTEXT\"]"); System.out.println(); } - protected static void writeAreaPattern(CGMFile cgmf) - { + protected static void writeAreaPattern(CGMFile cgmf) { String fileName = cgmf.file.getName().toUpperCase().replace(".CGM", ".png"); File outFile = new File(OUT_PATTERNS_PATH, fileName); - try - { + try { //noinspection ResultOfMethodCallIgnored outFile.getParentFile().mkdirs(); ImageIO.write(cgmf.getPattern(), "png", outFile); - } - catch (Exception e) - { + } catch (Exception e) { System.out.println("Could not save pattern " + fileName); } } diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeExpression.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeExpression.java index c88593c77d..5c2773ced1 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeExpression.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeExpression.java @@ -11,7 +11,7 @@ * @author dcollins * @version $Id: GeoSymAttributeExpression.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface GeoSymAttributeExpression -{ +public interface GeoSymAttributeExpression { + boolean evaluate(AVList featureAttributes); } diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeExpressionProvider.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeExpressionProvider.java index 7230249489..b2cc14648f 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeExpressionProvider.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymAttributeExpressionProvider.java @@ -14,49 +14,40 @@ * @author dcollins * @version $Id: GeoSymAttributeExpressionProvider.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymAttributeExpressionProvider -{ +public class GeoSymAttributeExpressionProvider { + protected Map expressionMap; - public GeoSymAttributeExpressionProvider(GeoSymTable table) - { + public GeoSymAttributeExpressionProvider(GeoSymTable table) { this.expressionMap = new HashMap(); this.loadExpressions(table); } - public GeoSymAttributeExpression getAttributeExpression(int symbolId) - { + public GeoSymAttributeExpression getAttributeExpression(int symbolId) { return this.expressionMap.get(symbolId); } - protected void loadExpressions(GeoSymTable table) - { + protected void loadExpressions(GeoSymTable table) { this.expressionMap.clear(); // Group attribute expression rows with the same symbol ID. There is either zero or one set of attribute // expressions associated with each symbol ID. Sort expression rows within each group according to the // expression sequence number for each row. - HashMap> map = new HashMap>(); - for (AVList row : table.getRecords()) - { + for (AVList row : table.getRecords()) { Integer symbolId = AVListImpl.getIntegerValue(row, "cond_index"); Integer sequenceNumber = AVListImpl.getIntegerValue(row, "seq"); - if (symbolId == null || sequenceNumber == null) - { + if (symbolId == null || sequenceNumber == null) { String message = Logging.getMessage("VPF.GeoSymInvalidAttributeExpression", row); Logging.logger().warning(message); continue; } Set list = map.get(symbolId); - if (list == null) - { - list = new TreeSet(new Comparator() - { - public int compare(AVList a, AVList b) - { + if (list == null) { + list = new TreeSet(new Comparator() { + public int compare(AVList a, AVList b) { Integer ia = AVListImpl.getIntegerValue(a, "seq"); Integer ib = AVListImpl.getIntegerValue(b, "seq"); @@ -72,13 +63,10 @@ public int compare(AVList a, AVList b) // Parse each set of attribute expressions into an abstract logical expression, which may be evaluated at a // later time (given a set of feature attributes). Place each expression in a map, keying by the symbol ID // associated with that expression. - - for (Map.Entry> entry : map.entrySet()) - { + for (Map.Entry> entry : map.entrySet()) { LinkedList queue = new LinkedList(); - for (AVList row : entry.getValue()) - { + for (AVList row : entry.getValue()) { // If no connector is specified, then assume the terminal connector '0'. int connector = AVListImpl.getIntegerValue(row, "connector", 0); queue.add(new Comparison(row)); @@ -86,8 +74,7 @@ public int compare(AVList a, AVList b) } Expression expression = this.parseExpression(queue); - if (expression != null) - { + if (expression != null) { this.expressionMap.put(entry.getKey(), expression); } } @@ -96,7 +83,6 @@ public int compare(AVList a, AVList b) //**************************************************************// //******************** Expression Parsing ********************// //**************************************************************// - /** * See MIL-HDBK-857A, section 6.4. *

        @@ -108,73 +94,63 @@ public int compare(AVList a, AVList b) * * @return a live Expression which may be evaluated against any set of attribute values. */ - protected Expression parseExpression(Queue queue) - { - if (queue.isEmpty()) - { + protected Expression parseExpression(Queue queue) { + if (queue.isEmpty()) { return null; } // Perform a recursive descent parsing of the attribute expression components in the queue. - ExpressionParser comparisonParser = new ComparisonParser(queue); ExpressionParser logicalLevel1Parser = new LogicalExpressionParser(queue, comparisonParser, - EnumSet.of(LogicalOperator.AND_LEVEL1, LogicalOperator.OR_LEVEL1)); + EnumSet.of(LogicalOperator.AND_LEVEL1, LogicalOperator.OR_LEVEL1)); ExpressionParser logicalLevel2Parser = new LogicalExpressionParser(queue, logicalLevel1Parser, - EnumSet.of(LogicalOperator.AND_LEVEL2, LogicalOperator.OR_LEVEL2)); + EnumSet.of(LogicalOperator.AND_LEVEL2, LogicalOperator.OR_LEVEL2)); return logicalLevel2Parser.parse(); } - protected interface ExpressionParser - { + protected interface ExpressionParser { + Expression parse(); } - protected static class ComparisonParser implements ExpressionParser - { + protected static class ComparisonParser implements ExpressionParser { + protected Queue queue; - public ComparisonParser(Queue queue) - { + public ComparisonParser(Queue queue) { this.queue = queue; } - public Expression parse() - { + public Expression parse() { return (this.queue.peek() instanceof Comparison) ? (Comparison) this.queue.poll() : null; } } - protected static class LogicalExpressionParser implements ExpressionParser - { + protected static class LogicalExpressionParser implements ExpressionParser { + protected Queue queue; protected ExpressionParser delegateParser; protected EnumSet operatorSet; public LogicalExpressionParser(Queue queue, ExpressionParser delegateParser, - EnumSet operatorSet) - { + EnumSet operatorSet) { this.queue = queue; this.delegateParser = delegateParser; this.operatorSet = operatorSet; } - public Expression parse() - { + public Expression parse() { Expression exp = this.delegateParser.parse(); - if (exp == null) - { + if (exp == null) { return null; } LogicalExpression bool = null; LogicalOperator cur; - while ((cur = this.peekOperator()) != null && this.operatorSet.contains(cur)) - { - if (bool == null || !bool.logicalOperator.equals(cur)) - { + while ((cur = this.peekOperator()) != null && this.operatorSet.contains(cur)) { + if (bool == null || !bool.logicalOperator.equals(cur)) { bool = new LogicalExpression(cur); bool.add(exp); exp = bool; @@ -187,8 +163,7 @@ public Expression parse() return exp; } - protected LogicalOperator peekOperator() - { + protected LogicalOperator peekOperator() { return (this.queue.peek() instanceof LogicalOperator) ? (LogicalOperator) this.queue.peek() : null; } } @@ -196,186 +171,148 @@ protected LogicalOperator peekOperator() //**************************************************************// //******************** Expression Syntax *********************// //**************************************************************// + protected interface Expression extends GeoSymAttributeExpression { - protected interface Expression extends GeoSymAttributeExpression - { boolean evaluate(AVList params); } - protected static class Comparison implements Expression - { + protected static class Comparison implements Expression { + protected String attributeName; protected ComparisonOperator operator; protected String value; - public Comparison(String attributeName, ComparisonOperator op, String value) - { + public Comparison(String attributeName, ComparisonOperator op, String value) { this.attributeName = attributeName; this.operator = op; this.value = value; } - public Comparison(AVList params) - { + public Comparison(AVList params) { this.attributeName = params.getStringValue("att"); this.value = params.getStringValue("value"); Integer i = AVListImpl.getIntegerValue(params, "oper"); - if (i != null) + if (i != null) { this.operator = ComparisonOperator.values()[i]; + } } - public boolean evaluate(AVList featureAttributes) - { + public boolean evaluate(AVList featureAttributes) { return this.operator.evaluate(featureAttributes, this.attributeName, this.value); } } - protected static class LogicalExpression extends ArrayList implements Expression - { + protected static class LogicalExpression extends ArrayList implements Expression { + protected LogicalOperator logicalOperator; - public LogicalExpression(LogicalOperator op) - { + public LogicalExpression(LogicalOperator op) { this.logicalOperator = op; } - public boolean evaluate(AVList featureAttributes) - { + public boolean evaluate(AVList featureAttributes) { return this.logicalOperator.evaluate(featureAttributes, this); } } - protected static enum ComparisonOperator - { - NONE - { - public boolean evaluate(AVList params, String paramName, String value) - { - return false; - } - }, - EQUAL - { - public boolean evaluate(AVList params, String paramName, String value) - { - return compare(params, paramName, value) == 0; - } - }, - NOT_EQUAL - { - public boolean evaluate(AVList params, String paramName, String value) - { - return !EQUAL.evaluate(params, paramName, value); - } - }, - LESS_THAN - { - public boolean evaluate(AVList params, String paramName, String value) - { - return compare(params, paramName, value) < 0; - } - }, - GREATER_THAN - { - public boolean evaluate(AVList params, String paramName, String value) - { - return compare(params, paramName, value) > 0; - } - }, - LESS_THAN_OR_EQUAL_TO - { - public boolean evaluate(AVList params, String paramName, String value) - { - return compare(params, paramName, value) <= 0; - } - }, - GREATER_THAN_OR_EQUAL_TO - { - public boolean evaluate(AVList params, String paramName, String value) - { - return compare(params, paramName, value) >= 0; - } - }; + protected static enum ComparisonOperator { + NONE { + public boolean evaluate(AVList params, String paramName, String value) { + return false; + } + }, + EQUAL { + public boolean evaluate(AVList params, String paramName, String value) { + return compare(params, paramName, value) == 0; + } + }, + NOT_EQUAL { + public boolean evaluate(AVList params, String paramName, String value) { + return !EQUAL.evaluate(params, paramName, value); + } + }, + LESS_THAN { + public boolean evaluate(AVList params, String paramName, String value) { + return compare(params, paramName, value) < 0; + } + }, + GREATER_THAN { + public boolean evaluate(AVList params, String paramName, String value) { + return compare(params, paramName, value) > 0; + } + }, + LESS_THAN_OR_EQUAL_TO { + public boolean evaluate(AVList params, String paramName, String value) { + return compare(params, paramName, value) <= 0; + } + }, + GREATER_THAN_OR_EQUAL_TO { + public boolean evaluate(AVList params, String paramName, String value) { + return compare(params, paramName, value) >= 0; + } + }; public abstract boolean evaluate(AVList params, String paramName, String value); - private static int compare(AVList params, String paramName, String value) - { + private static int compare(AVList params, String paramName, String value) { Object o = params.getValue(paramName); boolean valueIsNull = value.equalsIgnoreCase("NULL"); // NULL feature attributes are stored as actual Java null references, while NULL values are the literal // string "NULL" (without the quotes). If both the attribute and value are null, then the value and // attribute are "equal". Otherwise, we say that the non-null quantity is greater than the null quantity. - if (valueIsNull || o == null) - { + if (valueIsNull || o == null) { return valueIsNull ? (o != null ? -1 : 0) : 1; - } - else - { + } else { // When value contains a text string, it has a leading and trailing double-quotation character. - if (value.startsWith("\"") && value.endsWith("\"")) + if (value.startsWith("\"") && value.endsWith("\"")) { value = value.substring(1, value.length() - 1); + } return String.CASE_INSENSITIVE_ORDER.compare(o.toString(), value); } } } - protected static enum LogicalOperator - { - NONE - { - public boolean evaluate(AVList params, Iterable iterable) - { - return false; - } - }, - OR_LEVEL1 - { - public boolean evaluate(AVList params, Iterable iterable) - { - for (Expression term : iterable) - { - if (term.evaluate(params)) - { - return true; - } + protected static enum LogicalOperator { + NONE { + public boolean evaluate(AVList params, Iterable iterable) { + return false; + } + }, + OR_LEVEL1 { + public boolean evaluate(AVList params, Iterable iterable) { + for (Expression term : iterable) { + if (term.evaluate(params)) { + return true; } - - return false; } - }, - AND_LEVEL2 - { - public boolean evaluate(AVList params, Iterable iterable) - { - return AND_LEVEL1.evaluate(params, iterable); - } - }, - AND_LEVEL1 - { - public boolean evaluate(AVList params, Iterable iterable) - { - for (Expression term : iterable) - { - if (!term.evaluate(params)) - { - return false; - } - } - return true; - } - }, - OR_LEVEL2 - { - public boolean evaluate(AVList params, Iterable iterable) - { - return OR_LEVEL1.evaluate(params, iterable); + return false; + } + }, + AND_LEVEL2 { + public boolean evaluate(AVList params, Iterable iterable) { + return AND_LEVEL1.evaluate(params, iterable); + } + }, + AND_LEVEL1 { + public boolean evaluate(AVList params, Iterable iterable) { + for (Expression term : iterable) { + if (!term.evaluate(params)) { + return false; + } } - }; + + return true; + } + }, + OR_LEVEL2 { + public boolean evaluate(AVList params, Iterable iterable) { + return OR_LEVEL1.evaluate(params, iterable); + } + }; public abstract boolean evaluate(AVList params, Iterable iterable); } diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymColumn.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymColumn.java index 73f56666de..537eafa4e8 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymColumn.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymColumn.java @@ -9,61 +9,51 @@ * @author dcollins * @version $Id: GeoSymColumn.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymColumn -{ +public class GeoSymColumn { + private final String name; private String dataType; private String dataSize; private String description; private String codeRef; - public GeoSymColumn(String name) - { + public GeoSymColumn(String name) { this.name = name; } - public String getName() - { + public String getName() { return name; } - public String getDataType() - { + public String getDataType() { return dataType; } - public void setDataType(String dataType) - { + public void setDataType(String dataType) { this.dataType = dataType; } - public String getDataSize() - { + public String getDataSize() { return dataSize; } - public void setDataSize(String dataSize) - { + public void setDataSize(String dataSize) { this.dataSize = dataSize; } - public String getDescription() - { + public String getDescription() { return description; } - public void setDescription(String description) - { + public void setDescription(String description) { this.description = description; } - public String getCodeRef() - { + public String getCodeRef() { return codeRef; } - public void setCodeRef(String codeRef) - { + public void setCodeRef(String codeRef) { this.codeRef = codeRef; } } diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymConstants.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymConstants.java index c26faf2299..63b77fb630 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymConstants.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymConstants.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: GeoSymConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface GeoSymConstants -{ +public interface GeoSymConstants { + // Column Types // MIL-DTL-89045 3.5.3.1 final String INTEGER = "N"; // integer diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymStyleProvider.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymStyleProvider.java index 9b74724e88..36d53041f6 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymStyleProvider.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymStyleProvider.java @@ -17,8 +17,8 @@ * @author Patrick Murris * @version $Id: GeoSymStyleProvider.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymStyleProvider -{ +public class GeoSymStyleProvider { + //private static String TYPE_POINT = "Point"; private static String TYPE_LINE_PLAIN = "LinePlain"; private static String TYPE_LINE_COMPLEX = "LineComplex"; @@ -37,25 +37,19 @@ public class GeoSymStyleProvider private Map attributes; private double lineWidthFactor = 3d; // mm to pixels - public GeoSymStyleProvider(String filePath) - { - try - { + public GeoSymStyleProvider(String filePath) { + try { this.loadStylesFromFile(filePath); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionWhileReading", filePath); Logging.logger().severe(message); throw new WWRuntimeException(message); } } - protected void loadStylesFromFile(String filePath) throws IOException - { + protected void loadStylesFromFile(String filePath) throws IOException { InputStream inputStream = WWIO.openFileOrResourceStream(filePath, this.getClass()); - if (inputStream == null) - { + if (inputStream == null) { String message = Logging.getMessage("generic.ExceptionWhileReading", filePath); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -63,39 +57,34 @@ protected void loadStylesFromFile(String filePath) throws IOException this.attributes = new HashMap(); Scanner scanner = new Scanner(inputStream); - while (scanner.hasNextLine()) - { + while (scanner.hasNextLine()) { String s = scanner.nextLine().trim(); - if (s.length() == 0 || s.startsWith("#")) + if (s.length() == 0 || s.startsWith("#")) { continue; + } String[] tokens = s.split(","); String code = tokens[0]; VPFSymbolAttributes attr = getAttributes(tokens); - if (attr != null) + if (attr != null) { this.attributes.put(code, attr); + } } inputStream.close(); } - private VPFSymbolAttributes getAttributes(String[] tokens) - { + private VPFSymbolAttributes getAttributes(String[] tokens) { VPFSymbolAttributes attr = new VPFSymbolAttributes(null, null); - if (tokens[TYPE].equals(TYPE_AREA_PLAIN) || tokens[TYPE].equals(TYPE_AREA_PATTERN)) - { + if (tokens[TYPE].equals(TYPE_AREA_PLAIN) || tokens[TYPE].equals(TYPE_AREA_PATTERN)) { attr.setInteriorMaterial(new Material(Color.decode(tokens[FILL_COLOR]))); - if (tokens[TYPE].equals(TYPE_AREA_PATTERN)) - { + if (tokens[TYPE].equals(TYPE_AREA_PATTERN)) { attr.setImageSource(tokens[CODE]); } - } - else if (tokens[TYPE].equals(TYPE_LINE_PLAIN) || tokens[TYPE].equals(TYPE_LINE_COMPLEX)) - { + } else if (tokens[TYPE].equals(TYPE_LINE_PLAIN) || tokens[TYPE].equals(TYPE_LINE_COMPLEX)) { attr.setOutlineMaterial(new Material(Color.decode(tokens[LINE_COLOR]))); attr.setOutlineWidth(Double.parseDouble(tokens[LINE_WIDTH]) * this.lineWidthFactor); - if (tokens[TYPE].equals(TYPE_LINE_COMPLEX)) - { + if (tokens[TYPE].equals(TYPE_LINE_COMPLEX)) { attr.setOutlineStipplePattern(Integer.decode(tokens[STIPPLE_PATTERN]).shortValue()); attr.setOutlineStippleFactor(Integer.parseInt(tokens[STIPPLE_FACTOR])); } @@ -104,8 +93,7 @@ else if (tokens[TYPE].equals(TYPE_LINE_PLAIN) || tokens[TYPE].equals(TYPE_LINE_C return attr; } - public VPFSymbolAttributes getAttributes(String code) - { + public VPFSymbolAttributes getAttributes(String code) { return this.attributes.get(code); } } diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymSupport.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymSupport.java index 9d15ace451..5077b92be7 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymSupport.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymSupport.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.vpf; import gov.nasa.worldwind.avlist.*; @@ -18,39 +17,40 @@ * @author Patrick Murris * @version $Id: GeoSymSupport.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymSupport -{ - protected static class FeatureKey - { +public class GeoSymSupport { + + protected static class FeatureKey { + private VPFFeatureClass featureClass; private String featureCode; - public FeatureKey(VPFFeatureClass featureClass, String featureCode) - { + public FeatureKey(VPFFeatureClass featureClass, String featureCode) { this.featureClass = featureClass; this.featureCode = featureCode; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } FeatureKey that = (FeatureKey) o; - if (this.featureCode != null ? !this.featureCode.equals(that.featureCode) : that.featureCode != null) + if (this.featureCode != null ? !this.featureCode.equals(that.featureCode) : that.featureCode != null) { return false; + } //noinspection RedundantIfStatement - if (this.featureClass != null ? !this.featureClass.equals(that.featureClass) : that.featureClass != null) + if (this.featureClass != null ? !this.featureClass.equals(that.featureClass) : that.featureClass != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result = this.featureClass != null ? this.featureClass.hashCode() : 0; result = 31 * result + (this.featureCode != null ? this.featureCode.hashCode() : 0); return result; @@ -72,17 +72,14 @@ public int hashCode() private GeoSymAbbreviationProvider abbreviationProvider; private GeoSymAttributeExpressionProvider attributeExpressionProvider; - public GeoSymSupport(String filePath, String symbolMimeType) - { - if (filePath == null) - { + public GeoSymSupport(String filePath, String symbolMimeType) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (symbolMimeType == null) - { + if (symbolMimeType == null) { String message = Logging.getMessage("nullValue.ImageFomat"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -94,13 +91,10 @@ public GeoSymSupport(String filePath, String symbolMimeType) this.loadAssignment(filePath); - if (this.assignment == null) - { + if (this.assignment == null) { String message = Logging.getMessage("VPF.GeoSymSupportDisabled"); Logging.logger().warning(message); - } - else - { + } else { this.loadStyleProvider(); this.loadAbbreviationProvider(); this.loadAttributeExpressionProvider(); @@ -110,46 +104,38 @@ public GeoSymSupport(String filePath, String symbolMimeType) } } - public String getFilePath() - { + public String getFilePath() { return this.filePath; } - public String getImageSuffix() - { + public String getImageSuffix() { return this.imageSuffix; } - public GeoSymAssignment getAssignment() - { + public GeoSymAssignment getAssignment() { return this.assignment; } public Iterable getSymbolKeys(VPFFeatureClass featureClass, String featureCode, - AVList featureAttributes) - { - if (featureClass == null) - { + AVList featureAttributes) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (featureCode == null) - { + if (featureCode == null) { String message = Logging.getMessage("nullValue.FeatureCodeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.getAssignment() == null) - { + if (this.getAssignment() == null) { return null; } // GeoSym does not provide stylization for Text features. - if (featureClass.getType() == VPFFeatureType.TEXT) - { + if (featureClass.getType() == VPFFeatureType.TEXT) { return null; } @@ -157,65 +143,54 @@ public Iterable getSymbolKeys(VPFFeatureClass featureCla // and FCODE. FeatureKey featureKey = new FeatureKey(featureClass, featureCode); List symbolKeys = this.featureMap.get(featureKey); - if (symbolKeys == null && !this.featureMap.containsKey(featureKey)) - { + if (symbolKeys == null && !this.featureMap.containsKey(featureKey)) { symbolKeys = this.doGetSymbolKeys(featureClass, featureCode); this.featureMap.put(featureKey, symbolKeys); } - if (symbolKeys != null && featureAttributes != null) - { + if (symbolKeys != null && featureAttributes != null) { symbolKeys = this.doEvaluateSymbolKeys(symbolKeys, featureAttributes); } List symbols = symbolKeys; - if (symbolKeys != null && symbolKeys.size() == 0) - { + if (symbolKeys != null && symbolKeys.size() == 0) { symbols = this.doGetUnknownSymbolKeys(); } return symbols; } - public Iterable getSymbolAttributes(VPFFeatureClass featureClass, VPFSymbolKey key) - { - if (key == null) - { + public Iterable getSymbolAttributes(VPFFeatureClass featureClass, VPFSymbolKey key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.getAssignment() == null) - { + if (this.getAssignment() == null) { return null; } // GeoSym does not provide stylization for Text features. - if (featureClass.getType() == VPFFeatureType.TEXT) - { + if (featureClass.getType() == VPFFeatureType.TEXT) { return null; } - if (key == VPFSymbolKey.UNKNOWN_SYMBOL_KEY) - { + if (key == VPFSymbolKey.UNKNOWN_SYMBOL_KEY) { return this.doGetUnknownSymbolAttributes(featureClass, key); } return this.doGetSymbolAttributes(featureClass, key); } - public Object getSymbolSource(String symbol) - { - if (symbol == null) - { + public Object getSymbolSource(String symbol) { + if (symbol == null) { String message = Logging.getMessage("nullValue.SymbolIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.getAssignment() == null) - { + if (this.getAssignment() == null) { return null; } @@ -227,110 +202,89 @@ public Object getSymbolSource(String symbol) sb.append(GeoSymConstants.BINARY); sb.append("/"); sb.append(symbol); - if (imageSuffix != null) + if (imageSuffix != null) { sb.append(this.imageSuffix); + } return sb.toString(); } - public String getAbbreviation(int tableId, int abbreviationId) - { + public String getAbbreviation(int tableId, int abbreviationId) { return this.abbreviationProvider.getAbbreviation(tableId, abbreviationId); } //**************************************************************// //******************** Symbology Data Initialization *********// //**************************************************************// - - protected void loadAssignment(String filePath) - { + protected void loadAssignment(String filePath) { String geoSymPath = this.getAssignmentPath(filePath); - if (!GeoSymAssignment.isGeoSymAssignment(geoSymPath)) - { + if (!GeoSymAssignment.isGeoSymAssignment(geoSymPath)) { String message = Logging.getMessage("VPF.GeoSymNotFound"); Logging.logger().warning(message); return; } - try - { + try { this.assignment = GeoSymAssignment.fromFile(geoSymPath); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileReading", filePath); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - protected void loadStyleProvider() - { + protected void loadStyleProvider() { String path = this.getPathForAssignmentFile(this.filePath, GeoSymConstants.LINE_AREA_ATTRIBUTES_FILE); - try - { + try { this.styleProvider = new GeoSymStyleProvider(path); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileReading", path); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - protected void loadAbbreviationProvider() - { + protected void loadAbbreviationProvider() { String path = this.getPathForAssignmentFile(this.filePath, GeoSymConstants.TEXT_ABBREVIATIONS_ASSIGNMENT_FILE); - try - { + try { this.abbreviationProvider = new GeoSymAbbreviationProvider(path); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileReading", path); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - protected void loadAttributeExpressionProvider() - { + protected void loadAttributeExpressionProvider() { GeoSymTable table = this.getAssignment().getTable(GeoSymConstants.ATTRIBUTE_EXPRESSION_FILE); - try - { + try { this.attributeExpressionProvider = new GeoSymAttributeExpressionProvider(table); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileReading", - GeoSymConstants.ATTRIBUTE_EXPRESSION_FILE); + GeoSymConstants.ATTRIBUTE_EXPRESSION_FILE); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - protected void loadLabelAttributes() - { + protected void loadLabelAttributes() { // Load label attributes for text characteristics and text locations. GeoSymTable colorTable = this.getAssignment().getTable(GeoSymConstants.COLOR_ASSIGNMENT_FILE); GeoSymTable textCharTable = this.getAssignment().getTable(GeoSymConstants.TEXT_LABEL_CHARACTERISTICS_FILE); GeoSymTable textLocTable = this.getAssignment().getTable(GeoSymConstants.TEXT_LABEL_LOCATION_FILE); Map labelCharacteristics = getTextLabelCharacteristics( - textCharTable, colorTable); + textCharTable, colorTable); Map labelLocations = getTextLabelLocations(textLocTable); // Map text join to label attributes this.textJoinAttributes = new HashMap(); GeoSymTable joinTable = this.getAssignment().getTable(GeoSymConstants.TEXT_LABEL_JOIN_FILE); - for (AVList row : joinTable.getRecords()) - { + for (AVList row : joinTable.getRecords()) { int id = (Integer) row.getValue("id"); int textCharId = (Integer) row.getValue("textcharid"); int textLocId = (Integer) row.getValue("textlocid"); VPFSymbolAttributes.LabelAttributes attr = new VPFSymbolAttributes.LabelAttributes(); VPFSymbolAttributes.LabelAttributes chars = labelCharacteristics.get(textCharId); - if (chars != null) - { + if (chars != null) { attr.setFont(chars.getFont()); attr.setColor(chars.getColor()); attr.setBackgroundColor(chars.getBackgroundColor()); @@ -340,8 +294,7 @@ protected void loadLabelAttributes() } VPFSymbolAttributes.LabelAttributes loc = labelLocations.get(textLocId); - if (loc != null) - { + if (loc != null) { attr.setOffset(loc.getOffset()); attr.setOffsetAngle(loc.getOffsetAngle()); } @@ -350,37 +303,35 @@ protected void loadLabelAttributes() } } - protected void loadProductTypes() - { + protected void loadProductTypes() { GeoSymTable codeTable = this.getAssignment().getTable(GeoSymConstants.CODE_VALUE_DESCRIPTION_FILE); ArrayList rows = new ArrayList(Arrays.asList(codeTable.getRecords())); GeoSymTable.selectMatchingRows("file", GeoSymConstants.FULL_SYMBOL_ASSIGNMENT_FILE, false, rows); GeoSymTable.selectMatchingRows("attribute", "pid", false, rows); this.productTypes = new HashMap(); - for (AVList row : rows) - { + for (AVList row : rows) { Integer value = (Integer) row.getValue("value"); String description = (String) row.getValue("description"); - if (value != null && description != null) + if (value != null && description != null) { this.productTypes.put(description.toUpperCase(), value); + } } } - protected void loadFeatureTypes() - { + protected void loadFeatureTypes() { GeoSymTable codeTable = this.getAssignment().getTable(GeoSymConstants.CODE_VALUE_DESCRIPTION_FILE); ArrayList rows = new ArrayList(Arrays.asList(codeTable.getRecords())); GeoSymTable.selectMatchingRows("file", GeoSymConstants.FULL_SYMBOL_ASSIGNMENT_FILE, false, rows); GeoSymTable.selectMatchingRows("attribute", "delin", false, rows); this.deliniations = new HashMap(); - for (AVList row : rows) - { + for (AVList row : rows) { Integer value = (Integer) row.getValue("value"); String description = (String) row.getValue("description"); - if (value != null && description != null) + if (value != null && description != null) { this.deliniations.put(description.toUpperCase(), value); + } } this.featureName = new HashMap(); @@ -389,8 +340,7 @@ protected void loadFeatureTypes() this.featureName.put(VPFFeatureType.AREA, "AREA"); } - protected String getAssignmentPath(String filePath) - { + protected String getAssignmentPath(String filePath) { StringBuilder sb = new StringBuilder(); sb.append(filePath); sb.append("/"); @@ -401,8 +351,7 @@ protected String getAssignmentPath(String filePath) return sb.toString(); } - protected String getPathForAssignmentFile(String filePath, String fileName) - { + protected String getPathForAssignmentFile(String filePath, String fileName) { StringBuilder sb = new StringBuilder(); sb.append(this.getAssignmentPath(filePath)); sb.append("/"); @@ -411,14 +360,12 @@ protected String getPathForAssignmentFile(String filePath, String fileName) } protected static HashMap getTextLabelCharacteristics( - GeoSymTable textCharTable, - GeoSymTable colorTable) - { - HashMap attributes = - new HashMap(); - - for (AVList row : textCharTable.getRecords()) - { + GeoSymTable textCharTable, + GeoSymTable colorTable) { + HashMap attributes + = new HashMap(); + + for (AVList row : textCharTable.getRecords()) { Integer id = (Integer) row.getValue("id"); VPFSymbolAttributes.LabelAttributes attr = getTextLabelCharacteristics(row, colorTable); @@ -428,8 +375,7 @@ protected static HashMap getTextLa return attributes; } - protected static VPFSymbolAttributes.LabelAttributes getTextLabelCharacteristics(AVList row, GeoSymTable colorTable) - { + protected static VPFSymbolAttributes.LabelAttributes getTextLabelCharacteristics(AVList row, GeoSymTable colorTable) { VPFSymbolAttributes.LabelAttributes attr = new VPFSymbolAttributes.LabelAttributes(); // Get text characteristics @@ -442,45 +388,45 @@ protected static VPFSymbolAttributes.LabelAttributes getTextLabelCharacteristics Integer abbreviationTableIndex = (Integer) row.getValue("abindexid"); // Assemble label attributes - if (fontType != null && fontStyle != null && size != null) - { + if (fontType != null && fontStyle != null && size != null) { String fontString = fontType == 0 ? "Arial-" : "Serif-"; - if (fontStyle == 0 || fontStyle == 4) + if (fontStyle == 0 || fontStyle == 4) { fontString += "PLAIN"; - else if (fontStyle == 1 || fontStyle == 5) + } else if (fontStyle == 1 || fontStyle == 5) { fontString += "BOLD"; - else if (fontStyle == 2 || fontStyle == 6) + } else if (fontStyle == 2 || fontStyle == 6) { fontString += "ITALIC"; - else if (fontStyle == 3 || fontStyle == 7) + } else if (fontStyle == 3 || fontStyle == 7) { fontString += "BOLDITALIC"; - else + } else { fontString += "PLAIN"; + } fontString += "-" + size; attr.setFont(Font.decode(fontString)); } - if (color != null) - { + if (color != null) { attr.setColor(color); attr.setBackgroundColor(WWUtil.computeContrastingColor(color)); } - if (prepend != null) + if (prepend != null) { attr.setPrepend("" + Character.toChars(Integer.parseInt(prepend, 16))[0]); - if (append != null) + } + if (append != null) { attr.setAppend("" + Character.toChars(Integer.parseInt(append, 16))[0]); - if (abbreviationTableIndex != null) + } + if (abbreviationTableIndex != null) { attr.setAbbreviationTableId(abbreviationTableIndex); + } return attr; } protected static HashMap getTextLabelLocations( - GeoSymTable textLocTable) - { - HashMap attributes = - new HashMap(); + GeoSymTable textLocTable) { + HashMap attributes + = new HashMap(); - for (AVList row : textLocTable.getRecords()) - { + for (AVList row : textLocTable.getRecords()) { Integer id = (Integer) row.getValue("id"); VPFSymbolAttributes.LabelAttributes attr = getTextLabelLocation(row); @@ -490,8 +436,7 @@ protected static HashMap getTextLa return attributes; } - protected static VPFSymbolAttributes.LabelAttributes getTextLabelLocation(AVList row) - { + protected static VPFSymbolAttributes.LabelAttributes getTextLabelLocation(AVList row) { VPFSymbolAttributes.LabelAttributes attr = new VPFSymbolAttributes.LabelAttributes(); // From MIL-HDBK-857A, section 6.8.3: The tjust field contain a numeric code whose possible values for the @@ -500,24 +445,22 @@ protected static VPFSymbolAttributes.LabelAttributes getTextLabelLocation(AVList // In addition to the traditional vertical and horizontal justifications, one justification (sounding text) // specifies that the attribute is a depth value. See section 6.8.3.1 for details on how to place the depth // value as a text label. - // TODO: apply text justification - //Integer i = (Integer) row.getValue("tjust"); //if (i != null) // attr.setJustification(i); - // From MIL-HDBK-857A, section 6.8.3: The tdist and tdir fields describe the distance in millimeters and the // azimuth degrees from North for the default offset of the text label relative to the feature's position. Zero // values in these fields indicate that the text is to be displayed at the center of the feature. - Integer i = (Integer) row.getValue("tdist"); - if (i != null) + if (i != null) { attr.setOffset(i); + } i = (Integer) row.getValue("tdir"); - if (i != null) + if (i != null) { attr.setOffsetAngle(Angle.fromDegrees(i)); + } return attr; } @@ -525,26 +468,20 @@ protected static VPFSymbolAttributes.LabelAttributes getTextLabelLocation(AVList //**************************************************************// //******************** Symbol Selection **********************// //**************************************************************// - - protected List doGetSymbolKeys(VPFFeatureClass featureClass, String featureCode) - { + protected List doGetSymbolKeys(VPFFeatureClass featureClass, String featureCode) { // Select the symbol rows associated with this feature class and feature code combination. Collection symbolRows = this.selectSymbolRows(featureClass, featureCode); - if (symbolRows == null || symbolRows.isEmpty()) - { + if (symbolRows == null || symbolRows.isEmpty()) { return Collections.emptyList(); } // Create symbol keys for each symbol row. ArrayList keyList = new ArrayList(); - for (AVList symbolRow : symbolRows) - { - if (symbolRow != null) - { + for (AVList symbolRow : symbolRows) { + if (symbolRow != null) { Integer id = AVListImpl.getIntegerValue(symbolRow, "id"); - if (id != null) - { + if (id != null) { keyList.add(new VPFSymbolKey(id)); } } @@ -557,37 +494,33 @@ protected List doGetSymbolKeys(VPFFeatureClass featureCl } /** - * From MIL-HDBK-857A, section 6.4.1.6.1: Default Symbology Although all efforts have been made to symbolize all + * From MIL-HDBK-857A, section 6.4.1.6.1: Default Symbology Although all efforts have been made to symbolize all * features according to the appropriate symbology specifications, should the application software be unable to * determine at least one "true" condition for a particular instance of a feature in the VPF dataset, there are - * default CGMs provided in GeoSym for displaying that feature. The following table identifies which symbol should + * default CGMs provided in GeoSym for displaying that feature. The following table identifies which symbol should * be used to symbolize an "unknown" point, line, or area feature. *

        - * Note that the default symbols should only be placed under two conditions: 1. There is no row in the *sym.txt - * file for the feature (fcode) 2. After evaluating all rows in the *sym.txt file for that fcode, there is no row - * that results in an evaluation of "true". + * Note that the default symbols should only be placed under two conditions: 1. There is no row in the *sym.txt file + * for the feature (fcode) 2. After evaluating all rows in the *sym.txt file for that fcode, there is no row that + * results in an evaluation of "true". * * @return a single element list containing a reference to the unknown symbol key {@link * gov.nasa.worldwind.formats.vpf.VPFSymbolKey#UNKNOWN_SYMBOL_KEY}. */ - protected List doGetUnknownSymbolKeys() - { + protected List doGetUnknownSymbolKeys() { return Arrays.asList(VPFSymbolKey.UNKNOWN_SYMBOL_KEY); } protected List doEvaluateSymbolKeys(Iterable iterable, - AVList featureAttributes) - { + AVList featureAttributes) { ArrayList filteredKeys = new ArrayList(); - for (VPFSymbolKey key : iterable) - { + for (VPFSymbolKey key : iterable) { // If there exists an attribute expression for the current symbol, and the expression evaluates to 'false', // then drop the current symbol from the list of potential symbols. GeoSymAttributeExpression exp = this.attributeExpressionProvider.getAttributeExpression( - key.getSymbolCode()); - if (exp != null && !exp.evaluate(featureAttributes)) - { + key.getSymbolCode()); + if (exp != null && !exp.evaluate(featureAttributes)) { continue; } @@ -598,27 +531,26 @@ protected List doEvaluateSymbolKeys(Iterable selectSymbolRows(VPFFeatureClass featureClass, String featureCode) - { + protected Collection selectSymbolRows(VPFFeatureClass featureClass, String featureCode) { // Get the product id associated with the feature class. A value of -1 indicates that no id is available. int pid = -1; String productName = this.getProductName(featureClass); - if (productName != null) - { + if (productName != null) { Integer i = this.productTypes.get(productName.toUpperCase()); - if (i != null) + if (i != null) { pid = i; + } } // Get the feature deliniation id associated with the feature class. A value of -1 indicates that no id is // available. int delin = -1; String featureName = this.featureName.get(featureClass.getType()); - if (featureName != null) - { + if (featureName != null) { Integer i = this.deliniations.get(featureName.toUpperCase()); - if (i != null) + if (i != null) { delin = i; + } } // Get the coverage associated with the feature class. @@ -632,8 +564,7 @@ protected Collection selectSymbolRows(VPFFeatureClass featureClass, Stri } protected static Collection selectSymbolAssignments(GeoSymTable table, int pid, String fcode, int delin, - String cov) - { + String cov) { ArrayList rows = new ArrayList(Arrays.asList(table.getRecords())); // The fcode field contains the 5-character feature code as defined in the applicable VPF product specification. @@ -641,16 +572,14 @@ protected static Collection selectSymbolAssignments(GeoSymTable table, i // The pid field contains a coded numeric value that identifies the VPF product to which the rule applies. The // mapping from pidfile (see section 3.5.3.1.4). - if (pid > 0) - { + if (pid > 0) { // Some assignments do not specify a 'pid'. In these cases, we must select those rows too. GeoSymTable.selectMatchingRows("pid", pid, true, rows); } // The delin field contains a coded numeric value that identifies the delineation of that fcode. The mapping // from delin number to delineation type is defithe code.txt file. - if (delin > 0) - { + if (delin > 0) { // Some assignments do not specify a 'delin'. In these cases, we must select those rows too. GeoSymTable.selectMatchingRows("delin", delin, true, rows); } @@ -663,9 +592,7 @@ protected static Collection selectSymbolAssignments(GeoSymTable table, i // coverage is being displayed. If the cov field is populated, it will contain one of two types of information: // 1.) the abbreviation of the appropriate VPF coverage (e.g., sdr,pop) in that product as defined in that // product's coverage attribute table (cat); or 2.) the "not" of that same coverage (e.g., <>sdr,<>pop). - - if (cov != null) - { + if (cov != null) { // Some assignments do not specify a 'cov'. In these cases, we must ignore the cov parameter and return // the closest match according to the other parameters. selectMatchingCoverages("cov", cov, true, rows); @@ -674,13 +601,11 @@ protected static Collection selectSymbolAssignments(GeoSymTable table, i return rows; } - protected String getProductName(VPFFeatureClass featureClass) - { + protected String getProductName(VPFFeatureClass featureClass) { String s = featureClass.getCoverage().getLibrary().getProductType(); // 'TADS', or Terrain Analysis Data Set is an alias for 'VITD', or 'Vector Product Interim Terrain Data'. - if (s != null && s.equals("TADS")) - { + if (s != null && s.equals("TADS")) { s = "VITD"; } @@ -688,75 +613,74 @@ protected String getProductName(VPFFeatureClass featureClass) } protected static void selectMatchingCoverages(String columnName, String value, boolean acceptNullValue, - List outRows) - { + List outRows) { Iterator iter = outRows.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return; + } AVList record; - while (iter.hasNext()) - { + while (iter.hasNext()) { record = iter.next(); - if (record == null) + if (record == null) { continue; + } Object o = record.getValue(columnName); - if (o == null || o instanceof String) - { + if (o == null || o instanceof String) { String s = (String) o; - if (s == null || s.length() == 0) - { - if (!acceptNullValue) + if (s == null || s.length() == 0) { + if (!acceptNullValue) { iter.remove(); - } - else - { + } + } else { int pos = s.indexOf("<>"); - if (pos >= 0) + if (pos >= 0) { s = s.substring(pos + 1, s.length()); + } boolean match = s.equalsIgnoreCase(value); - if ((pos < 0 && !match) || (pos >= 0 && match)) + if ((pos < 0 && !match) || (pos >= 0 && match)) { iter.remove(); + } } } } } protected static int selectCodeValue(GeoSymTable codeTable, String fileName, String attributeName, - String description) - { + String description) { ArrayList rows = new ArrayList(Arrays.asList(codeTable.getRecords())); GeoSymTable.selectMatchingStringRows("file", fileName, false, rows); GeoSymTable.selectMatchingStringRows("attribute", attributeName, false, rows); GeoSymTable.selectMatchingStringRows("description", description, false, rows); - if (rows.size() == 0) + if (rows.size() == 0) { return -1; + } Integer i = (Integer) rows.get(0).getValue("value"); return (i != null) ? i : -1; } protected static String selectCodeDescription(GeoSymTable codeTable, String fileName, String attributeName, - int value) - { + int value) { ArrayList rows = new ArrayList(Arrays.asList(codeTable.getRecords())); GeoSymTable.selectMatchingStringRows("file", fileName, false, rows); GeoSymTable.selectMatchingStringRows("attribute", attributeName, false, rows); GeoSymTable.selectMatchingRows("value", value, false, rows); - if (rows.size() == 0) + if (rows.size() == 0) { return null; + } return (String) rows.get(0).getValue("description"); } - protected static Color selectColor(GeoSymTable colorTable, int colorIndex) - { + protected static Color selectColor(GeoSymTable colorTable, int colorIndex) { ArrayList rows = new ArrayList(Arrays.asList(colorTable.getRecords())); GeoSymTable.selectMatchingRows("index", colorIndex, false, rows); - if (rows.size() == 0) + if (rows.size() == 0) { return null; + } AVList row = rows.get(0); Integer r = (Integer) row.getValue("red"); @@ -765,8 +689,7 @@ protected static Color selectColor(GeoSymTable colorTable, int colorIndex) return (r != null && g != null && b != null) ? new Color(r, g, b) : null; } - protected static AVList selectTextLabelCharacteristics(GeoSymTable textCharTable, int txtRowId) - { + protected static AVList selectTextLabelCharacteristics(GeoSymTable textCharTable, int txtRowId) { ArrayList rows = new ArrayList(Arrays.asList(textCharTable.getRecords())); GeoSymTable.selectMatchingRows("id", txtRowId, false, rows); return (rows.size() == 0) ? null : rows.get(0); @@ -775,45 +698,34 @@ protected static AVList selectTextLabelCharacteristics(GeoSymTable textCharTable //**************************************************************// //******************** Symbol Attribute Assembly *************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) protected Iterable doGetSymbolAttributes(VPFFeatureClass featureClass, - VPFSymbolKey key) - { + VPFSymbolKey key) { // Get the symbology assignment table. GeoSymTable symbolTable = this.getAssignment().getTable(GeoSymConstants.FULL_SYMBOL_ASSIGNMENT_FILE); AVList symbolRow = symbolTable.getRecord(key.getSymbolCode()); - if (symbolRow == null) - { + if (symbolRow == null) { return null; } VPFSymbolAttributes attr = null; String s; - if ((s = symbolRow.getStringValue("pointsym")) != null && s.length() > 0) - { + if ((s = symbolRow.getStringValue("pointsym")) != null && s.length() > 0) { attr = new VPFSymbolAttributes(VPFFeatureType.POINT, key); this.assemblePointSymbolAttributes(s, attr); - } - else if ((s = symbolRow.getStringValue("linesym")) != null && s.length() > 0) - { + } else if ((s = symbolRow.getStringValue("linesym")) != null && s.length() > 0) { attr = new VPFSymbolAttributes(VPFFeatureType.LINE, key); this.assembleLineSymbolAttributes(s, attr); - } - else if ((s = symbolRow.getStringValue("areasym")) != null && s.length() > 0) - { + } else if ((s = symbolRow.getStringValue("areasym")) != null && s.length() > 0) { attr = new VPFSymbolAttributes(VPFFeatureType.AREA, key); this.assembleAreaSymbolAttributes(s, attr); - } - else if ((s = symbolRow.getStringValue("labatt")) != null && s.length() > 0) - { + } else if ((s = symbolRow.getStringValue("labatt")) != null && s.length() > 0) { attr = new VPFSymbolAttributes(VPFFeatureType.LABEL, key); this.assembleTextLabelAttributes(symbolRow, attr); } - if (attr != null) - { + if (attr != null) { // Assemble the common symbol attributes. this.assembleCommonSymbolAttributes(symbolRow, attr); } @@ -822,19 +734,16 @@ else if ((s = symbolRow.getStringValue("labatt")) != null && s.length() > 0) } protected Iterable doGetUnknownSymbolAttributes(VPFFeatureClass featureClass, - VPFSymbolKey key) - { + VPFSymbolKey key) { ArrayList list = new ArrayList(); - if (featureClass.getType() == VPFFeatureType.POINT || featureClass.getType() == VPFFeatureType.AREA) - { + if (featureClass.getType() == VPFFeatureType.POINT || featureClass.getType() == VPFFeatureType.AREA) { VPFSymbolAttributes attr = new VPFSymbolAttributes(featureClass.getType(), key); this.assemblePointSymbolAttributes(UNKNOWN_POINT_SYMBOL, attr); list.add(attr); } - if (featureClass.getType() == VPFFeatureType.LINE || featureClass.getType() == VPFFeatureType.AREA) - { + if (featureClass.getType() == VPFFeatureType.LINE || featureClass.getType() == VPFFeatureType.AREA) { VPFSymbolAttributes attr = new VPFSymbolAttributes(featureClass.getType(), key); this.assembleLineSymbolAttributes(UNKNOWN_LINE_SYMBOL, attr); list.add(attr); @@ -843,32 +752,31 @@ protected Iterable doGetUnknownSymbolAttributes(V return list; } - protected void assembleCommonSymbolAttributes(AVList symbolRow, VPFSymbolAttributes attr) - { + protected void assembleCommonSymbolAttributes(AVList symbolRow, VPFSymbolAttributes attr) { Integer i = AVListImpl.getIntegerValue(symbolRow, "dispri"); - if (i != null) + if (i != null) { attr.setDisplayPriority(i); + } String s = AVListImpl.getStringValue(symbolRow, "orient"); - if (s != null) + if (s != null) { attr.setOrientationAttributeName(s); + } s = AVListImpl.getStringValue(symbolRow, "feadesc"); - if (s != null) + if (s != null) { attr.setDescription(s); + } } - protected void assemblePointSymbolAttributes(String symbol, VPFSymbolAttributes attr) - { + protected void assemblePointSymbolAttributes(String symbol, VPFSymbolAttributes attr) { Object source = this.getSymbolSource(symbol); attr.setIconImageSource(source); } - protected void assembleLineSymbolAttributes(String symbol, VPFSymbolAttributes attr) - { + protected void assembleLineSymbolAttributes(String symbol, VPFSymbolAttributes attr) { VPFSymbolAttributes geoSymAttr = (this.styleProvider != null) ? this.styleProvider.getAttributes(symbol) : null; - if (geoSymAttr != null) - { + if (geoSymAttr != null) { attr.setDrawInterior(false); attr.setDrawOutline(true); attr.setOutlineMaterial(geoSymAttr.getOutlineMaterial()); @@ -878,72 +786,61 @@ protected void assembleLineSymbolAttributes(String symbol, VPFSymbolAttributes a } } - protected void assembleAreaSymbolAttributes(String symbol, VPFSymbolAttributes attr) - { + protected void assembleAreaSymbolAttributes(String symbol, VPFSymbolAttributes attr) { VPFSymbolAttributes geoSymAttr = (this.styleProvider != null) ? this.styleProvider.getAttributes(symbol) : null; - if (geoSymAttr != null) - { + if (geoSymAttr != null) { attr.setDrawInterior(true); attr.setDrawOutline(false); attr.setInteriorMaterial(geoSymAttr.getInteriorMaterial()); - if (geoSymAttr.getImageSource() != null && geoSymAttr.getImageSource() instanceof String) - { + if (geoSymAttr.getImageSource() != null && geoSymAttr.getImageSource() instanceof String) { Object symbolSource = this.getSymbolSource((String) geoSymAttr.getImageSource()); attr.setImageSource(symbolSource); } } } - protected void assembleTextLabelAttributes(AVList labelRow, VPFSymbolAttributes attr) - { + protected void assembleTextLabelAttributes(AVList labelRow, VPFSymbolAttributes attr) { String[] attributeNames = null; String[] txtRowIds = null; String s = (String) labelRow.getValue("labatt"); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { String[] array = s.split(","); - if (array != null && array.length > 0) - { + if (array != null && array.length > 0) { attributeNames = array; } } s = (String) labelRow.getValue("txrowid"); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { String[] array = s.split(","); - if (array != null && array.length > 0) - { + if (array != null && array.length > 0) { txtRowIds = array; } } - if (attributeNames == null || txtRowIds == null) - { + if (attributeNames == null || txtRowIds == null) { return; } // The cardinality of the labatt and txtrowid arrays should always be identical, but check anyway. Fall back to // using the smallest cardinality available in both arrays. int numLabels = attributeNames.length; - if (numLabels > txtRowIds.length) + if (numLabels > txtRowIds.length) { numLabels = txtRowIds.length; + } VPFSymbolAttributes.LabelAttributes[] labelAttr = new VPFSymbolAttributes.LabelAttributes[numLabels]; - for (int i = 0; i < numLabels; i++) - { + for (int i = 0; i < numLabels; i++) { labelAttr[i] = new VPFSymbolAttributes.LabelAttributes(); labelAttr[i].setAttributeName(attributeNames[i]); Integer txtRowId = WWUtil.convertStringToInteger(txtRowIds[i]); - if (txtRowId != null) - { + if (txtRowId != null) { VPFSymbolAttributes.LabelAttributes tmp = this.textJoinAttributes.get(txtRowId); - if (tmp != null) - { + if (tmp != null) { labelAttr[i].setFont(tmp.getFont()); labelAttr[i].setColor(tmp.getColor()); labelAttr[i].setBackgroundColor(tmp.getBackgroundColor()); diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymTable.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymTable.java index 768f3f27a4..2978032709 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymTable.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymTable.java @@ -13,103 +13,92 @@ * @author dcollins * @version $Id: GeoSymTable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymTable -{ +public class GeoSymTable { + private GeoSymTableHeader header; private AVList[] records; private Map indexOnId; - public GeoSymTable(GeoSymTableHeader header) - { + public GeoSymTable(GeoSymTableHeader header) { this.header = header; this.indexOnId = new HashMap(); } - public GeoSymTableHeader getHeader() - { + public GeoSymTableHeader getHeader() { return header; } - public AVList[] getRecords() - { + public AVList[] getRecords() { return this.records; } - public void setRecords(AVList[] records) - { + public void setRecords(AVList[] records) { this.records = records; this.buildRecordIndices(); } - public AVList getRecord(int id) - { + public AVList getRecord(int id) { Integer index = this.indexOnId.get(id); return (index != null && index >= 0 && index < this.records.length) ? this.records[index] : null; } public static void selectMatchingRows(String columnName, Object value, boolean acceptNullValue, - List outRows) - { + List outRows) { Iterator iter = outRows.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return; + } AVList record; - while (iter.hasNext()) - { + while (iter.hasNext()) { record = iter.next(); - if (record == null) + if (record == null) { continue; + } Object o = record.getValue(columnName); - if ((o == null && !acceptNullValue) || (o != null && !o.equals(value))) - { + if ((o == null && !acceptNullValue) || (o != null && !o.equals(value))) { iter.remove(); } } } public static void selectMatchingStringRows(String columnName, String value, boolean acceptNullValue, - List outRows) - { + List outRows) { Iterator iter = outRows.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return; + } AVList record; - while (iter.hasNext()) - { + while (iter.hasNext()) { record = iter.next(); - if (record == null) + if (record == null) { continue; + } Object o = record.getValue(columnName); - if (o == null || o instanceof String) - { + if (o == null || o instanceof String) { String s = (String) o; - if (s == null || s.length() == 0) - { - if (!acceptNullValue) + if (s == null || s.length() == 0) { + if (!acceptNullValue) { iter.remove(); - } - else - { - if (!s.equalsIgnoreCase(value)) + } + } else { + if (!s.equalsIgnoreCase(value)) { iter.remove(); + } } } } } - protected void buildRecordIndices() - { + protected void buildRecordIndices() { // Build index on record ids. this.indexOnId.clear(); - for (int i = 0; i < this.records.length; i++) - { + for (int i = 0; i < this.records.length; i++) { Integer id = AVListImpl.getIntegerValue(this.records[i], "id"); - if (id != null) - { + if (id != null) { this.indexOnId.put(id, i); } } diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymTableHeader.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymTableHeader.java index ddd3b4c8ab..73959d51f5 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymTableHeader.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymTableHeader.java @@ -15,47 +15,39 @@ * @author dcollins * @version $Id: GeoSymTableHeader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymTableHeader -{ +public class GeoSymTableHeader { + protected String fileName; protected String description; // Use LinkedHashMap to acheive predictable ordering of table columns. protected LinkedHashMap columnMap; - public GeoSymTableHeader() - { + public GeoSymTableHeader() { this.columnMap = new LinkedHashMap(); } - public String getFileName() - { + public String getFileName() { return this.fileName; } - public void setFileName(String fileName) - { + public void setFileName(String fileName) { this.fileName = fileName; } - public String getDescription() - { + public String getDescription() { return this.description; } - public void setDescription(String description) - { + public void setDescription(String description) { this.description = description; } - public int getNumColumns() - { + public int getNumColumns() { return this.columnMap.size(); } - public boolean containsColumn(String name) - { - if (name == null) - { + public boolean containsColumn(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -64,10 +56,8 @@ public boolean containsColumn(String name) return this.columnMap.containsKey(name); } - public GeoSymColumn getColumn(String name) - { - if (name == null) - { + public GeoSymColumn getColumn(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,28 +66,24 @@ public GeoSymColumn getColumn(String name) return this.columnMap.get(name); } - public Set getColumnNames() - { + public Set getColumnNames() { return Collections.unmodifiableSet(this.columnMap.keySet()); } - public Collection getColumns() - { + public Collection getColumns() { return Collections.unmodifiableCollection(this.columnMap.values()); } - public void setColumns(Collection collection) - { + public void setColumns(Collection collection) { this.removeAllColumns(); - if (collection != null) + if (collection != null) { this.addAllColumns(collection); + } } - public void addColumn(GeoSymColumn column) - { - if (column == null) - { + public void addColumn(GeoSymColumn column) { + if (column == null) { String message = Logging.getMessage("nullValue.ColumnIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -106,25 +92,20 @@ public void addColumn(GeoSymColumn column) this.columnMap.put(column.getName(), column); } - public void addAllColumns(Collection collection) - { - if (collection == null) - { + public void addAllColumns(Collection collection) { + if (collection == null) { String message = Logging.getMessage("nullValue.CollectionIsNulln"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (GeoSymColumn col : collection) - { + for (GeoSymColumn col : collection) { this.addColumn(col); } } - public void removeColumn(GeoSymColumn column) - { - if (column == null) - { + public void removeColumn(GeoSymColumn column) { + if (column == null) { String message = Logging.getMessage("nullValue.ColumnIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -133,8 +114,7 @@ public void removeColumn(GeoSymColumn column) this.columnMap.remove(column.getName()); } - public void removeAllColumns() - { + public void removeAllColumns() { this.columnMap.clear(); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/formats/vpf/GeoSymTableReader.java b/src/gov/nasa/worldwind/formats/vpf/GeoSymTableReader.java index 6009c13ad1..126c412f8b 100644 --- a/src/gov/nasa/worldwind/formats/vpf/GeoSymTableReader.java +++ b/src/gov/nasa/worldwind/formats/vpf/GeoSymTableReader.java @@ -18,16 +18,13 @@ * @author dcollins * @version $Id: GeoSymTableReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoSymTableReader -{ - public GeoSymTableReader() - { +public class GeoSymTableReader { + + public GeoSymTableReader() { } - public boolean canRead(String filePath) - { - if (filePath == null) - { + public boolean canRead(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -36,15 +33,11 @@ public boolean canRead(String filePath) Object streamOrException = null; boolean result = false; - try - { + try { streamOrException = WWIO.getFileOrResourceAsStream(filePath, this.getClass()); result = (streamOrException != null && streamOrException instanceof InputStream); - } - finally - { - if (streamOrException instanceof InputStream) - { + } finally { + if (streamOrException instanceof InputStream) { WWIO.closeStream(streamOrException, filePath); } } @@ -52,39 +45,30 @@ public boolean canRead(String filePath) return result; } - public GeoSymTable read(String filePath) - { - if (filePath == null) - { + public GeoSymTable read(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return this.doRead(filePath); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("VPF.ExceptionAttemptingToReadTable", filePath); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - protected GeoSymTable doRead(String filePath) throws IOException - { + protected GeoSymTable doRead(String filePath) throws IOException { InputStream inputStream = null; GeoSymTable result = null; - try - { + try { inputStream = WWIO.openFileOrResourceStream(filePath, this.getClass()); result = this.readTable(filePath, inputStream); - } - finally - { + } finally { WWIO.closeStream(inputStream, filePath); } @@ -92,8 +76,7 @@ protected GeoSymTable doRead(String filePath) throws IOException } @SuppressWarnings({"UnusedDeclaration"}) - protected GeoSymTable readTable(String filePath, InputStream inputStream) - { + protected GeoSymTable readTable(String filePath, InputStream inputStream) { Scanner scanner = new Scanner(inputStream); // Read the table header. @@ -106,8 +89,7 @@ protected GeoSymTable readTable(String filePath, InputStream inputStream) return table; } - protected void readHeader(Scanner scanner, GeoSymTableHeader header) - { + protected void readHeader(Scanner scanner, GeoSymTableHeader header) { header.removeAllColumns(); String string = scanner.nextLine(); @@ -115,28 +97,27 @@ protected void readHeader(Scanner scanner, GeoSymTableHeader header) // Read the file name. String s = tokens[0].trim(); - if (s != null && !isEmpty(s)) + if (s != null && !isEmpty(s)) { header.setFileName(s); + } // Read the description. s = tokens[1].trim(); - if (s != null && !isEmpty(s)) + if (s != null && !isEmpty(s)) { header.setDescription(s); + } - while (!(string = scanner.nextLine()).equals(";")) - { + while (!(string = scanner.nextLine()).equals(";")) { GeoSymColumn col = this.readColumn(string); header.addColumn(col); } } - protected GeoSymColumn readColumn(String string) - { + protected GeoSymColumn readColumn(String string) { String[] tokens = string.split("[=,:]"); String s = tokens[0].trim(); - if (s == null) - { + if (s == null) { String message = Logging.getMessage("VPF.MissingColumnName"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -145,33 +126,36 @@ protected GeoSymColumn readColumn(String string) GeoSymColumn col = new GeoSymColumn(s); s = tokens[1].trim(); - if (s != null) + if (s != null) { col.setDataType(s); + } s = tokens[2].trim(); - if (s != null) + if (s != null) { col.setDataSize(s); + } s = tokens[3].trim(); - if (s != null) + if (s != null) { col.setDescription(s); + } s = tokens[4].trim(); - if (s != null && !isEmpty(s)) + if (s != null && !isEmpty(s)) { col.setCodeRef(s); + } return col; } - protected void readRecords(Scanner scanner, GeoSymTable table) - { + protected void readRecords(Scanner scanner, GeoSymTable table) { ArrayList list = new ArrayList(); - while (scanner.hasNextLine()) - { + while (scanner.hasNextLine()) { String s = scanner.nextLine().trim(); - if (s.length() == 0) + if (s.length() == 0) { continue; + } AVList record = new AVListImpl(); this.readRecord(s, table, record); @@ -184,34 +168,30 @@ protected void readRecords(Scanner scanner, GeoSymTable table) table.setRecords(array); } - protected void readRecord(String string, GeoSymTable table, AVList record) - { + protected void readRecord(String string, GeoSymTable table, AVList record) { Collection columns = table.getHeader().getColumns(); String[] tokens = string.split("[|]"); int index = 0; - for (GeoSymColumn col : columns) - { + for (GeoSymColumn col : columns) { String s = (index < tokens.length) ? tokens[index++].trim() : null; Object o = null; - if (col.getDataType().equalsIgnoreCase(GeoSymConstants.INTEGER)) - { - if (s != null) + if (col.getDataType().equalsIgnoreCase(GeoSymConstants.INTEGER)) { + if (s != null) { o = WWUtil.convertStringToInteger(s); - } - else if (col.getDataType().equalsIgnoreCase(GeoSymConstants.CHARACTER_STRING)) - { - if (s != null && s.length() > 0) + } + } else if (col.getDataType().equalsIgnoreCase(GeoSymConstants.CHARACTER_STRING)) { + if (s != null && s.length() > 0) { o = s; + } } record.setValue(col.getName(), o); } } - protected static boolean isEmpty(String s) - { + protected static boolean isEmpty(String s) { return s.length() == 0 || s.equals("-"); } } diff --git a/src/gov/nasa/worldwind/formats/vpf/NIMAConstants.java b/src/gov/nasa/worldwind/formats/vpf/NIMAConstants.java index 0346234eea..b9d3bbeb33 100644 --- a/src/gov/nasa/worldwind/formats/vpf/NIMAConstants.java +++ b/src/gov/nasa/worldwind/formats/vpf/NIMAConstants.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: NIMAConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface NIMAConstants -{ +public interface NIMAConstants { + // Reserved Directory Names // MIL-PRF-0089049, section 3.16 final String REFERENCE_LIBRARY = "rference"; diff --git a/src/gov/nasa/worldwind/formats/vpf/NIMAUtils.java b/src/gov/nasa/worldwind/formats/vpf/NIMAUtils.java index 03abbe7eee..0244382910 100644 --- a/src/gov/nasa/worldwind/formats/vpf/NIMAUtils.java +++ b/src/gov/nasa/worldwind/formats/vpf/NIMAUtils.java @@ -9,15 +9,13 @@ * @author dcollins * @version $Id: NIMAUtils.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NIMAUtils -{ - public static boolean isReferenceLibrary(String libraryName) - { +public class NIMAUtils { + + public static boolean isReferenceLibrary(String libraryName) { return libraryName.equalsIgnoreCase(NIMAConstants.REFERENCE_LIBRARY); } - public static boolean isDatabaseReferenceCoverage(String coverageName) - { + public static boolean isDatabaseReferenceCoverage(String coverageName) { return coverageName.equalsIgnoreCase(NIMAConstants.DATABASE_REFERENCE_COVERAGE); } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFBasicDataBufferFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFBasicDataBufferFactory.java index 2785c28979..bba65d87b3 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFBasicDataBufferFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFBasicDataBufferFactory.java @@ -14,191 +14,166 @@ * @author dcollins * @version $Id: VPFBasicDataBufferFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class VPFBasicDataBufferFactory implements VPFDataBufferFactory -{ +public abstract class VPFBasicDataBufferFactory implements VPFDataBufferFactory { + public static final short NO_VALUE_SHORT = -32768; // binary: 10000000 00000000 public static final int NO_VALUE_INT = -2147483648; // binary: 10000000 00000000 00000000 00000000 - public static class NullDataFactory extends VPFBasicDataBufferFactory - { - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public static class NullDataFactory extends VPFBasicDataBufferFactory { + + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new NullDataBuffer(); } } - public static class DateTimeDataFactory extends VPFBasicDataBufferFactory - { - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public static class DateTimeDataFactory extends VPFBasicDataBufferFactory { + + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new GenericDataBuffer(new DateTimeReader(), numRows); } } - public static class TripledIdDataFactory extends VPFBasicDataBufferFactory - { - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public static class TripledIdDataFactory extends VPFBasicDataBufferFactory { + + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new GenericDataBuffer(new TripletIdReader(), numRows); } } - public static class TextDataFactory extends VPFBasicDataBufferFactory - { + public static class TextDataFactory extends VPFBasicDataBufferFactory { + protected String charsetName; - public TextDataFactory(String charsetName) - { + public TextDataFactory(String charsetName) { this.charsetName = charsetName; } - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new TextDataBuffer(this.charsetName, numRows, elementsPerRow); } } - public static class ShortDataFactory extends VPFBasicDataBufferFactory - { - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public static class ShortDataFactory extends VPFBasicDataBufferFactory { + + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new ScalarDataBuffer(new ShortReader(), new IntAccessor(), new BufferFactory.ShortBufferFactory(), - numRows); + numRows); } } - public static class IntDataFactory extends VPFBasicDataBufferFactory - { - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public static class IntDataFactory extends VPFBasicDataBufferFactory { + + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new ScalarDataBuffer(new IntReader(), new IntAccessor(), new BufferFactory.IntBufferFactory(), - numRows); + numRows); } } - public static class FloatDataFactory extends VPFBasicDataBufferFactory - { - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public static class FloatDataFactory extends VPFBasicDataBufferFactory { + + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new ScalarDataBuffer(new FloatReader(), new DoubleAccessor(), new BufferFactory.FloatBufferFactory(), - numRows); + numRows); } } - public static class DoubleDataFactory extends VPFBasicDataBufferFactory - { - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public static class DoubleDataFactory extends VPFBasicDataBufferFactory { + + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new ScalarDataBuffer(new DoubleReader(), new DoubleAccessor(), - new BufferFactory.DoubleBufferFactory(), numRows); + new BufferFactory.DoubleBufferFactory(), numRows); } } - public abstract static class VecDataFactory extends VPFBasicDataBufferFactory - { + public abstract static class VecDataFactory extends VPFBasicDataBufferFactory { + protected int coordsPerElem; - public VecDataFactory(int coordsPerElem) - { + public VecDataFactory(int coordsPerElem) { this.coordsPerElem = coordsPerElem; } } - public static class ShortVecDataFactory extends VecDataFactory - { - public ShortVecDataFactory(int coordsPerElem) - { + public static class ShortVecDataFactory extends VecDataFactory { + + public ShortVecDataFactory(int coordsPerElem) { super(coordsPerElem); } - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new VecDataBuffer( - new ShortVecReader(this.coordsPerElem), - this.coordsPerElem, - new BufferFactory.ShortBufferFactory(), numRows, elementsPerRow); + new ShortVecReader(this.coordsPerElem), + this.coordsPerElem, + new BufferFactory.ShortBufferFactory(), numRows, elementsPerRow); } } - public static class IntVecDataFactory extends VecDataFactory - { - public IntVecDataFactory(int coordsPerElem) - { + public static class IntVecDataFactory extends VecDataFactory { + + public IntVecDataFactory(int coordsPerElem) { super(coordsPerElem); } - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new VecDataBuffer( - new IntVecReader(this.coordsPerElem), - this.coordsPerElem, - new BufferFactory.IntBufferFactory(), numRows, elementsPerRow); + new IntVecReader(this.coordsPerElem), + this.coordsPerElem, + new BufferFactory.IntBufferFactory(), numRows, elementsPerRow); } } - public static class FloatVecDataFactory extends VecDataFactory - { - public FloatVecDataFactory(int coordsPerElem) - { + public static class FloatVecDataFactory extends VecDataFactory { + + public FloatVecDataFactory(int coordsPerElem) { super(coordsPerElem); } - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new VecDataBuffer( - new FloatVecReader(this.coordsPerElem), - this.coordsPerElem, - new BufferFactory.FloatBufferFactory(), numRows, elementsPerRow); + new FloatVecReader(this.coordsPerElem), + this.coordsPerElem, + new BufferFactory.FloatBufferFactory(), numRows, elementsPerRow); } } - public static class DoubleVecDataFactory extends VecDataFactory - { - public DoubleVecDataFactory(int coordsPerElem) - { + public static class DoubleVecDataFactory extends VecDataFactory { + + public DoubleVecDataFactory(int coordsPerElem) { super(coordsPerElem); } - public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) - { + public VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow) { return new VecDataBuffer( - new DoubleVecReader(this.coordsPerElem), - this.coordsPerElem, - new BufferFactory.DoubleBufferFactory(), numRows, elementsPerRow); + new DoubleVecReader(this.coordsPerElem), + this.coordsPerElem, + new BufferFactory.DoubleBufferFactory(), numRows, elementsPerRow); } } - public static boolean isNoValueShort(short s) - { + public static boolean isNoValueShort(short s) { return s == NO_VALUE_SHORT; } - public static boolean isNoValueInt(int i) - { + public static boolean isNoValueInt(int i) { return i == NO_VALUE_INT; } - public static boolean isNoValueFloat(float f) - { + public static boolean isNoValueFloat(float f) { return Float.isNaN(f); } - public static boolean isNoValueDouble(double d) - { + public static boolean isNoValueDouble(double d) { return Double.isNaN(d); } - public static boolean isNoValueText(String s) - { - if (s == null) - { + public static boolean isNoValueText(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - switch (s.length()) - { + switch (s.length()) { case 1: return s.equals("-"); case 2: @@ -211,82 +186,69 @@ public static boolean isNoValueText(String s) //**************************************************************// //******************** Null Data *****************************// //**************************************************************// + protected static class NullDataBuffer implements VPFDataBuffer { - protected static class NullDataBuffer implements VPFDataBuffer - { - public Object get(int index) - { + public Object get(int index) { return null; } - public Object getBackingData() - { + public Object getBackingData() { return null; } - public boolean hasValue(int index) - { + public boolean hasValue(int index) { return false; } - public void read(ByteBuffer byteBuffer) - { + public void read(ByteBuffer byteBuffer) { } - public void read(ByteBuffer byteBuffer, int length) - { + public void read(ByteBuffer byteBuffer, int length) { } } //**************************************************************// //******************** Generic Data **************************// //**************************************************************// + protected interface GenericReader { - protected interface GenericReader - { Object read(ByteBuffer byteBuffer); } - protected static class GenericDataBuffer implements VPFDataBuffer - { + protected static class GenericDataBuffer implements VPFDataBuffer { + protected GenericReader reader; protected Object[] array; protected int position; - public GenericDataBuffer(GenericReader reader, int numRows) - { + public GenericDataBuffer(GenericReader reader, int numRows) { this.reader = reader; this.array = new Object[1 + numRows]; // Start with position 1 that the coordinate N cooresponds to row id N. this.position = 1; } - public Object get(int index) - { + public Object get(int index) { return this.array[index]; } - public Object getBackingData() - { + public Object getBackingData() { return this.array; } - public boolean hasValue(int index) - { + public boolean hasValue(int index) { // For Date/Time data, entry is null when space character filled. // For Triplet ID data, entry is null when type byte = 0. return this.get(index) != null; } - public void read(ByteBuffer byteBuffer) - { + public void read(ByteBuffer byteBuffer) { Object o = this.reader.read(byteBuffer); this.array[this.position] = o; this.position++; } - public void read(ByteBuffer byteBuffer, int length) - { + public void read(ByteBuffer byteBuffer, int length) { // Intentionally ignoring the length parameter. Generic fields can never be variable length. this.read(byteBuffer); } @@ -295,18 +257,17 @@ public void read(ByteBuffer byteBuffer, int length) //**************************************************************// //******************** Date/Time Data ************************// //**************************************************************// + protected static class DateTimeReader implements GenericReader { - protected static class DateTimeReader implements GenericReader - { protected TextReader textReader = new TextReader("US-ASCII"); - public Object read(ByteBuffer byteBuffer) - { + public Object read(ByteBuffer byteBuffer) { // TODO: correct VPF date parsing. CharBuffer buffer = this.textReader.read(byteBuffer, 20); - if (buffer.length() == 0) + if (buffer.length() == 0) { return null; + } //try //{ @@ -319,32 +280,34 @@ public Object read(ByteBuffer byteBuffer) // String message = Logging.getMessage("generic.ConversionError", s); // Logging.logger().severe(message); //} - return null; } - protected static String makeDatePattern(String dateText) - { + protected static String makeDatePattern(String dateText) { StringBuilder sb = new StringBuilder(); int length = dateText.length(); sb.append("yyyy"); - if (length > 4) + if (length > 4) { sb.append("MM"); - if (length > 6) + } + if (length > 6) { sb.append("dd"); + } - if (length > 8) + if (length > 8) { sb.append("HHmmss"); + } - if (length > 14) + if (length > 14) { sb.append(dateText, 14, 15); // Append the separator character. - - if (length > 16) + } + if (length > 16) { sb.append("ZZZZ"); - else if (length == 16) + } else if (length == 16) { sb.append("Z"); + } return sb.toString(); } @@ -353,14 +316,13 @@ else if (length == 16) //**************************************************************// //******************** Triplet ID Data ***********************// //**************************************************************// + protected static class TripletIdReader implements GenericReader { - protected static class TripletIdReader implements GenericReader - { - public Object read(ByteBuffer byteBuffer) - { + public Object read(ByteBuffer byteBuffer) { int type = byteBuffer.get(); - if (type == 0) + if (type == 0) { return null; + } int id = readId(byteBuffer, type >> 6); int tileId = readId(byteBuffer, type >> 4); @@ -369,16 +331,14 @@ public Object read(ByteBuffer byteBuffer) return new VPFTripletId(id, tileId, extId); } - protected static int readId(ByteBuffer buffer, int length) - { + protected static int readId(ByteBuffer buffer, int length) { // Bit Count -> Number Bits In Field // 0 0 // 1 8 // 2 16 // 3 32 - switch (length & 3) - { + switch (length & 3) { case 0: return -1; case 1: @@ -396,36 +356,28 @@ protected static int readId(ByteBuffer buffer, int length) //**************************************************************// //******************** Text Data *****************************// //**************************************************************// + protected static class TextReader { - protected static class TextReader - { protected CharsetDecoder decoder; - public TextReader(String charsetName) - { - try - { + public TextReader(String charsetName) { + try { Charset cs = Charset.forName(charsetName); this.decoder = cs.newDecoder(); this.decoder.onMalformedInput(CodingErrorAction.REPLACE); this.decoder.onUnmappableCharacter(CodingErrorAction.REPLACE); - } - catch (IllegalCharsetNameException e) - { + } catch (IllegalCharsetNameException e) { String message = Logging.getMessage("generic.InvalidCharsetName", charsetName); Logging.logger().severe(message); throw new IllegalArgumentException(message); - } - catch (UnsupportedCharsetException e) - { + } catch (UnsupportedCharsetException e) { String message = Logging.getMessage("generic.InvalidCharsetName", charsetName); Logging.logger().severe(message); throw new IllegalArgumentException(message); } } - public void read(ByteBuffer byteBuffer, int length, CharBuffer outBuffer) - { + public void read(ByteBuffer byteBuffer, int length, CharBuffer outBuffer) { int nextPosition = byteBuffer.position() + length; int limit = byteBuffer.limit(); byteBuffer.limit(nextPosition); @@ -439,23 +391,21 @@ public void read(ByteBuffer byteBuffer, int length, CharBuffer outBuffer) outBuffer.flip(); } - public CharBuffer read(ByteBuffer byteBuffer, int length) - { + public CharBuffer read(ByteBuffer byteBuffer, int length) { CharBuffer charBuffer = CharBuffer.allocate(length); this.read(byteBuffer, length, charBuffer); return charBuffer; } } - protected static class TextDataBuffer implements VPFDataBuffer - { + protected static class TextDataBuffer implements VPFDataBuffer { + protected int elementsPerRow; protected TextReader reader; protected CompoundStringBuilder buffer; protected CharBuffer tmpBuffer; - public TextDataBuffer(String charsetName, int numRows, int elementsPerRow) - { + public TextDataBuffer(String charsetName, int numRows, int elementsPerRow) { int stringLength = Math.max(1, elementsPerRow); this.elementsPerRow = elementsPerRow; @@ -465,41 +415,34 @@ public TextDataBuffer(String charsetName, int numRows, int elementsPerRow) this.buffer.append(""); } - public Object get(int index) - { + public Object get(int index) { String s = this.buffer.substring(index); return s != null ? s.trim() : null; } - public Object getBackingData() - { + public Object getBackingData() { return this.buffer; } - public boolean hasValue(int index) - { + public boolean hasValue(int index) { // Variable length text is null if it has zero length. - if (this.elementsPerRow < 0) - { + if (this.elementsPerRow < 0) { return this.buffer.substringLength(index) > 0; - } - // Fixed length text is null if it equals "N/A". - else - { + } // Fixed length text is null if it equals "N/A". + else { return !isNoValueText(this.buffer.substring(index).trim()); } } - public void read(ByteBuffer byteBuffer) - { + public void read(ByteBuffer byteBuffer) { int length = byteBuffer.getInt(); this.read(byteBuffer, length); } - public void read(ByteBuffer byteBuffer, int length) - { - if (this.tmpBuffer == null || this.tmpBuffer.capacity() < length) + public void read(ByteBuffer byteBuffer, int length) { + if (this.tmpBuffer == null || this.tmpBuffer.capacity() < length) { this.tmpBuffer = WWBufferUtil.newCharBuffer(length, true); + } this.tmpBuffer.clear(); this.tmpBuffer.limit(length); @@ -511,106 +454,94 @@ public void read(ByteBuffer byteBuffer, int length) //**************************************************************// //******************** Scalar Data ***************************// //**************************************************************// + protected interface ScalarReader { - protected interface ScalarReader - { double read(ByteBuffer byteBuffer); } - protected interface ScalarAccessor - { + protected interface ScalarAccessor { + Object get(BufferWrapper bufferWrapper, int index); boolean hasValue(BufferWrapper bufferWrapper, int index); } - protected static class ShortReader implements ScalarReader - { - public double read(ByteBuffer byteBuffer) - { + protected static class ShortReader implements ScalarReader { + + public double read(ByteBuffer byteBuffer) { return byteBuffer.getShort(); } } - protected static class IntReader implements ScalarReader - { - public double read(ByteBuffer byteBuffer) - { + protected static class IntReader implements ScalarReader { + + public double read(ByteBuffer byteBuffer) { return byteBuffer.getInt(); } } - protected static class FloatReader implements ScalarReader - { - public double read(ByteBuffer byteBuffer) - { + protected static class FloatReader implements ScalarReader { + + public double read(ByteBuffer byteBuffer) { return byteBuffer.getFloat(); } } - protected static class DoubleReader implements ScalarReader - { - public double read(ByteBuffer byteBuffer) - { + protected static class DoubleReader implements ScalarReader { + + public double read(ByteBuffer byteBuffer) { return byteBuffer.getDouble(); } } - protected static class ShortAccessor extends IntAccessor - { - public boolean hasValue(BufferWrapper bufferWrapper, int index) - { + protected static class ShortAccessor extends IntAccessor { + + public boolean hasValue(BufferWrapper bufferWrapper, int index) { // Scalar shorts are null when equal to "no value" 16 bit pattern. return !isNoValueShort((short) bufferWrapper.getInt(index)); } } - protected static class IntAccessor implements ScalarAccessor - { - public Object get(BufferWrapper bufferWrapper, int index) - { + protected static class IntAccessor implements ScalarAccessor { + + public Object get(BufferWrapper bufferWrapper, int index) { return bufferWrapper.getInt(index); } - public boolean hasValue(BufferWrapper bufferWrapper, int index) - { + public boolean hasValue(BufferWrapper bufferWrapper, int index) { // Scalar ints are null when equal to "no value" 32 bit pattern. return !isNoValueInt(bufferWrapper.getInt(index)); } } - protected static class FloatAccessor extends DoubleAccessor - { - public boolean hasValue(BufferWrapper bufferWrapper, int index) - { + protected static class FloatAccessor extends DoubleAccessor { + + public boolean hasValue(BufferWrapper bufferWrapper, int index) { // Scalar floats are null when equal to the 32 bit floating point NaN. return !isNoValueFloat((float) bufferWrapper.getDouble(index)); } } - protected static class DoubleAccessor implements ScalarAccessor - { - public Object get(BufferWrapper bufferWrapper, int index) - { + protected static class DoubleAccessor implements ScalarAccessor { + + public Object get(BufferWrapper bufferWrapper, int index) { return bufferWrapper.getDouble(index); } - public boolean hasValue(BufferWrapper bufferWrapper, int index) - { + public boolean hasValue(BufferWrapper bufferWrapper, int index) { // Scalar doubles are null when equal to the 64 bit floating point NaN. return !isNoValueDouble(bufferWrapper.getDouble(index)); } } - protected static class ScalarDataBuffer implements VPFDataBuffer - { + protected static class ScalarDataBuffer implements VPFDataBuffer { + protected ScalarReader reader; protected ScalarAccessor accessor; protected BufferWrapper buffer; protected int position; - public ScalarDataBuffer(ScalarReader reader, ScalarAccessor accessor, BufferFactory bufferFactory, int numRows) - { + public ScalarDataBuffer(ScalarReader reader, ScalarAccessor accessor, BufferFactory bufferFactory, int numRows) { this.reader = reader; this.accessor = accessor; this.buffer = bufferFactory.newBuffer(1 + numRows); @@ -618,30 +549,25 @@ public ScalarDataBuffer(ScalarReader reader, ScalarAccessor accessor, BufferFact this.position = 1; } - public Object get(int index) - { + public Object get(int index) { return this.accessor.get(this.buffer, index); } - public Object getBackingData() - { + public Object getBackingData() { return this.buffer; } - public boolean hasValue(int index) - { + public boolean hasValue(int index) { return this.accessor.hasValue(this.buffer, index); } - public void read(ByteBuffer byteBuffer) - { + public void read(ByteBuffer byteBuffer) { double d = this.reader.read(byteBuffer); this.buffer.putDouble(this.position, d); this.position++; } - public void read(ByteBuffer byteBuffer, int length) - { + public void read(ByteBuffer byteBuffer, int length) { // Intentionally ignoring the length parameter. Numeric fields can never be variable length. this.read(byteBuffer); } @@ -650,44 +576,37 @@ public void read(ByteBuffer byteBuffer, int length) //**************************************************************// //******************** Vector Data ***************************// //**************************************************************// + protected interface VecReader { - protected interface VecReader - { int getCoordsPerElem(); VecBuffer read(ByteBuffer byteBuffer, int length); } - protected abstract static class AbstractVecReader implements VecReader - { + protected abstract static class AbstractVecReader implements VecReader { + protected int coordsPerElem; protected int bytesPerCoord; - public AbstractVecReader(int coordsPerElem, int bytesPerCoord) - { + public AbstractVecReader(int coordsPerElem, int bytesPerCoord) { this.coordsPerElem = coordsPerElem; this.bytesPerCoord = bytesPerCoord; } - public int getCoordsPerElem() - { + public int getCoordsPerElem() { return this.coordsPerElem; } - public VecBuffer read(ByteBuffer byteBuffer, int length) - { + public VecBuffer read(ByteBuffer byteBuffer, int length) { VecBuffer vecBuffer = null; int prevLimit = byteBuffer.limit(); int limit = byteBuffer.position() + (this.coordsPerElem * this.bytesPerCoord * length); - try - { + try { byteBuffer.limit(limit); BufferWrapper newBuffer = this.doRead(byteBuffer); vecBuffer = new VecBuffer(this.coordsPerElem, newBuffer); - } - finally - { + } finally { byteBuffer.limit(prevLimit); byteBuffer.position(limit); } @@ -698,17 +617,15 @@ public VecBuffer read(ByteBuffer byteBuffer, int length) protected abstract BufferWrapper doRead(ByteBuffer byteBuffer); } - protected static class ShortVecReader extends AbstractVecReader - { + protected static class ShortVecReader extends AbstractVecReader { + private short[] tmpBuffer; - public ShortVecReader(int coordsPerElem) - { + public ShortVecReader(int coordsPerElem) { super(coordsPerElem, (Short.SIZE / 8)); } - protected BufferWrapper doRead(ByteBuffer byteBuffer) - { + protected BufferWrapper doRead(ByteBuffer byteBuffer) { ShortBuffer shortBuffer = byteBuffer.asShortBuffer(); // Replace null (NaN) values in partially null coordinates with 0. Because these vector coordinate buffers @@ -716,29 +633,30 @@ protected BufferWrapper doRead(ByteBuffer byteBuffer) // NaN coordinate in the vectors. We must also detect when a vector is completely null, and enter an empty // sub-buffer in this case. This is necessary because we are eliminating the NaN signal which the data // consumer would ordinarily use to detect null coordinates. - if (this.replaceNaN(shortBuffer, (short) 0) <= 0) + if (this.replaceNaN(shortBuffer, (short) 0) <= 0) { return null; + } return new BufferWrapper.ShortBufferWrapper(shortBuffer); } - protected int replaceNaN(ShortBuffer shortBuffer, short value) - { + protected int replaceNaN(ShortBuffer shortBuffer, short value) { int length = shortBuffer.remaining(); int numValues = 0; - if (this.tmpBuffer == null || this.tmpBuffer.length < shortBuffer.remaining()) + if (this.tmpBuffer == null || this.tmpBuffer.length < shortBuffer.remaining()) { this.tmpBuffer = new short[length]; + } shortBuffer.get(this.tmpBuffer, 0, length); shortBuffer.flip(); - for (int i = 0; i < length; i++) - { - if (isNoValueShort(this.tmpBuffer[i])) + for (int i = 0; i < length; i++) { + if (isNoValueShort(this.tmpBuffer[i])) { this.tmpBuffer[i] = value; - else + } else { numValues++; + } } shortBuffer.put(this.tmpBuffer, 0, length); @@ -748,17 +666,15 @@ protected int replaceNaN(ShortBuffer shortBuffer, short value) } } - protected static class IntVecReader extends AbstractVecReader - { + protected static class IntVecReader extends AbstractVecReader { + private int[] tmpBuffer; - public IntVecReader(int coordsPerElem) - { + public IntVecReader(int coordsPerElem) { super(coordsPerElem, (Integer.SIZE / 8)); } - protected BufferWrapper doRead(ByteBuffer byteBuffer) - { + protected BufferWrapper doRead(ByteBuffer byteBuffer) { IntBuffer intBuffer = byteBuffer.asIntBuffer(); // Replace null (NaN) values in partially null coordinates with 0. Because these vector coordinate buffers @@ -766,29 +682,30 @@ protected BufferWrapper doRead(ByteBuffer byteBuffer) // NaN coordinate in the vectors. We must also detect when a vector is completely null, and enter an empty // sub-buffer in this case. This is necessary because we are eliminating the NaN signal which the data // consumer would ordinarily use to detect null coordinates. - if (this.replaceNaN(intBuffer, 0) <= 0) + if (this.replaceNaN(intBuffer, 0) <= 0) { return null; + } return new BufferWrapper.IntBufferWrapper(intBuffer); } - protected int replaceNaN(IntBuffer intBuffer, int value) - { + protected int replaceNaN(IntBuffer intBuffer, int value) { int length = intBuffer.remaining(); int numValues = 0; - if (this.tmpBuffer == null || this.tmpBuffer.length < intBuffer.remaining()) + if (this.tmpBuffer == null || this.tmpBuffer.length < intBuffer.remaining()) { this.tmpBuffer = new int[length]; + } intBuffer.get(this.tmpBuffer, 0, length); intBuffer.flip(); - for (int i = 0; i < length; i++) - { - if (isNoValueInt(this.tmpBuffer[i])) + for (int i = 0; i < length; i++) { + if (isNoValueInt(this.tmpBuffer[i])) { this.tmpBuffer[i] = value; - else + } else { numValues++; + } } intBuffer.put(this.tmpBuffer, 0, length); @@ -798,17 +715,15 @@ protected int replaceNaN(IntBuffer intBuffer, int value) } } - protected static class FloatVecReader extends AbstractVecReader - { + protected static class FloatVecReader extends AbstractVecReader { + private float[] tmpBuffer; - public FloatVecReader(int coordsPerElem) - { + public FloatVecReader(int coordsPerElem) { super(coordsPerElem, (Float.SIZE / 8)); } - protected BufferWrapper doRead(ByteBuffer byteBuffer) - { + protected BufferWrapper doRead(ByteBuffer byteBuffer) { FloatBuffer floatBuffer = byteBuffer.asFloatBuffer(); // Replace null (NaN) values in partially null coordinates with 0. Because these vector coordinate buffers @@ -816,29 +731,30 @@ protected BufferWrapper doRead(ByteBuffer byteBuffer) // NaN coordinate in the vectors. We must also detect when a vector is completely null, and enter an empty // sub-buffer in this case. This is necessary because we are eliminating the NaN signal which the data // consumer would ordinarily use to detect null coordinates. - if (this.replaceNaN(floatBuffer, 0f) <= 0) + if (this.replaceNaN(floatBuffer, 0f) <= 0) { return null; + } return new BufferWrapper.FloatBufferWrapper(floatBuffer); } - protected int replaceNaN(FloatBuffer floatBuffer, float value) - { + protected int replaceNaN(FloatBuffer floatBuffer, float value) { int length = floatBuffer.remaining(); int numValues = 0; - if (this.tmpBuffer == null || this.tmpBuffer.length < floatBuffer.remaining()) + if (this.tmpBuffer == null || this.tmpBuffer.length < floatBuffer.remaining()) { this.tmpBuffer = new float[length]; + } floatBuffer.get(this.tmpBuffer, 0, length); floatBuffer.flip(); - for (int i = 0; i < length; i++) - { - if (isNoValueFloat(this.tmpBuffer[i])) + for (int i = 0; i < length; i++) { + if (isNoValueFloat(this.tmpBuffer[i])) { this.tmpBuffer[i] = value; - else + } else { numValues++; + } } floatBuffer.put(this.tmpBuffer, 0, length); @@ -848,17 +764,15 @@ protected int replaceNaN(FloatBuffer floatBuffer, float value) } } - protected static class DoubleVecReader extends AbstractVecReader - { + protected static class DoubleVecReader extends AbstractVecReader { + private double[] tmpBuffer; - public DoubleVecReader(int coordsPerElem) - { + public DoubleVecReader(int coordsPerElem) { super(coordsPerElem, Double.SIZE / 8); } - protected BufferWrapper doRead(ByteBuffer byteBuffer) - { + protected BufferWrapper doRead(ByteBuffer byteBuffer) { DoubleBuffer doubleBuffer = byteBuffer.asDoubleBuffer(); // Replace null (NaN) values in partially null coordinates with 0. Because these vector coordinate buffers @@ -866,29 +780,30 @@ protected BufferWrapper doRead(ByteBuffer byteBuffer) // NaN coordinate in the vectors. We must also detect when a vector is completely null, and enter an empty // sub-buffer in this case. This is necessary because we are eliminating the NaN signal which the data // consumer would ordinarily use to detect null coordinates. - if (this.replaceNaN(doubleBuffer, 0d) <= 0) + if (this.replaceNaN(doubleBuffer, 0d) <= 0) { return null; + } return new BufferWrapper.DoubleBufferWrapper(doubleBuffer); } - protected int replaceNaN(DoubleBuffer doubleBuffer, double value) - { + protected int replaceNaN(DoubleBuffer doubleBuffer, double value) { int length = doubleBuffer.remaining(); int numValues = 0; - if (this.tmpBuffer == null || this.tmpBuffer.length < doubleBuffer.remaining()) + if (this.tmpBuffer == null || this.tmpBuffer.length < doubleBuffer.remaining()) { this.tmpBuffer = new double[length]; + } doubleBuffer.get(this.tmpBuffer, 0, length); doubleBuffer.flip(); - for (int i = 0; i < length; i++) - { - if (isNoValueDouble(this.tmpBuffer[i])) + for (int i = 0; i < length; i++) { + if (isNoValueDouble(this.tmpBuffer[i])) { this.tmpBuffer[i] = value; - else + } else { numValues++; + } } doubleBuffer.put(this.tmpBuffer, 0, length); @@ -898,14 +813,13 @@ protected int replaceNaN(DoubleBuffer doubleBuffer, double value) } } - protected static class VecDataBuffer implements VPFDataBuffer - { + protected static class VecDataBuffer implements VPFDataBuffer { + protected VecReader reader; protected VecBufferSequence buffer; public VecDataBuffer(VecReader reader, int coordsPerElem, BufferFactory bufferFactory, int numRows, - int elementsPerRow) - { + int elementsPerRow) { int bufferLength = Math.max(1, elementsPerRow); BufferWrapper buffer = bufferFactory.newBuffer((1 + numRows) * coordsPerElem * bufferLength); @@ -915,18 +829,15 @@ public VecDataBuffer(VecReader reader, int coordsPerElem, BufferFactory bufferFa this.buffer.append(VecBuffer.emptyVecBuffer(coordsPerElem)); } - public Object get(int index) - { + public Object get(int index) { return this.buffer.subBuffer(index); } - public Object getBackingData() - { + public Object getBackingData() { return this.buffer; } - public boolean hasValue(int index) - { + public boolean hasValue(int index) { // Variable length vector is null if it has zero length. Fixed length vector is null if all coordinates are // null, in which case the sub-buffer entry will also have zero length because we have detected this case // at read time. Early detection and handling of null coordinates is necessary because we replace null (NaN) @@ -935,22 +846,17 @@ public boolean hasValue(int index) return this.buffer.subBufferSize(index) > 0; } - public void read(ByteBuffer byteBuffer) - { + public void read(ByteBuffer byteBuffer) { int length = byteBuffer.getInt(); this.read(byteBuffer, length); } - public void read(ByteBuffer byteBuffer, int length) - { + public void read(ByteBuffer byteBuffer, int length) { VecBuffer vecBuffer = this.reader.read(byteBuffer, length); - if (vecBuffer != null) - { + if (vecBuffer != null) { this.buffer.append(vecBuffer); - } - else - { + } else { this.buffer.append(VecBuffer.emptyVecBuffer(this.buffer.getCoordsPerVec())); } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFBasicFeatureClassFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFBasicFeatureClassFactory.java index 6d7f1649d0..f08fab0f31 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFBasicFeatureClassFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFBasicFeatureClassFactory.java @@ -15,43 +15,37 @@ * @author dcollins * @version $Id: VPFBasicFeatureClassFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFBasicFeatureClassFactory implements VPFFeatureClassFactory -{ - /** Constructs an instance of a VPFBasicCoverageFactory, but otherwise does nothing. */ - public VPFBasicFeatureClassFactory() - { +public class VPFBasicFeatureClassFactory implements VPFFeatureClassFactory { + + /** + * Constructs an instance of a VPFBasicCoverageFactory, but otherwise does nothing. + */ + public VPFBasicFeatureClassFactory() { } - public VPFFeatureClass createFromSchema(VPFCoverage coverage, VPFFeatureClassSchema schema) - { - if (coverage == null) - { + public VPFFeatureClass createFromSchema(VPFCoverage coverage, VPFFeatureClassSchema schema) { + if (coverage == null) { String message = Logging.getMessage("nullValue.CoverageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (schema == null) - { + if (schema == null) { String message = Logging.getMessage("nullValue.SchemaIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return this.doCreateFromSchema(coverage, schema); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileReading", - coverage.getFilePath() + File.separator + schema.getClassName()); + coverage.getFilePath() + File.separator + schema.getClassName()); throw new WWRuntimeException(message, e); } } - protected VPFFeatureClass doCreateFromSchema(VPFCoverage coverage, VPFFeatureClassSchema schema) throws IOException - { + protected VPFFeatureClass doCreateFromSchema(VPFCoverage coverage, VPFFeatureClassSchema schema) throws IOException { // DIGEST Part 2, Annex C.2.2.2.2.3.a: Simple feature classes. // A simple feature class consists of a (logically) single primitive table and a single simple feature table. // There are four subtypes of the simple feature class in VRF: @@ -70,8 +64,9 @@ protected VPFFeatureClass doCreateFromSchema(VPFCoverage coverage, VPFFeatureCla // 'all text with HEIGHT > 0.5'. VPFFeatureClass cls = this.doCreateFeatureClass(coverage, schema); - if (cls != null) + if (cls != null) { return cls; + } cls = this.doCreateFromFeatureType(coverage, schema); this.initFeatureClass(cls); @@ -80,15 +75,12 @@ protected VPFFeatureClass doCreateFromSchema(VPFCoverage coverage, VPFFeatureCla } @SuppressWarnings({"UnusedDeclaration"}) - protected VPFFeatureClass doCreateFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) - { + protected VPFFeatureClass doCreateFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) { return null; } - protected VPFFeatureClass doCreateFromFeatureType(VPFCoverage coverage, VPFFeatureClassSchema schema) - { - switch (schema.getType()) - { + protected VPFFeatureClass doCreateFromFeatureType(VPFCoverage coverage, VPFFeatureClassSchema schema) { + switch (schema.getType()) { case POINT: return this.createPointFeatureClass(coverage, schema); case LINE: @@ -104,11 +96,9 @@ protected VPFFeatureClass doCreateFromFeatureType(VPFCoverage coverage, VPFFeatu } } - protected void initFeatureClass(VPFFeatureClass cls) - { + protected void initFeatureClass(VPFFeatureClass cls) { VPFRelation[] rels = cls.getCoverage().getFeatureClassRelations(cls.getClassName()); - if (rels != null) - { + if (rels != null) { cls.setRelations(rels); } } @@ -116,107 +106,83 @@ protected void initFeatureClass(VPFFeatureClass cls) //**************************************************************// //******************** Feature Class Assembly ****************// //**************************************************************// - - protected VPFFeatureClass createPointFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) - { + protected VPFFeatureClass createPointFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) { return new VPFFeatureClass(coverage, schema, - this.getJoinTableName(coverage, schema, VPFConstants.POINT_JOIN_TABLE), - this.getPointFeaturePrimitiveTable(coverage, schema)) - { - public Collection createFeatures(VPFFeatureFactory factory) - { + this.getJoinTableName(coverage, schema, VPFConstants.POINT_JOIN_TABLE), + this.getPointFeaturePrimitiveTable(coverage, schema)) { + public Collection createFeatures(VPFFeatureFactory factory) { return factory.createPointFeatures(this); } - public Collection createFeatureSymbols(VPFSymbolFactory factory) - { + public Collection createFeatureSymbols(VPFSymbolFactory factory) { return factory.createPointSymbols(this); } }; } - protected VPFFeatureClass createLineFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) - { + protected VPFFeatureClass createLineFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) { return new VPFFeatureClass(coverage, schema, - this.getJoinTableName(coverage, schema, VPFConstants.LINE_JOIN_TABLE), - VPFConstants.EDGE_PRIMITIVE_TABLE) - { - public Collection createFeatures(VPFFeatureFactory factory) - { + this.getJoinTableName(coverage, schema, VPFConstants.LINE_JOIN_TABLE), + VPFConstants.EDGE_PRIMITIVE_TABLE) { + public Collection createFeatures(VPFFeatureFactory factory) { return factory.createLineFeatures(this); } - public Collection createFeatureSymbols(VPFSymbolFactory factory) - { + public Collection createFeatureSymbols(VPFSymbolFactory factory) { return factory.createLineSymbols(this); } }; } - protected VPFFeatureClass createAreaFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) - { + protected VPFFeatureClass createAreaFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) { return new VPFFeatureClass(coverage, schema, - this.getJoinTableName(coverage, schema, VPFConstants.AREA_JOIN_TABLE), - VPFConstants.FACE_PRIMITIVE_TABLE) - { - public Collection createFeatures(VPFFeatureFactory factory) - { + this.getJoinTableName(coverage, schema, VPFConstants.AREA_JOIN_TABLE), + VPFConstants.FACE_PRIMITIVE_TABLE) { + public Collection createFeatures(VPFFeatureFactory factory) { return factory.createAreaFeatures(this); } - public Collection createFeatureSymbols(VPFSymbolFactory factory) - { + public Collection createFeatureSymbols(VPFSymbolFactory factory) { return factory.createAreaSymbols(this); } }; } - protected VPFFeatureClass createTextFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) - { + protected VPFFeatureClass createTextFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) { return new VPFFeatureClass(coverage, schema, - this.getJoinTableName(coverage, schema, VPFConstants.TEXT_FEATURE_JOIN_TABLE), - VPFConstants.TEXT_PRIMITIVE_TABLE) - { - public Collection createFeatures(VPFFeatureFactory factory) - { + this.getJoinTableName(coverage, schema, VPFConstants.TEXT_FEATURE_JOIN_TABLE), + VPFConstants.TEXT_PRIMITIVE_TABLE) { + public Collection createFeatures(VPFFeatureFactory factory) { return factory.createTextFeatures(this); } - public Collection createFeatureSymbols(VPFSymbolFactory factory) - { + public Collection createFeatureSymbols(VPFSymbolFactory factory) { return factory.createTextSymbols(this); } }; } - protected VPFFeatureClass createComplexFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) - { + protected VPFFeatureClass createComplexFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) { return new VPFFeatureClass(coverage, schema, - this.getJoinTableName(coverage, schema, VPFConstants.TEXT_FEATURE_JOIN_TABLE), null) - { - public Collection createFeatures(VPFFeatureFactory factory) - { + this.getJoinTableName(coverage, schema, VPFConstants.TEXT_FEATURE_JOIN_TABLE), null) { + public Collection createFeatures(VPFFeatureFactory factory) { return factory.createComplexFeatures(this); } - public Collection createFeatureSymbols(VPFSymbolFactory factory) - { + public Collection createFeatureSymbols(VPFSymbolFactory factory) { return factory.createComplexSymbols(this); } }; } - protected VPFFeatureClass createUnknownFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) - { + protected VPFFeatureClass createUnknownFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema) { return new VPFFeatureClass(coverage, schema, null, null); } //**************************************************************// //******************** Utility Methods ***********************// //**************************************************************// - - protected String getJoinTableName(VPFCoverage coverage, VPFFeatureClassSchema schema, String suffix) - { + protected String getJoinTableName(VPFCoverage coverage, VPFFeatureClassSchema schema, String suffix) { StringBuilder sb = new StringBuilder(); sb.append(schema.getClassName()); sb.append(suffix); @@ -227,24 +193,23 @@ protected String getJoinTableName(VPFCoverage coverage, VPFFeatureClassSchema sc return file.exists() ? tableName : null; } - protected String getPointFeaturePrimitiveTable(VPFCoverage coverage, VPFFeatureClassSchema schema) - { + protected String getPointFeaturePrimitiveTable(VPFCoverage coverage, VPFFeatureClassSchema schema) { String primitiveTableName = null; VPFRelation[] rels = coverage.getFeatureClassRelations(schema.getClassName()); - if (rels != null) - { - for (VPFRelation rel : rels) - { - if (rel.getTable2().equalsIgnoreCase(VPFConstants.NODE_PRIMITIVE_TABLE)) + if (rels != null) { + for (VPFRelation rel : rels) { + if (rel.getTable2().equalsIgnoreCase(VPFConstants.NODE_PRIMITIVE_TABLE)) { primitiveTableName = VPFConstants.NODE_PRIMITIVE_TABLE; - else if (rel.getTable2().equalsIgnoreCase(VPFConstants.ENTITY_NODE_PRIMITIVE_TABLE)) + } else if (rel.getTable2().equalsIgnoreCase(VPFConstants.ENTITY_NODE_PRIMITIVE_TABLE)) { primitiveTableName = VPFConstants.ENTITY_NODE_PRIMITIVE_TABLE; - else if (rel.getTable2().equalsIgnoreCase(VPFConstants.CONNECTED_NODE_PRIMITIVE_TABLE)) + } else if (rel.getTable2().equalsIgnoreCase(VPFConstants.CONNECTED_NODE_PRIMITIVE_TABLE)) { primitiveTableName = VPFConstants.CONNECTED_NODE_PRIMITIVE_TABLE; + } - if (primitiveTableName != null) + if (primitiveTableName != null) { break; + } } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFBasicFeatureFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFBasicFeatureFactory.java index 86c1b84f50..8ea1424946 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFBasicFeatureFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFBasicFeatureFactory.java @@ -15,8 +15,8 @@ * @author dcollins * @version $Id: VPFBasicFeatureFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFBasicFeatureFactory implements VPFFeatureFactory -{ +public class VPFBasicFeatureFactory implements VPFFeatureFactory { + private VPFTile tile; private VPFPrimitiveData primitiveData; @@ -25,30 +25,25 @@ public class VPFBasicFeatureFactory implements VPFFeatureFactory * gov.nasa.worldwind.formats.vpf.VPFTile} and {@link gov.nasa.worldwind.formats.vpf.VPFPrimitiveData}. The * primitive data must contain information for at least those features found in the specified tile. * - * @param tile the tile which defines the geographic region to construct features for. + * @param tile the tile which defines the geographic region to construct features for. * @param primitiveData the primitive data describing feature information for the geographic region defined by the - * tile. + * tile. */ - public VPFBasicFeatureFactory(VPFTile tile, VPFPrimitiveData primitiveData) - { + public VPFBasicFeatureFactory(VPFTile tile, VPFPrimitiveData primitiveData) { this.tile = tile; this.primitiveData = primitiveData; } - public VPFTile getTile() - { + public VPFTile getTile() { return this.tile; } - public VPFPrimitiveData getPrimitiveData() - { + public VPFPrimitiveData getPrimitiveData() { return this.primitiveData; } - public Collection createPointFeatures(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createPointFeatures(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -57,10 +52,8 @@ public Collection createPointFeatures(VPFFeatureClass feat return this.doCreateSimpleFeatures(featureClass); } - public Collection createLineFeatures(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createLineFeatures(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -69,10 +62,8 @@ public Collection createLineFeatures(VPFFeatureClass featu return this.doCreateSimpleFeatures(featureClass); } - public Collection createAreaFeatures(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createAreaFeatures(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -81,10 +72,8 @@ public Collection createAreaFeatures(VPFFeatureClass featu return this.doCreateSimpleFeatures(featureClass); } - public Collection createTextFeatures(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createTextFeatures(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -93,10 +82,8 @@ public Collection createTextFeatures(VPFFeatureClass featu return this.doCreateSimpleFeatures(featureClass); } - public Collection createComplexFeatures(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createComplexFeatures(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -108,11 +95,8 @@ public Collection createComplexFeatures(VPFFeatureClass fe //**************************************************************// //******************** Simple Feature Assembly ***************// //**************************************************************// - - protected Collection doCreateSimpleFeatures(VPFFeatureClass featureClass) - { - if (this.primitiveData == null) - { + protected Collection doCreateSimpleFeatures(VPFFeatureClass featureClass) { + if (this.primitiveData == null) { String message = Logging.getMessage("VPF.NoPrimitiveData"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -121,81 +105,79 @@ protected Collection doCreateSimpleFeatures(VPFFeatureClas ArrayList results = new ArrayList(); VPFBufferedRecordData featureTable = this.createFeatureTable(featureClass); - if (featureTable == null) + if (featureTable == null) { return null; + } VPFBufferedRecordData joinTable = this.createJoinTable(featureClass); Iterable attributeKeys = this.getFeatureAttributeKeys(featureTable); - for (VPFRecord featureRow : featureTable) - { + for (VPFRecord featureRow : featureTable) { VPFFeature feature = this.doCreateSimpleFeature(featureClass, featureRow, joinTable, attributeKeys); - if (feature != null) + if (feature != null) { results.add(feature); + } } return results; } protected VPFFeature doCreateSimpleFeature(VPFFeatureClass featureClass, VPFRecord featureRow, - VPFBufferedRecordData joinTable, Iterable attributeKeys) - { - if (joinTable != null) - { + VPFBufferedRecordData joinTable, Iterable attributeKeys) { + if (joinTable != null) { return this.createCompoundSimpleFeature(featureClass, featureRow, joinTable, attributeKeys); - } - else - { + } else { return this.createSimpleFeature(featureClass, featureRow, attributeKeys); } } protected VPFFeature createSimpleFeature(VPFFeatureClass featureClass, VPFRecord featureRow, - Iterable attributeKeys) - { + Iterable attributeKeys) { // Feature has a direct 1:1 relation to the primitive table. - if (this.tile != null && !matchesTile(featureRow, this.tile)) + if (this.tile != null && !matchesTile(featureRow, this.tile)) { return null; + } VPFRelation featureToPrimitive = this.getFeatureToPrimitiveRelation(featureClass); - if (featureToPrimitive == null) + if (featureToPrimitive == null) { return null; + } int primitiveId = asInt(featureRow.getValue(featureToPrimitive.getTable1Key())); VPFPrimitiveData.PrimitiveInfo primitiveInfo = this.primitiveData.getPrimitiveInfo( - featureToPrimitive.getTable2(), primitiveId); + featureToPrimitive.getTable2(), primitiveId); return this.createFeature(featureClass, featureRow, attributeKeys, primitiveInfo.getBounds(), - new int[] {primitiveId}); + new int[]{primitiveId}); } protected VPFFeature createCompoundSimpleFeature(VPFFeatureClass featureClass, VPFRecord featureRow, - VPFBufferedRecordData joinTable, Iterable attributeKeys) - { + VPFBufferedRecordData joinTable, Iterable attributeKeys) { // Feature has a direct 1:* relation to the primitive table through a join table. // Query the number of primitives which match the feature. Object o = this.getPrimitiveIds(featureClass, featureRow, joinTable, null, true); - if (o == null || !(o instanceof Integer)) + if (o == null || !(o instanceof Integer)) { return null; + } int numPrimitives = (Integer) o; - if (numPrimitives < 1) + if (numPrimitives < 1) { return null; + } // Gather the actual primitive ids matching the feature. int[] primitiveIds = new int[numPrimitives]; VPFBoundingBox bounds = (VPFBoundingBox) this.getPrimitiveIds(featureClass, featureRow, joinTable, primitiveIds, - false); + false); return this.createFeature(featureClass, featureRow, attributeKeys, bounds, primitiveIds); } protected VPFFeature createFeature(VPFFeatureClass featureClass, VPFRecord featureRow, - Iterable attributeKeys, - VPFBoundingBox bounds, int[] primitiveIds) - { + Iterable attributeKeys, + VPFBoundingBox bounds, int[] primitiveIds) { VPFFeature feature = new VPFFeature(featureClass, featureRow.getId(), bounds, primitiveIds); this.setFeatureAttributes(featureRow, attributeKeys, feature); @@ -205,31 +187,29 @@ protected VPFFeature createFeature(VPFFeatureClass featureClass, VPFRecord featu //**************************************************************// //******************** Complex Feature Assembly **************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) - protected Collection doCreateComplexFeatures(VPFFeatureClass featureClass) - { + protected Collection doCreateComplexFeatures(VPFFeatureClass featureClass) { throw new UnsupportedOperationException(); } //**************************************************************// //******************** Common Feature Assembly ***************// //**************************************************************// - protected Object getPrimitiveIds(VPFFeatureClass featureClass, VPFRecord featureRow, - VPFBufferedRecordData joinTable, int[] primitiveIds, boolean query) - { + VPFBufferedRecordData joinTable, int[] primitiveIds, boolean query) { // Although a direct link between feature and primitive(s) is provided by the primitive_id column in the join // table, a sequential search of the feature_id column must still be performed to find all primitives associated // with a selected feature. VPFRelation featureToJoin = this.getFeatureToJoinRelation(featureClass); - if (featureToJoin == null) + if (featureToJoin == null) { return null; + } VPFRelation joinToPrimitive = this.getJoinToPrimitiveRelation(featureClass); - if (joinToPrimitive == null) + if (joinToPrimitive == null) { return null; + } int featureId = featureRow.getId(); String joinFeatureKey = featureToJoin.getTable2Key(); @@ -239,17 +219,17 @@ protected Object getPrimitiveIds(VPFFeatureClass featureClass, VPFRecord feature int numPrimitives = 0; VPFBoundingBox bounds = null; - for (VPFRecord joinRow : joinTable) - { - if (this.tile != null && !matchesTile(joinRow, this.tile)) + for (VPFRecord joinRow : joinTable) { + if (this.tile != null && !matchesTile(joinRow, this.tile)) { continue; + } int fId = asInt(joinRow.getValue(joinFeatureKey)); - if (featureId != fId) + if (featureId != fId) { continue; + } - if (!query) - { + if (!query) { int pId = asInt(joinRow.getValue(joinPrimitiveKey)); primitiveIds[numPrimitives] = pId; @@ -263,22 +243,19 @@ protected Object getPrimitiveIds(VPFFeatureClass featureClass, VPFRecord feature return query ? numPrimitives : bounds; } - protected Iterable getFeatureAttributeKeys(VPFBufferedRecordData table) - { + protected Iterable getFeatureAttributeKeys(VPFBufferedRecordData table) { ArrayList keys = new ArrayList(); - for (String name : table.getRecordParameterNames()) - { - if (name.equalsIgnoreCase("id") || - name.equalsIgnoreCase("tile_id") || - name.equalsIgnoreCase("from_to") || - name.equalsIgnoreCase("nod_id") || - name.equalsIgnoreCase("end_id") || - name.equalsIgnoreCase("cnd_id") || - name.equalsIgnoreCase("edg_id") || - name.equalsIgnoreCase("fac_id") || - name.equalsIgnoreCase("txt_id")) - { + for (String name : table.getRecordParameterNames()) { + if (name.equalsIgnoreCase("id") + || name.equalsIgnoreCase("tile_id") + || name.equalsIgnoreCase("from_to") + || name.equalsIgnoreCase("nod_id") + || name.equalsIgnoreCase("end_id") + || name.equalsIgnoreCase("cnd_id") + || name.equalsIgnoreCase("edg_id") + || name.equalsIgnoreCase("fac_id") + || name.equalsIgnoreCase("txt_id")) { continue; } @@ -288,10 +265,8 @@ protected Iterable getFeatureAttributeKeys(VPFBufferedRecordData table) return keys; } - protected void setFeatureAttributes(VPFRecord row, Iterable attributeKeys, AVList params) - { - for (String key : attributeKeys) - { + protected void setFeatureAttributes(VPFRecord row, Iterable attributeKeys, AVList params) { + for (String key : attributeKeys) { VPFUtils.checkAndSetValue(row, key, key, params); } } @@ -299,9 +274,7 @@ protected void setFeatureAttributes(VPFRecord row, Iterable attributeKey //**************************************************************// //******************** Utility Methods ***********************// //**************************************************************// - - protected VPFBufferedRecordData createFeatureTable(VPFFeatureClass featureClass) - { + protected VPFBufferedRecordData createFeatureTable(VPFFeatureClass featureClass) { StringBuilder sb = new StringBuilder(featureClass.getCoverage().getFilePath()); sb.append(File.separator); sb.append(featureClass.getFeatureTableName()); @@ -309,10 +282,10 @@ protected VPFBufferedRecordData createFeatureTable(VPFFeatureClass featureClass) return VPFUtils.readTable(new File(sb.toString())); } - protected VPFBufferedRecordData createJoinTable(VPFFeatureClass featureClass) - { - if (featureClass.getJoinTableName() == null) + protected VPFBufferedRecordData createJoinTable(VPFFeatureClass featureClass) { + if (featureClass.getJoinTableName() == null) { return null; + } StringBuilder sb = new StringBuilder(featureClass.getCoverage().getFilePath()); sb.append(File.separator); @@ -321,48 +294,44 @@ protected VPFBufferedRecordData createJoinTable(VPFFeatureClass featureClass) return VPFUtils.readTable(new File(sb.toString())); } - protected VPFRelation getFeatureToPrimitiveRelation(VPFFeatureClass featureClass) - { + protected VPFRelation getFeatureToPrimitiveRelation(VPFFeatureClass featureClass) { return findFirstRelation(featureClass.getFeatureTableName(), featureClass.getPrimitiveTableName(), - featureClass.getRelations()); + featureClass.getRelations()); } - protected VPFRelation getFeatureToJoinRelation(VPFFeatureClass featureClass) - { + protected VPFRelation getFeatureToJoinRelation(VPFFeatureClass featureClass) { return findFirstRelation(featureClass.getFeatureTableName(), featureClass.getJoinTableName(), - featureClass.getRelations()); + featureClass.getRelations()); } - protected VPFRelation getJoinToPrimitiveRelation(VPFFeatureClass featureClass) - { + protected VPFRelation getJoinToPrimitiveRelation(VPFFeatureClass featureClass) { return findFirstRelation(featureClass.getJoinTableName(), featureClass.getPrimitiveTableName(), - featureClass.getRelations()); + featureClass.getRelations()); } - protected static VPFRelation findFirstRelation(String table1, String table2, VPFRelation[] relations) - { - if (relations == null) + protected static VPFRelation findFirstRelation(String table1, String table2, VPFRelation[] relations) { + if (relations == null) { return null; + } - for (VPFRelation rel : relations) - { - if (rel.getTable1().equalsIgnoreCase(table1) && rel.getTable2().equalsIgnoreCase(table2)) + for (VPFRelation rel : relations) { + if (rel.getTable1().equalsIgnoreCase(table1) && rel.getTable2().equalsIgnoreCase(table2)) { return rel; + } } return null; } - protected static boolean matchesTile(VPFRecord row, VPFTile tile) - { + protected static boolean matchesTile(VPFRecord row, VPFTile tile) { Object fk = row.getValue("tile_id"); return (fk != null) && (tile.getId() == asInt(fk)); } - protected static int asInt(Object o) - { - if (o instanceof Number) + protected static int asInt(Object o) { + if (o instanceof Number) { return ((Number) o).intValue(); + } return -1; } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFBasicPrimitiveDataFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFBasicPrimitiveDataFactory.java index 24282a9f23..b0e5df146d 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFBasicPrimitiveDataFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFBasicPrimitiveDataFactory.java @@ -14,8 +14,8 @@ * @author dcollins * @version $Id: VPFBasicPrimitiveDataFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFBasicPrimitiveDataFactory implements VPFPrimitiveDataFactory -{ +public class VPFBasicPrimitiveDataFactory implements VPFPrimitiveDataFactory { + private VPFTile tile; /** @@ -24,20 +24,16 @@ public class VPFBasicPrimitiveDataFactory implements VPFPrimitiveDataFactory * * @param tile the tile which defines the geographic region to construct features for. */ - public VPFBasicPrimitiveDataFactory(VPFTile tile) - { + public VPFBasicPrimitiveDataFactory(VPFTile tile) { this.tile = tile; } - public VPFTile getTile() - { + public VPFTile getTile() { return this.tile; } - public VPFPrimitiveData createPrimitiveData(VPFCoverage coverage) - { - if (coverage == null) - { + public VPFPrimitiveData createPrimitiveData(VPFCoverage coverage) { + if (coverage == null) { String message = Logging.getMessage("nullValue.CoverageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -45,8 +41,9 @@ public VPFPrimitiveData createPrimitiveData(VPFCoverage coverage) String path = getPrimitiveTablePath(coverage, this.tile, ""); File file = new File(path); - if (!file.exists()) + if (!file.exists()) { return null; + } return this.doCreatePrimitives(coverage); } @@ -54,9 +51,7 @@ public VPFPrimitiveData createPrimitiveData(VPFCoverage coverage) //**************************************************************// //******************** Primitive Assembly ********************// //**************************************************************// - - protected VPFPrimitiveData doCreatePrimitives(VPFCoverage coverage) - { + protected VPFPrimitiveData doCreatePrimitives(VPFCoverage coverage) { VPFPrimitiveData primitiveData = new VPFPrimitiveData(); this.buildNodePrimitives(coverage, this.tile, primitiveData); this.buildEdgePrimitives(coverage, this.tile, primitiveData); @@ -66,35 +61,35 @@ protected VPFPrimitiveData doCreatePrimitives(VPFCoverage coverage) return primitiveData; } - protected void buildNodePrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimitiveData primitiveData) - { + protected void buildNodePrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimitiveData primitiveData) { VPFBufferedRecordData nodeTable = this.createPrimitiveTable(coverage, tile, VPFConstants.NODE_PRIMITIVE_TABLE); - if (nodeTable != null && nodeTable.getNumRecords() > 0) + if (nodeTable != null && nodeTable.getNumRecords() > 0) { this.buildNodePrimitives(nodeTable, VPFConstants.NODE_PRIMITIVE_TABLE, primitiveData); + } VPFBufferedRecordData entityNodeTable = this.createPrimitiveTable(coverage, tile, - VPFConstants.ENTITY_NODE_PRIMITIVE_TABLE); - if (entityNodeTable != null && entityNodeTable.getNumRecords() > 0) + VPFConstants.ENTITY_NODE_PRIMITIVE_TABLE); + if (entityNodeTable != null && entityNodeTable.getNumRecords() > 0) { this.buildNodePrimitives(entityNodeTable, VPFConstants.ENTITY_NODE_PRIMITIVE_TABLE, primitiveData); + } VPFBufferedRecordData connectedNodeTable = this.createPrimitiveTable(coverage, tile, - VPFConstants.CONNECTED_NODE_PRIMITIVE_TABLE); - if (connectedNodeTable != null && connectedNodeTable.getNumRecords() > 0) + VPFConstants.CONNECTED_NODE_PRIMITIVE_TABLE); + if (connectedNodeTable != null && connectedNodeTable.getNumRecords() > 0) { this.buildNodePrimitives(connectedNodeTable, VPFConstants.CONNECTED_NODE_PRIMITIVE_TABLE, primitiveData); + } } - protected boolean buildNodePrimitives(VPFBufferedRecordData table, String name, VPFPrimitiveData primitiveData) - { + protected boolean buildNodePrimitives(VPFBufferedRecordData table, String name, VPFPrimitiveData primitiveData) { int numNodes = table.getNumRecords(); VPFPrimitiveData.BasicPrimitiveInfo[] nodeInfo = new VPFPrimitiveData.BasicPrimitiveInfo[numNodes]; VecBufferSequence coords = (VecBufferSequence) table.getRecordData("coordinate").getBackingData(); - for (VPFRecord row : table) - { + for (VPFRecord row : table) { int id = row.getId(); nodeInfo[VPFBufferedRecordData.indexFromId(id)] = new VPFPrimitiveData.BasicPrimitiveInfo( - VPFBoundingBox.fromVecBuffer(coords.subBuffer(id))); + VPFBoundingBox.fromVecBuffer(coords.subBuffer(id))); } primitiveData.setPrimitiveInfo(name, nodeInfo); @@ -102,123 +97,123 @@ protected boolean buildNodePrimitives(VPFBufferedRecordData table, String name, return true; } - protected void buildEdgePrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimitiveData primitiveData) - { + protected void buildEdgePrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimitiveData primitiveData) { VPFBufferedRecordData edgeTable = this.createPrimitiveTable(coverage, tile, VPFConstants.EDGE_PRIMITIVE_TABLE); - if (edgeTable == null || edgeTable.getNumRecords() == 0) + if (edgeTable == null || edgeTable.getNumRecords() == 0) { return; + } VPFBufferedRecordData mbrTable = this.createPrimitiveTable(coverage, tile, - VPFConstants.EDGE_BOUNDING_RECTANGLE_TABLE); - if (mbrTable == null) + VPFConstants.EDGE_BOUNDING_RECTANGLE_TABLE); + if (mbrTable == null) { return; + } int numEdges = edgeTable.getNumRecords(); VPFPrimitiveData.EdgeInfo[] edgeInfo = new VPFPrimitiveData.EdgeInfo[numEdges]; VecBufferSequence coords = (VecBufferSequence) edgeTable.getRecordData( - "coordinates").getBackingData(); + "coordinates").getBackingData(); - for (VPFRecord row : edgeTable) - { + for (VPFRecord row : edgeTable) { int id = row.getId(); VPFRecord mbrRow = mbrTable.getRecord(id); edgeInfo[VPFBufferedRecordData.indexFromId(id)] = new VPFPrimitiveData.EdgeInfo( - getNumber(row.getValue("edge_type")), - getId(row.getValue("start_node")), getNumber(row.getValue("end_node")), - getId(row.getValue("left_face")), getId(row.getValue("right_face")), - getId(row.getValue("left_edge")), getId(row.getValue("right_edge")), - isEdgeOnTileBoundary(row), - VPFUtils.getExtent(mbrRow)); + getNumber(row.getValue("edge_type")), + getId(row.getValue("start_node")), getNumber(row.getValue("end_node")), + getId(row.getValue("left_face")), getId(row.getValue("right_face")), + getId(row.getValue("left_edge")), getId(row.getValue("right_edge")), + isEdgeOnTileBoundary(row), + VPFUtils.getExtent(mbrRow)); } primitiveData.setPrimitiveInfo(VPFConstants.EDGE_PRIMITIVE_TABLE, edgeInfo); primitiveData.setPrimitiveCoords(VPFConstants.EDGE_PRIMITIVE_TABLE, coords); } - protected void buildFacePrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimitiveData primitiveData) - { + protected void buildFacePrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimitiveData primitiveData) { VPFBufferedRecordData faceTable = this.createPrimitiveTable(coverage, tile, VPFConstants.FACE_PRIMITIVE_TABLE); - if (faceTable == null) + if (faceTable == null) { return; + } VPFBufferedRecordData mbrTable = this.createPrimitiveTable(coverage, tile, - VPFConstants.FACE_BOUNDING_RECTANGLE_TABLE); - if (mbrTable == null) + VPFConstants.FACE_BOUNDING_RECTANGLE_TABLE); + if (mbrTable == null) { return; + } VPFBufferedRecordData ringTable = this.createPrimitiveTable(coverage, tile, VPFConstants.RING_TABLE); - if (ringTable == null) + if (ringTable == null) { return; + } VPFPrimitiveData.PrimitiveInfo[] edgeInfo = primitiveData.getPrimitiveInfo(VPFConstants.EDGE_PRIMITIVE_TABLE); int numFaces = faceTable.getNumRecords(); VPFPrimitiveData.FaceInfo[] faceInfo = new VPFPrimitiveData.FaceInfo[numFaces]; - for (VPFRecord faceRow : faceTable) - { + for (VPFRecord faceRow : faceTable) { int faceId = faceRow.getId(); VPFRecord mbrRow = mbrTable.getRecord(faceId); // Face ID 1 is reserved for the "universe face", which does not have any associated geometry. - if (faceId == 1) + if (faceId == 1) { continue; + } // The first ring primitive associated with the face primitive defines the outer ring. The face primitive must // at least contain coordinates for an outer ring. - int ringId = ((Number) faceRow.getValue("ring_ptr")).intValue(); VPFRecord ringRow = ringTable.getRecord(ringId); VPFPrimitiveData.Ring outerRing = this.buildRing(ringRow, edgeInfo); // The ring table maintains an order relationship for its rows. The first record of a new face id will always // be defined as the outer ring. Any repeating records with an identical face value will define inner rings. - ArrayList innerRingList = new ArrayList(); - for (ringId = ringId + 1; ringId <= ringTable.getNumRecords(); ringId++) - { + for (ringId = ringId + 1; ringId <= ringTable.getNumRecords(); ringId++) { ringRow = ringTable.getRecord(ringId); // Break on the first ring primitive row which isn't associated with the face. Because the ring rows // maintain an ordering with respect to face id, there will be no other ring rows corresponding to this // face. - if (faceId != getId(ringRow.getValue("face_id"))) + if (faceId != getId(ringRow.getValue("face_id"))) { break; + } VPFPrimitiveData.Ring innerRing = this.buildRing(ringRow, edgeInfo); - if (innerRing != null) + if (innerRing != null) { innerRingList.add(innerRing); + } } VPFPrimitiveData.Ring[] innerRings = new VPFPrimitiveData.Ring[innerRingList.size()]; innerRingList.toArray(innerRings); faceInfo[VPFBufferedRecordData.indexFromId(faceId)] = new VPFPrimitiveData.FaceInfo( - outerRing, innerRings, VPFUtils.getExtent(mbrRow)); + outerRing, innerRings, VPFUtils.getExtent(mbrRow)); } primitiveData.setPrimitiveInfo(VPFConstants.FACE_PRIMITIVE_TABLE, faceInfo); } - protected void buildTextPrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimitiveData primitiveData) - { + protected void buildTextPrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimitiveData primitiveData) { VPFBufferedRecordData textTable = this.createPrimitiveTable(coverage, tile, VPFConstants.TEXT_PRIMITIVE_TABLE); - if (textTable == null || textTable.getNumRecords() == 0) + if (textTable == null || textTable.getNumRecords() == 0) { return; + } int numText = textTable.getNumRecords(); VPFPrimitiveData.BasicPrimitiveInfo[] textInfo = new VPFPrimitiveData.BasicPrimitiveInfo[numText]; VecBufferSequence coords = (VecBufferSequence) textTable.getRecordData("shape_line").getBackingData(); CompoundStringBuilder strings = (CompoundStringBuilder) textTable.getRecordData("string").getBackingData(); - for (VPFRecord row : textTable) - { + for (VPFRecord row : textTable) { int id = row.getId(); textInfo[VPFBufferedRecordData.indexFromId(id)] = new VPFPrimitiveData.BasicPrimitiveInfo( - VPFBoundingBox.fromVecBuffer(coords.subBuffer(id))); + VPFBoundingBox.fromVecBuffer(coords.subBuffer(id))); } primitiveData.setPrimitiveInfo(VPFConstants.TEXT_PRIMITIVE_TABLE, textInfo); @@ -229,18 +224,16 @@ protected void buildTextPrimitives(VPFCoverage coverage, VPFTile tile, VPFPrimit //**************************************************************// //******************** Winged-Edge Face Construction *********// //**************************************************************// - /** * Given a row from the ring primitive table, navigate the ring and edge primitive tables to construct a new {@link * VPFPrimitiveData.Ring}. * - * @param row the ring primitive row. + * @param row the ring primitive row. * @param edgeInfoArray the edge primitive data. * * @return a new Ring. */ - protected VPFPrimitiveData.Ring buildRing(VPFRecord row, VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray) - { + protected VPFPrimitiveData.Ring buildRing(VPFRecord row, VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray) { int faceId = ((Number) row.getValue("face_id")).intValue(); int startEdgeId = ((Number) row.getValue("start_edge")).intValue(); VPFWingedEdgeTraverser traverser = new VPFWingedEdgeTraverser(); @@ -252,10 +245,8 @@ protected VPFPrimitiveData.Ring buildRing(VPFRecord row, VPFPrimitiveData.Primit // Traverse the ring again, but this time populate an entry for the primitiveID and orientation data stuctures // for each edge. - traverser.traverseRing(faceId, startEdgeId, edgeInfoArray, new VPFWingedEdgeTraverser.EdgeTraversalListener() - { - public void nextEdge(int index, int primitiveId, boolean reverseCoordinates) - { + traverser.traverseRing(faceId, startEdgeId, edgeInfoArray, new VPFWingedEdgeTraverser.EdgeTraversalListener() { + public void nextEdge(int index, int primitiveId, boolean reverseCoordinates) { idArray[index] = primitiveId; orientationArray[index] = reverseCoordinates ? -1 : 1; } @@ -267,27 +258,24 @@ public void nextEdge(int index, int primitiveId, boolean reverseCoordinates) //**************************************************************// //******************** Utility Methods ***********************// //**************************************************************// - - protected VPFBufferedRecordData createPrimitiveTable(VPFCoverage coverage, VPFTile tile, String tableName) - { + protected VPFBufferedRecordData createPrimitiveTable(VPFCoverage coverage, VPFTile tile, String tableName) { String path = getPrimitiveTablePath(coverage, tile, tableName); File file = new File(path); - if (!file.exists()) + if (!file.exists()) { return null; + } return VPFUtils.readTable(file); } - protected static String getPrimitiveTablePath(VPFCoverage coverage, VPFTile tile, String tableName) - { + protected static String getPrimitiveTablePath(VPFCoverage coverage, VPFTile tile, String tableName) { // Start with the coverage directory. StringBuilder sb = new StringBuilder(coverage.getFilePath()); sb.append(File.separator); // If the tile is non-null then append the tile's path. - if (tile != null) - { + if (tile != null) { sb.append(tile.getName()); sb.append(File.separator); } @@ -298,38 +286,38 @@ protected static String getPrimitiveTablePath(VPFCoverage coverage, VPFTile tile return sb.toString(); } - protected static boolean isEdgeOnTileBoundary(VPFRecord record) - { + protected static boolean isEdgeOnTileBoundary(VPFRecord record) { VPFTripletId id = null; Object o = record.getValue("left_face"); - if (o instanceof VPFTripletId) + if (o instanceof VPFTripletId) { id = (VPFTripletId) o; + } - if (id == null) - { + if (id == null) { o = record.getValue("right_face"); - if (o instanceof VPFTripletId) + if (o instanceof VPFTripletId) { id = (VPFTripletId) o; + } } return id != null && id.getExtId() > 0; } - protected static int getNumber(Object key) - { - if (key instanceof Number) + protected static int getNumber(Object key) { + if (key instanceof Number) { return ((Number) key).intValue(); + } return -1; } - protected static int getId(Object key) - { - if (key instanceof Number) + protected static int getId(Object key) { + if (key instanceof Number) { return ((Number) key).intValue(); - else if (key instanceof VPFTripletId) + } else if (key instanceof VPFTripletId) { return ((VPFTripletId) key).getId(); + } return -1; } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFBasicSymbolFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFBasicSymbolFactory.java index 14923df996..a8a61cf193 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFBasicSymbolFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFBasicSymbolFactory.java @@ -17,27 +17,24 @@ * @author dcollins * @version $Id: VPFBasicSymbolFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFBasicSymbolFactory implements VPFSymbolFactory -{ +public class VPFBasicSymbolFactory implements VPFSymbolFactory { + private static final double DEFAULT_ICON_MAX_SIZE = 10000; // Max 10km protected VPFPrimitiveData primitiveData; protected VPFFeatureFactory featureFactory; protected VPFSymbolSupport symbolSupport; - public VPFBasicSymbolFactory(VPFTile tile, VPFPrimitiveData primitiveData) - { + public VPFBasicSymbolFactory(VPFTile tile, VPFPrimitiveData primitiveData) { this.primitiveData = primitiveData; this.featureFactory = new VPFBasicFeatureFactory(tile, primitiveData); } - public VPFSymbolSupport getStyleSupport() - { + public VPFSymbolSupport getStyleSupport() { return this.symbolSupport; } - public void setStyleSupport(VPFSymbolSupport symbolSupport) - { + public void setStyleSupport(VPFSymbolSupport symbolSupport) { this.symbolSupport = symbolSupport; } @@ -47,18 +44,17 @@ public void setStyleSupport(VPFSymbolSupport symbolSupport) * @return the symbols. */ @Override - public Collection createPointSymbols(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createPointSymbols(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FeatureMap map = this.createFeatureMap(featureClass); - if (map == null) + if (map == null) { return null; + } ArrayList symbols = new ArrayList(); this.doCreatePointSymbols(map, symbols); @@ -70,18 +66,17 @@ public Collection createPointSymbols(VPFFeatureClass featur * * @return The symbols. */ - public Collection createLineSymbols(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createLineSymbols(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FeatureMap map = this.createFeatureMap(featureClass); - if (map == null) + if (map == null) { return null; + } ArrayList symbols = new ArrayList(); this.doCreateLineSymbols(map, symbols); @@ -93,18 +88,17 @@ public Collection createLineSymbols(VPFFeatureClass feature * * @return The symbols. */ - public Collection createAreaSymbols(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createAreaSymbols(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FeatureMap map = this.createFeatureMap(featureClass); - if (map == null) + if (map == null) { return null; + } ArrayList symbols = new ArrayList(); this.doCreateAreaSymbols(map, symbols); @@ -116,18 +110,17 @@ public Collection createAreaSymbols(VPFFeatureClass feature * * @return The symbols. */ - public Collection createTextSymbols(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createTextSymbols(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FeatureMap map = this.createFeatureMap(featureClass); - if (map == null) + if (map == null) { return null; + } ArrayList symbols = new ArrayList(); this.doCreateTextSymbols(map, symbols); @@ -139,10 +132,8 @@ public Collection createTextSymbols(VPFFeatureClass feature * * @return The symbols. */ - public Collection createComplexSymbols(VPFFeatureClass featureClass) - { - if (featureClass == null) - { + public Collection createComplexSymbols(VPFFeatureClass featureClass) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -151,25 +142,24 @@ public Collection createComplexSymbols(VPFFeatureClass feat throw new UnsupportedOperationException(); } - protected FeatureMap createFeatureMap(VPFFeatureClass featureClass) - { + protected FeatureMap createFeatureMap(VPFFeatureClass featureClass) { // Get the features associated with the feature class. Collection features = featureClass.createFeatures(this.featureFactory); - if (features == null) + if (features == null) { return null; + } FeatureMap map = new FeatureMap(); - for (VPFFeature feature : features) - { + for (VPFFeature feature : features) { // Get the symbol keys associated with the current feature. Iterable symbolKeys = this.getSymbolKeys(feature); - if (symbolKeys == null) + if (symbolKeys == null) { continue; + } // Map the feature according to its associated symbol key. - for (VPFSymbolKey key : symbolKeys) - { + for (VPFSymbolKey key : symbolKeys) { map.addFeature(key, feature); } } @@ -180,7 +170,6 @@ protected FeatureMap createFeatureMap(VPFFeatureClass featureClass) //**************************************************************// //******************** Symbol Assembly ***********************// //**************************************************************// - /** * From MIL-DTL-89045A, section 3.5.3.1.1: A point feature may be symbolized as either a point symbol or as a text * label or both. @@ -188,19 +177,16 @@ protected FeatureMap createFeatureMap(VPFFeatureClass featureClass) * From MIL-HDBK-857A, section 6.5.3.1: For point features (e.g., buoys, beacons, lights) that are composed of * several symbol components, displaying the components according to the row ids in the *sym.txt file will result in * the properly constructed composite symbol. + * * @param featureMap The feature map. * @param outCollection The symbols. */ - protected void doCreatePointSymbols(FeatureMap featureMap, Collection outCollection) - { - for (Map.Entry entry : featureMap.entrySet()) - { + protected void doCreatePointSymbols(FeatureMap featureMap, Collection outCollection) { + for (Map.Entry entry : featureMap.entrySet()) { CombinedFeature feature = entry.getValue(); - for (VPFSymbolAttributes attr : this.getSymbolAttributes(feature, entry.getKey())) - { - switch (attr.getFeatureType()) - { + for (VPFSymbolAttributes attr : this.getSymbolAttributes(feature, entry.getKey())) { + switch (attr.getFeatureType()) { // Construct a renderable object for each point symbol. case POINT: this.addPointSymbol(feature, attr, outCollection); @@ -217,19 +203,16 @@ protected void doCreatePointSymbols(FeatureMap featureMap, Collection /** * From MIL-DTL-89045A, section 3.5.3.1.1: A linear feature will be symbolized exclusively by a line symbol that may * or may not be labeled. + * * @param featureMap The feature map. * @param outCollection The symbols. */ - protected void doCreateLineSymbols(FeatureMap featureMap, Collection outCollection) - { - for (Map.Entry entry : featureMap.entrySet()) - { + protected void doCreateLineSymbols(FeatureMap featureMap, Collection outCollection) { + for (Map.Entry entry : featureMap.entrySet()) { CombinedFeature feature = entry.getValue(); - for (VPFSymbolAttributes attr : this.getSymbolAttributes(feature, entry.getKey())) - { - switch (attr.getFeatureType()) - { + for (VPFSymbolAttributes attr : this.getSymbolAttributes(feature, entry.getKey())) { + switch (attr.getFeatureType()) { // Construct a renderable object for each line symbol. case LINE: this.addLineSymbol(feature, attr, outCollection); @@ -248,16 +231,16 @@ protected void doCreateLineSymbols(FeatureMap featureMap, Collection * area symbol as well as with a text label. *

        * From MIL-HDBK-857A, section 6.4.1.4: It is also possible for there to exist multiple symbology components for - * area features. The most common situation is the need for the addition of the low accuracy symbol (see - * 6.4.1.3.4). This situation is implemented in the same way as for points, with an additional row in the *sym.txt - * table to control the placement of the low accuracy symbol. + * area features. The most common situation is the need for the addition of the low accuracy symbol (see 6.4.1.3.4). + * This situation is implemented in the same way as for points, with an additional row in the *sym.txt table to + * control the placement of the low accuracy symbol. *

        * It is also possible for the symbolization of an area feature to require multiple rows to specify the components - * of the full area symbol. This situation will exist for those area features requiring both a solid fill and a - * pattern fill. In this case, the two area symbols will be specified using two rows in the *sym.txt file with the - * row specifying the solid fill always preceding the row specifying the pattern fill. If the same area feature - * also requires a boundary and/or a centered point symbol, those symbols will be specified in the second row for - * the area feature (along with the area pattern). Section 6.5 explains the ramifications of this approach in more + * of the full area symbol. This situation will exist for those area features requiring both a solid fill and a + * pattern fill. In this case, the two area symbols will be specified using two rows in the *sym.txt file with the + * row specifying the solid fill always preceding the row specifying the pattern fill. If the same area feature also + * requires a boundary and/or a centered point symbol, those symbols will be specified in the second row for the + * area feature (along with the area pattern). Section 6.5 explains the ramifications of this approach in more * detail. *

        * For these reasons, as well as for the placement of text labels (see section 6.4.1.5), it is crucial that @@ -265,24 +248,21 @@ protected void doCreateLineSymbols(FeatureMap featureMap, Collection * to ensure full symbolization for any feature. *

        * From MIL-HDBK-857A, section 6.5.3.2: There are some area features (e.g., Maritime Areas) that require both a - * solid fill and one or more pattern fills. Since the areasym column can only contain a single CGM reference, - * there is a separate row in the *sym.txt file for each of the area symbols, as well as for the line symbol and/or - * point symbol that apply to the specific area feature. These multiple rows will have sequential row ids in the - * *sym.txt file according to the order in which the symbols are to be displayed on the screen: solid fill, pattern - * fill (may be more than one), linear boundary, centered point symbol (may be more than one). + * solid fill and one or more pattern fills. Since the areasym column can only contain a single CGM reference, there + * is a separate row in the *sym.txt file for each of the area symbols, as well as for the line symbol and/or point + * symbol that apply to the specific area feature. These multiple rows will have sequential row ids in the *sym.txt + * file according to the order in which the symbols are to be displayed on the screen: solid fill, pattern fill (may + * be more than one), linear boundary, centered point symbol (may be more than one). + * * @param featureMap The feature map. * @param outCollection The symbols. */ - protected void doCreateAreaSymbols(FeatureMap featureMap, Collection outCollection) - { - for (Map.Entry entry : featureMap.entrySet()) - { + protected void doCreateAreaSymbols(FeatureMap featureMap, Collection outCollection) { + for (Map.Entry entry : featureMap.entrySet()) { CombinedFeature feature = entry.getValue(); - for (VPFSymbolAttributes attr : this.getSymbolAttributes(feature, entry.getKey())) - { - switch (attr.getFeatureType()) - { + for (VPFSymbolAttributes attr : this.getSymbolAttributes(feature, entry.getKey())) { + switch (attr.getFeatureType()) { // Construct a renderable object for each area symbol. case AREA: this.addAreaSymbol(feature, attr, outCollection); @@ -314,16 +294,12 @@ protected void doCreateAreaSymbols(FeatureMap featureMap, Collection * @param featureMap The feature map. * @param outCollection The symbols. */ - protected void doCreateTextSymbols(FeatureMap featureMap, Collection outCollection) - { - for (Map.Entry entry : featureMap.entrySet()) - { + protected void doCreateTextSymbols(FeatureMap featureMap, Collection outCollection) { + for (Map.Entry entry : featureMap.entrySet()) { CombinedFeature feature = entry.getValue(); - for (VPFSymbolAttributes attr : this.getSymbolAttributes(feature, entry.getKey())) - { - switch (attr.getFeatureType()) - { + for (VPFSymbolAttributes attr : this.getSymbolAttributes(feature, entry.getKey())) { + switch (attr.getFeatureType()) { // Construct a renderable object for each area symbol. case TEXT: this.addTextSymbol(feature, attr, outCollection); @@ -334,29 +310,25 @@ protected void doCreateTextSymbols(FeatureMap featureMap, Collection } protected void addPointSymbol(CombinedFeature feature, VPFSymbolAttributes attr, - Collection outCollection) - { + Collection outCollection) { // Build the list of locations and headings associated with each point symbol. int numSymbols = 0; boolean haveUniqueHeadings = false; ArrayList locations = new ArrayList(); ArrayList headings = new ArrayList(); - for (VPFFeature subFeature : feature) - { + for (VPFFeature subFeature : feature) { String primitiveName = feature.getFeatureClass().getPrimitiveTableName(); Angle heading = this.getPointSymbolHeading(attr, subFeature); - for (int id : subFeature.getPrimitiveIds()) - { + for (int id : subFeature.getPrimitiveIds()) { CompoundVecBuffer combinedCoords = this.primitiveData.getPrimitiveCoords(primitiveName); - if (combinedCoords != null) - { + if (combinedCoords != null) { VecBuffer coords = combinedCoords.subBuffer(id); - if (coords != null) - { - if (!haveUniqueHeadings) + if (coords != null) { + if (!haveUniqueHeadings) { haveUniqueHeadings = headings.size() > 0 && !headings.contains(heading); + } locations.add(coords.getPosition(0)); headings.add(heading); @@ -366,53 +338,47 @@ protected void addPointSymbol(CombinedFeature feature, VPFSymbolAttributes attr, } } - if (haveUniqueHeadings) - { - for (int i = 0; i < numSymbols; i++) - { + if (haveUniqueHeadings) { + for (int i = 0; i < numSymbols; i++) { SurfaceIcon o = new SurfaceIcon("", locations.get(i)); o.setHeading(headings.get(i)); this.applyPointSymbolAttributes(attr, o); outCollection.add(new VPFSymbol(feature, attr, o)); } - } - else - { + } else { SurfaceIcons o = new SurfaceIcons("", locations); - if (headings.get(0) != null) + if (headings.get(0) != null) { o.setHeading(headings.get(0)); + } this.applyPointSymbolAttributes(attr, o); outCollection.add(new VPFSymbol(feature, attr, o)); } } - protected void addLineSymbol(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) - { + protected void addLineSymbol(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) { SurfaceShape o = new VPFSurfaceLine(feature, this.primitiveData); this.applySymbolAttributes(attr, o); outCollection.add(new VPFSymbol(feature, attr, o)); } - protected void addAreaSymbol(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) - { + protected void addAreaSymbol(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) { SurfaceShape o = new VPFSurfaceArea(feature, this.primitiveData); this.applySymbolAttributes(attr, o); outCollection.add(new VPFSymbol(feature, attr, o)); } - protected void addTextSymbol(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) - { + protected void addTextSymbol(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) { String primitiveName = feature.getFeatureClass().getPrimitiveTableName(); CompoundVecBuffer combinedCoords = this.primitiveData.getPrimitiveCoords(primitiveName); CompoundStringBuilder combinedStrings = this.primitiveData.getPrimitiveStrings(primitiveName); // Construct a renderable object for the first text symbol. - for (int id : feature.getPrimitiveIds()) - { + for (int id : feature.getPrimitiveIds()) { VecBuffer coords = combinedCoords.subBuffer(id); CharSequence text = combinedStrings.subSequence(id); - if (text != null) + if (text != null) { text = WWUtil.trimCharSequence(text); + } GeographicText o = new UserFacingText(text, coords.getPosition(0)); this.applyTextAttributes(attr, o); @@ -420,22 +386,19 @@ protected void addTextSymbol(CombinedFeature feature, VPFSymbolAttributes attr, } } - protected void addTextLabel(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) - { - for (VPFFeature subFeature : feature) - { + protected void addTextLabel(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) { + for (VPFFeature subFeature : feature) { this.addTextLabel(subFeature, attr, outCollection); } } - protected void addTextLabel(VPFFeature feature, VPFSymbolAttributes attr, Collection outCollection) - { + protected void addTextLabel(VPFFeature feature, VPFSymbolAttributes attr, Collection outCollection) { VPFSymbolAttributes.LabelAttributes[] labelAttr = attr.getLabelAttributes(); - if (labelAttr == null || labelAttr.length == 0) + if (labelAttr == null || labelAttr.length == 0) { return; + } - for (VPFSymbolAttributes.LabelAttributes la : labelAttr) - { + for (VPFSymbolAttributes.LabelAttributes la : labelAttr) { GeographicText o = new UserFacingText("", null); this.applyLabelAttributes(la, feature, o); @@ -444,15 +407,12 @@ protected void addTextLabel(VPFFeature feature, VPFSymbolAttributes attr, Collec } } - protected void addPointLabel(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) - { + protected void addPointLabel(CombinedFeature feature, VPFSymbolAttributes attr, Collection outCollection) { // Build the list of point symbol locations associated with each sub-feature. ArrayList locations = new ArrayList(); - for (VPFFeature subFeature : feature) - { - if (subFeature.getBounds() != null) - { + for (VPFFeature subFeature : feature) { + if (subFeature.getBounds() != null) { locations.add(subFeature.getBounds().toSector().getCentroid()); } } @@ -465,66 +425,54 @@ protected void addPointLabel(CombinedFeature feature, VPFSymbolAttributes attr, //**************************************************************// //******************** Symbol Attribute Assembly *************// //**************************************************************// - - protected Iterable getSymbolKeys(VPFFeature feature) - { + protected Iterable getSymbolKeys(VPFFeature feature) { String fcode = feature.getStringValue("f_code"); return this.symbolSupport.getSymbolKeys(feature.getFeatureClass(), fcode, feature); } - protected Iterable getSymbolAttributes(VPFFeature feature, VPFSymbolKey symbolKey) - { + protected Iterable getSymbolAttributes(VPFFeature feature, VPFSymbolKey symbolKey) { return this.symbolSupport.getSymbolAttributes(feature.getFeatureClass(), symbolKey); } - protected void applyPointSymbolAttributes(VPFSymbolAttributes attr, SurfaceIcon icon) - { - if (attr.getIconImageSource() != null) + protected void applyPointSymbolAttributes(VPFSymbolAttributes attr, SurfaceIcon icon) { + if (attr.getIconImageSource() != null) { icon.setImageSource(attr.getIconImageSource()); + } icon.setUseMipMaps(attr.isMipMapIconImage()); icon.setScale(attr.getIconImageScale()); icon.setMaxSize(DEFAULT_ICON_MAX_SIZE); } - protected Angle getPointSymbolHeading(VPFSymbolAttributes attr, AVList featureAttributes) - { - if (attr.getOrientationAttributeName() == null) - { + protected Angle getPointSymbolHeading(VPFSymbolAttributes attr, AVList featureAttributes) { + if (attr.getOrientationAttributeName() == null) { return null; } Object o = featureAttributes.getValue(attr.getOrientationAttributeName()); - if (o instanceof Number) - { + if (o instanceof Number) { Double d = ((Number) o).doubleValue(); return Angle.fromDegrees(d); - } - else if (o instanceof String) - { + } else if (o instanceof String) { Double d = WWUtil.convertStringToDouble((String) o); - if (d != null) + if (d != null) { return Angle.fromDegrees(d); + } } return null; } - protected void applySymbolAttributes(VPFSymbolAttributes attr, SurfaceShape surfaceShape) - { + protected void applySymbolAttributes(VPFSymbolAttributes attr, SurfaceShape surfaceShape) { surfaceShape.setAttributes(attr); } - public void applyTextAttributes(VPFSymbolAttributes attr, GeographicText text) - { + public void applyTextAttributes(VPFSymbolAttributes attr, GeographicText text) { VPFSymbolAttributes.LabelAttributes[] labelAttr = attr.getLabelAttributes(); - if (labelAttr != null && labelAttr.length > 0) - { + if (labelAttr != null && labelAttr.length > 0) { text.setFont(labelAttr[0].getFont()); text.setColor(labelAttr[0].getColor()); text.setBackgroundColor(labelAttr[0].getBackgroundColor()); - } - else - { + } else { text.setFont(Font.decode("Arial-PLAIN-12")); text.setColor(attr.getInteriorMaterial().getDiffuse()); text.setBackgroundColor(WWUtil.computeContrastingColor(attr.getInteriorMaterial().getDiffuse())); @@ -532,35 +480,33 @@ public void applyTextAttributes(VPFSymbolAttributes attr, GeographicText text) } protected void applyLabelAttributes(VPFSymbolAttributes.LabelAttributes attr, VPFFeature feature, - GeographicText text) - { + GeographicText text) { text.setFont(attr.getFont()); text.setColor(attr.getColor()); text.setBackgroundColor(attr.getBackgroundColor()); LatLon location = this.computeLabelLocation(attr, feature); - if (location != null) + if (location != null) { text.setPosition(new Position(location, 0)); + } String labelText = this.symbolSupport.getSymbolLabelText(attr, feature); - if (labelText != null) + if (labelText != null) { text.setText(labelText); + } } - protected LatLon computeLabelLocation(VPFSymbolAttributes.LabelAttributes attr, VPFFeature feature) - { + protected LatLon computeLabelLocation(VPFSymbolAttributes.LabelAttributes attr, VPFFeature feature) { LatLon location = feature.getBounds().toSector().getCentroid(); // If we are given label offset parameters, compute the label location using the offset azimuth and offset arc // length. - if (attr.getOffset() != 0) - { + if (attr.getOffset() != 0) { VPFLibrary library = feature.getFeatureClass().getCoverage().getLibrary(); Angle offsetAzimuth = attr.getOffsetAngle(); Angle offsetLength = library.computeArcLengthFromMapDistance(attr.getOffset()); - if (offsetAzimuth != null && offsetLength != null) - { + if (offsetAzimuth != null && offsetLength != null) { location = LatLon.greatCircleEndPosition(location, offsetAzimuth, offsetLength); } } @@ -571,14 +517,11 @@ protected LatLon computeLabelLocation(VPFSymbolAttributes.LabelAttributes attr, //**************************************************************// //******************** Feature Support ***********************// //**************************************************************// + protected static class FeatureMap extends HashMap { - protected static class FeatureMap extends HashMap - { - public void addFeature(VPFSymbolKey key, VPFFeature feature) - { + public void addFeature(VPFSymbolKey key, VPFFeature feature) { CombinedFeature combined = this.get(key); - if (combined == null) - { + if (combined == null) { combined = new CombinedFeature(feature.getFeatureClass()); this.put(key, combined); } @@ -587,66 +530,54 @@ public void addFeature(VPFSymbolKey key, VPFFeature feature) } } - protected static class CombinedFeature extends VPFFeature implements Iterable - { + protected static class CombinedFeature extends VPFFeature implements Iterable { + private ArrayList featureList; - public CombinedFeature(VPFFeatureClass featureClass) - { + public CombinedFeature(VPFFeatureClass featureClass) { super(featureClass, -1, new VPFBoundingBox(0, 0, 0, 0), null); this.featureList = new ArrayList(); } - public VPFBoundingBox getBounds() - { + public VPFBoundingBox getBounds() { return combineBounds(this.featureList); } - public int[] getPrimitiveIds() - { + public int[] getPrimitiveIds() { return combinePrimitiveIds(this.featureList); } - public void add(VPFFeature feature) - { + public void add(VPFFeature feature) { this.featureList.add(feature); } - public Iterator iterator() - { + public Iterator iterator() { return this.featureList.iterator(); } } - protected static VPFBoundingBox combineBounds(Iterable features) - { + protected static VPFBoundingBox combineBounds(Iterable features) { VPFBoundingBox bounds = null; - for (VPFFeature f : features) - { + for (VPFFeature f : features) { bounds = (bounds != null) ? f.getBounds().union(bounds) : f.getBounds(); } return bounds; } - protected static int[] combinePrimitiveIds(Iterable features) - { + protected static int[] combinePrimitiveIds(Iterable features) { int length = 0; - for (VPFFeature f : features) - { - if (f.getPrimitiveIds() != null) - { + for (VPFFeature f : features) { + if (f.getPrimitiveIds() != null) { length += f.getPrimitiveIds().length; } } int[] array = new int[length]; int position = 0; - for (VPFFeature f : features) - { - if (f.getPrimitiveIds() != null) - { + for (VPFFeature f : features) { + if (f.getPrimitiveIds() != null) { int[] src = f.getPrimitiveIds(); System.arraycopy(src, 0, array, position, src.length); position += src.length; diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFBoundingBox.java b/src/gov/nasa/worldwind/formats/vpf/VPFBoundingBox.java index f0d1813157..566be5b294 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFBoundingBox.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFBoundingBox.java @@ -12,64 +12,55 @@ * @author dcollins * @version $Id: VPFBoundingBox.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFBoundingBox -{ +public class VPFBoundingBox { + private double xmin; private double ymin; private double xmax; private double ymax; - public VPFBoundingBox(double xmin, double ymin, double xmax, double ymax) - { + public VPFBoundingBox(double xmin, double ymin, double xmax, double ymax) { this.xmin = xmin; this.ymin = ymin; this.xmax = xmax; this.ymax = ymax; } - public double getXmin() - { + public double getXmin() { return this.xmin; } - public double getYmin() - { + public double getYmin() { return this.ymin; } - public double getXmax() - { + public double getXmax() { return this.xmax; } - public double getYmax() - { + public double getYmax() { return this.ymax; } - public Sector toSector() - { + public Sector toSector() { return Sector.fromDegrees(this.ymin, this.ymax, this.xmin, this.xmax); } - public VPFBoundingBox union(VPFBoundingBox boundingBox) - { - if (boundingBox == null) - { + public VPFBoundingBox union(VPFBoundingBox boundingBox) { + if (boundingBox == null) { String message = Logging.getMessage("nullValue.BoundingBoxIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new VPFBoundingBox( - (this.xmin < boundingBox.xmin) ? this.xmin : boundingBox.xmin, - (this.ymin < boundingBox.ymin) ? this.ymin : boundingBox.ymin, - (this.xmax > boundingBox.xmax) ? this.xmax : boundingBox.xmax, - (this.ymax > boundingBox.ymax) ? this.ymax : boundingBox.ymax); + (this.xmin < boundingBox.xmin) ? this.xmin : boundingBox.xmin, + (this.ymin < boundingBox.ymin) ? this.ymin : boundingBox.ymin, + (this.xmax > boundingBox.xmax) ? this.xmax : boundingBox.xmax, + (this.ymax > boundingBox.ymax) ? this.ymax : boundingBox.ymax); } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("xmin=").append(this.xmin).append(", "); @@ -80,17 +71,14 @@ public String toString() return sb.toString(); } - public static VPFBoundingBox fromVecBuffer(VecBuffer buffer) - { - if (buffer == null) - { + public static VPFBoundingBox fromVecBuffer(VecBuffer buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer.getCoordsPerVec() < 2) - { + if (buffer.getCoordsPerVec() < 2) { String message = Logging.getMessage("generic.BufferIncompatible", buffer); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -104,19 +92,22 @@ public static VPFBoundingBox fromVecBuffer(VecBuffer buffer) int bufferSize = buffer.getSize(); double[] compArray = new double[2]; - for (int i = 0; i < bufferSize; i++) - { + for (int i = 0; i < bufferSize; i++) { buffer.get(i, compArray); - if (xmin > compArray[0]) + if (xmin > compArray[0]) { xmin = compArray[0]; - if (xmax < compArray[0]) + } + if (xmax < compArray[0]) { xmax = compArray[0]; + } - if (ymin > compArray[1]) + if (ymin > compArray[1]) { ymin = compArray[1]; - if (ymax < compArray[1]) + } + if (ymax < compArray[1]) { ymax = compArray[1]; + } } return new VPFBoundingBox(xmin, ymin, xmax, ymax); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFBufferedRecordData.java b/src/gov/nasa/worldwind/formats/vpf/VPFBufferedRecordData.java index 6220b7f5cf..2a00a13e0c 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFBufferedRecordData.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFBufferedRecordData.java @@ -13,40 +13,33 @@ * @author dcollins * @version $Id: VPFBufferedRecordData.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFBufferedRecordData implements Iterable -{ - protected static class RecordData - { +public class VPFBufferedRecordData implements Iterable { + + protected static class RecordData { + public VPFDataBuffer dataBuffer; protected Map recordIndex; - public RecordData(VPFDataBuffer dataBuffer) - { + public RecordData(VPFDataBuffer dataBuffer) { this.dataBuffer = dataBuffer; } - public boolean hasIndex() - { + public boolean hasIndex() { return this.recordIndex != null; } - public int indexOf(Object value, int startIndex, int endIndex) - { + public int indexOf(Object value, int startIndex, int endIndex) { int index = -1; - if (this.recordIndex != null) - { + if (this.recordIndex != null) { Integer i = this.recordIndex.get(value); - if (i != null) + if (i != null) { index = i; - } - else - { - for (int i = startIndex; i <= endIndex; i++) - { + } + } else { + for (int i = startIndex; i <= endIndex; i++) { Object o = this.dataBuffer.get(i); - if ((o != null) ? o.equals(value) : (value == null)) - { + if ((o != null) ? o.equals(value) : (value == null)) { index = i; break; } @@ -56,15 +49,14 @@ public int indexOf(Object value, int startIndex, int endIndex) return index; } - public boolean updateIndex(int startIndex, int endIndex) - { - if (this.recordIndex == null) + public boolean updateIndex(int startIndex, int endIndex) { + if (this.recordIndex == null) { this.recordIndex = new HashMap(); + } this.recordIndex.clear(); - for (int index = startIndex; index <= endIndex; index++) - { + for (int index = startIndex; index <= endIndex; index++) { Object o = this.dataBuffer.get(index); this.recordIndex.put(o, index); } @@ -76,29 +68,23 @@ public boolean updateIndex(int startIndex, int endIndex) private int numRecords; private Map dataMap = new HashMap(); - public VPFBufferedRecordData() - { + public VPFBufferedRecordData() { } - public int getNumRecords() - { + public int getNumRecords() { return this.numRecords; } - public void setNumRecords(int numRecords) - { + public void setNumRecords(int numRecords) { this.numRecords = numRecords; } - public Iterable getRecordParameterNames() - { + public Iterable getRecordParameterNames() { return Collections.unmodifiableSet(this.dataMap.keySet()); } - public VPFDataBuffer getRecordData(String parameterName) - { - if (parameterName == null) - { + public VPFDataBuffer getRecordData(String parameterName) { + if (parameterName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -108,29 +94,22 @@ public VPFDataBuffer getRecordData(String parameterName) return (data != null) ? data.dataBuffer : null; } - public void setRecordData(String parameterName, VPFDataBuffer dataBuffer) - { - if (parameterName == null) - { + public void setRecordData(String parameterName, VPFDataBuffer dataBuffer) { + if (parameterName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dataBuffer != null) - { + if (dataBuffer != null) { this.dataMap.put(parameterName, new RecordData(dataBuffer)); - } - else - { + } else { this.dataMap.remove(parameterName); } } - public VPFRecord getRecord(int id) - { - if (id < 1 || id > this.numRecords) - { + public VPFRecord getRecord(int id) { + if (id < 1 || id > this.numRecords) { String message = Logging.getMessage("generic.indexOutOfRange", id); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -139,18 +118,15 @@ public VPFRecord getRecord(int id) return new RecordImpl(id); } - public VPFRecord getRecord(String parameterName, Object value) - { - if (parameterName == null) - { + public VPFRecord getRecord(String parameterName, Object value) { + if (parameterName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RecordData data = this.dataMap.get(parameterName); - if (data == null) - { + if (data == null) { return null; } @@ -158,34 +134,27 @@ public VPFRecord getRecord(String parameterName, Object value) return (index > 0) ? new RecordImpl(index) : null; } - public Iterator iterator() - { - return new Iterator() - { + public Iterator iterator() { + return new Iterator() { private int id = 0; private int maxId = numRecords; - public boolean hasNext() - { + public boolean hasNext() { return this.id < this.maxId; } - public VPFRecord next() - { + public VPFRecord next() { return new RecordImpl(++this.id); } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } }; } - public boolean buildRecordIndex(String parameterName) - { - if (parameterName == null) - { + public boolean buildRecordIndex(String parameterName) { + if (parameterName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -195,37 +164,31 @@ public boolean buildRecordIndex(String parameterName) return (data != null) && data.updateIndex(1, this.numRecords); } - public static int indexFromId(int rowId) - { + public static int indexFromId(int rowId) { return rowId - 1; } //**************************************************************// //******************** Record Implementation *****************// //**************************************************************// + protected class RecordImpl implements VPFRecord { - protected class RecordImpl implements VPFRecord - { protected final int id; - public RecordImpl(int id) - { + public RecordImpl(int id) { this.id = id; } - public int getId() - { + public int getId() { return this.id; } - public boolean hasValue(String parameterName) - { + public boolean hasValue(String parameterName) { VPFDataBuffer dataBuffer = getRecordData(parameterName); return (dataBuffer != null) && dataBuffer.hasValue(this.id); } - public Object getValue(String parameterName) - { + public Object getValue(String parameterName) { VPFDataBuffer dataBuffer = getRecordData(parameterName); return (dataBuffer != null) ? dataBuffer.get(this.id) : null; } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFConstants.java b/src/gov/nasa/worldwind/formats/vpf/VPFConstants.java index c7513eff72..5cafc817dc 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFConstants.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFConstants.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: VPFConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface VPFConstants -{ +public interface VPFConstants { + // Column Types // DIGEST Part 2, Annex C, Table C-11 final String TEXT = "T"; // Text (US ASCII) diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFCoverage.java b/src/gov/nasa/worldwind/formats/vpf/VPFCoverage.java index ac1a4cfc8b..aaab039075 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFCoverage.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFCoverage.java @@ -14,14 +14,14 @@ /** * DIGEST Part 2, Annex C.2.2.2.3:
        A coverage is composed of features whose primitives maintain topological - * relationships according to a level of topology (level 0, 1, 2, or 3) defined for the coverage. All of the file + * relationships according to a level of topology (level 0, 1, 2, or 3) defined for the coverage. All of the file * structures that make up a coverage are stored in a directory or subdirectories of that directory. * * @author dcollins * @version $Id: VPFCoverage.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFCoverage extends AVListImpl -{ +public class VPFCoverage extends AVListImpl { + private VPFLibrary library; private boolean tiled; private VPFBufferedRecordData featureClassSchemaTable; @@ -30,10 +30,8 @@ public class VPFCoverage extends AVListImpl private VPFBufferedRecordData integerValueDescriptionTable; private VPFBufferedRecordData symbolRelatedAttributeTable; - protected VPFCoverage(VPFLibrary library) - { - if (library == null) - { + protected VPFCoverage(VPFLibrary library) { + if (library == null) { String message = Logging.getMessage("nullValue.LibraryIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -48,31 +46,27 @@ protected VPFCoverage(VPFLibrary library) * Descrption table, and the Symbol Related Attribute table. * * @param library the Library which the Coverage resides in. - * @param name the Coverage's name. + * @param name the Coverage's name. * * @return a new Coverage from the specified Library with the specified name. * * @throws IllegalArgumentException if the library is null, or if the name is null or empty. */ - public static VPFCoverage fromFile(VPFLibrary library, String name) - { - if (library == null) - { + public static VPFCoverage fromFile(VPFLibrary library, String name) { + if (library == null) { String message = Logging.getMessage("nullValue.LibraryIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(name)) - { + if (WWUtil.isEmpty(name)) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File file = new File(library.getFilePath(), name); - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file.getPath()); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -80,20 +74,19 @@ public static VPFCoverage fromFile(VPFLibrary library, String name) // Coverage tables. VPFBufferedRecordData fcs = VPFUtils.readTable(new File(file, VPFConstants.FEATURE_CLASS_SCHEMA_TABLE)); - if (fcs == null) - { + if (fcs == null) { String message = Logging.getMessage("VPF.FeatureClassSchemaTableMissing"); throw new WWRuntimeException(message); } VPFBufferedRecordData fca = VPFUtils.readTable( - new File(file, VPFConstants.FEATURE_CLASS_ATTRIBUTE_TABLE)); + new File(file, VPFConstants.FEATURE_CLASS_ATTRIBUTE_TABLE)); VPFBufferedRecordData char_vdt = VPFUtils.readTable( - new File(file, VPFConstants.CHARACTER_VALUE_DESCRIPTION_TABLE)); + new File(file, VPFConstants.CHARACTER_VALUE_DESCRIPTION_TABLE)); VPFBufferedRecordData int_vdt = VPFUtils.readTable( - new File(file, VPFConstants.INTEGER_VALUE_DESCRIPTION_TABLE)); + new File(file, VPFConstants.INTEGER_VALUE_DESCRIPTION_TABLE)); VPFBufferedRecordData symbol_rat = VPFUtils.readTable( - new File(file, "symbol" + VPFConstants.RELATED_ATTRIBUTE_TABLE)); + new File(file, "symbol" + VPFConstants.RELATED_ATTRIBUTE_TABLE)); VPFCoverage coverage = new VPFCoverage(library); coverage.setFeatureClassSchemaTable(fcs); @@ -104,8 +97,7 @@ public static VPFCoverage fromFile(VPFLibrary library, String name) // Coverage metadata attributes. VPFRecord record = library.getCoverageAttributeTable().getRecord("coverage_name", name); - if (record != null) - { + if (record != null) { VPFUtils.checkAndSetValue(record, "coverage_name", AVKey.DISPLAY_NAME, coverage); VPFUtils.checkAndSetValue(record, "description", AVKey.DESCRIPTION, coverage); } @@ -113,8 +105,7 @@ public static VPFCoverage fromFile(VPFLibrary library, String name) return coverage; } - public VPFLibrary getLibrary() - { + public VPFLibrary getLibrary() { return this.library; } @@ -123,8 +114,7 @@ public VPFLibrary getLibrary() * * @return name of this Coverage. */ - public String getName() - { + public String getName() { return this.getStringValue(AVKey.DISPLAY_NAME); } @@ -133,42 +123,35 @@ public String getName() * * @return description of this Coverager. */ - public String getDescription() - { + public String getDescription() { return this.getStringValue(AVKey.DESCRIPTION); } - public String getFilePath() - { + public String getFilePath() { StringBuilder sb = new StringBuilder(this.library.getFilePath()); sb.append(File.separator); sb.append(this.getName()); return sb.toString(); } - public boolean isReferenceCoverage() - { + public boolean isReferenceCoverage() { String name = this.getName(); return name.equalsIgnoreCase(VPFConstants.DATA_QUALITY_COVERAGE) - || name.equalsIgnoreCase(VPFConstants.LIBRARY_REFERENCE_COVERAGE) - || name.equalsIgnoreCase(VPFConstants.NAMES_REFERENCE_COVERAGE) - || name.equalsIgnoreCase(VPFConstants.TILE_REFERENCE_COVERAGE); + || name.equalsIgnoreCase(VPFConstants.LIBRARY_REFERENCE_COVERAGE) + || name.equalsIgnoreCase(VPFConstants.NAMES_REFERENCE_COVERAGE) + || name.equalsIgnoreCase(VPFConstants.TILE_REFERENCE_COVERAGE); } - public boolean isTiled() - { + public boolean isTiled() { return this.tiled; } - public void setTiled(boolean tiled) - { + public void setTiled(boolean tiled) { this.tiled = tiled; } - public VPFFeatureClassSchema[] getFeatureClasses(FileFilter featureTableFilter) - { - if (featureTableFilter == null) - { + public VPFFeatureClassSchema[] getFeatureClasses(FileFilter featureTableFilter) { + if (featureTableFilter == null) { String message = Logging.getMessage("nullValue.FilterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -176,30 +159,31 @@ public VPFFeatureClassSchema[] getFeatureClasses(FileFilter featureTableFilter) // List the file names in the coverage directory matching the specified feature table file filter. String[] names = WWIO.listChildFilenames(new File(this.getFilePath()), featureTableFilter); - if (names == null) + if (names == null) { return null; + } int numFeatures = names.length; VPFFeatureClassSchema[] desc = new VPFFeatureClassSchema[numFeatures]; - for (int i = 0; i < numFeatures; i++) - { + for (int i = 0; i < numFeatures; i++) { String featureTableName = names[i]; String className = WWIO.replaceSuffix(featureTableName, ""); String type = null; // If the Feature Class Attriute Table is available, then use it to determine the feature type for the // specified class. - if (this.featureClassAttributeTable != null) - { + if (this.featureClassAttributeTable != null) { VPFRecord record = this.featureClassAttributeTable.getRecord("fclass", className); - if (record != null) + if (record != null) { type = (String) record.getValue("type"); + } } // Otherwise, determine the feature type is based on the feature table extension. - if (type == null) + if (type == null) { type = VPFUtils.getFeatureTypeName(featureTableName); + } desc[i] = new VPFFeatureClassSchema(className, VPFFeatureType.fromTypeName(type), featureTableName); } @@ -207,10 +191,8 @@ public VPFFeatureClassSchema[] getFeatureClasses(FileFilter featureTableFilter) return desc; } - public VPFRelation[] getFeatureClassRelations(String className) - { - if (className == null) - { + public VPFRelation[] getFeatureClassRelations(String className) { + if (className == null) { String message = Logging.getMessage("nullValue.ClassNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -218,20 +200,21 @@ public VPFRelation[] getFeatureClassRelations(String className) ArrayList rels = new ArrayList(); - for (VPFRecord row : this.featureClassSchemaTable) - { + for (VPFRecord row : this.featureClassSchemaTable) { Object o = row.getValue("feature_class"); - if (o == null || !(o instanceof String)) + if (o == null || !(o instanceof String)) { continue; + } - if (!className.equalsIgnoreCase((String) o)) + if (!className.equalsIgnoreCase((String) o)) { continue; + } rels.add(new VPFRelation( - (String) row.getValue("table1"), - (String) row.getValue("table1_key"), - (String) row.getValue("table2"), - (String) row.getValue("table2_key"))); + (String) row.getValue("table1"), + (String) row.getValue("table1_key"), + (String) row.getValue("table2"), + (String) row.getValue("table2_key"))); } VPFRelation[] array = new VPFRelation[rels.size()]; @@ -239,53 +222,43 @@ public VPFRelation[] getFeatureClassRelations(String className) return array; } - public VPFBufferedRecordData getFeatureClassSchemaTable() - { + public VPFBufferedRecordData getFeatureClassSchemaTable() { return this.featureClassSchemaTable; } - public void setFeatureClassSchemaTable(VPFBufferedRecordData table) - { + public void setFeatureClassSchemaTable(VPFBufferedRecordData table) { this.featureClassSchemaTable = table; } - public VPFBufferedRecordData getFeatureClassAttributeTable() - { + public VPFBufferedRecordData getFeatureClassAttributeTable() { return this.featureClassAttributeTable; } - public void setFeatureClassAttributeTable(VPFBufferedRecordData table) - { + public void setFeatureClassAttributeTable(VPFBufferedRecordData table) { this.featureClassAttributeTable = table; } - public VPFBufferedRecordData getCharacterValueDescriptionTable() - { + public VPFBufferedRecordData getCharacterValueDescriptionTable() { return this.characterValueDescriptionTable; } - public void setCharacterValueDescriptionTable(VPFBufferedRecordData table) - { + public void setCharacterValueDescriptionTable(VPFBufferedRecordData table) { this.characterValueDescriptionTable = table; } - public VPFBufferedRecordData getIntegerValueDescriptionTable() - { + public VPFBufferedRecordData getIntegerValueDescriptionTable() { return this.integerValueDescriptionTable; } - public void setIntegerValueDescriptionTable(VPFBufferedRecordData table) - { + public void setIntegerValueDescriptionTable(VPFBufferedRecordData table) { this.integerValueDescriptionTable = table; } - public VPFBufferedRecordData getSymbolRelatedAttributeTable() - { + public VPFBufferedRecordData getSymbolRelatedAttributeTable() { return this.symbolRelatedAttributeTable; } - public void setSymbolRelatedAttributeTable(VPFBufferedRecordData table) - { + public void setSymbolRelatedAttributeTable(VPFBufferedRecordData table) { this.symbolRelatedAttributeTable = table; } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFCoveragePanel.java b/src/gov/nasa/worldwind/formats/vpf/VPFCoveragePanel.java index 757f48b6df..c4080d9f61 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFCoveragePanel.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFCoveragePanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.vpf; import gov.nasa.worldwind.WorldWindow; @@ -31,8 +30,8 @@ * * @version $Id: VPFCoveragePanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFCoveragePanel extends JPanel -{ +public class VPFCoveragePanel extends JPanel { + private WorldWindow wwd; private Dimension preferredSize; private JTabbedPane libraryTabbedPane; @@ -40,34 +39,29 @@ public class VPFCoveragePanel extends JPanel private JPanel legendPanel; - public VPFCoveragePanel(WorldWindow wwd, VPFDatabase db) - { + public VPFCoveragePanel(WorldWindow wwd, VPFDatabase db) { // Make a panel at a default size. super(new BorderLayout()); this.wwd = wwd; this.makePanel(db, new Dimension(200, 400)); } - public VPFCoveragePanel(VPFDatabase db, Dimension size) - { + public VPFCoveragePanel(VPFDatabase db, Dimension size) { // Make a panel at a specified size. super(new BorderLayout()); this.makePanel(db, size); } - public VPFLayer getLayer() - { + public VPFLayer getLayer() { return this.layer; } - public void setLayer(VPFLayer layer) - { + public void setLayer(VPFLayer layer) { this.layer = layer; this.fillLegendPanel(); } - private void makePanel(VPFDatabase db, Dimension size) - { + private void makePanel(VPFDatabase db, Dimension size) { this.preferredSize = size; this.libraryTabbedPane = new JTabbedPane(); this.add(this.libraryTabbedPane, BorderLayout.CENTER); @@ -76,27 +70,23 @@ private void makePanel(VPFDatabase db, Dimension size) this.startLegendUpdateTimer(); } - private void fill(VPFDatabase db) - { + private void fill(VPFDatabase db) { this.addDatabase(db); this.addLegend(); } - public void addDatabase(VPFDatabase db) - { + public void addDatabase(VPFDatabase db) { // Sort the library list alphabetically. ArrayList sortedList = new ArrayList(); sortedList.addAll(db.getLibraries()); this.sortPropertyLists(sortedList, AVKey.DISPLAY_NAME); - for (VPFLibrary lib : sortedList) - { + for (VPFLibrary lib : sortedList) { this.addLibrary(db, lib); } } - public void addLibrary(VPFDatabase db, VPFLibrary lib) - { + public void addLibrary(VPFDatabase db, VPFLibrary lib) { // Make and fill the panel holding the library coverages. JPanel selectionPanel = new JPanel(new GridLayout(0, 1, 0, 4)); selectionPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); @@ -108,13 +98,14 @@ public void addLibrary(VPFDatabase db, VPFLibrary lib) // Put the name panel in a scroll bar. JScrollPane scrollPane = new JScrollPane(dummyPanel); scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); - if (this.preferredSize != null) + if (this.preferredSize != null) { scrollPane.setPreferredSize(this.preferredSize); + } // Add the scroll bar and name panel to a titled panel that will resize with the main window. JPanel westPanel = new JPanel(new GridLayout(0, 1, 0, 0)); westPanel.setBorder( - new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Coverage"))); + new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Coverage"))); westPanel.setToolTipText("Coverage to Show"); westPanel.add(scrollPane); @@ -149,21 +140,18 @@ public void addLibrary(VPFDatabase db, VPFLibrary lib) sortedList.addAll(lib.getCoverages()); this.sortPropertyLists(sortedList, AVKey.DESCRIPTION); - for (VPFCoverage cov : sortedList) - { - if (cov.isReferenceCoverage()) + for (VPFCoverage cov : sortedList) { + if (cov.isReferenceCoverage()) { continue; + } this.addCoverage(db, cov, selectionPanel); } } - protected void sortPropertyLists(java.util.List propertyList, final String propertyName) - { - Collections.sort(propertyList, new Comparator() - { - public int compare(AVList a, AVList b) - { + protected void sortPropertyLists(java.util.List propertyList, final String propertyName) { + Collections.sort(propertyList, new Comparator() { + public int compare(AVList a, AVList b) { String aValue = (a.getValue(propertyName) != null) ? a.getValue(propertyName).toString() : ""; String bValue = (b.getValue(propertyName) != null) ? b.getValue(propertyName).toString() : ""; return String.CASE_INSENSITIVE_ORDER.compare(aValue, bValue); @@ -171,8 +159,7 @@ public int compare(AVList a, AVList b) }); } - public void addLegend() - { + public void addLegend() { // Make and fill the panel holding the legend items. this.legendPanel = new JPanel(); this.legendPanel.setLayout(new BoxLayout(this.legendPanel, BoxLayout.PAGE_AXIS)); @@ -185,13 +172,14 @@ public void addLegend() // Put the panel in a scroll bar. JScrollPane scrollPane = new JScrollPane(dummyPanel); scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); - if (this.preferredSize != null) + if (this.preferredSize != null) { scrollPane.setPreferredSize(this.preferredSize); + } // Add the scroll bar and panel to a titled panel that will resize with the main window. JPanel westPanel = new JPanel(new GridLayout(0, 1, 0, 0)); westPanel.setBorder( - new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Legend"))); + new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Legend"))); westPanel.setToolTipText("VPF Layer Legend"); westPanel.add(scrollPane); westPanel.setAlignmentX(Component.LEFT_ALIGNMENT); @@ -207,16 +195,17 @@ public void addLegend() this.libraryTabbedPane.add("Legend", dummyPanel); } - protected void fillLegendPanel() - { + protected void fillLegendPanel() { this.legendPanel.removeAll(); - if (this.layer == null) + if (this.layer == null) { return; + } Iterable symbols = this.layer.getActiveSymbols(); - if (symbols == null) + if (symbols == null) { return; + } // Sort rendering attributes, and eliminate duplicate entries. Iterable symbolInfo = this.getUniqueSymbols(symbols); @@ -224,13 +213,12 @@ protected void fillLegendPanel() // Compose legend panel VPFLegendSupport legendSupport = new VPFLegendSupport(); String coverageName = null; - for (SymbolInfo info : symbolInfo) - { + for (SymbolInfo info : symbolInfo) { // Insert coverage title - if (coverageName == null || !info.getFeatureClass().getCoverage().getName().equals(coverageName)) - { - if (coverageName != null) + if (coverageName == null || !info.getFeatureClass().getCoverage().getName().equals(coverageName)) { + if (coverageName != null) { this.legendPanel.add(Box.createVerticalStrut(5)); + } JLabel label = new JLabel(info.getFeatureClass().getCoverage().getDescription()); this.legendPanel.add(label); coverageName = info.getFeatureClass().getCoverage().getName(); @@ -239,11 +227,11 @@ protected void fillLegendPanel() } // Add legend item String description = info.getDescription() != null ? info.getDescription() : ""; - if (description.length() > 0) + if (description.length() > 0) { description = description.substring(0, 1).toUpperCase() + description.substring(1); + } BufferedImage legendImage = legendSupport.createLegendImage(info.getAttributes(), 60, 22, 0); - if (legendImage != null && description.length() > 0) - { + if (legendImage != null && description.length() > 0) { Icon icon = new ImageIcon(legendImage); JLabel label = new JLabel(description, icon, SwingConstants.LEFT); label.setIconTextGap(8); @@ -256,31 +244,30 @@ protected void fillLegendPanel() this.legendPanel.repaint(); } - protected Iterable getUniqueSymbols(Iterable iterable) - { + protected Iterable getUniqueSymbols(Iterable iterable) { // Use a TreeSet to consolidate duplicate symbol attributes and simultaneously sort the attributes. - Set set = new TreeSet(new Comparator() - { - public int compare(SymbolInfo a, SymbolInfo b) - { + Set set = new TreeSet(new Comparator() { + public int compare(SymbolInfo a, SymbolInfo b) { String aCoverageName = (a.getFeatureClass().getCoverage().getName() != null) - ? a.getFeatureClass().getCoverage().getName() : ""; + ? a.getFeatureClass().getCoverage().getName() : ""; String bCoverageName = (b.getFeatureClass().getCoverage().getName() != null) - ? b.getFeatureClass().getCoverage().getName() : ""; + ? b.getFeatureClass().getCoverage().getName() : ""; int i = String.CASE_INSENSITIVE_ORDER.compare(aCoverageName, bCoverageName); - if (i != 0) + if (i != 0) { return i; + } String aKey = (a.getAttributes().getSymbolKey() != null) ? a.getAttributes().getSymbolKey().toString() - : ""; + : ""; String bKey = (b.getAttributes().getSymbolKey() != null) ? b.getAttributes().getSymbolKey().toString() - : ""; + : ""; i = String.CASE_INSENSITIVE_ORDER.compare(aKey, bKey); - if (i != 0) + if (i != 0) { return i; + } int aType = (a.getFeatureClass().getType() != null) ? a.getFeatureClass().getType().ordinal() : -1; int bType = (b.getFeatureClass().getType() != null) ? b.getFeatureClass().getType().ordinal() : -1; @@ -289,10 +276,8 @@ public int compare(SymbolInfo a, SymbolInfo b) } }); - for (VPFSymbol symbol : iterable) - { - if (symbol != null && symbol.getFeature() != null && symbol.getAttributes() != null) - { + for (VPFSymbol symbol : iterable) { + if (symbol != null && symbol.getFeature() != null && symbol.getAttributes() != null) { set.add(new SymbolInfo(symbol.getFeature().getFeatureClass(), symbol.getAttributes())); } } @@ -300,43 +285,37 @@ public int compare(SymbolInfo a, SymbolInfo b) return set; } - protected static class SymbolInfo - { + protected static class SymbolInfo { + protected VPFFeatureClass featureClass; protected VPFSymbolAttributes attributes; - public SymbolInfo(VPFFeatureClass featureClass, VPFSymbolAttributes attributes) - { + public SymbolInfo(VPFFeatureClass featureClass, VPFSymbolAttributes attributes) { this.featureClass = featureClass; this.attributes = attributes; } - public VPFFeatureClass getFeatureClass() - { + public VPFFeatureClass getFeatureClass() { return this.featureClass; } - public VPFSymbolAttributes getAttributes() - { + public VPFSymbolAttributes getAttributes() { return this.attributes; } - public String getDescription() - { + public String getDescription() { return this.attributes.getDescription(); } } - protected void addCoverage(VPFDatabase db, VPFCoverage cov, Container parent) - { + protected void addCoverage(VPFDatabase db, VPFCoverage cov, Container parent) { CoverageAction action = new CoverageAction(db, cov, false); // default to non selected JCheckBox jcb = new JCheckBox(action); jcb.setSelected(action.selected); parent.add(jcb); } - public void update(VPFDatabase db) - { + public void update(VPFDatabase db) { // Refresh the coverage list from the given db this.libraryTabbedPane.removeAll(); this.fill(db); @@ -344,33 +323,28 @@ public void update(VPFDatabase db) this.libraryTabbedPane.repaint(); } - public void clear() - { + public void clear() { this.libraryTabbedPane.removeAll(); this.libraryTabbedPane.revalidate(); this.libraryTabbedPane.repaint(); } - private void startLegendUpdateTimer() - { - Timer timer = new Timer(3000, new ActionListener() - { - public void actionPerformed(ActionEvent event) - { + private void startLegendUpdateTimer() { + Timer timer = new Timer(3000, new ActionListener() { + public void actionPerformed(ActionEvent event) { fillLegendPanel(); } }); timer.start(); } - private class LibraryAction extends AbstractAction - { + private class LibraryAction extends AbstractAction { + VPFDatabase db; VPFLibrary library; private boolean selected; - public LibraryAction(VPFDatabase db, VPFLibrary library, boolean selected) - { + public LibraryAction(VPFDatabase db, VPFLibrary library, boolean selected) { super("Show Library"); this.putValue(Action.SHORT_DESCRIPTION, "Show " + library.getName()); this.db = db; @@ -378,25 +352,23 @@ public LibraryAction(VPFDatabase db, VPFLibrary library, boolean selected) this.selected = selected; } - public void actionPerformed(ActionEvent actionEvent) - { + public void actionPerformed(ActionEvent actionEvent) { // Fire property change event on the database boolean newState = ((JCheckBox) actionEvent.getSource()).isSelected(); this.db.firePropertyChange( - new PropertyChangeEvent(this.library, VPFLayer.LIBRARY_CHANGED, this.selected, newState)); + new PropertyChangeEvent(this.library, VPFLayer.LIBRARY_CHANGED, this.selected, newState)); this.selected = newState; wwd.redraw(); } } - private class CoverageAction extends AbstractAction implements PropertyChangeListener - { + private class CoverageAction extends AbstractAction implements PropertyChangeListener { + VPFDatabase db; VPFCoverage coverage; private boolean selected; - public CoverageAction(VPFDatabase db, VPFCoverage coverage, boolean selected) - { + public CoverageAction(VPFDatabase db, VPFCoverage coverage, boolean selected) { super(coverage.getDescription()); this.putValue(Action.SHORT_DESCRIPTION, "Show " + coverage.getDescription()); this.db = db; @@ -406,47 +378,41 @@ public CoverageAction(VPFDatabase db, VPFCoverage coverage, boolean selected) this.setEnabled(false); } - public void actionPerformed(ActionEvent actionEvent) - { + public void actionPerformed(ActionEvent actionEvent) { // Fire property change event on the database boolean newState = ((JCheckBox) actionEvent.getSource()).isSelected(); this.db.firePropertyChange( - new PropertyChangeEvent(this.coverage, VPFLayer.COVERAGE_CHANGED, this.selected, newState)); + new PropertyChangeEvent(this.coverage, VPFLayer.COVERAGE_CHANGED, this.selected, newState)); this.selected = newState; wwd.redraw(); } - public void propertyChange(PropertyChangeEvent event) - { - if (event.getPropertyName().equals(VPFLayer.LIBRARY_CHANGED)) - { + public void propertyChange(PropertyChangeEvent event) { + if (event.getPropertyName().equals(VPFLayer.LIBRARY_CHANGED)) { VPFLibrary library = (VPFLibrary) event.getSource(); boolean enabled = (Boolean) event.getNewValue(); - if (library.getFilePath().equals(this.coverage.getLibrary().getFilePath())) - { + if (library.getFilePath().equals(this.coverage.getLibrary().getFilePath())) { this.setEnabled(enabled); } } } } - private class ZoomAction extends AbstractAction - { + private class ZoomAction extends AbstractAction { + private VPFLibrary library; - private ZoomAction(VPFLibrary library) - { + private ZoomAction(VPFLibrary library) { super("Zoom To Library"); this.library = library; this.setEnabled(this.library.getBounds() != null); } - public void actionPerformed(ActionEvent actionEvent) - { + public void actionPerformed(ActionEvent actionEvent) { Sector sector = this.library.getBounds().toSector(); Extent extent = Sector.computeBoundingCylinder(wwd.getModel().getGlobe(), - wwd.getSceneController().getVerticalExaggeration(), sector); + wwd.getSceneController().getVerticalExaggeration(), sector); Angle fov = wwd.getView().getFieldOfView(); Position centerPos = new Position(sector.getCentroid(), 0d); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFDataBuffer.java b/src/gov/nasa/worldwind/formats/vpf/VPFDataBuffer.java index 7f01120ade..a4a80027d1 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFDataBuffer.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFDataBuffer.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: VPFDataBuffer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface VPFDataBuffer -{ +public interface VPFDataBuffer { + Object get(int index); Object getBackingData(); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFDataBufferFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFDataBufferFactory.java index e67efa16f2..df2cf2055f 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFDataBufferFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFDataBufferFactory.java @@ -9,7 +9,7 @@ * @author dcollins * @version $Id: VPFDataBufferFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface VPFDataBufferFactory -{ +public interface VPFDataBufferFactory { + VPFDataBuffer newDataBuffer(int numRows, int elementsPerRow); } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFDataType.java b/src/gov/nasa/worldwind/formats/vpf/VPFDataType.java index e07759b213..1822f594cf 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFDataType.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFDataType.java @@ -13,8 +13,7 @@ * @author dcollins * @version $Id: VPFDataType.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public enum VPFDataType -{ +public enum VPFDataType { NULL(VPFConstants.NULL, 0, new VPFBasicDataBufferFactory.NullDataFactory()), DATE_AND_TIME(VPFConstants.DATE_AND_TIME, 20, new VPFBasicDataBufferFactory.DateTimeDataFactory()), TRIPLET_ID(VPFConstants.TRIPLET_ID, -1, new VPFBasicDataBufferFactory.TripledIdDataFactory()), @@ -40,26 +39,23 @@ public enum VPFDataType protected VPFDataBufferFactory dataBufferFactory; private static Map nameRegistry; - private VPFDataType(String name, int length, VPFDataBufferFactory dataBufferFactory) - { + private VPFDataType(String name, int length, VPFDataBufferFactory dataBufferFactory) { this.name = name; this.length = length; this.dataBufferFactory = dataBufferFactory; register(name, this); } - private static void register(String name, VPFDataType type) - { - if (nameRegistry == null) + private static void register(String name, VPFDataType type) { + if (nameRegistry == null) { nameRegistry = new HashMap(); + } nameRegistry.put(name, type); } - public static VPFDataType fromTypeName(String name) - { - if (name == null) - { + public static VPFDataType fromTypeName(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -68,25 +64,20 @@ public static VPFDataType fromTypeName(String name) return (nameRegistry != null) ? nameRegistry.get(name) : null; } - public String getFieldName() - { + public String getFieldName() { return this.name; } - public int getFieldLength() - { + public int getFieldLength() { return this.length; } - public boolean isVariableLength() - { + public boolean isVariableLength() { return this.length == -1; } - public VPFDataBuffer createDataBuffer(int numRows, int elementsPerRow) - { - if (numRows < 0) - { + public VPFDataBuffer createDataBuffer(int numRows, int elementsPerRow) { + if (numRows < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "numRows < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFDatabase.java b/src/gov/nasa/worldwind/formats/vpf/VPFDatabase.java index 5f0d5c44a2..f7b485b086 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFDatabase.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFDatabase.java @@ -14,23 +14,21 @@ /** * DIGEST Part 2, Annex C.2.2.2.5 and C.2.3.6:
        A database is a collection of related libraries and additional - * tables. The library attribute table acts as a table of contents for the database. Database information is contained - * in a database header table. Database level data quality information can be maintained in the data quality table. + * tables. The library attribute table acts as a table of contents for the database. Database information is contained + * in a database header table. Database level data quality information can be maintained in the data quality table. * * @author dcollins * @version $Id: VPFDatabase.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFDatabase extends AVListImpl -{ +public class VPFDatabase extends AVListImpl { + private String filePath; private Map libraryMap = new HashMap(); private VPFBufferedRecordData databaseHeaderTable; private VPFBufferedRecordData libraryAttributeTable; - protected VPFDatabase(String filePath) - { - if (filePath == null) - { + protected VPFDatabase(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -49,18 +47,15 @@ protected VPFDatabase(String filePath) * * @throws IllegalArgumentException if the file path is null or empty. */ - public static VPFDatabase fromFile(String filePath) - { - if (WWUtil.isEmpty(filePath)) - { + public static VPFDatabase fromFile(String filePath) { + if (WWUtil.isEmpty(filePath)) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File file = new File(filePath); - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", filePath); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -68,16 +63,14 @@ public static VPFDatabase fromFile(String filePath) // Database tables. VPFBufferedRecordData dht = VPFUtils.readTable(file); - if (dht == null) - { + if (dht == null) { String message = Logging.getMessage("VPF.DatabaseHeaderTableMissing"); throw new WWRuntimeException(message); } VPFBufferedRecordData lat = VPFUtils.readTable( - new File(file.getParent(), VPFConstants.LIBRARY_ATTRIBUTE_TABLE)); - if (lat == null) - { + new File(file.getParent(), VPFConstants.LIBRARY_ATTRIBUTE_TABLE)); + if (lat == null) { String message = Logging.getMessage("VPF.LibraryAttributeTableMissing"); throw new WWRuntimeException(message); } @@ -88,51 +81,52 @@ public static VPFDatabase fromFile(String filePath) // Database metadata attributes. VPFRecord record = dht.getRecord(1); - if (record != null) - { + if (record != null) { VPFUtils.checkAndSetValue(record, "database_name", AVKey.DISPLAY_NAME, database); VPFUtils.checkAndSetValue(record, "database_desc", AVKey.DESCRIPTION, database); } // Database Libraries. Collection col = createLibraries(database, lat); - if (col != null) + if (col != null) { database.setLibraries(col); + } return database; } - public static boolean isDatabase(String filePath) - { - if (filePath == null) - { + public static boolean isDatabase(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File file = new File(filePath); - if (!file.exists()) + if (!file.exists()) { return false; + } VPFBufferedRecordData table = VPFUtils.readTable(file); - if (table == null) + if (table == null) { return false; + } file = new File(file.getParent(), VPFConstants.LIBRARY_ATTRIBUTE_TABLE); - if (!file.exists()) + if (!file.exists()) { return false; + } table = VPFUtils.readTable(file); //noinspection RedundantIfStatement - if (table == null) + if (table == null) { return false; + } return true; } - public String getFilePath() - { + public String getFilePath() { return this.filePath; } @@ -141,8 +135,7 @@ public String getFilePath() * * @return name of this Database. */ - public String getName() - { + public String getName() { return this.getStringValue(AVKey.DISPLAY_NAME); } @@ -151,8 +144,7 @@ public String getName() * * @return description of this Database. */ - public String getDescription() - { + public String getDescription() { return this.getStringValue(AVKey.DESCRIPTION); } @@ -162,15 +154,12 @@ public String getDescription() * * @return number of Libraries associated with this Database. */ - public int getNumLibraries() - { + public int getNumLibraries() { return this.libraryMap.size(); } - public boolean containsLibrary(String name) - { - if (name == null) - { + public boolean containsLibrary(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -179,10 +168,8 @@ public boolean containsLibrary(String name) return this.libraryMap.containsKey(name); } - public VPFLibrary getLibrary(String name) - { - if (name == null) - { + public VPFLibrary getLibrary(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -191,28 +178,24 @@ public VPFLibrary getLibrary(String name) return this.libraryMap.get(name); } - public Set getLibraryNames() - { + public Set getLibraryNames() { return Collections.unmodifiableSet(this.libraryMap.keySet()); } - public Collection getLibraries() - { + public Collection getLibraries() { return Collections.unmodifiableCollection(this.libraryMap.values()); } - public void setLibraries(Collection collection) - { + public void setLibraries(Collection collection) { this.removeAllLibraries(); - if (collection != null) + if (collection != null) { this.addAllLibraries(collection); + } } - public void addLibrary(VPFLibrary library) - { - if (library == null) - { + public void addLibrary(VPFLibrary library) { + if (library == null) { String message = Logging.getMessage("nullValue.LibraryIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -221,25 +204,20 @@ public void addLibrary(VPFLibrary library) this.libraryMap.put(library.getName(), library); } - public void addAllLibraries(Collection collection) - { - if (collection == null) - { + public void addAllLibraries(Collection collection) { + if (collection == null) { String message = Logging.getMessage("nullValue.CollectionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (VPFLibrary lib : collection) - { + for (VPFLibrary lib : collection) { this.addLibrary(lib); } } - public void removeLibrary(VPFLibrary library) - { - if (library == null) - { + public void removeLibrary(VPFLibrary library) { + if (library == null) { String message = Logging.getMessage("nullValue.LibraryIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -248,8 +226,7 @@ public void removeLibrary(VPFLibrary library) this.libraryMap.remove(library.getName()); } - public void removeAllLibraries() - { + public void removeAllLibraries() { this.libraryMap.clear(); } @@ -258,8 +235,7 @@ public void removeAllLibraries() * * @return the Database Header Table. */ - public VPFBufferedRecordData getDatabaseHeaderTable() - { + public VPFBufferedRecordData getDatabaseHeaderTable() { return this.databaseHeaderTable; } @@ -270,10 +246,8 @@ public VPFBufferedRecordData getDatabaseHeaderTable() * * @throws IllegalArgumentException if the table is null. */ - public void setDatabaseHeaderTable(VPFBufferedRecordData table) - { - if (table == null) - { + public void setDatabaseHeaderTable(VPFBufferedRecordData table) { + if (table == null) { String message = Logging.getMessage("nullValue.TableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -287,8 +261,7 @@ public void setDatabaseHeaderTable(VPFBufferedRecordData table) * * @return the Library Attribute Table. */ - public VPFBufferedRecordData getLibraryAttributeTable() - { + public VPFBufferedRecordData getLibraryAttributeTable() { return this.libraryAttributeTable; } @@ -299,10 +272,8 @@ public VPFBufferedRecordData getLibraryAttributeTable() * * @throws IllegalArgumentException if the table is null. */ - public void setLibraryAttributeTable(VPFBufferedRecordData table) - { - if (table == null) - { + public void setLibraryAttributeTable(VPFBufferedRecordData table) { + if (table == null) { String message = Logging.getMessage("nullValue.TableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -314,19 +285,16 @@ public void setLibraryAttributeTable(VPFBufferedRecordData table) //**************************************************************// //******************** Library Assembly **********************// //**************************************************************// - - protected static Collection createLibraries(VPFDatabase db, VPFBufferedRecordData table) - { + protected static Collection createLibraries(VPFDatabase db, VPFBufferedRecordData table) { ArrayList list = new ArrayList(); - for (VPFRecord row : table) - { + for (VPFRecord row : table) { String name = (String) row.getValue("library_name"); - if (name != null) - { + if (name != null) { VPFLibrary lib = VPFUtils.readLibrary(db, name); - if (lib != null) + if (lib != null) { list.add(lib); + } } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFDatabaseFilter.java b/src/gov/nasa/worldwind/formats/vpf/VPFDatabaseFilter.java index c372c86248..322580c277 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFDatabaseFilter.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFDatabaseFilter.java @@ -11,11 +11,12 @@ * @author dcollins * @version $Id: VPFDatabaseFilter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFDatabaseFilter implements java.io.FileFilter -{ - /** Constructs a VPFDatabaseFilter. */ - public VPFDatabaseFilter() - { +public class VPFDatabaseFilter implements java.io.FileFilter { + + /** + * Constructs a VPFDatabaseFilter. + */ + public VPFDatabaseFilter() { } /** @@ -27,25 +28,21 @@ public VPFDatabaseFilter() * * @throws IllegalArgumentException if the file is null. */ - public boolean accept(java.io.File file) - { - if (file == null) - { + public boolean accept(java.io.File file) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // First check the file path, optionally returning false if the path cannot be accepted for any reason. - if (!this.acceptFilePath(file)) + if (!this.acceptFilePath(file)) { return false; + } - try - { + try { return VPFDatabase.isDatabase(file.getPath()); - } - catch (Exception e) - { + } catch (Exception e) { // Not interested in logging or reporting the exception; just return false indicating that the file is not // a VPF database. } @@ -53,10 +50,8 @@ public boolean accept(java.io.File file) return false; } - protected boolean acceptFilePath(java.io.File file) - { - if (file == null) - { + protected boolean acceptFilePath(java.io.File file) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFFeature.java b/src/gov/nasa/worldwind/formats/vpf/VPFFeature.java index 0584854625..9732f43a76 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFFeature.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFFeature.java @@ -12,24 +12,21 @@ * @author dcollins * @version $Id: VPFFeature.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFFeature extends AVListImpl -{ +public class VPFFeature extends AVListImpl { + protected VPFFeatureClass featureClass; protected int id; protected VPFBoundingBox bounds; private int[] primitiveIds; - public VPFFeature(VPFFeatureClass featureClass, int id, VPFBoundingBox bounds, int[] primitiveIds) - { - if (featureClass == null) - { + public VPFFeature(VPFFeatureClass featureClass, int id, VPFBoundingBox bounds, int[] primitiveIds) { + if (featureClass == null) { String message = Logging.getMessage("nullValue.FeatureClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bounds == null) - { + if (bounds == null) { String message = Logging.getMessage("nullValue.BoundingBoxIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -41,28 +38,23 @@ public VPFFeature(VPFFeatureClass featureClass, int id, VPFBoundingBox bounds, i this.primitiveIds = primitiveIds; } - public VPFFeatureClass getFeatureClass() - { + public VPFFeatureClass getFeatureClass() { return this.featureClass; } - public VPFFeatureType getType() - { + public VPFFeatureType getType() { return this.featureClass.getType(); } - public int getId() - { + public int getId() { return this.id; } - public VPFBoundingBox getBounds() - { + public VPFBoundingBox getBounds() { return this.bounds; } - public int[] getPrimitiveIds() - { + public int[] getPrimitiveIds() { return this.primitiveIds; } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClass.java b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClass.java index a411d06084..b35e568359 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClass.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClass.java @@ -13,8 +13,8 @@ * @author dcollins * @version $Id: VPFFeatureClass.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFFeatureClass extends AVListImpl -{ +public class VPFFeatureClass extends AVListImpl { + protected VPFCoverage coverage; protected VPFFeatureClassSchema schema; protected VPFRelation[] relations; @@ -22,97 +22,90 @@ public class VPFFeatureClass extends AVListImpl protected String primitiveTableName; public VPFFeatureClass(VPFCoverage coverage, VPFFeatureClassSchema schema, String joinTableName, - String primitiveTableName) - { + String primitiveTableName) { this.coverage = coverage; this.schema = schema; this.joinTableName = joinTableName; this.primitiveTableName = primitiveTableName; } - public VPFCoverage getCoverage() - { + public VPFCoverage getCoverage() { return this.coverage; } - public VPFFeatureClassSchema getSchema() - { + public VPFFeatureClassSchema getSchema() { return this.schema; } - public String getClassName() - { + public String getClassName() { return this.schema.getClassName(); } - public VPFFeatureType getType() - { + public VPFFeatureType getType() { return this.schema.getType(); } - public String getFeatureTableName() - { + public String getFeatureTableName() { return this.schema.getFeatureTableName(); } - public String getJoinTableName() - { + public String getJoinTableName() { return this.joinTableName; } - public String getPrimitiveTableName() - { + public String getPrimitiveTableName() { return this.primitiveTableName; } - public VPFRelation[] getRelations() - { + public VPFRelation[] getRelations() { return this.relations; } - public void setRelations(VPFRelation[] relations) - { + public void setRelations(VPFRelation[] relations) { this.relations = relations; } - public Collection createFeatures(VPFFeatureFactory factory) - { + public Collection createFeatures(VPFFeatureFactory factory) { return null; } - public Collection createFeatureSymbols(VPFSymbolFactory factory) - { + public Collection createFeatureSymbols(VPFSymbolFactory factory) { return null; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } VPFFeatureClass that = (VPFFeatureClass) o; if (this.coverage != null ? !this.coverage.getFilePath().equals(that.coverage.getFilePath()) - : that.coverage != null) + : that.coverage != null) { return false; - if (this.schema != null ? !this.schema.equals(that.schema) : that.schema != null) + } + if (this.schema != null ? !this.schema.equals(that.schema) : that.schema != null) { return false; - if (!Arrays.equals(this.relations, that.relations)) + } + if (!Arrays.equals(this.relations, that.relations)) { return false; - if (this.joinTableName != null ? !this.joinTableName.equals(that.joinTableName) : that.joinTableName != null) + } + if (this.joinTableName != null ? !this.joinTableName.equals(that.joinTableName) : that.joinTableName != null) { return false; + } //noinspection RedundantIfStatement if (this.primitiveTableName != null ? !this.primitiveTableName.equals(that.primitiveTableName) - : that.primitiveTableName != null) + : that.primitiveTableName != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result = this.coverage != null ? this.coverage.hashCode() : 0; result = 31 * result + (this.schema != null ? this.schema.hashCode() : 0); result = 31 * result + (this.relations != null ? Arrays.hashCode(this.relations) : 0); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClassFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClassFactory.java index 532a31d2c3..7ef7d5df79 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClassFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClassFactory.java @@ -9,7 +9,7 @@ * @author dcollins * @version $Id: VPFFeatureClassFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface VPFFeatureClassFactory -{ +public interface VPFFeatureClassFactory { + public VPFFeatureClass createFromSchema(VPFCoverage coverage, VPFFeatureClassSchema schema); } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClassSchema.java b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClassSchema.java index b78780aea4..b59ee18c69 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClassSchema.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureClassSchema.java @@ -9,57 +9,56 @@ * @author dcollins * @version $Id: VPFFeatureClassSchema.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFFeatureClassSchema -{ +public class VPFFeatureClassSchema { + protected String className; protected VPFFeatureType type; protected String featureTableName; - public VPFFeatureClassSchema(String className, VPFFeatureType type, String featureTableName) - { + public VPFFeatureClassSchema(String className, VPFFeatureType type, String featureTableName) { this.className = className; this.type = type; this.featureTableName = featureTableName; } - public String getClassName() - { + public String getClassName() { return this.className; } - public VPFFeatureType getType() - { + public VPFFeatureType getType() { return this.type; } - public String getFeatureTableName() - { + public String getFeatureTableName() { return this.featureTableName; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } VPFFeatureClassSchema that = (VPFFeatureClassSchema) o; - if (this.className != null ? !this.className.equals(that.className) : that.className != null) + if (this.className != null ? !this.className.equals(that.className) : that.className != null) { return false; + } if (this.featureTableName != null ? !this.featureTableName.equals(that.featureTableName) - : that.featureTableName != null) + : that.featureTableName != null) { return false; + } //noinspection RedundantIfStatement - if (this.type != null ? !this.type.equals(that.type) : that.type != null) + if (this.type != null ? !this.type.equals(that.type) : that.type != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result = this.className != null ? this.className.hashCode() : 0; result = 31 * result + (this.type != null ? this.type.hashCode() : 0); result = 31 * result + (this.featureTableName != null ? this.featureTableName.hashCode() : 0); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureFactory.java index e15d8cfa15..c97195fbaf 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureFactory.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: VPFFeatureFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface VPFFeatureFactory -{ +public interface VPFFeatureFactory { + Collection createPointFeatures(VPFFeatureClass featureClass); Collection createLineFeatures(VPFFeatureClass featureClass); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureTableFilter.java b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureTableFilter.java index 67c956876b..e45a03a5ba 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureTableFilter.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureTableFilter.java @@ -13,11 +13,12 @@ * @author dcollins * @version $Id: VPFFeatureTableFilter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFFeatureTableFilter implements FileFilter -{ - /** Creates a VPFFeatureTableFilter, but otherwise does nothing. */ - public VPFFeatureTableFilter() - { +public class VPFFeatureTableFilter implements FileFilter { + + /** + * Creates a VPFFeatureTableFilter, but otherwise does nothing. + */ + public VPFFeatureTableFilter() { } /** @@ -29,10 +30,8 @@ public VPFFeatureTableFilter() * * @throws IllegalArgumentException if the file is null. */ - public boolean accept(java.io.File file) - { - if (file == null) - { + public boolean accept(java.io.File file) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureType.java b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureType.java index d9f71424bd..bdb449d51e 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFFeatureType.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFFeatureType.java @@ -9,8 +9,7 @@ * @author dcollins * @version $Id: VPFFeatureType.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public enum VPFFeatureType -{ +public enum VPFFeatureType { POINT, LINE, AREA, @@ -18,26 +17,16 @@ public enum VPFFeatureType COMPLEX, LABEL; - public static VPFFeatureType fromTypeName(String featureType) - { - if (featureType.equalsIgnoreCase(VPFConstants.POINT_FEATURE_TYPE)) - { + public static VPFFeatureType fromTypeName(String featureType) { + if (featureType.equalsIgnoreCase(VPFConstants.POINT_FEATURE_TYPE)) { return POINT; - } - else if (featureType.equalsIgnoreCase(VPFConstants.LINE_FEATURE_TYPE)) - { + } else if (featureType.equalsIgnoreCase(VPFConstants.LINE_FEATURE_TYPE)) { return LINE; - } - else if (featureType.equalsIgnoreCase(VPFConstants.AREA_FEATURE_TYPE)) - { + } else if (featureType.equalsIgnoreCase(VPFConstants.AREA_FEATURE_TYPE)) { return AREA; - } - else if (featureType.equalsIgnoreCase(VPFConstants.TEXT_FEATURE_TYPE)) - { + } else if (featureType.equalsIgnoreCase(VPFConstants.TEXT_FEATURE_TYPE)) { return TEXT; - } - else if (featureType.equalsIgnoreCase(VPFConstants.COMPLEX_FEATURE_TYPE)) - { + } else if (featureType.equalsIgnoreCase(VPFConstants.COMPLEX_FEATURE_TYPE)) { return COMPLEX; } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFLayer.java b/src/gov/nasa/worldwind/formats/vpf/VPFLayer.java index 888c6bc14b..7fee13aec2 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFLayer.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFLayer.java @@ -22,8 +22,8 @@ * @author Patrick Murris * @version $Id: VPFLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFLayer extends AbstractLayer -{ +public class VPFLayer extends AbstractLayer { + public static final String LIBRARY_CHANGED = "VPFLayer.LibraryChanged"; public static final String COVERAGE_CHANGED = "VPFLayer.CoverageChanged"; @@ -48,11 +48,10 @@ public class VPFLayer extends AbstractLayer protected Queue disposalQ = new ConcurrentLinkedQueue(); // --- Inner classes ---------------------------------------------------------------------- - protected static final VPFTile NULL_TILE = new VPFTile(-1, "NullTile", new VPFBoundingBox(0, 0, 0, 0)); - protected static class VPFLibraryRenderable - { + protected static class VPFLibraryRenderable { + protected boolean enabled = false; protected VPFLayer layer; protected VPFLibrary library; @@ -60,102 +59,93 @@ protected static class VPFLibraryRenderable protected ArrayList coverages = new ArrayList(); protected ArrayList currentTiles = new ArrayList(); - public VPFLibraryRenderable(VPFLayer layer, VPFLibrary library) - { + public VPFLibraryRenderable(VPFLayer layer, VPFLibrary library) { this.layer = layer; this.library = library; - for (VPFCoverage cov : this.library.getCoverages()) - { - if (cov.getName().equalsIgnoreCase(VPFConstants.LIBRARY_REFERENCE_COVERAGE)) + for (VPFCoverage cov : this.library.getCoverages()) { + if (cov.getName().equalsIgnoreCase(VPFConstants.LIBRARY_REFERENCE_COVERAGE)) { this.referenceCoverage = new VPFCoverageRenderable(this.layer, cov); - else + } else { this.coverages.add(new VPFCoverageRenderable(this.layer, cov)); + } } - if (this.referenceCoverage != null) - { + if (this.referenceCoverage != null) { this.referenceCoverage.enabled = true; } } - public void assembleSymbols(DrawContext dc, double drawDistance, int maxTilesToDraw) - { - if (!this.enabled) + public void assembleSymbols(DrawContext dc, double drawDistance, int maxTilesToDraw) { + if (!this.enabled) { return; + } this.assembleVisibleTiles(dc, drawDistance, maxTilesToDraw); - if (this.referenceCoverage != null) - { + if (this.referenceCoverage != null) { this.referenceCoverage.assembleSymbols(null); } - for (VPFCoverageRenderable cr : this.coverages) - { + for (VPFCoverageRenderable cr : this.coverages) { cr.assembleSymbols((cr.coverage.isTiled() ? this.currentTiles : null)); } } - public void drawTileExtents(DrawContext dc) - { - for (VPFTile tile : this.currentTiles) - { + public void drawTileExtents(DrawContext dc) { + for (VPFTile tile : this.currentTiles) { Extent extent = tile.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()); - if (extent instanceof Renderable) + if (extent instanceof Renderable) { ((Renderable) extent).render(dc); + } } } - public void setCoverageEnabled(VPFCoverage coverage, boolean enabled) - { + public void setCoverageEnabled(VPFCoverage coverage, boolean enabled) { VPFCoverageRenderable cr = this.getCoverageRenderable(coverage); - if (cr != null) + if (cr != null) { cr.enabled = enabled; + } this.layer.firePropertyChange(AVKey.LAYER, null, this.layer); } - public VPFCoverageRenderable getCoverageRenderable(VPFCoverage coverage) - { - for (VPFCoverageRenderable cr : this.coverages) - { - if (cr.coverage.getFilePath().equals(coverage.getFilePath())) + public VPFCoverageRenderable getCoverageRenderable(VPFCoverage coverage) { + for (VPFCoverageRenderable cr : this.coverages) { + if (cr.coverage.getFilePath().equals(coverage.getFilePath())) { return cr; + } } return null; } - protected void assembleVisibleTiles(DrawContext dc, double drawDistance, int maxTilesToDraw) - { + protected void assembleVisibleTiles(DrawContext dc, double drawDistance, int maxTilesToDraw) { this.currentTiles.clear(); - if (!this.library.hasTiledCoverages()) + if (!this.library.hasTiledCoverages()) { return; + } Frustum frustum = dc.getView().getFrustumInModelCoordinates(); Vec4 eyePoint = dc.getView().getEyePoint(); - for (VPFTile tile : this.library.getTiles()) - { + for (VPFTile tile : this.library.getTiles()) { Extent extent = tile.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()); double d = extent.getCenter().distanceTo3(eyePoint) - extent.getRadius(); - if (d < drawDistance && frustum.intersects(extent)) + if (d < drawDistance && frustum.intersects(extent)) { this.currentTiles.add(tile); + } } // Trim down list to four closest tiles - while (this.currentTiles.size() > maxTilesToDraw) - { + while (this.currentTiles.size() > maxTilesToDraw) { int idx = -1; double maxDistance = 0; - for (int i = 0; i < this.currentTiles.size(); i++) - { + for (int i = 0; i < this.currentTiles.size(); i++) { Extent extent = this.currentTiles.get(i).getExtent(dc.getGlobe(), dc.getVerticalExaggeration()); double distance = dc.getView().getEyePoint().distanceTo3(extent.getCenter()); - if (distance > maxDistance) - { + if (distance > maxDistance) { maxDistance = distance; idx = i; } @@ -165,23 +155,21 @@ protected void assembleVisibleTiles(DrawContext dc, double drawDistance, int max } } - protected static class VPFCoverageRenderable - { + protected static class VPFCoverageRenderable { + protected boolean enabled = false; protected VPFLayer layer; protected VPFCoverage coverage; protected Map tileCache; - public VPFCoverageRenderable(VPFLayer layer, VPFCoverage coverage) - { + public VPFCoverageRenderable(VPFLayer layer, VPFCoverage coverage) { this.layer = layer; this.coverage = coverage; - this.tileCache = Collections.synchronizedMap(new BoundedHashMap(6, true) - { - protected boolean removeEldestEntry(Map.Entry eldest) - { - if (!super.removeEldestEntry(eldest)) + this.tileCache = Collections.synchronizedMap(new BoundedHashMap(6, true) { + protected boolean removeEldestEntry(Map.Entry eldest) { + if (!super.removeEldestEntry(eldest)) { return false; + } dispose(eldest.getValue()); return true; @@ -189,68 +177,58 @@ protected boolean removeEldestEntry(Map.Entry elde }); } - public void assembleSymbols(Iterable tiles) - { - if (!this.enabled) + public void assembleSymbols(Iterable tiles) { + if (!this.enabled) { return; + } - if (tiles == null) - { + if (tiles == null) { this.doAssembleSymbols(NULL_TILE); return; } - for (VPFTile tile : tiles) - { + for (VPFTile tile : tiles) { this.doAssembleSymbols(tile); } } - protected void doAssembleSymbols(VPFTile tile) - { + protected void doAssembleSymbols(VPFTile tile) { VPFSymbolCollection symbolCollection = this.tileCache.get(tile); - if (symbolCollection != null) - { + if (symbolCollection != null) { this.layer.symbols.addAll(symbolCollection.getSymbols()); - } - else - { + } else { this.layer.requestQ.add(new RequestTask(this, tile)); } } - protected void dispose(VPFSymbolCollection renderInfo) - { + protected void dispose(VPFSymbolCollection renderInfo) { this.layer.disposalQ.add(renderInfo); } } - protected static class VPFSymbolCollection implements Disposable - { + protected static class VPFSymbolCollection implements Disposable { + public static final VPFSymbolCollection EMPTY_SYMBOL_COLLECTION = new VPFSymbolCollection(null); protected final ArrayList symbols = new ArrayList(); - public VPFSymbolCollection(Collection symbols) - { - if (symbols != null) + public VPFSymbolCollection(Collection symbols) { + if (symbols != null) { this.symbols.addAll(symbols); + } } - public Collection getSymbols() - { + public Collection getSymbols() { return Collections.unmodifiableCollection(this.symbols); } - public void dispose() - { - for (VPFSymbol s : this.symbols) - { - if (s == null) + public void dispose() { + for (VPFSymbol s : this.symbols) { + if (s == null) { continue; + } - if (s.getMapObject() instanceof Disposable) - { + if (s.getMapObject() instanceof Disposable) { ((Disposable) s.getMapObject()).dispose(); } } @@ -259,16 +237,14 @@ public void dispose() } } - protected VPFSymbolCollection loadTileSymbols(VPFCoverage coverage, VPFTile tile) - { + protected VPFSymbolCollection loadTileSymbols(VPFCoverage coverage, VPFTile tile) { VPFPrimitiveDataFactory primitiveDataFactory = new VPFBasicPrimitiveDataFactory(tile); VPFPrimitiveData primitiveData = primitiveDataFactory.createPrimitiveData(coverage); // The PrimitiveDataFactory returns null when there are no primitive data tables for this coverage tile. We // return the constant EMPTY_SYMBOL_COLLECTION to indicate that we have successfully loaded nothing the empty // contents of this coverage tile. - if (primitiveData == null) - { + if (primitiveData == null) { return VPFSymbolCollection.EMPTY_SYMBOL_COLLECTION; } @@ -279,31 +255,29 @@ protected VPFSymbolCollection loadTileSymbols(VPFCoverage coverage, VPFTile tile // Create coverage renderables for one tile - if tile is null gets all coverage VPFFeatureClass[] array = VPFUtils.readFeatureClasses(coverage, new VPFFeatureTableFilter()); - for (VPFFeatureClass cls : array) - { + for (VPFFeatureClass cls : array) { Collection symbols = cls.createFeatureSymbols(symbolFactory); - if (symbols != null) + if (symbols != null) { list.addAll(symbols); + } } return new VPFSymbolCollection(list); } - protected static class RequestTask implements Runnable, Comparable - { + protected static class RequestTask implements Runnable, Comparable { + protected VPFCoverageRenderable coverageRenderable; protected VPFTile tile; - protected RequestTask(VPFCoverageRenderable coverageRenderable, VPFTile tile) - { + protected RequestTask(VPFCoverageRenderable coverageRenderable, VPFTile tile) { this.coverageRenderable = coverageRenderable; this.tile = tile; } - public void run() - { + public void run() { VPFSymbolCollection symbols = this.coverageRenderable.layer.loadTileSymbols( - this.coverageRenderable.coverage, (this.tile != NULL_TILE) ? this.tile : null); + this.coverageRenderable.coverage, (this.tile != NULL_TILE) ? this.tile : null); this.coverageRenderable.tileCache.put(this.tile, symbols); this.coverageRenderable.layer.firePropertyChange(AVKey.LAYER, null, this.coverageRenderable.layer); @@ -316,10 +290,8 @@ public void run() * * @throws IllegalArgumentException if that is null */ - public int compareTo(RequestTask that) - { - if (that == null) - { + public int compareTo(RequestTask that) { + if (that == null) { String msg = Logging.getMessage("nullValue.RequestTaskIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -328,34 +300,35 @@ public int compareTo(RequestTask that) return 0; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } RequestTask that = (RequestTask) o; if (coverageRenderable != null ? !coverageRenderable.equals(that.coverageRenderable) - : that.coverageRenderable != null) + : that.coverageRenderable != null) { return false; + } //noinspection RedundantIfStatement - if (tile != null ? !tile.equals(that.tile) : that.tile != null) + if (tile != null ? !tile.equals(that.tile) : that.tile != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result = coverageRenderable != null ? coverageRenderable.hashCode() : 0; result = 31 * result + (tile != null ? tile.hashCode() : 0); return result; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("coverageRenderable=").append(this.coverageRenderable.coverage.getName()); sb.append(", tile=").append(this.tile); @@ -364,45 +337,36 @@ public String toString() } // --- VPF Layer ---------------------------------------------------------------------- - - public VPFLayer() - { + public VPFLayer() { this(null); } - public VPFLayer(VPFDatabase db) - { + public VPFLayer(VPFDatabase db) { this.setName("VPF Layer"); this.setPickEnabled(false); - if (db != null) + if (db != null) { this.setVPFDatabase(db); + } this.textRenderer.setCullTextEnabled(true); this.textRenderer.setEffect(AVKey.TEXT_EFFECT_OUTLINE); } - public VPFDatabase getVPFDatabase() - { + public VPFDatabase getVPFDatabase() { return this.db; } - public void setVPFDatabase(VPFDatabase db) - { + public void setVPFDatabase(VPFDatabase db) { this.db = db; this.initialize(); - this.db.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent event) - { - if (event.getPropertyName().equals(LIBRARY_CHANGED)) - { + this.db.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + if (event.getPropertyName().equals(LIBRARY_CHANGED)) { VPFLibrary library = (VPFLibrary) event.getSource(); boolean enabled = (Boolean) event.getNewValue(); setLibraryEnabled(library, enabled); - } - else if (event.getPropertyName().equals(COVERAGE_CHANGED)) - { + } else if (event.getPropertyName().equals(COVERAGE_CHANGED)) { VPFCoverage coverage = (VPFCoverage) event.getSource(); boolean enabled = (Boolean) event.getNewValue(); setCoverageEnabled(coverage, enabled); @@ -411,128 +375,110 @@ else if (event.getPropertyName().equals(COVERAGE_CHANGED)) }); } - protected void initialize() - { + protected void initialize() { this.libraries = new ArrayList(); - for (VPFLibrary lib : db.getLibraries()) - { + for (VPFLibrary lib : db.getLibraries()) { this.libraries.add(new VPFLibraryRenderable(this, lib)); } } - public void setCoverageEnabled(VPFCoverage coverage, boolean enabled) - { - for (VPFLibraryRenderable lr : this.libraries) - { + public void setCoverageEnabled(VPFCoverage coverage, boolean enabled) { + for (VPFLibraryRenderable lr : this.libraries) { lr.setCoverageEnabled(coverage, enabled); } } - public void doPreRender(DrawContext dc) - { + public void doPreRender(DrawContext dc) { // Assemble renderables lists this.assembleRenderables(dc); // Handle object disposal. this.handleDisposal(); // Pre render renderable objects. - for (Renderable r : this.renderableObjects) - { - if (r instanceof PreRenderable) + for (Renderable r : this.renderableObjects) { + if (r instanceof PreRenderable) { ((PreRenderable) r).preRender(dc); + } } } - public void doRender(DrawContext dc) - { - for (Renderable r : this.renderableObjects) // Other renderables + public void doRender(DrawContext dc) { + for (Renderable r : this.renderableObjects) // Other renderables { r.render(dc); } this.textRenderer.render(dc, this.textObjects); // Geo text - if (this.drawTileExtents) - { - for (VPFLibraryRenderable lr : this.libraries) - { + if (this.drawTileExtents) { + for (VPFLibraryRenderable lr : this.libraries) { lr.drawTileExtents(dc); } } } - public void setLibraryEnabled(VPFLibrary library, boolean enabled) - { + public void setLibraryEnabled(VPFLibrary library, boolean enabled) { VPFLibraryRenderable lr = this.getLibraryRenderable(library); - if (lr != null) + if (lr != null) { lr.enabled = enabled; + } this.firePropertyChange(AVKey.LAYER, null, this); } - public VPFLibraryRenderable getLibraryRenderable(VPFLibrary library) - { - for (VPFLibraryRenderable lr : this.libraries) - { - if (lr.library.getFilePath().equals(library.getFilePath())) + public VPFLibraryRenderable getLibraryRenderable(VPFLibrary library) { + for (VPFLibraryRenderable lr : this.libraries) { + if (lr.library.getFilePath().equals(library.getFilePath())) { return lr; + } } return null; } - public Iterable getActiveSymbols() - { + public Iterable getActiveSymbols() { return this.symbols; } - protected void assembleRenderables(DrawContext dc) - { + protected void assembleRenderables(DrawContext dc) { this.symbols.clear(); this.textObjects.clear(); this.renderableObjects.clear(); - for (VPFLibraryRenderable lr : this.libraries) - { + for (VPFLibraryRenderable lr : this.libraries) { lr.assembleSymbols(dc, this.drawDistance, this.maxTilesToDraw); } this.sortSymbols(this.symbols); // Dispatch renderable according to its class - for (VPFSymbol symbol : this.symbols) - { - if (symbol.getMapObject() instanceof GeographicText) + for (VPFSymbol symbol : this.symbols) { + if (symbol.getMapObject() instanceof GeographicText) { this.textObjects.add((GeographicText) symbol.getMapObject()); - else if (symbol.getMapObject() instanceof Renderable) + } else if (symbol.getMapObject() instanceof Renderable) { this.renderableObjects.add((Renderable) symbol.getMapObject()); + } } this.sendRequests(); this.requestQ.clear(); } - protected void sortSymbols(List list) - { + protected void sortSymbols(List list) { Collections.sort(list, new VPFSymbolComparator()); } - protected void handleDisposal() - { + protected void handleDisposal() { Disposable disposable; - while ((disposable = this.disposalQ.poll()) != null) - { + while ((disposable = this.disposalQ.poll()) != null) { disposable.dispose(); } } - protected void sendRequests() - { + protected void sendRequests() { Runnable task; - while ((task = this.requestQ.poll()) != null) - { - if (!WorldWind.getTaskService().isFull()) - { + while ((task = this.requestQ.poll()) != null) { + if (!WorldWind.getTaskService().isFull()) { WorldWind.getTaskService().addTask(task); } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFLegendSupport.java b/src/gov/nasa/worldwind/formats/vpf/VPFLegendSupport.java index 3df117f913..641489795c 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFLegendSupport.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFLegendSupport.java @@ -17,16 +17,14 @@ * @author Patrick Murris * @version $Id: VPFLegendSupport.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFLegendSupport -{ - public BufferedImage createLegendImage(VPFSymbolAttributes attr, int width, int height, int margin) - { +public class VPFLegendSupport { + + public BufferedImage createLegendImage(VPFSymbolAttributes attr, int width, int height, int margin) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - switch (attr.getFeatureType()) - { + switch (attr.getFeatureType()) { case POINT: this.drawPointLegend(attr, g2, width, height, margin); break; @@ -41,14 +39,13 @@ public BufferedImage createLegendImage(VPFSymbolAttributes attr, int width, int return image; } - protected void drawPointLegend(VPFSymbolAttributes attr, Graphics2D g2, int width, int height, int margin) - { - if (attr.getIconImageSource() == null) + protected void drawPointLegend(VPFSymbolAttributes attr, Graphics2D g2, int width, int height, int margin) { + if (attr.getIconImageSource() == null) { return; + } BufferedImage icon = getImage(attr.getIconImageSource()); - if (icon != null) - { + if (icon != null) { // icon width / height int iw = icon.getWidth(); int ih = icon.getHeight(); @@ -69,65 +66,54 @@ protected void drawPointLegend(VPFSymbolAttributes attr, Graphics2D g2, int widt } } - protected void drawLineLegend(VPFSymbolAttributes attr, Graphics2D g2, int width, int height, int margin) - { + protected void drawLineLegend(VPFSymbolAttributes attr, Graphics2D g2, int width, int height, int margin) { g2.setStroke(this.getStroke(attr)); g2.setPaint(attr.getOutlineMaterial().getDiffuse()); g2.drawLine(margin, height / 2, width - margin, height / 2); } - protected void drawAreaLegend(VPFSymbolAttributes attr, Graphics2D g2, int width, int height, int margin) - { + protected void drawAreaLegend(VPFSymbolAttributes attr, Graphics2D g2, int width, int height, int margin) { // Interior if any - if (attr.isDrawInterior()) - { + if (attr.isDrawInterior()) { g2.setPaint(this.getFillPaint(attr, width, height)); g2.fillRect(margin, margin, width - margin * 2, height - margin * 2); } // Outline if any - if (attr.isDrawOutline()) - { + if (attr.isDrawOutline()) { g2.setStroke(this.getStroke(attr)); g2.setPaint(attr.getOutlineMaterial().getDiffuse()); g2.drawRect(margin, margin, width - margin * 2, height - margin * 2); } } - protected Stroke getStroke(VPFSymbolAttributes attr) - { + protected Stroke getStroke(VPFSymbolAttributes attr) { BasicStroke stroke; float lineWidth = (float) attr.getOutlineWidth() + .5f; // Exagerate a bit line width - if (attr.getOutlineStippleFactor() > 0) - { + if (attr.getOutlineStippleFactor() > 0) { // Dashed line - determine dash array from 16 bit stipple pattern ArrayList dashList = new ArrayList(); short pattern = attr.getOutlineStipplePattern(); int length = 0; boolean dash = true; - for (int i = 0; i < 16; i++) - { + for (int i = 0; i < 16; i++) { boolean dashBit = ((pattern << i) & 0x8000) > 0; - if (dashBit != dash) - { + if (dashBit != dash) { dashList.add((float) length); length = attr.getOutlineStippleFactor(); dash = dashBit; - } - else + } else { length += attr.getOutlineStippleFactor(); + } } dashList.add((float) length); float[] dashArray = new float[dashList.size()]; - for (int i = 0; i < dashList.size(); i++) - { + for (int i = 0; i < dashList.size(); i++) { dashArray[i] = dashList.get(i); } stroke = new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, - 10f, dashArray, 0f); - } - else - { + 10f, dashArray, 0f); + } else { // Plain line stroke = new BasicStroke(lineWidth); } @@ -135,46 +121,39 @@ protected Stroke getStroke(VPFSymbolAttributes attr) } @SuppressWarnings({"UnusedDeclaration"}) - protected Paint getFillPaint(VPFSymbolAttributes attr, int width, int height) - { - if (attr.getImageSource() == null) + protected Paint getFillPaint(VPFSymbolAttributes attr, int width, int height) { + if (attr.getImageSource() == null) { return attr.getInteriorMaterial().getDiffuse(); + } //int patternSize = Math.min(width, height); // fit one pattern tiles BufferedImage pattern = getImage(attr.getImageSource()); - if (pattern != null) + if (pattern != null) { return new TexturePaint(pattern, new Rectangle(0, 0, pattern.getWidth(), pattern.getHeight())); + } return attr.getInteriorMaterial().getDiffuse(); } - protected BufferedImage getImage(Object imageSource) - { - if (imageSource instanceof String) - { + protected BufferedImage getImage(Object imageSource) { + if (imageSource instanceof String) { String path = (String) imageSource; Object streamOrException = WWIO.getFileOrResourceAsStream(path, this.getClass()); - if (streamOrException == null || streamOrException instanceof Exception) - { + if (streamOrException == null || streamOrException instanceof Exception) { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionAttemptingToReadImageFile", - streamOrException != null ? streamOrException : path); + streamOrException != null ? streamOrException : path); return null; } - try - { + try { return ImageIO.read((InputStream) streamOrException); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionAttemptingToReadImageFile", - path); + path); return null; } - } - else if (imageSource instanceof BufferedImage) - { + } else if (imageSource instanceof BufferedImage) { return (BufferedImage) imageSource; } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFLibrary.java b/src/gov/nasa/worldwind/formats/vpf/VPFLibrary.java index 7e2f0c0717..1b123aab45 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFLibrary.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFLibrary.java @@ -20,8 +20,8 @@ * @author dcollins * @version $Id: VPFLibrary.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFLibrary extends AVListImpl -{ +public class VPFLibrary extends AVListImpl { + private VPFDatabase database; private VPFBoundingBox bounds; private Map coverageMap = new HashMap(); @@ -31,10 +31,8 @@ public class VPFLibrary extends AVListImpl private VPFBufferedRecordData coverageAttributeTable; private VPFBufferedRecordData geographicReferenceTable; - protected VPFLibrary(VPFDatabase database) - { - if (database == null) - { + protected VPFLibrary(VPFDatabase database) { + if (database == null) { String message = Logging.getMessage("nullValue.DatabaseIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -48,31 +46,27 @@ protected VPFLibrary(VPFDatabase database) * Table, the Coverage Attribute Table, and the Geographic Reference Table. * * @param database the Database which the Library resides in. - * @param name the Library's name. + * @param name the Library's name. * * @return a new Library from the specified Database with the specified name. * * @throws IllegalArgumentException if the database is null, or if the name is null or empty. */ - public static VPFLibrary fromFile(VPFDatabase database, String name) - { - if (database == null) - { + public static VPFLibrary fromFile(VPFDatabase database, String name) { + if (database == null) { String message = Logging.getMessage("nullValue.DatabaseIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(name)) - { + if (WWUtil.isEmpty(name)) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File file = new File(database.getFilePath(), name); - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file.getPath()); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -80,22 +74,19 @@ public static VPFLibrary fromFile(VPFDatabase database, String name) // Library tables. VPFBufferedRecordData lht = VPFUtils.readTable(new File(file, VPFConstants.LIBRARY_HEADER_TABLE)); - if (lht == null) - { + if (lht == null) { String message = Logging.getMessage("VPF.LibraryHeaderTableMissing"); throw new WWRuntimeException(message); } VPFBufferedRecordData cat = VPFUtils.readTable(new File(file, VPFConstants.COVERAGE_ATTRIBUTE_TABLE)); - if (cat == null) - { + if (cat == null) { String message = Logging.getMessage("VPF.CoverageAttributeTableMissing"); throw new WWRuntimeException(message); } VPFBufferedRecordData grt = VPFUtils.readTable(new File(file, VPFConstants.GEOGRAPHIC_REFERENCE_TABLE)); - if (grt == null) - { + if (grt == null) { String message = Logging.getMessage("VPF.GeographicReferenceTableMissing"); throw new WWRuntimeException(message); } @@ -107,40 +98,36 @@ public static VPFLibrary fromFile(VPFDatabase database, String name) // Library metadata attributes. VPFRecord record = database.getLibraryAttributeTable().getRecord("library_name", name); - if (record != null) + if (record != null) { library.bounds = VPFUtils.getExtent(record); + } record = lht.getRecord(1); - if (record != null) - { + if (record != null) { VPFUtils.checkAndSetValue(record, "library_name", AVKey.DISPLAY_NAME, library); VPFUtils.checkAndSetValue(record, "description", AVKey.DESCRIPTION, library); } // Library Coverages. Collection col = createCoverages(library, cat); - if (col != null) + if (col != null) { library.setCoverages(col); + } // Library tiles. VPFCoverage cov = library.getCoverage(VPFConstants.TILE_REFERENCE_COVERAGE); - if (cov != null) - { + if (cov != null) { VPFTile[] tiles = createTiles(cov); - if (tiles != null) - { + if (tiles != null) { library.setTiles(tiles); - } - else - { + } else { String message = Logging.getMessage("VPF.NoTilesInTileReferenceCoverage"); Logging.logger().warning(message); } } // Coverage tiled attributes. - for (VPFCoverage coverage : library.getCoverages()) - { + for (VPFCoverage coverage : library.getCoverages()) { boolean tiled = isCoverageTiled(library, coverage); coverage.setTiled(tiled); } @@ -148,8 +135,7 @@ record = lht.getRecord(1); return library; } - public VPFDatabase getDatabase() - { + public VPFDatabase getDatabase() { return this.database; } @@ -158,8 +144,7 @@ public VPFDatabase getDatabase() * * @return name of this Library. */ - public String getName() - { + public String getName() { return this.getStringValue(AVKey.DISPLAY_NAME); } @@ -168,21 +153,18 @@ public String getName() * * @return description of this Library. */ - public String getDescription() - { + public String getDescription() { return this.getStringValue(AVKey.DESCRIPTION); } - public String getFilePath() - { + public String getFilePath() { StringBuilder sb = new StringBuilder(this.database.getFilePath()); sb.append(File.separator); sb.append(this.getName()); return sb.toString(); } - public VPFBoundingBox getBounds() - { + public VPFBoundingBox getBounds() { return this.bounds; } @@ -192,15 +174,12 @@ public VPFBoundingBox getBounds() * * @return number of Coverages associated with this Library. */ - public int getNumCoverages() - { + public int getNumCoverages() { return this.coverageMap.size(); } - public boolean containsCoverage(String name) - { - if (name == null) - { + public boolean containsCoverage(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -209,10 +188,8 @@ public boolean containsCoverage(String name) return this.coverageMap.containsKey(name); } - public VPFCoverage getCoverage(String name) - { - if (name == null) - { + public VPFCoverage getCoverage(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -221,28 +198,24 @@ public VPFCoverage getCoverage(String name) return this.coverageMap.get(name); } - public Set getCoverageNames() - { + public Set getCoverageNames() { return Collections.unmodifiableSet(this.coverageMap.keySet()); } - public Collection getCoverages() - { + public Collection getCoverages() { return Collections.unmodifiableCollection(this.coverageMap.values()); } - public void setCoverages(Collection collection) - { + public void setCoverages(Collection collection) { this.removeAllCoverages(); - if (collection != null) + if (collection != null) { this.addAllCoverages(collection); + } } - public void addCoverage(VPFCoverage coverage) - { - if (coverage == null) - { + public void addCoverage(VPFCoverage coverage) { + if (coverage == null) { String message = Logging.getMessage("nullValue.CoverageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -251,25 +224,20 @@ public void addCoverage(VPFCoverage coverage) this.coverageMap.put(coverage.getName(), coverage); } - public void addAllCoverages(Collection collection) - { - if (collection == null) - { + public void addAllCoverages(Collection collection) { + if (collection == null) { String message = Logging.getMessage("nullValue.CollectionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (VPFCoverage cov : collection) - { + for (VPFCoverage cov : collection) { this.addCoverage(cov); } } - public void removeCoverage(VPFCoverage coverage) - { - if (coverage == null) - { + public void removeCoverage(VPFCoverage coverage) { + if (coverage == null) { String message = Logging.getMessage("nullValue.CoverageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -278,35 +246,30 @@ public void removeCoverage(VPFCoverage coverage) this.coverageMap.remove(coverage.getName()); } - public void removeAllCoverages() - { + public void removeAllCoverages() { this.coverageMap.clear(); } - public boolean hasTiledCoverages() - { + public boolean hasTiledCoverages() { return this.getCoverage(VPFConstants.TILE_REFERENCE_COVERAGE) != null; } - public int getNumTiles() - { + public int getNumTiles() { return (this.tiles != null) ? this.tiles.length : 0; } - public VPFTile[] getTiles() - { - if (this.tiles == null) + public VPFTile[] getTiles() { + if (this.tiles == null) { return null; + } VPFTile[] copy = new VPFTile[this.tiles.length]; System.arraycopy(this.tiles, 0, copy, 0, this.tiles.length); return copy; } - public void setTiles(VPFTile[] array) - { - if (array == null) - { + public void setTiles(VPFTile[] array) { + if (array == null) { this.tiles = null; this.tileMap.clear(); return; @@ -316,50 +279,48 @@ public void setTiles(VPFTile[] array) System.arraycopy(array, 0, this.tiles, 0, array.length); this.tileMap.clear(); - for (VPFTile tile : array) - { + for (VPFTile tile : array) { this.tileMap.put(tile.getId(), tile); } } - public VPFTile getTile(int tileId) - { + public VPFTile getTile(int tileId) { return this.tileMap.get(tileId); } - public String getProductType() - { - if (this.libraryHeaderTable == null || this.libraryHeaderTable.getNumRecords() == 0) + public String getProductType() { + if (this.libraryHeaderTable == null || this.libraryHeaderTable.getNumRecords() == 0) { return null; + } VPFRecord record = this.libraryHeaderTable.getRecord(1); Object o = (record != null) ? record.getValue("product_type") : null; return (o != null) ? o.toString() : null; } - public double getMapScale() - { - if (this.libraryHeaderTable == null || this.libraryHeaderTable.getNumRecords() == 0) + public double getMapScale() { + if (this.libraryHeaderTable == null || this.libraryHeaderTable.getNumRecords() == 0) { return 0; + } VPFRecord record = this.libraryHeaderTable.getRecord(1); Object o = (record != null) ? record.getValue("scale") : null; return (o != null && o instanceof Number) ? ((Number) o).doubleValue() : 0; } - public Angle computeArcLengthFromMapDistance(double millimeters) - { - if (this.geographicReferenceTable == null || this.geographicReferenceTable.getNumRecords() == 0) + public Angle computeArcLengthFromMapDistance(double millimeters) { + if (this.geographicReferenceTable == null || this.geographicReferenceTable.getNumRecords() == 0) { return null; + } VPFRecord record = this.geographicReferenceTable.getRecord(1); - if (record == null) + if (record == null) { return null; + } String s = (String) record.getValue("units"); Double unitsCoefficient = parseUnitsCoefficient(s); - if (unitsCoefficient == null) - { + if (unitsCoefficient == null) { String message = Logging.getMessage("VPF.UnrecognizedUnits", s); Logging.logger().severe(message); return null; @@ -367,8 +328,7 @@ public Angle computeArcLengthFromMapDistance(double millimeters) s = (String) record.getValue("ellipsoid_detail"); double[] ellipsoidParams = parseEllipsoidDetail(s); - if (ellipsoidParams == null || ellipsoidParams.length != 2) - { + if (ellipsoidParams == null || ellipsoidParams.length != 2) { String message = Logging.getMessage("VPF.UnrecognizedEllipsoidDetail", s); Logging.logger().severe(message); return null; @@ -381,15 +341,12 @@ public Angle computeArcLengthFromMapDistance(double millimeters) return Angle.fromRadians(meters / radius); } - public VPFBufferedRecordData getLibraryHeaderTable() - { + public VPFBufferedRecordData getLibraryHeaderTable() { return this.libraryHeaderTable; } - public void setLibraryHeaderTable(VPFBufferedRecordData table) - { - if (table == null) - { + public void setLibraryHeaderTable(VPFBufferedRecordData table) { + if (table == null) { String message = Logging.getMessage("nullValue.TableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -398,15 +355,12 @@ public void setLibraryHeaderTable(VPFBufferedRecordData table) this.libraryHeaderTable = table; } - public VPFBufferedRecordData getGeographicReferenceTable() - { + public VPFBufferedRecordData getGeographicReferenceTable() { return this.geographicReferenceTable; } - public void setGeographicReferenceTable(VPFBufferedRecordData table) - { - if (table == null) - { + public void setGeographicReferenceTable(VPFBufferedRecordData table) { + if (table == null) { String message = Logging.getMessage("nullValue.TableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -415,15 +369,12 @@ public void setGeographicReferenceTable(VPFBufferedRecordData table) this.geographicReferenceTable = table; } - public VPFBufferedRecordData getCoverageAttributeTable() - { + public VPFBufferedRecordData getCoverageAttributeTable() { return this.coverageAttributeTable; } - public void setCoverageAttributeTable(VPFBufferedRecordData table) - { - if (table == null) - { + public void setCoverageAttributeTable(VPFBufferedRecordData table) { + if (table == null) { String message = Logging.getMessage("nullValue.TableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -432,87 +383,84 @@ public void setCoverageAttributeTable(VPFBufferedRecordData table) this.coverageAttributeTable = table; } - protected static Double parseUnitsCoefficient(String value) - { - if (WWUtil.isEmpty(value)) + protected static Double parseUnitsCoefficient(String value) { + if (WWUtil.isEmpty(value)) { return null; + } - if (value.toLowerCase().startsWith("f")) - { + if (value.toLowerCase().startsWith("f")) { return 1d / WWMath.METERS_TO_FEET; - } - else if (value.toLowerCase().startsWith("m")) - { + } else if (value.toLowerCase().startsWith("m")) { return 1d; - } - else - { + } else { return null; } } - protected static double[] parseEllipsoidDetail(String value) - { - if (WWUtil.isEmpty(value)) + protected static double[] parseEllipsoidDetail(String value) { + if (WWUtil.isEmpty(value)) { return null; + } Pattern pattern = Pattern.compile("[A][=](.+)\\s+[B][=](.+)\\s+?(.+)?"); Matcher matcher = pattern.matcher(value); - if (!matcher.matches()) + if (!matcher.matches()) { return null; + } String aString = matcher.group(1); String bString = matcher.group(2); - if (WWUtil.isEmpty(aString) || WWUtil.isEmpty(bString)) + if (WWUtil.isEmpty(aString) || WWUtil.isEmpty(bString)) { return null; + } Double a = WWUtil.convertStringToDouble(aString); Double b = WWUtil.convertStringToDouble(bString); - if (a == null || b == null) + if (a == null || b == null) { return null; + } - return new double[] {a, b}; + return new double[]{a, b}; } //**************************************************************// //******************** Coverage Assembly *********************// //**************************************************************// - - protected static Collection createCoverages(VPFLibrary library, VPFBufferedRecordData table) - { + protected static Collection createCoverages(VPFLibrary library, VPFBufferedRecordData table) { ArrayList list = new ArrayList(); - for (VPFRecord row : table) - { + for (VPFRecord row : table) { String name = (String) row.getValue("coverage_name"); - if (name != null) - { + if (name != null) { VPFCoverage coverage = VPFUtils.readCoverage(library, name); - if (coverage != null) + if (coverage != null) { list.add(coverage); + } } } return list; } - protected static boolean isCoverageTiled(VPFLibrary lib, VPFCoverage cov) - { - if (cov.getName().equals(VPFConstants.TILE_REFERENCE_COVERAGE)) + protected static boolean isCoverageTiled(VPFLibrary lib, VPFCoverage cov) { + if (cov.getName().equals(VPFConstants.TILE_REFERENCE_COVERAGE)) { return false; + } - if (lib == null || lib.getCoverage(VPFConstants.TILE_REFERENCE_COVERAGE) == null) + if (lib == null || lib.getCoverage(VPFConstants.TILE_REFERENCE_COVERAGE) == null) { return false; + } VPFTile[] tiles = lib.getTiles(); - if (tiles == null) + if (tiles == null) { return false; + } - for (VPFTile tile : tiles) - { + for (VPFTile tile : tiles) { File tmp = new File(cov.getFilePath(), tile.getName()); - if (tmp.exists()) + if (tmp.exists()) { return true; + } } return false; @@ -521,51 +469,50 @@ protected static boolean isCoverageTiled(VPFLibrary lib, VPFCoverage cov) //**************************************************************// //******************** Tile Assembly *************************// //**************************************************************// - - protected static VPFTile[] createTiles(VPFCoverage coverage) - { + protected static VPFTile[] createTiles(VPFCoverage coverage) { VPFFeatureClassSchema[] schemas = coverage.getFeatureClasses(new VPFFeatureTableFilter()); - if (schemas == null || schemas.length == 0) + if (schemas == null || schemas.length == 0) { return null; + } VPFFeatureClassSchema tileRefSchema = null; - for (VPFFeatureClassSchema s : schemas) - { - if (s.getClassName().equalsIgnoreCase(VPFConstants.TILE_REFERENCE_COVERAGE)) - { + for (VPFFeatureClassSchema s : schemas) { + if (s.getClassName().equalsIgnoreCase(VPFConstants.TILE_REFERENCE_COVERAGE)) { tileRefSchema = s; break; } } - if (tileRefSchema == null) + if (tileRefSchema == null) { return null; + } VPFFeatureClassFactory factory = new VPFBasicFeatureClassFactory(); VPFFeatureClass areaClass = factory.createFromSchema(coverage, tileRefSchema); return createTiles(areaClass); } - protected static VPFTile[] createTiles(VPFFeatureClass featureClass) - { + protected static VPFTile[] createTiles(VPFFeatureClass featureClass) { VPFPrimitiveDataFactory primitiveFactory = new VPFBasicPrimitiveDataFactory(null); VPFPrimitiveData primitiveData = primitiveFactory.createPrimitiveData(featureClass.getCoverage()); - if (primitiveData == null) + if (primitiveData == null) { return null; + } VPFFeatureFactory featureFactory = new VPFBasicFeatureFactory(null, primitiveData); Collection features = featureClass.createFeatures(featureFactory); - if (features == null || features.size() == 0) + if (features == null || features.size() == 0) { return null; + } VPFTile[] tiles = new VPFTile[features.size()]; int index = 0; - for (VPFFeature feature : features) - { + for (VPFFeature feature : features) { String tileName = feature.getStringValue("tile_name"); - if (tileName != null) + if (tileName != null) { tileName = fixTileName(tileName); + } tiles[index++] = new VPFTile(feature.getId(), tileName, feature.getBounds()); } @@ -573,8 +520,7 @@ protected static VPFTile[] createTiles(VPFFeatureClass featureClass) return tiles; } - protected static String fixTileName(String s) - { + protected static String fixTileName(String s) { s = s.toLowerCase(); s = s.replace("\\", File.separator); return s; diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFPrimitiveData.java b/src/gov/nasa/worldwind/formats/vpf/VPFPrimitiveData.java index 6f2b6f12bd..8e486d0c21 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFPrimitiveData.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFPrimitiveData.java @@ -13,30 +13,28 @@ * @author dcollins * @version $Id: VPFPrimitiveData.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFPrimitiveData -{ - public interface PrimitiveInfo - { +public class VPFPrimitiveData { + + public interface PrimitiveInfo { + VPFBoundingBox getBounds(); } - public static class BasicPrimitiveInfo implements PrimitiveInfo - { + public static class BasicPrimitiveInfo implements PrimitiveInfo { + protected VPFBoundingBox bounds; - public BasicPrimitiveInfo(VPFBoundingBox bounds) - { + public BasicPrimitiveInfo(VPFBoundingBox bounds) { this.bounds = bounds; } - public VPFBoundingBox getBounds() - { + public VPFBoundingBox getBounds() { return this.bounds; } } - public static class EdgeInfo extends BasicPrimitiveInfo - { + public static class EdgeInfo extends BasicPrimitiveInfo { + protected int edgeType; protected int startNode; protected int endNode; @@ -47,8 +45,7 @@ public static class EdgeInfo extends BasicPrimitiveInfo protected boolean isOnTileBoundary; public EdgeInfo(int edgeType, int startNode, int endNode, int leftFace, int rightFace, int leftEdge, - int rightEdge, boolean isOnTileBoundary, VPFBoundingBox bounds) - { + int rightEdge, boolean isOnTileBoundary, VPFBoundingBox bounds) { super(bounds); this.edgeType = edgeType; this.startNode = startNode; @@ -60,96 +57,81 @@ public EdgeInfo(int edgeType, int startNode, int endNode, int leftFace, int righ this.isOnTileBoundary = isOnTileBoundary; } - public int getEdgeType() - { + public int getEdgeType() { return this.edgeType; } - public int getStartNode() - { + public int getStartNode() { return this.startNode; } - public int getEndNode() - { + public int getEndNode() { return this.endNode; } - public int getLeftFace() - { + public int getLeftFace() { return this.leftFace; } - public int getRightFace() - { + public int getRightFace() { return this.rightFace; } - public int getLeftEdge() - { + public int getLeftEdge() { return this.leftEdge; } - public int getRightEdge() - { + public int getRightEdge() { return this.rightEdge; } - public boolean isOnTileBoundary() - { + public boolean isOnTileBoundary() { return this.isOnTileBoundary; } } - public static class FaceInfo extends BasicPrimitiveInfo - { + public static class FaceInfo extends BasicPrimitiveInfo { + protected Ring outerRing; protected Ring[] innerRings; protected VPFBoundingBox bounds; - public FaceInfo(Ring outerRing, Ring[] innerRings, VPFBoundingBox bounds) - { + public FaceInfo(Ring outerRing, Ring[] innerRings, VPFBoundingBox bounds) { super(bounds); this.outerRing = outerRing; this.innerRings = innerRings; } - public Ring getOuterRing() - { + public Ring getOuterRing() { return this.outerRing; } - public Ring[] getInnerRings() - { + public Ring[] getInnerRings() { return this.innerRings; } } - public static class Ring - { + public static class Ring { + protected int numEdges; protected int[] edgeId; protected int[] edgeOrientation; - public Ring(int numEdges, int[] edgeId, int[] edgeOrientation) - { + public Ring(int numEdges, int[] edgeId, int[] edgeOrientation) { this.numEdges = numEdges; this.edgeId = edgeId; this.edgeOrientation = edgeOrientation; } - public int getNumEdges() - { + public int getNumEdges() { return this.numEdges; } - public int getEdgeId(int index) - { + public int getEdgeId(int index) { return this.edgeId[index]; } - public int getEdgeOrientation(int index) - { + public int getEdgeOrientation(int index) { return this.edgeOrientation[index]; } } @@ -158,45 +140,37 @@ public int getEdgeOrientation(int index) protected Map primitiveCoords; protected Map primitiveStrings; - public VPFPrimitiveData() - { + public VPFPrimitiveData() { this.primitiveInfo = new HashMap(); this.primitiveCoords = new HashMap(); this.primitiveStrings = new HashMap(); } - public PrimitiveInfo[] getPrimitiveInfo(String name) - { + public PrimitiveInfo[] getPrimitiveInfo(String name) { return this.primitiveInfo.get(name); } - public void setPrimitiveInfo(String name, PrimitiveInfo[] info) - { + public void setPrimitiveInfo(String name, PrimitiveInfo[] info) { this.primitiveInfo.put(name, info); } - public PrimitiveInfo getPrimitiveInfo(String name, int id) - { + public PrimitiveInfo getPrimitiveInfo(String name, int id) { return this.primitiveInfo.get(name)[VPFBufferedRecordData.indexFromId(id)]; } - public VecBufferSequence getPrimitiveCoords(String name) - { + public VecBufferSequence getPrimitiveCoords(String name) { return this.primitiveCoords.get(name); } - public void setPrimitiveCoords(String name, VecBufferSequence coords) - { + public void setPrimitiveCoords(String name, VecBufferSequence coords) { this.primitiveCoords.put(name, coords); } - public CompoundStringBuilder getPrimitiveStrings(String name) - { + public CompoundStringBuilder getPrimitiveStrings(String name) { return this.primitiveStrings.get(name); } - public void setPrimitiveStrings(String name, CompoundStringBuilder strings) - { + public void setPrimitiveStrings(String name, CompoundStringBuilder strings) { this.primitiveStrings.put(name, strings); } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFPrimitiveDataFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFPrimitiveDataFactory.java index 1c3c01ad9c..7ffea35221 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFPrimitiveDataFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFPrimitiveDataFactory.java @@ -9,7 +9,7 @@ * @author dcollins * @version $Id: VPFPrimitiveDataFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface VPFPrimitiveDataFactory -{ +public interface VPFPrimitiveDataFactory { + VPFPrimitiveData createPrimitiveData(VPFCoverage coverage); } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFRecord.java b/src/gov/nasa/worldwind/formats/vpf/VPFRecord.java index 405dab2645..d57b8798f9 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFRecord.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFRecord.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: VPFRecord.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface VPFRecord -{ +public interface VPFRecord { + int getId(); boolean hasValue(String parameterName); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFRelation.java b/src/gov/nasa/worldwind/formats/vpf/VPFRelation.java index aba77bbee5..4bad1e7b16 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFRelation.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFRelation.java @@ -9,65 +9,64 @@ * @author dcollins * @version $Id: VPFRelation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFRelation -{ +public class VPFRelation { + private String table1; private String table1Key; private String table2; private String table2Key; - public VPFRelation(String table1, String table1Key, String table2, String table2Key) - { + public VPFRelation(String table1, String table1Key, String table2, String table2Key) { this.table1 = table1; this.table1Key = table1Key; this.table2 = table2; this.table2Key = table2Key; } - public String getTable1() - { + public String getTable1() { return this.table1; } - public String getTable1Key() - { + public String getTable1Key() { return this.table1Key; } - public String getTable2() - { + public String getTable2() { return this.table2; } - public String getTable2Key() - { + public String getTable2Key() { return this.table2Key; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } VPFRelation that = (VPFRelation) o; - if (this.table1 != null ? !this.table1.equals(that.table1) : that.table1 != null) + if (this.table1 != null ? !this.table1.equals(that.table1) : that.table1 != null) { return false; - if (this.table1Key != null ? !this.table1Key.equals(that.table1Key) : that.table1Key != null) + } + if (this.table1Key != null ? !this.table1Key.equals(that.table1Key) : that.table1Key != null) { return false; - if (this.table2 != null ? !this.table2.equals(that.table2) : that.table2 != null) + } + if (this.table2 != null ? !this.table2.equals(that.table2) : that.table2 != null) { return false; + } //noinspection RedundantIfStatement - if (this.table2Key != null ? !this.table2Key.equals(that.table2Key) : that.table2Key != null) + if (this.table2Key != null ? !this.table2Key.equals(that.table2Key) : that.table2Key != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result = this.table1 != null ? this.table1.hashCode() : 0; result = 31 * result + (this.table1Key != null ? this.table1Key.hashCode() : 0); result = 31 * result + (this.table2 != null ? this.table2.hashCode() : 0); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFSurfaceArea.java b/src/gov/nasa/worldwind/formats/vpf/VPFSurfaceArea.java index 6b0f583389..de410c40d8 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFSurfaceArea.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFSurfaceArea.java @@ -22,29 +22,26 @@ */ public class VPFSurfaceArea extends SurfacePolygon // TODO: consolidate with SurfacePolygons { + protected VPFFeature feature; protected VPFPrimitiveData primitiveData; protected VecBufferSequence buffer; protected LatLon referenceLocation; protected Object interiorDisplayListCacheKey = new Object(); - public VPFSurfaceArea(VPFFeature feature, VPFPrimitiveData primitiveData) - { + public VPFSurfaceArea(VPFFeature feature, VPFPrimitiveData primitiveData) { this.feature = feature; this.primitiveData = primitiveData; this.buffer = computeAreaFeatureCoords(feature, primitiveData); this.referenceLocation = feature.getBounds().toSector().getCentroid(); } - protected static VecBufferSequence computeAreaFeatureCoords(VPFFeature feature, VPFPrimitiveData primitiveData) - { + protected static VecBufferSequence computeAreaFeatureCoords(VPFFeature feature, VPFPrimitiveData primitiveData) { final int numEdges = traverseAreaEdges(feature, primitiveData, null); final IntBuffer edgeIds = IntBuffer.wrap(new int[numEdges]); - traverseAreaEdges(feature, primitiveData, new EdgeListener() - { - public void nextEdge(int edgeId, VPFPrimitiveData.EdgeInfo edgeInfo) - { + traverseAreaEdges(feature, primitiveData, new EdgeListener() { + public void nextEdge(int edgeId, VPFPrimitiveData.EdgeInfo edgeInfo) { edgeIds.put(edgeId); } }); @@ -55,27 +52,24 @@ public void nextEdge(int edgeId, VPFPrimitiveData.EdgeInfo edgeInfo) return (VecBufferSequence) buffer.slice(edgeIds.array(), 0, numEdges); } - protected interface EdgeListener - { + protected interface EdgeListener { + void nextEdge(int edgeId, VPFPrimitiveData.EdgeInfo edgeInfo); } - protected static int traverseAreaEdges(VPFFeature feature, VPFPrimitiveData primitiveData, EdgeListener listener) - { + protected static int traverseAreaEdges(VPFFeature feature, VPFPrimitiveData primitiveData, EdgeListener listener) { int count = 0; String primitiveName = feature.getFeatureClass().getPrimitiveTableName(); - for (int id : feature.getPrimitiveIds()) - { + for (int id : feature.getPrimitiveIds()) { VPFPrimitiveData.FaceInfo faceInfo = (VPFPrimitiveData.FaceInfo) primitiveData.getPrimitiveInfo( - primitiveName, id); + primitiveName, id); VPFPrimitiveData.Ring outerRing = faceInfo.getOuterRing(); count += traverseRingEdges(outerRing, primitiveData, listener); - for (VPFPrimitiveData.Ring ring : faceInfo.getInnerRings()) - { + for (VPFPrimitiveData.Ring ring : faceInfo.getInnerRings()) { count += traverseRingEdges(ring, primitiveData, listener); } } @@ -84,19 +78,16 @@ protected static int traverseAreaEdges(VPFFeature feature, VPFPrimitiveData prim } protected static int traverseRingEdges(VPFPrimitiveData.Ring ring, VPFPrimitiveData primitiveData, - EdgeListener listener) - { + EdgeListener listener) { int count = 0; - for (int edgeId : ring.edgeId) - { - VPFPrimitiveData.EdgeInfo edgeInfo = (VPFPrimitiveData.EdgeInfo) - primitiveData.getPrimitiveInfo(VPFConstants.EDGE_PRIMITIVE_TABLE, edgeId); + for (int edgeId : ring.edgeId) { + VPFPrimitiveData.EdgeInfo edgeInfo = (VPFPrimitiveData.EdgeInfo) primitiveData.getPrimitiveInfo(VPFConstants.EDGE_PRIMITIVE_TABLE, edgeId); - if (!edgeInfo.isOnTileBoundary()) - { - if (listener != null) + if (!edgeInfo.isOnTileBoundary()) { + if (listener != null) { listener.nextEdge(edgeId, edgeInfo); + } count++; } } @@ -104,34 +95,30 @@ protected static int traverseRingEdges(VPFPrimitiveData.Ring ring, VPFPrimitiveD return count; } - protected List computeSectors(Globe globe) - { + protected List computeSectors(Globe globe) { Sector s = this.feature.getBounds().toSector(); - if (s == null || s.equals(Sector.EMPTY_SECTOR)) + if (s == null || s.equals(Sector.EMPTY_SECTOR)) { return null; + } return Arrays.asList(s); } - public Iterable getLocations() - { + public Iterable getLocations() { return this.buffer.getLocations(); } - public void setLocations(Iterable iterable) - { + public void setLocations(Iterable iterable) { throw new UnsupportedOperationException(); } @Override - public Position getReferencePosition() - { + public Position getReferencePosition() { return new Position(this.referenceLocation, 0d); } @Override - protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sdc) { // Apply the geographic to surface tile coordinate transform. Matrix modelview = sdc.getModelviewMatrix(); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -139,18 +126,15 @@ protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sd } @Override - protected ShapeAttributes createActiveAttributes() - { + protected ShapeAttributes createActiveAttributes() { return new VPFSymbolAttributes(); } - protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) { // Intentionally left blank in order to override the superclass behavior with nothing. } - protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) { // Concave shape makes no assumptions about the nature or structure of the shape's vertices. The interior is // treated as a potentially complex polygon, and this code will do its best to rasterize that polygon. The // outline is treated as a simple line loop, regardless of whether the shape's vertices actually define a @@ -162,33 +146,29 @@ protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) this.applyInteriorState(dc, sdc, this.getActiveAttributes(), this.getInteriorTexture(), LatLon.ZERO); int[] dlResource = (int[]) dc.getGpuResourceCache().get(this.interiorDisplayListCacheKey); - if (dlResource == null) - { - dlResource = new int[] {gl.glGenLists(1), 1}; + if (dlResource == null) { + dlResource = new int[]{gl.glGenLists(1), 1}; gl.glNewList(dlResource[0], GL2.GL_COMPILE); // Tessellate the interior vertices using a reference location of (0, 0), because VPFSurfaceArea's // coordinates do not need to be offset with respect to a reference location. Integer numBytes = this.tessellateInterior(dc); gl.glEndList(); - if (numBytes == null) - { + if (numBytes == null) { gl.glDeleteLists(dlResource[0], dlResource[1]); dlResource = null; - } - else - { + } else { dc.getGpuResourceCache().put(this.interiorDisplayListCacheKey, dlResource, - GpuResourceCache.DISPLAY_LISTS, numBytes); + GpuResourceCache.DISPLAY_LISTS, numBytes); } } - if (dlResource != null) + if (dlResource != null) { gl.glCallList(dlResource[0]); + } } - protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) { this.applyOutlineState(dc, this.getActiveAttributes()); // Edges features are not necessarily closed loops, therefore each edge must be rendered as separate line strip. @@ -196,17 +176,13 @@ protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) this.buffer.multiDrawArrays(dc, GL.GL_LINE_STRIP); } - protected WWTexture getInteriorTexture() - { - if (this.getActiveAttributes().getImageSource() == null) - { + protected WWTexture getInteriorTexture() { + if (this.getActiveAttributes().getImageSource() == null) { this.texture = null; - } - else if (this.texture == null - || this.texture.getImageSource() != this.getActiveAttributes().getImageSource()) - { + } else if (this.texture == null + || this.texture.getImageSource() != this.getActiveAttributes().getImageSource()) { this.texture = new BasicWWTexture(this.getActiveAttributes().getImageSource(), - ((VPFSymbolAttributes) this.getActiveAttributes()).isMipMapIconImage()); + ((VPFSymbolAttributes) this.getActiveAttributes()).isMipMapIconImage()); } return this.texture; @@ -215,9 +191,7 @@ else if (this.texture == null //**************************************************************// //******************** Interior Tessellation *****************// //**************************************************************// - - protected Integer tessellateInteriorVertices(GLUtessellator tess) - { + protected Integer tessellateInteriorVertices(GLUtessellator tess) { // Setup the winding order to correctly tessellate the outer and inner rings. The outer ring is specified // with a clockwise winding order, while inner rings are specified with a counter-clockwise order. Inner // rings are subtracted from the outer ring, producing an area with holes. @@ -227,20 +201,20 @@ protected Integer tessellateInteriorVertices(GLUtessellator tess) int numBytes = 0; // approximate size of the display list String primitiveName = this.feature.getFeatureClass().getPrimitiveTableName(); - for (int id : this.feature.getPrimitiveIds()) - { + for (int id : this.feature.getPrimitiveIds()) { VPFPrimitiveData.FaceInfo faceInfo = (VPFPrimitiveData.FaceInfo) primitiveData.getPrimitiveInfo( - primitiveName, id); + primitiveName, id); Integer nb = this.tessellateRing(tess, faceInfo.getOuterRing()); - if (nb != null) + if (nb != null) { numBytes += nb; + } - for (VPFPrimitiveData.Ring ring : faceInfo.getInnerRings()) - { + for (VPFPrimitiveData.Ring ring : faceInfo.getInnerRings()) { nb = this.tessellateRing(tess, ring); - if (nb != null) + if (nb != null) { numBytes += nb; + } } } @@ -249,22 +223,19 @@ protected Integer tessellateInteriorVertices(GLUtessellator tess) return numBytes; } - protected Integer tessellateRing(GLUtessellator tess, VPFPrimitiveData.Ring ring) - { + protected Integer tessellateRing(GLUtessellator tess, VPFPrimitiveData.Ring ring) { GLU.gluTessBeginContour(tess); CompoundVecBuffer buffer = this.primitiveData.getPrimitiveCoords(VPFConstants.EDGE_PRIMITIVE_TABLE); int numEdges = ring.getNumEdges(); int numBytes = 0; - for (int i = 0; i < numEdges; i++) - { + for (int i = 0; i < numEdges; i++) { VecBuffer vecBuffer = buffer.subBuffer(ring.getEdgeId(i)); - Iterable iterable = (ring.getEdgeOrientation(i) < 0) ? - vecBuffer.getReverseCoords(3) : vecBuffer.getCoords(3); + Iterable iterable = (ring.getEdgeOrientation(i) < 0) + ? vecBuffer.getReverseCoords(3) : vecBuffer.getCoords(3); - for (double[] coords : iterable) - { + for (double[] coords : iterable) { GLU.gluTessVertex(tess, coords, 0, coords); numBytes += 3 * 4; // 3 float coords } @@ -282,13 +253,11 @@ protected Integer tessellateRing(GLUtessellator tess, VPFPrimitiveData.Ring ring * @param dc the current DrawContext. */ @Override - protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) - { + protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) { super.handleUnsuccessfulInteriorTessellation(dc); // If tessellating the shape's interior was unsuccessful, we modify the shape to avoid any additional // tessellation attempts, and free any resources that the shape won't use. - // Replace the shape's coordinate buffer with an empty VecBufferSequence . This ensures that any rendering // code won't attempt to re-tessellate this shape. this.buffer = VecBufferSequence.emptyVecBufferSequence(2); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFSurfaceLine.java b/src/gov/nasa/worldwind/formats/vpf/VPFSurfaceLine.java index 1cd2feb36b..cd9bc15675 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFSurfaceLine.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFSurfaceLine.java @@ -19,12 +19,12 @@ */ public class VPFSurfaceLine extends SurfacePolyline // TODO: consolidate with SurfacePolylines { + protected Sector sector; protected VecBufferSequence buffer; protected LatLon referenceLocation; - public VPFSurfaceLine(VPFFeature feature, VPFPrimitiveData primitiveData) - { + public VPFSurfaceLine(VPFFeature feature, VPFPrimitiveData primitiveData) { String primitiveName = feature.getFeatureClass().getPrimitiveTableName(); int[] primitiveIds = feature.getPrimitiveIds(); @@ -33,33 +33,29 @@ public VPFSurfaceLine(VPFFeature feature, VPFPrimitiveData primitiveData) this.referenceLocation = feature.getBounds().toSector().getCentroid(); } - protected List computeSectors(Globe globe) - { - if (this.sector == null || this.sector.equals(Sector.EMPTY_SECTOR)) + protected List computeSectors(Globe globe) { + if (this.sector == null || this.sector.equals(Sector.EMPTY_SECTOR)) { return null; + } return Arrays.asList(this.sector); } - public Iterable getLocations() - { + public Iterable getLocations() { return this.buffer.getLocations(); } - public void setLocations(Iterable iterable) - { + public void setLocations(Iterable iterable) { throw new UnsupportedOperationException(); } @Override - public Position getReferencePosition() - { + public Position getReferencePosition() { return new Position(this.referenceLocation, 0d); } @Override - protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sdc) { // Apply the geographic to surface tile coordinate transform. Matrix modelview = sdc.getModelviewMatrix(); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -67,18 +63,15 @@ protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sd } @Override - protected ShapeAttributes createActiveAttributes() - { + protected ShapeAttributes createActiveAttributes() { return new VPFSymbolAttributes(); } - protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) { // Intentionally left blank in order to override the superclass behavior with nothing. } - protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) { this.applyOutlineState(dc, this.getActiveAttributes()); int drawMode = (this.isClosed() ? GL.GL_LINE_LOOP : GL.GL_LINE_STRIP); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFSymbol.java b/src/gov/nasa/worldwind/formats/vpf/VPFSymbol.java index 85daff6e52..896f15c5f8 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFSymbol.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFSymbol.java @@ -9,31 +9,27 @@ * @author dcollins * @version $Id: VPFSymbol.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFSymbol -{ +public class VPFSymbol { + protected VPFFeature feature; protected VPFSymbolAttributes attributes; protected Object mapObject; - public VPFSymbol(VPFFeature feature, VPFSymbolAttributes attributes, Object mapObject) - { + public VPFSymbol(VPFFeature feature, VPFSymbolAttributes attributes, Object mapObject) { this.feature = feature; this.attributes = attributes; this.mapObject = mapObject; } - public VPFFeature getFeature() - { + public VPFFeature getFeature() { return this.feature; } - public VPFSymbolAttributes getAttributes() - { + public VPFSymbolAttributes getAttributes() { return this.attributes; } - public Object getMapObject() - { + public Object getMapObject() { return this.mapObject; } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolAttributes.java b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolAttributes.java index 43ebb4ca99..f30eff8bfa 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolAttributes.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolAttributes.java @@ -16,10 +16,10 @@ * @author Patrick Murris * @version $Id: VPFSymbolAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFSymbolAttributes extends BasicShapeAttributes -{ - public static class LabelAttributes - { +public class VPFSymbolAttributes extends BasicShapeAttributes { + + public static class LabelAttributes { + private Font font; private Color color; private Color backgroundColor; @@ -30,17 +30,14 @@ public static class LabelAttributes private String attributeName; private int abbreviationTableId; - public LabelAttributes() - { + public LabelAttributes() { this.font = defaultFont; this.color = defaultColor; this.backgroundColor = defaultBackgroundColor; } - public LabelAttributes(LabelAttributes attributes) - { - if (attributes == null) - { + public LabelAttributes(LabelAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -57,139 +54,129 @@ public LabelAttributes(LabelAttributes attributes) this.abbreviationTableId = attributes.getAbbreviationTableId(); } - public LabelAttributes copy() - { + public LabelAttributes copy() { return new LabelAttributes(this); } - public Font getFont() - { + public Font getFont() { return this.font; } - public void setFont(Font font) - { + public void setFont(Font font) { this.font = font; } - public Color getColor() - { + public Color getColor() { return this.color; } - public void setColor(Color color) - { + public void setColor(Color color) { this.color = color; } - public Color getBackgroundColor() - { + public Color getBackgroundColor() { return this.backgroundColor; } - public void setBackgroundColor(Color color) - { + public void setBackgroundColor(Color color) { this.backgroundColor = color; } - public double getOffset() - { + public double getOffset() { return offset; } - public void setOffset(double offset) - { + public void setOffset(double offset) { this.offset = offset; } - public Angle getOffsetAngle() - { + public Angle getOffsetAngle() { return this.offsetAngle; } - public void setOffsetAngle(Angle angle) - { + public void setOffsetAngle(Angle angle) { this.offsetAngle = angle; } - public String getPrepend() - { + public String getPrepend() { return this.prepend; } - public void setPrepend(String text) - { + public void setPrepend(String text) { this.prepend = text; } - public String getAppend() - { + public String getAppend() { return this.append; } - public void setAppend(String text) - { + public void setAppend(String text) { this.append = text; } - public String getAttributeName() - { + public String getAttributeName() { return this.attributeName; } - public void setAttributeName(String name) - { + public void setAttributeName(String name) { this.attributeName = name; } - public int getAbbreviationTableId() - { + public int getAbbreviationTableId() { return this.abbreviationTableId; } - public void setAbbreviationTableId(int tableId) - { + public void setAbbreviationTableId(int tableId) { this.abbreviationTableId = tableId; } @SuppressWarnings({"RedundantIfStatement"}) @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } LabelAttributes that = (LabelAttributes) o; - if (this.abbreviationTableId != that.abbreviationTableId) + if (this.abbreviationTableId != that.abbreviationTableId) { return false; - if (Double.compare(this.offset, that.offset) != 0) + } + if (Double.compare(this.offset, that.offset) != 0) { return false; - if (this.append != null ? !this.append.equals(that.append) : that.append != null) + } + if (this.append != null ? !this.append.equals(that.append) : that.append != null) { return false; + } if (this.attributeName != null ? !this.attributeName.equals(that.attributeName) - : that.attributeName != null) + : that.attributeName != null) { return false; + } if (this.backgroundColor != null ? !this.backgroundColor.equals(that.backgroundColor) - : that.backgroundColor != null) + : that.backgroundColor != null) { return false; - if (this.color != null ? !this.color.equals(that.color) : that.color != null) + } + if (this.color != null ? !this.color.equals(that.color) : that.color != null) { return false; - if (this.font != null ? !this.font.equals(that.font) : that.font != null) + } + if (this.font != null ? !this.font.equals(that.font) : that.font != null) { return false; - if (this.offsetAngle != null ? !this.offsetAngle.equals(that.offsetAngle) : that.offsetAngle != null) + } + if (this.offsetAngle != null ? !this.offsetAngle.equals(that.offsetAngle) : that.offsetAngle != null) { return false; - if (this.prepend != null ? !this.prepend.equals(that.prepend) : that.prepend != null) + } + if (this.prepend != null ? !this.prepend.equals(that.prepend) : that.prepend != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; long temp; result = this.font != null ? this.font.hashCode() : 0; @@ -220,12 +207,10 @@ public int hashCode() private String orientationAttributeName; private String description; - public VPFSymbolAttributes() - { + public VPFSymbolAttributes() { } - public VPFSymbolAttributes(VPFFeatureType featureType, VPFSymbolKey symbolKey) - { + public VPFSymbolAttributes(VPFFeatureType featureType, VPFSymbolKey symbolKey) { this.featureType = featureType; this.symbolKey = symbolKey; this.iconImageSource = null; @@ -237,8 +222,7 @@ public VPFSymbolAttributes(VPFFeatureType featureType, VPFSymbolKey symbolKey) this.description = null; } - public VPFSymbolAttributes(VPFSymbolAttributes attributes) - { + public VPFSymbolAttributes(VPFSymbolAttributes attributes) { super(attributes); this.featureType = attributes.getFeatureType(); this.symbolKey = attributes.getSymbolKey(); @@ -249,32 +233,31 @@ public VPFSymbolAttributes(VPFSymbolAttributes attributes) this.orientationAttributeName = attributes.getOrientationAttributeName(); this.description = attributes.getDescription(); - if (attributes.getLabelAttributes() != null) - { + if (attributes.getLabelAttributes() != null) { LabelAttributes[] array = attributes.getLabelAttributes(); int numLabelAttributes = array.length; this.labelAttributes = new LabelAttributes[numLabelAttributes]; - for (int i = 0; i < numLabelAttributes; i++) - { + for (int i = 0; i < numLabelAttributes; i++) { this.labelAttributes[i] = (array[i] != null) ? array[i].copy() : null; } } } - /** {@inheritDoc} */ - public ShapeAttributes copy() - { + /** + * {@inheritDoc} + */ + public ShapeAttributes copy() { return new VPFSymbolAttributes(this); } - /** {@inheritDoc} */ - public void copy(ShapeAttributes attributes) - { + /** + * {@inheritDoc} + */ + public void copy(ShapeAttributes attributes) { super.copy(attributes); - if (attributes instanceof VPFSymbolAttributes) - { + if (attributes instanceof VPFSymbolAttributes) { VPFSymbolAttributes vpfAttrs = (VPFSymbolAttributes) attributes; this.featureType = vpfAttrs.getFeatureType(); this.symbolKey = vpfAttrs.getSymbolKey(); @@ -285,140 +268,132 @@ public void copy(ShapeAttributes attributes) this.orientationAttributeName = vpfAttrs.getOrientationAttributeName(); this.description = vpfAttrs.getDescription(); - if (vpfAttrs.getLabelAttributes() != null) - { + if (vpfAttrs.getLabelAttributes() != null) { LabelAttributes[] array = vpfAttrs.getLabelAttributes(); int numLabelAttributes = array.length; this.labelAttributes = new LabelAttributes[numLabelAttributes]; - for (int i = 0; i < numLabelAttributes; i++) - { + for (int i = 0; i < numLabelAttributes; i++) { this.labelAttributes[i] = (array[i] != null) ? array[i].copy() : null; } } } } - public VPFFeatureType getFeatureType() - { + public VPFFeatureType getFeatureType() { return this.featureType; } - public VPFSymbolKey getSymbolKey() - { + public VPFSymbolKey getSymbolKey() { return this.symbolKey; } - public Object getIconImageSource() - { + public Object getIconImageSource() { return this.iconImageSource; } - public void setIconImageSource(Object imageSource) - { + public void setIconImageSource(Object imageSource) { this.iconImageSource = imageSource; } - public double getIconImageScale() - { + public double getIconImageScale() { return this.iconImageScale; } - public void setIconImageScale(double scale) - { + public void setIconImageScale(double scale) { this.iconImageScale = scale; } - public boolean isMipMapIconImage() - { + public boolean isMipMapIconImage() { return this.mipMapIconImage; } - public void setMipMapIconImage(boolean mipMap) - { + public void setMipMapIconImage(boolean mipMap) { this.mipMapIconImage = mipMap; } - public LabelAttributes[] getLabelAttributes() - { + public LabelAttributes[] getLabelAttributes() { return this.labelAttributes; } - public void setLabelAttributes(LabelAttributes[] attributes) - { + public void setLabelAttributes(LabelAttributes[] attributes) { this.labelAttributes = attributes; } - public double getDisplayPriority() - { + public double getDisplayPriority() { return this.displayPriority; } - public void setDisplayPriority(double displayPriority) - { + public void setDisplayPriority(double displayPriority) { this.displayPriority = displayPriority; } - public String getOrientationAttributeName() - { + public String getOrientationAttributeName() { return this.orientationAttributeName; } - public void setOrientationAttributeName(String name) - { + public void setOrientationAttributeName(String name) { this.orientationAttributeName = name; } - public String getDescription() - { + public String getDescription() { return this.description; } - public void setDescription(String description) - { + public void setDescription(String description) { this.description = description; } @SuppressWarnings({"RedundantIfStatement"}) @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; - if (!super.equals(o)) + } + if (!super.equals(o)) { return false; + } VPFSymbolAttributes that = (VPFSymbolAttributes) o; - if (Double.compare(this.displayPriority, that.displayPriority) != 0) + if (Double.compare(this.displayPriority, that.displayPriority) != 0) { return false; - if (Double.compare(this.iconImageScale, that.iconImageScale) != 0) + } + if (Double.compare(this.iconImageScale, that.iconImageScale) != 0) { return false; - if (this.mipMapIconImage != that.mipMapIconImage) + } + if (this.mipMapIconImage != that.mipMapIconImage) { return false; - if (this.description != null ? !this.description.equals(that.description) : that.description != null) + } + if (this.description != null ? !this.description.equals(that.description) : that.description != null) { return false; - if (this.featureType != that.featureType) + } + if (this.featureType != that.featureType) { return false; + } if (this.iconImageSource != null ? !this.iconImageSource.equals(that.iconImageSource) - : that.iconImageSource != null) + : that.iconImageSource != null) { return false; - if (!Arrays.equals(this.labelAttributes, that.labelAttributes)) + } + if (!Arrays.equals(this.labelAttributes, that.labelAttributes)) { return false; + } if (this.orientationAttributeName != null ? !this.orientationAttributeName.equals(that.orientationAttributeName) - : that.orientationAttributeName != null) + : that.orientationAttributeName != null) { return false; - if (this.symbolKey != null ? !this.symbolKey.equals(that.symbolKey) : that.symbolKey != null) + } + if (this.symbolKey != null ? !this.symbolKey.equals(that.symbolKey) : that.symbolKey != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = super.hashCode(); long temp; result = 31 * result + (this.featureType != null ? this.featureType.hashCode() : 0); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolComparator.java b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolComparator.java index 28d53a9228..39659f188c 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolComparator.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolComparator.java @@ -10,72 +10,69 @@ import java.util.Comparator; /** - * From MIL-HDBK-857A, section 6.5: Display Hierarchy. In order to ensure that features that overlap other are drawn in + * From MIL-HDBK-857A, section 6.5: Display Hierarchy. In order to ensure that features that overlap other are drawn in * the correct sequence, the GeoSym application software must allow for the definition of a display order for the - * features being displayed. GeoSym uses four "nested" methods to define the order in which symbols should be - * displayed. + * features being displayed. GeoSym uses four "nested" methods to define the order in which symbols should be displayed. *

        * 1. Display priority 2. Feature delineation 3. Order of rows in *sym.txt 4. Symbol type *

        - * 6.5.1 Display Priority. The first criterion to use to determine the order to display features is the display - * priority. Each row in the *sym.txt file defines a display priority number to that specific feature/attribute. The - * display priority is a value between 0 and 9, where 9 identifies the highest priority. A feature/attribute with a - * higher priority should be displayed after (on top of) one with a lower priority. For DNC, the values contained in - * the display priority field are defined based on the S52 lookup tables. Each DNC feature/attribute was mapped to a - * corresponding S57 object class/attribute. The S52 lookup tables were then utilized to obtain the display priority - * values assigned to each object class. For all other products, the display priority values were based on cartographic + * 6.5.1 Display Priority. The first criterion to use to determine the order to display features is the display + * priority. Each row in the *sym.txt file defines a display priority number to that specific feature/attribute. The + * display priority is a value between 0 and 9, where 9 identifies the highest priority. A feature/attribute with a + * higher priority should be displayed after (on top of) one with a lower priority. For DNC, the values contained in the + * display priority field are defined based on the S52 lookup tables. Each DNC feature/attribute was mapped to a + * corresponding S57 object class/attribute. The S52 lookup tables were then utilized to obtain the display priority + * values assigned to each object class. For all other products, the display priority values were based on cartographic * experience with the corresponding hardcopy map/chart. *

        - * 6.5.2 Feature Delineation. Once the features to be displayed have been sorted based on display priority, they must - * then be sorted by their delineation (area, line, point). If the display priority is equal among features, then the + * 6.5.2 Feature Delineation. Once the features to be displayed have been sorted based on display priority, they must + * then be sorted by their delineation (area, line, point). If the display priority is equal among features, then the * "painter's algorithm" should be used to display the area features first, followed by the linear features and then the * point features. *

        - * 6.5.3 Order of Rows in *sym.txt. The third criterion that affects the display order is the order of the rows in the - * fullsym.txt file. The order will be represented in the id column of each row. Row ids will always be serial but may - * not necessarily be consecutive. Stated another way, the row ID for row N will always be less than the row ID for row - * N+1. Symbology being displayed based on this criterion should be displayed based on the least row id to the greatest + * 6.5.3 Order of Rows in *sym.txt. The third criterion that affects the display order is the order of the rows in the + * fullsym.txt file. The order will be represented in the id column of each row. Row ids will always be serial but may + * not necessarily be consecutive. Stated another way, the row ID for row N will always be less than the row ID for row + * N+1. Symbology being displayed based on this criterion should be displayed based on the least row id to the greatest * row id. *

        - * 6.5.3.1 Point Features with Components. For point features (e.g., buoys, beacons, lights) that are composed of + * 6.5.3.1 Point Features with Components. For point features (e.g., buoys, beacons, lights) that are composed of * several symbol components, displaying the components according to the row ids in the *sym.txt file will result in the - * properly constructed composite symbol. Each symbol component is based on the value of a specific attribute and the + * properly constructed composite symbol. Each symbol component is based on the value of a specific attribute and the * components will vary in display priority so should already have been sorted according to that value before examining * the row ids in the *sym.txt file. *

        - * 6.5.3.2 Area Features with Multiple Fills. There are some area features (e.g., Maritime Areas) that require both a - * solid fill and one or more pattern fills. Since the areasym column can only contain a single CGM reference, there is + * 6.5.3.2 Area Features with Multiple Fills. There are some area features (e.g., Maritime Areas) that require both a + * solid fill and one or more pattern fills. Since the areasym column can only contain a single CGM reference, there is * a separate row in the *sym.txt file for each of the area symbols, as well as for the line symbol and/or point symbol - * that apply to the specific area feature. These multiple rows will have sequential row ids in the *sym.txt file - * according to the order in which the symbols are to be displayed on the screen: solid fill, pattern fill (may be more + * that apply to the specific area feature. These multiple rows will have sequential row ids in the *sym.txt file + * according to the order in which the symbols are to be displayed on the screen: solid fill, pattern fill (may be more * than one), linear boundary, centered point symbol (may be more than one). *

        - * 6.5.3.3 Features with Text Labels As a general rule, the display priority specified for a feature's text label(s) - * is the highest value possible, regardless of the display priority assigned to the base feature. In DNC, all text - * labels will have a display priority of 8 (per IHO S52). In all other products, text labels have a display priority - * of 9. Therefore, the text labels will by default be displayed on top of all other symbols since the display priority - * value is the first criterion controlling the order of symbology display on the screen. However, it is possible that a + * 6.5.3.3 Features with Text Labels As a general rule, the display priority specified for a feature's text label(s) is + * the highest value possible, regardless of the display priority assigned to the base feature. In DNC, all text labels + * will have a display priority of 8 (per IHO S52). In all other products, text labels have a display priority of 9. + * Therefore, the text labels will by default be displayed on top of all other symbols since the display priority value + * is the first criterion controlling the order of symbology display on the screen. However, it is possible that a * critical feature in a product (e.g., area bridges in DNC) may be assigned the same high priority as the text label - * for that feature. Since the row(s) defining the text label(s) will always follow the row(s) defining the CGM symbols + * for that feature. Since the row(s) defining the text label(s) will always follow the row(s) defining the CGM symbols * for a feature, displaying the symbols and text labels according to their row ids (lowest to highest) in *sym.txt will * still result in the correct final symbology for a feature being displayed. *

        - * 6.5.4 Symbol Type. The final criterion for determining the order for symbol display applies only to area features. + * 6.5.4 Symbol Type. The final criterion for determining the order for symbol display applies only to area features. * Area features can be symbolized by any combination of centered point symbol, linear boundary, solid fill and/or - * pattern fill. Except for the special case where an area feature's symbology requires both a solid and pattern - * fill(s) (see section 6.5.3.2), all symbols for an area feature will be specified in the same row of the *sym.txt - * file. In other words, any or all of the symbol columns may be populated. In these cases, the symbols are to be - * displayed according to the same "painter's algorithm" that applies at the feature level: the area symbol (from - * areasym) should be drawn first, followed by the linear symbol (from linesym) followed by the point symbol (from - * pointsym). + * pattern fill. Except for the special case where an area feature's symbology requires both a solid and pattern fill(s) + * (see section 6.5.3.2), all symbols for an area feature will be specified in the same row of the *sym.txt file. In + * other words, any or all of the symbol columns may be populated. In these cases, the symbols are to be displayed + * according to the same "painter's algorithm" that applies at the feature level: the area symbol (from areasym) should + * be drawn first, followed by the linear symbol (from linesym) followed by the point symbol (from pointsym). * * @author dcollins * @version $Id: VPFSymbolComparator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFSymbolComparator implements Comparator -{ - public VPFSymbolComparator() - { +public class VPFSymbolComparator implements Comparator { + + public VPFSymbolComparator() { } /** @@ -84,10 +81,8 @@ public VPFSymbolComparator() * * @return The relationship between a and b. */ - public int compare(VPFSymbol a, VPFSymbol b) - { - if (a == null || b == null) - { + public int compare(VPFSymbol a, VPFSymbol b) { + if (a == null || b == null) { String message = Logging.getMessage("nullValue.SymbolIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -96,37 +91,40 @@ public int compare(VPFSymbol a, VPFSymbol b) VPFSymbolAttributes aAttr = a.getAttributes(); VPFSymbolAttributes bAttr = b.getAttributes(); - if (aAttr == null && bAttr == null) + if (aAttr == null && bAttr == null) { return 0; + } - if (aAttr == null || bAttr == null) + if (aAttr == null || bAttr == null) { return (aAttr != null) ? -1 : 1; + } double aPriority = a.getAttributes().getDisplayPriority(); double bPriority = b.getAttributes().getDisplayPriority(); int i = (aPriority < bPriority) ? -1 : (aPriority > bPriority ? 1 : 0); - if (i != 0) + if (i != 0) { return i; + } aPriority = this.getFeatureTypePriority(a.getAttributes().getFeatureType()); bPriority = this.getFeatureTypePriority(b.getAttributes().getFeatureType()); i = (aPriority < bPriority) ? -1 : (aPriority > bPriority ? 1 : 0); - if (i != 0) + if (i != 0) { return i; + } VPFSymbolKey aKey = a.getAttributes().getSymbolKey(); VPFSymbolKey bKey = b.getAttributes().getSymbolKey(); i = aKey.compareTo(bKey); - if (i != 0) + if (i != 0) { return i; + } return 0; } - protected int getFeatureTypePriority(VPFFeatureType type) - { - switch (type) - { + protected int getFeatureTypePriority(VPFFeatureType type) { + switch (type) { case POINT: return 3; case LINE: diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolFactory.java b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolFactory.java index ec908afadc..4533ad554b 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolFactory.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolFactory.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: VPFSymbolFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface VPFSymbolFactory -{ +public interface VPFSymbolFactory { + Collection createPointSymbols(VPFFeatureClass featureClass); Collection createLineSymbols(VPFFeatureClass featureClass); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolKey.java b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolKey.java index 69e724dd25..cfe5153776 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolKey.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolKey.java @@ -11,43 +11,39 @@ * @author dcollins * @version $Id: VPFSymbolKey.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFSymbolKey implements Comparable -{ +public class VPFSymbolKey implements Comparable { + public static final VPFSymbolKey UNKNOWN_SYMBOL_KEY = new VPFSymbolKey(-1); protected int symbolCode; - public VPFSymbolKey(int symbolCode) - { + public VPFSymbolKey(int symbolCode) { this.symbolCode = symbolCode; } - public int getSymbolCode() - { + public int getSymbolCode() { return this.symbolCode; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } VPFSymbolKey that = (VPFSymbolKey) o; return this.symbolCode == that.symbolCode; } - public int hashCode() - { + public int hashCode() { return this.symbolCode; } - public int compareTo(VPFSymbolKey key) - { - if (key == null) - { + public int compareTo(VPFSymbolKey key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolSupport.java b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolSupport.java index a8d4e27c9b..983fd68188 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFSymbolSupport.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFSymbolSupport.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.formats.vpf; import gov.nasa.worldwind.avlist.AVList; @@ -17,44 +16,43 @@ * @author Patrick Murris * @version $Id: VPFSymbolSupport.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFSymbolSupport -{ +public class VPFSymbolSupport { + protected GeoSymSupport geoSymSupport; - public VPFSymbolSupport(String geoSymPath, String geoSymMimeType) - { + public VPFSymbolSupport(String geoSymPath, String geoSymMimeType) { this.geoSymSupport = new GeoSymSupport(geoSymPath, geoSymMimeType); } public Iterable getSymbolKeys(VPFFeatureClass featureClass, String featureCode, - AVList featureAttributes) - { - if (featureCode != null) - { + AVList featureAttributes) { + if (featureCode != null) { Iterable keys = this.doGetSymbolKeys(featureClass, featureCode, featureAttributes); - if (keys != null) + if (keys != null) { return keys; + } keys = this.geoSymSupport.getSymbolKeys(featureClass, featureCode, featureAttributes); - if (keys != null) + if (keys != null) { return keys; + } } return Arrays.asList(VPFSymbolKey.UNKNOWN_SYMBOL_KEY); } - public Iterable getSymbolAttributes(VPFFeatureClass featureClass, VPFSymbolKey key) - { + public Iterable getSymbolAttributes(VPFFeatureClass featureClass, VPFSymbolKey key) { Iterable attr = this.doGetAttributes(featureClass, key); - if (attr != null) + if (attr != null) { return attr; + } attr = this.geoSymSupport.getSymbolAttributes(featureClass, key); - if (attr != null) + if (attr != null) { return attr; + } - if (key == VPFSymbolKey.UNKNOWN_SYMBOL_KEY) - { + if (key == VPFSymbolKey.UNKNOWN_SYMBOL_KEY) { attr = this.assembleGenericAttributes(featureClass, key); } @@ -62,21 +60,18 @@ public Iterable getSymbolAttributes(VPFFeatureCla } public Iterable getSymbolAttributes(VPFFeatureClass featureClass, String featureCode, - AVList featureAttributes) - { + AVList featureAttributes) { Iterable keys = this.getSymbolKeys(featureClass, featureCode, featureAttributes); - if (keys == null) + if (keys == null) { return null; + } ArrayList attrList = new ArrayList(); - for (VPFSymbolKey key : keys) - { + for (VPFSymbolKey key : keys) { Iterable attr = this.getSymbolAttributes(featureClass, key); - if (attr != null) - { - for (VPFSymbolAttributes a : attr) - { + if (attr != null) { + for (VPFSymbolAttributes a : attr) { attrList.add(a); } } @@ -85,35 +80,33 @@ public Iterable getSymbolAttributes(VPFFeatureCla return attrList; } - public String getSymbolLabelText(VPFSymbolAttributes.LabelAttributes attr, AVList featureAttributes) - { + public String getSymbolLabelText(VPFSymbolAttributes.LabelAttributes attr, AVList featureAttributes) { String text = null; // Look up label text. Object o = featureAttributes.getValue(attr.getAttributeName()); - if (o instanceof String) - { + if (o instanceof String) { String s = (String) o; - if (s.length() > 0 && !s.equalsIgnoreCase("UNK")) + if (s.length() > 0 && !s.equalsIgnoreCase("UNK")) { text = s; - } - // Use abbreviation - else if (o instanceof Number && attr.getAbbreviationTableId() > 0) - { + } + } // Use abbreviation + else if (o instanceof Number && attr.getAbbreviationTableId() > 0) { text = this.geoSymSupport.getAbbreviation(attr.getAbbreviationTableId(), ((Number) o).intValue()); } - if (text != null) - { + if (text != null) { StringBuilder sb = new StringBuilder(); - if (attr.getPrepend() != null) + if (attr.getPrepend() != null) { sb.append(attr.getPrepend()); + } sb.append(text); - if (attr.getAppend() != null) + if (attr.getAppend() != null) { sb.append(attr.getAppend()); + } text = sb.toString(); } @@ -123,13 +116,10 @@ else if (o instanceof Number && attr.getAbbreviationTableId() > 0) @SuppressWarnings({"UnusedDeclaration"}) protected Iterable doGetSymbolKeys(VPFFeatureClass featureClass, String featureCode, - AVList featureAttributes) - { - if (featureClass.getType() == VPFFeatureType.TEXT) - { + AVList featureAttributes) { + if (featureClass.getType() == VPFFeatureType.TEXT) { Integer i = this.getSymbolId(featureAttributes); - if (i != null) - { + if (i != null) { return Arrays.asList(new VPFSymbolKey(i)); } } @@ -137,10 +127,8 @@ protected Iterable doGetSymbolKeys(VPFFeatureClass featu return null; } - protected Iterable doGetAttributes(VPFFeatureClass featureClass, VPFSymbolKey key) - { - if (featureClass.getType() == VPFFeatureType.TEXT) - { + protected Iterable doGetAttributes(VPFFeatureClass featureClass, VPFSymbolKey key) { + if (featureClass.getType() == VPFFeatureType.TEXT) { return this.assembleTextAttributes(featureClass, key); } @@ -150,34 +138,29 @@ protected Iterable doGetAttributes(VPFFeatureClas //**************************************************************// //******************** Text Attribute Assembly ***************// //**************************************************************// - protected Iterable assembleTextAttributes(VPFFeatureClass featureClass, - VPFSymbolKey key) - { + VPFSymbolKey key) { VPFBufferedRecordData symbolTable = featureClass.getCoverage().getSymbolRelatedAttributeTable(); - if (symbolTable == null) - { + if (symbolTable == null) { return null; } VPFRecord symbolRow = null; - for (VPFRecord row : symbolTable) - { + for (VPFRecord row : symbolTable) { Object o = row.getValue("symbol_id"); - if (o == null || !(o instanceof Number)) + if (o == null || !(o instanceof Number)) { continue; + } int rowSymbolId = ((Number) o).intValue(); - if (rowSymbolId == key.getSymbolCode()) - { + if (rowSymbolId == key.getSymbolCode()) { symbolRow = row; break; } } - if (symbolRow == null) - { + if (symbolRow == null) { return null; } @@ -190,15 +173,13 @@ protected Iterable assembleTextAttributes(VPFFeat String fontName = null; int i = (Integer) symbolRow.getValue("fon"); // Text font name. - switch (i) - { + switch (i) { case 1: fontName = "Arial"; // System default break; } - if (fontName != null) - { + if (fontName != null) { // Ignore the 'sty' attribute - AWT does not provide the equivalent functionality to specify the font as // 'Kern', 'Proportional', or 'Constant'. int size = (Integer) symbolRow.getValue("size"); // Text font size in points. @@ -206,8 +187,7 @@ protected Iterable assembleTextAttributes(VPFFeat } i = (Integer) symbolRow.getValue("col"); // Text color. - switch (i) - { + switch (i) { case 1: labelAttr.setColor(Color.BLACK); break; @@ -223,13 +203,12 @@ protected Iterable assembleTextAttributes(VPFFeat } labelAttr.setBackgroundColor(WWUtil.computeContrastingColor(labelAttr.getColor())); - attr.setLabelAttributes(new VPFSymbolAttributes.LabelAttributes[] {labelAttr}); + attr.setLabelAttributes(new VPFSymbolAttributes.LabelAttributes[]{labelAttr}); return Arrays.asList(attr); } - protected Integer getSymbolId(AVList params) - { + protected Integer getSymbolId(AVList params) { Object o = params.getValue("symbol_id"); return (o != null && o instanceof Number) ? ((Number) o).intValue() : null; } @@ -237,10 +216,8 @@ protected Integer getSymbolId(AVList params) //**************************************************************// //******************** Generic Attribute Assembly ************// //**************************************************************// - protected Iterable assembleGenericAttributes(VPFFeatureClass featureClass, - VPFSymbolKey key) - { + VPFSymbolKey key) { VPFSymbolAttributes attr = new VPFSymbolAttributes(featureClass.getType(), key); attr.setDrawInterior(false); attr.setDrawOutline(true); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFTableReader.java b/src/gov/nasa/worldwind/formats/vpf/VPFTableReader.java index 67a2df474a..680cf1e9e5 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFTableReader.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFTableReader.java @@ -18,43 +18,35 @@ * @author dcollins * @version $Id: VPFTableReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFTableReader -{ - public VPFTableReader() - { +public class VPFTableReader { + + public VPFTableReader() { } - public VPFBufferedRecordData read(File file) - { - if (file == null) - { + public VPFBufferedRecordData read(File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { ByteBuffer buffer = this.readFileToBuffer(file); return this.doRead(file, buffer); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("VPF.ExceptionAttemptingToReadTable", file.getPath()); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - protected ByteBuffer readFileToBuffer(File file) throws IOException - { + protected ByteBuffer readFileToBuffer(File file) throws IOException { ByteBuffer buffer = WWIO.readFileToBuffer(file, true); // Read VPF table to a direct ByteBuffer. buffer.order(ByteOrder.LITTLE_ENDIAN); // Default to least significant byte first order. return buffer; } - protected VPFBufferedRecordData doRead(File file, ByteBuffer buffer) - { + protected VPFBufferedRecordData doRead(File file, ByteBuffer buffer) { // Read the table header. Header header = this.readHeader(buffer); // Set the byte ordering to the ordering specified by the table header. @@ -64,15 +56,16 @@ protected VPFBufferedRecordData doRead(File file, ByteBuffer buffer) // Attempt to find a variable-length record index according to the file naming convention in // DIGEST Part 2 Annex C.2.3.1.2 File recordIndexFile = new File(file.getParent(), getRecordIndexFilename(file.getName())); - if (recordIndexFile.exists()) + if (recordIndexFile.exists()) { recordIndex = this.readRecordIndex(recordIndexFile); + } // If the record index is null, then attempt to compute it from the header's column definitions. - if (recordIndex == null) + if (recordIndex == null) { recordIndex = this.computeRecordIndex(buffer, header); + } // If the record index is still null, then we the column definitions are variable length, and there is no // variable-length record index associated with this table. In this case, we cannot read the table body. - if (recordIndex == null) - { + if (recordIndex == null) { String message = Logging.getMessage("VPF.VariableLengthIndexFileMissing"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -85,24 +78,26 @@ protected VPFBufferedRecordData doRead(File file, ByteBuffer buffer) //**************************************************************// //******************** Header ********************************// //**************************************************************// + /** + * MIL-STD-2407, section 5.4.1.1 + */ + protected static class Header { - /** MIL-STD-2407, section 5.4.1.1 */ - protected static class Header - { public int length; public ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; // Default to least significant byte first order. public String description; public String narrativeTableName; public Column[] columns; - public Header() - { + public Header() { } } - /** MIL-STD-2407, section 5.4.1.1 */ - public class Column - { + /** + * MIL-STD-2407, section 5.4.1.1 + */ + public class Column { + public final String name; public String dataType; public int numElements; @@ -113,44 +108,38 @@ public class Column public String narrativeTableName; public VPFDataBuffer dataBuffer; - public Column(String name) - { + public Column(String name) { this.name = name; } - public int getFieldLength() - { - if (this.isVariableLengthField()) + public int getFieldLength() { + if (this.isVariableLengthField()) { return -1; + } VPFDataType type = VPFDataType.fromTypeName(this.dataType); return this.numElements * type.getFieldLength(); } - public boolean isVariableLengthField() - { + public boolean isVariableLengthField() { VPFDataType type = VPFDataType.fromTypeName(this.dataType); return (this.numElements < 0) || type.isVariableLength(); } - public boolean isPrimaryKey() - { + public boolean isPrimaryKey() { return this.keyType.equals(VPFConstants.PRIMARY_KEY); } - public boolean isUniqueKey() - { + public boolean isUniqueKey() { return this.keyType.equals(VPFConstants.UNIQUE_KEY); } - public boolean isNonUniqueKey() - { + public boolean isNonUniqueKey() { return this.keyType.equals(VPFConstants.NON_UNIQUE_KEY); } } - protected Header readHeader(ByteBuffer buffer) - { + protected Header readHeader(ByteBuffer buffer) { int offset = buffer.position(); int length = buffer.getInt(); @@ -158,30 +147,31 @@ protected Header readHeader(ByteBuffer buffer) header.length = length; header.byteOrder = ByteOrder.LITTLE_ENDIAN; // Default to least significant byte first order. - if (length == 0) - { + if (length == 0) { return header; } // Read the byte order character. String s = VPFUtils.readDelimitedText(buffer, ';'); - if (s != null && s.equalsIgnoreCase("M")) + if (s != null && s.equalsIgnoreCase("M")) { header.byteOrder = ByteOrder.BIG_ENDIAN; + } // Read the table description string. s = VPFUtils.readDelimitedText(buffer, ';'); - if (s != null) + if (s != null) { header.description = s.trim(); + } // Read the narrative table name. s = VPFUtils.readDelimitedText(buffer, ';'); - if (s != null && s.charAt(0) != '-') + if (s != null && s.charAt(0) != '-') { header.narrativeTableName = s.trim(); + } ArrayList columnList = new ArrayList(); - while (buffer.position() < (offset + length)) - { + while (buffer.position() < (offset + length)) { Column col = this.readColumnDescription(buffer); columnList.add(col); } @@ -195,11 +185,9 @@ protected Header readHeader(ByteBuffer buffer) return header; } - protected Column readColumnDescription(ByteBuffer buffer) - { + protected Column readColumnDescription(ByteBuffer buffer) { String s = VPFUtils.readDelimitedText(buffer, '='); - if (s == null) - { + if (s == null) { String message = Logging.getMessage("VPF.MissingColumnName"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -208,36 +196,40 @@ protected Column readColumnDescription(ByteBuffer buffer) Column col = new Column(s); s = VPFUtils.readDelimitedText(buffer, ','); - if (s != null) + if (s != null) { col.dataType = s; + } s = VPFUtils.readDelimitedText(buffer, ','); - if (s != null) + if (s != null) { col.numElements = parseNumElements(s); + } s = VPFUtils.readDelimitedText(buffer, ','); - if (s != null) + if (s != null) { col.keyType = s; + } s = VPFUtils.readDelimitedText(buffer, ','); - if (s != null) + if (s != null) { col.description = s; + } s = VPFUtils.readDelimitedText(buffer, ','); - if (s != null) + if (s != null) { col.valueDescriptionTableName = s; + } s = VPFUtils.readDelimitedText(buffer, ','); - if (s != null) + if (s != null) { col.thematicIndexName = s; + } // Consume any remaining text, up to the sub column delimiter ':'. s = VPFUtils.readDelimitedText(buffer, ':'); - if (s != null) - { + if (s != null) { int pos = s.indexOf(","); - if (pos >= 0) - { + if (pos >= 0) { s = s.substring(0, pos); col.narrativeTableName = s; } @@ -246,11 +238,11 @@ protected Column readColumnDescription(ByteBuffer buffer) return col; } - protected static int parseNumElements(String numElements) - { + protected static int parseNumElements(String numElements) { // "*" denotes a field with variable length. - if (numElements == null || numElements.equals("*")) + if (numElements == null || numElements.equals("*")) { return -1; + } Integer i = WWUtil.convertStringToInteger(numElements); return (i != null) ? i : -1; @@ -259,81 +251,70 @@ protected static int parseNumElements(String numElements) //**************************************************************// //******************** Record Data ***************************// //**************************************************************// + protected interface RecordDataReader { - protected interface RecordDataReader - { VPFDataBuffer getDataBuffer(); void read(ByteBuffer byteBuffer); } - protected abstract static class AbstractDataReader implements RecordDataReader - { + protected abstract static class AbstractDataReader implements RecordDataReader { + protected VPFDataBuffer dataBuffer; - public AbstractDataReader(VPFDataBuffer dataBuffer) - { + public AbstractDataReader(VPFDataBuffer dataBuffer) { this.dataBuffer = dataBuffer; } - public VPFDataBuffer getDataBuffer() - { + public VPFDataBuffer getDataBuffer() { return this.dataBuffer; } } - protected static class FixedLengthDataReader extends AbstractDataReader - { + protected static class FixedLengthDataReader extends AbstractDataReader { + protected int numElements; - public FixedLengthDataReader(VPFDataBuffer dataBuffer, int numElements) - { + public FixedLengthDataReader(VPFDataBuffer dataBuffer, int numElements) { super(dataBuffer); this.numElements = numElements; } - public void read(ByteBuffer byteBuffer) - { + public void read(ByteBuffer byteBuffer) { this.dataBuffer.read(byteBuffer, this.numElements); } } - protected static class VariableLengthDataReader extends AbstractDataReader - { - public VariableLengthDataReader(VPFDataBuffer dataBuffer) - { + protected static class VariableLengthDataReader extends AbstractDataReader { + + public VariableLengthDataReader(VPFDataBuffer dataBuffer) { super(dataBuffer); } - public void read(ByteBuffer byteBuffer) - { + public void read(ByteBuffer byteBuffer) { this.dataBuffer.read(byteBuffer); } } - protected VPFBufferedRecordData readRecordData(ByteBuffer byteBuffer, Column[] columns, RecordIndex recordIndex) - { + protected VPFBufferedRecordData readRecordData(ByteBuffer byteBuffer, Column[] columns, RecordIndex recordIndex) { int numRows = recordIndex.numEntries; int numColumns = columns.length; // Create data readers for each column. RecordDataReader[] readers = new RecordDataReader[numColumns]; - for (int col = 0; col < numColumns; col++) - { + for (int col = 0; col < numColumns; col++) { VPFDataType type = VPFDataType.fromTypeName(columns[col].dataType); VPFDataBuffer dataBuffer = type.createDataBuffer(numRows, columns[col].numElements); - readers[col] = columns[col].isVariableLengthField() ? - new VariableLengthDataReader(dataBuffer) - : new FixedLengthDataReader(dataBuffer, columns[col].numElements); + readers[col] = columns[col].isVariableLengthField() + ? new VariableLengthDataReader(dataBuffer) + : new FixedLengthDataReader(dataBuffer, columns[col].numElements); } // Read the column data associated with each row. - for (int row = 0; row < numRows; row++) - { + for (int row = 0; row < numRows; row++) { byteBuffer.position(recordIndex.entries[row].offset); - for (int col = 0; col < numColumns; col++) - { + for (int col = 0; col < numColumns; col++) { readers[col].read(byteBuffer); } } @@ -342,15 +323,13 @@ protected VPFBufferedRecordData readRecordData(ByteBuffer byteBuffer, Column[] c recordData.setNumRecords(numRows); // Set the record data buffer associated with each column. - for (int col = 0; col < numColumns; col++) - { + for (int col = 0; col < numColumns; col++) { recordData.setRecordData(columns[col].name, readers[col].getDataBuffer()); // Compute an index for any columns which are identified as primary keys or unique keys. - if (!columns[col].name.equals(VPFConstants.ID) && - (columns[col].name.equals(VPFConstants.PRIMARY_KEY) || - columns[col].name.equals(VPFConstants.UNIQUE_KEY))) - { + if (!columns[col].name.equals(VPFConstants.ID) + && (columns[col].name.equals(VPFConstants.PRIMARY_KEY) + || columns[col].name.equals(VPFConstants.UNIQUE_KEY))) { recordData.buildRecordIndex(columns[col].name); } } @@ -361,16 +340,14 @@ protected VPFBufferedRecordData readRecordData(ByteBuffer byteBuffer, Column[] c //**************************************************************// //******************** Record Index **************************// //**************************************************************// + public static class RecordIndex { + + public static class Entry { - public static class RecordIndex - { - public static class Entry - { public int offset; public int length; - public Entry(int offset, int length) - { + public Entry(int offset, int length) { this.offset = offset; this.length = length; } @@ -380,8 +357,7 @@ public Entry(int offset, int length) public int headerLength; public Entry[] entries; - public RecordIndex() - { + public RecordIndex() { } } @@ -394,8 +370,7 @@ public RecordIndex() * * @return the name of a variable-length index file associated with the table name., */ - protected static String getRecordIndexFilename(String tableName) - { + protected static String getRecordIndexFilename(String tableName) { boolean isFcs = tableName.equalsIgnoreCase(VPFConstants.FEATURE_CLASS_SCHEMA_TABLE); StringBuilder sb = new StringBuilder(); @@ -407,10 +382,8 @@ protected static String getRecordIndexFilename(String tableName) return sb.toString(); } - protected RecordIndex readRecordIndex(File file) - { - try - { + protected RecordIndex readRecordIndex(File file) { + try { ByteBuffer buffer = this.readFileToBuffer(file); buffer.order(ByteOrder.LITTLE_ENDIAN); // Default to least significant byte first order. @@ -419,33 +392,27 @@ protected RecordIndex readRecordIndex(File file) index.headerLength = buffer.getInt(); index.entries = new RecordIndex.Entry[index.numEntries]; - for (int i = 0; i < index.numEntries; i++) - { + for (int i = 0; i < index.numEntries; i++) { int recordOffset = buffer.getInt(); int recordLength = buffer.getInt(); index.entries[i] = new RecordIndex.Entry(recordOffset, recordLength); } return index; - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("VPF.ExceptionAttemptingToReadRecordIndex", file.getPath()); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message, e); } } - protected RecordIndex computeRecordIndex(ByteBuffer buffer, Header header) - { + protected RecordIndex computeRecordIndex(ByteBuffer buffer, Header header) { // Compute a fixed length record size by summing the sizes of individual columns. Assume that the bytes of row // values are tightly packed. int recordLength = 0; - for (Column col : header.columns) - { + for (Column col : header.columns) { // If any column contains a variable length field, then we cannot compute a record size for this table. - if (col.isVariableLengthField()) - { + if (col.isVariableLengthField()) { return null; } @@ -465,8 +432,7 @@ protected RecordIndex computeRecordIndex(ByteBuffer buffer, Header header) index.entries = new RecordIndex.Entry[numRecords]; int offset = bodyOffset; - for (int i = 0; i < numRecords; i++) - { + for (int i = 0; i < numRecords; i++) { index.entries[i] = new RecordIndex.Entry(offset, recordLength); offset += index.entries[i].length; } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFTile.java b/src/gov/nasa/worldwind/formats/vpf/VPFTile.java index 4fd4a3bcf4..3bce72b30c 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFTile.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFTile.java @@ -13,23 +13,20 @@ * @author dcollins * @version $Id: VPFTile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFTile implements ExtentHolder -{ +public class VPFTile implements ExtentHolder { + private int id; private String name; private VPFBoundingBox bounds; - public VPFTile(int id, String name, VPFBoundingBox bounds) - { - if (name == null) - { + public VPFTile(int id, String name, VPFBoundingBox bounds) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bounds == null) - { + if (bounds == null) { String message = Logging.getMessage("nullValue.BoundingBoxIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -40,25 +37,20 @@ public VPFTile(int id, String name, VPFBoundingBox bounds) this.bounds = bounds; } - public int getId() - { + public int getId() { return this.id; } - public String getName() - { + public String getName() { return this.name; } - public VPFBoundingBox getBounds() - { + public VPFBoundingBox getBounds() { return this.bounds; } - public Extent getExtent(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + public Extent getExtent(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -67,36 +59,38 @@ public Extent getExtent(Globe globe, double verticalExaggeration) return Sector.computeBoundingCylinder(globe, verticalExaggeration, this.bounds.toSector()); } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } VPFTile vpfTile = (VPFTile) o; - if (id != vpfTile.id) + if (id != vpfTile.id) { return false; - if (bounds != null ? !bounds.equals(vpfTile.bounds) : vpfTile.bounds != null) + } + if (bounds != null ? !bounds.equals(vpfTile.bounds) : vpfTile.bounds != null) { return false; + } //noinspection RedundantIfStatement - if (name != null ? !name.equals(vpfTile.name) : vpfTile.name != null) + if (name != null ? !name.equals(vpfTile.name) : vpfTile.name != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result = id; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (bounds != null ? bounds.hashCode() : 0); return result; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.id); sb.append(": "); diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFTripletId.java b/src/gov/nasa/worldwind/formats/vpf/VPFTripletId.java index 73050237b6..74a1bf42aa 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFTripletId.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFTripletId.java @@ -9,31 +9,27 @@ * @author dcollins * @version $Id: VPFTripletId.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFTripletId -{ +public class VPFTripletId { + private int id; private int tileId; private int extId; - public VPFTripletId(int id, int tileId, int extId) - { + public VPFTripletId(int id, int tileId, int extId) { this.id = id; this.tileId = tileId; this.extId = extId; } - public int getId() - { + public int getId() { return this.id; } - public int getTileId() - { + public int getTileId() { return this.tileId; } - public int getExtId() - { + public int getExtId() { return this.extId; } } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFUtils.java b/src/gov/nasa/worldwind/formats/vpf/VPFUtils.java index 7a48a1c68e..056699540e 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFUtils.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFUtils.java @@ -16,124 +16,97 @@ * @author dcollins * @version $Id: VPFUtils.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFUtils -{ - public static VPFBufferedRecordData readTable(File file) - { - if (file == null) - { +public class VPFUtils { + + public static VPFBufferedRecordData readTable(File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists()) - { + if (!file.exists()) { return null; } - try - { + try { VPFTableReader tableReader = new VPFTableReader(); return tableReader.read(file); - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { // Exception already logged by VPFTableReader. return null; } } - public static VPFDatabase readDatabase(File file) - { - if (file == null) - { + public static VPFDatabase readDatabase(File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists()) - { + if (!file.exists()) { return null; } - try - { + try { return VPFDatabase.fromFile(file.getPath()); - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { // Exception already logged by VPFLibrary. return null; } } - public static VPFLibrary readLibrary(VPFDatabase database, String name) - { - if (database == null) - { + public static VPFLibrary readLibrary(VPFDatabase database, String name) { + if (database == null) { String message = Logging.getMessage("nullValue.DatabaseIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return VPFLibrary.fromFile(database, name); - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { // Exception already logged by VPFLibrary. return null; } } - public static VPFCoverage readCoverage(VPFLibrary library, String name) - { - if (library == null) - { + public static VPFCoverage readCoverage(VPFLibrary library, String name) { + if (library == null) { String message = Logging.getMessage("nullValue.LibraryIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return VPFCoverage.fromFile(library, name); - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { // Exception already logged by VPFCoverage. return null; } } - public static VPFFeatureClass[] readFeatureClasses(VPFCoverage coverage, FileFilter featureTableFilter) - { - if (coverage == null) - { + public static VPFFeatureClass[] readFeatureClasses(VPFCoverage coverage, FileFilter featureTableFilter) { + if (coverage == null) { String message = Logging.getMessage("nullValue.CoverageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (featureTableFilter == null) - { + if (featureTableFilter == null) { String message = Logging.getMessage("nullValue.FilterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -143,18 +116,15 @@ public static VPFFeatureClass[] readFeatureClasses(VPFCoverage coverage, FileFil VPFFeatureClass[] cls = new VPFFeatureClass[schemas.length]; VPFFeatureClassFactory factory = new VPFBasicFeatureClassFactory(); - for (int i = 0; i < schemas.length; i++) - { + for (int i = 0; i < schemas.length; i++) { cls[i] = factory.createFromSchema(coverage, schemas[i]); } return cls; } - public static String readDelimitedText(ByteBuffer buffer, char delim) - { - if (buffer == null) - { + public static String readDelimitedText(ByteBuffer buffer, char delim) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -164,11 +134,11 @@ public static String readDelimitedText(ByteBuffer buffer, char delim) int remain = buffer.remaining(); int i; - for (i = 0; i < remain; i++) - { + for (i = 0; i < remain; i++) { byte b = buffer.get(); - if (delim == (char) b) + if (delim == (char) b) { break; + } sb.append((char) b); } @@ -176,41 +146,36 @@ public static String readDelimitedText(ByteBuffer buffer, char delim) return (i < remain) ? sb.toString().trim() : null; } - public static void checkAndSetValue(VPFRecord record, String paramName, String paramKey, AVList params) - { - if (record == null) - { + public static void checkAndSetValue(VPFRecord record, String paramName, String paramKey, AVList params) { + if (record == null) { String message = Logging.getMessage("nullValue.RecordIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (record.hasValue(paramName)) - { + if (record.hasValue(paramName)) { Object o = record.getValue(paramName); - if (o != null) + if (o != null) { params.setValue(paramKey, o); + } } } @@ -221,47 +186,45 @@ public static void checkAndSetValue(VPFRecord record, String paramName, String p * * @return extent of the specified row. */ - public static VPFBoundingBox getExtent(VPFRecord record) - { - if (record == null) - { + public static VPFBoundingBox getExtent(VPFRecord record) { + if (record == null) { String message = Logging.getMessage("nullValue.RecordIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new VPFBoundingBox( - ((Number) record.getValue("xmin")).doubleValue(), - ((Number) record.getValue("ymin")).doubleValue(), - ((Number) record.getValue("xmax")).doubleValue(), - ((Number) record.getValue("ymax")).doubleValue()); + ((Number) record.getValue("xmin")).doubleValue(), + ((Number) record.getValue("ymin")).doubleValue(), + ((Number) record.getValue("xmax")).doubleValue(), + ((Number) record.getValue("ymax")).doubleValue()); } - public static String getFeatureTypeName(String tableName) - { - if (tableName == null) - { + public static String getFeatureTypeName(String tableName) { + if (tableName == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String suffix = WWIO.getSuffix(tableName); - if (suffix == null) + if (suffix == null) { return null; + } suffix = "." + suffix; - if (suffix.equalsIgnoreCase(VPFConstants.POINT_FEATURE_TABLE)) + if (suffix.equalsIgnoreCase(VPFConstants.POINT_FEATURE_TABLE)) { return VPFConstants.POINT_FEATURE_TYPE; - else if (suffix.equalsIgnoreCase(VPFConstants.LINE_FEATURE_TABLE)) + } else if (suffix.equalsIgnoreCase(VPFConstants.LINE_FEATURE_TABLE)) { return VPFConstants.LINE_FEATURE_TYPE; - else if (suffix.equalsIgnoreCase(VPFConstants.AREA_FEATURE_TABLE)) + } else if (suffix.equalsIgnoreCase(VPFConstants.AREA_FEATURE_TABLE)) { return VPFConstants.AREA_FEATURE_TYPE; - else if (suffix.equalsIgnoreCase(VPFConstants.TEXT_FEATURE_TABLE)) + } else if (suffix.equalsIgnoreCase(VPFConstants.TEXT_FEATURE_TABLE)) { return VPFConstants.TEXT_FEATURE_TYPE; - else if (suffix.equalsIgnoreCase(VPFConstants.COMPLEX_FEATURE_TABLE)) + } else if (suffix.equalsIgnoreCase(VPFConstants.COMPLEX_FEATURE_TABLE)) { return VPFConstants.COMPLEX_FEATURE_TYPE; + } return null; } diff --git a/src/gov/nasa/worldwind/formats/vpf/VPFWingedEdgeTraverser.java b/src/gov/nasa/worldwind/formats/vpf/VPFWingedEdgeTraverser.java index 0e98f2488b..c6247e2a39 100644 --- a/src/gov/nasa/worldwind/formats/vpf/VPFWingedEdgeTraverser.java +++ b/src/gov/nasa/worldwind/formats/vpf/VPFWingedEdgeTraverser.java @@ -13,22 +13,20 @@ * @author dcollins * @version $Id: VPFWingedEdgeTraverser.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VPFWingedEdgeTraverser -{ - public interface EdgeTraversalListener - { +public class VPFWingedEdgeTraverser { + + public interface EdgeTraversalListener { + void nextEdge(int index, int primitiveId, boolean reverseCoordinates); } - protected enum Orientation - { + protected enum Orientation { LEFT, RIGHT, LEFT_AND_RIGHT } - public VPFWingedEdgeTraverser() - { + public VPFWingedEdgeTraverser() { } /** @@ -44,8 +42,7 @@ public VPFWingedEdgeTraverser() * @return the number of edges composing the specified ring. */ public int traverseRing(int faceId, int startEdgeId, VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray, - EdgeTraversalListener listener) - { + EdgeTraversalListener listener) { // 1. Determine which face primitive to construct. // The face is determined for us by the selection of a row in the face primitive table. @@ -53,51 +50,43 @@ public int traverseRing(int faceId, int startEdgeId, VPFPrimitiveData.PrimitiveI // Select the row in the ring primitive table which is associated with the face primitive. Then select the row // in the edge primitive table which corresponds to the ring primitive. Essentially, we follow the face to a // ring, and the ring to a starting edge. - // 3. Follow the edge network until we arrive back at the starting edge, or the data does not specify a next // edge. Travel in the direction according to which side of the edge (left or right) the face belongs to. If we // reach an auxiliary edge (face is both left and right of the edge), then travel to the next edge which does // not cause us to backtrack. - int count = 0; int prevEdgeId; int curEdgeId = -1; int nextEdgeId = startEdgeId; - do - { + do { prevEdgeId = curEdgeId; curEdgeId = nextEdgeId; - if (listener != null) - { + if (listener != null) { listener.nextEdge(count, curEdgeId, this.getMustReverseCoordinates(faceId, prevEdgeId, curEdgeId, - edgeInfoArray)); + edgeInfoArray)); } count++; - } - while ((nextEdgeId = this.nextEdgeId(faceId, prevEdgeId, curEdgeId, edgeInfoArray)) > 0 - && (nextEdgeId != startEdgeId)); + } while ((nextEdgeId = this.nextEdgeId(faceId, prevEdgeId, curEdgeId, edgeInfoArray)) > 0 + && (nextEdgeId != startEdgeId)); return count; } - protected int nextEdgeId(int faceId, int prevEdgeId, int curEdgeId, VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray) - { + protected int nextEdgeId(int faceId, int prevEdgeId, int curEdgeId, VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray) { // The next edge depends on which side of this edge (left or right) the face belongs to. If the face is on // the left side of this edge, we travel to the left edge, and visa versa. However if this is an auxiliary // edge (face is both left and right of the edge), then travel to the next edge which does not cause us to // backtrack. Orientation o = this.getOrientation(faceId, curEdgeId, edgeInfoArray); - if (o == null) - { + if (o == null) { return -1; } - switch (o) - { + switch (o) { case LEFT: return getEdgeInfo(edgeInfoArray, curEdgeId).getLeftEdge(); case RIGHT: @@ -109,8 +98,7 @@ protected int nextEdgeId(int faceId, int prevEdgeId, int curEdgeId, VPFPrimitive } } - protected Orientation getOrientation(int faceId, int edgeId, VPFPrimitiveData.PrimitiveInfo[] edgeInfo) - { + protected Orientation getOrientation(int faceId, int edgeId, VPFPrimitiveData.PrimitiveInfo[] edgeInfo) { VPFPrimitiveData.EdgeInfo thisInfo = getEdgeInfo(edgeInfo, edgeId); boolean matchLeft = thisInfo.getLeftFace() == faceId; boolean matchRight = thisInfo.getRightFace() == faceId; @@ -118,13 +106,9 @@ protected Orientation getOrientation(int faceId, int edgeId, VPFPrimitiveData.Pr if (matchLeft && matchRight) // Auxiliary edge has the same face on both sides. { return Orientation.LEFT_AND_RIGHT; - } - else if (matchLeft) - { + } else if (matchLeft) { return Orientation.LEFT; - } - else if (matchRight) - { + } else if (matchRight) { return Orientation.RIGHT; } @@ -132,8 +116,7 @@ else if (matchRight) } protected boolean getMustReverseCoordinates(int faceId, int prevEdgeId, int curEdgeId, - VPFPrimitiveData.PrimitiveInfo[] edgeInfo) - { + VPFPrimitiveData.PrimitiveInfo[] edgeInfo) { // Determine whether or not this edge's coordinate array must be reversed to provide a consistent ordering // of ring coordinates. There are two cases which cause the coordinates to need reversal: // 1. If the edge has left orientation, then we will travel backwards along this edge to arrive at the next @@ -142,13 +125,11 @@ protected boolean getMustReverseCoordinates(int faceId, int prevEdgeId, int curE // we *may* travel backwards along this edge. Orientation o = this.getOrientation(faceId, curEdgeId, edgeInfo); - if (o == null) - { + if (o == null) { return false; } - switch (o) - { + switch (o) { case LEFT: return true; case RIGHT: @@ -161,8 +142,7 @@ protected boolean getMustReverseCoordinates(int faceId, int prevEdgeId, int curE } protected int auxiliaryNextEdgeId(int prevEdgeId, int curEdgeId, - VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray) - { + VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray) { // Note: an edge which has the same face for both its left and right faces is known to be an "auxiliary edge". // Using auxiliary edges is a solution to defining a face (polygon) with holes. The face becomes a single loop, // with an auxiliary edge joining each inner and outer loop. The auxiliary edge is traversed twice; one upon @@ -172,33 +152,26 @@ protected int auxiliaryNextEdgeId(int prevEdgeId, int curEdgeId, VPFPrimitiveData.EdgeInfo curInfo = getEdgeInfo(edgeInfoArray, curEdgeId); // Previous edge is adjacent to starting node. - if (curInfo.getStartNode() == prevInfo.getStartNode() || curInfo.getStartNode() == prevInfo.getEndNode()) - { + if (curInfo.getStartNode() == prevInfo.getStartNode() || curInfo.getStartNode() == prevInfo.getEndNode()) { return (curInfo.getRightEdge() != curEdgeId) ? curInfo.getRightEdge() : curInfo.getLeftEdge(); - } - // Previous edge is adjacent to ending node. - else if (curInfo.getEndNode() == prevInfo.getStartNode() || curInfo.getEndNode() == prevInfo.getEndNode()) - { + } // Previous edge is adjacent to ending node. + else if (curInfo.getEndNode() == prevInfo.getStartNode() || curInfo.getEndNode() == prevInfo.getEndNode()) { return (curInfo.getLeftEdge() != curEdgeId) ? curInfo.getLeftEdge() : curInfo.getRightEdge(); - } - // Edges are not actually adjacent. This should never happen, but we check anyway. - else - { + } // Edges are not actually adjacent. This should never happen, but we check anyway. + else { return -1; } } protected boolean auxiliaryMustReverseCoordinates(int prevEdgeId, int curEdgeId, - VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray) - { + VPFPrimitiveData.PrimitiveInfo[] edgeInfoArray) { VPFPrimitiveData.EdgeInfo prevInfo = getEdgeInfo(edgeInfoArray, prevEdgeId); VPFPrimitiveData.EdgeInfo curInfo = getEdgeInfo(edgeInfoArray, curEdgeId); return curInfo.getEndNode() == prevInfo.getStartNode() || curInfo.getEndNode() == prevInfo.getEndNode(); } - protected static VPFPrimitiveData.EdgeInfo getEdgeInfo(VPFPrimitiveData.PrimitiveInfo[] edgeInfo, int id) - { + protected static VPFPrimitiveData.EdgeInfo getEdgeInfo(VPFPrimitiveData.PrimitiveInfo[] edgeInfo, int id) { return (VPFPrimitiveData.EdgeInfo) edgeInfo[VPFBufferedRecordData.indexFromId(id)]; } } diff --git a/src/gov/nasa/worldwind/formats/worldfile/WorldFile.java b/src/gov/nasa/worldwind/formats/worldfile/WorldFile.java index 6cd5e2f1a6..d03ae60709 100644 --- a/src/gov/nasa/worldwind/formats/worldfile/WorldFile.java +++ b/src/gov/nasa/worldwind/formats/worldfile/WorldFile.java @@ -22,8 +22,8 @@ * @author tag * @version $Id: WorldFile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WorldFile -{ +public class WorldFile { + public final static String WORLD_FILE_X_PIXEL_SIZE = "gov.nasa.worldwind.worldFile.XPixelSize"; public final static String WORLD_FILE_Y_PIXEL_SIZE = "gov.nasa.worldwind.worldFile.YPixelSize"; public final static String WORLD_FILE_X_COEFFICIENT = "gov.nasa.worldwind.worldFile.XCoefficient"; @@ -40,19 +40,16 @@ public class WorldFile * @return the metadata files that exist in the same directory as the data file, otherwise null. * * @throws IllegalArgumentException if the data file is null. - * @throws FileNotFoundException if the data file does not exist. + * @throws FileNotFoundException if the data file does not exist. */ - public static File[] getWorldFiles(File dataFile) throws FileNotFoundException - { - if (dataFile == null) - { + public static File[] getWorldFiles(File dataFile) throws FileNotFoundException { + if (dataFile == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!dataFile.exists()) - { + if (!dataFile.exists()) { String message = Logging.getMessage("generic.FileNotFound", dataFile.getPath()); Logging.logger().severe(message); throw new FileNotFoundException(message); @@ -62,24 +59,22 @@ public static File[] getWorldFiles(File dataFile) throws FileNotFoundException final String imageSuffix = WWIO.getSuffix(dataFile.getPath()); final String base = WWIO.replaceSuffix(dataFile.getName(), "").trim(); - return dir.listFiles(new FilenameFilter() - { - public boolean accept(File dir, String name) - { + return dir.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { int length = base.length() + 4; name = name.trim(); - if (!name.startsWith(base) || name.length() != length) + if (!name.startsWith(base) || name.length() != length) { return false; + } - if (name.toLowerCase().endsWith("w")) - { + if (name.toLowerCase().endsWith("w")) { // Match world file to the corresponding image file: certain chars of suffixes must match String nameSuffix = WWIO.getSuffix(name); - if (imageSuffix != null && nameSuffix != null) - { + if (imageSuffix != null && nameSuffix != null) { if (nameSuffix.substring(0, 1).equalsIgnoreCase(imageSuffix.substring(0, 1)) - && imageSuffix.toLowerCase().endsWith(nameSuffix.substring(1, 2))) + && imageSuffix.toLowerCase().endsWith(nameSuffix.substring(1, 2))) { return true; + } } } @@ -92,30 +87,27 @@ public boolean accept(File dir, String name) * Retrieves the useful values from a collection of world files. * * @param worldFiles the world files. - * @param values may contain a buffered image, needed to retrieve image size + * @param values may contain a buffered image, needed to retrieve image size * * @return an attribute-value list containing the values from the world files. * * @throws IllegalArgumentException if the file is null. - * @throws FileNotFoundException if the file does not exist. - * @throws IllegalStateException if the file cannot be parsed as a world file. + * @throws FileNotFoundException if the file does not exist. + * @throws IllegalStateException if the file cannot be parsed as a world file. */ - public static AVList decodeWorldFiles(File worldFiles[], AVList values) throws FileNotFoundException - { - if (worldFiles == null) - { + public static AVList decodeWorldFiles(File worldFiles[], AVList values) throws FileNotFoundException { + if (worldFiles == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (values == null) + if (values == null) { values = new AVListImpl(); + } - for (File file : worldFiles) - { - if (!file.exists()) - { + for (File file : worldFiles) { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file.getPath()); Logging.logger().severe(message); throw new FileNotFoundException(message); @@ -123,19 +115,13 @@ public static AVList decodeWorldFiles(File worldFiles[], AVList values) throws F } //File transformFile = null; - for (File file : worldFiles) - { - if (file.getName().toLowerCase().endsWith("w")) - { + for (File file : worldFiles) { + if (file.getName().toLowerCase().endsWith("w")) { scanWorldFile(file, values); //transformFile = file; - } - else if (file.getName().toLowerCase().endsWith(".hdr")) - { + } else if (file.getName().toLowerCase().endsWith(".hdr")) { scanHdrFile(file, values); - } - else if (file.getName().toLowerCase().endsWith(".prj")) - { + } else if (file.getName().toLowerCase().endsWith(".prj")) { String text = WWIO.readTextFile(file); decodeOGCCoordinateSystemWKT(text, values); } @@ -143,80 +129,71 @@ else if (file.getName().toLowerCase().endsWith(".prj")) int[] size; Object o = values.getValue(WORLD_FILE_IMAGE_SIZE); - if (o != null && (o instanceof int[])) - { + if (o != null && (o instanceof int[])) { size = (int[]) o; - } - else - { + } else { size = WorldFile.parseSize(values); - if (size != null) + if (size != null) { values.setValue(WORLD_FILE_IMAGE_SIZE, size); + } } o = WorldFile.parseByteOrder(values); - if (o != null) + if (o != null) { values.setValue(AVKey.BYTE_ORDER, o); + } o = WorldFile.parsePixelFormat(values); - if (o != null) + if (o != null) { values.setValue(AVKey.PIXEL_FORMAT, o); + } o = WorldFile.parseDataType(values); - if (o != null) + if (o != null) { values.setValue(AVKey.DATA_TYPE, o); + } // Consumers of this property are expecting the string "gov.nasa.worldwind.avkey.MissingDataValue", which now // corresponds to the key MISSING_DATA_REPLACEMENT. o = WorldFile.parseMissingDataValue(values); - if (o != null) + if (o != null) { values.setValue(AVKey.MISSING_DATA_REPLACEMENT, o); + } Sector sector = null; - if (WorldFile.worldFileValuesAppearGeographic(values)) - { - if (size != null) - { + if (WorldFile.worldFileValuesAppearGeographic(values)) { + if (size != null) { sector = WorldFile.parseDegrees(values, size[0], size[1]); - } - else - { + } else { BufferedImage image = (BufferedImage) values.getValue(AVKey.IMAGE); - if (image != null) - { + if (image != null) { sector = WorldFile.parseDegrees(values, image.getWidth(), image.getHeight()); } } - if (sector != null) - { + if (sector != null) { values.setValue(AVKey.SECTOR, sector); } } - if (null == sector) - { + if (null == sector) { sector = WorldFile.extractSectorFromHeader(values); // TODO: not checking for non-geographic proj - if (sector != null) + if (sector != null) { values.setValue(AVKey.SECTOR, sector); + } } return values; } - protected static void scanWorldFile(File file, AVList values) throws FileNotFoundException - { + protected static void scanWorldFile(File file, AVList values) throws FileNotFoundException { Scanner scanner = new Scanner(file); scanner.useLocale(Locale.US); - try - { - for (int i = 0; i < 6; i++) - { - if (scanner.hasNextDouble()) - { - switch (i) - { + try { + for (int i = 0; i < 6; i++) { + if (scanner.hasNextDouble()) { + switch (i) { case 0: values.setValue(WORLD_FILE_X_PIXEL_SIZE, scanner.nextDouble()); break; @@ -236,151 +213,113 @@ protected static void scanWorldFile(File file, AVList values) throws FileNotFoun values.setValue(WORLD_FILE_Y_LOCATION, scanner.nextDouble()); break; } - } - else - { + } else { String message = Logging.getMessage("SurfaceImage.WorldFileLineMissing", i + 1); Logging.logger().severe(message); throw new IllegalStateException(message); } } - } - finally - { - if (null != scanner) + } finally { + if (null != scanner) { scanner.close(); + } } } - protected static void scanHdrFile(File file, AVList values) throws FileNotFoundException - { + protected static void scanHdrFile(File file, AVList values) throws FileNotFoundException { Scanner scanner = new Scanner(file); scanner.useLocale(Locale.US); - try - { - while (scanner.hasNext()) - { + try { + while (scanner.hasNext()) { String key = scanner.next().toUpperCase(); - if (!scanner.hasNext()) + if (!scanner.hasNext()) { return; // Error. Log it. - - if (key.equalsIgnoreCase("NROWS")) + } + if (key.equalsIgnoreCase("NROWS")) { values.setValue(key, scanner.nextInt()); - else if (key.equalsIgnoreCase("NCOLS")) + } else if (key.equalsIgnoreCase("NCOLS")) { values.setValue(key, scanner.nextInt()); - else if (key.equalsIgnoreCase("NBANDS")) + } else if (key.equalsIgnoreCase("NBANDS")) { values.setValue(key, scanner.nextInt()); - else if (key.equalsIgnoreCase("NBITS")) + } else if (key.equalsIgnoreCase("NBITS")) { values.setValue(key, scanner.nextInt()); - else if (key.equalsIgnoreCase("BANDROWBYTES")) - { + } else if (key.equalsIgnoreCase("BANDROWBYTES")) { // BANDROWBYTES number of bytes in one row of data values.setValue(key, scanner.nextInt()); - } - - else if (key.equalsIgnoreCase("TOTALROWBYTES")) - { + } else if (key.equalsIgnoreCase("TOTALROWBYTES")) { // TOTALROWBYTES number of bytes in one row of data (for multi-band) values.setValue(key, scanner.nextInt()); - } - - else if (key.equalsIgnoreCase("SKIPBYTES")) - { + } else if (key.equalsIgnoreCase("SKIPBYTES")) { // SKIPBYTES number of header bytes before data starts in binary file values.setValue(key, scanner.nextInt()); - } - else if (key.equalsIgnoreCase("NODATA") || key.equalsIgnoreCase("NODATA_VALUE")) - { + } else if (key.equalsIgnoreCase("NODATA") || key.equalsIgnoreCase("NODATA_VALUE")) { // NODATA_VALUE is a newer version of the NODATA keyword, often = -9999 double nodata = scanner.nextDouble(); values.setValue(key, nodata); values.setValue("NODATA", nodata); - } - else if (key.equalsIgnoreCase("ULXMAP")) - { + } else if (key.equalsIgnoreCase("ULXMAP")) { // ULXMAP center x-coordinate of grid cell in upper-left corner values.setValue(key, scanner.nextDouble()); - } - else if (key.equalsIgnoreCase("ULYMAP")) - { + } else if (key.equalsIgnoreCase("ULYMAP")) { // ULYMAP center y-coordinate of grid cell in upper-left corner values.setValue(key, scanner.nextDouble()); - } - else if (key.equalsIgnoreCase("XLLCORNER")) - { + } else if (key.equalsIgnoreCase("XLLCORNER")) { // XLLCORNER left-edge x-coordinate of grid cell in lower-left corner values.setValue(key, scanner.nextDouble()); - } - else if (key.equalsIgnoreCase("YLLCORNER")) - { + } else if (key.equalsIgnoreCase("YLLCORNER")) { // YLLCORNER bottom y-coordinate of grid cell in lower-left corner values.setValue(key, scanner.nextDouble()); - } - else if (key.equalsIgnoreCase("XLLCENTER")) - { + } else if (key.equalsIgnoreCase("XLLCENTER")) { // XLLCENTER center x-coordinate of grid cell in lower-left corner values.setValue(key, scanner.nextDouble()); - } - else if (key.equalsIgnoreCase("YLLCCENTER")) - { + } else if (key.equalsIgnoreCase("YLLCCENTER")) { // YLLCCENTER center y-coordinate of grid cell in lower-left corner values.setValue(key, scanner.nextDouble()); - } - else if (key.equalsIgnoreCase("XDIM")) + } else if (key.equalsIgnoreCase("XDIM")) { values.setValue(key, scanner.nextDouble()); - else if (key.equalsIgnoreCase("YDIM")) + } else if (key.equalsIgnoreCase("YDIM")) { values.setValue(key, scanner.nextDouble()); - else if (key.equalsIgnoreCase("CELLSIZE")) - { + } else if (key.equalsIgnoreCase("CELLSIZE")) { // CELLSIZE size of a grid cell, using this keyword implies same size in x and y double cell_size = scanner.nextDouble(); values.setValue(key, cell_size); values.setValue("XDIM", cell_size); values.setValue("YDIM", cell_size); - } - else if (key.equalsIgnoreCase("PIXELTYPE")) - { + } else if (key.equalsIgnoreCase("PIXELTYPE")) { values.setValue(key, scanner.next()); - } - else if (key.equalsIgnoreCase("BYTEORDER")) - { + } else if (key.equalsIgnoreCase("BYTEORDER")) { // BYTEORDER byte order (only relevant for binary files, e.g. BIL, FLT) // I or LSBFIRST for Intel, M or MSBFIRST for Motorola values.setValue(key, scanner.next()); - } - else + } else { values.setValue(key, scanner.next()); + } } // USGS NED 10m HDR files do not contain NBANDS, NBITS, and PIXELTYPE properties - if (!values.hasKey("NBANDS") || !values.hasKey("NBITS")) - { - if (values.hasKey(AVKey.FILE_SIZE) && values.hasKey("NCOLS") && values.hasKey("NROWS")) - { + if (!values.hasKey("NBANDS") || !values.hasKey("NBITS")) { + if (values.hasKey(AVKey.FILE_SIZE) && values.hasKey("NCOLS") && values.hasKey("NROWS")) { Integer nCols = (Integer) values.getValue("NCOLS"); Integer nRows = (Integer) values.getValue("NROWS"); Integer fileSize = (Integer) values.getValue(AVKey.FILE_SIZE); double bits = (((double) fileSize) / ((double) nCols) / ((double) nRows)) * 8d; - if (bits == 8d || bits == 16d || bits == 32d) - { + if (bits == 8d || bits == 16d || bits == 32d) { values.setValue("NBANDS", 1); values.setValue("NBITS", (int) bits); } - if (bits == 24d) - { + if (bits == 24d) { values.setValue("NBANDS", 3); values.setValue("NBITS", 8); } } } - } - finally - { - if (null != scanner) + } finally { + if (null != scanner) { scanner.close(); + } } } @@ -392,20 +331,17 @@ else if (key.equalsIgnoreCase("BYTEORDER")) * @return an array containing the six values in the order they are found in the world file. * * @throws IllegalArgumentException if the file is null. - * @throws FileNotFoundException if the file does not exist. - * @throws IllegalStateException if the file cannot be parsed as a world file. + * @throws FileNotFoundException if the file does not exist. + * @throws IllegalStateException if the file cannot be parsed as a world file. */ - public static double[] decodeWorldFile(File worldFile) throws FileNotFoundException - { - if (worldFile == null) - { + public static double[] decodeWorldFile(File worldFile) throws FileNotFoundException { + if (worldFile == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!worldFile.exists()) - { + if (!worldFile.exists()) { String message = Logging.getMessage("generic.FileNotFound", worldFile.getPath()); Logging.logger().severe(message); throw new FileNotFoundException(message); @@ -416,25 +352,18 @@ public static double[] decodeWorldFile(File worldFile) throws FileNotFoundExcept Scanner scanner = new Scanner(worldFile); scanner.useLocale(Locale.US); - try - { + try { - for (int i = 0; i < 6; i++) - { - if (scanner.hasNextDouble()) - { + for (int i = 0; i < 6; i++) { + if (scanner.hasNextDouble()) { values[i] = scanner.nextDouble(); - } - else - { + } else { String message = Logging.getMessage("SurfaceImage.WorldFileLineMissing", i + 1); Logging.logger().severe(message); throw new IllegalStateException(message); } } - } - finally - { + } finally { scanner.close(); } @@ -447,60 +376,59 @@ public static double[] decodeWorldFile(File worldFile) throws FileNotFoundExcept * @param values the six values to examine. * * @return true if the values are between the normal limits of latitude, [-90, 90], and longitude, [-180, 180], - * othewise false. + * othewise false. */ - public static boolean worldFileValuesAppearGeographic(AVList values) - { + public static boolean worldFileValuesAppearGeographic(AVList values) { double xLocation; double yLocation; double xPixelSize; double yPixelSize; Object o = values.getValue(WORLD_FILE_X_LOCATION); - if (o != null && o instanceof Double) + if (o != null && o instanceof Double) { xLocation = (Double) o; - else + } else { return false; + } o = values.getValue(WORLD_FILE_Y_LOCATION); - if (o != null && o instanceof Double) + if (o != null && o instanceof Double) { yLocation = (Double) o; - else + } else { return false; + } o = values.getValue(WORLD_FILE_X_PIXEL_SIZE); - if (o != null && o instanceof Double) + if (o != null && o instanceof Double) { xPixelSize = (Double) o; - else + } else { return false; + } o = values.getValue(WORLD_FILE_Y_PIXEL_SIZE); - if (o != null && o instanceof Double) + if (o != null && o instanceof Double) { yPixelSize = (Double) o; - else + } else { return false; + } return (Angle.isValidLongitude(xPixelSize) && Angle.isValidLatitude(yPixelSize) - && Angle.isValidLongitude(xLocation) && Angle.isValidLatitude(yLocation)); + && Angle.isValidLongitude(xLocation) && Angle.isValidLatitude(yLocation)); } public static Sector extractSectorFromHeader(AVList values) // TODO: assumes degrees { if (null != values - && values.hasKey("NROWS") && values.hasKey("NCOLS") - && values.hasKey("XDIM") && values.hasKey("YDIM") - ) - { + && values.hasKey("NROWS") && values.hasKey("NCOLS") + && values.hasKey("XDIM") && values.hasKey("YDIM")) { Integer nCols = (Integer) values.getValue("NCOLS"); Integer nRows = (Integer) values.getValue("NROWS"); double xDim = Math.abs((Double) values.getValue("XDIM")); double yDim = Math.abs((Double) values.getValue("YDIM")); if (values.hasKey("XLLCORNER") && values.hasKey("YLLCORNER") - && Angle.isValidLongitude((Double) values.getValue("XLLCORNER")) - && Angle.isValidLatitude((Double) values.getValue("YLLCORNER")) - ) - { + && Angle.isValidLongitude((Double) values.getValue("XLLCORNER")) + && Angle.isValidLatitude((Double) values.getValue("YLLCORNER"))) { // XLLCORNER,YLLCORNER left-edge x-coordinate and bottom y-coordinate of grid cell in lower-left corner double xmin = Angle.fromDegreesLongitude((Double) values.getValue("XLLCORNER")).degrees; @@ -513,10 +441,8 @@ public static Sector extractSectorFromHeader(AVList values) // TODO: assumes deg } if (values.hasKey("XLLCENTER") && values.hasKey("YLLCCENTER") - && Angle.isValidLongitude((Double) values.getValue("XLLCENTER")) - && Angle.isValidLatitude((Double) values.getValue("YLLCCENTER")) - ) - { + && Angle.isValidLongitude((Double) values.getValue("XLLCENTER")) + && Angle.isValidLatitude((Double) values.getValue("YLLCCENTER"))) { // XLLCENTER,YLLCCENTER are center coordinate of grid cell in lower-left corner double xmin = Angle.fromDegreesLongitude((Double) values.getValue("XLLCENTER") - (xDim / 2d)).degrees; double ymin = Angle.fromDegreesLatitude((Double) values.getValue("YLLCENTER") - (yDim / 2d)).degrees; @@ -528,10 +454,8 @@ public static Sector extractSectorFromHeader(AVList values) // TODO: assumes deg } if (values.hasKey("ULXMAP") && values.hasKey("ULYMAP") - && Angle.isValidLongitude((Double) values.getValue("ULXMAP")) - && Angle.isValidLatitude((Double) values.getValue("ULYMAP")) - ) - { + && Angle.isValidLongitude((Double) values.getValue("ULXMAP")) + && Angle.isValidLatitude((Double) values.getValue("ULYMAP"))) { // ULXMAP and ULYMAP are center coordinates of grid cell in upper-left corner double xmin = Angle.fromDegreesLongitude((Double) values.getValue("ULXMAP") - (xDim / 2d)).degrees; double ymax = Angle.fromDegreesLatitude((Double) values.getValue("ULYMAP") + (yDim / 2d)).degrees; @@ -545,61 +469,63 @@ public static Sector extractSectorFromHeader(AVList values) // TODO: assumes deg return null; } - public static int[] parseSize(AVList values) - { - if (values == null) + public static int[] parseSize(AVList values) { + if (values == null) { return null; + } - if (!values.hasKey("NROWS") && !values.hasKey("NCOLS")) + if (!values.hasKey("NROWS") && !values.hasKey("NCOLS")) { return null; + } - return new int[] {(Integer) values.getValue("NCOLS"), (Integer) values.getValue("NROWS")}; + return new int[]{(Integer) values.getValue("NCOLS"), (Integer) values.getValue("NROWS")}; } - public static Object parseByteOrder(AVList values) - { - if (values == null) + public static Object parseByteOrder(AVList values) { + if (values == null) { return null; + } - if (!values.hasKey("BYTEORDER")) + if (!values.hasKey("BYTEORDER")) { return null; + } String s = values.getValue("BYTEORDER").toString(); return (s.equalsIgnoreCase("I") || s.equalsIgnoreCase("LSBFIRST")) ? AVKey.LITTLE_ENDIAN : AVKey.BIG_ENDIAN; } - public static Object parsePixelFormat(AVList values) - { - if (values == null) + public static Object parsePixelFormat(AVList values) { + if (values == null) { return null; + } - if (values.hasKey("NBANDS") && values.hasKey("NBITS")) - { + if (values.hasKey("NBANDS") && values.hasKey("NBITS")) { Integer nBands = (Integer) values.getValue("NBANDS"); Integer nBits = (Integer) values.getValue("NBITS"); - if (nBands == 1 && (nBits == 16 || nBits == 32)) + if (nBands == 1 && (nBits == 16 || nBits == 32)) { return AVKey.ELEVATION; - if (nBands == 1 && nBits == 8) + } + if (nBands == 1 && nBits == 8) { return AVKey.IMAGE; - if (nBands == 3 && nBits == 8) + } + if (nBands == 3 && nBits == 8) { return AVKey.IMAGE; + } } return null; } - public static Object parseDataType(AVList values) - { - if (values == null) + public static Object parseDataType(AVList values) { + if (values == null) { return null; + } - if (values.hasKey("NBITS")) - { + if (values.hasKey("NBITS")) { Integer nBits = (Integer) values.getValue("NBITS"); - switch (nBits) - { + switch (nBits) { case 8: return AVKey.INT8; case 16: @@ -607,24 +533,24 @@ public static Object parseDataType(AVList values) case 32: return AVKey.FLOAT32; } - } - else if (values.hasKey("PIXELTYPE")) - { + } else if (values.hasKey("PIXELTYPE")) { String pixelType = (String) values.getValue("PIXELTYPE"); - if ("FLOAT".equalsIgnoreCase(pixelType)) + if ("FLOAT".equalsIgnoreCase(pixelType)) { return AVKey.FLOAT32; + } } return null; } - public static Object parseMissingDataValue(AVList values) - { - if (values == null) + public static Object parseMissingDataValue(AVList values) { + if (values == null) { return null; + } - if (!values.hasKey("NODATA")) + if (!values.hasKey("NODATA")) { return null; + } return values.getValue("NODATA"); } @@ -633,29 +559,25 @@ public static Object parseMissingDataValue(AVList values) * Decodes the six values of a world file in the lat/lon coordinate system to a Sector. The rotation values are * ignored. * - * @param values the values to parse - * @param imageWidth the width of the image associated with the world file. + * @param values the values to parse + * @param imageWidth the width of the image associated with the world file. * @param imageHeight the height of the image associated with the world file. * * @return a sector computed from the world file values. * * @throws IllegalArgumentException if the values array is null or has a length less than six, or the image width - * and height are less than zero. - * @throws IllegalStateException if the decoded values are not within the normal range of latituded and - * longitude. + * and height are less than zero. + * @throws IllegalStateException if the decoded values are not within the normal range of latituded and longitude. * @see #worldFileValuesAppearGeographic(gov.nasa.worldwind.avlist.AVList) */ - public static Sector parseDegrees(AVList values, int imageWidth, int imageHeight) - { - if (values == null) - { + public static Sector parseDegrees(AVList values, int imageWidth, int imageHeight) { + if (values == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (imageWidth <= 0 || imageHeight <= 0) - { + if (imageWidth <= 0 || imageHeight <= 0) { String message = Logging.getMessage("generic.InvalidImageSize"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -671,33 +593,26 @@ public static Sector parseDegrees(AVList values, int imageWidth, int imageHeight Angle lonOffset = lonOrigin.addDegrees((Double) values.getValue(WORLD_FILE_X_PIXEL_SIZE) * imageWidth); Angle minLon, maxLon; - if (lonOrigin.degrees < lonOffset.degrees) - { + if (lonOrigin.degrees < lonOffset.degrees) { minLon = lonOrigin; maxLon = lonOffset; - } - else - { + } else { minLon = lonOffset; maxLon = lonOrigin; } Angle minLat, maxLat; - if (latOrigin.degrees < latOffset.degrees) - { + if (latOrigin.degrees < latOffset.degrees) { minLat = latOrigin; maxLat = latOffset; - } - else - { + } else { minLat = latOffset; maxLat = latOrigin; } Sector sector = new Sector(minLat, maxLat, minLon, maxLon); - if (!sector.isWithinLatLonLimits()) - { + if (!sector.isWithinLatLonLimits()) { String message = Logging.getMessage("generic.SectorNotGeographic"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -709,49 +624,43 @@ public static Sector parseDegrees(AVList values, int imageWidth, int imageHeight /** * Compute a Sector from UTM world file values. * - * @param values the six values from the world file. - * @param imageWidth the width of the image associated with the world file. + * @param values the six values from the world file. + * @param imageWidth the width of the image associated with the world file. * @param imageHeight the height of the image associated with the world file. - * @param zone the UTM zone number (1 to 60), can be zero if expected units are in decimal degrees. - * @param hemisphere the UTM hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link + * @param zone the UTM zone number (1 to 60), can be zero if expected units are in decimal degrees. + * @param hemisphere the UTM hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. * * @return the corresponding Sector or null if the sector could not be computed. * * @throws IllegalArgumentException if the values array is null or has a length less than six, , the image width and - * height are less than zero, or the hemisphere indicator is not {@link + * height are less than zero, or the hemisphere indicator is not {@link * gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link gov.nasa.worldwind.avlist.AVKey#SOUTH} - * @throws IllegalStateException if the decoded values are not within the normal range of latituded and - * longitude. + * @throws IllegalStateException if the decoded values are not within the normal range of latituded and longitude. * @see #worldFileValuesAppearGeographic(gov.nasa.worldwind.avlist.AVList) */ - @SuppressWarnings( {"UnnecessaryLocalVariable"}) - public static Sector parseUTM(double[] values, int imageWidth, int imageHeight, int zone, String hemisphere) - { + @SuppressWarnings({"UnnecessaryLocalVariable"}) + public static Sector parseUTM(double[] values, int imageWidth, int imageHeight, int zone, String hemisphere) { - if (values.length < 6) - { + if (values.length < 6) { String message = Logging.getMessage("WorldFile.TooFewWorldFileValues"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (imageWidth <= 0 || imageHeight <= 0) - { + if (imageWidth <= 0 || imageHeight <= 0) { String message = Logging.getMessage("generic.InvalidImageSize"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (zone < 1 || zone > 60) - { + if (zone < 1 || zone > 60) { String message = Logging.getMessage("generic.ZoneIsInvalid", zone); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!AVKey.NORTH.equals(hemisphere) && !AVKey.SOUTH.equals(hemisphere)) - { + if (!AVKey.NORTH.equals(hemisphere) && !AVKey.SOUTH.equals(hemisphere)) { String msg = Logging.getMessage("generic.HemisphereIsInvalid", hemisphere); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -775,8 +684,7 @@ public static Sector parseUTM(double[] values, int imageWidth, int imageHeight, Sector sector = new Sector(LR.getLatitude(), UL.getLatitude(), UL.getLongitude(), LR.getLongitude()); - if (!sector.isWithinLatLonLimits()) - { + if (!sector.isWithinLatLonLimits()) { String message = Logging.getMessage("generic.SectorNotGeographic"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -785,11 +693,17 @@ public static Sector parseUTM(double[] values, int imageWidth, int imageHeight, return sector; } - /** Pattern matching the geographic coordinate system keyword in an OGC coordinate system well-known text. */ + /** + * Pattern matching the geographic coordinate system keyword in an OGC coordinate system well-known text. + */ protected static final Pattern GEOGCS_WKT_PATTERN = Pattern.compile("\\{*GEOGCS[\\[\\(](.*)[\\]\\)]\\}*"); - /** Pattern matching the projected coordinate system keyword in an OGC coordinate system well-known text. */ + /** + * Pattern matching the projected coordinate system keyword in an OGC coordinate system well-known text. + */ protected static final Pattern PROJCS_WKT_PATTERN = Pattern.compile("\\{*PROJCS[\\[\\(](.*)[\\]\\)]\\}*"); - /** Pattern matching the UTM name in an projected coordinate system's well-known text. */ + /** + * Pattern matching the UTM name in an projected coordinate system's well-known text. + */ protected static final Pattern UTM_NAME_WKT_PATTERN = Pattern.compile(".*UTM.*ZONE.*?(\\d+).*?([\\w\\s]+).*?"); /** @@ -800,96 +714,90 @@ public static Sector parseUTM(double[] values, int imageWidth, int imageHeight, * follows:

        • Geographic - {@link gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM} set to {@link * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_GEOGRAPHIC}.
        • Projected coordinate system: Universal * Transverse Mercator (UTM) - {@link gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM} set to {@link - * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_PROJECTED} and {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_NAME} - * set to {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_UTM}. {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_HEMISPHERE} - * set to either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link gov.nasa.worldwind.avlist.AVKey#SOUTH}. + * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_PROJECTED} and + * {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_NAME} set to + * {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_UTM}. + * {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_HEMISPHERE} set to either + * {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link gov.nasa.worldwind.avlist.AVKey#SOUTH}. * {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_ZONE} set to an integer in the range 1-60
        • Projected * coordinate system: unknown projection - {@link gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM} set to {@link - * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_PROJECTED} and {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_NAME} - * set to {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_UNKNOWN}.
        • Unknown coordinate system - {@link - * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM} set to {@link gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_UNKNOWN}. + * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_PROJECTED} and + * {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_NAME} set to + * {@link gov.nasa.worldwind.avlist.AVKey#PROJECTION_UNKNOWN}.
        • Unknown coordinate system - {@link + * gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM} set to + * {@link gov.nasa.worldwind.avlist.AVKey#COORDINATE_SYSTEM_UNKNOWN}. *
        If an exception occurs while parsing the coordinate system text, the parameter list is left unchanged. * - * @param text a String containing an OGC coordinate system in well-known text format. + * @param text a String containing an OGC coordinate system in well-known text format. * @param params the coordinate system parameter list, or null to indicate a parameter list should be created. * * @return the coordinate system parameter list. * * @throws IllegalArgumentException if text is null. */ - public static AVList decodeOGCCoordinateSystemWKT(String text, AVList params) - { - if (text == null) - { + public static AVList decodeOGCCoordinateSystemWKT(String text, AVList params) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } // Convert the coordinate system text to upper case. The coordinate system regular expressions match against // upper case characters. text = text.trim().toUpperCase(); - try - { + try { Matcher csMatcher = GEOGCS_WKT_PATTERN.matcher(text); - if (csMatcher.matches()) - { + if (csMatcher.matches()) { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC); - } - else if ((csMatcher = PROJCS_WKT_PATTERN.matcher(text)).matches()) - { + } else if ((csMatcher = PROJCS_WKT_PATTERN.matcher(text)).matches()) { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_PROJECTED); String csText = csMatcher.group(1); Matcher projMatcher = UTM_NAME_WKT_PATTERN.matcher(csText); - if (projMatcher.matches()) - { + if (projMatcher.matches()) { params.setValue(AVKey.PROJECTION_NAME, AVKey.PROJECTION_UTM); // Parse the UTM zone from the coordinate system name. String s = projMatcher.group(1); - if (s != null) - { + if (s != null) { Integer i = WWUtil.makeInteger(s.trim()); - if (i != null && i >= 1 && i <= 60) + if (i != null && i >= 1 && i <= 60) { params.setValue(AVKey.PROJECTION_ZONE, i); + } } - if (params.getValue(AVKey.PROJECTION_ZONE) == null) + if (params.getValue(AVKey.PROJECTION_ZONE) == null) { Logging.logger().warning(Logging.getMessage("generic.ZoneIsInvalid", s)); + } // Parse the UTM hemisphere form the coordinate system name. s = projMatcher.group(2); - if (s != null) - { + if (s != null) { s = s.trim(); - if (s.startsWith("N") || s.startsWith("n")) + if (s.startsWith("N") || s.startsWith("n")) { params.setValue(AVKey.PROJECTION_HEMISPHERE, AVKey.NORTH); - else if (s.startsWith("S") || s.startsWith("s")) + } else if (s.startsWith("S") || s.startsWith("s")) { params.setValue(AVKey.PROJECTION_HEMISPHERE, AVKey.SOUTH); + } } - if (params.getValue(AVKey.PROJECTION_HEMISPHERE) == null) + if (params.getValue(AVKey.PROJECTION_HEMISPHERE) == null) { Logging.logger().warning(Logging.getMessage("generic.HemisphereIsInvalid", s)); - } - else - { + } + } else { params.setValue(AVKey.PROJECTION_NAME, AVKey.PROJECTION_UNKNOWN); } - } - else - { + } else { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_UNKNOWN); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, - Logging.getMessage("generic.ExceptionParsingCoordinateSystem", text), e); + Logging.getMessage("generic.ExceptionParsingCoordinateSystem", text), e); } return params; @@ -906,22 +814,18 @@ else if (s.startsWith("S") || s.startsWith("s")) * * @return TRUE if there is a world file for the source, otherwise returns FALSE */ - public static boolean hasWorldFiles(Object source) - { - try - { + public static boolean hasWorldFiles(Object source) { + try { File file = WWIO.getFileForLocalAddress(source); - if (null == file) + if (null == file) { return false; + } java.io.File[] worldFiles = WorldFile.getWorldFiles(file); - if (worldFiles == null || worldFiles.length == 0) - { + if (worldFiles == null || worldFiles.length == 0) { return false; } - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { // Not interested in logging the exception, we only want to report the failure to read. return false; } @@ -941,18 +845,15 @@ public static boolean hasWorldFiles(Object source) * * @throws IOException if the world file could not be read */ - public static void readWorldFiles(Object source, AVList params) throws java.io.IOException - { + public static void readWorldFiles(Object source, AVList params) throws java.io.IOException { File file = WWIO.getFileForLocalAddress(source); - if (null == file) - { + if (null == file) { String message = Logging.getMessage("generic.UnrecognizedSourceType", source); Logging.logger().severe(message); throw new java.io.IOException(message); } - if (null == params) - { + if (null == params) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -963,15 +864,16 @@ public static void readWorldFiles(Object source, AVList params) throws java.io.I // Translate the property WORLD_FILE_IMAGE_SIZE to separate properties WIDTH and HEIGHT. Object o = params.getValue(WorldFile.WORLD_FILE_IMAGE_SIZE); - if (o != null && o instanceof int[]) - { + if (o != null && o instanceof int[]) { int[] size = (int[]) o; - if (!params.hasKey(AVKey.WIDTH)) + if (!params.hasKey(AVKey.WIDTH)) { params.setValue(AVKey.WIDTH, size[0]); + } - if (!params.hasKey(AVKey.HEIGHT)) + if (!params.hasKey(AVKey.HEIGHT)) { params.setValue(AVKey.HEIGHT, size[1]); + } } } } diff --git a/src/gov/nasa/worldwind/formats/wvt/WaveletCodec.java b/src/gov/nasa/worldwind/formats/wvt/WaveletCodec.java index 0a80e8c76d..ad659763f0 100644 --- a/src/gov/nasa/worldwind/formats/wvt/WaveletCodec.java +++ b/src/gov/nasa/worldwind/formats/wvt/WaveletCodec.java @@ -15,25 +15,22 @@ * @author brownrigg * @version $Id: WaveletCodec.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class WaveletCodec { -public class WaveletCodec -{ private final int type; private final int resolutionX; private final int resolutionY; private byte[][] xform; - public static final int TYPE_BYTE_GRAY = 0x67726179; // ascii "gray" - public static final int TYPE_3BYTE_BGR = 0x72676220; // ascii "rgb " + public static final int TYPE_BYTE_GRAY = 0x67726179; // ascii "gray" + public static final int TYPE_3BYTE_BGR = 0x72676220; // ascii "rgb " public static final int TYPE_4BYTE_ARGB = 0x61726762; // ascii "argb" /** * A suggested filename extension for wavelet-encodings. */ public static final String WVT_EXT = ".wvt"; - private WaveletCodec(int type, int resolutionX, int resolutionY) - { - if (!isTypeValid(type)) - { + private WaveletCodec(int type, int resolutionX, int resolutionY) { + if (!isTypeValid(type)) { String message = "Invalid type: " + type; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -44,8 +41,7 @@ private WaveletCodec(int type, int resolutionX, int resolutionY) this.resolutionY = resolutionY; } - public final int getType() - { + public final int getType() { return type; } @@ -54,8 +50,7 @@ public final int getType() * * @return resolution */ - public final int getResolutionX() - { + public final int getResolutionX() { return this.resolutionX; } @@ -64,20 +59,17 @@ public final int getResolutionX() * * @return resolution */ - public final int getResolutionY() - { + public final int getResolutionY() { return this.resolutionY; } /** - * Reconstructs an image from this wavelet encoding at the given resolution. The specified resolution - * must be a power of two, and must be less than or equal to the resolution of the encoding. + * Reconstructs an image from this wavelet encoding at the given resolution. The specified resolution must be a + * power of two, and must be less than or equal to the resolution of the encoding. * * This reconstruction algorithm was hinted at in: * - * "Principles of Digital Image Synthesis" - * Andrew Glassner - * 1995, pp. 296 + * "Principles of Digital Image Synthesis" Andrew Glassner 1995, pp. 296 * * @param resolution The desired resolution. * @return reconstructed image. @@ -92,8 +84,7 @@ public BufferedImage reconstruct(int resolution) throws IllegalArgumentException // we need working buffers as large as 1/2 the output resolution... // Note how these are named after Glassner's convention... - - int res2 = (resolution/2) * (resolution/2); + int res2 = (resolution / 2) * (resolution / 2); int[][] A = new int[numBands][res2]; int[][] D = new int[numBands][res2]; int[][] V = new int[numBands][res2]; @@ -101,36 +92,39 @@ public BufferedImage reconstruct(int resolution) throws IllegalArgumentException // Prime the process. Recall that the first byte of each channel is a color value, not // signed coefficients. So treat it as an unsigned value. - for (int k=0; k < numBands; k++) + for (int k = 0; k < numBands; k++) { imageData[k][0] = 0x000000ff & this.xform[k][0]; + } int scale = 1; int offset = 1; do { // load up our A,D,V,H component arrays... - int numVals = scale*scale; - if (numVals >= resolution*resolution) break; + int numVals = scale * scale; + if (numVals >= resolution * resolution) { + break; + } int next = 0; - for (int j=0; j resolutionX || resolution > resolutionY) + if (resolution > resolutionX || resolution > resolutionY) { throw new IllegalArgumentException("WaveletCodec.loadPartially(): input resolution greater than encoded image"); + } int type = buffer.getInt(); - if (!isTypeValid(type)) + if (!isTypeValid(type)) { throw new IllegalArgumentException("WaveletCodec.loadPartially(): invalid encoding type"); + } int numBands = buffer.getInt(); - byte[][] xform = new byte[numBands][resolution*resolution]; + byte[][] xform = new byte[numBands][resolution * resolution]; for (int k = 0; k < numBands; k++) { - buffer.position(4*(Integer.SIZE/Byte.SIZE) + k * (resolutionX * resolutionY)); + buffer.position(4 * (Integer.SIZE / Byte.SIZE) + k * (resolutionX * resolutionY)); buffer.get(xform[k], 0, xform[k].length); } @@ -317,9 +298,9 @@ public static WaveletCodec loadPartial(java.nio.ByteBuffer buffer, int resolutio } /** - * Creates a wavelet encoding from the given BufferedImage. The image must have dimensions that are - * a power of 2. If the incoming image has at least 3 bands, the first three are assumed to be RGB channels. - * If only one-band, it is assumed to be grayscale. The SampleModel component-type must be BYTE. + * Creates a wavelet encoding from the given BufferedImage. The image must have dimensions that are a power of 2. If + * the incoming image has at least 3 bands, the first three are assumed to be RGB channels. If only one-band, it is + * assumed to be grayscale. The SampleModel component-type must be BYTE. * * @param image The source image. * @return The wavelet encoding. @@ -327,28 +308,31 @@ public static WaveletCodec loadPartial(java.nio.ByteBuffer buffer, int resolutio */ public static WaveletCodec encode(BufferedImage image) throws IllegalArgumentException { - if (image == null) + if (image == null) { throw new IllegalArgumentException("WaveletCodec.encode: null image"); + } // Does image have the required resolution constraints? int xRes = image.getWidth(); int yRes = image.getHeight(); - if (!WWMath.isPowerOfTwo(xRes) || !WWMath.isPowerOfTwo(yRes)) + if (!WWMath.isPowerOfTwo(xRes) || !WWMath.isPowerOfTwo(yRes)) { throw new IllegalArgumentException("Image dimensions are not a power of 2"); + } // Try to determine image type... SampleModel sampleModel = image.getSampleModel(); int numBands = sampleModel.getNumBands(); - if ( !(numBands == 1 || numBands == 3 || numBands == 4) || sampleModel.getDataType() != DataBuffer.TYPE_BYTE) + if (!(numBands == 1 || numBands == 3 || numBands == 4) || sampleModel.getDataType() != DataBuffer.TYPE_BYTE) { throw new IllegalArgumentException("Image is not of BYTE type, or not recognized as grayscale, RGB, or ARGB"); + } int type = getWaveletType(image); - if (!isTypeValid(type)) - throw new IllegalArgumentException("Image is not recognized as grayscale, RGB, or ARGB"); + if (!isTypeValid(type)) { + throw new IllegalArgumentException("Image is not recognized as grayscale, RGB, or ARGB"); + } // Looks good to go; grab the image data. We'll need to make a copy, as we need some // temp working space and we don't want to corrupt the BufferedImage's data... - int bandSize = xRes * yRes; //int next = 0; Raster rast = image.getRaster(); @@ -379,7 +363,9 @@ public static WaveletCodec encode(BufferedImage image) throws IllegalArgumentExc while (true) { ++level; - if ( !(xformXres > 0 || xformYres > 0)) break; + if (!(xformXres > 0 || xformYres > 0)) { + break; + } int halfXformXres = xformXres / 2; int halfXformYres = xformYres / 2; @@ -389,8 +375,8 @@ public static WaveletCodec encode(BufferedImage image) throws IllegalArgumentExc int offset = j * yRes; // IMPORTANT THAT THIS REFLECT SOURCE IMAGE, NOT THE CURRENT LEVEL! for (int i = 0; i < halfXformXres; i++) { - int indx1 = offset + i*2; - int indx2 = offset + i*2 + 1; + int indx1 = offset + i * 2; + int indx2 = offset + i * 2 + 1; // horizontally... for (int k = 0; k < numBands; k++) { @@ -404,21 +390,22 @@ public static WaveletCodec encode(BufferedImage image) throws IllegalArgumentExc } // copy transformed data from this iteration back into our source arrays... - for (int k=0; k < numBands; k++) + for (int k = 0; k < numBands; k++) { System.arraycopy(workspace[k], 0, imageData[k], 0, workspace[k].length); + } // now transform along columns... for (int j = 0; j < xformXres; j++) { for (int i = 0; i < halfXformYres; i++) { - int indx1 = j + (i*2)*yRes; - int indx2 = j + (i*2+1)*yRes; + int indx1 = j + (i * 2) * yRes; + int indx2 = j + (i * 2 + 1) * yRes; // horizontally... for (int k = 0; k < numBands; k++) { float average = (imageData[k][indx1] + imageData[k][indx2]) / 2f; float detail = imageData[k][indx1] - average; - workspace[k][j + i*yRes] = average; - workspace[k][j + (i+halfXformYres)*yRes] = detail; + workspace[k][j + i * yRes] = average; + workspace[k][j + (i + halfXformYres) * yRes] = detail; } } @@ -428,8 +415,9 @@ public static WaveletCodec encode(BufferedImage image) throws IllegalArgumentExc xformYres /= 2; // copy transformed data from this iteration back into our source arrays... - for (int k=0; k < numBands; k++) + for (int k = 0; k < numBands; k++) { System.arraycopy(workspace[k], 0, imageData[k], 0, workspace[k].length); + } } // Our return WaveletCodec... @@ -440,12 +428,12 @@ public static WaveletCodec encode(BufferedImage image) throws IllegalArgumentExc // Rearrange in memory for optimal, hierarchical layout on disk, quantizing down to // byte values as we go. // - // NOTE: the first byte of each channel is different; it represents the average color of the // overall image, and as such should be an unsigned quantity in the range 0..255. // All other values are signed coefficents, so the clamping boundaries are different. - for (int k=0; k 0) ? scale * xRes : 0; for (int j = 0; j < scale; j++) { for (int i = 0; i < scale; i++, next++) { - int indx = rowOffset + colOffset + j*xRes + i; + int indx = rowOffset + colOffset + j * xRes + i; for (int k = 0; k < numBands; k++) { - codec.xform[k][next] = (byte) Math.max(Byte.MIN_VALUE, Math.min(Byte.MAX_VALUE, Math.round(imageData[k][indx]))); + codec.xform[k][next] = (byte) Math.max(Byte.MIN_VALUE, Math.min(Byte.MAX_VALUE, Math.round(imageData[k][indx]))); } } } diff --git a/src/gov/nasa/worldwind/geom/Angle.java b/src/gov/nasa/worldwind/geom/Angle.java index c3bf4a5372..9154bd4c16 100644 --- a/src/gov/nasa/worldwind/geom/Angle.java +++ b/src/gov/nasa/worldwind/geom/Angle.java @@ -16,38 +16,56 @@ * @author Tom Gaskins * @version $Id: Angle.java 2419 2014-11-08 04:44:55Z tgaskins $ */ -public class Angle implements Comparable -{ +public class Angle implements Comparable { + // Angle format public final static String ANGLE_FORMAT_DD = "gov.nasa.worldwind.Geom.AngleDD"; public final static String ANGLE_FORMAT_DM = "gov.nasa.worldwind.Geom.AngleDM"; public final static String ANGLE_FORMAT_DMS = "gov.nasa.worldwind.Geom.AngleDMS"; - /** Represents an angle of zero degrees */ + /** + * Represents an angle of zero degrees + */ public final static Angle ZERO = Angle.fromDegrees(0); - /** Represents a right angle of positive 90 degrees */ + /** + * Represents a right angle of positive 90 degrees + */ public final static Angle POS90 = Angle.fromDegrees(90); - /** Represents a right angle of negative 90 degrees */ + /** + * Represents a right angle of negative 90 degrees + */ public final static Angle NEG90 = Angle.fromDegrees(-90); - /** Represents an angle of positive 180 degrees */ + /** + * Represents an angle of positive 180 degrees + */ public final static Angle POS180 = Angle.fromDegrees(180); - /** Represents an angle of negative 180 degrees */ + /** + * Represents an angle of negative 180 degrees + */ public final static Angle NEG180 = Angle.fromDegrees(-180); - /** Represents an angle of positive 360 degrees */ + /** + * Represents an angle of positive 360 degrees + */ public final static Angle POS360 = Angle.fromDegrees(360); - /** Represents an angle of negative 360 degrees */ + /** + * Represents an angle of negative 360 degrees + */ public final static Angle NEG360 = Angle.fromDegrees(-360); - /** Represents an angle of 1 minute */ + /** + * Represents an angle of 1 minute + */ public final static Angle MINUTE = Angle.fromDegrees(1d / 60d); - /** Represents an angle of 1 second */ + /** + * Represents an angle of 1 second + */ public final static Angle SECOND = Angle.fromDegrees(1d / 3600d); private final static double DEGREES_TO_RADIANS = Math.PI / 180d; @@ -60,8 +78,7 @@ public class Angle implements Comparable * * @return a new angle, whose size in degrees is given by degrees */ - public static Angle fromDegrees(double degrees) - { + public static Angle fromDegrees(double degrees) { return new Angle(degrees, DEGREES_TO_RADIANS * degrees); } @@ -72,15 +89,13 @@ public static Angle fromDegrees(double degrees) * * @return a new angle, whose size in radians is given by radians. */ - public static Angle fromRadians(double radians) - { + public static Angle fromRadians(double radians) { return new Angle(RADIANS_TO_DEGREES * radians, radians); } private static final double PIOver2 = Math.PI / 2; - public static Angle fromDegreesLatitude(double degrees) - { + public static Angle fromDegreesLatitude(double degrees) { degrees = degrees < -90 ? -90 : degrees > 90 ? 90 : degrees; double radians = DEGREES_TO_RADIANS * degrees; radians = radians < -PIOver2 ? -PIOver2 : radians > PIOver2 ? PIOver2 : radians; @@ -88,8 +103,7 @@ public static Angle fromDegreesLatitude(double degrees) return new Angle(degrees, radians); } - public static Angle fromRadiansLatitude(double radians) - { + public static Angle fromRadiansLatitude(double radians) { radians = radians < -PIOver2 ? -PIOver2 : radians > PIOver2 ? PIOver2 : radians; double degrees = RADIANS_TO_DEGREES * radians; degrees = degrees < -90 ? -90 : degrees > 90 ? 90 : degrees; @@ -97,8 +111,7 @@ public static Angle fromRadiansLatitude(double radians) return new Angle(degrees, radians); } - public static Angle fromDegreesLongitude(double degrees) - { + public static Angle fromDegreesLongitude(double degrees) { degrees = degrees < -180 ? -180 : degrees > 180 ? 180 : degrees; double radians = DEGREES_TO_RADIANS * degrees; radians = radians < -Math.PI ? -Math.PI : radians > Math.PI ? Math.PI : radians; @@ -106,8 +119,7 @@ public static Angle fromDegreesLongitude(double degrees) return new Angle(degrees, radians); } - public static Angle fromRadiansLongitude(double radians) - { + public static Angle fromRadiansLongitude(double radians) { radians = radians < -Math.PI ? -Math.PI : radians > Math.PI ? Math.PI : radians; double degrees = RADIANS_TO_DEGREES * radians; degrees = degrees < -180 ? -180 : degrees > 180 ? 180 : degrees; @@ -123,8 +135,7 @@ public static Angle fromRadiansLongitude(double radians) * * @return a new angle, whose size is determined from x and y. */ - public static Angle fromXY(double x, double y) - { + public static Angle fromXY(double x, double y) { double radians = Math.atan2(y, x); return new Angle(RADIANS_TO_DEGREES * radians, radians); } @@ -137,26 +148,22 @@ public static Angle fromXY(double x, double y) * @param seconds integer number of seconds, positive only between 0 and 60. * * @return a new angle whose size in degrees is given by degrees, minutes and - * seconds. + * seconds. * * @throws IllegalArgumentException if minutes or seconds are outside the 0-60 range or the degrees is negative. */ - public static Angle fromDMS(int degrees, int minutes, int seconds) - { - if (degrees < 0) - { + public static Angle fromDMS(int degrees, int minutes, int seconds) { + if (degrees < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", degrees); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minutes < 0 || minutes >= 60) - { + if (minutes < 0 || minutes >= 60) { String message = Logging.getMessage("generic.ArgumentOutOfRange", minutes); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (seconds < 0 || seconds >= 60) - { + if (seconds < 0 || seconds >= 60) { String message = Logging.getMessage("generic.ArgumentOutOfRange", seconds); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -175,16 +182,13 @@ public static Angle fromDMS(int degrees, int minutes, int seconds) * * @throws IllegalArgumentException if minutes or seconds are outside the 0-60 range or the degrees is negative. */ - public static Angle fromDMdS(int degrees, double minutes) - { - if (degrees < 0) - { + public static Angle fromDMdS(int degrees, double minutes) { + if (degrees < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", degrees); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minutes < 0 || minutes >= 60) - { + if (minutes < 0 || minutes >= 60) { String message = Logging.getMessage("generic.ArgumentOutOfRange", minutes); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -195,14 +199,14 @@ public static Angle fromDMdS(int degrees, double minutes) /** * Obtain an angle from a degrees, minute and seconds character string. - *

        eg:

        +     * 

        + * eg:

              * 123 34 42
              * -123* 34' 42" (where * stands for the degree symbol)
              * +45* 12' 30" (where * stands for the degree symbol)
              * 45 12 30 S
              * 45 12 30 N
        -     * 
        - * For a string containing both a sign and compass direction, the compass direction will take precedence. + *
        For a string containing both a sign and compass direction, the compass direction will take precedence. * * @param dmsString the degrees, minute and second character string. * @@ -210,21 +214,18 @@ public static Angle fromDMdS(int degrees, double minutes) * * @throws IllegalArgumentException if dmsString is null or not properly formated. */ - public static Angle fromDMS(String dmsString) - { - if (dmsString == null) - { + public static Angle fromDMS(String dmsString) { + if (dmsString == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Check for string format validity String regex = "([-|\\+]?\\d{1,3}[d|D|\u00B0|\\s](\\s*\\d{1,2}['|\u2019|\\s])?" - + "(\\s*\\d{1,2}[\"|\u201d|\\s])?\\s*([N|n|S|s|E|e|W|w])?\\s?)"; + + "(\\s*\\d{1,2}[\"|\u201d|\\s])?\\s*([N|n|S|s|E|e|W|w])?\\s?)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(dmsString + " "); - if (!matcher.matches()) - { + if (!matcher.matches()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", dmsString); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -239,21 +240,17 @@ public static Angle fromDMS(String dmsString) int sign = 1; char suffix = dmsString.toUpperCase().charAt(dmsString.length() - 1); char prefix = dmsString.charAt(0); - if (!Character.isDigit(suffix)) - { + if (!Character.isDigit(suffix)) { sign = (suffix == 'S' || suffix == 'W') ? -1 : 1; dmsString = dmsString.substring(0, dmsString.length() - 1); dmsString = dmsString.trim(); // check and trim the prefix if it is erroneously included - if (!Character.isDigit(prefix)) - { + if (!Character.isDigit(prefix)) { dmsString = dmsString.substring(1, dmsString.length()); dmsString = dmsString.trim(); } - } - else if (!Character.isDigit(prefix)) - { + } else if (!Character.isDigit(prefix)) { sign *= (prefix == '-') ? -1 : 1; dmsString = dmsString.substring(1, dmsString.length()); } @@ -270,14 +267,12 @@ else if (!Character.isDigit(prefix)) public final double degrees; public final double radians; - public Angle(Angle angle) - { + public Angle(Angle angle) { this.degrees = angle.degrees; this.radians = angle.radians; } - private Angle(double degrees, double radians) - { + private Angle(double degrees, double radians) { this.degrees = degrees; this.radians = radians; } @@ -288,8 +283,7 @@ private Angle(double degrees, double radians) * * @return the size of this angle in degrees. */ - public final double getDegrees() - { + public final double getDegrees() { return this.degrees; } @@ -300,8 +294,7 @@ public final double getDegrees() * * @return the size of this angle in radians. */ - public final double getRadians() - { + public final double getRadians() { return this.radians; } @@ -316,10 +309,8 @@ public final double getRadians() * * @throws IllegalArgumentException if angle is null. */ - public final Angle add(Angle angle) - { - if (angle == null) - { + public final Angle add(Angle angle) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -338,10 +329,8 @@ public final Angle add(Angle angle) * * @throws IllegalArgumentException if angle is null. */ - public final Angle subtract(Angle angle) - { - if (angle == null) - { + public final Angle subtract(Angle angle) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -358,8 +347,7 @@ public final Angle subtract(Angle angle) * * @return a new angle whose size equals this angle's size multiplied by multiplier. */ - public final Angle multiply(double multiplier) - { + public final Angle multiply(double multiplier) { return Angle.fromDegrees(this.degrees * multiplier); } @@ -373,16 +361,13 @@ public final Angle multiply(double multiplier) * * @throws IllegalArgumentException if angle is null. */ - public final double divide(Angle angle) - { - if (angle == null) - { + public final double divide(Angle angle) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle.getDegrees() == 0.0) - { + if (angle.getDegrees() == 0.0) { String message = Logging.getMessage("generic.DivideByZero"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -391,13 +376,11 @@ public final double divide(Angle angle) return this.degrees / angle.degrees; } - public final Angle addDegrees(double degrees) - { + public final Angle addDegrees(double degrees) { return Angle.fromDegrees(this.degrees + degrees); } - public final Angle subtractDegrees(double degrees) - { + public final Angle subtractDegrees(double degrees) { return Angle.fromDegrees(this.degrees - degrees); } @@ -409,18 +392,15 @@ public final Angle subtractDegrees(double degrees) * * @return a new angle equivalent to this angle divided by divisor. */ - public final Angle divide(double divisor) - { + public final Angle divide(double divisor) { return Angle.fromDegrees(this.degrees / divisor); } - public final Angle addRadians(double radians) - { + public final Angle addRadians(double radians) { return Angle.fromRadians(this.radians + radians); } - public final Angle subtractRadians(double radians) - { + public final Angle subtractRadians(double radians) { return Angle.fromRadians(this.radians - radians); } @@ -431,20 +411,19 @@ public final Angle subtractRadians(double radians) * * @return the angular distance between this and value. */ - public Angle angularDistanceTo(Angle angle) - { - if (angle == null) - { + public Angle angularDistanceTo(Angle angle) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } double differenceDegrees = angle.subtract(this).degrees; - if (differenceDegrees < -180) + if (differenceDegrees < -180) { differenceDegrees += 360; - else if (differenceDegrees > 180) + } else if (differenceDegrees > 180) { differenceDegrees -= 360; + } double absAngle = Math.abs(differenceDegrees); return Angle.fromDegrees(absAngle); @@ -455,23 +434,19 @@ else if (differenceDegrees > 180) * * @return the trigonometric sine of this angle. */ - public final double sin() - { + public final double sin() { return Math.sin(this.radians); } - public final double sinHalfAngle() - { + public final double sinHalfAngle() { return Math.sin(0.5 * this.radians); } - public static Angle asin(double sine) - { + public static Angle asin(double sine) { return Angle.fromRadians(Math.asin(sine)); } - public static double arctanh(double radians) - { + public static double arctanh(double radians) { return 0.5 * Math.log((1 + radians) / (1 - radians)); } @@ -480,18 +455,15 @@ public static double arctanh(double radians) * * @return the trigonometric cosine of this angle. */ - public final double cos() - { + public final double cos() { return Math.cos(this.radians); } - public final double cosHalfAngle() - { + public final double cosHalfAngle() { return Math.cos(0.5 * this.radians); } - public static Angle acos(double cosine) - { //Tom: this method is not used, should we delete it? (13th Dec 06) + public static Angle acos(double cosine) { //Tom: this method is not used, should we delete it? (13th Dec 06) return Angle.fromRadians(Math.acos(cosine)); } @@ -500,13 +472,11 @@ public static Angle acos(double cosine) * * @return the trigonometric tangent of half of this angle. */ - public final double tanHalfAngle() - { + public final double tanHalfAngle() { return Math.tan(0.5 * this.radians); } - public static Angle atan(double tan) - { //Tom: this method is not used, should we delete it? (13th Dec 06) + public static Angle atan(double tan) { //Tom: this method is not used, should we delete it? (13th Dec 06) return Angle.fromRadians(Math.atan(tan)); } @@ -518,12 +488,10 @@ public static Angle atan(double tan) * @param a2 the second angle. * * @return the average of a1 and a2 throws IllegalArgumentException if either angle is - * null. + * null. */ - public static Angle midAngle(Angle a1, Angle a2) - { - if (a1 == null || a2 == null) - { + public static Angle midAngle(Angle a1, Angle a2) { + if (a1 == null || a2 == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -542,10 +510,8 @@ public static Angle midAngle(Angle a1, Angle a2) * * @throws IllegalArgumentException if a or b is null */ - public static Angle average(Angle a, Angle b) - { - if (a == null || b == null) - { + public static Angle average(Angle a, Angle b) { + if (a == null || b == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -565,10 +531,8 @@ public static Angle average(Angle a, Angle b) * * @throws IllegalArgumentException if a, b or c is null. */ - public static Angle average(Angle a, Angle b, Angle c) - { - if (a == null || b == null || c == null) - { + public static Angle average(Angle a, Angle b, Angle c) { + if (a == null || b == null || c == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -582,20 +546,19 @@ public static Angle average(Angle a, Angle b, Angle c) *

        * The returned angle is undefined if min > max. Otherwise, this method's return value is equivalent to the * following: - *

        • min - If value < min
        • max - If value > max
        • value - If min <= value >= max
        + *
        • min - If value < min
        • max - If value > max
        • value - If min <= value >= + * max
        * * @param value The angle to clamp. - * @param min The minimum angle to clamp to. - * @param max The maximum angle to clamp to. + * @param min The minimum angle to clamp to. + * @param max The maximum angle to clamp to. * * @return The clamped angle. * * @throws IllegalArgumentException if any argument is null. */ - public static Angle clamp(Angle value, Angle min, Angle max) - { - if (value == null || min == null || max == null) - { + public static Angle clamp(Angle value, Angle min, Angle max) { + if (value == null || min == null || max == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -613,28 +576,28 @@ public static Angle clamp(Angle value, Angle min, Angle max) * * @return a new angle between value1 and value2. */ - public static Angle mix(double amount, Angle value1, Angle value2) - { - if (value1 == null || value2 == null) - { + public static Angle mix(double amount, Angle value1, Angle value2) { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (amount < 0) + if (amount < 0) { return value1; - else if (amount > 1) + } else if (amount > 1) { return value2; + } Quaternion quat = Quaternion.slerp( - amount, - Quaternion.fromAxisAngle(value1, Vec4.UNIT_X), - Quaternion.fromAxisAngle(value2, Vec4.UNIT_X)); + amount, + Quaternion.fromAxisAngle(value1, Vec4.UNIT_X), + Quaternion.fromAxisAngle(value2, Vec4.UNIT_X)); Angle angle = quat.getRotationX(); - if (Double.isNaN(angle.degrees)) + if (Double.isNaN(angle.degrees)) { return null; + } return angle; } @@ -649,46 +612,41 @@ else if (amount > 1) * * @throws IllegalArgumentException if angle is null. */ - public final int compareTo(Angle angle) - { - if (angle == null) - { + public final int compareTo(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.degrees < angle.degrees) + if (this.degrees < angle.degrees) { return -1; + } - if (this.degrees > angle.degrees) + if (this.degrees > angle.degrees) { return 1; + } return 0; } - public static double normalizedDegrees(double degrees) - { + public static double normalizedDegrees(double degrees) { double a = degrees % 360; return a > 180 ? a - 360 : a < -180 ? 360 + a : a; } - public static double normalizedDegreesLatitude(double degrees) - { + public static double normalizedDegreesLatitude(double degrees) { double lat = degrees % 180; return lat > 90 ? 180 - lat : lat < -90 ? -180 - lat : lat; } - public static double normalizedDegreesLongitude(double degrees) - { + public static double normalizedDegreesLongitude(double degrees) { double lon = degrees % 360; return lon > 180 ? lon - 360 : lon < -180 ? 360 + lon : lon; } - public static Angle normalizedAngle(Angle unnormalizedAngle) - { - if (unnormalizedAngle == null) - { + public static Angle normalizedAngle(Angle unnormalizedAngle) { + if (unnormalizedAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -697,10 +655,8 @@ public static Angle normalizedAngle(Angle unnormalizedAngle) return Angle.fromDegrees(normalizedDegrees(unnormalizedAngle.degrees)); } - public static Angle normalizedLatitude(Angle unnormalizedAngle) - { - if (unnormalizedAngle == null) - { + public static Angle normalizedLatitude(Angle unnormalizedAngle) { + if (unnormalizedAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -709,10 +665,8 @@ public static Angle normalizedLatitude(Angle unnormalizedAngle) return Angle.fromDegrees(normalizedDegreesLatitude(unnormalizedAngle.degrees)); } - public static Angle normalizedLongitude(Angle unnormalizedAngle) - { - if (unnormalizedAngle == null) - { + public static Angle normalizedLongitude(Angle unnormalizedAngle) { + if (unnormalizedAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -721,25 +675,20 @@ public static Angle normalizedLongitude(Angle unnormalizedAngle) return Angle.fromDegrees(normalizedDegreesLongitude(unnormalizedAngle.degrees)); } - public Angle normalize() - { + public Angle normalize() { return normalizedAngle(this); } - public Angle normalizedLatitude() - { + public Angle normalizedLatitude() { return normalizedLatitude(this); } - public Angle normalizedLongitude() - { + public Angle normalizedLongitude() { return normalizedLongitude(this); } - public static boolean crossesLongitudeBoundary(Angle angleA, Angle angleB) - { - if (angleA == null || angleB == null) - { + public static boolean crossesLongitudeBoundary(Angle angleA, Angle angleB) { + if (angleA == null || angleB == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -748,26 +697,22 @@ public static boolean crossesLongitudeBoundary(Angle angleA, Angle angleB) // A segment cross the line if end pos have different longitude signs // and are more than 180 degrees longitude apart return (Math.signum(angleA.degrees) != Math.signum(angleB.degrees)) - && (Math.abs(angleA.degrees - angleB.degrees) > 180); + && (Math.abs(angleA.degrees - angleB.degrees) > 180); } - public static boolean isValidLatitude(double value) - { + public static boolean isValidLatitude(double value) { return value >= -90 && value <= 90; } - public static boolean isValidLongitude(double value) - { + public static boolean isValidLongitude(double value) { return value >= -180 && value <= 180; } - public static Angle max(Angle a, Angle b) - { + public static Angle max(Angle a, Angle b) { return a.degrees >= b.degrees ? a : b; } - public static Angle min(Angle a, Angle b) - { + public static Angle min(Angle a, Angle b) { return a.degrees <= b.degrees ? a : b; } @@ -777,8 +722,7 @@ public static Angle min(Angle a, Angle b) * @return the value of this angle in degrees and as a String. */ @Override - public final String toString() - { + public final String toString() { return Double.toString(this.degrees) + '\u00B0'; } @@ -788,13 +732,11 @@ public final String toString() * @param digits the number of digits past the decimal point to include in the string. * * @return the value of this angle in decimal degrees as a string with the specified number of digits beyond the - * decimal point. The string is padded with trailing zeros to fill the number of post-decimal point - * positions requested. + * decimal point. The string is padded with trailing zeros to fill the number of post-decimal point positions + * requested. */ - public final String toDecimalDegreesString(int digits) - { - if ((digits < 0) || (digits > 15)) - { + public final String toDecimalDegreesString(int digits) { + if ((digits < 0) || (digits > 15)) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", digits); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -809,8 +751,7 @@ public final String toDecimalDegreesString(int digits) * * @return the value of this angle in degrees, minutes, seconds as a string. */ - public final String toDMSString() - { + public final String toDMSString() { double temp = this.degrees; int sign = (int) Math.signum(temp); temp *= sign; @@ -820,13 +761,11 @@ public final String toDMSString() temp = (temp - m) * 60d; int s = (int) Math.round(temp); - if (s == 60) - { + if (s == 60) { m++; s = 0; } // Fix rounding errors - if (m == 60) - { + if (m == 60) { d++; m = 0; } @@ -839,8 +778,7 @@ public final String toDMSString() * * @return the value of this angle in degrees and decimal minutes as a string. */ - public final String toDMString() - { + public final String toDMString() { double temp = this.degrees; int sign = (int) Math.signum(temp); temp *= sign; @@ -850,13 +788,11 @@ public final String toDMString() temp = (temp - m) * 60d; int s = (int) Math.round(temp); - if (s == 60) - { + if (s == 60) { m++; s = 0; } // Fix rounding errors - if (m == 60) - { + if (m == 60) { d++; m = 0; } @@ -866,8 +802,7 @@ public final String toDMString() return (sign == -1 ? "-" : "") + d + '\u00B0' + ' ' + String.format("%5.2f", mf) + '\u2019'; } - public final String toFormattedDMSString() - { + public final String toFormattedDMSString() { double temp = this.degrees; int sign = (int) Math.signum(temp); @@ -878,13 +813,11 @@ public final String toFormattedDMSString() temp = (temp - m) * 60d; double s = Math.rint(temp * 100) / 100; // keep two decimals for seconds - if (s == 60) - { + if (s == 60) { m++; s = 0; } // Fix rounding errors - if (m == 60) - { + if (m == 60) { d++; m = 0; } @@ -892,8 +825,7 @@ public final String toFormattedDMSString() return String.format("%4d\u00B0 %2d\u2019 %5.2f\u201d", sign * d, m, s); } - public final double[] toDMS() - { + public final double[] toDMS() { double temp = this.degrees; int sign = (int) Math.signum(temp); @@ -904,18 +836,16 @@ public final double[] toDMS() temp = (temp - m) * 60d; double s = Math.rint(temp * 100) / 100; // keep two decimals for seconds - if (s == 60) - { + if (s == 60) { m++; s = 0; } // Fix rounding errors - if (m == 60) - { + if (m == 60) { d++; m = 0; } - return new double[] {sign * d, m, s}; + return new double[]{sign * d, m, s}; } /** @@ -923,29 +853,29 @@ public final double[] toDMS() * * @return the memory footprint of this angle in bytes. */ - public long getSizeInBytes() - { + public long getSizeInBytes() { return Double.SIZE / 8; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } Angle angle = (Angle) o; //noinspection RedundantIfStatement - if (angle.degrees != this.degrees) + if (angle.degrees != this.degrees) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { long temp = degrees != +0.0d ? Double.doubleToLongBits(degrees) : 0L; return (int) (temp ^ (temp >>> 32)); } diff --git a/src/gov/nasa/worldwind/geom/BarycentricPlanarShape.java b/src/gov/nasa/worldwind/geom/BarycentricPlanarShape.java index 4e444be211..75891725bd 100644 --- a/src/gov/nasa/worldwind/geom/BarycentricPlanarShape.java +++ b/src/gov/nasa/worldwind/geom/BarycentricPlanarShape.java @@ -3,15 +3,14 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.geom; /** * @author tag * @version $Id: BarycentricPlanarShape.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface BarycentricPlanarShape -{ +public interface BarycentricPlanarShape { + double[] getBarycentricCoords(Vec4 p); Vec4 getPoint(double[] w); diff --git a/src/gov/nasa/worldwind/geom/BarycentricQuadrilateral.java b/src/gov/nasa/worldwind/geom/BarycentricQuadrilateral.java index 3a2f592785..9e36ebe681 100644 --- a/src/gov/nasa/worldwind/geom/BarycentricQuadrilateral.java +++ b/src/gov/nasa/worldwind/geom/BarycentricQuadrilateral.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.geom; import java.util.*; @@ -16,49 +15,43 @@ * @author tag * @version $Id: BarycentricQuadrilateral.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BarycentricQuadrilateral extends BarycentricTriangle -{ +public class BarycentricQuadrilateral extends BarycentricTriangle { + protected Vec4 p11; private double[] w11; - public BarycentricQuadrilateral(Vec4 p00, Vec4 p10, Vec4 p11, Vec4 p01) - { + public BarycentricQuadrilateral(Vec4 p00, Vec4 p10, Vec4 p11, Vec4 p01) { super(p00, p10, p01); this.p11 = p11; this.w11 = this.getBarycentricCoords(this.p11); } - public BarycentricQuadrilateral(LatLon p00, LatLon p10, LatLon p11, LatLon p01) - { + public BarycentricQuadrilateral(LatLon p00, LatLon p10, LatLon p11, LatLon p01) { super(p00, p10, p01); this.p11 = new Vec4(p11.getLongitude().getRadians(), p11.getLatitude().getRadians(), 0); this.w11 = this.getBarycentricCoords(this.p11); } - public BarycentricQuadrilateral(Point p00, Point p10, Point p11, Point p01) - { + public BarycentricQuadrilateral(Point p00, Point p10, Point p11, Point p01) { super(p00, p10, p01); this.p11 = new Vec4(p11.x, p11.y, 0); this.w11 = this.getBarycentricCoords(this.p11); } - public Vec4 getP11() - { + public Vec4 getP11() { return p11; } @Override - public boolean contains(Vec4 p) - { + public boolean contains(Vec4 p) { return this.invertBilinear(p) != null; } @SuppressWarnings({"UnnecessaryLocalVariable"}) - public double[] getBilinearCoords(double alpha, double beta) - { + public double[] getBilinearCoords(double alpha, double beta) { // TODO: this method isn't always finding the correct -- or any -- roots double eps = 1e-9; double u, v; @@ -70,52 +63,49 @@ public double[] getBilinearCoords(double alpha, double beta) { u = alpha; if (Math.abs(beta11 - 1) < eps) // if beta == 1 + { v = beta; - else + } else { v = beta / (u * (beta11 - 1) + 1); - } - else if (Math.abs(beta11 - 1) < eps) // if beta = 1 + } + } else if (Math.abs(beta11 - 1) < eps) // if beta = 1 { v = beta; u = alpha / (v * (alpha11 - 1) + 1); - } - else - { + } else { double a = 1d - beta11; double b = alpha * (beta11 - 1) - beta * (alpha11 - 1) - 1; double c = alpha; double b24ac = b * b - 4 * a * c; - if (a == 0 || b24ac < 0) - return new double[] {-1, -1}; // TODO: Warn. - + if (a == 0 || b24ac < 0) { + return new double[]{-1, -1}; // TODO: Warn. + } double q = -0.5 * (b + (b != 0 ? Math.signum(b) : 1) * Math.sqrt(b24ac)); u = q / a; double ualt = c / q; u = Math.abs(u) <= Math.abs(ualt) ? u : ualt; - if (u < 0 || u > 1) + if (u < 0 || u > 1) { u = c / q; + } v = u * (beta11 - 1) + 1; v = Math.abs(v) >= eps ? beta / v : -1; } - return new double[] {u, v}; + return new double[]{u, v}; } - public double[] getBilinearCoords(Vec4 point) - { + public double[] getBilinearCoords(Vec4 point) { double[] w = this.getBarycentricCoords(point); return this.getBilinearCoords(w[1], w[2]); } - public double[] invertBilinear(Vec4 U) - { + public double[] invertBilinear(Vec4 U) { return invertBilinear(U, this.p00, this.p10, this.p11, this.p01); } - public static double[] invertBilinear(Vec4 U, Vec4 X, Vec4 Y, Vec4 Z, Vec4 W) - { + public static double[] invertBilinear(Vec4 U, Vec4 X, Vec4 Y, Vec4 Z, Vec4 W) { Vec4 s1 = W.subtract3(X); Vec4 s2 = Z.subtract3(Y); Vec4 UminX = U.subtract3(X); @@ -127,8 +117,9 @@ public static double[] invertBilinear(Vec4 U, Vec4 X, Vec4 Y, Vec4 Z, Vec4 W) double C = UminX.cross3(UminY).dot3(normal); double descriminant = B * B - 4d * A * C; - if (descriminant < 0) + if (descriminant < 0) { return null; + } descriminant = Math.sqrt(descriminant); double beta = B > 0 ? (-B - descriminant) / (2d * A) : 2d * C / (-B + descriminant); @@ -138,7 +129,7 @@ public static double[] invertBilinear(Vec4 U, Vec4 X, Vec4 Y, Vec4 Z, Vec4 W) double alpha = U.subtract3(Sbeta1).dot3(Sbeta2.subtract3(Sbeta1)) / Sbeta2.subtract3(Sbeta1).dotSelf3(); - return new double[] {alpha, beta}; + return new double[]{alpha, beta}; } // // private static ArrayList makePoints(double x0, double y0, double x1, double y1) @@ -165,42 +156,39 @@ public static double[] invertBilinear(Vec4 U, Vec4 X, Vec4 Y, Vec4 Z, Vec4 W) // private static Vec4 g2 = new Vec4(-108, 54, 0); // private static Vec4 g3 = new Vec4(-144, 54, 0); private static Vec4 g0 = new Vec4(-180, -90, 0); - private static Vec4 g1 = new Vec4( 180, -90, 0); - private static Vec4 g2 = new Vec4( 180, 90, 0); - private static Vec4 g3 = new Vec4(-180, 90, 0); + private static Vec4 g1 = new Vec4(180, -90, 0); + private static Vec4 g2 = new Vec4(180, 90, 0); + private static Vec4 g3 = new Vec4(-180, 90, 0); // private static Vec4 i0 = new Vec4(-122.1594, 34.3680, 0); // private static Vec4 i1 = new Vec4(-117.9151, 34.3674, 0); // private static Vec4 i2 = new Vec4(-117.6527, 41.4891, 0); // private static Vec4 i3 = new Vec4(-122.4126, 41.4899, 0); - private static Vec4 i0 = new Vec4(0d, 0d, 0d); private static Vec4 i1 = new Vec4(1d, 0d, 0d); private static Vec4 i2 = new Vec4(2d, 2d, 0d); private static Vec4 i3 = new Vec4(0d, 1d, 0d); private static ArrayList testPoints = new ArrayList(Arrays.asList( - g0, g1, g2, g3, - i0, i1, i2, i3, - new Vec4(-17, 0, 0) -// new Vec4(-122.4, 34.2, 0), -// new Vec4(-120.6, 34.2, 0), -// new Vec4(-120.6, 36, 0), -// new Vec4(-122.4, 36, 0) + g0, g1, g2, g3, + i0, i1, i2, i3, + new Vec4(-17, 0, 0) + // new Vec4(-122.4, 34.2, 0), + // new Vec4(-120.6, 34.2, 0), + // new Vec4(-120.6, 36, 0), + // new Vec4(-122.4, 36, 0) )); - public static void main(String[] args) - { + public static void main(String[] args) { BarycentricPlanarShape bc = new BarycentricQuadrilateral(i0, i1, i2, i3); - for (Vec4 point : testPoints) - { + for (Vec4 point : testPoints) { double[] w = bc.getBarycentricCoords(point); Vec4 p = bc.getPoint(w); double[] uv = bc.getBilinearCoords(w[1], w[2]); System.out.printf("%s, %s: ( %f, %f, %f) : ( %f, %f), %s\n", - point, p, w[0], w[1], w[2], uv[0], uv[1], p.equals(point) ? "true" : "false"); + point, p, w[0], w[1], w[2], uv[0], uv[1], p.equals(point) ? "true" : "false"); } // // BarycentricPlanarShape bc = new BarycentricQuadrilateral(new Vec4(4, 3, 0), new Vec4(7, 1, 0), diff --git a/src/gov/nasa/worldwind/geom/BarycentricTriangle.java b/src/gov/nasa/worldwind/geom/BarycentricTriangle.java index 592ce35b07..ad214c2e43 100644 --- a/src/gov/nasa/worldwind/geom/BarycentricTriangle.java +++ b/src/gov/nasa/worldwind/geom/BarycentricTriangle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.geom; import java.awt.*; @@ -12,8 +11,8 @@ * @author tag * @version $Id: BarycentricTriangle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BarycentricTriangle implements BarycentricPlanarShape -{ +public class BarycentricTriangle implements BarycentricPlanarShape { + // TODO: arg checking // TODO: account for degenerate quads protected Vec4 p00; @@ -23,8 +22,7 @@ public class BarycentricTriangle implements BarycentricPlanarShape protected Vec4 q1; protected Vec4 q3; - public BarycentricTriangle(Vec4 p00, Vec4 p10, Vec4 p01) - { + public BarycentricTriangle(Vec4 p00, Vec4 p10, Vec4 p01) { this.p00 = p00; this.p10 = p10; this.p01 = p01; @@ -33,8 +31,7 @@ public BarycentricTriangle(Vec4 p00, Vec4 p10, Vec4 p01) q3 = p01.subtract3(p00); } - public BarycentricTriangle(LatLon p00, LatLon p10, LatLon p01) - { + public BarycentricTriangle(LatLon p00, LatLon p10, LatLon p01) { this.p00 = new Vec4(p00.getLongitude().getRadians(), p00.getLatitude().getRadians(), 0); this.p10 = new Vec4(p01.getLongitude().getRadians(), p01.getLatitude().getRadians(), 0); this.p01 = new Vec4(p10.getLongitude().getRadians(), p10.getLatitude().getRadians(), 0); @@ -43,8 +40,7 @@ public BarycentricTriangle(LatLon p00, LatLon p10, LatLon p01) q3 = this.p01.subtract3(this.p00); } - public BarycentricTriangle(Point p00, Point p10, Point p01) - { + public BarycentricTriangle(Point p00, Point p10, Point p01) { this.p00 = new Vec4(p00.x, p00.y, 0); this.p10 = new Vec4(p10.x, p10.y, 0); this.p01 = new Vec4(p01.x, p01.y, 0); @@ -53,23 +49,19 @@ public BarycentricTriangle(Point p00, Point p10, Point p01) q3 = this.p01.subtract3(this.p00); } - public Vec4 getP00() - { + public Vec4 getP00() { return p00; } - public Vec4 getP10() - { + public Vec4 getP10() { return p10; } - public Vec4 getP01() - { + public Vec4 getP01() { return p01; } - public double[] getBarycentricCoords(Vec4 p) - { + public double[] getBarycentricCoords(Vec4 p) { Vec4 n = this.q1.cross3(this.q3); Vec4 na = n.getAbs3(); Vec4 q2 = p.subtract3(this.p00); @@ -77,37 +69,29 @@ public double[] getBarycentricCoords(Vec4 p) double a, b; // Choose equations providing best numerical accuracy - if (na.x >= na.y && na.x >= na.z) - { + if (na.x >= na.y && na.x >= na.z) { a = (q2.y * q3.z - q2.z * q3.y) / n.x; b = (q1.y * q2.z - q1.z * q2.y) / n.y; - } - else if (na.y >= na.x && na.y >= na.z) - { + } else if (na.y >= na.x && na.y >= na.z) { a = (q2.z * q3.x - q2.x * q3.z) / n.y; b = (q1.z * q2.x - q1.x * q2.z) / n.y; - } - else - { + } else { a = (q2.x * q3.y - q2.y * q3.x) / n.z; b = (q1.x * q2.y - q1.y * q2.x) / n.z; } - return new double[] {1 - a - b, a, b}; + return new double[]{1 - a - b, a, b}; } - public double[] getBarycentricCoords(LatLon location) - { + public double[] getBarycentricCoords(LatLon location) { return this.getBarycentricCoords(new Vec4(location.getLongitude().radians, location.getLatitude().radians, 0)); } - public boolean contains(Vec4 p) - { + public boolean contains(Vec4 p) { return this.getBarycentricCoords(p)[0] >= 0; } - public Vec4 getPoint(double[] w) - { + public Vec4 getPoint(double[] w) { Vec4 pa = this.p00.multiply3(w[0]); Vec4 pb = this.p10.multiply3(w[1]); Vec4 pc = this.p01.multiply3(w[2]); @@ -115,15 +99,13 @@ public Vec4 getPoint(double[] w) return pa.add3(pb).add3(pc); } - public LatLon getLocation(double[] w) - { + public LatLon getLocation(double[] w) { Vec4 p = this.getPoint(w); return LatLon.fromRadians(p.y, p.x); } - public double[] getBilinearCoords(double alpha, double beta) - { - return new double[] {alpha, beta}; + public double[] getBilinearCoords(double alpha, double beta) { + return new double[]{alpha, beta}; } } diff --git a/src/gov/nasa/worldwind/geom/BilinearInterpolator.java b/src/gov/nasa/worldwind/geom/BilinearInterpolator.java index 32be614984..6b3a869c21 100644 --- a/src/gov/nasa/worldwind/geom/BilinearInterpolator.java +++ b/src/gov/nasa/worldwind/geom/BilinearInterpolator.java @@ -11,17 +11,15 @@ * @author dcollins * @version $Id: BilinearInterpolator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BilinearInterpolator -{ +public class BilinearInterpolator { + private Vec4 ll; private Vec4 lr; private Vec4 ur; private Vec4 ul; - public BilinearInterpolator(Vec4 ll, Vec4 lr, Vec4 ur, Vec4 ul) - { - if (ll == null || lr == null || ur == null || ul == null) - { + public BilinearInterpolator(Vec4 ll, Vec4 lr, Vec4 ur, Vec4 ul) { + if (ll == null || lr == null || ur == null || ul == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -33,29 +31,25 @@ public BilinearInterpolator(Vec4 ll, Vec4 lr, Vec4 ur, Vec4 ul) this.ul = ul; } - public Vec4[] getCorners() - { - return new Vec4[] {this.ll, this.lr, this.ur, this.ul}; + public Vec4[] getCorners() { + return new Vec4[]{this.ll, this.lr, this.ur, this.ul}; } - public void interpolate(double u, double v, double[] compArray) - { - if (compArray == null) - { + public void interpolate(double u, double v, double[] compArray) { + if (compArray == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (compArray.length < 1) - { + if (compArray.length < 1) { String message = Logging.getMessage("generic.ArrayInvalidLength", compArray.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } double pll = (1.0 - u) * (1.0 - v); - double plr = u * (1.0 - v); - double pur = u * v; + double plr = u * (1.0 - v); + double pur = u * v; double pul = (1.0 - u) * v; compArray[0] = (pll * ll.x) + (plr * lr.x) + (pur * ur.x) + (pul * ul.x); @@ -64,11 +58,10 @@ public void interpolate(double u, double v, double[] compArray) compArray[3] = (pll * ll.w) + (plr * lr.w) + (pur * ur.w) + (pul * ul.w); } - public Vec4 interpolateAsPoint(double u, double v) - { + public Vec4 interpolateAsPoint(double u, double v) { double[] compArray = new double[4]; this.interpolate(u, v, compArray); - + return Vec4.fromArray4(compArray, 0); } } diff --git a/src/gov/nasa/worldwind/geom/Box.java b/src/gov/nasa/worldwind/geom/Box.java index 3ec68e511e..d0e0481ee6 100644 --- a/src/gov/nasa/worldwind/geom/Box.java +++ b/src/gov/nasa/worldwind/geom/Box.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.geom; import gov.nasa.worldwind.View; @@ -48,56 +47,55 @@ * @author tag * @version $Id: Box.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Box implements Extent, Renderable -{ +public class Box implements Extent, Renderable { + /** */ - protected static final int[][] ProjectionHullTable = new int[][] - { - null, // 000000: inside - {7, 6, 5, 4}, // 000001: top - {0, 1, 2, 3}, // 000010: bottom - null, // 000011: - - {3, 2, 6, 7}, // 000100: front - {3, 2, 6, 5, 4, 7}, // 000101: front, top - {0, 1, 2, 6, 7, 3}, // 000110: front, bottom - null, // 000111: - - {1, 0, 4, 5}, // 001000: back - {1, 0, 4, 7, 6, 5}, // 001001: back, top - {2, 3, 0, 4, 5, 1}, // 001010: back, bottom - null, // 001011: - - null, // 001100: - - null, // 001101: - - null, // 001110: - - null, // 001111: - - {2, 1, 5, 6}, // 010000: right - {2, 1, 5, 4, 7, 6}, // 010001: right, top - {3, 0, 1, 5, 6, 2}, // 010010: right, bottom - null, // 010011: - - {3, 2, 1, 5, 6, 7}, // 010100: right, front - {3, 2, 1, 5, 4, 7}, // 010101: right, front, top - {3, 0, 1, 5, 6, 7}, // 010110: right, front, bottom - null, // 010111: - - {2, 1, 0, 4, 5, 6}, // 011000: right, back - {2, 1, 0, 4, 7, 6}, // 011001: right, back, top - {2, 3, 0, 4, 5, 6}, // 011010: right, back, bottom - null, // 011011: - - null, // 011100: - - null, // 011101: - - null, // 011110: - - null, // 011111: - - {0, 3, 7, 4}, // 100000: left - {0, 3, 7, 6, 5, 4}, // 100001: left, top - {1, 2, 3, 7, 4, 0}, // 100010: left, bottom - null, // 100011: - - {0, 3, 2, 6, 7, 4}, // 100100: left, front - {0, 3, 2, 6, 5, 4}, // 100101: left, front, top - {0, 1, 2, 6, 7, 4}, // 100110: left, front, bottom - null, // 100111: - - {1, 0, 3, 7, 4, 5}, // 101000: left, back - {1, 0, 3, 7, 6, 5}, // 101001: left, back, top - {1, 2, 3, 7, 4, 5}, // 101010: left, back, bottom - }; + protected static final int[][] ProjectionHullTable = new int[][]{ + null, // 000000: inside + {7, 6, 5, 4}, // 000001: top + {0, 1, 2, 3}, // 000010: bottom + null, // 000011: - + {3, 2, 6, 7}, // 000100: front + {3, 2, 6, 5, 4, 7}, // 000101: front, top + {0, 1, 2, 6, 7, 3}, // 000110: front, bottom + null, // 000111: - + {1, 0, 4, 5}, // 001000: back + {1, 0, 4, 7, 6, 5}, // 001001: back, top + {2, 3, 0, 4, 5, 1}, // 001010: back, bottom + null, // 001011: - + null, // 001100: - + null, // 001101: - + null, // 001110: - + null, // 001111: - + {2, 1, 5, 6}, // 010000: right + {2, 1, 5, 4, 7, 6}, // 010001: right, top + {3, 0, 1, 5, 6, 2}, // 010010: right, bottom + null, // 010011: - + {3, 2, 1, 5, 6, 7}, // 010100: right, front + {3, 2, 1, 5, 4, 7}, // 010101: right, front, top + {3, 0, 1, 5, 6, 7}, // 010110: right, front, bottom + null, // 010111: - + {2, 1, 0, 4, 5, 6}, // 011000: right, back + {2, 1, 0, 4, 7, 6}, // 011001: right, back, top + {2, 3, 0, 4, 5, 6}, // 011010: right, back, bottom + null, // 011011: - + null, // 011100: - + null, // 011101: - + null, // 011110: - + null, // 011111: - + {0, 3, 7, 4}, // 100000: left + {0, 3, 7, 6, 5, 4}, // 100001: left, top + {1, 2, 3, 7, 4, 0}, // 100010: left, bottom + null, // 100011: - + {0, 3, 2, 6, 7, 4}, // 100100: left, front + {0, 3, 2, 6, 5, 4}, // 100101: left, front, top + {0, 1, 2, 6, 7, 4}, // 100110: left, front, bottom + null, // 100111: - + {1, 0, 3, 7, 4, 5}, // 101000: left, back + {1, 0, 3, 7, 6, 5}, // 101001: left, back, top + {1, 2, 3, 7, 4, 5}, // 101010: left, back, bottom + }; public Vec4 bottomCenter; // point at center of box's longest axis public Vec4 topCenter; // point at center of box's longest axis @@ -114,8 +112,7 @@ public class Box implements Extent, Renderable protected final Plane[] planes; // the six planes, with positive normals facing outwards protected Box(Vec4 bottomCenter, Vec4 topCenter, Vec4 center, Vec4 r, Vec4 s, Vec4 t, Vec4 ru, Vec4 su, Vec4 tu, - double rlength, double sLength, double tLength, Plane[] planes) - { + double rlength, double sLength, double tLength, Plane[] planes) { this.bottomCenter = bottomCenter; this.topCenter = topCenter; this.center = center; @@ -152,10 +149,8 @@ protected Box(Vec4 bottomCenter, Vec4 topCenter, Vec4 center, Vec4 r, Vec4 s, Ve * * @throws IllegalArgumentException if the axes array or one of its entries is null. */ - public Box(Vec4 axes[], double rMin, double rMax, double sMin, double sMax, double tMin, double tMax) - { - if (axes == null || axes[0] == null || axes[1] == null || axes[2] == null) - { + public Box(Vec4 axes[], double rMin, double rMax, double sMin, double sMax, double tMin, double tMax) { + if (axes == null || axes[0] == null || axes[1] == null || axes[2] == null) { String msg = Logging.getMessage("nullValue.AxesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -199,10 +194,8 @@ public Box(Vec4 axes[], double rMin, double rMax, double sMin, double sMax, doub * * @throws IllegalArgumentException if the point is null. */ - public Box(Vec4 point) - { - if (point == null) - { + public Box(Vec4 point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -242,8 +235,7 @@ public Box(Vec4 point) * * @return the box's center point. */ - public Vec4 getCenter() - { + public Vec4 getCenter() { return this.center; } @@ -252,8 +244,7 @@ public Vec4 getCenter() * * @return the bottom-center point. */ - public Vec4 getBottomCenter() - { + public Vec4 getBottomCenter() { return this.bottomCenter; } @@ -262,8 +253,7 @@ public Vec4 getBottomCenter() * * @return the top-center point. */ - public Vec4 getTopCenter() - { + public Vec4 getTopCenter() { return this.topCenter; } @@ -272,8 +262,7 @@ public Vec4 getTopCenter() * * @return the R axis. */ - public Vec4 getRAxis() - { + public Vec4 getRAxis() { return this.r; } @@ -282,8 +271,7 @@ public Vec4 getRAxis() * * @return the S axis. */ - public Vec4 getSAxis() - { + public Vec4 getSAxis() { return this.s; } @@ -292,8 +280,7 @@ public Vec4 getSAxis() * * @return the T axis. */ - public Vec4 getTAxis() - { + public Vec4 getTAxis() { return this.t; } @@ -302,8 +289,7 @@ public Vec4 getTAxis() * * @return the unit R axis. */ - public Vec4 getUnitRAxis() - { + public Vec4 getUnitRAxis() { return this.ru; } @@ -312,8 +298,7 @@ public Vec4 getUnitRAxis() * * @return the unit S axis. */ - public Vec4 getUnitSAxis() - { + public Vec4 getUnitSAxis() { return this.su; } @@ -322,8 +307,7 @@ public Vec4 getUnitSAxis() * * @return the unit T axis. */ - public Vec4 getUnitTAxis() - { + public Vec4 getUnitTAxis() { return this.tu; } @@ -331,10 +315,9 @@ public Vec4 getUnitTAxis() * Returns the eight corners of the box. * * @return the eight box corners in the order bottom-lower-left, bottom-lower-right, bottom-upper-right, - * bottom-upper-left, top-lower-left, top-lower-right, top-upper-right, top-upper-left. + * bottom-upper-left, top-lower-left, top-lower-right, top-upper-right, top-upper-left. */ - public Vec4[] getCorners() - { + public Vec4[] getCorners() { Vec4 ll = this.s.add3(this.t).multiply3(-0.5); // Lower left. Vec4 lr = this.t.subtract3(this.s).multiply3(0.5); // Lower right. Vec4 ur = this.s.add3(this.t).multiply3(0.5); // Upper right. @@ -358,8 +341,7 @@ public Vec4[] getCorners() * * @return the six box planes in the order R-min, R-max, S-min, S-max, T-min, T-max. */ - public Plane[] getPlanes() - { + public Plane[] getPlanes() { return this.planes; } @@ -368,8 +350,7 @@ public Plane[] getPlanes() * * @return the length of the R axis. */ - public double getRLength() - { + public double getRLength() { return rLength; } @@ -378,8 +359,7 @@ public double getRLength() * * @return the length of the S axis. */ - public double getSLength() - { + public double getSLength() { return sLength; } @@ -388,8 +368,7 @@ public double getSLength() * * @return the length of the T axis. */ - public double getTLength() - { + public double getTLength() { return tLength; } @@ -399,8 +378,7 @@ public double getTLength() * * @return the effective diameter of the box. */ - public double getDiameter() - { + public double getDiameter() { return Math.sqrt(this.rLength * this.rLength + this.sLength * this.sLength + this.tLength * this.tLength); } @@ -410,27 +388,24 @@ public double getDiameter() * * @return the effective radius of the box. */ - public double getRadius() - { + public double getRadius() { return 0.5 * this.getDiameter(); } - public Box translate(Vec4 point) - { + public Box translate(Vec4 point) { Vec4 bc = this.bottomCenter.add3(point); Vec4 tc = this.topCenter.add3(point); Vec4 c = this.center.add3(point); Plane[] newPlanes = new Plane[this.planes.length]; - for (int i = 0; i < this.planes.length; i++) - { + for (int i = 0; i < this.planes.length; i++) { Plane pl = this.planes[i]; Vec4 n = pl.getNormal(); newPlanes[i] = new Plane(n.x, n.y, n.z, pl.getDistance() - (n.dot3(point))); } return new Box(bc, tc, c, this.r, this.s, this.t, this.ru, this.su, this.tu, this.rLength, this.sLength, - this.tLength, newPlanes); + this.tLength, newPlanes); } /** @@ -440,22 +415,19 @@ public Box translate(Vec4 point) * @param points the points for which to compute a bounding volume. * * @return the bounding volume, with axes lengths consistent with the conventions described in the Box - * class overview. + * class overview. * * @throws IllegalArgumentException if the point list is null or empty. */ - public static Box computeBoundingBox(Iterable points) - { - if (points == null) - { + public static Box computeBoundingBox(Iterable points) { + if (points == null) { String msg = Logging.getMessage("nullValue.PointListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Vec4[] axes = WWMath.computePrincipalAxes(points); - if (axes == null) - { + if (axes == null) { String msg = Logging.getMessage("generic.ListIsEmpty"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -473,36 +445,45 @@ public static Box computeBoundingBox(Iterable points) double minDotT = Double.MAX_VALUE; double maxDotT = -minDotT; - for (Vec4 p : points) - { - if (p == null) + for (Vec4 p : points) { + if (p == null) { continue; + } double pdr = p.dot3(r); - if (pdr < minDotR) + if (pdr < minDotR) { minDotR = pdr; - if (pdr > maxDotR) + } + if (pdr > maxDotR) { maxDotR = pdr; + } double pds = p.dot3(s); - if (pds < minDotS) + if (pds < minDotS) { minDotS = pds; - if (pds > maxDotS) + } + if (pds > maxDotS) { maxDotS = pds; + } double pdt = p.dot3(t); - if (pdt < minDotT) + if (pdt < minDotT) { minDotT = pdt; - if (pdt > maxDotT) + } + if (pdt > maxDotT) { maxDotT = pdt; + } } - if (maxDotR == minDotR) + if (maxDotR == minDotR) { maxDotR = minDotR + 1; - if (maxDotS == minDotS) + } + if (maxDotS == minDotS) { maxDotS = minDotS + 1; - if (maxDotT == minDotT) + } + if (maxDotT == minDotT) { maxDotT = minDotT + 1; + } return new Box(axes, minDotR, maxDotR, minDotS, maxDotS, minDotT, maxDotT); } @@ -519,33 +500,29 @@ public static Box computeBoundingBox(Iterable points) * remaining elements that follow the last complete tuple. * * @param coordinates the buffer containing the point coordinates for which to compute a bounding volume. - * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, - * this interprets the buffer has having tightly packed XYZ coordinate tuples. + * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, this + * interprets the buffer has having tightly packed XYZ coordinate tuples. * * @return the bounding volume, with axes lengths consistent with the conventions described in the Box - * class overview. + * class overview. * * @throws IllegalArgumentException if the buffer is null or empty, or if the stride is less than three. */ - public static Box computeBoundingBox(BufferWrapper coordinates, int stride) - { - if (coordinates == null) - { + public static Box computeBoundingBox(BufferWrapper coordinates, int stride) { + if (coordinates == null) { String msg = Logging.getMessage("nullValue.CoordinatesAreNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (stride < 3) - { + if (stride < 3) { String msg = Logging.getMessage("generic.StrideIsInvalid", stride); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Vec4[] axes = WWMath.computePrincipalAxes(coordinates, stride); - if (axes == null) - { + if (axes == null) { String msg = Logging.getMessage("generic.ListIsEmpty"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -563,37 +540,45 @@ public static Box computeBoundingBox(BufferWrapper coordinates, int stride) double minDotT = Double.MAX_VALUE; double maxDotT = -minDotT; - for (int i = 0; i <= coordinates.length() - stride; i += stride) - { + for (int i = 0; i <= coordinates.length() - stride; i += stride) { double x = coordinates.getDouble(i); double y = coordinates.getDouble(i + 1); double z = coordinates.getDouble(i + 2); double pdr = x * r.x + y * r.y + z * r.z; - if (pdr < minDotR) + if (pdr < minDotR) { minDotR = pdr; - if (pdr > maxDotR) + } + if (pdr > maxDotR) { maxDotR = pdr; + } double pds = x * s.x + y * s.y + z * s.z; - if (pds < minDotS) + if (pds < minDotS) { minDotS = pds; - if (pds > maxDotS) + } + if (pds > maxDotS) { maxDotS = pds; + } double pdt = x * t.x + y * t.y + z * t.z; - if (pdt < minDotT) + if (pdt < minDotT) { minDotT = pdt; - if (pdt > maxDotT) + } + if (pdt > maxDotT) { maxDotT = pdt; + } } - if (maxDotR == minDotR) + if (maxDotR == minDotR) { maxDotR = minDotR + 1; - if (maxDotS == minDotS) + } + if (maxDotS == minDotS) { maxDotS = minDotS + 1; - if (maxDotT == minDotT) + } + if (maxDotT == minDotT) { maxDotT = minDotT + 1; + } return new Box(axes, minDotR, maxDotR, minDotS, maxDotS, minDotT, maxDotT); } @@ -611,10 +596,8 @@ public static Box computeBoundingBox(BufferWrapper coordinates, int stride) * * @throws IllegalArgumentException if the iterable is null. */ - public static Box union(Iterable iterable) - { - if (iterable == null) - { + public static Box union(Iterable iterable) { + if (iterable == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -622,33 +605,27 @@ public static Box union(Iterable iterable) ArrayList boxes = new ArrayList(); - for (Box box : iterable) - { - if (box == null) + for (Box box : iterable) { + if (box == null) { continue; + } boxes.add(box); } - if (boxes.size() == 0) - { + if (boxes.size() == 0) { return null; - } - else if (boxes.size() == 1) - { + } else if (boxes.size() == 1) { // If the iterable contains only a single non-null box, we avoid unnecessarily computing its bouding box and // just return it directly. This also ensures that we do not return a box larger than the original box, by // performing a principal component analysis on the corners of a single box. return boxes.get(0); - } - else - { + } else { // If the iterable contains two or more boxes, gather up their corners and return a box that encloses the // boxes corners. We create an ArrayList with enough room to hold all the boxes corners to avoid unnecessary // overhead. ArrayList corners = new ArrayList(8 * boxes.size()); - for (Box box : boxes) - { + for (Box box : boxes) { corners.addAll(Arrays.asList(box.getCorners())); } @@ -656,13 +633,13 @@ else if (boxes.size() == 1) } } - /** {@inheritDoc} */ - public boolean intersects(Frustum frustum) - { + /** + * {@inheritDoc} + */ + public boolean intersects(Frustum frustum) { // FYI: this code is identical to that in Cylinder.intersects. - if (frustum == null) - { + if (frustum == null) { String message = Logging.getMessage("nullValue.FrustumIsNull"); Logging.logger().severe(message); @@ -670,33 +647,38 @@ public boolean intersects(Frustum frustum) } double intersectionPoint; - Vec4[] endPoints = new Vec4[] {this.bottomCenter, this.topCenter}; + Vec4[] endPoints = new Vec4[]{this.bottomCenter, this.topCenter}; double effectiveRadius = this.getEffectiveRadius2(frustum.getNear()); intersectionPoint = this.intersectsAt(frustum.getNear(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } // Near and far have the same effective radius. effectiveRadius = this.getEffectiveRadius2(frustum.getFar()); intersectionPoint = this.intersectsAt(frustum.getFar(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } effectiveRadius = this.getEffectiveRadius2(frustum.getLeft()); intersectionPoint = this.intersectsAt(frustum.getLeft(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } effectiveRadius = this.getEffectiveRadius2(frustum.getRight()); intersectionPoint = this.intersectsAt(frustum.getRight(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } effectiveRadius = this.getEffectiveRadius2(frustum.getTop()); intersectionPoint = this.intersectsAt(frustum.getTop(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } effectiveRadius = this.getEffectiveRadius2(frustum.getBottom()); intersectionPoint = this.intersectsAt(frustum.getBottom(), effectiveRadius, endPoints); @@ -712,12 +694,12 @@ public boolean intersects(Frustum frustum) * @param plane the plane in question. * * @return the effective radius of this box relative to the specified plane, using only this box's S and T axes to - * determine the effective radius. + * determine the effective radius. */ - protected double getEffectiveRadius2(Plane plane) - { - if (plane == null) + protected double getEffectiveRadius2(Plane plane) { + if (plane == null) { return 0; + } // Determine the effective radius of the box axis relative to the plane, use only the S and T axes because the // R axis is incorporated into the endpoints of the line this place is being tested against. @@ -725,19 +707,20 @@ protected double getEffectiveRadius2(Plane plane) return 0.5 * (Math.abs(this.s.dot3(n)) + Math.abs(this.t.dot3(n))); } - /** {@inheritDoc} */ - public double getEffectiveRadius(Plane plane) - { - if (plane == null) + /** + * {@inheritDoc} + */ + public double getEffectiveRadius(Plane plane) { + if (plane == null) { return 0; + } // Determine the effective radius of the box axis relative to the plane. Vec4 n = plane.getNormal(); return 0.5 * (Math.abs(this.s.dot3(n)) + Math.abs(this.t.dot3(n)) + Math.abs(this.r.dot3(n))); } - protected double intersectsAt(Plane plane, double effectiveRadius, Vec4[] endpoints) - { + protected double intersectsAt(Plane plane, double effectiveRadius, Vec4[] endpoints) { // Test the distance from the first end-point. double dq1 = plane.dot(endpoints[0]); boolean bq1 = dq1 <= -effectiveRadius; @@ -747,29 +730,34 @@ protected double intersectsAt(Plane plane, double effectiveRadius, Vec4[] endpoi boolean bq2 = dq2 <= -effectiveRadius; if (bq1 && bq2) // endpoints more distant from plane than effective radius; box is on neg. side of plane + { return -1; + } if (bq1 == bq2) // endpoints less distant from plane than effective radius; can't draw any conclusions + { return 0; + } // Compute and return the endpoints of the cylinder on the positive side of the plane. double t = (effectiveRadius + dq1) / plane.getNormal().dot3(endpoints[0].subtract3(endpoints[1])); Vec4 newEndPoint = endpoints[0].add3(endpoints[1].subtract3(endpoints[0]).multiply3(t)); // truncate the line to only that in the positive halfspace (e.g., inside the frustum) - if (bq1) + if (bq1) { endpoints[0] = newEndPoint; - else + } else { endpoints[1] = newEndPoint; + } return t; } - /** {@inheritDoc} */ - public boolean intersects(Plane plane) - { - if (plane == null) - { + /** + * {@inheritDoc} + */ + public boolean intersects(Plane plane) { + if (plane == null) { String message = Logging.getMessage("nullValue.PlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -779,8 +767,7 @@ public boolean intersects(Plane plane) return this.intersects(plane, effectiveRadius) >= 0; } - protected double intersects(Plane plane, double effectiveRadius) - { + protected double intersects(Plane plane, double effectiveRadius) { // Test the distance from the first end-point. double dq1 = plane.dot(this.bottomCenter); boolean bq1 = dq1 <= -effectiveRadius; @@ -790,25 +777,30 @@ protected double intersects(Plane plane, double effectiveRadius) boolean bq2 = dq2 <= -effectiveRadius; if (bq1 && bq2) // both beyond effective radius; box is on negative side of plane + { return -1; + } if (bq1 == bq2) // both within effective radius; can't draw any conclusions + { return 0; + } return 1; // box almost certainly intersects } - /** {@inheritDoc} */ - public Intersection[] intersect(Line line) - { + /** + * {@inheritDoc} + */ + public Intersection[] intersect(Line line) { return WWMath.polytopeIntersect(line, this.planes); } - /** {@inheritDoc} */ - public boolean intersects(Line line) - { - if (line == null) - { + /** + * {@inheritDoc} + */ + public boolean intersects(Line line) { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -817,11 +809,11 @@ public boolean intersects(Line line) return WWMath.polytopeIntersect(line, this.planes) != null; } - /** {@inheritDoc} */ - public double getProjectedArea(View view) - { - if (view == null) - { + /** + * {@inheritDoc} + */ + public double getProjectedArea(View view) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -830,7 +822,6 @@ public double getProjectedArea(View view) // Implementation based on "Real-time Bounding Box Area Computation" by Dieter Schmalstieg and Robert F. Tobler, // Vienna University of Technology: // http://jgt.akpeters.com/papers/SchmalstiegTobler99/ - // Compute the exact area of this Box in the screen by determining exact area covered by this Box's projected // vertices. We avoid computing a 2D bounding box of the projected vertices, because it is not necessarily more // efficient and is is less accurate: it is an approximation of an approximation. We start by computing the 2D @@ -841,18 +832,19 @@ public double getProjectedArea(View view) // Index 0 indicates that the view is inside this Box. Return positive infinity, indicating that this Box does // not have a finite area in the viewport. - if (lookupCode == 0) + if (lookupCode == 0) { return Double.POSITIVE_INFINITY; + } - if (lookupCode < 0 || lookupCode >= ProjectionHullTable.length) + if (lookupCode < 0 || lookupCode >= ProjectionHullTable.length) { return 0; // This should never happen, but we check anyway. - + } // Get the 4 or 6 vertex indices that define this Box's convex hull in screen coordinates. Each element is used // as an index into this Box's array of corners. int[] indices = ProjectionHullTable[lookupCode]; - if (indices == null || (indices.length != 4 && indices.length != 6)) + if (indices == null || (indices.length != 4 && indices.length != 6)) { return 0; // This should never happen, but we check anyway. - + } // Compute this Box's convex hull in screen coordinates, by transforming the 4 or 6 vertices that define its // projected outline from model coordinates into screen coordinates. Vec4[] vertices = this.getCorners(); @@ -861,15 +853,14 @@ public double getProjectedArea(View view) // If any of this Box's vertices are behind the eye point, return positive infinity indicating that this Box // does not have a finite area in the viewport. //noinspection ForLoopReplaceableByForEach - for (int i = 0; i < indices.length; i++) - { + for (int i = 0; i < indices.length; i++) { Vec4 eyeVertex = vertices[indices[i]].transformBy4(view.getModelviewMatrix()); - if (eyeVertex.z >= 0) + if (eyeVertex.z >= 0) { return Double.POSITIVE_INFINITY; + } } - for (int i = 0; i < indices.length; i++) - { + for (int i = 0; i < indices.length; i++) { screenVertices[i] = view.project(vertices[indices[i]]); } @@ -895,8 +886,7 @@ public double getProjectedArea(View view) * * @return an integer who's first 6 bits define an index into the ProjectionHullTable. */ - protected int computeProjectionHullCode(View view) - { + protected int computeProjectionHullCode(View view) { // Transform the view's eye point from world coordinates to this box's local coordinates. We use this box's r, s, // and t unit vectors axes as the x, y, and z axes of the local coordinate system. The r-axis is orthogonal to // the top and bottom sides, the s-axis is orthogonal to the front and back sides, and the t-axis is orthogonal @@ -906,12 +896,12 @@ protected int computeProjectionHullCode(View view) double ds = p.dot3(this.su); double dt = p.dot3(this.tu); - return (dr > this.rLength / 2.0 ? 1 : 0) // bit 0: top - | ((dr < (-this.rLength / 2.0) ? 1 : 0) << 1) // bit 1: bottom - | ((ds > this.sLength / 2.0 ? 1 : 0) << 2) // bit 2: front - | ((ds < (-this.sLength / 2.0) ? 1 : 0) << 3) // bit 3: back - | ((dt > this.tLength / 2.0 ? 1 : 0) << 4) // bit 4: right - | ((dt < (-this.tLength / 2.0) ? 1 : 0) << 5); // bit 5: left + return (dr > this.rLength / 2.0 ? 1 : 0) // bit 0: top + | ((dr < (-this.rLength / 2.0) ? 1 : 0) << 1) // bit 1: bottom + | ((ds > this.sLength / 2.0 ? 1 : 0) << 2) // bit 2: front + | ((ds < (-this.sLength / 2.0) ? 1 : 0) << 3) // bit 3: back + | ((dt > this.tLength / 2.0 ? 1 : 0) << 4) // bit 4: right + | ((dt < (-this.tLength / 2.0) ? 1 : 0) << 5); // bit 5: left } // public static void main(String[] args) @@ -925,7 +915,6 @@ protected int computeProjectionHullCode(View view) // if (intersections != null && intersections.length > 1 && intersections[1] != null) // System.out.println(intersections[1]); // } - // /** {@inheritDoc} */ // public Intersection[] intersect(Line line) // { @@ -994,23 +983,21 @@ protected int computeProjectionHullCode(View view) // else // intersects backface only; point origin is within the box // return new Intersection[] {new Intersection(p.add3(u.multiply3(bMin)), isTangent)}; // } - /** * Draws a representation of the Box. * * @param dc the DrawContext to be used. */ - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { return; + } Vec4 a = this.s.add3(this.t).multiply3(-0.5); Vec4 b = this.s.subtract3(this.t).multiply3(0.5); @@ -1020,12 +1007,11 @@ public void render(DrawContext dc) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushAttrib(gl, GL2.GL_COLOR_BUFFER_BIT // For alpha enable, blend enable, alpha func, blend func. - | GL2.GL_CURRENT_BIT // For current color. - | GL2.GL_LINE_BIT // For line width. - | GL2.GL_TRANSFORM_BIT // For matrix mode. - | GL2.GL_DEPTH_BUFFER_BIT); // For depth test enable, depth func. - try - { + | GL2.GL_CURRENT_BIT // For current color. + | GL2.GL_LINE_BIT // For line width. + | GL2.GL_TRANSFORM_BIT // For matrix mode. + | GL2.GL_DEPTH_BUFFER_BIT); // For depth test enable, depth func. + try { gl.glLineWidth(1f); gl.glEnable(GL.GL_BLEND); OGLUtil.applyBlending(gl, false); @@ -1038,15 +1024,12 @@ public void render(DrawContext dc) gl.glDepthFunc(GL.GL_GREATER); gl.glColor4f(1f, 0f, 1f, 0.4f); this.drawBox(dc, a, b, c, d); - } - finally - { + } finally { ogsh.pop(gl); } } - protected void drawBox(DrawContext dc, Vec4 a, Vec4 b, Vec4 c, Vec4 d) - { + protected void drawBox(DrawContext dc, Vec4 a, Vec4 b, Vec4 c, Vec4 d) { Vec4 e = a.add3(this.r); Vec4 f = d.add3(this.r); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -1054,15 +1037,13 @@ protected void drawBox(DrawContext dc, Vec4 a, Vec4 b, Vec4 c, Vec4 d) dc.getView().pushReferenceCenter(dc, this.bottomCenter); OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushModelview(gl); - try - { + try { // Draw parallel lines in R direction int n = 20; Vec4 dr = this.r.multiply3(1d / (double) n); this.drawOutline(dc, a, b, c, d); - for (int i = 1; i < n; i++) - { + for (int i = 1; i < n; i++) { gl.glTranslated(dr.x, dr.y, dr.z); this.drawOutline(dc, a, b, c, d); } @@ -1074,21 +1055,17 @@ protected void drawBox(DrawContext dc, Vec4 a, Vec4 b, Vec4 c, Vec4 d) gl.glPopMatrix(); gl.glPushMatrix(); this.drawOutline(dc, a, e, f, d); - for (int i = 1; i < n; i++) - { + for (int i = 1; i < n; i++) { gl.glTranslated(ds.x, ds.y, ds.z); this.drawOutline(dc, a, e, f, d); } - } - finally - { + } finally { ogsh.pop(gl); dc.getView().popReferenceCenter(dc); } } - protected void drawOutline(DrawContext dc, Vec4 a, Vec4 b, Vec4 c, Vec4 d) - { + protected void drawOutline(DrawContext dc, Vec4 a, Vec4 b, Vec4 c, Vec4 d) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_LINE_LOOP); gl.glVertex3d(a.x, a.y, a.z); @@ -1099,31 +1076,35 @@ protected void drawOutline(DrawContext dc, Vec4 a, Vec4 b, Vec4 c, Vec4 d) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (!(o instanceof Box)) + } + if (!(o instanceof Box)) { return false; + } Box box = (Box) o; - if (center != null ? !center.equals(box.center) : box.center != null) + if (center != null ? !center.equals(box.center) : box.center != null) { return false; - if (r != null ? !r.equals(box.r) : box.r != null) + } + if (r != null ? !r.equals(box.r) : box.r != null) { return false; - if (s != null ? !s.equals(box.s) : box.s != null) + } + if (s != null ? !s.equals(box.s) : box.s != null) { return false; + } //noinspection RedundantIfStatement - if (t != null ? !t.equals(box.t) : box.t != null) + if (t != null ? !t.equals(box.t) : box.t != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = center != null ? center.hashCode() : 0; result = 31 * result + (r != null ? r.hashCode() : 0); result = 31 * result + (s != null ? s.hashCode() : 0); diff --git a/src/gov/nasa/worldwind/geom/Cylinder.java b/src/gov/nasa/worldwind/geom/Cylinder.java index 216c2ada58..c812ca705a 100644 --- a/src/gov/nasa/worldwind/geom/Cylinder.java +++ b/src/gov/nasa/worldwind/geom/Cylinder.java @@ -20,8 +20,8 @@ * @author Tom Gaskins * @version $Id: Cylinder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Cylinder implements Extent, Renderable -{ +public class Cylinder implements Extent, Renderable { + protected final Vec4 bottomCenter; // point at center of cylinder base protected final Vec4 topCenter; // point at center of cylinder top protected final Vec4 axisUnitDirection; // axis as unit vector from bottomCenter to topCenter @@ -31,26 +31,22 @@ public class Cylinder implements Extent, Renderable /** * Create a Cylinder from two points and a radius. * - * @param bottomCenter the center point of of the cylinder's base. - * @param topCenter the center point of the cylinders top. + * @param bottomCenter the center point of of the cylinder's base. + * @param topCenter the center point of the cylinders top. * @param cylinderRadius the cylinder's radius. * - * @throws IllegalArgumentException if the radius is zero or the top or bottom point is null or they are - * coincident. + * @throws IllegalArgumentException if the radius is zero or the top or bottom point is null or they are coincident. */ - public Cylinder(Vec4 bottomCenter, Vec4 topCenter, double cylinderRadius) - { - if (bottomCenter == null || topCenter == null || bottomCenter.equals(topCenter)) - { + public Cylinder(Vec4 bottomCenter, Vec4 topCenter, double cylinderRadius) { + if (bottomCenter == null || topCenter == null || bottomCenter.equals(topCenter)) { String message = Logging.getMessage( - bottomCenter == null || topCenter == null ? "nullValue.EndPointIsNull" : "generic.EndPointsCoincident"); + bottomCenter == null || topCenter == null ? "nullValue.EndPointIsNull" : "generic.EndPointsCoincident"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cylinderRadius <= 0) - { + if (cylinderRadius <= 0) { String message = Logging.getMessage("Geom.Cylinder.RadiusIsZeroOrNegative", cylinderRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -71,27 +67,23 @@ public Cylinder(Vec4 bottomCenter, Vec4 topCenter, double cylinderRadius) * Create a Cylinder from two points, a radius and an axis direction. Provided for use when unit axis is know and * computation of it can be avoided. * - * @param bottomCenter the center point of of the cylinder's base. - * @param topCenter the center point of the cylinders top. + * @param bottomCenter the center point of of the cylinder's base. + * @param topCenter the center point of the cylinders top. * @param cylinderRadius the cylinder's radius. - * @param unitDirection the unit-length axis of the cylinder. + * @param unitDirection the unit-length axis of the cylinder. * - * @throws IllegalArgumentException if the radius is zero or the top or bottom point is null or they are - * coincident. + * @throws IllegalArgumentException if the radius is zero or the top or bottom point is null or they are coincident. */ - public Cylinder(Vec4 bottomCenter, Vec4 topCenter, double cylinderRadius, Vec4 unitDirection) - { - if (bottomCenter == null || topCenter == null || bottomCenter.equals(topCenter)) - { + public Cylinder(Vec4 bottomCenter, Vec4 topCenter, double cylinderRadius, Vec4 unitDirection) { + if (bottomCenter == null || topCenter == null || bottomCenter.equals(topCenter)) { String message = Logging.getMessage( - bottomCenter == null || topCenter == null ? "nullValue.EndPointIsNull" : "generic.EndPointsCoincident"); + bottomCenter == null || topCenter == null ? "nullValue.EndPointIsNull" : "generic.EndPointsCoincident"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cylinderRadius <= 0) - { + if (cylinderRadius <= 0) { String message = Logging.getMessage("Geom.Cylinder.RadiusIsZeroOrNegative", cylinderRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -113,8 +105,7 @@ public Cylinder(Vec4 bottomCenter, Vec4 topCenter, double cylinderRadius, Vec4 u * * @return the unit-length axis of this cylinder. */ - public Vec4 getAxisUnitDirection() - { + public Vec4 getAxisUnitDirection() { return axisUnitDirection; } @@ -123,8 +114,7 @@ public Vec4 getAxisUnitDirection() * * @return this cylinder's bottom-center point. */ - public Vec4 getBottomCenter() - { + public Vec4 getBottomCenter() { return bottomCenter; } @@ -133,8 +123,7 @@ public Vec4 getBottomCenter() * * @return this cylinder's top-center point. */ - public Vec4 getTopCenter() - { + public Vec4 getTopCenter() { return topCenter; } @@ -143,8 +132,7 @@ public Vec4 getTopCenter() * * @return this cylinder's radius. */ - public double getCylinderRadius() - { + public double getCylinderRadius() { return cylinderRadius; } @@ -153,8 +141,7 @@ public double getCylinderRadius() * * @return this cylinder's height. */ - public double getCylinderHeight() - { + public double getCylinderHeight() { return cylinderHeight; } @@ -163,25 +150,26 @@ public double getCylinderHeight() * * @return this cylinder's center point. */ - public Vec4 getCenter() - { + public Vec4 getCenter() { Vec4 b = this.bottomCenter; Vec4 t = this.topCenter; return new Vec4( - (b.x + t.x) / 2.0, - (b.y + t.y) / 2.0, - (b.z + t.z) / 2.0); + (b.x + t.x) / 2.0, + (b.y + t.y) / 2.0, + (b.z + t.z) / 2.0); } - /** {@inheritDoc} */ - public double getDiameter() - { + /** + * {@inheritDoc} + */ + public double getDiameter() { return 2 * this.getRadius(); } - /** {@inheritDoc} */ - public double getRadius() - { + /** + * {@inheritDoc} + */ + public double getRadius() { // return the radius of the enclosing sphere double halfHeight = this.bottomCenter.distanceTo3(this.topCenter) / 2.0; return Math.sqrt(halfHeight * halfHeight + this.cylinderRadius * this.cylinderRadius); @@ -192,8 +180,7 @@ public double getRadius() * * @return this cylinder's volume. */ - public double getVolume() - { + public double getVolume() { return Math.PI * this.cylinderRadius * this.cylinderRadius * this.cylinderHeight; } @@ -203,23 +190,20 @@ public double getVolume() * @param points the points to compute a bounding cylinder for. * * @return a cylinder bounding all the points. The axis of the cylinder is the longest principal axis of the - * collection. (See {@link WWMath#computePrincipalAxes(Iterable)}. + * collection. (See {@link WWMath#computePrincipalAxes(Iterable)}. * * @throws IllegalArgumentException if the point list is null or empty. * @see #computeVerticalBoundingCylinder(gov.nasa.worldwind.globes.Globe, double, Sector) */ - public static Cylinder computeBoundingCylinder(Iterable points) - { - if (points == null) - { + public static Cylinder computeBoundingCylinder(Iterable points) { + if (points == null) { String message = Logging.getMessage("nullValue.PointListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Vec4[] axes = WWMath.computePrincipalAxes(points); - if (axes == null) - { + if (axes == null) { String message = Logging.getMessage("generic.ListIsEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -232,31 +216,29 @@ public static Cylinder computeBoundingCylinder(Iterable points) double minDotR = Double.MAX_VALUE; double maxDotR = -minDotR; - for (Vec4 p : points) - { + for (Vec4 p : points) { double pdr = p.dot3(r); sPlanePoints.add(p.subtract3(r.multiply3(p.dot3(r)))); - if (pdr < minDotR) + if (pdr < minDotR) { minDotR = pdr; - if (pdr > maxDotR) + } + if (pdr > maxDotR) { maxDotR = pdr; + } } Vec4 minPoint = sPlanePoints.get(0); Vec4 maxPoint = minPoint; double minDotS = Double.MAX_VALUE; double maxDotS = -minDotS; - for (Vec4 p : sPlanePoints) - { + for (Vec4 p : sPlanePoints) { double d = p.dot3(s); - if (d < minDotS) - { + if (d < minDotS) { minPoint = p; minDotS = d; } - if (d > maxDotS) - { + if (d > maxDotS) { maxPoint = p; maxDotS = d; } @@ -265,12 +247,10 @@ public static Cylinder computeBoundingCylinder(Iterable points) Vec4 center = minPoint.add3(maxPoint).divide3(2); double radius = center.distanceTo3(minPoint); - for (Vec4 h : sPlanePoints) - { + for (Vec4 h : sPlanePoints) { Vec4 hq = h.subtract3(center); double d = hq.getLength3(); - if (d > radius) - { + if (d > radius) { Vec4 g = center.subtract3(hq.normalize3().multiply3(radius)); center = g.add3(h).divide3(2); radius = d; @@ -280,20 +260,22 @@ public static Cylinder computeBoundingCylinder(Iterable points) Vec4 bottomCenter = center.add3(r.multiply3(minDotR)); Vec4 topCenter = center.add3((r.multiply3(maxDotR))); - if (radius == 0) + if (radius == 0) { radius = 1; + } - if (bottomCenter.equals(topCenter)) + if (bottomCenter.equals(topCenter)) { topCenter = bottomCenter.add3(new Vec4(1, 0, 0)); + } return new Cylinder(bottomCenter, topCenter, radius); } - /** {@inheritDoc} */ - public Intersection[] intersect(Line line) - { - if (line == null) - { + /** + * {@inheritDoc} + */ + public Intersection[] intersect(Line line) { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -301,28 +283,33 @@ public Intersection[] intersect(Line line) double[] tVals = new double[2]; if (!intcyl(line.getOrigin(), line.getDirection(), this.bottomCenter, this.axisUnitDirection, - this.cylinderRadius, tVals)) + this.cylinderRadius, tVals)) { return null; + } if (!clipcyl(line.getOrigin(), line.getDirection(), this.bottomCenter, this.topCenter, - this.axisUnitDirection, tVals)) + this.axisUnitDirection, tVals)) { return null; + } - if (!Double.isInfinite(tVals[0]) && !Double.isInfinite(tVals[1]) && tVals[0] >= 0.0 && tVals[1] >= 0.0) - return new Intersection[] {new Intersection(line.getPointAt(tVals[0]), false), + if (!Double.isInfinite(tVals[0]) && !Double.isInfinite(tVals[1]) && tVals[0] >= 0.0 && tVals[1] >= 0.0) { + return new Intersection[]{new Intersection(line.getPointAt(tVals[0]), false), new Intersection(line.getPointAt(tVals[1]), false)}; - if (!Double.isInfinite(tVals[0]) && tVals[0] >= 0.0) - return new Intersection[] {new Intersection(line.getPointAt(tVals[0]), false)}; - if (!Double.isInfinite(tVals[1]) && tVals[1] >= 0.0) - return new Intersection[] {new Intersection(line.getPointAt(tVals[1]), false)}; + } + if (!Double.isInfinite(tVals[0]) && tVals[0] >= 0.0) { + return new Intersection[]{new Intersection(line.getPointAt(tVals[0]), false)}; + } + if (!Double.isInfinite(tVals[1]) && tVals[1] >= 0.0) { + return new Intersection[]{new Intersection(line.getPointAt(tVals[1]), false)}; + } return null; } - /** {@inheritDoc} */ - public boolean intersects(Line line) - { - if (line == null) - { + /** + * {@inheritDoc} + */ + public boolean intersects(Line line) { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -332,9 +319,7 @@ public boolean intersects(Line line) } // Taken from "Graphics Gems IV", Section V.2, page 356. - - protected boolean intcyl(Vec4 raybase, Vec4 raycos, Vec4 base, Vec4 axis, double radius, double[] tVals) - { + protected boolean intcyl(Vec4 raybase, Vec4 raycos, Vec4 base, Vec4 axis, double radius, double[] tVals) { boolean hit; // True if ray intersects cyl Vec4 RC; // Ray base to cylinder base double d; // Shortest distance between the ray and the cylinder @@ -346,8 +331,7 @@ protected boolean intcyl(Vec4 raybase, Vec4 raycos, Vec4 base, Vec4 axis, double n = raycos.cross3(axis); // Ray is parallel to the cylinder's axis. - if ((ln = n.getLength3()) == 0.0) - { + if ((ln = n.getLength3()) == 0.0) { d = RC.dot3(axis); D = RC.subtract3(axis.multiply3(d)); d = D.getLength3(); @@ -362,8 +346,7 @@ protected boolean intcyl(Vec4 raybase, Vec4 raycos, Vec4 base, Vec4 axis, double hit = (d <= radius); // If ray hits cylinder. - if (hit) - { + if (hit) { O = RC.cross3(axis); t = -O.dot3(n) / ln; O = n.cross3(axis); @@ -377,9 +360,7 @@ protected boolean intcyl(Vec4 raybase, Vec4 raycos, Vec4 base, Vec4 axis, double } // Taken from "Graphics Gems IV", Section V.2, page 356. - - protected boolean clipcyl(Vec4 raybase, Vec4 raycos, Vec4 bot, Vec4 top, Vec4 axis, double[] tVals) - { + protected boolean clipcyl(Vec4 raybase, Vec4 raycos, Vec4 bot, Vec4 top, Vec4 axis, double[] tVals) { double dc, dwb, dwt, tb, tt; double in, out; // Object intersection distances. @@ -391,43 +372,47 @@ protected boolean clipcyl(Vec4 raybase, Vec4 raycos, Vec4 bot, Vec4 top, Vec4 ax dwt = axis.dot3(raybase) - axis.dot3(top); // Ray is parallel to the cylinder end-caps. - if (dc == 0.0) - { - if (dwb <= 0.0) + if (dc == 0.0) { + if (dwb <= 0.0) { return false; - if (dwt >= 0.0) + } + if (dwt >= 0.0) { return false; - } - else - { + } + } else { // Intersect the ray with the bottom end-cap. tb = -dwb / dc; // Intersect the ray with the top end-cap. tt = -dwt / dc; // Bottom is near cap, top is far cap. - if (dc >= 0.0) - { - if (tb > out) + if (dc >= 0.0) { + if (tb > out) { return false; - if (tt < in) + } + if (tt < in) { return false; - if (tb > in && tb < out) + } + if (tb > in && tb < out) { in = tb; - if (tt > in && tt < out) + } + if (tt > in && tt < out) { out = tt; - } - // Bottom is far cap, top is near cap. - else - { - if (tb < in) + } + } // Bottom is far cap, top is near cap. + else { + if (tb < in) { return false; - if (tt > out) + } + if (tt > out) { return false; - if (tb > in && tb < out) + } + if (tb > in && tb < out) { out = tb; - if (tt > in && tt < out) + } + if (tt > in && tt < out) { in = tt; + } } } @@ -436,8 +421,7 @@ protected boolean clipcyl(Vec4 raybase, Vec4 raycos, Vec4 bot, Vec4 top, Vec4 ax return in < out; } - protected double intersects(Plane plane, double effectiveRadius) - { + protected double intersects(Plane plane, double effectiveRadius) { // Test the distance from the first cylinder end-point. Assumes that bottomCenter's w-coordinate is 1. double dq1 = plane.dot(this.bottomCenter); boolean bq1 = dq1 <= -effectiveRadius; @@ -447,16 +431,19 @@ protected double intersects(Plane plane, double effectiveRadius) boolean bq2 = dq2 <= -effectiveRadius; if (bq1 && bq2) // both beyond effective radius; cylinder is on negative side of plane + { return -1; + } if (bq1 == bq2) // both within effective radius; can't draw any conclusions + { return 0; + } return 1; // Cylinder almost certainly intersects } - protected double intersectsAt(Plane plane, double effectiveRadius, Vec4[] endpoints) - { + protected double intersectsAt(Plane plane, double effectiveRadius, Vec4[] endpoints) { // Test the distance from the first end-point. Assumes that the first end-point's w-coordinate is 1. double dq1 = plane.dot(endpoints[0]); boolean bq1 = dq1 <= -effectiveRadius; @@ -467,43 +454,53 @@ protected double intersectsAt(Plane plane, double effectiveRadius, Vec4[] endpoi boolean bq2 = dq2 <= -effectiveRadius; if (bq1 && bq2) // endpoints more distant from plane than effective radius; cylinder is on neg. side of plane + { return -1; + } if (bq1 == bq2) // endpoints less distant from plane than effective radius; can't draw any conclusions + { return 0; + } // Compute and return the endpoints of the cylinder on the positive side of the plane. double t = (effectiveRadius + dq1) / plane.getNormal().dot3(endpoints[0].subtract3(endpoints[1])); Vec4 newEndPoint = endpoints[0].add3(endpoints[1].subtract3(endpoints[0]).multiply3(t)); if (bq1) // Truncate the lower end of the cylinder + { endpoints[0] = newEndPoint; - else // Truncate the upper end of the cylinder + } else // Truncate the upper end of the cylinder + { endpoints[1] = newEndPoint; + } return t; } - /** {@inheritDoc} */ - public double getEffectiveRadius(Plane plane) - { - if (plane == null) + /** + * {@inheritDoc} + */ + public double getEffectiveRadius(Plane plane) { + if (plane == null) { return 0; + } // Determine the effective radius of the cylinder axis relative to the plane. double dot = plane.getNormal().dot3(this.axisUnitDirection); double scale = 1d - dot * dot; - if (scale <= 0) + if (scale <= 0) { return 0; - else + } else { return this.cylinderRadius * Math.sqrt(scale); + } } - /** {@inheritDoc} */ - public boolean intersects(Plane plane) - { - if (plane == null) - { + /** + * {@inheritDoc} + */ + public boolean intersects(Plane plane) { + if (plane == null) { String message = Logging.getMessage("nullValue.PlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -513,11 +510,11 @@ public boolean intersects(Plane plane) return this.intersects(plane, effectiveRadius) >= 0; } - /** {@inheritDoc} */ - public boolean intersects(Frustum frustum) - { - if (frustum == null) - { + /** + * {@inheritDoc} + */ + public boolean intersects(Frustum frustum) { + if (frustum == null) { String message = Logging.getMessage("nullValue.FrustumIsNull"); Logging.logger().severe(message); @@ -525,43 +522,48 @@ public boolean intersects(Frustum frustum) } double intersectionPoint; - Vec4[] endPoints = new Vec4[] {this.bottomCenter, this.topCenter}; + Vec4[] endPoints = new Vec4[]{this.bottomCenter, this.topCenter}; double effectiveRadius = this.getEffectiveRadius(frustum.getNear()); intersectionPoint = this.intersectsAt(frustum.getNear(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } // Near and far have the same effective radius. intersectionPoint = this.intersectsAt(frustum.getFar(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } effectiveRadius = this.getEffectiveRadius(frustum.getLeft()); intersectionPoint = this.intersectsAt(frustum.getLeft(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } effectiveRadius = this.getEffectiveRadius(frustum.getRight()); intersectionPoint = this.intersectsAt(frustum.getRight(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } effectiveRadius = this.getEffectiveRadius(frustum.getTop()); intersectionPoint = this.intersectsAt(frustum.getTop(), effectiveRadius, endPoints); - if (intersectionPoint < 0) + if (intersectionPoint < 0) { return false; + } effectiveRadius = this.getEffectiveRadius(frustum.getBottom()); intersectionPoint = this.intersectsAt(frustum.getBottom(), effectiveRadius, endPoints); return intersectionPoint >= 0; } - /** {@inheritDoc} */ - public double getProjectedArea(View view) - { - if (view == null) - { + /** + * {@inheritDoc} + */ + public double getProjectedArea(View view) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -576,27 +578,24 @@ public double getProjectedArea(View view) * specified vertical exaggeration, and is oriented such that the cylinder axis is perpendicular to the globe's * surface. * - * @param globe The globe associated with the sector. + * @param globe The globe associated with the sector. * @param verticalExaggeration the vertical exaggeration to apply to the minimum and maximum elevations when - * computing the cylinder. - * @param sector the sector to return the bounding cylinder for. + * computing the cylinder. + * @param sector the sector to return the bounding cylinder for. * * @return The minimal bounding cylinder in Cartesian coordinates. * * @throws IllegalArgumentException if sector is null * @see #computeBoundingCylinder(Iterable) */ - static public Cylinder computeVerticalBoundingCylinder(Globe globe, double verticalExaggeration, Sector sector) - { - if (globe == null) - { + static public Cylinder computeVerticalBoundingCylinder(Globe globe, double verticalExaggeration, Sector sector) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -604,7 +603,7 @@ static public Cylinder computeVerticalBoundingCylinder(Globe globe, double verti double[] minAndMaxElevations = globe.getMinAndMaxElevations(sector); return computeVerticalBoundingCylinder(globe, verticalExaggeration, sector, - minAndMaxElevations[0], minAndMaxElevations[1]); + minAndMaxElevations[0], minAndMaxElevations[1]); } /** @@ -612,12 +611,12 @@ static public Cylinder computeVerticalBoundingCylinder(Globe globe, double verti * specified vertical exaggeration, and is oriented such that the cylinder axis is perpendicular to the globe's * surface. * - * @param globe The globe associated with the sector. + * @param globe The globe associated with the sector. * @param verticalExaggeration the vertical exaggeration to apply to the minimum and maximum elevations when - * computing the cylinder. - * @param sector the sector to return the bounding cylinder for. - * @param minElevation the minimum elevation of the bounding cylinder. - * @param maxElevation the maximum elevation of the bounding cylinder. + * computing the cylinder. + * @param sector the sector to return the bounding cylinder for. + * @param minElevation the minimum elevation of the bounding cylinder. + * @param maxElevation the maximum elevation of the bounding cylinder. * * @return The minimal bounding cylinder in Cartesian coordinates. * @@ -625,10 +624,8 @@ static public Cylinder computeVerticalBoundingCylinder(Globe globe, double verti * @see #computeBoundingCylinder(Iterable) */ public static Cylinder computeVerticalBoundingCylinder(Globe globe, double verticalExaggeration, Sector sector, - double minElevation, double maxElevation) - { - if (sector == null) - { + double minElevation, double maxElevation) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -638,22 +635,19 @@ public static Cylinder computeVerticalBoundingCylinder(Globe globe, double verti double minHeight = minElevation * verticalExaggeration; double maxHeight = maxElevation * verticalExaggeration; - if (minHeight == maxHeight) + if (minHeight == maxHeight) { maxHeight = minHeight + 1; // ensure the top and bottom of the cylinder won't be coincident - + } // If the sector spans both poles in latitude, or spans greater than 180 degrees in longitude, we cannot use the // sector's Cartesian quadrilateral to compute a bounding cylinde. This is because the quadrilateral is either // smaller than the geometry defined by the sector (when deltaLon >= 180), or the quadrilateral degenerates to // two points (when deltaLat >= 180). So we compute a bounging cylinder that spans the equator and covers the // sector's latitude range. In some cases this cylinder may be too large, but we're typically not interested // in culling these cylinders since the sector will span most of the globe. - if (sector.getDeltaLatDegrees() >= 180d || sector.getDeltaLonDegrees() >= 180d) - { + if (sector.getDeltaLatDegrees() >= 180d || sector.getDeltaLonDegrees() >= 180d) { return computeVerticalBoundsFromSectorLatitudeRange(globe, sector, minHeight, maxHeight); - } - // Otherwise, create a standard bounding cylinder that minimally surrounds the specified sector and elevations. - else - { + } // Otherwise, create a standard bounding cylinder that minimally surrounds the specified sector and elevations. + else { return computeVerticalBoundsFromSectorQuadrilateral(globe, sector, minHeight, maxHeight); } } @@ -662,8 +656,8 @@ public static Cylinder computeVerticalBoundingCylinder(Globe globe, double verti * Compute the Cylinder that surrounds the equator, and has height defined by the sector's minumum and maximum * latitudes (including maxHeight). * - * @param globe The globe associated with the sector. - * @param sector the sector to return the bounding cylinder for. + * @param globe The globe associated with the sector. + * @param sector the sector to return the bounding cylinder for. * @param minHeight the minimum height to include in the bounding cylinder. * @param maxHeight the maximum height to include in the bounding cylinder. * @@ -673,10 +667,8 @@ public static Cylinder computeVerticalBoundingCylinder(Globe globe, double verti */ @SuppressWarnings({"UnusedDeclaration"}) protected static Cylinder computeVerticalBoundsFromSectorLatitudeRange(Globe globe, Sector sector, double minHeight, - double maxHeight) - { - if (sector == null) - { + double maxHeight) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -689,7 +681,7 @@ protected static Cylinder computeVerticalBoundsFromSectorLatitudeRange(Globe glo // Compute the sector's lowest projection along the cylinder axis. This will be a point of minimum latitude // with maxHeight. Vec4 extremePoint = globe.computePointFromPosition(sector.getMinLatitude(), sector.getMinLongitude(), - maxHeight); + maxHeight); double minProj = extremePoint.subtract3(centerPoint).dot3(axis); // Compute the sector's lowest highest along the cylinder axis. This will be a point of maximum latitude // with maxHeight. @@ -699,11 +691,13 @@ protected static Cylinder computeVerticalBoundsFromSectorLatitudeRange(Globe glo Vec4 bottomCenterPoint = axis.multiply3(minProj).add3(centerPoint); Vec4 topCenterPoint = axis.multiply3(maxProj).add3(centerPoint); - if (radius == 0) + if (radius == 0) { radius = 1; + } - if (bottomCenterPoint.equals(topCenterPoint)) + if (bottomCenterPoint.equals(topCenterPoint)) { topCenterPoint = bottomCenterPoint.add3(new Vec4(1, 0, 0)); + } return new Cylinder(bottomCenterPoint, topCenterPoint, radius); } @@ -711,8 +705,8 @@ protected static Cylinder computeVerticalBoundsFromSectorLatitudeRange(Globe glo /** * Returns a cylinder that minimally surrounds the specified height range in the sector. * - * @param globe The globe associated with the sector. - * @param sector the sector to return the bounding cylinder for. + * @param globe The globe associated with the sector. + * @param sector the sector to return the bounding cylinder for. * @param minHeight the minimum height to include in the bounding cylinder. * @param maxHeight the maximum height to include in the bounding cylinder. * @@ -721,10 +715,8 @@ protected static Cylinder computeVerticalBoundsFromSectorLatitudeRange(Globe glo * @throws IllegalArgumentException if sector is null */ protected static Cylinder computeVerticalBoundsFromSectorQuadrilateral(Globe globe, Sector sector, double minHeight, - double maxHeight) - { - if (sector == null) - { + double maxHeight) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -734,14 +726,11 @@ protected static Cylinder computeVerticalBoundsFromSectorQuadrilateral(Globe glo // closest to the equator, then choose a third point from the opposite pair. We use maxHeight as elevation // because we want to bound the largest potential quadrilateral for the sector. Vec4 p0, p1, p2; - if (Math.abs(sector.getMinLatitude().degrees) <= Math.abs(sector.getMaxLatitude().degrees)) - { + if (Math.abs(sector.getMinLatitude().degrees) <= Math.abs(sector.getMaxLatitude().degrees)) { p0 = globe.computePointFromPosition(sector.getMinLatitude(), sector.getMaxLongitude(), maxHeight); // SE p1 = globe.computePointFromPosition(sector.getMinLatitude(), sector.getMinLongitude(), maxHeight); // SW p2 = globe.computePointFromPosition(sector.getMaxLatitude(), sector.getMinLongitude(), maxHeight); // NW - } - else - { + } else { p0 = globe.computePointFromPosition(sector.getMaxLatitude(), sector.getMinLongitude(), maxHeight); // NW p1 = globe.computePointFromPosition(sector.getMaxLatitude(), sector.getMaxLongitude(), maxHeight); // NE p2 = globe.computePointFromPosition(sector.getMinLatitude(), sector.getMinLongitude(), maxHeight); // SW @@ -752,8 +741,7 @@ protected static Cylinder computeVerticalBoundsFromSectorQuadrilateral(Globe glo Vec4[] centerOut = new Vec4[1]; Vec4[] axisOut = new Vec4[1]; double[] radiusOut = new double[1]; - if (!WWMath.computeCircleThroughPoints(p0, p1, p2, centerOut, axisOut, radiusOut)) - { + if (!WWMath.computeCircleThroughPoints(p0, p1, p2, centerOut, axisOut, radiusOut)) { // If the computation failed, then two of the points are coincident. Fall back to creating a bounding // cylinder based on the vertices of the sector. This bounding cylinder won't be as tight a fit, but // it will be correct. @@ -766,7 +754,7 @@ protected static Cylinder computeVerticalBoundsFromSectorQuadrilateral(Globe glo // Compute the sector's lowest projection along the cylinder axis. We test opposite corners of the sector // using minHeight. One of these will be the lowest point in the sector. Vec4 extremePoint = globe.computePointFromPosition(sector.getMinLatitude(), sector.getMinLongitude(), - minHeight); + minHeight); double minProj = extremePoint.subtract3(centerPoint).dot3(axis); extremePoint = globe.computePointFromPosition(sector.getMaxLatitude(), sector.getMaxLongitude(), minHeight); minProj = Math.min(minProj, extremePoint.subtract3(centerPoint).dot3(axis)); @@ -779,11 +767,13 @@ protected static Cylinder computeVerticalBoundsFromSectorQuadrilateral(Globe glo Vec4 bottomCenterPoint = axis.multiply3(minProj).add3(centerPoint); Vec4 topCenterPoint = axis.multiply3(maxProj).add3(centerPoint); - if (radius == 0) + if (radius == 0) { radius = 1; + } - if (bottomCenterPoint.equals(topCenterPoint)) + if (bottomCenterPoint.equals(topCenterPoint)) { topCenterPoint = bottomCenterPoint.add3(new Vec4(1, 0, 0)); + } return new Cylinder(bottomCenterPoint, topCenterPoint, radius); } @@ -792,8 +782,8 @@ protected static Cylinder computeVerticalBoundsFromSectorQuadrilateral(Globe glo * Returns a cylinder that surrounds the specified height range in the zero-area sector. The returned cylinder won't * be as tight a fit as computeBoundsFromSectorQuadrilateral. * - * @param globe The globe associated with the sector. - * @param sector the sector to return the bounding cylinder for. + * @param globe The globe associated with the sector. + * @param sector the sector to return the bounding cylinder for. * @param minHeight the minimum height to include in the bounding cylinder. * @param maxHeight the maximum height to include in the bounding cylinder. * @@ -802,10 +792,8 @@ protected static Cylinder computeVerticalBoundsFromSectorQuadrilateral(Globe glo * @throws IllegalArgumentException if sector is null */ protected static Cylinder computeVerticalBoundsFromSectorVertices(Globe globe, Sector sector, double minHeight, - double maxHeight) - { - if (sector == null) - { + double maxHeight) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -814,7 +802,7 @@ protected static Cylinder computeVerticalBoundsFromSectorVertices(Globe globe, S // Compute the top center point as the surface point with maxHeight at the sector's centroid. LatLon centroid = sector.getCentroid(); Vec4 topCenterPoint = globe.computePointFromPosition(centroid.getLatitude(), centroid.getLongitude(), - maxHeight); + maxHeight); // Compute the axis as the surface normal at the sector's centroid. Vec4 axis = globe.computeSurfaceNormalAtPoint(topCenterPoint); @@ -837,11 +825,13 @@ protected static Cylinder computeVerticalBoundsFromSectorVertices(Globe globe, S radius = Math.max(radius, topCenterPoint.distanceTo3(northeast)); radius = Math.max(radius, topCenterPoint.distanceTo3(northwest)); - if (radius == 0) + if (radius == 0) { radius = 1; + } - if (bottomCenterPoint.equals(topCenterPoint)) + if (bottomCenterPoint.equals(topCenterPoint)) { topCenterPoint = bottomCenterPoint.add3(new Vec4(1, 0, 0)); + } return new Cylinder(bottomCenterPoint, topCenterPoint, radius); } @@ -853,10 +843,8 @@ protected static Cylinder computeVerticalBoundsFromSectorVertices(Globe globe, S * * @throws IllegalArgumentException if the draw context is null. */ - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -867,8 +855,8 @@ public void render(DrawContext dc) // perpendicular to the cylinder's axisUnitDirection. Because the cylinder is symmetric, it does not matter // in what direction the y-axis points, as long as it is perpendicular to the z-axis. double tolerance = 1e-6; - Vec4 upVector = (this.axisUnitDirection.cross3(Vec4.UNIT_Y).getLength3() <= tolerance) ? - Vec4.UNIT_NEGATIVE_Z : Vec4.UNIT_Y; + Vec4 upVector = (this.axisUnitDirection.cross3(Vec4.UNIT_Y).getLength3() <= tolerance) + ? Vec4.UNIT_NEGATIVE_Z : Vec4.UNIT_Y; Matrix transformMatrix = Matrix.fromModelLookAt(this.bottomCenter, this.topCenter, upVector); double[] matrixArray = new double[16]; transformMatrix.toArray(matrixArray, 0, false); @@ -877,8 +865,7 @@ public void render(DrawContext dc) OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushAttrib(gl, GL2.GL_CURRENT_BIT | GL2.GL_ENABLE_BIT | GL2.GL_TRANSFORM_BIT | GL2.GL_DEPTH_BUFFER_BIT); - try - { + try { // The cylinder is drawn with as a wireframe plus a center axis. It's drawn in two passes in order to // visualize the portions of the cylinder above and below an intersecting surface. @@ -917,42 +904,45 @@ public void render(DrawContext dc) dc.getGLU().gluCylinder(quadric, this.cylinderRadius, this.cylinderRadius, this.cylinderHeight, 30, 30); dc.getGLU().gluDeleteQuadric(quadric); - } - finally - { + } finally { ogsh.pop(gl); } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (!(o instanceof Cylinder)) + } + if (!(o instanceof Cylinder)) { return false; + } Cylinder cylinder = (Cylinder) o; - if (Double.compare(cylinder.cylinderHeight, cylinderHeight) != 0) + if (Double.compare(cylinder.cylinderHeight, cylinderHeight) != 0) { return false; - if (Double.compare(cylinder.cylinderRadius, cylinderRadius) != 0) + } + if (Double.compare(cylinder.cylinderRadius, cylinderRadius) != 0) { return false; + } if (axisUnitDirection != null ? !axisUnitDirection.equals(cylinder.axisUnitDirection) - : cylinder.axisUnitDirection != null) + : cylinder.axisUnitDirection != null) { return false; - if (bottomCenter != null ? !bottomCenter.equals(cylinder.bottomCenter) : cylinder.bottomCenter != null) + } + if (bottomCenter != null ? !bottomCenter.equals(cylinder.bottomCenter) : cylinder.bottomCenter != null) { return false; + } //noinspection RedundantIfStatement - if (topCenter != null ? !topCenter.equals(cylinder.topCenter) : cylinder.topCenter != null) + if (topCenter != null ? !topCenter.equals(cylinder.topCenter) : cylinder.topCenter != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; long temp; result = bottomCenter != null ? bottomCenter.hashCode() : 0; @@ -965,9 +955,8 @@ public int hashCode() return result; } - public String toString() - { + public String toString() { return this.cylinderRadius + ", " + this.bottomCenter.toString() + ", " + this.topCenter.toString() + ", " - + this.axisUnitDirection.toString(); + + this.axisUnitDirection.toString(); } } diff --git a/src/gov/nasa/worldwind/geom/Extent.java b/src/gov/nasa/worldwind/geom/Extent.java index ed3f67bf61..568e311272 100644 --- a/src/gov/nasa/worldwind/geom/Extent.java +++ b/src/gov/nasa/worldwind/geom/Extent.java @@ -14,8 +14,8 @@ * @author Tom Gaskins * @version $Id: Extent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Extent -{ +public interface Extent { + /** * Returns the extent's center point. * @@ -57,7 +57,7 @@ public interface Extent * @param line the Line with which to intersect this Extent. * * @return an array of intersections representing all the points where line enters or leave this - * Extent. + * Extent. */ gov.nasa.worldwind.geom.Intersection[] intersect(gov.nasa.worldwind.geom.Line line); @@ -105,8 +105,8 @@ public interface Extent * @param view the View for which to compute a projected screen area. * * @return the projected screen area of this Extent in square pixels, or - * Double.POSITIVE_INFINITY if the view's eye point is inside this - * Extent or part of this Extent is behind the view's eye point. + * Double.POSITIVE_INFINITY if the view's eye point is inside this Extent or + * part of this Extent is behind the view's eye point. * * @throws IllegalArgumentException if the view is null. */ diff --git a/src/gov/nasa/worldwind/geom/ExtentHolder.java b/src/gov/nasa/worldwind/geom/ExtentHolder.java index f704d986c8..5053d959b8 100644 --- a/src/gov/nasa/worldwind/geom/ExtentHolder.java +++ b/src/gov/nasa/worldwind/geom/ExtentHolder.java @@ -14,14 +14,14 @@ * @version $Id: ExtentHolder.java 1171 2013-02-11 21:45:02Z dcollins $ * @see gov.nasa.worldwind.geom.Extent */ -public interface ExtentHolder -{ +public interface ExtentHolder { + /** * Returns the objects enclosing volume as an {@link gov.nasa.worldwind.geom.Extent} in model coordinates, given a * specified {@link gov.nasa.worldwind.globes.Globe} and vertical exaggeration (see {@link * gov.nasa.worldwind.SceneController#getVerticalExaggeration()}. * - * @param globe the Globe the object is related to. + * @param globe the Globe the object is related to. * @param verticalExaggeration the vertical exaggeration of the scene containing this object. * * @return the object's Extent in model coordinates. diff --git a/src/gov/nasa/worldwind/geom/Frustum.java b/src/gov/nasa/worldwind/geom/Frustum.java index adc6b6326f..eb036ab15d 100644 --- a/src/gov/nasa/worldwind/geom/Frustum.java +++ b/src/gov/nasa/worldwind/geom/Frustum.java @@ -15,27 +15,30 @@ * @author Tom Gaskins * @version $Id: Frustum.java 2178 2014-07-25 16:40:09Z dcollins $ */ -public class Frustum -{ +public class Frustum { + protected final Plane left; protected final Plane right; protected final Plane bottom; protected final Plane top; protected final Plane near; protected final Plane far; - /** Holds all six frustum planes in an array in the order left, right, bottom, top, near, far. */ + /** + * Holds all six frustum planes in an array in the order left, right, bottom, top, near, far. + */ protected final Plane[] allPlanes; - /** Constructs a frustum two meters wide centered at the origin. Primarily used for testing. */ - public Frustum() - { + /** + * Constructs a frustum two meters wide centered at the origin. Primarily used for testing. + */ + public Frustum() { this( - new Plane(1, 0, 0, 1), // Left - new Plane(-1, 0, 0, 1), // Right - new Plane(0, 1, 0, 1), // Bottom - new Plane(0, -1, 0, 1), // Top - new Plane(0, 0, -1, 1), // Near - new Plane(0, 0, 1, 1)); // Far + new Plane(1, 0, 0, 1), // Left + new Plane(-1, 0, 0, 1), // Right + new Plane(0, 1, 0, 1), // Bottom + new Plane(0, -1, 0, 1), // Top + new Plane(0, 0, -1, 1), // Near + new Plane(0, 0, 1, 1)); // Far } /** @@ -43,19 +46,17 @@ public Frustum() *

        * None of the arguments may be null. * - * @param near the near plane - * @param far the far plane - * @param left the left plane - * @param right the right plane - * @param top the top plane + * @param near the near plane + * @param far the far plane + * @param left the left plane + * @param right the right plane + * @param top the top plane * @param bottom the bottom plane * * @throws IllegalArgumentException if any argument is null. */ - public Frustum(Plane left, Plane right, Plane bottom, Plane top, Plane near, Plane far) - { - if (left == null || right == null || bottom == null || top == null || near == null || far == null) - { + public Frustum(Plane left, Plane right, Plane bottom, Plane top, Plane near, Plane far) { + if (left == null || right == null || bottom == null || top == null || near == null || far == null) { String message = Logging.getMessage("nullValue.PlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -67,7 +68,7 @@ public Frustum(Plane left, Plane right, Plane bottom, Plane top, Plane near, Pla this.near = near; this.far = far; - this.allPlanes = new Plane[] {this.left, this.right, this.bottom, this.top, this.near, this.far}; + this.allPlanes = new Plane[]{this.left, this.right, this.bottom, this.top, this.near, this.far}; } /** @@ -75,8 +76,7 @@ public Frustum(Plane left, Plane right, Plane bottom, Plane top, Plane near, Pla * * @return the left plane. */ - public final Plane getLeft() - { + public final Plane getLeft() { return this.left; } @@ -85,8 +85,7 @@ public final Plane getLeft() * * @return the right plane. */ - public final Plane getRight() - { + public final Plane getRight() { return this.right; } @@ -95,8 +94,7 @@ public final Plane getRight() * * @return the bottom plane. */ - public final Plane getBottom() - { + public final Plane getBottom() { return this.bottom; } @@ -105,8 +103,7 @@ public final Plane getBottom() * * @return the top plane. */ - public final Plane getTop() - { + public final Plane getTop() { return this.top; } @@ -115,8 +112,7 @@ public final Plane getTop() * * @return the left plane. */ - public final Plane getNear() - { + public final Plane getNear() { return this.near; } @@ -125,8 +121,7 @@ public final Plane getNear() * * @return the left plane. */ - public final Plane getFar() - { + public final Plane getFar() { return this.far; } @@ -135,29 +130,28 @@ public final Plane getFar() * * @return an array of the frustum planes, in the order left, right, bottom, top, near, far. */ - public Plane[] getAllPlanes() - { + public Plane[] getAllPlanes() { return this.allPlanes; } - public boolean equals(Object obj) - { - if (this == obj) + public boolean equals(Object obj) { + if (this == obj) { return true; - if (obj == null || getClass() != obj.getClass()) + } + if (obj == null || getClass() != obj.getClass()) { return false; + } Frustum that = (Frustum) obj; return this.left.equals(that.left) - && this.right.equals(that.right) - && this.bottom.equals(that.bottom) - && this.top.equals(that.top) - && this.near.equals(that.near) - && this.far.equals(that.far); + && this.right.equals(that.right) + && this.bottom.equals(that.bottom) + && this.top.equals(that.top) + && this.near.equals(that.near) + && this.far.equals(that.far); } - public int hashCode() - { + public int hashCode() { int result; result = this.left.hashCode(); result = 31 * result + this.right.hashCode(); @@ -169,8 +163,7 @@ public int hashCode() return result; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append("left=").append(this.left); @@ -186,7 +179,6 @@ public String toString() // ============== Factory Functions ======================= // // ============== Factory Functions ======================= // // ============== Factory Functions ======================= // - /** * Creates a frustum by extracting the six frustum planes from a projection matrix. * @@ -196,12 +188,10 @@ public String toString() * * @throws IllegalArgumentException if the projection matrix is null. */ - public static Frustum fromProjectionMatrix(Matrix projectionMatrix) - { + public static Frustum fromProjectionMatrix(Matrix projectionMatrix) { //noinspection UnnecessaryLocalVariable Matrix m = projectionMatrix; - if (m == null) - { + if (m == null) { String message = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -264,21 +254,19 @@ public static Frustum fromProjectionMatrix(Matrix projectionMatrix) * positive. * * @param horizontalFieldOfView horizontal field-of-view angle in the range (0, 180) - * @param viewportWidth the width of the viewport in screen pixels - * @param viewportHeight the height of the viewport in screen pixels - * @param near distance to the near depth clipping plane - * @param far distance to far depth clipping plane + * @param viewportWidth the width of the viewport in screen pixels + * @param viewportHeight the height of the viewport in screen pixels + * @param near distance to the near depth clipping plane + * @param far distance to far depth clipping plane * * @return Frustum configured from the specified perspective parameters. * * @throws IllegalArgumentException if fov is not in the range (0, 180), if either near or far are negative, or near - * is greater than or equal to far + * is greater than or equal to far */ public static Frustum fromPerspective(Angle horizontalFieldOfView, int viewportWidth, int viewportHeight, - double near, double far) - { - if (horizontalFieldOfView == null) - { + double near, double far) { + if (horizontalFieldOfView == null) { String message = Logging.getMessage("Geom.ViewFrustum.FieldOfViewIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -286,12 +274,13 @@ public static Frustum fromPerspective(Angle horizontalFieldOfView, int viewportW double fov = horizontalFieldOfView.getDegrees(); double farMinusNear = far - near; String message = null; - if (fov <= 0 || fov > 180) + if (fov <= 0 || fov > 180) { message = Logging.getMessage("Geom.ViewFrustum.FieldOfViewOutOfRange", fov); - if (near <= 0 || farMinusNear <= 0) + } + if (near <= 0 || farMinusNear <= 0) { message = Logging.getMessage("Geom.ViewFrustum.ClippingDistanceOutOfRange"); - if (message != null) - { + } + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -313,21 +302,19 @@ public static Frustum fromPerspective(Angle horizontalFieldOfView, int viewportW * Creates a Frustum from three sets of parallel clipping planes (a parallel projectionMatrix). In this * case, the near and far depth clipping planes may be negative. * - * @param near distance to the near depth clipping plane - * @param far distance to far depth clipping plane - * @param width horizontal dimension of the near clipping plane + * @param near distance to the near depth clipping plane + * @param far distance to far depth clipping plane + * @param width horizontal dimension of the near clipping plane * @param height vertical dimension of the near clipping plane * * @return a Frustum configured with the specified perspective parameters. * * @throws IllegalArgumentException if the difference of any plane set (lright - left, top - bottom, far - near) is - * less than or equal to zero. + * less than or equal to zero. */ - public static Frustum fromPerspective(double width, double height, double near, double far) - { + public static Frustum fromPerspective(double width, double height, double near, double far) { double farMinusNear = far - near; - if (farMinusNear <= 0.0 || width <= 0.0 || height <= 0.0) - { + if (farMinusNear <= 0.0 || width <= 0.0 || height <= 0.0) { String message = Logging.getMessage("Geom.ViewFrustum.ClippingDistanceOutOfRange"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -349,31 +336,28 @@ public static Frustum fromPerspective(double width, double height, double near, * The edge vectors connect the near corners of the frustum to the far corners. The near plane must be closer than * the far plane, and both planes must be positive. * - * @param vTL vector defining the top-left of the frustum - * @param vTR vector defining the top-right of the frustum - * @param vBL vector defining the bottom-left of the frustum - * @param vBR vector defining the bottom-right of the frustum + * @param vTL vector defining the top-left of the frustum + * @param vTR vector defining the top-right of the frustum + * @param vBL vector defining the bottom-left of the frustum + * @param vBR vector defining the bottom-right of the frustum * @param near distance to the near plane - * @param far distance to far plane + * @param far distance to far plane * * @return Frustum that was created * * @throws IllegalArgumentException if any of the vectors are null, if either near or far are negative, or near is - * greater than or equal to far + * greater than or equal to far */ public static Frustum fromPerspectiveVecs(Vec4 vTL, Vec4 vTR, Vec4 vBL, Vec4 vBR, - double near, double far) - { - if (vTL == null || vTR == null || vBL == null || vBR == null) - { + double near, double far) { + if (vTL == null || vTR == null || vBL == null || vBR == null) { String message = Logging.getMessage("Geom.ViewFrustum.EdgeVectorIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } double farMinusNear = far - near; - if (near <= 0 || farMinusNear <= 0) - { + if (near <= 0 || farMinusNear <= 0) { String message = Logging.getMessage("Geom.ViewFrustum.ClippingDistanceOutOfRange"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -396,7 +380,6 @@ public static Frustum fromPerspectiveVecs(Vec4 vTL, Vec4 vTR, Vec4 vBL, Vec4 vBR // ============== Intersection Functions ======================= // // ============== Intersection Functions ======================= // // ============== Intersection Functions ======================= // - /** * Indicates whether a specified {@link Extent} intersects this frustum. * @@ -406,10 +389,8 @@ public static Frustum fromPerspectiveVecs(Vec4 vTL, Vec4 vTR, Vec4 vBL, Vec4 vBR * * @throws IllegalArgumentException if the extent is null. */ - public boolean intersects(Extent extent) - { - if (extent == null) - { + public boolean intersects(Extent extent) { + if (extent == null) { String msg = Logging.getMessage("nullValue.ExtentIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -428,31 +409,32 @@ public boolean intersects(Extent extent) * * @throws IllegalArgumentException if either point is null. */ - public boolean intersectsSegment(Vec4 pa, Vec4 pb) - { - if (pa == null || pb == null) - { + public boolean intersectsSegment(Vec4 pa, Vec4 pb) { + if (pa == null || pb == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // First do a trivial accept test. - if (this.contains(pa) || this.contains(pb)) + if (this.contains(pa) || this.contains(pb)) { return true; + } - if (pa.equals(pb)) + if (pa.equals(pb)) { return false; + } - for (Plane p : this.getAllPlanes()) - { + for (Plane p : this.getAllPlanes()) { // See if both points are behind the plane and therefore not in the frustum. - if (p.onSameSide(pa, pb) < 0) + if (p.onSameSide(pa, pb) < 0) { return false; + } // See if the segment intersects the plane. - if (p.clip(pa, pb) != null) + if (p.clip(pa, pb) != null) { return true; + } } return false; // segment does not intersect frustum @@ -467,12 +449,10 @@ public boolean intersectsSegment(Vec4 pa, Vec4 pb) * * @throws IllegalArgumentException if the extent is null. */ - public final boolean contains(Extent extent) - { + public final boolean contains(Extent extent) { // TODO: This method should be implemented in the concrete extent classes and those implementing methods // invoked here, as is done above for intersects(Frustum). - if (extent == null) - { + if (extent == null) { String msg = Logging.getMessage("nullValue.ExtentIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -482,23 +462,28 @@ public final boolean contains(Extent extent) // point with each plane's vector provides a distance to each plane. If this distance is less than the extent's // radius, some part of the extent is clipped by that plane and therefore is not completely contained in the // space enclosed by this Frustum. - Vec4 c = extent.getCenter(); double r = extent.getRadius(); - if (this.far.dot(c) <= r) + if (this.far.dot(c) <= r) { return false; - if (this.left.dot(c) <= r) + } + if (this.left.dot(c) <= r) { return false; - if (this.right.dot(c) <= r) + } + if (this.right.dot(c) <= r) { return false; - if (this.top.dot(c) <= r) + } + if (this.top.dot(c) <= r) { return false; - if (this.bottom.dot(c) <= r) + } + if (this.bottom.dot(c) <= r) { return false; + } //noinspection RedundantIfStatement - if (this.near.dot(c) <= r) + if (this.near.dot(c) <= r) { return false; + } return true; } @@ -512,10 +497,8 @@ public final boolean contains(Extent extent) * * @throws IllegalArgumentException if the point is null. */ - public final boolean contains(Vec4 point) - { - if (point == null) - { + public final boolean contains(Vec4 point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -524,20 +507,25 @@ public final boolean contains(Vec4 point) // See if the point is entirely within the frustum. The dot product of the point with each plane's vector // provides a distance to each plane. If this distance is less than 0, the point is clipped by that plane and // neither intersects nor is contained by the space enclosed by this Frustum. - - if (this.far.dot(point) <= 0) + if (this.far.dot(point) <= 0) { return false; - if (this.left.dot(point) <= 0) + } + if (this.left.dot(point) <= 0) { return false; - if (this.right.dot(point) <= 0) + } + if (this.right.dot(point) <= 0) { return false; - if (this.top.dot(point) <= 0) + } + if (this.top.dot(point) <= 0) { return false; - if (this.bottom.dot(point) <= 0) + } + if (this.bottom.dot(point) <= 0) { return false; + } //noinspection RedundantIfStatement - if (this.near.dot(point) <= 0) + if (this.near.dot(point) <= 0) { return false; + } return true; } @@ -545,7 +533,6 @@ public final boolean contains(Vec4 point) // ============== Geometric Functions ======================= // // ============== Geometric Functions ======================= // // ============== Geometric Functions ======================= // - /** * Returns a copy of this frustum transformed by a specified {@link Matrix}. * @@ -555,10 +542,8 @@ public final boolean contains(Vec4 point) * * @throws IllegalArgumentException if the matrix is null. */ - public Frustum transformBy(Matrix matrix) - { - if (matrix == null) - { + public Frustum transformBy(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -573,9 +558,11 @@ public Frustum transformBy(Matrix matrix) return new Frustum(left, right, bottom, top, near, far); } - /** Holds the eight corner points of a frustum. */ - public static class Corners - { + /** + * Holds the eight corner points of a frustum. + */ + public static class Corners { + public Vec4 nbl, nbr, ntl, ntr, fbl, fbr, ftl, ftr; } @@ -584,8 +571,7 @@ public static class Corners * * @return the eight frustum corners. */ - public Corners getCorners() - { + public Corners getCorners() { Corners corners = new Corners(); corners.nbl = Plane.intersect(this.near, this.bottom, this.left); diff --git a/src/gov/nasa/worldwind/geom/GeoQuad.java b/src/gov/nasa/worldwind/geom/GeoQuad.java index b5d1453464..0eb851d3fa 100644 --- a/src/gov/nasa/worldwind/geom/GeoQuad.java +++ b/src/gov/nasa/worldwind/geom/GeoQuad.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.geom; import gov.nasa.worldwind.util.Logging; @@ -15,8 +14,8 @@ * @author tag * @version $Id: GeoQuad.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeoQuad -{ +public class GeoQuad { + public static final int NORTH = 1; public static final int SOUTH = 2; public static final int EAST = 4; @@ -29,10 +28,8 @@ public class GeoQuad private final LatLon sw, se, ne, nw; private final Line northEdge, southEdge, eastEdge, westEdge; - public GeoQuad(List corners) - { - if (corners == null) - { + public GeoQuad(List corners) { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -41,21 +38,19 @@ public GeoQuad(List corners) // Count the corners and check for nulls Iterator iter = corners.iterator(); int numCorners = 0; - for (LatLon c : corners) - { - if (c == null) - { + for (LatLon c : corners) { + if (c == null) { String message = Logging.getMessage("nullValue.LocationInListIsNull"); Logging.logger().log(Level.SEVERE, message); throw new IllegalArgumentException(message); } - if (++numCorners > 3) + if (++numCorners > 3) { break; + } } - if (numCorners < 4) - { + if (numCorners < 4) { String message = Logging.getMessage("nullValue.LocationInListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -67,85 +62,72 @@ public GeoQuad(List corners) this.nw = iter.next(); this.northEdge = Line.fromSegment( - new Vec4(this.nw.getLongitude().degrees, this.nw.getLatitude().degrees, 0), - new Vec4(this.ne.getLongitude().degrees, this.ne.getLatitude().degrees, 0)); + new Vec4(this.nw.getLongitude().degrees, this.nw.getLatitude().degrees, 0), + new Vec4(this.ne.getLongitude().degrees, this.ne.getLatitude().degrees, 0)); this.southEdge = Line.fromSegment( - new Vec4(this.sw.getLongitude().degrees, this.sw.getLatitude().degrees, 0), - new Vec4(this.se.getLongitude().degrees, this.se.getLatitude().degrees, 0)); + new Vec4(this.sw.getLongitude().degrees, this.sw.getLatitude().degrees, 0), + new Vec4(this.se.getLongitude().degrees, this.se.getLatitude().degrees, 0)); this.eastEdge = Line.fromSegment( - new Vec4(this.se.getLongitude().degrees, this.se.getLatitude().degrees, 0), - new Vec4(this.ne.getLongitude().degrees, this.ne.getLatitude().degrees, 0)); + new Vec4(this.se.getLongitude().degrees, this.se.getLatitude().degrees, 0), + new Vec4(this.ne.getLongitude().degrees, this.ne.getLatitude().degrees, 0)); this.westEdge = Line.fromSegment( - new Vec4(this.sw.getLongitude().degrees, this.sw.getLatitude().degrees, 0), - new Vec4(this.nw.getLongitude().degrees, this.nw.getLatitude().degrees, 0)); + new Vec4(this.sw.getLongitude().degrees, this.sw.getLatitude().degrees, 0), + new Vec4(this.nw.getLongitude().degrees, this.nw.getLatitude().degrees, 0)); } - public LatLon getSw() - { + public LatLon getSw() { return sw; } - public LatLon getSe() - { + public LatLon getSe() { return se; } - public LatLon getNe() - { + public LatLon getNe() { return ne; } - public LatLon getNw() - { + public LatLon getNw() { return nw; } - public Angle distanceToNW(LatLon p) - { + public Angle distanceToNW(LatLon p) { return LatLon.rhumbDistance(this.nw, p); } - public Angle distanceToNE(LatLon p) - { + public Angle distanceToNE(LatLon p) { return LatLon.rhumbDistance(this.ne, p); } - public Angle distanceToSW(LatLon p) - { + public Angle distanceToSW(LatLon p) { return LatLon.rhumbDistance(this.sw, p); } - public Angle distanceToSE(LatLon p) - { + public Angle distanceToSE(LatLon p) { return LatLon.rhumbDistance(this.se, p); } - public Angle distanceToNorthEdge(LatLon p) - { + public Angle distanceToNorthEdge(LatLon p) { return Angle.fromDegrees( - this.northEdge.distanceTo(new Vec4(p.getLongitude().degrees, p.getLatitude().degrees, 0))); + this.northEdge.distanceTo(new Vec4(p.getLongitude().degrees, p.getLatitude().degrees, 0))); } - public Angle distanceToSouthEdge(LatLon p) - { + public Angle distanceToSouthEdge(LatLon p) { return Angle.fromDegrees( - this.southEdge.distanceTo(new Vec4(p.getLongitude().degrees, p.getLatitude().degrees, 0))); + this.southEdge.distanceTo(new Vec4(p.getLongitude().degrees, p.getLatitude().degrees, 0))); } - public Angle distanceToEastEdge(LatLon p) - { + public Angle distanceToEastEdge(LatLon p) { return Angle.fromDegrees( - this.eastEdge.distanceTo(new Vec4(p.getLongitude().degrees, p.getLatitude().degrees, 0))); + this.eastEdge.distanceTo(new Vec4(p.getLongitude().degrees, p.getLatitude().degrees, 0))); } - public Angle distanceToWestEdge(LatLon p) - { + public Angle distanceToWestEdge(LatLon p) { return Angle.fromDegrees( - this.westEdge.distanceTo(new Vec4(p.getLongitude().degrees, p.getLatitude().degrees, 0))); + this.westEdge.distanceTo(new Vec4(p.getLongitude().degrees, p.getLatitude().degrees, 0))); } - public LatLon interpolate(double t, double s) - { + public LatLon interpolate(double t, double s) { Vec4 top = this.northEdge.getPointAt(s); Vec4 bot = this.southEdge.getPointAt(s); Line topToBot = Line.fromSegment(bot, top); diff --git a/src/gov/nasa/worldwind/geom/Intersection.java b/src/gov/nasa/worldwind/geom/Intersection.java index 6f9f4d1c94..c97fa61210 100644 --- a/src/gov/nasa/worldwind/geom/Intersection.java +++ b/src/gov/nasa/worldwind/geom/Intersection.java @@ -15,6 +15,7 @@ */ public final class Intersection // Instances are immutable { + protected Vec4 intersectionPoint; protected Double intersectionLength; protected Position intersectionPosition; @@ -25,14 +26,12 @@ public final class Intersection // Instances are immutable * Constructs an Intersection from an intersection point and tangency indicator. * * @param intersectionPoint the intersection point. - * @param isTangent true if the intersection is tangent to the object intersected, otherwise false. + * @param isTangent true if the intersection is tangent to the object intersected, otherwise false. * * @throws IllegalArgumentException if intersectionPoint is null */ - public Intersection(Vec4 intersectionPoint, boolean isTangent) - { - if (intersectionPoint == null) - { + public Intersection(Vec4 intersectionPoint, boolean isTangent) { + if (intersectionPoint == null) { String message = Logging.getMessage("nullValue.IntersectionPointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -44,24 +43,21 @@ public Intersection(Vec4 intersectionPoint, boolean isTangent) /** * Constructs an Intersection from an intersection point and tangency indicator. * - * @param intersectionPoint the intersection point + * @param intersectionPoint the intersection point * @param intersectionLength the parametric length along the intersection geometry. If the geometry was a line, then - * this value will be the parametric value of the intersection point along the line. - * @param isTangent true if the intersection is tangent to the object intersected, otherwise false. + * this value will be the parametric value of the intersection point along the line. + * @param isTangent true if the intersection is tangent to the object intersected, otherwise false. * * @throws IllegalArgumentException if intersectionPoint is null */ - public Intersection(Vec4 intersectionPoint, double intersectionLength, boolean isTangent) - { + public Intersection(Vec4 intersectionPoint, double intersectionLength, boolean isTangent) { this(intersectionPoint, isTangent); this.intersectionLength = intersectionLength; } - public Intersection(Vec4 intersectionPoint, Position intersectionPosition, boolean isTangent, Object object) - { - if (intersectionPoint == null) - { + public Intersection(Vec4 intersectionPoint, Position intersectionPosition, boolean isTangent, Object object) { + if (intersectionPoint == null) { String message = Logging.getMessage("nullValue.IntersectionPointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -78,8 +74,7 @@ public Intersection(Vec4 intersectionPoint, Position intersectionPosition, boole * * @return the intersection position, or null if the position has not been set. */ - public Position getIntersectionPosition() - { + public Position getIntersectionPosition() { return intersectionPosition; } @@ -88,8 +83,7 @@ public Position getIntersectionPosition() * * @param intersectionPosition the intersection position. May be null. */ - public void setIntersectionPosition(Position intersectionPosition) - { + public void setIntersectionPosition(Position intersectionPosition) { this.intersectionPosition = intersectionPosition; } @@ -98,8 +92,7 @@ public void setIntersectionPosition(Position intersectionPosition) * * @return the object associated with the intersection, or null if no object is associated. */ - public Object getObject() - { + public Object getObject() { return object; } @@ -108,8 +101,7 @@ public Object getObject() * * @param object the object to associate with the intersection. May be null. */ - public void setObject(Object object) - { + public void setObject(Object object) { this.object = object; } @@ -118,8 +110,7 @@ public void setObject(Object object) * * @return the intersection point. */ - public Vec4 getIntersectionPoint() - { + public Vec4 getIntersectionPoint() { return intersectionPoint; } @@ -128,8 +119,7 @@ public Vec4 getIntersectionPoint() * * @param intersectionPoint the intersection point. May be null, but typically should not be. */ - public void setIntersectionPoint(Vec4 intersectionPoint) - { + public void setIntersectionPoint(Vec4 intersectionPoint) { this.intersectionPoint = intersectionPoint; } @@ -138,8 +128,7 @@ public void setIntersectionPoint(Vec4 intersectionPoint) * * @return true if the intersection is tangent, otherwise false. */ - public boolean isTangent() - { + public boolean isTangent() { return isTangent; } @@ -148,8 +137,7 @@ public boolean isTangent() * * @param tangent true if the intersection is tangent, otherwise false. */ - public void setTangent(boolean tangent) - { + public void setTangent(boolean tangent) { isTangent = tangent; } @@ -159,8 +147,7 @@ public void setTangent(boolean tangent) * * @return the intersection length, or null if the length was not calculated. */ - public Double getIntersectionLength() - { + public Double getIntersectionLength() { return intersectionLength; } @@ -169,19 +156,17 @@ public Double getIntersectionLength() * point. * * @param refPoint the reference point. - * @param listA the first list of intersections. - * @param listB the second list of intersections. + * @param listA the first list of intersections. + * @param listB the second list of intersections. * * @return the merged list of intersections, sorted by increasing distance from the reference point. */ - public static Queue sort(final Vec4 refPoint, List listA, List listB) - { - PriorityQueue sorted = new PriorityQueue(10, new Comparator() - { - public int compare(Intersection losiA, Intersection losiB) - { - if (losiA.intersectionPoint == null || losiB.intersectionPoint == null) + public static Queue sort(final Vec4 refPoint, List listA, List listB) { + PriorityQueue sorted = new PriorityQueue(10, new Comparator() { + public int compare(Intersection losiA, Intersection losiB) { + if (losiA.intersectionPoint == null || losiB.intersectionPoint == null) { return 0; + } double dA = refPoint.distanceTo3(losiA.intersectionPoint); double dB = refPoint.distanceTo3(losiB.intersectionPoint); @@ -190,18 +175,14 @@ public int compare(Intersection losiA, Intersection losiB) } }); - if (listA != null) - { - for (Intersection intersection : listA) - { + if (listA != null) { + for (Intersection intersection : listA) { sorted.add(intersection); } } - if (listB != null) - { - for (Intersection intersection : listB) - { + if (listB != null) { + for (Intersection intersection : listB) { sorted.add(intersection); } } @@ -210,27 +191,29 @@ public int compare(Intersection losiA, Intersection losiB) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final gov.nasa.worldwind.geom.Intersection that = (gov.nasa.worldwind.geom.Intersection) o; - if (isTangent != that.isTangent) + if (isTangent != that.isTangent) { return false; + } //noinspection RedundantIfStatement - if (!intersectionPoint.equals(that.intersectionPoint)) + if (!intersectionPoint.equals(that.intersectionPoint)) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; result = intersectionPoint.hashCode(); result = 29 * result + (isTangent ? 1 : 0); @@ -238,8 +221,7 @@ public int hashCode() } @Override - public String toString() - { + public String toString() { String pt = "Intersection Point: " + this.intersectionPoint; String tang = this.isTangent ? " is a tangent." : " not a tangent"; return pt + tang; diff --git a/src/gov/nasa/worldwind/geom/LatLon.java b/src/gov/nasa/worldwind/geom/LatLon.java index 37020c156c..fb29982160 100644 --- a/src/gov/nasa/worldwind/geom/LatLon.java +++ b/src/gov/nasa/worldwind/geom/LatLon.java @@ -20,13 +20,12 @@ * @author Tom Gaskins * @version $Id: LatLon.java 3427 2015-09-30 23:24:13Z dcollins $ */ -public class LatLon -{ +public class LatLon { + public static final LatLon ZERO = new LatLon(Angle.ZERO, Angle.ZERO); /** - * A near zero threshold used in some of the rhumb line calculations where floating point calculations cause - * errors. + * A near zero threshold used in some of the rhumb line calculations where floating point calculations cause errors. */ protected final static double NEAR_ZERO_THRESHOLD = 1e-15; @@ -36,31 +35,28 @@ public class LatLon /** * Factor method for obtaining a new LatLon from two angles expressed in radians. * - * @param latitude in radians + * @param latitude in radians * @param longitude in radians * * @return a new LatLon from the given angles, which are expressed as radians */ - public static LatLon fromRadians(double latitude, double longitude) - { + public static LatLon fromRadians(double latitude, double longitude) { return new LatLon(Math.toDegrees(latitude), Math.toDegrees(longitude)); } /** * Factory method for obtaining a new LatLon from two angles expressed in degrees. * - * @param latitude in degrees + * @param latitude in degrees * @param longitude in degrees * * @return a new LatLon from the given angles, which are expressed as degrees */ - public static LatLon fromDegrees(double latitude, double longitude) - { + public static LatLon fromDegrees(double latitude, double longitude) { return new LatLon(latitude, longitude); } - private LatLon(double latitude, double longitude) - { + private LatLon(double latitude, double longitude) { this.latitude = Angle.fromDegrees(latitude); this.longitude = Angle.fromDegrees(longitude); } @@ -68,15 +64,13 @@ private LatLon(double latitude, double longitude) /** * Constructs a new LatLon from two angles. Neither angle may be null. * - * @param latitude latitude + * @param latitude latitude * @param longitude longitude * * @throws IllegalArgumentException if latitude or longitude is null */ - public LatLon(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public LatLon(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -86,10 +80,8 @@ public LatLon(Angle latitude, Angle longitude) this.longitude = longitude; } - public LatLon(LatLon latLon) - { - if (latLon == null) - { + public LatLon(LatLon latLon) { + if (latLon == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -104,8 +96,7 @@ public LatLon(LatLon latLon) * * @return this LatLon's latitude */ - public final Angle getLatitude() - { + public final Angle getLatitude() { return this.latitude; } @@ -114,8 +105,7 @@ public final Angle getLatitude() * * @return this LatLon's longitude */ - public final Angle getLongitude() - { + public final Angle getLongitude() { return this.longitude; } @@ -124,9 +114,8 @@ public final Angle getLongitude() * * @return the array of latitude and longitude, arranged in that order. */ - public double[] asDegreesArray() - { - return new double[] {this.getLatitude().degrees, this.getLongitude().degrees}; + public double[] asDegreesArray() { + return new double[]{this.getLatitude().degrees, this.getLongitude().degrees}; } /** @@ -134,9 +123,8 @@ public double[] asDegreesArray() * * @return the array of latitude and longitude, arranged in that order. */ - public double[] asRadiansArray() - { - return new double[] {this.getLatitude().radians, this.getLongitude().radians}; + public double[] asRadiansArray() { + return new double[]{this.getLatitude().radians, this.getLongitude().radians}; } /** @@ -148,40 +136,33 @@ public double[] asRadiansArray() * linear interpolation of the two locations (see {@link #interpolate(double, LatLon, LatLon)}. * * @param pathType the path type used to interpolate between geographic locations. - * @param amount the interpolation factor - * @param value1 the first location. - * @param value2 the second location. + * @param amount the interpolation factor + * @param value1 the first location. + * @param value2 the second location. * * @return an interpolated location between value1 and value2, according to the specified * path type. * * @throws IllegalArgumentException if the path type or either location is null. */ - public static LatLon interpolate(String pathType, double amount, LatLon value1, LatLon value2) - { - if (pathType == null) - { + public static LatLon interpolate(String pathType, double amount, LatLon value1, LatLon value2) { + if (pathType == null) { String message = Logging.getMessage("nullValue.PathTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (value1 == null || value2 == null) - { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pathType.equals(AVKey.GREAT_CIRCLE)) - { + if (pathType.equals(AVKey.GREAT_CIRCLE)) { return interpolateGreatCircle(amount, value1, value2); - } - else if (pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME)) - { + } else if (pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME)) { return interpolateRhumb(amount, value1, value2); - } - else // Default to linear interpolation. + } else // Default to linear interpolation. { return interpolate(amount, value1, value2); } @@ -199,27 +180,23 @@ else if (pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME)) * * @throws IllegalArgumentException if either location is null. */ - public static LatLon interpolate(double amount, LatLon value1, LatLon value2) - { - if (value1 == null || value2 == null) - { + public static LatLon interpolate(double amount, LatLon value1, LatLon value2) { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (LatLon.equals(value1, value2)) + if (LatLon.equals(value1, value2)) { return value1; + } Line line; - try - { + try { line = Line.fromSegment( - new Vec4(value1.getLongitude().radians, value1.getLatitude().radians, 0), - new Vec4(value2.getLongitude().radians, value2.getLatitude().radians, 0)); - } - catch (IllegalArgumentException e) - { + new Vec4(value1.getLongitude().radians, value1.getLatitude().radians, 0), + new Vec4(value2.getLongitude().radians, value2.getLatitude().radians, 0)); + } catch (IllegalArgumentException e) { // Locations became coincident after calculations. return value1; } @@ -234,8 +211,8 @@ public static LatLon interpolate(double amount, LatLon value1, LatLon value2) * interpolation factor amount defines the weight given to each value, and is clamped to the range [0, * 1]. If a is 0 or less, this returns value1. If amount is 1 or more, this * returns value2. Otherwise, this returns the location on the great-arc between value1 - * and value2 corresponding to the specified interpolation factor. - * This method uses a spherical model, not elliptical. + * and value2 corresponding to the specified interpolation factor. This method uses a spherical model, + * not elliptical. * * @param amount the interpolation factor * @param value1 the first location. @@ -245,17 +222,16 @@ public static LatLon interpolate(double amount, LatLon value1, LatLon value2) * * @throws IllegalArgumentException if either location is null. */ - public static LatLon interpolateGreatCircle(double amount, LatLon value1, LatLon value2) - { - if (value1 == null || value2 == null) - { + public static LatLon interpolateGreatCircle(double amount, LatLon value1, LatLon value2) { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (LatLon.equals(value1, value2)) + if (LatLon.equals(value1, value2)) { return value1; + } double t = WWMath.clamp(amount, 0d, 1d); Angle azimuth = LatLon.greatCircleAzimuth(value1, value2); @@ -270,8 +246,8 @@ public static LatLon interpolateGreatCircle(double amount, LatLon value1, LatLon * The interpolation factor amount defines the weight given to each value, and is clamped to the range * [0, 1]. If a is 0 or less, this returns value1. If amount is 1 or more, * this returns value2. Otherwise, this returns the location on the rhumb line between - * value1 and value2 corresponding to the specified interpolation factor. - * This method uses a spherical model, not elliptical. + * value1 and value2 corresponding to the specified interpolation factor. This method uses + * a spherical model, not elliptical. * * @param amount the interpolation factor * @param value1 the first location. @@ -281,17 +257,16 @@ public static LatLon interpolateGreatCircle(double amount, LatLon value1, LatLon * * @throws IllegalArgumentException if either location is null. */ - public static LatLon interpolateRhumb(double amount, LatLon value1, LatLon value2) - { - if (value1 == null || value2 == null) - { + public static LatLon interpolateRhumb(double amount, LatLon value1, LatLon value2) { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (LatLon.equals(value1, value2)) + if (LatLon.equals(value1, value2)) { return value1; + } double t = WWMath.clamp(amount, 0d, 1d); Angle azimuth = LatLon.rhumbAzimuth(value1, value2); @@ -310,39 +285,32 @@ public static LatLon interpolateRhumb(double amount, LatLon value1, LatLon value * {@link #linearDistance(LatLon, LatLon)}). * * @param pathType the path type used to interpolate between geographic locations. - * @param value1 the first location. - * @param value2 the second location. + * @param value1 the first location. + * @param value2 the second location. * * @return an length of the path between value1 and value2, according to the specified * path type. * * @throws IllegalArgumentException if the path type or either location is null. */ - public static Angle pathDistance(String pathType, LatLon value1, LatLon value2) - { - if (pathType == null) - { + public static Angle pathDistance(String pathType, LatLon value1, LatLon value2) { + if (pathType == null) { String message = Logging.getMessage("nullValue.PathTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (value1 == null || value2 == null) - { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pathType.equals(AVKey.GREAT_CIRCLE)) - { + if (pathType.equals(AVKey.GREAT_CIRCLE)) { return greatCircleDistance(value1, value2); - } - else if (pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME)) - { + } else if (pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME)) { return rhumbDistance(value1, value2); - } - else // Default to linear interpolation. + } else // Default to linear interpolation. { return linearDistance(value1, value2); } @@ -352,8 +320,7 @@ else if (pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME)) * Computes the great circle angular distance between two locations. The return value gives the distance as the * angle between the two positions on the pi radius circle. In radians, this angle is also the arc length of the * segment between the two positions on that circle. To compute a distance in meters from this value, multiply it by - * the radius of the globe. - * This method uses a spherical model, not elliptical. + * the radius of the globe. This method uses a spherical model, not elliptical. * * @param p1 LatLon of the first location * @param p2 LatLon of the second location @@ -361,10 +328,8 @@ else if (pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME)) * @return the angular distance between the two locations. In radians, this value is the arc length on the radius pi * circle. */ - public static Angle greatCircleDistance(LatLon p1, LatLon p2) - { - if ((p1 == null) || (p2 == null)) - { + public static Angle greatCircleDistance(LatLon p1, LatLon p2) { + if ((p1 == null) || (p2 == null)) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -375,8 +340,9 @@ public static Angle greatCircleDistance(LatLon p1, LatLon p2) double lat2 = p2.getLatitude().radians; double lon2 = p2.getLongitude().radians; - if (lat1 == lat2 && lon1 == lon2) + if (lat1 == lat2 && lon1 == lon2) { return Angle.ZERO; + } // "Haversine formula," taken from http://en.wikipedia.org/wiki/Great-circle_distance#Formul.C3.A6 double a = Math.sin((lat2 - lat1) / 2.0); @@ -390,18 +356,15 @@ public static Angle greatCircleDistance(LatLon p1, LatLon p2) /** * Computes the azimuth angle (clockwise from North) that points from the first location to the second location. * This angle can be used as the starting azimuth for a great circle arc that begins at the first location, and - * passes through the second location. - * This method uses a spherical model, not elliptical. + * passes through the second location. This method uses a spherical model, not elliptical. * * @param p1 LatLon of the first location * @param p2 LatLon of the second location * * @return Angle that points from the first location to the second location. */ - public static Angle greatCircleAzimuth(LatLon p1, LatLon p2) - { - if ((p1 == null) || (p2 == null)) - { + public static Angle greatCircleAzimuth(LatLon p1, LatLon p2) { + if ((p1 == null) || (p2 == null)) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -412,11 +375,13 @@ public static Angle greatCircleAzimuth(LatLon p1, LatLon p2) double lat2 = p2.getLatitude().radians; double lon2 = p2.getLongitude().radians; - if (lat1 == lat2 && lon1 == lon2) + if (lat1 == lat2 && lon1 == lon2) { return Angle.ZERO; + } - if (lon1 == lon2) + if (lon1 == lon2) { return lat1 > lat2 ? Angle.POS180 : Angle.ZERO; + } // Taken from "Map Projections - A Working Manual", page 30, equation 5-4b. // The atan2() function is used in place of the traditional atan(y/x) to simplify the case when x==0. @@ -428,25 +393,22 @@ public static Angle greatCircleAzimuth(LatLon p1, LatLon p2) } /** - * Computes the location on a great circle arc with the given starting location, azimuth, and arc distance. - * This method uses a spherical model, not elliptical. + * Computes the location on a great circle arc with the given starting location, azimuth, and arc distance. This + * method uses a spherical model, not elliptical. * - * @param p LatLon of the starting location + * @param p LatLon of the starting location * @param greatCircleAzimuth great circle azimuth angle (clockwise from North) - * @param pathLength arc distance to travel + * @param pathLength arc distance to travel * * @return LatLon location on the great circle arc. */ - public static LatLon greatCircleEndPosition(LatLon p, Angle greatCircleAzimuth, Angle pathLength) - { - if (p == null) - { + public static LatLon greatCircleEndPosition(LatLon p, Angle greatCircleAzimuth, Angle pathLength) { + if (p == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (greatCircleAzimuth == null || pathLength == null) - { + if (greatCircleAzimuth == null || pathLength == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -457,70 +419,66 @@ public static LatLon greatCircleEndPosition(LatLon p, Angle greatCircleAzimuth, double azimuth = greatCircleAzimuth.radians; double distance = pathLength.radians; - if (distance == 0) + if (distance == 0) { return p; + } // Taken from "Map Projections - A Working Manual", page 31, equation 5-5 and 5-6. double endLatRadians = Math.asin(Math.sin(lat) * Math.cos(distance) - + Math.cos(lat) * Math.sin(distance) * Math.cos(azimuth)); + + Math.cos(lat) * Math.sin(distance) * Math.cos(azimuth)); double endLonRadians = lon + Math.atan2( - Math.sin(distance) * Math.sin(azimuth), - Math.cos(lat) * Math.cos(distance) - Math.sin(lat) * Math.sin(distance) * Math.cos(azimuth)); + Math.sin(distance) * Math.sin(azimuth), + Math.cos(lat) * Math.cos(distance) - Math.sin(lat) * Math.sin(distance) * Math.cos(azimuth)); - if (Double.isNaN(endLatRadians) || Double.isNaN(endLonRadians)) + if (Double.isNaN(endLatRadians) || Double.isNaN(endLonRadians)) { return p; + } return new LatLon( - Angle.fromRadians(endLatRadians).normalizedLatitude(), - Angle.fromRadians(endLonRadians).normalizedLongitude()); + Angle.fromRadians(endLatRadians).normalizedLatitude(), + Angle.fromRadians(endLonRadians).normalizedLongitude()); } /** - * Computes the location on a great circle arc with the given starting location, azimuth, and arc distance. - * This method uses a spherical model, not elliptical. + * Computes the location on a great circle arc with the given starting location, azimuth, and arc distance. This + * method uses a spherical model, not elliptical. * - * @param p LatLon of the starting location + * @param p LatLon of the starting location * @param greatCircleAzimuthRadians great circle azimuth angle (clockwise from North), in radians - * @param pathLengthRadians arc distance to travel, in radians + * @param pathLengthRadians arc distance to travel, in radians * * @return LatLon location on the great circle arc. */ - public static LatLon greatCircleEndPosition(LatLon p, double greatCircleAzimuthRadians, double pathLengthRadians) - { - if (p == null) - { + public static LatLon greatCircleEndPosition(LatLon p, double greatCircleAzimuthRadians, double pathLengthRadians) { + if (p == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return greatCircleEndPosition(p, - Angle.fromRadians(greatCircleAzimuthRadians), Angle.fromRadians(pathLengthRadians)); + Angle.fromRadians(greatCircleAzimuthRadians), Angle.fromRadians(pathLengthRadians)); } /** * Returns two locations with the most extreme latitudes on the great circle with the given starting location and - * azimuth. - * This method uses a spherical model, not elliptical. + * azimuth. This method uses a spherical model, not elliptical. * * @param location location on the great circle. - * @param azimuth great circle azimuth angle (clockwise from North). + * @param azimuth great circle azimuth angle (clockwise from North). * * @return two locations where the great circle has its extreme latitudes. * * @throws IllegalArgumentException if either location or azimuth are null. */ - public static LatLon[] greatCircleExtremeLocations(LatLon location, Angle azimuth) - { - if (location == null) - { + public static LatLon[] greatCircleExtremeLocations(LatLon location, Angle azimuth) { + if (location == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (azimuth == null) - { + if (azimuth == null) { String message = Logging.getMessage("nullValue.AzimuthIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -548,43 +506,37 @@ public static LatLon[] greatCircleExtremeLocations(LatLon location, Angle azimut // // d1 = c + 90 // d2 = c - 90 - double tanDistance = -Math.tan(lat0) / Math.cos(az); double distance = Math.atan(tanDistance); Angle extremeDistance1 = Angle.fromRadians(distance + (Math.PI / 2.0)); Angle extremeDistance2 = Angle.fromRadians(distance - (Math.PI / 2.0)); - return new LatLon[] - { - greatCircleEndPosition(location, azimuth, extremeDistance1), - greatCircleEndPosition(location, azimuth, extremeDistance2) - }; + return new LatLon[]{ + greatCircleEndPosition(location, azimuth, extremeDistance1), + greatCircleEndPosition(location, azimuth, extremeDistance2) + }; } /** * Returns two locations with the most extreme latitudes on the great circle arc defined by, and limited to, the two - * locations. - * This method uses a spherical model, not elliptical. + * locations. This method uses a spherical model, not elliptical. * * @param begin beginning location on the great circle arc. - * @param end ending location on the great circle arc. + * @param end ending location on the great circle arc. * * @return two locations with the most extreme latitudes on the great circle arc. * * @throws IllegalArgumentException if either begin or end are null. */ - public static LatLon[] greatCircleArcExtremeLocations(LatLon begin, LatLon end) - { - if (begin == null) - { + public static LatLon[] greatCircleArcExtremeLocations(LatLon begin, LatLon end) { + if (begin == null) { String message = Logging.getMessage("nullValue.BeginIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (end == null) - { + if (end == null) { String message = Logging.getMessage("nullValue.EndIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -596,15 +548,12 @@ public static LatLon[] greatCircleArcExtremeLocations(LatLon begin, LatLon end) double maxLat = Angle.NEG90.degrees; // Compute the min and max latitude and associated locations from the arc endpoints. - for (LatLon ll : java.util.Arrays.asList(begin, end)) - { - if (minLat >= ll.getLatitude().degrees) - { + for (LatLon ll : java.util.Arrays.asList(begin, end)) { + if (minLat >= ll.getLatitude().degrees) { minLat = ll.getLatitude().degrees; minLatLocation = ll; } - if (maxLat <= ll.getLatitude().degrees) - { + if (maxLat <= ll.getLatitude().degrees) { maxLat = ll.getLatitude().degrees; maxLatLocation = ll; } @@ -618,25 +567,20 @@ public static LatLon[] greatCircleArcExtremeLocations(LatLon begin, LatLon end) // Determine whether either of the extreme locations are inside the arc defined by begin and end. If so, // adjust the min and max latitude accordingly. - for (LatLon ll : greatCircleExtremes) - { + for (LatLon ll : greatCircleExtremes) { Angle az = LatLon.greatCircleAzimuth(begin, ll); Angle d = LatLon.greatCircleDistance(begin, ll); // The extreme location must be between the begin and end locations. Therefore its azimuth relative to // the begin location should have the same signum, and its distance relative to the begin location should // be between 0 and greatArcDistance, inclusive. - if (Math.signum(az.degrees) == Math.signum(greatArcAzimuth.degrees)) - { - if (d.degrees >= 0 && d.degrees <= greatArcDistance.degrees) - { - if (minLat >= ll.getLatitude().degrees) - { + if (Math.signum(az.degrees) == Math.signum(greatArcAzimuth.degrees)) { + if (d.degrees >= 0 && d.degrees <= greatArcDistance.degrees) { + if (minLat >= ll.getLatitude().degrees) { minLat = ll.getLatitude().degrees; minLatLocation = ll; } - if (maxLat <= ll.getLatitude().degrees) - { + if (maxLat <= ll.getLatitude().degrees) { maxLat = ll.getLatitude().degrees; maxLatLocation = ll; } @@ -644,13 +588,12 @@ public static LatLon[] greatCircleArcExtremeLocations(LatLon begin, LatLon end) } } - return new LatLon[] {minLatLocation, maxLatLocation}; + return new LatLon[]{minLatLocation, maxLatLocation}; } /** * Returns two locations with the most extreme latitudes on the sequence of great circle arcs defined by each pair - * of locations in the specified iterable. - * This method uses a spherical model, not elliptical. + * of locations in the specified iterable. This method uses a spherical model, not elliptical. * * @param locations the pairs of locations defining a sequence of great circle arcs. * @@ -658,10 +601,8 @@ public static LatLon[] greatCircleArcExtremeLocations(LatLon begin, LatLon end) * * @throws IllegalArgumentException if locations is null. */ - public static LatLon[] greatCircleArcExtremeLocations(Iterable locations) - { - if (locations == null) - { + public static LatLon[] greatCircleArcExtremeLocations(Iterable locations) { + if (locations == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -672,32 +613,32 @@ public static LatLon[] greatCircleArcExtremeLocations(Iterable LatLon lastLocation = null; - for (LatLon ll : locations) - { - if (lastLocation != null) - { + for (LatLon ll : locations) { + if (lastLocation != null) { LatLon[] extremes = LatLon.greatCircleArcExtremeLocations(lastLocation, ll); - if (extremes == null) + if (extremes == null) { continue; + } - if (minLatLocation == null || minLatLocation.getLatitude().degrees > extremes[0].getLatitude().degrees) + if (minLatLocation == null || minLatLocation.getLatitude().degrees > extremes[0].getLatitude().degrees) { minLatLocation = extremes[0]; - if (maxLatLocation == null || maxLatLocation.getLatitude().degrees < extremes[1].getLatitude().degrees) + } + if (maxLatLocation == null || maxLatLocation.getLatitude().degrees < extremes[1].getLatitude().degrees) { maxLatLocation = extremes[1]; + } } lastLocation = ll; } - return new LatLon[] {minLatLocation, maxLatLocation}; + return new LatLon[]{minLatLocation, maxLatLocation}; } /** * Computes the length of the rhumb line between two locations. The return value gives the distance as the angular * distance between the two positions on the pi radius circle. In radians, this angle is also the arc length of the * segment between the two positions on that circle. To compute a distance in meters from this value, multiply it by - * the radius of the globe. - * This method uses a spherical model, not elliptical. + * the radius of the globe. This method uses a spherical model, not elliptical. * * @param p1 LatLon of the first location * @param p2 LatLon of the second location @@ -705,10 +646,8 @@ public static LatLon[] greatCircleArcExtremeLocations(Iterable * @return the arc length of the rhumb line between the two locations. In radians, this value is the arc length on * the radius pi circle. */ - public static Angle rhumbDistance(LatLon p1, LatLon p2) - { - if (p1 == null || p2 == null) - { + public static Angle rhumbDistance(LatLon p1, LatLon p2) { + if (p1 == null || p2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -719,27 +658,24 @@ public static Angle rhumbDistance(LatLon p1, LatLon p2) double lat2 = p2.getLatitude().radians; double lon2 = p2.getLongitude().radians; - if (lat1 == lat2 && lon1 == lon2) + if (lat1 == lat2 && lon1 == lon2) { return Angle.ZERO; + } // Taken from http://www.movable-type.co.uk/scripts/latlong.html double dLat = lat2 - lat1; double dLon = lon2 - lon1; double q; - if (Math.abs(dLat) < NEAR_ZERO_THRESHOLD) - { + if (Math.abs(dLat) < NEAR_ZERO_THRESHOLD) { q = Math.cos(lat1); - } - else - { + } else { double dPhi = Math.log(Math.tan(lat2 / 2.0 + Math.PI / 4.0) / Math.tan(lat1 / 2.0 + Math.PI / 4.0)); q = dLat / dPhi; } // If lonChange over 180 take shorter rhumb across 180 meridian. - if (Math.abs(dLon) > Math.PI) - { + if (Math.abs(dLon) > Math.PI) { dLon = dLon > 0 ? -(2 * Math.PI - dLon) : (2 * Math.PI + dLon); } @@ -750,18 +686,15 @@ public static Angle rhumbDistance(LatLon p1, LatLon p2) /** * Computes the azimuth angle (clockwise from North) of a rhumb line (a line of constant heading) between two - * locations. - * This method uses a spherical model, not elliptical. + * locations. This method uses a spherical model, not elliptical. * * @param p1 LatLon of the first location * @param p2 LatLon of the second location * * @return azimuth Angle of a rhumb line between the two locations. */ - public static Angle rhumbAzimuth(LatLon p1, LatLon p2) - { - if (p1 == null || p2 == null) - { + public static Angle rhumbAzimuth(LatLon p1, LatLon p2) { + if (p1 == null || p2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -772,15 +705,15 @@ public static Angle rhumbAzimuth(LatLon p1, LatLon p2) double lat2 = p2.getLatitude().radians; double lon2 = p2.getLongitude().radians; - if (lat1 == lat2 && lon1 == lon2) + if (lat1 == lat2 && lon1 == lon2) { return Angle.ZERO; + } // Taken from http://www.movable-type.co.uk/scripts/latlong.html double dLon = lon2 - lon1; double dPhi = Math.log(Math.tan(lat2 / 2.0 + Math.PI / 4.0) / Math.tan(lat1 / 2.0 + Math.PI / 4.0)); // If lonChange over 180 take shorter rhumb across 180 meridian. - if (Math.abs(dLon) > Math.PI) - { + if (Math.abs(dLon) > Math.PI) { dLon = dLon > 0 ? -(2 * Math.PI - dLon) : (2 * Math.PI + dLon); } double azimuthRadians = Math.atan2(dLon, dPhi); @@ -790,25 +723,21 @@ public static Angle rhumbAzimuth(LatLon p1, LatLon p2) /** * Computes the location on a rhumb line with the given starting location, rhumb azimuth, and arc distance along the - * line. - * This method uses a spherical model, not elliptical. + * line. This method uses a spherical model, not elliptical. * - * @param p LatLon of the starting location + * @param p LatLon of the starting location * @param rhumbAzimuth rhumb azimuth angle (clockwise from North) - * @param pathLength arc distance to travel + * @param pathLength arc distance to travel * * @return LatLon location on the rhumb line. */ - public static LatLon rhumbEndPosition(LatLon p, Angle rhumbAzimuth, Angle pathLength) - { - if (p == null) - { + public static LatLon rhumbEndPosition(LatLon p, Angle rhumbAzimuth, Angle pathLength) { + if (p == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rhumbAzimuth == null || pathLength == null) - { + if (rhumbAzimuth == null || pathLength == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -819,54 +748,49 @@ public static LatLon rhumbEndPosition(LatLon p, Angle rhumbAzimuth, Angle pathLe double azimuth = rhumbAzimuth.radians; double distance = pathLength.radians; - if (distance == 0) + if (distance == 0) { return p; + } // Taken from http://www.movable-type.co.uk/scripts/latlong.html double dLat = distance * Math.cos(azimuth); double lat2 = lat1 + dLat; double q; - if (Math.abs(dLat) < NEAR_ZERO_THRESHOLD) - { + if (Math.abs(dLat) < NEAR_ZERO_THRESHOLD) { q = Math.cos(lat1); - } - else - { + } else { double dPhi = Math.log(Math.tan(lat2 / 2.0 + Math.PI / 4.0) / Math.tan(lat1 / 2.0 + Math.PI / 4.0)); q = (lat2 - lat1) / dPhi; } double dLon = distance * Math.sin(azimuth) / q; // Handle latitude passing over either pole. - if (Math.abs(lat2) > Math.PI / 2.0) - { + if (Math.abs(lat2) > Math.PI / 2.0) { lat2 = lat2 > 0 ? Math.PI - lat2 : -Math.PI - lat2; } double lon2 = (lon1 + dLon + Math.PI) % (2 * Math.PI) - Math.PI; - if (Double.isNaN(lat2) || Double.isNaN(lon2)) + if (Double.isNaN(lat2) || Double.isNaN(lon2)) { return p; + } return new LatLon( - Angle.fromRadians(lat2).normalizedLatitude(), - Angle.fromRadians(lon2).normalizedLongitude()); + Angle.fromRadians(lat2).normalizedLatitude(), + Angle.fromRadians(lon2).normalizedLongitude()); } /** * Computes the location on a rhumb line with the given starting location, rhumb azimuth, and arc distance along the - * line. - * This method uses a spherical model, not elliptical. + * line. This method uses a spherical model, not elliptical. * - * @param p LatLon of the starting location + * @param p LatLon of the starting location * @param rhumbAzimuthRadians rhumb azimuth angle (clockwise from North), in radians - * @param pathLengthRadians arc distance to travel, in radians + * @param pathLengthRadians arc distance to travel, in radians * * @return LatLon location on the rhumb line. */ - public static LatLon rhumbEndPosition(LatLon p, double rhumbAzimuthRadians, double pathLengthRadians) - { - if (p == null) - { + public static LatLon rhumbEndPosition(LatLon p, double rhumbAzimuthRadians, double pathLengthRadians) { + if (p == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -887,10 +811,8 @@ public static LatLon rhumbEndPosition(LatLon p, double rhumbAzimuthRadians, doub * @return the arc length of the line between the two locations. In radians, this value is the arc length on the * radius pi circle. */ - public static Angle linearDistance(LatLon p1, LatLon p2) - { - if (p1 == null || p2 == null) - { + public static Angle linearDistance(LatLon p1, LatLon p2) { + if (p1 == null || p2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -901,15 +823,15 @@ public static Angle linearDistance(LatLon p1, LatLon p2) double lat2 = p2.getLatitude().radians; double lon2 = p2.getLongitude().radians; - if (lat1 == lat2 && lon1 == lon2) + if (lat1 == lat2 && lon1 == lon2) { return Angle.ZERO; + } double dLat = lat2 - lat1; double dLon = lon2 - lon1; // If lonChange over 180 take shorter path across 180 meridian. - if (Math.abs(dLon) > Math.PI) - { + if (Math.abs(dLon) > Math.PI) { dLon = dLon > 0 ? -(2 * Math.PI - dLon) : (2 * Math.PI + dLon); } @@ -926,10 +848,8 @@ public static Angle linearDistance(LatLon p1, LatLon p2) * * @return azimuth Angle of a linear path between the two locations. */ - public static Angle linearAzimuth(LatLon p1, LatLon p2) - { - if (p1 == null || p2 == null) - { + public static Angle linearAzimuth(LatLon p1, LatLon p2) { + if (p1 == null || p2 == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -940,15 +860,15 @@ public static Angle linearAzimuth(LatLon p1, LatLon p2) double lat2 = p2.getLatitude().radians; double lon2 = p2.getLongitude().radians; - if (lat1 == lat2 && lon1 == lon2) + if (lat1 == lat2 && lon1 == lon2) { return Angle.ZERO; + } double dLon = lon2 - lon1; double dLat = lat2 - lat1; // If lonChange over 180 take shorter rhumb across 180 meridian. - if (Math.abs(dLon) > Math.PI) - { + if (Math.abs(dLon) > Math.PI) { dLon = dLon > 0 ? -(2 * Math.PI - dLon) : (2 * Math.PI + dLon); } double azimuthRadians = Math.atan2(dLon, dLat); @@ -961,22 +881,19 @@ public static Angle linearAzimuth(LatLon p1, LatLon p2) * linear path is determined by treating latitude and longitude as a rectangular grid. This type of path is a * straight line in the equidistant cylindrical map projection (also called equirectangular). * - * @param p LatLon of the starting location + * @param p LatLon of the starting location * @param linearAzimuth azimuth angle (clockwise from North) - * @param pathLength arc distance to travel + * @param pathLength arc distance to travel * * @return LatLon location on the line. */ - public static LatLon linearEndPosition(LatLon p, Angle linearAzimuth, Angle pathLength) - { - if (p == null) - { + public static LatLon linearEndPosition(LatLon p, Angle linearAzimuth, Angle pathLength) { + if (p == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (linearAzimuth == null || pathLength == null) - { + if (linearAzimuth == null || pathLength == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -987,24 +904,25 @@ public static LatLon linearEndPosition(LatLon p, Angle linearAzimuth, Angle path double azimuth = linearAzimuth.radians; double distance = pathLength.radians; - if (distance == 0) + if (distance == 0) { return p; + } double lat2 = lat1 + distance * Math.cos(azimuth); // Handle latitude passing over either pole. - if (Math.abs(lat2) > Math.PI / 2.0) - { + if (Math.abs(lat2) > Math.PI / 2.0) { lat2 = lat2 > 0 ? Math.PI - lat2 : -Math.PI - lat2; } double lon2 = (lon1 + distance * Math.sin(azimuth) + Math.PI) % (2 * Math.PI) - Math.PI; - if (Double.isNaN(lat2) || Double.isNaN(lon2)) + if (Double.isNaN(lat2) || Double.isNaN(lon2)) { return p; + } return new LatLon( - Angle.fromRadians(lat2).normalizedLatitude(), - Angle.fromRadians(lon2).normalizedLongitude()); + Angle.fromRadians(lat2).normalizedLatitude(), + Angle.fromRadians(lon2).normalizedLongitude()); } /** @@ -1014,10 +932,8 @@ public static LatLon linearEndPosition(LatLon p, Angle linearAzimuth, Angle path * * @return Average rhumb line distance between locations, as an angular distance. */ - public static Angle getAverageDistance(Iterable locations) - { - if ((locations == null)) - { + public static Angle getAverageDistance(Iterable locations) { + if ((locations == null)) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1026,12 +942,9 @@ public static Angle getAverageDistance(Iterable locations) double totalDistance = 0.0; int count = 0; - for (LatLon p1 : locations) - { - for (LatLon p2 : locations) - { - if (p1 != p2) - { + for (LatLon p1 : locations) { + for (LatLon p2 : locations) { + if (p1 != p2) { double d = rhumbDistance(p1, p2).radians; totalDistance += d; count++; @@ -1045,48 +958,42 @@ public static Angle getAverageDistance(Iterable locations) /** * Computes the average distance between a specified center point and a list of locations. * - * @param globe the globe to use for the computations. - * @param center the center point. + * @param globe the globe to use for the computations. + * @param center the center point. * @param locations the locations. * * @return the average distance. * * @throws java.lang.IllegalArgumentException if any of the specified globe, center or locations are null. */ - public static Angle getAverageDistance(Globe globe, LatLon center, Iterable locations) - { - if ((globe == null)) - { + public static Angle getAverageDistance(Globe globe, LatLon center, Iterable locations) { + if ((globe == null)) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if ((center == null)) - { + if ((center == null)) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if ((locations == null)) - { + if ((locations == null)) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } int count = 0; - for (LatLon ignored : locations) - { + for (LatLon ignored : locations) { ++count; } Vec4 centerPoint = globe.computeEllipsoidalPointFromLocation(center); double totalDistance = 0; - for (LatLon location : locations) - { + for (LatLon location : locations) { double distance = globe.computeEllipsoidalPointFromLocation(location).subtract3(centerPoint).getLength3(); totalDistance += distance / count; } @@ -1103,10 +1010,8 @@ public static Angle getAverageDistance(Globe globe, LatLon center, Iterable locations) - { - if ((locations == null)) - { + public static LatLon getCenter(Iterable locations) { + if ((locations == null)) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1115,11 +1020,11 @@ public static LatLon getCenter(Iterable locations) double latitude = 0; double longitude = 0; int count = 0; - for (LatLon location : locations) - { + for (LatLon location : locations) { double lon = location.getLongitude().radians; - if (lon < 0) + if (lon < 0) { lon += 2 * Math.PI; + } longitude += lon; latitude += location.getLatitude().radians; @@ -1127,19 +1032,18 @@ public static LatLon getCenter(Iterable locations) ++count; } - if (count > 0) - { + if (count > 0) { latitude /= count; longitude /= count; } - if (longitude > Math.PI) + if (longitude > Math.PI) { longitude -= 2 * Math.PI; + } return LatLon.fromRadians(latitude, longitude); } - /** * Computes the average location of a specified list of locations. * @@ -1150,17 +1054,14 @@ public static LatLon getCenter(Iterable locations) * * @throws java.lang.IllegalArgumentException if either the specified globe or locations is null. */ - public static LatLon getCenter(Globe globe, Iterable locations) - { - if ((globe == null)) - { + public static LatLon getCenter(Globe globe, Iterable locations) { + if ((globe == null)) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if ((locations == null)) - { + if ((locations == null)) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1169,8 +1070,7 @@ public static LatLon getCenter(Globe globe, Iterable locations Vec4 center = Vec4.ZERO; int count = 0; - for (LatLon location : locations) - { + for (LatLon location : locations) { center = center.add3(globe.computeEllipsoidalPointFromLocation(location)); ++count; } @@ -1178,10 +1078,8 @@ public static LatLon getCenter(Globe globe, Iterable locations return globe.computePositionFromEllipsoidalPoint(center.divide3(count)); } - public LatLon add(LatLon that) - { - if (that == null) - { + public LatLon add(LatLon that) { + if (that == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1193,10 +1091,8 @@ public LatLon add(LatLon that) return new LatLon(lat, lon); } - public LatLon subtract(LatLon that) - { - if (that == null) - { + public LatLon subtract(LatLon that) { + if (that == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1208,10 +1104,8 @@ public LatLon subtract(LatLon that) return new LatLon(lat, lon); } - public LatLon add(Position that) - { - if (that == null) - { + public LatLon add(Position that) { + if (that == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1223,10 +1117,8 @@ public LatLon add(Position that) return new LatLon(lat, lon); } - public LatLon subtract(Position that) - { - if (that == null) - { + public LatLon subtract(Position that) { + if (that == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1238,27 +1130,23 @@ public LatLon subtract(Position that) return new LatLon(lat, lon); } - public static boolean locationsCrossDateLine(Iterable locations) - { - if (locations == null) - { + public static boolean locationsCrossDateLine(Iterable locations) { + if (locations == null) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } LatLon pos = null; - for (LatLon posNext : locations) - { - if (pos != null) - { + for (LatLon posNext : locations) { + if (pos != null) { // A segment cross the line if end pos have different longitude signs // and are more than 180 degrees longitude apart - if (Math.signum(pos.getLongitude().degrees) != Math.signum(posNext.getLongitude().degrees)) - { + if (Math.signum(pos.getLongitude().degrees) != Math.signum(posNext.getLongitude().degrees)) { double delta = Math.abs(pos.getLongitude().degrees - posNext.getLongitude().degrees); - if (delta > 180 && delta < 360) + if (delta > 180 && delta < 360) { return true; + } } } pos = posNext; @@ -1267,10 +1155,8 @@ public static boolean locationsCrossDateLine(Iterable location return false; } - public static boolean locationsCrossDateline(LatLon p1, LatLon p2) - { - if (p1 == null || p2 == null) - { + public static boolean locationsCrossDateline(LatLon p1, LatLon p2) { + if (p1 == null || p2 == null) { String msg = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1278,11 +1164,11 @@ public static boolean locationsCrossDateline(LatLon p1, LatLon p2) // A segment cross the line if end pos have different longitude signs // and are more than 180 degrees longitude apart - if (Math.signum(p1.getLongitude().degrees) != Math.signum(p2.getLongitude().degrees)) - { + if (Math.signum(p1.getLongitude().degrees) != Math.signum(p2.getLongitude().degrees)) { double delta = Math.abs(p1.getLongitude().degrees - p2.getLongitude().degrees); - if (delta > 180 && delta < 360) + if (delta > 180 && delta < 360) { return true; + } } return false; @@ -1300,10 +1186,8 @@ public static boolean locationsCrossDateline(LatLon p1, LatLon p2) * * @throws java.lang.IllegalArgumentException if the locations are null. */ - public static String locationsContainPole(Iterable locations) - { - if (locations == null) - { + public static String locationsContainPole(Iterable locations) { + if (locations == null) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1319,42 +1203,48 @@ public static String locationsContainPole(Iterable locations) LatLon first = null; LatLon prev = null; - for (LatLon ll : locations) - { - if (first == null) + for (LatLon ll : locations) { + if (first == null) { first = ll; + } - if (prev != null && LatLon.locationsCrossDateline(prev, ll)) + if (prev != null && LatLon.locationsCrossDateline(prev, ll)) { containsPole = !containsPole; + } - if (ll.latitude.degrees < minLatitude) + if (ll.latitude.degrees < minLatitude) { minLatitude = ll.latitude.degrees; + } - if (ll.latitude.degrees > maxLatitude) + if (ll.latitude.degrees > maxLatitude) { maxLatitude = ll.latitude.degrees; + } prev = ll; } // Close the loop by connecting the last position to the first. If the loop is already closed then the following // test will always fail, and will not affect the result. - if (first != null && LatLon.locationsCrossDateline(first, prev)) + if (first != null && LatLon.locationsCrossDateline(first, prev)) { containsPole = !containsPole; + } - if (!containsPole) + if (!containsPole) { return null; + } // Determine which pole is enclosed. If the shape is entirely in one hemisphere, then assume that it encloses // the pole in that hemisphere. Otherwise, assume that it encloses the pole that is closest to the shape's // extreme latitude. - if (minLatitude > 0) + if (minLatitude > 0) { return AVKey.NORTH; // Entirely in Northern Hemisphere - else if (maxLatitude < 0) + } else if (maxLatitude < 0) { return AVKey.SOUTH; // Entirely in Southern Hemisphere - else if (Math.abs(maxLatitude) >= Math.abs(minLatitude)) + } else if (Math.abs(maxLatitude) >= Math.abs(minLatitude)) { return AVKey.NORTH; // Spans equator, but more north than south - else + } else { return AVKey.SOUTH; + } } /** @@ -1368,10 +1258,8 @@ else if (Math.abs(maxLatitude) >= Math.abs(minLatitude)) * * @throws java.lang.IllegalArgumentException if the locations are null. */ - public static List> repeatLocationsAroundDateline(Iterable locations) - { - if (locations == null) - { + public static List> repeatLocationsAroundDateline(Iterable locations) { + if (locations == null) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1386,22 +1274,18 @@ public static List> repeatLocationsAroundDateline(Iterable locationsA = new ArrayList(); list.add(locationsA); - for (LatLon cur : locations) - { - if (prev != null && LatLon.locationsCrossDateline(prev, cur)) - { - if (lonOffset == 0) + for (LatLon cur : locations) { + if (prev != null && LatLon.locationsCrossDateline(prev, cur)) { + if (lonOffset == 0) { lonOffset = (prev.longitude.degrees < 0 ? -360 : 360); + } applyLonOffset = !applyLonOffset; } - if (applyLonOffset) - { + if (applyLonOffset) { locationsA.add(LatLon.fromDegrees(cur.latitude.degrees, cur.longitude.degrees + lonOffset)); - } - else - { + } else { locationsA.add(cur); } @@ -1413,8 +1297,7 @@ public static List> repeatLocationsAroundDateline(Iterable locationsB = new ArrayList(); list.add(locationsB); - for (LatLon cur : locationsA) - { + for (LatLon cur : locationsA) { locationsB.add(LatLon.fromDegrees(cur.latitude.degrees, cur.longitude.degrees - lonOffset)); } } @@ -1428,25 +1311,22 @@ public static List> repeatLocationsAroundDateline(Iterable cutLocationsAlongDateLine(Iterable locations, String pole, Globe globe) - { - if (locations == null) - { + public static List cutLocationsAlongDateLine(Iterable locations, String pole, Globe globe) { + if (locations == null) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (pole == null) - { + if (pole == null) { String msg = Logging.getMessage("nullValue.PoleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1457,13 +1337,10 @@ public static List cutLocationsAlongDateLine(Iterable Angle poleLat = AVKey.NORTH.equals(pole) ? Angle.POS90 : Angle.NEG90; LatLon pos = null; - for (LatLon posNext : locations) - { - if (pos != null) - { + for (LatLon posNext : locations) { + if (pos != null) { newLocations.add(pos); - if (LatLon.locationsCrossDateline(pos, posNext)) - { + if (LatLon.locationsCrossDateline(pos, posNext)) { // Determine where the segment crosses the dateline. LatLon separation = LatLon.intersectionWithMeridian(pos, posNext, Angle.POS180, globe); double sign = Math.signum(pos.getLongitude().degrees); @@ -1504,33 +1381,29 @@ public static List cutLocationsAlongDateLine(Iterable * * @throws IllegalArgumentException if the location list is null. */ - public static List makeDatelineCrossingLocationsPositive(Iterable locations) - { - if (locations == null) - { + public static List makeDatelineCrossingLocationsPositive(Iterable locations) { + if (locations == null) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Iterator iter = locations.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return Collections.emptyList(); + } ArrayList newLocations = new ArrayList(); - for (LatLon location : locations) - { - if (location == null) + for (LatLon location : locations) { + if (location == null) { continue; + } - if (location.getLongitude().degrees < 0) - { + if (location.getLongitude().degrees < 0) { newLocations.add( - LatLon.fromDegrees(location.getLatitude().degrees, location.getLongitude().degrees + 360)); - } - else - { + LatLon.fromDegrees(location.getLatitude().degrees, location.getLongitude().degrees + 360)); + } else { newLocations.add(location); } } @@ -1544,34 +1417,30 @@ public static List makeDatelineCrossingLocationsPositive(IterableLatLon instance with the parsed angles. * * @throws IllegalArgumentException if latLonString is null. - * @throws NumberFormatException if the string does not form a latitude, longitude pair. + * @throws NumberFormatException if the string does not form a latitude, longitude pair. */ public LatLon parseLatLon(String latLonString) // TODO { - if (latLonString == null) - { + if (latLonString == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1661,40 +1528,40 @@ public LatLon parseLatLon(String latLonString) // TODO } @Override - public String toString() - { + public String toString() { String las = String.format("Lat %7.4f\u00B0", this.getLatitude().getDegrees()); String los = String.format("Lon %7.4f\u00B0", this.getLongitude().getDegrees()); return "(" + las + ", " + los + ")"; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final gov.nasa.worldwind.geom.LatLon latLon = (gov.nasa.worldwind.geom.LatLon) o; - if (!latitude.equals(latLon.latitude)) + if (!latitude.equals(latLon.latitude)) { return false; + } //noinspection RedundantIfStatement - if (!longitude.equals(latLon.longitude)) + if (!longitude.equals(latLon.longitude)) { return false; + } return true; } - public static boolean equals(LatLon a, LatLon b) - { + public static boolean equals(LatLon a, LatLon b) { return a.getLatitude().equals(b.getLatitude()) && a.getLongitude().equals(b.getLongitude()); } @Override - public int hashCode() - { + public int hashCode() { int result; result = latitude.hashCode(); result = 29 * result + longitude.hashCode(); @@ -1704,17 +1571,15 @@ public int hashCode() /** * Compute the forward azimuth between two positions * - * @param p1 first position - * @param p2 second position + * @param p1 first position + * @param p2 second position * @param equatorialRadius the equatorial radius of the globe in meters - * @param polarRadius the polar radius of the globe in meters + * @param polarRadius the polar radius of the globe in meters * * @return the azimuth */ - public static Angle ellipsoidalForwardAzimuth(LatLon p1, LatLon p2, double equatorialRadius, double polarRadius) - { - if (p1 == null || p2 == null) - { + public static Angle ellipsoidalForwardAzimuth(LatLon p1, LatLon p2, double equatorialRadius, double polarRadius) { + if (p1 == null || p2 == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1746,25 +1611,21 @@ public static Angle ellipsoidalForwardAzimuth(LatLon p1, LatLon p2, double equat // dummy value to ensure double lambda_prev = Double.MAX_VALUE; int count = 0; - while (Math.abs(lambda - lambda_prev) > 1e-12 && count++ < 100) - { + while (Math.abs(lambda - lambda_prev) > 1e-12 && count++ < 100) { // Store old lambda lambda_prev = lambda; // Calculate new lambda double sSigma = Math.sqrt(Math.pow(cU2 * sLambda, 2) - + Math.pow(cU1 * sU2 - sU1 * cU2 * cLambda, 2)); + + Math.pow(cU1 * sU2 - sU1 * cU2 * cLambda, 2)); double cSigma = sU1 * sU2 + cU1 * cU2 * cLambda; double sigma = Math.atan2(sSigma, cSigma); double sAlpha = cU1 * cU2 * sLambda / sSigma; double cAlpha2 = 1 - sAlpha * sAlpha; // trig identity // As cAlpha2 approaches zeros, set cSigmam2 to zero to converge on a solution double cSigmam2; - if (Math.abs(cAlpha2) < 1e-6) - { + if (Math.abs(cAlpha2) < 1e-6) { cSigmam2 = 0; - } - else - { + } else { cSigmam2 = cSigma - 2 * sU1 * sU2 / cAlpha2; } double c = f / 16 * cAlpha2 * (4 + f * (4 - 3 * cAlpha2)); @@ -1779,11 +1640,11 @@ public static Angle ellipsoidalForwardAzimuth(LatLon p1, LatLon p2, double equat // TODO: Need method to compute end position from initial position, azimuth and distance. The companion to the // spherical version, endPosition(), above. - /** * Computes the distance between two points on an ellipsoid iteratively. *

        - * NOTE: This method was copied from the UniData NetCDF Java library. http://www.unidata.ucar.edu/software/netcdf-java/ + * NOTE: This method was copied from the UniData NetCDF Java library. + * http://www.unidata.ucar.edu/software/netcdf-java/ *

        * Algorithm from U.S. National Geodetic Survey, FORTRAN program "inverse," subroutine "INVER1," by L. PFEIFER and * JOHN G. GERGEN. See http://www.ngs.noaa.gov/TOOLS/Inv_Fwd/Inv_Fwd.html @@ -1797,23 +1658,21 @@ public static Angle ellipsoidalForwardAzimuth(LatLon p1, LatLon p2, double equat * The algorithm used is iterative and will iterate only 10 times if it does not converge. *

        * - * @param p1 first position - * @param p2 second position + * @param p1 first position + * @param p2 second position * @param equatorialRadius the equatorial radius of the globe in meters - * @param polarRadius the polar radius of the globe in meters + * @param polarRadius the polar radius of the globe in meters * * @return distance in meters between the two points */ - public static double ellipsoidalDistance(LatLon p1, LatLon p2, double equatorialRadius, double polarRadius) - { + public static double ellipsoidalDistance(LatLon p1, LatLon p2, double equatorialRadius, double polarRadius) { // TODO: I think there is a non-iterative way to calculate the distance. Find it and compare with this one. // TODO: What if polar radius is larger than equatorial radius? final double F = (equatorialRadius - polarRadius) / equatorialRadius; // flattening = 1.0 / 298.257223563; final double R = 1.0 - F; final double EPS = 0.5E-13; - if (p1 == null || p2 == null) - { + if (p1 == null || p2 == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1848,7 +1707,6 @@ public static double ellipsoidalDistance(LatLon p1, LatLon p2, double equatorial // //IMPLICIT REAL*8 (A-H,O-Z) // COMMON/CONST/PI,RAD - double GLAT1 = p1.getLatitude().radians; double GLAT2 = p2.getLatitude().radians; double TU1 = R * Math.sin(GLAT1) / Math.cos(GLAT1); @@ -1864,8 +1722,7 @@ public static double ellipsoidalDistance(LatLon p1, LatLon p2, double equatorial double X = GLON2 - GLON1; double D, SX, CX, SY, CY, Y, SA, C2A, CZ, E, C; int iterCount = 0; - do - { + do { SX = Math.sin(X); CX = Math.cos(X); TU1 = CU2 * SX; @@ -1876,8 +1733,7 @@ public static double ellipsoidalDistance(LatLon p1, LatLon p2, double equatorial SA = S * SX / SY; C2A = -SA * SA + 1.; CZ = FAZ + FAZ; - if (C2A > 0.) - { + if (C2A > 0.) { CZ = -CZ / C2A + CY; } E = CZ * CZ * 2. - 1.; @@ -1888,8 +1744,7 @@ public static double ellipsoidalDistance(LatLon p1, LatLon p2, double equatorial //IF(DABS(D-X).GT.EPS) GO TO 100 ++iterCount; - } - while (Math.abs(D - X) > EPS && iterCount <= 10); + } while (Math.abs(D - X) > EPS && iterCount <= 10); //FAZ = Math.atan2(TU1, TU2); //BAZ = Math.atan2(CU1 * SX, BAZ * CX - SU1 * CU2) + Math.PI; @@ -1901,7 +1756,7 @@ public static double ellipsoidalDistance(LatLon p1, LatLon p2, double equatorial X = E * CY; S = 1. - E - E; S = ((((SY * SY * 4. - 3.) * S * CZ * D / 6. - X) * D / 4. + CZ) * SY - * D + Y) * C * equatorialRadius * R; + * D + Y) * C * equatorialRadius * R; return S; } @@ -1911,25 +1766,22 @@ public static double ellipsoidalDistance(LatLon p1, LatLon p2, double equatorial * * @param oldLocation the original reference location. * @param newLocation the new reference location. - * @param locations the locations to translate. + * @param locations the locations to translate. * * @return the translated locations, or null if the locations could not be translated. * * @throws IllegalArgumentException if any argument is null. */ public static List computeShiftedLocations(Position oldLocation, Position newLocation, - Iterable locations) - { + Iterable locations) { // TODO: Account for dateline spanning - if (oldLocation == null || newLocation == null) - { + if (oldLocation == null || newLocation == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (locations == null) - { + if (locations == null) { String msg = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1937,8 +1789,7 @@ public static List computeShiftedLocations(Position oldLocation, Positio ArrayList newPositions = new ArrayList(); - for (LatLon location : locations) - { + for (LatLon location : locations) { Angle distance = LatLon.greatCircleDistance(oldLocation, location); Angle azimuth = LatLon.greatCircleAzimuth(oldLocation, location); newPositions.add(Position.greatCircleEndPosition(newLocation, azimuth, distance)); @@ -1948,24 +1799,20 @@ public static List computeShiftedLocations(Position oldLocation, Positio } public static List computeShiftedLocations(Globe globe, LatLon oldLocation, LatLon newLocation, - Iterable locations) - { - if (globe == null) - { + Iterable locations) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (oldLocation == null || newLocation == null) - { + if (oldLocation == null || newLocation == null) { String msg = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (locations == null) - { + if (locations == null) { String msg = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1977,8 +1824,7 @@ public static List computeShiftedLocations(Globe globe, LatLon oldLocati Vec4 newPoint = globe.computeEllipsoidalPointFromLocation(newLocation); Vec4 delta = newPoint.subtract3(oldPoint); - for (LatLon latLon : locations) - { + for (LatLon latLon : locations) { Vec4 point = globe.computeEllipsoidalPointFromLocation(latLon); point = point.add3(delta); Position newPos = globe.computePositionFromEllipsoidalPoint(point); diff --git a/src/gov/nasa/worldwind/geom/Line.java b/src/gov/nasa/worldwind/geom/Line.java index cbcff68eb6..8cdf9c296d 100644 --- a/src/gov/nasa/worldwind/geom/Line.java +++ b/src/gov/nasa/worldwind/geom/Line.java @@ -13,6 +13,7 @@ */ public final class Line// Instances are immutable { + private final Vec4 origin; private final Vec4 direction; @@ -26,29 +27,27 @@ public final class Line// Instances are immutable * * @throws IllegalArgumentException if either point is null or they are coincident. */ - public static Line fromSegment(Vec4 pa, Vec4 pb) - { + public static Line fromSegment(Vec4 pa, Vec4 pb) { return new Line(pa, new Vec4(pb.x - pa.x, pb.y - pa.y, pb.z - pa.z, 0)); } /** - * @param origin the origin of the line being constructed + * @param origin the origin of the line being constructed * @param direction the direction of the line being constructed * * @throws IllegalArgumentException if origin is null, or direction is null or has zero - * length + * length */ - public Line(Vec4 origin, Vec4 direction) - { + public Line(Vec4 origin, Vec4 direction) { String message = null; - if (origin == null) + if (origin == null) { message = "nullValue.OriginIsNull"; - else if (direction == null) + } else if (direction == null) { message = "nullValue.DirectionIsNull"; - else if (direction.getLength3() <= 0) + } else if (direction.getLength3() <= 0) { message = "Geom.Line.DirectionIsZeroVector"; - if (message != null) - { + } + if (message != null) { message = Logging.getMessage(message); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -58,23 +57,19 @@ else if (direction.getLength3() <= 0) this.direction = direction; } - public final Vec4 getDirection() - { + public final Vec4 getDirection() { return direction; } - public final Vec4 getOrigin() - { + public final Vec4 getOrigin() { return origin; } - public final Vec4 getPointAt(double t) - { + public final Vec4 getPointAt(double t) { return Vec4.fromLine3(this.origin, t, this.direction); } - public final double selfDot() - { + public final double selfDot() { return this.origin.dot3(this.direction); } @@ -88,35 +83,36 @@ public final double selfDot() * @return true if these two objects are equal, false otherwise */ @Override - public final boolean equals(Object o) - { - if (this == o) + public final boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final gov.nasa.worldwind.geom.Line line = (gov.nasa.worldwind.geom.Line) o; - if (!direction.equals(line.direction)) + if (!direction.equals(line.direction)) { return false; + } //noinspection RedundantIfStatement - if (!line.origin.equals(origin)) + if (!line.origin.equals(origin)) { return false; + } return true; } @Override - public final int hashCode() - { + public final int hashCode() { int result; result = origin.hashCode(); result = 29 * result + direction.hashCode(); return result; } - public String toString() - { + public String toString() { return "Origin: " + this.origin + ", Direction: " + this.direction; } // @@ -143,8 +139,7 @@ public String toString() // return Math.sqrt(bSquared - aSquared); // } - public final Vec4 nearestPointTo(Vec4 p) - { + public final Vec4 nearestPointTo(Vec4 p) { Vec4 w = p.subtract3(this.origin); double c1 = w.dot3(this.direction); @@ -163,8 +158,7 @@ public final Vec4 nearestPointTo(Vec4 p) * * @throws IllegalArgumentException if p is null */ - public final double distanceTo(Vec4 p) - { + public final double distanceTo(Vec4 p) { return p.distanceTo3(this.nearestPointTo(p)); } @@ -173,30 +167,30 @@ public final double distanceTo(Vec4 p) * * @param p0 The first endpoint of the segment. * @param p1 The second endpoint of the segment. - * @param p The point outside the segment whose closest point on the segment is desired. + * @param p The point outside the segment whose closest point on the segment is desired. * - * @return The closest point on (p0, p1) to p. Note that this will be p0 or p1 themselves whenever the closest - * point on the line defined by p0 and p1 is outside the segment (i.e., the results are bounded by - * the segment endpoints). + * @return The closest point on (p0, p1) to p. Note that this will be p0 or p1 themselves whenever the closest point + * on the line defined by p0 and p1 is outside the segment (i.e., the results are bounded by the segment + * endpoints). */ - public static Vec4 nearestPointOnSegment(Vec4 p0, Vec4 p1, Vec4 p) - { + public static Vec4 nearestPointOnSegment(Vec4 p0, Vec4 p1, Vec4 p) { Vec4 v = p1.subtract3(p0); Vec4 w = p.subtract3(p0); double c1 = w.dot3(v); double c2 = v.dot3(v); - if (c1 <= 0) + if (c1 <= 0) { return p0; - if (c2 <= c1) + } + if (c2 <= c1) { return p1; + } return p0.add3(v.multiply3(c1 / c2)); } - public static double distanceToSegment(Vec4 p0, Vec4 p1, Vec4 p) - { + public static double distanceToSegment(Vec4 p0, Vec4 p1, Vec4 p) { Vec4 pb = nearestPointOnSegment(p0, p1, p); return p.distanceTo3(pb); @@ -206,31 +200,26 @@ public static double distanceToSegment(Vec4 p0, Vec4 p1, Vec4 p) * Clip a line segment to a frustum, returning the end points of the portion of the segment that is within the * frustum. * - * @param pa the first point of the segment. - * @param pb the second point of the segment. + * @param pa the first point of the segment. + * @param pb the second point of the segment. * @param frustum the frustum. * * @return The two points at which the segment intersects the frustum, or null if the segment does not intersect and - * the frustum does not fully contain it. If the segment is coincident with a plane of the frustum, the - * returned segment is the portion of the original segment on that plane, clipped to the other frustum - * planes. + * the frustum does not fully contain it. If the segment is coincident with a plane of the frustum, the returned + * segment is the portion of the original segment on that plane, clipped to the other frustum planes. */ - public static Vec4[] clipToFrustum(Vec4 pa, Vec4 pb, Frustum frustum) - { + public static Vec4[] clipToFrustum(Vec4 pa, Vec4 pb, Frustum frustum) { return clipToFrustum(pa, pb, frustum, 1); } - private static Vec4[] clipToFrustum(Vec4 pa, Vec4 pb, Frustum frustum, int maxRecursionCount) - { - if (pa == null || pb == null) - { + private static Vec4[] clipToFrustum(Vec4 pa, Vec4 pb, Frustum frustum, int maxRecursionCount) { + if (pa == null || pb == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (frustum == null) - { + if (frustum == null) { String message = Logging.getMessage("nullValue.FrustumIsNull"); Logging.logger().severe(message); @@ -238,36 +227,38 @@ private static Vec4[] clipToFrustum(Vec4 pa, Vec4 pb, Frustum frustum, int maxRe } // First do a trivial accept test. - if (frustum.contains(pa) && frustum.contains(pb)) - return new Vec4[] {pa, pb}; + if (frustum.contains(pa) && frustum.contains(pb)) { + return new Vec4[]{pa, pb}; + } - Vec4[] segment = new Vec4[] {pa, pb}; + Vec4[] segment = new Vec4[]{pa, pb}; Vec4[] ipts; - for (Plane p : frustum.getAllPlanes()) - { + for (Plane p : frustum.getAllPlanes()) { // See if both points are behind the plane and therefore not in the frustum. - if (p.onSameSide(segment[0], segment[1]) < 0) + if (p.onSameSide(segment[0], segment[1]) < 0) { return null; + } // Clip the segment to the plane if they intersect. ipts = p.clip(segment[0], segment[1]); - if (ipts != null) - { + if (ipts != null) { segment = ipts; } } // If one of the initial points was in the frustum then the segment must have been clipped. - if (frustum.contains(pa) || frustum.contains(pb)) + if (frustum.contains(pa) || frustum.contains(pb)) { return segment; + } // The segment was clipped by an infinite frustum plane but may still lie outside the frustum. // So recurse using the clipped segment. - if (maxRecursionCount > 0) + if (maxRecursionCount > 0) { return clipToFrustum(segment[0], segment[1], frustum, --maxRecursionCount); - else + } else { return segment; + } } /** @@ -277,26 +268,21 @@ private static Vec4[] clipToFrustum(Vec4 pa, Vec4 pb, Frustum frustum, int maxRe * * @return true if point is behind this Line's origin, false otherwise. */ - public boolean isPointBehindLineOrigin(Vec4 point) - { + public boolean isPointBehindLineOrigin(Vec4 point) { double dot = point.subtract3(this.getOrigin()).dot3(this.getDirection()); return dot < 0.0; } - public Vec4 nearestIntersectionPoint(Intersection[] intersections) - { + public Vec4 nearestIntersectionPoint(Intersection[] intersections) { Vec4 intersectionPoint = null; // Find the nearest intersection that's in front of the ray origin. double nearestDistance = Double.MAX_VALUE; - for (Intersection intersection : intersections) - { + for (Intersection intersection : intersections) { // Ignore any intersections behind the line origin. - if (!this.isPointBehindLineOrigin(intersection.getIntersectionPoint())) - { + if (!this.isPointBehindLineOrigin(intersection.getIntersectionPoint())) { double d = intersection.getIntersectionPoint().distanceTo3(this.getOrigin()); - if (d < nearestDistance) - { + if (d < nearestDistance) { intersectionPoint = intersection.getIntersectionPoint(); nearestDistance = d; } diff --git a/src/gov/nasa/worldwind/geom/Matrix.java b/src/gov/nasa/worldwind/geom/Matrix.java index d310f8cca0..afbb38c0a7 100644 --- a/src/gov/nasa/worldwind/geom/Matrix.java +++ b/src/gov/nasa/worldwind/geom/Matrix.java @@ -14,14 +14,14 @@ * @author dcollins * @version $Id: Matrix.java 2201 2014-08-07 23:17:54Z dcollins $ */ -public class Matrix -{ +public class Matrix { + public static final Matrix IDENTITY = new Matrix( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1, - true); + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1, + true); // Row 1 public final double m11; @@ -54,37 +54,34 @@ public class Matrix // Cached computations. private int hashCode; - public Matrix(double value) - { + public Matrix(double value) { // 'value' is placed in the diagonal. this( - value, 0, 0, 0, - 0, value, 0, 0, - 0, 0, value, 0, - 0, 0, 0, value); + value, 0, 0, 0, + 0, value, 0, 0, + 0, 0, value, 0, + 0, 0, 0, value); } public Matrix( - double m11, double m12, double m13, double m14, - double m21, double m22, double m23, double m24, - double m31, double m32, double m33, double m34, - double m41, double m42, double m43, double m44) - { + double m11, double m12, double m13, double m14, + double m21, double m22, double m23, double m24, + double m31, double m32, double m33, double m34, + double m41, double m42, double m43, double m44) { this( - m11, m12, m13, m14, - m21, m22, m23, m24, - m31, m32, m33, m34, - m41, m42, m43, m44, - false); + m11, m12, m13, m14, + m21, m22, m23, m24, + m31, m32, m33, m34, + m41, m42, m43, m44, + false); } Matrix( - double m11, double m12, double m13, double m14, - double m21, double m22, double m23, double m24, - double m31, double m32, double m33, double m34, - double m41, double m42, double m43, double m44, - boolean isOrthonormalTransform) - { + double m11, double m12, double m13, double m14, + double m21, double m22, double m23, double m24, + double m31, double m32, double m33, double m34, + double m41, double m42, double m43, double m44, + boolean isOrthonormalTransform) { this.m11 = m11; this.m12 = m12; this.m13 = m13; @@ -104,24 +101,23 @@ public Matrix( this.isOrthonormalTransform = isOrthonormalTransform; } - public final boolean equals(Object obj) - { - if (this == obj) + public final boolean equals(Object obj) { + if (this == obj) { return true; - if (obj == null || obj.getClass() != this.getClass()) + } + if (obj == null || obj.getClass() != this.getClass()) { return false; + } Matrix that = (Matrix) obj; return (this.m11 == that.m11) && (this.m12 == that.m12) && (this.m13 == that.m13) && (this.m14 == that.m14) - && (this.m21 == that.m21) && (this.m22 == that.m22) && (this.m23 == that.m23) && (this.m24 == that.m24) - && (this.m31 == that.m31) && (this.m32 == that.m32) && (this.m33 == that.m33) && (this.m34 == that.m34) - && (this.m41 == that.m41) && (this.m42 == that.m42) && (this.m43 == that.m43) && (this.m44 == that.m44); + && (this.m21 == that.m21) && (this.m22 == that.m22) && (this.m23 == that.m23) && (this.m24 == that.m24) + && (this.m31 == that.m31) && (this.m32 == that.m32) && (this.m33 == that.m33) && (this.m34 == that.m34) + && (this.m41 == that.m41) && (this.m42 == that.m42) && (this.m43 == that.m43) && (this.m44 == that.m44); } - public final int hashCode() - { - if (this.hashCode == 0) - { + public final int hashCode() { + if (this.hashCode == 0) { int result; long tmp; tmp = Double.doubleToLongBits(this.m11); @@ -161,90 +157,80 @@ public final int hashCode() return this.hashCode; } - public static Matrix fromArray(double[] compArray, int offset, boolean rowMajor) - { - if (compArray == null) - { + public static Matrix fromArray(double[] compArray, int offset, boolean rowMajor) { + if (compArray == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if ((compArray.length - offset) < NUM_ELEMENTS) - { + if ((compArray.length - offset) < NUM_ELEMENTS) { String msg = Logging.getMessage("generic.ArrayInvalidLength", compArray.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (rowMajor) - { + if (rowMajor) { //noinspection PointlessArithmeticExpression return new Matrix( - // Row 1 - compArray[0 + offset], - compArray[1 + offset], - compArray[2 + offset], - compArray[3 + offset], - // Row 2 - compArray[4 + offset], - compArray[5 + offset], - compArray[6 + offset], - compArray[7 + offset], - // Row 3 - compArray[8 + offset], - compArray[9 + offset], - compArray[10 + offset], - compArray[11 + offset], - // Row 4 - compArray[12 + offset], - compArray[13 + offset], - compArray[14 + offset], - compArray[15 + offset]); - } - else - { + // Row 1 + compArray[0 + offset], + compArray[1 + offset], + compArray[2 + offset], + compArray[3 + offset], + // Row 2 + compArray[4 + offset], + compArray[5 + offset], + compArray[6 + offset], + compArray[7 + offset], + // Row 3 + compArray[8 + offset], + compArray[9 + offset], + compArray[10 + offset], + compArray[11 + offset], + // Row 4 + compArray[12 + offset], + compArray[13 + offset], + compArray[14 + offset], + compArray[15 + offset]); + } else { //noinspection PointlessArithmeticExpression return new Matrix( - // Row 1 - compArray[0 + offset], - compArray[4 + offset], - compArray[8 + offset], - compArray[12 + offset], - // Row 2 - compArray[1 + offset], - compArray[5 + offset], - compArray[9 + offset], - compArray[13 + offset], - // Row 3 - compArray[2 + offset], - compArray[6 + offset], - compArray[10 + offset], - compArray[14 + offset], - // Row 4 - compArray[3 + offset], - compArray[7 + offset], - compArray[11 + offset], - compArray[15 + offset]); - } - } - - public final double[] toArray(double[] compArray, int offset, boolean rowMajor) - { - if (compArray == null) - { + // Row 1 + compArray[0 + offset], + compArray[4 + offset], + compArray[8 + offset], + compArray[12 + offset], + // Row 2 + compArray[1 + offset], + compArray[5 + offset], + compArray[9 + offset], + compArray[13 + offset], + // Row 3 + compArray[2 + offset], + compArray[6 + offset], + compArray[10 + offset], + compArray[14 + offset], + // Row 4 + compArray[3 + offset], + compArray[7 + offset], + compArray[11 + offset], + compArray[15 + offset]); + } + } + + public final double[] toArray(double[] compArray, int offset, boolean rowMajor) { + if (compArray == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if ((compArray.length - offset) < NUM_ELEMENTS) - { + if ((compArray.length - offset) < NUM_ELEMENTS) { String msg = Logging.getMessage("generic.ArrayInvalidLength", compArray.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (rowMajor) - { + if (rowMajor) { // Row 1 //noinspection PointlessArithmeticExpression compArray[0 + offset] = this.m11; @@ -266,9 +252,7 @@ public final double[] toArray(double[] compArray, int offset, boolean rowMajor) compArray[13 + offset] = this.m42; compArray[14 + offset] = this.m43; compArray[15 + offset] = this.m44; - } - else - { + } else { // Row 1 //noinspection PointlessArithmeticExpression compArray[0 + offset] = this.m11; @@ -295,8 +279,7 @@ public final double[] toArray(double[] compArray, int offset, boolean rowMajor) return compArray; } - public final String toString() - { + public final String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(this.m11).append(", ").append(this.m12).append(", ").append(this.m13).append(", ").append(this.m14); @@ -310,170 +293,137 @@ public final String toString() return sb.toString(); } - public final double getM11() - { + public final double getM11() { return this.m11; } - public final double getM12() - { + public final double getM12() { return this.m12; } - public final double getM13() - { + public final double getM13() { return this.m13; } - public final double getM14() - { + public final double getM14() { return this.m14; } - public final double getM21() - { + public final double getM21() { return this.m21; } - public final double getM22() - { + public final double getM22() { return this.m22; } - public final double getM23() - { + public final double getM23() { return this.m23; } - public final double getM24() - { + public final double getM24() { return this.m24; } - public final double getM31() - { + public final double getM31() { return this.m31; } - public final double getM32() - { + public final double getM32() { return this.m32; } - public final double getM33() - { + public final double getM33() { return this.m33; } - public final double getM34() - { + public final double getM34() { return this.m34; } - public final double getM41() - { + public final double getM41() { return this.m41; } - public final double getM42() - { + public final double getM42() { return this.m42; } - public final double getM43() - { + public final double getM43() { return this.m43; } - public final double getM44() - { + public final double getM44() { return this.m44; } - public final double m11() - { + public final double m11() { return this.m11; } - public final double m12() - { + public final double m12() { return this.m12; } - public final double m13() - { + public final double m13() { return this.m13; } - public final double m14() - { + public final double m14() { return this.m14; } - public final double m21() - { + public final double m21() { return this.m21; } - public final double m22() - { + public final double m22() { return this.m22; } - public final double m23() - { + public final double m23() { return this.m23; } - public final double m24() - { + public final double m24() { return this.m24; } - public final double m31() - { + public final double m31() { return this.m31; } - public final double m32() - { + public final double m32() { return this.m32; } - public final double m33() - { + public final double m33() { return this.m33; } - public final double m34() - { + public final double m34() { return this.m34; } - public final double m41() - { + public final double m41() { return this.m41; } - public final double m42() - { + public final double m42() { return this.m42; } - public final double m43() - { + public final double m43() { return this.m43; } - public final double m44() - { + public final double m44() { return this.m44; } // ============== Factory Functions ======================= // // ============== Factory Functions ======================= // // ============== Factory Functions ======================= // - /** * Returns a Cartesian transform Matrix that maps a local orientation to model coordinates. The * orientation is specified by an array of three axes. The axes array must contain three @@ -481,32 +431,27 @@ public final double m44() * axes in the returned Matrix have unit length and are orthogonal to each other. * * @param axes an array must of three non-null vectors defining a local orientation in the following order: x-axis, - * y-axis, z-axis. + * y-axis, z-axis. * * @return a Matrix that a transforms local coordinates to world coordinates. * * @throws IllegalArgumentException if axes is null, if axes contains less - * than three elements, or if any of the first three elements in axes - * is null. + * than three elements, or if any of the first three elements in axes is null. */ - public static Matrix fromAxes(Vec4[] axes) - { - if (axes == null) - { + public static Matrix fromAxes(Vec4[] axes) { + if (axes == null) { String msg = Logging.getMessage("nullValue.AxesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (axes.length < 3) - { + if (axes.length < 3) { String msg = Logging.getMessage("generic.ArrayInvalidLength", axes.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (axes[0] == null || axes[1] == null || axes[2] == null) - { + if (axes[0] == null || axes[1] == null || axes[2] == null) { String msg = Logging.getMessage("nullValue.AxesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -517,23 +462,20 @@ public static Matrix fromAxes(Vec4[] axes) Vec4 u = f.cross3(s).normalize3(); return new Matrix( - s.x, u.x, f.x, 0.0, - s.y, u.y, f.y, 0.0, - s.z, u.z, f.z, 0.0, - 0.0, 0.0, 0.0, 1.0, - true); + s.x, u.x, f.x, 0.0, + s.y, u.y, f.y, 0.0, + s.z, u.z, f.z, 0.0, + 0.0, 0.0, 0.0, 1.0, + true); } - public static Matrix fromAxisAngle(Angle angle, Vec4 axis) - { - if (angle == null) - { + public static Matrix fromAxisAngle(Angle angle, Vec4 axis) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (axis == null) - { + if (axis == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -542,10 +484,8 @@ public static Matrix fromAxisAngle(Angle angle, Vec4 axis) return fromAxisAngle(angle, axis.x, axis.y, axis.z, true); } - public static Matrix fromAxisAngle(Angle angle, double axisX, double axisY, double axisZ) - { - if (angle == null) - { + public static Matrix fromAxisAngle(Angle angle, double axisX, double axisY, double axisZ) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -553,20 +493,16 @@ public static Matrix fromAxisAngle(Angle angle, double axisX, double axisY, doub return fromAxisAngle(angle, axisX, axisY, axisZ, true); } - private static Matrix fromAxisAngle(Angle angle, double axisX, double axisY, double axisZ, boolean normalize) - { - if (angle == null) - { + private static Matrix fromAxisAngle(Angle angle, double axisX, double axisY, double axisZ, boolean normalize) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (normalize) - { + if (normalize) { double length = Math.sqrt((axisX * axisX) + (axisY * axisY) + (axisZ * axisZ)); - if (!isZero(length) && (length != 1.0)) - { + if (!isZero(length) && (length != 1.0)) { axisX /= length; axisY /= length; axisZ /= length; @@ -577,31 +513,29 @@ private static Matrix fromAxisAngle(Angle angle, double axisX, double axisY, dou double s = angle.sin(); double one_minus_c = 1.0 - c; return new Matrix( - // Row 1 - c + (one_minus_c * axisX * axisX), - (one_minus_c * axisX * axisY) - (s * axisZ), - (one_minus_c * axisX * axisZ) + (s * axisY), - 0.0, - // Row 2 - (one_minus_c * axisX * axisY) + (s * axisZ), - c + (one_minus_c * axisY * axisY), - (one_minus_c * axisY * axisZ) - (s * axisX), - 0.0, - // Row 3 - (one_minus_c * axisX * axisZ) - (s * axisY), - (one_minus_c * axisY * axisZ) + (s * axisX), - c + (one_minus_c * axisZ * axisZ), - 0.0, - // Row 4 - 0.0, 0.0, 0.0, 1.0, - // Rotation matrices are orthogonal, 3D transforms. - true); + // Row 1 + c + (one_minus_c * axisX * axisX), + (one_minus_c * axisX * axisY) - (s * axisZ), + (one_minus_c * axisX * axisZ) + (s * axisY), + 0.0, + // Row 2 + (one_minus_c * axisX * axisY) + (s * axisZ), + c + (one_minus_c * axisY * axisY), + (one_minus_c * axisY * axisZ) - (s * axisX), + 0.0, + // Row 3 + (one_minus_c * axisX * axisZ) - (s * axisY), + (one_minus_c * axisY * axisZ) + (s * axisX), + c + (one_minus_c * axisZ * axisZ), + 0.0, + // Row 4 + 0.0, 0.0, 0.0, 1.0, + // Rotation matrices are orthogonal, 3D transforms. + true); } - public static Matrix fromQuaternion(Quaternion quaternion) - { - if (quaternion == null) - { + public static Matrix fromQuaternion(Quaternion quaternion) { + if (quaternion == null) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -610,13 +544,10 @@ public static Matrix fromQuaternion(Quaternion quaternion) return fromQuaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w, true); } - private static Matrix fromQuaternion(double x, double y, double z, double w, boolean normalize) - { - if (normalize) - { + private static Matrix fromQuaternion(double x, double y, double z, double w, boolean normalize) { + if (normalize) { double length = Math.sqrt((x * x) + (y * y) + (z * z) + (w * w)); - if (!isZero(length) && (length != 1.0)) - { + if (!isZero(length) && (length != 1.0)) { x /= length; y /= length; z /= length; @@ -625,31 +556,29 @@ private static Matrix fromQuaternion(double x, double y, double z, double w, boo } return new Matrix( - // Row 1 - 1.0 - (2.0 * y * y) - (2.0 * z * z), - (2.0 * x * y) - (2.0 * z * w), - (2.0 * x * z) + (2.0 * y * w), - 0.0, - // Row 2 - (2.0 * x * y) + (2.0 * z * w), - 1.0 - (2.0 * x * x) - (2.0 * z * z), - (2.0 * y * z) - (2.0 * x * w), - 0.0, - // Row 3 - (2.0 * x * z) - (2.0 * y * w), - (2.0 * y * z) + (2.0 * x * w), - 1.0 - (2.0 * x * x) - (2.0 * y * y), - 0.0, - // Row 4 - 0.0, 0.0, 0.0, 1.0, - // Rotation matrices are orthogonal, 3D transforms. - true); + // Row 1 + 1.0 - (2.0 * y * y) - (2.0 * z * z), + (2.0 * x * y) - (2.0 * z * w), + (2.0 * x * z) + (2.0 * y * w), + 0.0, + // Row 2 + (2.0 * x * y) + (2.0 * z * w), + 1.0 - (2.0 * x * x) - (2.0 * z * z), + (2.0 * y * z) - (2.0 * x * w), + 0.0, + // Row 3 + (2.0 * x * z) - (2.0 * y * w), + (2.0 * y * z) + (2.0 * x * w), + 1.0 - (2.0 * x * x) - (2.0 * y * y), + 0.0, + // Row 4 + 0.0, 0.0, 0.0, 1.0, + // Rotation matrices are orthogonal, 3D transforms. + true); } - public static Matrix fromRotationXYZ(Angle xRotation, Angle yRotation, Angle zRotation) - { - if ((xRotation == null) || (yRotation == null) || (zRotation == null)) - { + public static Matrix fromRotationXYZ(Angle xRotation, Angle yRotation, Angle zRotation) { + if ((xRotation == null) || (yRotation == null) || (zRotation == null)) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -662,18 +591,16 @@ public static Matrix fromRotationXYZ(Angle xRotation, Angle yRotation, Angle zRo double sy = yRotation.sin(); double sz = zRotation.sin(); return new Matrix( - cy * cz, -cy * sz, sy, 0.0, - (sx * sy * cz) + (cx * sz), -(sx * sy * sz) + (cx * cz), -sx * cy, 0.0, - -(cx * sy * cz) + (sx * sz), (cx * sy * sz) + (sx * cz), cx * cy, 0.0, - 0.0, 0.0, 0.0, 1.0, - // Rotation matrices are orthogonal, 3D transforms. - true); + cy * cz, -cy * sz, sy, 0.0, + (sx * sy * cz) + (cx * sz), -(sx * sy * sz) + (cx * cz), -sx * cy, 0.0, + -(cx * sy * cz) + (sx * sz), (cx * sy * sz) + (sx * cz), cx * cy, 0.0, + 0.0, 0.0, 0.0, 1.0, + // Rotation matrices are orthogonal, 3D transforms. + true); } - public static Matrix fromRotationX(Angle angle) - { - if (angle == null) - { + public static Matrix fromRotationX(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -682,18 +609,16 @@ public static Matrix fromRotationX(Angle angle) double c = angle.cos(); double s = angle.sin(); return new Matrix( - 1.0, 0.0, 0.0, 0.0, - 0.0, c, -s, 0.0, - 0.0, s, c, 0.0, - 0.0, 0.0, 0.0, 1.0, - // Rotation matrices are orthogonal, 3D transforms. - true); + 1.0, 0.0, 0.0, 0.0, + 0.0, c, -s, 0.0, + 0.0, s, c, 0.0, + 0.0, 0.0, 0.0, 1.0, + // Rotation matrices are orthogonal, 3D transforms. + true); } - public static Matrix fromRotationY(Angle angle) - { - if (angle == null) - { + public static Matrix fromRotationY(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -702,18 +627,16 @@ public static Matrix fromRotationY(Angle angle) double c = angle.cos(); double s = angle.sin(); return new Matrix( - c, 0.0, s, 0.0, - 0.0, 1.0, 0.0, 0.0, - -s, 0.0, c, 0.0, - 0.0, 0.0, 0.0, 1.0, - // Rotation matrices are orthogonal, 3D transforms. - true); + c, 0.0, s, 0.0, + 0.0, 1.0, 0.0, 0.0, + -s, 0.0, c, 0.0, + 0.0, 0.0, 0.0, 1.0, + // Rotation matrices are orthogonal, 3D transforms. + true); } - public static Matrix fromRotationZ(Angle angle) - { - if (angle == null) - { + public static Matrix fromRotationZ(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -722,23 +645,20 @@ public static Matrix fromRotationZ(Angle angle) double c = angle.cos(); double s = angle.sin(); return new Matrix( - c, -s, 0.0, 0.0, - s, c, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - // Rotation matrices are orthogonal, 3D transforms. - true); + c, -s, 0.0, 0.0, + s, c, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + // Rotation matrices are orthogonal, 3D transforms. + true); } - public static Matrix fromScale(double scale) - { + public static Matrix fromScale(double scale) { return fromScale(scale, scale, scale); } - public static Matrix fromScale(Vec4 scale) - { - if (scale == null) - { + public static Matrix fromScale(Vec4 scale) { + if (scale == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -747,21 +667,18 @@ public static Matrix fromScale(Vec4 scale) return fromScale(scale.x, scale.y, scale.z); } - public static Matrix fromScale(double scaleX, double scaleY, double scaleZ) - { + public static Matrix fromScale(double scaleX, double scaleY, double scaleZ) { return new Matrix( - scaleX, 0.0, 0.0, 0.0, - 0.0, scaleY, 0.0, 0.0, - 0.0, 0.0, scaleZ, 0.0, - 0.0, 0.0, 0.0, 1.0, - // Scale matrices are non-orthogonal, 3D transforms. - false); + scaleX, 0.0, 0.0, 0.0, + 0.0, scaleY, 0.0, 0.0, + 0.0, 0.0, scaleZ, 0.0, + 0.0, 0.0, 0.0, 1.0, + // Scale matrices are non-orthogonal, 3D transforms. + false); } - public static Matrix fromTranslation(Vec4 translation) - { - if (translation == null) - { + public static Matrix fromTranslation(Vec4 translation) { + if (translation == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -770,43 +687,40 @@ public static Matrix fromTranslation(Vec4 translation) return fromTranslation(translation.x, translation.y, translation.z); } - public static Matrix fromTranslation(double x, double y, double z) - { + public static Matrix fromTranslation(double x, double y, double z) { return new Matrix( - 1.0, 0.0, 0.0, x, - 0.0, 1.0, 0.0, y, - 0.0, 0.0, 1.0, z, - 0.0, 0.0, 0.0, 1.0, - // Translation matrices are orthogonal, 3D transforms. - true); + 1.0, 0.0, 0.0, x, + 0.0, 1.0, 0.0, y, + 0.0, 0.0, 1.0, z, + 0.0, 0.0, 0.0, 1.0, + // Translation matrices are orthogonal, 3D transforms. + true); } - public static Matrix fromSkew(Angle theta, Angle phi) - { + public static Matrix fromSkew(Angle theta, Angle phi) { // from http://faculty.juniata.edu/rhodes/graphics/projectionmat.htm double cotTheta = 1.0e6; double cotPhi = 1.0e6; - if (theta.getRadians() < EPSILON && phi.getRadians() < EPSILON) - { + if (theta.getRadians() < EPSILON && phi.getRadians() < EPSILON) { cotTheta = 0; cotPhi = 0; - } - else - { - if (Math.abs(Math.tan(theta.getRadians())) > EPSILON) + } else { + if (Math.abs(Math.tan(theta.getRadians())) > EPSILON) { cotTheta = 1 / Math.tan(theta.getRadians()); - if (Math.abs(Math.tan(phi.getRadians())) > EPSILON) + } + if (Math.abs(Math.tan(phi.getRadians())) > EPSILON) { cotPhi = 1 / Math.tan(phi.getRadians()); + } } return new Matrix( - 1.0, 0.0, -cotTheta, 0, - 0.0, 1.0, -cotPhi, 0, - 0.0, 0.0, 1.0, 0, - 0.0, 0.0, 0.0, 1.0, - false); + 1.0, 0.0, -cotTheta, 0, + 0.0, 1.0, -cotPhi, 0, + 0.0, 0.0, 1.0, 0, + 0.0, 0.0, 0.0, 1.0, + false); } /** @@ -817,40 +731,35 @@ public static Matrix fromSkew(Angle theta, Angle phi) * orthogonal to each other. * * @param origin the origin of the local coordinate system. - * @param axes an array must of three non-null vectors defining a local orientation in the following order: - * x-axis, y-axis, z-axis. + * @param axes an array must of three non-null vectors defining a local orientation in the following order: x-axis, + * y-axis, z-axis. * * @return a Matrix that transforms local coordinates to world coordinates. * * @throws IllegalArgumentException if origin is null, if axes is - * null, if axes contains less than three elements, or if - * any of the first three elements in axes is null. + * null, if axes contains less than three elements, or if any of the first three elements + * in axes is null. */ - public static Matrix fromLocalOrientation(Vec4 origin, Vec4[] axes) - { - if (origin == null) - { + public static Matrix fromLocalOrientation(Vec4 origin, Vec4[] axes) { + if (origin == null) { String msg = Logging.getMessage("nullValue.OriginIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (axes == null) - { + if (axes == null) { String msg = Logging.getMessage("nullValue.AxesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (axes.length < 3) - { + if (axes.length < 3) { String msg = Logging.getMessage("generic.ArrayInvalidLength", axes.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (axes[0] == null || axes[1] == null || axes[2] == null) - { + if (axes[0] == null || axes[1] == null || axes[2] == null) { String msg = Logging.getMessage("nullValue.AxesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -870,28 +779,24 @@ public static Matrix fromLocalOrientation(Vec4 origin, Vec4[] axes) * the up vector must not be parallel to the line of sight (the vector from the eye point to the reference center * point). * - * @param eye the eye point, in model coordinates. + * @param eye the eye point, in model coordinates. * @param center the scene's reference center point, in model coordinates. - * @param up the direction of the up vector, in model coordinates. + * @param up the direction of the up vector, in model coordinates. * * @return a viewing matrix in model coordinates defined by the specified eye point, reference center point, and up - * vector. + * vector. * * @throws IllegalArgumentException if any of the eye point, reference center point, or up vector are null, if the - * eye point and reference center point are coincident, or if the up vector and the - * line of sight are parallel. + * eye point and reference center point are coincident, or if the up vector and the line of sight are parallel. */ - public static Matrix fromViewLookAt(Vec4 eye, Vec4 center, Vec4 up) - { - if (eye == null || center == null || up == null) - { + public static Matrix fromViewLookAt(Vec4 eye, Vec4 center, Vec4 up) { + if (eye == null || center == null || up == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (eye.distanceTo3(center) <= EPSILON) - { + if (eye.distanceTo3(center) <= EPSILON) { String msg = Logging.getMessage("Geom.EyeAndCenterInvalid", eye, center); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -903,8 +808,7 @@ public static Matrix fromViewLookAt(Vec4 eye, Vec4 center, Vec4 up) Vec4 s = f.cross3(up); s = s.normalize3(); - if (s.getLength3() <= EPSILON) - { + if (s.getLength3() <= EPSILON) { String msg = Logging.getMessage("Geom.UpAndLineOfSightInvalid", up, forward); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -914,13 +818,13 @@ public static Matrix fromViewLookAt(Vec4 eye, Vec4 center, Vec4 up) u = u.normalize3(); Matrix mAxes = new Matrix( - s.x, s.y, s.z, 0.0, - u.x, u.y, u.z, 0.0, - -f.x, -f.y, -f.z, 0.0, - 0.0, 0.0, 0.0, 1.0, - true); + s.x, s.y, s.z, 0.0, + u.x, u.y, u.z, 0.0, + -f.x, -f.y, -f.z, 0.0, + 0.0, 0.0, 0.0, 1.0, + true); Matrix mEye = Matrix.fromTranslation( - -eye.x, -eye.y, -eye.z); + -eye.x, -eye.y, -eye.z); return mAxes.multiply(mEye); } @@ -932,28 +836,24 @@ public static Matrix fromViewLookAt(Vec4 eye, Vec4 center, Vec4 up) * coincident, and the up vector must not be parallel to the line of sight (the vector from the eye point to the * reference center point). * - * @param eye the eye point, in model coordinates. + * @param eye the eye point, in model coordinates. * @param center the scene's reference center point, in model coordinates. - * @param up the direction of the up vector, in model coordinates. + * @param up the direction of the up vector, in model coordinates. * * @return a viewing matrix in model coordinates defined by the specified eye point, reference center point, and up - * vector. + * vector. * * @throws IllegalArgumentException if any of the eye point, reference center point, or up vector are null, if the - * eye point and reference center point are coincident, or if the up vector and the - * line of sight are parallel. + * eye point and reference center point are coincident, or if the up vector and the line of sight are parallel. */ - public static Matrix fromModelLookAt(Vec4 eye, Vec4 center, Vec4 up) - { - if (eye == null || center == null || up == null) - { + public static Matrix fromModelLookAt(Vec4 eye, Vec4 center, Vec4 up) { + if (eye == null || center == null || up == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (eye.distanceTo3(center) <= EPSILON) - { + if (eye.distanceTo3(center) <= EPSILON) { String msg = Logging.getMessage("Geom.EyeAndCenterInvalid", eye, center); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -965,8 +865,7 @@ public static Matrix fromModelLookAt(Vec4 eye, Vec4 center, Vec4 up) Vec4 s = up.cross3(f); s = s.normalize3(); - if (s.getLength3() <= EPSILON) - { + if (s.getLength3() <= EPSILON) { String msg = Logging.getMessage("Geom.UpAndLineOfSightInvalid", up, forward); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -976,59 +875,51 @@ public static Matrix fromModelLookAt(Vec4 eye, Vec4 center, Vec4 up) u = u.normalize3(); Matrix mAxes = new Matrix( - s.x, u.x, f.x, 0.0, - s.y, u.y, f.y, 0.0, - s.z, u.z, f.z, 0.0, - 0.0, 0.0, 0.0, 1.0, - true); + s.x, u.x, f.x, 0.0, + s.y, u.y, f.y, 0.0, + s.z, u.z, f.z, 0.0, + 0.0, 0.0, 0.0, 1.0, + true); Matrix mEye = Matrix.fromTranslation( - eye.x, eye.y, eye.z); + eye.x, eye.y, eye.z); return mEye.multiply(mAxes); } public static Matrix fromPerspective(Angle horizontalFieldOfView, double viewportWidth, double viewportHeight, - double near, double far) - { - if (horizontalFieldOfView == null) - { + double near, double far) { + if (horizontalFieldOfView == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } double fovX = horizontalFieldOfView.degrees; - if (fovX <= 0.0 || fovX > 180.0) - { + if (fovX <= 0.0 || fovX > 180.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", "horizontalFieldOfView=" + fovX); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (viewportWidth <= 0.0) - { + if (viewportWidth <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", "viewportWidth=" + viewportWidth); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (viewportHeight <= 0.0) - { + if (viewportHeight <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", "viewportHeight=" + viewportHeight); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (near <= 0.0) - { + if (near <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", "near=" + near); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (far <= 0.0) - { + if (far <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", "far=" + far); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (far <= near) - { + if (far <= near) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", "far=" + far + ",near=" + near); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1038,112 +929,97 @@ public static Matrix fromPerspective(Angle horizontalFieldOfView, double viewpor // We are using *horizontal* field-of-view here. This results in a different matrix than documented in sources // using vertical field-of-view. return new Matrix( - f, 0.0, 0.0, 0.0, - 0.0, (f * viewportWidth) / viewportHeight, 0.0, 0.0, - 0.0, 0.0, -(far + near) / (far - near), -(2.0 * far * near) / (far - near), - 0.0, 0.0, -1.0, 0.0); + f, 0.0, 0.0, 0.0, + 0.0, (f * viewportWidth) / viewportHeight, 0.0, 0.0, + 0.0, 0.0, -(far + near) / (far - near), -(2.0 * far * near) / (far - near), + 0.0, 0.0, -1.0, 0.0); } - public static Matrix fromPerspective(double width, double height, double near, double far) - { - if (width <= 0.0) - { + public static Matrix fromPerspective(double width, double height, double near, double far) { + if (width <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", width); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (height <= 0.0) - { + if (height <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", height); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (near <= 0.0) - { + if (near <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", near); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (far <= 0.0) - { + if (far <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", far); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (far <= near) - { + if (far <= near) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", far); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Matrix( - 2.0 / width, 0.0, 0.0, 0.0, - 0.0, (2.0 * near) / height, 0.0, 0.0, - 0.0, 0.0, -(far + near) / (far - near), -(2.0 * far * near) / (far - near), - 0.0, 0.0, -1.0, 0.0); + 2.0 / width, 0.0, 0.0, 0.0, + 0.0, (2.0 * near) / height, 0.0, 0.0, + 0.0, 0.0, -(far + near) / (far - near), -(2.0 * far * near) / (far - near), + 0.0, 0.0, -1.0, 0.0); } - public static Matrix fromOrthographic(double width, double height, double near, double far) - { - if (width <= 0.0) - { + public static Matrix fromOrthographic(double width, double height, double near, double far) { + if (width <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", width); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (height <= 0.0) - { + if (height <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", height); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (near <= 0.0) - { + if (near <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", near); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (far <= 0.0) - { + if (far <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", far); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (far <= near) - { + if (far <= near) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", far); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Matrix( - 2.0 / width, 0.0, 0.0, 0.0, - 0.0, 2.0 / height, 0.0, 0.0, - 0.0, 0.0, -2.0 / (far - near), -(far + near) / (far - near), - 0.0, 0.0, 0.0, 1.0); + 2.0 / width, 0.0, 0.0, 0.0, + 0.0, 2.0 / height, 0.0, 0.0, + 0.0, 0.0, -2.0 / (far - near), -(far + near) / (far - near), + 0.0, 0.0, 0.0, 1.0); } - public static Matrix fromOrthographic2D(double width, double height) - { - if (width <= 0.0) - { + public static Matrix fromOrthographic2D(double width, double height) { + if (width <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", width); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (height <= 0.0) - { + if (height <= 0.0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", height); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Matrix( - 2.0 / width, 0.0, 0.0, 0.0, - 0.0, 2.0 / height, 0.0, 0.0, - 0.0, 0.0, -1.0, 0.0, - 0.0, 0.0, 0.0, 1.0); + 2.0 / width, 0.0, 0.0, 0.0, + 0.0, 2.0 / height, 0.0, 0.0, + 0.0, 0.0, -1.0, 0.0, + 0.0, 0.0, 0.0, 1.0); } /** @@ -1151,25 +1027,22 @@ public static Matrix fromOrthographic2D(double width, double height) * It is assumed that the destination grid is parallel with lines of latitude and longitude, and has its origin in * the upper left hand corner. * - * @param sector the grid sector. - * @param imageWidth the grid width. + * @param sector the grid sector. + * @param imageWidth the grid width. * @param imageHeight the grid height. * * @return Matrix that will map from grid coordinates to geographic coordinates in degrees. * * @throws IllegalArgumentException if sector is null, or if either width or - * height are less than 1. + * height are less than 1. */ - public static Matrix fromImageToGeographic(int imageWidth, int imageHeight, Sector sector) - { - if (imageWidth < 1 || imageHeight < 1) - { + public static Matrix fromImageToGeographic(int imageWidth, int imageHeight, Sector sector) { + if (imageWidth < 1 || imageHeight < 1) { String message = Logging.getMessage("generic.InvalidImageSize", imageWidth, imageHeight); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1177,23 +1050,20 @@ public static Matrix fromImageToGeographic(int imageWidth, int imageHeight, Sect // Transform from grid coordinates to geographic coordinates. Since the grid is parallel with lines of latitude // and longitude, this is a simple scale and translation. - double sx = sector.getDeltaLonDegrees() / imageWidth; double sy = -sector.getDeltaLatDegrees() / imageHeight; double tx = sector.getMinLongitude().degrees; double ty = sector.getMaxLatitude().degrees; return new Matrix( - sx, 0.0, tx, 0.0, - 0.0, sy, ty, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 0.0); + sx, 0.0, tx, 0.0, + 0.0, sy, ty, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 0.0); } - public static Matrix fromImageToGeographic(AVList worldFileParams) - { - if (worldFileParams == null) - { + public static Matrix fromImageToGeographic(AVList worldFileParams) { + if (worldFileParams == null) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1206,7 +1076,6 @@ public static Matrix fromImageToGeographic(AVList worldFileParams) // | a b c | | x | | lon | // | d e f | * | y | = | lat | // | 0 0 1 | | 1 | | 1 | - Double a = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_X_PIXEL_SIZE); Double d = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_Y_COEFFICIENT); Double b = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_X_COEFFICIENT); @@ -1214,22 +1083,19 @@ public static Matrix fromImageToGeographic(AVList worldFileParams) Double c = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_X_LOCATION); Double f = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_Y_LOCATION); - if (a == null || b == null || c == null || d == null || e == null || f == null) - { + if (a == null || b == null || c == null || d == null || e == null || f == null) { return null; } return new Matrix( - a, b, c, 0.0, - d, e, f, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 0.0); + a, b, c, 0.0, + d, e, f, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 0.0); } - public static Matrix fromGeographicToImage(AVList worldFileParams) - { - if (worldFileParams == null) - { + public static Matrix fromGeographicToImage(AVList worldFileParams) { + if (worldFileParams == null) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1278,7 +1144,6 @@ public static Matrix fromGeographicToImage(AVList worldFileParams) // d' = 0 // e' = 1/e // f' = -f/e - Double a = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_X_PIXEL_SIZE); Double d = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_Y_COEFFICIENT); Double b = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_X_COEFFICIENT); @@ -1286,21 +1151,17 @@ public static Matrix fromGeographicToImage(AVList worldFileParams) Double c = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_X_LOCATION); Double f = AVListImpl.getDoubleValue(worldFileParams, WorldFile.WORLD_FILE_Y_LOCATION); - if (a == null || b == null || c == null || d == null || e == null || f == null) - { + if (a == null || b == null || c == null || d == null || e == null || f == null) { return null; } - if (b == 0.0 && d == 0.0) - { + if (b == 0.0 && d == 0.0) { return new Matrix( - 1.0 / a, 0.0, (-c / a), 0.0, - 0.0, 1.0 / e, (-f / e), 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 0.0); - } - else - { + 1.0 / a, 0.0, (-c / a), 0.0, + 0.0, 1.0 / e, (-f / e), 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 0.0); + } else { double x0 = d - (e * a) / b; double ap = -e / (b * x0); double bp = 1.0 / x0; @@ -1312,10 +1173,10 @@ public static Matrix fromGeographicToImage(AVList worldFileParams) double fp = (d * c) / (a * y0) - f / y0; return new Matrix( - ap, bp, cp, 0.0, - dp, ep, fp, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 0.0); + ap, bp, cp, 0.0, + dp, ep, fp, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 0.0); } } @@ -1325,35 +1186,30 @@ public static Matrix fromGeographicToImage(AVList worldFileParams) * geographic location. * * @param imagePoints three control points in the source grid. - * @param geoPoints three geographic locations corresponding to each grid control point. + * @param geoPoints three geographic locations corresponding to each grid control point. * * @return Matrix that will map from geographic coordinates to grid coordinates in degrees. * * @throws IllegalArgumentException if either imagePoints or geoPoints is null or have - * length less than 3. + * length less than 3. */ - public static Matrix fromImageToGeographic(java.awt.geom.Point2D[] imagePoints, LatLon[] geoPoints) - { - if (imagePoints == null) - { + public static Matrix fromImageToGeographic(java.awt.geom.Point2D[] imagePoints, LatLon[] geoPoints) { + if (imagePoints == null) { String message = Logging.getMessage("nullValue.ImagePointsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (geoPoints == null) - { + if (geoPoints == null) { String message = Logging.getMessage("nullValue.GeoPointsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (imagePoints.length < 3) - { + if (imagePoints.length < 3) { String message = Logging.getMessage("generic.ArrayInvalidLength", "imagePoints.length < 3"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (geoPoints.length < 3) - { + if (geoPoints.length < 3) { String message = Logging.getMessage("generic.ArrayInvalidLength", "geoPoints.length < 3"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1387,7 +1243,6 @@ public static Matrix fromImageToGeographic(java.awt.geom.Point2D[] imagePoints, // d = (1/d0) * [(lat3-lat1) - (lat2-lat1)*(y3-y1)/(y2-y1)] // e = (lat2-lat1)/(y2-y1) - d*(x2-x1)/(y2-y1) // f = lat1 - d*x1 - e*y1 - double lat1 = geoPoints[0].getLatitude().degrees; double lat2 = geoPoints[1].getLatitude().degrees; double lat3 = geoPoints[2].getLatitude().degrees; @@ -1413,34 +1268,29 @@ public static Matrix fromImageToGeographic(java.awt.geom.Point2D[] imagePoints, double f = lat1 - d * x1 - e * y1; return new Matrix( - a, b, c, 0.0, - d, e, f, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 0.0); + a, b, c, 0.0, + d, e, f, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 0.0); } - public static Matrix fromGeographicToImage(java.awt.geom.Point2D[] imagePoints, LatLon[] geoPoints) - { - if (imagePoints == null) - { + public static Matrix fromGeographicToImage(java.awt.geom.Point2D[] imagePoints, LatLon[] geoPoints) { + if (imagePoints == null) { String message = Logging.getMessage("nullValue.ImagePointsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (geoPoints == null) - { + if (geoPoints == null) { String message = Logging.getMessage("nullValue.GeoPointsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (imagePoints.length < 3) - { + if (imagePoints.length < 3) { String message = Logging.getMessage("generic.ArrayInvalidLength", "imagePoints.length < 3"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (geoPoints.length < 3) - { + if (geoPoints.length < 3) { String message = Logging.getMessage("generic.ArrayInvalidLength", "geoPoints.length < 3"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1474,7 +1324,6 @@ public static Matrix fromGeographicToImage(java.awt.geom.Point2D[] imagePoints, // d = (1/d0) * [(y3-y1) - (y2-y1)*(lat3-lat1)/(lat2-lat1)] // e = (y2-y1)/(lat2-lat1) - d*(lon2-lon1)/(lat2-lat1) // f = y1 - d*lon1 - e*lat1 - double lat1 = geoPoints[0].getLatitude().degrees; double lat2 = geoPoints[1].getLatitude().degrees; double lat3 = geoPoints[2].getLatitude().degrees; @@ -1500,10 +1349,10 @@ public static Matrix fromGeographicToImage(java.awt.geom.Point2D[] imagePoints, double f = y1 - d * lon1 - e * lat1; return new Matrix( - a, b, c, 0.0, - d, e, f, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 0.0); + a, b, c, 0.0, + d, e, f, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 0.0); } /** @@ -1511,34 +1360,30 @@ public static Matrix fromGeographicToImage(java.awt.geom.Point2D[] imagePoints, * width and height and centered at the point (x, y). * * @param sector the geographic region which will be mapped to the Cartesian region - * @param x x-coordinate of lower left hand corner of the Cartesian region - * @param y y-coordinate of lower left hand corner of the Cartesian region - * @param width width of the Cartesian region, extending to the right from the x-coordinate + * @param x x-coordinate of lower left hand corner of the Cartesian region + * @param y y-coordinate of lower left hand corner of the Cartesian region + * @param width width of the Cartesian region, extending to the right from the x-coordinate * @param height height of the Cartesian region, extending up from the y-coordinate * * @return Matrix that will map from the geographic region to the Cartesian region. * * @throws IllegalArgumentException if sector is null, or if width or height - * are less than zero. + * are less than zero. */ - public static Matrix fromGeographicToViewport(Sector sector, int x, int y, int width, int height) - { - if (sector == null) - { + public static Matrix fromGeographicToViewport(Sector sector, int x, int y, int width, int height) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (width <= 0) - { + if (width <= 0) { String message = Logging.getMessage("Geom.WidthInvalid", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("Geom.HeightInvalid", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1546,11 +1391,11 @@ public static Matrix fromGeographicToViewport(Sector sector, int x, int y, int w Matrix transform = Matrix.IDENTITY; transform = transform.multiply( - Matrix.fromTranslation(-x, -y, 0.0)); + Matrix.fromTranslation(-x, -y, 0.0)); transform = transform.multiply( - Matrix.fromScale(width / sector.getDeltaLonDegrees(), height / sector.getDeltaLatDegrees(), 1.0)); + Matrix.fromScale(width / sector.getDeltaLonDegrees(), height / sector.getDeltaLatDegrees(), 1.0)); transform = transform.multiply( - Matrix.fromTranslation(-sector.getMinLongitude().degrees, -sector.getMinLatitude().degrees, 0.0)); + Matrix.fromTranslation(-sector.getMinLongitude().degrees, -sector.getMinLatitude().degrees, 0.0)); return transform; } @@ -1560,34 +1405,30 @@ public static Matrix fromGeographicToViewport(Sector sector, int x, int y, int w * and centered at the point (x, y) to the geographic region defined by sector onto . * * @param sector the geographic region the Cartesian region will be mapped to - * @param x x-coordinate of lower left hand corner of the Cartesian region - * @param y y-coordinate of lower left hand corner of the Cartesian region - * @param width width of the Cartesian region, extending to the right from the x-coordinate + * @param x x-coordinate of lower left hand corner of the Cartesian region + * @param y y-coordinate of lower left hand corner of the Cartesian region + * @param width width of the Cartesian region, extending to the right from the x-coordinate * @param height height of the Cartesian region, extending up from the y-coordinate * * @return Matrix that will map from Cartesian region to the geographic region. * * @throws IllegalArgumentException if sector is null, or if width or height - * are less than zero. + * are less than zero. */ - public static Matrix fromViewportToGeographic(Sector sector, int x, int y, int width, int height) - { - if (sector == null) - { + public static Matrix fromViewportToGeographic(Sector sector, int x, int y, int width, int height) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (width <= 0) - { + if (width <= 0) { String message = Logging.getMessage("Geom.WidthInvalid", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("Geom.HeightInvalid", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1595,11 +1436,11 @@ public static Matrix fromViewportToGeographic(Sector sector, int x, int y, int w Matrix transform = Matrix.IDENTITY; transform = transform.multiply( - Matrix.fromTranslation(sector.getMinLongitude().degrees, sector.getMinLatitude().degrees, 0.0)); + Matrix.fromTranslation(sector.getMinLongitude().degrees, sector.getMinLatitude().degrees, 0.0)); transform = transform.multiply( - Matrix.fromScale(sector.getDeltaLonDegrees() / width, sector.getDeltaLatDegrees() / height, 1.0)); + Matrix.fromScale(sector.getDeltaLonDegrees() / width, sector.getDeltaLatDegrees() / height, 1.0)); transform = transform.multiply( - Matrix.fromTranslation(x, y, 0.0)); + Matrix.fromTranslation(x, y, 0.0)); return transform; } @@ -1611,7 +1452,7 @@ public static Matrix fromViewportToGeographic(Sector sector, int x, int y, int w * The returned covariance matrix represents the correlation between each pair of x-, y-, and z-coordinates as * they're distributed about the point Iterable's arithmetic mean. Its layout is as follows: *

        - * C(x, x) C(x, y) C(x, z)
        C(x, y) C(y, y) C(y, z)
        C(x, z) C(y, z) C(z, z)
        + * C(x, x) C(x, y) C(x, z)
        C(x, y) C(y, y) C(y, z)
        C(x, z) C(y, z) C(z, z)
        *

        * C(i, j) is the covariance of coordinates i and j, where i or j are a coordinate's dispersion about its mean * value. If any entry is zero, then there's no correlation between the two coordinates defining that entry. If the @@ -1624,18 +1465,17 @@ public static Matrix fromViewportToGeographic(Sector sector, int x, int y, int w * * @throws IllegalArgumentException if the points Iterable is null. */ - public static Matrix fromCovarianceOfVertices(Iterable points) - { - if (points == null) - { + public static Matrix fromCovarianceOfVertices(Iterable points) { + if (points == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Vec4 mean = Vec4.computeAveragePoint(points); - if (mean == null) + if (mean == null) { return null; + } int count = 0; double c11 = 0d; @@ -1645,10 +1485,10 @@ public static Matrix fromCovarianceOfVertices(Iterable points) double c13 = 0d; double c23 = 0d; - for (Vec4 vec : points) - { - if (vec == null) + for (Vec4 vec : points) { + if (vec == null) { continue; + } count++; c11 += (vec.x - mean.x) * (vec.x - mean.x); @@ -1659,14 +1499,15 @@ public static Matrix fromCovarianceOfVertices(Iterable points) c23 += (vec.y - mean.y) * (vec.z - mean.z); // c23 = c32 } - if (count == 0) + if (count == 0) { return null; + } return new Matrix( - c11 / (double) count, c12 / (double) count, c13 / (double) count, 0d, - c12 / (double) count, c22 / (double) count, c23 / (double) count, 0d, - c13 / (double) count, c23 / (double) count, c33 / (double) count, 0d, - 0d, 0d, 0d, 0d); + c11 / (double) count, c12 / (double) count, c13 / (double) count, 0d, + c12 / (double) count, c22 / (double) count, c23 / (double) count, 0d, + c13 / (double) count, c23 / (double) count, c33 / (double) count, 0d, + 0d, 0d, 0d, 0d); } /** @@ -1676,7 +1517,7 @@ public static Matrix fromCovarianceOfVertices(Iterable points) * The returned covariance matrix represents the correlation between each pair of x-, y-, and z-coordinates as * they're distributed about the points arithmetic mean. Its layout is as follows: *

        - * C(x, x) C(x, y) C(x, z)
        C(x, y) C(y, y) C(y, z)
        C(x, z) C(y, z) C(z, z)
        + * C(x, x) C(x, y) C(x, z)
        C(x, y) C(y, y) C(y, z)
        C(x, z) C(y, z) C(z, z)
        *

        * C(i, j) is the covariance of coordinates i and j, where i or j are a coordinate's dispersion about its mean * value. If any entry is zero, then there's no correlation between the two coordinates defining that entry. If the @@ -1691,32 +1532,30 @@ public static Matrix fromCovarianceOfVertices(Iterable points) * remaining elements that follow the last complete tuple. * * @param coordinates the buffer containing the point coordinates for which to compute a Covariance matrix. - * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, - * this interprets the buffer has having tightly packed XYZ coordinate tuples. + * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, this + * interprets the buffer has having tightly packed XYZ coordinate tuples. * * @return the covariance matrix for the buffer of points. * * @throws IllegalArgumentException if the buffer is null, or if the stride is less than three. */ - public static Matrix fromCovarianceOfVertices(BufferWrapper coordinates, int stride) - { - if (coordinates == null) - { + public static Matrix fromCovarianceOfVertices(BufferWrapper coordinates, int stride) { + if (coordinates == null) { String msg = Logging.getMessage("nullValue.CoordinatesAreNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (stride < 3) - { + if (stride < 3) { String msg = Logging.getMessage("generic.StrideIsInvalid"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Vec4 mean = Vec4.computeAveragePoint3(coordinates, stride); - if (mean == null) + if (mean == null) { return null; + } int count = 0; double c11 = 0d; @@ -1726,8 +1565,7 @@ public static Matrix fromCovarianceOfVertices(BufferWrapper coordinates, int str double c13 = 0d; double c23 = 0d; - for (int i = 0; i <= coordinates.length() - stride; i += stride) - { + for (int i = 0; i <= coordinates.length() - stride; i += stride) { double x = coordinates.getDouble(i); double y = coordinates.getDouble(i + 1); double z = coordinates.getDouble(i + 2); @@ -1740,14 +1578,15 @@ public static Matrix fromCovarianceOfVertices(BufferWrapper coordinates, int str c23 += (y - mean.y) * (z - mean.z); // c23 = c32 } - if (count == 0) + if (count == 0) { return null; + } return new Matrix( - c11 / (double) count, c12 / (double) count, c13 / (double) count, 0d, - c12 / (double) count, c22 / (double) count, c23 / (double) count, 0d, - c13 / (double) count, c23 / (double) count, c33 / (double) count, 0d, - 0d, 0d, 0d, 0d); + c11 / (double) count, c12 / (double) count, c13 / (double) count, 0d, + c12 / (double) count, c22 / (double) count, c23 / (double) count, 0d, + c13 / (double) count, c23 / (double) count, c33 / (double) count, 0d, + 0d, 0d, 0d, 0d); } /** @@ -1757,26 +1596,22 @@ public static Matrix fromCovarianceOfVertices(BufferWrapper coordinates, int str * entries of array outEigenValues, and the corresponding eigenvectors in the entires of array * outEigenVectors. These arrays must be non-null, and have length three or greater. * - * @param matrix the symmetric Matrix for which to compute an eigensystem. - * @param outEigenvalues the array which receives the three output eigenvalues. + * @param matrix the symmetric Matrix for which to compute an eigensystem. + * @param outEigenvalues the array which receives the three output eigenvalues. * @param outEigenvectors the array which receives the three output eigenvectors. * * @throws IllegalArgumentException if the Matrix is null or is not symmetric, if the output eigenvalue array is - * null or has length less than 3, or if the output eigenvector is null or has - * length less than 3. + * null or has length less than 3, or if the output eigenvector is null or has length less than 3. */ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[] outEigenvalues, - Vec4[] outEigenvectors) - { - if (matrix == null) - { + Vec4[] outEigenvectors) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (matrix.m12 != matrix.m21 || matrix.m13 != matrix.m31 || matrix.m23 != matrix.m32) - { + if (matrix.m12 != matrix.m21 || matrix.m13 != matrix.m31 || matrix.m23 != matrix.m32) { String msg = Logging.getMessage("generic.MatrixNotSymmetric", matrix); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1784,7 +1619,6 @@ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[ // Take from "Mathematics for 3D Game Programming and Computer Graphics, Second Edition" by Eric Lengyel, // Listing 14.6 (pages 441-444). - final double EPSILON = 1.0e-10; final int MAX_SWEEPS = 32; @@ -1800,21 +1634,20 @@ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[ double[][] r = new double[3][3]; r[0][0] = r[1][1] = r[2][2] = 1d; - for (int a = 0; a < MAX_SWEEPS; a++) - { + for (int a = 0; a < MAX_SWEEPS; a++) { // Exit if off-diagonal entries small enough - if ((Math.abs(m12) < EPSILON) && (Math.abs(m13) < EPSILON) && (Math.abs(m23) < EPSILON)) + if ((Math.abs(m12) < EPSILON) && (Math.abs(m13) < EPSILON) && (Math.abs(m23) < EPSILON)) { break; + } // Annihilate (1,2) entry - if (m12 != 0d) - { + if (m12 != 0d) { double u = (m22 - m11) * 0.5 / m12; double u2 = u * u; double u2p1 = u2 + 1d; - double t = (u2p1 != u2) ? - ((u < 0d) ? -1d : 1d) * (Math.sqrt(u2p1) - Math.abs(u)) - : 0.5 / u; + double t = (u2p1 != u2) + ? ((u < 0d) ? -1d : 1d) * (Math.sqrt(u2p1) - Math.abs(u)) + : 0.5 / u; double c = 1d / Math.sqrt(t * t + 1d); double s = c * t; @@ -1826,8 +1659,7 @@ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[ m23 = s * m13 + c * m23; m13 = temp; - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { temp = c * r[i][0] - s * r[i][1]; r[i][1] = s * r[i][0] + c * r[i][1]; r[i][0] = temp; @@ -1835,14 +1667,13 @@ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[ } // Annihilate (1,3) entry - if (m13 != 0d) - { + if (m13 != 0d) { double u = (m33 - m11) * 0.5 / m13; double u2 = u * u; double u2p1 = u2 + 1d; - double t = (u2p1 != u2) ? - ((u < 0d) ? -1d : 1d) * (Math.sqrt(u2p1) - Math.abs(u)) - : 0.5 / u; + double t = (u2p1 != u2) + ? ((u < 0d) ? -1d : 1d) * (Math.sqrt(u2p1) - Math.abs(u)) + : 0.5 / u; double c = 1d / Math.sqrt(t * t + 1d); double s = c * t; @@ -1854,8 +1685,7 @@ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[ m23 = s * m12 + c * m23; m12 = temp; - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { temp = c * r[i][0] - s * r[i][2]; r[i][2] = s * r[i][0] + c * r[i][2]; r[i][0] = temp; @@ -1863,14 +1693,13 @@ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[ } // Annihilate (2,3) entry - if (m23 != 0d) - { + if (m23 != 0d) { double u = (m33 - m22) * 0.5 / m23; double u2 = u * u; double u2p1 = u2 + 1d; - double t = (u2p1 != u2) ? - ((u < 0d) ? -1d : 1d) * (Math.sqrt(u2p1) - Math.abs(u)) - : 0.5 / u; + double t = (u2p1 != u2) + ? ((u < 0d) ? -1d : 1d) * (Math.sqrt(u2p1) - Math.abs(u)) + : 0.5 / u; double c = 1d / Math.sqrt(t * t + 1d); double s = c * t; @@ -1882,8 +1711,7 @@ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[ m13 = s * m12 + c * m13; m12 = temp; - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { temp = c * r[i][1] - s * r[i][2]; r[i][2] = s * r[i][1] + c * r[i][2]; r[i][1] = temp; @@ -1903,184 +1731,165 @@ public static void computeEigensystemFromSymmetricMatrix3(Matrix matrix, double[ // ============== Arithmetic Functions ======================= // // ============== Arithmetic Functions ======================= // // ============== Arithmetic Functions ======================= // - - public final Matrix add(Matrix matrix) - { - if (matrix == null) - { + public final Matrix add(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Matrix( - this.m11 + matrix.m11, this.m12 + matrix.m12, this.m13 + matrix.m13, this.m14 + matrix.m14, - this.m21 + matrix.m21, this.m22 + matrix.m22, this.m23 + matrix.m23, this.m24 + matrix.m24, - this.m31 + matrix.m31, this.m32 + matrix.m32, this.m33 + matrix.m33, this.m34 + matrix.m34, - this.m41 + matrix.m41, this.m42 + matrix.m42, this.m43 + matrix.m43, this.m44 + matrix.m44); + this.m11 + matrix.m11, this.m12 + matrix.m12, this.m13 + matrix.m13, this.m14 + matrix.m14, + this.m21 + matrix.m21, this.m22 + matrix.m22, this.m23 + matrix.m23, this.m24 + matrix.m24, + this.m31 + matrix.m31, this.m32 + matrix.m32, this.m33 + matrix.m33, this.m34 + matrix.m34, + this.m41 + matrix.m41, this.m42 + matrix.m42, this.m43 + matrix.m43, this.m44 + matrix.m44); } - public final Matrix subtract(Matrix matrix) - { - if (matrix == null) - { + public final Matrix subtract(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Matrix( - this.m11 - matrix.m11, this.m12 - matrix.m12, this.m13 - matrix.m13, this.m14 - matrix.m14, - this.m21 - matrix.m21, this.m22 - matrix.m22, this.m23 - matrix.m23, this.m24 - matrix.m24, - this.m31 - matrix.m31, this.m32 - matrix.m32, this.m33 - matrix.m33, this.m34 - matrix.m34, - this.m41 - matrix.m41, this.m42 - matrix.m42, this.m43 - matrix.m43, this.m44 - matrix.m44); + this.m11 - matrix.m11, this.m12 - matrix.m12, this.m13 - matrix.m13, this.m14 - matrix.m14, + this.m21 - matrix.m21, this.m22 - matrix.m22, this.m23 - matrix.m23, this.m24 - matrix.m24, + this.m31 - matrix.m31, this.m32 - matrix.m32, this.m33 - matrix.m33, this.m34 - matrix.m34, + this.m41 - matrix.m41, this.m42 - matrix.m42, this.m43 - matrix.m43, this.m44 - matrix.m44); } - public final Matrix multiplyComponents(double value) - { + public final Matrix multiplyComponents(double value) { return new Matrix( - this.m11 * value, this.m12 * value, this.m13 * value, this.m14 * value, - this.m21 * value, this.m22 * value, this.m23 * value, this.m24 * value, - this.m31 * value, this.m32 * value, this.m33 * value, this.m34 * value, - this.m41 * value, this.m42 * value, this.m43 * value, this.m44 * value); + this.m11 * value, this.m12 * value, this.m13 * value, this.m14 * value, + this.m21 * value, this.m22 * value, this.m23 * value, this.m24 * value, + this.m31 * value, this.m32 * value, this.m33 * value, this.m34 * value, + this.m41 * value, this.m42 * value, this.m43 * value, this.m44 * value); } - public final Matrix multiply(Matrix matrix) - { - if (matrix == null) - { + public final Matrix multiply(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Matrix( - // Row 1 - (this.m11 * matrix.m11) + (this.m12 * matrix.m21) + (this.m13 * matrix.m31) + (this.m14 * matrix.m41), - (this.m11 * matrix.m12) + (this.m12 * matrix.m22) + (this.m13 * matrix.m32) + (this.m14 * matrix.m42), - (this.m11 * matrix.m13) + (this.m12 * matrix.m23) + (this.m13 * matrix.m33) + (this.m14 * matrix.m43), - (this.m11 * matrix.m14) + (this.m12 * matrix.m24) + (this.m13 * matrix.m34) + (this.m14 * matrix.m44), - // Row 2 - (this.m21 * matrix.m11) + (this.m22 * matrix.m21) + (this.m23 * matrix.m31) + (this.m24 * matrix.m41), - (this.m21 * matrix.m12) + (this.m22 * matrix.m22) + (this.m23 * matrix.m32) + (this.m24 * matrix.m42), - (this.m21 * matrix.m13) + (this.m22 * matrix.m23) + (this.m23 * matrix.m33) + (this.m24 * matrix.m43), - (this.m21 * matrix.m14) + (this.m22 * matrix.m24) + (this.m23 * matrix.m34) + (this.m24 * matrix.m44), - // Row 3 - (this.m31 * matrix.m11) + (this.m32 * matrix.m21) + (this.m33 * matrix.m31) + (this.m34 * matrix.m41), - (this.m31 * matrix.m12) + (this.m32 * matrix.m22) + (this.m33 * matrix.m32) + (this.m34 * matrix.m42), - (this.m31 * matrix.m13) + (this.m32 * matrix.m23) + (this.m33 * matrix.m33) + (this.m34 * matrix.m43), - (this.m31 * matrix.m14) + (this.m32 * matrix.m24) + (this.m33 * matrix.m34) + (this.m34 * matrix.m44), - // Row 4 - (this.m41 * matrix.m11) + (this.m42 * matrix.m21) + (this.m43 * matrix.m31) + (this.m44 * matrix.m41), - (this.m41 * matrix.m12) + (this.m42 * matrix.m22) + (this.m43 * matrix.m32) + (this.m44 * matrix.m42), - (this.m41 * matrix.m13) + (this.m42 * matrix.m23) + (this.m43 * matrix.m33) + (this.m44 * matrix.m43), - (this.m41 * matrix.m14) + (this.m42 * matrix.m24) + (this.m43 * matrix.m34) + (this.m44 * matrix.m44), - // Product of orthonormal 3D transform matrices is also an orthonormal 3D transform. - this.isOrthonormalTransform && matrix.isOrthonormalTransform); + // Row 1 + (this.m11 * matrix.m11) + (this.m12 * matrix.m21) + (this.m13 * matrix.m31) + (this.m14 * matrix.m41), + (this.m11 * matrix.m12) + (this.m12 * matrix.m22) + (this.m13 * matrix.m32) + (this.m14 * matrix.m42), + (this.m11 * matrix.m13) + (this.m12 * matrix.m23) + (this.m13 * matrix.m33) + (this.m14 * matrix.m43), + (this.m11 * matrix.m14) + (this.m12 * matrix.m24) + (this.m13 * matrix.m34) + (this.m14 * matrix.m44), + // Row 2 + (this.m21 * matrix.m11) + (this.m22 * matrix.m21) + (this.m23 * matrix.m31) + (this.m24 * matrix.m41), + (this.m21 * matrix.m12) + (this.m22 * matrix.m22) + (this.m23 * matrix.m32) + (this.m24 * matrix.m42), + (this.m21 * matrix.m13) + (this.m22 * matrix.m23) + (this.m23 * matrix.m33) + (this.m24 * matrix.m43), + (this.m21 * matrix.m14) + (this.m22 * matrix.m24) + (this.m23 * matrix.m34) + (this.m24 * matrix.m44), + // Row 3 + (this.m31 * matrix.m11) + (this.m32 * matrix.m21) + (this.m33 * matrix.m31) + (this.m34 * matrix.m41), + (this.m31 * matrix.m12) + (this.m32 * matrix.m22) + (this.m33 * matrix.m32) + (this.m34 * matrix.m42), + (this.m31 * matrix.m13) + (this.m32 * matrix.m23) + (this.m33 * matrix.m33) + (this.m34 * matrix.m43), + (this.m31 * matrix.m14) + (this.m32 * matrix.m24) + (this.m33 * matrix.m34) + (this.m34 * matrix.m44), + // Row 4 + (this.m41 * matrix.m11) + (this.m42 * matrix.m21) + (this.m43 * matrix.m31) + (this.m44 * matrix.m41), + (this.m41 * matrix.m12) + (this.m42 * matrix.m22) + (this.m43 * matrix.m32) + (this.m44 * matrix.m42), + (this.m41 * matrix.m13) + (this.m42 * matrix.m23) + (this.m43 * matrix.m33) + (this.m44 * matrix.m43), + (this.m41 * matrix.m14) + (this.m42 * matrix.m24) + (this.m43 * matrix.m34) + (this.m44 * matrix.m44), + // Product of orthonormal 3D transform matrices is also an orthonormal 3D transform. + this.isOrthonormalTransform && matrix.isOrthonormalTransform); } - public final Matrix divideComponents(double value) - { - if (isZero(value)) - { + public final Matrix divideComponents(double value) { + if (isZero(value)) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", value); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Matrix( - this.m11 / value, this.m12 / value, this.m13 / value, this.m14 / value, - this.m21 / value, this.m22 / value, this.m23 / value, this.m24 / value, - this.m31 / value, this.m32 / value, this.m33 / value, this.m34 / value, - this.m41 / value, this.m42 / value, this.m43 / value, this.m44 / value); + this.m11 / value, this.m12 / value, this.m13 / value, this.m14 / value, + this.m21 / value, this.m22 / value, this.m23 / value, this.m24 / value, + this.m31 / value, this.m32 / value, this.m33 / value, this.m34 / value, + this.m41 / value, this.m42 / value, this.m43 / value, this.m44 / value); } - public final Matrix divideComponents(Matrix matrix) - { - if (matrix == null) - { + public final Matrix divideComponents(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Matrix( - this.m11 / matrix.m11, this.m12 / matrix.m12, this.m13 / matrix.m13, this.m14 / matrix.m14, - this.m21 / matrix.m21, this.m22 / matrix.m22, this.m23 / matrix.m23, this.m24 / matrix.m24, - this.m31 / matrix.m31, this.m32 / matrix.m32, this.m33 / matrix.m33, this.m34 / matrix.m34, - this.m41 / matrix.m41, this.m42 / matrix.m42, this.m43 / matrix.m43, this.m44 / matrix.m44); + this.m11 / matrix.m11, this.m12 / matrix.m12, this.m13 / matrix.m13, this.m14 / matrix.m14, + this.m21 / matrix.m21, this.m22 / matrix.m22, this.m23 / matrix.m23, this.m24 / matrix.m24, + this.m31 / matrix.m31, this.m32 / matrix.m32, this.m33 / matrix.m33, this.m34 / matrix.m34, + this.m41 / matrix.m41, this.m42 / matrix.m42, this.m43 / matrix.m43, this.m44 / matrix.m44); } - public final Matrix negate() - { + public final Matrix negate() { return new Matrix( - 0.0 - this.m11, 0.0 - this.m12, 0.0 - this.m13, 0.0 - this.m14, - 0.0 - this.m21, 0.0 - this.m22, 0.0 - this.m23, 0.0 - this.m24, - 0.0 - this.m31, 0.0 - this.m32, 0.0 - this.m33, 0.0 - this.m34, - 0.0 - this.m41, 0.0 - this.m42, 0.0 - this.m43, 0.0 - this.m44, - // Negative of orthonormal 3D transform matrix is also an orthonormal 3D transform. - this.isOrthonormalTransform); + 0.0 - this.m11, 0.0 - this.m12, 0.0 - this.m13, 0.0 - this.m14, + 0.0 - this.m21, 0.0 - this.m22, 0.0 - this.m23, 0.0 - this.m24, + 0.0 - this.m31, 0.0 - this.m32, 0.0 - this.m33, 0.0 - this.m34, + 0.0 - this.m41, 0.0 - this.m42, 0.0 - this.m43, 0.0 - this.m44, + // Negative of orthonormal 3D transform matrix is also an orthonormal 3D transform. + this.isOrthonormalTransform); } - public final Vec4 transformBy3(Matrix matrix, double x, double y, double z) - { - if (matrix == null) - { + public final Vec4 transformBy3(Matrix matrix, double x, double y, double z) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - (matrix.m11 * x) + (matrix.m12 * y) + (matrix.m13 * z), - (matrix.m21 * x) + (matrix.m22 * y) + (matrix.m23 * z), - (matrix.m31 * x) + (matrix.m32 * y) + (matrix.m33 * z)); + (matrix.m11 * x) + (matrix.m12 * y) + (matrix.m13 * z), + (matrix.m21 * x) + (matrix.m22 * y) + (matrix.m23 * z), + (matrix.m31 * x) + (matrix.m32 * y) + (matrix.m33 * z)); } // ============== Matrix Arithmetic Functions ======================= // // ============== Matrix Arithmetic Functions ======================= // // ============== Matrix Arithmetic Functions ======================= // - - public final double getDeterminant() - { + public final double getDeterminant() { double result = 0.0; // Columns 2, 3, 4. - result += this.m11 * - (this.m22 * (this.m33 * this.m44 - this.m43 * this.m34) + result += this.m11 + * (this.m22 * (this.m33 * this.m44 - this.m43 * this.m34) - this.m23 * (this.m32 * this.m44 - this.m42 * this.m34) + this.m24 * (this.m32 * this.m43 - this.m42 * this.m33)); // Columns 1, 3, 4. - result -= this.m12 * - (this.m21 * (this.m33 * this.m44 - this.m43 * this.m34) + result -= this.m12 + * (this.m21 * (this.m33 * this.m44 - this.m43 * this.m34) - this.m23 * (this.m31 * this.m44 - this.m41 * this.m34) + this.m24 * (this.m31 * this.m43 - this.m41 * this.m33)); // Columns 1, 2, 4. - result += this.m13 * - (this.m21 * (this.m32 * this.m44 - this.m42 * this.m34) + result += this.m13 + * (this.m21 * (this.m32 * this.m44 - this.m42 * this.m34) - this.m22 * (this.m31 * this.m44 - this.m41 * this.m34) + this.m24 * (this.m31 * this.m42 - this.m41 * this.m32)); // Columns 1, 2, 3. - result -= this.m14 * - (this.m21 * (this.m32 * this.m43 - this.m42 - this.m33) + result -= this.m14 + * (this.m21 * (this.m32 * this.m43 - this.m42 - this.m33) - this.m22 * (this.m31 * this.m43 - this.m41 * this.m33) + this.m23 * (this.m31 * this.m42 - this.m41 * this.m32)); return result; } - public final Matrix getTranspose() - { + public final Matrix getTranspose() { // Swap rows with columns. return new Matrix( - this.m11, this.m21, this.m31, this.m41, - this.m12, this.m22, this.m32, this.m42, - this.m13, this.m23, this.m33, this.m43, - this.m14, this.m24, this.m34, this.m44, - // Transpose of orthonormal 3D transform matrix is not an orthonormal 3D transform matrix. - false); + this.m11, this.m21, this.m31, this.m41, + this.m12, this.m22, this.m32, this.m42, + this.m13, this.m23, this.m33, this.m43, + this.m14, this.m24, this.m34, this.m44, + // Transpose of orthonormal 3D transform matrix is not an orthonormal 3D transform matrix. + false); } - public final double getTrace() - { + public final double getTrace() { return this.m11 + this.m22 + this.m33 + this.m44; } @@ -2089,28 +1898,26 @@ public final double getTrace() * * @return the inverse of this matrix, or null if this matrix has no inverse. */ - public final Matrix getInverse() - { - if (this.isOrthonormalTransform) + public final Matrix getInverse() { + if (this.isOrthonormalTransform) { return computeTransformInverse(this); - else + } else { return computeGeneralInverse(this); + } } - private static Matrix computeTransformInverse(Matrix a) - { + private static Matrix computeTransformInverse(Matrix a) { // 'a' is assumed to contain a 3D transformation matrix. // Upper-3x3 is inverted, translation is transformed by inverted-upper-3x3 and negated. return new Matrix( - a.m11, a.m21, a.m31, 0.0 - (a.m11 * a.m14) - (a.m21 * a.m24) - (a.m31 * a.m34), - a.m12, a.m22, a.m32, 0.0 - (a.m12 * a.m14) - (a.m22 * a.m24) - (a.m32 * a.m34), - a.m13, a.m23, a.m33, 0.0 - (a.m13 * a.m14) - (a.m23 * a.m24) - (a.m33 * a.m34), - 0.0, 0.0, 0.0, 1.0, - false); // Inverse of an orthogonal, 3D transform matrix is not an orthogonal 3D transform. + a.m11, a.m21, a.m31, 0.0 - (a.m11 * a.m14) - (a.m21 * a.m24) - (a.m31 * a.m34), + a.m12, a.m22, a.m32, 0.0 - (a.m12 * a.m14) - (a.m22 * a.m24) - (a.m32 * a.m34), + a.m13, a.m23, a.m33, 0.0 - (a.m13 * a.m14) - (a.m23 * a.m24) - (a.m33 * a.m34), + 0.0, 0.0, 0.0, 1.0, + false); // Inverse of an orthogonal, 3D transform matrix is not an orthogonal 3D transform. } - private static Matrix computeGeneralInverse(Matrix a) - { + private static Matrix computeGeneralInverse(Matrix a) { // Copy the specified matrix into a mutable two-dimensional array. double[][] A = new double[4][4]; A[0][0] = a.m11; @@ -2134,70 +1941,59 @@ private static Matrix computeGeneralInverse(Matrix a) double d = ludcmp(A, indx); // Compute the matrix's determinant. - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { d *= A[i][i]; } // The matrix is singular if its determinant is zero or very close to zero. - if (Math.abs(d) < NEAR_ZERO_THRESHOLD) + if (Math.abs(d) < NEAR_ZERO_THRESHOLD) { return null; + } double[][] Y = new double[4][4]; double[] col = new double[4]; - for (int j = 0; j < 4; j++) - { - for (int i = 0; i < 4; i++) - { + for (int j = 0; j < 4; j++) { + for (int i = 0; i < 4; i++) { col[i] = 0.0; } col[j] = 1.0; lubksb(A, indx, col); - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { Y[i][j] = col[i]; } } return new Matrix( - Y[0][0], Y[0][1], Y[0][2], Y[0][3], - Y[1][0], Y[1][1], Y[1][2], Y[1][3], - Y[2][0], Y[2][1], Y[2][2], Y[2][3], - Y[3][0], Y[3][1], Y[3][2], Y[3][3]); + Y[0][0], Y[0][1], Y[0][2], Y[0][3], + Y[1][0], Y[1][1], Y[1][2], Y[1][3], + Y[2][0], Y[2][1], Y[2][2], Y[2][3], + Y[3][0], Y[3][1], Y[3][2], Y[3][3]); } // Method "lubksb" derived from "Numerical Recipes in C", Press et al., 1988 - private static void lubksb(double[][] A, int[] indx, double[] b) - { + private static void lubksb(double[][] A, int[] indx, double[] b) { int ii = -1; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { int ip = indx[i]; double sum = b[ip]; b[ip] = b[i]; - if (ii != -1) - { - for (int j = ii; j <= i - 1; j++) - { + if (ii != -1) { + for (int j = ii; j <= i - 1; j++) { sum -= A[i][j] * b[j]; } - } - else if (sum != 0.0) - { + } else if (sum != 0.0) { ii = i; } b[i] = sum; } - for (int i = 3; i >= 0; i--) - { + for (int i = 3; i >= 0; i--) { double sum = b[i]; - for (int j = i + 1; j < 4; j++) - { + for (int j = i + 1; j < 4; j++) { sum -= A[i][j] * b[j]; } @@ -2206,36 +2002,32 @@ else if (sum != 0.0) } // Method "ludcmp" derived from "Numerical Recipes in C", Press et al., 1988 - private static double ludcmp(double[][] A, int[] indx) - { + private static double ludcmp(double[][] A, int[] indx) { final double TINY = 1.0e-20; double[] vv = new double[4]; double d = 1.0; double temp; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { double big = 0.0; - for (int j = 0; j < 4; j++) - { - if ((temp = Math.abs(A[i][j])) > big) + for (int j = 0; j < 4; j++) { + if ((temp = Math.abs(A[i][j])) > big) { big = temp; + } } - if (big == 0.0) + if (big == 0.0) { return 0.0; // Matrix is singular if the entire row contains zero. - else + } else { vv[i] = 1.0 / big; + } } double sum; - for (int j = 0; j < 4; j++) - { - for (int i = 0; i < j; i++) - { + for (int j = 0; j < 4; j++) { + for (int i = 0; i < j; i++) { sum = A[i][j]; - for (int k = 0; k < i; k++) - { + for (int k = 0; k < i; k++) { sum -= A[i][k] * A[k][j]; } @@ -2245,27 +2037,22 @@ private static double ludcmp(double[][] A, int[] indx) double big = 0.0; double dum; int imax = -1; - for (int i = j; i < 4; i++) - { + for (int i = j; i < 4; i++) { sum = A[i][j]; - for (int k = 0; k < j; k++) - { + for (int k = 0; k < j; k++) { sum -= A[i][k] * A[k][j]; } A[i][j] = sum; - if ((dum = vv[i] * Math.abs(sum)) >= big) - { + if ((dum = vv[i] * Math.abs(sum)) >= big) { big = dum; imax = i; } } - if (j != imax) - { - for (int k = 0; k < 4; k++) - { + if (j != imax) { + for (int k = 0; k < 4; k++) { dum = A[imax][k]; A[imax][k] = A[j][k]; A[j][k] = dum; @@ -2276,14 +2063,13 @@ private static double ludcmp(double[][] A, int[] indx) } indx[j] = imax; - if (A[j][j] == 0.0) + if (A[j][j] == 0.0) { A[j][j] = TINY; + } - if (j != 3) - { + if (j != 3) { dum = 1.0 / A[j][j]; - for (int i = j + 1; i < 4; i++) - { + for (int i = j + 1; i < 4; i++) { A[i][j] *= dum; } } @@ -2295,128 +2081,118 @@ private static double ludcmp(double[][] A, int[] indx) // ============== Accessor Functions ======================= // // ============== Accessor Functions ======================= // // ============== Accessor Functions ======================= // - - public final Angle getRotationX() - { + public final Angle getRotationX() { double yRadians = Math.asin(this.m13); double cosY = Math.cos(yRadians); - if (isZero(cosY)) + if (isZero(cosY)) { return null; + } double xRadians; // No Gimball lock. - if (Math.abs(cosY) > 0.005) - { + if (Math.abs(cosY) > 0.005) { xRadians = Math.atan2(-this.m23 / cosY, this.m33 / cosY); - } - // Gimball lock has occurred. Rotation around X axis becomes rotation around Z axis. - else - { + } // Gimball lock has occurred. Rotation around X axis becomes rotation around Z axis. + else { xRadians = 0; } - if (Double.isNaN(xRadians)) + if (Double.isNaN(xRadians)) { return null; + } return Angle.fromRadians(xRadians); } - public final Angle getRotationY() - { + public final Angle getRotationY() { double yRadians = Math.asin(this.m13); - if (Double.isNaN(yRadians)) + if (Double.isNaN(yRadians)) { return null; + } return Angle.fromRadians(yRadians); } - public final Angle getRotationZ() - { + public final Angle getRotationZ() { double yRadians = Math.asin(this.m13); double cosY = Math.cos(yRadians); - if (isZero(cosY)) + if (isZero(cosY)) { return null; + } double zRadians; // No Gimball lock. - if (Math.abs(cosY) > 0.005) - { + if (Math.abs(cosY) > 0.005) { zRadians = Math.atan2(-this.m12 / cosY, this.m11 / cosY); - } - // Gimball lock has occurred. Rotation around X axis becomes rotation around Z axis. - else - { + } // Gimball lock has occurred. Rotation around X axis becomes rotation around Z axis. + else { zRadians = Math.atan2(this.m21, this.m22); } - if (Double.isNaN(zRadians)) + if (Double.isNaN(zRadians)) { return null; + } return Angle.fromRadians(zRadians); } - public final Angle getKMLRotationX() // KML assumes the order of rotations is YXZ, positive CW + public final Angle getKMLRotationX() // KML assumes the order of rotations is YXZ, positive CW { double xRadians = Math.asin(-this.m23); - if (Double.isNaN(xRadians)) + if (Double.isNaN(xRadians)) { return null; + } return Angle.fromRadians(-xRadians); // negate to make angle CW } - public final Angle getKMLRotationY() // KML assumes the order of rotations is YXZ, positive CW + public final Angle getKMLRotationY() // KML assumes the order of rotations is YXZ, positive CW { double xRadians = Math.asin(-this.m23); - if (Double.isNaN(xRadians)) + if (Double.isNaN(xRadians)) { return null; + } double yRadians; - if (xRadians < Math.PI / 2) - { - if (xRadians > -Math.PI / 2) - { + if (xRadians < Math.PI / 2) { + if (xRadians > -Math.PI / 2) { yRadians = Math.atan2(this.m13, this.m33); - } - else - { + } else { yRadians = -Math.atan2(-this.m12, this.m11); } - } - else - { + } else { yRadians = Math.atan2(-this.m12, this.m11); } - if (Double.isNaN(yRadians)) + if (Double.isNaN(yRadians)) { return null; + } return Angle.fromRadians(-yRadians); // negate angle to make it CW } - public final Angle getKMLRotationZ() // KML assumes the order of rotations is YXZ, positive CW + public final Angle getKMLRotationZ() // KML assumes the order of rotations is YXZ, positive CW { double xRadians = Math.asin(-this.m23); - if (Double.isNaN(xRadians)) + if (Double.isNaN(xRadians)) { return null; + } double zRadians; - if (xRadians < Math.PI / 2 && xRadians > -Math.PI / 2) - { + if (xRadians < Math.PI / 2 && xRadians > -Math.PI / 2) { zRadians = Math.atan2(this.m21, this.m22); - } - else - { + } else { zRadians = 0; } - if (Double.isNaN(zRadians)) + if (Double.isNaN(zRadians)) { return null; + } return Angle.fromRadians(-zRadians); // negate angle to make it CW } - public final Vec4 getTranslation() - { + public final Vec4 getTranslation() { return new Vec4(this.m14, this.m24, this.m34); } @@ -2431,8 +2207,7 @@ public final Vec4 getTranslation() * * @return this viewing matrix's eye point, in model coordinates. */ - public Vec4 extractEyePoint() - { + public Vec4 extractEyePoint() { // The eye point of a modelview matrix is computed by transforming the origin (0, 0, 0, 1) by the matrix's // inverse. This is equivalent to transforming the inverse of this matrix's translation components in the // rightmost column by the transpose of its upper 3x3 components. @@ -2454,8 +2229,7 @@ public Vec4 extractEyePoint() * * @return this viewing matrix's forward vector, in model coordinates. */ - public Vec4 extractForwardVector() - { + public Vec4 extractForwardVector() { // The forward vector of a modelview matrix is computed by transforming the negative Z axis (0, 0, -1, 0) by the // matrix's inverse. We have pre-computed the result inline here to simplify this computation. return new Vec4(-this.m31, -this.m32, -this.m33); @@ -2476,38 +2250,36 @@ public Vec4 extractForwardVector() * The following list outlines the returned key-value pairs and their meanings: *

          *
        • AVKey.ORIGIN - The geographic position corresponding to the origin point.
        • - *
        • AVKey.RANGE - The distance between the specified origin point and the view's eye point, in model coordinates.
        • - *
        • AVKey.HEADING - The view's heading angle relative to the globe's north pointing tangent at the origin point.
        • + *
        • AVKey.RANGE - The distance between the specified origin point and the view's eye point, in model + * coordinates.
        • + *
        • AVKey.HEADING - The view's heading angle relative to the globe's north pointing tangent at the origin + * point.
        • *
        • AVKey.TILT - The view's tilt angle relative to the globe's normal vector at the origin point.
        • *
        • AVKey.ROLL - The view's roll relative to the globe's normal vector at the origin point.
        • *
        * * @param origin the origin of the viewing parameters, in model coordinates. - * @param roll the view's roll. - * @param globe the globe the viewer is looking at. + * @param roll the view's roll. + * @param globe the globe the viewer is looking at. * * @return a parameterization of this viewing matrix as a list of key-value pairs. * * @throws IllegalArgumentException if any argument is null. */ - public AVList extractViewingParameters(Vec4 origin, Angle roll, Globe globe) - { - if (origin == null) - { + public AVList extractViewingParameters(Vec4 origin, Angle roll, Globe globe) { + if (origin == null) { String msg = Logging.getMessage("nullValue.OriginIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (roll == null) - { + if (roll == null) { String msg = Logging.getMessage("nullValue.RollIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (globe == null) - { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -2520,7 +2292,6 @@ public AVList extractViewingParameters(Vec4 origin, Angle roll, Globe globe) // Extract the viewing parameters from the transform in local coordinates. // TODO: Document how these parameters are extracted. See [WWMatrix extractViewingParameters] in WWiOS. - Matrix m = modelviewLocal; double range = -m.m34; @@ -2547,14 +2318,12 @@ public AVList extractViewingParameters(Vec4 origin, Angle roll, Globe globe) // ============== Helper Functions ======================= // // ============== Helper Functions ======================= // // ============== Helper Functions ======================= // - private static final Double POSITIVE_ZERO = +0.0d; private static final Double NEGATIVE_ZERO = -0.0d; - private static boolean isZero(double value) - { + private static boolean isZero(double value) { return (POSITIVE_ZERO.compareTo(value) == 0) - || (NEGATIVE_ZERO.compareTo(value) == 0); + || (NEGATIVE_ZERO.compareTo(value) == 0); } } diff --git a/src/gov/nasa/worldwind/geom/MeasurableArea.java b/src/gov/nasa/worldwind/geom/MeasurableArea.java index e661e0fa46..9fde019050 100644 --- a/src/gov/nasa/worldwind/geom/MeasurableArea.java +++ b/src/gov/nasa/worldwind/geom/MeasurableArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.geom; import gov.nasa.worldwind.globes.*; @@ -15,15 +14,15 @@ * @author tag * @version $Id: MeasurableArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MeasurableArea -{ +public interface MeasurableArea { + /** * Returns the object's area in square meters. If the object conforms to terrain, the area returned is the surface * area of the terrain, including its hillsides and other undulations. * * @param globe The globe the object is related to. * @return the object's area in square meters. Returns -1 if the object does not form an area due to an insufficient - * number of vertices or any other condition. + * number of vertices or any other condition. * @throws IllegalArgumentException if the globe is null. */ double getArea(Globe globe); @@ -34,7 +33,7 @@ public interface MeasurableArea * * @param globe The globe the object is related to. * @return the object's perimeter in meters. Returns -1 if the object does not form an area due to an insufficient - * number of vertices or any other condition. + * number of vertices or any other condition. * @throws IllegalArgumentException if the globe is null. */ double getPerimeter(Globe globe); diff --git a/src/gov/nasa/worldwind/geom/MeasurableLength.java b/src/gov/nasa/worldwind/geom/MeasurableLength.java index d7f3321c62..86f728ff1f 100644 --- a/src/gov/nasa/worldwind/geom/MeasurableLength.java +++ b/src/gov/nasa/worldwind/geom/MeasurableLength.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.geom; import gov.nasa.worldwind.globes.*; @@ -12,8 +11,8 @@ * @author tag * @version $Id: MeasurableLength.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MeasurableLength -{ +public interface MeasurableLength { + /** * Returns the object's length in meters. If the object conforms to terrain, the length is that along the terrain, * including its hillsides and other undulations. diff --git a/src/gov/nasa/worldwind/geom/PickPointFrustum.java b/src/gov/nasa/worldwind/geom/PickPointFrustum.java index 67984ead8a..ca366f1c08 100644 --- a/src/gov/nasa/worldwind/geom/PickPointFrustum.java +++ b/src/gov/nasa/worldwind/geom/PickPointFrustum.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.geom; import gov.nasa.worldwind.util.Logging; @@ -17,23 +16,21 @@ * @author Jeff Addison * @version $Id: PickPointFrustum.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PickPointFrustum extends Frustum -{ +public class PickPointFrustum extends Frustum { + private final Rectangle screenRect; /** * Constructs a new PickPointFrustum from another Frustum and screen rectangle * * @param frustum frustum to create the PickPointFrustum from - * @param rect screen rectangle to store with this frustum + * @param rect screen rectangle to store with this frustum */ - public PickPointFrustum(Frustum frustum, Rectangle rect) - { + public PickPointFrustum(Frustum frustum, Rectangle rect) { super(frustum.getLeft(), frustum.getRight(), frustum.getBottom(), frustum.getTop(), frustum.getNear(), - frustum.getFar()); + frustum.getFar()); - if (rect == null) - { + if (rect == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -43,7 +40,6 @@ public PickPointFrustum(Frustum frustum, Rectangle rect) } // ============== Intersection Functions ======================= // - /** * Returns true if the specified 2D screen {@link java.awt.Rectangle} intersects the space enclosed by this view * aligned frustums screen rectangle. @@ -54,10 +50,8 @@ public PickPointFrustum(Frustum frustum, Rectangle rect) * * @throws IllegalArgumentException if the extent is null. */ - public final boolean intersects(Rectangle rect) - { - if (rect == null) - { + public final boolean intersects(Rectangle rect) { + if (rect == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -76,8 +70,7 @@ public final boolean intersects(Rectangle rect) * * @throws IllegalArgumentException if the point is null. */ - public final boolean contains(double x, double y) - { + public final boolean contains(double x, double y) { return this.screenRect.contains(x, y); } @@ -90,10 +83,8 @@ public final boolean contains(double x, double y) * * @throws IllegalArgumentException if the point is null. */ - public final boolean contains(Point point) - { - if (point == null) - { + public final boolean contains(Point point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -111,10 +102,8 @@ public final boolean contains(Point point) * * @throws IllegalArgumentException if the matrix is null */ - public PickPointFrustum transformBy(Matrix matrix) - { - if (matrix == null) - { + public PickPointFrustum transformBy(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -128,8 +117,7 @@ public PickPointFrustum transformBy(Matrix matrix) * * @return screenRect associated with this frustum */ - public Rectangle getScreenRect() - { + public Rectangle getScreenRect() { return screenRect; } } diff --git a/src/gov/nasa/worldwind/geom/Plane.java b/src/gov/nasa/worldwind/geom/Plane.java index af87bd68e0..6527d65abf 100644 --- a/src/gov/nasa/worldwind/geom/Plane.java +++ b/src/gov/nasa/worldwind/geom/Plane.java @@ -15,8 +15,8 @@ * @author Tom Gaskins * @version $Id: Plane.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public final class Plane -{ +public final class Plane { + private final Vec4 n; // the plane normal and proportional distance. The vector is not necessarily a unit vector. /** @@ -26,17 +26,14 @@ public final class Plane * * @throws IllegalArgumentException if the vector is null. */ - public Plane(Vec4 vec) - { - if (vec == null) - { + public Plane(Vec4 vec) { + if (vec == null) { String message = Logging.getMessage("nullValue.VectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vec.getLengthSquared3() == 0.0) - { + if (vec.getLengthSquared3() == 0.0) { String message = Logging.getMessage("Geom.Plane.VectorIsZero"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -51,14 +48,12 @@ public Plane(Vec4 vec) * @param nx the X component of the plane normal vector. * @param ny the Y component of the plane normal vector. * @param nz the Z component of the plane normal vector. - * @param d the plane distance. + * @param d the plane distance. * * @throws IllegalArgumentException if the normal vector components define the zero vector (all values are zero). */ - public Plane(double nx, double ny, double nz, double d) - { - if (nx == 0.0 && ny == 0.0 && nz == 0.0) - { + public Plane(double nx, double ny, double nz, double d) { + if (nx == 0.0 && ny == 0.0 && nz == 0.0) { String message = Logging.getMessage("Geom.Plane.VectorIsZero"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -80,10 +75,8 @@ public Plane(double nx, double ny, double nz, double d) * * @throws IllegalArgumentException if pa, pb, or pc is null. */ - public static Plane fromPoints(Vec4 pa, Vec4 pb, Vec4 pc) - { - if (pa == null || pb == null || pc == null) - { + public static Plane fromPoints(Vec4 pa, Vec4 pb, Vec4 pc) { + if (pa == null || pb == null || pc == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -102,8 +95,7 @@ public static Plane fromPoints(Vec4 pa, Vec4 pb, Vec4 pc) * * @return the plane's normal vector. */ - public final Vec4 getNormal() - { + public final Vec4 getNormal() { return this.n;//new Vec4(this.n.x, this.n.y, this.n.z); } @@ -112,8 +104,7 @@ public final Vec4 getNormal() * * @return the plane distance. */ - public final double getDistance() - { + public final double getDistance() { return this.n.w; } @@ -122,8 +113,7 @@ public final double getDistance() * * @return a 4-D vector indicating the plane's normal vector and distance. */ - public final Vec4 getVector() - { + public final Vec4 getVector() { return this.n; } @@ -133,17 +123,18 @@ public final Vec4 getVector() * * @return a normalized copy of this Plane. */ - public final Plane normalize() - { + public final Plane normalize() { double length = this.n.getLength3(); if (length == 0) // should not happen, but check to be sure. + { return this; + } return new Plane(new Vec4( - this.n.x / length, - this.n.y / length, - this.n.z / length, - this.n.w / length)); + this.n.x / length, + this.n.y / length, + this.n.z / length, + this.n.w / length)); } /** @@ -155,10 +146,8 @@ public final Plane normalize() * * @throws IllegalArgumentException if the vector is null. */ - public final double dot(Vec4 p) - { - if (p == null) - { + public final double dot(Vec4 p) { + if (p == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -176,10 +165,8 @@ public final double dot(Vec4 p) * * @throws IllegalArgumentException if the line is null. */ - public Vec4 intersect(Line line) - { - if (line == null) - { + public Vec4 intersect(Line line) { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -187,11 +174,13 @@ public Vec4 intersect(Line line) double t = this.intersectDistance(line); - if (Double.isNaN(t)) + if (Double.isNaN(t)) { return null; + } - if (Double.isInfinite(t)) + if (Double.isInfinite(t)) { return line.getOrigin(); + } return line.getPointAt(t); } @@ -202,15 +191,13 @@ public Vec4 intersect(Line line) * @param line the line to test * * @return The parametric value of the point on the line at which it intersects the plane. {@link Double#NaN} is - * returned if the line does not intersect the plane. {@link Double#POSITIVE_INFINITY} is returned if the - * line is coincident with the plane. + * returned if the line does not intersect the plane. {@link Double#POSITIVE_INFINITY} is returned if the line is + * coincident with the plane. * * @throws IllegalArgumentException if the line is null. */ - public double intersectDistance(Line line) - { - if (line == null) - { + public double intersectDistance(Line line) { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -220,10 +207,11 @@ public double intersectDistance(Line line) if (ldotv == 0) // are line and plane parallel { double ldots = this.n.dot4(line.getOrigin()); - if (ldots == 0) + if (ldots == 0) { return Double.POSITIVE_INFINITY; // line is coincident with the plane - else + } else { return Double.NaN; // line is not coincident with the plane + } } return -this.n.dot4(line.getOrigin()) / ldotv; // ldots / ldotv @@ -236,44 +224,41 @@ public double intersectDistance(Line line) * @param pb the second point of the line segment. * * @return The point of intersection with the plane. Null is returned if the segment does not instersect this plane. - * {@link gov.nasa.worldwind.geom.Vec4#INFINITY} coincident with the plane. + * {@link gov.nasa.worldwind.geom.Vec4#INFINITY} coincident with the plane. * * @throws IllegalArgumentException if either input point is null. */ - public Vec4 intersect(Vec4 pa, Vec4 pb) - { - if (pa == null || pb == null) - { + public Vec4 intersect(Vec4 pa, Vec4 pb) { + if (pa == null || pb == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { // Test if line segment is in fact a point - if (pa.equals(pb)) - { + if (pa.equals(pb)) { double d = this.distanceTo(pa); - if (d == 0) + if (d == 0) { return pa; - else + } else { return null; + } } Line l = Line.fromSegment(pa, pb); double t = this.intersectDistance(l); - if (Double.isInfinite(t)) + if (Double.isInfinite(t)) { return Vec4.INFINITY; + } - if (Double.isNaN(t) || t < 0 || t > 1) + if (Double.isNaN(t) || t < 0 || t > 1) { return null; + } return l.getPointAt(t); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { return null; } } @@ -285,26 +270,25 @@ public Vec4 intersect(Vec4 pa, Vec4 pb) * @param pb the second point of the segment. * * @return An array of two points both on the positive side of the plane. If the direction of the line formed by the - * two points is positive with respect to this plane's normal vector, the first point in the array will be - * the intersection point on the plane, and the second point will be the original segment end point. If the - * direction of the line is negative with respect to this plane's normal vector, the first point in the - * array will be the original segment's begin point, and the second point will be the intersection point on - * the plane. If the segment does not intersect the plane, null is returned. If the segment is coincident - * with the plane, the input points are returned, in their input order. + * two points is positive with respect to this plane's normal vector, the first point in the array will be the + * intersection point on the plane, and the second point will be the original segment end point. If the direction of + * the line is negative with respect to this plane's normal vector, the first point in the array will be the + * original segment's begin point, and the second point will be the intersection point on the plane. If the segment + * does not intersect the plane, null is returned. If the segment is coincident with the plane, the input points are + * returned, in their input order. * * @throws IllegalArgumentException if either input point is null. */ - public Vec4[] clip(Vec4 pa, Vec4 pb) - { - if (pa == null || pb == null) - { + public Vec4[] clip(Vec4 pa, Vec4 pb) { + if (pa == null || pb == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pa.equals(pb)) + if (pa.equals(pb)) { return null; + } // Get the projection of the segment onto the plane. Line line = Line.fromSegment(pa, pb); @@ -314,26 +298,29 @@ public Vec4[] clip(Vec4 pa, Vec4 pb) if (ldotv == 0) // line and plane are parallel and maybe coincident { double ldots = this.n.dot4(line.getOrigin()); - if (ldots == 0) - return new Vec4[] {pa, pb}; // line is coincident with the plane - else + if (ldots == 0) { + return new Vec4[]{pa, pb}; // line is coincident with the plane + } else { return null; // line is not coincident with the plane + } } // Not parallel so the line intersects. But does the segment intersect? double t = -this.n.dot4(line.getOrigin()) / ldotv; // ldots / ldotv if (t < 0 || t > 1) // segment does not intersect + { return null; + } Vec4 p = line.getPointAt(t); - if (ldotv > 0) - return new Vec4[] {p, pb}; - else - return new Vec4[] {pa, p}; + if (ldotv > 0) { + return new Vec4[]{p, pb}; + } else { + return new Vec4[]{pa, p}; + } } - public double distanceTo(Vec4 p) - { + public double distanceTo(Vec4 p) { return this.n.dot4(p); } @@ -347,10 +334,8 @@ public double distanceTo(Vec4 p) * * @throws IllegalArgumentException if either point is null. */ - public int onSameSide(Vec4 pa, Vec4 pb) - { - if (pa == null || pb == null) - { + public int onSameSide(Vec4 pa, Vec4 pb) { + if (pa == null || pb == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -359,11 +344,13 @@ public int onSameSide(Vec4 pa, Vec4 pb) double da = this.distanceTo(pa); double db = this.distanceTo(pb); - if (da < 0 && db < 0) + if (da < 0 && db < 0) { return -1; + } - if (da > 0 && db > 0) + if (da > 0 && db > 0) { return 1; + } return 0; } @@ -377,10 +364,8 @@ public int onSameSide(Vec4 pa, Vec4 pb) * * @throws IllegalArgumentException if the points array is null or any point within it is null. */ - public int onSameSide(Vec4[] pts) - { - if (pts == null) - { + public int onSameSide(Vec4[] pts) { + if (pts == null) { String message = Logging.getMessage("nullValue.PointsArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -388,21 +373,21 @@ public int onSameSide(Vec4[] pts) double d = this.distanceTo(pts[0]); int side = d < 0 ? -1 : d > 0 ? 1 : 0; - if (side == 0) + if (side == 0) { return 0; + } - for (int i = 1; i < pts.length; i++) - { - if (pts[i] == null) - { + for (int i = 1; i < pts.length; i++) { + if (pts[i] == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } d = this.distanceTo(pts[i]); - if ((side == -1 && d < 0) || (side == 1 && d > 0)) + if ((side == -1 && d < 0) || (side == 1 && d > 0)) { continue; + } return 0; // point is not on same side as the others } @@ -421,10 +406,8 @@ public int onSameSide(Vec4[] pts) * * @throws IllegalArgumentException if any of the planes are null. */ - public static Vec4 intersect(Plane pa, Plane pb, Plane pc) - { - if (pa == null || pb == null || pc == null) - { + public static Vec4 intersect(Plane pa, Plane pb, Plane pc) { + if (pa == null || pb == null || pc == null) { String message = Logging.getMessage("nullValue.PlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -435,10 +418,10 @@ public static Vec4 intersect(Plane pa, Plane pb, Plane pc) Vec4 nc = pc.getNormal(); Matrix m = new Matrix( - na.x, na.y, na.z, 0, - nb.x, nb.y, nb.z, 0, - nc.x, nc.y, nc.z, 0, - 0, 0, 0, 1, true + na.x, na.y, na.z, 0, + nb.x, nb.y, nb.z, 0, + nc.x, nc.y, nc.z, 0, + 0, 0, 0, 1, true ); Matrix mInverse = m.getInverse(); @@ -449,12 +432,13 @@ public static Vec4 intersect(Plane pa, Plane pb, Plane pc) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (!(o instanceof Plane)) + } + if (!(o instanceof Plane)) { return false; + } Plane plane = (Plane) o; @@ -462,14 +446,12 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { return n != null ? n.hashCode() : 0; } @Override - public final String toString() - { + public final String toString() { return this.n.toString(); } } diff --git a/src/gov/nasa/worldwind/geom/PolarPoint.java b/src/gov/nasa/worldwind/geom/PolarPoint.java index 725704e512..34aa62c399 100644 --- a/src/gov/nasa/worldwind/geom/PolarPoint.java +++ b/src/gov/nasa/worldwind/geom/PolarPoint.java @@ -15,8 +15,8 @@ * @author Tom Gaskins * @version $Id: PolarPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PolarPoint -{ +public class PolarPoint { + public static final PolarPoint ZERO = new PolarPoint(Angle.ZERO, Angle.ZERO, 0d); private final Angle latitude; @@ -26,26 +26,24 @@ public class PolarPoint /** * Obtains a PolarPoint from radians and a radius. * - * @param latitude the latitude in radians + * @param latitude the latitude in radians * @param longitude the longitude in radians - * @param radius the distance form the center + * @param radius the distance form the center * @return a new PolarPoint */ - public static PolarPoint fromRadians(double latitude, double longitude, double radius) - { + public static PolarPoint fromRadians(double latitude, double longitude, double radius) { return new PolarPoint(Angle.fromRadians(latitude), Angle.fromRadians(longitude), radius); } /** * Obtains a PolarPoint from degrees and a radius. * - * @param latitude the latitude in degrees + * @param latitude the latitude in degrees * @param longitude the longitude in degrees - * @param radius the distance form the center + * @param radius the distance form the center * @return a new PolarPoint */ - public static PolarPoint fromDegrees(double latitude, double longitude, double radius) - { + public static PolarPoint fromDegrees(double latitude, double longitude, double radius) { return new PolarPoint(Angle.fromDegrees(latitude), Angle.fromDegrees(longitude), radius); } @@ -56,10 +54,8 @@ public static PolarPoint fromDegrees(double latitude, double longitude, double r * @return the cartesian point expressed as a polar point * @throws IllegalArgumentException if cartesianPoint is null */ - public static PolarPoint fromCartesian(Vec4 cartesianPoint) - { - if (cartesianPoint == null) - { + public static PolarPoint fromCartesian(Vec4 cartesianPoint) { + if (cartesianPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,8 +72,7 @@ public static PolarPoint fromCartesian(Vec4 cartesianPoint) * @param z the z coordinate of the cartesian point * @return a polar point located at (x,y,z) in cartesian space */ - public static PolarPoint fromCartesian(double x, double y, double z) - { + public static PolarPoint fromCartesian(double x, double y, double z) { double radius = Math.sqrt(x * x + y * y + z * z); double latRads = Math.atan2(y, Math.sqrt(x * x + z * z)); double lonRads = Math.atan2(x, z); @@ -87,15 +82,13 @@ public static PolarPoint fromCartesian(double x, double y, double z) /** * Obtains a PolarPoint from two angles and a radius. * - * @param latitude the latitude + * @param latitude the latitude * @param longitude the longitude - * @param radius the distance from the center + * @param radius the distance from the center * @throws IllegalArgumentException if latitude or longitude is null */ - public PolarPoint(Angle latitude, Angle longitude, double radius) - { - if (latitude == null || longitude == null) - { + public PolarPoint(Angle latitude, Angle longitude, double radius) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -111,8 +104,7 @@ public PolarPoint(Angle latitude, Angle longitude, double radius) * * @return this polar point's latitude */ - public final Angle getLatitude() - { + public final Angle getLatitude() { return this.latitude; } @@ -121,8 +113,7 @@ public final Angle getLatitude() * * @return this polar point's longitude */ - public final Angle getLongitude() - { + public final Angle getLongitude() { return this.longitude; } @@ -131,8 +122,7 @@ public final Angle getLongitude() * * @return the distance from this polar point to its origin */ - public final double getRadius() - { + public final double getRadius() { return radius; } @@ -141,8 +131,7 @@ public final double getRadius() * * @return this polar point in cartesian coordinates */ - public final Vec4 toCartesian() - { + public final Vec4 toCartesian() { return toCartesian(this.latitude, this.longitude, this.radius); } @@ -150,16 +139,14 @@ public final Vec4 toCartesian() * Obtains a cartesian point from a given latitude, longitude and distance from center. This method is equivalent * to, but may perform faster than Vec4 p = new PolarPoint(latitude, longitude, radius).toCartesian() * - * @param latitude the latitude + * @param latitude the latitude * @param longitude the longitude - * @param radius the distance from the origin + * @param radius the distance from the origin * @return a cartesian point from two angles and a radius * @throws IllegalArgumentException if latitude or longitude is null */ - public static Vec4 toCartesian(Angle latitude, Angle longitude, double radius) - { - if (latitude == null || longitude == null) - { + public static Vec4 toCartesian(Angle latitude, Angle longitude, double radius) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,29 +159,32 @@ public static Vec4 toCartesian(Angle latitude, Angle longitude, double radius) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final gov.nasa.worldwind.geom.PolarPoint that = (gov.nasa.worldwind.geom.PolarPoint) o; - if (Double.compare(that.radius, radius) != 0) + if (Double.compare(that.radius, radius) != 0) { return false; - if (!latitude.equals(that.latitude)) + } + if (!latitude.equals(that.latitude)) { return false; + } //noinspection RedundantIfStatement - if (!longitude.equals(that.longitude)) + if (!longitude.equals(that.longitude)) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; long temp; result = latitude.hashCode(); @@ -205,9 +195,8 @@ public int hashCode() } @Override - public String toString() - { + public String toString() { return "(lat: " + this.latitude.toString() + ", lon: " + this.longitude.toString() + ", r: " + this.radius - + ")"; + + ")"; } } diff --git a/src/gov/nasa/worldwind/geom/Position.java b/src/gov/nasa/worldwind/geom/Position.java index 8b53b08813..4748a3c3f8 100644 --- a/src/gov/nasa/worldwind/geom/Position.java +++ b/src/gov/nasa/worldwind/geom/Position.java @@ -14,46 +14,40 @@ * @author tag * @version $Id: Position.java 2291 2014-08-30 21:38:47Z tgaskins $ */ -public class Position extends LatLon -{ +public class Position extends LatLon { + public static final Position ZERO = new Position(Angle.ZERO, Angle.ZERO, 0d); public final double elevation; - public static Position fromRadians(double latitude, double longitude, double elevation) - { + public static Position fromRadians(double latitude, double longitude, double elevation) { return new Position(Angle.fromRadians(latitude), Angle.fromRadians(longitude), elevation); } - public static Position fromDegrees(double latitude, double longitude, double elevation) - { + public static Position fromDegrees(double latitude, double longitude, double elevation) { return new Position(Angle.fromDegrees(latitude), Angle.fromDegrees(longitude), elevation); } - public static Position fromDegrees(double latitude, double longitude) - { + public static Position fromDegrees(double latitude, double longitude) { return new Position(Angle.fromDegrees(latitude), Angle.fromDegrees(longitude), 0); } - public Position(Angle latitude, Angle longitude, double elevation) - { + public Position(Angle latitude, Angle longitude, double elevation) { super(latitude, longitude); this.elevation = elevation; } - public Position(LatLon latLon, double elevation) - { + public Position(LatLon latLon, double elevation) { super(latLon); this.elevation = elevation; } // A class that makes it easier to pass around position lists. - public static class PositionList - { + public static class PositionList { + public List list; - public PositionList(List list) - { + public PositionList(List list) { this.list = list; } } @@ -63,8 +57,7 @@ public PositionList(List list) * * @return this position's elevation */ - public double getElevation() - { + public double getElevation() { return this.elevation; } @@ -73,21 +66,18 @@ public double getElevation() * * @return this position's elevation */ - public double getAltitude() - { + public double getAltitude() { return this.elevation; } - public Position add(Position that) - { + public Position add(Position that) { Angle lat = Angle.normalizedLatitude(this.latitude.add(that.latitude)); Angle lon = Angle.normalizedLongitude(this.longitude.add(that.longitude)); return new Position(lat, lon, this.elevation + that.elevation); } - public Position subtract(Position that) - { + public Position subtract(Position that) { Angle lat = Angle.normalizedLatitude(this.latitude.subtract(that.latitude)); Angle lon = Angle.normalizedLongitude(this.longitude.subtract(that.longitude)); @@ -106,19 +96,18 @@ public Position subtract(Position that) * * @throws IllegalArgumentException if either position is null. */ - public static Position interpolate(double amount, Position value1, Position value2) - { - if (value1 == null || value2 == null) - { + public static Position interpolate(double amount, Position value1, Position value2) { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (amount < 0) + if (amount < 0) { return value1; - else if (amount > 1) + } else if (amount > 1) { return value2; + } LatLon latLon = LatLon.interpolate(amount, value1, value2); // Elevation is independent of geographic interpolation method (i.e. rhumb, great-circle, linear), so we @@ -142,14 +131,12 @@ else if (amount > 1) * @param value2 the second position. * * @return an interpolated position along the great-arc between value1 and value2, with a - * linearly interpolated elevation component. + * linearly interpolated elevation component. * * @throws IllegalArgumentException if either location is null. */ - public static Position interpolateGreatCircle(double amount, Position value1, Position value2) - { - if (value1 == null || value2 == null) - { + public static Position interpolateGreatCircle(double amount, Position value1, Position value2) { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -177,14 +164,12 @@ public static Position interpolateGreatCircle(double amount, Position value1, Po * @param value2 the second position. * * @return an interpolated position along the great-arc between value1 and value2, with a - * linearly interpolated elevation component. + * linearly interpolated elevation component. * * @throws IllegalArgumentException if either location is null. */ - public static Position interpolateRhumb(double amount, Position value1, Position value2) - { - if (value1 == null || value2 == null) - { + public static Position interpolateRhumb(double amount, Position value1, Position value2) { + if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -198,27 +183,23 @@ public static Position interpolateRhumb(double amount, Position value1, Position return new Position(latLon, elevation); } - public static boolean positionsCrossDateLine(Iterable positions) - { - if (positions == null) - { + public static boolean positionsCrossDateLine(Iterable positions) { + if (positions == null) { String msg = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Position pos = null; - for (Position posNext : positions) - { - if (pos != null) - { + for (Position posNext : positions) { + if (pos != null) { // A segment cross the line if end pos have different longitude signs // and are more than 180 degress longitude apart - if (Math.signum(pos.getLongitude().degrees) != Math.signum(posNext.getLongitude().degrees)) - { + if (Math.signum(pos.getLongitude().degrees) != Math.signum(posNext.getLongitude().degrees)) { double delta = Math.abs(pos.getLongitude().degrees - posNext.getLongitude().degrees); - if (delta > 180 && delta < 360) + if (delta > 180 && delta < 360) { return true; + } } } pos = posNext; @@ -232,25 +213,22 @@ public static boolean positionsCrossDateLine(Iterable positi * * @param oldPosition the original reference position. * @param newPosition the new reference position. - * @param positions the positions to translate. + * @param positions the positions to translate. * * @return the translated positions, or null if the positions could not be translated. * * @throws IllegalArgumentException if any argument is null. */ public static List computeShiftedPositions(Position oldPosition, Position newPosition, - Iterable positions) - { + Iterable positions) { // TODO: Account for dateline spanning - if (oldPosition == null || newPosition == null) - { + if (oldPosition == null || newPosition == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (positions == null) - { + if (positions == null) { String msg = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -260,8 +238,7 @@ public static List computeShiftedPositions(Position oldPosition, Posit double elevDelta = newPosition.getElevation() - oldPosition.getElevation(); - for (Position pos : positions) - { + for (Position pos : positions) { Angle distance = LatLon.greatCircleDistance(oldPosition, pos); Angle azimuth = LatLon.greatCircleAzimuth(oldPosition, pos); LatLon newLocation = LatLon.greatCircleEndPosition(newPosition, azimuth, distance); @@ -274,24 +251,20 @@ public static List computeShiftedPositions(Position oldPosition, Posit } public static List computeShiftedPositions(Globe globe, Position oldPosition, Position newPosition, - Iterable positions) - { - if (globe == null) - { + Iterable positions) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (oldPosition == null || newPosition == null) - { + if (oldPosition == null || newPosition == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (positions == null) - { + if (positions == null) { String msg = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -304,8 +277,7 @@ public static List computeShiftedPositions(Globe globe, Position oldPo Vec4 newPoint = globe.computePointFromPosition(newPosition); Vec4 delta = newPoint.subtract3(oldPoint); - for (Position pos : positions) - { + for (Position pos : positions) { Vec4 point = globe.computePointFromPosition(pos); point = point.add3(delta); Position newPos = globe.computePositionFromPoint(point); @@ -318,27 +290,29 @@ public static List computeShiftedPositions(Globe globe, Position oldPo } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; - if (!super.equals(o)) + } + if (!super.equals(o)) { return false; + } Position position = (Position) o; //noinspection RedundantIfStatement - if (Double.compare(position.elevation, elevation) != 0) + if (Double.compare(position.elevation, elevation) != 0) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = super.hashCode(); long temp; temp = elevation != +0.0d ? Double.doubleToLongBits(elevation) : 0L; @@ -346,8 +320,7 @@ public int hashCode() return result; } - public String toString() - { + public String toString() { return "(" + this.latitude.toString() + ", " + this.longitude.toString() + ", " + this.elevation + ")"; } } diff --git a/src/gov/nasa/worldwind/geom/Quaternion.java b/src/gov/nasa/worldwind/geom/Quaternion.java index 46b4ebba4e..cd776868af 100644 --- a/src/gov/nasa/worldwind/geom/Quaternion.java +++ b/src/gov/nasa/worldwind/geom/Quaternion.java @@ -11,8 +11,8 @@ * @author Chris Maxwell * @version $Id: Quaternion.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Quaternion -{ +public class Quaternion { + // Multiplicative identity quaternion. public static final Quaternion IDENTITY = new Quaternion(0, 0, 0, 1); @@ -26,32 +26,30 @@ public class Quaternion // Cached computations. private int hashCode; - public Quaternion(double x, double y, double z, double w) - { + public Quaternion(double x, double y, double z, double w) { this.x = x; this.y = y; this.z = z; this.w = w; } - public final boolean equals(Object obj) - { - if (this == obj) + public final boolean equals(Object obj) { + if (this == obj) { return true; - if (obj == null || obj.getClass() != this.getClass()) + } + if (obj == null || obj.getClass() != this.getClass()) { return false; + } Quaternion that = (Quaternion) obj; return (this.x == that.x) - && (this.y == that.y) - && (this.z == that.z) - && (this.w == that.w); + && (this.y == that.y) + && (this.z == that.z) + && (this.w == that.w); } - public final int hashCode() - { - if (this.hashCode == 0) - { + public final int hashCode() { + if (this.hashCode == 0) { int result; long tmp; tmp = Double.doubleToLongBits(this.x); @@ -67,16 +65,13 @@ public final int hashCode() return this.hashCode; } - public static Quaternion fromArray(double[] compArray, int offset) - { - if (compArray == null) - { + public static Quaternion fromArray(double[] compArray, int offset) { + if (compArray == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if ((compArray.length - offset) < NUM_ELEMENTS) - { + if ((compArray.length - offset) < NUM_ELEMENTS) { String msg = Logging.getMessage("generic.ArrayInvalidLength", compArray.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -84,27 +79,24 @@ public static Quaternion fromArray(double[] compArray, int offset) //noinspection PointlessArithmeticExpression return new Quaternion( - compArray[0 + offset], - compArray[1 + offset], - compArray[2 + offset], - compArray[3 + offset]); + compArray[0 + offset], + compArray[1 + offset], + compArray[2 + offset], + compArray[3 + offset]); } - public final double[] toArray(double[] compArray, int offset) - { - if (compArray == null) - { + public final double[] toArray(double[] compArray, int offset) { + if (compArray == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if ((compArray.length - offset) < NUM_ELEMENTS) - { + if ((compArray.length - offset) < NUM_ELEMENTS) { String msg = Logging.getMessage("generic.ArrayInvalidLength", compArray.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - + //noinspection PointlessArithmeticExpression compArray[0 + offset] = this.x; compArray[1 + offset] = this.y; @@ -113,8 +105,7 @@ public final double[] toArray(double[] compArray, int offset) return compArray; } - public final String toString() - { + public final String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(this.x).append(", "); @@ -125,60 +116,48 @@ public final String toString() return sb.toString(); } - public final double getX() - { + public final double getX() { return this.x; } - public final double getY() - { + public final double getY() { return this.y; } - public final double getZ() - { + public final double getZ() { return this.z; } - public final double getW() - { + public final double getW() { return this.w; } - public final double x() - { + public final double x() { return this.x; } - public final double y() - { + public final double y() { return this.y; } - public final double z() - { + public final double z() { return this.z; } - public final double w() - { + public final double w() { return this.w; } // ============== Factory Functions ======================= // // ============== Factory Functions ======================= // // ============== Factory Functions ======================= // - - public static Quaternion fromAxisAngle(Angle angle, Vec4 axis) - { - if (angle == null) - { + public static Quaternion fromAxisAngle(Angle angle, Vec4 axis) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (axis == null) - { + if (axis == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -187,10 +166,8 @@ public static Quaternion fromAxisAngle(Angle angle, Vec4 axis) return fromAxisAngle(angle, axis.x, axis.y, axis.z, true); } - public static Quaternion fromAxisAngle(Angle angle, double axisX, double axisY, double axisZ) - { - if (angle == null) - { + public static Quaternion fromAxisAngle(Angle angle, double axisX, double axisY, double axisZ) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -198,20 +175,16 @@ public static Quaternion fromAxisAngle(Angle angle, double axisX, double axisY, return fromAxisAngle(angle, axisX, axisY, axisZ, true); } - private static Quaternion fromAxisAngle(Angle angle, double axisX, double axisY, double axisZ, boolean normalize) - { - if (angle == null) - { + private static Quaternion fromAxisAngle(Angle angle, double axisX, double axisY, double axisZ, boolean normalize) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (normalize) - { + if (normalize) { double length = Math.sqrt((axisX * axisX) + (axisY * axisY) + (axisZ * axisZ)); - if (!isZero(length) && (length != 1.0)) - { + if (!isZero(length) && (length != 1.0)) { axisX /= length; axisY /= length; axisZ /= length; @@ -223,68 +196,57 @@ private static Quaternion fromAxisAngle(Angle angle, double axisX, double axisY, return new Quaternion(axisX * s, axisY * s, axisZ * s, c); } - public static Quaternion fromMatrix(Matrix matrix) - { - if (matrix == null) - { + public static Quaternion fromMatrix(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - + double t = 1.0 + matrix.m11 + matrix.m22 + matrix.m33; double x, y, z, w; double s; final double EPSILON = 0.00000001; - if (t > EPSILON) - { - s = 2.0 * Math.sqrt(t); - x = (matrix.m32 - matrix.m23) / s; + if (t > EPSILON) { + s = 2.0 * Math.sqrt(t); + x = (matrix.m32 - matrix.m23) / s; y = (matrix.m13 - matrix.m31) / s; z = (matrix.m21 - matrix.m12) / s; w = s / 4.0; + } else if ((matrix.m11 > matrix.m22) && (matrix.m11 > matrix.m33)) { + s = 2.0 * Math.sqrt(1.0 + matrix.m11 - matrix.m22 - matrix.m33); + x = s / 4.0; + y = (matrix.m21 + matrix.m12) / s; + z = (matrix.m13 + matrix.m31) / s; + w = (matrix.m32 - matrix.m23) / s; + } else if (matrix.m22 > matrix.m33) { + s = 2.0 * Math.sqrt(1.0 + matrix.m22 - matrix.m11 - matrix.m33); + x = (matrix.m21 + matrix.m12) / s; + y = s / 4.0; + z = (matrix.m32 + matrix.m23) / s; + w = (matrix.m13 - matrix.m31) / s; + } else { + s = 2.0 * Math.sqrt(1.0 + matrix.m33 - matrix.m11 - matrix.m22); + x = (matrix.m13 + matrix.m31) / s; + y = (matrix.m32 + matrix.m23) / s; + z = s / 4.0; + w = (matrix.m21 - matrix.m12) / s; } - else if ((matrix.m11 > matrix.m22) && (matrix.m11 > matrix.m33)) - { - s = 2.0 * Math.sqrt(1.0 + matrix.m11 - matrix.m22 - matrix.m33); - x = s / 4.0; - y = (matrix.m21 + matrix.m12) / s; - z = (matrix.m13 + matrix.m31) / s; - w = (matrix.m32 - matrix.m23) / s; - } - else if (matrix.m22 > matrix.m33) - { - s = 2.0 * Math.sqrt(1.0 + matrix.m22 - matrix.m11 - matrix.m33); - x = (matrix.m21 + matrix.m12) / s; - y = s / 4.0; - z = (matrix.m32 + matrix.m23) / s; - w = (matrix.m13 - matrix.m31) / s; - } - else - { - s = 2.0 * Math.sqrt(1.0 + matrix.m33 - matrix.m11 - matrix.m22); - x = (matrix.m13 + matrix.m31) / s; - y = (matrix.m32 + matrix.m23) / s; - z = s / 4.0; - w = (matrix.m21 - matrix.m12) / s; - } return new Quaternion(x, y, z, w); } /** * Returns a Quaternion created from three Euler angle rotations. The angles represent rotation about their - * respective unit-axes. The angles are applied in the order X, Y, Z. - * Angles can be extracted by calling {@link #getRotationX}, {@link #getRotationY}, {@link #getRotationZ}. + * respective unit-axes. The angles are applied in the order X, Y, Z. Angles can be extracted by calling + * {@link #getRotationX}, {@link #getRotationY}, {@link #getRotationZ}. * * @param x Angle rotation about unit-X axis. * @param y Angle rotation about unit-Y axis. * @param z Angle rotation about unit-Z axis. * @return Quaternion representation of the combined X-Y-Z rotation. */ - public static Quaternion fromRotationXYZ(Angle x, Angle y, Angle z) - { - if (x == null || y == null || z == null) - { + public static Quaternion fromRotationXYZ(Angle x, Angle y, Angle z) { + if (x == null || y == null || z == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -325,7 +287,6 @@ public static Quaternion fromRotationXYZ(Angle x, Angle y, Angle z) // qy = (cx * sy * cz) - (sx * cy * sz); // qz = (cx * cy * sz) + (sx * sy * cz); // - double qw = (cx * cy * cz) + (sx * sy * sz); double qx = (sx * cy * cz) - (cx * sy * sz); double qy = (cx * sy * cz) + (sx * cy * sz); @@ -335,18 +296,15 @@ public static Quaternion fromRotationXYZ(Angle x, Angle y, Angle z) } /** - * Returns a Quaternion created from latitude and longitude rotations. - * Latitude and longitude can be extracted from a Quaternion by calling - * {@link #getLatLon}. + * Returns a Quaternion created from latitude and longitude rotations. Latitude and longitude can be extracted from + * a Quaternion by calling {@link #getLatLon}. * * @param latitude Angle rotation of latitude. * @param longitude Angle rotation of longitude. * @return Quaternion representing combined latitude and longitude rotation. */ - public static Quaternion fromLatLon(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public static Quaternion fromLatLon(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -356,7 +314,7 @@ public static Quaternion fromLatLon(Angle latitude, Angle longitude) double clon = longitude.cosHalfAngle(); double slat = latitude.sinHalfAngle(); double slon = longitude.sinHalfAngle(); - + // The order in which the lat/lon angles are applied is critical. This can be thought of as multiplying two // quaternions together, one for each lat/lon angle. Like matrices, quaternions affect vectors in reverse // order. For example, suppose we construct a quaternion @@ -384,7 +342,6 @@ public static Quaternion fromLatLon(Angle latitude, Angle longitude) // qy = slat * clon; // qz = - slat * slon; // - double qw = clat * clon; double qx = clat * slon; double qy = slat * clon; @@ -396,153 +353,130 @@ public static Quaternion fromLatLon(Angle latitude, Angle longitude) // ============== Arithmetic Functions ======================= // // ============== Arithmetic Functions ======================= // // ============== Arithmetic Functions ======================= // - - public final Quaternion add(Quaternion quaternion) - { - if (quaternion == null) - { + public final Quaternion add(Quaternion quaternion) { + if (quaternion == null) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Quaternion( - this.x + quaternion.x, - this.y + quaternion.y, - this.z + quaternion.z, - this.w + quaternion.w); + this.x + quaternion.x, + this.y + quaternion.y, + this.z + quaternion.z, + this.w + quaternion.w); } - public final Quaternion subtract(Quaternion quaternion) - { - if (quaternion == null) - { + public final Quaternion subtract(Quaternion quaternion) { + if (quaternion == null) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Quaternion( - this.x - quaternion.x, - this.y - quaternion.y, - this.z - quaternion.z, - this.w - quaternion.w); + this.x - quaternion.x, + this.y - quaternion.y, + this.z - quaternion.z, + this.w - quaternion.w); } - public final Quaternion multiplyComponents(double value) - { + public final Quaternion multiplyComponents(double value) { return new Quaternion( - this.x * value, - this.y * value, - this.z * value, - this.w * value); + this.x * value, + this.y * value, + this.z * value, + this.w * value); } - public final Quaternion multiply(Quaternion quaternion) - { - if (quaternion == null) - { + public final Quaternion multiply(Quaternion quaternion) { + if (quaternion == null) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Quaternion( - (this.w * quaternion.x) + (this.x * quaternion.w) + (this.y * quaternion.z) - (this.z * quaternion.y), - (this.w * quaternion.y) + (this.y * quaternion.w) + (this.z * quaternion.x) - (this.x * quaternion.z), - (this.w * quaternion.z) + (this.z * quaternion.w) + (this.x * quaternion.y) - (this.y * quaternion.x), - (this.w * quaternion.w) - (this.x * quaternion.x) - (this.y * quaternion.y) - (this.z * quaternion.z)); + (this.w * quaternion.x) + (this.x * quaternion.w) + (this.y * quaternion.z) - (this.z * quaternion.y), + (this.w * quaternion.y) + (this.y * quaternion.w) + (this.z * quaternion.x) - (this.x * quaternion.z), + (this.w * quaternion.z) + (this.z * quaternion.w) + (this.x * quaternion.y) - (this.y * quaternion.x), + (this.w * quaternion.w) - (this.x * quaternion.x) - (this.y * quaternion.y) - (this.z * quaternion.z)); } - public final Quaternion divideComponents(double value) - { - if (isZero(value)) - { + public final Quaternion divideComponents(double value) { + if (isZero(value)) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", value); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Quaternion( - this.x / value, - this.y / value, - this.z / value, - this.w / value); + this.x / value, + this.y / value, + this.z / value, + this.w / value); } - public final Quaternion divideComponents(Quaternion quaternion) - { - if (quaternion == null) - { + public final Quaternion divideComponents(Quaternion quaternion) { + if (quaternion == null) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Quaternion( - this.x / quaternion.x, - this.y / quaternion.y, - this.z / quaternion.z, - this.w / quaternion.w); + this.x / quaternion.x, + this.y / quaternion.y, + this.z / quaternion.z, + this.w / quaternion.w); } - public final Quaternion getConjugate() - { + public final Quaternion getConjugate() { return new Quaternion( - 0.0 - this.x, - 0.0 - this.y, - 0.0 - this.z, - this.w); + 0.0 - this.x, + 0.0 - this.y, + 0.0 - this.z, + this.w); } - public final Quaternion getNegative() - { + public final Quaternion getNegative() { return new Quaternion( - 0.0 - this.x, - 0.0 - this.y, - 0.0 - this.z, - 0.0 - this.w); + 0.0 - this.x, + 0.0 - this.y, + 0.0 - this.z, + 0.0 - this.w); } // ============== Geometric Functions ======================= // // ============== Geometric Functions ======================= // // ============== Geometric Functions ======================= // - - public final double getLength() - { + public final double getLength() { return Math.sqrt(this.getLengthSquared()); } - public final double getLengthSquared() - { + public final double getLengthSquared() { return (this.x * this.x) - + (this.y * this.y) - + (this.z * this.z) - + (this.w * this.w); + + (this.y * this.y) + + (this.z * this.z) + + (this.w * this.w); } - public final Quaternion normalize() - { + public final Quaternion normalize() { double length = this.getLength(); // Vector has zero length. - if (isZero(length)) - { + if (isZero(length)) { return this; - } - else - { + } else { return new Quaternion( - this.x / length, - this.y / length, - this.z / length, - this.w / length); + this.x / length, + this.y / length, + this.z / length, + this.w / length); } } - public final double dot(Quaternion quaternion) - { - if (quaternion == null) - { + public final double dot(Quaternion quaternion) { + if (quaternion == null) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -551,76 +485,66 @@ public final double dot(Quaternion quaternion) return (this.x * quaternion.x) + (this.y * quaternion.y) + (this.z * quaternion.z) + (this.w * quaternion.w); } - public final Quaternion getInverse() - { + public final Quaternion getInverse() { double length = this.getLength(); // Vector has zero length. - if (isZero(length)) - { + if (isZero(length)) { return this; - } - else - { + } else { return new Quaternion( - (0.0 - this.x) / length, - (0.0 - this.y) / length, - (0.0 - this.z) / length, - this.w / length); + (0.0 - this.x) / length, + (0.0 - this.y) / length, + (0.0 - this.z) / length, + this.w / length); } } // ============== Mixing Functions ======================= // // ============== Mixing Functions ======================= // // ============== Mixing Functions ======================= // - - public static Quaternion mix(double amount, Quaternion value1, Quaternion value2) - { - if ((value1 == null) || (value2 == null)) - { + public static Quaternion mix(double amount, Quaternion value1, Quaternion value2) { + if ((value1 == null) || (value2 == null)) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (amount < 0.0) + if (amount < 0.0) { return value1; - else if (amount > 1.0) + } else if (amount > 1.0) { return value2; + } double t1 = 1.0 - amount; return new Quaternion( - (value1.x * t1) + (value2.x * amount), - (value1.y * t1) + (value2.y * amount), - (value1.z * t1) + (value2.z * amount), - (value1.w * t1) + (value2.w * amount)); + (value1.x * t1) + (value2.x * amount), + (value1.y * t1) + (value2.y * amount), + (value1.z * t1) + (value2.z * amount), + (value1.w * t1) + (value2.w * amount)); } - public static Quaternion slerp(double amount, Quaternion value1, Quaternion value2) - { - if ((value1 == null) || (value2 == null)) - { + public static Quaternion slerp(double amount, Quaternion value1, Quaternion value2) { + if ((value1 == null) || (value2 == null)) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (amount < 0.0) + if (amount < 0.0) { return value1; - else if (amount > 1.0) + } else if (amount > 1.0) { return value2; + } double dot = value1.dot(value2); double x2, y2, z2, w2; - if (dot < 0.0) - { + if (dot < 0.0) { dot = 0.0 - dot; x2 = 0.0 - value2.x; y2 = 0.0 - value2.y; z2 = 0.0 - value2.z; w2 = 0.0 - value2.w; - } - else - { + } else { x2 = value2.x; y2 = value2.y; z2 = value2.z; @@ -636,56 +560,52 @@ else if (amount > 1.0) double sinAngle = Math.sin(angle); t1 = Math.sin((1.0 - amount) * angle) / sinAngle; t2 = Math.sin(amount * angle) / sinAngle; - } - else // just lerp + } else // just lerp { t1 = 1.0 - amount; t2 = amount; } return new Quaternion( - (value1.x * t1) + (x2 * t2), - (value1.y * t1) + (y2 * t2), - (value1.z * t1) + (z2 * t2), - (value1.w * t1) + (w2 * t2)); + (value1.x * t1) + (x2 * t2), + (value1.y * t1) + (y2 * t2), + (value1.z * t1) + (z2 * t2), + (value1.w * t1) + (w2 * t2)); } // ============== Accessor Functions ======================= // // ============== Accessor Functions ======================= // // ============== Accessor Functions ======================= // - - public final Angle getAngle() - { + public final Angle getAngle() { double w = this.w; double length = this.getLength(); - if (!isZero(length) && (length != 1.0)) + if (!isZero(length) && (length != 1.0)) { w /= length; + } double radians = 2.0 * Math.acos(w); - if (Double.isNaN(radians)) + if (Double.isNaN(radians)) { return null; + } return Angle.fromRadians(radians); } - public final Vec4 getAxis() - { + public final Vec4 getAxis() { double x = this.x; double y = this.y; double z = this.z; double length = this.getLength(); - if (!isZero(length) && (length != 1.0)) - { + if (!isZero(length) && (length != 1.0)) { x /= length; y /= length; z /= length; } double vecLength = Math.sqrt((x * x) + (y * y) + (z * z)); - if (!isZero(vecLength) && (vecLength != 1.0)) - { + if (!isZero(vecLength) && (vecLength != 1.0)) { x /= vecLength; y /= vecLength; z /= vecLength; @@ -694,42 +614,42 @@ public final Vec4 getAxis() return new Vec4(x, y, z); } - public final Angle getRotationX() - { + public final Angle getRotationX() { double radians = Math.atan2((2.0 * this.x * this.w) - (2.0 * this.y * this.z), - 1.0 - 2.0 * (this.x * this.x) - 2.0 * (this.z * this.z)); - if (Double.isNaN(radians)) + 1.0 - 2.0 * (this.x * this.x) - 2.0 * (this.z * this.z)); + if (Double.isNaN(radians)) { return null; + } return Angle.fromRadians(radians); } - public final Angle getRotationY() - { + public final Angle getRotationY() { double radians = Math.atan2((2.0 * this.y * this.w) - (2.0 * this.x * this.z), - 1.0 - (2.0 * this.y * this.y) - (2.0 * this.z * this.z)); - if (Double.isNaN(radians)) + 1.0 - (2.0 * this.y * this.y) - (2.0 * this.z * this.z)); + if (Double.isNaN(radians)) { return null; + } return Angle.fromRadians(radians); } - public final Angle getRotationZ() - { + public final Angle getRotationZ() { double radians = Math.asin((2.0 * this.x * this.y) + (2.0 * this.z * this.w)); - if (Double.isNaN(radians)) + if (Double.isNaN(radians)) { return null; + } return Angle.fromRadians(radians); } - public final LatLon getLatLon() - { + public final LatLon getLatLon() { double latRadians = Math.asin((2.0 * this.y * this.w) - (2.0 * this.x * this.z)); double lonRadians = Math.atan2((2.0 * this.y * this.z) + (2.0 * this.x * this.w), - (this.w * this.w) - (this.x * this.x) - (this.y * this.y) + (this.z * this.z)); - if (Double.isNaN(latRadians) || Double.isNaN(lonRadians)) + (this.w * this.w) - (this.x * this.x) - (this.y * this.y) + (this.z * this.z)); + if (Double.isNaN(latRadians) || Double.isNaN(lonRadians)) { return null; + } return LatLon.fromRadians(latRadians, lonRadians); } @@ -737,14 +657,12 @@ public final LatLon getLatLon() // ============== Helper Functions ======================= // // ============== Helper Functions ======================= // // ============== Helper Functions ======================= // - private static final Double PositiveZero = +0.0d; private static final Double NegativeZero = -0.0d; - private static boolean isZero(double value) - { + private static boolean isZero(double value) { return (PositiveZero.compareTo(value) == 0) - || (NegativeZero.compareTo(value) == 0); + || (NegativeZero.compareTo(value) == 0); } } diff --git a/src/gov/nasa/worldwind/geom/Sector.java b/src/gov/nasa/worldwind/geom/Sector.java index d2c7489868..8d67e64073 100644 --- a/src/gov/nasa/worldwind/geom/Sector.java +++ b/src/gov/nasa/worldwind/geom/Sector.java @@ -22,15 +22,19 @@ * 90 degrees latitude and +/- 180 degrees longitude. The minimums and maximums are relative to these ranges, e.g., -80 * is less than 20. Behavior of the class is undefined for angles outside these ranges. Normalization is not performed * on the angles by this class, nor is it verified by the class' methods. See {@link Angle} for a description of - * specifying angles.

        Sector instances are immutable.

        + * specifying angles. + *

        + * Sector instances are immutable.

        * * @author Tom Gaskins * @version $Id: Sector.java 2397 2014-10-28 17:13:04Z dcollins $ * @see Angle */ -public class Sector implements Cacheable, Comparable, Iterable -{ - /** A Sector of latitude [-90 degrees, + 90 degrees] and longitude [-180 degrees, + 180 degrees]. */ +public class Sector implements Cacheable, Comparable, Iterable { + + /** + * A Sector of latitude [-90 degrees, + 90 degrees] and longitude [-180 degrees, + 180 degrees]. + */ public static final Sector FULL_SPHERE = new Sector(Angle.NEG90, Angle.POS90, Angle.NEG180, Angle.POS180); public static final Sector EMPTY_SECTOR = new Sector(Angle.ZERO, Angle.ZERO, Angle.ZERO, Angle.ZERO); @@ -45,45 +49,47 @@ public class Sector implements Cacheable, Comparable, Iterable * Creates a new Sector and initializes it to the specified angles. The angles are assumed to be * normalized to +/- 90 degrees latitude and +/- 180 degrees longitude, but this method does not verify that. * - * @param minLatitude the sector's minimum latitude in degrees. - * @param maxLatitude the sector's maximum latitude in degrees. + * @param minLatitude the sector's minimum latitude in degrees. + * @param maxLatitude the sector's maximum latitude in degrees. * @param minLongitude the sector's minimum longitude in degrees. * @param maxLongitude the sector's maximum longitude in degrees. * * @return the new Sector */ public static Sector fromDegrees(double minLatitude, double maxLatitude, double minLongitude, - double maxLongitude) - { + double maxLongitude) { return new Sector(Angle.fromDegrees(minLatitude), Angle.fromDegrees(maxLatitude), Angle.fromDegrees( - minLongitude), Angle.fromDegrees(maxLongitude)); + minLongitude), Angle.fromDegrees(maxLongitude)); } /** * Creates a new Sector and initializes it to the specified angles. The angles are assumed to be * normalized to +/- 90 degrees latitude and +/- 180 degrees longitude, but this method does not verify that. * - * @param minLatitude the sector's minimum latitude in degrees. - * @param maxLatitude the sector's maximum latitude in degrees. + * @param minLatitude the sector's minimum latitude in degrees. + * @param maxLatitude the sector's maximum latitude in degrees. * @param minLongitude the sector's minimum longitude in degrees. * @param maxLongitude the sector's maximum longitude in degrees. * * @return the new Sector */ public static Sector fromDegreesAndClamp(double minLatitude, double maxLatitude, double minLongitude, - double maxLongitude) - { - if (minLatitude < -90) + double maxLongitude) { + if (minLatitude < -90) { minLatitude = -90; - if (maxLatitude > 90) + } + if (maxLatitude > 90) { maxLatitude = 90; - if (minLongitude < -180) + } + if (minLongitude < -180) { minLongitude = -180; - if (maxLongitude > 180) + } + if (maxLongitude > 180) { maxLongitude = 180; + } return new Sector(Angle.fromDegrees(minLatitude), Angle.fromDegrees(maxLatitude), Angle.fromDegrees( - minLongitude), Angle.fromDegrees(maxLongitude)); + minLongitude), Angle.fromDegrees(maxLongitude)); } /** @@ -98,17 +104,14 @@ public static Sector fromDegreesAndClamp(double minLatitude, double maxLatitude, * * @throws IllegalArgumentException if array is null or if its length is less than 4. */ - public static Sector fromDegrees(double[] array) - { - if (array == null) - { + public static Sector fromDegrees(double[] array) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (array.length < 4) - { + if (array.length < 4) { String message = Logging.getMessage("generic.ArrayInvalidLength", array.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -127,8 +130,7 @@ public static Sector fromDegrees(double[] array) * * @return the new Sector */ - public static Sector fromDegrees(java.awt.geom.Rectangle2D rectangle) - { + public static Sector fromDegrees(java.awt.geom.Rectangle2D rectangle) { return fromDegrees(rectangle.getY(), rectangle.getMaxY(), rectangle.getX(), rectangle.getMaxX()); } @@ -137,50 +139,46 @@ public static Sector fromDegrees(java.awt.geom.Rectangle2D rectangle) * normalized to +/- \u03c0/2 radians latitude and +/- \u03c0 radians longitude, but this method does not verify * that. * - * @param minLatitude the sector's minimum latitude in radians. - * @param maxLatitude the sector's maximum latitude in radians. + * @param minLatitude the sector's minimum latitude in radians. + * @param maxLatitude the sector's maximum latitude in radians. * @param minLongitude the sector's minimum longitude in radians. * @param maxLongitude the sector's maximum longitude in radians. * * @return the new Sector */ public static Sector fromRadians(double minLatitude, double maxLatitude, double minLongitude, - double maxLongitude) - { + double maxLongitude) { return new Sector(Angle.fromRadians(minLatitude), Angle.fromRadians(maxLatitude), Angle.fromRadians( - minLongitude), Angle.fromRadians(maxLongitude)); + minLongitude), Angle.fromRadians(maxLongitude)); } /** * Returns a geographic Sector which bounds the specified UTM rectangle. The UTM rectangle is located in specified * UTM zone and hemisphere. * - * @param zone the UTM zone. - * @param hemisphere the UTM hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link + * @param zone the UTM zone. + * @param hemisphere the UTM hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param minEasting the minimum UTM easting, in meters. - * @param maxEasting the maximum UTM easting, in meters. + * @param minEasting the minimum UTM easting, in meters. + * @param maxEasting the maximum UTM easting, in meters. * @param minNorthing the minimum UTM northing, in meters. * @param maxNorthing the maximum UTM northing, in meters. * * @return a Sector that bounds the specified UTM rectangle. * * @throws IllegalArgumentException if zone is outside the range 1-60, if hemisphere is - * null, or if hemisphere is not one of {@link + * null, or if hemisphere is not one of {@link * gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link gov.nasa.worldwind.avlist.AVKey#SOUTH}. */ public static Sector fromUTMRectangle(int zone, String hemisphere, double minEasting, double maxEasting, - double minNorthing, double maxNorthing) - { - if (zone < 1 || zone > 60) - { + double minNorthing, double maxNorthing) { + if (zone < 1 || zone > 60) { String message = Logging.getMessage("generic.ZoneIsInvalid", zone); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!AVKey.NORTH.equals(hemisphere) && !AVKey.SOUTH.equals(hemisphere)) - { + if (!AVKey.NORTH.equals(hemisphere) && !AVKey.SOUTH.equals(hemisphere)) { String message = Logging.getMessage("generic.HemisphereIsInvalid", hemisphere); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -194,17 +192,16 @@ public static Sector fromUTMRectangle(int zone, String hemisphere, double minEas return boundingSector(Arrays.asList(ll, lr, ur, ul)); } - public static Sector boundingSector(java.util.Iterator positions) - { - if (positions == null) - { + public static Sector boundingSector(java.util.Iterator positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.TracksPointsIteratorNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!positions.hasNext()) + if (!positions.hasNext()) { return EMPTY_SECTOR; + } TrackPoint position = positions.next(); double minLat = position.getLatitude(); @@ -212,71 +209,72 @@ public static Sector boundingSector(java.util.Iterator positions) double maxLat = minLat; double maxLon = minLon; - while (positions.hasNext()) - { + while (positions.hasNext()) { TrackPoint p = positions.next(); double lat = p.getLatitude(); - if (lat < minLat) + if (lat < minLat) { minLat = lat; - else if (lat > maxLat) + } else if (lat > maxLat) { maxLat = lat; + } double lon = p.getLongitude(); - if (lon < minLon) + if (lon < minLon) { minLon = lon; - else if (lon > maxLon) + } else if (lon > maxLon) { maxLon = lon; + } } return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); } - public static Sector boundingSector(Iterable locations) - { - if (locations == null) - { + public static Sector boundingSector(Iterable locations) { + if (locations == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!locations.iterator().hasNext()) + if (!locations.iterator().hasNext()) { return EMPTY_SECTOR; // TODO: should be returning null - + } double minLat = Angle.POS90.getDegrees(); double minLon = Angle.POS180.getDegrees(); double maxLat = Angle.NEG90.getDegrees(); double maxLon = Angle.NEG180.getDegrees(); - for (LatLon p : locations) - { + for (LatLon p : locations) { double lat = p.getLatitude().getDegrees(); - if (lat < minLat) + if (lat < minLat) { minLat = lat; - if (lat > maxLat) + } + if (lat > maxLat) { maxLat = lat; + } double lon = p.getLongitude().getDegrees(); - if (lon < minLon) + if (lon < minLon) { minLon = lon; - if (lon > maxLon) + } + if (lon > maxLon) { maxLon = lon; + } } return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); } - public static Sector[] splitBoundingSectors(Iterable locations) - { - if (locations == null) - { + public static Sector[] splitBoundingSectors(Iterable locations) { + if (locations == null) { String message = Logging.getMessage("nullValue.LocationInListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!locations.iterator().hasNext()) + if (!locations.iterator().hasNext()) { return null; + } double minLat = Angle.POS90.getDegrees(); double minLon = Angle.POS180.getDegrees(); @@ -285,27 +283,27 @@ public static Sector[] splitBoundingSectors(Iterable locations LatLon lastLocation = null; - for (LatLon ll : locations) - { + for (LatLon ll : locations) { double lat = ll.getLatitude().getDegrees(); - if (lat < minLat) + if (lat < minLat) { minLat = lat; - if (lat > maxLat) + } + if (lat > maxLat) { maxLat = lat; + } double lon = ll.getLongitude().getDegrees(); - if (lon >= 0 && lon < minLon) + if (lon >= 0 && lon < minLon) { minLon = lon; - if (lon <= 0 && lon > maxLon) + } + if (lon <= 0 && lon > maxLon) { maxLon = lon; + } - if (lastLocation != null) - { + if (lastLocation != null) { double lastLon = lastLocation.getLongitude().getDegrees(); - if (Math.signum(lon) != Math.signum(lastLon)) - { - if (Math.abs(lon - lastLon) < 180) - { + if (Math.signum(lon) != Math.signum(lastLon)) { + if (Math.abs(lon - lastLon) < 180) { // Crossing the zero longitude line too maxLon = 0; minLon = 0; @@ -315,20 +313,18 @@ public static Sector[] splitBoundingSectors(Iterable locations lastLocation = ll; } - if (minLat == maxLat && minLon == maxLon) + if (minLat == maxLat && minLon == maxLon) { return null; + } - return new Sector[] - { - Sector.fromDegrees(minLat, maxLat, minLon, 180), // Sector on eastern hemisphere. - Sector.fromDegrees(minLat, maxLat, -180, maxLon) // Sector on western hemisphere. - }; + return new Sector[]{ + Sector.fromDegrees(minLat, maxLat, minLon, 180), // Sector on eastern hemisphere. + Sector.fromDegrees(minLat, maxLat, -180, maxLon) // Sector on western hemisphere. + }; } - public static Sector boundingSector(LatLon pA, LatLon pB) - { - if (pA == null || pB == null) - { + public static Sector boundingSector(LatLon pA, LatLon pB) { + if (pA == null || pB == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -339,15 +335,17 @@ public static Sector boundingSector(LatLon pA, LatLon pB) double maxLat = pA.getLatitude().degrees; double maxLon = pA.getLongitude().degrees; - if (pB.getLatitude().degrees < minLat) + if (pB.getLatitude().degrees < minLat) { minLat = pB.getLatitude().degrees; - else if (pB.getLatitude().degrees > maxLat) + } else if (pB.getLatitude().degrees > maxLat) { maxLat = pB.getLatitude().degrees; + } - if (pB.getLongitude().degrees < minLon) + if (pB.getLongitude().degrees < minLon) { minLon = pB.getLongitude().degrees; - else if (pB.getLongitude().degrees > maxLon) + } else if (pB.getLongitude().degrees > maxLon) { maxLon = pB.getLongitude().degrees; + } return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); } @@ -356,24 +354,24 @@ else if (pB.getLongitude().degrees > maxLon) * Returns a new Sector encompassing a circle centered at a given position, with a given radius in * meter. * - * @param globe a Globe instance. + * @param globe a Globe instance. * @param center the circle center position. * @param radius the circle radius in meter. * * @return the circle bounding sector. */ - public static Sector boundingSector(Globe globe, LatLon center, double radius) - { + public static Sector boundingSector(Globe globe, LatLon center, double radius) { double halfDeltaLatRadians = radius / globe.getRadiusAt(center); double halfDeltaLonRadians = Math.PI * 2; - if (center.getLatitude().cos() > 0) + if (center.getLatitude().cos() > 0) { halfDeltaLonRadians = halfDeltaLatRadians / center.getLatitude().cos(); + } return new Sector( - Angle.fromRadiansLatitude(center.getLatitude().radians - halfDeltaLatRadians), - Angle.fromRadiansLatitude(center.getLatitude().radians + halfDeltaLatRadians), - Angle.fromRadiansLongitude(center.getLongitude().radians - halfDeltaLonRadians), - Angle.fromRadiansLongitude(center.getLongitude().radians + halfDeltaLonRadians)); + Angle.fromRadiansLatitude(center.getLatitude().radians - halfDeltaLatRadians), + Angle.fromRadiansLatitude(center.getLatitude().radians + halfDeltaLatRadians), + Angle.fromRadiansLongitude(center.getLongitude().radians - halfDeltaLonRadians), + Angle.fromRadiansLongitude(center.getLongitude().radians + halfDeltaLonRadians)); } /** @@ -382,7 +380,7 @@ public static Sector boundingSector(Globe globe, LatLon center, double radius) * for each side of the dateline. Otherwise, this will return a single bounding sector. This returns null if the * radius is zero. * - * @param globe a Globe instance. + * @param globe a Globe instance. * @param center the circle center location. * @param radius the circle radius in meters. * @@ -390,24 +388,20 @@ public static Sector boundingSector(Globe globe, LatLon center, double radius) * * @throws IllegalArgumentException if either the globe or center is null, or if the radius is less than zero. */ - public static Sector[] splitBoundingSectors(Globe globe, LatLon center, double radius) - { - if (globe == null) - { + public static Sector[] splitBoundingSectors(Globe globe, LatLon center, double radius) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius < 0) - { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -422,8 +416,7 @@ public static Sector[] splitBoundingSectors(Globe globe, LatLon center, double r double maxLon; // If the circle does not cross a pole, then compute the max and min longitude. - if (minLat >= Angle.NEG90.radians && maxLat <= Angle.POS90.radians) - { + if (minLat >= Angle.NEG90.radians && maxLat <= Angle.POS90.radians) { // We want to find the maximum and minimum longitude values on the circle. We will start with equation 5-6 // from "Map Projections - A Working Manual", page 31, and solve for the value of Az that will maximize // lon - lon0. @@ -455,41 +448,38 @@ public static Sector[] splitBoundingSectors(Globe globe, LatLon center, double r // circle would cover a pole. double az; if (Math.abs(Angle.POS90.radians - halfDeltaLatRadians) - > 0.001) // Consider within 1/1000th of a radian to be equal + > 0.001) // Consider within 1/1000th of a radian to be equal + { az = Math.acos(Math.tan(halfDeltaLatRadians) * Math.tan(center.latitude.radians)); - else + } else { az = Angle.POS90.radians; + } LatLon east = LatLon.greatCircleEndPosition(center, az, halfDeltaLatRadians); LatLon west = LatLon.greatCircleEndPosition(center, -az, halfDeltaLatRadians); minLon = Math.min(east.longitude.radians, west.longitude.radians); maxLon = Math.max(east.longitude.radians, west.longitude.radians); - } - else - { + } else { // If the circle crosses the pole then it spans the full circle of longitude minLon = Angle.NEG180.radians; maxLon = Angle.POS180.radians; } LatLon ll = new LatLon( - Angle.fromRadiansLatitude(minLat), - Angle.normalizedLongitude(Angle.fromRadians(minLon))); + Angle.fromRadiansLatitude(minLat), + Angle.normalizedLongitude(Angle.fromRadians(minLon))); LatLon ur = new LatLon( - Angle.fromRadiansLatitude(maxLat), - Angle.normalizedLongitude(Angle.fromRadians(maxLon))); + Angle.fromRadiansLatitude(maxLat), + Angle.normalizedLongitude(Angle.fromRadians(maxLon))); Iterable locations = java.util.Arrays.asList(ll, ur); - if (LatLon.locationsCrossDateLine(locations)) - { + if (LatLon.locationsCrossDateLine(locations)) { return splitBoundingSectors(locations); - } - else - { + } else { Sector s = boundingSector(locations); - return (s != null && !s.equals(Sector.EMPTY_SECTOR)) ? new Sector[] {s} : null; + return (s != null && !s.equals(Sector.EMPTY_SECTOR)) ? new Sector[]{s} : null; } } @@ -497,17 +487,15 @@ public static Sector[] splitBoundingSectors(Globe globe, LatLon center, double r * Creates a new Sector and initializes it to the specified angles. The angles are assumed to be * normalized to +/- 90 degrees latitude and +/- 180 degrees longitude, but this method does not verify that. * - * @param minLatitude the sector's minimum latitude. - * @param maxLatitude the sector's maximum latitude. + * @param minLatitude the sector's minimum latitude. + * @param maxLatitude the sector's maximum latitude. * @param minLongitude the sector's minimum longitude. * @param maxLongitude the sector's maximum longitude. * * @throws IllegalArgumentException if any of the angles are null */ - public Sector(Angle minLatitude, Angle maxLatitude, Angle minLongitude, Angle maxLongitude) - { - if (minLatitude == null || maxLatitude == null || minLongitude == null || maxLongitude == null) - { + public Sector(Angle minLatitude, Angle maxLatitude, Angle minLongitude, Angle maxLongitude) { + if (minLatitude == null || maxLatitude == null || minLongitude == null || maxLongitude == null) { String message = Logging.getMessage("nullValue.InputAnglesNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -521,10 +509,8 @@ public Sector(Angle minLatitude, Angle maxLatitude, Angle minLongitude, Angle ma this.deltaLon = Angle.fromDegrees(this.maxLongitude.degrees - this.minLongitude.degrees); } - public Sector(Sector sector) - { - if (sector == null) - { + public Sector(Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -543,8 +529,7 @@ public Sector(Sector sector) * * @return The sector's minimum latitude. */ - public final Angle getMinLatitude() - { + public final Angle getMinLatitude() { return minLatitude; } @@ -553,8 +538,7 @@ public final Angle getMinLatitude() * * @return The sector's minimum longitude. */ - public final Angle getMinLongitude() - { + public final Angle getMinLongitude() { return minLongitude; } @@ -563,8 +547,7 @@ public final Angle getMinLongitude() * * @return The sector's maximum latitude. */ - public final Angle getMaxLatitude() - { + public final Angle getMaxLatitude() { return maxLatitude; } @@ -573,8 +556,7 @@ public final Angle getMaxLatitude() * * @return The sector's maximum longitude. */ - public final Angle getMaxLongitude() - { + public final Angle getMaxLongitude() { return maxLongitude; } @@ -583,18 +565,15 @@ public final Angle getMaxLongitude() * * @return The angular difference between the sector's minimum and maximum latitudes. */ - public final Angle getDeltaLat() - { + public final Angle getDeltaLat() { return this.deltaLat;//Angle.fromDegrees(this.maxLatitude.degrees - this.minLatitude.degrees); } - public final double getDeltaLatDegrees() - { + public final double getDeltaLatDegrees() { return this.deltaLat.degrees;//this.maxLatitude.degrees - this.minLatitude.degrees; } - public final double getDeltaLatRadians() - { + public final double getDeltaLatRadians() { return this.deltaLat.radians;//this.maxLatitude.radians - this.minLatitude.radians; } @@ -603,38 +582,33 @@ public final double getDeltaLatRadians() * * @return The angular difference between the sector's minimum and maximum longitudes */ - public final Angle getDeltaLon() - { + public final Angle getDeltaLon() { return this.deltaLon;//Angle.fromDegrees(this.maxLongitude.degrees - this.minLongitude.degrees); } - public final double getDeltaLonDegrees() - { + public final double getDeltaLonDegrees() { return this.deltaLon.degrees;//this.maxLongitude.degrees - this.minLongitude.degrees; } - public final double getDeltaLonRadians() - { + public final double getDeltaLonRadians() { return this.deltaLon.radians;//this.maxLongitude.radians - this.minLongitude.radians; } - public boolean isWithinLatLonLimits() - { + public boolean isWithinLatLonLimits() { return this.minLatitude.degrees >= -90 && this.maxLatitude.degrees <= 90 - && this.minLongitude.degrees >= -180 && this.maxLongitude.degrees <= 180; + && this.minLongitude.degrees >= -180 && this.maxLongitude.degrees <= 180; } - public boolean isSameSector(Iterable corners) - { - if (corners == null) - { + public boolean isSameSector(Iterable corners) { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!isSector(corners)) + if (!isSector(corners)) { return false; + } Sector s = Sector.boundingSector(corners); @@ -642,10 +616,8 @@ public boolean isSameSector(Iterable corners) } @SuppressWarnings({"RedundantIfStatement"}) - public static boolean isSector(Iterable corners) - { - if (corners == null) - { + public static boolean isSector(Iterable corners) { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -654,25 +626,30 @@ public static boolean isSector(Iterable corners) LatLon[] latlons = new LatLon[5]; int i = 0; - for (LatLon ll : corners) - { - if (i > 4 || ll == null) + for (LatLon ll : corners) { + if (i > 4 || ll == null) { return false; + } latlons[i++] = ll; } - if (!latlons[0].getLatitude().equals(latlons[1].getLatitude())) + if (!latlons[0].getLatitude().equals(latlons[1].getLatitude())) { return false; - if (!latlons[2].getLatitude().equals(latlons[3].getLatitude())) + } + if (!latlons[2].getLatitude().equals(latlons[3].getLatitude())) { return false; - if (!latlons[0].getLongitude().equals(latlons[3].getLongitude())) + } + if (!latlons[0].getLongitude().equals(latlons[3].getLongitude())) { return false; - if (!latlons[1].getLongitude().equals(latlons[2].getLongitude())) + } + if (!latlons[1].getLongitude().equals(latlons[2].getLongitude())) { return false; + } - if (i == 5 && !latlons[4].equals(latlons[0])) + if (i == 5 && !latlons[4].equals(latlons[0])) { return false; + } return true; } @@ -683,8 +660,7 @@ public static boolean isSector(Iterable corners) * * @return The latitude and longitude of the sector's angular center */ - public LatLon getCentroid() - { + public LatLon getCentroid() { Angle la = Angle.fromDegrees(0.5 * (this.getMaxLatitude().degrees + this.getMinLatitude().degrees)); Angle lo = Angle.fromDegrees(0.5 * (this.getMaxLongitude().degrees + this.getMinLongitude().degrees)); return new LatLon(la, lo); @@ -693,17 +669,15 @@ public LatLon getCentroid() /** * Computes the Cartesian coordinates of a Sector's center. * - * @param globe The globe associated with the sector. + * @param globe The globe associated with the sector. * @param exaggeration The vertical exaggeration to apply. * * @return the Cartesian coordinates of the sector's center. * * @throws IllegalArgumentException if globe is null. */ - public Vec4 computeCenterPoint(Globe globe, double exaggeration) - { - if (globe == null) - { + public Vec4 computeCenterPoint(Globe globe, double exaggeration) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -720,17 +694,15 @@ public Vec4 computeCenterPoint(Globe globe, double exaggeration) /** * Computes the Cartesian coordinates of a Sector's corners. * - * @param globe The globe associated with the sector. + * @param globe The globe associated with the sector. * @param exaggeration The vertical exaggeration to apply. * * @return an array of four Cartesian points. * * @throws IllegalArgumentException if globe is null. */ - public Vec4[] computeCornerPoints(Globe globe, double exaggeration) - { - if (globe == null) - { + public Vec4[] computeCornerPoints(Globe globe, double exaggeration) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -753,25 +725,22 @@ public Vec4[] computeCornerPoints(Globe globe, double exaggeration) /** * Returns a sphere that minimally surrounds the sector at a specified vertical exaggeration. * - * @param globe the globe the sector is associated with + * @param globe the globe the sector is associated with * @param verticalExaggeration the vertical exaggeration to apply to the globe's elevations when computing the - * sphere. - * @param sector the sector to return the bounding sphere for. + * sphere. + * @param sector the sector to return the bounding sphere for. * * @return The minimal bounding sphere in Cartesian coordinates. * * @throws IllegalArgumentException if globe or sector is null */ - static public Sphere computeBoundingSphere(Globe globe, double verticalExaggeration, Sector sector) - { - if (globe == null) - { + static public Sphere computeBoundingSphere(Globe globe, double verticalExaggeration, Sector sector) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -803,25 +772,22 @@ static public Sphere computeBoundingSphere(Globe globe, double verticalExaggerat * the minimum and maximum elevation are equal, this assumes a maximum elevation of 10 + the minimum. If this fails * to compute a box enclosing the sector, this returns a unit box enclosing one of the boxes corners. * - * @param globe the globe the extent relates to. + * @param globe the globe the extent relates to. * @param verticalExaggeration the globe's vertical surface exaggeration. - * @param sector a sector on the globe's surface to compute a bounding box for. + * @param sector a sector on the globe's surface to compute a bounding box for. * * @return a box enclosing the globe's surface on the specified sector. * * @throws IllegalArgumentException if either the globe or sector is null. */ - public static Box computeBoundingBox(Globe globe, double verticalExaggeration, Sector sector) - { - if (globe == null) - { + public static Box computeBoundingBox(Globe globe, double verticalExaggeration, Sector sector) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -838,28 +804,25 @@ public static Box computeBoundingBox(Globe globe, double verticalExaggeration, S * maximum elevation are equal, this assumes a maximum elevation of 10 + the minimum. If this fails to compute a box * enclosing the sector, this returns a unit box enclosing one of the boxes corners. * - * @param globe the globe the extent relates to. + * @param globe the globe the extent relates to. * @param verticalExaggeration the globe's vertical surface exaggeration. - * @param sector a sector on the globe's surface to compute a bounding box for. - * @param minElevation the globe's minimum elevation in the sector. - * @param maxElevation the globe's maximum elevation in the sector. + * @param sector a sector on the globe's surface to compute a bounding box for. + * @param minElevation the globe's minimum elevation in the sector. + * @param maxElevation the globe's maximum elevation in the sector. * * @return a box enclosing the globe's surface on the specified sector. * * @throws IllegalArgumentException if either the globe or sector is null. */ public static Box computeBoundingBox(Globe globe, double verticalExaggeration, Sector sector, - double minElevation, double maxElevation) - { - if (globe == null) - { + double minElevation, double maxElevation) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -870,8 +833,7 @@ public static Box computeBoundingBox(Globe globe, double verticalExaggeration, S double max = maxElevation * verticalExaggeration; // Ensure the top and bottom heights are not equal. - if (min == max) - { + if (min == max) { max = min + 10; } @@ -885,12 +847,9 @@ public static Box computeBoundingBox(Globe globe, double verticalExaggeration, S Vec4[] points = new Vec4[15]; globe.computePointsFromPositions(sector, 3, 5, elevations, points); - try - { + try { return Box.computeBoundingBox(Arrays.asList(points)); - } - catch (Exception e) - { + } catch (Exception e) { return new Box(points[0]); // unit box around point } } @@ -898,26 +857,23 @@ public static Box computeBoundingBox(Globe globe, double verticalExaggeration, S /** * Returns a cylinder that minimally surrounds the specified sector at a specified vertical exaggeration. * - * @param globe The globe associated with the sector. + * @param globe The globe associated with the sector. * @param verticalExaggeration the vertical exaggeration to apply to the minimum and maximum elevations when - * computing the cylinder. - * @param sector the sector to return the bounding cylinder for. + * computing the cylinder. + * @param sector the sector to return the bounding cylinder for. * * @return The minimal bounding cylinder in Cartesian coordinates. * * @throws IllegalArgumentException if sector is null */ - static public Cylinder computeBoundingCylinder(Globe globe, double verticalExaggeration, Sector sector) - { - if (globe == null) - { + static public Cylinder computeBoundingCylinder(Globe globe, double verticalExaggeration, Sector sector) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -925,36 +881,33 @@ static public Cylinder computeBoundingCylinder(Globe globe, double verticalExagg double[] minAndMaxElevations = globe.getMinAndMaxElevations(sector); return computeBoundingCylinder(globe, verticalExaggeration, sector, - minAndMaxElevations[0], minAndMaxElevations[1]); + minAndMaxElevations[0], minAndMaxElevations[1]); } /** * Returns a cylinder that minimally surrounds the specified sector at a specified vertical exaggeration and minimum * and maximum elevations for the sector. * - * @param globe The globe associated with the sector. + * @param globe The globe associated with the sector. * @param verticalExaggeration the vertical exaggeration to apply to the minimum and maximum elevations when - * computing the cylinder. - * @param sector the sector to return the bounding cylinder for. - * @param minElevation the minimum elevation of the bounding cylinder. - * @param maxElevation the maximum elevation of the bounding cylinder. + * computing the cylinder. + * @param sector the sector to return the bounding cylinder for. + * @param minElevation the minimum elevation of the bounding cylinder. + * @param maxElevation the maximum elevation of the bounding cylinder. * * @return The minimal bounding cylinder in Cartesian coordinates. * * @throws IllegalArgumentException if sector is null */ public static Cylinder computeBoundingCylinder(Globe globe, double verticalExaggeration, Sector sector, - double minElevation, double maxElevation) - { - if (globe == null) - { + double minElevation, double maxElevation) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -964,19 +917,17 @@ public static Cylinder computeBoundingCylinder(Globe globe, double verticalExagg double minHeight = minElevation * verticalExaggeration; double maxHeight = maxElevation * verticalExaggeration; - if (minHeight == maxHeight) + if (minHeight == maxHeight) { maxHeight = minHeight + 1; // ensure the top and bottom of the cylinder won't be coincident - + } List points = new ArrayList(); - for (LatLon ll : sector) - { + for (LatLon ll : sector) { points.add(globe.computePointFromPosition(ll, minHeight)); points.add(globe.computePointFromPosition(ll, maxHeight)); } points.add(globe.computePointFromPosition(sector.getCentroid(), maxHeight)); - if (sector.getDeltaLonDegrees() > 180) - { + if (sector.getDeltaLonDegrees() > 180) { // Need to compute more points to ensure the box encompasses the full sector. Angle cLon = sector.getCentroid().getLongitude(); Angle cLat = sector.getCentroid().getLatitude(); @@ -994,18 +945,14 @@ public static Cylinder computeBoundingCylinder(Globe globe, double verticalExagg points.add(globe.computePointFromPosition(cLat, sector.getMaxLongitude(), maxHeight)); } - try - { + try { return Cylinder.computeBoundingCylinder(points); - } - catch (Exception e) - { + } catch (Exception e) { return new Cylinder(points.get(0), points.get(0).add3(Vec4.UNIT_Y), 1); } } - static public Cylinder computeBoundingCylinderOrig(Globe globe, double verticalExaggeration, Sector sector) - { + static public Cylinder computeBoundingCylinderOrig(Globe globe, double verticalExaggeration, Sector sector) { return Cylinder.computeVerticalBoundingCylinder(globe, verticalExaggeration, sector); } @@ -1013,28 +960,25 @@ static public Cylinder computeBoundingCylinderOrig(Globe globe, double verticalE * Returns a cylinder that minimally surrounds the specified minimum and maximum elevations in the sector at a * specified vertical exaggeration. * - * @param globe The globe associated with the sector. + * @param globe The globe associated with the sector. * @param verticalExaggeration the vertical exaggeration to apply to the minimum and maximum elevations when - * computing the cylinder. - * @param sector the sector to return the bounding cylinder for. - * @param minElevation the minimum elevation of the bounding cylinder. - * @param maxElevation the maximum elevation of the bounding cylinder. + * computing the cylinder. + * @param sector the sector to return the bounding cylinder for. + * @param minElevation the minimum elevation of the bounding cylinder. + * @param maxElevation the maximum elevation of the bounding cylinder. * * @return The minimal bounding cylinder in Cartesian coordinates. * * @throws IllegalArgumentException if sector is null */ public static Cylinder computeBoundingCylinderOrig(Globe globe, double verticalExaggeration, Sector sector, - double minElevation, double maxElevation) - { + double minElevation, double maxElevation) { return Cylinder.computeVerticalBoundingCylinder(globe, verticalExaggeration, sector, minElevation, - maxElevation); + maxElevation); } - public final boolean contains(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public final boolean contains(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1054,10 +998,8 @@ public final boolean contains(Angle latitude, Angle longitude) * * @throws IllegalArgumentException if latlon is null. */ - public final boolean contains(LatLon latLon) - { - if (latLon == null) - { + public final boolean contains(LatLon latLon) { + if (latLon == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1071,21 +1013,19 @@ public final boolean contains(LatLon latLon) * are assumed to be normalized to +/- 90 degrees latitude and +/- 180 degrees longitude. The result of the * operation is undefined if they are not. * - * @param radiansLatitude the latitude in radians of the position to test, normalized +/- π. + * @param radiansLatitude the latitude in radians of the position to test, normalized +/- π. * @param radiansLongitude the longitude in radians of the position to test, normalized +/- 2π. * * @return true if the position is within the sector, false otherwise. */ - public boolean containsRadians(double radiansLatitude, double radiansLongitude) - { + public boolean containsRadians(double radiansLatitude, double radiansLongitude) { return radiansLatitude >= this.minLatitude.radians && radiansLatitude <= this.maxLatitude.radians - && radiansLongitude >= this.minLongitude.radians && radiansLongitude <= this.maxLongitude.radians; + && radiansLongitude >= this.minLongitude.radians && radiansLongitude <= this.maxLongitude.radians; } - public boolean containsDegrees(double degreesLatitude, double degreesLongitude) - { + public boolean containsDegrees(double degreesLatitude, double degreesLongitude) { return degreesLatitude >= this.minLatitude.degrees && degreesLatitude <= this.maxLatitude.degrees - && degreesLongitude >= this.minLongitude.degrees && degreesLongitude <= this.maxLongitude.degrees; + && degreesLongitude >= this.minLongitude.degrees && degreesLongitude <= this.maxLongitude.degrees; } /** @@ -1097,21 +1037,25 @@ public boolean containsDegrees(double degreesLatitude, double degreesLongitude) * * @return true if this sector fully contains the input sector, otherwise false. */ - public boolean contains(Sector that) - { - if (that == null) + public boolean contains(Sector that) { + if (that == null) { return false; + } // Assumes normalized angles -- [-180, 180], [-90, 90] - if (that.minLongitude.degrees < this.minLongitude.degrees) + if (that.minLongitude.degrees < this.minLongitude.degrees) { return false; - if (that.maxLongitude.degrees > this.maxLongitude.degrees) + } + if (that.maxLongitude.degrees > this.maxLongitude.degrees) { return false; - if (that.minLatitude.degrees < this.minLatitude.degrees) + } + if (that.minLatitude.degrees < this.minLatitude.degrees) { return false; + } //noinspection RedundantIfStatement - if (that.maxLatitude.degrees > this.maxLatitude.degrees) + if (that.maxLatitude.degrees > this.maxLatitude.degrees) { return false; + } return true; } @@ -1125,21 +1069,25 @@ public boolean contains(Sector that) * * @return true if the sectors intersect, otherwise false. */ - public boolean intersects(Sector that) - { - if (that == null) + public boolean intersects(Sector that) { + if (that == null) { return false; + } // Assumes normalized angles -- [-180, 180], [-90, 90] - if (that.maxLongitude.degrees < this.minLongitude.degrees) + if (that.maxLongitude.degrees < this.minLongitude.degrees) { return false; - if (that.minLongitude.degrees > this.maxLongitude.degrees) + } + if (that.minLongitude.degrees > this.maxLongitude.degrees) { return false; - if (that.maxLatitude.degrees < this.minLatitude.degrees) + } + if (that.maxLatitude.degrees < this.minLatitude.degrees) { return false; + } //noinspection RedundantIfStatement - if (that.minLatitude.degrees > this.maxLatitude.degrees) + if (that.minLatitude.degrees > this.maxLatitude.degrees) { return false; + } return true; } @@ -1155,21 +1103,25 @@ public boolean intersects(Sector that) * * @see #intersects(Sector) */ - public boolean intersectsInterior(Sector that) - { - if (that == null) + public boolean intersectsInterior(Sector that) { + if (that == null) { return false; + } // Assumes normalized angles -- [-180, 180], [-90, 90] - if (that.maxLongitude.degrees <= this.minLongitude.degrees) + if (that.maxLongitude.degrees <= this.minLongitude.degrees) { return false; - if (that.minLongitude.degrees >= this.maxLongitude.degrees) + } + if (that.minLongitude.degrees >= this.maxLongitude.degrees) { return false; - if (that.maxLatitude.degrees <= this.minLatitude.degrees) + } + if (that.maxLatitude.degrees <= this.minLatitude.degrees) { return false; + } //noinspection RedundantIfStatement - if (that.minLatitude.degrees >= this.maxLatitude.degrees) + if (that.minLatitude.degrees >= this.maxLatitude.degrees) { return false; + } return true; } @@ -1181,23 +1133,20 @@ public boolean intersectsInterior(Sector that) * begin and end locations. * * @param begin the line segment begin location. - * @param end the line segment end location. + * @param end the line segment end location. * * @return true true if this sector intersects the line segment, otherwise false. * * @throws IllegalArgumentException if either the begin location or the end location is null. */ - public boolean intersectsSegment(LatLon begin, LatLon end) - { - if (begin == null) - { + public boolean intersectsSegment(LatLon begin, LatLon end) { + if (begin == null) { String message = Logging.getMessage("nullValue.BeginIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (end == null) - { + if (end == null) { String message = Logging.getMessage("nullValue.EndIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1217,21 +1166,19 @@ public boolean intersectsSegment(LatLon begin, LatLon end) Vec4 diff = segmentCenter.subtract3(boxCenter); - if (Math.abs(diff.x) > (boxExtentX + segmentExtent * Math.abs(segmentDirection.x))) - { + if (Math.abs(diff.x) > (boxExtentX + segmentExtent * Math.abs(segmentDirection.x))) { return false; } - if (Math.abs(diff.y) > (boxExtentY + segmentExtent * Math.abs(segmentDirection.y))) - { + if (Math.abs(diff.y) > (boxExtentY + segmentExtent * Math.abs(segmentDirection.y))) { return false; } //noinspection SuspiciousNameCombination Vec4 segmentPerp = new Vec4(segmentDirection.y, -segmentDirection.x, 0); - return Math.abs(segmentPerp.dot3(diff)) <= - (boxExtentX * Math.abs(segmentPerp.x) + boxExtentY * Math.abs(segmentPerp.y)); + return Math.abs(segmentPerp.dot3(diff)) + <= (boxExtentX * Math.abs(segmentPerp.x) + boxExtentY * Math.abs(segmentPerp.y)); } /** @@ -1244,19 +1191,17 @@ public boolean intersectsSegment(LatLon begin, LatLon end) * * @throws java.lang.IllegalArgumentException if the iterable is null. */ - public boolean intersectsAny(Iterable sectors) - { - if (sectors == null) - { + public boolean intersectsAny(Iterable sectors) { + if (sectors == null) { String msg = Logging.getMessage("nullValue.SectorListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (Sector s : sectors) - { - if (s != null && s.intersects(this)) + for (Sector s : sectors) { + if (s != null && s.intersects(this)) { return true; + } } return false; @@ -1271,58 +1216,65 @@ public boolean intersectsAny(Iterable sectors) * @param that the sector to join with this. * * @return A new sector formed from the extremes of the two sectors, or this if the incoming sector is - * null. + * null. */ - public final Sector union(Sector that) - { - if (that == null) + public final Sector union(Sector that) { + if (that == null) { return this; + } Angle minLat = this.minLatitude; Angle maxLat = this.maxLatitude; Angle minLon = this.minLongitude; Angle maxLon = this.maxLongitude; - if (that.minLatitude.degrees < this.minLatitude.degrees) + if (that.minLatitude.degrees < this.minLatitude.degrees) { minLat = that.minLatitude; - if (that.maxLatitude.degrees > this.maxLatitude.degrees) + } + if (that.maxLatitude.degrees > this.maxLatitude.degrees) { maxLat = that.maxLatitude; - if (that.minLongitude.degrees < this.minLongitude.degrees) + } + if (that.minLongitude.degrees < this.minLongitude.degrees) { minLon = that.minLongitude; - if (that.maxLongitude.degrees > this.maxLongitude.degrees) + } + if (that.maxLongitude.degrees > this.maxLongitude.degrees) { maxLon = that.maxLongitude; + } return new Sector(minLat, maxLat, minLon, maxLon); } - public final Sector union(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) + public final Sector union(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { return this; + } Angle minLat = this.minLatitude; Angle maxLat = this.maxLatitude; Angle minLon = this.minLongitude; Angle maxLon = this.maxLongitude; - if (latitude.degrees < this.minLatitude.degrees) + if (latitude.degrees < this.minLatitude.degrees) { minLat = latitude; - if (latitude.degrees > this.maxLatitude.degrees) + } + if (latitude.degrees > this.maxLatitude.degrees) { maxLat = latitude; - if (longitude.degrees < this.minLongitude.degrees) + } + if (longitude.degrees < this.minLongitude.degrees) { minLon = longitude; - if (longitude.degrees > this.maxLongitude.degrees) + } + if (longitude.degrees > this.maxLongitude.degrees) { maxLon = longitude; + } return new Sector(minLat, maxLat, minLon, maxLon); } - public static Sector union(Sector sectorA, Sector sectorB) - { - if (sectorA == null || sectorB == null) - { - if (sectorA == sectorB) + public static Sector union(Sector sectorA, Sector sectorB) { + if (sectorA == null || sectorB == null) { + if (sectorA == sectorB) { return sectorA; + } return sectorB == null ? sectorA : sectorB; } @@ -1330,10 +1282,8 @@ public static Sector union(Sector sectorA, Sector sectorB) return sectorA.union(sectorB); } - public static Sector union(Iterable sectors) - { - if (sectors == null) - { + public static Sector union(Iterable sectors) { + if (sectors == null) { String msg = Logging.getMessage("nullValue.SectorListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1344,54 +1294,60 @@ public static Sector union(Iterable sectors) Angle minLon = Angle.POS180; Angle maxLon = Angle.NEG180; - for (Sector s : sectors) - { - if (s == null) + for (Sector s : sectors) { + if (s == null) { continue; + } - for (LatLon p : s) - { - if (p.getLatitude().degrees < minLat.degrees) + for (LatLon p : s) { + if (p.getLatitude().degrees < minLat.degrees) { minLat = p.getLatitude(); - if (p.getLatitude().degrees > maxLat.degrees) + } + if (p.getLatitude().degrees > maxLat.degrees) { maxLat = p.getLatitude(); - if (p.getLongitude().degrees < minLon.degrees) + } + if (p.getLongitude().degrees < minLon.degrees) { minLon = p.getLongitude(); - if (p.getLongitude().degrees > maxLon.degrees) + } + if (p.getLongitude().degrees > maxLon.degrees) { maxLon = p.getLongitude(); + } } } return new Sector(minLat, maxLat, minLon, maxLon); } - public final Sector intersection(Sector that) - { - if (that == null) + public final Sector intersection(Sector that) { + if (that == null) { return this; + } Angle minLat, maxLat; minLat = (this.minLatitude.degrees > that.minLatitude.degrees) ? this.minLatitude : that.minLatitude; maxLat = (this.maxLatitude.degrees < that.maxLatitude.degrees) ? this.maxLatitude : that.maxLatitude; - if (minLat.degrees > maxLat.degrees) + if (minLat.degrees > maxLat.degrees) { return null; + } Angle minLon, maxLon; minLon = (this.minLongitude.degrees > that.minLongitude.degrees) ? this.minLongitude : that.minLongitude; maxLon = (this.maxLongitude.degrees < that.maxLongitude.degrees) ? this.maxLongitude : that.maxLongitude; - if (minLon.degrees > maxLon.degrees) + if (minLon.degrees > maxLon.degrees) { return null; + } return new Sector(minLat, maxLat, minLon, maxLon); } - public final Sector intersection(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) + public final Sector intersection(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { return this; + } - if (!this.contains(latitude, longitude)) + if (!this.contains(latitude, longitude)) { return null; + } return new Sector(latitude, latitude, longitude, longitude); } @@ -1408,10 +1364,8 @@ public final Sector intersection(Angle latitude, Angle longitude) * * @throws java.lang.IllegalArgumentException if the iterable is null. */ - public static Sector intersection(Iterable sectors) - { - if (sectors == null) - { + public static Sector intersection(Iterable sectors) { + if (sectors == null) { String msg = Logging.getMessage("nullValue.SectorListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1419,22 +1373,21 @@ public static Sector intersection(Iterable sectors) Sector result = null; - for (Sector s : sectors) - { - if (s == null) + for (Sector s : sectors) { + if (s == null) { continue; // ignore null sectors - - if (result == null) + } + if (result == null) { result = s; // start with the first non-null sector - else if ((result = result.intersection(s)) == null) + } else if ((result = result.intersection(s)) == null) { break; // at least one of the sectors does not intersect the others + } } return result; } - public Sector[] subdivide() - { + public Sector[] subdivide() { Angle midLat = Angle.average(this.minLatitude, this.maxLatitude); Angle midLon = Angle.average(this.minLongitude, this.maxLongitude); @@ -1447,22 +1400,19 @@ public Sector[] subdivide() return sectors; } - public Sector[] subdivide(int div) - { + public Sector[] subdivide(int div) { double dLat = this.deltaLat.degrees / div; double dLon = this.deltaLon.degrees / div; Sector[] sectors = new Sector[div * div]; int idx = 0; - for (int row = 0; row < div; row++) - { - for (int col = 0; col < div; col++) - { + for (int row = 0; row < div; row++) { + for (int col = 0; col < div; col++) { sectors[idx++] = Sector.fromDegrees( - this.minLatitude.degrees + dLat * row, - this.minLatitude.degrees + dLat * row + dLat, - this.minLongitude.degrees + dLon * col, - this.minLongitude.degrees + dLon * col + dLon); + this.minLatitude.degrees + dLat * row, + this.minLatitude.degrees + dLat * row + dLat, + this.minLongitude.degrees + dLon * col, + this.minLongitude.degrees + dLon * col + dLon); } } @@ -1475,24 +1425,21 @@ public Sector[] subdivide(int div) * specified point and this sector's corner points or its center point. The draw context defines the globe and the * elevations that are used to compute the corner points and the center point. * - * @param dc The draw context defining the surface geometry. + * @param dc The draw context defining the surface geometry. * @param point The model coordinate point to compute a distance to. * * @return The distance between this sector's surface geometry and the specified point, in model coordinates. * * @throws IllegalArgumentException if any argument is null. */ - public double distanceTo(DrawContext dc, Vec4 point) - { - if (dc == null) - { + public double distanceTo(DrawContext dc, Vec4 point) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (point == null) - { + if (point == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1510,14 +1457,18 @@ public double distanceTo(DrawContext dc, Vec4 point) // Find the minimum distance. double minDistance = d1; - if (minDistance > d2) + if (minDistance > d2) { minDistance = d2; - if (minDistance > d3) + } + if (minDistance > d3) { minDistance = d3; - if (minDistance > d4) + } + if (minDistance > d4) { minDistance = d4; - if (minDistance > d5) + } + if (minDistance > d5) { minDistance = d5; + } return minDistance; } @@ -1528,13 +1479,11 @@ public double distanceTo(DrawContext dc, Vec4 point) * * @return four-element array containing the Sector's angles. */ - public double[] toArrayDegrees() - { - return new double[] - { - this.minLatitude.degrees, this.maxLatitude.degrees, - this.minLongitude.degrees, this.maxLongitude.degrees - }; + public double[] toArrayDegrees() { + return new double[]{ + this.minLatitude.degrees, this.maxLatitude.degrees, + this.minLongitude.degrees, this.maxLongitude.degrees + }; } /** @@ -1543,10 +1492,9 @@ public double[] toArrayDegrees() * * @return a {@link java.awt.geom.Rectangle2D} corresponding to this Sector in degrees lat-lon coordinates. */ - public Rectangle2D toRectangleDegrees() - { + public Rectangle2D toRectangleDegrees() { return new Rectangle2D.Double(this.getMinLongitude().degrees, this.getMinLatitude().degrees, - this.getDeltaLonDegrees(), this.getDeltaLatDegrees()); + this.getDeltaLonDegrees(), this.getDeltaLatDegrees()); } /** @@ -1555,8 +1503,7 @@ public Rectangle2D toRectangleDegrees() * @return A string indicating the sector's angles. */ @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(this.minLatitude.toString()); @@ -1580,8 +1527,7 @@ public String toString() * * @return the size of this object in bytes */ - public long getSizeInBytes() - { + public long getSizeInBytes() { return 4 * minLatitude.getSizeInBytes(); // 4 angles } @@ -1595,38 +1541,44 @@ public long getSizeInBytes() * * @throws IllegalArgumentException if that is null */ - public int compareTo(Sector that) - { - if (that == null) - { + public int compareTo(Sector that) { + if (that == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.getMinLatitude().compareTo(that.getMinLatitude()) < 0) + if (this.getMinLatitude().compareTo(that.getMinLatitude()) < 0) { return -1; + } - if (this.getMinLatitude().compareTo(that.getMinLatitude()) > 0) + if (this.getMinLatitude().compareTo(that.getMinLatitude()) > 0) { return 1; + } - if (this.getMinLongitude().compareTo(that.getMinLongitude()) < 0) + if (this.getMinLongitude().compareTo(that.getMinLongitude()) < 0) { return -1; + } - if (this.getMinLongitude().compareTo(that.getMinLongitude()) > 0) + if (this.getMinLongitude().compareTo(that.getMinLongitude()) > 0) { return 1; + } - if (this.getMaxLatitude().compareTo(that.getMaxLatitude()) < 0) + if (this.getMaxLatitude().compareTo(that.getMaxLatitude()) < 0) { return -1; + } - if (this.getMaxLatitude().compareTo(that.getMaxLatitude()) > 0) + if (this.getMaxLatitude().compareTo(that.getMaxLatitude()) > 0) { return 1; + } - if (this.getMaxLongitude().compareTo(that.getMaxLongitude()) < 0) + if (this.getMaxLongitude().compareTo(that.getMaxLongitude()) < 0) { return -1; + } - if (this.getMaxLongitude().compareTo(that.getMaxLongitude()) > 0) + if (this.getMaxLongitude().compareTo(that.getMaxLongitude()) > 0) { return 1; + } return 0; } @@ -1637,25 +1589,21 @@ public int compareTo(Sector that) * * @return an iterator for the sector. */ - public Iterator iterator() - { - return new Iterator() - { + public Iterator iterator() { + return new Iterator() { private int position = 0; - public boolean hasNext() - { + public boolean hasNext() { return this.position < 4; } - public LatLon next() - { - if (this.position > 3) + public LatLon next() { + if (this.position > 3) { throw new NoSuchElementException(); + } LatLon p; - switch (this.position) - { + switch (this.position) { case 0: p = new LatLon(Sector.this.getMinLatitude(), Sector.this.getMinLongitude()); break; @@ -1674,8 +1622,7 @@ public LatLon next() return p; } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } }; @@ -1686,12 +1633,10 @@ public void remove() * * @return the list of sector coordinates. */ - public List asList() - { + public List asList() { ArrayList list = new ArrayList(4); - for (LatLon ll : this) - { + for (LatLon ll : this) { list.add(ll); } @@ -1704,13 +1649,11 @@ public List asList() * * @return the array of sector coordinates. */ - public double[] asDegreesArray() - { - return new double[] - { - this.getMinLatitude().degrees, this.getMaxLatitude().degrees, - this.getMinLongitude().degrees, this.getMaxLongitude().degrees - }; + public double[] asDegreesArray() { + return new double[]{ + this.getMinLatitude().degrees, this.getMaxLatitude().degrees, + this.getMinLongitude().degrees, this.getMaxLongitude().degrees + }; } /** @@ -1719,13 +1662,11 @@ public double[] asDegreesArray() * * @return the array of sector coordinates. */ - public double[] asRadiansArray() - { - return new double[] - { - this.getMinLatitude().radians, this.getMaxLatitude().radians, - this.getMinLongitude().radians, this.getMaxLongitude().radians - }; + public double[] asRadiansArray() { + return new double[]{ + this.getMinLatitude().radians, this.getMaxLatitude().radians, + this.getMinLongitude().radians, this.getMaxLongitude().radians + }; } /** @@ -1733,8 +1674,7 @@ public double[] asRadiansArray() * * @return an array of the four corner locations, in the order SW, SE, NE, NW */ - public LatLon[] getCorners() - { + public LatLon[] getCorners() { LatLon[] corners = new LatLon[4]; corners[0] = new LatLon(this.minLatitude, this.minLongitude); @@ -1751,27 +1691,32 @@ public LatLon[] getCorners() * @param o the sector to compareTo with this. * * @return true if the four corresponding angles of each sector are equal, false - * otherwise. + * otherwise. */ @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final gov.nasa.worldwind.geom.Sector sector = (gov.nasa.worldwind.geom.Sector) o; - if (!maxLatitude.equals(sector.maxLatitude)) + if (!maxLatitude.equals(sector.maxLatitude)) { return false; - if (!maxLongitude.equals(sector.maxLongitude)) + } + if (!maxLongitude.equals(sector.maxLongitude)) { return false; - if (!minLatitude.equals(sector.minLatitude)) + } + if (!minLatitude.equals(sector.minLatitude)) { return false; + } //noinspection RedundantIfStatement - if (!minLongitude.equals(sector.minLongitude)) + if (!minLongitude.equals(sector.minLongitude)) { return false; + } return true; } @@ -1782,8 +1727,7 @@ public boolean equals(Object o) * @return a hash code incorporating the sector's four angles. */ @Override - public int hashCode() - { + public int hashCode() { int result; result = minLatitude.hashCode(); result = 29 * result + maxLatitude.hashCode(); @@ -1791,4 +1735,4 @@ public int hashCode() result = 29 * result + maxLongitude.hashCode(); return result; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/geom/Sphere.java b/src/gov/nasa/worldwind/geom/Sphere.java index db20ec66d9..1c4fb06a34 100644 --- a/src/gov/nasa/worldwind/geom/Sphere.java +++ b/src/gov/nasa/worldwind/geom/Sphere.java @@ -13,13 +13,15 @@ import com.jogamp.opengl.glu.*; /** - * Represents a sphere in three dimensional space.

        Instances of Sphere are immutable.

        + * Represents a sphere in three dimensional space. + *

        + * Instances of Sphere are immutable.

        * * @author Tom Gaskins * @version $Id: Sphere.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public final class Sphere implements Extent, Renderable -{ +public final class Sphere implements Extent, Renderable { + public final static Sphere UNIT_SPHERE = new Sphere(Vec4.ZERO, 1); protected final Vec4 center; @@ -34,17 +36,14 @@ public final class Sphere implements Extent, Renderable * * @throws IllegalArgumentException if points is null or empty */ - public static Sphere createBoundingSphere(Vec4 points[]) - { - if (points == null) - { + public static Sphere createBoundingSphere(Vec4 points[]) { + if (points == null) { String message = Logging.getMessage("nullValue.PointsArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (points.length < 1) - { + if (points.length < 1) { String message = Logging.getMessage("Geom.Sphere.NoPointsSpecified"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -53,9 +52,9 @@ public static Sphere createBoundingSphere(Vec4 points[]) // Creates the sphere around the axis aligned bounding box of the input points. Vec4[] extrema = Vec4.computeExtrema(points); Vec4 center = new Vec4( - (extrema[0].x + extrema[1].x) / 2.0, - (extrema[0].y + extrema[1].y) / 2.0, - (extrema[0].z + extrema[1].z) / 2.0); + (extrema[0].x + extrema[1].x) / 2.0, + (extrema[0].y + extrema[1].y) / 2.0, + (extrema[0].z + extrema[1].z) / 2.0); double radius = extrema[0].distanceTo3(extrema[1]) / 2.0; return new Sphere(center, radius); @@ -70,17 +69,14 @@ public static Sphere createBoundingSphere(Vec4 points[]) * * @throws IllegalArgumentException if buffer is null or contains fewer than three values. */ - public static Sphere createBoundingSphere(BufferWrapper buffer) - { - if (buffer == null) - { + public static Sphere createBoundingSphere(BufferWrapper buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer.getBackingBuffer().position() > buffer.getBackingBuffer().limit() - 3) - { + if (buffer.getBackingBuffer().position() > buffer.getBackingBuffer().limit() - 3) { String message = Logging.getMessage("Geom.Sphere.NoPointsSpecified"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -89,9 +85,9 @@ public static Sphere createBoundingSphere(BufferWrapper buffer) // Creates the sphere around the axis aligned bounding box of the input points. Vec4[] extrema = Vec4.computeExtrema(buffer); Vec4 center = new Vec4( - (extrema[0].x + extrema[1].x) / 2.0, - (extrema[0].y + extrema[1].y) / 2.0, - (extrema[0].z + extrema[1].z) / 2.0); + (extrema[0].x + extrema[1].x) / 2.0, + (extrema[0].y + extrema[1].y) / 2.0, + (extrema[0].z + extrema[1].z) / 2.0); double radius = extrema[0].distanceTo3(extrema[1]) / 2.0; return new Sphere(center, radius); @@ -110,10 +106,8 @@ public static Sphere createBoundingSphere(BufferWrapper buffer) * * @throws IllegalArgumentException if the Iterable is null. */ - public static Sphere createBoundingSphere(Iterable extents) - { - if (extents == null) - { + public static Sphere createBoundingSphere(Iterable extents) { + if (extents == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -124,10 +118,10 @@ public static Sphere createBoundingSphere(Iterable extents) int count = 0; // Compute the mean center point of the specified extents. - for (Extent e : extents) - { - if (e == null) + for (Extent e : extents) { + if (e == null) { continue; + } center = (center != null) ? e.getCenter().add3(center) : e.getCenter(); count++; @@ -135,21 +129,23 @@ public static Sphere createBoundingSphere(Iterable extents) // If the accumulated center point is null, then the specified Iterable is empty or contains only null elements. // We cannot compute an enclosing extent, so just return null. - if (center == null) + if (center == null) { return null; + } center = center.divide3(count); // Compute the maximum distance from the mean center point to the outermost point on each extent. This is // the radius of the enclosing extent. - for (Extent e : extents) - { - if (e == null) + for (Extent e : extents) { + if (e == null) { continue; + } double distance = e.getCenter().distanceTo3(center) + e.getRadius(); - if (radius < distance) + if (radius < distance) { radius = distance; + } } return new Sphere(center, radius); @@ -164,17 +160,14 @@ public static Sphere createBoundingSphere(Iterable extents) * * @throws IllegalArgumentException if center is null or if radius is non-positive */ - public Sphere(Vec4 center, double radius) - { - if (center == null) - { + public Sphere(Vec4 center, double radius) { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius <= 0) - { + if (radius <= 0) { String message = Logging.getMessage("Geom.Sphere.RadiusIsZeroOrNegative", radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -191,8 +184,7 @@ public Sphere(Vec4 center, double radius) * * @return the radius of this sphere */ - public final double getRadius() - { + public final double getRadius() { return this.radius; } @@ -201,8 +193,7 @@ public final double getRadius() * * @return the diameter of this Sphere */ - public final double getDiameter() - { + public final double getDiameter() { return 2 * this.radius; } @@ -211,14 +202,14 @@ public final double getDiameter() * * @return the Vec4 situated at the center of this Sphere */ - public final Vec4 getCenter() - { + public final Vec4 getCenter() { return this.center; } - /** {@inheritDoc} */ - public double getEffectiveRadius(Plane plane) - { + /** + * {@inheritDoc} + */ + public double getEffectiveRadius(Plane plane) { return this.getRadius(); } @@ -231,10 +222,8 @@ public double getEffectiveRadius(Plane plane) * * @throws IllegalArgumentException if the location is null. */ - public Vec4 getPointOnSphere(LatLon location) - { - if (location == null) - { + public Vec4 getPointOnSphere(LatLon location) { + if (location == null) { String msg = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -260,10 +249,8 @@ public Vec4 getPointOnSphere(LatLon location) * * @throws IllegalArgumentException if line is null */ - public final Intersection[] intersect(Line line) - { - if (line == null) - { + public final Intersection[] intersect(Line line) { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -274,20 +261,19 @@ public final Intersection[] intersect(Line line) double c = line.getOrigin().getLengthSquared3() - this.radius * this.radius; double discriminant = Sphere.discriminant(a, b, c); - if (discriminant < 0) + if (discriminant < 0) { return null; + } double discriminantRoot = Math.sqrt(discriminant); - if (discriminant == 0) - { + if (discriminant == 0) { Vec4 p = line.getPointAt((-b - discriminantRoot) / (2 * a)); - return new Intersection[] {new Intersection(p, true)}; - } - else // (discriminant > 0) + return new Intersection[]{new Intersection(p, true)}; + } else // (discriminant > 0) { Vec4 near = line.getPointAt((-b - discriminantRoot) / (2 * a)); Vec4 far = line.getPointAt((-b + discriminantRoot) / (2 * a)); - return new Intersection[] {new Intersection(near, false), new Intersection(far, false)}; + return new Intersection[]{new Intersection(near, false), new Intersection(far, false)}; } } @@ -302,8 +288,7 @@ public final Intersection[] intersect(Line line) * * @return the discriminant "b squared minus 4ac" */ - private static double discriminant(double a, double b, double c) - { + private static double discriminant(double a, double b, double c) { return b * b - 4 * a * c; } @@ -316,10 +301,8 @@ private static double discriminant(double a, double b, double c) * * @throws IllegalArgumentException if the frustum is null. */ - public final boolean intersects(Frustum frustum) - { - if (frustum == null) - { + public final boolean intersects(Frustum frustum) { + if (frustum == null) { String message = Logging.getMessage("nullValue.FrustumIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -329,23 +312,28 @@ public final boolean intersects(Frustum frustum) // center point with each plane's vector provides a distance to each plane. If this distance is less than // -radius, the extent is completely clipped by that plane and therefore does not intersect the space enclosed // by this Frustum. - Vec4 c = this.getCenter(); double nr = -this.getRadius(); - if (frustum.getFar().dot(c) <= nr) + if (frustum.getFar().dot(c) <= nr) { return false; - if (frustum.getLeft().dot(c) <= nr) + } + if (frustum.getLeft().dot(c) <= nr) { return false; - if (frustum.getRight().dot(c) <= nr) + } + if (frustum.getRight().dot(c) <= nr) { return false; - if (frustum.getTop().dot(c) <= nr) + } + if (frustum.getTop().dot(c) <= nr) { return false; - if (frustum.getBottom().dot(c) <= nr) + } + if (frustum.getBottom().dot(c) <= nr) { return false; + } //noinspection RedundantIfStatement - if (frustum.getNear().dot(c) <= nr) + if (frustum.getNear().dot(c) <= nr) { return false; + } return true; } @@ -359,10 +347,8 @@ public final boolean intersects(Frustum frustum) * * @throws IllegalArgumentException if line is null */ - public boolean intersects(Line line) - { - if (line == null) - { + public boolean intersects(Line line) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -379,10 +365,8 @@ public boolean intersects(Line line) * * @throws IllegalArgumentException if plane is null */ - public boolean intersects(Plane plane) - { - if (plane == null) - { + public boolean intersects(Plane plane) { + if (plane == null) { String msg = Logging.getMessage("nullValue.PlaneIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -392,11 +376,11 @@ public boolean intersects(Plane plane) return dq1 <= this.radius; } - /** {@inheritDoc} */ - public double getProjectedArea(View view) - { - if (view == null) - { + /** + * {@inheritDoc} + */ + public double getProjectedArea(View view) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -413,10 +397,8 @@ public double getProjectedArea(View view) * * @throws IllegalArgumentException if dc is null */ - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -439,33 +421,34 @@ public void render(DrawContext dc) } @Override - public String toString() - { + public String toString() { return "Sphere: center = " + this.center.toString() + " radius = " + Double.toString(this.radius); } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final gov.nasa.worldwind.geom.Sphere sphere = (gov.nasa.worldwind.geom.Sphere) o; - if (Double.compare(sphere.radius, radius) != 0) + if (Double.compare(sphere.radius, radius) != 0) { return false; + } //noinspection RedundantIfStatement - if (!center.equals(sphere.center)) + if (!center.equals(sphere.center)) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; long temp; result = center.hashCode(); diff --git a/src/gov/nasa/worldwind/geom/Triangle.java b/src/gov/nasa/worldwind/geom/Triangle.java index 9012bbcd7d..89e798f219 100644 --- a/src/gov/nasa/worldwind/geom/Triangle.java +++ b/src/gov/nasa/worldwind/geom/Triangle.java @@ -17,8 +17,8 @@ * @author Eric Dalgliesh 30/11/2006 * @version $Id: Triangle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Triangle -{ +public class Triangle { + private static final double EPSILON = 0.0000001; // used in intersects method private final Vec4 a; @@ -35,10 +35,8 @@ public class Triangle * * @throws IllegalArgumentException if any vertex is null. */ - public Triangle(Vec4 a, Vec4 b, Vec4 c) - { - if (a == null || b == null || c == null) - { + public Triangle(Vec4 a, Vec4 b, Vec4 c) { + if (a == null || b == null || c == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -54,8 +52,7 @@ public Triangle(Vec4 a, Vec4 b, Vec4 c) * * @return the first vertex. */ - public Vec4 getA() - { + public Vec4 getA() { return this.a; } @@ -64,8 +61,7 @@ public Vec4 getA() * * @return the second vertex. */ - public Vec4 getB() - { + public Vec4 getB() { return this.b; } @@ -74,8 +70,7 @@ public Vec4 getB() * * @return the third vertex. */ - public Vec4 getC() - { + public Vec4 getC() { return this.c; } @@ -89,7 +84,6 @@ public Vec4 getC() // // return new gov.nasa.worldwind.geom.Plane(n); // } - // private Point temporaryIntersectPlaneAndLine(Line line, Plane plane) // { // Vector n = line.getDirection(); @@ -108,7 +102,6 @@ public Vec4 getC() // d = 1/d; // return new Triangle(this.a.multiply(d), this.b.multiply(d), this.c.multiply(d)); // } - /** * Indicates whether a specified point is on the triangle. * @@ -116,10 +109,10 @@ public Vec4 getC() * * @return true if the point is on the triangle, otherwise false. */ - public boolean contains(Vec4 p) - { - if (p == null) + public boolean contains(Vec4 p) { + if (p == null) { return false; + } // Compute vectors Vec4 v0 = this.c.subtract3(this.a); @@ -156,8 +149,7 @@ public boolean contains(Vec4 p) * * @throws IllegalArgumentException if the line is null. */ - public Vec4 intersect(Line line) - { + public Vec4 intersect(Line line) { Intersection intersection = intersect(line, this.a, this.b, this.c); return intersection != null ? intersection.getIntersectionPoint() : null; @@ -168,16 +160,15 @@ public Vec4 intersect(Line line) * points ordered counterclockwise. The triangle's front face is determined by the right-hand rule. * * @param line the line to test. - * @param a the first vertex of the triangle. - * @param b the second vertex of the triangle. - * @param c the third vertex of the triangle. + * @param a the first vertex of the triangle. + * @param b the second vertex of the triangle. + * @param c the third vertex of the triangle. * * @return the point of intersection if the line intersects the triangle, otherwise null. * * @throws IllegalArgumentException if the line or any of the triangle vertices is null. */ - public static Intersection intersect(Line line, Vec4 a, Vec4 b, Vec4 c) - { + public static Intersection intersect(Line line, Vec4 a, Vec4 b, Vec4 c) { return intersect(line, a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z); } @@ -185,23 +176,21 @@ public static Intersection intersect(Line line, Vec4 a, Vec4 b, Vec4 c) * Determines the intersection of a specified line with a triangle specified by individual coordinates. * * @param line the line to test. - * @param vax the X coordinate of the first vertex of the triangle. - * @param vay the Y coordinate of the first vertex of the triangle. - * @param vaz the Z coordinate of the first vertex of the triangle. - * @param vbx the X coordinate of the second vertex of the triangle. - * @param vby the Y coordinate of the second vertex of the triangle. - * @param vbz the Z coordinate of the second vertex of the triangle. - * @param vcx the X coordinate of the third vertex of the triangle. - * @param vcy the Y coordinate of the third vertex of the triangle. - * @param vcz the Z coordinate of the third vertex of the triangle. + * @param vax the X coordinate of the first vertex of the triangle. + * @param vay the Y coordinate of the first vertex of the triangle. + * @param vaz the Z coordinate of the first vertex of the triangle. + * @param vbx the X coordinate of the second vertex of the triangle. + * @param vby the Y coordinate of the second vertex of the triangle. + * @param vbz the Z coordinate of the second vertex of the triangle. + * @param vcx the X coordinate of the third vertex of the triangle. + * @param vcy the Y coordinate of the third vertex of the triangle. + * @param vcz the Z coordinate of the third vertex of the triangle. * * @return the point of intersection if the line intersects the triangle, otherwise null. */ public static Intersection intersect(Line line, - double vax, double vay, double vaz, double vbx, double vby, double vbz, double vcx, double vcy, double vcz) - { - if (line == null) - { + double vax, double vay, double vaz, double vbx, double vby, double vbz, double vcx, double vcy, double vcz) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -210,7 +199,6 @@ public static Intersection intersect(Line line, // taken from Moller and Trumbore // http://www.cs.virginia.edu/~gfx/Courses/2003/ImageSynthesis/papers/Acceleration/ // Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf - Vec4 origin = line.getOrigin(); Vec4 dir = line.getDirection(); @@ -232,7 +220,9 @@ public static Intersection intersect(Line line, double det = edge1x * pvecx + edge1y * pvecy + edge1z * pvecz; // edge1 dot pvec if (det > -EPSILON && det < EPSILON) // If det is near zero, then ray lies on plane of triangle + { return null; + } double detInv = 1d / det; @@ -243,8 +233,9 @@ public static Intersection intersect(Line line, // Calculate u parameter and test bounds: 1/det * tvec dot pvec double u = detInv * (tvecx * pvecx + tvecy * pvecy + tvecz * pvecz); - if (u < 0 || u > 1) + if (u < 0 || u > 1) { return null; + } // Prepare to test v parameter: tvec cross edge1 double qvecx = (tvecy * edge1z) - (tvecz * edge1y); @@ -253,13 +244,15 @@ public static Intersection intersect(Line line, // Calculate v parameter and test bounds: 1/det * dir dot qvec double v = detInv * (dir.x * qvecx + dir.y * qvecy + dir.z * qvecz); - if (v < 0 || u + v > 1) + if (v < 0 || u + v > 1) { return null; + } // Calculate the point of intersection on the line: t = 1/det * edge2 dot qvec; double t = detInv * (edge2x * qvecx + edge2y * qvecy + edge2z * qvecz); - if (t < 0) + if (t < 0) { return null; + } return new Intersection(line.getPointAt(t), t, false); } @@ -267,25 +260,22 @@ public static Intersection intersect(Line line, /** * Compute the intersections of a line with a triangle strip. * - * @param line the line to intersect. + * @param line the line to intersect. * @param vertices the tri-strip vertices. - * @param indices the indices forming the tri-strip. + * @param indices the indices forming the tri-strip. * * @return the list of intersections with the line and the tri-strip, or null if there are no intersections. * * @throws IllegalArgumentException if the line, vertex buffer or index buffer is null. */ - public static List intersectTriStrip(final Line line, FloatBuffer vertices, IntBuffer indices) - { - if (line == null) - { + public static List intersectTriStrip(final Line line, FloatBuffer vertices, IntBuffer indices) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (vertices == null || indices == null) - { + if (vertices == null || indices == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -293,8 +283,7 @@ public static List intersectTriStrip(final Line line, FloatBuffer List intersections = null; - for (int n = indices.position(); n < indices.limit() - 2; n++) - { + for (int n = indices.position(); n < indices.limit() - 2; n++) { Intersection intersection; int i = indices.get(n) * 3; @@ -304,14 +293,14 @@ public static List intersectTriStrip(final Line line, FloatBuffer // The triangle intersect method detects front and back face intersections so there's no reason to // order the vertices. intersection = intersect(line, - vertices.get(i), vertices.get(i + 1), vertices.get(i + 2), - vertices.get(j), vertices.get(j + 1), vertices.get(j + 2), - vertices.get(k), vertices.get(k + 1), vertices.get(k + 2)); + vertices.get(i), vertices.get(i + 1), vertices.get(i + 2), + vertices.get(j), vertices.get(j + 1), vertices.get(j + 2), + vertices.get(k), vertices.get(k + 1), vertices.get(k + 2)); - if (intersection != null) - { - if (intersections == null) + if (intersection != null) { + if (intersections == null) { intersections = new ArrayList(); + } intersections.add(intersection); } } @@ -322,32 +311,28 @@ public static List intersectTriStrip(final Line line, FloatBuffer /** * Compute the intersections of a line with a triangle strip. * - * @param line the line to intersect. + * @param line the line to intersect. * @param vertices the tri-strip vertices. - * @param indices the indices forming the tri-strip. + * @param indices the indices forming the tri-strip. * * @return the list of intersections with the line and the triangle strip, or null if there are no intersections. * * @throws IllegalArgumentException if the line, vertex array or index buffer is null. */ - public static List intersectTriStrip(final Line line, Vec4[] vertices, IntBuffer indices) - { - if (line == null) - { + public static List intersectTriStrip(final Line line, Vec4[] vertices, IntBuffer indices) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (vertices == null) - { + if (vertices == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (indices == null) - { + if (indices == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -355,8 +340,7 @@ public static List intersectTriStrip(final Line line, Vec4[] verti List intersections = null; - for (int n = indices.position(); n < indices.limit() - 1; n++) - { + for (int n = indices.position(); n < indices.limit() - 1; n++) { Intersection intersection; int i = indices.get(n) * 3; @@ -367,10 +351,10 @@ public static List intersectTriStrip(final Line line, Vec4[] verti // order the vertices. intersection = intersect(line, vertices[i], vertices[j], vertices[k]); - if (intersection != null) - { - if (intersections == null) + if (intersection != null) { + if (intersections == null) { intersections = new ArrayList(); + } intersections.add(intersection); } } @@ -381,25 +365,22 @@ public static List intersectTriStrip(final Line line, Vec4[] verti /** * Compute the intersections of a line with a triangle fan. * - * @param line the line to intersect. + * @param line the line to intersect. * @param vertices the tri-fan vertices. - * @param indices the indices forming the tri-fan. + * @param indices the indices forming the tri-fan. * * @return the list of intersections with the line and the triangle fan, or null if there are no intersections. * * @throws IllegalArgumentException if the line, vertex buffer or index buffer is null. */ - public static List intersectTriFan(final Line line, FloatBuffer vertices, IntBuffer indices) - { - if (line == null) - { + public static List intersectTriFan(final Line line, FloatBuffer vertices, IntBuffer indices) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (vertices == null || indices == null) - { + if (vertices == null || indices == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -415,8 +396,7 @@ public static List intersectTriFan(final Line line, FloatBuffer ve float v0z = vertices.get(k * 3 + 2); // Starting with the second position in the index buffer, get subsequent indices and vertices. - for (int n = indices.position(); n < indices.limit() - 1; n++) - { + for (int n = indices.position(); n < indices.limit() - 1; n++) { Intersection intersection; int i = indices.get(n) * 3; @@ -425,14 +405,14 @@ public static List intersectTriFan(final Line line, FloatBuffer ve // The triangle intersect method detects front and back face intersections so there's no reason to // order the vertices. intersection = intersect(line, - v0x, v0y, v0z, - vertices.get(i), vertices.get(i + 1), vertices.get(i + 2), - vertices.get(j), vertices.get(j + 1), vertices.get(j + 2)); + v0x, v0y, v0z, + vertices.get(i), vertices.get(i + 1), vertices.get(i + 2), + vertices.get(j), vertices.get(j + 1), vertices.get(j + 2)); - if (intersection != null) - { - if (intersections == null) + if (intersection != null) { + if (intersections == null) { intersections = new ArrayList(); + } intersections.add(intersection); } } @@ -443,32 +423,28 @@ public static List intersectTriFan(final Line line, FloatBuffer ve /** * Compute the intersections of a line with a triangle fan. * - * @param line the line to intersect. + * @param line the line to intersect. * @param vertices the tri-fan vertices. - * @param indices the indices forming the tri-fan. + * @param indices the indices forming the tri-fan. * * @return the list of intersections with the line and the triangle fan, or null if there are no intersections. * * @throws IllegalArgumentException if the line, vertex array or index buffer is null. */ - public static List intersectTriFan(final Line line, Vec4[] vertices, IntBuffer indices) - { - if (line == null) - { + public static List intersectTriFan(final Line line, Vec4[] vertices, IntBuffer indices) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (vertices == null) - { + if (vertices == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (indices == null) - { + if (indices == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -478,8 +454,7 @@ public static List intersectTriFan(final Line line, Vec4[] vertice Vec4 v0 = vertices[0]; - for (int n = indices.position() + 1; n < indices.limit() - 1; n++) - { + for (int n = indices.position() + 1; n < indices.limit() - 1; n++) { Intersection intersection; Vec4 v1 = vertices[indices.get(n)]; @@ -488,10 +463,10 @@ public static List intersectTriFan(final Line line, Vec4[] vertice // The triangle intersect method detects front and back face intersections so there's no reason to // order the vertices. intersection = intersect(line, v0, v1, v2); - if (intersection != null) - { - if (intersections == null) + if (intersection != null) { + if (intersections == null) { intersections = new ArrayList(); + } intersections.add(intersection); } } @@ -502,24 +477,21 @@ public static List intersectTriFan(final Line line, Vec4[] vertice /** * Compute the intersections of a line with a collection of triangles. * - * @param line the line to intersect. + * @param line the line to intersect. * @param vertices the triangles, arranged in a buffer as GL_TRIANGLES (9 floats per triangle). * * @return the list of intersections with the line and the triangles, or null if there are no intersections. * * @throws IllegalArgumentException if the line or vertex buffer is null. */ - public static List intersectTriangles(final Line line, FloatBuffer vertices) - { - if (line == null) - { + public static List intersectTriangles(final Line line, FloatBuffer vertices) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (vertices == null) - { + if (vertices == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -529,17 +501,16 @@ public static List intersectTriangles(final Line line, FloatBuffer vertices.rewind(); - while (vertices.limit() - vertices.position() >= 9) - { + while (vertices.limit() - vertices.position() >= 9) { Intersection intersection = intersect(line, - vertices.get(), vertices.get(), vertices.get(), - vertices.get(), vertices.get(), vertices.get(), - vertices.get(), vertices.get(), vertices.get()); + vertices.get(), vertices.get(), vertices.get(), + vertices.get(), vertices.get(), vertices.get(), + vertices.get(), vertices.get(), vertices.get()); - if (intersection != null) - { - if (intersections == null) + if (intersection != null) { + if (intersections == null) { intersections = new ArrayList(); + } intersections.add(intersection); } } @@ -550,25 +521,22 @@ public static List intersectTriangles(final Line line, FloatBuffer /** * Compute the intersections of a line with a collection of triangles. * - * @param line the line to intersect. + * @param line the line to intersect. * @param vertices the triangles, arranged in a buffer as GL_TRIANGLES (9 floats per triangle). - * @param indices the indices forming the triangles. + * @param indices the indices forming the triangles. * * @return the list of intersections with the line and the triangle fan, or null if there are no intersections. * * @throws IllegalArgumentException if the line, vertex buffer or index buffer is null. */ - public static List intersectTriangles(final Line line, FloatBuffer vertices, IntBuffer indices) - { - if (line == null) - { + public static List intersectTriangles(final Line line, FloatBuffer vertices, IntBuffer indices) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (vertices == null || indices == null) - { + if (vertices == null || indices == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -576,8 +544,7 @@ public static List intersectTriangles(final Line line, FloatBuffer List intersections = null; - for (int n = indices.position(); n < indices.limit(); n += 3) - { + for (int n = indices.position(); n < indices.limit(); n += 3) { Intersection intersection; int i = indices.get(n) * 3; @@ -585,14 +552,14 @@ public static List intersectTriangles(final Line line, FloatBuffer int k = indices.get(n + 2) * 3; intersection = intersect(line, - vertices.get(i), vertices.get(i + 1), vertices.get(i + 2), - vertices.get(j), vertices.get(j + 1), vertices.get(j + 2), - vertices.get(k), vertices.get(k + 1), vertices.get(k + 2)); + vertices.get(i), vertices.get(i + 1), vertices.get(i + 2), + vertices.get(j), vertices.get(j + 1), vertices.get(j + 2), + vertices.get(k), vertices.get(k + 1), vertices.get(k + 2)); - if (intersection != null) - { - if (intersections == null) + if (intersection != null) { + if (intersections == null) { intersections = new ArrayList(); + } intersections.add(intersection); } } @@ -603,22 +570,22 @@ public static List intersectTriangles(final Line line, FloatBuffer /** * Compute the intersections of a line with a triangle collection. * - * @param line the line to intersect. - * @param vertices the tri-fan vertices, in the order x, y, z, x, y, z, ... - * @param indices the indices forming the tri-fan. + * @param line the line to intersect. + * @param vertices the tri-fan vertices, in the order x, y, z, x, y, z, ... + * @param indices the indices forming the tri-fan. * @param triangleType the type of triangle collection, either GL.GL_TRIANGLE_STRIP or GL.GL_TRIANGLE_FAN. * * @return the list of intersections with the line and the triangle fan, or null if there are no intersections. */ public static List intersectTriangleTypes(final Line line, FloatBuffer vertices, IntBuffer indices, - int triangleType) - { - if (triangleType == GL.GL_TRIANGLES) + int triangleType) { + if (triangleType == GL.GL_TRIANGLES) { return Triangle.intersectTriangles(line, vertices, indices); - else if (triangleType == GL.GL_TRIANGLE_STRIP) + } else if (triangleType == GL.GL_TRIANGLE_STRIP) { return Triangle.intersectTriStrip(line, vertices, indices); - else if (triangleType == GL.GL_TRIANGLE_FAN) + } else if (triangleType == GL.GL_TRIANGLE_FAN) { return Triangle.intersectTriFan(line, vertices, indices); + } return null; } @@ -627,39 +594,34 @@ else if (triangleType == GL.GL_TRIANGLE_FAN) * Expands a buffer of indexed triangle vertices to a buffer of non-indexed triangle vertices. * * @param indices the triangle indices. - * @param inBuf the vertex buffer the indices refer to, in the order x, y, z, x, y, z, ... - * @param outBuf the buffer in which to place the expanded triangle vertices. The buffer must have a limit - * sufficient to hold the output vertices. + * @param inBuf the vertex buffer the indices refer to, in the order x, y, z, x, y, z, ... + * @param outBuf the buffer in which to place the expanded triangle vertices. The buffer must have a limit + * sufficient to hold the output vertices. * * @throws IllegalArgumentException if the index list or the input or output buffer is null, or if the output buffer - * size is insufficient. + * size is insufficient. */ - public static void expandTriangles(List indices, FloatBuffer inBuf, FloatBuffer outBuf) - { - if (indices == null) - { + public static void expandTriangles(List indices, FloatBuffer inBuf, FloatBuffer outBuf) { + if (indices == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (inBuf == null || outBuf == null) - { + if (inBuf == null || outBuf == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } int nunTriangles = indices.size() / 3; - if (nunTriangles * 3 * 3 > outBuf.limit() - outBuf.position()) - { + if (nunTriangles * 3 * 3 > outBuf.limit() - outBuf.position()) { String msg = Logging.getMessage("generic.BufferSize", outBuf.limit() - outBuf.position()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (int i = 0; i < indices.size(); i += 3) - { + for (int i = 0; i < indices.size(); i += 3) { int k = indices.get(i) * 3; outBuf.put(inBuf.get(k)).put(inBuf.get(k + 1)).put(inBuf.get(k + 2)); @@ -675,32 +637,28 @@ public static void expandTriangles(List indices, FloatBuffer inBuf, Flo * Expands a buffer of indexed triangle fan vertices to a buffer of non-indexed general-triangle vertices. * * @param indices the triangle indices. - * @param inBuf the vertex buffer the indices refer to, in the order x, y, z, x, y, z, ... - * @param outBuf the buffer in which to place the expanded triangle vertices. The buffer must have a limit - * sufficient to hold the output vertices. + * @param inBuf the vertex buffer the indices refer to, in the order x, y, z, x, y, z, ... + * @param outBuf the buffer in which to place the expanded triangle vertices. The buffer must have a limit + * sufficient to hold the output vertices. * * @throws IllegalArgumentException if the index list or the input or output buffer is null, or if the output buffer - * size is insufficient. + * size is insufficient. */ - public static void expandTriangleFan(List indices, FloatBuffer inBuf, FloatBuffer outBuf) - { - if (indices == null) - { + public static void expandTriangleFan(List indices, FloatBuffer inBuf, FloatBuffer outBuf) { + if (indices == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (inBuf == null || outBuf == null) - { + if (inBuf == null || outBuf == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } int nunTriangles = indices.size() - 2; - if (nunTriangles * 3 * 3 > outBuf.limit() - outBuf.position()) - { + if (nunTriangles * 3 * 3 > outBuf.limit() - outBuf.position()) { String msg = Logging.getMessage("generic.BufferSize", outBuf.limit() - outBuf.position()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -711,8 +669,7 @@ public static void expandTriangleFan(List indices, FloatBuffer inBuf, F float v0y = inBuf.get(k + 1); float v0z = inBuf.get(k + 2); - for (int i = 1; i < indices.size() - 1; i++) - { + for (int i = 1; i < indices.size() - 1; i++) { outBuf.put(v0x).put(v0y).put(v0z); k = indices.get(i) * 3; @@ -727,39 +684,34 @@ public static void expandTriangleFan(List indices, FloatBuffer inBuf, F * Expands a buffer of indexed triangle strip vertices to a buffer of non-indexed general-triangle vertices. * * @param indices the triangle indices. - * @param inBuf the vertex buffer the indices refer to, in the order x, y, z, x, y, z, ... - * @param outBuf the buffer in which to place the expanded triangle vertices. The buffer must have a limit - * sufficient to hold the output vertices. + * @param inBuf the vertex buffer the indices refer to, in the order x, y, z, x, y, z, ... + * @param outBuf the buffer in which to place the expanded triangle vertices. The buffer must have a limit + * sufficient to hold the output vertices. * * @throws IllegalArgumentException if the index list or the input or output buffer is null, or if the output buffer - * size is insufficient. + * size is insufficient. */ - public static void expandTriangleStrip(List indices, FloatBuffer inBuf, FloatBuffer outBuf) - { - if (indices == null) - { + public static void expandTriangleStrip(List indices, FloatBuffer inBuf, FloatBuffer outBuf) { + if (indices == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (inBuf == null || outBuf == null) - { + if (inBuf == null || outBuf == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } int nunTriangles = indices.size() - 2; - if (nunTriangles * 3 * 3 > outBuf.limit() - outBuf.position()) - { + if (nunTriangles * 3 * 3 > outBuf.limit() - outBuf.position()) { String msg = Logging.getMessage("generic.BufferSize", outBuf.limit() - outBuf.position()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (int i = 2; i < indices.size(); i++) - { + for (int i = 2; i < indices.size(); i++) { int k = indices.get(i - 2) * 3; outBuf.put(inBuf.get(k)).put(inBuf.get(k + 1)).put(inBuf.get(k + 2)); @@ -771,55 +723,46 @@ public static void expandTriangleStrip(List indices, FloatBuffer inBuf, } } - public static void expandTriangles(List indices, IntBuffer outBuf) - { - if (indices == null) - { + public static void expandTriangles(List indices, IntBuffer outBuf) { + if (indices == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (outBuf == null) - { + if (outBuf == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } int numTriangles = indices.size() / 3; - if (numTriangles * 3 > outBuf.limit() - outBuf.position()) - { + if (numTriangles * 3 > outBuf.limit() - outBuf.position()) { String msg = Logging.getMessage("generic.BufferSize", outBuf.limit() - outBuf.position()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (int i = 0; i < indices.size(); i++) - { + for (int i = 0; i < indices.size(); i++) { outBuf.put(indices.get(i)); } } - public static void expandTriangleFan(List indices, IntBuffer outBuf) - { - if (indices == null) - { + public static void expandTriangleFan(List indices, IntBuffer outBuf) { + if (indices == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (outBuf == null) - { + if (outBuf == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } int nunTriangles = indices.size() - 2; - if (nunTriangles * 3 > outBuf.limit() - outBuf.position()) - { + if (nunTriangles * 3 > outBuf.limit() - outBuf.position()) { String msg = Logging.getMessage("generic.BufferSize", outBuf.limit() - outBuf.position()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -827,40 +770,34 @@ public static void expandTriangleFan(List indices, IntBuffer outBuf) int k0 = indices.get(0); - for (int i = 1; i < indices.size() - 1; i++) - { + for (int i = 1; i < indices.size() - 1; i++) { outBuf.put(k0); outBuf.put(indices.get(i)); outBuf.put(indices.get(i + 1)); } } - public static void expandTriangleStrip(List indices, IntBuffer outBuf) - { - if (indices == null) - { + public static void expandTriangleStrip(List indices, IntBuffer outBuf) { + if (indices == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (outBuf == null) - { + if (outBuf == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } int nunTriangles = indices.size() - 2; - if (nunTriangles * 3 > outBuf.limit() - outBuf.position()) - { + if (nunTriangles * 3 > outBuf.limit() - outBuf.position()) { String msg = Logging.getMessage("generic.BufferSize", outBuf.limit() - outBuf.position()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (int i = 2; i < indices.size(); i++) - { + for (int i = 2; i < indices.size(); i++) { outBuf.put(indices.get(i - 2)); outBuf.put(indices.get(i % 2 == 0 ? i - 1 : i)); outBuf.put(indices.get(i % 2 == 0 ? i : i - 1)); @@ -871,8 +808,8 @@ public static void expandTriangleStrip(List indices, IntBuffer outBuf) * Defines a line segment representing the intersection of a line with and in the plane of a triangle. Used only * within {@link #intersectTriangles}. */ - protected static class TriangleIntersection - { + protected static class TriangleIntersection { + public Vec4 p0; // the first point of the line public Vec4 p1; // the second point of the line public double s0; // the distance along the line to the first intersection with the triangle @@ -882,15 +819,14 @@ protected static class TriangleIntersection /** * Intersects two triangles and returns their intersection vertices. * - * @param v the Cartesian coordinates of the first triangle. - * @param u the Cartesian coordinates of the second triangle. + * @param v the Cartesian coordinates of the first triangle. + * @param u the Cartesian coordinates of the second triangle. * @param intersectionVertices a pre-allocated two-element array in which the intersection vertices, if any, are - * returned. + * returned. * * @return -1 if there is no intersection, 1 if there is an intersection, or 0 if the triangles are co-planar. */ - public static int intersectTriangles(Vec4[] v, Vec4[] u, Vec4[] intersectionVertices) - { + public static int intersectTriangles(Vec4[] v, Vec4[] u, Vec4[] intersectionVertices) { // Taken from http://jgt.akpeters.com/papers/Moller97/tritri.html#ISECTLINE // Compute plane equation of first triangle: n1 * x + d1 = 0. @@ -909,18 +845,23 @@ public static int intersectTriangles(Vec4[] v, Vec4[] u, Vec4[] intersectionVert double du2 = n1.dot3(u[2]) + d1; // Coplanarity robustness check. - if (Math.abs(du0) < EPSILON) + if (Math.abs(du0) < EPSILON) { du0 = 0; - if (Math.abs(du1) < EPSILON) + } + if (Math.abs(du1) < EPSILON) { du1 = 0; - if (Math.abs(du2) < EPSILON) + } + if (Math.abs(du2) < EPSILON) { du2 = 0; + } double du0du1 = du0 * du1; double du0du2 = du0 * du2; if (du0du1 > 0 && du0du2 > 0) // same sign on all of them + != 0 ==> no intersection + { return -1; + } // Compute plane equation of second triangle: n2 * x + d2 = 0 e1x = u[1].x - u[0].x; @@ -938,18 +879,23 @@ public static int intersectTriangles(Vec4[] v, Vec4[] u, Vec4[] intersectionVert double dv2 = n2.dot3(v[2]) + d2; // Coplanarity robustness check. - if (Math.abs(dv0) < EPSILON) + if (Math.abs(dv0) < EPSILON) { dv0 = 0; - if (Math.abs(dv1) < EPSILON) + } + if (Math.abs(dv1) < EPSILON) { dv1 = 0; - if (Math.abs(dv2) < EPSILON) + } + if (Math.abs(dv2) < EPSILON) { dv2 = 0; + } double dv0dv1 = dv0 * dv1; double dv0dv2 = dv0 * dv2; if (dv0dv1 > 0 && dv0dv2 > 0) // same sign on all of them + != 0 ==> no intersection + { return -1; + } // Compute direction of intersection line. Vec4 ld = n1.cross3(n2); @@ -959,13 +905,11 @@ public static int intersectTriangles(Vec4[] v, Vec4[] u, Vec4[] intersectionVert int index = 0; double b = Math.abs(ld.y); double c = Math.abs(ld.z); - if (b > max) - { + if (b > max) { max = b; index = 1; } - if (c > max) - { + if (c > max) { index = 2; } @@ -977,8 +921,7 @@ public static int intersectTriangles(Vec4[] v, Vec4[] u, Vec4[] intersectionVert double up0 = u[0].x; double up1 = u[1].x; double up2 = u[2].x; - if (index == 1) - { + if (index == 1) { vp0 = v[0].y; vp1 = v[1].y; vp2 = v[2].y; @@ -986,9 +929,7 @@ public static int intersectTriangles(Vec4[] v, Vec4[] u, Vec4[] intersectionVert up0 = u[0].y; up1 = u[1].y; up2 = u[2].y; - } - else if (index == 2) - { + } else if (index == 2) { vp0 = v[0].z; vp1 = v[1].z; vp2 = v[2].z; @@ -1001,12 +942,12 @@ else if (index == 2) // Compute interval for triangle 1. TriangleIntersection isectA = compute_intervals_isectline(v, vp0, vp1, vp2, dv0, dv1, dv2, dv0dv1, dv0dv2); - if (isectA == null) + if (isectA == null) { return coplanarTriangles(n1, v, u) ? 0 : -1; + } int smallest1 = 0; - if (isectA.s0 > isectA.s1) - { + if (isectA.s0 > isectA.s1) { double cc = isectA.s0; isectA.s0 = isectA.s1; isectA.s1 = cc; @@ -1017,62 +958,58 @@ else if (index == 2) TriangleIntersection isectB = compute_intervals_isectline(u, up0, up1, up2, du0, du1, du2, du0du1, du0du2); int smallest2 = 0; - if (isectB.s0 > isectB.s1) - { + if (isectB.s0 > isectB.s1) { double cc = isectB.s0; isectB.s0 = isectB.s1; isectB.s1 = cc; smallest2 = 1; } - if (isectA.s1 < isectB.s0 || isectB.s1 < isectA.s0) + if (isectA.s1 < isectB.s0 || isectB.s1 < isectA.s0) { return -1; + } // At this point we know that the triangles intersect: there's an intersection line, the triangles are not // coplanar, and they overlap. - - if (isectB.s0 < isectA.s0) - { - if (smallest1 == 0) + if (isectB.s0 < isectA.s0) { + if (smallest1 == 0) { intersectionVertices[0] = isectA.p0; - else + } else { intersectionVertices[0] = isectA.p1; + } - if (isectB.s1 < isectA.s1) - { - if (smallest2 == 0) + if (isectB.s1 < isectA.s1) { + if (smallest2 == 0) { intersectionVertices[1] = isectB.p1; - else + } else { intersectionVertices[1] = isectB.p0; - } - else - { - if (smallest1 == 0) + } + } else { + if (smallest1 == 0) { intersectionVertices[1] = isectA.p1; - else + } else { intersectionVertices[1] = isectA.p0; + } } - } - else - { - if (smallest2 == 0) + } else { + if (smallest2 == 0) { intersectionVertices[0] = isectB.p0; - else + } else { intersectionVertices[0] = isectB.p1; + } - if (isectB.s1 > isectA.s1) - { - if (smallest1 == 0) + if (isectB.s1 > isectA.s1) { + if (smallest1 == 0) { intersectionVertices[1] = isectA.p1; - else + } else { intersectionVertices[1] = isectA.p0; - } - else - { - if (smallest2 == 0) + } + } else { + if (smallest2 == 0) { intersectionVertices[1] = isectB.p1; - else + } else { intersectionVertices[1] = isectB.p0; + } } } @@ -1080,26 +1017,26 @@ else if (index == 2) } protected static TriangleIntersection compute_intervals_isectline(Vec4[] v, double vv0, double vv1, double vv2, - double d0, double d1, double d2, - double d0d1, double d0d2) - { + double d0, double d1, double d2, + double d0d1, double d0d2) { if (d0d1 > 0) // D0, D1 are on the same side, D2 on the other or on the plane + { return intersect(v[2], v[0], v[1], vv2, vv0, vv1, d2, d0, d1); - else if (d0d2 > 0) + } else if (d0d2 > 0) { return intersect(v[1], v[0], v[2], vv1, vv0, vv2, d1, d0, d2); - else if (d1 * d2 > 0 || d0 != 0) + } else if (d1 * d2 > 0 || d0 != 0) { return intersect(v[0], v[1], v[2], vv0, vv1, vv2, d0, d1, d2); - else if (d1 != 0) + } else if (d1 != 0) { return intersect(v[1], v[0], v[2], vv1, vv0, vv2, d1, d0, d2); - else if (d2 != 0) + } else if (d2 != 0) { return intersect(v[2], v[0], v[1], vv2, vv0, vv1, d2, d0, d1); - else + } else { return null; // triangles are coplanar + } } protected static TriangleIntersection intersect(Vec4 v0, Vec4 v1, Vec4 v2, double vv0, double vv1, double vv2, - double d0, double d1, double d2) - { + double d0, double d1, double d2) { TriangleIntersection intersection = new TriangleIntersection(); double tmp = d0 / (d0 - d1); @@ -1117,91 +1054,87 @@ protected static TriangleIntersection intersect(Vec4 v0, Vec4 v1, Vec4 v2, doubl return intersection; } - protected static boolean coplanarTriangles(Vec4 n, Vec4[] v, Vec4[] u) - { + protected static boolean coplanarTriangles(Vec4 n, Vec4[] v, Vec4[] u) { // First project onto an axis-aligned plane that maximizes the are of the triangles. int i0; int i1; - double[] a = new double[] {Math.abs(n.x), Math.abs(n.y), Math.abs(n.z)}; + double[] a = new double[]{Math.abs(n.x), Math.abs(n.y), Math.abs(n.z)}; if (a[0] > a[1]) // X > Y { - if (a[0] > a[2]) - { // X is greatest + if (a[0] > a[2]) { // X is greatest i0 = 1; i1 = 2; - } - else - { // Z is greatest + } else { // Z is greatest i0 = 0; i1 = 1; } - } - else // X < Y + } else // X < Y { - if (a[2] > a[1]) - { // Z is greatest + if (a[2] > a[1]) { // Z is greatest i0 = 0; i1 = 1; - } - else - { // Y is greatest + } else { // Y is greatest i0 = 0; i1 = 2; } } // Test all edges of triangle 1 against the edges of triangle 2. - double[] v0 = new double[] {v[0].x, v[0].y, v[0].z}; - double[] v1 = new double[] {v[1].x, v[1].y, v[1].z}; - double[] v2 = new double[] {v[2].x, v[2].y, v[2].z}; + double[] v0 = new double[]{v[0].x, v[0].y, v[0].z}; + double[] v1 = new double[]{v[1].x, v[1].y, v[1].z}; + double[] v2 = new double[]{v[2].x, v[2].y, v[2].z}; - double[] u0 = new double[] {u[0].x, u[0].y, u[0].z}; - double[] u1 = new double[] {u[1].x, u[1].y, u[1].z}; - double[] u2 = new double[] {u[2].x, u[2].y, u[2].z}; + double[] u0 = new double[]{u[0].x, u[0].y, u[0].z}; + double[] u1 = new double[]{u[1].x, u[1].y, u[1].z}; + double[] u2 = new double[]{u[2].x, u[2].y, u[2].z}; boolean tf = triangleEdgeTest(v0, v1, u0, u1, u2, i0, i1); - if (tf) + if (tf) { return true; + } tf = triangleEdgeTest(v1, v2, u0, u1, u2, i0, i1); - if (tf) + if (tf) { return true; + } tf = triangleEdgeTest(v2, v0, u0, u1, u2, i0, i1); - if (tf) + if (tf) { return true; + } // Finally, test whether one triangle is contained in the other one. tf = pointInTri(v0, u0, u1, u2, i0, i1); - if (tf) + if (tf) { return true; + } return pointInTri(u0, v0, v1, v2, i0, i1); } protected static boolean triangleEdgeTest(double[] v0, double[] v1, double[] u0, double[] u1, double[] u2, int i0, - int i1) - { + int i1) { double ax = v1[i0] - v0[i0]; double ay = v1[i1] - v0[i1]; // Test edge u0:u1 against v0:v1 boolean tf = edgeEdgeTest(v0, u0, u1, i0, i1, ax, ay); - if (tf) + if (tf) { return true; + } // Test edge u1:u2 against v0:v1 tf = edgeEdgeTest(v0, u1, u2, i0, i1, ax, ay); - if (tf) + if (tf) { return true; + } // Test edge u2:u0 against v0:v1 return edgeEdgeTest(v0, u2, u0, i0, i1, ax, ay); } - protected static boolean edgeEdgeTest(double[] v0, double[] u0, double[] u1, int i0, int i1, double ax, double ay) - { + protected static boolean edgeEdgeTest(double[] v0, double[] u0, double[] u1, int i0, int i1, double ax, double ay) { double bx = u0[i0] - u1[i0]; double by = u0[i1] - u1[i1]; double cx = v0[i0] - u0[i0]; @@ -1210,26 +1143,23 @@ protected static boolean edgeEdgeTest(double[] v0, double[] u0, double[] u1, int double f = ay * bx - ax * by; double d = by * cx - bx * cy; - if ((f > 0 && d >= 0 && d <= f) || (f < 0 && d <= 0 && d >= f)) - { + if ((f > 0 && d >= 0 && d <= f) || (f < 0 && d <= 0 && d >= f)) { double e = ax * cy - ay * cx; - if (f > 0) - { - if (e >= 0 && e <= f) + if (f > 0) { + if (e >= 0 && e <= f) { return true; - } - else - { - if (e <= 0 && e >= f) + } + } else { + if (e <= 0 && e >= f) { return true; + } } } return false; } - protected static boolean pointInTri(double[] v0, double[] u0, double[] u1, double[] u2, int i0, int i1) - { + protected static boolean pointInTri(double[] v0, double[] u0, double[] u1, double[] u2, int i0, int i1) { double a = u1[i1] - u0[i1]; double b = -(u1[i0] - u0[i0]); double c = -a * u0[i0] - b * u0[i1]; @@ -1248,8 +1178,7 @@ protected static boolean pointInTri(double[] v0, double[] u0, double[] u1, doubl return d0 * d1 > 0 && d0 * d2 > 0; } - public String toString() - { + public String toString() { return "Triangle (" + a + ", " + b + ", " + c + ")"; } } diff --git a/src/gov/nasa/worldwind/geom/Vec4.java b/src/gov/nasa/worldwind/geom/Vec4.java index df8abc793b..e24162842b 100644 --- a/src/gov/nasa/worldwind/geom/Vec4.java +++ b/src/gov/nasa/worldwind/geom/Vec4.java @@ -11,10 +11,10 @@ * @author dcollins * @version $Id: Vec4.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Vec4 -{ - public static final Vec4 INFINITY = - new Vec4(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 0); +public class Vec4 { + + public static final Vec4 INFINITY + = new Vec4(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 0); public static final Vec4 ZERO = new Vec4(0, 0, 0, 1); public static final Vec4 ONE = new Vec4(1, 1, 1, 1); public static final Vec4 UNIT_X = new Vec4(1, 0, 0, 0); @@ -36,47 +36,42 @@ public class Vec4 // Cached computations. private int hashCode; - public Vec4(double value) - { + public Vec4(double value) { this(value, value, value); } - public Vec4(double x, double y) - { + public Vec4(double x, double y) { this(x, y, 0, DEFAULT_W); } - public Vec4(double x, double y, double z) - { + public Vec4(double x, double y, double z) { this(x, y, z, DEFAULT_W); } - public Vec4(double x, double y, double z, double w) - { + public Vec4(double x, double y, double z, double w) { this.x = x; this.y = y; this.z = z; this.w = w; } - public final boolean equals(Object obj) - { - if (this == obj) + public final boolean equals(Object obj) { + if (this == obj) { return true; - if (obj == null || obj.getClass() != this.getClass()) + } + if (obj == null || obj.getClass() != this.getClass()) { return false; + } Vec4 that = (Vec4) obj; return (this.x == that.x) - && (this.y == that.y) - && (this.z == that.z) - && (this.w == that.w); + && (this.y == that.y) + && (this.z == that.z) + && (this.w == that.w); } - public final int hashCode() - { - if (this.hashCode == 0) - { + public final int hashCode() { + if (this.hashCode == 0) { int result; long tmp; tmp = Double.doubleToLongBits(this.x); @@ -95,58 +90,58 @@ public final int hashCode() /** * Constructs a new Vec4 with coordinate values read from the specified double array. The specified offset must be 0 * or greater, the specified length must be 1 or greater, and the array must have capacity equal to or greater than - * offset + length. Coordinates are assigned as follows:

        x = array[offset]
        y + * offset + length. Coordinates are assigned as follows: + *

        + * x = array[offset]
        y * = array[offset + 1] if length > 1, otherwise y=0
        z = array[offset + * 2] if length > 2, otherwise z=0
        w = array[offset + 3] if * length > 3, otherwise w=1

        * - * @param array the double array from which to read coordinate data. + * @param array the double array from which to read coordinate data. * @param offset the array starting index. * @param length the number of coordinates to read. * * @return a new Vec4 with coordinate values read from the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, if length is less than 1, or if the - * array's capacity is less than offset + length. + * array's capacity is less than offset + length. */ - public static Vec4 fromDoubleArray(double[] array, int offset, int length) - { - if (array == null) - { + public static Vec4 fromDoubleArray(double[] array, int offset, int length) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (offset < 0) - { + if (offset < 0) { String msg = Logging.getMessage("generic.OffsetIsInvalid", offset); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (length < 1) - { + if (length < 1) { String msg = Logging.getMessage("generic.LengthIsInvalid", length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (array.length < offset + length) - { + if (array.length < offset + length) { String msg = Logging.getMessage("generic.ArrayInvalidLength", array.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (length == 1) + if (length == 1) { return new Vec4(array[offset], 0d); + } - if (length == 2) + if (length == 2) { return new Vec4(array[offset], array[offset + 1]); + } - if (length == 3) + if (length == 3) { return new Vec4(array[offset], array[offset + 1], array[offset + 2]); + } return new Vec4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); } @@ -154,55 +149,54 @@ public static Vec4 fromDoubleArray(double[] array, int offset, int length) /** * Constructs a new Vec4 with coordinate values read from the specified float array. The specified offset must be 0 * or greater, the specified length must be 1 or greater, and the array must have capacity equal to or greater than - * offset + length. Coordinates are assigned as follows:

        x = array[offset]
        y + * offset + length. Coordinates are assigned as follows: + *

        + * x = array[offset]
        y * = array[offset + 1] if length > 1, otherwise y=0
        z = array[offset + * 2] if length > 2, otherwise z=0
        w = array[offset + 3] if * length > 3, otherwise w=1

        * - * @param array the float array from which to read coordinate data. + * @param array the float array from which to read coordinate data. * @param offset the array starting index. * @param length the number of coordinates to read. * * @return a new Vec4 with coordinate values read from the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, if length is less than 1, or if the - * array's capacity is less than offset + length. + * array's capacity is less than offset + length. */ - public static Vec4 fromFloatArray(float[] array, int offset, int length) - { - if (array == null) - { + public static Vec4 fromFloatArray(float[] array, int offset, int length) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (offset < 0) - { + if (offset < 0) { String msg = Logging.getMessage("generic.OffsetIsInvalid", offset); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (length < 1) - { + if (length < 1) { String msg = Logging.getMessage("generic.LengthIsInvalid", length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (array.length < offset + length) - { + if (array.length < offset + length) { String msg = Logging.getMessage("generic.ArrayInvalidLength", array.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (length == 2) + if (length == 2) { return new Vec4(array[offset], array[offset + 1], 0d); + } - if (length == 3) + if (length == 3) { return new Vec4(array[offset], array[offset + 1], array[offset + 2]); + } return new Vec4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); } @@ -210,21 +204,21 @@ public static Vec4 fromFloatArray(float[] array, int offset, int length) /** * Constructs a new Vec4 with x and y values from the specified double array. The * specified offset must be 0 or greater, and the array must have capacity equal to or greater than offset + - * 2. Coordinates are assigned as follows:

        x = array[offset]
        y = array[offset + + * 2. Coordinates are assigned as follows: + *

        + * x = array[offset]
        y = array[offset + * 1]

        * - * @param array the double array from which to read coordinate data. + * @param array the double array from which to read coordinate data. * @param offset the array starting index. * * @return a new Vec4 with x and y coordinate values from the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, or if the array's capacity is less - * than offset + 2. + * than offset + 2. */ - public static Vec4 fromArray2(double[] array, int offset) - { - if (array == null) - { + public static Vec4 fromArray2(double[] array, int offset) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -236,22 +230,22 @@ public static Vec4 fromArray2(double[] array, int offset) /** * Constructs a new Vec4 with x, y and z values from the specified double * array. The specified offset must be 0 or greater, and the array must have capacity equal to or greater than - * offset + 3. Coordinates are assigned as follows:

        x = array[offset]
        y = + * offset + 3. Coordinates are assigned as follows: + *

        + * x = array[offset]
        y = * array[offset + 1]
        z = array[offset + 2]

        * - * @param array the double array from which to read coordinate data. + * @param array the double array from which to read coordinate data. * @param offset the array starting index. * * @return a new Vec4 with x, y and z coordinate values from the specified - * double array. + * double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, or if the array's capacity is less - * than offset + 3. + * than offset + 3. */ - public static Vec4 fromArray3(double[] array, int offset) - { - if (array == null) - { + public static Vec4 fromArray3(double[] array, int offset) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -263,23 +257,23 @@ public static Vec4 fromArray3(double[] array, int offset) /** * Constructs a new Vec4 with x, y, z and w values from the * specified double array. The specified offset must be 0 or greater, and the array must have capacity equal to or - * greater than offset + 4. Coordinates are assigned as follows:

        x = + * greater than offset + 4. Coordinates are assigned as follows: + *

        + * x = * array[offset]
        y = array[offset + 1]
        z = array[offset + 2]
        w = * array[offset + 3]

        * - * @param array the double array from which to read coordinate data. + * @param array the double array from which to read coordinate data. * @param offset the array starting index. * * @return a new Vec4 with x, y, z and w coordinate values from - * the specified double array. + * the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, or if the array's capacity is less - * than offset + 4. + * than offset + 4. */ - public static Vec4 fromArray4(double[] array, int offset) - { - if (array == null) - { + public static Vec4 fromArray4(double[] array, int offset) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -291,46 +285,43 @@ public static Vec4 fromArray4(double[] array, int offset) /** * Writes this Vec4's coordinate values to the specified double array. The specified offset must be 0 or greater, * the specified length must be 1 or greater, and the array must have capacity equal to or greater than offset - * + length. Coordinates are written to the array as follows:

        array[offset] = + * + length. Coordinates are written to the array as follows: + *

        + * array[offset] = * x
        array[offset + 1] = y if length > 1, otherwise array[offset + * 1] is not written to
        array[offset + 2] = z if length > 2, otherwise * array[offset + 2] is not written to
        array[offset + 3] = w if length > * 3, otherwise array[offset + 3] is not written to

        * - * @param array the double array to receive the coordinate data. + * @param array the double array to receive the coordinate data. * @param offset the array starting index. * @param length the number of coordinates to write. * * @return the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, if length is less than 1, or if the - * array's capacity is less than offset + length. + * array's capacity is less than offset + length. */ - public final double[] toDoubleArray(double[] array, int offset, int length) - { - if (array == null) - { + public final double[] toDoubleArray(double[] array, int offset, int length) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (offset < 0) - { + if (offset < 0) { String msg = Logging.getMessage("generic.OffsetIsInvalid", offset); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (length < 1) - { + if (length < 1) { String msg = Logging.getMessage("generic.LengthIsInvalid", length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (array.length < offset + length) - { + if (array.length < offset + length) { String msg = Logging.getMessage("generic.ArrayInvalidLength", array.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -338,12 +329,15 @@ public final double[] toDoubleArray(double[] array, int offset, int length) array[offset] = this.x; - if (length > 1) + if (length > 1) { array[offset + 1] = this.y; - if (length > 2) + } + if (length > 2) { array[offset + 2] = this.z; - if (length > 3) + } + if (length > 3) { array[offset + 3] = this.w; + } return array; } @@ -351,46 +345,43 @@ public final double[] toDoubleArray(double[] array, int offset, int length) /** * Writes this Vec4's coordinate values to the specified float array. The specified offset must be 0 or greater, the * specified length must be 1 or greater, and the array must have capacity equal to or greater than offset + - * length. Coordinates are written to the array as follows:

        array[offset] = + * length. Coordinates are written to the array as follows: + *

        + * array[offset] = * x
        array[offset + 1] = y if length > 1, otherwise array[offset + * 1] is not written to
        array[offset + 2] = z if length > 2, otherwise * array[offset + 2] is not written to
        array[offset + 3] = w if length > * 3, otherwise array[offset + 3] is not written to

        * - * @param array the float array to receive the coordinate data. + * @param array the float array to receive the coordinate data. * @param offset the array starting index. * @param length the number of coordinates to write. * * @return the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, if length is less than 1, or if the - * array's capacity is less than offset + length. + * array's capacity is less than offset + length. */ - public final float[] toFloatArray(float[] array, int offset, int length) - { - if (array == null) - { + public final float[] toFloatArray(float[] array, int offset, int length) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (offset < 0) - { + if (offset < 0) { String msg = Logging.getMessage("generic.OffsetIsInvalid", offset); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (length < 1) - { + if (length < 1) { String msg = Logging.getMessage("generic.LengthIsInvalid", length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (array.length < offset + length) - { + if (array.length < offset + length) { String msg = Logging.getMessage("generic.ArrayInvalidLength", array.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -399,10 +390,12 @@ public final float[] toFloatArray(float[] array, int offset, int length) array[offset] = (float) this.x; array[offset + 1] = (float) this.y; - if (length > 2) + if (length > 2) { array[offset + 2] = (float) this.z; - if (length > 3) + } + if (length > 3) { array[offset + 3] = (float) this.w; + } return array; } @@ -410,21 +403,21 @@ public final float[] toFloatArray(float[] array, int offset, int length) /** * Writes this Vec4's x and y values to the specified double array. The specified offset * must be 0 or greater, and the array must have have capacity equal to or greater than offset + 2. - * Coordinates are written to the array as follows:

        array[offset] = x
        array[offset + 1] = + * Coordinates are written to the array as follows: + *

        + * array[offset] = x
        array[offset + 1] = * y

        * - * @param array the double array to receive the coordinate data. + * @param array the double array to receive the coordinate data. * @param offset the array starting index. * * @return the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, or if the array's capacity is less - * than offset + 2. + * than offset + 2. */ - public final double[] toArray2(double[] array, int offset) - { - if (array == null) - { + public final double[] toArray2(double[] array, int offset) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -436,21 +429,21 @@ public final double[] toArray2(double[] array, int offset) /** * Writes this Vec4's x, y and z values to the specified double array. The * specified offset must be 0 or greater, and the array must have have capacity equal to or greater than - * offset + 3. Coordinates are written to the array as follows:

        array[offset] = + * offset + 3. Coordinates are written to the array as follows: + *

        + * array[offset] = * x
        array[offset + 1] = y
        array[offset + 2] = z

        * - * @param array the double array to receive the coordinate data. + * @param array the double array to receive the coordinate data. * @param offset the array starting index. * * @return the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, or if the array's capacity is less - * than offset + 3. + * than offset + 3. */ - public final double[] toArray3(double[] array, int offset) - { - if (array == null) - { + public final double[] toArray3(double[] array, int offset) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -462,22 +455,22 @@ public final double[] toArray3(double[] array, int offset) /** * Writes this Vec4's x, y, z and w values to the specified * double array. The specified offset must be 0 or greater, and the array must have have capacity equal to or - * greater than offset + 4. Coordinates are written to the array as follows:

        array[offset] = + * greater than offset + 4. Coordinates are written to the array as follows: + *

        + * array[offset] = * x
        array[offset + 1] = y
        array[offset + 2] = z
        array[offset + * 3] = w

        * - * @param array the double array to receive the coordinate data. + * @param array the double array to receive the coordinate data. * @param offset the array starting index. * * @return the specified double array. * * @throws IllegalArgumentException if the array is null, if offset is negative, or if the array's capacity is less - * than offset + 4. + * than offset + 4. */ - public final double[] toArray4(double[] array, int offset) - { - if (array == null) - { + public final double[] toArray4(double[] array, int offset) { + if (array == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -497,13 +490,13 @@ public final double[] toArray4(double[] array, int offset) * * @return this Vec4 converted to a point vector in four-dimensional homogeneous coordinates. */ - public Vec4 toHomogeneousPoint3() - { + public Vec4 toHomogeneousPoint3() { // For a discussion of homogeneous coordinates, see "Mathematics for 3D Game Programming and Computer Graphics, // Second Edition" by Eric Lengyel, Section 3.4 (pages 81-84). - if (this.w == 1.0) + if (this.w == 1.0) { return this; + } return new Vec4(this.x, this.y, this.z, 1.0); } @@ -519,19 +512,18 @@ public Vec4 toHomogeneousPoint3() * * @return this Vec4 converted to a direction vector in four-dimensional homogeneous coordinates. */ - public Vec4 toHomogeneousDirection3() - { + public Vec4 toHomogeneousDirection3() { // For a discussion of homogeneous coordinates, see "Mathematics for 3D Game Programming and Computer Graphics, // Second Edition" by Eric Lengyel, Section 3.4 (pages 81-84). - if (this.w == 0.0) + if (this.w == 0.0) { return this; + } return new Vec4(this.x, this.y, this.z, 0.0); } - public final String toString() - { + public final String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(this.x).append(", "); @@ -542,63 +534,52 @@ public final String toString() return sb.toString(); } - public final double getX() - { + public final double getX() { return this.x; } - public final double getY() - { + public final double getY() { return this.y; } - public final double getZ() - { + public final double getZ() { return this.z; } - public final double getW() - { + public final double getW() { return this.w; } - public final double x() - { + public final double x() { return this.x; } - public final double y() - { + public final double y() { return this.y; } - public final double z() - { + public final double z() { return this.z; } - public final double w() - { + public final double w() { return this.w; } // ============== Factory Functions ======================= // // ============== Factory Functions ======================= // // ============== Factory Functions ======================= // - - public static Vec4 fromLine3(Vec4 origin, double t, Vec4 direction) - { - if (origin == null || direction == null) - { + public static Vec4 fromLine3(Vec4 origin, double t, Vec4 direction) { + if (origin == null || direction == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - origin.x + (direction.x * t), - origin.y + (direction.y * t), - origin.z + (direction.z * t)); + origin.x + (direction.x * t), + origin.y + (direction.y * t), + origin.z + (direction.z * t)); // return fromLine3( // origin.x, origin.y, origin.z, @@ -633,157 +614,132 @@ public static Vec4 fromLine3(Vec4 origin, double t, Vec4 direction) // ============== Arithmetic Functions ======================= // // ============== Arithmetic Functions ======================= // // ============== Arithmetic Functions ======================= // - - public final Vec4 add3(Vec4 vec4) - { - if (vec4 == null) - { + public final Vec4 add3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - this.x + vec4.x, - this.y + vec4.y, - this.z + vec4.z, - this.w); + this.x + vec4.x, + this.y + vec4.y, + this.z + vec4.z, + this.w); } - public final Vec4 add3(double x, double y, double z) - { + public final Vec4 add3(double x, double y, double z) { return new Vec4(this.x + x, this.y + y, this.z + z, this.w); } - public final Vec4 subtract3(Vec4 vec4) - { - if (vec4 == null) - { + public final Vec4 subtract3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - this.x - vec4.x, - this.y - vec4.y, - this.z - vec4.z, - this.w); + this.x - vec4.x, + this.y - vec4.y, + this.z - vec4.z, + this.w); } - public final Vec4 subtract3(double x, double y, double z) - { + public final Vec4 subtract3(double x, double y, double z) { return new Vec4(this.x - x, this.y - y, this.z - z, this.w); } - public final Vec4 multiply3(double value) - { + public final Vec4 multiply3(double value) { return new Vec4( - this.x * value, - this.y * value, - this.z * value, - this.w); + this.x * value, + this.y * value, + this.z * value, + this.w); } - public final Vec4 multiply3(Vec4 vec4) - { - if (vec4 == null) - { + public final Vec4 multiply3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - this.x * vec4.x, - this.y * vec4.y, - this.z * vec4.z, - this.w); + this.x * vec4.x, + this.y * vec4.y, + this.z * vec4.z, + this.w); } - public final Vec4 divide3(double value) - { - if (value == 0) - { + public final Vec4 divide3(double value) { + if (value == 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", value); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - this.x / value, - this.y / value, - this.z / value, - this.w); + this.x / value, + this.y / value, + this.z / value, + this.w); } - public final Vec4 divide3(Vec4 vec4) - { - if (vec4 == null) - { + public final Vec4 divide3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - this.x / vec4.x, - this.y / vec4.y, - this.z / vec4.z, - this.w); + this.x / vec4.x, + this.y / vec4.y, + this.z / vec4.z, + this.w); } - public final Vec4 getNegative3() - { + public final Vec4 getNegative3() { return new Vec4( - 0.0 - this.x, - 0.0 - this.y, - 0.0 - this.z, - this.w); + 0.0 - this.x, + 0.0 - this.y, + 0.0 - this.z, + this.w); } - public final Vec4 getAbs3() - { + public final Vec4 getAbs3() { return new Vec4(Math.abs(this.x), Math.abs(this.y), Math.abs(this.z)); } // ============== Geometric Functions ======================= // // ============== Geometric Functions ======================= // // ============== Geometric Functions ======================= // - - public final double getLength3() - { + public final double getLength3() { return Math.sqrt(this.getLengthSquared3()); } - public final double getLengthSquared3() - { + public final double getLengthSquared3() { return (this.x * this.x) - + (this.y * this.y) - + (this.z * this.z); + + (this.y * this.y) + + (this.z * this.z); } - public final Vec4 normalize3() - { + public final Vec4 normalize3() { double length = this.getLength3(); // Vector has zero length. - if (length == 0) - { + if (length == 0) { return this; - } - else - { + } else { return new Vec4( - this.x / length, - this.y / length, - this.z / length); + this.x / length, + this.y / length, + this.z / length); } } - public final double distanceTo2(Vec4 vec4) - { - if (vec4 == null) - { + public final double distanceTo2(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -794,10 +750,8 @@ public final double distanceTo2(Vec4 vec4) return Math.sqrt(dx * dx + dy * dy); } - public final double distanceTo3(Vec4 vec4) - { - if (vec4 == null) - { + public final double distanceTo3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -806,10 +760,8 @@ public final double distanceTo3(Vec4 vec4) return Math.sqrt(this.distanceToSquared3(vec4)); } - public final double distanceToSquared3(Vec4 vec4) - { - if (vec4 == null) - { + public final double distanceToSquared3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -826,10 +778,8 @@ public final double distanceToSquared3(Vec4 vec4) return result; } - public final double dot3(Vec4 vec4) - { - if (vec4 == null) - { + public final double dot3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -838,10 +788,8 @@ public final double dot3(Vec4 vec4) return (this.x * vec4.x) + (this.y * vec4.y) + (this.z * vec4.z); } - public final double dot4(Vec4 vec4) - { - if (vec4 == null) - { + public final double dot4(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -850,35 +798,29 @@ public final double dot4(Vec4 vec4) return (this.x * vec4.x) + (this.y * vec4.y) + (this.z * vec4.z) + (this.w * vec4.w); } - public final double dotSelf3() - { + public final double dotSelf3() { return this.dot3(this); } - public final double dotSelf4() - { + public final double dotSelf4() { return this.dot4(this); } - public final Vec4 cross3(Vec4 vec4) - { - if (vec4 == null) - { + public final Vec4 cross3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - (this.y * vec4.z) - (this.z * vec4.y), - (this.z * vec4.x) - (this.x * vec4.z), - (this.x * vec4.y) - (this.y * vec4.x)); + (this.y * vec4.z) - (this.z * vec4.y), + (this.z * vec4.x) - (this.x * vec4.z), + (this.x * vec4.y) - (this.y * vec4.x)); } - public final Angle angleBetween3(Vec4 vec4) - { - if (vec4 == null) - { + public final Angle angleBetween3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -888,15 +830,17 @@ public final Angle angleBetween3(Vec4 vec4) // Compute the sum of magnitudes. double length = this.getLength3() * vec4.getLength3(); // Normalize the dot product, if necessary. - if (!(length == 0) && (length != 1.0)) + if (!(length == 0) && (length != 1.0)) { a_dot_b /= length; + } // The normalized dot product should be in the range [-1, 1]. Otherwise the result is an error from floating // point roundoff. So if a_dot_b is less than -1 or greater than +1, we treat it as -1 and +1 respectively. - if (a_dot_b < -1.0) + if (a_dot_b < -1.0) { a_dot_b = -1.0; - else if (a_dot_b > 1.0) + } else if (a_dot_b > 1.0) { a_dot_b = 1.0; + } // Angle is arc-cosine of normalized dot product. return Angle.fromRadians(Math.acos(a_dot_b)); @@ -905,25 +849,22 @@ else if (a_dot_b > 1.0) /** * Compute the angle and rotation axis required to rotate one vector to align with another. * - * @param v1 The base vector. - * @param v2 The vector to rotate into alignment with v1. + * @param v1 The base vector. + * @param v2 The vector to rotate into alignment with v1. * @param result A reference to an array in which to return the computed axis. May not be null. * * @return The rotation angle. * * @throws IllegalArgumentException if any parameter is null. */ - public static Angle axisAngle(Vec4 v1, Vec4 v2, Vec4[] result) - { - if (v1 == null || v2 == null) - { + public static Angle axisAngle(Vec4 v1, Vec4 v2, Vec4[] result) { + if (v1 == null || v2 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (result == null) - { + if (result == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -944,10 +885,8 @@ public static Angle axisAngle(Vec4 v1, Vec4 v2, Vec4[] result) return angle; } - public final Vec4 projectOnto3(Vec4 vec4) - { - if (vec4 == null) - { + public final Vec4 projectOnto3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -956,15 +895,14 @@ public final Vec4 projectOnto3(Vec4 vec4) double dot = this.dot3(vec4); double length = vec4.getLength3(); // Normalize the dot product, if necessary. - if (!(length == 0) && (length != 1.0)) + if (!(length == 0) && (length != 1.0)) { dot /= (length * length); + } return vec4.multiply3(dot); } - public final Vec4 perpendicularTo3(Vec4 vec4) - { - if (vec4 == null) - { + public final Vec4 perpendicularTo3(Vec4 vec4) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -978,37 +916,32 @@ public final Vec4 perpendicularTo3(Vec4 vec4) * * @return an array of two unit vectors mutually orthogonal to this vector. */ - public Vec4[] perpendicularVectors() - { + public Vec4[] perpendicularVectors() { // For the first vector, use the direction of the least component of this, which indicates the more // orthogonal axis to this. Vec4 v = this; Vec4 v1 = v.x <= v.y && v.x <= v.z ? Vec4.UNIT_X : v.y <= v.x && v.y <= v.z ? Vec4.UNIT_Y : Vec4.UNIT_Z; - Vec4 va = v.cross3(v1).normalize3(); + Vec4 va = v.cross3(v1).normalize3(); Vec4 vb = v.cross3(va).normalize3(); - return new Vec4[] {va, vb}; + return new Vec4[]{va, vb}; } - public final Vec4 transformBy3(Matrix matrix) - { - if (matrix == null) - { + public final Vec4 transformBy3(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - (matrix.m11 * this.x) + (matrix.m12 * this.y) + (matrix.m13 * this.z), - (matrix.m21 * this.x) + (matrix.m22 * this.y) + (matrix.m23 * this.z), - (matrix.m31 * this.x) + (matrix.m32 * this.y) + (matrix.m33 * this.z)); + (matrix.m11 * this.x) + (matrix.m12 * this.y) + (matrix.m13 * this.z), + (matrix.m21 * this.x) + (matrix.m22 * this.y) + (matrix.m23 * this.z), + (matrix.m31 * this.x) + (matrix.m32 * this.y) + (matrix.m33 * this.z)); } - public final Vec4 transformBy3(Quaternion quaternion) - { - if (quaternion == null) - { + public final Vec4 transformBy3(Quaternion quaternion) { + if (quaternion == null) { String msg = Logging.getMessage("nullValue.QuaternionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1020,90 +953,80 @@ public final Vec4 transformBy3(Quaternion quaternion) return new Vec4(tmp.x, tmp.y, tmp.z, 0.0); } - public final Vec4 transformBy4(Matrix matrix) - { - if (matrix == null) - { + public final Vec4 transformBy4(Matrix matrix) { + if (matrix == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - (matrix.m11 * this.x) + (matrix.m12 * this.y) + (matrix.m13 * this.z) + (matrix.m14 * this.w), - (matrix.m21 * this.x) + (matrix.m22 * this.y) + (matrix.m23 * this.z) + (matrix.m24 * this.w), - (matrix.m31 * this.x) + (matrix.m32 * this.y) + (matrix.m33 * this.z) + (matrix.m34 * this.w), - (matrix.m41 * this.x) + (matrix.m42 * this.y) + (matrix.m43 * this.z) + (matrix.m44 * this.w)); + (matrix.m11 * this.x) + (matrix.m12 * this.y) + (matrix.m13 * this.z) + (matrix.m14 * this.w), + (matrix.m21 * this.x) + (matrix.m22 * this.y) + (matrix.m23 * this.z) + (matrix.m24 * this.w), + (matrix.m31 * this.x) + (matrix.m32 * this.y) + (matrix.m33 * this.z) + (matrix.m34 * this.w), + (matrix.m41 * this.x) + (matrix.m42 * this.y) + (matrix.m43 * this.z) + (matrix.m44 * this.w)); } // ============== Mixing Functions ======================= // // ============== Mixing Functions ======================= // // ============== Mixing Functions ======================= // - - public static Vec4 min3(Vec4 value1, Vec4 value2) - { - if ((value1 == null) || (value2 == null)) - { + public static Vec4 min3(Vec4 value1, Vec4 value2) { + if ((value1 == null) || (value2 == null)) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - (value1.x < value2.x) ? value1.x : value2.x, - (value1.y < value2.y) ? value1.y : value2.y, - (value1.z < value2.z) ? value1.z : value2.z); + (value1.x < value2.x) ? value1.x : value2.x, + (value1.y < value2.y) ? value1.y : value2.y, + (value1.z < value2.z) ? value1.z : value2.z); } - public static Vec4 max3(Vec4 value1, Vec4 value2) - { - if ((value1 == null) || (value2 == null)) - { + public static Vec4 max3(Vec4 value1, Vec4 value2) { + if ((value1 == null) || (value2 == null)) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - (value1.x > value2.x) ? value1.x : value2.x, - (value1.y > value2.y) ? value1.y : value2.y, - (value1.z > value2.z) ? value1.z : value2.z); + (value1.x > value2.x) ? value1.x : value2.x, + (value1.y > value2.y) ? value1.y : value2.y, + (value1.z > value2.z) ? value1.z : value2.z); } - public static Vec4 clamp3(Vec4 vec4, double min, double max) - { - if (vec4 == null) - { + public static Vec4 clamp3(Vec4 vec4, double min, double max) { + if (vec4 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return new Vec4( - (vec4.x < min) ? min : ((vec4.x > max) ? max : vec4.x), - (vec4.y < min) ? min : ((vec4.y > max) ? max : vec4.y), - (vec4.z < min) ? min : ((vec4.z > max) ? max : vec4.z)); + (vec4.x < min) ? min : ((vec4.x > max) ? max : vec4.x), + (vec4.y < min) ? min : ((vec4.y > max) ? max : vec4.y), + (vec4.z < min) ? min : ((vec4.z > max) ? max : vec4.z)); } - public static Vec4 mix3(double amount, Vec4 value1, Vec4 value2) - { - if ((value1 == null) || (value2 == null)) - { + public static Vec4 mix3(double amount, Vec4 value1, Vec4 value2) { + if ((value1 == null) || (value2 == null)) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (amount < 0.0) + if (amount < 0.0) { return value1; - else if (amount > 1.0) + } else if (amount > 1.0) { return value2; + } double t1 = 1.0 - amount; return new Vec4( - (value1.x * t1) + (value2.x * amount), - (value1.y * t1) + (value2.y * amount), - (value1.z * t1) + (value2.z * amount)); + (value1.x * t1) + (value2.x * amount), + (value1.y * t1) + (value2.y * amount), + (value1.z * t1) + (value2.z * amount)); } /** @@ -1113,14 +1036,12 @@ else if (amount > 1.0) * @param points the Iterable of points which define the returned arithmetic mean. * * @return the arithmetic mean point of the specified points Iterable, or null if the Iterable is empty or contains - * only null points. + * only null points. * * @throws IllegalArgumentException if the Iterable is null. */ - public static Vec4 computeAveragePoint(Iterable points) - { - if (points == null) - { + public static Vec4 computeAveragePoint(Iterable points) { + if (points == null) { String msg = Logging.getMessage("nullValue.PointListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1132,10 +1053,10 @@ public static Vec4 computeAveragePoint(Iterable points) double z = 0d; double w = 0d; - for (Vec4 vec : points) - { - if (vec == null) + for (Vec4 vec : points) { + if (vec == null) { continue; + } count++; x += vec.x; @@ -1144,8 +1065,9 @@ public static Vec4 computeAveragePoint(Iterable points) w += vec.w; } - if (count == 0) + if (count == 0) { return null; + } return new Vec4(x / (double) count, y / (double) count, z / (double) count, w / (double) count); } @@ -1162,25 +1084,22 @@ public static Vec4 computeAveragePoint(Iterable points) * remaining elements that follow the last complete tuple. * * @param coordinates the buffer containing the point coordinates for which to compute a bounding volume. - * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, - * this interprets the buffer has having tightly packed XYZ coordinate tuples. + * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, this + * interprets the buffer has having tightly packed XYZ coordinate tuples. * * @return the arithmetic mean point of the specified points Iterable, or null if the Iterable is empty or contains - * only null points. + * only null points. * * @throws IllegalArgumentException if the buffer is null, or if the stride is less than three. */ - public static Vec4 computeAveragePoint3(BufferWrapper coordinates, int stride) - { - if (coordinates == null) - { + public static Vec4 computeAveragePoint3(BufferWrapper coordinates, int stride) { + if (coordinates == null) { String msg = Logging.getMessage("nullValue.CoordinatesAreNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (stride < 3) - { + if (stride < 3) { String msg = Logging.getMessage("generic.StrideIsInvalid"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1191,24 +1110,22 @@ public static Vec4 computeAveragePoint3(BufferWrapper coordinates, int stride) double y = 0d; double z = 0d; - for (int i = 0; i <= coordinates.length() - stride; i += stride) - { + for (int i = 0; i <= coordinates.length() - stride; i += stride) { count++; x += coordinates.getDouble(i); y += coordinates.getDouble(i + 1); z += coordinates.getDouble(i + 2); } - if (count == 0) + if (count == 0) { return null; + } return new Vec4(x / (double) count, y / (double) count, z / (double) count); } - public static double getAverageDistance(Iterable points) - { - if ((points == null)) - { + public static double getAverageDistance(Iterable points) { + if ((points == null)) { String msg = Logging.getMessage("nullValue.PointListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1217,12 +1134,9 @@ public static double getAverageDistance(Iterable points) double totalDistance = 0.0; int count = 0; - for (Vec4 p1 : points) - { - for (Vec4 p2 : points) - { - if (p1 != p2) - { + for (Vec4 p1 : points) { + for (Vec4 p2 : points) { + if (p1 != p2) { double d = p1.distanceTo3(p2); totalDistance += d; count++; @@ -1245,17 +1159,16 @@ public static double getAverageDistance(Iterable points) * * @throws IllegalArgumentException if points is null */ - public static Vec4[] computeExtrema(Vec4 points[]) - { - if (points == null) - { + public static Vec4[] computeExtrema(Vec4 points[]) { + if (points == null) { String message = Logging.getMessage("nullValue.PointsArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (points.length == 0) + if (points.length == 0) { return null; + } double xmin = points[0].x; double ymin = points[0].y; @@ -1264,53 +1177,42 @@ public static Vec4[] computeExtrema(Vec4 points[]) double ymax = ymin; double zmax = zmin; - for (int i = 1; i < points.length; i++) - { + for (int i = 1; i < points.length; i++) { double x = points[i].x; - if (x > xmax) - { + if (x > xmax) { xmax = x; - } - else if (x < xmin) - { + } else if (x < xmin) { xmin = x; } double y = points[i].y; - if (y > ymax) - { + if (y > ymax) { ymax = y; - } - else if (y < ymin) - { + } else if (y < ymin) { ymin = y; } double z = points[i].z; - if (z > zmax) - { + if (z > zmax) { zmax = z; - } - else if (z < zmin) - { + } else if (z < zmin) { zmin = z; } } - return new Vec4[] {new Vec4(xmin, ymin, zmin), new Vec4(xmax, ymax, zmax)}; + return new Vec4[]{new Vec4(xmin, ymin, zmin), new Vec4(xmax, ymax, zmax)}; } - public static Vec4[] computeExtrema(BufferWrapper buffer) - { - if (buffer == null) - { + public static Vec4[] computeExtrema(BufferWrapper buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer.getBackingBuffer().position() > buffer.getBackingBuffer().limit() - 3) + if (buffer.getBackingBuffer().position() > buffer.getBackingBuffer().limit() - 3) { return null; + } double xmin = buffer.getDouble(0); double ymin = buffer.getDouble(1); @@ -1319,40 +1221,30 @@ public static Vec4[] computeExtrema(BufferWrapper buffer) double ymax = ymin; double zmax = zmin; - for (int i = 1; i < buffer.length() / 3; i++) - { + for (int i = 1; i < buffer.length() / 3; i++) { double x = buffer.getDouble(i * 3); - if (x > xmax) - { + if (x > xmax) { xmax = x; - } - else if (x < xmin) - { + } else if (x < xmin) { xmin = x; } double y = buffer.getDouble(i * 3 + 1); - if (y > ymax) - { + if (y > ymax) { ymax = y; - } - else if (y < ymin) - { + } else if (y < ymin) { ymin = y; } double z = buffer.getDouble(i * 3 + 2); - if (z > zmax) - { + if (z > zmax) { zmax = z; - } - else if (z < zmin) - { + } else if (z < zmin) { zmin = z; } } - return new Vec4[] {new Vec4(xmin, ymin, zmin), new Vec4(xmax, ymax, zmax)}; + return new Vec4[]{new Vec4(xmin, ymin, zmin), new Vec4(xmax, ymax, zmax)}; } /** @@ -1366,10 +1258,8 @@ else if (z < zmin) * * @throws IllegalArgumentException if any argument is null. */ - public static boolean areColinear(Vec4 a, Vec4 b, Vec4 c) - { - if (a == null || b == null || c == null) - { + public static boolean areColinear(Vec4 a, Vec4 b, Vec4 c) { + if (a == null || b == null || c == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); diff --git a/src/gov/nasa/worldwind/geom/coords/DatumTransformation.java b/src/gov/nasa/worldwind/geom/coords/DatumTransformation.java index 4675d1a8a5..0593246cf7 100644 --- a/src/gov/nasa/worldwind/geom/coords/DatumTransformation.java +++ b/src/gov/nasa/worldwind/geom/coords/DatumTransformation.java @@ -11,22 +11,21 @@ import gov.nasa.worldwind.util.Logging; /** - * Class with static methods for datum transformation. Currently shifts between NAD27 and WGS84. Other shifts will be + * Class with static methods for datum transformation. Currently shifts between NAD27 and WGS84. Other shifts will be * added as needed. * * @author jparsons * @version $Id: DatumTransformation.java 1958 2014-04-24 19:25:37Z tgaskins $ */ -public class DatumTransformation -{ +public class DatumTransformation { private final static double Clarke1866_EQUATORIAL_RADIUS = 6378206.4; // ellipsoid equatorial getRadius, in meters private final static double Clarke1866_POLAR_RADIUS = 6356583.8; // ellipsoid polar getRadius, in meters private final static double Clarke1866_ES = 0.00676865799729; // eccentricity squared, semi-major axis public static Globe CLARKE1866_GLOBE = new EllipsoidalGlobe(Clarke1866_EQUATORIAL_RADIUS, Clarke1866_POLAR_RADIUS, - Clarke1866_ES, - EllipsoidalGlobe.makeElevationModel(AVKey.EARTH_ELEVATION_MODEL_CONFIG_FILE, - "config/Earth/EarthElevations2.xml")); + Clarke1866_ES, + EllipsoidalGlobe.makeElevationModel(AVKey.EARTH_ELEVATION_MODEL_CONFIG_FILE, + "config/Earth/EarthElevations2.xml")); /** * Shift datum from NAD27 to WGS84 @@ -37,10 +36,8 @@ public class DatumTransformation * * @throws IllegalArgumentException if Position is null */ - public static Position convertNad27toWGS84(Position pos) - { - if (pos == null) - { + public static Position convertNad27toWGS84(Position pos) { + if (pos == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -52,7 +49,7 @@ public static Position convertNad27toWGS84(Position pos) double dz_nad27_to_wgs84 = 176; return DatumTransformation.threeParamMolodenski(pos, CLARKE1866_GLOBE, new Earth(), - dx_nad27_to_wgs84, dy_nad27_to_wgs84, dz_nad27_to_wgs84); + dx_nad27_to_wgs84, dy_nad27_to_wgs84, dz_nad27_to_wgs84); } /** @@ -64,10 +61,8 @@ public static Position convertNad27toWGS84(Position pos) * * @throws IllegalArgumentException if Position is null */ - public static Position convertWGS84toNad27(Position pos) - { - if (pos == null) - { + public static Position convertWGS84toNad27(Position pos) { + if (pos == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -79,12 +74,11 @@ public static Position convertWGS84toNad27(Position pos) double dz_wgs84_to_nad27 = -176; return DatumTransformation.threeParamMolodenski(pos, new Earth(), CLARKE1866_GLOBE, - dx_wgs84_to_nad27, dy_wgs84_to_nad27, dz_wgs84_to_nad27); + dx_wgs84_to_nad27, dy_wgs84_to_nad27, dz_wgs84_to_nad27); } private static Position threeParamMolodenski(Position source, Globe fromGlobe, Globe toGlobe, - double dx, double dy, double dz) - { + double dx, double dy, double dz) { double sinLat = Math.sin(source.getLatitude().getRadians()); double cosLat = Math.cos(source.getLatitude().getRadians()); @@ -99,23 +93,22 @@ private static Position threeParamMolodenski(Position source, Globe fromGlobe, G double dEquatorialRadius = (toGlobe.getEquatorialRadius() - fromGlobe.getEquatorialRadius()); double rn = fromGlobe.getEquatorialRadius() / Math.sqrt( - 1.0 - fromGlobe.getEccentricitySquared() * sinLatsquared); - double rm = fromGlobe.getEquatorialRadius() * (1. - fromGlobe.getEccentricitySquared()) / - Math.pow((1.0 - fromGlobe.getEccentricitySquared() * sinLatsquared), 1.5); + 1.0 - fromGlobe.getEccentricitySquared() * sinLatsquared); + double rm = fromGlobe.getEquatorialRadius() * (1. - fromGlobe.getEccentricitySquared()) + / Math.pow((1.0 - fromGlobe.getEccentricitySquared() * sinLatsquared), 1.5); double dLat = (((((-dx * sinLat * cosLon - dy * sinLat * sinLon) + dz * cosLat) - + (dEquatorialRadius * ((rn * fromGlobe.getEccentricitySquared() * sinLat * cosLat) - / fromGlobe.getEquatorialRadius()))) - + (dF * (rm * adb + rn / adb) * sinLat * cosLat))) - / (rm + source.getElevation()); + + (dEquatorialRadius * ((rn * fromGlobe.getEccentricitySquared() * sinLat * cosLat) + / fromGlobe.getEquatorialRadius()))) + + (dF * (rm * adb + rn / adb) * sinLat * cosLat))) + / (rm + source.getElevation()); double dLon = (-dx * sinLon + dy * cosLon) / ((rn + source.getElevation()) * cosLat); double dh = (dx * cosLat * cosLon) + (dy * cosLat * sinLon) + (dz * sinLat) - - (dEquatorialRadius * (fromGlobe.getEquatorialRadius() / rn)) + ((dF * rn * sinLatsquared) / adb); + - (dEquatorialRadius * (fromGlobe.getEquatorialRadius() / rn)) + ((dF * rn * sinLatsquared) / adb); return Position.fromRadians(source.getLatitude().getRadians() + dLat, - source.getLongitude().getRadians() + dLon, source.getElevation() + dh); + source.getLongitude().getRadians() + dLon, source.getElevation() + dh); } } - diff --git a/src/gov/nasa/worldwind/geom/coords/MGRSCoord.java b/src/gov/nasa/worldwind/geom/coords/MGRSCoord.java index 60bc871426..d40d650a6e 100644 --- a/src/gov/nasa/worldwind/geom/coords/MGRSCoord.java +++ b/src/gov/nasa/worldwind/geom/coords/MGRSCoord.java @@ -10,82 +10,75 @@ import gov.nasa.worldwind.util.Logging; /** - * This class holds an immutable MGRS coordinate string along with - * the corresponding latitude and longitude. + * This class holds an immutable MGRS coordinate string along with the corresponding latitude and longitude. * * @author Patrick Murris * @version $Id: MGRSCoord.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class MGRSCoord { -public class MGRSCoord -{ private final String MGRSString; private final Angle latitude; private final Angle longitude; /** - * Create a WGS84 MGRS coordinate from a pair of latitude and longitude Angle - * with the maximum precision of five digits (one meter). + * Create a WGS84 MGRS coordinate from a pair of latitude and longitude Angle with the maximum + * precision of five digits (one meter). * * @param latitude the latitude Angle. * @param longitude the longitude Angle. * @return the corresponding MGRSCoord. - * @throws IllegalArgumentException if latitude or longitude is null, - * or the conversion to MGRS coordinates fails. + * @throws IllegalArgumentException if latitude or longitude is null, or the conversion to + * MGRS coordinates fails. */ - public static MGRSCoord fromLatLon(Angle latitude, Angle longitude) - { + public static MGRSCoord fromLatLon(Angle latitude, Angle longitude) { return fromLatLon(latitude, longitude, null, 5); } /** - * Create a WGS84 MGRS coordinate from a pair of latitude and longitude Angle - * with the given precision or number of digits. + * Create a WGS84 MGRS coordinate from a pair of latitude and longitude Angle with the given precision + * or number of digits. * * @param latitude the latitude Angle. * @param longitude the longitude Angle. * @param precision the number of digits used for easting and northing (1 to 5). * @return the corresponding MGRSCoord. - * @throws IllegalArgumentException if latitude or longitude is null, - * or the conversion to MGRS coordinates fails. + * @throws IllegalArgumentException if latitude or longitude is null, or the conversion to + * MGRS coordinates fails. */ - public static MGRSCoord fromLatLon(Angle latitude, Angle longitude, int precision) - { + public static MGRSCoord fromLatLon(Angle latitude, Angle longitude, int precision) { return fromLatLon(latitude, longitude, null, precision); } /** - * Create a MGRS coordinate from a pair of latitude and longitude Angle - * with the maximum precision of five digits (one meter). + * Create a MGRS coordinate from a pair of latitude and longitude Angle with the maximum precision of + * five digits (one meter). * * @param latitude the latitude Angle. * @param longitude the longitude Angle. * @param globe the Globe. * @return the corresponding MGRSCoord. - * @throws IllegalArgumentException if latitude or longitude is null, - * the globe is null, or the conversion to MGRS coordinates fails. + * @throws IllegalArgumentException if latitude or longitude is null, the + * globe is null, or the conversion to MGRS coordinates fails. */ - public static MGRSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) - { + public static MGRSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) { return fromLatLon(latitude, longitude, globe, 5); } /** - * Create a MGRS coordinate from a pair of latitude and longitude Angle - * with the given precision or number of digits (1 to 5). + * Create a MGRS coordinate from a pair of latitude and longitude Angle with the given precision or + * number of digits (1 to 5). * * @param latitude the latitude Angle. * @param longitude the longitude Angle. * @param globe the Globe - can be null (will use WGS84). * @param precision the number of digits used for easting and northing (1 to 5). * @return the corresponding MGRSCoord. - * @throws IllegalArgumentException if latitude or longitude is null, - * or the conversion to MGRS coordinates fails. + * @throws IllegalArgumentException if latitude or longitude is null, or the conversion to + * MGRS coordinates fails. */ - public static MGRSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe, int precision) - { - if (latitude == null || longitude == null) - { + public static MGRSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe, int precision) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -94,8 +87,7 @@ public static MGRSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe, final MGRSCoordConverter converter = new MGRSCoordConverter(globe); long err = converter.convertGeodeticToMGRS(latitude.radians, longitude.radians, precision); - if (err != MGRSCoordConverter.MGRS_NO_ERROR) - { + if (err != MGRSCoordConverter.MGRS_NO_ERROR) { String message = Logging.getMessage("Coord.MGRSConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -109,21 +101,21 @@ public static MGRSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe, *

        * The string will be converted to uppercase and stripped of all spaces before being evaluated. *

        - *

        Valid examples:
        + *

        + * Valid examples:
        * 32TLP5626635418
        * 32 T LP 56266 35418
        * 11S KU 528 111
        *

        + * * @param MGRSString the MGRS coordinate text string. * @param globe the Globe - can be null (will use WGS84). * @return the corresponding MGRSCoord. - * @throws IllegalArgumentException if the MGRSString is null or empty, - * the globe is null, or the conversion to geodetic coordinates fails (invalid coordinate string). + * @throws IllegalArgumentException if the MGRSString is null or empty, the globe is null, + * or the conversion to geodetic coordinates fails (invalid coordinate string). */ - public static MGRSCoord fromString(String MGRSString, Globe globe) - { - if (MGRSString == null || MGRSString.length() == 0) - { + public static MGRSCoord fromString(String MGRSString, Globe globe) { + if (MGRSString == null || MGRSString.length() == 0) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -134,8 +126,7 @@ public static MGRSCoord fromString(String MGRSString, Globe globe) final MGRSCoordConverter converter = new MGRSCoordConverter(globe); long err = converter.convertMGRSToGeodetic(MGRSString); - if (err != MGRSCoordConverter.MGRS_NO_ERROR) - { + if (err != MGRSCoordConverter.MGRS_NO_ERROR) { String message = Logging.getMessage("Coord.MGRSConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -145,31 +136,27 @@ public static MGRSCoord fromString(String MGRSString, Globe globe) } /** - * Create an arbitrary MGRS coordinate from a pair of latitude-longitude Angle - * and the corresponding MGRS coordinate string. + * Create an arbitrary MGRS coordinate from a pair of latitude-longitude Angle and the corresponding + * MGRS coordinate string. * * @param latitude the latitude Angle. * @param longitude the longitude Angle. * @param MGRSString the corresponding MGRS coordinate string. - * @throws IllegalArgumentException if latitude or longitude is null, - * or the MGRSString is null or empty. + * @throws IllegalArgumentException if latitude or longitude is null, or the MGRSString is + * null or empty. */ - public MGRSCoord(Angle latitude, Angle longitude, String MGRSString) - { - if (latitude == null || longitude == null) - { + public MGRSCoord(Angle latitude, Angle longitude, String MGRSString) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (MGRSString == null) - { + if (MGRSString == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (MGRSString.length() == 0) - { + if (MGRSString.length() == 0) { String message = Logging.getMessage("generic.StringIsEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -179,18 +166,15 @@ public MGRSCoord(Angle latitude, Angle longitude, String MGRSString) this.MGRSString = MGRSString; } - public Angle getLatitude() - { + public Angle getLatitude() { return this.latitude; } - public Angle getLongitude() - { + public Angle getLongitude() { return this.longitude; } - public String toString() - { + public String toString() { return this.MGRSString; } diff --git a/src/gov/nasa/worldwind/geom/coords/MGRSCoordConverter.java b/src/gov/nasa/worldwind/geom/coords/MGRSCoordConverter.java index 4762603fa8..5ee1671464 100644 --- a/src/gov/nasa/worldwind/geom/coords/MGRSCoordConverter.java +++ b/src/gov/nasa/worldwind/geom/coords/MGRSCoordConverter.java @@ -16,15 +16,14 @@ * @version $Id: MGRSCoordConverter.java 1171 2013-02-11 21:45:02Z dcollins $ * @see MGRSCoord */ - /** * Ported to Java from the NGA GeoTrans mgrs.c and mgrs.h code. Contains routines to convert from Geodetic to MGRS and * the other direction. * * @author Garrett Headley, Patrick Murris */ -class MGRSCoordConverter -{ +class MGRSCoordConverter { + public static final int MGRS_NO_ERROR = 0; private static final int MGRS_LAT_ERROR = 0x0001; private static final int MGRS_LON_ERROR = 0x0002; @@ -76,33 +75,60 @@ class MGRSCoordConverter private double latitude; private double longitude; - private static final int LETTER_A = 0; /* ARRAY INDEX FOR LETTER A */ - private static final int LETTER_B = 1; /* ARRAY INDEX FOR LETTER B */ - private static final int LETTER_C = 2; /* ARRAY INDEX FOR LETTER C */ - private static final int LETTER_D = 3; /* ARRAY INDEX FOR LETTER D */ - private static final int LETTER_E = 4; /* ARRAY INDEX FOR LETTER E */ - private static final int LETTER_F = 5; /* ARRAY INDEX FOR LETTER E */ - private static final int LETTER_G = 6; /* ARRAY INDEX FOR LETTER H */ - private static final int LETTER_H = 7; /* ARRAY INDEX FOR LETTER H */ - private static final int LETTER_I = 8; /* ARRAY INDEX FOR LETTER I */ - private static final int LETTER_J = 9; /* ARRAY INDEX FOR LETTER J */ - private static final int LETTER_K = 10; /* ARRAY INDEX FOR LETTER J */ - private static final int LETTER_L = 11; /* ARRAY INDEX FOR LETTER L */ - private static final int LETTER_M = 12; /* ARRAY INDEX FOR LETTER M */ - private static final int LETTER_N = 13; /* ARRAY INDEX FOR LETTER N */ - private static final int LETTER_O = 14; /* ARRAY INDEX FOR LETTER O */ - private static final int LETTER_P = 15; /* ARRAY INDEX FOR LETTER P */ - private static final int LETTER_Q = 16; /* ARRAY INDEX FOR LETTER Q */ - private static final int LETTER_R = 17; /* ARRAY INDEX FOR LETTER R */ - private static final int LETTER_S = 18; /* ARRAY INDEX FOR LETTER S */ - private static final int LETTER_T = 19; /* ARRAY INDEX FOR LETTER S */ - private static final int LETTER_U = 20; /* ARRAY INDEX FOR LETTER U */ - private static final int LETTER_V = 21; /* ARRAY INDEX FOR LETTER V */ - private static final int LETTER_W = 22; /* ARRAY INDEX FOR LETTER W */ - private static final int LETTER_X = 23; /* ARRAY INDEX FOR LETTER X */ - private static final int LETTER_Y = 24; /* ARRAY INDEX FOR LETTER Y */ - private static final int LETTER_Z = 25; /* ARRAY INDEX FOR LETTER Z */ - private static final int MGRS_LETTERS = 3; /* NUMBER OF LETTERS IN MGRS */ + private static final int LETTER_A = 0; + /* ARRAY INDEX FOR LETTER A */ + private static final int LETTER_B = 1; + /* ARRAY INDEX FOR LETTER B */ + private static final int LETTER_C = 2; + /* ARRAY INDEX FOR LETTER C */ + private static final int LETTER_D = 3; + /* ARRAY INDEX FOR LETTER D */ + private static final int LETTER_E = 4; + /* ARRAY INDEX FOR LETTER E */ + private static final int LETTER_F = 5; + /* ARRAY INDEX FOR LETTER E */ + private static final int LETTER_G = 6; + /* ARRAY INDEX FOR LETTER H */ + private static final int LETTER_H = 7; + /* ARRAY INDEX FOR LETTER H */ + private static final int LETTER_I = 8; + /* ARRAY INDEX FOR LETTER I */ + private static final int LETTER_J = 9; + /* ARRAY INDEX FOR LETTER J */ + private static final int LETTER_K = 10; + /* ARRAY INDEX FOR LETTER J */ + private static final int LETTER_L = 11; + /* ARRAY INDEX FOR LETTER L */ + private static final int LETTER_M = 12; + /* ARRAY INDEX FOR LETTER M */ + private static final int LETTER_N = 13; + /* ARRAY INDEX FOR LETTER N */ + private static final int LETTER_O = 14; + /* ARRAY INDEX FOR LETTER O */ + private static final int LETTER_P = 15; + /* ARRAY INDEX FOR LETTER P */ + private static final int LETTER_Q = 16; + /* ARRAY INDEX FOR LETTER Q */ + private static final int LETTER_R = 17; + /* ARRAY INDEX FOR LETTER R */ + private static final int LETTER_S = 18; + /* ARRAY INDEX FOR LETTER S */ + private static final int LETTER_T = 19; + /* ARRAY INDEX FOR LETTER S */ + private static final int LETTER_U = 20; + /* ARRAY INDEX FOR LETTER U */ + private static final int LETTER_V = 21; + /* ARRAY INDEX FOR LETTER V */ + private static final int LETTER_W = 22; + /* ARRAY INDEX FOR LETTER W */ + private static final int LETTER_X = 23; + /* ARRAY INDEX FOR LETTER X */ + private static final int LETTER_Y = 24; + /* ARRAY INDEX FOR LETTER Y */ + private static final int LETTER_Z = 25; + /* ARRAY INDEX FOR LETTER Z */ + private static final int MGRS_LETTERS = 3; + /* NUMBER OF LETTERS IN MGRS */ private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; @@ -130,7 +156,7 @@ class MGRSCoordConverter {LETTER_E, 2800000.0, -56.0, -64.0, 2000000.0}, {LETTER_F, 3700000.0, -48.0, -56.0, 2000000.0}, {LETTER_G, 4600000.0, -40.0, -48.0, 4000000.0}, - {LETTER_H, 5500000.0, -32.0, -40.0, 4000000.0}, //smithjl last column to table + {LETTER_H, 5500000.0, -32.0, -40.0, 4000000.0}, //smithjl last column to table {LETTER_J, 6400000.0, -24.0, -32.0, 6000000.0}, {LETTER_K, 7300000.0, -16.0, -24.0, 6000000.0}, {LETTER_L, 8200000.0, -8.0, -16.0, 8000000.0}, @@ -146,8 +172,8 @@ class MGRSCoordConverter {LETTER_W, 7000000.0, 72.0, 64.0, 6000000.0}, {LETTER_X, 7900000.0, 84.5, 72.0, 6000000.0}}; - private class MGRSComponents - { + private class MGRSComponents { + private final int zone; private final int latitudeBand; private final int squareLetter1; @@ -157,8 +183,7 @@ private class MGRSComponents private final int precision; public MGRSComponents(int zone, int latitudeBand, int squareLetter1, int squareLetter2, - double easting, double northing, int precision) - { + double easting, double northing, int precision) { this.zone = zone; this.latitudeBand = latitudeBand; this.squareLetter1 = squareLetter1; @@ -168,22 +193,19 @@ public MGRSComponents(int zone, int latitudeBand, int squareLetter1, int squareL this.precision = precision; } - public String toString() - { - return "MGRS: " + zone + " " + - alphabet.charAt(latitudeBand) + " " + - alphabet.charAt(squareLetter1) + alphabet.charAt(squareLetter2) + " " + - easting + " " + - northing + " " + - "(" + precision + ")"; + public String toString() { + return "MGRS: " + zone + " " + + alphabet.charAt(latitudeBand) + " " + + alphabet.charAt(squareLetter1) + alphabet.charAt(squareLetter2) + " " + + easting + " " + + northing + " " + + "(" + precision + ")"; } } - MGRSCoordConverter(Globe globe) - { + MGRSCoordConverter(Globe globe) { this.globe = globe; - if (globe != null) - { + if (globe != null) { double a = globe.getEquatorialRadius(); double f = (globe.getEquatorialRadius() - globe.getPolarRadius()) / globe.getEquatorialRadius(); setMGRSParameters(a, f, MGRS_Ellipsoid_Code); @@ -194,22 +216,24 @@ public String toString() * The function setMGRSParameters receives the ellipsoid parameters and sets the corresponding state variables. If * any errors occur, the error code(s) are returned by the function, otherwise MGRS_NO_ERROR is returned. * - * @param mgrs_a Semi-major axis of ellipsoid in meters - * @param mgrs_f Flattening of ellipsoid + * @param mgrs_a Semi-major axis of ellipsoid in meters + * @param mgrs_f Flattening of ellipsoid * @param ellipsoidCode 2-letter code for ellipsoid * * @return error code */ - public long setMGRSParameters(double mgrs_a, double mgrs_f, String ellipsoidCode) - { - if (mgrs_a <= 0.0) + public long setMGRSParameters(double mgrs_a, double mgrs_f, String ellipsoidCode) { + if (mgrs_a <= 0.0) { return MGRS_A_ERROR; + } - if (mgrs_f == 0.0) + if (mgrs_f == 0.0) { return MGRS_INV_F_ERROR; + } double inv_f = 1 / mgrs_f; - if (inv_f < 250 || inv_f > 350) + if (inv_f < 250 || inv_f > 350) { return MGRS_INV_F_ERROR; + } MGRS_a = mgrs_a; MGRS_f = mgrs_f; @@ -218,77 +242,73 @@ public long setMGRSParameters(double mgrs_a, double mgrs_f, String ellipsoidCode return MGRS_NO_ERROR; } - /** @return Flattening of ellipsoid */ - public double getMGRS_f() - { + /** + * @return Flattening of ellipsoid + */ + public double getMGRS_f() { return MGRS_f; } - /** @return Semi-major axis of ellipsoid in meters */ - public double getMGRS_a() - { + /** + * @return Semi-major axis of ellipsoid in meters + */ + public double getMGRS_a() { return MGRS_a; } - /** @return Latitude band letter */ - private long getLastLetter() - { + /** + * @return Latitude band letter + */ + private long getLastLetter() { return lastLetter; } - /** @return 2-letter code for ellipsoid */ - public String getMGRS_Ellipsoid_Code() - { + /** + * @return 2-letter code for ellipsoid + */ + public String getMGRS_Ellipsoid_Code() { return MGRS_Ellipsoid_Code; } /** * The function ConvertMGRSToGeodetic converts an MGRS coordinate string to Geodetic (latitude and longitude) - * coordinates according to the current ellipsoid parameters. If any errors occur, the error code(s) are returned - * by the function, otherwise UTM_NO_ERROR is returned. + * coordinates according to the current ellipsoid parameters. If any errors occur, the error code(s) are returned by + * the function, otherwise UTM_NO_ERROR is returned. * * @param MGRSString MGRS coordinate string. * * @return the error code. */ - public long convertMGRSToGeodetic(String MGRSString) - { + public long convertMGRSToGeodetic(String MGRSString) { latitude = 0; longitude = 0; long error_code = checkZone(MGRSString); - if (error_code == MGRS_NO_ERROR) - { + if (error_code == MGRS_NO_ERROR) { UTMCoord UTM = convertMGRSToUTM(MGRSString); - if (UTM != null) - { + if (UTM != null) { latitude = UTM.getLatitude().radians; longitude = UTM.getLongitude().radians; - } - else + } else { error_code = MGRS_UTM_ERROR; - } - else if (error_code == MGRS_NOZONE_WARNING) - { + } + } else if (error_code == MGRS_NOZONE_WARNING) { // TODO: polar conversion UPSCoord UPS = convertMGRSToUPS(MGRSString); - if (UPS != null) - { + if (UPS != null) { latitude = UPS.getLatitude().radians; longitude = UPS.getLongitude().radians; - } - else + } else { error_code = MGRS_UPS_ERROR; + } } return (error_code); } - public double getLatitude() - { + public double getLatitude() { return latitude; } - public double getLongitude() - { + public double getLongitude() { return longitude; } @@ -300,8 +320,7 @@ public double getLongitude() * * @return the corresponding MGRSComponents or null. */ - private MGRSComponents breakMGRSString(String MGRSString) - { + private MGRSComponents breakMGRSString(String MGRSString) { int num_digits; int num_letters; int i = 0; @@ -314,82 +333,79 @@ private MGRSComponents breakMGRSString(String MGRSString) long northing = 0; int precision = 0; - while (i < MGRSString.length() && MGRSString.charAt(i) == ' ') - { - i++; /* skip any leading blanks */ + while (i < MGRSString.length() && MGRSString.charAt(i) == ' ') { + i++; + /* skip any leading blanks */ } j = i; - while (i < MGRSString.length() && Character.isDigit(MGRSString.charAt(i))) - { + while (i < MGRSString.length() && Character.isDigit(MGRSString.charAt(i))) { i++; } num_digits = i - j; - if (num_digits <= 2) - if (num_digits > 0) - { + if (num_digits <= 2) { + if (num_digits > 0) { /* get zone */ zone = Integer.parseInt(MGRSString.substring(j, i)); - if ((zone < 1) || (zone > 60)) + if ((zone < 1) || (zone > 60)) { error_code |= MGRS_STRING_ERROR; - } - else + } + } else { error_code |= MGRS_STRING_ERROR; + } + } j = i; - while (i < MGRSString.length() && Character.isLetter(MGRSString.charAt(i))) - { + while (i < MGRSString.length() && Character.isLetter(MGRSString.charAt(i))) { i++; } num_letters = i - j; - if (num_letters == 3) - { + if (num_letters == 3) { /* get letters */ letters[0] = alphabet.indexOf(Character.toUpperCase(MGRSString.charAt(j))); - if ((letters[0] == LETTER_I) || (letters[0] == LETTER_O)) + if ((letters[0] == LETTER_I) || (letters[0] == LETTER_O)) { error_code |= MGRS_STRING_ERROR; + } letters[1] = alphabet.indexOf(Character.toUpperCase(MGRSString.charAt(j + 1))); - if ((letters[1] == LETTER_I) || (letters[1] == LETTER_O)) + if ((letters[1] == LETTER_I) || (letters[1] == LETTER_O)) { error_code |= MGRS_STRING_ERROR; + } letters[2] = alphabet.indexOf(Character.toUpperCase(MGRSString.charAt(j + 2))); - if ((letters[2] == LETTER_I) || (letters[2] == LETTER_O)) + if ((letters[2] == LETTER_I) || (letters[2] == LETTER_O)) { error_code |= MGRS_STRING_ERROR; - } - else + } + } else { error_code |= MGRS_STRING_ERROR; + } j = i; - while (i < MGRSString.length() && Character.isDigit(MGRSString.charAt(i))) - { + while (i < MGRSString.length() && Character.isDigit(MGRSString.charAt(i))) { i++; } num_digits = i - j; - if ((num_digits <= 10) && (num_digits % 2 == 0)) - { + if ((num_digits <= 10) && (num_digits % 2 == 0)) { /* get easting, northing and precision */ int n; double multiplier; /* get easting & northing */ n = num_digits / 2; precision = n; - if (n > 0) - { + if (n > 0) { easting = Integer.parseInt(MGRSString.substring(j, j + n)); northing = Integer.parseInt(MGRSString.substring(j + n, j + n + n)); multiplier = Math.pow(10.0, 5 - n); easting *= multiplier; northing *= multiplier; - } - else - { + } else { easting = 0; northing = 0; } - } - else + } else { error_code |= MGRS_STRING_ERROR; + } last_error = error_code; - if (error_code == MGRS_NO_ERROR) + if (error_code == MGRS_NO_ERROR) { return new MGRSComponents(zone, letters[0], letters[1], letters[2], easting, northing, precision); + } return null; } @@ -402,28 +418,26 @@ private MGRSComponents breakMGRSString(String MGRSString) * * @return the error code. */ - private long checkZone(String MGRSString) - { + private long checkZone(String MGRSString) { int i = 0; int j = 0; int num_digits = 0; long error_code = MGRS_NO_ERROR; /* skip any leading blanks */ - while (i < MGRSString.length() && MGRSString.charAt(i) == ' ') - { + while (i < MGRSString.length() && MGRSString.charAt(i) == ' ') { i++; } j = i; - while (i < MGRSString.length() && Character.isDigit(MGRSString.charAt(i))) - { + while (i < MGRSString.length() && Character.isDigit(MGRSString.charAt(i))) { i++; } num_digits = i - j; - if (num_digits > 2) + if (num_digits > 2) { error_code |= MGRS_STRING_ERROR; - else if (num_digits <= 0) + } else if (num_digits <= 0) { error_code |= MGRS_NOZONE_WARNING; + } return error_code; } @@ -436,27 +450,21 @@ else if (num_digits <= 0) * * @return the error code. */ - private long getLatitudeBandMinNorthing(int letter) - { + private long getLatitudeBandMinNorthing(int letter) { long error_code = MGRS_NO_ERROR; - if ((letter >= LETTER_C) && (letter <= LETTER_H)) - { + if ((letter >= LETTER_C) && (letter <= LETTER_H)) { min_northing = latitudeBandConstants[letter - 2][1]; northing_offset = latitudeBandConstants[letter - 2][4]; //smithjl - } - else if ((letter >= LETTER_J) && (letter <= LETTER_N)) - { + } else if ((letter >= LETTER_J) && (letter <= LETTER_N)) { min_northing = latitudeBandConstants[letter - 3][1]; northing_offset = latitudeBandConstants[letter - 3][4]; //smithjl - } - else if ((letter >= LETTER_P) && (letter <= LETTER_X)) - { + } else if ((letter >= LETTER_P) && (letter <= LETTER_X)) { min_northing = latitudeBandConstants[letter - 4][1]; northing_offset = latitudeBandConstants[letter - 4][4]; //smithjl - } - else + } else { error_code |= MGRS_STRING_ERROR; + } return error_code; } @@ -468,44 +476,39 @@ else if ((letter >= LETTER_P) && (letter <= LETTER_X)) * * @return the error code. */ - private long getLatitudeRange(int letter) - { + private long getLatitudeRange(int letter) { long error_code = MGRS_NO_ERROR; - if ((letter >= LETTER_C) && (letter <= LETTER_H)) - { + if ((letter >= LETTER_C) && (letter <= LETTER_H)) { north = latitudeBandConstants[letter - 2][2] * DEG_TO_RAD; south = latitudeBandConstants[letter - 2][3] * DEG_TO_RAD; - } - else if ((letter >= LETTER_J) && (letter <= LETTER_N)) - { + } else if ((letter >= LETTER_J) && (letter <= LETTER_N)) { north = latitudeBandConstants[letter - 3][2] * DEG_TO_RAD; south = latitudeBandConstants[letter - 3][3] * DEG_TO_RAD; - } - else if ((letter >= LETTER_P) && (letter <= LETTER_X)) - { + } else if ((letter >= LETTER_P) && (letter <= LETTER_X)) { north = latitudeBandConstants[letter - 4][2] * DEG_TO_RAD; south = latitudeBandConstants[letter - 4][3] * DEG_TO_RAD; - } - else + } else { error_code |= MGRS_STRING_ERROR; + } return error_code; } /** * The function convertMGRSToUTM converts an MGRS coordinate string to UTM projection (zone, hemisphere, easting and - * northing) coordinates according to the current ellipsoid parameters. Updates last_error if any errors occured. + * northing) coordinates according to the current ellipsoid parameters. Updates last_error if any errors occured. * * @param MGRSString the MGRS coordinate string * * @return the corresponding UTMComponents or null. */ - private UTMCoord convertMGRSToUTM(String MGRSString) - { + private UTMCoord convertMGRSToUTM(String MGRSString) { double scaled_min_northing; - double grid_easting; /* Easting for 100,000 meter grid square */ - double grid_northing; /* Northing for 100,000 meter grid square */ + double grid_easting; + /* Easting for 100,000 meter grid square */ + double grid_northing; + /* Northing for 100,000 meter grid square */ double temp_grid_northing = 0.0; double fabs_grid_northing = 0.0; double latitude = 0.0; @@ -519,81 +522,80 @@ private UTMCoord convertMGRSToUTM(String MGRSString) UTMCoord UTM = null; MGRSComponents MGRS = breakMGRSString(MGRSString); - if (MGRS == null) + if (MGRS == null) { error_code |= MGRS_STRING_ERROR; - else - { - if (error_code == MGRS_NO_ERROR) - { - if ((MGRS.latitudeBand == LETTER_X) && ((MGRS.zone == 32) || (MGRS.zone == 34) || (MGRS.zone == 36))) + } else { + if (error_code == MGRS_NO_ERROR) { + if ((MGRS.latitudeBand == LETTER_X) && ((MGRS.zone == 32) || (MGRS.zone == 34) || (MGRS.zone == 36))) { error_code |= MGRS_STRING_ERROR; - else - { - if (MGRS.latitudeBand < LETTER_N) + } else { + if (MGRS.latitudeBand < LETTER_N) { hemisphere = AVKey.SOUTH; - else + } else { hemisphere = AVKey.NORTH; + } getGridValues(MGRS.zone); // Check that the second letter of the MGRS string is within // the range of valid second letter values // Also check that the third letter is valid - if ((MGRS.squareLetter1 < ltr2_low_value) || (MGRS.squareLetter1 > ltr2_high_value) || - (MGRS.squareLetter2 > LETTER_V)) + if ((MGRS.squareLetter1 < ltr2_low_value) || (MGRS.squareLetter1 > ltr2_high_value) + || (MGRS.squareLetter2 > LETTER_V)) { error_code |= MGRS_STRING_ERROR; + } - if (error_code == MGRS_NO_ERROR) - { - grid_northing = - (double) (MGRS.squareLetter2) * ONEHT; // smithjl commented out + false_northing; + if (error_code == MGRS_NO_ERROR) { + grid_northing + = (double) (MGRS.squareLetter2) * ONEHT; // smithjl commented out + false_northing; grid_easting = (double) ((MGRS.squareLetter1) - ltr2_low_value + 1) * ONEHT; - if ((ltr2_low_value == LETTER_J) && (MGRS.squareLetter1 > LETTER_O)) + if ((ltr2_low_value == LETTER_J) && (MGRS.squareLetter1 > LETTER_O)) { grid_easting = grid_easting - ONEHT; + } - if (MGRS.squareLetter2 > LETTER_O) + if (MGRS.squareLetter2 > LETTER_O) { grid_northing = grid_northing - ONEHT; + } - if (MGRS.squareLetter2 > LETTER_I) + if (MGRS.squareLetter2 > LETTER_I) { grid_northing = grid_northing - ONEHT; + } - if (grid_northing >= TWOMIL) + if (grid_northing >= TWOMIL) { grid_northing = grid_northing - TWOMIL; + } error_code = getLatitudeBandMinNorthing(MGRS.latitudeBand); - if (error_code == MGRS_NO_ERROR) - { + if (error_code == MGRS_NO_ERROR) { /*smithjl Deleted code here and added this*/ grid_northing = grid_northing - false_northing; - if (grid_northing < 0.0) + if (grid_northing < 0.0) { grid_northing += TWOMIL; + } grid_northing += northing_offset; - if (grid_northing < min_northing) + if (grid_northing < min_northing) { grid_northing += TWOMIL; + } /* smithjl End of added code */ - easting = grid_easting + MGRS.easting; northing = grid_northing + MGRS.northing; - try - { + try { UTM = UTMCoord.fromUTM(MGRS.zone, hemisphere, easting, northing, globe); latitude = UTM.getLatitude().radians; divisor = Math.pow(10.0, MGRS.precision); error_code = getLatitudeRange(MGRS.latitudeBand); - if (error_code == MGRS_NO_ERROR) - { + if (error_code == MGRS_NO_ERROR) { if (!(((south - DEG_TO_RAD / divisor) <= latitude) - && (latitude <= (north + DEG_TO_RAD / divisor)))) + && (latitude <= (north + DEG_TO_RAD / divisor)))) { error_code |= MGRS_LAT_WARNING; + } } - } - catch (Exception e) - { + } catch (Exception e) { error_code = MGRS_UTM_ERROR; } } @@ -603,25 +605,27 @@ private UTMCoord convertMGRSToUTM(String MGRSString) } last_error = error_code; - if (error_code == MGRS_NO_ERROR || error_code == MGRS_LAT_WARNING) + if (error_code == MGRS_NO_ERROR || error_code == MGRS_LAT_WARNING) { return UTM; + } return null; - } /* Convert_MGRS_To_UTM */ + } + + /* Convert_MGRS_To_UTM */ /** * The function convertGeodeticToMGRS converts Geodetic (latitude and longitude) coordinates to an MGRS coordinate - * string, according to the current ellipsoid parameters. If any errors occur, the error code(s) are returned by - * the function, otherwise MGRS_NO_ERROR is returned. + * string, according to the current ellipsoid parameters. If any errors occur, the error code(s) are returned by the + * function, otherwise MGRS_NO_ERROR is returned. * - * @param latitude Latitude in radians + * @param latitude Latitude in radians * @param longitude Longitude in radian * @param precision Precision level of MGRS string * * @return error code */ - public long convertGeodeticToMGRS(double latitude, double longitude, int precision) - { + public long convertGeodeticToMGRS(double latitude, double longitude, int precision) { String Hemisphere = AVKey.NORTH; double Easting = 0.0; double Northing = 0.0; @@ -629,47 +633,38 @@ public long convertGeodeticToMGRS(double latitude, double longitude, int precisi MGRSString = ""; long error_code = MGRS_NO_ERROR; - if ((latitude < -PI_OVER_2) || (latitude > PI_OVER_2)) - { /* Latitude out of range */ + if ((latitude < -PI_OVER_2) || (latitude > PI_OVER_2)) { + /* Latitude out of range */ error_code = MGRS_LAT_ERROR; } - if ((longitude < -PI) || (longitude > (2 * PI))) - { /* Longitude out of range */ + if ((longitude < -PI) || (longitude > (2 * PI))) { + /* Longitude out of range */ error_code = MGRS_LON_ERROR; } - if ((precision < 0) || (precision > MAX_PRECISION)) + if ((precision < 0) || (precision > MAX_PRECISION)) { error_code = MGRS_PRECISION_ERROR; + } - if (error_code == MGRS_NO_ERROR) - { - if ((latitude < MIN_UTM_LAT) || (latitude > MAX_UTM_LAT)) - { + if (error_code == MGRS_NO_ERROR) { + if ((latitude < MIN_UTM_LAT) || (latitude > MAX_UTM_LAT)) { // TODO: polar - try - { - UPSCoord UPS = - UPSCoord.fromLatLon(Angle.fromRadians(latitude), Angle.fromRadians(longitude), globe); + try { + UPSCoord UPS + = UPSCoord.fromLatLon(Angle.fromRadians(latitude), Angle.fromRadians(longitude), globe); error_code |= convertUPSToMGRS(UPS.getHemisphere(), UPS.getEasting(), - UPS.getNorthing(), precision); - } - catch (Exception e) - { + UPS.getNorthing(), precision); + } catch (Exception e) { error_code = MGRS_UPS_ERROR; } - } - else - { - try - { - UTMCoord UTM = - UTMCoord.fromLatLon(Angle.fromRadians(latitude), Angle.fromRadians(longitude), globe); + } else { + try { + UTMCoord UTM + = UTMCoord.fromLatLon(Angle.fromRadians(latitude), Angle.fromRadians(longitude), globe); error_code |= convertUTMToMGRS(UTM.getZone(), latitude, UTM.getEasting(), - UTM.getNorthing(), precision); - } - catch (Exception e) - { + UTM.getNorthing(), precision); + } catch (Exception e) { error_code = MGRS_UTM_ERROR; } } @@ -678,58 +673,67 @@ public long convertGeodeticToMGRS(double latitude, double longitude, int precisi return error_code; } - /** @return converted MGRS string */ - public String getMGRSString() - { + /** + * @return converted MGRS string + */ + public String getMGRSString() { return MGRSString; } /** * The function Convert_UPS_To_MGRS converts UPS (hemisphere, easting, and northing) coordinates to an MGRS - * coordinate string according to the current ellipsoid parameters. If any errors occur, the error code(s) are + * coordinate string according to the current ellipsoid parameters. If any errors occur, the error code(s) are * returned by the function, otherwise MGRS_NO_ERROR is returned. * * @param Hemisphere Hemisphere either, {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param Easting Easting/X in meters - * @param Northing Northing/Y in meters - * @param Precision Precision level of MGRS string + * @param Easting Easting/X in meters + * @param Northing Northing/Y in meters + * @param Precision Precision level of MGRS string * * @return error value */ - private long convertUPSToMGRS(String Hemisphere, Double Easting, Double Northing, long Precision) - { - double false_easting; /* False easting for 2nd letter */ - double false_northing; /* False northing for 3rd letter */ - double grid_easting; /* Easting used to derive 2nd letter of MGRS */ - double grid_northing; /* Northing used to derive 3rd letter of MGRS */ - int ltr2_low_value; /* 2nd letter range - low number */ - long[] letters = new long[MGRS_LETTERS]; /* Number location of 3 letters in alphabet */ + private long convertUPSToMGRS(String Hemisphere, Double Easting, Double Northing, long Precision) { + double false_easting; + /* False easting for 2nd letter */ + double false_northing; + /* False northing for 3rd letter */ + double grid_easting; + /* Easting used to derive 2nd letter of MGRS */ + double grid_northing; + /* Northing used to derive 3rd letter of MGRS */ + int ltr2_low_value; + /* 2nd letter range - low number */ + long[] letters = new long[MGRS_LETTERS]; + /* Number location of 3 letters in alphabet */ double divisor; int index; long error_code = MGRS_NO_ERROR; - if (!AVKey.NORTH.equals(Hemisphere) && !AVKey.SOUTH.equals(Hemisphere)) + if (!AVKey.NORTH.equals(Hemisphere) && !AVKey.SOUTH.equals(Hemisphere)) { error_code |= MGRS_HEMISPHERE_ERROR; - if ((Easting < MIN_EAST_NORTH) || (Easting > MAX_EAST_NORTH)) + } + if ((Easting < MIN_EAST_NORTH) || (Easting > MAX_EAST_NORTH)) { error_code |= MGRS_EASTING_ERROR; - if ((Northing < MIN_EAST_NORTH) || (Northing > MAX_EAST_NORTH)) + } + if ((Northing < MIN_EAST_NORTH) || (Northing > MAX_EAST_NORTH)) { error_code |= MGRS_NORTHING_ERROR; - if ((Precision < 0) || (Precision > MAX_PRECISION)) + } + if ((Precision < 0) || (Precision > MAX_PRECISION)) { error_code |= MGRS_PRECISION_ERROR; + } - if (error_code == MGRS_NO_ERROR) - { + if (error_code == MGRS_NO_ERROR) { divisor = Math.pow(10.0, (5 - Precision)); Easting = roundMGRS(Easting / divisor) * divisor; Northing = roundMGRS(Northing / divisor) * divisor; - if (AVKey.NORTH.equals(Hemisphere)) - { - if (Easting >= TWOMIL) + if (AVKey.NORTH.equals(Hemisphere)) { + if (Easting >= TWOMIL) { letters[0] = LETTER_Z; - else + } else { letters[0] = LETTER_Y; + } index = (int) letters[0] - 22; // ltr2_low_value = UPS_Constant_Table.get(index).ltr2_low_value; @@ -738,13 +742,13 @@ private long convertUPSToMGRS(String Hemisphere, Double Easting, Double Northing ltr2_low_value = (int) upsConstants[index][1]; false_easting = (double) upsConstants[index][4]; false_northing = (double) upsConstants[index][5]; - } - else // AVKey.SOUTH.equals(Hemisphere) + } else // AVKey.SOUTH.equals(Hemisphere) { - if (Easting >= TWOMIL) + if (Easting >= TWOMIL) { letters[0] = LETTER_B; - else + } else { letters[0] = LETTER_A; + } // ltr2_low_value = UPS_Constant_Table.get((int) letters[0]).ltr2_low_value; // false_easting = UPS_Constant_Table.get((int) letters[0]).false_easting; @@ -758,34 +762,38 @@ private long convertUPSToMGRS(String Hemisphere, Double Easting, Double Northing grid_northing = grid_northing - false_northing; letters[2] = (int) (grid_northing / ONEHT); - if (letters[2] > LETTER_H) + if (letters[2] > LETTER_H) { letters[2] = letters[2] + 1; + } - if (letters[2] > LETTER_N) + if (letters[2] > LETTER_N) { letters[2] = letters[2] + 1; + } grid_easting = Easting; grid_easting = grid_easting - false_easting; letters[1] = (int) ltr2_low_value + ((int) (grid_easting / ONEHT)); - if (Easting < TWOMIL) - { - if (letters[1] > LETTER_L) + if (Easting < TWOMIL) { + if (letters[1] > LETTER_L) { letters[1] = letters[1] + 3; + } - if (letters[1] > LETTER_U) + if (letters[1] > LETTER_U) { letters[1] = letters[1] + 2; - } - else - { - if (letters[1] > LETTER_C) + } + } else { + if (letters[1] > LETTER_C) { letters[1] = letters[1] + 2; + } - if (letters[1] > LETTER_H) + if (letters[1] > LETTER_H) { letters[1] = letters[1] + 1; + } - if (letters[1] > LETTER_L) + if (letters[1] > LETTER_L) { letters[1] = letters[1] + 3; + } } makeMGRSString(0, letters, Easting, Northing, Precision); @@ -796,19 +804,21 @@ private long convertUPSToMGRS(String Hemisphere, Double Easting, Double Northing /** * The function UTM_To_MGRS calculates an MGRS coordinate string based on the zone, latitude, easting and northing. * - * @param Zone Zone number - * @param Latitude Latitude in radians - * @param Easting Easting - * @param Northing Northing + * @param Zone Zone number + * @param Latitude Latitude in radians + * @param Easting Easting + * @param Northing Northing * @param Precision Precision * * @return error code */ - private long convertUTMToMGRS(long Zone, double Latitude, double Easting, double Northing, long Precision) - { - double grid_easting; /* Easting used to derive 2nd letter of MGRS */ - double grid_northing; /* Northing used to derive 3rd letter of MGRS */ - long[] letters = new long[MGRS_LETTERS]; /* Number location of 3 letters in alphabet */ + private long convertUTMToMGRS(long Zone, double Latitude, double Easting, double Northing, long Precision) { + double grid_easting; + /* Easting used to derive 2nd letter of MGRS */ + double grid_northing; + /* Northing used to derive 3rd letter of MGRS */ + long[] letters = new long[MGRS_LETTERS]; + /* Number location of 3 letters in alphabet */ double divisor; long error_code; @@ -822,35 +832,39 @@ private long convertUTMToMGRS(long Zone, double Latitude, double Easting, double error_code = getLatitudeLetter(Latitude); letters[0] = getLastLetter(); - if (error_code == MGRS_NO_ERROR) - { + if (error_code == MGRS_NO_ERROR) { grid_northing = Northing; - if (grid_northing == 1.e7) + if (grid_northing == 1.e7) { grid_northing = grid_northing - 1.0; + } - while (grid_northing >= TWOMIL) - { + while (grid_northing >= TWOMIL) { grid_northing = grid_northing - TWOMIL; } grid_northing = grid_northing + false_northing; //smithjl - if (grid_northing >= TWOMIL) //smithjl + if (grid_northing >= TWOMIL) //smithjl + { grid_northing = grid_northing - TWOMIL; //smithjl - + } letters[2] = (long) (grid_northing / ONEHT); - if (letters[2] > LETTER_H) + if (letters[2] > LETTER_H) { letters[2] = letters[2] + 1; + } - if (letters[2] > LETTER_N) + if (letters[2] > LETTER_N) { letters[2] = letters[2] + 1; + } grid_easting = Easting; - if (((letters[0] == LETTER_V) && (Zone == 31)) && (grid_easting == 500000.0)) + if (((letters[0] == LETTER_V) && (Zone == 31)) && (grid_easting == 500000.0)) { grid_easting = grid_easting - 1.0; /* SUBTRACT 1 METER */ + } letters[1] = ltr2_low_value + ((long) (grid_easting / ONEHT) - 1); - if ((ltr2_low_value == LETTER_J) && (letters[1] > LETTER_N)) + if ((ltr2_low_value == LETTER_J) && (letters[1] > LETTER_N)) { letters[1] = letters[1] + 1; + } makeMGRSString(Zone, letters, Easting, Northing, Precision); } @@ -862,56 +876,53 @@ private long convertUTMToMGRS(long Zone, double Latitude, double Easting, double * on the set number of the utm zone. It also sets the false northing using a value of A for the second letter of * the grid square, based on the grid pattern and set number of the utm zone. *

        - * Key values that are set in this function include: ltr2_low_value, ltr2_high_value, and false_northing. + * Key values that are set in this function include: ltr2_low_value, ltr2_high_value, and false_northing. * * @param zone Zone number */ - private void getGridValues(long zone) - { - long set_number; /* Set number (1-6) based on UTM zone number */ - long aa_pattern; /* Pattern based on ellipsoid code */ + private void getGridValues(long zone) { + long set_number; + /* Set number (1-6) based on UTM zone number */ + long aa_pattern; + /* Pattern based on ellipsoid code */ set_number = zone % 6; - if (set_number == 0) + if (set_number == 0) { set_number = 6; + } - if (MGRS_Ellipsoid_Code.compareTo(CLARKE_1866) == 0 || MGRS_Ellipsoid_Code.compareTo(CLARKE_1880) == 0 || - MGRS_Ellipsoid_Code.compareTo(BESSEL_1841) == 0 || MGRS_Ellipsoid_Code.compareTo(BESSEL_1841_NAMIBIA) == 0) + if (MGRS_Ellipsoid_Code.compareTo(CLARKE_1866) == 0 || MGRS_Ellipsoid_Code.compareTo(CLARKE_1880) == 0 + || MGRS_Ellipsoid_Code.compareTo(BESSEL_1841) == 0 || MGRS_Ellipsoid_Code.compareTo(BESSEL_1841_NAMIBIA) == 0) { aa_pattern = 0L; - else + } else { aa_pattern = 1L; + } - if ((set_number == 1) || (set_number == 4)) - { + if ((set_number == 1) || (set_number == 4)) { ltr2_low_value = (long) LETTER_A; ltr2_high_value = (long) LETTER_H; - } - else if ((set_number == 2) || (set_number == 5)) - { + } else if ((set_number == 2) || (set_number == 5)) { ltr2_low_value = (long) LETTER_J; ltr2_high_value = (long) LETTER_R; - } - else if ((set_number == 3) || (set_number == 6)) - { + } else if ((set_number == 3) || (set_number == 6)) { ltr2_low_value = (long) LETTER_S; ltr2_high_value = (long) LETTER_Z; } /* False northing at A for second letter of grid square */ - if (aa_pattern == 1L) - { - if ((set_number % 2) == 0) + if (aa_pattern == 1L) { + if ((set_number % 2) == 0) { false_northing = 500000.0; //smithjl was 1500000 - else + } else { false_northing = 0.0; - } - else - { - if ((set_number % 2) == 0) + } + } else { + if ((set_number % 2) == 0) { false_northing = 1500000.0; //smithjl was 500000 - else + } else { false_northing = 1000000.00; + } } } @@ -923,22 +934,20 @@ else if ((set_number == 3) || (set_number == 6)) * * @return error code */ - private long getLatitudeLetter(double latitude) - { + private long getLatitudeLetter(double latitude) { double temp; long error_code = MGRS_NO_ERROR; double lat_deg = latitude * RAD_TO_DEG; - if (lat_deg >= 72 && lat_deg < 84.5) + if (lat_deg >= 72 && lat_deg < 84.5) { lastLetter = (long) LETTER_X; - else if (lat_deg > -80.5 && lat_deg < 72) - { + } else if (lat_deg > -80.5 && lat_deg < 72) { temp = ((latitude + (80.0 * DEG_TO_RAD)) / (8.0 * DEG_TO_RAD)) + 1.0e-12; // lastLetter = Latitude_Band_Table.get((int) temp).letter; lastLetter = (long) latitudeBandConstants[(int) temp][0]; - } - else + } else { error_code |= MGRS_LAT_ERROR; + } return error_code; } @@ -951,88 +960,86 @@ else if (lat_deg > -80.5 && lat_deg < 72) * * @return rounded double value */ - private double roundMGRS(double value) - { + private double roundMGRS(double value) { double ivalue = Math.floor(value); long ival; double fraction = value - ivalue; // double fraction = modf (value, &ivalue); ival = (long) (ivalue); - if ((fraction > 0.5) || ((fraction == 0.5) && (ival % 2 == 1))) + if ((fraction > 0.5) || ((fraction == 0.5) && (ival % 2 == 1))) { ival++; + } return (double) ival; } /** * The function Make_MGRS_String constructs an MGRS string from its component parts. * - * @param Zone UTM Zone - * @param Letters MGRS coordinate string letters - * @param Easting Easting value - * @param Northing Northing value + * @param Zone UTM Zone + * @param Letters MGRS coordinate string letters + * @param Easting Easting value + * @param Northing Northing value * @param Precision Precision level of MGRS string * * @return error code */ - private long makeMGRSString(long Zone, long[] Letters, double Easting, double Northing, long Precision) - { + private long makeMGRSString(long Zone, long[] Letters, double Easting, double Northing, long Precision) { int j; double divisor; long east; long north; long error_code = MGRS_NO_ERROR; - if (Zone != 0) + if (Zone != 0) { MGRSString = String.format("%02d", Zone); - else + } else { MGRSString = " "; + } - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { - if (Letters[j] < 0 || Letters[j] > 26) + if (Letters[j] < 0 || Letters[j] > 26) { return MGRS_ZONE_ERROR; // TODO: Find out why this happens + } MGRSString = MGRSString + alphabet.charAt((int) Letters[j]); } divisor = Math.pow(10.0, (5 - Precision)); Easting = Easting % 100000.0; - if (Easting >= 99999.5) + if (Easting >= 99999.5) { Easting = 99999.0; + } east = (long) (Easting / divisor); // Here we need to only use the number requesting in the precision Integer iEast = (int) east; String sEast = iEast.toString(); - if (sEast.length() > Precision) + if (sEast.length() > Precision) { sEast = sEast.substring(0, (int) Precision - 1); - else - { + } else { int i; int length = sEast.length(); - for (i = 0; i < Precision - length; i++) - { + for (i = 0; i < Precision - length; i++) { sEast = "0" + sEast; } } MGRSString = MGRSString + " " + sEast; Northing = Northing % 100000.0; - if (Northing >= 99999.5) + if (Northing >= 99999.5) { Northing = 99999.0; + } north = (long) (Northing / divisor); Integer iNorth = (int) north; String sNorth = iNorth.toString(); - if (sNorth.length() > Precision) + if (sNorth.length() > Precision) { sNorth = sNorth.substring(0, (int) Precision - 1); - else - { + } else { int i; int length = sNorth.length(); - for (i = 0; i < Precision - length; i++) - { + for (i = 0; i < Precision - length; i++) { sNorth = "0" + sNorth; } } @@ -1046,8 +1053,7 @@ private long makeMGRSString(long Zone, long[] Letters, double Easting, double No * * @return the last error code. */ - public long getError() - { + public long getError() { return last_error; } @@ -1060,15 +1066,21 @@ public long getError() * * @return a corresponding {@link UPSCoord} instance. */ - private UPSCoord convertMGRSToUPS(String MGRS) - { - long ltr2_high_value; /* 2nd letter range - high number */ - long ltr3_high_value; /* 3rd letter range - high number (UPS) */ - long ltr2_low_value; /* 2nd letter range - low number */ - double false_easting; /* False easting for 2nd letter */ - double false_northing; /* False northing for 3rd letter */ - double grid_easting; /* easting for 100,000 meter grid square */ - double grid_northing; /* northing for 100,000 meter grid square */ + private UPSCoord convertMGRSToUPS(String MGRS) { + long ltr2_high_value; + /* 2nd letter range - high number */ + long ltr3_high_value; + /* 3rd letter range - high number (UPS) */ + long ltr2_low_value; + /* 2nd letter range - low number */ + double false_easting; + /* False easting for 2nd letter */ + double false_northing; + /* False northing for 3rd letter */ + double grid_easting; + /* easting for 100,000 meter grid square */ + double grid_northing; + /* northing for 100,000 meter grid square */ int index = 0; long error_code = MGRS_NO_ERROR; @@ -1076,19 +1088,19 @@ private UPSCoord convertMGRSToUPS(String MGRS) double easting, northing; MGRSComponents mgrs = breakMGRSString(MGRS); - if (mgrs == null) + if (mgrs == null) { error_code = this.last_error; + } - if (mgrs != null && mgrs.zone > 0) + if (mgrs != null && mgrs.zone > 0) { error_code |= MGRS_STRING_ERROR; + } - if (error_code == MGRS_NO_ERROR) - { + if (error_code == MGRS_NO_ERROR) { easting = mgrs.easting; northing = mgrs.northing; - if (mgrs.latitudeBand >= LETTER_Y) - { + if (mgrs.latitudeBand >= LETTER_Y) { hemisphere = AVKey.NORTH; index = mgrs.latitudeBand - 22; @@ -1097,9 +1109,7 @@ private UPSCoord convertMGRSToUPS(String MGRS) ltr3_high_value = upsConstants[index][3]; //.ltr3_high_value; false_easting = upsConstants[index][4]; //.false_easting; false_northing = upsConstants[index][5]; //.false_northing; - } - else - { + } else { hemisphere = AVKey.SOUTH; ltr2_low_value = upsConstants[mgrs.latitudeBand][12]; //.ltr2_low_value; @@ -1112,41 +1122,45 @@ private UPSCoord convertMGRSToUPS(String MGRS) // Check that the second letter of the MGRS string is within // the range of valid second letter values // Also check that the third letter is valid - if ((mgrs.squareLetter1 < ltr2_low_value) || (mgrs.squareLetter1 > ltr2_high_value) || - ((mgrs.squareLetter1 == LETTER_D) || (mgrs.squareLetter1 == LETTER_E) || - (mgrs.squareLetter1 == LETTER_M) || (mgrs.squareLetter1 == LETTER_N) || - (mgrs.squareLetter1 == LETTER_V) || (mgrs.squareLetter1 == LETTER_W)) || - (mgrs.squareLetter2 > ltr3_high_value)) + if ((mgrs.squareLetter1 < ltr2_low_value) || (mgrs.squareLetter1 > ltr2_high_value) + || ((mgrs.squareLetter1 == LETTER_D) || (mgrs.squareLetter1 == LETTER_E) + || (mgrs.squareLetter1 == LETTER_M) || (mgrs.squareLetter1 == LETTER_N) + || (mgrs.squareLetter1 == LETTER_V) || (mgrs.squareLetter1 == LETTER_W)) + || (mgrs.squareLetter2 > ltr3_high_value)) { error_code = MGRS_STRING_ERROR; + } - if (error_code == MGRS_NO_ERROR) - { + if (error_code == MGRS_NO_ERROR) { grid_northing = (double) mgrs.squareLetter2 * ONEHT + false_northing; - if (mgrs.squareLetter2 > LETTER_I) + if (mgrs.squareLetter2 > LETTER_I) { grid_northing = grid_northing - ONEHT; + } - if (mgrs.squareLetter2 > LETTER_O) + if (mgrs.squareLetter2 > LETTER_O) { grid_northing = grid_northing - ONEHT; + } grid_easting = (double) ((mgrs.squareLetter1) - ltr2_low_value) * ONEHT + false_easting; - if (ltr2_low_value != LETTER_A) - { - if (mgrs.squareLetter1 > LETTER_L) + if (ltr2_low_value != LETTER_A) { + if (mgrs.squareLetter1 > LETTER_L) { grid_easting = grid_easting - 300000.0; + } - if (mgrs.squareLetter1 > LETTER_U) + if (mgrs.squareLetter1 > LETTER_U) { grid_easting = grid_easting - 200000.0; - } - else - { - if (mgrs.squareLetter1 > LETTER_C) + } + } else { + if (mgrs.squareLetter1 > LETTER_C) { grid_easting = grid_easting - 200000.0; + } - if (mgrs.squareLetter1 > LETTER_I) + if (mgrs.squareLetter1 > LETTER_I) { grid_easting = grid_easting - ONEHT; + } - if (mgrs.squareLetter1 > LETTER_L) + if (mgrs.squareLetter1 > LETTER_L) { grid_easting = grid_easting - 300000.0; + } } easting = grid_easting + easting; diff --git a/src/gov/nasa/worldwind/geom/coords/PolarCoordConverter.java b/src/gov/nasa/worldwind/geom/coords/PolarCoordConverter.java index 3e7b14e74d..723ef543c4 100644 --- a/src/gov/nasa/worldwind/geom/coords/PolarCoordConverter.java +++ b/src/gov/nasa/worldwind/geom/coords/PolarCoordConverter.java @@ -3,8 +3,7 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - -/***************************************************************************/ +/** ************************************************************************ */ /* RSC IDENTIFIER: POLAR STEREOGRAPHIC * * @@ -91,7 +90,6 @@ * * */ - package gov.nasa.worldwind.geom.coords; /** @@ -100,8 +98,8 @@ * @author Garrett Headley - Feb 12, 2007 4:48:11 PM * @version $Id: PolarCoordConverter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PolarCoordConverter -{ +public class PolarCoordConverter { + private static final long POLAR_NO_ERROR = 0x0000; private static final long POLAR_LAT_ERROR = 0x0001; private static final long POLAR_LON_ERROR = 0x0002; @@ -119,24 +117,35 @@ public class PolarCoordConverter private static final double TWO_PI = 2.0 * PI; /* Ellipsoid Parameters, default to WGS 84 */ - private double Polar_a = 6378137.0; /* Semi-major axis of ellipsoid in meters */ - private double Polar_f = 1 / 298.257223563; /* Flattening of ellipsoid */ - private double es = 0.08181919084262188000; /* Eccentricity of ellipsoid */ - private double es_OVER_2 = .040909595421311; /* es / 2.0 */ - private double Southern_Hemisphere = 0; /* Flag variable */ + private double Polar_a = 6378137.0; + /* Semi-major axis of ellipsoid in meters */ + private double Polar_f = 1 / 298.257223563; + /* Flattening of ellipsoid */ + private double es = 0.08181919084262188000; + /* Eccentricity of ellipsoid */ + private double es_OVER_2 = .040909595421311; + /* es / 2.0 */ + private double Southern_Hemisphere = 0; + /* Flag variable */ private double mc = 1.0; private double tc = 1.0; private double e4 = 1.0033565552493; - private double Polar_a_mc = 6378137.0; /* Polar_a * mc */ - private double two_Polar_a = 12756274.0; /* 2.0 * Polar_a */ - - /* Polar Stereographic projection Parameters */ - private double Polar_Origin_Lat = ((PI * 90) / 180); /* Latitude of origin in radians */ - private double Polar_Origin_Long = 0.0; /* Longitude of origin in radians */ - private double Polar_False_Easting = 0.0; /* False easting in meters */ - private double Polar_False_Northing = 0.0; /* False northing in meters */ - - /* Maximum variance for easting and northing values for WGS 84. */ + private double Polar_a_mc = 6378137.0; + /* Polar_a * mc */ + private double two_Polar_a = 12756274.0; + /* 2.0 * Polar_a */ + + /* Polar Stereographic projection Parameters */ + private double Polar_Origin_Lat = ((PI * 90) / 180); + /* Latitude of origin in radians */ + private double Polar_Origin_Long = 0.0; + /* Longitude of origin in radians */ + private double Polar_False_Easting = 0.0; + /* False easting in meters */ + private double Polar_False_Northing = 0.0; + /* False northing in meters */ + + /* Maximum variance for easting and northing values for WGS 84. */ private double Polar_Delta_Easting = 12713601.0; private double Polar_Delta_Northing = 12713601.0; @@ -145,27 +154,24 @@ public class PolarCoordConverter private double Latitude; private double Longitude; - PolarCoordConverter() - { + PolarCoordConverter() { } /** * The function setPolarStereographicParameters receives the ellipsoid parameters and Polar Stereograpic projection - * parameters as inputs, and sets the corresponding state variables. If any errors occur, error code(s) are - * returned by the function, otherwise POLAR_NO_ERROR is returned. + * parameters as inputs, and sets the corresponding state variables. If any errors occur, error code(s) are returned + * by the function, otherwise POLAR_NO_ERROR is returned. * - * @param a Semi-major axis of ellipsoid, in meters - * @param f Flattening of ellipsoid - * @param Latitude_of_True_Scale Latitude of true scale, in radians + * @param a Semi-major axis of ellipsoid, in meters + * @param f Flattening of ellipsoid + * @param Latitude_of_True_Scale Latitude of true scale, in radians * @param Longitude_Down_from_Pole Longitude down from pole, in radians - * @param False_Easting Easting (X) at center of projection, in meters - * @param False_Northing Northing (Y) at center of projection, in meters + * @param False_Easting Easting (X) at center of projection, in meters + * @param False_Northing Northing (Y) at center of projection, in meters * @return error code */ public long setPolarStereographicParameters(double a, double f, double Latitude_of_True_Scale, - double Longitude_Down_from_Pole, double False_Easting, double False_Northing) - - { + double Longitude_Down_from_Pole, double False_Easting, double False_Northing) { double es2; double slat, clat; double essin; @@ -175,39 +181,38 @@ public long setPolarStereographicParameters(double a, double f, double Latitude_ final double epsilon = 1.0e-2; long Error_Code = POLAR_NO_ERROR; - if (a <= 0.0) - { /* Semi-major axis must be greater than zero */ + if (a <= 0.0) { + /* Semi-major axis must be greater than zero */ Error_Code |= POLAR_A_ERROR; } - if ((inv_f < 250) || (inv_f > 350)) - { /* Inverse flattening must be between 250 and 350 */ + if ((inv_f < 250) || (inv_f > 350)) { + /* Inverse flattening must be between 250 and 350 */ Error_Code |= POLAR_INV_F_ERROR; } - if ((Latitude_of_True_Scale < -PI_OVER_2) || (Latitude_of_True_Scale > PI_OVER_2)) - { /* Origin Latitude out of range */ + if ((Latitude_of_True_Scale < -PI_OVER_2) || (Latitude_of_True_Scale > PI_OVER_2)) { + /* Origin Latitude out of range */ Error_Code |= POLAR_ORIGIN_LAT_ERROR; } - if ((Longitude_Down_from_Pole < -PI) || (Longitude_Down_from_Pole > TWO_PI)) - { /* Origin Longitude out of range */ + if ((Longitude_Down_from_Pole < -PI) || (Longitude_Down_from_Pole > TWO_PI)) { + /* Origin Longitude out of range */ Error_Code |= POLAR_ORIGIN_LON_ERROR; } - if (Error_Code == POLAR_NO_ERROR) - { /* no errors */ + if (Error_Code == POLAR_NO_ERROR) { + /* no errors */ Polar_a = a; two_Polar_a = 2.0 * Polar_a; Polar_f = f; - if (Longitude_Down_from_Pole > PI) + if (Longitude_Down_from_Pole > PI) { Longitude_Down_from_Pole -= TWO_PI; - if (Latitude_of_True_Scale < 0) - { + } + if (Latitude_of_True_Scale < 0) { Southern_Hemisphere = 1; Polar_Origin_Lat = -Latitude_of_True_Scale; Polar_Origin_Long = -Longitude_Down_from_Pole; - } else - { + } else { Southern_Hemisphere = 0; Polar_Origin_Lat = Latitude_of_True_Scale; Polar_Origin_Long = Longitude_Down_from_Pole; @@ -219,8 +224,7 @@ public long setPolarStereographicParameters(double a, double f, double Latitude_ es = Math.sqrt(es2); es_OVER_2 = es / 2.0; - if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) - { + if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) { slat = Math.sin(Polar_Origin_Lat); essin = es * slat; pow_es = Math.pow((1.0 - essin) / (1.0 + essin), es_OVER_2); @@ -228,8 +232,7 @@ public long setPolarStereographicParameters(double a, double f, double Latitude_ mc = clat / Math.sqrt(1.0 - essin * essin); Polar_a_mc = Polar_a * mc; tc = Math.tan(PI_Over_4 - Polar_Origin_Lat / 2.0) / pow_es; - } else - { + } else { one_PLUS_es = 1.0 + es; one_MINUS_es = 1.0 - es; e4 = Math.sqrt(Math.pow(one_PLUS_es, one_PLUS_es) * Math.pow(one_MINUS_es, one_MINUS_es)); @@ -252,12 +255,11 @@ public long setPolarStereographicParameters(double a, double f, double Latitude_ * Stereographic projection parameters. If any errors occur, error code(s) are returned by the function, otherwise * POLAR_NO_ERROR is returned. * - * @param Latitude latitude, in radians + * @param Latitude latitude, in radians * @param Longitude Longitude, in radians * @return error code */ - public long convertGeodeticToPolarStereographic(double Latitude, double Longitude) - { + public long convertGeodeticToPolarStereographic(double Latitude, double Longitude) { double dlam; double slat; double essin; @@ -266,44 +268,39 @@ public long convertGeodeticToPolarStereographic(double Latitude, double Longitud double pow_es; long Error_Code = POLAR_NO_ERROR; - if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) - { /* Latitude out of range */ + if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) { + /* Latitude out of range */ Error_Code |= POLAR_LAT_ERROR; } - if ((Latitude < 0) && (Southern_Hemisphere == 0)) - { /* Latitude and Origin Latitude in different hemispheres */ + if ((Latitude < 0) && (Southern_Hemisphere == 0)) { + /* Latitude and Origin Latitude in different hemispheres */ Error_Code |= POLAR_LAT_ERROR; } - if ((Latitude > 0) && (Southern_Hemisphere == 1)) - { /* Latitude and Origin Latitude in different hemispheres */ + if ((Latitude > 0) && (Southern_Hemisphere == 1)) { + /* Latitude and Origin Latitude in different hemispheres */ Error_Code |= POLAR_LAT_ERROR; } - if ((Longitude < -PI) || (Longitude > TWO_PI)) - { /* Longitude out of range */ + if ((Longitude < -PI) || (Longitude > TWO_PI)) { + /* Longitude out of range */ Error_Code |= POLAR_LON_ERROR; } - if (Error_Code == POLAR_NO_ERROR) - { /* no errors */ + if (Error_Code == POLAR_NO_ERROR) { + /* no errors */ - if (Math.abs(Math.abs(Latitude) - PI_OVER_2) < 1.0e-10) - { + if (Math.abs(Math.abs(Latitude) - PI_OVER_2) < 1.0e-10) { Easting = 0.0; Northing = 0.0; - } else - { - if (Southern_Hemisphere != 0) - { + } else { + if (Southern_Hemisphere != 0) { Longitude *= -1.0; Latitude *= -1.0; } dlam = Longitude - Polar_Origin_Long; - if (dlam > PI) - { + if (dlam > PI) { dlam -= TWO_PI; } - if (dlam < -PI) - { + if (dlam < -PI) { dlam += TWO_PI; } slat = Math.sin(Latitude); @@ -311,49 +308,44 @@ public long convertGeodeticToPolarStereographic(double Latitude, double Longitud pow_es = Math.pow((1.0 - essin) / (1.0 + essin), es_OVER_2); t = Math.tan(PI_Over_4 - Latitude / 2.0) / pow_es; - if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) + if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) { rho = Polar_a_mc * t / tc; - else + } else { rho = two_Polar_a * t / e4; + } - - if (Southern_Hemisphere != 0) - { + if (Southern_Hemisphere != 0) { Easting = -(rho * Math.sin(dlam) - Polar_False_Easting); //Easting *= -1.0; Northing = rho * Math.cos(dlam) + Polar_False_Northing; - } else + } else { Easting = rho * Math.sin(dlam) + Polar_False_Easting; - Northing = -rho * Math.cos(dlam) + Polar_False_Northing; + } + Northing = -rho * Math.cos(dlam) + Polar_False_Northing; } } return (Error_Code); } - public double getEasting() - { + public double getEasting() { return Easting; } - public double getNorthing() - { + public double getNorthing() { return Northing; } /** - * The function Convert_Polar_Stereographic_To_Geodetic converts Polar - * Stereographic coordinates (easting and northing) to geodetic - * coordinates (latitude and longitude) according to the current ellipsoid - * and Polar Stereographic projection Parameters. If any errors occur, the - * code(s) are returned by the function, otherwise POLAR_NO_ERROR - * is returned. + * The function Convert_Polar_Stereographic_To_Geodetic converts Polar Stereographic coordinates (easting and + * northing) to geodetic coordinates (latitude and longitude) according to the current ellipsoid and Polar + * Stereographic projection Parameters. If any errors occur, the code(s) are returned by the function, otherwise + * POLAR_NO_ERROR is returned. * - * @param Easting Easting (X), in meters - * @param Northing Northing (Y), in meters - * @return error code + * @param Easting Easting (X), in meters + * @param Northing Northing (Y), in meters + * @return error code */ - public long convertPolarStereographicToGeodetic (double Easting, double Northing) - { + public long convertPolarStereographicToGeodetic(double Easting, double Northing) { double dy = 0, dx = 0; double rho = 0; double t; @@ -368,17 +360,16 @@ public long convertPolarStereographicToGeodetic (double Easting, double Northing double min_northing = Polar_False_Northing - Polar_Delta_Northing; double max_northing = Polar_False_Northing + Polar_Delta_Northing; - if (Easting > max_easting || Easting < min_easting) - { /* Easting out of range */ + if (Easting > max_easting || Easting < min_easting) { + /* Easting out of range */ Error_Code |= POLAR_EASTING_ERROR; } - if (Northing > max_northing || Northing < min_northing) - { /* Northing out of range */ + if (Northing > max_northing || Northing < min_northing) { + /* Northing out of range */ Error_Code |= POLAR_NORTHING_ERROR; } - if (Error_Code == POLAR_NO_ERROR) - { + if (Error_Code == POLAR_NO_ERROR) { dy = Northing - Polar_False_Northing; dx = Easting - Polar_False_Easting; @@ -387,86 +378,80 @@ public long convertPolarStereographicToGeodetic (double Easting, double Northing delta_radius = Math.sqrt(Polar_Delta_Easting * Polar_Delta_Easting + Polar_Delta_Northing * Polar_Delta_Northing); - if(rho > delta_radius) - { /* Point is outside of projection area */ + if (rho > delta_radius) { + /* Point is outside of projection area */ Error_Code |= POLAR_RADIUS_ERROR; } } - if (Error_Code == POLAR_NO_ERROR) - { /* no errors */ - if ((dy == 0.0) && (dx == 0.0)) - { + if (Error_Code == POLAR_NO_ERROR) { + /* no errors */ + if ((dy == 0.0) && (dx == 0.0)) { Latitude = PI_OVER_2; Longitude = Polar_Origin_Long; - } - else - { - if (Southern_Hemisphere != 0) - { + } else { + if (Southern_Hemisphere != 0) { dy *= -1.0; dx *= -1.0; } - if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) + if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) { t = rho * tc / (Polar_a_mc); - else + } else { t = rho * e4 / (two_Polar_a); + } PHI = PI_OVER_2 - 2.0 * Math.atan(t); - while (Math.abs(PHI - tempPHI) > 1.0e-10) - { + while (Math.abs(PHI - tempPHI) > 1.0e-10) { tempPHI = PHI; sin_PHI = Math.sin(PHI); - essin = es * sin_PHI; + essin = es * sin_PHI; pow_es = Math.pow((1.0 - essin) / (1.0 + essin), es_OVER_2); PHI = PI_OVER_2 - 2.0 * Math.atan(t * pow_es); } Latitude = PHI; Longitude = Polar_Origin_Long + Math.atan2(dx, -dy); - if (Longitude > PI) + if (Longitude > PI) { Longitude -= TWO_PI; - else if (Longitude < -PI) + } else if (Longitude < -PI) { Longitude += TWO_PI; + } - - if (Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ + if (Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ { Latitude = PI_OVER_2; - else if (Latitude < -PI_OVER_2) + } else if (Latitude < -PI_OVER_2) { Latitude = -PI_OVER_2; + } - if (Longitude > PI) /* force distorted values to 180, -180 degrees */ + if (Longitude > PI) /* force distorted values to 180, -180 degrees */ { Longitude = PI; - else if (Longitude < -PI) + } else if (Longitude < -PI) { Longitude = -PI; + } } - if (Southern_Hemisphere != 0) - { + if (Southern_Hemisphere != 0) { Latitude *= -1.0; Longitude *= -1.0; } } return (Error_Code); - } + } /** * @return Latitude in radians. */ - public double getLatitude() - { + public double getLatitude() { return Latitude; } /** * @return Longitude in radians. */ - public double getLongitude() - { + public double getLongitude() { return Longitude; } } - diff --git a/src/gov/nasa/worldwind/geom/coords/TMCoord.java b/src/gov/nasa/worldwind/geom/coords/TMCoord.java index b5b0aa9c5e..91c9964466 100644 --- a/src/gov/nasa/worldwind/geom/coords/TMCoord.java +++ b/src/gov/nasa/worldwind/geom/coords/TMCoord.java @@ -10,15 +10,14 @@ import gov.nasa.worldwind.util.Logging; /** - * This class holds a set of Transverse Mercator coordinates along with the - * corresponding latitude and longitude. + * This class holds a set of Transverse Mercator coordinates along with the corresponding latitude and longitude. * * @author Patrick Murris * @version $Id: TMCoord.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TMCoordConverter */ -public class TMCoord -{ +public class TMCoord { + private final Angle latitude; private final Angle longitude; private final Angle originLatitude; @@ -30,60 +29,55 @@ public class TMCoord private final double northing; /** - * Create a set of Transverse Mercator coordinates from a pair of latitude and longitude, - * for the given Globe and projection parameters. + * Create a set of Transverse Mercator coordinates from a pair of latitude and longitude, for the given + * Globe and projection parameters. * * @param latitude the latitude Angle. * @param longitude the longitude Angle. * @param globe the Globe - can be null (will use WGS84). - * @param a semi-major ellipsoid radius. If this and argument f are non-null and globe is null, will use the specfied a and f. - * @param f ellipsoid flattening. If this and argument a are non-null and globe is null, will use the specfied a and f. + * @param a semi-major ellipsoid radius. If this and argument f are non-null and globe is null, will use the + * specfied a and f. + * @param f ellipsoid flattening. If this and argument a are non-null and globe is null, will use the specfied a and + * f. * @param originLatitude the origin latitude Angle. * @param centralMeridian the central meridian longitude Angle. * @param falseEasting easting value at the center of the projection in meters. * @param falseNorthing northing value at the center of the projection in meters. * @param scale scaling factor. * @return the corresponding TMCoord. - * @throws IllegalArgumentException if latitude or longitude is null, - * or the conversion to TM coordinates fails. If the globe is null conversion will default - * to using WGS84. + * @throws IllegalArgumentException if latitude or longitude is null, or the conversion to + * TM coordinates fails. If the globe is null conversion will default to using WGS84. */ public static TMCoord fromLatLon(Angle latitude, Angle longitude, Globe globe, Double a, Double f, - Angle originLatitude, Angle centralMeridian, - double falseEasting, double falseNorthing, - double scale) - { - if (latitude == null || longitude == null) - { + Angle originLatitude, Angle centralMeridian, + double falseEasting, double falseNorthing, + double scale) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (originLatitude == null || centralMeridian == null) - { + if (originLatitude == null || centralMeridian == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } final TMCoordConverter converter = new TMCoordConverter(); - if (globe != null) - { + if (globe != null) { a = globe.getEquatorialRadius(); f = (globe.getEquatorialRadius() - globe.getPolarRadius()) / globe.getEquatorialRadius(); - } - else if (a == null || f == null) - { + } else if (a == null || f == null) { a = converter.getA(); f = converter.getF(); } long err = converter.setTransverseMercatorParameters(a, f, originLatitude.radians, centralMeridian.radians, falseEasting, falseNorthing, scale); - if (err == TMCoordConverter.TRANMERC_NO_ERROR) + if (err == TMCoordConverter.TRANMERC_NO_ERROR) { err = converter.convertGeodeticToTransverseMercator(latitude.radians, longitude.radians); + } - if (err != TMCoordConverter.TRANMERC_NO_ERROR && err != TMCoordConverter.TRANMERC_LON_WARNING) - { + if (err != TMCoordConverter.TRANMERC_NO_ERROR && err != TMCoordConverter.TRANMERC_LON_WARNING) { String message = Logging.getMessage("Coord.TMConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -94,8 +88,8 @@ else if (a == null || f == null) } /** - * Create a set of Transverse Mercator coordinates for the given Globe, - * easting, northing and projection parameters. + * Create a set of Transverse Mercator coordinates for the given Globe, easting, northing and + * projection parameters. * * @param easting the easting distance value in meters. * @param northing the northing distance value in meters. @@ -106,17 +100,14 @@ else if (a == null || f == null) * @param falseNorthing northing value at the center of the projection in meters. * @param scale scaling factor. * @return the corresponding TMCoord. - * @throws IllegalArgumentException if originLatitude or centralMeridian - * is null, or the conversion to geodetic coordinates fails. If the globe is null conversion will default - * to using WGS84. + * @throws IllegalArgumentException if originLatitude or centralMeridian is null, or the + * conversion to geodetic coordinates fails. If the globe is null conversion will default to using WGS84. */ public static TMCoord fromTM(double easting, double northing, Globe globe, - Angle originLatitude, Angle centralMeridian, - double falseEasting, double falseNorthing, - double scale) - { - if (originLatitude == null || centralMeridian == null) - { + Angle originLatitude, Angle centralMeridian, + double falseEasting, double falseNorthing, + double scale) { + if (originLatitude == null || centralMeridian == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -124,23 +115,20 @@ public static TMCoord fromTM(double easting, double northing, Globe globe, final TMCoordConverter converter = new TMCoordConverter(); double a, f; - if (globe != null) - { + if (globe != null) { a = globe.getEquatorialRadius(); f = (globe.getEquatorialRadius() - globe.getPolarRadius()) / globe.getEquatorialRadius(); - } - else - { + } else { a = converter.getA(); f = converter.getF(); } long err = converter.setTransverseMercatorParameters(a, f, originLatitude.radians, centralMeridian.radians, falseEasting, falseNorthing, scale); - if (err == TMCoordConverter.TRANMERC_NO_ERROR) + if (err == TMCoordConverter.TRANMERC_NO_ERROR) { err = converter.convertTransverseMercatorToGeodetic(easting, northing); + } - if (err != TMCoordConverter.TRANMERC_NO_ERROR && err != TMCoordConverter.TRANMERC_LON_WARNING) - { + if (err != TMCoordConverter.TRANMERC_NO_ERROR && err != TMCoordConverter.TRANMERC_LON_WARNING) { String message = Logging.getMessage("Coord.TMConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -162,22 +150,19 @@ public static TMCoord fromTM(double easting, double northing, Globe globe, * @param falseEasting easting value at the center of the projection in meters. * @param falseNorthing northing value at the center of the projection in meters. * @param scale scaling factor. - * @throws IllegalArgumentException if latitude, longitude, originLatitude - * or centralMeridian is null. + * @throws IllegalArgumentException if latitude, longitude, originLatitude or + * centralMeridian is null. */ public TMCoord(Angle latitude, Angle longitude, double easting, double northing, - Angle originLatitude, Angle centralMeridian, - double falseEasting, double falseNorthing, - double scale) - { - if (latitude == null || longitude == null) - { + Angle originLatitude, Angle centralMeridian, + double falseEasting, double falseNorthing, + double scale) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (originLatitude == null || centralMeridian == null) - { + if (originLatitude == null || centralMeridian == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -194,48 +179,39 @@ public TMCoord(Angle latitude, Angle longitude, double easting, double northing, this.scale = scale; } - public Angle getLatitude() - { + public Angle getLatitude() { return this.latitude; } - public Angle getLongitude() - { + public Angle getLongitude() { return this.longitude; } - public Angle getOriginLatitude() - { + public Angle getOriginLatitude() { return this.originLatitude; } - public Angle getCentralMeridian() - { + public Angle getCentralMeridian() { return this.centralMeridian; } - public double getFalseEasting() - { + public double getFalseEasting() { return this.falseEasting; } - public double getFalseNorthing() - { + public double getFalseNorthing() { return this.falseNorthing; } - public double getScale() - { + public double getScale() { return this.scale; } - public double getEasting() - { + public double getEasting() { return this.easting; } - public double getNorthing() - { + public double getNorthing() { return this.northing; } diff --git a/src/gov/nasa/worldwind/geom/coords/TMCoordConverter.java b/src/gov/nasa/worldwind/geom/coords/TMCoordConverter.java index d48d3a523c..b42f3c9e99 100644 --- a/src/gov/nasa/worldwind/geom/coords/TMCoordConverter.java +++ b/src/gov/nasa/worldwind/geom/coords/TMCoordConverter.java @@ -12,14 +12,13 @@ * @version $Id: TMCoordConverter.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TMCoord, UTMCoordConverter, MGRSCoordConverter */ - /** * Ported to Java from the NGA GeoTrans code tranmerc.c and tranmerc.h * * @author Garrett Headley, Patrick Murris */ -class TMCoordConverter -{ +class TMCoordConverter { + public final static int TRANMERC_NO_ERROR = 0x0000; private final static int TRANMERC_LAT_ERROR = 0x0001; private final static int TRANMERC_LON_ERROR = 0x0002; @@ -32,27 +31,40 @@ class TMCoordConverter private final static int TRANMERC_SCALE_FACTOR_ERROR = 0x0100; public final static int TRANMERC_LON_WARNING = 0x0200; - private final static double PI = 3.14159265358979323; /* PI */ - public final static double PI_OVER = (PI / 2.0); /* PI over 2 */ - private final static double MAX_LAT = ((PI * 89.99) / 180.0); /* 90 degrees in radians */ - private final static double MAX_DELTA_LONG = ((PI * 90) / 180.0); /* 90 degrees in radians */ + private final static double PI = 3.14159265358979323; + /* PI */ + public final static double PI_OVER = (PI / 2.0); + /* PI over 2 */ + private final static double MAX_LAT = ((PI * 89.99) / 180.0); + /* 90 degrees in radians */ + private final static double MAX_DELTA_LONG = ((PI * 90) / 180.0); + /* 90 degrees in radians */ private final static double MIN_SCALE_FACTOR = 0.3; private final static double MAX_SCALE_FACTOR = 3.0; /* Ellipsoid Parameters, default to WGS 84 */ - private double TranMerc_a = 6378137.0; /* Semi-major axis of ellipsoid i meters */ - private double TranMerc_f = 1 / 298.257223563; /* Flattening of ellipsoid */ - private double TranMerc_es = 0.0066943799901413800; /* Eccentricity (0.08181919084262188000) squared */ - private double TranMerc_ebs = 0.0067394967565869; /* Second Eccentricity squared */ - - /* Transverse_Mercator projection Parameters */ - private double TranMerc_Origin_Lat = 0.0; /* Latitude of origin in radians */ - private double TranMerc_Origin_Long = 0.0; /* Longitude of origin in radians */ - private double TranMerc_False_Northing = 0.0; /* False northing in meters */ - private double TranMerc_False_Easting = 0.0; /* False easting in meters */ - private double TranMerc_Scale_Factor = 1.0; /* Scale factor */ - - /* Isometeric to geodetic latitude parameters, default to WGS 84 */ + private double TranMerc_a = 6378137.0; + /* Semi-major axis of ellipsoid i meters */ + private double TranMerc_f = 1 / 298.257223563; + /* Flattening of ellipsoid */ + private double TranMerc_es = 0.0066943799901413800; + /* Eccentricity (0.08181919084262188000) squared */ + private double TranMerc_ebs = 0.0067394967565869; + /* Second Eccentricity squared */ + + /* Transverse_Mercator projection Parameters */ + private double TranMerc_Origin_Lat = 0.0; + /* Latitude of origin in radians */ + private double TranMerc_Origin_Long = 0.0; + /* Longitude of origin in radians */ + private double TranMerc_False_Northing = 0.0; + /* False northing in meters */ + private double TranMerc_False_Easting = 0.0; + /* False easting in meters */ + private double TranMerc_Scale_Factor = 1.0; + /* Scale factor */ + + /* Isometeric to geodetic latitude parameters, default to WGS 84 */ private double TranMerc_ap = 6367449.1458008; private double TranMerc_bp = 16038.508696861; private double TranMerc_cp = 16.832613334334; @@ -68,17 +80,14 @@ class TMCoordConverter private double Longitude; private double Latitude; - TMCoordConverter() - { + TMCoordConverter() { } - public double getA() - { + public double getA() { return TranMerc_a; } - public double getF() - { + public double getF() { return TranMerc_f; } @@ -87,51 +96,51 @@ public double getF() * projection parameters as inputs, and sets the corresponding state variables. If any errors occur, the error * code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is returned. * - * @param a Semi-major axis of ellipsoid, in meters - * @param f Flattening of ellipsoid - * @param Origin_Latitude Latitude in radians at the origin of the projection + * @param a Semi-major axis of ellipsoid, in meters + * @param f Flattening of ellipsoid + * @param Origin_Latitude Latitude in radians at the origin of the projection * @param Central_Meridian Longitude in radians at the center of the projection - * @param False_Easting Easting/X at the center of the projection - * @param False_Northing Northing/Y at the center of the projection - * @param Scale_Factor Projection scale factor + * @param False_Easting Easting/X at the center of the projection + * @param False_Northing Northing/Y at the center of the projection + * @param Scale_Factor Projection scale factor * * @return error code */ public long setTransverseMercatorParameters(double a, double f, double Origin_Latitude, - double Central_Meridian, - double False_Easting, double False_Northing, double Scale_Factor) - { - double tn; /* True Meridianal distance constant */ + double Central_Meridian, + double False_Easting, double False_Northing, double Scale_Factor) { + double tn; + /* True Meridianal distance constant */ double tn2; double tn3; double tn4; double tn5; - double TranMerc_b; /* Semi-minor axis of ellipsoid, in meters */ + double TranMerc_b; + /* Semi-minor axis of ellipsoid, in meters */ double inv_f = 1 / f; long Error_Code = TRANMERC_NO_ERROR; - if (a <= 0.0) - { /* Semi-major axis must be greater than zero */ + if (a <= 0.0) { + /* Semi-major axis must be greater than zero */ Error_Code |= TRANMERC_A_ERROR; } - if ((inv_f < 250) || (inv_f > 350)) - { /* Inverse flattening must be between 250 and 350 */ + if ((inv_f < 250) || (inv_f > 350)) { + /* Inverse flattening must be between 250 and 350 */ Error_Code |= TRANMERC_INV_F_ERROR; } - if ((Origin_Latitude < -MAX_LAT) || (Origin_Latitude > MAX_LAT)) - { /* origin latitude out of range */ + if ((Origin_Latitude < -MAX_LAT) || (Origin_Latitude > MAX_LAT)) { + /* origin latitude out of range */ Error_Code |= TRANMERC_ORIGIN_LAT_ERROR; } - if ((Central_Meridian < -PI) || (Central_Meridian > (2 * PI))) - { /* origin longitude out of range */ + if ((Central_Meridian < -PI) || (Central_Meridian > (2 * PI))) { + /* origin longitude out of range */ Error_Code |= TRANMERC_CENT_MER_ERROR; } - if ((Scale_Factor < MIN_SCALE_FACTOR) || (Scale_Factor > MAX_SCALE_FACTOR)) - { + if ((Scale_Factor < MIN_SCALE_FACTOR) || (Scale_Factor > MAX_SCALE_FACTOR)) { Error_Code |= TRANMERC_SCALE_FACTOR_ERROR; } - if (Error_Code == TRANMERC_NO_ERROR) - { /* no errors */ + if (Error_Code == TRANMERC_NO_ERROR) { + /* no errors */ TranMerc_a = a; TranMerc_f = f; TranMerc_Origin_Lat = 0; @@ -154,9 +163,9 @@ public long setTransverseMercatorParameters(double a, double f, double Origin_La tn5 = tn4 * tn; TranMerc_ap = TranMerc_a * (1.e0 - tn + 5.e0 * (tn2 - tn3) / 4.e0 - + 81.e0 * (tn4 - tn5) / 64.e0); + + 81.e0 * (tn4 - tn5) / 64.e0); TranMerc_bp = 3.e0 * TranMerc_a * (tn - tn2 + 7.e0 * (tn3 - tn4) - / 8.e0 + 55.e0 * tn5 / 64.e0) / 2.e0; + / 8.e0 + 55.e0 * tn5 / 64.e0) / 2.e0; TranMerc_cp = 15.e0 * TranMerc_a * (tn2 - tn3 + 3.e0 * (tn4 - tn5) / 4.e0) / 16.0; TranMerc_dp = 35.e0 * TranMerc_a * (tn3 - tn4 + 11.e0 * tn5 / 16.e0) / 48.e0; TranMerc_ep = 315.e0 * TranMerc_a * (tn4 - tn5) / 512.e0; @@ -170,8 +179,9 @@ public long setTransverseMercatorParameters(double a, double f, double Origin_La TranMerc_Delta_Easting = getEasting(); TranMerc_Origin_Lat = Origin_Latitude; - if (Central_Meridian > PI) + if (Central_Meridian > PI) { Central_Meridian -= (2 * PI); + } TranMerc_Origin_Long = Central_Meridian; TranMerc_False_Northing = False_Northing; TranMerc_False_Easting = False_Easting; @@ -183,88 +193,110 @@ public long setTransverseMercatorParameters(double a, double f, double Origin_La /** * The function Convert_Geodetic_To_Transverse_Mercator converts geodetic (latitude and longitude) coordinates to * Transverse Mercator projection (easting and northing) coordinates, according to the current ellipsoid and - * Transverse Mercator projection coordinates. If any errors occur, the error code(s) are returned by the function, + * Transverse Mercator projection coordinates. If any errors occur, the error code(s) are returned by the function, * otherwise TRANMERC_NO_ERROR is returned. * - * @param Latitude Latitude in radians + * @param Latitude Latitude in radians * @param Longitude Longitude in radians * * @return error code */ - public long convertGeodeticToTransverseMercator(double Latitude, double Longitude) - { - double c; /* Cosine of latitude */ + public long convertGeodeticToTransverseMercator(double Latitude, double Longitude) { + double c; + /* Cosine of latitude */ double c2; double c3; double c5; double c7; - double dlam; /* Delta longitude - Difference in Longitude */ - double eta; /* constant - TranMerc_ebs *c *c */ + double dlam; + /* Delta longitude - Difference in Longitude */ + double eta; + /* constant - TranMerc_ebs *c *c */ double eta2; double eta3; double eta4; - double s; /* Sine of latitude */ - double sn; /* Radius of curvature in the prime vertical */ - double t; /* Tangent of latitude */ + double s; + /* Sine of latitude */ + double sn; + /* Radius of curvature in the prime vertical */ + double t; + /* Tangent of latitude */ double tan2; double tan3; double tan4; double tan5; double tan6; - double t1; /* Term in coordinate conversion formula - GP to Y */ - double t2; /* Term in coordinate conversion formula - GP to Y */ - double t3; /* Term in coordinate conversion formula - GP to Y */ - double t4; /* Term in coordinate conversion formula - GP to Y */ - double t5; /* Term in coordinate conversion formula - GP to Y */ - double t6; /* Term in coordinate conversion formula - GP to Y */ - double t7; /* Term in coordinate conversion formula - GP to Y */ - double t8; /* Term in coordinate conversion formula - GP to Y */ - double t9; /* Term in coordinate conversion formula - GP to Y */ - double tmd; /* True Meridional distance */ - double tmdo; /* True Meridional distance for latitude of origin */ + double t1; + /* Term in coordinate conversion formula - GP to Y */ + double t2; + /* Term in coordinate conversion formula - GP to Y */ + double t3; + /* Term in coordinate conversion formula - GP to Y */ + double t4; + /* Term in coordinate conversion formula - GP to Y */ + double t5; + /* Term in coordinate conversion formula - GP to Y */ + double t6; + /* Term in coordinate conversion formula - GP to Y */ + double t7; + /* Term in coordinate conversion formula - GP to Y */ + double t8; + /* Term in coordinate conversion formula - GP to Y */ + double t9; + /* Term in coordinate conversion formula - GP to Y */ + double tmd; + /* True Meridional distance */ + double tmdo; + /* True Meridional distance for latitude of origin */ long Error_Code = TRANMERC_NO_ERROR; double temp_Origin; double temp_Long; - if ((Latitude < -MAX_LAT) || (Latitude > MAX_LAT)) - { /* Latitude out of range */ + if ((Latitude < -MAX_LAT) || (Latitude > MAX_LAT)) { + /* Latitude out of range */ Error_Code |= TRANMERC_LAT_ERROR; } - if (Longitude > PI) + if (Longitude > PI) { Longitude -= (2 * PI); + } if ((Longitude < (TranMerc_Origin_Long - MAX_DELTA_LONG)) - || (Longitude > (TranMerc_Origin_Long + MAX_DELTA_LONG))) - { - if (Longitude < 0) + || (Longitude > (TranMerc_Origin_Long + MAX_DELTA_LONG))) { + if (Longitude < 0) { temp_Long = Longitude + 2 * PI; - else + } else { temp_Long = Longitude; - if (TranMerc_Origin_Long < 0) + } + if (TranMerc_Origin_Long < 0) { temp_Origin = TranMerc_Origin_Long + 2 * PI; - else + } else { temp_Origin = TranMerc_Origin_Long; + } if ((temp_Long < (temp_Origin - MAX_DELTA_LONG)) - || (temp_Long > (temp_Origin + MAX_DELTA_LONG))) + || (temp_Long > (temp_Origin + MAX_DELTA_LONG))) { Error_Code |= TRANMERC_LON_ERROR; + } } - if (Error_Code == TRANMERC_NO_ERROR) - { /* no errors */ - /* + if (Error_Code == TRANMERC_NO_ERROR) { + /* no errors */ + /* * Delta Longitude */ dlam = Longitude - TranMerc_Origin_Long; - if (Math.abs(dlam) > (9.0 * PI / 180)) - { /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian */ + if (Math.abs(dlam) > (9.0 * PI / 180)) { + /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian */ Error_Code |= TRANMERC_LON_WARNING; } - if (dlam > PI) + if (dlam > PI) { dlam -= (2 * PI); - if (dlam < -PI) + } + if (dlam < -PI) { dlam += (2 * PI); - if (Math.abs(dlam) < 2.e-10) + } + if (Math.abs(dlam) < 2.e-10) { dlam = 0.0; + } s = Math.sin(Latitude); c = Math.cos(Latitude); @@ -290,153 +322,172 @@ public long convertGeodeticToTransverseMercator(double Latitude, double Longitud /* True Meridianal Distances */ // tmd = SPHTMD(Latitude); tmd = TranMerc_ap * Latitude - - TranMerc_bp * Math.sin(2.0 * Latitude) - + TranMerc_cp * Math.sin(4.0 * Latitude) - - TranMerc_dp * Math.sin(6.0 * Latitude) - + TranMerc_ep * Math.sin(8.0 * Latitude); + - TranMerc_bp * Math.sin(2.0 * Latitude) + + TranMerc_cp * Math.sin(4.0 * Latitude) + - TranMerc_dp * Math.sin(6.0 * Latitude) + + TranMerc_ep * Math.sin(8.0 * Latitude); /* Origin */ // tmdo = SPHTMD (TranMerc_Origin_Lat); tmdo = TranMerc_ap * TranMerc_Origin_Lat - - TranMerc_bp * Math.sin(2.0 * TranMerc_Origin_Lat) - + TranMerc_cp * Math.sin(4.0 * TranMerc_Origin_Lat) - - TranMerc_dp * Math.sin(6.0 * TranMerc_Origin_Lat) - + TranMerc_ep * Math.sin(8.0 * TranMerc_Origin_Lat); + - TranMerc_bp * Math.sin(2.0 * TranMerc_Origin_Lat) + + TranMerc_cp * Math.sin(4.0 * TranMerc_Origin_Lat) + - TranMerc_dp * Math.sin(6.0 * TranMerc_Origin_Lat) + + TranMerc_ep * Math.sin(8.0 * TranMerc_Origin_Lat); /* northing */ t1 = (tmd - tmdo) * TranMerc_Scale_Factor; t2 = sn * s * c * TranMerc_Scale_Factor / 2.e0; t3 = sn * s * c3 * TranMerc_Scale_Factor * (5.e0 - tan2 + 9.e0 * eta - + 4.e0 * eta2) / 24.e0; + + 4.e0 * eta2) / 24.e0; t4 = sn * s * c5 * TranMerc_Scale_Factor * (61.e0 - 58.e0 * tan2 - + tan4 + 270.e0 * eta - 330.e0 * tan2 * eta + 445.e0 * eta2 - + 324.e0 * eta3 - 680.e0 * tan2 * eta2 + 88.e0 * eta4 - - 600.e0 * tan2 * eta3 - 192.e0 * tan2 * eta4) / 720.e0; + + tan4 + 270.e0 * eta - 330.e0 * tan2 * eta + 445.e0 * eta2 + + 324.e0 * eta3 - 680.e0 * tan2 * eta2 + 88.e0 * eta4 + - 600.e0 * tan2 * eta3 - 192.e0 * tan2 * eta4) / 720.e0; - t5 = sn * s * c7 * TranMerc_Scale_Factor * (1385.e0 - 3111.e0 * - tan2 + 543.e0 * tan4 - tan6) / 40320.e0; + t5 = sn * s * c7 * TranMerc_Scale_Factor * (1385.e0 - 3111.e0 + * tan2 + 543.e0 * tan4 - tan6) / 40320.e0; Northing = TranMerc_False_Northing + t1 + Math.pow(dlam, 2.e0) * t2 - + Math.pow(dlam, 4.e0) * t3 + Math.pow(dlam, 6.e0) * t4 - + Math.pow(dlam, 8.e0) * t5; + + Math.pow(dlam, 4.e0) * t3 + Math.pow(dlam, 6.e0) * t4 + + Math.pow(dlam, 8.e0) * t5; /* Easting */ t6 = sn * c * TranMerc_Scale_Factor; t7 = sn * c3 * TranMerc_Scale_Factor * (1.e0 - tan2 + eta) / 6.e0; t8 = sn * c5 * TranMerc_Scale_Factor * (5.e0 - 18.e0 * tan2 + tan4 - + 14.e0 * eta - 58.e0 * tan2 * eta + 13.e0 * eta2 + 4.e0 * eta3 - - 64.e0 * tan2 * eta2 - 24.e0 * tan2 * eta3) / 120.e0; + + 14.e0 * eta - 58.e0 * tan2 * eta + 13.e0 * eta2 + 4.e0 * eta3 + - 64.e0 * tan2 * eta2 - 24.e0 * tan2 * eta3) / 120.e0; t9 = sn * c7 * TranMerc_Scale_Factor * (61.e0 - 479.e0 * tan2 - + 179.e0 * tan4 - tan6) / 5040.e0; + + 179.e0 * tan4 - tan6) / 5040.e0; Easting = TranMerc_False_Easting + dlam * t6 + Math.pow(dlam, 3.e0) * t7 - + Math.pow(dlam, 5.e0) * t8 + Math.pow(dlam, 7.e0) * t9; + + Math.pow(dlam, 5.e0) * t8 + Math.pow(dlam, 7.e0) * t9; } return (Error_Code); } - /** @return Easting/X at the center of the projection */ - public double getEasting() - { + /** + * @return Easting/X at the center of the projection + */ + public double getEasting() { return Easting; } - /** @return Northing/Y at the center of the projection */ - public double getNorthing() - { + /** + * @return Northing/Y at the center of the projection + */ + public double getNorthing() { return Northing; } /** * The function Convert_Transverse_Mercator_To_Geodetic converts Transverse Mercator projection (easting and * northing) coordinates to geodetic (latitude and longitude) coordinates, according to the current ellipsoid and - * Transverse Mercator projection parameters. If any errors occur, the error code(s) are returned by the function, + * Transverse Mercator projection parameters. If any errors occur, the error code(s) are returned by the function, * otherwise TRANMERC_NO_ERROR is returned. * - * @param Easting Easting/X in meters + * @param Easting Easting/X in meters * @param Northing Northing/Y in meters * * @return error code */ - public long convertTransverseMercatorToGeodetic(double Easting, double Northing) - { - double c; /* Cosine of latitude */ - double de; /* Delta easting - Difference in Easting (Easting-Fe) */ - double dlam; /* Delta longitude - Difference in Longitude */ - double eta; /* constant - TranMerc_ebs *c *c */ + public long convertTransverseMercatorToGeodetic(double Easting, double Northing) { + double c; + /* Cosine of latitude */ + double de; + /* Delta easting - Difference in Easting (Easting-Fe) */ + double dlam; + /* Delta longitude - Difference in Longitude */ + double eta; + /* constant - TranMerc_ebs *c *c */ double eta2; double eta3; double eta4; - double ftphi; /* Footpoint latitude */ - int i; /* Loop iterator */ - double s; /* Sine of latitude */ - double sn; /* Radius of curvature in the prime vertical */ - double sr; /* Radius of curvature in the meridian */ - double t; /* Tangent of latitude */ + double ftphi; + /* Footpoint latitude */ + int i; + /* Loop iterator */ + double s; + /* Sine of latitude */ + double sn; + /* Radius of curvature in the prime vertical */ + double sr; + /* Radius of curvature in the meridian */ + double t; + /* Tangent of latitude */ double tan2; double tan4; - double t10; /* Term in coordinate conversion formula - GP to Y */ - double t11; /* Term in coordinate conversion formula - GP to Y */ - double t12; /* Term in coordinate conversion formula - GP to Y */ - double t13; /* Term in coordinate conversion formula - GP to Y */ - double t14; /* Term in coordinate conversion formula - GP to Y */ - double t15; /* Term in coordinate conversion formula - GP to Y */ - double t16; /* Term in coordinate conversion formula - GP to Y */ - double t17; /* Term in coordinate conversion formula - GP to Y */ - double tmd; /* True Meridional distance */ - double tmdo; /* True Meridional distance for latitude of origin */ + double t10; + /* Term in coordinate conversion formula - GP to Y */ + double t11; + /* Term in coordinate conversion formula - GP to Y */ + double t12; + /* Term in coordinate conversion formula - GP to Y */ + double t13; + /* Term in coordinate conversion formula - GP to Y */ + double t14; + /* Term in coordinate conversion formula - GP to Y */ + double t15; + /* Term in coordinate conversion formula - GP to Y */ + double t16; + /* Term in coordinate conversion formula - GP to Y */ + double t17; + /* Term in coordinate conversion formula - GP to Y */ + double tmd; + /* True Meridional distance */ + double tmdo; + /* True Meridional distance for latitude of origin */ long Error_Code = TRANMERC_NO_ERROR; if ((Easting < (TranMerc_False_Easting - TranMerc_Delta_Easting)) - || (Easting > (TranMerc_False_Easting + TranMerc_Delta_Easting))) - { /* Easting out of range */ + || (Easting > (TranMerc_False_Easting + TranMerc_Delta_Easting))) { + /* Easting out of range */ Error_Code |= TRANMERC_EASTING_ERROR; } if ((Northing < (TranMerc_False_Northing - TranMerc_Delta_Northing)) - || (Northing > (TranMerc_False_Northing + TranMerc_Delta_Northing))) - { /* Northing out of range */ + || (Northing > (TranMerc_False_Northing + TranMerc_Delta_Northing))) { + /* Northing out of range */ Error_Code |= TRANMERC_NORTHING_ERROR; } - if (Error_Code == TRANMERC_NO_ERROR) - { + if (Error_Code == TRANMERC_NO_ERROR) { /* True Meridional Distances for latitude of origin */ // tmdo = SPHTMD(TranMerc_Origin_Lat); tmdo = TranMerc_ap * TranMerc_Origin_Lat - - TranMerc_bp * Math.sin(2.0 * TranMerc_Origin_Lat) - + TranMerc_cp * Math.sin(4.0 * TranMerc_Origin_Lat) - - TranMerc_dp * Math.sin(6.0 * TranMerc_Origin_Lat) - + TranMerc_ep * Math.sin(8.0 * TranMerc_Origin_Lat); + - TranMerc_bp * Math.sin(2.0 * TranMerc_Origin_Lat) + + TranMerc_cp * Math.sin(4.0 * TranMerc_Origin_Lat) + - TranMerc_dp * Math.sin(6.0 * TranMerc_Origin_Lat) + + TranMerc_ep * Math.sin(8.0 * TranMerc_Origin_Lat); /* Origin */ tmd = tmdo + (Northing - TranMerc_False_Northing) / TranMerc_Scale_Factor; /* First Estimate */ //sr = SPHSR(0.e0); - sr = TranMerc_a * (1.e0 - TranMerc_es) / - Math.pow(Math.sqrt(1.e0 - TranMerc_es * Math.pow(Math.sin(0.e0), 2)), 3); + sr = TranMerc_a * (1.e0 - TranMerc_es) + / Math.pow(Math.sqrt(1.e0 - TranMerc_es * Math.pow(Math.sin(0.e0), 2)), 3); ftphi = tmd / sr; - for (i = 0; i < 5; i++) - { + for (i = 0; i < 5; i++) { // t10 = SPHTMD (ftphi); t10 = TranMerc_ap * ftphi - - TranMerc_bp * Math.sin(2.0 * ftphi) - + TranMerc_cp * Math.sin(4.0 * ftphi) - - TranMerc_dp * Math.sin(6.0 * ftphi) - + TranMerc_ep * Math.sin(8.0 * ftphi); + - TranMerc_bp * Math.sin(2.0 * ftphi) + + TranMerc_cp * Math.sin(4.0 * ftphi) + - TranMerc_dp * Math.sin(6.0 * ftphi) + + TranMerc_ep * Math.sin(8.0 * ftphi); // sr = SPHSR(ftphi); - sr = TranMerc_a * (1.e0 - TranMerc_es) / - Math.pow(Math.sqrt(1.e0 - TranMerc_es * Math.pow(Math.sin(ftphi), 2)), 3); + sr = TranMerc_a * (1.e0 - TranMerc_es) + / Math.pow(Math.sqrt(1.e0 - TranMerc_es * Math.pow(Math.sin(ftphi), 2)), 3); ftphi = ftphi + (tmd - t10) / sr; } /* Radius of Curvature in the meridian */ // sr = SPHSR(ftphi); - sr = TranMerc_a * (1.e0 - TranMerc_es) / - Math.pow(Math.sqrt(1.e0 - TranMerc_es * Math.pow(Math.sin(ftphi), 2)), 3); + sr = TranMerc_a * (1.e0 - TranMerc_es) + / Math.pow(Math.sqrt(1.e0 - TranMerc_es * Math.pow(Math.sin(ftphi), 2)), 3); /* Radius of Curvature in the meridian */ // sn = SPHSN(ftphi); @@ -455,39 +506,40 @@ public long convertTransverseMercatorToGeodetic(double Easting, double Northing) eta3 = eta2 * eta; eta4 = eta3 * eta; de = Easting - TranMerc_False_Easting; - if (Math.abs(de) < 0.0001) + if (Math.abs(de) < 0.0001) { de = 0.0; + } /* Latitude */ t10 = t / (2.e0 * sr * sn * Math.pow(TranMerc_Scale_Factor, 2)); t11 = t * (5.e0 + 3.e0 * tan2 + eta - 4.e0 * Math.pow(eta, 2) - - 9.e0 * tan2 * eta) / (24.e0 * sr * Math.pow(sn, 3) - * Math.pow(TranMerc_Scale_Factor, 4)); + - 9.e0 * tan2 * eta) / (24.e0 * sr * Math.pow(sn, 3) + * Math.pow(TranMerc_Scale_Factor, 4)); t12 = t * (61.e0 + 90.e0 * tan2 + 46.e0 * eta + 45.E0 * tan4 - - 252.e0 * tan2 * eta - 3.e0 * eta2 + 100.e0 - * eta3 - 66.e0 * tan2 * eta2 - 90.e0 * tan4 - * eta + 88.e0 * eta4 + 225.e0 * tan4 * eta2 - + 84.e0 * tan2 * eta3 - 192.e0 * tan2 * eta4) - / (720.e0 * sr * Math.pow(sn, 5) * Math.pow(TranMerc_Scale_Factor, 6)); + - 252.e0 * tan2 * eta - 3.e0 * eta2 + 100.e0 + * eta3 - 66.e0 * tan2 * eta2 - 90.e0 * tan4 + * eta + 88.e0 * eta4 + 225.e0 * tan4 * eta2 + + 84.e0 * tan2 * eta3 - 192.e0 * tan2 * eta4) + / (720.e0 * sr * Math.pow(sn, 5) * Math.pow(TranMerc_Scale_Factor, 6)); t13 = t * (1385.e0 + 3633.e0 * tan2 + 4095.e0 * tan4 + 1575.e0 - * Math.pow(t, 6)) / (40320.e0 * sr * Math.pow(sn, 7) * Math.pow(TranMerc_Scale_Factor, 8)); + * Math.pow(t, 6)) / (40320.e0 * sr * Math.pow(sn, 7) * Math.pow(TranMerc_Scale_Factor, 8)); Latitude = ftphi - Math.pow(de, 2) * t10 + Math.pow(de, 4) * t11 - Math.pow(de, 6) * t12 - + Math.pow(de, 8) * t13; + + Math.pow(de, 8) * t13; t14 = 1.e0 / (sn * c * TranMerc_Scale_Factor); - t15 = (1.e0 + 2.e0 * tan2 + eta) / (6.e0 * Math.pow(sn, 3) * c * - Math.pow(TranMerc_Scale_Factor, 3)); + t15 = (1.e0 + 2.e0 * tan2 + eta) / (6.e0 * Math.pow(sn, 3) * c + * Math.pow(TranMerc_Scale_Factor, 3)); t16 = (5.e0 + 6.e0 * eta + 28.e0 * tan2 - 3.e0 * eta2 - + 8.e0 * tan2 * eta + 24.e0 * tan4 - 4.e0 - * eta3 + 4.e0 * tan2 * eta2 + 24.e0 - * tan2 * eta3) / (120.e0 * Math.pow(sn, 5) * c - * Math.pow(TranMerc_Scale_Factor, 5)); + + 8.e0 * tan2 * eta + 24.e0 * tan4 - 4.e0 + * eta3 + 4.e0 * tan2 * eta2 + 24.e0 + * tan2 * eta3) / (120.e0 * Math.pow(sn, 5) * c + * Math.pow(TranMerc_Scale_Factor, 5)); t17 = (61.e0 + 662.e0 * tan2 + 1320.e0 * tan4 + 720.e0 - * Math.pow(t, 6)) / (5040.e0 * Math.pow(sn, 7) * c - * Math.pow(TranMerc_Scale_Factor, 7)); + * Math.pow(t, 6)) / (5040.e0 * Math.pow(sn, 7) * c + * Math.pow(TranMerc_Scale_Factor, 7)); /* Difference in Longitude */ dlam = de * t14 - Math.pow(de, 3) * t15 + Math.pow(de, 5) * t16 - Math.pow(de, 7) * t17; @@ -495,38 +547,42 @@ public long convertTransverseMercatorToGeodetic(double Easting, double Northing) /* Longitude */ Longitude = TranMerc_Origin_Long + dlam; - if (Math.abs(Latitude) > (90.0 * PI / 180.0)) + if (Math.abs(Latitude) > (90.0 * PI / 180.0)) { Error_Code |= TRANMERC_NORTHING_ERROR; + } - if ((Longitude) > (PI)) - { + if ((Longitude) > (PI)) { Longitude -= (2 * PI); - if (Math.abs(Longitude) > PI) + if (Math.abs(Longitude) > PI) { Error_Code |= TRANMERC_EASTING_ERROR; + } } - if (Math.abs(dlam) > (9.0 * PI / 180) * Math.cos(Latitude)) - { /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian at the equator */ - /* and decreases to 0 degrees at the poles */ - /* As you move towards the poles, distortion will become more significant */ + if (Math.abs(dlam) > (9.0 * PI / 180) * Math.cos(Latitude)) { + /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian at the equator */ + /* and decreases to 0 degrees at the poles */ + /* As you move towards the poles, distortion will become more significant */ Error_Code |= TRANMERC_LON_WARNING; } - if (Latitude > 1.0e10) + if (Latitude > 1.0e10) { Error_Code |= TRANMERC_LON_WARNING; + } } return (Error_Code); } - /** @return Latitude in radians. */ - public double getLatitude() - { + /** + * @return Latitude in radians. + */ + public double getLatitude() { return Latitude; } - /** @return Longitude in radians. */ - public double getLongitude() - { + /** + * @return Longitude in radians. + */ + public double getLongitude() { return Longitude; } } // end TMConverter class diff --git a/src/gov/nasa/worldwind/geom/coords/UPSCoord.java b/src/gov/nasa/worldwind/geom/coords/UPSCoord.java index 62fc813bf0..3c129e88d8 100644 --- a/src/gov/nasa/worldwind/geom/coords/UPSCoord.java +++ b/src/gov/nasa/worldwind/geom/coords/UPSCoord.java @@ -16,9 +16,8 @@ * @author Patrick Murris * @version $Id: UPSCoord.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class UPSCoord { -public class UPSCoord -{ private final Angle latitude; private final Angle longitude; private final String hemisphere; @@ -28,35 +27,32 @@ public class UPSCoord /** * Create a set of UPS coordinates from a pair of latitude and longitude for a WGS84 globe. * - * @param latitude the latitude Angle. + * @param latitude the latitude Angle. * @param longitude the longitude Angle. * * @return the corresponding UPSCoord. * * @throws IllegalArgumentException if latitude or longitude is null, or the conversion to - * UPS coordinates fails. + * UPS coordinates fails. */ - public static UPSCoord fromLatLon(Angle latitude, Angle longitude) - { + public static UPSCoord fromLatLon(Angle latitude, Angle longitude) { return fromLatLon(latitude, longitude, null); } /** * Create a set of UPS coordinates from a pair of latitude and longitude for the given Globe. * - * @param latitude the latitude Angle. + * @param latitude the latitude Angle. * @param longitude the longitude Angle. - * @param globe the Globe - can be null (will use WGS84). + * @param globe the Globe - can be null (will use WGS84). * * @return the corresponding UPSCoord. * * @throws IllegalArgumentException if latitude or longitude is null, or the conversion to - * UPS coordinates fails. + * UPS coordinates fails. */ - public static UPSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) - { - if (latitude == null || longitude == null) - { + public static UPSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -65,15 +61,14 @@ public static UPSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) final UPSCoordConverter converter = new UPSCoordConverter(globe); long err = converter.convertGeodeticToUPS(latitude.radians, longitude.radians); - if (err != UPSCoordConverter.UPS_NO_ERROR) - { + if (err != UPSCoordConverter.UPS_NO_ERROR) { String message = Logging.getMessage("Coord.UPSConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new UPSCoord(latitude, longitude, converter.getHemisphere(), - converter.getEasting(), converter.getNorthing()); + converter.getEasting(), converter.getNorthing()); } /** @@ -81,15 +76,14 @@ public static UPSCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) * * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param easting the easting distance in meters - * @param northing the northing distance in meters. + * @param easting the easting distance in meters + * @param northing the northing distance in meters. * * @return the corresponding UPSCoord. * * @throws IllegalArgumentException if the conversion to UPS coordinates fails. */ - public static UPSCoord fromUTM(String hemisphere, double easting, double northing) - { + public static UPSCoord fromUTM(String hemisphere, double easting, double northing) { return fromUPS(hemisphere, easting, northing, null); } @@ -98,48 +92,44 @@ public static UPSCoord fromUTM(String hemisphere, double easting, double northin * * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param easting the easting distance in meters - * @param northing the northing distance in meters. - * @param globe the Globe - can be null (will use WGS84). + * @param easting the easting distance in meters + * @param northing the northing distance in meters. + * @param globe the Globe - can be null (will use WGS84). * * @return the corresponding UPSCoord. * * @throws IllegalArgumentException if the conversion to UPS coordinates fails. */ - public static UPSCoord fromUPS(String hemisphere, double easting, double northing, Globe globe) - { + public static UPSCoord fromUPS(String hemisphere, double easting, double northing, Globe globe) { final UPSCoordConverter converter = new UPSCoordConverter(globe); long err = converter.convertUPSToGeodetic(hemisphere, easting, northing); - if (err != UTMCoordConverter.UTM_NO_ERROR) - { + if (err != UTMCoordConverter.UTM_NO_ERROR) { String message = Logging.getMessage("Coord.UTMConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new UPSCoord(Angle.fromRadians(converter.getLatitude()), - Angle.fromRadians(converter.getLongitude()), - hemisphere, easting, northing); + Angle.fromRadians(converter.getLongitude()), + hemisphere, easting, northing); } /** * Create an arbitrary set of UPS coordinates with the given values. * - * @param latitude the latitude Angle. - * @param longitude the longitude Angle. + * @param latitude the latitude Angle. + * @param longitude the longitude Angle. * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param easting the easting distance in meters - * @param northing the northing distance in meters. + * @param easting the easting distance in meters + * @param northing the northing distance in meters. * * @throws IllegalArgumentException if latitude, longitude, or hemisphere is - * null. + * null. */ - public UPSCoord(Angle latitude, Angle longitude, String hemisphere, double easting, double northing) - { - if (latitude == null || longitude == null) - { + public UPSCoord(Angle latitude, Angle longitude, String hemisphere, double easting, double northing) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -152,33 +142,27 @@ public UPSCoord(Angle latitude, Angle longitude, String hemisphere, double easti this.northing = northing; } - public Angle getLatitude() - { + public Angle getLatitude() { return this.latitude; } - public Angle getLongitude() - { + public Angle getLongitude() { return this.longitude; } - public String getHemisphere() - { + public String getHemisphere() { return this.hemisphere; } - public double getEasting() - { + public double getEasting() { return this.easting; } - public double getNorthing() - { + public double getNorthing() { return this.northing; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append(AVKey.NORTH.equals(hemisphere) ? "N" : "S"); sb.append(" ").append(easting).append("E"); diff --git a/src/gov/nasa/worldwind/geom/coords/UPSCoordConverter.java b/src/gov/nasa/worldwind/geom/coords/UPSCoordConverter.java index a3819591c6..f7eae632fa 100644 --- a/src/gov/nasa/worldwind/geom/coords/UPSCoordConverter.java +++ b/src/gov/nasa/worldwind/geom/coords/UPSCoordConverter.java @@ -3,8 +3,7 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - -/********************************************************************/ +/** ***************************************************************** */ /* RSC IDENTIFIER: UPS * * @@ -82,7 +81,6 @@ * * */ - package gov.nasa.worldwind.geom.coords; import gov.nasa.worldwind.avlist.AVKey; @@ -94,8 +92,8 @@ * @author Garrett Headley, Patrick Murris * @version $Id: UPSCoordConverter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class UPSCoordConverter -{ +public class UPSCoordConverter { + public static final int UPS_NO_ERROR = 0x0000; private static final int UPS_LAT_ERROR = 0x0001; private static final int UPS_LON_ERROR = 0x0002; @@ -115,13 +113,16 @@ public class UPSCoordConverter private static final double MIN_EAST_NORTH = 0; private static final double MAX_EAST_NORTH = 4000000; - private double UPS_Origin_Latitude = MAX_ORIGIN_LAT; /*set default = North Hemisphere */ + private double UPS_Origin_Latitude = MAX_ORIGIN_LAT; + /*set default = North Hemisphere */ private double UPS_Origin_Longitude = 0.0; /* Ellipsoid Parameters, default to WGS 84 */ private final Globe globe; - private double UPS_a = 6378137.0; /* Semi-major axis of ellipsoid in meters */ - private double UPS_f = 1 / 298.257223563; /* Flattening of ellipsoid */ + private double UPS_a = 6378137.0; + /* Semi-major axis of ellipsoid in meters */ + private double UPS_f = 1 / 298.257223563; + /* Flattening of ellipsoid */ private double UPS_False_Easting = 2000000.0; private double UPS_False_Northing = 2000000.0; private double false_easting = 0.0; @@ -137,11 +138,9 @@ public class UPSCoordConverter private PolarCoordConverter polarConverter = new PolarCoordConverter(); - UPSCoordConverter(Globe globe) - { + UPSCoordConverter(Globe globe) { this.globe = globe; - if (globe != null) - { + if (globe != null) { double a = globe.getEquatorialRadius(); double f = (globe.getEquatorialRadius() - globe.getPolarRadius()) / globe.getEquatorialRadius(); setUPSParameters(a, f); @@ -157,16 +156,15 @@ public class UPSCoordConverter * * @return error code */ - public long setUPSParameters(double a, double f) - { + public long setUPSParameters(double a, double f) { double inv_f = 1 / f; - if (a <= 0.0) - { /* Semi-major axis must be greater than zero */ + if (a <= 0.0) { + /* Semi-major axis must be greater than zero */ return UPS_A_ERROR; } - if ((inv_f < 250) || (inv_f > 350)) - { /* Inverse flattening must be between 250 and 350 */ + if ((inv_f < 250) || (inv_f > 350)) { + /* Inverse flattening must be between 250 and 350 */ return UPS_INV_F_ERROR; } @@ -181,48 +179,47 @@ public long setUPSParameters(double a, double f) * easting, and northing) coordinates, according to the current ellipsoid parameters. If any errors occur, the error * code(s) are returned by the function, otherwide UPS_NO_ERROR is returned. * - * @param latitude Latitude in radians + * @param latitude Latitude in radians * @param longitude Longitude in radians * * @return error code */ - public long convertGeodeticToUPS(double latitude, double longitude) - { - if ((latitude < -MAX_LAT) || (latitude > MAX_LAT)) - { /* latitude out of range */ + public long convertGeodeticToUPS(double latitude, double longitude) { + if ((latitude < -MAX_LAT) || (latitude > MAX_LAT)) { + /* latitude out of range */ return UPS_LAT_ERROR; } - if ((latitude < 0) && (latitude > MIN_SOUTH_LAT)) + if ((latitude < 0) && (latitude > MIN_SOUTH_LAT)) { return UPS_LAT_ERROR; - if ((latitude >= 0) && (latitude < MIN_NORTH_LAT)) + } + if ((latitude >= 0) && (latitude < MIN_NORTH_LAT)) { return UPS_LAT_ERROR; + } - if ((longitude < -PI) || (longitude > (2 * PI))) - { /* slam out of range */ + if ((longitude < -PI) || (longitude > (2 * PI))) { + /* slam out of range */ return UPS_LON_ERROR; } - if (latitude < 0) - { + if (latitude < 0) { UPS_Origin_Latitude = -MAX_ORIGIN_LAT; Hemisphere = AVKey.SOUTH; - } - else - { + } else { UPS_Origin_Latitude = MAX_ORIGIN_LAT; Hemisphere = AVKey.NORTH; } polarConverter.setPolarStereographicParameters(UPS_a, UPS_f, - UPS_Origin_Latitude, UPS_Origin_Longitude, - false_easting, false_northing); + UPS_Origin_Latitude, UPS_Origin_Longitude, + false_easting, false_northing); polarConverter.convertGeodeticToPolarStereographic(latitude, longitude); UPS_Easting = UPS_False_Easting + polarConverter.getEasting(); UPS_Northing = UPS_False_Northing + polarConverter.getNorthing(); - if (AVKey.SOUTH.equals(Hemisphere)) + if (AVKey.SOUTH.equals(Hemisphere)) { UPS_Northing = UPS_False_Northing - polarConverter.getNorthing(); + } Easting = UPS_Easting; Northing = UPS_Northing; @@ -230,15 +227,17 @@ public long convertGeodeticToUPS(double latitude, double longitude) return UPS_NO_ERROR; } - /** @return Easting/X in meters */ - public double getEasting() - { + /** + * @return Easting/X in meters + */ + public double getEasting() { return Easting; } - /** @return Northing/Y in meters */ - public double getNorthing() - { + /** + * @return Northing/Y in meters + */ + public double getNorthing() { return Northing; } @@ -246,71 +245,76 @@ public double getNorthing() * @return Hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. */ - public String getHemisphere() - { + public String getHemisphere() { return Hemisphere; } /** * The function Convert_UPS_To_Geodetic converts UPS (hemisphere, easting, and northing) coordinates to geodetic - * (latitude and longitude) coordinates according to the current ellipsoid parameters. If any errors occur, the + * (latitude and longitude) coordinates according to the current ellipsoid parameters. If any errors occur, the * error code(s) are returned by the function, otherwise UPS_NO_ERROR is returned. * * @param Hemisphere Hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param Easting Easting/X in meters - * @param Northing Northing/Y in meters + * @param Easting Easting/X in meters + * @param Northing Northing/Y in meters * * @return error code */ - public long convertUPSToGeodetic(String Hemisphere, double Easting, double Northing) - { + public long convertUPSToGeodetic(String Hemisphere, double Easting, double Northing) { long Error_Code = UPS_NO_ERROR; - if (!AVKey.NORTH.equals(Hemisphere) && !AVKey.SOUTH.equals(Hemisphere)) + if (!AVKey.NORTH.equals(Hemisphere) && !AVKey.SOUTH.equals(Hemisphere)) { Error_Code |= UPS_HEMISPHERE_ERROR; - if ((Easting < MIN_EAST_NORTH) || (Easting > MAX_EAST_NORTH)) + } + if ((Easting < MIN_EAST_NORTH) || (Easting > MAX_EAST_NORTH)) { Error_Code |= UPS_EASTING_ERROR; - if ((Northing < MIN_EAST_NORTH) || (Northing > MAX_EAST_NORTH)) + } + if ((Northing < MIN_EAST_NORTH) || (Northing > MAX_EAST_NORTH)) { Error_Code |= UPS_NORTHING_ERROR; + } - if (AVKey.NORTH.equals(Hemisphere)) + if (AVKey.NORTH.equals(Hemisphere)) { UPS_Origin_Latitude = MAX_ORIGIN_LAT; - if (AVKey.SOUTH.equals(Hemisphere)) + } + if (AVKey.SOUTH.equals(Hemisphere)) { UPS_Origin_Latitude = -MAX_ORIGIN_LAT; + } - if (Error_Code == UPS_NO_ERROR) - { /* no errors */ + if (Error_Code == UPS_NO_ERROR) { + /* no errors */ polarConverter.setPolarStereographicParameters(UPS_a, - UPS_f, - UPS_Origin_Latitude, - UPS_Origin_Longitude, - UPS_False_Easting, - UPS_False_Northing); + UPS_f, + UPS_Origin_Latitude, + UPS_Origin_Longitude, + UPS_False_Easting, + UPS_False_Northing); polarConverter.convertPolarStereographicToGeodetic(Easting, Northing); Latitude = polarConverter.getLatitude(); Longitude = polarConverter.getLongitude(); - if ((Latitude < 0) && (Latitude > MIN_SOUTH_LAT)) + if ((Latitude < 0) && (Latitude > MIN_SOUTH_LAT)) { Error_Code |= UPS_LAT_ERROR; - if ((Latitude >= 0) && (Latitude < MIN_NORTH_LAT)) + } + if ((Latitude >= 0) && (Latitude < MIN_NORTH_LAT)) { Error_Code |= UPS_LAT_ERROR; + } } return Error_Code; } - /** @return Latitude in radians. */ - public double getLatitude() - { + /** + * @return Latitude in radians. + */ + public double getLatitude() { return Latitude; } - /** @return Longitude in radians. */ - public double getLongitude() - { + /** + * @return Longitude in radians. + */ + public double getLongitude() { return Longitude; } } - - diff --git a/src/gov/nasa/worldwind/geom/coords/UTMCoord.java b/src/gov/nasa/worldwind/geom/coords/UTMCoord.java index 67cadb870d..c40e9e7a09 100644 --- a/src/gov/nasa/worldwind/geom/coords/UTMCoord.java +++ b/src/gov/nasa/worldwind/geom/coords/UTMCoord.java @@ -16,9 +16,8 @@ * @author Patrick Murris * @version $Id: UTMCoord.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class UTMCoord { -public class UTMCoord -{ private final Angle latitude; private final Angle longitude; private final String hemisphere; @@ -30,35 +29,32 @@ public class UTMCoord /** * Create a set of UTM coordinates from a pair of latitude and longitude for a WGS84 globe. * - * @param latitude the latitude Angle. + * @param latitude the latitude Angle. * @param longitude the longitude Angle. * * @return the corresponding UTMCoord. * * @throws IllegalArgumentException if latitude or longitude is null, or the conversion to - * UTM coordinates fails. + * UTM coordinates fails. */ - public static UTMCoord fromLatLon(Angle latitude, Angle longitude) - { + public static UTMCoord fromLatLon(Angle latitude, Angle longitude) { return fromLatLon(latitude, longitude, (Globe) null); } /** * Create a set of UTM coordinates from a pair of latitude and longitude for the given Globe. * - * @param latitude the latitude Angle. + * @param latitude the latitude Angle. * @param longitude the longitude Angle. - * @param globe the Globe - can be null (will use WGS84). + * @param globe the Globe - can be null (will use WGS84). * * @return the corresponding UTMCoord. * * @throws IllegalArgumentException if latitude or longitude is null, or the conversion to - * UTM coordinates fails. + * UTM coordinates fails. */ - public static UTMCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) - { - if (latitude == null || longitude == null) - { + public static UTMCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -67,115 +63,104 @@ public static UTMCoord fromLatLon(Angle latitude, Angle longitude, Globe globe) final UTMCoordConverter converter = new UTMCoordConverter(globe); long err = converter.convertGeodeticToUTM(latitude.radians, longitude.radians); - if (err != UTMCoordConverter.UTM_NO_ERROR) - { + if (err != UTMCoordConverter.UTM_NO_ERROR) { String message = Logging.getMessage("Coord.UTMConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new UTMCoord(latitude, longitude, converter.getZone(), converter.getHemisphere(), - converter.getEasting(), converter.getNorthing(), Angle.fromRadians(converter.getCentralMeridian())); + converter.getEasting(), converter.getNorthing(), Angle.fromRadians(converter.getCentralMeridian())); } - public static UTMCoord fromLatLon(Angle latitude, Angle longitude, String datum) - { - if (latitude == null || longitude == null) - { + public static UTMCoord fromLatLon(Angle latitude, Angle longitude, String datum) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } UTMCoordConverter converter; - if (!WWUtil.isEmpty(datum) && datum.equals("NAD27")) - { + if (!WWUtil.isEmpty(datum) && datum.equals("NAD27")) { converter = new UTMCoordConverter(UTMCoordConverter.CLARKE_A, UTMCoordConverter.CLARKE_F); LatLon llNAD27 = UTMCoordConverter.convertWGS84ToNAD27(latitude, longitude); latitude = llNAD27.getLatitude(); longitude = llNAD27.getLongitude(); - } - else - { + } else { converter = new UTMCoordConverter(UTMCoordConverter.WGS84_A, UTMCoordConverter.WGS84_F); } long err = converter.convertGeodeticToUTM(latitude.radians, longitude.radians); - if (err != UTMCoordConverter.UTM_NO_ERROR) - { + if (err != UTMCoordConverter.UTM_NO_ERROR) { String message = Logging.getMessage("Coord.UTMConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new UTMCoord(latitude, longitude, converter.getZone(), converter.getHemisphere(), - converter.getEasting(), converter.getNorthing(), Angle.fromRadians(converter.getCentralMeridian())); + converter.getEasting(), converter.getNorthing(), Angle.fromRadians(converter.getCentralMeridian())); } /** * Create a set of UTM coordinates for a WGS84 globe. * - * @param zone the UTM zone - 1 to 60. + * @param zone the UTM zone - 1 to 60. * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param easting the easting distance in meters - * @param northing the northing distance in meters. + * @param easting the easting distance in meters + * @param northing the northing distance in meters. * * @return the corresponding UTMCoord. * * @throws IllegalArgumentException if the conversion to UTM coordinates fails. */ - public static UTMCoord fromUTM(int zone, String hemisphere, double easting, double northing) - { + public static UTMCoord fromUTM(int zone, String hemisphere, double easting, double northing) { return fromUTM(zone, hemisphere, easting, northing, null); } /** * Create a set of UTM coordinates for the given Globe. * - * @param zone the UTM zone - 1 to 60. + * @param zone the UTM zone - 1 to 60. * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param easting the easting distance in meters - * @param northing the northing distance in meters. - * @param globe the Globe - can be null (will use WGS84). + * @param easting the easting distance in meters + * @param northing the northing distance in meters. + * @param globe the Globe - can be null (will use WGS84). * * @return the corresponding UTMCoord. * * @throws IllegalArgumentException if the conversion to UTM coordinates fails. */ - public static UTMCoord fromUTM(int zone, String hemisphere, double easting, double northing, Globe globe) - { + public static UTMCoord fromUTM(int zone, String hemisphere, double easting, double northing, Globe globe) { final UTMCoordConverter converter = new UTMCoordConverter(globe); long err = converter.convertUTMToGeodetic(zone, hemisphere, easting, northing); - if (err != UTMCoordConverter.UTM_NO_ERROR) - { + if (err != UTMCoordConverter.UTM_NO_ERROR) { String message = Logging.getMessage("Coord.UTMConversionError"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new UTMCoord(Angle.fromRadians(converter.getLatitude()), - Angle.fromRadians(converter.getLongitude()), - zone, hemisphere, easting, northing, Angle.fromRadians(converter.getCentralMeridian())); + Angle.fromRadians(converter.getLongitude()), + zone, hemisphere, easting, northing, Angle.fromRadians(converter.getCentralMeridian())); } /** * Convenience method for converting a UTM coordinate to a geographic location. * - * @param zone the UTM zone: 1 to 60. + * @param zone the UTM zone: 1 to 60. * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param easting the easting distance in meters - * @param northing the northing distance in meters. - * @param globe the Globe. Can be null (will use WGS84). + * @param easting the easting distance in meters + * @param northing the northing distance in meters. + * @param globe the Globe. Can be null (will use WGS84). * * @return the geographic location corresponding to the specified UTM coordinate. */ - public static LatLon locationFromUTMCoord(int zone, String hemisphere, double easting, double northing, Globe globe) - { + public static LatLon locationFromUTMCoord(int zone, String hemisphere, double easting, double northing, Globe globe) { UTMCoord coord = UTMCoord.fromUTM(zone, hemisphere, easting, northing, globe); return new LatLon(coord.getLatitude(), coord.getLongitude()); } @@ -183,40 +168,37 @@ public static LatLon locationFromUTMCoord(int zone, String hemisphere, double ea /** * Create an arbitrary set of UTM coordinates with the given values. * - * @param latitude the latitude Angle. - * @param longitude the longitude Angle. - * @param zone the UTM zone - 1 to 60. + * @param latitude the latitude Angle. + * @param longitude the longitude Angle. + * @param zone the UTM zone - 1 to 60. * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param easting the easting distance in meters - * @param northing the northing distance in meters. + * @param easting the easting distance in meters + * @param northing the northing distance in meters. * * @throws IllegalArgumentException if latitude or longitude is null. */ - public UTMCoord(Angle latitude, Angle longitude, int zone, String hemisphere, double easting, double northing) - { + public UTMCoord(Angle latitude, Angle longitude, int zone, String hemisphere, double easting, double northing) { this(latitude, longitude, zone, hemisphere, easting, northing, Angle.fromDegreesLongitude(0.0)); } /** * Create an arbitrary set of UTM coordinates with the given values. * - * @param latitude the latitude Angle. - * @param longitude the longitude Angle. - * @param zone the UTM zone - 1 to 60. - * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link + * @param latitude the latitude Angle. + * @param longitude the longitude Angle. + * @param zone the UTM zone - 1 to 60. + * @param hemisphere the hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param easting the easting distance in meters - * @param northing the northing distance in meters. + * @param easting the easting distance in meters + * @param northing the northing distance in meters. * @param centralMeridian the cntral meridian Angle. * * @throws IllegalArgumentException if latitude or longitude is null. */ public UTMCoord(Angle latitude, Angle longitude, int zone, String hemisphere, double easting, double northing, - Angle centralMeridian) - { - if (latitude == null || longitude == null) - { + Angle centralMeridian) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -231,43 +213,35 @@ public UTMCoord(Angle latitude, Angle longitude, int zone, String hemisphere, do this.centralMeridian = centralMeridian; } - public Angle getCentralMeridian() - { + public Angle getCentralMeridian() { return this.centralMeridian; } - public Angle getLatitude() - { + public Angle getLatitude() { return this.latitude; } - public Angle getLongitude() - { + public Angle getLongitude() { return this.longitude; } - public int getZone() - { + public int getZone() { return this.zone; } - public String getHemisphere() - { + public String getHemisphere() { return this.hemisphere; } - public double getEasting() - { + public double getEasting() { return this.easting; } - public double getNorthing() - { + public double getNorthing() { return this.northing; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append(zone); sb.append(" ").append(AVKey.NORTH.equals(hemisphere) ? "N" : "S"); diff --git a/src/gov/nasa/worldwind/geom/coords/UTMCoordConverter.java b/src/gov/nasa/worldwind/geom/coords/UTMCoordConverter.java index 1570d9fbe0..88aad7f1e4 100644 --- a/src/gov/nasa/worldwind/geom/coords/UTMCoordConverter.java +++ b/src/gov/nasa/worldwind/geom/coords/UTMCoordConverter.java @@ -16,14 +16,13 @@ * @version $Id: UTMCoordConverter.java 1171 2013-02-11 21:45:02Z dcollins $ * @see UTMCoord, TMCoordConverter */ - /** * Ported to Java from the NGA GeoTrans utm.c and utm.h * * @author Garrett Headley, Patrick Murris */ -class UTMCoordConverter -{ +class UTMCoordConverter { + public final static double CLARKE_A = 6378206.4; public final static double CLARKE_B = 6356583.8; public final static double CLARKE_F = 1 / 294.9786982; @@ -46,8 +45,10 @@ class UTMCoordConverter private final static double PI = 3.14159265358979323; //private final static double MIN_LAT = ((-80.5 * PI) / 180.0); /* -80.5 degrees in radians */ //private final static double MAX_LAT = ((84.5 * PI) / 180.0); /* 84.5 degrees in radians */ - private final static double MIN_LAT = ((-82 * PI) / 180.0); /* -82 degrees in radians */ - private final static double MAX_LAT = ((86 * PI) / 180.0); /* 86 degrees in radians */ + private final static double MIN_LAT = ((-82 * PI) / 180.0); + /* -82 degrees in radians */ + private final static double MAX_LAT = ((86 * PI) / 180.0); + /* 86 degrees in radians */ private final static int MIN_EASTING = 100000; private final static int MAX_EASTING = 900000; @@ -55,9 +56,12 @@ class UTMCoordConverter private final static int MAX_NORTHING = 10000000; private final Globe globe; - private double UTM_a = 6378137.0; /* Semi-major axis of ellipsoid in meters */ - private double UTM_f = 1 / 298.257223563; /* Flattening of ellipsoid */ - private long UTM_Override = 0; /* Zone override flag */ + private double UTM_a = 6378137.0; + /* Semi-major axis of ellipsoid in meters */ + private double UTM_f = 1 / 298.257223563; + /* Flattening of ellipsoid */ + private long UTM_Override = 0; + /* Zone override flag */ private double Easting; private double Northing; @@ -67,53 +71,48 @@ class UTMCoordConverter private double Longitude; private double Central_Meridian; - UTMCoordConverter(Globe globe) - { + UTMCoordConverter(Globe globe) { this.globe = globe; - if (globe != null) - { + if (globe != null) { double a = globe.getEquatorialRadius(); double f = (globe.getEquatorialRadius() - globe.getPolarRadius()) / globe.getEquatorialRadius(); setUTMParameters(a, f, 0); } } - UTMCoordConverter(double a, double f) - { + UTMCoordConverter(double a, double f) { this.globe = null; setUTMParameters(a, f, 0); } /** * The function Set_UTM_Parameters receives the ellipsoid parameters and UTM zone override parameter as inputs, and - * sets the corresponding state variables. If any errors occur, the error code(s) are returned by the function, + * sets the corresponding state variables. If any errors occur, the error code(s) are returned by the function, * otherwise UTM_NO_ERROR is returned. * - * @param a Semi-major axis of ellipsoid, in meters - * @param f Flattening of ellipsoid + * @param a Semi-major axis of ellipsoid, in meters + * @param f Flattening of ellipsoid * @param override UTM override zone, zero indicates no override * * @return error code */ - private long setUTMParameters(double a, double f, long override) - { + private long setUTMParameters(double a, double f, long override) { double inv_f = 1 / f; long Error_Code = UTM_NO_ERROR; - if (a <= 0.0) - { /* Semi-major axis must be greater than zero */ + if (a <= 0.0) { + /* Semi-major axis must be greater than zero */ Error_Code |= UTM_A_ERROR; } - if ((inv_f < 250) || (inv_f > 350)) - { /* Inverse flattening must be between 250 and 350 */ + if ((inv_f < 250) || (inv_f > 350)) { + /* Inverse flattening must be between 250 and 350 */ Error_Code |= UTM_INV_F_ERROR; } - if ((override < 0) || (override > 60)) - { + if ((override < 0) || (override > 60)) { Error_Code |= UTM_ZONE_OVERRIDE_ERROR; } - if (Error_Code == UTM_NO_ERROR) - { /* no errors */ + if (Error_Code == UTM_NO_ERROR) { + /* no errors */ UTM_a = a; UTM_f = f; UTM_Override = override; @@ -124,16 +123,15 @@ private long setUTMParameters(double a, double f, long override) /** * The function Convert_Geodetic_To_UTM converts geodetic (latitude and longitude) coordinates to UTM projection * (zone, hemisphere, easting and northing) coordinates according to the current ellipsoid and UTM zone override - * parameters. If any errors occur, the error code(s) are returned by the function, otherwise UTM_NO_ERROR is + * parameters. If any errors occur, the error code(s) are returned by the function, otherwise UTM_NO_ERROR is * returned. * - * @param Latitude Latitude in radians + * @param Latitude Latitude in radians * @param Longitude Longitude in radians * * @return error code */ - public long convertGeodeticToUTM(double Latitude, double Longitude) - { + public long convertGeodeticToUTM(double Latitude, double Longitude) { long Lat_Degrees; long Long_Degrees; long temp_zone; @@ -143,82 +141,89 @@ public long convertGeodeticToUTM(double Latitude, double Longitude) double False_Northing = 0; double Scale = 0.9996; - if ((Latitude < MIN_LAT) || (Latitude > MAX_LAT)) - { /* Latitude out of range */ + if ((Latitude < MIN_LAT) || (Latitude > MAX_LAT)) { + /* Latitude out of range */ Error_Code |= UTM_LAT_ERROR; } - if ((Longitude < -PI) || (Longitude > (2 * PI))) - { /* Longitude out of range */ + if ((Longitude < -PI) || (Longitude > (2 * PI))) { + /* Longitude out of range */ Error_Code |= UTM_LON_ERROR; } - if (Error_Code == UTM_NO_ERROR) - { /* no errors */ - if (Longitude < 0) + if (Error_Code == UTM_NO_ERROR) { + /* no errors */ + if (Longitude < 0) { Longitude += (2 * PI) + 1.0e-10; + } Lat_Degrees = (long) (Latitude * 180.0 / PI); Long_Degrees = (long) (Longitude * 180.0 / PI); - if (Longitude < PI) + if (Longitude < PI) { temp_zone = (long) (31 + ((Longitude * 180.0 / PI) / 6.0)); - else + } else { temp_zone = (long) (((Longitude * 180.0 / PI) / 6.0) - 29); - if (temp_zone > 60) + } + if (temp_zone > 60) { temp_zone = 1; + } /* UTM special cases */ - if ((Lat_Degrees > 55) && (Lat_Degrees < 64) && (Long_Degrees > -1) && (Long_Degrees < 3)) + if ((Lat_Degrees > 55) && (Lat_Degrees < 64) && (Long_Degrees > -1) && (Long_Degrees < 3)) { temp_zone = 31; - if ((Lat_Degrees > 55) && (Lat_Degrees < 64) && (Long_Degrees > 2) && (Long_Degrees < 12)) + } + if ((Lat_Degrees > 55) && (Lat_Degrees < 64) && (Long_Degrees > 2) && (Long_Degrees < 12)) { temp_zone = 32; - if ((Lat_Degrees > 71) && (Long_Degrees > -1) && (Long_Degrees < 9)) + } + if ((Lat_Degrees > 71) && (Long_Degrees > -1) && (Long_Degrees < 9)) { temp_zone = 31; - if ((Lat_Degrees > 71) && (Long_Degrees > 8) && (Long_Degrees < 21)) + } + if ((Lat_Degrees > 71) && (Long_Degrees > 8) && (Long_Degrees < 21)) { temp_zone = 33; - if ((Lat_Degrees > 71) && (Long_Degrees > 20) && (Long_Degrees < 33)) + } + if ((Lat_Degrees > 71) && (Long_Degrees > 20) && (Long_Degrees < 33)) { temp_zone = 35; - if ((Lat_Degrees > 71) && (Long_Degrees > 32) && (Long_Degrees < 42)) + } + if ((Lat_Degrees > 71) && (Long_Degrees > 32) && (Long_Degrees < 42)) { temp_zone = 37; + } - if (UTM_Override != 0) - { - if ((temp_zone == 1) && (UTM_Override == 60)) + if (UTM_Override != 0) { + if ((temp_zone == 1) && (UTM_Override == 60)) { temp_zone = UTM_Override; - else if ((temp_zone == 60) && (UTM_Override == 1)) + } else if ((temp_zone == 60) && (UTM_Override == 1)) { temp_zone = UTM_Override; - else if (((temp_zone - 1) <= UTM_Override) && (UTM_Override <= (temp_zone + 1))) + } else if (((temp_zone - 1) <= UTM_Override) && (UTM_Override <= (temp_zone + 1))) { temp_zone = UTM_Override; - else + } else { Error_Code = UTM_ZONE_OVERRIDE_ERROR; + } } - if (Error_Code == UTM_NO_ERROR) - { - if (temp_zone >= 31) + if (Error_Code == UTM_NO_ERROR) { + if (temp_zone >= 31) { Central_Meridian = (6 * temp_zone - 183) * PI / 180.0; - else + } else { Central_Meridian = (6 * temp_zone + 177) * PI / 180.0; + } Zone = (int) temp_zone; - if (Latitude < 0) - { + if (Latitude < 0) { False_Northing = 10000000; Hemisphere = AVKey.SOUTH; - } - else + } else { Hemisphere = AVKey.NORTH; + } - try - { + try { TMCoord TM = TMCoord.fromLatLon(Angle.fromRadians(Latitude), Angle.fromRadians(Longitude), - this.globe, this.UTM_a, this.UTM_f, Angle.fromRadians(Origin_Latitude), - Angle.fromRadians(Central_Meridian), False_Easting, False_Northing, Scale); + this.globe, this.UTM_a, this.UTM_f, Angle.fromRadians(Origin_Latitude), + Angle.fromRadians(Central_Meridian), False_Easting, False_Northing, Scale); Easting = TM.getEasting(); Northing = TM.getNorthing(); - if ((Easting < MIN_EASTING) || (Easting > MAX_EASTING)) + if ((Easting < MIN_EASTING) || (Easting > MAX_EASTING)) { Error_Code = UTM_EASTING_ERROR; - if ((Northing < MIN_NORTHING) || (Northing > MAX_NORTHING)) + } + if ((Northing < MIN_NORTHING) || (Northing > MAX_NORTHING)) { Error_Code |= UTM_NORTHING_ERROR; - } - catch (Exception e) - { + } + } catch (Exception e) { Error_Code = UTM_TM_ERROR; } } @@ -226,15 +231,17 @@ else if (((temp_zone - 1) <= UTM_Override) && (UTM_Override <= (temp_zone + 1))) return (Error_Code); } - /** @return Easting (X) in meters */ - public double getEasting() - { + /** + * @return Easting (X) in meters + */ + public double getEasting() { return Easting; } - /** @return Northing (Y) in meters */ - public double getNorthing() - { + /** + * @return Northing (Y) in meters + */ + public double getNorthing() { return Northing; } @@ -242,32 +249,31 @@ public double getNorthing() * @return The coordinate hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. */ - public String getHemisphere() - { + public String getHemisphere() { return Hemisphere; } - /** @return UTM zone */ - public int getZone() - { + /** + * @return UTM zone + */ + public int getZone() { return Zone; } /** * The function Convert_UTM_To_Geodetic converts UTM projection (zone, hemisphere, easting and northing) coordinates - * to geodetic(latitude and longitude) coordinates, according to the current ellipsoid parameters. If any errors + * to geodetic(latitude and longitude) coordinates, according to the current ellipsoid parameters. If any errors * occur, the error code(s) are returned by the function, otherwise UTM_NO_ERROR is returned. * - * @param Zone UTM zone. + * @param Zone UTM zone. * @param Hemisphere The coordinate hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param Easting Easting (X) in meters. - * @param Northing Northing (Y) in meters. + * @param Easting Easting (X) in meters. + * @param Northing Northing (Y) in meters. * * @return error code. */ - public long convertUTMToGeodetic(long Zone, String Hemisphere, double Easting, double Northing) - { + public long convertUTMToGeodetic(long Zone, String Hemisphere, double Easting, double Northing) { // TODO: arg checking long Error_Code = UTM_NO_ERROR; double Origin_Latitude = 0; @@ -275,64 +281,68 @@ public long convertUTMToGeodetic(long Zone, String Hemisphere, double Easting, d double False_Northing = 0; double Scale = 0.9996; - if ((Zone < 1) || (Zone > 60)) + if ((Zone < 1) || (Zone > 60)) { Error_Code |= UTM_ZONE_ERROR; - if (!Hemisphere.equals(AVKey.SOUTH) && !Hemisphere.equals(AVKey.NORTH)) + } + if (!Hemisphere.equals(AVKey.SOUTH) && !Hemisphere.equals(AVKey.NORTH)) { Error_Code |= UTM_HEMISPHERE_ERROR; + } // if ((Easting < MIN_EASTING) || (Easting > MAX_EASTING)) //removed check to enable reprojecting images // Error_Code |= UTM_EASTING_ERROR; //that extend into another zone - if ((Northing < MIN_NORTHING) || (Northing > MAX_NORTHING)) + if ((Northing < MIN_NORTHING) || (Northing > MAX_NORTHING)) { Error_Code |= UTM_NORTHING_ERROR; + } - if (Error_Code == UTM_NO_ERROR) - { /* no errors */ - if (Zone >= 31) + if (Error_Code == UTM_NO_ERROR) { + /* no errors */ + if (Zone >= 31) { Central_Meridian = ((6 * Zone - 183) * PI / 180.0 /*+ 0.00000005*/); - else + } else { Central_Meridian = ((6 * Zone + 177) * PI / 180.0 /*+ 0.00000005*/); - if (Hemisphere.equals(AVKey.SOUTH)) + } + if (Hemisphere.equals(AVKey.SOUTH)) { False_Northing = 10000000; - try - { + } + try { TMCoord TM = TMCoord.fromTM(Easting, Northing, - this.globe, Angle.fromRadians(Origin_Latitude), Angle.fromRadians(Central_Meridian), - False_Easting, False_Northing, Scale); + this.globe, Angle.fromRadians(Origin_Latitude), Angle.fromRadians(Central_Meridian), + False_Easting, False_Northing, Scale); Latitude = TM.getLatitude().radians; Longitude = TM.getLongitude().radians; - if ((Latitude < MIN_LAT) || (Latitude > MAX_LAT)) - { /* Latitude out of range */ + if ((Latitude < MIN_LAT) || (Latitude > MAX_LAT)) { + /* Latitude out of range */ Error_Code |= UTM_NORTHING_ERROR; } - } - catch (Exception e) - { + } catch (Exception e) { Error_Code = UTM_TM_ERROR; } } return (Error_Code); } - /** @return Latitude in radians. */ - public double getLatitude() - { + /** + * @return Latitude in radians. + */ + public double getLatitude() { return Latitude; } - /** @return Longitude in radians. */ - public double getLongitude() - { + /** + * @return Longitude in radians. + */ + public double getLongitude() { return Longitude; } - /** @return Central_Meridian in radians. */ - public double getCentralMeridian() - { + /** + * @return Central_Meridian in radians. + */ + public double getCentralMeridian() { return Central_Meridian; } - public static LatLon convertWGS84ToNAD27(Angle latWGS, Angle lonWGS) - { + public static LatLon convertWGS84ToNAD27(Angle latWGS, Angle lonWGS) { double deltaX = -12.0; double deltaY = 130.0; double deltaZ = 190.0; @@ -348,9 +358,9 @@ public static LatLon convertWGS84ToNAD27(Angle latWGS, Angle lonWGS) double Rm = (CLARKE_A * (1 - e2)) / Math.pow(1 - e2 * Math.pow(Math.sin(lat), 2.0), 1.5); double errLon = (-1 * deltaX * Math.sin(lon) + deltaY * Math.cos(lon)) / (Rn * Math.cos(lat)); double errLat = (-1 * deltaX * Math.sin(lat) * Math.cos(lon) - deltaY * Math.sin(lat) * Math.sin(lon) - + deltaZ * Math.cos(lat) - + difA * (Rn * e2 * Math.sin(lat) * Math.cos(lat)) / CLARKE_A - + difF * (Rm * CLARKE_A / CLARKE_B + Rn * CLARKE_B / CLARKE_A) * Math.sin(lat) * Math.cos(lat)) / Rm; + + deltaZ * Math.cos(lat) + + difA * (Rn * e2 * Math.sin(lat) * Math.cos(lat)) / CLARKE_A + + difF * (Rm * CLARKE_A / CLARKE_B + Rn * CLARKE_B / CLARKE_A) * Math.sin(lat) * Math.cos(lat)) / Rm; return LatLon.fromRadians(lat - errLat, lon - errLon); } diff --git a/src/gov/nasa/worldwind/globes/Earth.java b/src/gov/nasa/worldwind/globes/Earth.java index 817376174a..2ac5dd00bc 100644 --- a/src/gov/nasa/worldwind/globes/Earth.java +++ b/src/gov/nasa/worldwind/globes/Earth.java @@ -14,9 +14,8 @@ * @author Tom Gaskins * @version $Id: Earth.java 1958 2014-04-24 19:25:37Z tgaskins $ */ +public class Earth extends EllipsoidalGlobe { -public class Earth extends EllipsoidalGlobe -{ public static final double WGS84_EQUATORIAL_RADIUS = 6378137.0; // ellipsoid equatorial getRadius, in meters public static final double WGS84_POLAR_RADIUS = 6356752.3; // ellipsoid polar getRadius, in meters public static final double WGS84_ES = 0.00669437999013; // eccentricity squared, semi-major axis @@ -24,15 +23,13 @@ public class Earth extends EllipsoidalGlobe public static final double ELEVATION_MIN = -11000d; // Depth of Marianas trench public static final double ELEVATION_MAX = 8500d; // Height of Mt. Everest. - public Earth() - { + public Earth() { super(WGS84_EQUATORIAL_RADIUS, WGS84_POLAR_RADIUS, WGS84_ES, - EllipsoidalGlobe.makeElevationModel(AVKey.EARTH_ELEVATION_MODEL_CONFIG_FILE, - "config/Earth/EarthElevations2.xml")); + EllipsoidalGlobe.makeElevationModel(AVKey.EARTH_ELEVATION_MODEL_CONFIG_FILE, + "config/Earth/EarthElevations2.xml")); } - public String toString() - { + public String toString() { return "Earth"; } } diff --git a/src/gov/nasa/worldwind/globes/EarthFlat.java b/src/gov/nasa/worldwind/globes/EarthFlat.java index d68f2dd52a..dc38756665 100644 --- a/src/gov/nasa/worldwind/globes/EarthFlat.java +++ b/src/gov/nasa/worldwind/globes/EarthFlat.java @@ -14,22 +14,19 @@ * @author Tom Gaskins * @version $Id: EarthFlat.java 1958 2014-04-24 19:25:37Z tgaskins $ */ +public class EarthFlat extends FlatGlobe { -public class EarthFlat extends FlatGlobe -{ public static final double WGS84_EQUATORIAL_RADIUS = 6378137.0; // ellipsoid equatorial getRadius, in meters public static final double WGS84_POLAR_RADIUS = 6356752.3; // ellipsoid polar getRadius, in meters public static final double WGS84_ES = 0.00669437999013; // eccentricity squared, semi-major axis - public EarthFlat() - { + public EarthFlat() { super(WGS84_EQUATORIAL_RADIUS, WGS84_POLAR_RADIUS, WGS84_ES, - EllipsoidalGlobe.makeElevationModel(AVKey.EARTH_ELEVATION_MODEL_CONFIG_FILE, - "config/Earth/EarthElevations2.xml")); + EllipsoidalGlobe.makeElevationModel(AVKey.EARTH_ELEVATION_MODEL_CONFIG_FILE, + "config/Earth/EarthElevations2.xml")); } - public String toString() - { + public String toString() { return "Flat Earth"; } } diff --git a/src/gov/nasa/worldwind/globes/ElevationModel.java b/src/gov/nasa/worldwind/globes/ElevationModel.java index 176c42ff20..f91297a5b0 100644 --- a/src/gov/nasa/worldwind/globes/ElevationModel.java +++ b/src/gov/nasa/worldwind/globes/ElevationModel.java @@ -25,8 +25,8 @@ * @author Tom Gaskins * @version $Id: ElevationModel.java 3420 2015-09-10 23:25:43Z tgaskins $ */ -public interface ElevationModel extends WWObject, Restorable, Disposable -{ +public interface ElevationModel extends WWObject, Restorable, Disposable { + /** * Returns the elevation model's name. * @@ -111,14 +111,14 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * @param sector the sector in question. * * @return 0 if the elevation model fully contains the sector, 1 if the elevation model intersects the sector but - * does not fully contain it, or -1 if the sector does not intersect the elevation model. + * does not fully contain it, or -1 if the sector does not intersect the elevation model. */ int intersects(Sector sector); /** * Indicates whether a specified location is within the elevation model's domain. * - * @param latitude the latitude of the location in question. + * @param latitude the latitude of the location in question. * @param longitude the longitude of the location in question. * * @return true if the location is within the elevation model's domain, otherwise false. @@ -145,12 +145,12 @@ public interface ElevationModel extends WWObject, Restorable, Disposable /** * Returns the minimum and maximum elevations at a specified location. * - * @param latitude the latitude of the location in question. + * @param latitude the latitude of the location in question. * @param longitude the longitude of the location in question. * * @return A two-element double array indicating, respectively, the minimum and maximum elevations at - * the specified location. These values are the global minimum and maximum if the local minimum and maximum - * values are currently unknown. + * the specified location. These values are the global minimum and maximum if the local minimum and maximum values + * are currently unknown. */ double[] getExtremeElevations(Angle latitude, Angle longitude); @@ -160,8 +160,8 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * @param sector the sector in question. * * @return A two-element double array indicating, respectively, the sector's minimum and maximum - * elevations. These elements are the global minimum and maximum if the local minimum and maximum values are - * currently unknown. + * elevations. These elements are the global minimum and maximum if the local minimum and maximum values are + * currently unknown. */ double[] getExtremeElevations(Sector sector); @@ -169,10 +169,10 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * Indicates the best resolution attainable for a specified sector. * * @param sector the sector in question. If null, the elevation model's best overall resolution is returned. This is - * the best attainable at some locations but not necessarily at all locations. + * the best attainable at some locations but not necessarily at all locations. * * @return the best resolution attainable for the specified sector, in radians, or {@link Double#MAX_VALUE} if the - * sector does not intersect the elevation model. + * sector does not intersect the elevation model. */ double getBestResolution(Sector sector); @@ -198,11 +198,11 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * The elevation returned from this method is the best available in memory. If no elevation is in memory, the * elevation model's minimum extreme elevation at the location is returned. Local disk caches are not consulted. * - * @param latitude the latitude of the location in question. + * @param latitude the latitude of the location in question. * @param longitude the longitude of the location in question. * * @return The elevation corresponding to the specified location, or the elevation model's missing-data replacement - * value if there is no elevation for the given location. + * value if there is no elevation for the given location. * * @see #setMissingDataSignal(double) * @see #getUnmappedElevation(gov.nasa.worldwind.geom.Angle, gov.nasa.worldwind.geom.Angle) @@ -214,12 +214,12 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * missing data replacement value. When a missing data signal is found, the signal value is returned, not the * replacement value. * - * @param latitude the latitude of the location for which to return the elevation. + * @param latitude the latitude of the location for which to return the elevation. * @param longitude the longitude of the location for which to return the elevation. * * @return the elevation at the specified location, or the elevation model's missing data signal. If no data is - * currently in memory for the location, and the location is within the elevation model's coverage area, the - * elevation model's minimum elevation at that location is returned. + * currently in memory for the location, and the location is within the elevation model's coverage area, the + * elevation model's minimum elevation at that location is returned. */ double getUnmappedElevation(Angle latitude, Angle longitude); @@ -230,18 +230,17 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * is returned in the output buffer. If a location is outside the elevation model's coverage area, the output buffer * for that location is not modified; it retains the buffer's original value. * - * @param sector the sector in question. - * @param latlons the locations to return elevations for. If a location is null, the output buffer for that - * location is not modified. + * @param sector the sector in question. + * @param latlons the locations to return elevations for. If a location is null, the output buffer for that location + * is not modified. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) - * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and - * contain at least as many elements as the list of locations. + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) + * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and contain at + * least as many elements as the list of locations. * * @return the resolution achieved, in radians, or {@link Double#MAX_VALUE} if individual elevations cannot be - * determined for all of the locations. + * determined for all of the locations. * * @throws IllegalArgumentException if either the sector, latlons list or elevations array is null. * @see #setMissingDataSignal(double) @@ -256,25 +255,25 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * is returned in the output buffer. If a location is outside the elevation model's coverage area, the output buffer * for that location is not modified; it retains the buffer's original value. * - * @param sector the sector in question. - * @param latlons the locations to return elevations for. If a location is null, the output buffer for that - * location is not modified. + * @param sector the sector in question. + * @param latlons the locations to return elevations for. If a location is null, the output buffer for that location + * is not modified. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) This is an array to enable specification of a target resolution per - * elevation model for {@link gov.nasa.worldwind.terrain.CompoundElevationModel}. The - * entries must be in the same order as the elevations in {@link + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) This is an array to enable + * specification of a target resolution per elevation model for + * {@link gov.nasa.worldwind.terrain.CompoundElevationModel}. The entries must be in the same order as the + * elevations in {@link * gov.nasa.worldwind.terrain.CompoundElevationModel}. - * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and - * contain at least as many elements as the list of locations. + * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and contain at + * least as many elements as the list of locations. * * @return the resolutions achieved, in radians, which will be {@link Double#MAX_VALUE} if individual elevations - * cannot be determined for all of the locations. The entries are in the same order as the elevations in - * {@link gov.nasa.worldwind.terrain.CompoundElevationModel}. + * cannot be determined for all of the locations. The entries are in the same order as the elevations in + * {@link gov.nasa.worldwind.terrain.CompoundElevationModel}. * * @throws IllegalArgumentException if either the sector, latlons list, target resolutions array or elevations array - * is null. + * is null. * @see #setMissingDataSignal(double) */ double[] getElevations(Sector sector, List latlons, double targetResolution[], double[] buffer); @@ -286,23 +285,22 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * for that location is returned in the output buffer. If a location is outside the elevation model's coverage area, * the output buffer for that location is not modified; it retains the buffer's original value. * - * @param sector the sector in question. - * @param latlons the locations to return elevations for. If a location is null, the output buffer for that - * location is not modified. + * @param sector the sector in question. + * @param latlons the locations to return elevations for. If a location is null, the output buffer for that location + * is not modified. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) - * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and - * contain at least as many elements as the list of locations. + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) + * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and contain at + * least as many elements as the list of locations. * * @return the resolution achieved, in radians, or {@link Double#MAX_VALUE} if individual elevations cannot be - * determined for all of the locations. + * determined for all of the locations. * * @see #setMissingDataSignal(double) */ double getUnmappedElevations(Sector sector, List latlons, double targetResolution, - double[] buffer); + double[] buffer); /** * Returns the elevations of a collection of locations. Does not replace any elevation values corresponding @@ -311,29 +309,28 @@ public interface ElevationModel extends WWObject, Restorable, Disposable * for that location is returned in the output buffer. If a location is outside the elevation model's coverage area, * the output buffer for that location is not modified; it retains the buffer's original value. * - * @param sector the sector in question. - * @param latlons the locations to return elevations for. If a location is null, the output buffer for that - * location is not modified. + * @param sector the sector in question. + * @param latlons the locations to return elevations for. If a location is null, the output buffer for that location + * is not modified. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) This is an array to enable specification of a target resolution per - * elevation model for {@link gov.nasa.worldwind.terrain.CompoundElevationModel}. The - * entries must be in the same order as the elevations in {@link + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) This is an array to enable + * specification of a target resolution per elevation model for + * {@link gov.nasa.worldwind.terrain.CompoundElevationModel}. The entries must be in the same order as the + * elevations in {@link * gov.nasa.worldwind.terrain.CompoundElevationModel}. - * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and - * contain at least as many elements as the list of locations. + * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and contain at + * least as many elements as the list of locations. * * @return the resolutions achieved, in radians, which will be {@link Double#MAX_VALUE} if individual elevations - * cannot be determined for all of the locations. The entries are in the same order as the elevations in - * {@link gov.nasa.worldwind.terrain.CompoundElevationModel}. + * cannot be determined for all of the locations. The entries are in the same order as the elevations in + * {@link gov.nasa.worldwind.terrain.CompoundElevationModel}. * - * @throws IllegalArgumentException if either the sector, latlons list, target resolutions array or elevations - * array + * @throws IllegalArgumentException if either the sector, latlons list, target resolutions array or elevations array * @see #setMissingDataSignal(double) */ double[] getUnmappedElevations(Sector sector, List latlons, double targetResolution[], - double[] buffer); + double[] buffer); /** * Returns the elevation used for missing values in the elevation model. @@ -357,29 +354,29 @@ public interface ElevationModel extends WWObject, Restorable, Disposable /** * Determines the elevations at specified locations within a specified {@link Sector}. * - * @param sector the sector containing the locations. - * @param latlons the locations for which to return elevations. + * @param sector the sector containing the locations. + * @param latlons the locations for which to return elevations. * @param tileWidth the number of locations that comprise one row in the {@code latlons} argument. - * @param buffer a buffer in which to put the elevations. The buffer must have at least as many elements as the - * number of specified locations. + * @param buffer a buffer in which to put the elevations. The buffer must have at least as many elements as the + * number of specified locations. * - * @throws Exception if the method fails. Different elevation models may fail for different reasons. + * @throws Exception if the method fails. Different elevation models may fail for different reasons. * @throws IllegalArgumentException if either the sector, list of locations or buffer is null, if the buffer size is - * not at least as large as the location list, or the tile width is greater than - * the locations list length or less than 1. + * not at least as large as the location list, or the tile width is greater than the locations list length or less + * than 1. */ void composeElevations(Sector sector, List latlons, int tileWidth, double[] buffer) - throws Exception; + throws Exception; /** * Returns the proportion of this elevation model's data that is local -- in the computer's data cache or installed * data filestore -- for a specified sector and target resolution. * - * @param sector the sector of interest. + * @param sector the sector of interest. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) Specify null to use this elevation model's best resolution. + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) Specify null to use this elevation + * model's best resolution. * * @return the fraction of the data that is local. A value of 1.0 indicates that all the data is available. */ @@ -422,6 +419,7 @@ void composeElevations(Sector sector, List latlons, int tileWi * Returns the elevation for this elevation model's highest level of detail if the source file for that level and * the specified location exists in the local elevation cache on disk. This method is useful only when an elevation * dataset has been pre-cached. + * * @param latitude The latitude of the location whose elevation is desired. * @param longitude The longitude of the location whose elevation is desired. * @return The elevation at the specified location, if that location is contained in this elevation model and the diff --git a/src/gov/nasa/worldwind/globes/EllipsoidalGlobe.java b/src/gov/nasa/worldwind/globes/EllipsoidalGlobe.java index 47aa197606..b19f8fe02d 100644 --- a/src/gov/nasa/worldwind/globes/EllipsoidalGlobe.java +++ b/src/gov/nasa/worldwind/globes/EllipsoidalGlobe.java @@ -26,8 +26,8 @@ * @author Tom Gaskins * @version $Id: EllipsoidalGlobe.java 2295 2014-09-04 17:33:25Z tgaskins $ */ -public class EllipsoidalGlobe extends WWObjectImpl implements Globe -{ +public class EllipsoidalGlobe extends WWObjectImpl implements Globe { + protected final double equatorialRadius; protected final double polarRadius; protected final double es; @@ -41,12 +41,11 @@ public class EllipsoidalGlobe extends WWObjectImpl implements Globe * defined by the {@link AVKey#TESSELLATOR_CLASS_NAME} configuration parameter. * * @param equatorialRadius Radius of the globe at the equator. - * @param polarRadius Radius of the globe at the poles. - * @param es Square of the globe's eccentricity. - * @param em Elevation model. May be null. + * @param polarRadius Radius of the globe at the poles. + * @param es Square of the globe's eccentricity. + * @param em Elevation model. May be null. */ - public EllipsoidalGlobe(double equatorialRadius, double polarRadius, double es, ElevationModel em) - { + public EllipsoidalGlobe(double equatorialRadius, double polarRadius, double es, ElevationModel em) { this.equatorialRadius = equatorialRadius; this.polarRadius = polarRadius; this.es = es; // assume it's consistent with the two radii @@ -60,13 +59,12 @@ public EllipsoidalGlobe(double equatorialRadius, double polarRadius, double es, * defined by the {@link AVKey#TESSELLATOR_CLASS_NAME} configuration parameter. * * @param equatorialRadius Radius of the globe at the equator. - * @param polarRadius Radius of the globe at the poles. - * @param es Square of the globe's eccentricity. - * @param em Elevation model. May be null. - * @param center Cartesian coordinates of the globe's center point. + * @param polarRadius Radius of the globe at the poles. + * @param es Square of the globe's eccentricity. + * @param em Elevation model. May be null. + * @param center Cartesian coordinates of the globe's center point. */ - public EllipsoidalGlobe(double equatorialRadius, double polarRadius, double es, ElevationModel em, Vec4 center) - { + public EllipsoidalGlobe(double equatorialRadius, double polarRadius, double es, ElevationModel em, Vec4 center) { this.equatorialRadius = equatorialRadius; this.polarRadius = polarRadius; this.es = es; // assume it's consistent with the two radii @@ -75,17 +73,15 @@ public EllipsoidalGlobe(double equatorialRadius, double polarRadius, double es, this.tessellator = (Tessellator) WorldWind.createConfigurationComponent(AVKey.TESSELLATOR_CLASS_NAME); } - protected class StateKey implements GlobeStateKey - { + protected class StateKey implements GlobeStateKey { + protected Globe globe; protected final Tessellator tessellator; protected double verticalExaggeration; protected ElevationModel elevationModel; - public StateKey(DrawContext dc) - { - if (dc == null) - { + public StateKey(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -97,46 +93,48 @@ public StateKey(DrawContext dc) this.elevationModel = this.globe.getElevationModel(); } - public StateKey(Globe globe) - { + public StateKey(Globe globe) { this.globe = globe; this.tessellator = EllipsoidalGlobe.this.tessellator; this.verticalExaggeration = 1; this.elevationModel = this.globe.getElevationModel(); } - public Globe getGlobe() - { + public Globe getGlobe() { return this.globe; } @SuppressWarnings({"RedundantIfStatement"}) @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } StateKey stateKey = (StateKey) o; - if (Double.compare(stateKey.verticalExaggeration, verticalExaggeration) != 0) + if (Double.compare(stateKey.verticalExaggeration, verticalExaggeration) != 0) { return false; - if (elevationModel != null ? !elevationModel.equals(stateKey.elevationModel) : - stateKey.elevationModel != null) + } + if (elevationModel != null ? !elevationModel.equals(stateKey.elevationModel) + : stateKey.elevationModel != null) { return false; - if (globe != null ? !globe.equals(stateKey.globe) : stateKey.globe != null) + } + if (globe != null ? !globe.equals(stateKey.globe) : stateKey.globe != null) { return false; - if (tessellator != null ? !tessellator.equals(stateKey.tessellator) : stateKey.tessellator != null) + } + if (tessellator != null ? !tessellator.equals(stateKey.tessellator) : stateKey.tessellator != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; long temp; result = globe != null ? globe.hashCode() : 0; @@ -148,65 +146,52 @@ public int hashCode() } } - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { return this.getGlobeStateKey(dc); } - public GlobeStateKey getGlobeStateKey(DrawContext dc) - { + public GlobeStateKey getGlobeStateKey(DrawContext dc) { return new StateKey(dc); } - public GlobeStateKey getGlobeStateKey() - { + public GlobeStateKey getGlobeStateKey() { return new StateKey(this); } - public Tessellator getTessellator() - { + public Tessellator getTessellator() { return tessellator; } - public void setTessellator(Tessellator tessellator) - { + public void setTessellator(Tessellator tessellator) { this.tessellator = tessellator; } - public ElevationModel getElevationModel() - { + public ElevationModel getElevationModel() { return elevationModel; } - public void setElevationModel(ElevationModel elevationModel) - { + public void setElevationModel(ElevationModel elevationModel) { this.elevationModel = elevationModel; } - public double getRadius() - { + public double getRadius() { return this.equatorialRadius; } - public double getEquatorialRadius() - { + public double getEquatorialRadius() { return this.equatorialRadius; } - public double getPolarRadius() - { + public double getPolarRadius() { return this.polarRadius; } - public double getMaximumRadius() - { + public double getMaximumRadius() { return this.equatorialRadius; } - public double getRadiusAt(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getRadiusAt(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -216,17 +201,14 @@ public double getRadiusAt(Angle latitude, Angle longitude) // observing that the length of the ellipsoidal point at the specified latitude and longitude indicates the // radius at that location. The formula for the length of the ellipsoidal point was then converted into the // simplified form below. - double sinLat = Math.sin(latitude.radians); double rpm = this.equatorialRadius / Math.sqrt(1.0 - this.es * sinLat * sinLat); return rpm * Math.sqrt(1.0 + (this.es * this.es - 2.0 * this.es) * sinLat * sinLat); } - public double getRadiusAt(LatLon location) - { - if (location == null) - { + public double getRadiusAt(LatLon location) { + if (location == null) { String msg = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -235,72 +217,59 @@ public double getRadiusAt(LatLon location) return this.getRadiusAt(location.latitude, location.longitude); } - public double getEccentricitySquared() - { + public double getEccentricitySquared() { return this.es; } - public double getDiameter() - { + public double getDiameter() { return this.equatorialRadius * 2; } - public Vec4 getCenter() - { + public Vec4 getCenter() { return this.center; } - public double getMaxElevation() - { + public double getMaxElevation() { return this.elevationModel != null ? this.elevationModel.getMaxElevation() : 0; } - public double getMinElevation() - { + public double getMinElevation() { // TODO: The value returned might not reflect the globe's actual minimum elevation if the elevation model does // not span the full globe. See WWJINT-435. return this.elevationModel != null ? this.elevationModel.getMinElevation() : 0; } - public double[] getMinAndMaxElevations(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double[] getMinAndMaxElevations(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return this.elevationModel != null ? this.elevationModel.getExtremeElevations(latitude, longitude) - : new double[] {0, 0}; + : new double[]{0, 0}; } - public double[] getMinAndMaxElevations(Sector sector) - { - if (sector == null) - { + public double[] getMinAndMaxElevations(Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - return this.elevationModel != null ? this.elevationModel.getExtremeElevations(sector) : new double[] {0, 0}; + return this.elevationModel != null ? this.elevationModel.getExtremeElevations(sector) : new double[]{0, 0}; } - public Extent getExtent() - { + public Extent getExtent() { return this; } - public double getEffectiveRadius(Plane plane) - { + public double getEffectiveRadius(Plane plane) { return this.getRadius(); } - public boolean intersects(Frustum frustum) - { - if (frustum == null) - { + public boolean intersects(Frustum frustum) { + if (frustum == null) { String message = Logging.getMessage("nullValue.FrustumIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -309,23 +278,20 @@ public boolean intersects(Frustum frustum) return frustum.intersects(new Sphere(Vec4.ZERO, this.getRadius())); } - public Intersection[] intersect(Line line) - { + public Intersection[] intersect(Line line) { return this.intersect(line, this.equatorialRadius, this.polarRadius); } - public Intersection[] intersect(Line line, double altitude) - { + public Intersection[] intersect(Line line, double altitude) { return this.intersect(line, this.equatorialRadius + altitude, this.polarRadius + altitude); } - protected Intersection[] intersect(Line line, double equRadius, double polRadius) - { - if (line == null) + protected Intersection[] intersect(Line line, double equRadius, double polRadius) { + if (line == null) { return null; + } // Taken from Lengyel, 2Ed., Section 5.2.3, page 148. - double m = equRadius / polRadius; // "ratio of the x semi-axis length to the y semi-axis length" double n = 1d; // "ratio of the x semi-axis length to the z semi-axis length" double m2 = m * m; @@ -344,92 +310,99 @@ protected Intersection[] intersect(Line line, double equRadius, double polRadius double c = sx * sx + m2 * sy * sy + n2 * sz * sz - r2; double discriminant = discriminant(a, b, c); - if (discriminant < 0) + if (discriminant < 0) { return null; + } double discriminantRoot = Math.sqrt(discriminant); - if (discriminant == 0) - { + if (discriminant == 0) { Vec4 p = line.getPointAt((-b - discriminantRoot) / (2 * a)); - return new Intersection[] {new Intersection(p, true)}; - } - else // (discriminant > 0) + return new Intersection[]{new Intersection(p, true)}; + } else // (discriminant > 0) { Vec4 near = line.getPointAt((-b - discriminantRoot) / (2 * a)); Vec4 far = line.getPointAt((-b + discriminantRoot) / (2 * a)); if (c >= 0) // Line originates outside the Globe. - return new Intersection[] {new Intersection(near, false), new Intersection(far, false)}; - else // Line originates inside the Globe. - return new Intersection[] {new Intersection(far, false)}; + { + return new Intersection[]{new Intersection(near, false), new Intersection(far, false)}; + } else // Line originates inside the Globe. + { + return new Intersection[]{new Intersection(far, false)}; + } } } - static private double discriminant(double a, double b, double c) - { + static private double discriminant(double a, double b, double c) { return b * b - 4 * a * c; } - public Intersection[] intersect(Triangle t, double elevation) - { - if (t == null) + public Intersection[] intersect(Triangle t, double elevation) { + if (t == null) { return null; + } boolean bA = isPointAboveElevation(t.getA(), elevation); boolean bB = isPointAboveElevation(t.getB(), elevation); boolean bC = isPointAboveElevation(t.getC(), elevation); - if (!(bA ^ bB) && !(bB ^ bC)) + if (!(bA ^ bB) && !(bB ^ bC)) { return null; // all triangle points are either above or below the given elevation - + } Intersection[] inter = new Intersection[2]; int idx = 0; // Assumes that intersect(Line) returns only one intersection when the line // originates inside the ellipsoid at the given elevation. - if (bA ^ bB) - if (bA) + if (bA ^ bB) { + if (bA) { inter[idx++] = intersect(new Line(t.getB(), t.getA().subtract3(t.getB())), elevation)[0]; - else + } else { inter[idx++] = intersect(new Line(t.getA(), t.getB().subtract3(t.getA())), elevation)[0]; + } + } - if (bB ^ bC) - if (bB) + if (bB ^ bC) { + if (bB) { inter[idx++] = intersect(new Line(t.getC(), t.getB().subtract3(t.getC())), elevation)[0]; - else + } else { inter[idx++] = intersect(new Line(t.getB(), t.getC().subtract3(t.getB())), elevation)[0]; + } + } - if (bC ^ bA) - if (bC) + if (bC ^ bA) { + if (bC) { inter[idx] = intersect(new Line(t.getA(), t.getC().subtract3(t.getA())), elevation)[0]; - else + } else { inter[idx] = intersect(new Line(t.getC(), t.getA().subtract3(t.getC())), elevation)[0]; + } + } return inter; } - public boolean intersects(Line line) - { + public boolean intersects(Line line) { //noinspection SimplifiableIfStatement - if (line == null) + if (line == null) { return false; + } return line.distanceTo(this.center) <= this.equatorialRadius; } - public boolean intersects(Plane plane) - { - if (plane == null) + public boolean intersects(Plane plane) { + if (plane == null) { return false; + } double dq1 = plane.dot(this.center); return dq1 <= this.equatorialRadius; } - /** {@inheritDoc} */ - public double getProjectedArea(View view) - { - if (view == null) - { + /** + * {@inheritDoc} + */ + public double getProjectedArea(View view) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -438,26 +411,24 @@ public double getProjectedArea(View view) return WWMath.computeSphereProjectedArea(view, this.getCenter(), this.getRadius()); } - public void applyEGMA96Offsets(String offsetsFilePath) throws IOException - { - if (offsetsFilePath != null) + public void applyEGMA96Offsets(String offsetsFilePath) throws IOException { + if (offsetsFilePath != null) { this.egm96 = new EGM96(offsetsFilePath); - else + } else { this.egm96 = null; + } } public double getElevations(Sector sector, List latlons, double targetResolution, - double[] elevations) - { - if (this.elevationModel == null) + double[] elevations) { + if (this.elevationModel == null) { return 0; + } double resolution = this.elevationModel.getElevations(sector, latlons, targetResolution, elevations); - if (this.egm96 != null) - { - for (int i = 0; i < elevations.length; i++) - { + if (this.egm96 != null) { + for (int i = 0; i < elevations.length; i++) { LatLon latLon = latlons.get(i); elevations[i] = elevations[i] + this.egm96.getOffset(latLon.getLatitude(), latLon.getLongitude()); } @@ -467,17 +438,15 @@ public double getElevations(Sector sector, List latlons, doubl } public double[] getElevations(Sector sector, List latLons, double[] targetResolution, - double[] elevations) - { - if (this.elevationModel == null) - return new double[] {0}; + double[] elevations) { + if (this.elevationModel == null) { + return new double[]{0}; + } double[] resolution = this.elevationModel.getElevations(sector, latLons, targetResolution, elevations); - if (this.egm96 != null) - { - for (int i = 0; i < elevations.length; i++) - { + if (this.egm96 != null) { + for (int i = 0; i < elevations.length; i++) { LatLon latLon = latLons.get(i); elevations[i] = elevations[i] + this.egm96.getOffset(latLon.getLatitude(), latLon.getLongitude()); } @@ -486,30 +455,28 @@ public double[] getElevations(Sector sector, List latLons, dou return resolution; } - public double getElevation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getElevation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.elevationModel == null) + if (this.elevationModel == null) { return 0; + } double elevation = this.elevationModel.getElevation(latitude, longitude); - if (this.egm96 != null) + if (this.egm96 != null) { elevation += this.egm96.getOffset(latitude, longitude); + } return elevation; } - public Vec4 computePointFromPosition(Position position) - { - if (position == null) - { + public Vec4 computePointFromPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -518,10 +485,8 @@ public Vec4 computePointFromPosition(Position position) return this.geodeticToCartesian(position.getLatitude(), position.getLongitude(), position.getElevation()); } - public Vec4 computePointFromLocation(LatLon location) - { - if (location == null) - { + public Vec4 computePointFromLocation(LatLon location) { + if (location == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -530,10 +495,8 @@ public Vec4 computePointFromLocation(LatLon location) return this.geodeticToCartesian(location.getLatitude(), location.getLongitude(), 0); } - public Vec4 computePointFromPosition(LatLon latLon, double metersElevation) - { - if (latLon == null) - { + public Vec4 computePointFromPosition(LatLon latLon, double metersElevation) { + if (latLon == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -542,10 +505,8 @@ public Vec4 computePointFromPosition(LatLon latLon, double metersElevation) return this.geodeticToCartesian(latLon.getLatitude(), latLon.getLongitude(), metersElevation); } - public Vec4 computePointFromPosition(Angle latitude, Angle longitude, double metersElevation) - { - if (latitude == null || longitude == null) - { + public Vec4 computePointFromPosition(Angle latitude, Angle longitude, double metersElevation) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -554,10 +515,8 @@ public Vec4 computePointFromPosition(Angle latitude, Angle longitude, double met return this.geodeticToCartesian(latitude, longitude, metersElevation); } - public Position computePositionFromPoint(Vec4 point) - { - if (point == null) - { + public Position computePositionFromPoint(Vec4 point) { + if (point == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -566,33 +525,30 @@ public Position computePositionFromPoint(Vec4 point) return this.cartesianToGeodetic(point); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void computePointsFromPositions(Sector sector, int numLat, int numLon, double[] metersElevation, Vec4[] out) - { - if (sector == null) - { + public void computePointsFromPositions(Sector sector, int numLat, int numLon, double[] metersElevation, Vec4[] out) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numLat <= 0 || numLon <= 0) - { + if (numLat <= 0 || numLon <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "numLat <= 0 or numLon <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (metersElevation == null) - { + if (metersElevation == null) { String message = Logging.getMessage("nullValue.ElevationsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (out == null) - { + if (out == null) { String message = Logging.getMessage("nullValue.OutputIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -604,15 +560,13 @@ public void computePointsFromPositions(Sector sector, int numLat, int numLon, do /** * Returns the normal to the Globe at the specified position. * - * @param latitude the latitude of the position. + * @param latitude the latitude of the position. * @param longitude the longitude of the position. * * @return the Globe normal at the specified position. */ - public Vec4 computeSurfaceNormalAtLocation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public Vec4 computeSurfaceNormalAtLocation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -628,10 +582,8 @@ public Vec4 computeSurfaceNormalAtLocation(Angle latitude, Angle longitude) * * @return the Globe normal at the specified point. */ - public Vec4 computeSurfaceNormalAtPoint(Vec4 point) - { - if (point == null) - { + public Vec4 computeSurfaceNormalAtPoint(Vec4 point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -647,10 +599,8 @@ public Vec4 computeSurfaceNormalAtPoint(Vec4 point) return new Vec4(x, y, z).normalize3(); } - public Vec4 computeNorthPointingTangentAtLocation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public Vec4 computeNorthPointingTangentAtLocation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -682,21 +632,19 @@ public Vec4 computeNorthPointingTangentAtLocation(Angle latitude, Angle longitud return new Vec4(x, y, z).normalize3(); } - public Matrix computeModelCoordinateOriginTransform(Angle latitude, Angle longitude, double metersElevation) - { + public Matrix computeModelCoordinateOriginTransform(Angle latitude, Angle longitude, double metersElevation) { return this.computeSurfaceOrientationAtPosition(latitude, longitude, metersElevation); } - public Matrix computeModelCoordinateOriginTransform(Position position) - { + public Matrix computeModelCoordinateOriginTransform(Position position) { return this.computeSurfaceOrientationAtPosition(position); } - /** {@inheritDoc} */ - public Matrix computeSurfaceOrientationAtPosition(Angle latitude, Angle longitude, double metersElevation) - { - if (latitude == null || longitude == null) - { + /** + * {@inheritDoc} + */ + public Matrix computeSurfaceOrientationAtPosition(Angle latitude, Angle longitude, double metersElevation) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -705,26 +653,26 @@ public Matrix computeSurfaceOrientationAtPosition(Angle latitude, Angle longitud return this.computeEllipsoidalOrientationAtPosition(latitude, longitude, metersElevation); } - /** {@inheritDoc} */ - public Matrix computeSurfaceOrientationAtPosition(Position position) - { - if (position == null) - { + /** + * {@inheritDoc} + */ + public Matrix computeSurfaceOrientationAtPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return this.computeSurfaceOrientationAtPosition(position.getLatitude(), position.getLongitude(), - position.getElevation()); + position.getElevation()); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Vec4 computeEllipsoidalPointFromPosition(Angle latitude, Angle longitude, double metersElevation) - { - if (latitude == null || longitude == null) - { + public Vec4 computeEllipsoidalPointFromPosition(Angle latitude, Angle longitude, double metersElevation) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -733,27 +681,27 @@ public Vec4 computeEllipsoidalPointFromPosition(Angle latitude, Angle longitude, return this.geodeticToEllipsoidal(latitude, longitude, metersElevation); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Vec4 computeEllipsoidalPointFromPosition(Position position) - { - if (position == null) - { + public Vec4 computeEllipsoidalPointFromPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return this.computeEllipsoidalPointFromPosition(position.getLatitude(), position.getLongitude(), - position.getAltitude()); + position.getAltitude()); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Vec4 computeEllipsoidalPointFromLocation(LatLon location) - { - if (location == null) - { + public Vec4 computeEllipsoidalPointFromLocation(LatLon location) { + if (location == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -762,12 +710,12 @@ public Vec4 computeEllipsoidalPointFromLocation(LatLon location) return this.geodeticToEllipsoidal(location.getLatitude(), location.getLongitude(), 0); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Position computePositionFromEllipsoidalPoint(Vec4 ellipsoidalPoint) - { - if (ellipsoidalPoint == null) - { + public Position computePositionFromEllipsoidalPoint(Vec4 ellipsoidalPoint) { + if (ellipsoidalPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -776,12 +724,12 @@ public Position computePositionFromEllipsoidalPoint(Vec4 ellipsoidalPoint) return this.ellipsoidalToGeodetic(ellipsoidalPoint); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Vec4 computeEllipsoidalNormalAtLocation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public Vec4 computeEllipsoidalNormalAtLocation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -804,10 +752,8 @@ public Vec4 computeEllipsoidalNormalAtLocation(Angle latitude, Angle longitude) @Override public Matrix computeEllipsoidalOrientationAtPosition(Angle latitude, Angle longitude, - double metersElevation) - { - if (latitude == null || longitude == null) - { + double metersElevation) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -826,18 +772,17 @@ public Matrix computeEllipsoidalOrientationAtPosition(Angle latitude, Angle long return transform; } - public Position getIntersectionPosition(Line line) - { - if (line == null) - { + public Position getIntersectionPosition(Line line) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Intersection[] intersections = this.intersect(line); - if (intersections == null) + if (intersections == null) { return null; + } return this.computePositionFromPoint(intersections[0].getIntersectionPoint()); } @@ -848,14 +793,13 @@ public Position getIntersectionPosition(Line line) * coordinate system, and is 90 degrees east of the Z axis and also in the equatorial plane. Sea level is at z = * zero. * - * @param latitude the latitude of the position. - * @param longitude the longitude of the position. + * @param latitude the latitude of the position. + * @param longitude the longitude of the position. * @param metersElevation the number of meters above or below mean sea level. * * @return The Cartesian point corresponding to the input position. */ - protected Vec4 geodeticToCartesian(Angle latitude, Angle longitude, double metersElevation) - { + protected Vec4 geodeticToCartesian(Angle latitude, Angle longitude, double metersElevation) { return this.geodeticToEllipsoidal(latitude, longitude, metersElevation); } @@ -865,18 +809,16 @@ protected Vec4 geodeticToCartesian(Angle latitude, Angle longitude, double meter * coordinate system, and is 90 degrees east of the Z axis and also in the equatorial plane. Sea level is at z = * zero. * - * @param latitude the latitude of the position. - * @param longitude the longitude of the position. + * @param latitude the latitude of the position. + * @param longitude the longitude of the position. * @param metersElevation the number of meters above or below mean sea level. * * @return The ellipsoidal point corresponding to the input position. * * @see #ellipsoidalToGeodetic(gov.nasa.worldwind.geom.Vec4) */ - protected Vec4 geodeticToEllipsoidal(Angle latitude, Angle longitude, double metersElevation) - { - if (latitude == null || longitude == null) - { + protected Vec4 geodeticToEllipsoidal(Angle latitude, Angle longitude, double metersElevation) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -887,8 +829,9 @@ protected Vec4 geodeticToEllipsoidal(Angle latitude, Angle longitude, double met double cosLon = Math.cos(longitude.radians); double sinLon = Math.sin(longitude.radians); - double rpm = // getRadius (in meters) of vertical in prime meridian - this.equatorialRadius / Math.sqrt(1.0 - this.es * sinLat * sinLat); + double rpm + = // getRadius (in meters) of vertical in prime meridian + this.equatorialRadius / Math.sqrt(1.0 - this.es * sinLat * sinLat); double x = (rpm + metersElevation) * cosLat * sinLon; double y = (rpm * (1.0 - this.es) + metersElevation) * sinLat; @@ -911,21 +854,20 @@ protected Vec4 geodeticToEllipsoidal(Angle latitude, Angle longitude, double met * For each grid point within the sector, an elevation value is specified via an array of elevations. The * calculation at each position incorporates the associated elevation. * - * @param sector The sector over which to generate the points. - * @param numLat The number of points to generate latitudinally. - * @param numLon The number of points to generate longitudinally. + * @param sector The sector over which to generate the points. + * @param numLat The number of points to generate latitudinally. + * @param numLon The number of points to generate longitudinally. * @param metersElevation An array of elevations to incorporate in the point calculations. There must be one - * elevation value in the array for each generated point, so the array must have a length of - * at least numLon x numLat. Elevations are read from this array in row major - * order, beginning with the row of minimum latitude. - * @param out An array to hold the computed cartesian points. It must have a length of at least - * numLon x numLat. Points are written to this array in row major order, - * beginning with the row of minimum latitude. + * elevation value in the array for each generated point, so the array must have a length of at least + * numLon x numLat. Elevations are read from this array in row major order, beginning with the row of + * minimum latitude. + * @param out An array to hold the computed cartesian points. It must have a length of at least + * numLon x numLat. Points are written to this array in row major order, beginning with the row of + * minimum latitude. * * @throws IllegalArgumentException If any argument is null, or if numLat or numLon are less than or equal to zero. */ - protected void geodeticToCartesian(Sector sector, int numLat, int numLon, double[] metersElevation, Vec4[] out) - { + protected void geodeticToCartesian(Sector sector, int numLat, int numLon, double[] metersElevation, Vec4[] out) { double minLat = sector.getMinLatitude().radians; double maxLat = sector.getMaxLatitude().radians; double minLon = sector.getMinLongitude().radians; @@ -939,10 +881,11 @@ protected void geodeticToCartesian(Sector sector, int numLat, int numLon, double double[] cosLon = new double[numLon]; double[] sinLon = new double[numLon]; double lon = minLon; - for (int i = 0; i < numLon; i++, lon += deltaLon) - { + for (int i = 0; i < numLon; i++, lon += deltaLon) { if (i == numLon - 1) // explicitly set the last lon to the max longitude to ensure alignment + { lon = maxLon; + } cosLon[i] = Math.cos(lon); sinLon[i] = Math.sin(lon); @@ -951,18 +894,18 @@ protected void geodeticToCartesian(Sector sector, int numLat, int numLon, double // Iterate over the latitude and longitude coordinates in the specified sector, computing the Cartesian point // corresponding to each latitude and longitude. double lat = minLat; - for (int j = 0; j < numLat; j++, lat += deltaLat) - { + for (int j = 0; j < numLat; j++, lat += deltaLat) { if (j == numLat - 1) // explicitly set the last lat to the max latitude to ensure alignment + { lat = maxLat; + } // Latitude is constant for each row. Values that are a function of latitude can be computed once per row. double cosLat = Math.cos(lat); double sinLat = Math.sin(lat); double rpm = this.equatorialRadius / Math.sqrt(1.0 - this.es * sinLat * sinLat); - for (int i = 0; i < numLon; i++) - { + for (int i = 0; i < numLon; i++) { double elev = metersElevation[pos]; double x = (rpm + elev) * cosLat * sinLon[i]; double y = (rpm * (1.0 - this.es) + elev) * sinLat; @@ -1013,7 +956,6 @@ protected void geodeticToCartesian(Sector sector, int numLat, int numLon, double // // return Position.fromRadians(lat, lon, elevation); // } - /** * Compute the geographic position to corresponds to a Cartesian point. * @@ -1023,8 +965,7 @@ protected void geodeticToCartesian(Sector sector, int numLat, int numLon, double * * @see #geodeticToCartesian(gov.nasa.worldwind.geom.Angle, gov.nasa.worldwind.geom.Angle, double) */ - protected Position cartesianToGeodetic(Vec4 cart) - { + protected Position cartesianToGeodetic(Vec4 cart) { return this.ellipsoidalToGeodetic(cart); } @@ -1038,12 +979,10 @@ protected Position cartesianToGeodetic(Vec4 cart) * @see #geodeticToEllipsoidal(gov.nasa.worldwind.geom.Angle, gov.nasa.worldwind.geom.Angle, double) */ @SuppressWarnings({"SuspiciousNameCombination"}) - protected Position ellipsoidalToGeodetic(Vec4 cart) - { + protected Position ellipsoidalToGeodetic(Vec4 cart) { // Contributed by Nathan Kronenfeld. Integrated 1/24/2011. Brings this calculation in line with Vermeille's // most recent update. - if (null == cart) - { + if (null == cart) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1074,30 +1013,23 @@ protected Position ellipsoidalToGeodetic(Vec4 cart) double phi; double evoluteBorderTest = 8 * r * r * r + e4 * p * q; - if (evoluteBorderTest > 0 || q != 0) - { + if (evoluteBorderTest > 0 || q != 0) { double u; - if (evoluteBorderTest > 0) - { + if (evoluteBorderTest > 0) { // Step 2: general case double rad1 = Math.sqrt(evoluteBorderTest); double rad2 = Math.sqrt(e4 * p * q); // 10*e2 is my arbitrary decision of what Vermeille means by "near... the cusps of the evolute". - if (evoluteBorderTest > 10 * e2) - { + if (evoluteBorderTest > 10 * e2) { double rad3 = Math.cbrt((rad1 + rad2) * (rad1 + rad2)); u = r + 0.5 * rad3 + 2 * r * r / rad3; - } - else - { + } else { u = r + 0.5 * Math.cbrt((rad1 + rad2) * (rad1 + rad2)) + 0.5 * Math.cbrt( - (rad1 - rad2) * (rad1 - rad2)); + (rad1 - rad2) * (rad1 - rad2)); } - } - else - { + } else { // Step 3: near evolute double rad1 = Math.sqrt(-evoluteBorderTest); double rad2 = Math.sqrt(-8 * r * r * r); @@ -1115,9 +1047,7 @@ protected Position ellipsoidalToGeodetic(Vec4 cart) h = (k + e2 - 1) * sqrtDDpZZ / k; phi = 2 * Math.atan2(Z, sqrtDDpZZ + D); - } - else - { + } else { // Step 4: singular disk double rad1 = Math.sqrt(1 - e2); double rad2 = Math.sqrt(e2 - p); @@ -1130,18 +1060,13 @@ protected Position ellipsoidalToGeodetic(Vec4 cart) // Compute lambda double lambda; double s2 = Math.sqrt(2); - if ((s2 - 1) * Y < sqrtXXpYY + X) - { + if ((s2 - 1) * Y < sqrtXXpYY + X) { // case 1 - -135deg < lambda < 135deg lambda = 2 * Math.atan2(Y, sqrtXXpYY + X); - } - else if (sqrtXXpYY + Y < (s2 + 1) * X) - { + } else if (sqrtXXpYY + Y < (s2 + 1) * X) { // case 2 - -225deg < lambda < 45deg lambda = -Math.PI * 0.5 + 2 * Math.atan2(X, sqrtXXpYY - Y); - } - else - { + } else { // if (sqrtXXpYY-Y<(s2=1)*X) { // is the test, if needed, but it's not // case 3: - -45deg < lambda < 225deg lambda = Math.PI * 0.5 - 2 * Math.atan2(X, sqrtXXpYY + Y); @@ -1292,14 +1217,11 @@ else if (sqrtXXpYY + Y < (s2 + 1) * X) // return Cylinder.compute(points); // } - public SectorGeometryList tessellate(DrawContext dc) - { - if (this.tessellator == null) - { + public SectorGeometryList tessellate(DrawContext dc) { + if (this.tessellator == null) { this.tessellator = (Tessellator) WorldWind.createConfigurationComponent(AVKey.TESSELLATOR_CLASS_NAME); - if (this.tessellator == null) - { + if (this.tessellator == null) { String msg = Logging.getMessage("Tessellator.TessellatorUnavailable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -1312,35 +1234,33 @@ public SectorGeometryList tessellate(DrawContext dc) /** * Determines whether a point is above a given elevation * - * @param point the Vec4 point to test. + * @param point the Vec4 point to test. * @param elevation the elevation to test for. * * @return true if the given point is above the given elevation. */ - public boolean isPointAboveElevation(Vec4 point, double elevation) - { + public boolean isPointAboveElevation(Vec4 point, double elevation) { //noinspection SimplifiableIfStatement - if (point == null) + if (point == null) { return false; + } return (point.x() * point.x()) / ((this.equatorialRadius + elevation) * (this.equatorialRadius + elevation)) - + (point.y() * point.y()) / ((this.polarRadius + elevation) * (this.polarRadius + elevation)) - + (point.z() * point.z()) / ((this.equatorialRadius + elevation) * (this.equatorialRadius + elevation)) - - 1 > 0; + + (point.y() * point.y()) / ((this.polarRadius + elevation) * (this.polarRadius + elevation)) + + (point.z() * point.z()) / ((this.equatorialRadius + elevation) * (this.equatorialRadius + elevation)) + - 1 > 0; } /** * Construct an elevation model given a key for a configuration source and the source's default value. * - * @param key the key identifying the configuration property in {@link Configuration}. + * @param key the key identifying the configuration property in {@link Configuration}. * @param defaultValue the default value of the property to use if it's not found in {@link Configuration}. * * @return a new elevation model configured according to the configuration source. */ - public static ElevationModel makeElevationModel(String key, String defaultValue) - { - if (key == null) - { + public static ElevationModel makeElevationModel(String key, String defaultValue) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); throw new IllegalArgumentException(msg); } @@ -1348,4 +1268,4 @@ public static ElevationModel makeElevationModel(String key, String defaultValue) Object configSource = Configuration.getStringValue(key, defaultValue); return (ElevationModel) BasicFactory.create(AVKey.ELEVATION_MODEL_FACTORY, configSource); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/globes/FlatGlobe.java b/src/gov/nasa/worldwind/globes/FlatGlobe.java index 65dadb11fd..3bb65bf30d 100644 --- a/src/gov/nasa/worldwind/globes/FlatGlobe.java +++ b/src/gov/nasa/worldwind/globes/FlatGlobe.java @@ -25,24 +25,26 @@ * @author Patrick Murris * @version $Id: FlatGlobe.java 2277 2014-08-28 21:19:37Z dcollins $ */ -public class FlatGlobe extends EllipsoidalGlobe implements Globe2D -{ +public class FlatGlobe extends EllipsoidalGlobe implements Globe2D { + /** * Latitude/Longitude * projection. Also known as the geographic projection, the equirectangular projection, or the Plate Carree * projection. */ public final static String PROJECTION_LAT_LON = "gov.nasa.worldwind.globes.projectionLatLon"; - /** Mercator projection. */ + /** Mercator projection. + */ public final static String PROJECTION_MERCATOR = "gov.nasa.worldwind.globes.projectionMercator"; - /** Sinusoidal projection. */ + /** Sinusoidal projection. + */ public final static String PROJECTION_SINUSOIDAL = "gov.nasa.worldwind.globes.projectionSinusoidal"; - public final static String PROJECTION_MODIFIED_SINUSOIDAL = - "gov.nasa.worldwind.globes.projectionModifiedSinusoidal"; + public final static String PROJECTION_MODIFIED_SINUSOIDAL + = "gov.nasa.worldwind.globes.projectionModifiedSinusoidal"; protected GeographicProjection projection = (GeographicProjection) WorldWind.createComponent( - Configuration.getStringValue(AVKey.GEOGRAPHIC_PROJECTION_CLASS_NAME, - "gov.nasa.worldwind.globes.projections.ProjectionEquirectangular")); + Configuration.getStringValue(AVKey.GEOGRAPHIC_PROJECTION_CLASS_NAME, + "gov.nasa.worldwind.globes.projections.ProjectionEquirectangular")); protected boolean continuous; protected int offset; @@ -53,62 +55,63 @@ public class FlatGlobe extends EllipsoidalGlobe implements Globe2D * #setProjection(GeographicProjection)}. * * @param equatorialRadius Radius of the globe at the equator. - * @param polarRadius Radius of the globe at the poles. - * @param es Square of the globe's eccentricity. - * @param em Elevation model. May be null. + * @param polarRadius Radius of the globe at the poles. + * @param es Square of the globe's eccentricity. + * @param em Elevation model. May be null. */ - public FlatGlobe(double equatorialRadius, double polarRadius, double es, ElevationModel em) - { + public FlatGlobe(double equatorialRadius, double polarRadius, double es, ElevationModel em) { super(equatorialRadius, polarRadius, es, em); } - private class FlatStateKey extends StateKey - { + private class FlatStateKey extends StateKey { + protected GeographicProjection projection; protected double verticalExaggeration; protected int offset; - public FlatStateKey(DrawContext dc) - { + public FlatStateKey(DrawContext dc) { super(dc); this.projection = FlatGlobe.this.getProjection(); this.offset = FlatGlobe.this.offset; } - public FlatStateKey(Globe globe) - { + public FlatStateKey(Globe globe) { super(globe); this.projection = FlatGlobe.this.getProjection(); this.offset = FlatGlobe.this.offset; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; - if (!super.equals(o)) + } + if (!super.equals(o)) { return false; + } FlatStateKey that = (FlatStateKey) o; - if (offset != that.offset) + if (offset != that.offset) { return false; - if (Double.compare(that.verticalExaggeration, verticalExaggeration) != 0) + } + if (Double.compare(that.verticalExaggeration, verticalExaggeration) != 0) { return false; + } //noinspection RedundantIfStatement if (projection != null ? !projection.equals(that.projection) - : that.projection != null) + : that.projection != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = super.hashCode(); long temp; result = 31 * result + (projection != null ? projection.hashCode() : 0); @@ -119,18 +122,15 @@ public int hashCode() } } - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { return this.getGlobeStateKey(dc); } - public GlobeStateKey getGlobeStateKey(DrawContext dc) - { + public GlobeStateKey getGlobeStateKey(DrawContext dc) { return new FlatStateKey(dc); } - public GlobeStateKey getGlobeStateKey() - { + public GlobeStateKey getGlobeStateKey() { return new FlatStateKey(this); } @@ -142,41 +142,28 @@ public GlobeStateKey getGlobeStateKey() * * @deprecated Use {@link #setProjection(GeographicProjection)}. */ - public void setProjection(String projection) - { - if (projection == null) - { + public void setProjection(String projection) { + if (projection == null) { String message = Logging.getMessage("nullValue.GeographicProjectionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (projection.equals(PROJECTION_LAT_LON)) - { + if (projection.equals(PROJECTION_LAT_LON)) { this.setProjection(new ProjectionEquirectangular()); - } - else if (projection.equals(PROJECTION_MERCATOR)) - { + } else if (projection.equals(PROJECTION_MERCATOR)) { this.setProjection(new ProjectionMercator()); - } - else if (projection.equals(PROJECTION_SINUSOIDAL)) - { + } else if (projection.equals(PROJECTION_SINUSOIDAL)) { this.setProjection(new ProjectionSinusoidal()); - } - else if (projection.equals(PROJECTION_MODIFIED_SINUSOIDAL)) - { + } else if (projection.equals(PROJECTION_MODIFIED_SINUSOIDAL)) { this.setProjection(new ProjectionModifiedSinusoidal()); - } - else - { + } else { this.setProjection(new ProjectionEquirectangular()); } } - public void setProjection(GeographicProjection projection) - { - if (projection == null) - { + public void setProjection(GeographicProjection projection) { + if (projection == null) { String message = Logging.getMessage("nullValue.GeographicProjectionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -192,54 +179,45 @@ public void setProjection(GeographicProjection projection) * * @see #setProjection */ - public GeographicProjection getProjection() - { + public GeographicProjection getProjection() { return this.projection; } @Override - public void setContinuous(boolean continuous) - { + public void setContinuous(boolean continuous) { this.continuous = continuous; } @Override - public boolean isContinuous() - { + public boolean isContinuous() { return this.continuous || (this.projection != null && this.projection.isContinuous()); } - public int getOffset() - { + public int getOffset() { return offset; } - public void setOffset(int offset) - { + public void setOffset(int offset) { this.offset = offset; this.offsetVector = new Vec4(2.0 * Math.PI * this.equatorialRadius * this.offset, 0, 0); } - public boolean intersects(Frustum frustum) - { - if (frustum == null) - { + public boolean intersects(Frustum frustum) { + if (frustum == null) { String message = Logging.getMessage("nullValue.FrustumIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return Sector.computeBoundingBox(this, 1.0, Sector.FULL_SPHERE, this.getMinElevation(), - this.getMaxElevation()).intersects(frustum); + this.getMaxElevation()).intersects(frustum); } @Override - protected Intersection[] intersect(Line line, double equRadius, double polarRadius) - { + protected Intersection[] intersect(Line line, double equRadius, double polarRadius) { // Flat World Note: plane/line intersection point (OK) // Flat World Note: extract altitude from equRadius by subtracting this.equatorialRadius (OK) - if (line == null) - { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -247,26 +225,28 @@ protected Intersection[] intersect(Line line, double equRadius, double polarRadi // Intersection with world plane Plane plane = new Plane(0, 0, 1, -(equRadius - this.equatorialRadius)); // Flat globe plane Vec4 p = plane.intersect(line); - if (p == null) + if (p == null) { return null; + } // Check if we are in the world boundaries Position pos = this.computePositionFromPoint(p); - if (pos == null) + if (pos == null) { return null; - if (pos.getLatitude().degrees < -90 || pos.getLatitude().degrees > 90) + } + if (pos.getLatitude().degrees < -90 || pos.getLatitude().degrees > 90) { return null; - if (!this.isContinuous() && (pos.getLongitude().degrees < -180 || pos.getLongitude().degrees > 180)) + } + if (!this.isContinuous() && (pos.getLongitude().degrees < -180 || pos.getLongitude().degrees > 180)) { return null; + } - return new Intersection[] {new Intersection(p, false)}; + return new Intersection[]{new Intersection(p, false)}; } @Override - public boolean intersects(Line line) - { + public boolean intersects(Line line) { // Flat World Note: plane/line intersection test (OK) - if (line == null) - { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -276,11 +256,9 @@ public boolean intersects(Line line) } @Override - public boolean intersects(Plane plane) - { + public boolean intersects(Plane plane) { // Flat World Note: plane/plane intersection test (OK) - if (plane == null) - { + if (plane == null) { String msg = Logging.getMessage("nullValue.PlaneIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -291,11 +269,9 @@ public boolean intersects(Plane plane) } @Override - public Vec4 computeSurfaceNormalAtLocation(Angle latitude, Angle longitude) - { + public Vec4 computeSurfaceNormalAtLocation(Angle latitude, Angle longitude) { // Flat World Note: return constant (OK) - if (latitude == null || longitude == null) - { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -305,11 +281,9 @@ public Vec4 computeSurfaceNormalAtLocation(Angle latitude, Angle longitude) } @Override - public Vec4 computeSurfaceNormalAtPoint(Vec4 point) - { + public Vec4 computeSurfaceNormalAtPoint(Vec4 point) { // Flat World Note: return constant (OK) - if (point == null) - { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -319,10 +293,8 @@ public Vec4 computeSurfaceNormalAtPoint(Vec4 point) } @Override - public Vec4 computeNorthPointingTangentAtLocation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public Vec4 computeNorthPointingTangentAtLocation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -332,10 +304,8 @@ public Vec4 computeNorthPointingTangentAtLocation(Angle latitude, Angle longitud } @Override - public Matrix computeSurfaceOrientationAtPosition(Angle latitude, Angle longitude, double metersElevation) - { - if (latitude == null || longitude == null) - { + public Matrix computeSurfaceOrientationAtPosition(Angle latitude, Angle longitude, double metersElevation) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -354,18 +324,17 @@ public Matrix computeSurfaceOrientationAtPosition(Angle latitude, Angle longitud } @Override - public double getElevation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getElevation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Flat World Note: return zero if outside the lat/lon normal boundaries (OK) - if (latitude.degrees < -90 || latitude.degrees > 90 || longitude.degrees < -180 || longitude.degrees > 180) + if (latitude.degrees < -90 || latitude.degrees > 90 || longitude.degrees < -180 || longitude.degrees > 180) { return 0d; + } return super.getElevation(latitude, longitude); } @@ -376,52 +345,47 @@ public double getElevation(Angle latitude, Angle longitude) * system, and points east. Latitude and longitude zero are at the origin on y and x respectively. Sea level is at z * = zero. * - * @param latitude the latitude of the position. - * @param longitude the longitude of the position. + * @param latitude the latitude of the position. + * @param longitude the longitude of the position. * @param metersElevation the number of meters above or below mean sea level. * * @return The Cartesian point corresponding to the input position. */ @Override - protected Vec4 geodeticToCartesian(Angle latitude, Angle longitude, double metersElevation) - { - if (latitude == null || longitude == null) - { + protected Vec4 geodeticToCartesian(Angle latitude, Angle longitude, double metersElevation) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return this.projection.geographicToCartesian(this, latitude, longitude, metersElevation, - this.offsetVector); + this.offsetVector); } @Override - protected void geodeticToCartesian(Sector sector, int numLat, int numLon, double[] metersElevation, Vec4[] out) - { + protected void geodeticToCartesian(Sector sector, int numLat, int numLon, double[] metersElevation, Vec4[] out) { this.projection.geographicToCartesian(this, sector, numLat, numLon, metersElevation, this.offsetVector, out); } @Override - protected Position cartesianToGeodetic(Vec4 cart) - { - if (cart == null) - { + protected Position cartesianToGeodetic(Vec4 cart) { + if (cart == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Position pos = this.projection.cartesianToGeographic(this, cart, this.offsetVector); - if (this.isContinuous()) - { + if (this.isContinuous()) { // Wrap if the globe is continuous. - if (pos.getLongitude().degrees < -180) + if (pos.getLongitude().degrees < -180) { pos = Position.fromDegrees(pos.getLatitude().degrees, pos.getLongitude().degrees + 360, - pos.getAltitude()); - else if (pos.getLongitude().degrees > 180) + pos.getAltitude()); + } else if (pos.getLongitude().degrees > 180) { pos = Position.fromDegrees(pos.getLatitude().degrees, pos.getLongitude().degrees - 360, - pos.getAltitude()); + pos.getAltitude()); + } } return pos; @@ -476,20 +440,19 @@ else if (pos.getLongitude().degrees > 180) // // return new Cylinder(centroidBot, centroidTop, radius); // } - /** * Determines whether a point is above a given elevation * - * @param point the Vec4 point to test. + * @param point the Vec4 point to test. * @param elevation the elevation to test for. * * @return true if the given point is above the given elevation. */ - public boolean isPointAboveElevation(Vec4 point, double elevation) - { + public boolean isPointAboveElevation(Vec4 point, double elevation) { //noinspection SimplifiableIfStatement - if (point == null) + if (point == null) { return false; + } return point.z() > elevation; } diff --git a/src/gov/nasa/worldwind/globes/GeographicProjection.java b/src/gov/nasa/worldwind/globes/GeographicProjection.java index d192b745b5..223cffed77 100644 --- a/src/gov/nasa/worldwind/globes/GeographicProjection.java +++ b/src/gov/nasa/worldwind/globes/GeographicProjection.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes; import gov.nasa.worldwind.geom.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: GeographicProjection.java 2277 2014-08-28 21:19:37Z dcollins $ */ -public interface GeographicProjection -{ +public interface GeographicProjection { + /** * Returns the projection name. * @@ -31,8 +30,7 @@ public interface GeographicProjection * Indicates whether it makes sense to treat this projection as contiguous with itself. If true, the scene * controller will make the globe using the projection appear to scroll continuously horizontally. * - * @return true if it makes sense to treat this projection as continuous, otherwise - * false. + * @return true if it makes sense to treat this projection as continuous, otherwise false. */ boolean isContinuous(); @@ -49,7 +47,7 @@ public interface GeographicProjection * @param projectionLimits The projection limits. * * @throws IllegalArgumentException if the specified limits is null or the limits are outside the normal range of - * latitude or longitude. + * latitude or longitude. */ void setProjectionLimits(Sector projectionLimits); @@ -59,13 +57,12 @@ public interface GeographicProjection * Note: The input arguments are not checked for null prior to being used. The caller, typically a * {@link Globe2D} implementation, is expected do perform that check prior to calling this method. * - * @param globe The globe this projection is applied to. - * @param latitude The latitude of the position. - * @param longitude The longitude of the position. + * @param globe The globe this projection is applied to. + * @param latitude The latitude of the position. + * @param longitude The longitude of the position. * @param metersElevation The elevation of the position, in meters. - * @param offset An optional offset to be applied to the Cartesian output. Typically only projections that - * are continuous (see {@link #isContinuous()} apply this offset. Others ignore it. May be - * null. + * @param offset An optional offset to be applied to the Cartesian output. Typically only projections that are + * continuous (see {@link #isContinuous()} apply this offset. Others ignore it. May be null. * * @return The Cartesian point, in meters, corresponding to the input position. * @@ -84,23 +81,22 @@ public interface GeographicProjection * For each grid point within the sector, an elevation value is specified via an array of elevations. The * calculation at each position incorporates the associated elevation. * - * @param globe The globe this projection is applied to. - * @param sector The sector over which to generate the points. - * @param numLat The number of points to generate latitudinally. - * @param numLon The number of points to generate longitudinally. + * @param globe The globe this projection is applied to. + * @param sector The sector over which to generate the points. + * @param numLat The number of points to generate latitudinally. + * @param numLon The number of points to generate longitudinally. * @param metersElevation An array of elevations to incorporate in the point calculations. There must be one - * elevation value in the array for each generated point, so the array must have a length of - * at least numLon x numLat. Elevations are read from this array in row major - * order, beginning with the row of minimum latitude. - * @param offset An optional offset to be applied to the Cartesian output. Typically only projections that - * are continuous (see {@link #isContinuous()} apply this offset. Others ignore it. May be - * null. - * @param out An array to hold the computed cartesian points. It must have a length of at least - * numLon x numLat. Points are written to this array in row major order, - * beginning with the row of minimum latitude. + * elevation value in the array for each generated point, so the array must have a length of at least + * numLon x numLat. Elevations are read from this array in row major order, beginning with the row of + * minimum latitude. + * @param offset An optional offset to be applied to the Cartesian output. Typically only projections that are + * continuous (see {@link #isContinuous()} apply this offset. Others ignore it. May be null. + * @param out An array to hold the computed cartesian points. It must have a length of at least + * numLon x numLat. Points are written to this array in row major order, beginning with the row of + * minimum latitude. */ void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, double[] metersElevation, - Vec4 offset, Vec4[] out); + Vec4 offset, Vec4[] out); /** * Converts a Cartesian point in meters to a geographic position. @@ -108,16 +104,15 @@ void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, d * Note: The input arguments are not checked for null prior to being used. The caller, typically a * {@link Globe2D} implementation, is expected do perform that check prior to calling this method. * - * @param globe The globe this projection is applied to. - * @param cart The Cartesian point, in meters. + * @param globe The globe this projection is applied to. + * @param cart The Cartesian point, in meters. * @param offset An optional offset to be applied to the Cartesian input prior to converting it. Typically only - * projections that are continuous (see {@link #isContinuous()} apply this offset. Others ignore it. - * May be null. + * projections that are continuous (see {@link #isContinuous()} apply this offset. Others ignore it. May be null. * * @return The geographic position corresponding to the input point. * * @see #geographicToCartesian(Globe, gov.nasa.worldwind.geom.Angle, gov.nasa.worldwind.geom.Angle, double, - * gov.nasa.worldwind.geom.Vec4) + * gov.nasa.worldwind.geom.Vec4) */ Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset); @@ -125,8 +120,8 @@ void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, d * Computes a Cartesian vector that points north and is tangent to the meridian at the specified geographic * location. * - * @param globe The globe this projection is applied to. - * @param latitude The latitude of the location. + * @param globe The globe this projection is applied to. + * @param latitude The latitude of the location. * @param longitude The longitude of the location. * * @return The north pointing tangent corresponding to the input location. diff --git a/src/gov/nasa/worldwind/globes/Globe.java b/src/gov/nasa/worldwind/globes/Globe.java index 4bbdc0a5c6..1ae480c7f7 100644 --- a/src/gov/nasa/worldwind/globes/Globe.java +++ b/src/gov/nasa/worldwind/globes/Globe.java @@ -43,8 +43,8 @@ * @author Tom Gaskins * @version $Id: Globe.java 2295 2014-09-04 17:33:25Z tgaskins $ */ -public interface Globe extends WWObject, Extent -{ +public interface Globe extends WWObject, Extent { + /** * Indicates the spatial volume contained by this globe. * @@ -76,7 +76,7 @@ public interface Globe extends WWObject, Extent /** * Indicates the radius in meters of the globe's ellipsoid at a location. * - * @param latitude Latitude of the location at which to determine radius. + * @param latitude Latitude of the location at which to determine radius. * @param longitude Longitude of the location at which to determine radius. * * @return The radius in meters of the globe's ellipsoid at the specified location. @@ -91,11 +91,11 @@ public interface Globe extends WWObject, Extent * The elevation returned from this method is the best available in memory. If no elevation is in memory, the * elevation model's minimum extreme elevation at the location is returned. Local disk caches are not consulted. * - * @param latitude the latitude of the location at which to determine elevation. + * @param latitude the latitude of the location at which to determine elevation. * @param longitude the longitude of the location at which to determine elevation. * * @return The elevation corresponding to the specified location, or the elevation model's missing-data replacement - * value if there is no elevation for the given location. Returns zero if no elevation model is available. + * value if there is no elevation for the given location. Returns zero if no elevation model is available. * * @see #getElevationModel() */ @@ -108,18 +108,17 @@ public interface Globe extends WWObject, Extent * is returned in the output buffer. If a location is outside the elevation model's coverage area, the output buffer * for that location is not modified; it retains the buffer's original value. * - * @param sector the sector in question. - * @param latlons the locations to return elevations for. If a location is null, the output buffer for that - * location is not modified. + * @param sector the sector in question. + * @param latlons the locations to return elevations for. If a location is null, the output buffer for that location + * is not modified. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) - * @param elevations an array in which to place the returned elevations. The array must be pre-allocated and - * contain at least as many elements as the list of locations. + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) + * @param elevations an array in which to place the returned elevations. The array must be pre-allocated and contain + * at least as many elements as the list of locations. * * @return the resolution achieved, in radians, or {@link Double#MAX_VALUE} if individual elevations cannot be - * determined for all of the locations. Returns zero if an elevation model is not available. + * determined for all of the locations. Returns zero if an elevation model is not available. * * @throws IllegalArgumentException if either the sector, latlons list or elevations array is null. * @see #getElevationModel() @@ -133,26 +132,25 @@ public interface Globe extends WWObject, Extent * is returned in the output buffer. If a location is outside the elevation model's coverage area, the output buffer * for that location is not modified; it retains the buffer's original value. * - * @param sector the sector in question. - * @param latlons the locations to return elevations for. If a location is null, the output buffer for that - * location is not modified. + * @param sector the sector in question. + * @param latlons the locations to return elevations for. If a location is null, the output buffer for that location + * is not modified. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) This parameter is an array to allow varying resolutions to be specified for - * {@link CompoundElevationModel}. - * @param elevations an array in which to place the returned elevations. The array must be pre-allocated and - * contain at least as many elements as the list of locations. + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) This parameter is an array to allow + * varying resolutions to be specified for {@link CompoundElevationModel}. + * @param elevations an array in which to place the returned elevations. The array must be pre-allocated and contain + * at least as many elements as the list of locations. * * @return the resolution achieved, in radians, or {@link Double#MAX_VALUE} if individual elevations cannot be - * determined for all of the locations. Returns zero if an elevation model is not available. + * determined for all of the locations. Returns zero if an elevation model is not available. * * @throws IllegalArgumentException if either the sector, latlons list, target resolutions array or elevations array - * is null. + * is null. * @see #getElevationModel() */ double[] getElevations(Sector sector, List latlons, double[] targetResolution, - double[] elevations); + double[] elevations); /** * Indicates the maximum elevation on this globe, in meters. @@ -174,8 +172,8 @@ public interface Globe extends WWObject, Extent * @param line the line with which to intersect this globe. * * @return the geographic position of the intersection of this globe and specified line. If there are multiple - * intersections the intersection nearest to the line's origin is returned. The intersection may be a - * tangent. Returns null if the line does not intersect this globe. + * intersections the intersection nearest to the line's origin is returned. The intersection may be a tangent. + * Returns null if the line does not intersect this globe. */ Position getIntersectionPosition(Line line); @@ -190,8 +188,8 @@ public interface Globe extends WWObject, Extent /** * Computes a cartesian point from a latitude, longitude, and elevation. * - * @param latitude Latitude of the location to convert to cartesian. - * @param longitude Longitude of the location to convert to cartesian. + * @param latitude Latitude of the location to convert to cartesian. + * @param longitude Longitude of the location to convert to cartesian. * @param metersElevation Elevation, in meters, of the geographic position to convert to cartesian. * * @return The cartesian point that corresponds to the specified geographic position. @@ -201,7 +199,7 @@ public interface Globe extends WWObject, Extent /** * Computes a cartesian point from a geographic location and elevation. * - * @param latLon Geographic location to convert to cartesian. + * @param latLon Geographic location to convert to cartesian. * @param metersElevation Elevation, in meters, of the geographic position to convert to cartesian. * * @return The cartesian point that corresponds to the specified geographic position. @@ -212,7 +210,7 @@ public interface Globe extends WWObject, Extent * Computes a cartesian point from a geographic position. * * @param position Geographic position to convert to cartesian. The position may include elevation above or below - * the globe's surface. + * the globe's surface. * * @return The cartesian point that corresponds to the specified geographic position. */ @@ -247,16 +245,16 @@ public interface Globe extends WWObject, Extent * For each grid point within the sector, an elevation value is specified via an array of elevations. The * calculation at each position incorporates the associated elevation. * - * @param sector The sector over which to generate the points. - * @param numLat The number of points to generate latitudinally. - * @param numLon The number of points to generate longitudinally. + * @param sector The sector over which to generate the points. + * @param numLat The number of points to generate latitudinally. + * @param numLon The number of points to generate longitudinally. * @param metersElevation An array of elevations to incorporate in the point calculations. There must be one - * elevation value in the array for each generated point, so the array must have a length of - * at least numLon x numLat. Elevations are read from this array in row major - * order, beginning with the row of minimum latitude. - * @param out An array to hold the computed cartesian points. It must have a length of at least - * numLon x numLat. Points are written to this array in row major order, - * beginning with the row of minimum latitude. + * elevation value in the array for each generated point, so the array must have a length of at least + * numLon x numLat. Elevations are read from this array in row major order, beginning with the row of + * minimum latitude. + * @param out An array to hold the computed cartesian points. It must have a length of at least + * numLon x numLat. Points are written to this array in row major order, beginning with the row of + * minimum latitude. * * @throws IllegalArgumentException If any argument is null, or if numLat or numLon are less than or equal to zero. */ @@ -265,7 +263,7 @@ public interface Globe extends WWObject, Extent /** * Computes a vector perpendicular to the surface of this globe in cartesian coordinates. * - * @param latitude Latitude of the location at which to compute the normal vector. + * @param latitude Latitude of the location at which to compute the normal vector. * @param longitude Longitude of the location at which to compute the normal vector. * * @return A vector perpendicular to the surface of this globe, at the specified location. @@ -284,11 +282,11 @@ public interface Globe extends WWObject, Extent /** * Computes a vector tangent to this globe and pointing toward the north pole. * - * @param latitude Latitude of the location at which to compute the tangent vector. + * @param latitude Latitude of the location at which to compute the tangent vector. * @param longitude Longitude of the location at which to compute the tangent vector. * * @return A vector tangent to this globe at (latitude, longitude), and pointing toward the north pole of this - * globe. + * globe. */ Vec4 computeNorthPointingTangentAtLocation(Angle latitude, Angle longitude); @@ -302,7 +300,7 @@ public interface Globe extends WWObject, Extent Matrix computeModelCoordinateOriginTransform(Angle latitude, Angle longitude, double metersElevation); /** - * @see #computeSurfaceOrientationAtPosition(gov.nasa.worldwind.geom.Position) + * @see #computeSurfaceOrientationAtPosition(gov.nasa.worldwind.geom.Position) * @param position See computeSurfaceOrientationAtPosition. * @return See computeSurfaceOrientationAtPosition. */ @@ -315,12 +313,12 @@ public interface Globe extends WWObject, Extent * globe normal at (latitude, longitude, metersElevation). The origin is mapped to the cartesian position of * (latitude, longitude, metersElevation). * - * @param latitude the latitude of the position. - * @param longitude the longitude of the position. + * @param latitude the latitude of the position. + * @param longitude the longitude of the position. * @param metersElevation the number of meters above or below mean sea level. * * @return the cartesian transform matrix that maps model coordinates to the local coordinate system at the - * specified position. + * specified position. */ Matrix computeSurfaceOrientationAtPosition(Angle latitude, Angle longitude, double metersElevation); @@ -334,7 +332,7 @@ public interface Globe extends WWObject, Extent * @param position the latitude, longitude, and number of meters above or below mean sea level. * * @return The cartesian transform matrix that maps model coordinates to the local coordinate system at the - * specified position. + * specified position. */ Matrix computeSurfaceOrientationAtPosition(Position position); @@ -345,14 +343,13 @@ public interface Globe extends WWObject, Extent * point on the ellipsoid in 3D cartesian coordinates that corresponds to the specified position. Calling this * method on an instance of Globe2D will return a point on the ellipsoid defined by the 2D globe's radii. * - * @param latitude Latitude of the location to convert. - * @param longitude Longitude of the location to convert. + * @param latitude Latitude of the location to convert. + * @param longitude Longitude of the location to convert. * @param metersElevation Elevation, in meters, of the geographic position to convert. * * @return The ellipsoidal point that corresponds to the specified geographic position. * - * @throws java.lang.IllegalArgumentException - * if the specified latitude or longitude is null. + * @throws java.lang.IllegalArgumentException if the specified latitude or longitude is null. */ Vec4 computeEllipsoidalPointFromPosition(Angle latitude, Angle longitude, double metersElevation); @@ -382,8 +379,7 @@ public interface Globe extends WWObject, Extent * * @return The ellipsoidal point that corresponds to the specified geographic position. * - * @throws java.lang.IllegalArgumentException - * if the specified position is null. + * @throws java.lang.IllegalArgumentException if the specified position is null. */ Vec4 computeEllipsoidalPointFromPosition(Position position); @@ -395,7 +391,7 @@ public interface Globe extends WWObject, Extent * instance of Globe2D will return a position corresponding to the ellipsoid defined by the 2D globe's radii. * * @param ellipsoidalPoint Point of which to find the geographic position, relative to the ellipsoid defined by the - * globe's radii. + * globe's radii. * * @return The geographic position of the specified ellipsoidal point. */ @@ -409,11 +405,11 @@ public interface Globe extends WWObject, Extent * vector normal to the corresponding ellipsoid in 3D cartesian coordinates. Calling this method on an instance of * Globe2D will return a vector normal to the ellipsoid defined by the 2D globe's radii. * - * @param latitude Latitude of the location at which to compute the normal vector. + * @param latitude Latitude of the location at which to compute the normal vector. * @param longitude Longitude of the location at which to compute the normal vector. * * @return A vector perpendicular to the surface of the ellipsoid specified by this globe, at the specified - * location. + * location. * * @throws IllegalArgumentException if either angle is null. */ @@ -430,14 +426,13 @@ public interface Globe extends WWObject, Extent * transform matrix appropriate for the corresponding ellipsoid in 3D cartesian coordinates. Calling this method on * an instance of Globe2D will return a transform matrix for the ellipsoid defined by the 2D globe's radii. * - * @param latitude the latitude of the position. - * @param longitude the longitude of the position. + * @param latitude the latitude of the position. + * @param longitude the longitude of the position. * @param metersElevation the number of meters above or below mean sea level. * * @return The cartesian transform matrix that maps model coordinates to the ellipsoidal coordinate system at the - * specified position. + * specified position. */ - Matrix computeEllipsoidalOrientationAtPosition(Angle latitude, Angle longitude, double metersElevation); /** @@ -453,12 +448,12 @@ public interface Globe extends WWObject, Extent * Returns the minimum and maximum elevations at a specified location on this Globe. This returns a two-element * array filled with zero if this Globe has no elevation model. * - * @param latitude the latitude of the location in question. + * @param latitude the latitude of the location in question. * @param longitude the longitude of the location in question. * * @return A two-element double array indicating the minimum and maximum elevations at the specified - * location, respectively. These values are the global minimum and maximum if the local minimum and maximum - * values are currently unknown, or zero if this Globe has no elevation model. + * location, respectively. These values are the global minimum and maximum if the local minimum and maximum values + * are currently unknown, or zero if this Globe has no elevation model. */ double[] getMinAndMaxElevations(Angle latitude, Angle longitude); @@ -469,8 +464,8 @@ public interface Globe extends WWObject, Extent * @param sector the sector in question. * * @return A two-element double array indicating the sector's minimum and maximum elevations, - * respectively. These elements are the global minimum and maximum if the local minimum and maximum values - * are currently unknown, or zero if this Globe has no elevation model. + * respectively. These elements are the global minimum and maximum if the local minimum and maximum values are + * currently unknown, or zero if this Globe has no elevation model. */ double[] getMinAndMaxElevations(Sector sector); @@ -478,9 +473,9 @@ public interface Globe extends WWObject, Extent * Intersects a specified line with this globe. Only the ellipsoid itself is considered; terrain elevations are not * incorporated. * - * @param line the line to intersect. + * @param line the line to intersect. * @param altitude a distance in meters to expand the globe's equatorial and polar radii prior to performing the - * intersection. + * intersection. * * @return the intersection points, or null if no intersection occurs or the line is null. */ @@ -492,7 +487,7 @@ public interface Globe extends WWObject, Extent * * @param triangle the triangle to intersect. * @param altitude a distance in meters to expand the globe's equatorial and polar radii prior to performing the - * intersection. + * intersection. * * @return the intersection points, or null if no intersection occurs or triangle is null. */ @@ -574,7 +569,7 @@ public interface Globe extends WWObject, Extent /** * Determines whether a point is above a given elevation. * - * @param point the Vec4 point to test. If null, this method returns false. + * @param point the Vec4 point to test. If null, this method returns false. * @param elevation the elevation to test for. * * @return true if the given point is above the given elevation, otherwise false. diff --git a/src/gov/nasa/worldwind/globes/Globe2D.java b/src/gov/nasa/worldwind/globes/Globe2D.java index 3644ca2f9a..ab56fc6d27 100644 --- a/src/gov/nasa/worldwind/globes/Globe2D.java +++ b/src/gov/nasa/worldwind/globes/Globe2D.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes; /** @@ -12,15 +11,15 @@ * @author tag * @version $Id: Globe2D.java 2158 2014-07-19 00:00:57Z pabercrombie $ */ -public interface Globe2D -{ +public interface Globe2D { + /** * Specifies whether to treat the associated projection as contiguous with itself. If true, the scene controller * will make the implementing globe appear to scroll continuously horizontally. Calling this method overrides the * associated projection's value for this field. * * @param continuous true if it makes sense to treat the associated projection as continuous, otherwise - * false. + * false. * * @see gov.nasa.worldwind.globes.GeographicProjection#isContinuous() */ @@ -31,7 +30,7 @@ public interface Globe2D * controller will make the implementing globe appear to scroll continuously horizontally. * * @return true if it makes sense to treat the associated projection as continuous, otherwise - * false. + * false. */ boolean isContinuous(); diff --git a/src/gov/nasa/worldwind/globes/GlobeStateKey.java b/src/gov/nasa/worldwind/globes/GlobeStateKey.java index ddcf70d5d6..699c9354b4 100644 --- a/src/gov/nasa/worldwind/globes/GlobeStateKey.java +++ b/src/gov/nasa/worldwind/globes/GlobeStateKey.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes; /** @@ -13,12 +12,12 @@ * @author tag * @version $Id: GlobeStateKey.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface GlobeStateKey -{ +public interface GlobeStateKey { + /** * Indicates the globe associated with this state key. * * @return the globe associated with this state key. */ Globe getGlobe(); -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/globes/package-info.java b/src/gov/nasa/worldwind/globes/package-info.java index 09b9b8fd1a..482656717b 100644 --- a/src/gov/nasa/worldwind/globes/package-info.java +++ b/src/gov/nasa/worldwind/globes/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

        * Provides classes for representing the shape and terrain of a planet. A {@link gov.nasa.worldwind.globes.Globe} is diff --git a/src/gov/nasa/worldwind/globes/projections/AbstractGeographicProjection.java b/src/gov/nasa/worldwind/globes/projections/AbstractGeographicProjection.java index 8be038f428..4f1305bd43 100644 --- a/src/gov/nasa/worldwind/globes/projections/AbstractGeographicProjection.java +++ b/src/gov/nasa/worldwind/globes/projections/AbstractGeographicProjection.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.geom.Sector; @@ -14,14 +13,12 @@ * @author tag * @version $Id: AbstractGeographicProjection.java 2270 2014-08-25 20:58:41Z tgaskins $ */ -public abstract class AbstractGeographicProjection implements GeographicProjection -{ +public abstract class AbstractGeographicProjection implements GeographicProjection { + protected Sector projectionLimits; - public AbstractGeographicProjection(Sector projectionLimits) - { - if (projectionLimits == null) - { + public AbstractGeographicProjection(Sector projectionLimits) { + if (projectionLimits == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -31,23 +28,19 @@ public AbstractGeographicProjection(Sector projectionLimits) } @Override - public Sector getProjectionLimits() - { + public Sector getProjectionLimits() { return projectionLimits; } @Override - public void setProjectionLimits(Sector projectionLimits) - { - if (projectionLimits == null) - { + public void setProjectionLimits(Sector projectionLimits) { + if (projectionLimits == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!projectionLimits.isWithinLatLonLimits()) - { + if (!projectionLimits.isWithinLatLonLimits()) { String message = Logging.getMessage("generic.AngleOutOfRange", projectionLimits); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/globes/projections/ProjectionEquirectangular.java b/src/gov/nasa/worldwind/globes/projections/ProjectionEquirectangular.java index 8112bd097d..736baacb91 100644 --- a/src/gov/nasa/worldwind/globes/projections/ProjectionEquirectangular.java +++ b/src/gov/nasa/worldwind/globes/projections/ProjectionEquirectangular.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.geom.*; @@ -16,35 +15,30 @@ * @author tag * @version $Id: ProjectionEquirectangular.java 2277 2014-08-28 21:19:37Z dcollins $ */ -public class ProjectionEquirectangular extends AbstractGeographicProjection -{ - public ProjectionEquirectangular() - { +public class ProjectionEquirectangular extends AbstractGeographicProjection { + + public ProjectionEquirectangular() { super(Sector.FULL_SPHERE); } - public String getName() - { + public String getName() { return "Equirectangular"; } @Override - public boolean isContinuous() - { + public boolean isContinuous() { return true; } @Override - public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) - { + public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) { return new Vec4(globe.getEquatorialRadius() * longitude.radians + offset.x, - globe.getEquatorialRadius() * latitude.radians, metersElevation); + globe.getEquatorialRadius() * latitude.radians, metersElevation); } @Override public void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, double[] metersElevation, - Vec4 offset, Vec4[] out) - { + Vec4 offset, Vec4[] out) { double eqr = globe.getEquatorialRadius(); double minLat = sector.getMinLatitude().radians; double maxLat = sector.getMaxLatitude().radians; @@ -58,19 +52,21 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu // Iterate over the latitude and longitude coordinates in the specified sector, computing the Cartesian point // corresponding to each latitude and longitude. double lat = minLat; - for (int j = 0; j < numLat; j++, lat += deltaLat) - { + for (int j = 0; j < numLat; j++, lat += deltaLat) { if (j == numLat - 1) // explicitly set the last lat to the max latitude to ensure alignment + { lat = maxLat; + } // Latitude is constant for each row. Values that are a function of latitude can be computed once per row. double y = eqr * lat; double lon = minLon; - for (int i = 0; i < numLon; i++, lon += deltaLon) - { + for (int i = 0; i < numLon; i++, lon += deltaLon) { if (i == numLon - 1) // explicitly set the last lon to the max longitude to ensure alignment + { lon = maxLon; + } double x = eqr * lon + offset_x; double z = metersElevation[pos]; @@ -80,15 +76,13 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu } @Override - public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) - { + public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) { return Position.fromRadians(cart.y / globe.getEquatorialRadius(), - (cart.x - offset.x) / globe.getEquatorialRadius(), cart.z); + (cart.x - offset.x) / globe.getEquatorialRadius(), cart.z); } @Override - public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) - { + public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) { return Vec4.UNIT_Y; } } diff --git a/src/gov/nasa/worldwind/globes/projections/ProjectionMercator.java b/src/gov/nasa/worldwind/globes/projections/ProjectionMercator.java index 3efe381db8..d94adb44a6 100644 --- a/src/gov/nasa/worldwind/globes/projections/ProjectionMercator.java +++ b/src/gov/nasa/worldwind/globes/projections/ProjectionMercator.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.geom.*; @@ -16,41 +15,40 @@ * @author tag * @version $Id: ProjectionMercator.java 2277 2014-08-28 21:19:37Z dcollins $ */ -public class ProjectionMercator extends AbstractGeographicProjection -{ - public ProjectionMercator() - { +public class ProjectionMercator extends AbstractGeographicProjection { + + public ProjectionMercator() { super(Sector.fromDegrees(-78, 78, -180, 180)); } @Override - public String getName() - { + public String getName() { return "Mercator"; } @Override - public boolean isContinuous() - { + public boolean isContinuous() { return true; } @Override - public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) - { - if (latitude.degrees > this.getProjectionLimits().getMaxLatitude().degrees) + public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) { + if (latitude.degrees > this.getProjectionLimits().getMaxLatitude().degrees) { latitude = this.getProjectionLimits().getMaxLatitude(); - if (latitude.degrees < this.getProjectionLimits().getMinLatitude().degrees) + } + if (latitude.degrees < this.getProjectionLimits().getMinLatitude().degrees) { latitude = this.getProjectionLimits().getMinLatitude(); - if (longitude.degrees > this.getProjectionLimits().getMaxLongitude().degrees) + } + if (longitude.degrees > this.getProjectionLimits().getMaxLongitude().degrees) { longitude = this.getProjectionLimits().getMaxLongitude(); - if (longitude.degrees < this.getProjectionLimits().getMinLongitude().degrees) + } + if (longitude.degrees < this.getProjectionLimits().getMinLongitude().degrees) { longitude = this.getProjectionLimits().getMinLongitude(); + } double xOffset = offset != null ? offset.x : 0; // See "Map Projections: A Working Manual", page 44 for the source of the below formulas. - double x = globe.getEquatorialRadius() * longitude.radians + xOffset; double ecc = Math.sqrt(globe.getEccentricitySquared()); @@ -63,8 +61,7 @@ public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, @Override public void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, double[] metersElevation, - Vec4 offset, Vec4[] out) - { + Vec4 offset, Vec4[] out) { double eqr = globe.getEquatorialRadius(); double ecc = Math.sqrt(globe.getEccentricitySquared()); double minLat = sector.getMinLatitude().radians; @@ -83,10 +80,11 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu // Iterate over the latitude and longitude coordinates in the specified sector, computing the Cartesian point // corresponding to each latitude and longitude. double lat = minLat; - for (int j = 0; j < numLat; j++, lat += deltaLat) - { + for (int j = 0; j < numLat; j++, lat += deltaLat) { if (j == numLat - 1) // explicitly set the last lat to the max latitude to ensure alignment + { lat = maxLat; + } lat = WWMath.clamp(lat, minLatLimit, maxLatLimit); // limit lat to projection limits // Latitude is constant for each row. Values that are a function of latitude can be computed once per row. @@ -95,10 +93,11 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu double y = eqr * Math.log(s) * 0.5; double lon = minLon; - for (int i = 0; i < numLon; i++, lon += deltaLon) - { + for (int i = 0; i < numLon; i++, lon += deltaLon) { if (i == numLon - 1) // explicitly set the last lon to the max longitude to ensure alignment + { lon = maxLon; + } lon = WWMath.clamp(lon, minLonLimit, maxLonLimit); // limit lon to projection limits double x = eqr * lon + offset_x; @@ -109,12 +108,10 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu } @Override - public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) - { + public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) { double xOffset = offset != null ? offset.x : 0; // See "Map Projections: A Working Manual", pages 45 and 19 for the source of the below formulas. - double ecc2 = globe.getEccentricitySquared(); double ecc4 = ecc2 * ecc2; double ecc6 = ecc4 * ecc2; @@ -141,8 +138,7 @@ public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) } @Override - public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) - { + public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) { return Vec4.UNIT_Y; } } diff --git a/src/gov/nasa/worldwind/globes/projections/ProjectionModifiedSinusoidal.java b/src/gov/nasa/worldwind/globes/projections/ProjectionModifiedSinusoidal.java index 9c6367a239..22e7fdf2c9 100644 --- a/src/gov/nasa/worldwind/globes/projections/ProjectionModifiedSinusoidal.java +++ b/src/gov/nasa/worldwind/globes/projections/ProjectionModifiedSinusoidal.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.geom.*; @@ -16,28 +15,24 @@ * @author tag * @version $Id: ProjectionModifiedSinusoidal.java 2277 2014-08-28 21:19:37Z dcollins $ */ -public class ProjectionModifiedSinusoidal extends AbstractGeographicProjection -{ - public ProjectionModifiedSinusoidal() - { +public class ProjectionModifiedSinusoidal extends AbstractGeographicProjection { + + public ProjectionModifiedSinusoidal() { super(Sector.FULL_SPHERE); } @Override - public String getName() - { + public String getName() { return "Modified Sinusoidal"; } @Override - public boolean isContinuous() - { + public boolean isContinuous() { return false; } @Override - public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) - { + public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) { double latCos = latitude.cos(); double x = latCos > 0 ? globe.getEquatorialRadius() * longitude.radians * Math.pow(latCos, .3) : 0; double y = globe.getEquatorialRadius() * latitude.radians; @@ -47,8 +42,7 @@ public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, @Override public void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, double[] metersElevation, - Vec4 offset, Vec4[] out) - { + Vec4 offset, Vec4[] out) { double eqr = globe.getEquatorialRadius(); double minLat = sector.getMinLatitude().radians; double maxLat = sector.getMaxLatitude().radians; @@ -61,10 +55,11 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu // Iterate over the latitude and longitude coordinates in the specified sector, computing the Cartesian point // corresponding to each latitude and longitude. double lat = minLat; - for (int j = 0; j < numLat; j++, lat += deltaLat) - { + for (int j = 0; j < numLat; j++, lat += deltaLat) { if (j == numLat - 1) // explicitly set the last lat to the max latitude to ensure alignment + { lat = maxLat; + } // Latitude is constant for each row. Values that are a function of latitude can be computed once per row. double y = eqr * lat; @@ -72,10 +67,11 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu double powLat = cosLat > 0 ? Math.pow(cosLat, .3) : 0; double lon = minLon; - for (int i = 0; i < numLon; i++, lon += deltaLon) - { + for (int i = 0; i < numLon; i++, lon += deltaLon) { if (i == numLon - 1) // explicitly set the last lon to the max longitude to ensure alignment + { lon = maxLon; + } double x = eqr * lon * powLat; double z = metersElevation[pos]; @@ -85,8 +81,7 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu } @Override - public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) - { + public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) { double latRadians = cart.y / globe.getEquatorialRadius(); latRadians = WWMath.clamp(latRadians, -Math.PI / 2, Math.PI / 2); @@ -98,13 +93,12 @@ public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) } @Override - public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) - { + public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) { // Computed by taking the partial derivative of the x and y components in geographicToCartesian with // respect to latitude (keeping longitude a constant). double x = globe.getEquatorialRadius() * longitude.radians * .3 * Math.pow(latitude.cos(), .3 - 1) - * -latitude.sin(); + * -latitude.sin(); double y = globe.getEquatorialRadius(); return new Vec4(x, y, 0).normalize3(); diff --git a/src/gov/nasa/worldwind/globes/projections/ProjectionPolarEquidistant.java b/src/gov/nasa/worldwind/globes/projections/ProjectionPolarEquidistant.java index 7bcd79d9b7..6881a8164b 100644 --- a/src/gov/nasa/worldwind/globes/projections/ProjectionPolarEquidistant.java +++ b/src/gov/nasa/worldwind/globes/projections/ProjectionPolarEquidistant.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.avlist.AVKey; @@ -17,8 +16,8 @@ * @author tag * @version $Id: ProjectionPolarEquidistant.java 2277 2014-08-28 21:19:37Z dcollins $ */ -public class ProjectionPolarEquidistant extends AbstractGeographicProjection -{ +public class ProjectionPolarEquidistant extends AbstractGeographicProjection { + protected static final int NORTH = 0; protected static final int SOUTH = 1; @@ -27,8 +26,7 @@ public class ProjectionPolarEquidistant extends AbstractGeographicProjection /** * Creates a projection centered on the North pole. */ - public ProjectionPolarEquidistant() - { + public ProjectionPolarEquidistant() { super(Sector.FULL_SPHERE); } @@ -40,12 +38,10 @@ public ProjectionPolarEquidistant() * * @throws IllegalArgumentException if the specified pole is null. */ - public ProjectionPolarEquidistant(String pole) - { + public ProjectionPolarEquidistant(String pole) { super(Sector.FULL_SPHERE); - if (pole == null) - { + if (pole == null) { String message = Logging.getMessage("nullValue.HemisphereIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -54,14 +50,12 @@ public ProjectionPolarEquidistant(String pole) this.pole = pole.equals(AVKey.SOUTH) ? SOUTH : NORTH; } - public String getName() - { + public String getName() { return (this.pole == SOUTH ? "South " : "North ") + "Polar Equidistant"; } @Override - public boolean isContinuous() - { + public boolean isContinuous() { return false; } @@ -70,18 +64,17 @@ public boolean isContinuous() * * @return The pole on which this projection is centered, either {@link AVKey#NORTH} or {@link AVKey#SOUTH}. */ - public String getPole() - { + public String getPole() { return this.pole == SOUTH ? AVKey.SOUTH : AVKey.NORTH; } @Override - public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) - { + public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) { // Formulae taken from "Map Projections -- A Working Manual", Snyder, USGS paper 1395, pg. 195. - if ((this.pole == NORTH && latitude.degrees == 90) || (this.pole == SOUTH && latitude.degrees == -90)) + if ((this.pole == NORTH && latitude.degrees == 90) || (this.pole == SOUTH && latitude.degrees == -90)) { return new Vec4(0, 0, metersElevation); + } double a = globe.getRadius() * (Math.PI / 2 + latitude.radians * (this.pole == SOUTH ? 1 : -1)); double x = a * Math.sin(longitude.radians); @@ -92,8 +85,7 @@ public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, @Override public void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, double[] metersElevation, - Vec4 offset, Vec4[] out) - { + Vec4 offset, Vec4[] out) { double radius = globe.getRadius(); double minLat = sector.getMinLatitude().radians; double maxLat = sector.getMaxLatitude().radians; @@ -111,10 +103,11 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu double[] cosLon = new double[numLon]; double[] sinLon = new double[numLon]; double lon = minLon; - for (int i = 0; i < numLon; i++, lon += deltaLon) - { + for (int i = 0; i < numLon; i++, lon += deltaLon) { if (i == numLon - 1) // explicitly set the last lon to the max longitude to ensure alignment + { lon = maxLon; + } cosLon[i] = Math.cos(lon); sinLon[i] = Math.sin(lon); @@ -123,20 +116,19 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu // Iterate over the latitude and longitude coordinates in the specified sector, computing the Cartesian point // corresponding to each latitude and longitude. double lat = minLat; - for (int j = 0; j < numLat; j++, lat += deltaLat) - { + for (int j = 0; j < numLat; j++, lat += deltaLat) { if (j == numLat - 1) // explicitly set the last lat to the max latitude to ensure alignment + { lat = maxLat; + } // Latitude is constant for each row. Values that are a function of latitude can be computed once per row. double a = radius * (pi_2 + lat * pole); - if ((this.pole == NORTH && lat == pi_2) || (this.pole == SOUTH && lat == -pi_2)) - { + if ((this.pole == NORTH && lat == pi_2) || (this.pole == SOUTH && lat == -pi_2)) { a = 0; } - for (int i = 0; i < numLon; i++) - { + for (int i = 0; i < numLon; i++) { double x = a * sinLon[i]; double y = a * cosLon[i] * pole; double z = metersElevation[pos]; @@ -147,17 +139,19 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu @SuppressWarnings("SuspiciousNameCombination") @Override - public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) - { + public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) { // Formulae taken from "Map Projections -- A Working Manual", Snyder, USGS paper 1395, pg. 196. double rho = Math.sqrt(cart.x * cart.x + cart.y * cart.y); - if (rho < 1.0e-4) + if (rho < 1.0e-4) { return Position.fromDegrees((this.pole == SOUTH ? -90 : 90), 0, cart.z); + } double c = rho / globe.getRadius(); if (c > Math.PI) // map cartesian points beyond the projections radius to the edge of the projection + { c = Math.PI; + } double lat = Math.asin(Math.cos(c) * (this.pole == SOUTH ? -1 : 1)); double lon = Math.atan2(cart.x, cart.y * (this.pole == SOUTH ? 1 : -1)); // use atan2(x,y) instead of atan(x/y) @@ -166,8 +160,7 @@ public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) } @Override - public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) - { + public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) { // The north pointing tangent depends on the pole. With the south pole, the north pointing tangent points in the // same direction as the vector returned by cartesianToGeographic. With the north pole, the north pointing // tangent has the opposite direction. @@ -179,24 +172,25 @@ public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } ProjectionPolarEquidistant that = (ProjectionPolarEquidistant) o; - if (pole != that.pole) + if (pole != that.pole) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { return pole; } } diff --git a/src/gov/nasa/worldwind/globes/projections/ProjectionSinusoidal.java b/src/gov/nasa/worldwind/globes/projections/ProjectionSinusoidal.java index 93608a58a9..ab1557ea9f 100644 --- a/src/gov/nasa/worldwind/globes/projections/ProjectionSinusoidal.java +++ b/src/gov/nasa/worldwind/globes/projections/ProjectionSinusoidal.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.geom.*; @@ -16,28 +15,24 @@ * @author tag * @version $Id: ProjectionSinusoidal.java 2277 2014-08-28 21:19:37Z dcollins $ */ -public class ProjectionSinusoidal extends AbstractGeographicProjection -{ - public ProjectionSinusoidal() - { +public class ProjectionSinusoidal extends AbstractGeographicProjection { + + public ProjectionSinusoidal() { super(Sector.FULL_SPHERE); } @Override - public String getName() - { + public String getName() { return "Sinusoidal"; } @Override - public boolean isContinuous() - { + public boolean isContinuous() { return false; } @Override - public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) - { + public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) { double latCos = latitude.cos(); double x = latCos > 0 ? globe.getEquatorialRadius() * longitude.radians * latCos : 0; double y = globe.getEquatorialRadius() * latitude.radians; @@ -47,8 +42,7 @@ public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, @Override public void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, double[] metersElevation, - Vec4 offset, Vec4[] out) - { + Vec4 offset, Vec4[] out) { double eqr = globe.getEquatorialRadius(); double minLat = sector.getMinLatitude().radians; double maxLat = sector.getMaxLatitude().radians; @@ -61,10 +55,11 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu // Iterate over the latitude and longitude coordinates in the specified sector, computing the Cartesian point // corresponding to each latitude and longitude. double lat = minLat; - for (int j = 0; j < numLat; j++, lat += deltaLat) - { + for (int j = 0; j < numLat; j++, lat += deltaLat) { if (j == numLat - 1) // explicitly set the last lat to the max latitude to ensure alignment + { lat = maxLat; + } // Latitude is constant for each row. Values that are a function of latitude can be computed once per row. double y = eqr * lat; @@ -72,10 +67,11 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu cosLat = cosLat > 0 ? cosLat : 0; double lon = minLon; - for (int i = 0; i < numLon; i++, lon += deltaLon) - { + for (int i = 0; i < numLon; i++, lon += deltaLon) { if (i == numLon - 1) // explicitly set the last lon to the max longitude to ensure alignment + { lon = maxLon; + } double x = eqr * lon * cosLat; double z = metersElevation[pos]; @@ -85,8 +81,7 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu } @Override - public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) - { + public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) { double latRadians = cart.y / globe.getEquatorialRadius(); latRadians = WWMath.clamp(latRadians, -Math.PI / 2, Math.PI / 2); @@ -98,8 +93,7 @@ public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) } @Override - public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) - { + public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) { // Computed by taking the partial derivative of the x and y components in geographicToCartesian with // respect to latitude (keeping longitude a constant). diff --git a/src/gov/nasa/worldwind/globes/projections/ProjectionTransverseMercator.java b/src/gov/nasa/worldwind/globes/projections/ProjectionTransverseMercator.java index d191257aee..91dd25a264 100644 --- a/src/gov/nasa/worldwind/globes/projections/ProjectionTransverseMercator.java +++ b/src/gov/nasa/worldwind/globes/projections/ProjectionTransverseMercator.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.geom.*; @@ -24,8 +23,8 @@ * @author tag * @version $Id: ProjectionTransverseMercator.java 2393 2014-10-20 20:21:55Z tgaskins $ */ -public class ProjectionTransverseMercator extends AbstractGeographicProjection -{ +public class ProjectionTransverseMercator extends AbstractGeographicProjection { + protected static Angle DEFAULT_WIDTH = Angle.fromDegrees(30); protected static Angle DEFAULT_CENTRAL_MERIDIAN = Angle.ZERO; protected static Angle DEFAULT_CENTRAL_LATITUDE = Angle.ZERO; @@ -34,9 +33,10 @@ public class ProjectionTransverseMercator extends AbstractGeographicProjection protected Angle centralMeridian = DEFAULT_CENTRAL_MERIDIAN; protected Angle centralLatitude = DEFAULT_CENTRAL_LATITUDE; - /** Creates a projection whose central meridian is the Prime Meridian and central latitude is 0. */ - public ProjectionTransverseMercator() - { + /** + * Creates a projection whose central meridian is the Prime Meridian and central latitude is 0. + */ + public ProjectionTransverseMercator() { super(makeProjectionLimits(DEFAULT_CENTRAL_MERIDIAN, DEFAULT_WIDTH)); } @@ -45,12 +45,10 @@ public ProjectionTransverseMercator() * * @param centralMeridian The projection's central meridian. */ - public ProjectionTransverseMercator(Angle centralMeridian) - { + public ProjectionTransverseMercator(Angle centralMeridian) { super(makeProjectionLimits(centralMeridian, DEFAULT_WIDTH)); - if (centralMeridian == null) - { + if (centralMeridian == null) { String message = Logging.getMessage("nullValue.CentralMeridianIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -65,19 +63,16 @@ public ProjectionTransverseMercator(Angle centralMeridian) * @param centralMeridian The projection's central meridian. * @param centralLatitude The projection's central latitude. */ - public ProjectionTransverseMercator(Angle centralMeridian, Angle centralLatitude) - { + public ProjectionTransverseMercator(Angle centralMeridian, Angle centralLatitude) { super(makeProjectionLimits(centralMeridian, DEFAULT_WIDTH)); - if (centralMeridian == null) - { + if (centralMeridian == null) { String message = Logging.getMessage("nullValue.CentralMeridianIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (centralLatitude == null) - { + if (centralLatitude == null) { String message = Logging.getMessage("nullValue.CentralLatitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -88,8 +83,7 @@ public ProjectionTransverseMercator(Angle centralMeridian, Angle centralLatitude } @Override - public String getName() - { + public String getName() { return "Transverse Mercator"; } @@ -98,8 +92,7 @@ public String getName() * * @return This projection's central meridian. */ - public Angle getCentralMeridian() - { + public Angle getCentralMeridian() { return centralMeridian; } @@ -108,10 +101,8 @@ public Angle getCentralMeridian() * * @param centralMeridian This projection's central meridian. The default is 0. */ - public void setCentralMeridian(Angle centralMeridian) - { - if (centralMeridian == null) - { + public void setCentralMeridian(Angle centralMeridian) { + if (centralMeridian == null) { String message = Logging.getMessage("nullValue.CentralMeridianIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -126,8 +117,7 @@ public void setCentralMeridian(Angle centralMeridian) * * @return This projection's central latitude. */ - public Angle getCentralLatitude() - { + public Angle getCentralLatitude() { return centralLatitude; } @@ -136,10 +126,8 @@ public Angle getCentralLatitude() * * @param centralLatitude This projection's central latitude. The default is 0. */ - public void setCentralLatitude(Angle centralLatitude) - { - if (centralLatitude == null) - { + public void setCentralLatitude(Angle centralLatitude) { + if (centralLatitude == null) { String message = Logging.getMessage("nullValue.CentralLatitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -154,8 +142,7 @@ public void setCentralLatitude(Angle centralLatitude) * * @return This projection's width. */ - public Angle getWidth() - { + public Angle getWidth() { return width; } @@ -165,10 +152,8 @@ public Angle getWidth() * * @param width This projection's width. */ - public void setWidth(Angle width) - { - if (width == null) - { + public void setWidth(Angle width) { + if (width == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -178,47 +163,47 @@ public void setWidth(Angle width) this.setProjectionLimits(makeProjectionLimits(this.getCentralMeridian(), this.getWidth())); } - protected static Sector makeProjectionLimits(Angle centralMeridian, Angle width) - { + protected static Sector makeProjectionLimits(Angle centralMeridian, Angle width) { double minLon = centralMeridian.degrees - width.degrees; - if (minLon < -180) + if (minLon < -180) { minLon = -180; + } double maxLon = centralMeridian.degrees + width.degrees; - if (maxLon > 180) + if (maxLon > 180) { maxLon = 180; + } return Sector.fromDegrees(-90, 90, minLon, maxLon); } - protected double getScale() - { + protected double getScale() { return 1.0; } @Override - public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) - { - if (latitude.degrees > 86) + public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) { + if (latitude.degrees > 86) { latitude = Angle.fromDegrees(86); - else if (latitude.degrees < -82) + } else if (latitude.degrees < -82) { latitude = Angle.fromDegrees(-82); + } - if (longitude.degrees > this.centralMeridian.degrees + this.width.degrees) + if (longitude.degrees > this.centralMeridian.degrees + this.width.degrees) { longitude = Angle.fromDegrees(this.centralMeridian.degrees + this.width.degrees); - else if (longitude.degrees < this.centralMeridian.degrees - this.width.degrees) + } else if (longitude.degrees < this.centralMeridian.degrees - this.width.degrees) { longitude = Angle.fromDegrees(this.centralMeridian.degrees - this.width.degrees); + } TMCoord tm = TMCoord.fromLatLon(latitude, longitude, - globe, null, null, this.centralLatitude, this.centralMeridian, 0, 0, this.getScale()); + globe, null, null, this.centralLatitude, this.centralMeridian, 0, 0, this.getScale()); return new Vec4(tm.getEasting(), tm.getNorthing(), metersElevation); } @Override public void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, double[] metersElevation, - Vec4 offset, Vec4[] out) - { + Vec4 offset, Vec4[] out) { double minLat = sector.getMinLatitude().radians; double maxLat = sector.getMaxLatitude().radians; double minLon = sector.getMinLongitude().radians; @@ -234,21 +219,23 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu // Iterate over the latitude and longitude coordinates in the specified sector, computing the Cartesian point // corresponding to each latitude and longitude. double lat = minLat; - for (int j = 0; j < numLat; j++, lat += deltaLat) - { + for (int j = 0; j < numLat; j++, lat += deltaLat) { if (j == numLat - 1) // explicitly set the last lat to the max latitude to ensure alignment + { lat = maxLat; + } lat = WWMath.clamp(lat, minLatLimit, maxLatLimit); // limit lat to projection limits double lon = minLon; - for (int i = 0; i < numLon; i++, lon += deltaLon) - { + for (int i = 0; i < numLon; i++, lon += deltaLon) { if (i == numLon - 1) // explicitly set the last lon to the max longitude to ensure alignment + { lon = maxLon; + } lon = WWMath.clamp(lon, minLonLimit, maxLonLimit); // limit lon to projection limits TMCoord tm = TMCoord.fromLatLon(Angle.fromRadians(lat), Angle.fromRadians(lon), - globe, null, null, this.centralLatitude, this.centralMeridian, 0, 0, this.getScale()); + globe, null, null, this.centralLatitude, this.centralMeridian, 0, 0, this.getScale()); double x = tm.getEasting(); double y = tm.getNorthing(); double z = metersElevation[pos]; @@ -258,10 +245,9 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu } @Override - public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) - { + public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) { TMCoord tm = TMCoord.fromTM(cart.x, cart.y, globe, this.centralLatitude, this.centralMeridian, 0, 0, - this.getScale()); + this.getScale()); return new Position(tm.getLatitude(), tm.getLongitude(), cart.z); } @@ -300,8 +286,7 @@ public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) // } @Override - public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) - { + public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) { // Choose a small angle that we'll use as an increment in order to estimate the north pointing tangent by // computing the vector resulting from a small increment in latitude. Using 1e-7 in radians gives a tangent // resolution of approximately 1/2 meter. We specify the value in radians since geodeticToCartesian performs @@ -313,14 +298,12 @@ public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) Vec4 p1 = this.geographicToCartesian(globe, latitude, longitude, 0, null); Vec4 p2 = this.geographicToCartesian(globe, latitude.subtract(deltaLat), longitude, 0, null); return p1.subtract3(p2).normalize3(); - } - else if (latitude.degrees - deltaLat.degrees <= -82) // compute the incremental vector above the location + } else if (latitude.degrees - deltaLat.degrees <= -82) // compute the incremental vector above the location { Vec4 p1 = this.geographicToCartesian(globe, latitude.add(deltaLat), longitude, 0, null); Vec4 p2 = this.geographicToCartesian(globe, latitude, longitude, 0, null); return p1.subtract3(p2).normalize3(); - } - else // compute the average of the incremental vector above and below the location + } else // compute the average of the incremental vector above and below the location { Vec4 p1 = this.geographicToCartesian(globe, latitude.add(deltaLat), longitude, 0, null); Vec4 p2 = this.geographicToCartesian(globe, latitude.subtract(deltaLat), longitude, 0, null); @@ -329,34 +312,36 @@ else if (latitude.degrees - deltaLat.degrees <= -82) // compute the incremental } @Override - public boolean isContinuous() - { + public boolean isContinuous() { return false; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } ProjectionTransverseMercator that = (ProjectionTransverseMercator) o; - if (!centralMeridian.equals(that.centralMeridian)) + if (!centralMeridian.equals(that.centralMeridian)) { return false; - if (!centralLatitude.equals(that.centralLatitude)) + } + if (!centralLatitude.equals(that.centralLatitude)) { return false; - if (!width.equals(that.width)) + } + if (!width.equals(that.width)) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = width.hashCode(); result = 31 * result + centralMeridian.hashCode(); result = 31 * result + centralLatitude.hashCode(); diff --git a/src/gov/nasa/worldwind/globes/projections/ProjectionUPS.java b/src/gov/nasa/worldwind/globes/projections/ProjectionUPS.java index c181f2cffc..e31aac9d54 100644 --- a/src/gov/nasa/worldwind/globes/projections/ProjectionUPS.java +++ b/src/gov/nasa/worldwind/globes/projections/ProjectionUPS.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.avlist.AVKey; @@ -17,8 +16,8 @@ * @author tag * @version $Id$ */ -public class ProjectionUPS extends AbstractGeographicProjection -{ +public class ProjectionUPS extends AbstractGeographicProjection { + protected static final int NORTH = 0; protected static final int SOUTH = 1; @@ -30,8 +29,7 @@ public class ProjectionUPS extends AbstractGeographicProjection /** * Creates a projection centered on the North pole. */ - public ProjectionUPS() - { + public ProjectionUPS() { super(NORTH_LIMITS); } @@ -43,12 +41,10 @@ public ProjectionUPS() * * @throws IllegalArgumentException if the specified pole is null. */ - public ProjectionUPS(String pole) - { + public ProjectionUPS(String pole) { super(pole != null && pole.equals(AVKey.SOUTH) ? SOUTH_LIMITS : NORTH_LIMITS); - if (pole == null) - { + if (pole == null) { String message = Logging.getMessage("nullValue.HemisphereIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -58,32 +54,31 @@ public ProjectionUPS(String pole) } @Override - public String getName() - { + public String getName() { return (this.pole == SOUTH ? "South " : "North ") + "Universal Polar Stereographic"; } @Override - public boolean isContinuous() - { + public boolean isContinuous() { return false; } @Override - public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) - { + public Vec4 geographicToCartesian(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) { // Formulas taken from "Map Projections -- A Working Manual", Snyder, USGS paper 1395, pg. 161. - if ((this.pole == NORTH && latitude.degrees == 90) || (this.pole == SOUTH && latitude.degrees == -90)) + if ((this.pole == NORTH && latitude.degrees == 90) || (this.pole == SOUTH && latitude.degrees == -90)) { return new Vec4(0, 0, metersElevation); + } double lat = latitude.radians; double lon = longitude.radians; - if (this.pole == NORTH && lat < 0) + if (this.pole == NORTH && lat < 0) { lat = 0; - else if (this.pole == SOUTH && lat > 0) + } else if (this.pole == SOUTH && lat > 0) { lat = 0; + } double k0 = 0.994; // standard UPS scale factor -- see above reference pg.157, pp 2. double ecc = Math.sqrt(globe.getEccentricitySquared()); @@ -101,8 +96,7 @@ else if (this.pole == SOUTH && lat > 0) @Override public void geographicToCartesian(Globe globe, Sector sector, int numLat, int numLon, double[] metersElevation, - Vec4 offset, Vec4[] out) - { + Vec4 offset, Vec4[] out) { double minLat = sector.getMinLatitude().radians; double maxLat = sector.getMaxLatitude().radians; double minLon = sector.getMinLongitude().radians; @@ -118,29 +112,30 @@ public void geographicToCartesian(Globe globe, Sector sector, int numLat, int nu // Iterate over the latitude and longitude coordinates in the specified sector, computing the Cartesian point // corresponding to each latitude and longitude. double lat = minLat; - for (int j = 0; j < numLat; j++, lat += deltaLat) - { + for (int j = 0; j < numLat; j++, lat += deltaLat) { if (j == numLat - 1) // explicitly set the last lat to the max latitude to ensure alignment + { lat = maxLat; + } lat = WWMath.clamp(lat, minLatLimit, maxLatLimit); // limit lat to projection limits double lon = minLon; - for (int i = 0; i < numLon; i++, lon += deltaLon) - { + for (int i = 0; i < numLon; i++, lon += deltaLon) { if (i == numLon - 1) // explicitly set the last lon to the max longitude to ensure alignment + { lon = maxLon; + } lon = WWMath.clamp(lon, minLonLimit, maxLonLimit); // limit lon to projection limits out[pos] = this.geographicToCartesian(globe, Angle.fromRadiansLatitude(lat), - Angle.fromRadiansLongitude(lon), metersElevation[pos], offset); + Angle.fromRadiansLongitude(lon), metersElevation[pos], offset); ++pos; } } } @Override - public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) - { + public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) { double xOffset = offset != null ? offset.x : 0; double x = (cart.x - xOffset); double y = cart.y; @@ -180,8 +175,7 @@ public Position cartesianToGeographic(Globe globe, Vec4 cart, Vec4 offset) } @Override - public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) - { + public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) { // The north pointing tangent depends on the pole. With the south pole, the north pointing tangent points in the // same direction as the vector returned by cartesianToGeographic. With the north pole, the north pointing // tangent has the opposite direction. @@ -193,16 +187,15 @@ public Vec4 northPointingTangent(Globe globe, Angle latitude, Angle longitude) } // @Override - public Vec4 geographicToCartesianNGA(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) - { + public Vec4 geographicToCartesianNGA(Globe globe, Angle latitude, Angle longitude, double metersElevation, Vec4 offset) { // Formula from NGA.SIG.0012_2.0.0_UTMUPS dated 2014-03-25. - if ((this.pole == NORTH && latitude.degrees == 90) || (this.pole == SOUTH && latitude.degrees == -90)) + if ((this.pole == NORTH && latitude.degrees == 90) || (this.pole == SOUTH && latitude.degrees == -90)) { return new Vec4(0, 0, metersElevation); + } double clampedLat = WWMath.clamp(latitude.radians, this.getProjectionLimits().getMinLatitude().radians, - this.getProjectionLimits().getMaxLatitude().radians); - + this.getProjectionLimits().getMaxLatitude().radians); double a = globe.getEquatorialRadius(); double lat = clampedLat * (this.pole == NORTH ? 1 : -1); @@ -220,21 +213,19 @@ public Vec4 geographicToCartesianNGA(Globe globe, Angle latitude, Angle longitud double sinChi = ((1 + sinLat) / P - (1 - sinLat) * P) / denom; denom = k90 * (1 + sinChi); - double x = 0.994 * 2 * a * Math.sin(lon) * cosChi/ denom; - double y = 0.994 * -2 * a * Math.cos(lon) * cosChi/ denom * (this.pole == NORTH ? 1 : -1); + double x = 0.994 * 2 * a * Math.sin(lon) * cosChi / denom; + double y = 0.994 * -2 * a * Math.cos(lon) * cosChi / denom * (this.pole == NORTH ? 1 : -1); return new Vec4(x, y, metersElevation); } // @Override - public Position cartesianToGeographicNGA(Globe globe, Vec4 cart, Vec4 offset) - { + public Position cartesianToGeographicNGA(Globe globe, Vec4 cart, Vec4 offset) { // Formula from NGA.SIG.0012_2.0.0_UTMUPS dated 2014-03-25. // THIS FORMULA IS NOT PRODUCING THE EXPECTED RESULTS. Using this formula causes navigation to behave as // though there's a singularity at the pole. The user appears to be prevented from moving the pole over // the center of Cartesian coordinates. - double xOffset = offset != null ? offset.x : 0; double x = (cart.x - xOffset) / 0.994; double y = cart.y / (0.994 * this.pole == NORTH ? 1 : -1); @@ -255,22 +246,23 @@ public Position cartesianToGeographicNGA(Globe globe, Vec4 cart, Vec4 offset) double P = 1; double convergence = 0.00000001; // ~ 6 cm on Earth - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { P = Math.exp(e * Angle.arctanh(e * sinLat)); double sPrevious = sinLat; sinLat = ((1 + sinChi) * P * P - (1 - sinChi)) / ((1 + sinChi) * P * P + (1 - sinChi)); - if (Math.abs(sinLat - sPrevious) <= convergence) + if (Math.abs(sinLat - sPrevious) <= convergence) { break; + } } double cosLat = 0.5 * ((1 + sinLat) / P + (1 - sinLat) * P) * cosChi; double lat = Math.atan2(sinLat, cosLat) * this.pole == NORTH ? 1 : -1; double lon = Math.atan2(x, -y); - if (x == 0 && y == 0) + if (x == 0 && y == 0) { lon = 0; + } return Position.fromRadians(lat, lon, cart.z); } diff --git a/src/gov/nasa/worldwind/globes/projections/ProjectionUTM.java b/src/gov/nasa/worldwind/globes/projections/ProjectionUTM.java index 5a5f29d507..5903c9df3b 100644 --- a/src/gov/nasa/worldwind/globes/projections/ProjectionUTM.java +++ b/src/gov/nasa/worldwind/globes/projections/ProjectionUTM.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.globes.projections; import gov.nasa.worldwind.geom.Angle; @@ -15,15 +14,16 @@ * @author tag * @version $Id: ProjectionUTM.java 2097 2014-06-25 18:19:42Z tgaskins $ */ -public class ProjectionUTM extends ProjectionTransverseMercator -{ +public class ProjectionUTM extends ProjectionTransverseMercator { + protected static final int DEFAULT_ZONE = 1; protected int zone = DEFAULT_ZONE; - /** Creates a projection for UTM zone 1. */ - public ProjectionUTM() - { + /** + * Creates a projection for UTM zone 1. + */ + public ProjectionUTM() { super(centralMeridianForZone(DEFAULT_ZONE)); } @@ -34,13 +34,11 @@ public ProjectionUTM() * * @throws IllegalArgumentException if the specified zone is less than 1 or greater than 60. */ - public ProjectionUTM(int zone) - { + public ProjectionUTM(int zone) { super(centralMeridianForZone(zone)); } - protected double getScale() - { + protected double getScale() { return 0.9996; } @@ -49,8 +47,7 @@ protected double getScale() * * @return The UTM zone, a value between 1 and 60, inclusive. */ - public int getZone() - { + public int getZone() { return zone; } @@ -62,10 +59,8 @@ public int getZone() * @throws IllegalArgumentException If the specified zone is less than 1 or greater than 60. * @see ProjectionTransverseMercator */ - public void setZone(int zone) - { - if (zone < 1 || zone > 60) - { + public void setZone(int zone) { + if (zone < 1 || zone > 60) { String message = Logging.getMessage("UTM.InvalidZone", zone); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,10 +71,8 @@ public void setZone(int zone) this.setCentralMeridian(centralMeridianForZone(this.zone)); } - public static Angle centralMeridianForZone(int zone) - { - if (zone < 1 || zone > 60) - { + public static Angle centralMeridianForZone(int zone) { + if (zone < 1 || zone > 60) { String message = Logging.getMessage("UTM.InvalidZone", zone); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/layers/AbstractGraticuleLayer.java b/src/gov/nasa/worldwind/layers/AbstractGraticuleLayer.java index 111b77beba..032a92bfc7 100644 --- a/src/gov/nasa/worldwind/layers/AbstractGraticuleLayer.java +++ b/src/gov/nasa/worldwind/layers/AbstractGraticuleLayer.java @@ -22,8 +22,8 @@ * @author Patrick Murris * @version $Id: AbstractGraticuleLayer.java 2153 2014-07-17 17:33:13Z tgaskins $ */ -public class AbstractGraticuleLayer extends AbstractLayer -{ +public class AbstractGraticuleLayer extends AbstractLayer { + /** * Solid line rendering style. This style specifies that a line will be drawn without any breaks.
        *

        _________
        @@ -40,8 +40,7 @@ public class AbstractGraticuleLayer extends AbstractLayer /** * Dotted line rendering style. This style specifies that a line will be drawn as a series of evenly spaced "square" * dots.
        - *
        . . . . .
        - * is an example of a dotted line. + *
        . . . . .
        is an example of a dotted line. */ public static final String LINE_STYLE_DOTTED = GraticuleRenderingParams.VALUE_LINE_STYLE_DOTTED; @@ -59,8 +58,7 @@ public class AbstractGraticuleLayer extends AbstractLayer protected GeographicProjection lastProjection; protected long frameTimeStamp; // used only for 2D continuous globes to determine whether render is in same frame - public AbstractGraticuleLayer() - { + public AbstractGraticuleLayer() { } /** @@ -72,10 +70,8 @@ public AbstractGraticuleLayer() * * @throws IllegalArgumentException key is null. */ - public boolean isDrawGraticule(String key) - { - if (key == null) - { + public boolean isDrawGraticule(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -87,14 +83,12 @@ public boolean isDrawGraticule(String key) * Sets whether or not graticule lines will be rendered. * * @param drawGraticule true to render graticule lines; false to disable rendering. - * @param key the rendering parameters key. + * @param key the rendering parameters key. * * @throws IllegalArgumentException key is null. */ - public void setDrawGraticule(boolean drawGraticule, String key) - { - if (key == null) - { + public void setDrawGraticule(boolean drawGraticule, String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -111,10 +105,8 @@ public void setDrawGraticule(boolean drawGraticule, String key) * * @throws IllegalArgumentException key is null. */ - public Color getGraticuleLineColor(String key) - { - if (key == null) - { + public Color getGraticuleLineColor(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -126,20 +118,17 @@ public Color getGraticuleLineColor(String key) * Sets the graticule line Color. * * @param color Color that will be used to render graticule lines. - * @param key the rendering parameters key. + * @param key the rendering parameters key. * * @throws IllegalArgumentException if color or key is null. */ - public void setGraticuleLineColor(Color color, String key) - { - if (color == null) - { + public void setGraticuleLineColor(Color color, String key) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (key == null) - { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -157,10 +146,8 @@ public void setGraticuleLineColor(Color color, String key) * * @throws IllegalArgumentException key is null. */ - public double getGraticuleLineWidth(String key) - { - if (key == null) - { + public double getGraticuleLineWidth(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,14 +159,12 @@ public double getGraticuleLineWidth(String key) * Sets the graticule line width. * * @param lineWidth width of the graticule lines. - * @param key the rendering parameters key. + * @param key the rendering parameters key. * * @throws IllegalArgumentException key is null. */ - public void setGraticuleLineWidth(double lineWidth, String key) - { - if (key == null) - { + public void setGraticuleLineWidth(double lineWidth, String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -196,10 +181,8 @@ public void setGraticuleLineWidth(double lineWidth, String key) * * @throws IllegalArgumentException key is null. */ - public String getGraticuleLineStyle(String key) - { - if (key == null) - { + public String getGraticuleLineStyle(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -211,21 +194,18 @@ public String getGraticuleLineStyle(String key) * Sets the graticule line rendering style. * * @param lineStyle rendering style of the graticule lines. One of LINE_STYLE_PLAIN, LINE_STYLE_DASHED, or - * LINE_STYLE_DOTTED. - * @param key the rendering parameters key. + * LINE_STYLE_DOTTED. + * @param key the rendering parameters key. * * @throws IllegalArgumentException if lineStyle or key is null. */ - public void setGraticuleLineStyle(String lineStyle, String key) - { - if (lineStyle == null) - { + public void setGraticuleLineStyle(String lineStyle, String key) { + if (lineStyle == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (key == null) - { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -243,10 +223,8 @@ public void setGraticuleLineStyle(String lineStyle, String key) * * @throws IllegalArgumentException key is null. */ - public boolean isDrawLabels(String key) - { - if (key == null) - { + public boolean isDrawLabels(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -258,14 +236,12 @@ public boolean isDrawLabels(String key) * Sets whether or not graticule labels will be rendered. * * @param drawLabels true to render graticule labels; false to disable rendering. - * @param key the rendering parameters key. + * @param key the rendering parameters key. * * @throws IllegalArgumentException key is null. */ - public void setDrawLabels(boolean drawLabels, String key) - { - if (key == null) - { + public void setDrawLabels(boolean drawLabels, String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -282,10 +258,8 @@ public void setDrawLabels(boolean drawLabels, String key) * * @throws IllegalArgumentException key is null. */ - public Color getLabelColor(String key) - { - if (key == null) - { + public Color getLabelColor(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -297,20 +271,17 @@ public Color getLabelColor(String key) * Sets the graticule label Color. * * @param color Color that will be used to render graticule labels. - * @param key the rendering parameters key. + * @param key the rendering parameters key. * * @throws IllegalArgumentException if color or key is null. */ - public void setLabelColor(Color color, String key) - { - if (color == null) - { + public void setLabelColor(Color color, String key) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (key == null) - { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -328,10 +299,8 @@ public void setLabelColor(Color color, String key) * * @throws IllegalArgumentException key is null. */ - public Font getLabelFont(String key) - { - if (key == null) - { + public Font getLabelFont(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -343,20 +312,17 @@ public Font getLabelFont(String key) * Sets the Font used for graticule labels. * * @param font Font that will be used to render graticule labels. - * @param key the rendering parameters key. + * @param key the rendering parameters key. * * @throws IllegalArgumentException if font or key is null. */ - public void setLabelFont(Font font, String key) - { - if (font == null) - { + public void setLabelFont(Font font, String key) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (key == null) - { + if (key == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -365,18 +331,16 @@ public void setLabelFont(Font font, String key) getRenderingParams(key).setLabelFont(font); } - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (rs == null) + if (rs == null) { return null; + } RestorableSupport.StateObject so = rs.addStateObject("renderingParams"); - for (Map.Entry entry : this.graticuleSupport.getAllRenderingParams()) - { - if (entry.getKey() != null && entry.getValue() != null) - { + for (Map.Entry entry : this.graticuleSupport.getAllRenderingParams()) { + if (entry.getKey() != null && entry.getValue() != null) { RestorableSupport.StateObject eso = rs.addStateObject(so, entry.getKey()); makeRestorableState(entry.getValue(), rs, eso); } @@ -386,49 +350,36 @@ public String getRestorableState() } private static void makeRestorableState(GraticuleRenderingParams params, RestorableSupport rs, - RestorableSupport.StateObject context) - { - if (params != null && rs != null) - { - for (Map.Entry p : params.getEntries()) - { - if (p.getValue() instanceof Color) - { + RestorableSupport.StateObject context) { + if (params != null && rs != null) { + for (Map.Entry p : params.getEntries()) { + if (p.getValue() instanceof Color) { rs.addStateValueAsInteger(context, p.getKey() + ".Red", ((Color) p.getValue()).getRed()); rs.addStateValueAsInteger(context, p.getKey() + ".Green", ((Color) p.getValue()).getGreen()); rs.addStateValueAsInteger(context, p.getKey() + ".Blue", ((Color) p.getValue()).getBlue()); rs.addStateValueAsInteger(context, p.getKey() + ".Alpha", ((Color) p.getValue()).getAlpha()); - } - else if (p.getValue() instanceof Font) - { + } else if (p.getValue() instanceof Font) { rs.addStateValueAsString(context, p.getKey() + ".Name", ((Font) p.getValue()).getName()); rs.addStateValueAsInteger(context, p.getKey() + ".Style", ((Font) p.getValue()).getStyle()); rs.addStateValueAsInteger(context, p.getKey() + ".Size", ((Font) p.getValue()).getSize()); - } - else - { + } else { params.getRestorableStateForAVPair(p.getKey(), p.getValue(), rs, context); } } } } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -436,16 +387,14 @@ public void restoreState(String stateInXml) } RestorableSupport.StateObject so = rs.getStateObject("renderingParams"); - if (so != null) - { + if (so != null) { RestorableSupport.StateObject[] renderParams = rs.getAllStateObjects(so); - for (RestorableSupport.StateObject rp : renderParams) - { - if (rp != null) - { + for (RestorableSupport.StateObject rp : renderParams) { + if (rp != null) { GraticuleRenderingParams params = getRenderingParams(rp.getName()); - if (params == null) + if (params == null) { params = new GraticuleRenderingParams(); + } restorableStateToParams(params, rs, rp); setRenderingParams(rp.getName(), params); } @@ -454,54 +403,56 @@ public void restoreState(String stateInXml) } private static void restorableStateToParams(AVList params, RestorableSupport rs, - RestorableSupport.StateObject context) - { - if (params != null && rs != null) - { + RestorableSupport.StateObject context) { + if (params != null && rs != null) { Boolean b = rs.getStateValueAsBoolean(context, GraticuleRenderingParams.KEY_DRAW_LINES); - if (b != null) + if (b != null) { params.setValue(GraticuleRenderingParams.KEY_DRAW_LINES, b); + } Integer red = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LINE_COLOR + ".Red"); Integer green = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LINE_COLOR + ".Green"); Integer blue = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LINE_COLOR + ".Blue"); Integer alpha = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LINE_COLOR + ".Alpha"); - if (red != null && green != null && blue != null && alpha != null) + if (red != null && green != null && blue != null && alpha != null) { params.setValue(GraticuleRenderingParams.KEY_LINE_COLOR, new Color(red, green, blue, alpha)); + } Double d = rs.getStateValueAsDouble(context, GraticuleRenderingParams.KEY_LINE_WIDTH); - if (d != null) + if (d != null) { params.setValue(GraticuleRenderingParams.KEY_LINE_WIDTH, d); + } String s = rs.getStateValueAsString(context, GraticuleRenderingParams.KEY_LINE_STYLE); - if (s != null) + if (s != null) { params.setValue(GraticuleRenderingParams.KEY_LINE_STYLE, s); + } b = rs.getStateValueAsBoolean(context, GraticuleRenderingParams.KEY_DRAW_LABELS); - if (b != null) + if (b != null) { params.setValue(GraticuleRenderingParams.KEY_DRAW_LABELS, b); + } red = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LABEL_COLOR + ".Red"); green = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LABEL_COLOR + ".Green"); blue = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LABEL_COLOR + ".Blue"); alpha = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LABEL_COLOR + ".Alpha"); - if (red != null && green != null && blue != null && alpha != null) + if (red != null && green != null && blue != null && alpha != null) { params.setValue(GraticuleRenderingParams.KEY_LABEL_COLOR, new Color(red, green, blue, alpha)); + } String name = rs.getStateValueAsString(context, GraticuleRenderingParams.KEY_LABEL_FONT + ".Name"); Integer style = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LABEL_FONT + ".Style"); Integer size = rs.getStateValueAsInteger(context, GraticuleRenderingParams.KEY_LABEL_FONT + ".Size"); - if (name != null && style != null && size != null) + if (name != null && style != null && size != null) { params.setValue(GraticuleRenderingParams.KEY_LABEL_FONT, new Font(name, style, size)); + } } } // --- Graticule Rendering -------------------------------------------------------------- - - protected GraticuleRenderingParams getRenderingParams(String key) - { - if (key == null) - { + protected GraticuleRenderingParams getRenderingParams(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -510,10 +461,8 @@ protected GraticuleRenderingParams getRenderingParams(String key) return this.graticuleSupport.getRenderingParams(key); } - protected void setRenderingParams(String key, GraticuleRenderingParams renderingParams) - { - if (key == null) - { + protected void setRenderingParams(String key, GraticuleRenderingParams renderingParams) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -522,10 +471,8 @@ protected void setRenderingParams(String key, GraticuleRenderingParams rendering this.graticuleSupport.setRenderingParams(key, renderingParams); } - protected void addRenderable(Object renderable, String paramsKey) - { - if (renderable == null) - { + protected void addRenderable(Object renderable, String paramsKey) { + if (renderable == null) { String message = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -534,49 +481,40 @@ protected void addRenderable(Object renderable, String paramsKey) this.graticuleSupport.addRenderable(renderable, paramsKey); } - protected void removeAllRenderables() - { + protected void removeAllRenderables() { this.graticuleSupport.removeAllRenderables(); } - public void doPreRender(DrawContext dc) - { - if (dc == null) - { + public void doPreRender(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.isContinuous2DGlobe()) - { - if (this.needsToUpdate(dc)) - { + if (dc.isContinuous2DGlobe()) { + if (this.needsToUpdate(dc)) { this.clear(dc); this.selectRenderables(dc); } // If the frame time stamp is the same, then this is the second or third pass of the same frame. We continue // selecting renderables in these passes. - if (dc.getFrameTimeStamp() == this.frameTimeStamp) + if (dc.getFrameTimeStamp() == this.frameTimeStamp) { this.selectRenderables(dc); + } this.frameTimeStamp = dc.getFrameTimeStamp(); - } - else - { - if (this.needsToUpdate(dc)) - { + } else { + if (this.needsToUpdate(dc)) { this.clear(dc); this.selectRenderables(dc); } } } - public void doRender(DrawContext dc) - { - if (dc == null) - { + public void doRender(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -586,10 +524,8 @@ public void doRender(DrawContext dc) this.renderGraticule(dc); } - protected void renderGraticule(DrawContext dc) - { - if (dc == null) - { + protected void renderGraticule(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -603,17 +539,14 @@ protected void renderGraticule(DrawContext dc) * * @param dc the current DrawContext. */ - protected void selectRenderables(DrawContext dc) - { - if (dc == null) - { + protected void selectRenderables(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // This method is intended to be overriden by subclasses - } /** @@ -626,45 +559,50 @@ protected void selectRenderables(DrawContext dc) * @return true if the graticule should be updated. */ @SuppressWarnings({"RedundantIfStatement"}) - protected boolean needsToUpdate(DrawContext dc) - { - if (this.lastEyePoint == null) + protected boolean needsToUpdate(DrawContext dc) { + if (this.lastEyePoint == null) { return true; + } View view = dc.getView(); double altitudeAboveGround = computeAltitudeAboveGround(dc); - if (view.getEyePoint().distanceTo3(this.lastEyePoint) > altitudeAboveGround / 100) // 1% of AAG + if (view.getEyePoint().distanceTo3(this.lastEyePoint) > altitudeAboveGround / 100) // 1% of AAG + { return true; + } - if (this.lastVerticalExaggeration != dc.getVerticalExaggeration()) + if (this.lastVerticalExaggeration != dc.getVerticalExaggeration()) { return true; + } - if (Math.abs(this.lastViewHeading - view.getHeading().degrees) > 1) + if (Math.abs(this.lastViewHeading - view.getHeading().degrees) > 1) { return true; - if (Math.abs(this.lastViewPitch - view.getPitch().degrees) > 1) + } + if (Math.abs(this.lastViewPitch - view.getPitch().degrees) > 1) { return true; + } - if (Math.abs(this.lastViewFOV - view.getFieldOfView().degrees) > 1) + if (Math.abs(this.lastViewFOV - view.getFieldOfView().degrees) > 1) { return true; + } // We must test the globe and its projection to see if either changed. We can't simply use the globe state // key for this because we don't want a 2D globe offset change to cause an update. Offset changes don't // invalidate the current set of renderables. - - if (dc.getGlobe() != this.globe) + if (dc.getGlobe() != this.globe) { return true; + } - if (dc.is2DGlobe()) - { - if (((Globe2D) dc.getGlobe()).getProjection() != this.lastProjection) + if (dc.is2DGlobe()) { + if (((Globe2D) dc.getGlobe()).getProjection() != this.lastProjection) { return true; + } } return false; } - protected void clear(DrawContext dc) - { + protected void clear(DrawContext dc) { this.removeAllRenderables(); this.terrainConformance = computeTerrainConformance(dc); this.globe = dc.getGlobe(); @@ -674,51 +612,48 @@ protected void clear(DrawContext dc) this.lastViewPitch = dc.getView().getPitch().degrees; this.lastVerticalExaggeration = dc.getVerticalExaggeration(); - if (dc.is2DGlobe()) + if (dc.is2DGlobe()) { this.lastProjection = ((Globe2D) dc.getGlobe()).getProjection(); + } } - protected double computeTerrainConformance(DrawContext dc) - { + protected double computeTerrainConformance(DrawContext dc) { int value = 100; double alt = dc.getView().getEyePosition().getElevation(); - if (alt < 10e3) + if (alt < 10e3) { value = 20; - else if (alt < 50e3) + } else if (alt < 50e3) { value = 30; - else if (alt < 100e3) + } else if (alt < 100e3) { value = 40; - else if (alt < 1000e3) + } else if (alt < 1000e3) { value = 60; + } return value; } - protected LatLon computeLabelOffset(DrawContext dc) - { + protected LatLon computeLabelOffset(DrawContext dc) { LatLon labelPos; // Compute labels offset from view center - if (dc.getView() instanceof OrbitView) - { + if (dc.getView() instanceof OrbitView) { OrbitView view = (OrbitView) dc.getView(); Position centerPos = view.getCenterPosition(); Double pixelSizeDegrees = Angle.fromRadians(view.computePixelSizeAtDistance(view.getZoom()) - / dc.getGlobe().getEquatorialRadius()).degrees; + / dc.getGlobe().getEquatorialRadius()).degrees; Double labelOffsetDegrees = pixelSizeDegrees * view.getViewport().getWidth() / 4; labelPos = LatLon.fromDegrees(centerPos.getLatitude().degrees - labelOffsetDegrees, - centerPos.getLongitude().degrees - labelOffsetDegrees); + centerPos.getLongitude().degrees - labelOffsetDegrees); Double labelLatDegrees = labelPos.getLatitude().normalizedLatitude().degrees; labelLatDegrees = Math.min(Math.max(labelLatDegrees, -70), 70); labelPos = new LatLon(Angle.fromDegrees(labelLatDegrees), labelPos.getLongitude().normalizedLongitude()); - } - else + } else { labelPos = dc.getView().getEyePosition(); // fall back if no orbit view - + } return labelPos; } - protected Object createLineRenderable(Iterable positions, String pathType) - { + protected Object createLineRenderable(Iterable positions, String pathType) { Path path = new Path(positions); path.setPathType(pathType); path.setFollowTerrain(true); @@ -727,8 +662,8 @@ protected Object createLineRenderable(Iterable positions, St return path; } - protected class GridElement - { + protected class GridElement { + public final static String TYPE_LINE = "GridElement_Line"; public final static String TYPE_LINE_NORTH = "GridElement_LineNorth"; public final static String TYPE_LINE_SOUTH = "GridElement_LineSouth"; @@ -745,22 +680,18 @@ protected class GridElement public final String type; public double value; - public GridElement(Sector sector, Object renderable, String type) - { - if (sector == null) - { + public GridElement(Sector sector, Object renderable, String type) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (renderable == null) - { + if (renderable == null) { String message = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (type == null) - { + if (type == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -770,15 +701,12 @@ public GridElement(Sector sector, Object renderable, String type) this.type = type; } - public void setValue(double value) - { + public void setValue(double value) { this.value = value; } - public boolean isInView(DrawContext dc) - { - if (dc == null) - { + public boolean isInView(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -787,41 +715,37 @@ public boolean isInView(DrawContext dc) } @SuppressWarnings({"RedundantIfStatement"}) - public boolean isInView(DrawContext dc, Sector vs) - { - if (dc == null) - { + public boolean isInView(DrawContext dc, Sector vs) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vs == null) - { + if (vs == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.sector.intersects(vs)) + if (!this.sector.intersects(vs)) { return false; + } return true; } } // === Support methods === - - protected Vec4 getSurfacePoint(DrawContext dc, Angle latitude, Angle longitude) - { + protected Vec4 getSurfacePoint(DrawContext dc, Angle latitude, Angle longitude) { Vec4 surfacePoint = dc.getSurfaceGeometry().getSurfacePoint(latitude, longitude); - if (surfacePoint == null) + if (surfacePoint == null) { surfacePoint = dc.getGlobe().computePointFromPosition(new Position(latitude, longitude, - dc.getGlobe().getElevation(latitude, longitude))); + dc.getGlobe().getElevation(latitude, longitude))); + } return surfacePoint; } - protected double computeAltitudeAboveGround(DrawContext dc) - { + protected double computeAltitudeAboveGround(DrawContext dc) { View view = dc.getView(); Position eyePosition = view.getEyePosition(); Vec4 surfacePoint = getSurfacePoint(dc, eyePosition.getLatitude(), eyePosition.getLongitude()); @@ -829,62 +753,52 @@ protected double computeAltitudeAboveGround(DrawContext dc) return view.getEyePoint().distanceTo3(surfacePoint); } - protected void computeTruncatedSegment(Position p1, Position p2, Sector sector, ArrayList positions) - { - if (p1 == null || p2 == null) + protected void computeTruncatedSegment(Position p1, Position p2, Sector sector, ArrayList positions) { + if (p1 == null || p2 == null) { return; + } boolean p1In = sector.contains(p1); boolean p2In = sector.contains(p2); - if (!p1In && !p2In) - { + if (!p1In && !p2In) { // whole segment is (likely) outside return; } - if (p1In && p2In) - { + if (p1In && p2In) { // whole segment is (likely) inside positions.add(p1); positions.add(p2); - } - else - { + } else { // segment does cross the boundary Position outPoint = !p1In ? p1 : p2; Position inPoint = p1In ? p1 : p2; - for (int i = 1; i <= 2; i++) // there may be two intersections + for (int i = 1; i <= 2; i++) // there may be two intersections { LatLon intersection = null; if (outPoint.getLongitude().degrees > sector.getMaxLongitude().degrees - || (sector.getMaxLongitude().degrees == 180 && outPoint.getLongitude().degrees < 0)) - { + || (sector.getMaxLongitude().degrees == 180 && outPoint.getLongitude().degrees < 0)) { // intersect with east meridian intersection = greatCircleIntersectionAtLongitude( - inPoint, outPoint, sector.getMaxLongitude()); - } - else if (outPoint.getLongitude().degrees < sector.getMinLongitude().degrees - || (sector.getMinLongitude().degrees == -180 && outPoint.getLongitude().degrees > 0)) - { + inPoint, outPoint, sector.getMaxLongitude()); + } else if (outPoint.getLongitude().degrees < sector.getMinLongitude().degrees + || (sector.getMinLongitude().degrees == -180 && outPoint.getLongitude().degrees > 0)) { // intersect with west meridian intersection = greatCircleIntersectionAtLongitude( - inPoint, outPoint, sector.getMinLongitude()); - } - else if (outPoint.getLatitude().degrees > sector.getMaxLatitude().degrees) - { + inPoint, outPoint, sector.getMinLongitude()); + } else if (outPoint.getLatitude().degrees > sector.getMaxLatitude().degrees) { // intersect with top parallel intersection = greatCircleIntersectionAtLatitude( - inPoint, outPoint, sector.getMaxLatitude()); - } - else if (outPoint.getLatitude().degrees < sector.getMinLatitude().degrees) - { + inPoint, outPoint, sector.getMaxLatitude()); + } else if (outPoint.getLatitude().degrees < sector.getMinLatitude().degrees) { // intersect with bottom parallel intersection = greatCircleIntersectionAtLatitude( - inPoint, outPoint, sector.getMinLatitude()); + inPoint, outPoint, sector.getMinLatitude()); } - if (intersection != null) + if (intersection != null) { outPoint = new Position(intersection, outPoint.getElevation()); - else + } else { break; + } } positions.add(inPoint); positions.add(outPoint); @@ -894,35 +808,35 @@ else if (outPoint.getLatitude().degrees < sector.getMinLatitude().degrees) /** * Computes the intersection point position between a great circle segment and a meridian. * - * @param p1 the great circle segment start position. - * @param p2 the great circle segment end position. + * @param p1 the great circle segment start position. + * @param p2 the great circle segment end position. * @param longitude the meridian longitude Angle * * @return the intersection Position or null if there was no intersection found. */ - protected LatLon greatCircleIntersectionAtLongitude(LatLon p1, LatLon p2, Angle longitude) - { - if (p1.getLongitude().degrees == longitude.degrees) + protected LatLon greatCircleIntersectionAtLongitude(LatLon p1, LatLon p2, Angle longitude) { + if (p1.getLongitude().degrees == longitude.degrees) { return p1; - if (p2.getLongitude().degrees == longitude.degrees) + } + if (p2.getLongitude().degrees == longitude.degrees) { return p2; + } LatLon pos = null; Double deltaLon = getDeltaLongitude(p1, p2.getLongitude()).degrees; if (getDeltaLongitude(p1, longitude).degrees < deltaLon - && getDeltaLongitude(p2, longitude).degrees < deltaLon) - { + && getDeltaLongitude(p2, longitude).degrees < deltaLon) { int count = 0; double precision = 1d / 6378137d; // 1m angle in radians LatLon a = p1; LatLon b = p2; LatLon midPoint = greatCircleMidPoint(a, b); - while (getDeltaLongitude(midPoint, longitude).radians > precision && count <= 20) - { + while (getDeltaLongitude(midPoint, longitude).radians > precision && count <= 20) { count++; - if (getDeltaLongitude(a, longitude).degrees < getDeltaLongitude(b, longitude).degrees) + if (getDeltaLongitude(a, longitude).degrees < getDeltaLongitude(b, longitude).degrees) { b = midPoint; - else + } else { a = midPoint; + } midPoint = greatCircleMidPoint(a, b); } pos = midPoint; @@ -930,39 +844,38 @@ && getDeltaLongitude(p2, longitude).degrees < deltaLon) // System.out.println("Warning dichotomy loop aborted: " + p1 + " - " + p2 + " for lon " + longitude + " = " + pos); } // Adjust final longitude for an exact match - if (pos != null) + if (pos != null) { pos = new LatLon(pos.getLatitude(), longitude); + } return pos; } /** * Computes the intersection point position between a great circle segment and a parallel. * - * @param p1 the great circle segment start position. - * @param p2 the great circle segment end position. + * @param p1 the great circle segment start position. + * @param p2 the great circle segment end position. * @param latitude the parallel latitude Angle * * @return the intersection Position or null if there was no intersection found. */ - protected LatLon greatCircleIntersectionAtLatitude(LatLon p1, LatLon p2, Angle latitude) - { + protected LatLon greatCircleIntersectionAtLatitude(LatLon p1, LatLon p2, Angle latitude) { LatLon pos = null; if (Math.signum(p1.getLatitude().degrees - latitude.degrees) - != Math.signum(p2.getLatitude().degrees - latitude.degrees)) - { + != Math.signum(p2.getLatitude().degrees - latitude.degrees)) { int count = 0; double precision = 1d / 6378137d; // 1m angle in radians LatLon a = p1; LatLon b = p2; LatLon midPoint = greatCircleMidPoint(a, b); - while (Math.abs(midPoint.getLatitude().radians - latitude.radians) > precision && count <= 20) - { + while (Math.abs(midPoint.getLatitude().radians - latitude.radians) > precision && count <= 20) { count++; if (Math.signum(a.getLatitude().degrees - latitude.degrees) - != Math.signum(midPoint.getLatitude().degrees - latitude.degrees)) + != Math.signum(midPoint.getLatitude().degrees - latitude.degrees)) { b = midPoint; - else + } else { a = midPoint; + } midPoint = greatCircleMidPoint(a, b); } pos = midPoint; @@ -970,20 +883,19 @@ protected LatLon greatCircleIntersectionAtLatitude(LatLon p1, LatLon p2, Angle l // System.out.println("Warning dichotomy loop aborted: " + p1 + " - " + p2 + " for lat " + latitude + " = " + pos); } // Adjust final latitude for an exact match - if (pos != null) + if (pos != null) { pos = new LatLon(latitude, pos.getLongitude()); + } return pos; } - protected LatLon greatCircleMidPoint(LatLon p1, LatLon p2) - { + protected LatLon greatCircleMidPoint(LatLon p1, LatLon p2) { Angle azimuth = LatLon.greatCircleAzimuth(p1, p2); Angle distance = LatLon.greatCircleDistance(p1, p2); return LatLon.greatCircleEndPosition(p1, azimuth.radians, distance.radians / 2); } - protected Angle getDeltaLongitude(LatLon p1, Angle longitude) - { + protected Angle getDeltaLongitude(LatLon p1, Angle longitude) { double deltaLon = Math.abs(p1.getLongitude().degrees - longitude.degrees); return Angle.fromDegrees(deltaLon < 180 ? deltaLon : 360 - deltaLon); } diff --git a/src/gov/nasa/worldwind/layers/AbstractLayer.java b/src/gov/nasa/worldwind/layers/AbstractLayer.java index edc6405886..9b26e48185 100644 --- a/src/gov/nasa/worldwind/layers/AbstractLayer.java +++ b/src/gov/nasa/worldwind/layers/AbstractLayer.java @@ -20,8 +20,8 @@ * @author tag * @version $Id: AbstractLayer.java 2254 2014-08-22 17:02:46Z tgaskins $ */ -public abstract class AbstractLayer extends WWObjectImpl implements Layer -{ +public abstract class AbstractLayer extends WWObjectImpl implements Layer { + private boolean enabled = true; private boolean pickable = true; private double opacity = 1d; @@ -32,112 +32,91 @@ public abstract class AbstractLayer extends WWObjectImpl implements Layer private ScreenCredit screenCredit = null; private FileStore dataFileStore = WorldWind.getDataFileStore(); - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public boolean isPickEnabled() - { + public boolean isPickEnabled() { return pickable; } - public void setPickEnabled(boolean pickable) - { + public void setPickEnabled(boolean pickable) { this.pickable = pickable; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { Boolean oldEnabled = this.enabled; this.enabled = enabled; this.propertyChange(new PropertyChangeEvent(this, "Enabled", oldEnabled, this.enabled)); } - public String getName() - { + public String getName() { Object n = this.getValue(AVKey.DISPLAY_NAME); return n != null ? n.toString() : this.toString(); } - public void setName(String name) - { + public void setName(String name) { this.setValue(AVKey.DISPLAY_NAME, name); } - public String toString() - { + public String toString() { Object n = this.getValue(AVKey.DISPLAY_NAME); return n != null ? n.toString() : super.toString(); } - public double getOpacity() - { + public double getOpacity() { return opacity; } - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { this.opacity = opacity; } - public double getMinActiveAltitude() - { + public double getMinActiveAltitude() { return minActiveAltitude; } - public void setMinActiveAltitude(double minActiveAltitude) - { + public void setMinActiveAltitude(double minActiveAltitude) { this.minActiveAltitude = minActiveAltitude; } - public double getMaxActiveAltitude() - { + public double getMaxActiveAltitude() { return maxActiveAltitude; } - public void setMaxActiveAltitude(double maxActiveAltitude) - { + public void setMaxActiveAltitude(double maxActiveAltitude) { this.maxActiveAltitude = maxActiveAltitude; } - public Double getMinEffectiveAltitude(Double radius) - { + public Double getMinEffectiveAltitude(Double radius) { return null; } - public Double getMaxEffectiveAltitude(Double radius) - { + public Double getMaxEffectiveAltitude(Double radius) { return null; } - public double getScale() - { + public double getScale() { Object o = this.getValue(AVKey.MAP_SCALE); return o != null && o instanceof Double ? (Double) o : 1; } - public boolean isNetworkRetrievalEnabled() - { + public boolean isNetworkRetrievalEnabled() { return networkDownloadEnabled; } - public void setNetworkRetrievalEnabled(boolean networkDownloadEnabled) - { + public void setNetworkRetrievalEnabled(boolean networkDownloadEnabled) { this.networkDownloadEnabled = networkDownloadEnabled; } - public FileStore getDataFileStore() - { + public FileStore getDataFileStore() { return this.dataFileStore; } - public void setDataFileStore(FileStore fileStore) - { - if (fileStore == null) - { + public void setDataFileStore(FileStore fileStore) { + if (fileStore == null) { String message = Logging.getMessage("nullValue.FileStoreIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -146,10 +125,8 @@ public void setDataFileStore(FileStore fileStore) this.dataFileStore = fileStore; } - public boolean isLayerInView(DrawContext dc) - { - if (dc == null) - { + public boolean isLayerInView(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -158,61 +135,57 @@ public boolean isLayerInView(DrawContext dc) return true; } - public boolean isLayerActive(DrawContext dc) - { - if (dc == null) - { + public boolean isLayerActive(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (null == dc.getView()) - { + if (null == dc.getView()) { String message = Logging.getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } Position eyePos = dc.getView().getEyePosition(); - if (eyePos == null) + if (eyePos == null) { return false; + } double altitude = eyePos.getElevation(); return altitude >= this.minActiveAltitude && altitude <= this.maxActiveAltitude; } - public void preRender(DrawContext dc) - { - if (!this.enabled) + public void preRender(DrawContext dc) { + if (!this.enabled) { return; // Don't check for arg errors if we're disabled - - if (null == dc) - { + } + if (null == dc) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (null == dc.getGlobe()) - { + if (null == dc.getGlobe()) { String message = Logging.getMessage("layers.AbstractLayer.NoGlobeSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (null == dc.getView()) - { + if (null == dc.getView()) { String message = Logging.getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (!this.isLayerActive(dc)) + if (!this.isLayerActive(dc)) { return; + } - if (!this.isLayerInView(dc)) + if (!this.isLayerInView(dc)) { return; + } this.doPreRender(dc); } @@ -221,80 +194,75 @@ public void preRender(DrawContext dc) * @param dc the current draw context * * @throws IllegalArgumentException if dc is null, or dc's Globe or - * View is null + * View is null */ - public void render(DrawContext dc) - { - if (!this.enabled) + public void render(DrawContext dc) { + if (!this.enabled) { return; // Don't check for arg errors if we're disabled - - if (null == dc) - { + } + if (null == dc) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (null == dc.getGlobe()) - { + if (null == dc.getGlobe()) { String message = Logging.getMessage("layers.AbstractLayer.NoGlobeSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (null == dc.getView()) - { + if (null == dc.getView()) { String message = Logging.getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (!this.isLayerActive(dc)) + if (!this.isLayerActive(dc)) { return; + } - if (!this.isLayerInView(dc)) + if (!this.isLayerInView(dc)) { return; + } this.doRender(dc); } - public void pick(DrawContext dc, java.awt.Point point) - { - if (!this.enabled) + public void pick(DrawContext dc, java.awt.Point point) { + if (!this.enabled) { return; // Don't check for arg errors if we're disabled - - if (null == dc) - { + } + if (null == dc) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (null == dc.getGlobe()) - { + if (null == dc.getGlobe()) { String message = Logging.getMessage("layers.AbstractLayer.NoGlobeSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (null == dc.getView()) - { + if (null == dc.getView()) { String message = Logging.getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (!this.isLayerActive(dc)) + if (!this.isLayerActive(dc)) { return; + } - if (!this.isLayerInView(dc)) + if (!this.isLayerInView(dc)) { return; + } this.doPick(dc, point); } - protected void doPick(DrawContext dc, java.awt.Point point) - { + protected void doPick(DrawContext dc, java.awt.Point point) { // any state that could change the color needs to be disabled, such as GL_TEXTURE, GL_LIGHTING or GL_FOG. // re-draw with unique colors // store the object info in the selectable objects table @@ -307,58 +275,48 @@ public void dispose() // override if disposal is a supported operation { } - protected void doPreRender(DrawContext dc) - { + protected void doPreRender(DrawContext dc) { } protected abstract void doRender(DrawContext dc); - public boolean isAtMaxResolution() - { + public boolean isAtMaxResolution() { return !this.isMultiResolution(); } - public boolean isMultiResolution() - { + public boolean isMultiResolution() { return false; } - public String getRestorableState() - { + public String getRestorableState() { return null; } - public void restoreState(String stateInXml) - { + public void restoreState(String stateInXml) { String message = Logging.getMessage("RestorableSupport.RestoreNotSupported"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } - public void setExpiryTime(long expiryTime) - { + public void setExpiryTime(long expiryTime) { this.expiryTime = expiryTime; } - public long getExpiryTime() - { + public long getExpiryTime() { return this.expiryTime; } - protected ScreenCredit getScreenCredit() - { + protected ScreenCredit getScreenCredit() { return screenCredit; } - protected void setScreenCredit(ScreenCredit screenCredit) - { + protected void setScreenCredit(ScreenCredit screenCredit) { this.screenCredit = screenCredit; } //**************************************************************// //******************** Configuration *************************// //**************************************************************// - /** * Returns true if a specified DOM document is a Layer configuration document, and false otherwise. * @@ -368,10 +326,8 @@ protected void setScreenCredit(ScreenCredit screenCredit) * * @throws IllegalArgumentException if document is null. */ - public static boolean isLayerConfigDocument(Element domElement) - { - if (domElement == null) - { + public static boolean isLayerConfigDocument(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -388,30 +344,29 @@ public static boolean isLayerConfigDocument(Element domElement) * following parameters: * + * AVKey#OPACITY} + * * + * AVKey#MAP_SCALE} + * *
        Append Elements
        ParameterElement PathType
        {@link * AVKey#DISPLAY_NAME}DisplayNameString
        {@link - * AVKey#OPACITY}OpacityDouble
        {@link AVKey#MAX_ACTIVE_ALTITUDE}ActiveAltitudes/@maxDouble
        OpacityDouble
        {@link AVKey#MAX_ACTIVE_ALTITUDE}ActiveAltitudes/@maxDouble
        {@link AVKey#MIN_ACTIVE_ALTITUDE}ActiveAltitudes/@minDouble
        {@link * AVKey#NETWORK_RETRIEVAL_ENABLED}NetworkRetrievalEnabledBoolean
        {@link - * AVKey#MAP_SCALE}MapScaleDouble
        {@link AVKey#SCREEN_CREDIT}ScreenCreditScreenCredit
        MapScaleDouble
        {@link AVKey#SCREEN_CREDIT}ScreenCreditScreenCredit
        * - * @param params the key-value pairs which define the layer configuration parameters. + * @param params the key-value pairs which define the layer configuration parameters. * @param context the XML document root on which to append layer configuration elements. * * @return a reference to context. * * @throws IllegalArgumentException if either the parameters or the context are null. */ - public static Element createLayerConfigElements(AVList params, Element context) - { - if (params == null) - { + public static Element createLayerConfigElements(AVList params, Element context) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -422,13 +377,14 @@ public static Element createLayerConfigElements(AVList params, Element context) Double maxAlt = AVListImpl.getDoubleValue(params, AVKey.MAX_ACTIVE_ALTITUDE); Double minAlt = AVListImpl.getDoubleValue(params, AVKey.MIN_ACTIVE_ALTITUDE); - if (maxAlt != null || minAlt != null) - { + if (maxAlt != null || minAlt != null) { Element el = WWXML.appendElementPath(context, "ActiveAltitudes"); - if (maxAlt != null) + if (maxAlt != null) { WWXML.setDoubleAttribute(el, "max", maxAlt); - if (minAlt != null) + } + if (minAlt != null) { WWXML.setDoubleAttribute(el, "min", minAlt); + } } WWXML.checkAndAppendBooleanElement(params, AVKey.NETWORK_RETRIEVAL_ENABLED, context, "NetworkRetrievalEnabled"); @@ -445,31 +401,31 @@ public static Element createLayerConfigElements(AVList params, Element context) * and parameter names are: * + * AVKey#OPACITY} + * *
        Supported Names
        ParameterElement PathType
        {@link * AVKey#DISPLAY_NAME}DisplayNameString
        {@link - * AVKey#OPACITY}OpacityDouble
        {@link AVKey#MAX_ACTIVE_ALTITUDE}ActiveAltitudes/@maxDouble
        OpacityDouble
        {@link AVKey#MAX_ACTIVE_ALTITUDE}ActiveAltitudes/@maxDouble
        {@link AVKey#MIN_ACTIVE_ALTITUDE}ActiveAltitudes/@minDouble
        {@link * AVKey#NETWORK_RETRIEVAL_ENABLED}NetworkRetrievalEnabledBoolean
        {@link * AVKey#MAP_SCALE}MapScaleDouble
        {@link AVKey#SCREEN_CREDIT}ScreenCredit{@link * ScreenCredit}
        * * @param domElement the XML document root to parse for layer configuration elements. - * @param params the output key-value pairs which recieve the layer configuration parameters. A null reference - * is permitted. + * @param params the output key-value pairs which recieve the layer configuration parameters. A null reference is + * permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - public static AVList getLayerConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + public static AVList getLayerConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } XPath xpath = WWXML.makeXPath(); @@ -478,13 +434,13 @@ public static AVList getLayerConfigParams(Element domElement, AVList params) WWXML.checkAndSetDoubleParam(domElement, params, AVKey.MAX_ACTIVE_ALTITUDE, "ActiveAltitudes/@max", xpath); WWXML.checkAndSetDoubleParam(domElement, params, AVKey.MIN_ACTIVE_ALTITUDE, "ActiveAltitudes/@min", xpath); WWXML.checkAndSetBooleanParam(domElement, params, AVKey.NETWORK_RETRIEVAL_ENABLED, "NetworkRetrievalEnabled", - xpath); + xpath); WWXML.checkAndSetDoubleParam(domElement, params, AVKey.MAP_SCALE, "MapScale", xpath); WWXML.checkAndSetScreenCreditParam(domElement, params, AVKey.SCREEN_CREDIT, "ScreenCredit", xpath); WWXML.checkAndSetIntegerParam(domElement, params, AVKey.MAX_ABSENT_TILE_ATTEMPTS, "MaxAbsentTileAttempts", - xpath); + xpath); WWXML.checkAndSetIntegerParam(domElement, params, AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL, - "MinAbsentTileCheckInterval", xpath); + "MinAbsentTileCheckInterval", xpath); WWXML.checkAndSetBooleanParam(domElement, params, AVKey.PICK_ENABLED, "PickEnabled", xpath); return params; diff --git a/src/gov/nasa/worldwind/layers/AirspaceLayer.java b/src/gov/nasa/worldwind/layers/AirspaceLayer.java index 2bba0a9536..3351d273e9 100644 --- a/src/gov/nasa/worldwind/layers/AirspaceLayer.java +++ b/src/gov/nasa/worldwind/layers/AirspaceLayer.java @@ -19,14 +19,15 @@ * @version $Id: AirspaceLayer.java 2231 2014-08-15 19:03:12Z dcollins $ * @deprecated Use {@link RenderableLayer} instead. */ -public class AirspaceLayer extends AbstractLayer -{ +public class AirspaceLayer extends AbstractLayer { + private final java.util.Collection airspaces = new java.util.concurrent.ConcurrentLinkedQueue(); private Iterable airspacesOverride; - /** Creates a new Airspace with an empty collection of Airspaces. */ - public AirspaceLayer() - { + /** + * Creates a new Airspace with an empty collection of Airspaces. + */ + public AirspaceLayer() { } /** @@ -36,20 +37,17 @@ public AirspaceLayer() * @param airspace the airspace to add. * * @throws IllegalArgumentException if the airspace is null. - * @throws IllegalStateException if a custom Iterable has been specified by a call to setRenderables. - * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#addRenderable(gov.nasa.worldwind.render.Renderable)} - * instead. + * @throws IllegalStateException if a custom Iterable has been specified by a call to setRenderables. + * @deprecated Use {@link RenderableLayer} and + * {@link RenderableLayer#addRenderable(gov.nasa.worldwind.render.Renderable)} instead. */ - public void addAirspace(Airspace airspace) - { - if (airspace == null) - { + public void addAirspace(Airspace airspace) { + if (airspace == null) { String msg = "nullValue.AirspaceIsNull"; Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.airspacesOverride != null) - { + if (this.airspacesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -66,29 +64,26 @@ public void addAirspace(Airspace airspace) * @param airspaces the airspaces to add. * * @throws IllegalArgumentException if the iterable is null. - * @throws IllegalStateException if a custom Iterable has been specified by a call to setRenderables. + * @throws IllegalStateException if a custom Iterable has been specified by a call to setRenderables. * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#addRenderables(Iterable)} instead. */ - public void addAirspaces(Iterable airspaces) - { - if (airspaces == null) - { + public void addAirspaces(Iterable airspaces) { + if (airspaces == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.airspacesOverride != null) - { + if (this.airspacesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - for (Airspace airspace : airspaces) - { + for (Airspace airspace : airspaces) { // Internal list of airspaces does not accept null values. - if (airspace != null) + if (airspace != null) { this.airspaces.add(airspace); + } } } @@ -100,20 +95,17 @@ public void addAirspaces(Iterable airspaces) * @param airspace the airspace to remove. * * @throws IllegalArgumentException if the airspace is null. - * @throws IllegalStateException if a custom Iterable has been specified by a call to setRenderables. - * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#removeRenderable(gov.nasa.worldwind.render.Renderable)} - * instead. + * @throws IllegalStateException if a custom Iterable has been specified by a call to setRenderables. + * @deprecated Use {@link RenderableLayer} and + * {@link RenderableLayer#removeRenderable(gov.nasa.worldwind.render.Renderable)} instead. */ - public void removeAirspace(Airspace airspace) - { - if (airspace == null) - { + public void removeAirspace(Airspace airspace) { + if (airspace == null) { String msg = "nullValue.AirspaceIsNull"; Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.airspacesOverride != null) - { + if (this.airspacesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -129,10 +121,8 @@ public void removeAirspace(Airspace airspace) * @throws IllegalStateException If a custom Iterable has been specified by a call to setAirspaces. * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#removeAllRenderables()} instead. */ - public void removeAllAirspaces() - { - if (this.airspacesOverride != null) - { + public void removeAllAirspaces() { + if (this.airspacesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -141,10 +131,10 @@ public void removeAllAirspaces() clearAirspaces(); } - private void clearAirspaces() - { - if (this.airspaces != null && this.airspaces.size() > 0) + private void clearAirspaces() { + if (this.airspaces != null && this.airspaces.size() > 0) { this.airspaces.clear(); + } } /** @@ -157,14 +147,10 @@ private void clearAirspaces() * * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#getRenderables()} instead. */ - public Iterable getAirspaces() - { - if (this.airspacesOverride != null) - { + public Iterable getAirspaces() { + if (this.airspacesOverride != null) { return this.airspacesOverride; - } - else - { + } else { // Return an unmodifiable reference to the internal list of airspaces. // This prevents callers from changing this list and invalidating any invariants we have established. return java.util.Collections.unmodifiableCollection(this.airspaces); @@ -179,14 +165,10 @@ public Iterable getAirspaces() * * @return Iterable of currently active Airspaces. */ - private Iterable getActiveAirspaces() - { - if (this.airspacesOverride != null) - { + private Iterable getActiveAirspaces() { + if (this.airspacesOverride != null) { return this.airspacesOverride; - } - else - { + } else { return this.airspaces; } } @@ -204,8 +186,7 @@ private Iterable getActiveAirspaces() * * @deprecated Use {@link RenderableLayer} and {@link RenderableLayer#setRenderables(Iterable)} instead. */ - public void setAirspaces(Iterable airspaceIterable) - { + public void setAirspaces(Iterable airspaceIterable) { this.airspacesOverride = airspaceIterable; // Clear the internal collection of Airspaces. clearAirspaces(); @@ -217,10 +198,9 @@ public void setAirspaces(Iterable airspaceIterable) * @return false * * @deprecated Use {@link gov.nasa.worldwind.render.ShapeAttributes#isEnableAntialiasing()} on each Airspace - * instance in the layer. + * instance in the layer. */ - public boolean isEnableAntialiasing() - { + public boolean isEnableAntialiasing() { return false; // deprecated method } @@ -230,10 +210,9 @@ public boolean isEnableAntialiasing() * @param enable ignored. * * @deprecated Use {@link gov.nasa.worldwind.render.ShapeAttributes#setEnableAntialiasing(boolean)} on each Airspace - * instance in the layer. + * instance in the layer. */ - public void setEnableAntialiasing(boolean enable) - { + public void setEnableAntialiasing(boolean enable) { // deprecated method } @@ -243,10 +222,9 @@ public void setEnableAntialiasing(boolean enable) * @return false * * @deprecated Control over airspace blending is no longer supported. Airspaces implicitly blend themselves with - * other objects in the scene. + * other objects in the scene. */ - public boolean isEnableBlending() - { + public boolean isEnableBlending() { return false; // deprecated method } @@ -256,10 +234,9 @@ public boolean isEnableBlending() * @param enable ignored. * * @deprecated Control over airspace blending is no longer supported. Airspaces implicitly blend themselves with - * other objects in the scene. + * other objects in the scene. */ - public void setEnableBlending(boolean enable) - { + public void setEnableBlending(boolean enable) { // deprecated method } @@ -269,10 +246,9 @@ public void setEnableBlending(boolean enable) * @return false * * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#isEnableDepthOffset()} on each Airspace - * instance in the layer. + * instance in the layer. */ - public boolean isEnableDepthOffset() - { + public boolean isEnableDepthOffset() { return false; // deprecated method } @@ -282,10 +258,9 @@ public boolean isEnableDepthOffset() * @param enable ignored. * * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#setEnableDepthOffset(boolean)} on each - * Airspace instance in the layer. + * Airspace instance in the layer. */ - public void setEnableDepthOffset(boolean enable) - { + public void setEnableDepthOffset(boolean enable) { // deprecated method } @@ -295,10 +270,9 @@ public void setEnableDepthOffset(boolean enable) * @return false * * @deprecated Use {@link gov.nasa.worldwind.render.ShapeAttributes#isEnableLighting()} on each Airspace instance in - * the layer. + * the layer. */ - public boolean isEnableLighting() - { + public boolean isEnableLighting() { return false; // deprecated method } @@ -308,10 +282,9 @@ public boolean isEnableLighting() * @param enable ignored. * * @deprecated Use {@link gov.nasa.worldwind.render.ShapeAttributes#isEnableLighting()} on each Airspace instance in - * the layer. + * the layer. */ - public void setEnableLighting(boolean enable) - { + public void setEnableLighting(boolean enable) { // deprecated method } @@ -322,8 +295,7 @@ public void setEnableLighting(boolean enable) * * @deprecated Control over drawing Airspace extents is no longer supported. */ - public boolean isDrawExtents() - { + public boolean isDrawExtents() { return false; // deprecated method } @@ -334,8 +306,7 @@ public boolean isDrawExtents() * * @deprecated Control over drawing Airspace extents is no longer supported. */ - public void setDrawExtents(boolean draw) - { + public void setDrawExtents(boolean draw) { // deprecated method } @@ -346,8 +317,7 @@ public void setDrawExtents(boolean draw) * * @deprecated Control over drawing Airspace in wireframe mode is no longer supported. */ - public boolean isDrawWireframe() - { + public boolean isDrawWireframe() { return false; // deprecated method } @@ -358,8 +328,7 @@ public boolean isDrawWireframe() * * @deprecated Control over drawing Airspace in wireframe mode is no longer supported. */ - public void setDrawWireframe(boolean draw) - { + public void setDrawWireframe(boolean draw) { // deprecated method } @@ -371,8 +340,7 @@ public void setDrawWireframe(boolean draw) * @deprecated Control over Airspace depth offset is no longer supported. See {@link * gov.nasa.worldwind.render.airspaces.Airspace#setEnableDepthOffset(boolean)}. */ - public Double getDepthOffsetFactor() - { + public Double getDepthOffsetFactor() { return 0d; // deprecated method } @@ -384,8 +352,7 @@ public Double getDepthOffsetFactor() * @deprecated Control over Airspace depth factor is no longer supported. See {@link * gov.nasa.worldwind.render.airspaces.Airspace#setEnableDepthOffset(boolean)}. */ - public void setDepthOffsetFactor(Double factor) - { + public void setDepthOffsetFactor(Double factor) { // deprecated method } @@ -397,8 +364,7 @@ public void setDepthOffsetFactor(Double factor) * @deprecated Control over Airspace depth units is no longer supported. See {@link * gov.nasa.worldwind.render.airspaces.Airspace#setEnableDepthOffset(boolean)}. */ - public Double getDepthOffsetUnits() - { + public Double getDepthOffsetUnits() { return 0d; // deprecated method } @@ -410,8 +376,7 @@ public Double getDepthOffsetUnits() * @deprecated Control over Airspace depth units is no longer supported. See {@link * gov.nasa.worldwind.render.airspaces.Airspace#setEnableDepthOffset(boolean)}. */ - public void setDepthOffsetUnits(Double units) - { + public void setDepthOffsetUnits(Double units) { // deprecated method } @@ -421,10 +386,9 @@ public void setDepthOffsetUnits(Double units) * @return false * * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#isEnableBatchRendering()} on each Airspace - * instance in the layer. + * instance in the layer. */ - public boolean isEnableBatchRendering() - { + public boolean isEnableBatchRendering() { return false; // deprecated method } @@ -434,10 +398,9 @@ public boolean isEnableBatchRendering() * @param enableBatchRendering ignored * * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#setEnableBatchRendering(boolean)} on each - * Airspace instance in the layer. + * Airspace instance in the layer. */ - public void setEnableBatchRendering(boolean enableBatchRendering) - { + public void setEnableBatchRendering(boolean enableBatchRendering) { // deprecated method } @@ -447,10 +410,9 @@ public void setEnableBatchRendering(boolean enableBatchRendering) * @return false * * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#isEnableBatchPicking()} on each Airspace - * instance in the layer. + * instance in the layer. */ - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return false; // deprecated method } @@ -460,25 +422,21 @@ public boolean isEnableBatchPicking() * @param enableBatchPicking ignored * * @deprecated Use {@link gov.nasa.worldwind.render.airspaces.Airspace#setEnableBatchPicking(boolean)} on each - * Airspace instance in the layer. + * Airspace instance in the layer. */ - public void setEnableBatchPicking(boolean enableBatchPicking) - { + public void setEnableBatchPicking(boolean enableBatchPicking) { // deprecated method } @Override - protected void doPick(DrawContext dc, java.awt.Point pickPoint) - { - for (Airspace airspace : this.getActiveAirspaces()) - { - try - { + protected void doPick(DrawContext dc, java.awt.Point pickPoint) { + for (Airspace airspace : this.getActiveAirspaces()) { + try { if (airspace != null) // caller-specified Iterables can include null elements + { airspace.render(dc); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhileRenderingAirspace"); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); // continue to next airspace @@ -487,17 +445,14 @@ protected void doPick(DrawContext dc, java.awt.Point pickPoint) } @Override - protected void doRender(DrawContext dc) - { - for (Airspace airspace : this.getActiveAirspaces()) - { - try - { + protected void doRender(DrawContext dc) { + for (Airspace airspace : this.getActiveAirspaces()) { + try { if (airspace != null) // caller-specified Iterables can include null elements + { airspace.render(dc); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhileRenderingAirspace"); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); // continue to next airspace @@ -506,8 +461,7 @@ protected void doRender(DrawContext dc) } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.AirspaceLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/AnnotationLayer.java b/src/gov/nasa/worldwind/layers/AnnotationLayer.java index 29bb6fd0f6..8e297f510c 100644 --- a/src/gov/nasa/worldwind/layers/AnnotationLayer.java +++ b/src/gov/nasa/worldwind/layers/AnnotationLayer.java @@ -19,16 +19,17 @@ * @see gov.nasa.worldwind.render.Annotation * @see gov.nasa.worldwind.render.AnnotationRenderer */ -public class AnnotationLayer extends AbstractLayer -{ - protected final java.util.Collection annotations = - new java.util.concurrent.ConcurrentLinkedQueue(); +public class AnnotationLayer extends AbstractLayer { + + protected final java.util.Collection annotations + = new java.util.concurrent.ConcurrentLinkedQueue(); protected Iterable annotationsOverride; private AnnotationRenderer annotationRenderer = new BasicAnnotationRenderer(); - /** Creates a new AnnotationLayer with an empty collection of Annotations. */ - public AnnotationLayer() - { + /** + * Creates a new AnnotationLayer with an empty collection of Annotations. + */ + public AnnotationLayer() { } /** @@ -38,18 +39,15 @@ public AnnotationLayer() * @param annotation Annotation to add. * * @throws IllegalArgumentException If annotation is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setAnnotations. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setAnnotations. */ - public void addAnnotation(Annotation annotation) - { - if (annotation == null) - { + public void addAnnotation(Annotation annotation) { + if (annotation == null) { String msg = Logging.getMessage("nullValue.AnnotationIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.annotationsOverride != null) - { + if (this.annotationsOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -65,28 +63,25 @@ public void addAnnotation(Annotation annotation) * @param annotations Annotations to add. * * @throws IllegalArgumentException If annotations is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setAnnotations. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setAnnotations. */ - public void addAnnotations(Iterable annotations) - { - if (annotations == null) - { + public void addAnnotations(Iterable annotations) { + if (annotations == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.annotationsOverride != null) - { + if (this.annotationsOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - for (Annotation annotation : annotations) - { + for (Annotation annotation : annotations) { // Internal list of annotations does not accept null values. - if (annotation != null) + if (annotation != null) { this.annotations.add(annotation); + } } } @@ -98,18 +93,15 @@ public void addAnnotations(Iterable annotations) * @param annotation Annotation to remove. * * @throws IllegalArgumentException If annotation is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setAnnotations. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setAnnotations. */ - public void removeAnnotation(Annotation annotation) - { - if (annotation == null) - { + public void removeAnnotation(Annotation annotation) { + if (annotation == null) { String msg = Logging.getMessage("nullValue.IconIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.annotationsOverride != null) - { + if (this.annotationsOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -124,10 +116,8 @@ public void removeAnnotation(Annotation annotation) * * @throws IllegalStateException If a custom Iterable has been specified by a call to setAnnotations. */ - public void removeAllAnnotations() - { - if (this.annotationsOverride != null) - { + public void removeAllAnnotations() { + if (this.annotationsOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -136,10 +126,10 @@ public void removeAllAnnotations() clearAnnotations(); } - protected void clearAnnotations() - { - if (this.annotations != null && this.annotations.size() > 0) + protected void clearAnnotations() { + if (this.annotations != null && this.annotations.size() > 0) { this.annotations.clear(); + } } /** @@ -150,8 +140,7 @@ protected void clearAnnotations() * * @return Iterable of currently active Annotations. */ - public Iterable getAnnotations() - { + public Iterable getAnnotations() { return getActiveAnnotations(); } @@ -163,14 +152,10 @@ public Iterable getAnnotations() * * @return Iterable of currently active Annotations. */ - protected Iterable getActiveAnnotations() - { - if (this.annotationsOverride != null) - { + protected Iterable getActiveAnnotations() { + if (this.annotationsOverride != null) { return this.annotationsOverride; - } - else - { + } else { // Return an unmodifiable reference to the internal list of annotations. // This prevents callers from changing this list and invalidating any invariants we have established. return java.util.Collections.unmodifiableCollection(this.annotations); @@ -187,10 +172,9 @@ protected Iterable getActiveAnnotations() * collection. * * @param annotationIterable Iterable to use instead of this layer's internal collection, or null to use this - * layer's internal collection. + * layer's internal collection. */ - public void setAnnotations(Iterable annotationIterable) - { + public void setAnnotations(Iterable annotationIterable) { this.annotationsOverride = annotationIterable; // Clear the internal collection of Annotations. clearAnnotations(); @@ -202,8 +186,7 @@ public void setAnnotations(Iterable annotationIterable) * @param opacity the current opacity value, which is ignored by this layer. */ @Override - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { super.setOpacity(opacity); } @@ -214,8 +197,7 @@ public void setOpacity(double opacity) * @return The layer opacity, a value between 0 and 1. */ @Override - public double getOpacity() - { + public double getOpacity() { return super.getOpacity(); } @@ -224,8 +206,7 @@ public double getOpacity() * * @return AnnotationRenderer used to pick and render Annotations. */ - public AnnotationRenderer getAnnotationRenderer() - { + public AnnotationRenderer getAnnotationRenderer() { return this.annotationRenderer; } @@ -236,10 +217,8 @@ public AnnotationRenderer getAnnotationRenderer() * * @throws IllegalArgumentException If annotationRenderer is null. */ - public void setAnnotationRenderer(AnnotationRenderer annotationRenderer) - { - if (annotationRenderer == null) - { + public void setAnnotationRenderer(AnnotationRenderer annotationRenderer) { + if (annotationRenderer == null) { String msg = Logging.getMessage("nullValue.RendererIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -249,20 +228,17 @@ public void setAnnotationRenderer(AnnotationRenderer annotationRenderer) } @Override - protected void doPick(DrawContext dc, java.awt.Point pickPoint) - { + protected void doPick(DrawContext dc, java.awt.Point pickPoint) { this.annotationRenderer.pick(dc, getActiveAnnotations(), pickPoint, this); } @Override - protected void doRender(DrawContext dc) - { + protected void doRender(DrawContext dc) { this.annotationRenderer.render(dc, getActiveAnnotations(), this); } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.AnnotationLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/BasicLayerFactory.java b/src/gov/nasa/worldwind/layers/BasicLayerFactory.java index d4979aa638..7b788a59c6 100644 --- a/src/gov/nasa/worldwind/layers/BasicLayerFactory.java +++ b/src/gov/nasa/worldwind/layers/BasicLayerFactory.java @@ -22,11 +22,12 @@ * @author dcollins * @version $Id: BasicLayerFactory.java 2348 2014-09-25 23:35:46Z dcollins $ */ -public class BasicLayerFactory extends BasicFactory -{ - /** Creates an instance of BasicLayerFactory; otherwise does nothing. */ - public BasicLayerFactory() - { +public class BasicLayerFactory extends BasicFactory { + + /** + * Creates an instance of BasicLayerFactory; otherwise does nothing. + */ + public BasicLayerFactory() { } /** @@ -46,16 +47,14 @@ public BasicLayerFactory() * @return a layer or layer list. * * @throws IllegalArgumentException if the configuration file name is null or an empty string. - * @throws WWUnrecognizedException if the layer service type is unrecognized. - * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is - * included as the {@link Exception#initCause(Throwable)}. + * @throws WWUnrecognizedException if the layer service type is unrecognized. + * @throws WWRuntimeException if object creation fails. The exception indicating the source of the failure is + * included as the {@link Exception#initCause(Throwable)}. */ - public Object createFromConfigSource(Object configSource, AVList params) - { + public Object createFromConfigSource(Object configSource, AVList params) { Object layerOrLists = super.createFromConfigSource(configSource, params); - if (layerOrLists == null) - { + if (layerOrLists == null) { String msg = Logging.getMessage("generic.UnrecognizedDocument", configSource); throw new WWUnrecognizedException(msg); } @@ -64,27 +63,24 @@ public Object createFromConfigSource(Object configSource, AVList params) } @Override - protected Layer doCreateFromCapabilities(OGCCapabilities caps, AVList params) - { + protected Layer doCreateFromCapabilities(OGCCapabilities caps, AVList params) { String serviceName = caps.getServiceInformation().getServiceName(); if (serviceName == null || !(serviceName.equalsIgnoreCase(OGCConstants.WMS_SERVICE_NAME) - || serviceName.contains("WMS"))) - { + || serviceName.contains("WMS"))) { String message = Logging.getMessage("WMS.NotWMSService", serviceName != null ? serviceName : "null"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } - if (params.getStringValue(AVKey.LAYER_NAMES) == null) - { + if (params.getStringValue(AVKey.LAYER_NAMES) == null) { // Use the first named layer since no other guidance given List namedLayers = ((WMSCapabilities) caps).getNamedLayers(); - if (namedLayers == null || namedLayers.size() == 0 || namedLayers.get(0) == null) - { + if (namedLayers == null || namedLayers.size() == 0 || namedLayers.get(0) == null) { String message = Logging.getMessage("WMS.NoLayersFound"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -101,32 +97,35 @@ protected Layer doCreateFromCapabilities(OGCCapabilities caps, AVList params) * lists and included layers are created recursively. * * @param domElement an XML element describing the layers and/or layer lists. - * @param params any properties to apply when creating the included layers. + * @param params any properties to apply when creating the included layers. * * @return a Layer, LayerList or array of LayerLists, as described by the - * specified description. + * specified description. * * @throws Exception if an exception occurs during creation. Exceptions occurring during creation of internal layers - * or layer lists are not re-thrown but are logged. The layer or layer list associated with the - * exception is not contained in the returned object. + * or layer lists are not re-thrown but are logged. The layer or layer list associated with the exception is not + * contained in the returned object. */ @Override - protected Object doCreateFromElement(Element domElement, AVList params) throws Exception - { + protected Object doCreateFromElement(Element domElement, AVList params) throws Exception { Element[] elements = WWXML.getElements(domElement, "//LayerList", null); - if (elements != null && elements.length > 0) + if (elements != null && elements.length > 0) { return createLayerLists(elements, params); + } elements = WWXML.getElements(domElement, "./Layer", null); - if (elements != null && elements.length > 1) + if (elements != null && elements.length > 1) { return createLayerList(elements, params); + } - if (elements != null && elements.length == 1) + if (elements != null && elements.length == 1) { return this.createFromLayerDocument(elements[0], params); + } String localName = WWXML.getUnqualifiedName(domElement); - if (localName != null && localName.equals("Layer")) + if (localName != null && localName.equals("Layer")) { return this.createFromLayerDocument(domElement, params); + } return null; } @@ -139,46 +138,39 @@ protected Object doCreateFromElement(Element domElement, AVList params) throws E * re-thrown. The layers associated with the exceptions are not included in the returned layer list. * * @param elements the XML elements describing the layer lists to create. - * @param params any parameters to apply when creating the included layers. + * @param params any parameters to apply when creating the included layers. * * @return an array containing the specified layer lists. */ - protected LayerList[] createLayerLists(Element[] elements, AVList params) - { + protected LayerList[] createLayerLists(Element[] elements, AVList params) { ArrayList layerLists = new ArrayList(); - for (Element element : elements) - { - try - { + for (Element element : elements) { + try { String href = WWXML.getText(element, "@href"); - if (href != null && href.length() > 0) - { + if (href != null && href.length() > 0) { Object o = this.createFromConfigSource(href, params); - if (o == null) + if (o == null) { continue; + } - if (o instanceof Layer) - { + if (o instanceof Layer) { LayerList ll = new LayerList(); ll.add((Layer) o); o = ll; } - if (o instanceof LayerList) - { + if (o instanceof LayerList) { LayerList list = (LayerList) o; - if (list != null && list.size() > 0) + if (list != null && list.size() > 0) { layerLists.add(list); - } - else if (o instanceof LayerList[]) - { + } + } else if (o instanceof LayerList[]) { LayerList[] lists = (LayerList[]) o; - if (lists != null && lists.length > 0) + if (lists != null && lists.length > 0) { layerLists.addAll(Arrays.asList(lists)); - } - else - { + } + } else { String msg = Logging.getMessage("LayerFactory.UnexpectedTypeForLayer", o.getClass().getName()); Logging.logger().log(java.util.logging.Level.WARNING, msg); } @@ -188,19 +180,16 @@ else if (o instanceof LayerList[]) String title = WWXML.getText(element, "@title"); Element[] children = WWXML.getElements(element, "./Layer", null); - if (children != null && children.length > 0) - { + if (children != null && children.length > 0) { LayerList list = this.createLayerList(children, params); - if (list != null && list.size() > 0) - { + if (list != null && list.size() > 0) { layerLists.add(list); - if (title != null && title.length() > 0) + if (title != null && title.length() > 0) { list.setValue(AVKey.DISPLAY_NAME, title); + } } } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.WARNING, e.getMessage(), e); // keep going to create other layers } @@ -216,22 +205,17 @@ else if (o instanceof LayerList[]) * the exceptions are not included in the returned layer list. * * @param layerElements the XML elements describing the layers to create. - * @param params any parameters to apply when creating the layers. + * @param params any parameters to apply when creating the layers. * * @return a layer list containing the specified layers. */ - protected LayerList createLayerList(Element[] layerElements, AVList params) - { + protected LayerList createLayerList(Element[] layerElements, AVList params) { LayerList layerList = new LayerList(); - for (Element element : layerElements) - { - try - { + for (Element element : layerElements) { + try { layerList.add(this.createFromLayerDocument(element, params)); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.WARNING, e.getMessage(), e); // keep going to create other layers } @@ -244,19 +228,17 @@ protected LayerList createLayerList(Element[] layerElements, AVList params) * Create a layer described by an XML layer description. * * @param domElement the XML element describing the layer to create. - * @param params any parameters to apply when creating the layer. + * @param params any parameters to apply when creating the layer. * * @return a new layer * * @throws WWUnrecognizedException if the layer type or service type given in the describing element is - * unrecognized. + * unrecognized. * @see #createTiledImageLayer(org.w3c.dom.Element, gov.nasa.worldwind.avlist.AVList) */ - protected Layer createFromLayerDocument(Element domElement, AVList params) - { + protected Layer createFromLayerDocument(Element domElement, AVList params) { String className = WWXML.getText(domElement, "@className"); - if (className != null && className.length() > 0) - { + if (className != null && className.length() > 0) { Layer layer = (Layer) WorldWind.createComponent(className); String actuate = WWXML.getText(domElement, "@actuate"); layer.setEnabled(WWUtil.isEmpty(actuate) || actuate.equals("onLoad")); @@ -265,49 +247,40 @@ protected Layer createFromLayerDocument(Element domElement, AVList params) } AVList props = WWXML.copyProperties(domElement, null); - if (props != null) - { // Copy params and add any properties for this layer to the copy - if (params != null) + if (props != null) { // Copy params and add any properties for this layer to the copy + if (params != null) { props.setValues(params); + } params = props; } Layer layer; String href = WWXML.getText(domElement, "@href"); - if (href != null && href.length() > 0) - { + if (href != null && href.length() > 0) { Object o = this.createFromConfigSource(href, params); - if (o == null) + if (o == null) { return null; + } - if (!(o instanceof Layer)) - { + if (!(o instanceof Layer)) { String msg = Logging.getMessage("LayerFactory.UnexpectedTypeForLayer", o.getClass().getName()); throw new WWRuntimeException(msg); } layer = (Layer) o; - } - else - { + } else { String layerType = WWXML.getText(domElement, "@layerType"); - if (layerType != null && layerType.equals("TiledImageLayer")) - { + if (layerType != null && layerType.equals("TiledImageLayer")) { layer = this.createTiledImageLayer(domElement, params); - } - else if (layerType != null && layerType.equals("ShapefileLayer")) - { + } else if (layerType != null && layerType.equals("ShapefileLayer")) { layer = this.createShapefileLayer(domElement, params); - } - else - { + } else { String msg = Logging.getMessage("generic.UnrecognizedLayerType", layerType); throw new WWUnrecognizedException(msg); } } - if (layer != null) - { + if (layer != null) { String actuate = WWXML.getText(domElement, "@actuate"); layer.setEnabled(actuate != null && actuate.equals("onLoad")); WWXML.invokePropertySetters(layer, domElement); @@ -320,38 +293,28 @@ else if (layerType != null && layerType.equals("ShapefileLayer")) * Create a {@link TiledImageLayer} layer described by an XML layer description. * * @param domElement the XML element describing the layer to create. The element must inculde a service name - * identifying the type of service to use to retrieve layer data. Recognized service types are - * "Offline", "WWTileService" and "OGC:WMS". - * @param params any parameters to apply when creating the layer. + * identifying the type of service to use to retrieve layer data. Recognized service types are "Offline", + * "WWTileService" and "OGC:WMS". + * @param params any parameters to apply when creating the layer. * * @return a new layer * * @throws WWUnrecognizedException if the service type given in the describing element is unrecognized. */ - protected Layer createTiledImageLayer(Element domElement, AVList params) - { + protected Layer createTiledImageLayer(Element domElement, AVList params) { Layer layer; String serviceName = WWXML.getText(domElement, "Service/@serviceName"); - if ("Offline".equals(serviceName)) - { + if ("Offline".equals(serviceName)) { layer = new BasicTiledImageLayer(domElement, params); - } - else if ("WWTileService".equals(serviceName)) - { + } else if ("WWTileService".equals(serviceName)) { layer = new BasicTiledImageLayer(domElement, params); - } - else if (OGCConstants.WMS_SERVICE_NAME.equals(serviceName)) - { + } else if (OGCConstants.WMS_SERVICE_NAME.equals(serviceName)) { layer = new WMSTiledImageLayer(domElement, params); - } - else if (AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER.equals(serviceName)) - { + } else if (AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER.equals(serviceName)) { layer = new LocalRasterServerLayer(domElement, params); - } - else - { + } else { String msg = Logging.getMessage("generic.UnrecognizedServiceName", serviceName); throw new WWUnrecognizedException(msg); } @@ -370,14 +333,13 @@ else if (AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER.equals(serviceName)) * class associated with the configuration key "gov.nasa.worldwind.avkey.ShapefileLayerFactory". * * @param domElement the XML element describing the layer to create. The element must contain the shapefile - * location, and may contain elements specifying shapefile attribute mappings, shape attributes to - * assign to created shapes, and layer properties. - * @param params any parameters to apply when creating the layer. + * location, and may contain elements specifying shapefile attribute mappings, shape attributes to assign to created + * shapes, and layer properties. + * @param params any parameters to apply when creating the layer. * * @return a new layer */ - protected Layer createShapefileLayer(Element domElement, AVList params) - { + protected Layer createShapefileLayer(Element domElement, AVList params) { return (Layer) BasicFactory.create(AVKey.SHAPEFILE_LAYER_FACTORY, domElement, params); } } diff --git a/src/gov/nasa/worldwind/layers/BasicTiledImageLayer.java b/src/gov/nasa/worldwind/layers/BasicTiledImageLayer.java index 5dd11238e2..3e12d4595e 100644 --- a/src/gov/nasa/worldwind/layers/BasicTiledImageLayer.java +++ b/src/gov/nasa/worldwind/layers/BasicTiledImageLayer.java @@ -30,128 +30,138 @@ * @author tag * @version $Id: BasicTiledImageLayer.java 2684 2015-01-26 18:31:22Z tgaskins $ */ -public class BasicTiledImageLayer extends TiledImageLayer implements BulkRetrievable -{ +public class BasicTiledImageLayer extends TiledImageLayer implements BulkRetrievable { + protected final Object fileLock = new Object(); // Layer resource properties. protected static final int RESOURCE_ID_OGC_CAPABILITIES = 1; - public BasicTiledImageLayer(LevelSet levelSet) - { + public BasicTiledImageLayer(LevelSet levelSet) { super(levelSet); } - public BasicTiledImageLayer(AVList params) - { + public BasicTiledImageLayer(AVList params) { this(new LevelSet(params)); String s = params.getStringValue(AVKey.DISPLAY_NAME); - if (s != null) + if (s != null) { this.setName(s); + } String[] strings = (String[]) params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS); - if (strings != null && strings.length > 0) + if (strings != null && strings.length > 0) { this.setAvailableImageFormats(strings); + } s = params.getStringValue(AVKey.TEXTURE_FORMAT); - if (s != null) + if (s != null) { this.setTextureFormat(s); + } Double d = (Double) params.getValue(AVKey.OPACITY); - if (d != null) + if (d != null) { this.setOpacity(d); + } d = (Double) params.getValue(AVKey.MAX_ACTIVE_ALTITUDE); - if (d != null) + if (d != null) { this.setMaxActiveAltitude(d); + } d = (Double) params.getValue(AVKey.MIN_ACTIVE_ALTITUDE); - if (d != null) + if (d != null) { this.setMinActiveAltitude(d); + } d = (Double) params.getValue(AVKey.MAP_SCALE); - if (d != null) + if (d != null) { this.setValue(AVKey.MAP_SCALE, d); + } d = (Double) params.getValue(AVKey.DETAIL_HINT); - if (d != null) + if (d != null) { this.setDetailHint(d); + } Boolean b = (Boolean) params.getValue(AVKey.FORCE_LEVEL_ZERO_LOADS); - if (b != null) + if (b != null) { this.setForceLevelZeroLoads(b); + } b = (Boolean) params.getValue(AVKey.RETAIN_LEVEL_ZERO_TILES); - if (b != null) + if (b != null) { this.setRetainLevelZeroTiles(b); + } b = (Boolean) params.getValue(AVKey.NETWORK_RETRIEVAL_ENABLED); - if (b != null) + if (b != null) { this.setNetworkRetrievalEnabled(b); + } b = (Boolean) params.getValue(AVKey.USE_MIP_MAPS); - if (b != null) + if (b != null) { this.setUseMipMaps(b); + } b = (Boolean) params.getValue(AVKey.USE_TRANSPARENT_TEXTURES); - if (b != null) + if (b != null) { this.setUseTransparentTextures(b); + } Object o = params.getValue(AVKey.URL_CONNECT_TIMEOUT); - if (o != null) + if (o != null) { this.setValue(AVKey.URL_CONNECT_TIMEOUT, o); + } o = params.getValue(AVKey.URL_READ_TIMEOUT); - if (o != null) + if (o != null) { this.setValue(AVKey.URL_READ_TIMEOUT, o); + } o = params.getValue(AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT); - if (o != null) + if (o != null) { this.setValue(AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT, o); + } ScreenCredit sc = (ScreenCredit) params.getValue(AVKey.SCREEN_CREDIT); - if (sc != null) + if (sc != null) { this.setScreenCredit(sc); + } - if (params.getValue(AVKey.TRANSPARENCY_COLORS) != null) + if (params.getValue(AVKey.TRANSPARENCY_COLORS) != null) { this.setValue(AVKey.TRANSPARENCY_COLORS, params.getValue(AVKey.TRANSPARENCY_COLORS)); + } b = (Boolean) params.getValue(AVKey.DELETE_CACHE_ON_EXIT); - if (b != null) + if (b != null) { this.setValue(AVKey.DELETE_CACHE_ON_EXIT, true); + } this.setValue(AVKey.CONSTRUCTION_PARAMETERS, params.copy()); // If any resources should be retrieved for this Layer, start a task to retrieve those resources, and initialize // this Layer once those resources are retrieved. - if (this.isRetrieveResources()) - { + if (this.isRetrieveResources()) { this.startResourceRetrieval(); } } - public BasicTiledImageLayer(Document dom, AVList params) - { + public BasicTiledImageLayer(Document dom, AVList params) { this(dom.getDocumentElement(), params); } - public BasicTiledImageLayer(Element domElement, AVList params) - { + public BasicTiledImageLayer(Element domElement, AVList params) { this(getParamsFromDocument(domElement, params)); } - public BasicTiledImageLayer(String restorableStateInXml) - { + public BasicTiledImageLayer(String restorableStateInXml) { this(restorableStateToParams(restorableStateInXml)); RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(restorableStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", restorableStateInXml); Logging.logger().severe(message); @@ -161,17 +171,16 @@ public BasicTiledImageLayer(String restorableStateInXml) this.doRestoreState(rs, null); } - protected static AVList getParamsFromDocument(Element domElement, AVList params) - { - if (domElement == null) - { + protected static AVList getParamsFromDocument(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } getTiledImageLayerConfigParams(domElement, params); setFallbacks(params); @@ -179,83 +188,76 @@ protected static AVList getParamsFromDocument(Element domElement, AVList params) return params; } - protected static void setFallbacks(AVList params) - { - if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) - { + protected static void setFallbacks(AVList params) { + if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) { Angle delta = Angle.fromDegrees(36); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, new LatLon(delta, delta)); } - if (params.getValue(AVKey.TILE_WIDTH) == null) + if (params.getValue(AVKey.TILE_WIDTH) == null) { params.setValue(AVKey.TILE_WIDTH, 512); + } - if (params.getValue(AVKey.TILE_HEIGHT) == null) + if (params.getValue(AVKey.TILE_HEIGHT) == null) { params.setValue(AVKey.TILE_HEIGHT, 512); + } - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { params.setValue(AVKey.FORMAT_SUFFIX, ".dds"); + } - if (params.getValue(AVKey.NUM_LEVELS) == null) + if (params.getValue(AVKey.NUM_LEVELS) == null) { params.setValue(AVKey.NUM_LEVELS, 19); // approximately 0.1 meters per pixel - - if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) + } + if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); + } } - protected void forceTextureLoad(TextureTile tile) - { + protected void forceTextureLoad(TextureTile tile) { final URL textureURL = this.getDataFileStore().findFile(tile.getPath(), true); - if (textureURL != null && !this.isTextureFileExpired(tile, textureURL, this.getDataFileStore())) - { + if (textureURL != null && !this.isTextureFileExpired(tile, textureURL, this.getDataFileStore())) { this.loadTexture(tile, textureURL); } } - protected void requestTexture(DrawContext dc, TextureTile tile) - { + protected void requestTexture(DrawContext dc, TextureTile tile) { Vec4 centroid = tile.getCentroidPoint(dc.getGlobe()); Vec4 referencePoint = this.getReferencePoint(dc); - if (referencePoint != null) + if (referencePoint != null) { tile.setPriority(centroid.distanceTo3(referencePoint)); + } RequestTask task = this.createRequestTask(tile); this.getRequestQ().add(task); } - protected RequestTask createRequestTask(TextureTile tile) - { + protected RequestTask createRequestTask(TextureTile tile) { return new RequestTask(tile, this); } - protected static class RequestTask implements Runnable, Comparable - { + protected static class RequestTask implements Runnable, Comparable { + protected final BasicTiledImageLayer layer; protected final TextureTile tile; - protected RequestTask(TextureTile tile, BasicTiledImageLayer layer) - { + protected RequestTask(TextureTile tile, BasicTiledImageLayer layer) { this.layer = layer; this.tile = tile; } - public void run() - { - if (Thread.currentThread().isInterrupted()) + public void run() { + if (Thread.currentThread().isInterrupted()) { return; // the task was cancelled because it's a duplicate or for some other reason - + } final java.net.URL textureURL = this.layer.getDataFileStore().findFile(tile.getPath(), false); - if (textureURL != null && !this.layer.isTextureFileExpired(tile, textureURL, this.layer.getDataFileStore())) - { - if (this.layer.loadTexture(tile, textureURL)) - { + if (textureURL != null && !this.layer.isTextureFileExpired(tile, textureURL, this.layer.getDataFileStore())) { + if (this.layer.loadTexture(tile, textureURL)) { layer.getLevels().unmarkResourceAbsent(this.tile); this.layer.firePropertyChange(AVKey.LAYER, null, this); return; - } - else - { + } else { // Assume that something is wrong with the file and delete it. this.layer.getDataFileStore().removeFile(textureURL); String message = Logging.getMessage("generic.DeletedCorruptDataFile", textureURL); @@ -273,24 +275,23 @@ public void run() * * @throws IllegalArgumentException if that is null */ - public int compareTo(RequestTask that) - { - if (that == null) - { + public int compareTo(RequestTask that) { + if (that == null) { String msg = Logging.getMessage("nullValue.RequestTaskIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - return this.tile.getPriority() == that.tile.getPriority() ? 0 : - this.tile.getPriority() < that.tile.getPriority() ? -1 : 1; + return this.tile.getPriority() == that.tile.getPriority() ? 0 + : this.tile.getPriority() < that.tile.getPriority() ? -1 : 1; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final RequestTask that = (RequestTask) o; @@ -298,21 +299,19 @@ public boolean equals(Object o) return !(tile != null ? !tile.equals(that.tile) : that.tile != null); } - public int hashCode() - { + public int hashCode() { return (tile != null ? tile.hashCode() : 0); } - public String toString() - { + public String toString() { return this.tile.toString(); } } - protected boolean isTextureFileExpired(TextureTile tile, java.net.URL textureURL, FileStore fileStore) - { - if (!WWIO.isFileOutOfDate(textureURL, tile.getLevel().getExpiryTime())) + protected boolean isTextureFileExpired(TextureTile tile, java.net.URL textureURL, FileStore fileStore) { + if (!WWIO.isFileOutOfDate(textureURL, tile.getLevel().getExpiryTime())) { return false; + } // The file has expired. Delete it. fileStore.removeFile(textureURL); @@ -321,21 +320,21 @@ protected boolean isTextureFileExpired(TextureTile tile, java.net.URL textureURL return true; } - protected boolean loadTexture(TextureTile tile, java.net.URL textureURL) - { + protected boolean loadTexture(TextureTile tile, java.net.URL textureURL) { TextureData textureData; - synchronized (this.fileLock) - { + synchronized (this.fileLock) { textureData = readTexture(textureURL, this.getTextureFormat(), this.isUseMipMaps()); } - if (textureData == null) + if (textureData == null) { return false; + } tile.setTextureData(textureData); - if (tile.getLevelNumber() != 0 || !this.isRetainLevelZeroTiles()) + if (tile.getLevelNumber() != 0 || !this.isRetainLevelZeroTiles()) { this.addTileToCache(tile); + } return true; } @@ -350,21 +349,18 @@ protected boolean loadTexture(TextureTile tile, java.net.URL textureURL) * Supported texture formats are as follows:
        • image/dds - Returns DDS texture data, converting * the data to DDS if necessary. If the data is already in DDS format it's returned as-is.
        * - * @param url the URL referencing the texture data to read. + * @param url the URL referencing the texture data to read. * @param textureFormat the texture data format to return. - * @param useMipMaps true to generate mip-maps for the texture data or use mip maps already in the texture data, - * and false to read the texture data without generating or using mip-maps. + * @param useMipMaps true to generate mip-maps for the texture data or use mip maps already in the texture data, and + * false to read the texture data without generating or using mip-maps. * * @return TextureData the texture data from the specified URL, in the specified format and with mip-maps. */ - protected TextureData readTexture(java.net.URL url, String textureFormat, boolean useMipMaps) - { - try - { + protected TextureData readTexture(java.net.URL url, String textureFormat, boolean useMipMaps) { + try { // If the caller has enabled texture compression, and the texture data is not a DDS file, then use read the // texture data and convert it to DDS. - if ("image/dds".equalsIgnoreCase(textureFormat) && !url.toString().toLowerCase().endsWith("dds")) - { + if ("image/dds".equalsIgnoreCase(textureFormat) && !url.toString().toLowerCase().endsWith("dds")) { // Configure a DDS compressor to generate mipmaps based according to the 'useMipMaps' parameter, and // convert the image URL to a compressed DDS format. DXTCompressionAttributes attributes = DDSCompressor.getDefaultCompressionAttributes(); @@ -372,32 +368,26 @@ protected TextureData readTexture(java.net.URL url, String textureFormat, boolea ByteBuffer buffer = DDSCompressor.compressImageURL(url, attributes); return OGLUtil.newTextureData(Configuration.getMaxCompatibleGLProfile(), - WWIO.getInputStreamFromByteBuffer(buffer), useMipMaps); - } - // If the caller has disabled texture compression, or if the texture data is already a DDS file, then read + WWIO.getInputStreamFromByteBuffer(buffer), useMipMaps); + } // If the caller has disabled texture compression, or if the texture data is already a DDS file, then read // the texture data without converting it. - else - { + else { return OGLUtil.newTextureData(Configuration.getMaxCompatibleGLProfile(), url, useMipMaps); } - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("layers.TextureLayer.ExceptionAttemptingToReadTextureFile", url); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); return null; } } - protected void addTileToCache(TextureTile tile) - { + protected void addTileToCache(TextureTile tile) { TextureTile.getMemoryCache().add(tile.getTileKey(), tile); } // *** Bulk download *** // *** Bulk download *** // *** Bulk download *** - /** * Start a new {@link BulkRetrievalThread} that downloads all imagery for a given sector and resolution to the * current WorldWind file cache, without downloading imagery that is already in the cache. @@ -408,9 +398,9 @@ protected void addTileToCache(TextureTile tile) * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to download imagery for. + * @param sector the sector to download imagery for. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param listener an optional retrieval listener. May be null. + * @param listener an optional retrieval listener. May be null. * * @return the {@link BulkRetrievalThread} executing the retrieval or null if the specified sector does * not intersect the layer bounding sector. @@ -418,8 +408,7 @@ protected void addTileToCache(TextureTile tile) * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. * @see BasicTiledImageLayerBulkDownloader */ - public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetrievalListener listener) - { + public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetrievalListener listener) { return makeLocal(sector, resolution, null, listener); } @@ -433,11 +422,11 @@ public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetri * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to download data for. + * @param sector the sector to download data for. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param fileStore the file store in which to place the downloaded imagery. If null the current WorldWind file - * cache is used. - * @param listener an optional retrieval listener. May be null. + * @param fileStore the file store in which to place the downloaded imagery. If null the current WorldWind file + * cache is used. + * @param listener an optional retrieval listener. May be null. * * @return the {@link BulkRetrievalThread} executing the retrieval or null if the specified sector does * not intersect the layer bounding sector. @@ -446,14 +435,14 @@ public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetri * @see BasicTiledImageLayerBulkDownloader */ public BulkRetrievalThread makeLocal(Sector sector, double resolution, FileStore fileStore, - BulkRetrievalListener listener) - { + BulkRetrievalListener listener) { Sector targetSector = sector != null ? getLevels().getSector().intersection(sector) : null; - if (targetSector == null) + if (targetSector == null) { return null; + } BasicTiledImageLayerBulkDownloader thread = new BasicTiledImageLayerBulkDownloader(this, targetSector, - resolution, fileStore != null ? fileStore : this.getDataFileStore(), listener); + resolution, fileStore != null ? fileStore : this.getDataFileStore(), listener); thread.setDaemon(true); thread.start(); return thread; @@ -466,15 +455,14 @@ public BulkRetrievalThread makeLocal(Sector sector, double resolution, FileStore * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to estimate. + * @param sector the sector to estimate. * @param resolution the target resolution, provided in radians of latitude per texel. * * @return the estimated size in bytes of the missing imagery. * * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. */ - public long getEstimatedMissingDataSize(Sector sector, double resolution) - { + public long getEstimatedMissingDataSize(Sector sector, double resolution) { return this.getEstimatedMissingDataSize(sector, resolution, null); } @@ -485,22 +473,22 @@ public long getEstimatedMissingDataSize(Sector sector, double resolution) * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to estimate. + * @param sector the sector to estimate. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param fileStore the file store to examine. If null the current WorldWind file cache is used. + * @param fileStore the file store to examine. If null the current WorldWind file cache is used. * * @return the estimated size in byte of the missing imagery. * * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. */ - public long getEstimatedMissingDataSize(Sector sector, double resolution, FileStore fileStore) - { + public long getEstimatedMissingDataSize(Sector sector, double resolution, FileStore fileStore) { Sector targetSector = sector != null ? getLevels().getSector().intersection(sector) : null; - if (targetSector == null) + if (targetSector == null) { return 0; + } BasicTiledImageLayerBulkDownloader downloader = new BasicTiledImageLayerBulkDownloader(this, sector, resolution, - fileStore != null ? fileStore : this.getDataFileStore(), null); + fileStore != null ? fileStore : this.getDataFileStore(), null); return downloader.getEstimatedMissingDataSize(); } @@ -508,24 +496,24 @@ public long getEstimatedMissingDataSize(Sector sector, double resolution, FileSt // *** Tile download *** // *** Tile download *** // *** Tile download *** - - protected void retrieveTexture(TextureTile tile, DownloadPostProcessor postProcessor) - { - if (this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL) != null) + protected void retrieveTexture(TextureTile tile, DownloadPostProcessor postProcessor) { + if (this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL) != null) { this.retrieveLocalTexture(tile, postProcessor); - else - // Assume it's remote, which handles the legacy cases. + } else // Assume it's remote, which handles the legacy cases. + { this.retrieveRemoteTexture(tile, postProcessor); + } } - protected void retrieveLocalTexture(TextureTile tile, DownloadPostProcessor postProcessor) - { - if (!WorldWind.getLocalRetrievalService().isAvailable()) + protected void retrieveLocalTexture(TextureTile tile, DownloadPostProcessor postProcessor) { + if (!WorldWind.getLocalRetrievalService().isAvailable()) { return; + } RetrieverFactory retrieverFactory = (RetrieverFactory) this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL); - if (retrieverFactory == null) + if (retrieverFactory == null) { return; + } AVListImpl avList = new AVListImpl(); avList.setValue(AVKey.SECTOR, tile.getSector()); @@ -538,82 +526,78 @@ protected void retrieveLocalTexture(TextureTile tile, DownloadPostProcessor post WorldWind.getLocalRetrievalService().runRetriever(retriever, tile.getPriority()); } - protected void retrieveRemoteTexture(TextureTile tile, DownloadPostProcessor postProcessor) - { - if (!this.isNetworkRetrievalEnabled()) - { + protected void retrieveRemoteTexture(TextureTile tile, DownloadPostProcessor postProcessor) { + if (!this.isNetworkRetrievalEnabled()) { this.getLevels().markResourceAbsent(tile); return; } - if (!WorldWind.getRetrievalService().isAvailable()) + if (!WorldWind.getRetrievalService().isAvailable()) { return; + } java.net.URL url; - try - { + try { url = tile.getResourceURL(); - if (url == null) + if (url == null) { return; + } - if (WorldWind.getNetworkStatus().isHostUnavailable(url)) - { + if (WorldWind.getNetworkStatus().isHostUnavailable(url)) { this.getLevels().markResourceAbsent(tile); return; } - } - catch (java.net.MalformedURLException e) - { + } catch (java.net.MalformedURLException e) { Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("layers.TextureLayer.ExceptionCreatingTextureUrl", tile), e); + Logging.getMessage("layers.TextureLayer.ExceptionCreatingTextureUrl", tile), e); return; } Retriever retriever; - if (postProcessor == null) + if (postProcessor == null) { postProcessor = this.createDownloadPostProcessor(tile); + } retriever = URLRetriever.createRetriever(url, postProcessor); - if (retriever == null) - { + if (retriever == null) { Logging.logger().severe( - Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", url.toString())); + Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", url.toString())); return; } retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers // Apply any overridden timeouts. Integer cto = AVListImpl.getIntegerValue(this, AVKey.URL_CONNECT_TIMEOUT); - if (cto != null && cto > 0) + if (cto != null && cto > 0) { retriever.setConnectTimeout(cto); + } Integer cro = AVListImpl.getIntegerValue(this, AVKey.URL_READ_TIMEOUT); - if (cro != null && cro > 0) + if (cro != null && cro > 0) { retriever.setReadTimeout(cro); + } Integer srl = AVListImpl.getIntegerValue(this, AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT); - if (srl != null && srl > 0) + if (srl != null && srl > 0) { retriever.setStaleRequestLimit(srl); + } WorldWind.getRetrievalService().runRetriever(retriever, tile.getPriority()); } - protected DownloadPostProcessor createDownloadPostProcessor(TextureTile tile) - { + protected DownloadPostProcessor createDownloadPostProcessor(TextureTile tile) { return new DownloadPostProcessor(tile, this); } - protected static class DownloadPostProcessor extends AbstractRetrievalPostProcessor - { + protected static class DownloadPostProcessor extends AbstractRetrievalPostProcessor { + protected final TextureTile tile; protected final BasicTiledImageLayer layer; protected final FileStore fileStore; - public DownloadPostProcessor(TextureTile tile, BasicTiledImageLayer layer) - { + public DownloadPostProcessor(TextureTile tile, BasicTiledImageLayer layer) { this(tile, layer, null); } - public DownloadPostProcessor(TextureTile tile, BasicTiledImageLayer layer, FileStore fileStore) - { + public DownloadPostProcessor(TextureTile tile, BasicTiledImageLayer layer, FileStore fileStore) { //noinspection RedundantCast super((AVList) layer); @@ -622,36 +606,30 @@ public DownloadPostProcessor(TextureTile tile, BasicTiledImageLayer layer, FileS this.fileStore = fileStore; } - protected FileStore getFileStore() - { + protected FileStore getFileStore() { return this.fileStore != null ? this.fileStore : this.layer.getDataFileStore(); } @Override - protected void markResourceAbsent() - { + protected void markResourceAbsent() { this.layer.getLevels().markResourceAbsent(this.tile); } @Override - protected Object getFileLock() - { + protected Object getFileLock() { return this.layer.fileLock; } @Override - protected File doGetOutputFile() - { + protected File doGetOutputFile() { return this.getFileStore().newFile(this.tile.getPath()); } @Override - protected ByteBuffer handleSuccessfulRetrieval() - { + protected ByteBuffer handleSuccessfulRetrieval() { ByteBuffer buffer = super.handleSuccessfulRetrieval(); - if (buffer != null) - { + if (buffer != null) { // We've successfully cached data. Check if there's a configuration file for this layer, create one // if there's not. this.layer.writeConfigurationFile(this.getFileStore()); @@ -664,8 +642,7 @@ protected ByteBuffer handleSuccessfulRetrieval() } @Override - protected ByteBuffer handleTextContent() throws IOException - { + protected ByteBuffer handleTextContent() throws IOException { this.markResourceAbsent(); return super.handleTextContent(); @@ -675,7 +652,6 @@ protected ByteBuffer handleTextContent() throws IOException //**************************************************************// //******************** Non-Tile Resource Retrieval ***********// //**************************************************************// - /** * Retrieves any non-tile resources associated with this Layer, either online or in the local filesystem, and * initializes properties of this Layer using those resources. This returns a key indicating the retrieval state: @@ -688,13 +664,11 @@ protected ByteBuffer handleTextContent() throws IOException * gov.nasa.worldwind.avlist.AVKey#RETRIEVAL_STATE_ERROR} if the retrieval failed with errors, and null * if the retrieval state is unknown. */ - protected String retrieveResources() - { + protected String retrieveResources() { // This Layer has no construction parameters, so there is no description of what to retrieve. Return a key // indicating the resources have been successfully retrieved, though there is nothing to retrieve. AVList params = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ConstructionParametersIsNull"); Logging.logger().warning(message); return AVKey.RETRIEVAL_STATE_SUCCESSFUL; @@ -703,8 +677,7 @@ protected String retrieveResources() // This Layer has no OGC Capabilities URL in its construction parameters. Return a key indicating the resources // have been successfully retrieved, though there is nothing to retrieve. URL url = DataConfigurationUtils.getOGCGetCapabilitiesURL(params); - if (url == null) - { + if (url == null) { String message = Logging.getMessage("nullValue.CapabilitiesURLIsNull"); Logging.logger().warning(message); return AVKey.RETRIEVAL_STATE_SUCCESSFUL; @@ -719,18 +692,20 @@ protected String retrieveResources() // of hashCode() and equals() perform blocking IO calls. WorldWind does not perform blocking calls during // rendering, and this method is likely to be called from the rendering thread. WMSCapabilities caps; - if (this.isNetworkRetrievalEnabled()) + if (this.isNetworkRetrievalEnabled()) { caps = SessionCacheUtils.getOrRetrieveSessionCapabilities(url, WorldWind.getSessionCache(), - url.toString(), null, RESOURCE_ID_OGC_CAPABILITIES, null, null); - else + url.toString(), null, RESOURCE_ID_OGC_CAPABILITIES, null, null); + } else { caps = SessionCacheUtils.getSessionCapabilities(WorldWind.getSessionCache(), url.toString(), - url.toString()); + url.toString()); + } // The OGC Capabilities resource retrieval is either currently running in another thread, or has failed. In // either case, return null indicating that that the retrieval was not successful, and we should try again // later. - if (caps == null) + if (caps == null) { return null; + } // We have successfully retrieved this Layer's OGC Capabilities resource. Initialize this Layer using the // Capabilities document, and return a key indicating the retrieval has succeeded. @@ -744,40 +719,37 @@ protected String retrieveResources() * describing the WMS layer names associated with this Layer. This method is thread safe; it synchronizes changes to * this Layer by wrapping the appropriate method calls in {@link SwingUtilities#invokeLater(Runnable)}. * - * @param caps the WMS Capabilities document retrieved from this Layer's WMS server. + * @param caps the WMS Capabilities document retrieved from this Layer's WMS server. * @param params the parameter list describing the WMS layer names associated with this Layer. * * @throws IllegalArgumentException if either the Capabilities or the parameter list is null. */ - protected void initFromOGCCapabilitiesResource(WMSCapabilities caps, AVList params) - { - if (caps == null) - { + protected void initFromOGCCapabilitiesResource(WMSCapabilities caps, AVList params) { + if (caps == null) { String message = Logging.getMessage("nullValue.CapabilitiesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String[] names = DataConfigurationUtils.getOGCLayerNames(params); - if (names == null || names.length == 0) + if (names == null || names.length == 0) { return; + } final Long expiryTime = caps.getLayerLatestLastUpdateTime(names); - if (expiryTime == null) + if (expiryTime == null) { return; + } // Synchronize changes to this Layer with the Event Dispatch Thread. - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + SwingUtilities.invokeLater(new Runnable() { + public void run() { BasicTiledImageLayer.this.setExpiryTime(expiryTime); BasicTiledImageLayer.this.firePropertyChange(AVKey.LAYER, null, BasicTiledImageLayer.this); } @@ -790,24 +762,23 @@ public void run() * * @return true if this Layer should retrieve any non-tile resources, and false otherwise. */ - protected boolean isRetrieveResources() - { + protected boolean isRetrieveResources() { AVList params = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (params == null) + if (params == null) { return false; + } Boolean b = (Boolean) params.getValue(AVKey.RETRIEVE_PROPERTIES_FROM_SERVICE); return b != null && b; } - /** Starts retrieving non-tile resources associated with this Layer in a non-rendering thread. */ - protected void startResourceRetrieval() - { - Thread t = new Thread(new Runnable() - { + /** + * Starts retrieving non-tile resources associated with this Layer in a non-rendering thread. + */ + protected void startResourceRetrieval() { + Thread t = new Thread(new Runnable() { @Override - public void run() - { + public void run() { retrieveResources(); } }); @@ -818,30 +789,23 @@ public void run() //**************************************************************// //******************** Configuration *************************// //**************************************************************// - - protected void writeConfigurationFile(FileStore fileStore) - { + protected void writeConfigurationFile(FileStore fileStore) { // TODO: configurable max attempts for creating a configuration file. - try - { + try { AVList configParams = this.getConfigurationParams(null); this.writeConfigurationParams(fileStore, configParams); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionAttemptingToWriteConfigurationFile"); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - protected void writeConfigurationParams(FileStore fileStore, AVList params) - { + protected void writeConfigurationParams(FileStore fileStore, AVList params) { // Determine what the configuration file name should be based on the configuration parameters. Assume an XML // configuration document type, and append the XML file suffix. String fileName = DataConfigurationUtils.getDataConfigFilename(params, ".xml"); - if (fileName == null) - { + if (fileName == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -851,26 +815,25 @@ protected void writeConfigurationParams(FileStore fileStore, AVList params) // to improve multithreaded performance for the common case: the configuration file already exists, this just // need to check that it's there and return. If the file exists but is expired, do not remove it - this // removes the file inside the synchronized block below. - if (!this.needsConfigurationFile(fileStore, fileName, params, false)) + if (!this.needsConfigurationFile(fileStore, fileName, params, false)) { return; + } - synchronized (this.fileLock) - { + synchronized (this.fileLock) { // Check again if the component needs to write a configuration file, potentially removing any existing file // which has expired. This additional check is necessary because the file could have been created by // another thread while we were waiting for the lock. - if (!this.needsConfigurationFile(fileStore, fileName, params, true)) + if (!this.needsConfigurationFile(fileStore, fileName, params, true)) { return; + } this.doWriteConfigurationParams(fileStore, fileName, params); } } - protected void doWriteConfigurationParams(FileStore fileStore, String fileName, AVList params) - { + protected void doWriteConfigurationParams(FileStore fileStore, String fileName, AVList params) { java.io.File file = fileStore.newFile(fileName); - if (file == null) - { + if (file == null) { String message = Logging.getMessage("generic.CannotCreateFile", fileName); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -884,24 +847,25 @@ protected void doWriteConfigurationParams(FileStore fileStore, String fileName, } protected boolean needsConfigurationFile(FileStore fileStore, String fileName, AVList params, - boolean removeIfExpired) - { + boolean removeIfExpired) { long expiryTime = this.getExpiryTime(); - if (expiryTime <= 0) + if (expiryTime <= 0) { expiryTime = AVListImpl.getLongValue(params, AVKey.EXPIRY_TIME, 0L); + } return !DataConfigurationUtils.hasDataConfigFile(fileStore, fileName, removeIfExpired, expiryTime); } - protected AVList getConfigurationParams(AVList params) - { - if (params == null) + protected AVList getConfigurationParams(AVList params) { + if (params == null) { params = new AVListImpl(); + } // Gather all the construction parameters if they are available. AVList constructionParams = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (constructionParams != null) + if (constructionParams != null) { params.setValues(constructionParams); + } // Gather any missing LevelSet parameters from the LevelSet itself. DataConfigurationUtils.getLevelSetConfigParams(this.getLevels(), params); @@ -909,45 +873,40 @@ protected AVList getConfigurationParams(AVList params) return params; } - protected Document createConfigurationDocument(AVList params) - { + protected Document createConfigurationDocument(AVList params) { return createTiledImageLayerConfigDocument(params); } //**************************************************************// //******************** Restorable Support ********************// //**************************************************************// - - public String getRestorableState() - { + public String getRestorableState() { // We only create a restorable state XML if this elevation model was constructed with an AVList. AVList constructionParams = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (constructionParams == null) + if (constructionParams == null) { return null; + } RestorableSupport rs = RestorableSupport.newRestorableSupport(); // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (rs == null) + if (rs == null) { return null; + } this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - public void restoreState(String stateInXml) - { + public void restoreState(String stateInXml) { String message = Logging.getMessage("RestorableSupport.RestoreRequiresConstructor"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { AVList constructionParams = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (constructionParams != null) - { - for (Map.Entry avp : constructionParams.getEntries()) - { + if (constructionParams != null) { + for (Map.Entry avp : constructionParams.getEntries()) { this.getRestorableStateForAVPair(avp.getKey(), avp.getValue(), rs, context); } } @@ -962,119 +921,112 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsBoolean(context, "TiledImageLayer.UseTransparentTextures", this.isUseTransparentTextures()); RestorableSupport.StateObject so = rs.addStateObject(context, "avlist"); - for (Map.Entry avp : this.getEntries()) - { + for (Map.Entry avp : this.getEntries()) { this.getRestorableStateForAVPair(avp.getKey(), avp.getValue(), rs, so); } } public void getRestorableStateForAVPair(String key, Object value, - RestorableSupport rs, RestorableSupport.StateObject context) - { - if (value == null) + RestorableSupport rs, RestorableSupport.StateObject context) { + if (value == null) { return; + } - if (key.equals(AVKey.CONSTRUCTION_PARAMETERS)) + if (key.equals(AVKey.CONSTRUCTION_PARAMETERS)) { return; + } - if (key.equals(AVKey.FRAME_TIMESTAMP)) + if (key.equals(AVKey.FRAME_TIMESTAMP)) { return; // frame timestamp is a runtime property and must not be saved/restored - - if (value instanceof LatLon) - { - rs.addStateValueAsLatLon(context, key, (LatLon) value); } - else if (value instanceof Sector) - { + if (value instanceof LatLon) { + rs.addStateValueAsLatLon(context, key, (LatLon) value); + } else if (value instanceof Sector) { rs.addStateValueAsSector(context, key, (Sector) value); - } - else if (value instanceof Color) - { + } else if (value instanceof Color) { rs.addStateValueAsColor(context, key, (Color) value); - } - else - { + } else { super.getRestorableStateForAVPair(key, value, rs, context); } } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { Boolean b = rs.getStateValueAsBoolean(context, "Layer.Enabled"); - if (b != null) + if (b != null) { this.setEnabled(b); + } Double d = rs.getStateValueAsDouble(context, "Layer.Opacity"); - if (d != null) + if (d != null) { this.setOpacity(d); + } d = rs.getStateValueAsDouble(context, "Layer.MinActiveAltitude"); - if (d != null) + if (d != null) { this.setMinActiveAltitude(d); + } d = rs.getStateValueAsDouble(context, "Layer.MaxActiveAltitude"); - if (d != null) + if (d != null) { this.setMaxActiveAltitude(d); + } b = rs.getStateValueAsBoolean(context, "Layer.NetworkRetrievalEnabled"); - if (b != null) + if (b != null) { this.setNetworkRetrievalEnabled(b); + } String s = rs.getStateValueAsString(context, "Layer.Name"); - if (s != null) + if (s != null) { this.setName(s); + } b = rs.getStateValueAsBoolean(context, "TiledImageLayer.UseMipMaps"); - if (b != null) + if (b != null) { this.setUseMipMaps(b); + } b = rs.getStateValueAsBoolean(context, "TiledImageLayer.UseTransparentTextures"); - if (b != null) + if (b != null) { this.setUseTransparentTextures(b); + } RestorableSupport.StateObject so = rs.getStateObject(context, "avlist"); - if (so != null) - { + if (so != null) { RestorableSupport.StateObject[] avpairs = rs.getAllStateObjects(so, ""); - if (avpairs != null) - { - for (RestorableSupport.StateObject avp : avpairs) - { - if (avp != null) + if (avpairs != null) { + for (RestorableSupport.StateObject avp : avpairs) { + if (avp != null) { this.doRestoreStateForObject(rs, avp); + } } } } } @SuppressWarnings({"UnusedDeclaration"}) - protected void doRestoreStateForObject(RestorableSupport rs, RestorableSupport.StateObject so) - { - if (so == null) + protected void doRestoreStateForObject(RestorableSupport rs, RestorableSupport.StateObject so) { + if (so == null) { return; + } - if (so.getName().equals(AVKey.FRAME_TIMESTAMP)) + if (so.getName().equals(AVKey.FRAME_TIMESTAMP)) { return; // frame timestamp is a runtime property and must not be saved/restored - + } this.setValue(so.getName(), so.getValue()); } - protected static AVList restorableStateToParams(String stateInXml) - { - if (stateInXml == null) - { + protected static AVList restorableStateToParams(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -1087,54 +1039,65 @@ protected static AVList restorableStateToParams(String stateInXml) } protected static void restoreStateForParams(RestorableSupport rs, RestorableSupport.StateObject context, - AVList params) - { + AVList params) { String s = rs.getStateValueAsString(context, AVKey.DATA_CACHE_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DATA_CACHE_NAME, s); + } s = rs.getStateValueAsString(context, AVKey.SERVICE); - if (s != null) + if (s != null) { params.setValue(AVKey.SERVICE, s); + } s = rs.getStateValueAsString(context, AVKey.DATASET_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DATASET_NAME, s); + } s = rs.getStateValueAsString(context, AVKey.FORMAT_SUFFIX); - if (s != null) + if (s != null) { params.setValue(AVKey.FORMAT_SUFFIX, s); + } Integer i = rs.getStateValueAsInteger(context, AVKey.NUM_EMPTY_LEVELS); - if (i != null) + if (i != null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, i); + } i = rs.getStateValueAsInteger(context, AVKey.NUM_LEVELS); - if (i != null) + if (i != null) { params.setValue(AVKey.NUM_LEVELS, i); + } i = rs.getStateValueAsInteger(context, AVKey.TILE_WIDTH); - if (i != null) + if (i != null) { params.setValue(AVKey.TILE_WIDTH, i); + } i = rs.getStateValueAsInteger(context, AVKey.TILE_HEIGHT); - if (i != null) + if (i != null) { params.setValue(AVKey.TILE_HEIGHT, i); + } Long lo = rs.getStateValueAsLong(context, AVKey.EXPIRY_TIME); - if (lo != null) + if (lo != null) { params.setValue(AVKey.EXPIRY_TIME, lo); + } LatLon ll = rs.getStateValueAsLatLon(context, AVKey.LEVEL_ZERO_TILE_DELTA); - if (ll != null) + if (ll != null) { params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, ll); + } ll = rs.getStateValueAsLatLon(context, AVKey.TILE_ORIGIN); - if (ll != null) + if (ll != null) { params.setValue(AVKey.TILE_ORIGIN, ll); + } Sector sector = rs.getStateValueAsSector(context, AVKey.SECTOR); - if (sector != null) + if (sector != null) { params.setValue(AVKey.SECTOR, sector); + } } } diff --git a/src/gov/nasa/worldwind/layers/BasicTiledImageLayerBulkDownloader.java b/src/gov/nasa/worldwind/layers/BasicTiledImageLayerBulkDownloader.java index c3a05dc135..c4c2b544d4 100644 --- a/src/gov/nasa/worldwind/layers/BasicTiledImageLayerBulkDownloader.java +++ b/src/gov/nasa/worldwind/layers/BasicTiledImageLayerBulkDownloader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers; import gov.nasa.worldwind.WorldWind; @@ -28,8 +27,8 @@ * @author tag * @version $Id: BasicTiledImageLayerBulkDownloader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicTiledImageLayerBulkDownloader extends BulkRetrievalThread -{ +public class BasicTiledImageLayerBulkDownloader extends BulkRetrievalThread { + protected final static int MAX_TILE_COUNT_PER_REGION = 200; protected final static long DEFAULT_AVERAGE_FILE_SIZE = 350000L; @@ -42,16 +41,15 @@ public class BasicTiledImageLayerBulkDownloader extends BulkRetrievalThread *

        * The thread returned is not started during construction, the caller must start the thread. * - * @param layer the layer for which to download imagery. - * @param sector the sector to download data for. This value is final. + * @param layer the layer for which to download imagery. + * @param sector the sector to download data for. This value is final. * @param resolution the target resolution, provided in radians of latitude per texel. This value is final. - * @param listener an optional retrieval listener. May be null. + * @param listener an optional retrieval listener. May be null. * * @throws IllegalArgumentException if either the layer or sector are null, or the resolution is less than zero. */ public BasicTiledImageLayerBulkDownloader(BasicTiledImageLayer layer, Sector sector, double resolution, - BulkRetrievalListener listener) - { + BulkRetrievalListener listener) { // Arguments checked in parent constructor super(layer, sector, resolution, layer.getDataFileStore(), listener); @@ -64,18 +62,17 @@ public BasicTiledImageLayerBulkDownloader(BasicTiledImageLayer layer, Sector sec *

        * The thread returned is not started during construction, the caller must start the thread. * - * @param layer the layer for which to download imagery. - * @param sector the sector to download data for. This value is final. + * @param layer the layer for which to download imagery. + * @param sector the sector to download data for. This value is final. * @param resolution the target resolution, provided in radians of latitude per texel. This value is final. - * @param fileStore the file store in which to place the downloaded elevations. - * @param listener an optional retrieval listener. May be null. + * @param fileStore the file store in which to place the downloaded elevations. + * @param listener an optional retrieval listener. May be null. * * @throws IllegalArgumentException if either the layer, the sector or file store are null, or the resolution is - * less than zero. + * less than zero. */ public BasicTiledImageLayerBulkDownloader(BasicTiledImageLayer layer, Sector sector, double resolution, - FileStore fileStore, BulkRetrievalListener listener) - { + FileStore fileStore, BulkRetrievalListener listener) { // Arguments checked in parent constructor super(layer, sector, resolution, fileStore, listener); @@ -83,50 +80,43 @@ public BasicTiledImageLayerBulkDownloader(BasicTiledImageLayer layer, Sector sec this.level = this.layer.computeLevelForResolution(sector, resolution); } - public void run() - { - try - { + public void run() { + try { // Init progress with missing tile count estimate this.progress.setTotalCount(this.estimateMissingTilesCount(20)); this.progress.setTotalSize(this.progress.getTotalCount() * estimateAverageTileSize()); // Determine and request missing tiles by level/region - for (int levelNumber = 0; levelNumber <= this.level; levelNumber++) - { - if (this.layer.getLevels().isLevelEmpty(levelNumber)) + for (int levelNumber = 0; levelNumber <= this.level; levelNumber++) { + if (this.layer.getLevels().isLevelEmpty(levelNumber)) { continue; + } int div = this.computeRegionDivisions(this.sector, levelNumber, MAX_TILE_COUNT_PER_REGION); Iterator regionsIterator = this.getRegionIterator(this.sector, div); - + Sector region; - while (regionsIterator.hasNext()) - { + while (regionsIterator.hasNext()) { region = regionsIterator.next(); // Determine missing tiles this.missingTiles = getMissingTilesInSector(region, levelNumber); // Submit missing tiles requests at intervals - while (this.missingTiles.size() > 0) - { + while (this.missingTiles.size() > 0) { submitMissingTilesRequests(); - if (this.missingTiles.size() > 0) + if (this.missingTiles.size() > 0) { Thread.sleep(RETRIEVAL_SERVICE_POLL_DELAY); + } } } } // Set progress to 100% this.progress.setTotalCount(this.progress.getCurrentCount()); this.progress.setTotalSize(this.progress.getCurrentSize()); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { String message = Logging.getMessage("generic.BulkRetrievalInterrupted", this.layer.getName()); Logging.logger().log(java.util.logging.Level.WARNING, message, e); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionDuringBulkRetrieval", this.layer.getName()); Logging.logger().severe(message); throw new RuntimeException(message); @@ -146,26 +136,21 @@ public void run() // // return count; // } - - protected synchronized void submitMissingTilesRequests() throws InterruptedException - { + protected synchronized void submitMissingTilesRequests() throws InterruptedException { RetrievalService rs = WorldWind.getRetrievalService(); int i = 0; - while (this.missingTiles.size() > i && rs.isAvailable()) - { + while (this.missingTiles.size() > i && rs.isAvailable()) { Thread.sleep(1); // generates InterruptedException if thread has been interrupted TextureTile tile = this.missingTiles.get(i); - if (this.layer.getLevels().isResourceAbsent(tile)) - { + if (this.layer.getLevels().isResourceAbsent(tile)) { removeAbsentTile(tile); // tile is absent, count it off. continue; } URL url = this.fileStore.findFile(tile.getPath(), false); - if (url != null) - { + if (url != null) { // tile has been retrieved and is local now, count it as retrieved. removeRetrievedTile(tile); continue; @@ -176,41 +161,38 @@ protected synchronized void submitMissingTilesRequests() throws InterruptedExcep } } - protected BasicTiledImageLayer.DownloadPostProcessor createBulkDownloadPostProcessor(TextureTile tile) - { + protected BasicTiledImageLayer.DownloadPostProcessor createBulkDownloadPostProcessor(TextureTile tile) { return new BulkDownloadPostProcessor(tile, this.layer, this.fileStore); } - protected class BulkDownloadPostProcessor extends BasicTiledImageLayer.DownloadPostProcessor - { - public BulkDownloadPostProcessor(TextureTile tile, BasicTiledImageLayer layer, FileStore fileStore) - { + protected class BulkDownloadPostProcessor extends BasicTiledImageLayer.DownloadPostProcessor { + + public BulkDownloadPostProcessor(TextureTile tile, BasicTiledImageLayer layer, FileStore fileStore) { super(tile, layer, fileStore); } - public ByteBuffer run(Retriever retriever) - { + public ByteBuffer run(Retriever retriever) { ByteBuffer buffer = super.run(retriever); - if (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) + if (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) { removeRetrievedTile(this.tile); + } - if (hasRetrievalListeners()) + if (hasRetrievalListeners()) { callRetrievalListeners(retriever, this.tile); + } return buffer; } } - protected void callRetrievalListeners(Retriever retriever, TextureTile tile) - { + protected void callRetrievalListeners(Retriever retriever, TextureTile tile) { String eventType = (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) - ? BulkRetrievalEvent.RETRIEVAL_SUCCEEDED : BulkRetrievalEvent.RETRIEVAL_FAILED; + ? BulkRetrievalEvent.RETRIEVAL_SUCCEEDED : BulkRetrievalEvent.RETRIEVAL_FAILED; super.callRetrievalListeners(new BulkRetrievalEvent(this.layer, eventType, tile.getPath())); } - protected synchronized void removeRetrievedTile(TextureTile tile) - { + protected synchronized void removeRetrievedTile(TextureTile tile) { this.missingTiles.remove(tile); // Update progress this.progress.setCurrentCount(this.progress.getCurrentCount() + 1); @@ -219,8 +201,7 @@ protected synchronized void removeRetrievedTile(TextureTile tile) this.normalizeProgress(); } - protected synchronized void removeAbsentTile(TextureTile tile) - { + protected synchronized void removeAbsentTile(TextureTile tile) { this.missingTiles.remove(tile); // Decrease progress expected total count and size this.progress.setTotalCount(this.progress.getTotalCount() - 1); @@ -229,10 +210,8 @@ protected synchronized void removeAbsentTile(TextureTile tile) this.normalizeProgress(); } - protected void normalizeProgress() - { - if (this.progress.getTotalCount() < this.progress.getCurrentCount()) - { + protected void normalizeProgress() { + if (this.progress.getTotalCount() < this.progress.getCurrentCount()) { this.progress.setTotalCount(this.progress.getCurrentCount()); this.progress.setTotalSize(this.progress.getCurrentSize()); } @@ -245,8 +224,7 @@ protected void normalizeProgress() * * @return the estimated size in byte of the missing imagery. */ - protected long getEstimatedMissingDataSize() - { + protected long getEstimatedMissingDataSize() { // Get missing tiles count estimate long totMissing = estimateMissingTilesCount(6); // Get average tile size estimate @@ -255,204 +233,180 @@ protected long getEstimatedMissingDataSize() return totMissing * averageTileSize; } - protected long estimateMissingTilesCount(int numSamples) - { + protected long estimateMissingTilesCount(int numSamples) { int maxLevel = this.layer.computeLevelForResolution(this.sector, this.resolution); // Total expected tiles long totCount = 0; - for (int levelNumber = 0; levelNumber <= maxLevel; levelNumber++) - { - if (!this.layer.getLevels().isLevelEmpty(levelNumber)) + for (int levelNumber = 0; levelNumber <= maxLevel; levelNumber++) { + if (!this.layer.getLevels().isLevelEmpty(levelNumber)) { totCount += this.layer.countImagesInSector(sector, levelNumber); + } } // Sample random small sized sectors at finest level int div = this.computeRegionDivisions(this.sector, maxLevel, 36); // max 6x6 tiles per region Sector[] regions = computeRandomRegions(this.sector, div, numSamples); long regionMissing = 0; long regionCount = 0; - try - { - if (regions.length < numSamples) - { + try { + if (regions.length < numSamples) { regionCount = this.layer.countImagesInSector(this.sector, maxLevel); regionMissing = getMissingTilesInSector(this.sector, maxLevel).size(); - } - else - { - for (Sector region : regions) - { + } else { + for (Sector region : regions) { // Count how many tiles are missing in each sample region regionCount += this.layer.countImagesInSector(region, maxLevel); regionMissing += getMissingTilesInSector(region, maxLevel).size(); } } - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { return 0; - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionDuringDataSizeEstimate", this.layer.getName()); Logging.logger().severe(message); throw new RuntimeException(message); } // Extrapolate total missing count - return (long)(totCount * ((double)regionMissing / regionCount)); + return (long) (totCount * ((double) regionMissing / regionCount)); } - protected int computeRegionDivisions(Sector sector, int levelNumber, int maxCount) - { + protected int computeRegionDivisions(Sector sector, int levelNumber, int maxCount) { long tileCount = this.layer.countImagesInSector(sector, levelNumber); - if (tileCount <= maxCount) + if (tileCount <= maxCount) { return 1; + } // Divide sector in regions that will contain no more tiles then maxCount return (int) Math.ceil(Math.sqrt((double) tileCount / maxCount)); } - protected Sector[] computeRandomRegions(Sector sector, int div, int numRegions) - { - if (numRegions > div * div) + protected Sector[] computeRandomRegions(Sector sector, int div, int numRegions) { + if (numRegions > div * div) { return sector.subdivide(div); + } final double dLat = sector.getDeltaLat().degrees / div; final double dLon = sector.getDeltaLon().degrees / div; ArrayList regions = new ArrayList(numRegions); Random rand = new Random(); - while (regions.size() < numRegions) - { + while (regions.size() < numRegions) { int row = rand.nextInt(div); int col = rand.nextInt(div); Sector s = Sector.fromDegrees( - sector.getMinLatitude().degrees + dLat * row, - sector.getMinLatitude().degrees + dLat * row + dLat, - sector.getMinLongitude().degrees + dLon * col, - sector.getMinLongitude().degrees + dLon * col + dLon); - if (!regions.contains(s)) + sector.getMinLatitude().degrees + dLat * row, + sector.getMinLatitude().degrees + dLat * row + dLat, + sector.getMinLongitude().degrees + dLon * col, + sector.getMinLongitude().degrees + dLon * col + dLon); + if (!regions.contains(s)) { regions.add(s); + } } return regions.toArray(new Sector[numRegions]); } - protected Iterator getRegionIterator(final Sector sector, final int div) - { + protected Iterator getRegionIterator(final Sector sector, final int div) { final double dLat = sector.getDeltaLat().degrees / div; final double dLon = sector.getDeltaLon().degrees / div; - return new Iterator() - { + return new Iterator() { int row = 0; int col = 0; - public boolean hasNext() - { + public boolean hasNext() { return row < div; } - public Sector next() - { + public Sector next() { Sector s = Sector.fromDegrees( - sector.getMinLatitude().degrees + dLat * row, - sector.getMinLatitude().degrees + dLat * row + dLat, - sector.getMinLongitude().degrees + dLon * col, - sector.getMinLongitude().degrees + dLon * col + dLon); + sector.getMinLatitude().degrees + dLat * row, + sector.getMinLatitude().degrees + dLat * row + dLat, + sector.getMinLongitude().degrees + dLon * col, + sector.getMinLongitude().degrees + dLon * col + dLon); col++; - if (col >= div) - { + if (col >= div) { col = 0; row++; } return s; } - public void remove() - { + public void remove() { } }; } protected ArrayList getMissingTilesInSector(Sector sector, int levelNumber) - throws InterruptedException - { + throws InterruptedException { ArrayList tiles = new ArrayList(); TextureTile[][] tileArray = this.layer.getTilesInSector(sector, levelNumber); - for (TextureTile[] row : tileArray) - { - for (TextureTile tile : row) - { + for (TextureTile[] row : tileArray) { + for (TextureTile tile : row) { Thread.sleep(1); // generates InterruptedException if thread has been interrupted - if (tile == null) + if (tile == null) { continue; + } - if (isTileLocalOrAbsent(tile)) + if (isTileLocalOrAbsent(tile)) { continue; // tile is local or absent - + } tiles.add(tile); } } return tiles; } - protected boolean isTileLocalOrAbsent(TextureTile tile) - { - if (this.layer.getLevels().isResourceAbsent(tile)) + protected boolean isTileLocalOrAbsent(TextureTile tile) { + if (this.layer.getLevels().isResourceAbsent(tile)) { return true; // tile is absent - + } URL url = this.fileStore.findFile(tile.getPath(), false); return url != null && !this.layer.isTextureFileExpired(tile, url, fileStore); } - protected long estimateAverageTileSize() - { + protected long estimateAverageTileSize() { Long previouslyComputedSize = (Long) this.layer.getValue(AVKey.AVERAGE_TILE_SIZE); - if (previouslyComputedSize != null) + if (previouslyComputedSize != null) { return previouslyComputedSize; + } long size = 0; long count = 0; // Average cached tile files size in a few directories from first non empty level Level targetLevel = this.layer.getLevels().getFirstLevel(); - while (targetLevel.isEmpty() && !targetLevel.equals(this.layer.getLevels().getLastLevel())) - { + while (targetLevel.isEmpty() && !targetLevel.equals(this.layer.getLevels().getLastLevel())) { targetLevel = this.layer.getLevels().getLevel(targetLevel.getLevelNumber() + 1); } File cacheRoot = new File(this.fileStore.getWriteLocation(), targetLevel.getPath()); - if (cacheRoot.exists()) - { - File[] rowDirs = cacheRoot.listFiles(new FileFilter() - { - public boolean accept(File file) - { + if (cacheRoot.exists()) { + File[] rowDirs = cacheRoot.listFiles(new FileFilter() { + public boolean accept(File file) { return file.isDirectory(); } }); - for (File dir : rowDirs) - { + for (File dir : rowDirs) { long averageSize = computeAverageTileSize(dir); - if (averageSize > 0) - { + if (averageSize > 0) { size += averageSize; count++; } if (count >= 2) // average content from up to 2 cache folders + { break; + } } } Long averageTileSize = DEFAULT_AVERAGE_FILE_SIZE; - if (count > 0 && size > 0) - { + if (count > 0 && size > 0) { averageTileSize = size / count; this.layer.setValue(AVKey.AVERAGE_TILE_SIZE, averageTileSize); } @@ -460,23 +414,18 @@ public boolean accept(File file) return averageTileSize; } - protected long computeAverageTileSize(File dir) - { + protected long computeAverageTileSize(File dir) { long size = 0; int count = 0; File[] files = dir.listFiles(); - for (File file : files) - { - try - { + for (File file : files) { + try { FileInputStream fis = new FileInputStream(file); size += fis.available(); fis.close(); count++; - } - catch (IOException e) - { + } catch (IOException e) { count += 0; } } diff --git a/src/gov/nasa/worldwind/layers/CachedRenderableLayer.java b/src/gov/nasa/worldwind/layers/CachedRenderableLayer.java index 2fd8fdc01c..1c964931ca 100644 --- a/src/gov/nasa/worldwind/layers/CachedRenderableLayer.java +++ b/src/gov/nasa/worldwind/layers/CachedRenderableLayer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers; import gov.nasa.worldwind.*; @@ -24,8 +23,8 @@ * @author tag * @version $Id: CachedRenderableLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CachedRenderableLayer extends AbstractLayer -{ +public class CachedRenderableLayer extends AbstractLayer { + protected static final int DEFAULT_DEPTH = 4; protected BasicQuadTree extentTree; // this is used until we work out the caching and retrieval scheme @@ -38,8 +37,7 @@ public class CachedRenderableLayer extends AbstractLayer * * @throws IllegalArgumentException if the coverage sector is null. */ - public CachedRenderableLayer(Sector coverage) - { + public CachedRenderableLayer(Sector coverage) { // Extent tree checks args this.extentTree = new BasicQuadTree(DEFAULT_DEPTH, coverage, null); } @@ -47,13 +45,12 @@ public CachedRenderableLayer(Sector coverage) /** * Constructs a layer instance. * - * @param coverage the geographic area covered by the layer's Renderables. + * @param coverage the geographic area covered by the layer's Renderables. * @param numLevels the depth of the tree used to sort the Renderables. * * @throws IllegalArgumentException if the coverage sector is null or the number of levels is less than 1; */ - public CachedRenderableLayer(Sector coverage, int numLevels) - { + public CachedRenderableLayer(Sector coverage, int numLevels) { // Extent tree checks args this.extentTree = new BasicQuadTree(numLevels, coverage, null); } @@ -63,8 +60,7 @@ public CachedRenderableLayer(Sector coverage, int numLevels) * * @return true if the layer contains Renderables, otherwise false. */ - public boolean hasItems() - { + public boolean hasItems() { return this.extentTree.hasItems(); } @@ -73,11 +69,11 @@ public boolean hasItems() * * @param item the Renderable to add. * - * @throws IllegalArgumentException if the item is null or does not implement {@link gov.nasa.worldwind.render.GeographicExtent}. + * @throws IllegalArgumentException if the item is null or does not implement + * {@link gov.nasa.worldwind.render.GeographicExtent}. * @see #add(gov.nasa.worldwind.render.Renderable, String) */ - public void add(Renderable item) - { + public void add(Renderable item) { this.add(item, null); // extent tree checks args } @@ -87,13 +83,12 @@ public void add(Renderable item) * @param item the Renderable to add. * @param name a name for the Renderable. May be null, in which case the item has no name. * - * @throws IllegalArgumentException if the item is null or does not implement {@link gov.nasa.worldwind.render.GeographicExtent}. + * @throws IllegalArgumentException if the item is null or does not implement + * {@link gov.nasa.worldwind.render.GeographicExtent}. * @see #add(gov.nasa.worldwind.render.Renderable) */ - public void add(Renderable item, String name) - { - if (!(item instanceof GeographicExtent)) - { + public void add(Renderable item, String name) { + if (!(item instanceof GeographicExtent)) { String message = Logging.getMessage("GeographicTree.NotGeometricExtent"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,8 +105,7 @@ public void add(Renderable item, String name) * * @see #removeByName(String) */ - public void remove(Renderable item) - { + public void remove(Renderable item) { // extent tree checks args this.extentTree.remove(item); } @@ -123,8 +117,7 @@ public void remove(Renderable item) * * @see #remove(gov.nasa.worldwind.render.Renderable) */ - public void removeByName(String name) - { + public void removeByName(String name) { this.extentTree.removeByName(name); } @@ -138,8 +131,7 @@ public void removeByName(String name) * @see #getRenderables(gov.nasa.worldwind.geom.Sector) * @see #getAllRenderables() */ - public Collection getRenderables(LatLon location) - { + public Collection getRenderables(LatLon location) { // extent tree checks args return this.extentTree.getItemsAtLocation(location, null); } @@ -154,8 +146,7 @@ public Collection getRenderables(LatLon location) * @see #getRenderables(gov.nasa.worldwind.geom.LatLon) * @see #getAllRenderables() */ - public Collection getRenderables(Sector extent) - { + public Collection getRenderables(Sector extent) { // extent tree checks args return this.extentTree.getItemsInRegion(extent, null); } @@ -165,8 +156,7 @@ public Collection getRenderables(Sector extent) * * @return an Iterable over all the Renderables in the layer. */ - public Iterable getAllRenderables() - { + public Iterable getAllRenderables() { return this.extentTree; // the tree is an Iterable } @@ -177,8 +167,7 @@ public Iterable getAllRenderables() * * @return the Renderable of the given name, or null if no Renderable with the name is in the layer. */ - public Renderable getByName(String name) - { + public Renderable getByName(String name) { return this.extentTree.getByName(name); } @@ -188,8 +177,7 @@ public Renderable getByName(String name) * @param opacity the current opacity value, which is ignored by this layer. */ @Override - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { super.setOpacity(opacity); } @@ -200,28 +188,24 @@ public void setOpacity(double opacity) * @return The layer opacity, a value between 0 and 1. */ @Override - public double getOpacity() - { + public double getOpacity() { return super.getOpacity(); } - /** Disposes any Renderables implementing @{link Dispose} and removes all Renderables from the layer. */ - public void dispose() - { + /** + * Disposes any Renderables implementing @{link Dispose} and removes all Renderables from the layer. + */ + public void dispose() { this.disposeRenderables(); } - protected void disposeRenderables() - { - for (Renderable renderable : this.getAllRenderables()) - { - try - { - if (renderable instanceof Disposable) + protected void disposeRenderables() { + for (Renderable renderable : this.getAllRenderables()) { + try { + if (renderable instanceof Disposable) { ((Disposable) renderable).dispose(); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToDisposeRenderable"); Logging.logger().severe(msg); // continue to next renderable @@ -231,34 +215,27 @@ protected void disposeRenderables() this.extentTree.clear(); } - protected void doPreRender(DrawContext dc) - { + protected void doPreRender(DrawContext dc) { this.doPreRender(dc, this.getAllRenderables()); } - protected void doPick(DrawContext dc, java.awt.Point pickPoint) - { + protected void doPick(DrawContext dc, java.awt.Point pickPoint) { this.doPick(dc, this.getAllRenderables(), pickPoint); } - protected void doRender(DrawContext dc) - { + protected void doRender(DrawContext dc) { this.doRender(dc, this.getAllRenderables()); } - protected void doPreRender(DrawContext dc, Iterable renderables) - { - for (Renderable renderable : renderables) - { - try - { + protected void doPreRender(DrawContext dc, Iterable renderables) { + for (Renderable renderable : renderables) { + try { // If the caller has specified their own Iterable, // then we cannot make any guarantees about its contents. - if (renderable != null && renderable instanceof PreRenderable) + if (renderable != null && renderable instanceof PreRenderable) { ((PreRenderable) renderable).preRender(dc); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhilePrerenderingRenderable"); Logging.logger().severe(msg); // continue to next renderable @@ -266,31 +243,24 @@ protected void doPreRender(DrawContext dc, Iterable render } } - protected void doPick(DrawContext dc, Iterable renderables, java.awt.Point pickPoint) - { + protected void doPick(DrawContext dc, Iterable renderables, java.awt.Point pickPoint) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); - try - { - for (Renderable renderable : renderables) - { + try { + for (Renderable renderable : renderables) { // If the caller has specified their own Iterable, // then we cannot make any guarantees about its contents. - if (renderable != null) - { + if (renderable != null) { float[] inColor = new float[4]; gl.glGetFloatv(GL2.GL_CURRENT_COLOR, inColor, 0); java.awt.Color color = dc.getUniquePickColor(); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); - try - { + try { renderable.render(dc); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhilePickingRenderable"); Logging.logger().severe(msg); continue; // go on to next renderable @@ -298,39 +268,30 @@ protected void doPick(DrawContext dc, Iterable renderables gl.glColor4fv(inColor, 0); - if (renderable instanceof Locatable) - { + if (renderable instanceof Locatable) { this.pickSupport.addPickableObject(color.getRGB(), renderable, - ((Locatable) renderable).getPosition(), false); - } - else - { + ((Locatable) renderable).getPosition(), false); + } else { this.pickSupport.addPickableObject(color.getRGB(), renderable); } } } this.pickSupport.resolvePick(dc, pickPoint, this); - } - finally - { + } finally { this.pickSupport.endPicking(dc); } } - protected void doRender(DrawContext dc, Iterable renderables) - { - for (Renderable renderable : renderables) - { - try - { + protected void doRender(DrawContext dc, Iterable renderables) { + for (Renderable renderable : renderables) { + try { // If the caller has specified their own Iterable, // then we cannot make any guarantees about its contents. - if (renderable != null) + if (renderable != null) { renderable.render(dc); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhileRenderingRenderable"); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); // continue to next renderable @@ -339,8 +300,7 @@ protected void doRender(DrawContext dc, Iterable renderabl } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.CachedRenderableLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/CompassLayer.java b/src/gov/nasa/worldwind/layers/CompassLayer.java index 634f5c0430..05937a1d69 100644 --- a/src/gov/nasa/worldwind/layers/CompassLayer.java +++ b/src/gov/nasa/worldwind/layers/CompassLayer.java @@ -23,8 +23,8 @@ * @author tag * @version $Id: CompassLayer.java 2121 2014-07-03 03:10:54Z tgaskins $ */ -public class CompassLayer extends AbstractLayer -{ +public class CompassLayer extends AbstractLayer { + protected String iconFilePath = "images/notched-compass.dds"; // TODO: make configurable protected double compassToViewportScale = 0.2; // TODO: make configurable protected double iconScale = 0.5; @@ -43,32 +43,27 @@ public class CompassLayer extends AbstractLayer // Draw it as ordered with an eye distance of 0 so that it shows up in front of most other things. protected OrderedIcon orderedImage = new OrderedIcon(); - protected class OrderedIcon implements OrderedRenderable - { - public double getDistanceFromEye() - { + protected class OrderedIcon implements OrderedRenderable { + + public double getDistanceFromEye() { return 0; } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { CompassLayer.this.draw(dc); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { CompassLayer.this.draw(dc); } } - public CompassLayer() - { + public CompassLayer() { this.setOpacity(0.8); // TODO: make configurable this.setPickEnabled(false); // Default to no picking } - public CompassLayer(String iconFilePath) - { + public CompassLayer(String iconFilePath) { this.setIconFilePath(iconFilePath); this.setOpacity(0.8); // TODO: make configurable this.setPickEnabled(false); // Default to no picking @@ -79,8 +74,7 @@ public CompassLayer(String iconFilePath) * * @return the icon file path */ - public String getIconFilePath() - { + public String getIconFilePath() { return iconFilePath; } @@ -90,10 +84,8 @@ public String getIconFilePath() * * @param iconFilePath the path to the icon's image file */ - public void setIconFilePath(String iconFilePath) - { - if (iconFilePath == null) - { + public void setIconFilePath(String iconFilePath) { + if (iconFilePath == null) { String message = Logging.getMessage("nullValue.IconFilePath"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -106,8 +98,7 @@ public void setIconFilePath(String iconFilePath) * * @return the compass-to-viewport scale factor */ - public double getCompassToViewportScale() - { + public double getCompassToViewportScale() { return compassToViewportScale; } @@ -119,8 +110,7 @@ public double getCompassToViewportScale() * * @param compassToViewportScale the compass to viewport scale factor */ - public void setCompassToViewportScale(double compassToViewportScale) - { + public void setCompassToViewportScale(double compassToViewportScale) { this.compassToViewportScale = compassToViewportScale; } @@ -129,8 +119,7 @@ public void setCompassToViewportScale(double compassToViewportScale) * * @return the current icon scale */ - public double getIconScale() - { + public double getIconScale() { return iconScale; } @@ -144,8 +133,7 @@ public double getIconScale() * * @param iconScale the icon scale factor */ - public void setIconScale(double iconScale) - { + public void setIconScale(double iconScale) { this.iconScale = iconScale; } @@ -154,8 +142,7 @@ public void setIconScale(double iconScale) * * @return the icon's resize behavior */ - public String getResizeBehavior() - { + public String getResizeBehavior() { return resizeBehavior; } @@ -171,13 +158,11 @@ public String getResizeBehavior() * * @param resizeBehavior the desired resize behavior */ - public void setResizeBehavior(String resizeBehavior) - { + public void setResizeBehavior(String resizeBehavior) { this.resizeBehavior = resizeBehavior; } - public int getBorderWidth() - { + public int getBorderWidth() { return borderWidth; } @@ -187,8 +172,7 @@ public int getBorderWidth() * @param borderWidth the number of pixels to offset the compass icon from the borders indicated by {@link * #setPosition(String)}. */ - public void setBorderWidth(int borderWidth) - { + public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; } @@ -197,8 +181,7 @@ public void setBorderWidth(int borderWidth) * * @return the current compass position */ - public String getPosition() - { + public String getPosition() { return position; } @@ -209,10 +192,8 @@ public String getPosition() * * @param position the desired compass position */ - public void setPosition(String position) - { - if (position == null) - { + public void setPosition(String position) { + if (position == null) { String message = Logging.getMessage("nullValue.CompassPositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -225,8 +206,7 @@ public void setPosition(String position) * * @return the current location center. May be null. */ - public Vec4 getLocationCenter() - { + public Vec4 getLocationCenter() { return locationCenter; } @@ -243,8 +223,7 @@ public Vec4 getLocationCenter() * @see #setPosition(String) * @see #setLocationOffset(gov.nasa.worldwind.geom.Vec4) */ - public void setLocationCenter(Vec4 locationCenter) - { + public void setLocationCenter(Vec4 locationCenter) { this.locationCenter = locationCenter; } @@ -253,8 +232,7 @@ public void setLocationCenter(Vec4 locationCenter) * * @return the location offset. Will be null if no offset has been specified. */ - public Vec4 getLocationOffset() - { + public Vec4 getLocationOffset() { return locationOffset; } @@ -262,66 +240,60 @@ public Vec4 getLocationOffset() * Specifies a placement offset from the compass' position on the screen. * * @param locationOffset the number of pixels to shift the compass image from its specified screen position. A - * positive X value shifts the image to the right. A positive Y value shifts the image up. If - * null, no offset is applied. The default offset is null. + * positive X value shifts the image to the right. A positive Y value shifts the image up. If null, no offset is + * applied. The default offset is null. * * @see #setLocationCenter(gov.nasa.worldwind.geom.Vec4) * @see #setPosition(String) */ - public void setLocationOffset(Vec4 locationOffset) - { + public void setLocationOffset(Vec4 locationOffset) { this.locationOffset = locationOffset; } - protected void doRender(DrawContext dc) - { - if (dc.isContinuous2DGlobe() && this.frameStampForDrawing == dc.getFrameTimeStamp()) + protected void doRender(DrawContext dc) { + if (dc.isContinuous2DGlobe() && this.frameStampForDrawing == dc.getFrameTimeStamp()) { return; + } dc.addOrderedRenderable(this.orderedImage); this.frameStampForDrawing = dc.getFrameTimeStamp(); } - protected void doPick(DrawContext dc, Point pickPoint) - { - if (dc.isContinuous2DGlobe() && this.frameStampForPicking == dc.getFrameTimeStamp()) + protected void doPick(DrawContext dc, Point pickPoint) { + if (dc.isContinuous2DGlobe() && this.frameStampForPicking == dc.getFrameTimeStamp()) { return; + } dc.addOrderedRenderable(this.orderedImage); this.frameStampForPicking = dc.getFrameTimeStamp(); } - public boolean isShowTilt() - { + public boolean isShowTilt() { return showTilt; } - public void setShowTilt(boolean showTilt) - { + public void setShowTilt(boolean showTilt) { this.showTilt = showTilt; } - protected void draw(DrawContext dc) - { - if (this.getIconFilePath() == null) + protected void draw(DrawContext dc) { + if (this.getIconFilePath() == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { gl.glDisable(GL.GL_DEPTH_TEST); Texture iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture == null) - { + if (iconTexture == null) { this.initializeTexture(dc); iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture == null) - { + if (iconTexture == null) { String msg = Logging.getMessage("generic.ImageReadFailed"); Logging.logger().finer(msg); return; @@ -341,8 +313,9 @@ protected void draw(DrawContext dc) java.awt.Rectangle viewport = dc.getView().getViewport(); ogsh.pushProjectionIdentity(gl); double maxwh = width > height ? width : height; - if (maxwh == 0) + if (maxwh == 0) { maxwh = 1; + } gl.glOrtho(0d, viewport.width, 0d, viewport.height, -0.6 * maxwh, 0.6 * maxwh); ogsh.pushModelviewIdentity(gl); @@ -354,11 +327,12 @@ protected void draw(DrawContext dc) gl.glTranslated(locationSW.x, locationSW.y, locationSW.z); gl.glScaled(scale, scale, 1); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glTranslated(width / 2, height / 2, 0); if (this.showTilt) // formula contributed by Ty Hayden + { gl.glRotated(70d * (pitch / 90.0), 1d, 0d, 0d); + } gl.glRotated(heading, 0d, 0d, 1d); gl.glTranslated(-width / 2, -height / 2, 0); @@ -371,26 +345,22 @@ protected void draw(DrawContext dc) TextureCoords texCoords = iconTexture.getImageTexCoords(); gl.glScaled(width, height, 1d); dc.drawUnitQuad(texCoords); - } - else - { + } else { // Picking this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); - try - { + try { // Add a picked object for the compass to the list of pickable objects. Color color = dc.getUniquePickColor(); PickedObject po = new PickedObject(color.getRGB(), this, null, false); this.pickSupport.addPickableObject(po); - if (dc.getPickPoint() != null) - { + if (dc.getPickPoint() != null) { // If the pick point is not null, compute the pick point 'heading' relative to the compass // center and set the picked heading on our picked object. The pick point is null if a pick // rectangle is specified but a pick point is not. Vec4 center = new Vec4(locationSW.x + width * scale / 2, locationSW.y + height * scale / 2, - 0); + 0); double px = dc.getPickPoint().x - center.x; double py = viewport.getHeight() - dc.getPickPoint().y - center.y; Angle pickHeading = Angle.fromRadians(Math.atan2(px, py)); @@ -402,22 +372,17 @@ protected void draw(DrawContext dc) gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); gl.glScaled(width, height, 1d); dc.drawUnitQuad(); - } - finally - { + } finally { // Done picking this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, dc.getPickPoint(), this); } } - } - finally - { + } finally { dc.restoreDefaultDepthTesting(); dc.restoreDefaultCurrentColor(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glBindTexture(GL.GL_TEXTURE_2D, 0); gl.glDisable(GL.GL_TEXTURE_2D); // restore to default texture state dc.restoreDefaultBlending(); @@ -427,38 +392,27 @@ protected void draw(DrawContext dc) } } - protected double computeScale(java.awt.Rectangle viewport) - { - if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) - { + protected double computeScale(java.awt.Rectangle viewport) { + if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) { return Math.min(1d, (this.compassToViewportScale) * viewport.width / this.getScaledIconWidth()); - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) { return (this.compassToViewportScale) * viewport.width / this.getScaledIconWidth(); - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) { return 1d; - } - else - { + } else { return 1d; } } - protected double getScaledIconWidth() - { + protected double getScaledIconWidth() { return this.iconWidth * this.iconScale; } - protected double getScaledIconHeight() - { + protected double getScaledIconHeight() { return this.iconHeight * this.iconScale; } - protected Vec4 computeLocation(java.awt.Rectangle viewport, double scale) - { + protected Vec4 computeLocation(java.awt.Rectangle viewport, double scale) { double width = this.getScaledIconWidth(); double height = this.getScaledIconHeight(); @@ -468,39 +422,28 @@ protected Vec4 computeLocation(java.awt.Rectangle viewport, double scale) double x; double y; - if (this.locationCenter != null) - { + if (this.locationCenter != null) { x = this.locationCenter.x - scaledWidth / 2; y = this.locationCenter.y - scaledHeight / 2; - } - else if (this.position.equals(AVKey.NORTHEAST)) - { + } else if (this.position.equals(AVKey.NORTHEAST)) { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHEAST)) - { + } else if (this.position.equals(AVKey.SOUTHEAST)) { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = 0d + this.borderWidth; - } - else if (this.position.equals(AVKey.NORTHWEST)) - { + } else if (this.position.equals(AVKey.NORTHWEST)) { x = 0d + this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHWEST)) - { + } else if (this.position.equals(AVKey.SOUTHWEST)) { x = 0d + this.borderWidth; y = 0d + this.borderWidth; - } - else // use North East as default + } else // use North East as default { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; } - if (this.locationOffset != null) - { + if (this.locationOffset != null) { x += this.locationOffset.x; y += this.locationOffset.y; } @@ -508,42 +451,40 @@ else if (this.position.equals(AVKey.SOUTHWEST)) return new Vec4(x, y, 0); } - protected double computeHeading(View view) - { - if (view == null) + protected double computeHeading(View view) { + if (view == null) { return 0.0; + } return view.getHeading().getDegrees(); } - protected double computePitch(View view) - { - if (view == null) + protected double computePitch(View view) { + if (view == null) { return 0.0; + } - if (!(view instanceof OrbitView)) + if (!(view instanceof OrbitView)) { return 0.0; + } OrbitView orbitView = (OrbitView) view; return orbitView.getPitch().getDegrees(); } - protected void initializeTexture(DrawContext dc) - { + protected void initializeTexture(DrawContext dc) { Texture iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture != null) + if (iconTexture != null) { return; + } GL gl = dc.getGL(); - try - { + try { InputStream iconStream = this.getClass().getResourceAsStream("/" + this.getIconFilePath()); - if (iconStream == null) - { + if (iconStream == null) { File iconFile = new File(this.iconFilePath); - if (iconFile.exists()) - { + if (iconFile.exists()) { iconStream = new FileInputStream(iconFile); } } @@ -554,9 +495,7 @@ protected void initializeTexture(DrawContext dc) this.iconWidth = iconTexture.getWidth(); this.iconHeight = iconTexture.getHeight(); dc.getTextureCache().put(this.getIconFilePath(), iconTexture); - } - catch (IOException e) - { + } catch (IOException e) { String msg = Logging.getMessage("layers.IOExceptionDuringInitialization"); Logging.logger().severe(msg); throw new WWRuntimeException(msg, e); @@ -573,8 +512,7 @@ protected void initializeTexture(DrawContext dc) } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.CompassLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/CrosshairLayer.java b/src/gov/nasa/worldwind/layers/CrosshairLayer.java index c1de7dc03a..5489238fba 100644 --- a/src/gov/nasa/worldwind/layers/CrosshairLayer.java +++ b/src/gov/nasa/worldwind/layers/CrosshairLayer.java @@ -22,8 +22,8 @@ * @author Patrick Murris * @version $Id: CrosshairLayer.java 1953 2014-04-21 15:43:35Z tgaskins $ */ -public class CrosshairLayer extends AbstractLayer -{ +public class CrosshairLayer extends AbstractLayer { + private String iconFilePath = "images/32x32-crosshair-simple.png"; // TODO: make configurable private double toViewportScale = 1d; // TODO: make configurable private double iconScale = 1d; @@ -35,31 +35,26 @@ public class CrosshairLayer extends AbstractLayer // Draw it as ordered with an eye distance of 0 so that it shows up in front of most other things. private OrderedIcon orderedImage = new OrderedIcon(); - private class OrderedIcon implements OrderedRenderable - { - public double getDistanceFromEye() - { + private class OrderedIcon implements OrderedRenderable { + + public double getDistanceFromEye() { return 0; } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { // Not implemented } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { CrosshairLayer.this.draw(dc); } } - public CrosshairLayer() - { + public CrosshairLayer() { this.setOpacity(0.8); // TODO: make configurable } - public CrosshairLayer(String iconFilePath) - { + public CrosshairLayer(String iconFilePath) { this.setIconFilePath(iconFilePath); this.setOpacity(0.8); // TODO: make configurable } @@ -69,8 +64,7 @@ public CrosshairLayer(String iconFilePath) * * @return the icon file path */ - public String getIconFilePath() - { + public String getIconFilePath() { return iconFilePath; } @@ -81,10 +75,8 @@ public String getIconFilePath() * * @param iconFilePath the path to the icon's image file */ - public void setIconFilePath(String iconFilePath) - { - if (iconFilePath == null) - { + public void setIconFilePath(String iconFilePath) { + if (iconFilePath == null) { String message = Logging.getMessage("nullValue.IconFilePath"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -97,8 +89,7 @@ public void setIconFilePath(String iconFilePath) * * @return the crosshair-to-viewport scale factor */ - public double getToViewportScale() - { + public double getToViewportScale() { return toViewportScale; } @@ -110,8 +101,7 @@ public double getToViewportScale() * * @param toViewportScale the compass to viewport scale factor */ - public void setToViewportScale(double toViewportScale) - { + public void setToViewportScale(double toViewportScale) { this.toViewportScale = toViewportScale; } @@ -120,8 +110,7 @@ public void setToViewportScale(double toViewportScale) * * @return the current icon scale */ - public double getIconScale() - { + public double getIconScale() { return iconScale; } @@ -133,8 +122,7 @@ public double getIconScale() * * @param iconScale the icon scale factor */ - public void setIconScale(double iconScale) - { + public void setIconScale(double iconScale) { this.iconScale = iconScale; } @@ -143,8 +131,7 @@ public void setIconScale(double iconScale) * * @return the icon's resize behavior */ - public String getResizeBehavior() - { + public String getResizeBehavior() { return resizeBehavior; } @@ -160,8 +147,7 @@ public String getResizeBehavior() * * @param resizeBehavior the desired resize behavior */ - public void setResizeBehavior(String resizeBehavior) - { + public void setResizeBehavior(String resizeBehavior) { this.resizeBehavior = resizeBehavior; } @@ -171,8 +157,7 @@ public void setResizeBehavior(String resizeBehavior) * * @return the crosshair location inside the viewport. */ - public Vec4 getLocationCenter() - { + public Vec4 getLocationCenter() { return locationCenter; } @@ -182,20 +167,18 @@ public Vec4 getLocationCenter() * * @param locationCenter the crosshair location inside the viewport. */ - public void setLocationCenter(Vec4 locationCenter) - { + public void setLocationCenter(Vec4 locationCenter) { this.locationCenter = locationCenter; } - protected void doRender(DrawContext dc) - { + protected void doRender(DrawContext dc) { dc.addOrderedRenderable(this.orderedImage); } - private void draw(DrawContext dc) - { - if (this.getIconFilePath() == null) + private void draw(DrawContext dc) { + if (this.getIconFilePath() == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -203,23 +186,20 @@ private void draw(DrawContext dc) boolean modelviewPushed = false; boolean projectionPushed = false; - try - { + try { gl.glPushAttrib(GL2.GL_DEPTH_BUFFER_BIT - | GL2.GL_COLOR_BUFFER_BIT - | GL2.GL_ENABLE_BIT - | GL2.GL_TRANSFORM_BIT - | GL2.GL_VIEWPORT_BIT - | GL2.GL_CURRENT_BIT); + | GL2.GL_COLOR_BUFFER_BIT + | GL2.GL_ENABLE_BIT + | GL2.GL_TRANSFORM_BIT + | GL2.GL_VIEWPORT_BIT + | GL2.GL_CURRENT_BIT); attribsPushed = true; Texture iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture == null) - { + if (iconTexture == null) { this.initializeTexture(dc); iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture == null) - { + if (iconTexture == null) { String msg = Logging.getMessage("generic.ImageReadFailed"); Logging.logger().finer(msg); return; @@ -266,58 +246,44 @@ private void draw(DrawContext dc) TextureCoords texCoords = iconTexture.getImageTexCoords(); gl.glScaled(width, height, 1d); dc.drawUnitQuad(texCoords); - } - finally - { + } finally { gl.glBindTexture(GL.GL_TEXTURE_2D, 0); - if (projectionPushed) - { + if (projectionPushed) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); } - if (modelviewPushed) - { + if (modelviewPushed) { gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); } - if (attribsPushed) + if (attribsPushed) { gl.glPopAttrib(); + } } } - private double computeScale(Rectangle viewport) - { - if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) - { + private double computeScale(Rectangle viewport) { + if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) { return Math.min(1d, (this.toViewportScale) * viewport.width / this.getScaledIconWidth()); - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) { return (this.toViewportScale) * viewport.width / this.getScaledIconWidth(); - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) { return 1d; - } - else - { + } else { return 1d; } } - private double getScaledIconWidth() - { + private double getScaledIconWidth() { return this.iconWidth * this.iconScale; } - private double getScaledIconHeight() - { + private double getScaledIconHeight() { return this.iconHeight * this.iconScale; } - private Vec4 computeLocation(Rectangle viewport, double scale) - { + private Vec4 computeLocation(Rectangle viewport, double scale) { double width = this.getScaledIconWidth(); double height = this.getScaledIconHeight(); @@ -327,12 +293,10 @@ private Vec4 computeLocation(Rectangle viewport, double scale) double x; double y; - if (this.locationCenter != null) - { + if (this.locationCenter != null) { x = this.locationCenter.x - scaledWidth / 2; y = this.locationCenter.y - scaledHeight / 2; - } - else // viewport center + } else // viewport center { x = viewport.getWidth() / 2 - scaledWidth / 2; y = viewport.getHeight() / 2 - scaledHeight / 2; @@ -341,22 +305,19 @@ private Vec4 computeLocation(Rectangle viewport, double scale) return new Vec4(x, y, 0); } - private void initializeTexture(DrawContext dc) - { + private void initializeTexture(DrawContext dc) { Texture iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture != null) + if (iconTexture != null) { return; + } GL gl = dc.getGL(); - try - { + try { InputStream iconStream = this.getClass().getResourceAsStream("/" + this.getIconFilePath()); - if (iconStream == null) - { + if (iconStream == null) { File iconFile = new File(this.getIconFilePath()); - if (iconFile.exists()) - { + if (iconFile.exists()) { iconStream = new FileInputStream(iconFile); } } @@ -367,9 +328,7 @@ private void initializeTexture(DrawContext dc) this.iconWidth = iconTexture.getWidth(); this.iconHeight = iconTexture.getHeight(); dc.getTextureCache().put(this.getIconFilePath(), iconTexture); - } - catch (IOException e) - { + } catch (IOException e) { String msg = Logging.getMessage("layers.IOExceptionDuringInitialization"); Logging.logger().severe(msg); throw new WWRuntimeException(msg, e); @@ -386,8 +345,7 @@ private void initializeTexture(DrawContext dc) } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.CrosshairLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/BMNGOneImage.java b/src/gov/nasa/worldwind/layers/Earth/BMNGOneImage.java index 660039fee4..03b51fd352 100644 --- a/src/gov/nasa/worldwind/layers/Earth/BMNGOneImage.java +++ b/src/gov/nasa/worldwind/layers/Earth/BMNGOneImage.java @@ -14,12 +14,11 @@ * @author tag * @version $Id: BMNGOneImage.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BMNGOneImage extends RenderableLayer -{ +public class BMNGOneImage extends RenderableLayer { + protected static final String IMAGE_PATH = "images/BMNG_world.topo.bathy.200405.3.2048x1024.dds"; - public BMNGOneImage() - { + public BMNGOneImage() { this.setName(Logging.getMessage("layers.Earth.BlueMarbleOneImageLayer.Name")); this.addRenderable(new SurfaceImage(IMAGE_PATH, Sector.FULL_SPHERE)); @@ -28,8 +27,7 @@ public BMNGOneImage() } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.Earth.BlueMarbleOneImageLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/BMNGWMSLayer.java b/src/gov/nasa/worldwind/layers/Earth/BMNGWMSLayer.java index 45b5493711..f54e78035f 100644 --- a/src/gov/nasa/worldwind/layers/Earth/BMNGWMSLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/BMNGWMSLayer.java @@ -13,15 +13,13 @@ * @author tag * @version $Id: BMNGWMSLayer.java 1958 2014-04-24 19:25:37Z tgaskins $ */ -public class BMNGWMSLayer extends WMSTiledImageLayer -{ - public BMNGWMSLayer() - { +public class BMNGWMSLayer extends WMSTiledImageLayer { + + public BMNGWMSLayer() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/BMNGWMSLayer2.xml", null); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/CountryBoundariesLayer.java b/src/gov/nasa/worldwind/layers/Earth/CountryBoundariesLayer.java index dfcca1859e..ee8830b121 100644 --- a/src/gov/nasa/worldwind/layers/Earth/CountryBoundariesLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/CountryBoundariesLayer.java @@ -13,15 +13,13 @@ * @author tag * @version $Id: CountryBoundariesLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CountryBoundariesLayer extends WMSTiledImageLayer -{ - public CountryBoundariesLayer() - { +public class CountryBoundariesLayer extends WMSTiledImageLayer { + + public CountryBoundariesLayer() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/CountryBoundariesLayer.xml", null); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/LandsatI3WMSLayer.java b/src/gov/nasa/worldwind/layers/Earth/LandsatI3WMSLayer.java index dfd9cddc3f..c34cb997cd 100644 --- a/src/gov/nasa/worldwind/layers/Earth/LandsatI3WMSLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/LandsatI3WMSLayer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers.Earth; import gov.nasa.worldwind.util.*; @@ -14,15 +13,13 @@ * @author tag * @version $Id: LandsatI3WMSLayer.java 1958 2014-04-24 19:25:37Z tgaskins $ */ -public class LandsatI3WMSLayer extends WMSTiledImageLayer -{ - public LandsatI3WMSLayer() - { +public class LandsatI3WMSLayer extends WMSTiledImageLayer { + + public LandsatI3WMSLayer() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/LandsatI3WMSLayer2.xml", null); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/MGRSGraticuleLayer.java b/src/gov/nasa/worldwind/layers/Earth/MGRSGraticuleLayer.java index 8b1a54853d..430eecad3b 100644 --- a/src/gov/nasa/worldwind/layers/Earth/MGRSGraticuleLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/MGRSGraticuleLayer.java @@ -21,22 +21,35 @@ * @author Patrick Murris * @version $Id: MGRSGraticuleLayer.java 2153 2014-07-17 17:33:13Z tgaskins $ */ +public class MGRSGraticuleLayer extends UTMBaseGraticuleLayer { -public class MGRSGraticuleLayer extends UTMBaseGraticuleLayer -{ - /** Graticule for the UTM grid. */ + /** + * Graticule for the UTM grid. + */ public static final String GRATICULE_UTM_GRID = "Graticule.UTM.Grid"; - /** Graticule for the 100,000 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 100,000 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_100000M = "Graticule.100000m"; - /** Graticule for the 10,000 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 10,000 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_10000M = "Graticule.10000m"; - /** Graticule for the 1,000 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 1,000 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_1000M = "Graticule.1000m"; - /** Graticule for the 100 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 100 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_100M = "Graticule.100m"; - /** Graticule for the 10 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 10 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_10M = "Graticule.10m"; - /** Graticule for the 1 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 1 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_1M = "Graticule.1m"; private GridZone[][] gridZones = new GridZone[20][60]; // row/col @@ -44,9 +57,10 @@ public class MGRSGraticuleLayer extends UTMBaseGraticuleLayer private double zoneMaxAltitude = 5000e3; private double squareMaxAltitude = 3000e3; - /** Creates a new MGRSGraticuleLayer, with default graticule attributes. */ - public MGRSGraticuleLayer() - { + /** + * Creates a new MGRSGraticuleLayer, with default graticule attributes. + */ + public MGRSGraticuleLayer() { initRenderingParams(); this.metricScaleSupport.setScaleModulo((int) 100e3); this.setName(Logging.getMessage("layers.Earth.MGRSGraticule.Name")); @@ -58,15 +72,12 @@ public MGRSGraticuleLayer() * * @return maximum resolution rendered. */ - public String getMaximumGraticuleResolution() - { + public String getMaximumGraticuleResolution() { String maxTypeDrawn = null; String[] orderedTypeList = getOrderedTypes(); - for (String type : orderedTypeList) - { + for (String type : orderedTypeList) { GraticuleRenderingParams params = getRenderingParams(type); - if (params.isDrawLines()) - { + if (params.isDrawLines()) { maxTypeDrawn = type; } } @@ -77,15 +88,13 @@ public String getMaximumGraticuleResolution() * Sets the maxiumum resolution graticule that will be rendered. * * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public void setMaximumGraticuleResolution(String graticuleType) - { - if (graticuleType == null) - { + public void setMaximumGraticuleResolution(String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -93,15 +102,13 @@ public void setMaximumGraticuleResolution(String graticuleType) boolean pastTarget = false; String[] orderedTypeList = getOrderedTypes(); - for (String type : orderedTypeList) - { + for (String type : orderedTypeList) { // Enable all graticulte BEFORE and INCLUDING the target. // Disable all graticules AFTER the target. GraticuleRenderingParams params = getRenderingParams(type); params.setDrawLines(!pastTarget); params.setDrawLabels(!pastTarget); - if (!pastTarget && type.equals(graticuleType)) - { + if (!pastTarget && type.equals(graticuleType)) { pastTarget = true; } } @@ -111,17 +118,15 @@ public void setMaximumGraticuleResolution(String graticuleType) * Returns the line color of the specified graticule. * * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @return Color of the the graticule line. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public Color getGraticuleLineColor(String graticuleType) - { - if (graticuleType == null) - { + public Color getGraticuleLineColor(String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -133,23 +138,20 @@ public Color getGraticuleLineColor(String graticuleType) /** * Sets the line rendering color for the specified graticule. * - * @param color the line color for the specified graticule. + * @param color the line color for the specified graticule. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException ifcolor is null, if graticuleType is null, or if - * graticuleType is not a valid type. + * graticuleType is not a valid type. */ - public void setGraticuleLineColor(Color color, String graticuleType) - { - if (color == null) - { + public void setGraticuleLineColor(Color color, String graticuleType) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (graticuleType == null) - { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -161,30 +163,26 @@ public void setGraticuleLineColor(Color color, String graticuleType) /** * Sets the line rendering color for the specified graticules. * - * @param color the line color for the specified graticules. + * @param color the line color for the specified graticules. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException ifcolor is null, if graticuleType is null, or if - * graticuleType is not a valid type. + * graticuleType is not a valid type. */ - public void setGraticuleLineColor(Color color, Iterable graticuleType) - { - if (color == null) - { + public void setGraticuleLineColor(Color color, Iterable graticuleType) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (graticuleType == null) - { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (String type : graticuleType) - { + for (String type : graticuleType) { setGraticuleLineColor(color, type); } } @@ -196,18 +194,15 @@ public void setGraticuleLineColor(Color color, Iterable graticuleType) * * @throws IllegalArgumentException if color is null. */ - public void setGraticuleLineColor(Color color) - { - if (color == null) - { + public void setGraticuleLineColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { setGraticuleLineColor(color, type); } } @@ -216,17 +211,15 @@ public void setGraticuleLineColor(Color color) * Returns the line width of the specified graticule. * * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @return width of the graticule line. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public double getGraticuleLineWidth(String graticuleType) - { - if (graticuleType == null) - { + public double getGraticuleLineWidth(String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -238,17 +231,15 @@ public double getGraticuleLineWidth(String graticuleType) /** * Sets the line rendering width for the specified graticule. * - * @param lineWidth the line rendering width for the specified graticule. + * @param lineWidth the line rendering width for the specified graticule. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public void setGraticuleLineWidth(double lineWidth, String graticuleType) - { - if (graticuleType == null) - { + public void setGraticuleLineWidth(double lineWidth, String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -260,24 +251,21 @@ public void setGraticuleLineWidth(double lineWidth, String graticuleType) /** * Sets the line rendering width for the specified graticules. * - * @param lineWidth the line rendering width for the specified graticules. + * @param lineWidth the line rendering width for the specified graticules. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public void setGraticuleLineWidth(double lineWidth, Iterable graticuleType) - { - if (graticuleType == null) - { + public void setGraticuleLineWidth(double lineWidth, Iterable graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (String type : graticuleType) - { + for (String type : graticuleType) { setGraticuleLineWidth(lineWidth, type); } } @@ -287,11 +275,9 @@ public void setGraticuleLineWidth(double lineWidth, Iterable graticuleTy * * @param lineWidth the line rendering width. */ - public void setGraticuleLineWidth(double lineWidth) - { + public void setGraticuleLineWidth(double lineWidth) { String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { setGraticuleLineWidth(lineWidth, type); } } @@ -300,17 +286,15 @@ public void setGraticuleLineWidth(double lineWidth) * Returns the line rendering style of the specified graticule. * * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @return line rendering style of the graticule. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public String getGraticuleLineStyle(String graticuleType) - { - if (graticuleType == null) - { + public String getGraticuleLineStyle(String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -322,24 +306,21 @@ public String getGraticuleLineStyle(String graticuleType) /** * Sets the line rendering style for the specified graticule. * - * @param lineStyle the line rendering style for the specified graticule. One of LINE_STYLE_PLAIN, - * LINE_STYLE_DASHED, or LINE_STYLE_DOTTED. + * @param lineStyle the line rendering style for the specified graticule. One of LINE_STYLE_PLAIN, + * LINE_STYLE_DASHED, or LINE_STYLE_DOTTED. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M * * @throws IllegalArgumentException if lineStyle is null, if graticuleType is null, or if - * graticuleType is not a valid type. + * graticuleType is not a valid type. */ - public void setGraticuleLineStyle(String lineStyle, String graticuleType) - { - if (lineStyle == null) - { + public void setGraticuleLineStyle(String lineStyle, String graticuleType) { + if (lineStyle == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (graticuleType == null) - { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -351,31 +332,27 @@ public void setGraticuleLineStyle(String lineStyle, String graticuleType) /** * Sets the line rendering style for the specified graticules. * - * @param lineStyle the line rendering style for the specified graticules. One of LINE_STYLE_PLAIN, - * LINE_STYLE_DASHED, or LINE_STYLE_DOTTED. + * @param lineStyle the line rendering style for the specified graticules. One of LINE_STYLE_PLAIN, + * LINE_STYLE_DASHED, or LINE_STYLE_DOTTED. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M * * @throws IllegalArgumentException if lineStyle is null, if graticuleType is null, or if - * graticuleType is not a valid type. + * graticuleType is not a valid type. */ - public void setGraticuleLineStyle(String lineStyle, Iterable graticuleType) - { - if (lineStyle == null) - { + public void setGraticuleLineStyle(String lineStyle, Iterable graticuleType) { + if (lineStyle == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (graticuleType == null) - { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (String type : graticuleType) - { + for (String type : graticuleType) { setGraticuleLineStyle(lineStyle, type); } } @@ -387,18 +364,15 @@ public void setGraticuleLineStyle(String lineStyle, Iterable graticuleTy * * @throws IllegalArgumentException if lineStyle is null. */ - public void setGraticuleLineStyle(String lineStyle) - { - if (lineStyle == null) - { + public void setGraticuleLineStyle(String lineStyle) { + if (lineStyle == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { setGraticuleLineStyle(lineStyle, type); } } @@ -407,17 +381,15 @@ public void setGraticuleLineStyle(String lineStyle) * Returns whether specified graticule labels will be rendered. * * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @return true if graticule labels are will be rendered; false otherwise. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public boolean isDrawLabels(String graticuleType) - { - if (graticuleType == null) - { + public boolean isDrawLabels(String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -430,17 +402,15 @@ public boolean isDrawLabels(String graticuleType) * Sets whether the specified graticule labels will be rendered. If true, the graticule labels will be rendered. * Otherwise, the graticule labels will not be rendered, but other graticules will not be affected. * - * @param drawLabels true to render graticule labels; false to disable rendering. + * @param drawLabels true to render graticule labels; false to disable rendering. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public void setDrawLabels(boolean drawLabels, String graticuleType) - { - if (graticuleType == null) - { + public void setDrawLabels(boolean drawLabels, String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -453,24 +423,21 @@ public void setDrawLabels(boolean drawLabels, String graticuleType) * Sets whether the specified graticule labels will be rendered. If true, the graticule labels will be rendered. * Otherwise, the graticule labels will not be rendered, but other graticules will not be affected. * - * @param drawLabels true to render graticule labels; false to disable rendering. + * @param drawLabels true to render graticule labels; false to disable rendering. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public void setDrawLabels(boolean drawLabels, Iterable graticuleType) - { - if (graticuleType == null) - { + public void setDrawLabels(boolean drawLabels, Iterable graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (String type : graticuleType) - { + for (String type : graticuleType) { setDrawLabels(drawLabels, type); } } @@ -481,11 +448,9 @@ public void setDrawLabels(boolean drawLabels, Iterable graticuleType) * * @param drawLabels true to render all graticule labels; false to disable rendering. */ - public void setDrawLabels(boolean drawLabels) - { + public void setDrawLabels(boolean drawLabels) { String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { setDrawLabels(drawLabels, type); } } @@ -494,17 +459,15 @@ public void setDrawLabels(boolean drawLabels) * Returns the label color of the specified graticule. * * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @return Color of the the graticule label. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public Color getLabelColor(String graticuleType) - { - if (graticuleType == null) - { + public Color getLabelColor(String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -516,23 +479,20 @@ public Color getLabelColor(String graticuleType) /** * Sets the label rendering color for the specified graticule. * - * @param color the label color for the specified graticule. + * @param color the label color for the specified graticule. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException ifcolor is null, if graticuleType is null, or if - * graticuleType is not a valid type. + * graticuleType is not a valid type. */ - public void setLabelColor(Color color, String graticuleType) - { - if (color == null) - { + public void setLabelColor(Color color, String graticuleType) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (graticuleType == null) - { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -544,30 +504,26 @@ public void setLabelColor(Color color, String graticuleType) /** * Sets the label rendering color for the specified graticules. * - * @param color the label color for the specified graticules. + * @param color the label color for the specified graticules. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException ifcolor is null, if graticuleType is null, or if - * graticuleType is not a valid type. + * graticuleType is not a valid type. */ - public void setLabelColor(Color color, Iterable graticuleType) - { - if (color == null) - { + public void setLabelColor(Color color, Iterable graticuleType) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (graticuleType == null) - { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (String type : graticuleType) - { + for (String type : graticuleType) { setLabelColor(color, type); } } @@ -579,18 +535,15 @@ public void setLabelColor(Color color, Iterable graticuleType) * * @throws IllegalArgumentException if color is null. */ - public void setLabelColor(Color color) - { - if (color == null) - { + public void setLabelColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { setLabelColor(color, type); } } @@ -599,17 +552,15 @@ public void setLabelColor(Color color) * Returns the label font of the specified graticule. * * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @return Font of the graticule label. * * @throws IllegalArgumentException if graticuleType is null, or if graticuleType is not a - * valid type. + * valid type. */ - public Font getLabelFont(String graticuleType) - { - if (graticuleType == null) - { + public Font getLabelFont(String graticuleType) { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -621,23 +572,20 @@ public Font getLabelFont(String graticuleType) /** * Sets the label rendering font for the specified graticule. * - * @param font the label font for the specified graticule. + * @param font the label font for the specified graticule. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException iffont is null, if graticuleType is null, or if - * graticuleType is not a valid type. + * graticuleType is not a valid type. */ - public void setLabelFont(Font font, String graticuleType) - { - if (font == null) - { + public void setLabelFont(Font font, String graticuleType) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (graticuleType == null) - { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -649,30 +597,26 @@ public void setLabelFont(Font font, String graticuleType) /** * Sets the label rendering font for the specified graticules. * - * @param font the label font for the specified graticules. + * @param font the label font for the specified graticules. * @param graticuleType one of GRATICULE_UTM, GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, - * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. + * GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, or GRATICULE_1M. * * @throws IllegalArgumentException iffont is null, if graticuleType is null, or if - * graticuleType is not a valid type. + * graticuleType is not a valid type. */ - public void setLabelFont(Font font, Iterable graticuleType) - { - if (font == null) - { + public void setLabelFont(Font font, Iterable graticuleType) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (graticuleType == null) - { + if (graticuleType == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (String type : graticuleType) - { + for (String type : graticuleType) { setLabelFont(font, type); } } @@ -684,24 +628,20 @@ public void setLabelFont(Font font, Iterable graticuleType) * * @throws IllegalArgumentException if font is null. */ - public void setLabelFont(Font font) - { - if (font == null) - { + public void setLabelFont(Font font) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { setLabelFont(font, type); } } - protected void initRenderingParams() - { + protected void initRenderingParams() { GraticuleRenderingParams params; // UTM graticule params = new GraticuleRenderingParams(); @@ -742,24 +682,20 @@ protected void initRenderingParams() setRenderingParams(GRATICULE_1M, params); } - protected String[] getOrderedTypes() - { - return new String[] { + protected String[] getOrderedTypes() { + return new String[]{ GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, - GRATICULE_1M, - }; + GRATICULE_1M,}; } - protected String getTypeFor(int resolution) - { + protected String getTypeFor(int resolution) { String graticuleType = null; - switch (resolution) - { + switch (resolution) { case 100000: // 100,000 meters graticuleType = GRATICULE_100000M; break; @@ -784,9 +720,7 @@ protected String getTypeFor(int resolution) } // --- Renderable layer -------------------------------------------------------------- - - protected void clear(DrawContext dc) - { + protected void clear(DrawContext dc) { super.clear(dc); this.frameCount++; @@ -796,93 +730,82 @@ protected void clear(DrawContext dc) this.metricScaleSupport.computeZone(dc); } - private void applyTerrainConformance() - { + private void applyTerrainConformance() { String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { getRenderingParams(type).setValue( - GraticuleRenderingParams.KEY_LINE_CONFORMANCE, this.terrainConformance); + GraticuleRenderingParams.KEY_LINE_CONFORMANCE, this.terrainConformance); } } - protected Sector computeVisibleSector(DrawContext dc) - { + protected Sector computeVisibleSector(DrawContext dc) { return dc.getVisibleSector(); } - protected void selectRenderables(DrawContext dc) - { - if (dc.getView().getEyePosition().getElevation() <= this.zoneMaxAltitude) - { + protected void selectRenderables(DrawContext dc) { + if (dc.getView().getEyePosition().getElevation() <= this.zoneMaxAltitude) { this.selectMGRSRenderables(dc, this.computeVisibleSector(dc)); this.metricScaleSupport.selectRenderables(dc); - } - else - { + } else { super.selectRenderables(dc); } } - protected void selectMGRSRenderables(DrawContext dc, Sector vs) - { + protected void selectMGRSRenderables(DrawContext dc, Sector vs) { ArrayList zoneList = getVisibleZones(dc); - if (zoneList.size() > 0) - { - for (GridZone gz : zoneList) - { + if (zoneList.size() > 0) { + for (GridZone gz : zoneList) { // Select visible grid zones elements gz.selectRenderables(dc, vs, this); } } } - private ArrayList getVisibleZones(DrawContext dc) - { + private ArrayList getVisibleZones(DrawContext dc) { ArrayList zoneList = new ArrayList(); Sector vs = dc.getVisibleSector(); - if (vs != null) - { + if (vs != null) { // UTM Grid Rectangle2D gridRectangle = getGridRectangleForSector(vs); - if (gridRectangle != null) - { + if (gridRectangle != null) { for (int row = (int) gridRectangle.getY(); row <= gridRectangle.getY() + gridRectangle.getHeight(); - row++) - { + row++) { for (int col = (int) gridRectangle.getX(); col <= gridRectangle.getX() + gridRectangle.getWidth(); - col++) - { + col++) { if (row != 19 || (col != 31 && col != 33 && col != 35)) // ignore X32, 34 and 36 { - if (gridZones[row][col] == null) + if (gridZones[row][col] == null) { gridZones[row][col] = new GridZone(getGridSector(row, col)); - if (gridZones[row][col].isInView(dc)) + } + if (gridZones[row][col].isInView(dc)) { zoneList.add(gridZones[row][col]); - else + } else { gridZones[row][col].clearRenderables(); + } } } } } // Poles - if (vs.getMaxLatitude().degrees > 84) - { + if (vs.getMaxLatitude().degrees > 84) { // North pole - if (poleZones[2] == null) + if (poleZones[2] == null) { poleZones[2] = new GridZone(Sector.fromDegrees(84, 90, -180, 0)); // Y - if (poleZones[3] == null) + } + if (poleZones[3] == null) { poleZones[3] = new GridZone(Sector.fromDegrees(84, 90, 0, 180)); // Z + } zoneList.add(poleZones[2]); zoneList.add(poleZones[3]); } - if (vs.getMinLatitude().degrees < -80) - { + if (vs.getMinLatitude().degrees < -80) { // South pole - if (poleZones[0] == null) + if (poleZones[0] == null) { poleZones[0] = new GridZone(Sector.fromDegrees(-90, -80, -180, 0)); // B - if (poleZones[1] == null) + } + if (poleZones[1] == null) { poleZones[1] = new GridZone(Sector.fromDegrees(-90, -80, 0, 180)); // A + } zoneList.add(poleZones[0]); zoneList.add(poleZones[1]); } @@ -890,100 +813,109 @@ private ArrayList getVisibleZones(DrawContext dc) return zoneList; } - private Rectangle2D getGridRectangleForSector(Sector sector) - { + private Rectangle2D getGridRectangleForSector(Sector sector) { Rectangle2D rectangle = null; - if (sector.getMinLatitude().degrees < 84 && sector.getMaxLatitude().degrees > -80) - { + if (sector.getMinLatitude().degrees < 84 && sector.getMaxLatitude().degrees > -80) { Sector gridSector = Sector.fromDegrees( - Math.max(sector.getMinLatitude().degrees, -80), Math.min(sector.getMaxLatitude().degrees, 84), - sector.getMinLongitude().degrees, sector.getMaxLongitude().degrees); + Math.max(sector.getMinLatitude().degrees, -80), Math.min(sector.getMaxLatitude().degrees, 84), + sector.getMinLongitude().degrees, sector.getMaxLongitude().degrees); int x1 = getGridColumn(gridSector.getMinLongitude().degrees); int x2 = getGridColumn(gridSector.getMaxLongitude().degrees); int y1 = getGridRow(gridSector.getMinLatitude().degrees); int y2 = getGridRow(gridSector.getMaxLatitude().degrees); // Adjust rectangle to include special zones if (y1 <= 17 && y2 >= 17 && x2 == 30) // 32V Norway + { x2 = 31; + } if (y1 <= 19 && y2 >= 19) // X band { if (x1 == 31) // 31X + { x1 = 30; + } if (x2 == 31) // 33X + { x2 = 32; + } if (x1 == 33) // 33X + { x1 = 32; + } if (x2 == 33) // 35X + { x2 = 34; + } if (x1 == 35) // 35X + { x1 = 34; + } if (x2 == 35) // 37X + { x2 = 36; + } } rectangle = new Rectangle(x1, y1, x2 - x1, y2 - y1); } return rectangle; } - private int getGridColumn(Double longitude) - { + private int getGridColumn(Double longitude) { int col = (int) Math.floor((longitude + 180) / 6d); return Math.min(col, 59); } - private int getGridRow(Double latitude) - { + private int getGridRow(Double latitude) { int row = (int) Math.floor((latitude + 80) / 8d); return Math.min(row, 19); } - private Sector getGridSector(int row, int col) - { + private Sector getGridSector(int row, int col) { int minLat = -80 + row * 8; int maxLat = minLat + (minLat != 72 ? 8 : 12); int minLon = -180 + col * 6; int maxLon = minLon + 6; // Special sectors - if (row == 17 && col == 30) // 31V + if (row == 17 && col == 30) // 31V + { maxLon -= 3; - else if (row == 17 && col == 31) // 32V + } else if (row == 17 && col == 31) // 32V + { minLon -= 3; - else if (row == 19 && col == 30) // 31X + } else if (row == 19 && col == 30) // 31X + { maxLon += 3; - else if (row == 19 && col == 31) // 32X does not exist + } else if (row == 19 && col == 31) // 32X does not exist { minLon += 3; maxLon -= 3; - } - else if (row == 19 && col == 32) // 33X + } else if (row == 19 && col == 32) // 33X { minLon -= 3; maxLon += 3; - } - else if (row == 19 && col == 33) // 34X does not exist + } else if (row == 19 && col == 33) // 34X does not exist { minLon += 3; maxLon -= 3; - } - else if (row == 19 && col == 34) // 35X + } else if (row == 19 && col == 34) // 35X { minLon -= 3; maxLon += 3; - } - else if (row == 19 && col == 35) // 36X does not exist + } else if (row == 19 && col == 35) // 36X does not exist { minLon += 3; maxLon -= 3; - } - else if (row == 19 && col == 36) // 37X + } else if (row == 19 && col == 36) // 37X + { minLon -= 3; + } return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); } - private boolean isNorthNeighborInView(GridZone gz, DrawContext dc) - { - if (gz.isUPS) + private boolean isNorthNeighborInView(GridZone gz, DrawContext dc) { + if (gz.isUPS) { return true; + } int row = getGridRow(gz.sector.getCentroid().getLatitude().degrees); int col = getGridColumn(gz.sector.getCentroid().getLongitude().degrees); @@ -991,10 +923,10 @@ private boolean isNorthNeighborInView(GridZone gz, DrawContext dc) return neighbor != null && neighbor.isInView(dc); } - private boolean isEastNeighborInView(GridZone gz, DrawContext dc) - { - if (gz.isUPS) + private boolean isEastNeighborInView(GridZone gz, DrawContext dc) { + if (gz.isUPS) { return true; + } int row = getGridRow(gz.sector.getCentroid().getLatitude().degrees); int col = getGridColumn(gz.sector.getCentroid().getLongitude().degrees); @@ -1003,10 +935,11 @@ private boolean isEastNeighborInView(GridZone gz, DrawContext dc) } //--- Grid zone ---------------------------------------------------------------------- + /** + * Represent a UTM zone / latitude band intersection + */ + private class GridZone { - /** Represent a UTM zone / latitude band intersection */ - private class GridZone - { private static final double ONEHT = 100e3; private static final double TWOMIL = 2e6; @@ -1019,92 +952,79 @@ private class GridZone private ArrayList gridElements; private ArrayList squares; - public GridZone(Sector sector) - { + public GridZone(Sector sector) { this.sector = sector; this.isUPS = (sector.getMaxLatitude().degrees > UTM_MAX_LATITUDE - || sector.getMinLatitude().degrees < UTM_MIN_LATITUDE); - try - { + || sector.getMinLatitude().degrees < UTM_MIN_LATITUDE); + try { MGRSCoord MGRS = MGRSCoord.fromLatLon(sector.getCentroid().getLatitude(), - sector.getCentroid().getLongitude(), globe); - if (this.isUPS) - { + sector.getCentroid().getLongitude(), globe); + if (this.isUPS) { this.name = MGRS.toString().substring(2, 3); this.hemisphere = sector.getMinLatitude().degrees > 0 ? AVKey.NORTH : AVKey.SOUTH; - } - else - { + } else { this.name = MGRS.toString().substring(0, 3); UTMCoord UTM = UTMCoord.fromLatLon(sector.getCentroid().getLatitude(), - sector.getCentroid().getLongitude(), globe); + sector.getCentroid().getLongitude(), globe); this.UTMZone = UTM.getZone(); this.hemisphere = UTM.getHemisphere(); } - } - catch (IllegalArgumentException ignore) - { + } catch (IllegalArgumentException ignore) { } } - public Extent getExtent(Globe globe, double ve) - { + public Extent getExtent(Globe globe, double ve) { return Sector.computeBoundingCylinder(globe, ve, this.sector); } - public boolean isInView(DrawContext dc) - { + public boolean isInView(DrawContext dc) { return dc.getView().getFrustumInModelCoordinates().intersects( - this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration())); + this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration())); } - public void selectRenderables(DrawContext dc, Sector vs, MGRSGraticuleLayer layer) - { + public void selectRenderables(DrawContext dc, Sector vs, MGRSGraticuleLayer layer) { // Select zone elements - if (this.gridElements == null) + if (this.gridElements == null) { createRenderables(); + } - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc, vs)) - { - if (ge.type.equals(GridElement.TYPE_LINE_NORTH) && isNorthNeighborInView(this, dc)) + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc, vs)) { + if (ge.type.equals(GridElement.TYPE_LINE_NORTH) && isNorthNeighborInView(this, dc)) { continue; - if (ge.type.equals(GridElement.TYPE_LINE_EAST) && isEastNeighborInView(this, dc)) + } + if (ge.type.equals(GridElement.TYPE_LINE_EAST) && isEastNeighborInView(this, dc)) { continue; + } layer.addRenderable(ge.renderable, GRATICULE_UTM_GRID); } } - if (dc.getView().getEyePosition().getElevation() > MGRSGraticuleLayer.this.squareMaxAltitude) + if (dc.getView().getEyePosition().getElevation() > MGRSGraticuleLayer.this.squareMaxAltitude) { return; + } // Select 100km squares elements - if (this.squares == null) + if (this.squares == null) { createSquares(); - for (SquareZone sz : this.squares) - { - if (sz.isInView(dc)) - { + } + for (SquareZone sz : this.squares) { + if (sz.isInView(dc)) { sz.selectRenderables(dc, vs); - } - else + } else { sz.clearRenderables(); + } } } - public void clearRenderables() - { - if (this.gridElements != null) - { + public void clearRenderables() { + if (this.gridElements != null) { this.gridElements.clear(); this.gridElements = null; } - if (this.squares != null) - { - for (SquareZone sz : this.squares) - { + if (this.squares != null) { + for (SquareZone sz : this.squares) { sz.clearRenderables(); } this.squares.clear(); @@ -1112,25 +1032,23 @@ public void clearRenderables() } } - private void createSquares() - { - if (this.isUPS) + private void createSquares() { + if (this.isUPS) { createSquaresUPS(); - else + } else { createSquaresUTM(); + } } - private void createSquaresUTM() - { - try - { + private void createSquaresUTM() { + try { // Find grid zone easting and northing boundaries UTMCoord UTM; UTM = UTMCoord.fromLatLon(this.sector.getMinLatitude(), this.sector.getCentroid().getLongitude(), - globe); + globe); double minNorthing = UTM.getNorthing(); UTM = UTMCoord.fromLatLon(this.sector.getMaxLatitude(), this.sector.getCentroid().getLongitude(), - globe); + globe); double maxNorthing = UTM.getNorthing(); maxNorthing = maxNorthing == 0 ? 10e6 : maxNorthing; UTM = UTMCoord.fromLatLon(this.sector.getMinLatitude(), this.sector.getMinLongitude(), globe); @@ -1141,33 +1059,32 @@ private void createSquaresUTM() // Compensate for some distorted zones if (this.name.equals("32V")) // catch KS and LS in 32V + { maxNorthing += 20e3; + } if (this.name.equals("31X")) // catch GA and GV in 31X + { maxEasting += ONEHT; + } // Create squares this.squares = createSquaresGrid(this.UTMZone, this.hemisphere, this.sector, minEasting, maxEasting, - minNorthing, maxNorthing); + minNorthing, maxNorthing); this.setSquareNames(); - } - catch (IllegalArgumentException ignore) - { + } catch (IllegalArgumentException ignore) { } } - private void createSquaresUPS() - { + private void createSquaresUPS() { this.squares = new ArrayList(); double minEasting, maxEasting, minNorthing, maxNorthing; - if (AVKey.NORTH.equals(this.hemisphere)) - { + if (AVKey.NORTH.equals(this.hemisphere)) { minNorthing = TWOMIL - ONEHT * 7; maxNorthing = TWOMIL + ONEHT * 7; minEasting = this.name.equals("Y") ? TWOMIL - ONEHT * 7 : TWOMIL; maxEasting = this.name.equals("Y") ? TWOMIL : TWOMIL + ONEHT * 7; - } - else // AVKey.SOUTH.equals(this.hemisphere) + } else // AVKey.SOUTH.equals(this.hemisphere) { minNorthing = TWOMIL - ONEHT * 12; maxNorthing = TWOMIL + ONEHT * 12; @@ -1177,54 +1094,49 @@ private void createSquaresUPS() // Create squares this.squares = createSquaresGrid(this.UTMZone, this.hemisphere, this.sector, minEasting, maxEasting, - minNorthing, maxNorthing); + minNorthing, maxNorthing); this.setSquareNames(); } - private void setSquareNames() - { - for (SquareZone sz : this.squares) - { + private void setSquareNames() { + for (SquareZone sz : this.squares) { this.setSquareName(sz); } } - private void setSquareName(SquareZone sz) - { + private void setSquareName(SquareZone sz) { // Find out MGRS 100Km square name double tenMeterRadian = 10d / 6378137d; - try - { + try { MGRSCoord MGRS = null; - if (sz.centroid != null && sz.isPositionInside(new Position(sz.centroid, 0))) + if (sz.centroid != null && sz.isPositionInside(new Position(sz.centroid, 0))) { MGRS = MGRSCoord.fromLatLon(sz.centroid.latitude, sz.centroid.longitude, globe); - else if (sz.isPositionInside(sz.sw)) + } else if (sz.isPositionInside(sz.sw)) { MGRS = MGRSCoord.fromLatLon( - Angle.fromRadiansLatitude(sz.sw.getLatitude().radians + tenMeterRadian), - Angle.fromRadiansLongitude(sz.sw.getLongitude().radians + tenMeterRadian), globe); - else if (sz.isPositionInside(sz.se)) + Angle.fromRadiansLatitude(sz.sw.getLatitude().radians + tenMeterRadian), + Angle.fromRadiansLongitude(sz.sw.getLongitude().radians + tenMeterRadian), globe); + } else if (sz.isPositionInside(sz.se)) { MGRS = MGRSCoord.fromLatLon( - Angle.fromRadiansLatitude(sz.se.getLatitude().radians + tenMeterRadian), - Angle.fromRadiansLongitude(sz.se.getLongitude().radians - tenMeterRadian), globe); - else if (sz.isPositionInside(sz.nw)) + Angle.fromRadiansLatitude(sz.se.getLatitude().radians + tenMeterRadian), + Angle.fromRadiansLongitude(sz.se.getLongitude().radians - tenMeterRadian), globe); + } else if (sz.isPositionInside(sz.nw)) { MGRS = MGRSCoord.fromLatLon( - Angle.fromRadiansLatitude(sz.nw.getLatitude().radians - tenMeterRadian), - Angle.fromRadiansLongitude(sz.nw.getLongitude().radians + tenMeterRadian), globe); - else if (sz.isPositionInside(sz.ne)) + Angle.fromRadiansLatitude(sz.nw.getLatitude().radians - tenMeterRadian), + Angle.fromRadiansLongitude(sz.nw.getLongitude().radians + tenMeterRadian), globe); + } else if (sz.isPositionInside(sz.ne)) { MGRS = MGRSCoord.fromLatLon( - Angle.fromRadiansLatitude(sz.ne.getLatitude().radians - tenMeterRadian), - Angle.fromRadiansLongitude(sz.ne.getLongitude().radians - tenMeterRadian), globe); + Angle.fromRadiansLatitude(sz.ne.getLatitude().radians - tenMeterRadian), + Angle.fromRadiansLongitude(sz.ne.getLongitude().radians - tenMeterRadian), globe); + } // Set square zone name - if (MGRS != null) + if (MGRS != null) { sz.setName(MGRS.toString().substring(3, 5)); - } - catch (IllegalArgumentException ignore) - { + } + } catch (IllegalArgumentException ignore) { } } - private void createRenderables() - { + private void createRenderables() { this.gridElements = new ArrayList(); ArrayList positions = new ArrayList(); @@ -1235,18 +1147,17 @@ private void createRenderables() positions.add(new Position(this.sector.getMaxLatitude(), this.sector.getMinLongitude(), 10e3)); Object polyline = createLineRenderable(new ArrayList(positions), AVKey.LINEAR); Sector lineSector = new Sector(this.sector.getMinLatitude(), this.sector.getMaxLatitude(), - this.sector.getMinLongitude(), this.sector.getMinLongitude()); + this.sector.getMinLongitude(), this.sector.getMinLongitude()); this.gridElements.add(new GridElement(lineSector, polyline, GridElement.TYPE_LINE_WEST)); - if (!this.isUPS) - { + if (!this.isUPS) { // right meridian segment positions.clear(); positions.add(new Position(this.sector.getMinLatitude(), this.sector.getMaxLongitude(), 10e3)); positions.add(new Position(this.sector.getMaxLatitude(), this.sector.getMaxLongitude(), 10e3)); polyline = createLineRenderable(new ArrayList(positions), AVKey.LINEAR); lineSector = new Sector(this.sector.getMinLatitude(), this.sector.getMaxLatitude(), - this.sector.getMaxLongitude(), this.sector.getMaxLongitude()); + this.sector.getMaxLongitude(), this.sector.getMaxLongitude()); this.gridElements.add(new GridElement(lineSector, polyline, GridElement.TYPE_LINE_EAST)); // bottom parallel segment @@ -1255,7 +1166,7 @@ private void createRenderables() positions.add(new Position(this.sector.getMinLatitude(), this.sector.getMaxLongitude(), 10e3)); polyline = createLineRenderable(new ArrayList(positions), AVKey.LINEAR); lineSector = new Sector(this.sector.getMinLatitude(), this.sector.getMinLatitude(), - this.sector.getMinLongitude(), this.sector.getMaxLongitude()); + this.sector.getMinLongitude(), this.sector.getMaxLongitude()); this.gridElements.add(new GridElement(lineSector, polyline, GridElement.TYPE_LINE_SOUTH)); // top parallel segment @@ -1264,7 +1175,7 @@ private void createRenderables() positions.add(new Position(this.sector.getMaxLatitude(), this.sector.getMaxLongitude(), 10e3)); polyline = createLineRenderable(new ArrayList(positions), AVKey.LINEAR); lineSector = new Sector(this.sector.getMaxLatitude(), this.sector.getMaxLatitude(), - this.sector.getMinLongitude(), this.sector.getMaxLongitude()); + this.sector.getMinLongitude(), this.sector.getMaxLongitude()); this.gridElements.add(new GridElement(lineSector, polyline, GridElement.TYPE_LINE_NORTH)); } diff --git a/src/gov/nasa/worldwind/layers/Earth/MSVirtualEarthLayer.java b/src/gov/nasa/worldwind/layers/Earth/MSVirtualEarthLayer.java index c701c72d04..8262e94916 100644 --- a/src/gov/nasa/worldwind/layers/Earth/MSVirtualEarthLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/MSVirtualEarthLayer.java @@ -13,36 +13,28 @@ * @author Patrick Murris * @version $Id: MSVirtualEarthLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MSVirtualEarthLayer extends BasicTiledImageLayer -{ +public class MSVirtualEarthLayer extends BasicTiledImageLayer { + public static final String LAYER_AERIAL = "gov.nasa.worldwind.layers.Earth.MSVirtualEarthLayer.Aerial"; public static final String LAYER_ROADS = "gov.nasa.worldwind.layers.Earth.MSVirtualEarthLayer.Roads"; public static final String LAYER_HYBRID = "gov.nasa.worldwind.layers.Earth.MSVirtualEarthLayer.Hybrid"; - public MSVirtualEarthLayer(String layerName) - { + public MSVirtualEarthLayer(String layerName) { super(getConfigurationDocument(layerName), null); } - public MSVirtualEarthLayer() - { - this(LAYER_AERIAL); + public MSVirtualEarthLayer() { + this(LAYER_AERIAL); } - protected static Document getConfigurationDocument(String layerName) - { + protected static Document getConfigurationDocument(String layerName) { String filePath; - if (layerName != null && layerName.equals(LAYER_HYBRID)) - { + if (layerName != null && layerName.equals(LAYER_HYBRID)) { filePath = "config/Earth/MSVirtualEarthHybridLayer.xml"; - } - else if (layerName != null && layerName.equals(LAYER_ROADS)) - { + } else if (layerName != null && layerName.equals(LAYER_ROADS)) { filePath = "config/Earth/MSVirtualEarthRoadsLayer.xml"; - } - else - { + } else { // Default to MS Virtual Earth Aerial. filePath = "config/Earth/MSVirtualEarthAerialLayer.xml"; } diff --git a/src/gov/nasa/worldwind/layers/Earth/NASAWFSPlaceNameLayer.java b/src/gov/nasa/worldwind/layers/Earth/NASAWFSPlaceNameLayer.java index 42c81de083..778c66a7db 100644 --- a/src/gov/nasa/worldwind/layers/Earth/NASAWFSPlaceNameLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/NASAWFSPlaceNameLayer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers.Earth; import gov.nasa.worldwind.geom.Angle; @@ -22,47 +21,45 @@ public class NASAWFSPlaceNameLayer extends PlaceNameLayer { //String constants for name sets - public static final String OCEANS="topp:wpl_oceans"; - public static final String CONTINENTS="topp:wpl_continents"; - public static final String WATERBODIES="topp:wpl_waterbodies"; - public static final String TRENCHESRIDGES="topp:wpl_trenchesridges"; - public static final String DESERTSPLAINS="topp:wpl_desertsplains"; - public static final String LAKESRIVERS="topp:wpl_lakesrivers"; - public static final String MOUNTAINSVALLEYS="topp:wpl_mountainsvalleys"; - public static final String COUNTRIES="topp:wpl_countries"; - public static final String GEONET_P_PPC="topp:wpl_geonet_p_pplc"; - public static final String CITIESOVER500K="topp:citiesover500k"; - public static final String CITIESOVER100K="topp:citiesover100k"; - public static final String CITIESOVER50K="topp:citiesover50k"; - public static final String CITIESOVER10K="topp:citiesover10k"; - public static final String CITIESOVER1K="topp:citiesover1k"; - public static final String USCITIESOVER0="topp:wpl_uscitiesover0"; - public static final String USCITIES0="topp:wpl_uscities0"; - public static final String US_ANTHROPOGENIC="topp:wpl_us_anthropogenic"; - public static final String US_WATER="topp:wpl_us_water"; - public static final String US_TERRAIN="topp:wpl_us_terrain"; - public static final String GEONET_A_ADM1="topp:wpl_geonet_a_adm1"; - public static final String GEONET_A_ADM2="topp:wpl_geonet_a_adm2"; - public static final String GEONET_P_PPLA="topp:wpl_geonet_p_ppla"; - public static final String GEONET_P_PPL="topp:wpl_geonet_p_ppl"; - public static final String GEONET_P_PPLC="topp:wpl_geonet_p_pplC"; - + public static final String OCEANS = "topp:wpl_oceans"; + public static final String CONTINENTS = "topp:wpl_continents"; + public static final String WATERBODIES = "topp:wpl_waterbodies"; + public static final String TRENCHESRIDGES = "topp:wpl_trenchesridges"; + public static final String DESERTSPLAINS = "topp:wpl_desertsplains"; + public static final String LAKESRIVERS = "topp:wpl_lakesrivers"; + public static final String MOUNTAINSVALLEYS = "topp:wpl_mountainsvalleys"; + public static final String COUNTRIES = "topp:wpl_countries"; + public static final String GEONET_P_PPC = "topp:wpl_geonet_p_pplc"; + public static final String CITIESOVER500K = "topp:citiesover500k"; + public static final String CITIESOVER100K = "topp:citiesover100k"; + public static final String CITIESOVER50K = "topp:citiesover50k"; + public static final String CITIESOVER10K = "topp:citiesover10k"; + public static final String CITIESOVER1K = "topp:citiesover1k"; + public static final String USCITIESOVER0 = "topp:wpl_uscitiesover0"; + public static final String USCITIES0 = "topp:wpl_uscities0"; + public static final String US_ANTHROPOGENIC = "topp:wpl_us_anthropogenic"; + public static final String US_WATER = "topp:wpl_us_water"; + public static final String US_TERRAIN = "topp:wpl_us_terrain"; + public static final String GEONET_A_ADM1 = "topp:wpl_geonet_a_adm1"; + public static final String GEONET_A_ADM2 = "topp:wpl_geonet_a_adm2"; + public static final String GEONET_P_PPLA = "topp:wpl_geonet_p_ppla"; + public static final String GEONET_P_PPL = "topp:wpl_geonet_p_ppl"; + public static final String GEONET_P_PPLC = "topp:wpl_geonet_p_pplC"; - private static final String[] allNameSets={OCEANS, CONTINENTS, WATERBODIES, TRENCHESRIDGES, DESERTSPLAINS, LAKESRIVERS, - MOUNTAINSVALLEYS, COUNTRIES, GEONET_P_PPC, CITIESOVER500K, CITIESOVER100K, - CITIESOVER50K, CITIESOVER10K, CITIESOVER1K, USCITIESOVER0,USCITIES0, - US_ANTHROPOGENIC, US_WATER, US_TERRAIN, GEONET_A_ADM1, GEONET_A_ADM2, - GEONET_P_PPLA, GEONET_P_PPL}; + private static final String[] allNameSets = {OCEANS, CONTINENTS, WATERBODIES, TRENCHESRIDGES, DESERTSPLAINS, LAKESRIVERS, + MOUNTAINSVALLEYS, COUNTRIES, GEONET_P_PPC, CITIESOVER500K, CITIESOVER100K, + CITIESOVER50K, CITIESOVER10K, CITIESOVER1K, USCITIESOVER0, USCITIES0, + US_ANTHROPOGENIC, US_WATER, US_TERRAIN, GEONET_A_ADM1, GEONET_A_ADM2, + GEONET_P_PPLA, GEONET_P_PPL}; private static List activeNamesList = Arrays.asList(allNameSets); - + public NASAWFSPlaceNameLayer() { super(makePlaceNameServiceSet()); } - public void setPlaceNameSetsVisible(List names) - { - activeNamesList=names; + public void setPlaceNameSetsVisible(List names) { + activeNamesList = names; makePlaceNameServiceSet(); } @@ -72,7 +69,7 @@ private static PlaceNameServiceSet makePlaceNameServiceSet() { PlaceNameServiceSet placeNameServiceSet = new PlaceNameServiceSet(); placeNameServiceSet.setExpiryTime(new GregorianCalendar(2008, 1, 11).getTimeInMillis()); PlaceNameService placeNameService; - final boolean addVersionTag=true; //true if pointing to a new wfs server + final boolean addVersionTag = true; //true if pointing to a new wfs server // Oceans if (activeNamesList.contains(OCEANS)) { placeNameService = new PlaceNameService(service, "topp:wpl_oceans", fileCachePath, Sector.FULL_SPHERE, GRID_1x1, @@ -92,7 +89,7 @@ private static PlaceNameServiceSet makePlaceNameServiceSet() { placeNameServiceSet.addService(placeNameService, false); } - // Water Bodies + // Water Bodies if (activeNamesList.contains(WATERBODIES)) { placeNameService = new PlaceNameService(service, "topp:wpl_waterbodies", fileCachePath, Sector.FULL_SPHERE, GRID_4x8, java.awt.Font.decode("Arial-ITALIC-10"), addVersionTag); @@ -149,7 +146,7 @@ private static PlaceNameServiceSet makePlaceNameServiceSet() { // GeoNet World Capitals if (activeNamesList.contains(GEONET_P_PPLC)) { placeNameService = new PlaceNameService(service, "topp:wpl_geonet_p_pplc", fileCachePath, Sector.FULL_SPHERE, - GRID_16x32, java.awt.Font.decode("Arial-BOLD-10"), addVersionTag); + GRID_16x32, java.awt.Font.decode("Arial-BOLD-10"), addVersionTag); placeNameService.setColor(java.awt.Color.yellow); placeNameService.setMinDisplayDistance(0d); placeNameService.setMaxDisplayDistance(LEVEL_D); @@ -244,7 +241,7 @@ private static PlaceNameServiceSet makePlaceNameServiceSet() { placeNameService.setMaxDisplayDistance(LEVEL_M); placeNameServiceSet.addService(placeNameService, false); } - // US Terrain Features + // US Terrain Features if (activeNamesList.contains(US_TERRAIN)) { placeNameService = new PlaceNameService(service, "topp:wpl_us_terrain", fileCachePath, Sector.FULL_SPHERE, GRID_72x144, java.awt.Font.decode("Arial-PLAIN-10"), addVersionTag); diff --git a/src/gov/nasa/worldwind/layers/Earth/OSMCycleMapLayer.java b/src/gov/nasa/worldwind/layers/Earth/OSMCycleMapLayer.java index 6e85210c2e..553e901de1 100644 --- a/src/gov/nasa/worldwind/layers/Earth/OSMCycleMapLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/OSMCycleMapLayer.java @@ -15,47 +15,43 @@ /** * @version $Id: OSMCycleMapLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OSMCycleMapLayer extends BasicMercatorTiledImageLayer -{ - public OSMCycleMapLayer() - { - super(makeLevels()); +public class OSMCycleMapLayer extends BasicMercatorTiledImageLayer { + + public OSMCycleMapLayer() { + super(makeLevels()); + } + + private static LevelSet makeLevels() { + AVList params = new AVListImpl(); + + params.setValue(AVKey.TILE_WIDTH, 256); + params.setValue(AVKey.TILE_HEIGHT, 256); + params.setValue(AVKey.DATA_CACHE_NAME, "Earth/OSM-Mercator/OpenStreetMap Cycle"); + params.setValue(AVKey.SERVICE, "http://b.andy.sandbox.cloudmade.com/tiles/cycle/"); + params.setValue(AVKey.DATASET_NAME, "*"); + params.setValue(AVKey.FORMAT_SUFFIX, ".png"); + params.setValue(AVKey.NUM_LEVELS, 16); + params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); + params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, new LatLon(Angle + .fromDegrees(22.5d), Angle.fromDegrees(45d))); + params.setValue(AVKey.SECTOR, new MercatorSector(-1.0, 1.0, + Angle.NEG180, Angle.POS180)); + params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder()); + + return new LevelSet(params); } - private static LevelSet makeLevels() - { - AVList params = new AVListImpl(); - - params.setValue(AVKey.TILE_WIDTH, 256); - params.setValue(AVKey.TILE_HEIGHT, 256); - params.setValue(AVKey.DATA_CACHE_NAME, "Earth/OSM-Mercator/OpenStreetMap Cycle"); - params.setValue(AVKey.SERVICE, "http://b.andy.sandbox.cloudmade.com/tiles/cycle/"); - params.setValue(AVKey.DATASET_NAME, "*"); - params.setValue(AVKey.FORMAT_SUFFIX, ".png"); - params.setValue(AVKey.NUM_LEVELS, 16); - params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); - params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, new LatLon(Angle - .fromDegrees(22.5d), Angle.fromDegrees(45d))); - params.setValue(AVKey.SECTOR, new MercatorSector(-1.0, 1.0, - Angle.NEG180, Angle.POS180)); - params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder()); - - return new LevelSet(params); - } - - private static class URLBuilder implements TileUrlBuilder - { - public URL getURL(Tile tile, String imageFormat) - throws MalformedURLException - { - return new URL(tile.getLevel().getService() - + (tile.getLevelNumber() + 3) +"/"+ tile.getColumn()+"/"+ ((1 << (tile.getLevelNumber()) + 3) - 1 - tile.getRow()) + ".png"); - } - } - - @Override - public String toString() - { - return "OpenStreetMap Cycle"; - } + private static class URLBuilder implements TileUrlBuilder { + + public URL getURL(Tile tile, String imageFormat) + throws MalformedURLException { + return new URL(tile.getLevel().getService() + + (tile.getLevelNumber() + 3) + "/" + tile.getColumn() + "/" + ((1 << (tile.getLevelNumber()) + 3) - 1 - tile.getRow()) + ".png"); + } + } + + @Override + public String toString() { + return "OpenStreetMap Cycle"; + } } diff --git a/src/gov/nasa/worldwind/layers/Earth/OSMMapnikLayer.java b/src/gov/nasa/worldwind/layers/Earth/OSMMapnikLayer.java index 94c56d1069..f0e798b4be 100644 --- a/src/gov/nasa/worldwind/layers/Earth/OSMMapnikLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/OSMMapnikLayer.java @@ -15,15 +15,13 @@ /** * @version $Id: OSMMapnikLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OSMMapnikLayer extends BasicMercatorTiledImageLayer -{ - public OSMMapnikLayer() - { +public class OSMMapnikLayer extends BasicMercatorTiledImageLayer { + + public OSMMapnikLayer() { super(makeLevels()); } - private static LevelSet makeLevels() - { + private static LevelSet makeLevels() { AVList params = new AVListImpl(); params.setValue(AVKey.TILE_WIDTH, 256); @@ -35,27 +33,25 @@ private static LevelSet makeLevels() params.setValue(AVKey.NUM_LEVELS, 16); params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, new LatLon(Angle - .fromDegrees(22.5d), Angle.fromDegrees(45d))); + .fromDegrees(22.5d), Angle.fromDegrees(45d))); params.setValue(AVKey.SECTOR, new MercatorSector(-1.0, 1.0, Angle.NEG180, Angle.POS180)); params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder()); return new LevelSet(params); } - private static class URLBuilder implements TileUrlBuilder - { + private static class URLBuilder implements TileUrlBuilder { + public URL getURL(Tile tile, String imageFormat) - throws MalformedURLException - { + throws MalformedURLException { return new URL(tile.getLevel().getService() - + (tile.getLevelNumber() + 3) + "/" + tile.getColumn() + "/" - + ((1 << (tile.getLevelNumber()) + 3) - 1 - tile.getRow()) + ".png"); + + (tile.getLevelNumber() + 3) + "/" + tile.getColumn() + "/" + + ((1 << (tile.getLevelNumber()) + 3) - 1 - tile.getRow()) + ".png"); } } @Override - public String toString() - { + public String toString() { return "OpenStreetMap"; } } diff --git a/src/gov/nasa/worldwind/layers/Earth/USDANAIPWMSImageLayer.java b/src/gov/nasa/worldwind/layers/Earth/USDANAIPWMSImageLayer.java index e00dfbb894..de5ca4a626 100644 --- a/src/gov/nasa/worldwind/layers/Earth/USDANAIPWMSImageLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/USDANAIPWMSImageLayer.java @@ -14,23 +14,18 @@ * @author garakl * @version $Id: USDANAIPWMSImageLayer.java 2257 2014-08-22 18:02:19Z tgaskins $ */ +public class USDANAIPWMSImageLayer extends WMSTiledImageLayer { -public class USDANAIPWMSImageLayer extends WMSTiledImageLayer -{ - public USDANAIPWMSImageLayer() - { + public USDANAIPWMSImageLayer() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/USDANAIPWMSImageLayer.xml", null); } - public String toString() - { + public String toString() { Object o = this.getStringValue(AVKey.DISPLAY_NAME); return o != null ? (String) o : "USDA FSA Imagery"; } } - diff --git a/src/gov/nasa/worldwind/layers/Earth/USGSDigitalOrtho.java b/src/gov/nasa/worldwind/layers/Earth/USGSDigitalOrtho.java index ec67bab8f1..85d1fa7e94 100644 --- a/src/gov/nasa/worldwind/layers/Earth/USGSDigitalOrtho.java +++ b/src/gov/nasa/worldwind/layers/Earth/USGSDigitalOrtho.java @@ -13,15 +13,13 @@ * @author tag * @version $Id: USGSDigitalOrtho.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class USGSDigitalOrtho extends BasicTiledImageLayer -{ - public USGSDigitalOrtho() - { +public class USGSDigitalOrtho extends BasicTiledImageLayer { + + public USGSDigitalOrtho() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/USGSDigitalOrthoLayer.xml", null); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/USGSTopoHighRes.java b/src/gov/nasa/worldwind/layers/Earth/USGSTopoHighRes.java index c337a53d92..0224a700f3 100644 --- a/src/gov/nasa/worldwind/layers/Earth/USGSTopoHighRes.java +++ b/src/gov/nasa/worldwind/layers/Earth/USGSTopoHighRes.java @@ -13,15 +13,13 @@ * @author tag * @version $Id: USGSTopoHighRes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class USGSTopoHighRes extends WMSTiledImageLayer -{ - public USGSTopoHighRes() - { +public class USGSTopoHighRes extends WMSTiledImageLayer { + + public USGSTopoHighRes() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/USGSTopoHighResLayer.xml", null); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/USGSTopoLowRes.java b/src/gov/nasa/worldwind/layers/Earth/USGSTopoLowRes.java index d8fbe56e4d..5d05604ef5 100644 --- a/src/gov/nasa/worldwind/layers/Earth/USGSTopoLowRes.java +++ b/src/gov/nasa/worldwind/layers/Earth/USGSTopoLowRes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers.Earth; import gov.nasa.worldwind.util.WWXML; @@ -14,15 +13,13 @@ * @author tag * @version $Id: USGSTopoLowRes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class USGSTopoLowRes extends WMSTiledImageLayer -{ - public USGSTopoLowRes() - { +public class USGSTopoLowRes extends WMSTiledImageLayer { + + public USGSTopoLowRes() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/USGSTopoLowResLayer.xml", null); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/USGSTopoMedRes.java b/src/gov/nasa/worldwind/layers/Earth/USGSTopoMedRes.java index 013f5c1edc..11100baecb 100644 --- a/src/gov/nasa/worldwind/layers/Earth/USGSTopoMedRes.java +++ b/src/gov/nasa/worldwind/layers/Earth/USGSTopoMedRes.java @@ -13,15 +13,13 @@ * @author tag * @version $Id: USGSTopoMedRes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class USGSTopoMedRes extends WMSTiledImageLayer -{ - public USGSTopoMedRes() - { +public class USGSTopoMedRes extends WMSTiledImageLayer { + + public USGSTopoMedRes() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/USGSTopoMedResLayer.xml", null); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/USGSUrbanAreaOrtho.java b/src/gov/nasa/worldwind/layers/Earth/USGSUrbanAreaOrtho.java index e30a5ea089..861a8adfdb 100644 --- a/src/gov/nasa/worldwind/layers/Earth/USGSUrbanAreaOrtho.java +++ b/src/gov/nasa/worldwind/layers/Earth/USGSUrbanAreaOrtho.java @@ -13,15 +13,13 @@ * @author tag * @version $Id: USGSUrbanAreaOrtho.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class USGSUrbanAreaOrtho extends BasicTiledImageLayer -{ - public USGSUrbanAreaOrtho() - { +public class USGSUrbanAreaOrtho extends BasicTiledImageLayer { + + public USGSUrbanAreaOrtho() { super(getConfigurationDocument(), null); } - protected static Document getConfigurationDocument() - { + protected static Document getConfigurationDocument() { return WWXML.openDocumentFile("config/Earth/USGSUrbanAreaOrthoLayer.xml", null); } } diff --git a/src/gov/nasa/worldwind/layers/Earth/UTMBaseGraticuleLayer.java b/src/gov/nasa/worldwind/layers/Earth/UTMBaseGraticuleLayer.java index 238e5a7935..1b68e0ec62 100644 --- a/src/gov/nasa/worldwind/layers/Earth/UTMBaseGraticuleLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/UTMBaseGraticuleLayer.java @@ -24,8 +24,8 @@ * @author Patrick Murris * @version $Id: UTMBaseGraticuleLayer.java 2153 2014-07-17 17:33:13Z tgaskins $ */ -public class UTMBaseGraticuleLayer extends AbstractGraticuleLayer -{ +public class UTMBaseGraticuleLayer extends AbstractGraticuleLayer { + public static final String GRATICULE_UTM = "Graticule.UTM"; protected static final double ONEHT = 100e3; @@ -40,8 +40,7 @@ public class UTMBaseGraticuleLayer extends AbstractGraticuleLayer // Latitude bands letters - from south to north private static final String latBands = "CDEFGHJKLMNPQRSTUVWX"; - public UTMBaseGraticuleLayer() - { + public UTMBaseGraticuleLayer() { createUTMRenderables(); initRenderingParams(); this.setPickEnabled(false); @@ -53,8 +52,7 @@ public UTMBaseGraticuleLayer() * * @return true if graticule lines will be rendered; false otherwise. */ - public boolean isDrawGraticule() - { + public boolean isDrawGraticule() { return getUTMRenderingParams().isDrawLines(); } @@ -63,8 +61,7 @@ public boolean isDrawGraticule() * * @param drawGraticule true to render graticule lines; false to disable rendering. */ - public void setDrawGraticule(boolean drawGraticule) - { + public void setDrawGraticule(boolean drawGraticule) { getUTMRenderingParams().setDrawLines(drawGraticule); } @@ -73,8 +70,7 @@ public void setDrawGraticule(boolean drawGraticule) * * @return Color used to render graticule lines. */ - public Color getGraticuleLineColor() - { + public Color getGraticuleLineColor() { return getUTMRenderingParams().getLineColor(); } @@ -85,10 +81,8 @@ public Color getGraticuleLineColor() * * @throws IllegalArgumentException if color is null. */ - public void setGraticuleLineColor(Color color) - { - if (color == null) - { + public void setGraticuleLineColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -102,8 +96,7 @@ public void setGraticuleLineColor(Color color) * * @return width of the graticule lines. */ - public double getGraticuleLineWidth() - { + public double getGraticuleLineWidth() { return getUTMRenderingParams().getLineWidth(); } @@ -112,8 +105,7 @@ public double getGraticuleLineWidth() * * @param lineWidth width of the graticule lines. */ - public void setGraticuleLineWidth(double lineWidth) - { + public void setGraticuleLineWidth(double lineWidth) { getUTMRenderingParams().setLineWidth(lineWidth); } @@ -122,8 +114,7 @@ public void setGraticuleLineWidth(double lineWidth) * * @return rendering style of the graticule lines. */ - public String getGraticuleLineStyle() - { + public String getGraticuleLineStyle() { return getUTMRenderingParams().getLineStyle(); } @@ -131,14 +122,12 @@ public String getGraticuleLineStyle() * Sets the graticule line rendering style. * * @param lineStyle rendering style of the graticule lines. One of LINE_STYLE_PLAIN, LINE_STYLE_DASHED, or - * LINE_STYLE_DOTTED. + * LINE_STYLE_DOTTED. * * @throws IllegalArgumentException if lineStyle is null. */ - public void setGraticuleLineStyle(String lineStyle) - { - if (lineStyle == null) - { + public void setGraticuleLineStyle(String lineStyle) { + if (lineStyle == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -152,8 +141,7 @@ public void setGraticuleLineStyle(String lineStyle) * * @return true if graticule labels will be rendered; false otherwise. */ - public boolean isDrawLabels() - { + public boolean isDrawLabels() { return getUTMRenderingParams().isDrawLabels(); } @@ -162,8 +150,7 @@ public boolean isDrawLabels() * * @param drawLabels true to render graticule labels; false to disable rendering. */ - public void setDrawLabels(boolean drawLabels) - { + public void setDrawLabels(boolean drawLabels) { getUTMRenderingParams().setDrawLabels(drawLabels); } @@ -172,8 +159,7 @@ public void setDrawLabels(boolean drawLabels) * * @return Color used to render graticule labels. */ - public Color getLabelColor() - { + public Color getLabelColor() { return getUTMRenderingParams().getLabelColor(); } @@ -184,10 +170,8 @@ public Color getLabelColor() * * @throws IllegalArgumentException if color is null. */ - public void setLabelColor(Color color) - { - if (color == null) - { + public void setLabelColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -201,8 +185,7 @@ public void setLabelColor(Color color) * * @return Font used to render graticule labels. */ - public Font getLabelFont() - { + public Font getLabelFont() { return getUTMRenderingParams().getLabelFont(); } @@ -213,10 +196,8 @@ public Font getLabelFont() * * @throws IllegalArgumentException if font is null. */ - public void setLabelFont(Font font) - { - if (font == null) - { + public void setLabelFont(Font font) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -226,14 +207,11 @@ public void setLabelFont(Font font) } // --- Graticule Rendering -------------------------------------------------------------- - - protected String getTypeFor(int resolution) - { + protected String getTypeFor(int resolution) { return GRATICULE_UTM; } - protected void initRenderingParams() - { + protected void initRenderingParams() { GraticuleRenderingParams params = new GraticuleRenderingParams(); params.setValue(GraticuleRenderingParams.KEY_LINE_COLOR, new Color(.8f, .8f, .8f, .5f)); params.setValue(GraticuleRenderingParams.KEY_LABEL_COLOR, new Color(1f, 1f, 1f, .8f)); @@ -242,8 +220,7 @@ protected void initRenderingParams() setRenderingParams(GRATICULE_UTM, params); } - private GraticuleRenderingParams getUTMRenderingParams() - { + private GraticuleRenderingParams getUTMRenderingParams() { return this.graticuleSupport.getRenderingParams(GRATICULE_UTM); } @@ -252,10 +229,8 @@ private GraticuleRenderingParams getUTMRenderingParams() * * @param dc the current DrawContext. */ - protected void selectRenderables(DrawContext dc) - { - if (dc == null) - { + protected void selectRenderables(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -265,33 +240,29 @@ protected void selectRenderables(DrawContext dc) // Compute labels offset from view center Position centerPos = view.getCenterPosition(); Double pixelSizeDegrees = Angle.fromRadians(view.computePixelSizeAtDistance(view.getZoom()) - / dc.getGlobe().getEquatorialRadius()).degrees; + / dc.getGlobe().getEquatorialRadius()).degrees; Double labelOffsetDegrees = pixelSizeDegrees * view.getViewport().getWidth() / 4; Position labelPos = Position.fromDegrees(centerPos.getLatitude().degrees - labelOffsetDegrees, - centerPos.getLongitude().degrees - labelOffsetDegrees, 0); + centerPos.getLongitude().degrees - labelOffsetDegrees, 0); Double labelLatDegrees = labelPos.getLatitude().normalizedLatitude().degrees; labelLatDegrees = Math.min(Math.max(labelLatDegrees, -76), 78); labelPos = new Position(Angle.fromDegrees(labelLatDegrees), labelPos.getLongitude().normalizedLongitude(), 0); - if (vs != null) - { - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc)) - { - if (ge.renderable instanceof GeographicText) - { + if (vs != null) { + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc)) { + if (ge.renderable instanceof GeographicText) { GeographicText gt = (GeographicText) ge.renderable; - if (labelPos.getLatitude().degrees < 72 || "*32*34*36*".indexOf("*" + gt.getText() + "*") == -1) - { + if (labelPos.getLatitude().degrees < 72 || "*32*34*36*".indexOf("*" + gt.getText() + "*") == -1) { // Adjust label position according to eye position Position pos = gt.getPosition(); - if (ge.type.equals(GridElement.TYPE_LATITUDE_LABEL)) + if (ge.type.equals(GridElement.TYPE_LATITUDE_LABEL)) { pos = Position.fromDegrees(pos.getLatitude().degrees, - labelPos.getLongitude().degrees, pos.getElevation()); - else if (ge.type.equals(GridElement.TYPE_LONGITUDE_LABEL)) + labelPos.getLongitude().degrees, pos.getElevation()); + } else if (ge.type.equals(GridElement.TYPE_LONGITUDE_LABEL)) { pos = Position.fromDegrees(labelPos.getLatitude().degrees, - pos.getLongitude().degrees, pos.getElevation()); + pos.getLongitude().degrees, pos.getElevation()); + } gt.setPosition(pos); } @@ -304,9 +275,10 @@ else if (ge.type.equals(GridElement.TYPE_LONGITUDE_LABEL)) } } - /** Create the graticule grid elements */ - private void createUTMRenderables() - { + /** + * Create the graticule grid elements + */ + private void createUTMRenderables() { this.gridElements = new ArrayList(); ArrayList positions = new ArrayList(); @@ -315,8 +287,7 @@ private void createUTMRenderables() int lon = -180; int zoneNumber = 1; int maxLat; - for (int i = 0; i < 60; i++) - { + for (int i = 0; i < 60; i++) { Angle longitude = Angle.fromDegrees(lon); // Meridian positions.clear(); @@ -325,23 +296,17 @@ private void createUTMRenderables() positions.add(new Position(Angle.fromDegrees(-30), longitude, 10e3)); positions.add(new Position(Angle.ZERO, longitude, 10e3)); positions.add(new Position(Angle.fromDegrees(30), longitude, 10e3)); - if (lon < 6 || lon > 36) - { + if (lon < 6 || lon > 36) { // 'regular' UTM meridians maxLat = 84; positions.add(new Position(Angle.fromDegrees(60), longitude, 10e3)); positions.add(new Position(Angle.fromDegrees(maxLat), longitude, 10e3)); - } - else - { + } else { // Exceptions: shorter meridians around and north-east of Norway - if (lon == 6) - { + if (lon == 6) { maxLat = 56; positions.add(new Position(Angle.fromDegrees(maxLat), longitude, 10e3)); - } - else - { + } else { maxLat = 72; positions.add(new Position(Angle.fromDegrees(60), longitude, 10e3)); positions.add(new Position(Angle.fromDegrees(maxLat), longitude, 10e3)); @@ -353,7 +318,7 @@ private void createUTMRenderables() // Zone label GeographicText text = new UserFacingText(zoneNumber + "", - Position.fromDegrees(0, lon + 3, 0)); + Position.fromDegrees(0, lon + 3, 0)); sector = Sector.fromDegrees(-90, 90, lon + 3, lon + 3); this.gridElements.add(new GridElement(sector, text, GridElement.TYPE_LONGITUDE_LABEL)); @@ -363,8 +328,7 @@ private void createUTMRenderables() } // Generate special meridian segments for exceptions around and north-east of Norway - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { positions.clear(); lon = specialMeridians[i][0]; positions.add(new Position(Angle.fromDegrees(specialMeridians[i][1]), Angle.fromDegrees(lon), 10e3)); @@ -376,11 +340,9 @@ private void createUTMRenderables() // Generate parallels - no exceptions int lat = -80; - for (int i = 0; i < 21; i++) - { + for (int i = 0; i < 21; i++) { Angle latitude = Angle.fromDegrees(lat); - for (int j = 0; j < 4; j++) - { + for (int j = 0; j < 4; j++) { // Each prallel is divided into four 90 degrees segments positions.clear(); lon = -180 + j * 90; @@ -393,10 +355,9 @@ private void createUTMRenderables() this.gridElements.add(new GridElement(sector, polyline, GridElement.TYPE_LINE)); } // Latitude band label - if (i < 20) - { + if (i < 20) { GeographicText text = new UserFacingText(latBands.charAt(i) + "", - Position.fromDegrees(lat + 4, 0, 0)); + Position.fromDegrees(lat + 4, 0, 0)); Sector sector = Sector.fromDegrees(lat + 4, lat + 4, -180, 180); this.gridElements.add(new GridElement(sector, text, GridElement.TYPE_LATITUDE_LABEL)); } @@ -407,46 +368,35 @@ private void createUTMRenderables() } //=== Support classes and methods ==================================================== - - protected Position computePosition(int zone, String hemisphere, double easting, double northing) - { - return zone > 0 ? - computePositionFromUTM(zone, hemisphere, easting, northing) : - computePositionFromUPS(hemisphere, easting, northing); + protected Position computePosition(int zone, String hemisphere, double easting, double northing) { + return zone > 0 + ? computePositionFromUTM(zone, hemisphere, easting, northing) + : computePositionFromUPS(hemisphere, easting, northing); } - protected Position computePositionFromUTM(int zone, String hemisphere, double easting, double northing) - { - try - { + protected Position computePositionFromUTM(int zone, String hemisphere, double easting, double northing) { + try { UTMCoord UTM = UTMCoord.fromUTM(zone, hemisphere, easting, northing, globe); return new Position(Angle.fromRadiansLatitude(UTM.getLatitude().radians), - Angle.fromRadiansLongitude(UTM.getLongitude().radians), 10e3); - } - catch (IllegalArgumentException e) - { + Angle.fromRadiansLongitude(UTM.getLongitude().radians), 10e3); + } catch (IllegalArgumentException e) { return null; } } - protected Position computePositionFromUPS(String hemisphere, double easting, double northing) - { - try - { + protected Position computePositionFromUPS(String hemisphere, double easting, double northing) { + try { UPSCoord UPS = UPSCoord.fromUPS(hemisphere, easting, northing, globe); return new Position(Angle.fromRadiansLatitude(UPS.getLatitude().radians), - Angle.fromRadiansLongitude(UPS.getLongitude().radians), 10e3); - } - catch (IllegalArgumentException e) - { + Angle.fromRadiansLongitude(UPS.getLongitude().radians), 10e3); + } catch (IllegalArgumentException e) { return null; } } //--- Metric scale support ----------------------------------------------------------- + protected class MetricScaleSupport { - protected class MetricScaleSupport - { private int zone; private double offsetFactorX = -.5; @@ -458,18 +408,16 @@ protected class MetricScaleSupport // 5 levels 100km to 10m UTMExtremes[] extremes; - private class UTMExtremes - { + private class UTMExtremes { + protected double minX, maxX, minY, maxY; protected String minYHemisphere, maxYHemisphere; - public UTMExtremes() - { + public UTMExtremes() { this.clear(); } - public void clear() - { + public void clear() { minX = 1e6; maxX = 0; minY = 10e6; @@ -479,98 +427,81 @@ public void clear() } } - public int getZone() - { + public int getZone() { return this.zone; } - public void setScaleModulo(int modulo) - { + public void setScaleModulo(int modulo) { this.scaleModulo = modulo; } - public void setMaxResolution(double resolutionInMeter) - { + public void setMaxResolution(double resolutionInMeter) { this.maxResolution = resolutionInMeter; this.clear(); } - public void computeZone(DrawContext dc) - { - try - { + public void computeZone(DrawContext dc) { + try { Position centerPos = ((OrbitView) dc.getView()).getCenterPosition(); - if (centerPos != null) - { + if (centerPos != null) { if (centerPos.latitude.degrees <= UTM_MAX_LATITUDE - && centerPos.latitude.degrees >= UTM_MIN_LATITUDE) - { + && centerPos.latitude.degrees >= UTM_MIN_LATITUDE) { UTMCoord UTM = UTMCoord.fromLatLon(centerPos.getLatitude(), centerPos.getLongitude(), - dc.getGlobe()); + dc.getGlobe()); this.zone = UTM.getZone(); - } - else + } else { this.zone = 0; + } } - } - catch (Exception ex) - { + } catch (Exception ex) { this.zone = 0; } } - public void clear() - { + public void clear() { int numLevels = (int) Math.log10(this.maxResolution); this.extremes = new UTMExtremes[numLevels]; - for (int i = 0; i < numLevels; i++) - { + for (int i = 0; i < numLevels; i++) { this.extremes[i] = new UTMExtremes(); this.extremes[i].clear(); } } - public void computeMetricScaleExtremes(int UTMZone, String hemisphere, GridElement ge, double size) - { - if (UTMZone != this.zone) + public void computeMetricScaleExtremes(int UTMZone, String hemisphere, GridElement ge, double size) { + if (UTMZone != this.zone) { return; - if (size < 1 || size > this.maxResolution) + } + if (size < 1 || size > this.maxResolution) { return; + } UTMExtremes levelExtremes = this.extremes[(int) Math.log10(size) - 1]; if (ge.type.equals(GridElement.TYPE_LINE_EASTING) - || ge.type.equals(GridElement.TYPE_LINE_EAST) - || ge.type.equals(GridElement.TYPE_LINE_WEST)) - { + || ge.type.equals(GridElement.TYPE_LINE_EAST) + || ge.type.equals(GridElement.TYPE_LINE_WEST)) { levelExtremes.minX = ge.value < levelExtremes.minX ? ge.value : levelExtremes.minX; levelExtremes.maxX = ge.value > levelExtremes.maxX ? ge.value : levelExtremes.maxX; - } - else if (ge.type.equals(GridElement.TYPE_LINE_NORTHING) - || ge.type.equals(GridElement.TYPE_LINE_SOUTH) - || ge.type.equals(GridElement.TYPE_LINE_NORTH)) - { - if (hemisphere.equals(levelExtremes.minYHemisphere)) + } else if (ge.type.equals(GridElement.TYPE_LINE_NORTHING) + || ge.type.equals(GridElement.TYPE_LINE_SOUTH) + || ge.type.equals(GridElement.TYPE_LINE_NORTH)) { + if (hemisphere.equals(levelExtremes.minYHemisphere)) { levelExtremes.minY = ge.value < levelExtremes.minY ? ge.value : levelExtremes.minY; - else if (hemisphere.equals(AVKey.SOUTH)) - { + } else if (hemisphere.equals(AVKey.SOUTH)) { levelExtremes.minY = ge.value; levelExtremes.minYHemisphere = hemisphere; } - if (hemisphere.equals(levelExtremes.maxYHemisphere)) + if (hemisphere.equals(levelExtremes.maxYHemisphere)) { levelExtremes.maxY = ge.value > levelExtremes.maxY ? ge.value : levelExtremes.maxY; - else if (hemisphere.equals(AVKey.NORTH)) - { + } else if (hemisphere.equals(AVKey.NORTH)) { levelExtremes.maxY = ge.value; levelExtremes.maxYHemisphere = hemisphere; } } } - public void selectRenderables(DrawContext dc) - { - try - { + public void selectRenderables(DrawContext dc) { + try { OrbitView view = (OrbitView) dc.getView(); // Compute easting and northing label offsets Double pixelSize = view.computePixelSizeAtDistance(view.getZoom()); @@ -581,23 +512,19 @@ public void selectRenderables(DrawContext dc) double labelEasting; double labelNorthing; String labelHemisphere; - if (this.zone > 0) - { + if (this.zone > 0) { UTMCoord UTM = UTMCoord.fromLatLon(centerPos.getLatitude(), centerPos.getLongitude(), - dc.getGlobe()); + dc.getGlobe()); labelEasting = UTM.getEasting() + eastingOffset; labelNorthing = UTM.getNorthing() + northingOffset; labelHemisphere = UTM.getHemisphere(); - if (labelNorthing < 0) - { + if (labelNorthing < 0) { labelNorthing = 10e6 + labelNorthing; labelHemisphere = AVKey.SOUTH; } - } - else - { + } else { UPSCoord UPS = UPSCoord.fromLatLon(centerPos.getLatitude(), centerPos.getLongitude(), - dc.getGlobe()); + dc.getGlobe()); labelEasting = UPS.getEasting() + eastingOffset; labelNorthing = UPS.getNorthing() + northingOffset; labelHemisphere = UPS.getHemisphere(); @@ -606,75 +533,61 @@ public void selectRenderables(DrawContext dc) Frustum viewFrustum = dc.getView().getFrustumInModelCoordinates(); Position labelPos; - for (int i = 0; i < this.extremes.length; i++) - { + for (int i = 0; i < this.extremes.length; i++) { UTMExtremes levelExtremes = this.extremes[i]; double gridStep = Math.pow(10, i); double gridStepTimesTen = gridStep * 10; String graticuleType = getTypeFor((int) gridStep); - if (levelExtremes.minX <= levelExtremes.maxX) - { + if (levelExtremes.minX <= levelExtremes.maxX) { // Process easting scale labels for this level - for (double easting = levelExtremes.minX; easting <= levelExtremes.maxX; easting += gridStep) - { + for (double easting = levelExtremes.minX; easting <= levelExtremes.maxX; easting += gridStep) { // Skip multiples of ten grid steps except for last (higher) level - if (i == this.extremes.length - 1 || easting % gridStepTimesTen != 0) - { - try - { + if (i == this.extremes.length - 1 || easting % gridStepTimesTen != 0) { + try { labelPos = computePosition(this.zone, labelHemisphere, easting, labelNorthing); - if (labelPos == null) + if (labelPos == null) { continue; + } Angle lat = labelPos.getLatitude(); Angle lon = labelPos.getLongitude(); Vec4 surfacePoint = getSurfacePoint(dc, lat, lon); - if (viewFrustum.contains(surfacePoint) && isPointInRange(dc, surfacePoint)) - { + if (viewFrustum.contains(surfacePoint) && isPointInRange(dc, surfacePoint)) { String text = String.valueOf((int) (easting % this.scaleModulo)); GeographicText gt = new UserFacingText(text, new Position(lat, lon, 0)); gt.setPriority(gridStepTimesTen); addRenderable(gt, graticuleType); } - } - catch (IllegalArgumentException ignore) - { + } catch (IllegalArgumentException ignore) { } } } } - if (!(levelExtremes.maxYHemisphere.equals(AVKey.SOUTH) && levelExtremes.maxY == 0)) - { + if (!(levelExtremes.maxYHemisphere.equals(AVKey.SOUTH) && levelExtremes.maxY == 0)) { // Process northing scale labels for this level String currentHemisphere = levelExtremes.minYHemisphere; for (double northing = levelExtremes.minY; (northing <= levelExtremes.maxY) - || !currentHemisphere.equals(levelExtremes.maxYHemisphere); northing += gridStep) - { + || !currentHemisphere.equals(levelExtremes.maxYHemisphere); northing += gridStep) { // Skip multiples of ten grid steps except for last (higher) level - if (i == this.extremes.length - 1 || northing % gridStepTimesTen != 0) - { - try - { + if (i == this.extremes.length - 1 || northing % gridStepTimesTen != 0) { + try { labelPos = computePosition(this.zone, currentHemisphere, labelEasting, northing); - if (labelPos == null) + if (labelPos == null) { continue; + } Angle lat = labelPos.getLatitude(); Angle lon = labelPos.getLongitude(); Vec4 surfacePoint = getSurfacePoint(dc, lat, lon); - if (viewFrustum.contains(surfacePoint) && isPointInRange(dc, surfacePoint)) - { + if (viewFrustum.contains(surfacePoint) && isPointInRange(dc, surfacePoint)) { String text = String.valueOf((int) (northing % this.scaleModulo)); GeographicText gt = new UserFacingText(text, new Position(lat, lon, 0)); gt.setPriority(gridStepTimesTen); addRenderable(gt, graticuleType); } - } - catch (IllegalArgumentException ignore) - { + } catch (IllegalArgumentException ignore) { } if (!currentHemisphere.equals(levelExtremes.maxYHemisphere) - && northing >= 10e6 - gridStep) - { + && northing >= 10e6 - gridStep) { // Switch hemisphere currentHemisphere = levelExtremes.maxYHemisphere; northing = -gridStep; @@ -683,31 +596,25 @@ public void selectRenderables(DrawContext dc) } } // end northing } // for levels - } - catch (IllegalArgumentException ignore) - { + } catch (IllegalArgumentException ignore) { } } - private boolean isPointInRange(DrawContext dc, Vec4 point) - { + private boolean isPointInRange(DrawContext dc, Vec4 point) { double altitudeAboveGround = computeAltitudeAboveGround(dc); return dc.getView().getEyePoint().distanceTo3(point) - < altitudeAboveGround * this.visibleDistanceFactor; + < altitudeAboveGround * this.visibleDistanceFactor; } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { sb.append("level "); sb.append(String.valueOf(i)); sb.append(" : "); UTMExtremes levelExtremes = this.extremes[i]; - if (levelExtremes.minX < levelExtremes.maxX || - !(levelExtremes.maxYHemisphere.equals(AVKey.SOUTH) && levelExtremes.maxY == 0)) - { + if (levelExtremes.minX < levelExtremes.maxX + || !(levelExtremes.maxYHemisphere.equals(AVKey.SOUTH) && levelExtremes.maxY == 0)) { sb.append(levelExtremes.minX); sb.append(", "); sb.append(levelExtremes.maxX); @@ -717,9 +624,7 @@ public String toString() sb.append(", "); sb.append(levelExtremes.maxY); sb.append(AVKey.NORTH.equals(levelExtremes.maxYHemisphere) ? "N" : "S"); - } - else - { + } else { sb.append("empty"); } sb.append("\n"); @@ -729,10 +634,8 @@ public String toString() } // --- UTM/UPS square zone ------------------------------------------------------------------ - protected ArrayList createSquaresGrid(int UTMZone, String hemisphere, Sector UTMZoneSector, - double minEasting, double maxEasting, double minNorthing, double maxNorthing) - { + double minEasting, double maxEasting, double minNorthing, double maxNorthing) { ArrayList squares = new ArrayList(); double startEasting = Math.floor(minEasting / ONEHT) * ONEHT; double startNorthing = Math.floor(minNorthing / ONEHT) * ONEHT; @@ -740,14 +643,11 @@ protected ArrayList createSquaresGrid(int UTMZone, String hemisphere int rows = (int) Math.ceil((maxNorthing - startNorthing) / ONEHT); SquareZone[][] squaresArray = new SquareZone[rows][cols]; int col = 0; - for (double easting = startEasting; easting < maxEasting; easting += ONEHT) - { + for (double easting = startEasting; easting < maxEasting; easting += ONEHT) { int row = 0; - for (double northing = startNorthing; northing < maxNorthing; northing += ONEHT) - { + for (double northing = startNorthing; northing < maxNorthing; northing += ONEHT) { SquareZone sz = new SquareZone(UTMZone, hemisphere, UTMZoneSector, easting, northing, ONEHT); - if (sz.boundingSector != null && !sz.isOutsideGridZone()) - { + if (sz.boundingSector != null && !sz.isOutsideGridZone()) { squares.add(sz); squaresArray[row][col] = sz; } @@ -757,13 +657,10 @@ protected ArrayList createSquaresGrid(int UTMZone, String hemisphere } // Keep track of neighbors - for (col = 0; col < cols; col++) - { - for (int row = 0; row < rows; row++) - { + for (col = 0; col < cols; col++) { + for (int row = 0; row < rows; row++) { SquareZone sz = squaresArray[row][col]; - if (sz != null) - { + if (sz != null) { sz.setNorthNeighbor(row + 1 < rows ? squaresArray[row + 1][col] : null); sz.setEastNeighbor(col + 1 < cols ? squaresArray[row][col + 1] : null); } @@ -773,9 +670,11 @@ protected ArrayList createSquaresGrid(int UTMZone, String hemisphere return squares; } - /** Represent a generic UTM/UPS square area */ - private class SquareSector - { + /** + * Represent a generic UTM/UPS square area + */ + private class SquareSector { + public static final int MIN_CELL_SIZE_PIXELS = 50; protected int UTMZone; @@ -792,8 +691,7 @@ private class SquareSector protected boolean isTruncated = false; public SquareSector(int UTMZone, String hemisphere, Sector UTMZoneSector, double SWEasting, - double SWNorthing, double size) - { + double SWNorthing, double size) { this.UTMZone = UTMZone; this.hemisphere = hemisphere; this.UTMZoneSector = UTMZoneSector; @@ -807,15 +705,15 @@ public SquareSector(int UTMZone, String hemisphere, Sector UTMZoneSector, double this.nw = computePosition(this.UTMZone, this.hemisphere, SWEasting, SWNorthing + size); this.ne = computePosition(this.UTMZone, this.hemisphere, SWEasting + size, SWNorthing + size); this.squareCenter = computePosition(this.UTMZone, this.hemisphere, SWEasting + size / 2, - SWNorthing + size / 2); + SWNorthing + size / 2); // Compute approximate bounding sector and center point - if (this.sw != null && this.se != null && this.nw != null && this.ne != null) - { + if (this.sw != null && this.se != null && this.nw != null && this.ne != null) { adjustDateLineCrossingPoints(); this.boundingSector = Sector.boundingSector(Arrays.asList(sw, se, nw, ne)); - if (!isInsideGridZone()) + if (!isInsideGridZone()) { this.boundingSector = this.UTMZoneSector.intersection(this.boundingSector); + } this.centroid = this.boundingSector != null ? this.boundingSector.getCentroid() : this.squareCenter; //this.squareCenter = this.boundingSector.getCentroid(); @@ -825,47 +723,52 @@ public SquareSector(int UTMZone, String hemisphere, Sector UTMZoneSector, double this.isTruncated = !isInsideGridZone(); } - private void adjustDateLineCrossingPoints() - { + private void adjustDateLineCrossingPoints() { ArrayList corners = new ArrayList(Arrays.asList(sw, se, nw, ne)); - if (!LatLon.locationsCrossDateLine(corners)) + if (!LatLon.locationsCrossDateLine(corners)) { return; + } double lonSign = 0; - for (LatLon corner : corners) - { - if (Math.abs(corner.getLongitude().degrees) != 180) + for (LatLon corner : corners) { + if (Math.abs(corner.getLongitude().degrees) != 180) { lonSign = Math.signum(corner.getLongitude().degrees); + } } - if (lonSign == 0) + if (lonSign == 0) { return; + } - if (Math.abs(sw.getLongitude().degrees) == 180 && Math.signum(sw.getLongitude().degrees) != lonSign) + if (Math.abs(sw.getLongitude().degrees) == 180 && Math.signum(sw.getLongitude().degrees) != lonSign) { sw = new Position(sw.getLatitude(), sw.getLongitude().multiply(-1), sw.getElevation()); - if (Math.abs(se.getLongitude().degrees) == 180 && Math.signum(se.getLongitude().degrees) != lonSign) + } + if (Math.abs(se.getLongitude().degrees) == 180 && Math.signum(se.getLongitude().degrees) != lonSign) { se = new Position(se.getLatitude(), se.getLongitude().multiply(-1), se.getElevation()); - if (Math.abs(nw.getLongitude().degrees) == 180 && Math.signum(nw.getLongitude().degrees) != lonSign) + } + if (Math.abs(nw.getLongitude().degrees) == 180 && Math.signum(nw.getLongitude().degrees) != lonSign) { nw = new Position(nw.getLatitude(), nw.getLongitude().multiply(-1), nw.getElevation()); - if (Math.abs(ne.getLongitude().degrees) == 180 && Math.signum(ne.getLongitude().degrees) != lonSign) + } + if (Math.abs(ne.getLongitude().degrees) == 180 && Math.signum(ne.getLongitude().degrees) != lonSign) { ne = new Position(ne.getLatitude(), ne.getLongitude().multiply(-1), ne.getElevation()); + } } - public Extent getExtent(Globe globe, double ve) - { + public Extent getExtent(Globe globe, double ve) { return Sector.computeBoundingCylinder(globe, ve, this.boundingSector); } @SuppressWarnings({"RedundantIfStatement"}) - public boolean isInView(DrawContext dc) - { + public boolean isInView(DrawContext dc) { if (!dc.getView().getFrustumInModelCoordinates().intersects( - this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) + this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) { return false; + } // Check apparent size - if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS) + if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS) { return false; + } return true; } @@ -876,16 +779,19 @@ public boolean isInView(DrawContext dc) * @return true if this square is totaly inside its parent grid zone. */ @SuppressWarnings({"RedundantIfStatement"}) - public boolean isInsideGridZone() - { - if (!this.isPositionInside(this.nw)) + public boolean isInsideGridZone() { + if (!this.isPositionInside(this.nw)) { return false; - if (!this.isPositionInside(this.ne)) + } + if (!this.isPositionInside(this.ne)) { return false; - if (!this.isPositionInside(this.sw)) + } + if (!this.isPositionInside(this.sw)) { return false; - if (!this.isPositionInside(this.se)) + } + if (!this.isPositionInside(this.se)) { return false; + } return true; } @@ -895,26 +801,27 @@ public boolean isInsideGridZone() * @return true if this square is totaly outside its parent grid zone. */ @SuppressWarnings({"RedundantIfStatement"}) - public boolean isOutsideGridZone() - { - if (this.isPositionInside(this.nw)) + public boolean isOutsideGridZone() { + if (this.isPositionInside(this.nw)) { return false; - if (this.isPositionInside(this.ne)) + } + if (this.isPositionInside(this.ne)) { return false; - if (this.isPositionInside(this.sw)) + } + if (this.isPositionInside(this.sw)) { return false; - if (this.isPositionInside(this.se)) + } + if (this.isPositionInside(this.se)) { return false; + } return true; } - public boolean isPositionInside(Position position) - { + public boolean isPositionInside(Position position) { return position != null && this.UTMZoneSector.contains(position); } - public double getSizeInPixels(DrawContext dc) - { + public double getSizeInPixels(DrawContext dc) { View view = dc.getView(); Vec4 centerPoint = getSurfacePoint(dc, this.centroid.getLatitude(), this.centroid.getLongitude()); Double distance = view.getEyePoint().distanceTo3(centerPoint); @@ -922,9 +829,11 @@ public double getSizeInPixels(DrawContext dc) } } - /** Represent a 100km square zone inside an UTM zone. */ - protected class SquareZone extends SquareSector - { + /** + * Represent a 100km square zone inside an UTM zone. + */ + protected class SquareZone extends SquareSector { + protected String name; protected SquareGrid squareGrid; protected ArrayList gridElements; @@ -932,91 +841,83 @@ protected class SquareZone extends SquareSector private SquareZone northNeighbor, eastNeighbor; public SquareZone(int UTMZone, String hemisphere, Sector UTMZoneSector, double SWEasting, - double SWNorthing, double size) - { + double SWNorthing, double size) { super(UTMZone, hemisphere, UTMZoneSector, SWEasting, SWNorthing, size); } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public void setNorthNeighbor(SquareZone sz) - { + public void setNorthNeighbor(SquareZone sz) { this.northNeighbor = sz; } - public void setEastNeighbor(SquareZone sz) - { + public void setEastNeighbor(SquareZone sz) { this.eastNeighbor = sz; } - public void selectRenderables(DrawContext dc, Sector vs) - { + public void selectRenderables(DrawContext dc, Sector vs) { // Select our renderables - if (this.gridElements == null) + if (this.gridElements == null) { createRenderables(); + } boolean drawMetricLabels = getSizeInPixels(dc) > MIN_CELL_SIZE_PIXELS * 2; String graticuleType = getTypeFor((int) this.size); - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc, vs)) - { - if (ge.type.equals(GridElement.TYPE_LINE_NORTH) && this.isNorthNeighborInView(dc)) + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc, vs)) { + if (ge.type.equals(GridElement.TYPE_LINE_NORTH) && this.isNorthNeighborInView(dc)) { continue; - if (ge.type.equals(GridElement.TYPE_LINE_EAST) && this.isEastNeighborInView(dc)) + } + if (ge.type.equals(GridElement.TYPE_LINE_EAST) && this.isEastNeighborInView(dc)) { continue; + } - if (drawMetricLabels) + if (drawMetricLabels) { metricScaleSupport.computeMetricScaleExtremes(this.UTMZone, this.hemisphere, ge, - this.size * 10); + this.size * 10); + } addRenderable(ge.renderable, graticuleType); } } - if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS * 2) + if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS * 2) { return; + } // Select grid renderables - if (this.squareGrid == null) + if (this.squareGrid == null) { this.squareGrid = new SquareGrid(this.UTMZone, this.hemisphere, this.UTMZoneSector, this.SWEasting, - this.SWNorthing, this.size); - if (this.squareGrid.isInView(dc)) - { - this.squareGrid.selectRenderables(dc, vs); + this.SWNorthing, this.size); } - else + if (this.squareGrid.isInView(dc)) { + this.squareGrid.selectRenderables(dc, vs); + } else { this.squareGrid.clearRenderables(); + } } - private boolean isNorthNeighborInView(DrawContext dc) - { + private boolean isNorthNeighborInView(DrawContext dc) { return this.northNeighbor != null && this.northNeighbor.isInView(dc); } - private boolean isEastNeighborInView(DrawContext dc) - { + private boolean isEastNeighborInView(DrawContext dc) { return this.eastNeighbor != null && this.eastNeighbor.isInView(dc); } - public void clearRenderables() - { - if (this.gridElements != null) - { + public void clearRenderables() { + if (this.gridElements != null) { this.gridElements.clear(); this.gridElements = null; } - if (this.squareGrid != null) - { + if (this.squareGrid != null) { this.squareGrid.clearRenderables(); this.squareGrid = null; } } - public void createRenderables() - { + public void createRenderables() { this.gridElements = new ArrayList(); ArrayList positions = new ArrayList(); @@ -1026,17 +927,13 @@ public void createRenderables() // left segment positions.clear(); - if (this.isTruncated) - { + if (this.isTruncated) { computeTruncatedSegment(sw, nw, this.UTMZoneSector, positions); - } - else - { + } else { positions.add(sw); positions.add(nw); } - if (positions.size() > 0) - { + if (positions.size() > 0) { p1 = positions.get(0); p2 = positions.get(1); polyline = createLineRenderable(new ArrayList(positions), AVKey.GREAT_CIRCLE); @@ -1048,17 +945,13 @@ public void createRenderables() // right segment positions.clear(); - if (this.isTruncated) - { + if (this.isTruncated) { computeTruncatedSegment(se, ne, this.UTMZoneSector, positions); - } - else - { + } else { positions.add(se); positions.add(ne); } - if (positions.size() > 0) - { + if (positions.size() > 0) { p1 = positions.get(0); p2 = positions.get(1); polyline = createLineRenderable(new ArrayList(positions), AVKey.GREAT_CIRCLE); @@ -1070,17 +963,13 @@ public void createRenderables() // bottom segment positions.clear(); - if (this.isTruncated) - { + if (this.isTruncated) { computeTruncatedSegment(sw, se, this.UTMZoneSector, positions); - } - else - { + } else { positions.add(sw); positions.add(se); } - if (positions.size() > 0) - { + if (positions.size() > 0) { p1 = positions.get(0); p2 = positions.get(1); polyline = createLineRenderable(new ArrayList(positions), AVKey.GREAT_CIRCLE); @@ -1092,17 +981,13 @@ public void createRenderables() // top segment positions.clear(); - if (this.isTruncated) - { + if (this.isTruncated) { computeTruncatedSegment(nw, ne, this.UTMZoneSector, positions); - } - else - { + } else { positions.add(nw); positions.add(ne); } - if (positions.size() > 0) - { + if (positions.size() > 0) { p1 = positions.get(0); p2 = positions.get(1); polyline = createLineRenderable(new ArrayList(positions), AVKey.GREAT_CIRCLE); @@ -1113,113 +998,103 @@ public void createRenderables() } // Label - if (this.name != null) - { + if (this.name != null) { // Only add a label to squares above some dimension if (this.boundingSector.getDeltaLon().degrees * Math.cos(this.centroid.getLatitude().radians) > .2 - && this.boundingSector.getDeltaLat().degrees > .2) - { + && this.boundingSector.getDeltaLat().degrees > .2) { LatLon labelPos = null; if (this.UTMZone != 0) // Not at poles { labelPos = this.centroid; - } - else if (this.isPositionInside(new Position(this.squareCenter, 0))) - { + } else if (this.isPositionInside(new Position(this.squareCenter, 0))) { labelPos = this.squareCenter; - } - else if (this.squareCenter.getLatitude().degrees <= this.UTMZoneSector.getMaxLatitude().degrees - && this.squareCenter.getLatitude().degrees >= this.UTMZoneSector.getMinLatitude().degrees) - { + } else if (this.squareCenter.getLatitude().degrees <= this.UTMZoneSector.getMaxLatitude().degrees + && this.squareCenter.getLatitude().degrees >= this.UTMZoneSector.getMinLatitude().degrees) { labelPos = this.centroid; } - if (labelPos != null) - { + if (labelPos != null) { GeographicText text = new UserFacingText(this.name, new Position(labelPos, 0)); text.setPriority(this.size * 10); this.gridElements.add( - new GridElement(this.boundingSector, text, GridElement.TYPE_GRIDZONE_LABEL)); + new GridElement(this.boundingSector, text, GridElement.TYPE_GRIDZONE_LABEL)); } } } } } - /** Represent a square 10x10 grid and recursive tree in easting/northing coordinates */ - protected class SquareGrid extends SquareSector - { + /** + * Represent a square 10x10 grid and recursive tree in easting/northing coordinates + */ + protected class SquareGrid extends SquareSector { + private ArrayList gridElements; private ArrayList subGrids; public SquareGrid(int UTMZone, String hemisphere, Sector UTMZoneSector, double SWEasting, - double SWNorthing, double size) - { + double SWNorthing, double size) { super(UTMZone, hemisphere, UTMZoneSector, SWEasting, SWNorthing, size); } @SuppressWarnings({"RedundantIfStatement"}) - public boolean isInView(DrawContext dc) - { + public boolean isInView(DrawContext dc) { if (!dc.getView().getFrustumInModelCoordinates().intersects( - this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) + this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) { return false; + } // Check apparent size - if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS * 4) + if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS * 4) { return false; + } return true; } - public void selectRenderables(DrawContext dc, Sector vs) - { + public void selectRenderables(DrawContext dc, Sector vs) { // Select our renderables - if (this.gridElements == null) + if (this.gridElements == null) { createRenderables(); + } int gridStep = (int) this.size / 10; boolean drawMetricLabels = getSizeInPixels(dc) > MIN_CELL_SIZE_PIXELS * 4 * 1.7; String graticuleType = getTypeFor(gridStep); - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc, vs)) - { - if (drawMetricLabels) + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc, vs)) { + if (drawMetricLabels) { metricScaleSupport.computeMetricScaleExtremes(this.UTMZone, this.hemisphere, ge, this.size); + } addRenderable(ge.renderable, graticuleType); } } - if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS * 4 * 2) + if (getSizeInPixels(dc) <= MIN_CELL_SIZE_PIXELS * 4 * 2) { return; + } // Select sub grids renderables - if (this.subGrids == null) + if (this.subGrids == null) { createSubGrids(); - for (SquareGrid sg : this.subGrids) - { - if (sg.isInView(dc)) - { + } + for (SquareGrid sg : this.subGrids) { + if (sg.isInView(dc)) { sg.selectRenderables(dc, vs); - } - else + } else { sg.clearRenderables(); + } } } - public void clearRenderables() - { - if (this.gridElements != null) - { + public void clearRenderables() { + if (this.gridElements != null) { this.gridElements.clear(); this.gridElements = null; } - if (this.subGrids != null) - { - for (SquareGrid sg : this.subGrids) - { + if (this.subGrids != null) { + for (SquareGrid sg : this.subGrids) { sg.clearRenderables(); } this.subGrids.clear(); @@ -1227,49 +1102,41 @@ public void clearRenderables() } } - public void createSubGrids() - { + public void createSubGrids() { this.subGrids = new ArrayList(); double gridStep = this.size / 10; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { double easting = this.SWEasting + gridStep * i; - for (int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { double northing = this.SWNorthing + gridStep * j; SquareGrid sg = new SquareGrid(this.UTMZone, this.hemisphere, this.UTMZoneSector, - easting, northing, gridStep); - if (!sg.isOutsideGridZone()) + easting, northing, gridStep); + if (!sg.isOutsideGridZone()) { this.subGrids.add(sg); + } } } } - public void createRenderables() - { + public void createRenderables() { this.gridElements = new ArrayList(); double gridStep = this.size / 10; Position p1, p2; ArrayList positions = new ArrayList(); // South-North lines - for (int i = 1; i <= 9; i++) - { + for (int i = 1; i <= 9; i++) { double easting = this.SWEasting + gridStep * i; positions.clear(); p1 = computePosition(this.UTMZone, this.hemisphere, easting, SWNorthing); p2 = computePosition(this.UTMZone, this.hemisphere, easting, SWNorthing + this.size); - if (this.isTruncated) - { + if (this.isTruncated) { computeTruncatedSegment(p1, p2, this.UTMZoneSector, positions); - } - else - { + } else { positions.add(p1); positions.add(p2); } - if (positions.size() > 0) - { + if (positions.size() > 0) { p1 = positions.get(0); p2 = positions.get(1); Object polyline = createLineRenderable(new ArrayList(positions), AVKey.GREAT_CIRCLE); @@ -1280,23 +1147,18 @@ public void createRenderables() } } // West-East lines - for (int i = 1; i <= 9; i++) - { + for (int i = 1; i <= 9; i++) { double northing = this.SWNorthing + gridStep * i; positions.clear(); p1 = computePosition(this.UTMZone, this.hemisphere, SWEasting, northing); p2 = computePosition(this.UTMZone, this.hemisphere, SWEasting + this.size, northing); - if (this.isTruncated) - { + if (this.isTruncated) { computeTruncatedSegment(p1, p2, this.UTMZoneSector, positions); - } - else - { + } else { positions.add(p1); positions.add(p2); } - if (positions.size() > 0) - { + if (positions.size() > 0) { p1 = positions.get(0); p2 = positions.get(1); Object polyline = createLineRenderable(new ArrayList(positions), AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/layers/Earth/UTMGraticuleLayer.java b/src/gov/nasa/worldwind/layers/Earth/UTMGraticuleLayer.java index 97d90422c6..f8db9a5b78 100644 --- a/src/gov/nasa/worldwind/layers/Earth/UTMGraticuleLayer.java +++ b/src/gov/nasa/worldwind/layers/Earth/UTMGraticuleLayer.java @@ -24,21 +24,35 @@ * @author Patrick Murris * @version $Id: UTMGraticuleLayer.java 2153 2014-07-17 17:33:13Z tgaskins $ */ -public class UTMGraticuleLayer extends UTMBaseGraticuleLayer -{ - /** Graticule for the UTM zone grid. */ +public class UTMGraticuleLayer extends UTMBaseGraticuleLayer { + + /** + * Graticule for the UTM zone grid. + */ public static final String GRATICULE_UTM_GRID = "Graticule.UTM.Grid"; - /** Graticule for the 100,000 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 100,000 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_100000M = "Graticule.100000m"; - /** Graticule for the 10,000 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 10,000 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_10000M = "Graticule.10000m"; - /** Graticule for the 1,000 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 1,000 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_1000M = "Graticule.1000m"; - /** Graticule for the 100 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 100 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_100M = "Graticule.100m"; - /** Graticule for the 10 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 10 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_10M = "Graticule.10m"; - /** Graticule for the 1 meter grid, nested inside the UTM grid. */ + /** + * Graticule for the 1 meter grid, nested inside the UTM grid. + */ public static final String GRATICULE_1M = "Graticule.1m"; protected static final int MIN_CELL_SIZE_PIXELS = 40; // TODO: make settable @@ -47,8 +61,7 @@ public class UTMGraticuleLayer extends UTMBaseGraticuleLayer protected GraticuleTile[][] gridTiles = new GraticuleTile[GRID_ROWS][GRID_COLS]; - public UTMGraticuleLayer() - { + public UTMGraticuleLayer() { initRenderingParams(); this.setPickEnabled(false); this.setName(Logging.getMessage("layers.Earth.UTMGraticule.Name")); @@ -56,9 +69,7 @@ public UTMGraticuleLayer() } // --- Graticule Rendering -------------------------------------------------------------- - - protected void initRenderingParams() - { + protected void initRenderingParams() { GraticuleRenderingParams params; // UTM zone grid params = new GraticuleRenderingParams(); @@ -99,59 +110,54 @@ protected void initRenderingParams() setRenderingParams(GRATICULE_1M, params); } - protected String[] getOrderedTypes() - { - return new String[] { + protected String[] getOrderedTypes() { + return new String[]{ GRATICULE_UTM_GRID, GRATICULE_100000M, GRATICULE_10000M, GRATICULE_1000M, GRATICULE_100M, GRATICULE_10M, - GRATICULE_1M, - }; + GRATICULE_1M,}; } - protected String getTypeFor(int resolution) - { - if (resolution >= 500000) + protected String getTypeFor(int resolution) { + if (resolution >= 500000) { return GRATICULE_UTM_GRID; - if (resolution >= 100000) + } + if (resolution >= 100000) { return GRATICULE_100000M; - else if (resolution >= 10000) + } else if (resolution >= 10000) { return GRATICULE_10000M; - else if (resolution >= 1000) + } else if (resolution >= 1000) { return GRATICULE_1000M; - else if (resolution >= 100) + } else if (resolution >= 100) { return GRATICULE_100M; - else if (resolution >= 10) + } else if (resolution >= 10) { return GRATICULE_10M; - else if (resolution >= 1) + } else if (resolution >= 1) { return GRATICULE_1M; + } return null; } - protected void clear(DrawContext dc) - { + protected void clear(DrawContext dc) { super.clear(dc); this.applyTerrainConformance(); this.metricScaleSupport.clear(); this.metricScaleSupport.computeZone(dc); } - private void applyTerrainConformance() - { + private void applyTerrainConformance() { String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { double lineConformance = type.equals(GRATICULE_UTM_GRID) ? 20 : this.terrainConformance; getRenderingParams(type).setValue(GraticuleRenderingParams.KEY_LINE_CONFORMANCE, lineConformance); } } - protected void selectRenderables(DrawContext dc) - { + protected void selectRenderables(DrawContext dc) { this.selectUTMRenderables(dc); this.metricScaleSupport.selectRenderables(dc); } @@ -161,40 +167,34 @@ protected void selectRenderables(DrawContext dc) * * @param dc the current DrawContext. */ - protected void selectUTMRenderables(DrawContext dc) - { + protected void selectUTMRenderables(DrawContext dc) { ArrayList tileList = getVisibleTiles(dc); - if (tileList.size() > 0) - { - for (GraticuleTile gt : tileList) - { + if (tileList.size() > 0) { + for (GraticuleTile gt : tileList) { // Select tile visible elements gt.selectRenderables(dc); } } } - protected ArrayList getVisibleTiles(DrawContext dc) - { + protected ArrayList getVisibleTiles(DrawContext dc) { ArrayList tileList = new ArrayList(); Sector vs = dc.getVisibleSector(); - if (vs != null) - { + if (vs != null) { Rectangle2D gridRectangle = getGridRectangleForSector(vs); - if (gridRectangle != null) - { + if (gridRectangle != null) { for (int row = (int) gridRectangle.getY(); row <= gridRectangle.getY() + gridRectangle.getHeight(); - row++) - { + row++) { for (int col = (int) gridRectangle.getX(); col <= gridRectangle.getX() + gridRectangle.getWidth(); - col++) - { - if (gridTiles[row][col] == null) + col++) { + if (gridTiles[row][col] == null) { gridTiles[row][col] = new GraticuleTile(getGridSector(row, col)); - if (gridTiles[row][col].isInView(dc)) + } + if (gridTiles[row][col].isInView(dc)) { tileList.add(gridTiles[row][col]); - else + } else { gridTiles[row][col].clearRenderables(); + } } } } @@ -202,8 +202,7 @@ protected ArrayList getVisibleTiles(DrawContext dc) return tileList; } - private Rectangle2D getGridRectangleForSector(Sector sector) - { + private Rectangle2D getGridRectangleForSector(Sector sector) { int x1 = getGridColumn(sector.getMinLongitude().degrees); int x2 = getGridColumn(sector.getMaxLongitude().degrees); int y1 = getGridRow(sector.getMinLatitude().degrees); @@ -211,8 +210,7 @@ private Rectangle2D getGridRectangleForSector(Sector sector) return new Rectangle(x1, y1, x2 - x1, y2 - y1); } - private Sector getGridSector(int row, int col) - { + private Sector getGridSector(int row, int col) { double deltaLat = UTM_MAX_LATITUDE * 2 / GRID_ROWS; double deltaLon = 360 / GRID_COLS; double minLat = row == 0 ? UTM_MIN_LATITUDE : -UTM_MAX_LATITUDE + deltaLat * row; @@ -222,28 +220,22 @@ private Sector getGridSector(int row, int col) return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); } - private int getGridColumn(double longitude) - { + private int getGridColumn(double longitude) { double deltaLon = 360 / GRID_COLS; int col = (int) Math.floor((longitude + 180) / deltaLon); return Math.min(col, GRID_COLS - 1); } - private int getGridRow(double latitude) - { + private int getGridRow(double latitude) { double deltaLat = UTM_MAX_LATITUDE * 2 / GRID_ROWS; int row = (int) Math.floor((latitude + UTM_MAX_LATITUDE) / deltaLat); return Math.max(0, Math.min(row, GRID_ROWS - 1)); } - protected void clearTiles() - { - for (int row = 0; row < 2; row++) - { - for (int col = 0; col < 60; col++) - { - if (this.gridTiles[row][col] != null) - { + protected void clearTiles() { + for (int row = 0; row < 2; row++) { + for (int col = 0; col < 60; col++) { + if (this.gridTiles[row][col] != null) { this.gridTiles[row][col].clearRenderables(); this.gridTiles[row][col] = null; } @@ -252,9 +244,8 @@ protected void clearTiles() } // --- Graticule tile ---------------------------------------------------------------------- + protected class GraticuleTile { - protected class GraticuleTile - { private Sector sector; private int zone; private String hemisphere; @@ -262,80 +253,73 @@ protected class GraticuleTile private ArrayList gridElements; private ArrayList squares; - public GraticuleTile(Sector sector) - { + public GraticuleTile(Sector sector) { this.sector = sector; this.zone = getGridColumn(this.sector.getCentroid().getLongitude().degrees) + 1; this.hemisphere = this.sector.getCentroid().latitude.degrees > 0 ? AVKey.NORTH : AVKey.SOUTH; } - public Extent getExtent(Globe globe, double ve) - { + public Extent getExtent(Globe globe, double ve) { return Sector.computeBoundingCylinder(globe, ve, this.sector); } @SuppressWarnings({"RedundantIfStatement"}) - public boolean isInView(DrawContext dc) - { + public boolean isInView(DrawContext dc) { if (!dc.getView().getFrustumInModelCoordinates().intersects( - this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) + this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) { return false; + } return true; } - public double getSizeInPixels(DrawContext dc) - { + public double getSizeInPixels(DrawContext dc) { View view = dc.getView(); Vec4 centerPoint = getSurfacePoint(dc, this.sector.getCentroid().getLatitude(), - this.sector.getCentroid().getLongitude()); + this.sector.getCentroid().getLongitude()); double distance = view.getEyePoint().distanceTo3(centerPoint); double tileSizeMeter = this.sector.getDeltaLatRadians() * dc.getGlobe().getRadius(); return tileSizeMeter / view.computePixelSizeAtDistance(distance); } - public void selectRenderables(DrawContext dc) - { - if (this.gridElements == null) + public void selectRenderables(DrawContext dc) { + if (this.gridElements == null) { this.createRenderables(); + } // Select tile grid elements int resolution = 500000; // Top level 6 degrees zones String graticuleType = getTypeFor(resolution); - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc)) + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc)) { addRenderable(ge.renderable, graticuleType); + } } - if (getSizeInPixels(dc) / 10 < MIN_CELL_SIZE_PIXELS * 2) + if (getSizeInPixels(dc) / 10 < MIN_CELL_SIZE_PIXELS * 2) { return; + } // Select child elements - if (this.squares == null) + if (this.squares == null) { createSquares(); - for (SquareZone sz : this.squares) - { - if (sz.isInView(dc)) - { + } + for (SquareZone sz : this.squares) { + if (sz.isInView(dc)) { sz.selectRenderables(dc, dc.getVisibleSector()); - } - else + } else { sz.clearRenderables(); + } } } - public void clearRenderables() - { - if (this.gridElements != null) - { + public void clearRenderables() { + if (this.gridElements != null) { this.gridElements.clear(); this.gridElements = null; } - if (this.squares != null) - { - for (SquareZone sz : this.squares) - { + if (this.squares != null) { + for (SquareZone sz : this.squares) { sz.clearRenderables(); } this.squares.clear(); @@ -343,17 +327,15 @@ public void clearRenderables() } } - private void createSquares() - { - try - { + private void createSquares() { + try { // Find grid zone easting and northing boundaries UTMCoord UTM; UTM = UTMCoord.fromLatLon(this.sector.getMinLatitude(), this.sector.getCentroid().getLongitude(), - globe); + globe); double minNorthing = UTM.getNorthing(); UTM = UTMCoord.fromLatLon(this.sector.getMaxLatitude(), this.sector.getCentroid().getLongitude(), - globe); + globe); double maxNorthing = UTM.getNorthing(); maxNorthing = maxNorthing == 0 ? 10e6 : maxNorthing; UTM = UTMCoord.fromLatLon(this.sector.getMinLatitude(), this.sector.getMinLongitude(), globe); @@ -364,16 +346,15 @@ private void createSquares() // Create squares this.squares = createSquaresGrid(this.zone, this.hemisphere, this.sector, minEasting, maxEasting, - minNorthing, maxNorthing); - } - catch (IllegalArgumentException ignore) - { + minNorthing, maxNorthing); + } catch (IllegalArgumentException ignore) { } } - /** Create the grid elements */ - private void createRenderables() - { + /** + * Create the grid elements + */ + private void createRenderables() { this.gridElements = new ArrayList(); ArrayList positions = new ArrayList(); @@ -384,42 +365,39 @@ private void createRenderables() positions.add(new Position(this.sector.getMaxLatitude(), this.sector.getMinLongitude(), 0)); Object polyline = createLineRenderable(new ArrayList(positions), AVKey.LINEAR); Sector lineSector = new Sector(this.sector.getMinLatitude(), this.sector.getMaxLatitude(), - this.sector.getMinLongitude(), this.sector.getMinLongitude()); + this.sector.getMinLongitude(), this.sector.getMinLongitude()); GridElement ge = new GridElement(lineSector, polyline, GridElement.TYPE_LINE); ge.value = this.sector.getMinLongitude().degrees; this.gridElements.add(ge); // Generate south parallel at south pole and equator - if (this.sector.getMinLatitude().degrees == UTM_MIN_LATITUDE || this.sector.getMinLatitude().degrees == 0) - { + if (this.sector.getMinLatitude().degrees == UTM_MIN_LATITUDE || this.sector.getMinLatitude().degrees == 0) { positions.clear(); positions.add(new Position(this.sector.getMinLatitude(), this.sector.getMinLongitude(), 0)); positions.add(new Position(this.sector.getMinLatitude(), this.sector.getMaxLongitude(), 0)); polyline = createLineRenderable(new ArrayList(positions), AVKey.LINEAR); lineSector = new Sector(this.sector.getMinLatitude(), this.sector.getMinLatitude(), - this.sector.getMinLongitude(), this.sector.getMaxLongitude()); + this.sector.getMinLongitude(), this.sector.getMaxLongitude()); ge = new GridElement(lineSector, polyline, GridElement.TYPE_LINE); ge.value = this.sector.getMinLatitude().degrees; this.gridElements.add(ge); } // Generate north parallel at north pole - if (this.sector.getMaxLatitude().degrees == UTM_MAX_LATITUDE) - { + if (this.sector.getMaxLatitude().degrees == UTM_MAX_LATITUDE) { positions.clear(); positions.add(new Position(this.sector.getMaxLatitude(), this.sector.getMinLongitude(), 0)); positions.add(new Position(this.sector.getMaxLatitude(), this.sector.getMaxLongitude(), 0)); polyline = createLineRenderable(new ArrayList(positions), AVKey.LINEAR); lineSector = new Sector(this.sector.getMaxLatitude(), this.sector.getMaxLatitude(), - this.sector.getMinLongitude(), this.sector.getMaxLongitude()); + this.sector.getMinLongitude(), this.sector.getMaxLongitude()); ge = new GridElement(lineSector, polyline, GridElement.TYPE_LINE); ge.value = this.sector.getMaxLatitude().degrees; this.gridElements.add(ge); } // Add label - if (this.hasLabel()) - { + if (this.hasLabel()) { StringBuilder sb = new StringBuilder(); sb.append(this.zone).append(AVKey.NORTH.equals(this.hemisphere) ? "N" : "S"); GeographicText text = new UserFacingText(sb.toString(), new Position(this.sector.getCentroid(), 0)); @@ -427,18 +405,17 @@ private void createRenderables() } } - private boolean hasLabel() - { + private boolean hasLabel() { // Has label if it contains hemisphere mid latitude double southLat = UTM_MIN_LATITUDE / 2; boolean southLabel = this.sector.getMinLatitude().degrees < southLat - && southLat <= this.sector.getMaxLatitude().degrees; + && southLat <= this.sector.getMaxLatitude().degrees; double northLat = UTM_MAX_LATITUDE / 2; boolean northLabel = this.sector.getMinLatitude().degrees < northLat - && northLat <= this.sector.getMaxLatitude().degrees; + && northLat <= this.sector.getMaxLatitude().degrees; return southLabel || northLabel; } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/layers/GARSGraticuleLayer.java b/src/gov/nasa/worldwind/layers/GARSGraticuleLayer.java index 2dd96febe8..6abcce8c1a 100644 --- a/src/gov/nasa/worldwind/layers/GARSGraticuleLayer.java +++ b/src/gov/nasa/worldwind/layers/GARSGraticuleLayer.java @@ -25,8 +25,8 @@ * * @version $Id: GARSGraticuleLayer.java 2384 2014-10-14 21:55:10Z tgaskins $ */ -public class GARSGraticuleLayer extends AbstractGraticuleLayer -{ +public class GARSGraticuleLayer extends AbstractGraticuleLayer { + public static final String GRATICULE_GARS_LEVEL_0 = "Graticule.GARSLevel0"; public static final String GRATICULE_GARS_LEVEL_1 = "Graticule.GARSLevel1"; public static final String GRATICULE_GARS_LEVEL_2 = "Graticule.GARSLevel2"; @@ -41,23 +41,21 @@ public class GARSGraticuleLayer extends AbstractGraticuleLayer /** * Indicates the eye altitudes in meters below which each level should be displayed. */ - protected double[] thresholds = new double[] {1200e3, 600e3, 180e3}; // 30 min, 15 min, 5 min + protected double[] thresholds = new double[]{1200e3, 600e3, 180e3}; // 30 min, 15 min, 5 min - public GARSGraticuleLayer() - { + public GARSGraticuleLayer() { initRenderingParams(); this.setPickEnabled(false); this.setName(Logging.getMessage("layers.LatLonGraticule.Name")); } /** - * Get the graticule division and angular display format. Can be one of {@link gov.nasa.worldwind.geom.Angle#ANGLE_FORMAT_DD} - * or {@link gov.nasa.worldwind.geom.Angle#ANGLE_FORMAT_DMS}. + * Get the graticule division and angular display format. Can be one of + * {@link gov.nasa.worldwind.geom.Angle#ANGLE_FORMAT_DD} or {@link gov.nasa.worldwind.geom.Angle#ANGLE_FORMAT_DMS}. * * @return the graticule division and angular display format. */ - public String getAngleFormat() - { + public String getAngleFormat() { return this.angleFormat; } @@ -70,17 +68,16 @@ public String getAngleFormat() * * @throws IllegalArgumentException is format is null. */ - public void setAngleFormat(String format) - { - if (format == null) - { + public void setAngleFormat(String format) { + if (format == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.angleFormat.equals(format)) + if (this.angleFormat.equals(format)) { return; + } this.angleFormat = format; this.clearTiles(); @@ -92,8 +89,7 @@ public void setAngleFormat(String format) * * @param altitude the eye altitude in meters below which the 30 minute grid is displayed. */ - public void set30MinuteThreshold(double altitude) - { + public void set30MinuteThreshold(double altitude) { this.thresholds[0] = altitude; } @@ -102,8 +98,7 @@ public void set30MinuteThreshold(double altitude) * * @return the eye altitude in meters below which the 30 minute grid is displayed. */ - public double get30MinuteThreshold() - { + public double get30MinuteThreshold() { return this.thresholds[0]; } @@ -112,8 +107,7 @@ public double get30MinuteThreshold() * * @param altitude the eye altitude in meters below which the 15 minute grid is displayed. */ - public void set15MinuteThreshold(double altitude) - { + public void set15MinuteThreshold(double altitude) { this.thresholds[1] = altitude; } @@ -122,8 +116,7 @@ public void set15MinuteThreshold(double altitude) * * @return the eye altitude in meters below which the 15 minute grid is displayed. */ - public double get15MinuteThreshold() - { + public double get15MinuteThreshold() { return this.thresholds[1]; } @@ -132,8 +125,7 @@ public double get15MinuteThreshold() * * @param altitude the eye altitude in meters below which the 5 minute grid is displayed. */ - public void set5MinuteThreshold(double altitude) - { + public void set5MinuteThreshold(double altitude) { this.thresholds[2] = altitude; } @@ -142,15 +134,12 @@ public void set5MinuteThreshold(double altitude) * * @return the eye altitude in meters below which the 5 minute grid is displayed. */ - public double get5MinuteThreshold() - { + public double get5MinuteThreshold() { return this.thresholds[2]; } // --- Graticule Rendering -------------------------------------------------------------- - - protected void initRenderingParams() - { + protected void initRenderingParams() { GraticuleRenderingParams params; // Ten degrees grid params = new GraticuleRenderingParams(); @@ -176,45 +165,40 @@ protected void initRenderingParams() setRenderingParams(GRATICULE_GARS_LEVEL_3, params); } - protected String[] getOrderedTypes() - { - return new String[] { + protected String[] getOrderedTypes() { + return new String[]{ GRATICULE_GARS_LEVEL_0, GRATICULE_GARS_LEVEL_1, GRATICULE_GARS_LEVEL_2, - GRATICULE_GARS_LEVEL_3, - }; + GRATICULE_GARS_LEVEL_3,}; } - protected String getTypeFor(double resolution) - { - if (resolution >= 10) + protected String getTypeFor(double resolution) { + if (resolution >= 10) { return GRATICULE_GARS_LEVEL_0; - else if (resolution >= 0.5) + } else if (resolution >= 0.5) { return GRATICULE_GARS_LEVEL_1; - else if (resolution >= .25) + } else if (resolution >= .25) { return GRATICULE_GARS_LEVEL_2; - else if (resolution >= 5.0 / 60.0) + } else if (resolution >= 5.0 / 60.0) { return GRATICULE_GARS_LEVEL_3; + } return null; } - protected void clear(DrawContext dc) - { + protected void clear(DrawContext dc) { super.clear(dc); this.latitudeLabels.clear(); this.longitudeLabels.clear(); this.applyTerrainConformance(); } - private void applyTerrainConformance() - { + private void applyTerrainConformance() { String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { getRenderingParams(type).setValue( - GraticuleRenderingParams.KEY_LINE_CONFORMANCE, this.terrainConformance); + GraticuleRenderingParams.KEY_LINE_CONFORMANCE, this.terrainConformance); } } @@ -223,40 +207,34 @@ private void applyTerrainConformance() * * @param dc the current DrawContext. */ - protected void selectRenderables(DrawContext dc) - { + protected void selectRenderables(DrawContext dc) { ArrayList tileList = getVisibleTiles(dc); - if (tileList.size() > 0) - { - for (GraticuleTile gz : tileList) - { + if (tileList.size() > 0) { + for (GraticuleTile gz : tileList) { // Select tile visible elements gz.selectRenderables(dc); } } } - protected ArrayList getVisibleTiles(DrawContext dc) - { + protected ArrayList getVisibleTiles(DrawContext dc) { ArrayList tileList = new ArrayList(); Sector vs = dc.getVisibleSector(); - if (vs != null) - { + if (vs != null) { Rectangle2D gridRectangle = getGridRectangleForSector(vs); - if (gridRectangle != null) - { + if (gridRectangle != null) { for (int row = (int) gridRectangle.getY(); row <= gridRectangle.getY() + gridRectangle.getHeight(); - row++) - { + row++) { for (int col = (int) gridRectangle.getX(); col <= gridRectangle.getX() + gridRectangle.getWidth(); - col++) - { - if (gridTiles[row][col] == null) + col++) { + if (gridTiles[row][col] == null) { gridTiles[row][col] = new GraticuleTile(getGridSector(row, col), 20, 0); - if (gridTiles[row][col].isInView(dc)) + } + if (gridTiles[row][col].isInView(dc)) { tileList.add(gridTiles[row][col]); - else + } else { gridTiles[row][col].clearRenderables(); + } } } } @@ -264,8 +242,7 @@ protected ArrayList getVisibleTiles(DrawContext dc) return tileList; } - private Rectangle2D getGridRectangleForSector(Sector sector) - { + private Rectangle2D getGridRectangleForSector(Sector sector) { int x1 = getGridColumn(sector.getMinLongitude().degrees); int x2 = getGridColumn(sector.getMaxLongitude().degrees); int y1 = getGridRow(sector.getMinLatitude().degrees); @@ -273,8 +250,7 @@ private Rectangle2D getGridRectangleForSector(Sector sector) return new Rectangle(x1, y1, x2 - x1, y2 - y1); } - private Sector getGridSector(int row, int col) - { + private Sector getGridSector(int row, int col) { int minLat = -90 + row * 10; int maxLat = minLat + 10; int minLon = -180 + col * 10; @@ -282,26 +258,20 @@ private Sector getGridSector(int row, int col) return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); } - private int getGridColumn(Double longitude) - { + private int getGridColumn(Double longitude) { int col = (int) Math.floor((longitude + 180) / 10d); return Math.min(col, 35); } - private int getGridRow(Double latitude) - { + private int getGridRow(Double latitude) { int row = (int) Math.floor((latitude + 90) / 10d); return Math.min(row, 17); } - protected void clearTiles() - { - for (int row = 0; row < 18; row++) - { - for (int col = 0; col < 36; col++) - { - if (this.gridTiles[row][col] != null) - { + protected void clearTiles() { + for (int row = 0; row < 18; row++) { + for (int col = 0; col < 36; col++) { + if (this.gridTiles[row][col] != null) { this.gridTiles[row][col].clearRenderables(); this.gridTiles[row][col] = null; } @@ -309,81 +279,71 @@ protected void clearTiles() } } - protected String makeAngleLabel(Angle angle, double resolution) - { + protected String makeAngleLabel(Angle angle, double resolution) { double epsilon = .000000001; String label; - if (this.getAngleFormat().equals(Angle.ANGLE_FORMAT_DMS)) - { - if (resolution >= 1) + if (this.getAngleFormat().equals(Angle.ANGLE_FORMAT_DMS)) { + if (resolution >= 1) { label = angle.toDecimalDegreesString(0); - else - { + } else { double[] dms = angle.toDMS(); - if (dms[1] < epsilon && dms[2] < epsilon) + if (dms[1] < epsilon && dms[2] < epsilon) { label = String.format("%4d\u00B0", (int) dms[0]); - else if (dms[2] < epsilon) + } else if (dms[2] < epsilon) { label = String.format("%4d\u00B0 %2d\u2019", (int) dms[0], (int) dms[1]); - else + } else { label = angle.toDMSString(); + } } - } - else if (this.getAngleFormat().equals(Angle.ANGLE_FORMAT_DM)) - { - if (resolution >= 1) + } else if (this.getAngleFormat().equals(Angle.ANGLE_FORMAT_DM)) { + if (resolution >= 1) { label = angle.toDecimalDegreesString(0); - else - { + } else { double[] dms = angle.toDMS(); - if (dms[1] < epsilon && dms[2] < epsilon) + if (dms[1] < epsilon && dms[2] < epsilon) { label = String.format("%4d\u00B0", (int) dms[0]); - else if (dms[2] < epsilon) + } else if (dms[2] < epsilon) { label = String.format("%4d\u00B0 %2d\u2019", (int) dms[0], (int) dms[1]); - else + } else { label = angle.toDMString(); + } } - } - else // default to decimal degrees + } else // default to decimal degrees { - if (resolution >= 1) + if (resolution >= 1) { label = angle.toDecimalDegreesString(0); - else if (resolution >= .1) + } else if (resolution >= .1) { label = angle.toDecimalDegreesString(1); - else if (resolution >= .01) + } else if (resolution >= .01) { label = angle.toDecimalDegreesString(2); - else if (resolution >= .001) + } else if (resolution >= .001) { label = angle.toDecimalDegreesString(3); - else + } else { label = angle.toDecimalDegreesString(4); + } } return label; } protected void addLevel0Label(double value, String labelType, String graticuleType, double resolution, - LatLon labelOffset) - { - if (labelType.equals(GridElement.TYPE_LATITUDE_LABEL)) - { - if (!graticuleType.equals(GRATICULE_GARS_LEVEL_0) || !this.latitudeLabels.contains(value)) - { + LatLon labelOffset) { + if (labelType.equals(GridElement.TYPE_LATITUDE_LABEL)) { + if (!graticuleType.equals(GRATICULE_GARS_LEVEL_0) || !this.latitudeLabels.contains(value)) { this.latitudeLabels.add(value); String label = makeAngleLabel(Angle.fromDegrees(value), resolution); GeographicText text = new UserFacingText(label, - Position.fromDegrees(value, labelOffset.getLongitude().degrees, 0)); + Position.fromDegrees(value, labelOffset.getLongitude().degrees, 0)); text.setPriority(resolution * 1e6); this.addRenderable(text, graticuleType); } - } - else if (labelType.equals(GridElement.TYPE_LONGITUDE_LABEL)) - { - if (!graticuleType.equals(GRATICULE_GARS_LEVEL_0) || !this.longitudeLabels.contains(value)) - { + } else if (labelType.equals(GridElement.TYPE_LONGITUDE_LABEL)) { + if (!graticuleType.equals(GRATICULE_GARS_LEVEL_0) || !this.longitudeLabels.contains(value)) { this.longitudeLabels.add(value); String label = makeAngleLabel(Angle.fromDegrees(value), resolution); GeographicText text = new UserFacingText(label, - Position.fromDegrees(labelOffset.getLatitude().degrees, value, 0)); + Position.fromDegrees(labelOffset.getLatitude().degrees, value, 0)); text.setPriority(resolution * 1e6); this.addRenderable(text, graticuleType); } @@ -393,17 +353,14 @@ else if (labelType.equals(GridElement.TYPE_LONGITUDE_LABEL)) protected static ArrayList latLabels = new ArrayList(360); protected static ArrayList lonLabels = new ArrayList(720); protected static String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ"; - protected static String[][] level2Labels = new String[][] {{"3", "4"}, {"1", "2"}}; + protected static String[][] level2Labels = new String[][]{{"3", "4"}, {"1", "2"}}; - static - { - for (int i = 1; i <= 720; i++) - { + static { + for (int i = 1; i <= 720; i++) { lonLabels.add(String.format("%03d", i)); } - for (int i = 0; i < 360; i++) - { + for (int i = 0; i < 360; i++) { int length = chars.length(); int i1 = i / length; int i2 = i % length; @@ -411,34 +368,27 @@ else if (labelType.equals(GridElement.TYPE_LONGITUDE_LABEL)) } } - protected String makeLabel(Sector sector, String graticuleType) - { - if (graticuleType.equals(GRATICULE_GARS_LEVEL_1)) - { + protected String makeLabel(Sector sector, String graticuleType) { + if (graticuleType.equals(GRATICULE_GARS_LEVEL_1)) { int iLat = (int) ((90 + sector.getCentroid().getLatitude().degrees) * 60 / 30); int iLon = (int) ((180 + sector.getCentroid().getLongitude().degrees) * 60 / 30); return lonLabels.get(iLon) + latLabels.get(iLat); - } - else if (graticuleType.equals(GRATICULE_GARS_LEVEL_2)) - { + } else if (graticuleType.equals(GRATICULE_GARS_LEVEL_2)) { int minutesLat = (int) ((90 + sector.getMinLatitude().degrees) * 60); int j = (minutesLat % 30) / 15; int minutesLon = (int) ((180 + sector.getMinLongitude().degrees) * 60); int i = (minutesLon % 30) / 15; return level2Labels[j][i]; - } - else - { + } else { return ""; } } // --- Graticule tile ---------------------------------------------------------------------- + protected class GraticuleTile { - protected class GraticuleTile - { private Sector sector; private int divisions; private int level; @@ -446,126 +396,113 @@ protected class GraticuleTile private ArrayList gridElements; private ArrayList subTiles; - public GraticuleTile(Sector sector, int divisions, int level) - { + public GraticuleTile(Sector sector, int divisions, int level) { this.sector = sector; this.divisions = divisions; this.level = level; } - public Extent getExtent(Globe globe, double ve) - { + public Extent getExtent(Globe globe, double ve) { return Sector.computeBoundingCylinder(globe, ve, this.sector); } @SuppressWarnings({"RedundantIfStatement"}) - public boolean isInView(DrawContext dc) - { + public boolean isInView(DrawContext dc) { if (!dc.getView().getFrustumInModelCoordinates().intersects( - this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) + this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) { return false; + } - if (this.level != 0) - { - if (dc.getView().getEyePosition().getAltitude() > thresholds[this.level - 1]) + if (this.level != 0) { + if (dc.getView().getEyePosition().getAltitude() > thresholds[this.level - 1]) { return false; + } } return true; } - public double getSizeInPixels(DrawContext dc) - { + public double getSizeInPixels(DrawContext dc) { View view = dc.getView(); Vec4 centerPoint = getSurfacePoint(dc, this.sector.getCentroid().getLatitude(), - this.sector.getCentroid().getLongitude()); + this.sector.getCentroid().getLongitude()); double distance = view.getEyePoint().distanceTo3(centerPoint); double tileSizeMeter = this.sector.getDeltaLatRadians() * dc.getGlobe().getRadius(); return tileSizeMeter / view.computePixelSizeAtDistance(distance); } - public void selectRenderables(DrawContext dc) - { - if (this.gridElements == null) + public void selectRenderables(DrawContext dc) { + if (this.gridElements == null) { this.createRenderables(); + } String graticuleType = getTypeFor(this.sector.getDeltaLatDegrees()); - if (this.level == 0 && dc.getView().getEyePosition().getAltitude() > thresholds[0]) - { + if (this.level == 0 && dc.getView().getEyePosition().getAltitude() > thresholds[0]) { LatLon labelOffset = computeLabelOffset(dc); - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc)) - { + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc)) { // Add level zero bounding lines and labels if (ge.type.equals(GridElement.TYPE_LINE_SOUTH) || ge.type.equals(GridElement.TYPE_LINE_NORTH) - || ge.type.equals(GridElement.TYPE_LINE_WEST)) - { + || ge.type.equals(GridElement.TYPE_LINE_WEST)) { addRenderable(ge.renderable, graticuleType); String labelType = ge.type.equals(GridElement.TYPE_LINE_SOUTH) - || ge.type.equals(GridElement.TYPE_LINE_NORTH) ? - GridElement.TYPE_LATITUDE_LABEL : GridElement.TYPE_LONGITUDE_LABEL; + || ge.type.equals(GridElement.TYPE_LINE_NORTH) + ? GridElement.TYPE_LATITUDE_LABEL : GridElement.TYPE_LONGITUDE_LABEL; GARSGraticuleLayer.this.addLevel0Label(ge.value, labelType, graticuleType, - this.sector.getDeltaLatDegrees(), labelOffset); + this.sector.getDeltaLatDegrees(), labelOffset); } } } - if (dc.getView().getEyePosition().getAltitude() > thresholds[0]) + if (dc.getView().getEyePosition().getAltitude() > thresholds[0]) { return; + } } // Select tile grid elements double eyeDistance = dc.getView().getEyePosition().getAltitude(); if (this.level == 0 && eyeDistance <= thresholds[0] - || this.level == 1 && eyeDistance <= thresholds[1] - || this.level == 2) - { + || this.level == 1 && eyeDistance <= thresholds[1] + || this.level == 2) { double resolution = this.sector.getDeltaLatDegrees() / this.divisions; graticuleType = getTypeFor(resolution); - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc)) - { + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc)) { addRenderable(ge.renderable, graticuleType); } } } - if (this.level == 0 && eyeDistance > thresholds[1]) + if (this.level == 0 && eyeDistance > thresholds[1]) { return; - else if (this.level == 1 && eyeDistance > thresholds[2]) + } else if (this.level == 1 && eyeDistance > thresholds[2]) { return; - else if (this.level == 2) + } else if (this.level == 2) { return; + } // Select child elements - if (this.subTiles == null) + if (this.subTiles == null) { createSubTiles(); - for (GraticuleTile gt : this.subTiles) - { - if (gt.isInView(dc)) - { + } + for (GraticuleTile gt : this.subTiles) { + if (gt.isInView(dc)) { gt.selectRenderables(dc); - } - else + } else { gt.clearRenderables(); + } } } - public void clearRenderables() - { - if (this.gridElements != null) - { + public void clearRenderables() { + if (this.gridElements != null) { this.gridElements.clear(); this.gridElements = null; } - if (this.subTiles != null) - { - for (GraticuleTile gt : this.subTiles) - { + if (this.subTiles != null) { + for (GraticuleTile gt : this.subTiles) { gt.clearRenderables(); } this.subTiles.clear(); @@ -573,33 +510,32 @@ public void clearRenderables() } } - private void createSubTiles() - { + private void createSubTiles() { this.subTiles = new ArrayList(); Sector[] sectors = this.sector.subdivide(this.divisions); int nextLevel = this.level + 1; int subDivisions = 10; - if (nextLevel == 1) + if (nextLevel == 1) { subDivisions = 2; - else if (nextLevel == 2) + } else if (nextLevel == 2) { subDivisions = 3; - for (Sector s : sectors) - { + } + for (Sector s : sectors) { this.subTiles.add(new GraticuleTile(s, subDivisions, nextLevel)); } } - /** Create the grid elements */ - private void createRenderables() - { + /** + * Create the grid elements + */ + private void createRenderables() { this.gridElements = new ArrayList(); double step = sector.getDeltaLatDegrees() / this.divisions; // Generate meridians with labels double lon = sector.getMinLongitude().degrees + (this.level == 0 ? 0 : step); - while (lon < sector.getMaxLongitude().degrees - step / 2) - { + while (lon < sector.getMaxLongitude().degrees - step / 2) { Angle longitude = Angle.fromDegrees(lon); // Meridian ArrayList positions = new ArrayList(2); @@ -608,9 +544,9 @@ private void createRenderables() Object line = createLineRenderable(positions, AVKey.LINEAR); Sector sector = Sector.fromDegrees( - this.sector.getMinLatitude().degrees, this.sector.getMaxLatitude().degrees, lon, lon); - String lineType = lon == this.sector.getMinLongitude().degrees ? - GridElement.TYPE_LINE_WEST : GridElement.TYPE_LINE; + this.sector.getMinLatitude().degrees, this.sector.getMaxLatitude().degrees, lon, lon); + String lineType = lon == this.sector.getMinLongitude().degrees + ? GridElement.TYPE_LINE_WEST : GridElement.TYPE_LINE; GridElement ge = new GridElement(sector, line, lineType); ge.value = lon; this.gridElements.add(ge); @@ -621,8 +557,7 @@ private void createRenderables() // Generate parallels double lat = this.sector.getMinLatitude().degrees + (this.level == 0 ? 0 : step); - while (lat < this.sector.getMaxLatitude().degrees - step / 2) - { + while (lat < this.sector.getMaxLatitude().degrees - step / 2) { Angle latitude = Angle.fromDegrees(lat); ArrayList positions = new ArrayList(2); positions.add(new Position(latitude, this.sector.getMinLongitude(), 0)); @@ -630,9 +565,9 @@ private void createRenderables() Object line = createLineRenderable(positions, AVKey.LINEAR); Sector sector = Sector.fromDegrees( - lat, lat, this.sector.getMinLongitude().degrees, this.sector.getMaxLongitude().degrees); - String lineType = lat == this.sector.getMinLatitude().degrees ? - GridElement.TYPE_LINE_SOUTH : GridElement.TYPE_LINE; + lat, lat, this.sector.getMinLongitude().degrees, this.sector.getMaxLongitude().degrees); + String lineType = lat == this.sector.getMinLatitude().degrees + ? GridElement.TYPE_LINE_SOUTH : GridElement.TYPE_LINE; GridElement ge = new GridElement(sector, line, lineType); ge.value = lat; this.gridElements.add(ge); @@ -642,36 +577,30 @@ private void createRenderables() } // Draw and label a parallel at the top of the graticule. The line is apparent only on 2D globes. - if (this.sector.getMaxLatitude().equals(Angle.POS90)) - { + if (this.sector.getMaxLatitude().equals(Angle.POS90)) { ArrayList positions = new ArrayList(2); positions.add(new Position(Angle.POS90, this.sector.getMinLongitude(), 0)); positions.add(new Position(Angle.POS90, this.sector.getMaxLongitude(), 0)); Object line = createLineRenderable(positions, AVKey.LINEAR); Sector sector = Sector.fromDegrees( - 90, 90, this.sector.getMinLongitude().degrees, this.sector.getMaxLongitude().degrees); + 90, 90, this.sector.getMinLongitude().degrees, this.sector.getMaxLongitude().degrees); GridElement ge = new GridElement(sector, line, GridElement.TYPE_LINE_NORTH); ge.value = 90; this.gridElements.add(ge); } double resolution = this.sector.getDeltaLatDegrees() / this.divisions; - if (this.level == 0) - { + if (this.level == 0) { Sector[] sectors = this.sector.subdivide(20); - for (int j = 0; j < 20; j++) - { - for (int i = 0; i < 20; i++) - { + for (int j = 0; j < 20; j++) { + for (int i = 0; i < 20; i++) { Sector sector = sectors[j * 20 + i]; String label = makeLabel(sector, GRATICULE_GARS_LEVEL_1); addLabel(label, sectors[j * 20 + i], resolution); } } - } - else if (this.level == 1) - { + } else if (this.level == 1) { String label = makeLabel(this.sector, GRATICULE_GARS_LEVEL_1); Sector[] sectors = this.sector.subdivide(); @@ -679,9 +608,7 @@ else if (this.level == 1) addLabel(label + "4", sectors[1], resolution); addLabel(label + "1", sectors[2], resolution); addLabel(label + "2", sectors[3], resolution); - } - else if (this.level == 2) - { + } else if (this.level == 2) { String label = makeLabel(this.sector, GRATICULE_GARS_LEVEL_1); label += makeLabel(this.sector, GRATICULE_GARS_LEVEL_2); @@ -699,8 +626,7 @@ else if (this.level == 2) } } - protected void addLabel(String label, Sector sector, double resolution) - { + protected void addLabel(String label, Sector sector, double resolution) { GeographicText text = new UserFacingText(label, new Position(sector.getCentroid(), 0)); text.setPriority(resolution * 1e6); GridElement ge = new GridElement(sector, text, GridElement.TYPE_GRIDZONE_LABEL); diff --git a/src/gov/nasa/worldwind/layers/GraticuleRenderingParams.java b/src/gov/nasa/worldwind/layers/GraticuleRenderingParams.java index b19a3dd3f7..39bad73ea1 100644 --- a/src/gov/nasa/worldwind/layers/GraticuleRenderingParams.java +++ b/src/gov/nasa/worldwind/layers/GraticuleRenderingParams.java @@ -14,8 +14,8 @@ * @author dcollins * @version $Id: GraticuleRenderingParams.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GraticuleRenderingParams extends AVListImpl -{ +public class GraticuleRenderingParams extends AVListImpl { + public static final String KEY_DRAW_LINES = "DrawGraticule"; public static final String KEY_LINE_COLOR = "GraticuleLineColor"; public static final String KEY_LINE_WIDTH = "GraticuleLineWidth"; @@ -28,31 +28,25 @@ public class GraticuleRenderingParams extends AVListImpl public static final String VALUE_LINE_STYLE_DASHED = "LineStyleDashed"; public static final String VALUE_LINE_STYLE_DOTTED = "LineStyleDotted"; - public GraticuleRenderingParams() - { + public GraticuleRenderingParams() { } - public boolean isDrawLines() - { + public boolean isDrawLines() { Object value = getValue(KEY_DRAW_LINES); return value instanceof Boolean ? (Boolean) value : false; } - public void setDrawLines(boolean drawLines) - { + public void setDrawLines(boolean drawLines) { setValue(KEY_DRAW_LINES, drawLines); } - public Color getLineColor() - { + public Color getLineColor() { Object value = getValue(KEY_LINE_COLOR); return value instanceof Color ? (Color) value : null; } - public void setLineColor(Color color) - { - if (color == null) - { + public void setLineColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -61,28 +55,23 @@ public void setLineColor(Color color) setValue(KEY_LINE_COLOR, color); } - public double getLineWidth() - { + public double getLineWidth() { Object value = getValue(KEY_LINE_WIDTH); return value instanceof Double ? (Double) value : 0; } - public void setLineWidth(double lineWidth) - { + public void setLineWidth(double lineWidth) { setValue(KEY_LINE_WIDTH, lineWidth); } - public String getLineStyle() - { + public String getLineStyle() { Object value = getValue(KEY_LINE_STYLE); return value instanceof String ? (String) value : null; } - public void setLineStyle(String lineStyle) - { - if (lineStyle == null) - { + public void setLineStyle(String lineStyle) { + if (lineStyle == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -91,27 +80,22 @@ public void setLineStyle(String lineStyle) setValue(KEY_LINE_STYLE, lineStyle); } - public boolean isDrawLabels() - { + public boolean isDrawLabels() { Object value = getValue(KEY_DRAW_LABELS); return value instanceof Boolean ? (Boolean) value : false; } - public void setDrawLabels(boolean drawLabels) - { + public void setDrawLabels(boolean drawLabels) { setValue(KEY_DRAW_LABELS, drawLabels); } - public Color getLabelColor() - { + public Color getLabelColor() { Object value = getValue(KEY_LABEL_COLOR); return value instanceof Color ? (Color) value : null; } - public void setLabelColor(Color color) - { - if (color == null) - { + public void setLabelColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -120,16 +104,13 @@ public void setLabelColor(Color color) setValue(KEY_LABEL_COLOR, color); } - public Font getLabelFont() - { + public Font getLabelFont() { Object value = getValue(KEY_LABEL_FONT); return value instanceof Font ? (Font) value : null; } - public void setLabelFont(Font font) - { - if (font == null) - { + public void setLabelFont(Font font) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/layers/GraticuleSupport.java b/src/gov/nasa/worldwind/layers/GraticuleSupport.java index ba980af0b6..cc1de6e09f 100644 --- a/src/gov/nasa/worldwind/layers/GraticuleSupport.java +++ b/src/gov/nasa/worldwind/layers/GraticuleSupport.java @@ -16,40 +16,41 @@ * @author dcollins * @version $Id: GraticuleSupport.java 2372 2014-10-10 18:32:15Z tgaskins $ */ -public class GraticuleSupport -{ - private static class Pair - { +public class GraticuleSupport { + + private static class Pair { + final Object a; final Object b; - Pair(Object a, Object b) - { + Pair(Object a, Object b) { this.a = a; this.b = b; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } Pair pair = (Pair) o; - if (a != null ? !a.equals(pair.a) : pair.a != null) + if (a != null ? !a.equals(pair.a) : pair.a != null) { return false; - if (b != null ? !b.equals(pair.b) : pair.b != null) + } + if (b != null ? !b.equals(pair.b) : pair.b != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = a != null ? a.hashCode() : 0; result = 31 * result + (b != null ? b.hashCode() : 0); return result; @@ -62,8 +63,7 @@ public int hashCode() private AVList defaultParams; private GeographicTextRenderer textRenderer = new GeographicTextRenderer(); - public GraticuleSupport() - { + public GraticuleSupport() { this.textRenderer.setEffect(AVKey.TEXT_EFFECT_SHADOW); // Keep labels separated by at least two pixels this.textRenderer.setCullTextEnabled(true); @@ -73,10 +73,8 @@ public GraticuleSupport() this.textRenderer.setDistanceMinOpacity(.5); } - public void addRenderable(Object renderable, String paramsKey) - { - if (renderable == null) - { + public void addRenderable(Object renderable, String paramsKey) { + if (renderable == null) { String message = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -85,20 +83,16 @@ public void addRenderable(Object renderable, String paramsKey) this.renderables.add(new Pair(renderable, paramsKey)); } - public void removeAllRenderables() - { + public void removeAllRenderables() { this.renderables.clear(); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { this.render(dc, 1); } - public void render(DrawContext dc, double opacity) - { - if (dc == null) - { + public void render(DrawContext dc, double opacity) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -108,24 +102,18 @@ public void render(DrawContext dc, double opacity) // Render lines and collect text labels Collection text = new ArrayList(); - for (Pair pair : this.renderables) - { + for (Pair pair : this.renderables) { Object renderable = pair.a; String paramsKey = (pair.b != null && pair.b instanceof String) ? (String) pair.b : null; GraticuleRenderingParams renderingParams = paramsKey != null ? this.namedParams.get(paramsKey) : null; - if (renderable != null && renderable instanceof Path) - { - if (renderingParams == null || renderingParams.isDrawLines()) - { + if (renderable != null && renderable instanceof Path) { + if (renderingParams == null || renderingParams.isDrawLines()) { applyRenderingParams(paramsKey, renderingParams, (Path) renderable, opacity); ((Path) renderable).render(dc); } - } - else if (renderable != null && renderable instanceof GeographicText) - { - if (renderingParams == null || renderingParams.isDrawLabels()) - { + } else if (renderable != null && renderable instanceof GeographicText) { + if (renderingParams == null || renderingParams.isDrawLabels()) { applyRenderingParams(renderingParams, (GeographicText) renderable, opacity); text.add((GeographicText) renderable); } @@ -136,22 +124,20 @@ else if (renderable != null && renderable instanceof GeographicText) this.textRenderer.render(dc, text); } - public GraticuleRenderingParams getRenderingParams(String key) - { - if (key == null) - { + public GraticuleRenderingParams getRenderingParams(String key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } GraticuleRenderingParams value = this.namedParams.get(key); - if (value == null) - { + if (value == null) { value = new GraticuleRenderingParams(); initRenderingParams(value); - if (this.defaultParams != null) + if (this.defaultParams != null) { value.setValues(this.defaultParams); + } this.namedParams.put(key, value); } @@ -159,15 +145,12 @@ public GraticuleRenderingParams getRenderingParams(String key) return value; } - public Collection> getAllRenderingParams() - { + public Collection> getAllRenderingParams() { return this.namedParams.entrySet(); } - public void setRenderingParams(String key, GraticuleRenderingParams renderingParams) - { - if (key == null) - { + public void setRenderingParams(String key, GraticuleRenderingParams renderingParams) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -177,58 +160,58 @@ public void setRenderingParams(String key, GraticuleRenderingParams renderingPar this.namedParams.put(key, renderingParams); } - public AVList getDefaultParams() - { + public AVList getDefaultParams() { return this.defaultParams; } - public void setDefaultParams(AVList defaultParams) - { + public void setDefaultParams(AVList defaultParams) { this.defaultParams = defaultParams; } - private AVList initRenderingParams(AVList params) - { - if (params == null) - { + private AVList initRenderingParams(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params.getValue(GraticuleRenderingParams.KEY_DRAW_LINES) == null) + if (params.getValue(GraticuleRenderingParams.KEY_DRAW_LINES) == null) { params.setValue(GraticuleRenderingParams.KEY_DRAW_LINES, Boolean.TRUE); + } - if (params.getValue(GraticuleRenderingParams.KEY_LINE_COLOR) == null) + if (params.getValue(GraticuleRenderingParams.KEY_LINE_COLOR) == null) { params.setValue(GraticuleRenderingParams.KEY_LINE_COLOR, Color.WHITE); + } - if (params.getValue(GraticuleRenderingParams.KEY_LINE_WIDTH) == null) - //noinspection UnnecessaryBoxing + if (params.getValue(GraticuleRenderingParams.KEY_LINE_WIDTH) == null) //noinspection UnnecessaryBoxing + { params.setValue(GraticuleRenderingParams.KEY_LINE_WIDTH, new Double(1)); + } - if (params.getValue(GraticuleRenderingParams.KEY_LINE_STYLE) == null) + if (params.getValue(GraticuleRenderingParams.KEY_LINE_STYLE) == null) { params.setValue(GraticuleRenderingParams.KEY_LINE_STYLE, GraticuleRenderingParams.VALUE_LINE_STYLE_SOLID); + } - if (params.getValue(GraticuleRenderingParams.KEY_DRAW_LABELS) == null) + if (params.getValue(GraticuleRenderingParams.KEY_DRAW_LABELS) == null) { params.setValue(GraticuleRenderingParams.KEY_DRAW_LABELS, Boolean.TRUE); + } - if (params.getValue(GraticuleRenderingParams.KEY_LABEL_COLOR) == null) + if (params.getValue(GraticuleRenderingParams.KEY_LABEL_COLOR) == null) { params.setValue(GraticuleRenderingParams.KEY_LABEL_COLOR, Color.WHITE); + } - if (params.getValue(GraticuleRenderingParams.KEY_LABEL_FONT) == null) + if (params.getValue(GraticuleRenderingParams.KEY_LABEL_FONT) == null) { params.setValue(GraticuleRenderingParams.KEY_LABEL_FONT, Font.decode("Arial-Bold-12")); + } return params; } - private void applyRenderingParams(AVList params, GeographicText text, double opacity) - { - if (params != null && text != null) - { + private void applyRenderingParams(AVList params, GeographicText text, double opacity) { + if (params != null && text != null) { // Apply "label" properties to the GeographicText. Object o = params.getValue(GraticuleRenderingParams.KEY_LABEL_COLOR); - if (o != null && o instanceof Color) - { + if (o != null && o instanceof Color) { Color color = applyOpacity((Color) o, opacity); float[] compArray = new float[4]; Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), compArray); @@ -238,70 +221,56 @@ private void applyRenderingParams(AVList params, GeographicText text, double opa } o = params.getValue(GraticuleRenderingParams.KEY_LABEL_FONT); - if (o != null && o instanceof Font) - { + if (o != null && o instanceof Font) { text.setFont((Font) o); } } } - private void applyRenderingParams(String key, AVList params, Path path, double opacity) - { - if (key != null && params != null && path != null) - { + private void applyRenderingParams(String key, AVList params, Path path, double opacity) { + if (key != null && params != null && path != null) { path.setAttributes(this.getLineShapeAttributes(key, params, opacity)); } } - private ShapeAttributes getLineShapeAttributes(String key, AVList params, double opacity) - { + private ShapeAttributes getLineShapeAttributes(String key, AVList params, double opacity) { ShapeAttributes attrs = this.namedShapeAttributes.get(key); - if (attrs == null) - { + if (attrs == null) { attrs = createLineShapeAttributes(params, opacity); this.namedShapeAttributes.put(key, attrs); } return attrs; } - private ShapeAttributes createLineShapeAttributes(AVList params, double opacity) - { + private ShapeAttributes createLineShapeAttributes(AVList params, double opacity) { ShapeAttributes attrs = new BasicShapeAttributes(); attrs.setDrawInterior(false); attrs.setDrawOutline(true); - if (params != null) - { + if (params != null) { // Apply "line" properties. Object o = params.getValue(GraticuleRenderingParams.KEY_LINE_COLOR); - if (o != null && o instanceof Color) - { + if (o != null && o instanceof Color) { attrs.setOutlineMaterial(new Material(applyOpacity((Color) o, opacity))); attrs.setOutlineOpacity(opacity); } Double lineWidth = AVListImpl.getDoubleValue(params, GraticuleRenderingParams.KEY_LINE_WIDTH); - if (lineWidth != null) - { + if (lineWidth != null) { attrs.setOutlineWidth(lineWidth); } String s = params.getStringValue(GraticuleRenderingParams.KEY_LINE_STYLE); // Draw a solid line. - if (GraticuleRenderingParams.VALUE_LINE_STYLE_SOLID.equalsIgnoreCase(s)) - { + if (GraticuleRenderingParams.VALUE_LINE_STYLE_SOLID.equalsIgnoreCase(s)) { attrs.setOutlineStipplePattern((short) 0xAAAA); attrs.setOutlineStippleFactor(0); - } - // Draw the line as longer strokes with space in between. - else if (GraticuleRenderingParams.VALUE_LINE_STYLE_DASHED.equalsIgnoreCase(s)) - { + } // Draw the line as longer strokes with space in between. + else if (GraticuleRenderingParams.VALUE_LINE_STYLE_DASHED.equalsIgnoreCase(s)) { int baseFactor = (int) (lineWidth != null ? Math.round(lineWidth) : 1.0); attrs.setOutlineStipplePattern((short) 0xAAAA); attrs.setOutlineStippleFactor(3 * baseFactor); - } - // Draw the line as a evenly spaced "square" dots. - else if (GraticuleRenderingParams.VALUE_LINE_STYLE_DOTTED.equalsIgnoreCase(s)) - { + } // Draw the line as a evenly spaced "square" dots. + else if (GraticuleRenderingParams.VALUE_LINE_STYLE_DOTTED.equalsIgnoreCase(s)) { int baseFactor = (int) (lineWidth != null ? Math.round(lineWidth) : 1.0); attrs.setOutlineStipplePattern((short) 0xAAAA); attrs.setOutlineStippleFactor(baseFactor); @@ -310,10 +279,10 @@ else if (GraticuleRenderingParams.VALUE_LINE_STYLE_DOTTED.equalsIgnoreCase(s)) return attrs; } - private Color applyOpacity(Color color, double opacity) - { - if (opacity >= 1) + private Color applyOpacity(Color color, double opacity) { + if (opacity >= 1) { return color; + } float[] compArray = color.getRGBComponents(null); return new Color(compArray[0], compArray[1], compArray[2], compArray[3] * (float) opacity); diff --git a/src/gov/nasa/worldwind/layers/IconLayer.java b/src/gov/nasa/worldwind/layers/IconLayer.java index 2adabc309a..c1323cff17 100644 --- a/src/gov/nasa/worldwind/layers/IconLayer.java +++ b/src/gov/nasa/worldwind/layers/IconLayer.java @@ -15,16 +15,16 @@ /** * The IconLayer class manages a collection of {@link gov.nasa.worldwind.render.WWIcon} objects for - * rendering and picking. IconLayer delegates to its internal {@link gov.nasa.worldwind.render.IconRenderer} - * for rendering and picking operations. + * rendering and picking. IconLayer delegates to its internal + * {@link gov.nasa.worldwind.render.IconRenderer} for rendering and picking operations. * * @author tag * @version $Id: IconLayer.java 2140 2014-07-10 18:56:05Z tgaskins $ * @see gov.nasa.worldwind.render.WWIcon * @see gov.nasa.worldwind.render.IconRenderer */ -public class IconLayer extends AbstractLayer -{ +public class IconLayer extends AbstractLayer { + protected final BasicQuadTree icons = new BasicQuadTree(8, Sector.FULL_SPHERE, null, false); protected Iterable iconsOverride; protected IconRenderer iconRenderer = new IconRenderer(); @@ -35,9 +35,10 @@ public class IconLayer extends AbstractLayer protected HashMap> lastActiveIconsLists = new HashMap>(1); protected long frameId; - /** Creates a new IconLayer with an empty collection of Icons. */ - public IconLayer() - { + /** + * Creates a new IconLayer with an empty collection of Icons. + */ + public IconLayer() { } /** @@ -47,18 +48,15 @@ public IconLayer() * @param icon Icon to add. * * @throws IllegalArgumentException If icon is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setIcons. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setIcons. */ - public void addIcon(WWIcon icon) - { - if (icon == null) - { + public void addIcon(WWIcon icon) { + if (icon == null) { String msg = Logging.getMessage("nullValue.Icon"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.iconsOverride != null) - { + if (this.iconsOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -74,28 +72,25 @@ public void addIcon(WWIcon icon) * @param icons Icons to add. * * @throws IllegalArgumentException If icons is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setIcons. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setIcons. */ - public void addIcons(Iterable icons) - { - if (icons == null) - { + public void addIcons(Iterable icons) { + if (icons == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.iconsOverride != null) - { + if (this.iconsOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - for (WWIcon icon : icons) - { + for (WWIcon icon : icons) { // Internal list of icons does not accept null values. - if (icon != null) + if (icon != null) { this.icons.add(icon, icon.getPosition().asDegreesArray()); + } } } @@ -106,18 +101,15 @@ public void addIcons(Iterable icons) * @param icon Icon to remove. * * @throws IllegalArgumentException If icon is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setIcons. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setIcons. */ - public void removeIcon(WWIcon icon) - { - if (icon == null) - { + public void removeIcon(WWIcon icon) { + if (icon == null) { String msg = Logging.getMessage("nullValue.Icon"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.iconsOverride != null) - { + if (this.iconsOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -132,10 +124,8 @@ public void removeIcon(WWIcon icon) * * @throws IllegalStateException If a custom Iterable has been specified by a call to setIcons. */ - public void removeAllIcons() - { - if (this.iconsOverride != null) - { + public void removeAllIcons() { + if (this.iconsOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -144,10 +134,10 @@ public void removeAllIcons() this.clearIcons(); } - protected void clearIcons() - { - if (this.icons != null) + protected void clearIcons() { + if (this.icons != null) { this.icons.clear(); + } } /** @@ -158,13 +148,14 @@ protected void clearIcons() * * @return Iterable of currently active Icons. */ - public Iterable getIcons() - { - if (this.iconsOverride != null) + public Iterable getIcons() { + if (this.iconsOverride != null) { return this.iconsOverride; + } - if (this.icons != null) + if (this.icons != null) { return this.icons; + } return Collections.emptyList(); } @@ -175,8 +166,7 @@ public Iterable getIcons() * * @return regionCulling true if region culling is performed, otherwise false. */ - public boolean isRegionCulling() - { + public boolean isRegionCulling() { return this.regionCulling; } @@ -187,8 +177,7 @@ public boolean isRegionCulling() * * @param regionCulling true if region culling is performed, otherwise false. */ - public void setRegionCulling(boolean regionCulling) - { + public void setRegionCulling(boolean regionCulling) { this.regionCulling = regionCulling; } @@ -202,23 +191,26 @@ public void setRegionCulling(boolean regionCulling) * * @return Iterable of currently active Icons. */ - protected Iterable getActiveIcons(DrawContext dc) - { - if (this.iconsOverride != null) + protected Iterable getActiveIcons(DrawContext dc) { + if (this.iconsOverride != null) { return this.iconsOverride; + } // Use the active icons computed in the pick pass. Set lastActiveIcons = this.lastActiveIconsLists.get(dc.getGlobe().getGlobeStateKey()); this.lastActiveIconsLists.remove(dc.getGlobe().getGlobeStateKey()); // remove it on re-use - if (lastActiveIcons != null && this.frameId == dc.getFrameTimeStamp()) + if (lastActiveIcons != null && this.frameId == dc.getFrameTimeStamp()) { return lastActiveIcons; + } - if (!this.isRegionCulling()) + if (!this.isRegionCulling()) { return this.icons; + } SectorGeometryList sgList = dc.getSurfaceGeometry(); - if (sgList == null || sgList.size() == 0) + if (sgList == null || sgList.size() == 0) { return Collections.emptyList(); + } lastActiveIcons = this.icons.getItemsInRegions(sgList, new HashSet()); this.lastActiveIconsLists.put(dc.getGlobe().getGlobeStateKey(), lastActiveIcons); @@ -237,10 +229,9 @@ protected Iterable getActiveIcons(DrawContext dc) * collection. * * @param iconIterable Iterable to use instead of this layer's internal collection, or null to use this layer's - * internal collection. + * internal collection. */ - public void setIcons(Iterable iconIterable) - { + public void setIcons(Iterable iconIterable) { this.iconsOverride = iconIterable; // Clear the internal collection of Icons. clearIcons(); @@ -251,8 +242,7 @@ public void setIcons(Iterable iconIterable) * * @return Pedestal used by this layers internal IconRenderer. */ - public Pedestal getPedestal() - { + public Pedestal getPedestal() { return pedestal; } @@ -261,8 +251,7 @@ public Pedestal getPedestal() * * @param pedestal Pedestal to be used by this layers internal IconRenderer. */ - public void setPedestal(Pedestal pedestal) - { + public void setPedestal(Pedestal pedestal) { this.pedestal = pedestal; } @@ -273,8 +262,7 @@ public void setPedestal(Pedestal pedestal) * * @see #setHorizonClippingEnabled(boolean) */ - public boolean isHorizonClippingEnabled() - { + public boolean isHorizonClippingEnabled() { return this.iconRenderer.isHorizonClippingEnabled(); } @@ -283,12 +271,11 @@ public boolean isHorizonClippingEnabled() * view volume inclusion. The default is false, horizon clipping is not performed. * * @param horizonClippingEnabled true if horizon clipping should be performed, otherwise - * false. + * false. * * @see #setViewClippingEnabled(boolean) */ - public void setHorizonClippingEnabled(boolean horizonClippingEnabled) - { + public void setHorizonClippingEnabled(boolean horizonClippingEnabled) { this.iconRenderer.setHorizonClippingEnabled(horizonClippingEnabled); } @@ -299,8 +286,7 @@ public void setHorizonClippingEnabled(boolean horizonClippingEnabled) * * @see #setViewClippingEnabled(boolean) */ - public boolean isViewClippingEnabled() - { + public boolean isViewClippingEnabled() { return this.iconRenderer.isViewClippingEnabled(); } @@ -314,8 +300,7 @@ public boolean isViewClippingEnabled() * * @see #setHorizonClippingEnabled(boolean) */ - public void setViewClippingEnabled(boolean viewClippingEnabled) - { + public void setViewClippingEnabled(boolean viewClippingEnabled) { this.iconRenderer.setViewClippingEnabled(viewClippingEnabled); } @@ -326,8 +311,7 @@ public void setViewClippingEnabled(boolean viewClippingEnabled) * * @see #setViewClippingEnabled(boolean) */ - public boolean isPickFrustumClippingEnabled() - { + public boolean isPickFrustumClippingEnabled() { return this.iconRenderer.isPickFrustumClippingEnabled(); } @@ -337,10 +321,9 @@ public boolean isPickFrustumClippingEnabled() * clipping not be performed. The default is false, picking volume clipping is not performed. * * @param pickFrustumClippingEnabled true if picking clipping should be performed, otherwise - * false. + * false. */ - public void setPickFrustumClippingEnabled(boolean pickFrustumClippingEnabled) - { + public void setPickFrustumClippingEnabled(boolean pickFrustumClippingEnabled) { this.iconRenderer.setPickFrustumClippingEnabled(pickFrustumClippingEnabled); } @@ -349,10 +332,9 @@ public void setPickFrustumClippingEnabled(boolean pickFrustumClippingEnabled) * level. * * @return true if icon elevations are treated as absolute, false if they're treated as - * offsets from the terrain. + * offsets from the terrain. */ - public boolean isAlwaysUseAbsoluteElevation() - { + public boolean isAlwaysUseAbsoluteElevation() { return this.iconRenderer.isAlwaysUseAbsoluteElevation(); } @@ -362,10 +344,9 @@ public boolean isAlwaysUseAbsoluteElevation() * absolute elevation above sea level. * * @param alwaysUseAbsoluteElevation true to treat icon elevations as absolute, false to - * treat them as offsets from the terrain. + * treat them as offsets from the terrain. */ - public void setAlwaysUseAbsoluteElevation(boolean alwaysUseAbsoluteElevation) - { + public void setAlwaysUseAbsoluteElevation(boolean alwaysUseAbsoluteElevation) { this.iconRenderer.setAlwaysUseAbsoluteElevation(alwaysUseAbsoluteElevation); } @@ -375,8 +356,7 @@ public void setAlwaysUseAbsoluteElevation(boolean alwaysUseAbsoluteElevation) * @param opacity the current opacity value, which is ignored by this layer. */ @Override - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { super.setOpacity(opacity); } @@ -387,8 +367,7 @@ public void setOpacity(double opacity) * @return The layer opacity, a value between 0 and 1. */ @Override - public double getOpacity() - { + public double getOpacity() { return super.getOpacity(); } @@ -401,8 +380,7 @@ public double getOpacity() * * @see #setAllowBatchPicking(boolean) */ - public boolean isAllowBatchPicking() - { + public boolean isAllowBatchPicking() { return this.iconRenderer.isAllowBatchPicking(); } @@ -413,28 +391,24 @@ public boolean isAllowBatchPicking() * * @param allowBatchPicking true if batch picking is allowed, otherwise false. */ - public void setAllowBatchPicking(boolean allowBatchPicking) - { + public void setAllowBatchPicking(boolean allowBatchPicking) { this.iconRenderer.setAllowBatchPicking(allowBatchPicking); } @Override - protected void doPick(DrawContext dc, java.awt.Point pickPoint) - { + protected void doPick(DrawContext dc, java.awt.Point pickPoint) { this.iconRenderer.setPedestal(this.pedestal); this.iconRenderer.pick(dc, getActiveIcons(dc), pickPoint, this); } @Override - protected void doRender(DrawContext dc) - { + protected void doRender(DrawContext dc) { this.iconRenderer.setPedestal(this.pedestal); this.iconRenderer.render(dc, getActiveIcons(dc)); } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.IconLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/LatLonGraticuleLayer.java b/src/gov/nasa/worldwind/layers/LatLonGraticuleLayer.java index 57fa0b4a76..f0b9198a78 100644 --- a/src/gov/nasa/worldwind/layers/LatLonGraticuleLayer.java +++ b/src/gov/nasa/worldwind/layers/LatLonGraticuleLayer.java @@ -22,8 +22,8 @@ * @author Patrick Murris * @version $Id: LatLonGraticuleLayer.java 2153 2014-07-17 17:33:13Z tgaskins $ */ -public class LatLonGraticuleLayer extends AbstractGraticuleLayer -{ +public class LatLonGraticuleLayer extends AbstractGraticuleLayer { + public static final String GRATICULE_LATLON_LEVEL_0 = "Graticule.LatLonLevel0"; public static final String GRATICULE_LATLON_LEVEL_1 = "Graticule.LatLonLevel1"; public static final String GRATICULE_LATLON_LEVEL_2 = "Graticule.LatLonLevel2"; @@ -38,8 +38,7 @@ public class LatLonGraticuleLayer extends AbstractGraticuleLayer protected ArrayList longitudeLabels = new ArrayList(); private String angleFormat = Angle.ANGLE_FORMAT_DMS; - public LatLonGraticuleLayer() - { + public LatLonGraticuleLayer() { initRenderingParams(); this.setPickEnabled(false); this.setName(Logging.getMessage("layers.LatLonGraticule.Name")); @@ -51,8 +50,7 @@ public LatLonGraticuleLayer() * * @return the graticule division and angular display format. */ - public String getAngleFormat() - { + public String getAngleFormat() { return this.angleFormat; } @@ -64,17 +62,16 @@ public String getAngleFormat() * * @throws IllegalArgumentException is format is null. */ - public void setAngleFormat(String format) - { - if (format == null) - { + public void setAngleFormat(String format) { + if (format == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.angleFormat.equals(format)) + if (this.angleFormat.equals(format)) { return; + } this.angleFormat = format; this.clearTiles(); @@ -82,9 +79,7 @@ public void setAngleFormat(String format) } // --- Graticule Rendering -------------------------------------------------------------- - - protected void initRenderingParams() - { + protected void initRenderingParams() { GraticuleRenderingParams params; // Ten degrees grid params = new GraticuleRenderingParams(); @@ -120,51 +115,46 @@ protected void initRenderingParams() setRenderingParams(GRATICULE_LATLON_LEVEL_5, params); } - protected String[] getOrderedTypes() - { - return new String[] { + protected String[] getOrderedTypes() { + return new String[]{ GRATICULE_LATLON_LEVEL_0, GRATICULE_LATLON_LEVEL_1, GRATICULE_LATLON_LEVEL_2, GRATICULE_LATLON_LEVEL_3, GRATICULE_LATLON_LEVEL_4, - GRATICULE_LATLON_LEVEL_5, - }; + GRATICULE_LATLON_LEVEL_5,}; } - protected String getTypeFor(double resolution) - { - if (resolution >= 10) + protected String getTypeFor(double resolution) { + if (resolution >= 10) { return GRATICULE_LATLON_LEVEL_0; - else if (resolution >= 1) + } else if (resolution >= 1) { return GRATICULE_LATLON_LEVEL_1; - else if (resolution >= .1) + } else if (resolution >= .1) { return GRATICULE_LATLON_LEVEL_2; - else if (resolution >= .01) + } else if (resolution >= .01) { return GRATICULE_LATLON_LEVEL_3; - else if (resolution >= .001) + } else if (resolution >= .001) { return GRATICULE_LATLON_LEVEL_4; - else if (resolution >= .0001) + } else if (resolution >= .0001) { return GRATICULE_LATLON_LEVEL_5; + } return null; } - protected void clear(DrawContext dc) - { + protected void clear(DrawContext dc) { super.clear(dc); this.latitudeLabels.clear(); this.longitudeLabels.clear(); this.applyTerrainConformance(); } - private void applyTerrainConformance() - { + private void applyTerrainConformance() { String[] graticuleType = getOrderedTypes(); - for (String type : graticuleType) - { + for (String type : graticuleType) { getRenderingParams(type).setValue( - GraticuleRenderingParams.KEY_LINE_CONFORMANCE, this.terrainConformance); + GraticuleRenderingParams.KEY_LINE_CONFORMANCE, this.terrainConformance); } } @@ -173,40 +163,34 @@ private void applyTerrainConformance() * * @param dc the current DrawContext. */ - protected void selectRenderables(DrawContext dc) - { + protected void selectRenderables(DrawContext dc) { ArrayList tileList = getVisibleTiles(dc); - if (tileList.size() > 0) - { - for (GraticuleTile gz : tileList) - { + if (tileList.size() > 0) { + for (GraticuleTile gz : tileList) { // Select tile visible elements gz.selectRenderables(dc); } } } - protected ArrayList getVisibleTiles(DrawContext dc) - { + protected ArrayList getVisibleTiles(DrawContext dc) { ArrayList tileList = new ArrayList(); Sector vs = dc.getVisibleSector(); - if (vs != null) - { + if (vs != null) { Rectangle2D gridRectangle = getGridRectangleForSector(vs); - if (gridRectangle != null) - { + if (gridRectangle != null) { for (int row = (int) gridRectangle.getY(); row <= gridRectangle.getY() + gridRectangle.getHeight(); - row++) - { + row++) { for (int col = (int) gridRectangle.getX(); col <= gridRectangle.getX() + gridRectangle.getWidth(); - col++) - { - if (gridTiles[row][col] == null) + col++) { + if (gridTiles[row][col] == null) { gridTiles[row][col] = new GraticuleTile(getGridSector(row, col), 10, 0); - if (gridTiles[row][col].isInView(dc)) + } + if (gridTiles[row][col].isInView(dc)) { tileList.add(gridTiles[row][col]); - else + } else { gridTiles[row][col].clearRenderables(); + } } } } @@ -214,8 +198,7 @@ protected ArrayList getVisibleTiles(DrawContext dc) return tileList; } - private Rectangle2D getGridRectangleForSector(Sector sector) - { + private Rectangle2D getGridRectangleForSector(Sector sector) { int x1 = getGridColumn(sector.getMinLongitude().degrees); int x2 = getGridColumn(sector.getMaxLongitude().degrees); int y1 = getGridRow(sector.getMinLatitude().degrees); @@ -223,8 +206,7 @@ private Rectangle2D getGridRectangleForSector(Sector sector) return new Rectangle(x1, y1, x2 - x1, y2 - y1); } - private Sector getGridSector(int row, int col) - { + private Sector getGridSector(int row, int col) { int minLat = -90 + row * 10; int maxLat = minLat + 10; int minLon = -180 + col * 10; @@ -232,26 +214,20 @@ private Sector getGridSector(int row, int col) return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); } - private int getGridColumn(Double longitude) - { + private int getGridColumn(Double longitude) { int col = (int) Math.floor((longitude + 180) / 10d); return Math.min(col, 35); } - private int getGridRow(Double latitude) - { + private int getGridRow(Double latitude) { int row = (int) Math.floor((latitude + 90) / 10d); return Math.min(row, 17); } - protected void clearTiles() - { - for (int row = 0; row < 18; row++) - { - for (int col = 0; col < 36; col++) - { - if (this.gridTiles[row][col] != null) - { + protected void clearTiles() { + for (int row = 0; row < 18; row++) { + for (int col = 0; col < 36; col++) { + if (this.gridTiles[row][col] != null) { this.gridTiles[row][col].clearRenderables(); this.gridTiles[row][col] = null; } @@ -259,79 +235,69 @@ protected void clearTiles() } } - protected String makeAngleLabel(Angle angle, double resolution) - { + protected String makeAngleLabel(Angle angle, double resolution) { double epsilon = .000000001; String label; - if (this.getAngleFormat().equals(Angle.ANGLE_FORMAT_DMS)) - { - if (resolution >= 1) + if (this.getAngleFormat().equals(Angle.ANGLE_FORMAT_DMS)) { + if (resolution >= 1) { label = angle.toDecimalDegreesString(0); - else - { + } else { double[] dms = angle.toDMS(); - if (dms[1] < epsilon && dms[2] < epsilon) + if (dms[1] < epsilon && dms[2] < epsilon) { label = String.format("%4d\u00B0", (int) dms[0]); - else if (dms[2] < epsilon) + } else if (dms[2] < epsilon) { label = String.format("%4d\u00B0 %2d\u2019", (int) dms[0], (int) dms[1]); - else + } else { label = angle.toDMSString(); + } } - } - else if (this.getAngleFormat().equals(Angle.ANGLE_FORMAT_DM)) - { - if (resolution >= 1) + } else if (this.getAngleFormat().equals(Angle.ANGLE_FORMAT_DM)) { + if (resolution >= 1) { label = angle.toDecimalDegreesString(0); - else - { + } else { double[] dms = angle.toDMS(); - if (dms[1] < epsilon && dms[2] < epsilon) + if (dms[1] < epsilon && dms[2] < epsilon) { label = String.format("%4d\u00B0", (int) dms[0]); - else if (dms[2] < epsilon) + } else if (dms[2] < epsilon) { label = String.format("%4d\u00B0 %2d\u2019", (int) dms[0], (int) dms[1]); - else + } else { label = angle.toDMString(); + } } - } - else // default to decimal degrees + } else // default to decimal degrees { - if (resolution >= 1) + if (resolution >= 1) { label = angle.toDecimalDegreesString(0); - else if (resolution >= .1) + } else if (resolution >= .1) { label = angle.toDecimalDegreesString(1); - else if (resolution >= .01) + } else if (resolution >= .01) { label = angle.toDecimalDegreesString(2); - else if (resolution >= .001) + } else if (resolution >= .001) { label = angle.toDecimalDegreesString(3); - else + } else { label = angle.toDecimalDegreesString(4); + } } return label; } - protected void addLabel(double value, String labelType, String graticuleType, double resolution, LatLon labelOffset) - { - if (labelType.equals(GridElement.TYPE_LATITUDE_LABEL)) - { - if (!this.latitudeLabels.contains(value)) - { + protected void addLabel(double value, String labelType, String graticuleType, double resolution, LatLon labelOffset) { + if (labelType.equals(GridElement.TYPE_LATITUDE_LABEL)) { + if (!this.latitudeLabels.contains(value)) { this.latitudeLabels.add(value); String label = makeAngleLabel(Angle.fromDegrees(value), resolution); GeographicText text = new UserFacingText(label, - Position.fromDegrees(value, labelOffset.getLongitude().degrees, 0)); + Position.fromDegrees(value, labelOffset.getLongitude().degrees, 0)); text.setPriority(resolution * 1e6); this.addRenderable(text, graticuleType); } - } - else if (labelType.equals(GridElement.TYPE_LONGITUDE_LABEL)) - { - if (!this.longitudeLabels.contains(value)) - { + } else if (labelType.equals(GridElement.TYPE_LONGITUDE_LABEL)) { + if (!this.longitudeLabels.contains(value)) { this.longitudeLabels.add(value); String label = makeAngleLabel(Angle.fromDegrees(value), resolution); GeographicText text = new UserFacingText(label, - Position.fromDegrees(labelOffset.getLatitude().degrees, value, 0)); + Position.fromDegrees(labelOffset.getLatitude().degrees, value, 0)); text.setPriority(resolution * 1e6); this.addRenderable(text, graticuleType); } @@ -339,9 +305,8 @@ else if (labelType.equals(GridElement.TYPE_LONGITUDE_LABEL)) } // --- Graticule tile ---------------------------------------------------------------------- + protected class GraticuleTile { - protected class GraticuleTile - { private Sector sector; private int divisions; private int level; @@ -349,116 +314,104 @@ protected class GraticuleTile private ArrayList gridElements; private ArrayList subTiles; - public GraticuleTile(Sector sector, int divisions, int level) - { + public GraticuleTile(Sector sector, int divisions, int level) { this.sector = sector; this.divisions = divisions; this.level = level; } - public Extent getExtent(Globe globe, double ve) - { + public Extent getExtent(Globe globe, double ve) { return Sector.computeBoundingCylinder(globe, ve, this.sector); } @SuppressWarnings({"RedundantIfStatement"}) - public boolean isInView(DrawContext dc) - { + public boolean isInView(DrawContext dc) { if (!dc.getView().getFrustumInModelCoordinates().intersects( - this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) + this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()))) { return false; + } // Check apparent size - if (this.level != 0 && getSizeInPixels(dc) / this.divisions < MIN_CELL_SIZE_PIXELS) + if (this.level != 0 && getSizeInPixels(dc) / this.divisions < MIN_CELL_SIZE_PIXELS) { return false; + } return true; } - public double getSizeInPixels(DrawContext dc) - { + public double getSizeInPixels(DrawContext dc) { View view = dc.getView(); Vec4 centerPoint = getSurfacePoint(dc, this.sector.getCentroid().getLatitude(), - this.sector.getCentroid().getLongitude()); + this.sector.getCentroid().getLongitude()); double distance = view.getEyePoint().distanceTo3(centerPoint); double tileSizeMeter = this.sector.getDeltaLatRadians() * dc.getGlobe().getRadius(); return tileSizeMeter / view.computePixelSizeAtDistance(distance); } - public void selectRenderables(DrawContext dc) - { - if (this.gridElements == null) + public void selectRenderables(DrawContext dc) { + if (this.gridElements == null) { this.createRenderables(); + } LatLon labelOffset = computeLabelOffset(dc); String graticuleType = getTypeFor(this.sector.getDeltaLatDegrees()); - if (this.level == 0) - { - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc)) - { + if (this.level == 0) { + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc)) { // Add level zero bounding lines and labels if (ge.type.equals(GridElement.TYPE_LINE_SOUTH) || ge.type.equals(GridElement.TYPE_LINE_NORTH) - || ge.type.equals(GridElement.TYPE_LINE_WEST)) - { + || ge.type.equals(GridElement.TYPE_LINE_WEST)) { addRenderable(ge.renderable, graticuleType); String labelType = ge.type.equals(GridElement.TYPE_LINE_SOUTH) - || ge.type.equals(GridElement.TYPE_LINE_NORTH) ? - GridElement.TYPE_LATITUDE_LABEL : GridElement.TYPE_LONGITUDE_LABEL; + || ge.type.equals(GridElement.TYPE_LINE_NORTH) + ? GridElement.TYPE_LATITUDE_LABEL : GridElement.TYPE_LONGITUDE_LABEL; addLabel(ge.value, labelType, graticuleType, this.sector.getDeltaLatDegrees(), labelOffset); } } } - if (getSizeInPixels(dc) / this.divisions < MIN_CELL_SIZE_PIXELS) + if (getSizeInPixels(dc) / this.divisions < MIN_CELL_SIZE_PIXELS) { return; + } } // Select tile grid elements double resolution = this.sector.getDeltaLatDegrees() / this.divisions; graticuleType = getTypeFor(resolution); - for (GridElement ge : this.gridElements) - { - if (ge.isInView(dc)) - { - if (ge.type.equals(GridElement.TYPE_LINE)) - { + for (GridElement ge : this.gridElements) { + if (ge.isInView(dc)) { + if (ge.type.equals(GridElement.TYPE_LINE)) { addRenderable(ge.renderable, graticuleType); - String labelType = ge.sector.getDeltaLatDegrees() == 0 ? - GridElement.TYPE_LATITUDE_LABEL : GridElement.TYPE_LONGITUDE_LABEL; + String labelType = ge.sector.getDeltaLatDegrees() == 0 + ? GridElement.TYPE_LATITUDE_LABEL : GridElement.TYPE_LONGITUDE_LABEL; addLabel(ge.value, labelType, graticuleType, resolution, labelOffset); } } } - if (getSizeInPixels(dc) / this.divisions < MIN_CELL_SIZE_PIXELS * 2) + if (getSizeInPixels(dc) / this.divisions < MIN_CELL_SIZE_PIXELS * 2) { return; + } // Select child elements - if (this.subTiles == null) + if (this.subTiles == null) { createSubTiles(); - for (GraticuleTile gt : this.subTiles) - { - if (gt.isInView(dc)) - { + } + for (GraticuleTile gt : this.subTiles) { + if (gt.isInView(dc)) { gt.selectRenderables(dc); - } - else + } else { gt.clearRenderables(); + } } } - public void clearRenderables() - { - if (this.gridElements != null) - { + public void clearRenderables() { + if (this.gridElements != null) { this.gridElements.clear(); this.gridElements = null; } - if (this.subTiles != null) - { - for (GraticuleTile gt : this.subTiles) - { + if (this.subTiles != null) { + for (GraticuleTile gt : this.subTiles) { gt.clearRenderables(); } this.subTiles.clear(); @@ -466,31 +419,30 @@ public void clearRenderables() } } - private void createSubTiles() - { + private void createSubTiles() { this.subTiles = new ArrayList(); Sector[] sectors = this.sector.subdivide(this.divisions); int subDivisions = 10; if ((getAngleFormat().equals(Angle.ANGLE_FORMAT_DMS) || getAngleFormat().equals(Angle.ANGLE_FORMAT_DM)) - && (this.level == 0 || this.level == 2)) + && (this.level == 0 || this.level == 2)) { subDivisions = 6; - for (Sector s : sectors) - { + } + for (Sector s : sectors) { this.subTiles.add(new GraticuleTile(s, subDivisions, this.level + 1)); } } - /** Create the grid elements */ - private void createRenderables() - { + /** + * Create the grid elements + */ + private void createRenderables() { this.gridElements = new ArrayList(); double step = sector.getDeltaLatDegrees() / this.divisions; // Generate meridians with labels double lon = sector.getMinLongitude().degrees + (this.level == 0 ? 0 : step); - while (lon < sector.getMaxLongitude().degrees - step / 2) - { + while (lon < sector.getMaxLongitude().degrees - step / 2) { Angle longitude = Angle.fromDegrees(lon); // Meridian ArrayList positions = new ArrayList(2); @@ -499,9 +451,9 @@ private void createRenderables() Object line = createLineRenderable(positions, AVKey.LINEAR); Sector sector = Sector.fromDegrees( - this.sector.getMinLatitude().degrees, this.sector.getMaxLatitude().degrees, lon, lon); - String lineType = lon == this.sector.getMinLongitude().degrees ? - GridElement.TYPE_LINE_WEST : GridElement.TYPE_LINE; + this.sector.getMinLatitude().degrees, this.sector.getMaxLatitude().degrees, lon, lon); + String lineType = lon == this.sector.getMinLongitude().degrees + ? GridElement.TYPE_LINE_WEST : GridElement.TYPE_LINE; GridElement ge = new GridElement(sector, line, lineType); ge.value = lon; this.gridElements.add(ge); @@ -512,8 +464,7 @@ private void createRenderables() // Generate parallels double lat = this.sector.getMinLatitude().degrees + (this.level == 0 ? 0 : step); - while (lat < this.sector.getMaxLatitude().degrees - step / 2) - { + while (lat < this.sector.getMaxLatitude().degrees - step / 2) { Angle latitude = Angle.fromDegrees(lat); ArrayList positions = new ArrayList(2); positions.add(new Position(latitude, this.sector.getMinLongitude(), 0)); @@ -521,9 +472,9 @@ private void createRenderables() Object line = createLineRenderable(positions, AVKey.LINEAR); Sector sector = Sector.fromDegrees( - lat, lat, this.sector.getMinLongitude().degrees, this.sector.getMaxLongitude().degrees); - String lineType = lat == this.sector.getMinLatitude().degrees ? - GridElement.TYPE_LINE_SOUTH : GridElement.TYPE_LINE; + lat, lat, this.sector.getMinLongitude().degrees, this.sector.getMaxLongitude().degrees); + String lineType = lat == this.sector.getMinLatitude().degrees + ? GridElement.TYPE_LINE_SOUTH : GridElement.TYPE_LINE; GridElement ge = new GridElement(sector, line, lineType); ge.value = lat; this.gridElements.add(ge); @@ -533,15 +484,14 @@ private void createRenderables() } // Draw and label a parallel at the top of the graticule. The line is apparent only on 2D globes. - if (this.sector.getMaxLatitude().equals(Angle.POS90)) - { + if (this.sector.getMaxLatitude().equals(Angle.POS90)) { ArrayList positions = new ArrayList(2); positions.add(new Position(Angle.POS90, this.sector.getMinLongitude(), 0)); positions.add(new Position(Angle.POS90, this.sector.getMaxLongitude(), 0)); Object line = createLineRenderable(positions, AVKey.LINEAR); Sector sector = Sector.fromDegrees( - 90, 90, this.sector.getMinLongitude().degrees, this.sector.getMaxLongitude().degrees); + 90, 90, this.sector.getMinLongitude().degrees, this.sector.getMaxLongitude().degrees); GridElement ge = new GridElement(sector, line, GridElement.TYPE_LINE_NORTH); ge.value = 90; this.gridElements.add(ge); diff --git a/src/gov/nasa/worldwind/layers/Layer.java b/src/gov/nasa/worldwind/layers/Layer.java index 9ab76ebb55..79598eb9dd 100644 --- a/src/gov/nasa/worldwind/layers/Layer.java +++ b/src/gov/nasa/worldwind/layers/Layer.java @@ -13,8 +13,8 @@ * @author Tom Gaskins * @version $Id: Layer.java 1824 2014-01-22 22:41:10Z dcollins $ */ -public interface Layer extends WWObject, Disposable, Restorable -{ +public interface Layer extends WWObject, Disposable, Restorable { + /** * Indicates whether the layer is enabled for rendering and selection. * @@ -61,7 +61,7 @@ public interface Layer extends WWObject, Disposable, Restorable * renderables. See the description of this method in specific layers to determine usage there. * * @param opacity The layer opacity, a value between 0 and 1. 0 indicates non-opaque (fully transparent), 1 - * indicates fully opaque. Values between 0 and 1 indicate partial opacity. + * indicates fully opaque. Values between 0 and 1 indicate partial opacity. */ void setOpacity(double opacity); @@ -88,8 +88,7 @@ public interface Layer extends WWObject, Disposable, Restorable /** * Causes the layer to perform any actions necessary to subsequently render the layer. The layer has exclusive * access to the frame buffer during the call, and may use it to generate images or other information that is - * subsequently used to render the layer's contents. Upon return, the OpenGL state must be restored to its - * original. + * subsequently used to render the layer's contents. Upon return, the OpenGL state must be restored to its original. * * @param dc the current draw context. */ @@ -107,7 +106,7 @@ public interface Layer extends WWObject, Disposable, Restorable * on the screen. Objects that intersect that point are added to the draw context's pick list and are conveyed to * the application via selection events or by a direct query of {@link WorldWindow#getObjectsAtCurrentPosition()}. * - * @param dc the current draw context for rendering. + * @param dc the current draw context for rendering. * @param pickPoint the screen coordinate point * * @see SelectEvent @@ -225,12 +224,14 @@ public interface Layer extends WWObject, Disposable, Restorable * Indicates the altitude above which this layer likely has low value or is not expected to be active. This value is * independent of the maximum active altitude, {@link #setMaxActiveAltitude(double)} and does not reflect it. *

        - * The returned altitude is valid when the field of view indicated by {@link gov.nasa.worldwind.View#getFieldOfView()} - * is set to its default value. Changing the field of view to any value other than the default may change this - * layer's maximum effective altitude, but the returned altitude will not reflect that change. + * The returned altitude is valid when the field of view indicated by + * {@link gov.nasa.worldwind.View#getFieldOfView()} is set to its default value. Changing the field of view to any + * value other than the default may change this layer's maximum effective altitude, but the returned altitude will + * not reflect that change. * * @param radius the radius of the {@link gov.nasa.worldwind.globes.Globe} the layer is associated with. May be - * null, in which case the Earth's equatorial radius is used, {@link gov.nasa.worldwind.globes.Earth#WGS84_EQUATORIAL_RADIUS}. + * null, in which case the Earth's equatorial radius is used, + * {@link gov.nasa.worldwind.globes.Earth#WGS84_EQUATORIAL_RADIUS}. * * @return the layer's maximum effective altitude. */ @@ -240,12 +241,14 @@ public interface Layer extends WWObject, Disposable, Restorable * Indicates the altitude below which this layer likely has low value or is not expected to be active. This value is * independent of the minimum active altitude, {@link #setMinActiveAltitude(double)} and does not reflect it. *

        - * The returned altitude is valid when the field of view indicated by {@link gov.nasa.worldwind.View#getFieldOfView()} - * is set to its default value. Changing the field of view to any value other than the default may change this - * layer's minimum effective altitude, but the returned altitude will not reflect that change. + * The returned altitude is valid when the field of view indicated by + * {@link gov.nasa.worldwind.View#getFieldOfView()} is set to its default value. Changing the field of view to any + * value other than the default may change this layer's minimum effective altitude, but the returned altitude will + * not reflect that change. * * @param radius the radius of the {@link gov.nasa.worldwind.globes.Globe} the layer is associated with. May be - * null, in which case the Earth's equatorial radius is used, {@link gov.nasa.worldwind.globes.Earth#WGS84_EQUATORIAL_RADIUS}. + * null, in which case the Earth's equatorial radius is used, + * {@link gov.nasa.worldwind.globes.Earth#WGS84_EQUATORIAL_RADIUS}. * * @return the layer's minimum effective altitude. */ diff --git a/src/gov/nasa/worldwind/layers/LayerList.java b/src/gov/nasa/worldwind/layers/LayerList.java index 52ab917a54..53652ff60b 100644 --- a/src/gov/nasa/worldwind/layers/LayerList.java +++ b/src/gov/nasa/worldwind/layers/LayerList.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers; import gov.nasa.worldwind.*; @@ -19,18 +18,15 @@ * @author Tom Gaskins * @version $Id: LayerList.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class LayerList extends CopyOnWriteArrayList implements WWObject -{ +public class LayerList extends CopyOnWriteArrayList implements WWObject { + private WWObjectImpl wwo = new WWObjectImpl(this); - public LayerList() - { + public LayerList() { } - public LayerList(Layer[] layers) - { - if (layers == null) - { + public LayerList(Layer[] layers) { + if (layers == null) { String message = Logging.getMessage("nullValue.LayersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -39,34 +35,29 @@ public LayerList(Layer[] layers) this.addAll(Arrays.asList(layers)); } - public LayerList(LayerList layerList) - { + public LayerList(LayerList layerList) { super(layerList); } - public String getDisplayName() - { + public String getDisplayName() { return this.getStringValue(AVKey.DISPLAY_NAME); } - public void setDisplayName(String displayName) - { + public void setDisplayName(String displayName) { this.setValue(AVKey.DISPLAY_NAME, displayName); } - protected LayerList makeShallowCopy(LayerList sourceList) - { + protected LayerList makeShallowCopy(LayerList sourceList) { return new LayerList(sourceList); } - public static List getListDifference(LayerList oldList, LayerList newList) - { + public static List getListDifference(LayerList oldList, LayerList newList) { ArrayList deltaList = new ArrayList(); - for (Layer layer : newList) - { - if (!oldList.contains(layer)) + for (Layer layer : newList) { + if (!oldList.contains(layer)) { deltaList.add(layer); + } } return deltaList; @@ -77,16 +68,14 @@ public static List getListDifference(LayerList oldList, LayerList newList * list and removed from the subsequent lists. * * @param lists an array containing the lists to aggregate. All members of the second and subsequent lists in the - * array are added to the first list in the array. + * array are added to the first list in the array. * * @return the aggregated list. * * @throws IllegalArgumentException if the layer-lists array is null or empty. */ - public static LayerList collapseLists(LayerList[] lists) - { - if (lists == null || lists.length == 0) - { + public static LayerList collapseLists(LayerList[] lists) { + if (lists == null || lists.length == 0) { String message = Logging.getMessage("nullValue.LayersListArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -94,16 +83,13 @@ public static LayerList collapseLists(LayerList[] lists) LayerList list = lists[0]; - for (int i = 1; i < lists.length; i++) - { + for (int i = 1; i < lists.length; i++) { LayerList ll = lists[i]; - for (Layer layer : ll) - { + for (Layer layer : ll) { list.add(layer); } - for (Layer layer : ll) - { + for (Layer layer : ll) { ll.remove(layer); } } @@ -111,20 +97,16 @@ public static LayerList collapseLists(LayerList[] lists) return list; } - public static List getLayersAdded(LayerList oldList, LayerList newList) - { + public static List getLayersAdded(LayerList oldList, LayerList newList) { return getListDifference(oldList, newList); } - public static List getLayersRemoved(LayerList oldList, LayerList newList) - { + public static List getLayersRemoved(LayerList oldList, LayerList newList) { return getListDifference(newList, oldList); } - public boolean add(Layer layer) - { - if (layer == null) - { + public boolean add(Layer layer) { + if (layer == null) { String message = Logging.getMessage("nullValue.LayerIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -138,10 +120,8 @@ public boolean add(Layer layer) return true; } - public void add(int index, Layer layer) - { - if (layer == null) - { + public void add(int index, Layer layer) { + if (layer == null) { String message = Logging.getMessage("nullValue.LayerIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -153,17 +133,16 @@ public void add(int index, Layer layer) this.firePropertyChange(AVKey.LAYERS, copy, this); } - public void remove(Layer layer) - { - if (layer == null) - { + public void remove(Layer layer) { + if (layer == null) { String msg = Logging.getMessage("nullValue.LayerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.contains(layer)) + if (!this.contains(layer)) { return; + } LayerList copy = makeShallowCopy(this); layer.removePropertyChangeListener(this); @@ -171,11 +150,11 @@ public void remove(Layer layer) this.firePropertyChange(AVKey.LAYERS, copy, this); } - public Layer remove(int index) - { + public Layer remove(int index) { Layer layer = get(index); - if (layer == null) + if (layer == null) { return null; + } LayerList copy = makeShallowCopy(this); layer.removePropertyChangeListener(this); @@ -185,11 +164,11 @@ public Layer remove(int index) return layer; } - public boolean moveLower(Layer targetLayer) - { + public boolean moveLower(Layer targetLayer) { int index = this.indexOf(targetLayer); - if (index <= 0) + if (index <= 0) { return false; + } this.remove(index); this.add(index - 1, targetLayer); @@ -197,11 +176,11 @@ public boolean moveLower(Layer targetLayer) return true; } - public boolean moveHigher(Layer targetLayer) - { + public boolean moveHigher(Layer targetLayer) { int index = this.indexOf(targetLayer); - if (index < 0) + if (index < 0) { return false; + } this.remove(index); this.add(index + 1, targetLayer); @@ -209,18 +188,17 @@ public boolean moveHigher(Layer targetLayer) return true; } - public Layer set(int index, Layer layer) - { - if (layer == null) - { + public Layer set(int index, Layer layer) { + if (layer == null) { String message = Logging.getMessage("nullValue.LayerIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Layer oldLayer = this.get(index); - if (oldLayer != null) + if (oldLayer != null) { oldLayer.removePropertyChangeListener(this); + } LayerList copy = makeShallowCopy(this); super.set(index, layer); @@ -230,189 +208,178 @@ public Layer set(int index, Layer layer) return oldLayer; } - public boolean remove(Object o) - { - for (Layer layer : this) - { - if (layer.equals(o)) + public boolean remove(Object o) { + for (Layer layer : this) { + if (layer.equals(o)) { layer.removePropertyChangeListener(this); + } } LayerList copy = makeShallowCopy(this); boolean removed = super.remove(o); - if (removed) + if (removed) { this.firePropertyChange(AVKey.LAYERS, copy, this); + } return removed; } - public boolean addIfAbsent(Layer layer) - { - for (Layer l : this) - { - if (l.equals(layer)) + public boolean addIfAbsent(Layer layer) { + for (Layer l : this) { + if (l.equals(layer)) { return false; + } } layer.addPropertyChangeListener(this); LayerList copy = makeShallowCopy(this); boolean added = super.addIfAbsent(layer); - if (added) + if (added) { this.firePropertyChange(AVKey.LAYERS, copy, this); + } return added; } - public boolean removeAll(Collection objects) - { - for (Layer layer : this) - { + public boolean removeAll(Collection objects) { + for (Layer layer : this) { layer.removePropertyChangeListener(this); } LayerList copy = makeShallowCopy(this); boolean removed = super.removeAll(objects); - if (removed) + if (removed) { this.firePropertyChange(AVKey.LAYERS, copy, this); + } - for (Layer layer : this) - { + for (Layer layer : this) { layer.addPropertyChangeListener(this); } return removed; } - public boolean removeAll() - { - for (Layer layer : this) - { + public boolean removeAll() { + for (Layer layer : this) { layer.removePropertyChangeListener(this); } LayerList copy = makeShallowCopy(this); boolean removed = super.retainAll(new ArrayList()); // retain no layers - if (removed) + if (removed) { this.firePropertyChange(AVKey.LAYERS, copy, this); + } return removed; } - public int addAllAbsent(Collection layers) - { - for (Layer layer : layers) - { - if (!this.contains(layer)) + public int addAllAbsent(Collection layers) { + for (Layer layer : layers) { + if (!this.contains(layer)) { layer.addPropertyChangeListener(this); + } } LayerList copy = makeShallowCopy(this); int numAdded = super.addAllAbsent(layers); - if (numAdded > 0) + if (numAdded > 0) { this.firePropertyChange(AVKey.LAYERS, copy, this); + } return numAdded; } - public boolean addAll(Collection layers) - { - for (Layer layer : layers) - { + public boolean addAll(Collection layers) { + for (Layer layer : layers) { layer.addPropertyChangeListener(this); } LayerList copy = makeShallowCopy(this); boolean added = super.addAll(layers); - if (added) + if (added) { this.firePropertyChange(AVKey.LAYERS, copy, this); + } return added; } - public boolean addAll(int i, Collection layers) - { - for (Layer layer : layers) - { + public boolean addAll(int i, Collection layers) { + for (Layer layer : layers) { layer.addPropertyChangeListener(this); } LayerList copy = makeShallowCopy(this); boolean added = super.addAll(i, layers); - if (added) + if (added) { this.firePropertyChange(AVKey.LAYERS, copy, this); + } return added; } - @SuppressWarnings( {"SuspiciousMethodCalls"}) - public boolean retainAll(Collection objects) - { - for (Layer layer : this) - { - if (!objects.contains(layer)) + @SuppressWarnings({"SuspiciousMethodCalls"}) + public boolean retainAll(Collection objects) { + for (Layer layer : this) { + if (!objects.contains(layer)) { layer.removePropertyChangeListener(this); + } } LayerList copy = makeShallowCopy(this); boolean added = super.retainAll(objects); - if (added) + if (added) { this.firePropertyChange(AVKey.LAYERS, copy, this); + } return added; } - public void replaceAll(Collection layers) - { + public void replaceAll(Collection layers) { ArrayList toDelete = new ArrayList(); ArrayList toKeep = new ArrayList(); - for (Layer layer : layers) - { - if (!this.contains(layer)) + for (Layer layer : layers) { + if (!this.contains(layer)) { toDelete.add(layer); - else + } else { toKeep.add(layer); + } } - for (Layer layer : toDelete) - { + for (Layer layer : toDelete) { this.remove(layer); } super.clear(); - for (Layer layer : layers) - { - if (!toKeep.contains(layer)) + for (Layer layer : layers) { + if (!toKeep.contains(layer)) { layer.addPropertyChangeListener(this); + } super.add(layer); } } - public Layer getLayerByName(String name) - { - if (name == null) - { + public Layer getLayerByName(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (Layer l : this) - { - if (l.getName().equals(name)) + for (Layer l : this) { + if (l.getName().equals(name)) { return l; + } } return null; } - public List getLayersByClass(Class classToFind) - { - if (classToFind == null) - { + public List getLayersByClass(Class classToFind) { + if (classToFind == null) { String message = Logging.getMessage("nullValue.ClassIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -420,76 +387,64 @@ public List getLayersByClass(Class classToFind) ArrayList layers = new ArrayList(); - for (Layer l : this) - { - if (l.getClass().equals(classToFind)) + for (Layer l : this) { + if (l.getClass().equals(classToFind)) { layers.add(l); + } } return layers; } - public Object getValue(String key) - { + public Object getValue(String key) { return wwo.getValue(key); } - public Collection getValues() - { + public Collection getValues() { return wwo.getValues(); } - public Set> getEntries() - { + public Set> getEntries() { return wwo.getEntries(); } - public String getStringValue(String key) - { + public String getStringValue(String key) { return wwo.getStringValue(key); } - public Object setValue(String key, Object value) - { + public Object setValue(String key, Object value) { return wwo.setValue(key, value); } - public AVList setValues(AVList avList) - { + public AVList setValues(AVList avList) { return wwo.setValues(avList); } - public boolean hasKey(String key) - { + public boolean hasKey(String key) { return wwo.hasKey(key); } - public Object removeKey(String key) - { + public Object removeKey(String key) { return wwo.removeKey(key); } - public AVList copy() - { + public AVList copy() { return wwo.copy(); } - public AVList clearList() - { + public AVList clearList() { return this.wwo.clearList(); } - public LayerList sort() - { - if (this.size() <= 0) + public LayerList sort() { + if (this.size() <= 0) { return this; + } Layer[] array = new Layer[this.size()]; this.toArray(array); - Arrays.sort(array, new Comparator() - { - public int compare(Layer layer, Layer layer1) - { + Arrays.sort(array, new Comparator() { + public int compare(Layer layer, Layer layer1) { return layer.getName().compareTo(layer1.getName()); } }); @@ -500,52 +455,42 @@ public int compare(Layer layer, Layer layer1) return this; } - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { wwo.addPropertyChangeListener(propertyName, listener); } - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { wwo.removePropertyChangeListener(propertyName, listener); } - public void addPropertyChangeListener(PropertyChangeListener listener) - { + public void addPropertyChangeListener(PropertyChangeListener listener) { wwo.addPropertyChangeListener(listener); } - public void removePropertyChangeListener(PropertyChangeListener listener) - { + public void removePropertyChangeListener(PropertyChangeListener listener) { wwo.removePropertyChangeListener(listener); } - public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) { wwo.firePropertyChange(propertyChangeEvent); } - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { wwo.firePropertyChange(propertyName, oldValue, newValue); } - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { wwo.propertyChange(propertyChangeEvent); } - public void onMessage(Message message) - { + public void onMessage(Message message) { wwo.onMessage(message); } @Override - public String toString() - { + public String toString() { String r = ""; - for (Layer l : this) - { + for (Layer l : this) { r += l.toString() + ", "; } return r; diff --git a/src/gov/nasa/worldwind/layers/LocalRasterServerLayer.java b/src/gov/nasa/worldwind/layers/LocalRasterServerLayer.java index 33aa740c4b..630c85ea11 100644 --- a/src/gov/nasa/worldwind/layers/LocalRasterServerLayer.java +++ b/src/gov/nasa/worldwind/layers/LocalRasterServerLayer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers; import gov.nasa.worldwind.avlist.*; @@ -21,8 +20,8 @@ * @author tag * @version $Id: LocalRasterServerLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class LocalRasterServerLayer extends BasicTiledImageLayer -{ +public class LocalRasterServerLayer extends BasicTiledImageLayer { + /** * Constructs a layer from a list of parameters describing the layer. *

        @@ -33,10 +32,9 @@ public class LocalRasterServerLayer extends BasicTiledImageLayer * @param params the parameters describing the dataset. * * @throws IllegalArgumentException if the parameter list is null. - * @throws IllegalStateException if the required parameters are missing from the parameter list. + * @throws IllegalStateException if the required parameters are missing from the parameter list. */ - public LocalRasterServerLayer(AVList params) - { + public LocalRasterServerLayer(AVList params) { super(params); this.createRasterServer(params); @@ -49,16 +47,14 @@ public LocalRasterServerLayer(AVList params) *

        * TODO: Enumerate the other required and optional parameters. * - * @param dom the XML document describing the dataset. + * @param dom the XML document describing the dataset. * @param params a list of parameters that each override a parameter of the same name in the XML document, or that - * augment the definition there. + * augment the definition there. * * @throws IllegalArgumentException if the XML document reference is null. - * @throws IllegalStateException if the required parameters are missing from the XML document or the parameter - * list. + * @throws IllegalStateException if the required parameters are missing from the XML document or the parameter list. */ - public LocalRasterServerLayer(Document dom, AVList params) - { + public LocalRasterServerLayer(Document dom, AVList params) { super(dom, params); this.createRasterServer(params != null ? params : (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS)); @@ -72,15 +68,13 @@ public LocalRasterServerLayer(Document dom, AVList params) * TODO: Enumerate the other required and optional parameters. * * @param domElement the XML document describing the dataset. - * @param params a list of parameters that each override a parameter of the same name in the XML document, or - * that augment the definition there. + * @param params a list of parameters that each override a parameter of the same name in the XML document, or that + * augment the definition there. * * @throws IllegalArgumentException if the XML document reference is null. - * @throws IllegalStateException if the required parameters are missing from the XML element or the parameter - * list. + * @throws IllegalStateException if the required parameters are missing from the XML element or the parameter list. */ - public LocalRasterServerLayer(Element domElement, AVList params) - { + public LocalRasterServerLayer(Element domElement, AVList params) { super(domElement, params); this.createRasterServer(params != null ? params : (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS)); @@ -93,28 +87,24 @@ public LocalRasterServerLayer(Element domElement, AVList params) * @param restorableStateInXml a string containing the restorable state. * * @throws IllegalArgumentException if the restorable state is null or cannot be interpreted. - * @throws IllegalStateException if the restorable state does not contain values for DATASET_NAME and - * DATA_CACHE_NAME. + * @throws IllegalStateException if the restorable state does not contain values for DATASET_NAME and + * DATA_CACHE_NAME. */ - public LocalRasterServerLayer(String restorableStateInXml) - { + public LocalRasterServerLayer(String restorableStateInXml) { super(restorableStateInXml); this.createRasterServer((AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS)); } - protected void createRasterServer(AVList params) - { - if (params == null) - { + protected void createRasterServer(AVList params) { + if (params == null) { String reason = Logging.getMessage("nullValue.ParamsIsNull"); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - if (this.getDataFileStore() == null) - { + if (this.getDataFileStore() == null) { String reason = Logging.getMessage("nullValue.FileStoreIsNull"); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); @@ -122,8 +112,7 @@ protected void createRasterServer(AVList params) } String datasetName = params.getStringValue(AVKey.DATASET_NAME); - if (WWUtil.isEmpty(datasetName)) - { + if (WWUtil.isEmpty(datasetName)) { String reason = Logging.getMessage("generic.MissingRequiredParameter", AVKey.DATASET_NAME); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); @@ -131,8 +120,7 @@ protected void createRasterServer(AVList params) } String dataCacheName = params.getStringValue(AVKey.DATA_CACHE_NAME); - if (WWUtil.isEmpty(dataCacheName)) - { + if (WWUtil.isEmpty(dataCacheName)) { String reason = Logging.getMessage("generic.MissingRequiredParameter", AVKey.DATA_CACHE_NAME); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); @@ -142,8 +130,7 @@ protected void createRasterServer(AVList params) String rasterServerConfigFilename = dataCacheName + File.separator + datasetName + ".RasterServer.xml"; final URL rasterServerFileURL = this.getDataFileStore().findFile(rasterServerConfigFilename, false); - if (WWUtil.isEmpty(rasterServerFileURL)) - { + if (WWUtil.isEmpty(rasterServerFileURL)) { String reason = Logging.getMessage("Configuration.ConfigNotFound", rasterServerConfigFilename); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); @@ -154,19 +141,16 @@ protected void createRasterServer(AVList params) rasterServerParams.setValue(AVKey.FILE_STORE, this.getDataFileStore()); - RetrieverFactory retrieverFactory = new RetrieverFactory() - { + RetrieverFactory retrieverFactory = new RetrieverFactory() { final protected RasterServer rasterServer = new BasicRasterServer(rasterServerFileURL, rasterServerParams); - public Retriever createRetriever(AVList tileParams, RetrievalPostProcessor postProcessor) - { - LocalRasterServerRetriever retriever = - new LocalRasterServerRetriever(tileParams, this.rasterServer, postProcessor); + public Retriever createRetriever(AVList tileParams, RetrievalPostProcessor postProcessor) { + LocalRasterServerRetriever retriever + = new LocalRasterServerRetriever(tileParams, this.rasterServer, postProcessor); // copy only values that do not exist in destination AVList // from rasterServerParams (source) to retriever (destination) - - String[] keysToCopy = new String[] { + String[] keysToCopy = new String[]{ AVKey.DATASET_NAME, AVKey.DISPLAY_NAME, AVKey.FILE_STORE, AVKey.IMAGE_FORMAT, AVKey.FORMAT_SUFFIX}; WWUtil.copyValues(rasterServerParams, retriever, keysToCopy, false); diff --git a/src/gov/nasa/worldwind/layers/MarkerLayer.java b/src/gov/nasa/worldwind/layers/MarkerLayer.java index 439060c64a..9f85330d1c 100644 --- a/src/gov/nasa/worldwind/layers/MarkerLayer.java +++ b/src/gov/nasa/worldwind/layers/MarkerLayer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers; import gov.nasa.worldwind.render.DrawContext; @@ -15,67 +14,55 @@ * @author tag * @version $Id: MarkerLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MarkerLayer extends AbstractLayer -{ +public class MarkerLayer extends AbstractLayer { + private MarkerRenderer markerRenderer = new MarkerRenderer(); private Iterable markers; - public MarkerLayer() - { + public MarkerLayer() { } - public MarkerLayer(Iterable markers) - { + public MarkerLayer(Iterable markers) { this.markers = markers; } - public Iterable getMarkers() - { + public Iterable getMarkers() { return markers; } - public void setMarkers(Iterable markers) - { + public void setMarkers(Iterable markers) { this.markers = markers; } - public double getElevation() - { + public double getElevation() { return this.getMarkerRenderer().getElevation(); } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.getMarkerRenderer().setElevation(elevation); } - public boolean isOverrideMarkerElevation() - { + public boolean isOverrideMarkerElevation() { return this.getMarkerRenderer().isOverrideMarkerElevation(); } - public void setOverrideMarkerElevation(boolean overrideMarkerElevation) - { + public void setOverrideMarkerElevation(boolean overrideMarkerElevation) { this.getMarkerRenderer().setOverrideMarkerElevation(overrideMarkerElevation); } - public boolean isKeepSeparated() - { + public boolean isKeepSeparated() { return this.getMarkerRenderer().isKeepSeparated(); } - public void setKeepSeparated(boolean keepSeparated) - { + public void setKeepSeparated(boolean keepSeparated) { this.getMarkerRenderer().setKeepSeparated(keepSeparated); } - public boolean isEnablePickSizeReturn() - { + public boolean isEnablePickSizeReturn() { return this.getMarkerRenderer().isEnablePickSizeReturn(); } - public void setEnablePickSizeReturn(boolean enablePickSizeReturn) - { + public void setEnablePickSizeReturn(boolean enablePickSizeReturn) { this.getMarkerRenderer().setEnablePickSizeReturn(enablePickSizeReturn); } @@ -85,8 +72,7 @@ public void setEnablePickSizeReturn(boolean enablePickSizeReturn) * @param opacity the current opacity value, which is ignored by this layer. */ @Override - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { super.setOpacity(opacity); } @@ -97,43 +83,40 @@ public void setOpacity(double opacity) * @return The layer opacity, a value between 0 and 1. */ @Override - public double getOpacity() - { + public double getOpacity() { return super.getOpacity(); } - protected MarkerRenderer getMarkerRenderer() - { + protected MarkerRenderer getMarkerRenderer() { return markerRenderer; } - protected void setMarkerRenderer(MarkerRenderer markerRenderer) - { + protected void setMarkerRenderer(MarkerRenderer markerRenderer) { this.markerRenderer = markerRenderer; } - protected void doRender(DrawContext dc) - { + protected void doRender(DrawContext dc) { this.draw(dc, null); } @Override - protected void doPick(DrawContext dc, java.awt.Point pickPoint) - { + protected void doPick(DrawContext dc, java.awt.Point pickPoint) { this.draw(dc, pickPoint); } - protected void draw(DrawContext dc, java.awt.Point pickPoint) - { - if (this.markers == null) + protected void draw(DrawContext dc, java.awt.Point pickPoint) { + if (this.markers == null) { return; + } - if (dc.getVisibleSector() == null) + if (dc.getVisibleSector() == null) { return; + } SectorGeometryList geos = dc.getSurfaceGeometry(); - if (geos == null) + if (geos == null) { return; + } // Adds markers to the draw context's ordered renderable queue. During picking, this gets the pick point and the // current layer from the draw context. @@ -141,8 +124,7 @@ protected void draw(DrawContext dc, java.awt.Point pickPoint) } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.MarkerLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/RenderableLayer.java b/src/gov/nasa/worldwind/layers/RenderableLayer.java index 00e0016e0c..1c0ce47325 100644 --- a/src/gov/nasa/worldwind/layers/RenderableLayer.java +++ b/src/gov/nasa/worldwind/layers/RenderableLayer.java @@ -24,15 +24,16 @@ * @version $Id: RenderableLayer.java 3435 2015-10-13 10:32:43Z dcollins $ * @see gov.nasa.worldwind.render.Renderable */ -public class RenderableLayer extends AbstractLayer -{ +public class RenderableLayer extends AbstractLayer { + protected Collection renderables = new ConcurrentLinkedQueue(); protected Iterable renderablesOverride; protected PickSupport pickSupport = new PickSupport(); - /** Creates a new RenderableLayer with a null delegateOwner */ - public RenderableLayer() - { + /** + * Creates a new RenderableLayer with a null delegateOwner + */ + public RenderableLayer() { } /** @@ -48,19 +49,16 @@ public RenderableLayer() * @param renderable Renderable to add. * * @throws IllegalArgumentException If renderable is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. */ - public void addRenderable(Renderable renderable) - { - if (renderable == null) - { + public void addRenderable(Renderable renderable) { + if (renderable == null) { String msg = Logging.getMessage("nullValue.RenderableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.renderablesOverride != null) - { + if (this.renderablesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -70,8 +68,9 @@ public void addRenderable(Renderable renderable) // Attach the layer as a property change listener of the renderable. This forwards property change events from // the renderable to the SceneController. - if (renderable instanceof AVList) + if (renderable instanceof AVList) { ((AVList) renderable).addPropertyChangeListener(this); + } } /** @@ -84,32 +83,27 @@ public void addRenderable(Renderable renderable) * to the renderable are removed in {@link #removeRenderable(gov.nasa.worldwind.render.Renderable)}, * {@link #removeAllRenderables()}, or {@link #dispose()}. * - * @param index the index at which to insert the specified renderable. + * @param index the index at which to insert the specified renderable. * @param renderable Renderable to insert. * * @throws IllegalArgumentException If renderable is null, if the index is less than zero, - * or if the index is greater than the number of renderables in this - * layer. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. + * or if the index is greater than the number of renderables in this layer. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. */ - public void addRenderable(int index, Renderable renderable) - { - if (renderable == null) - { + public void addRenderable(int index, Renderable renderable) { + if (renderable == null) { String msg = Logging.getMessage("nullValue.RenderableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.renderablesOverride != null) - { + if (this.renderablesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - if (index < 0 || index > this.renderables.size()) - { + if (index < 0 || index > this.renderables.size()) { String msg = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -125,8 +119,9 @@ public void addRenderable(int index, Renderable renderable) // Attach the layer as a property change listener of the renderable. This forwards property change events from // the renderable to the SceneController. - if (renderable instanceof AVList) + if (renderable instanceof AVList) { ((AVList) renderable).addPropertyChangeListener(this); + } } /** @@ -142,34 +137,32 @@ public void addRenderable(int index, Renderable renderable) * @param renderables Renderables to add. * * @throws IllegalArgumentException If renderables is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. */ - public void addRenderables(Iterable renderables) - { - if (renderables == null) - { + public void addRenderables(Iterable renderables) { + if (renderables == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.renderablesOverride != null) - { + if (this.renderablesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - for (Renderable renderable : renderables) - { + for (Renderable renderable : renderables) { // Internal list of renderables does not accept null values. - if (renderable != null) + if (renderable != null) { this.renderables.add(renderable); + } // Attach the layer as a property change listener of the renderable. This forwards property change events // from the renderable to the SceneController. - if (renderable instanceof AVList) + if (renderable instanceof AVList) { ((AVList) renderable).addPropertyChangeListener(this); + } } } @@ -186,19 +179,16 @@ public void addRenderables(Iterable renderables) * @param renderable Renderable to remove. * * @throws IllegalArgumentException If renderable is null. - * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. + * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. */ - public void removeRenderable(Renderable renderable) - { - if (renderable == null) - { + public void removeRenderable(Renderable renderable) { + if (renderable == null) { String msg = Logging.getMessage("nullValue.RenderableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.renderablesOverride != null) - { + if (this.renderablesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -208,8 +198,9 @@ public void removeRenderable(Renderable renderable) // Remove the layer as a property change listener of the renderable. This prevents the renderable from keeping a // dangling reference to the layer. - if (renderable instanceof AVList) + if (renderable instanceof AVList) { ((AVList) renderable).removePropertyChangeListener(this); + } } /** @@ -223,10 +214,8 @@ public void removeRenderable(Renderable renderable) * * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. */ - public void removeAllRenderables() - { - if (this.renderablesOverride != null) - { + public void removeAllRenderables() { + if (this.renderablesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -235,37 +224,30 @@ public void removeAllRenderables() this.clearRenderables(); } - protected void clearRenderables() - { - if (this.renderables != null && this.renderables.size() > 0) - { + protected void clearRenderables() { + if (this.renderables != null && this.renderables.size() > 0) { // Remove the layer as property change listener of any renderables. This prevents the renderables from // keeping a dangling references to the layer. - for (Renderable renderable : this.renderables) - { - if (renderable instanceof AVList) + for (Renderable renderable : this.renderables) { + if (renderable instanceof AVList) { ((AVList) renderable).removePropertyChangeListener(this); + } } this.renderables.clear(); } } - public int getNumRenderables() - { - if (this.renderablesOverride != null) - { + public int getNumRenderables() { + if (this.renderablesOverride != null) { int size = 0; //noinspection UnusedDeclaration - for (Renderable r : this.renderablesOverride) - { + for (Renderable r : this.renderablesOverride) { ++size; } return size; - } - else - { + } else { return this.renderables.size(); } } @@ -278,8 +260,7 @@ public int getNumRenderables() * * @return Iterable of currently active Renderables. */ - public Iterable getRenderables() - { + public Iterable getRenderables() { return this.getActiveRenderables(); } @@ -291,14 +272,10 @@ public Iterable getRenderables() * * @return Iterable of currently active Renderables. */ - protected Iterable getActiveRenderables() - { - if (this.renderablesOverride != null) - { + protected Iterable getActiveRenderables() { + if (this.renderablesOverride != null) { return this.renderablesOverride; - } - else - { + } else { // Return an unmodifiable reference to the internal list of renderables. // This prevents callers from changing this list and invalidating any invariants we have established. return java.util.Collections.unmodifiableCollection(this.renderables); @@ -316,17 +293,16 @@ protected Iterable getActiveRenderables() * does not forward any of the renderable's property change events to the layer's property change listeners. Since * the layer is not in control of the iIterable's contents, attaching property change listeners to the renderables * could cause the them to hold dangling references to the layer. If any of the renderables in the Iterable rely on - * forwarding property change events for proper operation - such as {@link gov.nasa.worldwind.render.AbstractBrowserBalloon} - * - use {@link #addRenderables(Iterable)} instead. + * forwarding property change events for proper operation - such as + * {@link gov.nasa.worldwind.render.AbstractBrowserBalloon} - use {@link #addRenderables(Iterable)} instead. *

        * If the specified renderableIterable is null, this layer reverts to maintaining its internal * collection. * * @param renderableIterable Iterable to use instead of this layer's internal collection, or null to use this - * layer's internal collection. + * layer's internal collection. */ - public void setRenderables(Iterable renderableIterable) - { + public void setRenderables(Iterable renderableIterable) { this.renderablesOverride = renderableIterable; // Dispose of the internal collection of Renderables. this.disposeRenderables(); @@ -340,8 +316,7 @@ public void setRenderables(Iterable renderableIterable) * @param opacity the current opacity value, which is ignored by this layer. */ @Override - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { super.setOpacity(opacity); } @@ -352,8 +327,7 @@ public void setOpacity(double opacity) * @return The layer opacity, a value between 0 and 1. */ @Override - public double getOpacity() - { + public double getOpacity() { return super.getOpacity(); } @@ -368,10 +342,8 @@ public double getOpacity() * * @throws IllegalStateException If a custom Iterable has been specified by a call to setRenderables. */ - public void dispose() - { - if (this.renderablesOverride != null) - { + public void dispose() { + if (this.renderablesOverride != null) { String msg = Logging.getMessage("generic.LayerIsUsingCustomIterable"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -380,24 +352,20 @@ public void dispose() this.disposeRenderables(); } - protected void disposeRenderables() - { - if (this.renderables != null && this.renderables.size() > 0) - { - for (Renderable renderable : this.renderables) - { - try - { + protected void disposeRenderables() { + if (this.renderables != null && this.renderables.size() > 0) { + for (Renderable renderable : this.renderables) { + try { // Remove the layer as a property change listener of the renderable. This prevents the renderable // from keeping a dangling reference to the layer. - if (renderable instanceof AVList) + if (renderable instanceof AVList) { ((AVList) renderable).removePropertyChangeListener(this); + } - if (renderable instanceof Disposable) + if (renderable instanceof Disposable) { ((Disposable) renderable).dispose(); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToDisposeRenderable"); Logging.logger().severe(msg); // continue to next renderable @@ -408,34 +376,27 @@ protected void disposeRenderables() this.renderables.clear(); } - protected void doPreRender(DrawContext dc) - { + protected void doPreRender(DrawContext dc) { this.doPreRender(dc, this.getActiveRenderables()); } - protected void doPick(DrawContext dc, java.awt.Point pickPoint) - { + protected void doPick(DrawContext dc, java.awt.Point pickPoint) { this.doPick(dc, this.getActiveRenderables(), pickPoint); } - protected void doRender(DrawContext dc) - { + protected void doRender(DrawContext dc) { this.doRender(dc, this.getActiveRenderables()); } - protected void doPreRender(DrawContext dc, Iterable renderables) - { - for (Renderable renderable : renderables) - { - try - { + protected void doPreRender(DrawContext dc, Iterable renderables) { + for (Renderable renderable : renderables) { + try { // If the caller has specified their own Iterable, // then we cannot make any guarantees about its contents. - if (renderable != null && renderable instanceof PreRenderable) + if (renderable != null && renderable instanceof PreRenderable) { ((PreRenderable) renderable).preRender(dc); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhilePrerenderingRenderable"); Logging.logger().severe(msg); // continue to next renderable @@ -443,31 +404,24 @@ protected void doPreRender(DrawContext dc, Iterable render } } - protected void doPick(DrawContext dc, Iterable renderables, java.awt.Point pickPoint) - { + protected void doPick(DrawContext dc, Iterable renderables, java.awt.Point pickPoint) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); - try - { - for (Renderable renderable : renderables) - { + try { + for (Renderable renderable : renderables) { // If the caller has specified their own Iterable, // then we cannot make any guarantees about its contents. - if (renderable != null) - { + if (renderable != null) { // float[] inColor = new float[4]; // gl.glGetFloatv(GL.GL_CURRENT_COLOR, inColor, 0); java.awt.Color color = dc.getUniquePickColor(); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); - try - { + try { renderable.render(dc); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhilePickingRenderable"); Logging.logger().severe(msg); Logging.logger().log(java.util.logging.Level.FINER, msg, e); // show exception for this level @@ -476,39 +430,30 @@ protected void doPick(DrawContext dc, Iterable renderables // // gl.glColor4fv(inColor, 0); - if (renderable instanceof Locatable) - { + if (renderable instanceof Locatable) { this.pickSupport.addPickableObject(color.getRGB(), renderable, - ((Locatable) renderable).getPosition(), false); - } - else - { + ((Locatable) renderable).getPosition(), false); + } else { this.pickSupport.addPickableObject(color.getRGB(), renderable); } } } this.pickSupport.resolvePick(dc, pickPoint, this); - } - finally - { + } finally { this.pickSupport.endPicking(dc); } } - protected void doRender(DrawContext dc, Iterable renderables) - { - for (Renderable renderable : renderables) - { - try - { + protected void doRender(DrawContext dc, Iterable renderables) { + for (Renderable renderable : renderables) { + try { // If the caller has specified their own Iterable, // then we cannot make any guarantees about its contents. - if (renderable != null) + if (renderable != null) { renderable.render(dc); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhileRenderingRenderable"); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); // continue to next renderable @@ -517,8 +462,7 @@ protected void doRender(DrawContext dc, Iterable renderabl } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.RenderableLayer.Name"); } @@ -530,17 +474,13 @@ public String toString() * @param message The message that was received. */ @Override - public void onMessage(Message message) - { - for (Renderable renderable : this.renderables) - { - try - { - if (renderable instanceof MessageListener) + public void onMessage(Message message) { + for (Renderable renderable : this.renderables) { + try { + if (renderable instanceof MessageListener) { ((MessageListener) renderable).onMessage(message); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionInvokingMessageListener"); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); // continue to next renderable diff --git a/src/gov/nasa/worldwind/layers/ScalebarLayer.java b/src/gov/nasa/worldwind/layers/ScalebarLayer.java index 0f5239d0fb..3e0d8882ce 100644 --- a/src/gov/nasa/worldwind/layers/ScalebarLayer.java +++ b/src/gov/nasa/worldwind/layers/ScalebarLayer.java @@ -21,8 +21,8 @@ * @author Patrick Murris * @version $Id: ScalebarLayer.java 2126 2014-07-04 00:35:06Z tgaskins $ */ -public class ScalebarLayer extends AbstractLayer -{ +public class ScalebarLayer extends AbstractLayer { + // Units constants public final static String UNIT_METRIC = "gov.nasa.worldwind.ScalebarLayer.Metric"; public final static String UNIT_IMPERIAL = "gov.nasa.worldwind.ScalebarLayer.Imperial"; @@ -44,48 +44,43 @@ public class ScalebarLayer extends AbstractLayer protected long frameStampForPicking; protected long frameStampForDrawing; - protected class OrderedImage implements OrderedRenderable - { + protected class OrderedImage implements OrderedRenderable { + protected Position referencePosition; protected double pixelSize; - public OrderedImage(Position referencePosition, double pixelSize) - { + public OrderedImage(Position referencePosition, double pixelSize) { this.referencePosition = referencePosition; this.pixelSize = pixelSize; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return 0; } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { ScalebarLayer.this.draw(dc, this); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { ScalebarLayer.this.draw(dc, this); } } - /** Renders a scalebar graphic in a screen corner */ - public ScalebarLayer() - { + /** + * Renders a scalebar graphic in a screen corner + */ + public ScalebarLayer() { setPickEnabled(false); } // Public properties - /** * Get the scalebar graphic Dimension (in pixels) * * @return the scalebar graphic Dimension */ - public Dimension getSize() - { + public Dimension getSize() { return this.size; } @@ -94,10 +89,8 @@ public Dimension getSize() * * @param size the scalebar graphic Dimension */ - public void setSize(Dimension size) - { - if (size == null) - { + public void setSize(Dimension size) { + if (size == null) { String message = Logging.getMessage("nullValue.DimensionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,8 +103,7 @@ public void setSize(Dimension size) * * @return the scalebar Color */ - public Color getColor() - { + public Color getColor() { return this.color; } @@ -120,10 +112,8 @@ public Color getColor() * * @param color the scalebar Color */ - public void setColor(Color color) - { - if (color == null) - { + public void setColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -136,8 +126,7 @@ public void setColor(Color color) * * @return the scalebar-to-viewport scale factor */ - public double getToViewportScale() - { + public double getToViewportScale() { return toViewportScale; } @@ -149,13 +138,11 @@ public double getToViewportScale() * * @param toViewportScale the scalebar to viewport scale factor */ - public void setToViewportScale(double toViewportScale) - { + public void setToViewportScale(double toViewportScale) { this.toViewportScale = toViewportScale; } - public String getPosition() - { + public String getPosition() { return this.position; } @@ -165,10 +152,8 @@ public String getPosition() * * @param position the desired scalebar position */ - public void setPosition(String position) - { - if (position == null) - { + public void setPosition(String position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -181,8 +166,7 @@ public void setPosition(String position) * * @return the current location center. May be null. */ - public Vec4 getLocationCenter() - { + public Vec4 getLocationCenter() { return locationCenter; } @@ -198,8 +182,7 @@ public Vec4 getLocationCenter() * @see #setPosition * @see #setLocationOffset */ - public void setLocationCenter(Vec4 locationCenter) - { + public void setLocationCenter(Vec4 locationCenter) { this.locationCenter = locationCenter; } @@ -208,8 +191,7 @@ public void setLocationCenter(Vec4 locationCenter) * * @return the location offset. Will be null if no offset has been specified. */ - public Vec4 getLocationOffset() - { + public Vec4 getLocationOffset() { return locationOffset; } @@ -217,14 +199,13 @@ public Vec4 getLocationOffset() * Specifies a placement offset from the scalebar's position on the screen. * * @param locationOffset the number of pixels to shift the scalebar from its specified screen position. A positive X - * value shifts the image to the right. A positive Y value shifts the image up. If null, no - * offset is applied. The default offset is null. + * value shifts the image to the right. A positive Y value shifts the image up. If null, no offset is applied. The + * default offset is null. * * @see #setLocationCenter * @see #setPosition */ - public void setLocationOffset(Vec4 locationOffset) - { + public void setLocationOffset(Vec4 locationOffset) { this.locationOffset = locationOffset; } @@ -233,8 +214,7 @@ public void setLocationOffset(Vec4 locationOffset) * * @return the layer's resize behavior */ - public String getResizeBehavior() - { + public String getResizeBehavior() { return resizeBehavior; } @@ -249,13 +229,11 @@ public String getResizeBehavior() * * @param resizeBehavior the desired resize behavior */ - public void setResizeBehavior(String resizeBehavior) - { + public void setResizeBehavior(String resizeBehavior) { this.resizeBehavior = resizeBehavior; } - public int getBorderWidth() - { + public int getBorderWidth() { return borderWidth; } @@ -265,13 +243,11 @@ public int getBorderWidth() * @param borderWidth the number of pixels to offset the scalebar from the borders indicated by {@link * #setPosition(String)}. */ - public void setBorderWidth(int borderWidth) - { + public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; } - public String getUnit() - { + public String getUnit() { return this.unit; } @@ -281,8 +257,7 @@ public String getUnit() * * @param unit the desired unit */ - public void setUnit(String unit) - { + public void setUnit(String unit) { this.unit = unit; } @@ -291,8 +266,7 @@ public void setUnit(String unit) * * @return the scalebar legend Font */ - public Font getFont() - { + public Font getFont() { return this.defaultFont; } @@ -301,10 +275,8 @@ public Font getFont() * * @param font the scalebar legend Font */ - public void setFont(Font font) - { - if (font == null) - { + public void setFont(Font font) { + if (font == null) { String msg = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -314,10 +286,10 @@ public void setFont(Font font) // Rendering @Override - public void doRender(DrawContext dc) - { - if (dc.isContinuous2DGlobe() && this.frameStampForDrawing == dc.getFrameTimeStamp()) + public void doRender(DrawContext dc) { + if (dc.isContinuous2DGlobe() && this.frameStampForDrawing == dc.getFrameTimeStamp()) { return; + } this.addOrderedImage(dc); @@ -325,28 +297,27 @@ public void doRender(DrawContext dc) } @Override - public void doPick(DrawContext dc, Point pickPoint) - { - if (dc.isContinuous2DGlobe() && this.frameStampForPicking == dc.getFrameTimeStamp()) + public void doPick(DrawContext dc, Point pickPoint) { + if (dc.isContinuous2DGlobe() && this.frameStampForPicking == dc.getFrameTimeStamp()) { return; + } this.addOrderedImage(dc); this.frameStampForPicking = dc.getFrameTimeStamp(); } - protected void addOrderedImage(DrawContext dc) - { + protected void addOrderedImage(DrawContext dc) { // Capture the current reference position and pixel size and create an ordered renderable to defer drawing. Position referencePosition = dc.getViewportCenterPosition(); dc.addOrderedRenderable(new OrderedImage(referencePosition, this.computePixelSize(dc, referencePosition))); } - protected double computePixelSize(DrawContext dc, Position referencePosition) - { - if (referencePosition == null) + protected double computePixelSize(DrawContext dc, Position referencePosition) { + if (referencePosition == null) { return -1; + } Vec4 groundTarget = dc.getGlobe().computePointFromPosition(referencePosition); double eyeDistance = dc.getView().getEyePoint().distanceTo3(groundTarget); @@ -354,14 +325,12 @@ protected double computePixelSize(DrawContext dc, Position referencePosition) } // Rendering - public void draw(DrawContext dc, OrderedImage orderedImage) - { + public void draw(DrawContext dc, OrderedImage orderedImage) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { ogsh.pushAttrib(gl, GL2.GL_TRANSFORM_BIT); gl.glDisable(GL.GL_DEPTH_TEST); @@ -386,53 +355,43 @@ public void draw(DrawContext dc, OrderedImage orderedImage) gl.glScaled(scale, scale, 1); // Compute scale size in real world - if (orderedImage.pixelSize > 0) - { + if (orderedImage.pixelSize > 0) { Double scaleSize = orderedImage.pixelSize * width * scale; // meter String unitLabel = "m"; - if (this.unit.equals(UNIT_METRIC)) - { - if (scaleSize > 10000) - { + if (this.unit.equals(UNIT_METRIC)) { + if (scaleSize > 10000) { scaleSize /= 1000; unitLabel = "Km"; } - } - else if (this.unit.equals(UNIT_IMPERIAL)) - { + } else if (this.unit.equals(UNIT_IMPERIAL)) { scaleSize *= 3.280839895; // feet unitLabel = "ft"; - if (scaleSize > 5280) - { + if (scaleSize > 5280) { scaleSize /= 5280; unitLabel = "mile(s)"; } - } - else if (this.unit.equals(UNIT_NAUTICAL)) - { + } else if (this.unit.equals(UNIT_NAUTICAL)) { scaleSize *= 3.280839895; // feet unitLabel = "ft"; - if (scaleSize > 6076) - { + if (scaleSize > 6076) { scaleSize /= 6076; unitLabel = "Nautical mile(s)"; } } // Rounded division size int pot = (int) Math.floor(Math.log10(scaleSize)); - if (!Double.isNaN(pot)) - { + if (!Double.isNaN(pot)) { int digit = Integer.parseInt(String.format("%.0f", scaleSize).substring(0, 1)); double divSize = digit * Math.pow(10, pot); - if (digit >= 5) + if (digit >= 5) { divSize = 5 * Math.pow(10, pot); - else if (digit >= 2) + } else if (digit >= 2) { divSize = 2 * Math.pow(10, pot); + } double divWidth = width * divSize / scaleSize; // Draw scale - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); @@ -440,7 +399,7 @@ else if (digit >= 2) Color backColor = this.getBackgroundColor(this.color); float[] colorRGB = backColor.getRGBColorComponents(null); gl.glColor4d(colorRGB[0], colorRGB[1], colorRGB[2], (double) backColor.getAlpha() / 255d - * this.getOpacity()); + * this.getOpacity()); gl.glTranslated((width - divWidth) / 2, 0d, 0d); this.drawScale(dc, divWidth, height); @@ -454,11 +413,9 @@ else if (digit >= 2) gl.glLoadIdentity(); gl.glDisable(GL.GL_CULL_FACE); drawLabel(dc, label, - locationSW.add3( - new Vec4(divWidth * scale / 2 + (width - divWidth) / 2, height * scale, 0))); - } - else - { + locationSW.add3( + new Vec4(divWidth * scale / 2 + (width - divWidth) / 2, height * scale, 0))); + } else { // Picking this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); @@ -476,14 +433,11 @@ else if (digit >= 2) } } } - } - finally - { + } finally { gl.glColor4d(1d, 1d, 1d, 1d); // restore the default OpenGL color gl.glEnable(GL.GL_DEPTH_TEST); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glBlendFunc(GL.GL_ONE, GL.GL_ZERO); // restore to default blend function gl.glDisable(GL.GL_BLEND); // restore to default blend state } @@ -493,8 +447,7 @@ else if (digit >= 2) } // Draw scale rectangle - private void drawRectangle(DrawContext dc, double width, double height) - { + private void drawRectangle(DrawContext dc, double width, double height) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_POLYGON); gl.glVertex3d(0, height, 0); @@ -506,8 +459,7 @@ private void drawRectangle(DrawContext dc, double width, double height) } // Draw scale graphic - private void drawScale(DrawContext dc, double width, double height) - { + private void drawScale(DrawContext dc, double width, double height) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_LINE_STRIP); gl.glVertex3d(0, height, 0); @@ -522,10 +474,9 @@ private void drawScale(DrawContext dc, double width, double height) } // Draw the scale label - private void drawLabel(DrawContext dc, String text, Vec4 screenPoint) - { + private void drawLabel(DrawContext dc, String text, Vec4 screenPoint) { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - this.defaultFont); + this.defaultFont); Rectangle2D nameBound = textRenderer.getBounds(text); int x = (int) (screenPoint.x() - nameBound.getWidth() / 2d); @@ -544,76 +495,56 @@ private void drawLabel(DrawContext dc, String text, Vec4 screenPoint) private final float[] compArray = new float[4]; // Compute background color for best contrast - private Color getBackgroundColor(Color color) - { + private Color getBackgroundColor(Color color) { Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), compArray); - if (compArray[2] > 0.5) + if (compArray[2] > 0.5) { return new Color(0, 0, 0, 0.7f); - else + } else { return new Color(1, 1, 1, 0.7f); + } } - private double computeScale(java.awt.Rectangle viewport) - { - if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) - { + private double computeScale(java.awt.Rectangle viewport) { + if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) { return Math.min(1d, (this.toViewportScale) * viewport.width / this.size.width); - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) { return (this.toViewportScale) * viewport.width / this.size.width; - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) { return 1d; - } - else - { + } else { return 1d; } } - private Vec4 computeLocation(java.awt.Rectangle viewport, double scale) - { + private Vec4 computeLocation(java.awt.Rectangle viewport, double scale) { double scaledWidth = scale * this.size.width; double scaledHeight = scale * this.size.height; double x; double y; - if (this.locationCenter != null) - { + if (this.locationCenter != null) { x = this.locationCenter.x - scaledWidth / 2; y = this.locationCenter.y - scaledHeight / 2; - } - else if (this.position.equals(AVKey.NORTHEAST)) - { + } else if (this.position.equals(AVKey.NORTHEAST)) { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHEAST)) - { + } else if (this.position.equals(AVKey.SOUTHEAST)) { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = 0d + this.borderWidth; - } - else if (this.position.equals(AVKey.NORTHWEST)) - { + } else if (this.position.equals(AVKey.NORTHWEST)) { x = 0d + this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHWEST)) - { + } else if (this.position.equals(AVKey.SOUTHWEST)) { x = 0d + this.borderWidth; y = 0d + this.borderWidth; - } - else // use North East + } else // use North East { x = viewport.getWidth() - scaledWidth / 2 - this.borderWidth; y = viewport.getHeight() - scaledHeight / 2 - this.borderWidth; } - if (this.locationOffset != null) - { + if (this.locationOffset != null) { x += this.locationOffset.x; y += this.locationOffset.y; } @@ -622,8 +553,7 @@ else if (this.position.equals(AVKey.SOUTHWEST)) } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.Earth.ScalebarLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/SkyColorLayer.java b/src/gov/nasa/worldwind/layers/SkyColorLayer.java index dac19200ff..874d5b026e 100644 --- a/src/gov/nasa/worldwind/layers/SkyColorLayer.java +++ b/src/gov/nasa/worldwind/layers/SkyColorLayer.java @@ -18,8 +18,8 @@ * @author Patrick Murris * @version $Id: SkyColorLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SkyColorLayer extends RenderableLayer -{ +public class SkyColorLayer extends RenderableLayer { + private Color color = new Color(73, 131, 204); // Sky blue private double fadeBottomAltitude = 50e3; private double fadeTopAltitude = 140e3; @@ -32,28 +32,29 @@ public SkyColorLayer() { /** * Paints the sky color background depending on altitude + * * @param color the sky Color */ public SkyColorLayer(Color color) { this.setSkyColor(color); } + /** * Get the sky Color - * @return the sky color + * + * @return the sky color */ - public Color getSkyColor() - { + public Color getSkyColor() { return this.color; } /** * Set the sky Color + * * @param color the sky color */ - public void setSkyColor(Color color) - { - if (color == null) - { + public void setSkyColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -63,52 +64,53 @@ public void setSkyColor(Color color) /** * Get the bottom altitude for the fade effect (meters) - * @return the bottom altitude in meters + * + * @return the bottom altitude in meters */ - public double getFadeBottomAltitude() - { + public double getFadeBottomAltitude() { return this.fadeBottomAltitude; } /** * Set the bottom altitude for the fade effect (meters) + * * @param alt the bottom altitude in meters */ - public void setFadeBottomAltitude(double alt) - { + public void setFadeBottomAltitude(double alt) { this.fadeBottomAltitude = alt; } /** * Get the top altitude for the fade effect (meters) - * @return the top altitude in meters + * + * @return the top altitude in meters */ - public double getFadeTopAltitude() - { + public double getFadeTopAltitude() { return this.fadeTopAltitude; } /** * Set the top altitude for the fade effect (meters) + * * @param alt the top altitude in meters */ - public void setFadeTopAltitude(double alt) - { + public void setFadeTopAltitude(double alt) { this.fadeTopAltitude = alt; } - public void doRender(DrawContext dc) - { + public void doRender(DrawContext dc) { Position eyePos = dc.getView().getEyePosition(); - if (eyePos == null) + if (eyePos == null) { return; + } double alt = eyePos.getElevation(); - if(alt > this.fadeTopAltitude) + if (alt > this.fadeTopAltitude) { return; + } // Compute fade factor - float fadeFactor = (alt < this.fadeBottomAltitude) ? 1f : - (float)((this.fadeTopAltitude - alt) / (this.fadeTopAltitude - this.fadeBottomAltitude)); + float fadeFactor = (alt < this.fadeBottomAltitude) ? 1f + : (float) ((this.fadeTopAltitude - alt) / (this.fadeTopAltitude - this.fadeBottomAltitude)); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -116,15 +118,14 @@ public void doRender(DrawContext dc) boolean modelviewPushed = false; boolean projectionPushed = false; - try - { + try { // GL setup gl.glPushAttrib(GL2.GL_DEPTH_BUFFER_BIT - | GL2.GL_COLOR_BUFFER_BIT - | GL2.GL_ENABLE_BIT - | GL2.GL_TRANSFORM_BIT - | GL2.GL_VIEWPORT_BIT - | GL2.GL_CURRENT_BIT); + | GL2.GL_COLOR_BUFFER_BIT + | GL2.GL_ENABLE_BIT + | GL2.GL_TRANSFORM_BIT + | GL2.GL_VIEWPORT_BIT + | GL2.GL_CURRENT_BIT); attribsPushed = true; gl.glEnable(GL.GL_BLEND); @@ -148,34 +149,30 @@ public void doRender(DrawContext dc) // Set color Color cc = this.color; - gl.glColor4d((float)cc.getRed() / 255f * fadeFactor, - (float)cc.getGreen() / 255f * fadeFactor, - (float)cc.getBlue() / 255f * fadeFactor, - (float)cc.getAlpha() / 255f * fadeFactor); + gl.glColor4d((float) cc.getRed() / 255f * fadeFactor, + (float) cc.getGreen() / 255f * fadeFactor, + (float) cc.getBlue() / 255f * fadeFactor, + (float) cc.getAlpha() / 255f * fadeFactor); // Draw gl.glDisable(GL.GL_TEXTURE_2D); // no textures dc.drawUnitQuad(); - } - finally - { - if (projectionPushed) - { + } finally { + if (projectionPushed) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); } - if (modelviewPushed) - { + if (modelviewPushed) { gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); } - if (attribsPushed) + if (attribsPushed) { gl.glPopAttrib(); + } } } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.Earth.SkyColorLayer.Name"); } diff --git a/src/gov/nasa/worldwind/layers/SkyGradientLayer.java b/src/gov/nasa/worldwind/layers/SkyGradientLayer.java index 3d522dbb60..4cb1756f01 100644 --- a/src/gov/nasa/worldwind/layers/SkyGradientLayer.java +++ b/src/gov/nasa/worldwind/layers/SkyGradientLayer.java @@ -21,20 +21,21 @@ * @author Patrick Murris * @version $Id: SkyGradientLayer.java 2146 2014-07-11 17:37:04Z tgaskins $ */ -public class SkyGradientLayer extends AbstractLayer -{ +public class SkyGradientLayer extends AbstractLayer { + protected final static int STACKS = 12; protected final static int SLICES = 64; // TODO: make configurable protected double thickness = 100e3; // Atmosphere thickness //protected float[] horizonColor = new float[] { 0.66f, 0.70f, 0.81f, 1.0f }; // horizon color (same as fog) - protected float[] horizonColor = new float[] {0.76f, 0.76f, 0.80f, 1.0f}; // horizon color - protected float[] zenithColor = new float[] {0.26f, 0.47f, 0.83f, 1.0f}; // zenith color + protected float[] horizonColor = new float[]{0.76f, 0.76f, 0.80f, 1.0f}; // horizon color + protected float[] zenithColor = new float[]{0.26f, 0.47f, 0.83f, 1.0f}; // zenith color - /** Renders an atmosphere around the globe */ - public SkyGradientLayer() - { + /** + * Renders an atmosphere around the globe + */ + public SkyGradientLayer() { this.setPickEnabled(false); } @@ -43,8 +44,7 @@ public SkyGradientLayer() * * @return the atmosphere thickness in meter */ - public double getAtmosphereThickness() - { + public double getAtmosphereThickness() { return this.thickness; } @@ -53,10 +53,8 @@ public double getAtmosphereThickness() * * @param thickness the atmosphere thickness in meter */ - public void setAtmosphereThickness(double thickness) - { - if (thickness < 0) - { + public void setAtmosphereThickness(double thickness) { + if (thickness < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -69,8 +67,7 @@ public void setAtmosphereThickness(double thickness) * * @return the horizon color */ - public Color getHorizonColor() - { + public Color getHorizonColor() { return new Color(this.horizonColor[0], this.horizonColor[1], this.horizonColor[2], this.horizonColor[3]); } @@ -79,10 +76,8 @@ public Color getHorizonColor() * * @param color the horizon color */ - public void setHorizonColor(Color color) - { - if (color == null) - { + public void setHorizonColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -95,8 +90,7 @@ public void setHorizonColor(Color color) * * @return the zenith color */ - public Color getZenithColor() - { + public Color getZenithColor() { return new Color(this.zenithColor[0], this.zenithColor[1], this.zenithColor[2], this.zenithColor[3]); } @@ -105,10 +99,8 @@ public Color getZenithColor() * * @param color the zenith color */ - public void setZenithColor(Color color) - { - if (color == null) - { + public void setZenithColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -117,16 +109,14 @@ public void setZenithColor(Color color) } @Override - public void doRender(DrawContext dc) - { - if (dc.is2DGlobe()) + public void doRender(DrawContext dc) { + if (dc.is2DGlobe()) { return; // Layer doesn't make sense in 2D - + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { ogsh.pushAttrib(gl, GL2.GL_TRANSFORM_BIT); gl.glDisable(GL.GL_DEPTH_TEST); @@ -139,9 +129,7 @@ public void doRender(DrawContext dc) // Draw sky this.updateSkyDome(dc); - } - finally - { + } finally { dc.restoreDefaultDepthTesting(); dc.restoreDefaultBlending(); dc.restoreDefaultCurrentColor(); @@ -149,8 +137,7 @@ public void doRender(DrawContext dc) } } - protected void applyDrawTransform(DrawContext dc, OGLStackHandler ogsh) - { + protected void applyDrawTransform(DrawContext dc, OGLStackHandler ogsh) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. View view = dc.getView(); ogsh.pushModelview(gl); @@ -163,29 +150,29 @@ protected void applyDrawTransform(DrawContext dc, OGLStackHandler ogsh) gl.glTranslatef(0.0f, (float) (view.getEyePoint().getLength3()), 0.0f); } - protected void applyDrawProjection(DrawContext dc, OGLStackHandler ogsh) - { + protected void applyDrawProjection(DrawContext dc, OGLStackHandler ogsh) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. View view = dc.getView(); double viewportWidth = view.getViewport().getWidth(); double viewportHeight = view.getViewport().getHeight(); // If either the viewport width or height is zero, then treat the dimension as if it had value 1. - if (viewportWidth <= 0) + if (viewportWidth <= 0) { viewportWidth = 1; - if (viewportHeight <= 0) + } + if (viewportHeight <= 0) { viewportHeight = 1; + } Matrix projection = Matrix.fromPerspective(view.getFieldOfView(), viewportWidth, viewportHeight, - 100, view.getHorizonDistance() + 10e3); + 100, view.getHorizonDistance() + 10e3); double[] matrixArray = new double[16]; projection.toArray(matrixArray, 0, false); ogsh.pushProjection(gl); gl.glLoadMatrixd(matrixArray, 0); } - protected void updateSkyDome(DrawContext dc) - { + protected void updateSkyDome(DrawContext dc) { View view = dc.getView(); double tangentialDistance = view.getHorizonDistance(); @@ -196,22 +183,20 @@ protected void updateSkyDome(DrawContext dc) // horizon latitude degrees double horizonLat = (-Math.PI / 2 + Math.acos(tangentialDistance / distToCenterOfPlanet)) - * 180 / Math.PI; + * 180 / Math.PI; // zenith latitude degrees double zenithLat = 90; float zenithOpacity = 1f; float gradientBias = 2f; - if (camAlt >= thickness) - { + if (camAlt >= thickness) { // Eye is above atmosphere double tangentalDistanceZenith = Math.sqrt(distToCenterOfPlanet * distToCenterOfPlanet - - (worldRadius + thickness) * (worldRadius + thickness)); + - (worldRadius + thickness) * (worldRadius + thickness)); zenithLat = (-Math.PI / 2 + Math.acos(tangentalDistanceZenith / distToCenterOfPlanet)) * 180 / Math.PI; zenithOpacity = 0f; gradientBias = 1f; } - if (camAlt < thickness && camAlt > thickness * 0.7) - { + if (camAlt < thickness && camAlt > thickness * 0.7) { // Eye is entering atmosphere - outer 30% double factor = (thickness - camAlt) / (thickness - thickness * 0.7); zenithLat = factor * 90; @@ -219,27 +204,25 @@ protected void updateSkyDome(DrawContext dc) gradientBias = 1f + (float) factor; } - this.drawSkyDome(dc, (float)tangentialDistance, horizonLat, zenithLat, SLICES, STACKS, zenithOpacity, gradientBias); + this.drawSkyDome(dc, (float) tangentialDistance, horizonLat, zenithLat, SLICES, STACKS, zenithOpacity, gradientBias); } /** * Draws the sky dome * - * @param dc the current DrawContext - * @param radius the sky dome radius - * @param startLat the horizon latitude - * @param endLat the zenith latitude - * @param slices the number of slices - vertical divisions - * @param stacks the nuber os stacks - horizontal divisions + * @param dc the current DrawContext + * @param radius the sky dome radius + * @param startLat the horizon latitude + * @param endLat the zenith latitude + * @param slices the number of slices - vertical divisions + * @param stacks the nuber os stacks - horizontal divisions * @param zenithOpacity the sky opacity at zenith - * @param gradientBias determines how fast the sky goes from the horizon color to the zenith color. A value of - * 1 with produce a balanced gradient, a value greater then 1 will - * have the zenith color dominate and a value less then 1 will have the opposite - * effect. + * @param gradientBias determines how fast the sky goes from the horizon color to the zenith color. A value of + * 1 with produce a balanced gradient, a value greater then 1 will have the zenith color + * dominate and a value less then 1 will have the opposite effect. */ protected void drawSkyDome(DrawContext dc, float radius, double startLat, double endLat, - int slices, int stacks, float zenithOpacity, float gradientBias) - { + int slices, int stacks, float zenithOpacity, float gradientBias) { double latitude, longitude, latitudeTop = endLat; // GL setup @@ -253,8 +236,7 @@ protected void drawSkyDome(DrawContext dc, float radius, double startLat, double // bottom fade latitude = startLat - Math.max((endLat - startLat) / 4, 3); gl.glBegin(GL2.GL_QUAD_STRIP); - for (int slice = 0; slice <= slices; slice++) - { + for (int slice = 0; slice <= slices; slice++) { longitude = 180 - ((float) slice / slices * (float) 360); Vec4 v = SphericalToCartesian(latitude, longitude, radius); gl.glColor4d(zenithColor[0], zenithColor[1], zenithColor[2], 0); @@ -266,8 +248,7 @@ protected void drawSkyDome(DrawContext dc, float radius, double startLat, double gl.glEnd(); // stacks and slices - for (int stack = 1; stack < stacks - 1; stack++) - { + for (int stack = 1; stack < stacks - 1; stack++) { // bottom vertex linear = (float) (stack - 1) / (stacks - 1f); k = 1 - Math.cos(linear * Math.PI / 2); @@ -284,22 +265,21 @@ protected void drawSkyDome(DrawContext dc, float radius, double startLat, double alphaFactorTop = 1 - Math.pow(linearTop, 4) * (1 - zenithOpacity); // coef alpha transparency // Draw stack gl.glBegin(GL2.GL_QUAD_STRIP); - for (int slice = 0; slice <= slices; slice++) - { + for (int slice = 0; slice <= slices; slice++) { longitude = 180 - ((float) slice / slices * (float) 360); Vec4 v = SphericalToCartesian(latitude, longitude, radius); gl.glColor4d( - (horizonColor[0] * colorFactorH + zenithColor[0] * colorFactorZ), - (horizonColor[1] * colorFactorH + zenithColor[1] * colorFactorZ), - (horizonColor[2] * colorFactorH + zenithColor[2] * colorFactorZ), - (horizonColor[3] * colorFactorH + zenithColor[3] * colorFactorZ) * alphaFactor); + (horizonColor[0] * colorFactorH + zenithColor[0] * colorFactorZ), + (horizonColor[1] * colorFactorH + zenithColor[1] * colorFactorZ), + (horizonColor[2] * colorFactorH + zenithColor[2] * colorFactorZ), + (horizonColor[3] * colorFactorH + zenithColor[3] * colorFactorZ) * alphaFactor); gl.glVertex3d(v.getX(), v.getY(), v.getZ()); v = SphericalToCartesian(latitudeTop, longitude, radius); gl.glColor4d( - (horizonColor[0] * colorFactorHTop + zenithColor[0] * colorFactorZTop), - (horizonColor[1] * colorFactorHTop + zenithColor[1] * colorFactorZTop), - (horizonColor[2] * colorFactorHTop + zenithColor[2] * colorFactorZTop), - (horizonColor[3] * colorFactorHTop + zenithColor[3] * colorFactorZTop) * alphaFactorTop); + (horizonColor[0] * colorFactorHTop + zenithColor[0] * colorFactorZTop), + (horizonColor[1] * colorFactorHTop + zenithColor[1] * colorFactorZTop), + (horizonColor[2] * colorFactorHTop + zenithColor[2] * colorFactorZTop), + (horizonColor[3] * colorFactorHTop + zenithColor[3] * colorFactorZTop) * alphaFactorTop); gl.glVertex3d(v.getX(), v.getY(), v.getZ()); } gl.glEnd(); @@ -307,15 +287,14 @@ protected void drawSkyDome(DrawContext dc, float radius, double startLat, double // Top fade gl.glBegin(GL2.GL_QUAD_STRIP); - for (int slice = 0; slice <= slices; slice++) - { + for (int slice = 0; slice <= slices; slice++) { longitude = 180 - ((float) slice / slices * (float) 360); Vec4 v = SphericalToCartesian(latitudeTop, longitude, radius); gl.glColor4d( - (horizonColor[0] * colorFactorHTop + zenithColor[0] * colorFactorZTop), - (horizonColor[1] * colorFactorHTop + zenithColor[1] * colorFactorZTop), - (horizonColor[2] * colorFactorHTop + zenithColor[2] * colorFactorZTop), - (horizonColor[3] * colorFactorHTop + zenithColor[3] * colorFactorZTop) * alphaFactorTop); + (horizonColor[0] * colorFactorHTop + zenithColor[0] * colorFactorZTop), + (horizonColor[1] * colorFactorHTop + zenithColor[1] * colorFactorZTop), + (horizonColor[2] * colorFactorHTop + zenithColor[2] * colorFactorZTop), + (horizonColor[3] * colorFactorHTop + zenithColor[3] * colorFactorZTop) * alphaFactorTop); gl.glVertex3d(v.getX(), v.getY(), v.getZ()); v = SphericalToCartesian(endLat, longitude, radius); gl.glColor4d(zenithColor[0], zenithColor[1], zenithColor[2], zenithOpacity < 1 ? 0 : zenithColor[3]); @@ -328,7 +307,7 @@ protected void drawSkyDome(DrawContext dc, float radius, double startLat, double /** * Draws the positive three axes - x is red, y is green and z is blue * - * @param dc the current DrawContext + * @param dc the current DrawContext * @param length the lenght of the axes lines */ // private static void DrawAxis(DrawContext dc, float length) { @@ -348,27 +327,25 @@ protected void drawSkyDome(DrawContext dc, float radius, double startLat, double // // gl.glEnd(); // } - /** * Converts position in spherical coordinates (lat/lon/altitude) to cartesian (XYZ) coordinates. * - * @param latitude Latitude in decimal degrees + * @param latitude Latitude in decimal degrees * @param longitude Longitude in decimal degrees - * @param radius Radius + * @param radius Radius * * @return the corresponding Point */ - protected static Vec4 SphericalToCartesian(double latitude, double longitude, double radius) - { + protected static Vec4 SphericalToCartesian(double latitude, double longitude, double radius) { latitude *= Math.PI / 180.0f; longitude *= Math.PI / 180.0f; double radCosLat = radius * Math.cos(latitude); return new Vec4( - radCosLat * Math.sin(longitude), - radius * Math.sin(latitude), - radCosLat * Math.cos(longitude)); + radCosLat * Math.sin(longitude), + radius * Math.sin(latitude), + radCosLat * Math.cos(longitude)); } /** @@ -380,8 +357,7 @@ protected static Vec4 SphericalToCartesian(double latitude, double longitude, do * * @return a Vec4 point for the spherical coordinates {radius, lat, lon} */ - protected static Vec4 CartesianToSpherical(double x, double y, double z) - { + protected static Vec4 CartesianToSpherical(double x, double y, double z) { double rho = Math.sqrt(x * x + y * y + z * z); double longitude = Math.atan2(x, z); double latitude = Math.asin(y / rho); @@ -390,8 +366,7 @@ protected static Vec4 CartesianToSpherical(double x, double y, double z) } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.Earth.SkyGradientLayer.Name"); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/layers/StarsConvertor.java b/src/gov/nasa/worldwind/layers/StarsConvertor.java index 7ec22fe028..2b42c69e54 100644 --- a/src/gov/nasa/worldwind/layers/StarsConvertor.java +++ b/src/gov/nasa/worldwind/layers/StarsConvertor.java @@ -21,8 +21,8 @@ * @author Patrick Murris * @version $Id: StarsConvertor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class StarsConvertor -{ +public class StarsConvertor { + private static final float DEFAULT_RADIUS = 6356752 * 10; // Earth radius x 10 /** @@ -30,8 +30,7 @@ public class StarsConvertor * * @param tsvFileName name of tsv text star file */ - public static void convertTsvToDat(String tsvFileName) - { + public static void convertTsvToDat(String tsvFileName) { String datFileName = WWIO.replaceSuffix(tsvFileName, ".dat"); convertTsvToDat(tsvFileName, datFileName, DEFAULT_RADIUS); @@ -41,10 +40,9 @@ public static void convertTsvToDat(String tsvFileName) * Convert star tsv text file to binary dat file * * @param tsvFileName name of tsv text star file - * @param radius radius of star sphere + * @param radius radius of star sphere */ - public static void convertTsvToDat(String tsvFileName, float radius) - { + public static void convertTsvToDat(String tsvFileName, float radius) { String datFileName = WWIO.replaceSuffix(tsvFileName, ".dat"); convertTsvToDat(tsvFileName, datFileName, radius); @@ -56,8 +54,7 @@ public static void convertTsvToDat(String tsvFileName, float radius) * @param tsvFileName name of tsv text star file * @param datFileName name of dat binary star file */ - public static void convertTsvToDat(String tsvFileName, String datFileName) - { + public static void convertTsvToDat(String tsvFileName, String datFileName) { convertTsvToDat(tsvFileName, datFileName, DEFAULT_RADIUS); } @@ -66,21 +63,17 @@ public static void convertTsvToDat(String tsvFileName, String datFileName) * * @param tsvFileName name of tsv text star file * @param datFileName name of dat binary star file - * @param radius radius of star sphere + * @param radius radius of star sphere */ - public static void convertTsvToDat(String tsvFileName, String datFileName, float radius) - { + public static void convertTsvToDat(String tsvFileName, String datFileName, float radius) { //Convert the Tsv Star file to a ByteBuffer in little-endian order ByteBuffer bbuf = convertTsvToByteBuffer(tsvFileName, radius); - try - { + try { WWIO.saveBuffer(bbuf, new File(datFileName)); - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("generic.ExceptionAttemptingToWriteTo", datFileName), e); + Logging.getMessage("generic.ExceptionAttemptingToWriteTo", datFileName), e); } } @@ -91,8 +84,7 @@ public static void convertTsvToDat(String tsvFileName, String datFileName, float * * @return ByteBuffer with interleaved color and vertex positions as floats in little-endian order */ - public static ByteBuffer convertTsvToByteBuffer(String starsFileName) - { + public static ByteBuffer convertTsvToByteBuffer(String starsFileName) { return convertTsvToByteBuffer(starsFileName, DEFAULT_RADIUS); } @@ -100,30 +92,27 @@ public static ByteBuffer convertTsvToByteBuffer(String starsFileName) * Converts a Stars tsv file to a ByteBuffer * * @param starsFileName filename of tsv file - * @param radius radius of the sphere on which to paint stars + * @param radius radius of the sphere on which to paint stars * * @return ByteBuffer with interleaved color and vertex positions as floats in little-endian order */ - public static ByteBuffer convertTsvToByteBuffer(String starsFileName, float radius) - { - try - { + public static ByteBuffer convertTsvToByteBuffer(String starsFileName, float radius) { + try { ArrayList tmpBuffer = new ArrayList(); InputStream starsStream = StarsConvertor.class.getResourceAsStream("/" + starsFileName); - if (starsStream == null) - { + if (starsStream == null) { File starsFile = new File(starsFileName); - if (starsFile.exists()) - { + if (starsFile.exists()) { starsStream = new FileInputStream(starsFile); } } - if (starsStream == null) - // TODO: logger error + if (starsStream == null) // TODO: logger error + { return null; + } BufferedReader starsReader = new BufferedReader(new InputStreamReader(starsStream)); @@ -139,12 +128,13 @@ public static ByteBuffer convertTsvToByteBuffer(String starsFileName, float radi //Add the radius as the first value tmpBuffer.add(radius); - while ((line = starsReader.readLine()) != null) - { - if (line.length() < 3) + while ((line = starsReader.readLine()) != null) { + if (line.length() < 3) { continue; - if (line.substring(0, 1).equals("#")) + } + if (line.substring(0, 1).equals("#")) { continue; + } if (isData) // Star data here { // Split data in ';' separated values @@ -167,22 +157,21 @@ public static ByteBuffer convertTsvToByteBuffer(String starsFileName, float radi double DEm = Double.parseDouble(DEdms.substring(4, 6)); double DEs = Double.parseDouble(DEdms.substring(7)); latitude = DEd + (DEm / 60) + (DEs / 3600); - if (DEsign.equals("-")) + if (DEsign.equals("-")) { latitude *= -1; + } // compute aparent magnitude -1.5 - 10 to grayscale 0 - 255 double VM = Double.parseDouble(Vmag); double Vdec = 255 - ((VM + 1.5) * 255 / 10); - if (Vdec > 255) + if (Vdec > 255) { Vdec = 255; + } Vdec /= 255; // scale back to 0.0 - 1.0 // convert B-V -0.5 - 4 for rgb color select double BVdec; - try - { + try { BVdec = Double.parseDouble(BV); - } - catch (Exception e) - { + } catch (Exception e) { BVdec = 0; } @@ -200,8 +189,9 @@ public static ByteBuffer convertTsvToByteBuffer(String starsFileName, float radi } // Data starting next line - if (line.substring(0, 3).equals("---")) + if (line.substring(0, 3).equals("---")) { isData = true; + } } starsReader.close(); @@ -210,24 +200,19 @@ public static ByteBuffer convertTsvToByteBuffer(String starsFileName, float radi buf.order(ByteOrder.LITTLE_ENDIAN); FloatBuffer fBuf = buf.asFloatBuffer(); - for (Float fVal : tmpBuffer) - { + for (Float fVal : tmpBuffer) { fBuf.put(fVal); } buf.rewind(); return buf; - } - catch (IOException e) - { + } catch (IOException e) { // TODO: Log proper message //String message = WorldWind.retrieveErrMsg("generic.IOExceptionWhileLoadingData"); String message = "IOException while loading stars data from " + starsFileName; Logging.logger().severe(message); - } - catch (Exception e) - { + } catch (Exception e) { String message = "Error while loading stars data from " + starsFileName; Logging.logger().severe(message); } @@ -238,23 +223,22 @@ public static ByteBuffer convertTsvToByteBuffer(String starsFileName, float radi /** * Converts position in spherical coordinates (lat/lon/radius) to cartesian (XYZ) coordinates. * - * @param latitude Latitude in decimal degrees + * @param latitude Latitude in decimal degrees * @param longitude Longitude in decimal degrees - * @param radius Radius + * @param radius Radius * * @return the corresponding Point */ - private static Vec4 SphericalToCartesian(double latitude, double longitude, float radius) - { + private static Vec4 SphericalToCartesian(double latitude, double longitude, float radius) { latitude *= Math.PI / 180.0f; longitude *= Math.PI / 180.0f; double radCosLat = radius * Math.cos(latitude); return new Vec4( - radCosLat * Math.sin(longitude), - (double) radius * Math.sin(latitude), - radCosLat * Math.cos(longitude)); + radCosLat * Math.sin(longitude), + (double) radius * Math.sin(latitude), + radCosLat * Math.cos(longitude)); } /** @@ -264,35 +248,34 @@ private static Vec4 SphericalToCartesian(double latitude, double longitude, floa * * @return the corresponding Color */ - private static Color BVColor(double BV) - { + private static Color BVColor(double BV) { // TODO: interpolate between values - if (BV < 0) + if (BV < 0) { return new Color(.635f, .764f, .929f); // Light blue - else if (BV < .5) + } else if (BV < .5) { return new Color(1f, 1f, 1f); // White - else if (BV < 1) + } else if (BV < 1) { return new Color(1f, .984f, .266f); // Yellow - else if (BV < 1.5) + } else if (BV < 1.5) { return new Color(.964f, .725f, .0784f); // Orange - else + } else { return new Color(.921f, .376f, .0392f); // Redish + } } - public static void main(String[] args) - { + public static void main(String[] args) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setMultiSelectionEnabled(true); int status = fileChooser.showOpenDialog(null); - if (status != JFileChooser.APPROVE_OPTION) + if (status != JFileChooser.APPROVE_OPTION) { return; + } File[] files = fileChooser.getSelectedFiles(); - if (files == null) - { + if (files == null) { System.out.println("No files selected"); return; } @@ -302,26 +285,21 @@ public static void main(String[] args) float radius; - while (true) - { - try - { + while (true) { + try { radius = Float.parseFloat(ans); break; - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.NumberFormatException"); Logging.logger().warning(message); ans = JOptionPane.showInputDialog( - "INVALID VALUE: Please enter a floating point number." + "INVALID VALUE: Please enter a floating point number." + "
        Enter star sphere radius?", DEFAULT_RADIUS); } } - for (File file : files) - { + for (File file : files) { convertTsvToDat(file.getAbsolutePath(), radius); } } diff --git a/src/gov/nasa/worldwind/layers/StarsLayer.java b/src/gov/nasa/worldwind/layers/StarsLayer.java index aba50d43f3..8c1c2b71eb 100644 --- a/src/gov/nasa/worldwind/layers/StarsLayer.java +++ b/src/gov/nasa/worldwind/layers/StarsLayer.java @@ -21,30 +21,43 @@ * @author Patrick Murris * @version $Id: StarsLayer.java 2176 2014-07-25 16:35:25Z dcollins $ */ -public class StarsLayer extends RenderableLayer -{ - /** The default name of the stars file.s */ +public class StarsLayer extends RenderableLayer { + + /** + * The default name of the stars file.s + */ protected static final String DEFAULT_STARS_FILE = "config/Hipparcos_Stars_Mag6x5044.dat"; protected static final double DEFAULT_MIN_ACTIVE_ALTITUDE = 100e3; - /** The stars file name. */ - protected String starsFileName = - Configuration.getStringValue("gov.nasa.worldwind.StarsLayer.StarsFileName", DEFAULT_STARS_FILE); - /** The float buffer holding the Cartesian star coordinates. */ + /** + * The stars file name. + */ + protected String starsFileName + = Configuration.getStringValue("gov.nasa.worldwind.StarsLayer.StarsFileName", DEFAULT_STARS_FILE); + /** + * The float buffer holding the Cartesian star coordinates. + */ protected FloatBuffer starsBuffer; protected int numStars; protected boolean rebuild; // True if need to rebuild GL list - /** The radius of the spherical shell containing the stars. */ + /** + * The radius of the spherical shell containing the stars. + */ protected Double radius; // radius is either set explicitly or taken from the star file - /** The star sphere longitudinal rotation. */ + /** + * The star sphere longitudinal rotation. + */ protected Angle longitudeOffset = Angle.ZERO; - /** The star sphere latitudinal rotation. */ + /** + * The star sphere latitudinal rotation. + */ protected Angle latitudeOffset = Angle.ZERO; protected Object vboCacheKey = new Object(); - /** Constructs a stars layer using the default stars file, which may be specified in {@link Configuration}. */ - public StarsLayer() - { + /** + * Constructs a stars layer using the default stars file, which may be specified in {@link Configuration}. + */ + public StarsLayer() { this.initialize(null, null); } @@ -53,8 +66,7 @@ public StarsLayer() * * @param starsFileName the full path the star file. */ - public StarsLayer(String starsFileName) - { + public StarsLayer(String starsFileName) { this.initialize(starsFileName, null); } @@ -62,13 +74,10 @@ public StarsLayer(String starsFileName) * Constructs a stars layer using a specified stars file and star-field radius. * * @param starsFileName the full path the star file. - * @param radius the radius of the stars sphere. May be null, in which case the radius in the stars file is - * used. + * @param radius the radius of the stars sphere. May be null, in which case the radius in the stars file is used. */ - public StarsLayer(String starsFileName, Double radius) - { - if (WWUtil.isEmpty(starsFileName)) - { + public StarsLayer(String starsFileName, Double radius) { + if (WWUtil.isEmpty(starsFileName)) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -82,16 +91,16 @@ public StarsLayer(String starsFileName, Double radius) * altitude. * * @param starsFileName the full path the star file. - * @param radius the radius of the stars sphere. May be null, in which case the radius in the stars file is - * used. + * @param radius the radius of the stars sphere. May be null, in which case the radius in the stars file is used. */ - protected void initialize(String starsFileName, Double radius) - { - if (starsFileName != null) + protected void initialize(String starsFileName, Double radius) { + if (starsFileName != null) { this.setStarsFileName(starsFileName); + } - if (radius != null) + if (radius != null) { this.radius = radius; + } this.setPickEnabled(false); @@ -104,8 +113,7 @@ protected void initialize(String starsFileName, Double radius) * * @return name of stars catalog file. */ - public String getStarsFileName() - { + public String getStarsFileName() { return this.starsFileName; } @@ -116,10 +124,8 @@ public String getStarsFileName() * * @throws IllegalArgumentException if the file name is null or empty. */ - public void setStarsFileName(String fileName) - { - if (WWUtil.isEmpty(fileName)) - { + public void setStarsFileName(String fileName) { + if (WWUtil.isEmpty(fileName)) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -134,8 +140,7 @@ public void setStarsFileName(String fileName) * * @return the latitude offset. */ - public Angle getLatitudeOffset() - { + public Angle getLatitudeOffset() { return this.latitudeOffset; } @@ -144,10 +149,8 @@ public Angle getLatitudeOffset() * * @param offset the latitude offset. */ - public void setLatitudeOffset(Angle offset) - { - if (offset == null) - { + public void setLatitudeOffset(Angle offset) { + if (offset == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -160,8 +163,7 @@ public void setLatitudeOffset(Angle offset) * * @return the longitude offset. */ - public Angle getLongitudeOffset() - { + public Angle getLongitudeOffset() { return this.longitudeOffset; } @@ -172,10 +174,8 @@ public Angle getLongitudeOffset() * * @throws IllegalArgumentException if the angle is null.s */ - public void setLongitudeOffset(Angle offset) - { - if (offset == null) - { + public void setLongitudeOffset(Angle offset) { + if (offset == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -185,38 +185,37 @@ public void setLongitudeOffset(Angle offset) } @Override - public void doRender(DrawContext dc) - { - if (dc.is2DGlobe()) + public void doRender(DrawContext dc) { + if (dc.is2DGlobe()) { return; // Layer doesn't make sense in 2D - + } // Load or reload stars if not previously loaded - if (this.starsBuffer == null || this.rebuild) - { + if (this.starsBuffer == null || this.rebuild) { this.loadStars(); this.rebuild = false; } // Still no stars to render ? - if (this.starsBuffer == null) + if (this.starsBuffer == null) { return; + } // Exit if the viewport is not visible, in which case rendering results in exceptions. View view = dc.getView(); - if (view.getViewport().getWidth() == 0 || view.getViewport().getHeight() == 0) + if (view.getViewport().getWidth() == 0 || view.getViewport().getHeight() == 0) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); double[] matrixArray = new double[16]; - try - { + try { gl.glDisable(GL.GL_DEPTH_TEST); // Override the default projection matrix in order to extend the far clip plane to include the stars. Matrix projection = Matrix.fromPerspective(view.getFieldOfView(), view.getViewport().width, - view.getViewport().height, 1, this.radius + 1); + view.getViewport().height, 1, this.radius + 1); ogsh.pushProjectionIdentity(gl); gl.glLoadMatrixd(projection.toArray(matrixArray, 0, false), 0); @@ -233,40 +232,34 @@ public void doRender(DrawContext dc) // Draw ogsh.pushClientAttrib(gl, GL2.GL_CLIENT_VERTEX_ARRAY_BIT); - if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) - { - if (!this.drawWithVBO(dc)) + if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) { + if (!this.drawWithVBO(dc)) { this.drawWithVertexArray(dc); - } - else - { + } + } else { this.drawWithVertexArray(dc); } - } - finally - { + } finally { dc.restoreDefaultDepthTesting(); ogsh.pop(gl); } } - protected void drawWithVertexArray(DrawContext dc) - { + protected void drawWithVertexArray(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glInterleavedArrays(GL2.GL_C3F_V3F, 0, this.starsBuffer); gl.glDrawArrays(GL.GL_POINTS, 0, this.numStars); } - protected boolean drawWithVBO(DrawContext dc) - { + protected boolean drawWithVBO(DrawContext dc) { int[] vboId = (int[]) dc.getGpuResourceCache().get(this.vboCacheKey); - if (vboId == null) - { + if (vboId == null) { this.fillVbo(dc); vboId = (int[]) dc.getGpuResourceCache().get(this.vboCacheKey); - if (vboId == null) + if (vboId == null) { return false; + } } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -284,8 +277,7 @@ protected boolean drawWithVBO(DrawContext dc) * * @param dc the current draw context. */ - protected void fillVbo(DrawContext dc) - { + protected void fillVbo(DrawContext dc) { GL gl = dc.getGL(); //Create a new bufferId @@ -298,69 +290,58 @@ protected void fillVbo(DrawContext dc) // Add it to the gpu resource cache dc.getGpuResourceCache().put(this.vboCacheKey, glBuf, GpuResourceCache.VBO_BUFFERS, - this.starsBuffer.limit() * 4); + this.starsBuffer.limit() * 4); } - /** Read stars file and load it into a float buffer. */ - protected void loadStars() - { + /** + * Read stars file and load it into a float buffer. + */ + protected void loadStars() { ByteBuffer byteBuffer = null; - if (WWIO.getSuffix(this.starsFileName).equals("dat")) - { - try - { + if (WWIO.getSuffix(this.starsFileName).equals("dat")) { + try { //Try loading from a resource InputStream starsStream = WWIO.openFileOrResourceStream(this.starsFileName, this.getClass()); - if (starsStream == null) - { + if (starsStream == null) { String message = Logging.getMessage("layers.StarLayer.CannotReadStarFile"); Logging.logger().severe(message); return; } //Read in the binary buffer - try - { + try { byteBuffer = WWIO.readStreamToBuffer(starsStream, true); // Read stars to a direct ByteBuffer. byteBuffer.order(ByteOrder.LITTLE_ENDIAN); - } - finally - { + } finally { WWIO.closeStream(starsStream, starsFileName); } - } - catch (IOException e) - { + } catch (IOException e) { String message = "IOException while loading stars data from " + this.starsFileName; Logging.logger().severe(message); } - } - else - { + } else { //Assume it is a tsv text file byteBuffer = StarsConvertor.convertTsvToByteBuffer(this.starsFileName); } - if (byteBuffer == null) - { + if (byteBuffer == null) { String message = "IOException while loading stars data from " + this.starsFileName; Logging.logger().severe(message); return; } //Grab the radius from the first value in the buffer - if (this.radius == null) + if (this.radius == null) { this.radius = (double) byteBuffer.getFloat(); - else + } else { byteBuffer.getFloat(); // skip over it - + } //View the rest of the ByteBuffer as a FloatBuffer this.starsBuffer = byteBuffer.asFloatBuffer(); //byteBuffer is Little-Endian. If native order is not Little-Endian, switch to Big-Endian. - if (byteBuffer.order() != ByteOrder.nativeOrder()) - { + if (byteBuffer.order() != ByteOrder.nativeOrder()) { //tmpByteBuffer is allocated as Big-Endian on all systems ByteBuffer tmpByteBuffer = ByteBuffer.allocateDirect(byteBuffer.limit()); @@ -368,8 +349,7 @@ protected void loadStars() FloatBuffer fbuffer = tmpByteBuffer.asFloatBuffer(); //Fill it with the floats in starsBuffer - for (int i = 0; i < fbuffer.limit(); i++) - { + for (int i = 0; i < fbuffer.limit(); i++) { fbuffer.put(this.starsBuffer.get(i)); } @@ -384,8 +364,7 @@ protected void loadStars() } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.Earth.StarsLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/SurfaceImageLayer.java b/src/gov/nasa/worldwind/layers/SurfaceImageLayer.java index bf316cad0e..bbdfdf5584 100644 --- a/src/gov/nasa/worldwind/layers/SurfaceImageLayer.java +++ b/src/gov/nasa/worldwind/layers/SurfaceImageLayer.java @@ -28,17 +28,16 @@ * @author tag * @version $Id: SurfaceImageLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SurfaceImageLayer extends RenderableLayer -{ +public class SurfaceImageLayer extends RenderableLayer { + protected ImageTiler imageTiler = new ImageTiler(); - protected ConcurrentHashMap> imageTable = - new ConcurrentHashMap>(); + protected ConcurrentHashMap> imageTable + = new ConcurrentHashMap>(); protected BasicDataRasterReaderFactory factory = new BasicDataRasterReaderFactory(); @Override - public void dispose() - { + public void dispose() { super.dispose(); this.imageTable.clear(); @@ -58,34 +57,29 @@ public void dispose() * @param imagePath the path to the image file. * * @throws IllegalArgumentException if the image path is null. - * @throws IOException if an error occurs reading the image file. - * @throws IllegalStateException if an error occurs while reprojecting or otherwise processing the image. - * @throws WWRuntimeException if the image type is unsupported. + * @throws IOException if an error occurs reading the image file. + * @throws IllegalStateException if an error occurs while reprojecting or otherwise processing the image. + * @throws WWRuntimeException if the image type is unsupported. */ - public void addImage(final String imagePath) throws IOException - { + public void addImage(final String imagePath) throws IOException { DataRaster raster = this.openDataRaster(imagePath, null); final BufferedImage image = this.getBufferedImage(raster); - if (null != raster && image != null) - { + if (null != raster && image != null) { addImage(imagePath, image, raster.getSector()); - } - else - { + } else { String message = Logging.getMessage("generic.ImageReadFailed", imagePath); Logging.logger().severe(message); throw new WWRuntimeException(message); } } - protected BufferedImage getBufferedImage(DataRaster raster) - { - if (null == raster) + protected BufferedImage getBufferedImage(DataRaster raster) { + if (null == raster) { return null; + } - if (raster instanceof GDALDataRaster) - { + if (raster instanceof GDALDataRaster) { AVList params = new AVListImpl(); params.setValue(AVKey.WIDTH, raster.getWidth()); @@ -95,13 +89,11 @@ protected BufferedImage getBufferedImage(DataRaster raster) raster = raster.getSubRaster(params); } - if (raster instanceof BufferedImageRaster) - { + if (raster instanceof BufferedImageRaster) { return ((BufferedImageRaster) raster).getBufferedImage(); } - if (raster instanceof BufferWrapperRaster) - { + if (raster instanceof BufferWrapperRaster) { return ImageUtil.visualize((BufferWrapperRaster) raster); } @@ -109,34 +101,30 @@ protected BufferedImage getBufferedImage(DataRaster raster) } protected DataRaster openDataRaster(Object src, AVList params) - throws IllegalArgumentException, WWRuntimeException - { - if (src == null) - { + throws IllegalArgumentException, WWRuntimeException { + if (src == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } final File rasterFile = WWIO.getFileForLocalAddress(src); - if (null == rasterFile || !rasterFile.exists()) - { + if (null == rasterFile || !rasterFile.exists()) { String message = Logging.getMessage("generic.FileNotFound", src); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == params) + if (null == params) { params = new AVListImpl(); + } DataRaster raster; - try - { + try { DataRasterReader reader = factory.findReaderFor(rasterFile, params); DataRaster[] rasters = reader.read(rasterFile, params); - if (null == rasters || rasters.length == 0 || null == rasters[0]) - { + if (null == rasters || rasters.length == 0 || null == rasters[0]) { String message = Logging.getMessage("generic.ImageReadFailed", src); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -144,34 +132,28 @@ protected DataRaster openDataRaster(Object src, AVList params) raster = rasters[0]; - if (raster.getSector() == null && params.hasKey(AVKey.SECTOR)) - { + if (raster.getSector() == null && params.hasKey(AVKey.SECTOR)) { Object o = params.getValue(AVKey.SECTOR); - if (null != o && o instanceof Sector) - { + if (null != o && o instanceof Sector) { Sector sector = (Sector) o; - if (raster instanceof GDALDataRaster) + if (raster instanceof GDALDataRaster) { ((GDALDataRaster) raster).setSector(sector); - else + } else { raster.setValue(AVKey.SECTOR, sector); + } } } - if (raster.getSector() == null) - { + if (raster.getSector() == null) { String reason = Logging.getMessage("nullValue.SpatialReferenceIsNull"); String message = Logging.getMessage("generic.ImageReadFailed", src + ":" + reason); Logging.logger().severe(message); throw new WWRuntimeException(message); } - } - catch (WWRuntimeException wwre) - { + } catch (WWRuntimeException wwre) { throw wwre; - } - catch (Throwable t) - { + } catch (Throwable t) { String reason = WWUtil.extractExceptionReason(t); String message = Logging.getMessage("generic.ImageReadFailed", reason); Logging.logger().severe(message); @@ -186,31 +168,28 @@ protected DataRaster openDataRaster(Object src, AVList params) * (latitude and longitude). * * @param imagePath the path to the image file. - * @param sector the geographic location of the image. + * @param sector the geographic location of the image. * * @throws IllegalArgumentException if the image path or sector is null. - * @throws IOException if an error occurs reading the image file. - * @throws WWRuntimeException if the image type is unsupported. + * @throws IOException if an error occurs reading the image file. + * @throws WWRuntimeException if the image type is unsupported. */ @SuppressWarnings({"UnusedDeclaration"}) - public void addImage(String imagePath, Sector sector) throws IOException, WWRuntimeException - { + public void addImage(String imagePath, Sector sector) throws IOException, WWRuntimeException { AVList params = new AVListImpl(); - if (null != sector) + if (null != sector) { params.setValue(AVKey.SECTOR, sector); + } DataRaster raster = this.openDataRaster(imagePath, params); final BufferedImage image = this.getBufferedImage(raster); - if (null != raster && image != null) - { + if (null != raster && image != null) { Sector rasterSector = raster.getSector(); rasterSector = (null == rasterSector) ? sector : rasterSector; addImage(imagePath, image, rasterSector); - } - else - { + } else { String message = Logging.getMessage("generic.ImageReadFailed", imagePath); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -221,48 +200,42 @@ public void addImage(String imagePath, Sector sector) throws IOException, WWRunt * Add a {@link BufferedImage} to the collection at an explicitly specified location. The image is assumed to be in * geographic projection (latitude and longitude). * - * @param name a unique name to associate with the image so that it can be subsequently referred to without having - * to keep a reference to the image itself. Use this name in calls to {@link #removeImage(String)}. - * @param image the image to add. + * @param name a unique name to associate with the image so that it can be subsequently referred to without having + * to keep a reference to the image itself. Use this name in calls to {@link #removeImage(String)}. + * @param image the image to add. * @param sector the geographic location of the image. * * @throws IllegalArgumentException if the image path or sector is null. - * @throws WWRuntimeException if the image type is unsupported. + * @throws WWRuntimeException if the image type is unsupported. */ - public void addImage(String name, BufferedImage image, Sector sector) - { - if (name == null) - { + public void addImage(String name, BufferedImage image, Sector sector) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (image == null) - { + if (image == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.imageTable.contains(name)) + if (this.imageTable.contains(name)) { this.removeImage(name); + } final ArrayList surfaceImages = new ArrayList(); this.imageTable.put(name, surfaceImages); - this.imageTiler.tileImage(image, sector, new ImageTiler.ImageTilerListener() - { - public void newTile(BufferedImage tileImage, Sector tileSector) - { - try - { + this.imageTiler.tileImage(image, sector, new ImageTiler.ImageTilerListener() { + public void newTile(BufferedImage tileImage, Sector tileSector) { + try { File tempFile = File.createTempFile("wwj-", ".png"); tempFile.deleteOnExit(); ImageIO.write(tileImage, "png", tempFile); @@ -270,16 +243,13 @@ public void newTile(BufferedImage tileImage, Sector tileSector) surfaceImages.add(si); si.setOpacity(SurfaceImageLayer.this.getOpacity()); SurfaceImageLayer.this.addRenderable(si); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ImageReadFailed"); Logging.logger().severe(message); } } - public void newTile(BufferedImage tileImage, List corners) - { + public void newTile(BufferedImage tileImage, List corners) { } }); } @@ -289,19 +259,17 @@ public void newTile(BufferedImage tileImage, List corners) * projection (latitude and longitude). * * @param imagePath the path to the image file. - * @param corners the geographic location of the image's corners, specified in order of lower-left, lower-right, - * upper-right, upper-left. + * @param corners the geographic location of the image's corners, specified in order of lower-left, lower-right, + * upper-right, upper-left. * * @throws IllegalArgumentException if the image path or sector is null. - * @throws IOException if an error occurs reading the image file. - * @throws WWRuntimeException if the image type is unsupported. + * @throws IOException if an error occurs reading the image file. + * @throws WWRuntimeException if the image type is unsupported. */ - public void addImage(String imagePath, List corners) throws IOException, WWRuntimeException - { + public void addImage(String imagePath, List corners) throws IOException, WWRuntimeException { AVList params = new AVListImpl(); - if (null != corners) - { + if (null != corners) { Sector sector = Sector.boundingSector(corners); params.setValue(AVKey.SECTOR, sector); } @@ -309,12 +277,9 @@ public void addImage(String imagePath, List corners) throws IO DataRaster raster = this.openDataRaster(imagePath, params); final BufferedImage image = this.getBufferedImage(raster); - if (null != raster && image != null) - { + if (null != raster && image != null) { this.addImage(imagePath, image, corners); - } - else - { + } else { String message = Logging.getMessage("generic.ImageReadFailed", imagePath); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -325,53 +290,47 @@ public void addImage(String imagePath, List corners) throws IO * Add a {@link BufferedImage} to the collection at an explicitly specified location. The image is assumed to be in * geographic projection (latitude and longitude). * - * @param name a unique name to associate with the image so that it can be subsequently referred to without - * having to keep a reference to the image itself. Use this name in calls to {@link + * @param name a unique name to associate with the image so that it can be subsequently referred to without having + * to keep a reference to the image itself. Use this name in calls to {@link * #removeImage(String)}. - * @param image the image to add. + * @param image the image to add. * @param corners the geographic location of the image's corners, specified in order of lower-left, lower-right, - * upper-right, upper-left. + * upper-right, upper-left. * * @throws IllegalArgumentException if the image path is null, the corners list is null, contains null values or - * fewer than four locations. - * @throws WWRuntimeException if the image type is unsupported. + * fewer than four locations. + * @throws WWRuntimeException if the image type is unsupported. */ - public void addImage(String name, BufferedImage image, List corners) - { - if (name == null) - { + public void addImage(String name, BufferedImage image, List corners) { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (image == null) - { + if (image == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (corners == null) - { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.imageTable.contains(name)) + if (this.imageTable.contains(name)) { this.removeImage(name); + } final ArrayList surfaceImages = new ArrayList(); this.imageTable.put(name, surfaceImages); - this.imageTiler.tileImage(image, corners, new ImageTiler.ImageTilerListener() - { - public void newTile(BufferedImage tileImage, Sector tileSector) - { + this.imageTiler.tileImage(image, corners, new ImageTiler.ImageTilerListener() { + public void newTile(BufferedImage tileImage, Sector tileSector) { } - public void newTile(BufferedImage tileImage, List corners) - { + public void newTile(BufferedImage tileImage, List corners) { SurfaceImage si = new SurfaceImage(tileImage, corners); surfaceImages.add(si); si.setOpacity(SurfaceImageLayer.this.getOpacity()); @@ -380,43 +339,39 @@ public void newTile(BufferedImage tileImage, List corners) }); } - public void removeImage(String imagePath) - { + public void removeImage(String imagePath) { ArrayList images = this.imageTable.get(imagePath); - if (images == null) + if (images == null) { return; + } this.imageTable.remove(imagePath); - for (SurfaceImage si : images) - { - if (si != null) + for (SurfaceImage si : images) { + if (si != null) { this.removeRenderable(si); + } } } @Override - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { super.setOpacity(opacity); - for (Map.Entry> entry : this.imageTable.entrySet()) - { - for (SurfaceImage si : entry.getValue()) - { - if (si != null) + for (Map.Entry> entry : this.imageTable.entrySet()) { + for (SurfaceImage si : entry.getValue()) { + if (si != null) { si.setOpacity(opacity); + } } } } @SuppressWarnings({"UnusedDeclaration"}) - public int getNumImages() - { + public int getNumImages() { int count = 0; - for (ArrayList images : this.imageTable.values()) - { + for (ArrayList images : this.imageTable.values()) { count += images.size(); } @@ -427,62 +382,58 @@ public int getNumImages() * Create an image for the portion of this layer lying within a specified sector. The image is created at a * specified aspect ratio within a canvas of a specified size. * - * @param sector the sector of interest. - * @param canvasWidth the width of the canvas. + * @param sector the sector of interest. + * @param canvasWidth the width of the canvas. * @param canvasHeight the height of the canvas. - * @param aspectRatio the aspect ratio, width/height, of the window. If the aspect ratio is greater or equal to - * one, the full width of the canvas is used for the image; the height used is proportional to - * the inverse of the aspect ratio. If the aspect ratio is less than one, the full height of the - * canvas is used, and the width used is proportional to the aspect ratio. - * @param image if non-null, a {@link BufferedImage} in which to place the image. If null, a new buffered - * image of type {@link BufferedImage#TYPE_INT_RGB} is created. The image must be the width and - * height specified in the canvasWidth and canvasHeight arguments. + * @param aspectRatio the aspect ratio, width/height, of the window. If the aspect ratio is greater or equal to one, + * the full width of the canvas is used for the image; the height used is proportional to the inverse of the aspect + * ratio. If the aspect ratio is less than one, the full height of the canvas is used, and the width used is + * proportional to the aspect ratio. + * @param image if non-null, a {@link BufferedImage} in which to place the image. If null, a new buffered image of + * type {@link BufferedImage#TYPE_INT_RGB} is created. The image must be the width and height specified in the + * canvasWidth and canvasHeight arguments. * - * @return image the assembelled image, of size indicated by the canvasWidth and - * canvasHeight. If the specified aspect ratio is one, all pixels contain values. If the aspect - * ratio is greater than one, a full-width segment along the top of the canvas is blank. If the aspect ratio - * is less than one, a full-height segment along the right side of the canvase is blank. If the - * image argument was non-null, that buffered image is returned. + * @return image the assembelled image, of size indicated by the canvasWidth and + * canvasHeight. If the specified aspect ratio is one, all pixels contain values. If the aspect ratio + * is greater than one, a full-width segment along the top of the canvas is blank. If the aspect ratio is less than + * one, a full-height segment along the right side of the canvase is blank. If the image argument was + * non-null, that buffered image is returned. * * @see ImageUtil#mergeImage(Sector, Sector, double, BufferedImage, BufferedImage) */ @SuppressWarnings({"UnusedDeclaration"}) public BufferedImage composeImageForSector(Sector sector, int canvasWidth, int canvasHeight, double aspectRatio, - BufferedImage image) - { - if (sector == null) - { + BufferedImage image) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (!this.getRenderables().iterator().hasNext()) - { + if (!this.getRenderables().iterator().hasNext()) { Logging.logger().severe(Logging.getMessage("generic.NoImagesAvailable")); return null; } - if (image == null) + if (image == null) { image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB); + } - for (Renderable r : this.getRenderables()) - { + for (Renderable r : this.getRenderables()) { SurfaceImage si = (SurfaceImage) r; - if (si.getImageSource() == null) + if (si.getImageSource() == null) { continue; + } BufferedImage sourceImage = null; - try - { - if (si.getImageSource() instanceof String) + try { + if (si.getImageSource() instanceof String) { sourceImage = ImageIO.read(new File((String) si.getImageSource())); - else + } else { sourceImage = (BufferedImage) si.getImageSource(); - } - catch (IOException e) - { + } + } catch (IOException e) { Logging.logger().severe(Logging.getMessage("generic.ExceptionAttemptingToReadImageFile", sourceImage)); return null; } diff --git a/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java b/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java index b76a337c3a..75f723a666 100644 --- a/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java +++ b/src/gov/nasa/worldwind/layers/TerrainProfileLayer.java @@ -22,15 +22,16 @@ import java.util.List; /** - * Displays a terrain profile graph in a screen corner.

        Usage: do setEventSource(wwd) to have the graph - * activated and updated with position changes. See public properties for options: keepProportions, follow, unit, start - * and end latlon...

        + * Displays a terrain profile graph in a screen corner. + *

        + * Usage: do setEventSource(wwd) to have the graph activated and updated with position changes. See public properties + * for options: keepProportions, follow, unit, start and end latlon...

        * * @author Patrick Murris * @version $Id: TerrainProfileLayer.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class TerrainProfileLayer extends AbstractLayer implements PositionListener, SelectListener -{ +public class TerrainProfileLayer extends AbstractLayer implements PositionListener, SelectListener { + // Units constants public final static String UNIT_METRIC = "gov.nasa.worldwind.TerrainProfileLayer.Metric"; public final static String UNIT_IMPERIAL = "gov.nasa.worldwind.TerrainProfileLayer.Imperial"; @@ -95,51 +96,47 @@ public class TerrainProfileLayer extends AbstractLayer implements PositionListen // Draw it as ordered with an eye distance of 0 so that it shows up in front of most other things. protected OrderedIcon orderedImage = new OrderedIcon(); - protected class OrderedIcon implements OrderedRenderable - { - public double getDistanceFromEye() - { + protected class OrderedIcon implements OrderedRenderable { + + public double getDistanceFromEye() { return 0; } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { TerrainProfileLayer.this.drawProfile(dc); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { TerrainProfileLayer.this.drawProfile(dc); } } - /** Renders a terrain profile graphic in a screen corner. */ - public TerrainProfileLayer() - { + /** + * Renders a terrain profile graphic in a screen corner. + */ + public TerrainProfileLayer() { } // ** Public properties ************************************************************ - /** * Get whether the profile graph is minimized. * * @return true if the profile graph is minimized. */ @SuppressWarnings({"UnusedDeclaration"}) - public boolean getIsMinimized() - { + public boolean getIsMinimized() { return this.isMinimized; } /** - * Set whether the profile graph should be minimized.

        Note that the graph can be both minimized and maximized at - * the same time. The minimized state will take precedence and the graph will display as an icon. When - * 'un-minimized' it will display as maximized.

        + * Set whether the profile graph should be minimized. + *

        + * Note that the graph can be both minimized and maximized at the same time. The minimized state will take + * precedence and the graph will display as an icon. When 'un-minimized' it will display as maximized.

        * * @param state true if the profile should be minimized. */ - public void setIsMinimized(boolean state) - { + public void setIsMinimized(boolean state) { this.isMinimized = state; this.pickedSample = -1; // Clear picked position } @@ -150,8 +147,7 @@ public void setIsMinimized(boolean state) * @return true if the profile graph is maximized. */ @SuppressWarnings({"UnusedDeclaration"}) - public boolean getIsMaximized() - { + public boolean getIsMaximized() { return this.isMaximized; } @@ -160,8 +156,7 @@ public boolean getIsMaximized() * * @param state true if the profile should be maximized. */ - public void setIsMaximized(boolean state) - { + public void setIsMaximized(boolean state) { this.isMaximized = state; } @@ -170,8 +165,7 @@ public void setIsMaximized(boolean state) * * @return the scalebar graphic Dimension. */ - public Dimension getSize() - { + public Dimension getSize() { return this.size; } @@ -180,10 +174,8 @@ public Dimension getSize() * * @param size the graphic Dimension. */ - public void setSize(Dimension size) - { - if (size == null) - { + public void setSize(Dimension size) { + if (size == null) { String message = Logging.getMessage("nullValue.DimensionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -196,8 +188,7 @@ public void setSize(Dimension size) * * @return the graphic Color. */ - public Color getColor() - { + public Color getColor() { return this.color; } @@ -206,10 +197,8 @@ public Color getColor() * * @param color the graphic Color. */ - public void setColor(Color color) - { - if (color == null) - { + public void setColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -226,8 +215,7 @@ public void setColor(Color color) * @see #setColor */ @Override - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { super.setOpacity(opacity); } @@ -240,8 +228,7 @@ public void setOpacity(double opacity) * @see #getColor */ @Override - public double getOpacity() - { + public double getOpacity() { return super.getOpacity(); } @@ -251,8 +238,7 @@ public double getOpacity() * @return the graphic-to-viewport scale factor. */ @SuppressWarnings({"UnusedDeclaration"}) - public double getToViewportScale() - { + public double getToViewportScale() { return toViewportScale; } @@ -265,13 +251,11 @@ public double getToViewportScale() * @param toViewportScale the graphic to viewport scale factor. */ @SuppressWarnings({"UnusedDeclaration"}) - public void setToViewportScale(double toViewportScale) - { + public void setToViewportScale(double toViewportScale) { this.toViewportScale = toViewportScale; } - public String getPosition() - { + public String getPosition() { return this.position; } @@ -282,10 +266,8 @@ public String getPosition() * * @param position the desired graphic position. */ - public void setPosition(String position) - { - if (position == null) - { + public void setPosition(String position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -299,8 +281,7 @@ public void setPosition(String position) * @return the screen location of the graph center if set (can be null). */ @SuppressWarnings({"UnusedDeclaration"}) - public Point getLocationCenter() - { + public Point getLocationCenter() { return this.locationCenter; } @@ -309,8 +290,7 @@ public Point getLocationCenter() * * @param point the screen location of the graph center (can be null). */ - public void setLocationCenter(Point point) - { + public void setLocationCenter(Point point) { this.locationCenter = point; } @@ -321,8 +301,7 @@ public void setLocationCenter(Point point) * @return the location offset. Will be null if no offset has been specified. */ @SuppressWarnings({"UnusedDeclaration"}) - public Vec4 getLocationOffset() - { + public Vec4 getLocationOffset() { return locationOffset; } @@ -330,14 +309,13 @@ public Vec4 getLocationOffset() * Specifies a placement offset from the layer position on the screen. * * @param locationOffset the number of pixels to shift the layer image from its specified screen position. A - * positive X value shifts the image to the right. A positive Y value shifts the image up. If - * null, no offset is applied. The default offset is null. + * positive X value shifts the image to the right. A positive Y value shifts the image up. If null, no offset is + * applied. The default offset is null. * * @see #setLocationCenter * @see #setPosition */ - public void setLocationOffset(Vec4 locationOffset) - { + public void setLocationOffset(Vec4 locationOffset) { this.locationOffset = locationOffset; } @@ -347,8 +325,7 @@ public void setLocationOffset(Vec4 locationOffset) * @return the layer's resize behavior. */ @SuppressWarnings({"UnusedDeclaration"}) - public String getResizeBehavior() - { + public String getResizeBehavior() { return resizeBehavior; } @@ -364,13 +341,11 @@ public String getResizeBehavior() * @param resizeBehavior the desired resize behavior */ @SuppressWarnings({"UnusedDeclaration"}) - public void setResizeBehavior(String resizeBehavior) - { + public void setResizeBehavior(String resizeBehavior) { this.resizeBehavior = resizeBehavior; } - public int getBorderWidth() - { + public int getBorderWidth() { return borderWidth; } @@ -380,14 +355,12 @@ public int getBorderWidth() * @param borderWidth the number of pixels to offset the graphic from the borders indicated by {@link * #setPosition(String)}. */ - public void setBorderWidth(int borderWidth) - { + public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; } @SuppressWarnings({"UnusedDeclaration"}) - public String getUnit() - { + public String getUnit() { return this.unit; } @@ -397,8 +370,7 @@ public String getUnit() * * @param unit the desired unit. */ - public void setUnit(String unit) - { + public void setUnit(String unit) { this.unit = unit; } @@ -407,8 +379,7 @@ public void setUnit(String unit) * * @return the graphic legend Font. */ - public Font getFont() - { + public Font getFont() { return this.defaultFont; } @@ -417,10 +388,8 @@ public Font getFont() * * @param font the graphic legend Font. */ - public void setFont(Font font) - { - if (font == null) - { + public void setFont(Font font) { + if (font == null) { String msg = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -433,8 +402,7 @@ public void setFont(Font font) * * @return true if the graph maintains distance/elevation proportions. */ - public boolean getKeepProportions() - { + public boolean getKeepProportions() { return this.keepProportions; } @@ -443,8 +411,7 @@ public boolean getKeepProportions() * * @param state true if the graph should maintains distance/elevation proportions. */ - public void setKeepProportions(boolean state) - { + public void setKeepProportions(boolean state) { this.keepProportions = state; } @@ -453,8 +420,7 @@ public void setKeepProportions(boolean state) * * @return the graph center point placement behavior. */ - public String getFollow() - { + public String getFollow() { return this.follow; } @@ -466,8 +432,7 @@ public String getFollow() * * @param behavior the graph center point placement behavior. */ - public void setFollow(String behavior) - { + public void setFollow(String behavior) { this.follow = behavior; } @@ -476,8 +441,7 @@ public void setFollow(String behavior) * * @return true if the eye or object position is shown on the graph. */ - public boolean getShowEyePosition() - { + public boolean getShowEyePosition() { return this.showEyePosition; } @@ -487,8 +451,7 @@ public boolean getShowEyePosition() * * @param state if true the eye or object position should be shown on the graph. */ - public void setShowEyePosition(Boolean state) - { + public void setShowEyePosition(Boolean state) { this.showEyePosition = state; } @@ -497,8 +460,7 @@ public void setShowEyePosition(Boolean state) * * @param factor the new profile length factor. */ - public void setProfileLengthFactor(double factor) - { + public void setProfileLengthFactor(double factor) { this.profileLengthFactor = factor; } @@ -507,8 +469,7 @@ public void setProfileLengthFactor(double factor) * * @return the profile length factor. */ - public double getProfileLenghtFactor() - { + public double getProfileLenghtFactor() { return this.profileLengthFactor; } @@ -518,8 +479,7 @@ public double getProfileLenghtFactor() * @return the profile start position lat/lon. */ @SuppressWarnings({"UnusedDeclaration"}) - public LatLon getStartLatLon() - { + public LatLon getStartLatLon() { return this.startLatLon; } @@ -528,10 +488,8 @@ public LatLon getStartLatLon() * * @param latLon the profile start position lat/lon. */ - public void setStartLatLon(LatLon latLon) - { - if (latLon == null) - { + public void setStartLatLon(LatLon latLon) { + if (latLon == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -545,8 +503,7 @@ public void setStartLatLon(LatLon latLon) * @return the profile end position lat/lon. */ @SuppressWarnings({"UnusedDeclaration"}) - public LatLon getEndLatLon() - { + public LatLon getEndLatLon() { return this.endLatLon; } @@ -555,10 +512,8 @@ public LatLon getEndLatLon() * * @param latLon the profile end position lat/lon. */ - public void setEndLatLon(LatLon latLon) - { - if (latLon == null) - { + public void setEndLatLon(LatLon latLon) { + if (latLon == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -572,8 +527,7 @@ public void setEndLatLon(LatLon latLon) * @return the number of elevation samples in the profile. */ @SuppressWarnings({"UnusedDeclaration"}) - public int getSamples() - { + public int getSamples() { return this.samples; } @@ -583,8 +537,7 @@ public int getSamples() * @param number the number of elevation samples in the profile. */ @SuppressWarnings({"UnusedDeclaration"}) - public void setSamples(int number) - { + public void setSamples(int number) { this.samples = Math.abs(number); } @@ -593,8 +546,7 @@ public void setSamples(int number) * * @return whether the profile graph should include sea level. */ - public boolean getZeroBased() - { + public boolean getZeroBased() { return this.zeroBased; } @@ -603,8 +555,7 @@ public boolean getZeroBased() * * @param state true if the profile graph should include sea level. */ - public void setZeroBased(boolean state) - { + public void setZeroBased(boolean state) { this.zeroBased = state; } @@ -614,8 +565,7 @@ public void setZeroBased(boolean state) * @return the object position the graph follows. */ @SuppressWarnings({"UnusedDeclaration"}) - public Position getObjectPosition() - { + public Position getObjectPosition() { return this.objectPosition; } @@ -624,8 +574,7 @@ public Position getObjectPosition() * * @param pos the object position the graph follows. */ - public void setObjectPosition(Position pos) - { + public void setObjectPosition(Position pos) { this.objectPosition = pos; } @@ -636,8 +585,7 @@ public void setObjectPosition(Position pos) * @return the object heading the graph follows. */ @SuppressWarnings({"UnusedDeclaration"}) - public Angle getObjectHeading() - { + public Angle getObjectHeading() { return this.objectHeading; } @@ -647,8 +595,7 @@ public Angle getObjectHeading() * * @param heading the object heading the graph follows. */ - public void setObjectHeading(Angle heading) - { + public void setObjectHeading(Angle heading) { this.objectHeading = heading; } @@ -658,20 +605,17 @@ public void setObjectHeading(Angle heading) * @return the path positions that the profile follows. */ @SuppressWarnings({"UnusedDeclaration"}) - public List getPathPositions() - { + public List getPathPositions() { return this.pathPositions; } /** - * Set the path positions that the profile should follow if {@link #FOLLOW_PATH}. + * Set the path positions that the profile should follow if {@link #FOLLOW_PATH}. * * @param positions the path positions that the profile should follow. */ - public void setPathPositions(ArrayList positions) - { - if (positions == null) - { + public void setPathPositions(ArrayList positions) { + if (positions == null) { String msg = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -680,8 +624,7 @@ public void setPathPositions(ArrayList positions) } @SuppressWarnings({"UnusedDeclaration"}) - public int getPathType() - { + public int getPathType() { return this.pathType; } @@ -692,8 +635,7 @@ public int getPathType() * * @param type the type of path to follow. */ - public void setPathType(int type) - { + public void setPathType(int type) { this.pathType = type; } @@ -703,8 +645,7 @@ public void setPathType(int type) * @return the Polyline used to render the profile line on the ground. */ @SuppressWarnings({"UnusedDeclaration"}) - public Polyline getProfileLine() - { + public Polyline getProfileLine() { return this.selectionShape; } @@ -714,8 +655,7 @@ public Polyline getProfileLine() * @return the Polyline used to render the picked position on the terrain. */ @SuppressWarnings({"UnusedDeclaration"}) - public Polyline getPickedLine() - { + public Polyline getPickedLine() { return this.selectionShape; } @@ -725,8 +665,7 @@ public Polyline getPickedLine() * @return true is the profile line is displayed over the ground. */ @SuppressWarnings({"UnusedDeclaration"}) - public boolean isShowProfileLine() - { + public boolean isShowProfileLine() { return this.showProfileLine; } @@ -735,8 +674,7 @@ public boolean isShowProfileLine() * * @param state true if the profile line should be displayed over the terrain. */ - public void setShowProfileLine(boolean state) - { + public void setShowProfileLine(boolean state) { this.showProfileLine = state; } @@ -746,8 +684,7 @@ public void setShowProfileLine(boolean state) * @return true if the picked line is displayed over the ground. */ @SuppressWarnings({"UnusedDeclaration"}) - public boolean isShowPickedLine() - { + public boolean isShowPickedLine() { return this.showPickedLine; } @@ -757,62 +694,59 @@ public boolean isShowPickedLine() * @param state if the picked line should be displayed over the ground. */ @SuppressWarnings({"UnusedDeclaration"}) - public void setShowPickedLine(boolean state) - { + public void setShowPickedLine(boolean state) { this.showPickedLine = state; } // ** Rendering ************************************************************ - @Override - public void doRender(DrawContext dc) - { + public void doRender(DrawContext dc) { // Delegate graph rendering to OrderedRenderable list dc.addOrderedRenderable(this.orderedImage); // Render section line on the ground now - if (!isMinimized && this.positions != null && this.selectionShape != null) - { - if (this.showProfileLine) + if (!isMinimized && this.positions != null && this.selectionShape != null) { + if (this.showProfileLine) { this.selectionShape.render(dc); + } // If picking in progress, render pick indicator - if (this.showPickedLine && this.pickedSample != -1 && this.pickedShape != null) + if (this.showPickedLine && this.pickedSample != -1 && this.pickedShape != null) { this.pickedShape.render(dc); + } } } @Override - public void doPick(DrawContext dc, Point pickPoint) - { + public void doPick(DrawContext dc, Point pickPoint) { dc.addOrderedRenderable(this.orderedImage); } - protected void initialize(DrawContext dc) - { - if (this.initialized || this.positions != null) + protected void initialize(DrawContext dc) { + if (this.initialized || this.positions != null) { return; + } - if (this.wwd != null) - { + if (this.wwd != null) { this.computeProfile(dc); // this.expirySupport.restart(dc); } - if (this.positions != null) + if (this.positions != null) { this.initialized = true; + } } // Profile graph rendering - ortho - - public void drawProfile(DrawContext dc) - { + public void drawProfile(DrawContext dc) { this.computeProfile(dc); if ((this.positions == null || (this.minElevation == 0 && this.maxElevation == 0)) - && !this.initialized) + && !this.initialized) { this.initialize(dc); + } - if (this.positions == null || (this.minElevation == 0 && this.maxElevation == 0)) + if (this.positions == null || (this.minElevation == 0 && this.maxElevation == 0)) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -820,14 +754,13 @@ public void drawProfile(DrawContext dc) boolean modelviewPushed = false; boolean projectionPushed = false; - try - { + try { gl.glPushAttrib(GL2.GL_DEPTH_BUFFER_BIT - | GL2.GL_COLOR_BUFFER_BIT - | GL2.GL_ENABLE_BIT - | GL2.GL_TRANSFORM_BIT - | GL2.GL_VIEWPORT_BIT - | GL2.GL_CURRENT_BIT); + | GL2.GL_COLOR_BUFFER_BIT + | GL2.GL_ENABLE_BIT + | GL2.GL_TRANSFORM_BIT + | GL2.GL_VIEWPORT_BIT + | GL2.GL_CURRENT_BIT); attribsPushed = true; gl.glDisable(GL.GL_TEXTURE_2D); // no textures @@ -837,9 +770,9 @@ public void drawProfile(DrawContext dc) gl.glDisable(GL.GL_DEPTH_TEST); Rectangle viewport = dc.getView().getViewport(); - Dimension drawSize = isMinimized ? new Dimension(MINIMIZED_SIZE, MINIMIZED_SIZE) : - isMaximized ? new Dimension(viewport.width - this.borderWidth * 2, - viewport.height * 2 / 3 - this.borderWidth * 2) : this.size; + Dimension drawSize = isMinimized ? new Dimension(MINIMIZED_SIZE, MINIMIZED_SIZE) + : isMaximized ? new Dimension(viewport.width - this.borderWidth * 2, + viewport.height * 2 / 3 - this.borderWidth * 2) : this.size; double width = drawSize.width; double height = drawSize.height; @@ -864,54 +797,48 @@ public void drawProfile(DrawContext dc) gl.glTranslated(locationSW.x(), locationSW.y(), locationSW.z()); gl.glScaled(scale, scale, 1d); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Draw grid - Set color using current layer opacity this.drawGrid(dc, drawSize); // Draw profile graph this.drawGraph(dc, drawSize); - if (!isMinimized) - { + if (!isMinimized) { // Draw GUI buttons drawGUI(dc, drawSize); // Draw labels String label = String.format("min %.0fm max %.0fm", this.minElevation, this.maxElevation); - if (this.unit.equals(UNIT_IMPERIAL)) + if (this.unit.equals(UNIT_IMPERIAL)) { label = String.format("min %.0fft max %.0fft", this.minElevation * METER_TO_FEET, - this.maxElevation * METER_TO_FEET); + this.maxElevation * METER_TO_FEET); + } gl.glLoadIdentity(); gl.glDisable(GL.GL_CULL_FACE); drawLabel(dc, label, locationSW.add3(new Vec4(0, -12, 0)), -1); // left aligned - if (this.pickedSample != -1) - { + if (this.pickedSample != -1) { double pickedElevation = positions[this.pickedSample].getElevation(); label = String.format("%.0fm", pickedElevation); - if (this.unit.equals(UNIT_IMPERIAL)) + if (this.unit.equals(UNIT_IMPERIAL)) { label = String.format("%.0fft", pickedElevation * METER_TO_FEET); + } drawLabel(dc, label, locationSW.add3(new Vec4(width, -12, 0)), 1); // right aligned } } - } - else - { + } else { // Picking this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); // Draw unique color across the rectangle Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); - if (!isMinimized) - { + if (!isMinimized) { // Update graph pick point computePickPosition(dc, locationSW, new Dimension((int) (width * scale), (int) (height * scale))); // Draw GUI buttons drawGUI(dc, drawSize); - } - else - { + } else { // Add graph to the pickable list for 'un-minimize' click this.pickSupport.addPickableObject(colorCode, this); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); @@ -927,36 +854,29 @@ public void drawProfile(DrawContext dc) this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, dc.getPickPoint(), this); } - } - catch (Exception e) - { + } catch (Exception e) { //e.printStackTrace(); - } - finally - { - if (projectionPushed) - { + } finally { + if (projectionPushed) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); } - if (modelviewPushed) - { + if (modelviewPushed) { gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); } - if (attribsPushed) + if (attribsPushed) { gl.glPopAttrib(); + } } } // Draw grid graphic - - protected void drawGrid(DrawContext dc, Dimension dimension) - { + protected void drawGrid(DrawContext dc, Dimension dimension) { // Background color Color backColor = getBackgroundColor(this.color); drawFilledRectangle(dc, new Vec4(0, 0, 0), dimension, new Color(backColor.getRed(), - backColor.getGreen(), backColor.getBlue(), (int) (backColor.getAlpha() * .5))); // Increased transparency + backColor.getGreen(), backColor.getBlue(), (int) (backColor.getAlpha() * .5))); // Increased transparency // Grid - minimal float[] colorRGB = this.color.getRGBColorComponents(null); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -967,30 +887,30 @@ protected void drawGrid(DrawContext dc, Dimension dimension) } // Draw profile graphic - - protected void drawGraph(DrawContext dc, Dimension dimension) - { + protected void drawGraph(DrawContext dc, Dimension dimension) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Adjust min/max elevation for the graph double min = this.minElevation; double max = this.maxElevation; - if (this.showEyePosition && this.follow.equals(FOLLOW_EYE)) + if (this.showEyePosition && this.follow.equals(FOLLOW_EYE)) { max = Math.max(max, dc.getView().getEyePosition().getElevation()); + } if (this.showEyePosition && (this.follow.equals(FOLLOW_OBJECT) || this.follow.equals(FOLLOW_PATH)) - && this.objectPosition != null) + && this.objectPosition != null) { max = Math.max(max, this.objectPosition.getElevation()); - if (this.zeroBased) - { - if (min > 0) + } + if (this.zeroBased) { + if (min > 0) { min = 0; - if (max < 0) + } + if (max < 0) { max = 0; + } } int i; double stepX = dimension.getWidth() / this.length; double stepY = dimension.getHeight() / (max - min); - if (this.keepProportions) - { + if (this.keepProportions) { stepX = Math.min(stepX, stepY); //noinspection SuspiciousNameCombination stepY = stepX; @@ -999,10 +919,9 @@ protected void drawGraph(DrawContext dc, Dimension dimension) double x = 0, y; // Filled graph gl.glColor4ub((byte) this.color.getRed(), (byte) this.color.getGreen(), - (byte) this.color.getBlue(), (byte) 100); + (byte) this.color.getBlue(), (byte) 100); gl.glBegin(GL2.GL_TRIANGLE_STRIP); - for (i = 0; i < this.samples; i++) - { + for (i = 0; i < this.samples; i++) { x = i * lengthStep * stepX; y = (this.positions[i].getElevation() - min) * stepY; gl.glVertex3d(x, 0, 0); @@ -1013,8 +932,7 @@ protected void drawGraph(DrawContext dc, Dimension dimension) float[] colorRGB = this.color.getRGBColorComponents(null); gl.glColor4d(colorRGB[0], colorRGB[1], colorRGB[2], this.getOpacity()); gl.glBegin(GL2.GL_LINE_STRIP); - for (i = 0; i < this.samples; i++) - { + for (i = 0; i < this.samples; i++) { x = i * lengthStep * stepX; y = (this.positions[i].getElevation() - min) * stepY; gl.glVertex3d(x, y, 0); @@ -1022,125 +940,119 @@ protected void drawGraph(DrawContext dc, Dimension dimension) gl.glEnd(); // Middle vertical line gl.glColor4d(colorRGB[0], colorRGB[1], colorRGB[2], this.getOpacity() * .3); // increased transparency here - if (!this.follow.equals(FOLLOW_PATH)) + if (!this.follow.equals(FOLLOW_PATH)) { drawVerticalLine(dc, dimension, x / 2); + } // Eye or object position double eyeX = -1, eyeY = -1; - if ((this.follow.equals(FOLLOW_EYE) || - (this.follow.equals(FOLLOW_OBJECT) && this.objectPosition != null) || - (this.follow.equals(FOLLOW_PATH) && this.objectPosition != null)) - && this.showEyePosition) - { + if ((this.follow.equals(FOLLOW_EYE) + || (this.follow.equals(FOLLOW_OBJECT) && this.objectPosition != null) + || (this.follow.equals(FOLLOW_PATH) && this.objectPosition != null)) + && this.showEyePosition) { eyeX = x / 2; eyeY = (dc.getView().getEyePosition().getElevation() - min) * stepY; - if (this.follow.equals(FOLLOW_PATH)) + if (this.follow.equals(FOLLOW_PATH)) { eyeX = computeObjectSample(this.objectPosition) * lengthStep * stepX; - if (this.follow.equals(FOLLOW_OBJECT) || this.follow.equals(FOLLOW_PATH)) + } + if (this.follow.equals(FOLLOW_OBJECT) || this.follow.equals(FOLLOW_PATH)) { eyeY = (this.objectPosition.getElevation() - min) * stepY; - if (eyeX >= 0 && eyeY >= 0) + } + if (eyeX >= 0 && eyeY >= 0) { this.drawFilledRectangle(dc, new Vec4(eyeX - 2, eyeY - 2, 0), new Dimension(5, 5), this.color); + } // Vertical line at object position when follow path - if (this.follow.equals(FOLLOW_PATH) && eyeX >= 0) + if (this.follow.equals(FOLLOW_PATH) && eyeX >= 0) { drawVerticalLine(dc, dimension, eyeX); + } } // Selected/picked vertical and horizontal lines - if (this.pickedSample != -1) - { + if (this.pickedSample != -1) { double pickedX = this.pickedSample * lengthStep * stepX; double pickedY = (positions[this.pickedSample].getElevation() - min) * stepY; gl.glColor4d(colorRGB[0], colorRGB[1], colorRGB[2] * .5, this.getOpacity() * .8); // yellower color drawVerticalLine(dc, dimension, pickedX); drawHorizontalLine(dc, dimension, pickedY); // Eye or object - picked position line - if (eyeX >= 0 && eyeY >= 0) - { + if (eyeX >= 0 && eyeY >= 0) { // Line drawLine(dc, pickedX, pickedY, eyeX, eyeY); // Distance label double distance = dc.getView().getEyePoint().distanceTo3( - dc.getGlobe().computePointFromPosition(positions[this.pickedSample])); - if (this.follow.equals(FOLLOW_OBJECT) || this.follow.equals(FOLLOW_PATH)) - distance = dc.getGlobe().computePointFromPosition(this.objectPosition).distanceTo3( dc.getGlobe().computePointFromPosition(positions[this.pickedSample])); + if (this.follow.equals(FOLLOW_OBJECT) || this.follow.equals(FOLLOW_PATH)) { + distance = dc.getGlobe().computePointFromPosition(this.objectPosition).distanceTo3( + dc.getGlobe().computePointFromPosition(positions[this.pickedSample])); + } String label = String.format("Dist %.0fm", distance); - if (this.unit.equals(UNIT_IMPERIAL)) + if (this.unit.equals(UNIT_IMPERIAL)) { label = String.format("Dist %.0fft", distance * METER_TO_FEET); + } drawLabel(dc, label, new Vec4(pickedX + 5, pickedY - 12, 0), -1); // left aligned } } // Min elevation horizontal line - if (this.minElevation != min) - { + if (this.minElevation != min) { y = (this.minElevation - min) * stepY; gl.glColor4d(colorRGB[0], colorRGB[1], colorRGB[2], this.getOpacity() * .5); // medium transparency drawHorizontalLine(dc, dimension, y); } // Max elevation horizontal line - if (this.maxElevation != max) - { + if (this.maxElevation != max) { y = (this.maxElevation - min) * stepY; gl.glColor4d(colorRGB[0], colorRGB[1], colorRGB[2], this.getOpacity() * .5); // medium transparency drawHorizontalLine(dc, dimension, y); } // Sea level in between positive elevations only (not across land) - if (min < 0 && max >= 0) - { + if (min < 0 && max >= 0) { gl.glColor4d(colorRGB[0] * .7, colorRGB[1] * .7, colorRGB[2], this.getOpacity() * .5); // bluer color y = -this.minElevation * stepY; double previousX = -1; - for (i = 0; i < this.samples; i++) - { + for (i = 0; i < this.samples; i++) { x = i * lengthStep * stepX; - if (this.positions[i].getElevation() > 0 || i == this.samples - 1) - { - if (previousX >= 0) - { + if (this.positions[i].getElevation() > 0 || i == this.samples - 1) { + if (previousX >= 0) { gl.glBegin(GL2.GL_LINE_STRIP); gl.glVertex3d(previousX, y, 0); gl.glVertex3d(x, y, 0); gl.glEnd(); previousX = -1; } - } - else + } else { previousX = previousX < 0 ? x : previousX; + } } } } - protected void drawGUI(DrawContext dc, Dimension dimension) - { + protected void drawGUI(DrawContext dc, Dimension dimension) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int buttonSize = 16; int hs = buttonSize / 2; int buttonBorder = 4; Dimension buttonDimension = new Dimension(buttonSize, buttonSize); Color highlightColor = new Color(color.getRed(), color.getGreen(), - color.getBlue(), (int) (color.getAlpha() * .5)); + color.getBlue(), (int) (color.getAlpha() * .5)); Color backColor = getBackgroundColor(this.color); backColor = new Color(backColor.getRed(), backColor.getGreen(), - backColor.getBlue(), (int) (backColor.getAlpha() * .5)); // Increased transparency + backColor.getBlue(), (int) (backColor.getAlpha() * .5)); // Increased transparency Color drawColor; int y = dimension.height - buttonDimension.height - buttonBorder; int x = dimension.width; Object pickedObject = dc.getPickedObjects() != null ? dc.getPickedObjects().getTopObject() : null; // Maximize button - if (!isMaximized) - { + if (!isMaximized) { x -= buttonDimension.width + buttonBorder; - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { drawColor = dc.getUniquePickColor(); int colorCode = drawColor.getRGB(); this.pickSupport.addPickableObject(colorCode, this.buttonMaximize, null, false); - } - else + } else { drawColor = this.buttonMaximize == pickedObject ? highlightColor : backColor; + } drawFilledRectangle(dc, new Vec4(x, y, 0), buttonDimension, drawColor); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), - (byte) color.getBlue(), (byte) color.getAlpha()); + (byte) color.getBlue(), (byte) color.getAlpha()); // Draw '+' drawLine(dc, x + 3, y + hs, x + buttonDimension.width - 3, y + hs); // Horizontal line drawLine(dc, x + hs, y + 3, x + hs, y + buttonDimension.height - 3); // Vertical line @@ -1149,39 +1061,34 @@ protected void drawGUI(DrawContext dc, Dimension dimension) // Minimize button x -= buttonDimension.width + buttonBorder; - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { drawColor = dc.getUniquePickColor(); int colorCode = drawColor.getRGB(); this.pickSupport.addPickableObject(colorCode, this.buttonMinimize, null, false); - } - else + } else { drawColor = this.buttonMinimize == pickedObject ? highlightColor : backColor; + } drawFilledRectangle(dc, new Vec4(x, y, 0), buttonDimension, drawColor); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), - (byte) color.getBlue(), (byte) color.getAlpha()); + (byte) color.getBlue(), (byte) color.getAlpha()); // Draw '-' drawLine(dc, x + 3, y + hs, x + buttonDimension.width - 3, y + hs); // Horizontal line } } - protected void drawHorizontalLine(DrawContext dc, Dimension dimension, double y) - { + protected void drawHorizontalLine(DrawContext dc, Dimension dimension, double y) { drawLine(dc, 0, y, dimension.getWidth(), y); } - protected void drawVerticalLine(DrawContext dc, Dimension dimension, double x) - { + protected void drawVerticalLine(DrawContext dc, Dimension dimension, double x) { drawLine(dc, x, 0, x, dimension.getHeight()); } - protected void drawFilledRectangle(DrawContext dc, Vec4 origin, Dimension dimension, Color color) - { + protected void drawFilledRectangle(DrawContext dc, Vec4 origin, Dimension dimension, Color color) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), - (byte) color.getBlue(), (byte) color.getAlpha()); + (byte) color.getBlue(), (byte) color.getAlpha()); gl.glDisable(GL.GL_TEXTURE_2D); // no textures gl.glBegin(GL2.GL_POLYGON); gl.glVertex3d(origin.x, origin.y, 0); @@ -1192,8 +1099,7 @@ protected void drawFilledRectangle(DrawContext dc, Vec4 origin, Dimension dimens gl.glEnd(); } - protected void drawLine(DrawContext dc, double x1, double y1, double x2, double y2) - { + protected void drawLine(DrawContext dc, double x1, double y1, double x2, double y2) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_LINE_STRIP); gl.glVertex3d(x1, y1, 0); @@ -1203,18 +1109,18 @@ protected void drawLine(DrawContext dc, double x1, double y1, double x2, double // Draw a text label // Align = -1: left, 0: center and 1: right - - protected void drawLabel(DrawContext dc, String text, Vec4 screenPoint, int align) - { + protected void drawLabel(DrawContext dc, String text, Vec4 screenPoint, int align) { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - this.defaultFont); + this.defaultFont); Rectangle2D nameBound = textRenderer.getBounds(text); int x = (int) screenPoint.x(); // left - if (align == 0) + if (align == 0) { x = (int) (screenPoint.x() - nameBound.getWidth() / 2d); // centered - if (align > 0) + } + if (align > 0) { x = (int) (screenPoint.x() - nameBound.getWidth()); // right + } int y = (int) screenPoint.y(); textRenderer.begin3DRendering(); @@ -1228,82 +1134,60 @@ protected void drawLabel(DrawContext dc, String text, Vec4 screenPoint, int alig } // Compute background color for best contrast - - protected Color getBackgroundColor(Color color) - { + protected Color getBackgroundColor(Color color) { float[] compArray = new float[4]; Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), compArray); - if (compArray[2] > 0.5) + if (compArray[2] > 0.5) { return new Color(0, 0, 0, (int) (this.color.getAlpha() * 0.7f)); - else + } else { return new Color(255, 255, 255, (int) (this.color.getAlpha() * 0.7f)); + } } // ** Dimensions and positionning ************************************************************ - - protected double computeScale(java.awt.Rectangle viewport) - { - if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) - { + protected double computeScale(java.awt.Rectangle viewport) { + if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) { return Math.min(1d, (this.toViewportScale) * viewport.width / this.size.width); - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) { return (this.toViewportScale) * viewport.width / this.size.width; - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) { return 1d; - } - else - { + } else { return 1d; } } - protected Vec4 computeLocation(java.awt.Rectangle viewport, double scale) - { - double scaledWidth = scale * (isMinimized ? MINIMIZED_SIZE : - isMaximized ? viewport.width - this.borderWidth * 2 : this.size.width); - double scaledHeight = scale * (isMinimized ? MINIMIZED_SIZE : - isMaximized ? viewport.height * 2 / 3 - this.borderWidth * 2 : this.size.height); + protected Vec4 computeLocation(java.awt.Rectangle viewport, double scale) { + double scaledWidth = scale * (isMinimized ? MINIMIZED_SIZE + : isMaximized ? viewport.width - this.borderWidth * 2 : this.size.width); + double scaledHeight = scale * (isMinimized ? MINIMIZED_SIZE + : isMaximized ? viewport.height * 2 / 3 - this.borderWidth * 2 : this.size.height); double x; double y; - if (this.locationCenter != null) - { + if (this.locationCenter != null) { x = this.locationCenter.x - scaledWidth / 2; y = this.locationCenter.y - scaledHeight / 2; - } - else if (this.position.equals(AVKey.NORTHEAST)) - { + } else if (this.position.equals(AVKey.NORTHEAST)) { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHEAST)) - { + } else if (this.position.equals(AVKey.SOUTHEAST)) { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = 0d + this.borderWidth; - } - else if (this.position.equals(AVKey.NORTHWEST)) - { + } else if (this.position.equals(AVKey.NORTHWEST)) { x = 0d + this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHWEST)) - { + } else if (this.position.equals(AVKey.SOUTHWEST)) { x = 0d + this.borderWidth; y = 0d + this.borderWidth; - } - else // use North East + } else // use North East { x = viewport.getWidth() - scaledWidth / 2 - this.borderWidth; y = viewport.getHeight() - scaledHeight / 2 - this.borderWidth; } - if (this.locationOffset != null) - { + if (this.locationOffset != null) { x += this.locationOffset.x; y += this.locationOffset.y; } @@ -1314,47 +1198,42 @@ else if (this.position.equals(AVKey.SOUTHWEST)) /** * Computes the Position of the pickPoint over the graph and updates pickedSample indice * - * @param dc the current DrawContext + * @param dc the current DrawContext * @param locationSW the screen location of the bottom left corner of the graph - * @param mapSize the graph screen dimension in pixels + * @param mapSize the graph screen dimension in pixels * * @return the picked Position */ - protected Position computePickPosition(DrawContext dc, Vec4 locationSW, Dimension mapSize) - { + protected Position computePickPosition(DrawContext dc, Vec4 locationSW, Dimension mapSize) { Position pickPosition = null; this.pickedSample = -1; Point pickPoint = dc.getPickPoint(); - if (pickPoint != null && this.positions != null && !this.follow.equals(FOLLOW_CURSOR)) - { + if (pickPoint != null && this.positions != null && !this.follow.equals(FOLLOW_CURSOR)) { Rectangle viewport = dc.getView().getViewport(); // Check if pickpoint is inside the graph if (pickPoint.getX() >= locationSW.getX() - && pickPoint.getX() < locationSW.getX() + mapSize.width - && viewport.height - pickPoint.getY() >= locationSW.getY() - && viewport.height - pickPoint.getY() < locationSW.getY() + mapSize.height) - { + && pickPoint.getX() < locationSW.getX() + mapSize.width + && viewport.height - pickPoint.getY() >= locationSW.getY() + && viewport.height - pickPoint.getY() < locationSW.getY() + mapSize.height) { // Find sample - Note: only works when graph expends over the full width int sample = (int) (((double) (pickPoint.getX() - locationSW.getX()) / mapSize.width) * this.samples); - if (sample >= 0 && sample < this.samples) - { + if (sample >= 0 && sample < this.samples) { pickPosition = this.positions[sample]; this.pickedSample = sample; // Update polyline indicator ArrayList posList = new ArrayList(); posList.add(positions[sample]); posList.add(new Position(positions[sample].getLatitude(), positions[sample].getLongitude(), - positions[sample].getElevation() + this.length / 10)); - if (this.pickedShape == null) - { + positions[sample].getElevation() + this.length / 10)); + if (this.pickedShape == null) { this.pickedShape = new Polyline(posList); this.pickedShape.setPathType(Polyline.LINEAR); this.pickedShape.setLineWidth(2); this.pickedShape.setColor(new Color(this.color.getRed(), - this.color.getGreen(), (int) (this.color.getBlue() * .8), (int) (255 * .8))); - } - else + this.color.getGreen(), (int) (this.color.getBlue() * .8), (int) (255 * .8))); + } else { this.pickedShape.setPositions(posList); + } } } } @@ -1368,18 +1247,17 @@ protected Position computePickPosition(DrawContext dc, Vec4 locationSW, Dimensio * * @return the sample number or -1 if not found. */ - protected int computeObjectSample(LatLon pos) - { - if (this.pathPositions.size() < 2) + protected int computeObjectSample(LatLon pos) { + if (this.pathPositions.size() < 2) { return -1; + } double radius = this.wwd.getModel().getGlobe().getRadius(); double maxDistanceFromPath = 1000; // meters double distanceFromStart = 0; int segmentIndex = 0; LatLon pos1 = this.pathPositions.get(segmentIndex); - for (int i = 1; i < this.pathPositions.size(); i++) - { + for (int i = 1; i < this.pathPositions.size(); i++) { LatLon pos2 = this.pathPositions.get(i); double segmentLength = LatLon.greatCircleDistance(pos1, pos2).radians * radius; // Check wether the position is close to the segment line @@ -1387,22 +1265,20 @@ protected int computeObjectSample(LatLon pos) Vec4 v1 = new Vec4(pos1.getLatitude().radians, pos1.getLongitude().radians, 0, 0); Vec4 v2 = new Vec4(pos2.getLatitude().radians, pos2.getLongitude().radians, 0, 0); Line line = new Line(v1, v2.subtract3(v1)); - if (line.distanceTo(v0) * radius <= maxDistanceFromPath) - { + if (line.distanceTo(v0) * radius <= maxDistanceFromPath) { // Check whether the position is inside the segment double length1 = LatLon.greatCircleDistance(pos1, pos).radians * radius; double length2 = LatLon.greatCircleDistance(pos2, pos).radians * radius; - if (length1 <= segmentLength && length2 <= segmentLength) - { + if (length1 <= segmentLength && length2 <= segmentLength) { // Compute portion of segment length distanceFromStart += length1 / (length1 + length2) * segmentLength; break; - } - else + } else { distanceFromStart += segmentLength; - } - else + } + } else { distanceFromStart += segmentLength; + } // Next segment pos1 = pos2; } @@ -1411,64 +1287,48 @@ protected int computeObjectSample(LatLon pos) } // ** Position listener impl. ************************************************************ - - public void moved(PositionEvent event) - { + public void moved(PositionEvent event) { this.positions = null; } // ** Select listener impl. ************************************************************ - - public void selected(SelectEvent event) - { - if (event.hasObjects() && event.getEventAction().equals(SelectEvent.LEFT_CLICK)) - { - if (event.getMouseEvent() != null && event.getMouseEvent().isConsumed()) + public void selected(SelectEvent event) { + if (event.hasObjects() && event.getEventAction().equals(SelectEvent.LEFT_CLICK)) { + if (event.getMouseEvent() != null && event.getMouseEvent().isConsumed()) { return; + } Object o = event.getTopObject(); - if (o == this.buttonMinimize) - { - if (this.isMaximized) + if (o == this.buttonMinimize) { + if (this.isMaximized) { this.setIsMaximized(false); - else + } else { this.setIsMinimized(true); - } - - else if (o == this.buttonMaximize) - { + } + } else if (o == this.buttonMaximize) { this.setIsMaximized(true); - } - - else if (o == this && this.isMinimized) - { + } else if (o == this && this.isMinimized) { this.setIsMinimized(false); } } } // ** Property change listener *********************************************************** - - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { this.positions = null; } // Sets the wwd local reference and add us to the position listeners // the view and elevation model property change listener - - public void setEventSource(WorldWindow wwd) - { - if (this.wwd != null) - { + public void setEventSource(WorldWindow wwd) { + if (this.wwd != null) { this.wwd.removePositionListener(this); this.wwd.getView().removePropertyChangeListener(this); // this.wwd.getModel().getGlobe().getElevationModel().removePropertyChangeListener(this); this.wwd.removeSelectListener(this); } this.wwd = wwd; - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.addPositionListener(this); this.wwd.getView().addPropertyChangeListener(this); // this.wwd.getModel().getGlobe().getElevationModel().addPropertyChangeListener(this); @@ -1477,139 +1337,123 @@ public void setEventSource(WorldWindow wwd) } // ** Profile data collection ************************************************************ - /** - * Compute the terrain profile.

        If {@link #FOLLOW_VIEW}, {@link #FOLLOW_EYE}, {@link #FOLLOW_CURSOR} or {@link + * Compute the terrain profile. + *

        + * If {@link #FOLLOW_VIEW}, {@link #FOLLOW_EYE}, {@link #FOLLOW_CURSOR} or {@link * #FOLLOW_OBJECT}, collects terrain profile data along a great circle line centered at the current position (view, - * eye, cursor or object) and perpendicular to the view heading - or object heading if {@link #FOLLOW_OBJECT}.

        - * If {@link #FOLLOW_NONE} the profile is computed in between start and end latlon.

        If {@link #FOLLOW_PATH} the - * profile is computed along the path provided with {@link #setPathPositions(ArrayList)}

        + * eye, cursor or object) and perpendicular to the view heading - or object heading if {@link #FOLLOW_OBJECT}. + *

        + * If {@link #FOLLOW_NONE} the profile is computed in between start and end latlon. + *

        + * If {@link #FOLLOW_PATH} the profile is computed along the path provided with + * {@link #setPathPositions(ArrayList)}

        * * @param dc the current DrawContext */ - protected void computeProfile(DrawContext dc) - { - if (this.wwd == null) + protected void computeProfile(DrawContext dc) { + if (this.wwd == null) { return; + } - try - { + try { // Find center position View view = this.wwd.getView(); Position groundPos = null; - if (this.follow.equals(FOLLOW_VIEW)) + if (this.follow.equals(FOLLOW_VIEW)) { groundPos = this.computeViewCenterPosition(dc); - else if (this.follow.equals(FOLLOW_CURSOR)) + } else if (this.follow.equals(FOLLOW_CURSOR)) { groundPos = this.computeCursorPosition(dc); - else if (this.follow.equals(FOLLOW_EYE)) + } else if (this.follow.equals(FOLLOW_EYE)) { groundPos = view.getEyePosition(); - else if (this.follow.equals(FOLLOW_OBJECT)) + } else if (this.follow.equals(FOLLOW_OBJECT)) { groundPos = this.objectPosition; + } // Compute profile if we can - if ((this.follow.equals(FOLLOW_VIEW) && groundPos != null) || - (this.follow.equals(FOLLOW_EYE) && groundPos != null) || - (this.follow.equals(FOLLOW_CURSOR) && groundPos != null) || - (this.follow.equals(FOLLOW_NONE) && this.startLatLon != null && this.endLatLon != null) || - (this.follow.equals(FOLLOW_OBJECT) && this.objectPosition != null && this.objectHeading != null) || - (this.follow.equals(FOLLOW_PATH) && this.pathPositions != null && this.pathPositions.size() >= 2)) - { + if ((this.follow.equals(FOLLOW_VIEW) && groundPos != null) + || (this.follow.equals(FOLLOW_EYE) && groundPos != null) + || (this.follow.equals(FOLLOW_CURSOR) && groundPos != null) + || (this.follow.equals(FOLLOW_NONE) && this.startLatLon != null && this.endLatLon != null) + || (this.follow.equals(FOLLOW_OBJECT) && this.objectPosition != null && this.objectHeading != null) + || (this.follow.equals(FOLLOW_PATH) && this.pathPositions != null && this.pathPositions.size() >= 2)) { this.positions = new Position[samples]; this.minElevation = Double.MAX_VALUE; this.maxElevation = -Double.MAX_VALUE; // Compute profile positions - if (this.follow.equals(FOLLOW_PATH)) - { + if (this.follow.equals(FOLLOW_PATH)) { computePathPositions(); - } - else - { + } else { computeMirroredPositions(groundPos); } // Update shape on ground - if (this.selectionShape == null) - { + if (this.selectionShape == null) { this.selectionShape = new Polyline(Arrays.asList(this.positions)); this.selectionShape.setLineWidth(2); this.selectionShape.setFollowTerrain(true); this.selectionShape.setColor(new Color(this.color.getRed(), - this.color.getGreen(), (int) (this.color.getBlue() * .5), (int) (255 * .8))); - } - else + this.color.getGreen(), (int) (this.color.getBlue() * .5), (int) (255 * .8))); + } else { this.selectionShape.setPositions(Arrays.asList(this.positions)); - } - else - { + } + } else { // Off globe or something missing this.positions = null; } - } - catch (Exception e) - { + } catch (Exception e) { this.positions = null; } } - protected Position computeViewCenterPosition(DrawContext dc) - { + protected Position computeViewCenterPosition(DrawContext dc) { View view = dc.getView(); Line ray = view.computeRayFromScreenPoint(view.getViewport().getWidth() / 2, - view.getViewport().getHeight() / 2); + view.getViewport().getHeight() / 2); Intersection[] inters = dc.getSurfaceGeometry().intersect(ray); - if (inters.length > 0) + if (inters.length > 0) { return dc.getGlobe().computePositionFromPoint(inters[0].getIntersectionPoint()); + } return null; } - protected void computeMirroredPositions(LatLon centerLatLon) - { + protected void computeMirroredPositions(LatLon centerLatLon) { View view = this.wwd.getView(); // Compute profile length - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { this.length = Math.min(((OrbitView) view).getZoom() * .8 * this.profileLengthFactor, - this.wwd.getModel().getGlobe().getRadius() * Math.PI); - } - else - { + this.wwd.getModel().getGlobe().getRadius() * Math.PI); + } else { this.length = Math.min(Math.abs(view.getEyePosition().getElevation()) * .8 * this.profileLengthFactor, - this.wwd.getModel().getGlobe().getRadius() * Math.PI); + this.wwd.getModel().getGlobe().getRadius() * Math.PI); } - if (this.follow.equals(FOLLOW_NONE)) - { + if (this.follow.equals(FOLLOW_NONE)) { this.length = LatLon.greatCircleDistance(this.startLatLon, this.endLatLon).radians - * this.wwd.getModel().getGlobe().getRadius(); - } - else if (this.follow.equals(FOLLOW_OBJECT)) - { + * this.wwd.getModel().getGlobe().getRadius(); + } else if (this.follow.equals(FOLLOW_OBJECT)) { this.length = Math.min(Math.abs(this.objectPosition.getElevation()) * .8 * this.profileLengthFactor, - this.wwd.getModel().getGlobe().getRadius() * Math.PI); + this.wwd.getModel().getGlobe().getRadius() * Math.PI); } double lengthRadian = this.length / this.wwd.getModel().getGlobe().getRadius(); // Iterate on both sides of the center point int i; double step = lengthRadian / (samples - 1); - for (i = 0; i < this.samples; i++) - { + for (i = 0; i < this.samples; i++) { LatLon latLon = null; - if (!this.follow.equals(FOLLOW_NONE)) - { + if (!this.follow.equals(FOLLOW_NONE)) { // Compute segments perpendicular to view or object heading double azimuth = view.getHeading().subtract(Angle.POS90).radians; - if (this.follow.equals(FOLLOW_OBJECT)) + if (this.follow.equals(FOLLOW_OBJECT)) { azimuth = this.objectHeading.subtract(Angle.POS90).radians; - if (i > (float) (this.samples - 1) / 2f) - { + } + if (i > (float) (this.samples - 1) / 2f) { //azimuth = view.getHeading().subtract(Angle.NEG90).radians; azimuth += Math.PI; } double distance = Math.abs(((double) i - ((double) (this.samples - 1) / 2d)) * step); latLon = LatLon.greatCircleEndPosition(centerLatLon, azimuth, distance); - } - else if (this.follow.equals(FOLLOW_NONE) && this.startLatLon != null - && this.endLatLon != null) - { + } else if (this.follow.equals(FOLLOW_NONE) && this.startLatLon != null + && this.endLatLon != null) { // Compute segments between start and end positions latlon latLon = LatLon.interpolate((double) i / (this.samples - 1), this.startLatLon, this.endLatLon); } @@ -1617,8 +1461,7 @@ else if (this.follow.equals(FOLLOW_NONE) && this.startLatLon != null } } - protected void computePathPositions() - { + protected void computePathPositions() { this.length = computePathLength(); double lengthRadians = this.length / this.wwd.getModel().getGlobe().getRadius(); double step = lengthRadians / (this.samples - 1); @@ -1628,33 +1471,26 @@ protected void computePathPositions() this.setPosition(0, latLon); // Compute in between samples double distance, azimuth; - for (int i = 1; i < this.samples - 1; i++) - { + for (int i = 1; i < this.samples - 1; i++) { double stepToGo = step; - while (stepToGo > 0) - { - if (this.pathType == Polyline.RHUMB_LINE) + while (stepToGo > 0) { + if (this.pathType == Polyline.RHUMB_LINE) { distance = LatLon.rhumbDistance(latLon, this.pathPositions.get(segmentIndex + 1)).radians; - else + } else { distance = LatLon.greatCircleDistance(latLon, this.pathPositions.get(segmentIndex + 1)).radians; - if (distance >= stepToGo) - { - if (this.pathType == Polyline.RHUMB_LINE) - { + } + if (distance >= stepToGo) { + if (this.pathType == Polyline.RHUMB_LINE) { azimuth = LatLon.rhumbAzimuth(latLon, this.pathPositions.get(segmentIndex + 1)).radians; latLon = LatLon.rhumbEndPosition(latLon, azimuth, stepToGo); - } - else - { + } else { azimuth = LatLon.greatCircleAzimuth(latLon, this.pathPositions.get(segmentIndex + 1)).radians; latLon = LatLon.greatCircleEndPosition(latLon, azimuth, stepToGo); } this.setPosition(i, latLon); stepToGo = 0; - } - else - { + } else { segmentIndex++; latLon = this.pathPositions.get(segmentIndex); stepToGo -= distance; @@ -1665,42 +1501,38 @@ protected void computePathPositions() this.setPosition(this.samples - 1, this.pathPositions.get(this.pathPositions.size() - 1)); } - protected double computePathLength() - { + protected double computePathLength() { double pathLengthRadians = 0; LatLon pos1 = null; - for (LatLon pos2 : this.pathPositions) - { - if (pos1 != null) + for (LatLon pos2 : this.pathPositions) { + if (pos1 != null) { pathLengthRadians += LatLon.greatCircleDistance(pos1, pos2).radians; + } pos1 = pos2; } return pathLengthRadians * this.wwd.getModel().getGlobe().getRadius(); } - protected void setPosition(int index, LatLon latLon) - { - Double elevation = - this.wwd.getModel().getGlobe().getElevation(latLon.getLatitude(), latLon.getLongitude()); + protected void setPosition(int index, LatLon latLon) { + Double elevation + = this.wwd.getModel().getGlobe().getElevation(latLon.getLatitude(), latLon.getLongitude()); this.minElevation = elevation < this.minElevation ? elevation : this.minElevation; this.maxElevation = elevation > this.maxElevation ? elevation : this.maxElevation; // Add position to the list positions[index] = new Position(latLon, elevation); } - protected Position computeCursorPosition(DrawContext dc) - { + protected Position computeCursorPosition(DrawContext dc) { Position pos = this.wwd.getCurrentPosition(); - if (pos == null && dc.getPickPoint() != null) - { + if (pos == null && dc.getPickPoint() != null) { // Current pos is null, try intersection with terrain geometry Line ray = dc.getView().computeRayFromScreenPoint(dc.getPickPoint().x, dc.getPickPoint().y); Intersection[] inter = dc.getSurfaceGeometry().intersect(ray); - if (inter != null && inter.length > 0) + if (inter != null && inter.length > 0) { pos = dc.getGlobe().computePositionFromPoint(inter[0].getIntersectionPoint()); + } } - if (pos == null && dc.getPickPoint() != null) - { + if (pos == null && dc.getPickPoint() != null) { // Position is still null, fallback on intersection with ellipsoid. pos = dc.getView().computePositionFromScreenPoint(dc.getPickPoint().x, dc.getPickPoint().y); } @@ -1708,8 +1540,7 @@ protected Position computeCursorPosition(DrawContext dc) } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.Earth.TerrainProfileLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/TextureTile.java b/src/gov/nasa/worldwind/layers/TextureTile.java index 9f71544426..a234bf49db 100644 --- a/src/gov/nasa/worldwind/layers/TextureTile.java +++ b/src/gov/nasa/worldwind/layers/TextureTile.java @@ -26,8 +26,8 @@ * @author tag * @version $Id: TextureTile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TextureTile extends Tile implements SurfaceTile -{ +public class TextureTile extends Tile implements SurfaceTile { + private volatile TextureData textureData; // if non-null, then must be converted to a Texture private TextureTile fallbackTile = null; // holds texture to use if own texture not available protected boolean hasMipmapData = false; @@ -39,10 +39,8 @@ public class TextureTile extends Tile implements SurfaceTile * * @return the memory cache associated with the tile. */ - public static synchronized MemoryCache getMemoryCache() - { - if (!WorldWind.getMemoryCacheSet().containsCache(TextureTile.class.getName())) - { + public static synchronized MemoryCache getMemoryCache() { + if (!WorldWind.getMemoryCacheSet().containsCache(TextureTile.class.getName())) { long size = Configuration.getLongValue(AVKey.TEXTURE_IMAGE_CACHE_SIZE, 3000000L); MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size); cache.setName("Texture Tiles"); @@ -52,50 +50,43 @@ public static synchronized MemoryCache getMemoryCache() return WorldWind.getMemoryCacheSet().getCache(TextureTile.class.getName()); } - public TextureTile(Sector sector) - { + public TextureTile(Sector sector) { super(sector); } - public TextureTile(Sector sector, Level level, int row, int col) - { + public TextureTile(Sector sector, Level level, int row, int col) { super(sector, level, row, col); } - public TextureTile(Sector sector, Level level, int row, int column, String cacheName) - { + public TextureTile(Sector sector, Level level, int row, int column, String cacheName) { super(sector, level, row, column, cacheName); } @Override - public long getSizeInBytes() - { + public long getSizeInBytes() { long size = super.getSizeInBytes(); - if (this.textureData != null) + if (this.textureData != null) { size += this.textureData.getEstimatedMemorySize(); + } return size; } - public List getCorners() - { + public List getCorners() { ArrayList list = new ArrayList(4); - for (LatLon ll : this.getSector()) - { + for (LatLon ll : this.getSector()) { list.add(ll); } return list; } - public TextureTile getFallbackTile() - { + public TextureTile getFallbackTile() { return this.fallbackTile; } - public void setFallbackTile(TextureTile fallbackTile) - { + public void setFallbackTile(TextureTile fallbackTile) { this.fallbackTile = fallbackTile; } @@ -109,8 +100,7 @@ public void setFallbackTile(TextureTile fallbackTile) * * @return the texture data, which may be null. */ - public TextureData getTextureData() - { + public TextureData getTextureData() { return this.textureData; } @@ -127,17 +117,15 @@ public TextureData getTextureData() * * @param textureData the texture data, which may be null. */ - public void setTextureData(TextureData textureData) - { + public void setTextureData(TextureData textureData) { this.textureData = textureData; - if (textureData.getMipmapData() != null) + if (textureData.getMipmapData() != null) { this.hasMipmapData = true; + } } - public Texture getTexture(GpuResourceCache tc) - { - if (tc == null) - { + public Texture getTexture(GpuResourceCache tc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TextureCacheIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -146,10 +134,8 @@ public Texture getTexture(GpuResourceCache tc) return tc.getTexture(this.getTileKey()); } - public boolean isTextureInMemory(GpuResourceCache tc) - { - if (tc == null) - { + public boolean isTextureInMemory(GpuResourceCache tc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TextureCacheIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -158,25 +144,20 @@ public boolean isTextureInMemory(GpuResourceCache tc) return this.getTexture(tc) != null || this.getTextureData() != null; } - public long getUpdateTime() - { + public long getUpdateTime() { return this.updateTime.get(); } - public boolean isTextureExpired() - { + public boolean isTextureExpired() { return this.isTextureExpired(this.getLevel().getExpiryTime()); } - public boolean isTextureExpired(long expiryTime) - { + public boolean isTextureExpired(long expiryTime) { return this.updateTime.get() > 0 && this.updateTime.get() < expiryTime; } - public void setTexture(GpuResourceCache tc, Texture texture) - { - if (tc == null) - { + public void setTexture(GpuResourceCache tc, Texture texture) { + if (tc == null) { String message = Logging.getMessage("nullValue.TextureCacheIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -191,10 +172,8 @@ public void setTexture(GpuResourceCache tc, Texture texture) this.updateMemoryCache(); } - public Vec4 getCentroidPoint(Globe globe) - { - if (globe == null) - { + public Vec4 getCentroidPoint(Globe globe) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -203,10 +182,8 @@ public Vec4 getCentroidPoint(Globe globe) return globe.computePointFromLocation(this.getSector().getCentroid()); } - public Extent getExtent(DrawContext dc) - { - if (dc == null) - { + public Extent getExtent(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -226,10 +203,8 @@ public Extent getExtent(DrawContext dc) * * @throws IllegalArgumentException if the level is null. */ - public TextureTile[] createSubTiles(Level nextLevel) - { - if (nextLevel == null) - { + public TextureTile[] createSubTiles(Level nextLevel) { + if (nextLevel == null) { String msg = Logging.getMessage("nullValue.LevelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -250,50 +225,53 @@ public TextureTile[] createSubTiles(Level nextLevel) TileKey key = this.createSubTileKey(nextLevel, 2 * row, 2 * col); TextureTile subTile = this.getTileFromMemoryCache(key); - if (subTile != null) + if (subTile != null) { subTiles[0] = subTile; - else + } else { subTiles[0] = this.createSubTile(new Sector(p0, p1, t0, t1), nextLevel, 2 * row, 2 * col); + } key = this.createSubTileKey(nextLevel, 2 * row, 2 * col + 1); subTile = this.getTileFromMemoryCache(key); - if (subTile != null) + if (subTile != null) { subTiles[1] = subTile; - else + } else { subTiles[1] = this.createSubTile(new Sector(p0, p1, t1, t2), nextLevel, 2 * row, 2 * col + 1); + } key = this.createSubTileKey(nextLevel, 2 * row + 1, 2 * col); subTile = this.getTileFromMemoryCache(key); - if (subTile != null) + if (subTile != null) { subTiles[2] = subTile; - else + } else { subTiles[2] = this.createSubTile(new Sector(p1, p2, t0, t1), nextLevel, 2 * row + 1, 2 * col); + } key = this.createSubTileKey(nextLevel, 2 * row + 1, 2 * col + 1); subTile = this.getTileFromMemoryCache(key); - if (subTile != null) + if (subTile != null) { subTiles[3] = subTile; - else + } else { subTiles[3] = this.createSubTile(new Sector(p1, p2, t1, t2), nextLevel, 2 * row + 1, 2 * col + 1); + } return subTiles; } /** * Creates a sub tile of this texture tile with the specified {@link gov.nasa.worldwind.geom.Sector}, {@link - * gov.nasa.worldwind.util.Level}, row, and column. This is called by {@link #createSubTiles(gov.nasa.worldwind.util.Level)}, - * to construct a sub tile for each quadrant of this tile. Subclasses must override this method to return an - * instance of the derived version. + * gov.nasa.worldwind.util.Level}, row, and column. This is called by + * {@link #createSubTiles(gov.nasa.worldwind.util.Level)}, to construct a sub tile for each quadrant of this tile. + * Subclasses must override this method to return an instance of the derived version. * * @param sector the sub tile's sector. - * @param level the sub tile's level. - * @param row the sub tile's row. - * @param col the sub tile's column. + * @param level the sub tile's level. + * @param row the sub tile's row. + * @param col the sub tile's column. * * @return a sub tile of this texture tile. */ - protected TextureTile createSubTile(Sector sector, Level level, int row, int col) - { + protected TextureTile createSubTile(Sector sector, Level level, int row, int col) { return new TextureTile(sector, level, row, col); } @@ -303,31 +281,27 @@ protected TextureTile createSubTile(Sector sector, Level level, int row, int col * for each quadrant of this tile. * * @param level the sub tile's level. - * @param row the sub tile's row. - * @param col the sub tile's column. + * @param row the sub tile's row. + * @param col the sub tile's column. * * @return a sub tile of this texture tile. */ - protected TileKey createSubTileKey(Level level, int row, int col) - { + protected TileKey createSubTileKey(Level level, int row, int col) { return new TileKey(level.getLevelNumber(), row, col, level.getCacheName()); } - protected TextureTile getTileFromMemoryCache(TileKey tileKey) - { + protected TextureTile getTileFromMemoryCache(TileKey tileKey) { return (TextureTile) getMemoryCache().getObject(tileKey); } - protected void updateMemoryCache() - { - if (this.getTileFromMemoryCache(this.getTileKey()) != null) + protected void updateMemoryCache() { + if (this.getTileFromMemoryCache(this.getTileKey()) != null) { getMemoryCache().add(this.getTileKey(), this); + } } - protected Texture initializeTexture(DrawContext dc) - { - if (dc == null) - { + protected Texture initializeTexture(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -335,8 +309,9 @@ protected Texture initializeTexture(DrawContext dc) Texture t = this.getTexture(dc.getTextureCache()); // Return texture if found and there is no new texture data - if (t != null && this.getTextureData() == null) + if (t != null && this.getTextureData() == null) { return t; + } if (this.getTextureData() == null) // texture not in cache yet texture data is null, can't initialize { @@ -345,12 +320,9 @@ protected Texture initializeTexture(DrawContext dc) throw new IllegalStateException(msg); } - try - { + try { t = TextureIO.newTexture(this.getTextureData()); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("layers.TextureLayer.ExceptionAttemptingToReadTextureFile", ""); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); return null; @@ -364,10 +336,8 @@ protected Texture initializeTexture(DrawContext dc) return t; } - protected void setTextureParameters(DrawContext dc, Texture t) - { - if (dc == null) - { + protected void setTextureParameters(DrawContext dc, Texture t) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -384,29 +354,24 @@ protected void setTextureParameters(DrawContext dc, Texture t) // between textures near the poles. // // TODO: remove the latitude range restriction if a better tessellator fixes the problem. - boolean useMipmapFilter = (this.hasMipmapData || t.isUsingAutoMipmapGeneration()) - && this.getSector().getMaxLatitude().degrees < 80d && this.getSector().getMinLatitude().degrees > -80; + && this.getSector().getMaxLatitude().degrees < 80d && this.getSector().getMinLatitude().degrees > -80; // Set the texture minification filter. If the texture qualifies for mipmaps, apply a minification filter that // will access the mipmap data using the highest quality algorithm. If the anisotropic texture filter is // available, we will enable it. This will sharpen the appearance of the mipmap filter when the textured // surface is at a high slope to the eye. - if (useMipmapFilter) - { + if (useMipmapFilter) { gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR); // If the maximum degree of anisotropy is 2.0 or greater, then we know this graphics context supports // the anisotropic texture filter. double maxAnisotropy = dc.getGLRuntimeCapabilities().getMaxTextureAnisotropy(); - if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) - { + if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) { gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, (float) maxAnisotropy); } - } - // If the texture does not qualify for mipmaps, then apply a linear minification filter. - else - { + } // If the texture does not qualify for mipmaps, then apply a linear minification filter. + else { gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); } @@ -420,47 +385,43 @@ protected void setTextureParameters(DrawContext dc, Texture t) gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); } - public boolean bind(DrawContext dc) - { - if (dc == null) - { + public boolean bind(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } // Reinitialize texture if new texture data - if (this.getTextureData() != null) - { + if (this.getTextureData() != null) { Texture t = this.initializeTexture(dc); - if (t != null) + if (t != null) { return true; // texture was bound during initialization. + } } Texture t = this.getTexture(dc.getTextureCache()); - if (t == null && this.getFallbackTile() != null) - { + if (t == null && this.getFallbackTile() != null) { TextureTile resourceTile = this.getFallbackTile(); t = resourceTile.getTexture(dc.getTextureCache()); - if (t == null) - { + if (t == null) { t = resourceTile.initializeTexture(dc); - if (t != null) + if (t != null) { return true; // texture was bound during initialization. + } } } - if (t != null) + if (t != null) { t.bind(dc.getGL()); + } return t != null; } - public void applyInternalTransform(DrawContext dc, boolean textureIdentityActive) - { - if (dc == null) - { + public void applyInternalTransform(DrawContext dc, boolean textureIdentityActive) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -470,16 +431,14 @@ public void applyInternalTransform(DrawContext dc, boolean textureIdentityActive Texture t; if (this.getTextureData() != null) // Reinitialize if new texture data + { t = this.initializeTexture(dc); - else + } else { t = this.getTexture(dc.getTextureCache()); // Use the tile's texture if available - - if (t != null) - { - if (t.getMustFlipVertically()) - { - if (!textureIdentityActive) - { + } + if (t != null) { + if (t.getMustFlipVertically()) { + if (!textureIdentityActive) { gl.glMatrixMode(GL2.GL_TEXTURE); gl.glLoadIdentity(); } @@ -492,24 +451,27 @@ public void applyInternalTransform(DrawContext dc, boolean textureIdentityActive // Use the tile's fallback texture if its primary texture is not available. TextureTile resourceTile = this.getFallbackTile(); if (resourceTile == null) // no fallback specified + { return; + } t = resourceTile.getTexture(dc.getTextureCache()); - if (t == null && resourceTile.getTextureData() != null) + if (t == null && resourceTile.getTextureData() != null) { t = resourceTile.initializeTexture(dc); + } if (t == null) // was not able to initialize the fallback texture + { return; + } // Apply necessary transforms to the fallback texture. - if (!textureIdentityActive) - { + if (!textureIdentityActive) { gl.glMatrixMode(GL2.GL_TEXTURE); gl.glLoadIdentity(); } - if (t.getMustFlipVertically()) - { + if (t.getMustFlipVertically()) { gl.glScaled(1, -1, 1); gl.glTranslated(0, -1, 0); } @@ -517,21 +479,21 @@ public void applyInternalTransform(DrawContext dc, boolean textureIdentityActive this.applyResourceTextureTransform(dc); } - protected void applyResourceTextureTransform(DrawContext dc) - { - if (dc == null) - { + protected void applyResourceTextureTransform(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.getLevel() == null) + if (this.getLevel() == null) { return; + } int levelDelta = this.getLevelNumber() - this.getFallbackTile().getLevelNumber(); - if (levelDelta <= 0) + if (levelDelta <= 0) { return; + } double twoToTheN = Math.pow(2, levelDelta); double oneOverTwoToTheN = 1 / twoToTheN; @@ -545,12 +507,13 @@ protected void applyResourceTextureTransform(DrawContext dc) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final TextureTile tile = (TextureTile) o; @@ -558,14 +521,12 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { return (this.getTileKey() != null ? this.getTileKey().hashCode() : 0); } @Override - public String toString() - { + public String toString() { return this.getSector().toString(); } } diff --git a/src/gov/nasa/worldwind/layers/TiledImageLayer.java b/src/gov/nasa/worldwind/layers/TiledImageLayer.java index 19230bd3a3..a552ba49ba 100644 --- a/src/gov/nasa/worldwind/layers/TiledImageLayer.java +++ b/src/gov/nasa/worldwind/layers/TiledImageLayer.java @@ -28,8 +28,8 @@ * @author tag * @version $Id: TiledImageLayer.java 2922 2015-03-24 23:56:58Z tgaskins $ */ -public abstract class TiledImageLayer extends AbstractLayer -{ +public abstract class TiledImageLayer extends AbstractLayer { + // Infrastructure protected static final LevelComparer levelComparer = new LevelComparer(); protected final LevelSet levels; @@ -60,10 +60,8 @@ public abstract class TiledImageLayer extends AbstractLayer abstract protected void forceTextureLoad(TextureTile tile); - public TiledImageLayer(LevelSet levelSet) - { - if (levelSet == null) - { + public TiledImageLayer(LevelSet levelSet) { + if (levelSet == null) { String message = Logging.getMessage("nullValue.LevelSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -77,77 +75,65 @@ public TiledImageLayer(LevelSet levelSet) } @Override - public Object setValue(String key, Object value) - { + public Object setValue(String key, Object value) { // Offer it to the level set - if (this.getLevels() != null) + if (this.getLevels() != null) { this.getLevels().setValue(key, value); + } return super.setValue(key, value); } @Override - public Object getValue(String key) - { + public Object getValue(String key) { Object value = super.getValue(key); return value != null ? value : this.getLevels().getValue(key); // see if the level set has it } @Override - public void setName(String name) - { + public void setName(String name) { super.setName(name); this.tileCountName = this.getName() + " Tiles"; } - public boolean isForceLevelZeroLoads() - { + public boolean isForceLevelZeroLoads() { return this.forceLevelZeroLoads; } - public void setForceLevelZeroLoads(boolean forceLevelZeroLoads) - { + public void setForceLevelZeroLoads(boolean forceLevelZeroLoads) { this.forceLevelZeroLoads = forceLevelZeroLoads; } - public boolean isRetainLevelZeroTiles() - { + public boolean isRetainLevelZeroTiles() { return retainLevelZeroTiles; } - public void setRetainLevelZeroTiles(boolean retainLevelZeroTiles) - { + public void setRetainLevelZeroTiles(boolean retainLevelZeroTiles) { this.retainLevelZeroTiles = retainLevelZeroTiles; } - public boolean isDrawTileIDs() - { + public boolean isDrawTileIDs() { return drawTileIDs; } - public void setDrawTileIDs(boolean drawTileIDs) - { + public void setDrawTileIDs(boolean drawTileIDs) { this.drawTileIDs = drawTileIDs; } - public boolean isDrawTileBoundaries() - { + public boolean isDrawTileBoundaries() { return drawTileBoundaries; } - public void setDrawTileBoundaries(boolean drawTileBoundaries) - { + public void setDrawTileBoundaries(boolean drawTileBoundaries) { this.drawTileBoundaries = drawTileBoundaries; } - public boolean isDrawBoundingVolumes() - { + public boolean isDrawBoundingVolumes() { return drawBoundingVolumes; } - public void setDrawBoundingVolumes(boolean drawBoundingVolumes) - { + public void setDrawBoundingVolumes(boolean drawBoundingVolumes) { this.drawBoundingVolumes = drawBoundingVolumes; } @@ -158,8 +144,7 @@ public void setDrawBoundingVolumes(boolean drawBoundingVolumes) * * @see #setDetailHint(double) */ - public double getDetailHint() - { + public double getDetailHint() { return this.detailHint; } @@ -178,33 +163,28 @@ public double getDetailHint() * Such scales significantly decrease performance. * * @param detailHint the degree to modify the default relationship of image resolution to screen resolution with - * changing view altitudes. Values greater than 1 increase the resolution. Values less than zero - * decrease the resolution. The default value is 0. + * changing view altitudes. Values greater than 1 increase the resolution. Values less than zero decrease the + * resolution. The default value is 0. */ - public void setDetailHint(double detailHint) - { + public void setDetailHint(double detailHint) { this.detailHint = detailHint; } - public LevelSet getLevels() - { + public LevelSet getLevels() { return levels; } - protected PriorityBlockingQueue getRequestQ() - { + protected PriorityBlockingQueue getRequestQ() { return requestQ; } @Override - public boolean isMultiResolution() - { + public boolean isMultiResolution() { return this.getLevels() != null && this.getLevels().getNumLevels() > 1; } @Override - public boolean isAtMaxResolution() - { + public boolean isAtMaxResolution() { return this.atMaxResolution; } @@ -215,8 +195,7 @@ public boolean isAtMaxResolution() * * @see #setTextureFormat(String) */ - public String getTextureFormat() - { + public String getTextureFormat() { return this.textureFormat; } @@ -227,28 +206,23 @@ public String getTextureFormat() * * @param textureFormat the texture image format; null to store images in their native format. */ - public void setTextureFormat(String textureFormat) - { + public void setTextureFormat(String textureFormat) { this.textureFormat = textureFormat; } - public boolean isUseMipMaps() - { + public boolean isUseMipMaps() { return useMipMaps; } - public void setUseMipMaps(boolean useMipMaps) - { + public void setUseMipMaps(boolean useMipMaps) { this.useMipMaps = useMipMaps; } - public boolean isUseTransparentTextures() - { + public boolean isUseTransparentTextures() { return this.useTransparentTextures; } - public void setUseTransparentTextures(boolean useTransparentTextures) - { + public void setUseTransparentTextures(boolean useTransparentTextures) { this.useTransparentTextures = useTransparentTextures; } @@ -261,7 +235,7 @@ public void setUseTransparentTextures(boolean useTransparentTextures) * expiry times of the layer's individual levels if the value specified to the method is greater than zero. * * @param expiryTime the expiry time of any cached data, expressed as a number of milliseconds beyond the epoch. The - * default expiry time is zero. + * default expiry time is zero. * * @see System#currentTimeMillis() for a description of milliseconds beyond the epoch. */ @@ -269,20 +243,20 @@ public void setExpiryTime(long expiryTime) // Override this method to use intrin { super.setExpiryTime(expiryTime); - if (expiryTime > 0) + if (expiryTime > 0) { this.levels.setExpiryTime(expiryTime); // remove this in sub-class to use level-specific expiry times + } } - public List getTopLevels() - { - if (this.topLevels == null) + public List getTopLevels() { + if (this.topLevels == null) { this.createTopLevelTiles(); + } return topLevels; } - protected void createTopLevelTiles() - { + protected void createTopLevelTiles() { Sector sector = this.levels.getSector(); Level level = levels.getFirstLevel(); @@ -303,14 +277,12 @@ protected void createTopLevelTiles() this.topLevels = new ArrayList(nLatTiles * nLonTiles); Angle p1 = Tile.computeRowLatitude(firstRow, dLat, latOrigin); - for (int row = firstRow; row <= lastRow; row++) - { + for (int row = firstRow; row <= lastRow; row++) { Angle p2; p2 = p1.add(dLat); Angle t1 = Tile.computeColumnLongitude(firstCol, dLon, lonOrigin); - for (int col = firstCol; col <= lastCol; col++) - { + for (int col = firstCol; col <= lastCol; col++) { Angle t2; t2 = t1.add(dLon); @@ -321,12 +293,11 @@ protected void createTopLevelTiles() } } - protected void loadAllTopLevelTextures(DrawContext dc) - { - for (TextureTile tile : this.getTopLevels()) - { - if (!tile.isTextureInMemory(dc.getTextureCache())) + protected void loadAllTopLevelTextures(DrawContext dc) { + for (TextureTile tile : this.getTopLevels()) { + if (!tile.isTextureInMemory(dc.getTextureCache())) { this.forceTextureLoad(tile); + } } this.levelZeroLoaded = true; @@ -335,43 +306,34 @@ protected void loadAllTopLevelTextures(DrawContext dc) // ============== Tile Assembly ======================= // // ============== Tile Assembly ======================= // // ============== Tile Assembly ======================= // - - protected void assembleTiles(DrawContext dc) - { + protected void assembleTiles(DrawContext dc) { this.currentTiles.clear(); - for (TextureTile tile : this.getTopLevels()) - { - if (this.isTileVisible(dc, tile)) - { + for (TextureTile tile : this.getTopLevels()) { + if (this.isTileVisible(dc, tile)) { this.currentResourceTile = null; this.addTileOrDescendants(dc, tile); } } } - protected void addTileOrDescendants(DrawContext dc, TextureTile tile) - { - if (this.meetsRenderCriteria(dc, tile)) - { + protected void addTileOrDescendants(DrawContext dc, TextureTile tile) { + if (this.meetsRenderCriteria(dc, tile)) { this.addTile(dc, tile); return; } // The incoming tile does not meet the rendering criteria, so it must be subdivided and those // subdivisions tested against the criteria. - // All tiles that meet the selection criteria are drawn, but some of those tiles will not have // textures associated with them either because their texture isn't loaded yet or because they // are finer grain than the layer has textures for. In these cases the tiles use the texture of // the closest ancestor that has a texture loaded. This ancestor is called the currentResourceTile. // A texture transform is applied during rendering to align the sector's texture coordinates with the // appropriate region of the ancestor's texture. - TextureTile ancestorResource = null; - try - { + try { // TODO: Revise this to reflect that the parent layer is only requested while the algorithm continues // to search for the layer matching the criteria. // At this point the tile does not meet the render criteria but it may have its texture in memory. @@ -385,13 +347,10 @@ protected void addTileOrDescendants(DrawContext dc, TextureTile tile) // progressive resolution increase, this ensures that the parents are available as the user zooms out, and // therefore the layer remains visible until the user is zoomed out to the point the layer is no longer // active. - if (tile.isTextureInMemory(dc.getTextureCache()) || tile.getLevelNumber() == 0) - { + if (tile.isTextureInMemory(dc.getTextureCache()) || tile.getLevelNumber() == 0) { ancestorResource = this.currentResourceTile; this.currentResourceTile = tile; - } - else if (!tile.getLevel().isEmpty()) - { + } else if (!tile.getLevel().isEmpty()) { // this.addTile(dc, tile); // return; @@ -405,87 +364,77 @@ else if (!tile.getLevel().isEmpty()) } TextureTile[] subTiles = tile.createSubTiles(this.levels.getLevel(tile.getLevelNumber() + 1)); - for (TextureTile child : subTiles) - { - if (this.getLevels().getSector().intersects(child.getSector()) && this.isTileVisible(dc, child)) + for (TextureTile child : subTiles) { + if (this.getLevels().getSector().intersects(child.getSector()) && this.isTileVisible(dc, child)) { this.addTileOrDescendants(dc, child); + } } - } - finally - { + } finally { if (ancestorResource != null) // Pop this tile as the currentResource ancestor + { this.currentResourceTile = ancestorResource; + } } } - protected void addTile(DrawContext dc, TextureTile tile) - { + protected void addTile(DrawContext dc, TextureTile tile) { tile.setFallbackTile(null); - if (tile.isTextureInMemory(dc.getTextureCache())) - { + if (tile.isTextureInMemory(dc.getTextureCache())) { this.addTileToCurrent(tile); return; } // Level 0 loads may be forced - if (tile.getLevelNumber() == 0 && this.forceLevelZeroLoads && !tile.isTextureInMemory(dc.getTextureCache())) - { + if (tile.getLevelNumber() == 0 && this.forceLevelZeroLoads && !tile.isTextureInMemory(dc.getTextureCache())) { this.forceTextureLoad(tile); - if (tile.isTextureInMemory(dc.getTextureCache())) - { + if (tile.isTextureInMemory(dc.getTextureCache())) { this.addTileToCurrent(tile); return; } } // Tile's texture isn't available, so request it - if (tile.getLevelNumber() < this.levels.getNumLevels()) - { + if (tile.getLevelNumber() < this.levels.getNumLevels()) { // Request only tiles with data associated at this level - if (!this.levels.isResourceAbsent(tile)) + if (!this.levels.isResourceAbsent(tile)) { this.requestTexture(dc, tile); + } } // Set up to use the currentResource tile's texture - if (this.currentResourceTile != null) - { - if (this.currentResourceTile.getLevelNumber() == 0 && this.forceLevelZeroLoads && - !this.currentResourceTile.isTextureInMemory(dc.getTextureCache()) && - !this.currentResourceTile.isTextureInMemory(dc.getTextureCache())) + if (this.currentResourceTile != null) { + if (this.currentResourceTile.getLevelNumber() == 0 && this.forceLevelZeroLoads + && !this.currentResourceTile.isTextureInMemory(dc.getTextureCache()) + && !this.currentResourceTile.isTextureInMemory(dc.getTextureCache())) { this.forceTextureLoad(this.currentResourceTile); + } - if (this.currentResourceTile.isTextureInMemory(dc.getTextureCache())) - { + if (this.currentResourceTile.isTextureInMemory(dc.getTextureCache())) { tile.setFallbackTile(currentResourceTile); this.addTileToCurrent(tile); } } } - protected void addTileToCurrent(TextureTile tile) - { + protected void addTileToCurrent(TextureTile tile) { this.currentTiles.add(tile); } - protected boolean isTileVisible(DrawContext dc, TextureTile tile) - { - return tile.getExtent(dc).intersects(dc.getView().getFrustumInModelCoordinates()) && - (dc.getVisibleSector() == null || dc.getVisibleSector().intersects(tile.getSector())); + protected boolean isTileVisible(DrawContext dc, TextureTile tile) { + return tile.getExtent(dc).intersects(dc.getView().getFrustumInModelCoordinates()) + && (dc.getVisibleSector() == null || dc.getVisibleSector().intersects(tile.getSector())); } - protected boolean meetsRenderCriteria(DrawContext dc, TextureTile tile) - { + protected boolean meetsRenderCriteria(DrawContext dc, TextureTile tile) { return this.levels.isFinalLevel(tile.getLevelNumber()) || !needToSplit(dc, tile.getSector(), tile.getLevel()); } - protected double getDetailFactor() - { + protected double getDetailFactor() { return this.detailHintOrigin + this.getDetailHint(); } - protected boolean needToSplit(DrawContext dc, Sector sector, Level level) - { + protected boolean needToSplit(DrawContext dc, Sector sector, Level level) { // Compute the height in meters of a texel from the specified level. Take care to convert from the radians to // meters by multiplying by the globe's radius, not the length of a Cartesian point. Using the length of a // Cartesian point is incorrect when the globe is flat. @@ -500,8 +449,9 @@ protected boolean needToSplit(DrawContext dc, Sector sector, Level level) // 50% has the same effect on object size as decreasing the distance between the eye and the object by 50%. // The detail hint is reduced for tiles above 75 degrees north and below 75 degrees south. double s = this.getDetailFactor(); - if (sector.getMinLatitude().degrees >= 75 || sector.getMaxLatitude().degrees <= -75) + if (sector.getMinLatitude().degrees >= 75 || sector.getMaxLatitude().degrees <= -75) { s *= 0.9; + } double detailScale = Math.pow(10, -s); double fieldOfViewScale = dc.getView().getFieldOfView().tanHalfAngle() / Angle.fromDegrees(45).tanHalfAngle(); fieldOfViewScale = WWMath.clamp(fieldOfViewScale, 0, 1); @@ -520,10 +470,10 @@ protected boolean needToSplit(DrawContext dc, Sector sector, Level level) return texelSizeMeters > scaledEyeDistanceMeters; } - public Double getMinEffectiveAltitude(Double radius) - { - if (radius == null) + public Double getMinEffectiveAltitude(Double radius) { + if (radius == null) { radius = Earth.WGS84_EQUATORIAL_RADIUS; + } // Get the texel size in meters for the highest-resolution level. double texelSizeRadians = this.getLevels().getLastLevel().getTexelSize(); @@ -533,16 +483,16 @@ public Double getMinEffectiveAltitude(Double radius) return texelSizeMeters * Math.pow(10, this.getDetailFactor()); } - public Double getMaxEffectiveAltitude(Double radius) - { - if (radius == null) + public Double getMaxEffectiveAltitude(Double radius) { + if (radius == null) { radius = Earth.WGS84_EQUATORIAL_RADIUS; + } // Find first non-empty level. Compute altitude at which it comes into effect. - for (int i = 0; i < this.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (this.levels.isLevelEmpty(i)) + for (int i = 0; i < this.getLevels().getLastLevel().getLevelNumber(); i++) { + if (this.levels.isLevelEmpty(i)) { continue; + } // Compute altitude associated with the texel size at which it would switch if it had a lower-res level. // That texel size is twice that of the current lowest-res level. @@ -555,21 +505,23 @@ public Double getMaxEffectiveAltitude(Double radius) return null; } - protected boolean atMaxLevel(DrawContext dc) - { + protected boolean atMaxLevel(DrawContext dc) { Position vpc = dc.getViewportCenterPosition(); - if (dc.getView() == null || this.getLevels() == null || vpc == null) + if (dc.getView() == null || this.getLevels() == null || vpc == null) { return false; + } - if (!this.getLevels().getSector().contains(vpc.getLatitude(), vpc.getLongitude())) + if (!this.getLevels().getSector().contains(vpc.getLatitude(), vpc.getLongitude())) { return true; + } Level nextToLast = this.getLevels().getNextToLastLevel(); - if (nextToLast == null) + if (nextToLast == null) { return true; + } Sector centerSector = nextToLast.computeSectorForPosition(vpc.getLatitude(), vpc.getLongitude(), - this.levels.getTileOrigin()); + this.levels.getTileOrigin()); return this.needToSplit(dc, centerSector, nextToLast); } @@ -577,38 +529,34 @@ protected boolean atMaxLevel(DrawContext dc) // ============== Rendering ======================= // // ============== Rendering ======================= // // ============== Rendering ======================= // - @Override - public void render(DrawContext dc) - { + public void render(DrawContext dc) { this.atMaxResolution = this.atMaxLevel(dc); super.render(dc); } @Override - protected final void doRender(DrawContext dc) - { - if (this.forceLevelZeroLoads && !this.levelZeroLoaded) + protected final void doRender(DrawContext dc) { + if (this.forceLevelZeroLoads && !this.levelZeroLoaded) { this.loadAllTopLevelTextures(dc); - if (dc.getSurfaceGeometry() == null || dc.getSurfaceGeometry().size() < 1) + } + if (dc.getSurfaceGeometry() == null || dc.getSurfaceGeometry().size() < 1) { return; + } dc.getGeographicSurfaceTileRenderer().setShowImageTileOutlines(this.isDrawTileBoundaries()); draw(dc); } - protected void draw(DrawContext dc) - { + protected void draw(DrawContext dc) { this.assembleTiles(dc); // Determine the tiles to draw. - if (this.currentTiles.size() >= 1) - { + if (this.currentTiles.size() >= 1) { // Indicate that this layer rendered something this frame. this.setValue(AVKey.FRAME_TIMESTAMP, dc.getFrameTimeStamp()); - if (this.getScreenCredit() != null) - { + if (this.getScreenCredit() != null) { dc.addScreenCredit(this.getScreenCredit()); } @@ -618,13 +566,10 @@ protected void draw(DrawContext dc) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (this.isUseTransparentTextures() || this.getOpacity() < 1) - { + if (this.isUseTransparentTextures() || this.getOpacity() < 1) { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_POLYGON_BIT | GL2.GL_CURRENT_BIT); this.setBlendingFunction(dc); - } - else - { + } else { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_POLYGON_BIT); } @@ -633,23 +578,26 @@ protected void draw(DrawContext dc) gl.glCullFace(GL.GL_BACK); dc.setPerFrameStatistic(PerformanceStatistic.IMAGE_TILE_COUNT, this.tileCountName, - this.currentTiles.size()); + this.currentTiles.size()); dc.getGeographicSurfaceTileRenderer().renderTiles(dc, this.currentTiles); gl.glPopAttrib(); - if (this.drawTileIDs) + if (this.drawTileIDs) { this.drawTileIDs(dc, this.currentTiles); + } - if (this.drawBoundingVolumes) + if (this.drawBoundingVolumes) { this.drawBoundingVolumes(dc, this.currentTiles); + } // Check texture expiration. Memory-cached textures are checked for expiration only when an explicit, // non-zero expiry time has been set for the layer. If none has been set, the expiry times of the layer's // individual levels are used, but only for images in the local file cache, not textures in memory. This is // to avoid incurring the overhead of checking expiration of in-memory textures, a very rarely used feature. - if (this.getExpiryTime() > 0 && this.getExpiryTime() <= System.currentTimeMillis()) + if (this.getExpiryTime() > 0 && this.getExpiryTime() <= System.currentTimeMillis()) { this.checkTextureExpiration(dc, this.currentTiles); + } this.currentTiles.clear(); } @@ -658,17 +606,15 @@ protected void draw(DrawContext dc) this.requestQ.clear(); } - protected void checkTextureExpiration(DrawContext dc, List tiles) - { - for (TextureTile tile : tiles) - { - if (tile.isTextureExpired()) + protected void checkTextureExpiration(DrawContext dc, List tiles) { + for (TextureTile tile : tiles) { + if (tile.isTextureExpired()) { this.requestTexture(dc, tile); + } } } - protected void setBlendingFunction(DrawContext dc) - { + protected void setBlendingFunction(DrawContext dc) { // Set up a premultiplied-alpha blending function. Any texture read by JOGL will have alpha-premultiplied color // components, as will any DDS file created by WorldWind or the WorldWind WMS. We'll also set up the base // color as a premultiplied color, so that any incoming premultiplied color will be properly combined with the @@ -682,30 +628,24 @@ protected void setBlendingFunction(DrawContext dc) gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); } - protected void sendRequests() - { + protected void sendRequests() { Runnable task = this.requestQ.poll(); - while (task != null) - { - if (!WorldWind.getTaskService().isFull()) - { + while (task != null) { + if (!WorldWind.getTaskService().isFull()) { WorldWind.getTaskService().addTask(task); } task = this.requestQ.poll(); } } - public boolean isLayerInView(DrawContext dc) - { - if (dc == null) - { + public boolean isLayerInView(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (dc.getView() == null) - { + if (dc.getView() == null) { String message = Logging.getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -714,18 +654,18 @@ public boolean isLayerInView(DrawContext dc) return !(dc.getVisibleSector() != null && !this.levels.getSector().intersects(dc.getVisibleSector())); } - protected Vec4 computeReferencePoint(DrawContext dc) - { - if (dc.getViewportCenterPosition() != null) + protected Vec4 computeReferencePoint(DrawContext dc) { + if (dc.getViewportCenterPosition() != null) { return dc.getGlobe().computePointFromPosition(dc.getViewportCenterPosition()); + } java.awt.geom.Rectangle2D viewport = dc.getView().getViewport(); int x = (int) viewport.getWidth() / 2; - for (int y = (int) (0.5 * viewport.getHeight()); y >= 0; y--) - { + for (int y = (int) (0.5 * viewport.getHeight()); y >= 0; y--) { Position pos = dc.getView().computePositionFromScreenPoint(x, y); - if (pos == null) + if (pos == null) { continue; + } return dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), 0d); } @@ -733,15 +673,13 @@ protected Vec4 computeReferencePoint(DrawContext dc) return null; } - protected Vec4 getReferencePoint(DrawContext dc) - { + protected Vec4 getReferencePoint(DrawContext dc) { return this.computeReferencePoint(dc); } - protected static class LevelComparer implements Comparator - { - public int compare(TextureTile ta, TextureTile tb) - { + protected static class LevelComparer implements Comparator { + + public int compare(TextureTile ta, TextureTile tb) { int la = ta.getFallbackTile() == null ? ta.getLevelNumber() : ta.getFallbackTile().getLevelNumber(); int lb = tb.getFallbackTile() == null ? tb.getLevelNumber() : tb.getFallbackTile().getLevelNumber(); @@ -749,11 +687,10 @@ public int compare(TextureTile ta, TextureTile tb) } } - protected void drawTileIDs(DrawContext dc, ArrayList tiles) - { + protected void drawTileIDs(DrawContext dc, ArrayList tiles) { java.awt.Rectangle viewport = dc.getView().getViewport(); TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - java.awt.Font.decode("Arial-Plain-13")); + java.awt.Font.decode("Arial-Plain-13")); GL gl = dc.getGL(); gl.glDisable(GL.GL_DEPTH_TEST); @@ -762,16 +699,16 @@ protected void drawTileIDs(DrawContext dc, ArrayList tiles) textRenderer.beginRendering(viewport.width, viewport.height); textRenderer.setColor(java.awt.Color.YELLOW); - for (TextureTile tile : tiles) - { + for (TextureTile tile : tiles) { String tileLabel = tile.getLabel(); - if (tile.getFallbackTile() != null) + if (tile.getFallbackTile() != null) { tileLabel += "/" + tile.getFallbackTile().getLabel(); + } LatLon ll = tile.getSector().getCentroid(); Vec4 pt = dc.getGlobe().computePointFromPosition(ll.getLatitude(), ll.getLongitude(), - dc.getGlobe().getElevation(ll.getLatitude(), ll.getLongitude())); + dc.getGlobe().getElevation(ll.getLatitude(), ll.getLongitude())); pt = dc.getView().project(pt); textRenderer.draw(tileLabel, (int) pt.x, (int) pt.y); } @@ -779,18 +716,17 @@ protected void drawTileIDs(DrawContext dc, ArrayList tiles) textRenderer.endRendering(); } - protected void drawBoundingVolumes(DrawContext dc, ArrayList tiles) - { + protected void drawBoundingVolumes(DrawContext dc, ArrayList tiles) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. float[] previousColor = new float[4]; gl.glGetFloatv(GL2.GL_CURRENT_COLOR, previousColor, 0); gl.glColor3d(0, 1, 0); - for (TextureTile tile : tiles) - { - if (tile.getExtent(dc) instanceof Renderable) + for (TextureTile tile : tiles) { + if (tile.getExtent(dc) instanceof Renderable) { ((Renderable) tile.getExtent(dc)).render(dc); + } } Box c = Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), this.levels.getSector()); @@ -803,7 +739,6 @@ protected void drawBoundingVolumes(DrawContext dc, ArrayList tiles) //**************************************************************// //******************** Configuration *************************// //**************************************************************// - /** * Creates a configuration document for a TiledImageLayer described by the specified params. The returned document * may be used as a construction parameter to {@link gov.nasa.worldwind.layers.BasicTiledImageLayer}. @@ -812,8 +747,7 @@ protected void drawBoundingVolumes(DrawContext dc, ArrayList tiles) * * @return a configuration document for the TiledImageLayer. */ - public static Document createTiledImageLayerConfigDocument(AVList params) - { + public static Document createTiledImageLayerConfigDocument(AVList params) { Document doc = WWXML.createDocumentBuilder(true).newDocument(); Element root = WWXML.setDocumentElement(doc, "Layer"); @@ -845,24 +779,21 @@ public static Document createTiledImageLayerConfigDocument(AVList params) * org.w3c.dom.Element)} and {@link DataConfigurationUtils#createLevelSetConfigElements(gov.nasa.worldwind.avlist.AVList, * org.w3c.dom.Element)}. * - * @param params the key-value pairs which define the TiledImageLayer configuration parameters. + * @param params the key-value pairs which define the TiledImageLayer configuration parameters. * @param context the XML document root on which to append TiledImageLayer configuration elements. * * @return a reference to context. * * @throws IllegalArgumentException if either the parameters or the context are null. */ - public static Element createTiledImageLayerConfigElements(AVList params, Element context) - { - if (params == null) - { + public static Element createTiledImageLayerConfigElements(AVList params, Element context) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -879,33 +810,32 @@ public static Element createTiledImageLayerConfigElements(AVList params, Element // Service properties. // Try to get the SERVICE_NAME property, but default to "WWTileService". String s = AVListImpl.getStringValue(params, AVKey.SERVICE_NAME, "WWTileService"); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { // The service element may already exist, in which case we want to append to it. Element el = WWXML.getElement(context, "Service", xpath); - if (el == null) + if (el == null) { el = WWXML.appendElementPath(context, "Service"); + } WWXML.setTextAttribute(el, "serviceName", s); } WWXML.checkAndAppendBooleanElement(params, AVKey.RETRIEVE_PROPERTIES_FROM_SERVICE, context, - "RetrievePropertiesFromService"); + "RetrievePropertiesFromService"); // Image format properties. WWXML.checkAndAppendTextElement(params, AVKey.IMAGE_FORMAT, context, "ImageFormat"); WWXML.checkAndAppendTextElement(params, AVKey.TEXTURE_FORMAT, context, "TextureFormat"); Object o = params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS); - if (o != null && o instanceof String[]) - { + if (o != null && o instanceof String[]) { String[] strings = (String[]) o; - if (strings.length > 0) - { + if (strings.length > 0) { // The available image formats element may already exists, in which case we want to append to it, rather // than create entirely separate paths. Element el = WWXML.getElement(context, "AvailableImageFormats", xpath); - if (el == null) + if (el == null) { el = WWXML.appendElementPath(context, "AvailableImageFormats"); + } WWXML.appendTextArray(el, "ImageFormat", strings); } } @@ -918,18 +848,18 @@ public static Element createTiledImageLayerConfigElements(AVList params, Element WWXML.checkAndAppendDoubleElement(params, AVKey.DETAIL_HINT, context, "DetailHint"); // Retrieval properties. - if (params.getValue(AVKey.URL_CONNECT_TIMEOUT) != null || - params.getValue(AVKey.URL_READ_TIMEOUT) != null || - params.getValue(AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT) != null) - { + if (params.getValue(AVKey.URL_CONNECT_TIMEOUT) != null + || params.getValue(AVKey.URL_READ_TIMEOUT) != null + || params.getValue(AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT) != null) { Element el = WWXML.getElement(context, "RetrievalTimeouts", xpath); - if (el == null) + if (el == null) { el = WWXML.appendElementPath(context, "RetrievalTimeouts"); + } WWXML.checkAndAppendTimeElement(params, AVKey.URL_CONNECT_TIMEOUT, el, "ConnectTimeout/Time"); WWXML.checkAndAppendTimeElement(params, AVKey.URL_READ_TIMEOUT, el, "ReadTimeout/Time"); WWXML.checkAndAppendTimeElement(params, AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT, el, - "StaleRequestLimit/Time"); + "StaleRequestLimit/Time"); } return context; @@ -957,24 +887,23 @@ public static Element createTiledImageLayerConfigElements(AVList params, Element * gov.nasa.worldwind.avlist.AVList)}. * * @param domElement the XML document root to parse for TiledImageLayer configuration parameters. - * @param params the output key-value pairs which recieve the TiledImageLayer configuration parameters. A null - * reference is permitted. + * @param params the output key-value pairs which recieve the TiledImageLayer configuration parameters. A null + * reference is permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - public static AVList getTiledImageLayerConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + public static AVList getTiledImageLayerConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } XPath xpath = WWXML.makeXPath(); @@ -987,32 +916,32 @@ public static AVList getTiledImageLayerConfigParams(Element domElement, AVList p // Service properties. WWXML.checkAndSetStringParam(domElement, params, AVKey.SERVICE_NAME, "Service/@serviceName", xpath); WWXML.checkAndSetBooleanParam(domElement, params, AVKey.RETRIEVE_PROPERTIES_FROM_SERVICE, - "RetrievePropertiesFromService", xpath); + "RetrievePropertiesFromService", xpath); // Image format properties. WWXML.checkAndSetStringParam(domElement, params, AVKey.IMAGE_FORMAT, "ImageFormat", xpath); WWXML.checkAndSetStringParam(domElement, params, AVKey.TEXTURE_FORMAT, "TextureFormat", xpath); WWXML.checkAndSetUniqueStringsParam(domElement, params, AVKey.AVAILABLE_IMAGE_FORMATS, - "AvailableImageFormats/ImageFormat", xpath); + "AvailableImageFormats/ImageFormat", xpath); // Optional behavior properties. WWXML.checkAndSetBooleanParam(domElement, params, AVKey.FORCE_LEVEL_ZERO_LOADS, "ForceLevelZeroLoads", xpath); WWXML.checkAndSetBooleanParam(domElement, params, AVKey.RETAIN_LEVEL_ZERO_TILES, "RetainLevelZeroTiles", xpath); WWXML.checkAndSetBooleanParam(domElement, params, AVKey.USE_MIP_MAPS, "UseMipMaps", xpath); WWXML.checkAndSetBooleanParam(domElement, params, AVKey.USE_TRANSPARENT_TEXTURES, "UseTransparentTextures", - xpath); + xpath); WWXML.checkAndSetDoubleParam(domElement, params, AVKey.DETAIL_HINT, "DetailHint", xpath); WWXML.checkAndSetColorArrayParam(domElement, params, AVKey.TRANSPARENCY_COLORS, "TransparencyColors/Color", - xpath); + xpath); // Retrieval properties. Convert the Long time values to Integers, because BasicTiledImageLayer is expecting // Integer values. WWXML.checkAndSetTimeParamAsInteger(domElement, params, AVKey.URL_CONNECT_TIMEOUT, - "RetrievalTimeouts/ConnectTimeout/Time", xpath); + "RetrievalTimeouts/ConnectTimeout/Time", xpath); WWXML.checkAndSetTimeParamAsInteger(domElement, params, AVKey.URL_READ_TIMEOUT, - "RetrievalTimeouts/ReadTimeout/Time", xpath); + "RetrievalTimeouts/ReadTimeout/Time", xpath); WWXML.checkAndSetTimeParamAsInteger(domElement, params, AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT, - "RetrievalTimeouts/StaleRequestLimit/Time", xpath); + "RetrievalTimeouts/StaleRequestLimit/Time", xpath); // Parse the legacy configuration parameters. This enables TiledImageLayer to recognize elements from previous // versions of configuration documents. @@ -1024,39 +953,39 @@ public static AVList getTiledImageLayerConfigParams(Element domElement, AVList p /** * Parses TiledImageLayer configuration parameters from previous versions of configuration documents. This writes * output as key-value pairs to params. If a parameter from the XML document already exists in params, that - * parameter is ignored. Supported key and parameter names are: - *
        Supported Names
        ParameterElement - * PathType
        {@link AVKey#TEXTURE_FORMAT}CompressTextures"image/dds" if - * CompressTextures is "true"; null otherwise
        + * parameter is ignored. Supported key and parameter names are: + * + * + *
        Supported Names
        ParameterElement PathType
        {@link AVKey#TEXTURE_FORMAT}CompressTextures"image/dds" if CompressTextures is "true"; + * null otherwise
        * * @param domElement the XML document root to parse for legacy TiledImageLayer configuration parameters. - * @param params the output key-value pairs which recieve the TiledImageLayer configuration parameters. A null - * reference is permitted. + * @param params the output key-value pairs which recieve the TiledImageLayer configuration parameters. A null + * reference is permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - protected static AVList getLegacyTiledImageLayerConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + protected static AVList getLegacyTiledImageLayerConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } XPath xpath = WWXML.makeXPath(); Object o = params.getValue(AVKey.TEXTURE_FORMAT); - if (o == null) - { + if (o == null) { Boolean b = WWXML.getBoolean(domElement, "CompressTextures", xpath); - if (b != null && b) + if (b != null && b) { params.setValue(AVKey.TEXTURE_FORMAT, "image/dds"); + } } return params; @@ -1065,74 +994,63 @@ protected static AVList getLegacyTiledImageLayerConfigParams(Element domElement, // ============== Image Composition ======================= // // ============== Image Composition ======================= // // ============== Image Composition ======================= // - - public List getAvailableImageFormats() - { + public List getAvailableImageFormats() { return new ArrayList(this.supportedImageFormats); } - public boolean isImageFormatAvailable(String imageFormat) - { + public boolean isImageFormatAvailable(String imageFormat) { return imageFormat != null && this.supportedImageFormats.contains(imageFormat); } - public String getDefaultImageFormat() - { + public String getDefaultImageFormat() { return this.supportedImageFormats.size() > 0 ? this.supportedImageFormats.get(0) : null; } - protected void setAvailableImageFormats(String[] formats) - { + protected void setAvailableImageFormats(String[] formats) { this.supportedImageFormats.clear(); - if (formats != null) + if (formats != null) { this.supportedImageFormats.addAll(Arrays.asList(formats)); + } } protected BufferedImage requestImage(TextureTile tile, String mimeType) - throws URISyntaxException, InterruptedIOException, MalformedURLException - { + throws URISyntaxException, InterruptedIOException, MalformedURLException { String pathBase = tile.getPathBase(); String suffix = WWIO.makeSuffixForMimeType(mimeType); String path = pathBase + suffix; File f = new File(path); URL url; - if (f.isAbsolute() && f.exists()) + if (f.isAbsolute() && f.exists()) { url = f.toURI().toURL(); - else + } else { url = this.getDataFileStore().findFile(path, false); + } if (url == null) // image is not local + { return null; + } - if (WWIO.isFileOutOfDate(url, tile.getLevel().getExpiryTime())) - { + if (WWIO.isFileOutOfDate(url, tile.getLevel().getExpiryTime())) { // The file has expired. Delete it. this.getDataFileStore().removeFile(url); String message = Logging.getMessage("generic.DataFileExpired", url); Logging.logger().fine(message); - } - else - { - try - { + } else { + try { File imageFile = new File(url.toURI()); BufferedImage image = ImageIO.read(imageFile); - if (image == null) - { + if (image == null) { String message = Logging.getMessage("generic.ImageReadFailed", imageFile); throw new RuntimeException(message); } this.levels.unmarkResourceAbsent(tile); return image; - } - catch (InterruptedIOException e) - { + } catch (InterruptedIOException e) { throw e; - } - catch (IOException e) - { + } catch (IOException e) { // Assume that something's wrong with the file and delete it. this.getDataFileStore().removeFile(url); this.levels.markResourceAbsent(tile); @@ -1144,33 +1062,30 @@ protected BufferedImage requestImage(TextureTile tile, String mimeType) return null; } - protected void downloadImage(final TextureTile tile, String mimeType, int timeout) throws Exception - { - if (this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL) != null) + protected void downloadImage(final TextureTile tile, String mimeType, int timeout) throws Exception { + if (this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL) != null) { this.retrieveLocalImage(tile, mimeType, timeout); - else - // Assume it's remote. + } else // Assume it's remote. + { this.retrieveRemoteImage(tile, mimeType, timeout); + } } - protected void retrieveRemoteImage(final TextureTile tile, String mimeType, int timeout) throws Exception - { + protected void retrieveRemoteImage(final TextureTile tile, String mimeType, int timeout) throws Exception { // TODO: apply retriever-factory pattern for remote retrieval case. final URL resourceURL = tile.getResourceURL(mimeType); - if (resourceURL == null) + if (resourceURL == null) { return; + } Retriever retriever; String protocol = resourceURL.getProtocol(); - if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol)) - { + if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol)) { retriever = new HTTPRetriever(resourceURL, new CompositionRetrievalPostProcessor(tile)); retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers - } - else - { + } else { String message = Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", resourceURL); throw new RuntimeException(message); } @@ -1181,14 +1096,15 @@ protected void retrieveRemoteImage(final TextureTile tile, String mimeType, int retriever.call(); } - protected void retrieveLocalImage(TextureTile tile, String mimeType, int timeout) throws Exception - { - if (!WorldWind.getLocalRetrievalService().isAvailable()) + protected void retrieveLocalImage(TextureTile tile, String mimeType, int timeout) throws Exception { + if (!WorldWind.getLocalRetrievalService().isAvailable()) { return; + } RetrieverFactory retrieverFactory = (RetrieverFactory) this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL); - if (retrieverFactory == null) + if (retrieverFactory == null) { return; + } AVListImpl avList = new AVListImpl(); avList.setValue(AVKey.SECTOR, tile.getSector()); @@ -1204,10 +1120,8 @@ protected void retrieveLocalImage(TextureTile tile, String mimeType, int timeout retriever.call(); } - public int computeLevelForResolution(Sector sector, double resolution) - { - if (sector == null) - { + public int computeLevelForResolution(Sector sector, double resolution) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1216,57 +1130,58 @@ public int computeLevelForResolution(Sector sector, double resolution) // Find the first level exceeding the desired resolution double texelSize; Level targetLevel = this.levels.getLastLevel(); - for (int i = 0; i < this.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (this.levels.isLevelEmpty(i)) + for (int i = 0; i < this.getLevels().getLastLevel().getLevelNumber(); i++) { + if (this.levels.isLevelEmpty(i)) { continue; + } texelSize = this.levels.getLevel(i).getTexelSize(); - if (texelSize > resolution) + if (texelSize > resolution) { continue; + } targetLevel = this.levels.getLevel(i); break; } // Choose the level closest to the resolution desired - if (targetLevel.getLevelNumber() != 0 && !this.levels.isLevelEmpty(targetLevel.getLevelNumber() - 1)) - { + if (targetLevel.getLevelNumber() != 0 && !this.levels.isLevelEmpty(targetLevel.getLevelNumber() - 1)) { Level nextLowerLevel = this.levels.getLevel(targetLevel.getLevelNumber() - 1); double dless = Math.abs(nextLowerLevel.getTexelSize() - resolution); double dmore = Math.abs(targetLevel.getTexelSize() - resolution); - if (dless < dmore) + if (dless < dmore) { targetLevel = nextLowerLevel; + } } Logging.logger().fine(Logging.getMessage("layers.TiledImageLayer.LevelSelection", - targetLevel.getLevelNumber(), Double.toString(targetLevel.getTexelSize()))); + targetLevel.getLevelNumber(), Double.toString(targetLevel.getTexelSize()))); return targetLevel.getLevelNumber(); } /** - * Create an image for the portion of this layer lying within a specified sector.The image is created at a - specified aspect ratio within a canvas of a specified size. This returns the specified image if this layer has no - content in the specified sector. + * Create an image for the portion of this layer lying within a specified sector.The image is created at a specified + * aspect ratio within a canvas of a specified size. This returns the specified image if this layer has no content + * in the specified sector. * - * @param sector the sector of interest. - * @param canvasWidth the width of the canvas. + * @param sector the sector of interest. + * @param canvasWidth the width of the canvas. * @param canvasHeight the height of the canvas. - * @param aspectRatio the aspect ratio, width/height, of the window. If the aspect ratio is greater or equal to - * one, the full width of the canvas is used for the image; the height used is proportional to - * the inverse of the aspect ratio. If the aspect ratio is less than one, the full height of the - * canvas is used, and the width used is proportional to the aspect ratio. - * @param levelNumber the target level of the tiled image layer. - * @param mimeType the type of image to create, e.g., "png" and "jpg". + * @param aspectRatio the aspect ratio, width/height, of the window. If the aspect ratio is greater or equal to one, + * the full width of the canvas is used for the image; the height used is proportional to the inverse of the aspect + * ratio. If the aspect ratio is less than one, the full height of the canvas is used, and the width used is + * proportional to the aspect ratio. + * @param levelNumber the target level of the tiled image layer. + * @param mimeType the type of image to create, e.g., "png" and "jpg". * @param abortOnError indicates whether to stop assembling the image if an error occurs. If false, processing - * continues until all portions of the layer that intersect the specified sector have been added - * to the image. Portions for which an error occurs will be blank. - * @param image if non-null, a {@link BufferedImage} in which to place the image. If null, a new buffered - * image is created. The image must be the width and height specified in the - * canvasWidth and canvasHeight arguments. - * @param timeout The amount of time to allow for reading the image from the server. + * continues until all portions of the layer that intersect the specified sector have been added to the image. + * Portions for which an error occurs will be blank. + * @param image if non-null, a {@link BufferedImage} in which to place the image. If null, a new buffered image is + * created. The image must be the width and height specified in the canvasWidth and + * canvasHeight arguments. + * @param timeout The amount of time to allow for reading the image from the server. * - * @return image the assembled image, of size indicated by the canvasWidth and + * @return image the assembled image, of size indicated by the canvasWidth and * canvasHeight. If the specified aspect ratio is one, all pixels contain values. If the aspect ratio * is greater than one, a full-width segment along the top of the canvas is blank. If the aspect ratio is less than * one, a full-height segment along the right side of the canvase is blank. If the image argument was @@ -1275,85 +1190,72 @@ public int computeLevelForResolution(Sector sector, double resolution) * @throws IllegalArgumentException if sector is null. * @throws java.lang.Exception Other errors. * @see ImageUtil#mergeImage(gov.nasa.worldwind.geom.Sector, gov.nasa.worldwind.geom.Sector, double, - * java.awt.image.BufferedImage, java.awt.image.BufferedImage) ; + * java.awt.image.BufferedImage, java.awt.image.BufferedImage) ; */ public BufferedImage composeImageForSector(Sector sector, int canvasWidth, int canvasHeight, double aspectRatio, - int levelNumber, String mimeType, boolean abortOnError, BufferedImage image, int timeout) throws Exception - { - if (sector == null) - { + int levelNumber, String mimeType, boolean abortOnError, BufferedImage image, int timeout) throws Exception { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.levels.getSector().intersects(sector)) - { + if (!this.levels.getSector().intersects(sector)) { Logging.logger().severe(Logging.getMessage("generic.SectorRequestedOutsideCoverageArea", sector, - this.levels.getSector())); + this.levels.getSector())); return image; } Sector intersection = this.levels.getSector().intersection(sector); - if (levelNumber < 0) - { + if (levelNumber < 0) { levelNumber = this.levels.getLastLevel().getLevelNumber(); - } - else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) - { + } else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) { Logging.logger().warning(Logging.getMessage("generic.LevelRequestedGreaterThanMaxLevel", - levelNumber, this.levels.getLastLevel().getLevelNumber())); + levelNumber, this.levels.getLastLevel().getLevelNumber())); levelNumber = this.levels.getLastLevel().getLevelNumber(); } int numTiles = 0; TextureTile[][] tiles = this.getTilesInSector(intersection, levelNumber); - for (TextureTile[] row : tiles) - { + for (TextureTile[] row : tiles) { numTiles += row.length; } - if (tiles.length == 0 || tiles[0].length == 0) - { + if (tiles.length == 0 || tiles[0].length == 0) { Logging.logger().severe(Logging.getMessage("layers.TiledImageLayer.NoImagesAvailable")); return image; } - if (image == null) + if (image == null) { image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB); + } double tileCount = 0; - for (TextureTile[] row : tiles) - { - for (TextureTile tile : row) - { - if (tile == null) + for (TextureTile[] row : tiles) { + for (TextureTile tile : row) { + if (tile == null) { continue; + } BufferedImage tileImage; - try - { + try { tileImage = this.getImage(tile, mimeType, timeout); Thread.sleep(1); // generates InterruptedException if thread has been interupted - if (tileImage != null) + if (tileImage != null) { ImageUtil.mergeImage(sector, tile.getSector(), aspectRatio, tileImage, image); + } this.firePropertyChange(AVKey.PROGRESS, tileCount / numTiles, ++tileCount / numTiles); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { throw e; - } - catch (InterruptedIOException e) - { + } catch (InterruptedIOException e) { throw e; - } - catch (Exception e) - { - if (abortOnError) + } catch (Exception e) { + if (abortOnError) { throw e; + } String message = Logging.getMessage("generic.ExceptionWhileRequestingImage", tile.getPath()); Logging.logger().log(java.util.logging.Level.WARNING, message, e); @@ -1364,33 +1266,29 @@ else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) return image; } - public long countImagesInSector(Sector sector) - { + public long countImagesInSector(Sector sector) { long count = 0; - for (int i = 0; i <= this.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (!this.levels.isLevelEmpty(i)) + for (int i = 0; i <= this.getLevels().getLastLevel().getLevelNumber(); i++) { + if (!this.levels.isLevelEmpty(i)) { count += countImagesInSector(sector, i); + } } return count; } - public long countImagesInSector(Sector sector, int levelNumber) - { - if (sector == null) - { + public long countImagesInSector(Sector sector, int levelNumber) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.levels.getLastLevel(); - if (levelNumber >= 0) - { - for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (this.levels.isLevelEmpty(i)) + if (levelNumber >= 0) { + for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) { + if (this.levels.isLevelEmpty(i)) { continue; + } targetLevel = this.levels.getLevel(i); break; @@ -1411,22 +1309,19 @@ public long countImagesInSector(Sector sector, int levelNumber) return numRows * numCols; } - public TextureTile[][] getTilesInSector(Sector sector, int levelNumber) - { - if (sector == null) - { + public TextureTile[][] getTilesInSector(Sector sector, int levelNumber) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.levels.getLastLevel(); - if (levelNumber >= 0) - { - for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (this.levels.isLevelEmpty(i)) + if (levelNumber >= 0) { + for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) { + if (this.levels.isLevelEmpty(i)) { continue; + } targetLevel = this.levels.getLevel(i); break; @@ -1445,10 +1340,8 @@ public TextureTile[][] getTilesInSector(Sector sector, int levelNumber) int numCols = seCol - nwCol + 1; TextureTile[][] sectorTiles = new TextureTile[numRows][numCols]; - for (int row = nwRow; row >= seRow; row--) - { - for (int col = nwCol; col <= seCol; col++) - { + for (int row = nwRow; row >= seRow; row--) { + for (int col = nwCol; col <= seCol; col++) { TileKey key = new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName()); Sector tileSector = this.levels.computeSectorForKey(key); sectorTiles[nwRow - row][col - nwCol] = new TextureTile(tileSector, targetLevel, row, col); @@ -1458,13 +1351,13 @@ public TextureTile[][] getTilesInSector(Sector sector, int levelNumber) return sectorTiles; } - protected BufferedImage getImage(TextureTile tile, String mimeType, int timeout) throws Exception - { + protected BufferedImage getImage(TextureTile tile, String mimeType, int timeout) throws Exception { // Read the image from disk. BufferedImage image = this.requestImage(tile, mimeType); Thread.sleep(1); // generates InterruptedException if thread has been interrupted - if (image != null) + if (image != null) { return image; + } // Retrieve it from the net since it's not on disk. this.downloadImage(tile, mimeType, timeout); @@ -1472,32 +1365,28 @@ protected BufferedImage getImage(TextureTile tile, String mimeType, int timeout) // Try to read from disk again after retrieving it from the net. image = this.requestImage(tile, mimeType); Thread.sleep(1); // generates InterruptedException if thread has been interupted - if (image == null) - { - String message = - Logging.getMessage("layers.TiledImageLayer.ImageUnavailable", tile.getPath()); + if (image == null) { + String message + = Logging.getMessage("layers.TiledImageLayer.ImageUnavailable", tile.getPath()); throw new RuntimeException(message); } return image; } - protected class CompositionRetrievalPostProcessor extends AbstractRetrievalPostProcessor - { + protected class CompositionRetrievalPostProcessor extends AbstractRetrievalPostProcessor { + protected TextureTile tile; - public CompositionRetrievalPostProcessor(TextureTile tile) - { + public CompositionRetrievalPostProcessor(TextureTile tile) { this.tile = tile; } - protected File doGetOutputFile() - { + protected File doGetOutputFile() { String suffix = WWIO.makeSuffixForMimeType(this.getRetriever().getContentType()); - if (suffix == null) - { + if (suffix == null) { Logging.logger().severe( - Logging.getMessage("generic.UnknownContentType", this.getRetriever().getContentType())); + Logging.getMessage("generic.UnknownContentType", this.getRetriever().getContentType())); return null; } @@ -1506,31 +1395,28 @@ protected File doGetOutputFile() File f = new File(path); final File outFile = f.isAbsolute() ? f : getDataFileStore().newFile(path); - if (outFile == null) + if (outFile == null) { return null; + } return outFile; } @Override - protected boolean isDeleteOnExit(File outFile) - { + protected boolean isDeleteOnExit(File outFile) { return outFile.getPath().contains(WWIO.DELETE_ON_EXIT_PREFIX); } @Override - protected boolean overwriteExistingFile() - { + protected boolean overwriteExistingFile() { return true; } - protected void markResourceAbsent() - { + protected void markResourceAbsent() { TiledImageLayer.this.levels.markResourceAbsent(tile); } - protected void handleUnsuccessfulRetrieval() - { + protected void handleUnsuccessfulRetrieval() { // Don't mark the tile as absent because the caller may want to try again. } } diff --git a/src/gov/nasa/worldwind/layers/ViewControlsLayer.java b/src/gov/nasa/worldwind/layers/ViewControlsLayer.java index 163c1356c8..e836bfcf32 100644 --- a/src/gov/nasa/worldwind/layers/ViewControlsLayer.java +++ b/src/gov/nasa/worldwind/layers/ViewControlsLayer.java @@ -17,7 +17,8 @@ * and vertical exaggeration. Each of the controls can be enabled or disabled independently. *

        * An instance of this class depends on an instance of {@link ViewControlsSelectListener} to control it. The select - * listener must be registered as such via {@link gov.nasa.worldwind.WorldWindow#addSelectListener(gov.nasa.worldwind.event.SelectListener)}. + * listener must be registered as such via + * {@link gov.nasa.worldwind.WorldWindow#addSelectListener(gov.nasa.worldwind.event.SelectListener)}. *

        * ViewControlsLayer instances are not sharable among WorldWindows. * @@ -25,8 +26,8 @@ * @version $Id: ViewControlsLayer.java 1171 2013-02-11 21:45:02Z dcollins $ * @see ViewControlsSelectListener */ -public class ViewControlsLayer extends RenderableLayer -{ +public class ViewControlsLayer extends RenderableLayer { + // The default images protected final static String IMAGE_PAN = "images/view-pan-64x64.png"; protected final static String IMAGE_LOOK = "images/view-look-64x64.png"; @@ -75,8 +76,7 @@ public class ViewControlsLayer extends RenderableLayer protected boolean showFovControls = false; protected boolean showVeControls = true; - public int getBorderWidth() - { + public int getBorderWidth() { return this.borderWidth; } @@ -86,8 +86,7 @@ public int getBorderWidth() * @param borderWidth the number of pixels to offset the view controls from the borders indicated by {@link * #setPosition(String)}. */ - public void setBorderWidth(int borderWidth) - { + public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; clearControls(); } @@ -97,8 +96,7 @@ public void setBorderWidth(int borderWidth) * * @return the controls display scale. */ - public double getScale() - { + public double getScale() { return this.scale; } @@ -107,30 +105,25 @@ public double getScale() * * @param scale the controls display scale. */ - public void setScale(double scale) - { + public void setScale(double scale) { this.scale = scale; clearControls(); } - protected int getButtonSize() - { + protected int getButtonSize() { return buttonSize; } - protected void setButtonSize(int buttonSize) - { + protected void setButtonSize(int buttonSize) { this.buttonSize = buttonSize; clearControls(); } - protected int getPanSize() - { + protected int getPanSize() { return panSize; } - protected void setPanSize(int panSize) - { + protected void setPanSize(int panSize) { this.panSize = panSize; clearControls(); } @@ -140,8 +133,7 @@ protected void setPanSize(int panSize) * * @return the current view controls position. */ - public String getPosition() - { + public String getPosition() { return this.position; } @@ -152,10 +144,8 @@ public String getPosition() * * @param position the desired view controls position, in screen coordinates. */ - public void setPosition(String position) - { - if (position == null) - { + public void setPosition(String position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -169,8 +159,7 @@ public void setPosition(String position) * * @return the current layout. */ - public String getLayout() - { + public String getLayout() { return this.layout; } @@ -179,16 +168,13 @@ public String getLayout() * * @param layout the desired layout. */ - public void setLayout(String layout) - { - if (layout == null) - { + public void setLayout(String layout) { + if (layout == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.layout.equals(layout)) - { + if (!this.layout.equals(layout)) { this.layout = layout; clearControls(); } @@ -201,8 +187,7 @@ public void setLayout(String layout) * @param opacity the current opacity value, which is ignored by this layer. */ @Override - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { super.setOpacity(opacity); } @@ -213,8 +198,7 @@ public void setOpacity(double opacity) * @return The layer opacity, a value between 0 and 1. */ @Override - public double getOpacity() - { + public double getOpacity() { return super.getOpacity(); } @@ -223,8 +207,7 @@ public double getOpacity() * * @return the current location center. May be null. */ - public Vec4 getLocationCenter() - { + public Vec4 getLocationCenter() { return locationCenter; } @@ -241,8 +224,7 @@ public Vec4 getLocationCenter() * @see #setPosition(String) * @see #setLocationOffset(gov.nasa.worldwind.geom.Vec4) */ - public void setLocationCenter(Vec4 locationCenter) - { + public void setLocationCenter(Vec4 locationCenter) { this.locationCenter = locationCenter; clearControls(); } @@ -252,8 +234,7 @@ public void setLocationCenter(Vec4 locationCenter) * * @return the location offset. Will be null if no offset has been specified. */ - public Vec4 getLocationOffset() - { + public Vec4 getLocationOffset() { return locationOffset; } @@ -261,113 +242,91 @@ public Vec4 getLocationOffset() * Specifies a placement offset from the layer position on the screen. * * @param locationOffset the number of pixels to shift the layer image from its specified screen position. A - * positive X value shifts the image to the right. A positive Y value shifts the image up. If - * null, no offset is applied. The default offset is null. + * positive X value shifts the image to the right. A positive Y value shifts the image up. If null, no offset is + * applied. The default offset is null. * * @see #setLocationCenter(gov.nasa.worldwind.geom.Vec4) * @see #setPosition(String) */ - public void setLocationOffset(Vec4 locationOffset) - { + public void setLocationOffset(Vec4 locationOffset) { this.locationOffset = locationOffset; clearControls(); } - public boolean isShowPanControls() - { + public boolean isShowPanControls() { return this.showPanControls; } - public void setShowPanControls(boolean state) - { - if (this.showPanControls != state) - { + public void setShowPanControls(boolean state) { + if (this.showPanControls != state) { this.showPanControls = state; clearControls(); } } - public boolean isShowLookControls() - { + public boolean isShowLookControls() { return this.showLookControls; } - public void setShowLookControls(boolean state) - { - if (this.showLookControls != state) - { + public void setShowLookControls(boolean state) { + if (this.showLookControls != state) { this.showLookControls = state; clearControls(); } } - public boolean isShowHeadingControls() - { + public boolean isShowHeadingControls() { return this.showHeadingControls; } - public void setShowHeadingControls(boolean state) - { - if (this.showHeadingControls != state) - { + public void setShowHeadingControls(boolean state) { + if (this.showHeadingControls != state) { this.showHeadingControls = state; clearControls(); } } - public boolean isShowZoomControls() - { + public boolean isShowZoomControls() { return this.showZoomControls; } - public void setShowZoomControls(boolean state) - { - if (this.showZoomControls != state) - { + public void setShowZoomControls(boolean state) { + if (this.showZoomControls != state) { this.showZoomControls = state; clearControls(); } } - public boolean isShowPitchControls() - { + public boolean isShowPitchControls() { return this.showPitchControls; } - public void setShowPitchControls(boolean state) - { - if (this.showPitchControls != state) - { + public void setShowPitchControls(boolean state) { + if (this.showPitchControls != state) { this.showPitchControls = state; clearControls(); } } - public boolean isShowFovControls() - { + public boolean isShowFovControls() { return this.showFovControls; } - public void setShowFovControls(boolean state) - { - if (this.showFovControls != state) - { + public void setShowFovControls(boolean state) { + if (this.showFovControls != state) { this.showFovControls = state; clearControls(); } } - public void setShowVeControls(boolean state) - { - if (this.showVeControls != state) - { + public void setShowVeControls(boolean state) { + if (this.showVeControls != state) { this.showVeControls = state; clearControls(); } } - public boolean isShowVeControls() - { + public boolean isShowVeControls() { return this.showVeControls; } @@ -379,38 +338,40 @@ public boolean isShowVeControls() * @return the control type. Can be one of {@link AVKey#VIEW_PAN}, {@link AVKey#VIEW_LOOK}, {@link * AVKey#VIEW_HEADING_LEFT}, {@link AVKey#VIEW_HEADING_RIGHT}, {@link AVKey#VIEW_ZOOM_IN}, {@link * AVKey#VIEW_ZOOM_OUT}, {@link AVKey#VIEW_PITCH_UP}, {@link AVKey#VIEW_PITCH_DOWN}, {@link - * AVKey#VIEW_FOV_NARROW} or {@link AVKey#VIEW_FOV_WIDE}.

        Returns null if the object is not a view - * control associated with this layer.

        + * AVKey#VIEW_FOV_NARROW} or {@link AVKey#VIEW_FOV_WIDE}. + *

        + * Returns null if the object is not a view control associated with this layer.

        */ - public String getControlType(Object control) - { - if (control == null || !(control instanceof ScreenAnnotation)) + public String getControlType(Object control) { + if (control == null || !(control instanceof ScreenAnnotation)) { return null; + } - if (showPanControls && controlPan.equals(control)) + if (showPanControls && controlPan.equals(control)) { return AVKey.VIEW_PAN; - else if (showLookControls && controlLook.equals(control)) + } else if (showLookControls && controlLook.equals(control)) { return AVKey.VIEW_LOOK; - else if (showHeadingControls && controlHeadingLeft.equals(control)) + } else if (showHeadingControls && controlHeadingLeft.equals(control)) { return AVKey.VIEW_HEADING_LEFT; - else if (showHeadingControls && controlHeadingRight.equals(control)) + } else if (showHeadingControls && controlHeadingRight.equals(control)) { return AVKey.VIEW_HEADING_RIGHT; - else if (showZoomControls && controlZoomIn.equals(control)) + } else if (showZoomControls && controlZoomIn.equals(control)) { return AVKey.VIEW_ZOOM_IN; - else if (showZoomControls && controlZoomOut.equals(control)) + } else if (showZoomControls && controlZoomOut.equals(control)) { return AVKey.VIEW_ZOOM_OUT; - else if (showPitchControls && controlPitchUp.equals(control)) + } else if (showPitchControls && controlPitchUp.equals(control)) { return AVKey.VIEW_PITCH_UP; - else if (showPitchControls && controlPitchDown.equals(control)) + } else if (showPitchControls && controlPitchDown.equals(control)) { return AVKey.VIEW_PITCH_DOWN; - else if (showFovControls && controlFovNarrow.equals(control)) + } else if (showFovControls && controlFovNarrow.equals(control)) { return AVKey.VIEW_FOV_NARROW; - else if (showFovControls && controlFovWide.equals(control)) + } else if (showFovControls && controlFovWide.equals(control)) { return AVKey.VIEW_FOV_WIDE; - else if (showVeControls && controlVeUp.equals(control)) + } else if (showVeControls && controlVeUp.equals(control)) { return AVKey.VERTICAL_EXAGGERATION_UP; - else if (showVeControls && controlVeDown.equals(control)) + } else if (showVeControls && controlVeDown.equals(control)) { return AVKey.VERTICAL_EXAGGERATION_DOWN; + } return null; } @@ -420,8 +381,7 @@ else if (showVeControls && controlVeDown.equals(control)) * * @return the currently highlighted control, or null if no control is highlighted. */ - public Object getHighlightedObject() - { + public Object getHighlightedObject() { return this.currentControl; } @@ -430,48 +390,45 @@ public Object getHighlightedObject() * * @param control the control to highlight. */ - public void highlight(Object control) - { + public void highlight(Object control) { // Manage highlighting of controls. - if (this.currentControl == control) + if (this.currentControl == control) { return; // same thing selected - + } // Turn off highlight if on. - if (this.currentControl != null) - { + if (this.currentControl != null) { this.currentControl.getAttributes().setImageOpacity(-1); // use default opacity this.currentControl = null; } // Turn on highlight if object selected. - if (control != null && control instanceof ScreenAnnotation) - { + if (control != null && control instanceof ScreenAnnotation) { this.currentControl = (ScreenAnnotation) control; this.currentControl.getAttributes().setImageOpacity(1); } } @Override - public void doRender(DrawContext dc) - { - if (!this.initialized) + public void doRender(DrawContext dc) { + if (!this.initialized) { initialize(dc); + } - if (!this.referenceViewport.equals(dc.getView().getViewport())) + if (!this.referenceViewport.equals(dc.getView().getViewport())) { updatePositions(dc); + } super.doRender(dc); } - protected boolean isInitialized() - { + protected boolean isInitialized() { return initialized; } - protected void initialize(DrawContext dc) - { - if (this.initialized) + protected void initialize(DrawContext dc) { + if (this.initialized) { return; + } // Setup user interface - common default attributes AnnotationAttributes ca = new AnnotationAttributes(); @@ -486,8 +443,7 @@ protected void initialize(DrawContext dc) final String NOTEXT = ""; final Point ORIGIN = new Point(0, 0); - if (this.showPanControls) - { + if (this.showPanControls) { // Pan controlPan = new ScreenAnnotation(NOTEXT, ORIGIN, ca); controlPan.setValue(AVKey.VIEW_OPERATION, AVKey.VIEW_PAN); @@ -495,8 +451,7 @@ protected void initialize(DrawContext dc) controlPan.getAttributes().setSize(new Dimension(panSize, panSize)); this.addRenderable(controlPan); } - if (this.showLookControls) - { + if (this.showLookControls) { // Look controlLook = new ScreenAnnotation(NOTEXT, ORIGIN, ca); controlLook.setValue(AVKey.VIEW_OPERATION, AVKey.VIEW_LOOK); @@ -504,8 +459,7 @@ protected void initialize(DrawContext dc) controlLook.getAttributes().setSize(new Dimension(panSize, panSize)); this.addRenderable(controlLook); } - if (this.showZoomControls) - { + if (this.showZoomControls) { // Zoom controlZoomIn = new ScreenAnnotation(NOTEXT, ORIGIN, ca); controlZoomIn.setValue(AVKey.VIEW_OPERATION, AVKey.VIEW_ZOOM_IN); @@ -516,8 +470,7 @@ protected void initialize(DrawContext dc) controlZoomOut.getAttributes().setImageSource(getImageSource(AVKey.VIEW_ZOOM_OUT)); this.addRenderable(controlZoomOut); } - if (this.showHeadingControls) - { + if (this.showHeadingControls) { // Heading controlHeadingLeft = new ScreenAnnotation(NOTEXT, ORIGIN, ca); controlHeadingLeft.setValue(AVKey.VIEW_OPERATION, AVKey.VIEW_HEADING_LEFT); @@ -528,8 +481,7 @@ protected void initialize(DrawContext dc) controlHeadingRight.getAttributes().setImageSource(getImageSource(AVKey.VIEW_HEADING_RIGHT)); this.addRenderable(controlHeadingRight); } - if (this.showPitchControls) - { + if (this.showPitchControls) { // Pitch controlPitchUp = new ScreenAnnotation(NOTEXT, ORIGIN, ca); controlPitchUp.setValue(AVKey.VIEW_OPERATION, AVKey.VIEW_PITCH_UP); @@ -540,8 +492,7 @@ protected void initialize(DrawContext dc) controlPitchDown.getAttributes().setImageSource(getImageSource(AVKey.VIEW_PITCH_DOWN)); this.addRenderable(controlPitchDown); } - if (this.showFovControls) - { + if (this.showFovControls) { // Field of view FOV controlFovNarrow = new ScreenAnnotation(NOTEXT, ORIGIN, ca); controlFovNarrow.setValue(AVKey.VIEW_OPERATION, AVKey.VIEW_FOV_NARROW); @@ -552,8 +503,7 @@ protected void initialize(DrawContext dc) controlFovWide.getAttributes().setImageSource(getImageSource(AVKey.VIEW_FOV_WIDE)); this.addRenderable(controlFovWide); } - if (this.showVeControls) - { + if (this.showVeControls) { // Vertical Exaggeration controlVeUp = new ScreenAnnotation(NOTEXT, ORIGIN, ca); controlVeUp.setValue(AVKey.VIEW_OPERATION, AVKey.VERTICAL_EXAGGERATION_UP); @@ -581,57 +531,55 @@ protected void initialize(DrawContext dc) * * @return the image source associated with the given control type. */ - protected Object getImageSource(String control) - { - if (control.equals(AVKey.VIEW_PAN)) + protected Object getImageSource(String control) { + if (control.equals(AVKey.VIEW_PAN)) { return IMAGE_PAN; - else if (control.equals(AVKey.VIEW_LOOK)) + } else if (control.equals(AVKey.VIEW_LOOK)) { return IMAGE_LOOK; - else if (control.equals(AVKey.VIEW_HEADING_LEFT)) + } else if (control.equals(AVKey.VIEW_HEADING_LEFT)) { return IMAGE_HEADING_LEFT; - else if (control.equals(AVKey.VIEW_HEADING_RIGHT)) + } else if (control.equals(AVKey.VIEW_HEADING_RIGHT)) { return IMAGE_HEADING_RIGHT; - else if (control.equals(AVKey.VIEW_ZOOM_IN)) + } else if (control.equals(AVKey.VIEW_ZOOM_IN)) { return IMAGE_ZOOM_IN; - else if (control.equals(AVKey.VIEW_ZOOM_OUT)) + } else if (control.equals(AVKey.VIEW_ZOOM_OUT)) { return IMAGE_ZOOM_OUT; - else if (control.equals(AVKey.VIEW_PITCH_UP)) + } else if (control.equals(AVKey.VIEW_PITCH_UP)) { return IMAGE_PITCH_UP; - else if (control.equals(AVKey.VIEW_PITCH_DOWN)) + } else if (control.equals(AVKey.VIEW_PITCH_DOWN)) { return IMAGE_PITCH_DOWN; - else if (control.equals(AVKey.VIEW_FOV_WIDE)) + } else if (control.equals(AVKey.VIEW_FOV_WIDE)) { return IMAGE_FOV_WIDE; - else if (control.equals(AVKey.VIEW_FOV_NARROW)) + } else if (control.equals(AVKey.VIEW_FOV_NARROW)) { return IMAGE_FOV_NARROW; - else if (control.equals(AVKey.VERTICAL_EXAGGERATION_UP)) + } else if (control.equals(AVKey.VERTICAL_EXAGGERATION_UP)) { return IMAGE_VE_UP; - else if (control.equals(AVKey.VERTICAL_EXAGGERATION_DOWN)) + } else if (control.equals(AVKey.VERTICAL_EXAGGERATION_DOWN)) { return IMAGE_VE_DOWN; + } return null; } // Set controls positions according to layout and viewport dimension - protected void updatePositions(DrawContext dc) - { + protected void updatePositions(DrawContext dc) { boolean horizontalLayout = this.layout.equals(AVKey.HORIZONTAL); // horizontal layout: pan button + look button beside 2 rows of 4 buttons - int width = (showPanControls ? panSize : 0) + - (showLookControls ? panSize : 0) + - (showZoomControls ? buttonSize : 0) + - (showHeadingControls ? buttonSize : 0) + - (showPitchControls ? buttonSize : 0) + - (showFovControls ? buttonSize : 0) + - (showVeControls ? buttonSize : 0); + int width = (showPanControls ? panSize : 0) + + (showLookControls ? panSize : 0) + + (showZoomControls ? buttonSize : 0) + + (showHeadingControls ? buttonSize : 0) + + (showPitchControls ? buttonSize : 0) + + (showFovControls ? buttonSize : 0) + + (showVeControls ? buttonSize : 0); int height = Math.max(panSize, buttonSize * 2); width = (int) (width * scale); height = (int) (height * scale); int xOffset = 0; int yOffset = (int) (buttonSize * scale); - if (!horizontalLayout) - { + if (!horizontalLayout) { // vertical layout: pan button above look button above 4 rows of 2 buttons int temp = height; //noinspection SuspiciousNameCombination @@ -651,66 +599,73 @@ protected void updatePositions(DrawContext dc) int x = locationSW.x; int y = horizontalLayout ? locationSW.y : locationSW.y + height; - if (this.showPanControls) - { - if (!horizontalLayout) + if (this.showPanControls) { + if (!horizontalLayout) { y -= (int) (panSize * scale); + } controlPan.setScreenPoint(new Point(x + halfPanSize, y)); - if (horizontalLayout) + if (horizontalLayout) { x += (int) (panSize * scale); + } } - if (this.showLookControls) - { - if (!horizontalLayout) + if (this.showLookControls) { + if (!horizontalLayout) { y -= (int) (panSize * scale); + } controlLook.setScreenPoint(new Point(x + halfPanSize, y)); - if (horizontalLayout) + if (horizontalLayout) { x += (int) (panSize * scale); + } } - if (this.showZoomControls) - { - if (!horizontalLayout) + if (this.showZoomControls) { + if (!horizontalLayout) { y -= (int) (buttonSize * scale); + } controlZoomIn.setScreenPoint(new Point(x + halfButtonSize + xOffset, y + yOffset)); controlZoomOut.setScreenPoint(new Point(x + halfButtonSize, y)); - if (horizontalLayout) + if (horizontalLayout) { x += (int) (buttonSize * scale); + } } - if (this.showHeadingControls) - { - if (!horizontalLayout) + if (this.showHeadingControls) { + if (!horizontalLayout) { y -= (int) (buttonSize * scale); + } controlHeadingLeft.setScreenPoint(new Point(x + halfButtonSize + xOffset, y + yOffset)); controlHeadingRight.setScreenPoint(new Point(x + halfButtonSize, y)); - if (horizontalLayout) + if (horizontalLayout) { x += (int) (buttonSize * scale); + } } - if (this.showPitchControls) - { - if (!horizontalLayout) + if (this.showPitchControls) { + if (!horizontalLayout) { y -= (int) (buttonSize * scale); + } controlPitchUp.setScreenPoint(new Point(x + halfButtonSize + xOffset, y + yOffset)); controlPitchDown.setScreenPoint(new Point(x + halfButtonSize, y)); - if (horizontalLayout) + if (horizontalLayout) { x += (int) (buttonSize * scale); + } } - if (this.showFovControls) - { - if (!horizontalLayout) + if (this.showFovControls) { + if (!horizontalLayout) { y -= (int) (buttonSize * scale); + } controlFovNarrow.setScreenPoint(new Point(x + halfButtonSize + xOffset, y + yOffset)); controlFovWide.setScreenPoint(new Point(x + halfButtonSize, y)); - if (horizontalLayout) + if (horizontalLayout) { x += (int) (buttonSize * scale); + } } - if (this.showVeControls) - { - if (!horizontalLayout) + if (this.showVeControls) { + if (!horizontalLayout) { y -= (int) (buttonSize * scale); + } controlVeUp.setScreenPoint(new Point(x + halfButtonSize + xOffset, y + yOffset)); controlVeDown.setScreenPoint(new Point(x + halfButtonSize, y)); - if (horizontalLayout) + if (horizontalLayout) { x += (int) (buttonSize * scale); + } } this.referenceViewport = dc.getView().getViewport(); @@ -725,44 +680,32 @@ protected void updatePositions(DrawContext dc) * * @return the screen location of the bottom left corner - south west corner. */ - protected Point computeLocation(Rectangle viewport, Rectangle controls) - { + protected Point computeLocation(Rectangle viewport, Rectangle controls) { double x; double y; - if (this.locationCenter != null) - { + if (this.locationCenter != null) { x = this.locationCenter.x - controls.width / 2; y = this.locationCenter.y - controls.height / 2; - } - else if (this.position.equals(AVKey.NORTHEAST)) - { + } else if (this.position.equals(AVKey.NORTHEAST)) { x = viewport.getWidth() - controls.width - this.borderWidth; y = viewport.getHeight() - controls.height - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHEAST)) - { + } else if (this.position.equals(AVKey.SOUTHEAST)) { x = viewport.getWidth() - controls.width - this.borderWidth; y = 0d + this.borderWidth; - } - else if (this.position.equals(AVKey.NORTHWEST)) - { + } else if (this.position.equals(AVKey.NORTHWEST)) { x = 0d + this.borderWidth; y = viewport.getHeight() - controls.height - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHWEST)) - { + } else if (this.position.equals(AVKey.SOUTHWEST)) { x = 0d + this.borderWidth; y = 0d + this.borderWidth; - } - else // use North East as default + } else // use North East as default { x = viewport.getWidth() - controls.width - this.borderWidth; y = viewport.getHeight() - controls.height - this.borderWidth; } - if (this.locationOffset != null) - { + if (this.locationOffset != null) { x += this.locationOffset.x; y += this.locationOffset.y; } @@ -770,8 +713,7 @@ else if (this.position.equals(AVKey.SOUTHWEST)) return new Point((int) x, (int) y); } - protected void clearControls() - { + protected void clearControls() { this.removeAllRenderables(); this.controlPan = null; @@ -791,8 +733,7 @@ protected void clearControls() } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.ViewControlsLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/ViewControlsSelectListener.java b/src/gov/nasa/worldwind/layers/ViewControlsSelectListener.java index 2a4f274717..6f1ef31c62 100644 --- a/src/gov/nasa/worldwind/layers/ViewControlsSelectListener.java +++ b/src/gov/nasa/worldwind/layers/ViewControlsSelectListener.java @@ -25,8 +25,8 @@ * @version $Id: ViewControlsSelectListener.java 1876 2014-03-19 17:13:30Z tgaskins $ * @see ViewControlsLayer */ -public class ViewControlsSelectListener implements SelectListener -{ +public class ViewControlsSelectListener implements SelectListener { + protected static final int DEFAULT_TIMER_DELAY = 50; protected WorldWindow wwd; @@ -50,19 +50,16 @@ public class ViewControlsSelectListener implements SelectListener * ViewControlLayers are not sharable among WorldWindows. A separate layer and controller * must be established for each window that's to have view controls. * - * @param wwd the WorldWindow the specified layer is associated with. + * @param wwd the WorldWindow the specified layer is associated with. * @param layer the layer to control. */ - public ViewControlsSelectListener(WorldWindow wwd, ViewControlsLayer layer) - { - if (wwd == null) - { + public ViewControlsSelectListener(WorldWindow wwd, ViewControlsLayer layer) { + if (wwd == null) { String msg = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (layer == null) - { + if (layer == null) { String msg = Logging.getMessage("nullValue.LayerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -72,12 +69,11 @@ public ViewControlsSelectListener(WorldWindow wwd, ViewControlsLayer layer) this.viewControlsLayer = layer; // Setup repeat timer - this.repeatTimer = new Timer(DEFAULT_TIMER_DELAY, new ActionListener() - { - public void actionPerformed(ActionEvent event) - { - if (pressedControl != null) + this.repeatTimer = new Timer(DEFAULT_TIMER_DELAY, new ActionListener() { + public void actionPerformed(ActionEvent event) { + if (pressedControl != null) { updateView(pressedControl, pressedControlType); + } } }); this.repeatTimer.start(); @@ -90,10 +86,8 @@ public void actionPerformed(ActionEvent event) * * @throws IllegalArgumentException if delay is less than or equal to zero. */ - public void setRepeatTimerDelay(int delay) - { - if (delay <= 0) - { + public void setRepeatTimerDelay(int delay) { + if (delay <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", delay); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -106,8 +100,7 @@ public void setRepeatTimerDelay(int delay) * * @return the repeat timer delay in milliseconds. */ - public int getRepeatTimerDelay() - { + public int getRepeatTimerDelay() { return this.repeatTimer.getDelay(); } @@ -117,8 +110,7 @@ public int getRepeatTimerDelay() * * @param value the panning distance factor. */ - public void setPanIncrement(double value) - { + public void setPanIncrement(double value) { this.panStep = value; } @@ -127,8 +119,7 @@ public void setPanIncrement(double value) * * @return the panning distance factor. */ - public double getPanIncrement() - { + public double getPanIncrement() { return this.panStep; } @@ -138,8 +129,7 @@ public double getPanIncrement() * * @param value the zooming distance factor. */ - public void setZoomIncrement(double value) - { + public void setZoomIncrement(double value) { this.zoomStep = value; } @@ -148,8 +138,7 @@ public void setZoomIncrement(double value) * * @return the zooming distance factor. */ - public double getZoomIncrement() - { + public double getZoomIncrement() { return this.zoomStep; } @@ -159,8 +148,7 @@ public double getZoomIncrement() * * @param value the heading increment value in decimal degrees. */ - public void setHeadingIncrement(double value) - { + public void setHeadingIncrement(double value) { this.headingStep = value; } @@ -169,8 +157,7 @@ public void setHeadingIncrement(double value) * * @return the heading increment value in decimal degrees. */ - public double getHeadingIncrement() - { + public double getHeadingIncrement() { return this.headingStep; } @@ -182,10 +169,8 @@ public double getHeadingIncrement() * * @throws IllegalArgumentException if value is < zero. */ - public void setPitchIncrement(double value) - { - if (value < 0) - { + public void setPitchIncrement(double value) { + if (value < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", value); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -198,8 +183,7 @@ public void setPitchIncrement(double value) * * @return the pitch increment value in decimal degrees. */ - public double getPitchIncrement() - { + public double getPitchIncrement() { return this.pitchStep; } @@ -211,10 +195,8 @@ public double getPitchIncrement() * * @throws IllegalArgumentException if value < 1; */ - public void setFovIncrement(double value) - { - if (value < 1) - { + public void setFovIncrement(double value) { + if (value < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", value); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -227,8 +209,7 @@ public void setFovIncrement(double value) * * @return the field of view increment factor. */ - public double getFovIncrement() - { + public double getFovIncrement() { return this.fovStep; } @@ -240,10 +221,8 @@ public double getFovIncrement() * * @throws IllegalArgumentException if value < 0. */ - public void setVeIncrement(double value) - { - if (value < 0) - { + public void setVeIncrement(double value) { + if (value < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", value); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -256,79 +235,75 @@ public void setVeIncrement(double value) * * @return the vertical exaggeration increment. */ - public double getVeIncrement() - { + public double getVeIncrement() { return this.veStep; } - public void selected(SelectEvent event) - { - if (this.wwd == null) + public void selected(SelectEvent event) { + if (this.wwd == null) { return; + } - if (!(this.wwd.getView() instanceof OrbitView)) + if (!(this.wwd.getView() instanceof OrbitView)) { return; + } OrbitView view = (OrbitView) this.wwd.getView(); - if (this.viewControlsLayer.getHighlightedObject() != null) - { + if (this.viewControlsLayer.getHighlightedObject() != null) { this.viewControlsLayer.highlight(null); this.wwd.redraw(); // must redraw so the de-highlight can take effect } - if (event.getMouseEvent() != null && event.getMouseEvent().isConsumed()) + if (event.getMouseEvent() != null && event.getMouseEvent().isConsumed()) { return; + } if (event.getTopObject() == null || event.getTopPickedObject().getParentLayer() != this.getParentLayer() - || !(event.getTopObject() instanceof AVList)) + || !(event.getTopObject() instanceof AVList)) { return; + } String controlType = ((AVList) event.getTopObject()).getStringValue(AVKey.VIEW_OPERATION); - if (controlType == null) + if (controlType == null) { return; + } ScreenAnnotation selectedObject = (ScreenAnnotation) event.getTopObject(); this.lastPickPoint = event.getPickPoint(); - if (event.getEventAction().equals(SelectEvent.ROLLOVER)) - { + if (event.getEventAction().equals(SelectEvent.ROLLOVER)) { // Highlight on rollover this.viewControlsLayer.highlight(selectedObject); this.wwd.redraw(); } - if (event.getEventAction().equals(SelectEvent.DRAG)) - { + if (event.getEventAction().equals(SelectEvent.DRAG)) { // just consume drag events event.consume(); - } - else if (event.getEventAction().equals(SelectEvent.HOVER)) - { + } else if (event.getEventAction().equals(SelectEvent.HOVER)) { // Highlight on hover this.viewControlsLayer.highlight(selectedObject); this.wwd.redraw(); - } - else if (event.getEventAction().equals(SelectEvent.LEFT_PRESS) || - (event.getEventAction().equals(SelectEvent.DRAG) && controlType.equals(AVKey.VIEW_PAN)) || - (event.getEventAction().equals(SelectEvent.DRAG) && controlType.equals(AVKey.VIEW_LOOK))) - { + } else if (event.getEventAction().equals(SelectEvent.LEFT_PRESS) + || (event.getEventAction().equals(SelectEvent.DRAG) && controlType.equals(AVKey.VIEW_PAN)) + || (event.getEventAction().equals(SelectEvent.DRAG) && controlType.equals(AVKey.VIEW_LOOK))) { // Handle left press on controls this.pressedControl = selectedObject; this.pressedControlType = controlType; // Consume drag events, but do not consume left press events. It is not necessary to consume left press // events here, and doing so prevents the WorldWindow from gaining focus. - if (event.getEventAction().equals(SelectEvent.DRAG)) + if (event.getEventAction().equals(SelectEvent.DRAG)) { event.consume(); - } - else if (event.getEventAction().equals(SelectEvent.LEFT_CLICK) - || event.getEventAction().equals(SelectEvent.LEFT_DOUBLE_CLICK) - || event.getEventAction().equals(SelectEvent.DRAG_END)) - { + } + } else if (event.getEventAction().equals(SelectEvent.LEFT_CLICK) + || event.getEventAction().equals(SelectEvent.LEFT_DOUBLE_CLICK) + || event.getEventAction().equals(SelectEvent.DRAG_END)) { // Release pressed control - if (pressedControl != null) + if (pressedControl != null) { event.consume(); + } this.pressedControl = null; resetOrbitView(view); @@ -336,8 +311,7 @@ else if (event.getEventAction().equals(SelectEvent.LEFT_CLICK) } // Keep pressed control highlighted - overrides rollover non currently pressed controls - if (this.pressedControl != null) - { + if (this.pressedControl != null) { this.viewControlsLayer.highlight(this.pressedControl); this.wwd.redraw(); } @@ -349,45 +323,42 @@ else if (event.getEventAction().equals(SelectEvent.LEFT_CLICK) * * @return this ViewControlsSelectListener's parent layer. */ - protected Layer getParentLayer() - { + protected Layer getParentLayer() { return this.viewControlsLayer; } - protected void updateView(ScreenAnnotation control, String controlType) - { - if (this.wwd == null) + protected void updateView(ScreenAnnotation control, String controlType) { + if (this.wwd == null) { return; - if (!(this.wwd.getView() instanceof OrbitView)) + } + if (!(this.wwd.getView() instanceof OrbitView)) { return; + } OrbitView view = (OrbitView) this.wwd.getView(); view.stopAnimations(); view.stopMovement(); - if (controlType.equals(AVKey.VIEW_PAN)) - { + if (controlType.equals(AVKey.VIEW_PAN)) { resetOrbitView(view); // Go some distance in the control mouse direction Angle heading = computePanHeading(view, control); Angle distance = computePanAmount(this.wwd.getModel().getGlobe(), view, control, panStep); LatLon newViewCenter = LatLon.greatCircleEndPosition(view.getCenterPosition(), - heading, distance); + heading, distance); // Turn around if passing by a pole - TODO: better handling of the pole crossing situation - if (this.isPathCrossingAPole(newViewCenter, view.getCenterPosition())) + if (this.isPathCrossingAPole(newViewCenter, view.getCenterPosition())) { view.setHeading(Angle.POS180.subtract(view.getHeading())); + } // Set new center pos view.setCenterPosition(new Position(newViewCenter, view.getCenterPosition().getElevation())); - } - else if (controlType.equals(AVKey.VIEW_LOOK)) - { + } else if (controlType.equals(AVKey.VIEW_LOOK)) { setupFirstPersonView(view); Angle heading = computeLookHeading(view, control, headingStep); Angle pitch = computeLookPitch(view, control, pitchStep); // Check whether the view will still point at terrain Vec4 surfacePoint = computeSurfacePoint(view, heading, pitch); - if (surfacePoint != null) - { + if (surfacePoint != null) { // Change view state final Position eyePos = view.getEyePosition();// Save current eye position view.setHeading(heading); @@ -395,70 +366,52 @@ else if (controlType.equals(AVKey.VIEW_LOOK)) view.setZoom(0); view.setCenterPosition(eyePos); // Set center at the eye position } - } - else if (controlType.equals(AVKey.VIEW_ZOOM_IN)) - { + } else if (controlType.equals(AVKey.VIEW_ZOOM_IN)) { resetOrbitView(view); view.setZoom(computeNewZoom(view, -zoomStep)); - } - else if (controlType.equals(AVKey.VIEW_ZOOM_OUT)) - { + } else if (controlType.equals(AVKey.VIEW_ZOOM_OUT)) { resetOrbitView(view); view.setZoom(computeNewZoom(view, zoomStep)); - } - else if (controlType.equals(AVKey.VIEW_HEADING_LEFT)) - { + } else if (controlType.equals(AVKey.VIEW_HEADING_LEFT)) { resetOrbitView(view); view.setHeading(view.getHeading().addDegrees(headingStep)); - } - else if (controlType.equals(AVKey.VIEW_HEADING_RIGHT)) - { + } else if (controlType.equals(AVKey.VIEW_HEADING_RIGHT)) { resetOrbitView(view); view.setHeading(view.getHeading().addDegrees(-headingStep)); - } - else if (controlType.equals(AVKey.VIEW_PITCH_UP)) - { + } else if (controlType.equals(AVKey.VIEW_PITCH_UP)) { resetOrbitView(view); - if (view.getPitch().degrees >= pitchStep) + if (view.getPitch().degrees >= pitchStep) { view.setPitch(view.getPitch().addDegrees(-pitchStep)); - } - else if (controlType.equals(AVKey.VIEW_PITCH_DOWN)) - { + } + } else if (controlType.equals(AVKey.VIEW_PITCH_DOWN)) { resetOrbitView(view); - if (view.getPitch().degrees <= 90 - pitchStep) + if (view.getPitch().degrees <= 90 - pitchStep) { view.setPitch(view.getPitch().addDegrees(pitchStep)); - } - else if (controlType.equals(AVKey.VIEW_FOV_NARROW)) - { - if (view.getFieldOfView().degrees / fovStep >= 4) + } + } else if (controlType.equals(AVKey.VIEW_FOV_NARROW)) { + if (view.getFieldOfView().degrees / fovStep >= 4) { view.setFieldOfView(view.getFieldOfView().divide(fovStep)); - } - else if (controlType.equals(AVKey.VIEW_FOV_WIDE)) - { - if (view.getFieldOfView().degrees * fovStep < 120) + } + } else if (controlType.equals(AVKey.VIEW_FOV_WIDE)) { + if (view.getFieldOfView().degrees * fovStep < 120) { view.setFieldOfView(view.getFieldOfView().multiply(fovStep)); - } - else if (controlType.equals(AVKey.VERTICAL_EXAGGERATION_UP)) - { + } + } else if (controlType.equals(AVKey.VERTICAL_EXAGGERATION_UP)) { SceneController sc = this.wwd.getSceneController(); sc.setVerticalExaggeration(sc.getVerticalExaggeration() + this.veStep); - } - else if (controlType.equals(AVKey.VERTICAL_EXAGGERATION_DOWN)) - { + } else if (controlType.equals(AVKey.VERTICAL_EXAGGERATION_DOWN)) { SceneController sc = this.wwd.getSceneController(); sc.setVerticalExaggeration(Math.max(1d, sc.getVerticalExaggeration() - this.veStep)); } view.firePropertyChange(AVKey.VIEW, null, view); } - protected boolean isPathCrossingAPole(LatLon p1, LatLon p2) - { + protected boolean isPathCrossingAPole(LatLon p1, LatLon p2) { return Math.abs(p1.getLongitude().degrees - p2.getLongitude().degrees) > 20 - && Math.abs(p1.getLatitude().degrees - 90 * Math.signum(p1.getLatitude().degrees)) < 10; + && Math.abs(p1.getLatitude().degrees - 90 * Math.signum(p1.getLatitude().degrees)) < 10; } - protected double computeNewZoom(OrbitView view, double amount) - { + protected double computeNewZoom(OrbitView view, double amount) { double coeff = 0.05; double change = coeff * amount; double logZoom = view.getZoom() != 0 ? Math.log(view.getZoom()) : 0; @@ -468,8 +421,7 @@ protected double computeNewZoom(OrbitView view, double amount) return Math.exp(logZoom + change); } - protected Angle computePanHeading(OrbitView view, ScreenAnnotation control) - { + protected Angle computePanHeading(OrbitView view, ScreenAnnotation control) { // Compute last pick point 'heading' relative to pan control center double size = control.getAttributes().getSize().width * control.getAttributes().getScale(); Vec4 center = new Vec4(control.getScreenPoint().x, control.getScreenPoint().y + size / 2, 0); @@ -480,8 +432,7 @@ protected Angle computePanHeading(OrbitView view, ScreenAnnotation control) return heading; } - protected Angle computePanAmount(Globe globe, OrbitView view, ScreenAnnotation control, double panStep) - { + protected Angle computePanAmount(Globe globe, OrbitView view, ScreenAnnotation control, double panStep) { // Compute last pick point distance relative to pan control center double size = control.getAttributes().getSize().width * control.getAttributes().getScale(); Vec4 center = new Vec4(control.getScreenPoint().x, control.getScreenPoint().y + size / 2, 0); @@ -507,8 +458,7 @@ protected Angle computePanAmount(Globe globe, OrbitView view, ScreenAnnotation c return Angle.fromDegrees(value * pickDistanceFactor * panStep); } - protected Angle computeLookHeading(OrbitView view, ScreenAnnotation control, double headingStep) - { + protected Angle computeLookHeading(OrbitView view, ScreenAnnotation control, double headingStep) { // Compute last pick point 'heading' relative to look control center on x double size = control.getAttributes().getSize().width * control.getAttributes().getScale(); Vec4 center = new Vec4(control.getScreenPoint().x, control.getScreenPoint().y + size / 2, 0); @@ -520,8 +470,7 @@ protected Angle computeLookHeading(OrbitView view, ScreenAnnotation control, dou return heading; } - protected Angle computeLookPitch(OrbitView view, ScreenAnnotation control, double pitchStep) - { + protected Angle computeLookPitch(OrbitView view, ScreenAnnotation control, double pitchStep) { // Compute last pick point 'pitch' relative to look control center on y double size = control.getAttributes().getSize().width * control.getAttributes().getScale(); Vec4 center = new Vec4(control.getScreenPoint().x, control.getScreenPoint().y + size / 2, 0); @@ -538,25 +487,25 @@ protected Angle computeLookPitch(OrbitView view, ScreenAnnotation control, doubl * * @param view the orbit view to reset */ - protected void resetOrbitView(OrbitView view) - { - if (view.getZoom() > 0) // already in orbit view mode + protected void resetOrbitView(OrbitView view) { + if (view.getZoom() > 0) // already in orbit view mode + { return; + } // Find out where on the terrain the eye is looking at in the viewport center // TODO: if no terrain is found in the viewport center, iterate toward viewport bottom until it is found Vec4 centerPoint = computeSurfacePoint(view, view.getHeading(), view.getPitch()); // Reset the orbit view center point heading, pitch and zoom - if (centerPoint != null) - { + if (centerPoint != null) { Vec4 eyePoint = view.getEyePoint(); // Center pos on terrain surface Position centerPosition = wwd.getModel().getGlobe().computePositionFromPoint(centerPoint); // Compute pitch and heading relative to center position Vec4 normal = wwd.getModel().getGlobe().computeSurfaceNormalAtLocation(centerPosition.getLatitude(), - centerPosition.getLongitude()); + centerPosition.getLongitude()); Vec4 north = wwd.getModel().getGlobe().computeNorthPointingTangentAtLocation(centerPosition.getLatitude(), - centerPosition.getLongitude()); + centerPosition.getLongitude()); // Pitch view.setPitch(Angle.POS180.subtract(view.getForwardVector().angleBetween3(normal))); // Heading @@ -576,19 +525,20 @@ protected void resetOrbitView(OrbitView view) * * @param view the orbit view to set into a first person view. */ - protected void setupFirstPersonView(OrbitView view) - { - if (view.getZoom() == 0) // already in first person mode + protected void setupFirstPersonView(OrbitView view) { + if (view.getZoom() == 0) // already in first person mode + { return; + } Vec4 eyePoint = view.getEyePoint(); // Center pos at eye pos Position centerPosition = wwd.getModel().getGlobe().computePositionFromPoint(eyePoint); // Compute pitch and heading relative to center position Vec4 normal = wwd.getModel().getGlobe().computeSurfaceNormalAtLocation(centerPosition.getLatitude(), - centerPosition.getLongitude()); + centerPosition.getLongitude()); Vec4 north = wwd.getModel().getGlobe().computeNorthPointingTangentAtLocation(centerPosition.getLatitude(), - centerPosition.getLongitude()); + centerPosition.getLongitude()); // Pitch view.setPitch(Angle.POS180.subtract(view.getForwardVector().angleBetween3(normal))); // Heading @@ -605,14 +555,13 @@ protected void setupFirstPersonView(OrbitView view) /** * Find out where on the terrain surface the eye would be looking at with the given heading and pitch angles. * - * @param view the orbit view + * @param view the orbit view * @param heading heading direction clockwise from north. - * @param pitch view pitch angle from the surface normal at the center point. + * @param pitch view pitch angle from the surface normal at the center point. * * @return the terrain surface point the view would be looking at in the viewport center. */ - protected Vec4 computeSurfacePoint(OrbitView view, Angle heading, Angle pitch) - { + protected Vec4 computeSurfacePoint(OrbitView view, Angle heading, Angle pitch) { Globe globe = wwd.getModel().getGlobe(); // Compute transform to be applied to north pointing Y so that it would point in the view direction // Move coordinate system to view center point @@ -624,7 +573,7 @@ protected Vec4 computeSurfacePoint(OrbitView view, Angle heading, Angle pitch) Vec4 forward = Vec4.UNIT_Y.transformBy4(transform); // Return intersection with terrain Intersection[] intersections = wwd.getSceneController().getTerrain().intersect( - new Line(view.getEyePoint(), forward)); + new Line(view.getEyePoint(), forward)); return (intersections != null && intersections.length != 0) ? intersections[0].getIntersectionPoint() : null; } } diff --git a/src/gov/nasa/worldwind/layers/WorldMapLayer.java b/src/gov/nasa/worldwind/layers/WorldMapLayer.java index aa5dc3b1b0..62a5d0fca7 100644 --- a/src/gov/nasa/worldwind/layers/WorldMapLayer.java +++ b/src/gov/nasa/worldwind/layers/WorldMapLayer.java @@ -31,8 +31,8 @@ * @author Patrick Murris * @version $Id: WorldMapLayer.java 2230 2014-08-14 18:19:48Z tgaskins $ */ -public class WorldMapLayer extends AbstractLayer -{ +public class WorldMapLayer extends AbstractLayer { + protected String iconFilePath; protected double toViewportScale = 0.2; protected double iconScale = 0.5; @@ -54,27 +54,25 @@ public class WorldMapLayer extends AbstractLayer // Draw it as ordered with an eye distance of 0 so that it shows up in front of most other things. protected OrderedIcon orderedImage = new OrderedIcon(); - protected class OrderedIcon implements OrderedRenderable - { - public double getDistanceFromEye() - { + protected class OrderedIcon implements OrderedRenderable { + + public double getDistanceFromEye() { return 0; } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { WorldMapLayer.this.drawIcon(dc); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { WorldMapLayer.this.drawIcon(dc); } } - /** Displays a world map overlay with a current position crosshair in a screen corner */ - public WorldMapLayer() - { + /** + * Displays a world map overlay with a current position crosshair in a screen corner + */ + public WorldMapLayer() { this.setOpacity(0.6); this.setIconFilePath(Configuration.getStringValue(AVKey.WORLD_MAP_IMAGE_PATH)); } @@ -84,21 +82,18 @@ public WorldMapLayer() * * @param iconFilePath the world map image path and filename */ - public WorldMapLayer(String iconFilePath) - { + public WorldMapLayer(String iconFilePath) { this.setOpacity(0.6); this.setIconFilePath(iconFilePath); } // Public properties - /** * Returns the layer's current icon file path. * * @return the icon file path */ - public String getIconFilePath() - { + public String getIconFilePath() { return iconFilePath; } @@ -109,10 +104,8 @@ public String getIconFilePath() * * @param iconFilePath the path to the icon's image file */ - public void setIconFilePath(String iconFilePath) - { - if (iconFilePath == null || iconFilePath.length() == 0) - { + public void setIconFilePath(String iconFilePath) { + if (iconFilePath == null || iconFilePath.length() == 0) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -125,8 +118,7 @@ public void setIconFilePath(String iconFilePath) * * @return the world map-to-viewport scale factor */ - public double getToViewportScale() - { + public double getToViewportScale() { return toViewportScale; } @@ -138,8 +130,7 @@ public double getToViewportScale() * * @param toViewportScale the world map to viewport scale factor */ - public void setToViewportScale(double toViewportScale) - { + public void setToViewportScale(double toViewportScale) { this.toViewportScale = toViewportScale; } @@ -148,8 +139,7 @@ public void setToViewportScale(double toViewportScale) * * @return the current icon scale */ - public double getIconScale() - { + public double getIconScale() { return iconScale; } @@ -161,8 +151,7 @@ public double getIconScale() * * @param iconScale the icon scale factor */ - public void setIconScale(double iconScale) - { + public void setIconScale(double iconScale) { this.iconScale = iconScale; } @@ -171,8 +160,7 @@ public void setIconScale(double iconScale) * * @return the icon's resize behavior */ - public String getResizeBehavior() - { + public String getResizeBehavior() { return resizeBehavior; } @@ -188,13 +176,11 @@ public String getResizeBehavior() * * @param resizeBehavior the desired resize behavior */ - public void setResizeBehavior(String resizeBehavior) - { + public void setResizeBehavior(String resizeBehavior) { this.resizeBehavior = resizeBehavior; } - public int getBorderWidth() - { + public int getBorderWidth() { return borderWidth; } @@ -204,8 +190,7 @@ public int getBorderWidth() * @param borderWidth the number of pixels to offset the world map icon from the borders indicated by {@link * #setPosition(String)}. */ - public void setBorderWidth(int borderWidth) - { + public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; } @@ -214,8 +199,7 @@ public void setBorderWidth(int borderWidth) * * @return the current world map position */ - public String getPosition() - { + public String getPosition() { return position; } @@ -225,10 +209,8 @@ public String getPosition() * * @param position the desired world map position */ - public void setPosition(String position) - { - if (position == null) - { + public void setPosition(String position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -241,8 +223,7 @@ public void setPosition(String position) * * @return the current location center. May be null. */ - public Vec4 getLocationCenter() - { + public Vec4 getLocationCenter() { return locationCenter; } @@ -257,8 +238,7 @@ public Vec4 getLocationCenter() * * @see #locationCenter the screen location at which to place the map. */ - public void setLocationCenter(Vec4 locationCenter) - { + public void setLocationCenter(Vec4 locationCenter) { this.locationCenter = locationCenter; } @@ -267,8 +247,7 @@ public void setLocationCenter(Vec4 locationCenter) * * @return the location offset. Will be null if no offset has been specified. */ - public Vec4 getLocationOffset() - { + public Vec4 getLocationOffset() { return locationOffset; } @@ -276,26 +255,22 @@ public Vec4 getLocationOffset() * Specifies a placement offset from the worldmap's position on the screen. * * @param locationOffset the number of pixels to shift the worldmap image from its specified screen position. A - * positive X value shifts the image to the right. A positive Y value shifts the image up. If - * null, no offset is applied. The default offset is null. + * positive X value shifts the image to the right. A positive Y value shifts the image up. If null, no offset is + * applied. The default offset is null. * * @see #setLocationCenter(gov.nasa.worldwind.geom.Vec4) * @see #setPosition(String) */ - public void setLocationOffset(Vec4 locationOffset) - { + public void setLocationOffset(Vec4 locationOffset) { this.locationOffset = locationOffset; } - public Color getBackgrounColor() - { + public Color getBackgrounColor() { return this.backColor; } - public void setBackgroundColor(Color color) - { - if (color == null) - { + public void setBackgroundColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -303,33 +278,29 @@ public void setBackgroundColor(Color color) this.backColor = color; } - public boolean getShowFootprint() - { + public boolean getShowFootprint() { return this.showFootprint; } - public void setShowFootprint(boolean state) - { + public void setShowFootprint(boolean state) { this.showFootprint = state; } /** - * Get the current view footprint position list. May be null if no footprint is displayed or none has been - * computed. + * Get the current view footprint position list. May be null if no footprint is displayed or none has been computed. * * @return the current view footprint position list - may be null. */ - public java.util.List getFootPrintPositions() - { + public java.util.List getFootPrintPositions() { return this.footPrintPositions; } @Override - public void doRender(DrawContext dc) - { + public void doRender(DrawContext dc) { // Ensure that this shape isn't added to the ordered renderable list more than once per frame. - if (dc.isContinuous2DGlobe() && this.frameStampForDrawing == dc.getFrameTimeStamp()) + if (dc.isContinuous2DGlobe() && this.frameStampForDrawing == dc.getFrameTimeStamp()) { return; + } // Delegate drawing to the ordered renderable list dc.addOrderedRenderable(this.orderedImage); @@ -338,11 +309,11 @@ public void doRender(DrawContext dc) } @Override - public void doPick(DrawContext dc, Point pickPoint) - { + public void doPick(DrawContext dc, Point pickPoint) { // Ensure that this shape isn't added to the ordered renderable list more than once per frame. - if (dc.isContinuous2DGlobe() && this.frameStampForPicking == dc.getFrameTimeStamp()) + if (dc.isContinuous2DGlobe() && this.frameStampForPicking == dc.getFrameTimeStamp()) { return; + } // Delegate drawing to the ordered renderable list dc.addOrderedRenderable(this.orderedImage); @@ -350,24 +321,21 @@ public void doPick(DrawContext dc, Point pickPoint) this.frameStampForPicking = dc.getFrameTimeStamp(); } - protected void drawIcon(DrawContext dc) - { - if (this.getIconFilePath() == null) + protected void drawIcon(DrawContext dc) { + if (this.getIconFilePath() == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { // Initialize texture if necessary Texture iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture == null) - { + if (iconTexture == null) { this.initializeTexture(dc); iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture == null) - { + if (iconTexture == null) { String msg = Logging.getMessage("generic.ImageReadFailed"); Logging.logger().finer(msg); return; @@ -399,14 +367,13 @@ protected void drawIcon(DrawContext dc) gl.glScaled(scale, scale, 1); gl.glScaled(width, height, 1d); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); // Draw background color behind the map gl.glColor4ub((byte) this.backColor.getRed(), (byte) this.backColor.getGreen(), - (byte) this.backColor.getBlue(), (byte) (this.backColor.getAlpha() * this.getOpacity())); + (byte) this.backColor.getBlue(), (byte) (this.backColor.getAlpha() * this.getOpacity())); dc.drawUnitQuad(); // Draw world map icon @@ -430,8 +397,7 @@ protected void drawIcon(DrawContext dc) // Draw crosshair Position groundPos = this.computeGroundPosition(dc, dc.getView()); - if (groundPos != null) - { + if (groundPos != null) { int x = (int) (width * (groundPos.getLongitude().degrees + 180) / 360); int y = (int) (height * (groundPos.getLatitude().degrees + 90) / 180); int w = 10; // cross branch length @@ -447,20 +413,16 @@ protected void drawIcon(DrawContext dc) } // Draw view footprint in map icon space - if (!dc.is2DGlobe() && this.showFootprint) - { + if (!dc.is2DGlobe() && this.showFootprint) { this.footPrintPositions = this.computeViewFootPrint(dc, 32); - if (this.footPrintPositions != null) - { + if (this.footPrintPositions != null) { gl.glBegin(GL2.GL_LINE_STRIP); LatLon p1 = this.footPrintPositions.get(0); - for (LatLon p2 : this.footPrintPositions) - { + for (LatLon p2 : this.footPrintPositions) { int x = (int) (width * (p2.getLongitude().degrees + 180) / 360); int y = (int) (height * (p2.getLatitude().degrees + 90) / 180); // Draw - if (LatLon.locationsCrossDateline(p1, p2)) - { + if (LatLon.locationsCrossDateline(p1, p2)) { int y1 = (int) (height * (p1.getLatitude().degrees + 90) / 180); gl.glVertex3d(x < width / 2 ? width : 0, (y1 + y) / 2, 0); gl.glEnd(); @@ -481,15 +443,13 @@ protected void drawIcon(DrawContext dc) gl.glVertex3d(0, height - 1, 0); gl.glVertex3d(0, 0, 0); gl.glEnd(); - } - else - { + } else { // Picking this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); // Where in the world are we picking ? - Position pickPosition = - computePickPosition(dc, locationSW, new Dimension((int) (width * scale), (int) (height * scale))); + Position pickPosition + = computePickPosition(dc, locationSW, new Dimension((int) (width * scale), (int) (height * scale))); Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); this.pickSupport.addPickableObject(colorCode, this, pickPosition, false); @@ -498,49 +458,37 @@ protected void drawIcon(DrawContext dc) this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, dc.getPickPoint(), this); } - } - finally - { + } finally { dc.restoreDefaultDepthTesting(); dc.restoreDefaultCurrentColor(); - if (dc.isPickingMode()) + if (dc.isPickingMode()) { dc.restoreDefaultBlending(); + } ogsh.pop(gl); } } - protected double computeScale(java.awt.Rectangle viewport) - { - if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) - { + protected double computeScale(java.awt.Rectangle viewport) { + if (this.resizeBehavior.equals(AVKey.RESIZE_SHRINK_ONLY)) { return Math.min(1d, (this.toViewportScale) * viewport.width / this.getScaledIconWidth()); - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_STRETCH)) { return (this.toViewportScale) * viewport.width / this.getScaledIconWidth(); - } - else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) - { + } else if (this.resizeBehavior.equals(AVKey.RESIZE_KEEP_FIXED_SIZE)) { return 1d; - } - else - { + } else { return 1d; } } - protected double getScaledIconWidth() - { + protected double getScaledIconWidth() { return this.iconWidth * this.iconScale; } - protected double getScaledIconHeight() - { + protected double getScaledIconHeight() { return this.iconHeight * this.iconScale; } - protected Vec4 computeLocation(java.awt.Rectangle viewport, double scale) - { + protected Vec4 computeLocation(java.awt.Rectangle viewport, double scale) { double width = this.getScaledIconWidth(); double height = this.getScaledIconHeight(); @@ -550,39 +498,28 @@ protected Vec4 computeLocation(java.awt.Rectangle viewport, double scale) double x; double y; - if (this.locationCenter != null) - { + if (this.locationCenter != null) { x = this.locationCenter.x - scaledWidth / 2; y = this.locationCenter.y - scaledHeight / 2; - } - else if (this.position.equals(AVKey.NORTHEAST)) - { + } else if (this.position.equals(AVKey.NORTHEAST)) { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHEAST)) - { + } else if (this.position.equals(AVKey.SOUTHEAST)) { x = viewport.getWidth() - scaledWidth - this.borderWidth; y = 0d + this.borderWidth; - } - else if (this.position.equals(AVKey.NORTHWEST)) - { + } else if (this.position.equals(AVKey.NORTHWEST)) { x = 0d + this.borderWidth; y = viewport.getHeight() - scaledHeight - this.borderWidth; - } - else if (this.position.equals(AVKey.SOUTHWEST)) - { + } else if (this.position.equals(AVKey.SOUTHWEST)) { x = 0d + this.borderWidth; y = 0d + this.borderWidth; - } - else // use North East + } else // use North East { x = viewport.getWidth() - scaledWidth / 2 - this.borderWidth; y = viewport.getHeight() - scaledHeight / 2 - this.borderWidth; } - if (this.locationOffset != null) - { + if (this.locationOffset != null) { x += this.locationOffset.x; y += this.locationOffset.y; } @@ -590,22 +527,19 @@ else if (this.position.equals(AVKey.SOUTHWEST)) return new Vec4(x, y, 0); } - protected void initializeTexture(DrawContext dc) - { + protected void initializeTexture(DrawContext dc) { Texture iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath()); - if (iconTexture != null) + if (iconTexture != null) { return; + } GL gl = dc.getGL(); - try - { + try { InputStream iconStream = this.getClass().getResourceAsStream("/" + this.getIconFilePath()); - if (iconStream == null) - { + if (iconStream == null) { File iconFile = new File(this.iconFilePath); - if (iconFile.exists()) - { + if (iconFile.exists()) { iconStream = new FileInputStream(iconFile); } } @@ -616,9 +550,7 @@ protected void initializeTexture(DrawContext dc) this.iconWidth = iconTexture.getWidth(); this.iconHeight = iconTexture.getHeight(); dc.getTextureCache().put(this.getIconFilePath(), iconTexture); - } - catch (IOException e) - { + } catch (IOException e) { String msg = Logging.getMessage("layers.IOExceptionDuringInitialization"); Logging.logger().severe(msg); throw new WWRuntimeException(msg, e); @@ -637,50 +569,48 @@ protected void initializeTexture(DrawContext dc) /** * Compute the lat/lon position of the view center * - * @param dc the current DrawContext + * @param dc the current DrawContext * @param view the current View * * @return the ground position of the view center or null */ - protected Position computeGroundPosition(DrawContext dc, View view) - { - if (view == null) + protected Position computeGroundPosition(DrawContext dc, View view) { + if (view == null) { return null; + } Position groundPos = view.computePositionFromScreenPoint( - view.getViewport().getWidth() / 2, view.getViewport().getHeight() / 2); - if (groundPos == null) + view.getViewport().getWidth() / 2, view.getViewport().getHeight() / 2); + if (groundPos == null) { return null; + } double elevation = dc.getGlobe().getElevation(groundPos.getLatitude(), groundPos.getLongitude()); return new Position( - groundPos.getLatitude(), - groundPos.getLongitude(), - elevation * dc.getVerticalExaggeration()); + groundPos.getLatitude(), + groundPos.getLongitude(), + elevation * dc.getVerticalExaggeration()); } /** * Computes the lat/lon of the pickPoint over the world map * - * @param dc the current DrawContext + * @param dc the current DrawContext * @param locationSW the screen location of the bottom left corner of the map - * @param mapSize the world map screen dimension in pixels + * @param mapSize the world map screen dimension in pixels * * @return the picked Position */ - protected Position computePickPosition(DrawContext dc, Vec4 locationSW, Dimension mapSize) - { + protected Position computePickPosition(DrawContext dc, Vec4 locationSW, Dimension mapSize) { Position pickPosition = null; Point pickPoint = dc.getPickPoint(); - if (pickPoint != null) - { + if (pickPoint != null) { Rectangle viewport = dc.getView().getViewport(); // Check if pickpoint is inside the map if (pickPoint.getX() >= locationSW.getX() - && pickPoint.getX() < locationSW.getX() + mapSize.width - && viewport.height - pickPoint.getY() >= locationSW.getY() - && viewport.height - pickPoint.getY() < locationSW.getY() + mapSize.height) - { + && pickPoint.getX() < locationSW.getX() + mapSize.width + && viewport.height - pickPoint.getY() >= locationSW.getY() + && viewport.height - pickPoint.getY() < locationSW.getY() + mapSize.height) { double lon = (pickPoint.getX() - locationSW.getX()) / mapSize.width * 360 - 180; double lat = (viewport.height - pickPoint.getY() - locationSW.getY()) / mapSize.height * 180 - 90; double pickAltitude = 1000e3; @@ -693,36 +623,32 @@ protected Position computePickPosition(DrawContext dc, Vec4 locationSW, Dimensio /** * Compute the view range footprint on the globe. * - * @param dc the current DrawContext + * @param dc the current DrawContext * @param steps the number of steps. * * @return an array list of LatLon forming a closed shape. */ - protected ArrayList computeViewFootPrint(DrawContext dc, int steps) - { + protected ArrayList computeViewFootPrint(DrawContext dc, int steps) { ArrayList positions = new ArrayList(); Position eyePos = dc.getView().getEyePosition(); Angle distance = Angle.fromRadians( - Math.asin(dc.getView().getFarClipDistance() / (dc.getGlobe().getRadius() + eyePos.getElevation()))); - if (distance.degrees > 10) - { + Math.asin(dc.getView().getFarClipDistance() / (dc.getGlobe().getRadius() + eyePos.getElevation()))); + if (distance.degrees > 10) { double headStep = 360d / steps; Angle heading = Angle.ZERO; - for (int i = 0; i <= steps; i++) - { + for (int i = 0; i <= steps; i++) { LatLon p = LatLon.greatCircleEndPosition(eyePos, heading, distance); positions.add(p); heading = heading.addDegrees(headStep); } return positions; - } - else + } else { return null; + } } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.Earth.WorldMapLayer.Name"); } } diff --git a/src/gov/nasa/worldwind/layers/mercator/BasicMercatorTiledImageLayer.java b/src/gov/nasa/worldwind/layers/mercator/BasicMercatorTiledImageLayer.java index 62a045f6b0..6935a95891 100644 --- a/src/gov/nasa/worldwind/layers/mercator/BasicMercatorTiledImageLayer.java +++ b/src/gov/nasa/worldwind/layers/mercator/BasicMercatorTiledImageLayer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers.mercator; import com.jogamp.opengl.util.texture.*; @@ -27,87 +26,76 @@ * @author tag * @version $Id: BasicMercatorTiledImageLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicMercatorTiledImageLayer extends MercatorTiledImageLayer -{ +public class BasicMercatorTiledImageLayer extends MercatorTiledImageLayer { + private final Object fileLock = new Object(); - public BasicMercatorTiledImageLayer(LevelSet levelSet) - { + public BasicMercatorTiledImageLayer(LevelSet levelSet) { super(levelSet); - if (!WorldWind.getMemoryCacheSet().containsCache(MercatorTextureTile.class.getName())) - { + if (!WorldWind.getMemoryCacheSet().containsCache(MercatorTextureTile.class.getName())) { long size = Configuration.getLongValue( - AVKey.TEXTURE_IMAGE_CACHE_SIZE, 3000000L); + AVKey.TEXTURE_IMAGE_CACHE_SIZE, 3000000L); MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size); cache.setName("Texture Tiles"); WorldWind.getMemoryCacheSet().addCache(MercatorTextureTile.class.getName(), cache); } } - public BasicMercatorTiledImageLayer(AVList params) - { + public BasicMercatorTiledImageLayer(AVList params) { this(new LevelSet(params)); this.setValue(AVKey.CONSTRUCTION_PARAMETERS, params); } - protected void forceTextureLoad(MercatorTextureTile tile) - { + protected void forceTextureLoad(MercatorTextureTile tile) { final URL textureURL = this.getDataFileStore().findFile( - tile.getPath(), true); + tile.getPath(), true); - if (textureURL != null && !this.isTextureExpired(tile, textureURL)) - { + if (textureURL != null && !this.isTextureExpired(tile, textureURL)) { this.loadTexture(tile, textureURL); } } - protected void requestTexture(DrawContext dc, MercatorTextureTile tile) - { + protected void requestTexture(DrawContext dc, MercatorTextureTile tile) { Vec4 centroid = tile.getCentroidPoint(dc.getGlobe()); - if (this.getReferencePoint() != null) + if (this.getReferencePoint() != null) { tile.setPriority(centroid.distanceTo3(this.getReferencePoint())); + } RequestTask task = new RequestTask(tile, this); this.getRequestQ().add(task); } private static class RequestTask implements Runnable, - Comparable - { + Comparable { + private final BasicMercatorTiledImageLayer layer; private final MercatorTextureTile tile; private RequestTask(MercatorTextureTile tile, - BasicMercatorTiledImageLayer layer) - { + BasicMercatorTiledImageLayer layer) { this.layer = layer; this.tile = tile; } - public void run() - { + public void run() { // TODO: check to ensure load is still needed final java.net.URL textureURL = this.layer.getDataFileStore() - .findFile(tile.getPath(), false); + .findFile(tile.getPath(), false); if (textureURL != null - && !this.layer.isTextureExpired(tile, textureURL)) - { - if (this.layer.loadTexture(tile, textureURL)) - { + && !this.layer.isTextureExpired(tile, textureURL)) { + if (this.layer.loadTexture(tile, textureURL)) { layer.getLevels().unmarkResourceAbsent(tile); this.layer.firePropertyChange(AVKey.LAYER, null, this); return; - } - else - { + } else { // Assume that something's wrong with the file and delete it. this.layer.getDataFileStore().removeFile( - textureURL); + textureURL); layer.getLevels().markResourceAbsent(tile); String message = Logging.getMessage( - "generic.DeletedCorruptDataFile", textureURL); + "generic.DeletedCorruptDataFile", textureURL); Logging.logger().info(message); } } @@ -122,25 +110,24 @@ public void run() * * @throws IllegalArgumentException if that is null */ - public int compareTo(RequestTask that) - { - if (that == null) - { + public int compareTo(RequestTask that) { + if (that == null) { String msg = Logging.getMessage("nullValue.RequestTaskIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return this.tile.getPriority() == that.tile.getPriority() ? 0 - : this.tile.getPriority() < that.tile.getPriority() ? -1 + : this.tile.getPriority() < that.tile.getPriority() ? -1 : 1; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final RequestTask that = (RequestTask) o; @@ -148,130 +135,121 @@ public boolean equals(Object o) return !(tile != null ? !tile.equals(that.tile) : that.tile != null); } - public int hashCode() - { + public int hashCode() { return (tile != null ? tile.hashCode() : 0); } - public String toString() - { + public String toString() { return this.tile.toString(); } } private boolean isTextureExpired(MercatorTextureTile tile, - java.net.URL textureURL) - { - if (!WWIO.isFileOutOfDate(textureURL, tile.getLevel().getExpiryTime())) + java.net.URL textureURL) { + if (!WWIO.isFileOutOfDate(textureURL, tile.getLevel().getExpiryTime())) { return false; + } // The file has expired. Delete it. this.getDataFileStore().removeFile(textureURL); String message = Logging.getMessage("generic.DataFileExpired", - textureURL); + textureURL); Logging.logger().fine(message); return true; } private boolean loadTexture(MercatorTextureTile tile, - java.net.URL textureURL) - { + java.net.URL textureURL) { TextureData textureData; - synchronized (this.fileLock) - { + synchronized (this.fileLock) { textureData = readTexture(textureURL, this.isUseMipMaps()); } - if (textureData == null) + if (textureData == null) { return false; + } tile.setTextureData(textureData); - if (tile.getLevelNumber() != 0 || !this.isRetainLevelZeroTiles()) + if (tile.getLevelNumber() != 0 || !this.isRetainLevelZeroTiles()) { this.addTileToCache(tile); + } return true; } - private static TextureData readTexture(java.net.URL url, boolean useMipMaps) - { - try - { + private static TextureData readTexture(java.net.URL url, boolean useMipMaps) { + try { return OGLUtil.newTextureData(Configuration.getMaxCompatibleGLProfile(), url, useMipMaps); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("layers.TextureLayer.ExceptionAttemptingToReadTextureFile", url.toString()); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); return null; } } - private void addTileToCache(MercatorTextureTile tile) - { + private void addTileToCache(MercatorTextureTile tile) { WorldWind.getMemoryCache(MercatorTextureTile.class.getName()).add( - tile.getTileKey(), tile); + tile.getTileKey(), tile); } - protected void downloadTexture(final MercatorTextureTile tile) - { - if (!WorldWind.getRetrievalService().isAvailable()) + protected void downloadTexture(final MercatorTextureTile tile) { + if (!WorldWind.getRetrievalService().isAvailable()) { return; + } java.net.URL url; - try - { + try { url = tile.getResourceURL(); - if (url == null) + if (url == null) { return; + } - if (WorldWind.getNetworkStatus().isHostUnavailable(url)) + if (WorldWind.getNetworkStatus().isHostUnavailable(url)) { return; - } - catch (java.net.MalformedURLException e) - { + } + } catch (java.net.MalformedURLException e) { Logging.logger().log( - java.util.logging.Level.SEVERE, - Logging.getMessage( - "layers.TextureLayer.ExceptionCreatingTextureUrl", - tile), e); + java.util.logging.Level.SEVERE, + Logging.getMessage( + "layers.TextureLayer.ExceptionCreatingTextureUrl", + tile), e); return; } Retriever retriever; - if ("http".equalsIgnoreCase(url.getProtocol())) - { + if ("http".equalsIgnoreCase(url.getProtocol())) { retriever = new HTTPRetriever(url, new DownloadPostProcessor(tile, this)); retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers - } - else - { + } else { Logging.logger().severe( - Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", url.toString())); + Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", url.toString())); return; } // Apply any overridden timeouts. Integer cto = AVListImpl.getIntegerValue(this, - AVKey.URL_CONNECT_TIMEOUT); - if (cto != null && cto > 0) + AVKey.URL_CONNECT_TIMEOUT); + if (cto != null && cto > 0) { retriever.setConnectTimeout(cto); + } Integer cro = AVListImpl.getIntegerValue(this, AVKey.URL_READ_TIMEOUT); - if (cro != null && cro > 0) + if (cro != null && cro > 0) { retriever.setReadTimeout(cro); + } Integer srl = AVListImpl.getIntegerValue(this, - AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT); - if (srl != null && srl > 0) + AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT); + if (srl != null && srl > 0) { retriever.setStaleRequestLimit(srl); + } WorldWind.getRetrievalService().runRetriever(retriever, - tile.getPriority()); + tile.getPriority()); } private void saveBuffer(java.nio.ByteBuffer buffer, java.io.File outFile) - throws java.io.IOException - { + throws java.io.IOException { synchronized (this.fileLock) // synchronized with read of file in RequestTask.run() { WWIO.saveBuffer(buffer, outFile); @@ -279,48 +257,41 @@ private void saveBuffer(java.nio.ByteBuffer buffer, java.io.File outFile) } private static class DownloadPostProcessor implements - RetrievalPostProcessor - { + RetrievalPostProcessor { + // TODO: Rewrite this inner class, factoring out the generic parts. private final MercatorTextureTile tile; private final BasicMercatorTiledImageLayer layer; public DownloadPostProcessor(MercatorTextureTile tile, - BasicMercatorTiledImageLayer layer) - { + BasicMercatorTiledImageLayer layer) { this.tile = tile; this.layer = layer; } - public ByteBuffer run(Retriever retriever) - { - if (retriever == null) - { + public ByteBuffer run(Retriever retriever) { + if (retriever == null) { String msg = Logging.getMessage("nullValue.RetrieverIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - try - { + try { if (!retriever.getState().equals( - Retriever.RETRIEVER_STATE_SUCCESSFUL)) + Retriever.RETRIEVER_STATE_SUCCESSFUL)) { return null; + } URLRetriever r = (URLRetriever) retriever; ByteBuffer buffer = r.getBuffer(); - if (retriever instanceof HTTPRetriever) - { + if (retriever instanceof HTTPRetriever) { HTTPRetriever htr = (HTTPRetriever) retriever; - if (htr.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) - { + if (htr.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { // Mark tile as missing to avoid excessive attempts this.layer.getLevels().markResourceAbsent(this.tile); return null; - } - else if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) - { + } else if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) { // Also mark tile as missing, but for an unknown reason. this.layer.getLevels().markResourceAbsent(this.tile); return null; @@ -328,162 +299,135 @@ else if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) } final File outFile = this.layer.getDataFileStore().newFile( - this.tile.getPath()); - if (outFile == null) + this.tile.getPath()); + if (outFile == null) { return null; + } - if (outFile.exists()) + if (outFile.exists()) { return buffer; + } // TODO: Better, more generic and flexible handling of file-format type - if (buffer != null) - { + if (buffer != null) { String contentType = r.getContentType(); - if (contentType == null) - { + if (contentType == null) { // TODO: logger message return null; } if (contentType.contains("xml") - || contentType.contains("html") - || contentType.contains("text")) - { + || contentType.contains("html") + || contentType.contains("text")) { this.layer.getLevels().markResourceAbsent(this.tile); StringBuffer sb = new StringBuffer(); - while (buffer.hasRemaining()) - { + while (buffer.hasRemaining()) { sb.append((char) buffer.get()); } // TODO: parse out the message if the content is xml or html. Logging.logger().severe(sb.toString()); return null; - } - else if (contentType.contains("dds")) - { + } else if (contentType.contains("dds")) { this.layer.saveBuffer(buffer, outFile); - } - else if (contentType.contains("zip")) - { + } else if (contentType.contains("zip")) { // Assume it's zipped DDS, which the retriever would have unzipped into the buffer. this.layer.saveBuffer(buffer, outFile); - } -// else if (outFile.getName().endsWith(".dds")) -// { -// // Convert to DDS and save the result. -// buffer = DDSConverter.convertToDDS(buffer, contentType); -// if (buffer != null) -// this.layer.saveBuffer(buffer, outFile); -// } - else if (contentType.contains("image")) - { + } // else if (outFile.getName().endsWith(".dds")) + // { + // // Convert to DDS and save the result. + // buffer = DDSConverter.convertToDDS(buffer, contentType); + // if (buffer != null) + // this.layer.saveBuffer(buffer, outFile); + // } + else if (contentType.contains("image")) { BufferedImage image = this.layer.convertBufferToImage(buffer); - if (image != null) - { + if (image != null) { image = this.layer.modifyImage(image); - if (this.layer.isTileValid(image)) - { - if (!this.layer.transformAndSave(image, tile.getMercatorSector(), outFile)) + if (this.layer.isTileValid(image)) { + if (!this.layer.transformAndSave(image, tile.getMercatorSector(), outFile)) { image = null; - } - else - { + } + } else { this.layer.getLevels().markResourceAbsent(this.tile); return null; } } - if (image == null) - { + if (image == null) { // Just save whatever it is to the cache. this.layer.saveBuffer(buffer, outFile); } } - if (buffer != null) - { + if (buffer != null) { this.layer.firePropertyChange(AVKey.LAYER, null, this); } return buffer; } - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { this.layer.getLevels().markResourceAbsent(this.tile); Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("layers.TextureLayer.ExceptionSavingRetrievedTextureFile", tile.getPath()), e); + Logging.getMessage("layers.TextureLayer.ExceptionSavingRetrievedTextureFile", tile.getPath()), e); } return null; } } - protected boolean isTileValid(BufferedImage image) - { + protected boolean isTileValid(BufferedImage image) { //override in subclass to check image tile //if false is returned, then tile is marked absent return true; } - protected BufferedImage modifyImage(BufferedImage image) - { + protected BufferedImage modifyImage(BufferedImage image) { //override in subclass to modify image tile return image; } - private BufferedImage convertBufferToImage(ByteBuffer buffer) - { - try - { + private BufferedImage convertBufferToImage(ByteBuffer buffer) { + try { InputStream is = new ByteArrayInputStream(buffer.array()); return ImageIO.read(is); - } - catch (IOException e) - { + } catch (IOException e) { return null; } } private boolean transformAndSave(BufferedImage image, MercatorSector sector, - File outFile) - { - try - { + File outFile) { + try { image = transform(image, sector); String extension = outFile.getName().substring( - outFile.getName().lastIndexOf('.') + 1); + outFile.getName().lastIndexOf('.') + 1); synchronized (this.fileLock) // synchronized with read of file in RequestTask.run() { return ImageIO.write(image, extension, outFile); } - } - catch (IOException e) - { + } catch (IOException e) { return false; } } - private BufferedImage transform(BufferedImage image, MercatorSector sector) - { + private BufferedImage transform(BufferedImage image, MercatorSector sector) { int type = image.getType(); - if (type == 0) + if (type == 0) { type = BufferedImage.TYPE_INT_RGB; + } BufferedImage trans = new BufferedImage(image.getWidth(), image - .getHeight(), type); + .getHeight(), type); double miny = sector.getMinLatPercent(); double maxy = sector.getMaxLatPercent(); - for (int y = 0; y < image.getHeight(); y++) - { + for (int y = 0; y < image.getHeight(); y++) { double sy = 1.0 - y / (double) (image.getHeight() - 1); Angle lat = Angle.fromRadians(sy * sector.getDeltaLatRadians() - + sector.getMinLatitude().radians); + + sector.getMinLatitude().radians); double dy = 1.0 - (MercatorSector.gudermannianInverse(lat) - miny) - / (maxy - miny); + / (maxy - miny); dy = Math.max(0.0, Math.min(1.0, dy)); int iy = (int) (dy * (image.getHeight() - 1)); - for (int x = 0; x < image.getWidth(); x++) - { + for (int x = 0; x < image.getWidth(); x++) { trans.setRGB(x, y, image.getRGB(x, iy)); } } diff --git a/src/gov/nasa/worldwind/layers/mercator/MercatorSector.java b/src/gov/nasa/worldwind/layers/mercator/MercatorSector.java index 60c4f23457..d68a6aed76 100644 --- a/src/gov/nasa/worldwind/layers/mercator/MercatorSector.java +++ b/src/gov/nasa/worldwind/layers/mercator/MercatorSector.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers.mercator; import gov.nasa.worldwind.geom.*; @@ -11,52 +10,45 @@ /** * @version $Id: MercatorSector.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MercatorSector extends Sector -{ +public class MercatorSector extends Sector { + private double minLatPercent, maxLatPercent; public MercatorSector(double minLatPercent, double maxLatPercent, - Angle minLongitude, Angle maxLongitude) - { + Angle minLongitude, Angle maxLongitude) { super(gudermannian(minLatPercent), gudermannian(maxLatPercent), - minLongitude, maxLongitude); + minLongitude, maxLongitude); this.minLatPercent = minLatPercent; this.maxLatPercent = maxLatPercent; } public static MercatorSector fromDegrees(double minLatPercent, - double maxLatPercent, double minLongitude, double maxLongitude) - { + double maxLatPercent, double minLongitude, double maxLongitude) { return new MercatorSector(minLatPercent, maxLatPercent, Angle - .fromDegrees(minLongitude), Angle.fromDegrees(maxLongitude)); + .fromDegrees(minLongitude), Angle.fromDegrees(maxLongitude)); } - public static MercatorSector fromSector(Sector sector) - { + public static MercatorSector fromSector(Sector sector) { return new MercatorSector(gudermannianInverse(sector.getMinLatitude()), - gudermannianInverse(sector.getMaxLatitude()), new Angle(sector + gudermannianInverse(sector.getMaxLatitude()), new Angle(sector .getMinLongitude()), - new Angle(sector.getMaxLongitude())); + new Angle(sector.getMaxLongitude())); } - public static double gudermannianInverse(Angle latitude) - { + public static double gudermannianInverse(Angle latitude) { return Math.log(Math.tan(Math.PI / 4.0 + latitude.radians / 2.0)) - / Math.PI; + / Math.PI; } - public static Angle gudermannian(double percent) - { + public static Angle gudermannian(double percent) { return Angle.fromRadians(Math.atan(Math.sinh(percent * Math.PI))); } - public double getMinLatPercent() - { + public double getMinLatPercent() { return minLatPercent; } - public double getMaxLatPercent() - { + public double getMaxLatPercent() { return maxLatPercent; } } diff --git a/src/gov/nasa/worldwind/layers/mercator/MercatorTextureTile.java b/src/gov/nasa/worldwind/layers/mercator/MercatorTextureTile.java index 8f8a8fd562..fa9a190087 100644 --- a/src/gov/nasa/worldwind/layers/mercator/MercatorTextureTile.java +++ b/src/gov/nasa/worldwind/layers/mercator/MercatorTextureTile.java @@ -13,88 +13,87 @@ /** * @version $Id: MercatorTextureTile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MercatorTextureTile extends TextureTile -{ - private MercatorSector mercatorSector; +public class MercatorTextureTile extends TextureTile { - public MercatorTextureTile(MercatorSector mercatorSector, Level level, - int row, int col) - { - super(mercatorSector, level, row, col); - this.mercatorSector = mercatorSector; - } + private MercatorSector mercatorSector; - @Override - public MercatorTextureTile[] createSubTiles(Level nextLevel) - { - if (nextLevel == null) - { - String msg = Logging.getMessage("nullValue.LevelIsNull"); - Logging.logger().severe(msg); - throw new IllegalArgumentException(msg); - } - double d0 = this.getMercatorSector().getMinLatPercent(); - double d2 = this.getMercatorSector().getMaxLatPercent(); - double d1 = d0 + (d2 - d0) / 2.0; + public MercatorTextureTile(MercatorSector mercatorSector, Level level, + int row, int col) { + super(mercatorSector, level, row, col); + this.mercatorSector = mercatorSector; + } - Angle t0 = this.getSector().getMinLongitude(); - Angle t2 = this.getSector().getMaxLongitude(); - Angle t1 = Angle.midAngle(t0, t2); + @Override + public MercatorTextureTile[] createSubTiles(Level nextLevel) { + if (nextLevel == null) { + String msg = Logging.getMessage("nullValue.LevelIsNull"); + Logging.logger().severe(msg); + throw new IllegalArgumentException(msg); + } + double d0 = this.getMercatorSector().getMinLatPercent(); + double d2 = this.getMercatorSector().getMaxLatPercent(); + double d1 = d0 + (d2 - d0) / 2.0; - String nextLevelCacheName = nextLevel.getCacheName(); - int nextLevelNum = nextLevel.getLevelNumber(); - int row = this.getRow(); - int col = this.getColumn(); + Angle t0 = this.getSector().getMinLongitude(); + Angle t2 = this.getSector().getMaxLongitude(); + Angle t1 = Angle.midAngle(t0, t2); - MercatorTextureTile[] subTiles = new MercatorTextureTile[4]; + String nextLevelCacheName = nextLevel.getCacheName(); + int nextLevelNum = nextLevel.getLevelNumber(); + int row = this.getRow(); + int col = this.getColumn(); - TileKey key = new TileKey(nextLevelNum, 2 * row, 2 * col, - nextLevelCacheName); - MercatorTextureTile subTile = this.getTileFromMemoryCache(key); - if (subTile != null) - subTiles[0] = subTile; - else - subTiles[0] = new MercatorTextureTile(new MercatorSector(d0, d1, - t0, t1), nextLevel, 2 * row, 2 * col); + MercatorTextureTile[] subTiles = new MercatorTextureTile[4]; - key = new TileKey(nextLevelNum, 2 * row, 2 * col + 1, - nextLevelCacheName); - subTile = this.getTileFromMemoryCache(key); - if (subTile != null) - subTiles[1] = subTile; - else - subTiles[1] = new MercatorTextureTile(new MercatorSector(d0, d1, - t1, t2), nextLevel, 2 * row, 2 * col + 1); + TileKey key = new TileKey(nextLevelNum, 2 * row, 2 * col, + nextLevelCacheName); + MercatorTextureTile subTile = this.getTileFromMemoryCache(key); + if (subTile != null) { + subTiles[0] = subTile; + } else { + subTiles[0] = new MercatorTextureTile(new MercatorSector(d0, d1, + t0, t1), nextLevel, 2 * row, 2 * col); + } - key = new TileKey(nextLevelNum, 2 * row + 1, 2 * col, - nextLevelCacheName); - subTile = this.getTileFromMemoryCache(key); - if (subTile != null) - subTiles[2] = subTile; - else - subTiles[2] = new MercatorTextureTile(new MercatorSector(d1, d2, - t0, t1), nextLevel, 2 * row + 1, 2 * col); + key = new TileKey(nextLevelNum, 2 * row, 2 * col + 1, + nextLevelCacheName); + subTile = this.getTileFromMemoryCache(key); + if (subTile != null) { + subTiles[1] = subTile; + } else { + subTiles[1] = new MercatorTextureTile(new MercatorSector(d0, d1, + t1, t2), nextLevel, 2 * row, 2 * col + 1); + } - key = new TileKey(nextLevelNum, 2 * row + 1, 2 * col + 1, - nextLevelCacheName); - subTile = this.getTileFromMemoryCache(key); - if (subTile != null) - subTiles[3] = subTile; - else - subTiles[3] = new MercatorTextureTile(new MercatorSector(d1, d2, - t1, t2), nextLevel, 2 * row + 1, 2 * col + 1); + key = new TileKey(nextLevelNum, 2 * row + 1, 2 * col, + nextLevelCacheName); + subTile = this.getTileFromMemoryCache(key); + if (subTile != null) { + subTiles[2] = subTile; + } else { + subTiles[2] = new MercatorTextureTile(new MercatorSector(d1, d2, + t0, t1), nextLevel, 2 * row + 1, 2 * col); + } - return subTiles; - } + key = new TileKey(nextLevelNum, 2 * row + 1, 2 * col + 1, + nextLevelCacheName); + subTile = this.getTileFromMemoryCache(key); + if (subTile != null) { + subTiles[3] = subTile; + } else { + subTiles[3] = new MercatorTextureTile(new MercatorSector(d1, d2, + t1, t2), nextLevel, 2 * row + 1, 2 * col + 1); + } - protected MercatorTextureTile getTileFromMemoryCache(TileKey tileKey) - { - return (MercatorTextureTile) WorldWind.getMemoryCache( - MercatorTextureTile.class.getName()).getObject(tileKey); - } + return subTiles; + } - public MercatorSector getMercatorSector() - { - return mercatorSector; - } + protected MercatorTextureTile getTileFromMemoryCache(TileKey tileKey) { + return (MercatorTextureTile) WorldWind.getMemoryCache( + MercatorTextureTile.class.getName()).getObject(tileKey); + } + + public MercatorSector getMercatorSector() { + return mercatorSector; + } } diff --git a/src/gov/nasa/worldwind/layers/mercator/MercatorTiledImageLayer.java b/src/gov/nasa/worldwind/layers/mercator/MercatorTiledImageLayer.java index c81ebda904..9d83c424b1 100644 --- a/src/gov/nasa/worldwind/layers/mercator/MercatorTiledImageLayer.java +++ b/src/gov/nasa/worldwind/layers/mercator/MercatorTiledImageLayer.java @@ -32,8 +32,8 @@ * @author tag * @version $Id: MercatorTiledImageLayer.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public abstract class MercatorTiledImageLayer extends AbstractLayer -{ +public abstract class MercatorTiledImageLayer extends AbstractLayer { + // Infrastructure private static final LevelComparer levelComparer = new LevelComparer(); private final LevelSet levels; @@ -60,16 +60,14 @@ public abstract class MercatorTiledImageLayer extends AbstractLayer private Vec4 referencePoint; private boolean atMaxResolution = false; private PriorityBlockingQueue requestQ = new PriorityBlockingQueue( - 200); + 200); abstract protected void requestTexture(DrawContext dc, MercatorTextureTile tile); abstract protected void forceTextureLoad(MercatorTextureTile tile); - public MercatorTiledImageLayer(LevelSet levelSet) - { - if (levelSet == null) - { + public MercatorTiledImageLayer(LevelSet levelSet) { + if (levelSet == null) { String message = Logging.getMessage("nullValue.LevelSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -84,114 +82,92 @@ public MercatorTiledImageLayer(LevelSet levelSet) } @Override - public void setName(String name) - { + public void setName(String name) { super.setName(name); this.tileCountName = this.getName() + " Tiles"; } - public boolean isUseTransparentTextures() - { + public boolean isUseTransparentTextures() { return this.useTransparentTextures; } - public void setUseTransparentTextures(boolean useTransparentTextures) - { + public void setUseTransparentTextures(boolean useTransparentTextures) { this.useTransparentTextures = useTransparentTextures; } - public boolean isForceLevelZeroLoads() - { + public boolean isForceLevelZeroLoads() { return this.forceLevelZeroLoads; } - public void setForceLevelZeroLoads(boolean forceLevelZeroLoads) - { + public void setForceLevelZeroLoads(boolean forceLevelZeroLoads) { this.forceLevelZeroLoads = forceLevelZeroLoads; } - public boolean isRetainLevelZeroTiles() - { + public boolean isRetainLevelZeroTiles() { return retainLevelZeroTiles; } - public void setRetainLevelZeroTiles(boolean retainLevelZeroTiles) - { + public void setRetainLevelZeroTiles(boolean retainLevelZeroTiles) { this.retainLevelZeroTiles = retainLevelZeroTiles; } - public boolean isDrawTileIDs() - { + public boolean isDrawTileIDs() { return drawTileIDs; } - public void setDrawTileIDs(boolean drawTileIDs) - { + public void setDrawTileIDs(boolean drawTileIDs) { this.drawTileIDs = drawTileIDs; } - public boolean isDrawTileBoundaries() - { + public boolean isDrawTileBoundaries() { return drawTileBoundaries; } - public void setDrawTileBoundaries(boolean drawTileBoundaries) - { + public void setDrawTileBoundaries(boolean drawTileBoundaries) { this.drawTileBoundaries = drawTileBoundaries; } - public boolean isShowImageTileOutlines() - { + public boolean isShowImageTileOutlines() { return showImageTileOutlines; } - public void setShowImageTileOutlines(boolean showImageTileOutlines) - { + public void setShowImageTileOutlines(boolean showImageTileOutlines) { this.showImageTileOutlines = showImageTileOutlines; } - public boolean isDrawBoundingVolumes() - { + public boolean isDrawBoundingVolumes() { return drawBoundingVolumes; } - public void setDrawBoundingVolumes(boolean drawBoundingVolumes) - { + public void setDrawBoundingVolumes(boolean drawBoundingVolumes) { this.drawBoundingVolumes = drawBoundingVolumes; } - protected LevelSet getLevels() - { + protected LevelSet getLevels() { return levels; } - protected PriorityBlockingQueue getRequestQ() - { + protected PriorityBlockingQueue getRequestQ() { return requestQ; } - public boolean isMultiResolution() - { + public boolean isMultiResolution() { return this.getLevels() != null && this.getLevels().getNumLevels() > 1; } - public boolean isAtMaxResolution() - { + public boolean isAtMaxResolution() { return this.atMaxResolution; } - public boolean isUseMipMaps() - { + public boolean isUseMipMaps() { return useMipMaps; } - public void setUseMipMaps(boolean useMipMaps) - { + public void setUseMipMaps(boolean useMipMaps) { this.useMipMaps = useMipMaps; } - private void createTopLevelTiles() - { + private void createTopLevelTiles() { MercatorSector sector = (MercatorSector) this.levels.getSector(); Level level = levels.getFirstLevel(); @@ -211,37 +187,34 @@ private void createTopLevelTiles() int nLonTiles = lastCol - firstCol + 1; this.topLevels = new ArrayList(nLatTiles - * nLonTiles); + * nLonTiles); //Angle p1 = Tile.computeRowLatitude(firstRow, dLat); double deltaLat = dLat.degrees / 90; double d1 = -1.0 + deltaLat * firstRow; - for (int row = firstRow; row <= lastRow; row++) - { + for (int row = firstRow; row <= lastRow; row++) { //Angle p2; //p2 = p1.add(dLat); double d2 = d1 + deltaLat; Angle t1 = Tile.computeColumnLongitude(firstCol, dLon, lonOrigin); - for (int col = firstCol; col <= lastCol; col++) - { + for (int col = firstCol; col <= lastCol; col++) { Angle t2; t2 = t1.add(dLon); this.topLevels.add(new MercatorTextureTile(new MercatorSector( - d1, d2, t1, t2), level, row, col)); + d1, d2, t1, t2), level, row, col)); t1 = t2; } d1 = d2; } } - private void loadAllTopLevelTextures(DrawContext dc) - { - for (MercatorTextureTile tile : this.topLevels) - { - if (!tile.isTextureInMemory(dc.getTextureCache())) + private void loadAllTopLevelTextures(DrawContext dc) { + for (MercatorTextureTile tile : this.topLevels) { + if (!tile.isTextureInMemory(dc.getTextureCache())) { this.forceTextureLoad(tile); + } } this.levelZeroLoaded = true; @@ -250,43 +223,34 @@ private void loadAllTopLevelTextures(DrawContext dc) // ============== Tile Assembly ======================= // // ============== Tile Assembly ======================= // // ============== Tile Assembly ======================= // - - private void assembleTiles(DrawContext dc) - { + private void assembleTiles(DrawContext dc) { this.currentTiles.clear(); - for (MercatorTextureTile tile : this.topLevels) - { - if (this.isTileVisible(dc, tile)) - { + for (MercatorTextureTile tile : this.topLevels) { + if (this.isTileVisible(dc, tile)) { this.currentResourceTile = null; this.addTileOrDescendants(dc, tile); } } } - private void addTileOrDescendants(DrawContext dc, MercatorTextureTile tile) - { - if (this.meetsRenderCriteria(dc, tile)) - { + private void addTileOrDescendants(DrawContext dc, MercatorTextureTile tile) { + if (this.meetsRenderCriteria(dc, tile)) { this.addTile(dc, tile); return; } // The incoming tile does not meet the rendering criteria, so it must be subdivided and those // subdivisions tested against the criteria. - // All tiles that meet the selection criteria are drawn, but some of those tiles will not have // textures associated with them either because their texture isn't loaded yet or because they // are finer grain than the layer has textures for. In these cases the tiles use the texture of // the closest ancestor that has a texture loaded. This ancestor is called the currentResourceTile. // A texture transform is applied during rendering to align the sector's texture coordinates with the // appropriate region of the ancestor's texture. - MercatorTextureTile ancestorResource = null; - try - { + try { // TODO: Revise this to reflect that the parent layer is only requested while the algorithm continues // to search for the layer matching the criteria. // At this point the tile does not meet the render criteria but it may have its texture in memory. @@ -301,46 +265,41 @@ private void addTileOrDescendants(DrawContext dc, MercatorTextureTile tile) // therefore the layer remains visible until the user is zoomed out to the point the layer is no longer // active. if (tile.isTextureInMemory(dc.getTextureCache()) - || tile.getLevelNumber() == 0) - { + || tile.getLevelNumber() == 0) { ancestorResource = this.currentResourceTile; this.currentResourceTile = tile; - } - else if (!tile.getLevel().isEmpty()) - { + } else if (!tile.getLevel().isEmpty()) { // this.addTile(dc, tile); // return; // Issue a request for the parent before descending to the children. - if (tile.getLevelNumber() < this.levels.getNumLevels()) - { + if (tile.getLevelNumber() < this.levels.getNumLevels()) { // Request only tiles with data associated at this level - if (!this.levels.isResourceAbsent(tile)) + if (!this.levels.isResourceAbsent(tile)) { this.requestTexture(dc, tile); + } } } MercatorTextureTile[] subTiles = tile.createSubTiles(this.levels - .getLevel(tile.getLevelNumber() + 1)); - for (MercatorTextureTile child : subTiles) - { - if (this.isTileVisible(dc, child)) + .getLevel(tile.getLevelNumber() + 1)); + for (MercatorTextureTile child : subTiles) { + if (this.isTileVisible(dc, child)) { this.addTileOrDescendants(dc, child); + } } - } - finally - { + } finally { if (ancestorResource != null) // Pop this tile as the currentResource ancestor + { this.currentResourceTile = ancestorResource; + } } } - private void addTile(DrawContext dc, MercatorTextureTile tile) - { + private void addTile(DrawContext dc, MercatorTextureTile tile) { tile.setFallbackTile(null); - if (tile.isTextureInMemory(dc.getTextureCache())) - { + if (tile.isTextureInMemory(dc.getTextureCache())) { // System.out.printf("Sector %s, min = %f, max = %f\n", tile.getSector(), // dc.getGlobe().getMinElevation(tile.getSector()), dc.getGlobe().getMaxElevation(tile.getSector())); this.addTileToCurrent(tile); @@ -349,51 +308,46 @@ private void addTile(DrawContext dc, MercatorTextureTile tile) // Level 0 loads may be forced if (tile.getLevelNumber() == 0 && this.forceLevelZeroLoads - && !tile.isTextureInMemory(dc.getTextureCache())) - { + && !tile.isTextureInMemory(dc.getTextureCache())) { this.forceTextureLoad(tile); - if (tile.isTextureInMemory(dc.getTextureCache())) - { + if (tile.isTextureInMemory(dc.getTextureCache())) { this.addTileToCurrent(tile); return; } } // Tile's texture isn't available, so request it - if (tile.getLevelNumber() < this.levels.getNumLevels()) - { + if (tile.getLevelNumber() < this.levels.getNumLevels()) { // Request only tiles with data associated at this level - if (!this.levels.isResourceAbsent(tile)) + if (!this.levels.isResourceAbsent(tile)) { this.requestTexture(dc, tile); + } } // Set up to use the currentResource tile's texture - if (this.currentResourceTile != null) - { + if (this.currentResourceTile != null) { if (this.currentResourceTile.getLevelNumber() == 0 - && this.forceLevelZeroLoads - && !this.currentResourceTile.isTextureInMemory(dc - .getTextureCache()) - && !this.currentResourceTile.isTextureInMemory(dc - .getTextureCache())) + && this.forceLevelZeroLoads + && !this.currentResourceTile.isTextureInMemory(dc + .getTextureCache()) + && !this.currentResourceTile.isTextureInMemory(dc + .getTextureCache())) { this.forceTextureLoad(this.currentResourceTile); + } if (this.currentResourceTile - .isTextureInMemory(dc.getTextureCache())) - { + .isTextureInMemory(dc.getTextureCache())) { tile.setFallbackTile(currentResourceTile); this.addTileToCurrent(tile); } } } - private void addTileToCurrent(MercatorTextureTile tile) - { + private void addTileToCurrent(MercatorTextureTile tile) { this.currentTiles.add(tile); } - private boolean isTileVisible(DrawContext dc, MercatorTextureTile tile) - { + private boolean isTileVisible(DrawContext dc, MercatorTextureTile tile) { // if (!(tile.getExtent(dc).intersects(dc.getView().getFrustumInModelCoordinates()) // && (dc.getVisibleSector() == null || dc.getVisibleSector().intersects(tile.getSector())))) // return false; @@ -407,9 +361,9 @@ private boolean isTileVisible(DrawContext dc, MercatorTextureTile tile) // return true; // return tile.getExtent(dc).intersects( - dc.getView().getFrustumInModelCoordinates()) - && (dc.getVisibleSector() == null || dc.getVisibleSector() - .intersects(tile.getSector())); + dc.getView().getFrustumInModelCoordinates()) + && (dc.getVisibleSector() == null || dc.getVisibleSector() + .intersects(tile.getSector())); } // @@ -456,15 +410,12 @@ private boolean isTileVisible(DrawContext dc, MercatorTextureTile tile) // // return 2 * pixelSize >= texelSize; // } - - private boolean meetsRenderCriteria(DrawContext dc, MercatorTextureTile tile) - { + private boolean meetsRenderCriteria(DrawContext dc, MercatorTextureTile tile) { return this.levels.isFinalLevel(tile.getLevelNumber()) - || !needToSplit(dc, tile.getSector()); + || !needToSplit(dc, tile.getSector()); } - private boolean needToSplit(DrawContext dc, Sector sector) - { + private boolean needToSplit(DrawContext dc, Sector sector) { Vec4[] corners = sector.computeCornerPoints(dc.getGlobe(), dc.getVerticalExaggeration()); Vec4 centerPoint = sector.computeCenterPoint(dc.getGlobe(), dc.getVerticalExaggeration()); @@ -476,91 +427,91 @@ private boolean needToSplit(DrawContext dc, Sector sector) double d5 = view.getEyePoint().distanceTo3(centerPoint); double minDistance = d1; - if (d2 < minDistance) + if (d2 < minDistance) { minDistance = d2; - if (d3 < minDistance) + } + if (d3 < minDistance) { minDistance = d3; - if (d4 < minDistance) + } + if (d4 < minDistance) { minDistance = d4; - if (d5 < minDistance) + } + if (d5 < minDistance) { minDistance = d5; + } double cellSize = (Math.PI * sector.getDeltaLatRadians() * dc - .getGlobe().getRadius()) / 20; // TODO + .getGlobe().getRadius()) / 20; // TODO return !(Math.log10(cellSize) <= (Math.log10(minDistance) - this.splitScale)); } - private boolean atMaxLevel(DrawContext dc) - { + private boolean atMaxLevel(DrawContext dc) { Position vpc = dc.getViewportCenterPosition(); - if (dc.getView() == null || this.getLevels() == null || vpc == null) + if (dc.getView() == null || this.getLevels() == null || vpc == null) { return false; + } if (!this.getLevels().getSector().contains(vpc.getLatitude(), - vpc.getLongitude())) + vpc.getLongitude())) { return true; + } Level nextToLast = this.getLevels().getNextToLastLevel(); - if (nextToLast == null) + if (nextToLast == null) { return true; + } Sector centerSector = nextToLast.computeSectorForPosition(vpc.getLatitude(), vpc.getLongitude(), - this.getLevels().getTileOrigin()); + this.getLevels().getTileOrigin()); return this.needToSplit(dc, centerSector); } // ============== Rendering ======================= // // ============== Rendering ======================= // // ============== Rendering ======================= // - @Override - public void render(DrawContext dc) - { + public void render(DrawContext dc) { this.atMaxResolution = this.atMaxLevel(dc); super.render(dc); } @Override - protected final void doRender(DrawContext dc) - { - if (this.forceLevelZeroLoads && !this.levelZeroLoaded) + protected final void doRender(DrawContext dc) { + if (this.forceLevelZeroLoads && !this.levelZeroLoaded) { this.loadAllTopLevelTextures(dc); + } if (dc.getSurfaceGeometry() == null - || dc.getSurfaceGeometry().size() < 1) + || dc.getSurfaceGeometry().size() < 1) { return; + } dc.getGeographicSurfaceTileRenderer().setShowImageTileOutlines( - this.showImageTileOutlines); + this.showImageTileOutlines); draw(dc); } - private void draw(DrawContext dc) - { + private void draw(DrawContext dc) { this.referencePoint = this.computeReferencePoint(dc); this.assembleTiles(dc); // Determine the tiles to draw. - if (this.currentTiles.size() >= 1) - { + if (this.currentTiles.size() >= 1) { MercatorTextureTile[] sortedTiles = new MercatorTextureTile[this.currentTiles - .size()]; + .size()]; sortedTiles = this.currentTiles.toArray(sortedTiles); Arrays.sort(sortedTiles, levelComparer); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (this.isUseTransparentTextures() || this.getOpacity() < 1) - { + if (this.isUseTransparentTextures() || this.getOpacity() < 1) { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_POLYGON_BIT - | GL2.GL_CURRENT_BIT); + | GL2.GL_CURRENT_BIT); gl.glColor4d(1d, 1d, 1d, this.getOpacity()); gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); - } - else - { + } else { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_POLYGON_BIT); } @@ -569,17 +520,19 @@ private void draw(DrawContext dc) gl.glCullFace(GL.GL_BACK); dc.setPerFrameStatistic(PerformanceStatistic.IMAGE_TILE_COUNT, - this.tileCountName, this.currentTiles.size()); + this.tileCountName, this.currentTiles.size()); dc.getGeographicSurfaceTileRenderer().renderTiles(dc, - this.currentTiles); + this.currentTiles); gl.glPopAttrib(); - if (this.drawTileIDs) + if (this.drawTileIDs) { this.drawTileIDs(dc, this.currentTiles); + } - if (this.drawBoundingVolumes) + if (this.drawBoundingVolumes) { this.drawBoundingVolumes(dc, this.currentTiles); + } this.currentTiles.clear(); } @@ -588,86 +541,77 @@ private void draw(DrawContext dc) this.requestQ.clear(); } - private void sendRequests() - { + private void sendRequests() { Runnable task = this.requestQ.poll(); - while (task != null) - { - if (!WorldWind.getTaskService().isFull()) - { + while (task != null) { + if (!WorldWind.getTaskService().isFull()) { WorldWind.getTaskService().addTask(task); } task = this.requestQ.poll(); } } - public boolean isLayerInView(DrawContext dc) - { - if (dc == null) - { + public boolean isLayerInView(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (dc.getView() == null) - { + if (dc.getView() == null) { String message = Logging - .getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); + .getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } return !(dc.getVisibleSector() != null && !this.levels.getSector() - .intersects(dc.getVisibleSector())); + .intersects(dc.getVisibleSector())); } - private Vec4 computeReferencePoint(DrawContext dc) - { - if (dc.getViewportCenterPosition() != null) + private Vec4 computeReferencePoint(DrawContext dc) { + if (dc.getViewportCenterPosition() != null) { return dc.getGlobe().computePointFromPosition( - dc.getViewportCenterPosition()); + dc.getViewportCenterPosition()); + } java.awt.geom.Rectangle2D viewport = dc.getView().getViewport(); int x = (int) viewport.getWidth() / 2; - for (int y = (int) (0.5 * viewport.getHeight()); y >= 0; y--) - { + for (int y = (int) (0.5 * viewport.getHeight()); y >= 0; y--) { Position pos = dc.getView().computePositionFromScreenPoint(x, y); - if (pos == null) + if (pos == null) { continue; + } return dc.getGlobe().computePointFromPosition(pos.getLatitude(), - pos.getLongitude(), 0d); + pos.getLongitude(), 0d); } return null; } - protected Vec4 getReferencePoint() - { + protected Vec4 getReferencePoint() { return this.referencePoint; } private static class LevelComparer implements - Comparator - { - public int compare(MercatorTextureTile ta, MercatorTextureTile tb) - { + Comparator { + + public int compare(MercatorTextureTile ta, MercatorTextureTile tb) { int la = ta.getFallbackTile() == null ? ta.getLevelNumber() : ta - .getFallbackTile().getLevelNumber(); + .getFallbackTile().getLevelNumber(); int lb = tb.getFallbackTile() == null ? tb.getLevelNumber() : tb - .getFallbackTile().getLevelNumber(); + .getFallbackTile().getLevelNumber(); return la < lb ? -1 : la == lb ? 0 : 1; } } private void drawTileIDs(DrawContext dc, - ArrayList tiles) - { + ArrayList tiles) { java.awt.Rectangle viewport = dc.getView().getViewport(); TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - java.awt.Font.decode("Arial-Plain-13")); + java.awt.Font.decode("Arial-Plain-13")); dc.getGL().glDisable(GL.GL_DEPTH_TEST); dc.getGL().glDisable(GL.GL_BLEND); @@ -675,19 +619,19 @@ private void drawTileIDs(DrawContext dc, textRenderer.setColor(java.awt.Color.YELLOW); textRenderer.beginRendering(viewport.width, viewport.height); - for (MercatorTextureTile tile : tiles) - { + for (MercatorTextureTile tile : tiles) { String tileLabel = tile.getLabel(); - if (tile.getFallbackTile() != null) + if (tile.getFallbackTile() != null) { tileLabel += "/" + tile.getFallbackTile().getLabel(); + } LatLon ll = tile.getSector().getCentroid(); Vec4 pt = dc.getGlobe().computePointFromPosition( - ll.getLatitude(), - ll.getLongitude(), - dc.getGlobe().getElevation(ll.getLatitude(), - ll.getLongitude())); + ll.getLatitude(), + ll.getLongitude(), + dc.getGlobe().getElevation(ll.getLatitude(), + ll.getLongitude())); pt = dc.getView().project(pt); textRenderer.draw(tileLabel, (int) pt.x, (int) pt.y); } @@ -695,21 +639,19 @@ private void drawTileIDs(DrawContext dc, } private void drawBoundingVolumes(DrawContext dc, - ArrayList tiles) - { + ArrayList tiles) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. float[] previousColor = new float[4]; gl.glGetFloatv(GL2.GL_CURRENT_COLOR, previousColor, 0); gl.glColor3d(0, 1, 0); - for (MercatorTextureTile tile : tiles) - { + for (MercatorTextureTile tile : tiles) { ((Cylinder) tile.getExtent(dc)).render(dc); } Cylinder c = Sector.computeBoundingCylinder(dc.getGlobe(), dc.getVerticalExaggeration(), - this.levels.getSector()); + this.levels.getSector()); gl.glColor3d(1, 1, 0); c.render(dc); @@ -719,77 +661,65 @@ private void drawBoundingVolumes(DrawContext dc, // ============== Image Composition ======================= // // ============== Image Composition ======================= // // ============== Image Composition ======================= // - - public List getAvailableImageFormats() - { + public List getAvailableImageFormats() { return new ArrayList(this.supportedImageFormats); } - public boolean isImageFormatAvailable(String imageFormat) - { + public boolean isImageFormatAvailable(String imageFormat) { return imageFormat != null - && this.supportedImageFormats.contains(imageFormat); + && this.supportedImageFormats.contains(imageFormat); } - public String getDefaultImageFormat() - { + public String getDefaultImageFormat() { return this.supportedImageFormats.size() > 0 ? this.supportedImageFormats - .get(0) - : null; + .get(0) + : null; } - protected void setAvailableImageFormats(String[] formats) - { + protected void setAvailableImageFormats(String[] formats) { this.supportedImageFormats.clear(); - if (formats != null) - { + if (formats != null) { this.supportedImageFormats.addAll(Arrays.asList(formats)); } } private BufferedImage requestImage(MercatorTextureTile tile, String mimeType) - throws URISyntaxException - { + throws URISyntaxException { String pathBase = tile.getPath().substring(0, - tile.getPath().lastIndexOf(".")); + tile.getPath().lastIndexOf(".")); String suffix = WWIO.makeSuffixForMimeType(mimeType); String path = pathBase + suffix; URL url = this.getDataFileStore().findFile(path, false); if (url == null) // image is not local + { return null; + } - if (WWIO.isFileOutOfDate(url, tile.getLevel().getExpiryTime())) - { + if (WWIO.isFileOutOfDate(url, tile.getLevel().getExpiryTime())) { // The file has expired. Delete it. this.getDataFileStore().removeFile(url); String message = Logging.getMessage("generic.DataFileExpired", url); Logging.logger().fine(message); - } - else - { - try - { + } else { + try { File imageFile = new File(url.toURI()); BufferedImage image = ImageIO.read(imageFile); - if (image == null) - { + if (image == null) { String message = Logging.getMessage( - "generic.ImageReadFailed", imageFile); + "generic.ImageReadFailed", imageFile); throw new RuntimeException(message); } this.levels.unmarkResourceAbsent(tile); return image; - } - catch (IOException e) - { + } catch (IOException e) { // Assume that something's wrong with the file and delete it. this.getDataFileStore().removeFile(url); this.levels.markResourceAbsent(tile); String message = Logging.getMessage( - "generic.DeletedCorruptDataFile", url); + "generic.DeletedCorruptDataFile", url); Logging.logger().info(message); } } @@ -798,24 +728,20 @@ private BufferedImage requestImage(MercatorTextureTile tile, String mimeType) } private void downloadImage(final MercatorTextureTile tile, String mimeType) - throws Exception - { + throws Exception { // System.out.println(tile.getPath()); final URL resourceURL = tile.getResourceURL(mimeType); Retriever retriever; String protocol = resourceURL.getProtocol(); - if ("http".equalsIgnoreCase(protocol)) - { + if ("http".equalsIgnoreCase(protocol)) { retriever = new HTTPRetriever(resourceURL, new HttpRetrievalPostProcessor(tile)); retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers - } - else - { + } else { String message = Logging - .getMessage("layers.TextureLayer.UnknownRetrievalProtocol", - resourceURL); + .getMessage("layers.TextureLayer.UnknownRetrievalProtocol", + resourceURL); throw new RuntimeException(message); } @@ -825,17 +751,14 @@ private void downloadImage(final MercatorTextureTile tile, String mimeType) } public int computeLevelForResolution(Sector sector, Globe globe, - double resolution) - { - if (sector == null) - { + double resolution) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -843,115 +766,108 @@ public int computeLevelForResolution(Sector sector, Globe globe, double texelSize = 0; Level targetLevel = this.levels.getLastLevel(); - for (int i = 0; i < this.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (this.levels.isLevelEmpty(i)) + for (int i = 0; i < this.getLevels().getLastLevel().getLevelNumber(); i++) { + if (this.levels.isLevelEmpty(i)) { continue; + } texelSize = this.levels.getLevel(i).getTexelSize(); - if (texelSize > resolution) + if (texelSize > resolution) { continue; + } targetLevel = this.levels.getLevel(i); break; } Logging.logger().info( - Logging.getMessage("layers.TiledImageLayer.LevelSelection", - targetLevel.getLevelNumber(), texelSize)); + Logging.getMessage("layers.TiledImageLayer.LevelSelection", + targetLevel.getLevelNumber(), texelSize)); return targetLevel.getLevelNumber(); } public BufferedImage composeImageForSector(Sector sector, int imageWidth, - int imageHeight, int levelNumber, String mimeType, - boolean abortOnError, BufferedImage image) - { - if (sector == null) - { + int imageHeight, int levelNumber, String mimeType, + boolean abortOnError, BufferedImage image) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (levelNumber < 0) - { + if (levelNumber < 0) { levelNumber = this.levels.getLastLevel().getLevelNumber(); - } - else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) - { + } else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) { Logging.logger().warning( - Logging.getMessage( - "generic.LevelRequestedGreaterThanMaxLevel", - levelNumber, this.levels.getLastLevel() - .getLevelNumber())); + Logging.getMessage( + "generic.LevelRequestedGreaterThanMaxLevel", + levelNumber, this.levels.getLastLevel() + .getLevelNumber())); levelNumber = this.levels.getLastLevel().getLevelNumber(); } MercatorTextureTile[][] tiles = this.getTilesInSector(sector, - levelNumber); + levelNumber); - if (tiles.length == 0 || tiles[0].length == 0) - { + if (tiles.length == 0 || tiles[0].length == 0) { Logging - .logger() - .severe( - Logging - .getMessage("layers.TiledImageLayer.NoImagesAvailable")); + .logger() + .severe( + Logging + .getMessage("layers.TiledImageLayer.NoImagesAvailable")); return null; } - if (image == null) + if (image == null) { image = new BufferedImage(imageWidth, imageHeight, - BufferedImage.TYPE_INT_RGB); + BufferedImage.TYPE_INT_RGB); + } Graphics2D g = image.createGraphics(); - for (MercatorTextureTile[] row : tiles) - { - for (MercatorTextureTile tile : row) - { - if (tile == null) + for (MercatorTextureTile[] row : tiles) { + for (MercatorTextureTile tile : row) { + if (tile == null) { continue; + } BufferedImage tileImage; - try - { + try { tileImage = this.getImage(tile, mimeType); double sh = ((double) imageHeight / (double) tileImage - .getHeight()) - * (tile.getSector().getDeltaLat().divide(sector - .getDeltaLat())); + .getHeight()) + * (tile.getSector().getDeltaLat().divide(sector + .getDeltaLat())); double sw = ((double) imageWidth / (double) tileImage - .getWidth()) - * (tile.getSector().getDeltaLon().divide(sector - .getDeltaLon())); + .getWidth()) + * (tile.getSector().getDeltaLon().divide(sector + .getDeltaLon())); double dh = imageHeight - * (-tile.getSector().getMaxLatitude().subtract( - sector.getMaxLatitude()).degrees / sector - .getDeltaLat().degrees); + * (-tile.getSector().getMaxLatitude().subtract( + sector.getMaxLatitude()).degrees / sector + .getDeltaLat().degrees); double dw = imageWidth - * (tile.getSector().getMinLongitude().subtract( - sector.getMinLongitude()).degrees / sector - .getDeltaLon().degrees); + * (tile.getSector().getMinLongitude().subtract( + sector.getMinLongitude()).degrees / sector + .getDeltaLon().degrees); AffineTransform txf = g.getTransform(); g.translate(dw, dh); g.scale(sw, sh); g.drawImage(tileImage, 0, 0, null); g.setTransform(txf); - } - catch (Exception e) - { - if (abortOnError) + } catch (Exception e) { + if (abortOnError) { throw new RuntimeException(e); + } String message = Logging.getMessage( - "generic.ExceptionWhileRequestingImage", tile - .getPath()); + "generic.ExceptionWhileRequestingImage", tile + .getPath()); Logging.logger().log(java.util.logging.Level.WARNING, - message, e); + message, e); } } } @@ -959,23 +875,20 @@ else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) return image; } - public int countImagesInSector(Sector sector, int levelNumber) - { - if (sector == null) - { + public int countImagesInSector(Sector sector, int levelNumber) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.levels.getLastLevel(); - if (levelNumber >= 0) - { + if (levelNumber >= 0) { for (int i = levelNumber; i < this.getLevels().getLastLevel() - .getLevelNumber(); i++) - { - if (this.levels.isLevelEmpty(i)) + .getLevelNumber(); i++) { + if (this.levels.isLevelEmpty(i)) { continue; + } targetLevel = this.levels.getLevel(i); break; @@ -987,13 +900,13 @@ public int countImagesInSector(Sector sector, int levelNumber) Angle latOrigin = this.levels.getTileOrigin().getLatitude(); Angle lonOrigin = this.levels.getTileOrigin().getLongitude(); final int nwRow = Tile.computeRow(delta.getLatitude(), sector - .getMaxLatitude(), latOrigin); + .getMaxLatitude(), latOrigin); final int nwCol = Tile.computeColumn(delta.getLongitude(), sector - .getMinLongitude(), lonOrigin); + .getMinLongitude(), lonOrigin); final int seRow = Tile.computeRow(delta.getLatitude(), sector - .getMinLatitude(), latOrigin); + .getMinLatitude(), latOrigin); final int seCol = Tile.computeColumn(delta.getLongitude(), sector - .getMaxLongitude(), lonOrigin); + .getMaxLongitude(), lonOrigin); int numRows = nwRow - seRow + 1; int numCols = seCol - nwCol + 1; @@ -1002,23 +915,20 @@ public int countImagesInSector(Sector sector, int levelNumber) } private MercatorTextureTile[][] getTilesInSector(Sector sector, - int levelNumber) - { - if (sector == null) - { + int levelNumber) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.levels.getLastLevel(); - if (levelNumber >= 0) - { + if (levelNumber >= 0) { for (int i = levelNumber; i < this.getLevels().getLastLevel() - .getLevelNumber(); i++) - { - if (this.levels.isLevelEmpty(i)) + .getLevelNumber(); i++) { + if (this.levels.isLevelEmpty(i)) { continue; + } targetLevel = this.levels.getLevel(i); break; @@ -1030,28 +940,26 @@ private MercatorTextureTile[][] getTilesInSector(Sector sector, Angle latOrigin = this.levels.getTileOrigin().getLatitude(); Angle lonOrigin = this.levels.getTileOrigin().getLongitude(); final int nwRow = Tile.computeRow(delta.getLatitude(), sector - .getMaxLatitude(), latOrigin); + .getMaxLatitude(), latOrigin); final int nwCol = Tile.computeColumn(delta.getLongitude(), sector - .getMinLongitude(), lonOrigin); + .getMinLongitude(), lonOrigin); final int seRow = Tile.computeRow(delta.getLatitude(), sector - .getMinLatitude(), latOrigin); + .getMinLatitude(), latOrigin); final int seCol = Tile.computeColumn(delta.getLongitude(), sector - .getMaxLongitude(), lonOrigin); + .getMaxLongitude(), lonOrigin); int numRows = nwRow - seRow + 1; int numCols = seCol - nwCol + 1; MercatorTextureTile[][] sectorTiles = new MercatorTextureTile[numRows][numCols]; - for (int row = nwRow; row >= seRow; row--) - { - for (int col = nwCol; col <= seCol; col++) - { + for (int row = nwRow; row >= seRow; row--) { + for (int col = nwCol; col <= seCol; col++) { TileKey key = new TileKey(targetLevel.getLevelNumber(), row, - col, targetLevel.getCacheName()); + col, targetLevel.getCacheName()); Sector tileSector = this.levels.computeSectorForKey(key); MercatorSector mSector = MercatorSector.fromSector(tileSector); //TODO: check sectorTiles[nwRow - row][col - nwCol] = new MercatorTextureTile( - mSector, targetLevel, row, col); + mSector, targetLevel, row, col); } } @@ -1059,78 +967,73 @@ private MercatorTextureTile[][] getTilesInSector(Sector sector, } private BufferedImage getImage(MercatorTextureTile tile, String mimeType) - throws Exception - { + throws Exception { // Read the image from disk. BufferedImage image = this.requestImage(tile, mimeType); - if (image != null) + if (image != null) { return image; + } // Retrieve it from the net since it's not on disk. this.downloadImage(tile, mimeType); // Try to read from disk again after retrieving it from the net. image = this.requestImage(tile, mimeType); - if (image == null) - { + if (image == null) { String message = Logging.getMessage( - "layers.TiledImageLayer.ImageUnavailable", tile.getPath()); + "layers.TiledImageLayer.ImageUnavailable", tile.getPath()); throw new RuntimeException(message); } return image; } - private class HttpRetrievalPostProcessor implements RetrievalPostProcessor - { + private class HttpRetrievalPostProcessor implements RetrievalPostProcessor { + private MercatorTextureTile tile; - public HttpRetrievalPostProcessor(MercatorTextureTile tile) - { + public HttpRetrievalPostProcessor(MercatorTextureTile tile) { this.tile = tile; } - public ByteBuffer run(Retriever retriever) - { + public ByteBuffer run(Retriever retriever) { if (!retriever.getState().equals( - Retriever.RETRIEVER_STATE_SUCCESSFUL)) + Retriever.RETRIEVER_STATE_SUCCESSFUL)) { return null; + } HTTPRetriever htr = (HTTPRetriever) retriever; - if (htr.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) - { + if (htr.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { // Mark tile as missing to avoid excessive attempts MercatorTiledImageLayer.this.levels.markResourceAbsent(tile); return null; } - if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) + if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; + } URLRetriever r = (URLRetriever) retriever; ByteBuffer buffer = r.getBuffer(); String suffix = WWIO.makeSuffixForMimeType(htr.getContentType()); - if (suffix == null) - { + if (suffix == null) { return null; // TODO: log error } String path = tile.getPath().substring(0, - tile.getPath().lastIndexOf(".")); + tile.getPath().lastIndexOf(".")); path += suffix; final File outFile = getDataFileStore().newFile(path); - if (outFile == null) + if (outFile == null) { return null; + } - try - { + try { WWIO.saveBuffer(buffer, outFile); return buffer; - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); // TODO: log error return null; } diff --git a/src/gov/nasa/worldwind/layers/placename/PlaceNameLayer.java b/src/gov/nasa/worldwind/layers/placename/PlaceNameLayer.java index 5db0ca0294..edab51cc37 100644 --- a/src/gov/nasa/worldwind/layers/placename/PlaceNameLayer.java +++ b/src/gov/nasa/worldwind/layers/placename/PlaceNameLayer.java @@ -26,8 +26,8 @@ * @author Paul Collins * @version $Id: PlaceNameLayer.java 2392 2014-10-20 20:02:44Z tgaskins $ */ -public class PlaceNameLayer extends AbstractLayer implements BulkRetrievable -{ +public class PlaceNameLayer extends AbstractLayer implements BulkRetrievable { + protected final PlaceNameServiceSet placeNameServiceSet; protected PriorityBlockingQueue requestQ = new PriorityBlockingQueue(64); protected Vec4 referencePoint; @@ -67,12 +67,10 @@ public class PlaceNameLayer extends AbstractLayer implements BulkRetrievable /** * @param placeNameServiceSet the set of PlaceNameService objects that PlaceNameLayer will render. * - * @throws IllegalArgumentException if {@link gov.nasa.worldwind.layers.placename.PlaceNameServiceSet} is null + * @throws IllegalArgumentException if {@link gov.nasa.worldwind.layers.placename.PlaceNameServiceSet} is null */ - public PlaceNameLayer(PlaceNameServiceSet placeNameServiceSet) - { - if (placeNameServiceSet == null) - { + public PlaceNameLayer(PlaceNameServiceSet placeNameServiceSet) { + if (placeNameServiceSet == null) { String message = Logging.getMessage("nullValue.PlaceNameServiceSetIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -80,19 +78,17 @@ public PlaceNameLayer(PlaceNameServiceSet placeNameServiceSet) // this.placeNameServiceSet = placeNameServiceSet.deepCopy(); - for (int i = 0; i < this.placeNameServiceSet.getServiceCount(); i++) - { + for (int i = 0; i < this.placeNameServiceSet.getServiceCount(); i++) { //todo do this for long as well and pick min int calc1 = (int) (PlaceNameService.TILING_SECTOR.getDeltaLatDegrees() - / this.placeNameServiceSet.getService(i).getTileDelta().getLatitude().getDegrees()); + / this.placeNameServiceSet.getService(i).getTileDelta().getLatitude().getDegrees()); int numLevels = (int) Math.log(calc1); navTiles.add( - new NavigationTile(this.placeNameServiceSet.getService(i), PlaceNameService.TILING_SECTOR, numLevels, - "top")); + new NavigationTile(this.placeNameServiceSet.getService(i), PlaceNameService.TILING_SECTOR, numLevels, + "top")); } - if (!WorldWind.getMemoryCacheSet().containsCache(Tile.class.getName())) - { + if (!WorldWind.getMemoryCacheSet().containsCache(Tile.class.getName())) { long size = Configuration.getLongValue(AVKey.PLACENAME_LAYER_CACHE_SIZE, 2000000L); MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size); cache.setName("Placename Tiles"); @@ -105,8 +101,7 @@ public PlaceNameLayer(PlaceNameServiceSet placeNameServiceSet) * * @deprecated This flag no longer has any effect. Placenames participate in global decluttering. */ - public boolean isCullNames() - { + public boolean isCullNames() { return cullNames; } @@ -115,27 +110,23 @@ public boolean isCullNames() * * @deprecated This flag no longer has any effect. Placenames participate in global decluttering. */ - public void setCullNames(boolean cullNames) - { + public void setCullNames(boolean cullNames) { this.cullNames = cullNames; } - public final PlaceNameServiceSet getPlaceNameServiceSet() - { + public final PlaceNameServiceSet getPlaceNameServiceSet() { return this.placeNameServiceSet; } - protected PriorityBlockingQueue getRequestQ() - { + protected PriorityBlockingQueue getRequestQ() { return this.requestQ; } // ============== Tile Assembly ======================= // // ============== Tile Assembly ======================= // // ============== Tile Assembly ======================= // + protected class NavigationTile { - protected class NavigationTile - { String id; protected PlaceNameService placeNameService; public Sector navSector; @@ -143,43 +134,35 @@ protected class NavigationTile protected List tileKeys = new ArrayList(); protected int level; - NavigationTile(PlaceNameService placeNameService, Sector sector, int levels, String id) - { + NavigationTile(PlaceNameService placeNameService, Sector sector, int levels, String id) { this.placeNameService = placeNameService; this.id = id; this.navSector = sector; level = levels; } - protected void buildSubNavTiles() - { - if (level > 0) - { + protected void buildSubNavTiles() { + if (level > 0) { //split sector, create a navTile for each quad Sector[] subSectors = this.navSector.subdivide(); - for (int j = 0; j < subSectors.length; j++) - { + for (int j = 0; j < subSectors.length; j++) { subNavTiles.add(new NavigationTile(placeNameService, subSectors[j], level - 1, this.id + "." + j)); } } } - public List navTilesVisible(DrawContext dc, double minDistSquared, double maxDistSquared) - { + public List navTilesVisible(DrawContext dc, double minDistSquared, double maxDistSquared) { ArrayList navList = new ArrayList(); - if (this.isNavSectorVisible(dc, minDistSquared, maxDistSquared)) - { - if (this.level > 0 && !this.hasSubTiles()) + if (this.isNavSectorVisible(dc, minDistSquared, maxDistSquared)) { + if (this.level > 0 && !this.hasSubTiles()) { this.buildSubNavTiles(); + } - if (this.hasSubTiles()) - { - for (NavigationTile nav : subNavTiles) - { + if (this.hasSubTiles()) { + for (NavigationTile nav : subNavTiles) { navList.addAll(nav.navTilesVisible(dc, minDistSquared, maxDistSquared)); } - } - else //at bottom level navigation tile + } else //at bottom level navigation tile { navList.add(this); } @@ -188,76 +171,68 @@ public List navTilesVisible(DrawContext dc, double minDistSquare return navList; } - public boolean hasSubTiles() - { + public boolean hasSubTiles() { return !subNavTiles.isEmpty(); } - protected boolean isNavSectorVisible(DrawContext dc, double minDistanceSquared, double maxDistanceSquared) - { - if (!navSector.intersects(dc.getVisibleSector())) + protected boolean isNavSectorVisible(DrawContext dc, double minDistanceSquared, double maxDistanceSquared) { + if (!navSector.intersects(dc.getVisibleSector())) { return false; + } - if (dc.is2DGlobe()) - { - Sector limits = ((Globe2D)dc.getGlobe()).getProjection().getProjectionLimits(); - if (limits != null && !limits.intersectsInterior(navSector)) + if (dc.is2DGlobe()) { + Sector limits = ((Globe2D) dc.getGlobe()).getProjection().getProjectionLimits(); + if (limits != null && !limits.intersectsInterior(navSector)) { return false; + } } View view = dc.getView(); Position eyePos = view.getEyePosition(); - if (eyePos == null) + if (eyePos == null) { return false; + } //check for eyePos over globe - if (Double.isNaN(eyePos.getLatitude().getDegrees()) || Double.isNaN(eyePos.getLongitude().getDegrees())) + if (Double.isNaN(eyePos.getLatitude().getDegrees()) || Double.isNaN(eyePos.getLongitude().getDegrees())) { return false; + } double distSquared; - if (dc.isContinuous2DGlobe()) - { + if (dc.isContinuous2DGlobe()) { // Just use the eye altitude since the majority of non-visible sectors are culled elsewhere. distSquared = eyePos.getAltitude() * eyePos.getAltitude(); - } - else - { + } else { Angle lat = clampAngle(eyePos.getLatitude(), navSector.getMinLatitude(), - navSector.getMaxLatitude()); + navSector.getMaxLatitude()); Angle lon = clampAngle(eyePos.getLongitude(), navSector.getMinLongitude(), - navSector.getMaxLongitude()); + navSector.getMaxLongitude()); Vec4 p = dc.getGlobe().computePointFromPosition(lat, lon, 0d); distSquared = dc.getView().getEyePoint().distanceToSquared3(p); } //noinspection RedundantIfStatement - if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) + if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) { return false; + } return true; } - public List getTiles() - { - if (tileKeys.isEmpty()) - { + public List getTiles() { + if (tileKeys.isEmpty()) { Tile[] tiles = buildTiles(this.placeNameService, this); //load tileKeys - for (Tile t : tiles) - { + for (Tile t : tiles) { tileKeys.add(t.getFileCachePath()); WorldWind.getMemoryCache(Tile.class.getName()).add(t.getFileCachePath(), t); } return Arrays.asList(tiles); - } - else - { + } else { List dataTiles = new ArrayList(); - for (String s : tileKeys) - { + for (String s : tileKeys) { Tile t = (Tile) WorldWind.getMemoryCache(Tile.class.getName()).getObject(s); - if (t != null) - { + if (t != null) { dataTiles.add(t); } } @@ -266,8 +241,8 @@ public List getTiles() } } - protected static class Tile implements Cacheable - { + protected static class Tile implements Cacheable { + protected final PlaceNameService placeNameService; protected final Sector sector; protected final int row; @@ -279,8 +254,7 @@ protected static class Tile implements Cacheable protected double priority = Double.MAX_VALUE; // Default is minimum priority protected PlaceNameChunk dataChunk = null; - Tile(PlaceNameService placeNameService, Sector sector, int row, int column) - { + Tile(PlaceNameService placeNameService, Sector sector, int row, int column) { this.placeNameService = placeNameService; this.sector = sector; this.row = row; @@ -289,37 +263,32 @@ protected static class Tile implements Cacheable this.hashInt = this.computeHash(); } - public void setDataChunk(PlaceNameChunk chunk) - { + public void setDataChunk(PlaceNameChunk chunk) { dataChunk = chunk; } - public PlaceNameChunk getDataChunk() - { + public PlaceNameChunk getDataChunk() { return dataChunk; } - public long getSizeInBytes() - { + public long getSizeInBytes() { long result = 32; //references result += this.getSector().getSizeInBytes(); - if (this.getFileCachePath() != null) + if (this.getFileCachePath() != null) { result += this.getFileCachePath().length(); + } - if (dataChunk != null) - { + if (dataChunk != null) { result += dataChunk.estimatedMemorySize; } return result; } - static int computeRow(Angle delta, Angle latitude) - { - if (delta == null || latitude == null) - { + static int computeRow(Angle delta, Angle latitude) { + if (delta == null || latitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -327,10 +296,8 @@ static int computeRow(Angle delta, Angle latitude) return (int) ((latitude.getDegrees() + 90d) / delta.getDegrees()); } - static int computeColumn(Angle delta, Angle longitude) - { - if (delta == null || longitude == null) - { + static int computeColumn(Angle delta, Angle longitude) { + if (delta == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -338,10 +305,8 @@ static int computeColumn(Angle delta, Angle longitude) return (int) ((longitude.getDegrees() + 180d) / delta.getDegrees()); } - static Angle computeRowLatitude(int row, Angle delta) - { - if (delta == null) - { + static Angle computeRowLatitude(int row, Angle delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -349,10 +314,8 @@ static Angle computeRowLatitude(int row, Angle delta) return Angle.fromDegrees(-90d + delta.getDegrees() * row); } - static Angle computeColumnLongitude(int column, Angle delta) - { - if (delta == null) - { + static Angle computeColumnLongitude(int column, Angle delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -360,77 +323,68 @@ static Angle computeColumnLongitude(int column, Angle delta) return Angle.fromDegrees(-180 + delta.getDegrees() * column); } - public Integer getHashInt() - { + public Integer getHashInt() { return hashInt; } - int computeHash() - { + int computeHash() { return this.getFileCachePath() != null ? this.getFileCachePath().hashCode() : 0; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final Tile tile = (Tile) o; return !(this.getFileCachePath() != null ? !this.getFileCachePath().equals(tile.getFileCachePath()) - : tile.getFileCachePath() != null); + : tile.getFileCachePath() != null); } - public String getFileCachePath() - { - if (this.fileCachePath == null) + public String getFileCachePath() { + if (this.fileCachePath == null) { this.fileCachePath = this.placeNameService.createFileCachePathFromTile(this.row, this.column); + } return this.fileCachePath; } - public PlaceNameService getPlaceNameService() - { + public PlaceNameService getPlaceNameService() { return placeNameService; } - public java.net.URL getRequestURL() throws java.net.MalformedURLException - { + public java.net.URL getRequestURL() throws java.net.MalformedURLException { return this.placeNameService.createServiceURLFromSector(this.sector); } - public Sector getSector() - { + public Sector getSector() { return sector; } - public int hashCode() - { + public int hashCode() { return this.hashInt; } - protected boolean isTileInMemoryWithData() - { + protected boolean isTileInMemoryWithData() { Tile t = (Tile) WorldWind.getMemoryCache(Tile.class.getName()).getObject(this.getFileCachePath()); return !(t == null || t.getDataChunk() == null); } - public double getPriority() - { + public double getPriority() { return priority; } - public void setPriority(double priority) - { + public void setPriority(double priority) { this.priority = priority; } } - protected Tile[] buildTiles(PlaceNameService placeNameService, NavigationTile navTile) - { + protected Tile[] buildTiles(PlaceNameService placeNameService, NavigationTile navTile) { final Angle dLat = placeNameService.getTileDelta().getLatitude(); final Angle dLon = placeNameService.getTileDelta().getLongitude(); @@ -446,19 +400,17 @@ protected Tile[] buildTiles(PlaceNameService placeNameService, NavigationTile na Tile[] tiles = new Tile[nLatTiles * nLonTiles]; Angle p1 = Tile.computeRowLatitude(firstRow, dLat); - for (int row = 0; row <= lastRow - firstRow; row++) - { + for (int row = 0; row <= lastRow - firstRow; row++) { Angle p2; p2 = p1.add(dLat); Angle t1 = Tile.computeColumnLongitude(firstCol, dLon); - for (int col = 0; col <= lastCol - firstCol; col++) - { + for (int col = 0; col <= lastCol - firstCol; col++) { Angle t2; t2 = t1.add(dLon); //Need offset row and column to correspond to total ro/col numbering tiles[col + row * nLonTiles] = new Tile(placeNameService, new Sector(p1, p2, t1, t2), - row + firstRow, col + firstCol); + row + firstRow, col + firstCol); t1 = t2; } p1 = p2; @@ -470,9 +422,8 @@ protected Tile[] buildTiles(PlaceNameService placeNameService, NavigationTile na // ============== Place Name Data Structures ======================= // // ============== Place Name Data Structures ======================= // // ============== Place Name Data Structures ======================= // + protected static class PlaceNameChunk implements Cacheable { - protected static class PlaceNameChunk implements Cacheable - { protected final PlaceNameService placeNameService; protected final CharBuffer textArray; protected final int[] textIndexArray; @@ -481,8 +432,7 @@ protected static class PlaceNameChunk implements Cacheable protected final long estimatedMemorySize; protected PlaceNameChunk(PlaceNameService service, CharBuffer text, int[] textIndices, - double[] positions, int numEntries) - { + double[] positions, int numEntries) { this.placeNameService = service; this.textArray = text; this.textIndexArray = textIndices; @@ -491,29 +441,26 @@ protected PlaceNameChunk(PlaceNameService service, CharBuffer text, int[] textIn this.estimatedMemorySize = this.computeEstimatedMemorySize(); } - protected long computeEstimatedMemorySize() - { + protected long computeEstimatedMemorySize() { long result = 0; - if (!textArray.isDirect()) + if (!textArray.isDirect()) { result += (Character.SIZE / 8) * textArray.capacity(); + } result += (Integer.SIZE / 8) * textIndexArray.length; result += (Double.SIZE / 8) * latlonArray.length; return result; } - protected Position getPosition(int index) - { + protected Position getPosition(int index) { int latlonIndex = 2 * index; return Position.fromDegrees(latlonArray[latlonIndex], latlonArray[latlonIndex + 1], 0); } - protected PlaceNameService getPlaceNameService() - { + protected PlaceNameService getPlaceNameService() { return this.placeNameService; } - protected CharSequence getText(int index) - { + protected CharSequence getText(int index) { int beginIndex = textIndexArray[index]; int endIndex = (index + 1 < numEntries) ? textIndexArray[index + 1] : textArray.length(); @@ -524,18 +471,15 @@ protected CharSequence getText(int index) return ((CharSequence) this.textArray).subSequence(beginIndex, endIndex); } - public long getSizeInBytes() - { + public long getSizeInBytes() { return this.estimatedMemorySize; } - protected Iterable makeIterable(DrawContext dc) - { + protected Iterable makeIterable(DrawContext dc) { //get dispay dist for this service for use in label annealing double maxDisplayDistance = this.getPlaceNameService().getMaxDisplayDistance(); ArrayList list = new ArrayList(); - for (int i = 0; i < this.numEntries; i++) - { + for (int i = 0; i < this.numEntries; i++) { CharSequence str = getText(i); Position pos = getPosition(i); GeographicText text = new UserFacingText(str, pos); @@ -553,44 +497,36 @@ protected Iterable makeIterable(DrawContext dc) // ============== Rendering ======================= // // ============== Rendering ======================= // // ============== Rendering ======================= // - @Override - protected void doRender(DrawContext dc) - { + protected void doRender(DrawContext dc) { this.referencePoint = this.computeReferencePoint(dc); int serviceCount = this.placeNameServiceSet.getServiceCount(); - for (int i = 0; i < serviceCount; i++) - { + for (int i = 0; i < serviceCount; i++) { PlaceNameService placeNameService = this.placeNameServiceSet.getService(i); - if (!isServiceVisible(dc, placeNameService)) + if (!isServiceVisible(dc, placeNameService)) { continue; + } double minDistSquared = placeNameService.getMinDisplayDistance() * placeNameService.getMinDisplayDistance(); double maxDistSquared = placeNameService.getMaxDisplayDistance() * placeNameService.getMaxDisplayDistance(); - if (isSectorVisible(dc, placeNameService.getMaskingSector(), minDistSquared, maxDistSquared)) - { + if (isSectorVisible(dc, placeNameService.getMaskingSector(), minDistSquared, maxDistSquared)) { ArrayList baseTiles = new ArrayList(); NavigationTile navTile = this.navTiles.get(i); //drill down into tiles to find bottom level navTiles visible List list = navTile.navTilesVisible(dc, minDistSquared, maxDistSquared); - for (NavigationTile nt : list) - { + for (NavigationTile nt : list) { baseTiles.addAll(nt.getTiles()); } - for (Tile tile : baseTiles) - { - try - { + for (Tile tile : baseTiles) { + try { drawOrRequestTile(dc, tile, minDistSquared, maxDistSquared); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.FINE, - Logging.getMessage("layers.PlaceNameLayer.ExceptionRenderingTile"), - e); + Logging.getMessage("layers.PlaceNameLayer.ExceptionRenderingTile"), + e); } } } @@ -600,18 +536,18 @@ protected void doRender(DrawContext dc) this.requestQ.clear(); } - protected Vec4 computeReferencePoint(DrawContext dc) - { - if (dc.getViewportCenterPosition() != null) + protected Vec4 computeReferencePoint(DrawContext dc) { + if (dc.getViewportCenterPosition() != null) { return dc.getGlobe().computePointFromPosition(dc.getViewportCenterPosition()); + } java.awt.geom.Rectangle2D viewport = dc.getView().getViewport(); int x = (int) viewport.getWidth() / 2; - for (int y = (int) (0.5 * viewport.getHeight()); y >= 0; y--) - { + for (int y = (int) (0.5 * viewport.getHeight()); y >= 0; y--) { Position pos = dc.getView().computePositionFromScreenPoint(x, y); - if (pos == null) + if (pos == null) { continue; + } return dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), 0d); } @@ -619,22 +555,19 @@ protected Vec4 computeReferencePoint(DrawContext dc) return null; } - protected Vec4 getReferencePoint() - { + protected Vec4 getReferencePoint() { return this.referencePoint; } protected void drawOrRequestTile(DrawContext dc, Tile tile, double minDisplayDistanceSquared, - double maxDisplayDistanceSquared) - { - if (!isTileVisible(dc, tile, minDisplayDistanceSquared, maxDisplayDistanceSquared)) + double maxDisplayDistanceSquared) { + if (!isTileVisible(dc, tile, minDisplayDistanceSquared, maxDisplayDistanceSquared)) { return; + } - if (tile.isTileInMemoryWithData()) - { + if (tile.isTileInMemoryWithData()) { PlaceNameChunk placeNameChunk = tile.getDataChunk(); - if (placeNameChunk.numEntries > 0) - { + if (placeNameChunk.numEntries > 0) { Iterable renderIter = placeNameChunk.makeIterable(dc); dc.getDeclutteringTextRenderer().render(dc, renderIter); } @@ -643,17 +576,16 @@ protected void drawOrRequestTile(DrawContext dc, Tile tile, double minDisplayDis // Tile's data isn't available, so request it if (!tile.getPlaceNameService().isResourceAbsent(tile.getPlaceNameService().getTileNumber( - tile.row, tile.column))) - { + tile.row, tile.column))) { this.requestTile(dc, tile); } } - protected static boolean isServiceVisible(DrawContext dc, PlaceNameService placeNameService) - { + protected static boolean isServiceVisible(DrawContext dc, PlaceNameService placeNameService) { //noinspection SimplifiableIfStatement - if (!placeNameService.isEnabled()) + if (!placeNameService.isEnabled()) { return false; + } return (dc.getVisibleSector() != null) && placeNameService.getMaskingSector().intersects(dc.getVisibleSector()); // @@ -661,84 +593,79 @@ protected static boolean isServiceVisible(DrawContext dc, PlaceNameService place } protected static boolean isSectorVisible(DrawContext dc, Sector sector, double minDistanceSquared, - double maxDistanceSquared) - { + double maxDistanceSquared) { View view = dc.getView(); Position eyePos = view.getEyePosition(); - if (eyePos == null) + if (eyePos == null) { return false; + } double distSquared; - if (dc.isContinuous2DGlobe()) - { + if (dc.isContinuous2DGlobe()) { // Just use the eye altitude since the majority of non-visible sectors are culled elsewhere. distSquared = eyePos.getAltitude() * eyePos.getAltitude(); - } - else - { + } else { Angle lat = clampAngle(eyePos.getLatitude(), sector.getMinLatitude(), - sector.getMaxLatitude()); + sector.getMaxLatitude()); Angle lon = clampAngle(eyePos.getLongitude(), sector.getMinLongitude(), - sector.getMaxLongitude()); + sector.getMaxLongitude()); Vec4 p = dc.getGlobe().computePointFromPosition(lat, lon, 0d); distSquared = dc.getView().getEyePoint().distanceToSquared3(p); } //noinspection RedundantIfStatement - if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) + if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) { return false; + } return true; } protected static boolean isTileVisible(DrawContext dc, Tile tile, double minDistanceSquared, - double maxDistanceSquared) - { - if (!tile.getSector().intersects(dc.getVisibleSector())) + double maxDistanceSquared) { + if (!tile.getSector().intersects(dc.getVisibleSector())) { return false; + } View view = dc.getView(); Position eyePos = view.getEyePosition(); - if (eyePos == null) + if (eyePos == null) { return false; + } double distSquared; - if (dc.isContinuous2DGlobe()) - { + if (dc.isContinuous2DGlobe()) { // Just use the eye altitude since the majority of non-visible sectors are culled elsewhere. distSquared = eyePos.getAltitude() * eyePos.getAltitude(); - } - else - { + } else { Angle lat = clampAngle(eyePos.getLatitude(), tile.getSector().getMinLatitude(), - tile.getSector().getMaxLatitude()); + tile.getSector().getMaxLatitude()); Angle lon = clampAngle(eyePos.getLongitude(), tile.getSector().getMinLongitude(), - tile.getSector().getMaxLongitude()); + tile.getSector().getMaxLongitude()); Vec4 p = dc.getGlobe().computePointFromPosition(lat, lon, 0d); distSquared = dc.getView().getEyePoint().distanceToSquared3(p); } //noinspection RedundantIfStatement - if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) + if (minDistanceSquared > distSquared || maxDistanceSquared < distSquared) { return false; + } return true; } - protected static boolean isNameVisible(DrawContext dc, PlaceNameService service, Position namePosition) - { + protected static boolean isNameVisible(DrawContext dc, PlaceNameService service, Position namePosition) { double elevation = dc.getVerticalExaggeration() * namePosition.getElevation(); Vec4 namePoint = dc.getGlobe().computePointFromPosition(namePosition.getLatitude(), - namePosition.getLongitude(), elevation); + namePosition.getLongitude(), elevation); Vec4 eyeVec = dc.getView().getEyePoint(); double dist = eyeVec.distanceTo3(namePoint); return dist >= service.getMinDisplayDistance() && dist <= service.getMaxDisplayDistance(); } - protected static Angle clampAngle(Angle a, Angle min, Angle max) - { + protected static Angle clampAngle(Angle a, Angle min, Angle max) { double degrees = a.degrees; double minDegrees = min.degrees; double maxDegrees = max.degrees; @@ -748,57 +675,51 @@ protected static Angle clampAngle(Angle a, Angle min, Angle max) // ============== Image Reading and Downloading ======================= // // ============== Image Reading and Downloading ======================= // // ============== Image Reading and Downloading ======================= // - - protected void requestTile(DrawContext dc, Tile tile) - { + protected void requestTile(DrawContext dc, Tile tile) { Vec4 centroid = dc.getGlobe().computePointFromPosition(tile.getSector().getCentroid(), 0); - if (this.getReferencePoint() != null) + if (this.getReferencePoint() != null) { tile.setPriority(centroid.distanceTo3(this.getReferencePoint())); + } RequestTask task = new RequestTask(tile, this); this.getRequestQ().add(task); } - protected void sendRequests() - { + protected void sendRequests() { Runnable task = this.requestQ.poll(); - while (task != null) - { - if (!WorldWind.getTaskService().isFull()) - { + while (task != null) { + if (!WorldWind.getTaskService().isFull()) { WorldWind.getTaskService().addTask(task); } task = this.requestQ.poll(); } } - protected static class RequestTask implements Runnable, Comparable - { + protected static class RequestTask implements Runnable, Comparable { + protected final PlaceNameLayer layer; protected final Tile tile; - RequestTask(Tile tile, PlaceNameLayer layer) - { + RequestTask(Tile tile, PlaceNameLayer layer) { this.layer = layer; this.tile = tile; } - public void run() - { - if (Thread.currentThread().isInterrupted()) + public void run() { + if (Thread.currentThread().isInterrupted()) { return; + } - if (this.tile.isTileInMemoryWithData()) + if (this.tile.isTileInMemoryWithData()) { return; + } final java.net.URL tileURL = this.layer.getDataFileStore().findFile(tile.getFileCachePath(), false); - if (tileURL != null) - { - if (this.layer.loadTile(this.tile, tileURL)) - { + if (tileURL != null) { + if (this.layer.loadTile(this.tile, tileURL)) { tile.getPlaceNameService().unmarkResourceAbsent(tile.getPlaceNameService().getTileNumber( - tile.row, - tile.column)); + tile.row, + tile.column)); this.layer.firePropertyChange(AVKey.LAYER, null, this); return; } @@ -814,24 +735,23 @@ public void run() * * @throws IllegalArgumentException if that is null */ - public int compareTo(RequestTask that) - { - if (that == null) - { + public int compareTo(RequestTask that) { + if (that == null) { String msg = Logging.getMessage("nullValue.RequestTaskIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - return this.tile.getPriority() == that.tile.getPriority() ? 0 : - this.tile.getPriority() < that.tile.getPriority() ? -1 : 1; + return this.tile.getPriority() == that.tile.getPriority() ? 0 + : this.tile.getPriority() < that.tile.getPriority() ? -1 : 1; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final RequestTask that = (RequestTask) o; @@ -839,21 +759,17 @@ public boolean equals(Object o) return !(tile != null ? !tile.equals(that.tile) : that.tile != null); } - public int hashCode() - { + public int hashCode() { return (tile != null ? tile.hashCode() : 0); } - public String toString() - { + public String toString() { return this.tile.toString(); } } - protected boolean loadTile(Tile tile, java.net.URL url) - { - if (WWIO.isFileOutOfDate(url, this.placeNameServiceSet.getExpiryTime())) - { + protected boolean loadTile(Tile tile, java.net.URL url) { + if (WWIO.isFileOutOfDate(url, this.placeNameServiceSet.getExpiryTime())) { // The file has expired. Delete it then request download of newer. this.getDataFileStore().removeFile(url); String message = Logging.getMessage("generic.DataFileExpired", url); @@ -862,17 +778,15 @@ protected boolean loadTile(Tile tile, java.net.URL url) } PlaceNameChunk tileData; - synchronized (this.fileLock) - { + synchronized (this.fileLock) { tileData = readTileData(tile, url); } - if (tileData == null) - { + if (tileData == null) { // Assume that something's wrong with the file and delete it. this.getDataFileStore().removeFile(url); tile.getPlaceNameService().markResourceAbsent(tile.getPlaceNameService().getTileNumber(tile.row, - tile.column)); + tile.column)); String message = Logging.getMessage("generic.DeletedCorruptDataFile", url); Logging.logger().fine(message); return false; @@ -883,12 +797,10 @@ protected boolean loadTile(Tile tile, java.net.URL url) return true; } - protected static PlaceNameChunk readTileData(Tile tile, java.net.URL url) - { + protected static PlaceNameChunk readTileData(Tile tile, java.net.URL url) { java.io.InputStream is = null; - try - { + try { String path = url.getFile(); path = path.replaceAll("%20", " "); // TODO: find a better way to get a path usable by FileInputStream @@ -899,39 +811,32 @@ protected static PlaceNameChunk readTileData(Tile tile, java.net.URL url) GMLPlaceNameSAXHandler handler = new GMLPlaceNameSAXHandler(); javax.xml.parsers.SAXParserFactory.newInstance().newSAXParser().parse(is, handler); return handler.createPlaceNameChunk(tile.getPlaceNameService()); - } - catch (Exception e) - { + } catch (Exception e) { //todo log actual error Logging.logger().log(Level.FINE, - Logging.getMessage("layers.PlaceNameLayer.ExceptionAttemptingToReadFile", url.toString()), e); - } - finally - { - try - { - if (is != null) + Logging.getMessage("layers.PlaceNameLayer.ExceptionAttemptingToReadFile", url.toString()), e); + } finally { + try { + if (is != null) { is.close(); - } - catch (java.io.IOException e) - { + } + } catch (java.io.IOException e) { Logging.logger().log(Level.FINE, - Logging.getMessage("layers.PlaceNameLayer.ExceptionAttemptingToReadFile", url.toString()), e); + Logging.getMessage("layers.PlaceNameLayer.ExceptionAttemptingToReadFile", url.toString()), e); } } return null; } - protected static CharBuffer newCharBuffer(int numElements) - { + protected static CharBuffer newCharBuffer(int numElements) { ByteBuffer bb = ByteBuffer.allocateDirect((Character.SIZE / 8) * numElements); bb.order(ByteOrder.nativeOrder()); return bb.asCharBuffer(); } - protected static class GMLPlaceNameSAXHandler extends org.xml.sax.helpers.DefaultHandler - { + protected static class GMLPlaceNameSAXHandler extends org.xml.sax.helpers.DefaultHandler { + protected static final String GML_FEATURE_MEMBER = "gml:featureMember"; protected static final String TOPP_FULL_NAME_ND = "topp:full_name_nd"; protected static final String TOPP_LATITUDE = "topp:latitude"; @@ -946,12 +851,10 @@ protected static class GMLPlaceNameSAXHandler extends org.xml.sax.helpers.Defaul double[] latlonArray = new double[16]; int numEntries = 0; - protected GMLPlaceNameSAXHandler() - { + protected GMLPlaceNameSAXHandler() { } - protected PlaceNameChunk createPlaceNameChunk(PlaceNameService service) - { + protected PlaceNameChunk createPlaceNameChunk(PlaceNameService service) { int numChars = this.textArray.length(); CharBuffer textBuffer = newCharBuffer(numChars); textBuffer.put(this.textArray.toString()); @@ -959,15 +862,13 @@ protected PlaceNameChunk createPlaceNameChunk(PlaceNameService service) return new PlaceNameChunk(service, textBuffer, this.textIndexArray, this.latlonArray, this.numEntries); } - protected void beginEntry() - { + protected void beginEntry() { int textIndex = this.textArray.length(); this.textIndexArray = append(this.textIndexArray, this.numEntries, textIndex); this.inBeginEndPair = true; } - protected void endEntry() - { + protected void endEntry() { double lat = this.parseDouble(this.latBuffer); double lon = this.parseDouble(this.lonBuffer); int numLatLon = 2 * this.numEntries; @@ -981,47 +882,41 @@ protected void endEntry() this.numEntries++; } - protected double parseDouble(StringBuilder sb) - { + protected double parseDouble(StringBuilder sb) { double value = 0; - try - { + try { value = Double.parseDouble(sb.toString()); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(Level.FINE, - Logging.getMessage("layers.PlaceNameLayer.ExceptionAttemptingToReadFile", ""), e); + Logging.getMessage("layers.PlaceNameLayer.ExceptionAttemptingToReadFile", ""), e); } return value; } - protected int[] append(int[] array, int index, int value) - { - if (index >= array.length) + protected int[] append(int[] array, int index, int value) { + if (index >= array.length) { array = this.resizeArray(array); + } array[index] = value; return array; } - protected int[] resizeArray(int[] oldArray) - { + protected int[] resizeArray(int[] oldArray) { int newSize = 2 * oldArray.length; int[] newArray = new int[newSize]; System.arraycopy(oldArray, 0, newArray, 0, oldArray.length); return newArray; } - protected double[] append(double[] array, int index, double value) - { - if (index >= array.length) + protected double[] append(double[] array, int index, double value) { + if (index >= array.length) { array = this.resizeArray(array); + } array[index] = value; return array; } - protected double[] resizeArray(double[] oldArray) - { + protected double[] resizeArray(double[] oldArray) { int newSize = 2 * oldArray.length; double[] newArray = new double[newSize]; System.arraycopy(oldArray, 0, newArray, 0, oldArray.length); @@ -1029,129 +924,127 @@ protected double[] resizeArray(double[] oldArray) } @SuppressWarnings({"StringEquality"}) - public void characters(char ch[], int start, int length) - { - if (!this.inBeginEndPair) + public void characters(char ch[], int start, int length) { + if (!this.inBeginEndPair) { return; + } // Top of QName stack is an interned string, // so we can use pointer comparison. String internedTopQName = this.internedQNameStack.getFirst(); StringBuilder sb = null; - if (TOPP_LATITUDE == internedTopQName) + if (TOPP_LATITUDE == internedTopQName) { sb = this.latBuffer; - else if (TOPP_LONGITUDE == internedTopQName) + } else if (TOPP_LONGITUDE == internedTopQName) { sb = this.lonBuffer; - else if (TOPP_FULL_NAME_ND == internedTopQName) + } else if (TOPP_FULL_NAME_ND == internedTopQName) { sb = this.textArray; + } - if (sb != null) + if (sb != null) { sb.append(ch, start, length); + } } - public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes attributes) - { + public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes attributes) { // Don't validate uri, localName or attributes because they aren't used. // Intern the qName string so we can use pointer comparison. String internedQName = qName.intern(); //noinspection StringEquality - if (GML_FEATURE_MEMBER == internedQName) + if (GML_FEATURE_MEMBER == internedQName) { this.beginEntry(); + } this.internedQNameStack.addFirst(internedQName); } - public void endElement(String uri, String localName, String qName) - { + public void endElement(String uri, String localName, String qName) { // Don't validate uri or localName because they aren't used. // Intern the qName string so we can use pointer comparison. String internedQName = qName.intern(); //noinspection StringEquality - if (GML_FEATURE_MEMBER == internedQName) + if (GML_FEATURE_MEMBER == internedQName) { this.endEntry(); + } this.internedQNameStack.removeFirst(); } } - protected void downloadTile(final Tile tile) - { + protected void downloadTile(final Tile tile) { downloadTile(tile, null); } - protected void downloadTile(final Tile tile, DownloadPostProcessor postProcessor) - { - if (!this.isNetworkRetrievalEnabled()) + protected void downloadTile(final Tile tile, DownloadPostProcessor postProcessor) { + if (!this.isNetworkRetrievalEnabled()) { return; + } - if (!WorldWind.getRetrievalService().isAvailable()) + if (!WorldWind.getRetrievalService().isAvailable()) { return; + } java.net.URL url; - try - { + try { url = tile.getRequestURL(); - if (WorldWind.getNetworkStatus().isHostUnavailable(url)) + if (WorldWind.getNetworkStatus().isHostUnavailable(url)) { return; - } - catch (java.net.MalformedURLException e) - { + } + } catch (java.net.MalformedURLException e) { Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("layers.PlaceNameLayer.ExceptionCreatingUrl", tile), e); + Logging.getMessage("layers.PlaceNameLayer.ExceptionCreatingUrl", tile), e); return; } Retriever retriever; - if ("http".equalsIgnoreCase(url.getProtocol()) || "https".equalsIgnoreCase(url.getProtocol())) - { - if (postProcessor == null) + if ("http".equalsIgnoreCase(url.getProtocol()) || "https".equalsIgnoreCase(url.getProtocol())) { + if (postProcessor == null) { postProcessor = new DownloadPostProcessor(this, tile); + } retriever = new HTTPRetriever(url, postProcessor); retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers - } - else - { + } else { Logging.logger().severe( - Logging.getMessage("layers.PlaceNameLayer.UnknownRetrievalProtocol", url.toString())); + Logging.getMessage("layers.PlaceNameLayer.UnknownRetrievalProtocol", url.toString())); return; } // Apply any overridden timeouts. Integer cto = AVListImpl.getIntegerValue(this, AVKey.URL_CONNECT_TIMEOUT); - if (cto != null && cto > 0) + if (cto != null && cto > 0) { retriever.setConnectTimeout(cto); + } Integer cro = AVListImpl.getIntegerValue(this, AVKey.URL_READ_TIMEOUT); - if (cro != null && cro > 0) + if (cro != null && cro > 0) { retriever.setReadTimeout(cro); + } Integer srl = AVListImpl.getIntegerValue(this, AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT); - if (srl != null && srl > 0) + if (srl != null && srl > 0) { retriever.setStaleRequestLimit(srl); + } WorldWind.getRetrievalService().runRetriever(retriever, tile.getPriority()); } - protected void saveBuffer(java.nio.ByteBuffer buffer, java.io.File outFile) throws java.io.IOException - { + protected void saveBuffer(java.nio.ByteBuffer buffer, java.io.File outFile) throws java.io.IOException { synchronized (this.fileLock) // sychronized with read of file in RequestTask.run() { WWIO.saveBuffer(buffer, outFile); } } - protected static class DownloadPostProcessor extends AbstractRetrievalPostProcessor - { + protected static class DownloadPostProcessor extends AbstractRetrievalPostProcessor { + protected final PlaceNameLayer layer; protected final Tile tile; protected final FileStore fileStore; - public DownloadPostProcessor(PlaceNameLayer layer, Tile tile) - { + public DownloadPostProcessor(PlaceNameLayer layer, Tile tile) { // No arg check; the class has protected access. this(layer, tile, null); } - public DownloadPostProcessor(PlaceNameLayer layer, Tile tile, FileStore fileStore) - { + public DownloadPostProcessor(PlaceNameLayer layer, Tile tile, FileStore fileStore) { // No arg check; the class has protected access. //noinspection RedundantCast @@ -1162,36 +1055,30 @@ public DownloadPostProcessor(PlaceNameLayer layer, Tile tile, FileStore fileStor this.fileStore = fileStore; } - protected FileStore getFileStore() - { + protected FileStore getFileStore() { return this.fileStore != null ? this.fileStore : this.layer.getDataFileStore(); } @Override - protected void markResourceAbsent() - { + protected void markResourceAbsent() { this.tile.getPlaceNameService().markResourceAbsent( - this.tile.getPlaceNameService().getTileNumber(this.tile.row, this.tile.column)); + this.tile.getPlaceNameService().getTileNumber(this.tile.row, this.tile.column)); } @Override - protected Object getFileLock() - { + protected Object getFileLock() { return this.layer.fileLock; } - protected File doGetOutputFile() - { + protected File doGetOutputFile() { return this.getFileStore().newFile(this.tile.getFileCachePath()); } @Override - protected ByteBuffer handleSuccessfulRetrieval() - { + protected ByteBuffer handleSuccessfulRetrieval() { ByteBuffer buffer = super.handleSuccessfulRetrieval(); - if (buffer != null) - { + if (buffer != null) { // Fire a property change to denote that the layer's backing data has changed. this.layer.firePropertyChange(AVKey.LAYER, null, this); } @@ -1200,12 +1087,10 @@ protected ByteBuffer handleSuccessfulRetrieval() } @Override - protected ByteBuffer handleXMLContent() throws IOException - { + protected ByteBuffer handleXMLContent() throws IOException { // Check for an exception report String s = WWIO.byteBufferToString(this.getRetriever().getBuffer(), 1024, null); - if (s.contains("")) - { + if (s.contains("")) { // TODO: Parse the xml and include only the message text in the log message. StringBuilder sb = new StringBuilder(this.getRetriever().getName()); @@ -1226,7 +1111,6 @@ protected ByteBuffer handleXMLContent() throws IOException // *** Bulk download *** // *** Bulk download *** // *** Bulk download *** - /** * Start a new {@link BulkRetrievalThread} that downloads all placenames for a given sector and resolution to the * current WorldWind file cache. @@ -1237,19 +1121,18 @@ protected ByteBuffer handleXMLContent() throws IOException * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to download data for. + * @param sector the sector to download data for. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param listener an optional retrieval listener. May be null. + * @param listener an optional retrieval listener. May be null. * * @return the {@link PlaceNameLayerBulkDownloader} that executes the retrieval. * * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. * @see PlaceNameLayerBulkDownloader */ - public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetrievalListener listener) - { + public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetrievalListener listener) { PlaceNameLayerBulkDownloader thread = new PlaceNameLayerBulkDownloader(this, sector, resolution, - this.getDataFileStore(), listener); + this.getDataFileStore(), listener); thread.setDaemon(true); thread.start(); return thread; @@ -1265,11 +1148,11 @@ public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetri * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to download data for. + * @param sector the sector to download data for. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param fileStore the file store in which to place the downloaded elevations. If null the current WorldWind file - * cache is used. - * @param listener an optional retrieval listener. May be null. + * @param fileStore the file store in which to place the downloaded elevations. If null the current WorldWind file + * cache is used. + * @param listener an optional retrieval listener. May be null. * * @return the {@link PlaceNameLayerBulkDownloader} that executes the retrieval. * @@ -1277,10 +1160,9 @@ public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetri * @see PlaceNameLayerBulkDownloader */ public BulkRetrievalThread makeLocal(Sector sector, double resolution, FileStore fileStore, - BulkRetrievalListener listener) - { + BulkRetrievalListener listener) { PlaceNameLayerBulkDownloader thread = new PlaceNameLayerBulkDownloader(this, sector, resolution, - fileStore != null ? fileStore : this.getDataFileStore(), listener); + fileStore != null ? fileStore : this.getDataFileStore(), listener); thread.setDaemon(true); thread.start(); return thread; @@ -1293,15 +1175,14 @@ public BulkRetrievalThread makeLocal(Sector sector, double resolution, FileStore * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to estimate. + * @param sector the sector to estimate. * @param resolution the target resolution, provided in radians of latitude per texel. * * @return the estimated size in bytes of the missing placenames. * * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. */ - public long getEstimatedMissingDataSize(Sector sector, double resolution) - { + public long getEstimatedMissingDataSize(Sector sector, double resolution) { return this.getEstimatedMissingDataSize(sector, resolution, this.getDataFileStore()); } @@ -1312,24 +1193,20 @@ public long getEstimatedMissingDataSize(Sector sector, double resolution) * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to estimate. + * @param sector the sector to estimate. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param fileStore the file store to examine. If null the current WorldWind file cache is used. + * @param fileStore the file store to examine. If null the current WorldWind file cache is used. * * @return the estimated size in byte of the missing placenames. * * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. */ - public long getEstimatedMissingDataSize(Sector sector, double resolution, FileStore fileStore) - { - try - { + public long getEstimatedMissingDataSize(Sector sector, double resolution, FileStore fileStore) { + try { PlaceNameLayerBulkDownloader downloader = new PlaceNameLayerBulkDownloader(this, sector, resolution, - fileStore != null ? fileStore : this.getDataFileStore(), null); + fileStore != null ? fileStore : this.getDataFileStore(), null); return downloader.getEstimatedMissingDataSize(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionDuringDataSizeEstimate", this.getName()); Logging.logger().severe(message); throw new RuntimeException(message); diff --git a/src/gov/nasa/worldwind/layers/placename/PlaceNameLayerBulkDownloader.java b/src/gov/nasa/worldwind/layers/placename/PlaceNameLayerBulkDownloader.java index d35535cd1b..af5a7cf4bc 100644 --- a/src/gov/nasa/worldwind/layers/placename/PlaceNameLayerBulkDownloader.java +++ b/src/gov/nasa/worldwind/layers/placename/PlaceNameLayerBulkDownloader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.layers.placename; import gov.nasa.worldwind.WorldWind; @@ -26,8 +25,8 @@ * @author tag * @version $Id: PlaceNameLayerBulkDownloader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PlaceNameLayerBulkDownloader extends BulkRetrievalThread -{ +public class PlaceNameLayerBulkDownloader extends BulkRetrievalThread { + protected static final long AVG_TILE_SIZE = 8 * 1024; protected int MAX_TILE_COUNT_PER_REGION = 200; @@ -40,16 +39,15 @@ public class PlaceNameLayerBulkDownloader extends BulkRetrievalThread *

        * The thread returned is not started during construction, the caller must start the thread. * - * @param layer the layer for which to download placenames. - * @param sector the sector to download data for. This value is final. + * @param layer the layer for which to download placenames. + * @param sector the sector to download data for. This value is final. * @param resolution the target resolution, provided in radians of latitude per texel. This value is final. - * @param listener an optional retrieval listener. May be null. + * @param listener an optional retrieval listener. May be null. * * @throws IllegalArgumentException if either the layer or sector are null, or the resolution is less than zero. */ public PlaceNameLayerBulkDownloader(PlaceNameLayer layer, Sector sector, double resolution, - BulkRetrievalListener listener) - { + BulkRetrievalListener listener) { // Arguments checked in parent constructor //resolution is compared to the maxDsiatnce value in each placenameservice super(layer, sector, resolution, layer.getDataFileStore(), listener); @@ -63,18 +61,17 @@ public PlaceNameLayerBulkDownloader(PlaceNameLayer layer, Sector sector, double *

        * The thread returned is not started during construction, the caller must start the thread. * - * @param layer the layer for which to download placenames. - * @param sector the sector to download data for. This value is final. + * @param layer the layer for which to download placenames. + * @param sector the sector to download data for. This value is final. * @param resolution the target resolution, provided in radians of latitude per texel. This value is final. - * @param fileStore the file store in which to place the downloaded elevations. - * @param listener an optional retrieval listener. May be null. + * @param fileStore the file store in which to place the downloaded elevations. + * @param listener an optional retrieval listener. May be null. * * @throws IllegalArgumentException if either the layer, the sector or file store are null, or the resolution is - * less than zero. + * less than zero. */ public PlaceNameLayerBulkDownloader(PlaceNameLayer layer, Sector sector, double resolution, FileStore fileStore, - BulkRetrievalListener listener) - { + BulkRetrievalListener listener) { // Arguments checked in parent constructor //resolution is compared to the maxDsiatnce value in each placenameservice super(layer, sector, resolution, fileStore, listener); @@ -82,35 +79,28 @@ public PlaceNameLayerBulkDownloader(PlaceNameLayer layer, Sector sector, double this.layer = layer; } - public void run() - { - try - { + public void run() { + try { // Cycle though placenameservices and find missing tiles this.missingTiles = new ArrayList(); ArrayList allMissingTiles = this.getMissingTilesInSector(this.sector); this.progress.setTotalCount(allMissingTiles.size()); // Submit missing tiles requests at 10 sec intervals - while (allMissingTiles.size() > 0) - { + while (allMissingTiles.size() > 0) { transferMissingTiles(allMissingTiles, missingTiles, MAX_TILE_COUNT_PER_REGION); - while (missingTiles.size() > 0) - { + while (missingTiles.size() > 0) { submitMissingTilesRequests(); - if (missingTiles.size() > 0) + if (missingTiles.size() > 0) { Thread.sleep(this.pollDelay); + } } } - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { String message = Logging.getMessage("generic.BulkRetrievalInterrupted", layer.getName()); Logging.logger().log(java.util.logging.Level.WARNING, message, e); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionDuringBulkRetrieval", layer.getName()); Logging.logger().severe(message); throw new RuntimeException(message); @@ -118,86 +108,73 @@ public void run() } protected void transferMissingTiles(ArrayList source, - ArrayList destination, int maxCount) - { + ArrayList destination, int maxCount) { int i = 0; - while (i < maxCount && source.size() > 0) - { + while (i < maxCount && source.size() > 0) { destination.add(source.remove(0)); i++; } } - protected synchronized void submitMissingTilesRequests() throws InterruptedException - { + protected synchronized void submitMissingTilesRequests() throws InterruptedException { RetrievalService rs = WorldWind.getRetrievalService(); int i = 0; - while (this.missingTiles.size() > i && rs.isAvailable()) - { + while (this.missingTiles.size() > i && rs.isAvailable()) { Thread.sleep(1); // generates InterruptedException if thread has been interrupted PlaceNameLayer.Tile tile = this.missingTiles.get(i); - if (this.isTileLocalOrAbsent(tile)) - { + if (this.isTileLocalOrAbsent(tile)) { // No need to request that tile anymore this.missingTiles.remove(i); - } - else - { + } else { this.layer.downloadTile(tile, new BulkDownloadPostProcessor(this.layer, tile, this.fileStore)); i++; } } } - protected class BulkDownloadPostProcessor extends PlaceNameLayer.DownloadPostProcessor - { - public BulkDownloadPostProcessor(PlaceNameLayer layer, PlaceNameLayer.Tile tile, FileStore fileStore) - { + protected class BulkDownloadPostProcessor extends PlaceNameLayer.DownloadPostProcessor { + + public BulkDownloadPostProcessor(PlaceNameLayer layer, PlaceNameLayer.Tile tile, FileStore fileStore) { super(layer, tile, fileStore); } - public ByteBuffer run(Retriever retriever) - { + public ByteBuffer run(Retriever retriever) { ByteBuffer buffer = super.run(retriever); - if (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) + if (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) { removeRetrievedTile(this.tile); + } - if (hasRetrievalListeners()) + if (hasRetrievalListeners()) { callRetrievalListeners(retriever, this.tile); + } return buffer; } } - protected void callRetrievalListeners(Retriever retriever, PlaceNameLayer.Tile tile) - { + protected void callRetrievalListeners(Retriever retriever, PlaceNameLayer.Tile tile) { String eventType = (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) - ? BulkRetrievalEvent.RETRIEVAL_SUCCEEDED : BulkRetrievalEvent.RETRIEVAL_FAILED; + ? BulkRetrievalEvent.RETRIEVAL_SUCCEEDED : BulkRetrievalEvent.RETRIEVAL_FAILED; super.callRetrievalListeners(new BulkRetrievalEvent(this.layer, eventType, tile.getFileCachePath())); } - protected synchronized void removeRetrievedTile(PlaceNameLayer.Tile tile) - { + protected synchronized void removeRetrievedTile(PlaceNameLayer.Tile tile) { this.missingTiles.remove(tile); this.progress.setCurrentCount(this.progress.getCurrentCount() + 1); this.progress.setCurrentSize(this.progress.getCurrentSize() + AVG_TILE_SIZE); this.progress.setLastUpdateTime(System.currentTimeMillis()); // Estimate total size this.progress.setTotalSize( - this.progress.getCurrentSize() / this.progress.getCurrentCount() * this.progress.getTotalCount()); + this.progress.getCurrentSize() / this.progress.getCurrentCount() * this.progress.getTotalCount()); } - protected long getEstimatedMissingDataSize() - { + protected long getEstimatedMissingDataSize() { int tileCount; - try - { + try { tileCount = this.getMissingTilesCountEstimate(sector, resolution); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionDuringDataSizeEstimate", this.getName()); Logging.logger().severe(message); throw new RuntimeException(message); @@ -205,21 +182,17 @@ protected long getEstimatedMissingDataSize() return tileCount * AVG_TILE_SIZE; } - protected int getMissingTilesCountEstimate(Sector sector, double resolution) - { + protected int getMissingTilesCountEstimate(Sector sector, double resolution) { int tileCount = 0; int serviceCount = this.layer.getPlaceNameServiceSet().getServiceCount(); - for (int i = 0; i < serviceCount; i++) - { + for (int i = 0; i < serviceCount; i++) { int serviceTileCount = 0; PlaceNameService service = this.layer.getPlaceNameServiceSet().getService(i); - if (service.getMaxDisplayDistance() > resolution) - { + if (service.getMaxDisplayDistance() > resolution) { PlaceNameLayer.NavigationTile navTile = this.layer.navTiles.get(i); // drill down into tiles to find bottom level navTiles visible List list = this.navTilesVisible(navTile, sector); - for (PlaceNameLayer.NavigationTile nt : list) - { + for (PlaceNameLayer.NavigationTile nt : list) { serviceTileCount += this.estimateNumberTilesinSector(nt, sector); } } @@ -230,30 +203,26 @@ protected int getMissingTilesCountEstimate(Sector sector, double resolution) return tileCount; } - protected ArrayList getMissingTilesInSector(Sector sector) throws InterruptedException - { + protected ArrayList getMissingTilesInSector(Sector sector) throws InterruptedException { ArrayList allMissingTiles = new ArrayList(); int serviceCount = this.layer.getPlaceNameServiceSet().getServiceCount(); - for (int i = 0; i < serviceCount; i++) - { + for (int i = 0; i < serviceCount; i++) { PlaceNameService service = this.layer.getPlaceNameServiceSet().getService(i); - if (service.getMaxDisplayDistance() > this.resolution) - { + if (service.getMaxDisplayDistance() > this.resolution) { // get tiles in sector ArrayList baseTiles = new ArrayList(); PlaceNameLayer.NavigationTile navTile = this.layer.navTiles.get(i); // drill down into tiles to find bottom level navTiles visible List list = this.navTilesVisible(navTile, sector); - for (PlaceNameLayer.NavigationTile nt : list) - { + for (PlaceNameLayer.NavigationTile nt : list) { baseTiles.addAll(nt.getTiles()); } - for (PlaceNameLayer.Tile tile : baseTiles) - { - if ((tile.getSector().intersects(sector)) && (!this.isTileLocalOrAbsent(tile))) + for (PlaceNameLayer.Tile tile : baseTiles) { + if ((tile.getSector().intersects(sector)) && (!this.isTileLocalOrAbsent(tile))) { allMissingTiles.add(tile); + } } } } @@ -261,22 +230,18 @@ protected ArrayList getMissingTilesInSector(Sector sector) return allMissingTiles; } - protected List navTilesVisible(PlaceNameLayer.NavigationTile tile, Sector sector) - { + protected List navTilesVisible(PlaceNameLayer.NavigationTile tile, Sector sector) { ArrayList navList = new ArrayList(); - if (tile.navSector.intersects(sector)) - { - if (tile.level > 0 && !tile.hasSubTiles()) + if (tile.navSector.intersects(sector)) { + if (tile.level > 0 && !tile.hasSubTiles()) { tile.buildSubNavTiles(); + } - if (tile.hasSubTiles()) - { - for (PlaceNameLayer.NavigationTile nav : tile.subNavTiles) - { + if (tile.hasSubTiles()) { + for (PlaceNameLayer.NavigationTile nav : tile.subNavTiles) { navList.addAll(this.navTilesVisible(nav, sector)); } - } - else //at bottom level navigation tile + } else //at bottom level navigation tile { navList.add(tile); } @@ -285,8 +250,7 @@ protected List navTilesVisible(PlaceNameLayer.Nav return navList; } - protected int estimateNumberTilesinSector(PlaceNameLayer.NavigationTile tile, Sector searchSector) - { + protected int estimateNumberTilesinSector(PlaceNameLayer.NavigationTile tile, Sector searchSector) { final Angle dLat = tile.placeNameService.getTileDelta().getLatitude(); final Angle dLon = tile.placeNameService.getTileDelta().getLongitude(); @@ -299,30 +263,27 @@ protected int estimateNumberTilesinSector(PlaceNameLayer.NavigationTile tile, Se int tileCount = 0; Angle p1 = PlaceNameLayer.Tile.computeRowLatitude(firstRow, dLat); boolean needToCheckDisk = true; - for (int row = 0; row <= lastRow - firstRow; row++) - { + for (int row = 0; row <= lastRow - firstRow; row++) { Angle p2; p2 = p1.add(dLat); Angle t1 = PlaceNameLayer.Tile.computeColumnLongitude(firstCol, dLon); - for (int col = 0; col <= lastCol - firstCol; col++) - { + for (int col = 0; col <= lastCol - firstCol; col++) { Angle t2; t2 = t1.add(dLon); Sector tileSector = new Sector(p1, p2, t1, t2); - if (tileSector.intersects(searchSector)) - { - if (needToCheckDisk) - { + if (tileSector.intersects(searchSector)) { + if (needToCheckDisk) { //now check if on disk String filePath = tile.placeNameService.createFileCachePathFromTile(row + firstRow, - col + firstCol); + col + firstCol); final java.net.URL tileURL = this.fileStore.findFile(filePath, false); - if (tileURL == null) + if (tileURL == null) { needToCheckDisk = false; //looked and found nothing - else + } else { return 0; //found one, assume rest are there + } } tileCount++; @@ -335,12 +296,11 @@ protected int estimateNumberTilesinSector(PlaceNameLayer.NavigationTile tile, Se return tileCount; } - protected boolean isTileLocalOrAbsent(PlaceNameLayer.Tile tile) - { + protected boolean isTileLocalOrAbsent(PlaceNameLayer.Tile tile) { if (tile.getPlaceNameService().isResourceAbsent( - tile.getPlaceNameService().getTileNumber(tile.row, tile.column))) + tile.getPlaceNameService().getTileNumber(tile.row, tile.column))) { return true; // tile is absent - + } URL url = this.fileStore.findFile(tile.getFileCachePath(), false); return url != null; // tile is already in cache } diff --git a/src/gov/nasa/worldwind/layers/placename/PlaceNameService.java b/src/gov/nasa/worldwind/layers/placename/PlaceNameService.java index 8b121e5869..57aeab8930 100644 --- a/src/gov/nasa/worldwind/layers/placename/PlaceNameService.java +++ b/src/gov/nasa/worldwind/layers/placename/PlaceNameService.java @@ -15,8 +15,8 @@ * @author Paul Collins * @version $Id: PlaceNameService.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PlaceNameService -{ +public class PlaceNameService { + // Data retrieval and caching attributes. private final String service; private final String dataset; @@ -36,26 +36,25 @@ public class PlaceNameService private static final int MAX_ABSENT_TILE_TRIES = 2; private static final int MIN_ABSENT_TILE_CHECK_INTERVAL = 10000; private final AbsentResourceList absentTiles = new AbsentResourceList(MAX_ABSENT_TILE_TRIES, - MIN_ABSENT_TILE_CHECK_INTERVAL); + MIN_ABSENT_TILE_CHECK_INTERVAL); private boolean addVersionTag = false; private Sector maskingSector = null; /** * PlaceNameService Constructor * - * @param service server hostong placename data - * @param dataset name of the dataset + * @param service server hostong placename data + * @param dataset name of the dataset * @param fileCachePath location of cache - * @param sector sets the masking sector for this service. - * @param tileDelta tile size - * @param font font for rendering name - * @param versionTag dictates if the wfs version tag is added to requests + * @param sector sets the masking sector for this service. + * @param tileDelta tile size + * @param font font for rendering name + * @param versionTag dictates if the wfs version tag is added to requests * * @throws IllegalArgumentException if any parameter is null */ public PlaceNameService(String service, String dataset, String fileCachePath, Sector sector, LatLon tileDelta, - java.awt.Font font, boolean versionTag) - { + java.awt.Font font, boolean versionTag) { // Data retrieval and caching attributes. this.service = service; this.dataset = dataset; @@ -72,8 +71,7 @@ public PlaceNameService(String service, String dataset, String fileCachePath, Se this.addVersionTag = versionTag; String message = this.validate(); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -82,17 +80,15 @@ public PlaceNameService(String service, String dataset, String fileCachePath, Se } /** - * @param row row + * @param row row * @param column column * * @return path of the tile in the cache * * @throws IllegalArgumentException if either row or column is less than zero */ - public String createFileCachePathFromTile(int row, int column) - { - if (row < 0 || column < 0) - { + public String createFileCachePathFromTile(int row, int column) { + if (row < 0 || column < 0) { String message = Logging.getMessage("PlaceNameService.RowOrColumnOutOfRange", row, column); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -108,17 +104,15 @@ public String createFileCachePathFromTile(int row, int column) return path.replaceAll("[:*?<>|]", ""); } - private int numColumnsInLevel() - { + private int numColumnsInLevel() { int firstCol = Tile.computeColumn(this.tileDelta.getLongitude(), TILING_SECTOR.getMinLongitude(), Angle.NEG180); int lastCol = Tile.computeColumn(this.tileDelta.getLongitude(), - TILING_SECTOR.getMaxLongitude().subtract(this.tileDelta.getLongitude()), Angle.NEG180); + TILING_SECTOR.getMaxLongitude().subtract(this.tileDelta.getLongitude()), Angle.NEG180); return lastCol - firstCol + 1; } - public long getTileNumber(int row, int column) - { + public long getTileNumber(int row, int column) { return row * this.numColumns + column; } @@ -128,26 +122,26 @@ public long getTileNumber(int row, int column) * @return wfs request url * * @throws java.net.MalformedURLException thrown if error creating the url - * @throws IllegalArgumentException if {@link gov.nasa.worldwind.geom.Sector} is null + * @throws IllegalArgumentException if {@link gov.nasa.worldwind.geom.Sector} is null */ - public java.net.URL createServiceURLFromSector(Sector sector) throws java.net.MalformedURLException - { - if (sector == null) - { + public java.net.URL createServiceURLFromSector(Sector sector) throws java.net.MalformedURLException { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } StringBuilder sb = new StringBuilder(this.service); - if (sb.charAt(sb.length() - 1) != '?') + if (sb.charAt(sb.length() - 1) != '?') { sb.append('?'); + } - if (addVersionTag) + if (addVersionTag) { sb.append("version=1.0.0&TypeName=").append( - dataset); //version=1.0.0 is needed when querying a new wfs server - else + dataset); //version=1.0.0 is needed when querying a new wfs server + } else { sb.append("TypeName=").append(dataset); + } sb.append("&Request=GetFeature"); sb.append("&Service=WFS"); @@ -160,10 +154,9 @@ public java.net.URL createServiceURLFromSector(Sector sector) throws java.net.Ma return new java.net.URL(sb.toString()); } - public synchronized final PlaceNameService deepCopy() - { + public synchronized final PlaceNameService deepCopy() { PlaceNameService copy = new PlaceNameService(this.service, this.dataset, this.fileCachePath, maskingSector, - this.tileDelta, this.font, this.addVersionTag); + this.tileDelta, this.font, this.addVersionTag); copy.enabled = this.enabled; copy.color = this.color; copy.minDisplayDistance = this.minDisplayDistance; @@ -172,55 +165,64 @@ public synchronized final PlaceNameService deepCopy() } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } final PlaceNameService other = (PlaceNameService) o; - if (this.service != null ? !this.service.equals(other.service) : other.service != null) + if (this.service != null ? !this.service.equals(other.service) : other.service != null) { return false; - if (this.dataset != null ? !this.dataset.equals(other.dataset) : other.dataset != null) + } + if (this.dataset != null ? !this.dataset.equals(other.dataset) : other.dataset != null) { return false; - if (this.fileCachePath != null ? !this.fileCachePath.equals(other.fileCachePath) : other.fileCachePath != null) + } + if (this.fileCachePath != null ? !this.fileCachePath.equals(other.fileCachePath) : other.fileCachePath != null) { return false; - if (this.maskingSector != null ? !this.maskingSector.equals(other.maskingSector) : other.maskingSector != null) + } + if (this.maskingSector != null ? !this.maskingSector.equals(other.maskingSector) : other.maskingSector != null) { return false; - if (this.tileDelta != null ? !this.tileDelta.equals(other.tileDelta) : other.tileDelta != null) + } + if (this.tileDelta != null ? !this.tileDelta.equals(other.tileDelta) : other.tileDelta != null) { return false; - if (this.font != null ? !this.font.equals(other.font) : other.font != null) + } + if (this.font != null ? !this.font.equals(other.font) : other.font != null) { return false; - if (this.color != null ? !this.color.equals(other.color) : other.color != null) + } + if (this.color != null ? !this.color.equals(other.color) : other.color != null) { return false; + } if (this.backgroundColor != null ? !this.backgroundColor.equals(other.backgroundColor) - : other.backgroundColor != null) + : other.backgroundColor != null) { return false; - if (this.minDisplayDistance != other.minDisplayDistance) + } + if (this.minDisplayDistance != other.minDisplayDistance) { return false; + } //noinspection RedundantIfStatement - if (this.maxDisplayDistance != other.maxDisplayDistance) + if (this.maxDisplayDistance != other.maxDisplayDistance) { return false; + } return true; } - public synchronized final java.awt.Color getColor() - { + public synchronized final java.awt.Color getColor() { return this.color; } - public synchronized final Color getBackgroundColor() - { - if (this.backgroundColor == null) + public synchronized final Color getBackgroundColor() { + if (this.backgroundColor == null) { this.backgroundColor = suggestBackgroundColor(this.color); + } return this.backgroundColor; } - private Color suggestBackgroundColor(Color foreground) - { + private Color suggestBackgroundColor(Color foreground) { float[] compArray = new float[4]; Color.RGBtoHSB(foreground.getRed(), foreground.getGreen(), foreground.getBlue(), compArray); int colorValue = compArray[2] < 0.5f ? 255 : 0; @@ -228,8 +230,7 @@ private Color suggestBackgroundColor(Color foreground) return new Color(colorValue, colorValue, colorValue, alphaValue); } - public final String getDataset() - { + public final String getDataset() { return this.dataset; } @@ -240,10 +241,8 @@ public final String getDataset() * * @throws IllegalArgumentException if {@link gov.nasa.worldwind.render.DrawContext} is null */ - public final Extent getExtent(DrawContext dc) - { - if (dc == null) - { + public final Extent getExtent(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -252,54 +251,44 @@ public final Extent getExtent(DrawContext dc) return Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), this.maskingSector); } - public final String getFileCachePath() - { + public final String getFileCachePath() { return this.fileCachePath; } - public final java.awt.Font getFont() - { + public final java.awt.Font getFont() { return this.font; } - public synchronized final double getMaxDisplayDistance() - { + public synchronized final double getMaxDisplayDistance() { return this.maxDisplayDistance; } - public synchronized final double getMinDisplayDistance() - { + public synchronized final double getMinDisplayDistance() { return this.minDisplayDistance; } - public final LatLon getTileDelta() - { + public final LatLon getTileDelta() { return tileDelta; } - public final Sector getMaskingSector() - { + public final Sector getMaskingSector() { return this.maskingSector; } - public final String getService() - { + public final String getService() { return this.service; } - public boolean isAddVersionTag() - { + public boolean isAddVersionTag() { return addVersionTag; } - public void setAddVersionTag(boolean addVersionTag) - { + public void setAddVersionTag(boolean addVersionTag) { this.addVersionTag = addVersionTag; } @Override - public int hashCode() - { + public int hashCode() { int result; result = (service != null ? service.hashCode() : 0); result = 29 * result + (this.dataset != null ? this.dataset.hashCode() : 0); @@ -313,8 +302,7 @@ public int hashCode() return result; } - public synchronized final boolean isEnabled() - { + public synchronized final boolean isEnabled() { return this.enabled; } @@ -323,10 +311,8 @@ public synchronized final boolean isEnabled() * * @throws IllegalArgumentException if {@link java.awt.Color} is null */ - public synchronized final void setColor(java.awt.Color color) - { - if (color == null) - { + public synchronized final void setColor(java.awt.Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -335,13 +321,11 @@ public synchronized final void setColor(java.awt.Color color) this.color = color; } - public synchronized final void setBackgroundColor(java.awt.Color backgroundColor) - { + public synchronized final void setBackgroundColor(java.awt.Color backgroundColor) { this.backgroundColor = backgroundColor; } - public synchronized final void setEnabled(boolean enabled) - { + public synchronized final void setEnabled(boolean enabled) { this.enabled = enabled; } @@ -349,14 +333,12 @@ public synchronized final void setEnabled(boolean enabled) * @param maxDisplayDistance maximum distance to display labels for this service * * @throws IllegalArgumentException if maxDisplayDistance is less than the current minimum display - * distance + * distance */ - public synchronized final void setMaxDisplayDistance(double maxDisplayDistance) - { - if (maxDisplayDistance < this.minDisplayDistance) - { + public synchronized final void setMaxDisplayDistance(double maxDisplayDistance) { + if (maxDisplayDistance < this.minDisplayDistance) { String message = Logging.getMessage("PlaceNameService.MaxDisplayDistanceLessThanMinDisplayDistance", - maxDisplayDistance, this.minDisplayDistance); + maxDisplayDistance, this.minDisplayDistance); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -368,14 +350,12 @@ public synchronized final void setMaxDisplayDistance(double maxDisplayDistance) * @param minDisplayDistance minimum distance to display labels for this service * * @throws IllegalArgumentException if minDisplayDistance is less than the current maximum display - * distance + * distance */ - public synchronized final void setMinDisplayDistance(double minDisplayDistance) - { - if (minDisplayDistance > this.maxDisplayDistance) - { + public synchronized final void setMinDisplayDistance(double minDisplayDistance) { + if (minDisplayDistance > this.maxDisplayDistance) { String message = Logging.getMessage("PlaceNameService.MinDisplayDistanceGrtrThanMaxDisplayDistance", - minDisplayDistance, this.maxDisplayDistance); + minDisplayDistance, this.maxDisplayDistance); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -383,18 +363,15 @@ public synchronized final void setMinDisplayDistance(double minDisplayDistance) this.minDisplayDistance = minDisplayDistance; } - public synchronized final void markResourceAbsent(long tileNumber) - { + public synchronized final void markResourceAbsent(long tileNumber) { this.absentTiles.markResourceAbsent(tileNumber); } - public synchronized final boolean isResourceAbsent(long resourceNumber) - { + public synchronized final boolean isResourceAbsent(long resourceNumber) { return this.absentTiles.isResourceAbsent(resourceNumber); } - public synchronized final void unmarkResourceAbsent(long tileNumber) - { + public synchronized final void unmarkResourceAbsent(long tileNumber) { this.absentTiles.unmarkResourceAbsent(tileNumber); } @@ -403,36 +380,28 @@ public synchronized final void unmarkResourceAbsent(long tileNumber) * * @return null if valid, otherwise a string message containing a description of why it is invalid. */ - public final String validate() - { + public final String validate() { String msg = ""; - if (this.service == null) - { + if (this.service == null) { msg += Logging.getMessage("nullValue.ServiceIsNull") + ", "; } - if (this.dataset == null) - { + if (this.dataset == null) { msg += Logging.getMessage("nullValue.DataSetIsNull") + ", "; } - if (this.fileCachePath == null) - { + if (this.fileCachePath == null) { msg += Logging.getMessage("nullValue.FileStorePathIsNull") + ", "; } - if (this.maskingSector == null) - { + if (this.maskingSector == null) { msg += Logging.getMessage("nullValue.SectorIsNull") + ", "; } - if (this.tileDelta == null) - { + if (this.tileDelta == null) { msg += Logging.getMessage("nullValue.TileDeltaIsNull") + ", "; } - if (this.font == null) - { + if (this.font == null) { msg += Logging.getMessage("nullValue.FontIsNull") + ", "; } - if (msg.length() == 0) - { + if (msg.length() == 0) { return null; } diff --git a/src/gov/nasa/worldwind/layers/placename/PlaceNameServiceSet.java b/src/gov/nasa/worldwind/layers/placename/PlaceNameServiceSet.java index 1a507b10af..578dce63bf 100644 --- a/src/gov/nasa/worldwind/layers/placename/PlaceNameServiceSet.java +++ b/src/gov/nasa/worldwind/layers/placename/PlaceNameServiceSet.java @@ -15,49 +15,41 @@ * @author Paul Collins * @version $Id: PlaceNameServiceSet.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PlaceNameServiceSet extends WWObjectImpl implements AVList -{ +public class PlaceNameServiceSet extends WWObjectImpl implements AVList { + private final List serviceList = new LinkedList(); private long expiryTime = 0; - public PlaceNameServiceSet() - { + public PlaceNameServiceSet() { } /** * Add a service to the service set. * * @param placeNameService Service to add. May not be null. - * @param replace {@code true} if the service may replace an equivalent service already in the set. {@code + * @param replace {@code true} if the service may replace an equivalent service already in the set. {@code * false} if the service may not replace a service already in the set. * * @return {@code true} if the service was added to the service set, or if the service replaced an existing item in - * the service set. Returns {@code false} if the set was not changed. + * the service set. Returns {@code false} if the set was not changed. * * @throws IllegalArgumentException if placeNameService is null */ - public boolean addService(PlaceNameService placeNameService, boolean replace) - { - if (placeNameService == null) - { + public boolean addService(PlaceNameService placeNameService, boolean replace) { + if (placeNameService == null) { String message = Logging.getMessage("nullValue.PlaceNameServiceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (int i = 0; i < this.serviceList.size(); i++) - { + for (int i = 0; i < this.serviceList.size(); i++) { final PlaceNameService other = this.serviceList.get(i); if (placeNameService.getService().equals(other.getService()) && placeNameService.getDataset().equals( - other.getDataset())) - { - if (replace) - { + other.getDataset())) { + if (replace) { this.serviceList.set(i, placeNameService); return true; - } - else - { + } else { return false; } } @@ -67,16 +59,14 @@ public boolean addService(PlaceNameService placeNameService, boolean replace) return true; } - public PlaceNameServiceSet deepCopy() - { + public PlaceNameServiceSet deepCopy() { PlaceNameServiceSet copy = new PlaceNameServiceSet(); // Copy params copy.setValues(this); // Creates a deep copy of this.serviceList in copy.serviceList. - for (int i = 0; i < this.serviceList.size(); i++) - { + for (int i = 0; i < this.serviceList.size(); i++) { copy.serviceList.add(i, this.serviceList.get(i).deepCopy()); } @@ -85,37 +75,31 @@ public PlaceNameServiceSet deepCopy() return copy; } - public final int getServiceCount() - { + public final int getServiceCount() { return this.serviceList.size(); } - public final PlaceNameService getService(int index) - { + public final PlaceNameService getService(int index) { return this.serviceList.get(index); } - public final long getExpiryTime() - { + public final long getExpiryTime() { return this.expiryTime; } - public final void setExpiryTime(long expiryTime) - { + public final void setExpiryTime(long expiryTime) { this.expiryTime = expiryTime; } - public List getServices() - { + public List getServices() { return serviceList; } - public PlaceNameService getService(String name) - { - for (int i = 0; i < this.serviceList.size(); i++) - { - if (this.serviceList.get(i).getDataset().equalsIgnoreCase(name)) + public PlaceNameService getService(String name) { + for (int i = 0; i < this.serviceList.size(); i++) { + if (this.serviceList.get(i).getDataset().equalsIgnoreCase(name)) { return this.serviceList.get(i); + } } return null; diff --git a/src/gov/nasa/worldwind/layers/rpf/RPFFileIndex.java b/src/gov/nasa/worldwind/layers/rpf/RPFFileIndex.java index 0889822977..ea2905543b 100644 --- a/src/gov/nasa/worldwind/layers/rpf/RPFFileIndex.java +++ b/src/gov/nasa/worldwind/layers/rpf/RPFFileIndex.java @@ -17,8 +17,8 @@ * @author dcollins * @version $Id: RPFFileIndex.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFFileIndex -{ +public class RPFFileIndex { + private final Table rpfFileTable; private final Table waveletTable; private final Table directoryTable; @@ -28,8 +28,7 @@ public class RPFFileIndex private static final int FILE_ID_LENGTH = 16; private static final int VERSION_LENGTH = 16; - public RPFFileIndex() - { + public RPFFileIndex() { this.rpfFileTable = new Table(); this.waveletTable = new Table(); this.directoryTable = new Table(); @@ -51,30 +50,24 @@ public Record newRecord(long key) { this.properties = new IndexProperties(); } - public Table getRPFFileTable() - { + public Table getRPFFileTable() { return this.rpfFileTable; } - public Table getWaveletTable() - { + public Table getWaveletTable() { return this.waveletTable; } - public Table getDirectoryTable() - { + public Table getDirectoryTable() { return this.directoryTable; } - public IndexProperties getIndexProperties() - { + public IndexProperties getIndexProperties() { return properties; } - public File getRPFFile(long key) - { - if (key == Table.INVALID_KEY) - { + public File getRPFFile(long key) { + if (key == Table.INVALID_KEY) { String message = "key is invalid: " + key; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -82,17 +75,14 @@ public File getRPFFile(long key) File file = null; RPFFileRecord rec = (RPFFileRecord) this.rpfFileTable.getRecord(key); - if (rec != null) - { + if (rec != null) { file = getFile(rec.getFilename(), rec.getDirectorySecondaryKey()); } return file; } - public File getWaveletFile(long key) - { - if (key == Table.INVALID_KEY) - { + public File getWaveletFile(long key) { + if (key == Table.INVALID_KEY) { String message = "key is invalid: " + key; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -100,28 +90,23 @@ public File getWaveletFile(long key) File file = null; WaveletRecord rec = (WaveletRecord) this.waveletTable.getRecord(key); - if (rec != null) - { + if (rec != null) { file = getFile(rec.getFilename(), rec.getDirectorySecondaryKey()); } return file; } - private File getFile(String filename, long directoryKey) - { + private File getFile(String filename, long directoryKey) { File file = null; - if (directoryKey != Table.INVALID_KEY) - { + if (directoryKey != Table.INVALID_KEY) { DirectoryRecord dirRec = (DirectoryRecord) this.directoryTable.getRecord(directoryKey); file = new File(dirRec != null ? dirRec.getPath() : null, filename); } return file; } - public Record createRPFFileRecord(File file) - { - if (file == null) - { + public Record createRPFFileRecord(File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -135,15 +120,13 @@ public Record createRPFFileRecord(File file) String filename = file.getName(); Record record = this.rpfFileTable.createRecord(); ((RPFFileRecord) record).filename = filename; - ((RPFFileRecord) record).directorySecondaryKey = dirRecord != null ? dirRecord.getKey() : Table.INVALID_KEY; + ((RPFFileRecord) record).directorySecondaryKey = dirRecord != null ? dirRecord.getKey() : Table.INVALID_KEY; return record; } - public Record createWaveletRecord(File file, long rpfFileKey) - { - if (file == null) - { + public Record createWaveletRecord(File file, long rpfFileKey) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -161,8 +144,7 @@ public Record createWaveletRecord(File file, long rpfFileKey) // Attempt to update the RPFFileRecord. Record rpfRecord = this.rpfFileTable.getRecord(rpfFileKey); - if (rpfRecord != null) - { + if (rpfRecord != null) { ((RPFFileRecord) rpfRecord).waveletSecondaryKey = record.getKey(); ((WaveletRecord) record).rpfFileSecondaryKey = rpfRecord.getKey(); } @@ -170,22 +152,17 @@ public Record createWaveletRecord(File file, long rpfFileKey) return record; } - private synchronized Record createDirectoryRecord(String path) - { + private synchronized Record createDirectoryRecord(String path) { Record record = null; - if (path != null) - { - for (Record rec : this.directoryTable.getRecords()) - { - if (((DirectoryRecord) rec).path.equals(path)) - { + if (path != null) { + for (Record rec : this.directoryTable.getRecords()) { + if (((DirectoryRecord) rec).path.equals(path)) { record = rec; break; } } - if (record == null) - { + if (record == null) { record = this.directoryTable.createRecord(); ((DirectoryRecord) record).path = path; } @@ -193,46 +170,40 @@ record = this.directoryTable.createRecord(); return record; } - public void updateBoundingSector() - { + public void updateBoundingSector() { Sector bs = null; - for (Record rec : this.rpfFileTable.getRecords()) - { + for (Record rec : this.rpfFileTable.getRecords()) { RPFFileRecord rpfRec = (RPFFileRecord) rec; Sector fs = rpfRec.getSector(); // If the entry has no sector, then ignore it. - if (fs != null) + if (fs != null) { bs = (bs != null ? bs.union(fs) : fs); + } } - if (bs != null) - { + if (bs != null) { bs = Sector.fromDegrees( - clamp(bs.getMinLatitude().degrees, -90d, 90d), - clamp(bs.getMaxLatitude().degrees, -90d, 90d), - clamp(bs.getMinLongitude().degrees, -180d, 180d), - clamp(bs.getMaxLongitude().degrees, -180d, 180d)); + clamp(bs.getMinLatitude().degrees, -90d, 90d), + clamp(bs.getMaxLatitude().degrees, -90d, 90d), + clamp(bs.getMinLongitude().degrees, -180d, 180d), + clamp(bs.getMaxLongitude().degrees, -180d, 180d)); } this.properties.setBoundingSector(bs); } - private static double clamp(double x, double min, double max) - { + private static double clamp(double x, double min, double max) { return x < min ? min : x > max ? max : x; } - public void load(java.nio.ByteBuffer buffer) throws IOException - { - if (buffer == null) - { + public void load(java.nio.ByteBuffer buffer) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String fileId = getString(buffer, FILE_ID_LENGTH); - if (!FILE_ID.equals(fileId)) - { + if (!FILE_ID.equals(fileId)) { String message = "buffer does not contain an RPFFileIndex"; Logging.logger().severe(message); throw new IOException(message); @@ -247,8 +218,7 @@ public void load(java.nio.ByteBuffer buffer) throws IOException this.directoryTable.load(buffer, locationSection.getDirectoryTableSectionLocation()); } - public java.nio.ByteBuffer save() throws IOException - { + public java.nio.ByteBuffer save() throws IOException { java.nio.ByteBuffer informationSectionBuffer = this.properties.save(); java.nio.ByteBuffer rpfFileTableBuffer = this.rpfFileTable.save(); java.nio.ByteBuffer waveletTableBuffer = this.waveletTable.save(); @@ -265,16 +235,16 @@ public java.nio.ByteBuffer save() throws IOException location += waveletTableBuffer.limit(); locationSection.setDirectoryTableSection(directoryTableBuffer.limit(), location); location += directoryTableBuffer.limit(); - + java.nio.ByteBuffer locationSectionBuffer = locationSection.save(); - int length = - FILE_ID_LENGTH + VERSION_LENGTH - + locationSectionBuffer.limit() - + informationSectionBuffer.limit() - + rpfFileTableBuffer.limit() - + waveletTableBuffer.limit() - + directoryTableBuffer.limit(); + int length + = FILE_ID_LENGTH + VERSION_LENGTH + + locationSectionBuffer.limit() + + informationSectionBuffer.limit() + + rpfFileTableBuffer.limit() + + waveletTableBuffer.limit() + + directoryTableBuffer.limit(); java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(length); putString(buffer, FILE_ID, FILE_ID_LENGTH); @@ -289,81 +259,68 @@ public java.nio.ByteBuffer save() throws IOException return buffer; } - public static class Table - { + public static class Table { + private final List records; private final Map keyIndex; private RecordFactory recordFactory; private volatile long uniqueKey = INVALID_KEY; static final long INVALID_KEY = -1L; - public Table() - { + public Table() { this.records = new ArrayList(); this.keyIndex = new HashMap(); this.recordFactory = new DefaultRecordFactory(); } - public final List getRecords() - { + public final List getRecords() { return this.records; } - public final Record getRecord(long key) - { + public final Record getRecord(long key) { Record found = null; - if (key != INVALID_KEY) - { + if (key != INVALID_KEY) { found = this.keyIndex.get(key); } return found; } - public RecordFactory getRecordFactory() - { + public RecordFactory getRecordFactory() { return this.recordFactory; } - public void setRecordFactory(RecordFactory recordFactory) - { - if (recordFactory == null) - { + public void setRecordFactory(RecordFactory recordFactory) { + if (recordFactory == null) { String message = "RecordFactory is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - + this.recordFactory = recordFactory; } - public Record createRecord() - { + public Record createRecord() { long key = createUniqueKey(); return newRecord(key); } - Record newRecord(long key) - { + Record newRecord(long key) { Record rec = this.recordFactory.newRecord(key); putRecord(key, rec); return rec; } - private void putRecord(long key, Record record) - { + private void putRecord(long key, Record record) { this.records.add(record); this.keyIndex.put(key, record); } - private synchronized long createUniqueKey() - { + private synchronized long createUniqueKey() { return ++this.uniqueKey; } - void load(java.nio.ByteBuffer buffer, int location) throws IOException - { - if (buffer == null) - { + void load(java.nio.ByteBuffer buffer, int location) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -380,10 +337,9 @@ void load(java.nio.ByteBuffer buffer, int location) throws IOException int componentLength = buffer.getInt(); int recordTableOffset = buffer.getInt(); int numRecords = buffer.getInt(); - + buffer.position(location + recordTableOffset); - for (int i = 0; i < numRecords; i++) - { + for (int i = 0; i < numRecords; i++) { long key = buffer.getLong(); Record rec = newRecord(key); rec.load(buffer); @@ -392,15 +348,13 @@ void load(java.nio.ByteBuffer buffer, int location) throws IOException buffer.position(savePos); } - java.nio.ByteBuffer save() throws IOException - { + java.nio.ByteBuffer save() throws IOException { List records = this.getRecords(); int numRecords = records.size(); int headerLength = 3 * Integer.SIZE / 8; int length = headerLength; - for (Record rec : records) - { + for (Record rec : records) { length += (Long.SIZE + rec.getSizeInBits()) / 8; } @@ -408,8 +362,7 @@ java.nio.ByteBuffer save() throws IOException buffer.putInt(length); // component length buffer.putInt(headerLength); // record table offset buffer.putInt(numRecords); // num records - for (Record rec : records) - { + for (Record rec : records) { buffer.putLong(rec.getKey()); rec.save(buffer); } @@ -418,49 +371,43 @@ java.nio.ByteBuffer save() throws IOException } } - public static class Record - { + public static class Record { + private final long key; - public Record(long key) - { + public Record(long key) { this.key = key; } - public final long getKey() - { + public final long getKey() { return this.key; } - void load(java.nio.ByteBuffer buffer) throws IOException - { + void load(java.nio.ByteBuffer buffer) throws IOException { } - void save(java.nio.ByteBuffer buffer) throws IOException - { + void save(java.nio.ByteBuffer buffer) throws IOException { } - int getSizeInBits() - { + int getSizeInBits() { return 0; } } - public static interface RecordFactory - { + public static interface RecordFactory { + Record newRecord(long key); } - private static class DefaultRecordFactory implements RecordFactory - { - public Record newRecord(long key) - { + private static class DefaultRecordFactory implements RecordFactory { + + public Record newRecord(long key) { return new Record(key); } } - public static class RPFFileRecord extends Record - { + public static class RPFFileRecord extends Record { + private String filename; private long directorySecondaryKey = Table.INVALID_KEY; private long waveletSecondaryKey = Table.INVALID_KEY; @@ -469,64 +416,54 @@ public static class RPFFileRecord extends Record private Angle minLongitude; private Angle maxLongitude; private static int FILENAME_LENGTH = 12; - private static int SIZE = - (FILENAME_LENGTH * Byte.SIZE) // Filename. - + Long.SIZE // Directory path secondary key. - + Long.SIZE // Wavelet file secondary key. - + (4 * Double.SIZE); // min-latitude, max-latitude, min-longitude, and max-longitude. - - public RPFFileRecord(long key) - { + private static int SIZE + = (FILENAME_LENGTH * Byte.SIZE) // Filename. + + Long.SIZE // Directory path secondary key. + + Long.SIZE // Wavelet file secondary key. + + (4 * Double.SIZE); // min-latitude, max-latitude, min-longitude, and max-longitude. + + public RPFFileRecord(long key) { super(key); } - public String getFilename() - { + public String getFilename() { return this.filename; } - public void setFilename(String filename) - { + public void setFilename(String filename) { this.filename = filename; } - public long getDirectorySecondaryKey() - { + public long getDirectorySecondaryKey() { return this.directorySecondaryKey; } - public long getWaveletSecondaryKey() - { + public long getWaveletSecondaryKey() { return this.waveletSecondaryKey; } - public Sector getSector() - { + public Sector getSector() { Sector sector = null; if (this.minLatitude != null - && this.maxLatitude != null - && this.minLongitude != null - && this.maxLongitude != null) - { + && this.maxLatitude != null + && this.minLongitude != null + && this.maxLongitude != null) { sector = new Sector( - this.minLatitude, this.maxLatitude, - this.minLongitude, this.maxLongitude); + this.minLatitude, this.maxLatitude, + this.minLongitude, this.maxLongitude); } return sector; } - public void setSector(Sector sector) - { + public void setSector(Sector sector) { this.minLatitude = sector != null ? sector.getMinLatitude() : null; this.maxLatitude = sector != null ? sector.getMaxLatitude() : null; this.minLongitude = sector != null ? sector.getMinLongitude() : null; this.maxLongitude = sector != null ? sector.getMaxLongitude() : null; } - void load(java.nio.ByteBuffer buffer) throws IOException - { - if (buffer == null) - { + void load(java.nio.ByteBuffer buffer) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -541,10 +478,8 @@ void load(java.nio.ByteBuffer buffer) throws IOException this.maxLongitude = getAngle(buffer); } - void save(java.nio.ByteBuffer buffer) throws IOException - { - if (buffer == null) - { + void save(java.nio.ByteBuffer buffer) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -559,52 +494,44 @@ void save(java.nio.ByteBuffer buffer) throws IOException putAngle(buffer, this.maxLongitude); } - int getSizeInBits() - { + int getSizeInBits() { return SIZE + super.getSizeInBits(); } } - public static class WaveletRecord extends Record - { + public static class WaveletRecord extends Record { + private String filename; private long directorySecondaryKey = Table.INVALID_KEY; private long rpfFileSecondaryKey = Table.INVALID_KEY; private static int FILENAME_LENGTH = 16; - private static int SIZE = - (FILENAME_LENGTH * Byte.SIZE) // Filename. - + Long.SIZE // Directory path secondary key. - + Long.SIZE; // RPF file secondary key. + private static int SIZE + = (FILENAME_LENGTH * Byte.SIZE) // Filename. + + Long.SIZE // Directory path secondary key. + + Long.SIZE; // RPF file secondary key. - public WaveletRecord(long key) - { + public WaveletRecord(long key) { super(key); } - public String getFilename() - { + public String getFilename() { return this.filename; } - public void setFilename(String filename) - { + public void setFilename(String filename) { this.filename = filename; } - public long getDirectorySecondaryKey() - { + public long getDirectorySecondaryKey() { return this.directorySecondaryKey; } - public long getRPFFileSecondaryKey() - { + public long getRPFFileSecondaryKey() { return this.rpfFileSecondaryKey; } - void load(java.nio.ByteBuffer buffer) throws IOException - { - if (buffer == null) - { + void load(java.nio.ByteBuffer buffer) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -615,10 +542,8 @@ void load(java.nio.ByteBuffer buffer) throws IOException this.rpfFileSecondaryKey = buffer.getLong(); } - void save(java.nio.ByteBuffer buffer) throws IOException - { - if (buffer == null) - { + void save(java.nio.ByteBuffer buffer) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -629,33 +554,28 @@ void save(java.nio.ByteBuffer buffer) throws IOException buffer.putLong(this.rpfFileSecondaryKey); } - int getSizeInBits() - { + int getSizeInBits() { return SIZE + super.getSizeInBits(); } } - public static class DirectoryRecord extends Record - { + public static class DirectoryRecord extends Record { + private String path; private static int PATH_LENGTH = 512; - private static int SIZE = - (PATH_LENGTH * Byte.SIZE); // Path. + private static int SIZE + = (PATH_LENGTH * Byte.SIZE); // Path. - public DirectoryRecord(long key) - { + public DirectoryRecord(long key) { super(key); } - public String getPath() - { + public String getPath() { return this.path; } - public void setPath(String path) - { - if (path == null) - { + public void setPath(String path) { + if (path == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -664,10 +584,8 @@ public void setPath(String path) this.path = path; } - void load(java.nio.ByteBuffer buffer) throws IOException - { - if (buffer == null) - { + void load(java.nio.ByteBuffer buffer) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -676,10 +594,8 @@ void load(java.nio.ByteBuffer buffer) throws IOException this.path = getString(buffer, PATH_LENGTH); } - void save(java.nio.ByteBuffer buffer) throws IOException - { - if (buffer == null) - { + void save(java.nio.ByteBuffer buffer) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -688,14 +604,13 @@ void save(java.nio.ByteBuffer buffer) throws IOException putString(buffer, this.path, PATH_LENGTH); } - int getSizeInBits() - { + int getSizeInBits() { return SIZE + super.getSizeInBits(); } } - public static class IndexProperties - { + public static class IndexProperties { + public String rootPath; public String dataSeriesIdentifier; public String description; @@ -706,74 +621,62 @@ public static class IndexProperties private static int ROOT_PATH_LENGTH = 512; private static int DATA_SERIES_ID_LENGTH = 512; private static int DESCRIPTION_LENGTH = 4096; - private static int SIZE = - Integer.SIZE // Section length. - + (ROOT_PATH_LENGTH * Byte.SIZE) // Root path. - + (DATA_SERIES_ID_LENGTH * Byte.SIZE) // Data series identifier. - + (DESCRIPTION_LENGTH * Byte.SIZE) // Description. - + (4 * Double.SIZE); // min-latitude, max-latitude, min-longitude, and max-longitude. + private static int SIZE + = Integer.SIZE // Section length. + + (ROOT_PATH_LENGTH * Byte.SIZE) // Root path. + + (DATA_SERIES_ID_LENGTH * Byte.SIZE) // Data series identifier. + + (DESCRIPTION_LENGTH * Byte.SIZE) // Description. + + (4 * Double.SIZE); // min-latitude, max-latitude, min-longitude, and max-longitude. - public IndexProperties() - { + public IndexProperties() { } - public String getRootPath() - { + public String getRootPath() { return this.rootPath; } - public void setRootPath(String rootPath) - { + public void setRootPath(String rootPath) { this.rootPath = rootPath; } - public String getDataSeriesIdentifier() - { + public String getDataSeriesIdentifier() { return this.dataSeriesIdentifier; } - public void setDataSeriesIdentifier(String dataSeriesIdentifier) - { + public void setDataSeriesIdentifier(String dataSeriesIdentifier) { this.dataSeriesIdentifier = dataSeriesIdentifier; } - public String getDescription() - { + public String getDescription() { return this.description; } - public void setDescription(String description) - { + public void setDescription(String description) { this.description = description; } - public Sector getBoundingSector() - { + public Sector getBoundingSector() { Sector sector = null; if (this.minLatitude != null - && this.maxLatitude != null - && this.minLongitude != null - && this.maxLongitude != null) - { + && this.maxLatitude != null + && this.minLongitude != null + && this.maxLongitude != null) { sector = new Sector( - this.minLatitude, this.maxLatitude, - this.minLongitude, this.maxLongitude); + this.minLatitude, this.maxLatitude, + this.minLongitude, this.maxLongitude); } return sector; } - public void setBoundingSector(Sector sector) - { + public void setBoundingSector(Sector sector) { this.minLatitude = sector != null ? sector.getMinLatitude() : null; this.maxLatitude = sector != null ? sector.getMaxLatitude() : null; this.minLongitude = sector != null ? sector.getMinLongitude() : null; this.maxLongitude = sector != null ? sector.getMaxLongitude() : null; } - void load(java.nio.ByteBuffer buffer, int location) throws IOException - { - if (buffer == null) - { + void load(java.nio.ByteBuffer buffer, int location) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -795,8 +698,7 @@ void load(java.nio.ByteBuffer buffer, int location) throws IOException buffer.position(savePos); } - java.nio.ByteBuffer save() throws IOException - { + java.nio.ByteBuffer save() throws IOException { int length = SIZE / 8; java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(length); buffer.putInt(length); @@ -812,26 +714,25 @@ java.nio.ByteBuffer save() throws IOException } } - private static class LocationSection - { + private static class LocationSection { + public int locationSectionLength; public int componentLocationTableOffset; public int numOfComponentLocationRecords; - private java.util.Map table = - new java.util.HashMap(); + private java.util.Map table + = new java.util.HashMap(); - public LocationSection() - { - for (int i = 1; i <= 4; i++) + public LocationSection() { + for (int i = 1; i <= 4; i++) { this.table.put(i, new ComponentLocationRecord(i, -1, -1)); + } this.locationSectionLength = (3 * Integer.SIZE / 8) + (this.table.size() * 3 * Integer.SIZE / 8); this.componentLocationTableOffset = (3 * Integer.SIZE / 8); this.numOfComponentLocationRecords = this.table.size(); } - public LocationSection(java.nio.ByteBuffer buffer) throws IOException - { + public LocationSection(java.nio.ByteBuffer buffer) throws IOException { int savePos = buffer.position(); this.locationSectionLength = buffer.getInt(); @@ -839,20 +740,18 @@ public LocationSection(java.nio.ByteBuffer buffer) throws IOException this.numOfComponentLocationRecords = buffer.getInt(); buffer.position(savePos + this.componentLocationTableOffset); - for (int i = 0; i < this.numOfComponentLocationRecords; i++) - { + for (int i = 0; i < this.numOfComponentLocationRecords; i++) { int id = buffer.getInt(); table.put(id, new ComponentLocationRecord(id, - buffer.getInt(), // length - buffer.getInt() // location + buffer.getInt(), // length + buffer.getInt() // location )); } buffer.position(savePos); } - public java.nio.ByteBuffer save() throws IOException - { + public java.nio.ByteBuffer save() throws IOException { java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(this.locationSectionLength); buffer.putInt(this.locationSectionLength); buffer.putInt(this.componentLocationTableOffset); @@ -863,8 +762,7 @@ public java.nio.ByteBuffer save() throws IOException records.toArray(recordArray); buffer.position(this.componentLocationTableOffset); - for (int i = 0; i < this.numOfComponentLocationRecords; i++) - { + for (int i = 0; i < this.numOfComponentLocationRecords; i++) { ComponentLocationRecord rec = recordArray[i]; buffer.putInt(rec.getId()); buffer.putInt(rec.getLength()); @@ -875,120 +773,100 @@ public java.nio.ByteBuffer save() throws IOException return buffer; } - public int getInformationSectionLocation() - { + public int getInformationSectionLocation() { return getLocation(1); } - public int getInformationSectionLength() - { + public int getInformationSectionLength() { return getLength(1); } - public void setInformationSection(int length, int location) - { + public void setInformationSection(int length, int location) { set(1, length, location); } - public int getRPFFileTableSectionLocation() - { + public int getRPFFileTableSectionLocation() { return getLocation(2); } - public int getRPFFileTableSectionLength() - { + public int getRPFFileTableSectionLength() { return getLength(2); } - public void setRPFFileTableSection(int length, int location) - { + public void setRPFFileTableSection(int length, int location) { set(2, length, location); } - public int getWaveletTableSectionLocation() - { + public int getWaveletTableSectionLocation() { return getLocation(3); } - public int getWaveletTableSectionLength() - { + public int getWaveletTableSectionLength() { return getLength(3); } - public void setWaveletTableSection(int length, int location) - { + public void setWaveletTableSection(int length, int location) { set(3, length, location); } - public int getDirectoryTableSectionLocation() - { + public int getDirectoryTableSectionLocation() { return getLocation(4); } - public int getDirectoryTableSectionLength() - { + public int getDirectoryTableSectionLength() { return getLength(4); } - public void setDirectoryTableSection(int length, int location) - { + public void setDirectoryTableSection(int length, int location) { set(4, length, location); } - private int getLocation(int componentID) - { + private int getLocation(int componentID) { ComponentLocationRecord rec = this.getRecord(componentID); return (null != rec) ? rec.getLocation() : 0; } - private int getLength(int componentID) - { + private int getLength(int componentID) { ComponentLocationRecord rec = this.getRecord(componentID); return (null != rec) ? rec.getLength() : 0; } - private void set(int componentID, int length, int location) - { + private void set(int componentID, int length, int location) { ComponentLocationRecord rec = this.getRecord(componentID); - if (rec != null) - { + if (rec != null) { rec.length = length; rec.location = location; } } - private ComponentLocationRecord getRecord(int componentID) - { - if(table.containsKey(componentID)) + private ComponentLocationRecord getRecord(int componentID) { + if (table.containsKey(componentID)) { return table.get(componentID); + } return null; } - public static class ComponentLocationRecord - { - private int id; + public static class ComponentLocationRecord { + + private int id; private int length; private int location; - public ComponentLocationRecord(int id, int length, int location) - { + public ComponentLocationRecord(int id, int length, int location) { this.id = id; this.length = length; this.location = location; } - public int getId() - { + public int getId() { return id; } - public int getLength() - { + public int getLength() { return length; } - public int getLocation() - { + public int getLocation() { return location; } } @@ -996,11 +874,9 @@ public int getLocation() private static final String CHARACTER_ENCODING = "UTF-8"; - private static String getString(java.nio.ByteBuffer buffer, int len) throws IOException - { + private static String getString(java.nio.ByteBuffer buffer, int len) throws IOException { String s = null; - if (buffer != null && buffer.remaining() >= len) - { + if (buffer != null && buffer.remaining() >= len) { byte[] dest = new byte[len]; buffer.get(dest, 0, len); s = new String(dest, CHARACTER_ENCODING).trim(); @@ -1008,16 +884,12 @@ private static String getString(java.nio.ByteBuffer buffer, int len) throws IOEx return s; } - private static void putString(java.nio.ByteBuffer buffer, String s, int len) throws IOException - { - if (buffer != null) - { + private static void putString(java.nio.ByteBuffer buffer, String s, int len) throws IOException { + if (buffer != null) { byte[] src = new byte[len]; - if (s != null) - { + if (s != null) { byte[] utfBytes = s.getBytes(CHARACTER_ENCODING); - if (utfBytes != null) - { + if (utfBytes != null) { System.arraycopy(utfBytes, 0, src, 0, utfBytes.length); } } @@ -1025,28 +897,23 @@ private static void putString(java.nio.ByteBuffer buffer, String s, int len) thr } } - private static Angle getAngle(java.nio.ByteBuffer buffer) - { + private static Angle getAngle(java.nio.ByteBuffer buffer) { // The binary description of an angle needs to distinguish between // non-null and null. We use Double.NaN as a marker for a null-value. Angle a = null; - if (buffer != null) - { + if (buffer != null) { double value = buffer.getDouble(); - if (!Double.isNaN(value)) - { + if (!Double.isNaN(value)) { a = Angle.fromDegrees(value); } } return a; } - private static void putAngle(java.nio.ByteBuffer buffer, Angle angle) - { + private static void putAngle(java.nio.ByteBuffer buffer, Angle angle) { // The binary description of an angle needs to distinguish between // non-null and null. We use Double.NaN as a marker for a null-value. - if (buffer != null) - { + if (buffer != null) { double value = angle != null ? angle.degrees : Double.NaN; buffer.putDouble(value); } diff --git a/src/gov/nasa/worldwind/layers/rpf/RPFGenerator.java b/src/gov/nasa/worldwind/layers/rpf/RPFGenerator.java index 842389eb02..36c38960e5 100644 --- a/src/gov/nasa/worldwind/layers/rpf/RPFGenerator.java +++ b/src/gov/nasa/worldwind/layers/rpf/RPFGenerator.java @@ -22,8 +22,8 @@ * @author brownrigg * @version $Id: RPFGenerator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class RPFGenerator -{ +class RPFGenerator { + @SuppressWarnings({"FieldCanBeLocal"}) private final RPFFileIndex fileIndex; private final FrameFile[] frameFiles; @@ -38,10 +38,8 @@ class RPFGenerator public static final String WAVELET_IMAGE_THRESHOLD = "RPFGenerator.WaveletImageThreshold"; public static final String WAVELET_PRELOAD_SIZE = "RPFGenerator.WaveletPreloadSize"; - public RPFGenerator(AVList params) - { - if (params == null) - { + public RPFGenerator(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -58,66 +56,57 @@ public RPFGenerator(AVList params) this.preloadRes = (Integer) params.getValue(WAVELET_PRELOAD_SIZE); } - private static AVList initParams(AVList params) - { - if (params == null) - { + private static AVList initParams(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params.getValue(RPF_FILE_INDEX) == null) - { + if (params.getValue(RPF_FILE_INDEX) == null) { String message = "RPFFileIndex is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(WAVELET_IMAGE_THRESHOLD); - if (o == null || !(o instanceof Integer)) + if (o == null || !(o instanceof Integer)) { params.setValue(WAVELET_IMAGE_THRESHOLD, 256); + } o = params.getValue(WAVELET_PRELOAD_SIZE); - if (o == null || !(o instanceof Integer) || !WWMath.isPowerOfTwo((Integer) o)) + if (o == null || !(o instanceof Integer) || !WWMath.isPowerOfTwo((Integer) o)) { params.setValue(WAVELET_PRELOAD_SIZE, 32); + } return params; } - public Sector getGlobalBounds() - { + public Sector getGlobalBounds() { return this.globalBounds; } - public RPFServiceInstance getServiceInstance() - { + public RPFServiceInstance getServiceInstance() { return new RPFServiceInstance(); } - private FrameFile[] loadFrameFiles(RPFFileIndex fileIndex) - { + private FrameFile[] loadFrameFiles(RPFFileIndex fileIndex) { Collection list = new ArrayList(); long frameId = -1; RPFFileIndex.Table fileTable = fileIndex.getRPFFileTable(); - if (fileTable != null) - { - for (RPFFileIndex.Record record : fileTable.getRecords()) - { + if (fileTable != null) { + for (RPFFileIndex.Record record : fileTable.getRecords()) { ++frameId; RPFFileIndex.RPFFileRecord rpfRecord = (RPFFileIndex.RPFFileRecord) record; long rpfKey = record.getKey(); long waveletKey = rpfRecord.getWaveletSecondaryKey(); Sector sector = rpfRecord.getSector(); - if (rpfKey != -1 && waveletKey != -1 && sector != null) - { + if (rpfKey != -1 && waveletKey != -1 && sector != null) { File rpfFile = fileIndex.getRPFFile(rpfKey); File waveletFile = fileIndex.getWaveletFile(waveletKey); list.add(new FrameFile(frameId, rpfFile, waveletFile, sector)); - } - else - { + } else { String message = "Ignoring frame file: " + (rpfKey != -1 ? fileIndex.getRPFFile(rpfKey).getPath() : "?"); Logging.logger().fine(message); } @@ -132,13 +121,14 @@ private FrameFile[] loadFrameFiles(RPFFileIndex fileIndex) // // Find the global bounds for this collection of frame files (i.e., the union of their Sectors). // - private Sector computeGlobalBounds(RPFFileIndex fileIndex) - { + private Sector computeGlobalBounds(RPFFileIndex fileIndex) { Sector gb = null; - if (fileIndex != null && fileIndex.getIndexProperties() != null) + if (fileIndex != null && fileIndex.getIndexProperties() != null) { gb = fileIndex.getIndexProperties().getBoundingSector(); - if (gb == null) + } + if (gb == null) { gb = Sector.EMPTY_SECTOR; + } return gb; } @@ -148,8 +138,8 @@ private Sector computeGlobalBounds(RPFFileIndex fileIndex) // A small private class to bundle info about framefiles. // Public access to fields is intentional. // - private static class FrameFile - { + private static class FrameFile { + public long id; public File rpfFile; public File waveletFile; @@ -158,8 +148,7 @@ private static class FrameFile public RPFFrameFilename frameFile; public RPFFrameTransform transform; - public FrameFile(long id, File rpfFile, File waveletFile, Sector sector) - { + public FrameFile(long id, File rpfFile, File waveletFile, Sector sector) { this.id = id; this.rpfFile = rpfFile; this.waveletFile = waveletFile; @@ -167,13 +156,11 @@ public FrameFile(long id, File rpfFile, File waveletFile, Sector sector) this.frameFile = RPFFrameFilename.parseFilename(rpfFile.getName().toUpperCase()); } - public RPFFrameTransform getFrameTransform() - { - if (this.transform == null) - { + public RPFFrameTransform getFrameTransform() { + if (this.transform == null) { RPFDataSeries dataSeries = RPFDataSeries.dataSeriesFor(this.frameFile.getDataSeriesCode()); this.transform = RPFFrameTransform.createFrameTransform(this.frameFile.getZoneCode(), - dataSeries.rpfDataType, dataSeries.scaleOrGSD); + dataSeries.rpfDataType, dataSeries.scaleOrGSD); } return this.transform; } @@ -189,32 +176,28 @@ public int getFrameNumber() { // // Used to manage per-request state. // - public class RPFServiceInstance - { + public class RPFServiceInstance { + public static final String BBOX = "bbox"; public static final String WIDTH = "width"; public static final String HEIGHT = "height"; - public RPFServiceInstance() - {} + public RPFServiceInstance() { + } - public BufferedImage serviceRequest(AVList params) throws IOException - { - if (params == null) - { + public BufferedImage serviceRequest(AVList params) throws IOException { + if (params == null) { String message = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String message = this.validate(params); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Sector reqSector = (Sector) params.getValue(BBOX); int reqWidth = (Integer) params.getValue(WIDTH); int reqHeight = (Integer) params.getValue(HEIGHT); @@ -222,19 +205,16 @@ public BufferedImage serviceRequest(AVList params) throws IOException BufferedImage reqImage = new BufferedImage(reqWidth, reqHeight, BufferedImage.TYPE_4BYTE_ABGR); int numFramesInRequest = 0; - for (FrameFile frame : RPFGenerator.this.frameFiles) - { - try - { + for (FrameFile frame : RPFGenerator.this.frameFiles) { + try { // The call to getSector() can throw an exception if the file is // named with an inappropriate frameNumber for the dataseries/zone. // We don't want these to short circuit the entire request, so // trap any such occurances and ignore 'em. - if (!reqSector.intersects(frame.sector)) + if (!reqSector.intersects(frame.sector)) { continue; - } - catch (Exception e) - { + } + } catch (Exception e) { /* ignore this framefile */ String msg = String.format("Exception while computing frame bounds: %s", frame.rpfFile); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); @@ -242,8 +222,9 @@ public BufferedImage serviceRequest(AVList params) throws IOException continue; } - if (RPFGenerator.this.isFrameFileAbsent(frame)) + if (RPFGenerator.this.isFrameFileAbsent(frame)) { continue; + } Sector frameSector = frame.sector; @@ -254,57 +235,52 @@ public BufferedImage serviceRequest(AVList params) throws IOException // Depending upon footprint, either get image from it RPF framefile, or reconstruct // it from a wavelet encoding. BufferedImage sourceImage; - if (footprintX > smallImageSize || footprintY > smallImageSize) - { + if (footprintX > smallImageSize || footprintY > smallImageSize) { RPFFrameTransform.RPFImage[] images = getImageFromRPFSource(frame); - if (images == null) - continue; - for (RPFFrameTransform.RPFImage image : images) { - if (image.getSector() == null || image.getImage() == null) continue; - drawImageIntoRequest(reqImage, reqSector, image.getImage(), image.getSector()); - } - } - else - { - int maxRes = footprintX; - maxRes = (footprintY > maxRes) ? footprintY : maxRes; - int power = (int) Math.ceil(Math.log(maxRes) / Math.log(2.)); - int res = (int) Math.pow(2., power); - res = Math.max(1, res); - - sourceImage = getImageFromWaveletEncoding(frame, res); - if (sourceImage == null) - continue; - drawImageIntoRequest(reqImage, reqSector, sourceImage, frameSector); + if (images == null) { + continue; + } + for (RPFFrameTransform.RPFImage image : images) { + if (image.getSector() == null || image.getImage() == null) { + continue; + } + drawImageIntoRequest(reqImage, reqSector, image.getImage(), image.getSector()); + } + } else { + int maxRes = footprintX; + maxRes = (footprintY > maxRes) ? footprintY : maxRes; + int power = (int) Math.ceil(Math.log(maxRes) / Math.log(2.)); + int res = (int) Math.pow(2., power); + res = Math.max(1, res); + + sourceImage = getImageFromWaveletEncoding(frame, res); + if (sourceImage == null) { + continue; + } + drawImageIntoRequest(reqImage, reqSector, sourceImage, frameSector); } ++numFramesInRequest; } - if (numFramesInRequest <= 0) + if (numFramesInRequest <= 0) { return null; + } return reqImage; - } - catch (Exception e) - { + } catch (Exception e) { String msg = "Exception while processing request"; Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); throw new IOException(msg); } } - private void drawImageIntoRequest(BufferedImage reqImage, Sector reqSector, BufferedImage srcImage, Sector srcSector) - { + private void drawImageIntoRequest(BufferedImage reqImage, Sector reqSector, BufferedImage srcImage, Sector srcSector) { - double tx = (srcSector.getMinLongitude().degrees - reqSector.getMinLongitude().degrees) * ( - reqImage.getWidth() / reqSector.getDeltaLonDegrees()); - double ty = (reqSector.getMaxLatitude().degrees - srcSector.getMaxLatitude().degrees) * ( - reqImage.getHeight() / reqSector.getDeltaLatDegrees()); - double sx = (reqImage.getWidth() / reqSector.getDeltaLonDegrees()) * ( - srcSector.getDeltaLonDegrees() / srcImage.getWidth()); - double sy = (reqImage.getHeight() / reqSector.getDeltaLatDegrees()) * ( - srcSector.getDeltaLatDegrees() / srcImage.getHeight()); + double tx = (srcSector.getMinLongitude().degrees - reqSector.getMinLongitude().degrees) * (reqImage.getWidth() / reqSector.getDeltaLonDegrees()); + double ty = (reqSector.getMaxLatitude().degrees - srcSector.getMaxLatitude().degrees) * (reqImage.getHeight() / reqSector.getDeltaLatDegrees()); + double sx = (reqImage.getWidth() / reqSector.getDeltaLonDegrees()) * (srcSector.getDeltaLonDegrees() / srcImage.getWidth()); + double sy = (reqImage.getHeight() / reqSector.getDeltaLatDegrees()) * (srcSector.getDeltaLatDegrees() / srcImage.getHeight()); Graphics2D g2d = (Graphics2D) reqImage.getGraphics(); AffineTransform xform = g2d.getTransform(); @@ -314,12 +290,8 @@ private void drawImageIntoRequest(BufferedImage reqImage, Sector reqSector, Buff g2d.setTransform(xform); } - - - public BufferedImage serviceRequest(URL url) throws IOException - { - if (url == null) - { + public BufferedImage serviceRequest(URL url) throws IOException { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -328,14 +300,13 @@ public BufferedImage serviceRequest(URL url) throws IOException AVList params = new AVListImpl(); // Extract query parameters from the URL, placing them in the AVList. String query = url.getQuery(); - if (query != null) - { + if (query != null) { String[] pairs = query.split("&"); - for (String s : pairs) - { + for (String s : pairs) { String[] keyvalue = s.split("=", 2); - if (keyvalue != null && keyvalue.length == 2) + if (keyvalue != null && keyvalue.length == 2) { params.setValue(keyvalue[0], keyvalue[1]); + } } } // Convert parameter values to the appropriate type. @@ -350,47 +321,44 @@ public BufferedImage serviceRequest(URL url) throws IOException * @param params the list of parameters to validate. * @return null if valid, otherwise a String containing a description of why it's invalid. */ - private String validate(AVList params) - { + private String validate(AVList params) { StringBuffer sb = new StringBuffer(); Object o = params.getValue(BBOX); - if (o == null || !(o instanceof Sector)) + if (o == null || !(o instanceof Sector)) { sb.append("bounding box"); + } o = params.getValue(WIDTH); - if (o == null || !(o instanceof Integer) || ((Integer) o) < 1) + if (o == null || !(o instanceof Integer) || ((Integer) o) < 1) { sb.append("width"); + } o = params.getValue(HEIGHT); - if (o == null || !(o instanceof Integer) || ((Integer) o) < 1) + if (o == null || !(o instanceof Integer) || ((Integer) o) < 1) { sb.append("height"); + } - if (sb.length() == 0) + if (sb.length() == 0) { return null; + } return "Inavlid RPFGenerator service request fields: " + sb.toString(); } - private AVList initParams(AVList params) - { + private AVList initParams(AVList params) { String s = params.getStringValue(BBOX); - if (s != null) - { + if (s != null) { String[] values = s.split(","); - if (values != null && values.length == 4) - { - try - { + if (values != null && values.length == 4) { + try { // Bounding box string is expected in WMS format: "minlon,minlat,maxlon,maxlat" double minLon = Double.parseDouble(values[0]); double minLat = Double.parseDouble(values[1]); double maxLon = Double.parseDouble(values[2]); double maxLat = Double.parseDouble(values[3]); params.setValue(BBOX, Sector.fromDegrees(minLat, maxLat, minLon, maxLon)); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(java.util.logging.Level.WARNING, "Parameter conversion error", e); params.setValue(BBOX, null); } @@ -398,30 +366,22 @@ private AVList initParams(AVList params) } s = params.getStringValue(WIDTH); - if (s != null) - { - try - { + if (s != null) { + try { int value = Integer.parseInt(s); params.setValue(WIDTH, value); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(java.util.logging.Level.WARNING, "Parameter conversion error", e); params.setValue(WIDTH, null); } } s = params.getStringValue(HEIGHT); - if (s != null) - { - try - { + if (s != null) { + try { int value = Integer.parseInt(s); params.setValue(HEIGHT, value); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(java.util.logging.Level.WARNING, "Parameter conversion error", e); params.setValue(HEIGHT, null); } @@ -433,17 +393,13 @@ private AVList initParams(AVList params) // // Attempts to return the specified FrameFile as a BufferedImage. Returns null on failure. // - private RPFFrameTransform.RPFImage[] getImageFromRPFSource(FrameFile frame) - { - try - { + private RPFFrameTransform.RPFImage[] getImageFromRPFSource(FrameFile frame) { + try { File file = frame.rpfFile; RPFImageFile sourceFile = RPFImageFile.load(file); BufferedImage image = sourceFile.getBufferedImage(); return frame.getFrameTransform().deproject(frame.getFrameNumber(), image); - } - catch (Exception e) - { + } catch (Exception e) { String message = "Exception while reading frame file: " + frame.rpfFile; Logging.logger().log(java.util.logging.Level.SEVERE, message, e); RPFGenerator.this.markFrameFileAbsent(frame); @@ -455,39 +411,33 @@ private RPFFrameTransform.RPFImage[] getImageFromRPFSource(FrameFile frame) // Attempts to reconstruct the given FrameFile as a BufferedImage from a WaveletEncoding. // Returns null if encoding does not exist or on any other failure. // - private BufferedImage getImageFromWaveletEncoding(FrameFile frame, int resolution) - { - if (resolution <= 0) + private BufferedImage getImageFromWaveletEncoding(FrameFile frame, int resolution) { + if (resolution <= 0) { return null; + } - try - { + try { WaveletCodec codec; - if (resolution <= RPFGenerator.this.preloadRes) - { + if (resolution <= RPFGenerator.this.preloadRes) { // Lazily load the wavelet up to "preload resolution". - if (frame.codec == null) - { + if (frame.codec == null) { java.nio.ByteBuffer buffer = WWIO.readFileToBuffer(frame.waveletFile); frame.codec = WaveletCodec.loadPartial(buffer, RPFGenerator.this.preloadRes); } codec = frame.codec; - } - else - { + } else { // Read wavelet file. java.nio.ByteBuffer buffer = WWIO.readFileToBuffer(frame.waveletFile); codec = WaveletCodec.loadPartial(buffer, resolution); } BufferedImage sourceImage = null; - if (codec != null) + if (codec != null) { sourceImage = codec.reconstruct(resolution); + } return sourceImage; - } - catch (Exception e) - { + } catch (Exception e) { String message = "Exception while reading wavelet file: " + frame.waveletFile; Logging.logger().log(java.util.logging.Level.SEVERE, message, e); RPFGenerator.this.markFrameFileAbsent(frame); @@ -496,13 +446,11 @@ private BufferedImage getImageFromWaveletEncoding(FrameFile frame, int resolutio } } - private void markFrameFileAbsent(FrameFile frame) - { + private void markFrameFileAbsent(FrameFile frame) { this.absentFrames.markResourceAbsent(frame.id); } - private boolean isFrameFileAbsent(FrameFile frame) - { + private boolean isFrameFileAbsent(FrameFile frame) { return this.absentFrames.isResourceAbsent(frame.id); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/layers/rpf/RPFRetriever.java b/src/gov/nasa/worldwind/layers/rpf/RPFRetriever.java index 63fa5edf4f..f868d37963 100644 --- a/src/gov/nasa/worldwind/layers/rpf/RPFRetriever.java +++ b/src/gov/nasa/worldwind/layers/rpf/RPFRetriever.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: RPFRetriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class RPFRetriever extends WWObjectImpl implements Retriever -{ +class RPFRetriever extends WWObjectImpl implements Retriever { + private volatile ByteBuffer byteBuffer; private volatile int contentLength = 0; private AtomicInteger contentLengthRead = new AtomicInteger(0); @@ -43,22 +43,18 @@ class RPFRetriever extends WWObjectImpl implements Retriever public static final int RESPONSE_CODE_OK = 1; public static final int RESPONSE_CODE_NO_CONTENT = 2; - public RPFRetriever(RPFGenerator.RPFServiceInstance service, URL url, RetrievalPostProcessor postProcessor) - { - if (service == null) - { + public RPFRetriever(RPFGenerator.RPFServiceInstance service, URL url, RetrievalPostProcessor postProcessor) { + if (service == null) { String message = "Service is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (url == null) - { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (postProcessor == null) - { + if (postProcessor == null) { String message = Logging.getMessage("nullValue.PostProcessorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -69,38 +65,31 @@ public RPFRetriever(RPFGenerator.RPFServiceInstance service, URL url, RetrievalP this.postProcessor = postProcessor; } - public final ByteBuffer getBuffer() - { + public final ByteBuffer getBuffer() { return this.byteBuffer; } - public final int getContentLength() - { + public final int getContentLength() { return this.contentLength; } - public final int getContentLengthRead() - { + public final int getContentLengthRead() { return this.contentLengthRead.get(); } - protected void setContentLengthRead(int length) - { + protected void setContentLengthRead(int length) { this.contentLengthRead.set(length); } - public final String getName() - { + public final String getName() { return this.url.toString(); } - public final String getState() - { + public final String getState() { return this.state; } - public final String getContentType() - { + public final String getContentType() { return this.contentType; } @@ -109,138 +98,114 @@ public final String getContentType() * * @return Always returns zero (no expiration). */ - public long getExpirationTime() - { + public long getExpirationTime() { return 0; } - public long getSubmitTime() - { + public long getSubmitTime() { return this.submitTime; } - public void setSubmitTime(long submitTime) - { + public void setSubmitTime(long submitTime) { this.submitTime = submitTime; } - public long getBeginTime() - { + public long getBeginTime() { return this.beginTime; } - public void setBeginTime(long beginTime) - { + public void setBeginTime(long beginTime) { this.beginTime = beginTime; } - public long getEndTime() - { + public long getEndTime() { return this.endTime; } - public void setEndTime(long endTime) - { + public void setEndTime(long endTime) { this.endTime = endTime; } - public int getConnectTimeout() - { + public int getConnectTimeout() { return this.connectTimeout; } - public void setConnectTimeout(int connectTimeout) - { + public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } - public int getReadTimeout() - { + public int getReadTimeout() { return this.readTimeout; } - public void setReadTimeout(int readTimeout) - { + public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } - public int getStaleRequestLimit() - { + public int getStaleRequestLimit() { return this.staleRequestLimit; } - public void setStaleRequestLimit(int staleRequestLimit) - { + public void setStaleRequestLimit(int staleRequestLimit) { this.staleRequestLimit = staleRequestLimit; } - public final RPFGenerator.RPFServiceInstance getService() - { + public final RPFGenerator.RPFServiceInstance getService() { return this.service; } - public final URL getURL() - { + public final URL getURL() { return this.url; } - public final RetrievalPostProcessor getPostProcessor() - { + public final RetrievalPostProcessor getPostProcessor() { return this.postProcessor; } - public int getResponseCode() - { + public int getResponseCode() { return this.responseCode; } - public final Retriever call() throws Exception - { - if (interrupted()) + public final Retriever call() throws Exception { + if (interrupted()) { return this; + } - try - { + try { setState(RETRIEVER_STATE_STARTED); // Simulate connected state. - if (!interrupted()) + if (!interrupted()) { setState(RETRIEVER_STATE_CONNECTING); + } - if (!interrupted()) - { + if (!interrupted()) { setState(RETRIEVER_STATE_READING); this.byteBuffer = read(); } - if (!interrupted()) + if (!interrupted()) { setState(RETRIEVER_STATE_SUCCESSFUL); - } - catch (Exception e) - { + } + } catch (Exception e) { setState(RETRIEVER_STATE_ERROR); Logging.logger().log(Level.SEVERE, - Logging.getMessage("URLRetriever.ErrorAttemptingToRetrieve", this.url.toString()), e); - } - finally - { + Logging.getMessage("URLRetriever.ErrorAttemptingToRetrieve", this.url.toString()), e); + } finally { end(); } return this; } - private void setState(String state) - { + private void setState(String state) { String oldState = this.state; this.state = state; this.firePropertyChange(AVKey.RETRIEVER_STATE, oldState, this.state); } - private boolean interrupted() - { - if (Thread.currentThread().isInterrupted()) - { + private boolean interrupted() { + if (Thread.currentThread().isInterrupted()) { setState(RETRIEVER_STATE_INTERRUPTED); String message = Logging.getMessage("URLRetriever.RetrievalInterruptedFor", this.url.toString()); Logging.logger().fine(message); @@ -249,43 +214,35 @@ private boolean interrupted() return false; } - private void end() throws Exception - { - try - { - if (this.postProcessor != null) - { + private void end() throws Exception { + try { + if (this.postProcessor != null) { this.byteBuffer = this.postProcessor.run(this); } - } - catch (Exception e) - { + } catch (Exception e) { setState(RETRIEVER_STATE_ERROR); Logging.logger().log(Level.SEVERE, - Logging.getMessage("Retriever.ErrorPostProcessing", this.url.toString()), e); + Logging.getMessage("Retriever.ErrorPostProcessing", this.url.toString()), e); throw e; } } - private ByteBuffer read() throws Exception - { + private ByteBuffer read() throws Exception { ByteBuffer buffer = this.doRead(this.service, this.url); - if (buffer == null) + if (buffer == null) { this.contentLength = 0; + } return buffer; } - protected ByteBuffer doRead(RPFGenerator.RPFServiceInstance service, URL url) throws Exception - { + protected ByteBuffer doRead(RPFGenerator.RPFServiceInstance service, URL url) throws Exception { ByteBuffer buffer = null; BufferedImage bufferedImage = service.serviceRequest(url); - if (bufferedImage != null) - { + if (bufferedImage != null) { // TODO: format parameter should determine image type buffer = DDSCompressor.compressImage(bufferedImage); - if (buffer != null) - { + if (buffer != null) { int length = buffer.limit(); this.contentType = "image/dds"; this.contentLength = length; @@ -300,12 +257,13 @@ protected ByteBuffer doRead(RPFGenerator.RPFServiceInstance service, URL url) th } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final RPFRetriever that = (RPFRetriever) o; @@ -315,16 +273,14 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result; result = (url != null ? url.hashCode() : 0); return result; } @Override - public String toString() - { + public String toString() { return this.getName() != null ? this.getName() : super.toString(); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/layers/rpf/RPFTiledImageLayer.java b/src/gov/nasa/worldwind/layers/rpf/RPFTiledImageLayer.java index 93f8aba545..b39886c84f 100644 --- a/src/gov/nasa/worldwind/layers/rpf/RPFTiledImageLayer.java +++ b/src/gov/nasa/worldwind/layers/rpf/RPFTiledImageLayer.java @@ -25,8 +25,8 @@ * @author dcollins * @version $Id: RPFTiledImageLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFTiledImageLayer extends TiledImageLayer -{ +public class RPFTiledImageLayer extends TiledImageLayer { + private AVList creationParams; private final RPFGenerator rpfGenerator; private final Object fileLock = new Object(); @@ -34,10 +34,8 @@ public class RPFTiledImageLayer extends TiledImageLayer public static final String RPF_ROOT_PATH = "rpf.RootPath"; public static final String RPF_DATA_SERIES_ID = "rpf.DataSeriesId"; - static Collection createTopLevelTiles(AVList params) - { - if (params == null) - { + static Collection createTopLevelTiles(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.LayerConfigParams"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -64,14 +62,12 @@ static Collection createTopLevelTiles(AVList params) ArrayList topLevels = new ArrayList(nLatTiles * nLonTiles); Angle p1 = Tile.computeRowLatitude(firstRow, dLat, latOrigin); - for (int row = firstRow; row <= lastRow; row++) - { + for (int row = firstRow; row <= lastRow; row++) { Angle p2; p2 = p1.add(dLat); Angle t1 = Tile.computeColumnLongitude(firstCol, dLon, lonOrigin); - for (int col = firstCol; col <= lastCol; col++) - { + for (int col = firstCol; col <= lastCol; col++) { Angle t2; t2 = t1.add(dLon); @@ -84,23 +80,19 @@ static Collection createTopLevelTiles(AVList params) return topLevels; } - static String getFileIndexCachePath(String rootPath, String dataSeriesId) - { + static String getFileIndexCachePath(String rootPath, String dataSeriesId) { String path = null; - if (rootPath != null && dataSeriesId != null) - { + if (rootPath != null && dataSeriesId != null) { path = WWIO.formPath( - rootPath, - dataSeriesId, - "rpf_file_index.idx"); + rootPath, + dataSeriesId, + "rpf_file_index.idx"); } return path; } - public static RPFTiledImageLayer fromRestorableState(String stateInXml) - { - if (stateInXml == null) - { + public static RPFTiledImageLayer fromRestorableState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -109,17 +101,13 @@ public static RPFTiledImageLayer fromRestorableState(String stateInXml) return new RPFTiledImageLayer(stateInXml); } - public RPFTiledImageLayer(String stateInXml) - { + public RPFTiledImageLayer(String stateInXml) { this(xmlStateToParams(stateInXml)); RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -127,50 +115,54 @@ public RPFTiledImageLayer(String stateInXml) } Boolean b = rs.getStateValueAsBoolean("rpf.LayerEnabled"); - if (b != null) + if (b != null) { this.setEnabled(b); + } Double d = rs.getStateValueAsDouble("rpf.Opacity"); - if (d != null) + if (d != null) { this.setOpacity(d); + } d = rs.getStateValueAsDouble("rpf.MinActiveAltitude"); - if (d != null) + if (d != null) { this.setMinActiveAltitude(d); + } d = rs.getStateValueAsDouble("rpf.MaxActiveAltitude"); - if (d != null) + if (d != null) { this.setMaxActiveAltitude(d); + } String s = rs.getStateValueAsString("rpf.LayerName"); - if (s != null) + if (s != null) { this.setName(s); + } b = rs.getStateValueAsBoolean("rpf.UseMipMaps"); - if (b != null) + if (b != null) { this.setUseMipMaps(b); + } b = rs.getStateValueAsBoolean("rpf.UseTransparentTextures"); - if (b != null) + if (b != null) { this.setUseTransparentTextures(b); + } RestorableSupport.StateObject so = rs.getStateObject("avlist"); - if (so != null) - { + if (so != null) { RestorableSupport.StateObject[] avpairs = rs.getAllStateObjects(so, ""); - if (avpairs != null) - { - for (RestorableSupport.StateObject avp : avpairs) - { - if (avp != null) + if (avpairs != null) { + for (RestorableSupport.StateObject avp : avpairs) { + if (avp != null) { setValue(avp.getName(), avp.getValue()); + } } } } } - public RPFTiledImageLayer(AVList params) - { + public RPFTiledImageLayer(AVList params) { super(new LevelSet(initParams(params))); this.initRPFFileIndex(params); @@ -183,8 +175,7 @@ public RPFTiledImageLayer(AVList params) this.setName(makeTitle(params)); } - protected void initRPFFileIndex(AVList params) - { + protected void initRPFFileIndex(AVList params) { // Load the RPFFileIndex associated with this RPFTiledImageLayer, and update the layer's expiry time according // to the last modified time on the RPFFileIndex. @@ -196,11 +187,9 @@ protected void initRPFFileIndex(AVList params) File file = fileStore.newFile(getFileIndexCachePath(rootPath, dataSeriesId)); RPFFileIndex fileIndex = (RPFFileIndex) params.getValue(RPFGenerator.RPF_FILE_INDEX); - if (fileIndex == null) - { + if (fileIndex == null) { fileIndex = initFileIndex(file); - if (fileIndex == null) - { + if (fileIndex == null) { String message = Logging.getMessage("nullValue.RPFFileIndexIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -214,62 +203,63 @@ protected void initRPFFileIndex(AVList params) // removed), then all previously created layer imagery will be expired (but not necessarily the preprocessed // data). Long expiryTime = new GregorianCalendar(2009, Calendar.FEBRUARY, 25).getTimeInMillis(); - if (file != null && file.lastModified() > expiryTime) - { + if (file != null && file.lastModified() > expiryTime) { expiryTime = file.lastModified(); } this.setExpiryTime(expiryTime); } - private static AVList initParams(AVList params) - { - if (params == null) - { + private static AVList initParams(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.LayerConfigParams"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String rootPath = params.getStringValue(RPF_ROOT_PATH); - if (rootPath == null) - { + if (rootPath == null) { String message = Logging.getMessage("nullValue.RPFRootPath"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String dataSeriesId = params.getStringValue(RPF_DATA_SERIES_ID); - if (dataSeriesId == null) - { + if (dataSeriesId == null) { String message = Logging.getMessage("nullValue.RPFDataSeriesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Use a dummy value for service. - if (params.getValue(AVKey.SERVICE) == null) + if (params.getValue(AVKey.SERVICE) == null) { params.setValue(AVKey.SERVICE, "file://" + RPFGenerator.class.getName() + "?"); + } // Use a dummy value for dataset-name. - if (params.getValue(AVKey.DATASET_NAME) == null) + if (params.getValue(AVKey.DATASET_NAME) == null) { params.setValue(AVKey.DATASET_NAME, dataSeriesId); + } - if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) - { + if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) { Angle delta = Angle.fromDegrees(36); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, new LatLon(delta, delta)); } - if (params.getValue(AVKey.TILE_WIDTH) == null) + if (params.getValue(AVKey.TILE_WIDTH) == null) { params.setValue(AVKey.TILE_WIDTH, 512); - if (params.getValue(AVKey.TILE_HEIGHT) == null) + } + if (params.getValue(AVKey.TILE_HEIGHT) == null) { params.setValue(AVKey.TILE_HEIGHT, 512); - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) + } + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { params.setValue(AVKey.FORMAT_SUFFIX, ".dds"); - if (params.getValue(AVKey.NUM_LEVELS) == null) + } + if (params.getValue(AVKey.NUM_LEVELS) == null) { params.setValue(AVKey.NUM_LEVELS, 14); // approximately 0.5 meters per pixel - if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) + } + if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); + } params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder()); @@ -277,14 +267,13 @@ private static AVList initParams(AVList params) // state XML. In the first case, either the sector parameter or the RPFFileIndex parameter are specified by the // processor. In the latter case, the sector is restored as part of the state xml. Sector sector = (Sector) params.getValue(AVKey.SECTOR); - if (sector == null) - { + if (sector == null) { RPFFileIndex fileIndex = (RPFFileIndex) params.getValue(RPFGenerator.RPF_FILE_INDEX); - if (fileIndex != null && fileIndex.getIndexProperties() != null) + if (fileIndex != null && fileIndex.getIndexProperties() != null) { sector = fileIndex.getIndexProperties().getBoundingSector(); + } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("RPFTiledImageLayer.NoGeographicBoundingBox"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -293,8 +282,7 @@ private static AVList initParams(AVList params) params.setValue(AVKey.SECTOR, sector); } - if (params.getValue(AVKey.DATA_CACHE_NAME) == null) - { + if (params.getValue(AVKey.DATA_CACHE_NAME) == null) { String cacheName = WWIO.formPath(rootPath, dataSeriesId); params.setValue(AVKey.DATA_CACHE_NAME, cacheName); } @@ -302,31 +290,23 @@ private static AVList initParams(AVList params) return params; } - private static RPFFileIndex initFileIndex(File file) - { + private static RPFFileIndex initFileIndex(File file) { ByteBuffer buffer; - try - { + try { buffer = WWIO.mapFile(file); - } - catch (Exception e) - { + } catch (Exception e) { String message = "Exception while attempting to map file: " + file; Logging.logger().log(java.util.logging.Level.SEVERE, message, e); buffer = null; } RPFFileIndex fileIndex = null; - try - { - if (buffer != null) - { + try { + if (buffer != null) { fileIndex = new RPFFileIndex(); fileIndex.load(buffer); } - } - catch (Exception e) - { + } catch (Exception e) { String message = "Exception while attempting to load RPFFileIndex: " + file; Logging.logger().log(java.util.logging.Level.SEVERE, message, e); fileIndex = null; @@ -335,29 +315,25 @@ private static RPFFileIndex initFileIndex(File file) return fileIndex; } - private static String makeTitle(AVList params) - { + private static String makeTitle(AVList params) { StringBuilder sb = new StringBuilder(); Object o = params.getValue(RPFGenerator.RPF_FILE_INDEX); - if (o != null && o instanceof RPFFileIndex) - { + if (o != null && o instanceof RPFFileIndex) { RPFFileIndex fileIndex = (RPFFileIndex) o; - if (fileIndex.getIndexProperties() != null) - { - if (fileIndex.getIndexProperties().getDescription() != null) + if (fileIndex.getIndexProperties() != null) { + if (fileIndex.getIndexProperties().getDescription() != null) { sb.append(fileIndex.getIndexProperties().getDescription()); - else + } else { sb.append(fileIndex.getIndexProperties().getDataSeriesIdentifier()); + } } } - if (sb.length() == 0) - { + if (sb.length() == 0) { String rootPath = params.getStringValue(RPF_ROOT_PATH); String dataSeriesId = params.getStringValue(RPF_DATA_SERIES_ID); - if (rootPath != null && dataSeriesId != null) - { + if (rootPath != null && dataSeriesId != null) { sb.append(rootPath).append(":").append(dataSeriesId); } } @@ -365,44 +341,33 @@ private static String makeTitle(AVList params) return sb.toString(); } - protected void checkResources() - { + protected void checkResources() { // Intentionally left blank. } - private RestorableSupport makeRestorableState(AVList params) - { + private RestorableSupport makeRestorableState(AVList params) { RestorableSupport rs = RestorableSupport.newRestorableSupport(); // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (rs == null) + if (rs == null) { return null; + } - for (Map.Entry p : params.getEntries()) - { - if (p.getValue() instanceof LatLon) - { + for (Map.Entry p : params.getEntries()) { + if (p.getValue() instanceof LatLon) { rs.addStateValueAsDouble(p.getKey() + ".Latitude", ((LatLon) p.getValue()).getLatitude().degrees); rs.addStateValueAsDouble(p.getKey() + ".Longitude", ((LatLon) p.getValue()).getLongitude().degrees); - } - else if (p.getValue() instanceof Sector) - { + } else if (p.getValue() instanceof Sector) { rs.addStateValueAsDouble(p.getKey() + ".MinLatitude", ((Sector) p.getValue()).getMinLatitude().degrees); rs.addStateValueAsDouble(p.getKey() + ".MaxLatitude", ((Sector) p.getValue()).getMaxLatitude().degrees); rs.addStateValueAsDouble(p.getKey() + ".MinLongitude", - ((Sector) p.getValue()).getMinLongitude().degrees); + ((Sector) p.getValue()).getMinLongitude().degrees); rs.addStateValueAsDouble(p.getKey() + ".MaxLongitude", - ((Sector) p.getValue()).getMaxLongitude().degrees); - } - else if (p.getValue() instanceof URLBuilder) - { + ((Sector) p.getValue()).getMaxLongitude().degrees); + } else if (p.getValue() instanceof URLBuilder) { // Intentionally left blank. URLBuilder will be created from scratch in fromRestorableState(). - } - else if (p.getKey().equals(RPFGenerator.RPF_FILE_INDEX)) - { + } else if (p.getKey().equals(RPFGenerator.RPF_FILE_INDEX)) { // Intentionally left blank. - } - else - { + } else { super.getRestorableStateForAVPair(p.getKey(), p.getValue(), rs, null); } } @@ -416,10 +381,10 @@ else if (p.getKey().equals(RPFGenerator.RPF_FILE_INDEX)) rs.addStateValueAsBoolean("rpf.UseTransparentTextures", this.isUseTransparentTextures()); RestorableSupport.StateObject so = rs.addStateObject("avlist"); - for (Map.Entry p : this.getEntries()) - { - if (p.getKey().equals(AVKey.CONSTRUCTION_PARAMETERS)) + for (Map.Entry p : this.getEntries()) { + if (p.getKey().equals(AVKey.CONSTRUCTION_PARAMETERS)) { continue; + } super.getRestorableStateForAVPair(p.getKey(), p.getValue(), rs, so); } @@ -427,27 +392,21 @@ else if (p.getKey().equals(RPFGenerator.RPF_FILE_INDEX)) return rs; } - public String getRestorableState() - { + public String getRestorableState() { return this.makeRestorableState(this.creationParams).getStateAsXml(); } - public static AVList xmlStateToParams(String stateInXml) - { - if (stateInXml == null) - { + public static AVList xmlStateToParams(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -457,104 +416,117 @@ public static AVList xmlStateToParams(String stateInXml) AVList params = new AVListImpl(); String s = rs.getStateValueAsString(RPF_ROOT_PATH); - if (s != null) + if (s != null) { params.setValue(RPF_ROOT_PATH, s); + } s = rs.getStateValueAsString(RPF_DATA_SERIES_ID); - if (s != null) + if (s != null) { params.setValue(RPF_DATA_SERIES_ID, s); + } s = rs.getStateValueAsString(AVKey.IMAGE_FORMAT); - if (s != null) + if (s != null) { params.setValue(AVKey.IMAGE_FORMAT, s); + } s = rs.getStateValueAsString(AVKey.DATA_CACHE_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DATA_CACHE_NAME, s); + } s = rs.getStateValueAsString(AVKey.SERVICE); - if (s != null) + if (s != null) { params.setValue(AVKey.SERVICE, s); + } s = rs.getStateValueAsString(AVKey.TITLE); - if (s != null) + if (s != null) { params.setValue(AVKey.TITLE, s); + } s = rs.getStateValueAsString(AVKey.DISPLAY_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DISPLAY_NAME, s); + } RestorableSupport.adjustTitleAndDisplayName(params); s = rs.getStateValueAsString(AVKey.DATASET_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DATASET_NAME, s); + } s = rs.getStateValueAsString(AVKey.FORMAT_SUFFIX); - if (s != null) + if (s != null) { params.setValue(AVKey.FORMAT_SUFFIX, s); + } s = rs.getStateValueAsString(AVKey.LAYER_NAMES); - if (s != null) + if (s != null) { params.setValue(AVKey.LAYER_NAMES, s); + } s = rs.getStateValueAsString(AVKey.STYLE_NAMES); - if (s != null) + if (s != null) { params.setValue(AVKey.STYLE_NAMES, s); + } Integer i = rs.getStateValueAsInteger(AVKey.NUM_EMPTY_LEVELS); - if (i != null) + if (i != null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, i); + } i = rs.getStateValueAsInteger(AVKey.NUM_LEVELS); - if (i != null) + if (i != null) { params.setValue(AVKey.NUM_LEVELS, i); + } i = rs.getStateValueAsInteger(AVKey.TILE_WIDTH); - if (i != null) + if (i != null) { params.setValue(AVKey.TILE_WIDTH, i); + } i = rs.getStateValueAsInteger(AVKey.TILE_HEIGHT); - if (i != null) + if (i != null) { params.setValue(AVKey.TILE_HEIGHT, i); + } Double lat = rs.getStateValueAsDouble(AVKey.LEVEL_ZERO_TILE_DELTA + ".Latitude"); Double lon = rs.getStateValueAsDouble(AVKey.LEVEL_ZERO_TILE_DELTA + ".Longitude"); - if (lat != null && lon != null) + if (lat != null && lon != null) { params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, LatLon.fromDegrees(lat, lon)); + } Double minLat = rs.getStateValueAsDouble(AVKey.SECTOR + ".MinLatitude"); Double minLon = rs.getStateValueAsDouble(AVKey.SECTOR + ".MinLongitude"); Double maxLat = rs.getStateValueAsDouble(AVKey.SECTOR + ".MaxLatitude"); Double maxLon = rs.getStateValueAsDouble(AVKey.SECTOR + ".MaxLongitude"); - if (minLat != null && minLon != null && maxLat != null && maxLon != null) + if (minLat != null && minLon != null && maxLat != null && maxLon != null) { params.setValue(AVKey.SECTOR, Sector.fromDegrees(minLat, maxLat, minLon, maxLon)); + } params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder()); return params; } - public void restoreState(String stateInXml) - { + public void restoreState(String stateInXml) { String message = Logging.getMessage("RestorableSupport.RestoreRequiresConstructor"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } - private static class URLBuilder implements TileUrlBuilder - { + private static class URLBuilder implements TileUrlBuilder { + public String URLTemplate = null; - private URLBuilder() - { + private URLBuilder() { } - public java.net.URL getURL(Tile tile, String imageFormat) throws java.net.MalformedURLException - { + public java.net.URL getURL(Tile tile, String imageFormat) throws java.net.MalformedURLException { StringBuffer sb; - if (this.URLTemplate == null) - { + if (this.URLTemplate == null) { sb = new StringBuffer(tile.getLevel().getService()); sb.append("dataset="); sb.append(tile.getLevel().getDataset()); @@ -564,9 +536,7 @@ public java.net.URL getURL(Tile tile, String imageFormat) throws java.net.Malfor sb.append(tile.getLevel().getTileHeight()); this.URLTemplate = sb.toString(); - } - else - { + } else { sb = new StringBuffer(this.URLTemplate); } @@ -585,54 +555,45 @@ public java.net.URL getURL(Tile tile, String imageFormat) throws java.net.Malfor } } - protected void forceTextureLoad(TextureTile tile) - { + protected void forceTextureLoad(TextureTile tile) { final java.net.URL textureURL = WorldWind.getDataFileStore().findFile(tile.getPath(), true); - if (textureURL != null) - { + if (textureURL != null) { this.loadTexture(tile, textureURL); } } - protected void requestTexture(DrawContext dc, TextureTile tile) - { + protected void requestTexture(DrawContext dc, TextureTile tile) { Vec4 centroid = tile.getCentroidPoint(dc.getGlobe()); Vec4 referencePoint = this.getReferencePoint(dc); - if (referencePoint != null) + if (referencePoint != null) { tile.setPriority(centroid.distanceTo3(referencePoint)); + } RequestTask task = new RequestTask(tile, this); this.getRequestQ().add(task); } - private static class RequestTask extends TileTask - { + private static class RequestTask extends TileTask { + private final RPFTiledImageLayer layer; - private RequestTask(TextureTile tile, RPFTiledImageLayer layer) - { + private RequestTask(TextureTile tile, RPFTiledImageLayer layer) { super(tile); this.layer = layer; } - public void run() - { + public void run() { final TextureTile tile = getTile(); // TODO: check to ensure load is still needed - final java.net.URL textureURL = WorldWind.getDataFileStore().findFile(tile.getPath(), false); - if (textureURL != null) - { - if (this.layer.loadTexture(tile, textureURL)) - { + if (textureURL != null) { + if (this.layer.loadTexture(tile, textureURL)) { layer.getLevels().unmarkResourceAbsent(tile); this.layer.firePropertyChange(AVKey.LAYER, null, this); return; - } - else - { + } else { // Assume that something's wrong with the file and delete it. gov.nasa.worldwind.WorldWind.getDataFileStore().removeFile(textureURL); layer.getLevels().markResourceAbsent(tile); @@ -645,10 +606,8 @@ public void run() } } - private boolean loadTexture(TextureTile tile, java.net.URL textureURL) - { - if (WWIO.isFileOutOfDate(textureURL, tile.getLevel().getExpiryTime())) - { + private boolean loadTexture(TextureTile tile, java.net.URL textureURL) { + if (WWIO.isFileOutOfDate(textureURL, tile.getLevel().getExpiryTime())) { // The file has expired. Delete it then request download of newer. gov.nasa.worldwind.WorldWind.getDataFileStore().removeFile(textureURL); String message = Logging.getMessage("generic.DataFileExpired", textureURL); @@ -658,109 +617,94 @@ private boolean loadTexture(TextureTile tile, java.net.URL textureURL) TextureData textureData; - synchronized (this.fileLock) - { + synchronized (this.fileLock) { textureData = readTexture(textureURL, this.isUseMipMaps()); } - if (textureData == null) + if (textureData == null) { return false; + } tile.setTextureData(textureData); - if (tile.getLevelNumber() != 0 || !this.isRetainLevelZeroTiles()) + if (tile.getLevelNumber() != 0 || !this.isRetainLevelZeroTiles()) { this.addTileToCache(tile); + } return true; } - private static TextureData readTexture(java.net.URL url, boolean useMipMaps) - { - try - { + private static TextureData readTexture(java.net.URL url, boolean useMipMaps) { + try { return OGLUtil.newTextureData(Configuration.getMaxCompatibleGLProfile(), url, useMipMaps); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("layers.TextureLayer.ExceptionAttemptingToReadTextureFile", url.toString()); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); return null; } } - private void addTileToCache(TextureTile tile) - { + private void addTileToCache(TextureTile tile) { TextureTile.getMemoryCache().add(tile.getTileKey(), tile); } - protected void downloadTexture(final TextureTile tile) - { + protected void downloadTexture(final TextureTile tile) { RPFGenerator.RPFServiceInstance service = this.rpfGenerator.getServiceInstance(); - if (service == null) + if (service == null) { return; + } java.net.URL url; - try - { + try { url = tile.getResourceURL(); - } - catch (java.net.MalformedURLException e) - { + } catch (java.net.MalformedURLException e) { Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("layers.TextureLayer.ExceptionCreatingTextureUrl", tile), e); + Logging.getMessage("layers.TextureLayer.ExceptionCreatingTextureUrl", tile), e); return; } - if (WorldWind.getRetrievalService().isAvailable()) - { + if (WorldWind.getRetrievalService().isAvailable()) { Retriever retriever = new RPFRetriever(service, url, new DownloadPostProcessor(tile, this)); // Apply any overridden timeouts. Integer srl = AVListImpl.getIntegerValue(this, AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT); - if (srl != null && srl > 0) + if (srl != null && srl > 0) { retriever.setStaleRequestLimit(srl); + } WorldWind.getRetrievalService().runRetriever(retriever, tile.getPriority()); - } - else - { + } else { DownloadTask task = new DownloadTask(service, url, tile, this); this.getRequestQ().add(task); } } - private static class DownloadPostProcessor extends AbstractRetrievalPostProcessor - { + private static class DownloadPostProcessor extends AbstractRetrievalPostProcessor { + private final TextureTile tile; private final RPFTiledImageLayer layer; - public DownloadPostProcessor(TextureTile tile, RPFTiledImageLayer layer) - { + public DownloadPostProcessor(TextureTile tile, RPFTiledImageLayer layer) { this.tile = tile; this.layer = layer; } @Override - protected void markResourceAbsent() - { + protected void markResourceAbsent() { this.layer.getLevels().markResourceAbsent(this.tile); } @Override - protected Object getFileLock() - { + protected Object getFileLock() { return this.layer.fileLock; } - protected File doGetOutputFile() - { + protected File doGetOutputFile() { return WorldWind.getDataFileStore().newFile(this.tile.getPath()); } @Override - protected ByteBuffer handleSuccessfulRetrieval() - { + protected ByteBuffer handleSuccessfulRetrieval() { ByteBuffer buffer = super.handleSuccessfulRetrieval(); - if (buffer != null) - { + if (buffer != null) { // Fire a property change to denote that the layer's backing data has changed. this.layer.firePropertyChange(AVKey.LAYER, null, this); } @@ -769,99 +713,85 @@ protected ByteBuffer handleSuccessfulRetrieval() } @Override - protected boolean validateResponseCode() - { - if (this.getRetriever() instanceof RPFRetriever) + protected boolean validateResponseCode() { + if (this.getRetriever() instanceof RPFRetriever) { return ((RPFRetriever) this.getRetriever()).getResponseCode() == RPFRetriever.RESPONSE_CODE_OK; - else + } else { return super.validateResponseCode(); + } } @Override - protected ByteBuffer handleTextContent() throws IOException - { + protected ByteBuffer handleTextContent() throws IOException { this.markResourceAbsent(); return super.handleTextContent(); } } - private static class DownloadTask extends TileTask - { + private static class DownloadTask extends TileTask { + private final RPFGenerator.RPFServiceInstance service; private final java.net.URL url; private final RPFTiledImageLayer layer; private DownloadTask(RPFGenerator.RPFServiceInstance service, java.net.URL url, TextureTile tile, - RPFTiledImageLayer layer) - { + RPFTiledImageLayer layer) { super(tile); this.service = service; this.url = url; this.layer = layer; } - public void run() - { + public void run() { final TextureTile tile = getTile(); - try - { + try { ByteBuffer buffer = createImage(this.service, this.url); - if (buffer != null) - { + if (buffer != null) { final File outFile = WorldWind.getDataFileStore().newFile(tile.getPath()); - if (outFile != null) - { + if (outFile != null) { this.layer.saveBuffer(buffer, outFile); } } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log( - java.util.logging.Level.SEVERE, "layers.TextureLayer.ExceptionAttemptingToCreateTileImage", e); + java.util.logging.Level.SEVERE, "layers.TextureLayer.ExceptionAttemptingToCreateTileImage", e); this.layer.getLevels().markResourceAbsent(tile); } } } private static ByteBuffer createImage(RPFGenerator.RPFServiceInstance service, java.net.URL url) - throws java.io.IOException - { + throws java.io.IOException { ByteBuffer buffer = null; BufferedImage bufferedImage = service.serviceRequest(url); - if (bufferedImage != null) - { + if (bufferedImage != null) { buffer = DDSCompressor.compressImage(bufferedImage); } return buffer; } - private void saveBuffer(ByteBuffer buffer, File outFile) throws java.io.IOException - { + private void saveBuffer(ByteBuffer buffer, File outFile) throws java.io.IOException { synchronized (this.fileLock) // sychronized with read of file in RequestTask.run() { WWIO.saveBuffer(buffer, outFile); } } - private static class TileTask implements Runnable, Comparable - { + private static class TileTask implements Runnable, Comparable { + private final TextureTile tile; - private TileTask(TextureTile tile) - { + private TileTask(TextureTile tile) { this.tile = tile; } - public final TextureTile getTile() - { + public final TextureTile getTile() { return this.tile; } - public void run() - { + public void run() { } /** @@ -871,24 +801,23 @@ public void run() * * @throws IllegalArgumentException if that is null */ - public int compareTo(TileTask that) - { - if (that == null) - { + public int compareTo(TileTask that) { + if (that == null) { String msg = Logging.getMessage("nullValue.RequestTaskIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - return this.tile.getPriority() == that.tile.getPriority() ? 0 : - this.tile.getPriority() < that.tile.getPriority() ? -1 : 1; + return this.tile.getPriority() == that.tile.getPriority() ? 0 + : this.tile.getPriority() < that.tile.getPriority() ? -1 : 1; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final TileTask that = (TileTask) o; @@ -896,14 +825,12 @@ public boolean equals(Object o) return !(tile != null ? !tile.equals(that.tile) : that.tile != null); } - public int hashCode() - { + public int hashCode() { return (tile != null ? tile.hashCode() : 0); } - public String toString() - { + public String toString() { return this.tile.getPath(); } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/layers/rpf/RPFTiledImageProcessor.java b/src/gov/nasa/worldwind/layers/rpf/RPFTiledImageProcessor.java index fbcaf437a5..838b967f50 100644 --- a/src/gov/nasa/worldwind/layers/rpf/RPFTiledImageProcessor.java +++ b/src/gov/nasa/worldwind/layers/rpf/RPFTiledImageProcessor.java @@ -28,8 +28,8 @@ * @author dcollins * @version $Id: RPFTiledImageProcessor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFTiledImageProcessor -{ +public class RPFTiledImageProcessor { + private int numThreads = -1; private final PropertyChangeSupport propertyChangeSupport; private final Object fileLock = new Object(); @@ -43,54 +43,45 @@ public class RPFTiledImageProcessor public static final String SUB_TASK_STEP_COMPLETE = "SubTaskStepComplete"; public static final String SUB_TASK_STEP_FAILED = "SubTaskStepFailed"; - public RPFTiledImageProcessor() - { + public RPFTiledImageProcessor() { this.propertyChangeSupport = new PropertyChangeSupport(this); } - public int getThreadPoolSize() - { + public int getThreadPoolSize() { return this.numThreads; } - public void setThreadPoolSize(int size) - { + public void setThreadPoolSize(int size) { this.numThreads = size; } public RPFFileIndex makeFileIndex(File rootFile, String dataSeriesId, String description, - Iterable fileIterable) - { - if (rootFile == null) - { + Iterable fileIterable) { + if (rootFile == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dataSeriesId == null) - { + if (dataSeriesId == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (fileIterable == null) - { + if (fileIterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RPFFileIndex result = null; - if (!this.doStop) - { + if (!this.doStop) { RPFFileIndex fileIndex = new RPFFileIndex(); fileIndex.getIndexProperties().setRootPath(rootFile.getAbsolutePath()); fileIndex.getIndexProperties().setDataSeriesIdentifier(dataSeriesId); fileIndex.getIndexProperties().setDescription(description); // Populate the index with the list of RPF files. - for (File file : fileIterable) - { + for (File file : fileIterable) { fileIndex.createRPFFileRecord(file); } @@ -102,32 +93,27 @@ public RPFFileIndex makeFileIndex(File rootFile, String dataSeriesId, String des // Update the RPF bounding sector. fileIndex.updateBoundingSector(); - if (!this.doStop) - { + if (!this.doStop) { result = fileIndex; } } return result; } - public Layer makeLayer(RPFFileIndex fileIndex) - { - if (fileIndex == null) - { + public Layer makeLayer(RPFFileIndex fileIndex) { + if (fileIndex == null) { String message = "RPFFileIndex is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (fileIndex.getIndexProperties() == null) - { + if (fileIndex.getIndexProperties() == null) { String message = "RPFFileIndex.IndexProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } Layer result = null; - if (!this.doStop) - { + if (!this.doStop) { String rootPath = fileIndex.getIndexProperties().getRootPath(); String dataSeriesId = fileIndex.getIndexProperties().getDataSeriesIdentifier(); @@ -145,27 +131,22 @@ public Layer makeLayer(RPFFileIndex fileIndex) createTiledImagery(tileList, generator); // Return the layer. - if (!this.doStop) - { + if (!this.doStop) { result = new RPFTiledImageLayer(params); } } return result; } - public void stop() - { + public void stop() { this.doStop = true; } - private String makeWaveletCachePath(RPFFileIndex fileIndex, long rpfFileKey) - { + private String makeWaveletCachePath(RPFFileIndex fileIndex, long rpfFileKey) { String path = null; - if (fileIndex != null && fileIndex.getIndexProperties() != null && rpfFileKey != -1) - { + if (fileIndex != null && fileIndex.getIndexProperties() != null && rpfFileKey != -1) { File rpfFile = fileIndex.getRPFFile(rpfFileKey); - if (rpfFile != null) - { + if (rpfFile != null) { String rpfFilePath = rpfFile.getPath(); String rootPath = fileIndex.getIndexProperties().getRootPath(); int index = rpfFilePath.lastIndexOf(rootPath); @@ -173,9 +154,9 @@ private String makeWaveletCachePath(RPFFileIndex fileIndex, long rpfFileKey) StringBuilder sb = new StringBuilder(); sb.append(WWIO.formPath( - fileIndex.getIndexProperties().getRootPath(), - fileIndex.getIndexProperties().getDataSeriesIdentifier(), - "wavelet")); + fileIndex.getIndexProperties().getRootPath(), + fileIndex.getIndexProperties().getDataSeriesIdentifier(), + "wavelet")); sb.append(File.separator); sb.append(partialPath); sb.append(WaveletCodec.WVT_EXT); @@ -185,18 +166,15 @@ private String makeWaveletCachePath(RPFFileIndex fileIndex, long rpfFileKey) return path; } - private void processFileIndex(final RPFFileIndex fileIndex, final int waveletWidth, final int waveletHeight) - { + private void processFileIndex(final RPFFileIndex fileIndex, final int waveletWidth, final int waveletHeight) { RPFFileIndex.Table table = fileIndex.getRPFFileTable(); Collection recordList = table.getRecords(); - if (recordList != null) - { + if (recordList != null) { firePropertyChange(BEGIN_SUB_TASK, null, null); firePropertyChange(SUB_TASK_NUM_STEPS, null, recordList.size()); Collection tasks = new ArrayList(); - for (final RPFFileIndex.Record record : recordList) - { + for (final RPFFileIndex.Record record : recordList) { tasks.add(new Runnable() { public void run() { File file = fileIndex.getRPFFile(record.getKey()); @@ -212,26 +190,24 @@ public void run() { }); } - if (this.numThreads > 1) + if (this.numThreads > 1) { runAsynchronously(tasks, this.numThreads, true); - else + } else { run(tasks); + } firePropertyChange(END_SUB_TASK, null, null); } } private void processRecord(RPFFileIndex fileIndex, RPFFileIndex.Record record, - int waveletWidth, int waveletHeight) throws IOException - { - if (fileIndex == null) - { + int waveletWidth, int waveletHeight) throws IOException { + if (fileIndex == null) { String message = "RPFFileIndex is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (record == null) - { + if (record == null) { String message = "RPFFileIndex.Record is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -239,44 +215,37 @@ private void processRecord(RPFFileIndex fileIndex, RPFFileIndex.Record record, File file = null; RPFImageFile rpfImageFile = null; - if (!this.doStop) - { + if (!this.doStop) { // Load the RPF image file. file = fileIndex.getRPFFile(record.getKey()); rpfImageFile = RPFImageFile.load(file); // Create an attribute for the file's sector. Sector sector = getFileSector(rpfImageFile); - if (sector != null) - { + if (sector != null) { ((RPFFileIndex.RPFFileRecord) record).setSector(sector); } } File waveletFile = null; - if (!this.doStop) - { + if (!this.doStop) { // Create the wavelet file path. - synchronized (this.fileLock) - { + synchronized (this.fileLock) { String cachePath = makeWaveletCachePath(fileIndex, record.getKey()); waveletFile = WorldWind.getDataFileStore().newFile(cachePath); } // Create a record for the wavelet file. - if (waveletFile != null) - { + if (waveletFile != null) { fileIndex.createWaveletRecord(waveletFile, record.getKey()); } } WaveletCodec wavelet = null; - if (!this.doStop) - { + if (!this.doStop) { // If the wavelet file is not null, and the source RPF file is newer than the wavelet file, // then create a new wavelet file. - if (waveletFile != null && (file != null && file.lastModified() > waveletFile.lastModified())) - { + if (waveletFile != null && (file != null && file.lastModified() > waveletFile.lastModified())) { // Get the RPF image file as a BufferedImage. BufferedImage bi = rpfImageFile.getBufferedImage(); @@ -285,8 +254,7 @@ private void processRecord(RPFFileIndex fileIndex, RPFFileIndex.Record record, // Get coverage information from the transform. // Create the wavelet from the RPF BufferedImage. - if (bi != null) - { + if (bi != null) { wavelet = createWavelet(bi, waveletWidth, waveletHeight); //noinspection UnusedAssignment bi = null; @@ -296,15 +264,12 @@ private void processRecord(RPFFileIndex fileIndex, RPFFileIndex.Record record, rpfImageFile = null; } - if (!this.doStop) - { + if (!this.doStop) { // If a wavelet has been created, // then write the wavelet to file. - if (wavelet != null) - { + if (wavelet != null) { ByteBuffer buffer = WaveletCodec.save(wavelet); - if (buffer != null) - { + if (buffer != null) { WWIO.saveBuffer(buffer, waveletFile); //noinspection UnusedAssignment buffer = null; @@ -315,24 +280,22 @@ private void processRecord(RPFFileIndex fileIndex, RPFFileIndex.Record record, } } - private WaveletCodec createWavelet(BufferedImage image, int waveletWidth, int waveletHeight) - { + private WaveletCodec createWavelet(BufferedImage image, int waveletWidth, int waveletHeight) { int waveletImgType; - switch (image.getType()) - { - case BufferedImage.TYPE_BYTE_GRAY: - waveletImgType = BufferedImage.TYPE_BYTE_GRAY; - break; - case BufferedImage.TYPE_INT_BGR: - case BufferedImage.TYPE_INT_RGB: - waveletImgType = BufferedImage.TYPE_3BYTE_BGR; - break; - case BufferedImage.TYPE_INT_ARGB: - waveletImgType = BufferedImage.TYPE_4BYTE_ABGR; - break; - default: - waveletImgType = BufferedImage.TYPE_3BYTE_BGR; - break; + switch (image.getType()) { + case BufferedImage.TYPE_BYTE_GRAY: + waveletImgType = BufferedImage.TYPE_BYTE_GRAY; + break; + case BufferedImage.TYPE_INT_BGR: + case BufferedImage.TYPE_INT_RGB: + waveletImgType = BufferedImage.TYPE_3BYTE_BGR; + break; + case BufferedImage.TYPE_INT_ARGB: + waveletImgType = BufferedImage.TYPE_4BYTE_ABGR; + break; + default: + waveletImgType = BufferedImage.TYPE_3BYTE_BGR; + break; } BufferedImage scaledImage = new BufferedImage(waveletWidth, waveletHeight, waveletImgType); @@ -340,45 +303,41 @@ private WaveletCodec createWavelet(BufferedImage image, int waveletWidth, int wa return WaveletCodec.encode(scaledImage); } - private BufferedImage scaleImage(BufferedImage srcImage, BufferedImage destImage) - { + private BufferedImage scaleImage(BufferedImage srcImage, BufferedImage destImage) { double sx = (double) destImage.getWidth() / (double) srcImage.getWidth(); double sy = (double) destImage.getHeight() / (double) srcImage.getHeight(); Graphics2D g2d = (Graphics2D) destImage.getGraphics(); g2d.scale(sx, sy); - g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(srcImage, 0, 0, null); return destImage; } - private Sector getFileSector(RPFFile rpfFile) - { + private Sector getFileSector(RPFFile rpfFile) { // Attempt to get the file's coverage from the RPFFile. Sector sector = null; - if (rpfFile != null) - { + if (rpfFile != null) { // We'll first attempt to compute the Sector, if possible, from the filename (if it exists) by using // the conventions for CADRG and CIB filenames. It has been observed that for polar frame files in // particular that coverage information in the file itself is sometimes unreliable. File file = rpfFile.getFile(); - if (file != null) + if (file != null) { sector = sectorFromFilename(file); + } // Can't compute the Sector; see if the RPFFile contains coverage information. - if (sector == null) + if (sector == null) { sector = sectorFromHeader(rpfFile); + } } return sector; } - private Sector sectorFromHeader(RPFFile rpfFile) - { + private Sector sectorFromHeader(RPFFile rpfFile) { Sector sector = null; - try - { - if (rpfFile != null) - { + try { + if (rpfFile != null) { NITFSImageSegment imageSegment = (NITFSImageSegment) rpfFile.getNITFSSegment(NITFSSegmentType.IMAGE_SEGMENT); RPFFrameFileComponents comps = imageSegment.getUserDefinedImageSubheader().getRPFFrameFileComponents(); Angle minLat = comps.swLowerleft.getLatitude(); @@ -387,19 +346,15 @@ private Sector sectorFromHeader(RPFFile rpfFile) Angle maxLon = comps.neUpperRight.getLongitude(); // This sector spans the longitude boundary. In order to render this sector, // we must adjust the longitudes such that minLon 0) - { + if (Angle.crossesLongitudeBoundary(minLon, maxLon)) { + if (minLon.compareTo(maxLon) > 0) { double degrees = 360 + maxLon.degrees; maxLon = Angle.fromDegrees(degrees); } } sector = new Sector(minLat, maxLat, minLon, maxLon); } - } - catch (Exception e) - { + } catch (Exception e) { // Computing the file's coverage failed. Log the condition and return null. // This at allows the coverage to be re-computed at a later time. String message = String.format("Exception while getting file sector: %s", rpfFile != null ? rpfFile.getFile() : ""); @@ -409,26 +364,21 @@ private Sector sectorFromHeader(RPFFile rpfFile) return sector; } - private Sector sectorFromFilename(File file) - { + private Sector sectorFromFilename(File file) { Sector sector = null; - try - { - if (file != null && file.getName() != null) - { + try { + if (file != null && file.getName() != null) { // Parse the filename, using the conventions for CADRG and CIB filenames. RPFFrameFilename rpfFilename = RPFFrameFilename.parseFilename(file.getName().toUpperCase()); // Get the dataseries associated with that code. RPFDataSeries ds = RPFDataSeries.dataSeriesFor(rpfFilename.getDataSeriesCode()); // Create a transform to compute coverage information. RPFFrameTransform tx = RPFFrameTransform.createFrameTransform( - rpfFilename.getZoneCode(), ds.rpfDataType, ds.scaleOrGSD); + rpfFilename.getZoneCode(), ds.rpfDataType, ds.scaleOrGSD); // Get coverage information from the transform. sector = tx.computeFrameCoverage(rpfFilename.getFrameNumber()); } - } - catch (Exception e) - { + } catch (Exception e) { // Computing the file's coverage failed. Log the condition and return null. // This at allows the coverage to be re-computed at a later time. String message = String.format("Exception while computing file sector: %s", file); @@ -461,16 +411,13 @@ private Sector sectorFromFilename(File file) // } // return isPolar; //} - - private void createTiledImagery(Collection tileList, RPFGenerator generator) - { + private void createTiledImagery(Collection tileList, RPFGenerator generator) { firePropertyChange(BEGIN_SUB_TASK, null, null); firePropertyChange(SUB_TASK_NUM_STEPS, null, tileList.size()); Collection tasks = new ArrayList(); final RPFGenerator.RPFServiceInstance service = generator.getServiceInstance(); - for (final Tile tile : tileList) - { + for (final Tile tile : tileList) { tasks.add(new Runnable() { public void run() { try { @@ -485,143 +432,115 @@ public void run() { }); } - if (this.numThreads > 1) + if (this.numThreads > 1) { runAsynchronously(tasks, this.numThreads, true); - else + } else { run(tasks); + } firePropertyChange(END_SUB_TASK, null, null); } - private void createTileImage(Tile tile, RPFGenerator.RPFServiceInstance service) throws Exception - { - if (tile == null) - { + private void createTileImage(Tile tile, RPFGenerator.RPFServiceInstance service) throws Exception { + if (tile == null) { String message = "Tile is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (service == null) - { + if (service == null) { String message = "RPFGenerator.RPFServiceInstance is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } File outFile = null; - if (!this.doStop) - { - synchronized (this.fileLock) - { + if (!this.doStop) { + synchronized (this.fileLock) { outFile = WorldWind.getDataFileStore().newFile(tile.getPath()); } } BufferedImage image = null; - if (!this.doStop) - { + if (!this.doStop) { URL url = tile.getResourceURL(); - if (url != null) - { + if (url != null) { image = service.serviceRequest(url); } } - if (!this.doStop) - { + if (!this.doStop) { // If an image has been created, // then convert it to DDS and write it to file. - if (image != null) - { + if (image != null) { ByteBuffer buffer = DDSCompressor.compressImage(image); - if (buffer != null && outFile != null) - { + if (buffer != null && outFile != null) { WWIO.saveBuffer(buffer, outFile); } } } } - private void saveFileIndex(RPFFileIndex fileIndex, File file) - { - try - { + private void saveFileIndex(RPFFileIndex fileIndex, File file) { + try { ByteBuffer buffer = null; - if (fileIndex != null) - { + if (fileIndex != null) { buffer = fileIndex.save(); } - if (buffer != null && file != null) - { + if (buffer != null && file != null) { WWIO.saveBuffer(buffer, file); } - } - catch (Exception e) - { + } catch (Exception e) { String message = String.format("Exception while saving RPFFileIndex: %s", file); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - private BufferedImage deproject(File file, BufferedImage image) - { + private BufferedImage deproject(File file, BufferedImage image) { // Need a RPFFrameTransform object and a frame-number to perform the deprojection... RPFFrameFilename fframe = RPFFrameFilename.parseFilename(file.getName().toUpperCase()); RPFDataSeries ds = RPFDataSeries.dataSeriesFor(fframe.getDataSeriesCode()); RPFFrameTransform tx = RPFFrameTransform.createFrameTransform(fframe.getZoneCode(), - ds.rpfDataType, ds.scaleOrGSD); + ds.rpfDataType, ds.scaleOrGSD); RPFFrameTransform.RPFImage[] images = tx.deproject(fframe.getFrameNumber(), image); - if (images.length == 1) + if (images.length == 1) { return images[0].getImage(); + } // NOTE we are using explicit knowledge of the order of the two images produced in the deprojection step... BufferedImage westImage = images[0].getImage(); BufferedImage eastImage = images[1].getImage(); - BufferedImage outImage = new BufferedImage(westImage.getWidth()+eastImage.getWidth(), westImage.getHeight(), - BufferedImage.TYPE_4BYTE_ABGR); + BufferedImage outImage = new BufferedImage(westImage.getWidth() + eastImage.getWidth(), westImage.getHeight(), + BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g2d = (Graphics2D) outImage.getGraphics(); g2d.drawImage(westImage, 0, 0, null); g2d.drawImage(eastImage, westImage.getWidth(), 0, null); return outImage; } - private void run(Iterable taskIterable) - { - try - { - if (taskIterable != null) - { - for (Runnable task : taskIterable) - { - if (!this.doStop) - { + private void run(Iterable taskIterable) { + try { + if (taskIterable != null) { + for (Runnable task : taskIterable) { + if (!this.doStop) { task.run(); } } } - } - catch (Exception e) - { + } catch (Exception e) { String message = "Exception while executing tasks"; Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - private void runAsynchronously(Iterable taskIterable, int threadPoolSize, boolean blockUntilFinished) - { - try - { - if (taskIterable != null) - { + private void runAsynchronously(Iterable taskIterable, int threadPoolSize, boolean blockUntilFinished) { + try { + if (taskIterable != null) { ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize); - for (Runnable task : taskIterable) - { - if (!this.doStop) - { - if (task != null) - { + for (Runnable task : taskIterable) { + if (!this.doStop) { + if (task != null) { executor.submit(task); } } @@ -630,29 +549,24 @@ private void runAsynchronously(Iterable taskIterable, int threadPoolSi // Attempt to block this thread until all Runnables // have completed execution. - while (blockUntilFinished && !executor.awaitTermination(1000L, TimeUnit.MILLISECONDS)) - {} + while (blockUntilFinished && !executor.awaitTermination(1000L, TimeUnit.MILLISECONDS)) { + } } - } - catch (Exception e) - { + } catch (Exception e) { String message = "Exception while executing tasks"; Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - public void addPropertyChangeListener(PropertyChangeListener listener) - { + public void addPropertyChangeListener(PropertyChangeListener listener) { this.propertyChangeSupport.addPropertyChangeListener(listener); } - public void removePropertyChangeListener(PropertyChangeListener listener) - { + public void removePropertyChangeListener(PropertyChangeListener listener) { this.propertyChangeSupport.removePropertyChangeListener(listener); } - private void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { + private void firePropertyChange(String propertyName, Object oldValue, Object newValue) { this.propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } } diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/DataChooserPanel.java b/src/gov/nasa/worldwind/layers/rpf/wizard/DataChooserPanel.java index b7a94302ce..bcb049046a 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/DataChooserPanel.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/DataChooserPanel.java @@ -19,8 +19,8 @@ * @author dcollins * @version $Id: DataChooserPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DataChooserPanel extends JPanel -{ +public class DataChooserPanel extends JPanel { + private JLabel title; private JLabel description; // Logical data components. @@ -34,56 +34,46 @@ public class DataChooserPanel extends JPanel private JScrollPane dataScrollPane; private JLabel dataDescription; - public DataChooserPanel() - { + public DataChooserPanel() { this.propertyEvents = new PropertyEvents(); makeComponents(); layoutComponents(); } - public String getTitle() - { + public String getTitle() { return this.title.getText(); } - public void setTitle(String title) - { + public void setTitle(String title) { this.title.setText(title); } - public String getDescription() - { + public String getDescription() { return this.description.getText(); } - public void setDescription(String description) - { + public void setDescription(String description) { this.description.setText(description); } - public String getDataDescription() - { + public String getDataDescription() { return this.dataDescription.getText(); } - public void setDataDescription(String dataDescription) - { + public void setDataDescription(String dataDescription) { this.dataDescription.setText(dataDescription); } - public void setFileSetList(Collection fileSetList) - { + public void setFileSetList(Collection fileSetList) { removeListeners(this.fileSetList); this.fileSetList = fileSetList; addListeners(this.fileSetList); this.selectButtons = new HashMap(); - if (fileSetList != null && fileSetList.size() > 0) - { + if (fileSetList != null && fileSetList.size() > 0) { Box box = Box.createVerticalBox(); - for (FileSet set : fileSetList) - { + for (FileSet set : fileSetList) { JCheckBox checkBox = new JCheckBox(); checkBox.putClientProperty("fileSet", set); checkBox.setSelected(set.isSelected()); @@ -100,9 +90,7 @@ public void itemStateChanged(ItemEvent e) { } this.dataScrollPane.setViewportView(box); this.dataPanel.setVisible(true); - } - else - { + } else { this.dataScrollPane.setViewportView(null); this.dataPanel.setVisible(false); } @@ -111,25 +99,24 @@ public void itemStateChanged(ItemEvent e) { fileSetSelectionChanged(null); } - private String makeTitle(FileSet set) - { + private String makeTitle(FileSet set) { String title = null; - if (set != null) - { + if (set != null) { StringBuilder sb = new StringBuilder(); sb.append(""); - if (set.getTitle() != null) + if (set.getTitle() != null) { sb.append(set.getTitle()); - else if (set.getIdentifier() != null) + } else if (set.getIdentifier() != null) { sb.append(set.getIdentifier()); - else + } else { sb.append("Various"); + } int fileCount = set.getFileCount(); - if (fileCount > 0) - { + if (fileCount > 0) { sb.append(""); - if (sb.length() > 0) + if (sb.length() > 0) { sb.append(" - "); + } sb.append(String.format("%,d", fileCount)).append(" file").append(fileCount > 1 ? "s" : ""); sb.append(""); } @@ -139,67 +126,57 @@ else if (set.getIdentifier() != null) return title; } - private void fileSetClicked(ItemEvent e) - { - if (e != null) - { + private void fileSetClicked(ItemEvent e) { + if (e != null) { FileSet set = null; - if (e.getItem() != null && e.getItem() instanceof JComponent) - { + if (e.getItem() != null && e.getItem() instanceof JComponent) { Object property = ((JComponent) e.getItem()).getClientProperty("fileSet"); - if (property != null && property instanceof FileSet) + if (property != null && property instanceof FileSet) { set = (FileSet) property; + } } - if (set != null) - { - if (e.getStateChange() == ItemEvent.SELECTED) + if (set != null) { + if (e.getStateChange() == ItemEvent.SELECTED) { set.setSelected(true); - else if (e.getStateChange() == ItemEvent.DESELECTED) + } else if (e.getStateChange() == ItemEvent.DESELECTED) { set.setSelected(false); + } } } } - private void setAllSelected(boolean b) - { - if (this.fileSetList != null) - { - for (FileSet set : this.fileSetList) - { + private void setAllSelected(boolean b) { + if (this.fileSetList != null) { + for (FileSet set : this.fileSetList) { set.setSelected(b); } } } - private void selectAllPressed() - { + private void selectAllPressed() { setAllSelected(true); } - private void deselectAllPressed() - { + private void deselectAllPressed() { setAllSelected(false); } - private void fileSetSelectionChanged(Object source) - { + private void fileSetSelectionChanged(Object source) { // Make sure the CheckBox selection reflects the FileSet selection state. - if (source != null && source instanceof FileSet) - { + if (source != null && source instanceof FileSet) { FileSet set = (FileSet) source; JToggleButton button = this.selectButtons.get(set); - if (button != null) + if (button != null) { button.setSelected(set.isSelected()); + } } // Enable "Select All" and "Select None" only when necessary. boolean allSelected = true; boolean anySelected = false; - if (this.fileSetList != null) - { - for (FileSet set : this.fileSetList) - { + if (this.fileSetList != null) { + for (FileSet set : this.fileSetList) { allSelected &= set.isSelected(); anySelected |= set.isSelected(); } @@ -208,29 +185,24 @@ private void fileSetSelectionChanged(Object source) this.deselectAllButton.setEnabled(anySelected); } - private void addListeners(Collection fileSetList) - { - if (fileSetList != null) - { - for (FileSet set : fileSetList) - { + private void addListeners(Collection fileSetList) { + if (fileSetList != null) { + for (FileSet set : fileSetList) { set.addPropertyChangeListener(this.propertyEvents); } } } - private void removeListeners(Collection fileSetList) - { - if (fileSetList != null) - { - for (FileSet set : fileSetList) - { + private void removeListeners(Collection fileSetList) { + if (fileSetList != null) { + for (FileSet set : fileSetList) { set.removePropertyChangeListener(this.propertyEvents); } } } private class PropertyEvents implements PropertyChangeListener { + public void propertyChange(PropertyChangeEvent evt) { if (evt != null && evt.getPropertyName() != null) { String propertyName = evt.getPropertyName(); @@ -242,8 +214,7 @@ public void propertyChange(PropertyChangeEvent evt) { } } - private void makeComponents() - { + private void makeComponents() { this.title = new JLabel(" "); this.title.setBackground(Color.gray); this.title.setOpaque(true); @@ -279,8 +250,7 @@ public void actionPerformed(ActionEvent e) { this.dataDescription = new JLabel(" "); } - private void layoutComponents() - { + private void layoutComponents() { setLayout(new BorderLayout()); JPanel p = new JPanel(); diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/DataChooserPanelDescriptor.java b/src/gov/nasa/worldwind/layers/rpf/wizard/DataChooserPanelDescriptor.java index 5e5edcff83..abf9e0b74b 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/DataChooserPanelDescriptor.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/DataChooserPanelDescriptor.java @@ -18,14 +18,13 @@ * @author dcollins * @version $Id: DataChooserPanelDescriptor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DataChooserPanelDescriptor extends DefaultPanelDescriptor -{ +public class DataChooserPanelDescriptor extends DefaultPanelDescriptor { + private DataChooserPanel panelComponent; private PropertyEvents propertyEvents; public static final String IDENTIFIER = "gov.nasa.worldwind.rpf.wizard.DataChooserPanel"; - public DataChooserPanelDescriptor() - { + public DataChooserPanelDescriptor() { this.panelComponent = new DataChooserPanel(); this.propertyEvents = new PropertyEvents(); this.panelComponent.addPropertyChangeListener(this.propertyEvents); @@ -33,56 +32,50 @@ public DataChooserPanelDescriptor() setPanelComponent(this.panelComponent); } - public Object getBackPanelDescriptor() - { + public Object getBackPanelDescriptor() { return FileChooserPanelDescriptor.IDENTIFIER; } - public Object getNextPanelDescriptor() - { + public Object getNextPanelDescriptor() { return PreprocessPanelDescriptor.IDENTIFIER; } - public void registerPanel(Wizard wizard) - { + public void registerPanel(Wizard wizard) { WizardModel oldWizardModel = getWizardModel(); - if (oldWizardModel != null) + if (oldWizardModel != null) { oldWizardModel.removePropertyChangeListener(this.propertyEvents); + } super.registerPanel(wizard); WizardModel newWizardModel = getWizardModel(); - if (newWizardModel != null) + if (newWizardModel != null) { newWizardModel.addPropertyChangeListener(this.propertyEvents); + } } - public void aboutToDisplayPanel() - { + public void aboutToDisplayPanel() { setNextButtonAccordingToSelection(); } - private void setNextButtonAccordingToSelection() - { + private void setNextButtonAccordingToSelection() { Wizard wizard = getWizard(); - if (wizard != null) - { + if (wizard != null) { boolean anySelected = false; Collection fileSetList = RPFWizardUtil.getFileSetList(wizard.getModel()); - if (fileSetList != null && fileSetList.size() > 0) - { - for (FileSet set : fileSetList) + if (fileSetList != null && fileSetList.size() > 0) { + for (FileSet set : fileSetList) { anySelected |= set.isSelected(); + } } wizard.setNextButtonEnabled(anySelected); wizard.giveFocusToNextButton(); } } - private void fileSetListChanged() - { + private void fileSetListChanged() { WizardModel model = getWizardModel(); - if (model != null) - { + if (model != null) { Collection fileSetList = RPFWizardUtil.getFileSetList(model); updatePanelTitle(fileSetList); updatePanelData(fileSetList); @@ -90,19 +83,18 @@ private void fileSetListChanged() } } - private void fileSetSelectionChanged() - { + private void fileSetSelectionChanged() { setNextButtonAccordingToSelection(); WizardModel model = getWizardModel(); - if (model != null) - { + if (model != null) { Collection fileSetList = RPFWizardUtil.getFileSetList(model); updatePanelDataDescription(fileSetList); } } private class PropertyEvents implements PropertyChangeListener { + public void propertyChange(PropertyChangeEvent evt) { if (evt != null && evt.getPropertyName() != null) { String propertyName = evt.getPropertyName(); @@ -115,85 +107,71 @@ public void propertyChange(PropertyChangeEvent evt) { } } - private void updatePanelTitle(Collection fileSetList) - { - if (fileSetList != null && fileSetList.size() > 0) - { + private void updatePanelTitle(Collection fileSetList) { + if (fileSetList != null && fileSetList.size() > 0) { this.panelComponent.setTitle(RPFWizardUtil.makeLarger("Select Imagery to Import")); - } - else - { + } else { this.panelComponent.setTitle(RPFWizardUtil.makeLarger("No Imagery Found")); } } - private void updatePanelData(Collection fileSetList) - { + private void updatePanelData(Collection fileSetList) { this.panelComponent.setFileSetList(fileSetList); } - private void updatePanelDataDescription(Collection fileSetList) - { + private void updatePanelDataDescription(Collection fileSetList) { int totalFiles = 0; int selectedFiles = 0; - if (fileSetList != null && fileSetList.size() > 0) - { - for (FileSet set : fileSetList) - { - if (set != null) - { + if (fileSetList != null && fileSetList.size() > 0) { + for (FileSet set : fileSetList) { + if (set != null) { int count = set.getFileCount(); totalFiles += count; - if (set.isSelected()) + if (set.isSelected()) { selectedFiles += count; + } } } } - if (totalFiles > 0) - { + if (totalFiles > 0) { StringBuilder sb = new StringBuilder(); - if (selectedFiles > 0) - { + if (selectedFiles > 0) { long WAVELET_SIZE_EST = 262160; // TODO: compute this value long WAVELET_TIME_EST = 200; // TODO: compute this value long estimatedBytes = selectedFiles * WAVELET_SIZE_EST; long estimatedMillis = selectedFiles * WAVELET_TIME_EST; sb.append("Selected files: "); sb.append(String.format("%,d", selectedFiles)); - if (estimatedBytes > 0) - { + if (estimatedBytes > 0) { SizeFormatter sf = new SizeFormatter(); - if (sb.length() > 0) + if (sb.length() > 0) { sb.append(" - "); + } sb.append("Disk space required: ~"); sb.append(sf.formatEstimate(estimatedBytes)); } - if (estimatedMillis > 0) - { + if (estimatedMillis > 0) { TimeFormatter tf = new TimeFormatter(); - if (sb.length() > 0) + if (sb.length() > 0) { sb.append(" - "); + } sb.append("Processing time: "); sb.append(tf.formatEstimate(estimatedMillis)); } - } - else - { + } else { sb.append("No files selected"); } this.panelComponent.setDataDescription(RPFWizardUtil.makeSmaller(sb.toString())); - } - else - { + } else { StringBuilder sb = new StringBuilder(); sb.append("No Imagery"); WizardModel model = getWizardModel(); - if (model != null) - { + if (model != null) { File selectedFile = RPFWizardUtil.getSelectedFile(model); - if (selectedFile != null) + if (selectedFile != null) { sb.append(" in \'").append(selectedFile.getAbsolutePath()).append(File.separator).append("\'"); + } } this.panelComponent.setDataDescription(RPFWizardUtil.makeBold(sb.toString())); } diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/ETRCalculator.java b/src/gov/nasa/worldwind/layers/rpf/wizard/ETRCalculator.java index ae53aa52d0..52482fb0d7 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/ETRCalculator.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/ETRCalculator.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: ETRCalculator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ETRCalculator -{ +public class ETRCalculator { + private int step = -1; private int numSteps = -1; private int stepsNeededForEstimate = 1; @@ -19,79 +19,64 @@ public class ETRCalculator private long etr = -1; private long nextUpdateTime = -1; - public ETRCalculator() - {} + public ETRCalculator() { + } - public int getStep() - { + public int getStep() { return this.step; } - public void setStep(int step) - { + public void setStep(int step) { this.step = step < 0 ? -1 : step; } - public int getNumSteps() - { + public int getNumSteps() { return this.numSteps; } - public void setNumSteps(int numSteps) - { + public void setNumSteps(int numSteps) { this.numSteps = numSteps < 0 ? -1 : numSteps; } - public double getStepsNeededForEstimate() - { + public double getStepsNeededForEstimate() { return this.stepsNeededForEstimate; } - public void setStepsNeededForEstimate(int stepsNeededForEstimate) - { + public void setStepsNeededForEstimate(int stepsNeededForEstimate) { this.stepsNeededForEstimate = stepsNeededForEstimate < 1 ? 1 : stepsNeededForEstimate; } - public long getStartTime() - { + public long getStartTime() { return this.startTime; } - public void setStartTime(long timeMillis) - { + public void setStartTime(long timeMillis) { this.startTime = timeMillis; this.nextUpdateTime = this.startTime + this.updateFrequency; } - public long getUpdateFrequency() - { + public long getUpdateFrequency() { return this.updateFrequency; } - public void setUpdateFrequency(long updateFrequencyMillis) - { + public void setUpdateFrequency(long updateFrequencyMillis) { this.updateFrequency = updateFrequencyMillis < 0 ? 0 : updateFrequencyMillis; } - public long getEstimatedTimeRemaining() - { + public long getEstimatedTimeRemaining() { if (this.step >= 0 - && this.step >= this.stepsNeededForEstimate - && this.numSteps >= 0 - && this.startTime >= 0) - { + && this.step >= this.stepsNeededForEstimate + && this.numSteps >= 0 + && this.startTime >= 0) { long time = System.currentTimeMillis(); - if (this.nextUpdateTime < time) - { + if (this.nextUpdateTime < time) { this.nextUpdateTime = time + this.updateFrequency; double elapsed = time - this.startTime; double pctComplete = this.step / (double) (this.numSteps - 1); this.etr = (long) (elapsed / pctComplete - elapsed); } - } - else - { + } else { this.etr = -1; } diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/FileChooserPanel.java b/src/gov/nasa/worldwind/layers/rpf/wizard/FileChooserPanel.java index f560ac0ab3..b18d2f750a 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/FileChooserPanel.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/FileChooserPanel.java @@ -20,104 +20,90 @@ * @author dcollins * @version $Id: FileChooserPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FileChooserPanel extends JPanel -{ +public class FileChooserPanel extends JPanel { + private JLabel title; private JLabel description; private JFormattedTextField fileField; private JButton chooseButton; private JFileChooser fileChooser; - - public FileChooserPanel() - { + + public FileChooserPanel() { makeComponents(); layoutComponents(); } - public String getTitle() - { + public String getTitle() { return this.title.getText(); } - public void setTitle(String title) - { + public void setTitle(String title) { this.title.setText(title); } - public String getDescription() - { + public String getDescription() { return this.description.getText(); } - public void setDescription(String description) - { + public void setDescription(String description) { this.description.setText(description); } - public JFileChooser getFileChooser() - { + public JFileChooser getFileChooser() { return this.fileChooser; } - public void setFileChooser(JFileChooser fileChooser) - { - if (fileChooser == null) - { + public void setFileChooser(JFileChooser fileChooser) { + if (fileChooser == null) { String message = "JFileChooser is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - + this.fileChooser = fileChooser; } - public File getSelectedFile() - { + public File getSelectedFile() { return getValueAsFile(this.fileField.getValue()); } - private File getValueAsFile(Object value) - { - if (value != null) - { - if (value instanceof File) + private File getValueAsFile(Object value) { + if (value != null) { + if (value instanceof File) { return (File) value; - else + } else { return new File(value.toString()); + } } return null; } - public void promptForNewSelection() - { + public void promptForNewSelection() { onChooseClicked(); } - private void onChooseClicked() - { + private void onChooseClicked() { int returnCode = this.fileChooser.showDialog(this, "Choose"); - if (returnCode == JFileChooser.APPROVE_OPTION && this.fileChooser.getSelectedFile() != null) - { + if (returnCode == JFileChooser.APPROVE_OPTION && this.fileChooser.getSelectedFile() != null) { this.fileField.setValue(this.fileChooser.getSelectedFile()); } } - private void onFileFieldChanged(Object newValue) - { + private void onFileFieldChanged(Object newValue) { File newFile = getValueAsFile(newValue); firePropertyChange("selectedFile", null, newFile); } - private void makeComponents() - { + private void makeComponents() { this.title = new JLabel(" "); this.title.setBackground(Color.gray); - this.title.setOpaque(true); + this.title.setOpaque(true); this.description = new JLabel(); this.fileField = new JFormattedTextField("Click 'Choose...'"); Font font = this.fileField.getFont(); - if (!font.isBold()) + if (!font.isBold()) { font = new Font(font.getName(), Font.BOLD | font.getStyle(), font.getSize()); + } this.fileField.setFont(font); // Override input-path maximum size to avoid any vertical stretching by the layout manager. Dimension preferred = this.fileField.getPreferredSize(); @@ -142,8 +128,7 @@ public void actionPerformed(ActionEvent e) { this.fileChooser.setMultiSelectionEnabled(false); } - private void layoutComponents() - { + private void layoutComponents() { setLayout(new BorderLayout()); JPanel p = new JPanel(); diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/FileChooserPanelDescriptor.java b/src/gov/nasa/worldwind/layers/rpf/wizard/FileChooserPanelDescriptor.java index 18d790006b..d9cc2b5f69 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/FileChooserPanelDescriptor.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/FileChooserPanelDescriptor.java @@ -17,68 +17,62 @@ * @author dcollins * @version $Id: FileChooserPanelDescriptor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FileChooserPanelDescriptor extends DefaultPanelDescriptor -{ +public class FileChooserPanelDescriptor extends DefaultPanelDescriptor { + private FileChooserPanel panelComponent; public static final String IDENTIFIER = "gov.nasa.worldwind.rpf.wizard.FileChooserPanel"; - public FileChooserPanelDescriptor() - { + public FileChooserPanelDescriptor() { this.panelComponent = new FileChooserPanel(); this.panelComponent.addPropertyChangeListener(new PropertyEvents()); setPanelIdentifier(IDENTIFIER); setPanelComponent(this.panelComponent); } - public Object getBackPanelDescriptor() - { + public Object getBackPanelDescriptor() { return null; } - public Object getNextPanelDescriptor() - { + public Object getNextPanelDescriptor() { Object nextDescriptor; - if (!RPFWizardUtil.isFileListCurrent(getWizardModel())) + if (!RPFWizardUtil.isFileListCurrent(getWizardModel())) { nextDescriptor = FileSearchPanelDescriptor.IDENTIFIER; - else + } else { nextDescriptor = DataChooserPanelDescriptor.IDENTIFIER; + } return nextDescriptor; } - public void aboutToDisplayPanel() - { + public void aboutToDisplayPanel() { this.panelComponent.setTitle(RPFWizardUtil.makeLarger("Choose Folder to Search")); this.panelComponent.setDescription("
        Folder to search..."); setNextButtonAccordingToSelectedFile(); } - private void setNextButtonAccordingToSelectedFile() - { + private void setNextButtonAccordingToSelectedFile() { Wizard wizard = getWizard(); - if (wizard != null) - { + if (wizard != null) { File file = RPFWizardUtil.getSelectedFile(wizard.getModel()); wizard.setNextButtonEnabled(file != null && file.exists()); wizard.giveFocusToNextButton(); } } - private void selectedFileChanged(Object newValue) - { + private void selectedFileChanged(Object newValue) { WizardModel model = getWizardModel(); - if (model != null && newValue != null && newValue instanceof File) - { + if (model != null && newValue != null && newValue instanceof File) { RPFWizardUtil.setSelectedFile(model, (File) newValue); } setNextButtonAccordingToSelectedFile(); } private class PropertyEvents implements PropertyChangeListener { + public void propertyChange(PropertyChangeEvent evt) { if (evt != null && evt.getPropertyName() != null) { String propertyName = evt.getPropertyName(); if (propertyName.equals("selectedFile")) { - selectedFileChanged(evt.getNewValue()); + selectedFileChanged(evt.getNewValue()); } } } diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/FileSearchPanelDescriptor.java b/src/gov/nasa/worldwind/layers/rpf/wizard/FileSearchPanelDescriptor.java index 6b0810a99c..65e279ae8e 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/FileSearchPanelDescriptor.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/FileSearchPanelDescriptor.java @@ -23,15 +23,14 @@ * @author dcollins * @version $Id: FileSearchPanelDescriptor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FileSearchPanelDescriptor extends DefaultPanelDescriptor -{ +public class FileSearchPanelDescriptor extends DefaultPanelDescriptor { + private ProgressPanel panelComponent; private PropertyEvents propertyEvents; private Thread workerThread; public static final String IDENTIFIER = "gov.nasa.worldwind.rpf.wizard.FileSearchPanel"; - public FileSearchPanelDescriptor() - { + public FileSearchPanelDescriptor() { this.panelComponent = new ProgressPanel(); this.propertyEvents = new PropertyEvents(); this.panelComponent.addPropertyChangeListener(this.propertyEvents); @@ -39,41 +38,37 @@ public FileSearchPanelDescriptor() setPanelComponent(this.panelComponent); } - public Object getBackPanelDescriptor() - { + public Object getBackPanelDescriptor() { return FileChooserPanelDescriptor.IDENTIFIER; } - public Object getNextPanelDescriptor() - { + public Object getNextPanelDescriptor() { return DataChooserPanelDescriptor.IDENTIFIER; } - public void registerPanel(Wizard wizard) - { + public void registerPanel(Wizard wizard) { WizardModel oldWizardModel = getWizardModel(); - if (oldWizardModel != null) + if (oldWizardModel != null) { oldWizardModel.removePropertyChangeListener(this.propertyEvents); + } super.registerPanel(wizard); WizardModel newWizardModel = getWizardModel(); - if (newWizardModel != null) + if (newWizardModel != null) { newWizardModel.addPropertyChangeListener(this.propertyEvents); + } } - public void aboutToDisplayPanel() - { + public void aboutToDisplayPanel() { this.panelComponent.setTitle(RPFWizardUtil.makeLarger("Searching for Imagery")); this.panelComponent.setProgressDescription1(" "); this.panelComponent.setProgressDescription2(" "); this.panelComponent.getProgressBar().setIndeterminate(false); WizardModel model = getWizardModel(); - if (model != null) - { + if (model != null) { File selectedFile = RPFWizardUtil.getSelectedFile(model); - if (selectedFile != null) - { + if (selectedFile != null) { StringBuilder sb = new StringBuilder(); sb.append("
        "); sb.append("Searching "); @@ -84,19 +79,18 @@ public void aboutToDisplayPanel() } } - public void displayingPanel() - { + public void displayingPanel() { WizardModel model = getWizardModel(); - if (model != null && !RPFWizardUtil.isFileListCurrent(model)) - { + if (model != null && !RPFWizardUtil.isFileListCurrent(model)) { this.panelComponent.getProgressBar().setIndeterminate(true); startWorkerThread(new Runnable() { public void run() { refreshFileList(); WizardModel model = getWizardModel(); - if (model != null) + if (model != null) { RPFWizardUtil.setFileListCurrent(model, true); + } moveToNextPanel(); } @@ -104,31 +98,27 @@ public void run() { } } - public void aboutToHidePanel() - { + public void aboutToHidePanel() { killWorkerThread(); } - private void moveToNextPanel() - { + private void moveToNextPanel() { Wizard wizard = getWizard(); Object nextPanel = getNextPanelDescriptor(); - if (wizard != null && nextPanel != null) - { + if (wizard != null && nextPanel != null) { wizard.setCurrentPanelDescriptor(nextPanel); } } - private void selectedFileChanged() - { + private void selectedFileChanged() { WizardModel model = getWizardModel(); - if (model != null) - { + if (model != null) { RPFWizardUtil.setFileListCurrent(model, false); } } private class PropertyEvents implements PropertyChangeListener { + public void propertyChange(PropertyChangeEvent evt) { if (evt != null && evt.getPropertyName() != null) { String propertyName = evt.getPropertyName(); @@ -139,11 +129,9 @@ public void propertyChange(PropertyChangeEvent evt) { } } - private void refreshFileList() - { + private void refreshFileList() { WizardModel model = getWizardModel(); - if (model != null) - { + if (model != null) { // Disable the "" buttons. boolean backEnabled = model.isBackButtonEnabled(); boolean nextEnabled = model.isNextButtonEnabled(); @@ -159,8 +147,7 @@ private void refreshFileList() // Create FileSets from the search results (if any). List fileSetList = makeFileSetList(fileList); - if (fileSetList != null) - { + if (fileSetList != null) { makeDefaultSelections(fileSetList); makeTitles(fileSetList); sortFileSetList(fileSetList); @@ -176,12 +163,15 @@ private void refreshFileList() } private static class UpdateDescriptionFilter implements FileFilter { + private FileFilter delegate; private ProgressPanel panel; + private UpdateDescriptionFilter(FileFilter delegate, ProgressPanel panel) { this.delegate = delegate; this.panel = panel; } + public boolean accept(File pathname) { if (!Thread.interrupted()) { if (this.panel != null && pathname != null) { @@ -197,20 +187,17 @@ public boolean accept(File pathname) { } } - private List searchSelectedFile(File fileToSearch, FileFilter fileFilter) - { - if (Thread.interrupted()) + private List searchSelectedFile(File fileToSearch, FileFilter fileFilter) { + if (Thread.interrupted()) { return null; + } List fileList; - try - { + try { FileTree fileTree = new FileTree(fileToSearch); fileTree.setMode(FileTree.FILES_ONLY); fileList = fileTree.asList(fileFilter); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = String.format("Exception while searching file: %s", fileToSearch); Logging.logger().log(java.util.logging.Level.SEVERE, message, t); fileList = null; @@ -219,6 +206,7 @@ private List searchSelectedFile(File fileToSearch, FileFilter fileFilter) } private static class AcceptRPFFilter implements FileFilter { + public boolean accept(File pathname) { if (pathname != null && pathname.getName() != null) { String filename = pathname.getName().toUpperCase(); @@ -228,31 +216,24 @@ public boolean accept(File pathname) { } } - private List makeFileSetList(List fileList) - { + private List makeFileSetList(List fileList) { List result = null; - if (fileList != null) - { + if (fileList != null) { Map map = new HashMap(); - for (File file : fileList) - { - try - { + for (File file : fileList) { + try { String filename = file.getName().toUpperCase(); RPFFrameFilename rpfFilename = RPFFrameFilename.parseFilename(filename); String id = rpfFilename.getDataSeriesCode(); FileSet set = map.get(id); - if (set == null) - { + if (set == null) { set = new FileSet(); set.setIdentifier(id); set.setFiles(new LinkedList()); map.put(id, set); } set.getFiles().add(file); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } @@ -262,44 +243,35 @@ private List makeFileSetList(List fileList) return result; } - private void makeDefaultSelections(List fileSetList) - { + private void makeDefaultSelections(List fileSetList) { // If only one FileSet is available, select it. if (fileSetList != null - && fileSetList.size() == 1 - && fileSetList.get(0) != null) - { + && fileSetList.size() == 1 + && fileSetList.get(0) != null) { fileSetList.get(0).setSelected(true); } } - private void makeTitles(Iterable fileSetList) - { - if (fileSetList != null) - { - for (FileSet set : fileSetList) + private void makeTitles(Iterable fileSetList) { + if (fileSetList != null) { + for (FileSet set : fileSetList) { makeTitle(set); + } } } - private void makeTitle(FileSet set) - { - if (set != null && set.getIdentifier() != null) - { + private void makeTitle(FileSet set) { + if (set != null && set.getIdentifier() != null) { String id = set.getIdentifier(); RPFDataSeries ds; - try - { + try { ds = RPFDataSeries.dataSeriesFor(id); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); ds = null; } - if (ds != null) - { + if (ds != null) { StringBuilder sb = new StringBuilder(); sb.append(ds.dataSeries); sb.append(" ("); @@ -310,27 +282,25 @@ private void makeTitle(FileSet set) } } - private void sortFileSetList(List fileSetList) - { + private void sortFileSetList(List fileSetList) { Comparator comparator = new Comparator() { public int compare(FileSet o1, FileSet o2) { // Don't care about ordering in this case. - if (o1 == null || o2 == null) + if (o1 == null || o2 == null) { return 0; + } String id1 = o1.getIdentifier(); String id2 = o2.getIdentifier(); // Don't care about ordering in this case. - if (id1 == null || id2 == null) + if (id1 == null || id2 == null) { return 0; + } RPFDataSeries ds1, ds2; - try - { + try { ds1 = RPFDataSeries.dataSeriesFor(id1); ds2 = RPFDataSeries.dataSeriesFor(id2); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); ds1 = ds2 = null; } @@ -343,17 +313,16 @@ public int compare(FileSet o1, FileSet o2) { Collections.sort(fileSetList, comparator); } - private void startWorkerThread(Runnable runnable) - { + private void startWorkerThread(Runnable runnable) { killWorkerThread(); this.workerThread = new Thread(runnable); this.workerThread.start(); } - private void killWorkerThread() - { - if (this.workerThread != null && this.workerThread.isAlive()) + private void killWorkerThread() { + if (this.workerThread != null && this.workerThread.isAlive()) { this.workerThread.interrupt(); + } this.workerThread = null; } } diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/FileSet.java b/src/gov/nasa/worldwind/layers/rpf/wizard/FileSet.java index 876e240df6..a7d3caa71c 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/FileSet.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/FileSet.java @@ -14,63 +14,53 @@ * @author dcollins * @version $Id: FileSet.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FileSet extends WizardProperties -{ +public class FileSet extends WizardProperties { + public static final String IDENTIFIER = "fileSet.Identifier"; public static final String FILES = "fileSet.Files"; public static final String TITLE = "fileSet.Title"; public static final String SELECTED = "fileSet.Selected"; - public FileSet() - { + public FileSet() { } - public String getIdentifier() - { + public String getIdentifier() { return getStringProperty(IDENTIFIER); } - public void setIdentifier(String identifier) - { + public void setIdentifier(String identifier) { setProperty(IDENTIFIER, identifier); } @SuppressWarnings({"unchecked"}) - public Collection getFiles() - { + public Collection getFiles() { Object value = getProperty(FILES); return (value != null && value instanceof Collection) ? (Collection) value : null; } - public void setFiles(Collection files) - { + public void setFiles(Collection files) { setProperty(FILES, files); } - public int getFileCount() - { + public int getFileCount() { Collection files = getFiles(); return files != null ? files.size() : 0; } - public String getTitle() - { + public String getTitle() { return getStringProperty(TITLE); } - public void setTitle(String title) - { + public void setTitle(String title) { setProperty(TITLE, title); } - public boolean isSelected() - { + public boolean isSelected() { Boolean b = getBooleanProperty(SELECTED); return b != null ? b : false; } - public void setSelected(boolean b) - { + public void setSelected(boolean b) { setProperty(SELECTED, b); } } diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/PreprocessPanelDescriptor.java b/src/gov/nasa/worldwind/layers/rpf/wizard/PreprocessPanelDescriptor.java index 94dc91b32a..1c959d9492 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/PreprocessPanelDescriptor.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/PreprocessPanelDescriptor.java @@ -25,8 +25,8 @@ * @author dcollins * @version $Id: PreprocessPanelDescriptor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PreprocessPanelDescriptor extends DefaultPanelDescriptor -{ +public class PreprocessPanelDescriptor extends DefaultPanelDescriptor { + private ProgressPanel panelComponent; // Preprocessor logical components. private RPFTiledImageProcessor preprocessor; @@ -44,14 +44,13 @@ public class PreprocessPanelDescriptor extends DefaultPanelDescriptor private static final int DEFAULT_THREAD_POOL_SIZE = 3; private static final int DEFAULT_STEPS_NEEDED_FOR_ESTIMATE = 20; - public PreprocessPanelDescriptor() - { + public PreprocessPanelDescriptor() { // Get preprocessor thread pool size, and num steps needed for ETR // from Configuration. Provide suitable defaults if these values // aren't specified. int threadPoolSize = Configuration.getIntegerValue(THREAD_POOL_SIZE, DEFAULT_THREAD_POOL_SIZE); int stepsNeededForEst = Configuration.getIntegerValue(STEPS_NEEDED_FOR_ESTIMATE, - DEFAULT_STEPS_NEEDED_FOR_ESTIMATE); + DEFAULT_STEPS_NEEDED_FOR_ESTIMATE); this.panelComponent = new ProgressPanel(); this.preprocessor = new RPFTiledImageProcessor(); @@ -62,18 +61,15 @@ public PreprocessPanelDescriptor() setPanelComponent(this.panelComponent); } - public Object getBackPanelDescriptor() - { + public Object getBackPanelDescriptor() { return null; } - public Object getNextPanelDescriptor() - { + public Object getNextPanelDescriptor() { return Wizard.FINISH; } - public void aboutToDisplayPanel() - { + public void aboutToDisplayPanel() { this.panelComponent.getProgressBar().setMinimum(0); this.panelComponent.getProgressBar().setMaximum(0); this.panelComponent.getProgressBar().setValue(0); @@ -81,18 +77,15 @@ public void aboutToDisplayPanel() this.panelComponent.setProgressDescription2(" "); } - public void displayingPanel() - { + public void displayingPanel() { WizardModel model = getWizardModel(); final Iterable fileSetList = RPFWizardUtil.getFileSetList(model); final File selectedFile = RPFWizardUtil.getSelectedFile(model); - if (fileSetList != null && selectedFile != null) - { + if (fileSetList != null && selectedFile != null) { this.panelComponent.setTitle(RPFWizardUtil.makeLarger("Importing Imagery")); this.panelComponent.setDescription(""); this.panelComponent.getProgressBar().setVisible(true); - if (model != null) - { + if (model != null) { model.setNextButtonEnabled(false); } @@ -111,41 +104,33 @@ public void run() { finished(); } }); - } - else - { + } else { this.panelComponent.setTitle(RPFWizardUtil.makeLarger("No Imagery to Import")); this.panelComponent.setDescription("No Imagery"); this.panelComponent.getProgressBar().setVisible(false); } } - public void aboutToHidePanel() - { + public void aboutToHidePanel() { Wizard wizard = getWizard(); - if (wizard != null && wizard.getReturnCode() == Wizard.FINISH_RETURN_CODE) - { + if (wizard != null && wizard.getReturnCode() == Wizard.FINISH_RETURN_CODE) { // "Finish" button pressed. - } - else - { + } else { // " layerList = RPFWizardUtil.getLayerList(model); - if (layerList == null) - { + if (layerList == null) { layerList = new ArrayList(); RPFWizardUtil.setLayerList(model, layerList); } @@ -187,8 +167,7 @@ private void preprocess(File inFile, FileSet set, int setNumber, int numSets) Logging.logger().fine(message); } - private void finished() - { + private void finished() { this.panelComponent.setTitle(RPFWizardUtil.makeLarger("Finished")); this.panelComponent.setDescription(makeFinishedDescription()); this.panelComponent.getProgressBar().setMinimum(0); @@ -199,13 +178,13 @@ private void finished() this.panelComponent.setProgressDescription2(" "); WizardModel model = getWizardModel(); - if (model != null) - { + if (model != null) { model.setNextButtonEnabled(true); } } private class PropertyEvents implements PropertyChangeListener { + public void propertyChange(PropertyChangeEvent evt) { if (evt != null && evt.getPropertyName() != null) { if (evt.getPropertyName().equals(RPFTiledImageProcessor.BEGIN_SUB_TASK)) { @@ -223,29 +202,26 @@ public void propertyChange(PropertyChangeEvent evt) { } } - private void beginTask() - { + private void beginTask() { this.stepsTaken.set(0); this.stepsWithErrors.set(0); this.etrCalc.setStartTime(System.currentTimeMillis()); } - private void endTask() - { + private void endTask() { this.panelComponent.setProgressDescription1(" "); this.panelComponent.setProgressDescription2(" "); } - private void stepsForTask(int numSteps) - { + private void stepsForTask(int numSteps) { this.numSteps = numSteps; } - private void stepComplete(String description, boolean success) - { + private void stepComplete(String description, boolean success) { int n = this.stepsTaken.incrementAndGet(); - if (!success) + if (!success) { this.stepsWithErrors.incrementAndGet(); + } int numFiles = this.numSteps; this.etrCalc.setStep(n); @@ -255,75 +231,66 @@ private void stepComplete(String description, boolean success) StringBuilder sb = new StringBuilder(); sb.append(description); int nErrors = this.stepsWithErrors.get(); - if (nErrors > 0) - { - if (sb.length() > 0) + if (nErrors > 0) { + if (sb.length() > 0) { sb.append("; "); + } sb.append(formatFileCount(nErrors)).append(" with errors"); } setProgressMessage(sb.toString()); setProgress(n, numFiles, etr); } - private void setProgress(int progressValue, int progressRange, long remainingMillis) - { - if (progressValue >= 0 && progressValue < progressRange) - { + private void setProgress(int progressValue, int progressRange, long remainingMillis) { + if (progressValue >= 0 && progressValue < progressRange) { this.panelComponent.getProgressBar().setValue(progressValue); this.panelComponent.getProgressBar().setMaximum(progressRange); StringBuilder sb = new StringBuilder(); sb.append(String.format("%,d of %,d", progressValue, progressRange)); - if (remainingMillis > 0) - { + if (remainingMillis > 0) { TimeFormatter tf = new TimeFormatter(); - if (sb.length() > 0) + if (sb.length() > 0) { sb.append(" - "); + } sb.append(tf.formatEstimate(remainingMillis)); } this.panelComponent.setProgressDescription2(sb.toString()); - } - else - { + } else { this.panelComponent.getProgressBar().setValue(0); this.panelComponent.getProgressBar().setMaximum(0); this.panelComponent.setProgressDescription2(" "); } } - private void setProgressMessage(String message) - { + private void setProgressMessage(String message) { this.panelComponent.setProgressDescription1(message); } - private String formatFileCount(int n) - { + private String formatFileCount(int n) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%,d", n)); sb.append(" file"); - if (n != 1) + if (n != 1) { sb.append("s"); + } return sb.toString(); } - private String makeDescription(FileSet set, int value, int max) - { + private String makeDescription(FileSet set, int value, int max) { StringBuilder sb = new StringBuilder(); sb.append("Importing "); - if (set != null && set.getTitle() != null) - { + if (set != null && set.getTitle() != null) { sb.append("\'"); sb.append(set.getTitle()); sb.append("\'"); } - if (max > 1) - { + if (max > 1) { sb.append(" (").append(value).append(" of ").append(max).append(")"); } return sb.toString(); } - private String makeSubStepDescription(String description, String subDescription) - { + private String makeSubStepDescription(String description, String subDescription) { StringBuilder sb = new StringBuilder(); sb.append("
        "); sb.append(description); @@ -332,8 +299,7 @@ private String makeSubStepDescription(String description, String subDescription) return sb.toString(); } - private String makeFinishedDescription() - { + private String makeFinishedDescription() { StringBuilder sb = new StringBuilder(); sb.append(""); sb.append("
        "); @@ -344,26 +310,21 @@ private String makeFinishedDescription() WizardModel model = getWizardModel(); Iterable fileSetList = RPFWizardUtil.getFileSetList(model); - if (fileSetList != null) - { - for (FileSet set : fileSetList) - { - if (set != null && set.isSelected()) - { + if (fileSetList != null) { + for (FileSet set : fileSetList) { + if (set != null && set.isSelected()) { sb.append(""); sb.append(set.getTitle()); sb.append(""); Integer filesProcessed = set.getIntegerProperty("filesProcessed"); Integer filesWithErrors = set.getIntegerProperty("filesWithErrors"); - if (filesProcessed != null && filesWithErrors != null) - { + if (filesProcessed != null && filesWithErrors != null) { int numFilesOk = filesProcessed - filesWithErrors; sb.append("
        "); sb.append(""); sb.append(formatFileCount(numFilesOk)).append(" imported"); - if (filesWithErrors > 0) - { + if (filesWithErrors > 0) { sb.append("; "); sb.append(""); sb.append(formatFileCount(filesWithErrors)).append(" with errors"); @@ -380,17 +341,16 @@ private String makeFinishedDescription() return sb.toString(); } - private void startWorkerThread(Runnable runnable) - { + private void startWorkerThread(Runnable runnable) { killWorkerThread(); this.workerThread = new Thread(runnable); this.workerThread.start(); } - private void killWorkerThread() - { - if (this.workerThread != null && this.workerThread.isAlive()) + private void killWorkerThread() { + if (this.workerThread != null && this.workerThread.isAlive()) { this.workerThread.interrupt(); + } this.workerThread = null; } } diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/ProgressPanel.java b/src/gov/nasa/worldwind/layers/rpf/wizard/ProgressPanel.java index f5973cd75e..0ba3f7e9bf 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/ProgressPanel.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/ProgressPanel.java @@ -13,8 +13,8 @@ * @author dcollins * @version $Id: ProgressPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ProgressPanel extends JPanel -{ +public class ProgressPanel extends JPanel { + // Panel title and optional description. private JLabel title; private JLabel description; @@ -23,59 +23,48 @@ public class ProgressPanel extends JPanel private JLabel progressDescription1; private JLabel progressDescription2; - public ProgressPanel() - { + public ProgressPanel() { makeComponents(); layoutComponents(); } - public String getTitle() - { + public String getTitle() { return this.title.getText(); } - public void setTitle(String title) - { + public void setTitle(String title) { this.title.setText(title); } - public String getDescription() - { + public String getDescription() { return this.description.getText(); } - public void setDescription(String description) - { + public void setDescription(String description) { this.description.setText(description); } - public JProgressBar getProgressBar() - { + public JProgressBar getProgressBar() { return this.progressBar; } - - public String getProgressDescription1() - { + + public String getProgressDescription1() { return this.progressDescription1.getText(); } - public void setProgressDescription1(String description) - { + public void setProgressDescription1(String description) { this.progressDescription1.setText(description); } - public String getProgressDescription2() - { + public String getProgressDescription2() { return this.progressDescription2.getText(); } - public void setProgressDescription2(String description) - { + public void setProgressDescription2(String description) { this.progressDescription2.setText(description); } - private void makeComponents() - { + private void makeComponents() { this.title = new JLabel(" "); this.title.setBackground(Color.gray); this.title.setOpaque(true); @@ -86,8 +75,7 @@ private void makeComponents() this.progressDescription2 = new JLabel(); } - private void layoutComponents() - { + private void layoutComponents() { removeAll(); setLayout(new BorderLayout()); diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/RPFImportWizard.java b/src/gov/nasa/worldwind/layers/rpf/wizard/RPFImportWizard.java index d08bbe13de..f171799c6a 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/RPFImportWizard.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/RPFImportWizard.java @@ -16,27 +16,23 @@ * @author dcollins * @version $Id: RPFImportWizard.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFImportWizard extends Wizard -{ - public RPFImportWizard() - { +public class RPFImportWizard extends Wizard { + + public RPFImportWizard() { registerPanels(); } - public RPFImportWizard(Dialog owner) - { + public RPFImportWizard(Dialog owner) { super(owner); registerPanels(); } - public RPFImportWizard(Frame owner) - { + public RPFImportWizard(Frame owner) { super(owner); registerPanels(); } - - private void registerPanels() - { + + private void registerPanels() { // Step 1: Choose where to import from. WizardPanelDescriptor wpd = new FileChooserPanelDescriptor(); registerWizardPanel(FileChooserPanelDescriptor.IDENTIFIER, wpd); diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/RPFWizardUtil.java b/src/gov/nasa/worldwind/layers/rpf/wizard/RPFWizardUtil.java index d1f57ee737..d2af8f6039 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/RPFWizardUtil.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/RPFWizardUtil.java @@ -16,18 +16,16 @@ * @author dcollins * @version $Id: RPFWizardUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RPFWizardUtil -{ +public class RPFWizardUtil { + public static final String SELECTED_FILE = "selectedFile"; public static final String FILE_LIST = "fileList"; public static final String IS_FILE_LIST_CURRENT = "isFileListCurrent"; public static final String FILE_SET_LIST = "fileSetList"; public static final String LAYER_LIST = "layerList"; - public static File getSelectedFile(WizardProperties properties) - { - if (properties == null) - { + public static File getSelectedFile(WizardProperties properties) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -35,15 +33,14 @@ public static File getSelectedFile(WizardProperties properties) File file = null; Object value = properties.getProperty(SELECTED_FILE); - if (value != null && value instanceof File) + if (value != null && value instanceof File) { file = (File) value; + } return file; } - public static void setSelectedFile(WizardProperties properties, File file) - { - if (properties == null) - { + public static void setSelectedFile(WizardProperties properties, File file) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -53,10 +50,8 @@ public static void setSelectedFile(WizardProperties properties, File file) } @SuppressWarnings({"unchecked"}) - public static List getFileList(WizardProperties properties) - { - if (properties == null) - { + public static List getFileList(WizardProperties properties) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -64,15 +59,14 @@ public static List getFileList(WizardProperties properties) List fileList = null; Object value = properties.getProperty(FILE_LIST); - if (value != null && value instanceof List) + if (value != null && value instanceof List) { fileList = (List) value; + } return fileList; } - public static void setFileList(WizardProperties properties, List fileList) - { - if (properties == null) - { + public static void setFileList(WizardProperties properties, List fileList) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -81,10 +75,8 @@ public static void setFileList(WizardProperties properties, List fileList) properties.setProperty(FILE_LIST, fileList); } - public static boolean isFileListCurrent(WizardProperties properties) - { - if (properties == null) - { + public static boolean isFileListCurrent(WizardProperties properties) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -92,15 +84,14 @@ public static boolean isFileListCurrent(WizardProperties properties) boolean isFileListCurrent = false; Boolean value = properties.getBooleanProperty(IS_FILE_LIST_CURRENT); - if (value != null) + if (value != null) { isFileListCurrent = value; + } return isFileListCurrent; } - public static void setFileListCurrent(WizardProperties properties, boolean current) - { - if (properties == null) - { + public static void setFileListCurrent(WizardProperties properties, boolean current) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,10 +101,8 @@ public static void setFileListCurrent(WizardProperties properties, boolean curre } @SuppressWarnings({"unchecked"}) - public static List getFileSetList(WizardProperties properties) - { - if (properties == null) - { + public static List getFileSetList(WizardProperties properties) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -121,15 +110,14 @@ public static List getFileSetList(WizardProperties properties) List fileSets = null; Object value = properties.getProperty(FILE_SET_LIST); - if (value != null && value instanceof List) + if (value != null && value instanceof List) { fileSets = (List) value; + } return fileSets; } - public static void setFileSetList(WizardProperties properties, List fileSetList) - { - if (properties == null) - { + public static void setFileSetList(WizardProperties properties, List fileSetList) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -139,10 +127,8 @@ public static void setFileSetList(WizardProperties properties, List fil } @SuppressWarnings({"unchecked"}) - public static List getLayerList(WizardProperties properties) - { - if (properties == null) - { + public static List getLayerList(WizardProperties properties) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -150,15 +136,14 @@ public static List getLayerList(WizardProperties properties) List fileSets = null; Object value = properties.getProperty(LAYER_LIST); - if (value != null && value instanceof List) + if (value != null && value instanceof List) { fileSets = (List) value; + } return fileSets; } - public static void setLayerList(WizardProperties properties, List layerList) - { - if (properties == null) - { + public static void setLayerList(WizardProperties properties, List layerList) { + if (properties == null) { String message = "WizardProperties is null"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -167,10 +152,8 @@ public static void setLayerList(WizardProperties properties, List layerLi properties.setProperty(LAYER_LIST, layerList); } - public static String makeLarger(String text) - { - if (text == null) - { + public static String makeLarger(String text) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -185,10 +168,8 @@ public static String makeLarger(String text) return sb.toString(); } - public static String makeSmaller(String text) - { - if (text == null) - { + public static String makeSmaller(String text) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -203,10 +184,8 @@ public static String makeSmaller(String text) return sb.toString(); } - public static String makeBold(String text) - { - if (text == null) - { + public static String makeBold(String text) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/SizeFormatter.java b/src/gov/nasa/worldwind/layers/rpf/wizard/SizeFormatter.java index 59e748506d..2e05bc3983 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/SizeFormatter.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/SizeFormatter.java @@ -9,55 +9,45 @@ * @author dcollins * @version $Id: SizeFormatter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SizeFormatter -{ +public class SizeFormatter { + private static final long ONE_GIGABYTE = 1L << 30L; private static final long ONE_MEGABYTE = 1L << 20L; private static final long ONE_KILOBYTE = 1L << 10L; - public SizeFormatter() - {} + public SizeFormatter() { + } - public String formatPrecise(long bytes) - { + public String formatPrecise(long bytes) { long[] GbMbKbB = bytesToGbMbKbB(bytes); return String.format("%dGB %dMB %dKB %dbytes", GbMbKbB[0], GbMbKbB[1], GbMbKbB[2], GbMbKbB[3]); } - public String formatEstimate(long bytes) - { + public String formatEstimate(long bytes) { String result; double Gb = bytes / (double) ONE_GIGABYTE; double Mb = bytes / (double) ONE_MEGABYTE; double Kb = bytes / (double) ONE_KILOBYTE; // Size in Giga-bytes. - if (Gb >= 1) - { + if (Gb >= 1) { result = String.format("%.2f GB", Gb); - } - // Size in Mega-bytes. - else if (Mb >= 1) - { + } // Size in Mega-bytes. + else if (Mb >= 1) { result = String.format("%.0f MB", Mb); - } - // Size in Kilo-bytes. - else if (Kb >= 1) - { + } // Size in Kilo-bytes. + else if (Kb >= 1) { result = String.format("%.0f KB", Kb); - } - // Size in bytes. - else - { + } // Size in bytes. + else { result = String.format("%d bytes", bytes); } return result; } - private static long[] bytesToGbMbKbB(long bytes) - { - return new long[] { + private static long[] bytesToGbMbKbB(long bytes) { + return new long[]{ (long) (Math.floor(bytes / (double) ONE_GIGABYTE) % 1024d), (long) (Math.floor(bytes / (double) ONE_MEGABYTE) % 1024d), (long) (Math.floor(bytes / (double) ONE_KILOBYTE) % 1024d), diff --git a/src/gov/nasa/worldwind/layers/rpf/wizard/TimeFormatter.java b/src/gov/nasa/worldwind/layers/rpf/wizard/TimeFormatter.java index 56ae5159cc..4acb6d57b4 100644 --- a/src/gov/nasa/worldwind/layers/rpf/wizard/TimeFormatter.java +++ b/src/gov/nasa/worldwind/layers/rpf/wizard/TimeFormatter.java @@ -9,63 +9,54 @@ * @author dcollins * @version $Id: TimeFormatter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TimeFormatter -{ - private static final long ONE_HOUR = 60L * 60L * 1000L; +public class TimeFormatter { + + private static final long ONE_HOUR = 60L * 60L * 1000L; private static final long ONE_MINUTE = 60L * 1000L; private static final long ONE_SECOND = 1000L; - public TimeFormatter() - {} + public TimeFormatter() { + } - public String formatPrecise(long millis) - { + public String formatPrecise(long millis) { long[] hms = millisToHMS(millis); return String.format("%02d:%02d:%02d", hms[0], hms[1], hms[2]); } - public String formatEstimate(long millis) - { + public String formatEstimate(long millis) { String result; // Less than a minute. - if (millis < ONE_MINUTE) - { + if (millis < ONE_MINUTE) { result = "less than 1 minute"; - } - // Report time in one-minute increments. - else if (millis < 10L* ONE_MINUTE) - { + } // Report time in one-minute increments. + else if (millis < 10L * ONE_MINUTE) { millis = ONE_MINUTE * Math.round(millis / (double) ONE_MINUTE); long m = millis / ONE_MINUTE; result = "about " + m + (m > 1 ? " minutes" : " minute"); - } - // Report time in ten-minute increments. - else if (millis < 55L * ONE_MINUTE) - { + } // Report time in ten-minute increments. + else if (millis < 55L * ONE_MINUTE) { millis = 10L * ONE_MINUTE * Math.round(millis / (10d * ONE_MINUTE)); long m = millis / ONE_MINUTE; result = "about " + m + " minutes"; - } - // Report time in half-hour increments. - else - { + } // Report time in half-hour increments. + else { millis = 30L * ONE_MINUTE * Math.round(millis / (30d * ONE_MINUTE)); long h = millis / ONE_HOUR; result = "about " + h + (h > 1 ? " hours" : " hour"); long m = (millis / ONE_MINUTE) % 60L; - if (m > 0) + if (m > 0) { result += " " + m + " minutes"; + } } return result; } - private static long[] millisToHMS(long millis) - { - return new long[] { - (long) (Math.floor(millis / (double) ONE_HOUR) % 60d), // hours - (long) (Math.floor(millis / (double) ONE_MINUTE) % 60d), // minutes + private static long[] millisToHMS(long millis) { + return new long[]{ + (long) (Math.floor(millis / (double) ONE_HOUR) % 60d), // hours + (long) (Math.floor(millis / (double) ONE_MINUTE) % 60d), // minutes (long) (Math.floor(millis / (double) ONE_SECOND) % 60d)}; // seconds } diff --git a/src/gov/nasa/worldwind/ogc/OGCAddress.java b/src/gov/nasa/worldwind/ogc/OGCAddress.java index 099c576d19..663a4b1666 100644 --- a/src/gov/nasa/worldwind/ogc/OGCAddress.java +++ b/src/gov/nasa/worldwind/ogc/OGCAddress.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.xml.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: OGCAddress.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGCAddress extends AbstractXMLEventParser -{ +public class OGCAddress extends AbstractXMLEventParser { + protected QName ADDRESS_TYPE; protected QName ADDRESS; protected QName CITY; @@ -34,15 +33,13 @@ public class OGCAddress extends AbstractXMLEventParser protected String postCode; protected String country; - public OGCAddress(String namespaceURI) - { + public OGCAddress(String namespaceURI) { super(namespaceURI); this.initialize(); } - protected void initialize() - { + protected void initialize() { ADDRESS_TYPE = new QName(this.getNamespaceURI(), "AddressType"); ADDRESS = new QName(this.getNamespaceURI(), "Address"); CITY = new QName(this.getNamespaceURI(), "City"); @@ -53,97 +50,72 @@ protected void initialize() @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, ADDRESS_TYPE)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, ADDRESS_TYPE)) { this.setAddressType(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, ADDRESS)) - { + } else if (ctx.isStartElement(event, ADDRESS)) { this.setAddress(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, CITY)) - { + } else if (ctx.isStartElement(event, CITY)) { this.setCity(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, STATE_OR_PROVINCE)) - { + } else if (ctx.isStartElement(event, STATE_OR_PROVINCE)) { this.setStateOrProvince(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, POST_CODE)) - { + } else if (ctx.isStartElement(event, POST_CODE)) { this.setPostCode(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, COUNTRY)) - { + } else if (ctx.isStartElement(event, COUNTRY)) { this.setCountry(ctx.getStringParser().parseString(ctx, event)); } } - public String getAddressType() - { + public String getAddressType() { return addressType; } - protected void setAddressType(String addressType) - { + protected void setAddressType(String addressType) { this.addressType = addressType; } - public String getAddress() - { + public String getAddress() { return address; } - protected void setAddress(String address) - { + protected void setAddress(String address) { this.address = address; } - public String getCity() - { + public String getCity() { return city; } - protected void setCity(String city) - { + protected void setCity(String city) { this.city = city; } - public String getStateOrProvince() - { + public String getStateOrProvince() { return stateOrProvince; } - protected void setStateOrProvince(String stateOrProvince) - { + protected void setStateOrProvince(String stateOrProvince) { this.stateOrProvince = stateOrProvince; } - public String getPostCode() - { + public String getPostCode() { return postCode; } - protected void setPostCode(String postCode) - { + protected void setPostCode(String postCode) { this.postCode = postCode; } - public String getCountry() - { + public String getCountry() { return country; } - protected void setCountry(String country) - { + protected void setCountry(String country) { this.country = country; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AddressType: ").append(this.addressType != null ? this.addressType : "none").append(" "); diff --git a/src/gov/nasa/worldwind/ogc/OGCBoundingBox.java b/src/gov/nasa/worldwind/ogc/OGCBoundingBox.java index a1e7c7f087..b3f60da7ec 100644 --- a/src/gov/nasa/worldwind/ogc/OGCBoundingBox.java +++ b/src/gov/nasa/worldwind/ogc/OGCBoundingBox.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: OGCBoundingBox.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGCBoundingBox extends AbstractXMLEventParser -{ +public class OGCBoundingBox extends AbstractXMLEventParser { + private String crs; private double minx; private double maxx; @@ -29,12 +28,10 @@ public class OGCBoundingBox extends AbstractXMLEventParser private double resy; public static OGCBoundingBox createFromStrings(String crs, String minx, String maxx, String miny, String maxy, - String resx, String resy) - { + String resx, String resy) { OGCBoundingBox bbox = new OGCBoundingBox(null); - try - { + try { bbox.crs = crs; bbox.minx = Double.parseDouble(minx); bbox.maxx = Double.parseDouble(maxx); @@ -42,9 +39,7 @@ public static OGCBoundingBox createFromStrings(String crs, String minx, String m bbox.maxy = Double.parseDouble(maxy); bbox.resx = resx != null && !resx.equals("") ? Double.parseDouble(resx) : 0; bbox.resy = resy != null && !resy.equals("") ? Double.parseDouble(resy) : 0; - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("XML.ImproperDataType"); Logging.logger().severe(message); throw e; @@ -53,139 +48,116 @@ public static OGCBoundingBox createFromStrings(String crs, String minx, String m return bbox; } - public OGCBoundingBox(String namespaceURI) - { + public OGCBoundingBox(String namespaceURI) { super(namespaceURI); } @Override - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("CRS") && attr.getValue() != null) - { + if (attr.getName().getLocalPart().equals("CRS") && attr.getValue() != null) { String s = attr.getValue(); - if (s != null) + if (s != null) { this.setCRS(s); - } - else if (attr.getName().getLocalPart().equals("minx") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("minx") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setMinx(d); - } - else if (attr.getName().getLocalPart().equals("miny") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("miny") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setMiny(d); - } - else if (attr.getName().getLocalPart().equals("maxx") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("maxx") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setMaxx(d); - } - else if (attr.getName().getLocalPart().equals("maxy") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("maxy") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setMaxy(d); - } - else if (attr.getName().getLocalPart().equals("resx") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("resx") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setResx(d); - } - else if (attr.getName().getLocalPart().equals("resy") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("resy") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setResy(d); + } } } } - public String getCRS() - { + public String getCRS() { return crs; } - protected void setCRS(String crs) - { + protected void setCRS(String crs) { this.crs = crs; } - public double getMinx() - { + public double getMinx() { return minx; } - protected void setMinx(double minx) - { + protected void setMinx(double minx) { this.minx = minx; } - public double getMaxx() - { + public double getMaxx() { return maxx; } - protected void setMaxx(double maxx) - { + protected void setMaxx(double maxx) { this.maxx = maxx; } - public double getMiny() - { + public double getMiny() { return miny; } - protected void setMiny(double miny) - { + protected void setMiny(double miny) { this.miny = miny; } - public double getMaxy() - { + public double getMaxy() { return maxy; } - protected void setMaxy(double maxy) - { + protected void setMaxy(double maxy) { this.maxy = maxy; } - public double getResx() - { + public double getResx() { return resx; } - protected void setResx(double resx) - { + protected void setResx(double resx) { this.resx = resx; } - public double getResy() - { + public double getResy() { return resy; } - protected void setResy(double resy) - { + protected void setResy(double resy) { this.resy = resy; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.crs); diff --git a/src/gov/nasa/worldwind/ogc/OGCCapabilities.java b/src/gov/nasa/worldwind/ogc/OGCCapabilities.java index 8dd6b21920..5d56d55ab3 100644 --- a/src/gov/nasa/worldwind/ogc/OGCCapabilities.java +++ b/src/gov/nasa/worldwind/ogc/OGCCapabilities.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.*; @@ -20,8 +19,8 @@ * @author tag * @version $Id: OGCCapabilities.java 1171 2013-02-11 21:45:02Z dcollins $ */ -abstract public class OGCCapabilities extends AbstractXMLEventParser -{ +abstract public class OGCCapabilities extends AbstractXMLEventParser { + /** * Returns the default namespace URI. Must be overridden by subclasses to provide a specific URI. The default * namespace is used to match XML elements found in the default namespace of the XML stream. @@ -58,21 +57,19 @@ abstract public class OGCCapabilities extends AbstractXMLEventParser * Create a new capabilities parser. * * @param namespaceURI the default namespace URI. - * @param docSource the XML source. May be a filename, file, stream or other type allowed by {@link + * @param docSource the XML source. May be a filename, file, stream or other type allowed by {@link * WWXML#openEventReader(Object)}. * * @throws IllegalArgumentException if the document source is null. */ - public OGCCapabilities(String namespaceURI, Object docSource) - { + public OGCCapabilities(String namespaceURI, Object docSource) { super(namespaceURI); this.eventReader = this.createReader(docSource); this.initialize(); } - private void initialize() - { + private void initialize() { this.parserContext = this.createParserContext(this.eventReader); SERVICE = new QName(this.getNamespaceURI(), "Service"); @@ -84,24 +81,22 @@ private void initialize() // Capability parser is registered by subclass. } - protected XMLEventReader createReader(Object docSource) - { + protected XMLEventReader createReader(Object docSource) { return WWXML.openEventReader(docSource); } - protected XMLEventParserContext createParserContext(XMLEventReader reader) - { + protected XMLEventParserContext createParserContext(XMLEventReader reader) { this.parserContext = new BasicXMLEventParserContext(reader); this.parserContext.setDefaultNamespaceURI(this.getDefaultNamespaceURI()); return this.parserContext; } - /** {@inheritDoc} */ - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { - if (ctx == null) - { + /** + * {@inheritDoc} + */ + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { + if (ctx == null) { String message = Logging.getMessage("nullValue.ParserContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -109,8 +104,9 @@ public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) XMLEventParser defaultParser = null; - if (ctx.isStartElement(event, SERVICE)) + if (ctx.isStartElement(event, SERVICE)) { defaultParser = new OGCServiceInformation(this.getNamespaceURI()); + } return ctx.allocate(event, defaultParser); } @@ -121,21 +117,19 @@ public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) * * @param args optional arguments to pass to parsers of sub-elements. * - * @return this if parsing is successful, otherwise null. + * @return this if parsing is successful, otherwise null. * * @throws XMLStreamException if an exception occurs while attempting to read the event stream. */ - public OGCCapabilities parse(Object... args) throws XMLStreamException - { + public OGCCapabilities parse(Object... args) throws XMLStreamException { XMLEventParserContext ctx = this.parserContext; - for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isStartElement() && this.isRootElementName(event.asStartElement().getName())) - { + if (event.isStartElement() && this.isRootElementName(event.asStartElement().getName())) { super.parse(ctx, event, args); return this; } @@ -145,49 +139,44 @@ public OGCCapabilities parse(Object... args) throws XMLStreamException } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, SERVICE)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, SERVICE)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCServiceInformation) + if (o != null && o instanceof OGCServiceInformation) { this.setServiceInformation((OGCServiceInformation) o); + } } - } - else if (ctx.isStartElement(event, CAPABILITY)) - { + } else if (ctx.isStartElement(event, CAPABILITY)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCCapabilityInformation) + if (o != null && o instanceof OGCCapabilityInformation) { this.setCapabilityInformation((OGCCapabilityInformation) o); + } } } } @Override - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (ctx.isSameAttributeName(attr.getName(), VERSION)) + if (ctx.isSameAttributeName(attr.getName(), VERSION)) { this.setVersion(attr.getValue()); - else if (ctx.isSameAttributeName(attr.getName(), UPDATE_SEQUENCE)) + } else if (ctx.isSameAttributeName(attr.getName(), UPDATE_SEQUENCE)) { this.setUpdateSequence(attr.getValue()); + } } } - protected XMLEventParserContext getParserContext() - { + protected XMLEventParserContext getParserContext() { return this.parserContext; } @@ -196,18 +185,15 @@ protected XMLEventParserContext getParserContext() * * @return the document's service information. */ - public OGCServiceInformation getServiceInformation() - { + public OGCServiceInformation getServiceInformation() { return serviceInformation; } - protected void setServiceInformation(OGCServiceInformation serviceInformation) - { + protected void setServiceInformation(OGCServiceInformation serviceInformation) { this.serviceInformation = serviceInformation; } - protected void setCapabilityInformation(OGCCapabilityInformation capabilityInformation) - { + protected void setCapabilityInformation(OGCCapabilityInformation capabilityInformation) { this.capabilityInformation = capabilityInformation; } @@ -216,8 +202,7 @@ protected void setCapabilityInformation(OGCCapabilityInformation capabilityInfor * * @return the document's capability information. */ - public OGCCapabilityInformation getCapabilityInformation() - { + public OGCCapabilityInformation getCapabilityInformation() { return capabilityInformation; } @@ -226,13 +211,11 @@ public OGCCapabilityInformation getCapabilityInformation() * * @return the document's version number. */ - public String getVersion() - { + public String getVersion() { return version; } - protected void setVersion(String version) - { + protected void setVersion(String version) { this.version = version; } @@ -241,30 +224,27 @@ protected void setVersion(String version) * * @return the document's update sequence. */ - public String getUpdateSequence() - { + public String getUpdateSequence() { return updateSequence; } - protected void setUpdateSequence(String updateSequence) - { + protected void setUpdateSequence(String updateSequence) { this.updateSequence = updateSequence; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Version: "). - append(this.getVersion() != null ? this.getVersion() : "none").append("\n"); + append(this.getVersion() != null ? this.getVersion() : "none").append("\n"); sb.append("UpdateSequence: "). - append(this.getUpdateSequence() != null ? this.getUpdateSequence() : "none"); + append(this.getUpdateSequence() != null ? this.getUpdateSequence() : "none"); sb.append("\n"); sb.append(this.getServiceInformation() != null ? this.getServiceInformation() : "Service Information: none"); sb.append("\n"); sb.append(this.getCapabilityInformation() != null - ? this.getCapabilityInformation() : "Capability Information: none"); + ? this.getCapabilityInformation() : "Capability Information: none"); sb.append("\n"); return sb.toString(); diff --git a/src/gov/nasa/worldwind/ogc/OGCCapabilityInformation.java b/src/gov/nasa/worldwind/ogc/OGCCapabilityInformation.java index babf4f5053..ab5a6f5360 100644 --- a/src/gov/nasa/worldwind/ogc/OGCCapabilityInformation.java +++ b/src/gov/nasa/worldwind/ogc/OGCCapabilityInformation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.xml.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: OGCCapabilityInformation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -abstract public class OGCCapabilityInformation extends AbstractXMLEventParser -{ +abstract public class OGCCapabilityInformation extends AbstractXMLEventParser { + abstract protected boolean isRequestName(XMLEventParserContext ctx, QName name); protected QName REQUEST; @@ -33,15 +32,13 @@ abstract public class OGCCapabilityInformation extends AbstractXMLEventParser protected Set requestDescriptions = new HashSet(); protected Map userDefinedSymbolization; - public OGCCapabilityInformation(String namespaceURI) - { + public OGCCapabilityInformation(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { REQUEST = new QName(this.getNamespaceURI(), "Request"); EXCEPTION = new QName(this.getNamespaceURI(), "Exception"); FORMAT = new QName(this.getNamespaceURI(), "Format"); @@ -50,146 +47,127 @@ private void initialize() } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; - if (this.isRequestName(ctx, event.asStartElement().getName())) + if (this.isRequestName(ctx, event.asStartElement().getName())) { defaultParser = new OGCRequestDescription(this.getNamespaceURI()); - else if (ctx.isStartElement(event, EXCEPTION)) + } else if (ctx.isStartElement(event, EXCEPTION)) { defaultParser = new StringSetXMLEventParser(this.getNamespaceURI(), FORMAT); + } return ctx.allocate(event, defaultParser); } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, EXCEPTION)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, EXCEPTION)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof StringSetXMLEventParser) + if (o != null && o instanceof StringSetXMLEventParser) { this.setExceptionFormats(((StringSetXMLEventParser) o).getStrings()); + } } - } - else if (event.isStartElement() && this.isRequestName(ctx, event.asStartElement().getName())) - { + } else if (event.isStartElement() && this.isRequestName(ctx, event.asStartElement().getName())) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCRequestDescription) + if (o != null && o instanceof OGCRequestDescription) { this.requestDescriptions.add((OGCRequestDescription) o); + } } - } - else if (ctx.isStartElement(event, USER_DEFINED_SYMBOLIZATION)) - { + } else if (ctx.isStartElement(event, USER_DEFINED_SYMBOLIZATION)) { // Break out the parsing so that it can be overridden by subclasses. this.parseUserDefinedSymbolization(event); - } - else if (ctx.isStartElement(event, EXTENDED_CAPABILITIES)) - { + } else if (ctx.isStartElement(event, EXTENDED_CAPABILITIES)) { // Break out the parsing so that it can be overridden by subclasses. this.parseExtendedCapabilities(ctx, event, args); } } protected void parseExtendedCapabilities(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { + throws XMLStreamException { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null) + if (o != null) { this.setExtendedCapabilities(o); + } } } - @SuppressWarnings( {"UnusedDeclaration"}) - protected void setExtendedCapabilities(Object extendedCapabilities) - { + @SuppressWarnings({"UnusedDeclaration"}) + protected void setExtendedCapabilities(Object extendedCapabilities) { // Override in subclass to handle extended capabilities. } - protected void parseUserDefinedSymbolization(XMLEvent event) throws XMLStreamException - { + protected void parseUserDefinedSymbolization(XMLEvent event) throws XMLStreamException { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); this.addUserDefinedSymbolization(attr.getName().getLocalPart(), attr.getValue()); } } - public Set getExceptionFormats() - { - if (this.exceptionFormats != null) + public Set getExceptionFormats() { + if (this.exceptionFormats != null) { return exceptionFormats; - else + } else { return Collections.emptySet(); + } } - protected void setExceptionFormats(Set exceptionFormats) - { + protected void setExceptionFormats(Set exceptionFormats) { this.exceptionFormats = exceptionFormats; } - public Set getRequestDescriptions() - { + public Set getRequestDescriptions() { return requestDescriptions; } - protected void setRequestDescriptions(Set requestDescriptions) - { + protected void setRequestDescriptions(Set requestDescriptions) { this.requestDescriptions = requestDescriptions; } - public Map getUserDefinedSymbolization() - { - if (this.userDefinedSymbolization != null) + public Map getUserDefinedSymbolization() { + if (this.userDefinedSymbolization != null) { return userDefinedSymbolization; - else + } else { return Collections.emptyMap(); + } } - protected void setUserDefinedSymbolization(Map userDefinedSymbolization) - { + protected void setUserDefinedSymbolization(Map userDefinedSymbolization) { this.userDefinedSymbolization = userDefinedSymbolization; } - protected void addUserDefinedSymbolization(String key, String value) - { - if (this.userDefinedSymbolization == null) + protected void addUserDefinedSymbolization(String key, String value) { + if (this.userDefinedSymbolization == null) { this.userDefinedSymbolization = new HashMap(); + } this.userDefinedSymbolization.put(key, value); } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - for (String ef : this.getExceptionFormats()) - { + for (String ef : this.getExceptionFormats()) { sb.append("Exception format: ").append(ef).append("\n"); } - for (OGCRequestDescription rd : this.getRequestDescriptions()) - { + for (OGCRequestDescription rd : this.getRequestDescriptions()) { sb.append(rd); } - for (Map.Entry uds : this.getUserDefinedSymbolization().entrySet()) - { + for (Map.Entry uds : this.getUserDefinedSymbolization().entrySet()) { sb.append(uds.getKey()).append("=").append(uds.getValue()).append("\n"); } diff --git a/src/gov/nasa/worldwind/ogc/OGCConstants.java b/src/gov/nasa/worldwind/ogc/OGCConstants.java index 5d1ec91472..1b3dd7bd0c 100644 --- a/src/gov/nasa/worldwind/ogc/OGCConstants.java +++ b/src/gov/nasa/worldwind/ogc/OGCConstants.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; /** @@ -12,8 +11,8 @@ * @author tag * @version $Id: OGCConstants.java 2057 2014-06-14 01:13:52Z tgaskins $ */ -public interface OGCConstants -{ +public interface OGCConstants { + /** * The name of the OGC Web Service GetCapabilities operation. The GetCapabilities * operation returns metadata about the operations and data provided by an OGC Web Service. @@ -47,4 +46,4 @@ public interface OGCConstants public static final String WMS_NAMESPACE_URI = "http://www.opengis.net/wms"; public static final String WCS_1_0_0_NAMESPACE_URI = "http://www.opengis.net/wcs"; public static final String WCS_1_1_1_NAMESPACE_URI = "http://www.opengis.net/wcs/1.1.1"; -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/ogc/OGCContactInformation.java b/src/gov/nasa/worldwind/ogc/OGCContactInformation.java index d4e358c978..e7be8da0be 100644 --- a/src/gov/nasa/worldwind/ogc/OGCContactInformation.java +++ b/src/gov/nasa/worldwind/ogc/OGCContactInformation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.xml.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: OGCContactInformation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGCContactInformation extends AbstractXMLEventParser -{ +public class OGCContactInformation extends AbstractXMLEventParser { + protected QName CONTACT_POSITION; protected QName CONTACT_VOICE_TELEPHONE; protected QName CONTACT_FACSIMILE_TELEPHONE; @@ -37,15 +36,13 @@ public class OGCContactInformation extends AbstractXMLEventParser protected String electronicMailAddress; protected OGCAddress contactAddress; - public OGCContactInformation(String namespaceURI) - { + public OGCContactInformation(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { CONTACT_POSITION = new QName(this.getNamespaceURI(), "ContactPosition"); CONTACT_VOICE_TELEPHONE = new QName(this.getNamespaceURI(), "ContactVoiceTelephone"); CONTACT_FACSIMILE_TELEPHONE = new QName(this.getNamespaceURI(), "ContactFacsimileTelephone"); @@ -57,69 +54,53 @@ private void initialize() } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; - if (ctx.isStartElement(event, CONTACT_ADDRESS)) + if (ctx.isStartElement(event, CONTACT_ADDRESS)) { defaultParser = new OGCAddress(this.getNamespaceURI()); + } return ctx.allocate(event, defaultParser); } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, CONTACT_POSITION)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, CONTACT_POSITION)) { this.setPosition(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, CONTACT_VOICE_TELEPHONE)) - { + } else if (ctx.isStartElement(event, CONTACT_VOICE_TELEPHONE)) { this.setVoiceTelephone(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, CONTACT_FACSIMILE_TELEPHONE)) - { + } else if (ctx.isStartElement(event, CONTACT_FACSIMILE_TELEPHONE)) { this.setFacsimileTelephone(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, CONTACT_ELECTRONIC_MAIL_ADDRESS)) - { + } else if (ctx.isStartElement(event, CONTACT_ELECTRONIC_MAIL_ADDRESS)) { this.setElectronicMailAddress(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, CONTACT_PERSON_PRIMARY)) - { + } else if (ctx.isStartElement(event, CONTACT_PERSON_PRIMARY)) { String[] sa = this.parseContactPersonPrimary(ctx, event); this.setPersonPrimary(sa[0]); this.setOrganization(sa[1]); - } - else if (ctx.isStartElement(event, CONTACT_ADDRESS)) - { + } else if (ctx.isStartElement(event, CONTACT_ADDRESS)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCAddress) + if (o != null && o instanceof OGCAddress) { this.setContactAddress((OGCAddress) o); + } } } } - protected String[] parseContactPersonPrimary(XMLEventParserContext ctx, XMLEvent cppEvent) throws XMLStreamException - { + protected String[] parseContactPersonPrimary(XMLEventParserContext ctx, XMLEvent cppEvent) throws XMLStreamException { String[] items = new String[2]; - for (XMLEvent event = ctx.nextEvent(); event != null; event = ctx.nextEvent()) - { - if (ctx.isEndElement(event, cppEvent)) + for (XMLEvent event = ctx.nextEvent(); event != null; event = ctx.nextEvent()) { + if (ctx.isEndElement(event, cppEvent)) { return items; + } - if (ctx.isStartElement(event, CONTACT_PERSON)) - { + if (ctx.isStartElement(event, CONTACT_PERSON)) { items[0] = ctx.getStringParser().parseString(ctx, event); - } - else if (ctx.isStartElement(event, CONTACT_ORGANIZATION)) - { + } else if (ctx.isStartElement(event, CONTACT_ORGANIZATION)) { items[1] = ctx.getStringParser().parseString(ctx, event); } } @@ -127,79 +108,64 @@ else if (ctx.isStartElement(event, CONTACT_ORGANIZATION)) return null; } - public String getPersonPrimary() - { + public String getPersonPrimary() { return personPrimary; } - protected void setPersonPrimary(String personPrimary) - { + protected void setPersonPrimary(String personPrimary) { this.personPrimary = personPrimary; } - public String getOrganization() - { + public String getOrganization() { return organization; } - protected void setOrganization(String organization) - { + protected void setOrganization(String organization) { this.organization = organization; } - public String getPosition() - { + public String getPosition() { return position; } - protected void setPosition(String position) - { + protected void setPosition(String position) { this.position = position; } - public String getVoiceTelephone() - { + public String getVoiceTelephone() { return voiceTelephone; } - protected void setVoiceTelephone(String voiceTelephone) - { + protected void setVoiceTelephone(String voiceTelephone) { this.voiceTelephone = voiceTelephone; } - public String getFacsimileTelephone() - { + public String getFacsimileTelephone() { return facsimileTelephone; } - protected void setFacsimileTelephone(String facsimileTelephone) - { + protected void setFacsimileTelephone(String facsimileTelephone) { this.facsimileTelephone = facsimileTelephone; } - public String getElectronicMailAddress() - { + public String getElectronicMailAddress() { return electronicMailAddress; } - protected void setElectronicMailAddress(String electronicMailAddress) - { + protected void setElectronicMailAddress(String electronicMailAddress) { this.electronicMailAddress = electronicMailAddress; } - public OGCAddress getContactAddress() - { + public OGCAddress getContactAddress() { return contactAddress; } - protected void setContactAddress(OGCAddress contactAddress) - { + protected void setContactAddress(OGCAddress contactAddress) { this.contactAddress = contactAddress; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("PersonPrimary: ").append(this.personPrimary != null ? this.personPrimary : "none").append("\n"); @@ -207,9 +173,9 @@ public String toString() sb.append("Position: ").append(this.position != null ? this.position : "none").append("\n"); sb.append("VoiceTelephone: ").append(this.voiceTelephone != null ? this.voiceTelephone : "none").append("\n"); sb.append("FacsimileTelephone: ").append( - this.facsimileTelephone != null ? this.facsimileTelephone : "none").append("\n"); + this.facsimileTelephone != null ? this.facsimileTelephone : "none").append("\n"); sb.append("ElectronicMailAddress: ").append( - this.electronicMailAddress != null ? this.electronicMailAddress : "none").append("\n"); + this.electronicMailAddress != null ? this.electronicMailAddress : "none").append("\n"); sb.append(this.contactAddress != null ? this.contactAddress : "none"); return sb.toString(); diff --git a/src/gov/nasa/worldwind/ogc/OGCDCType.java b/src/gov/nasa/worldwind/ogc/OGCDCType.java index 02465b44f6..4ce7062298 100644 --- a/src/gov/nasa/worldwind/ogc/OGCDCType.java +++ b/src/gov/nasa/worldwind/ogc/OGCDCType.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.xml.*; @@ -19,47 +18,44 @@ * @author tag * @version $Id: OGCDCType.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGCDCType extends AbstractXMLEventParser -{ +public class OGCDCType extends AbstractXMLEventParser { + protected QName GET; protected QName POST; protected QName HTTP; protected QName ONLINE_RESOURCE; - public static class DCPInfo - { + public static class DCPInfo { + protected String protocol; protected String method; protected OGCOnlineResource onlineResource; - public DCPInfo(String protocol) - { + public DCPInfo(String protocol) { this.protocol = protocol; } } protected List protocols = new ArrayList(1); - public OGCDCType(String namespaceURI) - { + public OGCDCType(String namespaceURI) { super(namespaceURI); this.initialize(); } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; - if (ctx.isStartElement(event, ONLINE_RESOURCE)) + if (ctx.isStartElement(event, ONLINE_RESOURCE)) { defaultParser = new OGCOnlineResource(this.getNamespaceURI()); + } return ctx.allocate(event, defaultParser); } - private void initialize() - { + private void initialize() { GET = new QName(this.getNamespaceURI(), "Get"); POST = new QName(this.getNamespaceURI(), "Post"); HTTP = new QName(this.getNamespaceURI(), "HTTP"); @@ -68,44 +64,34 @@ private void initialize() @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, HTTP)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, HTTP)) { this.addProtocol(event.asStartElement().getName().getLocalPart()); - } - else if (ctx.isStartElement(event, GET) || ctx.isStartElement(event, POST)) - { + } else if (ctx.isStartElement(event, GET) || ctx.isStartElement(event, POST)) { this.addRequestMethod(event.asStartElement().getName().getLocalPart()); - } - else if (ctx.isStartElement(event, ONLINE_RESOURCE)) - { + } else if (ctx.isStartElement(event, ONLINE_RESOURCE)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCOnlineResource) + if (o != null && o instanceof OGCOnlineResource) { this.addOnlineResource((OGCOnlineResource) o); + } } } } - public List getDCPInfos() - { + public List getDCPInfos() { return this.protocols; } - protected void addProtocol(String protocol) - { + protected void addProtocol(String protocol) { this.protocols.add(new DCPInfo(protocol)); } - protected void addRequestMethod(String requestMethod) - { + protected void addRequestMethod(String requestMethod) { DCPInfo dcpi = this.protocols.get(this.protocols.size() - 1); - if (dcpi.method != null) - { + if (dcpi.method != null) { dcpi = new DCPInfo(dcpi.protocol); this.protocols.add(dcpi); } @@ -113,34 +99,31 @@ protected void addRequestMethod(String requestMethod) dcpi.method = requestMethod; } - protected void addOnlineResource(OGCOnlineResource onlineResource) - { + protected void addOnlineResource(OGCOnlineResource onlineResource) { DCPInfo dcpi = this.protocols.get(this.protocols.size() - 1); dcpi.onlineResource = onlineResource; } - public OGCOnlineResource getOnlineResouce(String protocol, String requestMethod) - { - for (DCPInfo dcpi : this.getDCPInfos()) - { - if (!dcpi.protocol.equalsIgnoreCase(protocol)) + public OGCOnlineResource getOnlineResouce(String protocol, String requestMethod) { + for (DCPInfo dcpi : this.getDCPInfos()) { + if (!dcpi.protocol.equalsIgnoreCase(protocol)) { continue; + } - if (dcpi.method.equalsIgnoreCase(requestMethod)) + if (dcpi.method.equalsIgnoreCase(requestMethod)) { return dcpi.onlineResource; + } } return null; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - for (DCPInfo dcpi : this.getDCPInfos()) - { + for (DCPInfo dcpi : this.getDCPInfos()) { sb.append(dcpi.protocol).append(", "); sb.append(dcpi.method).append(", "); sb.append(dcpi.onlineResource.toString()); diff --git a/src/gov/nasa/worldwind/ogc/OGCOnlineResource.java b/src/gov/nasa/worldwind/ogc/OGCOnlineResource.java index 6d56734567..620528d9fe 100644 --- a/src/gov/nasa/worldwind/ogc/OGCOnlineResource.java +++ b/src/gov/nasa/worldwind/ogc/OGCOnlineResource.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.WWXML; @@ -19,67 +18,60 @@ * @author tag * @version $Id: OGCOnlineResource.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGCOnlineResource extends AbstractXMLEventParser -{ +public class OGCOnlineResource extends AbstractXMLEventParser { + protected QName HREF; protected QName TYPE; protected String type; protected String href; - public OGCOnlineResource(String namespaceURI) - { + public OGCOnlineResource(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { HREF = new QName(WWXML.XLINK_URI, "href"); TYPE = new QName(WWXML.XLINK_URI, "type"); } @Override - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (ctx.isSameAttributeName(attr.getName(), HREF)) + if (ctx.isSameAttributeName(attr.getName(), HREF)) { this.setHref(attr.getValue()); - else if (ctx.isSameAttributeName(attr.getName(), TYPE)) + } else if (ctx.isSameAttributeName(attr.getName(), TYPE)) { this.setType(attr.getValue()); + } } } - public String getType() - { + public String getType() { return type; } - protected void setType(String type) - { + protected void setType(String type) { this.type = type; } - public String getHref() - { + public String getHref() { return href; } - protected void setHref(String href) - { + protected void setHref(String href) { this.href = href; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("href: ").append(this.href != null ? this.href : "null"); diff --git a/src/gov/nasa/worldwind/ogc/OGCRequestDescription.java b/src/gov/nasa/worldwind/ogc/OGCRequestDescription.java index 4938eded84..f1ed67e451 100644 --- a/src/gov/nasa/worldwind/ogc/OGCRequestDescription.java +++ b/src/gov/nasa/worldwind/ogc/OGCRequestDescription.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.WWUtil; @@ -20,8 +19,8 @@ * @author tag * @version $Id: OGCRequestDescription.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGCRequestDescription extends AbstractXMLEventParser -{ +public class OGCRequestDescription extends AbstractXMLEventParser { + protected QName FORMAT; protected QName DCPTYPE; @@ -29,146 +28,136 @@ public class OGCRequestDescription extends AbstractXMLEventParser protected Set formats; protected Set dcpTypes; - public OGCRequestDescription(String namespaceURI) - { + public OGCRequestDescription(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { FORMAT = new QName(this.getNamespaceURI(), "Format"); DCPTYPE = new QName(this.getNamespaceURI(), "DCPType"); } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; - if (ctx.isStartElement(event, DCPTYPE)) + if (ctx.isStartElement(event, DCPTYPE)) { defaultParser = new OGCDCType(this.getNamespaceURI()); + } return ctx.allocate(event, defaultParser); } - public Object parse(XMLEventParserContext ctx, XMLEvent rqstEvent, Object... args) throws XMLStreamException - { - if (this.formats != null) + public Object parse(XMLEventParserContext ctx, XMLEvent rqstEvent, Object... args) throws XMLStreamException { + if (this.formats != null) { this.formats.clear(); - if (this.dcpTypes != null) + } + if (this.dcpTypes != null) { this.dcpTypes.clear(); + } - if (rqstEvent.isStartElement()) + if (rqstEvent.isStartElement()) { this.setRequestName(rqstEvent.asStartElement().getName().getLocalPart()); + } return super.parse(ctx, rqstEvent, args); } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, FORMAT)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, FORMAT)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.addFormat(s); - } - else if (ctx.isStartElement(event, DCPTYPE)) - { + } + } else if (ctx.isStartElement(event, DCPTYPE)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCDCType) + if (o != null && o instanceof OGCDCType) { this.addDCPType((OGCDCType) o); + } } } } - public OGCOnlineResource getOnlineResouce(String protocol, String requestMethod) - { - for (OGCDCType dct : this.getDCPTypes()) - { + public OGCOnlineResource getOnlineResouce(String protocol, String requestMethod) { + for (OGCDCType dct : this.getDCPTypes()) { OGCOnlineResource olr = dct.getOnlineResouce(protocol, requestMethod); - if (olr != null) + if (olr != null) { return olr; + } } return null; } - public Set getFormats() - { - if (this.formats != null) + public Set getFormats() { + if (this.formats != null) { return formats; - else + } else { return Collections.emptySet(); + } } - protected void setFormats(Set formats) - { + protected void setFormats(Set formats) { this.formats = formats; } - protected void addFormat(String format) - { - if (this.formats == null) + protected void addFormat(String format) { + if (this.formats == null) { this.formats = new HashSet(); + } this.formats.add(format); } - protected void setDCPTypes(Set dcTypes) - { + protected void setDCPTypes(Set dcTypes) { this.dcpTypes = dcTypes; } - public Set getDCPTypes() - { - if (this.dcpTypes != null) + public Set getDCPTypes() { + if (this.dcpTypes != null) { return dcpTypes; - else + } else { return Collections.emptySet(); + } } - public void addDCPType(OGCDCType dct) - { - if (this.dcpTypes == null) + public void addDCPType(OGCDCType dct) { + if (this.dcpTypes == null) { this.dcpTypes = new HashSet(); + } this.dcpTypes.add(dct); } - public String getRequestName() - { + public String getRequestName() { return requestName; } - protected void setRequestName(String requestName) - { + protected void setRequestName(String requestName) { this.requestName = requestName; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - if (this.getRequestName() != null) + if (this.getRequestName() != null) { sb.append(this.getRequestName()).append("\n"); + } sb.append("\tFormats: "); - for (String format : this.getFormats()) - { + for (String format : this.getFormats()) { sb.append("\t").append(format).append(", "); } sb.append("\n\tDCPTypes:\n"); - for (OGCDCType dcpt : this.getDCPTypes()) - { + for (OGCDCType dcpt : this.getDCPTypes()) { sb.append("\t\t").append(dcpt.toString()).append("\n"); } diff --git a/src/gov/nasa/worldwind/ogc/OGCServiceInformation.java b/src/gov/nasa/worldwind/ogc/OGCServiceInformation.java index ce892ffefe..cd6790c8fe 100644 --- a/src/gov/nasa/worldwind/ogc/OGCServiceInformation.java +++ b/src/gov/nasa/worldwind/ogc/OGCServiceInformation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc; import gov.nasa.worldwind.util.xml.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: OGCServiceInformation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGCServiceInformation extends AbstractXMLEventParser -{ +public class OGCServiceInformation extends AbstractXMLEventParser { + protected QName NAME; protected QName TITLE; protected QName ABSTRACT; @@ -40,15 +39,13 @@ public class OGCServiceInformation extends AbstractXMLEventParser protected OGCOnlineResource onlineResource; protected OGCContactInformation contactInformation; - public OGCServiceInformation(String namespaceURI) - { + public OGCServiceInformation(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { NAME = new QName(this.getNamespaceURI(), "Name"); TITLE = new QName(this.getNamespaceURI(), "Title"); ABSTRACT = new QName(this.getNamespaceURI(), "Abstract"); @@ -61,171 +58,139 @@ private void initialize() } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; - if (ctx.isStartElement(event, ONLINE_RESOURCE)) + if (ctx.isStartElement(event, ONLINE_RESOURCE)) { defaultParser = new OGCOnlineResource(this.getNamespaceURI()); - else if (ctx.isStartElement(event, CONTACT_INFORMATION)) + } else if (ctx.isStartElement(event, CONTACT_INFORMATION)) { defaultParser = new OGCContactInformation(this.getNamespaceURI()); - else if (ctx.isStartElement(event, KEYWORD_LIST)) + } else if (ctx.isStartElement(event, KEYWORD_LIST)) { defaultParser = new StringSetXMLEventParser(this.getNamespaceURI(), KEYWORD); + } return ctx.allocate(event, defaultParser); } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, NAME)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, NAME)) { this.setServiceName(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, TITLE)) - { + } else if (ctx.isStartElement(event, TITLE)) { this.setServiceTitle(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, ABSTRACT)) - { + } else if (ctx.isStartElement(event, ABSTRACT)) { this.setServiceAbstract(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, FEES)) - { + } else if (ctx.isStartElement(event, FEES)) { this.setFees(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, ACCESS_CONSTRAINTS)) - { + } else if (ctx.isStartElement(event, ACCESS_CONSTRAINTS)) { this.setAccessConstraints(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, KEYWORD_LIST)) - { + } else if (ctx.isStartElement(event, KEYWORD_LIST)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof StringSetXMLEventParser) + if (o != null && o instanceof StringSetXMLEventParser) { this.setKeywords(((StringSetXMLEventParser) o).getStrings()); + } } - } - else if (ctx.isStartElement(event, ONLINE_RESOURCE)) - { + } else if (ctx.isStartElement(event, ONLINE_RESOURCE)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCOnlineResource) + if (o != null && o instanceof OGCOnlineResource) { this.setOnlineResource((OGCOnlineResource) o); + } } - } - else if (ctx.isStartElement(event, CONTACT_INFORMATION)) - { + } else if (ctx.isStartElement(event, CONTACT_INFORMATION)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCContactInformation) + if (o != null && o instanceof OGCContactInformation) { this.setContactInformation((OGCContactInformation) o); + } } } } - public OGCContactInformation getContactInformation() - { + public OGCContactInformation getContactInformation() { return contactInformation; } - protected void setContactInformation(OGCContactInformation contactInformation) - { + protected void setContactInformation(OGCContactInformation contactInformation) { this.contactInformation = contactInformation; } - public OGCOnlineResource getOnlineResource() - { + public OGCOnlineResource getOnlineResource() { return onlineResource; } - protected void setOnlineResource(OGCOnlineResource onlineResource) - { + protected void setOnlineResource(OGCOnlineResource onlineResource) { this.onlineResource = onlineResource; } - public Set getKeywords() - { - if (keywords != null) + public Set getKeywords() { + if (keywords != null) { return keywords; - else + } else { return Collections.emptySet(); + } } - protected void setKeywords(Set keywords) - { + protected void setKeywords(Set keywords) { this.keywords = keywords; } - public String getAccessConstraints() - { + public String getAccessConstraints() { return accessConstraints; } - protected void setAccessConstraints(String accessConstraints) - { + protected void setAccessConstraints(String accessConstraints) { this.accessConstraints = accessConstraints; } - public String getFees() - { + public String getFees() { return fees; } - protected void setFees(String fees) - { + protected void setFees(String fees) { this.fees = fees; } - public String getServiceAbstract() - { + public String getServiceAbstract() { return serviceAbstract; } - protected void setServiceAbstract(String serviceAbstract) - { + protected void setServiceAbstract(String serviceAbstract) { this.serviceAbstract = serviceAbstract; } - public String getServiceTitle() - { + public String getServiceTitle() { return serviceTitle; } - protected void setServiceTitle(String serviceTitle) - { + protected void setServiceTitle(String serviceTitle) { this.serviceTitle = serviceTitle; } - public String getServiceName() - { + public String getServiceName() { return serviceName; } - protected void setServiceName(String serviceName) - { + protected void setServiceName(String serviceName) { this.serviceName = serviceName; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ServiceName: ").append(this.serviceName != null ? this.serviceName : "none").append("\n"); sb.append("ServiceTitle: ").append(this.serviceTitle != null ? this.serviceTitle : "none").append("\n"); sb.append("ServiceAbstract: ").append(this.serviceAbstract != null ? this.serviceAbstract : "none").append( - "\n"); + "\n"); sb.append("Fees: ").append(this.fees != null ? this.fees : "none").append("\n"); sb.append("AccessConstraints: ").append( - this.accessConstraints != null ? this.accessConstraints : "none").append("\n"); + this.accessConstraints != null ? this.accessConstraints : "none").append("\n"); this.keywordsToString(sb); sb.append("OnlineResource: ").append(this.onlineResource != null ? this.onlineResource : "none").append("\n"); sb.append(this.contactInformation != null ? this.contactInformation : "none").append("\n"); @@ -233,15 +198,12 @@ public String toString() return sb.toString(); } - protected void keywordsToString(StringBuilder sb) - { + protected void keywordsToString(StringBuilder sb) { sb.append("Keywords: "); - if (this.getKeywords().size() == 0) + if (this.getKeywords().size() == 0) { sb.append(" none"); - else - { - for (String keyword : this.getKeywords()) - { + } else { + for (String keyword : this.getKeywords()) { sb.append(keyword != null ? keyword : "null").append(", "); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractGeometry.java b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractGeometry.java index 6d17659f1c..42acca6cff 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractGeometry.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractGeometry.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.util.Logging; @@ -17,20 +16,26 @@ * @author pabercrombie * @version $Id: ColladaAbstractGeometry.java 618 2012-06-01 17:35:11Z pabercrombie $ */ -public abstract class ColladaAbstractGeometry extends ColladaAbstractObject -{ +public abstract class ColladaAbstractGeometry extends ColladaAbstractObject { + /** * Default semantic that identifies texture coordinates. Used the a file does not specify the semantic using a * bind_vertex_input element. */ public static final String DEFAULT_TEX_COORD_SEMANTIC = "TEXCOORD"; - /** Number of coordinates per vertex. */ + /** + * Number of coordinates per vertex. + */ public static final int COORDS_PER_VERTEX = 3; - /** Number of texture coordinates per vertex. */ + /** + * Number of texture coordinates per vertex. + */ public static final int TEX_COORDS_PER_VERTEX = 2; - /** Inputs for the geometry. Inputs provide the geometry with vertices, texture coordinates, etc. */ + /** + * Inputs for the geometry. Inputs provide the geometry with vertices, texture coordinates, etc. + */ protected List inputs = new ArrayList(); /** @@ -45,8 +50,7 @@ public abstract class ColladaAbstractGeometry extends ColladaAbstractObject * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaAbstractGeometry(String ns) - { + public ColladaAbstractGeometry(String ns) { super(ns); } @@ -55,8 +59,7 @@ public ColladaAbstractGeometry(String ns) * * @return Inputs to the geometry. */ - public List getInputs() - { + public List getInputs() { return this.inputs; } @@ -65,8 +68,7 @@ public List getInputs() * * @return The number of shapes in the geometry. */ - public int getCount() - { + public int getCount() { return Integer.parseInt((String) this.getField("count")); } @@ -75,8 +77,7 @@ public int getCount() * * @return The material applied to this geometry. May be null. */ - public String getMaterial() - { + public String getMaterial() { return (String) this.getField("material"); } @@ -85,8 +86,7 @@ public String getMaterial() * * @param buffer Buffer to receive coordinates. */ - public void getVertices(FloatBuffer buffer) - { + public void getVertices(FloatBuffer buffer) { this.getFloatFromAccessor(buffer, this.getVertexAccessor(), "VERTEX", COORDS_PER_VERTEX); } @@ -95,22 +95,21 @@ public void getVertices(FloatBuffer buffer) * * @param buffer Buffer to receive coordinates. */ - public void getNormals(FloatBuffer buffer) - { + public void getNormals(FloatBuffer buffer) { this.getFloatFromAccessor(buffer, this.getNormalAccessor(), "NORMAL", COORDS_PER_VERTEX); } /** * Retrieves the texture coordinates of vertices in this geometry. * - * @param buffer Buffer to receive coordinates. + * @param buffer Buffer to receive coordinates. * @param semantic String to identify which input holds the texture coordinates. May be null, in which case the - * "TEXCOORD" is used. + * "TEXCOORD" is used. */ - public void getTextureCoordinates(FloatBuffer buffer, String semantic) - { - if (semantic == null) + public void getTextureCoordinates(FloatBuffer buffer, String semantic) { + if (semantic == null) { semantic = DEFAULT_TEX_COORD_SEMANTIC; + } this.getFloatFromAccessor(buffer, this.getTexCoordAccessor(semantic), semantic, TEX_COORDS_PER_VERTEX); } @@ -118,16 +117,14 @@ public void getTextureCoordinates(FloatBuffer buffer, String semantic) /** * Retrieve numbers from an accessor. * - * @param buffer Buffer to receive floats. - * @param accessor Accessor that will provide floats. - * @param semantic Semantic that identifiers the set of indices to use (for example, "VERTEX" or "NORMAL"). + * @param buffer Buffer to receive floats. + * @param accessor Accessor that will provide floats. + * @param semantic Semantic that identifiers the set of indices to use (for example, "VERTEX" or "NORMAL"). * @param floatsPerVertex Number of floats to read for each vertex. */ protected void getFloatFromAccessor(FloatBuffer buffer, ColladaAccessor accessor, String semantic, - int floatsPerVertex) - { - if (buffer == null) - { + int floatsPerVertex) { + if (buffer == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -136,8 +133,7 @@ protected void getFloatFromAccessor(FloatBuffer buffer, ColladaAccessor accessor int vertsPerShape = this.getVerticesPerShape(); int indexCount = this.getCount() * vertsPerShape; - if (buffer.remaining() < indexCount * floatsPerVertex) - { + if (buffer.remaining() < indexCount * floatsPerVertex) { String msg = Logging.getMessage("generic.BufferSize"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -146,25 +142,22 @@ protected void getFloatFromAccessor(FloatBuffer buffer, ColladaAccessor accessor int[] indices = this.getIndices(semantic); float[] vertexCoords = accessor.getFloats(); - for (int i : indices) - { + for (int i : indices) { buffer.put(vertexCoords, i * floatsPerVertex, floatsPerVertex); } } - protected int[] getIndices(String semantic) - { + protected int[] getIndices(String semantic) { ColladaInput input = null; - for (ColladaInput in : this.getInputs()) - { - if (semantic.equals(in.getSemantic())) - { + for (ColladaInput in : this.getInputs()) { + if (semantic.equals(in.getSemantic())) { input = in; break; } } - if (input == null) + if (input == null) { return null; + } ColladaP primitives = (ColladaP) this.getField("p"); @@ -177,10 +170,8 @@ protected int[] getIndices(String semantic) int ri = 0; int sourcesStride = this.getInputs().size(); - for (int i = 0; i < this.getCount(); i++) - { - for (int j = 0; j < vertsPerShape; j++) - { + for (int i = 0; i < this.getCount(); i++) { + for (int j = 0; j < vertsPerShape; j++) { int index = i * (vertsPerShape * sourcesStride) + j * sourcesStride; result[ri++] = intData[index + offset]; } @@ -189,53 +180,48 @@ protected int[] getIndices(String semantic) return result; } - public ColladaAccessor getVertexAccessor() - { + public ColladaAccessor getVertexAccessor() { String vertexUri = null; - for (ColladaInput input : this.getInputs()) - { - if ("VERTEX".equals(input.getSemantic())) - { + for (ColladaInput input : this.getInputs()) { + if ("VERTEX".equals(input.getSemantic())) { vertexUri = input.getSource(); break; } } - if (vertexUri == null) + if (vertexUri == null) { return null; + } String positionUri = null; ColladaVertices vertices = (ColladaVertices) this.getRoot().resolveReference(vertexUri); - for (ColladaInput input : vertices.getInputs()) - { - if ("POSITION".equals(input.getSemantic())) - { + for (ColladaInput input : vertices.getInputs()) { + if ("POSITION".equals(input.getSemantic())) { positionUri = input.getSource(); break; } } - if (positionUri == null) + if (positionUri == null) { return null; + } ColladaSource source = (ColladaSource) this.getRoot().resolveReference(positionUri); return (source != null) ? source.getAccessor() : null; } - public ColladaAccessor getNormalAccessor() - { + public ColladaAccessor getNormalAccessor() { String sourceUri = null; - for (ColladaInput input : this.getInputs()) - { - if ("NORMAL".equals(input.getSemantic())) - { + for (ColladaInput input : this.getInputs()) { + if ("NORMAL".equals(input.getSemantic())) { sourceUri = input.getSource(); break; } } - if (sourceUri == null) + if (sourceUri == null) { return null; + } ColladaSource source = (ColladaSource) this.getRoot().resolveReference(sourceUri); return (source != null) ? source.getAccessor() : null; @@ -245,42 +231,39 @@ public ColladaAccessor getNormalAccessor() * Indicates the accessor for texture coordinates. * * @param semantic Semantic that identifies the texture coordinates. May be null, in which case the semantic - * "TEXCOORD" is used. + * "TEXCOORD" is used. * * @return The texture coordinates accessor, or null if the accessor cannot be resolved. */ - public ColladaAccessor getTexCoordAccessor(String semantic) - { - if (semantic == null) + public ColladaAccessor getTexCoordAccessor(String semantic) { + if (semantic == null) { semantic = DEFAULT_TEX_COORD_SEMANTIC; + } String sourceUri = null; - for (ColladaInput input : this.getInputs()) - { - if (semantic.equals(input.getSemantic())) - { + for (ColladaInput input : this.getInputs()) { + if (semantic.equals(input.getSemantic())) { sourceUri = input.getSource(); break; } } - if (sourceUri == null) + if (sourceUri == null) { return null; + } ColladaSource source = (ColladaSource) this.getRoot().resolveReference(sourceUri); return (source != null) ? source.getAccessor() : null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setField(String keyName, Object value) - { - if (keyName.equals("input")) - { + public void setField(String keyName, Object value) { + if (keyName.equals("input")) { this.inputs.add((ColladaInput) value); - } - else - { + } else { super.setField(keyName, value); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractInstance.java b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractInstance.java index 611296e15d..bd583359f2 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractInstance.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractInstance.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -13,9 +12,11 @@ * @author pabercrombie * @version $Id: ColladaAbstractInstance.java 600 2012-05-17 22:57:25Z pabercrombie $ */ -public abstract class ColladaAbstractInstance extends ColladaAbstractObject -{ - /** Resolved target of the link. */ +public abstract class ColladaAbstractInstance extends ColladaAbstractObject { + + /** + * Resolved target of the link. + */ protected T instance; /** @@ -23,8 +24,7 @@ public abstract class ColladaAbstractInstance extends ColladaAbstractObject * * @param ns Namespace. */ - public ColladaAbstractInstance(String ns) - { + public ColladaAbstractInstance(String ns) { super(ns); } @@ -33,8 +33,7 @@ public ColladaAbstractInstance(String ns) * * @return URL field. */ - public String getUrl() - { + public String getUrl() { return (String) this.getField("url"); } @@ -46,10 +45,8 @@ public String getUrl() * @return The linked resource, or null if the resource is not available. */ @SuppressWarnings("unchecked") - public T get() - { - if (this.instance == null) - { + public T get() { + if (this.instance == null) { Object o = this.getRoot().resolveReference(this.getUrl()); this.instance = (T) o; // May be null } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractObject.java b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractObject.java index 57a2e01e82..804544734d 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractObject.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractObject.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.geom.Box; @@ -17,22 +16,22 @@ * @author pabercrombie * @version $Id: ColladaAbstractObject.java 1696 2013-10-31 18:46:55Z tgaskins $ */ -public abstract class ColladaAbstractObject extends AbstractXMLEventParser -{ +public abstract class ColladaAbstractObject extends AbstractXMLEventParser { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected ColladaAbstractObject(String namespaceURI) - { + protected ColladaAbstractObject(String namespaceURI) { super(namespaceURI); } - /** {@inheritDoc} Overridden to return ColladaRoot instead of a XMLEventParser. */ + /** + * {@inheritDoc} Overridden to return ColladaRoot instead of a XMLEventParser. + */ @Override - public ColladaRoot getRoot() - { + public ColladaRoot getRoot() { XMLEventParser root = super.getRoot(); return root instanceof ColladaRoot ? (ColladaRoot) root : null; } @@ -45,10 +44,8 @@ public ColladaRoot getRoot() * * @throws IllegalArgumentException if either the traversal context is null. */ - public Box getLocalExtent(ColladaTraversalContext tc) - { - if (tc == null) - { + public Box getLocalExtent(ColladaTraversalContext tc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractParamContainer.java b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractParamContainer.java index 34b5fbf627..03ffb27abf 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractParamContainer.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractParamContainer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import java.util.*; @@ -14,9 +13,11 @@ * @author pabercrombie * @version $Id: ColladaAbstractParamContainer.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaAbstractParamContainer extends ColladaAbstractObject -{ - /** Named newparam elements in the container. */ +public class ColladaAbstractParamContainer extends ColladaAbstractObject { + + /** + * Named newparam elements in the container. + */ protected Map newParams; /** @@ -24,8 +25,7 @@ public class ColladaAbstractParamContainer extends ColladaAbstractObject * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected ColladaAbstractParamContainer(String namespaceURI) - { + protected ColladaAbstractParamContainer(String namespaceURI) { super(namespaceURI); } @@ -36,35 +36,33 @@ protected ColladaAbstractParamContainer(String namespaceURI) * * @return The requested parameter, or null if no such parameter can be found. */ - public ColladaNewParam getParam(String sid) - { - if (this.newParams != null) + public ColladaNewParam getParam(String sid) { + if (this.newParams != null) { return this.newParams.get(sid); + } return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setField(String keyName, Object value) - { - if ("newparam".equals(keyName)) - { + public void setField(String keyName, Object value) { + if ("newparam".equals(keyName)) { ColladaNewParam param = (ColladaNewParam) value; String sid = (String) param.getField("sid"); // SID is a required attribute of newparam, so should never be null. Check for null to guard against // malformed documents, and just ignore the parameter in this these cases. - if (sid != null) - { - if (this.newParams == null) + if (sid != null) { + if (this.newParams == null) { this.newParams = new HashMap(); + } this.newParams.put(sid, param); } - } - else - { + } else { super.setField(keyName, value); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractShader.java b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractShader.java index d932335583..c106e1b6c7 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractShader.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaAbstractShader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaAbstractShader.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaAbstractShader extends ColladaAbstractObject -{ +public class ColladaAbstractShader extends ColladaAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected ColladaAbstractShader(String namespaceURI) - { + protected ColladaAbstractShader(String namespaceURI) { super(namespaceURI); } @@ -29,8 +27,7 @@ protected ColladaAbstractShader(String namespaceURI) * * @return The emission parameter, or null if none is set. */ - public ColladaTextureOrColor getEmission() - { + public ColladaTextureOrColor getEmission() { return (ColladaTextureOrColor) this.getField("emission"); } @@ -39,8 +36,7 @@ public ColladaTextureOrColor getEmission() * * @return The ambient parameter, or null if none is set. */ - public ColladaTextureOrColor getAmbient() - { + public ColladaTextureOrColor getAmbient() { return (ColladaTextureOrColor) this.getField("ambient"); } @@ -49,8 +45,7 @@ public ColladaTextureOrColor getAmbient() * * @return The diffuse parameter, or null if none is set. */ - public ColladaTextureOrColor getDiffuse() - { + public ColladaTextureOrColor getDiffuse() { return (ColladaTextureOrColor) this.getField("diffuse"); } @@ -59,8 +54,7 @@ public ColladaTextureOrColor getDiffuse() * * @return The specular parameter, or null if none is set. */ - public ColladaTextureOrColor getSpecular() - { + public ColladaTextureOrColor getSpecular() { return (ColladaTextureOrColor) this.getField("specular"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaAccessor.java b/src/gov/nasa/worldwind/ogc/collada/ColladaAccessor.java index 87a2d0cafe..c77d0d22a8 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaAccessor.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaAccessor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.util.WWUtil; @@ -19,9 +18,11 @@ * @author pabercrombie * @version $Id: ColladaAccessor.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaAccessor extends ColladaAbstractObject -{ - /** Parameters used by this accessor. */ +public class ColladaAccessor extends ColladaAbstractObject { + + /** + * Parameters used by this accessor. + */ protected List params = new ArrayList(); /** @@ -29,8 +30,7 @@ public class ColladaAccessor extends ColladaAbstractObject * * @param ns Namespace. */ - public ColladaAccessor(String ns) - { + public ColladaAccessor(String ns) { super(ns); } @@ -39,8 +39,7 @@ public ColladaAccessor(String ns) * * @return Accessor source. */ - public String getSource() - { + public String getSource() { return (String) this.getField("source"); } @@ -51,8 +50,7 @@ public String getSource() * * @return Number of elements that the accessor can read. */ - public int getCount() - { + public int getCount() { Integer count = (Integer) this.getField("count"); return count != null ? count : 0; } @@ -63,8 +61,7 @@ public int getCount() * * @return Offset at which the accessor starts reading. */ - public int getOffset() - { + public int getOffset() { Integer offset = (Integer) this.getField("offset"); return offset != null ? offset : 0; } @@ -74,8 +71,7 @@ public int getOffset() * * @return Offset at which the accessor starts reading. */ - public int getStride() - { + public int getStride() { Integer stride = (Integer) this.getField("stride"); return stride != null ? stride : 1; } @@ -86,13 +82,12 @@ public int getStride() * * @return Number of tokens that the accessor can read. */ - public int size() - { + public int size() { int count = 0; - for (ColladaParam param : this.params) - { - if (!WWUtil.isEmpty(param.getName())) + for (ColladaParam param : this.params) { + if (!WWUtil.isEmpty(param.getName())) { count += 1; + } } return count * this.getCount(); } @@ -103,46 +98,49 @@ public int size() * * @return Array of floats. May return null if the data source is not available. */ - public float[] getFloats() - { + public float[] getFloats() { String source = this.getSource(); - if (source == null) + if (source == null) { return null; + } Object o = this.getRoot().resolveReference(source); - if (o == null) + if (o == null) { return null; // Source not available - + } // TODO: COLLADA spec says source can be a non-COLLADA document (pg 5-5) - if (!(o instanceof ColladaFloatArray)) + if (!(o instanceof ColladaFloatArray)) { return null; + } float[] floats = ((ColladaFloatArray) o).getFloats(); - if (floats == null) + if (floats == null) { return null; + } // Skip values before the start offset int index = this.getOffset(); int strideSkip = 0; int stride = this.getStride(); - if (stride > this.params.size()) + if (stride > this.params.size()) { strideSkip = stride - this.params.size(); + } float[] result = new float[this.size()]; int ri = 0; - for (int i = 0; i < this.getCount() && index < floats.length; i++) - { - for (ColladaParam param : this.params) - { - if (index >= floats.length) + for (int i = 0; i < this.getCount() && index < floats.length; i++) { + for (ColladaParam param : this.params) { + if (index >= floats.length) { break; + } // Parse the next value and add to the buffer. Skip unnamed parameters. // See COLLADA spec pg 5-5. - if (!WWUtil.isEmpty(param.getName())) + if (!WWUtil.isEmpty(param.getName())) { result[ri++] = floats[index]; + } index += 1; } @@ -154,27 +152,31 @@ public float[] getFloats() return result; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setField(String keyName, Object value) - { - if (keyName.equals("param")) + public void setField(String keyName, Object value) { + if (keyName.equals("param")) { this.params.add((ColladaParam) value); - else + } else { super.setField(keyName, value); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override protected void doAddEventAttribute(Attribute attr, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { + throws XMLStreamException { String localName = attr.getName().getLocalPart(); boolean isIntField = "count".equals(localName) || "offset".equals(localName) || "stride".equals(localName); - if (isIntField) + if (isIntField) { this.setField(localName, WWUtil.makeInteger(attr.getValue())); - else + } else { super.doAddEventAttribute(attr, ctx, event, args); + } } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaAsset.java b/src/gov/nasa/worldwind/ogc/collada/ColladaAsset.java index b6a7b195a0..d3b87f8dba 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaAsset.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaAsset.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaAsset.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaAsset extends ColladaAbstractObject -{ +public class ColladaAsset extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaAsset(String ns) - { + public ColladaAsset(String ns) { super(ns); } @@ -29,8 +27,7 @@ public ColladaAsset(String ns) * * @return This Asset's unit field, or null if no unit is set. */ - public ColladaUnit getUnit() - { + public ColladaUnit getUnit() { return (ColladaUnit) this.getField("unit"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaBind.java b/src/gov/nasa/worldwind/ogc/collada/ColladaBind.java index 5a84c7e6af..5d7a0fed0a 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaBind.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaBind.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaBind.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaBind extends ColladaAbstractObject -{ +public class ColladaBind extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaBind(String ns) - { + public ColladaBind(String ns) { super(ns); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaBindMaterial.java b/src/gov/nasa/worldwind/ogc/collada/ColladaBindMaterial.java index 9208a144db..7448a7045b 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaBindMaterial.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaBindMaterial.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaBindMaterial.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaBindMaterial extends ColladaAbstractObject -{ +public class ColladaBindMaterial extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaBindMaterial(String ns) - { + public ColladaBindMaterial(String ns) { super(ns); } @@ -29,8 +27,7 @@ public ColladaBindMaterial(String ns) * * @return Technique common element, or null if none is set. */ - public ColladaTechniqueCommon getTechniqueCommon() - { + public ColladaTechniqueCommon getTechniqueCommon() { return (ColladaTechniqueCommon) this.getField("technique_common"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaBindVertexInput.java b/src/gov/nasa/worldwind/ogc/collada/ColladaBindVertexInput.java index f5d5c7d594..7ca6baf84a 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaBindVertexInput.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaBindVertexInput.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,35 +11,32 @@ * @author pabercrombie * @version $Id: ColladaBindVertexInput.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaBindVertexInput extends ColladaAbstractObject -{ +public class ColladaBindVertexInput extends ColladaAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaBindVertexInput(String namespaceURI) - { + public ColladaBindVertexInput(String namespaceURI) { super(namespaceURI); } /** * Indicates the value of the semantic field. * - * @return The value of the semantic field, or null if the field is not set. + * @return The value of the semantic field, or null if the field is not set. */ - public String getSemantic() - { + public String getSemantic() { return (String) this.getField("semantic"); } /** * Indicates the value of the input_semantic field. * - * @return The value of the input_semantic field, or null if the field is not set. + * @return The value of the input_semantic field, or null if the field is not set. */ - public String getInputSemantic() - { + public String getInputSemantic() { return (String) this.getField("input_semantic"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaColor.java b/src/gov/nasa/worldwind/ogc/collada/ColladaColor.java index 710d466557..2d333fd8ed 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaColor.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaColor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaColor.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaColor extends ColladaAbstractObject -{ +public class ColladaColor extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaColor(String ns) - { + public ColladaColor(String ns) { super(ns); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaConstants.java b/src/gov/nasa/worldwind/ogc/collada/ColladaConstants.java index bb69ba01d8..d9aceabc1e 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaConstants.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaConstants.java @@ -3,14 +3,19 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; -/** Constants related to COLLADA documents. */ -public interface ColladaConstants -{ - /** The Collada namespace URI. */ +/** + * Constants related to COLLADA documents. + */ +public interface ColladaConstants { + + /** + * The Collada namespace URI. + */ final String COLLADA_NAMESPACE = "http://www.collada.org/2005/11/COLLADASchema"; - /** MIME type for Collada documents. */ + /** + * MIME type for Collada documents. + */ final String COLLADA_MIME_TYPE = "model/collada+xml"; } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaContributor.java b/src/gov/nasa/worldwind/ogc/collada/ColladaContributor.java index 7538b248fe..edf01443d5 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaContributor.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaContributor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaContributor.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaContributor extends ColladaAbstractObject -{ +public class ColladaContributor extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaContributor(String ns) - { + public ColladaContributor(String ns) { super(ns); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaEffect.java b/src/gov/nasa/worldwind/ogc/collada/ColladaEffect.java index 8555a7f505..2c88ad4f9a 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaEffect.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaEffect.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.render.Material; @@ -16,15 +15,14 @@ * @author pabercrombie * @version $Id: ColladaEffect.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaEffect extends ColladaAbstractParamContainer -{ +public class ColladaEffect extends ColladaAbstractParamContainer { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaEffect(String ns) - { + public ColladaEffect(String ns) { super(ns); } @@ -33,8 +31,7 @@ public ColladaEffect(String ns) * * @return The value of the profile_COMMON field, or null if the field is not set. */ - public ColladaProfileCommon getProfileCommon() - { + public ColladaProfileCommon getProfileCommon() { return (ColladaProfileCommon) this.getField("profile_COMMON"); } @@ -44,23 +41,26 @@ public ColladaProfileCommon getProfileCommon() * * @return The texture specified by this effect, or null if the texture cannot be resolved. */ - public ColladaTexture getTexture() - { + public ColladaTexture getTexture() { ColladaProfileCommon profile = this.getProfileCommon(); - if (profile == null) + if (profile == null) { return null; + } ColladaTechnique technique = profile.getTechnique(); - if (technique == null) + if (technique == null) { return null; + } ColladaAbstractShader shader = technique.getShader(); - if (shader == null) + if (shader == null) { return null; + } ColladaTextureOrColor diffuse = shader.getDiffuse(); - if (diffuse == null) + if (diffuse == null) { return null; + } return diffuse.getTexture(); } @@ -71,19 +71,21 @@ public ColladaTexture getTexture() * * @return The material for this effect, or null if the material cannot be resolved. */ - public Material getMaterial() - { + public Material getMaterial() { ColladaProfileCommon profile = this.getProfileCommon(); - if (profile == null) + if (profile == null) { return null; + } ColladaTechnique technique = profile.getTechnique(); - if (technique == null) + if (technique == null) { return null; + } ColladaAbstractShader shader = technique.getShader(); - if (shader == null) + if (shader == null) { return null; + } Color emission = null; Color ambient = null; @@ -91,46 +93,57 @@ public Material getMaterial() Color specular = null; ColladaTextureOrColor textureOrColor = shader.getEmission(); - if (textureOrColor != null) + if (textureOrColor != null) { emission = textureOrColor.getColor(); + } textureOrColor = shader.getAmbient(); - if (textureOrColor != null) + if (textureOrColor != null) { ambient = textureOrColor.getColor(); + } textureOrColor = shader.getSpecular(); - if (textureOrColor != null) + if (textureOrColor != null) { specular = textureOrColor.getColor(); + } textureOrColor = shader.getDiffuse(); - if (textureOrColor != null) + if (textureOrColor != null) { diffuse = textureOrColor.getColor(); + } // TODO what should be we do with materials that don't have Diffuse? - if (diffuse == null) + if (diffuse == null) { return null; + } - if (emission == null) + if (emission == null) { emission = new Color(0, 0, 0, diffuse.getAlpha()); - if (ambient == null) + } + if (ambient == null) { ambient = diffuse; - if (specular == null) + } + if (specular == null) { specular = new Color(255, 255, 255, diffuse.getAlpha()); + } return new Material(specular, diffuse, ambient, emission, 1f); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public ColladaNewParam getParam(String sid) - { + public ColladaNewParam getParam(String sid) { ColladaNewParam param = super.getParam(sid); - if (param != null) + if (param != null) { return param; + } ColladaProfileCommon profile = this.getProfileCommon(); - if (profile == null) + if (profile == null) { return null; + } return profile.getParam(sid); } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaExtra.java b/src/gov/nasa/worldwind/ogc/collada/ColladaExtra.java index fcbcfc9eb5..2171e45ec2 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaExtra.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaExtra.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaExtra.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaExtra extends ColladaAbstractObject -{ +public class ColladaExtra extends ColladaAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaExtra(String namespaceURI) - { + public ColladaExtra(String namespaceURI) { super(namespaceURI); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaFloatArray.java b/src/gov/nasa/worldwind/ogc/collada/ColladaFloatArray.java index 0e900d1eab..975aa7f97c 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaFloatArray.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaFloatArray.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.util.WWUtil; @@ -18,9 +17,11 @@ * @author pabercrombie * @version $Id: ColladaFloatArray.java 662 2012-06-26 19:05:46Z pabercrombie $ */ -public class ColladaFloatArray extends ColladaAbstractObject -{ - /** Floats parsed from this element. */ +public class ColladaFloatArray extends ColladaAbstractObject { + + /** + * Floats parsed from this element. + */ protected float[] floats; /** @@ -28,8 +29,7 @@ public class ColladaFloatArray extends ColladaAbstractObject * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaFloatArray(String ns) - { + public ColladaFloatArray(String ns) { super(ns); } @@ -38,22 +38,22 @@ public ColladaFloatArray(String ns) * * @return Floats contained in this element. May return an empty array, but will not return null. */ - public float[] getFloats() - { + public float[] getFloats() { return (this.floats != null) ? this.floats : new float[0]; } - /** {@inheritDoc} Overridden to parse character content into a float[]. */ + /** + * {@inheritDoc} Overridden to parse character content into a float[]. + */ @Override - public Object parse(XMLEventParserContext ctx, XMLEvent event, Object... args) throws XMLStreamException - { + public Object parse(XMLEventParserContext ctx, XMLEvent event, Object... args) throws XMLStreamException { super.parse(ctx, event, args); - if (this.hasField(CHARACTERS_CONTENT)) - { + if (this.hasField(CHARACTERS_CONTENT)) { String s = (String) this.getField(CHARACTERS_CONTENT); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.floats = this.parseFloats(s); + } // Don't need to keep string version of the floats this.removeField(CHARACTERS_CONTENT); @@ -69,16 +69,15 @@ public Object parse(XMLEventParserContext ctx, XMLEvent event, Object... args) t * * @return Array of parsed floats. */ - protected float[] parseFloats(String floatArrayString) - { + protected float[] parseFloats(String floatArrayString) { String[] arrayOfNumbers = floatArrayString.split("\\s"); float[] ary = new float[arrayOfNumbers.length]; int i = 0; - for (String s : arrayOfNumbers) - { - if (!WWUtil.isEmpty(s)) + for (String s : arrayOfNumbers) { + if (!WWUtil.isEmpty(s)) { ary[i++] = Float.parseFloat(s); + } } return ary; diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaFloatOrParam.java b/src/gov/nasa/worldwind/ogc/collada/ColladaFloatOrParam.java index 95619b5691..18e21e65c7 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaFloatOrParam.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaFloatOrParam.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaFloatOrParam.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaFloatOrParam extends ColladaAbstractObject -{ +public class ColladaFloatOrParam extends ColladaAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaFloatOrParam(String namespaceURI) - { + public ColladaFloatOrParam(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaFormat.java b/src/gov/nasa/worldwind/ogc/collada/ColladaFormat.java index 489fbd8d91..4ff56067a9 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaFormat.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaFormat.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaFormat.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaFormat extends ColladaAbstractObject -{ +public class ColladaFormat extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaFormat(String ns) - { + public ColladaFormat(String ns) { super(ns); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaGeometry.java b/src/gov/nasa/worldwind/ogc/collada/ColladaGeometry.java index 24b29b13f9..3eddf766e5 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaGeometry.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaGeometry.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaGeometry.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaGeometry extends ColladaAbstractObject -{ +public class ColladaGeometry extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaGeometry(String ns) - { + public ColladaGeometry(String ns) { super(ns); } @@ -29,8 +27,7 @@ public ColladaGeometry(String ns) * * @return The mesh element, or null if none is set. */ - public ColladaMesh getMesh() - { + public ColladaMesh getMesh() { return (ColladaMesh) this.getField("mesh"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaImage.java b/src/gov/nasa/worldwind/ogc/collada/ColladaImage.java index e0cb43ded4..897c5bfd9b 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaImage.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaImage.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,13 @@ * @author pabercrombie * @version $Id: ColladaImage.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ColladaImage extends ColladaAbstractObject -{ - public ColladaImage(String ns) - { +public class ColladaImage extends ColladaAbstractObject { + + public ColladaImage(String ns) { super(ns); } - public String getInitFrom() - { + public String getInitFrom() { return (String) this.getField("init_from"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaInput.java b/src/gov/nasa/worldwind/ogc/collada/ColladaInput.java index 57dbf39715..c998ab01c5 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaInput.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaInput.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,25 +11,21 @@ * @author pabercrombie * @version $Id: ColladaInput.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaInput extends ColladaAbstractObject -{ - public ColladaInput(String ns) - { +public class ColladaInput extends ColladaAbstractObject { + + public ColladaInput(String ns) { super(ns); } - public int getOffset() - { + public int getOffset() { return Integer.parseInt((String) this.getField("offset")); } - public String getSource() - { + public String getSource() { return (String) this.getField("source"); } - public String getSemantic() - { + public String getSemantic() { return (String) this.getField("semantic"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceEffect.java b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceEffect.java index c39db075dc..fa2e2289bf 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceEffect.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceEffect.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,10 +11,9 @@ * @author pabercrombie * @version $Id: ColladaInstanceEffect.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaInstanceEffect extends ColladaAbstractInstance -{ - public ColladaInstanceEffect(String ns) - { +public class ColladaInstanceEffect extends ColladaAbstractInstance { + + public ColladaInstanceEffect(String ns) { super(ns); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceGeometry.java b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceGeometry.java index 4e0848a081..23b69c4585 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceGeometry.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceGeometry.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,13 @@ * @author pabercrombie * @version $Id: ColladaInstanceGeometry.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaInstanceGeometry extends ColladaAbstractInstance -{ - public ColladaInstanceGeometry(String ns) - { +public class ColladaInstanceGeometry extends ColladaAbstractInstance { + + public ColladaInstanceGeometry(String ns) { super(ns); } - public ColladaBindMaterial getBindMaterial() - { + public ColladaBindMaterial getBindMaterial() { return (ColladaBindMaterial) this.getField("bind_material"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceMaterial.java b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceMaterial.java index e0f376900b..1c1a21af6b 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceMaterial.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceMaterial.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import java.util.*; @@ -14,29 +13,27 @@ * @author pabercrombie * @version $Id: ColladaInstanceMaterial.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaInstanceMaterial extends ColladaAbstractInstance -{ +public class ColladaInstanceMaterial extends ColladaAbstractInstance { + protected List bindVertexInputs = new ArrayList(); - public ColladaInstanceMaterial(String ns) - { + public ColladaInstanceMaterial(String ns) { super(ns); } - public String getTarget() - { + public String getTarget() { return (String) this.getField("target"); } - public String getSymbol() - { + public String getSymbol() { return (String) this.getField("symbol"); } - /** Instance_material uses a "target" attribute instead of the "url" attribute used by other instance elements. */ + /** + * Instance_material uses a "target" attribute instead of the "url" attribute used by other instance elements. + */ @Override - public String getUrl() - { + public String getUrl() { return this.getTarget(); } @@ -45,21 +42,18 @@ public String getUrl() * * @return The bind_vertex_input elements, if present. Otherwise null. */ - public List getBindVertexInputs() - { + public List getBindVertexInputs() { return this.bindVertexInputs; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setField(String keyName, Object value) - { - if ("bind_vertex_input".equals(keyName)) - { + public void setField(String keyName, Object value) { + if ("bind_vertex_input".equals(keyName)) { this.bindVertexInputs.add((ColladaBindVertexInput) value); - } - else - { + } else { super.setField(keyName, value); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceNode.java b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceNode.java index 00a5bef33c..e19c06875a 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceNode.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceNode.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.geom.Box; @@ -16,38 +15,40 @@ * @author pabercrombie * @version $Id: ColladaInstanceNode.java 1696 2013-10-31 18:46:55Z tgaskins $ */ -public class ColladaInstanceNode extends ColladaAbstractInstance implements ColladaRenderable -{ +public class ColladaInstanceNode extends ColladaAbstractInstance implements ColladaRenderable { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaInstanceNode(String ns) - { + public ColladaInstanceNode(String ns) { super(ns); } - public Box getLocalExtent(ColladaTraversalContext tc) - { + public Box getLocalExtent(ColladaTraversalContext tc) { ColladaNode instance = this.get(); return instance != null ? instance.getLocalExtent(tc) : null; } - /** {@inheritDoc} Renders the target of the instance pointer, if the target can be resolved. */ - public void preRender(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} Renders the target of the instance pointer, if the target can be resolved. + */ + public void preRender(ColladaTraversalContext tc, DrawContext dc) { ColladaNode instance = this.get(); - if (instance != null) + if (instance != null) { instance.preRender(tc, dc); + } } - /** {@inheritDoc} Renders the target of the instance pointer, if the target can be resolved. */ - public void render(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} Renders the target of the instance pointer, if the target can be resolved. + */ + public void render(ColladaTraversalContext tc, DrawContext dc) { ColladaNode instance = this.get(); - if (instance != null) + if (instance != null) { instance.render(tc, dc); + } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceVisualScene.java b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceVisualScene.java index 6690917e58..76f936c9a2 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceVisualScene.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaInstanceVisualScene.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.geom.Box; @@ -16,34 +15,36 @@ * @author pabercrombie * @version $Id: ColladaInstanceVisualScene.java 1696 2013-10-31 18:46:55Z tgaskins $ */ -public class ColladaInstanceVisualScene extends ColladaAbstractInstance implements ColladaRenderable -{ - public ColladaInstanceVisualScene(String ns) - { +public class ColladaInstanceVisualScene extends ColladaAbstractInstance implements ColladaRenderable { + + public ColladaInstanceVisualScene(String ns) { super(ns); } @Override - public Box getLocalExtent(ColladaTraversalContext tc) - { + public Box getLocalExtent(ColladaTraversalContext tc) { ColladaVisualScene instance = this.get(); return instance != null ? instance.getLocalExtent(tc) : null; } - /** {@inheritDoc} Renders the target of the instance pointer, if the target can be resolved. */ - public void preRender(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} Renders the target of the instance pointer, if the target can be resolved. + */ + public void preRender(ColladaTraversalContext tc, DrawContext dc) { ColladaVisualScene instance = this.get(); - if (instance != null) + if (instance != null) { instance.preRender(tc, dc); + } } - /** {@inheritDoc} Renders the target of the instance pointer, if the target can be resolved. */ - public void render(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} Renders the target of the instance pointer, if the target can be resolved. + */ + public void render(ColladaTraversalContext tc, DrawContext dc) { ColladaVisualScene instance = this.get(); - if (instance != null) + if (instance != null) { instance.render(tc, dc); + } } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaLambert.java b/src/gov/nasa/worldwind/ogc/collada/ColladaLambert.java index 00b6badd2d..19640019e7 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaLambert.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaLambert.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaLambert.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaLambert extends ColladaAbstractShader -{ +public class ColladaLambert extends ColladaAbstractShader { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaLambert(String namespaceURI) - { + public ColladaLambert(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaLibrary.java b/src/gov/nasa/worldwind/ogc/collada/ColladaLibrary.java index bb7eed5d94..b3c1b58407 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaLibrary.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaLibrary.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -20,14 +19,16 @@ * @author pabercrombie * @version $Id: ColladaLibrary.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaLibrary extends ColladaAbstractObject -{ +public class ColladaLibrary extends ColladaAbstractObject { + /** * Local name of the elements in the library. This is determined from the name of the library element. For example, * if the library element is "library_nodes" then the element name is "node". */ protected String elementName; - /** Elements in the library. */ + /** + * Elements in the library. + */ protected List elements = new ArrayList(); /** @@ -35,8 +36,7 @@ public class ColladaLibrary extends ColladaAbstractObject * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaLibrary(String ns) - { + public ColladaLibrary(String ns) { super(ns); } @@ -45,52 +45,49 @@ public ColladaLibrary(String ns) * * @return Elements in the library. Returns an empty list if the library is empty. */ - public List getElements() - { + public List getElements() { return this.elements; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object parse(XMLEventParserContext context, XMLEvent event, Object... args) throws XMLStreamException - { - if (event.isStartDocument()) - { + public Object parse(XMLEventParserContext context, XMLEvent event, Object... args) throws XMLStreamException { + if (event.isStartDocument()) { String name = event.asStartElement().getName().getLocalPart(); this.elementName = this.getElementName(name); } return super.parse(context, event, args); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override @SuppressWarnings("unchecked") - public void setField(String keyName, Object value) - { - if (keyName.equals(this.elementName)) - { + public void setField(String keyName, Object value) { + if (keyName.equals(this.elementName)) { this.elements.add((T) value); - } - else - { + } else { super.setField(keyName, value); } } - protected String getElementName(String libraryName) - { - if ("library_nodes".equals(libraryName)) + protected String getElementName(String libraryName) { + if ("library_nodes".equals(libraryName)) { return "node"; - else if ("library_effects".equals(libraryName)) + } else if ("library_effects".equals(libraryName)) { return "effect"; - else if ("library_materials".equals(libraryName)) + } else if ("library_materials".equals(libraryName)) { return "material"; - else if ("library_geometries".equals(libraryName)) + } else if ("library_geometries".equals(libraryName)) { return "geometry"; - else if ("library_images".equals(libraryName)) + } else if ("library_images".equals(libraryName)) { return "image"; - else if ("library_visual_scenes".equals(libraryName)) + } else if ("library_visual_scenes".equals(libraryName)) { return "visual_scene"; + } return null; } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaLines.java b/src/gov/nasa/worldwind/ogc/collada/ColladaLines.java index 0c1ea7b5b1..6e6d1461bb 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaLines.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaLines.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id$ */ -public class ColladaLines extends ColladaAbstractGeometry -{ +public class ColladaLines extends ColladaAbstractGeometry { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaLines(String ns) - { + public ColladaLines(String ns) { super(ns); } @@ -30,8 +28,7 @@ public ColladaLines(String ns) * @return Two */ @Override - protected int getVerticesPerShape() - { + protected int getVerticesPerShape() { return 2; } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaMaterial.java b/src/gov/nasa/worldwind/ogc/collada/ColladaMaterial.java index fa4cc5ffff..87f2001278 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaMaterial.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaMaterial.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,20 +11,18 @@ * @author pabercrombie * @version $Id: ColladaMaterial.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaMaterial extends ColladaAbstractObject -{ +public class ColladaMaterial extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaMaterial(String ns) - { + public ColladaMaterial(String ns) { super(ns); } - public ColladaInstanceEffect getInstanceEffect() - { + public ColladaInstanceEffect getInstanceEffect() { return (ColladaInstanceEffect) this.getField("instance_effect"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaMatrix.java b/src/gov/nasa/worldwind/ogc/collada/ColladaMatrix.java index e843c27c2e..4ef1838cb4 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaMatrix.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaMatrix.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaMatrix.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaMatrix extends ColladaAbstractObject -{ +public class ColladaMatrix extends ColladaAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaMatrix(String namespaceURI) - { + public ColladaMatrix(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaMesh.java b/src/gov/nasa/worldwind/ogc/collada/ColladaMesh.java index 78e5ab9e5d..2ae49d75b4 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaMesh.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaMesh.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import java.util.*; @@ -14,8 +13,8 @@ * @author pabercrombie * @version $Id: ColladaMesh.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaMesh extends ColladaAbstractObject -{ +public class ColladaMesh extends ColladaAbstractObject { + protected List sources = new ArrayList(); protected List vertices = new ArrayList(); @@ -23,58 +22,45 @@ public class ColladaMesh extends ColladaAbstractObject protected List triangles; protected List lines; - public ColladaMesh(String ns) - { + public ColladaMesh(String ns) { super(ns); } - public List getSources() - { + public List getSources() { return this.sources; } - public List getTriangles() - { + public List getTriangles() { return this.triangles != null ? this.triangles : Collections.emptyList(); } - public List getLines() - { + public List getLines() { return this.lines != null ? this.lines : Collections.emptyList(); } - public List getVertices() - { + public List getVertices() { return this.vertices; } @Override - public void setField(String keyName, Object value) - { - if (keyName.equals("vertices")) - { + public void setField(String keyName, Object value) { + if (keyName.equals("vertices")) { this.vertices.add((ColladaVertices) value); - } - else if (keyName.equals("source")) - { + } else if (keyName.equals("source")) { this.sources.add((ColladaSource) value); - } - else if (keyName.equals("triangles")) - { - if (this.triangles == null) + } else if (keyName.equals("triangles")) { + if (this.triangles == null) { this.triangles = new ArrayList(); + } this.triangles.add((ColladaTriangles) value); - } - else if (keyName.equals("lines")) - { - if (this.lines == null) + } else if (keyName.equals("lines")) { + if (this.lines == null) { this.lines = new ArrayList(); + } this.lines.add((ColladaLines) value); - } - else - { + } else { super.setField(keyName, value); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaNewParam.java b/src/gov/nasa/worldwind/ogc/collada/ColladaNewParam.java index 4767dbe0b3..486ed16d9b 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaNewParam.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaNewParam.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,25 +11,22 @@ * @author pabercrombie * @version $Id: ColladaNewParam.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaNewParam extends ColladaAbstractObject -{ +public class ColladaNewParam extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaNewParam(String ns) - { + public ColladaNewParam(String ns) { super(ns); } - public ColladaSampler2D getSampler2D() - { + public ColladaSampler2D getSampler2D() { return (ColladaSampler2D) this.getField("sampler2D"); } - public ColladaSurface getSurface() - { + public ColladaSurface getSurface() { return (ColladaSurface) this.getField("surface"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaNode.java b/src/gov/nasa/worldwind/ogc/collada/ColladaNode.java index 7b2e7f4cd4..335269ae85 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaNode.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaNode.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.geom.*; @@ -19,20 +18,26 @@ * @author pabercrombie * @version $Id: ColladaNode.java 1696 2013-10-31 18:46:55Z tgaskins $ */ -public class ColladaNode extends ColladaAbstractObject implements ColladaRenderable -{ +public class ColladaNode extends ColladaAbstractObject implements ColladaRenderable { + /** * Children of this node. Children may be ColladaNode (direct child of this node) or ColladaInstanceNode (reference * to a node elsewhere in the current document, or another document). */ protected List children; - /** Geometries defined in this node. */ + /** + * Geometries defined in this node. + */ protected List geometries; - /** Shape used to render geometry in this node. */ + /** + * Shape used to render geometry in this node. + */ protected List shapes; - /** Transform matrix for this node. */ + /** + * Transform matrix for this node. + */ protected Matrix matrix; /** @@ -40,98 +45,94 @@ public class ColladaNode extends ColladaAbstractObject implements ColladaRendera * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaNode(String ns) - { + public ColladaNode(String ns) { super(ns); } - public Box getLocalExtent(ColladaTraversalContext tc) - { - if (tc == null) - { + public Box getLocalExtent(ColladaTraversalContext tc) { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // Create shapes for this node, if necessary - if (this.shapes == null) + if (this.shapes == null) { this.shapes = this.createShapes(); + } - if (this.getMatrix() != null) - { + if (this.getMatrix() != null) { tc.pushMatrix(); tc.multiplyMatrix(this.getMatrix()); } ArrayList extents = new ArrayList(); - for (ColladaMeshShape shape : this.shapes) - { + for (ColladaMeshShape shape : this.shapes) { Box extent = shape.getLocalExtent(tc); - if (extent != null) + if (extent != null) { extents.add(extent); + } } - if (this.children != null) - { - for (ColladaRenderable node : children) - { + if (this.children != null) { + for (ColladaRenderable node : children) { Box extent = node.getLocalExtent(tc); - if (extent != null) + if (extent != null) { extents.add(extent); + } } } - if (this.getMatrix() != null) + if (this.getMatrix() != null) { tc.popMatrix(); + } - if (extents.isEmpty()) + if (extents.isEmpty()) { return null; + } return Box.union(extents); } - /** {@inheritDoc} */ - public void preRender(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void preRender(ColladaTraversalContext tc, DrawContext dc) { List children = this.getChildren(); - if (WWUtil.isEmpty(children)) + if (WWUtil.isEmpty(children)) { return; + } Matrix matrix = this.getMatrix(); - try - { - if (matrix != null && matrix != Matrix.IDENTITY) - { + try { + if (matrix != null && matrix != Matrix.IDENTITY) { tc.pushMatrix(); tc.multiplyMatrix(matrix); } - for (ColladaRenderable node : children) - { + for (ColladaRenderable node : children) { node.preRender(tc, dc); } - } - finally - { - if (matrix != null && matrix != Matrix.IDENTITY) + } finally { + if (matrix != null && matrix != Matrix.IDENTITY) { tc.popMatrix(); + } } } - /** {@inheritDoc} */ - public void render(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(ColladaTraversalContext tc, DrawContext dc) { // Create shapes for this node, if necessary - if (this.shapes == null) + if (this.shapes == null) { this.shapes = this.createShapes(); + } Matrix matrix = this.getMatrix(); - try - { - if (matrix != null && matrix != Matrix.IDENTITY) - { + try { + if (matrix != null && matrix != Matrix.IDENTITY) { tc.pushMatrix(); tc.multiplyMatrix(matrix); } @@ -145,8 +146,7 @@ public void render(ColladaTraversalContext tc, DrawContext dc) Position position = root.getPosition(); Matrix traversalMatrix = tc.peekMatrix(); - for (ColladaMeshShape shape : this.shapes) - { + for (ColladaMeshShape shape : this.shapes) { shape.setModelPosition(position); shape.setAltitudeMode(altitudeMode); shape.setHighlighted(highlighted); @@ -154,15 +154,13 @@ public void render(ColladaTraversalContext tc, DrawContext dc) shape.render(dc, traversalMatrix); } - for (ColladaRenderable node : this.getChildren()) - { + for (ColladaRenderable node : this.getChildren()) { node.render(tc, dc); } - } - finally - { - if (matrix != null && matrix != Matrix.IDENTITY) + } finally { + if (matrix != null && matrix != Matrix.IDENTITY) { tc.popMatrix(); + } } } @@ -171,14 +169,13 @@ public void render(ColladaTraversalContext tc, DrawContext dc) * * @return List shapes. The list may be empty, but will never be null. */ - protected List createShapes() - { - if (WWUtil.isEmpty(this.geometries)) + protected List createShapes() { + if (WWUtil.isEmpty(this.geometries)) { return Collections.emptyList(); + } List shapes = new ArrayList(); - for (ColladaInstanceGeometry geometry : this.geometries) - { + for (ColladaInstanceGeometry geometry : this.geometries) { this.createShapesForGeometry(geometry, shapes); } return shapes; @@ -188,24 +185,24 @@ protected List createShapes() * Create shapes for a geometry. * * @param geomInstance Geometry for which to create shapes. - * @param shapes List to collect the new shapes. + * @param shapes List to collect the new shapes. */ - protected void createShapesForGeometry(ColladaInstanceGeometry geomInstance, List shapes) - { + protected void createShapesForGeometry(ColladaInstanceGeometry geomInstance, List shapes) { ColladaGeometry geometry = geomInstance.get(); - if (geometry == null) + if (geometry == null) { return; + } ColladaMesh mesh = geometry.getMesh(); - if (mesh == null) + if (mesh == null) { return; + } ColladaBindMaterial bindMaterial = geomInstance.getBindMaterial(); ColladaRoot root = this.getRoot(); List triangles = mesh.getTriangles(); - if (!WWUtil.isEmpty(triangles)) - { + if (!WWUtil.isEmpty(triangles)) { ColladaMeshShape newShape = ColladaMeshShape.createTriangleMesh(triangles, bindMaterial); newShape.setDelegateOwner(root); @@ -213,8 +210,7 @@ protected void createShapesForGeometry(ColladaInstanceGeometry geomInstance, Lis } List lines = mesh.getLines(); - if (!WWUtil.isEmpty(lines)) - { + if (!WWUtil.isEmpty(lines)) { ColladaMeshShape newShape = ColladaMeshShape.createLineMesh(lines, bindMaterial); newShape.setDelegateOwner(root); @@ -223,24 +219,20 @@ protected void createShapesForGeometry(ColladaInstanceGeometry geomInstance, Lis } @Override - public void setField(String keyName, Object value) - { - if ("node".equals(keyName) || "instance_node".equals(keyName)) - { - if (this.children == null) + public void setField(String keyName, Object value) { + if ("node".equals(keyName) || "instance_node".equals(keyName)) { + if (this.children == null) { this.children = new ArrayList(); + } this.children.add((ColladaRenderable) value); - } - else if ("instance_geometry".equals(keyName)) - { - if (this.geometries == null) + } else if ("instance_geometry".equals(keyName)) { + if (this.geometries == null) { this.geometries = new ArrayList(); + } this.geometries.add((ColladaInstanceGeometry) value); - } - else - { + } else { super.setField(keyName, value); } } @@ -251,8 +243,7 @@ else if ("instance_geometry".equals(keyName)) * * @return List of children. The list may be empty, but will never be null. */ - protected List getChildren() - { + protected List getChildren() { return this.children != null ? this.children : Collections.emptyList(); } @@ -261,15 +252,14 @@ protected List getChildren() * * @return The matrix specified in this node. Returns the identity matrix if the node does not specify a matrix. */ - protected Matrix getMatrix() - { - if (this.matrix != null) + protected Matrix getMatrix() { + if (this.matrix != null) { return this.matrix; + } // TODO a node can have more than one matrix ColladaMatrix matrix = (ColladaMatrix) this.getField("matrix"); - if (matrix == null) - { + if (matrix == null) { // Set matrix to identity so that we won't look for it again. this.matrix = Matrix.IDENTITY; return this.matrix; @@ -291,14 +281,12 @@ protected Matrix getMatrix() * * @return Parsed double[] */ - protected double[] parseDoubleArray(String doubleArrayString) - { + protected double[] parseDoubleArray(String doubleArrayString) { String[] arrayOfNumbers = doubleArrayString.trim().split("\\s+"); double[] doubles = new double[arrayOfNumbers.length]; int i = 0; - for (String s : arrayOfNumbers) - { + for (String s : arrayOfNumbers) { doubles[i++] = Double.parseDouble(s); } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaP.java b/src/gov/nasa/worldwind/ogc/collada/ColladaP.java index 9af2cd54d5..f3acff954b 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaP.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaP.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.util.WWUtil; @@ -21,9 +20,11 @@ * @author pabercrombie * @version $Id: ColladaP.java 662 2012-06-26 19:05:46Z pabercrombie $ */ -public class ColladaP extends ColladaAbstractObject -{ - /** Indices contained in this element. */ +public class ColladaP extends ColladaAbstractObject { + + /** + * Indices contained in this element. + */ protected int[] indices; /** @@ -31,8 +32,7 @@ public class ColladaP extends ColladaAbstractObject * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaP(String ns) - { + public ColladaP(String ns) { super(ns); } @@ -41,22 +41,22 @@ public ColladaP(String ns) * * @return Array of indices defined by this element. */ - public int[] getIndices() - { + public int[] getIndices() { return this.indices; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object parse(XMLEventParserContext ctx, XMLEvent event, Object... args) throws XMLStreamException - { + public Object parse(XMLEventParserContext ctx, XMLEvent event, Object... args) throws XMLStreamException { super.parse(ctx, event, args); - if (this.hasField(CHARACTERS_CONTENT)) - { + if (this.hasField(CHARACTERS_CONTENT)) { String s = (String) this.getField(CHARACTERS_CONTENT); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.indices = this.parseInts(s); + } // Don't need to keep string version of the ints this.removeField(CHARACTERS_CONTENT); @@ -72,16 +72,15 @@ public Object parse(XMLEventParserContext ctx, XMLEvent event, Object... args) t * * @return Array of integers parsed from the input string. */ - protected int[] parseInts(String intArrayString) - { + protected int[] parseInts(String intArrayString) { String[] arrayOfNumbers = intArrayString.split("\\s"); int[] ints = new int[arrayOfNumbers.length]; int i = 0; - for (String s : arrayOfNumbers) - { - if (!WWUtil.isEmpty(s)) + for (String s : arrayOfNumbers) { + if (!WWUtil.isEmpty(s)) { ints[i++] = Integer.parseInt(s); + } } return ints; diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaParam.java b/src/gov/nasa/worldwind/ogc/collada/ColladaParam.java index 1aaf9dc954..d73e0ad148 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaParam.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaParam.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaParam.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ColladaParam extends ColladaAbstractObject -{ +public class ColladaParam extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaParam(String ns) - { + public ColladaParam(String ns) { super(ns); } @@ -29,8 +27,7 @@ public ColladaParam(String ns) * * @return The value of the name field, or null if the field is not set. */ - public String getName() - { + public String getName() { return (String) this.getField("name"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaParserContext.java b/src/gov/nasa/worldwind/ogc/collada/ColladaParserContext.java index 41529b255b..1d793ba803 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaParserContext.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaParserContext.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.util.xml.*; @@ -17,71 +16,72 @@ * @author jfb * @version $Id: ColladaParserContext.java 644 2012-06-14 20:07:17Z pabercrombie $ */ -public class ColladaParserContext extends BasicXMLEventParserContext -{ - /** The key used to identify the coordinates parser in the parser context's parser map. */ +public class ColladaParserContext extends BasicXMLEventParserContext { + + /** + * The key used to identify the coordinates parser in the parser context's parser map. + */ protected static QName COORDINATES = new QName("Coordinates"); - /** The names of elements that contain merely string data and can be parsed by a generic string parser. */ - protected static final String[] StringFields = new String[] - { - "author", - "name", - "authoring_tool", - "source_data", - "init_from", - "created", - "modified", - "up_axis", - }; - - /** The names of elements that contain merely double data and can be parsed by a generic double parser. */ - protected static final String[] DoubleFields = new String[] - { - "revision", - "float" - }; - - /** The names of elements that contain merely integer data and can be parsed by a generic integer parser. */ - protected static final String[] IntegerFields = new String[] - { - "drawOrder", - "meter", - "double_sided" // Not part of core COLLADA spec, but included in most SketchUp models. - }; + /** + * The names of elements that contain merely string data and can be parsed by a generic string parser. + */ + protected static final String[] StringFields = new String[]{ + "author", + "name", + "authoring_tool", + "source_data", + "init_from", + "created", + "modified", + "up_axis",}; + + /** + * The names of elements that contain merely double data and can be parsed by a generic double parser. + */ + protected static final String[] DoubleFields = new String[]{ + "revision", + "float" + }; + + /** + * The names of elements that contain merely integer data and can be parsed by a generic integer parser. + */ + protected static final String[] IntegerFields = new String[]{ + "drawOrder", + "meter", + "double_sided" // Not part of core COLLADA spec, but included in most SketchUp models. + }; /** * The names of elements that contain merely boolean integer (0 or 1) data and can be parsed by a generic boolean * integer parser. */ - protected static final String[] BooleanFields = new String[] - { - "extrude", - }; + protected static final String[] BooleanFields = new String[]{ + "extrude",}; /** * Creates a parser context instance. * - * @param eventReader the event reader from which to read events. - * @param defaultNamespace the default namespace. If null, {@link gov.nasa.worldwind.ogc.collada.ColladaConstants#COLLADA_NAMESPACE} + * @param eventReader the event reader from which to read events. + * @param defaultNamespace the default namespace. If null, + * {@link gov.nasa.worldwind.ogc.collada.ColladaConstants#COLLADA_NAMESPACE} */ - public ColladaParserContext(XMLEventReader eventReader, String defaultNamespace) - { + public ColladaParserContext(XMLEventReader eventReader, String defaultNamespace) { super(eventReader, defaultNamespace != null ? defaultNamespace : ColladaConstants.COLLADA_NAMESPACE); } /** * Creates a parser context instance. * - * @param defaultNamespace the default namespace. If null, {@link gov.nasa.worldwind.ogc.collada.ColladaConstants#COLLADA_NAMESPACE} + * @param defaultNamespace the default namespace. If null, + * {@link gov.nasa.worldwind.ogc.collada.ColladaConstants#COLLADA_NAMESPACE} */ - public ColladaParserContext(String defaultNamespace) - { + public ColladaParserContext(String defaultNamespace) { this(null, defaultNamespace); } - public ColladaParserContext(ColladaParserContext ctx) - { + public ColladaParserContext(ColladaParserContext ctx) { super(ctx); } @@ -90,15 +90,13 @@ public ColladaParserContext(ColladaParserContext ctx) * #registerParser(javax.xml.namespace.QName, gov.nasa.worldwind.util.xml.XMLEventParser)}. */ @Override - protected void initializeParsers() - { + protected void initializeParsers() { super.initializeParsers(); this.initializeParsers(ColladaConstants.COLLADA_NAMESPACE); } - protected void initializeParsers(String ns) - { + protected void initializeParsers(String ns) { this.parsers.put(new QName(ns, "unit"), new ColladaUnit(ns)); this.parsers.put(new QName(ns, "material"), new ColladaMaterial(ns)); this.parsers.put(new QName(ns, "technique"), new ColladaTechnique(ns)); diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaPhong.java b/src/gov/nasa/worldwind/ogc/collada/ColladaPhong.java index 9b5f60c1bb..9f42edf565 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaPhong.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaPhong.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaPhong.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaPhong extends ColladaAbstractShader -{ +public class ColladaPhong extends ColladaAbstractShader { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaPhong(String ns) - { + public ColladaPhong(String ns) { super(ns); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaProfileCommon.java b/src/gov/nasa/worldwind/ogc/collada/ColladaProfileCommon.java index 834279e640..be00e2407b 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaProfileCommon.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaProfileCommon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaProfileCommon.java 675 2012-07-02 18:47:47Z pabercrombie $ */ -public class ColladaProfileCommon extends ColladaAbstractParamContainer -{ +public class ColladaProfileCommon extends ColladaAbstractParamContainer { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaProfileCommon(String ns) - { + public ColladaProfileCommon(String ns) { super(ns); } @@ -29,8 +27,7 @@ public ColladaProfileCommon(String ns) * * @return The value of the technique field, or null if the field is not set. */ - public ColladaTechnique getTechnique() - { + public ColladaTechnique getTechnique() { return (ColladaTechnique) this.getField("technique"); } @@ -39,22 +36,24 @@ public ColladaTechnique getTechnique() * * @return The value of the technique field, or null if the field is not set. */ - public ColladaExtra getExtra() - { + public ColladaExtra getExtra() { return (ColladaExtra) this.getField("extra"); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public ColladaNewParam getParam(String sid) - { + public ColladaNewParam getParam(String sid) { ColladaNewParam param = super.getParam(sid); - if (param != null) + if (param != null) { return param; + } ColladaTechnique technique = this.getTechnique(); - if (technique == null) + if (technique == null) { return null; + } return technique.getParam(sid); } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaResourceResolver.java b/src/gov/nasa/worldwind/ogc/collada/ColladaResourceResolver.java index 0b5a55db33..8cee57eec7 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaResourceResolver.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaResourceResolver.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import java.io.IOException; @@ -15,8 +14,8 @@ * @version $Id: ColladaResourceResolver.java 654 2012-06-25 04:15:52Z pabercrombie $ * @see ColladaRoot */ -public interface ColladaResourceResolver -{ +public interface ColladaResourceResolver { + /** * Resolve a file path. * diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaRoot.java b/src/gov/nasa/worldwind/ogc/collada/ColladaRoot.java index 3916227b2e..908a4f98a6 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaRoot.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaRoot.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.WorldWind; @@ -28,18 +27,28 @@ * @author pabercrombie * @version $Id: ColladaRoot.java 1696 2013-10-31 18:46:55Z tgaskins $ */ -public class ColladaRoot extends ColladaAbstractObject implements ColladaRenderable, Highlightable -{ - /** Reference to the ColladaDoc representing the COLLADA file. */ +public class ColladaRoot extends ColladaAbstractObject implements ColladaRenderable, Highlightable { + + /** + * Reference to the ColladaDoc representing the COLLADA file. + */ protected ColladaDoc colladaDoc; - /** The event reader used to parse the document's XML. */ + /** + * The event reader used to parse the document's XML. + */ protected XMLEventReader eventReader; - /** The input stream underlying the event reader. */ + /** + * The input stream underlying the event reader. + */ protected InputStream eventStream; - /** The parser context for the document. */ + /** + * The parser context for the document. + */ protected ColladaParserContext parserContext; - /** This shape's geographic location. The altitude is relative to this shapes altitude mode. */ + /** + * This shape's geographic location. The altitude is relative to this shapes altitude mode. + */ protected Position position; /** * This shape's altitude mode. May be one of {@link WorldWind#CLAMP_TO_GROUND}, {@link @@ -47,7 +56,9 @@ public class ColladaRoot extends ColladaAbstractObject implements ColladaRendera */ protected int altitudeMode = WorldWind.CLAMP_TO_GROUND; - /** This shape's heading, positive values are clockwise from north. Null is an allowed value. */ + /** + * This shape's heading, positive values are clockwise from north. Null is an allowed value. + */ protected Angle heading; /** * This shape's pitch (often called tilt), its rotation about the model's X axis. Positive values are clockwise. @@ -59,20 +70,32 @@ public class ColladaRoot extends ColladaAbstractObject implements ColladaRendera * Value. */ protected Angle roll; - /** A scale to apply to the model. Null is an allowed value. */ + /** + * A scale to apply to the model. Null is an allowed value. + */ protected Vec4 modelScale; - /** Flag to indicate that the scene has been retrieved from the hash map. */ + /** + * Flag to indicate that the scene has been retrieved from the hash map. + */ protected boolean sceneFetched = false; - /** Cached COLLADA scene. */ + /** + * Cached COLLADA scene. + */ protected ColladaScene scene; - /** Flag to indicate that the scale has been computed. */ + /** + * Flag to indicate that the scale has been computed. + */ protected boolean scaleFetched = false; - /** Scale applied to the model. Determined by the COLLADA/asset/unit element. */ + /** + * Scale applied to the model. Determined by the COLLADA/asset/unit element. + */ protected double scale; - /** Indicates whether or not the COLLADA model is highlighted. */ + /** + * Indicates whether or not the COLLADA model is highlighted. + */ protected boolean highlighted; /** @@ -81,7 +104,9 @@ public class ColladaRoot extends ColladaAbstractObject implements ColladaRendera */ protected Matrix matrix; - /** Resource resolver to resolve relative file paths. */ + /** + * Resource resolver to resolve relative file paths. + */ protected ColladaResourceResolver resourceResolver; /** @@ -91,14 +116,12 @@ public class ColladaRoot extends ColladaAbstractObject implements ColladaRendera * @param docSource the ColladaDoc instance representing the COLLADA document. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the COLLADA document. + * @throws IOException if an error occurs while reading the COLLADA document. */ - public ColladaRoot(ColladaDoc docSource) throws IOException - { + public ColladaRoot(ColladaDoc docSource) throws IOException { super(ColladaConstants.COLLADA_NAMESPACE); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -114,14 +137,12 @@ public ColladaRoot(ColladaDoc docSource) throws IOException * @param docSource the File containing the document. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the Collada document. + * @throws IOException if an error occurs while reading the Collada document. */ - public ColladaRoot(File docSource) throws IOException - { + public ColladaRoot(File docSource) throws IOException { super(ColladaConstants.COLLADA_NAMESPACE); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -138,14 +159,12 @@ public ColladaRoot(File docSource) throws IOException * @param docSource the URL of the document. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the Collada document. + * @throws IOException if an error occurs while reading the Collada document. */ - public ColladaRoot(URL docSource) throws IOException - { + public ColladaRoot(URL docSource) throws IOException { super(ColladaConstants.COLLADA_NAMESPACE); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -163,14 +182,12 @@ public ColladaRoot(URL docSource) throws IOException * @param docSource the URL of the document. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the Collada document. + * @throws IOException if an error occurs while reading the Collada document. */ - public ColladaRoot(InputStream docSource) throws IOException - { + public ColladaRoot(InputStream docSource) throws IOException { super(ColladaConstants.COLLADA_NAMESPACE); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -190,37 +207,30 @@ public ColladaRoot(InputStream docSource) throws IOException * @return a new {@link ColladaRoot} for the specified source, or null if the source type is not supported. * * @throws IllegalArgumentException if the source is null. - * @throws IOException if an error occurs while reading the source. + * @throws IOException if an error occurs while reading the source. */ - public static ColladaRoot create(Object docSource) throws IOException - { - if (docSource == null) - { + public static ColladaRoot create(Object docSource) throws IOException { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (docSource instanceof File) - { + if (docSource instanceof File) { return new ColladaRoot((File) docSource); - } - else if (docSource instanceof URL) - { + } else if (docSource instanceof URL) { return new ColladaRoot((URL) docSource); - } - else if (docSource instanceof String) - { + } else if (docSource instanceof String) { File file = new File((String) docSource); - if (file.exists()) + if (file.exists()) { return new ColladaRoot(file); + } URL url = WWIO.makeURL(docSource); - if (url != null) + if (url != null) { return new ColladaRoot(url); - } - else if (docSource instanceof InputStream) - { + } + } else if (docSource instanceof InputStream) { return new ColladaRoot((InputStream) docSource); } @@ -228,7 +238,9 @@ else if (docSource instanceof InputStream) } /** - * Creates and parses a Collada root for an untyped source.The source must be either a {@link File} or a {@link String} identifying either a file path or a {@link URL}. Null is returned if the source type is not recognized. + * Creates and parses a Collada root for an untyped source.The source must be either a {@link File} or a + * {@link String} identifying either a file path or a {@link URL}. Null is returned if the source type is not + * recognized. * * @param docSource either a {@link File} or a {@link String} identifying a file path or {@link URL}. * @@ -236,16 +248,14 @@ else if (docSource instanceof InputStream) * * @throws IllegalArgumentException if the source is null. * @throws javax.xml.stream.XMLStreamException if the XML stream is not readable. - * @throws IOException if an error occurs while reading the source. + * @throws IOException if an error occurs while reading the source. */ - public static ColladaRoot createAndParse(Object docSource) throws IOException, XMLStreamException - { + public static ColladaRoot createAndParse(Object docSource) throws IOException, XMLStreamException { ColladaRoot colladaRoot = ColladaRoot.create(docSource); - if (colladaRoot == null) - { + if (colladaRoot == null) { String message = Logging.getMessage("generic.UnrecognizedSourceTypeOrUnavailableSource", - docSource.toString()); + docSource.toString()); throw new IllegalArgumentException(message); } @@ -260,12 +270,12 @@ public static ColladaRoot createAndParse(Object docSource) throws IOException, X * * @throws java.io.IOException if an I/O error occurs attempting to open the document source. */ - protected void initialize() throws IOException - { + protected void initialize() throws IOException { this.eventStream = new BufferedInputStream(this.getColladaDoc().getInputStream()); this.eventReader = this.createReader(this.eventStream); - if (this.eventReader == null) + if (this.eventReader == null) { throw new WWRuntimeException(Logging.getMessage("XML.UnableToOpenDocument", this.getColladaDoc())); + } this.parserContext = this.createParserContext(this.eventReader); } @@ -275,8 +285,7 @@ protected void initialize() throws IOException * * @return The source of the COLLADA content. */ - protected ColladaDoc getColladaDoc() - { + protected ColladaDoc getColladaDoc() { return this.colladaDoc; } @@ -285,8 +294,7 @@ protected ColladaDoc getColladaDoc() * * @return this shape's geographic position. The position's altitude is relative to this shape's altitude mode. */ - public Position getPosition() - { + public Position getPosition() { return this.position; } @@ -297,10 +305,8 @@ public Position getPosition() * * @throws IllegalArgumentException if the position is null. */ - public void setPosition(Position position) - { - if (position == null) - { + public void setPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -316,8 +322,7 @@ public void setPosition(Position position) * * @see #setAltitudeMode(int) */ - public int getAltitudeMode() - { + public int getAltitudeMode() { return this.altitudeMode; } @@ -331,8 +336,7 @@ public int getAltitudeMode() * * @param altitudeMode the altitude mode. The default value is {@link WorldWind#ABSOLUTE}. */ - public void setAltitudeMode(int altitudeMode) - { + public void setAltitudeMode(int altitudeMode) { this.altitudeMode = altitudeMode; } @@ -341,8 +345,7 @@ public void setAltitudeMode(int altitudeMode) * * @return this shape's heading, or null if no heading has been specified. */ - public Angle getHeading() - { + public Angle getHeading() { return this.heading; } @@ -351,8 +354,7 @@ public Angle getHeading() * * @param heading this shape's heading. May be null. */ - public void setHeading(Angle heading) - { + public void setHeading(Angle heading) { this.heading = heading; this.reset(); } @@ -362,10 +364,9 @@ public void setHeading(Angle heading) * axis. * * @return this shape's pitch, or null if no pitch has been specified. Positive values are clockwise as observed - * looking along the model's X axis toward the model's origin. + * looking along the model's X axis toward the model's origin. */ - public Angle getPitch() - { + public Angle getPitch() { return this.pitch; } @@ -374,10 +375,9 @@ public Angle getPitch() * axis. * * @param pitch this shape's pitch. Positive values are clockwise as observed looking along the model's X axis - * toward the model's origin. May be null. + * toward the model's origin. May be null. */ - public void setPitch(Angle pitch) - { + public void setPitch(Angle pitch) { this.pitch = pitch; this.reset(); } @@ -386,10 +386,9 @@ public void setPitch(Angle pitch) * Indicates this shape's roll, the angle to rotate this shape's model about its Y axis. * * @return this shape's roll, or null if no roll has been specified. Positive values are clockwise as observed - * looking along the model's Y axis toward the origin. + * looking along the model's Y axis toward the origin. */ - public Angle getRoll() - { + public Angle getRoll() { return this.roll; } @@ -397,10 +396,9 @@ public Angle getRoll() * Specifies this shape's roll, the angle to rotate this shape's model about its Y axis. * * @param roll this shape's roll. May be null. Positive values are clockwise as observed looking along the model's Y - * axis toward the origin. + * axis toward the origin. */ - public void setRoll(Angle roll) - { + public void setRoll(Angle roll) { this.roll = roll; this.reset(); } @@ -410,8 +408,7 @@ public void setRoll(Angle roll) * * @return this shape's scale, or null if no scale has been specified. */ - public Vec4 getModelScale() - { + public Vec4 getModelScale() { return this.modelScale; } @@ -421,8 +418,7 @@ public Vec4 getModelScale() * * @param modelScale this shape's scale. May be null, in which case no scaling is applied. */ - public void setModelScale(Vec4 modelScale) - { + public void setModelScale(Vec4 modelScale) { this.modelScale = modelScale; this.reset(); } @@ -432,8 +428,7 @@ public void setModelScale(Vec4 modelScale) * * @return The resource resolver, or null if none is set. */ - public ColladaResourceResolver getResourceResolver() - { + public ColladaResourceResolver getResourceResolver() { return this.resourceResolver; } @@ -442,20 +437,21 @@ public ColladaResourceResolver getResourceResolver() * * @param resourceResolver New resource resolver. May be null. */ - public void setResourceResolver(ColladaResourceResolver resourceResolver) - { + public void setResourceResolver(ColladaResourceResolver resourceResolver) { this.resourceResolver = resourceResolver; } - /** {@inheritDoc} */ - public boolean isHighlighted() - { + /** + * {@inheritDoc} + */ + public boolean isHighlighted() { return this.highlighted; } - /** {@inheritDoc} Setting root COLLADA root highlighted causes all parts of the COLLADA model to highlight. */ - public void setHighlighted(boolean highlighted) - { + /** + * {@inheritDoc} Setting root COLLADA root highlighted causes all parts of the COLLADA model to highlight. + */ + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } @@ -467,63 +463,62 @@ public void setHighlighted(boolean highlighted) * ColladaRoot. * * @param link the address of the document or element to resolve. This may be a full URL, a URL fragment that - * identifies an element in the current document ("#myElement"), or a URL and a fragment identifier - * ("http://server.com/model.dae#myElement"). + * identifies an element in the current document ("#myElement"), or a URL and a fragment identifier + * ("http://server.com/model.dae#myElement"). * * @return the requested element, or null if the element is not found. * * @throws IllegalArgumentException if the address is null. */ - public Object resolveReference(String link) - { - if (link == null) - { + public Object resolveReference(String link) { + if (link == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { String[] linkParts = link.split("#"); String linkBase = linkParts[0]; String linkRef = linkParts.length > 1 ? linkParts[1] : null; // See if it's a reference to an internal element. - if (WWUtil.isEmpty(linkBase) && !WWUtil.isEmpty(linkRef)) + if (WWUtil.isEmpty(linkBase) && !WWUtil.isEmpty(linkRef)) { return this.getItemByID(linkRef); + } // Interpret the path relative to the current document. String path = this.getSupportFilePath(linkBase); - if (path == null) + if (path == null) { path = linkBase; + } // See if it's an already found and parsed COLLADA file. Object o = WorldWind.getSessionCache().get(path); - if (o != null && o instanceof ColladaRoot) + if (o != null && o instanceof ColladaRoot) { return linkRef != null ? ((ColladaRoot) o).getItemByID(linkRef) : o; + } URL url = WWIO.makeURL(path); - if (url == null) - { + if (url == null) { // See if the reference can be resolved to a local file. o = this.resolveLocalReference(path, linkRef); } // If we didn't find a local file, treat it as a remote reference. - if (o == null) + if (o == null) { o = this.resolveRemoteReference(path, linkRef); + } - if (o != null) + if (o != null) { return o; + } // If the reference was not resolved as a remote reference, look for a local element identified by the // reference string. This handles the case of malformed internal references that omit the # sign at the // beginning of the reference. return this.getItemByID(link); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.UnableToResolveReference", link); Logging.logger().warning(message); } @@ -540,31 +535,30 @@ public Object resolveReference(String link) * ColladaRoot} for the COLLADA file identified by {@code linkBase}. Otherwise, {@code linkBase} is returned. * * @param linkBase the address of the document containing the requested element. - * @param linkRef the element's identifier. + * @param linkRef the element's identifier. * * @return the requested element, or null if the element is not found. * * @throws IllegalArgumentException if the address is null. */ - protected Object resolveLocalReference(String linkBase, String linkRef) - { - if (linkBase == null) - { + protected Object resolveLocalReference(String linkBase, String linkRef) { + if (linkBase == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { File file = new File(linkBase); - if (!file.exists()) + if (!file.exists()) { return null; + } // Determine whether the file is a COLLADA document. If not, just return the file path. - if (!WWIO.isContentType(file, ColladaConstants.COLLADA_MIME_TYPE)) + if (!WWIO.isContentType(file, ColladaConstants.COLLADA_MIME_TYPE)) { return file.toURI().toString(); + } // Attempt to open and parse the COLLADA file. ColladaRoot refRoot = ColladaRoot.createAndParse(file); @@ -574,13 +568,12 @@ protected Object resolveLocalReference(String linkBase, String linkRef) WorldWind.getSessionCache().put(linkBase, refRoot); // Now check the newly opened COLLADA file for the referenced item, if a reference was specified. - if (linkRef != null) + if (linkRef != null) { return refRoot.getItemByID(linkRef); - else + } else { return refRoot; - } - catch (Exception e) - { + } + } catch (Exception e) { String message = Logging.getMessage("generic.UnableToResolveReference", linkBase + "/" + linkRef); Logging.logger().warning(message); return null; @@ -599,41 +592,40 @@ protected Object resolveLocalReference(String linkBase, String linkRef) * the file in the file cache. * * @param linkBase the address of the document containing the requested element. - * @param linkRef the element's identifier. + * @param linkRef the element's identifier. * * @return URL to the requested file, parsed ColladaRoot, or COLLADA element. Returns null if the document is not - * yet available in the FileStore. + * yet available in the FileStore. * * @throws IllegalArgumentException if the {@code linkBase} is null. */ - public Object resolveRemoteReference(String linkBase, String linkRef) - { - if (linkBase == null) - { + public Object resolveRemoteReference(String linkBase, String linkRef) { + if (linkBase == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { // See if it's in the cache. If not, requestFile will start another thread to retrieve it and return null. URL url = WorldWind.getDataFileStore().requestFile(linkBase); - if (url == null) + if (url == null) { return null; + } // It's in the cache. If it's a COLLADA file try to parse it so we can search for the specified reference. // If it's not COLLADA, just return the url for the cached file. String contentType = WorldWind.getDataFileStore().getContentType(linkBase); - if (contentType == null) - { + if (contentType == null) { String suffix = WWIO.getSuffix(linkBase.split(";")[0]); // strip of trailing garbage - if (!WWUtil.isEmpty(suffix)) + if (!WWUtil.isEmpty(suffix)) { contentType = WWIO.makeMimeTypeForSuffix(suffix); + } } - if (!this.canParseContentType(contentType)) + if (!this.canParseContentType(contentType)) { return url; + } // If the file is a COLLADA document, attempt to open it. We can't open it as a File with createAndParse // because the ColladaRoot that will be created needs to have the remote address in order to resolve any @@ -644,13 +636,12 @@ public Object resolveRemoteReference(String linkBase, String linkRef) WorldWind.getSessionCache().put(linkBase, refRoot); // Now check the newly opened COLLADA file for the referenced item, if a reference was specified. - if (linkRef != null) + if (linkRef != null) { return refRoot.getItemByID(linkRef); - else + } else { return refRoot; - } - catch (Exception e) - { + } + } catch (Exception e) { String message = Logging.getMessage("generic.UnableToResolveReference", linkBase + "/" + linkRef); Logging.logger().warning(message); return null; @@ -665,40 +656,35 @@ public Object resolveRemoteReference(String linkBase, String linkRef) * * @return {@code true} if {@code mimeType} can be parsed as COLLADA. */ - protected boolean canParseContentType(String mimeType) - { + protected boolean canParseContentType(String mimeType) { return ColladaConstants.COLLADA_MIME_TYPE.equals(mimeType) - || "text/plain".equals(mimeType) || "text/xml".equals(mimeType); + || "text/plain".equals(mimeType) || "text/xml".equals(mimeType); } /** * Open and parse the specified file expressed as a file: URL.. * - * @param url the URL of the file to open, expressed as a URL with a scheme of "file". + * @param url the URL of the file to open, expressed as a URL with a scheme of "file". * @param linkBase the original address of the document if the file is a retrieved and cached file. * * @return A {@code ColladaRoot} representing the file's COLLADA contents. * - * @throws IOException if an I/O error occurs during opening and parsing. + * @throws IOException if an I/O error occurs during opening and parsing. * @throws XMLStreamException if a server parsing error is encountered. */ protected ColladaRoot parseCachedColladaFile(URL url, String linkBase) - throws IOException, XMLStreamException - { + throws IOException, XMLStreamException { ColladaDoc colladaDoc; InputStream refStream = url.openStream(); colladaDoc = new ColladaInputStream(refStream, WWIO.makeURI(linkBase)); - try - { + try { ColladaRoot refRoot = new ColladaRoot(colladaDoc); refRoot.parse(); // also closes the URL's stream return refRoot; - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { refStream.close(); // parsing failed, so explicitly close the stream throw e; } @@ -712,8 +698,7 @@ protected ColladaRoot parseCachedColladaFile(URL url, String linkBase) * * @return a new event reader, or null if the source type cannot be determined. */ - protected XMLEventReader createReader(Object docSource) - { + protected XMLEventReader createReader(Object docSource) { return WWXML.openEventReader(docSource, true); } @@ -725,19 +710,15 @@ protected XMLEventReader createReader(Object docSource) * * @return a new parser context. */ - protected ColladaParserContext createParserContext(XMLEventReader reader) - { - ColladaParserContext ctx = (ColladaParserContext) - XMLEventParserContextFactory.createParserContext(ColladaConstants.COLLADA_MIME_TYPE, + protected ColladaParserContext createParserContext(XMLEventReader reader) { + ColladaParserContext ctx = (ColladaParserContext) XMLEventParserContextFactory.createParserContext(ColladaConstants.COLLADA_MIME_TYPE, this.getNamespaceURI()); - if (ctx == null) - { + if (ctx == null) { // Register a parser context for this root's default namespace - String[] mimeTypes = new String[] {ColladaConstants.COLLADA_MIME_TYPE}; + String[] mimeTypes = new String[]{ColladaConstants.COLLADA_MIME_TYPE}; XMLEventParserContextFactory.addParserContext(mimeTypes, new ColladaParserContext(this.getNamespaceURI())); - ctx = (ColladaParserContext) - XMLEventParserContextFactory.createParserContext(ColladaConstants.COLLADA_MIME_TYPE, + ctx = (ColladaParserContext) XMLEventParserContextFactory.createParserContext(ColladaConstants.COLLADA_MIME_TYPE, this.getNamespaceURI()); } @@ -752,47 +733,40 @@ protected ColladaParserContext createParserContext(XMLEventReader reader) * * @param args optional arguments to pass to parsers of sub-elements. * - * @return this if parsing is successful, otherwise null. + * @return this if parsing is successful, otherwise null. * * @throws XMLStreamException if an exception occurs while attempting to read the event stream. */ - public ColladaRoot parse(Object... args) throws XMLStreamException - { + public ColladaRoot parse(Object... args) throws XMLStreamException { ColladaParserContext ctx = this.parserContext; - try - { - for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + try { + for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } // Allow a element in any namespace - if (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals("COLLADA")) - { + if (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals("COLLADA")) { super.parse(ctx, event, args); return this; } } - } - finally - { + } finally { ctx.getEventReader().close(); this.closeEventStream(); } return null; } - /** Closes the event stream associated with this context's XML event reader. */ - protected void closeEventStream() - { - try - { + /** + * Closes the event stream associated with this context's XML event reader. + */ + protected void closeEventStream() { + try { this.eventStream.close(); this.eventStream = null; - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionClosingXmlEventReader"); Logging.logger().warning(message); } @@ -803,10 +777,8 @@ protected void closeEventStream() * * @return The COLLADA scene, or null if there is no scene. */ - public ColladaScene getScene() - { - if (!this.sceneFetched) - { + public ColladaScene getScene() { + if (!this.sceneFetched) { this.scene = (ColladaScene) this.getField("scene"); this.sceneFetched = true; } @@ -818,15 +790,12 @@ public ColladaScene getScene() * * @return The asset field, or null if the field has not been set. */ - public ColladaAsset getAsset() - { + public ColladaAsset getAsset() { return (ColladaAsset) this.getField("asset"); } - public Box getLocalExtent(ColladaTraversalContext tc) - { - if (tc == null) - { + public Box getLocalExtent(ColladaTraversalContext tc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -837,25 +806,29 @@ public Box getLocalExtent(ColladaTraversalContext tc) return scene != null ? scene.getLocalExtent(tc) : null; } - /** {@inheritDoc} Renders the scene contained in this document. */ - public void preRender(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} Renders the scene contained in this document. + */ + public void preRender(ColladaTraversalContext tc, DrawContext dc) { tc.multiplyMatrix(this.getMatrix()); // COLLADA doc contains at most one scene. See COLLADA spec pg 5-67. ColladaScene scene = this.getScene(); - if (scene != null) + if (scene != null) { scene.preRender(tc, dc); + } } - /** {@inheritDoc} Renders the scene contained in this document. */ - public void render(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} Renders the scene contained in this document. + */ + public void render(ColladaTraversalContext tc, DrawContext dc) { tc.multiplyMatrix(this.getMatrix()); ColladaScene scene = this.getScene(); - if (scene != null) + if (scene != null) { scene.render(tc, dc); + } } /** @@ -863,29 +836,33 @@ public void render(ColladaTraversalContext tc, DrawContext dc) * * @return Transform matrix. */ - protected Matrix getMatrix() - { + protected Matrix getMatrix() { // If the matrix has already been computed then just return the cached value. - if (this.matrix != null) + if (this.matrix != null) { return this.matrix; + } Matrix m = Matrix.IDENTITY; - if (this.heading != null) + if (this.heading != null) { m = m.multiply(Matrix.fromRotationZ(Angle.POS360.subtract(this.heading))); + } - if (this.pitch != null) + if (this.pitch != null) { m = m.multiply(Matrix.fromRotationX(this.pitch)); + } - if (this.roll != null) + if (this.roll != null) { m = m.multiply(Matrix.fromRotationY(this.roll)); + } // Apply scaling factor to convert file units to meters. double scale = this.getScale(); m = m.multiply(Matrix.fromScale(scale)); - if (this.modelScale != null) + if (this.modelScale != null) { m = m.multiply(Matrix.fromScale(this.modelScale)); + } this.matrix = m; return m; @@ -897,10 +874,8 @@ protected Matrix getMatrix() * * @return Scale applied to the document. Returns 1.0 if the document does not specify a scale. */ - protected double getScale() - { - if (!this.scaleFetched) - { + protected double getScale() { + if (!this.scaleFetched) { this.scale = this.computeScale(); this.scaleFetched = true; } @@ -912,23 +887,23 @@ protected double getScale() * * @return Scale for this document, or 1.0 if no scale is defined. */ - protected double computeScale() - { + protected double computeScale() { Double scale = null; ColladaAsset asset = this.getAsset(); - if (asset != null) - { + if (asset != null) { ColladaUnit unit = asset.getUnit(); - if (unit != null) + if (unit != null) { scale = unit.getMeter(); + } } return (scale != null) ? scale : 1.0; } - /** Clear cached values. Values will be recomputed the next time this document is rendered. */ - protected void reset() - { + /** + * Clear cached values. Values will be recomputed the next time this document is rendered. + */ + protected void reset() { this.matrix = null; } @@ -937,8 +912,7 @@ protected void reset() * * @return The parser context used to parse the document. */ - protected XMLEventParserContext getParserContext() - { + protected XMLEventParserContext getParserContext() { return this.parserContext; } @@ -949,8 +923,7 @@ protected XMLEventParserContext getParserContext() * * @return the element requested, or null if there is no corresponding element in the document. */ - public Object getItemByID(String id) - { + public Object getItemByID(String id) { return id != null ? this.getParserContext().getIdTable().get(id) : null; } @@ -965,18 +938,19 @@ public Object getItemByID(String id) * * @throws IOException If an error occurs while attempting to resolve the resource. */ - public String getSupportFilePath(String link) throws IOException - { + public String getSupportFilePath(String link) throws IOException { String filePath = null; // Use the resource resolver to find the file. ColladaResourceResolver resolver = this.getResourceResolver(); - if (resolver != null) + if (resolver != null) { filePath = resolver.resolveFilePath(link); + } // If the resolver failed to find the file then attempt to resolve the reference relative to the document. - if (filePath == null) + if (filePath == null) { filePath = this.getColladaDoc().getSupportFilePath(link); + } return filePath; } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaSampler2D.java b/src/gov/nasa/worldwind/ogc/collada/ColladaSampler2D.java index 701fb1517a..d4cfcfe646 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaSampler2D.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaSampler2D.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaSampler2D.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaSampler2D extends ColladaAbstractObject -{ +public class ColladaSampler2D extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaSampler2D(String ns) - { + public ColladaSampler2D(String ns) { super(ns); } @@ -29,8 +27,7 @@ public ColladaSampler2D(String ns) * * @return The value of the source field, or null if the field is not set. */ - public ColladaSource getSource() - { + public ColladaSource getSource() { return (ColladaSource) this.getField("source"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaScene.java b/src/gov/nasa/worldwind/ogc/collada/ColladaScene.java index c5a324c084..fc289dd591 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaScene.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaScene.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.geom.Box; @@ -17,11 +16,15 @@ * @author pabercrombie * @version $Id: ColladaScene.java 1696 2013-10-31 18:46:55Z tgaskins $ */ -public class ColladaScene extends ColladaAbstractObject implements ColladaRenderable -{ - /** Flag to indicate that the scene has been fetched from the hash map. */ +public class ColladaScene extends ColladaAbstractObject implements ColladaRenderable { + + /** + * Flag to indicate that the scene has been fetched from the hash map. + */ protected boolean sceneFetched = false; - /** Cached value of the instance_visual_scene field. */ + /** + * Cached value of the instance_visual_scene field. + */ protected ColladaInstanceVisualScene instanceVisualScene; /** @@ -29,8 +32,7 @@ public class ColladaScene extends ColladaAbstractObject implements ColladaRender * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaScene(String ns) - { + public ColladaScene(String ns) { super(ns); } @@ -39,20 +41,16 @@ public ColladaScene(String ns) * * @return The value of the instance_visual_scene field, or null if the field is not set. */ - protected ColladaInstanceVisualScene getInstanceVisualScene() - { - if (!this.sceneFetched) - { + protected ColladaInstanceVisualScene getInstanceVisualScene() { + if (!this.sceneFetched) { this.instanceVisualScene = (ColladaInstanceVisualScene) this.getField("instance_visual_scene"); this.sceneFetched = true; } return this.instanceVisualScene; } - public Box getLocalExtent(ColladaTraversalContext tc) - { - if (tc == null) - { + public Box getLocalExtent(ColladaTraversalContext tc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -63,19 +61,23 @@ public Box getLocalExtent(ColladaTraversalContext tc) return sceneInstance != null ? sceneInstance.getLocalExtent(tc) : null; } - /** {@inheritDoc} */ - public void preRender(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void preRender(ColladaTraversalContext tc, DrawContext dc) { ColladaInstanceVisualScene sceneInstance = this.getInstanceVisualScene(); - if (sceneInstance != null) + if (sceneInstance != null) { sceneInstance.preRender(tc, dc); + } } - /** {@inheritDoc} */ - public void render(ColladaTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(ColladaTraversalContext tc, DrawContext dc) { ColladaInstanceVisualScene sceneInstance = this.getInstanceVisualScene(); - if (sceneInstance != null) + if (sceneInstance != null) { sceneInstance.render(tc, dc); + } } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaSource.java b/src/gov/nasa/worldwind/ogc/collada/ColladaSource.java index fdfc5e631d..e356e1b36e 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaSource.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaSource.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaSource.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaSource extends ColladaAbstractObject -{ +public class ColladaSource extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaSource(String ns) - { + public ColladaSource(String ns) { super(ns); } @@ -28,14 +26,14 @@ public ColladaSource(String ns) * Indicates the value of the accessor field of the technique_common field. * * @return The value of the accessor field, or null if either the accessor or technique_common - * is not set. + * is not set. */ - public ColladaAccessor getAccessor() - { + public ColladaAccessor getAccessor() { // Handles only the COLLADA Common profile ColladaTechniqueCommon technique = (ColladaTechniqueCommon) this.getField("technique_common"); - if (technique == null) + if (technique == null) { return null; + } return (ColladaAccessor) technique.getField("accessor"); } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaSurface.java b/src/gov/nasa/worldwind/ogc/collada/ColladaSurface.java index 3f5a3e3b56..6ebc9cad87 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaSurface.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaSurface.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaSurface.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaSurface extends ColladaAbstractObject -{ +public class ColladaSurface extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaSurface(String ns) - { + public ColladaSurface(String ns) { super(ns); } @@ -29,8 +27,7 @@ public ColladaSurface(String ns) * * @return The init_from field, or null if it is not set. */ - public String getInitFrom() - { + public String getInitFrom() { return (String) this.getField("init_from"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaTechnique.java b/src/gov/nasa/worldwind/ogc/collada/ColladaTechnique.java index bc5032cbb8..4120fcb703 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaTechnique.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaTechnique.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaTechnique.java 675 2012-07-02 18:47:47Z pabercrombie $ */ -public class ColladaTechnique extends ColladaAbstractParamContainer -{ +public class ColladaTechnique extends ColladaAbstractParamContainer { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaTechnique(String ns) - { + public ColladaTechnique(String ns) { super(ns); } @@ -29,15 +27,16 @@ public ColladaTechnique(String ns) * * @return The shader for this technique, or null if the shader is not set, or is not supported. */ - public ColladaAbstractShader getShader() - { + public ColladaAbstractShader getShader() { Object o = this.getField("lambert"); - if (o != null) + if (o != null) { return (ColladaAbstractShader) o; + } o = this.getField("phong"); - if (o != null) + if (o != null) { return (ColladaAbstractShader) o; + } // TODO handle other shaders return null; @@ -48,8 +47,7 @@ public ColladaAbstractShader getShader() * * @return The value of the profile field, or null if the field is not set. */ - public String getProfile() - { + public String getProfile() { return (String) this.getField("profile"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaTechniqueCommon.java b/src/gov/nasa/worldwind/ogc/collada/ColladaTechniqueCommon.java index 1157531a58..33447364b1 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaTechniqueCommon.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaTechniqueCommon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import java.util.*; @@ -14,9 +13,11 @@ * @author pabercrombie * @version $Id: ColladaTechniqueCommon.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaTechniqueCommon extends ColladaAbstractObject -{ - /** Materials contained by this technique. */ +public class ColladaTechniqueCommon extends ColladaAbstractObject { + + /** + * Materials contained by this technique. + */ protected List materials = new ArrayList(); /** @@ -24,8 +25,7 @@ public class ColladaTechniqueCommon extends ColladaAbstractObject * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaTechniqueCommon(String ns) - { + public ColladaTechniqueCommon(String ns) { super(ns); } @@ -34,21 +34,18 @@ public ColladaTechniqueCommon(String ns) * * @return List of materials. May return an empty list, but never returns null. */ - public List getMaterials() - { + public List getMaterials() { return this.materials; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setField(String keyName, Object value) - { - if (keyName.equals("instance_material")) - { + public void setField(String keyName, Object value) { + if (keyName.equals("instance_material")) { this.materials.add((ColladaInstanceMaterial) value); - } - else - { + } else { super.setField(keyName, value); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaTexture.java b/src/gov/nasa/worldwind/ogc/collada/ColladaTexture.java index bb07b219e1..20b960a6d5 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaTexture.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaTexture.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaTexture.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaTexture extends ColladaAbstractObject -{ +public class ColladaTexture extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaTexture(String ns) - { + public ColladaTexture(String ns) { super(ns); } @@ -29,8 +27,7 @@ public ColladaTexture(String ns) * * @return The texture attribute, or null the attribute is not set. */ - public String getTexture() - { + public String getTexture() { return (String) this.getField("texture"); } @@ -39,8 +36,7 @@ public String getTexture() * * @return The texcoord attribute, or null the attribute is not set. */ - public String getTexCoord() - { + public String getTexCoord() { return (String) this.getField("texcoord"); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaTextureOrColor.java b/src/gov/nasa/worldwind/ogc/collada/ColladaTextureOrColor.java index 714f75424d..c80b9cb0b1 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaTextureOrColor.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaTextureOrColor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import java.awt.*; @@ -14,15 +13,14 @@ * @author pabercrombie * @version $Id: ColladaTextureOrColor.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaTextureOrColor extends ColladaAbstractObject -{ +public class ColladaTextureOrColor extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaTextureOrColor(String ns) - { + public ColladaTextureOrColor(String ns) { super(ns); } @@ -31,8 +29,7 @@ public ColladaTextureOrColor(String ns) * * @return The value of the texture field, or null if the field is not set. */ - public ColladaTexture getTexture() - { + public ColladaTexture getTexture() { return (ColladaTexture) this.getField("texture"); } @@ -41,11 +38,11 @@ public ColladaTexture getTexture() * * @return The value of the color field, or null if the field is not set. */ - public Color getColor() - { + public Color getColor() { ColladaColor color = (ColladaColor) this.getField("color"); - if (color == null) + if (color == null) { return null; + } String colorString = color.getCharacters(); float[] values = this.parseFloatArray(colorString); @@ -65,14 +62,12 @@ public Color getColor() * * @return Parsed float[]. */ - protected float[] parseFloatArray(String floatArrayString) - { + protected float[] parseFloatArray(String floatArrayString) { String[] arrayOfNumbers = floatArrayString.trim().split("\\s+"); float[] floats = new float[arrayOfNumbers.length]; int i = 0; - for (String s : arrayOfNumbers) - { + for (String s : arrayOfNumbers) { floats[i++] = Float.parseFloat(s); } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaTriangles.java b/src/gov/nasa/worldwind/ogc/collada/ColladaTriangles.java index 5dd6446394..7290c8d68f 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaTriangles.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaTriangles.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaTriangles.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaTriangles extends ColladaAbstractGeometry -{ +public class ColladaTriangles extends ColladaAbstractGeometry { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaTriangles(String ns) - { + public ColladaTriangles(String ns) { super(ns); } @@ -30,8 +28,7 @@ public ColladaTriangles(String ns) * @return Three */ @Override - protected int getVerticesPerShape() - { + protected int getVerticesPerShape() { return 3; } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaUnit.java b/src/gov/nasa/worldwind/ogc/collada/ColladaUnit.java index 3f30eae09f..7fd80b05e3 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaUnit.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaUnit.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.util.WWUtil; @@ -14,15 +13,14 @@ * @author pabercrombie * @version $Id: ColladaUnit.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaUnit extends ColladaAbstractObject -{ +public class ColladaUnit extends ColladaAbstractObject { + /** * Construct an instance. * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaUnit(String ns) - { + public ColladaUnit(String ns) { super(ns); } @@ -32,8 +30,7 @@ public ColladaUnit(String ns) * * @return The scaling factor, or null if none is defined. */ - public Double getMeter() - { + public Double getMeter() { String s = (String) this.getField("meter"); return WWUtil.makeDouble(s); } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaUnsupported.java b/src/gov/nasa/worldwind/ogc/collada/ColladaUnsupported.java index 03f1cc9fda..8a904d61fb 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaUnsupported.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaUnsupported.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; /** @@ -12,15 +11,14 @@ * @author pabercrombie * @version $Id: ColladaUnsupported.java 642 2012-06-14 17:31:29Z pabercrombie $ */ -public class ColladaUnsupported extends ColladaAbstractObject -{ +public class ColladaUnsupported extends ColladaAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaUnsupported(String namespaceURI) - { + public ColladaUnsupported(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaVertices.java b/src/gov/nasa/worldwind/ogc/collada/ColladaVertices.java index 9618beade0..e905c9ff4e 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaVertices.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaVertices.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import java.util.*; @@ -14,9 +13,11 @@ * @author pabercrombie * @version $Id: ColladaVertices.java 654 2012-06-25 04:15:52Z pabercrombie $ */ -public class ColladaVertices extends ColladaAbstractObject -{ - /** Inputs to the vertices element. */ +public class ColladaVertices extends ColladaAbstractObject { + + /** + * Inputs to the vertices element. + */ protected List inputs = new ArrayList(); /** @@ -24,8 +25,7 @@ public class ColladaVertices extends ColladaAbstractObject * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaVertices(String ns) - { + public ColladaVertices(String ns) { super(ns); } @@ -34,8 +34,7 @@ public ColladaVertices(String ns) * * @return Vertex inputs. May return an empty list, but never returns null. */ - public List getInputs() - { + public List getInputs() { return this.inputs; } @@ -44,26 +43,23 @@ public List getInputs() * * @return The input labeled with semantic "POSITION", or null if no such input is set. */ - public ColladaInput getPositionInput() - { - for (ColladaInput input : this.getInputs()) - { - if ("POSITION".equals(input.getSemantic())) + public ColladaInput getPositionInput() { + for (ColladaInput input : this.getInputs()) { + if ("POSITION".equals(input.getSemantic())) { return input; + } } return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setField(String keyName, Object value) - { - if (keyName.equals("input")) - { + public void setField(String keyName, Object value) { + if (keyName.equals("input")) { this.inputs.add((ColladaInput) value); - } - else - { + } else { super.setField(keyName, value); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/ColladaVisualScene.java b/src/gov/nasa/worldwind/ogc/collada/ColladaVisualScene.java index 4998905827..a59804074d 100644 --- a/src/gov/nasa/worldwind/ogc/collada/ColladaVisualScene.java +++ b/src/gov/nasa/worldwind/ogc/collada/ColladaVisualScene.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada; import gov.nasa.worldwind.geom.Box; @@ -19,9 +18,11 @@ * @author pabercrombie * @version $Id: ColladaVisualScene.java 1696 2013-10-31 18:46:55Z tgaskins $ */ -public class ColladaVisualScene extends ColladaAbstractObject implements ColladaRenderable -{ - /** Nodes in this scene. */ +public class ColladaVisualScene extends ColladaAbstractObject implements ColladaRenderable { + + /** + * Nodes in this scene. + */ protected List nodes = new ArrayList(); /** @@ -29,8 +30,7 @@ public class ColladaVisualScene extends ColladaAbstractObject implements Collada * * @param ns the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public ColladaVisualScene(String ns) - { + public ColladaVisualScene(String ns) { super(ns); } @@ -39,60 +39,55 @@ public ColladaVisualScene(String ns) * * @return List of nodes. May return an empty list, but never returns null. */ - public List getNodes() - { + public List getNodes() { return this.nodes; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setField(String keyName, Object value) - { - if (keyName.equals("node")) - { + public void setField(String keyName, Object value) { + if (keyName.equals("node")) { this.nodes.add((ColladaNode) value); - } - else - { + } else { super.setField(keyName, value); } } @Override - public Box getLocalExtent(ColladaTraversalContext tc) - { - if (tc == null) - { + public Box getLocalExtent(ColladaTraversalContext tc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } ArrayList extents = new ArrayList(); - for (ColladaNode node : this.getNodes()) - { + for (ColladaNode node : this.getNodes()) { Box extent = node.getLocalExtent(tc); - if (extent != null) + if (extent != null) { extents.add(extent); + } } return extents.isEmpty() ? null : Box.union(extents); } - /** {@inheritDoc} Renders all nodes in this scene. */ - public void preRender(ColladaTraversalContext tc, DrawContext dc) - { - for (ColladaNode node : this.getNodes()) - { + /** + * {@inheritDoc} Renders all nodes in this scene. + */ + public void preRender(ColladaTraversalContext tc, DrawContext dc) { + for (ColladaNode node : this.getNodes()) { node.preRender(tc, dc); } } - /** {@inheritDoc} Renders all nodes in this scene. */ - public void render(ColladaTraversalContext tc, DrawContext dc) - { - for (ColladaNode node : this.getNodes()) - { + /** + * {@inheritDoc} Renders all nodes in this scene. + */ + public void render(ColladaTraversalContext tc, DrawContext dc) { + for (ColladaNode node : this.getNodes()) { node.render(tc, dc); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/impl/ColladaController.java b/src/gov/nasa/worldwind/ogc/collada/impl/ColladaController.java index d1d1929b2c..c03e7424b5 100644 --- a/src/gov/nasa/worldwind/ogc/collada/impl/ColladaController.java +++ b/src/gov/nasa/worldwind/ogc/collada/impl/ColladaController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada.impl; import gov.nasa.worldwind.ogc.collada.ColladaRoot; @@ -17,11 +16,15 @@ * @author pabercrombie * @version $Id: ColladaController.java 661 2012-06-26 18:02:23Z pabercrombie $ */ -public class ColladaController implements Renderable, PreRenderable -{ - /** Collada document rendered by this controller. */ +public class ColladaController implements Renderable, PreRenderable { + + /** + * Collada document rendered by this controller. + */ protected ColladaRoot colladaRoot; - /** Traversal context used to render the document. */ + /** + * Traversal context used to render the document. + */ protected ColladaTraversalContext tc; /** @@ -29,8 +32,7 @@ public class ColladaController implements Renderable, PreRenderable * * @param root Parsed COLLADA document to render. */ - public ColladaController(ColladaRoot root) - { + public ColladaController(ColladaRoot root) { this.setColladaRoot(root); this.setTraversalContext(new ColladaTraversalContext()); } @@ -40,8 +42,7 @@ public ColladaController(ColladaRoot root) * * @return The COLLADA document referenced by this controller. */ - public ColladaRoot getColladaRoot() - { + public ColladaRoot getColladaRoot() { return this.colladaRoot; } @@ -50,10 +51,8 @@ public ColladaRoot getColladaRoot() * * @param colladaRoot New COLLADA document to render. */ - public void setColladaRoot(ColladaRoot colladaRoot) - { - if (colladaRoot == null) - { + public void setColladaRoot(ColladaRoot colladaRoot) { + if (colladaRoot == null) { String msg = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -67,8 +66,7 @@ public void setColladaRoot(ColladaRoot colladaRoot) * * @return The active traversal context. */ - public ColladaTraversalContext getTraversalContext() - { + public ColladaTraversalContext getTraversalContext() { return this.tc; } @@ -77,10 +75,8 @@ public ColladaTraversalContext getTraversalContext() * * @param tc New traversal context. */ - public void setTraversalContext(ColladaTraversalContext tc) - { - if (tc == null) - { + public void setTraversalContext(ColladaTraversalContext tc) { + if (tc == null) { String msg = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -89,16 +85,18 @@ public void setTraversalContext(ColladaTraversalContext tc) this.tc = tc; } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { this.initializeTraversalContext(this.getTraversalContext()); this.colladaRoot.preRender(this.getTraversalContext(), dc); } - /** {@inheritDoc} */ - public void render(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { this.initializeTraversalContext(this.getTraversalContext()); this.colladaRoot.render(this.getTraversalContext(), dc); } @@ -110,8 +108,7 @@ public void render(DrawContext dc) * * @param tc the COLLADA traversal context to initialize. */ - protected void initializeTraversalContext(ColladaTraversalContext tc) - { + protected void initializeTraversalContext(ColladaTraversalContext tc) { tc.initialize(); } } diff --git a/src/gov/nasa/worldwind/ogc/collada/impl/ColladaMeshShape.java b/src/gov/nasa/worldwind/ogc/collada/impl/ColladaMeshShape.java index b9b14235dc..fcb42d3122 100644 --- a/src/gov/nasa/worldwind/ogc/collada/impl/ColladaMeshShape.java +++ b/src/gov/nasa/worldwind/ogc/collada/impl/ColladaMeshShape.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada.impl; import com.jogamp.common.nio.Buffers; @@ -35,47 +34,49 @@ * @author pabercrombie * @version $Id: ColladaMeshShape.java 2216 2014-08-11 20:29:24Z tgaskins $ */ -public class ColladaMeshShape extends AbstractGeneralShape -{ +public class ColladaMeshShape extends AbstractGeneralShape { + /** * Class to represent an instance of the mesh to be drawn as an ordered renderable. We can't use the mesh itself as * the ordered renderable because it may be drawn multiple times with different transforms. */ - public static class OrderedMeshShape implements OrderedRenderable - { - /** Shape to render. */ + public static class OrderedMeshShape implements OrderedRenderable { + + /** + * Shape to render. + */ protected ColladaMeshShape mesh; - /** Distance from the eye to the shape's reference position. */ + /** + * Distance from the eye to the shape's reference position. + */ protected double eyeDistance; - /** Transform applied to this instance of the mesh. */ + /** + * Transform applied to this instance of the mesh. + */ protected Matrix renderMatrix; /** * Create a new ordered renderable. * - * @param mesh Mesh shape to render. + * @param mesh Mesh shape to render. * @param renderMatrix Transform matrix to apply when rendering the shape. - * @param eyeDistance Distance from the eye position to the shape's reference position. + * @param eyeDistance Distance from the eye position to the shape's reference position. */ - public OrderedMeshShape(ColladaMeshShape mesh, Matrix renderMatrix, double eyeDistance) - { + public OrderedMeshShape(ColladaMeshShape mesh, Matrix renderMatrix, double eyeDistance) { this.mesh = mesh; this.eyeDistance = eyeDistance; this.renderMatrix = renderMatrix; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { this.mesh.pick(dc, pickPoint, this.renderMatrix); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { this.mesh.render(dc, this.renderMatrix); } } @@ -84,16 +85,15 @@ public void render(DrawContext dc) * This class holds globe-specific data for this shape. It's managed via the shape-data cache in {@link * gov.nasa.worldwind.render.AbstractShape.AbstractShapeData}. */ - protected static class ShapeData extends AbstractGeneralShape.ShapeData - { + protected static class ShapeData extends AbstractGeneralShape.ShapeData { + /** * Construct a cache entry for this shape. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape this shape. */ - public ShapeData(DrawContext dc, AbstractGeneralShape shape) - { + public ShapeData(DrawContext dc, AbstractGeneralShape shape) { super(dc, shape); } @@ -108,22 +108,34 @@ public ShapeData(DrawContext dc, AbstractGeneralShape shape) * matrix, and {@link #surfaceOrientationMatrix}. */ protected Matrix renderMatrix; - /** Cached reference center for the shape. */ + /** + * Cached reference center for the shape. + */ protected Vec4 referenceCenter; } - /** Geometry and attributes of a COLLADA {@code triangles} or {@code lines} element. */ - protected static class Geometry - { - /** Collada element that defines this geometry. */ + /** + * Geometry and attributes of a COLLADA {@code triangles} or {@code lines} element. + */ + protected static class Geometry { + + /** + * Collada element that defines this geometry. + */ protected ColladaAbstractGeometry colladaGeometry; - /** Offset (in vertices) into the coord, normal, and texcoord buffers of this coordinates for this geometry. */ + /** + * Offset (in vertices) into the coord, normal, and texcoord buffers of this coordinates for this geometry. + */ protected int offset = -1; - /** Texture applied to this geometry. */ + /** + * Texture applied to this geometry. + */ protected WWTexture texture; - /** Material applied to this geometry. */ + /** + * Material applied to this geometry. + */ protected Material material; /** @@ -140,43 +152,36 @@ protected static class Geometry * * @param geometry COLLADA geometry to render. */ - public Geometry(ColladaAbstractGeometry geometry) - { + public Geometry(ColladaAbstractGeometry geometry) { this.colladaGeometry = geometry; } } - protected static class ExtentCacheKey - { + protected static class ExtentCacheKey { + protected GlobeStateKey globeStateKey; protected Matrix matrix; - public ExtentCacheKey(Globe globe, Matrix matrix) - { + public ExtentCacheKey(Globe globe, Matrix matrix) { this.globeStateKey = globe.getGlobeStateKey(); this.matrix = matrix; } @Override - public boolean equals(Object o) - { - if (this == o) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } ExtentCacheKey that = (ExtentCacheKey) o; - if (globeStateKey != null ? !globeStateKey.equals(that.globeStateKey) : that.globeStateKey != null) - { + if (globeStateKey != null ? !globeStateKey.equals(that.globeStateKey) : that.globeStateKey != null) { return false; } - if (matrix != null ? !matrix.equals(that.matrix) : that.matrix != null) - { + if (matrix != null ? !matrix.equals(that.matrix) : that.matrix != null) { return false; } @@ -184,28 +189,39 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result = globeStateKey != null ? globeStateKey.hashCode() : 0; result = 31 * result + (matrix != null ? matrix.hashCode() : 0); return result; } } - /** OpenGL element type for this shape (GL.GL_LINES or GL.GL_TRIANGLES). */ + /** + * OpenGL element type for this shape (GL.GL_LINES or GL.GL_TRIANGLES). + */ protected int elementType; - /** Number of vertices per shape. Two in the case of a line mesh, three in the case of a triangle mesh. */ + /** + * Number of vertices per shape. Two in the case of a line mesh, three in the case of a triangle mesh. + */ protected int vertsPerShape; - /** Total number of shapes (lines or triangles) in this mesh. Equal to the sum of the shapes in each geometry. */ + /** + * Total number of shapes (lines or triangles) in this mesh. Equal to the sum of the shapes in each geometry. + */ protected int shapeCount; - /** Material applied to this mesh. */ + /** + * Material applied to this mesh. + */ protected ColladaBindMaterial bindMaterial; - /** Geometry objects that describe different parts of the mesh. */ + /** + * Geometry objects that describe different parts of the mesh. + */ protected List geometries; - /** Cache of shape extents computed for different transform matrices. */ + /** + * Cache of shape extents computed for different transform matrices. + */ protected Map extentCache = new HashMap(); /** @@ -213,25 +229,32 @@ public int hashCode() * normals, and the third part contains texture coordinates. */ protected FloatBuffer coordBuffer; - /** The slice of the {@link #coordBuffer} that contains normals. */ + /** + * The slice of the {@link #coordBuffer} that contains normals. + */ protected FloatBuffer normalBuffer; - /** The index of the first normal in the {@link #coordBuffer}. */ + /** + * The index of the first normal in the {@link #coordBuffer}. + */ protected int normalBufferPosition; - /** Texture coordinates for all geometries in this shape. */ + /** + * Texture coordinates for all geometries in this shape. + */ protected FloatBuffer textureCoordsBuffer; - /** The index of the first texture coordinate in the {@link #coordBuffer}. */ + /** + * The index of the first texture coordinate in the {@link #coordBuffer}. + */ protected int texCoordBufferPosition; /** * Create a triangle mesh shape. * - * @param geometries COLLADA elements that defines geometry for this shape. Must contain at least one element. + * @param geometries COLLADA elements that defines geometry for this shape. Must contain at least one element. * @param bindMaterial Material applied to the mesh. May be null. * @return The resulting shape. */ public static ColladaMeshShape createTriangleMesh(List geometries, - ColladaBindMaterial bindMaterial) - { + ColladaBindMaterial bindMaterial) { ColladaMeshShape shape = new ColladaMeshShape(geometries); shape.bindMaterial = bindMaterial; @@ -244,13 +267,12 @@ public static ColladaMeshShape createTriangleMesh(List geometr /** * Create a line mesh shape. * - * @param geometries COLLADA elements that defines geometry for this shape. Must contain at least one element. + * @param geometries COLLADA elements that defines geometry for this shape. Must contain at least one element. * @param bindMaterial Material applied to the mesh. May be null. * @return The resulting shape. */ public static ColladaMeshShape createLineMesh(List geometries, - ColladaBindMaterial bindMaterial) - { + ColladaBindMaterial bindMaterial) { ColladaMeshShape shape = new ColladaMeshShape(geometries); shape.bindMaterial = bindMaterial; @@ -264,20 +286,17 @@ public static ColladaMeshShape createLineMesh(List geometries, * Create an instance of the shape. * * @param geometries Geometries to render. All geometries must be of the same type (either {@link ColladaTriangles} - * or {@link ColladaLines}. + * or {@link ColladaLines}. */ - protected ColladaMeshShape(List geometries) - { - if (WWUtil.isEmpty(geometries)) - { + protected ColladaMeshShape(List geometries) { + if (WWUtil.isEmpty(geometries)) { String message = Logging.getMessage("generic.ListIsEmpty"); Logging.logger().severe(message); throw new IllegalStateException(message); } this.geometries = new ArrayList(geometries.size()); - for (ColladaAbstractGeometry geometry : geometries) - { + for (ColladaAbstractGeometry geometry : geometries) { this.geometries.add(new Geometry(geometry)); this.shapeCount += geometry.getCount(); } @@ -293,17 +312,16 @@ protected ColladaMeshShape(List geometries) * @return Always returns {@code null}. */ @Override - public List intersect(Line line, Terrain terrain) throws InterruptedException - { + public List intersect(Line line, Terrain terrain) throws InterruptedException { return null; } - /** {@inheritDoc} Overridden to invalidate cached geometry when the model position is changed. */ + /** + * {@inheritDoc} Overridden to invalidate cached geometry when the model position is changed. + */ @Override - public void setModelPosition(Position modelPosition) - { - if (modelPosition != this.modelPosition) - { + public void setModelPosition(Position modelPosition) { + if (modelPosition != this.modelPosition) { this.modelPosition = modelPosition; this.reset(); } @@ -312,21 +330,17 @@ public void setModelPosition(Position modelPosition) ////////////////////////////////////////////////////////////////////// // Rendering ////////////////////////////////////////////////////////////////////// - @Override - protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) - { + protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = super.beginDrawing(dc, attrMask); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Push an identity texture matrix. This prevents drawSides() from leaking GL texture matrix state. The // texture matrix stack is popped from OGLStackHandler.pop(), in the finally block below. ogsh.pushTextureIdentity(gl); - if (this.mustApplyLighting(dc, null)) - { + if (this.mustApplyLighting(dc, null)) { // We apply a scale transform on the modelview matrix, so the normal vectors must be re-normalized // before lighting is computed. gl.glEnable(GL2.GL_NORMALIZE); @@ -339,14 +353,12 @@ protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) /** * Render the mesh in a given orientation. * - * @param dc Current draw context. + * @param dc Current draw context. * @param matrix Matrix to be multiply with the current modelview matrix to orient the mesh. */ - public void render(DrawContext dc, Matrix matrix) - { + public void render(DrawContext dc, Matrix matrix) { this.currentData = (AbstractShapeData) this.shapeDataCache.getEntry(dc.getGlobe()); - if (this.currentData == null) - { + if (this.currentData == null) { this.currentData = this.createCacheEntry(dc); this.shapeDataCache.addEntry(this.currentData); } @@ -360,8 +372,7 @@ public void render(DrawContext dc, Matrix matrix) // been built, in which case the extent will be computed by createMinimalGeometry. ExtentCacheKey extentCacheKey = new ExtentCacheKey(dc.getGlobe(), matrix); Extent extent = this.extentCache.get(extentCacheKey); - if (extent == null) - { + if (extent == null) { extent = this.computeExtent(dc); this.extentCache.put(extentCacheKey, extent); } @@ -373,29 +384,24 @@ public void render(DrawContext dc, Matrix matrix) /** * Pick the mesh in a given orientation. * - * @param dc Current draw context. + * @param dc Current draw context. * @param pickPoint Current pick point. - * @param matrix Matrix to multiply with the current modelview matrix to orient the mesh. + * @param matrix Matrix to multiply with the current modelview matrix to orient the mesh. */ - public void pick(DrawContext dc, Point pickPoint, Matrix matrix) - { + public void pick(DrawContext dc, Point pickPoint, Matrix matrix) { // This method is called only when ordered renderables are being drawn. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.render(dc, matrix); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } @@ -406,38 +412,36 @@ public void pick(DrawContext dc, Point pickPoint, Matrix matrix) * renderable queue. */ @Override - protected void drawBatched(DrawContext dc) - { + protected void drawBatched(DrawContext dc) { // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - if (!dc.isPickingMode()) - { - while (nextItem != null && nextItem.getClass() == OrderedMeshShape.class) - { + if (!dc.isPickingMode()) { + while (nextItem != null && nextItem.getClass() == OrderedMeshShape.class) { OrderedMeshShape or = (OrderedMeshShape) nextItem; ColladaMeshShape shape = or.mesh; - if (!shape.isEnableBatchRendering()) + if (!shape.isEnableBatchRendering()) { break; + } dc.pollOrderedRenderables(); // take it off the queue shape.doDrawOrderedRenderable(dc, this.pickSupport, or.renderMatrix); nextItem = dc.peekOrderedRenderables(); } - } - else if (this.isEnableBatchPicking()) - { + } else if (this.isEnableBatchPicking()) { super.drawBatched(dc); - while (nextItem != null && nextItem.getClass() == this.getClass()) - { + while (nextItem != null && nextItem.getClass() == this.getClass()) { OrderedMeshShape or = (OrderedMeshShape) nextItem; ColladaMeshShape shape = or.mesh; - if (!shape.isEnableBatchRendering() || !shape.isEnableBatchPicking()) + if (!shape.isEnableBatchRendering() || !shape.isEnableBatchPicking()) { break; + } if (shape.pickLayer != this.pickLayer) // batch pick only within a single layer + { break; + } dc.pollOrderedRenderables(); // take it off the queue shape.doDrawOrderedRenderable(dc, this.pickSupport, or.renderMatrix); @@ -447,9 +451,10 @@ else if (this.isEnableBatchPicking()) } } - /** {@inheritDoc} */ - protected boolean doMakeOrderedRenderable(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected boolean doMakeOrderedRenderable(DrawContext dc) { // Clear cached extents because we are creating new geometry. this.extentCache.clear(); @@ -457,11 +462,13 @@ protected boolean doMakeOrderedRenderable(DrawContext dc) this.createMinimalGeometry(dc, (ShapeData) this.getCurrent()); // If the shape is less that a pixel in size, don't render it. - if (this.getCurrent().getExtent() == null || dc.isSmall(this.getExtent(), 1)) + if (this.getCurrent().getExtent() == null || dc.isSmall(this.getExtent(), 1)) { return false; + } - if (!this.intersectsFrustum(dc)) + if (!this.intersectsFrustum(dc)) { return false; + } this.createFullGeometry(dc); @@ -469,12 +476,12 @@ protected boolean doMakeOrderedRenderable(DrawContext dc) } /** - * {@inheritDoc} Overridden because this shape uses {@link gov.nasa.worldwind.ogc.collada.impl.ColladaMeshShape.OrderedMeshShape} - * to represent this drawn instance of the mesh in the ordered renderable queue. + * {@inheritDoc} Overridden because this shape uses + * {@link gov.nasa.worldwind.ogc.collada.impl.ColladaMeshShape.OrderedMeshShape} to represent this drawn instance of + * the mesh in the ordered renderable queue. */ @Override - protected void addOrderedRenderable(DrawContext dc) - { + protected void addOrderedRenderable(DrawContext dc) { ShapeData current = (ShapeData) this.getCurrent(); double eyeDistance = this.computeEyeDistance(dc); @@ -485,29 +492,31 @@ protected void addOrderedRenderable(DrawContext dc) /** * Draw the shape as an OrderedRenderable, using the specified transform matrix. * - * @param dc Current draw context. + * @param dc Current draw context. * @param pickCandidates Pick candidates for this frame. - * @param matrix Transform matrix to apply before trying shape. m + * @param matrix Transform matrix to apply before trying shape. m */ - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates, Matrix matrix) - { + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates, Matrix matrix) { ShapeData current = (ShapeData) this.getCurrent(); current.renderMatrix = matrix; super.doDrawOrderedRenderable(dc, pickCandidates); } - /** {@inheritDoc} Does nothing, all drawing is performed by {@link #doDrawInterior(gov.nasa.worldwind.render.DrawContext)}. */ + /** + * {@inheritDoc} Does nothing, all drawing is performed by + * {@link #doDrawInterior(gov.nasa.worldwind.render.DrawContext)}. + */ @Override - protected void doDrawOutline(DrawContext dc) - { + protected void doDrawOutline(DrawContext dc) { // Do nothing. All drawing is performed in doDrawInterior } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void doDrawInterior(DrawContext dc) - { + protected void doDrawInterior(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Create an OpenGL stack handler to handle matrix stack push/pop. Explicitly track changes to the OpenGL @@ -515,8 +524,7 @@ protected void doDrawInterior(DrawContext dc) OGLStackHandler stackHandler = new OGLStackHandler(); boolean texturesEnabled = false; boolean cullingEnabled = false; - try - { + try { stackHandler.pushModelview(gl); this.setModelViewMatrix(dc); @@ -529,31 +537,27 @@ protected void doDrawInterior(DrawContext dc) // When drawing with vertex arrays we can bind the vertex buffer once. When using vertex buffer objects // we need to check to make sure that the vbo is available each time through the loop because loading // textures may force vbos out of the cache (see loop below). - if (!this.shouldUseVBOs(dc)) - { + if (!this.shouldUseVBOs(dc)) { FloatBuffer vb = this.coordBuffer; gl.glVertexPointer(ColladaAbstractGeometry.COORDS_PER_VERTEX, GL.GL_FLOAT, 0, vb.rewind()); } - for (Geometry geometry : this.geometries) - { + for (Geometry geometry : this.geometries) { Material nextMaterial = geometry.material != null ? geometry.material : defaultMaterial; // Apply new material if necessary - if (!dc.isPickingMode() && !nextMaterial.equals(activeMaterial)) - { + if (!dc.isPickingMode() && !nextMaterial.equals(activeMaterial)) { this.applyMaterial(dc, nextMaterial); activeMaterial = nextMaterial; } if (!dc.isPickingMode() - && this.mustApplyTexture(geometry) - && this.getTexture(geometry).bind(dc)) // bind initiates retrieval + && this.mustApplyTexture(geometry) + && this.getTexture(geometry).bind(dc)) // bind initiates retrieval { this.getTexture(geometry).applyInternalTransform(dc); - if (!texturesEnabled) - { + if (!texturesEnabled) { gl.glEnable(GL.GL_TEXTURE_2D); gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); texturesEnabled = true; @@ -563,10 +567,8 @@ protected void doDrawInterior(DrawContext dc) gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT); gl.glTexCoordPointer(ColladaAbstractGeometry.TEX_COORDS_PER_VERTEX, GL.GL_FLOAT, 0, - this.textureCoordsBuffer.rewind()); - } - else if (texturesEnabled) - { + this.textureCoordsBuffer.rewind()); + } else if (texturesEnabled) { gl.glDisable(GL.GL_TEXTURE_2D); gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY); texturesEnabled = false; @@ -574,13 +576,10 @@ else if (texturesEnabled) // If this geometry is double sided, then backface culling must be disabled. Otherwise backface culling // must be enabled, because some SketchUp models will not render correctly without it. - if (geometry.doubleSided && cullingEnabled) - { + if (geometry.doubleSided && cullingEnabled) { gl.glDisable(GL.GL_CULL_FACE); cullingEnabled = false; - } - else if (!geometry.doubleSided && !cullingEnabled) - { + } else if (!geometry.doubleSided && !cullingEnabled) { gl.glEnable(GL.GL_CULL_FACE); cullingEnabled = true; } @@ -588,24 +587,21 @@ else if (!geometry.doubleSided && !cullingEnabled) // Look up VBO IDs each time through the loop because binding a texture may bump a VBO out of the cache. // If VBOs are not used, the vertex array is bound once, before the loop. int[] vboIds = null; - if (this.shouldUseVBOs(dc)) - { + if (this.shouldUseVBOs(dc)) { vboIds = this.getVboIds(dc); - if (vboIds == null) - { + if (vboIds == null) { FloatBuffer vb = this.coordBuffer; gl.glVertexPointer(ColladaAbstractGeometry.COORDS_PER_VERTEX, GL.GL_FLOAT, 0, vb.rewind()); } } - if (vboIds != null) + if (vboIds != null) { this.doDrawInteriorVBO(dc, geometry, vboIds); - else + } else { this.doDrawInteriorVA(dc, geometry); + } } - } - finally - { + } finally { // Restore the OpenGL matrix stack state. stackHandler.pop(gl); @@ -613,14 +609,12 @@ else if (!geometry.doubleSided && !cullingEnabled) // subsequent ColladaMeshShape instances processed during batch picking/rendering have the same initial // conditions as the first ColladaMeshShape. Without this restore, subsequent ColladaMeshShapes without a // texture will have the GL_TEXTURE_COORD_ARRAY state enabled during glDrawArrays. - if (texturesEnabled) - { + if (texturesEnabled) { gl.glDisable(GL.GL_TEXTURE_2D); gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY); } - if (cullingEnabled) - { + if (cullingEnabled) { gl.glDisable(GL.GL_CULL_FACE); } } @@ -629,17 +623,18 @@ else if (!geometry.doubleSided && !cullingEnabled) /** * Draw one geometry in the mesh interior using vertex arrays. * - * @param dc Current draw context. + * @param dc Current draw context. * @param geometry Geometry to draw. */ - protected void doDrawInteriorVA(DrawContext dc, Geometry geometry) - { + protected void doDrawInteriorVA(DrawContext dc, Geometry geometry) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (geometry.offset == -1) + if (geometry.offset == -1) { return; + } - if (!dc.isPickingMode() && this.mustApplyLighting(dc, null) && this.normalBuffer != null) + if (!dc.isPickingMode() && this.mustApplyLighting(dc, null) && this.normalBuffer != null) { gl.glNormalPointer(GL.GL_FLOAT, 0, this.normalBuffer.rewind()); + } gl.glDrawArrays(this.elementType, geometry.offset, geometry.colladaGeometry.getCount() * this.vertsPerShape); } @@ -647,32 +642,28 @@ protected void doDrawInteriorVA(DrawContext dc, Geometry geometry) /** * Draw one geometry in the mesh interior using vertex buffer objects. * - * @param dc Current draw context. + * @param dc Current draw context. * @param geometry Geometry to draw. - * @param vboIds Array of vertex buffer identifiers. The first element of the array identifies the buffer that - * contains vertex coordinates and normal vectors. + * @param vboIds Array of vertex buffer identifiers. The first element of the array identifies the buffer that + * contains vertex coordinates and normal vectors. */ - protected void doDrawInteriorVBO(DrawContext dc, Geometry geometry, int[] vboIds) - { + protected void doDrawInteriorVBO(DrawContext dc, Geometry geometry, int[] vboIds) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (geometry.offset == -1) + if (geometry.offset == -1) { return; + } - try - { + try { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]); gl.glVertexPointer(ColladaAbstractGeometry.COORDS_PER_VERTEX, GL.GL_FLOAT, 0, 0); - if (!dc.isPickingMode() && this.mustApplyLighting(dc, null) && this.normalBuffer != null) - { + if (!dc.isPickingMode() && this.mustApplyLighting(dc, null) && this.normalBuffer != null) { gl.glNormalPointer(GL.GL_FLOAT, 0, this.normalBufferPosition * Buffers.SIZEOF_FLOAT); } gl.glDrawArrays(this.elementType, geometry.offset, - geometry.colladaGeometry.getCount() * this.vertsPerShape); - } - finally - { + geometry.colladaGeometry.getCount() * this.vertsPerShape); + } finally { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } } @@ -685,10 +676,8 @@ protected void doDrawInteriorVBO(DrawContext dc, Geometry geometry, int[] vboIds * * @throws IllegalArgumentException if draw context is null or the draw context GL is null */ - protected void setModelViewMatrix(DrawContext dc) - { - if (dc.getGL() == null) - { + protected void setModelViewMatrix(DrawContext dc) { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -708,16 +697,17 @@ protected void setModelViewMatrix(DrawContext dc) ////////////////////////////////////////////////////////////////////// // Geometry creation ////////////////////////////////////////////////////////////////////// - - /** {@inheritDoc} */ - protected boolean isOrderedRenderableValid(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected boolean isOrderedRenderableValid(DrawContext dc) { return this.coordBuffer != null; } - /** {@inheritDoc} */ - protected AbstractShapeData createCacheEntry(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected AbstractShapeData createCacheEntry(DrawContext dc) { return new ShapeData(dc, this); } @@ -726,25 +716,25 @@ protected AbstractShapeData createCacheEntry(DrawContext dc) *

        * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shapeData the current shape data for this shape. */ - protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) - { + protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) { Vec4 refPt = this.computeReferencePoint(dc.getTerrain()); - if (refPt == null) + if (refPt == null) { return; + } shapeData.setReferencePoint(refPt); shapeData.setEyeDistance(this.computeEyeDistance(dc, shapeData)); shapeData.setGlobeStateKey(dc.getGlobe().getGlobeStateKey(dc)); shapeData.setVerticalExaggeration(dc.getVerticalExaggeration()); - if (this.coordBuffer == null) + if (this.coordBuffer == null) { this.createVertexCoords(dc); + } - if (shapeData.getExtent() == null) - { + if (shapeData.getExtent() == null) { Extent extent = this.computeExtent(dc); this.extentCache.put(new ExtentCacheKey(dc.getGlobe(), shapeData.renderMatrix), extent); shapeData.setExtent(extent); @@ -756,18 +746,19 @@ protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) * * @param dc Current draw context. */ - protected void createFullGeometry(DrawContext dc) - { - if (this.normalBuffer == null && this.mustApplyLighting(dc, null)) + protected void createFullGeometry(DrawContext dc) { + if (this.normalBuffer == null && this.mustApplyLighting(dc, null)) { this.createNormals(); + } - if (this.textureCoordsBuffer == null && this.mustApplyTexture(dc)) + if (this.textureCoordsBuffer == null && this.mustApplyTexture(dc)) { this.createTexCoords(); + } - for (Geometry geometry : this.geometries) - { - if (geometry.material == null) + for (Geometry geometry : this.geometries) { + if (geometry.material == null) { geometry.material = this.getMaterial(geometry); + } geometry.doubleSided = this.isDoubleSided(geometry.colladaGeometry); } @@ -780,37 +771,35 @@ protected void createFullGeometry(DrawContext dc) * * @return The spatial extent of the shape, or null if the extent cannot be determined. */ - protected Extent computeExtent(DrawContext dc) - { - if (this.coordBuffer == null) + protected Extent computeExtent(DrawContext dc) { + if (this.coordBuffer == null) { return null; + } // Compute a bounding box around the vertices in this shape. this.coordBuffer.rewind(); Box box = Box.computeBoundingBox(new BufferWrapper.FloatBufferWrapper(this.coordBuffer), - ColladaAbstractGeometry.COORDS_PER_VERTEX); + ColladaAbstractGeometry.COORDS_PER_VERTEX); Matrix matrix = this.computeRenderMatrix(dc); // Compute the corners of the bounding box and transform with the active transform matrix. List extrema = new ArrayList(); Vec4[] corners = box.getCorners(); - for (Vec4 corner : corners) - { + for (Vec4 corner : corners) { extrema.add(corner.transformBy4(matrix)); } - if (extrema.isEmpty()) + if (extrema.isEmpty()) { return null; + } // Compute the bounding box around the transformed corners. return Box.computeBoundingBox(extrema); } - public Box getLocalExtent(ColladaTraversalContext tc) - { - if (tc == null) - { + public Box getLocalExtent(ColladaTraversalContext tc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -819,26 +808,25 @@ public Box getLocalExtent(ColladaTraversalContext tc) int size = this.shapeCount * this.vertsPerShape * ColladaAbstractGeometry.COORDS_PER_VERTEX; FloatBuffer vertexBuffer = WWBufferUtil.newFloatBuffer(size, true); - for (Geometry geometry : this.geometries) - { + for (Geometry geometry : this.geometries) { geometry.colladaGeometry.getVertices(vertexBuffer); } // Compute a bounding box around the vertices in this shape. vertexBuffer.rewind(); Box box = Box.computeBoundingBox(new BufferWrapper.FloatBufferWrapper(vertexBuffer), - ColladaAbstractGeometry.COORDS_PER_VERTEX); + ColladaAbstractGeometry.COORDS_PER_VERTEX); // Compute the corners of the bounding box and transform with the active transform matrix. List extrema = new ArrayList(); Vec4[] corners = box.getCorners(); - for (Vec4 corner : corners) - { + for (Vec4 corner : corners) { extrema.add(corner.transformBy4(tc.peekMatrix())); } - if (extrema.isEmpty()) + if (extrema.isEmpty()) { return null; + } // Compute the bounding box around the transformed corners. return Box.computeBoundingBox(extrema); @@ -849,104 +837,92 @@ public Box getLocalExtent(ColladaTraversalContext tc) * * @param dc Current draw context. */ - protected void createVertexCoords(DrawContext dc) - { + protected void createVertexCoords(DrawContext dc) { int size = this.shapeCount * this.vertsPerShape * ColladaAbstractGeometry.COORDS_PER_VERTEX; // Capture the position at which normals buffer starts (in case there are normals) this.normalBufferPosition = size; - if (this.mustApplyLighting(dc, null)) - { + if (this.mustApplyLighting(dc, null)) { size += (this.shapeCount * this.vertsPerShape * ColladaAbstractGeometry.COORDS_PER_VERTEX); } // Capture the position at which texture coordinate buffer starts (in case that textures are applied) this.texCoordBufferPosition = size; - if (this.mustApplyTexture(dc)) - { + if (this.mustApplyTexture(dc)) { size += (this.shapeCount * this.vertsPerShape * ColladaAbstractGeometry.TEX_COORDS_PER_VERTEX); } - if (this.coordBuffer != null && this.coordBuffer.capacity() >= size) + if (this.coordBuffer != null && this.coordBuffer.capacity() >= size) { this.coordBuffer.clear(); - else + } else { this.coordBuffer = Buffers.newDirectFloatBuffer(size); + } - for (Geometry geometry : this.geometries) - { + for (Geometry geometry : this.geometries) { geometry.offset = this.coordBuffer.position() / this.vertsPerShape; geometry.colladaGeometry.getVertices(this.coordBuffer); } } - /** Create this shape's vertex normals. The normals are stored in {@link #normalBuffer}. */ - protected void createNormals() - { + /** + * Create this shape's vertex normals. The normals are stored in {@link #normalBuffer}. + */ + protected void createNormals() { this.coordBuffer.position(this.normalBufferPosition); this.normalBuffer = this.coordBuffer.slice(); - for (Geometry geometry : this.geometries) - { - if (geometry.colladaGeometry.getNormalAccessor() != null) - { + for (Geometry geometry : this.geometries) { + if (geometry.colladaGeometry.getNormalAccessor() != null) { geometry.colladaGeometry.getNormals(this.normalBuffer); - } - else - { + } else { int thisSize = geometry.colladaGeometry.getCount() * this.vertsPerShape - * ColladaAbstractGeometry.COORDS_PER_VERTEX; + * ColladaAbstractGeometry.COORDS_PER_VERTEX; this.normalBuffer.position(this.normalBuffer.position() + thisSize); } } } - /** Create this shape's texture coordinates. The texture coordinates are stored in {@link #textureCoordsBuffer}. */ - protected void createTexCoords() - { + /** + * Create this shape's texture coordinates. The texture coordinates are stored in {@link #textureCoordsBuffer}. + */ + protected void createTexCoords() { this.coordBuffer.position(this.texCoordBufferPosition); this.textureCoordsBuffer = this.coordBuffer.slice(); - for (Geometry geometry : this.geometries) - { - if (this.mustApplyTexture(geometry)) - { + for (Geometry geometry : this.geometries) { + if (this.mustApplyTexture(geometry)) { String semantic = this.getTexCoordSemantic(geometry); geometry.colladaGeometry.getTextureCoordinates(this.textureCoordsBuffer, semantic); - } - else - { + } else { int thisSize = geometry.colladaGeometry.getCount() * this.vertsPerShape - * ColladaAbstractGeometry.TEX_COORDS_PER_VERTEX; + * ColladaAbstractGeometry.TEX_COORDS_PER_VERTEX; this.textureCoordsBuffer.position(this.textureCoordsBuffer.position() + thisSize); } } } - /** {@inheritDoc} */ - protected void fillVBO(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected void fillVBO(DrawContext dc) { GL gl = dc.getGL(); ShapeData shapeData = (ShapeData) getCurrentData(); int[] vboIds = this.getVboIds(dc); - if (vboIds == null) - { + if (vboIds == null) { int size = this.coordBuffer.limit() * Buffers.SIZEOF_FLOAT; vboIds = new int[1]; gl.glGenBuffers(vboIds.length, vboIds, 0); dc.getGpuResourceCache().put(shapeData.getVboCacheKey(), vboIds, GpuResourceCache.VBO_BUFFERS, - size); + size); } - try - { + try { FloatBuffer vb = this.coordBuffer; gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]); gl.glBufferData(GL.GL_ARRAY_BUFFER, vb.limit() * Buffers.SIZEOF_FLOAT, vb.rewind(), GL.GL_STATIC_DRAW); - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } } @@ -958,11 +934,11 @@ protected void fillVBO(DrawContext dc) * * @return the computed reference center, or null if it cannot be computed. */ - protected Vec4 computeReferenceCenter(DrawContext dc) - { + protected Vec4 computeReferenceCenter(DrawContext dc) { Position pos = this.getReferencePosition(); - if (pos == null) + if (pos == null) { return null; + } return this.computePoint(dc.getTerrain(), pos); } @@ -976,13 +952,13 @@ protected Vec4 computeReferenceCenter(DrawContext dc) * * @return the minimum distance from the shape to the eye point. */ - protected double computeEyeDistance(DrawContext dc) - { + protected double computeEyeDistance(DrawContext dc) { Vec4 eyePoint = dc.getView().getEyePoint(); Vec4 refPt = this.computePoint(dc.getTerrain(), this.getModelPosition()); - if (refPt != null) + if (refPt != null) { return refPt.distanceTo3(eyePoint); + } return 0; } @@ -994,12 +970,10 @@ protected double computeEyeDistance(DrawContext dc) * * @return the modelview transform for this shape. */ - protected Matrix computeRenderMatrix(DrawContext dc) - { + protected Matrix computeRenderMatrix(DrawContext dc) { ShapeData current = (ShapeData) this.getCurrent(); - if (current.referenceCenter == null || current.isExpired(dc)) - { + if (current.referenceCenter == null || current.isExpired(dc)) { current.referenceCenter = this.computeReferenceCenter(dc); Position refPosition = dc.getGlobe().computePositionFromPoint(current.referenceCenter); @@ -1011,19 +985,17 @@ protected Matrix computeRenderMatrix(DrawContext dc) ////////////////////////////////////////////////////////////////////// // Materials and textures ////////////////////////////////////////////////////////////////////// - /** * {@inheritDoc} * * @return True if any geometry in this shape includes a texture. */ @Override - protected boolean mustApplyTexture(DrawContext dc) - { - for (Geometry geometry : this.geometries) - { - if (this.mustApplyTexture(geometry)) + protected boolean mustApplyTexture(DrawContext dc) { + for (Geometry geometry : this.geometries) { + if (this.mustApplyTexture(geometry)) { return true; + } } return false; } @@ -1035,11 +1007,10 @@ protected boolean mustApplyTexture(DrawContext dc) * * @return True if the specified geometry includes a texture. */ - protected boolean mustApplyTexture(Geometry geometry) - { + protected boolean mustApplyTexture(Geometry geometry) { String semantic = this.getTexCoordSemantic(geometry); return geometry.colladaGeometry.getTexCoordAccessor(semantic) != null - && this.getTexture(geometry) != null; + && this.getTexture(geometry) != null; } /** @@ -1047,19 +1018,19 @@ protected boolean mustApplyTexture(Geometry geometry) * * @param geometry The geometry to set the texture from. * @return The texture that must be applied to the shape, or null if there is no texture, or the texture is not - * available. + * available. */ - protected WWTexture getTexture(Geometry geometry) - { - if (geometry.texture != null) + protected WWTexture getTexture(Geometry geometry) { + if (geometry.texture != null) { return geometry.texture; + } String source = this.getTextureSource(geometry.colladaGeometry); - if (source != null) - { + if (source != null) { Object o = geometry.colladaGeometry.getRoot().resolveReference(source); - if (o != null) + if (o != null) { geometry.texture = new LazilyLoadedTexture(o); + } } return geometry.texture; @@ -1068,25 +1039,21 @@ protected WWTexture getTexture(Geometry geometry) /** * Apply a material to the active draw context. * - * @param dc Current draw context. + * @param dc Current draw context. * @param material Material to apply. */ - protected void applyMaterial(DrawContext dc, Material material) - { + protected void applyMaterial(DrawContext dc, Material material) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. ShapeAttributes activeAttrs = this.getActiveAttributes(); double opacity = activeAttrs.getInteriorOpacity(); // We don't need to enable or disable lighting; that's handled by super.prepareToDrawInterior. - if (this.mustApplyLighting(dc, activeAttrs)) - { + if (this.mustApplyLighting(dc, activeAttrs)) { material.apply(gl, GL2.GL_FRONT_AND_BACK, (float) opacity); - } - else - { + } else { Color sc = material.getDiffuse(); gl.glColor4ub((byte) sc.getRed(), (byte) sc.getGreen(), (byte) sc.getBlue(), - (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); + (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); } } @@ -1096,28 +1063,31 @@ protected void applyMaterial(DrawContext dc, Material material) * @param geometry Geometry for which to find material. * * @return Material to apply to the geometry. If the COLLADA document does not define a material, this method return - * a default material. + * a default material. */ - protected Material getMaterial(Geometry geometry) - { + protected Material getMaterial(Geometry geometry) { ColladaInstanceMaterial myMaterialInstance = this.getInstanceMaterial(geometry); - if (myMaterialInstance == null) + if (myMaterialInstance == null) { return DEFAULT_INTERIOR_MATERIAL; + } // Attempt to resolve the instance. The material may not be immediately available. ColladaMaterial myMaterial = myMaterialInstance.get(); - if (myMaterial == null) + if (myMaterial == null) { return DEFAULT_INTERIOR_MATERIAL; + } ColladaInstanceEffect myEffectInstance = myMaterial.getInstanceEffect(); - if (myEffectInstance == null) + if (myEffectInstance == null) { return DEFAULT_INTERIOR_MATERIAL; + } // Attempt to resolve effect. The effect may not be immediately available. ColladaEffect myEffect = myEffectInstance.get(); - if (myEffect == null) + if (myEffect == null) { return DEFAULT_INTERIOR_MATERIAL; + } return myEffect.getMaterial(); } @@ -1129,23 +1099,25 @@ protected Material getMaterial(Geometry geometry) * * @return Material for the specified geometry, or null if the material cannot be resolved. */ - protected ColladaInstanceMaterial getInstanceMaterial(Geometry geometry) - { - if (this.bindMaterial == null) + protected ColladaInstanceMaterial getInstanceMaterial(Geometry geometry) { + if (this.bindMaterial == null) { return null; + } ColladaTechniqueCommon techniqueCommon = this.bindMaterial.getTechniqueCommon(); - if (techniqueCommon == null) + if (techniqueCommon == null) { return null; + } String materialSource = geometry.colladaGeometry.getMaterial(); - if (materialSource == null) + if (materialSource == null) { return null; + } - for (ColladaInstanceMaterial material : techniqueCommon.getMaterials()) - { - if (materialSource.equals(material.getSymbol())) + for (ColladaInstanceMaterial material : techniqueCommon.getMaterials()) { + if (materialSource.equals(material.getSymbol())) { return material; + } } return null; } @@ -1157,30 +1129,32 @@ protected ColladaInstanceMaterial getInstanceMaterial(Geometry geometry) * @param geometry Geometry for which to find semantic. * * @return The semantic string that identifies the texture coordinates, or null if the geometry does not define the - * semantic. + * semantic. */ - protected String getTexCoordSemantic(Geometry geometry) - { + protected String getTexCoordSemantic(Geometry geometry) { ColladaEffect effect = this.getEffect(geometry.colladaGeometry); - if (effect == null) + if (effect == null) { return null; + } ColladaTexture texture = effect.getTexture(); - if (texture == null) + if (texture == null) { return null; + } String texcoord = texture.getTexCoord(); - if (texcoord == null) + if (texcoord == null) { return null; + } ColladaInstanceMaterial instanceMaterial = this.getInstanceMaterial(geometry); String inputSemantic = null; // Search bind_vertex_input to find the semantic that identifies the texture coords. - for (ColladaBindVertexInput bind : instanceMaterial.getBindVertexInputs()) - { - if (texcoord.equals(bind.getSemantic())) + for (ColladaBindVertexInput bind : instanceMaterial.getBindVertexInputs()) { + if (texcoord.equals(bind.getSemantic())) { inputSemantic = bind.getInputSemantic(); + } } return inputSemantic; @@ -1193,60 +1167,67 @@ protected String getTexCoordSemantic(Geometry geometry) * * @return The source of the texture, or null if it cannot be resolved. */ - protected String getTextureSource(ColladaAbstractGeometry geometry) - { + protected String getTextureSource(ColladaAbstractGeometry geometry) { ColladaTechniqueCommon techniqueCommon = this.bindMaterial.getTechniqueCommon(); - if (techniqueCommon == null) + if (techniqueCommon == null) { return null; + } String materialSource = geometry.getMaterial(); - if (materialSource == null) + if (materialSource == null) { return null; + } ColladaInstanceMaterial myMaterialInstance = null; - for (ColladaInstanceMaterial material : techniqueCommon.getMaterials()) - { - if (materialSource.equals(material.getSymbol())) - { + for (ColladaInstanceMaterial material : techniqueCommon.getMaterials()) { + if (materialSource.equals(material.getSymbol())) { myMaterialInstance = material; break; } } - if (myMaterialInstance == null) + if (myMaterialInstance == null) { return null; + } // Attempt to resolve the instance. The material may not be immediately available. ColladaMaterial myMaterial = myMaterialInstance.get(); - if (myMaterial == null) + if (myMaterial == null) { return null; + } ColladaInstanceEffect myEffectInstance = myMaterial.getInstanceEffect(); - if (myEffectInstance == null) + if (myEffectInstance == null) { return null; + } // Attempt to resolve effect. The effect may not be immediately available. ColladaEffect myEffect = myEffectInstance.get(); - if (myEffect == null) + if (myEffect == null) { return null; + } ColladaTexture texture = myEffect.getTexture(); - if (texture == null) + if (texture == null) { return null; + } String imageRef = this.getImageRef(myEffect, texture); - if (imageRef == null) + if (imageRef == null) { return null; + } // imageRef identifiers an element in this or another document. If the string doesn't already contain a // # then treat the entire string as a fragment identifier in the current document. - if (!imageRef.contains("#")) + if (!imageRef.contains("#")) { imageRef = "#" + imageRef; + } // imageRef identifiers an element (may be external). This element will give us the filename. Object o = geometry.getRoot().resolveReference(imageRef); - if (o instanceof ColladaImage) + if (o instanceof ColladaImage) { return ((ColladaImage) o).getInitFrom(); + } return null; } @@ -1255,38 +1236,43 @@ protected String getTextureSource(ColladaAbstractGeometry geometry) * Indicates the reference string for an image. The image reference identifies an image element in this, or * another COLLADA file. For example, "#myImage". * - * @param effect Effect that defines the texture. + * @param effect Effect that defines the texture. * @param texture Texture for which to find the image reference. * * @return The image reference, or null if it cannot be resolved. */ - protected String getImageRef(ColladaEffect effect, ColladaTexture texture) - { + protected String getImageRef(ColladaEffect effect, ColladaTexture texture) { String sid = texture.getTexture(); ColladaNewParam param = effect.getParam(sid); - if (param == null) + if (param == null) { return null; + } ColladaSampler2D sampler = param.getSampler2D(); - if (sampler == null) + if (sampler == null) { return null; + } ColladaSource source = sampler.getSource(); - if (source == null) + if (source == null) { return null; + } sid = source.getCharacters(); - if (sid == null) + if (sid == null) { return null; + } param = effect.getParam(sid); - if (param == null) + if (param == null) { return null; + } ColladaSurface surface = param.getSurface(); - if (surface != null) + if (surface != null) { return surface.getInitFrom(); + } return null; } @@ -1297,39 +1283,41 @@ protected String getImageRef(ColladaEffect effect, ColladaTexture texture) * @param geometry Geometry for which to find effect. * * @return Effect applied to the specified geometry, or null if no effect is defined, or the effect is not - * available. + * available. */ - protected ColladaEffect getEffect(ColladaAbstractGeometry geometry) - { + protected ColladaEffect getEffect(ColladaAbstractGeometry geometry) { ColladaTechniqueCommon techniqueCommon = this.bindMaterial.getTechniqueCommon(); - if (techniqueCommon == null) + if (techniqueCommon == null) { return null; + } String materialSource = geometry.getMaterial(); - if (materialSource == null) + if (materialSource == null) { return null; + } ColladaInstanceMaterial myMaterialInstance = null; - for (ColladaInstanceMaterial material : techniqueCommon.getMaterials()) - { - if (materialSource.equals(material.getSymbol())) - { + for (ColladaInstanceMaterial material : techniqueCommon.getMaterials()) { + if (materialSource.equals(material.getSymbol())) { myMaterialInstance = material; break; } } - if (myMaterialInstance == null) + if (myMaterialInstance == null) { return null; + } // Attempt to resolve the instance. The material may not be immediately available. ColladaMaterial myMaterial = myMaterialInstance.get(); - if (myMaterial == null) + if (myMaterial == null) { return null; + } ColladaInstanceEffect myEffectInstance = myMaterial.getInstanceEffect(); - if (myEffectInstance == null) + if (myEffectInstance == null) { return null; + } // Attempt to resolve effect. The effect may not be immediately available. return myEffectInstance.get(); @@ -1345,23 +1333,26 @@ protected ColladaEffect getEffect(ColladaAbstractGeometry geometry) * * @return True if the geometry is marked as double sided. Otherwise false. */ - protected boolean isDoubleSided(ColladaAbstractGeometry geometry) - { + protected boolean isDoubleSided(ColladaAbstractGeometry geometry) { ColladaEffect effect = this.getEffect(geometry); - if (effect == null) + if (effect == null) { return false; + } ColladaProfileCommon profile = effect.getProfileCommon(); - if (profile == null) + if (profile == null) { return false; + } ColladaExtra extra = profile.getExtra(); - if (extra == null) + if (extra == null) { return false; + } ColladaTechnique technique = (ColladaTechnique) extra.getField("technique"); - if (technique == null || !"GOOGLEEARTH".equals(technique.getProfile())) + if (technique == null || !"GOOGLEEARTH".equals(technique.getProfile())) { return false; + } Integer i = (Integer) technique.getField("double_sided"); return i != null && i == 1; diff --git a/src/gov/nasa/worldwind/ogc/collada/impl/ColladaRenderable.java b/src/gov/nasa/worldwind/ogc/collada/impl/ColladaRenderable.java index e27d390d91..87c263fa18 100644 --- a/src/gov/nasa/worldwind/ogc/collada/impl/ColladaRenderable.java +++ b/src/gov/nasa/worldwind/ogc/collada/impl/ColladaRenderable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada.impl; import gov.nasa.worldwind.geom.Box; @@ -15,8 +14,8 @@ * @author pabercrombie * @version $Id: ColladaRenderable.java 1696 2013-10-31 18:46:55Z tgaskins $ */ -public interface ColladaRenderable -{ +public interface ColladaRenderable { + /** * Returns this renderable's model coordinate extent. * diff --git a/src/gov/nasa/worldwind/ogc/collada/impl/ColladaTraversalContext.java b/src/gov/nasa/worldwind/ogc/collada/impl/ColladaTraversalContext.java index ab002b73f9..4f3cd6e194 100644 --- a/src/gov/nasa/worldwind/ogc/collada/impl/ColladaTraversalContext.java +++ b/src/gov/nasa/worldwind/ogc/collada/impl/ColladaTraversalContext.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada.impl; import gov.nasa.worldwind.geom.Matrix; @@ -18,14 +17,17 @@ * @author pabercrombie * @version $Id: ColladaTraversalContext.java 661 2012-06-26 18:02:23Z pabercrombie $ */ -public class ColladaTraversalContext -{ - /** Transform matrix stack. */ +public class ColladaTraversalContext { + + /** + * Transform matrix stack. + */ protected Stack matrixStack = new Stack(); - /** Create a new traversal context. The traversal matrix stack initially contains one element: the identity matrix. */ - public ColladaTraversalContext() - { + /** + * Create a new traversal context. The traversal matrix stack initially contains one element: the identity matrix. + */ + public ColladaTraversalContext() { this.matrixStack = new Stack(); this.matrixStack.push(Matrix.IDENTITY); } @@ -35,14 +37,14 @@ public ColladaTraversalContext() * * @return The matrix at the top of the matrix stack. */ - public Matrix peekMatrix() - { + public Matrix peekMatrix() { return this.matrixStack.peek(); } - /** Clone the matrix at the top of the matrix stack and push the clone onto the stack. */ - public void pushMatrix() - { + /** + * Clone the matrix at the top of the matrix stack and push the clone onto the stack. + */ + public void pushMatrix() { this.matrixStack.push(this.peekMatrix()); } @@ -51,10 +53,8 @@ public void pushMatrix() * * @param m Matrix to add to the stack. This matrix becomes the new top matrix. */ - public void pushMatrix(Matrix m) - { - if (m == null) - { + public void pushMatrix(Matrix m) { + if (m == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -68,8 +68,7 @@ public void pushMatrix(Matrix m) * * @return The matrix that was at the top of the stack. */ - public Matrix popMatrix() - { + public Matrix popMatrix() { return this.matrixStack.pop(); } @@ -78,10 +77,8 @@ public Matrix popMatrix() * * @param m Matrix to multiply. Multiplication is performed as top * m. */ - public void multiplyMatrix(Matrix m) - { - if (m == null) - { + public void multiplyMatrix(Matrix m) { + if (m == null) { String msg = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -91,9 +88,10 @@ public void multiplyMatrix(Matrix m) this.pushMatrix(top.multiply(m)); } - /** Reset the context so that it may be used for a fresh traversal. */ - public void initialize() - { + /** + * Reset the context so that it may be used for a fresh traversal. + */ + public void initialize() { this.matrixStack.clear(); this.pushMatrix(Matrix.IDENTITY); } diff --git a/src/gov/nasa/worldwind/ogc/collada/impl/package-info.java b/src/gov/nasa/worldwind/ogc/collada/impl/package-info.java index d51dfea4f8..7cc73c1a85 100644 --- a/src/gov/nasa/worldwind/ogc/collada/impl/package-info.java +++ b/src/gov/nasa/worldwind/ogc/collada/impl/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

        * Provides classes for rendering COLLADA documents. The {@link gov.nasa.worldwind.ogc.collada.impl.ColladaController} diff --git a/src/gov/nasa/worldwind/ogc/collada/io/ColladaDoc.java b/src/gov/nasa/worldwind/ogc/collada/io/ColladaDoc.java index 76445b9cc1..ed1df5510b 100644 --- a/src/gov/nasa/worldwind/ogc/collada/io/ColladaDoc.java +++ b/src/gov/nasa/worldwind/ogc/collada/io/ColladaDoc.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada.io; import java.io.*; @@ -14,8 +13,8 @@ * @author pabercrombie * @version $Id: ColladaDoc.java 660 2012-06-26 16:13:11Z pabercrombie $ */ -public interface ColladaDoc -{ +public interface ColladaDoc { + /** * Returns an {@link java.io.InputStream} to the associated COLLADA document. *

        @@ -35,7 +34,7 @@ public interface ColladaDoc * @return an absolute path or URL to the file, or null if the file does not exist. * * @throws IllegalArgumentException if the specified path is null. - * @throws java.io.IOException if an error occurs while attempting to read the support file. + * @throws java.io.IOException if an error occurs while attempting to read the support file. */ String getSupportFilePath(String path) throws IOException; } diff --git a/src/gov/nasa/worldwind/ogc/collada/io/ColladaFile.java b/src/gov/nasa/worldwind/ogc/collada/io/ColladaFile.java index 609ead9ed8..9d2b76908e 100644 --- a/src/gov/nasa/worldwind/ogc/collada/io/ColladaFile.java +++ b/src/gov/nasa/worldwind/ogc/collada/io/ColladaFile.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada.io; import gov.nasa.worldwind.util.Logging; @@ -16,9 +15,11 @@ * @author pabercrombie * @version $Id: ColladaFile.java 660 2012-06-26 16:13:11Z pabercrombie $ */ -public class ColladaFile implements ColladaDoc -{ - /** File from which COLLADA content is read. */ +public class ColladaFile implements ColladaDoc { + + /** + * File from which COLLADA content is read. + */ protected File colladaFile; /** @@ -26,10 +27,8 @@ public class ColladaFile implements ColladaDoc * * @param file COLLADA file from which to read content. */ - public ColladaFile(File file) - { - if (file == null) - { + public ColladaFile(File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -38,25 +37,27 @@ public ColladaFile(File file) this.colladaFile = file; } - /** {@inheritDoc} */ - public InputStream getInputStream() throws IOException - { + /** + * {@inheritDoc} + */ + public InputStream getInputStream() throws IOException { return new FileInputStream(this.colladaFile); } - /** {@inheritDoc} */ - public String getSupportFilePath(String path) - { - if (path == null) - { + /** + * {@inheritDoc} + */ + public String getSupportFilePath(String path) { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File pathFile = new File(path); - if (pathFile.isAbsolute()) + if (pathFile.isAbsolute()) { return null; + } pathFile = new File(this.colladaFile.getParentFile(), path); diff --git a/src/gov/nasa/worldwind/ogc/collada/io/ColladaInputStream.java b/src/gov/nasa/worldwind/ogc/collada/io/ColladaInputStream.java index 81d33318cc..7f0076b943 100644 --- a/src/gov/nasa/worldwind/ogc/collada/io/ColladaInputStream.java +++ b/src/gov/nasa/worldwind/ogc/collada/io/ColladaInputStream.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.collada.io; import gov.nasa.worldwind.util.Logging; @@ -17,28 +16,30 @@ * @author pabercrombie * @version $Id: ColladaInputStream.java 660 2012-06-26 16:13:11Z pabercrombie $ */ -public class ColladaInputStream implements ColladaDoc -{ - /** The {@link java.io.InputStream} specified to the constructor. */ +public class ColladaInputStream implements ColladaDoc { + + /** + * The {@link java.io.InputStream} specified to the constructor. + */ protected InputStream inputStream; - /** The URI of this COLLADA document. May be {@code null}. */ + /** + * The URI of this COLLADA document. May be {@code null}. + */ protected URI uri; /** * Construct a ColladaInputStream instance. * * @param sourceStream the COLLADA stream. - * @param uri the URI of this COLLADA document. This URI is used to resolve relative references. May be - * {@code null}. + * @param uri the URI of this COLLADA document. This URI is used to resolve relative references. May be + * {@code null}. * * @throws IllegalArgumentException if the specified input stream is null. - * @throws IOException if an error occurs while attempting to read from the stream. + * @throws IOException if an error occurs while attempting to read from the stream. */ - public ColladaInputStream(InputStream sourceStream, URI uri) throws IOException - { - if (sourceStream == null) - { + public ColladaInputStream(InputStream sourceStream, URI uri) throws IOException { + if (sourceStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -53,26 +54,25 @@ public ColladaInputStream(InputStream sourceStream, URI uri) throws IOException * * @return the input stream reference passed to the constructor. */ - public InputStream getInputStream() throws IOException - { + public InputStream getInputStream() throws IOException { return this.inputStream; } - /** {@inheritDoc} */ - public String getSupportFilePath(String path) - { - if (path == null) - { + /** + * {@inheritDoc} + */ + public String getSupportFilePath(String path) { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.uri != null) - { + if (this.uri != null) { URI remoteFile = uri.resolve(path); - if (remoteFile != null) + if (remoteFile != null) { return remoteFile.toString(); + } } return null; } diff --git a/src/gov/nasa/worldwind/ogc/collada/io/package-info.java b/src/gov/nasa/worldwind/ogc/collada/io/package-info.java index a045b0b01e..98165b04ef 100644 --- a/src/gov/nasa/worldwind/ogc/collada/io/package-info.java +++ b/src/gov/nasa/worldwind/ogc/collada/io/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

        * Provides classes for COLLADA file and stream I/O and relative-path resolution.

        diff --git a/src/gov/nasa/worldwind/ogc/collada/package-info.java b/src/gov/nasa/worldwind/ogc/collada/package-info.java index 448e78818f..7a96b32540 100644 --- a/src/gov/nasa/worldwind/ogc/collada/package-info.java +++ b/src/gov/nasa/worldwind/ogc/collada/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

        * Provides classes for parsing COLLADA files and streams.

        @@ -31,16 +30,16 @@ * * * -

        Extending the Classes

        + *

        Extending the Classes

        * -

        + *

        * This package's classes are designed for easy behavior modification and replacement, and for straightforward addition * of operations to be performed during parsing. See the description of {@link * gov.nasa.worldwind.util.xml.AbstractXMLEventParser} for further information.

        * -

        Relative References

        + *

        Relative References

        * -

        + *

        * By default, relative references will be resolved relative to the location of the COLLADA file that includes the * reference. However, this behavior can be overridden by providing the ColladaRoot with a {@link * gov.nasa.worldwind.ogc.collada.ColladaResourceResolver}.

        diff --git a/src/gov/nasa/worldwind/ogc/gml/GMLEnvelope.java b/src/gov/nasa/worldwind/ogc/gml/GMLEnvelope.java index 743e49dd9d..36674b46b6 100644 --- a/src/gov/nasa/worldwind/ogc/gml/GMLEnvelope.java +++ b/src/gov/nasa/worldwind/ogc/gml/GMLEnvelope.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.gml; import gov.nasa.worldwind.util.xml.*; @@ -16,41 +15,34 @@ * @author tag * @version $Id: GMLEnvelope.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class GMLEnvelope extends AbstractXMLEventParser -{ +public class GMLEnvelope extends AbstractXMLEventParser { + List positions = new ArrayList(2); List timePositions = new ArrayList(2); - public GMLEnvelope(String namespaceURI) - { + public GMLEnvelope(String namespaceURI) { super(namespaceURI); } - public String getSRSName() - { + public String getSRSName() { return (String) this.getField("srsName"); } - public List getPositions() - { + public List getPositions() { return this.positions; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "pos")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "pos")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof GMLPos) + if (o != null && o instanceof GMLPos) { this.positions.add((GMLPos) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/gml/GMLEnvelopeWithTimePeriod.java b/src/gov/nasa/worldwind/ogc/gml/GMLEnvelopeWithTimePeriod.java index 10e06d2de2..f9d2770c3a 100644 --- a/src/gov/nasa/worldwind/ogc/gml/GMLEnvelopeWithTimePeriod.java +++ b/src/gov/nasa/worldwind/ogc/gml/GMLEnvelopeWithTimePeriod.java @@ -3,27 +3,23 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.gml; /** * @author tag * @version $Id: GMLEnvelopeWithTimePeriod.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class GMLEnvelopeWithTimePeriod extends GMLEnvelope -{ - public GMLEnvelopeWithTimePeriod(String namespaceURI) - { +public class GMLEnvelopeWithTimePeriod extends GMLEnvelope { + + public GMLEnvelopeWithTimePeriod(String namespaceURI) { super(namespaceURI); } - public Object getBeginPosition() - { + public Object getBeginPosition() { return this.getField("beginPosition"); } - public Object getEndPosition() - { + public Object getEndPosition() { return this.getField("endPosition"); } } diff --git a/src/gov/nasa/worldwind/ogc/gml/GMLGrid.java b/src/gov/nasa/worldwind/ogc/gml/GMLGrid.java index 593b9765f1..ed336b144c 100644 --- a/src/gov/nasa/worldwind/ogc/gml/GMLGrid.java +++ b/src/gov/nasa/worldwind/ogc/gml/GMLGrid.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.gml; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,30 +11,25 @@ * @author tag * @version $Id: GMLGrid.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class GMLGrid extends AbstractXMLEventParser -{ - public GMLGrid(String namespaceURI) - { +public class GMLGrid extends AbstractXMLEventParser { + + public GMLGrid(String namespaceURI) { super(namespaceURI); } - public String getDimension() - { + public String getDimension() { return (String) this.getField("dimension"); } - public String getSRSName() - { + public String getSRSName() { return (String) this.getField("srsName"); } - public GMLOrigin getOrigin() - { + public GMLOrigin getOrigin() { return (GMLOrigin) this.getField("origin"); } - public GMLLimits getLimits() - { + public GMLLimits getLimits() { return (GMLLimits) this.getField("limits"); } } diff --git a/src/gov/nasa/worldwind/ogc/gml/GMLGridEnvelope.java b/src/gov/nasa/worldwind/ogc/gml/GMLGridEnvelope.java index 488d49a38d..10e10fa8c8 100644 --- a/src/gov/nasa/worldwind/ogc/gml/GMLGridEnvelope.java +++ b/src/gov/nasa/worldwind/ogc/gml/GMLGridEnvelope.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.gml; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,20 +11,17 @@ * @author tag * @version $Id: GMLGridEnvelope.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class GMLGridEnvelope extends AbstractXMLEventParser -{ - public GMLGridEnvelope(String namespaceURI) - { +public class GMLGridEnvelope extends AbstractXMLEventParser { + + public GMLGridEnvelope(String namespaceURI) { super(namespaceURI); } - public String getHigh() - { + public String getHigh() { return (String) this.getField("high"); } - public String getLow() - { + public String getLow() { return (String) this.getField("low"); } } diff --git a/src/gov/nasa/worldwind/ogc/gml/GMLLimits.java b/src/gov/nasa/worldwind/ogc/gml/GMLLimits.java index 9ebf20ecb9..5cb72c0789 100644 --- a/src/gov/nasa/worldwind/ogc/gml/GMLLimits.java +++ b/src/gov/nasa/worldwind/ogc/gml/GMLLimits.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.gml; import gov.nasa.worldwind.util.xml.*; @@ -16,35 +15,29 @@ * @author tag * @version $Id: GMLLimits.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class GMLLimits extends AbstractXMLEventParser -{ +public class GMLLimits extends AbstractXMLEventParser { + protected List gridEnvelopes = new ArrayList(1); - public GMLLimits(String namespaceURI) - { + public GMLLimits(String namespaceURI) { super(namespaceURI); } - public List getGridEnvelopes() - { + public List getGridEnvelopes() { return this.gridEnvelopes; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "GridEnvelope")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "GridEnvelope")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof GMLGridEnvelope) + if (o != null && o instanceof GMLGridEnvelope) { this.gridEnvelopes.add((GMLGridEnvelope) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/gml/GMLOrigin.java b/src/gov/nasa/worldwind/ogc/gml/GMLOrigin.java index e777b8cc64..f7f991b344 100644 --- a/src/gov/nasa/worldwind/ogc/gml/GMLOrigin.java +++ b/src/gov/nasa/worldwind/ogc/gml/GMLOrigin.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.gml; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,15 +11,13 @@ * @author tag * @version $Id: GMLOrigin.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class GMLOrigin extends AbstractXMLEventParser -{ - public GMLOrigin(String namespaceURI) - { +public class GMLOrigin extends AbstractXMLEventParser { + + public GMLOrigin(String namespaceURI) { super(namespaceURI); } - public GMLPos getPos() - { + public GMLPos getPos() { return (GMLPos) this.getField("pos"); } } diff --git a/src/gov/nasa/worldwind/ogc/gml/GMLPos.java b/src/gov/nasa/worldwind/ogc/gml/GMLPos.java index 3172f640d8..83e78fc66f 100644 --- a/src/gov/nasa/worldwind/ogc/gml/GMLPos.java +++ b/src/gov/nasa/worldwind/ogc/gml/GMLPos.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.gml; import gov.nasa.worldwind.util.Logging; @@ -15,36 +14,30 @@ * @author tag * @version $Id: GMLPos.java 2066 2014-06-20 20:41:46Z tgaskins $ */ -public class GMLPos extends AbstractXMLEventParser -{ - public GMLPos(String namespaceURI) - { +public class GMLPos extends AbstractXMLEventParser { + + public GMLPos(String namespaceURI) { super(namespaceURI); } - public String getDimension() - { + public String getDimension() { return (String) this.getField("dimension"); } - public String getPosString() - { + public String getPosString() { return (String) this.getField("CharactersContent"); } - public double[] getPos2() - { + public double[] getPos2() { String[] strings = this.getPosString().split(" "); - if (strings.length < 2) + if (strings.length < 2) { return null; - - try - { - return new double[] {Double.parseDouble(strings[0]), Double.parseDouble(strings[1])}; } - catch (NumberFormatException e) - { + + try { + return new double[]{Double.parseDouble(strings[0]), Double.parseDouble(strings[1])}; + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.NumberFormatException"); Logging.logger().log(Level.WARNING, message, e); return null; diff --git a/src/gov/nasa/worldwind/ogc/gml/GMLRectifiedGrid.java b/src/gov/nasa/worldwind/ogc/gml/GMLRectifiedGrid.java index 2594584de5..0393b0efa9 100644 --- a/src/gov/nasa/worldwind/ogc/gml/GMLRectifiedGrid.java +++ b/src/gov/nasa/worldwind/ogc/gml/GMLRectifiedGrid.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.gml; import gov.nasa.worldwind.geom.Vec4; @@ -18,42 +17,33 @@ * @author tag * @version $Id: GMLRectifiedGrid.java 2066 2014-06-20 20:41:46Z tgaskins $ */ -public class GMLRectifiedGrid extends GMLGrid -{ +public class GMLRectifiedGrid extends GMLGrid { + protected List axisNames = new ArrayList(2); protected List offsetVectors = new ArrayList(2); - public GMLRectifiedGrid(String namespaceURI) - { + public GMLRectifiedGrid(String namespaceURI) { super(namespaceURI); } - public List getAxisNames() - { + public List getAxisNames() { return this.axisNames; } - public List getOffsetVectorStrings() - { + public List getOffsetVectorStrings() { return this.offsetVectors; } - public List getOffsetVectors() - { + public List getOffsetVectors() { List vectors = new ArrayList(this.offsetVectors.size()); - for (String s : this.offsetVectors) - { - double[] arr = new double[] {0, 0, 0, 0}; + for (String s : this.offsetVectors) { + double[] arr = new double[]{0, 0, 0, 0}; String[] split = s.split(" "); - for (int i = 0; i < Math.min(split.length, 4); i++) - { - try - { + for (int i = 0; i < Math.min(split.length, 4); i++) { + try { arr[i] = Double.parseDouble(split[i]); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.NumberFormatException"); Logging.logger().log(java.util.logging.Level.WARNING, message, e); return Collections.emptyList(); @@ -66,22 +56,18 @@ public List getOffsetVectors() } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "axisName")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "axisName")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.axisNames.add(s); - } - else if (ctx.isStartElement(event, "offsetVector")) - { + } + } else if (ctx.isStartElement(event, "offsetVector")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.offsetVectors.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractColorStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractColorStyle.java index eb5d80cc90..37d646aff6 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractColorStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractColorStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,25 +11,22 @@ * @author tag * @version $Id: KMLAbstractColorStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractColorStyle extends KMLAbstractSubStyle -{ +public abstract class KMLAbstractColorStyle extends KMLAbstractSubStyle { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractColorStyle(String namespaceURI) - { + protected KMLAbstractColorStyle(String namespaceURI) { super(namespaceURI); } - public String getColor() - { + public String getColor() { return (String) this.getField("color"); } - public String getColorMode() - { + public String getColorMode() { return (String) this.getField("colorMode"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractContainer.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractContainer.java index d7dbec02fc..522ab0e75b 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractContainer.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractContainer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -22,8 +21,8 @@ * @author tag * @version $Id: KMLAbstractContainer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLAbstractContainer extends KMLAbstractFeature -{ +public class KMLAbstractContainer extends KMLAbstractFeature { + protected ArrayList features = new ArrayList(); /** @@ -31,36 +30,34 @@ public class KMLAbstractContainer extends KMLAbstractFeature * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractContainer(String namespaceURI) - { + protected KMLAbstractContainer(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractFeature) + throws XMLStreamException { + if (o instanceof KMLAbstractFeature) { this.addFeature((KMLAbstractFeature) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public List getFeatures() - { + public List getFeatures() { return this.features; } - public void addFeature(KMLAbstractFeature feature) - { - if (feature != null) + public void addFeature(KMLAbstractFeature feature) { + if (feature != null) { this.features.add(feature); + } } - public void removeFeature(KMLAbstractFeature feature) - { - if (feature != null) + public void removeFeature(KMLAbstractFeature feature) { + if (feature != null) { this.getFeatures().remove(feature); + } } /** @@ -80,8 +77,7 @@ public void removeFeature(KMLAbstractFeature feature) * @return true if this container should be rendered, otherwise false. */ @Override - protected boolean isFeatureActive(KMLTraversalContext tc, DrawContext dc) - { + protected boolean isFeatureActive(KMLTraversalContext tc, DrawContext dc) { return this.getVisibility() == null || this.getVisibility(); } @@ -96,15 +92,11 @@ protected boolean isFeatureActive(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @Override - protected void doPreRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doPreRender(KMLTraversalContext tc, DrawContext dc) { this.beginRendering(tc, dc); - try - { + try { this.preRenderFeatures(tc, dc); - } - finally - { + } finally { this.endRendering(tc, dc); } } @@ -120,16 +112,12 @@ protected void doPreRender(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @Override - protected void doRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doRender(KMLTraversalContext tc, DrawContext dc) { this.beginRendering(tc, dc); - try - { + try { this.renderBalloon(tc, dc); this.renderFeatures(tc, dc); - } - finally - { + } finally { this.endRendering(tc, dc); } } @@ -143,10 +131,10 @@ protected void doRender(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @SuppressWarnings({"UnusedDeclaration"}) - protected void beginRendering(KMLTraversalContext tc, DrawContext dc) - { - if (this.getRegion() != null) + protected void beginRendering(KMLTraversalContext tc, DrawContext dc) { + if (this.getRegion() != null) { tc.pushRegion(this.getRegion()); + } } /** @@ -158,10 +146,10 @@ protected void beginRendering(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @SuppressWarnings({"UnusedDeclaration"}) - protected void endRendering(KMLTraversalContext tc, DrawContext dc) - { - if (this.getRegion() != null) + protected void endRendering(KMLTraversalContext tc, DrawContext dc) { + if (this.getRegion() != null) { tc.popRegion(); + } } /** @@ -171,25 +159,23 @@ protected void endRendering(KMLTraversalContext tc, DrawContext dc) * @param tc the current KML traversal context. * @param dc the current draw context. */ - protected void preRenderFeatures(KMLTraversalContext tc, DrawContext dc) - { + protected void preRenderFeatures(KMLTraversalContext tc, DrawContext dc) { List containers = new ArrayList(); // PreRender non-container child features first, and containers second. This ensures that features closer to the // root are rendered before features deeper in the tree. In the case of an image pyramid of GroundOverlays, // this causes the deeper nested overlays (which are typically more detailed) to render on top of the more // general overlay that is higher in the tree. - for (KMLAbstractFeature feature : this.getFeatures()) - { - if (feature instanceof KMLAbstractContainer) + for (KMLAbstractFeature feature : this.getFeatures()) { + if (feature instanceof KMLAbstractContainer) { containers.add(feature); - else + } else { feature.preRender(tc, dc); + } } // Now preRender the containers - for (KMLAbstractFeature feature : containers) - { + for (KMLAbstractFeature feature : containers) { feature.preRender(tc, dc); } } @@ -201,34 +187,30 @@ protected void preRenderFeatures(KMLTraversalContext tc, DrawContext dc) * @param tc the current KML traversal context. * @param dc the current draw context. */ - protected void renderFeatures(KMLTraversalContext tc, DrawContext dc) - { + protected void renderFeatures(KMLTraversalContext tc, DrawContext dc) { List containers = new ArrayList(); // Render non-container child features first, and containers second. This ensures that features closer to the // root are rendered before features deeper in the tree. In the case of an image pyramid of GroundOverlays, // this causes the deeper nested overlays (which are typically more detailed) to render on top of the more // general overlay that is higher in the tree. - for (KMLAbstractFeature feature : this.getFeatures()) - { - if (feature instanceof KMLAbstractContainer) + for (KMLAbstractFeature feature : this.getFeatures()) { + if (feature instanceof KMLAbstractContainer) { containers.add(feature); - else + } else { feature.render(tc, dc); + } } // Now render the containers - for (KMLAbstractFeature feature : containers) - { + for (KMLAbstractFeature feature : containers) { feature.render(tc, dc); } } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLAbstractContainer)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLAbstractContainer)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -238,8 +220,9 @@ public void applyChange(KMLAbstractObject sourceValues) KMLAbstractContainer sourceContainer = (KMLAbstractContainer) sourceValues; - if (sourceContainer.getFeatures() != null && sourceContainer.getFeatures().size() > 0) + if (sourceContainer.getFeatures() != null && sourceContainer.getFeatures().size() > 0) { this.mergeFeatures(sourceContainer); + } } /** @@ -248,22 +231,19 @@ public void applyChange(KMLAbstractObject sourceValues) * * @param sourceContainer the incoming container of features. */ - protected void mergeFeatures(KMLAbstractContainer sourceContainer) - { + protected void mergeFeatures(KMLAbstractContainer sourceContainer) { // Make a copy of the existing list so we can modify it as we traverse. List featuresListCopy = new ArrayList(this.getFeatures().size()); Collections.copy(featuresListCopy, this.getFeatures()); - for (KMLAbstractFeature sourceFeature : sourceContainer.getFeatures()) - { + for (KMLAbstractFeature sourceFeature : sourceContainer.getFeatures()) { String id = sourceFeature.getId(); - if (!WWUtil.isEmpty(id)) - { - for (KMLAbstractFeature existingFeature : featuresListCopy) - { + if (!WWUtil.isEmpty(id)) { + for (KMLAbstractFeature existingFeature : featuresListCopy) { String currentId = existingFeature.getId(); - if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) + if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) { this.getFeatures().remove(existingFeature); + } } } @@ -272,10 +252,8 @@ protected void mergeFeatures(KMLAbstractContainer sourceContainer) } @Override - public void onMessage(Message msg) - { - for (KMLAbstractFeature feature : this.getFeatures()) - { + public void onMessage(Message msg) { + for (KMLAbstractFeature feature : this.getFeatures()) { feature.onMessage(msg); } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractEventParser.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractEventParser.java index 9f2d11e125..fa3eb39642 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractEventParser.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractEventParser.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -15,15 +14,14 @@ * @author tag * @version $Id: KMLAbstractEventParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractEventParser extends AbstractXMLEventParser -{ +public abstract class KMLAbstractEventParser extends AbstractXMLEventParser { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractEventParser(String namespaceURI) - { + protected KMLAbstractEventParser(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractFeature.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractFeature.java index 5c5f49360a..c48cffc243 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractFeature.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractFeature.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -30,9 +29,11 @@ * @author tag * @version $Id: KMLAbstractFeature.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractFeature extends KMLAbstractObject implements KMLRenderable -{ - /** The style selectors specified in the KML Feature element. Is empty if no selectors were specified. */ +public abstract class KMLAbstractFeature extends KMLAbstractObject implements KMLRenderable { + + /** + * The style selectors specified in the KML Feature element. Is empty if no selectors were specified. + */ protected List styleSelectors = new ArrayList(); /** * The visibility flag for the feature. This field is determined from the visibility element of the KML feature @@ -40,9 +41,13 @@ public abstract class KMLAbstractFeature extends KMLAbstractObject implements KM * fields table. */ protected Boolean visibility; // may be different from the visibility field if application has set it explicitly - /** The region specified in the KML Feature element. Is null if no region was specified. */ + /** + * The region specified in the KML Feature element. Is null if no region was specified. + */ protected KMLRegion region; - /** A balloon explicitly associated with this feature by the client. This is not a KML field of the Feature element. */ + /** + * A balloon explicitly associated with this feature by the client. This is not a KML field of the Feature element. + */ protected Balloon balloon; // not a KML schema field, merely a convenience field of this class /** @@ -50,31 +55,29 @@ public abstract class KMLAbstractFeature extends KMLAbstractObject implements KM * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractFeature(String namespaceURI) - { + protected KMLAbstractFeature(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractView) + throws XMLStreamException { + if (o instanceof KMLAbstractView) { this.setView((KMLAbstractView) o); - else if (o instanceof KMLAbstractTimePrimitive) + } else if (o instanceof KMLAbstractTimePrimitive) { this.setTimePrimitive((KMLAbstractTimePrimitive) o); - else if (o instanceof KMLAbstractStyleSelector) + } else if (o instanceof KMLAbstractStyleSelector) { this.addStyleSelector((KMLAbstractStyleSelector) o); - else if (o instanceof KMLRegion) + } else if (o instanceof KMLRegion) { this.setRegion((KMLRegion) o); - else if (o instanceof Boolean && event.asStartElement().getName().getLocalPart().equalsIgnoreCase("visibility")) + } else if (o instanceof Boolean && event.asStartElement().getName().getLocalPart().equalsIgnoreCase("visibility")) { this.setVisibility((Boolean) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public String getName() - { + public String getName() { return (String) this.getField("name"); } @@ -83,12 +86,11 @@ public String getName() * if no visibility is specified. This indicates the default visibility of true should be used. * * @return true or null to draw feature shape, otherwise false. The default - * value is true. + * value is true. * * @see #setVisibility(Boolean) */ - public Boolean getVisibility() - { + public Boolean getVisibility() { return this.visibility; } @@ -96,129 +98,109 @@ public Boolean getVisibility() * Specifies whether this KMLAbstractFeature is enabled for rendering. * * @param visibility true or null to draw this feature, otherwise false. The - * default value is true. + * default value is true. * * @see #getVisibility() */ - public void setVisibility(Boolean visibility) - { + public void setVisibility(Boolean visibility) { this.visibility = visibility; } - public Boolean getOpen() - { + public Boolean getOpen() { return (Boolean) this.getField("open"); } - public AtomPerson getAuthor() - { + public AtomPerson getAuthor() { return (AtomPerson) this.getField("author"); } - public AtomLink getLink() - { + public AtomLink getLink() { return (AtomLink) this.getField("link"); } - public String getAddress() - { + public String getAddress() { return (String) this.getField("address"); } - public XALAddressDetails getAddressDetails() - { + public XALAddressDetails getAddressDetails() { return (XALAddressDetails) this.getField("AddressDetails"); } - public String getPhoneNumber() - { + public String getPhoneNumber() { return (String) this.getField("phoneNumber"); } - public Object getSnippet() - { + public Object getSnippet() { Object o = this.getField("snippet"); - if (o != null) + if (o != null) { return o; + } return this.getField("Snippet"); } - public String getSnippetText() - { + public String getSnippetText() { Object o = this.getField("snippet"); - if (o != null) + if (o != null) { return ((String) o).trim(); + } KMLSnippet snippet = (KMLSnippet) this.getSnippet(); - if (snippet != null && snippet.getCharacters() != null) + if (snippet != null && snippet.getCharacters() != null) { return snippet.getCharacters().trim(); // trim because string parser might not have parsed it - + } return null; } - public String getDescription() - { + public String getDescription() { return (String) this.getField("description"); } - protected void setView(KMLAbstractView o) - { + protected void setView(KMLAbstractView o) { this.setField("AbstractView", o); } - public KMLAbstractView getView() - { + public KMLAbstractView getView() { return (KMLAbstractView) this.getField("AbstractView"); } - protected void setTimePrimitive(KMLAbstractTimePrimitive o) - { + protected void setTimePrimitive(KMLAbstractTimePrimitive o) { this.setField("AbstractTimePrimitive", o); } - public KMLAbstractTimePrimitive getTimePrimitive() - { + public KMLAbstractTimePrimitive getTimePrimitive() { return (KMLAbstractTimePrimitive) this.getField("AbstractTimePrimitive"); } - public KMLStyleUrl getStyleUrl() - { + public KMLStyleUrl getStyleUrl() { return (KMLStyleUrl) this.getField("styleUrl"); } - protected void addStyleSelector(KMLAbstractStyleSelector o) - { + protected void addStyleSelector(KMLAbstractStyleSelector o) { this.styleSelectors.add(o); } - public List getStyleSelectors() - { + public List getStyleSelectors() { return this.styleSelectors; } - public boolean hasStyleSelectors() - { + public boolean hasStyleSelectors() { return this.getStyleSelectors() != null && this.getStyleSelectors().size() > 0; } - public boolean hasStyle() - { + public boolean hasStyle() { return this.hasStyleSelectors() || this.getStyleUrl() != null; } - public KMLRegion getRegion() - { + public KMLRegion getRegion() { return this.region; } - protected void setRegion(KMLRegion region) - { + protected void setRegion(KMLRegion region) { this.region = region; } - public KMLExtendedData getExtendedData() - { + public KMLExtendedData getExtendedData() { return (KMLExtendedData) this.getField("ExtendedData"); } @@ -230,8 +212,7 @@ public KMLExtendedData getExtendedData() * * @param balloon New balloon. */ - public void setBalloon(Balloon balloon) - { + public void setBalloon(Balloon balloon) { this.balloon = balloon; } @@ -240,53 +221,52 @@ public void setBalloon(Balloon balloon) * * @return The balloon associated with the feature. Returns null if there is no associated balloon. */ - public Balloon getBalloon() - { + public Balloon getBalloon() { return this.balloon; } - /** {@inheritDoc} */ - public void preRender(KMLTraversalContext tc, DrawContext dc) - { - if (tc == null) - { + /** + * {@inheritDoc} + */ + public void preRender(KMLTraversalContext tc, DrawContext dc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.isFeatureActive(tc, dc)) + if (!this.isFeatureActive(tc, dc)) { return; + } this.doPreRender(tc, dc); } - /** {@inheritDoc} */ - public void render(KMLTraversalContext tc, DrawContext dc) - { - if (tc == null) - { + /** + * {@inheritDoc} + */ + public void render(KMLTraversalContext tc, DrawContext dc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.isFeatureActive(tc, dc)) + if (!this.isFeatureActive(tc, dc)) { return; + } this.doRender(tc, dc); } @@ -301,22 +281,22 @@ public void render(KMLTraversalContext tc, DrawContext dc) * If this feature has no Region, this inherits the Region of its nearest ancestor by using the Region on the top of * the KML traversal context's region stack (if any). If there is no ancestor Region this feature is assumed to be * the DrawContext's view and is rendered according to its visibility flag. A Region is - * considered active if it is visible, and the DrawContext meets the Region's level of detail - * criteria. + * considered active if it is visible, and the DrawContext meets the Region's level of detail criteria. * * @param tc the current KML traversal context. Specifies an inherited Region (if any) and a detail hint. * @param dc the current draw context. Used to determine whether this feature's Region is active. * * @return true if this feature should be rendered, otherwise false. */ - protected boolean isFeatureActive(KMLTraversalContext tc, DrawContext dc) - { - if (this.getVisibility() != null && !this.getVisibility()) + protected boolean isFeatureActive(KMLTraversalContext tc, DrawContext dc) { + if (this.getVisibility() != null && !this.getVisibility()) { return false; + } KMLRegion region = this.getRegion(); - if (region == null) + if (region == null) { region = tc.peekRegion(); + } return region == null || region.isActive(tc, dc); } @@ -328,8 +308,7 @@ protected boolean isFeatureActive(KMLTraversalContext tc, DrawContext dc) * @param tc the current KML traversal context. * @param dc the current draw context. */ - protected void doPreRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doPreRender(KMLTraversalContext tc, DrawContext dc) { // Subclasses override to implement render behavior. } @@ -340,8 +319,7 @@ protected void doPreRender(KMLTraversalContext tc, DrawContext dc) * @param tc the current KML traversal context. * @param dc the current draw context. */ - protected void doRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doRender(KMLTraversalContext tc, DrawContext dc) { // Subclasses override to implement render behavior. } @@ -353,10 +331,10 @@ protected void doRender(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @SuppressWarnings({"UnusedDeclaration"}) - protected void renderBalloon(KMLTraversalContext tc, DrawContext dc) - { - if (this.getBalloon() != null) + protected void renderBalloon(KMLTraversalContext tc, DrawContext dc) { + if (this.getBalloon() != null) { this.getBalloon().render(dc); + } } /** @@ -369,26 +347,23 @@ protected void renderBalloon(KMLTraversalContext tc, DrawContext dc) * StyleMap style selector contains a reference to an external Style and that reference has not been resolved. * * @param styleState the style mode, either \"normal\" or \"highlight\". - * @param subStyle an instance of the sub-style desired, such as {@link gov.nasa.worldwind.ogc.kml.KMLIconStyle}. - * The effective sub-style values are accumulated and merged into this instance. The instance - * should not be one from within the KML document because its values are overridden and augmented; - * it's just an independent variable in which to return the merged attribute values. For - * convenience, the instance specified is returned as the return value of this method. + * @param subStyle an instance of the sub-style desired, such as {@link gov.nasa.worldwind.ogc.kml.KMLIconStyle}. + * The effective sub-style values are accumulated and merged into this instance. The instance should not be one from + * within the KML document because its values are overridden and augmented; it's just an independent variable in + * which to return the merged attribute values. For convenience, the instance specified is returned as the return + * value of this method. * * @return the sub-style values for the specified type and state. The reference returned is the one passed in as the - * subStyle argument. + * subStyle argument. */ - public KMLAbstractSubStyle getSubStyle(KMLAbstractSubStyle subStyle, String styleState) - { + public KMLAbstractSubStyle getSubStyle(KMLAbstractSubStyle subStyle, String styleState) { return KMLAbstractStyleSelector.mergeSubStyles(this.getStyleUrl(), this.getStyleSelectors(), styleState, - subStyle); + subStyle); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLAbstractFeature)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLAbstractFeature)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -398,14 +373,15 @@ public void applyChange(KMLAbstractObject sourceValues) KMLAbstractFeature sourceFeature = (KMLAbstractFeature) sourceValues; - if (sourceValues.hasField("visibility")) + if (sourceValues.hasField("visibility")) { this.setVisibility((Boolean) sourceFeature.getField("visibility")); + } - if (sourceFeature.getRegion() != null) + if (sourceFeature.getRegion() != null) { this.setRegion(sourceFeature.getRegion()); + } - if (sourceFeature.getStyleSelectors() != null && sourceFeature.getStyleSelectors().size() > 0) - { + if (sourceFeature.getStyleSelectors() != null && sourceFeature.getStyleSelectors().size() > 0) { this.mergeStyleSelectors(sourceFeature); this.onChange(new Message(KMLAbstractObject.MSG_STYLE_CHANGED, this)); } @@ -417,23 +393,18 @@ public void applyChange(KMLAbstractObject sourceValues) * * @param sourceFeature the incoming style selectors. */ - protected void mergeStyleSelectors(KMLAbstractFeature sourceFeature) - { + protected void mergeStyleSelectors(KMLAbstractFeature sourceFeature) { // Make a copy of the existing list so we can modify it as we traverse the copy. - List styleSelectorsCopy = - new ArrayList(this.getStyleSelectors().size()); + List styleSelectorsCopy + = new ArrayList(this.getStyleSelectors().size()); styleSelectorsCopy.addAll(this.getStyleSelectors()); - for (KMLAbstractStyleSelector sourceSelector : sourceFeature.getStyleSelectors()) - { + for (KMLAbstractStyleSelector sourceSelector : sourceFeature.getStyleSelectors()) { String id = sourceSelector.getId(); - if (!WWUtil.isEmpty(id)) - { - for (KMLAbstractStyleSelector existingSelector : styleSelectorsCopy) - { + if (!WWUtil.isEmpty(id)) { + for (KMLAbstractStyleSelector existingSelector : styleSelectorsCopy) { String currentId = existingSelector.getId(); - if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) - { + if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) { this.getStyleSelectors().remove(existingSelector); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractGeometry.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractGeometry.java index aa52b6a8e5..cc78db5e20 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractGeometry.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractGeometry.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -15,23 +14,20 @@ * @author tag * @version $Id: KMLAbstractGeometry.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractGeometry extends KMLAbstractObject -{ +public abstract class KMLAbstractGeometry extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractGeometry(String namespaceURI) - { + protected KMLAbstractGeometry(String namespaceURI) { super(namespaceURI); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLAbstractGeometry)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLAbstractGeometry)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractLatLonBoxType.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractLatLonBoxType.java index c192800b57..b35cbc8614 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractLatLonBoxType.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractLatLonBoxType.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -15,43 +14,36 @@ * @author tag * @version $Id: KMLAbstractLatLonBoxType.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractLatLonBoxType extends KMLAbstractObject -{ +public abstract class KMLAbstractLatLonBoxType extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractLatLonBoxType(String namespaceURI) - { + protected KMLAbstractLatLonBoxType(String namespaceURI) { super(namespaceURI); } - public Double getNorth() - { + public Double getNorth() { return (Double) this.getField("north"); } - public Double getSouth() - { + public Double getSouth() { return (Double) this.getField("south"); } - public Double getEast() - { + public Double getEast() { return (Double) this.getField("east"); } - public Double getWest() - { + public Double getWest() { return (Double) this.getField("west"); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLAbstractLatLonBoxType)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLAbstractLatLonBoxType)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractObject.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractObject.java index 1ffa092193..09465f39f4 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractObject.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractObject.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLAbstractObject.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractObject extends AbstractXMLEventParser implements MessageListener -{ +public abstract class KMLAbstractObject extends AbstractXMLEventParser implements MessageListener { + public static final String MSG_BOX_CHANGED = "KMLAbstractObject.BoxChanged"; public static final String MSG_GEOMETRY_CHANGED = "KMLAbstractObject.GeometryChanged"; public static final String MSG_LINK_CHANGED = "KMLAbstractObject.LinkChanged"; @@ -28,8 +27,7 @@ public abstract class KMLAbstractObject extends AbstractXMLEventParser implement public static final String MSG_TIME_CHANGED = "KMLAbstractObject.TimeChanged"; public static final String MSG_VIEW_CHANGED = "KMLAbstractObject.ViewChanged"; - protected KMLAbstractObject() - { + protected KMLAbstractObject() { super(); } @@ -38,8 +36,7 @@ protected KMLAbstractObject() * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractObject(String namespaceURI) - { + protected KMLAbstractObject(String namespaceURI) { super(namespaceURI); } @@ -48,8 +45,7 @@ protected KMLAbstractObject(String namespaceURI) * * @return the id of this object, or null if it's not specified in the element. */ - public String getId() - { + public String getId() { return (String) this.getField("id"); } @@ -58,40 +54,34 @@ public String getId() * * @return the targetId of this object, or null if it's not specified in the element. */ - public String getTargetId() - { + public String getTargetId() { return (String) this.getField("targetId"); } @Override - public KMLRoot getRoot() - { + public KMLRoot getRoot() { XMLEventParser root = super.getRoot(); return root instanceof KMLRoot ? (KMLRoot) root : null; } - public void onMessage(Message msg) - { + public void onMessage(Message msg) { // Empty implementation } - public void onChange(Message msg) - { - if (this.getParent() != null) + public void onChange(Message msg) { + if (this.getParent() != null) { ((KMLAbstractObject) this.getParent()).onChange(msg); + } } - public void applyChange(KMLAbstractObject sourceValues) - { - if (sourceValues == null) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (sourceValues == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); } - for (Map.Entry entry : sourceValues.getFields().getEntries()) - { + for (Map.Entry entry : sourceValues.getFields().getEntries()) { this.setField(entry.getKey(), entry.getValue()); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractOverlay.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractOverlay.java index e75a44a465..ecc24167bb 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractOverlay.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractOverlay.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,30 +11,26 @@ * @author tag * @version $Id: KMLAbstractOverlay.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractOverlay extends KMLAbstractFeature -{ +public abstract class KMLAbstractOverlay extends KMLAbstractFeature { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractOverlay(String namespaceURI) - { + protected KMLAbstractOverlay(String namespaceURI) { super(namespaceURI); } - public String getColor() - { + public String getColor() { return (String) this.getField("color"); } - public Integer getDrawOrder() - { + public Integer getDrawOrder() { return (Integer) this.getField("drawOrder"); } - public KMLIcon getIcon() - { + public KMLIcon getIcon() { return (KMLIcon) this.getField("Icon"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractStyleSelector.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractStyleSelector.java index ef1f3c3d80..138953f022 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractStyleSelector.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractStyleSelector.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.avlist.AVKey; @@ -17,15 +16,14 @@ * @author tag * @version $Id: KMLAbstractStyleSelector.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractStyleSelector extends KMLAbstractObject -{ +public abstract class KMLAbstractStyleSelector extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractStyleSelector(String namespaceURI) - { + protected KMLAbstractStyleSelector(String namespaceURI) { super(namespaceURI); } @@ -38,45 +36,40 @@ protected KMLAbstractStyleSelector(String namespaceURI) * sub-style is marked with a field named {@link gov.nasa.worldwind.avlist.AVKey#UNRESOLVED}. The same is true when * a StyleMap refers to a Style other than one internal to the KML document. * - * @param styleUrl an applicable style URL. May be null. + * @param styleUrl an applicable style URL. May be null. * @param styleSelectors a list of {@link gov.nasa.worldwind.ogc.kml.KMLAbstractStyleSelector}s to consider when - * determining the effective attributes. May be null, in which case only the specified - * styleUrl is considered. - * @param styleState the style mode, either \"normal\" or \"highlight\". - * @param subStyle an instance of the {@link gov.nasa.worldwind.ogc.kml.KMLAbstractSubStyle} class desired, - * such as {@link gov.nasa.worldwind.ogc.kml.KMLIconStyle}. The effective style values are - * accumulated and merged into this instance. The instance should not be one from within the - * KML document because its values may be overridden and augmented. The instance specified is - * the return value of this method. + * determining the effective attributes. May be null, in which case only the specified styleUrl is + * considered. + * @param styleState the style mode, either \"normal\" or \"highlight\". + * @param subStyle an instance of the {@link gov.nasa.worldwind.ogc.kml.KMLAbstractSubStyle} class desired, such as + * {@link gov.nasa.worldwind.ogc.kml.KMLIconStyle}. The effective style values are accumulated and merged into this + * instance. The instance should not be one from within the KML document because its values may be overridden and + * augmented. The instance specified is the return value of this method. * * @return the sub-style values for the specified type and state. The reference returned is the same one passed in - * as the subStyle argument. + * as the subStyle argument. * * @throws IllegalArgumentException if the sub-style parameter is null. */ public static KMLAbstractSubStyle mergeSubStyles(KMLStyleUrl styleUrl, - List styleSelectors, String styleState, KMLAbstractSubStyle subStyle) - { - if (subStyle == null) - { + List styleSelectors, String styleState, KMLAbstractSubStyle subStyle) { + if (subStyle == null) { String message = Logging.getMessage("nullValue.SymbolIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (styleUrl != null) - { + if (styleUrl != null) { KMLAbstractStyleSelector selector = styleUrl.resolveStyleUrl(); - if (selector != null) + if (selector != null) { mergeSubStyles(null, selector, styleState, subStyle); - else + } else { markUnresolved(true, subStyle); + } } - if (styleSelectors != null) - { - for (KMLAbstractStyleSelector selector : styleSelectors) - { + if (styleSelectors != null) { + for (KMLAbstractStyleSelector selector : styleSelectors) { mergeSubStyles(null, selector, styleState, subStyle); } } @@ -92,47 +85,43 @@ public static KMLAbstractSubStyle mergeSubStyles(KMLStyleUrl styleUrl, * Remote styleUrls that have not yet been resolved are not included in the result. In this case the returned * sub-style is marked with the value {@link gov.nasa.worldwind.avlist.AVKey#UNRESOLVED}. * - * @param styleUrl an applicable style URL. May be null. + * @param styleUrl an applicable style URL. May be null. * @param styleSelector the {@link gov.nasa.worldwind.ogc.kml.KMLAbstractStyleSelector} to consider when determining - * the effective attributes. May be null, in which case only the specified - * styleUrl is considered. - * @param styleState the style mode, either \"normal\" or \"highlight\". - * @param subStyle an instance of the {@link gov.nasa.worldwind.ogc.kml.KMLAbstractSubStyle} class desired, - * such as {@link gov.nasa.worldwind.ogc.kml.KMLIconStyle}. The effective style values are - * accumulated and merged into this instance. The instance should not be one from within the - * KML document because its values may be overridden and augmented. The instance specified is - * the return value of this method. + * the effective attributes. May be null, in which case only the specified styleUrl is considered. + * @param styleState the style mode, either \"normal\" or \"highlight\". + * @param subStyle an instance of the {@link gov.nasa.worldwind.ogc.kml.KMLAbstractSubStyle} class desired, such as + * {@link gov.nasa.worldwind.ogc.kml.KMLIconStyle}. The effective style values are accumulated and merged into this + * instance. The instance should not be one from within the KML document because its values may be overridden and + * augmented. The instance specified is the return value of this method. * * @return the sub-style values for the specified type and state. The reference returned is the same one passed in - * as the subStyle parameter. + * as the subStyle parameter. * * @throws IllegalArgumentException if the sub-style parameter is null. */ public static KMLAbstractSubStyle mergeSubStyles(KMLStyleUrl styleUrl, - KMLAbstractStyleSelector styleSelector, String styleState, KMLAbstractSubStyle subStyle) - { - if (subStyle == null) - { + KMLAbstractStyleSelector styleSelector, String styleState, KMLAbstractSubStyle subStyle) { + if (subStyle == null) { String message = Logging.getMessage("nullValue.SymbolIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (styleUrl != null) - { + if (styleUrl != null) { KMLAbstractStyleSelector ss = styleUrl.resolveStyleUrl(); - if (ss != null) + if (ss != null) { mergeSubStyles(null, ss, styleState, subStyle); - else + } else { markUnresolved(true, subStyle); + } } - if (styleSelector != null) - { - if (styleSelector instanceof KMLStyleMap) + if (styleSelector != null) { + if (styleSelector instanceof KMLStyleMap) { ((KMLStyleMap) styleSelector).mergeSubStyles(subStyle, styleState); - else + } else { ((KMLStyle) styleSelector).mergeSubStyle(subStyle); + } } return subStyle; @@ -142,14 +131,14 @@ public static KMLAbstractSubStyle mergeSubStyles(KMLStyleUrl styleUrl, * Marks a sub-style to indicate that a style URL associated with it has not yet been resolved, or removes the mark * if the style URL has been resolved. * - * @param tf true to indicate an unresolved style URL, otherwise false. + * @param tf true to indicate an unresolved style URL, otherwise false. * @param subStyle the sub-style to mark. */ - protected static void markUnresolved(boolean tf, KMLAbstractSubStyle subStyle) - { - if (!tf) + protected static void markUnresolved(boolean tf, KMLAbstractSubStyle subStyle) { + if (!tf) { subStyle.removeField(AVKey.UNRESOLVED); - else + } else { subStyle.setField(AVKey.UNRESOLVED, System.currentTimeMillis()); + } } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractSubStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractSubStyle.java index 6bd6cdeefc..31a1a6b1d2 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractSubStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractSubStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -15,23 +14,20 @@ * @author tag * @version $Id: KMLAbstractSubStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractSubStyle extends KMLAbstractObject -{ +public abstract class KMLAbstractSubStyle extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractSubStyle(String namespaceURI) - { + protected KMLAbstractSubStyle(String namespaceURI) { super(namespaceURI); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLAbstractSubStyle)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLAbstractSubStyle)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractTimePrimitive.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractTimePrimitive.java index 1c31288dac..63c8b6de28 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractTimePrimitive.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractTimePrimitive.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -15,23 +14,20 @@ * @author tag * @version $Id: KMLAbstractTimePrimitive.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractTimePrimitive extends KMLAbstractObject -{ +public abstract class KMLAbstractTimePrimitive extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - protected KMLAbstractTimePrimitive(String namespaceURI) - { + protected KMLAbstractTimePrimitive(String namespaceURI) { super(namespaceURI); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLAbstractTimePrimitive)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLAbstractTimePrimitive)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractView.java b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractView.java index a676cd2ba6..2570d9808f 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAbstractView.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAbstractView.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -15,18 +14,15 @@ * @author tag * @version $Id: KMLAbstractView.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class KMLAbstractView extends KMLAbstractObject -{ - protected KMLAbstractView(String namespaceURI) - { +public abstract class KMLAbstractView extends KMLAbstractObject { + + protected KMLAbstractView(String namespaceURI) { super(namespaceURI); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLAbstractView)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLAbstractView)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLAlias.java b/src/gov/nasa/worldwind/ogc/kml/KMLAlias.java index a51a9c0daf..4e62e573c5 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLAlias.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLAlias.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,25 +11,22 @@ * @author tag * @version $Id: KMLAlias.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLAlias extends KMLAbstractObject -{ +public class KMLAlias extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLAlias(String namespaceURI) - { + public KMLAlias(String namespaceURI) { super(namespaceURI); } - public String getTargetHref() - { + public String getTargetHref() { return (String) this.getField("targetHref"); } - public String getSourceRef() - { + public String getSourceRef() { return (String) this.getField("sourceHref"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLBalloonStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLBalloonStyle.java index 8f841530fa..2d2573b7cb 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLBalloonStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLBalloonStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,15 +11,14 @@ * @author tag * @version $Id: KMLBalloonStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLBalloonStyle extends KMLAbstractSubStyle -{ +public class KMLBalloonStyle extends KMLAbstractSubStyle { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLBalloonStyle(String namespaceURI) - { + public KMLBalloonStyle(String namespaceURI) { super(namespaceURI); } @@ -31,8 +29,7 @@ public KMLBalloonStyle(String namespaceURI) * * @return the background color as a hexadecimal string. */ - public String getColor() - { + public String getColor() { return (String) this.getField("color"); } @@ -42,13 +39,11 @@ public String getColor() * * @return the background color as a hexadecimal string. */ - public String getBgColor() - { + public String getBgColor() { return (String) this.getField("bgColor"); } - public String getTextColor() - { + public String getTextColor() { return (String) this.getField("textColor"); } @@ -57,13 +52,11 @@ public String getTextColor() * * @return Balloon text field. */ - public String getText() - { + public String getText() { return (String) this.getField("text"); } - public String getDisplayMode() - { + public String getDisplayMode() { return (String) this.getField("displayMode"); } @@ -73,12 +66,11 @@ public String getDisplayMode() * * @return True if at least one of the BalloonStyle fields is set (text, displayMode, bgColor, etc). */ - public boolean hasStyleFields() - { + public boolean hasStyleFields() { return this.hasField("text") - || this.hasField("bgColor") - || this.hasField("textColor") - || this.hasField("color") - || this.hasField("displayMode"); + || this.hasField("bgColor") + || this.hasField("textColor") + || this.hasField("color") + || this.hasField("displayMode"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLBoundary.java b/src/gov/nasa/worldwind/ogc/kml/KMLBoundary.java index 8e4d11dfa6..4a6b6c4890 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLBoundary.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLBoundary.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,20 +11,18 @@ * @author tag * @version $Id: KMLBoundary.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLBoundary extends KMLAbstractObject -{ +public class KMLBoundary extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLBoundary(String namespaceURI) - { + public KMLBoundary(String namespaceURI) { super(namespaceURI); } - public KMLLinearRing getLinearRing() - { + public KMLLinearRing getLinearRing() { return (KMLLinearRing) this.getField("LinearRing"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLCamera.java b/src/gov/nasa/worldwind/ogc/kml/KMLCamera.java index 6eadb310e5..f18f4725e6 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLCamera.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLCamera.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,50 +11,42 @@ * @author tag * @version $Id: KMLCamera.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLCamera extends KMLAbstractView -{ +public class KMLCamera extends KMLAbstractView { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLCamera(String namespaceURI) - { + public KMLCamera(String namespaceURI) { super(namespaceURI); } - public Double getLongitude() - { + public Double getLongitude() { return (Double) this.getField("longitude"); } - public Double getLatitude() - { + public Double getLatitude() { return (Double) this.getField("latitude"); } - public Double getAltitude() - { + public Double getAltitude() { return (Double) this.getField("altitude"); } - public Double getHeading() - { + public Double getHeading() { return (Double) this.getField("heading"); } - public Double getTilt() - { + public Double getTilt() { return (Double) this.getField("tilt"); } - public Double getRoll() - { + public Double getRoll() { return (Double) this.getField("roll"); } - public String getAltitudeMode() - { + public String getAltitudeMode() { return (String) this.getField("altitudeMode"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLChange.java b/src/gov/nasa/worldwind/ogc/kml/KMLChange.java index 313938f95b..78179247c5 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLChange.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLChange.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.WWUtil; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLChange.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLChange extends AbstractXMLEventParser implements KMLUpdateOperation -{ +public class KMLChange extends AbstractXMLEventParser implements KMLUpdateOperation { + protected List objects = new ArrayList(); /** @@ -28,42 +27,39 @@ public class KMLChange extends AbstractXMLEventParser implements KMLUpdateOperat * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLChange(String namespaceURI) - { + public KMLChange(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractObject) + throws XMLStreamException { + if (o instanceof KMLAbstractObject) { this.addObject((KMLAbstractObject) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addObject(KMLAbstractObject o) - { + protected void addObject(KMLAbstractObject o) { this.objects.add(o); } - public List getObjects() - { + public List getObjects() { return this.objects; } - public void applyOperation(KMLRoot targetRoot) - { - for (KMLAbstractObject sourceValues : this.objects) - { + public void applyOperation(KMLRoot targetRoot) { + for (KMLAbstractObject sourceValues : this.objects) { String targetId = sourceValues.getTargetId(); - if (WWUtil.isEmpty(targetId)) + if (WWUtil.isEmpty(targetId)) { continue; + } Object o = targetRoot.getItemByID(targetId); - if (o == null || !(o instanceof KMLAbstractObject)) + if (o == null || !(o instanceof KMLAbstractObject)) { continue; + } KMLAbstractObject objectToChange = (KMLAbstractObject) o; diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLConstants.java b/src/gov/nasa/worldwind/ogc/kml/KMLConstants.java index a547812e12..8ee7363424 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLConstants.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLConstants.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.ogc.collada.ColladaConstants; @@ -14,16 +13,20 @@ * @author tag * @version $Id: KMLConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface KMLConstants -{ - /** The KML 2.2 namespace URI. */ +public interface KMLConstants { + + /** + * The KML 2.2 namespace URI. + */ final String KML_2dot0_NAMESPACE = "http://earth.google.com/kml/2.0"; final String KML_2dot1_NAMESPACE = "http://earth.google.com/kml/2.1"; final String KML_2dot2_NAMESPACE = "http://www.opengis.net/kml/2.2"; final String KML_GOOGLE_2dot2_NAMESPACE = "http://earth.google.com/kml/2.2"; final String KML_NAMESPACE = KML_2dot2_NAMESPACE; - /** List of the versioned KML namespaces. */ + /** + * List of the versioned KML namespaces. + */ final String[] KML_NAMESPACES = { KML_2dot2_NAMESPACE, KML_GOOGLE_2dot2_NAMESPACE, @@ -31,16 +34,24 @@ public interface KMLConstants KML_2dot0_NAMESPACE }; - /** The mime type for KML documents. */ + /** + * The mime type for KML documents. + */ final String KML_MIME_TYPE = "application/vnd.google-earth.kml+xml"; - /** The mime type for KMZ documents. */ + /** + * The mime type for KMZ documents. + */ final String KMZ_MIME_TYPE = "application/vnd.google-earth.kmz"; - /** @deprecated Use {@link ColladaConstants#COLLADA_MIME_TYPE}. */ + /** + * @deprecated Use {@link ColladaConstants#COLLADA_MIME_TYPE}. + */ @Deprecated final String COLLADA_MIME_TYPE = ColladaConstants.COLLADA_MIME_TYPE; - /** Most recent version of KML that WorldWind supports. */ + /** + * Most recent version of KML that WorldWind supports. + */ final String KML_VERSION = "2.2"; // Style state enums diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLCoordinateTokenizer.java b/src/gov/nasa/worldwind/ogc/kml/KMLCoordinateTokenizer.java index 66290fcb65..0d353c30b7 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLCoordinateTokenizer.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLCoordinateTokenizer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.geom.Position; @@ -25,20 +24,18 @@ * For example: *
          * -18.3,23.56,9     34.9, 56.0, 2     56.9, 19     90.0,23.9,44
        - * 
        - * Will be tokenized to four coordinates: (23.56, -18.3, 9), (56.0, 34.9, 2), (56.9, 19, 0), and (90, 23.9, 44). + * Will be tokenized to four coordinates: (23.56, -18.3, 9), (56.0, 34.9, 2), (56.9, 19, 0), and (90, 23.9, 44). *

        * The tokenizer also handles coordinate strings with no embedded white space. For example: *

          * -18.3,23.56,9,34.9,56.0,2
        - * 
        - * Will be tokenized to two coordinates: (23.56, -18.3, 9), (56.0, 34.9, 2) + * Will be tokenized to two coordinates: (23.56, -18.3, 9), (56.0, 34.9, 2) * * @author pabercrombie * @version $Id: KMLCoordinateTokenizer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLCoordinateTokenizer -{ +public class KMLCoordinateTokenizer { + protected int i; protected char[] buffer; @@ -54,8 +51,7 @@ public class KMLCoordinateTokenizer * * @param s String to read from. */ - public KMLCoordinateTokenizer(String s) - { + public KMLCoordinateTokenizer(String s) { this.buffer = s.trim().toCharArray(); } @@ -64,8 +60,7 @@ public KMLCoordinateTokenizer(String s) * * @return True if there are more coordinates to read from the string. */ - public boolean hasMoreTokens() - { + public boolean hasMoreTokens() { return i < buffer.length; } @@ -76,60 +71,57 @@ public boolean hasMoreTokens() * * @throws NumberFormatException if the coordinates cannot be parsed to a number. */ - public Position nextPosition() throws NumberFormatException - { + public Position nextPosition() throws NumberFormatException { this.words.clear(); - while (this.i < this.buffer.length) - { + while (this.i < this.buffer.length) { char ch = this.buffer[this.i++]; - if (Character.isWhitespace(ch)) - { - if (this.inWord) + if (Character.isWhitespace(ch)) { + if (this.inWord) { wordBoundary(); + } // If the last separator was a comma, don't break. Wait for another word. - if (!this.afterComma && this.words.size() >= 2) + if (!this.afterComma && this.words.size() >= 2) { break; - } - else if (ch == ',') - { - if (this.inWord) + } + } else if (ch == ',') { + if (this.inWord) { wordBoundary(); + } this.afterComma = true; // Three words make a complete coordinate. Break out of the loop and return the coordinate. - if (this.words.size() >= 3) + if (this.words.size() >= 3) { break; - } - else - { + } + } else { this.inWord = true; this.afterComma = false; this.nextWord.append(ch); } } - if (this.inWord) + if (this.inWord) { this.wordBoundary(); + } return this.makePosition(); } - protected Position makePosition() - { - if (this.words.size() > 2) + protected Position makePosition() { + if (this.words.size() > 2) { return Position.fromDegrees(Double.valueOf(this.words.get(1)), Double.valueOf(this.words.get(0)), - Double.valueOf(this.words.get(2))); - else if (this.words.size() == 2) + Double.valueOf(this.words.get(2))); + } else if (this.words.size() == 2) { return Position.fromDegrees(Double.valueOf(this.words.get(1)), Double.valueOf(this.words.get(0))); + } return null; } - protected void wordBoundary() - { + protected void wordBoundary() { this.inWord = false; this.words.add(this.nextWord.toString()); this.nextWord = new StringBuilder(); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLCoordinatesParser.java b/src/gov/nasa/worldwind/ogc/kml/KMLCoordinatesParser.java index 6550b8f2c3..7d9fdd8bb6 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLCoordinatesParser.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLCoordinatesParser.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.geom.Position; @@ -19,45 +18,36 @@ * @author tag * @version $Id: KMLCoordinatesParser.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLCoordinatesParser extends AbstractXMLEventParser -{ - public KMLCoordinatesParser() - { +public class KMLCoordinatesParser extends AbstractXMLEventParser { + + public KMLCoordinatesParser() { } - public KMLCoordinatesParser(String namespaceURI) - { + public KMLCoordinatesParser(String namespaceURI) { super(namespaceURI); } - @SuppressWarnings( {"UnnecessaryContinue"}) + @SuppressWarnings({"UnnecessaryContinue"}) public Position.PositionList parse(XMLEventParserContext ctx, XMLEvent doubleEvent, Object... args) - throws XMLStreamException - { + throws XMLStreamException { String s = ctx.getStringParser().parseString(ctx, doubleEvent); if (s == null || s.length() < 3) // "a,b" is the smallest possible coordinate string + { return null; + } ArrayList positions = new ArrayList(); KMLCoordinateTokenizer tokenizer = new KMLCoordinateTokenizer(s); - while (tokenizer.hasMoreTokens()) - { - try - { + while (tokenizer.hasMoreTokens()) { + try { positions.add(tokenizer.nextPosition()); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { continue; // TODO: issue warning? - } - catch (NullPointerException e) - { + } catch (NullPointerException e) { continue; // TODO: issue warning? - } - catch (Exception e) - { + } catch (Exception e) { continue; // TODO: issue warning } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLCreate.java b/src/gov/nasa/worldwind/ogc/kml/KMLCreate.java index c5df8f17e8..bd15610be7 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLCreate.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLCreate.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.WWUtil; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLCreate.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLCreate extends AbstractXMLEventParser implements KMLUpdateOperation -{ +public class KMLCreate extends AbstractXMLEventParser implements KMLUpdateOperation { + protected List containers = new ArrayList(); /** @@ -28,47 +27,43 @@ public class KMLCreate extends AbstractXMLEventParser implements KMLUpdateOperat * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLCreate(String namespaceURI) - { + public KMLCreate(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractContainer) + throws XMLStreamException { + if (o instanceof KMLAbstractContainer) { this.addContainer((KMLAbstractContainer) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addContainer(KMLAbstractContainer o) - { + protected void addContainer(KMLAbstractContainer o) { this.containers.add(o); } - public List getContainers() - { + public List getContainers() { return this.containers; } - public void applyOperation(KMLRoot targetRoot) - { - for (KMLAbstractContainer container : this.containers) - { + public void applyOperation(KMLRoot targetRoot) { + for (KMLAbstractContainer container : this.containers) { String targetId = container.getTargetId(); - if (WWUtil.isEmpty(targetId)) + if (WWUtil.isEmpty(targetId)) { continue; + } Object o = targetRoot.getItemByID(targetId); - if (o == null || !(o instanceof KMLAbstractContainer)) + if (o == null || !(o instanceof KMLAbstractContainer)) { continue; + } KMLAbstractContainer receivingContainer = (KMLAbstractContainer) o; - for (KMLAbstractFeature feature : container.getFeatures()) - { + for (KMLAbstractFeature feature : container.getFeatures()) { receivingContainer.addFeature(feature); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLData.java b/src/gov/nasa/worldwind/ogc/kml/KMLData.java index 01d8afed34..31dca5764a 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLData.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLData.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,30 +11,26 @@ * @author tag * @version $Id: KMLData.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLData extends KMLAbstractObject -{ +public class KMLData extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLData(String namespaceURI) - { + public KMLData(String namespaceURI) { super(namespaceURI); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public String getDisplayName() - { + public String getDisplayName() { return (String) this.getField("displayName"); } - public String getValue() - { + public String getValue() { return (String) this.getField("value"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLDelete.java b/src/gov/nasa/worldwind/ogc/kml/KMLDelete.java index b250b15d08..85b97f6b74 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLDelete.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLDelete.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.WWUtil; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLDelete.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLDelete extends AbstractXMLEventParser implements KMLUpdateOperation -{ +public class KMLDelete extends AbstractXMLEventParser implements KMLUpdateOperation { + protected List features = new ArrayList(); /** @@ -28,48 +27,46 @@ public class KMLDelete extends AbstractXMLEventParser implements KMLUpdateOperat * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLDelete(String namespaceURI) - { + public KMLDelete(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractFeature) + throws XMLStreamException { + if (o instanceof KMLAbstractFeature) { this.addFeature((KMLAbstractFeature) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addFeature(KMLAbstractFeature o) - { + protected void addFeature(KMLAbstractFeature o) { this.features.add(o); } - public List getFeatures() - { + public List getFeatures() { return this.features; } - public void applyOperation(KMLRoot targetRoot) - { - for (KMLAbstractFeature feature : this.features) - { + public void applyOperation(KMLRoot targetRoot) { + for (KMLAbstractFeature feature : this.features) { String targetId = feature.getTargetId(); - if (WWUtil.isEmpty(targetId)) + if (WWUtil.isEmpty(targetId)) { continue; + } Object o = targetRoot.getItemByID(targetId); - if (o == null || !(o instanceof KMLAbstractFeature)) + if (o == null || !(o instanceof KMLAbstractFeature)) { continue; + } KMLAbstractFeature featureToDelete = (KMLAbstractFeature) o; Object p = featureToDelete.getParent(); - if (!(p instanceof KMLAbstractContainer)) + if (!(p instanceof KMLAbstractContainer)) { continue; + } ((KMLAbstractContainer) p).removeFeature(featureToDelete); } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLDocument.java b/src/gov/nasa/worldwind/ogc/kml/KMLDocument.java index 06a6773ccc..2df83c2df6 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLDocument.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLDocument.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLDocument.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLDocument extends KMLAbstractContainer -{ +public class KMLDocument extends KMLAbstractContainer { + protected List schemas = new ArrayList(); /** @@ -28,36 +27,31 @@ public class KMLDocument extends KMLAbstractContainer * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLDocument(String namespaceURI) - { + public KMLDocument(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLSchema) + throws XMLStreamException { + if (o instanceof KMLSchema) { this.addSchema((KMLSchema) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addSchema(KMLSchema o) - { + protected void addSchema(KMLSchema o) { this.schemas.add(o); } - public List getSchemas() - { + public List getSchemas() { return this.schemas; } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLDocument)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLDocument)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -67,32 +61,30 @@ public void applyChange(KMLAbstractObject sourceValues) KMLDocument sourceDocument = (KMLDocument) sourceValues; - if (sourceDocument.getSchemas() != null && sourceDocument.getSchemas().size() > 0) + if (sourceDocument.getSchemas() != null && sourceDocument.getSchemas().size() > 0) { this.mergeSchemas(sourceDocument); + } } /** - * Merge a list of incoming schemas with the current list. If an incoming schema has the same ID as an existing - * one, replace the existing one, otherwise just add the incoming one. + * Merge a list of incoming schemas with the current list. If an incoming schema has the same ID as an existing one, + * replace the existing one, otherwise just add the incoming one. * * @param sourceDocument the incoming document. */ - protected void mergeSchemas(KMLDocument sourceDocument) - { + protected void mergeSchemas(KMLDocument sourceDocument) { // Make a copy of the existing list so we can modify it as we traverse the copy. List schemaListCopy = new ArrayList(this.getSchemas().size()); Collections.copy(schemaListCopy, this.getSchemas()); - for (KMLSchema sourceSchema : sourceDocument.getSchemas()) - { + for (KMLSchema sourceSchema : sourceDocument.getSchemas()) { String id = sourceSchema.getId(); - if (!WWUtil.isEmpty(id)) - { - for (KMLSchema existingSchema : schemaListCopy) - { + if (!WWUtil.isEmpty(id)) { + for (KMLSchema existingSchema : schemaListCopy) { String currentId = existingSchema.getId(); - if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) + if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) { this.getSchemas().remove(existingSchema); + } } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLExtendedData.java b/src/gov/nasa/worldwind/ogc/kml/KMLExtendedData.java index 04c9c9c5fb..bb0d4878c6 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLExtendedData.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLExtendedData.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -18,8 +17,8 @@ * @author tag * @version $Id: KMLExtendedData.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLExtendedData extends KMLAbstractObject -{ +public class KMLExtendedData extends KMLAbstractObject { + protected List data = new ArrayList(); protected List schemaData = new ArrayList(); @@ -28,40 +27,35 @@ public class KMLExtendedData extends KMLAbstractObject * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLExtendedData(String namespaceURI) - { + public KMLExtendedData(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLData) + throws XMLStreamException { + if (o instanceof KMLData) { this.addData((KMLData) o); - else if (o instanceof KMLSchemaData) + } else if (o instanceof KMLSchemaData) { this.addSchemaData((KMLSchemaData) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addData(KMLData o) - { + protected void addData(KMLData o) { this.data.add(o); } - public List getData() - { + public List getData() { return this.data; } - protected void addSchemaData(KMLSchemaData o) - { + protected void addSchemaData(KMLSchemaData o) { this.schemaData.add(o); } - public List getSchemaData() - { + public List getSchemaData() { return this.schemaData; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLFolder.java b/src/gov/nasa/worldwind/ogc/kml/KMLFolder.java index e699d59f6a..2012e97415 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLFolder.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLFolder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,15 +11,14 @@ * @author tag * @version $Id: KMLFolder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLFolder extends KMLAbstractContainer -{ +public class KMLFolder extends KMLAbstractContainer { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLFolder(String namespaceURI) - { + public KMLFolder(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLGroundOverlay.java b/src/gov/nasa/worldwind/ogc/kml/KMLGroundOverlay.java index 2ea22eb852..178bec3dea 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLGroundOverlay.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLGroundOverlay.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -21,8 +20,8 @@ * @author tag * @version $Id: KMLGroundOverlay.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLGroundOverlay extends KMLAbstractOverlay implements KMLRenderable -{ +public class KMLGroundOverlay extends KMLAbstractOverlay implements KMLRenderable { + protected KMLRenderable renderable; /** @@ -30,28 +29,23 @@ public class KMLGroundOverlay extends KMLAbstractOverlay implements KMLRenderabl * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLGroundOverlay(String namespaceURI) - { + public KMLGroundOverlay(String namespaceURI) { super(namespaceURI); } - public Double getAltitude() - { + public Double getAltitude() { return (Double) this.getField("altitude"); } - public String getAltitudeMode() - { + public String getAltitudeMode() { return (String) this.getField("altitudeMode"); } - public KMLLatLonBox getLatLonBox() - { + public KMLLatLonBox getLatLonBox() { return (KMLLatLonBox) this.getField("LatLonBox"); } - public GXLatLongQuad getLatLonQuad() - { + public GXLatLongQuad getLatLonQuad() { return (GXLatLongQuad) this.getField("LatLonQuad"); } @@ -63,14 +57,13 @@ public GXLatLongQuad getLatLonQuad() * @param dc the current draw context. */ @Override - protected void doPreRender(KMLTraversalContext tc, DrawContext dc) - { - if (this.getRenderable() == null) + protected void doPreRender(KMLTraversalContext tc, DrawContext dc) { + if (this.getRenderable() == null) { this.initializeRenderable(tc); + } KMLRenderable r = this.getRenderable(); - if (r != null) - { + if (r != null) { r.preRender(tc, dc); } } @@ -82,14 +75,12 @@ protected void doPreRender(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @Override - protected void doRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doRender(KMLTraversalContext tc, DrawContext dc) { // We've already initialized the image renderable during the preRender pass. Render the image // without any further preparation. KMLRenderable r = this.getRenderable(); - if (r != null) - { + if (r != null) { r.render(tc, dc); } @@ -102,21 +93,19 @@ protected void doRender(KMLTraversalContext tc, DrawContext dc) * * @param tc the current KML traversal context. */ - protected void initializeRenderable(KMLTraversalContext tc) - { + protected void initializeRenderable(KMLTraversalContext tc) { final String altitudeMode = this.getAltitudeMode(); - if ("absolute".equals(altitudeMode)) - { + if ("absolute".equals(altitudeMode)) { this.renderable = new KMLGroundOverlayPolygonImpl(tc, this); - } - else // Default to clampToGround + } else // Default to clampToGround { // If the overlay has an icon, create a surface image renderable. Otherwise, create a surface polygon to // render the overlay as a colored polygon. - if (this.getIcon() != null && this.getIcon().getHref() != null) + if (this.getIcon() != null && this.getIcon().getHref() != null) { this.renderable = new KMLSurfaceImageImpl(tc, this); - else + } else { this.renderable = new KMLSurfacePolygonImpl(tc, this); + } } } @@ -126,8 +115,7 @@ protected void initializeRenderable(KMLTraversalContext tc) * * @return The renderable, or null if the renderable has not been created yet. */ - public KMLRenderable getRenderable() - { + public KMLRenderable getRenderable() { return this.renderable; } @@ -139,28 +127,21 @@ public KMLRenderable getRenderable() * * @return A list of the positions that define the corner points of the overlay. */ - public Position.PositionList getPositions() - { + public Position.PositionList getPositions() { double altitude = this.getAltitude() != null ? this.getAltitude() : 0.0; // Positions are specified either as a kml:LatLonBox or a gx:LatLonQuad List corners = new ArrayList(4); KMLLatLonBox box = this.getLatLonBox(); - if (box != null) - { + if (box != null) { Sector sector = KMLUtil.createSectorFromLatLonBox(box); - for (LatLon ll : sector.getCorners()) - { + for (LatLon ll : sector.getCorners()) { corners.add(new Position(ll, altitude)); } - } - else - { + } else { GXLatLongQuad latLonQuad = this.getLatLonQuad(); - if (latLonQuad != null && latLonQuad.getCoordinates() != null) - { - for (Position position : latLonQuad.getCoordinates().list) - { + if (latLonQuad != null && latLonQuad.getCoordinates() != null) { + for (Position position : latLonQuad.getCoordinates().list) { corners.add(new Position(position, altitude)); } } @@ -170,10 +151,8 @@ public Position.PositionList getPositions() } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLGroundOverlay)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLGroundOverlay)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -185,15 +164,15 @@ public void applyChange(KMLAbstractObject sourceValues) } @Override - public void onChange(Message msg) - { - if (KMLAbstractObject.MSG_LINK_CHANGED.equals(msg.getName())) + public void onChange(Message msg) { + if (KMLAbstractObject.MSG_LINK_CHANGED.equals(msg.getName())) { this.renderable = null; + } - if (KMLAbstractObject.MSG_BOX_CHANGED.equals(msg.getName())) + if (KMLAbstractObject.MSG_BOX_CHANGED.equals(msg.getName())) { this.renderable = null; + } super.onChange(msg); } } - diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLIcon.java b/src/gov/nasa/worldwind/ogc/kml/KMLIcon.java index eb53b3a7c0..5a5a58e32d 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLIcon.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLIcon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,15 +11,14 @@ * @author tag * @version $Id: KMLIcon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLIcon extends KMLLink -{ +public class KMLIcon extends KMLLink { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLIcon(String namespaceURI) - { + public KMLIcon(String namespaceURI) { super(namespaceURI); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLIconStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLIconStyle.java index fa7e96a6c4..7c29e3cf73 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLIconStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLIconStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -14,44 +13,39 @@ * @author tag * @version $Id: KMLIconStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLIconStyle extends KMLAbstractColorStyle -{ +public class KMLIconStyle extends KMLAbstractColorStyle { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLIconStyle(String namespaceURI) - { + public KMLIconStyle(String namespaceURI) { super(namespaceURI); } - public Double getScale() - { + public Double getScale() { return (Double) this.getField("scale"); } - public Double getHeading() - { + public Double getHeading() { return (Double) this.getField("heading"); } - public KMLVec2 getHotSpot() - { + public KMLVec2 getHotSpot() { return (KMLVec2) this.getField("hotSpot"); } - public KMLIcon getIcon() - { + public KMLIcon getIcon() { return (KMLIcon) this.getField("Icon"); } @Override - public void onChange(Message msg) - { - if (KMLAbstractObject.MSG_LINK_CHANGED.equals(msg.getName())) + public void onChange(Message msg) { + if (KMLAbstractObject.MSG_LINK_CHANGED.equals(msg.getName())) { this.onChange(new Message(KMLAbstractObject.MSG_STYLE_CHANGED, this)); + } super.onChange(msg); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLImagePyramid.java b/src/gov/nasa/worldwind/ogc/kml/KMLImagePyramid.java index 53a3b4cac8..08dfc6d8ea 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLImagePyramid.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLImagePyramid.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,35 +11,30 @@ * @author tag * @version $Id: KMLImagePyramid.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLImagePyramid extends KMLAbstractObject -{ +public class KMLImagePyramid extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLImagePyramid(String namespaceURI) - { + public KMLImagePyramid(String namespaceURI) { super(namespaceURI); } - public Integer getTileSize() - { + public Integer getTileSize() { return (Integer) this.getField("tileSize"); } - public Integer getMaxWidth() - { + public Integer getMaxWidth() { return (Integer) this.getField("maxWidth"); } - public Integer getMaxHeight() - { + public Integer getMaxHeight() { return (Integer) this.getField("maxHeight"); } - public String getGridOrigin() - { + public String getGridOrigin() { return (String) this.getField("gridOrigin"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLItemIcon.java b/src/gov/nasa/worldwind/ogc/kml/KMLItemIcon.java index 6300590939..6d51517d09 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLItemIcon.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLItemIcon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,25 +11,22 @@ * @author tag * @version $Id: KMLItemIcon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLItemIcon extends KMLAbstractObject -{ +public class KMLItemIcon extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLItemIcon(String namespaceURI) - { + public KMLItemIcon(String namespaceURI) { super(namespaceURI); } - public String getHref() - { + public String getHref() { return (String) this.getField("href"); } - public String getState() - { + public String getState() { return (String) this.getField("state"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLabelStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLLabelStyle.java index 2825c9acf7..f34f910d6b 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLabelStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLabelStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,20 +11,18 @@ * @author tag * @version $Id: KMLLabelStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLabelStyle extends KMLAbstractColorStyle -{ +public class KMLLabelStyle extends KMLAbstractColorStyle { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLLabelStyle(String namespaceURI) - { + public KMLLabelStyle(String namespaceURI) { super(namespaceURI); } - public Double getScale() - { + public Double getScale() { return (Double) this.getField("scale"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLatLonAltBox.java b/src/gov/nasa/worldwind/ogc/kml/KMLLatLonAltBox.java index a4b68c6012..49280a2584 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLatLonAltBox.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLatLonAltBox.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,30 +11,26 @@ * @author tag * @version $Id: KMLLatLonAltBox.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLatLonAltBox extends KMLAbstractLatLonBoxType -{ +public class KMLLatLonAltBox extends KMLAbstractLatLonBoxType { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLLatLonAltBox(String namespaceURI) - { + public KMLLatLonAltBox(String namespaceURI) { super(namespaceURI); } - public Double getMinAltitude() - { + public Double getMinAltitude() { return (Double) this.getField("minAltitude"); } - public Double getMaxAltitude() - { + public Double getMaxAltitude() { return (Double) this.getField("maxAltitude"); } - public String getAltitudeMode() - { + public String getAltitudeMode() { return (String) this.getField("altitudeMode"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLatLonBox.java b/src/gov/nasa/worldwind/ogc/kml/KMLLatLonBox.java index 878a82c2f1..7fc3029204 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLatLonBox.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLatLonBox.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,20 +11,18 @@ * @author tag * @version $Id: KMLLatLonBox.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLatLonBox extends KMLAbstractLatLonBoxType -{ +public class KMLLatLonBox extends KMLAbstractLatLonBoxType { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLLatLonBox(String namespaceURI) - { + public KMLLatLonBox(String namespaceURI) { super(namespaceURI); } - public Double getRotation() - { + public Double getRotation() { return (Double) this.getField("rotation"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLineString.java b/src/gov/nasa/worldwind/ogc/kml/KMLLineString.java index 0a66fccd7d..971557e944 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLineString.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLineString.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.geom.Position; @@ -14,40 +13,33 @@ * @author tag * @version $Id: KMLLineString.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLineString extends KMLAbstractGeometry -{ - public KMLLineString(String namespaceURI) - { +public class KMLLineString extends KMLAbstractGeometry { + + public KMLLineString(String namespaceURI) { super(namespaceURI); } - public boolean isExtrude() - { + public boolean isExtrude() { return this.getExtrude() == Boolean.TRUE; } - public Boolean getExtrude() - { + public Boolean getExtrude() { return (Boolean) this.getField("extrude"); } - public boolean isTessellate() - { + public boolean isTessellate() { return this.getTessellate() == Boolean.TRUE; } - public Boolean getTessellate() - { + public Boolean getTessellate() { return (Boolean) this.getField("tessellate"); } - public String getAltitudeMode() - { + public String getAltitudeMode() { return (String) this.getField("altitudeMode"); } - public Position.PositionList getCoordinates() - { + public Position.PositionList getCoordinates() { return (Position.PositionList) this.getField("coordinates"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLineStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLLineStyle.java index a0f5c8a29e..714126ffe5 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLineStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLineStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,15 +11,13 @@ * @author tag * @version $Id: KMLLineStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLineStyle extends KMLAbstractColorStyle -{ - public KMLLineStyle(String namespaceURI) - { +public class KMLLineStyle extends KMLAbstractColorStyle { + + public KMLLineStyle(String namespaceURI) { super(namespaceURI); } - public Double getWidth() - { + public Double getWidth() { return (Double) this.getField("width"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLinearRing.java b/src/gov/nasa/worldwind/ogc/kml/KMLLinearRing.java index fca941257c..93ff25076f 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLinearRing.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLinearRing.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.geom.Position; @@ -14,15 +13,14 @@ * @author tag * @version $Id: KMLLinearRing.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLinearRing extends KMLLineString -{ +public class KMLLinearRing extends KMLLineString { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLLinearRing(String namespaceURI) - { + public KMLLinearRing(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLink.java b/src/gov/nasa/worldwind/ogc/kml/KMLLink.java index e2c5427fcc..b23da2dc94 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLink.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLink.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.*; @@ -31,19 +30,27 @@ * @author tag * @version $Id: KMLLink.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLink extends KMLAbstractObject -{ +public class KMLLink extends KMLAbstractObject { + protected static final String DEFAULT_VIEW_FORMAT = "BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]"; - /** The time, in milliseconds since the Epoch, at which the linked content was most recently updated. */ + /** + * The time, in milliseconds since the Epoch, at which the linked content was most recently updated. + */ protected AtomicLong updateTime = new AtomicLong(); - /** If this link's href does not need to be modified with a query string, this value is the resource address. */ + /** + * If this link's href does not need to be modified with a query string, this value is the resource address. + */ protected String finalHref; - /** The {@link URL} for the raw href. Will be null if the href is not a remote URL or this link has a query string */ + /** + * The {@link URL} for the raw href. Will be null if the href is not a remote URL or this link has a query string + */ protected URL hrefURL; - /** Scheduled task that will update the when it runs. Used to implement {@code onInterval} refresh mode. */ + /** + * Scheduled task that will update the when it runs. Used to implement {@code onInterval} refresh mode. + */ protected ScheduledFuture refreshTask; /** @@ -51,60 +58,51 @@ public class KMLLink extends KMLAbstractObject * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLLink(String namespaceURI) - { + public KMLLink(String namespaceURI) { super(namespaceURI); } - public String getHref() - { + public String getHref() { return (String) this.getField("href"); } - public String getRefreshMode() - { + public String getRefreshMode() { return (String) this.getField("refreshMode"); } - public Double getRefreshInterval() - { + public Double getRefreshInterval() { return (Double) this.getField("refreshInterval"); } - public String getViewRefreshMode() - { + public String getViewRefreshMode() { return (String) this.getField("viewRefreshMode"); } - public Double getViewRefreshTime() - { + public Double getViewRefreshTime() { return (Double) this.getField("viewRefreshTime"); } - public Double getViewBoundScale() - { + public Double getViewBoundScale() { return (Double) this.getField("viewBoundScale"); } - public String getViewFormat() - { + public String getViewFormat() { return (String) this.getField("viewFormat"); } - public String getHttpQuery() - { + public String getHttpQuery() { return (String) this.getField("httpQuery"); } - /** {@inheritDoc} Overridden to mark {@code onChange} links as updated when a field set. */ + /** + * {@inheritDoc} Overridden to mark {@code onChange} links as updated when a field set. + */ @Override - public void setField(String keyName, Object value) - { + public void setField(String keyName, Object value) { super.setField(keyName, value); // If the link refreshes "onChange", mark the link as updated because it has changed. - if (KMLConstants.ON_CHANGE.equals(this.getRefreshMode())) - { + if (KMLConstants.ON_CHANGE.equals(this.getRefreshMode())) { this.setUpdateTime(System.currentTimeMillis()); } } @@ -113,10 +111,9 @@ public void setField(String keyName, Object value) * Returns the time at which the linked resource was last updated. This method is safe to call from any thread. * * @return The time at which the linked content was most recently updated. See {@link System#currentTimeMillis()} - * for its numerical meaning of this timestamp. + * for its numerical meaning of this timestamp. */ - public long getUpdateTime() - { + public long getUpdateTime() { // Schedule a task to refresh the link if the refresh mode requires it. If the client code never calls // getUpdateTime, the link may never refresh. But in this case, the link is never rendered, so it doesn't matter. // Scheduling a refresh task only when the link is actually used avoids creating a long running update task @@ -127,13 +124,12 @@ public long getUpdateTime() } /** - * Specifies the time at which the linked resource was last updated. This method is safe to call from any thread. + * Specifies the time at which the linked resource was last updated. This method is safe to call from any thread. * * @param updateTime The time at which the linked content was most recently updated. See {@link * System#currentTimeMillis()} for its numerical meaning of this timestamp. */ - public void setUpdateTime(long updateTime) - { + public void setUpdateTime(long updateTime) { this.updateTime.set(updateTime); } @@ -143,18 +139,16 @@ public void setUpdateTime(long updateTime) * * @param time Time, in milliseconds since the Epoch, at which the link expires. Zero indicates no expiration. */ - public void setExpirationTime(long time) - { + public void setExpirationTime(long time) { // If the refresh mode is onExpire, schedule a task to update the link at the expiration time. Otherwise // we don't care about the expiration. - if (KMLConstants.ON_EXPIRE.equals(this.getRefreshMode())) - { + if (KMLConstants.ON_EXPIRE.equals(this.getRefreshMode())) { // If there is already a task running, cancel it - if (this.refreshTask != null) + if (this.refreshTask != null) { this.refreshTask.cancel(false); + } - if (time != 0) - { + if (time != 0) { long refreshDelay = time - System.currentTimeMillis(); this.refreshTask = this.scheduleDelayedTask(new RefreshTask(), refreshDelay, TimeUnit.MILLISECONDS); } @@ -166,49 +160,48 @@ public void setExpirationTime(long time) * {@code onExpire} refresh modes, this method schedules a task to update the link after the refresh interval * elapses, but only if such a task has not already been scheduled (only one refresh task is active at a time). */ - protected void scheduleRefreshIfNeeded() - { + protected void scheduleRefreshIfNeeded() { Long refreshTime = this.computeRefreshTime(); - if (refreshTime == null) + if (refreshTime == null) { return; + } // Determine if the refresh interval has elapsed since the last refresh task was scheduled. boolean intervalElapsed = System.currentTimeMillis() > refreshTime; // If the refresh interval has already elapsed then the link needs to refresh immediately. - if (intervalElapsed) + if (intervalElapsed) { this.updateTime.set(System.currentTimeMillis()); + } // Schedule a refresh if the refresh interval has elapsed, or if no refresh task is already active. // Checking the refresh interval ensures that even if the task fails to run for some reason, a new // task will be scheduled after the interval expires. - if (intervalElapsed || this.refreshTask == null || this.refreshTask.isDone()) - { + if (intervalElapsed || this.refreshTask == null || this.refreshTask.isDone()) { long refreshDelay = refreshTime - System.currentTimeMillis(); this.refreshTask = this.scheduleDelayedTask(new RefreshTask(), refreshDelay, TimeUnit.MILLISECONDS); } } - protected Long computeRefreshTime() - { + protected Long computeRefreshTime() { Long refreshTime = null; // Only handle onInterval here. onExpire is handled by KMLNetworkLink when the network resource is retrieved. - if (KMLConstants.ON_INTERVAL.equals(this.getRefreshMode())) - { + if (KMLConstants.ON_INTERVAL.equals(this.getRefreshMode())) { Double ri = this.getRefreshInterval(); refreshTime = ri != null ? this.updateTime.get() + (long) (ri * 1000d) : null; } - if (refreshTime == null) + if (refreshTime == null) { return null; + } KMLNetworkLinkControl linkControl = this.getRoot().getNetworkLinkControl(); - if (linkControl != null) - { + if (linkControl != null) { Long minRefresh = (long) (linkControl.getMinRefreshPeriod() * 1000d); - if (minRefresh != null && minRefresh > refreshTime) + if (minRefresh != null && minRefresh > refreshTime) { refreshTime = minRefresh; + } } return refreshTime; @@ -221,14 +214,11 @@ protected Long computeRefreshTime() * @param msg The message that was received. */ @Override - public void onMessage(Message msg) - { + public void onMessage(Message msg) { String viewRefreshMode = this.getViewRefreshMode(); - if (View.VIEW_STOPPED.equals(msg.getName()) && KMLConstants.ON_STOP.equals(viewRefreshMode)) - { + if (View.VIEW_STOPPED.equals(msg.getName()) && KMLConstants.ON_STOP.equals(viewRefreshMode)) { Double refreshTime = this.getViewRefreshTime(); - if (refreshTime != null) - { + if (refreshTime != null) { this.scheduleDelayedTask(new RefreshTask(), refreshTime.longValue(), TimeUnit.SECONDS); } } @@ -237,28 +227,27 @@ public void onMessage(Message msg) /** * Schedule a task to mark a link as updated after a delay. The task only executes once. * - * @param task Task to schedule. - * @param delay Delay to wait before executing the task. The time unit is determined by {code timeUnit}. + * @param task Task to schedule. + * @param delay Delay to wait before executing the task. The time unit is determined by {code timeUnit}. * @param timeUnit The time unit of {@code delay}. * * @return Future that represents the scheduled task. */ - protected ScheduledFuture scheduleDelayedTask(Runnable task, long delay, TimeUnit timeUnit) - { + protected ScheduledFuture scheduleDelayedTask(Runnable task, long delay, TimeUnit timeUnit) { return WorldWind.getScheduledTaskService().addScheduledTask(task, delay, timeUnit); } - /** {@inheritDoc} Overridden to set a default refresh mode of {@code onChange} if the refresh mode is not specified. */ + /** + * {@inheritDoc} Overridden to set a default refresh mode of {@code onChange} if the refresh mode is not specified. + */ @Override - public Object parse(XMLEventParserContext ctx, XMLEvent inputEvent, Object... args) throws XMLStreamException - { + public Object parse(XMLEventParserContext ctx, XMLEvent inputEvent, Object... args) throws XMLStreamException { Object o = super.parse(ctx, inputEvent, args); // If the link does not have a refresh mode, set the default refresh mode of "onChange". We set an explicit // default after parsing is complete so that we can distinguish links that do not specify a refresh mode from // those in which the refresh mode has not yet been parsed. - if (WWUtil.isEmpty(this.getRefreshMode())) - { + if (WWUtil.isEmpty(this.getRefreshMode())) { this.setField("refreshMode", KMLConstants.ON_CHANGE); } @@ -271,8 +260,8 @@ public Object parse(XMLEventParserContext ctx, XMLEvent inputEvent, Object... ar * viewFormat and httpQuery. Otherwise, this returns the concatenation of the * href, the viewFormat and the httpQuery for form an absolute URL string. If * the the href contains a query string, the viewFormat and httpQuery are - * appended to that string. If necessary, this inserts the & character between the href's - * query string, the viewFormat, and the httpQuery. + * appended to that string. If necessary, this inserts the & character between the + * href's query string, the viewFormat, and the httpQuery. *

        * This substitutes the following parameters in viewFormat and httpQuery:

          *
        • [bboxWest],[bboxSouth],[bboxEast],[bboxNorth] - visible bounds of the globe, or 0 if the globe @@ -308,55 +297,51 @@ public Object parse(XMLEventParserContext ctx, XMLEvent inputEvent, Object... ar * @see #getHttpQuery() * @see gov.nasa.worldwind.Configuration */ - public String getAddress(DrawContext dc) - { - if (dc == null) - { + public String getAddress(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // See if we've already determined the href is a local reference - if (this.finalHref != null) + if (this.finalHref != null) { return this.finalHref; + } String href = this.getHref(); - if (href != null) + if (href != null) { href = href.trim(); + } - if (WWUtil.isEmpty(href)) + if (WWUtil.isEmpty(href)) { return href; + } // If the href is a local resource, the viewFormat and httpQuery parameters are ignored, and we return the href. // We treat the href as a local resource reference if it fails to parse as a URL, or if the URL's protocol is // "file" or "jar". // See OGC KML specification 2.2.0, section 13.1.2. URL url = this.hrefURL != null ? this.hrefURL : WWIO.makeURL(href); - if (url == null || this.isLocalReference(url)) - { + if (url == null || this.isLocalReference(url)) { this.finalHref = href; // don't need to parse the href anymore return href; } String queryString = this.buildQueryString(dc); - if (WWUtil.isEmpty(queryString)) - { + if (WWUtil.isEmpty(queryString)) { this.finalHref = href; // don't need to parse the href anymore return href; } this.hrefURL = url; // retain it so that we don't regenerate it every time - try - { + try { // Create a new URL, with the full query string. URL newUrl = new URL(this.hrefURL.getProtocol(), this.hrefURL.getHost(), this.hrefURL.getPort(), - this.hrefURL.getPath() + queryString); + this.hrefURL.getPath() + queryString); return newUrl.toString(); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { return href; // If constructing a URL from the href and query string fails, assume this is a local file. } } @@ -368,8 +353,7 @@ public String getAddress(DrawContext dc) * * @return true if the url specifies a local resource, otherwise false. */ - protected boolean isLocalReference(URL url) - { + protected boolean isLocalReference(URL url) { return url.getProtocol() == null || "file".equals(url.getProtocol()) || "jar".equals(url.getProtocol()); } @@ -378,42 +362,42 @@ protected boolean isLocalReference(URL url) * the httpQuery to form the link URL's query part. This returns null if this link's * href does not specify a URL. This substitutes parameters in viewFormat according to the * specified DrawContext's current viewing parameters, and substitutes parameters in - * httpQuery according to the current {@link gov.nasa.worldwind.Configuration} - * parameters. + * httpQuery according to the current {@link gov.nasa.worldwind.Configuration} parameters. * * @param dc the DrawContext used to determine the current view parameters. * * @return the query part of this KML link's address, or null if this link does not specify a URL. */ - protected String buildQueryString(DrawContext dc) - { + protected String buildQueryString(DrawContext dc) { URL url = WWIO.makeURL(this.getHref()); - if (url == null) + if (url == null) { return null; + } StringBuilder queryString = new StringBuilder(url.getQuery() != null ? url.getQuery() : ""); String viewRefreshMode = this.getViewRefreshMode(); - if (viewRefreshMode != null) + if (viewRefreshMode != null) { viewRefreshMode = viewRefreshMode.trim(); + } // Ignore the viewFormat if the viewRefreshMode is unspecified or if the viewRefreshMode is "never". // See OGC KML specification 2.2.0, section 16.22.1. - if (!WWUtil.isEmpty(viewRefreshMode) && !KMLConstants.NEVER.equals(viewRefreshMode)) - { + if (!WWUtil.isEmpty(viewRefreshMode) && !KMLConstants.NEVER.equals(viewRefreshMode)) { String s = this.getViewFormat(); - if (s != null) + if (s != null) { s = s.trim(); + } // Use a default viewFormat that includes the view bounding box parameters if no viewFormat is specified // and the viewRefreshMode is "onStop". // See Google KML Reference: http://code.google.com/apis/kml/documentation/kmlreference.html#link - if (s == null && KMLConstants.ON_STOP.equals(viewRefreshMode)) + if (s == null && KMLConstants.ON_STOP.equals(viewRefreshMode)) { s = DEFAULT_VIEW_FORMAT; + } // Ignore the viewFormat if it's specified but empty. - if (!WWUtil.isEmpty(s)) - { + if (!WWUtil.isEmpty(s)) { Sector viewBounds = this.computeVisibleBounds(dc); //noinspection ConstantConditions s = s.replaceAll("\\[bboxWest\\]", Double.toString(viewBounds.getMinLongitude().degrees)); @@ -424,8 +408,7 @@ protected String buildQueryString(DrawContext dc) View view = dc.getView(); Vec4 centerPoint = view.getCenterPoint(); - if (centerPoint != null) - { + if (centerPoint != null) { // Use the view's center position as the "look at" position. Position centerPosition = view.getGlobe().computePositionFromPoint(centerPoint); s = s.replaceAll("\\[lookatLat\\]", Double.toString(centerPosition.getLatitude().degrees)); @@ -456,20 +439,20 @@ protected String buildQueryString(DrawContext dc) s = s.replaceAll("\\[vertPixels\\]", Integer.toString(viewport.height)); // TODO: Implement support for the remaining viewFormat parameters: [vertFov] [terrainEnabled]. - - if (queryString.length() > 0 && queryString.charAt(queryString.length() - 1) != '&') + if (queryString.length() > 0 && queryString.charAt(queryString.length() - 1) != '&') { queryString.append('&'); + } queryString.append(s, s.startsWith("&") ? 1 : 0, s.length()); } } // Ignore the httpQuery if it's unspecified, or if an empty httpQuery is specified. String s = this.getHttpQuery(); - if (s != null) + if (s != null) { s = s.trim(); + } - if (!WWUtil.isEmpty(s)) - { + if (!WWUtil.isEmpty(s)) { String clientName = Configuration.getStringValue(AVKey.NAME, Version.getVersionName()); String clientVersion = Configuration.getStringValue(AVKey.VERSION, Version.getVersionNumber()); @@ -479,13 +462,15 @@ protected String buildQueryString(DrawContext dc) s = s.replaceAll("\\[clientName\\]", clientName); s = s.replaceAll("\\[language\\]", Locale.getDefault().getLanguage()); - if (queryString.length() > 0 && queryString.charAt(queryString.length() - 1) != '&') + if (queryString.length() > 0 && queryString.charAt(queryString.length() - 1) != '&') { queryString.append('&'); + } queryString.append(s, s.startsWith("&") ? 1 : 0, s.length()); } - if (queryString.length() > 0 && queryString.charAt(0) != '?') + if (queryString.length() > 0 && queryString.charAt(0) != '?') { queryString.insert(0, '?'); + } return queryString.length() > 0 ? queryString.toString() : null; } @@ -500,10 +485,8 @@ protected String buildQueryString(DrawContext dc) * * @return the current visible bounds on the specified DrawContext. */ - protected Sector computeVisibleBounds(DrawContext dc) - { - if (dc.getVisibleSector() != null && this.getViewBoundScale() != null) - { + protected Sector computeVisibleBounds(DrawContext dc) { + if (dc.getVisibleSector() != null && this.getViewBoundScale() != null) { // If the DrawContext has a visible sector and a viewBoundScale is specified, compute the view bounding box // by scaling the DrawContext's visible sector from its centroid, based on the scale factor specified by // viewBoundScale. @@ -517,19 +500,15 @@ protected Sector computeVisibleBounds(DrawContext dc) // methods Angle.fromDegreesLatitude and Angle.fromDegreesLongitude automatically limit latitude and // longitude to these ranges. return new Sector( - Angle.fromDegreesLatitude(centerLat - this.getViewBoundScale() * (latDelta / 2d)), - Angle.fromDegreesLatitude(centerLat + this.getViewBoundScale() * (latDelta / 2d)), - Angle.fromDegreesLongitude(centerLon - this.getViewBoundScale() * (lonDelta / 2d)), - Angle.fromDegreesLongitude(centerLon + this.getViewBoundScale() * (lonDelta / 2d))); - } - else if (dc.getVisibleSector() != null) - { + Angle.fromDegreesLatitude(centerLat - this.getViewBoundScale() * (latDelta / 2d)), + Angle.fromDegreesLatitude(centerLat + this.getViewBoundScale() * (latDelta / 2d)), + Angle.fromDegreesLongitude(centerLon - this.getViewBoundScale() * (lonDelta / 2d)), + Angle.fromDegreesLongitude(centerLon + this.getViewBoundScale() * (lonDelta / 2d))); + } else if (dc.getVisibleSector() != null) { // If the DrawContext has a visible sector but no viewBoundScale is specified, use the DrawContext's visible // sector as the view bounding box. return dc.getVisibleSector(); - } - else - { + } else { // If the DrawContext does not have a visible sector, use the standard EMPTY_SECTOR as the view bounding // box. If the viewFormat contains bounding box parameters, we must substitute them with a valid value. In // this case we substitute them with 0. @@ -538,10 +517,8 @@ else if (dc.getVisibleSector() != null) } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLLink)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLLink)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -559,12 +536,15 @@ public void applyChange(KMLAbstractObject sourceValues) this.onChange(new Message(KMLAbstractObject.MSG_LINK_CHANGED, this)); } - /** A Runnable task that marks a KMLLink as updated when the task executes. */ - class RefreshTask implements Runnable - { - /** Mark the link as updated. */ - public void run() - { + /** + * A Runnable task that marks a KMLLink as updated when the task executes. + */ + class RefreshTask implements Runnable { + + /** + * Mark the link as updated. + */ + public void run() { // Mark the link as updated. KMLLink.this.setUpdateTime(System.currentTimeMillis()); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLListStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLListStyle.java index 08d0db9dc3..5f2ad2b196 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLListStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLListStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLListStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLListStyle extends KMLAbstractSubStyle -{ +public class KMLListStyle extends KMLAbstractSubStyle { + protected List itemIcons = new ArrayList(); /** @@ -28,51 +27,43 @@ public class KMLListStyle extends KMLAbstractSubStyle * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLListStyle(String namespaceURI) - { + public KMLListStyle(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLItemIcon) + throws XMLStreamException { + if (o instanceof KMLItemIcon) { this.addItemIcon((KMLItemIcon) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public String getListItemType() - { + public String getListItemType() { return (String) this.getField("listItemType"); } - public String getBgColor() - { + public String getBgColor() { return (String) this.getField("bgColor"); } - protected void addItemIcon(KMLItemIcon o) - { + protected void addItemIcon(KMLItemIcon o) { this.itemIcons.add(o); } - public List getItemIcons() - { + public List getItemIcons() { return this.itemIcons; } - public Integer getMaxSnippetLines() - { + public Integer getMaxSnippetLines() { return (Integer) this.getField("maxSnippetLines"); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLListStyle)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLListStyle)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -80,8 +71,9 @@ public void applyChange(KMLAbstractObject sourceValues) KMLListStyle sourceStyle = (KMLListStyle) sourceValues; - if (sourceStyle.getItemIcons() != null && sourceStyle.getItemIcons().size() > 0) + if (sourceStyle.getItemIcons() != null && sourceStyle.getItemIcons().size() > 0) { this.mergeItemIcons(sourceStyle); + } super.applyChange(sourceValues); } @@ -92,22 +84,17 @@ public void applyChange(KMLAbstractObject sourceValues) * * @param sourceStyle the incoming item icons. */ - protected void mergeItemIcons(KMLListStyle sourceStyle) - { + protected void mergeItemIcons(KMLListStyle sourceStyle) { // Make a copy of the existing list so we can modify it as we traverse the copy. List itemIconsCopy = new ArrayList(this.getItemIcons().size()); Collections.copy(itemIconsCopy, this.getItemIcons()); - for (KMLItemIcon sourceItemIcon : sourceStyle.getItemIcons()) - { + for (KMLItemIcon sourceItemIcon : sourceStyle.getItemIcons()) { String id = sourceItemIcon.getId(); - if (!WWUtil.isEmpty(id)) - { - for (KMLItemIcon existingItemIcon : itemIconsCopy) - { + if (!WWUtil.isEmpty(id)) { + for (KMLItemIcon existingItemIcon : itemIconsCopy) { String currentId = existingItemIcon.getId(); - if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) - { + if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) { this.getItemIcons().remove(existingItemIcon); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLocation.java b/src/gov/nasa/worldwind/ogc/kml/KMLLocation.java index 58d18f0fb6..40f66e6b5c 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLocation.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLocation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.geom.Position; @@ -14,30 +13,26 @@ * @author tag * @version $Id: KMLLocation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLocation extends KMLAbstractObject -{ +public class KMLLocation extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLLocation(String namespaceURI) - { + public KMLLocation(String namespaceURI) { super(namespaceURI); } - public Double getLongitude() - { + public Double getLongitude() { return (Double) this.getField("longitude"); } - public Double getLatitude() - { + public Double getLatitude() { return (Double) this.getField("latitude"); } - public Double getAltitude() - { + public Double getAltitude() { return (Double) this.getField("altitude"); } @@ -46,15 +41,14 @@ public Double getAltitude() * * @return Position object representing this location. */ - public Position getPosition() - { + public Position getPosition() { Double lat = this.getLatitude(); Double lon = this.getLongitude(); Double alt = this.getAltitude(); return Position.fromDegrees( - lat != null ? lat : 0, - lon != null ? lon : 0, - alt != null ? alt : 0); + lat != null ? lat : 0, + lon != null ? lon : 0, + alt != null ? alt : 0); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLod.java b/src/gov/nasa/worldwind/ogc/kml/KMLLod.java index ef8dbe45e9..6cb79e0576 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLod.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLod.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,35 +11,30 @@ * @author tag * @version $Id: KMLLod.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLod extends KMLAbstractObject -{ +public class KMLLod extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLLod(String namespaceURI) - { + public KMLLod(String namespaceURI) { super(namespaceURI); } - public Double getMinLodPixels() - { + public Double getMinLodPixels() { return (Double) this.getField("minLodPixels"); } - public Double getMaxLodPixels() - { + public Double getMaxLodPixels() { return (Double) this.getField("maxLodPixels"); } - public Double getMinFadeExtent() - { + public Double getMinFadeExtent() { return (Double) this.getField("minFadeExtent"); } - public Double getMaxFadeExtent() - { + public Double getMaxFadeExtent() { return (Double) this.getField("maxFadeExtent"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLLookAt.java b/src/gov/nasa/worldwind/ogc/kml/KMLLookAt.java index 989b9593f3..0a14982744 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLLookAt.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLLookAt.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,50 +11,42 @@ * @author tag * @version $Id: KMLLookAt.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLLookAt extends KMLAbstractView -{ +public class KMLLookAt extends KMLAbstractView { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLLookAt(String namespaceURI) - { + public KMLLookAt(String namespaceURI) { super(namespaceURI); } - public Double getLongitude() - { + public Double getLongitude() { return (Double) this.getField("longitude"); } - public Double getLatitude() - { + public Double getLatitude() { return (Double) this.getField("latitude"); } - public Double getAltitude() - { + public Double getAltitude() { return (Double) this.getField("altitude"); } - public Double getHeading() - { + public Double getHeading() { return (Double) this.getField("heading"); } - public Double getTilt() - { + public Double getTilt() { return (Double) this.getField("tilt"); } - public Double getRange() - { + public Double getRange() { return (Double) this.getField("range"); } - public String getAltitudeMode() - { + public String getAltitudeMode() { return (String) this.getField("altitudeMode"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLModel.java b/src/gov/nasa/worldwind/ogc/kml/KMLModel.java index ac9fe49c43..dfab271fdb 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLModel.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,9 +11,11 @@ * @author tag * @version $Id: KMLModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLModel extends KMLAbstractGeometry -{ - /** Flag to indicate that the link has been fetched from the hash map. */ +public class KMLModel extends KMLAbstractGeometry { + + /** + * Flag to indicate that the link has been fetched from the hash map. + */ protected boolean linkFetched = false; protected KMLLink link; @@ -23,43 +24,35 @@ public class KMLModel extends KMLAbstractGeometry * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLModel(String namespaceURI) - { + public KMLModel(String namespaceURI) { super(namespaceURI); } - public String getAltitudeMode() - { + public String getAltitudeMode() { return (String) this.getField("altitudeMode"); } - public KMLLocation getLocation() - { + public KMLLocation getLocation() { return (KMLLocation) this.getField("Location"); } - public KMLOrientation getOrientation() - { + public KMLOrientation getOrientation() { return (KMLOrientation) this.getField("Orientation"); } - public KMLScale getScale() - { + public KMLScale getScale() { return (KMLScale) this.getField("Scale"); } - public KMLLink getLink() - { - if (!this.linkFetched) - { + public KMLLink getLink() { + if (!this.linkFetched) { this.link = (KMLLink) this.getField("Link"); this.linkFetched = true; } return this.link; } - public KMLResourceMap getResourceMap() - { + public KMLResourceMap getResourceMap() { return (KMLResourceMap) this.getField("ResourceMap"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLMultiGeometry.java b/src/gov/nasa/worldwind/ogc/kml/KMLMultiGeometry.java index 895602df4f..c7590dbbee 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLMultiGeometry.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLMultiGeometry.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLMultiGeometry.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLMultiGeometry extends KMLAbstractGeometry -{ +public class KMLMultiGeometry extends KMLAbstractGeometry { + protected List geometries = new ArrayList(); /** @@ -28,36 +27,31 @@ public class KMLMultiGeometry extends KMLAbstractGeometry * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLMultiGeometry(String namespaceURI) - { + public KMLMultiGeometry(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractGeometry) + throws XMLStreamException { + if (o instanceof KMLAbstractGeometry) { this.addGeometry((KMLAbstractGeometry) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addGeometry(KMLAbstractGeometry o) - { + protected void addGeometry(KMLAbstractGeometry o) { this.geometries.add(o); } - public List getGeometries() - { + public List getGeometries() { return this.geometries; } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLMultiGeometry)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLMultiGeometry)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -65,34 +59,30 @@ public void applyChange(KMLAbstractObject sourceValues) KMLMultiGeometry multiGeometry = (KMLMultiGeometry) sourceValues; - if (multiGeometry.getGeometries() != null && multiGeometry.getGeometries().size() > 0) + if (multiGeometry.getGeometries() != null && multiGeometry.getGeometries().size() > 0) { this.mergeGeometries(multiGeometry); + } super.applyChange(sourceValues); } /** - * Merge a list of incoming geometries with the current list. If an incoming geometry has the same ID as - * an existing one, replace the existing one, otherwise just add the incoming one. + * Merge a list of incoming geometries with the current list. If an incoming geometry has the same ID as an existing + * one, replace the existing one, otherwise just add the incoming one. * * @param sourceMultiGeometry the incoming geometries. */ - protected void mergeGeometries(KMLMultiGeometry sourceMultiGeometry) - { + protected void mergeGeometries(KMLMultiGeometry sourceMultiGeometry) { // Make a copy of the existing list so we can modify it as we traverse the copy. List geometriesCopy = new ArrayList(this.getGeometries().size()); Collections.copy(geometriesCopy, this.getGeometries()); - for (KMLAbstractGeometry sourceGeometry : sourceMultiGeometry.getGeometries()) - { + for (KMLAbstractGeometry sourceGeometry : sourceMultiGeometry.getGeometries()) { String id = sourceGeometry.getId(); - if (!WWUtil.isEmpty(id)) - { - for (KMLAbstractGeometry existingGeometry : geometriesCopy) - { + if (!WWUtil.isEmpty(id)) { + for (KMLAbstractGeometry existingGeometry : geometriesCopy) { String currentId = existingGeometry.getId(); - if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) - { + if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) { this.getGeometries().remove(existingGeometry); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLNetworkLink.java b/src/gov/nasa/worldwind/ogc/kml/KMLNetworkLink.java index b71b159e5d..475f4b77e9 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLNetworkLink.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLNetworkLink.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.WorldWind; @@ -33,9 +32,11 @@ * @author tag * @version $Id: KMLNetworkLink.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLNetworkLink extends KMLAbstractContainer implements PropertyChangeListener -{ - /** Indicates the network resource referenced by this KMLNetworkLink. Initially null. */ +public class KMLNetworkLink extends KMLAbstractContainer implements PropertyChangeListener { + + /** + * Indicates the network resource referenced by this KMLNetworkLink. Initially null. + */ protected AtomicReference networkResource = new AtomicReference(); /** * Time, in milliseconds since the Epoch, at which this KMLNetworkLink's network resource was last @@ -45,7 +46,9 @@ public class KMLNetworkLink extends KMLAbstractContainer implements PropertyChan protected AtomicLong firstRetrievalTime; - /** Flag to indicate that the Link has been fetched from the hash map. */ + /** + * Flag to indicate that the Link has been fetched from the hash map. + */ protected boolean linkFetched = false; protected KMLLink link; @@ -66,8 +69,7 @@ public class KMLNetworkLink extends KMLAbstractContainer implements PropertyChan * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLNetworkLink(String namespaceURI) - { + public KMLNetworkLink(String namespaceURI) { super(namespaceURI); } @@ -76,51 +78,45 @@ public KMLNetworkLink(String namespaceURI) * * @param evt Event to forward. */ - public void propertyChange(PropertyChangeEvent evt) - { + public void propertyChange(PropertyChangeEvent evt) { this.getRoot().firePropertyChange(evt); } @Override - public void onMessage(Message msg) - { + public void onMessage(Message msg) { KMLLink link = this.getLinkOrUrl(); - if (link != null) - { + if (link != null) { link.onMessage(msg); } KMLRoot networkResource = this.getNetworkResource(); - if (networkResource != null) - { + if (networkResource != null) { networkResource.onMessage(msg); } } - /** {@inheritDoc} Overridden to cache the root instead of climbing the parse tree each time. */ + /** + * {@inheritDoc} Overridden to cache the root instead of climbing the parse tree each time. + */ @Override - public KMLRoot getRoot() - { - if (root == null) + public KMLRoot getRoot() { + if (root == null) { this.root = super.getRoot(); + } return this.root; } - public Boolean getRefreshVisibility() - { + public Boolean getRefreshVisibility() { return (Boolean) this.getField("refreshVisibility"); } - public Boolean getFlyToView() - { + public Boolean getFlyToView() { return (Boolean) this.getField("flyToView"); } - public KMLLink getNetworkLink() - { - if (!this.linkFetched) - { + public KMLLink getNetworkLink() { + if (!this.linkFetched) { this.linkFetched = true; this.link = (KMLLink) this.getField("Link"); } @@ -128,8 +124,7 @@ public KMLLink getNetworkLink() return this.link; } - public KMLLink getUrl() - { + public KMLLink getUrl() { return (KMLLink) this.getField("Url"); } @@ -140,14 +135,14 @@ public KMLLink getUrl() * Url element is returned. * * @return this NetworkLink's Link element, if one is specified. Otherwise, this - * NetworkLink's Url element. Returns null if neither - * Link or a Url are specified. + * NetworkLink's Url element. Returns null if neither Link or a + * Url are specified. */ - protected KMLLink getLinkOrUrl() - { + protected KMLLink getLinkOrUrl() { KMLLink link = this.getNetworkLink(); - if (link != null) + if (link != null) { return link; + } return this.getUrl(); } @@ -160,8 +155,7 @@ protected KMLLink getLinkOrUrl() * * @see #setNetworkResource(KMLRoot) */ - public KMLRoot getNetworkResource() - { + public KMLRoot getNetworkResource() { return networkResource.get(); } @@ -170,47 +164,47 @@ public KMLRoot getNetworkResource() * prevents retrieving network links in inactive regions. */ @Override - protected boolean isFeatureActive(KMLTraversalContext tc, DrawContext dc) - { - if (this.getVisibility() != null && !this.getVisibility()) + protected boolean isFeatureActive(KMLTraversalContext tc, DrawContext dc) { + if (this.getVisibility() != null && !this.getVisibility()) { return false; + } KMLRegion region = this.getRegion(); - if (region == null) + if (region == null) { region = tc.peekRegion(); + } return region == null || region.isActive(tc, dc); } - protected boolean hasNetworkLinkControl() - { + protected boolean hasNetworkLinkControl() { return this.getRoot().getNetworkLinkControl() != null; } @Override - public String getName() - { - if (this.hasNetworkLinkControl() && !WWUtil.isEmpty(this.getRoot().getNetworkLinkControl().getLinkName())) + public String getName() { + if (this.hasNetworkLinkControl() && !WWUtil.isEmpty(this.getRoot().getNetworkLinkControl().getLinkName())) { return this.getRoot().getNetworkLinkControl().getLinkName(); + } return super.getName(); } @Override - public String getDescription() - { + public String getDescription() { if (this.hasNetworkLinkControl() - && !WWUtil.isEmpty(this.getRoot().getNetworkLinkControl().getLinkDescription())) + && !WWUtil.isEmpty(this.getRoot().getNetworkLinkControl().getLinkDescription())) { return this.getRoot().getNetworkLinkControl().getLinkDescription(); + } return super.getDescription(); } @Override - public Object getSnippet() - { - if (this.hasNetworkLinkControl() && !WWUtil.isEmpty(this.getRoot().getNetworkLinkControl().getLinkSnippet())) + public Object getSnippet() { + if (this.hasNetworkLinkControl() && !WWUtil.isEmpty(this.getRoot().getNetworkLinkControl().getLinkSnippet())) { return this.getRoot().getNetworkLinkControl().getLinkSnippet(); + } return super.getSnippet(); } @@ -225,35 +219,34 @@ public Object getSnippet() * * @see #getNetworkResource() */ - public void setNetworkResource(final KMLRoot kmlRoot) - { + public void setNetworkResource(final KMLRoot kmlRoot) { // Remove any property change listeners previously set on the KMLRoot. This eliminates dangling references from // the KMLNetworkLink to its previous KMLRoot. KMLRoot resource = this.getNetworkResource(); - if (resource != null) + if (resource != null) { resource.removePropertyChangeListener(this); + } this.networkResource.set(kmlRoot); this.networkResourceRetrievalTime.set(System.currentTimeMillis()); - if (this.firstRetrievalTime == null) + if (this.firstRetrievalTime == null) { this.firstRetrievalTime = new AtomicLong(this.networkResourceRetrievalTime.get()); + } // Set up to listen for property change events on the KMLRoot. KMLNetworkLink must forward REPAINT and REFRESH // property change events from its internal KMLRoot to its parent KMLRoot to support BrowserBalloon repaint // events and recursive KMLNetworkLink elements. - if (kmlRoot != null) - { + if (kmlRoot != null) { kmlRoot.addPropertyChangeListener(this); // Apply any updates contained in the new root's optional network link control. - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + SwingUtilities.invokeLater(new Runnable() { + public void run() { if (kmlRoot.getNetworkLinkControl() != null - && kmlRoot.getNetworkLinkControl().getUpdate() != null - && !kmlRoot.getNetworkLinkControl().getUpdate().isUpdatesApplied()) + && kmlRoot.getNetworkLinkControl().getUpdate() != null + && !kmlRoot.getNetworkLinkControl().getUpdate().isUpdatesApplied()) { kmlRoot.getNetworkLinkControl().getUpdate().applyOperations(); + } } }); } @@ -263,8 +256,9 @@ public void run() * Pre-renders the network resource referenced by this KMLNetworkLink. If this link must retrieve its * network resource, this initiates a retrieval and does nothing until the resource is retrieved and loaded. Once * the network resource is retrieved and loaded, this calls {@link #setNetworkResource(KMLRoot)} to - * specify this link's new network resource, and sends an {@link gov.nasa.worldwind.avlist.AVKey#RETRIEVAL_STATE_SUCCESSFUL} - * property change event to this link's property change listeners. + * specify this link's new network resource, and sends an + * {@link gov.nasa.worldwind.avlist.AVKey#RETRIEVAL_STATE_SUCCESSFUL} property change event to this + * link's property change listeners. * * @param tc the current KML traversal context. * @param dc the current draw context. @@ -272,15 +266,16 @@ public void run() * @see #getNetworkResource() */ @Override - protected void doPreRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doPreRender(KMLTraversalContext tc, DrawContext dc) { super.doPreRender(tc, dc); - if (this.mustRetrieveNetworkResource()) + if (this.mustRetrieveNetworkResource()) { this.requestResource(dc); + } - if (this.getNetworkResource() != null) + if (this.getNetworkResource() != null) { this.getNetworkResource().preRender(tc, dc); + } } /** @@ -291,12 +286,12 @@ protected void doPreRender(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @Override - protected void doRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doRender(KMLTraversalContext tc, DrawContext dc) { super.doRender(tc, dc); - if (this.getNetworkResource() != null) + if (this.getNetworkResource() != null) { this.getNetworkResource().render(tc, dc); + } } /** @@ -304,34 +299,34 @@ protected void doRender(KMLTraversalContext tc, DrawContext dc) * false if this KMLNetworkLink has no KMLLink. * * @return true if this KMLNetworkLink must retrieve its network resource, otherwise - * false. + * false. */ - protected boolean mustRetrieveNetworkResource() - { + protected boolean mustRetrieveNetworkResource() { KMLLink link = this.getLinkOrUrl(); - if (link == null) + if (link == null) { return false; // If both the Link and the Url are null, then there's nothing to retrieve. - + } // If the resource has already been retrieved, but is not a KML file, don't retrieve the resource again. - if (this.invalidTarget) + if (this.invalidTarget) { return false; + } // Make sure a refresh doesn't occur within the minimum refresh period, if one is specified. KMLNetworkLinkControl linkControl = this.getRoot().getNetworkLinkControl(); - if (linkControl != null && linkControl.getMinRefreshPeriod() != null) - { + if (linkControl != null && linkControl.getMinRefreshPeriod() != null) { long now = System.currentTimeMillis(); if (this.firstRetrievalTime != null // be sure it gets retrieved a first time - && this.networkResourceRetrievalTime.get() + linkControl.getMinRefreshPeriod() * 1000 > now) + && this.networkResourceRetrievalTime.get() + linkControl.getMinRefreshPeriod() * 1000 > now) { return false; + } } // Make sure a refresh doesn't occur after the max session length is reached, if one is specified. - if (linkControl != null && linkControl.getMaxSessionLength() != null && this.firstRetrievalTime != null) - { + if (linkControl != null && linkControl.getMaxSessionLength() != null && this.firstRetrievalTime != null) { long now = System.currentTimeMillis(); - if (this.firstRetrievalTime.get() + linkControl.getMaxSessionLength() * 1000 > now) + if (this.firstRetrievalTime.get() + linkControl.getMaxSessionLength() * 1000 > now) { return false; + } } // The resource must be retrieved if the link has been updated since the resource was @@ -345,24 +340,27 @@ protected boolean mustRetrieveNetworkResource() * * @param dc the current draw context. */ - protected void requestResource(DrawContext dc) - { - if (WorldWind.getTaskService().isFull()) + protected void requestResource(DrawContext dc) { + if (WorldWind.getTaskService().isFull()) { return; + } KMLLink link = this.getLinkOrUrl(); - if (link == null) + if (link == null) { return; // If both the Link and the Url are null, then there's nothing to retrieve. - + } String address = link.getAddress(dc); - if (address != null) + if (address != null) { address = address.trim(); + } - if (WWUtil.isEmpty(address)) + if (WWUtil.isEmpty(address)) { return; + } - if (this.hasNetworkLinkControl() && this.getRoot().getNetworkLinkControl().getCookie() != null) + if (this.hasNetworkLinkControl() && this.getRoot().getNetworkLinkControl().getCookie() != null) { address = address + this.getRoot().getNetworkLinkControl().getCookie(); + } WorldWind.getTaskService().addTask(new RequestTask(this, address)); } @@ -370,15 +368,15 @@ protected void requestResource(DrawContext dc) /** * Initiates a retrieval of the network resource referenced by this KMLNetworkLink. Once the network * resource is retrieved and loaded, this calls {@link #setNetworkResource(KMLRoot)} to specify this - * link's new network resource, and sends an {@link gov.nasa.worldwind.avlist.AVKey#RETRIEVAL_STATE_SUCCESSFUL} - * property change event to this link's property change listeners. + * link's new network resource, and sends an + * {@link gov.nasa.worldwind.avlist.AVKey#RETRIEVAL_STATE_SUCCESSFUL} property change event to this + * link's property change listeners. *

          * This does nothing if this KMLNetworkLink has no KMLLink. * * @param address the address of the resource to retrieve */ - protected void retrieveNetworkResource(String address) - { + protected void retrieveNetworkResource(String address) { // Treat the address as either a path to a local document, or as an absolute URL to a remote document. If the // address references a remote document, this attempts to retrieve it and loads the document once retrieval // succeeds. This does not handle absolute local file paths; absolute local file paths are not supported by the @@ -391,14 +389,12 @@ protected void retrieveNetworkResource(String address) long updateTime = 0L; KMLLink link = this.getLinkOrUrl(); - if (link != null) - { + if (link != null) { updateTime = link.getUpdateTime(); } Object o = this.getRoot().resolveNetworkLink(address, this.isLinkCacheable(), updateTime); - if (o instanceof KMLRoot) - { + if (o instanceof KMLRoot) { KMLRoot newRoot = (KMLRoot) o; this.setNetworkResource(newRoot); @@ -407,10 +403,8 @@ protected void retrieveNetworkResource(String address) this.getLinkOrUrl().setExpirationTime(expiration); this.getRoot().firePropertyChange(AVKey.RETRIEVAL_STATE_SUCCESSFUL, null, KMLNetworkLink.this); - } - // Anything other than a KMLRoot is not a valid link target - else if (o != null) - { + } // Anything other than a KMLRoot is not a valid link target + else if (o != null) { String message = Logging.getMessage("KML.InvalidNetworkLinkTarget", address); Logging.logger().warning(message); this.invalidTarget = true; // Stop trying to retrieve this resource @@ -422,17 +416,15 @@ else if (o != null) * NetworkLinkControl/expires element in the target document, a HTTP Cache-Control header, or an HTTP Expires * header. * - * @param root Root of target resource. + * @param root Root of target resource. * @param address Address of linked resource. * * @return The expiration time of the resource, in milliseconds since the Epoch. Zero indicates that there is no - * expiration time. + * expiration time. */ - protected long computeExpiryRefreshTime(KMLRoot root, String address) - { + protected long computeExpiryRefreshTime(KMLRoot root, String address) { KMLNetworkLinkControl linkControl = root.getNetworkLinkControl(); - if (linkControl != null && linkControl.getExpires() != null) - { + if (linkControl != null && linkControl.getExpires() != null) { Long time = WWUtil.parseTimeString(linkControl.getExpires()); return time != null ? time : 0; } @@ -443,29 +435,26 @@ protected long computeExpiryRefreshTime(KMLRoot root, String address) /** * Indicates whether the network resource references by this KMLNetworkLink should be retrieved to the - * WorldWind cache or to a temporary location. This returns true if all of the following conditions - * are met, and false otherwise: + * WorldWind cache or to a temporary location. This returns true if all of the following conditions are + * met, and false otherwise: *

          • This network link has either a Link or a Url element.
          • The Link or Url * element's refreshMode is not onInterval or onExpire.
          • The Link or * Url element's viewRefreshMode is not onStop.
          * * @return true if this link's network resource can should be stored in a cache, or false - * if it should be stored in a temporary location. + * if it should be stored in a temporary location. */ - public boolean isLinkCacheable() - { + public boolean isLinkCacheable() { KMLLink link = this.getLinkOrUrl(); return link != null - && !KMLConstants.ON_INTERVAL.equalsIgnoreCase(link.getRefreshMode()) - && !KMLConstants.ON_EXPIRE.equalsIgnoreCase(link.getRefreshMode()) - && !KMLConstants.ON_STOP.equalsIgnoreCase(link.getViewRefreshMode()); + && !KMLConstants.ON_INTERVAL.equalsIgnoreCase(link.getRefreshMode()) + && !KMLConstants.ON_EXPIRE.equalsIgnoreCase(link.getRefreshMode()) + && !KMLConstants.ON_STOP.equalsIgnoreCase(link.getViewRefreshMode()); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLNetworkLink)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLNetworkLink)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -474,23 +463,23 @@ public void applyChange(KMLAbstractObject sourceValues) KMLNetworkLink sourceLink = (KMLNetworkLink) sourceValues; // Reset this network link only if the change contains a new link - if (sourceLink.getLinkOrUrl() != null) + if (sourceLink.getLinkOrUrl() != null) { this.reset(); + } super.applyChange(sourceValues); } @Override - public void onChange(Message msg) - { - if (KMLAbstractObject.MSG_LINK_CHANGED.equals(msg.getName())) + public void onChange(Message msg) { + if (KMLAbstractObject.MSG_LINK_CHANGED.equals(msg.getName())) { this.reset(); + } super.onChange(msg); } - protected void reset() - { + protected void reset() { this.networkResource.set(null); this.networkResourceRetrievalTime.set(-1); this.firstRetrievalTime = null; @@ -501,31 +490,34 @@ protected void reset() this.getRoot().requestRedraw(); // cause doPreRender to be called to initiate new link retrieval } - /** Attempts to find this network link resource file locally, and if that fails attempts to find it remotely. */ - protected static class RequestTask implements Runnable - { - /** The link associated with this request. */ + /** + * Attempts to find this network link resource file locally, and if that fails attempts to find it remotely. + */ + protected static class RequestTask implements Runnable { + + /** + * The link associated with this request. + */ protected final KMLNetworkLink link; - /** The resource's address. */ + /** + * The resource's address. + */ protected final String address; /** * Construct a request task for a specified network link resource. * - * @param link the network link for which to construct the request task. + * @param link the network link for which to construct the request task. * @param address the address of the resource to request. */ - protected RequestTask(KMLNetworkLink link, String address) - { - if (link == null) - { + protected RequestTask(KMLNetworkLink link, String address) { + if (link == null) { String message = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (address == null) - { + if (address == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -535,43 +527,43 @@ protected RequestTask(KMLNetworkLink link, String address) this.address = address; } - public void run() - { - if (Thread.currentThread().isInterrupted()) + public void run() { + if (Thread.currentThread().isInterrupted()) { return; // the task was cancelled because it's a duplicate or for some other reason - + } this.link.retrieveNetworkResource(this.address); } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } RequestTask that = (RequestTask) o; - if (!this.address.equals(that.address)) + if (!this.address.equals(that.address)) { return false; + } //noinspection RedundantIfStatement - if (!this.link.equals(that.link)) + if (!this.link.equals(that.link)) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = link.hashCode(); result = 31 * result + address.hashCode(); return result; } - public String toString() - { + public String toString() { return this.address; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLNetworkLinkControl.java b/src/gov/nasa/worldwind/ogc/kml/KMLNetworkLinkControl.java index 385cb037de..d4cf3bfa3f 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLNetworkLinkControl.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLNetworkLinkControl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.*; @@ -17,70 +16,59 @@ * @author tag * @version $Id: KMLNetworkLinkControl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLNetworkLinkControl extends AbstractXMLEventParser -{ - public KMLNetworkLinkControl(String namespaceURI) - { +public class KMLNetworkLinkControl extends AbstractXMLEventParser { + + public KMLNetworkLinkControl(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractView) + throws XMLStreamException { + if (o instanceof KMLAbstractView) { this.setField("AbstractView", o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public Double getMinRefreshPeriod() - { + public Double getMinRefreshPeriod() { return (Double) this.getField("minRefreshPeriod"); } - public Double getMaxSessionLength() - { + public Double getMaxSessionLength() { return (Double) this.getField("maxSessionLength"); } - public String getCookie() - { + public String getCookie() { return (String) this.getField("cookie"); } - public String getMessage() - { + public String getMessage() { return (String) this.getField("message"); } - public String getLinkName() - { + public String getLinkName() { return (String) this.getField("linkName"); } - public String getLinkDescription() - { + public String getLinkDescription() { return (String) this.getField("linkDescription"); } - public KMLSnippet getLinkSnippet() - { + public KMLSnippet getLinkSnippet() { return (KMLSnippet) this.getField("linkSnippet"); } - public String getExpires() - { + public String getExpires() { return (String) this.getField("expires"); } - public KMLUpdate getUpdate() - { + public KMLUpdate getUpdate() { return (KMLUpdate) this.getField("Update"); } - public KMLAbstractView getView() - { + public KMLAbstractView getView() { return (KMLAbstractView) this.getField("AbstractView"); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLOrientation.java b/src/gov/nasa/worldwind/ogc/kml/KMLOrientation.java index 3313132cd7..47587e23bb 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLOrientation.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLOrientation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,30 +11,26 @@ * @author tag * @version $Id: KMLOrientation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLOrientation extends KMLAbstractObject -{ +public class KMLOrientation extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLOrientation(String namespaceURI) - { + public KMLOrientation(String namespaceURI) { super(namespaceURI); } - public Double getHeading() - { + public Double getHeading() { return (Double) this.getField("heading"); } - public Double getTilt() - { + public Double getTilt() { return (Double) this.getField("tilt"); } - public Double getRoll() - { + public Double getRoll() { return (Double) this.getField("roll"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLPair.java b/src/gov/nasa/worldwind/ogc/kml/KMLPair.java index 59e9c8b67f..3c562274a6 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLPair.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLPair.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.*; @@ -17,45 +16,40 @@ * @author tag * @version $Id: KMLPair.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLPair extends KMLAbstractObject -{ +public class KMLPair extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLPair(String namespaceURI) - { + public KMLPair(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractStyleSelector) + throws XMLStreamException { + if (o instanceof KMLAbstractStyleSelector) { this.setStyleSelector((KMLAbstractStyleSelector) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public String getKey() - { + public String getKey() { return (String) this.getField("key"); } - public KMLStyleUrl getStyleUrl() - { + public KMLStyleUrl getStyleUrl() { return (KMLStyleUrl) this.getField("styleUrl"); } - public KMLAbstractStyleSelector getStyleSelector() - { + public KMLAbstractStyleSelector getStyleSelector() { return (KMLAbstractStyleSelector) this.getField("StyleSelector"); } - protected void setStyleSelector(KMLAbstractStyleSelector o) - { + protected void setStyleSelector(KMLAbstractStyleSelector o) { this.setField("StyleSelector", o); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLParserContext.java b/src/gov/nasa/worldwind/ogc/kml/KMLParserContext.java index fdcfc41584..fbd98a01ee 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLParserContext.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLParserContext.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.ogc.kml.gx.GXParserContext; @@ -21,147 +20,145 @@ * @author tag * @version $Id: KMLParserContext.java 1528 2013-07-31 01:00:32Z pabercrombie $ */ -public class KMLParserContext extends BasicXMLEventParserContext -{ +public class KMLParserContext extends BasicXMLEventParserContext { + protected KMLCoordinatesParser coordinatesParser; - /** The key used to identify the coordinates parser in the parser context's parser map. */ + /** + * The key used to identify the coordinates parser in the parser context's parser map. + */ protected static QName COORDINATES = new QName("Coordinates"); - /** The names of elements that contain merely string data and can be parsed by a generic string parser. */ - protected static final String[] StringFields = new String[] - { - // Only element names, not attribute names, are needed here. - "address", - "altitudeMode", - "begin", - "bgColor", - "color", - "colorMode", - "cookie", - "description", - "displayMode", - "displayName", - "end", - "expires", - "gridOrigin", - "href", - "httpQuery", - "key", - "labelColor", - "linkDescription", - "linkName", - "listItemType", - "message", - "name", - "phoneNumber", - "refreshMode", - "schemaUrl", - "shape", - "snippet", - "sourceHref", - "state", - "targetHref", - "text", - "textColor", - "type", - "value", - "viewFormat", - "viewRefreshMode", - "when", - "DocumentSource" - }; + /** + * The names of elements that contain merely string data and can be parsed by a generic string parser. + */ + protected static final String[] StringFields = new String[]{ + // Only element names, not attribute names, are needed here. + "address", + "altitudeMode", + "begin", + "bgColor", + "color", + "colorMode", + "cookie", + "description", + "displayMode", + "displayName", + "end", + "expires", + "gridOrigin", + "href", + "httpQuery", + "key", + "labelColor", + "linkDescription", + "linkName", + "listItemType", + "message", + "name", + "phoneNumber", + "refreshMode", + "schemaUrl", + "shape", + "snippet", + "sourceHref", + "state", + "targetHref", + "text", + "textColor", + "type", + "value", + "viewFormat", + "viewRefreshMode", + "when", + "DocumentSource" + }; - /** The names of elements that contain merely double data and can be parsed by a generic double parser. */ - protected static final String[] DoubleFields = new String[] - { - "altitude", - "bottomFov", - "east", - "heading", - "latitude", - "leftFov", - "longitude", - "maxAltitude", - "minAltitude", - "minFadeExtent", - "maxFadeExtent", - "minLodPixels", - "maxLodPixels", - "minRefreshPeriod", - "maxSessionLength", - "near", - "north", - "range", - "refreshInterval", - "rightFov", - "roll", - "rotation", - "scale", - "south", - "tilt", - "topFov", - "viewRefreshTime", - "viewBoundScale", - "west", - "width", - "x", - "y", - "z", - }; + /** + * The names of elements that contain merely double data and can be parsed by a generic double parser. + */ + protected static final String[] DoubleFields = new String[]{ + "altitude", + "bottomFov", + "east", + "heading", + "latitude", + "leftFov", + "longitude", + "maxAltitude", + "minAltitude", + "minFadeExtent", + "maxFadeExtent", + "minLodPixels", + "maxLodPixels", + "minRefreshPeriod", + "maxSessionLength", + "near", + "north", + "range", + "refreshInterval", + "rightFov", + "roll", + "rotation", + "scale", + "south", + "tilt", + "topFov", + "viewRefreshTime", + "viewBoundScale", + "west", + "width", + "x", + "y", + "z",}; - /** The names of elements that contain merely integer data and can be parsed by a generic integer parser. */ - protected static final String[] IntegerFields = new String[] - { - "drawOrder", - "maxHeight", - "maxLines", - "maxSnippetLines", - "maxWidth", - "tileSize", - }; + /** + * The names of elements that contain merely integer data and can be parsed by a generic integer parser. + */ + protected static final String[] IntegerFields = new String[]{ + "drawOrder", + "maxHeight", + "maxLines", + "maxSnippetLines", + "maxWidth", + "tileSize",}; /** * The names of elements that contain merely boolean integer (0 or 1) data and can be parsed by a generic boolean * integer parser. */ - protected static final String[] BooleanFields = new String[] - { - "extrude", - "fill", - "flyToView", - "open", - "outline", - "refreshVisibility", - "tessellate", - "visibility", - }; + protected static final String[] BooleanFields = new String[]{ + "extrude", + "fill", + "flyToView", + "open", + "outline", + "refreshVisibility", + "tessellate", + "visibility",}; /** * Creates a parser context instance. * - * @param defaultNamespace the default namespace. If null, {@link gov.nasa.worldwind.ogc.kml.KMLConstants#KML_NAMESPACE} - * is used. + * @param defaultNamespace the default namespace. If null, + * {@link gov.nasa.worldwind.ogc.kml.KMLConstants#KML_NAMESPACE} is used. */ - public KMLParserContext(String defaultNamespace) - { + public KMLParserContext(String defaultNamespace) { this(null, defaultNamespace); } /** * Creates a parser context instance. * - * @param eventReader the event reader from which to read events. - * @param defaultNamespace the default namespace. If null, {@link gov.nasa.worldwind.ogc.kml.KMLConstants#KML_NAMESPACE} - * is used. + * @param eventReader the event reader from which to read events. + * @param defaultNamespace the default namespace. If null, + * {@link gov.nasa.worldwind.ogc.kml.KMLConstants#KML_NAMESPACE} is used. */ - public KMLParserContext(XMLEventReader eventReader, String defaultNamespace) - { + public KMLParserContext(XMLEventReader eventReader, String defaultNamespace) { super(eventReader, defaultNamespace != null ? defaultNamespace : KMLConstants.KML_NAMESPACE); } - public KMLParserContext(KMLParserContext ctx) - { + public KMLParserContext(KMLParserContext ctx) { super(ctx); } @@ -169,8 +166,7 @@ public KMLParserContext(KMLParserContext ctx) * Loads the parser map with the parser to use for each element type. The parser may be changed by calling {@link * #registerParser(javax.xml.namespace.QName, gov.nasa.worldwind.util.xml.XMLEventParser)}. */ - protected void initializeParsers() - { + protected void initializeParsers() { super.initializeParsers(); this.parsers.put(COORDINATES, new KMLCoordinatesParser()); @@ -183,14 +179,12 @@ protected void initializeParsers() this.initializeVersion2dot0Parsers(); } - protected void initializeVersion2dot2Parsers() - { + protected void initializeVersion2dot2Parsers() { this.initializeParsers(KMLConstants.KML_2dot2_NAMESPACE); this.initializeParsers(KMLConstants.KML_GOOGLE_2dot2_NAMESPACE); } - protected void initializeParsers(String ns) - { + protected void initializeParsers(String ns) { this.parsers.put(new QName(ns, "Alias"), new KMLAlias(ns)); this.parsers.put(new QName(ns, "BalloonStyle"), new KMLBalloonStyle(ns)); this.parsers.put(new QName(ns, "Camera"), new KMLCamera(ns)); @@ -261,25 +255,21 @@ protected void initializeParsers(String ns) this.addBooleanParsers(ns, BooleanFields); } - protected void initializeVersion2dot1Parsers() - { + protected void initializeVersion2dot1Parsers() { // Just add all the default parsers. // TODO: Check for differences between 2.0 and 2.1 this.initializeParsers(KMLConstants.KML_2dot1_NAMESPACE); } - protected void initializeVersion2dot0Parsers() - { + protected void initializeVersion2dot0Parsers() { String ns = KMLConstants.KML_2dot0_NAMESPACE; // Just add all the default parsers. // TODO: Check for differences between 2.0 and 2.1 - for (Map.Entry entry : this.parsers.entrySet()) - { + for (Map.Entry entry : this.parsers.entrySet()) { this.parsers.put(new QName(ns, entry.getKey().getLocalPart()), entry.getValue()); } } - protected void initializeCompanionParsers() - { + protected void initializeCompanionParsers() { this.parsers.putAll(GXParserContext.getDefaultParsers()); this.parsers.putAll(AtomParserContext.getDefaultParsers()); this.parsers.putAll(XALParserContext.getDefaultParsers()); @@ -290,10 +280,10 @@ protected void initializeCompanionParsers() * * @return the default coordinates parser. */ - public KMLCoordinatesParser getCoordinatesParser() - { - if (this.coordinatesParser == null) + public KMLCoordinatesParser getCoordinatesParser() { + if (this.coordinatesParser == null) { this.coordinatesParser = (KMLCoordinatesParser) this.getParser(COORDINATES); + } return this.coordinatesParser; } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLPhotoOverlay.java b/src/gov/nasa/worldwind/ogc/kml/KMLPhotoOverlay.java index ecc4cb7da4..601c34779a 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLPhotoOverlay.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLPhotoOverlay.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,40 +11,34 @@ * @author tag * @version $Id: KMLPhotoOverlay.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLPhotoOverlay extends KMLAbstractOverlay -{ +public class KMLPhotoOverlay extends KMLAbstractOverlay { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLPhotoOverlay(String namespaceURI) - { + public KMLPhotoOverlay(String namespaceURI) { super(namespaceURI); } - public Double getRotation() - { + public Double getRotation() { return (Double) this.getField("rotation"); } - public KMLViewVolume getViewVolume() - { + public KMLViewVolume getViewVolume() { return (KMLViewVolume) this.getField("ViewVolume"); } - public KMLImagePyramid getImagePyramid() - { + public KMLImagePyramid getImagePyramid() { return (KMLImagePyramid) this.getField("ImagePyramid"); } - public KMLPoint getPoint() - { + public KMLPoint getPoint() { return (KMLPoint) this.getField("Point"); } - public String getShape() - { + public String getShape() { return (String) this.getField("shape"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLPlacemark.java b/src/gov/nasa/worldwind/ogc/kml/KMLPlacemark.java index 66a3cf9bb5..ed1bb03ed3 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLPlacemark.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLPlacemark.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.WorldWind; @@ -24,8 +23,8 @@ * @author tag * @version $Id: KMLPlacemark.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLPlacemark extends KMLAbstractFeature -{ +public class KMLPlacemark extends KMLAbstractFeature { + protected KMLAbstractGeometry geometry; protected List renderables; @@ -34,23 +33,21 @@ public class KMLPlacemark extends KMLAbstractFeature * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLPlacemark(String namespaceURI) - { + public KMLPlacemark(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractGeometry) + throws XMLStreamException { + if (o instanceof KMLAbstractGeometry) { this.setGeometry((KMLAbstractGeometry) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void setGeometry(KMLAbstractGeometry geometry) - { + protected void setGeometry(KMLAbstractGeometry geometry) { this.geometry = geometry; } @@ -59,8 +56,7 @@ protected void setGeometry(KMLAbstractGeometry geometry) * * @return the placemark's geometry element, or null if there is none. */ - public KMLAbstractGeometry getGeometry() - { + public KMLAbstractGeometry getGeometry() { return this.geometry; } @@ -74,15 +70,14 @@ public KMLSimpleData getSimpleData() // Included for test purposes only * * @return the placemark's renderables, or null if the placemark has no renderables. */ - public List getRenderables() - { + public List getRenderables() { return this.renderables; } - protected void addRenderable(KMLRenderable r) - { - if (r != null) + protected void addRenderable(KMLRenderable r) { + if (r != null) { this.getRenderables().add(r); + } } /** @@ -93,16 +88,14 @@ protected void addRenderable(KMLRenderable r) * @param dc the current draw context. */ @Override - protected void doPreRender(KMLTraversalContext tc, DrawContext dc) - { - if (this.getRenderables() == null) + protected void doPreRender(KMLTraversalContext tc, DrawContext dc) { + if (this.getRenderables() == null) { this.initializeGeometry(tc, this.getGeometry()); + } List rs = this.getRenderables(); - if (rs != null) - { - for (KMLRenderable r : rs) - { + if (rs != null) { + for (KMLRenderable r : rs) { r.preRender(tc, dc); } } @@ -115,16 +108,13 @@ protected void doPreRender(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @Override - protected void doRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doRender(KMLTraversalContext tc, DrawContext dc) { // We've already initialized the placemark's renderables during the preRender pass. Render the placemark's // renderable list without any further preparation. List rs = this.getRenderables(); - if (rs != null) - { - for (KMLRenderable r : rs) - { + if (rs != null) { + for (KMLRenderable r : rs) { r.render(tc, dc); } } @@ -133,89 +123,89 @@ protected void doRender(KMLTraversalContext tc, DrawContext dc) this.renderBalloon(tc, dc); } - protected void initializeGeometry(KMLTraversalContext tc, KMLAbstractGeometry geom) - { - if (geom == null) + protected void initializeGeometry(KMLTraversalContext tc, KMLAbstractGeometry geom) { + if (geom == null) { return; + } - if (this.getRenderables() == null) + if (this.getRenderables() == null) { this.renderables = new ArrayList(1); // most common case is one renderable - - if (geom instanceof KMLPoint) + } + if (geom instanceof KMLPoint) { this.addRenderable(this.selectPointRenderable(tc, geom)); - else if (geom instanceof KMLLinearRing) // since LinearRing is a subclass of LineString, this test must precede + } else if (geom instanceof KMLLinearRing) // since LinearRing is a subclass of LineString, this test must precede + { this.addRenderable(this.selectLinearRingRenderable(tc, geom)); - else if (geom instanceof KMLLineString) + } else if (geom instanceof KMLLineString) { this.addRenderable(this.selectLineStringRenderable(tc, geom)); - else if (geom instanceof KMLPolygon) + } else if (geom instanceof KMLPolygon) { this.addRenderable(this.selectPolygonRenderable(tc, geom)); - else if (geom instanceof KMLMultiGeometry) - { + } else if (geom instanceof KMLMultiGeometry) { List geoms = ((KMLMultiGeometry) geom).geometries; - if (geoms != null) - { - for (KMLAbstractGeometry g : geoms) - { + if (geoms != null) { + for (KMLAbstractGeometry g : geoms) { this.initializeGeometry(tc, g); // recurse } } - } - else if (geom instanceof KMLModel) + } else if (geom instanceof KMLModel) { this.addRenderable(this.selectModelRenderable(tc, geom)); + } } - protected KMLRenderable selectModelRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) - { + protected KMLRenderable selectModelRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) { return new KMLModelPlacemarkImpl(tc, this, geom); } - protected KMLRenderable selectPointRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) - { + protected KMLRenderable selectPointRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) { KMLPoint shape = (KMLPoint) geom; - if (shape.getCoordinates() == null) + if (shape.getCoordinates() == null) { return null; + } return new KMLPointPlacemarkImpl(tc, this, geom); } - protected KMLRenderable selectLineStringRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) - { + protected KMLRenderable selectLineStringRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) { KMLLineString shape = (KMLLineString) geom; - if (shape.getCoordinates() == null) + if (shape.getCoordinates() == null) { return null; + } return new KMLLineStringPlacemarkImpl(tc, this, geom); } - protected KMLRenderable selectLinearRingRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) - { + protected KMLRenderable selectLinearRingRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) { KMLLinearRing shape = (KMLLinearRing) geom; - if (shape.getCoordinates() == null) + if (shape.getCoordinates() == null) { return null; + } KMLLineStringPlacemarkImpl impl = new KMLLineStringPlacemarkImpl(tc, this, geom); if (impl.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND) // See note in google's version of KML spec + { impl.setPathType(AVKey.GREAT_CIRCLE); + } return impl; } - protected KMLRenderable selectPolygonRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) - { + protected KMLRenderable selectPolygonRenderable(KMLTraversalContext tc, KMLAbstractGeometry geom) { KMLPolygon shape = (KMLPolygon) geom; - if (shape.getOuterBoundary().getCoordinates() == null) + if (shape.getOuterBoundary().getCoordinates() == null) { return null; + } - if ("clampToGround".equals(shape.getAltitudeMode()) || !this.isValidAltitudeMode(shape.getAltitudeMode())) + if ("clampToGround".equals(shape.getAltitudeMode()) || !this.isValidAltitudeMode(shape.getAltitudeMode())) { return new KMLSurfacePolygonImpl(tc, this, geom); - else if (shape.isExtrude()) + } else if (shape.isExtrude()) { return new KMLExtrudedPolygonImpl(tc, this, geom); - else + } else { return new KMLPolygonImpl(tc, this, geom); + } } /** @@ -225,18 +215,15 @@ else if (shape.isExtrude()) * * @return True if {@code altMode} is one of "clampToGround", "relativeToGround", or "absolute". */ - protected boolean isValidAltitudeMode(String altMode) - { + protected boolean isValidAltitudeMode(String altMode) { return "clampToGround".equals(altMode) - || "relativeToGround".equals(altMode) - || "absolute".equals(altMode); + || "relativeToGround".equals(altMode) + || "absolute".equals(altMode); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLPlacemark)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLPlacemark)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -252,14 +239,11 @@ public void applyChange(KMLAbstractObject sourceValues) this.renderables = null; } - if (placemark.hasStyle()) - { + if (placemark.hasStyle()) { Message msg = new Message(KMLAbstractObject.MSG_STYLE_CHANGED, placemark); - if (this.renderables != null) - { - for (KMLRenderable renderable : this.renderables) - { + if (this.renderables != null) { + for (KMLRenderable renderable : this.renderables) { renderable.onMessage(msg); } } @@ -267,16 +251,11 @@ public void applyChange(KMLAbstractObject sourceValues) } @Override - public void onChange(Message msg) - { - if (KMLAbstractObject.MSG_GEOMETRY_CHANGED.equals(msg.getName())) - { + public void onChange(Message msg) { + if (KMLAbstractObject.MSG_GEOMETRY_CHANGED.equals(msg.getName())) { this.renderables = null; - } - else if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(msg.getName())) - { - for (KMLRenderable renderable : this.renderables) - { + } else if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(msg.getName())) { + for (KMLRenderable renderable : this.renderables) { renderable.onMessage(msg); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLPoint.java b/src/gov/nasa/worldwind/ogc/kml/KMLPoint.java index 090b7ef553..cc9e9624a8 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLPoint.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLPoint.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.geom.Position; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLPoint extends KMLAbstractGeometry -{ +public class KMLPoint extends KMLAbstractGeometry { + protected Position coordinates; /** @@ -28,52 +27,45 @@ public class KMLPoint extends KMLAbstractGeometry * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLPoint(String namespaceURI) - { + public KMLPoint(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (event.asStartElement().getName().getLocalPart().equals("coordinates")) + throws XMLStreamException { + if (event.asStartElement().getName().getLocalPart().equals("coordinates")) { this.setCoordinates((Position.PositionList) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public boolean isExtrude() - { + public boolean isExtrude() { return this.getExtrude() == Boolean.TRUE; } - public Boolean getExtrude() - { + public Boolean getExtrude() { return (Boolean) this.getField("extrude"); } - public String getAltitudeMode() - { + public String getAltitudeMode() { return (String) this.getField("altitudeMode"); } - public Position getCoordinates() - { + public Position getCoordinates() { return this.coordinates; } - protected void setCoordinates(Position.PositionList coordsList) - { - if (coordsList != null && coordsList.list.size() > 0) + protected void setCoordinates(Position.PositionList coordsList) { + if (coordsList != null && coordsList.list.size() > 0) { this.coordinates = coordsList.list.get(0); + } } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLPoint)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLPoint)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -81,8 +73,9 @@ public void applyChange(KMLAbstractObject sourceValues) KMLPoint point = (KMLPoint) sourceValues; - if (point.getCoordinates() != null) + if (point.getCoordinates() != null) { this.coordinates = point.getCoordinates(); + } super.applyChange(sourceValues); // sends geometry-changed notification } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLPolyStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLPolyStyle.java index e3d145eae3..2d863abeac 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLPolyStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLPolyStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,35 +11,30 @@ * @author tag * @version $Id: KMLPolyStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLPolyStyle extends KMLAbstractColorStyle -{ +public class KMLPolyStyle extends KMLAbstractColorStyle { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLPolyStyle(String namespaceURI) - { + public KMLPolyStyle(String namespaceURI) { super(namespaceURI); } - public Boolean getFill() - { + public Boolean getFill() { return (Boolean) this.getField("fill"); } - public boolean isFill() - { + public boolean isFill() { return this.getFill() == null || this.getFill(); } - public Boolean getOutline() - { + public Boolean getOutline() { return (Boolean) this.getField("outline"); } - public boolean isOutline() - { + public boolean isOutline() { return this.getOutline() == null || this.getOutline(); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLPolygon.java b/src/gov/nasa/worldwind/ogc/kml/KMLPolygon.java index 0d29d8af82..ff4a1371ec 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLPolygon.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLPolygon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLPolygon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLPolygon extends KMLAbstractGeometry -{ +public class KMLPolygon extends KMLAbstractGeometry { + protected List innerBoundaries; /** @@ -28,65 +27,56 @@ public class KMLPolygon extends KMLAbstractGeometry * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLPolygon(String namespaceURI) - { + public KMLPolygon(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLBoundary && event.asStartElement().getName().getLocalPart().equals("innerBoundaryIs")) + throws XMLStreamException { + if (o instanceof KMLBoundary && event.asStartElement().getName().getLocalPart().equals("innerBoundaryIs")) { this.addInnerBoundary(((KMLBoundary) o).getLinearRing()); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addInnerBoundary(KMLLinearRing o) - { - if (this.innerBoundaries == null) + protected void addInnerBoundary(KMLLinearRing o) { + if (this.innerBoundaries == null) { this.innerBoundaries = new ArrayList(); + } this.innerBoundaries.add(o); } - public boolean isExtrude() - { + public boolean isExtrude() { return this.getExtrude() == Boolean.TRUE; } - public Boolean getExtrude() - { + public Boolean getExtrude() { return (Boolean) this.getField("extrude"); } - public Boolean getTessellate() - { + public Boolean getTessellate() { return (Boolean) this.getField("tessellate"); } - public String getAltitudeMode() - { + public String getAltitudeMode() { return (String) this.getField("altitudeMode"); } - public Iterable getInnerBoundaries() - { + public Iterable getInnerBoundaries() { return this.innerBoundaries; } - public KMLLinearRing getOuterBoundary() - { + public KMLLinearRing getOuterBoundary() { Object o = this.getField("outerBoundaryIs"); return o != null ? ((KMLBoundary) o).getLinearRing() : null; } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLPolygon)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLPolygon)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -94,8 +84,9 @@ public void applyChange(KMLAbstractObject sourceValues) KMLPolygon sourcePolygon = (KMLPolygon) sourceValues; - if (sourcePolygon.getInnerBoundaries() != null) + if (sourcePolygon.getInnerBoundaries() != null) { this.innerBoundaries = sourcePolygon.innerBoundaries; + } super.applyChange(sourceValues); } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLRegion.java b/src/gov/nasa/worldwind/ogc/kml/KMLRegion.java index 93f14b323a..d9af37f1ec 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLRegion.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLRegion.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.*; @@ -71,8 +70,8 @@ * @author tag * @version $Id: KMLRegion.java 2029 2014-05-23 21:22:23Z pabercrombie $ */ -public class KMLRegion extends KMLAbstractObject -{ +public class KMLRegion extends KMLAbstractObject { + /** * The default time in milliseconds a RegionData element may exist in this Region's * regionDataCache before it must be regenerated: 6 seconds. @@ -84,8 +83,7 @@ public class KMLRegion extends KMLAbstractObject */ protected static final int DEFAULT_UNUSED_DATA_LIFETIME = 60000; /** - * The default value that configures KML scene resolution to screen resolution as the viewing distance changes: - * 2.8. + * The default value that configures KML scene resolution to screen resolution as the viewing distance changes: 2.8. */ protected static final double DEFAULT_DETAIL_HINT_ORIGIN = 2.8; @@ -112,9 +110,9 @@ public class KMLRegion extends KMLAbstractObject * determine if a Region's bounding box is in view. This property is accessed by calling getExtent and * setExtent. May be null. *

          - * sector
          RegionData's sector property is a Sector used to - * determine if Regions with an altitudeMode of clampToGround are in view. Accessed by - * calling getSector and setSector. When a Region's altitudeMode is + * sector
          RegionData's sector property is a Sector used to determine + * if Regions with an altitudeMode of clampToGround are in view. Accessed by calling + * getSector and setSector. When a Region's altitudeMode is * clampToGround, the Region's sector can be used to determine visibility because the Region is defined * to be on the Globe's surface. *

          @@ -124,13 +122,19 @@ public class KMLRegion extends KMLAbstractObject * clampToGround, this list must contain five points: the model-coordinate points of the Region's four * corners and center point on the surface terrain. */ - protected static class RegionData extends ShapeDataCache.ShapeDataCacheEntry - { - /** Identifies the frame used to calculate this entry's values. Initially -1. */ + protected static class RegionData extends ShapeDataCache.ShapeDataCacheEntry { + + /** + * Identifies the frame used to calculate this entry's values. Initially -1. + */ protected long frameNumber = -1; - /** Identifies the frame used to determine if this entry's Region is active. Initially -1. */ + /** + * Identifies the frame used to determine if this entry's Region is active. Initially -1. + */ protected long activeFrameNumber = -1; - /** Identifies whether this entry's Region is active. Initially false. */ + /** + * Identifies whether this entry's Region is active. Initially false. + */ protected boolean isActive; /** * Indicates the vertical datum against which the altitudes values in this entry's Region are interpreted. One @@ -154,12 +158,11 @@ protected static class RegionData extends ShapeDataCache.ShapeDataCacheEntry * Constructs a new RegionData entry from the Globe and vertical exaggeration of a * specified draw context. * - * @param dc the draw context. Must contain a Globe. + * @param dc the draw context. Must contain a Globe. * @param minExpiryTime the minimum expiration duration, in milliseconds. * @param maxExpiryTime the maximum expiration duration, in milliseconds. */ - public RegionData(DrawContext dc, long minExpiryTime, long maxExpiryTime) - { + public RegionData(DrawContext dc, long minExpiryTime, long maxExpiryTime) { super(dc, minExpiryTime, maxExpiryTime); } @@ -168,8 +171,7 @@ public RegionData(DrawContext dc, long minExpiryTime, long maxExpiryTime) * * @return the frame used to calculate this entry's values. */ - public long getFrameNumber() - { + public long getFrameNumber() { return frameNumber; } @@ -178,8 +180,7 @@ public long getFrameNumber() * * @param frameNumber the frame used to calculate this entry's values. */ - public void setFrameNumber(long frameNumber) - { + public void setFrameNumber(long frameNumber) { this.frameNumber = frameNumber; } @@ -188,8 +189,7 @@ public void setFrameNumber(long frameNumber) * * @return the frame used to determine if this entry's Region is active. */ - public long getActiveFrameNumber() - { + public long getActiveFrameNumber() { return activeFrameNumber; } @@ -198,8 +198,7 @@ public long getActiveFrameNumber() * * @param frameNumber the frame used to determine if this entry's Region is active. */ - public void setActiveFrameNumber(long frameNumber) - { + public void setActiveFrameNumber(long frameNumber) { this.activeFrameNumber = frameNumber; } @@ -208,8 +207,7 @@ public void setActiveFrameNumber(long frameNumber) * * @return true if this entry's Region is active, otherwise false. */ - public boolean isActive() - { + public boolean isActive() { return this.isActive; } @@ -218,8 +216,7 @@ public boolean isActive() * * @param active true to specify that this entry's Region is active, otherwise false. */ - public void setActive(boolean active) - { + public void setActive(boolean active) { this.isActive = active; } @@ -227,10 +224,9 @@ public void setActive(boolean active) * Indicates the vertical datum against which the altitudes values in this entry's Region are interpreted. * * @return the altitude mode of this entry's Region. One of WorldWind.ABSOLUTE, - * WorldWind.CLAMP_TO_GROUND, or WorldWind.RELATIVE_TO_GROUND. + * WorldWind.CLAMP_TO_GROUND, or WorldWind.RELATIVE_TO_GROUND. */ - public int getAltitudeMode() - { + public int getAltitudeMode() { return this.altitudeMode; } @@ -241,8 +237,7 @@ public int getAltitudeMode() * * @param altitudeMode the vertical datum to use. */ - public void setAltitudeMode(int altitudeMode) - { + public void setAltitudeMode(int altitudeMode) { this.altitudeMode = altitudeMode; } @@ -252,10 +247,9 @@ public void setAltitudeMode(int altitudeMode) * geographic bounding box. * * @return the Sector used to determine if a Region is visible, or null to specify - * that this entry's Region has no bounding box. + * that this entry's Region has no bounding box. */ - public Sector getSector() - { + public Sector getSector() { return this.sector; } @@ -264,10 +258,9 @@ public Sector getSector() * null to indicate that this entry' Region has no geographic bounding box. * * @param sector the Sector that is used to determine if a clampToGround Region is - * visible, or null to specify that the entry's Region's has no bounding box. + * visible, or null to specify that the entry's Region's has no bounding box. */ - public void setSector(Sector sector) - { + public void setSector(Sector sector) { this.sector = sector; } @@ -276,10 +269,9 @@ public void setSector(Sector sector) * returns null if this entry's Region has no geographic bounding box. * * @return the points representing the corners and interior of this entry's Region, or null if the - * Region has no bounding box. + * Region has no bounding box. */ - public List getPoints() - { + public List getPoints() { return this.points; } @@ -292,10 +284,9 @@ public List getPoints() * model-coordinate points of the Region's four corners and center point on the surface terrain. * * @param points the points representing the corners and interior of this entry's Region, or null - * to specify that this entry's Region has no bounding box. + * to specify that this entry's Region has no bounding box. */ - public void setPoints(List points) - { + public void setPoints(List points) { this.points = points; } } @@ -333,10 +324,9 @@ public void setPoints(List points) * has no bounding box and no level of detail range. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace - * qualification. + * qualification. */ - public KMLRegion(String namespaceURI) - { + public KMLRegion(String namespaceURI) { super(namespaceURI); } @@ -345,10 +335,9 @@ public KMLRegion(String namespaceURI) * null. * * @return this Region's geographic bounding box, or null indicating that this Region has no bounding - * box restriction. + * box restriction. */ - public KMLLatLonAltBox getLatLonAltBox() - { + public KMLLatLonAltBox getLatLonAltBox() { return (KMLLatLonAltBox) this.getField("LatLonAltBox"); } @@ -357,10 +346,9 @@ public KMLLatLonAltBox getLatLonAltBox() * null. * * @return this Region's level of detail range, or null indicating that this Region has no level of - * detail restriction. + * detail restriction. */ - public KMLLod getLod() - { + public KMLLod getLod() { return (KMLLod) this.getField("Lod"); } @@ -378,19 +366,16 @@ public KMLLod getLod() * @return true if this Region is active; otherwise false. * * @throws IllegalArgumentException if either the KMLTraversalContext or the DrawContext - * is null. + * is null. */ - public boolean isActive(KMLTraversalContext tc, DrawContext dc) - { - if (tc == null) - { + public boolean isActive(KMLTraversalContext tc, DrawContext dc) { + if (tc == null) { String message = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -403,8 +388,7 @@ public boolean isActive(KMLTraversalContext tc, DrawContext dc) // recompute isActive when the frame changes or when Globe changes, and return the computed value below. // Note that we use the same frustum intersection for both picking and rendering. We cannot cull against // the pick frustums because content (e.g. an open balloon) may extend beyond the region's bounding box. - if (dc.getFrameTimeStamp() != this.getCurrentData().getActiveFrameNumber()) - { + if (dc.getFrameTimeStamp() != this.getCurrentData().getActiveFrameNumber()) { this.getCurrentData().setActive(this.isRegionActive(tc, dc)); this.getCurrentData().setActiveFrameNumber(dc.getFrameTimeStamp()); } @@ -422,23 +406,19 @@ public boolean isActive(KMLTraversalContext tc, DrawContext dc) * * @see #isActive */ - protected void makeRegionData(DrawContext dc) - { + protected void makeRegionData(DrawContext dc) { // Retrieve the cached data for the current globe. If it doesn't yet exist, create it. Most code subsequently // executed depends on currentData being non-null. this.currentData = (RegionData) this.regionDataCache.getEntry(dc.getGlobe()); - if (this.currentData == null) - { + if (this.currentData == null) { this.currentData = this.createCacheEntry(dc); this.regionDataCache.addEntry(this.currentData); } // Re-use values already calculated this frame. - if (dc.getFrameTimeStamp() != this.getCurrentData().getFrameNumber()) - { + if (dc.getFrameTimeStamp() != this.getCurrentData().getFrameNumber()) { // Regenerate the region and data at a specified frequency. - if (this.mustRegenerateData(dc)) - { + if (this.mustRegenerateData(dc)) { this.doMakeRegionData(dc); this.getCurrentData().restartTimer(dc); this.getCurrentData().setGlobeStateKey(dc.getGlobe().getGlobeStateKey(dc)); @@ -454,8 +434,7 @@ protected void makeRegionData(DrawContext dc) * * @return the data cache entry for the current invocation of isActive. */ - protected RegionData getCurrentData() - { + protected RegionData getCurrentData() { return this.currentData; } @@ -466,8 +445,7 @@ protected RegionData getCurrentData() * * @return data cache entry for the state in the specified draw context. */ - protected RegionData createCacheEntry(DrawContext dc) - { + protected RegionData createCacheEntry(DrawContext dc) { return new RegionData(dc, this.minExpiryTime, this.maxExpiryTime); } @@ -482,8 +460,7 @@ protected RegionData createCacheEntry(DrawContext dc) * * @return true if this Region's data must be regenerated, otherwise false. */ - protected boolean mustRegenerateData(DrawContext dc) - { + protected boolean mustRegenerateData(DrawContext dc) { return this.getCurrentData().isExpired(dc) || !this.getCurrentData().isValid(dc); } @@ -498,28 +475,24 @@ protected boolean mustRegenerateData(DrawContext dc) * * @see #makeRegionData */ - protected void doMakeRegionData(DrawContext dc) - { + protected void doMakeRegionData(DrawContext dc) { this.getCurrentData().setExtent(null); this.getCurrentData().setSector(null); this.getCurrentData().setPoints(null); KMLLatLonAltBox box = this.getLatLonAltBox(); - if (box == null) + if (box == null) { return; + } int altitudeMode = KMLUtil.convertAltitudeMode(box.getAltitudeMode(), WorldWind.CLAMP_TO_GROUND); // KML default this.getCurrentData().setAltitudeMode(altitudeMode); - if (altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + if (altitudeMode == WorldWind.CLAMP_TO_GROUND) { this.doMakeClampToGroundRegionData(dc, box); - } - else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) { this.doMakeRelativeToGroundRegionData(dc, box); - } - else // Default to WorldWind.ABSOLUTE. + } else // Default to WorldWind.ABSOLUTE. { this.doMakeAbsoluteRegionData(dc, box); } @@ -530,19 +503,18 @@ else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) * is clampToGround. A {@link gov.nasa.worldwind.ogc.kml.KMLRegion.RegionData} must be * current when this method is called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param box the Region's geographic bounding box. */ - protected void doMakeClampToGroundRegionData(DrawContext dc, KMLLatLonAltBox box) - { + protected void doMakeClampToGroundRegionData(DrawContext dc, KMLLatLonAltBox box) { Sector sector = KMLUtil.createSectorFromLatLonBox(box); - if (sector == null) + if (sector == null) { return; + } // TODO: Regions outside of the normal lat/lon bounds ([-90, 90], [-180, 180]) are not supported. Remove // TODO: this warning when such regions are supported. See WWJINT-482. - if (!this.isSectorSupported(sector)) - { + if (!this.isSectorSupported(sector)) { String message = Logging.getMessage("KML.UnsupportedRegion", sector); Logging.logger().warning(message); return; @@ -550,7 +522,7 @@ protected void doMakeClampToGroundRegionData(DrawContext dc, KMLLatLonAltBox box double[] extremeElevations = dc.getGlobe().getMinAndMaxElevations(sector); Extent extent = Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), sector, - extremeElevations[0], extremeElevations[1]); + extremeElevations[0], extremeElevations[1]); this.getCurrentData().setExtent(extent); this.getCurrentData().setSector(sector); @@ -568,33 +540,32 @@ protected void doMakeClampToGroundRegionData(DrawContext dc, KMLLatLonAltBox box * is relativeToGround. A {@link gov.nasa.worldwind.ogc.kml.KMLRegion.RegionData} must be * current when this method is called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param box the Region's geographic bounding box. */ - protected void doMakeRelativeToGroundRegionData(DrawContext dc, KMLLatLonAltBox box) - { + protected void doMakeRelativeToGroundRegionData(DrawContext dc, KMLLatLonAltBox box) { Sector sector = KMLUtil.createSectorFromLatLonBox(box); - if (sector == null) + if (sector == null) { return; + } - if (!this.isSectorSupported(sector)) - { + if (!this.isSectorSupported(sector)) { String message = Logging.getMessage("KML.UnsupportedRegion", sector); Logging.logger().warning(message); return; } Double minAltitude = box.getMinAltitude(); - if (minAltitude == null) + if (minAltitude == null) { minAltitude = 0d; // The default minAltitude is zero. - + } Double maxAltitude = box.getMaxAltitude(); - if (maxAltitude == null) + if (maxAltitude == null) { maxAltitude = 0d; // The default maxAltitude is zero. - + } double[] extremeElevations = dc.getGlobe().getMinAndMaxElevations(sector); Extent extent = Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), sector, - extremeElevations[0] + minAltitude, extremeElevations[1] + maxAltitude); + extremeElevations[0] + minAltitude, extremeElevations[1] + maxAltitude); this.getCurrentData().setExtent(extent); this.getCurrentData().setSector(sector); } @@ -604,32 +575,31 @@ protected void doMakeRelativeToGroundRegionData(DrawContext dc, KMLLatLonAltBox * is absolute. A {@link gov.nasa.worldwind.ogc.kml.KMLRegion.RegionData} must be current * when this method is called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param box the Region's geographic bounding box. */ - protected void doMakeAbsoluteRegionData(DrawContext dc, KMLLatLonAltBox box) - { + protected void doMakeAbsoluteRegionData(DrawContext dc, KMLLatLonAltBox box) { Sector sector = KMLUtil.createSectorFromLatLonBox(box); - if (sector == null) + if (sector == null) { return; + } - if (!this.isSectorSupported(sector)) - { + if (!this.isSectorSupported(sector)) { String message = Logging.getMessage("KML.UnsupportedRegion", sector); Logging.logger().warning(message); return; } Double minAltitude = box.getMinAltitude(); - if (minAltitude == null) + if (minAltitude == null) { minAltitude = 0d; // The default minAltitude is zero. - + } Double maxAltitude = box.getMaxAltitude(); - if (maxAltitude == null) + if (maxAltitude == null) { maxAltitude = 0d; // The default maxAltitude is zero. - + } Extent extent = Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), sector, - minAltitude, maxAltitude); + minAltitude, maxAltitude); this.getCurrentData().setExtent(extent); this.getCurrentData().setSector(sector); } @@ -642,8 +612,7 @@ protected void doMakeAbsoluteRegionData(DrawContext dc, KMLLatLonAltBox box) * * @return {@code true} if {@code sector} is with [-90, 90] latitude and [-180, 180] longitude. */ - protected boolean isSectorSupported(Sector sector) - { + protected boolean isSectorSupported(Sector sector) { return sector.isWithinLatLonLimits(); } @@ -658,8 +627,7 @@ protected boolean isSectorSupported(Sector sector) * * @return true if this Region is active; otherwise false. */ - protected boolean isRegionActive(KMLTraversalContext tc, DrawContext dc) - { + protected boolean isRegionActive(KMLTraversalContext tc, DrawContext dc) { return this.isRegionVisible(dc) && this.meetsLodCriteria(tc, dc); } @@ -674,15 +642,13 @@ protected boolean isRegionActive(KMLTraversalContext tc, DrawContext dc) * * @return true if this Region is visible, otherwise false. */ - protected boolean isRegionVisible(DrawContext dc) - { + protected boolean isRegionVisible(DrawContext dc) { // If this Region's altitude mode is clampToGround and it has a non-null sector, compare its sector against the // DrawContext's visible sector to determine if the Region is visible. In this case the sector can be used to // determine visibility because the Region is defined to be on the Globe's surface. if (this.getCurrentData().getAltitudeMode() == WorldWind.CLAMP_TO_GROUND - && dc.getVisibleSector() != null && this.getCurrentData().getSector() != null - && !dc.getVisibleSector().intersects(this.getCurrentData().getSector())) - { + && dc.getVisibleSector() != null && this.getCurrentData().getSector() != null + && !dc.getVisibleSector().intersects(this.getCurrentData().getSector())) { return false; } @@ -692,8 +658,9 @@ protected boolean isRegionVisible(DrawContext dc) // is in the frustum, we treat the Region just as though its outside of the frustum and prevent the display of // any features associated with it. //noinspection SimplifiableIfStatement - if (this.getCurrentData().getExtent() != null && dc.isSmall(this.getCurrentData().getExtent(), 1)) + if (this.getCurrentData().getExtent() != null && dc.isSmall(this.getCurrentData().getExtent(), 1)) { return false; + } return this.intersectsFrustum(dc); } @@ -708,15 +675,14 @@ protected boolean isRegionVisible(DrawContext dc) * @param dc the DrawContext who's frustum is tested against this Region's bounding box. * * @return true if this Region's bounding box intersects the DrawContext's frustum, - * otherwise false. + * otherwise false. */ - protected boolean intersectsFrustum(DrawContext dc) - { + protected boolean intersectsFrustum(DrawContext dc) { Extent extent = this.getCurrentData().getExtent(); //noinspection SimplifiableIfStatement - if (extent == null) + if (extent == null) { return true; // We do not know the visibility; assume it intersects the frustum. - + } // Test against the view frustum even in picking mode. We cannot cull against the pick frustums because visible // content (e.g. an open balloon) may extend beyond the region's bounding box. return dc.getView().getFrustumInModelCoordinates().intersects(extent); @@ -733,32 +699,27 @@ protected boolean intersectsFrustum(DrawContext dc) * @param dc the DrawContext to test. * * @return true if the DrawContext's meets this Region's level of detail criteria, - * otherwise false. + * otherwise false. */ - protected boolean meetsLodCriteria(KMLTraversalContext tc, DrawContext dc) - { + protected boolean meetsLodCriteria(KMLTraversalContext tc, DrawContext dc) { KMLLod lod = this.getLod(); - if (lod == null) + if (lod == null) { return true; // No level of detail specified; assume the DrawContext meets the level of detail criteria. - + } if ((lod.getMinLodPixels() == null || lod.getMinLodPixels() <= 0d) - && (lod.getMaxLodPixels() == null || lod.getMaxLodPixels() < 0d)) + && (lod.getMaxLodPixels() == null || lod.getMaxLodPixels() < 0d)) { return true; // The level of detail range is infinite, so this Region always meets the lod criteria. - - if (lod.getMaxLodPixels() != null && lod.getMaxLodPixels() == 0d) + } + if (lod.getMaxLodPixels() != null && lod.getMaxLodPixels() == 0d) { return false; // The maximum number of pixels is zero, so this Region never meets the lod criteria. - + } int altitudeMode = this.getCurrentData().getAltitudeMode(); - if (altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + if (altitudeMode == WorldWind.CLAMP_TO_GROUND) { return this.meetsClampToGroundLodCriteria(tc, dc, lod); - } - else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) { return this.meetsRelativeToGroundLodCriteria(tc, dc, lod); - } - else // Default to WorldWind.ABSOLUTE. + } else // Default to WorldWind.ABSOLUTE. { return this.meetsAbsoluteLodCriteria(tc, dc, lod); } @@ -766,18 +727,17 @@ else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) /** * Indicates whether the specified DrawContext meets this Region's level of detail criteria. Assumes - * this region's altitude mode is clampToGround. A {@link gov.nasa.worldwind.ogc.kml.KMLRegion.RegionData} - * must be current when this method is called. + * this region's altitude mode is clampToGround. A + * {@link gov.nasa.worldwind.ogc.kml.KMLRegion.RegionData} must be current when this method is called. * - * @param tc the current KML traversal context. - * @param dc the DrawContext to test. + * @param tc the current KML traversal context. + * @param dc the DrawContext to test. * @param lod the level of detail criteria that must be met. * * @return true if the DrawContext's meets this Region's level of detail criteria, - * otherwise false. + * otherwise false. */ - protected boolean meetsClampToGroundLodCriteria(KMLTraversalContext tc, DrawContext dc, KMLLod lod) - { + protected boolean meetsClampToGroundLodCriteria(KMLTraversalContext tc, DrawContext dc, KMLLod lod) { // Neither the OGC KML specification nor the Google KML reference specify how to compute a clampToGround // Region's projected screen area. However, the Google Earth outreach tutorials, and an official post from a // Google engineer on the Google forums both indicate that clampToGround Regions are represented by a flat @@ -788,9 +748,9 @@ protected boolean meetsClampToGroundLodCriteria(KMLTraversalContext tc, DrawCont Sector sector = this.getCurrentData().getSector(); List points = this.getCurrentData().getPoints(); - if (sector == null || points == null || points.size() != 5) + if (sector == null || points == null || points.size() != 5) { return true; // Assume the criteria is met if we don't know this Region's sector or its surface points. - + } // Get the eye distance for each of the sector's corners and its center. View view = dc.getView(); double d1 = view.getEyePoint().distanceTo3(points.get(0)); @@ -807,23 +767,19 @@ protected boolean meetsClampToGroundLodCriteria(KMLTraversalContext tc, DrawCont double numRadians = Math.sqrt(sector.getDeltaLatRadians() * sector.getDeltaLonRadians()); double numMeters = points.get(0).getLength3() * numRadians; - if (d2 < minDistance) - { + if (d2 < minDistance) { minDistance = d2; numMeters = points.get(1).getLength3() * numRadians; } - if (d3 < minDistance) - { + if (d3 < minDistance) { minDistance = d3; numMeters = points.get(2).getLength3() * numRadians; } - if (d4 < minDistance) - { + if (d4 < minDistance) { minDistance = d4; numMeters = points.get(3).getLength3() * numRadians; } - if (d5 < minDistance) - { + if (d5 < minDistance) { minDistance = d5; numMeters = points.get(4).getLength3() * numRadians; } @@ -833,11 +789,9 @@ protected boolean meetsClampToGroundLodCriteria(KMLTraversalContext tc, DrawCont // scaled distance is less than or equal to the minimum pixel size, and greater than the maximum pixel size. // Said another way, this Region is used when a pixel in the Region's sector is close enough to meet the minimum // pixel size criteria, yet far enough away not to exceed the maximum pixel size criteria. - // NOTE: It's tempting to instead compare a screen pixel count to the minLodPixels and maxLodPixels, but that // calculation is window-size dependent and results in activating an excessive number of Regions when a KML // super overlay is displayed, especially if the window size is large. - Double lodMinPixels = lod.getMinLodPixels(); Double lodMaxPixels = lod.getMaxLodPixels(); double distanceFactor = minDistance * Math.pow(10, -this.getDetailFactor(tc)); @@ -846,7 +800,7 @@ protected boolean meetsClampToGroundLodCriteria(KMLTraversalContext tc, DrawCont // unspecified or less than 0 (infinity). In these cases any distance passes the test against minLodPixels or // maxLodPixels. return (lodMinPixels == null || lodMinPixels <= 0d || (numMeters / lodMinPixels) >= distanceFactor) - && (lodMaxPixels == null || lodMaxPixels < 0d || (numMeters / lodMaxPixels) < distanceFactor); + && (lodMaxPixels == null || lodMaxPixels < 0d || (numMeters / lodMaxPixels) < distanceFactor); } /** @@ -854,34 +808,32 @@ protected boolean meetsClampToGroundLodCriteria(KMLTraversalContext tc, DrawCont * this region's altitude mode is relativeToGround. A {@link * gov.nasa.worldwind.ogc.kml.KMLRegion.RegionData} must be current when this method is called. * - * @param tc the current KML traversal context. - * @param dc the DrawContext to test. + * @param tc the current KML traversal context. + * @param dc the DrawContext to test. * @param lod the level of detail criteria that must be met. * * @return true if the DrawContext's meets this Region's level of detail criteria, - * otherwise false. + * otherwise false. */ @SuppressWarnings({"UnusedDeclaration"}) - protected boolean meetsRelativeToGroundLodCriteria(KMLTraversalContext tc, DrawContext dc, KMLLod lod) - { + protected boolean meetsRelativeToGroundLodCriteria(KMLTraversalContext tc, DrawContext dc, KMLLod lod) { return this.meetsScreenAreaCriteria(dc, lod); } /** * Indicates whether the specified DrawContext meets this Region's level of detail criteria. Assumes - * this region's altitude mode is absolute. A {@link gov.nasa.worldwind.ogc.kml.KMLRegion.RegionData} - * must be current when this method is called. + * this region's altitude mode is absolute. A + * {@link gov.nasa.worldwind.ogc.kml.KMLRegion.RegionData} must be current when this method is called. * - * @param tc the current KML traversal context. - * @param dc the DrawContext to test. + * @param tc the current KML traversal context. + * @param dc the DrawContext to test. * @param lod the level of detail criteria that must be met. * * @return true if the DrawContext's meets this Region's level of detail criteria, - * otherwise false. + * otherwise false. */ @SuppressWarnings({"UnusedDeclaration"}) - protected boolean meetsAbsoluteLodCriteria(KMLTraversalContext tc, DrawContext dc, KMLLod lod) - { + protected boolean meetsAbsoluteLodCriteria(KMLTraversalContext tc, DrawContext dc, KMLLod lod) { return this.meetsScreenAreaCriteria(dc, lod); } @@ -889,14 +841,13 @@ protected boolean meetsAbsoluteLodCriteria(KMLTraversalContext tc, DrawContext d * Indicates whether this Region's projected screen area on the specified DrawContext is in the range * specified by lod. * - * @param dc the DrawContext to test. + * @param dc the DrawContext to test. * @param lod the level of detail criteria that must be met. * * @return true if this Region's screen area meets the level of detail criteria, otherwise - * false. + * false. */ - protected boolean meetsScreenAreaCriteria(DrawContext dc, KMLLod lod) - { + protected boolean meetsScreenAreaCriteria(DrawContext dc, KMLLod lod) { // The DrawContext does not meet this region's minLodPixels criteria if minLodPixels is specified and this // region's projected screen pixel count is less than minLodPixels. @@ -904,30 +855,29 @@ protected boolean meetsScreenAreaCriteria(DrawContext dc, KMLLod lod) // negative, and this region's projected screen pixel count is greater than or equal to maxLodPixels. If // maxLodPixels is negative, this indicates that maxLodPixels is positive infinity and therefore accepts any // value. - Extent extent = this.getCurrentData().getExtent(); - if (extent == null) + if (extent == null) { return true; // Assume the criteria is met if we don't know this Region's extent. - + } // Compute the projected screen area of this Region's extent in square pixels in the DrawContext's View. // According to the KML specification, we take the square root of this value to get a value that is comparable // against minLodPixels and maxLodPixels. The projected area is positive infinity if the view's eye point is // inside the extent, or if part of the extent is behind the eye point. In either case we do not take the square // root, and leave the value as positive infinity. double numPixels = extent.getProjectedArea(dc.getView()); - if (numPixels != Double.POSITIVE_INFINITY) + if (numPixels != Double.POSITIVE_INFINITY) { numPixels = Math.sqrt(numPixels); + } // This Region's level of detail criteria are met if the number of pixels is greater than or equal to // minLodPixels and less than maxLodPixels. We ignore minLodPixels if it's unspecified, zero, or less than zero. // We ignore maxLodPixels if it's unspecified or less than 0 (infinity). In these cases any distance passes the // test against minLodPixels or maxLodPixels. - Double lodMinPixels = lod.getMinLodPixels(); Double lodMaxPixels = lod.getMaxLodPixels(); return (lodMinPixels == null || lodMinPixels <= 0d || lodMinPixels <= numPixels) - && (lodMaxPixels == null || lodMaxPixels < 0d || lodMaxPixels > numPixels); + && (lodMaxPixels == null || lodMaxPixels < 0d || lodMaxPixels > numPixels); } /** @@ -939,16 +889,13 @@ protected boolean meetsScreenAreaCriteria(DrawContext dc, KMLLod lod) * * @return this Region's detailHintOrigin plus the traversal context's detailHintOrigin. */ - protected double getDetailFactor(KMLTraversalContext tc) - { + protected double getDetailFactor(KMLTraversalContext tc) { return this.detailHintOrigin + tc.getDetailHint(); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLRegion)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLRegion)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -960,16 +907,15 @@ public void applyChange(KMLAbstractObject sourceValues) } @Override - public void onChange(Message msg) - { - if (KMLAbstractObject.MSG_BOX_CHANGED.equals(msg.getName())) + public void onChange(Message msg) { + if (KMLAbstractObject.MSG_BOX_CHANGED.equals(msg.getName())) { this.reset(); + } super.onChange(msg); } - protected void reset() - { + protected void reset() { this.regionDataCache.removeAllEntries(); this.currentData = null; } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLResourceMap.java b/src/gov/nasa/worldwind/ogc/kml/KMLResourceMap.java index f4a76c70f8..0d20f0481b 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLResourceMap.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLResourceMap.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -18,32 +17,29 @@ * @author tag * @version $Id: KMLResourceMap.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLResourceMap extends KMLAbstractObject -{ +public class KMLResourceMap extends KMLAbstractObject { + protected List aliases = new ArrayList(); - public KMLResourceMap(String namespaceURI) - { + public KMLResourceMap(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAlias) + throws XMLStreamException { + if (o instanceof KMLAlias) { this.addAlias((KMLAlias) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addAlias(KMLAlias o) - { + protected void addAlias(KMLAlias o) { this.aliases.add(o); } - public List getAliases() - { + public List getAliases() { return this.aliases; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLRoot.java b/src/gov/nasa/worldwind/ogc/kml/KMLRoot.java index 16dc7ddad9..cfdbd8fe1f 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLRoot.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLRoot.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.WorldWind; @@ -31,15 +30,23 @@ * @author tag * @version $Id: KMLRoot.java 1951 2014-04-20 18:57:50Z tgaskins $ */ -public class KMLRoot extends KMLAbstractObject implements KMLRenderable -{ - /** Reference to the KMLDoc representing the KML or KMZ file. */ +public class KMLRoot extends KMLAbstractObject implements KMLRenderable { + + /** + * Reference to the KMLDoc representing the KML or KMZ file. + */ protected KMLDoc kmlDoc; - /** The event reader used to parse the document's XML. */ + /** + * The event reader used to parse the document's XML. + */ protected XMLEventReader eventReader; - /** The input stream underlying the event reader. */ + /** + * The input stream underlying the event reader. + */ protected InputStream eventStream; - /** The parser context for the document. */ + /** + * The parser context for the document. + */ protected KMLParserContext parserContext; /** * The PropertyChangeSupport that receives property change events this KMLRoot listens for, and sends @@ -53,11 +60,15 @@ public class KMLRoot extends KMLAbstractObject implements KMLRenderable * decrease the resolution. Initially 0. */ protected double detailHint; - /** Flag to indicate that the feature has been fetched from the hash map. */ + /** + * Flag to indicate that the feature has been fetched from the hash map. + */ protected boolean featureFetched = false; protected KMLAbstractFeature feature; - /** Flag to indicate that the network link control element has been fetched from the hash map. */ + /** + * Flag to indicate that the network link control element has been fetched from the hash map. + */ protected boolean linkControlFetched = false; protected KMLNetworkLinkControl networkLinkControl; @@ -70,15 +81,14 @@ public class KMLRoot extends KMLAbstractObject implements KMLRenderable * test is not definitive. Null is returned if the source type is not recognized. * * @param docSource either a {@link File}, a {@link URL}, or an {@link InputStream}, or a {@link String} identifying - * a file path or URL. + * a file path or URL. * * @return a new {@link KMLRoot} for the specified source, or null if the source type is not supported. * * @throws IllegalArgumentException if the source is null. - * @throws IOException if an error occurs while reading the source. + * @throws IOException if an error occurs while reading the source. */ - public static KMLRoot create(Object docSource) throws IOException - { + public static KMLRoot create(Object docSource) throws IOException { return create(docSource, true); } @@ -88,40 +98,39 @@ public static KMLRoot create(Object docSource) throws IOException * InputStream an attempt is made to determine whether the source is KML or KMZ; KML is assumed if the * test is not definitive. Null is returned if the source type is not recognized. * - * @param docSource either a {@link File}, a {@link URL}, or an {@link InputStream}, or a {@link String} - * identifying a file path or URL. + * @param docSource either a {@link File}, a {@link URL}, or an {@link InputStream}, or a {@link String} identifying + * a file path or URL. * @param namespaceAware specifies whether to use a namespace-aware XML parser. true if so, - * false if not. + * false if not. * * @return a new {@link KMLRoot} for the specified source, or null if the source type is not supported. * * @throws IllegalArgumentException if the source is null. - * @throws IOException if an error occurs while reading the source. + * @throws IOException if an error occurs while reading the source. */ - public static KMLRoot create(Object docSource, boolean namespaceAware) throws IOException - { - if (docSource == null) - { + public static KMLRoot create(Object docSource, boolean namespaceAware) throws IOException { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (docSource instanceof File) + if (docSource instanceof File) { return new KMLRoot((File) docSource, namespaceAware); - else if (docSource instanceof URL) + } else if (docSource instanceof URL) { return new KMLRoot((URL) docSource, null, namespaceAware); - else if (docSource instanceof InputStream) + } else if (docSource instanceof InputStream) { return new KMLRoot((InputStream) docSource, null, namespaceAware); - else if (docSource instanceof String) - { + } else if (docSource instanceof String) { File file = new File((String) docSource); - if (file.exists()) + if (file.exists()) { return new KMLRoot(file, namespaceAware); + } URL url = WWIO.makeURL(docSource); - if (url != null) + if (url != null) { return new KMLRoot(url, null, namespaceAware); + } } return null; @@ -139,33 +148,27 @@ else if (docSource instanceof String) * bypasses many problems, but it also causes namespace qualified elements in the XML to be unrecognized. * * @param docSource either a {@link File}, a {@link URL}, or an {@link InputStream}, or a {@link String} identifying - * a file path or URL. + * a file path or URL. * * @return a new {@link KMLRoot} for the specified source, or null if the source type is not supported. * * @throws IllegalArgumentException if the source is null. - * @throws IOException if an error occurs while reading the source. - * @throws javax.xml.stream.XMLStreamException - * if the KML file has severe errors. + * @throws IOException if an error occurs while reading the source. + * @throws javax.xml.stream.XMLStreamException if the KML file has severe errors. */ - public static KMLRoot createAndParse(Object docSource) throws IOException, XMLStreamException - { + public static KMLRoot createAndParse(Object docSource) throws IOException, XMLStreamException { KMLRoot kmlRoot = KMLRoot.create(docSource); - if (kmlRoot == null) - { + if (kmlRoot == null) { String message = Logging.getMessage("generic.UnrecognizedSourceTypeOrUnavailableSource", - docSource.toString()); + docSource.toString()); throw new IllegalArgumentException(message); } - try - { + try { // Try with a namespace aware parser. kmlRoot.parse(); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { // Try without namespace awareness. kmlRoot = KMLRoot.create(docSource, false); kmlRoot.parse(); @@ -181,10 +184,9 @@ public static KMLRoot createAndParse(Object docSource) throws IOException, XMLSt * @param docSource the KMLDoc instance representing the KML document. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the KML document. + * @throws IOException if an error occurs while reading the KML document. */ - public KMLRoot(KMLDoc docSource) throws IOException - { + public KMLRoot(KMLDoc docSource) throws IOException { this(docSource, true); } @@ -192,19 +194,17 @@ public KMLRoot(KMLDoc docSource) throws IOException * Create a new KMLRoot for a {@link KMLDoc} instance. A KMLDoc represents KML and KMZ files from * either files or input streams. * - * @param docSource the KMLDoc instance representing the KML document. + * @param docSource the KMLDoc instance representing the KML document. * @param namespaceAware specifies whether to use a namespace-aware XML parser. true if so, - * false if not. + * false if not. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the KML document. + * @throws IOException if an error occurs while reading the KML document. */ - public KMLRoot(KMLDoc docSource, boolean namespaceAware) throws IOException - { + public KMLRoot(KMLDoc docSource, boolean namespaceAware) throws IOException { super(KMLConstants.KML_NAMESPACE); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -221,52 +221,45 @@ public KMLRoot(KMLDoc docSource, boolean namespaceAware) throws IOException * @param docSource the File containing the document. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the KML document. + * @throws IOException if an error occurs while reading the KML document. */ - public KMLRoot(File docSource) throws IOException - { + public KMLRoot(File docSource) throws IOException { this(docSource, true); } /** * Create a new KMLRoot for a {@link File}. * - * @param docSource the File containing the document. + * @param docSource the File containing the document. * @param namespaceAware specifies whether to use a namespace-aware XML parser. true if so, - * false if not. + * false if not. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the KML document. + * @throws IOException if an error occurs while reading the KML document. */ - public KMLRoot(File docSource, boolean namespaceAware) throws IOException - { + public KMLRoot(File docSource, boolean namespaceAware) throws IOException { super(KMLConstants.KML_NAMESPACE); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWIO.isContentType(docSource, KMLConstants.KML_MIME_TYPE)) + if (WWIO.isContentType(docSource, KMLConstants.KML_MIME_TYPE)) { this.kmlDoc = new KMLFile(docSource); - else if (WWIO.isContentType(docSource, KMLConstants.KMZ_MIME_TYPE)) - { - try - { + } else if (WWIO.isContentType(docSource, KMLConstants.KMZ_MIME_TYPE)) { + try { this.kmlDoc = new KMZFile(docSource); - } - catch (ZipException e) - { + } catch (ZipException e) { // We've encountered some zip files that will not open with ZipFile, but will open // with ZipInputStream. Try again, this time opening treating the file as a stream. // See WWJINT-282. this.kmlDoc = new KMZInputStream(new FileInputStream(docSource)); } - } - else + } else { throw new WWUnrecognizedException(Logging.getMessage("KML.UnrecognizedKMLFileType")); + } this.initialize(namespaceAware); } @@ -274,49 +267,47 @@ else if (WWIO.isContentType(docSource, KMLConstants.KMZ_MIME_TYPE)) /** * Create a new KMLRoot for an {@link InputStream}. * - * @param docSource the input stream containing the document. + * @param docSource the input stream containing the document. * @param contentType the content type of the stream data. Specify {@link KMLConstants#KML_MIME_TYPE} for plain KML - * and {@link KMLConstants#KMZ_MIME_TYPE} for KMZ. The content is treated as KML for any other - * value or a value of null. + * and {@link KMLConstants#KMZ_MIME_TYPE} for KMZ. The content is treated as KML for any other value or a value of + * null. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the KML document. + * @throws IOException if an error occurs while reading the KML document. */ - public KMLRoot(InputStream docSource, String contentType) throws IOException - { + public KMLRoot(InputStream docSource, String contentType) throws IOException { this(docSource, contentType, true); } /** * Create a new KMLRoot for an {@link InputStream}. * - * @param docSource the input stream containing the document. - * @param contentType the content type of the stream data. Specify {@link KMLConstants#KML_MIME_TYPE} for plain - * KML and {@link KMLConstants#KMZ_MIME_TYPE} for KMZ. The content is treated as KML for any - * other value or a value of null. + * @param docSource the input stream containing the document. + * @param contentType the content type of the stream data. Specify {@link KMLConstants#KML_MIME_TYPE} for plain KML + * and {@link KMLConstants#KMZ_MIME_TYPE} for KMZ. The content is treated as KML for any other value or a value of + * null. * @param namespaceAware specifies whether to use a namespace-aware XML parser. true if so, - * false if not. + * false if not. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the KML document. + * @throws IOException if an error occurs while reading the KML document. */ - public KMLRoot(InputStream docSource, String contentType, boolean namespaceAware) throws IOException - { + public KMLRoot(InputStream docSource, String contentType, boolean namespaceAware) throws IOException { super(KMLConstants.KML_NAMESPACE); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (contentType != null && contentType.equals(KMLConstants.KMZ_MIME_TYPE)) + if (contentType != null && contentType.equals(KMLConstants.KMZ_MIME_TYPE)) { this.kmlDoc = new KMZInputStream(docSource); - else if (contentType == null && docSource instanceof ZipInputStream) + } else if (contentType == null && docSource instanceof ZipInputStream) { this.kmlDoc = new KMZInputStream(docSource); - else + } else { this.kmlDoc = new KMLInputStream(docSource, null); + } this.initialize(namespaceAware); } @@ -324,60 +315,58 @@ else if (contentType == null && docSource instanceof ZipInputStream) /** * Create a KMLRoot for a {@link URL}. * - * @param docSource the URL identifying the document. + * @param docSource the URL identifying the document. * @param contentType the content type of the data. Specify {@link KMLConstants#KML_MIME_TYPE} for plain KML and - * {@link KMLConstants#KMZ_MIME_TYPE} for KMZ. Any other non-null value causes the content to be - * treated as plain KML. If null is specified the content type is read from the server or other - * end point of the URL. When a content type is specified, the content type returned by the URL's - * end point is ignored. You can therefore force the content to be treated as KML or KMZ - * regardless of what a server declares it to be. + * {@link KMLConstants#KMZ_MIME_TYPE} for KMZ. Any other non-null value causes the content to be treated as plain + * KML. If null is specified the content type is read from the server or other end point of the URL. When a content + * type is specified, the content type returned by the URL's end point is ignored. You can therefore force the + * content to be treated as KML or KMZ regardless of what a server declares it to be. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the document. + * @throws IOException if an error occurs while reading the document. */ - public KMLRoot(URL docSource, String contentType) throws IOException - { + public KMLRoot(URL docSource, String contentType) throws IOException { this(docSource, contentType, true); } /** * Create a KMLRoot for a {@link URL}. * - * @param docSource the URL identifying the document. - * @param contentType the content type of the data. Specify {@link KMLConstants#KML_MIME_TYPE} for plain KML and - * {@link KMLConstants#KMZ_MIME_TYPE} for KMZ. Any other non-null value causes the content to - * be treated as plain KML. If null is specified the content type is read from the server or - * other end point of the URL. When a content type is specified, the content type returned by - * the URL's end point is ignored. You can therefore force the content to be treated as KML or - * KMZ regardless of what a server declares it to be. + * @param docSource the URL identifying the document. + * @param contentType the content type of the data. Specify {@link KMLConstants#KML_MIME_TYPE} for plain KML and + * {@link KMLConstants#KMZ_MIME_TYPE} for KMZ. Any other non-null value causes the content to be treated as plain + * KML. If null is specified the content type is read from the server or other end point of the URL. When a content + * type is specified, the content type returned by the URL's end point is ignored. You can therefore force the + * content to be treated as KML or KMZ regardless of what a server declares it to be. * @param namespaceAware specifies whether to use a namespace-aware XML parser. true if so, - * false if not. + * false if not. * * @throws IllegalArgumentException if the document source is null. - * @throws IOException if an error occurs while reading the document. + * @throws IOException if an error occurs while reading the document. */ - public KMLRoot(URL docSource, String contentType, boolean namespaceAware) throws IOException - { + public KMLRoot(URL docSource, String contentType, boolean namespaceAware) throws IOException { super(KMLConstants.KML_NAMESPACE); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } URLConnection conn = docSource.openConnection(); - if (contentType == null) + if (contentType == null) { contentType = conn.getContentType(); + } - if (!(KMLConstants.KMZ_MIME_TYPE.equals(contentType) || KMLConstants.KML_MIME_TYPE.equals(contentType))) + if (!(KMLConstants.KMZ_MIME_TYPE.equals(contentType) || KMLConstants.KML_MIME_TYPE.equals(contentType))) { contentType = WWIO.makeMimeTypeForSuffix(WWIO.getSuffix(docSource.getPath())); + } - if (KMLConstants.KMZ_MIME_TYPE.equals(contentType)) + if (KMLConstants.KMZ_MIME_TYPE.equals(contentType)) { this.kmlDoc = new KMZInputStream(conn.getInputStream()); - else + } else { this.kmlDoc = new KMLInputStream(conn.getInputStream(), WWIO.makeURI(docSource)); + } this.initialize(namespaceAware); } @@ -387,14 +376,13 @@ public KMLRoot(URL docSource, String contentType, boolean namespaceAware) throws * gov.nasa.worldwind.ogc.kml.KMLConstants#KML_NAMESPACE}). * * @param namespaceURI the default namespace URI. - * @param docSource the KML source specified via a {@link KMLDoc} instance. A KMLDoc represents KML and KMZ files - * from either files or input streams. + * @param docSource the KML source specified via a {@link KMLDoc} instance. A KMLDoc represents KML and KMZ files + * from either files or input streams. * * @throws IllegalArgumentException if the document source is null. - * @throws java.io.IOException if an I/O error occurs attempting to open the document source. + * @throws java.io.IOException if an I/O error occurs attempting to open the document source. */ - public KMLRoot(String namespaceURI, KMLDoc docSource) throws IOException - { + public KMLRoot(String namespaceURI, KMLDoc docSource) throws IOException { this(namespaceURI, docSource, true); } @@ -402,21 +390,19 @@ public KMLRoot(String namespaceURI, KMLDoc docSource) throws IOException * Create a new KMLRoot with a specific namespace. (The default namespace is defined by {@link * gov.nasa.worldwind.ogc.kml.KMLConstants#KML_NAMESPACE}). * - * @param namespaceURI the default namespace URI. - * @param docSource the KML source specified via a {@link KMLDoc} instance. A KMLDoc represents KML and KMZ - * files from either files or input streams. + * @param namespaceURI the default namespace URI. + * @param docSource the KML source specified via a {@link KMLDoc} instance. A KMLDoc represents KML and KMZ files + * from either files or input streams. * @param namespaceAware specifies whether to use a namespace-aware XML parser. true if so, - * false if not. + * false if not. * * @throws IllegalArgumentException if the document source is null. - * @throws java.io.IOException if an I/O error occurs attempting to open the document source. + * @throws java.io.IOException if an I/O error occurs attempting to open the document source. */ - public KMLRoot(String namespaceURI, KMLDoc docSource, boolean namespaceAware) throws IOException - { + public KMLRoot(String namespaceURI, KMLDoc docSource, boolean namespaceAware) throws IOException { super(namespaceURI); - if (docSource == null) - { + if (docSource == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -431,16 +417,16 @@ public KMLRoot(String namespaceURI, KMLDoc docSource, boolean namespaceAware) th * super.initialize(boolean). * * @param namespaceAware specifies whether to use a namespace-aware XML parser. true if so, - * false if not. + * false if not. * * @throws java.io.IOException if an I/O error occurs attempting to open the document source. */ - protected void initialize(boolean namespaceAware) throws IOException - { + protected void initialize(boolean namespaceAware) throws IOException { this.eventStream = this.getKMLDoc().getKMLStream(); this.eventReader = this.createReader(this.eventStream, namespaceAware); - if (this.eventReader == null) + if (this.eventReader == null) { throw new WWRuntimeException(Logging.getMessage("XML.UnableToOpenDocument", this.getKMLDoc())); + } this.parserContext = this.createParserContext(this.eventReader); } @@ -448,15 +434,14 @@ protected void initialize(boolean namespaceAware) throws IOException /** * Creates the event reader. Called from the constructor. * - * @param docSource the document source to create a reader for. The type can be any of those supported by - * {@link WWXML#openEventReader(Object)}. + * @param docSource the document source to create a reader for. The type can be any of those supported by + * {@link WWXML#openEventReader(Object)}. * @param namespaceAware specifies whether to use a namespace-aware XML parser. true if so, - * false if not. + * false if not. * * @return a new event reader, or null if the source type cannot be determined. */ - protected XMLEventReader createReader(Object docSource, boolean namespaceAware) - { + protected XMLEventReader createReader(Object docSource, boolean namespaceAware) { return WWXML.openEventReader(docSource, namespaceAware); } @@ -468,18 +453,14 @@ protected XMLEventReader createReader(Object docSource, boolean namespaceAware) * * @return a new parser context. */ - protected KMLParserContext createParserContext(XMLEventReader reader) - { - KMLParserContext ctx = (KMLParserContext) - XMLEventParserContextFactory.createParserContext(KMLConstants.KML_MIME_TYPE, this.getNamespaceURI()); + protected KMLParserContext createParserContext(XMLEventReader reader) { + KMLParserContext ctx = (KMLParserContext) XMLEventParserContextFactory.createParserContext(KMLConstants.KML_MIME_TYPE, this.getNamespaceURI()); - if (ctx == null) - { + if (ctx == null) { // Register a parser context for this root's default namespace - String[] mimeTypes = new String[] {KMLConstants.KML_MIME_TYPE, KMLConstants.KMZ_MIME_TYPE}; + String[] mimeTypes = new String[]{KMLConstants.KML_MIME_TYPE, KMLConstants.KMZ_MIME_TYPE}; XMLEventParserContextFactory.addParserContext(mimeTypes, new KMLParserContext(this.getNamespaceURI())); - ctx = (KMLParserContext) - XMLEventParserContextFactory.createParserContext(KMLConstants.KML_MIME_TYPE, this.getNamespaceURI()); + ctx = (KMLParserContext) XMLEventParserContextFactory.createParserContext(KMLConstants.KML_MIME_TYPE, this.getNamespaceURI()); } ctx.setEventReader(reader); @@ -497,18 +478,12 @@ protected KMLParserContext createParserContext(XMLEventReader reader) * * @see gov.nasa.worldwind.util.xml.XMLParserNotification */ - public void setNotificationListener(final XMLParserNotificationListener listener) - { - if (listener == null) - { + public void setNotificationListener(final XMLParserNotificationListener listener) { + if (listener == null) { this.parserContext.setNotificationListener(null); - } - else - { - this.parserContext.setNotificationListener(new XMLParserNotificationListener() - { - public void notify(XMLParserNotification notification) - { + } else { + this.parserContext.setNotificationListener(new XMLParserNotificationListener() { + public void notify(XMLParserNotification notification) { // Set up so the user sees the notification coming from the root rather than the parser notification.setSource(KMLRoot.this); listener.notify(notification); @@ -522,8 +497,7 @@ public void notify(XMLParserNotification notification) * * @return the KML document for this root. */ - public KMLDoc getKMLDoc() - { + public KMLDoc getKMLDoc() { return this.kmlDoc; } @@ -534,13 +508,11 @@ public KMLDoc getKMLDoc() * * @return the element requested, or null if there is no corresponding element in the document. */ - public Object getItemByID(String id) - { + public Object getItemByID(String id) { return id != null ? this.getParserContext().getIdTable().get(id) : null; } - public String getSupportFilePath(String link) throws IOException - { + public String getSupportFilePath(String link) throws IOException { return this.getKMLDoc().getSupportFilePath(link); } @@ -561,30 +533,30 @@ public String getSupportFilePath(String link) throws IOException * @param link the document address in the form address#identifier. * * @return the requested document, the requested or element within a document, or null if the document - * or the element are not found. + * or the element are not found. * * @throws IllegalArgumentException if the link is null. */ - public Object resolveReference(String link) - { - if (link == null) - { + public Object resolveReference(String link) { + if (link == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (absentResourceList.isResourceAbsent(link)) + if (absentResourceList.isResourceAbsent(link)) { return null; + } // Store remote files in the WorldWind cache by default. This provides backward compatibility with applications // depending on resolveReference's behavior prior to the addition of the cacheRemoteFile parameter. Object o = this.resolveReference(link, true); - if (o == null) + if (o == null) { absentResourceList.markResourceAbsent(link); - else + } else { absentResourceList.unmarkResourceAbsent(link); + } return o; } @@ -608,66 +580,64 @@ public Object resolveReference(String link) * location for a retrieved document does not persist between runtime sessions, and subsequent invocations of this * method may not return the same temporary location. * - * @param link the document address in the form address#identifier. + * @param link the document address in the form address#identifier. * @param cacheRemoteFile true to store remote documents in the WorldWind cache, or false - * to store remote documents in a temporary location. Has no effect if the address is a local - * document. + * to store remote documents in a temporary location. Has no effect if the address is a local document. * * @return the requested document, the requested or element within a document, or null if the document - * or the element are not found. + * or the element are not found. * * @throws IllegalArgumentException if the link is null. */ - public Object resolveReference(String link, boolean cacheRemoteFile) - { - if (link == null) - { + public Object resolveReference(String link, boolean cacheRemoteFile) { + if (link == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { String[] linkParts = link.split("#"); String linkBase = linkParts[0]; String linkRef = linkParts.length > 1 ? linkParts[1] : null; // See if it's a reference to an internal element. - if (WWUtil.isEmpty(linkBase) && !WWUtil.isEmpty(linkRef)) + if (WWUtil.isEmpty(linkBase) && !WWUtil.isEmpty(linkRef)) { return this.getItemByID(linkRef); + } // Interpret the path relative to the current document. String path = this.getSupportFilePath(linkBase); - if (path == null) + if (path == null) { path = linkBase; + } // See if it's an already found and parsed KML file. Object o = WorldWind.getSessionCache().get(path); - if (o != null && o instanceof KMLRoot) + if (o != null && o instanceof KMLRoot) { return linkRef != null ? ((KMLRoot) o).getItemByID(linkRef) : o; + } URL url = WWIO.makeURL(path); - if (url == null) - { + if (url == null) { // See if the reference can be resolved to a local file. o = this.resolveLocalReference(path, linkRef); } // If we didn't find a local file, treat it as a remote reference. - if (o == null) + if (o == null) { o = this.resolveRemoteReference(path, linkRef, cacheRemoteFile); + } - if (o != null) + if (o != null) { return o; + } // If the reference was not resolved as a remote reference, look for a local element identified by the // reference string. This handles the case of malformed internal references that omit the # sign at the // beginning of the reference. return this.getItemByID(link); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.UnableToResolveReference", link); Logging.logger().warning(message); } @@ -687,30 +657,29 @@ public Object resolveReference(String link, boolean cacheRemoteFile) * {@code linkBase} cannot be resolved to a local file then null is returned. * * @param linkBase the address of the document containing the requested element. - * @param linkRef the element's identifier. + * @param linkRef the element's identifier. * * @return the requested element, or null if the element is not found. * * @throws IllegalArgumentException if the address is null. */ - public Object resolveLocalReference(String linkBase, String linkRef) - { - if (linkBase == null) - { + public Object resolveLocalReference(String linkBase, String linkRef) { + if (linkBase == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { File file = new File(linkBase); - if (!file.exists()) + if (!file.exists()) { return null; + } // Determine whether the file is a KML or KMZ. If it's not just return the original address. - if (!WWIO.isContentType(file, KMLConstants.KML_MIME_TYPE, KMLConstants.KMZ_MIME_TYPE)) + if (!WWIO.isContentType(file, KMLConstants.KML_MIME_TYPE, KMLConstants.KMZ_MIME_TYPE)) { return linkBase; + } // Attempt to open and parse the KML/Z file, trying both namespace aware and namespace unaware stream // readers if necessary. @@ -721,13 +690,12 @@ public Object resolveLocalReference(String linkBase, String linkRef) WorldWind.getSessionCache().put(linkBase, refRoot); // Now check the newly opened KML/Z file for the referenced item, if a reference was specified. - if (linkRef != null) + if (linkRef != null) { return refRoot.getItemByID(linkRef); - else + } else { return refRoot; - } - catch (Exception e) - { + } + } catch (Exception e) { String message = Logging.getMessage("generic.UnableToResolveReference", linkBase + "/" + linkRef); Logging.logger().warning(message); return null; @@ -746,17 +714,15 @@ public Object resolveLocalReference(String linkBase, String linkRef) * file cache. * * @param linkBase the address of the document containing the requested element. - * @param linkRef the element's identifier. + * @param linkRef the element's identifier. * * @return URL to the requested file, parsed KMLRoot, or KML feature. Returns null if the document is not yet - * available in the FileStore. + * available in the FileStore. * * @throws IllegalArgumentException if the {@code linkBase} is null. */ - public Object resolveRemoteReference(String linkBase, String linkRef) - { - if (linkBase == null) - { + public Object resolveRemoteReference(String linkBase, String linkRef) { + if (linkBase == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -783,77 +749,73 @@ public Object resolveRemoteReference(String linkBase, String linkRef) * for a retrieved file does not persist between runtime sessions, and subsequent invocations of this method may not * return the same temporary location. * - * @param linkBase the address of the document containing the requested element. - * @param linkRef the element's identifier. + * @param linkBase the address of the document containing the requested element. + * @param linkRef the element's identifier. * @param cacheRemoteFile true to store remote files in the WorldWind cache, or false to - * store remote files in a temporary location. Has no effect if the address is a local file. + * store remote files in a temporary location. Has no effect if the address is a local file. * * @return URL to the requested file, parsed KMLRoot, or KML feature. Returns null if the document is not yet - * available in the FileStore. + * available in the FileStore. * * @throws IllegalArgumentException if the {@code linkBase} is null. */ - public Object resolveRemoteReference(String linkBase, String linkRef, boolean cacheRemoteFile) - { - if (linkBase == null) - { + public Object resolveRemoteReference(String linkBase, String linkRef, boolean cacheRemoteFile) { + if (linkBase == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { // See if it's in the cache. If not, requestFile will start another thread to retrieve it and return null. URL url = WorldWind.getDataFileStore().requestFile(linkBase, cacheRemoteFile); - if (url == null) + if (url == null) { return null; + } // It's in the cache. If it's a KML/Z, try to parse it so we can search for the specified reference. If it's // not KML/Z, just return the url for the cached file. String contentType = WorldWind.getDataFileStore().getContentType(linkBase); - if (contentType == null) - { + if (contentType == null) { String suffix = WWIO.getSuffix(linkBase.split(";")[0]); // strip of trailing garbage - if (!WWUtil.isEmpty(suffix)) + if (!WWUtil.isEmpty(suffix)) { contentType = WWIO.makeMimeTypeForSuffix(suffix); + } } - if (!this.canParseContentType(contentType)) + if (!this.canParseContentType(contentType)) { return url; + } // If the file is a KML or KMZ document, attempt to open it. We can't open it as a File with createAndParse // because the KMLRoot that will be created needs to have the remote address in order to resolve any // relative references within it, so we have to implement the namespace-aware/namespace-unaware attempts // here. KMLRoot refRoot; - try - { + try { // Try to parse with a namespace-aware event stream. refRoot = this.parseCachedKMLFile(url, linkBase, contentType, true); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { // Well that didn't work, so try with a namespace-unaware event stream. If this attempt fails this // method logs the exception and returns null. refRoot = this.parseCachedKMLFile(url, linkBase, contentType, false); } // If the file could not be parsed as KML, then just return the URL. - if (refRoot == null) + if (refRoot == null) { return url; + } // Add the parsed file to the session cache so it doesn't have to be parsed again. WorldWind.getSessionCache().put(linkBase, refRoot); // Now check the newly opened KML/Z file for the referenced item, if a reference was specified. - if (linkRef != null) + if (linkRef != null) { return refRoot.getItemByID(linkRef); - else + } else { return refRoot; - } - catch (Exception e) - { + } + } catch (Exception e) { String message = Logging.getMessage("generic.UnableToResolveReference", linkBase + "/" + linkRef); Logging.logger().warning(message); return null; @@ -872,63 +834,57 @@ public Object resolveRemoteReference(String linkBase, String linkRef, boolean ca * for a retrieved file does not persist between runtime sessions, and subsequent invocations of this method may not * return the same temporary location. * - * @param link the address to resolve + * @param link the address to resolve * @param cacheRemoteFile true to store remote files in the WorldWind cache, or false to - * store remote files in a temporary location. Has no effect if the address is a local file. - * @param updateTime the time at which the link was last updated. If a cached file exists for the specified - * resource, the file must have been retrieved after the link update time. Otherwise, the - * cache entry is considered invalid, and the file is deleted and retrieved again. + * store remote files in a temporary location. Has no effect if the address is a local file. + * @param updateTime the time at which the link was last updated. If a cached file exists for the specified + * resource, the file must have been retrieved after the link update time. Otherwise, the cache entry is considered + * invalid, and the file is deleted and retrieved again. * * @return URL to the requested file, parsed KMLRoot, or KML feature. Returns null if the document is not yet - * available in the FileStore. + * available in the FileStore. * * @throws IllegalArgumentException if the {@code link} is null. */ - public Object resolveNetworkLink(String link, boolean cacheRemoteFile, long updateTime) - { - if (link == null) - { + public Object resolveNetworkLink(String link, boolean cacheRemoteFile, long updateTime) { + if (link == null) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = null; - try - { + try { // Interpret the path relative to the current document. String path = this.getSupportFilePath(link); - if (path == null) + if (path == null) { path = link; + } // If the file is eligible for caching, check the session cache to see if it has already been retrieved and // parsed. - if (cacheRemoteFile) - { + if (cacheRemoteFile) { o = WorldWind.getSessionCache().get(path); - if (o instanceof KMLRoot) + if (o instanceof KMLRoot) { return o; + } } URL url = WWIO.makeURL(path); - if (url == null) - { + if (url == null) { // See if the reference can be resolved to a local file. o = this.resolveLocalReference(path, null); } // If we didn't find a local file, treat it as a remote reference. - if (o == null) - { + if (o == null) { url = WorldWind.getDataFileStore().requestFile(path, cacheRemoteFile); - if (url != null) - { + if (url != null) { // Check the file's modification time against the link update time. If the file was last modified // earlier than the link update time then we need to remove the cached file from the file store, // and start a new file retrieval. File file = new File(url.toURI()); - if (file.lastModified() < updateTime) - { + if (file.lastModified() < updateTime) { WorldWind.getDataFileStore().removeFile(link); } } @@ -936,9 +892,7 @@ public Object resolveNetworkLink(String link, boolean cacheRemoteFile, long upda // Call resolveRemoteReference to retrieve and parse the file. o = this.resolveRemoteReference(path, null, cacheRemoteFile); } - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.UnableToResolveReference", link); Logging.logger().warning(message); } @@ -949,29 +903,25 @@ public Object resolveNetworkLink(String link, boolean cacheRemoteFile, long upda /** * Check a cached resource for expiration. If the resource is expired, evict it from the cache. * - * @param link Link that identifies the resource to check for expiration. This is the same link that was - * passed to resolveReference to retrieve the resource. + * @param link Link that identifies the resource to check for expiration. This is the same link that was passed to + * resolveReference to retrieve the resource. * @param expirationTime Time at which the resource expires, in milliseconds since the Epoch. If the current system - * time is greater than the expiration time, then the resource will be evicted. + * time is greater than the expiration time, then the resource will be evicted. */ - public void evictIfExpired(String link, long expirationTime) - { - try - { + public void evictIfExpired(String link, long expirationTime) { + try { URL url = WorldWind.getDataFileStore().requestFile(link, false); - if (url != null) - { + if (url != null) { // Check the file's modification time against the link update time. If the file was last modified // earlier than the link update time then we need to remove the cached file from the file store, // and start a new file retrieval. File file = new File(url.toURI()); - if (file.lastModified() < expirationTime) + if (file.lastModified() < expirationTime) { WorldWind.getDataFileStore().removeFile(link); + } } - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { String message = Logging.getMessage("generic.UnableToResolveReference", link); Logging.logger().warning(message); } @@ -982,28 +932,26 @@ public void evictIfExpired(String link, long expirationTime) * #resolveNetworkLink(String, boolean, long) resolveNetworkLink}. * * @param link the address of the file (the same address as was previously passed to resolveReference). If null, - * zero is returned. + * zero is returned. * * @return The expiration time of the file, in milliseconds since the Epoch (January 1, 1970, 00:00:00 GMT). Zero - * indicates that there is no expiration time. Returns zero if te resource identified by {@code link} has - * not been retrieved. + * indicates that there is no expiration time. Returns zero if te resource identified by {@code link} has not been + * retrieved. */ - public long getExpiration(String link) - { - try - { - if (link == null) + public long getExpiration(String link) { + try { + if (link == null) { return 0; + } // Interpret the path relative to the current document. String path = this.getSupportFilePath(link); - if (path == null) + if (path == null) { path = link; + } return WorldWind.getDataFileStore().getExpirationTime(path); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.UnableToResolveReference", link); Logging.logger().warning(message); } @@ -1019,45 +967,42 @@ public long getExpiration(String link) * * @return {@code true} if {@code mimeType} can be parsed as KML. */ - protected boolean canParseContentType(String mimeType) - { + protected boolean canParseContentType(String mimeType) { return KMLConstants.KML_MIME_TYPE.equals(mimeType) || KMLConstants.KMZ_MIME_TYPE.equals(mimeType) - || "text/plain".equals(mimeType) || "text/xml".equals(mimeType); + || "text/plain".equals(mimeType) || "text/xml".equals(mimeType); } /** * Open and parse the specified file expressed as a file: URL.. * - * @param url the URL of the file to open, expressed as a URL with a scheme of "file". - * @param linkBase the original address of the document if the file is a retrieved and cached file. - * @param contentType the mime type of the file's content, either a KML or KMZ mime type. + * @param url the URL of the file to open, expressed as a URL with a scheme of "file". + * @param linkBase the original address of the document if the file is a retrieved and cached file. + * @param contentType the mime type of the file's content, either a KML or KMZ mime type. * @param namespaceAware specifies whether to use a namespace aware event reader. * * @return A {@code KMLRoot} representing the file's KML contents. * - * @throws IOException if an I/O error occurs during opening and parsing. + * @throws IOException if an I/O error occurs during opening and parsing. * @throws XMLStreamException if a server parsing error is encountered. */ protected KMLRoot parseCachedKMLFile(URL url, String linkBase, String contentType, boolean namespaceAware) - throws IOException, XMLStreamException - { + throws IOException, XMLStreamException { KMLDoc kmlDoc; InputStream refStream = url.openStream(); - if (KMLConstants.KMZ_MIME_TYPE.equals(contentType)) + if (KMLConstants.KMZ_MIME_TYPE.equals(contentType)) { kmlDoc = new KMZInputStream(refStream); - else // Attempt to parse as KML + } else // Attempt to parse as KML + { kmlDoc = new KMLInputStream(refStream, WWIO.makeURI(linkBase)); + } - try - { + try { KMLRoot refRoot = new KMLRoot(kmlDoc, namespaceAware); refRoot = refRoot.parse(); // also closes the URL's stream return refRoot; - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { refStream.close(); // parsing failed, so explicitly close the stream throw e; } @@ -1069,38 +1014,30 @@ protected KMLRoot parseCachedKMLFile(URL url, String linkBase, String contentTyp * * @param args optional arguments to pass to parsers of sub-elements. * - * @return this if parsing is successful, otherwise null. + * @return this if parsing is successful, otherwise null. * - * @throws javax.xml.stream.XMLStreamException - * if an exception occurs while attempting to read the event stream. + * @throws javax.xml.stream.XMLStreamException if an exception occurs while attempting to read the event stream. */ - public KMLRoot parse(Object... args) throws XMLStreamException - { + public KMLRoot parse(Object... args) throws XMLStreamException { KMLParserContext ctx = this.parserContext; - try - { - for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + try { + for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } // Allow a element in any namespace - if (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals("kml")) - { + if (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals("kml")) { super.parse(ctx, event, args); return this; - } - // Allow the document to start without a element. There are many such files around. - else if (event.isStartElement() && ctx.getParser(event) != null) - { + } // Allow the document to start without a element. There are many such files around. + else if (event.isStartElement() && ctx.getParser(event) != null) { this.doParseEventContent(ctx, event, args); return this; } } - } - finally - { + } finally { ctx.getEventReader().close(); this.closeEventStream(); } @@ -1108,23 +1045,20 @@ else if (event.isStartElement() && ctx.getParser(event) != null) return null; } - /** Closes the event stream associated with this context's XML event reader. */ - protected void closeEventStream() - { - try - { + /** + * Closes the event stream associated with this context's XML event reader. + */ + protected void closeEventStream() { + try { this.eventStream.close(); this.eventStream = null; - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionClosingXmlEventReader"); Logging.logger().warning(message); } } - protected XMLEventParserContext getParserContext() - { + protected XMLEventParserContext getParserContext() { return this.parserContext; } @@ -1133,8 +1067,7 @@ protected XMLEventParserContext getParserContext() * * @return the hint attribute, or null if the attribute is not specified. */ - public String getHint() - { + public String getHint() { return (String) this.getField("hint"); } @@ -1143,10 +1076,8 @@ public String getHint() * * @return the element if it is specified in the document, otherwise null. */ - public KMLNetworkLinkControl getNetworkLinkControl() - { - if (!linkControlFetched) - { + public KMLNetworkLinkControl getNetworkLinkControl() { + if (!linkControlFetched) { this.networkLinkControl = (KMLNetworkLinkControl) this.getField("NetworkLinkControl"); this.linkControlFetched = true; } @@ -1159,10 +1090,8 @@ public KMLNetworkLinkControl getNetworkLinkControl() * * @return the feature element if it is specified in the document, otherwise null. */ - public KMLAbstractFeature getFeature() - { - if (!this.featureFetched) - { + public KMLAbstractFeature getFeature() { + if (!this.featureFetched) { this.feature = findFeature(); this.featureFetched = true; } @@ -1175,15 +1104,15 @@ public KMLAbstractFeature getFeature() * * @return the feature element, or null if none was found. */ - protected KMLAbstractFeature findFeature() - { - if (!this.hasFields()) + protected KMLAbstractFeature findFeature() { + if (!this.hasFields()) { return null; + } - for (Map.Entry entry : this.getFields().getEntries()) - { - if (entry.getValue() instanceof KMLAbstractFeature) + for (Map.Entry entry : this.getFields().getEntries()) { + if (entry.getValue() instanceof KMLAbstractFeature) { return (KMLAbstractFeature) entry.getValue(); + } } return null; @@ -1196,8 +1125,7 @@ protected KMLAbstractFeature findFeature() * * @see #setDetailHint(double) */ - public double getDetailHint() - { + public double getDetailHint() { return this.detailHint; } @@ -1213,36 +1141,35 @@ public double getDetailHint() * ignored. * * @param detailHint the degree to modify the default relationship of KML scene resolution to screen resolution as - * viewing distance changes. Values greater than 0 increase the resolution. Values less than 0 - * decrease the resolution. The default value is 0. + * viewing distance changes. Values greater than 0 increase the resolution. Values less than 0 decrease the + * resolution. The default value is 0. */ - public void setDetailHint(double detailHint) - { + public void setDetailHint(double detailHint) { this.detailHint = detailHint; } - /** Request any scene containing this KML document be repainted. */ - public void requestRedraw() - { + /** + * Request any scene containing this KML document be repainted. + */ + public void requestRedraw() { this.firePropertyChange(AVKey.REPAINT, null, null); } - public void preRender(KMLTraversalContext tc, DrawContext dc) - { - if (this.getFeature() != null) + public void preRender(KMLTraversalContext tc, DrawContext dc) { + if (this.getFeature() != null) { this.getFeature().preRender(tc, dc); + } } - public void render(KMLTraversalContext tc, DrawContext dc) - { - if (this.getFeature() != null) + public void render(KMLTraversalContext tc, DrawContext dc) { + if (this.getFeature() != null) { this.getFeature().render(tc, dc); + } } //********************************************************************** //********************* Property change support ************************ //********************************************************************** - /** * {@inheritDoc} *

          @@ -1251,10 +1178,10 @@ public void render(KMLTraversalContext tc, DrawContext dc) * @param msg The message that was received. */ @Override - public void onMessage(Message msg) - { - if (this.getFeature() != null) + public void onMessage(Message msg) { + if (this.getFeature() != null) { this.getFeature().onMessage(msg); + } } /** @@ -1265,10 +1192,8 @@ public void onMessage(Message msg) * @throws IllegalArgumentException if listener is null * @see java.beans.PropertyChangeSupport */ - public void addPropertyChangeListener(java.beans.PropertyChangeListener listener) - { - if (listener == null) - { + public void addPropertyChangeListener(java.beans.PropertyChangeListener listener) { + if (listener == null) { String msg = Logging.getMessage("nullValue.ListenerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1284,10 +1209,8 @@ public void addPropertyChangeListener(java.beans.PropertyChangeListener listener * @throws IllegalArgumentException if listener is null. * @see java.beans.PropertyChangeSupport */ - public void removePropertyChangeListener(java.beans.PropertyChangeListener listener) - { - if (listener == null) - { + public void removePropertyChangeListener(java.beans.PropertyChangeListener listener) { + if (listener == null) { String msg = Logging.getMessage("nullValue.ListenerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1300,10 +1223,8 @@ public void removePropertyChangeListener(java.beans.PropertyChangeListener liste * * @param propertyChangeEvent Event to fire. */ - public void firePropertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent == null) - { + public void firePropertyChange(java.beans.PropertyChangeEvent propertyChangeEvent) { + if (propertyChangeEvent == null) { String msg = Logging.getMessage("nullValue.PropertyChangeEventIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1315,13 +1236,11 @@ public void firePropertyChange(java.beans.PropertyChangeEvent propertyChangeEven * Fire a property change event. * * @param propertyName Name of the property change changed. - * @param oldValue The previous value of the property. - * @param newValue The new value of the property. + * @param oldValue The previous value of the property. + * @param newValue The new value of the property. */ - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { - if (propertyName == null) - { + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + if (propertyName == null) { String msg = Logging.getMessage("nullValue.PropertyNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1335,10 +1254,10 @@ public void firePropertyChange(String propertyName, Object oldValue, Object newV * * @return PropertyChangeSupport for this KML object. */ - protected synchronized PropertyChangeSupport getChangeSupport() - { - if (this.propertyChangeSupport == null) + protected synchronized PropertyChangeSupport getChangeSupport() { + if (this.propertyChangeSupport == null) { this.propertyChangeSupport = new PropertyChangeSupport(this); + } return this.propertyChangeSupport; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLScale.java b/src/gov/nasa/worldwind/ogc/kml/KMLScale.java index deb703f12d..4d10ccd9f7 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLScale.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLScale.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,30 +11,26 @@ * @author tag * @version $Id: KMLScale.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLScale extends KMLAbstractObject -{ +public class KMLScale extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLScale(String namespaceURI) - { + public KMLScale(String namespaceURI) { super(namespaceURI); } - public Double getX() - { + public Double getX() { return (Double) this.getField("x"); } - public Double getY() - { + public Double getY() { return (Double) this.getField("y"); } - public Double getZ() - { + public Double getZ() { return (Double) this.getField("z"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLSchema.java b/src/gov/nasa/worldwind/ogc/kml/KMLSchema.java index d80edffb3b..632fa9596b 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLSchema.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLSchema.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: KMLSchema.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLSchema extends AbstractXMLEventParser -{ +public class KMLSchema extends AbstractXMLEventParser { + protected List simpleFields = new ArrayList(); /** @@ -27,38 +26,33 @@ public class KMLSchema extends AbstractXMLEventParser * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLSchema(String namespaceURI) - { + public KMLSchema(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLSimpleField) + throws XMLStreamException { + if (o instanceof KMLSimpleField) { this.addSimpleField((KMLSimpleField) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public String getId() - { + public String getId() { return (String) this.getField("id"); } - protected void addSimpleField(KMLSimpleField o) - { + protected void addSimpleField(KMLSimpleField o) { this.simpleFields.add(o); } - public List getSimpleFields() - { + public List getSimpleFields() { return this.simpleFields; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLSchemaData.java b/src/gov/nasa/worldwind/ogc/kml/KMLSchemaData.java index b98f6d839b..ef188b1990 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLSchemaData.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLSchemaData.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -18,8 +17,8 @@ * @author tag * @version $Id: KMLSchemaData.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLSchemaData extends KMLAbstractObject -{ +public class KMLSchemaData extends KMLAbstractObject { + protected List simpleData = new ArrayList(); /** @@ -27,31 +26,27 @@ public class KMLSchemaData extends KMLAbstractObject * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLSchemaData(String namespaceURI) - { + public KMLSchemaData(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLSimpleData) + throws XMLStreamException { + if (o instanceof KMLSimpleData) { this.addSimpleData((KMLSimpleData) o); + } } - public String getSchemaUrl() - { + public String getSchemaUrl() { return (String) this.getField("schemaUrl"); } - protected void addSimpleData(KMLSimpleData o) - { + protected void addSimpleData(KMLSimpleData o) { this.simpleData.add(o); } - public List getSimpleData() - { + public List getSimpleData() { return this.simpleData; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLScreenOverlay.java b/src/gov/nasa/worldwind/ogc/kml/KMLScreenOverlay.java index 55816729f8..2e751b28fe 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLScreenOverlay.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLScreenOverlay.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -17,8 +16,8 @@ * @author tag * @version $Id: KMLScreenOverlay.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLScreenOverlay extends KMLAbstractOverlay -{ +public class KMLScreenOverlay extends KMLAbstractOverlay { + protected KMLRenderable renderable; /** @@ -26,33 +25,27 @@ public class KMLScreenOverlay extends KMLAbstractOverlay * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLScreenOverlay(String namespaceURI) - { + public KMLScreenOverlay(String namespaceURI) { super(namespaceURI); } - public KMLVec2 getOverlayXY() - { + public KMLVec2 getOverlayXY() { return (KMLVec2) this.getField("overlayXY"); } - public KMLVec2 getScreenXY() - { + public KMLVec2 getScreenXY() { return (KMLVec2) this.getField("screenXY"); } - public KMLVec2 getRotationXY() - { + public KMLVec2 getRotationXY() { return (KMLVec2) this.getField("rotationXY"); } - public KMLVec2 getSize() - { + public KMLVec2 getSize() { return (KMLVec2) this.getField("size"); } - public Double getRotation() - { + public Double getRotation() { return (Double) this.getField("rotation"); } @@ -64,14 +57,13 @@ public Double getRotation() * @param dc the current draw context. */ @Override - protected void doPreRender(KMLTraversalContext tc, DrawContext dc) - { - if (this.getRenderable() == null) + protected void doPreRender(KMLTraversalContext tc, DrawContext dc) { + if (this.getRenderable() == null) { this.initializeRenderable(tc); + } KMLRenderable r = this.getRenderable(); - if (r != null) - { + if (r != null) { r.preRender(tc, dc); } } @@ -83,14 +75,12 @@ protected void doPreRender(KMLTraversalContext tc, DrawContext dc) * @param dc the current draw context. */ @Override - protected void doRender(KMLTraversalContext tc, DrawContext dc) - { + protected void doRender(KMLTraversalContext tc, DrawContext dc) { // We've already initialized the screen image renderable during the preRender pass. Render the screen image // without any further preparation. KMLRenderable r = this.getRenderable(); - if (r != null) - { + if (r != null) { r.render(tc, dc); } @@ -103,8 +93,7 @@ protected void doRender(KMLTraversalContext tc, DrawContext dc) * * @param tc the current KML traversal context. */ - protected void initializeRenderable(KMLTraversalContext tc) - { + protected void initializeRenderable(KMLTraversalContext tc) { renderable = new KMLScreenImageImpl(tc, this); } @@ -114,16 +103,13 @@ protected void initializeRenderable(KMLTraversalContext tc) * * @return The renderable, or null if the renderable has not been created yet. */ - public KMLRenderable getRenderable() - { + public KMLRenderable getRenderable() { return renderable; } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLScreenOverlay)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLScreenOverlay)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -135,10 +121,10 @@ public void applyChange(KMLAbstractObject sourceValues) } @Override - public void onChange(Message msg) - { - if (KMLAbstractObject.MSG_LINK_CHANGED.equals(msg.getName())) + public void onChange(Message msg) { + if (KMLAbstractObject.MSG_LINK_CHANGED.equals(msg.getName())) { this.renderable = null; + } super.onChange(msg); } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLSimpleData.java b/src/gov/nasa/worldwind/ogc/kml/KMLSimpleData.java index 98067c0aad..8b8597d8d8 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLSimpleData.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLSimpleData.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -14,20 +13,18 @@ * @author tag * @version $Id: KMLSimpleData.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLSimpleData extends AbstractXMLEventParser -{ +public class KMLSimpleData extends AbstractXMLEventParser { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLSimpleData(String namespaceURI) - { + public KMLSimpleData(String namespaceURI) { super(namespaceURI); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLSimpleField.java b/src/gov/nasa/worldwind/ogc/kml/KMLSimpleField.java index c8a3ff3b76..8aa2320e4c 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLSimpleField.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLSimpleField.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -14,30 +13,26 @@ * @author tag * @version $Id: KMLSimpleField.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLSimpleField extends AbstractXMLEventParser -{ +public class KMLSimpleField extends AbstractXMLEventParser { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLSimpleField(String namespaceURI) - { + public KMLSimpleField(String namespaceURI) { super(namespaceURI); } - public String getType() - { + public String getType() { return (String) this.getField("type"); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public String getDisplayName() - { + public String getDisplayName() { return (String) this.getField("displayName"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLSnippet.java b/src/gov/nasa/worldwind/ogc/kml/KMLSnippet.java index fad12ef5b0..fd178319e7 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLSnippet.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLSnippet.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -18,35 +17,32 @@ * @author tag * @version $Id: KMLSnippet.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLSnippet extends KMLAbstractObject -{ +public class KMLSnippet extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLSnippet(String namespaceURI) - { + public KMLSnippet(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventAttribute(Attribute attr, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if ("maxLines".equals(attr.getName().getLocalPart())) + throws XMLStreamException { + if ("maxLines".equals(attr.getName().getLocalPart())) { this.setMaxLines(WWUtil.makeInteger(attr.getValue())); - else + } else { super.doAddEventAttribute(attr, ctx, event, args); + } } - public Integer getMaxLines() - { + public Integer getMaxLines() { return (Integer) this.getField("maxLines"); } - public void setMaxLines(Integer o) - { + public void setMaxLines(Integer o) { this.setField("maxLines", o); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLStyle.java b/src/gov/nasa/worldwind/ogc/kml/KMLStyle.java index 2f2f182a74..483e08e210 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLStyle.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -17,45 +16,38 @@ * @author tag * @version $Id: KMLStyle.java 1528 2013-07-31 01:00:32Z pabercrombie $ */ -public class KMLStyle extends KMLAbstractStyleSelector -{ +public class KMLStyle extends KMLAbstractStyleSelector { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLStyle(String namespaceURI) - { + public KMLStyle(String namespaceURI) { super(namespaceURI); } - public KMLIconStyle getIconStyle() - { + public KMLIconStyle getIconStyle() { return (KMLIconStyle) this.getField(KMLConstants.ICON_STYLE_FIELD); } - public KMLLabelStyle getLabelStyle() - { + public KMLLabelStyle getLabelStyle() { return (KMLLabelStyle) this.getField(KMLConstants.LABEL_STYLE_FIELD); } - public KMLLineStyle getLineStyle() - { + public KMLLineStyle getLineStyle() { return (KMLLineStyle) this.getField(KMLConstants.LINE_STYLE_FIELD); } - public KMLPolyStyle getPolyStyle() - { + public KMLPolyStyle getPolyStyle() { return (KMLPolyStyle) this.getField(KMLConstants.POLY_STYLE_FIELD); } - public KMLBalloonStyle getBaloonStyle() - { + public KMLBalloonStyle getBaloonStyle() { return (KMLBalloonStyle) this.getField(KMLConstants.BALOON_STYLE_FIELD); } - public KMLListStyle getListStyle() - { + public KMLListStyle getListStyle() { return (KMLListStyle) this.getField(KMLConstants.LIST_STYLE_FIELD); } @@ -65,20 +57,15 @@ public KMLListStyle getListStyle() * color to the {@code LabelStyle}, creating a new {@code LabelStyle} if necessary. */ @Override - public void setField(String keyName, Object value) - { - if ("labelColor".equals(keyName)) - { + public void setField(String keyName, Object value) { + if ("labelColor".equals(keyName)) { KMLLabelStyle labelStyle = this.getLabelStyle(); - if (labelStyle == null) - { + if (labelStyle == null) { labelStyle = new KMLLabelStyle(this.getNamespaceURI()); this.setField(KMLConstants.LABEL_STYLE_FIELD, labelStyle); } labelStyle.setField("color", value); - } - else - { + } else { super.setField(keyName, value); } } @@ -92,23 +79,20 @@ public void setField(String keyName, Object value) * * @throws IllegalArgumentException if the sub-style parameter is null. */ - public KMLAbstractSubStyle mergeSubStyle(KMLAbstractSubStyle subStyle) - { - if (subStyle == null) - { + public KMLAbstractSubStyle mergeSubStyle(KMLAbstractSubStyle subStyle) { + if (subStyle == null) { String message = Logging.getMessage("nullValue.SymbolIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.hasFields()) + if (!this.hasFields()) { return subStyle; + } Class subStyleClass = subStyle.getClass(); - for (Map.Entry field : this.getFields().getEntries()) - { - if (field.getValue() != null && field.getValue().getClass().equals(subStyleClass)) - { + for (Map.Entry field : this.getFields().getEntries()) { + if (field.getValue() != null && field.getValue().getClass().equals(subStyleClass)) { this.overrideFields(subStyle, (KMLAbstractSubStyle) field.getValue()); } } @@ -117,10 +101,8 @@ public KMLAbstractSubStyle mergeSubStyle(KMLAbstractSubStyle subStyle) } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLStyle)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLStyle)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLStyleMap.java b/src/gov/nasa/worldwind/ogc/kml/KMLStyleMap.java index 3cbdb2563f..ec6105105e 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLStyleMap.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLStyleMap.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -20,8 +19,8 @@ * @author tag * @version $Id: KMLStyleMap.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLStyleMap extends KMLAbstractStyleSelector -{ +public class KMLStyleMap extends KMLAbstractStyleSelector { + protected List pairs = new ArrayList(); /** @@ -29,28 +28,25 @@ public class KMLStyleMap extends KMLAbstractStyleSelector * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLStyleMap(String namespaceURI) - { + public KMLStyleMap(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLPair) + throws XMLStreamException { + if (o instanceof KMLPair) { this.addPair((KMLPair) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public List getPairs() - { + public List getPairs() { return this.pairs; } - protected void addPair(KMLPair pair) - { + protected void addPair(KMLPair pair) { this.pairs.add(pair); } @@ -58,19 +54,19 @@ protected void addPair(KMLPair pair) * Returns a specified style from the style map. * * @param styleState the style key, either {@link KMLConstants#NORMAL} or {@link KMLConstants#HIGHLIGHT}. If null, - * {@link KMLConstants#NORMAL} is used. + * {@link KMLConstants#NORMAL} is used. * * @return the requested style, or null if it does not exist in the map. */ - public KMLAbstractStyleSelector getStyleFromMap(String styleState) - { - if (styleState == null) + public KMLAbstractStyleSelector getStyleFromMap(String styleState) { + if (styleState == null) { styleState = KMLConstants.NORMAL; + } - for (KMLPair pair : this.pairs) - { - if (pair.getKey().equals(styleState)) + for (KMLPair pair : this.pairs) { + if (pair.getKey().equals(styleState)) { return pair.getStyleSelector(); + } } return null; @@ -80,19 +76,19 @@ public KMLAbstractStyleSelector getStyleFromMap(String styleState) * Returns a specified style URL from the style map. * * @param styleState the style key, either {@link KMLConstants#NORMAL} or {@link KMLConstants#HIGHLIGHT}. If null, - * {@link KMLConstants#NORMAL} is used. + * {@link KMLConstants#NORMAL} is used. * * @return the requested style URL, or null if it does not exist in the map. */ - public KMLStyleUrl getStyleUrlFromMap(String styleState) - { - if (styleState == null) + public KMLStyleUrl getStyleUrlFromMap(String styleState) { + if (styleState == null) { styleState = KMLConstants.NORMAL; + } - for (KMLPair pair : this.pairs) - { - if (pair.getKey().equals(styleState)) + for (KMLPair pair : this.pairs) { + if (pair.getKey().equals(styleState)) { return pair.getStyleUrl(); + } } return null; @@ -107,32 +103,28 @@ public KMLStyleUrl getStyleUrlFromMap(String styleState) * sub-style is marked with the value {@link gov.nasa.worldwind.avlist.AVKey#UNRESOLVED}. * * @param styleState the style mode, either \"normal\" or \"highlight\". - * @param subStyle an instance of the {@link gov.nasa.worldwind.ogc.kml.KMLAbstractSubStyle} class desired, such - * as {@link gov.nasa.worldwind.ogc.kml.KMLIconStyle}. The effective style values are accumulated - * and merged into this instance. The instance should not be one from within the KML document - * because its values may be overridden and augmented. The instance specified is the return value - * of this method. + * @param subStyle an instance of the {@link gov.nasa.worldwind.ogc.kml.KMLAbstractSubStyle} class desired, such as + * {@link gov.nasa.worldwind.ogc.kml.KMLIconStyle}. The effective style values are accumulated and merged into this + * instance. The instance should not be one from within the KML document because its values may be overridden and + * augmented. The instance specified is the return value of this method. * * @return the sub-style values for the specified type and state. The reference returned is the same one passed in - * as the subStyle argument. + * as the subStyle argument. */ - public KMLAbstractSubStyle mergeSubStyles(KMLAbstractSubStyle subStyle, String styleState) - { + public KMLAbstractSubStyle mergeSubStyles(KMLAbstractSubStyle subStyle, String styleState) { KMLStyleUrl styleUrl = this.getStyleUrlFromMap(styleState); KMLAbstractStyleSelector selector = this.getStyleFromMap(styleState); - if (selector == null && styleUrl == null) + if (selector == null && styleUrl == null) { return subStyle; - else + } else { subStyle.setField(KMLConstants.STYLE_STATE, styleState); // identify which style state it is - + } return KMLAbstractStyleSelector.mergeSubStyles(styleUrl, selector, styleState, subStyle); } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLStyleMap)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLStyleMap)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -142,34 +134,30 @@ public void applyChange(KMLAbstractObject sourceValues) KMLStyleMap sourceMap = (KMLStyleMap) sourceValues; - if (sourceMap.getPairs() != null && sourceMap.getPairs().size() > 0) + if (sourceMap.getPairs() != null && sourceMap.getPairs().size() > 0) { this.pairs = sourceMap.getPairs(); + } this.onChange(new Message(KMLAbstractObject.MSG_STYLE_CHANGED, this)); } /** - * Merge a list of incoming pairs with the current list. If an incoming pair has the same ID as an - * existing one, replace the existing one, otherwise just add the incoming one. + * Merge a list of incoming pairs with the current list. If an incoming pair has the same ID as an existing one, + * replace the existing one, otherwise just add the incoming one. * * @param sourceMap the incoming pairs. */ - protected void mergePairs(KMLStyleMap sourceMap) - { + protected void mergePairs(KMLStyleMap sourceMap) { // Make a copy of the existing list so we can modify it as we traverse the copy. List pairsCopy = new ArrayList(this.getPairs().size()); Collections.copy(pairsCopy, this.getPairs()); - for (KMLPair sourcePair : sourceMap.getPairs()) - { + for (KMLPair sourcePair : sourceMap.getPairs()) { String id = sourcePair.getId(); - if (!WWUtil.isEmpty(id)) - { - for (KMLPair existingPair : pairsCopy) - { + if (!WWUtil.isEmpty(id)) { + for (KMLPair existingPair : pairsCopy) { String currentId = existingPair.getId(); - if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) - { + if (!WWUtil.isEmpty(currentId) && currentId.equals(id)) { this.getPairs().remove(existingPair); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLStyleUrl.java b/src/gov/nasa/worldwind/ogc/kml/KMLStyleUrl.java index fdfd540fa1..e7569b54c6 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLStyleUrl.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLStyleUrl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.event.Message; @@ -13,15 +12,14 @@ * @author tag * @version $Id: KMLStyleUrl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLStyleUrl extends KMLAbstractObject -{ +public class KMLStyleUrl extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLStyleUrl(String namespaceURI) - { + public KMLStyleUrl(String namespaceURI) { super(namespaceURI); } @@ -33,20 +31,18 @@ public KMLStyleUrl(String namespaceURI) * * @return the style or style map referred to by the style URL. */ - public KMLAbstractStyleSelector resolveStyleUrl() - { - if (WWUtil.isEmpty(this.getCharacters())) + public KMLAbstractStyleSelector resolveStyleUrl() { + if (WWUtil.isEmpty(this.getCharacters())) { return null; + } Object o = this.getRoot().resolveReference(this.getCharacters()); return o instanceof KMLAbstractStyleSelector ? (KMLAbstractStyleSelector) o : null; } @Override - public void applyChange(KMLAbstractObject sourceValues) - { - if (!(sourceValues instanceof KMLStyleUrl)) - { + public void applyChange(KMLAbstractObject sourceValues) { + if (!(sourceValues instanceof KMLStyleUrl)) { String message = Logging.getMessage("KML.InvalidElementType", sourceValues.getClass().getName()); Logging.logger().warning(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLTimeSpan.java b/src/gov/nasa/worldwind/ogc/kml/KMLTimeSpan.java index 9886c471e9..4a30f38722 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLTimeSpan.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLTimeSpan.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,25 +11,22 @@ * @author tag * @version $Id: KMLTimeSpan.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLTimeSpan extends KMLAbstractTimePrimitive -{ +public class KMLTimeSpan extends KMLAbstractTimePrimitive { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLTimeSpan(String namespaceURI) - { + public KMLTimeSpan(String namespaceURI) { super(namespaceURI); } - public String getBegin() - { + public String getBegin() { return (String) this.getField("begin"); } - public String getEnd() - { + public String getEnd() { return (String) this.getField("end"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLTimeStamp.java b/src/gov/nasa/worldwind/ogc/kml/KMLTimeStamp.java index 614783cbf0..455ab09b5d 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLTimeStamp.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLTimeStamp.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,20 +11,18 @@ * @author tag * @version $Id: KMLTimeStamp.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLTimeStamp extends KMLAbstractTimePrimitive -{ +public class KMLTimeStamp extends KMLAbstractTimePrimitive { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLTimeStamp(String namespaceURI) - { + public KMLTimeStamp(String namespaceURI) { super(namespaceURI); } - public String getWhen() - { + public String getWhen() { return (String) this.getField("when"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLUpdate.java b/src/gov/nasa/worldwind/ogc/kml/KMLUpdate.java index bf76604899..a5c4d923bf 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLUpdate.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLUpdate.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.avlist.AVKey; @@ -20,8 +19,8 @@ * @author tag * @version $Id: KMLUpdate.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLUpdate extends KMLAbstractObject -{ +public class KMLUpdate extends KMLAbstractObject { + protected List operations; // operations are performed in the order specified in the KML file protected boolean updatesApplied; @@ -30,78 +29,76 @@ public class KMLUpdate extends KMLAbstractObject * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLUpdate(String namespaceURI) - { + public KMLUpdate(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLChange) + throws XMLStreamException { + if (o instanceof KMLChange) { this.addChange((KMLChange) o); - else if (o instanceof KMLCreate) + } else if (o instanceof KMLCreate) { this.addCreate((KMLCreate) o); - else if (o instanceof KMLDelete) + } else if (o instanceof KMLDelete) { this.addDelete((KMLDelete) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public String getTargetHref() - { + public String getTargetHref() { return (String) this.getField("targetHref"); } - protected void addChange(KMLChange o) - { - if (this.operations == null) + protected void addChange(KMLChange o) { + if (this.operations == null) { this.operations = new ArrayList(); + } this.operations.add(o); } - protected void addCreate(KMLCreate o) - { - if (this.operations == null) + protected void addCreate(KMLCreate o) { + if (this.operations == null) { this.operations = new ArrayList(); + } this.operations.add(o); } - protected void addDelete(KMLDelete o) - { - if (this.operations == null) + protected void addDelete(KMLDelete o) { + if (this.operations == null) { this.operations = new ArrayList(); + } this.operations.add(o); } - public boolean isUpdatesApplied() - { + public boolean isUpdatesApplied() { return updatesApplied; } - public void applyOperations() - { + public void applyOperations() { this.updatesApplied = true; - if (WWUtil.isEmpty(this.getTargetHref())) + if (WWUtil.isEmpty(this.getTargetHref())) { return; + } - if (this.operations == null || this.operations.size() == 0) + if (this.operations == null || this.operations.size() == 0) { return; + } Object o = this.getRoot().resolveReference(this.getTargetHref()); - if (o == null || !(o instanceof KMLRoot)) + if (o == null || !(o instanceof KMLRoot)) { return; + } KMLRoot targetRoot = (KMLRoot) o; - for (KMLUpdateOperation operation : this.operations) - { + for (KMLUpdateOperation operation : this.operations) { operation.applyOperation(targetRoot); } targetRoot.firePropertyChange(AVKey.UPDATED, null, this); diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLUpdateOperation.java b/src/gov/nasa/worldwind/ogc/kml/KMLUpdateOperation.java index 57189a882c..b9db61952e 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLUpdateOperation.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLUpdateOperation.java @@ -3,14 +3,13 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** * @author tag * @version $Id: KMLUpdateOperation.java 390 2012-02-17 01:09:57Z tgaskins $ */ -public interface KMLUpdateOperation -{ +public interface KMLUpdateOperation { + public void applyOperation(KMLRoot operationsRoot); -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLVec2.java b/src/gov/nasa/worldwind/ogc/kml/KMLVec2.java index e30ca7304c..5b4644a15a 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLVec2.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLVec2.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; import gov.nasa.worldwind.util.WWUtil; @@ -18,8 +17,8 @@ * @author tag * @version $Id: KMLVec2.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLVec2 extends KMLAbstractObject -{ +public class KMLVec2 extends KMLAbstractObject { + protected Double x; protected Double y; @@ -28,50 +27,43 @@ public class KMLVec2 extends KMLAbstractObject * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLVec2(String namespaceURI) - { + public KMLVec2(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventAttribute(Attribute attr, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if ("x".equals(attr.getName().getLocalPart())) + throws XMLStreamException { + if ("x".equals(attr.getName().getLocalPart())) { this.setX(WWUtil.makeDouble(attr.getValue())); - else if ("y".equals(attr.getName().getLocalPart())) + } else if ("y".equals(attr.getName().getLocalPart())) { this.setY(WWUtil.makeDouble(attr.getValue())); - else + } else { super.doAddEventAttribute(attr, ctx, event, args); + } } - protected void setX(Double o) - { + protected void setX(Double o) { this.x = o; } - public Double getX() - { + public Double getX() { return this.x; } - protected void setY(Double o) - { + protected void setY(Double o) { this.y = o; } - public Double getY() - { + public Double getY() { return this.y; } - public String getXunits() - { + public String getXunits() { return (String) this.getField("xunits"); } - public String getYunits() - { + public String getYunits() { return (String) this.getField("yunits"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/KMLViewVolume.java b/src/gov/nasa/worldwind/ogc/kml/KMLViewVolume.java index e57470f4b7..8ab560b40c 100644 --- a/src/gov/nasa/worldwind/ogc/kml/KMLViewVolume.java +++ b/src/gov/nasa/worldwind/ogc/kml/KMLViewVolume.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml; /** @@ -12,40 +11,34 @@ * @author tag * @version $Id: KMLViewVolume.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLViewVolume extends KMLAbstractObject -{ +public class KMLViewVolume extends KMLAbstractObject { + /** * Construct an instance. * * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification. */ - public KMLViewVolume(String namespaceURI) - { + public KMLViewVolume(String namespaceURI) { super(namespaceURI); } - public Double getNear() - { + public Double getNear() { return (Double) this.getField("near"); } - public Double getLeftFov() - { + public Double getLeftFov() { return (Double) this.getField("leftFov"); } - public Double getRightFov() - { + public Double getRightFov() { return (Double) this.getField("rightFov"); } - public Double getTopFov() - { + public Double getTopFov() { return (Double) this.getField("topFov"); } - public Double getBottomFov() - { + public Double getBottomFov() { return (Double) this.getField("bottomFov"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXAbstractTourPrimitive.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXAbstractTourPrimitive.java index b5ef576d3a..50eb41a51a 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXAbstractTourPrimitive.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXAbstractTourPrimitive.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; import gov.nasa.worldwind.ogc.kml.KMLAbstractObject; @@ -12,10 +11,9 @@ * @author tag * @version $Id: GXAbstractTourPrimitive.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXAbstractTourPrimitive extends KMLAbstractObject -{ - public GXAbstractTourPrimitive(String namespaceURI) - { +public class GXAbstractTourPrimitive extends KMLAbstractObject { + + public GXAbstractTourPrimitive(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXAnimatedUpdate.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXAnimatedUpdate.java index 68e0895d64..d7b55c18f9 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXAnimatedUpdate.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXAnimatedUpdate.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; import gov.nasa.worldwind.ogc.kml.KMLUpdate; @@ -12,20 +11,17 @@ * @author tag * @version $Id: GXAnimatedUpdate.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXAnimatedUpdate extends GXAbstractTourPrimitive -{ - public GXAnimatedUpdate(String namespaceURI) - { +public class GXAnimatedUpdate extends GXAbstractTourPrimitive { + + public GXAnimatedUpdate(String namespaceURI) { super(namespaceURI); } - public Double getDuration() - { + public Double getDuration() { return (Double) this.getField("duration"); } - public KMLUpdate getUpdate() - { + public KMLUpdate getUpdate() { return (KMLUpdate) this.getField("Update"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXConstants.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXConstants.java index 5e7284b4bf..cfb838c065 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXConstants.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXConstants.java @@ -3,14 +3,13 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; /** * @author tag * @version $Id: GXConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface GXConstants -{ +public interface GXConstants { + final public String GX_NAMESPACE = "http://www.google.com/kml/ext/2.2"; } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXFlyTo.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXFlyTo.java index 2f64e14b4a..22d025ccbc 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXFlyTo.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXFlyTo.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -16,40 +15,35 @@ * @author tag * @version $Id: GXFlyTo.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXFlyTo extends GXAbstractTourPrimitive -{ - public GXFlyTo(String namespaceURI) - { +public class GXFlyTo extends GXAbstractTourPrimitive { + + public GXFlyTo(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof KMLAbstractView) + throws XMLStreamException { + if (o instanceof KMLAbstractView) { this.setView((KMLAbstractView) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public Double getDuration() - { + public Double getDuration() { return (Double) this.getField("duration"); } - public String getFlyToMode() - { + public String getFlyToMode() { return (String) this.getField("flyToMode"); } - public KMLAbstractView getView() - { + public KMLAbstractView getView() { return (KMLAbstractView) this.getField("AbstractView"); } - protected void setView(KMLAbstractView o) - { + protected void setView(KMLAbstractView o) { this.setField("AbstractView", o); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXLatLongQuad.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXLatLongQuad.java index 2d3b87484f..95bd56919b 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXLatLongQuad.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXLatLongQuad.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; import gov.nasa.worldwind.geom.Position; @@ -13,15 +12,13 @@ * @author tag * @version $Id: GXLatLongQuad.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXLatLongQuad extends KMLAbstractObject -{ - public GXLatLongQuad(String namespaceURI) - { +public class GXLatLongQuad extends KMLAbstractObject { + + public GXLatLongQuad(String namespaceURI) { super(namespaceURI); } - public Position.PositionList getCoordinates() - { + public Position.PositionList getCoordinates() { return (Position.PositionList) this.getField("coordinates"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXParserContext.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXParserContext.java index 5920f97580..94e7c10c5b 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXParserContext.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXParserContext.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; import gov.nasa.worldwind.ogc.kml.*; @@ -17,28 +16,21 @@ * @author tag * @version $Id: GXParserContext.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXParserContext extends BasicXMLEventParserContext -{ - protected static final String[] StringFields = new String[] - { - "altitudeMode", - "description", - "flyToMode", - "playMode", - }; +public class GXParserContext extends BasicXMLEventParserContext { + + protected static final String[] StringFields = new String[]{ + "altitudeMode", + "description", + "flyToMode", + "playMode",}; - protected static final String[] DoubleFields = new String[] - { - "duration", - }; + protected static final String[] DoubleFields = new String[]{ + "duration",}; - protected static final String[] BooleanFields = new String[] - { - "balloonVisibility", - }; + protected static final String[] BooleanFields = new String[]{ + "balloonVisibility",}; - public static Map getDefaultParsers() - { + public static Map getDefaultParsers() { ConcurrentHashMap parsers = new ConcurrentHashMap(); String ns = GXConstants.GX_NAMESPACE; @@ -54,20 +46,17 @@ public static Map getDefaultParsers() parsers.put(new QName(ns, "Wait"), new GXWait(ns)); StringXMLEventParser stringParser = new StringXMLEventParser(); - for (String s : StringFields) - { + for (String s : StringFields) { parsers.put(new QName(ns, s), stringParser); } DoubleXMLEventParser doubleParser = new DoubleXMLEventParser(); - for (String s : DoubleFields) - { + for (String s : DoubleFields) { parsers.put(new QName(ns, s), doubleParser); } BooleanXMLEventParser booleanParser = new BooleanXMLEventParser(); - for (String s : BooleanFields) - { + for (String s : BooleanFields) { parsers.put(new QName(ns, s), booleanParser); } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXPlaylist.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXPlaylist.java index 19c9f2ecc4..e77762ceff 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXPlaylist.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXPlaylist.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; import gov.nasa.worldwind.ogc.kml.KMLAbstractObject; @@ -17,32 +16,29 @@ * @author tag * @version $Id: GXPlaylist.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXPlaylist extends KMLAbstractObject -{ +public class GXPlaylist extends KMLAbstractObject { + protected List tourPrimitives = new ArrayList(); - public GXPlaylist(String namespaceURI) - { + public GXPlaylist(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof GXAbstractTourPrimitive) + throws XMLStreamException { + if (o instanceof GXAbstractTourPrimitive) { this.addTourPrimitive((GXAbstractTourPrimitive) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - protected void addTourPrimitive(GXAbstractTourPrimitive o) - { + protected void addTourPrimitive(GXAbstractTourPrimitive o) { this.tourPrimitives.add(o); } - public List getTourPrimitives() - { + public List getTourPrimitives() { return this.tourPrimitives; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXSoundCue.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXSoundCue.java index 404cd1024c..dd0ad83f2b 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXSoundCue.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXSoundCue.java @@ -3,22 +3,19 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; /** * @author tag * @version $Id: GXSoundCue.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXSoundCue extends GXAbstractTourPrimitive -{ - public GXSoundCue(String namespaceURI) - { +public class GXSoundCue extends GXAbstractTourPrimitive { + + public GXSoundCue(String namespaceURI) { super(namespaceURI); } - public String getHref() - { + public String getHref() { return (String) this.getField("href"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXTour.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXTour.java index 034692bb72..82b0cccd79 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXTour.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXTour.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; import gov.nasa.worldwind.ogc.kml.KMLAbstractFeature; @@ -12,15 +11,13 @@ * @author tag * @version $Id: GXTour.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXTour extends KMLAbstractFeature -{ - public GXTour(String namespaceURI) - { +public class GXTour extends KMLAbstractFeature { + + public GXTour(String namespaceURI) { super(namespaceURI); } - public GXPlaylist getPlaylist() - { + public GXPlaylist getPlaylist() { return (GXPlaylist) this.getField("Playlist"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXTourControl.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXTourControl.java index 151019c5cf..cf4b0f4456 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXTourControl.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXTourControl.java @@ -3,22 +3,19 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; /** * @author tag * @version $Id: GXTourControl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXTourControl extends GXAbstractTourPrimitive -{ - public GXTourControl(String namespaceURI) - { +public class GXTourControl extends GXAbstractTourPrimitive { + + public GXTourControl(String namespaceURI) { super(namespaceURI); } - public String getPlayMode() - { + public String getPlayMode() { return (String) this.getField("playMode"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/GXWait.java b/src/gov/nasa/worldwind/ogc/kml/gx/GXWait.java index 68f4bca67a..a020e8ee6d 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/GXWait.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/GXWait.java @@ -3,22 +3,19 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.gx; /** * @author tag * @version $Id: GXWait.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GXWait extends GXAbstractTourPrimitive -{ - public GXWait(String namespaceURI) - { +public class GXWait extends GXAbstractTourPrimitive { + + public GXWait(String namespaceURI) { super(namespaceURI); } - public Double getDuration() - { + public Double getDuration() { return (Double) this.getField("duration"); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/gx/package-info.java b/src/gov/nasa/worldwind/ogc/kml/gx/package-info.java index 74956b7bd4..9e8f741e7f 100644 --- a/src/gov/nasa/worldwind/ogc/kml/gx/package-info.java +++ b/src/gov/nasa/worldwind/ogc/kml/gx/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

          * Provides classes for parsing the Google GX KML extensions.

          diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLAbstractBalloon.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLAbstractBalloon.java index 2b01b30550..22023f7143 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLAbstractBalloon.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLAbstractBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.avlist.*; @@ -44,21 +43,27 @@ * @author pabercrombie * @version $Id: KMLAbstractBalloon.java 1555 2013-08-20 13:33:12Z pabercrombie $ */ -public abstract class KMLAbstractBalloon implements Balloon, WebResourceResolver, PropertyChangeListener -{ +public abstract class KMLAbstractBalloon implements Balloon, WebResourceResolver, PropertyChangeListener { + public static final String DISPLAY_MODE_HIDE = "hide"; public static final String DISPLAY_MODE_DEFAULT = "default"; protected KMLAbstractFeature parent; protected String displayMode = DISPLAY_MODE_DEFAULT; - /** Indicates that the balloon has default text loaded, rather than text supplied by the BalloonStyle. */ + /** + * Indicates that the balloon has default text loaded, rather than text supplied by the BalloonStyle. + */ protected boolean usingDefaultText; protected boolean normalAttributesResolved; protected boolean highlightAttributesResolved; - /** Text when balloon is not highlighted. */ + /** + * Text when balloon is not highlighted. + */ protected String normalText; - /** Text when balloon is highlighted. */ + /** + * Text when balloon is highlighted. + */ protected String highlightText; /** @@ -66,10 +71,8 @@ public abstract class KMLAbstractBalloon implements Balloon, WebResourceResolver * * @param feature Feature to create balloon annotation for. */ - public KMLAbstractBalloon(KMLAbstractFeature feature) - { - if (feature == null) - { + public KMLAbstractBalloon(KMLAbstractFeature feature) { + if (feature == null) { String msg = Logging.getMessage("nullValue.FeatureIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -83,14 +86,12 @@ public KMLAbstractBalloon(KMLAbstractFeature feature) * * @param balloon The balloon contained in this wrapper object. */ - protected void initialize(Balloon balloon) - { + protected void initialize(Balloon balloon) { balloon.setTextDecoder(this.createTextDecoder(this.parent)); balloon.setValue(AVKey.CONTEXT, this.parent); // Configure this balloon to resolve relative paths in the KML balloon HTML via its resolve() method. - if (balloon instanceof AbstractBrowserBalloon) - { + if (balloon instanceof AbstractBrowserBalloon) { ((AbstractBrowserBalloon) balloon).setResourceResolver(this); } @@ -111,44 +112,39 @@ protected void initialize(Balloon balloon) * * @param dc Draw context */ - public void render(DrawContext dc) - { + public void render(DrawContext dc) { Balloon balloon = this.getBalloon(); - if (balloon.isHighlighted() && !this.highlightAttributesResolved) - { + if (balloon.isHighlighted() && !this.highlightAttributesResolved) { this.makeAttributesCurrent(KMLConstants.HIGHLIGHT); - } - else if (!this.normalAttributesResolved) - { + } else if (!this.normalAttributesResolved) { this.makeAttributesCurrent(KMLConstants.NORMAL); } this.determineActiveText(); - if (!WWUtil.isEmpty(this.getText()) && !DISPLAY_MODE_HIDE.equals(this.getDisplayMode())) + if (!WWUtil.isEmpty(this.getText()) && !DISPLAY_MODE_HIDE.equals(this.getDisplayMode())) { balloon.render(dc); + } } - /** Determine the balloon text for this frame, depending on the balloon highlight state. */ - protected void determineActiveText() - { + /** + * Determine the balloon text for this frame, depending on the balloon highlight state. + */ + protected void determineActiveText() { String activeText = null; // If the balloon is highlighted, use the highlight text. - if (this.isHighlighted()) - { + if (this.isHighlighted()) { activeText = this.highlightText; } // If the balloon is not highlighted, or there is no highlight text, use the normal text. - if (activeText == null) - { + if (activeText == null) { activeText = this.normalText; } // Set the text if it does not match the active text. - if (activeText != null && !activeText.equals(this.getText())) - { + if (activeText != null && !activeText.equals(this.getText())) { this.setText(activeText); } } @@ -159,64 +155,64 @@ protected void determineActiveText() * @param attrType Type of attributes to update. Either {@link KMLConstants#NORMAL} or {@link * KMLConstants#HIGHLIGHT}. */ - protected void makeAttributesCurrent(String attrType) - { + protected void makeAttributesCurrent(String attrType) { BalloonAttributes attrs = this.getInitialBalloonAttributes(); KMLBalloonStyle balloonStyle = (KMLBalloonStyle) this.parent.getSubStyle(new KMLBalloonStyle(null), attrType); String displayMode = balloonStyle.getDisplayMode(); - if (displayMode != null) + if (displayMode != null) { this.setDisplayMode(displayMode); + } this.assembleBalloonAttributes(balloonStyle, attrs); - if (balloonStyle.hasField(AVKey.UNRESOLVED)) + if (balloonStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); - else + } else { attrs.setUnresolved(false); + } - if (KMLConstants.NORMAL.equals(attrType)) - { + if (KMLConstants.NORMAL.equals(attrType)) { this.getBalloon().setAttributes(attrs); // Set balloon text. If the style does not provide text, set the default text, if it has not been set // already. We use a field to track if the default text has been set to avoid continually resetting default // text if the style cannot be resolved. String text = balloonStyle.getText(); - if (text != null) - { - if (this.mustAddHyperlinks(text)) + if (text != null) { + if (this.mustAddHyperlinks(text)) { text = this.addHyperlinks(text); + } this.getBalloon().setText(text); this.normalText = text; - } - else if (!this.usingDefaultText) - { + } else if (!this.usingDefaultText) { text = this.createDefaultBalloonText(); - if (this.mustAddHyperlinks(text)) + if (this.mustAddHyperlinks(text)) { text = this.addHyperlinks(text); + } this.getBalloon().setText(text); this.usingDefaultText = true; this.normalText = text; } - if (!attrs.isUnresolved() || !balloonStyle.hasFields()) + if (!attrs.isUnresolved() || !balloonStyle.hasFields()) { this.normalAttributesResolved = true; - } - else - { + } + } else { this.getBalloon().setHighlightAttributes(attrs); String text = balloonStyle.getText(); - if (this.mustAddHyperlinks(text)) + if (this.mustAddHyperlinks(text)) { text = this.addHyperlinks(text); + } this.highlightText = text; - if (!attrs.isUnresolved() || !balloonStyle.hasFields()) + if (!attrs.isUnresolved() || !balloonStyle.hasFields()) { this.highlightAttributesResolved = true; + } } } @@ -225,31 +221,29 @@ else if (!this.usingDefaultText) * * @return Default balloon text. */ - protected String createDefaultBalloonText() - { + protected String createDefaultBalloonText() { StringBuilder sb = new StringBuilder(); // Create default text for features that have a description String name = this.parent.getName(); String description = this.parent.getDescription(); - if (!WWUtil.isEmpty(name)) + if (!WWUtil.isEmpty(name)) { sb.append("").append(name).append(""); + } - if (!WWUtil.isEmpty(description)) + if (!WWUtil.isEmpty(description)) { sb.append("
          ").append(description); + } KMLExtendedData extendedData = this.parent.getExtendedData(); - if (extendedData != null) - { + if (extendedData != null) { List data = extendedData.getData(); - if (data != null && !data.isEmpty()) - { + if (data != null && !data.isEmpty()) { this.createDefaultExtendedDataText(sb, data); } List schemaData = extendedData.getSchemaData(); - if (schemaData != null && !schemaData.isEmpty()) - { + if (schemaData != null && !schemaData.isEmpty()) { this.createDefaultSchemaDataText(sb, schemaData); } } @@ -261,54 +255,44 @@ protected String createDefaultBalloonText() * Build a default balloon text string for the feature's extended data. This implementation builds a simple data * table. * - * @param sb Extended data string will be appended to this StringBuilder. + * @param sb Extended data string will be appended to this StringBuilder. * @param data The feature's extended data. */ - protected void createDefaultExtendedDataText(StringBuilder sb, List data) - { + protected void createDefaultExtendedDataText(StringBuilder sb, List data) { sb.append("

          "); - for (KMLData item : data) - { + for (KMLData item : data) { String value = item.getValue(); - if (!WWUtil.isEmpty(value)) - { + if (!WWUtil.isEmpty(value)) { String name = item.getName() != null ? item.getName() : ""; sb.append(""); + ""); } } sb.append("
          $[").append(name).append("/displayName]").append(value).append( - "
          "); } /** - * Build a default balloon text string for the feature's schema data. This implementation builds a simple data + * Build a default balloon text string for the feature's schema data. This implementation builds a simple data * table. * - * @param sb Extended data string will be appended to this StringBuilder. + * @param sb Extended data string will be appended to this StringBuilder. * @param data The feature's schema data. */ - protected void createDefaultSchemaDataText(StringBuilder sb, List data) - { + protected void createDefaultSchemaDataText(StringBuilder sb, List data) { sb.append("

          "); - for (KMLSchemaData schemaData : data) - { + for (KMLSchemaData schemaData : data) { KMLSchema schema = (KMLSchema) this.parent.getRoot().resolveReference(schemaData.getSchemaUrl()); - for (KMLSimpleData simpleData : schemaData.getSimpleData()) - { + for (KMLSimpleData simpleData : schemaData.getSimpleData()) { String value = simpleData.getCharacters(); - if (!WWUtil.isEmpty(value)) - { + if (!WWUtil.isEmpty(value)) { String dataName = simpleData.getName() != null ? simpleData.getName() : ""; sb.append(" * * - * + * + * * * * @@ -383,12 +376,11 @@ public static int computeTexturePixelFormat(int internalFormat) *

          * The returned estimate assumes that the driver provides does not convert the formats to another supported, such * converting as GL2.GL_ALPHA4 to GL2.GL_ALPHA8. This returns 0 if the internal format is - * not one of the recognized types. This does not attempt to estimate a memory size for compressed internal - * formats. + * not one of the recognized types. This does not attempt to estimate a memory size for compressed internal formats. * * @param internalFormat the OpenGL texture internal format. - * @param width the texture width, in pixels. - * @param height the texture height, in pixels. + * @param width the texture width, in pixels. + * @param height the texture height, in pixels. * @param includeMipmaps true to include the texture's mip map data in the estimated size; false otherwise. * * @return a pixel format corresponding to the texture internal format, or 0 if the internal format is not @@ -396,17 +388,14 @@ public static int computeTexturePixelFormat(int internalFormat) * * @throws IllegalArgumentException if either the width or height is less than or equal to zero. */ - public static int estimateTextureMemorySize(int internalFormat, int width, int height, boolean includeMipmaps) - { - if (width < 0) - { + public static int estimateTextureMemorySize(int internalFormat, int width, int height, boolean includeMipmaps) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthInvalid", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("Geom.HeightInvalid", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -415,19 +404,16 @@ public static int estimateTextureMemorySize(int internalFormat, int width, int h int numPixels = width * height; // Add the number of pixels from each level in the mipmap chain to the total number of pixels. - if (includeMipmaps) - { + if (includeMipmaps) { int maxLevel = Math.max((int) WWMath.logBase2(width), (int) WWMath.logBase2(height)); - for (int level = 1; level <= maxLevel; level++) - { + for (int level = 1; level <= maxLevel; level++) { int w = Math.max(width >> level, 1); int h = Math.max(height >> level, 1); numPixels += w * h; } } - switch (internalFormat) - { + switch (internalFormat) { // 4 bits per pixel. case GL2.GL_ALPHA4: case GL2.GL_LUMINANCE4: @@ -512,25 +498,21 @@ public static int estimateTextureMemorySize(int internalFormat, int width, int h /** * Creates TextureData from the given URL. Does no OpenGL work. * - * @param glp the OpenGL Profile this texture data should be created for. - * @param url the URL from which to read the texture data + * @param glp the OpenGL Profile this texture data should be created for. + * @param url the URL from which to read the texture data * @param useMipMaps whether mipmaps should be produced for this texture either by auto-generating them or reading - * them from the file. Some file formats support multiple mipmaps in a single file in which case - * those mipmaps will be used rather than generating them. + * them from the file. Some file formats support multiple mipmaps in a single file in which case those mipmaps will + * be used rather than generating them. * * @return the texture data from the URL, or null if none of the registered texture providers could read the URL * * @throws IOException if an error occurred while reading the URL */ - public static TextureData newTextureData(GLProfile glp, URL url, boolean useMipMaps) throws IOException - { + public static TextureData newTextureData(GLProfile glp, URL url, boolean useMipMaps) throws IOException { InputStream stream = new BufferedInputStream(url.openStream()); - try - { + try { return newTextureData(glp, stream, useMipMaps); - } - finally - { + } finally { stream.close(); } } @@ -538,21 +520,19 @@ public static TextureData newTextureData(GLProfile glp, URL url, boolean useMipM /** * Creates TextureData from an InputStream. Does no OpenGL work. * - * @param glp the OpenGL Profile this texture data should be created for. - * @param stream the stream from which to read the texture data + * @param glp the OpenGL Profile this texture data should be created for. + * @param stream the stream from which to read the texture data * @param useMipMaps whether mipmaps should be produced for this texture either by auto-generating them or reading - * them from the file. Some file formats support multiple mipmaps in a single file in which case - * those mipmaps will be used rather than generating them. + * them from the file. Some file formats support multiple mipmaps in a single file in which case those mipmaps will + * be used rather than generating them. * * @return the texture data from the URL, or null if none of the registered texture providers could read the URL * * @throws IOException if an error occurred while reading the URL */ - public static TextureData newTextureData(GLProfile glp, InputStream stream, boolean useMipMaps) throws IOException - { + public static TextureData newTextureData(GLProfile glp, InputStream stream, boolean useMipMaps) throws IOException { // Wrap stream in BufferedInputStream so that DDS detection will work. This is a work around for JOGL issue 4764639/4892246. - if (!(stream instanceof BufferedInputStream)) - { + if (!(stream instanceof BufferedInputStream)) { stream = new BufferedInputStream(stream); } @@ -562,11 +542,11 @@ public static TextureData newTextureData(GLProfile glp, InputStream stream, bool // If the image is not in DDS format, attempt to load it using ImageIO. This works around an issue with the // JOGL PNG reader (WWJ-369). However, ImageIO does not support DDS, so in this case just send the image to // TextureIO, for better performance. - if (!ddsFormat) - { + if (!ddsFormat) { BufferedImage img = ImageIO.read(stream); - if (img != null) + if (img != null) { return AWTTextureIO.newTextureData(glp, img, useMipMaps); + } } return TextureIO.newTextureData(glp, stream, useMipMaps, null); @@ -575,28 +555,27 @@ public static TextureData newTextureData(GLProfile glp, InputStream stream, bool /** * Creates TextureData from a File. Does no OpenGL work. * - * @param glp the OpenGL Profile this texture data should be created for. - * @param file the file from which to read the texture data + * @param glp the OpenGL Profile this texture data should be created for. + * @param file the file from which to read the texture data * @param useMipMaps whether mipmaps should be produced for this texture either by auto-generating them or reading - * them from the file. Some file formats support multiple mipmaps in a single file in which case - * those mipmaps will be used rather than generating them. + * them from the file. Some file formats support multiple mipmaps in a single file in which case those mipmaps will + * be used rather than generating them. * * @return the texture data from the URL, or null if none of the registered texture providers could read the URL * * @throws IOException if an error occurred while reading the URL */ - public static TextureData newTextureData(GLProfile glp, File file, boolean useMipMaps) throws IOException - { + public static TextureData newTextureData(GLProfile glp, File file, boolean useMipMaps) throws IOException { boolean ddsFormat = "dds".equalsIgnoreCase(WWIO.getSuffix(file.getPath())); // If the image is not in DDS format, attempt to load it using ImageIO. This works around an issue with the // JOGL PNG reader (WWJ-369). However, ImageIO does not support DDS, so in this case just send the image to // TextureIO, for better performance. - if (!ddsFormat) - { + if (!ddsFormat) { BufferedImage img = ImageIO.read(file); - if (img != null) + if (img != null) { return AWTTextureIO.newTextureData(glp, img, useMipMaps); + } } return TextureIO.newTextureData(glp, file, useMipMaps, null); diff --git a/src/gov/nasa/worldwind/util/PerformanceStatistic.java b/src/gov/nasa/worldwind/util/PerformanceStatistic.java index 0e95cf0217..b56b030292 100644 --- a/src/gov/nasa/worldwind/util/PerformanceStatistic.java +++ b/src/gov/nasa/worldwind/util/PerformanceStatistic.java @@ -7,17 +7,21 @@ import java.util.*; -public class PerformanceStatistic implements Comparable -{ +public class PerformanceStatistic implements Comparable { + public static final String ALL = "gov.nasa.worldwind.perfstat.All"; - - /** @deprecated Airspace geometry count is no longer logged during airspace rendering. */ + + /** + * @deprecated Airspace geometry count is no longer logged during airspace rendering. + */ @Deprecated public static final String AIRSPACE_GEOMETRY_COUNT = "gov.nasa.worldwind.perfstat.AirspaceGeometryCount"; - /** @deprecated Airspace vertex count is no longer logged during airspace rendering. */ + /** + * @deprecated Airspace vertex count is no longer logged during airspace rendering. + */ @Deprecated public static final String AIRSPACE_VERTEX_COUNT = "gov.nasa.worldwind.perfstat.AirspaceVertexCount"; - + public static final String FRAME_RATE = "gov.nasa.worldwind.perfstat.FrameRate"; public static final String FRAME_TIME = "gov.nasa.worldwind.perfstat.FrameTime"; public static final String IMAGE_TILE_COUNT = "gov.nasa.worldwind.perfstat.ImageTileCount"; @@ -29,8 +33,8 @@ public class PerformanceStatistic implements Comparable public static final String TEXTURE_CACHE = "gov.nasa.worldwind.perfstat.TextureCache"; public static final Set ALL_STATISTICS_SET = new HashSet(1); - static - { + + static { ALL_STATISTICS_SET.add(PerformanceStatistic.ALL); } @@ -38,65 +42,65 @@ public class PerformanceStatistic implements Comparable private final String displayString; private final Object value; - public PerformanceStatistic(String key, String displayString, Object value) - { + public PerformanceStatistic(String key, String displayString, Object value) { this.key = key; this.displayString = displayString; this.value = value; } - public String getKey() - { + public String getKey() { return key; } - public String getDisplayString() - { + public String getDisplayString() { return displayString; } - public Object getValue() - { + public Object getValue() { return value; } @Override - public int compareTo(PerformanceStatistic that) - { + public int compareTo(PerformanceStatistic that) { //noinspection StringEquality - if (this.displayString == that.displayString) + if (this.displayString == that.displayString) { return 0; + } - if (this.displayString != null && that.displayString != null) + if (this.displayString != null && that.displayString != null) { return this.displayString.compareTo(that.displayString); + } return this.displayString == null ? -1 : 1; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } PerformanceStatistic that = (PerformanceStatistic) o; - if (displayString != null ? !displayString.equals(that.displayString) : that.displayString != null) + if (displayString != null ? !displayString.equals(that.displayString) : that.displayString != null) { return false; - if (key != null ? !key.equals(that.key) : that.key != null) + } + if (key != null ? !key.equals(that.key) : that.key != null) { return false; + } //noinspection RedundantIfStatement - if (value != null ? !value.equals(that.value) : that.value != null) + if (value != null ? !value.equals(that.value) : that.value != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; result = (key != null ? key.hashCode() : 0); result = 31 * result + (displayString != null ? displayString.hashCode() : 0); @@ -105,8 +109,7 @@ public int hashCode() } @Override - public String toString() - { + public String toString() { return this.displayString + " " + this.value.toString(); } } diff --git a/src/gov/nasa/worldwind/util/PickPointFrustumList.java b/src/gov/nasa/worldwind/util/PickPointFrustumList.java index 3c032f5125..a36f21a39a 100644 --- a/src/gov/nasa/worldwind/util/PickPointFrustumList.java +++ b/src/gov/nasa/worldwind/util/PickPointFrustumList.java @@ -14,14 +14,12 @@ * @author Jeff Addison * @version $Id: PickPointFrustumList.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PickPointFrustumList extends ArrayList -{ - public PickPointFrustumList() - { +public class PickPointFrustumList extends ArrayList { + + public PickPointFrustumList() { } - public PickPointFrustumList(PickPointFrustumList list) - { + public PickPointFrustumList(PickPointFrustumList list) { super(list); } @@ -34,19 +32,15 @@ public PickPointFrustumList(PickPointFrustumList list) * * @throws IllegalArgumentException if the point is null. */ - public final boolean containsInAll(Vec4 point) - { - if (point == null) - { + public final boolean containsInAll(Vec4 point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - for (PickPointFrustum frustum : this) - { - if (!frustum.contains(point)) - { + for (PickPointFrustum frustum : this) { + if (!frustum.contains(point)) { return false; } } @@ -63,19 +57,15 @@ public final boolean containsInAll(Vec4 point) * * @throws IllegalArgumentException if the point is null. */ - public final boolean containsInAny(Vec4 point) - { - if (point == null) - { + public final boolean containsInAny(Vec4 point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - for (PickPointFrustum frustum : this) - { - if (frustum.contains(point)) - { + for (PickPointFrustum frustum : this) { + if (frustum.contains(point)) { return true; } } @@ -92,19 +82,15 @@ public final boolean containsInAny(Vec4 point) * * @throws IllegalArgumentException if the point is null. */ - public final boolean containsInAll(Point point) - { - if (point == null) - { + public final boolean containsInAll(Point point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - for (PickPointFrustum frustum : this) - { - if (!frustum.contains(point)) - { + for (PickPointFrustum frustum : this) { + if (!frustum.contains(point)) { return false; } } @@ -122,12 +108,9 @@ public final boolean containsInAll(Point point) * * @throws IllegalArgumentException if the point is null. */ - public final boolean containsInAny(double x, double y) - { - for (PickPointFrustum frustum : this) - { - if (frustum.contains(x, y)) - { + public final boolean containsInAny(double x, double y) { + for (PickPointFrustum frustum : this) { + if (frustum.contains(x, y)) { return true; } } @@ -144,19 +127,15 @@ public final boolean containsInAny(double x, double y) * * @throws IllegalArgumentException if the point is null. */ - public final boolean containsInAny(Point point) - { - if (point == null) - { + public final boolean containsInAny(Point point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - for (PickPointFrustum frustum : this) - { - if (frustum.contains(point)) - { + for (PickPointFrustum frustum : this) { + if (frustum.contains(point)) { return true; } } @@ -174,19 +153,15 @@ public final boolean containsInAny(Point point) * * @throws IllegalArgumentException if the extent is null. */ - public final boolean intersectsAll(Extent extent) - { - if (extent == null) - { + public final boolean intersectsAll(Extent extent) { + if (extent == null) { String msg = Logging.getMessage("nullValue.ExtentIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - for (PickPointFrustum frustum : this) - { - if (!frustum.intersects(extent)) - { + for (PickPointFrustum frustum : this) { + if (!frustum.intersects(extent)) { return false; } } @@ -203,19 +178,15 @@ public final boolean intersectsAll(Extent extent) * * @throws IllegalArgumentException if the extent is null. */ - public final boolean intersectsAny(Extent extent) - { - if (extent == null) - { + public final boolean intersectsAny(Extent extent) { + if (extent == null) { String msg = Logging.getMessage("nullValue.ExtentIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - for (PickPointFrustum frustum : this) - { - if (frustum.intersects(extent)) - { + for (PickPointFrustum frustum : this) { + if (frustum.intersects(extent)) { return true; } } @@ -233,12 +204,11 @@ public final boolean intersectsAny(Extent extent) * * @throws IllegalArgumentException if either point is null. */ - public final boolean intersectsAny(Vec4 pa, Vec4 pb) - { - for (PickPointFrustum frustum : this) - { - if (frustum.intersectsSegment(pa, pb)) + public final boolean intersectsAny(Vec4 pa, Vec4 pb) { + for (PickPointFrustum frustum : this) { + if (frustum.intersectsSegment(pa, pb)) { return true; + } } return false; @@ -251,23 +221,19 @@ public final boolean intersectsAny(Vec4 pa, Vec4 pb) * @param rect the Rectangle to test. * * @return true if the specified Rectangle intersects the 2D screen space enclosed by ALL Frustums, and false - * otherwise. + * otherwise. * * @throws IllegalArgumentException if the extent is null. */ - public final boolean intersectsAll(Rectangle rect) - { - if (rect == null) - { + public final boolean intersectsAll(Rectangle rect) { + if (rect == null) { String msg = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - for (PickPointFrustum frustum : this) - { - if (!frustum.intersects(rect)) - { + for (PickPointFrustum frustum : this) { + if (!frustum.intersects(rect)) { return false; } } @@ -282,27 +248,23 @@ public final boolean intersectsAll(Rectangle rect) * @param rect the Rectangle to test. * * @return true if the specified Rectangle intersects the 2D screen space enclosed by ANY of the Frustums, and false - * otherwise. + * otherwise. * * @throws IllegalArgumentException if the extent is null. */ - public final boolean intersectsAny(Rectangle rect) - { - if (rect == null) - { + public final boolean intersectsAny(Rectangle rect) { + if (rect == null) { String msg = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - for (PickPointFrustum frustum : this) - { - if (frustum.intersects(rect)) - { + for (PickPointFrustum frustum : this) { + if (frustum.intersects(rect)) { return true; } } return false; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/PlacemarkClutterFilter.java b/src/gov/nasa/worldwind/util/PlacemarkClutterFilter.java index 07b01d9d1a..88ea4b7ed5 100644 --- a/src/gov/nasa/worldwind/util/PlacemarkClutterFilter.java +++ b/src/gov/nasa/worldwind/util/PlacemarkClutterFilter.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.avlist.AVKey; @@ -25,24 +24,25 @@ * @author tag * @version $Id: PlacemarkClutterFilter.java 2388 2014-10-15 22:58:36Z tgaskins $ */ -public class PlacemarkClutterFilter implements ClutterFilter -{ - /** Holds the rectangles of the regions already drawn. */ +public class PlacemarkClutterFilter implements ClutterFilter { + + /** + * Holds the rectangles of the regions already drawn. + */ protected List rectList = new ArrayList(); - /** Maintains a list of regions and the shapes associated with each region. */ + /** + * Maintains a list of regions and the shapes associated with each region. + */ protected Map> shapeMap = new HashMap>(); - public void apply(DrawContext dc, List shapes) - { - for (Declutterable shape : shapes) - { + public void apply(DrawContext dc, List shapes) { + for (Declutterable shape : shapes) { Rectangle2D bounds = shape.getBounds(dc); Rectangle2D intersectingRegion = this.intersects(bounds); - if (intersectingRegion != null) + if (intersectingRegion != null) { this.addShape(intersectingRegion, shape); - else if (bounds != null) - { + } else if (bounds != null) { // Double the size of the capturing rectangle in order to grab more than it otherwise would. This // reduces the clutter caused by the decluttered representations themselves. double w = 2 * bounds.getWidth(); @@ -57,9 +57,10 @@ else if (bounds != null) this.clear(); } - /** Release all the resources used in the most recent filter application. */ - protected void clear() - { + /** + * Release all the resources used in the most recent filter application. + */ + protected void clear() { this.rectList.clear(); this.shapeMap.clear(); } @@ -72,15 +73,15 @@ protected void clear() * @return the intersected region if the input region intersects one or more other regions in the filter, otherwise * false. */ - protected Rectangle2D intersects(Rectangle2D rectangle) - { - if (rectangle == null) + protected Rectangle2D intersects(Rectangle2D rectangle) { + if (rectangle == null) { return null; + } - for (Rectangle2D rect : this.rectList) - { - if (rectangle.intersects(rect)) + for (Rectangle2D rect : this.rectList) { + if (rectangle.intersects(rect)) { return rect; + } } return null; @@ -90,14 +91,12 @@ protected Rectangle2D intersects(Rectangle2D rectangle) * Adds a shape to the internal shape map. * * @param rectangle the rectangle to associate the shape with. - * @param shape the shape to associate with the specified rectangle. + * @param shape the shape to associate with the specified rectangle. */ - protected void addShape(Rectangle2D rectangle, Declutterable shape) - { + protected void addShape(Rectangle2D rectangle, Declutterable shape) { List shapeList = this.shapeMap.get(rectangle); - if (shapeList == null) - { + if (shapeList == null) { shapeList = new ArrayList(1); this.shapeMap.put(rectangle, shapeList); this.rectList.add(rectangle); @@ -113,45 +112,38 @@ protected void addShape(Rectangle2D rectangle, Declutterable shape) * * @param dc the current draw context. */ - protected void render(DrawContext dc) - { - for (Map.Entry> entry : this.shapeMap.entrySet()) - { + protected void render(DrawContext dc) { + for (Map.Entry> entry : this.shapeMap.entrySet()) { List placemarks = null; Declutterable firstShape = null; - for (Declutterable shape : entry.getValue()) - { - if (shape instanceof PointPlacemark.OrderedPlacemark) - { - if (placemarks == null) + for (Declutterable shape : entry.getValue()) { + if (shape instanceof PointPlacemark.OrderedPlacemark) { + if (placemarks == null) { placemarks = new ArrayList(); + } placemarks.add((PointPlacemark.OrderedPlacemark) shape); - } - else - { + } else { // Keep track of the first non-placemark shape associated with the current rectangle. - if (firstShape == null) + if (firstShape == null) { firstShape = shape; + } } } // Add the first shape back to the ordered renderable list. - if (firstShape != null) + if (firstShape != null) { dc.addOrderedRenderable(firstShape); + } - if (placemarks != null && placemarks.size() > 1) - { + if (placemarks != null && placemarks.size() > 1) { double angle = -placemarks.size(); // increments Y position of placemark label - for (PointPlacemark.OrderedPlacemark pp : placemarks) - { + for (PointPlacemark.OrderedPlacemark pp : placemarks) { angle += 1; dc.addOrderedRenderable(new DeclutteredLabel(angle, pp, entry.getKey())); } - } - else if (placemarks != null && placemarks.size() == 1) - { + } else if (placemarks != null && placemarks.size() == 1) { // If there's only one placemark associated with the current rectangle, just add it back to the // ordered renderable list. dc.addOrderedRenderable(placemarks.get(0)); @@ -159,60 +151,54 @@ else if (placemarks != null && placemarks.size() == 1) } } - protected static class DeclutteredLabel implements OrderedRenderable - { + protected static class DeclutteredLabel implements OrderedRenderable { + protected double angle; protected PointPlacemark.OrderedPlacemark opm; protected Rectangle2D region; protected PickSupport pickSupport; - public DeclutteredLabel(double angle, PointPlacemark.OrderedPlacemark opm, Rectangle2D region) - { + public DeclutteredLabel(double angle, PointPlacemark.OrderedPlacemark opm, Rectangle2D region) { this.angle = angle; this.opm = opm; this.region = region; } @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.opm.getDistanceFromEye(); } @Override - public void pick(DrawContext dc, Point pickPoint) - { - if (this.opm.getPlacemark().isEnableLabelPicking()) - { - if (this.pickSupport == null) + public void pick(DrawContext dc, Point pickPoint) { + if (this.opm.getPlacemark().isEnableLabelPicking()) { + if (this.pickSupport == null) { this.pickSupport = new PickSupport(); + } this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.render(dc); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, opm.getPickLayer()); } } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. PointPlacemarkAttributes attrs = this.opm.getPlacemark().getAttributes(); Font font = attrs != null ? attrs.getLabelFont() : null; - if (font == null) + if (font == null) { font = PointPlacemarkAttributes.DEFAULT_LABEL_FONT; + } OGLStackHandler osh = new OGLStackHandler(); - int attrMask = - GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask and depth func + int attrMask + = GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask and depth func | GL2.GL_TRANSFORM_BIT // for modelview and perspective | GL2.GL_VIEWPORT_BIT // for depth range | GL2.GL_CURRENT_BIT // for current color @@ -223,8 +209,7 @@ public void render(DrawContext dc) osh.pushAttrib(gl, attrMask); osh.pushProjectionIdentity(gl); - try - { + try { // Do not depth buffer the label. (Placemarks beyond the horizon are culled above.) gl.glDisable(GL.GL_DEPTH_TEST); @@ -248,8 +233,7 @@ public void render(DrawContext dc) osh.pushModelviewIdentity(gl); this.drawDeclutterLabel(dc, font, textPoint, this.opm.getPlacemark().getLabelText()); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Compute the end point of the line. Vec4 endPoint = new Vec4(textPoint.x + bounds.getWidth(), textPoint.y, textPoint.z); dx = endPoint.x - startPoint.x; @@ -258,28 +242,25 @@ public void render(DrawContext dc) dx = textPoint.x - startPoint.x; dy = textPoint.y - startPoint.y; double d2 = dx * dx + dy * dy; - if (d2 < d1) + if (d2 < d1) { endPoint = textPoint; + } this.drawDeclutterLine(dc, startPoint, endPoint); } - } - finally - { + } finally { osh.pop(gl); } } - protected void drawDeclutterLabel(DrawContext dc, Font font, Vec4 textPoint, String labelText) - { + protected void drawDeclutterLabel(DrawContext dc, Font font, Vec4 textPoint, String labelText) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { // Pick the text box, not just the text. Color pickColor = dc.getUniquePickColor(); Object delegateOwner = this.opm.getPlacemark().getDelegateOwner(); PickedObject po = new PickedObject(pickColor.getRGB(), - delegateOwner != null ? delegateOwner : this.opm.getPlacemark()); + delegateOwner != null ? delegateOwner : this.opm.getPlacemark()); po.setValue(AVKey.PICKED_OBJECT_ID, AVKey.LABEL); this.pickSupport.addPickableObject(po); gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue()); @@ -287,42 +268,37 @@ protected void drawDeclutterLabel(DrawContext dc, Font font, Vec4 textPoint, Str gl.glTranslated(textPoint.x, textPoint.y, 0); gl.glScaled(this.region.getWidth() / 2, this.region.getHeight() / 2, 1); dc.drawUnitQuad(); - } - else - { + } else { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); - try - { + try { PointPlacemark placemark = this.opm.getPlacemark(); Color textColor = Color.WHITE; if (placemark.isHighlighted() && placemark.getHighlightAttributes() != null - && placemark.getHighlightAttributes().getLabelColor() != null) + && placemark.getHighlightAttributes().getLabelColor() != null) { textColor = placemark.getHighlightAttributes().getLabelColor(); - else if (placemark.getAttributes() != null && placemark.getAttributes().getLabelColor() != null) + } else if (placemark.getAttributes() != null && placemark.getAttributes().getLabelColor() != null) { textColor = placemark.getAttributes().getLabelColor(); + } textRenderer.begin3DRendering(); textRenderer.setColor(Color.BLACK); textRenderer.draw3D(labelText, (float) textPoint.x + 1, (float) textPoint.y - 1, 0, 1); textRenderer.setColor(textColor); textRenderer.draw3D(labelText, (float) textPoint.x, (float) textPoint.y, 0, 1); - } - finally - { + } finally { textRenderer.end3DRendering(); } } } - protected void drawDeclutterLine(DrawContext dc, Vec4 startPoint, Vec4 endPoint) - { + protected void drawDeclutterLine(DrawContext dc, Vec4 startPoint, Vec4 endPoint) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glLineWidth(1); Color color = Color.WHITE; gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue(), - (byte) color.getAlpha()); + (byte) color.getAlpha()); gl.glBegin(GL2.GL_LINE_STRIP); gl.glVertex3d(startPoint.x(), startPoint.y, startPoint.z); diff --git a/src/gov/nasa/worldwind/util/PolygonTessellator2.java b/src/gov/nasa/worldwind/util/PolygonTessellator2.java index 308928d26b..c660f93ed3 100644 --- a/src/gov/nasa/worldwind/util/PolygonTessellator2.java +++ b/src/gov/nasa/worldwind/util/PolygonTessellator2.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import com.jogamp.opengl.glu.*; @@ -16,37 +15,32 @@ * @author dcollins * @version $Id: PolygonTessellator2.java 2367 2014-10-02 23:37:12Z dcollins $ */ -public class PolygonTessellator2 -{ - protected static class TessCallbackAdapter extends GLUtessellatorCallbackAdapter - { +public class PolygonTessellator2 { + + protected static class TessCallbackAdapter extends GLUtessellatorCallbackAdapter { + @Override - public void beginData(int type, Object userData) - { + public void beginData(int type, Object userData) { ((PolygonTessellator2) userData).tessBegin(type); } @Override - public void edgeFlagData(boolean boundaryEdge, Object userData) - { + public void edgeFlagData(boolean boundaryEdge, Object userData) { ((PolygonTessellator2) userData).tessEdgeFlag(boundaryEdge); } @Override - public void vertexData(Object vertexData, Object userData) - { + public void vertexData(Object vertexData, Object userData) { ((PolygonTessellator2) userData).tessVertex(vertexData); } @Override - public void endData(Object userData) - { + public void endData(Object userData) { ((PolygonTessellator2) userData).tessEnd(); } @Override - public void combineData(double[] coords, Object[] vertexData, float[] weight, Object[] outData, Object userData) - { + public void combineData(double[] coords, Object[] vertexData, float[] weight, Object[] outData, Object userData) { ((PolygonTessellator2) userData).tessCombine(coords, vertexData, weight, outData); } } @@ -64,8 +58,7 @@ public void combineData(double[] coords, Object[] vertexData, float[] weight, Ob protected float[] vertex = new float[3]; protected int prevClipCode; - public PolygonTessellator2() - { + public PolygonTessellator2() { this.tess = GLU.gluNewTess(); TessCallbackAdapter callback = new TessCallbackAdapter(); GLU.gluTessCallback(this.tess, GLU.GLU_TESS_BEGIN_DATA, callback); @@ -75,13 +68,11 @@ public PolygonTessellator2() GLU.gluTessCallback(this.tess, GLU.GLU_TESS_COMBINE_DATA, callback); } - public int getVertexCount() - { + public int getVertexCount() { return this.vertices.position() / this.vertexStride; } - public FloatBuffer getVertices(FloatBuffer buffer) - { + public FloatBuffer getVertices(FloatBuffer buffer) { int lim = this.vertices.limit(); int pos = this.vertices.position(); @@ -93,13 +84,11 @@ public FloatBuffer getVertices(FloatBuffer buffer) return buffer; } - public int getInteriorIndexCount() - { + public int getInteriorIndexCount() { return this.interiorIndices.position(); } - public IntBuffer getInteriorIndices(IntBuffer buffer) - { + public IntBuffer getInteriorIndices(IntBuffer buffer) { int lim = this.interiorIndices.limit(); int pos = this.interiorIndices.position(); @@ -111,13 +100,11 @@ public IntBuffer getInteriorIndices(IntBuffer buffer) return buffer; } - public int getBoundaryIndexCount() - { + public int getBoundaryIndexCount() { return this.boundaryIndices.position(); } - public IntBuffer getBoundaryIndices(IntBuffer buffer) - { + public IntBuffer getBoundaryIndices(IntBuffer buffer) { int lim = this.boundaryIndices.limit(); int pos = this.boundaryIndices.position(); @@ -129,64 +116,54 @@ public IntBuffer getBoundaryIndices(IntBuffer buffer) return buffer; } - public Range getPolygonVertexRange() - { + public Range getPolygonVertexRange() { return this.polygonVertexRange; } - public void reset() - { + public void reset() { this.vertices.clear(); this.resetIndices(); } - public void resetIndices() - { + public void resetIndices() { this.interiorIndices.clear(); this.boundaryIndices.clear(); } - public void setPolygonNormal(double x, double y, double z) - { + public void setPolygonNormal(double x, double y, double z) { GLU.gluTessNormal(this.tess, x, y, z); } - public void setPolygonClipCoords(double xMin, double xMax, double yMin, double yMax) - { + public void setPolygonClipCoords(double xMin, double xMax, double yMin, double yMax) { this.clip[0] = xMin; this.clip[1] = xMax; this.clip[2] = yMin; this.clip[3] = yMax; } - public void setVertexStride(int stride) - { + public void setVertexStride(int stride) { this.vertexStride = stride; } - public void setVertexOffset(double x, double y, double z) - { + public void setVertexOffset(double x, double y, double z) { this.offset[0] = x; this.offset[1] = y; this.offset[2] = z; } - public void beginPolygon() - { + public void beginPolygon() { GLU.gluTessBeginPolygon(this.tess, this); // Use this as the polygon user data to enable callbacks. this.polygonVertexRange.location = this.vertices.position() / this.vertexStride; this.polygonVertexRange.length = 0; } - public void beginContour() - { + public void beginContour() { GLU.gluTessBeginContour(this.tess); this.prevClipCode = -1; } - public void addVertex(double x, double y, double z) - { + public void addVertex(double x, double y, double z) { this.coords[0] = x; this.coords[1] = y; this.coords[2] = z; @@ -194,14 +171,12 @@ public void addVertex(double x, double y, double z) // TODO Modify this logic to clip edges against the clip boundary, adding new vertices as necessary // TODO and storing the code to indicate whether or not the vertex should be included in boundary edges. int code = this.clipCode(x, y, z); - if (this.prevClipCode > 0 && code != this.prevClipCode) - { + if (this.prevClipCode > 0 && code != this.prevClipCode) { int index = this.putVertex(this.coords, 3); // add the previous vertex GLU.gluTessVertex(this.tess, this.coords, 3, index); // associate the vertex with its index } - if (code == 0 || code != this.prevClipCode) - { + if (code == 0 || code != this.prevClipCode) { int index = this.putVertex(this.coords, 0); // add the current vertex GLU.gluTessVertex(this.tess, this.coords, 0, index); // associate the vertex with its index } @@ -210,13 +185,11 @@ public void addVertex(double x, double y, double z) this.prevClipCode = code; // copy the current clip code to the previous clip code } - public void endContour() - { + public void endContour() { GLU.gluTessEndContour(this.tess); } - public void endPolygon() - { + public void endPolygon() { GLU.gluTessEndPolygon(this.tess); this.polygonVertexRange.length = this.vertices.position() / this.vertexStride; @@ -224,18 +197,15 @@ public void endPolygon() } @SuppressWarnings("UnusedParameters") - protected void tessBegin(int type) - { + protected void tessBegin(int type) { // Intentionally left blank. } - protected void tessEdgeFlag(boolean boundaryEdge) - { + protected void tessEdgeFlag(boolean boundaryEdge) { this.isBoundaryEdge = boundaryEdge; } - protected void tessVertex(Object vertexData) - { + protected void tessVertex(Object vertexData) { // Accumulate interior indices appropriate for use as GL_interiorIndices primitives. Based on the GLU // tessellator documentation we can assume that the tessellator is providing interiorIndices because it's // configured with the edgeFlag callback. @@ -244,39 +214,32 @@ protected void tessVertex(Object vertexData) // Accumulate outline indices appropriate for use as GL_boundaryIndices. The tessBoundaryEdge flag indicates // whether or not the triangle edge starting with the current vertex is a boundary edge. - if ((this.boundaryIndices.position() % 2) == 1) - { + if ((this.boundaryIndices.position() % 2) == 1) { this.putBoundaryIndex(index); } - if (this.isBoundaryEdge) - { + if (this.isBoundaryEdge) { this.putBoundaryIndex(index); int interiorCount = this.interiorIndices.position(); - if (interiorCount > 0 && (interiorCount % 3) == 0) - { + if (interiorCount > 0 && (interiorCount % 3) == 0) { int firstTriIndex = this.interiorIndices.get(interiorCount - 3); this.putBoundaryIndex(firstTriIndex); } } } - protected void tessEnd() - { + protected void tessEnd() { // Intentionally left blank. } - protected void tessCombine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) - { + protected void tessCombine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) { outData[0] = this.putVertex(coords, 0); // TODO: Implement a caller-specified combine callback to enable customizing the vertex data added. } - protected int putVertex(double[] coords, int pos) - { - if (this.vertices.remaining() < this.vertexStride) - { + protected int putVertex(double[] coords, int pos) { + if (this.vertices.remaining() < this.vertexStride) { int capacity = this.vertices.capacity() + this.vertices.capacity() / 2; // increase capacity by 50% FloatBuffer buffer = FloatBuffer.allocate(capacity); buffer.put((FloatBuffer) this.vertices.flip()); @@ -293,12 +256,10 @@ protected int putVertex(double[] coords, int pos) return index; } - protected void putInteriorIndex(int i) - { - if (!this.interiorIndices.hasRemaining()) - { + protected void putInteriorIndex(int i) { + if (!this.interiorIndices.hasRemaining()) { int capacity = this.interiorIndices.capacity() - + this.interiorIndices.capacity() / 2; // increase capacity by 50% + + this.interiorIndices.capacity() / 2; // increase capacity by 50% IntBuffer buffer = IntBuffer.allocate(capacity); buffer.put((IntBuffer) this.interiorIndices.flip()); this.interiorIndices = buffer; @@ -307,12 +268,10 @@ protected void putInteriorIndex(int i) this.interiorIndices.put(i); } - protected void putBoundaryIndex(int i) - { - if (!this.boundaryIndices.hasRemaining()) - { + protected void putBoundaryIndex(int i) { + if (!this.boundaryIndices.hasRemaining()) { int capacity = this.boundaryIndices.capacity() - + this.boundaryIndices.capacity() / 2; // increase capacity by 50% + + this.boundaryIndices.capacity() / 2; // increase capacity by 50% IntBuffer buffer = IntBuffer.allocate(capacity); buffer.put((IntBuffer) this.boundaryIndices.flip()); this.boundaryIndices = buffer; @@ -331,8 +290,7 @@ protected void putBoundaryIndex(int i) * @param z The x coordinate for computation. * @return The vertex code. */ - protected int clipCode(double x, double y, double z) - { + protected int clipCode(double x, double y, double z) { // TODO: Add support for clipping z coordiantes. int code = 0; code |= (x < this.clip[0] ? 0x0001 : 0x0); // xMin diff --git a/src/gov/nasa/worldwind/util/PolylineGeneralizer.java b/src/gov/nasa/worldwind/util/PolylineGeneralizer.java index 322389a270..5a08a499c6 100644 --- a/src/gov/nasa/worldwind/util/PolylineGeneralizer.java +++ b/src/gov/nasa/worldwind/util/PolylineGeneralizer.java @@ -9,10 +9,10 @@ * @author dcollins * @version $Id: PolylineGeneralizer.java 2321 2014-09-17 19:34:42Z dcollins $ */ -public class PolylineGeneralizer -{ - protected static class Element - { +public class PolylineGeneralizer { + + protected static class Element { + public final int ordinal; public final double x; public final double y; @@ -22,8 +22,7 @@ protected static class Element public Element prev; public Element next; - public Element(int ordinal, double x, double y, double z) - { + public Element(int ordinal, double x, double y, double z) { this.ordinal = ordinal; this.heapIndex = ordinal; this.x = x; @@ -37,49 +36,42 @@ public Element(int ordinal, double x, double y, double z) protected int vertexCount; protected double[] vertexArea; - public PolylineGeneralizer() - { + public PolylineGeneralizer() { this.heap = new Element[10]; this.vertexArea = new double[10]; } - public int getVertexCount() - { + public int getVertexCount() { return this.vertexCount; } - public double[] getVertexEffectiveArea(double[] array) - { - if (array == null || array.length < this.vertexCount) + public double[] getVertexEffectiveArea(double[] array) { + if (array == null || array.length < this.vertexCount) { array = new double[this.vertexCount]; + } System.arraycopy(this.vertexArea, 0, array, 0, this.vertexCount); return array; } - public void beginPolyline() - { + public void beginPolyline() { this.heapSize = 0; } - public void endPolyline() - { + public void endPolyline() { this.computeInitialArea(); // compute the effective area of each vertex this.heapify(); // rearrange the vertex array in order to satisfy the min-heap property based on effective area this.computeEliminationArea(); // simulate repeated elimination of the min-area vertex } - public void reset() - { + public void reset() { this.heapSize = 0; this.vertexCount = 0; } - public void addVertex(double x, double y, double z) - { - if (this.heapSize == this.heap.length) - { + public void addVertex(double x, double y, double z) { + if (this.heapSize == this.heap.length) { int capacity = this.heap.length + this.heap.length / 2; // increase heap capacity by 50% Element[] array = new Element[capacity]; System.arraycopy(this.heap, 0, array, 0, this.heap.length); @@ -89,12 +81,10 @@ public void addVertex(double x, double y, double z) this.heap[this.heapSize++] = new Element(this.vertexCount++, x, y, z); } - protected void computeInitialArea() - { + protected void computeInitialArea() { this.heap[0].area = Double.MAX_VALUE; // assign the start point the maximum area - for (int i = 1; i < this.heapSize - 1; i++) - { + for (int i = 1; i < this.heapSize - 1; i++) { this.heap[i].prev = this.heap[i - 1]; this.heap[i].next = this.heap[i + 1]; this.heap[i].area = this.computeEffectiveArea(this.heap[i]); @@ -103,10 +93,8 @@ protected void computeInitialArea() this.heap[this.heapSize - 1].area = Double.MAX_VALUE; // assign the end point the maximum area } - protected void computeEliminationArea() - { - if (this.vertexArea.length < this.vertexCount) - { + protected void computeEliminationArea() { + if (this.vertexArea.length < this.vertexCount) { double[] array = new double[this.vertexCount]; System.arraycopy(this.vertexArea, 0, array, 0, this.vertexArea.length); this.vertexArea = array; @@ -116,27 +104,26 @@ protected void computeEliminationArea() // end point remain (the start point and end point are not in the heap). Element cur; double lastArea = 0; - while ((cur = this.pop()) != null) - { + while ((cur = this.pop()) != null) { // If the current point's area is less than that of the last point to be eliminated, use the latter's area // instead. This ensures that the current point cannot be filtered before previously eliminated points. double area = cur.area; - if (area < lastArea) + if (area < lastArea) { area = lastArea; - else // Otherwise, update the last area with the current point's area. + } else // Otherwise, update the last area with the current point's area. + { lastArea = area; + } this.vertexArea[cur.ordinal] = area; // Recompute previous point's effective area, unless it's the start point. - if (cur.prev != null && cur.prev.prev != null) - { + if (cur.prev != null && cur.prev.prev != null) { cur.prev.next = cur.next; this.updateEffectiveArea(cur.prev); } // Recompute next point's effective area, unless it's the end point. - if (cur.next != null && cur.next.next != null) - { + if (cur.next != null && cur.next.next != null) { cur.next.prev = cur.prev; this.updateEffectiveArea(cur.next); } @@ -148,8 +135,7 @@ protected void computeEliminationArea() } // TODO: Modify computeEffectiveArea to correctly compute area when z != 0 - protected double computeEffectiveArea(Element e) - { + protected double computeEffectiveArea(Element e) { Element c = e; Element p = e.prev; Element n = e.next; @@ -157,52 +143,48 @@ protected double computeEffectiveArea(Element e) return 0.5 * Math.abs((p.x - c.x) * (n.y - c.y) - (p.y - c.y) * (n.x - c.x)); } - protected void updateEffectiveArea(Element e) - { + protected void updateEffectiveArea(Element e) { double oldArea = e.area; double newArea = this.computeEffectiveArea(e); e.area = newArea; - if (newArea < oldArea) + if (newArea < oldArea) { this.siftUp(e.heapIndex, e); - else if (newArea > oldArea) + } else if (newArea > oldArea) { this.siftDown(e.heapIndex, e); + } } - protected void heapify() - { - for (int i = (this.heapSize >>> 1) - 1; i >= 0; i--) - { + protected void heapify() { + for (int i = (this.heapSize >>> 1) - 1; i >= 0; i--) { this.siftDown(i, this.heap[i]); } } - protected Element pop() - { - if (this.heapSize == 0) + protected Element pop() { + if (this.heapSize == 0) { return null; + } int size = --this.heapSize; Element top = this.heap[0]; Element last = this.heap[size]; this.heap[size] = null; - if (size != 0) - { + if (size != 0) { this.siftDown(0, last); } return top; } - protected void siftUp(int k, Element x) - { - while (k > 0) - { + protected void siftUp(int k, Element x) { + while (k > 0) { int parent = (k - 1) >>> 1; Element e = this.heap[parent]; - if (x.area >= e.area) + if (x.area >= e.area) { break; + } this.heap[k] = e; e.heapIndex = k; @@ -213,19 +195,19 @@ protected void siftUp(int k, Element x) x.heapIndex = k; } - protected void siftDown(int k, Element x) - { + protected void siftDown(int k, Element x) { int half = this.heapSize >>> 1; - while (k < half) - { + while (k < half) { int child = (k << 1) + 1; Element c = this.heap[child]; int right = child + 1; - if (right < this.heapSize && c.area > this.heap[right].area) + if (right < this.heapSize && c.area > this.heap[right].area) { c = this.heap[child = right]; - if (x.area <= c.area) + } + if (x.area <= c.area) { break; + } this.heap[k] = c; c.heapIndex = k; diff --git a/src/gov/nasa/worldwind/util/PropertyAccessor.java b/src/gov/nasa/worldwind/util/PropertyAccessor.java index f797e737db..1b2a348bcf 100644 --- a/src/gov/nasa/worldwind/util/PropertyAccessor.java +++ b/src/gov/nasa/worldwind/util/PropertyAccessor.java @@ -11,29 +11,27 @@ * @author jym * @version $Id: PropertyAccessor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PropertyAccessor -{ +public class PropertyAccessor { - public PropertyAccessor() - { + public PropertyAccessor() { } - public static interface AngleAccessor - { + public static interface AngleAccessor { + Angle getAngle(); boolean setAngle(Angle value); } - public static interface DoubleAccessor - { + public static interface DoubleAccessor { + Double getDouble(); boolean setDouble(Double value); } - public static interface PositionAccessor - { + public static interface PositionAccessor { + Position getPosition(); boolean setPosition(Position value); diff --git a/src/gov/nasa/worldwind/util/Range.java b/src/gov/nasa/worldwind/util/Range.java index 9e8f75091d..94bcef03eb 100644 --- a/src/gov/nasa/worldwind/util/Range.java +++ b/src/gov/nasa/worldwind/util/Range.java @@ -11,21 +11,24 @@ * @author dcollins * @version $Id: Range.java 2281 2014-08-29 23:08:04Z dcollins $ */ -public class Range -{ - /** The start index of the range. 0 indicates the first item in the series. */ +public class Range { + + /** + * The start index of the range. 0 indicates the first item in the series. + */ public int location; - /** The number of items in the range. May be 0 to indicate an empty range. */ + /** + * The number of items in the range. May be 0 to indicate an empty range. + */ public int length; /** * Creates a new range with the specified start index and number of items. * * @param location The start index of the range. - * @param length The number of items in the range. May be 0 to indicate an empty range. + * @param length The number of items in the range. May be 0 to indicate an empty range. */ - public Range(int location, int length) - { + public Range(int location, int length) { this.location = location; this.length = length; } @@ -39,8 +42,7 @@ public Range(int location, int length) * * @return true if the location is in this range, otherwise false. */ - public boolean contains(int location) - { + public boolean contains(int location) { return location >= this.location && location < this.location + this.length; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/RasterControlPointList.java b/src/gov/nasa/worldwind/util/RasterControlPointList.java index b17c024e23..bf97c917de 100644 --- a/src/gov/nasa/worldwind/util/RasterControlPointList.java +++ b/src/gov/nasa/worldwind/util/RasterControlPointList.java @@ -15,127 +15,105 @@ * @author dcollins * @version $Id: RasterControlPointList.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RasterControlPointList extends java.util.ArrayList implements AVList -{ - public static class ControlPoint extends AVListImpl - { +public class RasterControlPointList extends java.util.ArrayList implements AVList { + + public static class ControlPoint extends AVListImpl { + private final double wx; private final double wy; private final double rx; private final double ry; - public ControlPoint(double worldX, double worldY, double rasterX, double rasterY) - { + public ControlPoint(double worldX, double worldY, double rasterX, double rasterY) { this.wx = worldX; this.wy = worldY; this.rx = rasterX; this.ry = rasterY; } - public java.awt.geom.Point2D getWorldPoint() - { + public java.awt.geom.Point2D getWorldPoint() { return new java.awt.geom.Point2D.Double(this.wx, this.wy); } - public LatLon getWorldPointAsLatLon() - { + public LatLon getWorldPointAsLatLon() { return LatLon.fromDegrees(this.wy, this.wx); } - public java.awt.geom.Point2D getRasterPoint() - { + public java.awt.geom.Point2D getRasterPoint() { return new java.awt.geom.Point2D.Double(this.rx, this.ry); } } private AVList avList = new AVListImpl(); - public RasterControlPointList(java.util.Collection c) - { + public RasterControlPointList(java.util.Collection c) { super(c); } - public RasterControlPointList() - { + public RasterControlPointList() { } - public Object setValue(String key, Object value) - { + public Object setValue(String key, Object value) { return this.avList.setValue(key, value); } - public AVList setValues(AVList avList) - { + public AVList setValues(AVList avList) { return this.avList.setValues(avList); } - public Object getValue(String key) - { + public Object getValue(String key) { return this.avList.getValue(key); } - public Collection getValues() - { + public Collection getValues() { return this.avList.getValues(); } - public String getStringValue(String key) - { + public String getStringValue(String key) { return this.avList.getStringValue(key); } - public Set> getEntries() - { + public Set> getEntries() { return this.avList.getEntries(); } - public boolean hasKey(String key) - { + public boolean hasKey(String key) { return this.avList.hasKey(key); } - public Object removeKey(String key) - { + public Object removeKey(String key) { return this.avList.removeKey(key); } - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { this.avList.addPropertyChangeListener(propertyName, listener); } - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { this.avList.removePropertyChangeListener(propertyName, listener); } - public void addPropertyChangeListener(PropertyChangeListener listener) - { + public void addPropertyChangeListener(PropertyChangeListener listener) { this.avList.addPropertyChangeListener(listener); } - public void removePropertyChangeListener(PropertyChangeListener listener) - { + public void removePropertyChangeListener(PropertyChangeListener listener) { this.avList.removePropertyChangeListener(listener); } - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { this.avList.firePropertyChange(propertyName, oldValue, newValue); } - public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) { this.avList.firePropertyChange(propertyChangeEvent); } - public AVList copy() - { + public AVList copy() { return this.avList.copy(); } - public AVList clearList() - { + public AVList clearList() { return this.avList.clearList(); } } diff --git a/src/gov/nasa/worldwind/util/RayCastingSupport.java b/src/gov/nasa/worldwind/util/RayCastingSupport.java index 011d7d207f..1648468f91 100644 --- a/src/gov/nasa/worldwind/util/RayCastingSupport.java +++ b/src/gov/nasa/worldwind/util/RayCastingSupport.java @@ -10,31 +10,32 @@ /** * Contains methods to resolve ray intersections with the terrain. + * * @author Patrick Murris * @version $Id: RayCastingSupport.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class RayCastingSupport { -public class RayCastingSupport -{ private static double defaultSampleLength = 100; // meters private static double defaultPrecision = 10; // meters /** - * Compute the intersection Position of the globe terrain with the ray starting - * at origin in the given direction. Uses default sample length and result precision. + * Compute the intersection Position of the globe terrain with the ray starting at origin in the given + * direction. Uses default sample length and result precision. + * * @param globe the globe to intersect with. * @param origin origin of the ray. * @param direction direction of the ray. * @return the Position found or null. */ - public static Position intersectRayWithTerrain(Globe globe, Vec4 origin, Vec4 direction) - { + public static Position intersectRayWithTerrain(Globe globe, Vec4 origin, Vec4 direction) { return intersectRayWithTerrain(globe, origin, direction, defaultSampleLength, defaultPrecision); } /** - * Compute the intersection Position of the globe terrain with the ray starting - * at origin in the given direction. Uses the given sample length and result precision. + * Compute the intersection Position of the globe terrain with the ray starting at origin in the given + * direction. Uses the given sample length and result precision. + * * @param globe the globe to intersect with. * @param origin origin of the ray. * @param direction direction of the ray. @@ -43,28 +44,23 @@ public static Position intersectRayWithTerrain(Globe globe, Vec4 origin, Vec4 di * @return the Position found or null. */ public static Position intersectRayWithTerrain(Globe globe, Vec4 origin, Vec4 direction, - double sampleLength, double precision) - { - if (globe == null) - { + double sampleLength, double precision) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (origin == null || direction == null) - { + if (origin == null || direction == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sampleLength < 0) - { + if (sampleLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", sampleLength); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (precision < 0) - { + if (precision < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", precision); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -75,36 +71,34 @@ public static Position intersectRayWithTerrain(Globe globe, Vec4 origin, Vec4 di // Check whether we intersect the globe at it's highest elevation Intersection inters[] = globe.intersect(new Line(origin, direction), globe.getMaxElevation()); - if (inters != null) - { + if (inters != null) { // Sort out intersection points and direction Vec4 p1 = inters[0].getIntersectionPoint(); Vec4 p2 = null; - if (p1.subtract3(origin).dot3(direction) < 0) + if (p1.subtract3(origin).dot3(direction) < 0) { p1 = null; // wrong direction - if (inters.length == 2) - { + } + if (inters.length == 2) { p2 = inters[1].getIntersectionPoint(); - if (p2.subtract3(origin).dot3(direction) < 0) + if (p2.subtract3(origin).dot3(direction) < 0) { p2 = null; // wrong direction + } } - if (p1 == null && p2 == null) // both points in wrong direction + if (p1 == null && p2 == null) // both points in wrong direction + { return null; + } - if (p1 != null && p2 != null) - { + if (p1 != null && p2 != null) { // Outside sphere move to closest point - if (origin.distanceTo3(p1) > origin.distanceTo3(p2)) - { + if (origin.distanceTo3(p1) > origin.distanceTo3(p2)) { // switch p1 and p2 Vec4 temp = p2; p2 = p1; p1 = temp; } - } - else - { + } else { // single point in right direction: inside sphere p2 = p2 == null ? p1 : p2; p1 = origin; @@ -112,29 +106,31 @@ public static Position intersectRayWithTerrain(Globe globe, Vec4 origin, Vec4 di // Sample between p1 and p2 Vec4 point = intersectSegmentWithTerrain(globe, p1, p2, sampleLength, precision); - if (point != null) + if (point != null) { pos = globe.computePositionFromPoint(point); + } } return pos; } /** - * Compute the intersection Vec4 point of the globe terrain with a line segment - * defined between two points. Uses the default sample length and result precision. + * Compute the intersection Vec4 point of the globe terrain with a line segment defined between two + * points. Uses the default sample length and result precision. + * * @param globe the globe to intersect with. * @param p1 segment start point. * @param p2 segment end point. * @return the Vec4 point found or null. */ - public static Vec4 intersectSegmentWithTerrain(Globe globe, Vec4 p1, Vec4 p2) - { + public static Vec4 intersectSegmentWithTerrain(Globe globe, Vec4 p1, Vec4 p2) { return intersectSegmentWithTerrain(globe, p1, p2, defaultSampleLength, defaultPrecision); } /** - * Compute the intersection Vec4 point of the globe terrain with the a segment - * defined between two points. Uses the given sample length and result precision. + * Compute the intersection Vec4 point of the globe terrain with the a segment defined between two + * points. Uses the given sample length and result precision. + * * @param globe the globe to intersect with. * @param p1 segment start point. * @param p2 segment end point. @@ -143,28 +139,23 @@ public static Vec4 intersectSegmentWithTerrain(Globe globe, Vec4 p1, Vec4 p2) * @return the Vec4 point found or null. */ public static Vec4 intersectSegmentWithTerrain(Globe globe, Vec4 p1, Vec4 p2, - double sampleLength, double precision) - { - if (globe == null) - { + double sampleLength, double precision) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (p1 == null || p2 == null) - { + if (p1 == null || p2 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sampleLength < 0) - { + if (sampleLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", sampleLength); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (precision < 0) - { + if (precision < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", precision); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -177,26 +168,25 @@ public static Vec4 intersectSegmentWithTerrain(Globe globe, Vec4 p1, Vec4 p2, double sampledDistance = 0; Vec4 sample = p1; Vec4 lastSample = null; - while (sampledDistance <= rayLength) - { + while (sampledDistance <= rayLength) { Position samplePos = globe.computePositionFromPoint(sample); - if (samplePos.getElevation() <= globe.getElevation(samplePos.getLatitude(), samplePos.getLongitude())) - { + if (samplePos.getElevation() <= globe.getElevation(samplePos.getLatitude(), samplePos.getLongitude())) { // Below ground, intersection found point = sample; break; } - if (sampledDistance >= rayLength) + if (sampledDistance >= rayLength) { break; // break after last sample - // Keep sampling + } // Keep sampling lastSample = sample; sampledDistance = Math.min(sampledDistance + sampleLength, rayLength); sample = ray.getPointAt(sampledDistance); } // Recurse for more precision if needed - if (point != null && sampleLength > precision && lastSample != null) + if (point != null && sampleLength > precision && lastSample != null) { point = intersectSegmentWithTerrain(globe, lastSample, point, sampleLength / 10, precision); + } return point; } diff --git a/src/gov/nasa/worldwind/util/RestorableSupport.java b/src/gov/nasa/worldwind/util/RestorableSupport.java index e109032f22..cc7c978ef2 100644 --- a/src/gov/nasa/worldwind/util/RestorableSupport.java +++ b/src/gov/nasa/worldwind/util/RestorableSupport.java @@ -21,7 +21,7 @@ * stateObject elements. *

          * For example, this document stores four states: the string "Hello World!", the largest value an unsigned byte can - * hold, the value of PI to six digits, and a boolean "true". + * hold, the value of PI to six digits, and a boolean "true". *

            * 
            * {@literal }
          @@ -31,9 +31,8 @@
            *   {@literal 3.141592}
            *   {@literal true}
            * {@literal }
          - *  
          - * 
          - * Callers can create a new RestorableSupport with no state content, or create a RestorableSupport from an + * + * Callers can create a new RestorableSupport with no state content, or create a RestorableSupport from an * existing XML document string. Callers can then add state by name and value, and query state by name. * RestorableSupport provides convenience methods for addding and querying state values as Strings, Integers, Doubles, * and Booleans. @@ -42,8 +41,8 @@ * @version $Id: RestorableSupport.java 1171 2013-02-11 21:45:02Z dcollins $ * @see gov.nasa.worldwind.Restorable */ -public class RestorableSupport -{ +public class RestorableSupport { + protected static final String DEFAULT_DOCUMENT_ELEMENT_TAG_NAME = "restorableState"; protected static final String DEFAULT_STATE_OBJECT_TAG_NAME = "stateObject"; @@ -58,10 +57,8 @@ public class RestorableSupport * * @throws IllegalArgumentException if the document reference is null. */ - protected RestorableSupport(org.w3c.dom.Document doc) - { - if (doc == null) - { + protected RestorableSupport(org.w3c.dom.Document doc) { + if (doc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -82,28 +79,23 @@ protected RestorableSupport(org.w3c.dom.Document doc) * * @throws IllegalArgumentException if the specified element name is null or empty. */ - public static RestorableSupport newRestorableSupport(String documentElementName) - { - if (WWUtil.isEmpty(documentElementName)) - { + public static RestorableSupport newRestorableSupport(String documentElementName) { + if (WWUtil.isEmpty(documentElementName)) { String message = Logging.getMessage("nullValue.DocumentElementNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - javax.xml.parsers.DocumentBuilderFactory docBuilderFactory = - javax.xml.parsers.DocumentBuilderFactory.newInstance(); + javax.xml.parsers.DocumentBuilderFactory docBuilderFactory + = javax.xml.parsers.DocumentBuilderFactory.newInstance(); - try - { + try { javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); org.w3c.dom.Document doc = docBuilder.newDocument(); // Create the "restorableState" document root element. createDocumentElement(doc, documentElementName); return new RestorableSupport(doc); - } - catch (javax.xml.parsers.ParserConfigurationException e) - { + } catch (javax.xml.parsers.ParserConfigurationException e) { String message = Logging.getMessage("generic.ExceptionCreatingParser"); Logging.logger().severe(message); throw new IllegalStateException(message, e); @@ -115,8 +107,7 @@ public static RestorableSupport newRestorableSupport(String documentElementName) * * @return a new, empty RestorableSupport instance. */ - public static RestorableSupport newRestorableSupport() - { + public static RestorableSupport newRestorableSupport() { return newRestorableSupport(DEFAULT_DOCUMENT_ELEMENT_TAG_NAME); } @@ -128,70 +119,58 @@ public static RestorableSupport newRestorableSupport() * @return a new RestorableSupport instance with the specified state. * * @throws IllegalArgumentException If stateInXml is null, or the its contents are not a well formed - * XML document. + * XML document. */ - public static RestorableSupport parse(String stateInXml) - { - if (stateInXml == null) - { + public static RestorableSupport parse(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - javax.xml.parsers.DocumentBuilderFactory docBuilderFactory = - javax.xml.parsers.DocumentBuilderFactory.newInstance(); + javax.xml.parsers.DocumentBuilderFactory docBuilderFactory + = javax.xml.parsers.DocumentBuilderFactory.newInstance(); - try - { + try { javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); org.w3c.dom.Document doc = docBuilder.parse( - new org.xml.sax.InputSource(new java.io.StringReader(stateInXml))); + new org.xml.sax.InputSource(new java.io.StringReader(stateInXml))); return new RestorableSupport(doc); - } - catch (java.io.IOException e) - { + } catch (java.io.IOException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); throw new IllegalArgumentException(message, e); - } - catch (org.xml.sax.SAXException e) - { + } catch (org.xml.sax.SAXException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); throw new IllegalArgumentException(message, e); - } - catch (javax.xml.parsers.ParserConfigurationException e) - { + } catch (javax.xml.parsers.ParserConfigurationException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); throw new IllegalStateException(message, e); } } - protected org.w3c.dom.Element getDocumentElement() - { + protected org.w3c.dom.Element getDocumentElement() { return this.doc.getDocumentElement(); } - protected static void createDocumentElement(org.w3c.dom.Document doc, String tagName) - { - if (doc == null) - { + protected static void createDocumentElement(org.w3c.dom.Document doc, String tagName) { + if (doc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (tagName == null) - { + if (tagName == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Document already has a root element. - if (doc.getDocumentElement() != null) + if (doc.getDocumentElement() != null) { return; + } org.w3c.dom.Element elem = doc.createElement(tagName); doc.appendChild(elem); @@ -203,30 +182,24 @@ protected static void createDocumentElement(org.w3c.dom.Document doc, String tag * * @return an XML state document string. */ - public String getStateAsXml() - { - javax.xml.transform.TransformerFactory transformerFactory = - javax.xml.transform.TransformerFactory.newInstance(); - try - { + public String getStateAsXml() { + javax.xml.transform.TransformerFactory transformerFactory + = javax.xml.transform.TransformerFactory.newInstance(); + try { // The StringWriter will receive the document xml. java.io.StringWriter stringWriter = new java.io.StringWriter(); // Attempt to write the Document to the StringWriter. javax.xml.transform.Transformer transformer = transformerFactory.newTransformer(); transformer.transform( - new javax.xml.transform.dom.DOMSource(this.doc), - new javax.xml.transform.stream.StreamResult(stringWriter)); + new javax.xml.transform.dom.DOMSource(this.doc), + new javax.xml.transform.stream.StreamResult(stringWriter)); // If successful, return the StringWriter contents as a String. return stringWriter.toString(); - } - catch (javax.xml.transform.TransformerConfigurationException e) - { + } catch (javax.xml.transform.TransformerConfigurationException e) { String message = Logging.getMessage("generic.ExceptionWritingXml"); Logging.logger().severe(message); return null; - } - catch (javax.xml.transform.TransformerException e) - { + } catch (javax.xml.transform.TransformerException e) { String message = Logging.getMessage("generic.ExceptionWritingXml"); Logging.logger().severe(message); return null; @@ -239,8 +212,7 @@ public String getStateAsXml() * * @return an XML state document string. */ - public String toString() - { + public String toString() { return getStateAsXml(); } @@ -250,14 +222,12 @@ public String toString() * stateObject can be queried or set through StateObject. This also serves as a context through which * nested stateObjects can be found or created. */ - public static class StateObject - { + public static class StateObject { + final org.w3c.dom.Element elem; - public StateObject(org.w3c.dom.Element element) - { - if (element == null) - { + public StateObject(org.w3c.dom.Element element) { + if (element == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -271,8 +241,7 @@ public StateObject(org.w3c.dom.Element element) * * @return this StateObject's name. */ - public String getName() - { + public String getName() { return this.elem.getAttribute("name"); } @@ -283,10 +252,8 @@ public String getName() * * @throws IllegalArgumentException If name is null. */ - public void setName(String name) - { - if (name == null) - { + public void setName(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -302,8 +269,7 @@ public void setName(String name) * * @return the value of this StateObject as a String. */ - public String getValue() - { + public String getValue() { return this.elem.getTextContent(); } @@ -315,10 +281,8 @@ public String getValue() * * @throws IllegalArgumentException If value is null. */ - public void setValue(String value) - { - if (value == null) - { + public void setValue(String value) { + if (value == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -333,8 +297,7 @@ public void setValue(String value) * * @return String for the document element name. */ - public String getDocumentElementTagName() - { + public String getDocumentElementTagName() { return getDocumentElement().getTagName(); } @@ -345,8 +308,7 @@ public String getDocumentElementTagName() * * @return String to be used for each state object's tag name */ - public String getStateObjectTagName() - { + public String getStateObjectTagName() { return this.stateObjectTagName; } @@ -359,10 +321,8 @@ public String getStateObjectTagName() * * @throws IllegalArgumentException If stateObjectTagName is null. */ - public void setStateObjectTagName(String stateObjectTagName) - { - if (stateObjectTagName == null) - { + public void setStateObjectTagName(String stateObjectTagName) { + if (stateObjectTagName == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -371,10 +331,8 @@ public void setStateObjectTagName(String stateObjectTagName) this.stateObjectTagName = stateObjectTagName; } - protected StateObject findStateObject(org.w3c.dom.Node context, String name) - { - if (name == null) - { + protected StateObject findStateObject(org.w3c.dom.Node context, String name) { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -382,31 +340,27 @@ protected StateObject findStateObject(org.w3c.dom.Node context, String name) // Search for the state element with the specified name. String expression = String.format("%s[@name=\"%s\"]", getStateObjectTagName(), name); - try - { + try { Object result = this.xpath.evaluate( - expression, - // If non-null, search from the specified context. Otherwise, search from the - // document root element. - (context != null ? context : getDocumentElement()), - javax.xml.xpath.XPathConstants.NODE); - if (result == null) + expression, + // If non-null, search from the specified context. Otherwise, search from the + // document root element. + (context != null ? context : getDocumentElement()), + javax.xml.xpath.XPathConstants.NODE); + if (result == null) { return null; + } // If the result is an Element node, return a new StateObject with the result as its content. // Otherwise return null. return (result instanceof org.w3c.dom.Element) ? new StateObject((org.w3c.dom.Element) result) : null; - } - catch (javax.xml.xpath.XPathExpressionException e) - { + } catch (javax.xml.xpath.XPathExpressionException e) { return null; } } - protected StateObject[] findAllStateObjects(org.w3c.dom.Node context, String name) - { - if (name == null) - { + protected StateObject[] findAllStateObjects(org.w3c.dom.Node context, String name) { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -414,61 +368,52 @@ protected StateObject[] findAllStateObjects(org.w3c.dom.Node context, String nam // Search for the state elements beneath the context with the specified name. String expression; - if (name.length() != 0) + if (name.length() != 0) { expression = String.format("%s[@name=\"%s\"]", getStateObjectTagName(), name); - else + } else { expression = String.format("%s//.", getStateObjectTagName()); + } - try - { + try { Object result = this.xpath.evaluate( - expression, - // If non-null, search from the specified context. Otherwise, search from the - // document root element. - (context != null ? context : getDocumentElement()), - javax.xml.xpath.XPathConstants.NODESET); + expression, + // If non-null, search from the specified context. Otherwise, search from the + // document root element. + (context != null ? context : getDocumentElement()), + javax.xml.xpath.XPathConstants.NODESET); if (result == null - || !(result instanceof org.w3c.dom.NodeList) - || ((org.w3c.dom.NodeList) result).getLength() == 0) - { + || !(result instanceof org.w3c.dom.NodeList) + || ((org.w3c.dom.NodeList) result).getLength() == 0) { return null; } // If the result is a NodeList, return an array of StateObjects for each Element node in that list. org.w3c.dom.NodeList nodeList = (org.w3c.dom.NodeList) result; ArrayList stateObjectList = new ArrayList(); - for (int i = 0; i < nodeList.getLength(); i++) - { + for (int i = 0; i < nodeList.getLength(); i++) { org.w3c.dom.Node node = nodeList.item(i); - if (node instanceof org.w3c.dom.Element) - { + if (node instanceof org.w3c.dom.Element) { stateObjectList.add(new StateObject((org.w3c.dom.Element) node)); } } StateObject[] stateObjectArray = new StateObject[stateObjectList.size()]; stateObjectList.toArray(stateObjectArray); return stateObjectArray; - } - catch (javax.xml.xpath.XPathExpressionException e) - { + } catch (javax.xml.xpath.XPathExpressionException e) { return null; } } - protected StateObject[] extractStateObjects(org.w3c.dom.Element context) - { + protected StateObject[] extractStateObjects(org.w3c.dom.Element context) { org.w3c.dom.NodeList nodeList = (context != null ? context : getDocumentElement()).getChildNodes(); ArrayList stateObjectList = new ArrayList(); - if (nodeList != null) - { - for (int i = 0; i < nodeList.getLength(); i++) - { + if (nodeList != null) { + for (int i = 0; i < nodeList.getLength(); i++) { org.w3c.dom.Node node = nodeList.item(i); if (node instanceof org.w3c.dom.Element - && node.getNodeName() != null - && node.getNodeName().equals(getStateObjectTagName())) - { + && node.getNodeName() != null + && node.getNodeName().equals(getStateObjectTagName())) { stateObjectList.add(new StateObject((org.w3c.dom.Element) node)); } } @@ -479,28 +424,27 @@ protected StateObject[] extractStateObjects(org.w3c.dom.Element context) return stateObjectArray; } - protected StateObject createStateObject(org.w3c.dom.Element context, String name, String value) - { + protected StateObject createStateObject(org.w3c.dom.Element context, String name, String value) { return createStateObject(context, name, value, false); } - protected StateObject createStateObject(org.w3c.dom.Element context, String name, String value, boolean escapeValue) - { + protected StateObject createStateObject(org.w3c.dom.Element context, String name, String value, boolean escapeValue) { org.w3c.dom.Element elem = this.doc.createElement(getStateObjectTagName()); // If non-null, name goes in an attribute entitled "name". - if (name != null) + if (name != null) { elem.setAttribute("name", name); + } // If non-null, value goes in the element text content. - if (value != null) - { + if (value != null) { // If escapeValue is true, we place value in a CDATA node beneath elem. - if (escapeValue) + if (escapeValue) { elem.appendChild(this.doc.createCDATASection(value)); - // Otherwise, just set the text value of elem normally. - else + } // Otherwise, just set the text value of elem normally. + else { elem.setTextContent(value); + } } // If non-null, add the StateObject element to the specified context. Otherwise, add it to the @@ -510,10 +454,8 @@ protected StateObject createStateObject(org.w3c.dom.Element context, String name return new StateObject(elem); } - protected boolean containsElement(org.w3c.dom.Element elem) - { - if (elem == null) - { + protected boolean containsElement(org.w3c.dom.Element elem) { + if (elem == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -532,10 +474,8 @@ protected boolean containsElement(org.w3c.dom.Element elem) * * @throws IllegalArgumentException If name is null. */ - public StateObject getStateObject(String name) - { - if (name == null) - { + public StateObject getStateObject(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -550,23 +490,20 @@ public StateObject getStateObject(String name) * directly beneath the document root. If no StateObject with that name exists, this method returns null. * * @param context StateObject context to search, or null to search the document root. - * @param name the StateObject name to search for. + * @param name the StateObject name to search for. * * @return the StateObject instance, or null if none exists. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public StateObject getStateObject(StateObject context, String name) - { - if (context != null && !containsElement(context.elem)) - { + public StateObject getStateObject(StateObject context, String name) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -585,12 +522,10 @@ public StateObject getStateObject(StateObject context, String name) * @return an array of the StateObject instances, which has zero length if none exist. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public StateObject[] getAllStateObjects(StateObject context) - { - if (context != null && !containsElement(context.elem)) - { + public StateObject[] getAllStateObjects(StateObject context) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -609,10 +544,8 @@ public StateObject[] getAllStateObjects(StateObject context) * * @throws IllegalArgumentException If name is null. */ - public StateObject[] getAllStateObjects(String name) - { - if (name == null) - { + public StateObject[] getAllStateObjects(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -628,23 +561,20 @@ public StateObject[] getAllStateObjects(String name) * StateObject array with zero length. * * @param context StateObject context to search, or null to search the document root. - * @param name the StateObject name to search for. + * @param name the StateObject name to search for. * * @return an array of the StateObject instances, which has zero length if none exist. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public StateObject[] getAllStateObjects(StateObject context, String name) - { - if (context != null && !containsElement(context.elem)) - { + public StateObject[] getAllStateObjects(StateObject context, String name) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -663,10 +593,8 @@ public StateObject[] getAllStateObjects(StateObject context, String name) * * @throws IllegalArgumentException If name is null. */ - public StateObject addStateObject(String name) - { - if (name == null) - { + public StateObject addStateObject(String name) { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -682,24 +610,21 @@ public StateObject addStateObject(String name) * created. * * @param context the StateObject under which the new StateObject is created, or null to place it under the document - * root. - * @param name the new StateObject's name. + * root. + * @param name the new StateObject's name. * * @return the new StateObject instance. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public StateObject addStateObject(StateObject context, String name) - { - if (context != null && !containsElement(context.elem)) - { + public StateObject addStateObject(StateObject context, String name) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -709,10 +634,15 @@ public StateObject addStateObject(StateObject context, String name) return createStateObject(context != null ? context.elem : null, name, null); } - /*************************************************************************************************************/ - /** Convenience methods for adding and querying state values. **/ - /*************************************************************************************************************/ - + /** + * ********************************************************************************************************** + */ + /** + * Convenience methods for adding and querying state values. * + */ + /** + * ********************************************************************************************************** + */ /** * Returns the value of the StateObject as a String. * @@ -721,18 +651,15 @@ public StateObject addStateObject(StateObject context, String name) * @return the value of the StateObject as a String. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public String getStateObjectAsString(StateObject stateObject) - { - if (stateObject == null) - { + public String getStateObjectAsString(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -752,8 +679,7 @@ public String getStateObjectAsString(StateObject stateObject) * * @throws IllegalArgumentException If name is null. */ - public String getStateValueAsString(String name) - { + public String getStateValueAsString(String name) { return getStateValueAsString(null, name); } @@ -764,18 +690,18 @@ public String getStateValueAsString(String name) * value of that StateObject is not a String, this method returns null. * * @param context StateObject context to search, or null to search the document root. - * @param name the StateObject name to search for. + * @param name the StateObject name to search for. * * @return the value of the StateObject as a String, or null if none exists. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public String getStateValueAsString(StateObject context, String name) - { + public String getStateValueAsString(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsString(stateObject); } @@ -788,20 +714,17 @@ public String getStateValueAsString(StateObject context, String name) * @return the value of the StateObject as an Integer. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public Integer getStateObjectAsInteger(StateObject stateObject) - { + public Integer getStateObjectAsInteger(StateObject stateObject) { String stringValue = getStateObjectAsString(stateObject); - if (stringValue == null) + if (stringValue == null) { return null; + } - try - { + try { return Integer.valueOf(stringValue); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", stringValue); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -819,8 +742,7 @@ public Integer getStateObjectAsInteger(StateObject stateObject) * * @throws IllegalArgumentException If name is null. */ - public Integer getStateValueAsInteger(String name) - { + public Integer getStateValueAsInteger(String name) { return getStateValueAsInteger(null, name); } @@ -831,18 +753,18 @@ public Integer getStateValueAsInteger(String name) * value of that StateObject is not an Integer, this method returns null. * * @param context StateObject context to search, or null to search the document root. - * @param name the StateObject name to search for. + * @param name the StateObject name to search for. * * @return the value of the StateObject as an Integer, or null if none exists. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public Integer getStateValueAsInteger(StateObject context, String name) - { + public Integer getStateValueAsInteger(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsInteger(stateObject); } @@ -855,20 +777,17 @@ public Integer getStateValueAsInteger(StateObject context, String name) * @return the value of the StateObject as a Double. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public Double getStateObjectAsDouble(StateObject stateObject) - { + public Double getStateObjectAsDouble(StateObject stateObject) { String stringValue = getStateObjectAsString(stateObject); - if (stringValue == null) + if (stringValue == null) { return null; + } - try - { + try { return Double.valueOf(stringValue); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", stringValue); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -886,8 +805,7 @@ public Double getStateObjectAsDouble(StateObject stateObject) * * @throws IllegalArgumentException If name is null. */ - public Double getStateValueAsDouble(String name) - { + public Double getStateValueAsDouble(String name) { return getStateValueAsDouble(null, name); } @@ -898,18 +816,18 @@ public Double getStateValueAsDouble(String name) * that StateObject is not a Double, this method returns null. * * @param context StateObject context to search, or null to search the document root. - * @param name the StateObject name to search for. + * @param name the StateObject name to search for. * * @return the value of the StateObject as a Double, or null if none exists. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public Double getStateValueAsDouble(StateObject context, String name) - { + public Double getStateValueAsDouble(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsDouble(stateObject); } @@ -922,20 +840,17 @@ public Double getStateValueAsDouble(StateObject context, String name) * @return the value of the StateObject as a Long. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public Long getStateObjectAsLong(StateObject stateObject) - { + public Long getStateObjectAsLong(StateObject stateObject) { String stringValue = getStateObjectAsString(stateObject); - if (stringValue == null) + if (stringValue == null) { return null; + } - try - { + try { return Long.valueOf(stringValue); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", stringValue); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -953,8 +868,7 @@ public Long getStateObjectAsLong(StateObject stateObject) * * @throws IllegalArgumentException If name is null. */ - public Long getStateValueAsLong(String name) - { + public Long getStateValueAsLong(String name) { return getStateValueAsLong(null, name); } @@ -965,18 +879,18 @@ public Long getStateValueAsLong(String name) * value of that StateObject is not a Double, this method returns null. * * @param context StateObject context to search, or null to search the document root. - * @param name the StateObject name to search for. + * @param name the StateObject name to search for. * * @return the value of the StateObject as a Long, or null if none exists. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public Long getStateValueAsLong(StateObject context, String name) - { + public Long getStateValueAsLong(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsLong(stateObject); } @@ -989,20 +903,17 @@ public Long getStateValueAsLong(StateObject context, String name) * @return the value of the StateObject as a Float. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public Float getStateObjectAsFloat(StateObject stateObject) - { + public Float getStateObjectAsFloat(StateObject stateObject) { String stringValue = getStateObjectAsString(stateObject); - if (stringValue == null) + if (stringValue == null) { return null; + } - try - { + try { return Float.valueOf(stringValue); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", stringValue); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1020,8 +931,7 @@ public Float getStateObjectAsFloat(StateObject stateObject) * * @throws IllegalArgumentException If name is null. */ - public Float getStateValueAsFloat(String name) - { + public Float getStateValueAsFloat(String name) { return getStateValueAsFloat(null, name); } @@ -1032,18 +942,18 @@ public Float getStateValueAsFloat(String name) * that StateObject is not a Float, this method returns null. * * @param context StateObject context to search, or null to search the document root. - * @param name the StateObject name to search for. + * @param name the StateObject name to search for. * * @return the value of the StateObject as a Float, or null if none exists. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public Float getStateValueAsFloat(StateObject context, String name) - { + public Float getStateValueAsFloat(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsFloat(stateObject); } @@ -1057,20 +967,17 @@ public Float getStateValueAsFloat(StateObject context, String name) * @return the value of the StateObject as a Boolean. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public Boolean getStateObjectAsBoolean(StateObject stateObject) - { + public Boolean getStateObjectAsBoolean(StateObject stateObject) { String stringValue = getStateObjectAsString(stateObject); - if (stringValue == null) + if (stringValue == null) { return null; + } - try - { + try { return Boolean.valueOf(stringValue); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", stringValue); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1089,8 +996,7 @@ public Boolean getStateObjectAsBoolean(StateObject stateObject) * * @throws IllegalArgumentException If name is null. */ - public Boolean getStateValueAsBoolean(String name) - { + public Boolean getStateValueAsBoolean(String name) { return getStateValueAsBoolean(null, name); } @@ -1102,18 +1008,18 @@ public Boolean getStateValueAsBoolean(String name) * value to Boolean.valueOf. * * @param context StateObject context to search, or null to search the document root. - * @param name the StateObject name to search for. + * @param name the StateObject name to search for. * * @return the value of the StateObject as a Boolean, or null if none exists. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public Boolean getStateValueAsBoolean(StateObject context, String name) - { + public Boolean getStateValueAsBoolean(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsBoolean(stateObject); } @@ -1126,18 +1032,15 @@ public Boolean getStateValueAsBoolean(StateObject context, String name) * @return the value of the StateObject as a LatLon. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public LatLon getStateObjectAsLatLon(StateObject stateObject) - { - if (stateObject == null) - { + public LatLon getStateObjectAsLatLon(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1145,8 +1048,7 @@ public LatLon getStateObjectAsLatLon(StateObject stateObject) Double lat = getStateValueAsDouble(stateObject, "latitudeDegrees"); Double lon = getStateValueAsDouble(stateObject, "longitudeDegrees"); - if (lat == null || lon == null) - { + if (lat == null || lon == null) { String message = Logging.getMessage("generic.ConversionError", stateObject.getName()); Logging.logger().log(java.util.logging.Level.SEVERE, message); return null; @@ -1155,16 +1057,15 @@ public LatLon getStateObjectAsLatLon(StateObject stateObject) return LatLon.fromDegrees(lat, lon); } - public LatLon getStateValueAsLatLon(String name) - { + public LatLon getStateValueAsLatLon(String name) { return getStateValueAsLatLon(null, name); } - public LatLon getStateValueAsLatLon(StateObject context, String name) - { + public LatLon getStateValueAsLatLon(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsLatLon(stateObject); } @@ -1177,18 +1078,15 @@ public LatLon getStateValueAsLatLon(StateObject context, String name) * @return the value of the StateObject as a Position. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public Position getStateObjectAsPosition(StateObject stateObject) - { - if (stateObject == null) - { + public Position getStateObjectAsPosition(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1197,8 +1095,7 @@ public Position getStateObjectAsPosition(StateObject stateObject) Double lat = getStateValueAsDouble(stateObject, "latitudeDegrees"); Double lon = getStateValueAsDouble(stateObject, "longitudeDegrees"); Double elevation = getStateValueAsDouble(stateObject, "elevation"); - if (lat == null || lon == null || elevation == null) - { + if (lat == null || lon == null || elevation == null) { String message = Logging.getMessage("generic.ConversionError", stateObject.getName()); Logging.logger().log(java.util.logging.Level.SEVERE, message); return null; @@ -1207,16 +1104,15 @@ public Position getStateObjectAsPosition(StateObject stateObject) return Position.fromDegrees(lat, lon, elevation); } - public Position getStateValueAsPosition(String name) - { + public Position getStateValueAsPosition(String name) { return getStateValueAsPosition(null, name); } - public Position getStateValueAsPosition(StateObject context, String name) - { + public Position getStateValueAsPosition(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsPosition(stateObject); } @@ -1229,52 +1125,48 @@ public Position getStateValueAsPosition(StateObject context, String name) * @return the value of the StateObject as a List of LatLons. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public List getStateObjectAsLatLonList(StateObject stateObject) - { - if (stateObject == null) - { + public List getStateObjectAsLatLonList(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject[] llsos = getAllStateObjects(stateObject, "location"); - if (llsos == null || llsos.length == 0) + if (llsos == null || llsos.length == 0) { return null; + } ArrayList outList = new ArrayList(llsos.length); - for (RestorableSupport.StateObject llso : llsos) - { - if (llso != null) - { + for (RestorableSupport.StateObject llso : llsos) { + if (llso != null) { LatLon ll = getStateObjectAsLatLon(llso); - if (ll != null) + if (ll != null) { outList.add(ll); + } } } return outList; } - public List getStateValueAsLatLonList(String name) - { + public List getStateValueAsLatLonList(String name) { return getStateValueAsLatLonList(null, name); } - public List getStateValueAsLatLonList(StateObject context, String name) - { + public List getStateValueAsLatLonList(StateObject context, String name) { RestorableSupport.StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsLatLonList(stateObject); } @@ -1287,38 +1179,34 @@ public List getStateValueAsLatLonList(StateObject context, String name) * @return the value of the StateObject as a HashMap of <Integer, OffsetsList> pairs. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - - public HashMap getStateObjectAsOffsetsList(StateObject stateObject) - { - if (stateObject == null) - { + public HashMap getStateObjectAsOffsetsList(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject[] offsetsLists = getAllStateObjects(stateObject, "face"); - if (offsetsLists == null || offsetsLists.length == 0) + if (offsetsLists == null || offsetsLists.length == 0) { return null; + } HashMap outList = new HashMap(); int index = 0; - for (RestorableSupport.StateObject faceOffsets : offsetsLists) - { - if (faceOffsets != null) - { + for (RestorableSupport.StateObject faceOffsets : offsetsLists) { + if (faceOffsets != null) { OffsetsList offsets = getStateObjectAsOffsets(faceOffsets); - if (offsets != null) + if (offsets != null) { outList.put(index, offsets); + } } index++; } @@ -1326,16 +1214,15 @@ public HashMap getStateObjectAsOffsetsList(StateObject sta return outList; } - public HashMap getStateValueAsOffsetsList(String name) - { + public HashMap getStateValueAsOffsetsList(String name) { return getStateValueAsOffsetsList(null, name); } - public HashMap getStateValueAsOffsetsList(StateObject context, String name) - { + public HashMap getStateValueAsOffsetsList(StateObject context, String name) { RestorableSupport.StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsOffsetsList(stateObject); } @@ -1348,19 +1235,15 @@ public HashMap getStateValueAsOffsetsList(StateObject cont * @return the value of the StateObject as a OffsetsList. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - - public OffsetsList getStateObjectAsOffsets(StateObject stateObject) - { - if (stateObject == null) - { + public OffsetsList getStateObjectAsOffsets(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1371,8 +1254,7 @@ public OffsetsList getStateObjectAsOffsets(StateObject stateObject) float[] lowerLeftOffset = getStateValueAsOffsetPair(stateObject, "lowerLeftOffset"); float[] lowerRightOffset = getStateValueAsOffsetPair(stateObject, "lowerRightOffset"); - if (upperLeftOffset == null || upperRightOffset == null || lowerLeftOffset == null || lowerRightOffset == null) - { + if (upperLeftOffset == null || upperRightOffset == null || lowerLeftOffset == null || lowerRightOffset == null) { String message = Logging.getMessage("generic.ConversionError", stateObject.getName()); Logging.logger().log(java.util.logging.Level.SEVERE, message); return null; @@ -1388,16 +1270,15 @@ public OffsetsList getStateObjectAsOffsets(StateObject stateObject) return offsets; } - public OffsetsList getStateValueAsOffsets(String name) - { + public OffsetsList getStateValueAsOffsets(String name) { return getStateValueAsOffsets(null, name); } - public OffsetsList getStateValueAsOffsets(StateObject context, String name) - { + public OffsetsList getStateValueAsOffsets(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsOffsets(stateObject); } @@ -1410,19 +1291,15 @@ public OffsetsList getStateValueAsOffsets(StateObject context, String name) * @return the value of the StateObject as a float[]. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - - public float[] getStateObjectAsOffsetPair(StateObject stateObject) - { - if (stateObject == null) - { + public float[] getStateObjectAsOffsetPair(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1431,29 +1308,27 @@ public float[] getStateObjectAsOffsetPair(StateObject stateObject) Float uOffset = getStateValueAsFloat(stateObject, "uOffset"); Float vOffset = getStateValueAsFloat(stateObject, "vOffset"); - if (uOffset == null || vOffset == null) - { + if (uOffset == null || vOffset == null) { String message = Logging.getMessage("generic.ConversionError", stateObject.getName()); Logging.logger().log(java.util.logging.Level.SEVERE, message); return null; } float[] offsetPair; - offsetPair = new float[] {uOffset, vOffset}; + offsetPair = new float[]{uOffset, vOffset}; return offsetPair; } - public float[] getStateValueAsOffsetPair(String name) - { + public float[] getStateValueAsOffsetPair(String name) { return getStateValueAsOffsetPair(null, name); } - public float[] getStateValueAsOffsetPair(StateObject context, String name) - { + public float[] getStateValueAsOffsetPair(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsOffsetPair(stateObject); } @@ -1467,40 +1342,36 @@ public float[] getStateValueAsOffsetPair(StateObject context, String name) * @return the value of the StateObject as a HashMap of <Integer, Object> pairs. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - - public HashMap getStateObjectAsImageSourceList(StateObject stateObject) - { - if (stateObject == null) - { + public HashMap getStateObjectAsImageSourceList(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject[] imageSourceList = getAllStateObjects(stateObject, "imageSource"); - if (imageSourceList == null || imageSourceList.length == 0) + if (imageSourceList == null || imageSourceList.length == 0) { return null; + } HashMap outList = new HashMap(); int index = 0; - for (RestorableSupport.StateObject imageSource : imageSourceList) - { - if (imageSource != null) - { + for (RestorableSupport.StateObject imageSource : imageSourceList) { + if (imageSource != null) { String path = getStateObjectAsString(imageSource); - if (path != null) + if (path != null) { outList.put(index, path); - else + } else { outList.put(index, null); + } } index++; } @@ -1508,16 +1379,15 @@ public HashMap getStateObjectAsImageSourceList(StateObject stat return outList; } - public HashMap getStateValueAsImageSourceList(String name) - { + public HashMap getStateValueAsImageSourceList(String name) { return getStateValueAsImageSourceList(null, name); } - public HashMap getStateValueAsImageSourceList(StateObject context, String name) - { + public HashMap getStateValueAsImageSourceList(StateObject context, String name) { RestorableSupport.StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsImageSourceList(stateObject); } @@ -1530,18 +1400,15 @@ public HashMap getStateValueAsImageSourceList(StateObject conte * @return the value of the StateObject as a Sector. * * @throws IllegalArgumentException If stateObject is null, or does not belong to this - * RestorableSupport. + * RestorableSupport. */ - public Sector getStateObjectAsSector(StateObject stateObject) - { - if (stateObject == null) - { + public Sector getStateObjectAsSector(StateObject stateObject) { + if (stateObject == null) { String message = Logging.getMessage("nullValue.StateObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!containsElement(stateObject.elem)) - { + if (!containsElement(stateObject.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1551,8 +1418,7 @@ public Sector getStateObjectAsSector(StateObject stateObject) Double maxLat = getStateValueAsDouble(stateObject, "maxLatitudeDegrees"); Double minLon = getStateValueAsDouble(stateObject, "minLongitudeDegrees"); Double maxLon = getStateValueAsDouble(stateObject, "maxLongitudeDegrees"); - if (minLat == null || maxLat == null || minLon == null || maxLon == null) - { + if (minLat == null || maxLat == null || minLon == null || maxLon == null) { String message = Logging.getMessage("generic.ConversionError", stateObject.getName()); Logging.logger().log(java.util.logging.Level.SEVERE, message); return null; @@ -1561,34 +1427,33 @@ public Sector getStateObjectAsSector(StateObject stateObject) return Sector.fromDegrees(minLat, maxLat, minLon, maxLon); } - public Sector getStateValueAsSector(String name) - { + public Sector getStateValueAsSector(String name) { return this.getStateValueAsSector(null, name); } - public Sector getStateValueAsSector(StateObject context, String name) - { + public Sector getStateValueAsSector(StateObject context, String name) { RestorableSupport.StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsSector(stateObject); } - public java.awt.Color getStateObjectAsColor(StateObject stateObject) - { + public java.awt.Color getStateObjectAsColor(StateObject stateObject) { String stringValue = getStateObjectAsString(stateObject); - if (stringValue == null) + if (stringValue == null) { return null; + } return decodeColor(stringValue); } - public Color getStateValueAsColor(StateObject context, String name) - { + public Color getStateValueAsColor(StateObject context, String name) { StateObject stateObject = getStateObject(context, name); - if (stateObject == null) + if (stateObject == null) { return null; + } return getStateObjectAsColor(stateObject); } @@ -1597,13 +1462,12 @@ public Color getStateValueAsColor(StateObject context, String name) * Adds a new StateObject with the specified name and String value. The new StateObject is * placed beneath the document root. If a StateObject with this name already exists, a new one is still created. * - * @param name the new StateObject's name. + * @param name the new StateObject's name. * @param value the new StateObject's String value. * * @throws IllegalArgumentException If either name or value is null. */ - public void addStateValueAsString(String name, String value) - { + public void addStateValueAsString(String name, String value) { addStateValueAsString(null, name, value, false); } @@ -1614,14 +1478,13 @@ public void addStateValueAsString(String name, String value) * special processing is performed on value. Once value has been escaped and added, it can * be extracted exactly like any other String value. * - * @param name the new StateObject's name. - * @param value the new StateObject's String value. + * @param name the new StateObject's name. + * @param value the new StateObject's String value. * @param escapeValue whether to escape the String value or not. * * @throws IllegalArgumentException If either name or value is null. */ - public void addStateValueAsString(String name, String value, boolean escapeValue) - { + public void addStateValueAsString(String name, String value, boolean escapeValue) { addStateValueAsString(null, name, value, escapeValue); } @@ -1632,15 +1495,14 @@ public void addStateValueAsString(String name, String value, boolean escapeValue * StateObject with this name already exists, a new one is still created. * * @param context the StateObject context under which the new StateObject is created, or null to place it under the - * document root. - * @param name the new StateObject's name. - * @param value the new StateObject's String value. + * document root. + * @param name the new StateObject's name. + * @param value the new StateObject's String value. * * @throws IllegalArgumentException If either name or value is null, or if - * context is not null and does not belong to this RestorableSupport. + * context is not null and does not belong to this RestorableSupport. */ - public void addStateValueAsString(StateObject context, String name, String value) - { + public void addStateValueAsString(StateObject context, String name, String value) { addStateValueAsString(context, name, value, false); } @@ -1653,25 +1515,22 @@ public void addStateValueAsString(StateObject context, String name, String value * value. Once value has been escaped and added, it can be extracted exactly like any * other String value. * - * @param context the StateObject context under which the new StateObject is created, or null to place it under - * the document root. - * @param name the new StateObject's name. - * @param value the new StateObject's String value. + * @param context the StateObject context under which the new StateObject is created, or null to place it under the + * document root. + * @param name the new StateObject's name. + * @param value the new StateObject's String value. * @param escapeValue whether to escape the String value or not. * * @throws IllegalArgumentException If either name or value is null, or if - * context is not null and does not belong to this RestorableSupport. + * context is not null and does not belong to this RestorableSupport. */ - public void addStateValueAsString(StateObject context, String name, String value, boolean escapeValue) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsString(StateObject context, String name, String value, boolean escapeValue) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null || value == null) - { + if (name == null || value == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1684,13 +1543,12 @@ public void addStateValueAsString(StateObject context, String name, String value * Adds a new StateObject with the specified name and Integer value. The new StateObject * is placed beneath the document root. If a StateObject with this name already exists, a new one is still created. * - * @param name the new StateObject's name. + * @param name the new StateObject's name. * @param intValue the new StateObject's Integer value. * * @throws IllegalArgumentException If name is null. */ - public void addStateValueAsInteger(String name, int intValue) - { + public void addStateValueAsInteger(String name, int intValue) { addStateValueAsInteger(null, name, intValue); } @@ -1700,24 +1558,21 @@ public void addStateValueAsInteger(String name, int intValue) * context. Otherwise, the new StateObject is placed directly beneath the document root. If a * StateObject with this name already exists, a new one is still created. * - * @param context the StateObject context under which the new StateObject is created, or null to place it under the - * document root. - * @param name the new StateObject's name. + * @param context the StateObject context under which the new StateObject is created, or null to place it under the + * document root. + * @param name the new StateObject's name. * @param intValue the new StateObject's Integer value. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public void addStateValueAsInteger(StateObject context, String name, int intValue) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsInteger(StateObject context, String name, int intValue) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1730,13 +1585,12 @@ public void addStateValueAsInteger(StateObject context, String name, int intValu * Adds a new StateObject with the specified name and Double value. The new StateObject is * placed beneath the document root. If a StateObject with this name already exists, a new one is still created. * - * @param name the new StateObject's name. + * @param name the new StateObject's name. * @param doubleValue the new StateObject's Double value. * * @throws IllegalArgumentException If name is null. */ - public void addStateValueAsDouble(String name, double doubleValue) - { + public void addStateValueAsDouble(String name, double doubleValue) { addStateValueAsDouble(null, name, doubleValue); } @@ -1746,24 +1600,21 @@ public void addStateValueAsDouble(String name, double doubleValue) * context. Otherwise, the new StateObject is placed directly beneath the document root. If a * StateObject with this name already exists, a new one is still created. * - * @param context the StateObject context under which the new StateObject is created, or null to place it under - * the document root. - * @param name the new StateObject's name. + * @param context the StateObject context under which the new StateObject is created, or null to place it under the + * document root. + * @param name the new StateObject's name. * @param doubleValue the new StateObject's Double value. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public void addStateValueAsDouble(StateObject context, String name, double doubleValue) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsDouble(StateObject context, String name, double doubleValue) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1776,13 +1627,12 @@ public void addStateValueAsDouble(StateObject context, String name, double doubl * Adds a new StateObject with the specified name and Boolean value. The new StateObject * is placed beneath the document root. If a StateObject with this name already exists, a new one is still created. * - * @param name the new StateObject's name. + * @param name the new StateObject's name. * @param booleanValue the new StateObject's Boolean value. * * @throws IllegalArgumentException If name is null. */ - public void addStateValueAsBoolean(String name, boolean booleanValue) - { + public void addStateValueAsBoolean(String name, boolean booleanValue) { addStateValueAsBoolean(null, name, booleanValue); } @@ -1792,24 +1642,21 @@ public void addStateValueAsBoolean(String name, boolean booleanValue) * context. Otherwise, the new StateObject is placed directly beneath the document root. If a * StateObject with this name already exists, a new one is still created. * - * @param context the StateObject context under which the new StateObject is created, or null to place it under - * the document root. - * @param name the new StateObject's name. + * @param context the StateObject context under which the new StateObject is created, or null to place it under the + * document root. + * @param name the new StateObject's name. * @param booleanValue the new StateObject's Boolean value. * * @throws IllegalArgumentException If name is null, or if context is not null and does - * not belong to this RestorableSupport. + * not belong to this RestorableSupport. */ - public void addStateValueAsBoolean(StateObject context, String name, boolean booleanValue) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsBoolean(StateObject context, String name, boolean booleanValue) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1818,163 +1665,134 @@ public void addStateValueAsBoolean(StateObject context, String name, boolean boo addStateValueAsString(context, name, Boolean.toString(booleanValue)); } - public void addStateValueAsLatLon(String name, LatLon location) - { + public void addStateValueAsLatLon(String name, LatLon location) { addStateValueAsLatLon(null, name, location); } - public void addStateValueAsLatLon(StateObject context, String name, LatLon location) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsLatLon(StateObject context, String name, LatLon location) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (location == null) - { + if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject pStateObj = addStateObject(context, name); - if (pStateObj != null) - { + if (pStateObj != null) { addStateValueAsDouble(pStateObj, "latitudeDegrees", location.getLatitude().degrees); addStateValueAsDouble(pStateObj, "longitudeDegrees", location.getLongitude().degrees); } } - public void addStateValueAsPosition(String name, Position position) - { + public void addStateValueAsPosition(String name, Position position) { addStateValueAsPosition(null, name, position); } - public void addStateValueAsPosition(StateObject context, String name, Position position) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsPosition(StateObject context, String name, Position position) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject pStateObj = addStateObject(context, name); - if (pStateObj != null) - { + if (pStateObj != null) { addStateValueAsDouble(pStateObj, "latitudeDegrees", position.getLatitude().degrees); addStateValueAsDouble(pStateObj, "longitudeDegrees", position.getLongitude().degrees); addStateValueAsDouble(pStateObj, "elevation", position.getElevation()); } } - public void addStateValueAsLatLonList(StateObject context, String name, Iterable locations) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsLatLonList(StateObject context, String name, Iterable locations) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (locations == null) - { + if (locations == null) { String message = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject stateObject = addStateObject(context, name); - if (stateObject != null) - { - for (LatLon ll : locations) - { + if (stateObject != null) { + for (LatLon ll : locations) { addStateValueAsLatLon(stateObject, "location", ll); } } } - public void addStateValueAsOffsetsList(StateObject context, String name, Map offsets) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsOffsetsList(StateObject context, String name, Map offsets) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (offsets == null) - { + if (offsets == null) { String message = Logging.getMessage("nullValue.OffsetListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject stateObject = addStateObject(context, name); - for (Object key : ((Map) offsets).keySet()) - { + for (Object key : ((Map) offsets).keySet()) { addStateValueAsOffsets(stateObject, "face", offsets.get(key)); } } - public void addStateValueAsOffsets(String name, OffsetsList offsets) - { + public void addStateValueAsOffsets(String name, OffsetsList offsets) { addStateValueAsOffsets(null, name, offsets); } - public void addStateValueAsOffsets(StateObject context, String name, OffsetsList offsets) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsOffsets(StateObject context, String name, OffsetsList offsets) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (offsets == null) - { + if (offsets == null) { String message = Logging.getMessage("nullValue.OffsetsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject pStateObj = addStateObject(context, name); - if (pStateObj != null) - { + if (pStateObj != null) { addStateValueAsOffsetPair(pStateObj, "upperLeftOffset", offsets.getOffset(0)); // upper left uv offset addStateValueAsOffsetPair(pStateObj, "upperRightOffset", offsets.getOffset(1)); // upper right uv offset addStateValueAsOffsetPair(pStateObj, "lowerLeftOffset", offsets.getOffset(2)); // lower left uv offset @@ -1982,101 +1800,85 @@ public void addStateValueAsOffsets(StateObject context, String name, OffsetsList } } - public void addStateValueAsOffsetPair(StateObject context, String name, float[] offsetPair) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsOffsetPair(StateObject context, String name, float[] offsetPair) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (offsetPair == null) - { + if (offsetPair == null) { String message = Logging.getMessage("nullValue.OffsetPairIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject pStateObj = addStateObject(context, name); - if (pStateObj != null) - { + if (pStateObj != null) { addStateValueAsDouble(pStateObj, "uOffset", offsetPair[0]); addStateValueAsDouble(pStateObj, "vOffset", offsetPair[1]); } } - public void addStateValueAsImageSourceList(String name, Map imageSources, int faceCount) - { + public void addStateValueAsImageSourceList(String name, Map imageSources, int faceCount) { addStateValueAsImageSourceList(null, name, imageSources, faceCount); } public void addStateValueAsImageSourceList(StateObject context, String name, - Map imageSources, int faceCount) - { - if (context != null && !containsElement(context.elem)) - { + Map imageSources, int faceCount) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (imageSources == null) - { + if (imageSources == null) { String message = Logging.getMessage("nullValue.ImageSourcesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject stateObject = addStateObject(context, name); - for (int i = 0; i < faceCount; i++) - { - if (imageSources.get(i) == null) + for (int i = 0; i < faceCount; i++) { + if (imageSources.get(i) == null) { addStateValueAsString(stateObject, "imageSource", "null"); - else + } else { addStateValueAsString(stateObject, "imageSource", imageSources.get(i).toString()); + } } } - public void addStateValueAsSector(String name, Sector sector) - { + public void addStateValueAsSector(String name, Sector sector) { addStateValueAsSector(null, name, sector); } - public void addStateValueAsSector(StateObject context, String name, Sector sector) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsSector(StateObject context, String name, Sector sector) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject pStateObj = addStateObject(context, name); - if (pStateObj != null) - { + if (pStateObj != null) { addStateValueAsDouble(pStateObj, "minLatitudeDegrees", sector.getMinLatitude().degrees); addStateValueAsDouble(pStateObj, "maxLatitudeDegrees", sector.getMaxLatitude().degrees); addStateValueAsDouble(pStateObj, "minLongitudeDegrees", sector.getMinLongitude().degrees); @@ -2084,27 +1886,22 @@ public void addStateValueAsSector(StateObject context, String name, Sector secto } } - public void addStateValueAsColor(String name, java.awt.Color color) - { + public void addStateValueAsColor(String name, java.awt.Color color) { addStateValueAsColor(null, name, color); } - public void addStateValueAsColor(StateObject context, String name, java.awt.Color color) - { - if (context != null && !containsElement(context.elem)) - { + public void addStateValueAsColor(StateObject context, String name, java.awt.Color color) { + if (context != null && !containsElement(context.elem)) { String message = Logging.getMessage("RestorableSupport.InvalidStateObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (color == null) - { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2114,10 +1911,15 @@ public void addStateValueAsColor(StateObject context, String name, java.awt.Colo addStateValueAsString(context, name, value); } - /*************************************************************************************************************/ - /** Convenience methods for adding and querying state values. **/ - /*************************************************************************************************************/ - + /** + * ********************************************************************************************************** + */ + /** + * Convenience methods for adding and querying state values. * + */ + /** + * ********************************************************************************************************** + */ /** * Returns a String encoding of the specified color. The Color can be restored with a call to {@link * #decodeColor(String)}. @@ -2128,10 +1930,8 @@ public void addStateValueAsColor(StateObject context, String name, java.awt.Colo * * @throws IllegalArgumentException If color is null. */ - public static String encodeColor(java.awt.Color color) - { - if (color == null) - { + public static String encodeColor(java.awt.Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2139,9 +1939,9 @@ public static String encodeColor(java.awt.Color color) // Encode the red, green, blue, and alpha components int rgba = (color.getRed() & 0xFF) << 24 - | (color.getGreen() & 0xFF) << 16 - | (color.getBlue() & 0xFF) << 8 - | (color.getAlpha() & 0xFF); + | (color.getGreen() & 0xFF) << 16 + | (color.getBlue() & 0xFF) << 8 + | (color.getAlpha() & 0xFF); return String.format("%#08X", rgba); } @@ -2156,28 +1956,24 @@ public static String encodeColor(java.awt.Color color) * * @throws IllegalArgumentException If encodedString is null. */ - public static java.awt.Color decodeColor(String encodedString) - { - if (encodedString == null) - { + public static java.awt.Color decodeColor(String encodedString) { + if (encodedString == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) + if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) { return null; + } // The hexadecimal representation for an RGBA color can result in a value larger than // Integer.MAX_VALUE (for example, 0XFFFF). Therefore we decode the string as a long, // then keep only the lower four bytes. Long longValue; - try - { + try { longValue = Long.parseLong(encodedString.substring(2), 16); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", encodedString); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -2185,16 +1981,16 @@ public static java.awt.Color decodeColor(String encodedString) int i = (int) (longValue & 0xFFFFFFFFL); return new java.awt.Color( - (i >> 24) & 0xFF, - (i >> 16) & 0xFF, - (i >> 8) & 0xFF, - i & 0xFF); + (i >> 24) & 0xFF, + (i >> 16) & 0xFF, + (i >> 8) & 0xFF, + i & 0xFF); } - public static void adjustTitleAndDisplayName(AVList params) - { + public static void adjustTitleAndDisplayName(AVList params) { String displayName = params.getStringValue(AVKey.DISPLAY_NAME); - if (displayName == null && params.getValue(AVKey.TITLE) != null) + if (displayName == null && params.getValue(AVKey.TITLE) != null) { params.setValue(AVKey.DISPLAY_NAME, params.getValue(AVKey.TITLE)); + } } } diff --git a/src/gov/nasa/worldwind/util/ScheduledTaskService.java b/src/gov/nasa/worldwind/util/ScheduledTaskService.java index 6e3f503d70..eee1ece3a7 100644 --- a/src/gov/nasa/worldwind/util/ScheduledTaskService.java +++ b/src/gov/nasa/worldwind/util/ScheduledTaskService.java @@ -15,8 +15,8 @@ * * @see TaskService */ -public interface ScheduledTaskService -{ +public interface ScheduledTaskService { + /** * Shut down the service. If the {@code immediate} parameter is {@code true}, the service will attempt to stop all * active tasks, and will not begin work on any other tasks in the queue. Otherwise, the service will complete all @@ -39,11 +39,11 @@ public interface ScheduledTaskService * Enqueues a task to run after a delay. Duplicate tasks are ignored. * * @param runnable the task to add. - * @param delay delay before execution of the task. {@code timeUnit} determines the units of the value. + * @param delay delay before execution of the task. {@code timeUnit} determines the units of the value. * @param timeUnit time unit of {@code initialDelay} and {@code period}. * * @return a ScheduledFuture that can be used to get the result of the task, or cancel the task, or {@code null} if - * the task was not enqueued. + * the task was not enqueued. * * @throws IllegalArgumentException if runnable is null */ @@ -53,16 +53,16 @@ public interface ScheduledTaskService * Enqueues a task to run periodically. This method follows the same semantics as {@link * java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate}. Duplicate tasks are ignored. * - * @param runnable the task to add. + * @param runnable the task to add. * @param initialDelay delay before the first execution of the task. {@code timeUnit} determines the units of the - * value. - * @param period interval between executions of the task. {@code timeUnit} determines the units of the value. - * @param timeUnit time unit of {@code initialDelay} and {@code period}. + * value. + * @param period interval between executions of the task. {@code timeUnit} determines the units of the value. + * @param timeUnit time unit of {@code initialDelay} and {@code period}. * * @return a ScheduledFuture that can be used to get the result of the task, or cancel the task, or {@code null} if - * the task was not enqueued. + * the task was not enqueued. * * @throws IllegalArgumentException if runnable is null */ ScheduledFuture addRepeatingTask(Runnable runnable, long initialDelay, long period, TimeUnit timeUnit); -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/SectorVisibilityTree.java b/src/gov/nasa/worldwind/util/SectorVisibilityTree.java index b21fdfcdd5..60dcffefe6 100644 --- a/src/gov/nasa/worldwind/util/SectorVisibilityTree.java +++ b/src/gov/nasa/worldwind/util/SectorVisibilityTree.java @@ -16,16 +16,15 @@ * @author Tom Gaskins * @version $Id: SectorVisibilityTree.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SectorVisibilityTree -{ - protected static class Context - { +public class SectorVisibilityTree { + + protected static class Context { + private final DrawContext dc; private final double sectorSize; private final List sectors; - public Context(DrawContext dc, double sectorSize, List sectors) - { + public Context(DrawContext dc, double sectorSize, List sectors) { this.dc = dc; this.sectorSize = sectorSize; this.sectors = sectors; @@ -39,97 +38,86 @@ public Context(DrawContext dc, double sectorSize, List sectors) protected ArrayList sectors = new ArrayList(); protected long timeStamp; - public SectorVisibilityTree() - { + public SectorVisibilityTree() { } - public double getSectorSize() - { + public double getSectorSize() { return sectorSize; } - public List getSectors() - { + public List getSectors() { return this.sectors; } - public long getTimeStamp() - { + public long getTimeStamp() { return timeStamp; } - public void setTimeStamp(long timeStamp) - { + public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } - public void clearSectors() - { + public void clearSectors() { this.sectors.clear(); } protected DecisionTree tree = new DecisionTree( - new DecisionTree.Controller() - { - public boolean isTerminal(Sector s, Context context) - { - if (s.getDeltaLat().degrees > context.sectorSize) - return false; - - context.sectors.add(s); - return true; + new DecisionTree.Controller() { + public boolean isTerminal(Sector s, Context context) { + if (s.getDeltaLat().degrees > context.sectorSize) { + return false; } - public Sector[] split(Sector s, Context context) - { - return s.subdivide(); - } + context.sectors.add(s); + return true; + } - public boolean isVisible(Sector s, Context c) - { - Extent extent = prevExtents.get(s); - if (extent == null) - extent = Sector.computeBoundingBox(c.dc.getGlobe(), c.dc.getVerticalExaggeration(), s); + public Sector[] split(Sector s, Context context) { + return s.subdivide(); + } - if (extent.intersects(c.dc.getView().getFrustumInModelCoordinates())) - { - newExtents.put(s, extent); - return true; - } + public boolean isVisible(Sector s, Context c) { + Extent extent = prevExtents.get(s); + if (extent == null) { + extent = Sector.computeBoundingBox(c.dc.getGlobe(), c.dc.getVerticalExaggeration(), s); + } - return false; + if (extent.intersects(c.dc.getView().getFrustumInModelCoordinates())) { + newExtents.put(s, extent); + return true; } - }); + + return false; + } + }); /** * Determines the visible sectors at a specifed resolution within the draw context's current visible sector. * - * @param dc the current draw context + * @param dc the current draw context * @param sectorSize the granularity of sector visibility, in degrees. All visible sectors of this size are found. - * The value must be in the range, 1 second <= sectorSize <= 180 degrees. + * The value must be in the range, 1 second <= sectorSize <= 180 degrees. * * @return the list of visible sectors. The list will be empty if no sectors are visible. * * @throws IllegalArgumentException if the draw context is null. */ - public List refresh(DrawContext dc, double sectorSize) - { - if (dc == null) - { + public List refresh(DrawContext dc, double sectorSize) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sectorSize < Angle.SECOND.degrees || sectorSize > 180) - { + if (sectorSize < Angle.SECOND.degrees || sectorSize > 180) { String message = Logging.getMessage("generic.SizeOutOfRange", sectorSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getVisibleSector() == null) + if (dc.getVisibleSector() == null) { return Collections.emptyList(); + } this.sectors = new ArrayList(); this.sectorSize = sectorSize; @@ -143,35 +131,31 @@ public List refresh(DrawContext dc, double sectorSize) /** * Determines the visible sectors at a specified resolution within a specified sector. * - * @param dc the current draw context - * @param sectorSize the granularity of sector visibility, in degrees. All visible sectors of this size are found. - * The value must be in the range, 1 second <= sectorSize <= 180 degrees. + * @param dc the current draw context + * @param sectorSize the granularity of sector visibility, in degrees. All visible sectors of this size are found. + * The value must be in the range, 1 second <= sectorSize <= 180 degrees. * @param searchSector the overall sector for which to determine visibility. May be null, in which case the current - * visible sector of the draw context is used. + * visible sector of the draw context is used. * * @return the list of visible sectors. The list will be empty if no sectors are visible. * * @throws IllegalArgumentException if the draw context is null, the sector size is less than or equal to zero, or - * the search sector list is null. + * the search sector list is null. */ - public List refresh(DrawContext dc, double sectorSize, Sector searchSector) - { - if (dc == null) - { + public List refresh(DrawContext dc, double sectorSize, Sector searchSector) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sectorSize < Angle.SECOND.degrees || sectorSize > 180) - { + if (sectorSize < Angle.SECOND.degrees || sectorSize > 180) { String message = Logging.getMessage("generic.SizeOutOfRange", sectorSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (searchSector == null) - { + if (searchSector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -191,34 +175,30 @@ public List refresh(DrawContext dc, double sectorSize, Sector searchSect * to recursively determine visible sectors: the output of one invocation can be passed as an argument to the next * invocation. * - * @param dc the current draw context - * @param sectorSize the granularity of sector visibility, in degrees. All visible sectors of this size are The - * value must be in the range, 1 second <= sectorSize <= 180 degrees. found. + * @param dc the current draw context + * @param sectorSize the granularity of sector visibility, in degrees. All visible sectors of this size are The + * value must be in the range, 1 second <= sectorSize <= 180 degrees. found. * @param searchSectors the sectors for which to determine visibility. * * @return the list of visible sectors. The list will be empty if no sectors are visible. * * @throws IllegalArgumentException if the draw context is null, the sector size is less than or equal to zero or - * the search sector list is null. + * the search sector list is null. */ - public List refresh(DrawContext dc, double sectorSize, List searchSectors) - { - if (dc == null) - { + public List refresh(DrawContext dc, double sectorSize, List searchSectors) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sectorSize < Angle.SECOND.degrees || sectorSize > 180) - { + if (sectorSize < Angle.SECOND.degrees || sectorSize > 180) { String message = Logging.getMessage("generic.SizeOutOfRange", sectorSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (searchSectors == null) - { + if (searchSectors == null) { String message = Logging.getMessage("nullValue.SectorListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -227,8 +207,7 @@ public List refresh(DrawContext dc, double sectorSize, List sear this.swapCylinderLists(dc); this.sectors = new ArrayList(); this.sectorSize = sectorSize; - for (Sector s : searchSectors) - { + for (Sector s : searchSectors) { this.tree.traverse(s, new Context(dc, sectorSize, this.sectors)); } @@ -236,10 +215,10 @@ public List refresh(DrawContext dc, double sectorSize, List sear return this.sectors; } - protected void swapCylinderLists(DrawContext dc) - { - if (this.globeStateKey != null && !dc.getGlobe().getStateKey(dc).equals(this.globeStateKey)) + protected void swapCylinderLists(DrawContext dc) { + if (this.globeStateKey != null && !dc.getGlobe().getStateKey(dc).equals(this.globeStateKey)) { this.newExtents.clear(); + } this.prevExtents.clear(); HashMap temp = this.prevExtents; diff --git a/src/gov/nasa/worldwind/util/SessionCacheRetrievalPostProcessor.java b/src/gov/nasa/worldwind/util/SessionCacheRetrievalPostProcessor.java index 68b59737f1..903ba19bfd 100644 --- a/src/gov/nasa/worldwind/util/SessionCacheRetrievalPostProcessor.java +++ b/src/gov/nasa/worldwind/util/SessionCacheRetrievalPostProcessor.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: SessionCacheRetrievalPostProcessor.java 3086 2015-05-13 20:27:38Z dcollins $ */ -public class SessionCacheRetrievalPostProcessor implements RetrievalPostProcessor -{ +public class SessionCacheRetrievalPostProcessor implements RetrievalPostProcessor { + protected String name; protected final SessionCache cache; protected final Object cacheKey; @@ -35,26 +35,23 @@ public class SessionCacheRetrievalPostProcessor implements RetrievalPostProcesso * Constructs a SessionCachePostProcessor with a specified cache and cache key, and an optional property listener * and property name. * - * @param cache cache that receives the retrieved data. - * @param cacheKey cache key to place the retrieved data under. + * @param cache cache that receives the retrieved data. + * @param cacheKey cache key to place the retrieved data under. * @param absentResourceList the absent resource list to update. - * @param resourceID the resource ID to use in the absent resource list. - * @param propertyListener property listener to notify when the data is available. Can be null. - * @param propertyName property name to use for the property event when the data is available. Can be null. + * @param resourceID the resource ID to use in the absent resource list. + * @param propertyListener property listener to notify when the data is available. Can be null. + * @param propertyName property name to use for the property event when the data is available. Can be null. */ public SessionCacheRetrievalPostProcessor(SessionCache cache, Object cacheKey, - AbsentResourceList absentResourceList, long resourceID, - PropertyChangeListener propertyListener, String propertyName) - { - if (cache == null) - { + AbsentResourceList absentResourceList, long resourceID, + PropertyChangeListener propertyListener, String propertyName) { + if (cache == null) { String message = Logging.getMessage("nullValue.CacheIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cacheKey == null) - { + if (cacheKey == null) { String message = Logging.getMessage("nullValue.CacheKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -73,8 +70,7 @@ public SessionCacheRetrievalPostProcessor(SessionCache cache, Object cacheKey, * * @return this post processor's name. May be null. */ - public String getName() - { + public String getName() { return this.name; } @@ -84,8 +80,7 @@ public String getName() * * @param name this post processor's name. May be null. */ - public void setName(String name) - { + public void setName(String name) { this.name = name; } @@ -94,8 +89,7 @@ public void setName(String name) * * @return the session cache that receives data. */ - public final SessionCache getCache() - { + public final SessionCache getCache() { return this.cache; } @@ -104,8 +98,7 @@ public final SessionCache getCache() * * @return cache key for the retrieved data. */ - public final Object getCacheKey() - { + public final Object getCacheKey() { return this.cacheKey; } @@ -114,8 +107,7 @@ public final Object getCacheKey() * * @return the absent resource list. */ - public final AbsentResourceList getAbsentResourceList() - { + public final AbsentResourceList getAbsentResourceList() { return this.absentResourceList; } @@ -124,8 +116,7 @@ public final AbsentResourceList getAbsentResourceList() * * @return resource ID to use in the absent resource list. */ - public final long getResourceID() - { + public final long getResourceID() { return this.resourceID; } @@ -135,8 +126,7 @@ public final long getResourceID() * * @return property change listener to fire when retrieved data is available. */ - public final PropertyChangeListener getPropertyListener() - { + public final PropertyChangeListener getPropertyListener() { return this.propertyListener; } @@ -146,8 +136,7 @@ public final PropertyChangeListener getPropertyListener() * * @return property name to fire when retrieved data is available. */ - public final String getPropertyName() - { + public final String getPropertyName() { return this.propertyName; } @@ -161,10 +150,8 @@ public final String getPropertyName() * * @return the retrieved data. */ - public java.nio.ByteBuffer run(Retriever retriever) - { - if (retriever == null) - { + public java.nio.ByteBuffer run(Retriever retriever) { + if (retriever == null) { String message = Logging.getMessage("nullValue.RetrieverIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,12 +159,9 @@ public java.nio.ByteBuffer run(Retriever retriever) String message = this.validate(retriever); - if (message == null) - { + if (message == null) { this.onRetrievalSuceeded(retriever); - } - else - { + } else { this.onRetrievalFailed(retriever); Logging.logger().severe(message); } @@ -186,87 +170,73 @@ public java.nio.ByteBuffer run(Retriever retriever) return retriever.getBuffer(); } - protected void onRetrievalSuceeded(Retriever retriever) - { - try - { + protected void onRetrievalSuceeded(Retriever retriever) { + try { this.handleContent(retriever); - if (this.absentResourceList != null) + if (this.absentResourceList != null) { this.absentResourceList.unmarkResourceAbsent(this.resourceID); - } - catch (Exception e) - { + } + } catch (Exception e) { this.handleContentException(retriever, e); } } @SuppressWarnings({"UnusedDeclaration"}) - protected void onRetrievalFailed(Retriever retriever) - { - if (this.absentResourceList != null) + protected void onRetrievalFailed(Retriever retriever) { + if (this.absentResourceList != null) { this.absentResourceList.markResourceAbsent(this.resourceID); + } } - protected String validate(Retriever retriever) - { - if (!retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) + protected String validate(Retriever retriever) { + if (!retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) { return Logging.getMessage("generic.RetrievalFailed", this.toString()); + } - if (retriever.getBuffer() == null || retriever.getBuffer().limit() == 0) + if (retriever.getBuffer() == null || retriever.getBuffer().limit() == 0) { return Logging.getMessage("generic.RetrievalReturnedNoContent", this.toString()); + } return null; } - protected void signalRetrievalComplete() - { + protected void signalRetrievalComplete() { // If both the property listener and property name are non-null, then fire a property change event, // signalling that the retrieval has completed.s - if (this.propertyListener != null && this.propertyName != null) - { + if (this.propertyListener != null && this.propertyName != null) { this.propertyListener.propertyChange( - new PropertyChangeEvent(this, this.propertyName, null, this.propertyListener)); + new PropertyChangeEvent(this, this.propertyName, null, this.propertyListener)); } } - protected void handleContent(Retriever retriever) throws Exception - { + protected void handleContent(Retriever retriever) throws Exception { String uppercaseName = retriever.getName().toUpperCase(); - if (uppercaseName.contains("SERVICE=WMS") && uppercaseName.contains("REQUEST=GETCAPABILITIES")) - { + if (uppercaseName.contains("SERVICE=WMS") && uppercaseName.contains("REQUEST=GETCAPABILITIES")) { this.handleWMSCapabilitiesContent(retriever); - } - else - { + } else { this.handleUnknownContent(retriever); } } - protected void handleWMSCapabilitiesContent(Retriever retriever) throws Exception - { + protected void handleWMSCapabilitiesContent(Retriever retriever) throws Exception { WMSCapabilities caps = new WMSCapabilities(retriever.getBuffer()); this.cache.put(this.cacheKey, caps.parse()); } - protected void handleUnknownContent(Retriever retriever) throws Exception - { + protected void handleUnknownContent(Retriever retriever) throws Exception { this.cache.put(this.cacheKey, retriever.getBuffer()); } - protected void handleContentException(Retriever retriever, Exception e) - { - if (e instanceof ClosedByInterruptException) - { + protected void handleContentException(Retriever retriever, Exception e) { + if (e instanceof ClosedByInterruptException) { Logging.logger().log(java.util.logging.Level.FINE, - Logging.getMessage("generic.OperationCancelled", - "retrieval post-processing for " + retriever.getName()), e); - } - else - { + Logging.getMessage("generic.OperationCancelled", + "retrieval post-processing for " + retriever.getName()), e); + } else { this.onRetrievalFailed(retriever); Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("generic.ExceptionWhileSavingRetreivedData", retriever.getName()), e); + Logging.getMessage("generic.ExceptionWhileSavingRetreivedData", retriever.getName()), e); } } @@ -276,10 +246,10 @@ protected void handleContentException(Retriever retriever, Exception e) * * @return String representation of this post processor. */ - public String toString() - { - if (this.getName() != null) + public String toString() { + if (this.getName() != null) { return this.getName(); + } return super.toString(); } diff --git a/src/gov/nasa/worldwind/util/SessionCacheUtils.java b/src/gov/nasa/worldwind/util/SessionCacheUtils.java index 77dd418134..8e5505a655 100644 --- a/src/gov/nasa/worldwind/util/SessionCacheUtils.java +++ b/src/gov/nasa/worldwind/util/SessionCacheUtils.java @@ -18,69 +18,61 @@ * @author dcollins * @version $Id: SessionCacheUtils.java 3086 2015-05-13 20:27:38Z dcollins $ */ -public class SessionCacheUtils -{ +public class SessionCacheUtils { + /** - * Retrieves the contents of a specified {@link java.net.URL}. If successful, this places the URL - * contents in a specified session cache with a specified key. This either marks the resource as available or - * missing, depending on whether the retrieval succeeds or fails. Finally, this optionally notifies the caller that - * the retrieval has succeeded by firing a property change event. If either the property listener or property name - * are null, that functionality is disabled. + * Retrieves the contents of a specified {@link java.net.URL}. If successful, this places the URL contents in a + * specified session cache with a specified key. This either marks the resource as available or missing, depending + * on whether the retrieval succeeds or fails. Finally, this optionally notifies the caller that the retrieval has + * succeeded by firing a property change event. If either the property listener or property name are null, that + * functionality is disabled. * - * @param url the URL contents to retrieve. - * @param cache the cache which receives the retrieved data. - * @param cacheKey the cache key which identifies where the retrieved data is placed in the session - * cache. + * @param url the URL contents to retrieve. + * @param cache the cache which receives the retrieved data. + * @param cacheKey the cache key which identifies where the retrieved data is placed in the session cache. * @param absentResourceList the absent resource list to update. - * @param resourceID the resource ID to use in the absent resource list. - * @param propertyListener the property change listener which is fired when the retrieved data is available. - * @param propertyName the property name to fire when retrieved data is available. + * @param resourceID the resource ID to use in the absent resource list. + * @param propertyListener the property change listener which is fired when the retrieved data is available. + * @param propertyName the property name to fire when retrieved data is available. * * @throws IllegalArgumentException if any of the url, retrieval service, cache, or cache key are null. */ public static void retrieveSessionData(java.net.URL url, SessionCache cache, Object cacheKey, - AbsentResourceList absentResourceList, long resourceID, PropertyChangeListener propertyListener, - String propertyName) - { - if (url == null) - { + AbsentResourceList absentResourceList, long resourceID, PropertyChangeListener propertyListener, + String propertyName) { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cache == null) - { + if (cache == null) { String message = Logging.getMessage("nullValue.CacheIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cacheKey == null) - { + if (cacheKey == null) { String message = Logging.getMessage("nullValue.CacheKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WorldWind.getNetworkStatus().isHostUnavailable(url)) - { - if (absentResourceList != null) + if (WorldWind.getNetworkStatus().isHostUnavailable(url)) { + if (absentResourceList != null) { absentResourceList.markResourceAbsent(resourceID); + } return; } SessionCacheRetrievalPostProcessor postProcessor = new SessionCacheRetrievalPostProcessor(cache, cacheKey, - absentResourceList, resourceID, propertyListener, propertyName); + absentResourceList, resourceID, propertyListener, propertyName); postProcessor.setName(url.toString()); Retriever retriever = URLRetriever.createRetriever(url, postProcessor); - try - { + try { retriever.call(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("layers.TiledImageLayer.ExceptionRetrievingResources", url.toString()); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } @@ -92,26 +84,23 @@ public static void retrieveSessionData(java.net.URL url, SessionCache cache, Obj * Capabilities document, this returns null. If the entry exists, but must be converted to a Capabilities document, * this overrides the previous cache entry with the the newly converted Capabilities. * - * @param cache the session cache. + * @param cache the session cache. * @param cacheKey the key to identify the object in the session cache. - * @param name the name to use in logging messages. + * @param name the name to use in logging messages. * * @return the Capabilities document in the session cache, or null if either the key does not match an entry in the - * cache, or that entry cannot be interpreted as a Capabilities document. + * cache, or that entry cannot be interpreted as a Capabilities document. * * @throws IllegalArgumentException if either the cache or cache key are null. */ - public static WMSCapabilities getSessionCapabilities(SessionCache cache, Object cacheKey, String name) - { - if (cache == null) - { + public static WMSCapabilities getSessionCapabilities(SessionCache cache, Object cacheKey, String name) { + if (cache == null) { String message = Logging.getMessage("nullValue.CacheIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cacheKey == null) - { + if (cacheKey == null) { String message = Logging.getMessage("nullValue.CacheKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -126,46 +115,43 @@ public static WMSCapabilities getSessionCapabilities(SessionCache cache, Object * WMSCapabilities} document. If the key does not map to a Capabilities document for any reason, this attempts to * asynchronously retrieve the Capabilities from a specified URL, and returns null. * - * @param url the URL contents to retrieve. - * @param cache the session cache. - * @param cacheKey the key to identify the object in the session cache. + * @param url the URL contents to retrieve. + * @param cache the session cache. + * @param cacheKey the key to identify the object in the session cache. * @param absentResourceList the absent resource list to update. - * @param resourceID the resource ID to use in the absent resource list. - * @param propertyListener the property change listener which is fired when the retrieved data is available. - * @param propertyName the property name to fire when retrieved data is available. + * @param resourceID the resource ID to use in the absent resource list. + * @param propertyListener the property change listener which is fired when the retrieved data is available. + * @param propertyName the property name to fire when retrieved data is available. * * @return the Capabilities document in the session cache, or null if the document is not in the cache. * * @throws IllegalArgumentException if either the url, retrieval service, cache or cache key are null. */ public static WMSCapabilities getOrRetrieveSessionCapabilities(java.net.URL url, SessionCache cache, - Object cacheKey, AbsentResourceList absentResourceList, long resourceID, - PropertyChangeListener propertyListener, String propertyName) - { - if (url == null) - { + Object cacheKey, AbsentResourceList absentResourceList, long resourceID, + PropertyChangeListener propertyListener, String propertyName) { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cache == null) - { + if (cache == null) { String message = Logging.getMessage("nullValue.CacheIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cacheKey == null) - { + if (cacheKey == null) { String message = Logging.getMessage("nullValue.CacheKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } WMSCapabilities caps = getSessionCapabilities(cache, cacheKey, url.toString()); - if (caps != null) + if (caps != null) { return caps; + } retrieveSessionData(url, cache, cacheKey, absentResourceList, resourceID, propertyListener, propertyName); diff --git a/src/gov/nasa/worldwind/util/ShapeEditor.java b/src/gov/nasa/worldwind/util/ShapeEditor.java index f99199a214..083df537b5 100644 --- a/src/gov/nasa/worldwind/util/ShapeEditor.java +++ b/src/gov/nasa/worldwind/util/ShapeEditor.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.*; @@ -41,8 +40,8 @@ * @author tag * @version $Id: ShapeEditor.java 3423 2015-09-23 20:59:03Z tgaskins $ */ -public class ShapeEditor implements SelectListener, PropertyChangeListener -{ +public class ShapeEditor implements SelectListener, PropertyChangeListener { + // Control point purposes /** * Indicates that a control point is associated with annotation. @@ -108,8 +107,8 @@ public class ShapeEditor implements SelectListener, PropertyChangeListener /** * Represents editor control points. */ - protected static class ControlPointMarker extends BasicMarker - { + protected static class ControlPointMarker extends BasicMarker { + /** * The control point's ID, which is typically its list index when the shape has a list of locations. */ @@ -131,52 +130,43 @@ protected static class ControlPointMarker extends BasicMarker */ protected Angle rotation; - public ControlPointMarker(Position position, MarkerAttributes attrs, int id, String purpose) - { + public ControlPointMarker(Position position, MarkerAttributes attrs, int id, String purpose) { super(position, attrs); this.id = id; this.purpose = purpose; } - public ControlPointMarker(Position position, MarkerAttributes attrs, int id, int leg, String purpose) - { + public ControlPointMarker(Position position, MarkerAttributes attrs, int id, int leg, String purpose) { this(position, attrs, id, purpose); this.leg = leg; } - public int getId() - { + public int getId() { return this.id; } - public int getLeg() - { + public int getLeg() { return leg; } - public String getPurpose() - { + public String getPurpose() { return this.purpose; } - public void setSize(double size) - { + public void setSize(double size) { this.size = size; } - public Double getSize() - { + public Double getSize() { return size; } - public void setRotation(Angle rotation) - { + public void setRotation(Angle rotation) { this.rotation = rotation; } - public Angle getRotation() - { + public Angle getRotation() { return rotation; } } @@ -294,36 +284,31 @@ public Angle getRotation() * Constructs an editor for a specified shape. Once constructed, the editor must be armed to operate. See {@link * #setArmed(boolean)}. * - * @param wwd the {@link gov.nasa.worldwind.WorldWindow} associated with the specified shape. + * @param wwd the {@link gov.nasa.worldwind.WorldWindow} associated with the specified shape. * @param originalShape the shape to edit. * * @throws java.lang.IllegalArgumentException if either the specified WorldWindow or shape is null. */ - public ShapeEditor(WorldWindow wwd, Renderable originalShape) - { - if (wwd == null) - { + public ShapeEditor(WorldWindow wwd, Renderable originalShape) { + if (wwd == null) { String msg = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().log(java.util.logging.Level.SEVERE, msg); throw new IllegalArgumentException(msg); } - if (originalShape == null) - { + if (originalShape == null) { String msg = Logging.getMessage("nullValue.Shape"); Logging.logger().log(java.util.logging.Level.SEVERE, msg); throw new IllegalArgumentException(msg); } - if (!(originalShape instanceof Movable2)) - { + if (!(originalShape instanceof Movable2)) { String msg = Logging.getMessage("generic.Movable2NotSupported"); Logging.logger().log(java.util.logging.Level.SEVERE, msg); throw new IllegalArgumentException(msg); } - if (!(originalShape instanceof Attributable)) - { + if (!(originalShape instanceof Attributable)) { String msg = Logging.getMessage("generic.AttributableNotSupported"); Logging.logger().log(java.util.logging.Level.SEVERE, msg); throw new IllegalArgumentException(msg); @@ -338,8 +323,7 @@ public ShapeEditor(WorldWindow wwd, Renderable originalShape) this.controlPointLayer.setKeepSeparated(false); this.controlPointLayer.setValue(AVKey.IGNORE, true); // means "Don't show this layer in the layer manager." if (this.shape instanceof SurfaceShape - || (this.shape instanceof Airspace && ((Airspace) this.shape).isDrawSurfaceShape())) - { + || (this.shape instanceof Airspace && ((Airspace) this.shape).isDrawSurfaceShape())) { // This ensures that control points are always placed on the terrain for surface shapes. this.controlPointLayer.setOverrideMarkerElevation(true); this.controlPointLayer.setElevation(0); @@ -386,15 +370,14 @@ public ShapeEditor(WorldWindow wwd, Renderable originalShape) this.makeControlPointAttributes(); } - protected void makeControlPointAttributes() - { + protected void makeControlPointAttributes() { // Each attribute has color, marker type, opacity, size in pixels, and minimum size in meters (0 indicates that // the minimum size is not considered. this.locationControlPointAttributes = new BasicMarkerAttributes(Material.BLUE, BasicMarkerShape.SPHERE, 0.7, 10, - 0); + 0); this.sizeControlPointAttributes = new BasicMarkerAttributes(Material.CYAN, BasicMarkerShape.SPHERE, 0.7, 10, 0); this.angleControlPointAttributes = new BasicMarkerAttributes(Material.GREEN, BasicMarkerShape.SPHERE, 0.7, 10, - 0); + 0); } /** @@ -402,8 +385,7 @@ protected void makeControlPointAttributes() * * @return the units formatter associated with this editor. */ - public UnitsFormat getUnitsFormat() - { + public UnitsFormat getUnitsFormat() { return unitsFormat; } @@ -412,8 +394,7 @@ public UnitsFormat getUnitsFormat() * * @param unitsFormat the units formatter to use. A default is created if null is specified. */ - public void setUnitsFormat(UnitsFormat unitsFormat) - { + public void setUnitsFormat(UnitsFormat unitsFormat) { this.unitsFormat = unitsFormat != null ? unitsFormat : new UnitsFormat(); } @@ -422,8 +403,7 @@ public void setUnitsFormat(UnitsFormat unitsFormat) * * @return the WorldWindow associated with this editor. */ - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.wwd; } @@ -432,8 +412,7 @@ public WorldWindow getWwd() * * @return the shape associated with this editor. */ - public Renderable getShape() - { + public Renderable getShape() { return this.shape; } @@ -442,8 +421,7 @@ public Renderable getShape() * * @return the control point layer used by this editor. */ - public MarkerLayer getControlPointLayer() - { + public MarkerLayer getControlPointLayer() { return controlPointLayer; } @@ -452,8 +430,7 @@ public MarkerLayer getControlPointLayer() * * @return the accessory layer used by this editor. */ - public RenderableLayer getAccessoryLayer() - { + public RenderableLayer getAccessoryLayer() { return accessoryLayer; } @@ -462,8 +439,7 @@ public RenderableLayer getAccessoryLayer() * * @return the annotation layer used by this editor. */ - public RenderableLayer getAnnotationLayer() - { + public RenderableLayer getAnnotationLayer() { return annotationLayer; } @@ -472,18 +448,16 @@ public RenderableLayer getAnnotationLayer() * * @return the shadow layer used by this editor. */ - public RenderableLayer getShadowLayer() - { + public RenderableLayer getShadowLayer() { return shadowLayer; } /** - * Indicates the annotation used to show locations and measurements. + * Indicates the annotation used to show locations and measurements. * * @return the annotation used to show shape locations and measurements. */ - public EditorAnnotation getAnnotation() - { + public EditorAnnotation getAnnotation() { return annotation; } @@ -492,8 +466,7 @@ public EditorAnnotation getAnnotation() * * @return true if an operation is underway, otherwise false. */ - public boolean isActive() - { + public boolean isActive() { return active; } @@ -502,8 +475,7 @@ public boolean isActive() * * @return the current operation underway. */ - public int getActiveOperation() - { + public int getActiveOperation() { return activeOperation; } @@ -512,8 +484,7 @@ public int getActiveOperation() * * @return the geographic position associated with the previous select event. */ - public Position getPreviousPosition() - { + public Position getPreviousPosition() { return previousPosition; } @@ -522,8 +493,7 @@ public Position getPreviousPosition() * * @return the control point used in the operation currently underway. */ - public ControlPointMarker getCurrentSizingMarker() - { + public ControlPointMarker getCurrentSizingMarker() { return currentSizingMarker; } @@ -532,8 +502,7 @@ public ControlPointMarker getCurrentSizingMarker() * * @return the attributes associated with the shape when the editor was created. */ - public ShapeAttributes getOriginalAttributes() - { + public ShapeAttributes getOriginalAttributes() { return originalAttributes; } @@ -543,8 +512,7 @@ public ShapeAttributes getOriginalAttributes() * * @return the original highlight attributes. */ - public ShapeAttributes getOriginalHighlightAttributes() - { + public ShapeAttributes getOriginalHighlightAttributes() { return originalHighlightAttributes; } @@ -553,8 +521,7 @@ public ShapeAttributes getOriginalHighlightAttributes() * * @return the current rotation heading. */ - public Angle getCurrentHeading() - { + public Angle getCurrentHeading() { return currentHeading; } @@ -563,8 +530,7 @@ public Angle getCurrentHeading() * * @return the attributes associated with location control points. */ - public MarkerAttributes getLocationControlPointAttributes() - { + public MarkerAttributes getLocationControlPointAttributes() { return locationControlPointAttributes; } @@ -573,8 +539,7 @@ public MarkerAttributes getLocationControlPointAttributes() * * @return the attributes associated with size control points. */ - public MarkerAttributes getSizeControlPointAttributes() - { + public MarkerAttributes getSizeControlPointAttributes() { return sizeControlPointAttributes; } @@ -583,17 +548,16 @@ public MarkerAttributes getSizeControlPointAttributes() * * @return the attributes associated with angle control points. */ - public MarkerAttributes getAngleControlPointAttributes() - { + public MarkerAttributes getAngleControlPointAttributes() { return angleControlPointAttributes; } /** * Indicates whether multi-segment shapes such as Route and Track may be edited to add or remove segments. + * * @return true if segment addition and deletion are enabled, otherwise false. The default is true. */ - public boolean isExtensionEnabled() - { + public boolean isExtensionEnabled() { return extensionEnabled; } @@ -602,8 +566,7 @@ public boolean isExtensionEnabled() * * @param extensionEnabled true to allow segment addition and removal, otherwise false. */ - public void setExtensionEnabled(boolean extensionEnabled) - { + public void setExtensionEnabled(boolean extensionEnabled) { this.extensionEnabled = extensionEnabled; } @@ -612,8 +575,7 @@ public void setExtensionEnabled(boolean extensionEnabled) * * @return the event most recently passed to the select handler. */ - public SelectEvent getCurrentEvent() - { + public SelectEvent getCurrentEvent() { return currentEvent; } @@ -622,8 +584,7 @@ public SelectEvent getCurrentEvent() * * @return true if the editor is armed, otherwise false. */ - public boolean isArmed() - { + public boolean isArmed() { return this.armed; } @@ -632,17 +593,13 @@ public boolean isArmed() * that indicate possible editing operations. * * @param armed true to arm the editor, false to disarm it and remove the control points - * and other affordances. This method must be called when the editor is no longer needed so that the - * editor may remove the resources it created when it was armed. + * and other affordances. This method must be called when the editor is no longer needed so that the editor may + * remove the resources it created when it was armed. */ - public void setArmed(boolean armed) - { - if (!this.isArmed() && armed) - { + public void setArmed(boolean armed) { + if (!this.isArmed() && armed) { this.enable(); - } - else if (this.isArmed() && !armed) - { + } else if (this.isArmed() && !armed) { this.disable(); } @@ -652,31 +609,37 @@ else if (this.isArmed() && !armed) /** * Called by {@link #setArmed(boolean)} to initialize this editor. */ - protected void enable() - { + protected void enable() { LayerList layers = this.getWwd().getModel().getLayers(); - if (!layers.contains(this.getControlPointLayer())) + if (!layers.contains(this.getControlPointLayer())) { layers.add(this.getControlPointLayer()); + } - if (!this.getControlPointLayer().isEnabled()) + if (!this.getControlPointLayer().isEnabled()) { this.getControlPointLayer().setEnabled(true); + } - if (!layers.contains(this.getAccessoryLayer())) + if (!layers.contains(this.getAccessoryLayer())) { layers.add(this.getAccessoryLayer()); + } - if (!this.getAccessoryLayer().isEnabled()) + if (!this.getAccessoryLayer().isEnabled()) { this.getAccessoryLayer().setEnabled(true); + } - if (!layers.contains(this.getAnnotationLayer())) + if (!layers.contains(this.getAnnotationLayer())) { layers.add(this.getAnnotationLayer()); + } - if (!layers.contains(this.getShadowLayer())) + if (!layers.contains(this.getShadowLayer())) { layers.add(0, this.getShadowLayer()); + } this.getShadowLayer().setEnabled(true); - if (this.getShape() instanceof TrackAirspace) + if (this.getShape() instanceof TrackAirspace) { this.determineTrackAdjacency(); + } this.updateControlPoints(); @@ -687,8 +650,7 @@ protected void enable() /** * Called by {@link #setArmed(boolean)} to remove resources no longer needed after editing. */ - protected void disable() - { + protected void disable() { LayerList layers = this.getWwd().getModel().getLayers(); layers.remove(this.getControlPointLayer()); @@ -705,20 +667,20 @@ protected void disable() /** * Determines and stores internally the adjacency of successive track legs. Called during editor arming. */ - protected void determineTrackAdjacency() - { - if (this.trackAdjacencyList == null) + protected void determineTrackAdjacency() { + if (this.trackAdjacencyList == null) { this.trackAdjacencyList = new ArrayList(); - else + } else { this.trackAdjacencyList.clear(); + } TrackAirspace track = (TrackAirspace) this.getShape(); List legs = track.getLegs(); - for (int i = 1; i < legs.size(); i++) - { + for (int i = 1; i < legs.size(); i++) { boolean adjacent = legs.get(i - 1).getLocations()[1].equals(legs.get(i).getLocations()[0]); - if (adjacent) + if (adjacent) { this.trackAdjacencyList.add(legs.get(i)); + } } } @@ -728,10 +690,8 @@ protected void determineTrackAdjacency() * * @param event the select event indicating what was selected and the geographic location under the cursor. */ - public void selected(SelectEvent event) - { - if (event == null) - { + public void selected(SelectEvent event) { + if (event == null) { String msg = Logging.getMessage("nullValue.EventIsNull"); Logging.logger().log(java.util.logging.Level.FINE, msg); throw new IllegalArgumentException(msg); @@ -739,104 +699,97 @@ public void selected(SelectEvent event) this.currentEvent = event; - if (event.getEventAction().equals(SelectEvent.DRAG_END)) - { + if (event.getEventAction().equals(SelectEvent.DRAG_END)) { this.active = false; this.activeOperation = NONE; this.previousPosition = null; ((Component) this.getWwd()).setCursor(null); this.removeShadowShape(); this.updateAnnotation(null); - } - else if (event.getEventAction().equals(SelectEvent.ROLLOVER)) - { - if (!(this.getWwd() instanceof Component)) + } else if (event.getEventAction().equals(SelectEvent.ROLLOVER)) { + if (!(this.getWwd() instanceof Component)) { return; + } // Update the cursor. Cursor cursor = null; - if (this.activeOperation == MOVING) + if (this.activeOperation == MOVING) { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); - else if (this.getActiveOperation() == SIZING) + } else if (this.getActiveOperation() == SIZING) { cursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); - else if (event.getTopObject() != null && event.getTopObject() == this.getShape()) + } else if (event.getTopObject() != null && event.getTopObject() == this.getShape()) { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); - else if (event.getTopObject() != null && event.getTopObject() instanceof Marker) + } else if (event.getTopObject() != null && event.getTopObject() instanceof Marker) { cursor = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); + } ((Component) this.getWwd()).setCursor(cursor); // Update the shape or control point annotation. - if (this.getActiveOperation() == MOVING && event.getTopObject() == this.getShape()) + if (this.getActiveOperation() == MOVING && event.getTopObject() == this.getShape()) { this.updateShapeAnnotation(); - else if (this.getActiveOperation() == SIZING) + } else if (this.getActiveOperation() == SIZING) { this.updateAnnotation(this.getCurrentSizingMarker()); - else if (event.getTopObject() != null && event.getTopObject() == this.getShape()) + } else if (event.getTopObject() != null && event.getTopObject() == this.getShape()) { this.updateShapeAnnotation(); - else if (event.getTopObject() != null && event.getTopObject() instanceof ControlPointMarker) + } else if (event.getTopObject() != null && event.getTopObject() instanceof ControlPointMarker) { this.updateAnnotation((ControlPointMarker) event.getTopObject()); - else + } else { this.updateAnnotation(null); - } - else if (event.getEventAction().equals(SelectEvent.LEFT_PRESS)) - { + } + } else if (event.getEventAction().equals(SelectEvent.LEFT_PRESS)) { // Prepare for a drag. this.active = true; PickedObjectList objectsUnderCursor = this.getWwd().getObjectsAtCurrentPosition(); - if (objectsUnderCursor != null) - { + if (objectsUnderCursor != null) { PickedObject terrainObject = objectsUnderCursor.getTerrainObject(); - if (terrainObject != null) + if (terrainObject != null) { this.previousPosition = terrainObject.getPosition(); + } } - } - else if (event.getEventAction().equals(SelectEvent.LEFT_CLICK)) - { + } else if (event.getEventAction().equals(SelectEvent.LEFT_CLICK)) { Object topObject = event.getTopObject(); - if (topObject == null) + if (topObject == null) { return; + } // Add and delete control points. - if (event.getTopPickedObject().getParentLayer() == this.getControlPointLayer()) - { + if (event.getTopPickedObject().getParentLayer() == this.getControlPointLayer()) { this.reshapeShape((ControlPointMarker) topObject); this.updateControlPoints(); this.updateAnnotation(this.getCurrentSizingMarker()); event.consume(); - } - else if ((event.getTopObject() == this.getShape()) && - (this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0) - { + } else if ((event.getTopObject() == this.getShape()) + && (this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0) { this.reshapeShape(null); this.updateControlPoints(); event.consume(); } - } - else if (event.getEventAction().equals(SelectEvent.DRAG)) - { - if (!this.isActive()) + } else if (event.getEventAction().equals(SelectEvent.DRAG)) { + if (!this.isActive()) { return; + } DragSelectEvent dragEvent = (DragSelectEvent) event; Object topObject = dragEvent.getTopObject(); - if (topObject == null) + if (topObject == null) { return; + } if (this.getActiveOperation() == NONE) // drag is starting + { this.makeShadowShape(); + } - if (topObject == this.getShape() || this.getActiveOperation() == MOVING) - { + if (topObject == this.getShape() || this.getActiveOperation() == MOVING) { // Move the whole shape. this.activeOperation = MOVING; this.dragWholeShape(dragEvent); this.updateControlPoints(); this.updateShapeAnnotation(); event.consume(); - } - else if (dragEvent.getTopPickedObject().getParentLayer() == this.getControlPointLayer() - || this.getActiveOperation() == SIZING) - { + } else if (dragEvent.getTopPickedObject().getParentLayer() == this.getControlPointLayer() + || this.getActiveOperation() == SIZING) { // Perform the editing operation associated with the selected control point. this.activeOperation = SIZING; this.reshapeShape((ControlPointMarker) topObject); @@ -850,22 +803,19 @@ else if (dragEvent.getTopPickedObject().getParentLayer() == this.getControlPoint } /** - * The property change listener, the method called when a property of the Scene Controller changes - * (vertical exaggeration, etc.). Does not necessarily indicate a property associated with this editor. + * The property change listener, the method called when a property of the Scene Controller changes (vertical + * exaggeration, etc.). Does not necessarily indicate a property associated with this editor. * * @param event the property change event indicating the property name and its associated value. */ - public void propertyChange(PropertyChangeEvent event) - { - if (event == null) - { + public void propertyChange(PropertyChangeEvent event) { + if (event == null) { String msg = Logging.getMessage("nullValue.EventIsNull"); Logging.logger().log(java.util.logging.Level.FINE, msg); throw new IllegalArgumentException(msg); } - if (event.getPropertyName().equals(AVKey.VERTICAL_EXAGGERATION)) - { + if (event.getPropertyName().equals(AVKey.VERTICAL_EXAGGERATION)) { // The orientation line altitudes depend on the vertical exaggeration. this.updateControlPoints(); } @@ -874,32 +824,32 @@ public void propertyChange(PropertyChangeEvent event) /** * Creates the shape that will remain at the same location and is the same size as the shape to be edited. */ - protected void makeShadowShape() - { + protected void makeShadowShape() { Renderable shadowShape = this.doMakeShadowShape(); - if (shadowShape == null) + if (shadowShape == null) { return; + } - if (this.getShape() instanceof Airspace) + if (this.getShape() instanceof Airspace) { ((Airspace) this.getShape()).setAlwaysOnTop(true); + } // Reduce the opacity of an opaque current shape so that the shadow shape is visible while editing // is performed. - this.originalAttributes = ((Attributable) this.getShape()).getAttributes(); this.originalHighlightAttributes = ((Attributable) this.getShape()).getHighlightAttributes(); ShapeAttributes editingAttributes = new BasicShapeAttributes(this.originalAttributes); - if (editingAttributes.getInteriorOpacity() == 1) + if (editingAttributes.getInteriorOpacity() == 1) { editingAttributes.setInteriorOpacity(0.7); + } ((Attributable) this.getShape()).setAttributes(editingAttributes); ((Attributable) this.getShape()).setHighlightAttributes(editingAttributes); this.getShadowLayer().addRenderable(shadowShape); - if (this.getShape() instanceof Airspace) - { + if (this.getShape() instanceof Airspace) { double[] altitudes = ((Airspace) shadowShape).getAltitudes(); ((Airspace) shadowShape).setAltitudes(altitudes[0], 0.95 * altitudes[1]); // @@ -914,15 +864,14 @@ protected void makeShadowShape() /** * Remove the shadow shape. */ - protected void removeShadowShape() - { + protected void removeShadowShape() { this.getShadowLayer().removeAllRenderables(); - if (this.getShape() instanceof AbstractAirspace) + if (this.getShape() instanceof AbstractAirspace) { ((AbstractAirspace) this.getShape()).setAlwaysOnTop(false); + } // Restore the original attributes. - if (this.getOriginalAttributes() != null) - { + if (this.getOriginalAttributes() != null) { ((Attributable) this.getShape()).setAttributes(this.getOriginalAttributes()); ((Attributable) this.getShape()).setHighlightAttributes(this.getOriginalHighlightAttributes()); } @@ -936,38 +885,38 @@ protected void removeShadowShape() * * @return the new shadow shape created, or null if the shape type is not recognized. */ - protected Renderable doMakeShadowShape() - { - if (this.getShape() instanceof Polygon) + protected Renderable doMakeShadowShape() { + if (this.getShape() instanceof Polygon) { return new Polygon((Polygon) this.getShape()); - else if (this.getShape() instanceof PartialCappedCylinder) + } else if (this.getShape() instanceof PartialCappedCylinder) { return new PartialCappedCylinder((PartialCappedCylinder) this.getShape()); - else if (this.getShape() instanceof CappedCylinder) + } else if (this.getShape() instanceof CappedCylinder) { return new CappedCylinder((CappedCylinder) this.getShape()); - else if (this.getShape() instanceof CappedEllipticalCylinder) + } else if (this.getShape() instanceof CappedEllipticalCylinder) { return new CappedEllipticalCylinder((CappedEllipticalCylinder) this.getShape()); - else if (this.getShape() instanceof Orbit) + } else if (this.getShape() instanceof Orbit) { return new Orbit((Orbit) this.getShape()); - else if (this.getShape() instanceof Route) + } else if (this.getShape() instanceof Route) { return new Route((Route) this.getShape()); - else if (this.getShape() instanceof Curtain) + } else if (this.getShape() instanceof Curtain) { return new Curtain((Curtain) this.getShape()); - else if (this.getShape() instanceof SphereAirspace) + } else if (this.getShape() instanceof SphereAirspace) { return new SphereAirspace((SphereAirspace) this.getShape()); - else if (this.getShape() instanceof TrackAirspace) + } else if (this.getShape() instanceof TrackAirspace) { return new TrackAirspace((TrackAirspace) this.getShape()); - else if (this.getShape() instanceof SurfaceSquare) + } else if (this.getShape() instanceof SurfaceSquare) { return new SurfaceSquare((SurfaceSquare) this.getShape()); - else if (this.getShape() instanceof SurfaceQuad) + } else if (this.getShape() instanceof SurfaceQuad) { return new SurfaceQuad((SurfaceQuad) this.getShape()); - else if (this.getShape() instanceof SurfaceCircle) + } else if (this.getShape() instanceof SurfaceCircle) { return new SurfaceCircle((SurfaceCircle) this.getShape()); - else if (this.getShape() instanceof SurfaceEllipse) + } else if (this.getShape() instanceof SurfaceEllipse) { return new SurfaceEllipse((SurfaceEllipse) this.getShape()); - else if (this.getShape() instanceof SurfacePolyline) + } else if (this.getShape() instanceof SurfacePolyline) { return new SurfacePolyline((SurfacePolyline) this.getShape()); - else if (this.getShape() instanceof SurfacePolygon) + } else if (this.getShape() instanceof SurfacePolygon) { return new SurfacePolygon((SurfacePolygon) this.getShape()); + } return null; } @@ -980,31 +929,29 @@ else if (this.getShape() instanceof SurfacePolygon) * otherwise modify the shape to retain its original properties. Subclasses should override this method if they are * aware of shapes other than those recognized by default and those shapes need such adjustment during editing. */ - protected void adjustShape() - { - if (this.getShape() instanceof TrackAirspace) + protected void adjustShape() { + if (this.getShape() instanceof TrackAirspace) { this.adjustTrackShape(); + } } /** * Restores adjacency of {@link gov.nasa.worldwind.render.airspaces.TrackAirspace} shapes. Called by {@link * #adjustShape()}. */ - protected void adjustTrackShape() - { + protected void adjustTrackShape() { TrackAirspace track = (TrackAirspace) this.getShape(); List legs = track.getLegs(); - if (legs == null) + if (legs == null) { return; + } // Start with the second leg and restore coincidence of the first leg position with that of the previous leg. - for (int i = 1; i < legs.size(); i++) - { + for (int i = 1; i < legs.size(); i++) { Box leg = legs.get(i); - if (this.trackAdjacencyList.contains(legs.get(i))) - { + if (this.trackAdjacencyList.contains(legs.get(i))) { leg.setLocations(legs.get(i - 1).getLocations()[1], leg.getLocations()[1]); } } @@ -1015,8 +962,7 @@ protected void adjustTrackShape() * * @param dragEvent the event initiating the move. */ - protected void dragWholeShape(DragSelectEvent dragEvent) - { + protected void dragWholeShape(DragSelectEvent dragEvent) { Movable2 dragObject = (Movable2) this.getShape(); View view = getWwd().getView(); @@ -1024,8 +970,9 @@ protected void dragWholeShape(DragSelectEvent dragEvent) // Compute ref-point position in screen coordinates. Position refPos = dragObject.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return; + } Vec4 refPoint = globe.computePointFromPosition(refPos); Vec4 screenRefPoint = view.project(refPoint); @@ -1040,12 +987,11 @@ protected void dragWholeShape(DragSelectEvent dragEvent) Line ray = view.computeRayFromScreenPoint(x, y); Intersection inters[] = globe.intersect(ray, refPos.getElevation()); - if (inters != null) - { + if (inters != null) { // Intersection with globe. Move reference point to the intersection point. Position p = globe.computePositionFromPoint(inters[0].getIntersectionPoint()); dragObject.moveTo(getWwd().getModel().getGlobe(), new Position(p, - ((Movable2) this.getShape()).getReferencePosition().getAltitude())); + ((Movable2) this.getShape()).getReferencePosition().getAltitude())); } this.adjustShape(); @@ -1056,22 +1002,22 @@ protected void dragWholeShape(DragSelectEvent dragEvent) * * @param controlPoint the control point selected. */ - protected void reshapeShape(ControlPointMarker controlPoint) - { + protected void reshapeShape(ControlPointMarker controlPoint) { this.currentSizingMarker = controlPoint; // If the terrain beneath the control point is null, then the user is attempting to drag the handle off the // globe. This is not a valid state, so we ignore this action but keep the drag operation in effect. PickedObjectList objectsUnderCursor = this.getWwd().getObjectsAtCurrentPosition(); - if (objectsUnderCursor == null) + if (objectsUnderCursor == null) { return; + } PickedObject terrainObject = this.getWwd().getObjectsAtCurrentPosition().getTerrainObject(); - if (terrainObject == null) + if (terrainObject == null) { return; + } - if (this.getPreviousPosition() == null) - { + if (this.getPreviousPosition() == null) { this.previousPosition = terrainObject.getPosition(); return; } @@ -1089,42 +1035,40 @@ protected void reshapeShape(ControlPointMarker controlPoint) * Subclasses should override this method if they provide editing for shapes other than those supported by the basic * editor. * - * @param controlPoint the control point selected. + * @param controlPoint the control point selected. * @param terrainPosition the terrain position under the cursor. */ - protected void doReshapeShape(ControlPointMarker controlPoint, Position terrainPosition) - { - if (this.getShape() instanceof Airspace) - { - if (this.getShape() instanceof Polygon || this.getShape() instanceof Curtain) + protected void doReshapeShape(ControlPointMarker controlPoint, Position terrainPosition) { + if (this.getShape() instanceof Airspace) { + if (this.getShape() instanceof Polygon || this.getShape() instanceof Curtain) { this.reshapePolygonAirspace(terrainPosition, controlPoint); - else if (this.getShape() instanceof CappedCylinder) + } else if (this.getShape() instanceof CappedCylinder) { this.reshapeCappedCylinder(terrainPosition, controlPoint); - else if (this.getShape() instanceof CappedEllipticalCylinder) + } else if (this.getShape() instanceof CappedEllipticalCylinder) { this.reshapeCappedEllipticalCylinder(terrainPosition, controlPoint); - else if (this.getShape() instanceof Orbit) + } else if (this.getShape() instanceof Orbit) { this.reshapeOrbit(terrainPosition, controlPoint); - else if (this.getShape() instanceof Route) + } else if (this.getShape() instanceof Route) { this.reshapeRoute(terrainPosition, controlPoint); - else if (this.getShape() instanceof SphereAirspace) + } else if (this.getShape() instanceof SphereAirspace) { this.reshapeSphere(terrainPosition, controlPoint); - else if (this.getShape() instanceof TrackAirspace) + } else if (this.getShape() instanceof TrackAirspace) { this.reshapeTrack(terrainPosition, controlPoint); - } - else if (this.getShape() instanceof SurfaceShape) - { - if (this.getShape() instanceof SurfacePolygon) + } + } else if (this.getShape() instanceof SurfaceShape) { + if (this.getShape() instanceof SurfacePolygon) { this.reshapeSurfacePolygon(terrainPosition, controlPoint); - else if (this.getShape() instanceof SurfacePolyline) + } else if (this.getShape() instanceof SurfacePolyline) { this.reshapeSurfacePolygon(terrainPosition, controlPoint); - else if (this.getShape() instanceof SurfaceCircle) + } else if (this.getShape() instanceof SurfaceCircle) { this.reshapeSurfaceCircle(terrainPosition, controlPoint); - else if (this.getShape() instanceof SurfaceSquare) + } else if (this.getShape() instanceof SurfaceSquare) { this.reshapeSurfaceSquare(terrainPosition, controlPoint); - else if (this.getShape() instanceof SurfaceQuad) + } else if (this.getShape() instanceof SurfaceQuad) { this.reshapeSurfaceQuad(terrainPosition, controlPoint); - else if (this.getShape() instanceof SurfaceEllipse) + } else if (this.getShape() instanceof SurfaceEllipse) { this.reshapeSurfaceEllipse(terrainPosition, controlPoint); + } } } @@ -1132,39 +1076,37 @@ else if (this.getShape() instanceof SurfaceEllipse) * Updates the control points to the locations of the currently edited shape. Called each time a modification to the * shape is made. Subclasses should override this method to handle shape types not supported by the basic editor. */ - protected void updateControlPoints() - { - if (this.getShape() instanceof Airspace) - { - if (this.getShape() instanceof Polygon || this.getShape() instanceof Curtain) + protected void updateControlPoints() { + if (this.getShape() instanceof Airspace) { + if (this.getShape() instanceof Polygon || this.getShape() instanceof Curtain) { this.updatePolygonAirspaceControlPoints(); - else if (this.getShape() instanceof PartialCappedCylinder) + } else if (this.getShape() instanceof PartialCappedCylinder) { this.updatePartialCappedCylinderControlPoints(); - else if (this.getShape() instanceof CappedCylinder) + } else if (this.getShape() instanceof CappedCylinder) { this.updateCappedCylinderControlPoints(); - else if (this.getShape() instanceof CappedEllipticalCylinder) + } else if (this.getShape() instanceof CappedEllipticalCylinder) { this.updateCappedEllipticalCylinderControlPoints(); - else if (this.getShape() instanceof Orbit) + } else if (this.getShape() instanceof Orbit) { this.updateOrbitControlPoints(); - else if (this.getShape() instanceof Route) + } else if (this.getShape() instanceof Route) { this.updateRouteControlPoints(); - else if (this.getShape() instanceof SphereAirspace) + } else if (this.getShape() instanceof SphereAirspace) { this.updateSphereControlPoints(); - else if (this.getShape() instanceof TrackAirspace) + } else if (this.getShape() instanceof TrackAirspace) { this.updateTrackControlPoints(); - } - else if (this.getShape() instanceof SurfaceShape) - { - if (this.getShape() instanceof SurfacePolygon || this.getShape() instanceof SurfacePolyline) + } + } else if (this.getShape() instanceof SurfaceShape) { + if (this.getShape() instanceof SurfacePolygon || this.getShape() instanceof SurfacePolyline) { this.updateSurfacePolygonControlPoints(); - else if (this.getShape() instanceof SurfaceCircle) + } else if (this.getShape() instanceof SurfaceCircle) { this.updateSurfaceCircleControlPoints(); - else if (this.getShape() instanceof SurfaceSquare) + } else if (this.getShape() instanceof SurfaceSquare) { this.updateSurfaceSquareControlPoints(); - else if (this.getShape() instanceof SurfaceQuad) + } else if (this.getShape() instanceof SurfaceQuad) { this.updateSurfaceQuadControlPoints(); - else if (this.getShape() instanceof SurfaceEllipse) + } else if (this.getShape() instanceof SurfaceEllipse) { this.updateSurfaceEllipseControlPoints(); + } } } @@ -1172,18 +1114,14 @@ else if (this.getShape() instanceof SurfaceEllipse) * Updates the annotation indicating the edited shape's center. If the shape has no designated center, this method * prevents the annotation from displaying. */ - protected void updateShapeAnnotation() - { + protected void updateShapeAnnotation() { LatLon center = this.getShapeCenter(); - if (center != null) - { + if (center != null) { ControlPointMarker dummyMarker = this.makeControlPoint(new Position(center, 0), new BasicMarkerAttributes(), - 0, ANNOTATION); + 0, ANNOTATION); this.updateAnnotation(dummyMarker); - } - else - { + } else { this.updateAnnotation(null); } } @@ -1193,20 +1131,20 @@ protected void updateShapeAnnotation() * * @return the shape's center location, or null if the shape has no designated center. */ - protected LatLon getShapeCenter() - { + protected LatLon getShapeCenter() { LatLon center = null; - if (this.getShape() instanceof CappedCylinder) + if (this.getShape() instanceof CappedCylinder) { center = ((CappedCylinder) this.getShape()).getCenter(); - else if (this.getShape() instanceof CappedEllipticalCylinder) + } else if (this.getShape() instanceof CappedEllipticalCylinder) { center = ((CappedEllipticalCylinder) this.getShape()).getCenter(); - else if (this.getShape() instanceof SphereAirspace) + } else if (this.getShape() instanceof SphereAirspace) { center = ((SphereAirspace) this.getShape()).getLocation(); - else if (this.getShape() instanceof SurfaceEllipse) + } else if (this.getShape() instanceof SurfaceEllipse) { center = ((SurfaceEllipse) this.getShape()).getCenter(); - else if (this.getShape() instanceof SurfaceQuad) + } else if (this.getShape() instanceof SurfaceQuad) { center = ((SurfaceQuad) this.getShape()).getCenter(); + } return center; } @@ -1216,10 +1154,8 @@ else if (this.getShape() instanceof SurfaceQuad) * * @param controlPoint the control point. */ - protected void updateAnnotation(ControlPointMarker controlPoint) - { - if (controlPoint == null) - { + protected void updateAnnotation(ControlPointMarker controlPoint) { + if (controlPoint == null) { this.getAnnotationLayer().setEnabled(false); return; } @@ -1228,12 +1164,13 @@ protected void updateAnnotation(ControlPointMarker controlPoint) this.getAnnotation().setPosition(controlPoint.getPosition()); String annotationText; - if (controlPoint.size != null) + if (controlPoint.size != null) { annotationText = this.unitsFormat.length(null, controlPoint.size); - else if (controlPoint.rotation != null) + } else if (controlPoint.rotation != null) { annotationText = this.unitsFormat.angle(null, controlPoint.rotation); - else + } else { annotationText = this.unitsFormat.latLon2(controlPoint.getPosition()); + } this.getAnnotation().setText(annotationText); } @@ -1242,38 +1179,32 @@ else if (controlPoint.rotation != null) * Updates the line designating the shape's central axis. * * @param centerPosition the shape's center location and altitude at which to place one of the line's end points. - * @param controlPoint the shape orientation control point. + * @param controlPoint the shape orientation control point. */ - protected void updateOrientationLine(Position centerPosition, Position controlPoint) - { + protected void updateOrientationLine(Position centerPosition, Position controlPoint) { Path rotationLine = (Path) this.getAccessoryLayer().getRenderables().iterator().next(); double cAltitude = centerPosition.getAltitude(); double rAltitude = controlPoint.getAltitude(); - if (this.getShapeAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) - { + if (this.getShapeAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { rotationLine.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); rotationLine.setFollowTerrain(true); // Set the line's altitude relative to the ground. cAltitude = centerPosition.getAltitude() - this.getWwd().getModel().getGlobe().getElevation( - centerPosition.getLatitude(), centerPosition.getLongitude()); + centerPosition.getLatitude(), centerPosition.getLongitude()); rAltitude = controlPoint.getAltitude() - this.getWwd().getModel().getGlobe().getElevation( - controlPoint.getLatitude(), controlPoint.getLongitude()); + controlPoint.getLatitude(), controlPoint.getLongitude()); // Path does not incorporate vertical exaggeration, but airspace shapes do. Compensate for that difference here. cAltitude *= this.getWwd().getSceneController().getVerticalExaggeration(); rAltitude *= this.getWwd().getSceneController().getVerticalExaggeration(); // Add a little altitude so that the line isn't lost during depth buffering. cAltitude += 100; rAltitude += 100; - } - else if (this.getShapeAltitudeMode() == WorldWind.CLAMP_TO_GROUND) - { + } else if (this.getShapeAltitudeMode() == WorldWind.CLAMP_TO_GROUND) { rotationLine.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); rotationLine.setFollowTerrain(true); - } - else - { + } else { rotationLine.setAltitudeMode(WorldWind.ABSOLUTE); rotationLine.setFollowTerrain(false); } @@ -1291,55 +1222,46 @@ else if (this.getShapeAltitudeMode() == WorldWind.CLAMP_TO_GROUND) * * @return the appropriate altitude at which to place the control point. */ - protected double getControlPointAltitude(LatLon location) - { + protected double getControlPointAltitude(LatLon location) { return this.doGetControlPointAltitude(location, this.getShape()); } - protected double doGetControlPointAltitude(LatLon location, Renderable shape) - { + protected double doGetControlPointAltitude(LatLon location, Renderable shape) { double altitude = 0; - if (shape instanceof Airspace && !((Airspace) shape).isDrawSurfaceShape()) - { + if (shape instanceof Airspace && !((Airspace) shape).isDrawSurfaceShape()) { Airspace airspace = (Airspace) shape; altitude = airspace.getAltitudes()[1]; - if (airspace.getAltitudeDatum()[1].equals(AVKey.ABOVE_GROUND_LEVEL)) - { + if (airspace.getAltitudeDatum()[1].equals(AVKey.ABOVE_GROUND_LEVEL)) { LatLon refPos = airspace.getGroundReference(); - if (refPos == null) + if (refPos == null) { refPos = location; + } altitude += getWwd().getModel().getGlobe().getElevation(refPos.getLatitude(), refPos.getLongitude()); } - } - else if (shape instanceof Path) - { - for (Position position : ((Path) shape).getPositions()) - { - if (new LatLon(position).equals(location)) - { - if (((Path) shape).getAltitudeMode() == WorldWind.ABSOLUTE) + } else if (shape instanceof Path) { + for (Position position : ((Path) shape).getPositions()) { + if (new LatLon(position).equals(location)) { + if (((Path) shape).getAltitudeMode() == WorldWind.ABSOLUTE) { altitude = position.getAltitude(); - else if (((Path) shape).getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) + } else if (((Path) shape).getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { altitude = position.getAltitude() + this.getWwd().getModel().getGlobe().getElevation( - location.getLatitude(), location.getLongitude()); + location.getLatitude(), location.getLongitude()); + } } } - } - else if (shape instanceof gov.nasa.worldwind.render.Polygon) - { - for (Position position : ((gov.nasa.worldwind.render.Polygon) shape).outerBoundary()) - { - if (new LatLon(position).equals(location)) - { - if (((gov.nasa.worldwind.render.Polygon) shape).getAltitudeMode() == WorldWind.ABSOLUTE) + } else if (shape instanceof gov.nasa.worldwind.render.Polygon) { + for (Position position : ((gov.nasa.worldwind.render.Polygon) shape).outerBoundary()) { + if (new LatLon(position).equals(location)) { + if (((gov.nasa.worldwind.render.Polygon) shape).getAltitudeMode() == WorldWind.ABSOLUTE) { altitude = position.getAltitude(); - else if (((gov.nasa.worldwind.render.Polygon) shape).getAltitudeMode() - == WorldWind.RELATIVE_TO_GROUND) + } else if (((gov.nasa.worldwind.render.Polygon) shape).getAltitudeMode() + == WorldWind.RELATIVE_TO_GROUND) { altitude = position.getAltitude() + this.getWwd().getModel().getGlobe().getElevation( - location.getLatitude(), location.getLongitude()); + location.getLatitude(), location.getLongitude()); + } } } } @@ -1352,21 +1274,16 @@ else if (((gov.nasa.worldwind.render.Polygon) shape).getAltitudeMode() * * @return the shape's altitude mode if it has one, otherwise WorldWind.ABSOLUTE. */ - protected int getShapeAltitudeMode() - { + protected int getShapeAltitudeMode() { int altitudeMode = WorldWind.ABSOLUTE; - if (this.getShape() instanceof Airspace && ((Airspace) this.getShape()).isDrawSurfaceShape()) - { + if (this.getShape() instanceof Airspace && ((Airspace) this.getShape()).isDrawSurfaceShape()) { altitudeMode = WorldWind.CLAMP_TO_GROUND; - } - else if (this.getShape() instanceof Airspace) - { - if (((Airspace) this.getShape()).getAltitudeDatum()[1].equals(AVKey.ABOVE_GROUND_LEVEL)) + } else if (this.getShape() instanceof Airspace) { + if (((Airspace) this.getShape()).getAltitudeDatum()[1].equals(AVKey.ABOVE_GROUND_LEVEL)) { altitudeMode = WorldWind.RELATIVE_TO_GROUND; - } - else if (this.getShape() instanceof SurfaceShape) - { + } + } else if (this.getShape() instanceof SurfaceShape) { altitudeMode = WorldWind.CLAMP_TO_GROUND; } @@ -1376,33 +1293,31 @@ else if (this.getShape() instanceof SurfaceShape) /** * Creates a control point. * - * @param position the control point position. + * @param position the control point position. * @param attributes the control point attributes. - * @param id the control point ID. - * @param purpose the control point purpose. + * @param id the control point ID. + * @param purpose the control point purpose. * * @return the new control point. */ protected ControlPointMarker makeControlPoint(Position position, MarkerAttributes attributes, int id, - String purpose) - { + String purpose) { return new ControlPointMarker(position, attributes, id, purpose); } /** * Creates a control point. * - * @param position the control point position. + * @param position the control point position. * @param attributes the control point attributes. - * @param id the control point ID. - * @param leg the control point leg. - * @param purpose the control point purpose. + * @param id the control point ID. + * @param leg the control point leg. + * @param purpose the control point purpose. * * @return the new control point. */ protected ControlPointMarker makeControlPoint(Position position, MarkerAttributes attributes, int id, - int leg, String purpose) - { + int leg, String purpose) { return new ControlPointMarker(position, attributes, id, leg, purpose); } @@ -1410,12 +1325,11 @@ protected ControlPointMarker makeControlPoint(Position position, MarkerAttribute * Computes the Cartesian difference between two control points. * * @param previousLocation the location nof the previous control point. - * @param currentLocation the location of the current control point. + * @param currentLocation the location of the current control point. * * @return the Cartesian difference between the two control points. */ - protected Vec4 computeControlPointDelta(LatLon previousLocation, LatLon currentLocation) - { + protected Vec4 computeControlPointDelta(LatLon previousLocation, LatLon currentLocation) { // Compute how much the specified control point moved. Vec4 terrainPoint = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(currentLocation); Vec4 previousPoint = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(previousLocation); @@ -1427,18 +1341,18 @@ protected Vec4 computeControlPointDelta(LatLon previousLocation, LatLon currentL * Add a specified increment to an angle and normalize the result to be between 0 and 360 degrees. * * @param originalHeading the base angle. - * @param deltaHeading the increment to add prior to normalizing. + * @param deltaHeading the increment to add prior to normalizing. * * @return the normalized angle. */ - protected Angle normalizedHeading(Angle originalHeading, Angle deltaHeading) - { + protected Angle normalizedHeading(Angle originalHeading, Angle deltaHeading) { final double twoPI = 2 * Math.PI; double newHeading = originalHeading.getRadians() + deltaHeading.getRadians(); - if (Math.abs(newHeading) > twoPI) + if (Math.abs(newHeading) > twoPI) { newHeading = newHeading % twoPI; + } return Angle.fromRadians(newHeading >= 0 ? newHeading : newHeading + twoPI); } @@ -1446,27 +1360,26 @@ protected Angle normalizedHeading(Angle originalHeading, Angle deltaHeading) /** * Computes a control point location at the edge of a shape. * - * @param center the shape's center. + * @param center the shape's center. * @param location a location that forms a line from the shape's center along the shape's axis. The returned - * location is on the edge indicated by the cross product of a vector normal to the surface at the - * specified center and a vector from the center to this location. - * @param length the distance of the edge from the shape's center. + * location is on the edge indicated by the cross product of a vector normal to the surface at the specified center + * and a vector from the center to this location. + * @param length the distance of the edge from the shape's center. * * @return a location at the shape's edge at the same location along the shape's axis as the specified center * location. */ - protected Position computeEdgeLocation(LatLon center, LatLon location, double length) - { + protected Position computeEdgeLocation(LatLon center, LatLon location, double length) { Vec4 centerPoint = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(center); Vec4 surfaceNormal = getWwd().getModel().getGlobe().computeEllipsoidalNormalAtLocation( - center.getLatitude(), center.getLongitude()); + center.getLatitude(), center.getLongitude()); Vec4 point1 = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(location); Vec4 vecToLocation = point1.subtract3(centerPoint).normalize3(); Vec4 vecToEdge = surfaceNormal.cross3(vecToLocation).normalize3().multiply3(length); LatLon edgeLocation = getWwd().getModel().getGlobe().computePositionFromEllipsoidalPoint( - vecToEdge.add3(centerPoint)); + vecToEdge.add3(centerPoint)); double edgeAltitude = this.getControlPointAltitude(edgeLocation); return new Position(edgeLocation, edgeAltitude); @@ -1476,13 +1389,12 @@ protected Position computeEdgeLocation(LatLon center, LatLon location, double le * Computes a control point location at the edge of a rectangular shape. * * @param begin the beginning of the shape's center. - * @param end the end of the shape's center. + * @param end the end of the shape's center. * @param width the distance of the edge from the great circle arc between begin and end. * * @return a location centered along the edge parallel to the great circle arc between begin and end. */ - protected Position computeRectangularEdgeLocation(LatLon begin, LatLon end, double width) - { + protected Position computeRectangularEdgeLocation(LatLon begin, LatLon end, double width) { LatLon center = LatLon.interpolateGreatCircle(0.5, begin, end); Angle edgeAzimuth = LatLon.greatCircleAzimuth(center, end).add(Angle.POS90); Angle edgeLength = Angle.fromRadians(width / this.getWwd().getModel().getGlobe().getRadius()); @@ -1496,28 +1408,22 @@ protected Position computeRectangularEdgeLocation(LatLon begin, LatLon end, doub /** * Computes the point on a specified line segment that is nearest a specified point. * - * @param p1 the line's first point. - * @param p2 the line's second point. + * @param p1 the line's first point. + * @param p2 the line's second point. * @param point the point for which to determine a nearest point on the line segment. * * @return the nearest point on the line segment. */ - protected Vec4 nearestPointOnSegment(Vec4 p1, Vec4 p2, Vec4 point) - { + protected Vec4 nearestPointOnSegment(Vec4 p1, Vec4 p2, Vec4 point) { Vec4 segment = p2.subtract3(p1); Vec4 dir = segment.normalize3(); double dot = point.subtract3(p1).dot3(dir); - if (dot < 0.0) - { + if (dot < 0.0) { return p1; - } - else if (dot > segment.getLength3()) - { + } else if (dot > segment.getLength3()) { return p2; - } - else - { + } else { return Vec4.fromLine3(p1, dot, dir); } } @@ -1527,20 +1433,19 @@ else if (dot > segment.getLength3()) * appropriate place in that list. * * @param terrainPosition the position to find a nearest point for. - * @param altitude the altitude to use when determining the nearest point. Can be approximate and is not - * necessarily the altitude of the terrain position. - * @param locations the list of locations. This list is modified by this method to contain the new location on - * an edge nearest the specified terrain position. + * @param altitude the altitude to use when determining the nearest point. Can be approximate and is not necessarily + * the altitude of the terrain position. + * @param locations the list of locations. This list is modified by this method to contain the new location on an + * edge nearest the specified terrain position. * * @return the index at which the new location was inserted into the list. */ - protected int addNearestLocation(Position terrainPosition, double altitude, List locations) - { + protected int addNearestLocation(Position terrainPosition, double altitude, List locations) { Globe globe = this.getWwd().getModel().getGlobe(); // Find the nearest edge to the picked point and insert a new position on that edge. Vec4 pointPicked = globe.computeEllipsoidalPointFromPosition(terrainPosition.getLatitude(), - terrainPosition.getLongitude(), altitude); + terrainPosition.getLongitude(), altitude); Vec4 nearestPoint = null; int nearestSegmentIndex = 0; @@ -1549,35 +1454,35 @@ protected int addNearestLocation(Position terrainPosition, double altitude, List { // Skip the closing segment if the shape is not a polygon. if (!(this.getShape() instanceof Polygon || this.getShape() instanceof SurfacePolygon) - && i == locations.size()) + && i == locations.size()) { continue; + } LatLon locationA = locations.get(i - 1); LatLon locationB = locations.get(i == locations.size() ? 0 : i); Vec4 pointA = globe.computeEllipsoidalPointFromPosition(locationA.getLatitude(), - locationA.getLongitude(), altitude); + locationA.getLongitude(), altitude); Vec4 pointB = globe.computeEllipsoidalPointFromPosition(locationB.getLatitude(), - locationB.getLongitude(), altitude); + locationB.getLongitude(), altitude); Vec4 pointOnEdge = this.nearestPointOnSegment(pointA, pointB, pointPicked); double distance = pointOnEdge.distanceTo3(pointPicked); - if (distance < nearestDistance) - { + if (distance < nearestDistance) { nearestPoint = pointOnEdge; nearestSegmentIndex = i; nearestDistance = distance; } } - if (nearestPoint != null) - { + if (nearestPoint != null) { // Compute the location of the nearest point and add it to the shape. LatLon nearestLocation = globe.computePositionFromEllipsoidalPoint(nearestPoint); - if (nearestSegmentIndex == locations.size()) + if (nearestSegmentIndex == locations.size()) { locations.add(nearestLocation); - else + } else { locations.add(nearestSegmentIndex, nearestLocation); + } this.getControlPointLayer().setMarkers(null); return nearestSegmentIndex; @@ -1591,13 +1496,11 @@ protected int addNearestLocation(Position terrainPosition, double altitude, List * determined by a specified control point. * * @param controlPoint the control point of the shape's end. If the control point's ID is 0 the new location is - * inserted to the beginning of the list. If the control point ID corresponds to the last - * location in the list then the new location is appended to the list. Otherwise no operation - * occurs. - * @param locations the shape's locations. This list is modified upon return to include the new location. + * inserted to the beginning of the list. If the control point ID corresponds to the last location in the list then + * the new location is appended to the list. Otherwise no operation occurs. + * @param locations the shape's locations. This list is modified upon return to include the new location. */ - protected void appendLocation(ControlPointMarker controlPoint, List locations) - { + protected void appendLocation(ControlPointMarker controlPoint, List locations) { // Add a control point to the beginning or end of the shape. Globe globe = this.getWwd().getModel().getGlobe(); @@ -1607,8 +1510,7 @@ protected void appendLocation(ControlPointMarker controlPoint, List loca Vec4 pointB = globe.computeEllipsoidalPointFromLocation(locations.get(1)); Vec4 newPoint = pointA.add3(pointA.subtract3(pointB).multiply3(0.1)); locations.add(0, globe.computePositionFromEllipsoidalPoint(newPoint)); - } - else if (controlPoint.getId() == locations.size() - 1) // end of list + } else if (controlPoint.getId() == locations.size() - 1) // end of list { Vec4 pointA = globe.computeEllipsoidalPointFromLocation(locations.get(locations.size() - 2)); Vec4 pointB = globe.computeEllipsoidalPointFromLocation(locations.get(locations.size() - 1)); @@ -1620,18 +1522,17 @@ else if (controlPoint.getId() == locations.size() - 1) // end of list /** * Moves a control point location. * - * @param controlPoint the control point being moved. + * @param controlPoint the control point being moved. * @param terrainPosition the position selected by the user. - * @param locations the list of locations for the shape. + * @param locations the list of locations for the shape. */ - protected void moveLocation(ControlPointMarker controlPoint, Position terrainPosition, List locations) - { + protected void moveLocation(ControlPointMarker controlPoint, Position terrainPosition, List locations) { // Compute the new location for the polygon location associated with the incoming control point. Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); Vec4 markerPoint = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - new Position(controlPoint.getPosition(), 0)); + new Position(controlPoint.getPosition(), 0)); Position markerPosition = getWwd().getModel().getGlobe().computePositionFromEllipsoidalPoint( - markerPoint.add3(delta)); + markerPoint.add3(delta)); // Update the polygon's locations. locations.set(controlPoint.getId(), markerPosition); @@ -1641,10 +1542,9 @@ protected void moveLocation(ControlPointMarker controlPoint, Position terrainPos * Rotates a shape's locations. * * @param terrainPosition the position selected by the user. - * @param locations the list of locations for the shape. + * @param locations the list of locations for the shape. */ - protected void rotateLocations(Position terrainPosition, List locations) - { + protected void rotateLocations(Position terrainPosition, List locations) { // Rotate the positions. LatLon center = LatLon.getCenter(this.getWwd().getModel().getGlobe(), locations); // rotation axis Angle previousHeading = LatLon.greatCircleAzimuth(center, this.getPreviousPosition()); @@ -1652,8 +1552,7 @@ protected void rotateLocations(Position terrainPosition, List locations) this.currentHeading = this.normalizedHeading(this.getCurrentHeading(), deltaHeading); // Rotate the polygon's locations by the heading delta angle. - for (int i = 0; i < locations.size(); i++) - { + for (int i = 0; i < locations.size(); i++) { LatLon location = locations.get(i); Angle heading = LatLon.greatCircleAzimuth(center, location); @@ -1666,97 +1565,90 @@ protected void rotateLocations(Position terrainPosition, List locations) /** * Performs an edit for {@link gov.nasa.worldwind.render.airspaces.Polygon} shapes. * - * @param controlPoint the control point selected. + * @param controlPoint the control point selected. * @param terrainPosition the terrain position under the cursor. */ - protected void reshapePolygonAirspace(Position terrainPosition, ControlPointMarker controlPoint) - { + protected void reshapePolygonAirspace(Position terrainPosition, ControlPointMarker controlPoint) { Iterable currentLocations = null; - if (this.getShape() instanceof Polygon) + if (this.getShape() instanceof Polygon) { currentLocations = ((Polygon) this.getShape()).getLocations(); - else if (this.getShape() instanceof Curtain) + } else if (this.getShape() instanceof Curtain) { currentLocations = ((Curtain) this.getShape()).getLocations(); + } - if (currentLocations == null) + if (currentLocations == null) { return; + } // Assemble a local copy of the polygon's locations. java.util.List locations = new ArrayList(); - for (LatLon location : currentLocations) - { + for (LatLon location : currentLocations) { locations.add(location); } - if (controlPoint != null && controlPoint.getPurpose().equals(ROTATION)) - { + if (controlPoint != null && controlPoint.getPurpose().equals(ROTATION)) { // Rotate the polygon. this.rotateLocations(terrainPosition, locations); - } - else if (controlPoint != null) // location change or add/delete control point + } else if (controlPoint != null) // location change or add/delete control point { if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + && this.isExtensionEnabled()) { int minSize = this.getShape() instanceof Polygon ? 3 : 2; - if (locations.size() > minSize) - { + if (locations.size() > minSize) { // Delete the control point. locations.remove(controlPoint.getId()); this.getControlPointLayer().setMarkers(null); } - } - else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 - && this.isExtensionEnabled() - && this.getShape() instanceof Curtain) - { + } else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 + && this.isExtensionEnabled() + && this.getShape() instanceof Curtain) { // Add a new control point. this.appendLocation(controlPoint, locations); this.getControlPointLayer().setMarkers(null); - } - else // control point location change + } else // control point location change { this.moveLocation(controlPoint, terrainPosition, locations); } - } - else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + } else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 + && this.isExtensionEnabled()) { // Insert a new location along an edge of the polygon. double altitude = ((Airspace) this.getShape()).getAltitudes()[1]; this.addNearestLocation(terrainPosition, altitude, locations); } // Update the shape's locations. - if (this.getShape() instanceof Polygon) + if (this.getShape() instanceof Polygon) { ((Polygon) this.getShape()).setLocations(locations); - else if (this.getShape() instanceof Curtain) + } else if (this.getShape() instanceof Curtain) { ((Curtain) this.getShape()).setLocations(locations); + } } /** * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.Polygon} shapes. */ - protected void updatePolygonAirspaceControlPoints() - { + protected void updatePolygonAirspaceControlPoints() { Iterable currentLocations = null; - if (this.getShape() instanceof Polygon) + if (this.getShape() instanceof Polygon) { currentLocations = ((Polygon) this.getShape()).getLocations(); - else if (this.getShape() instanceof Curtain) + } else if (this.getShape() instanceof Curtain) { currentLocations = ((Curtain) this.getShape()).getLocations(); + } - if (currentLocations == null) + if (currentLocations == null) { return; + } java.util.List locations = new ArrayList(); - for (LatLon location : currentLocations) - { + for (LatLon location : currentLocations) { locations.add(location); } - if (locations.size() < 2) + if (locations.size() < 2) { return; + } Globe globe = this.getWwd().getModel().getGlobe(); @@ -1771,17 +1663,15 @@ else if (this.getShape() instanceof Curtain) double rotationControlAltitude = this.getControlPointAltitude(rotationControlLocation); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { // Create control points for the polygon locations. ArrayList controlPoints = new ArrayList(); int i = 0; - for (LatLon location : locations) - { + for (LatLon location : locations) { double altitude = this.getControlPointAltitude(location); Position cpPosition = new Position(location, altitude); controlPoints.add( - this.makeControlPoint(cpPosition, this.getLocationControlPointAttributes(), i++, LOCATION)); + this.makeControlPoint(cpPosition, this.getLocationControlPointAttributes(), i++, LOCATION)); } // Create a control point for the rotation control. @@ -1789,13 +1679,10 @@ else if (this.getShape() instanceof Curtain) controlPoints.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), i, ROTATION)); this.getControlPointLayer().setMarkers(controlPoints); - } - else - { + } else { // Update the polygon's location control points. Iterator markerIterator = markers.iterator(); - for (LatLon location : locations) - { + for (LatLon location : locations) { double altitude = this.getControlPointAltitude(location); markerIterator.next().setPosition(new Position(location, altitude)); } @@ -1806,57 +1693,55 @@ else if (this.getShape() instanceof Curtain) // Update the heading annotation. Iterator markerIterator = this.getControlPointLayer().getMarkers().iterator(); - for (LatLon ignored : locations) - { + for (LatLon ignored : locations) { markerIterator.next(); } ((ControlPointMarker) markerIterator.next()).rotation = heading; // Update the rotation orientation line. this.updateOrientationLine(new Position(polygonCenter, centerAltitude), - new Position(rotationControlLocation, rotationControlAltitude)); + new Position(rotationControlLocation, rotationControlAltitude)); } /** * Performs an edit for {@link gov.nasa.worldwind.render.airspaces.CappedCylinder} shapes. * - * @param controlPoint the control point selected. + * @param controlPoint the control point selected. * @param terrainPosition the terrain position under the cursor. */ - protected void reshapeCappedCylinder(Position terrainPosition, ControlPointMarker controlPoint) - { - if (controlPoint == null) + protected void reshapeCappedCylinder(Position terrainPosition, ControlPointMarker controlPoint) { + if (controlPoint == null) { return; // Cannot add locations to this shape. - + } CappedCylinder cylinder = (CappedCylinder) this.getShape(); double[] radii = cylinder.getRadii(); Vec4 centerPoint = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(cylinder.getCenter()); Vec4 markerPoint = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - controlPoint.getPosition()); + controlPoint.getPosition()); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); - if (controlPoint.getPurpose().equals(OUTER_RADIUS)) + if (controlPoint.getPurpose().equals(OUTER_RADIUS)) { radii[1] += delta.dot3(vMarker); - else if (controlPoint.getPurpose().equals(INNER_RADIUS)) + } else if (controlPoint.getPurpose().equals(INNER_RADIUS)) { radii[0] += delta.dot3(vMarker); + } - if (radii[0] >= 0 && radii[1] > 0 && radii[0] < radii[1]) + if (radii[0] >= 0 && radii[1] > 0 && radii[0] < radii[1]) { cylinder.setRadii(radii[0], radii[1]); + } - if (this.getShape() instanceof PartialCappedCylinder) - { + if (this.getShape() instanceof PartialCappedCylinder) { Angle oldHeading = LatLon.greatCircleAzimuth(cylinder.getCenter(), this.getPreviousPosition()); Angle deltaHeading = LatLon.greatCircleAzimuth(cylinder.getCenter(), terrainPosition).subtract(oldHeading); Angle[] azimuths = ((PartialCappedCylinder) cylinder).getAzimuths(); - if (controlPoint.getPurpose().equals(LEFT_AZIMUTH)) + if (controlPoint.getPurpose().equals(LEFT_AZIMUTH)) { azimuths[0] = this.normalizedHeading(azimuths[0], deltaHeading); - else if (controlPoint.getPurpose().equals(RIGHT_AZIMUTH)) + } else if (controlPoint.getPurpose().equals(RIGHT_AZIMUTH)) { azimuths[1] = this.normalizedHeading(azimuths[1], deltaHeading); - else if (controlPoint.getPurpose().equals(ROTATION)) - { + } else if (controlPoint.getPurpose().equals(ROTATION)) { this.currentHeading = this.normalizedHeading(this.getCurrentHeading(), deltaHeading); azimuths[0] = this.normalizedHeading(azimuths[0], deltaHeading); azimuths[1] = this.normalizedHeading(azimuths[1], deltaHeading); @@ -1867,57 +1752,52 @@ else if (controlPoint.getPurpose().equals(ROTATION)) } /** - * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.CappedCylinder} - * shapes. + * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.CappedCylinder} shapes. */ - protected void updateCappedCylinderControlPoints() - { + protected void updateCappedCylinderControlPoints() { CappedCylinder cylinder = (CappedCylinder) this.getShape(); double[] radii = cylinder.getRadii(); boolean hasInnerRadius = radii[0] > 0; LatLon outerRadiusLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), Angle.fromDegrees(90), - Angle.fromRadians(radii[1] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(radii[1] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon innerRadiusLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), Angle.fromDegrees(90), - Angle.fromRadians(radii[0] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(radii[0] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); double outerRadiusAltitude = this.getControlPointAltitude(outerRadiusLocation); double innerRadiusAltitude = this.getControlPointAltitude(innerRadiusLocation); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(1); Position cpPosition = new Position(outerRadiusLocation, outerRadiusAltitude); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, OUTER_RADIUS)); - if (hasInnerRadius) - { + if (hasInnerRadius) { cpPosition = new Position(innerRadiusLocation, innerRadiusAltitude); markerList.add( - this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 1, INNER_RADIUS)); + this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 1, INNER_RADIUS)); } this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { Iterator markerIterator = markers.iterator(); markerIterator.next().setPosition(new Position(outerRadiusLocation, outerRadiusAltitude)); - if (hasInnerRadius) + if (hasInnerRadius) { markerIterator.next().setPosition(new Position(innerRadiusLocation, innerRadiusAltitude)); + } } Iterator markerIterator = this.getControlPointLayer().getMarkers().iterator(); ((ControlPointMarker) markerIterator.next()).size = radii[1]; - if (hasInnerRadius) + if (hasInnerRadius) { ((ControlPointMarker) markerIterator.next()).size = radii[0]; + } } /** * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.PartialCappedCylinder} * shapes. */ - protected void updatePartialCappedCylinderControlPoints() - { + protected void updatePartialCappedCylinderControlPoints() { PartialCappedCylinder cylinder = (PartialCappedCylinder) this.getShape(); double[] radii = cylinder.getRadii(); @@ -1927,14 +1807,14 @@ protected void updatePartialCappedCylinderControlPoints() Angle[] azimuths = cylinder.getAzimuths(); LatLon outerRadiusLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), azimuths[1], - Angle.fromRadians(radii[1] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(radii[1] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon innerRadiusLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), azimuths[1], - Angle.fromRadians(radii[0] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(radii[0] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon leftAzimuthLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), azimuths[0], - Angle.fromRadians(averageRadius / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(averageRadius / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon rightAzimuthLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), azimuths[1], - Angle.fromRadians(averageRadius / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(averageRadius / this.getWwd().getModel().getGlobe().getEquatorialRadius())); double outerRadiusAltitude = this.getControlPointAltitude(outerRadiusLocation); double innerRadiusAltitude = this.getControlPointAltitude(innerRadiusLocation); @@ -1942,40 +1822,37 @@ protected void updatePartialCappedCylinderControlPoints() double leftAzimuthAltitude = this.getControlPointAltitude(leftAzimuthLocation); LatLon rotationControlLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), this.getCurrentHeading(), - Angle.fromRadians(1.2 * radii[1] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(1.2 * radii[1] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); double rotationControlAltitude = this.getControlPointAltitude(rotationControlLocation); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(1); Position cpPosition = new Position(outerRadiusLocation, outerRadiusAltitude); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, OUTER_RADIUS)); - if (hasInnerRadius) - { + if (hasInnerRadius) { cpPosition = new Position(innerRadiusLocation, innerRadiusAltitude); markerList.add( - this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 1, INNER_RADIUS)); + this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 1, INNER_RADIUS)); } cpPosition = new Position(leftAzimuthLocation, leftAzimuthAltitude); markerList.add( - this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 2, LEFT_AZIMUTH)); + this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 2, LEFT_AZIMUTH)); cpPosition = new Position(rightAzimuthLocation, rightAzimuthAltitude); markerList.add( - this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 3, RIGHT_AZIMUTH)); + this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 3, RIGHT_AZIMUTH)); cpPosition = new Position(rotationControlLocation, rotationControlAltitude); markerList.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 4, ROTATION)); this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { Iterator markerIterator = markers.iterator(); markerIterator.next().setPosition(new Position(outerRadiusLocation, outerRadiusAltitude)); - if (hasInnerRadius) + if (hasInnerRadius) { markerIterator.next().setPosition(new Position(innerRadiusLocation, rightAzimuthAltitude)); + } markerIterator.next().setPosition(new Position(leftAzimuthLocation, leftAzimuthAltitude)); markerIterator.next().setPosition(new Position(rightAzimuthLocation, rightAzimuthAltitude)); @@ -1984,8 +1861,9 @@ protected void updatePartialCappedCylinderControlPoints() Iterator markerIterator = this.getControlPointLayer().getMarkers().iterator(); ((ControlPointMarker) markerIterator.next()).size = radii[1]; - if (hasInnerRadius) + if (hasInnerRadius) { ((ControlPointMarker) markerIterator.next()).size = radii[0]; + } ((ControlPointMarker) markerIterator.next()).rotation = azimuths[0]; ((ControlPointMarker) markerIterator.next()).rotation = azimuths[1]; @@ -1995,79 +1873,76 @@ protected void updatePartialCappedCylinderControlPoints() // Update the rotation orientation line. double centerAltitude = this.getControlPointAltitude(cylinder.getCenter()); this.updateOrientationLine(new Position(cylinder.getCenter(), centerAltitude), - new Position(rotationControlLocation, rotationControlAltitude)); + new Position(rotationControlLocation, rotationControlAltitude)); } /** * Performs an edit for {@link gov.nasa.worldwind.render.airspaces.CappedCylinder} shapes. * - * @param controlPoint the control point selected. + * @param controlPoint the control point selected. * @param terrainPosition the terrain position under the cursor. */ - protected void reshapeCappedEllipticalCylinder(Position terrainPosition, ControlPointMarker controlPoint) - { - if (controlPoint == null) + protected void reshapeCappedEllipticalCylinder(Position terrainPosition, ControlPointMarker controlPoint) { + if (controlPoint == null) { return; // Cannot add locations to this shape. - + } CappedEllipticalCylinder cylinder = (CappedEllipticalCylinder) this.getShape(); double[] radii = cylinder.getRadii(); Vec4 centerPoint = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(cylinder.getCenter()); Vec4 markerPoint = getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - controlPoint.getPosition()); + controlPoint.getPosition()); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); - if (controlPoint.getPurpose().equals(INNER_MINOR_RADIUS)) + if (controlPoint.getPurpose().equals(INNER_MINOR_RADIUS)) { radii[0] += delta.dot3(vMarker); - else if (controlPoint.getPurpose().equals(INNER_MAJOR_RADIUS)) + } else if (controlPoint.getPurpose().equals(INNER_MAJOR_RADIUS)) { radii[1] += delta.dot3(vMarker); - else if (controlPoint.getPurpose().equals(OUTER_MINOR_RADIUS)) + } else if (controlPoint.getPurpose().equals(OUTER_MINOR_RADIUS)) { radii[2] += delta.dot3(vMarker); - else if (controlPoint.getPurpose().equals(OUTER_MAJOR_RADIUS)) + } else if (controlPoint.getPurpose().equals(OUTER_MAJOR_RADIUS)) { radii[3] += delta.dot3(vMarker); - else if (controlPoint.getPurpose().equals(ROTATION)) { + } else if (controlPoint.getPurpose().equals(ROTATION)) { Angle oldHeading = LatLon.greatCircleAzimuth(cylinder.getCenter(), this.getPreviousPosition()); Angle deltaHeading = LatLon.greatCircleAzimuth(cylinder.getCenter(), terrainPosition).subtract(oldHeading); cylinder.setHeading(this.normalizedHeading(cylinder.getHeading(), deltaHeading)); this.currentHeading = this.normalizedHeading(this.getCurrentHeading(), deltaHeading); } - if (isRadiiValid(radii[0], radii[2]) && isRadiiValid(radii[1], radii[3])) + if (isRadiiValid(radii[0], radii[2]) && isRadiiValid(radii[1], radii[3])) { cylinder.setRadii(radii[0], radii[1], radii[2], radii[3]); + } } - protected static boolean isRadiiValid(double innerRadius, double outerRadius) - { + protected static boolean isRadiiValid(double innerRadius, double outerRadius) { return innerRadius >= 0 && innerRadius < outerRadius; } /** - * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.CappedCylinder} - * shapes. + * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.CappedCylinder} shapes. */ - protected void updateCappedEllipticalCylinderControlPoints() - { + protected void updateCappedEllipticalCylinderControlPoints() { CappedEllipticalCylinder cylinder = (CappedEllipticalCylinder) this.getShape(); double[] radii = cylinder.getRadii(); boolean hasInnerRadius = radii[0] > 0 && radii[1] > 0; Angle heading = cylinder.getHeading(); LatLon innerMinorRadiusLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), - Angle.fromDegrees(90).add(heading), - Angle.fromRadians(radii[0] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(90).add(heading), + Angle.fromRadians(radii[0] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon innerMajorRadiusLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), - Angle.fromDegrees(0).add(heading), - Angle.fromRadians(radii[1] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(0).add(heading), + Angle.fromRadians(radii[1] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon outerMinorRadiusLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), - Angle.fromDegrees(90).add(heading), - Angle.fromRadians(radii[2] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(90).add(heading), + Angle.fromRadians(radii[2] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon outerMajorRadiusLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), - Angle.fromDegrees(0).add(heading), - Angle.fromRadians(radii[3] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(0).add(heading), + Angle.fromRadians(radii[3] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon rotationControlLocation = LatLon.greatCircleEndPosition(cylinder.getCenter(), this.getCurrentHeading(), - Angle.fromRadians(1.4 * radii[3] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(1.4 * radii[3] / this.getWwd().getModel().getGlobe().getEquatorialRadius())); double rotationControlAltitude = this.getControlPointAltitude(rotationControlLocation); double innerMinorRadiusAltitude = this.getControlPointAltitude(innerMinorRadiusLocation); @@ -2076,35 +1951,30 @@ protected void updateCappedEllipticalCylinderControlPoints() double outerMajorRadiusAltitude = this.getControlPointAltitude(outerMajorRadiusLocation); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(2); Position cpPosition = new Position(outerMinorRadiusLocation, outerMinorRadiusAltitude); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 2, OUTER_MINOR_RADIUS)); cpPosition = new Position(outerMajorRadiusLocation, outerMajorRadiusAltitude); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 3, OUTER_MAJOR_RADIUS)); - if (hasInnerRadius) - { + if (hasInnerRadius) { cpPosition = new Position(innerMinorRadiusLocation, innerMinorRadiusAltitude); markerList.add( - this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, INNER_MINOR_RADIUS)); + this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, INNER_MINOR_RADIUS)); cpPosition = new Position(innerMajorRadiusLocation, innerMajorRadiusAltitude); markerList.add( - this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 1, INNER_MAJOR_RADIUS)); + this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 1, INNER_MAJOR_RADIUS)); } cpPosition = new Position(rotationControlLocation, rotationControlAltitude); markerList.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 4, ROTATION)); this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { Iterator markerIterator = markers.iterator(); markerIterator.next().setPosition(new Position(outerMinorRadiusLocation, outerMinorRadiusAltitude)); markerIterator.next().setPosition(new Position(outerMajorRadiusLocation, outerMajorRadiusAltitude)); - if (hasInnerRadius) - { + if (hasInnerRadius) { markerIterator.next().setPosition(new Position(innerMinorRadiusLocation, innerMinorRadiusAltitude)); markerIterator.next().setPosition(new Position(innerMajorRadiusLocation, innerMajorRadiusAltitude)); } @@ -2115,8 +1985,7 @@ protected void updateCappedEllipticalCylinderControlPoints() Iterator markerIterator = this.getControlPointLayer().getMarkers().iterator(); ((ControlPointMarker) markerIterator.next()).size = radii[2]; ((ControlPointMarker) markerIterator.next()).size = radii[3]; - if (hasInnerRadius) - { + if (hasInnerRadius) { ((ControlPointMarker) markerIterator.next()).size = radii[0]; ((ControlPointMarker) markerIterator.next()).size = radii[1]; } @@ -2126,61 +1995,57 @@ protected void updateCappedEllipticalCylinderControlPoints() // Update the rotation orientation line. double centerAltitude = this.getControlPointAltitude(cylinder.getCenter()); this.updateOrientationLine(new Position(cylinder.getCenter(), centerAltitude), - new Position(rotationControlLocation, rotationControlAltitude)); + new Position(rotationControlLocation, rotationControlAltitude)); } /** * Performs an edit for {@link gov.nasa.worldwind.render.airspaces.SphereAirspace} shapes. * - * @param controlPoint the control point selected. + * @param controlPoint the control point selected. * @param terrainPosition the terrain position under the cursor. */ - protected void reshapeSphere(Position terrainPosition, ControlPointMarker controlPoint) - { - if (controlPoint == null) + protected void reshapeSphere(Position terrainPosition, ControlPointMarker controlPoint) { + if (controlPoint == null) { return; // Cannot add locations to this shape. - + } SphereAirspace sphere = (SphereAirspace) this.getShape(); double radius = sphere.getRadius(); Vec4 centerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - sphere.getLocation()); + sphere.getLocation()); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - controlPoint.getPosition()); + controlPoint.getPosition()); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); - if (controlPoint.getPurpose().equals(OUTER_RADIUS)) + if (controlPoint.getPurpose().equals(OUTER_RADIUS)) { radius += delta.dot3(vMarker); + } - if (radius > 0) + if (radius > 0) { sphere.setRadius(radius); + } } /** - * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.SphereAirspace} - * shapes. + * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.SphereAirspace} shapes. */ - protected void updateSphereControlPoints() - { + protected void updateSphereControlPoints() { SphereAirspace sphere = (SphereAirspace) this.getShape(); double radius = sphere.getRadius(); LatLon radiusLocation = LatLon.greatCircleEndPosition(sphere.getLocation(), Angle.fromDegrees(90), - Angle.fromRadians(radius / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(radius / this.getWwd().getModel().getGlobe().getEquatorialRadius())); double radiusAltitude = this.getControlPointAltitude(radiusLocation); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(1); Position cpPosition = new Position(radiusLocation, radiusAltitude); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, OUTER_RADIUS)); this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { Iterator markerIterator = markers.iterator(); markerIterator.next().setPosition(new Position(radiusLocation, radiusAltitude)); } @@ -2192,14 +2057,13 @@ protected void updateSphereControlPoints() /** * Performs an edit for {@link gov.nasa.worldwind.render.airspaces.Orbit} shapes. * - * @param controlPoint the control point selected. + * @param controlPoint the control point selected. * @param terrainPosition the terrain position under the cursor. */ - protected void reshapeOrbit(Position terrainPosition, ControlPointMarker controlPoint) - { - if (controlPoint == null) + protected void reshapeOrbit(Position terrainPosition, ControlPointMarker controlPoint) { + if (controlPoint == null) { return; // Cannot add locations to this shape. - + } Orbit orbit = (Orbit) this.getShape(); LatLon[] locations = orbit.getLocations(); double width = orbit.getWidth(); @@ -2208,34 +2072,30 @@ protected void reshapeOrbit(Position terrainPosition, ControlPointMarker control Vec4 centerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(center); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - new Position(controlPoint.getPosition(), 0)); + new Position(controlPoint.getPosition(), 0)); - if (controlPoint.getPurpose().equals(RIGHT_WIDTH)) - { + if (controlPoint.getPurpose().equals(RIGHT_WIDTH)) { Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); double newWidth = width + delta.dot3(vMarker); - if (newWidth > 0) + if (newWidth > 0) { orbit.setWidth(width + delta.dot3(vMarker)); - } - else if (controlPoint.getPurpose().equals(ROTATION)) - { + } + } else if (controlPoint.getPurpose().equals(ROTATION)) { Angle oldHeading = LatLon.greatCircleAzimuth(center, this.getPreviousPosition()); Angle deltaHeading = LatLon.greatCircleAzimuth(center, terrainPosition).subtract(oldHeading); - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { Angle heading = LatLon.greatCircleAzimuth(center, locations[i]); Angle distance = LatLon.greatCircleDistance(center, locations[i]); locations[i] = LatLon.greatCircleEndPosition(center, heading.add(deltaHeading), distance); } orbit.setLocations(locations[0], locations[1]); - } - else // location change + } else // location change { Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); Position markerPosition = this.getWwd().getModel().getGlobe().computePositionFromEllipsoidalPoint( - markerPoint.add3(delta)); + markerPoint.add3(delta)); locations[controlPoint.getId()] = markerPosition; orbit.setLocations(locations[0], locations[1]); } @@ -2244,8 +2104,7 @@ else if (controlPoint.getPurpose().equals(ROTATION)) /** * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.Orbit} shapes. */ - protected void updateOrbitControlPoints() - { + protected void updateOrbitControlPoints() { Orbit orbit = (Orbit) this.getShape(); LatLon[] locations = orbit.getLocations(); double width = orbit.getWidth(); @@ -2268,8 +2127,7 @@ protected void updateOrbitControlPoints() double rotationControlAltitude = this.getControlPointAltitude(rotationControlLocation); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(1); Position cpPosition = new Position(locations[0], location0Altitude); markerList.add(this.makeControlPoint(cpPosition, this.getLocationControlPointAttributes(), 0, LOCATION)); @@ -2283,9 +2141,7 @@ protected void updateOrbitControlPoints() markerList.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 3, ROTATION)); this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { Iterator markerIterator = markers.iterator(); markerIterator.next().setPosition(new Position(locations[0], location0Altitude)); markerIterator.next().setPosition(new Position(locations[1], location1Altitude)); @@ -2300,71 +2156,59 @@ protected void updateOrbitControlPoints() ((ControlPointMarker) markerIterator.next()).rotation = this.normalizedHeading(orbitHeading, Angle.ZERO); this.updateOrientationLine(new Position(center, centerAltitude), - new Position(rotationControlLocation, rotationControlAltitude)); + new Position(rotationControlLocation, rotationControlAltitude)); } /** * Performs an edit for {@link gov.nasa.worldwind.render.airspaces.Route} shapes. * - * @param controlPoint the control point selected. + * @param controlPoint the control point selected. * @param terrainPosition the terrain position under the cursor. */ - protected void reshapeRoute(Position terrainPosition, ControlPointMarker controlPoint) - { + protected void reshapeRoute(Position terrainPosition, ControlPointMarker controlPoint) { Route route = (Route) this.getShape(); java.util.List locations = new ArrayList(); - for (LatLon ll : route.getLocations()) - { + for (LatLon ll : route.getLocations()) { locations.add(ll); } - if (controlPoint != null && controlPoint.getPurpose().equals(ROTATION)) - { + if (controlPoint != null && controlPoint.getPurpose().equals(ROTATION)) { this.rotateLocations(terrainPosition, locations); route.setLocations(locations); - } - else if (controlPoint != null - && (controlPoint.getPurpose().equals(LEFT_WIDTH) || controlPoint.getPurpose().equals(RIGHT_WIDTH))) - { + } else if (controlPoint != null + && (controlPoint.getPurpose().equals(LEFT_WIDTH) || controlPoint.getPurpose().equals(RIGHT_WIDTH))) { LatLon legCenter = LatLon.interpolateGreatCircle(0.5, locations.get(0), locations.get(1)); Vec4 centerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(legCenter); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - new Position(controlPoint.getPosition(), 0)); + new Position(controlPoint.getPosition(), 0)); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); double newWidth = route.getWidth() + delta.dot3(vMarker); - if (newWidth >= 0) + if (newWidth >= 0) { route.setWidth(newWidth); - } - else if (controlPoint != null) // location change or add/delete control point + } + } else if (controlPoint != null) // location change or add/delete control point { if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { - if (locations.size() > 2) - { + && this.isExtensionEnabled()) { + if (locations.size() > 2) { // Delete the control point. locations.remove(controlPoint.getId()); this.getControlPointLayer().setMarkers(null); } - } - else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + } else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 + && this.isExtensionEnabled()) { this.appendLocation(controlPoint, locations); this.getControlPointLayer().setMarkers(null); - } - else // control point location change + } else // control point location change { this.moveLocation(controlPoint, terrainPosition, locations); } route.setLocations(locations); - } - else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + } else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 + && this.isExtensionEnabled()) { // Insert a new position into the shape. double altitude = ((Airspace) this.getShape()).getAltitudes()[1]; this.addNearestLocation(terrainPosition, altitude, locations); @@ -2375,28 +2219,28 @@ else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.S /** * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.Route} shapes. */ - protected void updateRouteControlPoints() - { + protected void updateRouteControlPoints() { Route route = (Route) this.getShape(); - if (route.getLocations() == null) + if (route.getLocations() == null) { return; + } java.util.List locations = new ArrayList(); - for (LatLon location : route.getLocations()) - { + for (LatLon location : route.getLocations()) { locations.add(location); } - if (locations.size() < 2) + if (locations.size() < 2) { return; + } Globe globe = this.getWwd().getModel().getGlobe(); double width = route.getWidth(); Position leftWidthPosition = this.computeRectangularEdgeLocation(locations.get(0), locations.get(1), - -0.5 * width); + -0.5 * width); Position rightWidthPosition = this.computeRectangularEdgeLocation(locations.get(0), locations.get(1), - 0.5 * width); + 0.5 * width); LatLon routeCenter = LatLon.getCenter(globe, locations); double centerAltitude = this.getControlPointAltitude(routeCenter); @@ -2409,16 +2253,14 @@ protected void updateRouteControlPoints() double rotationControlAltitude = this.getControlPointAltitude(rotationControlLocation); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { ArrayList controlPoints = new ArrayList(); int i = 0; - for (LatLon cpPosition : locations) - { + for (LatLon cpPosition : locations) { double altitude = this.getControlPointAltitude(cpPosition); Position position = new Position(cpPosition, altitude); controlPoints.add( - this.makeControlPoint(position, this.getLocationControlPointAttributes(), i++, LOCATION)); + this.makeControlPoint(position, this.getLocationControlPointAttributes(), i++, LOCATION)); } Position position = new Position(leftWidthPosition, leftWidthPosition.getAltitude()); @@ -2430,12 +2272,9 @@ protected void updateRouteControlPoints() controlPoints.add(this.makeControlPoint(position, this.getAngleControlPointAttributes(), i, ROTATION)); this.getControlPointLayer().setMarkers(controlPoints); - } - else - { + } else { Iterator markerIterator = markers.iterator(); - for (LatLon cpPosition : locations) - { + for (LatLon cpPosition : locations) { double altitude = this.getControlPointAltitude(cpPosition); markerIterator.next().setPosition(new Position(cpPosition, altitude)); } @@ -2455,25 +2294,22 @@ protected void updateRouteControlPoints() ((ControlPointMarker) markerIterator.next()).rotation = heading; this.updateOrientationLine(new Position(routeCenter, centerAltitude), - new Position(rotationControlLocation, rotationControlAltitude)); + new Position(rotationControlLocation, rotationControlAltitude)); } /** * Performs an edit for {@link gov.nasa.worldwind.render.airspaces.TrackAirspace} shapes. * - * @param controlPoint the control point selected. + * @param controlPoint the control point selected. * @param terrainPosition the terrain position under the cursor. */ - protected void reshapeTrack(Position terrainPosition, ControlPointMarker controlPoint) - { + protected void reshapeTrack(Position terrainPosition, ControlPointMarker controlPoint) { TrackAirspace track = (TrackAirspace) this.getShape(); List legs = track.getLegs(); - if (controlPoint != null && controlPoint.getPurpose().equals(ROTATION)) - { + if (controlPoint != null && controlPoint.getPurpose().equals(ROTATION)) { List trackLocations = new ArrayList(); - for (Box leg : legs) - { + for (Box leg : legs) { trackLocations.add(leg.getLocations()[0]); trackLocations.add(leg.getLocations()[1]); } @@ -2483,8 +2319,7 @@ protected void reshapeTrack(Position terrainPosition, ControlPointMarker control this.currentHeading = this.normalizedHeading(this.getCurrentHeading(), deltaHeading); // Rotate all the legs. - for (Box leg : legs) - { + for (Box leg : legs) { LatLon[] locations = leg.getLocations(); Angle heading = LatLon.greatCircleAzimuth(center, locations[0]); @@ -2499,63 +2334,54 @@ protected void reshapeTrack(Position terrainPosition, ControlPointMarker control } track.setLegs(new ArrayList(track.getLegs())); - } - else if (controlPoint != null - && (controlPoint.getPurpose().equals(LEFT_WIDTH) || controlPoint.getPurpose().equals(RIGHT_WIDTH))) - { + } else if (controlPoint != null + && (controlPoint.getPurpose().equals(LEFT_WIDTH) || controlPoint.getPurpose().equals(RIGHT_WIDTH))) { Box leg = legs.get(controlPoint.getLeg()); LatLon[] legLocations = leg.getLocations(); LatLon legCenter = LatLon.interpolateGreatCircle(0.5, legLocations[0], legLocations[1]); Vec4 centerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(legCenter); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - new Position(controlPoint.getPosition(), 0)); + new Position(controlPoint.getPosition(), 0)); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); double[] widths = leg.getWidths(); - double[] newWidths = new double[] {widths[0], widths[1]}; + double[] newWidths = new double[]{widths[0], widths[1]}; Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); - if (controlPoint.getPurpose().equals(LEFT_WIDTH)) + if (controlPoint.getPurpose().equals(LEFT_WIDTH)) { newWidths[0] += delta.dot3(vMarker); - else + } else { newWidths[1] += delta.dot3(vMarker); + } - if (newWidths[0] >= 0 && newWidths[1] >= 0) - { + if (newWidths[0] >= 0 && newWidths[1] >= 0) { leg.setWidths(newWidths[0], newWidths[1]); } track.setLegs(new ArrayList(track.getLegs())); - } - else if (controlPoint != null) - { + } else if (controlPoint != null) { // Make a modifiable copy of the legs list. legs = new ArrayList(legs); if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + && this.isExtensionEnabled()) { // Remove a control point. if (legs.size() < 2) // Can't remove a control point from a single-leg track. + { return; + } - if (controlPoint.getLeg() == 0 && controlPoint.getId() == 0) - { + if (controlPoint.getLeg() == 0 && controlPoint.getId() == 0) { legs.remove(0); - } - else if (controlPoint.getLeg() == legs.size() - 1 && controlPoint.getId() == 1) - { + } else if (controlPoint.getLeg() == legs.size() - 1 && controlPoint.getId() == 1) { legs.remove(legs.size() - 1); - } - else - { + } else { if (controlPoint.getLeg() == 0) // need to treat the second control point of leg 0 specially { legs.get(0).setLocations(legs.get(0).getLocations()[0], legs.get(1).getLocations()[1]); legs.remove(1); - } - else // remove an internal control point + } else // remove an internal control point { Box leftLeg = controlPoint.getLeg() == 0 ? legs.get(0) : legs.get(controlPoint.getLeg() - 1); Box rightLeg = legs.get(controlPoint.getLeg() + 1); @@ -2567,10 +2393,8 @@ else if (controlPoint.getLeg() == legs.size() - 1 && controlPoint.getId() == 1) track.setLegs(legs); this.determineTrackAdjacency(); this.getControlPointLayer().setMarkers(null); - } - else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + } else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 + && this.isExtensionEnabled()) { // Append a location to the beginning or end of the track. Globe globe = this.getWwd().getModel().getGlobe(); @@ -2585,8 +2409,7 @@ else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.S Box newLeg = new Box(legs.get(0)); newLeg.setLocations(newLocation, legs.get(0).getLocations()[0]); legs.add(0, newLeg); - } - else if (controlPoint.getLeg() == legs.size() - 1 && controlPoint.getId() == 1) // last control point + } else if (controlPoint.getLeg() == legs.size() - 1 && controlPoint.getId() == 1) // last control point { Box lastLeg = legs.get(legs.size() - 1); Vec4 pointA = globe.computeEllipsoidalPointFromLocation(lastLeg.getLocations()[1]); @@ -2597,42 +2420,37 @@ else if (controlPoint.getLeg() == legs.size() - 1 && controlPoint.getId() == 1) Box newLeg = new Box(lastLeg); newLeg.setLocations(lastLeg.getLocations()[1], newLocation); legs.add(newLeg); - } - else - { + } else { return; // the point is internal rather than at the end } track.setLegs(legs); this.determineTrackAdjacency(); this.getControlPointLayer().setMarkers(null); - } - else // control point location change + } else // control point location change { Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - new Position(controlPoint.getPosition(), 0)); + new Position(controlPoint.getPosition(), 0)); Position markerPosition = this.getWwd().getModel().getGlobe().computePositionFromEllipsoidalPoint( - markerPoint.add3(delta)); + markerPoint.add3(delta)); Box leg = track.getLegs().get(controlPoint.getLeg()); - if (controlPoint.getId() == 0) + if (controlPoint.getId() == 0) { leg.setLocations(markerPosition, leg.getLocations()[1]); - else + } else { leg.setLocations(leg.getLocations()[0], markerPosition); + } track.setLegs(new ArrayList(track.getLegs())); } - } - else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + } else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 + && this.isExtensionEnabled()) { // Make a modifiable copy of the legs list. legs = new ArrayList(legs); List locations = new ArrayList(); - for (Box leg : legs) - { + for (Box leg : legs) { locations.add(leg.getLocations()[0]); } locations.add(legs.get(legs.size() - 1).getLocations()[1]); // add the last point of the last leg. @@ -2644,14 +2462,11 @@ else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.S Box leg = legs.get(legIndex); Box newLeg = new Box(leg); - if (legIndex > 0) - { + if (legIndex > 0) { newLeg.setLocations(leg.getLocations()[0], newLocation); leg.setLocations(newLocation, leg.getLocations()[1]); legs.add(legIndex, newLeg); - } - else - { + } else { newLeg.setLocations(newLocation, leg.getLocations()[1]); leg.setLocations(leg.getLocations()[0], newLocation); legs.add(1, newLeg); @@ -2666,44 +2481,38 @@ else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.S /** * Updates the control points and affordances for {@link gov.nasa.worldwind.render.airspaces.TrackAirspace} shapes. */ - protected void updateTrackControlPoints() - { + protected void updateTrackControlPoints() { TrackAirspace track = (TrackAirspace) this.getShape(); List legs = track.getLegs(); - if (legs == null) + if (legs == null) { return; + } // Update the location control points. ArrayList controlPoints = new ArrayList(); Iterable markers = this.getControlPointLayer().getMarkers(); Iterator markerIterator = markers != null ? markers.iterator() : null; - for (int i = 0; i < legs.size(); i++) - { + for (int i = 0; i < legs.size(); i++) { Box leg = legs.get(i); LatLon[] legLocations = leg.getLocations(); double altitude; - if (markers == null) - { - if (!this.trackAdjacencyList.contains(leg)) - { + if (markers == null) { + if (!this.trackAdjacencyList.contains(leg)) { altitude = this.getControlPointAltitude(legLocations[0]); ControlPointMarker cp = this.makeControlPoint(new Position(legLocations[0], altitude), - this.getLocationControlPointAttributes(), 0, i, LOCATION); + this.getLocationControlPointAttributes(), 0, i, LOCATION); controlPoints.add(cp); } altitude = this.getControlPointAltitude(legLocations[1]); ControlPointMarker cp = this.makeControlPoint(new Position(legLocations[1], altitude), - this.getLocationControlPointAttributes(), 1, i, LOCATION); + this.getLocationControlPointAttributes(), 1, i, LOCATION); controlPoints.add(cp); - } - else - { - if (!this.trackAdjacencyList.contains(leg)) - { + } else { + if (!this.trackAdjacencyList.contains(leg)) { altitude = this.getControlPointAltitude(legLocations[0]); markerIterator.next().setPosition(new Position(legLocations[0], altitude)); } @@ -2714,8 +2523,7 @@ protected void updateTrackControlPoints() } // Update the width control points. - for (int i = 0; i < legs.size(); i++) - { + for (int i = 0; i < legs.size(); i++) { Box leg = legs.get(i); LatLon[] legLocations = leg.getLocations(); double[] widths = leg.getWidths(); @@ -2723,17 +2531,14 @@ protected void updateTrackControlPoints() Position cwLPosition = this.computeRectangularEdgeLocation(legLocations[0], legLocations[1], -widths[0]); Position cwRPosition = this.computeRectangularEdgeLocation(legLocations[0], legLocations[1], widths[1]); - if (markers == null) - { + if (markers == null) { Position cpPosition = new Position(cwLPosition, cwLPosition.getAltitude()); controlPoints.add( - this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 2, i, LEFT_WIDTH)); + this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 2, i, LEFT_WIDTH)); cpPosition = new Position(cwRPosition, cwRPosition.getAltitude()); controlPoints.add( - this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 3, i, RIGHT_WIDTH)); - } - else - { + this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 3, i, RIGHT_WIDTH)); + } else { //noinspection ConstantConditions markerIterator.next().setPosition(new Position(cwLPosition, cwLPosition.getAltitude())); markerIterator.next().setPosition(new Position(cwRPosition, cwRPosition.getAltitude())); @@ -2742,8 +2547,7 @@ protected void updateTrackControlPoints() // Update the rotation control points. List trackLocations = new ArrayList(); - for (Box leg : legs) - { + for (Box leg : legs) { trackLocations.add(leg.getLocations()[0]); trackLocations.add(leg.getLocations()[1]); } @@ -2759,110 +2563,99 @@ protected void updateTrackControlPoints() LatLon rotationLocation = LatLon.greatCircleEndPosition(trackCenter, heading, trackRadius); double rotationAltitude = this.getControlPointAltitude(rotationLocation); - if (markers == null) - { + if (markers == null) { Position cpPosition = new Position(rotationLocation, rotationAltitude); controlPoints.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 4, ROTATION)); - } - else - { + } else { //noinspection ConstantConditions markerIterator.next().setPosition(new Position(rotationLocation, rotationAltitude)); } - if (markers == null) + if (markers == null) { this.getControlPointLayer().setMarkers(controlPoints); + } this.updateOrientationLine(new Position(trackCenter, trackCenterAltitude), - new Position(rotationLocation, rotationAltitude)); + new Position(rotationLocation, rotationAltitude)); markers = this.getControlPointLayer().getMarkers(); - for (Marker marker : markers) - { + for (Marker marker : markers) { ControlPointMarker cp = (ControlPointMarker) marker; - if (cp.getId() == 2) + if (cp.getId() == 2) { cp.size = legs.get(cp.getLeg()).getWidths()[0]; - else if (cp.getId() == 3) + } else if (cp.getId() == 3) { cp.size = legs.get(cp.getLeg()).getWidths()[1]; - else if (cp.getId() == 4) + } else if (cp.getId() == 4) { cp.rotation = heading; + } } } - protected void reshapeSurfacePolygon(Position terrainPosition, ControlPointMarker controlPoint) - { + protected void reshapeSurfacePolygon(Position terrainPosition, ControlPointMarker controlPoint) { Iterable corners = this.getShape() instanceof SurfacePolygon - ? ((SurfacePolygon) this.getShape()).getLocations() : ((SurfacePolyline) this.getShape()).getLocations(); + ? ((SurfacePolygon) this.getShape()).getLocations() : ((SurfacePolyline) this.getShape()).getLocations(); java.util.List locations = new ArrayList(); - for (LatLon ll : corners) - { + for (LatLon ll : corners) { locations.add(ll); } - if (controlPoint != null && controlPoint.getPurpose().equals(ROTATION)) - { + if (controlPoint != null && controlPoint.getPurpose().equals(ROTATION)) { // Rotate the polygon. this.rotateLocations(terrainPosition, locations); - } - else if (controlPoint != null) // control point location change or add/delete a control point + } else if (controlPoint != null) // control point location change or add/delete a control point { if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + && this.isExtensionEnabled()) { int minSize = this.getShape() instanceof SurfacePolygon ? 3 : 2; - if (locations.size() > minSize) - { + if (locations.size() > minSize) { // Delete the control point. locations.remove(controlPoint.getId()); this.getControlPointLayer().setMarkers(null); } - } - else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 - && this.isExtensionEnabled() - && this.getShape() instanceof SurfacePolyline) - { + } else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 + && this.isExtensionEnabled() + && this.getShape() instanceof SurfacePolyline) { this.appendLocation(controlPoint, locations); this.getControlPointLayer().setMarkers(null); - } - else // location change + } else // location change { this.moveLocation(controlPoint, terrainPosition, locations); } - } - else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 - && this.isExtensionEnabled()) - { + } else if ((this.getCurrentEvent().getMouseEvent().getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) != 0 + && this.isExtensionEnabled()) { this.addNearestLocation(terrainPosition, 0, locations); } - if (this.getShape() instanceof SurfacePolygon) + if (this.getShape() instanceof SurfacePolygon) { ((SurfacePolygon) this.getShape()).setLocations(locations); - else + } else { ((SurfacePolyline) this.getShape()).setLocations(locations); + } } - protected void updateSurfacePolygonControlPoints() - { + protected void updateSurfacePolygonControlPoints() { Iterable locationsIterable = null; - if (this.getShape() instanceof SurfacePolygon) + if (this.getShape() instanceof SurfacePolygon) { locationsIterable = ((SurfacePolygon) this.getShape()).getLocations(); - else if (this.getShape() instanceof SurfacePolyline) + } else if (this.getShape() instanceof SurfacePolyline) { locationsIterable = ((SurfacePolyline) this.getShape()).getLocations(); + } - if (locationsIterable == null) + if (locationsIterable == null) { return; + } java.util.List locations = new ArrayList(); - for (LatLon location : locationsIterable) - { + for (LatLon location : locationsIterable) { locations.add(location); } - if (locations.size() < 2) + if (locations.size() < 2) { return; + } Globe globe = this.getWwd().getModel().getGlobe(); @@ -2873,15 +2666,13 @@ else if (this.getShape() instanceof SurfacePolyline) LatLon rotationControlLocation = LatLon.greatCircleEndPosition(polygonCenter, heading, shapeRadius); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { ArrayList controlPoints = new ArrayList(); int i = 0; - for (LatLon corner : locations) - { + for (LatLon corner : locations) { Position cpPosition = new Position(corner, 0); controlPoints.add( - this.makeControlPoint(cpPosition, this.getLocationControlPointAttributes(), i++, LOCATION)); + this.makeControlPoint(cpPosition, this.getLocationControlPointAttributes(), i++, LOCATION)); } // Create a control point for the rotation control. @@ -2889,12 +2680,9 @@ else if (this.getShape() instanceof SurfacePolyline) controlPoints.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), i, ROTATION)); this.getControlPointLayer().setMarkers(controlPoints); - } - else - { + } else { Iterator markerIterator = markers.iterator(); - for (LatLon cpPosition : locations) - { + for (LatLon cpPosition : locations) { markerIterator.next().setPosition(new Position(cpPosition, 0)); } @@ -2904,53 +2692,48 @@ else if (this.getShape() instanceof SurfacePolyline) // Update the heading annotation. Iterator markerIterator = this.getControlPointLayer().getMarkers().iterator(); - for (LatLon ignored : locations) - { + for (LatLon ignored : locations) { markerIterator.next(); } ((ControlPointMarker) markerIterator.next()).rotation = heading; // Update the rotation orientation line. this.updateOrientationLine(new Position(polygonCenter, 0), - new Position(rotationControlLocation, 0)); + new Position(rotationControlLocation, 0)); } - protected void reshapeSurfaceCircle(Position terrainPosition, ControlPointMarker controlPoint) - { - if (controlPoint == null) + protected void reshapeSurfaceCircle(Position terrainPosition, ControlPointMarker controlPoint) { + if (controlPoint == null) { return; // Cannot add locations to this shape. - + } SurfaceCircle circle = (SurfaceCircle) this.getShape(); Vec4 delta = this.computeControlPointDelta(this.getPreviousPosition(), terrainPosition); Vec4 centerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(circle.getCenter()); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - controlPoint.getPosition()); + controlPoint.getPosition()); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); double radius = circle.getRadius() + delta.dot3(vMarker); - if (radius > 0) + if (radius > 0) { circle.setRadius(radius); + } } - protected void updateSurfaceCircleControlPoints() - { + protected void updateSurfaceCircleControlPoints() { SurfaceCircle circle = (SurfaceCircle) this.getShape(); LatLon radiusLocation = LatLon.greatCircleEndPosition(circle.getCenter(), Angle.fromDegrees(90), - Angle.fromRadians(circle.getRadius() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromRadians(circle.getRadius() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(1); Position cpPosition = new Position(radiusLocation, 0); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, OUTER_RADIUS)); this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { markers.iterator().next().setPosition(new Position(radiusLocation, 0)); } @@ -2958,30 +2741,28 @@ protected void updateSurfaceCircleControlPoints() ((ControlPointMarker) markerIterator.next()).size = circle.getRadius(); } - protected void reshapeSurfaceSquare(Position terrainPosition, ControlPointMarker controlPoint) - { - if (controlPoint == null) + protected void reshapeSurfaceSquare(Position terrainPosition, ControlPointMarker controlPoint) { + if (controlPoint == null) { return; // Cannot add locations to this shape. - + } SurfaceSquare square = (SurfaceSquare) this.getShape(); Vec4 terrainPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(terrainPosition); Vec4 previousPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - this.getPreviousPosition()); + this.getPreviousPosition()); Vec4 delta = terrainPoint.subtract3(previousPoint); Vec4 centerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(square.getCenter()); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - controlPoint.getPosition()); + controlPoint.getPosition()); Vec4 vMarker = markerPoint.subtract3(centerPoint); - if (controlPoint.getPurpose().equals(RIGHT_WIDTH)) - { + if (controlPoint.getPurpose().equals(RIGHT_WIDTH)) { double size = square.getSize() + delta.dot3(vMarker.normalize3()); - if (size > 0) + if (size > 0) { square.setSize(size); - } - else // rotation + } + } else // rotation { Angle oldHeading = LatLon.greatCircleAzimuth(square.getCenter(), this.getPreviousPosition()); Angle deltaHeading = LatLon.greatCircleAzimuth(square.getCenter(), terrainPosition).subtract(oldHeading); @@ -2989,21 +2770,19 @@ protected void reshapeSurfaceSquare(Position terrainPosition, ControlPointMarker } } - protected void updateSurfaceSquareControlPoints() - { + protected void updateSurfaceSquareControlPoints() { SurfaceSquare square = (SurfaceSquare) this.getShape(); LatLon sizeLocation = LatLon.greatCircleEndPosition(square.getCenter(), - Angle.fromDegrees(90 + square.getHeading().degrees), - Angle.fromRadians(0.5 * square.getSize() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(90 + square.getHeading().degrees), + Angle.fromRadians(0.5 * square.getSize() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon rotationLocation = LatLon.greatCircleEndPosition(square.getCenter(), - Angle.fromDegrees(square.getHeading().degrees), - Angle.fromRadians(0.7 * square.getSize() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(square.getHeading().degrees), + Angle.fromRadians(0.7 * square.getSize() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(1); Position cpPosition = new Position(sizeLocation, 0); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, RIGHT_WIDTH)); @@ -3012,9 +2791,7 @@ protected void updateSurfaceSquareControlPoints() markerList.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 1, ROTATION)); this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { Iterator markerIterator = markers.iterator(); markerIterator.next().setPosition(new Position(sizeLocation, 0)); markerIterator.next().setPosition(new Position(rotationLocation, 0)); @@ -3027,57 +2804,52 @@ protected void updateSurfaceSquareControlPoints() this.updateOrientationLine(new Position(square.getCenter(), 0), new Position(rotationLocation, 0)); } - protected void reshapeSurfaceQuad(Position terrainPosition, ControlPointMarker controlPoint) - { - if (controlPoint == null) + protected void reshapeSurfaceQuad(Position terrainPosition, ControlPointMarker controlPoint) { + if (controlPoint == null) { return; // Cannot add locations to this shape. - + } SurfaceQuad quad = (SurfaceQuad) this.getShape(); Vec4 terrainPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(terrainPosition); Vec4 previousPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - this.getPreviousPosition()); + this.getPreviousPosition()); Vec4 delta = terrainPoint.subtract3(previousPoint); Vec4 centerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(quad.getCenter()); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - controlPoint.getPosition()); + controlPoint.getPosition()); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); - if (controlPoint.getPurpose().equals(WIDTH) || controlPoint.getPurpose().equals(HEIGHT)) - { + if (controlPoint.getPurpose().equals(WIDTH) || controlPoint.getPurpose().equals(HEIGHT)) { double width = quad.getWidth() + (controlPoint.getId() == 0 ? delta.dot3(vMarker) : 0); double height = quad.getHeight() + (controlPoint.getId() == 1 ? delta.dot3(vMarker) : 0); - if (width > 0 && height > 0) + if (width > 0 && height > 0) { quad.setSize(width, height); - } - else - { + } + } else { Angle oldHeading = LatLon.greatCircleAzimuth(quad.getCenter(), this.getPreviousPosition()); Angle deltaHeading = LatLon.greatCircleAzimuth(quad.getCenter(), terrainPosition).subtract(oldHeading); quad.setHeading(this.normalizedHeading(quad.getHeading(), deltaHeading)); } } - protected void updateSurfaceQuadControlPoints() - { + protected void updateSurfaceQuadControlPoints() { SurfaceQuad quad = (SurfaceQuad) this.getShape(); LatLon widthLocation = LatLon.greatCircleEndPosition(quad.getCenter(), - Angle.fromDegrees(90 + quad.getHeading().degrees), - Angle.fromRadians(0.5 * quad.getWidth() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(90 + quad.getHeading().degrees), + Angle.fromRadians(0.5 * quad.getWidth() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon heightLocation = LatLon.greatCircleEndPosition(quad.getCenter(), - Angle.fromDegrees(quad.getHeading().degrees), - Angle.fromRadians(0.5 * quad.getHeight() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(quad.getHeading().degrees), + Angle.fromRadians(0.5 * quad.getHeight() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon rotationLocation = LatLon.greatCircleEndPosition(quad.getCenter(), - Angle.fromDegrees(quad.getHeading().degrees), - Angle.fromRadians(0.7 * quad.getHeight() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(quad.getHeading().degrees), + Angle.fromRadians(0.7 * quad.getHeight() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(2); Position cpPosition = new Position(widthLocation, 0); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, WIDTH)); @@ -3088,9 +2860,7 @@ protected void updateSurfaceQuadControlPoints() markerList.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 2, ROTATION)); this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { Iterator markerIterator = markers.iterator(); markerIterator.next().setPosition(new Position(widthLocation, 0)); markerIterator.next().setPosition(new Position(heightLocation, 0)); @@ -3105,32 +2875,29 @@ protected void updateSurfaceQuadControlPoints() this.updateOrientationLine(new Position(quad.getCenter(), 0), new Position(rotationLocation, 0)); } - protected void reshapeSurfaceEllipse(Position terrainPosition, ControlPointMarker controlPoint) - { - if (controlPoint == null) + protected void reshapeSurfaceEllipse(Position terrainPosition, ControlPointMarker controlPoint) { + if (controlPoint == null) { return; // Cannot add locations to this shape. - + } SurfaceEllipse ellipse = (SurfaceEllipse) this.getShape(); Vec4 terrainPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(terrainPosition); Vec4 previousPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - this.getPreviousPosition()); + this.getPreviousPosition()); Vec4 delta = terrainPoint.subtract3(previousPoint); Vec4 centerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation(ellipse.getCenter()); Vec4 markerPoint = this.getWwd().getModel().getGlobe().computeEllipsoidalPointFromLocation( - controlPoint.getPosition()); + controlPoint.getPosition()); Vec4 vMarker = markerPoint.subtract3(centerPoint).normalize3(); - if (controlPoint.getPurpose().equals(WIDTH) || controlPoint.getPurpose().equals(HEIGHT)) - { + if (controlPoint.getPurpose().equals(WIDTH) || controlPoint.getPurpose().equals(HEIGHT)) { double majorRadius = ellipse.getMajorRadius() + (controlPoint.getId() == 0 ? delta.dot3(vMarker) : 0); double minorRadius = ellipse.getMinorRadius() + (controlPoint.getId() == 1 ? delta.dot3(vMarker) : 0); - if (majorRadius > 0 && minorRadius > 0) + if (majorRadius > 0 && minorRadius > 0) { ellipse.setRadii(majorRadius, minorRadius); - } - else - { + } + } else { Angle oldHeading = LatLon.greatCircleAzimuth(ellipse.getCenter(), this.getPreviousPosition()); Angle deltaHeading = LatLon.greatCircleAzimuth(ellipse.getCenter(), terrainPosition).subtract(oldHeading); ellipse.setHeading(this.normalizedHeading(ellipse.getHeading(), deltaHeading)); @@ -3139,26 +2906,24 @@ protected void reshapeSurfaceEllipse(Position terrainPosition, ControlPointMarke this.updateAnnotation(controlPoint); } - protected void updateSurfaceEllipseControlPoints() - { + protected void updateSurfaceEllipseControlPoints() { SurfaceEllipse ellipse = (SurfaceEllipse) this.getShape(); LatLon majorLocation = LatLon.greatCircleEndPosition(ellipse.getCenter(), - Angle.fromDegrees(90 + ellipse.getHeading().degrees), - Angle.fromRadians(ellipse.getMajorRadius() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(90 + ellipse.getHeading().degrees), + Angle.fromRadians(ellipse.getMajorRadius() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon minorLocation = LatLon.greatCircleEndPosition(ellipse.getCenter(), - Angle.fromDegrees(ellipse.getHeading().degrees), - Angle.fromRadians(ellipse.getMinorRadius() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(ellipse.getHeading().degrees), + Angle.fromRadians(ellipse.getMinorRadius() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); LatLon rotationLocation = LatLon.greatCircleEndPosition(ellipse.getCenter(), - Angle.fromDegrees(ellipse.getHeading().degrees), - Angle.fromRadians( - 1.15 * ellipse.getMinorRadius() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); + Angle.fromDegrees(ellipse.getHeading().degrees), + Angle.fromRadians( + 1.15 * ellipse.getMinorRadius() / this.getWwd().getModel().getGlobe().getEquatorialRadius())); Iterable markers = this.getControlPointLayer().getMarkers(); - if (markers == null) - { + if (markers == null) { java.util.List markerList = new ArrayList(2); Position cpPosition = new Position(majorLocation, 0); markerList.add(this.makeControlPoint(cpPosition, this.getSizeControlPointAttributes(), 0, WIDTH)); @@ -3170,9 +2935,7 @@ protected void updateSurfaceEllipseControlPoints() markerList.add(this.makeControlPoint(cpPosition, this.getAngleControlPointAttributes(), 2, ROTATION)); this.getControlPointLayer().setMarkers(markerList); - } - else - { + } else { Iterator markerIterator = markers.iterator(); markerIterator.next().setPosition(new Position(majorLocation, 0)); markerIterator.next().setPosition(new Position(minorLocation, 0)); diff --git a/src/gov/nasa/worldwind/util/StatisticsPanel.java b/src/gov/nasa/worldwind/util/StatisticsPanel.java index 9af3e15002..7a59791112 100644 --- a/src/gov/nasa/worldwind/util/StatisticsPanel.java +++ b/src/gov/nasa/worldwind/util/StatisticsPanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.WorldWindow; @@ -17,8 +16,8 @@ /** * @version $Id: StatisticsPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class StatisticsPanel extends JPanel -{ +public class StatisticsPanel extends JPanel { + private JPanel statsPanel; private JPanel outerPanel; private JScrollPane scrollPane; @@ -26,15 +25,13 @@ public class StatisticsPanel extends JPanel private int updateInterval = 500; private long lastUpdate; - public StatisticsPanel(WorldWindow wwd) - { + public StatisticsPanel(WorldWindow wwd) { // Make a panel at a default size. super(new BorderLayout()); this.makePanel(new Dimension(200, 400)); } - public StatisticsPanel(WorldWindow wwd, Dimension size) - { + public StatisticsPanel(WorldWindow wwd, Dimension size) { // Make a panel at a specified size. super(new BorderLayout()); @@ -42,18 +39,13 @@ public StatisticsPanel(WorldWindow wwd, Dimension size) this.makePanel(size); wwd.setPerFrameStatisticsKeys(PerformanceStatistic.ALL_STATISTICS_SET); - wwd.addRenderingListener(new RenderingListener() - { - public void stageChanged(RenderingEvent event) - { + wwd.addRenderingListener(new RenderingListener() { + public void stageChanged(RenderingEvent event) { long now = System.currentTimeMillis(); if (event.getStage().equals(RenderingEvent.AFTER_BUFFER_SWAP) - && event.getSource() instanceof WorldWindow && now - lastUpdate > updateInterval) - { - EventQueue.invokeLater(new Runnable() - { - public void run() - { + && event.getSource() instanceof WorldWindow && now - lastUpdate > updateInterval) { + EventQueue.invokeLater(new Runnable() { + public void run() { update(); } }); @@ -63,8 +55,7 @@ public void run() }); } - private void makePanel(Dimension size) - { + private void makePanel(Dimension size) { // Make and fill the panel holding the statistics. this.statsPanel = new JPanel(new GridLayout(0, 1, 0, 15)); this.statsPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); @@ -76,35 +67,34 @@ private void makePanel(Dimension size) // Put the name panel in a scroll bar. this.scrollPane = new JScrollPane(dummyPanel); this.scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); - if (size != null) + if (size != null) { this.scrollPane.setPreferredSize(size); + } // Add the scroll bar and stats panel to a titled panel that will resize with the main window. outerPanel = new JPanel(new GridLayout(0, 1, 0, 10)); outerPanel - .setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Statistics"))); + .setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Statistics"))); outerPanel.setToolTipText("Runtime Statistics"); outerPanel.add(scrollPane); this.add(outerPanel, BorderLayout.CENTER); } - private void fill(WorldWindow wwd) - { - if (wwd.getSceneController().getPerFrameStatistics().size() < 1) + private void fill(WorldWindow wwd) { + if (wwd.getSceneController().getPerFrameStatistics().size() < 1) { return; + } PerformanceStatistic[] pfs = new PerformanceStatistic[wwd.getPerFrameStatistics().size()]; pfs = wwd.getSceneController().getPerFrameStatistics().toArray(pfs); Arrays.sort(pfs); - for (PerformanceStatistic stat : pfs) - { + for (PerformanceStatistic stat : pfs) { JLabel jcb = new JLabel(stat.toString()); this.statsPanel.add(jcb); } } - public void update(WorldWindow wwd) - { + public void update(WorldWindow wwd) { // Replace all the statistics in the panel with the current ones. this.statsPanel.removeAll(); this.fill(wwd); @@ -112,8 +102,7 @@ public void update(WorldWindow wwd) this.outerPanel.repaint(); } - public void update() - { + public void update() { // Replace all the statistics in the panel with the current ones. this.statsPanel.removeAll(); this.fill(this.wwd); @@ -122,8 +111,7 @@ public void update() } @Override - public void setToolTipText(String string) - { + public void setToolTipText(String string) { this.scrollPane.setToolTipText(string); } } diff --git a/src/gov/nasa/worldwind/util/StatusBar.java b/src/gov/nasa/worldwind/util/StatusBar.java index 8ff986f977..e41e3f6037 100644 --- a/src/gov/nasa/worldwind/util/StatusBar.java +++ b/src/gov/nasa/worldwind/util/StatusBar.java @@ -20,8 +20,8 @@ * @author tag * @version $Id: StatusBar.java 1945 2014-04-18 17:08:43Z tgaskins $ */ -public class StatusBar extends JPanel implements PositionListener, RenderingListener -{ +public class StatusBar extends JPanel implements PositionListener, RenderingListener { + // Units constants TODO: Replace with UnitsFormat public final static String UNIT_METRIC = "gov.nasa.worldwind.StatusBar.Metric"; public final static String UNIT_IMPERIAL = "gov.nasa.worldwind.StatusBar.Imperial"; @@ -41,8 +41,7 @@ public class StatusBar extends JPanel implements PositionListener, RenderingList protected AtomicBoolean isNetworkAvailable = new AtomicBoolean(true); protected Thread netCheckThread; - public StatusBar() - { + public StatusBar() { super(new GridLayout(1, 0)); final JLabel heartBeat = new JLabel(Logging.getMessage("term.Downloading")); @@ -61,19 +60,16 @@ public StatusBar() heartBeat.setHorizontalAlignment(SwingConstants.CENTER); heartBeat.setForeground(new java.awt.Color(255, 0, 0, 0)); - Timer downloadTimer = new Timer(100, new ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent actionEvent) - { - if (!showNetworkStatus.get()) - { - if (heartBeat.getText().length() > 0) + Timer downloadTimer = new Timer(100, new ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent actionEvent) { + if (!showNetworkStatus.get()) { + if (heartBeat.getText().length() > 0) { heartBeat.setText(""); + } return; } - if (!isNetworkAvailable.get()) - { + if (!isNetworkAvailable.get()) { heartBeat.setText(Logging.getMessage("term.NoNetwork")); heartBeat.setForeground(new Color(255, 0, 0, MAX_ALPHA)); return; @@ -81,16 +77,14 @@ public void actionPerformed(java.awt.event.ActionEvent actionEvent) Color color = heartBeat.getForeground(); int alpha = color.getAlpha(); - if (isNetworkAvailable.get() && WorldWind.getRetrievalService().hasActiveTasks()) - { + if (isNetworkAvailable.get() && WorldWind.getRetrievalService().hasActiveTasks()) { heartBeat.setText(Logging.getMessage("term.Downloading")); - if (alpha >= MAX_ALPHA) + if (alpha >= MAX_ALPHA) { alpha = MAX_ALPHA; - else + } else { alpha = alpha < 16 ? 16 : Math.min(MAX_ALPHA, alpha + 20); - } - else - { + } + } else { alpha = Math.max(0, alpha - 20); } heartBeat.setForeground(new Color(255, 0, 0, alpha)); @@ -101,32 +95,27 @@ public void actionPerformed(java.awt.event.ActionEvent actionEvent) this.netCheckThread = this.startNetCheckThread(); WorldWind.getNetworkStatus().addPropertyChangeListener(NetworkStatus.HOST_UNAVAILABLE, - new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent evt) - { - Object nv = evt.getNewValue(); - String message = Logging.getMessage("NetworkStatus.UnavailableHost", + new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent evt) { + Object nv = evt.getNewValue(); + String message = Logging.getMessage("NetworkStatus.UnavailableHost", nv != null && nv instanceof URL ? ((URL) nv).getHost() : "Unknown"); - Logging.logger().info(message); - } - }); + Logging.logger().info(message); + } + }); WorldWind.getNetworkStatus().addPropertyChangeListener(NetworkStatus.HOST_AVAILABLE, - new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent evt) - { - Object nv = evt.getNewValue(); - String message = Logging.getMessage("NetworkStatus.HostNowAvailable", + new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent evt) { + Object nv = evt.getNewValue(); + String message = Logging.getMessage("NetworkStatus.HostNowAvailable", nv != null && nv instanceof URL ? ((URL) nv).getHost() : "Unknown"); - Logging.logger().info(message); - } - }); + Logging.logger().info(message); + } + }); } - protected NetworkCheckThread startNetCheckThread() - { + protected NetworkCheckThread startNetCheckThread() { NetworkCheckThread nct = new NetworkCheckThread(this.showNetworkStatus, this.isNetworkAvailable, null); nct.setDaemon(true); nct.start(); @@ -134,16 +123,13 @@ protected NetworkCheckThread startNetCheckThread() return nct; } - public void setEventSource(WorldWindow newEventSource) - { - if (this.eventSource != null) - { + public void setEventSource(WorldWindow newEventSource) { + if (this.eventSource != null) { this.eventSource.removePositionListener(this); this.eventSource.removeRenderingListener(this); } - if (newEventSource != null) - { + if (newEventSource != null) { newEventSource.addPositionListener(this); newEventSource.addRenderingListener(this); } @@ -151,50 +137,42 @@ public void setEventSource(WorldWindow newEventSource) this.eventSource = newEventSource; } - public boolean isShowNetworkStatus() - { + public boolean isShowNetworkStatus() { return showNetworkStatus.get(); } - public void setShowNetworkStatus(boolean showNetworkStatus) - { + public void setShowNetworkStatus(boolean showNetworkStatus) { this.showNetworkStatus.set(showNetworkStatus); - if (showNetworkStatus) - { - if (this.netCheckThread != null) + if (showNetworkStatus) { + if (this.netCheckThread != null) { this.netCheckThread.interrupt(); + } this.netCheckThread = this.startNetCheckThread(); - } - else - { - if (this.netCheckThread != null) + } else { + if (this.netCheckThread != null) { this.netCheckThread.interrupt(); + } this.netCheckThread = null; } } - public void moved(PositionEvent event) - { + public void moved(PositionEvent event) { this.handleCursorPositionChange(event); } - public WorldWindow getEventSource() - { + public WorldWindow getEventSource() { return this.eventSource; } - public String getElevationUnit() - { + public String getElevationUnit() { return this.elevationUnit; } - public void setElevationUnit(String unit) - { - if (unit == null) - { + public void setElevationUnit(String unit) { + if (unit == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -203,15 +181,12 @@ public void setElevationUnit(String unit) this.elevationUnit = unit; } - public String getAngleFormat() - { + public String getAngleFormat() { return this.angleFormat; } - public void setAngleFormat(String format) - { - if (format == null) - { + public void setAngleFormat(String format) { + if (format == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -220,81 +195,77 @@ public void setAngleFormat(String format) this.angleFormat = format; } - protected String makeCursorElevationDescription(double metersElevation) - { + protected String makeCursorElevationDescription(double metersElevation) { String s; String elev = Logging.getMessage("term.Elev"); - if (UNIT_IMPERIAL.equals(elevationUnit)) + if (UNIT_IMPERIAL.equals(elevationUnit)) { s = String.format(elev + " %,7d feet", (int) (WWMath.convertMetersToFeet(metersElevation))); - else // Default to metric units. + } else // Default to metric units. + { s = String.format(elev + " %,7d meters", (int) metersElevation); + } return s; } - protected String makeEyeAltitudeDescription(double metersAltitude) - { + protected String makeEyeAltitudeDescription(double metersAltitude) { String s; String altitude = Logging.getMessage("term.Altitude"); - if (UNIT_IMPERIAL.equals(elevationUnit)) - { + if (UNIT_IMPERIAL.equals(elevationUnit)) { double miles = WWMath.convertMetersToMiles(metersAltitude); - if (Math.abs(miles) >= 1) + if (Math.abs(miles) >= 1) { s = String.format(altitude + " %,7d mi", (int) Math.round(miles)); - else + } else { s = String.format(altitude + " %,7d ft", (int) Math.round(WWMath.convertMetersToFeet(metersAltitude))); - } - else if (Math.abs(metersAltitude) >= 1000) // Default to metric units. + } + } else if (Math.abs(metersAltitude) >= 1000) // Default to metric units. + { s = String.format(altitude + " %,7d km", (int) Math.round(metersAltitude / 1e3)); - else + } else { s = String.format(altitude + " %,7d m", (int) Math.round(metersAltitude)); + } return s; } - protected String makeAngleDescription(String label, Angle angle) - { + protected String makeAngleDescription(String label, Angle angle) { String s; - if (Angle.ANGLE_FORMAT_DMS.equals(angleFormat)) + if (Angle.ANGLE_FORMAT_DMS.equals(angleFormat)) { s = String.format("%s %s", label, angle.toDMSString()); - else + } else { s = String.format("%s %7.4f\u00B0", label, angle.degrees); + } return s; } - protected void handleCursorPositionChange(PositionEvent event) - { + protected void handleCursorPositionChange(PositionEvent event) { Position newPos = event.getPosition(); - if (newPos != null) - { + if (newPos != null) { String las = makeAngleDescription("Lat", newPos.getLatitude()); String los = makeAngleDescription("Lon", newPos.getLongitude()); String els = makeCursorElevationDescription( - eventSource.getModel().getGlobe().getElevation(newPos.getLatitude(), newPos.getLongitude())); + eventSource.getModel().getGlobe().getElevation(newPos.getLatitude(), newPos.getLongitude())); latDisplay.setText(las); lonDisplay.setText(los); eleDisplay.setText(els); - } - else - { + } else { latDisplay.setText(""); lonDisplay.setText(Logging.getMessage("term.OffGlobe")); eleDisplay.setText(""); } } - public void stageChanged(RenderingEvent event) - { - if (!event.getStage().equals(RenderingEvent.BEFORE_BUFFER_SWAP)) + public void stageChanged(RenderingEvent event) { + if (!event.getStage().equals(RenderingEvent.BEFORE_BUFFER_SWAP)) { return; + } - EventQueue.invokeLater(new Runnable() - { - public void run() - { - if (eventSource.getView() != null && eventSource.getView().getEyePosition() != null) + EventQueue.invokeLater(new Runnable() { + public void run() { + if (eventSource.getView() != null && eventSource.getView().getEyePosition() != null) { altDisplay.setText(makeEyeAltitudeDescription( - eventSource.getView().getEyePosition().getElevation())); - else + eventSource.getView().getEyePosition().getElevation())); + } else { altDisplay.setText(Logging.getMessage("term.Altitude")); + } } }); } diff --git a/src/gov/nasa/worldwind/util/StatusBarMGRS.java b/src/gov/nasa/worldwind/util/StatusBarMGRS.java index 9168deee0d..e6f97dfae7 100644 --- a/src/gov/nasa/worldwind/util/StatusBarMGRS.java +++ b/src/gov/nasa/worldwind/util/StatusBarMGRS.java @@ -13,38 +13,30 @@ * @author Patrick Murris * @version $Id: StatusBarMGRS.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class StatusBarMGRS extends StatusBar -{ - public void moved(PositionEvent event) - { +public class StatusBarMGRS extends StatusBar { + + public void moved(PositionEvent event) { this.handleCursorPositionChange(event); } - protected void handleCursorPositionChange(PositionEvent event) - { + protected void handleCursorPositionChange(PositionEvent event) { Position newPos = event.getPosition(); - if (newPos != null) - { + if (newPos != null) { String las = String.format("%7.4f\u00B0 %7.4f\u00B0", newPos.getLatitude().getDegrees(), newPos.getLongitude().getDegrees()); String els = makeCursorElevationDescription( - getEventSource().getModel().getGlobe().getElevation(newPos.getLatitude(), newPos.getLongitude())); + getEventSource().getModel().getGlobe().getElevation(newPos.getLatitude(), newPos.getLongitude())); String los = ""; - try - { + try { MGRSCoord MGRS = MGRSCoord.fromLatLon(newPos.getLatitude(), newPos.getLongitude(), getEventSource().getModel().getGlobe()); los = MGRS.toString(); - } - catch (Exception e) - { + } catch (Exception e) { los = ""; } latDisplay.setText(las); lonDisplay.setText(los); eleDisplay.setText(els); - } - else - { + } else { latDisplay.setText(""); lonDisplay.setText("Off globe"); eleDisplay.setText(""); diff --git a/src/gov/nasa/worldwind/util/StatusBarUTM.java b/src/gov/nasa/worldwind/util/StatusBarUTM.java index 1d319e6d5a..3d029864b8 100644 --- a/src/gov/nasa/worldwind/util/StatusBarUTM.java +++ b/src/gov/nasa/worldwind/util/StatusBarUTM.java @@ -13,37 +13,29 @@ * @author Patrick Murris * @version $Id: StatusBarUTM.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class StatusBarUTM extends StatusBar -{ - public void moved(PositionEvent event) - { +public class StatusBarUTM extends StatusBar { + + public void moved(PositionEvent event) { this.handleCursorPositionChange(event); } - protected void handleCursorPositionChange(PositionEvent event) - { + protected void handleCursorPositionChange(PositionEvent event) { Position newPos = event.getPosition(); - if (newPos != null) - { + if (newPos != null) { String las = String.format("%7.4f\u00B0 %7.4f\u00B0", newPos.getLatitude().getDegrees(), newPos.getLongitude().getDegrees()); String els = makeCursorElevationDescription( - getEventSource().getModel().getGlobe().getElevation(newPos.getLatitude(), newPos.getLongitude())); + getEventSource().getModel().getGlobe().getElevation(newPos.getLatitude(), newPos.getLongitude())); String los = ""; - try - { + try { UTMCoord UTM = UTMCoord.fromLatLon(newPos.getLatitude(), newPos.getLongitude(), getEventSource().getModel().getGlobe()); los = UTM.toString(); - } - catch (Exception e) - { + } catch (Exception e) { los = ""; } latDisplay.setText(las); lonDisplay.setText(los); eleDisplay.setText(els); - } - else - { + } else { latDisplay.setText(""); lonDisplay.setText("Off globe"); eleDisplay.setText(""); diff --git a/src/gov/nasa/worldwind/util/SurfaceTileDrawContext.java b/src/gov/nasa/worldwind/util/SurfaceTileDrawContext.java index b8ea2d294f..55b74e6590 100644 --- a/src/gov/nasa/worldwind/util/SurfaceTileDrawContext.java +++ b/src/gov/nasa/worldwind/util/SurfaceTileDrawContext.java @@ -20,8 +20,8 @@ * @author dcollins * @version $Id: SurfaceTileDrawContext.java 2320 2014-09-17 19:29:24Z dcollins $ */ -public class SurfaceTileDrawContext -{ +public class SurfaceTileDrawContext { + protected Sector sector; protected Rectangle viewport; protected Matrix modelview; @@ -32,22 +32,19 @@ public class SurfaceTileDrawContext * this context's geographic extent and screen viewport. The pick candidate collection is used to register picked * objects drawn into the surface tile. * - * @param tile the context's tile. + * @param tile the context's tile. * @param pickCandidates the context's list of pick candidates. * * @throws IllegalArgumentException if any argument is null. */ - public SurfaceTileDrawContext(Tile tile, Collection pickCandidates) - { - if (tile == null) - { + public SurfaceTileDrawContext(Tile tile, Collection pickCandidates) { + if (tile == null) { String message = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pickCandidates == null) - { + if (pickCandidates == null) { String message = Logging.getMessage("nullValue.PickedObjectList"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -64,8 +61,7 @@ public SurfaceTileDrawContext(Tile tile, Collection pickCandidates * * @return this's sector. */ - public Sector getSector() - { + public Sector getSector() { return this.sector; } @@ -74,8 +70,7 @@ public Sector getSector() * * @return this context's viewport. */ - public Rectangle getViewport() - { + public Rectangle getViewport() { return this.viewport; } @@ -84,8 +79,7 @@ public Rectangle getViewport() * * @return Matrix mapping geographic coordinates to tile coordinates. */ - public Matrix getModelviewMatrix() - { + public Matrix getModelviewMatrix() { return this.modelview; } @@ -99,18 +93,16 @@ public Matrix getModelviewMatrix() * * @throws IllegalArgumentException if the reference location is null. */ - public Matrix getModelviewMatrix(LatLon referenceLocation) - { - if (referenceLocation == null) - { + public Matrix getModelviewMatrix(LatLon referenceLocation) { + if (referenceLocation == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return this.modelview.multiply( - Matrix.fromTranslation(referenceLocation.getLongitude().degrees, referenceLocation.getLatitude().degrees, - 0)); + Matrix.fromTranslation(referenceLocation.getLongitude().degrees, referenceLocation.getLatitude().degrees, + 0)); } /** @@ -119,8 +111,7 @@ public Matrix getModelviewMatrix(LatLon referenceLocation) * * @return this context's pick candidates. */ - public Collection getPickCandidates() - { + public Collection getPickCandidates() { return this.pickCandidates; } @@ -132,10 +123,8 @@ public Collection getPickCandidates() * * @throws IllegalArgumentException if the object is null. */ - public void addPickCandidate(PickedObject pickedObject) - { - if (null == pickedObject) - { + public void addPickCandidate(PickedObject pickedObject) { + if (null == pickedObject) { String msg = Logging.getMessage("nullValue.PickedObject"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); diff --git a/src/gov/nasa/worldwind/util/TaskService.java b/src/gov/nasa/worldwind/util/TaskService.java index a5386e00e8..a1836d3652 100644 --- a/src/gov/nasa/worldwind/util/TaskService.java +++ b/src/gov/nasa/worldwind/util/TaskService.java @@ -9,8 +9,8 @@ * @author tag * @version $Id: TaskService.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TaskService -{ +public interface TaskService { + void shutdown(boolean immediately); boolean contains(Runnable runnable); diff --git a/src/gov/nasa/worldwind/util/TextDecoder.java b/src/gov/nasa/worldwind/util/TextDecoder.java index d05904c670..e995572a8d 100644 --- a/src/gov/nasa/worldwind/util/TextDecoder.java +++ b/src/gov/nasa/worldwind/util/TextDecoder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; /** @@ -12,8 +11,8 @@ * @author pabercrombie * @version $Id: TextDecoder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TextDecoder -{ +public interface TextDecoder { + /** * Set the input text which the decoder will process. * @@ -38,7 +37,7 @@ public interface TextDecoder * determine if the decoded text has changed since {@link #getDecodedText()} was last called. * * @return The time (as returned by {@code System.currentTimeMillis()}) at which the decoded text last changed. - * Returns zero if called before the text is decoded. + * Returns zero if called before the text is decoded. */ long getLastUpdateTime(); } diff --git a/src/gov/nasa/worldwind/util/TextureAtlas.java b/src/gov/nasa/worldwind/util/TextureAtlas.java index 5ad4c00f23..8dea4350a3 100644 --- a/src/gov/nasa/worldwind/util/TextureAtlas.java +++ b/src/gov/nasa/worldwind/util/TextureAtlas.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import com.jogamp.opengl.util.packrect.*; @@ -28,21 +27,20 @@ * @author dcollins * @version $Id: TextureAtlas.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TextureAtlas -{ +public class TextureAtlas { + /** * Implementation of the JOGL BackingStoreManager interface for texture atlas. This is used by the JOGL {@link * RectanglePacker}, and delegates calls from a JOGL rectangle packer to methods in this texture atlas. */ - protected class AtlasBackingStore implements BackingStoreManager - { + protected class AtlasBackingStore implements BackingStoreManager { + /** * {@inheritDoc} *

          * Calls {@link TextureAtlas#createBackingImage(int, int)} with the specified width and height. */ - public Object allocateBackingStore(int w, int h) - { + public Object allocateBackingStore(int w, int h) { return createBackingImage(w, h); } @@ -51,8 +49,7 @@ public Object allocateBackingStore(int w, int h) *

          * Calls {@link TextureAtlas#disposeBackingImage()}. */ - public void deleteBackingStore(Object backingStore) - { + public void deleteBackingStore(Object backingStore) { disposeBackingImage(); } @@ -61,8 +58,7 @@ public void deleteBackingStore(Object backingStore) *

          * Returns true. The texture atlas can always attempt to expand or compact. */ - public boolean canCompact() - { + public boolean canCompact() { return true; } @@ -73,8 +69,7 @@ public boolean canCompact() * so, texture atlas evicts old elements in additionFailed if this texture atlas is full and the * addition would otherwise fail. */ - public boolean preExpand(Rect cause, int attemptNumber) - { + public boolean preExpand(Rect cause, int attemptNumber) { return false; } @@ -87,12 +82,12 @@ public boolean preExpand(Rect cause, int attemptNumber) * * @throws WWRuntimeException if this backing store cannot fit the rectangle in its layout. */ - public boolean additionFailed(Rect cause, int attemptNumber) - { - if (!isEvictOldElements() || !removeLeastRecentlyUsedEntry()) + public boolean additionFailed(Rect cause, int attemptNumber) { + if (!isEvictOldElements() || !removeLeastRecentlyUsedEntry()) { throw new WWRuntimeException(Logging.getMessage("TextureAtlas.AtlasIsFull")); - else + } else { return true; + } } /** @@ -101,8 +96,7 @@ public boolean additionFailed(Rect cause, int attemptNumber) * Calls {@link TextureAtlas#beginMoveEntries(java.awt.image.BufferedImage, java.awt.image.BufferedImage)}, * casting the specified backing stores to BufferedImages. */ - public void beginMovement(Object oldBackingStore, Object newBackingStore) - { + public void beginMovement(Object oldBackingStore, Object newBackingStore) { beginMoveEntries((BufferedImage) oldBackingStore, (BufferedImage) newBackingStore); } @@ -113,8 +107,7 @@ public void beginMovement(Object oldBackingStore, Object newBackingStore) * java.awt.image.BufferedImage, com.jogamp.opengl.util.packrect.Rect)}, casting the specified backing stores to * BufferedImages. */ - public void move(Object oldBackingStore, Rect oldLocation, Object newBackingStore, Rect newLocation) - { + public void move(Object oldBackingStore, Rect oldLocation, Object newBackingStore, Rect newLocation) { moveEntry((BufferedImage) oldBackingStore, oldLocation, (BufferedImage) newBackingStore, newLocation); } @@ -124,8 +117,7 @@ public void move(Object oldBackingStore, Rect oldLocation, Object newBackingStor * Calls {@link TextureAtlas#endMoveEntries(java.awt.image.BufferedImage, java.awt.image.BufferedImage)}, * casting the specified backing stores to BufferedImages. */ - public void endMovement(Object oldBackingStore, Object newBackingStore) - { + public void endMovement(Object oldBackingStore, Object newBackingStore) { endMoveEntries((BufferedImage) oldBackingStore, (BufferedImage) newBackingStore); } } @@ -136,15 +128,23 @@ public void endMovement(Object oldBackingStore, Object newBackingStore) * timestamp indicating the last time the element was used. Implements the {@link Comparable} interface by comparing * the lastUsed timestamp, ordered from least recently used to most recently used. */ - protected static class Entry implements Comparable - { - /** Indicates the element's key. Initialized during construction. */ + protected static class Entry implements Comparable { + + /** + * Indicates the element's key. Initialized during construction. + */ public final Object key; - /** Indicates the element's bounding rectangle within the texture atlas. Initialized during construction. */ + /** + * Indicates the element's bounding rectangle within the texture atlas. Initialized during construction. + */ public Rect rect; - /** Indicates the element's image X offset withing the bounding rectangle. Initialized during construction. */ + /** + * Indicates the element's image X offset withing the bounding rectangle. Initialized during construction. + */ public int imageOffsetX; - /** Indicates the element's image Y offset withing the bounding rectangle. Initialized during construction. */ + /** + * Indicates the element's image Y offset withing the bounding rectangle. Initialized during construction. + */ public int imageOffsetY; /** * Indicates the element's image width. May be smaller than the bounding rectangle's width. Initialized during @@ -156,22 +156,23 @@ protected static class Entry implements Comparable * construction. */ public int imageHeight; - /** Indicates the last time this entry was used. */ + /** + * Indicates the last time this entry was used. + */ public long lastUsed; /** * Constructs a texture atlas entry corresponding with a texture atlas element with the specified key, bounding * rectangle, and image offsets within the bounding rectangle. * - * @param key the element's key. - * @param rect the element's bounding rectangle within the texture atlas. + * @param key the element's key. + * @param rect the element's bounding rectangle within the texture atlas. * @param imageOffsetX the element's image X offset withing the bounding rectangle. * @param imageOffsetY the element's image Y offset withing the bounding rectangle. - * @param imageWidth the element's image width. May be smaller than the bounding rectangle's width. - * @param imageHeight the element's image height. May be smaller than the bounding rectangle's height. + * @param imageWidth the element's image width. May be smaller than the bounding rectangle's width. + * @param imageHeight the element's image height. May be smaller than the bounding rectangle's height. */ - public Entry(Object key, Rect rect, int imageOffsetX, int imageOffsetY, int imageWidth, int imageHeight) - { + public Entry(Object key, Rect rect, int imageOffsetX, int imageOffsetY, int imageWidth, int imageHeight) { this.key = key; this.rect = rect; this.imageOffsetX = imageOffsetX; @@ -188,14 +189,12 @@ public Entry(Object key, Rect rect, int imageOffsetX, int imageOffsetY, int imag * @param that the texture atlas entry this entry is compared to. * * @return -1, 0, or 1 if this entry's last used time is earlier than, the same as, or later than the specified - * entry's last used time. + * entry's last used time. * * @throws IllegalArgumentException if the specified entry is null. */ - public int compareTo(Entry that) - { - if (that == null) - { + public int compareTo(Entry that) { + if (that == null) { String msg = Logging.getMessage("nullValue.EntryIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -205,11 +204,17 @@ public int compareTo(Entry that) } } - /** The texture atlas' default setting for the useMipMaps property: true. */ + /** + * The texture atlas' default setting for the useMipMaps property: true. + */ protected static final boolean DEFAULT_USE_MIP_MAPS = true; - /** The texture atlas' default setting for the useAnisotropy property: true. */ + /** + * The texture atlas' default setting for the useAnisotropy property: true. + */ protected static final boolean DEFAULT_USE_ANISOTROPY = true; - /** The texture atlas' default maximum vertical fragmentation: 0.7. */ + /** + * The texture atlas' default maximum vertical fragmentation: 0.7. + */ protected static final double DEFAULT_MAX_VERTICAL_FRAGMENTATION = 0.7; /** @@ -272,8 +277,7 @@ public int compareTo(Entry that) protected Graphics2D g; /** * Indicates the current key corresponding to this texture atlas' OpenGL texture in the GPU resource cache. This key - * is assigned to a new instance whenever this texture atlas creates new backing image. Initialized to a new - * Object. + * is assigned to a new instance whenever this texture atlas creates new backing image. Initialized to a new Object. */ protected Object textureKey = new Object(); /** @@ -289,18 +293,15 @@ public int compareTo(Entry that) * zero, and the maximum dimensions must be greater than or equal to the initial dimensions. The constructed texture * atlas generates mip-maps and applies an anisotropic filter to each element. * - * @param initialWidth the texture atlas' initial width, in pixels. Must be greater than zero. + * @param initialWidth the texture atlas' initial width, in pixels. Must be greater than zero. * @param initialHeight the texture atlas' initial height, in pixels. Must be greater than zero. - * @param maxWidth the texture atlas' maximum width, in pixels. Must be greater than or equal to initialWidth. - * @param maxHeight the texture atlas' maximum height, in pixels. Must be greater than or equal to - * initialHeight. + * @param maxWidth the texture atlas' maximum width, in pixels. Must be greater than or equal to initialWidth. + * @param maxHeight the texture atlas' maximum height, in pixels. Must be greater than or equal to initialHeight. * * @throws IllegalArgumentException if any of initialWidth, initialHeight, maxWidth, or maxHeight are less than or - * equal to zero, if maxWidth is less than initialWidth, or if maxHeight is less - * than initialHeight. + * equal to zero, if maxWidth is less than initialWidth, or if maxHeight is less than initialHeight. */ - public TextureAtlas(int initialWidth, int initialHeight, int maxWidth, int maxHeight) - { + public TextureAtlas(int initialWidth, int initialHeight, int maxWidth, int maxHeight) { this(initialWidth, initialHeight, maxWidth, maxHeight, DEFAULT_USE_MIP_MAPS, DEFAULT_USE_ANISOTROPY); } @@ -310,47 +311,39 @@ public TextureAtlas(int initialWidth, int initialHeight, int maxWidth, int maxHe * enables specification of whether the texture atlas generates mip-maps and applies an anisotropic filter to each * element. * - * @param initialWidth the texture atlas' initial width, in pixels. Must be greater than zero. + * @param initialWidth the texture atlas' initial width, in pixels. Must be greater than zero. * @param initialHeight the texture atlas' initial height, in pixels. Must be greater than zero. - * @param maxWidth the texture atlas' maximum width, in pixels. Must be greater than or equal to initialWidth. - * @param maxHeight the texture atlas' maximum height, in pixels. Must be greater than or equal to - * initialHeight. - * @param useMipMaps whether to generate mip-maps for each atlas element. true to generate mip-maps, - * and false otherwise. + * @param maxWidth the texture atlas' maximum width, in pixels. Must be greater than or equal to initialWidth. + * @param maxHeight the texture atlas' maximum height, in pixels. Must be greater than or equal to initialHeight. + * @param useMipMaps whether to generate mip-maps for each atlas element. true to generate mip-maps, + * and false otherwise. * @param useAnisotropy whether to apply an anisotropic filter to each atlas element. true to apply an - * anisotropic filter, and false otherwise. This has no effect if useMipMaps is - * false. + * anisotropic filter, and false otherwise. This has no effect if useMipMaps is false. * * @throws IllegalArgumentException if any of initialWidth, initialHeight, maxWidth, or maxHeight are less than or - * equal to zero, if maxWidth is less than initialWidth, or if maxHeight is less - * than initialHeight. + * equal to zero, if maxWidth is less than initialWidth, or if maxHeight is less than initialHeight. */ public TextureAtlas(int initialWidth, int initialHeight, int maxWidth, int maxHeight, boolean useMipMaps, - boolean useAnisotropy) - { - if (initialWidth < 1) - { + boolean useAnisotropy) { + if (initialWidth < 1) { String msg = Logging.getMessage("TextureAtlas.InitialWidthInvalid", initialWidth); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (initialHeight < 1) - { + if (initialHeight < 1) { String msg = Logging.getMessage("TextureAtlas.InitialHeightInvalid", initialHeight); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (maxWidth < initialWidth) - { + if (maxWidth < initialWidth) { String msg = Logging.getMessage("TextureAtlas.MaxWidthInvalid", maxWidth); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (maxHeight < initialHeight) - { + if (maxHeight < initialHeight) { String msg = Logging.getMessage("TextureAtlas.MaxWidthInvalid", maxHeight); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -372,13 +365,12 @@ public TextureAtlas(int initialWidth, int initialHeight, int maxWidth, int maxHe * within this texture atlas' backing image. By default, this returns a rectangle packer with an {@link * AtlasBackingStore} as the backing store manager. Called during construction. * - * @param initialWidth this texture atlas' initial width. + * @param initialWidth this texture atlas' initial width. * @param initialHeight this texture atlas' initial height. * * @return a new JOGL rectangle packer with the specified initial dimensions. */ - protected RectanglePacker createRectanglePacker(int initialWidth, int initialHeight) - { + protected RectanglePacker createRectanglePacker(int initialWidth, int initialHeight) { return new RectanglePacker(new AtlasBackingStore(), initialWidth, initialHeight); } @@ -387,8 +379,7 @@ protected RectanglePacker createRectanglePacker(int initialWidth, int initialHei * * @return this texture atlas' current width. */ - public int getWidth() - { + public int getWidth() { return ((BufferedImage) this.rectPacker.getBackingStore()).getWidth(); } @@ -397,8 +388,7 @@ public int getWidth() * * @return this texture atlas' current height. */ - public int getHeight() - { + public int getHeight() { return ((BufferedImage) this.rectPacker.getBackingStore()).getHeight(); } @@ -407,8 +397,7 @@ public int getHeight() * * @return this texture atlas' maximum width. */ - public int getMaxWidth() - { + public int getMaxWidth() { return this.maxWidth; } @@ -417,8 +406,7 @@ public int getMaxWidth() * * @return this texture atlas' maximum height. */ - public int getMaxHeight() - { + public int getMaxHeight() { return this.maxHeight; } @@ -427,8 +415,7 @@ public int getMaxHeight() * * @return true if this texture atlas generates mip-maps, and false otherwise. */ - public boolean isUseMipMaps() - { + public boolean isUseMipMaps() { return this.useMipMaps; } @@ -438,8 +425,7 @@ public boolean isUseMipMaps() * * @return true if this texture atlas applies an anisotropic filter, and false otherwise. */ - public boolean isUseAnisotropy() - { + public boolean isUseAnisotropy() { return this.useAnisotropy; } @@ -448,12 +434,11 @@ public boolean isUseAnisotropy() * atlas is full. * * @return true if this atlas evicts old elements to make room for new elements, and false - * otherwise. + * otherwise. * * @see #setEvictOldElements(boolean) */ - public boolean isEvictOldElements() - { + public boolean isEvictOldElements() { return this.evictOldElements; } @@ -464,10 +449,9 @@ public boolean isEvictOldElements() * oldest elements are evicted until there is enough space to fit the element in the layout. * * @param evictOldElements true if this atlas should evict old elements to make room for new elements, - * and false otherwise. + * and false otherwise. */ - public void setEvictOldElements(boolean evictOldElements) - { + public void setEvictOldElements(boolean evictOldElements) { this.evictOldElements = evictOldElements; } @@ -476,8 +460,7 @@ public void setEvictOldElements(boolean evictOldElements) * * @return the number of elements in this texture atlas, or 0 if this atlas does not contain any elements. */ - public int getNumElements() - { + public int getNumElements() { return this.entryMap.size(); } @@ -486,8 +469,7 @@ public int getNumElements() * * @return true if this texture atlas contains at least one element, and false otherwise. */ - public boolean isEmpty() - { + public boolean isEmpty() { return this.entryMap.isEmpty(); } @@ -503,43 +485,36 @@ public boolean isEmpty() * requires space for an image with dimensions (width + 2, height + 2), where width and height are the image's * original dimensions. * - * @param key an object used to reference the image. + * @param key an object used to reference the image. * @param image the image to add. * * @throws IllegalArgumentException if either the key or image is null, or if the image dimensions are - * greater than this texture atlas' maximum dimensions. - * @throws WWRuntimeException if this texture atlas is too full to fit the image in its layout. + * greater than this texture atlas' maximum dimensions. + * @throws WWRuntimeException if this texture atlas is too full to fit the image in its layout. */ - public void add(Object key, BufferedImage image) - { - if (key == null) - { + public void add(Object key, BufferedImage image) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (image == null) - { + if (image == null) { String msg = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // Add two to account for the 1 pixel border we add to the image. - if (image.getWidth() + 2 > this.maxWidth || image.getHeight() + 2 > this.maxHeight) - { + if (image.getWidth() + 2 > this.maxWidth || image.getHeight() + 2 > this.maxHeight) { String msg = Logging.getMessage("TextureAtlas.ImageTooLarge", key); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - try - { + try { this.doAdd(key, image); - } - catch (Exception e) - { + } catch (Exception e) { // doAdd throws a WWRuntimeException when the rectangle packer cannot fit the specified image into the // backing store. String msg = Logging.getMessage("TextureAtlas.AtlasIsFull", key); @@ -551,18 +526,16 @@ public void add(Object key, BufferedImage image) /** * Adds a new element to this texture atlas with the specified key and image. * - * @param key an object used to reference the image. + * @param key an object used to reference the image. * @param image the image to add. * * @throws WWRuntimeException if this texture atlas is too full to fit the image in its layout. */ - protected void doAdd(Object key, BufferedImage image) - { + protected void doAdd(Object key, BufferedImage image) { // Remove any existing entry and add it to the list of unused entries before attempting to add one with the same // key. This ensures that the old entry is not orphaned in the rectangle packer's list of rectangles. Entry entry = this.entryMap.remove(key); - if (entry != null) - { + if (entry != null) { this.doRemove(entry); } @@ -602,22 +575,19 @@ protected void doAdd(Object key, BufferedImage image) * @param key an object used to reference the element to remove. * * @return true if this texture atlas contained an element with the specified key, and - * false otherwise. + * false otherwise. * * @throws IllegalArgumentException if the key is null. */ - public boolean remove(Object key) - { - if (key == null) - { + public boolean remove(Object key) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Entry entry = this.entryMap.remove(key); - if (entry != null) - { + if (entry != null) { this.doRemove(entry); } @@ -630,8 +600,7 @@ public boolean remove(Object key) * * @param entry the entry to remove. */ - protected void doRemove(Entry entry) - { + protected void doRemove(Entry entry) { Rect rect = entry.rect; // Remove the element's rectangle from the JOGL rectangle packer. This frees space for the @@ -645,8 +614,9 @@ protected void doRemove(Entry entry) // Compact the remaining entries if the vertical fragmentation ratio is larger than this texture atlas' // configured threshold. This avoids wasting texture space when many elements of different sizes are // subsequently added and removed. - if (this.rectPacker.verticalFragmentationRatio() > this.maxVerticalFragmentation) + if (this.rectPacker.verticalFragmentationRatio() > this.maxVerticalFragmentation) { this.rectPacker.compact(); + } } /** @@ -655,14 +625,12 @@ protected void doRemove(Entry entry) * @param key the key which the element is referenced by. * * @return true if this texture atlas contains an element with the specified key, and - * false otherwise. + * false otherwise. * * @throws IllegalArgumentException if the key is null. */ - public boolean contains(Object key) - { - if (key == null) - { + public boolean contains(Object key) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -678,20 +646,19 @@ public boolean contains(Object key) * @param key the key which the element is referenced by. * * @return the image dimensions corresponding to the specified element, or null if this texture atlas - * does not contain the element. + * does not contain the element. */ - public Dimension getSize(Object key) - { - if (key == null) - { + public Dimension getSize(Object key) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Entry entry = this.entryMap.get(key); - if (entry == null) + if (entry == null) { return null; + } // Mark that the entry has been used at the current time. this.markUsed(entry); @@ -709,20 +676,19 @@ public Dimension getSize(Object key) * @param key the key which the element is referenced by. * * @return the OpenGL texture coordinates corresponding to the specified element, or null if this - * texture atlas does not contain the element. + * texture atlas does not contain the element. */ - public TextureCoords getTexCoords(Object key) - { - if (key == null) - { + public TextureCoords getTexCoords(Object key) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Entry entry = this.entryMap.get(key); - if (entry == null) + if (entry == null) { return null; + } // Mark that the entry has been used at the current time. this.markUsed(entry); @@ -747,9 +713,10 @@ public TextureCoords getTexCoords(Object key) return new TextureCoords(tx1, ty2, tx2, ty1); } - /** Removes all elements from this texture atlas. The backing image retains its current dimensions after this call. */ - public void clear() - { + /** + * Removes all elements from this texture atlas. The backing image retains its current dimensions after this call. + */ + public void clear() { this.rectPacker.clear(); this.entryMap.clear(); @@ -770,10 +737,8 @@ public void clear() * * @throws IllegalArgumentException if the draw context is null. */ - public boolean bind(DrawContext dc) - { - if (dc == null) - { + public boolean bind(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -786,13 +751,10 @@ public boolean bind(DrawContext dc) // Synchronize the OpenGL texture with the backing image, creating OpenGL texture as necessary. Texture texture = this.syncTexture(dc); - if (texture != null) - { + if (texture != null) { texture.bind(dc.getGL()); return true; - } - else - { + } else { return false; } } @@ -803,13 +765,12 @@ public boolean bind(DrawContext dc) * always returns an image with power-of-two dimensions in order to maximize compatibility with different graphics * cards. * - * @param width the backing image's minimum width, in pixels. + * @param width the backing image's minimum width, in pixels. * @param height the backing image's minimum height, in pixels. * * @return a new BufferedImage to use as this texture atlas' backing image. */ - protected BufferedImage createBackingImage(int width, int height) - { + protected BufferedImage createBackingImage(int width, int height) { // Create an image with power-of-two dimensions in order to maximize compatibility with different graphics // cards. This eliminates the need for the individual images to have power-of-two dimensions. int potWidth = WWMath.powerOfTwoCeiling(width); @@ -824,9 +785,10 @@ protected BufferedImage createBackingImage(int width, int height) return bi; } - /** Disposes of this texture atlas' current backing image. */ - protected void disposeBackingImage() - { + /** + * Disposes of this texture atlas' current backing image. + */ + protected void disposeBackingImage() { // The rectangle packer is expanding or compacting the backing image, so we need to dispose of the current // backing image and its associated texture. We dispose of the texture by generating a new texture key and // adding the old key to the list of disposed texture keys. The current key may not be associated with any @@ -841,22 +803,18 @@ protected void disposeBackingImage() * Fills the specified rectangle with the clear color in the backing image. * * @param backingImage the destination backing image to fill with the clear color. - * @param x the X coordinate of the rectangle's upper-left corner, in pixels. - * @param y the Y coordinates of the rectangle's upper-left corner, in pixels. - * @param width the rectangle's width, in pixels. - * @param height the rectangle's height, in pixels. + * @param x the X coordinate of the rectangle's upper-left corner, in pixels. + * @param y the Y coordinates of the rectangle's upper-left corner, in pixels. + * @param width the rectangle's width, in pixels. + * @param height the rectangle's height, in pixels. */ - protected void clearRect(BufferedImage backingImage, int x, int y, int width, int height) - { + protected void clearRect(BufferedImage backingImage, int x, int y, int width, int height) { Graphics2D g = backingImage.createGraphics(); - try - { + try { g.setComposite(AlphaComposite.Src); // Replace destination pixels with the clear color (disables blending). g.setColor(this.clearColor); g.fillRect(x, y, width, height); - } - finally - { + } finally { g.dispose(); } } @@ -864,83 +822,77 @@ protected void clearRect(BufferedImage backingImage, int x, int y, int width, in /** * Draws the specified image in the backing image at the specified (x, y) location. If drawBorder is * true, this copies the image's outer pixels into 1 pixel border surrounding the original image. This - * border avoids sampling pixels from neighboring atlas elements when an OpenGL box filter is applied to this - * image. + * border avoids sampling pixels from neighboring atlas elements when an OpenGL box filter is applied to this image. * * @param backingImage the destination backing image to draw into. - * @param image the source image to draw. - * @param x the X coordinate of the image's upper-left corner, in pixels. - * @param y the Y coordinates of the image's upper-left corner, in pixels. + * @param image the source image to draw. + * @param x the X coordinate of the image's upper-left corner, in pixels. + * @param y the Y coordinates of the image's upper-left corner, in pixels. * @param drawBorder true this copy the image's outer pixels into 1 pixel border surrounding the - * original image, or false to draw only the image. + * original image, or false to draw only the image. */ - protected void drawImage(BufferedImage backingImage, BufferedImage image, int x, int y, boolean drawBorder) - { + protected void drawImage(BufferedImage backingImage, BufferedImage image, int x, int y, boolean drawBorder) { int w = image.getWidth(); int h = image.getHeight(); Graphics2D g = backingImage.createGraphics(); - try - { + try { // Replace destination pixels with source pixels (disables blending). g.setComposite(AlphaComposite.Src); // Copy the entire image to (x, y). g.drawImage(image, x, y, null); - if (drawBorder) - { + if (drawBorder) { // Copy the image's top left corner to (x - 1, y - 1). g.drawImage(image, - x - 1, y - 1, x, y, // dstX1, dstY1, dstX2, dstY2 - 0, 0, 1, 1, // srcX1, srcY1, srcX2, srcY2 - null); + x - 1, y - 1, x, y, // dstX1, dstY1, dstX2, dstY2 + 0, 0, 1, 1, // srcX1, srcY1, srcX2, srcY2 + null); // Copy the image's top row to (x, y - 1). g.drawImage(image, - x, y - 1, x + w, y, // dstX1, dstY1, dstX2, dstY2 - 0, 0, w, 1, // srcX1, srcY1, srcX2, srcY2 - null); + x, y - 1, x + w, y, // dstX1, dstY1, dstX2, dstY2 + 0, 0, w, 1, // srcX1, srcY1, srcX2, srcY2 + null); // Copy the image's top right corner to (x + w, y - 1). g.drawImage(image, - x + w, y - 1, x + w + 1, y, // dstX1, dstY1, dstX2, dstY2 - w - 1, 0, w, 1, // srcX1, srcY1, srcX2, srcY2 - null); + x + w, y - 1, x + w + 1, y, // dstX1, dstY1, dstX2, dstY2 + w - 1, 0, w, 1, // srcX1, srcY1, srcX2, srcY2 + null); // Copy the image's right column to (x + w, y). g.drawImage(image, - x + w, y, x + w + 1, y + h, // dstX1, dstY1, dstX2, dstY2 - w - 1, 0, w, h, // srcX1, srcY1, srcX2, srcY2 - null); + x + w, y, x + w + 1, y + h, // dstX1, dstY1, dstX2, dstY2 + w - 1, 0, w, h, // srcX1, srcY1, srcX2, srcY2 + null); // Copy the image's bottom right corner to (x + w, y + h). g.drawImage(image, - x + w, y + h, x + w + 1, y + h + 1, // dstX1, dstY1, dstX2, dstY2 - w - 1, h - 1, w, h, // srcX1, srcY1, srcX2, srcY2 - null); + x + w, y + h, x + w + 1, y + h + 1, // dstX1, dstY1, dstX2, dstY2 + w - 1, h - 1, w, h, // srcX1, srcY1, srcX2, srcY2 + null); // Copy the image's bottom row to (x, y + h). g.drawImage(image, - x, y + h, x + w, y + h + 1, // dstX1, dstY1, dstX2, dstY2 - 0, h - 1, w, h, // srcX1, srcY1, srcX2, srcY2 - null); + x, y + h, x + w, y + h + 1, // dstX1, dstY1, dstX2, dstY2 + 0, h - 1, w, h, // srcX1, srcY1, srcX2, srcY2 + null); // Copy the image's bottom left corner to (x - 1, y + h). g.drawImage(image, - x - 1, y + h, x, y + h + 1, // dstX1, dstY1, dstX2, dstY2 - 0, h - 1, 1, h, // srcX1, srcY1, srcX2, srcY2 - null); + x - 1, y + h, x, y + h + 1, // dstX1, dstY1, dstX2, dstY2 + 0, h - 1, 1, h, // srcX1, srcY1, srcX2, srcY2 + null); // Copy the image's left column to (x - 1, y). g.drawImage(image, - x - 1, y, x, y + h, // dstX1, dstY1, dstX2, dstY2 - 0, 0, 1, h, // srcX1, srcY1, srcX2, srcY2 - null); + x - 1, y, x, y + h, // dstX1, dstY1, dstX2, dstY2 + 0, 0, 1, h, // srcX1, srcY1, srcX2, srcY2 + null); } - } - finally - { + } finally { g.dispose(); } } @@ -955,10 +907,11 @@ protected void drawImage(BufferedImage backingImage, BufferedImage image, int x, * @param newBackingImage the backing image corresponding to the new layout. */ @SuppressWarnings({"UnusedParameters"}) - protected void beginMoveEntries(BufferedImage oldBackingImage, BufferedImage newBackingImage) - { + protected void beginMoveEntries(BufferedImage oldBackingImage, BufferedImage newBackingImage) { if (this.g != null) // This should never happen, but we check anyway. + { this.g.dispose(); + } this.g = newBackingImage.createGraphics(); this.g.setComposite(AlphaComposite.Src); // Replace destination pixels with source pixels. @@ -974,8 +927,7 @@ protected void beginMoveEntries(BufferedImage oldBackingImage, BufferedImage new * @param newBackingImage the backing image corresponding to the new layout. */ @SuppressWarnings({"UnusedParameters"}) - protected void endMoveEntries(BufferedImage oldBackingImage, BufferedImage newBackingImage) - { + protected void endMoveEntries(BufferedImage oldBackingImage, BufferedImage newBackingImage) { if (this.g != null) // This should never happen, but we check anyway. { this.g.dispose(); @@ -995,33 +947,29 @@ protected void endMoveEntries(BufferedImage oldBackingImage, BufferedImage newBa * image and new backing image. * * @param oldBackingImage the backing image corresponding to the previous layout. - * @param oldRect the element's location in oldBackingImage. + * @param oldRect the element's location in oldBackingImage. * @param newBackingImage the backing image corresponding to the new layout. - * @param newRect the element's location in newBackingImage. + * @param newRect the element's location in newBackingImage. */ - protected void moveEntry(BufferedImage oldBackingImage, Rect oldRect, BufferedImage newBackingImage, Rect newRect) - { + protected void moveEntry(BufferedImage oldBackingImage, Rect oldRect, BufferedImage newBackingImage, Rect newRect) { // Note that there is no need to update the rectangle instance associated with the entry for this rectangle. The // JOGL rectangle packer automatically takes care of updating the rectangle for us. this.g.setComposite(AlphaComposite.Src); // Replace destination pixels with the clear color (disables blending). - if (oldBackingImage == newBackingImage) - { + if (oldBackingImage == newBackingImage) { // The backing image has not changed. Move the entry's rectangle from its old location to its new location. this.g.copyArea(oldRect.x(), oldRect.y(), oldRect.w(), oldRect.h(), // x, y, width, height - newRect.x() - oldRect.x(), newRect.y() - oldRect.y()); // dx, dy - } - else - { + newRect.x() - oldRect.x(), newRect.y() - oldRect.y()); // dx, dy + } else { // The backing image is changing. Copy the entry from its location in the old backing images to its location // in the new backing image. this.g.drawImage(oldBackingImage, - // dstX1, dstY1, dstX2, dstY2 - newRect.x(), newRect.y(), newRect.x() + newRect.w(), newRect.y() + newRect.h(), - // srcX1, srcY1, srcX2, srcY2 - oldRect.x(), oldRect.y(), oldRect.x() + oldRect.w(), oldRect.y() + oldRect.h(), - null); + // dstX1, dstY1, dstX2, dstY2 + newRect.x(), newRect.y(), newRect.x() + newRect.w(), newRect.y() + newRect.h(), + // srcX1, srcY1, srcX2, srcY2 + oldRect.x(), oldRect.y(), oldRect.x() + oldRect.w(), oldRect.y() + oldRect.h(), + null); } } @@ -1030,8 +978,7 @@ protected void moveEntry(BufferedImage oldBackingImage, Rect oldRect, BufferedIm * * @param entry the entry who's last used time is marked. */ - protected void markUsed(Entry entry) - { + protected void markUsed(Entry entry) { entry.lastUsed = System.nanoTime(); } @@ -1040,10 +987,10 @@ protected void markUsed(Entry entry) * * @return true if this removed an entry, and false if there are no entries to remove. */ - protected boolean removeLeastRecentlyUsedEntry() - { - if (this.entryMap.isEmpty()) + protected boolean removeLeastRecentlyUsedEntry() { + if (this.entryMap.isEmpty()) { return false; + } Entry[] timeOrderedEntries = new Entry[this.entryMap.size()]; Arrays.sort(this.entryMap.values().toArray(timeOrderedEntries)); @@ -1061,8 +1008,7 @@ protected boolean removeLeastRecentlyUsedEntry() * * @return the region of this texture atlas that must be synchronized. */ - protected Rectangle getDirtyRect() - { + protected Rectangle getDirtyRect() { return this.dirtyRect; } @@ -1070,27 +1016,26 @@ protected Rectangle getDirtyRect() * Marks a region of this texture atlas' backing image as needing to be synchronized with the OpenGL texture. If * there is already a dirty region, the final dirty region is the union of the two. * - * @param x the X coordinate of the region's upper-left corner, in pixels. - * @param y the Y coordinate of the region's upper-left corner, in pixels. - * @param width the region's width, in pixels. + * @param x the X coordinate of the region's upper-left corner, in pixels. + * @param y the Y coordinate of the region's upper-left corner, in pixels. + * @param width the region's width, in pixels. * @param height the region's height, in pixels. */ - protected void markDirty(int x, int y, int width, int height) - { + protected void markDirty(int x, int y, int width, int height) { Rectangle rect = new Rectangle(x, y, width, height); - if (this.dirtyRect == null) + if (this.dirtyRect == null) { this.dirtyRect = rect; - else + } else { this.dirtyRect.add(rect); + } } /** * Removes any regions in this texture atlas' backing image previously marked as needing to be synchronized with the * OpenGL texture. */ - protected void clearDirtyRect() - { + protected void clearDirtyRect() { this.dirtyRect = null; } @@ -1101,20 +1046,18 @@ protected void clearDirtyRect() * * @return this instance's OpenGL texture, or null if the texture does not currently exist. */ - protected Texture getTexture(DrawContext dc) - { + protected Texture getTexture(DrawContext dc) { return dc.getTextureCache().getTexture(this.textureKey); } /** * Specifies the OpenGL {@link Texture} associated with this texture atlas. * - * @param dc the current draw context. + * @param dc the current draw context. * @param texture this instance's OpenGL texture, or null to specify that this texture atlas has no - * texture. + * texture. */ - protected void setTexture(DrawContext dc, Texture texture) - { + protected void setTexture(DrawContext dc, Texture texture) { dc.getTextureCache().put(this.textureKey, texture); } @@ -1126,19 +1069,18 @@ protected void setTexture(DrawContext dc, Texture texture) * * @param dc the draw context containing the GPU resource cache to remove textures from. */ - protected void disposeOldTextures(DrawContext dc) - { + protected void disposeOldTextures(DrawContext dc) { // Process each key in the disposedTextureKeys queue. Since TextureAtlas keys are unique to each instance, the // texture keys are not shared with any other object, and therefore are orphaned once they're unused. We // explicitly remove them from the texture cache to ensure that this texture atlas uses a minimal amount of // texture memory. Object key; - while ((key = this.disposedTextureKeys.poll()) != null) - { + while ((key = this.disposedTextureKeys.poll()) != null) { // The key may never have been be associated with a texture if this texture atlas was expanded or contracted // more than once between calls to bind. In this case we just ignore the disposed key and continue. - if (dc.getTextureCache().contains(key)) + if (dc.getTextureCache().contains(key)) { dc.getTextureCache().remove(key); + } } } @@ -1151,18 +1093,14 @@ protected void disposeOldTextures(DrawContext dc) * * @return this texture atlas' OpenGL texture. */ - protected Texture syncTexture(DrawContext dc) - { + protected Texture syncTexture(DrawContext dc) { Texture texture = this.getTexture(dc); - if (texture == null) - { + if (texture == null) { // This texture atlas' OpenGL texture does not exist on the specified draw context. Load the entire backing // image into a new texture and use that as this texture atlas' OpenGL texture. texture = this.makeTextureWithBackingImage(dc); - } - else if (this.getDirtyRect() != null) - { + } else if (this.getDirtyRect() != null) { // A region of this texture atlas' OpenGL texture is out-of-sync; load only the necessary portion of the // backing image into the texture. texture = this.updateTextureWithSubImage(dc, this.getDirtyRect()); @@ -1182,8 +1120,7 @@ else if (this.getDirtyRect() != null) * * @return a new OpenGL texture containing the data from this texture atlas' backing image. */ - protected Texture makeTextureWithBackingImage(DrawContext dc) - { + protected Texture makeTextureWithBackingImage(DrawContext dc) { BufferedImage backingImage = (BufferedImage) this.rectPacker.getBackingStore(); Texture texture = AWTTextureIO.newTexture(dc.getGL().getGLProfile(), backingImage, this.isUseMipMaps()); @@ -1197,14 +1134,13 @@ protected Texture makeTextureWithBackingImage(DrawContext dc) * Loads a sub-region of this texture atlas' backing image into its OpenGL texture. This does nothing and returns * code null if this texture atlas' does not have an OpenGL texture. * - * @param dc the current draw context. + * @param dc the current draw context. * @param rect the rectangle to load. * * @return this texture atlas' OpenGL texture, or null if this texture atlas' does not have an OpenGL - * texture. + * texture. */ - protected Texture updateTextureWithSubImage(DrawContext dc, Rectangle rect) - { + protected Texture updateTextureWithSubImage(DrawContext dc, Rectangle rect) { Texture texture = this.getTexture(dc); if (texture == null) // This should never happen, but we check anyway. { @@ -1213,8 +1149,7 @@ protected Texture updateTextureWithSubImage(DrawContext dc, Rectangle rect) return null; } - if (!this.isUseMipMaps() || texture.isUsingAutoMipmapGeneration()) - { + if (!this.isUseMipMaps() || texture.isUsingAutoMipmapGeneration()) { // If we're either not using mip-maps or we have automatic mip-map generation, then load the sub-image // corresponding to the specified rectangle into the OpenGL texture. Note that the x and y coordinates of // the dirty region do not need to be translated because the image and texture share the same coordinate @@ -1224,9 +1159,7 @@ protected Texture updateTextureWithSubImage(DrawContext dc, Rectangle rect) GL gl = dc.getGL(); TextureData subTextureData = AWTTextureIO.newTextureData(gl.getGLProfile(), subImage, false); texture.updateSubImage(gl, subTextureData, 0, rect.x, rect.y); - } - else - { + } else { // If we're using mip-maps but do not have automatic mip-map generation, we must load the entire image into // the texture in order to force JOGL to recompute the mip-map data for all levels in Java. We must also // respecify the texture parameters, because Texture.updateImage overwrites the texture parameters with @@ -1247,8 +1180,7 @@ protected Texture updateTextureWithSubImage(DrawContext dc, Rectangle rect) * * @param dc the current draw context. */ - protected void setTextureParameters(DrawContext dc) - { + protected void setTextureParameters(DrawContext dc) { GL gl = dc.getGL(); // The JOGL Texture class specifies appropriate default values for the following OpenGL texture parameters: @@ -1256,12 +1188,9 @@ protected void setTextureParameters(DrawContext dc) // - GL_TEXTURE_MAG_FILTER // - GL_TEXTURE_WRAP_S // - GL_TEXTURE_WRAP_T - - if (this.isUseMipMaps() && this.isUseAnisotropy()) - { + if (this.isUseMipMaps() && this.isUseAnisotropy()) { double maxAnisotropy = dc.getGLRuntimeCapabilities().getMaxTextureAnisotropy(); - if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) - { + if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) { gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, (float) maxAnisotropy); } } diff --git a/src/gov/nasa/worldwind/util/TextureAtlasElement.java b/src/gov/nasa/worldwind/util/TextureAtlasElement.java index c3ac2087c0..871b75f6d2 100644 --- a/src/gov/nasa/worldwind/util/TextureAtlasElement.java +++ b/src/gov/nasa/worldwind/util/TextureAtlasElement.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import com.jogamp.opengl.util.texture.TextureCoords; @@ -29,11 +28,15 @@ * @author dcollins * @version $Id: TextureAtlasElement.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TextureAtlasElement implements Disposable -{ - /** Indicates the texture atlas this element belongs to. Specified during construction. */ +public class TextureAtlasElement implements Disposable { + + /** + * Indicates the texture atlas this element belongs to. Specified during construction. + */ protected TextureAtlas atlas; - /** Indicates the original image source associated with this element. Specified during construction. */ + /** + * Indicates the original image source associated with this element. Specified during construction. + */ protected Object imageSource; /** * The BufferedImage created as the image source is read. This intermediate field is necessary because the image @@ -59,25 +62,21 @@ public class TextureAtlasElement implements Disposable /** * Creates a new texture atlas element with the specified atlas and image source. * - * @param atlas the texture atlas this element belongs to. + * @param atlas the texture atlas this element belongs to. * @param imageSource a general image source. The source type may be one of the following:

          • a {@link * URL}
          • an {@link java.io.InputStream}
          • a {@link java.io.File}
          • a {@link - * String} containing a valid URL description or a file or resource name available on the - * classpath.
          + * String} containing a valid URL description or a file or resource name available on the classpath. * * @throws IllegalArgumentException if either the atlas or the image source is null. */ - public TextureAtlasElement(TextureAtlas atlas, Object imageSource) - { - if (atlas == null) - { + public TextureAtlasElement(TextureAtlas atlas, Object imageSource) { + if (atlas == null) { String msg = Logging.getMessage("nullValue.AtlasIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (WWUtil.isEmpty(imageSource)) - { + if (WWUtil.isEmpty(imageSource)) { String msg = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -92,8 +91,7 @@ public TextureAtlasElement(TextureAtlas atlas, Object imageSource) * * @return this element's texture atlas. */ - public TextureAtlas getTextureAtlas() - { + public TextureAtlas getTextureAtlas() { return this.atlas; } @@ -102,8 +100,7 @@ public TextureAtlas getTextureAtlas() * * @return this element's image source. */ - public Object getImageSource() - { + public Object getImageSource() { return this.imageSource; } @@ -112,8 +109,7 @@ public Object getImageSource() * * @return true if this element's image source is a BufferedImage, and false otherwise. */ - protected boolean isBufferedImageSource() - { + protected boolean isBufferedImageSource() { return this.getImageSource() instanceof BufferedImage; } @@ -124,8 +120,7 @@ protected boolean isBufferedImageSource() * * @see #setImage(java.awt.image.BufferedImage) */ - protected BufferedImage getImage() - { + protected BufferedImage getImage() { return this.image; } @@ -136,8 +131,7 @@ protected BufferedImage getImage() * * @param image this element's image. */ - protected void setImage(BufferedImage image) - { + protected void setImage(BufferedImage image) { this.image = image; } @@ -146,12 +140,11 @@ protected void setImage(BufferedImage image) * calling this method to ensure that the element is loaded into its texture atlas. * * @return the image dimensions associated with this texture atlas element, or null if this texture - * atlas element has not yet loaded or has failed to load. + * atlas element has not yet loaded or has failed to load. * * @see #load(gov.nasa.worldwind.render.DrawContext) */ - public Dimension getSize() - { + public Dimension getSize() { return this.getTextureAtlas().getSize(this.getImageSource()); } @@ -164,12 +157,11 @@ public Dimension getSize() * atlas has changed. * * @return the OpenGL texture coordinates corresponding this texture atlas element, or null if this - * texture atlas element has not yet loaded or has failed to load. + * texture atlas element has not yet loaded or has failed to load. * * @see #load(gov.nasa.worldwind.render.DrawContext) */ - public TextureCoords getTexCoords() - { + public TextureCoords getTexCoords() { return this.getTextureAtlas().getTexCoords(this.getImageSource()); } @@ -178,8 +170,7 @@ public TextureCoords getTexCoords() * * @return true if this element's image failed to load, and false otherwise. */ - public boolean isImageInitializationFailed() - { + public boolean isImageInitializationFailed() { return this.imageInitializationFailed; } @@ -191,23 +182,23 @@ public boolean isImageInitializationFailed() * @param dc the current draw context. Used to generate a repaint event when the image source retrieval completes. * * @return true if this element's image is successfully loaded and added to the texture atlas, - * otherwise false. + * otherwise false. */ - public boolean load(DrawContext dc) - { - if (dc == null) - { + public boolean load(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.isImageInitializationFailed()) + if (this.isImageInitializationFailed()) { return false; + } // The atlas already contains an entry for this element then just return true. - if (this.getTextureAtlas().contains(this.getImageSource())) + if (this.getTextureAtlas().contains(this.getImageSource())) { return true; + } // The atlas does not contain an entry for this element. Issue a request for this element's image if it does not // exist, or load it into the atlas if it does. In this case we return true if this element was successfully @@ -219,10 +210,10 @@ public boolean load(DrawContext dc) * Removes this element's image from its texture atlas and disposes of this element's image resource. This does * nothing if this element's image has not yet been loaded. */ - public void dispose() - { - if (this.getTextureAtlas().contains(this.getImageSource())) + public void dispose() { + if (this.getTextureAtlas().contains(this.getImageSource())) { this.getTextureAtlas().remove(this.getImageSource()); + } this.setImage(null); } @@ -234,31 +225,34 @@ public void dispose() * @param o the object to test. * * @return true if the specified object is a TextureAtlasElement and its image source is equivalent to - * this element's image source, otherwise false. + * this element's image source, otherwise false. */ @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } TextureAtlasElement that = (TextureAtlasElement) o; return this.imageSource != null ? this.imageSource.equals(that.imageSource) : that.imageSource == null; } - /** Returns the hash code for this texture atlas element's image source. */ + /** + * Returns the hash code for this texture atlas element's image source. + */ @Override - public int hashCode() - { + public int hashCode() { return this.imageSource != null ? this.imageSource.hashCode() : 0; } - /** Returns the string representation of this texture atlas element's image source. */ + /** + * Returns the string representation of this texture atlas element's image source. + */ @Override - public String toString() - { + public String toString() { return this.imageSource != null ? this.imageSource.toString() : null; } @@ -272,24 +266,27 @@ public String toString() * @param dc the current draw context. Used to generate a repaint event when the image source retrieval completes. * * @return true if this element's image is loaded into the texture atlas, and false - * otherwise. + * otherwise. */ - protected boolean requestImage(DrawContext dc) - { + protected boolean requestImage(DrawContext dc) { // If the image source is already a buffered image, assign it to this element's image and let the subsequent // logic in this method take care of adding it to the atlas. - if (this.isBufferedImageSource()) + if (this.isBufferedImageSource()) { this.setImage((BufferedImage) this.getImageSource()); + } - if (this.getImage() != null && !this.getTextureAtlas().contains(this.getImageSource())) + if (this.getImage() != null && !this.getTextureAtlas().contains(this.getImageSource())) { return this.addAtlasImage(); + } - if (WorldWind.getTaskService().isFull()) + if (WorldWind.getTaskService().isFull()) { return false; + } Runnable task = this.createRequestTask(); - if (WorldWind.getTaskService().contains(task)) + if (WorldWind.getTaskService().contains(task)) { return false; + } // Use either the current layer or the layer list as the listener to notify when the request completes. The // latter is used when the image source is requested during ordered rendering mode, and the current layer is @@ -306,25 +303,20 @@ protected boolean requestImage(DrawContext dc) * is not loaded and stored in the image property. * * @return true if this element's image is successfully added to the texture atlas, and - * false otherwise. + * false otherwise. */ - protected boolean addAtlasImage() - { - if (this.getImage() == null) - { + protected boolean addAtlasImage() { + if (this.getImage() == null) { String msg = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - try - { + try { // Place this element's image in the atlas, then release our reference to the image. this.getTextureAtlas().add(this.getImageSource(), this.getImage()); this.setImage(null); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("TextureAtlas.ExceptionAddingImage", this.getImageSource().toString()); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.imageInitializationFailed = true; @@ -340,8 +332,7 @@ protected boolean addAtlasImage() * * @return a new request task that retrieves and loads this element's image source. */ - protected Runnable createRequestTask() - { + protected Runnable createRequestTask() { return new RequestTask(this); } @@ -351,14 +342,13 @@ protected Runnable createRequestTask() * * @return true if the image source has been loaded successfully, and false otherwise. */ - protected boolean loadImage() - { + protected boolean loadImage() { URL fileUrl = WorldWind.getDataFileStore().requestFile(this.getImageSource().toString()); - if (fileUrl != null) - { + if (fileUrl != null) { BufferedImage image = this.readImage(fileUrl); - if (image != null) + if (image != null) { this.setImage(image); + } } return this.getImage() != null; @@ -371,16 +361,12 @@ protected boolean loadImage() * * @return the image URL as a BufferedImage, or null if the image could not be read. */ - protected BufferedImage readImage(URL fileUrl) - { - try - { + protected BufferedImage readImage(URL fileUrl) { + try { return ImageIO.read(fileUrl); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToReadImageFile", - this.getImageSource().toString()); + this.getImageSource().toString()); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.imageInitializationFailed = true; return null; @@ -391,10 +377,8 @@ protected BufferedImage readImage(URL fileUrl) * Notifies this texture atlas element's listener that image loading has completed. This does nothing if this * texture atlas element has no listener. */ - protected void notifyImageLoaded() - { - if (this.listener != null) - { + protected void notifyImageLoaded() { + if (this.listener != null) { this.listener.propertyChange(new PropertyChangeEvent(this, AVKey.IMAGE, null, this)); this.listener = null; // Forget the listener to avoid dangling references. } @@ -404,9 +388,11 @@ protected void notifyImageLoaded() * RequestTask is an implementation of the Runnable interface who's run method retrieves and loads this * element's image source. */ - protected static class RequestTask implements Runnable - { - /** The texture atlas element associated with this request task. Specified during construction. */ + protected static class RequestTask implements Runnable { + + /** + * The texture atlas element associated with this request task. Specified during construction. + */ protected TextureAtlasElement elem; /** @@ -418,10 +404,8 @@ protected static class RequestTask implements Runnable * * @throws IllegalArgumentException if the element is null. */ - protected RequestTask(TextureAtlasElement elem) - { - if (elem == null) - { + protected RequestTask(TextureAtlasElement elem) { + if (elem == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -434,13 +418,13 @@ protected RequestTask(TextureAtlasElement elem) * Retrieves and loads the image source from this request task's texture atlas element, and notifies the element * when the load completes. This does nothing if the current thread has been interrupted. */ - public void run() - { - if (Thread.currentThread().isInterrupted()) + public void run() { + if (Thread.currentThread().isInterrupted()) { return; // The task was cancelled because it's a duplicate or for some other reason. - - if (this.elem.loadImage()) + } + if (this.elem.loadImage()) { this.elem.notifyImageLoaded(); + } } /** @@ -450,31 +434,34 @@ public void run() * @param o the object to test. * * @return true if the specified object is a RequestTask, and its texture atlas element is - * equivalent to this task's texture atlas element. + * equivalent to this task's texture atlas element. */ @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } RequestTask that = (RequestTask) o; return this.elem.equals(that.elem); } - /** Returns the hash code for this request task's texture atlas element. */ + /** + * Returns the hash code for this request task's texture atlas element. + */ @Override - public int hashCode() - { + public int hashCode() { return this.elem.hashCode(); } - /** Returns the string representation of this request task's texture atlas element. */ + /** + * Returns the string representation of this request task's texture atlas element. + */ @Override - public String toString() - { + public String toString() { return this.elem.toString(); } } diff --git a/src/gov/nasa/worldwind/util/ThreadedTaskService.java b/src/gov/nasa/worldwind/util/ThreadedTaskService.java index 954af5a769..e8c7b381b7 100644 --- a/src/gov/nasa/worldwind/util/ThreadedTaskService.java +++ b/src/gov/nasa/worldwind/util/ThreadedTaskService.java @@ -14,19 +14,18 @@ * @author Tom Gaskins * @version $Id: ThreadedTaskService.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ThreadedTaskService extends WWObjectImpl implements TaskService, Thread.UncaughtExceptionHandler -{ +public class ThreadedTaskService extends WWObjectImpl implements TaskService, Thread.UncaughtExceptionHandler { + static final private int DEFAULT_CORE_POOL_SIZE = 1; static final private int DEFAULT_QUEUE_SIZE = 10; private static final String RUNNING_THREAD_NAME_PREFIX = Logging.getMessage( - "ThreadedTaskService.RunningThreadNamePrefix"); + "ThreadedTaskService.RunningThreadNamePrefix"); private static final String IDLE_THREAD_NAME_PREFIX = Logging.getMessage( - "ThreadedTaskService.IdleThreadNamePrefix"); + "ThreadedTaskService.IdleThreadNamePrefix"); private ConcurrentLinkedQueue activeTasks; // tasks currently allocated a thread private TaskExecutor executor; // thread pool for running retrievers - public ThreadedTaskService() - { + public ThreadedTaskService() { Integer poolSize = Configuration.getIntegerValue(AVKey.TASK_POOL_SIZE, DEFAULT_CORE_POOL_SIZE); Integer queueSize = Configuration.getIntegerValue(AVKey.TASK_QUEUE_SIZE, DEFAULT_QUEUE_SIZE); @@ -37,73 +36,64 @@ public ThreadedTaskService() this.activeTasks = new ConcurrentLinkedQueue(); } - public void shutdown(boolean immediately) - { - if (immediately) + public void shutdown(boolean immediately) { + if (immediately) { this.executor.shutdownNow(); - else + } else { this.executor.shutdown(); + } this.activeTasks.clear(); } - public void uncaughtException(Thread thread, Throwable throwable) - { + public void uncaughtException(Thread thread, Throwable throwable) { String message = Logging.getMessage("ThreadedTaskService.UncaughtExceptionDuringTask", thread.getName()); Logging.logger().fine(message); Thread.currentThread().getThreadGroup().uncaughtException(thread, throwable); } - private class TaskExecutor extends ThreadPoolExecutor - { + private class TaskExecutor extends ThreadPoolExecutor { + private static final long THREAD_TIMEOUT = 2; // keep idle threads alive this many seconds - private TaskExecutor(int poolSize, int queueSize) - { + private TaskExecutor(int poolSize, int queueSize) { super(poolSize, poolSize, THREAD_TIMEOUT, TimeUnit.SECONDS, - new ArrayBlockingQueue(queueSize), - new ThreadFactory() - { - public Thread newThread(Runnable runnable) - { - Thread thread = new Thread(runnable); - thread.setDaemon(true); - thread.setPriority(Thread.MIN_PRIORITY); - thread.setUncaughtExceptionHandler(ThreadedTaskService.this); - return thread; - } - }, - new ThreadPoolExecutor.DiscardPolicy() // abandon task when queue is full - { - public void rejectedExecution(Runnable runnable, - ThreadPoolExecutor threadPoolExecutor) - { - // Interposes logging for rejected execution - String message = Logging.getMessage("ThreadedTaskService.ResourceRejected", runnable); - Logging.logger().fine(message); - super.rejectedExecution(runnable, threadPoolExecutor); - } - }); + new ArrayBlockingQueue(queueSize), + new ThreadFactory() { + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + thread.setPriority(Thread.MIN_PRIORITY); + thread.setUncaughtExceptionHandler(ThreadedTaskService.this); + return thread; + } + }, + new ThreadPoolExecutor.DiscardPolicy() // abandon task when queue is full + { + public void rejectedExecution(Runnable runnable, + ThreadPoolExecutor threadPoolExecutor) { + // Interposes logging for rejected execution + String message = Logging.getMessage("ThreadedTaskService.ResourceRejected", runnable); + Logging.logger().fine(message); + super.rejectedExecution(runnable, threadPoolExecutor); + } + }); } - protected void beforeExecute(Thread thread, Runnable runnable) - { - if (thread == null) - { + protected void beforeExecute(Thread thread, Runnable runnable) { + if (thread == null) { String msg = Logging.getMessage("nullValue.ThreadIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (runnable == null) - { + if (runnable == null) { String msg = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (ThreadedTaskService.this.activeTasks.contains(runnable)) - { + if (ThreadedTaskService.this.activeTasks.contains(runnable)) { // Duplicate requests are simply interrupted here. The task itself must check the thread's isInterrupted // flag and actually terminate the task. String message = Logging.getMessage("ThreadedTaskService.CancellingDuplicateTask", runnable); @@ -114,18 +104,17 @@ protected void beforeExecute(Thread thread, Runnable runnable) ThreadedTaskService.this.activeTasks.add(runnable); - if (RUNNING_THREAD_NAME_PREFIX != null) + if (RUNNING_THREAD_NAME_PREFIX != null) { thread.setName(RUNNING_THREAD_NAME_PREFIX + runnable); + } thread.setPriority(Thread.MIN_PRIORITY); thread.setUncaughtExceptionHandler(ThreadedTaskService.this); super.beforeExecute(thread, runnable); } - protected void afterExecute(Runnable runnable, Throwable throwable) - { - if (runnable == null) - { + protected void afterExecute(Runnable runnable, Throwable throwable) { + if (runnable == null) { String msg = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -135,16 +124,17 @@ protected void afterExecute(Runnable runnable, Throwable throwable) ThreadedTaskService.this.activeTasks.remove(runnable); - if (throwable == null && IDLE_THREAD_NAME_PREFIX != null) + if (throwable == null && IDLE_THREAD_NAME_PREFIX != null) { Thread.currentThread().setName(IDLE_THREAD_NAME_PREFIX); + } } } - public synchronized boolean contains(Runnable runnable) - { + public synchronized boolean contains(Runnable runnable) { //noinspection SimplifiableIfStatement - if (runnable == null) + if (runnable == null) { return false; + } return (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)); } @@ -156,35 +146,32 @@ public synchronized boolean contains(Runnable runnable) * * @throws IllegalArgumentException if runnable is null */ - public synchronized void addTask(Runnable runnable) - { - if (runnable == null) - { + public synchronized void addTask(Runnable runnable) { + if (runnable == null) { String message = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } // Do not queue duplicates. - if (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)) + if (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)) { return; + } this.executor.execute(runnable); } - public boolean isFull() - { + public boolean isFull() { return this.executor.getQueue().remainingCapacity() == 0; } - public boolean hasActiveTasks() - { + public boolean hasActiveTasks() { Thread[] threads = new Thread[Thread.activeCount()]; int numThreads = Thread.enumerate(threads); - for (int i = 0; i < numThreads; i++) - { - if (threads[i].getName().startsWith(RUNNING_THREAD_NAME_PREFIX)) + for (int i = 0; i < numThreads; i++) { + if (threads[i].getName().startsWith(RUNNING_THREAD_NAME_PREFIX)) { return true; + } } return false; } diff --git a/src/gov/nasa/worldwind/util/Tile.java b/src/gov/nasa/worldwind/util/Tile.java index 8946c2a690..a347a72e44 100644 --- a/src/gov/nasa/worldwind/util/Tile.java +++ b/src/gov/nasa/worldwind/util/Tile.java @@ -22,13 +22,15 @@ * @author tag * @version $Id: Tile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Tile implements Comparable, Cacheable -{ +public class Tile implements Comparable, Cacheable { + private final Sector sector; private final Level level; private final int row; private final int column; - /** An optional cache name. Overrides the Level's cache name when non-null. */ + /** + * An optional cache name. Overrides the Level's cache name when non-null. + */ private final String cacheName; private final TileKey tileKey; private double priority = Double.MAX_VALUE; // Default is minimum priority @@ -39,23 +41,20 @@ public class Tile implements Comparable, Cacheable * Constructs a tile for a given sector, level, row and column of the tile's containing tile set. * * @param sector the sector corresponding with the tile. - * @param level the tile's level within a containing level set. - * @param row the row index (0 origin) of the tile within the indicated level. + * @param level the tile's level within a containing level set. + * @param row the row index (0 origin) of the tile within the indicated level. * @param column the column index (0 origin) of the tile within the indicated level. * * @throws IllegalArgumentException if sector or level is null. */ - public Tile(Sector sector, Level level, int row, int column) - { - if (sector == null) - { + public Tile(Sector sector, Level level, int row, int column) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (level == null) - { + if (level == null) { String msg = Logging.getMessage("nullValue.LevelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -93,25 +92,22 @@ public Tile(Sector sector, Level level, int row, int column) * is non-null, it overrides the level's cache name and is returned by {@link #getCacheName()}. Otherwise, the * level's cache name is used. * - * @param sector the sector corresponding with the tile. - * @param level the tile's level within a containing level set. - * @param row the row index (0 origin) of the tile within the indicated level. - * @param column the column index (0 origin) of the tile within the indicated level. + * @param sector the sector corresponding with the tile. + * @param level the tile's level within a containing level set. + * @param row the row index (0 origin) of the tile within the indicated level. + * @param column the column index (0 origin) of the tile within the indicated level. * @param cacheName optional cache name to override the Level's cache name. May be null. * * @throws IllegalArgumentException if sector or level is null. */ - public Tile(Sector sector, Level level, int row, int column, String cacheName) - { - if (sector == null) - { + public Tile(Sector sector, Level level, int row, int column, String cacheName) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (level == null) - { + if (level == null) { String msg = Logging.getMessage("nullValue.LevelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -130,20 +126,17 @@ public Tile(Sector sector, Level level, int row, int column, String cacheName) * Constructs a texture tile for a given sector and level, and with a default row and column. * * @param sector the sector to create the tile for. - * @param level the level to associate the tile with + * @param level the level to associate the tile with * * @throws IllegalArgumentException if sector or level are null. */ - public Tile(Sector sector, Level level) - { - if (sector == null) - { + public Tile(Sector sector, Level level) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (level == null) - { + if (level == null) { String msg = Logging.getMessage("nullValue.LevelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -163,10 +156,8 @@ public Tile(Sector sector, Level level) * * @param sector the sector to create the tile for. */ - public Tile(Sector sector) - { - if (sector == null) - { + public Tile(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -183,68 +174,61 @@ public Tile(Sector sector) this.path = null; } - public long getSizeInBytes() - { + public long getSizeInBytes() { // Return just an approximate size long size = 0; - if (this.sector != null) + if (this.sector != null) { size += this.sector.getSizeInBytes(); + } - if (this.path != null) + if (this.path != null) { size += this.getPath().length(); + } size += 32; // to account for the references and the TileKey size return size; } - public String getPath() - { - if (this.path == null) - { + public String getPath() { + if (this.path == null) { this.path = this.level.getPath() + "/" + this.row + "/" + this.row + "_" + this.column; - if (!this.level.isEmpty()) + if (!this.level.isEmpty()) { path += this.level.getFormatSuffix(); + } } return this.path; } - public String getPathBase() - { + public String getPathBase() { String path = this.getPath(); return path.contains(".") ? path.substring(0, path.lastIndexOf(".")) : path; } - public final Sector getSector() - { + public final Sector getSector() { return sector; } - public Level getLevel() - { + public Level getLevel() { return level; } - public final int getLevelNumber() - { + public final int getLevelNumber() { return this.level != null ? this.level.getLevelNumber() : 0; } - public final String getLevelName() - { + public final String getLevelName() { return this.level != null ? this.level.getLevelName() : ""; } - public final int getRow() - { + public final int getRow() { return row; } - public final int getColumn() - { + public final int getColumn() { return column; } @@ -254,36 +238,31 @@ public final int getColumn() * * @return the tile's cache name. */ - public final String getCacheName() - { - if (this.cacheName != null) + public final String getCacheName() { + if (this.cacheName != null) { return this.cacheName; + } return this.level != null ? this.level.getCacheName() : null; } - public final String getFormatSuffix() - { + public final String getFormatSuffix() { return this.level != null ? this.level.getFormatSuffix() : null; } - public final TileKey getTileKey() - { + public final TileKey getTileKey() { return this.tileKey; } - public java.net.URL getResourceURL() throws java.net.MalformedURLException - { + public java.net.URL getResourceURL() throws java.net.MalformedURLException { return this.level != null ? this.level.getTileResourceURL(this, null) : null; } - public java.net.URL getResourceURL(String imageFormat) throws java.net.MalformedURLException - { + public java.net.URL getResourceURL(String imageFormat) throws java.net.MalformedURLException { return this.level != null ? this.level.getTileResourceURL(this, imageFormat) : null; } - public String getLabel() - { + public String getLabel() { StringBuilder sb = new StringBuilder(); sb.append(this.getLevelNumber()); @@ -296,53 +275,57 @@ public String getLabel() return sb.toString(); } - public int getWidth() - { + public int getWidth() { return this.getLevel().getTileWidth(); } - public int getHeight() - { + public int getHeight() { return this.getLevel().getTileHeight(); } - public int compareTo(Tile tile) - { - if (tile == null) - { + public int compareTo(Tile tile) { + if (tile == null) { String msg = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // No need to compare Sectors or path because they are redundant with row and column - if (tile.getLevelNumber() == this.getLevelNumber() && tile.row == this.row && tile.column == this.column) + if (tile.getLevelNumber() == this.getLevelNumber() && tile.row == this.row && tile.column == this.column) { return 0; + } if (this.getLevelNumber() < tile.getLevelNumber()) // Lower-res levels compare lower than higher-res + { return -1; - if (this.getLevelNumber() > tile.getLevelNumber()) + } + if (this.getLevelNumber() > tile.getLevelNumber()) { return 1; + } - if (this.row < tile.row) + if (this.row < tile.row) { return -1; - if (this.row > tile.row) + } + if (this.row > tile.row) { return 1; + } - if (this.column < tile.column) + if (this.column < tile.column) { return -1; + } return 1; // tile.column must be > this.column because equality was tested above } @Override - public boolean equals(Object o) - { + public boolean equals(Object o) { // Equality based only on the tile key - if (this == o) + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final Tile tile = (Tile) o; @@ -350,47 +333,41 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { return (tileKey != null ? tileKey.hashCode() : 0); } @Override - public String toString() - { + public String toString() { return this.getPath(); } /** * Computes the row index of a latitude in the global tile grid corresponding to a specified grid interval. * - * @param delta the grid interval + * @param delta the grid interval * @param latitude the latitude for which to compute the row index - * @param origin the origin of the grid + * @param origin the origin of the grid * * @return the row index of the row containing the specified latitude * * @throws IllegalArgumentException if delta is null or non-positive, or latitude is null, - * greater than positive 90 degrees, or less than negative 90 degrees + * greater than positive 90 degrees, or less than negative 90 degrees */ - public static int computeRow(Angle delta, Angle latitude, Angle origin) - { - if (delta == null || latitude == null || origin == null) - { + public static int computeRow(Angle delta, Angle latitude, Angle origin) { + if (delta == null || latitude == null || origin == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (delta.degrees <= 0d) - { + if (delta.degrees <= 0d) { String message = Logging.getMessage("generic.DeltaAngleOutOfRange", delta); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (latitude.degrees < -90d || latitude.degrees > 90d) - { + if (latitude.degrees < -90d || latitude.degrees > 90d) { String message = Logging.getMessage("generic.AngleOutOfRange", latitude); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -398,8 +375,9 @@ public static int computeRow(Angle delta, Angle latitude, Angle origin) int row = (int) ((latitude.degrees - origin.degrees) / delta.degrees); // Latitude is at the end of the grid. Subtract 1 from the computed row to return the last row. - if ((latitude.degrees - origin.degrees) == 180d) + if ((latitude.degrees - origin.degrees) == 180d) { row = row - 1; + } return row; } @@ -407,33 +385,29 @@ public static int computeRow(Angle delta, Angle latitude, Angle origin) /** * Computes the column index of a longitude in the global tile grid corresponding to a specified grid interval. * - * @param delta the grid interval + * @param delta the grid interval * @param longitude the longitude for which to compute the column index - * @param origin the origin of the grid + * @param origin the origin of the grid * * @return the column index of the column containing the specified latitude * * @throws IllegalArgumentException if delta is null or non-positive, or longitude is - * null, greater than positive 180 degrees, or less than negative 180 degrees + * null, greater than positive 180 degrees, or less than negative 180 degrees */ - public static int computeColumn(Angle delta, Angle longitude, Angle origin) - { - if (delta == null || longitude == null || origin == null) - { + public static int computeColumn(Angle delta, Angle longitude, Angle origin) { + if (delta == null || longitude == null || origin == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (delta.degrees <= 0d) - { + if (delta.degrees <= 0d) { String message = Logging.getMessage("generic.DeltaAngleOutOfRange", delta); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (longitude.degrees < -180d || longitude.degrees > 180d) - { + if (longitude.degrees < -180d || longitude.degrees > 180d) { String message = Logging.getMessage("generic.AngleOutOfRange", longitude); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -442,13 +416,15 @@ public static int computeColumn(Angle delta, Angle longitude, Angle origin) // Compute the longitude relative to the grid. The grid provides 360 degrees of longitude from the grid origin. // We wrap grid longitude values so that the grid begins and ends at the origin. double gridLongitude = longitude.degrees - origin.degrees; - if (gridLongitude < 0.0) + if (gridLongitude < 0.0) { gridLongitude = 360d + gridLongitude; + } int col = (int) (gridLongitude / delta.degrees); // Longitude is at the end of the grid. Subtract 1 from the computed column to return the last column. - if ((longitude.degrees - origin.degrees) == 360d) + if ((longitude.degrees - origin.degrees) == 360d) { col = col - 1; + } return col; } @@ -456,32 +432,28 @@ public static int computeColumn(Angle delta, Angle longitude, Angle origin) /** * Determines the minimum latitude of a row in the global tile grid corresponding to a specified grid interval. * - * @param row the row index of the row in question - * @param delta the grid interval + * @param row the row index of the row in question + * @param delta the grid interval * @param origin the origin of the grid * * @return the minimum latitude of the tile corresponding to the specified row * * @throws IllegalArgumentException if the grid interval (delta) is null or zero or the row index is - * negative. + * negative. */ - public static Angle computeRowLatitude(int row, Angle delta, Angle origin) - { - if (delta == null || origin == null) - { + public static Angle computeRowLatitude(int row, Angle delta, Angle origin) { + if (delta == null || origin == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (row < 0) - { + if (row < 0) { String msg = Logging.getMessage("generic.RowIndexOutOfRange", row); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (delta.degrees <= 0d) - { + if (delta.degrees <= 0d) { String message = Logging.getMessage("generic.DeltaAngleOutOfRange", delta); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -495,31 +467,27 @@ public static Angle computeRowLatitude(int row, Angle delta, Angle origin) * Determines the minimum longitude of a column in the global tile grid corresponding to a specified grid interval. * * @param column the row index of the row in question - * @param delta the grid interval + * @param delta the grid interval * @param origin the origin of the grid * * @return the minimum longitude of the tile corresponding to the specified column * * @throws IllegalArgumentException if the grid interval (delta) is null or zero or the column index is - * negative. + * negative. */ - public static Angle computeColumnLongitude(int column, Angle delta, Angle origin) - { - if (delta == null || origin == null) - { + public static Angle computeColumnLongitude(int column, Angle delta, Angle origin) { + if (delta == null || origin == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (column < 0) - { + if (column < 0) { String msg = Logging.getMessage("generic.ColumnIndexOutOfRange", column); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (delta.degrees <= 0d) - { + if (delta.degrees <= 0d) { String message = Logging.getMessage("generic.DeltaAngleOutOfRange", delta); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -529,13 +497,11 @@ public static Angle computeColumnLongitude(int column, Angle delta, Angle origin return Angle.fromDegrees(lonDegrees); } - public double getPriority() - { + public double getPriority() { return priority; } - public void setPriority(double priority) - { + public void setPriority(double priority) { this.priority = priority; } } diff --git a/src/gov/nasa/worldwind/util/TileKey.java b/src/gov/nasa/worldwind/util/TileKey.java index b1f770283c..3306fbe447 100644 --- a/src/gov/nasa/worldwind/util/TileKey.java +++ b/src/gov/nasa/worldwind/util/TileKey.java @@ -11,8 +11,8 @@ * @author tag * @version $Id: TileKey.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TileKey implements Comparable -{ +public class TileKey implements Comparable { + private final int level; private final int row; private final int col; @@ -25,12 +25,10 @@ public class TileKey implements Comparable * @param col Tile col. * @param cacheName Cache name. * @throws IllegalArgumentException if level, row or column is negative or if - * cacheName is null or empty + * cacheName is null or empty */ - public TileKey(int level, int row, int col, String cacheName) - { - if (level < 0) - { + public TileKey(int level, int row, int col, String cacheName) { + if (level < 0) { String msg = Logging.getMessage("TileKey.levelIsLessThanZero"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -47,8 +45,7 @@ public TileKey(int level, int row, int col, String cacheName) // Logging.logger().severe(msg); // throw new IllegalArgumentException(msg); // } - if (cacheName == null || cacheName.length() < 1) - { + if (cacheName == null || cacheName.length() < 1) { String msg = Logging.getMessage("TileKey.cacheNameIsNullOrEmpty"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -67,16 +64,13 @@ public TileKey(int level, int row, int col, String cacheName) * @param levelNumber Tile level number. * @throws IllegalArgumentException if any parameter is null */ - public TileKey(Angle latitude, Angle longitude, LevelSet levelSet, int levelNumber) - { - if (latitude == null || longitude == null) - { + public TileKey(Angle latitude, Angle longitude, LevelSet levelSet, int levelNumber) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (levelSet == null) - { + if (levelSet == null) { String msg = Logging.getMessage("nullValue.LevelSetIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -93,10 +87,8 @@ public TileKey(Angle latitude, Angle longitude, LevelSet levelSet, int levelNumb * @param tile The source tile. * @throws IllegalArgumentException if tile is null */ - public TileKey(Tile tile) - { - if (tile == null) - { + public TileKey(Tile tile) { + if (tile == null) { String msg = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -108,28 +100,23 @@ public TileKey(Tile tile) this.hash = this.computeHash(); } - public int getLevelNumber() - { + public int getLevelNumber() { return level; } - public int getRow() - { + public int getRow() { return row; } - public int getColumn() - { + public int getColumn() { return col; } - public String getCacheName() - { + public String getCacheName() { return cacheName; } - private int computeHash() - { + private int computeHash() { int result; result = this.level; result = 29 * result + this.row; @@ -147,65 +134,72 @@ private int computeHash() * * @throws IllegalArgumentException if key is null */ - public final int compareTo(TileKey key) - { - if (key == null) - { + public final int compareTo(TileKey key) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // No need to compare Sectors because they are redundant with row and column - if (key.level == this.level && key.row == this.row && key.col == this.col) + if (key.level == this.level && key.row == this.row && key.col == this.col) { return 0; + } if (this.level < key.level) // Lower-res levels compare lower than higher-res + { return -1; - if (this.level > key.level) + } + if (this.level > key.level) { return 1; + } - if (this.row < key.row) + if (this.row < key.row) { return -1; - if (this.row > key.row) + } + if (this.row > key.row) { return 1; + } - if (this.col < key.col) + if (this.col < key.col) { return -1; + } return 1; // tile.col must be > this.col because equality was tested above } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final TileKey tileKey = (TileKey) o; - if (this.col != tileKey.col) + if (this.col != tileKey.col) { return false; - if (this.level != tileKey.level) + } + if (this.level != tileKey.level) { return false; + } //noinspection SimplifiableIfStatement - if (this.row != tileKey.row) + if (this.row != tileKey.row) { return false; + } return !(this.cacheName != null ? !this.cacheName.equals(tileKey.cacheName) : tileKey.cacheName != null); } @Override - public int hashCode() - { + public int hashCode() { return this.hash; } @Override - public String toString() - { + public String toString() { return this.cacheName + "/" + this.level + "/" + this.row + "/" + col; } } diff --git a/src/gov/nasa/worldwind/util/TileUrlBuilder.java b/src/gov/nasa/worldwind/util/TileUrlBuilder.java index b75a854993..1767738c77 100644 --- a/src/gov/nasa/worldwind/util/TileUrlBuilder.java +++ b/src/gov/nasa/worldwind/util/TileUrlBuilder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import java.net.URL; @@ -12,7 +11,7 @@ * @author lado * @version $Id: TileUrlBuilder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TileUrlBuilder -{ - public URL getURL(Tile tile, String imageFormat) throws java.net.MalformedURLException; +public interface TileUrlBuilder { + + public URL getURL(Tile tile, String imageFormat) throws java.net.MalformedURLException; } diff --git a/src/gov/nasa/worldwind/util/TimedExpirySupport.java b/src/gov/nasa/worldwind/util/TimedExpirySupport.java index 5714216893..bf42ea115f 100644 --- a/src/gov/nasa/worldwind/util/TimedExpirySupport.java +++ b/src/gov/nasa/worldwind/util/TimedExpirySupport.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.render.DrawContext; @@ -16,17 +15,18 @@ * * @version $Id: TimedExpirySupport.java 2065 2014-06-20 16:58:48Z dcollins $ */ -public class TimedExpirySupport -{ +public class TimedExpirySupport { + protected boolean expired = true; protected long expiryTime = -1L; protected long minExpiryTime; protected long maxExpiryTime; protected static Random rand = new Random(); - /** Constructs an instance with minimum expiry interval of 1 second and a max of 2 seconds. */ - public TimedExpirySupport() - { + /** + * Constructs an instance with minimum expiry interval of 1 second and a max of 2 seconds. + */ + public TimedExpirySupport() { this.minExpiryTime = 2000; this.maxExpiryTime = 3000; } @@ -38,8 +38,7 @@ public TimedExpirySupport() * @param minExpiryTime the minimum interval allowed to pass before expiration, in milliseconds. * @param maxExpiryTime the maximum interval allowed to pass before expiration, in milliseconds. */ - public TimedExpirySupport(long minExpiryTime, long maxExpiryTime) - { + public TimedExpirySupport(long minExpiryTime, long maxExpiryTime) { this.minExpiryTime = Math.max(minExpiryTime, 0); this.maxExpiryTime = Math.max(maxExpiryTime, 0); } @@ -49,8 +48,7 @@ public TimedExpirySupport(long minExpiryTime, long maxExpiryTime) * * @param expired true to indicate expired, false to indicate not expired. */ - public void setExpired(boolean expired) - { + public void setExpired(boolean expired) { this.expired = expired; } @@ -59,8 +57,7 @@ public void setExpired(boolean expired) * * @return the current expiration time, in milliseconds. */ - public long getExpiryTime() - { + public long getExpiryTime() { return this.expiryTime; } @@ -70,8 +67,7 @@ public long getExpiryTime() * * @param expiryTime the new expiration time, in milliseconds. */ - public void setExpiryTime(long expiryTime) - { + public void setExpiryTime(long expiryTime) { this.expiryTime = expiryTime; } @@ -82,8 +78,7 @@ public void setExpiryTime(long expiryTime) * @param minExpiryTime the minimum interval allowed to pass before expiration, in milliseconds. * @param maxExpiryTime the maximum interval allowed to pass before expiration, in milliseconds. */ - public void setExpiryTime(long minExpiryTime, long maxExpiryTime) - { + public void setExpiryTime(long minExpiryTime, long maxExpiryTime) { this.minExpiryTime = Math.max(minExpiryTime, 0); this.maxExpiryTime = Math.max(maxExpiryTime, 0); } @@ -93,8 +88,7 @@ public void setExpiryTime(long minExpiryTime, long maxExpiryTime) * * @return this timer's minimum expiry interval, in milliseconds. */ - public long getMinExpiryTime() - { + public long getMinExpiryTime() { return this.minExpiryTime; } @@ -103,8 +97,7 @@ public long getMinExpiryTime() * * @return this timer's maximum expiry interval, in milliseconds. */ - public long getMaxExpiryTime() - { + public long getMaxExpiryTime() { return this.maxExpiryTime; } @@ -117,14 +110,15 @@ public long getMaxExpiryTime() * * @throws IllegalArgumentException if the draw context is null. */ - public boolean isExpired(DrawContext dc) - { - if (this.expired) + public boolean isExpired(DrawContext dc) { + if (this.expired) { return true; + } long now = dc != null ? dc.getFrameTimeStamp() : System.currentTimeMillis(); - if (now >= this.expiryTime) + if (now >= this.expiryTime) { return true; + } return false; } @@ -133,12 +127,11 @@ public boolean isExpired(DrawContext dc) * Indicates whether this timer has expired. * * @param now the time to relate this timer's expiration time to. The timer is considered expired if this timer's - * expiry time is less than this value. + * expiry time is less than this value. * * @return true if this timer has expired relative to system time, otherwise false. */ - public boolean isExpired(long now) - { + public boolean isExpired(long now) { return this.expired || this.expiryTime < now; } @@ -149,17 +142,13 @@ public boolean isExpired(long now) * * @throws IllegalArgumentException if the draw context is null. */ - public void restart(DrawContext dc) - { - if (this.maxExpiryTime == 0 || this.maxExpiryTime < this.minExpiryTime) - { + public void restart(DrawContext dc) { + if (this.maxExpiryTime == 0 || this.maxExpiryTime < this.minExpiryTime) { this.expired = true; - } - else - { + } else { long now = dc != null ? dc.getFrameTimeStamp() : System.currentTimeMillis(); this.expiryTime = now + this.minExpiryTime - + rand.nextInt((int) (this.maxExpiryTime - this.minExpiryTime)); + + rand.nextInt((int) (this.maxExpiryTime - this.minExpiryTime)); this.expired = false; } } diff --git a/src/gov/nasa/worldwind/util/UnitsFormat.java b/src/gov/nasa/worldwind/util/UnitsFormat.java index 7b80ec11af..aa2446931d 100644 --- a/src/gov/nasa/worldwind/util/UnitsFormat.java +++ b/src/gov/nasa/worldwind/util/UnitsFormat.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.avlist.AVListImpl; @@ -18,8 +17,8 @@ * @author tag * @version $Id: UnitsFormat.java 2301 2014-09-06 00:34:45Z tgaskins $ */ -public class UnitsFormat extends AVListImpl -{ +public class UnitsFormat extends AVListImpl { + // Keys identifying unit systems and units public static final String IMPERIAL_SYSTEM = "gov.nasa.worldwind.units.ImperialSystem"; public static final String METRIC_SYSTEM = "gov.nasa.worldwind.units.MetricSystem"; @@ -98,8 +97,7 @@ public class UnitsFormat extends AVListImpl * Construct an instance that displays length in kilometers, area in square kilometers and angles in decimal * degrees. */ - public UnitsFormat() - { + public UnitsFormat() { this(UnitsFormat.KILOMETERS, UnitsFormat.SQUARE_KILOMETERS, false); } @@ -108,13 +106,12 @@ public UnitsFormat() * * @param lengthUnits the desired length units. Available length units are METERS, KILOMETERS, MILES, * NAUTICAL_MILES, YARDS and FEET. - * @param areaUnits the desired area units. Available area units are SQUARE_METERS, SQUARE_KILOMETERS, + * @param areaUnits the desired area units. Available area units are SQUARE_METERS, SQUARE_KILOMETERS, * HECTARE, ACRE, SQUARE_YARD and SQUARE_FEET. * * @throws IllegalArgumentException if either lengthUnits or areaUnits is null. */ - public UnitsFormat(String lengthUnits, String areaUnits) - { + public UnitsFormat(String lengthUnits, String areaUnits) { this(lengthUnits, areaUnits, false); } @@ -123,24 +120,21 @@ public UnitsFormat(String lengthUnits, String areaUnits) * * @param lengthUnits the desired length units. Available length units are METERS, KILOMETERS, MILES, * NAUTICAL_MILES, YARDS and FEET. - * @param areaUnits the desired area units. Available area units are SQUARE_METERS, SQUARE_KILOMETERS, + * @param areaUnits the desired area units. Available area units are SQUARE_METERS, SQUARE_KILOMETERS, * HECTARE, ACRE, SQUARE_YARD and SQUARE_FEET. - * @param showDMS true if the desired angle format is degrees-minutes-seconds, false if the format is decimal - * degrees. + * @param showDMS true if the desired angle format is degrees-minutes-seconds, false if the format is decimal + * degrees. * * @throws IllegalArgumentException if either lengthUnits or areaUnits is null. */ - public UnitsFormat(String lengthUnits, String areaUnits, boolean showDMS) - { - if (lengthUnits == null) - { + public UnitsFormat(String lengthUnits, String areaUnits, boolean showDMS) { + if (lengthUnits == null) { String msg = Logging.getMessage("nullValue.LengthUnit"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (areaUnits == null) - { + if (areaUnits == null) { String msg = Logging.getMessage("nullValue.AreaUnit"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -161,8 +155,7 @@ public UnitsFormat(String lengthUnits, String areaUnits, boolean showDMS) * establish labels other than the defaults. The default labels are drawn from the current message properties. The * recognized labels are those indicated by the "LABEL_" constants defined by this class or by its subclasses. */ - protected void setDefaultLabels() - { + protected void setDefaultLabels() { this.setLabel(LABEL_LATITUDE, Logging.getMessage(LABEL_LATITUDE)); this.setLabel(LABEL_LONGITUDE, Logging.getMessage(LABEL_LONGITUDE)); this.setLabel(LABEL_LATLON_LAT, Logging.getMessage(LABEL_LATLON_LAT)); @@ -183,8 +176,7 @@ protected void setDefaultLabels() * value types that have associated formats are indicated by the "FORMAT_" constants defined by this class or by its * subclasses. */ - protected void setDefaultFormats() - { + protected void setDefaultFormats() { this.setFormat(FORMAT_LENGTH, " %,12.1f %s"); this.setFormat(FORMAT_AREA, " %,12.1f %s"); this.setFormat(FORMAT_PITCH, " %9.2f\u00b0"); @@ -201,22 +193,19 @@ protected void setDefaultFormats() * labels. * * @param labelName a key identifying the label type. Available names are those indicated by the "LABEL_" constants - * defined by this class or by its subclasses - * @param label the label to use for the specified value type. + * defined by this class or by its subclasses + * @param label the label to use for the specified value type. * * @throws IllegalArgumentException if either the label or label name is null. */ - public void setLabel(String labelName, String label) - { - if (labelName == null) - { + public void setLabel(String labelName, String label) { + if (labelName == null) { String msg = Logging.getMessage("nullValue.LabelKey"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (label == null) - { + if (label == null) { String msg = Logging.getMessage("nullValue.Label"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -234,10 +223,8 @@ public void setLabel(String labelName, String label) * * @throws IllegalArgumentException if the label name is null. */ - public String getLabel(String labelName) - { - if (labelName == null) - { + public String getLabel(String labelName) { + if (labelName == null) { String msg = Logging.getMessage("nullValue.LabelKey"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -251,22 +238,19 @@ public String getLabel(String labelName) * formats. * * @param formatName a key identifying the value type that is to have the specified format. Available types are - * those indicated by the "FORMAT_" constants defined by this class or by its subclasses - * @param format the label to use for the specified value type. + * those indicated by the "FORMAT_" constants defined by this class or by its subclasses + * @param format the label to use for the specified value type. * * @throws IllegalArgumentException if either the format or format name are null. */ - public void setFormat(String formatName, String format) - { - if (formatName == null) - { + public void setFormat(String formatName, String format) { + if (formatName == null) { String msg = Logging.getMessage("nullValue.FormatKey"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (format == null) - { + if (format == null) { String msg = Logging.getMessage("nullValue.Format"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -284,10 +268,8 @@ public void setFormat(String formatName, String format) * * @throws IllegalArgumentException if the format name is null. */ - public String getFormat(String formatName) - { - if (formatName == null) - { + public String getFormat(String formatName) { + if (formatName == null) { String msg = Logging.getMessage("nullValue.FormatKey"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -301,8 +283,7 @@ public String getFormat(String formatName) * * @return true if angles are displayed in degrees-minutes seconds, false if they're displayed in decimal degrees. */ - public boolean isShowDMS() - { + public boolean isShowDMS() { return this.showDMS; } @@ -311,8 +292,7 @@ public boolean isShowDMS() * * @param showDMS true to display angles in degrees-minutes seconds, false to display them in decimal degrees. */ - public void setShowDMS(boolean showDMS) - { + public void setShowDMS(boolean showDMS) { this.showDMS = showDMS; } @@ -321,8 +301,7 @@ public void setShowDMS(boolean showDMS) * * @return the units symbol for the current length units. */ - public String getLengthUnitsSymbol() - { + public String getLengthUnitsSymbol() { return this.lengthUnitsSymbol; } @@ -330,10 +309,9 @@ public String getLengthUnitsSymbol() * Returns the current length units. * * @return the current length units. See {@link #UnitsFormat(String, String, boolean)} for the list of those - * available. + * available. */ - public String getLengthUnits() - { + public String getLengthUnits() { return this.lengthUnits; } @@ -342,14 +320,12 @@ public String getLengthUnits() * from meters to the desired units prior to formatting. * * @param lengthUnits the desired length units. See {@link #UnitsFormat(String, String, boolean)} for the list of - * those available. + * those available. * * @throws IllegalArgumentException if lengthUnits is null. */ - public void setLengthUnits(String lengthUnits) - { - if (lengthUnits == null) - { + public void setLengthUnits(String lengthUnits) { + if (lengthUnits == null) { String msg = Logging.getMessage("nullValue.LengthUnit"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -357,33 +333,22 @@ public void setLengthUnits(String lengthUnits) this.lengthUnits = lengthUnits; - if (lengthUnits.equals(UnitsFormat.KILOMETERS)) - { + if (lengthUnits.equals(UnitsFormat.KILOMETERS)) { this.lengthUnitsMultiplier = WWMath.METERS_TO_KILOMETERS; this.lengthUnitsSymbol = UnitsFormat.SYMBOL_KILOMETERS; - } - else if (lengthUnits.equals(UnitsFormat.MILES)) - { + } else if (lengthUnits.equals(UnitsFormat.MILES)) { this.lengthUnitsMultiplier = WWMath.METERS_TO_MILES; this.lengthUnitsSymbol = UnitsFormat.SYMBOL_MILES; - } - else if (lengthUnits.equals(UnitsFormat.NAUTICAL_MILES)) - { + } else if (lengthUnits.equals(UnitsFormat.NAUTICAL_MILES)) { this.lengthUnitsMultiplier = WWMath.METERS_TO_NAUTICAL_MILES; this.lengthUnitsSymbol = UnitsFormat.SYMBOL_NAUTICAL_MILES; - } - else if (lengthUnits.equals(UnitsFormat.YARDS)) - { + } else if (lengthUnits.equals(UnitsFormat.YARDS)) { this.lengthUnitsMultiplier = WWMath.METERS_TO_YARDS; this.lengthUnitsSymbol = UnitsFormat.SYMBOL_YARDS; - } - else if (lengthUnits.equals(UnitsFormat.FEET)) - { + } else if (lengthUnits.equals(UnitsFormat.FEET)) { this.lengthUnitsMultiplier = WWMath.METERS_TO_FEET; this.lengthUnitsSymbol = UnitsFormat.SYMBOL_FEET; - } - else - { + } else { this.lengthUnitsMultiplier = 1d; this.lengthUnitsSymbol = UnitsFormat.SYMBOL_METERS; } @@ -394,19 +359,16 @@ else if (lengthUnits.equals(UnitsFormat.FEET)) * * @return the conversion multiplier to convert meters to the current length units. */ - public double getLengthUnitsMultiplier() - { + public double getLengthUnitsMultiplier() { return this.lengthUnitsMultiplier; } /** - * Returns the units symbol for the current altitude units. Examples are "m" for meters and "Nm" for nautical - * miles. + * Returns the units symbol for the current altitude units. Examples are "m" for meters and "Nm" for nautical miles. * * @return the units symbol for the current altitude units. */ - public String getAltitudeUnitsSymbol() - { + public String getAltitudeUnitsSymbol() { return this.altitudeUnitsSymbol; } @@ -414,10 +376,9 @@ public String getAltitudeUnitsSymbol() * Returns the current altitude units. * * @return the current altitude units. See {@link #UnitsFormat(String, String, boolean)} for the list of those - * available. + * available. */ - public String getAltitudeUnits() - { + public String getAltitudeUnits() { return this.altitudeUnits; } @@ -426,14 +387,12 @@ public String getAltitudeUnits() * converted from meters to the desired units prior to formatting. * * @param altitudeUnits the desired altitude units. See {@link #UnitsFormat(String, String, boolean)} for the list - * of those available. + * of those available. * * @throws IllegalArgumentException if lengthUnits is null. */ - public void setAltitudeUnits(String altitudeUnits) - { - if (altitudeUnits == null) - { + public void setAltitudeUnits(String altitudeUnits) { + if (altitudeUnits == null) { String msg = Logging.getMessage("nullValue.AltitudeUnit"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -441,33 +400,22 @@ public void setAltitudeUnits(String altitudeUnits) this.altitudeUnits = altitudeUnits; - if (altitudeUnits.equals(UnitsFormat.KILOMETERS)) - { + if (altitudeUnits.equals(UnitsFormat.KILOMETERS)) { this.altitudeUnitsMultiplier = WWMath.METERS_TO_KILOMETERS; this.altitudeUnitsSymbol = UnitsFormat.SYMBOL_KILOMETERS; - } - else if (altitudeUnits.equals(UnitsFormat.MILES)) - { + } else if (altitudeUnits.equals(UnitsFormat.MILES)) { this.altitudeUnitsMultiplier = WWMath.METERS_TO_MILES; this.altitudeUnitsSymbol = UnitsFormat.SYMBOL_MILES; - } - else if (altitudeUnits.equals(UnitsFormat.NAUTICAL_MILES)) - { + } else if (altitudeUnits.equals(UnitsFormat.NAUTICAL_MILES)) { this.altitudeUnitsMultiplier = WWMath.METERS_TO_NAUTICAL_MILES; this.altitudeUnitsSymbol = UnitsFormat.SYMBOL_NAUTICAL_MILES; - } - else if (altitudeUnits.equals(UnitsFormat.YARDS)) - { + } else if (altitudeUnits.equals(UnitsFormat.YARDS)) { this.altitudeUnitsMultiplier = WWMath.METERS_TO_YARDS; this.altitudeUnitsSymbol = UnitsFormat.SYMBOL_YARDS; - } - else if (altitudeUnits.equals(UnitsFormat.FEET)) - { + } else if (altitudeUnits.equals(UnitsFormat.FEET)) { this.altitudeUnitsMultiplier = WWMath.METERS_TO_FEET; this.altitudeUnitsSymbol = UnitsFormat.SYMBOL_FEET; - } - else - { + } else { this.altitudeUnitsMultiplier = 1d; this.altitudeUnitsSymbol = UnitsFormat.SYMBOL_METERS; } @@ -478,8 +426,7 @@ else if (altitudeUnits.equals(UnitsFormat.FEET)) * * @return the conversion multiplier to convert meters to the current altitude units. */ - public double getAltitudeUnitsMultiplier() - { + public double getAltitudeUnitsMultiplier() { return this.altitudeUnitsMultiplier; } @@ -487,10 +434,9 @@ public double getAltitudeUnitsMultiplier() * Returns the current area units. * * @return the current area units. See {@link #UnitsFormat(String, String, boolean)} for the list of those - * available. + * available. */ - public String getAreaUnits() - { + public String getAreaUnits() { return this.areaUnits; } @@ -499,14 +445,12 @@ public String getAreaUnits() * from square meters to the desired units prior to formatting. * * @param areaUnits the desired length units. See {@link #UnitsFormat(String, String, boolean)} for the list of - * those available. + * those available. * * @throws IllegalArgumentException if areaUnits is null. */ - public void setAreaUnits(String areaUnits) - { - if (areaUnits == null) - { + public void setAreaUnits(String areaUnits) { + if (areaUnits == null) { String msg = Logging.getMessage("nullValue.AreaUnit"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -514,38 +458,25 @@ public void setAreaUnits(String areaUnits) this.areaUnits = areaUnits; - if (areaUnits.equals(UnitsFormat.SQUARE_KILOMETERS)) - { + if (areaUnits.equals(UnitsFormat.SQUARE_KILOMETERS)) { this.areaUnitsMultiplier = WWMath.SQUARE_METERS_TO_SQUARE_KILOMETERS; this.areaUnitsSymbol = UnitsFormat.SYMBOL_SQUARE_KILOMETERS; - } - else if (areaUnits.equals(UnitsFormat.SQUARE_MILES)) - { + } else if (areaUnits.equals(UnitsFormat.SQUARE_MILES)) { this.areaUnitsMultiplier = WWMath.SQUARE_METERS_TO_SQUARE_MILES; this.areaUnitsSymbol = UnitsFormat.SYMBOL_SQUARE_MILES; - } - else if (areaUnits.equals(UnitsFormat.HECTARE)) - { + } else if (areaUnits.equals(UnitsFormat.HECTARE)) { this.areaUnitsMultiplier = WWMath.SQUARE_METERS_TO_HECTARES; this.areaUnitsSymbol = UnitsFormat.SYMBOL_HECTARE; - } - else if (areaUnits.equals(UnitsFormat.ACRE)) - { + } else if (areaUnits.equals(UnitsFormat.ACRE)) { this.areaUnitsMultiplier = WWMath.SQUARE_METERS_TO_ACRES; this.areaUnitsSymbol = UnitsFormat.SYMBOL_ACRE; - } - else if (areaUnits.equals(UnitsFormat.SQUARE_YARDS)) - { + } else if (areaUnits.equals(UnitsFormat.SQUARE_YARDS)) { this.areaUnitsMultiplier = WWMath.SQUARE_METERS_TO_SQUARE_YARDS; this.areaUnitsSymbol = UnitsFormat.SYMBOL_SQUARE_YARDS; - } - else if (areaUnits.equals(UnitsFormat.SQUARE_FEET)) - { + } else if (areaUnits.equals(UnitsFormat.SQUARE_FEET)) { this.areaUnitsMultiplier = WWMath.SQUARE_METERS_TO_SQUARE_FEET; this.areaUnitsSymbol = UnitsFormat.SYMBOL_SQUARE_FEET; - } - else - { + } else { this.areaUnitsMultiplier = 1d; this.areaUnitsSymbol = UnitsFormat.SYMBOL_SQUARE_METERS; } @@ -556,8 +487,7 @@ else if (areaUnits.equals(UnitsFormat.SQUARE_FEET)) * * @return the conversion multiplier to convert square meters to the current area units. */ - public double getAreaUnitsMultiplier() - { + public double getAreaUnitsMultiplier() { return this.areaUnitsMultiplier; } @@ -567,8 +497,7 @@ public double getAreaUnitsMultiplier() * * @return the units symbol for the current area units. */ - public String getAreaUnitsSymbol() - { + public String getAreaUnitsSymbol() { return this.areaUnitsSymbol; } @@ -581,23 +510,18 @@ public String getAreaUnitsSymbol() * * @throws IllegalArgumentException if unitsSystem is null. */ - public void setUnitsSystem(String unitsSystem) - { - if (unitsSystem == null) - { + public void setUnitsSystem(String unitsSystem) { + if (unitsSystem == null) { String msg = Logging.getMessage("nullValue.UnitsSystem"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (unitsSystem.equals(UnitsFormat.IMPERIAL_SYSTEM)) - { + if (unitsSystem.equals(UnitsFormat.IMPERIAL_SYSTEM)) { this.setLengthUnits(UnitsFormat.MILES); this.setAltitudeUnits(UnitsFormat.MILES); this.setAreaUnits(UnitsFormat.SQUARE_MILES); - } - else - { + } else { this.setLengthUnits(UnitsFormat.KILOMETERS); this.setAltitudeUnits(UnitsFormat.KILOMETERS); this.setAreaUnits(UnitsFormat.SQUARE_KILOMETERS); @@ -610,13 +534,13 @@ public void setUnitsSystem(String unitsSystem) * * @return the current units system for lengths. */ - public String getLengthUnitsSystem() - { + public String getLengthUnitsSystem() { if (this.getLengthUnits().equals(UnitsFormat.METERS) - || this.getLengthUnits().equals(UnitsFormat.KILOMETERS)) + || this.getLengthUnits().equals(UnitsFormat.KILOMETERS)) { return UnitsFormat.METRIC_SYSTEM; - else + } else { return UnitsFormat.IMPERIAL_SYSTEM; + } } /** @@ -625,15 +549,14 @@ public String getLengthUnitsSystem() * * @return the current units system for areas. */ - public String getAreaUnitsSystem() - { + public String getAreaUnitsSystem() { if (this.getAreaUnits().equals(UnitsFormat.SQUARE_METERS) - || this.getAreaUnits().equals(UnitsFormat.SQUARE_KILOMETERS) - || this.getAreaUnits().equals(UnitsFormat.HECTARE) - ) + || this.getAreaUnits().equals(UnitsFormat.SQUARE_KILOMETERS) + || this.getAreaUnits().equals(UnitsFormat.HECTARE)) { return UnitsFormat.METRIC_SYSTEM; - else + } else { return UnitsFormat.IMPERIAL_SYSTEM; + } } /** @@ -647,10 +570,8 @@ public String getAreaUnitsSystem() * * @throws IllegalArgumentException if the angle is null. */ - public String latitudeNL(Angle angle) - { - if (angle == null) - { + public String latitudeNL(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -670,10 +591,8 @@ public String latitudeNL(Angle angle) * * @throws IllegalArgumentException if the angle is null. */ - public String latitude(Angle angle) - { - if (angle == null) - { + public String latitude(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -691,10 +610,8 @@ public String latitude(Angle angle) * * @return a string containing the formatted angle and ending with the new-line character. */ - public String longitudeNL(Angle angle) - { - if (angle == null) - { + public String longitudeNL(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -714,10 +631,8 @@ public String longitudeNL(Angle angle) * * @throws IllegalArgumentException if the angle is null. */ - public String longitude(Angle angle) - { - if (angle == null) - { + public String longitude(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -737,8 +652,7 @@ public String longitude(Angle angle) * * @throws IllegalArgumentException if the angle is null. */ - public String headingNL(Angle angle) - { + public String headingNL(Angle angle) { return this.angleNL(this.getLabel(LABEL_HEADING), angle); } @@ -753,10 +667,8 @@ public String headingNL(Angle angle) * * @throws IllegalArgumentException if the angle is null. */ - public String heading(Angle angle) - { - if (angle == null) - { + public String heading(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -775,8 +687,7 @@ public String heading(Angle angle) * * @return a string containing the formatted angle and ending with the new-line character. */ - public String headingNL(double heading) - { + public String headingNL(double heading) { return this.heading(heading) + NL; } @@ -790,16 +701,14 @@ public String headingNL(double heading) * * @return a string containing the formatted angle. */ - public String heading(double heading) - { + public String heading(double heading) { return String.format(this.getLabel(LABEL_HEADING) + this.getFormat(FORMAT_HEADING), heading); } /** * Format angles of latitude and longitude according to the current angle format, and append a new-line character. *

          - * The values are formatted using the current {@link #LABEL_LATLON_LAT}, {@link #LABEL_LATLON_LON} and angle - * format. + * The values are formatted using the current {@link #LABEL_LATLON_LAT}, {@link #LABEL_LATLON_LON} and angle format. * * @param latlon the angles to format. * @@ -807,10 +716,8 @@ public String heading(double heading) * * @throws IllegalArgumentException if latlon is null. */ - public String latLonNL(LatLon latlon) - { - if (latlon == null) - { + public String latLonNL(LatLon latlon) { + if (latlon == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -822,8 +729,7 @@ public String latLonNL(LatLon latlon) /** * Format angles of latitude and longitude according to the current angle format. *

          - * The values are formatted using the current {@link #LABEL_LATLON_LAT}, {@link #LABEL_LATLON_LON} and angle - * format. + * The values are formatted using the current {@link #LABEL_LATLON_LAT}, {@link #LABEL_LATLON_LON} and angle format. * * @param latlon the angles to format. * @@ -831,17 +737,15 @@ public String latLonNL(LatLon latlon) * * @throws IllegalArgumentException if latlon is null. */ - public String latLon(LatLon latlon) - { - if (latlon == null) - { + public String latLon(LatLon latlon) { + if (latlon == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } return String.format("%s %s", this.angle(this.getLabel(LABEL_LATLON_LAT), latlon.getLatitude()), - this.angle(this.getLabel(LABEL_LATLON_LON), latlon.getLongitude())).trim(); + this.angle(this.getLabel(LABEL_LATLON_LON), latlon.getLongitude())).trim(); } /** @@ -853,10 +757,8 @@ public String latLon(LatLon latlon) * * @throws IllegalArgumentException if latlon is null. */ - public String latLon2NL(LatLon latlon) - { - if (latlon == null) - { + public String latLon2NL(LatLon latlon) { + if (latlon == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -875,10 +777,8 @@ public String latLon2NL(LatLon latlon) * * @throws IllegalArgumentException if latlon is null. */ - public String latLon2(LatLon latlon) - { - if (latlon == null) - { + public String latLon2(LatLon latlon) { + if (latlon == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -894,21 +794,18 @@ public String latLon2(LatLon latlon) } /** - * Format an angle according to the current angle format. Prepend a specified label and append a new-line - * character. + * Format an angle according to the current angle format. Prepend a specified label and append a new-line character. * * @param label a label to prepend to the formatted angle. May be null to indicate no label. * @param angle the angle to format. * * @return a string containing the formatted angle prepended with the specified label and ending with the new-line - * character. + * character. * * @throws IllegalArgumentException if the angle is null. */ - public String angleNL(String label, Angle angle) - { - if (angle == null) - { + public String angleNL(String label, Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -927,20 +824,19 @@ public String angleNL(String label, Angle angle) * * @throws IllegalArgumentException if the angle is null. */ - public String angle(String label, Angle angle) - { - if (angle == null) - { + public String angle(String label, Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } String s; - if (this.isShowDMS()) + if (this.isShowDMS()) { s = String.format("%s", angle.toFormattedDMSString()).trim(); - else + } else { s = String.format(this.getFormat(FORMAT_DECIMAL_DEGREES), angle.degrees).trim(); + } return label != null ? label + " " + s : s; } @@ -955,8 +851,7 @@ public String angle(String label, Angle angle) * * @return a string containing the formatted eye altitude and ending with the new-line character. */ - public String eyeAltitudeNL(double metersAltitude) - { + public String eyeAltitudeNL(double metersAltitude) { return this.eyeAltitude(metersAltitude) + NL; } @@ -970,16 +865,16 @@ public String eyeAltitudeNL(double metersAltitude) * * @return a string containing the formatted eye altitude. */ - public String eyeAltitude(double metersAltitude) - { - if (this.getFormat(FORMAT_EYE_ALTITUDE).contains("f")) + public String eyeAltitude(double metersAltitude) { + if (this.getFormat(FORMAT_EYE_ALTITUDE).contains("f")) { return String.format(this.getLabel(LABEL_EYE_ALTITUDE) + this.getFormat(FORMAT_EYE_ALTITUDE), - metersAltitude * this.getAltitudeUnitsMultiplier(), - this.getAltitudeUnitsSymbol()); - else + metersAltitude * this.getAltitudeUnitsMultiplier(), + this.getAltitudeUnitsSymbol()); + } else { return String.format(this.getLabel(LABEL_EYE_ALTITUDE) + this.getFormat(FORMAT_EYE_ALTITUDE), - (int) Math.round(metersAltitude * this.getAltitudeUnitsMultiplier()), - this.getAltitudeUnitsSymbol()); + (int) Math.round(metersAltitude * this.getAltitudeUnitsMultiplier()), + this.getAltitudeUnitsSymbol()); + } } /** @@ -992,8 +887,7 @@ public String eyeAltitude(double metersAltitude) * * @return a string containing the formatted angle and ending with the new-line character. */ - public String pitchNL(double pitch) - { + public String pitchNL(double pitch) { return this.pitch(pitch) + NL; } @@ -1007,8 +901,7 @@ public String pitchNL(double pitch) * * @return a string containing the formatted angle. */ - public String pitch(double pitch) - { + public String pitch(double pitch) { return String.format(this.getLabel(LABEL_PITCH) + this.getFormat(FORMAT_PITCH), pitch); } @@ -1021,8 +914,7 @@ public String pitch(double pitch) * * @return the formatted UTM zone ending with a new-line character. */ - public String utmZoneNL(int zone) - { + public String utmZoneNL(int zone) { return this.utmZone(zone) + NL; } @@ -1035,8 +927,7 @@ public String utmZoneNL(int zone) * * @return the formatted UTM zone. */ - public String utmZone(int zone) - { + public String utmZone(int zone) { return String.format(this.getLabel(LABEL_UTM_ZONE) + " %2d", zone); } @@ -1051,8 +942,7 @@ public String utmZone(int zone) * * @return the formatted UTM northing ending with a new-line character. */ - public String utmNorthingNL(double northing) - { + public String utmNorthingNL(double northing) { return this.utmNorthing(northing) + NL; } @@ -1067,8 +957,7 @@ public String utmNorthingNL(double northing) * * @return the formatted UTM northing. */ - public String utmNorthing(double northing) - { + public String utmNorthing(double northing) { return String.format(this.getLabel(LABEL_UTM_NORTHING) + this.getFormat(FORMAT_UTM_NORTHING), northing); } @@ -1083,8 +972,7 @@ public String utmNorthing(double northing) * * @return the formatted UTM easting ending with a new-line character. */ - public String utmEastingNL(double easting) - { + public String utmEastingNL(double easting) { return this.utmEasting(easting) + NL; } @@ -1099,8 +987,7 @@ public String utmEastingNL(double easting) * * @return the formatted UTM easting. */ - public String utmEasting(double easting) - { + public String utmEasting(double easting) { return String.format(this.getLabel(LABEL_UTM_EASTING) + this.getFormat(FORMAT_UTM_EASTING), easting); } @@ -1108,13 +995,12 @@ public String utmEasting(double easting) * Format a terrain height value according to the current configuration and append a new-line character. See {@link * #terrainHeight(double, double)} for a description of the formatting. * - * @param metersElevation the terrain height in meters. + * @param metersElevation the terrain height in meters. * @param verticalExaggeration the vertical exaggeration to apply to the terrain height. * * @return the formatted terrain height ending with a new-line character. */ - public String terrainHeightNL(double metersElevation, double verticalExaggeration) - { + public String terrainHeightNL(double metersElevation, double verticalExaggeration) { return this.terrainHeight(metersElevation, verticalExaggeration) + NL; } @@ -1130,65 +1016,59 @@ public String terrainHeightNL(double metersElevation, double verticalExaggeratio * components are always passed to the internal formatter in the order: vertical exaggeration, terrain height, units * symbol. * - * @param metersElevation the terrain height in meters. + * @param metersElevation the terrain height in meters. * @param verticalExaggeration the vertical exaggeration to apply to the terrain height. * * @return the formatted terrain height ending with a new-line character. */ - public String terrainHeight(double metersElevation, double verticalExaggeration) - { + public String terrainHeight(double metersElevation, double verticalExaggeration) { double multiplier; String symbol; - if (this.getLengthUnitsSystem().equals(UnitsFormat.METRIC_SYSTEM)) - { + if (this.getLengthUnitsSystem().equals(UnitsFormat.METRIC_SYSTEM)) { multiplier = 1d; symbol = UnitsFormat.SYMBOL_METERS; - } - else - { + } else { multiplier = WWMath.METERS_TO_FEET; symbol = UnitsFormat.SYMBOL_FEET; } return String.format(this.getLabel(LABEL_TERRAIN_HEIGHT) + getFormat(FORMAT_TERRAIN_HEIGHT), - verticalExaggeration, (int) Math.round((metersElevation / verticalExaggeration) * multiplier), symbol); + verticalExaggeration, (int) Math.round((metersElevation / verticalExaggeration) * multiplier), symbol); } /** * Format a length according to the current length configuration. Prepend a specified label and append a new-line * character. *

          - * The value is formatted using the current {@link #FORMAT_LENGTH} and length units symbol, and is converted to the + * The value is formatted using the current {@link #FORMAT_LENGTH} and length units symbol, and is converted to the * current length units prior to formatting. The default length format is " %,12.1f %s", where the %s specifier * stands for the units symbol. * - * @param label the label to prepend to the formatted length. May be null to indicate no label. + * @param label the label to prepend to the formatted length. May be null to indicate no label. * @param meters the length to format, in meters. * * @return the formatted length with the specified label prepended and a new-line character appended. */ - public String lengthNL(String label, double meters) - { + public String lengthNL(String label, double meters) { return this.length(label, meters) + NL; } /** * Format a length according to the current length configuration. Prepend a specified label. *

          - * The value is formatted using the current {@link #FORMAT_LENGTH} and length units symbol, and is converted to the + * The value is formatted using the current {@link #FORMAT_LENGTH} and length units symbol, and is converted to the * current length units prior to formatting. The default length format is " %,12.1f %s", where the %s specifier * stands for the units symbol. * - * @param label the label to prepend to the formatted length. May be null to indicate no label. + * @param label the label to prepend to the formatted length. May be null to indicate no label. * @param meters the length to format, in meters. * * @return the formatted length with the specified label prepended. */ - public String length(String label, double meters) - { + public String length(String label, double meters) { String s = String.format(this.getFormat(FORMAT_LENGTH), meters * this.getLengthUnitsMultiplier(), - this.getLengthUnitsSymbol()).trim(); + this.getLengthUnitsSymbol()).trim(); return label != null ? label + " " + s : s; } @@ -1197,36 +1077,34 @@ public String length(String label, double meters) * Format an area value according to the current length configuration. Prepend a specified label and append a * new-line character. *

          - * The value is formatted using the current {@link #FORMAT_AREA} and area units symbol, and is converted to the + * The value is formatted using the current {@link #FORMAT_AREA} and area units symbol, and is converted to the * current area units prior to formatting. The default area format is " %,12.1f %s", where the %s specifier stands * for the units symbol. * - * @param label the label to prepend to the formatted length. May be null to indicate no label. + * @param label the label to prepend to the formatted length. May be null to indicate no label. * @param squareMeters the area value to format, in square meters. * * @return the formatted area with the specified label prepended and a new-line character appended. */ - public String areaNL(String label, double squareMeters) - { + public String areaNL(String label, double squareMeters) { return this.area(label, squareMeters) + NL; } /** * Format an area value according to the current length configuration and prepend a specified label. *

          - * The value is formatted using the current {@link #FORMAT_AREA} and area units symbol, and is converted to the + * The value is formatted using the current {@link #FORMAT_AREA} and area units symbol, and is converted to the * current area units prior to formatting. The default area format is " %,12.1f %s", where the %s specifier stands * for the units symbol. * - * @param label the label to prepend to the formatted length. May be null to indicate no label. + * @param label the label to prepend to the formatted length. May be null to indicate no label. * @param squareMeters the area value to format, in square meters. * * @return the formatted area with the specified label prepended. */ - public String area(String label, double squareMeters) - { + public String area(String label, double squareMeters) { String s = String.format(this.getFormat(FORMAT_AREA), squareMeters * this.getAreaUnitsMultiplier(), - this.getAreaUnitsSymbol()).trim(); + this.getAreaUnitsSymbol()).trim(); return label != null ? label + " " + s : s; } diff --git a/src/gov/nasa/worldwind/util/VecBuffer.java b/src/gov/nasa/worldwind/util/VecBuffer.java index 673205e7a2..627b4d632a 100644 --- a/src/gov/nasa/worldwind/util/VecBuffer.java +++ b/src/gov/nasa/worldwind/util/VecBuffer.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: VecBuffer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VecBuffer -{ +public class VecBuffer { + protected int coordsPerVec; protected BufferWrapper buffer; @@ -30,21 +30,18 @@ public class VecBuffer * Constructs a new VecBuffer with the specified vector size, and backing BufferWrapper. * * @param coordsPerVec the number of coordinates per logical vector. - * @param buffer the backing BufferWrapper. + * @param buffer the backing BufferWrapper. * * @throws IllegalArgumentException if coordsPerElem is 0 or negative, or if the buffer is null. */ - public VecBuffer(int coordsPerVec, BufferWrapper buffer) - { - if (coordsPerVec < 1) - { + public VecBuffer(int coordsPerVec, BufferWrapper buffer) { + if (coordsPerVec < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "coordsPerVec < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -61,8 +58,7 @@ public VecBuffer(int coordsPerVec, BufferWrapper buffer) * * @return the empty VecBuffer. */ - public static VecBuffer emptyVecBuffer(int coordsPerVec) - { + public static VecBuffer emptyVecBuffer(int coordsPerVec) { return new VecBuffer(coordsPerVec, BufferWrapper.emptyBufferWrapper()); } @@ -71,8 +67,7 @@ public static VecBuffer emptyVecBuffer(int coordsPerVec) * * @return the cardinality of a logical vector element. */ - public int getCoordsPerVec() - { + public int getCoordsPerVec() { return this.coordsPerVec; } @@ -81,8 +76,7 @@ public int getCoordsPerVec() * * @return the size of this VecBuffer, in units of logical vectors. */ - public int getSize() - { + public int getSize() { return this.buffer.length() / this.coordsPerVec; } @@ -91,8 +85,7 @@ public int getSize() * * @return the backing buffer. */ - public BufferWrapper getBufferWrapper() - { + public BufferWrapper getBufferWrapper() { return this.buffer; } @@ -102,23 +95,20 @@ public BufferWrapper getBufferWrapper() * only the specified portion of the vector element is returned. * * @param position the logical vector position. - * @param array the destination array. + * @param array the destination array. * * @return an array of vector elements. * * @throws IllegalArgumentException if the position is out of range, or if the array is null. */ - public double[] get(int position, double[] array) - { - if (position < 0 || position >= this.getSize()) - { + public double[] get(int position, double[] array) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (array == null) - { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -126,8 +116,9 @@ public double[] get(int position, double[] array) int index = this.indexFromVectorPosition(position); int length = array.length; - if (length > this.coordsPerVec) + if (length > this.coordsPerVec) { length = this.coordsPerVec; + } this.buffer.getDouble(index, array, 0, length); @@ -140,23 +131,20 @@ public double[] get(int position, double[] array) * only the specified portion of the vector element is returned. * * @param position the logical vector position. - * @param array the destination array. + * @param array the destination array. * * @return an array of vector elements. * * @throws IllegalArgumentException if the position is out of range, or if the array is null. */ - public float[] getFloat(int position, float[] array) - { - if (position < 0 || position >= this.getSize()) - { + public float[] getFloat(int position, float[] array) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (array == null) - { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -164,8 +152,9 @@ public float[] getFloat(int position, float[] array) int index = this.indexFromVectorPosition(position); int length = array.length; - if (length > this.coordsPerVec) + if (length > this.coordsPerVec) { length = this.coordsPerVec; + } this.buffer.getFloat(index, array, 0, length); @@ -178,21 +167,18 @@ public float[] getFloat(int position, float[] array) * only the specified portion of the vector element is set. * * @param position the logical vector position. - * @param array the source array. + * @param array the source array. * * @throws IllegalArgumentException if the position is out of range, or if the array is null. */ - public void put(int position, double[] array) - { - if (position < 0 || position >= this.getSize()) - { + public void put(int position, double[] array) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (array == null) - { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -200,8 +186,9 @@ public void put(int position, double[] array) int index = this.indexFromVectorPosition(position); int length = array.length; - if (length > this.coordsPerVec) + if (length > this.coordsPerVec) { length = this.coordsPerVec; + } this.buffer.putDouble(index, array, 0, length); } @@ -212,21 +199,18 @@ public void put(int position, double[] array) * only the specified portion of the vector element is set. * * @param position the logical vector position. - * @param array the source array. + * @param array the source array. * * @throws IllegalArgumentException if the position is out of range, or if the array is null. */ - public void putFloat(int position, float[] array) - { - if (position < 0 || position >= this.getSize()) - { + public void putFloat(int position, float[] array) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (array == null) - { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -234,8 +218,9 @@ public void putFloat(int position, float[] array) int index = this.indexFromVectorPosition(position); int length = array.length; - if (length > this.coordsPerVec) + if (length > this.coordsPerVec) { length = this.coordsPerVec; + } this.buffer.putFloat(index, array, 0, length); } @@ -247,24 +232,21 @@ public void putFloat(int position, float[] array) * packed into the array, starting at index 0. * * @param position the starting logical vector position. - * @param array the source array. - * @param count the number of logical arrays to set. + * @param array the source array. + * @param count the number of logical arrays to set. * * @throws IllegalArgumentException if the position is out of range, if the array is null, or if the array has - * insufficient length. + * insufficient length. */ - public void putAll(int position, double[] array, int count) - { - if (position < 0 || position + count > this.getSize()) - { + public void putAll(int position, double[] array, int count) { + if (position < 0 || position + count > this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", - "position < 0 or position + count >= size"); + "position < 0 or position + count >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (array == null) - { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -273,8 +255,7 @@ public void putAll(int position, double[] array, int count) int index = this.indexFromVectorPosition(position); int length = this.indexFromVectorPosition(count); - if (array.length < length) - { + if (array.length < length) { String message = Logging.getMessage("generic.ArrayInvalidLength", array.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -289,14 +270,12 @@ public void putAll(int position, double[] array, int count) * this buffer are reflected in the new buffer, and visa versa. * * @param position the new buffer's staring position, in logical vectors. - * @param size the new buffer's size, in logical vectors. + * @param size the new buffer's size, in logical vectors. * * @return a subsequence of this buffer. */ - public VecBuffer getSubBuffer(int position, int size) - { - if (position < 0 || position >= this.getSize()) - { + public VecBuffer getSubBuffer(int position, int size) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -315,23 +294,19 @@ public VecBuffer getSubBuffer(int position, int size) * must have the same logical vector size as this buffer (coordsPerVec must be equivalent). * * @param position the starting vector position to set. - * @param buffer the input buffer. + * @param buffer the input buffer. * * @throws IllegalArgumentException if the position is out of range, if the buffer is null or incompatible, or if - * this buffer has insufficient length to store the sub-buffer at the specified - * position. + * this buffer has insufficient length to store the sub-buffer at the specified position. */ - public void putSubBuffer(int position, VecBuffer buffer) - { - if (position < 0 || position >= this.getSize()) - { + public void putSubBuffer(int position, VecBuffer buffer) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -346,42 +321,36 @@ public void putSubBuffer(int position, VecBuffer buffer) * the same logical vector size as this buffer (coordsPerVec must be equivalent). * * @param position the starting vector position to set. - * @param buffer the input buffer. - * @param offset the vector position to start copying values from the specified buffer. - * @param size the number of vectors to read copy form the specified buffer. + * @param buffer the input buffer. + * @param offset the vector position to start copying values from the specified buffer. + * @param size the number of vectors to read copy form the specified buffer. * * @throws IllegalArgumentException if the position is out of range, if the buffer is null or incompatible, if this - * buffer has insufficient length to store the sub-buffer at the specified - * position, or if the specified offset and size define a range outside of the - * specified buffer. + * buffer has insufficient length to store the sub-buffer at the specified position, or if the specified offset and + * size define a range outside of the specified buffer. */ - public void putSubBuffer(int position, VecBuffer buffer, int offset, int size) - { - if (position < 0 || position >= this.getSize()) - { + public void putSubBuffer(int position, VecBuffer buffer, int offset, int size) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Not enough room in buffer. - if (buffer.getSize() < (offset + size)) - { + if (buffer.getSize() < (offset + size)) { String message = Logging.getMessage("generic.BufferOverflow", buffer.getSize(), size); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Buffer is incompatible. - if (this.coordsPerVec != buffer.coordsPerVec) - { + if (this.coordsPerVec != buffer.coordsPerVec) { String message = Logging.getMessage("generic.BufferIncompatible", buffer); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -389,8 +358,7 @@ public void putSubBuffer(int position, VecBuffer buffer, int offset, int size) // Buffer is too large. int sizeNeeded = position + size; - if (this.getSize() < sizeNeeded) - { + if (this.getSize() < sizeNeeded) { String message = Logging.getMessage("generic.BufferOverflow", this.getSize(), sizeNeeded); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -412,17 +380,14 @@ public void putSubBuffer(int position, VecBuffer buffer, int offset, int size) * * @throws IllegalArgumentException if the position is out of range, or if this buffer cannot store a Vec4. */ - public Vec4 getVector(int position) - { - if (position < 0 || position >= this.getSize()) - { + public Vec4 getVector(int position) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec != 2 && this.coordsPerVec != 3 && this.coordsPerVec != 4) - { + if (this.coordsPerVec != 2 && this.coordsPerVec != 3 && this.coordsPerVec != 4) { String message = Logging.getMessage("generic.BufferIncompatible", this); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -438,29 +403,25 @@ public Vec4 getVector(int position) * 3 or 4. * * @param position the logical vector position. - * @param vec the vector to set. + * @param vec the vector to set. * * @throws IllegalArgumentException if the position is out of range, if the vector is null, or if this buffer cannot - * store a Vec4. + * store a Vec4. */ - public void putVector(int position, Vec4 vec) - { - if (position < 0 || position >= this.getSize()) - { + public void putVector(int position, Vec4 vec) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vec == null) - { + if (vec == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec != 2 && this.coordsPerVec != 3 && this.coordsPerVec != 4) - { + if (this.coordsPerVec != 2 && this.coordsPerVec != 3 && this.coordsPerVec != 4) { String message = Logging.getMessage("generic.BufferIncompatible", this); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -481,17 +442,14 @@ public void putVector(int position, Vec4 vec) * * @throws IllegalArgumentException if the position is out of range, or if this buffer cannot store a LatLon. */ - public LatLon getLocation(int position) - { - if (position < 0 || position >= this.getSize()) - { + public LatLon getLocation(int position) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec < 2) - { + if (this.coordsPerVec < 2) { String message = Logging.getMessage("generic.BufferIncompatible", this); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -508,29 +466,25 @@ public LatLon getLocation(int position) * be at least 2. * * @param position the logical vector position. - * @param ll the geographic location to set. + * @param ll the geographic location to set. * * @throws IllegalArgumentException if the position is out of range, if the LatLon is null, or if this buffer cannot - * store a LatLon. + * store a LatLon. */ - public void putLocation(int position, LatLon ll) - { - if (position < 0 || position >= this.getSize()) - { + public void putLocation(int position, LatLon ll) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (ll == null) - { + if (ll == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec < 2) - { + if (this.coordsPerVec < 2) { String message = Logging.getMessage("generic.BufferIncompatible", this); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -553,17 +507,14 @@ public void putLocation(int position, LatLon ll) * * @throws IllegalArgumentException if the position is out of range, or if this buffer cannot store a Position. */ - public Position getPosition(int position) - { - if (position < 0 || position >= this.getSize()) - { + public Position getPosition(int position) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec < 2) - { + if (this.coordsPerVec < 2) { String message = Logging.getMessage("generic.BufferIncompatible", this); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -573,9 +524,9 @@ public Position getPosition(int position) this.get(position, compArray); return Position.fromDegrees( - compArray[1], - compArray[0], - (this.coordsPerVec > 2) ? compArray[2] : 0); + compArray[1], + compArray[0], + (this.coordsPerVec > 2) ? compArray[2] : 0); } /** @@ -583,29 +534,25 @@ public Position getPosition(int position) * must be at least 2. * * @param position the logical vector position. - * @param p the geographic Position to set. + * @param p the geographic Position to set. * * @throws IllegalArgumentException if the position is out of range, if the Position is null, or if this buffer - * cannot store a Position. + * cannot store a Position. */ - public void putPosition(int position, Position p) - { - if (position < 0 || position >= this.getSize()) - { + public void putPosition(int position, Position p) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (p == null) - { + if (p == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec < 2) - { + if (this.coordsPerVec < 2) { String message = Logging.getMessage("generic.BufferIncompatible", this); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -629,10 +576,8 @@ public void putPosition(int position, Position p) * * @return the new buffer, with the specified size. */ - public VecBuffer copyOf(int newSize) - { - if (newSize < this.getSize()) - { + public VecBuffer copyOf(int newSize) { + if (newSize < this.getSize()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -648,8 +593,7 @@ public VecBuffer copyOf(int newSize) * * @return iterator over this buffer's vectors, as double[] arrays. */ - public Iterable getCoords() - { + public Iterable getCoords() { return this.getCoords(this.coordsPerVec); } @@ -663,12 +607,9 @@ public Iterable getCoords() * * @return iterator over this buffer's vectors, as double[] arrays. */ - public Iterable getCoords(final int minCoordsPerVec) - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getCoords(final int minCoordsPerVec) { + return new Iterable() { + public Iterator iterator() { return new BasicIterator(new CoordAccessor(minCoordsPerVec)); } }; @@ -684,12 +625,9 @@ public Iterator iterator() * * @return reverse iterator over this buffer's vectors, as double[] arrays. */ - public Iterable getReverseCoords(final int minCoordsPerVec) - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getReverseCoords(final int minCoordsPerVec) { + return new Iterable() { + public Iterator iterator() { return new ReverseIterator(new CoordAccessor(minCoordsPerVec)); } }; @@ -705,17 +643,14 @@ public Iterator iterator() * * @throws IllegalArgumentException if the position is out of range, or if the iterable is null. */ - public void putCoords(int position, Iterable iterable) - { - if (position < 0 || position >= this.getSize()) - { + public void putCoords(int position, Iterable iterable) { + if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (iterable == null) - { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -723,12 +658,12 @@ public void putCoords(int position, Iterable iterable) int pos = position; - for (double[] coords : iterable) - { + for (double[] coords : iterable) { this.put(pos, coords); - if (++pos >= this.getSize()) + if (++pos >= this.getSize()) { break; + } } } @@ -737,12 +672,9 @@ public void putCoords(int position, Iterable iterable) * * @return iterator over this buffer's vectors, as Vec4 references. */ - public Iterable getVectors() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getVectors() { + return new Iterable() { + public Iterator iterator() { return new BasicIterator(new VectorAccessor()); } }; @@ -753,12 +685,9 @@ public Iterator iterator() * * @return reverse iterator over this buffer's vectors, as Vec4 references. */ - public Iterable getReverseVectors() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getReverseVectors() { + return new Iterable() { + public Iterator iterator() { return new ReverseIterator(new VectorAccessor()); } }; @@ -774,12 +703,10 @@ public Iterator iterator() * @param iterable iterator over the elements to set. * * @throws IllegalArgumentException if the position is out of range, if the iterable is null, or if this buffer - * cannot store a Vec4. + * cannot store a Vec4. */ - public void putVectors(int position, Iterable iterable) - { - if (iterable == null) - { + public void putVectors(int position, Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -787,12 +714,12 @@ public void putVectors(int position, Iterable iterable) int pos = position; - for (Vec4 vec : iterable) - { + for (Vec4 vec : iterable) { this.putVector(pos, vec); - if (++pos >= this.getSize()) + if (++pos >= this.getSize()) { break; + } } } @@ -801,12 +728,9 @@ public void putVectors(int position, Iterable iterable) * * @return iterator over this buffer's vectors, as LatLon locations. */ - public Iterable getLocations() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getLocations() { + return new Iterable() { + public Iterator iterator() { return new BasicIterator(new LocationAccessor()); } }; @@ -817,12 +741,9 @@ public Iterator iterator() * * @return reverse iterator over this buffer's vectors, as LatLon locations. */ - public Iterable getReverseLocations() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getReverseLocations() { + return new Iterable() { + public Iterator iterator() { return new ReverseIterator(new LocationAccessor()); } }; @@ -837,12 +758,10 @@ public Iterator iterator() * @param iterable iterator over the elements to set. * * @throws IllegalArgumentException if the position is out of range, if the iterable is null, or if this buffer - * cannot store a LatLon. + * cannot store a LatLon. */ - public void putLocations(int position, Iterable iterable) - { - if (iterable == null) - { + public void putLocations(int position, Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -850,12 +769,12 @@ public void putLocations(int position, Iterable iterable) int pos = position; - for (LatLon ll : iterable) - { + for (LatLon ll : iterable) { this.putLocation(pos, ll); - if (++pos >= this.getSize()) + if (++pos >= this.getSize()) { break; + } } } @@ -864,12 +783,9 @@ public void putLocations(int position, Iterable iterable) * * @return iterator over this buffer's vectors, as geographic Positions. */ - public Iterable getPositions() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getPositions() { + return new Iterable() { + public Iterator iterator() { return new BasicIterator(new PositionAccessor()); } }; @@ -880,12 +796,9 @@ public Iterator iterator() * * @return reverse iterator over this buffer's vectors, as geographic Positions. */ - public Iterable getReversePositions() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getReversePositions() { + return new Iterable() { + public Iterator iterator() { return new ReverseIterator(new PositionAccessor()); } }; @@ -900,12 +813,10 @@ public Iterator iterator() * @param iterable iterator over the elements to set. * * @throws IllegalArgumentException if the position is out of range, if the iterable is null, or if this buffer - * cannot store a LatLon. + * cannot store a LatLon. */ - public void putPositions(int position, Iterable iterable) - { - if (iterable == null) - { + public void putPositions(int position, Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -913,12 +824,12 @@ public void putPositions(int position, Iterable iterable) int pos = position; - for (Position p : iterable) - { + for (Position p : iterable) { this.putPosition(pos, p); - if (++pos >= this.getSize()) + if (++pos >= this.getSize()) { break; + } } } @@ -930,21 +841,18 @@ public void putPositions(int position, Iterable iterable) * @param dc the current {@link DrawContext}. * * @throws IllegalArgumentException if the DrawContext is null, or if this buffer is not compatible as a color - * buffer. + * buffer. */ - public void bindAsColorBuffer(DrawContext dc) - { - if (dc == null) - { + public void bindAsColorBuffer(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec != 3 && this.coordsPerVec != 4) - { + if (this.coordsPerVec != 3 && this.coordsPerVec != 4) { String message = Logging.getMessage("generic.ArgumentOutOfRange", - "coordinates per vertex = " + this.coordsPerVec); + "coordinates per vertex = " + this.coordsPerVec); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -961,21 +869,18 @@ public void bindAsColorBuffer(DrawContext dc) * @param dc the current {@link DrawContext}. * * @throws IllegalArgumentException if the DrawContext is null, or if this buffer is not compatible as a normal - * buffer. + * buffer. */ - public void bindAsNormalBuffer(DrawContext dc) - { - if (dc == null) - { + public void bindAsNormalBuffer(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec != 3) - { + if (this.coordsPerVec != 3) { String message = Logging.getMessage("generic.ArgumentOutOfRange", - "coordinates per vertex = " + this.coordsPerVec); + "coordinates per vertex = " + this.coordsPerVec); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -992,21 +897,18 @@ public void bindAsNormalBuffer(DrawContext dc) * @param dc the current DrawContext. * * @throws IllegalArgumentException if the DrawContext is null, or if this buffer is not compatible as a vertex - * buffer. + * buffer. */ - public void bindAsVertexBuffer(DrawContext dc) - { - if (dc == null) - { + public void bindAsVertexBuffer(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec != 2 && this.coordsPerVec != 3 && this.coordsPerVec != 4) - { + if (this.coordsPerVec != 2 && this.coordsPerVec != 3 && this.coordsPerVec != 4) { String message = Logging.getMessage("generic.ArgumentOutOfRange", - "coordinates per vertex = " + this.coordsPerVec); + "coordinates per vertex = " + this.coordsPerVec); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -1016,7 +918,7 @@ public void bindAsVertexBuffer(DrawContext dc) } /** - * Binds this buffer as the source of texture coordinates to use when rendering OpenGL primitives. The texture + * Binds this buffer as the source of texture coordinates to use when rendering OpenGL primitives. The texture * coordinate size is equal to coordsPerVertex, the texture coordinate type is equal to buffer's underlying * BufferWrapper GL type, the stride is 0, and the texture coordinate data itself is this buffer's backing NIO * Buffer. This buffer's vector size must be 1, 2, 3, or 4. @@ -1024,21 +926,18 @@ public void bindAsVertexBuffer(DrawContext dc) * @param dc the current DrawContext. * * @throws IllegalArgumentException if the DrawContext is null, or if this buffer is not compatible as a normal - * buffer. + * buffer. */ - public void bindAsTexCoordBuffer(DrawContext dc) - { - if (dc == null) - { + public void bindAsTexCoordBuffer(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.coordsPerVec != 1 && this.coordsPerVec != 2 && this.coordsPerVec != 3 && this.coordsPerVec != 4) - { + if (this.coordsPerVec != 1 && this.coordsPerVec != 2 && this.coordsPerVec != 3 && this.coordsPerVec != 4) { String message = Logging.getMessage("generic.ArgumentOutOfRange", - "coordinates per vertex = " + this.coordsPerVec); + "coordinates per vertex = " + this.coordsPerVec); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -1051,15 +950,13 @@ public void bindAsTexCoordBuffer(DrawContext dc) * Renders getSize() elements from the currently bounds OpenGL coordinate buffers, beginning with * element 0. The specified drawMode indicates which type of OpenGL primitives to render. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param drawMode the type of OpenGL primtives to render. * * @throws IllegalArgumentException if the DrawContext is null. */ - public void drawArrays(DrawContext dc, int drawMode) - { - if (dc == null) - { + public void drawArrays(DrawContext dc, int drawMode) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1075,8 +972,7 @@ public void drawArrays(DrawContext dc, int drawMode) * * @return the physical buffer index. */ - protected int indexFromVectorPosition(int position) - { + protected int indexFromVectorPosition(int position) { return this.coordsPerVec * position; } @@ -1087,133 +983,113 @@ protected int indexFromVectorPosition(int position) * * @return the vector position. */ - protected int vectorPositionFromIndex(int index) - { + protected int vectorPositionFromIndex(int index) { return index / this.coordsPerVec; } //**************************************************************// //******************** Iterators *****************************// //**************************************************************// + protected class BasicIterator implements Iterator { - protected class BasicIterator implements Iterator - { protected int position; protected final int size; protected ElementAccessor accessor; - public BasicIterator(ElementAccessor accessor) - { + public BasicIterator(ElementAccessor accessor) { this.position = -1; this.size = getSize(); this.accessor = accessor; } - public boolean hasNext() - { + public boolean hasNext() { return this.position < (this.size - 1); } - public T next() - { + public T next() { this.position++; - if (this.position < this.size) - { + if (this.position < this.size) { return this.accessor.getElement(this.position); - } - else - { + } else { throw new NoSuchElementException(); } } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } } - protected class ReverseIterator implements Iterator - { + protected class ReverseIterator implements Iterator { + protected int position; protected ElementAccessor accessor; - public ReverseIterator(ElementAccessor accessor) - { + public ReverseIterator(ElementAccessor accessor) { this.position = getSize(); this.accessor = accessor; } - public boolean hasNext() - { + public boolean hasNext() { return this.position > 0; } - public T next() - { + public T next() { this.position--; - if (this.position >= 0) - { + if (this.position >= 0) { return this.accessor.getElement(this.position); - } - else - { + } else { throw new NoSuchElementException(); } } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } } - protected interface ElementAccessor - { + protected interface ElementAccessor { + T getElement(int position); } - protected class CoordAccessor implements ElementAccessor - { + protected class CoordAccessor implements ElementAccessor { + private int numCoords; - public CoordAccessor(int minCoordsPerVec) - { + public CoordAccessor(int minCoordsPerVec) { this.numCoords = coordsPerVec; - if (this.numCoords < minCoordsPerVec) + if (this.numCoords < minCoordsPerVec) { this.numCoords = minCoordsPerVec; + } } - public double[] getElement(int position) - { + public double[] getElement(int position) { double[] compArray = new double[this.numCoords]; get(position, compArray); return compArray; } } - protected class VectorAccessor implements ElementAccessor - { - public Vec4 getElement(int position) - { + protected class VectorAccessor implements ElementAccessor { + + public Vec4 getElement(int position) { return getVector(position); } } - protected class LocationAccessor implements ElementAccessor - { - public LatLon getElement(int position) - { + protected class LocationAccessor implements ElementAccessor { + + public LatLon getElement(int position) { return getLocation(position); } } - protected class PositionAccessor implements ElementAccessor - { - public Position getElement(int position) - { + protected class PositionAccessor implements ElementAccessor { + + public Position getElement(int position) { return getPosition(position); } } diff --git a/src/gov/nasa/worldwind/util/VecBufferBlocks.java b/src/gov/nasa/worldwind/util/VecBufferBlocks.java index 3d3a0b134f..1f00dcbcf4 100644 --- a/src/gov/nasa/worldwind/util/VecBufferBlocks.java +++ b/src/gov/nasa/worldwind/util/VecBufferBlocks.java @@ -16,8 +16,8 @@ * @author dcollins * @version $Id: VecBufferBlocks.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VecBufferBlocks extends CompoundVecBuffer -{ +public class VecBufferBlocks extends CompoundVecBuffer { + protected int coordsPerVec; protected String dataType; protected ByteBuffer buffer; @@ -29,33 +29,29 @@ public class VecBufferBlocks extends CompoundVecBuffer * This assumes the buffer's position and limit are not changed by the caller for the lifetime of this instance. * * @param coordsPerVec the number of coordinates per logical vector. - * @param dataType the primitive data type. - * @param buffer the backing ByteBuffer. - * @param capacity the PackedCompoundVecBuffer's initial capacity, in number of sub-buffers. + * @param dataType the primitive data type. + * @param buffer the backing ByteBuffer. + * @param capacity the PackedCompoundVecBuffer's initial capacity, in number of sub-buffers. * * @throws IllegalArgumentException if the coordsPerVec is less than 1, if the dataType is null, if the buffer is - * null, or if the capacity is less than 1. + * null, or if the capacity is less than 1. */ - public VecBufferBlocks(int coordsPerVec, String dataType, ByteBuffer buffer, int capacity) - { + public VecBufferBlocks(int coordsPerVec, String dataType, ByteBuffer buffer, int capacity) { super(capacity); - if (coordsPerVec < 1) - { + if (coordsPerVec < 1) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dataType == null) - { + if (dataType == null) { String message = Logging.getMessage("nullValue.DataTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -73,19 +69,17 @@ public VecBufferBlocks(int coordsPerVec, String dataType, ByteBuffer buffer, int * position and limit are not changed by the caller for the lifetime of this instance. * * @param coordsPerVec the number of coordinates per logical vector. - * @param dataType the primitive data type. - * @param buffer the backing ByteBuffer. + * @param dataType the primitive data type. + * @param buffer the backing ByteBuffer. * * @throws IllegalArgumentException if the coordsPerVec is less than 1, if the dataType is null, or if the buffer is - * null. + * null. */ - public VecBufferBlocks(int coordsPerVec, String dataType, ByteBuffer buffer) - { + public VecBufferBlocks(int coordsPerVec, String dataType, ByteBuffer buffer) { this(coordsPerVec, dataType, buffer, DEFAULT_INITIAL_CAPACITY); } - protected VecBufferBlocks(VecBufferBlocks that, int beginIndex, int endIndex) - { + protected VecBufferBlocks(VecBufferBlocks that, int beginIndex, int endIndex) { super(that, beginIndex, endIndex); this.coordsPerVec = that.coordsPerVec; @@ -93,8 +87,7 @@ protected VecBufferBlocks(VecBufferBlocks that, int beginIndex, int endIndex) this.buffer = that.buffer; } - protected VecBufferBlocks(VecBufferBlocks that, int[] indices, int offset, int length) - { + protected VecBufferBlocks(VecBufferBlocks that, int[] indices, int offset, int length) { super(that, indices, offset, length); this.coordsPerVec = that.coordsPerVec; @@ -102,11 +95,11 @@ protected VecBufferBlocks(VecBufferBlocks that, int[] indices, int offset, int l this.buffer = that.buffer; } - /** {@inheritDoc} */ - public int subBufferSize(int index) - { - if (index < 0 || index >= this.count) - { + /** + * {@inheritDoc} + */ + public int subBufferSize(int index) { + if (index < 0 || index >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -115,9 +108,10 @@ public int subBufferSize(int index) return this.lengths.get(index) / WWBufferUtil.sizeOfPrimitiveType(this.dataType) / this.coordsPerVec; } - /** {@inheritDoc} */ - public int getCoordsPerVec() - { + /** + * {@inheritDoc} + */ + public int getCoordsPerVec() { return this.coordsPerVec; } @@ -126,8 +120,7 @@ public int getCoordsPerVec() * * @return this VecBufferBlocks' primitive data type. */ - public String getDataType() - { + public String getDataType() { return dataType; } @@ -136,8 +129,7 @@ public String getDataType() * * @return this VecBufferBlocks' backing ByteBuffer. */ - public ByteBuffer getBuffer() - { + public ByteBuffer getBuffer() { return buffer; } @@ -148,25 +140,21 @@ public ByteBuffer getBuffer() * and this buffer's primitive data type. * * @param beginPos the byte range's beginning position. - * @param endPos the byte range's ending position (inclusive). + * @param endPos the byte range's ending position (inclusive). * * @return the sub-buffer's index. * * @throws IllegalArgumentException if either the position are less than zero, if either position is greater than - * the backing buffer's capacity, or if the begin position is greater than the end - * position. + * the backing buffer's capacity, or if the begin position is greater than the end position. */ - public int addBlock(int beginPos, int endPos) - { - if (endPos < 0 || endPos > this.buffer.capacity()) - { + public int addBlock(int beginPos, int endPos) { + if (endPos < 0 || endPos > this.buffer.capacity()) { String message = Logging.getMessage("generic.indexOutOfRange", endPos); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (beginPos < 0 || beginPos > endPos) - { + if (beginPos < 0 || beginPos > endPos) { String message = Logging.getMessage("generic.indexOutOfRange", beginPos); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -178,23 +166,18 @@ public int addBlock(int beginPos, int endPos) //**************************************************************// //******************** Protected Interface *******************// //**************************************************************// - - protected VecBuffer createSubBuffer(int offsetInBytes, int lengthInBytes) - { + protected VecBuffer createSubBuffer(int offsetInBytes, int lengthInBytes) { VecBuffer subBuffer; // Save the buffer's current position and limit. int lim = this.buffer.limit(); int pos = this.buffer.position(); - try - { + try { this.buffer.limit(offsetInBytes + lengthInBytes); this.buffer.position(offsetInBytes); BufferWrapper slice = BufferWrapper.wrap(this.buffer, this.dataType); subBuffer = new VecBuffer(this.coordsPerVec, slice); - } - finally - { + } finally { // Restore the buffer's previous limit and position. Restore limit first in case the position is greater // than the current limit. this.buffer.limit(lim); @@ -204,13 +187,11 @@ protected VecBuffer createSubBuffer(int offsetInBytes, int lengthInBytes) return subBuffer; } - protected CompoundVecBuffer createSlice(int[] indices, int offset, int length) - { + protected CompoundVecBuffer createSlice(int[] indices, int offset, int length) { return new VecBufferBlocks(this, indices, offset, length); } - protected CompoundVecBuffer createSlice(int beginIndex, int endIndex) - { + protected CompoundVecBuffer createSlice(int beginIndex, int endIndex) { return new VecBufferBlocks(this, beginIndex, endIndex); } } diff --git a/src/gov/nasa/worldwind/util/VecBufferSequence.java b/src/gov/nasa/worldwind/util/VecBufferSequence.java index cfbab30e31..5e00800d19 100644 --- a/src/gov/nasa/worldwind/util/VecBufferSequence.java +++ b/src/gov/nasa/worldwind/util/VecBufferSequence.java @@ -18,25 +18,23 @@ * @author dcollins * @version $Id: VecBufferSequence.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class VecBufferSequence extends CompoundVecBuffer -{ +public class VecBufferSequence extends CompoundVecBuffer { + protected int vecCount; protected VecBuffer buffer; /** * Constructs a PackedCompoundVecBuffer with the specified backing VecBuffer and the specified initial capacity. * - * @param buffer the backing VecBuffer. + * @param buffer the backing VecBuffer. * @param capacity the PackedCompoundVecBuffer's initial capacity, in number of sub-buffers. * * @throws IllegalArgumentException if the buffer is null, or if the capacity is less than 1. */ - public VecBufferSequence(VecBuffer buffer, int capacity) - { + public VecBufferSequence(VecBuffer buffer, int capacity) { super(capacity); - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -52,21 +50,18 @@ public VecBufferSequence(VecBuffer buffer, int capacity) * * @throws IllegalArgumentException if the buffer is null. */ - public VecBufferSequence(VecBuffer buffer) - { + public VecBufferSequence(VecBuffer buffer) { this(buffer, DEFAULT_INITIAL_CAPACITY); } - protected VecBufferSequence(VecBufferSequence that, int beginIndex, int endIndex) - { + protected VecBufferSequence(VecBufferSequence that, int beginIndex, int endIndex) { super(that, beginIndex, endIndex); this.vecCount = that.vecCount; this.buffer = that.buffer; } - protected VecBufferSequence(VecBufferSequence that, int[] indices, int offset, int length) - { + protected VecBufferSequence(VecBufferSequence that, int[] indices, int offset, int length) { super(that, indices, offset, length); this.vecCount = that.vecCount; @@ -81,10 +76,8 @@ protected VecBufferSequence(VecBufferSequence that, int[] indices, int offset, i * * @return the empty VecBufferSequence. */ - public static VecBufferSequence emptyVecBufferSequence(int coordsPerVec) - { - if (coordsPerVec < 1) - { + public static VecBufferSequence emptyVecBufferSequence(int coordsPerVec) { + if (coordsPerVec < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", coordsPerVec); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -93,11 +86,11 @@ public static VecBufferSequence emptyVecBufferSequence(int coordsPerVec) return new VecBufferSequence(VecBuffer.emptyVecBuffer(coordsPerVec)); } - /** {@inheritDoc} */ - public int subBufferSize(int index) - { - if (index < 0 || index >= this.count) - { + /** + * {@inheritDoc} + */ + public int subBufferSize(int index) { + if (index < 0 || index >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -106,16 +99,18 @@ public int subBufferSize(int index) return this.lengths.get(index); } - /** {@inheritDoc} */ - public void clear() - { + /** + * {@inheritDoc} + */ + public void clear() { super.clear(); this.vecCount = 0; } - /** {@inheritDoc} */ - public int getCoordsPerVec() - { + /** + * {@inheritDoc} + */ + public int getCoordsPerVec() { return this.buffer.getCoordsPerVec(); } @@ -124,8 +119,7 @@ public int getCoordsPerVec() * * @return this PackedCompoundVecBuffer's backing VecBuffer. */ - public VecBuffer getVecBuffer() - { + public VecBuffer getVecBuffer() { return this.buffer; } @@ -140,18 +134,17 @@ public VecBuffer getVecBuffer() * * @throws IllegalArgumentException if the subBuffer is null. */ - public int append(VecBuffer buffer) - { - if (buffer == null) - { + public int append(VecBuffer buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int minVecCount = buffer.getSize() + this.vecCount; - if (minVecCount > this.buffer.getSize()) + if (minVecCount > this.buffer.getSize()) { this.expandBufferCapacity(minVecCount); + } int newBufferPos = this.vecCount; this.buffer.putSubBuffer(newBufferPos, buffer); @@ -163,35 +156,27 @@ public int append(VecBuffer buffer) //**************************************************************// //******************** Protected Interface *******************// //**************************************************************// - - protected VecBuffer createSubBuffer(int offset, int length) - { + protected VecBuffer createSubBuffer(int offset, int length) { return this.buffer.getSubBuffer(offset, length); } - protected CompoundVecBuffer createSlice(int[] indices, int offset, int length) - { + protected CompoundVecBuffer createSlice(int[] indices, int offset, int length) { return new VecBufferSequence(this, indices, offset, length); } - protected CompoundVecBuffer createSlice(int beginIndex, int endIndex) - { + protected CompoundVecBuffer createSlice(int beginIndex, int endIndex) { return new VecBufferSequence(this, beginIndex, endIndex); } - protected void expandBufferCapacity(int minCapacity) - { + protected void expandBufferCapacity(int minCapacity) { int newCapacity = 2 * this.buffer.getSize(); // If the new capacity overflows the range of 32-bit integers, then use the largest 32-bit integer. - if (newCapacity < 0) - { + if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; - } - // If the new capacity is still not large enough for the minimum capacity specified, then just use the minimum + } // If the new capacity is still not large enough for the minimum capacity specified, then just use the minimum // capacity specified. - else if (newCapacity < minCapacity) - { + else if (newCapacity < minCapacity) { newCapacity = minCapacity; } @@ -201,7 +186,6 @@ else if (newCapacity < minCapacity) //**************************************************************// //******************** OpenGL Vertex Buffer Interface ********// //**************************************************************// - /** * Binds this buffer as the source of normal coordinates to use when rendering OpenGL primitives. The normal type is * equal to buffer's underlying BufferWrapper GL type, the stride is 0, and the vertex data itself is this buffer's @@ -210,12 +194,10 @@ else if (newCapacity < minCapacity) * @param dc the current {@link gov.nasa.worldwind.render.DrawContext}. * * @throws IllegalArgumentException if the DrawContext is null, or if this buffer is not compatible as a normal - * buffer. + * buffer. */ - public void bindAsNormalBuffer(DrawContext dc) - { - if (dc == null) - { + public void bindAsNormalBuffer(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -232,12 +214,10 @@ public void bindAsNormalBuffer(DrawContext dc) * @param dc the current DrawContext. * * @throws IllegalArgumentException if the DrawContext is null, or if this buffer is not compatible as a vertex - * buffer. + * buffer. */ - public void bindAsVertexBuffer(DrawContext dc) - { - if (dc == null) - { + public void bindAsVertexBuffer(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -247,7 +227,7 @@ public void bindAsVertexBuffer(DrawContext dc) } /** - * Binds this buffer as the source of texture coordinates to use when rendering OpenGL primitives. The texture + * Binds this buffer as the source of texture coordinates to use when rendering OpenGL primitives. The texture * coordinate size is equal to coordsPerVertex, the texture coordinate type is equal to buffer's underlying * BufferWrapper GL type, the stride is 0, and the texture coordinate data itself is this buffer's backing NIO * Buffer. This buffer's vector size must be 1, 2, 3, or 4. @@ -255,12 +235,10 @@ public void bindAsVertexBuffer(DrawContext dc) * @param dc the current DrawContext. * * @throws IllegalArgumentException if the DrawContext is null, or if this buffer is not compatible as a normal - * buffer. + * buffer. */ - public void bindAsTexCoordBuffer(DrawContext dc) - { - if (dc == null) - { + public void bindAsTexCoordBuffer(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -273,15 +251,13 @@ public void bindAsTexCoordBuffer(DrawContext dc) * Renders getTotalBufferSize() elements from the currently bounds OpenGL coordinate buffers, beginning * with element 0. The specified drawMode indicates which type of OpenGL primitives to render. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param drawMode the type of OpenGL primtives to render. * * @throws IllegalArgumentException if the DrawContext is null. */ - public void drawArrays(DrawContext dc, int drawMode) - { - if (dc == null) - { + public void drawArrays(DrawContext dc, int drawMode) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -295,15 +271,13 @@ public void drawArrays(DrawContext dc, int drawMode) * #drawArrays(gov.nasa.worldwind.render.DrawContext, int)}, except that each sub-buffer is rendered independently. * The specified drawMode indicates which type of OpenGL primitives to render. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param drawMode the type of OpenGL primtives to render. * * @throws IllegalArgumentException if the DrawContext is null. */ - public void multiDrawArrays(DrawContext dc, int drawMode) - { - if (dc == null) - { + public void multiDrawArrays(DrawContext dc, int drawMode) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -311,21 +285,16 @@ public void multiDrawArrays(DrawContext dc, int drawMode) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (this.haveMultiDrawArrays(dc)) - { + if (this.haveMultiDrawArrays(dc)) { gl.glMultiDrawArrays(drawMode, this.offsets, this.lengths, this.count); - } - else - { - for (int i = 0; i < this.count; i++) - { + } else { + for (int i = 0; i < this.count; i++) { gl.glDrawArrays(drawMode, this.offsets.get(i), this.lengths.get(i)); } } } - protected boolean haveMultiDrawArrays(DrawContext dc) - { + protected boolean haveMultiDrawArrays(DrawContext dc) { return dc.getGL().isFunctionAvailable("glMultiDrawArrays"); } } diff --git a/src/gov/nasa/worldwind/util/WWBufferUtil.java b/src/gov/nasa/worldwind/util/WWBufferUtil.java index 67a7b58104..7ad94ce044 100644 --- a/src/gov/nasa/worldwind/util/WWBufferUtil.java +++ b/src/gov/nasa/worldwind/util/WWBufferUtil.java @@ -16,34 +16,42 @@ * @author dcollins * @version $Id: WWBufferUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWBufferUtil -{ - /** The size of a short primitive type, in bytes. */ +public class WWBufferUtil { + + /** + * The size of a short primitive type, in bytes. + */ public static final int SIZEOF_SHORT = 2; - /** The size of a int primitive type, in bytes. */ + /** + * The size of a int primitive type, in bytes. + */ public static final int SIZEOF_INT = 4; - /** The size of a float primitive type, in bytes. */ + /** + * The size of a float primitive type, in bytes. + */ public static final int SIZEOF_FLOAT = 4; - /** The size of a double primitive type, in bytes. */ + /** + * The size of a double primitive type, in bytes. + */ public static final int SIZEOF_DOUBLE = 8; - /** The size of a char primitive type, in bytes. */ + /** + * The size of a char primitive type, in bytes. + */ public static final int SIZEOF_CHAR = 2; /** * Allocates a new direct {@link java.nio.ByteBuffer} of the specified size, in chars. * - * @param size the new ByteBuffer's size. + * @param size the new ByteBuffer's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new buffer. * * @throws IllegalArgumentException if size is negative. */ - public static ByteBuffer newByteBuffer(int size, boolean allocateDirect) - { - if (size < 0) - { + public static ByteBuffer newByteBuffer(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -55,18 +63,16 @@ public static ByteBuffer newByteBuffer(int size, boolean allocateDirect) /** * Allocates a new direct {@link java.nio.ShortBuffer} of the specified size, in chars. * - * @param size the new ShortBuffer's size. + * @param size the new ShortBuffer's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new buffer. * * @throws IllegalArgumentException if size is negative. */ - public static ShortBuffer newShortBuffer(int size, boolean allocateDirect) - { - if (size < 0) - { + public static ShortBuffer newShortBuffer(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -78,18 +84,16 @@ public static ShortBuffer newShortBuffer(int size, boolean allocateDirect) /** * Allocates a new direct {@link java.nio.IntBuffer} of the specified size, in chars. * - * @param size the new IntBuffer's size. + * @param size the new IntBuffer's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new buffer. * * @throws IllegalArgumentException if size is negative. */ - public static IntBuffer newIntBuffer(int size, boolean allocateDirect) - { - if (size < 0) - { + public static IntBuffer newIntBuffer(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -101,18 +105,16 @@ public static IntBuffer newIntBuffer(int size, boolean allocateDirect) /** * Allocates a new direct {@link java.nio.FloatBuffer} of the specified size, in chars. * - * @param size the new FloatBuffer's size. + * @param size the new FloatBuffer's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new buffer. * * @throws IllegalArgumentException if size is negative. */ - public static FloatBuffer newFloatBuffer(int size, boolean allocateDirect) - { - if (size < 0) - { + public static FloatBuffer newFloatBuffer(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -124,42 +126,38 @@ public static FloatBuffer newFloatBuffer(int size, boolean allocateDirect) /** * Allocates a new direct {@link java.nio.DoubleBuffer} of the specified size, in chars. * - * @param size the new DoubleBuffer's size. + * @param size the new DoubleBuffer's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new buffer. * * @throws IllegalArgumentException if size is negative. */ - public static DoubleBuffer newDoubleBuffer(int size, boolean allocateDirect) - { - if (size < 0) - { + public static DoubleBuffer newDoubleBuffer(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return allocateDirect ? newDirectByteBuffer(SIZEOF_DOUBLE * size).asDoubleBuffer() - : DoubleBuffer.allocate(size); + : DoubleBuffer.allocate(size); } /** * Allocates a new direct {@link java.nio.CharBuffer} of the specified size, in chars. * - * @param size the new CharBuffer's size. + * @param size the new CharBuffer's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new buffer. * * @throws IllegalArgumentException if size is negative. */ - public static CharBuffer newCharBuffer(int size, boolean allocateDirect) - { - if (size < 0) - { + public static CharBuffer newCharBuffer(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,18 +170,16 @@ public static CharBuffer newCharBuffer(int size, boolean allocateDirect) * Allocates a new {@link BufferWrapper} of the specified size, in bytes. The BufferWrapper is backed by a Buffer of * bytes. * - * @param size the new BufferWrapper's size. + * @param size the new BufferWrapper's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new BufferWrapper. * * @throws IllegalArgumentException if size is negative. */ - public static BufferWrapper newByteBufferWrapper(int size, boolean allocateDirect) - { - if (size < 0) - { + public static BufferWrapper newByteBufferWrapper(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -197,18 +193,16 @@ public static BufferWrapper newByteBufferWrapper(int size, boolean allocateDirec * Allocates a new {@link BufferWrapper} of the specified size, in shorts. The BufferWrapper is backed by a Buffer * of shorts. * - * @param size the new BufferWrapper's size. + * @param size the new BufferWrapper's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new BufferWrapper. * * @throws IllegalArgumentException if size is negative. */ - public static BufferWrapper newShortBufferWrapper(int size, boolean allocateDirect) - { - if (size < 0) - { + public static BufferWrapper newShortBufferWrapper(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -222,18 +216,16 @@ public static BufferWrapper newShortBufferWrapper(int size, boolean allocateDire * Allocates a new {@link BufferWrapper} of the specified size, in ints. The BufferWrapper is backed by a Buffer of * ints. * - * @param size the new BufferWrapper's size. + * @param size the new BufferWrapper's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new BufferWrapper. * * @throws IllegalArgumentException if size is negative. */ - public static BufferWrapper newIntBufferWrapper(int size, boolean allocateDirect) - { - if (size < 0) - { + public static BufferWrapper newIntBufferWrapper(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -247,18 +239,16 @@ public static BufferWrapper newIntBufferWrapper(int size, boolean allocateDirect * Allocates a new {@link BufferWrapper} of the specified size, in floats. The BufferWrapper is backed by a Buffer * of floats. * - * @param size the new BufferWrapper's size. + * @param size the new BufferWrapper's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new BufferWrapper. * * @throws IllegalArgumentException if size is negative. */ - public static BufferWrapper newFloatBufferWrapper(int size, boolean allocateDirect) - { - if (size < 0) - { + public static BufferWrapper newFloatBufferWrapper(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -272,18 +262,16 @@ public static BufferWrapper newFloatBufferWrapper(int size, boolean allocateDire * Allocates a new {@link BufferWrapper} of the specified size, in doubles. The BufferWrapper is backed by a Buffer * of doubles. * - * @param size the new BufferWrapper's size. + * @param size the new BufferWrapper's size. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the new BufferWrapper. * * @throws IllegalArgumentException if size is negative. */ - public static BufferWrapper newDoubleBufferWrapper(int size, boolean allocateDirect) - { - if (size < 0) - { + public static BufferWrapper newDoubleBufferWrapper(int size, boolean allocateDirect) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -299,18 +287,16 @@ public static BufferWrapper newDoubleBufferWrapper(int size, boolean allocateDir * buffer which is partially filled with the contents of the specified buffer.The returned buffer is a direct * ByteBuffer if and only if the specified buffer is direct. * - * @param buffer the buffer to copy. + * @param buffer the buffer to copy. * @param newSize the new buffer's size, in bytes. * * @return the new buffer, with the specified size. * * @throws IllegalArgumentException if the buffer is null, if the new size is negative, or if the new size is less - * than the buffer's remaing elements. + * than the buffer's remaing elements. */ - public static ByteBuffer copyOf(ByteBuffer buffer, int newSize) - { - if (newSize < 0 || newSize < buffer.remaining()) - { + public static ByteBuffer copyOf(ByteBuffer buffer, int newSize) { + if (newSize < 0 || newSize < buffer.remaining()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -319,13 +305,10 @@ public static ByteBuffer copyOf(ByteBuffer buffer, int newSize) ByteBuffer newBuffer = newByteBuffer(newSize, buffer.isDirect()); int pos = buffer.position(); // Save the input buffer's current position. - try - { + try { newBuffer.put(buffer); newBuffer.rewind(); - } - finally - { + } finally { buffer.position(pos); // Restore the input buffer's original position. } @@ -338,18 +321,16 @@ public static ByteBuffer copyOf(ByteBuffer buffer, int newSize) * buffer which is partially filled with the contents of the specified buffer. The returned buffer is a backed by a * direct ByteBuffer if and only if the specified buffer is direct. * - * @param buffer the buffer to copy. + * @param buffer the buffer to copy. * @param newSize the new buffer's size, in chars. * * @return the new buffer, with the specified size. * * @throws IllegalArgumentException if the buffer is null, if the new size is negative, or if the new size is less - * than the buffer's remaing elements. + * than the buffer's remaing elements. */ - public static CharBuffer copyOf(CharBuffer buffer, int newSize) - { - if (newSize < 0 || newSize < buffer.remaining()) - { + public static CharBuffer copyOf(CharBuffer buffer, int newSize) { + if (newSize < 0 || newSize < buffer.remaining()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -358,13 +339,10 @@ public static CharBuffer copyOf(CharBuffer buffer, int newSize) CharBuffer newBuffer = newCharBuffer(newSize, buffer.isDirect()); int pos = buffer.position(); // Save the input buffer's current position. - try - { + try { newBuffer.put(buffer); newBuffer.rewind(); - } - finally - { + } finally { buffer.position(pos); // Restore the input buffer's original position. } @@ -377,18 +355,16 @@ public static CharBuffer copyOf(CharBuffer buffer, int newSize) * buffer which is partially filled with the contents of the specified buffer. The returned buffer is a backed by a * direct ByteBuffer if and only if the specified buffer is direct. * - * @param buffer the buffer to copy. + * @param buffer the buffer to copy. * @param newSize the new buffer's size, in shorts. * * @return the new buffer, with the specified size. * * @throws IllegalArgumentException if the buffer is null, if the new size is negative, or if the new size is less - * than the buffer's remaing elements. + * than the buffer's remaing elements. */ - public static ShortBuffer copyOf(ShortBuffer buffer, int newSize) - { - if (newSize < 0 || newSize < buffer.remaining()) - { + public static ShortBuffer copyOf(ShortBuffer buffer, int newSize) { + if (newSize < 0 || newSize < buffer.remaining()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -397,13 +373,10 @@ public static ShortBuffer copyOf(ShortBuffer buffer, int newSize) ShortBuffer newBuffer = newShortBuffer(newSize, buffer.isDirect()); int pos = buffer.position(); // Save the input buffer's current position. - try - { + try { newBuffer.put(buffer); newBuffer.rewind(); - } - finally - { + } finally { buffer.position(pos); // Restore the input buffer's original position. } @@ -416,18 +389,16 @@ public static ShortBuffer copyOf(ShortBuffer buffer, int newSize) * buffer which is partially filled with the contents of the specified buffer.The returned buffer is a backed by a * direct ByteBuffer if and only if the specified buffer is direct. * - * @param buffer the buffer to copy. + * @param buffer the buffer to copy. * @param newSize the new buffer's size, in ints. * * @return the new buffer, with the specified size. * * @throws IllegalArgumentException if the buffer is null, if the new size is negative, or if the new size is less - * than the buffer's remaing elements. + * than the buffer's remaing elements. */ - public static IntBuffer copyOf(IntBuffer buffer, int newSize) - { - if (newSize < 0 || newSize < buffer.remaining()) - { + public static IntBuffer copyOf(IntBuffer buffer, int newSize) { + if (newSize < 0 || newSize < buffer.remaining()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -436,13 +407,10 @@ public static IntBuffer copyOf(IntBuffer buffer, int newSize) IntBuffer newBuffer = newIntBuffer(newSize, buffer.isDirect()); int pos = buffer.position(); // Save the input buffer's current position. - try - { + try { newBuffer.put(buffer); newBuffer.rewind(); - } - finally - { + } finally { buffer.position(pos); // Restore the input buffer's original position. } @@ -455,18 +423,16 @@ public static IntBuffer copyOf(IntBuffer buffer, int newSize) * buffer which is partially filled with the contents of the specified buffer. The returned buffer is a backed by a * direct ByteBuffer if and only if the specified buffer is direct. * - * @param buffer the buffer to copy. + * @param buffer the buffer to copy. * @param newSize the new buffer's size, in floats. * * @return the new buffer, with the specified size. * * @throws IllegalArgumentException if the buffer is null, if the new size is negative, or if the new size is less - * than the buffer's remaing elements. + * than the buffer's remaing elements. */ - public static FloatBuffer copyOf(FloatBuffer buffer, int newSize) - { - if (newSize < 0 || newSize < buffer.remaining()) - { + public static FloatBuffer copyOf(FloatBuffer buffer, int newSize) { + if (newSize < 0 || newSize < buffer.remaining()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -475,13 +441,10 @@ public static FloatBuffer copyOf(FloatBuffer buffer, int newSize) FloatBuffer newBuffer = newFloatBuffer(newSize, buffer.isDirect()); int pos = buffer.position(); // Save the input buffer's current position. - try - { + try { newBuffer.put(buffer); newBuffer.rewind(); - } - finally - { + } finally { buffer.position(pos); // Restore the input buffer's original position. } @@ -494,18 +457,16 @@ public static FloatBuffer copyOf(FloatBuffer buffer, int newSize) * buffer which is partially filled with the contents of the specified buffer. The returned buffer is a backed by a * direct ByteBuffer if and only if the specified buffer is direct. * - * @param buffer the buffer to copy. + * @param buffer the buffer to copy. * @param newSize the new buffer's size, in doubles. * * @return the new buffer, with the specified size. * * @throws IllegalArgumentException if the buffer is null, if the new size is negative, or if the new size is less - * than the buffer's remaing elements. + * than the buffer's remaing elements. */ - public static DoubleBuffer copyOf(DoubleBuffer buffer, int newSize) - { - if (newSize < 0 || newSize < buffer.remaining()) - { + public static DoubleBuffer copyOf(DoubleBuffer buffer, int newSize) { + if (newSize < 0 || newSize < buffer.remaining()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -514,13 +475,10 @@ public static DoubleBuffer copyOf(DoubleBuffer buffer, int newSize) DoubleBuffer newBuffer = newDoubleBuffer(newSize, buffer.isDirect()); int pos = buffer.position(); // Save the input buffer's current position. - try - { + try { newBuffer.put(buffer); newBuffer.rewind(); - } - finally - { + } finally { buffer.position(pos); // Restore the input buffer's original position. } @@ -539,25 +497,24 @@ public static DoubleBuffer copyOf(DoubleBuffer buffer, int newSize) * * @throws IllegalArgumentException if the data type is null. */ - public static int sizeOfPrimitiveType(Object dataType) - { - if (dataType == null) - { + public static int sizeOfPrimitiveType(Object dataType) { + if (dataType == null) { String message = Logging.getMessage("nullValue.DataTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (AVKey.INT8.equals(dataType)) + if (AVKey.INT8.equals(dataType)) { return 1; - else if (AVKey.INT16.equals(dataType)) + } else if (AVKey.INT16.equals(dataType)) { return SIZEOF_SHORT; - else if (AVKey.INT32.equals(dataType)) + } else if (AVKey.INT32.equals(dataType)) { return SIZEOF_INT; - else if (AVKey.FLOAT32.equals(dataType)) + } else if (AVKey.FLOAT32.equals(dataType)) { return SIZEOF_FLOAT; - else if (AVKey.FLOAT64.equals(dataType)) + } else if (AVKey.FLOAT64.equals(dataType)) { return SIZEOF_DOUBLE; + } return -1; } @@ -567,18 +524,16 @@ else if (AVKey.FLOAT64.equals(dataType)) * missingDataSignal are ignored. This returns null if the buffer is empty or contains only missing * values. * - * @param buffer the buffer to search for the minimum and maximum values. + * @param buffer the buffer to search for the minimum and maximum values. * @param missingDataSignal the number indicating a specific floating point value to ignore. * * @return an array containing the minimum value in index 0 and the maximum value in index 1, or null if the buffer - * is empty or contains only missing values. + * is empty or contains only missing values. * * @throws IllegalArgumentException if the buffer is null. */ - public static double[] computeExtremeValues(BufferWrapper buffer, double missingDataSignal) - { - if (buffer == null) - { + public static double[] computeExtremeValues(BufferWrapper buffer, double missingDataSignal) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -587,23 +542,26 @@ public static double[] computeExtremeValues(BufferWrapper buffer, double missing double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; - for (int i = 0; i < buffer.length(); i++) - { + for (int i = 0; i < buffer.length(); i++) { double value = buffer.getDouble(i); - if (Double.compare(value, missingDataSignal) == 0) + if (Double.compare(value, missingDataSignal) == 0) { continue; + } - if (min > value) + if (min > value) { min = value; - if (max < value) + } + if (max < value) { max = value; + } } - if (Double.compare(min, Double.MAX_VALUE) == 0 || Double.compare(max, -Double.MAX_VALUE) == 0) + if (Double.compare(min, Double.MAX_VALUE) == 0 || Double.compare(max, -Double.MAX_VALUE) == 0) { return null; + } - return new double[] {min, max}; + return new double[]{min, max}; } /** @@ -613,14 +571,12 @@ public static double[] computeExtremeValues(BufferWrapper buffer, double missing * @param buffer the buffer to search for the minimum and maximum values. * * @return an array containing the minimum value in index 0 and the maximum value in index 1, or null if the buffer - * is empty or contains only NaN values. + * is empty or contains only NaN values. * * @throws IllegalArgumentException if the buffer is null. */ - public static double[] computeExtremeValues(BufferWrapper buffer) - { - if (buffer == null) - { + public static double[] computeExtremeValues(BufferWrapper buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -629,8 +585,7 @@ public static double[] computeExtremeValues(BufferWrapper buffer) return computeExtremeValues(buffer, Double.NaN); } - protected static ByteBuffer newDirectByteBuffer(int size) - { + protected static ByteBuffer newDirectByteBuffer(int size) { return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()); } @@ -638,30 +593,26 @@ protected static ByteBuffer newDirectByteBuffer(int size) * Copies a specified array of vertices to a specified vertex buffer. This method calls {@link * java.nio.FloatBuffer#flip()} prior to returning. * - * @param array the vertices to copy. + * @param array the vertices to copy. * @param buffer the buffer to copy the vertices to. Must have enough remaining space to hold the vertices. * * @return the buffer specified as input, with its limit incremented by the number of vertices copied, and its - * position set to 0. + * position set to 0. */ - public static FloatBuffer copyArrayToBuffer(Vec4[] array, FloatBuffer buffer) - { - if (array == null) - { + public static FloatBuffer copyArrayToBuffer(Vec4[] array, FloatBuffer buffer) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (Vec4 v : array) - { + for (Vec4 v : array) { buffer.put((float) v.x).put((float) v.y).put((float) v.z); } diff --git a/src/gov/nasa/worldwind/util/WWIO.java b/src/gov/nasa/worldwind/util/WWIO.java index e9f74d6929..b5955892d1 100644 --- a/src/gov/nasa/worldwind/util/WWIO.java +++ b/src/gov/nasa/worldwind/util/WWIO.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import com.jogamp.common.nio.Buffers; @@ -24,38 +23,43 @@ * @author Tom Gaskins * @version $Id: WWIO.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWIO -{ +public class WWIO { + public static final String DELETE_ON_EXIT_PREFIX = "WWJDeleteOnExit"; public static final String ILLEGAL_FILE_PATH_PART_CHARACTERS = "[" + "?/\\\\=+<>:;\\,\"\\|^\\[\\]" + "]"; - /** The default character encoding used if none is specified. */ + /** + * The default character encoding used if none is specified. + */ protected static final String DEFAULT_CHARACTER_ENCODING = "UTF-8"; - /** The maximum number of characters allowed in a file path. Covers Windows, Linux and OS X. */ + /** + * The maximum number of characters allowed in a file path. Covers Windows, Linux and OS X. + */ public static final int MAX_FILE_PATH_LENGTH = 255; - public static String formPath(String... pathParts) - { + public static String formPath(String... pathParts) { StringBuilder sb = new StringBuilder(); - for (String pathPart : pathParts) - { - if (pathPart == null) + for (String pathPart : pathParts) { + if (pathPart == null) { continue; + } - if (sb.length() > 0) + if (sb.length() > 0) { sb.append(File.separator); + } sb.append(pathPart.replaceAll(ILLEGAL_FILE_PATH_PART_CHARACTERS, "_")); } return sb.toString(); } - public static String appendPathPart(String firstPart, String secondPart) - { - if (secondPart == null || secondPart.length() == 0) + public static String appendPathPart(String firstPart, String secondPart) { + if (secondPart == null || secondPart.length() == 0) { return firstPart; - if (firstPart == null || firstPart.length() == 0) + } + if (firstPart == null || firstPart.length() == 0) { return secondPart; + } StringBuilder sb = new StringBuilder(); sb.append(WWIO.stripTrailingSeparator(firstPart)); @@ -74,10 +78,8 @@ public static String appendPathPart(String firstPart, String secondPart) * * @throws IllegalArgumentException if the specified string is null. */ - public static String replaceIllegalFileNameCharacters(String s) - { - if (s == null) - { + public static String replaceIllegalFileNameCharacters(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -86,40 +88,36 @@ public static String replaceIllegalFileNameCharacters(String s) return s.replaceAll(ILLEGAL_FILE_PATH_PART_CHARACTERS, "_"); } - public static String stripTrailingSeparator(String s) - { - if (s == null) - { + public static String stripTrailingSeparator(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (s.endsWith("/") || s.endsWith("\\")) + if (s.endsWith("/") || s.endsWith("\\")) { return s.substring(0, s.length() - 1); - else + } else { return s; + } } - public static String stripLeadingSeparator(String s) - { - if (s == null) - { + public static String stripLeadingSeparator(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (s.startsWith("/") || s.startsWith("\\")) + if (s.startsWith("/") || s.startsWith("\\")) { return s.substring(1, s.length()); - else + } else { return s; + } } - public static String stripLeadingZeros(String s) - { - if (s == null) - { + public static String stripLeadingZeros(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -127,18 +125,23 @@ public static String stripLeadingZeros(String s) int len = s.length(); if (len < 2) // String is empty or is a single character, so there is nothing to strip. + { return s; + } int i = 0; - while (i < len && s.charAt(i) == '0') - { + while (i < len && s.charAt(i) == '0') { i++; } if (i == len) // String is just '0' characters. Leave the last one. + { i = len - 1; + } if (i == 0) // String doesn't contain any '0' characters, return the original string. + { return s; + } return s.substring(i, len); // String contains at least one leading '0' character. } @@ -155,40 +158,39 @@ public static String stripLeadingZeros(String s) * * @throws IllegalArgumentException if the source is null or an empty string. */ - public static File getFileForLocalAddress(Object src) - { - if (WWUtil.isEmpty(src)) - { + public static File getFileForLocalAddress(Object src) { + if (WWUtil.isEmpty(src)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (src instanceof File) + if (src instanceof File) { return (File) src; - - else if (src instanceof URL) + } else if (src instanceof URL) { return convertURLToFile((URL) src); - - else if (src instanceof URI) + } else if (src instanceof URI) { return convertURIToFile((URI) src); - - else if (!(src instanceof String)) + } else if (!(src instanceof String)) { return null; + } String sourceName = (String) src; File file = new File(sourceName); - if (file.exists()) + if (file.exists()) { return file; + } URL url = makeURL(sourceName); - if (url != null) + if (url != null) { return convertURLToFile(url); + } URI uri = makeURI(sourceName); - if (uri != null) + if (uri != null) { return convertURIToFile(uri); + } return null; } @@ -203,21 +205,16 @@ else if (!(src instanceof String)) * * @throws IllegalArgumentException if the url is null. */ - public static File convertURIToFile(URI uri) - { - if (uri == null) - { + public static File convertURIToFile(URI uri) { + if (uri == null) { String message = Logging.getMessage("nullValue.URIIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return new File(uri); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { // Thrown if the URI cannot be interpreted as a path on the local filesystem. return null; } @@ -233,43 +230,33 @@ public static File convertURIToFile(URI uri) * * @throws IllegalArgumentException if the url is null. */ - public static File convertURLToFile(URL url) - { - if (url == null) - { + public static File convertURLToFile(URL url) { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return new File(url.toURI()); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { // Thrown if the URI cannot be interpreted as a path on the local filesystem. return null; - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { // Thrown if the URL cannot be converted to a URI. return null; } } @SuppressWarnings({"ResultOfMethodCallIgnored"}) - public static boolean saveBuffer(ByteBuffer buffer, File file, boolean forceFilesystemWrite) throws IOException - { - if (buffer == null) - { + public static boolean saveBuffer(ByteBuffer buffer, File file, boolean forceFilesystemWrite) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (file == null) - { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -279,97 +266,85 @@ public static boolean saveBuffer(ByteBuffer buffer, File file, boolean forceFile FileChannel channel = null; FileLock lock; int numBytesWritten = 0; - try - { + try { fos = new FileOutputStream(file); channel = fos.getChannel(); lock = channel.tryLock(); - if (lock == null) - { + if (lock == null) { // The file is being written to, or some other process is keeping it to itself. // This is an okay condition, but worth noting. Logging.logger().log(Level.FINER, "WWIO.UnableToAcquireLockFor", file.getPath()); return false; } - for (buffer.rewind(); buffer.hasRemaining(); ) - { + for (buffer.rewind(); buffer.hasRemaining();) { numBytesWritten += channel.write(buffer); } // Optionally force writing to the underlying storage device. Doing so ensures that all contents are // written to the device (and not in the I/O cache) in the event of a system failure. - if (forceFilesystemWrite) + if (forceFilesystemWrite) { channel.force(true); + } fos.flush(); return true; - } - catch (ClosedByInterruptException e) - { + } catch (ClosedByInterruptException e) { Logging.logger().log(Level.FINE, - Logging.getMessage("generic.interrupted", "WWIO.saveBuffer", file.getPath()), e); + Logging.getMessage("generic.interrupted", "WWIO.saveBuffer", file.getPath()), e); if (numBytesWritten > 0) // don't leave behind incomplete files + { file.delete(); + } throw e; - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().log(Level.SEVERE, Logging.getMessage("WWIO.ErrorSavingBufferTo", file.getPath()), e); if (numBytesWritten > 0) // don't leave behind incomplete files + { file.delete(); + } throw e; - } - finally - { + } finally { WWIO.closeStream(channel, file.getPath()); // also releases the lock WWIO.closeStream(fos, file.getPath()); } } - public static boolean saveBuffer(ByteBuffer buffer, File file) throws IOException - { + public static boolean saveBuffer(ByteBuffer buffer, File file) throws IOException { // By default, force changes to be written to the underlying storage device. return saveBuffer(buffer, file, true); } @SuppressWarnings({"ResultOfMethodCallIgnored"}) public static boolean saveBufferToStream(ByteBuffer buffer, OutputStream fos) - throws IOException - { - if (buffer == null) - { + throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (fos == null) - { + if (fos == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } WritableByteChannel channel; - try - { + try { channel = Channels.newChannel(fos); - for (buffer.rewind(); buffer.hasRemaining(); ) - { + for (buffer.rewind(); buffer.hasRemaining();) { channel.write(buffer); } fos.flush(); return true; - } - finally - { + } finally { WWIO.closeStream(fos, null); } } @@ -397,37 +372,33 @@ public static boolean saveBufferToStream(ByteBuffer buffer, OutputStream fos) * * @throws IOException if the file cannot be mapped for any reason. */ - public static MappedByteBuffer mapFile(File file, FileChannel.MapMode mode) throws IOException - { - if (file == null) - { + public static MappedByteBuffer mapFile(File file, FileChannel.MapMode mode) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (mode == null) - { + if (mode == null) { String message = Logging.getMessage("nullValue.ModelIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String accessMode; - if (mode == FileChannel.MapMode.READ_ONLY) + if (mode == FileChannel.MapMode.READ_ONLY) { accessMode = "r"; - else // (mode == FileChannel.MapMode.READ_WRITE || mode == FileChannel.MapMode.PRIVATE) + } else // (mode == FileChannel.MapMode.READ_WRITE || mode == FileChannel.MapMode.PRIVATE) + { accessMode = "rw"; + } RandomAccessFile raf = null; - try - { + try { raf = new RandomAccessFile(file, accessMode); FileChannel fc = raf.getChannel(); return fc.map(mode, 0, fc.size()); - } - finally - { + } finally { WWIO.closeStream(raf, file.getPath()); } } @@ -443,10 +414,8 @@ public static MappedByteBuffer mapFile(File file, FileChannel.MapMode mode) thro * * @throws IOException if the file cannot be mapped for any reason. */ - public static MappedByteBuffer mapFile(File file) throws IOException - { - if (file == null) - { + public static MappedByteBuffer mapFile(File file) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -464,12 +433,10 @@ public static MappedByteBuffer mapFile(File file) throws IOException * @return the bytes from the specified URL, with the current JVM byte order. * * @throws IllegalArgumentException if the URL is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static ByteBuffer readURLContentToBuffer(URL url) throws IOException - { - if (url == null) - { + public static ByteBuffer readURLContentToBuffer(URL url) throws IOException { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -484,32 +451,27 @@ public static ByteBuffer readURLContentToBuffer(URL url) throws IOException * otherwise. Direct buffers are backed by native memory, and may resite outside of the normal garbage-collected * heap. Non-direct buffers are backed by JVM heap memory. * - * @param url the URL to read. + * @param url the URL to read. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the bytes from the specified URL, with the current JVM byte order. * * @throws IllegalArgumentException if the URL is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static ByteBuffer readURLContentToBuffer(URL url, boolean allocateDirect) throws IOException - { - if (url == null) - { + public static ByteBuffer readURLContentToBuffer(URL url, boolean allocateDirect) throws IOException { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } InputStream is = null; - try - { + try { is = url.openStream(); return readStreamToBuffer(is, allocateDirect); - } - finally - { + } finally { WWIO.closeStream(is, url.toString()); } } @@ -518,23 +480,19 @@ public static ByteBuffer readURLContentToBuffer(URL url, boolean allocateDirect) * Reads all the bytes from the specified {@link URL}, returning the bytes as a String. The bytes are * interpreted according to the specified encoding, or UTF-8 if no encoding is specified. * - * @param url the URL to read. + * @param url the URL to read. * @param encoding the encoding do use. If null is specified then UTF-8 is used. * * @return the string representation of the bytes at the URL decoded according to the specified - * encoding. + * encoding. * * @throws IllegalArgumentException if the url is null. - * @throws IOException if an I/O error occurs. - * @throws java.nio.charset.IllegalCharsetNameException - * if the specified encoding name is illegal. - * @throws java.nio.charset.UnsupportedCharsetException - * if no support for the named encoding is available. + * @throws IOException if an I/O error occurs. + * @throws java.nio.charset.IllegalCharsetNameException if the specified encoding name is illegal. + * @throws java.nio.charset.UnsupportedCharsetException if no support for the named encoding is available. */ - public static String readURLContentToString(URL url, String encoding) throws IOException - { - if (url == null) - { + public static String readURLContentToString(URL url, String encoding) throws IOException { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -553,12 +511,10 @@ public static String readURLContentToString(URL url, String encoding) throws IOE * @return the bytes from the specified file, with the current JVM byte order. * * @throws IllegalArgumentException if the file is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static ByteBuffer readFileToBuffer(File file) throws IOException - { - if (file == null) - { + public static ByteBuffer readFileToBuffer(File file) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -573,97 +529,79 @@ public static ByteBuffer readFileToBuffer(File file) throws IOException * otherwise. Direct buffers are backed by native memory, and may reside outside of the normal garbage-collected * heap. Non-direct buffers are backed by JVM heap memory. * - * @param file the file to read. + * @param file the file to read. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the bytes from the specified file, with the current JVM byte order. * * @throws IllegalArgumentException if the file is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static ByteBuffer readFileToBuffer(File file, boolean allocateDirect) throws IOException - { - if (file == null) - { + public static ByteBuffer readFileToBuffer(File file, boolean allocateDirect) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream is = new FileInputStream(file); - try - { + try { FileChannel fc = is.getChannel(); int size = (int) fc.size(); ByteBuffer buffer = allocateDirect ? ByteBuffer.allocateDirect(size) : ByteBuffer.allocate(size); - for (int count = 0; count >= 0 && buffer.hasRemaining(); ) - { + for (int count = 0; count >= 0 && buffer.hasRemaining();) { count = fc.read(buffer); } buffer.flip(); return buffer; - } - finally - { + } finally { WWIO.closeStream(is, file.getPath()); } } - public static ByteBuffer inflateFileToBuffer(File file) throws IOException - { - if (file == null) - { + public static ByteBuffer inflateFileToBuffer(File file) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream is = new FileInputStream(file); - try - { + try { return inflateStreamToBuffer(is); - } - finally - { + } finally { WWIO.closeStream(is, file.getPath()); } } - public static boolean saveBufferToGZipFile(ByteBuffer buffer, File file) throws IOException - { + public static boolean saveBufferToGZipFile(ByteBuffer buffer, File file) throws IOException { return saveBufferToStream(buffer, new GZIPOutputStream(new FileOutputStream(file))); } - public static boolean deflateBufferToFile(ByteBuffer buffer, File file) throws IOException - { + public static boolean deflateBufferToFile(ByteBuffer buffer, File file) throws IOException { return saveBufferToStream(buffer, new DeflaterOutputStream(new FileOutputStream(file))); } - public static ByteBuffer readGZipFileToBuffer(File gzFile) throws IllegalArgumentException, IOException - { - if (gzFile == null) - { + public static ByteBuffer readGZipFileToBuffer(File gzFile) throws IllegalArgumentException, IOException { + if (gzFile == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!gzFile.exists()) - { + if (!gzFile.exists()) { String message = Logging.getMessage("generic.FileNotFound", gzFile.getAbsolutePath()); Logging.logger().severe(message); throw new FileNotFoundException(message); } - if (!gzFile.canRead()) - { + if (!gzFile.canRead()) { String message = Logging.getMessage("generic.FileNoReadPermission", gzFile.getAbsolutePath()); Logging.logger().severe(message); throw new IOException(message); } int inflatedLength = gzipGetInflatedLength(gzFile); - if (0 == inflatedLength) - { + if (0 == inflatedLength) { String message = Logging.getMessage("generic.LengthIsInvalid", gzFile.getAbsolutePath()); Logging.logger().severe(message); throw new IOException(message); @@ -672,26 +610,21 @@ public static ByteBuffer readGZipFileToBuffer(File gzFile) throws IllegalArgumen ByteBuffer buffer = null; GZIPInputStream is = null; - try - { + try { is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(gzFile))); buffer = transferStreamToByteBuffer(is, inflatedLength); buffer.rewind(); - } - finally - { + } finally { WWIO.closeStream(is, gzFile.getPath()); } return buffer; } - private static int gzipGetInflatedLength(File gzFile) throws IOException - { + private static int gzipGetInflatedLength(File gzFile) throws IOException { RandomAccessFile raf = null; int length = 0; - try - { + try { raf = new RandomAccessFile(gzFile, "r"); raf.seek(raf.length() - 4); int b4 = 0xFF & raf.read(); @@ -699,19 +632,16 @@ private static int gzipGetInflatedLength(File gzFile) throws IOException int b2 = 0xFF & raf.read(); int b1 = 0xFF & raf.read(); length = (b1 << 24) | (b2 << 16) + (b3 << 8) + b4; - } - finally - { - if (null != raf) + } finally { + if (null != raf) { raf.close(); + } } return length; } - public static ByteBuffer readZipEntryToBuffer(File zipFile, String entryName) throws IOException - { - if (zipFile == null) - { + public static ByteBuffer readZipEntryToBuffer(File zipFile, String entryName) throws IOException { + if (zipFile == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -719,40 +649,31 @@ public static ByteBuffer readZipEntryToBuffer(File zipFile, String entryName) th InputStream is = null; ZipEntry ze = null; - try - { + try { ZipFile zf = new ZipFile(zipFile); - if (zf.size() < 1) - { + if (zf.size() < 1) { String message = Logging.getMessage("WWIO.ZipFileIsEmpty", zipFile.getPath()); Logging.logger().severe(message); throw new java.io.IOException(message); } - if (entryName != null) - { // Read the specified entry + if (entryName != null) { // Read the specified entry ze = zf.getEntry(entryName); - if (ze == null) - { + if (ze == null) { String message = Logging.getMessage("WWIO.ZipFileEntryNIF", entryName, zipFile.getPath()); Logging.logger().severe(message); throw new IOException(message); } - } - else - { // Grab first first file entry + } else { // Grab first first file entry Enumeration entries = zf.entries(); - while (entries.hasMoreElements()) - { + while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); - if (null != entry && !entry.isDirectory()) - { + if (null != entry && !entry.isDirectory()) { ze = entry; break; } } - if (null == ze) - { + if (null == ze) { String message = Logging.getMessage("WWIO.ZipFileIsEmpty", zipFile.getPath()); Logging.logger().severe(message); throw new java.io.IOException(message); @@ -761,30 +682,24 @@ public static ByteBuffer readZipEntryToBuffer(File zipFile, String entryName) th is = zf.getInputStream(ze); ByteBuffer buffer = null; - if (ze.getSize() > 0) - { + if (ze.getSize() > 0) { buffer = transferStreamToByteBuffer(is, (int) ze.getSize()); buffer.rewind(); } return buffer; - } - finally - { + } finally { WWIO.closeStream(is, entryName); } } - private static ByteBuffer transferStreamToByteBuffer(InputStream stream, int numBytes) throws IOException - { - if (stream == null) - { + private static ByteBuffer transferStreamToByteBuffer(InputStream stream, int numBytes) throws IOException { + if (stream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numBytes < 1) - { + if (numBytes < 1) { Logging.logger().severe("WWIO.NumberBytesTransferLessThanOne"); throw new IllegalArgumentException(Logging.getMessage("WWIO.NumberBytesTransferLessThanOne")); } @@ -792,11 +707,9 @@ private static ByteBuffer transferStreamToByteBuffer(InputStream stream, int num int bytesRead = 0; int count = 0; byte[] bytes = new byte[numBytes]; - while (count >= 0 && (numBytes - bytesRead) > 0) - { + while (count >= 0 && (numBytes - bytesRead) > 0) { count = stream.read(bytes, bytesRead, numBytes - bytesRead); - if (count > 0) - { + if (count > 0) { bytesRead += count; } } @@ -813,12 +726,10 @@ private static ByteBuffer transferStreamToByteBuffer(InputStream stream, int num * @return the bytes from the specified stream, with the current JVM byte order. * * @throws IllegalArgumentException if the stream is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static ByteBuffer readStreamToBuffer(InputStream inputStream) throws IOException - { - if (inputStream == null) - { + public static ByteBuffer readStreamToBuffer(InputStream inputStream) throws IOException { + if (inputStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -833,19 +744,17 @@ public static ByteBuffer readStreamToBuffer(InputStream inputStream) throws IOEx * non-direct ByteBuffer otherwise. Direct buffers are backed by native memory, and may reside outside of the normal * garbage-collected heap. Non-direct buffers are backed by JVM heap memory. * - * @param inputStream the stream to read. + * @param inputStream the stream to read. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the bytes from the specified stream, with the current JVM byte order. * * @throws IllegalArgumentException if the stream is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static ByteBuffer readStreamToBuffer(InputStream inputStream, boolean allocateDirect) throws IOException - { - if (inputStream == null) - { + public static ByteBuffer readStreamToBuffer(InputStream inputStream, boolean allocateDirect) throws IOException { + if (inputStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -859,25 +768,23 @@ public static ByteBuffer readStreamToBuffer(InputStream inputStream, boolean all * Reads all the available bytes from the specified {@link java.io.InputStream}, returning the bytes as a String. * The bytes are interpreted according to the specified encoding, or UTF-8 if no encoding is specified. * - * @param stream the stream to read. + * @param stream the stream to read. * @param encoding the encoding do use. If null is specified then UTF-8 is used. * * @return the string representation of the bytes in the stream decoded according to the specified encoding. * * @throws IllegalArgumentException if the stream is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static String readStreamToString(InputStream stream, String encoding) throws IOException - { - if (stream == null) - { + public static String readStreamToString(InputStream stream, String encoding) throws IOException { + if (stream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return readCharacterStreamToString( - new InputStreamReader(stream, encoding != null ? encoding : DEFAULT_CHARACTER_ENCODING)); + new InputStreamReader(stream, encoding != null ? encoding : DEFAULT_CHARACTER_ENCODING)); } /** @@ -886,19 +793,17 @@ public static String readStreamToString(InputStream stream, String encoding) thr * is true, and returns a non-direct ByteBuffer otherwise. Direct buffers are backed by native memory, and may * reside outside of the normal garbage-collected heap. Non-direct buffers are backed by JVM heap memory. * - * @param channel the channel to read. + * @param channel the channel to read. * @param allocateDirect true to allocate and return a direct buffer, false to allocate and return a non-direct - * buffer. + * buffer. * * @return the bytes from the specified channel, with the current JVM byte order. * * @throws IllegalArgumentException if the channel is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static ByteBuffer readChannelToBuffer(ReadableByteChannel channel, boolean allocateDirect) throws IOException - { - if (channel == null) - { + public static ByteBuffer readChannelToBuffer(ReadableByteChannel channel, boolean allocateDirect) throws IOException { + if (channel == null) { String message = Logging.getMessage("nullValue.ChannelIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -908,20 +813,19 @@ public static ByteBuffer readChannelToBuffer(ReadableByteChannel channel, boolea ByteBuffer buffer = WWBufferUtil.newByteBuffer(PAGE_SIZE, allocateDirect); int count = 0; - while (count >= 0) - { + while (count >= 0) { count = channel.read(buffer); - if (count > 0 && !buffer.hasRemaining()) - { + if (count > 0 && !buffer.hasRemaining()) { ByteBuffer biggerBuffer = allocateDirect ? ByteBuffer.allocateDirect(buffer.limit() + PAGE_SIZE) - : ByteBuffer.allocate(buffer.limit() + PAGE_SIZE); + : ByteBuffer.allocate(buffer.limit() + PAGE_SIZE); biggerBuffer.put((ByteBuffer) buffer.rewind()); buffer = biggerBuffer; } } - if (buffer != null) + if (buffer != null) { buffer.flip(); + } return buffer; } @@ -933,32 +837,28 @@ public static ByteBuffer readChannelToBuffer(ReadableByteChannel channel, boolea * set to zero. * * @param channel the channel to read bytes from. - * @param buffer the buffer to receive the bytes. + * @param buffer the buffer to receive the bytes. * * @return the specified buffer. * * @throws IllegalArgumentException if the channel or the buffer is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static ByteBuffer readChannelToBuffer(ReadableByteChannel channel, ByteBuffer buffer) throws IOException - { - if (channel == null) - { + public static ByteBuffer readChannelToBuffer(ReadableByteChannel channel, ByteBuffer buffer) throws IOException { + if (channel == null) { String message = Logging.getMessage("nullValue.ChannelIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int count = 0; - while (count >= 0 && buffer.hasRemaining()) - { + while (count >= 0 && buffer.hasRemaining()) { count = channel.read(buffer); } @@ -972,25 +872,23 @@ public static ByteBuffer readChannelToBuffer(ReadableByteChannel channel, ByteBu * bytes as a String. The bytes are interpreted according to the specified encoding, or UTF-8 if no encoding is * specified. * - * @param channel the channel to read. + * @param channel the channel to read. * @param encoding the encoding do use. If null is specified then UTF-8 is used. * * @return the string representation of the bytes in the channel decoded according to the specified encoding. * * @throws IllegalArgumentException if the stream is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static String readChannelToString(ReadableByteChannel channel, String encoding) throws IOException - { - if (channel == null) - { + public static String readChannelToString(ReadableByteChannel channel, String encoding) throws IOException { + if (channel == null) { String message = Logging.getMessage("nullValue.ChannelIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return readCharacterStreamToString( - Channels.newReader(channel, encoding != null ? encoding : DEFAULT_CHARACTER_ENCODING)); + Channels.newReader(channel, encoding != null ? encoding : DEFAULT_CHARACTER_ENCODING)); } /** @@ -1002,12 +900,10 @@ public static String readChannelToString(ReadableByteChannel channel, String enc * @return the string representing the accumulated content from the character stream. * * @throws IllegalArgumentException if the reader is null. - * @throws IOException if an I/O error occurs. + * @throws IOException if an I/O error occurs. */ - public static String readCharacterStreamToString(Reader reader) throws IOException - { - if (reader == null) - { + public static String readCharacterStreamToString(Reader reader) throws IOException { + if (reader == null) { String message = Logging.getMessage("nullValue.ReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1017,23 +913,19 @@ public static String readCharacterStreamToString(Reader reader) throws IOExcepti BufferedReader br = new BufferedReader(reader); String line; - while ((line = br.readLine()) != null) - { + while ((line = br.readLine()) != null) { sb.append(line); } return sb.toString(); } - public static ByteBuffer inflateStreamToBuffer(InputStream inputStream) throws IOException - { + public static ByteBuffer inflateStreamToBuffer(InputStream inputStream) throws IOException { return readStreamToBuffer(new InflaterInputStream(inputStream)); } - public static String replaceSuffix(String in, String newSuffix) - { - if (in == null) - { + public static String replaceSuffix(String in, String newSuffix) { + if (in == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1044,10 +936,8 @@ public static String replaceSuffix(String in, String newSuffix) return p >= 0 ? in.substring(0, p) + suffix : in + suffix; } - public static String getSuffix(String filePath) - { - if (filePath == null) - { + public static String getSuffix(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1058,8 +948,7 @@ public static String getSuffix(String filePath) String suffix = (p >= 0 && p + 1 < len) ? filePath.substring(p + 1, len) : null; // handle .bil.gz extensions - if (null != suffix && p > 0 && "gz".equals(suffix)) - { + if (null != suffix && p > 0 && "gz".equals(suffix)) { int idx = filePath.lastIndexOf(".", p - 1); suffix = (idx >= 0 && idx + 1 < len) ? filePath.substring(idx + 1, len) : suffix; } @@ -1077,10 +966,8 @@ public static String getSuffix(String filePath) * * @throws IllegalArgumentException if the file path is null. */ - public static String getFilename(String filePath) - { - if (filePath == null) - { + public static String getFilename(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1090,8 +977,9 @@ public static String getFilename(String filePath) int len = filePath.length(); int p = filePath.lastIndexOf("/"); - if (p < 0) + if (p < 0) { p = filePath.lastIndexOf("\\"); + } return (p >= 0 && p + 1 < len) ? filePath.substring(p + 1, len) : null; } @@ -1104,10 +992,8 @@ public static String getFilename(String filePath) * * @throws IllegalArgumentException if the file path is null. */ - public static String getParentFilePath(String filePath) - { - if (filePath == null) - { + public static String getParentFilePath(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1117,8 +1003,9 @@ public static String getParentFilePath(String filePath) int len = filePath.length(); int p = filePath.lastIndexOf("/"); - if (p < 0) + if (p < 0) { p = filePath.lastIndexOf("\\"); + } return (p > 0 && p < len) ? filePath.substring(0, p) : null; } @@ -1128,16 +1015,14 @@ public static String getParentFilePath(String filePath) * name and is ignored. * * @param path the path whose directories are vefified to exist or be created. The last element of the path is - * ignored. + * ignored. * * @return true if all the directories in the path exist or were created. * * @throws IllegalArgumentException if the path is null. */ - public static boolean makeParentDirs(String path) - { - if (path == null) - { + public static boolean makeParentDirs(String path) { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1145,14 +1030,15 @@ public static boolean makeParentDirs(String path) String fs = File.separator; String[] pathParts = path.split("[/" + (fs.equals("/") ? "" : (fs.equals("\\") ? "\\\\" : fs)) + "]"); - if (pathParts.length <= 1) + if (pathParts.length <= 1) { return true; + } StringBuilder sb = new StringBuilder(); - for (int i = 0; i < pathParts.length - 1; i++) - { - if (pathParts[i].length() == 0) + for (int i = 0; i < pathParts.length - 1; i++) { + if (pathParts[i].length() == 0) { continue; + } sb.append(File.separator); sb.append(pathParts[i]); @@ -1166,28 +1052,27 @@ public static boolean makeParentDirs(String path) * * @return a file reference to the new directory, of null if a directory could not be created. * - * @throws IOException if a directory could not be created. + * @throws IOException if a directory could not be created. * @throws SecurityException if a security manager exists and it does not allow directory creation. */ - public static File makeTempDir() throws IOException - { + public static File makeTempDir() throws IOException { // To make a directory in the computer's temp directory, generate the name of a temp file then delete the file // and create a directory of the same name. File temp = File.createTempFile("wwj", null); - if (!temp.delete()) + if (!temp.delete()) { return null; + } - if (!temp.mkdir()) + if (!temp.mkdir()) { return null; + } return temp; } - public static File saveBufferToTempFile(ByteBuffer buffer, String suffix) throws IOException - { - if (buffer == null) - { + public static File saveBufferToTempFile(ByteBuffer buffer, String suffix) throws IOException { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1201,56 +1086,49 @@ public static File saveBufferToTempFile(ByteBuffer buffer, String suffix) throws return outputFile; } - public static boolean isFileOutOfDate(URL url, long expiryTime) - { - if (url == null) - { + public static boolean isFileOutOfDate(URL url, long expiryTime) { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { // Determine whether the file can be treated like a File, e.g., a jar entry. URI uri = url.toURI(); - if (uri.isOpaque()) + if (uri.isOpaque()) { return false; // TODO: Determine how to check the date of non-Files - + } File file = new File(uri); return file.exists() && file.lastModified() < expiryTime; - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { Logging.logger().log(Level.SEVERE, "WWIO.ExceptionValidatingFileExpiration", url); return false; } } - public static Proxy configureProxy() - { + public static Proxy configureProxy() { String proxyHost = Configuration.getStringValue(AVKey.URL_PROXY_HOST); - if (proxyHost == null) + if (proxyHost == null) { return null; + } Proxy proxy = null; - try - { + try { int proxyPort = Configuration.getIntegerValue(AVKey.URL_PROXY_PORT); String proxyType = Configuration.getStringValue(AVKey.URL_PROXY_TYPE); SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); - if (proxyType.equals("Proxy.Type.Http")) + if (proxyType.equals("Proxy.Type.Http")) { proxy = new Proxy(Proxy.Type.HTTP, addr); - else if (proxyType.equals("Proxy.Type.SOCKS")) + } else if (proxyType.equals("Proxy.Type.SOCKS")) { proxy = new Proxy(Proxy.Type.SOCKS, addr); - } - catch (Exception e) - { + } + } catch (Exception e) { Logging.logger().log(Level.WARNING, - Logging.getMessage("URLRetriever.ErrorConfiguringProxy", proxyHost), e); + Logging.getMessage("URLRetriever.ErrorConfiguringProxy", proxyHost), e); } return proxy; @@ -1261,33 +1139,36 @@ else if (proxyType.equals("Proxy.Type.SOCKS")) *

          * Only the filename suffix is consulted to determine the file's content type. * - * @param file the file to test. + * @param file the file to test. * @param mimeTypes the mime types to test for. * * @return true if the file contains a specified content type, false if the file does not contain a specified - * content type, the specified file is null, or no content types are specified. + * content type, the specified file is null, or no content types are specified. */ - public static boolean isContentType(File file, String... mimeTypes) - { - if (file == null || mimeTypes == null) + public static boolean isContentType(File file, String... mimeTypes) { + if (file == null || mimeTypes == null) { return false; + } - for (String mimeType : mimeTypes) - { - if (mimeType == null) + for (String mimeType : mimeTypes) { + if (mimeType == null) { continue; + } String typeSuffix = WWIO.makeSuffixForMimeType(mimeType); String fileSuffix = WWIO.getSuffix(file.getName()); - if (fileSuffix == null || typeSuffix == null) + if (fileSuffix == null || typeSuffix == null) { continue; + } - if (!fileSuffix.startsWith(".")) + if (!fileSuffix.startsWith(".")) { fileSuffix = "." + fileSuffix; + } - if (fileSuffix.equalsIgnoreCase(typeSuffix)) + if (fileSuffix.equalsIgnoreCase(typeSuffix)) { return true; + } } return false; @@ -1303,17 +1184,14 @@ public static boolean isContentType(File file, String... mimeTypes) * * @throws IllegalArgumentException if the mime type is null or malformed. */ - public static String makeSuffixForMimeType(String mimeType) - { - if (mimeType == null) - { + public static String makeSuffixForMimeType(String mimeType) { + if (mimeType == null) { String message = Logging.getMessage("nullValue.ImageFomat"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (!mimeType.contains("/") || mimeType.endsWith("/")) - { + if (!mimeType.contains("/") || mimeType.endsWith("/")) { String message = Logging.getMessage("generic.InvalidImageFormat"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1322,13 +1200,15 @@ public static String makeSuffixForMimeType(String mimeType) // Remove any parameters appended to this mime type before using it as a key in the mimeTypeToSuffixMap. Mime // parameters do not change the mapping from mime type to suffix. int paramIndex = mimeType.indexOf(";"); - if (paramIndex != -1) + if (paramIndex != -1) { mimeType = mimeType.substring(0, paramIndex); + } String suffix = mimeTypeToSuffixMap.get(mimeType); - if (suffix == null) + if (suffix == null) { suffix = mimeType.substring(mimeType.lastIndexOf("/") + 1); + } suffix = suffix.replaceFirst("bil32", "bil"); // if bil32, replace with "bil" suffix. suffix = suffix.replaceFirst("bil16", "bil"); // if bil16, replace with "bil" suffix. @@ -1345,18 +1225,17 @@ public static String makeSuffixForMimeType(String mimeType) * * @throws IllegalArgumentException if the file suffix is null. */ - public static String makeMimeTypeForSuffix(String suffix) - { - if (suffix == null) - { + public static String makeMimeTypeForSuffix(String suffix) { + if (suffix == null) { String message = Logging.getMessage("nullValue.FormatSuffixIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } // Strip the starting period from the suffix string, if any exists. - if (suffix.startsWith(".")) + if (suffix.startsWith(".")) { suffix = suffix.substring(1, suffix.length()); + } return suffixToMimeTypeMap.get(suffix.toLowerCase()); } @@ -1364,8 +1243,7 @@ public static String makeMimeTypeForSuffix(String suffix) protected static Map mimeTypeToSuffixMap = new HashMap(); protected static Map suffixToMimeTypeMap = new HashMap(); - static - { + static { mimeTypeToSuffixMap.put("application/acad", "dwg"); mimeTypeToSuffixMap.put("application/bil", "bil"); mimeTypeToSuffixMap.put("application/bil16", "bil"); @@ -1417,7 +1295,6 @@ public static String makeMimeTypeForSuffix(String suffix) mimeTypeToSuffixMap.put("world/x-vrml", "wrl"); //----------------------------------------------- - suffixToMimeTypeMap.put("aif", "audio/x-aiff"); suffixToMimeTypeMap.put("aifc", "audio/x-aiff"); suffixToMimeTypeMap.put("aiff", "audio/x-aiff"); @@ -1483,64 +1360,54 @@ public static String makeMimeTypeForSuffix(String suffix) * * @throws IllegalArgumentException if the mime type is null or malformed. */ - public static String makeDataTypeForMimeType(String mimeType) - { - if (mimeType == null) - { + public static String makeDataTypeForMimeType(String mimeType) { + if (mimeType == null) { String message = Logging.getMessage("nullValue.MimeTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!mimeType.contains("/") || mimeType.endsWith("/")) - { + if (!mimeType.contains("/") || mimeType.endsWith("/")) { String message = Logging.getMessage("generic.InvalidImageFormat"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (mimeType.equals("application/bil32")) + if (mimeType.equals("application/bil32")) { return AVKey.FLOAT32; - else if (mimeType.equals("application/bil16")) + } else if (mimeType.equals("application/bil16")) { return AVKey.INT16; - else if (mimeType.equals("application/bil")) + } else if (mimeType.equals("application/bil")) { return AVKey.INT16; - else if (mimeType.equals("image/bil")) + } else if (mimeType.equals("image/bil")) { return AVKey.INT16; + } return null; } - public static Object getFileOrResourceAsStream(String path, Class c) - { - if (path == null) - { + public static Object getFileOrResourceAsStream(String path, Class c) { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); throw new IllegalStateException(message); } File file = new File(path); - if (file.exists()) - { - try - { + if (file.exists()) { + try { return new FileInputStream(file); - } - catch (Exception e) - { + } catch (Exception e) { return e; } } - if (c == null) + if (c == null) { c = WWIO.class; + } - try - { + try { return c.getResourceAsStream("/" + path); - } - catch (Exception e) - { + } catch (Exception e) { return e; } } @@ -1555,8 +1422,7 @@ public static Object getFileOrResourceAsStream(String path, Class c) * * @throws IllegalArgumentException if string is null. */ - public static InputStream getInputStreamFromString(String string) - { + public static InputStream getInputStreamFromString(String string) { return getInputStreamFromString(string, DEFAULT_CHARACTER_ENCODING); } @@ -1564,28 +1430,23 @@ public static InputStream getInputStreamFromString(String string) * Creates an {@link InputStream} for the contents of a {@link String}. The method creates a copy of the string's * contents and passes a steam reference to that copy. * - * @param string the string to create a stream for. + * @param string the string to create a stream for. * @param encoding the character encoding of the string. UTF-8 is used if null. * * @return an {@link InputStream} for the string's contents. * * @throws IllegalArgumentException if string is null. */ - public static InputStream getInputStreamFromString(String string, String encoding) - { - if (string == null) - { + public static InputStream getInputStreamFromString(String string, String encoding) { + if (string == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - try - { + try { return new ByteArrayInputStream(string.getBytes(encoding != null ? encoding : DEFAULT_CHARACTER_ENCODING)); - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { throw new WWRuntimeException(e); // should never happen because encoding is always UTF-8. } } @@ -1600,17 +1461,17 @@ public static InputStream getInputStreamFromString(String string, String encodin * * @throws IllegalArgumentException if buffer is null. */ - public static InputStream getInputStreamFromByteBuffer(ByteBuffer buffer) - { - if (buffer == null) - { + public static InputStream getInputStreamFromByteBuffer(ByteBuffer buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (buffer.hasArray() && buffer.limit() == buffer.capacity()) // otherwise bytes beyond the limit are included + { return new ByteArrayInputStream(buffer.array()); + } byte[] byteArray = new byte[buffer.limit()]; buffer.get(byteArray); @@ -1626,29 +1487,24 @@ public static InputStream getInputStreamFromByteBuffer(ByteBuffer buffer) * * @return a new BufferedInputStream which wraps the specified InputStream. */ - public static BufferedInputStream getBufferedInputStream(InputStream is) - { - if (is == null) - { + public static BufferedInputStream getBufferedInputStream(InputStream is) { + if (is == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return (is instanceof BufferedInputStream && BufferedInputStream.class.equals(is.getClass())) - ? (BufferedInputStream) is : new BufferedInputStream(is); + ? (BufferedInputStream) is : new BufferedInputStream(is); } - public static boolean isAncestorOf(File file, File ancestor) - { - if (file == null) - { + public static boolean isAncestorOf(File file, File ancestor) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (ancestor == null) - { + if (ancestor == null) { String message = Logging.getMessage("nullValue.AncestorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1657,8 +1513,7 @@ public static boolean isAncestorOf(File file, File ancestor) // Traverse up the directory tree, visiting each node. If any node is equal to the specified ancestor, // then the files are related. File cur = file; - while (cur != null && !cur.equals(ancestor)) - { + while (cur != null && !cur.equals(ancestor)) { cur = cur.getParentFile(); } @@ -1667,16 +1522,13 @@ public static boolean isAncestorOf(File file, File ancestor) return cur != null; } - public static void copyFile(File source, File destination) throws IOException - { - if (source == null) - { + public static void copyFile(File source, File destination) throws IOException { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (destination == null) - { + if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1686,8 +1538,7 @@ public static void copyFile(File source, File destination) throws IOException FileOutputStream fos = null; FileChannel fic, foc; - try - { + try { fis = new FileInputStream(source); fic = fis.getChannel(); @@ -1699,67 +1550,61 @@ public static void copyFile(File source, File destination) throws IOException fis.close(); fos.close(); - } - finally - { + } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } } - public static void copyDirectory(File source, File destination, boolean copySubDirectories) throws IOException - { - if (source == null) - { + public static void copyDirectory(File source, File destination, boolean copySubDirectories) throws IOException { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (destination == null) - { + if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!destination.exists()) - //noinspection ResultOfMethodCallIgnored + if (!destination.exists()) //noinspection ResultOfMethodCallIgnored + { destination.mkdirs(); + } - if (!destination.exists()) - { + if (!destination.exists()) { String message = Logging.getMessage("generic.CannotCreateFile", destination); Logging.logger().severe(message); throw new IOException(message); } File[] fileList = source.listFiles(); - if (fileList == null) + if (fileList == null) { return; + } List childFiles = new ArrayList(); List childDirs = new ArrayList(); - for (File child : fileList) - { - if (child == null) + for (File child : fileList) { + if (child == null) { continue; + } - if (child.isDirectory()) + if (child.isDirectory()) { childDirs.add(child); - else + } else { childFiles.add(child); + } } - for (File childFile : childFiles) - { + for (File childFile : childFiles) { File destFile = new File(destination, childFile.getName()); copyFile(childFile, destFile); } - if (copySubDirectories) - { - for (File childDir : childDirs) - { + if (copySubDirectories) { + for (File childDir : childDirs) { File destDir = new File(destination, childDir.getName()); copyDirectory(childDir, destDir, copySubDirectories); } @@ -1767,38 +1612,34 @@ public static void copyDirectory(File source, File destination, boolean copySubD } @SuppressWarnings({"ResultOfMethodCallIgnored"}) - public static void deleteDirectory(File file) throws IOException - { - if (file == null) - { + public static void deleteDirectory(File file) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File[] fileList = file.listFiles(); - if (fileList != null) - { + if (fileList != null) { List childFiles = new ArrayList(); List childDirs = new ArrayList(); - for (File child : fileList) - { - if (child == null) + for (File child : fileList) { + if (child == null) { continue; + } - if (child.isDirectory()) + if (child.isDirectory()) { childDirs.add(child); - else + } else { childFiles.add(child); + } } - for (File childFile : childFiles) - { + for (File childFile : childFiles) { childFile.delete(); } - for (File childDir : childDirs) - { + for (File childDir : childDirs) { deleteDirectory(childDir); } } @@ -1809,27 +1650,21 @@ public static void deleteDirectory(File file) throws IOException * implements the {@link java.io.Closeable} interface. * * @param stream the stream to close. If null, this method does nothing. - * @param name the name of the stream to place in the log message if an exception is encountered. + * @param name the name of the stream to place in the log message if an exception is encountered. */ - public static void closeStream(Object stream, String name) - { - if (stream == null) + public static void closeStream(Object stream, String name) { + if (stream == null) { return; + } - try - { - if (stream instanceof Closeable) - { + try { + if (stream instanceof Closeable) { ((Closeable) stream).close(); - } - else - { + } else { String message = Logging.getMessage("WWIO.StreamTypeNotSupported", name != null ? name : "Unknown"); Logging.logger().warning(message); } - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionClosingStream", e, name != null ? name : "Unknown"); Logging.logger().severe(message); } @@ -1844,10 +1679,8 @@ public static void closeStream(Object stream, String name) * * @throws IllegalArgumentException if the file is null. */ - public static String readTextFile(File file) - { - if (file == null) - { + public static String readTextFile(File file) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1856,23 +1689,17 @@ public static String readTextFile(File file) StringBuilder sb = new StringBuilder(); BufferedReader reader = null; - try - { + try { reader = new BufferedReader(new FileReader(file)); String line; - while ((line = reader.readLine()) != null) - { + while ((line = reader.readLine()) != null) { sb.append(line); } - } - catch (IOException e) - { + } catch (IOException e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToReadFile", file.getPath()); Logging.logger().log(java.util.logging.Level.SEVERE, msg); return null; - } - finally - { + } finally { WWIO.closeStream(reader, file.getPath()); } @@ -1887,35 +1714,27 @@ public static String readTextFile(File file) * * @throws IllegalArgumentException if the text string or file is null. */ - public static void writeTextFile(String text, File file) - { - if (file == null) - { + public static void writeTextFile(String text, File file) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (text == null) - { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } BufferedWriter writer = null; - try - { + try { writer = new BufferedWriter(new FileWriter(file)); writer.write(text); - } - catch (IOException e) - { + } catch (IOException e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToWriteTo", file.getPath()); Logging.logger().log(java.util.logging.Level.SEVERE, msg); - } - finally - { + } finally { WWIO.closeStream(writer, file.getPath()); } } @@ -1924,18 +1743,16 @@ public static void writeTextFile(String text, File file) * Opens a file located via an absolute path or a path relative to the classpath. * * @param fileName the path of the file to open, either absolute or relative to the classpath. - * @param c the class that will be used to find a path relative to the classpath. + * @param c the class that will be used to find a path relative to the classpath. * * @return an {@link InputStream} to the open file * * @throws IllegalArgumentException if the file name is null. - * @throws WWRuntimeException if an exception occurs or the file can't be found. The causing exception is - * available via this exception's {@link Throwable#initCause(Throwable)} method. + * @throws WWRuntimeException if an exception occurs or the file can't be found. The causing exception is available + * via this exception's {@link Throwable#initCause(Throwable)} method. */ - public static InputStream openFileOrResourceStream(String fileName, Class c) - { - if (fileName == null) - { + public static InputStream openFileOrResourceStream(String fileName, Class c) { + if (fileName == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1943,8 +1760,7 @@ public static InputStream openFileOrResourceStream(String fileName, Class c) Object streamOrException = WWIO.getFileOrResourceAsStream(fileName, c); - if (streamOrException instanceof Exception) - { + if (streamOrException instanceof Exception) { String msg = Logging.getMessage("generic.CannotOpenFile", fileName); throw new WWRuntimeException(msg, (Exception) streamOrException); } @@ -1955,21 +1771,17 @@ public static InputStream openFileOrResourceStream(String fileName, Class c) /** * Create a {@link String} from a {@link ByteBuffer}. * - * @param buffer the byte buffer to convert. + * @param buffer the byte buffer to convert. * @param encoding the encoding do use. If null is specified then UTF-8 is used. * * @return the string representation of the bytes in the buffer decoded according to the specified encoding. * * @throws IllegalArgumentException if the buffer is null. - * @throws java.nio.charset.IllegalCharsetNameException - * if the specified encoding name is illegal. - * @throws java.nio.charset.UnsupportedCharsetException - * if no support for the named encoding is available. + * @throws java.nio.charset.IllegalCharsetNameException if the specified encoding name is illegal. + * @throws java.nio.charset.UnsupportedCharsetException if no support for the named encoding is available. */ - public static String byteBufferToString(ByteBuffer buffer, String encoding) - { - if (buffer == null) - { + public static String byteBufferToString(ByteBuffer buffer, String encoding) { + if (buffer == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1981,38 +1793,32 @@ public static String byteBufferToString(ByteBuffer buffer, String encoding) /** * Create a {@link String} of limited size from a {@link ByteBuffer}. * - * @param buffer the byte buffer to convert. - * @param length the maximum number of characters to read from the buffer. Must be greater than 0. + * @param buffer the byte buffer to convert. + * @param length the maximum number of characters to read from the buffer. Must be greater than 0. * @param encoding the encoding do use. If null is specified then UTF-8 is used. * * @return the string representation of the bytes in the buffer decoded according to the specified encoding. * * @throws IllegalArgumentException if the buffer is null or the length is less than 1. - * @throws java.nio.charset.IllegalCharsetNameException - * if the specified encoding name is illegal. - * @throws java.nio.charset.UnsupportedCharsetException - * if no support for the named encoding is available. + * @throws java.nio.charset.IllegalCharsetNameException if the specified encoding name is illegal. + * @throws java.nio.charset.UnsupportedCharsetException if no support for the named encoding is available. */ - public static String byteBufferToString(ByteBuffer buffer, int length, String encoding) - { - if (buffer == null) - { + public static String byteBufferToString(ByteBuffer buffer, int length, String encoding) { + if (buffer == null) { String msg = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (length < 1) - { + if (length < 1) { String msg = Logging.getMessage("generic.LengthIsInvalid", length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } CharBuffer charBuffer = Charset.forName(encoding != null ? encoding : DEFAULT_CHARACTER_ENCODING).decode( - buffer); - if (charBuffer.remaining() > length) - { + buffer); + if (charBuffer.remaining() > length) { charBuffer = charBuffer.slice(); charBuffer.limit(length); } @@ -2023,17 +1829,15 @@ public static String byteBufferToString(ByteBuffer buffer, int length, String en /** * Create a {@link ByteBuffer} from a {@link String}. * - * @param string the string to convert. + * @param string the string to convert. * @param encoding the encoding do use. If null is specified then UTF-8 is used. * * @return the ByteBuffer representation of the string decoded according to the specified encoding. * * @throws UnsupportedEncodingException if the specified encoding is not supported */ - public static ByteBuffer stringToByteBuffer(String string, String encoding) throws UnsupportedEncodingException - { - if (string == null) - { + public static ByteBuffer stringToByteBuffer(String string, String encoding) throws UnsupportedEncodingException { + if (string == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -2054,20 +1858,20 @@ public static ByteBuffer stringToByteBuffer(String string, String encoding) thro * * @throws java.io.IOException if i/o or other errors occur trying to create the reader. */ - public static java.io.Reader openReader(Object src) throws java.io.IOException - { + public static java.io.Reader openReader(Object src) throws java.io.IOException { java.io.Reader r = null; - if (src instanceof java.io.Reader) + if (src instanceof java.io.Reader) { r = (java.io.Reader) src; - else if (src instanceof java.io.InputStream) + } else if (src instanceof java.io.InputStream) { r = new java.io.InputStreamReader((java.io.InputStream) src); - else if (src instanceof java.io.File) + } else if (src instanceof java.io.File) { r = new java.io.FileReader((java.io.File) src); - else if (src instanceof java.net.URL) + } else if (src instanceof java.net.URL) { r = new java.io.InputStreamReader(((java.net.URL) src).openStream()); - else if (src instanceof String) + } else if (src instanceof String) { r = new java.io.StringReader((String) src); + } return r; } @@ -2083,41 +1887,29 @@ else if (src instanceof String) * @return an InputStream for the input source. * * @throws IllegalArgumentException if the source is null, an empty string, or is not one of the above types. - * @throws Exception if the source cannot be opened for any reason. + * @throws Exception if the source cannot be opened for any reason. */ - public static InputStream openStream(Object src) throws Exception - { - if (src == null || WWUtil.isEmpty(src)) - { + public static InputStream openStream(Object src) throws Exception { + if (src == null || WWUtil.isEmpty(src)) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (src instanceof InputStream) - { + if (src instanceof InputStream) { return (InputStream) src; - } - else if (src instanceof URL) - { + } else if (src instanceof URL) { return ((URL) src).openStream(); - } - else if (src instanceof URI) - { + } else if (src instanceof URI) { return ((URI) src).toURL().openStream(); - } - else if (src instanceof File) - { + } else if (src instanceof File) { Object streamOrException = getFileOrResourceAsStream(((File) src).getPath(), null); - if (streamOrException instanceof Exception) - { + if (streamOrException instanceof Exception) { throw (Exception) streamOrException; } return (InputStream) streamOrException; - } - else if (!(src instanceof String)) - { + } else if (!(src instanceof String)) { String message = Logging.getMessage("generic.UnrecognizedSourceType", src.toString()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2126,12 +1918,12 @@ else if (!(src instanceof String)) String sourceName = (String) src; URL url = WWIO.makeURL(sourceName); - if (url != null) + if (url != null) { return url.openStream(); + } Object streamOrException = getFileOrResourceAsStream(sourceName, null); - if (streamOrException instanceof Exception) - { + if (streamOrException instanceof Exception) { throw (Exception) streamOrException; } @@ -2149,10 +1941,8 @@ else if (!(src instanceof String)) * * @throws IllegalArgumentException if the source is null. */ - public static String getSourcePath(Object src) - { - if (src == null) - { + public static String getSourcePath(Object src) { + if (src == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2160,14 +1950,15 @@ public static String getSourcePath(Object src) String s = null; - if (src instanceof java.io.File) + if (src instanceof java.io.File) { s = ((java.io.File) src).getAbsolutePath(); - else if (src instanceof java.net.URL) + } else if (src instanceof java.net.URL) { s = ((java.net.URL) src).toExternalForm(); - else if (src instanceof java.net.URI) + } else if (src instanceof java.net.URI) { s = src.toString(); - else if (src instanceof String) + } else if (src instanceof String) { s = (String) src; + } return s; } @@ -2182,14 +1973,10 @@ else if (src instanceof String) * @see #makeURL(Object) * @see #makeURL(Object, String) */ - public static URL makeURL(String path) - { - try - { + public static URL makeURL(String path) { + try { return new URL(path); - } - catch (Exception e) - { + } catch (Exception e) { return null; } } @@ -2204,16 +1991,12 @@ public static URL makeURL(String path) * @see #makeURL(String) * @see #makeURL(Object, String) */ - public static URL makeURL(Object path) - { - try - { + public static URL makeURL(Object path) { + try { URI uri = makeURI(path); return uri != null ? uri.toURL() : null; - } - catch (Exception e) - { + } catch (Exception e) { return null; } } @@ -2222,7 +2005,7 @@ public static URL makeURL(Object path) * Creates a URL from an object. If the object does not already convert directly to a URL, a URL with a specified * protocol is created. * - * @param path the object from which to create a URL, typically a string. + * @param path the object from which to create a URL, typically a string. * @param defaultProtocol if non-null, a protocol to use if the specified path does not yet include a protocol. * * @return a URL for the specified object, or null if a URL could not be created. @@ -2230,19 +2013,16 @@ public static URL makeURL(Object path) * @see #makeURL(String) * @see #makeURL(Object) */ - public static URL makeURL(Object path, String defaultProtocol) - { - try - { + public static URL makeURL(Object path, String defaultProtocol) { + try { URL url = makeURL(path); - if (url == null && !WWUtil.isEmpty(path.toString()) && !WWUtil.isEmpty(defaultProtocol)) + if (url == null && !WWUtil.isEmpty(path.toString()) && !WWUtil.isEmpty(defaultProtocol)) { url = new URL(defaultProtocol, null, path.toString()); + } return url; - } - catch (Exception e) - { + } catch (Exception e) { return null; } } @@ -2258,21 +2038,18 @@ public static URL makeURL(Object path, String defaultProtocol) * @see #makeURL(Object) * @see #makeURL(Object, String) */ - public static URI makeURI(Object path) - { - try - { - if (path instanceof String) + public static URI makeURI(Object path) { + try { + if (path instanceof String) { return new URI((String) path); - else if (path instanceof File) + } else if (path instanceof File) { return ((File) path).toURI(); - else if (path instanceof URL) + } else if (path instanceof URL) { return ((URL) path).toURI(); - else + } else { return null; - } - catch (Exception e) - { + } + } catch (Exception e) { return null; } } @@ -2282,18 +2059,16 @@ else if (path instanceof URL) * satisfy the specified filter. If the filter is null, then all files and directories are accepted. This returns * null if the specified file is not a directory. * - * @param file the directory who's contents to list. + * @param file the directory who's contents to list. * @param filter a file filter. * * @return an array of file names denoting the files and directories in the directory denoted by the specified file, - * or null if the specified file is not a directory. + * or null if the specified file is not a directory. * * @throws IllegalArgumentException if the file is null. */ - public static String[] listChildFilenames(File file, FileFilter filter) - { - if (file == null) - { + public static String[] listChildFilenames(File file, FileFilter filter) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -2302,21 +2077,23 @@ public static String[] listChildFilenames(File file, FileFilter filter) // List the file and directory names in the specified file. If the returned array is null, then the specified // file does not denote a directory. String[] names = file.list(); - if (names == null) + if (names == null) { return null; + } ArrayList matches = new ArrayList(); // Collect the non-null pathnames which match the specified filter. - for (String filename : names) - { + for (String filename : names) { // Ignore null or empty filenames. - if (filename == null || filename.length() == 0) + if (filename == null || filename.length() == 0) { continue; + } // If the filter is null, then all pathnames are accepted. - if (filter != null && !filter.accept(new File(file, filename))) + if (filter != null && !filter.accept(new File(file, filename))) { continue; + } matches.add(filename); } @@ -2330,18 +2107,16 @@ public static String[] listChildFilenames(File file, FileFilter filter) * filter is null, then all files and directories are accepted. This returns null if the specified file is not a * directory. * - * @param file the directory tree who's contents to list. + * @param file the directory tree who's contents to list. * @param filter a file filter. * * @return an array of relative file paths naming the files and directories in the directory tree rooted by the - * specified file, or null if the specified file is not a directory. + * specified file, or null if the specified file is not a directory. * * @throws IllegalArgumentException if the file is null. */ - public static String[] listDescendantFilenames(File file, FileFilter filter) - { - if (file == null) - { + public static String[] listDescendantFilenames(File file, FileFilter filter) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -2357,20 +2132,18 @@ public static String[] listDescendantFilenames(File file, FileFilter filter) * directory tree. The returned paths are relative to the specified file. If the filter is null, then all files and * directories are accepted. This returns null if the specified file is not a directory. * - * @param file the directory tree who's contents to list. - * @param filter a file filter. + * @param file the directory tree who's contents to list. + * @param filter a file filter. * @param recurseAfterMatch true to list the contents of directory branches beneath a match; false to ignore - * branches beneath a match. + * branches beneath a match. * * @return an array of relative file paths naming the files and directories in the directory tree rooted by the - * specified file, or null if the specified file is not a directory. + * specified file, or null if the specified file is not a directory. * * @throws IllegalArgumentException if the file is null. */ - public static String[] listDescendantFilenames(File file, FileFilter filter, boolean recurseAfterMatch) - { - if (file == null) - { + public static String[] listDescendantFilenames(File file, FileFilter filter, boolean recurseAfterMatch) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -2378,8 +2151,9 @@ public static String[] listDescendantFilenames(File file, FileFilter filter, boo // List the file and directory names in the specified file. If the returned array is null, then the specified // file does not denote a directory. - if (file.list() == null) + if (file.list() == null) { return null; + } ArrayList matches = new ArrayList(); listDescendantFilenames(file, null, filter, recurseAfterMatch, matches); @@ -2388,8 +2162,7 @@ public static String[] listDescendantFilenames(File file, FileFilter filter, boo } protected static void listDescendantFilenames(File parent, String pathname, FileFilter filter, - boolean recurseAfterMatch, Collection matches) - { + boolean recurseAfterMatch, Collection matches) { // Create a file pointing to the file denoted by the parent file and child pathname string. Use the parent file // if the pathname string is null. File file = (pathname != null) ? new File(parent, pathname) : parent; @@ -2397,22 +2170,24 @@ protected static void listDescendantFilenames(File parent, String pathname, File // List the file and directory names in the specified file. Exit if the returned filename array is null, // indicating that the specified file does not denote a directory. String[] names = file.list(); - if (names == null) + if (names == null) { return; + } boolean haveMatch = false; // Collect the non-null pathnames which match the specified filter, and collect the non-null directory names // in a temporary list. - for (String filename : names) - { + for (String filename : names) { // Ignore null or empty filenames. - if (filename == null || filename.length() == 0) + if (filename == null || filename.length() == 0) { continue; + } // If the filter is null, then all pathnames are accepted. - if (filter != null && !filter.accept(new File(file, filename))) + if (filter != null && !filter.accept(new File(file, filename))) { continue; + } matches.add(appendPathPart(pathname, filename)); haveMatch = true; @@ -2420,12 +2195,12 @@ protected static void listDescendantFilenames(File parent, String pathname, File // Exit if any of the file or directories in the specified file match the file filter, and the caller has // specified to stop recursing after a match. - if (haveMatch && !recurseAfterMatch) + if (haveMatch && !recurseAfterMatch) { return; + } // Recursively process the contents of each path . - for (String filename : names) - { + for (String filename : names) { listDescendantFilenames(parent, appendPathPart(pathname, filename), filter, recurseAfterMatch, matches); } } @@ -2433,61 +2208,52 @@ protected static void listDescendantFilenames(File parent, String pathname, File /** * Skip over a specified number of bytes in an input stream. * - * @param is the input stream. + * @param is the input stream. * @param numBytes the number of bytes to skip over. * * @throws IllegalArgumentException if the specified input stream is null. - * @throws java.io.IOException is an exception occurs while skipping the bytes. + * @throws java.io.IOException is an exception occurs while skipping the bytes. */ - public static void skipBytes(InputStream is, int numBytes) throws IOException - { - if (is == null) - { + public static void skipBytes(InputStream is, int numBytes) throws IOException { + if (is == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int byteSkipped = 0; - while (byteSkipped < numBytes) - { + while (byteSkipped < numBytes) { byteSkipped += is.skip(numBytes - byteSkipped); } } - public static String[] makeCachePathForURL(URL url) - { + public static String[] makeCachePathForURL(URL url) { String cacheDir = WWIO.replaceIllegalFileNameCharacters(url.getHost()); String fileName = WWIO.replaceIllegalFileNameCharacters(url.getPath()); - return new String[] {cacheDir, fileName}; + return new String[]{cacheDir, fileName}; } - public static void reverseFloatArray(int pos, int count, float[] array) - { - if (pos < 0) - { + public static void reverseFloatArray(int pos, int count, float[] array) { + if (pos < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pos=" + pos); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (count < 0) - { + if (count < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "count=" + count); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (array == null) - { + if (array == null) { String message = "nullValue.ArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (array.length < (pos + count)) - { + if (array.length < (pos + count)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "points.length < " + (pos + count)); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2496,8 +2262,7 @@ public static void reverseFloatArray(int pos, int count, float[] array) float tmp; int i, j, mid; - for (i = 0, mid = count >> 1, j = count - 1; i < mid; i++, j--) - { + for (i = 0, mid = count >> 1, j = count - 1; i < mid; i++, j--) { tmp = array[pos + i]; array[pos + i] = array[pos + j]; array[pos + j] = tmp; @@ -2512,8 +2277,7 @@ public static void reverseFloatArray(int pos, int count, float[] array) * * @return true if the URL refers to a local resource, otherwise false. */ - public static boolean isLocalJarAddress(URL jarUrl) - { + public static boolean isLocalJarAddress(URL jarUrl) { return jarUrl != null && jarUrl.getFile().startsWith("file:"); } } diff --git a/src/gov/nasa/worldwind/util/WWMath.java b/src/gov/nasa/worldwind/util/WWMath.java index 82f422954e..f33f602935 100644 --- a/src/gov/nasa/worldwind/util/WWMath.java +++ b/src/gov/nasa/worldwind/util/WWMath.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import com.jogamp.common.nio.Buffers; @@ -24,8 +23,8 @@ * @author tag * @version $Id: WWMath.java 2191 2014-08-01 23:28:20Z dcollins $ */ -public class WWMath -{ +public class WWMath { + public static final double SECOND_TO_MILLIS = 1000.0; public static final double MINUTE_TO_MILLIS = 60.0 * SECOND_TO_MILLIS; public static final double HOUR_TO_MILLIS = 60.0 * MINUTE_TO_MILLIS; @@ -53,8 +52,7 @@ public class WWMath * * @return the log base 2 of the specified value. */ - public static double logBase2(double value) - { + public static double logBase2(double value) { return Math.log(value) / Math.log(2d); } @@ -65,8 +63,7 @@ public static double logBase2(double value) * * @return true if power of 2, else false */ - public static boolean isPowerOfTwo(int value) - { + public static boolean isPowerOfTwo(int value) { return (value == powerOfTwoCeiling(value)); } @@ -77,8 +74,7 @@ public static boolean isPowerOfTwo(int value) * * @return the value that is the nearest power of 2 greater than or equal to the reference value */ - public static int powerOfTwoCeiling(int reference) - { + public static int powerOfTwoCeiling(int reference) { int power = (int) Math.ceil(Math.log(reference) / Math.log(2d)); return (int) Math.pow(2d, power); } @@ -90,8 +86,7 @@ public static int powerOfTwoCeiling(int reference) * * @return the value that is the nearest power of 2 less than or equal to the reference value */ - public static int powerOfTwoFloor(int reference) - { + public static int powerOfTwoFloor(int reference) { int power = (int) Math.floor(Math.log(reference) / Math.log(2d)); return (int) Math.pow(2d, power); } @@ -99,19 +94,17 @@ public static int powerOfTwoFloor(int reference) /** * Populate an array with the successive powers of a number. * - * @param base the number whose powers to compute. + * @param base the number whose powers to compute. * @param numPowers the number of powers to compute. * * @return an array containing the requested values. Each element contains the value b^i, where b is the base and i - * is the element number (0, 1, etc.). + * is the element number (0, 1, etc.). */ - protected static int[] computePowers(int base, int numPowers) - { + protected static int[] computePowers(int base, int numPowers) { int[] powers = new int[numPowers]; powers[0] = 1; - for (int i = 1; i < numPowers; i++) - { + for (int i = 1; i < numPowers; i++) { powers[i] += base * powers[i - 1]; } @@ -121,70 +114,60 @@ protected static int[] computePowers(int base, int numPowers) /** * Clamps a value to a given range. * - * @param v the value to clamp. + * @param v the value to clamp. * @param min the floor. * @param max the ceiling * * @return the nearest value such that min <= v <= max. */ - public static double clamp(double v, double min, double max) - { + public static double clamp(double v, double min, double max) { return v < min ? min : v > max ? max : v; } /** * Clamps an integer value to a given range. * - * @param v the value to clamp. + * @param v the value to clamp. * @param min the floor. * @param max the ceiling * * @return the nearest value such that min <= v <= max. */ - public static int clamp(int v, int min, int max) - { + public static int clamp(int v, int min, int max) { return v < min ? min : v > max ? max : v; } /** * Returns a number between 0.0 and 1.0 indicating whether a specified floating point value is before, between or - * after the specified min and max. Returns a linear interpolation of min and max when the value is between the - * two. + * after the specified min and max. Returns a linear interpolation of min and max when the value is between the two. *

          * The returned number is undefined if min > max. Otherwise, the returned number is equivalent to the following: - *

          • 0.0 - If value < min
          • 1.0 - If value > max
          • Linear interpolation of min and max - If min - * <= value <= max
          + *
          • 0.0 - If value < min
          • 1.0 - If value > max
          • Linear interpolation of min and max - + * If min <= value <= max
          * * @param value the value to compare to the minimum and maximum. - * @param min the minimum value. - * @param max the maximum value. + * @param min the minimum value. + * @param max the maximum value. * * @return a floating point number between 0.0 and 1.0, inclusive. */ - public static double stepValue(double value, double min, double max) - { + public static double stepValue(double value, double min, double max) { // Note: when min==max this returns 0 if the value is on or before the min, and 1 if the value is after the max. // The case that would cause a divide by zero error is never evaluated. The value is always less than, equal to, // or greater than the min/max. - if (value <= min) - { + if (value <= min) { return 0; - } - else if (value >= max) - { + } else if (value >= max) { return 1; - } - else - { + } else { return (value - min) / (max - min); } } /** * Returns a number between 0.0 and 1.0 indicating whether a specified floating point value is before, between or - * after the specified min and max. Returns a smooth interpolation of min and max when the value is between the - * two. + * after the specified min and max. Returns a smooth interpolation of min and max when the value is between the two. *

          * This method's smooth interpolation is similar to the interpolation performed by {@link #stepValue(double, double, * double)}, except that the first derivative of the returned number approaches zero as the value approaches the @@ -192,31 +175,25 @@ else if (value >= max) * minimum and maximum. *

          * The returned number is undefined if min > max. Otherwise, the returned number is equivalent to the following: - *

          • 0.0 - If value < min
          • 1.0 - If value > max
          • Smooth interpolation of min and max - If min - * <= value <= max
          + *
          • 0.0 - If value < min
          • 1.0 - If value > max
          • Smooth interpolation of min and max - + * If min <= value <= max
          * * @param value the value to compare to the minimum and maximum. - * @param min the minimum value. - * @param max the maximum value. + * @param min the minimum value. + * @param max the maximum value. * * @return a floating point number between 0.0 and 1.0, inclusive. */ - public static double smoothStepValue(double value, double min, double max) - { + public static double smoothStepValue(double value, double min, double max) { // When the min and max are equivalent this cannot distinguish between the two. In this case, this returns 0 if // the value is on or before the min, and 1 if the value is after the max. The case that would cause a divide by // zero error is never evaluated. The value is always less than, equal to, or greater than the min/max. - if (value <= min) - { + if (value <= min) { return 0; - } - else if (value >= max) - { + } else if (value >= max) { return 1; - } - else - { + } else { double step = (value - min) / (max - min); return step * step * (3 - 2 * step); } @@ -234,8 +211,7 @@ else if (value >= max) * * @return the interpolation factor for v given the specified range [x, y] */ - public static double computeInterpolationFactor(double v, double x, double y) - { + public static double computeInterpolationFactor(double v, double x, double y) { return clamp((v - x) / (y - x), 0d, 1d); } @@ -252,8 +228,7 @@ public static double computeInterpolationFactor(double v, double x, double y) * * @return the linear interpolation of x and y. */ - public static double mix(double a, double x, double y) - { + public static double mix(double a, double x, double y) { double t = clamp(a, 0d, 1d); return x + t * (y - x); } @@ -275,8 +250,7 @@ public static double mix(double a, double x, double y) * * @return the smooth hermite interpolation of x and y. */ - public static double mixSmooth(double a, double x, double y) - { + public static double mixSmooth(double a, double x, double y) { double t = clamp(a, 0d, 1d); t = t * t * (3d - 2d * t); return x + t * (y - x); @@ -289,8 +263,7 @@ public static double mixSmooth(double a, double x, double y) * * @return the value converted to feet. */ - public static double convertMetersToFeet(double meters) - { + public static double convertMetersToFeet(double meters) { return (meters * METERS_TO_FEET); } @@ -301,8 +274,7 @@ public static double convertMetersToFeet(double meters) * * @return the value converted to miles. */ - public static double convertMetersToMiles(double meters) - { + public static double convertMetersToMiles(double meters) { return (meters * METERS_TO_MILES); } @@ -313,8 +285,7 @@ public static double convertMetersToMiles(double meters) * * @return the distance converted to meters. */ - public static double convertFeetToMeters(double feet) - { + public static double convertFeetToMeters(double feet) { return (feet / METERS_TO_FEET); } @@ -325,8 +296,7 @@ public static double convertFeetToMeters(double feet) * * @return time in milliseconds. */ - public static double convertSecondsToMillis(double seconds) - { + public static double convertSecondsToMillis(double seconds) { return (seconds * SECOND_TO_MILLIS); } @@ -337,8 +307,7 @@ public static double convertSecondsToMillis(double seconds) * * @return time in seconds. */ - public static double convertMillisToSeconds(double millis) - { + public static double convertMillisToSeconds(double millis) { return millis / SECOND_TO_MILLIS; } @@ -349,8 +318,7 @@ public static double convertMillisToSeconds(double millis) * * @return time in milliseconds. */ - public static double convertMinutesToMillis(double minutes) - { + public static double convertMinutesToMillis(double minutes) { return (minutes * MINUTE_TO_MILLIS); } @@ -361,8 +329,7 @@ public static double convertMinutesToMillis(double minutes) * * @return time in minutes. */ - public static double convertMillisToMinutes(double millis) - { + public static double convertMillisToMinutes(double millis) { return millis / MINUTE_TO_MILLIS; } @@ -373,8 +340,7 @@ public static double convertMillisToMinutes(double millis) * * @return time in milliseconds. */ - public static double convertHoursToMillis(double hours) - { + public static double convertHoursToMillis(double hours) { return (hours * HOUR_TO_MILLIS); } @@ -385,8 +351,7 @@ public static double convertHoursToMillis(double hours) * * @return time in hours. */ - public static double convertMillisToHours(double mills) - { + public static double convertMillisToHours(double mills) { return mills / HOUR_TO_MILLIS; } @@ -397,8 +362,7 @@ public static double convertMillisToHours(double mills) * * @return time in milliseconds. */ - public static double convertDaysToMillis(double millis) - { + public static double convertDaysToMillis(double millis) { return millis * DAY_TO_MILLIS; } @@ -409,8 +373,7 @@ public static double convertDaysToMillis(double millis) * * @return time in days. */ - public static double convertMillisToDays(double millis) - { + public static double convertMillisToDays(double millis) { return millis / DAY_TO_MILLIS; } @@ -418,24 +381,21 @@ public static double convertMillisToDays(double millis) * Returns the distance in model coordinates from the {@link gov.nasa.worldwind.View} eye point to the specified * {@link gov.nasa.worldwind.geom.Extent}. If the View eye point is inside the extent, this returns 0. * - * @param dc the {@link gov.nasa.worldwind.render.DrawContext} which the View eye point is obtained from. + * @param dc the {@link gov.nasa.worldwind.render.DrawContext} which the View eye point is obtained from. * @param extent the extent to compute the distance from. * * @return the distance from the View eye point to the extent, in model coordinates. * * @throws IllegalArgumentException if either the DrawContext or the extent is null. */ - public static double computeDistanceFromEye(DrawContext dc, Extent extent) - { - if (dc == null) - { + public static double computeDistanceFromEye(DrawContext dc, Extent extent) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (extent == null) - { + if (extent == null) { String message = Logging.getMessage("nullValue.ExtentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -447,27 +407,23 @@ public static double computeDistanceFromEye(DrawContext dc, Extent extent) /** * Returns the size in window coordinates of the specified {@link gov.nasa.worldwind.geom.Extent} from the current - * {@link gov.nasa.worldwind.View}. The returned size is an estimate of the Extent's diameter in window - * coordinates. + * {@link gov.nasa.worldwind.View}. The returned size is an estimate of the Extent's diameter in window coordinates. * - * @param dc the current draw context, from which the View is obtained from. + * @param dc the current draw context, from which the View is obtained from. * @param extent the extent to compute the window size for. * * @return size of the specified Extent from the specified View, in window coordinates (screen pixels). * * @throws IllegalArgumentException if either the DrawContext or the extent is null. */ - public static double computeSizeInWindowCoordinates(DrawContext dc, Extent extent) - { - if (dc == null) - { + public static double computeSizeInWindowCoordinates(DrawContext dc, Extent extent) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (extent == null) - { + if (extent == null) { String message = Logging.getMessage("nullValue.ExtentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -483,7 +439,6 @@ public static double computeSizeInWindowCoordinates(DrawContext dc, Extent exten // Finally, estimate W, the extent's diameter in window coordinates (screen pixels). // // W : 2R * 1/S = (2R meters / S meters) * 1 pixels = 2R/S pixels - double distance = dc.getView().getEyePoint().distanceTo3(extent.getCenter()); double pixelSize = dc.getView().computePixelSizeAtDistance(distance); return 2d * extent.getRadius() / pixelSize; @@ -497,45 +452,41 @@ public static double computeSizeInWindowCoordinates(DrawContext dc, Extent exten *

          * This returns zero if the specified radius is zero. * - * @param view the View for which to compute a projected screen area. + * @param view the View for which to compute a projected screen area. * @param center the sphere's center point, in model coordinates. * @param radius the sphere's radius, in meters. * * @return the projected screen area of the sphere in square pixels. * * @throws IllegalArgumentException if the view is null, if center is - * null, or if radius is less than zero. + * null, or if radius is less than zero. */ - public static double computeSphereProjectedArea(View view, Vec4 center, double radius) - { - if (view == null) - { + public static double computeSphereProjectedArea(View view, Vec4 center, double radius) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius < 0) - { + if (radius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius == 0) + if (radius == 0) { return 0; + } // Compute the sphere's area by scaling its radius based on the sphere's depth in eye coordinates. This provides // a good approximation of the sphere's projected area, but does not provide an exact value: the perspective // projection of a sphere is an ellipse. - // Compute the sphere's depth in eye coordinates by transforming the center point into eye coordinates and using // its absolute z-value as the depth value. Then compute the radius in pixels by dividing the radius in meters // by the number of meters per pixel at the sphere's depth. @@ -551,12 +502,11 @@ public static double computeSphereProjectedArea(View view, Vec4 center, double r * * @param coords the coordinates. This method returns null if this argument is null. * @param stride the number of floats between successive points. 0 indicates that the points are arranged one - * immediately after the other. + * immediately after the other. * * @return the computed unit-length normal vector, or null if a normal vector could not be computed. */ - public static Vec4 computeBufferNormal(FloatBuffer coords, int stride) - { + public static Vec4 computeBufferNormal(FloatBuffer coords, int stride) { Vec4[] verts = WWMath.findThreeIndependentVertices(coords, stride); return verts != null ? WWMath.computeTriangleNormal(verts[0], verts[1], verts[2]) : null; } @@ -569,8 +519,7 @@ public static Vec4 computeBufferNormal(FloatBuffer coords, int stride) * * @return the computed unit-length normal vector, or null if a normal vector could not be computed. */ - public static Vec4 computeArrayNormal(Vec4[] coords) - { + public static Vec4 computeArrayNormal(Vec4[] coords) { Vec4[] verts = WWMath.findThreeIndependentVertices(coords); return verts != null ? WWMath.computeTriangleNormal(verts[0], verts[1], verts[2]) : null; } @@ -580,48 +529,48 @@ public static Vec4 computeArrayNormal(Vec4[] coords) * * @param coords the coordinates. This method returns null if this argument is null. * @param stride the number of floats between successive points. 0 indicates that the points are arranged one - * immediately after the other. + * immediately after the other. * * @return an array of three points, or null if three non-colinear points could not be found. */ - public static Vec4[] findThreeIndependentVertices(FloatBuffer coords, int stride) - { + public static Vec4[] findThreeIndependentVertices(FloatBuffer coords, int stride) { int xstride = stride > 0 ? stride : 3; - if (coords == null || coords.limit() < 3 * xstride) + if (coords == null || coords.limit() < 3 * xstride) { return null; + } Vec4 a = new Vec4(coords.get(0), coords.get(1), coords.get(2)); Vec4 b = null; Vec4 c = null; int k = xstride; - for (; k < coords.limit(); k += xstride) - { + for (; k < coords.limit(); k += xstride) { b = new Vec4(coords.get(k), coords.get(k + 1), coords.get(k + 2)); - if (!(b.x == a.x && b.y == a.y && b.z == a.z)) + if (!(b.x == a.x && b.y == a.y && b.z == a.z)) { break; + } b = null; } - if (b == null) + if (b == null) { return null; + } - for (k += xstride; k < coords.limit(); k += xstride) - { + for (k += xstride; k < coords.limit(); k += xstride) { c = new Vec4(coords.get(k), coords.get(k + 1), coords.get(k + 2)); // if c is not coincident with a or b, and the vectors ab and bc are not colinear, break and return a, b, c - if (!((c.x == a.x && c.y == a.y && c.z == a.z) || (c.x == b.x && c.y == b.y && c.z == b.z))) - { - if (!Vec4.areColinear(a, b, c)) + if (!((c.x == a.x && c.y == a.y && c.z == a.z) || (c.x == b.x && c.y == b.y && c.z == b.z))) { + if (!Vec4.areColinear(a, b, c)) { break; + } } c = null; // reset c to signal failure to return statement below } - return c != null ? new Vec4[] {a, b, c} : null; + return c != null ? new Vec4[]{a, b, c} : null; } /** @@ -631,42 +580,42 @@ public static Vec4[] findThreeIndependentVertices(FloatBuffer coords, int stride * * @return an array of three points, or null if three non-colinear points could not be found. */ - public static Vec4[] findThreeIndependentVertices(Vec4[] coords) - { - if (coords == null || coords.length < 3) + public static Vec4[] findThreeIndependentVertices(Vec4[] coords) { + if (coords == null || coords.length < 3) { return null; + } Vec4 a = coords[0]; Vec4 b = null; Vec4 c = null; int k = 1; - for (; k < coords.length; k++) - { + for (; k < coords.length; k++) { b = coords[k]; - if (!(b.x == a.x && b.y == a.y && b.z == a.z)) + if (!(b.x == a.x && b.y == a.y && b.z == a.z)) { break; + } b = null; } - if (b == null) + if (b == null) { return null; + } - for (; k < coords.length; k++) - { + for (; k < coords.length; k++) { c = coords[k]; // if c is not coincident with a or b, and the vectors ab and bc are not colinear, break and return a, b, c - if (!((c.x == a.x && c.y == a.y && c.z == a.z) || (c.x == b.x && c.y == b.y && c.z == b.z))) - { - if (!Vec4.areColinear(a, b, c)) + if (!((c.x == a.x && c.y == a.y && c.z == a.z) || (c.x == b.x && c.y == b.y && c.z == b.z))) { + if (!Vec4.areColinear(a, b, c)) { break; + } } c = null; // reset c to signal failure to return statement below } - return c != null ? new Vec4[] {a, b, c} : null; + return c != null ? new Vec4[]{a, b, c} : null; } /** @@ -680,10 +629,8 @@ public static Vec4[] findThreeIndependentVertices(Vec4[] coords) * * @throws IllegalArgumentException if any of the specified vertices are null. */ - public static Vec4 computeTriangleNormal(Vec4 a, Vec4 b, Vec4 c) - { - if (a == null || b == null || c == null) - { + public static Vec4 computeTriangleNormal(Vec4 a, Vec4 b, Vec4 c) { + if (a == null || b == null || c == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -694,8 +641,9 @@ public static Vec4 computeTriangleNormal(Vec4 a, Vec4 b, Vec4 c) double z = ((b.x - a.x) * (c.y - a.y)) - ((b.y - a.y) * (c.x - a.x)); double length = (x * x) + (y * y) + (z * z); - if (length == 0d) + if (length == 0d) { return new Vec4(x, y, z); + } length = Math.sqrt(length); return new Vec4(x / length, y / length, z / length); @@ -712,18 +660,15 @@ public static Vec4 computeTriangleNormal(Vec4 a, Vec4 b, Vec4 c) * * @throws IllegalArgumentException if points is null. */ - public static double computePolygonAreaFromVertices(Iterable points) - { - if (points == null) - { + public static double computePolygonAreaFromVertices(Iterable points) { + if (points == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.util.Iterator iter = points.iterator(); - if (!iter.hasNext()) - { + if (!iter.hasNext()) { return 0; } @@ -731,8 +676,7 @@ public static double computePolygonAreaFromVertices(Iterable poi Vec4 firstPoint = iter.next(); Vec4 point = firstPoint; - while (iter.hasNext()) - { + while (iter.hasNext()) { Vec4 nextLocation = iter.next(); area += point.x * nextLocation.y; @@ -742,8 +686,7 @@ public static double computePolygonAreaFromVertices(Iterable poi } // Include the area connecting the last point to the first point, if they're not already equal. - if (!point.equals(firstPoint)) - { + if (!point.equals(firstPoint)) { area += point.x * firstPoint.y; area -= firstPoint.x * point.y; } @@ -759,30 +702,29 @@ public static double computePolygonAreaFromVertices(Iterable poi * @param locations the locations defining the geographic polygon. * * @return {@link AVKey#CLOCKWISE} if the polygon has clockwise winding order, and {@link AVKey#COUNTER_CLOCKWISE} - * otherwise. + * otherwise. */ - public static String computeWindingOrderOfLocations(Iterable locations) - { - if (locations == null) - { + public static String computeWindingOrderOfLocations(Iterable locations) { + if (locations == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.util.Iterator iter = locations.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return AVKey.COUNTER_CLOCKWISE; + } - if (LatLon.locationsCrossDateLine(locations)) + if (LatLon.locationsCrossDateLine(locations)) { iter = LatLon.makeDatelineCrossingLocationsPositive(locations).iterator(); + } double area = 0; LatLon firstLocation = iter.next(); LatLon location = firstLocation; - while (iter.hasNext()) - { + while (iter.hasNext()) { LatLon nextLocation = iter.next(); area += location.getLongitude().degrees * nextLocation.getLatitude().degrees; @@ -792,8 +734,7 @@ public static String computeWindingOrderOfLocations(Iterable l } // Include the area connecting the last point to the first point, if they're not already equal. - if (!location.equals(firstLocation)) - { + if (!location.equals(firstLocation)) { area += location.getLongitude().degrees * firstLocation.getLatitude().degrees; area -= firstLocation.getLongitude().degrees * location.getLatitude().degrees; } @@ -808,12 +749,10 @@ public static String computeWindingOrderOfLocations(Iterable l * @param points the (x, y) points which define the 2D polygon. * * @return AVKey.CLOCKWISE if the polygon has clockwise winding order about the positive z axis, and - * AVKey.COUNTER_CLOCKWISE otherwise. + * AVKey.COUNTER_CLOCKWISE otherwise. */ - public static String computeWindingOrderOfVertices(Iterable points) - { - if (points == null) - { + public static String computeWindingOrderOfVertices(Iterable points) { + if (points == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -834,14 +773,12 @@ public static String computeWindingOrderOfVertices(Iterable poin * @param points the Iterable of points for which to compute the principal axes. * * @return the normalized principal axes of the points Iterable, sorted from the most prominent axis to the least - * prominent. + * prominent. * * @throws IllegalArgumentException if the points Iterable is null. */ - public static Vec4[] computePrincipalAxes(Iterable points) - { - if (points == null) - { + public static Vec4[] computePrincipalAxes(Iterable points) { + if (points == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -850,8 +787,9 @@ public static Vec4[] computePrincipalAxes(Iterable points) // Compute the covariance matrix of the specified points Iterable. Note that Matrix.fromCovarianceOfVertices // returns null if the points Iterable is empty, or if all of the points are null. Matrix covariance = Matrix.fromCovarianceOfVertices(points); - if (covariance == null) + if (covariance == null) { return null; + } // Compute the eigenvalues and eigenvectors of the covariance matrix. Since the covariance matrix is symmetric // by definition, we can safely use the method Matrix.computeEigensystemFromSymmetricMatrix3(). @@ -862,10 +800,8 @@ public static Vec4[] computePrincipalAxes(Iterable points) // Compute an index array who's entries define the order in which the eigenValues array can be sorted in // ascending order. Integer[] indexArray = {0, 1, 2}; - Arrays.sort(indexArray, new Comparator() - { - public int compare(Integer a, Integer b) - { + Arrays.sort(indexArray, new Comparator() { + public int compare(Integer a, Integer b) { return Double.compare(eigenValues[a], eigenValues[b]); } }); @@ -873,12 +809,11 @@ public int compare(Integer a, Integer b) // Return the normalized eigenvectors in order of decreasing eigenvalue. This has the effect of returning three // normalized orthognal vectors defining a coordinate system, which are sorted from the most prominent axis to // the least prominent. - return new Vec4[] - { - eigenVectors[indexArray[2]].normalize3(), - eigenVectors[indexArray[1]].normalize3(), - eigenVectors[indexArray[0]].normalize3() - }; + return new Vec4[]{ + eigenVectors[indexArray[2]].normalize3(), + eigenVectors[indexArray[1]].normalize3(), + eigenVectors[indexArray[0]].normalize3() + }; } /** @@ -895,24 +830,21 @@ public int compare(Integer a, Integer b) * remaining elements that follow the last complete tuple. * * @param coordinates the buffer containing the point coordinates for which to compute the principal axes. - * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, - * this interprets the buffer has having tightly packed XYZ coordinate tuples. + * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, this + * interprets the buffer has having tightly packed XYZ coordinate tuples. * * @return the normalized principal axes of the points, sorted from the most prominent axis to the least prominent. * * @throws IllegalArgumentException if the buffer is null, or if the stride is less than three. */ - public static Vec4[] computePrincipalAxes(BufferWrapper coordinates, int stride) - { - if (coordinates == null) - { + public static Vec4[] computePrincipalAxes(BufferWrapper coordinates, int stride) { + if (coordinates == null) { String message = Logging.getMessage("nullValue.CoordinatesAreNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (stride < 3) - { + if (stride < 3) { String msg = Logging.getMessage("generic.StrideIsInvalid"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -921,8 +853,9 @@ public static Vec4[] computePrincipalAxes(BufferWrapper coordinates, int stride) // Compute the covariance matrix of the specified points Iterable. Note that Matrix.fromCovarianceOfVertices // returns null if the points Iterable is empty, or if all of the points are null. Matrix covariance = Matrix.fromCovarianceOfVertices(coordinates, stride); - if (covariance == null) + if (covariance == null) { return null; + } // Compute the eigenvalues and eigenvectors of the covariance matrix. Since the covariance matrix is symmetric // by definition, we can safely use the method Matrix.computeEigensystemFromSymmetricMatrix3(). @@ -933,10 +866,8 @@ public static Vec4[] computePrincipalAxes(BufferWrapper coordinates, int stride) // Compute an index array who's entries define the order in which the eigenValues array can be sorted in // ascending order. Integer[] indexArray = {0, 1, 2}; - Arrays.sort(indexArray, new Comparator() - { - public int compare(Integer a, Integer b) - { + Arrays.sort(indexArray, new Comparator() { + public int compare(Integer a, Integer b) { return Double.compare(eigenValues[a], eigenValues[b]); } }); @@ -944,12 +875,11 @@ public int compare(Integer a, Integer b) // Return the normalized eigenvectors in order of decreasing eigenvalue. This has the effect of returning three // normalized orthognal vectors defining a coordinate system, which are sorted from the most prominent axis to // the least prominent. - return new Vec4[] - { - eigenVectors[indexArray[2]].normalize3(), - eigenVectors[indexArray[1]].normalize3(), - eigenVectors[indexArray[0]].normalize3() - }; + return new Vec4[]{ + eigenVectors[indexArray[2]].normalize3(), + eigenVectors[indexArray[1]].normalize3(), + eigenVectors[indexArray[0]].normalize3() + }; } /** @@ -963,26 +893,22 @@ public int compare(Integer a, Integer b) * * @throws IllegalArgumentException if the locations are null. */ - public static boolean isPolygonClosed(Iterable locations) - { - if (locations == null) - { + public static boolean isPolygonClosed(Iterable locations) { + if (locations == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.util.Iterator iter = locations.iterator(); - if (!iter.hasNext()) - { + if (!iter.hasNext()) { return false; } LatLon firstLocation = iter.next(); LatLon lastLocation = null; - while (iter.hasNext()) - { + while (iter.hasNext()) { lastLocation = iter.next(); } @@ -1000,26 +926,22 @@ public static boolean isPolygonClosed(Iterable locations) * * @throws IllegalArgumentException if the points are null. */ - public static boolean isPolygonClosed2(Iterable points) - { - if (points == null) - { + public static boolean isPolygonClosed2(Iterable points) { + if (points == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.util.Iterator iter = points.iterator(); - if (!iter.hasNext()) - { + if (!iter.hasNext()) { return false; } Vec4 firstPoint = iter.next(); Vec4 lastPoint = null; - while (iter.hasNext()) - { + while (iter.hasNext()) { lastPoint = iter.next(); } @@ -1027,35 +949,30 @@ public static boolean isPolygonClosed2(Iterable points) } // TODO: this is only valid for linear path type - /** * Determines whether a {@link LatLon} location is located inside a given polygon. * - * @param location the location + * @param location the location * @param locations the list of positions describing the polygon. Last one should be the same as the first one. * * @return true if the location is inside the polygon. */ - public static boolean isLocationInside(LatLon location, Iterable locations) - { - if (location == null) - { + public static boolean isLocationInside(LatLon location, Iterable locations) { + if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.util.Iterator iter = locations.iterator(); - if (!iter.hasNext()) - { + if (!iter.hasNext()) { return false; } // Test for even/odd number of intersections with a constant latitude line going through the given location. boolean result = false; LatLon p1 = iter.next(); - while (iter.hasNext()) - { + while (iter.hasNext()) { LatLon p2 = iter.next(); // Developped for clarity @@ -1068,15 +985,15 @@ public static boolean isLocationInside(LatLon location, Iterablep0, p1, or p2 is null */ public static boolean computeCircleThroughPoints(Vec4 p0, Vec4 p1, Vec4 p2, Vec4[] centerOut, Vec4[] axisOut, - double[] radiusOut) - { - if (p0 == null || p1 == null || p2 == null) - { + double[] radiusOut) { + if (p0 == null || p1 == null || p2 == null) { String msg = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1132,13 +1047,15 @@ public static boolean computeCircleThroughPoints(Vec4 p0, Vec4 p1, Vec4 p2, Vec4 double E = e0 + e1 + e2; double tolerance = 1e-6; - if (Math.abs(E) <= tolerance * (max_e - min_e)) + if (Math.abs(E) <= tolerance * (max_e - min_e)) { return false; + } double radiusSquared = 0.5d * t0 * t1 * t2 / E; // the three points are collinear -- no circle with finite radius is possible - if (radiusSquared < 0d) + if (radiusSquared < 0d) { return false; + } double radius = Math.sqrt(radiusSquared); @@ -1149,12 +1066,15 @@ public static boolean computeCircleThroughPoints(Vec4 p0, Vec4 p1, Vec4 p2, Vec4 Vec4 axis = v2.cross3(v0); axis = axis.normalize3(); - if (centerOut != null) + if (centerOut != null) { centerOut[0] = center; - if (axisOut != null) + } + if (axisOut != null) { axisOut[0] = axis; - if (radiusOut != null) + } + if (radiusOut != null) { radiusOut[0] = radius; + } return true; } @@ -1163,33 +1083,28 @@ public static boolean computeCircleThroughPoints(Vec4 p0, Vec4 p1, Vec4 p2, Vec4 *

          * See "3-D Computer Graphics" by Samuel R. Buss, 2005, Section X.1.4. * - * @param line the line to intersect with the polytope. + * @param line the line to intersect with the polytope. * @param planes the planes defining the polytope. Each plane's normal must point away from the the polytope, i.e. - * each plane's positive halfspace is outside the polytope. (Note: This is the opposite convention - * from that of a view frustum.) + * each plane's positive halfspace is outside the polytope. (Note: This is the opposite convention from that of a + * view frustum.) * * @return the points of intersection, or null if the line does not intersect the polytope. Two points are returned - * if the line both enters and exits the polytope. One point is retured if the line origin is within the - * polytope. + * if the line both enters and exits the polytope. One point is retured if the line origin is within the polytope. * * @throws IllegalArgumentException if the line is null or ill-formed, the planes array is null or there are fewer - * than three planes. + * than three planes. */ - public static Intersection[] polytopeIntersect(Line line, Plane[] planes) - { - if (line == null) - { + public static Intersection[] polytopeIntersect(Line line, Plane[] planes) { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Algorithm from "3-D Computer Graphics" by Samuel R. Buss, 2005, Section X.1.4. - // Determine intersection with each plane and categorize the intersections as "front" if the line intersects // the front side of the plane (dot product of line direction with plane normal is negative) and "back" if the // line intersects the back side of the plane (dot product of line direction with plane normal is positive). - double fMax = -Double.MAX_VALUE; double bMin = Double.MAX_VALUE; boolean isTangent = false; @@ -1197,8 +1112,7 @@ public static Intersection[] polytopeIntersect(Line line, Plane[] planes) Vec4 u = line.getDirection(); Vec4 p = line.getOrigin(); - for (Plane plane : planes) - { + for (Plane plane : planes) { Vec4 n = plane.getNormal(); double d = -plane.getDistance(); @@ -1207,11 +1121,12 @@ public static Intersection[] polytopeIntersect(Line line, Plane[] planes) { double pdn = p.dot3(n); if (pdn > d) // is line in positive halfspace (in front of) of the plane? - return null; // no intersection - else { - if (pdn == d) + return null; // no intersection + } else { + if (pdn == d) { isTangent = true; // line coincident with plane + } continue; // line is in negative halfspace; possible intersection; check other planes } } @@ -1220,19 +1135,18 @@ public static Intersection[] polytopeIntersect(Line line, Plane[] planes) double a = (d - p.dot3(n)) / s; if (u.dot3(n) < 0) // line intersects front face and therefore entering polytope { - if (a > fMax) - { - if (a > bMin) + if (a > fMax) { + if (a > bMin) { return null; + } fMax = a; } - } - else // line intersects back face and therefore leaving polytope + } else // line intersects back face and therefore leaving polytope { - if (a < bMin) - { - if (a < 0 || a < fMax) + if (a < bMin) { + if (a < 0 || a < fMax) { return null; + } bMin = a; } } @@ -1240,19 +1154,20 @@ public static Intersection[] polytopeIntersect(Line line, Plane[] planes) // Compute the Cartesian intersection points. There will be no more than two. if (fMax >= 0) // intersects frontface and backface; point origin is outside the polytope - return new Intersection[] - { - new Intersection(p.add3(u.multiply3(fMax)), isTangent), - new Intersection(p.add3(u.multiply3(bMin)), isTangent) - }; - else // intersects backface only; point origin is within the polytope - return new Intersection[] {new Intersection(p.add3(u.multiply3(bMin)), isTangent)}; + { + return new Intersection[]{ + new Intersection(p.add3(u.multiply3(fMax)), isTangent), + new Intersection(p.add3(u.multiply3(bMin)), isTangent) + }; + } else // intersects backface only; point origin is within the polytope + { + return new Intersection[]{new Intersection(p.add3(u.multiply3(bMin)), isTangent)}; + } } //**************************************************************// //******************** Geometry Construction ******************// //**************************************************************// - /** * Computes an index buffer in the system native byte order that tessellates the interior of a vertex grid as a * triangle strip. The returned buffer may be used as the source buffer in a call to {@link @@ -1260,26 +1175,24 @@ public static Intersection[] polytopeIntersect(Line line, Plane[] planes) * com.jogamp.opengl.GL#GL_TRIANGLE_STRIP}, count is the number of elements remaining in the buffer, * and type is {@link com.jogamp.opengl.GL#GL_UNSIGNED_INT}. *

          - * For details the drawing OpenGL primitives, see http://www.glprogramming.com/red/chapter02.html#name14. + * For details the drawing OpenGL primitives, see + * http://www.glprogramming.com/red/chapter02.html#name14. * - * @param width the patch width, in vertices. + * @param width the patch width, in vertices. * @param height the patch height, in vertices. * * @return an index buffer that tessellate's the grid interior as a triangle strip. * * @throws IllegalArgumentException if either the width or height are less than or equal to zero. */ - public static IntBuffer computeIndicesForGridInterior(int width, int height) - { - if (width <= 0) - { + public static IntBuffer computeIndicesForGridInterior(int width, int height) { + if (width <= 0) { String message = Logging.getMessage("Geom.WidthInvalid", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("Geom.HeightInvalid", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1289,16 +1202,13 @@ public static IntBuffer computeIndicesForGridInterior(int width, int height) IntBuffer buffer = Buffers.newDirectIntBuffer(numIndices); int pos; - for (int y = 0; y < height - 1; y++) - { - if (y != 0) - { + for (int y = 0; y < height - 1; y++) { + if (y != 0) { buffer.put((width - 1) + (y - 1) * width); buffer.put(width + y * width); } - for (int x = 0; x < width; x++) - { + for (int x = 0; x < width; x++) { pos = x + y * width; buffer.put(pos + width); buffer.put(pos); @@ -1316,26 +1226,24 @@ public static IntBuffer computeIndicesForGridInterior(int width, int height) * com.jogamp.opengl.GL#GL_LINE_STRIP}, count is the number of elements remaining in the buffer, and * type is {@link com.jogamp.opengl.GL#GL_UNSIGNED_INT}. *

          - * For details the drawing OpenGL primitives, see http://www.glprogramming.com/red/chapter02.html#name14. + * For details the drawing OpenGL primitives, see + * http://www.glprogramming.com/red/chapter02.html#name14. * - * @param width the patch width, in vertices. + * @param width the patch width, in vertices. * @param height the patch height, in vertices. * * @return an index buffer that tessellates the grid outline as a line strip. * * @throws IllegalArgumentException if either the width or height are less than or equal to zero. */ - public static IntBuffer computeIndicesForGridOutline(int width, int height) - { - if (width <= 0) - { + public static IntBuffer computeIndicesForGridOutline(int width, int height) { + if (width <= 0) { String message = Logging.getMessage("Geom.WidthInvalid", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("Geom.HeightInvalid", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1344,23 +1252,19 @@ public static IntBuffer computeIndicesForGridOutline(int width, int height) int numIndices = 2 * (width + height - 2); IntBuffer buffer = Buffers.newDirectIntBuffer(numIndices); - for (int x = 0; x < width; x++) - { + for (int x = 0; x < width; x++) { buffer.put(x); } - for (int y = 1; y < height - 1; y++) - { + for (int y = 1; y < height - 1; y++) { buffer.put((width - 1) + y * width); } - for (int x = width - 1; x >= 0; x--) - { + for (int x = width - 1; x >= 0; x--) { buffer.put(x + (height - 1) * width); } - for (int y = height - 2; y >= 1; y--) - { + for (int y = height - 2; y >= 1; y--) { buffer.put(y * width); } @@ -1375,29 +1279,27 @@ public static IntBuffer computeIndicesForGridOutline(int width, int height) * 3-coordinate tuples. The 3-coordinate normal for each vertex is stored in the normal buffer at the same position * each vertex appears in the vertex buffer. *

          - * For details the drawing OpenGL primitives, see http://www.glprogramming.com/red/chapter02.html#name14. + * For details the drawing OpenGL primitives, see + * http://www.glprogramming.com/red/chapter02.html#name14. * - * @param indices indices into the vertex buffer defining a triangle strip. + * @param indices indices into the vertex buffer defining a triangle strip. * @param vertices buffer of vertex coordinate tuples used to compute the normal coordinates. - * @param normals buffer of normal coordinate tuples that receives the normal coordinates, or null to create a new - * buffer to hold the normal coordinates. + * @param normals buffer of normal coordinate tuples that receives the normal coordinates, or null to create a new + * buffer to hold the normal coordinates. * * @return buffer of normal coordinate tuples. * * @throws IllegalArgumentException if either the index buffer or the vertex buffer is null. */ public static FloatBuffer computeNormalsForIndexedTriangleStrip(IntBuffer indices, FloatBuffer vertices, - FloatBuffer normals) - { - if (indices == null) - { + FloatBuffer normals) { + if (indices == null) { String message = Logging.getMessage("nullValue.IndexBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = Logging.getMessage("nullValue.VertexBufferNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1408,12 +1310,10 @@ public static FloatBuffer computeNormalsForIndexedTriangleStrip(IntBuffer indice // If the normal buffer is null, create a new one with the capacity to store the same number of vertices as // the vertex buffer. Otherwise, initialize the normal buffer by setting all normal coordinate to zero. - if (normals == null) + if (normals == null) { normals = Buffers.newDirectFloatBuffer(3 * numVertices); - else - { - for (int i = 0; i < numVertices; i++) - { + } else { + for (int i = 0; i < numVertices; i++) { normals.put(0); normals.put(0); normals.put(0); @@ -1424,8 +1324,7 @@ public static FloatBuffer computeNormalsForIndexedTriangleStrip(IntBuffer indice // Compute the normal for each face, then add that normal to each individual vertex of the face. After this step // each normal contains the accumulated normal values from each face it contributes to. int[] triangle = new int[3]; - for (int i = 2; i < numIndices; i++) - { + for (int i = 2; i < numIndices; i++) { indices.position(i - 2); indices.get(triangle); @@ -1433,8 +1332,7 @@ public static FloatBuffer computeNormalsForIndexedTriangleStrip(IntBuffer indice // starting with an even index are clockwise, while those starting with an odd index are counter-clockwise. // Reverse the face's vertex order for even triangles to ensure that all faces have counter-clockwise // ordering. - if ((i % 2) != 0) - { + if ((i % 2) != 0) { int tmp = triangle[0]; triangle[0] = triangle[1]; triangle[1] = tmp; @@ -1450,8 +1348,7 @@ public static FloatBuffer computeNormalsForIndexedTriangleStrip(IntBuffer indice // Normalize each tuple. Each normal contains the accumulated normal values from each face it contributes to // Normalizing the tuple averages the accumulated normals from each face, and ensures that the normal has unit // length. - for (int i = 0; i < numVertices; i++) - { + for (int i = 0; i < numVertices; i++) { // Normalizes the tuple and the buffer's position then advances to the next tuple. normalize3(normals); } @@ -1465,14 +1362,13 @@ public static FloatBuffer computeNormalsForIndexedTriangleStrip(IntBuffer indice * Computes a triangle normal given the starting position of three tuples in the specified vertex buffer, and stores * adds the result to three tuples in the specified normal buffer with the same positions. * - * @param a the first tuple's starting position. - * @param b the second tuple's starting position. - * @param c the third tuple's starting position. + * @param a the first tuple's starting position. + * @param b the second tuple's starting position. + * @param c the third tuple's starting position. * @param vertices buffer of vertex coordinate tuples used to compute the normal coordinates. - * @param normals buffer of normal coordinate tuples that receives the normal coordinates. + * @param normals buffer of normal coordinate tuples that receives the normal coordinates. */ - protected static void addTriangleNormal(int a, int b, int c, FloatBuffer vertices, FloatBuffer normals) - { + protected static void addTriangleNormal(int a, int b, int c, FloatBuffer vertices, FloatBuffer normals) { vertices.position(a); float ax = vertices.get(); float ay = vertices.get(); @@ -1493,8 +1389,7 @@ protected static void addTriangleNormal(int a, int b, int c, FloatBuffer vertice float z = ((bx - ax) * (cy - ay)) - ((by - ay) * (cx - ax)); float length = (x * x) + (y * y) + (z * z); - if (length > 0d) - { + if (length > 0d) { length = (float) Math.sqrt(length); x /= length; y /= length; @@ -1537,8 +1432,7 @@ protected static void addTriangleNormal(int a, int b, int c, FloatBuffer vertice * * @throws NullPointerException if the buffer is null. */ - protected static void normalize3(FloatBuffer buffer) - { + protected static void normalize3(FloatBuffer buffer) { int pos = buffer.position(); float x = buffer.get(); @@ -1546,8 +1440,7 @@ protected static void normalize3(FloatBuffer buffer) float z = buffer.get(); float length = (x * x) + (y * y) + (z * z); - if (length > 0d) - { + if (length > 0d) { length = (float) Math.sqrt(length); x /= length; y /= length; @@ -1570,13 +1463,11 @@ protected static void normalize3(FloatBuffer buffer) * * @return a list of points defining a line between the two input points. */ - public static List bresenham(int x0, int y0, int x1, int y1) - { + public static List bresenham(int x0, int y0, int x1, int y1) { List points = new ArrayList(Math.abs(x1 - x0 + 1)); boolean steep = Math.abs(y1 - y0) > Math.abs(x1 - x0); - if (steep) - { + if (steep) { int t = x0; //noinspection SuspiciousNameCombination x0 = y0; @@ -1587,8 +1478,7 @@ public static List bresenham(int x0, int y0, int x1, int y1) y1 = t; } - if (x0 > x1) - { + if (x0 > x1) { int t = x0; x0 = x1; x1 = t; @@ -1603,15 +1493,14 @@ public static List bresenham(int x0, int y0, int x1, int y1) int ystep = y0 < y1 ? 1 : -1; int y = y0; - for (int x = x0; x <= x1; x += 1) - { - if (steep) + for (int x = x0; x <= x1; x += 1) { + if (steep) { points.add(new Point(y, x)); - else + } else { points.add(new Point(x, y)); + } error -= deltay; - if (error < 0) - { + if (error < 0) { y += ystep; error += deltax; } @@ -1624,33 +1513,29 @@ public static List bresenham(int x0, int y0, int x1, int y1) * Create positions that describe lines parallel to a control line. * * @param controlPositions List of positions along the control line. Must be greater than 1. - * @param leftPositions List to receive positions on the left line. - * @param rightPositions List to receive positions on the right line. - * @param distance Distance from the center line to the left and right lines. - * @param globe Globe used to compute positions. + * @param leftPositions List to receive positions on the left line. + * @param rightPositions List to receive positions on the right line. + * @param distance Distance from the center line to the left and right lines. + * @param globe Globe used to compute positions. * * @throws IllegalArgumentException if any of the lists are null, the number of control positions is less than 2, or - * the globe is null. + * the globe is null. */ public static void generateParallelLines(List controlPositions, List leftPositions, - List rightPositions, double distance, Globe globe) - { - if (controlPositions == null || leftPositions == null || rightPositions == null) - { + List rightPositions, double distance, Globe globe) { + if (controlPositions == null || leftPositions == null || rightPositions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPositions.size() < 2) - { + if (controlPositions.size() < 2) { String message = Logging.getMessage("generic.LengthIsInvalid"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1664,7 +1549,6 @@ public static void generateParallelLines(List controlPositions, List

          iterator = controlPositions.iterator(); Position posB = iterator.next(); @@ -1682,11 +1566,10 @@ public static void generateParallelLines(List controlPositions, List

          controlPositions, List

          leftPositions, - List rightPositions, double distance, double elevation, Globe globe, Vec4 previousOffset) - { - if ((point == null) || (prev == null && next == null)) - { + List rightPositions, double distance, double elevation, Globe globe, Vec4 previousOffset) { + if ((point == null) || (prev == null && next == null)) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (leftPositions == null || rightPositions == null) - { + if (leftPositions == null || rightPositions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1757,13 +1636,10 @@ public static Vec4 generateParallelPoints(Vec4 point, Vec4 prev, Vec4 next, List Vec4 perpendicular = backward.cross3(normal); // If the current point is co-located with either the next or prev points, then reuse the previously computed offset. - if (point.equals(prev) || (point.equals(next)) && previousOffset != null) - { + if (point.equals(prev) || (point.equals(next)) && previousOffset != null) { offset = previousOffset; - } - // If both next and previous points are supplied then calculate the angle that bisects the angle current, next, prev. - else if (next != null && prev != null && !Vec4.areColinear(prev, point, next)) - { + } // If both next and previous points are supplied then calculate the angle that bisects the angle current, next, prev. + else if (next != null && prev != null && !Vec4.areColinear(prev, point, next)) { // Compute vector in the forward direction. Vec4 forward = next.subtract3(point); @@ -1777,23 +1653,21 @@ else if (next != null && prev != null && !Vec4.areColinear(prev, point, next)) // If the angle is less than 1/10 of a degree than treat this segment as if it were linear. double length; - if (theta.degrees > 0.1) + if (theta.degrees > 0.1) { length = distance / theta.sin(); - else + } else { length = distance; + } // Compute the scalar triple product of the vector BC, the normal vector, and the offset vector to // determine if the offset points to the left or the right of the control line. double tripleProduct = perpendicular.dot3(offset); - if (tripleProduct < 0) - { + if (tripleProduct < 0) { offset = offset.multiply3(-1); } offset = offset.multiply3(length); - } - else - { + } else { offset = perpendicular.normalize3(); offset = offset.multiply3(distance); } diff --git a/src/gov/nasa/worldwind/util/WWUtil.java b/src/gov/nasa/worldwind/util/WWUtil.java index 65936bbf6a..18c0decbfd 100644 --- a/src/gov/nasa/worldwind/util/WWUtil.java +++ b/src/gov/nasa/worldwind/util/WWUtil.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.avlist.*; @@ -20,8 +19,8 @@ * @author tag * @version $Id: WWUtil.java 2396 2014-10-27 23:46:42Z tgaskins $ */ -public class WWUtil -{ +public class WWUtil { + /** * Converts a specified string to an integer value. Returns null if the string cannot be converted. * @@ -31,26 +30,20 @@ public class WWUtil * * @throws IllegalArgumentException if the string is null. */ - public static Integer convertStringToInteger(String s) - { - if (s == null) - { + public static Integer convertStringToInteger(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { - if (s.length() == 0) - { + try { + if (s.length() == 0) { return null; } return Integer.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -66,26 +59,20 @@ public static Integer convertStringToInteger(String s) * * @throws IllegalArgumentException if the string is null. */ - public static Double convertStringToDouble(String s) - { - if (s == null) - { + public static Double convertStringToDouble(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { - if (s.length() == 0) - { + try { + if (s.length() == 0) { return null; } return Double.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -101,26 +88,20 @@ public static Double convertStringToDouble(String s) * * @throws IllegalArgumentException if the string is null. */ - public static Long convertStringToLong(String s) - { - if (s == null) - { + public static Long convertStringToLong(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { - if (s.length() == 0) - { + try { + if (s.length() == 0) { return null; } return Long.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -136,29 +117,26 @@ public static Long convertStringToLong(String s) * * @throws IllegalArgumentException if the string is null. */ - public static Boolean convertStringToBoolean(String s) - { - if (s == null) - { + public static Boolean convertStringToBoolean(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { s = s.trim(); - if (s.length() == 0) + if (s.length() == 0) { return null; + } - if (s.length() == 1) + if (s.length() == 1) { return convertNumericStringToBoolean(s); + } return Boolean.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -174,27 +152,21 @@ public static Boolean convertStringToBoolean(String s) * * @throws IllegalArgumentException if the string is null. */ - public static Boolean convertNumericStringToBoolean(String s) - { - if (s == null) - { + public static Boolean convertNumericStringToBoolean(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { - if (s.length() == 0) - { + try { + if (s.length() == 0) { return null; } Integer i = makeInteger(s); return i != null && i != 0; - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -209,19 +181,14 @@ public static Boolean convertNumericStringToBoolean(String s) * * @return the integer value parsed from the string, or null if the string cannot be parsed as an integer. */ - public static Integer makeInteger(String s) - { - if (WWUtil.isEmpty(s)) - { + public static Integer makeInteger(String s) { + if (WWUtil.isEmpty(s)) { return null; } - try - { + try { return Integer.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } } @@ -234,19 +201,14 @@ public static Integer makeInteger(String s) * * @return the long value parsed from the string, or null if the string cannot be parsed as a long. */ - public static Long makeLong(String s) - { - if (WWUtil.isEmpty(s)) - { + public static Long makeLong(String s) { + if (WWUtil.isEmpty(s)) { return null; } - try - { + try { return Long.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } } @@ -259,19 +221,14 @@ public static Long makeLong(String s) * * @return the double value parsed from the string, or null if the string cannot be parsed as a double. */ - public static Double makeDoubleForLocale(String s) - { - if (WWUtil.isEmpty(s)) - { + public static Double makeDoubleForLocale(String s) { + if (WWUtil.isEmpty(s)) { return null; } - try - { + try { return NumberFormat.getInstance().parse(s.trim()).doubleValue(); - } - catch (ParseException e) - { + } catch (ParseException e) { return null; } } @@ -284,19 +241,14 @@ public static Double makeDoubleForLocale(String s) * * @return the double value parsed from the string, or null if the string cannot be parsed as a double. */ - public static Double makeDouble(String s) - { - if (WWUtil.isEmpty(s)) - { + public static Double makeDouble(String s) { + if (WWUtil.isEmpty(s)) { return null; } - try - { + try { return Double.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } } @@ -312,36 +264,30 @@ public static Double makeDouble(String s) * * @throws IllegalArgumentException if the charSequence is null. */ - public static CharSequence trimCharSequence(CharSequence charSequence) - { - if (charSequence == null) - { + public static CharSequence trimCharSequence(CharSequence charSequence) { + if (charSequence == null) { String message = Logging.getMessage("nullValue.CharSequenceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int len = charSequence.length(); - if (len == 0) - { + if (len == 0) { return charSequence; } int start, end; - for (start = 0; (start < len) && charSequence.charAt(start) == ' '; start++) - { + for (start = 0; (start < len) && charSequence.charAt(start) == ' '; start++) { } - for (end = charSequence.length() - 1; (end > start) && charSequence.charAt(end) == ' '; end--) - { + for (end = charSequence.length() - 1; (end > start) && charSequence.charAt(end) == ' '; end--) { } return charSequence.subSequence(start, end + 1); } - public static void alignComponent(Component parent, Component child, String alignment) - { + public static void alignComponent(Component parent, Component child, String alignment) { Dimension prefSize = child.getPreferredSize(); java.awt.Point parentLocation = parent != null ? parent.getLocation() : new java.awt.Point(0, 0); Dimension parentSize = parent != null ? parent.getSize() : Toolkit.getDefaultToolkit().getScreenSize(); @@ -349,23 +295,16 @@ public static void alignComponent(Component parent, Component child, String alig int x = parentLocation.x; int y = parentLocation.y; - if (alignment != null && alignment.equals(AVKey.RIGHT)) - { + if (alignment != null && alignment.equals(AVKey.RIGHT)) { x += parentSize.width - 50; y += parentSize.height - prefSize.height; - } - else if (alignment != null && alignment.equals(AVKey.CENTER)) - { + } else if (alignment != null && alignment.equals(AVKey.CENTER)) { x += (parentSize.width - prefSize.width) / 2; y += (parentSize.height - prefSize.height) / 2; - } - else if (alignment != null && alignment.equals(AVKey.LEFT_OF_CENTER)) - { + } else if (alignment != null && alignment.equals(AVKey.LEFT_OF_CENTER)) { x += parentSize.width / 2 - 1.05 * prefSize.width; y += (parentSize.height - prefSize.height) / 2; - } - else if (alignment != null && alignment.equals(AVKey.RIGHT_OF_CENTER)) - { + } else if (alignment != null && alignment.equals(AVKey.RIGHT_OF_CENTER)) { x += parentSize.width / 2 + 0.05 * prefSize.width; y += (parentSize.height - prefSize.height) / 2; } @@ -385,17 +324,15 @@ else if (alignment != null && alignment.equals(AVKey.RIGHT_OF_CENTER)) * * @return a new color with random red, green and blue components. */ - public static Color makeRandomColor(Color color) - { - if (color == null) - { + public static Color makeRandomColor(Color color) { + if (color == null) { color = Color.WHITE; } float[] cc = color.getRGBComponents(null); return new Color(cc[0] * (float) Math.random(), cc[1] * (float) Math.random(), cc[2] * (float) Math.random(), - cc[3]); + cc[3]); } /** @@ -405,39 +342,34 @@ public static Color makeRandomColor(Color color) *

          * Unless there's a reason to use a specific input color, the best color to use is white. * - * @param color the color to generate a random color from. If null, the color white (0x000000aa) is used. + * @param color the color to generate a random color from. If null, the color white (0x000000aa) is used. * @param darkestColor the darkest color allowed. If any of the generated color's components are less than the - * corresponding component in this color, new colors are generated until one satisfies this - * requirement, up to the specified maximum number of attempts. - * @param maxAttempts the maximum number of attempts to create a color lighter than the specified darkestColor. If - * this limit is reached, the last color generated is returned. + * corresponding component in this color, new colors are generated until one satisfies this requirement, up to the + * specified maximum number of attempts. + * @param maxAttempts the maximum number of attempts to create a color lighter than the specified darkestColor. If + * this limit is reached, the last color generated is returned. * * @return a new color with random red, green and blue components. */ - public static Color makeRandomColor(Color color, Color darkestColor, int maxAttempts) - { + public static Color makeRandomColor(Color color, Color darkestColor, int maxAttempts) { Color randomColor = makeRandomColor(color); - if (darkestColor == null) - { + if (darkestColor == null) { return randomColor; } float[] dc = darkestColor.getRGBComponents(null); float[] rc = randomColor.getRGBComponents(null); - for (int i = 0; i < (maxAttempts - 1) && (rc[0] < dc[0] || rc[1] < dc[1] || rc[2] < dc[2]); i++) - { + for (int i = 0; i < (maxAttempts - 1) && (rc[0] < dc[0] || rc[1] < dc[1] || rc[2] < dc[2]); i++) { rc = randomColor.getRGBComponents(null); } return randomColor; } - public static Color makeColorBrighter(Color color) - { - if (color == null) - { + public static Color makeColorBrighter(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -452,13 +384,11 @@ public static Color makeColorBrighter(Color color) saturation /= 3f; brightness *= 3f; - if (saturation < 0f) - { + if (saturation < 0f) { saturation = 0f; } - if (brightness > 1f) - { + if (brightness > 1f) { brightness = 1f; } @@ -467,10 +397,8 @@ public static Color makeColorBrighter(Color color) return new Color(rgbInt); } - public static Color makeColorDarker(Color color) - { - if (color == null) - { + public static Color makeColorDarker(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -485,13 +413,11 @@ public static Color makeColorDarker(Color color) saturation *= 3f; brightness /= 3f; - if (saturation > 1f) - { + if (saturation > 1f) { saturation = 1f; } - if (brightness < 0f) - { + if (brightness < 0f) { brightness = 0f; } @@ -500,10 +426,8 @@ public static Color makeColorDarker(Color color) return new Color(rgbInt); } - public static Color computeContrastingColor(Color color) - { - if (color == null) - { + public static Color computeContrastingColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -529,15 +453,13 @@ public static Color computeContrastingColor(Color color) * @param color2 the second color. * * @return this returns the linear interpolation of color1 and color2 if <amount> is - * between 0 and 1, a color equivalent to color1 if amount is 0 or less, or a color equivalent - * to color2 if amount is 1 or more. + * between 0 and 1, a color equivalent to color1 if amount is 0 or less, or a color equivalent to + * color2 if amount is 1 or more. * * @throws IllegalArgumentException if either color1 or color2 are null. */ - public static Color interpolateColor(double amount, Color color1, Color color2) - { - if (color1 == null || color2 == null) - { + public static Color interpolateColor(double amount, Color color1, Color color2) { + if (color1 == null || color2 == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -563,10 +485,8 @@ public static Color interpolateColor(double amount, Color color1, Color color2) * @see #decodeColorRGBA(String) * @see #encodeColorABGR(java.awt.Color) */ - public static String encodeColorRGBA(java.awt.Color color) - { - if (color == null) - { + public static String encodeColorRGBA(java.awt.Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -574,9 +494,9 @@ public static String encodeColorRGBA(java.awt.Color color) // Encode the red, green, blue, and alpha components int rgba = (color.getRed() & 0xFF) << 24 - | (color.getGreen() & 0xFF) << 16 - | (color.getBlue() & 0xFF) << 8 - | (color.getAlpha() & 0xFF); + | (color.getGreen() & 0xFF) << 16 + | (color.getBlue() & 0xFF) << 8 + | (color.getAlpha() & 0xFF); return String.format("%#08X", rgba); } @@ -591,10 +511,8 @@ public static String encodeColorRGBA(java.awt.Color color) * @see #decodeColorABGR(String) * @see #encodeColorRGBA(java.awt.Color) */ - public static String encodeColorABGR(java.awt.Color color) - { - if (color == null) - { + public static String encodeColorABGR(java.awt.Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -602,9 +520,9 @@ public static String encodeColorABGR(java.awt.Color color) // Encode the red, green, blue, and alpha components int rgba = (color.getRed() & 0xFF) - | (color.getGreen() & 0xFF) << 8 - | (color.getBlue() & 0xFF) << 16 - | (color.getAlpha() & 0xFF) << 24; + | (color.getGreen() & 0xFF) << 8 + | (color.getBlue() & 0xFF) << 16 + | (color.getAlpha() & 0xFF) << 24; return String.format("%#08X", rgba); } @@ -619,21 +537,16 @@ public static String encodeColorABGR(java.awt.Color color) * @see #decodeColorABGR(String) (String) * @see #encodeColorRGBA(java.awt.Color) */ - public static java.awt.Color decodeColorRGBA(String encodedString) - { - if (encodedString == null) - { + public static java.awt.Color decodeColorRGBA(String encodedString) { + if (encodedString == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (encodedString.startsWith("#")) - { + if (encodedString.startsWith("#")) { encodedString = encodedString.replaceFirst("#", "0x"); - } - else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) - { + } else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) { encodedString = "0x" + encodedString; } @@ -641,12 +554,9 @@ else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) // Integer.MAX_VALUE (for example, 0XFFFF). Therefore we decode the string as a long, // then keep only the lower four bytes. Long longValue; - try - { + try { longValue = Long.parseLong(encodedString.substring(2), 16); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", encodedString); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -654,10 +564,10 @@ else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) int i = (int) (longValue & 0xFFFFFFFFL); return new java.awt.Color( - (i >> 24) & 0xFF, - (i >> 16) & 0xFF, - (i >> 8) & 0xFF, - i & 0xFF); + (i >> 24) & 0xFF, + (i >> 16) & 0xFF, + (i >> 8) & 0xFF, + i & 0xFF); } /** @@ -671,21 +581,16 @@ else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) * @see #decodeColorRGBA(String) * @see #encodeColorABGR(java.awt.Color) */ - public static java.awt.Color decodeColorABGR(String encodedString) - { - if (encodedString == null) - { + public static java.awt.Color decodeColorABGR(String encodedString) { + if (encodedString == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (encodedString.startsWith("#")) - { + if (encodedString.startsWith("#")) { encodedString = encodedString.replaceFirst("#", "0x"); - } - else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) - { + } else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) { encodedString = "0x" + encodedString; } @@ -693,12 +598,9 @@ else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) // Integer.MAX_VALUE (for example, 0XFFFF). Therefore we decode the string as a long, // then keep only the lower four bytes. Long longValue; - try - { + try { longValue = Long.parseLong(encodedString.substring(2), 16); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", encodedString); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -706,10 +608,10 @@ else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) int i = (int) (longValue & 0xFFFFFFFFL); return new java.awt.Color( - i & 0xFF, - (i >> 8) & 0xFF, - (i >> 16) & 0xFF, - (i >> 24) & 0xFF); + i & 0xFF, + (i >> 8) & 0xFF, + (i >> 16) & 0xFF, + (i >> 24) & 0xFF); } /** @@ -719,8 +621,7 @@ else if (!encodedString.startsWith("0x") && !encodedString.startsWith("0X")) * * @return true if the reference is null or is a zero-length {@link String}. */ - public static boolean isEmpty(Object s) - { + public static boolean isEmpty(Object s) { return s == null || (s instanceof String && ((String) s).length() == 0); } @@ -731,8 +632,7 @@ public static boolean isEmpty(Object s) * * @return true if the list is null or zero-length. */ - public static boolean isEmpty(java.util.List list) - { + public static boolean isEmpty(java.util.List list) { return list == null || list.size() == 0; } @@ -740,11 +640,10 @@ public static boolean isEmpty(java.util.List list) * Creates a two-element array of default min and max values, typically used to initialize extreme values searches. * * @return a two-element array of extreme values. Entry 0 is the maximum double value; entry 1 is the negative of - * the maximum double value; + * the maximum double value; */ - public static double[] defaultMinMix() - { - return new double[] {Double.MAX_VALUE, -Double.MAX_VALUE}; + public static double[] defaultMinMix() { + return new double[]{Double.MAX_VALUE, -Double.MAX_VALUE}; } /** @@ -754,49 +653,42 @@ public static double[] defaultMinMix() * (longitude, latitude). Geographic locations are expressed in degrees. Tuples are replaced starting * at the buffer's position and ending at its limit. * - * @param zone the UTM zone. + * @param zone the UTM zone. * @param hemisphere the UTM hemisphere, either {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or {@link * gov.nasa.worldwind.avlist.AVKey#SOUTH}. - * @param buffer the buffer of UTM tuples to convert. + * @param buffer the buffer of UTM tuples to convert. * * @throws IllegalArgumentException if zone is outside the range 1-60, if hemisphere is - * null, if hemisphere is not one of {@link gov.nasa.worldwind.avlist.AVKey#NORTH} - * or {@link gov.nasa.worldwind.avlist.AVKey#SOUTH}, if buffer is - * null, or if the number of remaining elements in buffer is not a - * multiple of two. + * null, if hemisphere is not one of {@link gov.nasa.worldwind.avlist.AVKey#NORTH} or + * {@link gov.nasa.worldwind.avlist.AVKey#SOUTH}, if buffer is null, or if the number of remaining + * elements in buffer is not a multiple of two. */ - public static void convertUTMCoordinatesToGeographic(int zone, String hemisphere, DoubleBuffer buffer) - { - if (zone < 1 || zone > 60) - { + public static void convertUTMCoordinatesToGeographic(int zone, String hemisphere, DoubleBuffer buffer) { + if (zone < 1 || zone > 60) { String message = Logging.getMessage("generic.ZoneIsInvalid", zone); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!AVKey.NORTH.equals(hemisphere) && !AVKey.SOUTH.equals(hemisphere)) - { + if (!AVKey.NORTH.equals(hemisphere) && !AVKey.SOUTH.equals(hemisphere)) { String message = Logging.getMessage("generic.HemisphereIsInvalid", hemisphere); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if ((buffer.remaining() % 2) != 0) - { + if ((buffer.remaining() % 2) != 0) { String message = Logging.getMessage("generic.BufferSize", buffer.remaining()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - while (buffer.hasRemaining()) - { + while (buffer.hasRemaining()) { buffer.mark(); double easting = buffer.get(); double northing = buffer.get(); @@ -818,26 +710,22 @@ public static void convertUTMCoordinatesToGeographic(int zone, String hemisphere * @param buffer the buffer of geographic tuples to convert. * * @throws IllegalArgumentException if buffer is null, or if the number of remaining elements in - * buffer is not a multiple of two. + * buffer is not a multiple of two. */ - public static void normalizeGeographicCoordinates(DoubleBuffer buffer) - { - if (buffer == null) - { + public static void normalizeGeographicCoordinates(DoubleBuffer buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if ((buffer.remaining() % 2) != 0) - { + if ((buffer.remaining() % 2) != 0) { String message = Logging.getMessage("generic.BufferSize", buffer.remaining()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - while (buffer.hasRemaining()) - { + while (buffer.hasRemaining()) { buffer.mark(); Angle lon = Angle.fromDegrees(buffer.get()); Angle lat = Angle.fromDegrees(buffer.get()); @@ -854,30 +742,27 @@ public static void normalizeGeographicCoordinates(DoubleBuffer buffer) * argument, a single int argument or a single long argument. If it does, the method is * called with the specified property value argument. * - * @param parent the object on which to set the property. - * @param propertyName the name of the property. + * @param parent the object on which to set the property. + * @param propertyName the name of the property. * @param propertyValue the value to give the property. Specify double, int and long values in a - * String. + * String. * * @return the return value of the set method, or null if the method has no return value. * - * @throws IllegalArgumentException if the parent object or the property name is null. - * @throws NoSuchMethodException if no set method exists for the property name. + * @throws IllegalArgumentException if the parent object or the property name is null. + * @throws NoSuchMethodException if no set method exists for the property name. * @throws InvocationTargetException if the set method throws an exception. - * @throws IllegalAccessException if the set method is inaccessible due to access control. + * @throws IllegalAccessException if the set method is inaccessible due to access control. */ public static Object invokePropertyMethod(Object parent, String propertyName, String propertyValue) - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException - { - if (parent == null) - { + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + if (parent == null) { String message = Logging.getMessage("nullValue.nullValue.ParentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (propertyName == null) - { + if (propertyName == null) { String message = Logging.getMessage("nullValue.PropertyNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -887,67 +772,53 @@ public static Object invokePropertyMethod(Object parent, String propertyName, St try // String arg { - Method method = parent.getClass().getMethod(methodName, new Class[] {String.class}); + Method method = parent.getClass().getMethod(methodName, new Class[]{String.class}); return method != null ? method.invoke(parent, propertyValue) : null; - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // skip to next arg type } try // double arg { Double d = WWUtil.makeDouble(propertyValue); - if (d != null) - { - Method method = parent.getClass().getMethod(methodName, new Class[] {double.class}); + if (d != null) { + Method method = parent.getClass().getMethod(methodName, new Class[]{double.class}); return method != null ? method.invoke(parent, d) : null; } - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // skip to next arg type } try // int arg { Integer i = WWUtil.makeInteger(propertyValue); - if (i != null) - { - Method method = parent.getClass().getMethod(methodName, new Class[] {int.class}); + if (i != null) { + Method method = parent.getClass().getMethod(methodName, new Class[]{int.class}); return method != null ? method.invoke(parent, i) : null; } - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // skip to next arg type } try // boolean arg { Boolean b = WWUtil.convertStringToBoolean(propertyValue); - if (b != null) - { - Method method = parent.getClass().getMethod(methodName, new Class[] {boolean.class}); + if (b != null) { + Method method = parent.getClass().getMethod(methodName, new Class[]{boolean.class}); return method != null ? method.invoke(parent, b) : null; } - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // skip to next arg type } try // long arg { Long l = WWUtil.makeLong(propertyValue); - if (l != null) - { - Method method = parent.getClass().getMethod(methodName, new Class[] {long.class}); + if (l != null) { + Method method = parent.getClass().getMethod(methodName, new Class[]{long.class}); return method != null ? method.invoke(parent, l) : null; } - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // skip to next arg type } @@ -959,28 +830,23 @@ public static Object invokePropertyMethod(Object parent, String propertyName, St * The forceOverwrite controls what to do if the destination list already contains values for specified * keys. If forceOverwrite is set to true, the existing value wills be overwritten. * - * @param srcList The source list. May not be null. - * @param destList The destination list. May not be null. + * @param srcList The source list. May not be null. + * @param destList The destination list. May not be null. * @param forceOverwrite Allow overwrite existing values in the destination list - * @param keys Array of keys + * @param keys Array of keys */ - public static void copyValues(AVList srcList, AVList destList, String[] keys, boolean forceOverwrite) - { - if (WWUtil.isEmpty(srcList) || WWUtil.isEmpty(destList) || WWUtil.isEmpty(keys) || keys.length == 0) - { + public static void copyValues(AVList srcList, AVList destList, String[] keys, boolean forceOverwrite) { + if (WWUtil.isEmpty(srcList) || WWUtil.isEmpty(destList) || WWUtil.isEmpty(keys) || keys.length == 0) { return; } - for (String key : keys) - { - if (WWUtil.isEmpty(key) || !srcList.hasKey(key)) - { + for (String key : keys) { + if (WWUtil.isEmpty(key) || !srcList.hasKey(key)) { continue; } Object o = srcList.getValue(key); - if (!destList.hasKey(key) || forceOverwrite) - { + if (!destList.hasKey(key) || forceOverwrite) { destList.setValue(key, o); } } @@ -993,10 +859,8 @@ public static void copyValues(AVList srcList, AVList destList, String[] keys, bo * * @return the string with white space eliminated, or null if the input string is null. */ - public static String removeWhiteSpace(String inputString) - { - if (WWUtil.isEmpty(inputString)) - { + public static String removeWhiteSpace(String inputString) { + if (WWUtil.isEmpty(inputString)) { return inputString; } @@ -1010,39 +874,34 @@ public static String removeWhiteSpace(String inputString) * * @return A string that contains an error message */ - public static String extractExceptionReason(Throwable t) - { - if (t == null) - { + public static String extractExceptionReason(Throwable t) { + if (t == null) { return Logging.getMessage("generic.Unknown"); } StringBuilder sb = new StringBuilder(); String message = t.getMessage(); - if (!WWUtil.isEmpty(message)) + if (!WWUtil.isEmpty(message)) { sb.append(message); + } String messageClass = t.getClass().getName(); Throwable cause = t.getCause(); - if (null != cause && cause != t) - { + if (null != cause && cause != t) { String causeMessage = cause.getMessage(); String causeClass = cause.getClass().getName(); - if (!WWUtil.isEmpty(messageClass) && !WWUtil.isEmpty(causeClass) && !messageClass.equals(causeClass)) - { - if (sb.length() != 0) - { + if (!WWUtil.isEmpty(messageClass) && !WWUtil.isEmpty(causeClass) && !messageClass.equals(causeClass)) { + if (sb.length() != 0) { sb.append(" : "); } sb.append(causeClass).append(" (").append(causeMessage).append(")"); } } - if (sb.length() == 0) - { + if (sb.length() == 0) { sb.append(messageClass); } @@ -1056,15 +915,14 @@ public static String extractExceptionReason(Throwable t) * * @return String without leading period */ - public static String stripLeadingPeriod(String s) - { - if (null != s && s.startsWith(".")) + public static String stripLeadingPeriod(String s) { + if (null != s && s.startsWith(".")) { return s.substring(Math.min(1, s.length()), s.length()); + } return s; } - protected static boolean isKMLTimeShift(String timeString) - { + protected static boolean isKMLTimeShift(String timeString) { return Pattern.matches(".*[+-]+\\d\\d:\\d\\d$", timeString.trim()); } @@ -1077,18 +935,17 @@ protected static boolean isKMLTimeShift(String timeString) * @param timeString the date/time string to parse. * * @return the number of milliseconds since 00:00:00 1970 indicated by the date/time string, or null if the input - * string is null or the string is not a recognizable format. + * string is null or the string is not a recognizable format. */ - public static Long parseTimeString(String timeString) - { - if (timeString == null) + public static Long parseTimeString(String timeString) { + if (timeString == null) { return null; + } // KML allows a hybrid time zone offset that does not contain the leading "GMT", e.g. 1997-05-10T09:30:00+03:00. // If the time string has this pattern, we convert it to an RFC 822 time zone so that SimpleDateFormat can // parse it. - if (isKMLTimeShift(timeString)) - { + if (isKMLTimeShift(timeString)) { // Remove the colon from the GMT offset portion of the time string. timeString = timeString.trim(); int colonPosition = timeString.length() - 3; @@ -1096,49 +953,34 @@ public static Long parseTimeString(String timeString) timeString = newTimeString + timeString.substring(colonPosition + 1, timeString.length()); } - try - { + try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sszzzzz"); return df.parse(timeString).getTime(); - } - catch (ParseException ignored) - { + } catch (ParseException ignored) { } - try - { + try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); return df.parse(timeString).getTime(); - } - catch (ParseException ignored) - { + } catch (ParseException ignored) { } - try - { + try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); return df.parse(timeString).getTime(); - } - catch (ParseException ignored) - { + } catch (ParseException ignored) { } - try - { + try { DateFormat df = new SimpleDateFormat("yyyy-MM"); return df.parse(timeString).getTime(); - } - catch (ParseException ignored) - { + } catch (ParseException ignored) { } - try - { + try { DateFormat df = new SimpleDateFormat("yyyy"); return df.parse(timeString).getTime(); - } - catch (ParseException ignored) - { + } catch (ParseException ignored) { } return null; @@ -1153,31 +995,31 @@ public static Long parseTimeString(String timeString) * @param vb the second version string * * @return -1 if the first string is less than the second, 0 if the strings match, 1 if the first string is greater - * than the second string. + * than the second string. */ - public static int compareVersion(String va, String vb) - { - if (va == null || vb == null) - { + public static int compareVersion(String va, String vb) { + if (va == null || vb == null) { throw new IllegalArgumentException(Logging.getMessage("nullValue.StringIsNull")); } - if (va.equals(vb)) + if (va.equals(vb)) { return 0; + } String[] vas = va.split("\\."); String[] vbs = vb.split("\\."); - for (int i = 0; i < Math.max(vas.length, vbs.length); i++) - { + for (int i = 0; i < Math.max(vas.length, vbs.length); i++) { String sa = vas.length > i ? vas[i] : "0"; String sb = vbs.length > i ? vbs[i] : "0"; - if (sa.compareTo(sb) < 0) + if (sa.compareTo(sb) < 0) { return -1; + } - if (sa.compareTo(sb) > 0) + if (sa.compareTo(sb) > 0) { return 1; + } } return 0; // the versions match @@ -1187,32 +1029,27 @@ public static int compareVersion(String va, String vb) * Generates average normal vectors for the vertices of a triangle strip. * * @param vertices the triangle strip vertices. - * @param indices the indices identifying the triangle strip from the specified vertices. - * @param normals a buffer to accept the output normals. The buffer must be allocated and all its values must be - * initialized to 0. The buffer's size limit must be at least as large as that of the specified - * vertex buffer. + * @param indices the indices identifying the triangle strip from the specified vertices. + * @param normals a buffer to accept the output normals. The buffer must be allocated and all its values must be + * initialized to 0. The buffer's size limit must be at least as large as that of the specified vertex buffer. * - * @throws IllegalArgumentException if any of the specified buffers are null or the limit of the normal - * buffer is less than that of the vertex buffer. + * @throws IllegalArgumentException if any of the specified buffers are null or the limit of the normal buffer is + * less than that of the vertex buffer. */ - public static void generateTriStripNormals(FloatBuffer vertices, IntBuffer indices, FloatBuffer normals) - { - if (vertices == null || indices == null || normals == null) - { + public static void generateTriStripNormals(FloatBuffer vertices, IntBuffer indices, FloatBuffer normals) { + if (vertices == null || indices == null || normals == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (normals.limit() < vertices.limit()) - { + if (normals.limit() < vertices.limit()) { String message = Logging.getMessage("generic.BufferSize", normals.limit()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (int i = 0; i < indices.limit() - 2; i++) - { + for (int i = 0; i < indices.limit() - 2; i++) { int i1 = 3 * indices.get(i); int i2 = 3 * indices.get(i + 1); int i3 = 3 * indices.get(i + 2); @@ -1220,16 +1057,13 @@ public static void generateTriStripNormals(FloatBuffer vertices, IntBuffer indic Vec4 t0 = new Vec4(vertices.get(i1), vertices.get(i1 + 1), vertices.get(i1 + 2)); Vec4 t1 = new Vec4(vertices.get(i2), vertices.get(i2 + 1), vertices.get(i2 + 2)); Vec4 t2 = new Vec4(vertices.get(i3), vertices.get(i3 + 1), vertices.get(i3 + 2)); - Vec4 va = new Vec4(t1.x - t0.x, t1.y - t0.y, t1.z - t0.z); + Vec4 va = new Vec4(t1.x - t0.x, t1.y - t0.y, t1.z - t0.z); Vec4 vb = new Vec4(t2.x - t0.x, t2.y - t0.y, t2.z - t0.z); Vec4 facetNormal; - if (i % 2 == 0) - { + if (i % 2 == 0) { facetNormal = va.cross3(vb).normalize3(); - } - else - { + } else { facetNormal = vb.cross3(va).normalize3(); } @@ -1247,8 +1081,7 @@ public static void generateTriStripNormals(FloatBuffer vertices, IntBuffer indic } // Normalize all the computed normals. - for (int i = 0; i < indices.limit() - 2; i++) - { + for (int i = 0; i < indices.limit() - 2; i++) { int i1 = 3 * indices.get(i); int i2 = 3 * indices.get(i + 1); int i3 = 3 * indices.get(i + 2); diff --git a/src/gov/nasa/worldwind/util/WWXML.java b/src/gov/nasa/worldwind/util/WWXML.java index 3ce749f0ab..0f8b16d330 100644 --- a/src/gov/nasa/worldwind/util/WWXML.java +++ b/src/gov/nasa/worldwind/util/WWXML.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.Configuration; @@ -35,8 +34,8 @@ * @author tag * @version $Id: WWXML.java 1583 2013-09-05 23:35:23Z dcollins $ */ -public class WWXML -{ +public class WWXML { + public static final String XLINK_URI = "http://www.w3.org/1999/xlink"; /** @@ -48,32 +47,24 @@ public class WWXML * * @throws WWRuntimeException if an error occurs. */ - public static DocumentBuilder createDocumentBuilder(boolean isNamespaceAware) - { + public static DocumentBuilder createDocumentBuilder(boolean isNamespaceAware) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(isNamespaceAware); - if (Configuration.getJavaVersion() >= 1.6) - { - try - { + if (Configuration.getJavaVersion() >= 1.6) { + try { docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", - false); - } - catch (ParserConfigurationException e) - { // Note it and continue on. Some Java5 parsers don't support the feature. + false); + } catch (ParserConfigurationException e) { // Note it and continue on. Some Java5 parsers don't support the feature. String message = Logging.getMessage("XML.NonvalidatingNotSupported"); Logging.logger().finest(message); } } - try - { + try { return docBuilderFactory.newDocumentBuilder(); - } - catch (ParserConfigurationException e) - { + } catch (ParserConfigurationException e) { String message = Logging.getMessage("XML.ParserConfigurationException"); Logging.logger().finest(message); throw new WWRuntimeException(e); @@ -87,16 +78,12 @@ public static DocumentBuilder createDocumentBuilder(boolean isNamespaceAware) * * @throws WWRuntimeException if an error occurs. */ - public static Transformer createTransformer() - { + public static Transformer createTransformer() { TransformerFactory transformerFactory = TransformerFactory.newInstance(); - try - { + try { return transformerFactory.newTransformer(); - } - catch (TransformerConfigurationException e) - { + } catch (TransformerConfigurationException e) { String message = Logging.getMessage("XML.TransformerConfigurationException"); Logging.logger().finest(message); throw new WWRuntimeException(e); @@ -111,30 +98,21 @@ public static Transformer createTransformer() * @param docSource the source of the XML document. * * @return the source document as a {@link Document}, or null if the source object is a string that does not - * identify a URL, a file or a resource available on the classpath. + * identify a URL, a file or a resource available on the classpath. */ - public static Document openDocument(Object docSource) - { - if (docSource == null || WWUtil.isEmpty(docSource)) - { + public static Document openDocument(Object docSource) { + if (docSource == null || WWUtil.isEmpty(docSource)) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); throw new IllegalArgumentException(message); } - if (docSource instanceof URL) - { + if (docSource instanceof URL) { return openDocumentURL((URL) docSource); - } - else if (docSource instanceof InputStream) - { + } else if (docSource instanceof InputStream) { return openDocumentStream((InputStream) docSource); - } - else if (docSource instanceof File) - { + } else if (docSource instanceof File) { return openDocumentFile(((File) docSource).getPath(), null); - } - else if (!(docSource instanceof String)) - { + } else if (!(docSource instanceof String)) { String message = Logging.getMessage("generic.UnrecognizedSourceType", docSource.toString()); throw new IllegalArgumentException(message); } @@ -142,8 +120,9 @@ else if (!(docSource instanceof String)) String sourceName = (String) docSource; URL url = WWIO.makeURL(sourceName); - if (url != null) + if (url != null) { return openDocumentURL(url); + } return openDocumentFile(sourceName, null); } @@ -151,21 +130,17 @@ else if (!(docSource instanceof String)) /** * Opens an XML file given the file's location in the file system or on the classpath. * - * @param filePath the path to the file. Must be an absolute path or a path relative to a location in the - * classpath. - * @param c the class that is used to find a path relative to the classpath. + * @param filePath the path to the file. Must be an absolute path or a path relative to a location in the classpath. + * @param c the class that is used to find a path relative to the classpath. * * @return a DOM for the file, or null if the specified cannot be found. * * @throws IllegalArgumentException if the file path is null. - * @throws WWRuntimeException if an exception or error occurs while opening and parsing the file. The causing - * exception is included in this exception's {@link Throwable#initCause(Throwable)} - * . + * @throws WWRuntimeException if an exception or error occurs while opening and parsing the file. The causing + * exception is included in this exception's {@link Throwable#initCause(Throwable)} . */ - public static Document openDocumentFile(String filePath, Class c) - { - if (filePath == null) - { + public static Document openDocumentFile(String filePath, Class c) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FileIsNull"); throw new IllegalArgumentException(message); } @@ -183,25 +158,19 @@ public static Document openDocumentFile(String filePath, Class c) * @return a DOM for the URL. * * @throws IllegalArgumentException if the url is null. - * @throws WWRuntimeException if an exception or error occurs while opening and parsing the url. The causing - * exception is included in this exception's {@link Throwable#initCause(Throwable)} - * . + * @throws WWRuntimeException if an exception or error occurs while opening and parsing the url. The causing + * exception is included in this exception's {@link Throwable#initCause(Throwable)} . */ - public static Document openDocumentURL(URL url) - { - if (url == null) - { + public static Document openDocumentURL(URL url) { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); throw new IllegalArgumentException(message); } - try - { + try { InputStream inputStream = url.openStream(); return openDocumentStream(inputStream); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", url.toString()); throw new WWRuntimeException(message, e); } @@ -215,33 +184,25 @@ public static Document openDocumentURL(URL url) * @return a DOM for the stream content. * * @throws IllegalArgumentException if the input stream is null. - * @throws WWRuntimeException if an exception or error occurs while parsing the stream. The causing exception - * is included in this exception's {@link Throwable#initCause(Throwable)} + * @throws WWRuntimeException if an exception or error occurs while parsing the stream. The causing exception is + * included in this exception's {@link Throwable#initCause(Throwable)} */ - public static Document openDocumentStream(InputStream inputStream) - { + public static Document openDocumentStream(InputStream inputStream) { return openDocumentStream(inputStream, true); } - public static Document openDocumentStream(InputStream inputStream, boolean isNamespaceAware) - { - if (inputStream == null) - { + public static Document openDocumentStream(InputStream inputStream, boolean isNamespaceAware) { + if (inputStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); throw new IllegalArgumentException(message); } - try - { + try { return WWXML.createDocumentBuilder(isNamespaceAware).parse(inputStream); - } - catch (SAXException e) - { + } catch (SAXException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", inputStream); throw new WWRuntimeException(message, e); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", inputStream); throw new WWRuntimeException(message, e); } @@ -250,37 +211,31 @@ public static Document openDocumentStream(InputStream inputStream, boolean isNam /** * Writes an XML document to a location in the file system. * - * @param doc the DOM document to save. + * @param doc the DOM document to save. * @param filePath the path to the file. Must be an absolute path in the file system. * * @throws IllegalArgumentException if either the document or file path is null. - * @throws WWRuntimeException if an exception or error occurs while writing the document. The causing - * exception is included in this exception's {@link Throwable#initCause(Throwable)} + * @throws WWRuntimeException if an exception or error occurs while writing the document. The causing exception is + * included in this exception's {@link Throwable#initCause(Throwable)} */ - public static void saveDocumentToFile(Document doc, String filePath) - { - if (doc == null) - { + public static void saveDocumentToFile(Document doc, String filePath) { + if (doc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (filePath == null) - { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { java.io.FileOutputStream outputStream = new java.io.FileOutputStream(filePath); saveDocumentToStream(doc, outputStream); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToWriteXml", filePath); Logging.logger().severe(message); throw new WWRuntimeException(e); @@ -290,24 +245,21 @@ public static void saveDocumentToFile(Document doc, String filePath) /** * Writes an XML document to a specified outputstream stream. * - * @param doc the DOM document to save. + * @param doc the DOM document to save. * @param outputStream the outputstream to save the document contents to. * * @throws IllegalArgumentException if either the document or input stream is null. - * @throws WWRuntimeException if an exception or error occurs while writing the document. The causing - * exception is included in this exception's {@link Throwable#initCause(Throwable)} + * @throws WWRuntimeException if an exception or error occurs while writing the document. The causing exception is + * included in this exception's {@link Throwable#initCause(Throwable)} */ - public static void saveDocumentToStream(Document doc, OutputStream outputStream) - { - if (doc == null) - { + public static void saveDocumentToStream(Document doc, OutputStream outputStream) { + if (doc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (outputStream == null) - { + if (outputStream == null) { String message = Logging.getMessage("nullValue.OutputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -316,13 +268,10 @@ public static void saveDocumentToStream(Document doc, OutputStream outputStream) Source source = new DOMSource(doc); Result result = new StreamResult(outputStream); - try - { + try { Transformer transformer = createTransformer(); transformer.transform(source, result); - } - catch (TransformerException e) - { + } catch (TransformerException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToWriteXml", outputStream); Logging.logger().severe(message); throw new WWRuntimeException(e); @@ -332,19 +281,17 @@ public static void saveDocumentToStream(Document doc, OutputStream outputStream) /** * Opens an XML event stream given an input stream, and a namespace-aware processing mode. * - * @param inputStream an XML document as an input stream. + * @param inputStream an XML document as an input stream. * @param isNamespaceAware true to enable namespace-aware processing and false to disable it. * * @return an XMLEventReader for the stream content. * * @throws IllegalArgumentException if the input stream is null. - * @throws WWRuntimeException if an exception or error occurs while parsing the stream. The causing exception - * is included in this exception's {@link Throwable#initCause(Throwable)} + * @throws WWRuntimeException if an exception or error occurs while parsing the stream. The causing exception is + * included in this exception's {@link Throwable#initCause(Throwable)} */ - public static XMLEventReader openEventReaderStream(InputStream inputStream, boolean isNamespaceAware) - { - if (inputStream == null) - { + public static XMLEventReader openEventReaderStream(InputStream inputStream, boolean isNamespaceAware) { + if (inputStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -354,12 +301,9 @@ public static XMLEventReader openEventReaderStream(InputStream inputStream, bool inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, isNamespaceAware); inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); - try - { + try { return inputFactory.createXMLEventReader(inputStream); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", inputStream); throw new WWRuntimeException(message, e); } @@ -373,13 +317,11 @@ public static XMLEventReader openEventReaderStream(InputStream inputStream, bool * @return an XMLEventReader for the stream content. * * @throws IllegalArgumentException if the input stream is null. - * @throws WWRuntimeException if an exception or error occurs while parsing the stream. The causing exception - * is included in this exception's {@link Throwable#initCause(Throwable)} + * @throws WWRuntimeException if an exception or error occurs while parsing the stream. The causing exception is + * included in this exception's {@link Throwable#initCause(Throwable)} */ - public static XMLEventReader openEventReaderStream(InputStream inputStream) - { - if (inputStream == null) - { + public static XMLEventReader openEventReaderStream(InputStream inputStream) { + if (inputStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -391,21 +333,18 @@ public static XMLEventReader openEventReaderStream(InputStream inputStream) /** * Opens an XML event stream given the file's location in the file system or on the classpath. * - * @param filePath the path to the file. Must be an absolute path or a path relative to a location in the - * classpath. - * @param c the class that is used to find a path relative to the classpath. + * @param filePath the path to the file. Must be an absolute path or a path relative to a location in the classpath. + * @param c the class that is used to find a path relative to the classpath. * @param isNamespaceAware true to enable namespace-aware processing and false to disable it. * * @return an XMLEventReader for the file, or null if the specified cannot be found. * * @throws IllegalArgumentException if the file path is null. - * @throws WWRuntimeException if an exception or error occurs while opening and parsing the file. The causing - * exception is included in this exception's {@link Throwable#initCause(Throwable)}. + * @throws WWRuntimeException if an exception or error occurs while opening and parsing the file. The causing + * exception is included in this exception's {@link Throwable#initCause(Throwable)}. */ - public static XMLEventReader openEventReaderFile(String filePath, Class c, boolean isNamespaceAware) - { - if (filePath == null) - { + public static XMLEventReader openEventReaderFile(String filePath, Class c, boolean isNamespaceAware) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -419,31 +358,26 @@ public static XMLEventReader openEventReaderFile(String filePath, Class c, boole /** * Open an XML event stream given a generic {@link java.net.URL} reference. * - * @param url the URL to the document. + * @param url the URL to the document. * @param isNamespaceAware true to enable namespace-aware processing and false to disable it. * * @return an XMLEventReader for the URL. * * @throws IllegalArgumentException if the url is null. - * @throws WWRuntimeException if an exception or error occurs while opening and parsing the url. The causing - * exception is included in this exception's {@link Throwable#initCause(Throwable)}. + * @throws WWRuntimeException if an exception or error occurs while opening and parsing the url. The causing + * exception is included in this exception's {@link Throwable#initCause(Throwable)}. */ - public static XMLEventReader openEventReaderURL(URL url, boolean isNamespaceAware) - { - if (url == null) - { + public static XMLEventReader openEventReaderURL(URL url, boolean isNamespaceAware) { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { InputStream inputStream = url.openStream(); return openEventReaderStream(inputStream, isNamespaceAware); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", url.toString()); throw new WWRuntimeException(message, e); } @@ -457,10 +391,9 @@ public static XMLEventReader openEventReaderURL(URL url, boolean isNamespaceAwar * @param docSource the source of the XML document. * * @return the source document as a {@link javax.xml.stream.XMLEventReader}, or null if the source object is a - * string that does not identify a URL, a file or a resource available on the classpath. + * string that does not identify a URL, a file or a resource available on the classpath. */ - public static XMLEventReader openEventReader(Object docSource) - { + public static XMLEventReader openEventReader(Object docSource) { return openEventReader(docSource, true); } @@ -469,40 +402,29 @@ public static XMLEventReader openEventReader(Object docSource) * URL}

        • {@link InputStream}
        • {@link File}
        • {@link String} containing a valid URL * description or a file or resource name available on the classpath.
        • * - * @param docSource the source of the XML document. + * @param docSource the source of the XML document. * @param isNamespaceAware true to enable namespace-aware processing and false to disable it. * * @return the source document as a {@link javax.xml.stream.XMLEventReader}, or null if the source object is a - * string that does not identify a URL, a file or a resource available on the classpath. + * string that does not identify a URL, a file or a resource available on the classpath. */ - public static XMLEventReader openEventReader(Object docSource, boolean isNamespaceAware) - { - if (docSource == null || WWUtil.isEmpty(docSource)) - { + public static XMLEventReader openEventReader(Object docSource, boolean isNamespaceAware) { + if (docSource == null || WWUtil.isEmpty(docSource)) { String message = Logging.getMessage("nullValue.DocumentSourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (docSource instanceof URL) - { + if (docSource instanceof URL) { return openEventReaderURL((URL) docSource, isNamespaceAware); - } - else if (docSource instanceof InputStream) - { + } else if (docSource instanceof InputStream) { return openEventReaderStream((InputStream) docSource, isNamespaceAware); - } - else if (docSource instanceof File) - { + } else if (docSource instanceof File) { return openEventReaderFile(((File) docSource).getPath(), null, isNamespaceAware); - } - else if (docSource instanceof java.nio.ByteBuffer) - { + } else if (docSource instanceof java.nio.ByteBuffer) { InputStream is = WWIO.getInputStreamFromByteBuffer((java.nio.ByteBuffer) docSource); return openEventReaderStream(is, isNamespaceAware); - } - else if (!(docSource instanceof String)) - { + } else if (!(docSource instanceof String)) { String message = Logging.getMessage("generic.UnrecognizedSourceType", docSource.toString()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -511,8 +433,9 @@ else if (!(docSource instanceof String)) String sourceName = (String) docSource; URL url = WWIO.makeURL(sourceName); - if (url != null) + if (url != null) { return openEventReaderURL(url, isNamespaceAware); + } return openEventReaderFile(sourceName, null, isNamespaceAware); } @@ -521,21 +444,18 @@ else if (!(docSource instanceof String)) * Close an XML event stream and catch any {@link javax.xml.stream.XMLStreamException} generated in the process. * * @param eventReader the event reader to close. If null, this method does nothing. - * @param name the name of the event reader to place in the log message if an exception is encountered. + * @param name the name of the event reader to place in the log message if an exception is encountered. */ - public static void closeEventReader(XMLEventReader eventReader, String name) - { - if (eventReader == null) + public static void closeEventReader(XMLEventReader eventReader, String name) { + if (eventReader == null) { return; + } - try - { + try { eventReader.close(); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { String message = Logging.getMessage("generic.ExceptionClosingXmlEventReader", - name != null ? name : "Unknown"); + name != null ? name : "Unknown"); Logging.logger().severe(message); } } @@ -548,24 +468,23 @@ public static void closeEventReader(XMLEventReader eventReader, String name) * @param output the output destination for the XML document stream. * * @return the XMLStreamWriter that writes to the specified output, or null - * if the output type is not recognized. + * if the output type is not recognized. * * @throws IllegalArgumentException if output is null. - * @throws XMLStreamException if an exception occurs while attempting to open the XMLStreamWriter. + * @throws XMLStreamException if an exception occurs while attempting to open the XMLStreamWriter. */ - public static XMLStreamWriter openStreamWriter(Object output) throws XMLStreamException - { - if (output == null) - { + public static XMLStreamWriter openStreamWriter(Object output) throws XMLStreamException { + if (output == null) { String message = Logging.getMessage("nullValue.OutputIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output instanceof OutputStream) + if (output instanceof OutputStream) { return XMLOutputFactory.newInstance().createXMLStreamWriter((OutputStream) output); - else if (output instanceof Writer) + } else if (output instanceof Writer) { return XMLOutputFactory.newInstance().createXMLStreamWriter((Writer) output); + } return null; } @@ -580,29 +499,24 @@ else if (output instanceof Writer) * * @throws IllegalArgumentException if the event reader is null. */ - public static StartElement nextStartElementEvent(XMLEventReader eventReader) - { - if (eventReader == null) - { + public static StartElement nextStartElementEvent(XMLEventReader eventReader) { + if (eventReader == null) { String message = Logging.getMessage("nullValue.EventReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { XMLEvent event = null; - while (eventReader.hasNext()) - { + while (eventReader.hasNext()) { event = eventReader.nextEvent(); - if (event != null && event.isStartElement()) + if (event != null && event.isStartElement()) { break; + } } return (event != null && event.isStartElement()) ? (StartElement) event : null; - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", eventReader); Logging.logger().finest(message); } @@ -612,11 +526,11 @@ public static StartElement nextStartElementEvent(XMLEventReader eventReader) /** * Returns a string containing the text from all character nodes under the current element appended into a single - * continuous string. After this method returns the specified eventReader is positioned at the end element - * of the eventReader's current element. + * continuous string. After this method returns the specified eventReader is positioned at the end element of the + * eventReader's current element. * - * This returns the empty string if there are no character nodes under the current element, or if the element contains - * only whitespace. + * This returns the empty string if there are no character nodes under the current element, or if the element + * contains only whitespace. * * @param eventReader the stream to poll for XML events. * @@ -624,10 +538,8 @@ public static StartElement nextStartElementEvent(XMLEventReader eventReader) * * @throws IllegalArgumentException if the event reader is null. */ - public static String readCharacters(XMLEventReader eventReader) - { - if (eventReader == null) - { + public static String readCharacters(XMLEventReader eventReader) { + if (eventReader == null) { String message = Logging.getMessage("nullValue.EventReaderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -635,42 +547,29 @@ public static String readCharacters(XMLEventReader eventReader) StringBuilder sb = new StringBuilder(); - try - { + try { int depth = 0; - while (eventReader.hasNext()) - { + while (eventReader.hasNext()) { XMLEvent nextEvent = eventReader.peek(); - if (nextEvent.isStartElement()) - { + if (nextEvent.isStartElement()) { ++depth; eventReader.nextEvent(); // consume the event - } - else if (nextEvent.isEndElement()) - { - if (--depth > 0) - { + } else if (nextEvent.isEndElement()) { + if (--depth > 0) { eventReader.nextEvent(); // consume the event - } - else - { + } else { break; // stop parsing at the end element that corresponds to the root start element } - } - else if (nextEvent.isCharacters()) - { + } else if (nextEvent.isCharacters()) { Characters characters = eventReader.nextEvent().asCharacters(); // consume the event - if (!characters.isWhiteSpace()) + if (!characters.isWhiteSpace()) { sb.append(characters.getData()); - } - else - { + } + } else { eventReader.nextEvent(); // consume the event } } - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", eventReader); Logging.logger().finest(message); } @@ -683,44 +582,38 @@ else if (nextEvent.isCharacters()) * * @return a new XPath. */ - public static XPath makeXPath() - { + public static XPath makeXPath() { XPathFactory xpFactory = XPathFactory.newInstance(); return xpFactory.newXPath(); } - public static String checkOGCException(Document doc) - { - if (doc == null) - { + public static String checkOGCException(Document doc) { + if (doc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { XPath xpath = makeXPath(); String exception = xpath.evaluate("ServiceExceptionReport", doc); - if (exception == null || exception.length() == 0) + if (exception == null || exception.length() == 0) { return null; + } // TODO: Test this xpath expression for returning the text of the service exception. return xpath.evaluate("ServiceExceptionReport/ServiceException/text()", doc); - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { String message = Logging.getMessage("XML.XPathExpressionException"); Logging.logger().warning(message); return null; } } - @SuppressWarnings( {"UnusedParameters"}) - public static String extractOGCServiceException(ByteBuffer buffer) - { + @SuppressWarnings({"UnusedParameters"}) + public static String extractOGCServiceException(ByteBuffer buffer) { return null; // TODO } @@ -734,10 +627,8 @@ public static String extractOGCServiceException(ByteBuffer buffer) * * @throws IllegalArgumentException if the context is null. */ - public static String getUnqualifiedName(Element context) - { - if (context == null) - { + public static String getUnqualifiedName(Element context) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -756,10 +647,8 @@ public static String getUnqualifiedName(Element context) * * @throws IllegalArgumentException if the event is null. */ - public static String getUnqalifiedName(StartElement event) - { - if (event == null) - { + public static String getUnqalifiedName(StartElement event) { + if (event == null) { String message = Logging.getMessage("nullValue.EventIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -772,14 +661,13 @@ public static String getUnqalifiedName(StartElement event) * Returns the text of the element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. + * @param path the XPath expression. * * @return the text of an element matching the XPath expression, or null if no match is found. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static String getText(Element context, String path) - { + public static String getText(Element context, String path) { return getText(context, path, null); } @@ -787,39 +675,34 @@ public static String getText(Element context, String path) * Returns the text of the element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the text of an element matching the XPath expression, or null if no match is found. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static String getText(Element context, String path, XPath xpath) - { - if (context == null) - { + public static String getText(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (xpath == null) + if (xpath == null) { xpath = makeXPath(); + } - try - { + try { return xpath.evaluate(path, context); - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { return null; } } @@ -828,49 +711,44 @@ public static String getText(Element context, String path, XPath xpath) * Returns the text of all elements identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return an array containing the text of each element matching the XPath expression. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static String[] getTextArray(Element context, String path, XPath xpath) - { - if (context == null) - { + public static String[] getTextArray(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (xpath == null) + if (xpath == null) { xpath = makeXPath(); + } - try - { + try { NodeList nodes = (NodeList) xpath.evaluate(path, context, - XPathConstants.NODESET); - if (nodes == null || nodes.getLength() == 0) + XPathConstants.NODESET); + if (nodes == null || nodes.getLength() == 0) { return null; + } String[] strings = new String[nodes.getLength()]; - for (int i = 0; i < nodes.getLength(); i++) - { + for (int i = 0; i < nodes.getLength(); i++) { strings[i] = nodes.item(i).getTextContent(); } return strings; - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { return null; } } @@ -879,44 +757,43 @@ public static String[] getTextArray(Element context, String path, XPath xpath) * Returns the text of all unique elements identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return an array containing the text of each element matching the XPath expression and containing unique text. If - * multiple elements contain the same text only the first one found is returned. Returns null if no matching - * element is found. + * multiple elements contain the same text only the first one found is returned. Returns null if no matching element + * is found. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static String[] getUniqueText(Element context, String path, XPath xpath) - { - if (context == null) - { + public static String[] getUniqueText(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (xpath == null) + if (xpath == null) { xpath = makeXPath(); + } String[] strings = getTextArray(context, path, xpath); - if (strings == null) + if (strings == null) { return null; + } ArrayList sarl = new ArrayList(); - for (String s : strings) - { - if (!sarl.contains(s)) + for (String s : strings) { + if (!sarl.contains(s)) { sarl.add(s); + } } return sarl.toArray(new String[1]); @@ -926,43 +803,39 @@ public static String[] getUniqueText(Element context, String path, XPath xpath) * Returns the element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the element matching the XPath expression, or null if no element matches. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static Element getElement(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Element getElement(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (xpath == null) + if (xpath == null) { xpath = makeXPath(); + } - try - { + try { Node node = (Node) xpath.evaluate(path, context, XPathConstants.NODE); - if (node == null) + if (node == null) { return null; + } return node instanceof Element ? (Element) node : null; - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { String message = Logging.getMessage("XML.InvalidXPathExpression", "internal expression"); Logging.logger().log(java.util.logging.Level.WARNING, message, e); return null; @@ -973,50 +846,46 @@ public static Element getElement(Element context, String path, XPath xpath) * Returns all elements identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return an array containing the elements matching the XPath expression. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static Element[] getElements(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Element[] getElements(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (xpath == null) + if (xpath == null) { xpath = makeXPath(); + } - try - { + try { NodeList nodes = (NodeList) xpath.evaluate(path, context, XPathConstants.NODESET); - if (nodes == null || nodes.getLength() == 0) + if (nodes == null || nodes.getLength() == 0) { return null; + } Element[] elements = new Element[nodes.getLength()]; - for (int i = 0; i < nodes.getLength(); i++) - { + for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); - if (node instanceof Element) + if (node instanceof Element) { elements[i] = (Element) node; + } } return elements; - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { String message = Logging.getMessage("XML.InvalidXPathExpression", "internal expression"); Logging.logger().log(java.util.logging.Level.WARNING, message, e); return null; @@ -1026,54 +895,52 @@ public static Element[] getElements(Element context, String path, XPath xpath) /** * Returns the unique elements identified by an XPath expression and a sub-expression. * - * @param context the context from which to start the XPath search. - * @param path the XPath expression. + * @param context the context from which to start the XPath search. + * @param path the XPath expression. * @param uniqueTag an XPath expression to match with the elements matched with the above expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return an array containing the unique elements matching the XPath expression and subexpression. If multiple - * elements have the same content only the first one found is returned. Returns null if no matching element - * is found. + * elements have the same content only the first one found is returned. Returns null if no matching element is + * found. * * @throws IllegalArgumentException if either the context, XPath expression or XPath sub-expression are null. */ - public static Element[] getUniqueElements(Element context, String path, String uniqueTag, XPath xpath) - { - if (context == null) - { + public static Element[] getUniqueElements(Element context, String path, String uniqueTag, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (uniqueTag == null) - { + if (uniqueTag == null) { String message = Logging.getMessage("nullValue.UniqueTagIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (xpath == null) + if (xpath == null) { xpath = makeXPath(); + } Element[] elements = getElements(context, path, xpath); - if (elements == null) + if (elements == null) { return null; + } HashMap styles = new HashMap(); - for (Element e : elements) - { + for (Element e : elements) { String name = getText(e, uniqueTag, xpath); - if (name != null) + if (name != null) { styles.put(name, e); + } } return styles.values().toArray(new Element[1]); @@ -1083,26 +950,23 @@ public static Element[] getUniqueElements(Element context, String path, String u * Returns the {@link Double} value of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link Double}. + * contain a {@link Double}. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static Double getDouble(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Double getDouble(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1110,16 +974,14 @@ public static Double getDouble(Element context, String path, XPath xpath) String s = null; - try - { + try { s = getText(context, path, xpath); - if (s == null || s.length() == 0) + if (s == null || s.length() == 0) { return null; + } return Double.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1130,26 +992,23 @@ public static Double getDouble(Element context, String path, XPath xpath) * Returns the {@link Integer} value of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link Integer}. + * contain a {@link Integer}. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static Integer getInteger(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Integer getInteger(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1157,16 +1016,14 @@ public static Integer getInteger(Element context, String path, XPath xpath) String s = null; - try - { + try { s = getText(context, path, xpath); - if (s == null || s.length() == 0) + if (s == null || s.length() == 0) { return null; + } return Integer.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1177,26 +1034,23 @@ public static Integer getInteger(Element context, String path, XPath xpath) * Returns the {@link Long} value of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link Integer}. + * contain a {@link Integer}. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static Long getLong(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Long getLong(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1204,16 +1058,14 @@ public static Long getLong(Element context, String path, XPath xpath) String s = null; - try - { + try { s = getText(context, path, xpath); - if (s == null || s.length() == 0) + if (s == null || s.length() == 0) { return null; + } return Long.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1224,26 +1076,23 @@ public static Long getLong(Element context, String path, XPath xpath) * Returns the {@link Boolean} value of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link Boolean}. + * contain a {@link Boolean}. * * @throws IllegalArgumentException if the context or XPath expression are null. */ - public static Boolean getBoolean(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Boolean getBoolean(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1251,16 +1100,14 @@ public static Boolean getBoolean(Element context, String path, XPath xpath) String s = null; - try - { + try { s = getText(context, path, xpath); - if (s == null || s.length() == 0) + if (s == null || s.length() == 0) { return null; + } return Boolean.valueOf(s); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", s); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1271,52 +1118,51 @@ public static Boolean getBoolean(Element context, String path, XPath xpath) * Returns the {@link gov.nasa.worldwind.geom.LatLon} value of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. If null, indicates that the context is the LatLon element itself. If - * non-null, the context is searched for a LatLon element using the expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. If null, indicates that the context is the LatLon element itself. If non-null, + * the context is searched for a LatLon element using the expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link gov.nasa.worldwind.geom.LatLon}. + * contain a {@link gov.nasa.worldwind.geom.LatLon}. * * @throws IllegalArgumentException if the context is null. */ - public static LatLon getLatLon(Element context, String path, XPath xpath) - { - if (context == null) - { + public static LatLon getLatLon(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Element el = path == null ? context : getElement(context, path, xpath); - if (el == null) + if (el == null) { return null; + } String units = getText(el, "@units", xpath); Double lat = getDouble(el, "@latitude", xpath); Double lon = getDouble(el, "@longitude", xpath); - if (lat == null || lon == null) + if (lat == null || lon == null) { return null; + } - if (units == null || units.equals("degrees")) + if (units == null || units.equals("degrees")) { return LatLon.fromDegrees(lat, lon); + } - if (units.equals("radians")) + if (units.equals("radians")) { return LatLon.fromRadians(lat, lon); + } // Warn that units are not recognized String message = Logging.getMessage("XML.UnitsUnrecognized", units); Logging.logger().warning(message); return null; - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", path); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1327,30 +1173,28 @@ public static LatLon getLatLon(Element context, String path, XPath xpath) * Returns the {@link Color} value of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. If null, indicates that the context is the Color element itself. If - * non-null, the context is searched for a Color element using the expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. If null, indicates that the context is the Color element itself. If non-null, + * the context is searched for a Color element using the expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link Color}. + * contain a {@link Color}. * * @throws IllegalArgumentException if the context is null. */ - public static Color getColor(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Color getColor(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Element el = path == null ? context : getElement(context, path, xpath); - if (el == null) + if (el == null) { return null; + } Integer r = getInteger(el, "@red", xpath); Integer g = getInteger(el, "@green", xpath); @@ -1358,9 +1202,7 @@ public static Color getColor(Element context, String path, XPath xpath) Integer a = getInteger(el, "@alpha", xpath); return new Color(r != null ? r : 0, g != null ? g : 0, b != null ? b : 0, a != null ? a : 255); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", path); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1371,34 +1213,34 @@ public static Color getColor(Element context, String path, XPath xpath) * Returns the {@link gov.nasa.worldwind.geom.Sector} value of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. If null, indicates that the context is the Sector element itself. If - * non-null, the context is searched for a Sector element using the expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. If null, indicates that the context is the Sector element itself. If non-null, + * the context is searched for a Sector element using the expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link gov.nasa.worldwind.geom.Sector}. + * contain a {@link gov.nasa.worldwind.geom.Sector}. * * @throws IllegalArgumentException if the context is null. */ - public static Sector getSector(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Sector getSector(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Element el = path == null ? context : getElement(context, path, xpath); - if (el == null) + if (el == null) { return null; + } LatLon sw = getLatLon(el, "SouthWest/LatLon", xpath); LatLon ne = getLatLon(el, "NorthEast/LatLon", xpath); - if (sw == null || ne == null) + if (sw == null || ne == null) { return null; + } return new Sector(sw.latitude, ne.latitude, sw.longitude, ne.longitude); } @@ -1408,34 +1250,34 @@ public static Sector getSector(Element context, String path, XPath xpath) * expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. If null, indicates that the context is the SectorResolution element itself. - * If non-null, the context is searched for a SectorResolution element using the expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. If null, indicates that the context is the SectorResolution element itself. If + * non-null, the context is searched for a SectorResolution element using the expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link gov.nasa.worldwind.util.LevelSet.SectorResolution}. + * contain a {@link gov.nasa.worldwind.util.LevelSet.SectorResolution}. * * @throws IllegalArgumentException if the context is null. */ - public static LevelSet.SectorResolution getSectorResolutionLimit(Element context, String path, XPath xpath) - { - if (context == null) - { + public static LevelSet.SectorResolution getSectorResolutionLimit(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Element el = path == null ? context : getElement(context, path, xpath); - if (el == null) + if (el == null) { return null; + } Integer maxLevelNum = getInteger(el, "@maxLevelNum", xpath); Sector sector = getSector(el, "Sector", xpath); - if (maxLevelNum == null || sector == null) + if (maxLevelNum == null || sector == null) { return null; + } return new LevelSet.SectorResolution(sector, maxLevelNum); } @@ -1444,57 +1286,58 @@ public static LevelSet.SectorResolution getSectorResolutionLimit(Element context * Returns the time in milliseconds of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. If null, indicates that the context is the Time element itself. If non-null, - * the context is searched for a Time element using the expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. If null, indicates that the context is the Time element itself. If non-null, + * the context is searched for a Time element using the expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a {@link gov.nasa.worldwind.geom.LatLon}. + * contain a {@link gov.nasa.worldwind.geom.LatLon}. * * @throws IllegalArgumentException if the context is null. */ - public static Long getTimeInMillis(Element context, String path, XPath xpath) - { - if (context == null) - { + public static Long getTimeInMillis(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Element el = path == null ? context : getElement(context, path, xpath); - if (el == null) + if (el == null) { return null; + } String units = getText(el, "@units", xpath); Double value = getDouble(el, "@value", xpath); - if (value == null) + if (value == null) { return null; + } - if (units == null || units.equals("milliseconds")) + if (units == null || units.equals("milliseconds")) { return value.longValue(); + } - if (units.equals("seconds")) + if (units.equals("seconds")) { return (long) WWMath.convertSecondsToMillis(value); + } - if (units.equals("minutes")) + if (units.equals("minutes")) { return (long) WWMath.convertMinutesToMillis(value); + } - if (units.equals("hours")) + if (units.equals("hours")) { return (long) WWMath.convertHoursToMillis(value); + } // Warn that units are not recognized String message = Logging.getMessage("XML.UnitsUnrecognized", units); Logging.logger().warning(message); return null; - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", path); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1505,52 +1348,49 @@ public static Long getTimeInMillis(Element context, String path, XPath xpath) * Returns the date and time in milliseconds of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. If null, indicates that the context is the element itself. If non-null, the - * context is searched for an element matching the expression. + * @param path the XPath expression. If null, indicates that the context is the element itself. If non-null, the + * context is searched for an element matching the expression. * @param pattern the format pattern of the date. See {@link java.text.DateFormat} for the pattern symbols. The - * element content must either match the pattern or be directly convertible to a long. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * element content must either match the pattern or be directly convertible to a long. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found. * * @throws IllegalArgumentException if the context or pattern is null. */ - public static Long getDateTimeInMillis(Element context, String path, String pattern, XPath xpath) - { - if (context == null) - { + public static Long getDateTimeInMillis(Element context, String path, String pattern, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(pattern)) - { + if (WWUtil.isEmpty(pattern)) { String message = Logging.getMessage("nullValue.PatternIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Element el = path == null ? context : getElement(context, path, xpath); - if (el == null) + if (el == null) { return null; + } String s = getText(context, path, xpath); - if (s == null || s.length() == 0) + if (s == null || s.length() == 0) { return null; + } // See if the value is already a long Long longValue = WWUtil.makeLong(s); - if (longValue != null) + if (longValue != null) { return longValue; + } return new SimpleDateFormat(pattern).parse(s).getTime(); - } - catch (ParseException e) - { + } catch (ParseException e) { String message = Logging.getMessage("generic.ConversionError", path); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return null; @@ -1558,50 +1398,45 @@ public static Long getDateTimeInMillis(Element context, String path, String patt } /** - * Returns the {@link gov.nasa.worldwind.render.ScreenCredit} value of an element identified by an XPath - * expression. + * Returns the {@link gov.nasa.worldwind.render.ScreenCredit} value of an element identified by an XPath expression. * * @param context the context from which to start the XPath search. - * @param path the XPath expression. If null, indicates that the context is the ScreenCredit element itself. If - * non-null, the context is searched for a ScreenCredit element using the expression. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when - * performing multiple searches. May be null. + * @param path the XPath expression. If null, indicates that the context is the ScreenCredit element itself. If + * non-null, the context is searched for a ScreenCredit element using the expression. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @return the value of an element matching the XPath expression, or null if no match is found or the match does not - * contain a ScreenCredit. + * contain a ScreenCredit. * * @throws IllegalArgumentException if the context is null. */ - public static ScreenCredit getScreenCredit(Element context, String path, XPath xpath) - { - if (context == null) - { + public static ScreenCredit getScreenCredit(Element context, String path, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Element el = path == null ? context : WWXML.getElement(context, path, xpath); - if (el == null) + if (el == null) { return null; + } String type = WWXML.getText(el, "@creditType", xpath); - if (type != null && type.equals("ScreenImage")) - { + if (type != null && type.equals("ScreenImage")) { String fileName = WWXML.getText(el, "FileName", xpath); - if (fileName != null && fileName.length() > 0) - { + if (fileName != null && fileName.length() > 0) { ScreenCredit credit = new ScreenCreditImage(WWIO.getFilename(fileName), fileName); String link = WWXML.getText(el, "Link", xpath); - if (link != null && link.length() > 0) + if (link != null && link.length() > 0) { credit.setLink(link); + } return credit; - } - else - { + } else { // Warn that the FileName property is missing. String message = Logging.getMessage("generic.FileNameIsMissing"); Logging.logger().warning(message); @@ -1621,24 +1456,21 @@ public static ScreenCredit getScreenCredit(Element context, String path, XPath x * Sets the specified document's root element to a new element node with the specified name. If the document already * has a root element, this replaces the existing root node with the new element node. * - * @param doc the document which receives the new root element. + * @param doc the document which receives the new root element. * @param name the name of the document's new root element node. * * @return the document's new root element node. * * @throws IllegalArgumentException if the document is null, if the name is null, or if the name is empty. */ - public static Element setDocumentElement(Document doc, String name) - { - if (doc == null) - { + public static Element setDocumentElement(Document doc, String name) { + if (doc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(name)) - { + if (WWUtil.isEmpty(name)) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1649,12 +1481,9 @@ public static Element setDocumentElement(Document doc, String name) // mode. Element el = doc.createElementNS(null, name); - if (doc.getDocumentElement() != null) - { + if (doc.getDocumentElement() != null) { doc.replaceChild(el, doc.getDocumentElement()); - } - else - { + } else { doc.appendChild(el); } @@ -1666,23 +1495,20 @@ public static Element setDocumentElement(Document doc, String name) * returns the context element, and does not make any modifications to the context. * * @param context the context on which to append a new element. - * @param name the new element name to append. + * @param name the new element name to append. * * @return the new element appended to the context, or the context if the element name is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendElement(Element context, String name) - { - if (context == null) - { + public static Element appendElement(Element context, String name) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(name)) - { + if (WWUtil.isEmpty(name)) { return context; } @@ -1705,39 +1531,33 @@ public static Element appendElement(Element context, String name) * path is empty, that element is skipped. * * @param context the context on which to append new elements. - * @param path the element path to append. + * @param path the element path to append. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendElementPath(Element context, String path) - { - if (context == null) - { + public static Element appendElementPath(Element context, String path) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(path)) - { + if (WWUtil.isEmpty(path)) { return context; } String[] names = path.split("/"); - if (names == null || names.length == 0) - { + if (names == null || names.length == 0) { return context; } Document doc = context.getOwnerDocument(); Element cur = context; - for (String s : names) - { - if (s != null && s.length() > 0) - { + for (String s : names) { + if (s != null && s.length() > 0) { // Create a namespace-aware element node, which supports DOM Level 1 and Level 2 features. This ensures // the constructed DOM node is consistent with element nodes created by parsing an XML document in // namespace-aware mode. @@ -1756,24 +1576,21 @@ public static Element appendElementPath(Element context, String path) * that a terminating text element is appended to the last element. * * @param context the context on which to append new elements. - * @param path the element path to append. - * @param string the text element value. + * @param path the element path to append. + * @param string the text element value. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendText(Element context, String path, String string) - { - if (context == null) - { + public static Element appendText(Element context, String path, String string) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (string == null) - { + if (string == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1795,24 +1612,21 @@ public static Element appendText(Element context, String path, String string) * element. * * @param context the context on which to append new elements. - * @param path the element path to append. + * @param path the element path to append. * @param strings the text element values. * * @return array of new elements appended to the context. * * @throws IllegalArgumentException if the context is null. */ - public static Element[] appendTextArray(Element context, String path, String[] strings) - { - if (context == null) - { + public static Element[] appendTextArray(Element context, String path, String[] strings) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (strings == null) - { + if (strings == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1820,12 +1634,10 @@ public static Element[] appendTextArray(Element context, String path, String[] s Element[] els = new Element[strings.length]; - for (int i = 0; i < strings.length; i++) - { + for (int i = 0; i < strings.length; i++) { String s = strings[i]; - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { els[i] = appendText(context, path, s); } } @@ -1839,17 +1651,15 @@ public static Element[] appendTextArray(Element context, String path, String[] s * that a terminating text element is appended to the last element. * * @param context the context on which to append new elements. - * @param path the element path to append. - * @param value the text element value. + * @param path the element path to append. + * @param value the text element value. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendDouble(Element context, String path, double value) - { - if (context == null) - { + public static Element appendDouble(Element context, String path, double value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1864,17 +1674,15 @@ public static Element appendDouble(Element context, String path, double value) * that a terminating text element is appended to the last element. * * @param context the context on which to append new elements. - * @param path the element path to append. - * @param value the text element value. + * @param path the element path to append. + * @param value the text element value. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendInteger(Element context, String path, int value) - { - if (context == null) - { + public static Element appendInteger(Element context, String path, int value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1889,17 +1697,15 @@ public static Element appendInteger(Element context, String path, int value) * that a terminating text element is appended to the last element. * * @param context the context on which to append new elements. - * @param path the element path to append. - * @param value the text element value. + * @param path the element path to append. + * @param value the text element value. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendLong(Element context, String path, long value) - { - if (context == null) - { + public static Element appendLong(Element context, String path, long value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1914,17 +1720,15 @@ public static Element appendLong(Element context, String path, long value) * that a terminating text element is appended to the last element. * * @param context the context on which to append new elements. - * @param path the element path to append. - * @param value the text element value. + * @param path the element path to append. + * @param value the text element value. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendBoolean(Element context, String path, boolean value) - { - if (context == null) - { + public static Element appendBoolean(Element context, String path, boolean value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1939,24 +1743,21 @@ public static Element appendBoolean(Element context, String path, boolean value) * terminating text element is appended to the last element. * * @param context the context on which to append new elements. - * @param path the element path to append. - * @param ll the LatLon value to create. + * @param path the element path to append. + * @param ll the LatLon value to create. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendLatLon(Element context, String path, LatLon ll) - { - if (context == null) - { + public static Element appendLatLon(Element context, String path, LatLon ll) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (ll == null) - { + if (ll == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1976,24 +1777,21 @@ public static Element appendLatLon(Element context, String path, LatLon ll) * terminating text element is appended to the last element. * * @param context the context on which to append new elements. - * @param path the element path to append. - * @param sector the Sector value to create. + * @param path the element path to append. + * @param sector the Sector value to create. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendSector(Element context, String path, Sector sector) - { - if (context == null) - { + public static Element appendSector(Element context, String path, Sector sector) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2012,8 +1810,8 @@ public static Element appendSector(Element context, String path, Sector sector) * #appendElementPath(org.w3c.dom.Element, String)}, except that a terminating text element is appended to the last * element. * - * @param context the context on which to append new elements. - * @param path the element path to append. + * @param context the context on which to append new elements. + * @param path the element path to append. * @param sectorResolution the LevelSet.SectorResolutionLimit value to create. * * @return the new element appended to the context, or the context if the element path is null or empty. @@ -2021,17 +1819,14 @@ public static Element appendSector(Element context, String path, Sector sector) * @throws IllegalArgumentException if the context is null. */ public static Element appendSectorResolutionLimit(Element context, String path, - LevelSet.SectorResolution sectorResolution) - { - if (context == null) - { + LevelSet.SectorResolution sectorResolution) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sectorResolution == null) - { + if (sectorResolution == null) { String message = Logging.getMessage("nullValue.LevelSet.SectorResolutionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2049,18 +1844,16 @@ public static Element appendSectorResolutionLimit(Element context, String path, * milliseconds. Elements are added to the context as in {@link #appendElementPath(org.w3c.dom.Element, String)}, * except that a terminating text element is appended to the last element. * - * @param context the context on which to append new elements. - * @param path the element path to append. + * @param context the context on which to append new elements. + * @param path the element path to append. * @param timeInMillis the time value in milliseconds to create. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendTimeInMillis(Element context, String path, long timeInMillis) - { - if (context == null) - { + public static Element appendTimeInMillis(Element context, String path, long timeInMillis) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2078,49 +1871,43 @@ public static Element appendTimeInMillis(Element context, String path, long time * ScreenCredit. Elements are added to the context as in {@link WWXML#appendElementPath(org.w3c.dom.Element, * String)}, except that a terminating text element is appended to the last element. * - * @param context the context on which to append new elements. - * @param path the element path to append. + * @param context the context on which to append new elements. + * @param path the element path to append. * @param screenCredit the ScreenCredit value to create. * * @return the new element appended to the context, or the context if the element path is null or empty. * * @throws IllegalArgumentException if the context is null. */ - public static Element appendScreenCredit(Element context, String path, ScreenCredit screenCredit) - { - if (context == null) - { + public static Element appendScreenCredit(Element context, String path, ScreenCredit screenCredit) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (screenCredit == null) - { + if (screenCredit == null) { String message = Logging.getMessage("nullValue.ScreenCreditIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (screenCredit instanceof ScreenCreditImage) - { + if (screenCredit instanceof ScreenCreditImage) { Element el = WWXML.appendElementPath(context, path); setTextAttribute(el, "creditType", "ScreenImage"); String link = screenCredit.getLink(); - if (link != null && link.length() > 0) + if (link != null && link.length() > 0) { WWXML.appendText(el, "Link", link); + } Object imageSource = ((ScreenCreditImage) screenCredit).getImageSource(); - if (imageSource != null && imageSource instanceof String) - { + if (imageSource != null && imageSource instanceof String) { WWXML.appendText(el, "FileName", (String) imageSource); - } - else - { + } else { // Warn that the image source property cannot be written to the document. String message = Logging.getMessage("generic.UnrecognizedImageSourceType", - (imageSource != null) ? imageSource.getClass().getName() : null); + (imageSource != null) ? imageSource.getClass().getName() : null); Logging.logger().warning(message); } @@ -2139,22 +1926,19 @@ public static Element appendScreenCredit(Element context, String path, ScreenCre * attribute with this name, its value is repaced with the specified value. * * @param context the element on which to set the attribute. - * @param name the attribute's name. - * @param value the attribute's value. + * @param name the attribute's name. + * @param value the attribute's value. * * @throws IllegalArgumentException if the context is null, if the name is null, or if the name is empty. */ - public static void setTextAttribute(Element context, String name, String value) - { - if (context == null) - { + public static void setTextAttribute(Element context, String name, String value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(name)) - { + if (WWUtil.isEmpty(name)) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2171,22 +1955,19 @@ public static void setTextAttribute(Element context, String name, String value) * element already has an attribute with this name, its value is repaced with the specified value. * * @param context the Element on which to set the attribute. - * @param name the attribute's name. - * @param value the attribute's value. + * @param name the attribute's name. + * @param value the attribute's value. * * @throws IllegalArgumentException if the context is null, if the name is null, or if the name is empty. */ - public static void setDoubleAttribute(Element context, String name, double value) - { - if (context == null) - { + public static void setDoubleAttribute(Element context, String name, double value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2200,22 +1981,19 @@ public static void setDoubleAttribute(Element context, String name, double value * the element already has an attribute with this name, its value is repaced with the specified value. * * @param context the element on which to set the attribute. - * @param name the attribute's name. - * @param value the attribute's value. + * @param name the attribute's name. + * @param value the attribute's value. * * @throws IllegalArgumentException if the context is null, if the name is null, or if the name is empty. */ - public static void setIntegerAttribute(Element context, String name, int value) - { - if (context == null) - { + public static void setIntegerAttribute(Element context, String name, int value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2229,22 +2007,19 @@ public static void setIntegerAttribute(Element context, String name, int value) * If the element already has an attribute with this name, its value is repaced with the specified value. * * @param context the element on which to set the attribute. - * @param name the attribute's name. - * @param value the attribute's value. + * @param name the attribute's name. + * @param value the attribute's value. * * @throws IllegalArgumentException if the context is null, if the name is null, or if the name is empty. */ - public static void setLongAttribute(Element context, String name, long value) - { - if (context == null) - { + public static void setLongAttribute(Element context, String name, long value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2258,22 +2033,19 @@ public static void setLongAttribute(Element context, String name, long value) * the element already has an attribute with this name, its value is repaced with the specified value. * * @param context the element on which to set the attribute. - * @param name the attribute's name. - * @param value the attribute's value. + * @param name the attribute's name. + * @param value the attribute's value. * * @throws IllegalArgumentException if the context is null, if the name is null, or if the name is empty. */ - public static void setBooleanAttribute(Element context, String name, boolean value) - { - if (context == null) - { + public static void setBooleanAttribute(Element context, String name, boolean value) { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (name == null) - { + if (name == null) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2286,53 +2058,47 @@ public static void setBooleanAttribute(Element context, String name, boolean val * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetStringParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String s = params.getStringValue(paramKey); - if (s == null) - { + if (s == null) { s = getText(context, paramName, xpath); - if (s != null && s.length() > 0) + if (s != null && s.length() > 0) { params.setValue(paramKey, s.trim()); + } } } @@ -2340,53 +2106,47 @@ public static void checkAndSetStringParam(Element context, AVList params, String * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetStringArrayParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { String[] strings = getTextArray(context, paramName, xpath); - if (strings != null && strings.length > 0) + if (strings != null && strings.length > 0) { params.setValue(paramKey, strings); + } } } @@ -2394,53 +2154,47 @@ public static void checkAndSetStringArrayParam(Element context, AVList params, S * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetUniqueStringsParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { String[] strings = getUniqueText(context, paramName, xpath); - if (strings != null && strings.length > 0) + if (strings != null && strings.length > 0) { params.setValue(paramKey, strings); + } } } @@ -2448,53 +2202,47 @@ public static void checkAndSetUniqueStringsParam(Element context, AVList params, * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetDoubleParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Double d = getDouble(context, paramName, xpath); - if (d != null) + if (d != null) { params.setValue(paramKey, d); + } } } @@ -2502,53 +2250,47 @@ public static void checkAndSetDoubleParam(Element context, AVList params, String * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetIntegerParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Integer d = getInteger(context, paramName, xpath); - if (d != null) + if (d != null) { params.setValue(paramKey, d); + } } } @@ -2556,53 +2298,47 @@ public static void checkAndSetIntegerParam(Element context, AVList params, Strin * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetLongParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Long d = getLong(context, paramName, xpath); - if (d != null) + if (d != null) { params.setValue(paramKey, d); + } } } @@ -2610,53 +2346,47 @@ public static void checkAndSetLongParam(Element context, AVList params, String p * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetBooleanParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Boolean d = getBoolean(context, paramName, xpath); - if (d != null) + if (d != null) { params.setValue(paramKey, d); + } } } @@ -2664,53 +2394,47 @@ public static void checkAndSetBooleanParam(Element context, AVList params, Strin * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetLatLonParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { LatLon ll = getLatLon(context, paramName, xpath); - if (ll != null) + if (ll != null) { params.setValue(paramKey, ll); + } } } @@ -2718,101 +2442,90 @@ public static void checkAndSetLatLonParam(Element context, AVList params, String * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetColorParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Color color = getColor(context, paramName, xpath); - if (color != null) + if (color != null) { params.setValue(paramKey, color); + } } } public static void checkAndSetColorArrayParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Element[] els = getElements(context, paramName, xpath); - if (els == null || els.length == 0) + if (els == null || els.length == 0) { return; + } int[] colors = new int[els.length]; - for (int i = 0; i < els.length; i++) - { + for (int i = 0; i < els.length; i++) { Color color = getColor(context, paramName, xpath); - if (color != null) + if (color != null) { colors[i] = color.getRGB(); + } } params.setValue(paramKey, colors); @@ -2823,53 +2536,47 @@ public static void checkAndSetColorArrayParam(Element context, AVList params, St * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetSectorParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Sector sector = getSector(context, paramName, xpath); - if (sector != null) + if (sector != null) { params.setValue(paramKey, sector); + } } } @@ -2877,61 +2584,55 @@ public static void checkAndSetSectorParam(Element context, AVList params, String * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetSectorResolutionParam(Element context, AVList params, String paramKey, - String paramName, XPath xpath) - { - if (context == null) - { + String paramName, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Element[] els = getElements(context, paramName, xpath); - if (els == null || els.length == 0) + if (els == null || els.length == 0) { return; + } LevelSet.SectorResolution[] srs = new LevelSet.SectorResolution[els.length]; - for (int i = 0; i < els.length; i++) - { + for (int i = 0; i < els.length; i++) { LevelSet.SectorResolution sr = getSectorResolutionLimit(els[i], null, xpath); - if (sr != null) + if (sr != null) { srs[i] = sr; + } } params.setValue(paramKey, srs); @@ -2942,53 +2643,47 @@ public static void checkAndSetSectorResolutionParam(Element context, AVList para * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetTimeParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Long d = getTimeInMillis(context, paramName, xpath); - if (d != null) + if (d != null) { params.setValue(paramKey, d); + } } } @@ -2996,53 +2691,47 @@ public static void checkAndSetTimeParam(Element context, AVList params, String p * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetTimeParamAsInteger(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Long d = WWXML.getTimeInMillis(context, paramName, xpath); - if (d != null) + if (d != null) { params.setValue(paramKey, d.intValue()); + } } } @@ -3050,62 +2739,56 @@ public static void checkAndSetTimeParamAsInteger(Element context, AVList params, * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param pattern the format pattern of the date. See {@link java.text.DateFormat} for the pattern symbols. The - * element content must either match the pattern or be directly convertible to a long. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param pattern the format pattern of the date. See {@link java.text.DateFormat} for the pattern symbols. The + * element content must either match the pattern or be directly convertible to a long. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * * @throws IllegalArgumentException if either the context, parameter list, parameter key, pattern or parameter name - * are null. + * are null. */ public static void checkAndSetDateTimeParam(Element context, AVList params, String paramKey, String paramName, - String pattern, XPath xpath) - { - if (context == null) - { + String pattern, XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(pattern)) - { + if (WWUtil.isEmpty(pattern)) { String message = Logging.getMessage("nullValue.PatternIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { Long d = getDateTimeInMillis(context, paramName, pattern, xpath); - if (d != null) + if (d != null) { params.setValue(paramKey, d); + } } } @@ -3113,53 +2796,47 @@ public static void checkAndSetDateTimeParam(Element context, AVList params, Stri * Checks a parameter list for a specified key and if not present attempts to find a value for the key from an * element matched by an XPath expression. If found, the key and value are added to the parameter list. * - * @param context the context from which to start the XPath search. - * @param params the parameter list. - * @param paramKey the key used to identify the paramater in the parameter list. + * @param context the context from which to start the XPath search. + * @param params the parameter list. + * @param paramKey the key used to identify the paramater in the parameter list. * @param paramName the Xpath expression identifying the parameter value within the specified context. - * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects - * when performing multiple searches. May be null. + * @param xpath an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when + * performing multiple searches. May be null. * - * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are - * null. + * @throws IllegalArgumentException if either the context, parameter list, parameter key or parameter name are null. */ public static void checkAndSetScreenCreditParam(Element context, AVList params, String paramKey, String paramName, - XPath xpath) - { - if (context == null) - { + XPath xpath) { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramName == null) - { + if (paramName == null) { String message = Logging.getMessage("nullValue.ParameterNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o == null) - { + if (o == null) { ScreenCredit sc = getScreenCredit(context, paramName, xpath); - if (sc != null) + if (sc != null) { params.setValue(paramKey, sc); + } } } @@ -3167,39 +2844,34 @@ public static void checkAndSetScreenCreditParam(Element context, AVList params, * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendTextElement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendTextElement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String s = params.getStringValue(paramKey); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { appendText(context, path, s.trim()); } } @@ -3208,42 +2880,36 @@ public static void checkAndAppendTextElement(AVList params, String paramKey, Ele * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendTextArrayElement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendTextArrayElement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o != null && o instanceof String[]) - { + if (o != null && o instanceof String[]) { String[] strings = (String[]) o; - if (strings.length > 0) - { + if (strings.length > 0) { appendTextArray(context, path, (String[]) o); } } @@ -3253,39 +2919,34 @@ public static void checkAndAppendTextArrayElement(AVList params, String paramKey * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendDoubleElement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendDoubleElement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Double d = AVListImpl.getDoubleValue(params, paramKey); - if (d != null) - { + if (d != null) { appendDouble(context, path, d); } } @@ -3294,39 +2955,34 @@ public static void checkAndAppendDoubleElement(AVList params, String paramKey, E * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendIntegerlement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendIntegerlement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Integer i = AVListImpl.getIntegerValue(params, paramKey); - if (i != null) - { + if (i != null) { appendInteger(context, path, i); } } @@ -3335,39 +2991,34 @@ public static void checkAndAppendIntegerlement(AVList params, String paramKey, E * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendLongElement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendLongElement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Long l = AVListImpl.getLongValue(params, paramKey); - if (l != null) - { + if (l != null) { appendLong(context, path, l); } } @@ -3376,39 +3027,34 @@ public static void checkAndAppendLongElement(AVList params, String paramKey, Ele * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendBooleanElement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendBooleanElement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o != null && o instanceof Boolean) - { + if (o != null && o instanceof Boolean) { appendBoolean(context, path, (Boolean) o); } } @@ -3417,39 +3063,34 @@ public static void checkAndAppendBooleanElement(AVList params, String paramKey, * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendLatLonElement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendLatLonElement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o != null && o instanceof LatLon) - { + if (o != null && o instanceof LatLon) { appendLatLon(context, path, (LatLon) o); } } @@ -3458,39 +3099,34 @@ public static void checkAndAppendLatLonElement(AVList params, String paramKey, E * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendSectorElement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendSectorElement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o != null && o instanceof Sector) - { + if (o != null && o instanceof Sector) { appendSector(context, path, (Sector) o); } } @@ -3499,46 +3135,39 @@ public static void checkAndAppendSectorElement(AVList params, String paramKey, E * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ public static void checkAndAppendSectorResolutionElement(AVList params, String paramKey, Element context, - String path) - { - if (params == null) - { + String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o != null && o instanceof LevelSet.SectorResolution[]) - { + if (o != null && o instanceof LevelSet.SectorResolution[]) { LevelSet.SectorResolution[] srs = (LevelSet.SectorResolution[]) o; - for (LevelSet.SectorResolution sr : srs) - { - if (sr != null) - { + for (LevelSet.SectorResolution sr : srs) { + if (sr != null) { appendSectorResolutionLimit(context, path, sr); } } @@ -3549,40 +3178,35 @@ public static void checkAndAppendSectorResolutionElement(AVList params, String p * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ public static void checkAndAppendTimeElement(AVList params, String paramKey, Element context, - String path) - { - if (params == null) - { + String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o != null && o instanceof Number) - { + if (o != null && o instanceof Number) { Number num = (Number) o; appendTimeInMillis(context, path, num.longValue()); } @@ -3592,47 +3216,40 @@ public static void checkAndAppendTimeElement(AVList params, String paramKey, Ele * Checks a parameter list for a specified key and if present attempts to append new elements represeting the * parameter to a specified context. * - * @param context the context on which to append new elements. - * @param params the parameter list. + * @param context the context on which to append new elements. + * @param params the parameter list. * @param paramKey the key used to identify the paramater in the parameter list. - * @param path the element path to append. + * @param path the element path to append. * - * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. + * @throws IllegalArgumentException if either the parameter list parameter key, or context are null. */ - public static void checkAndAppendScreenCreditElement(AVList params, String paramKey, Element context, String path) - { - if (params == null) - { + public static void checkAndAppendScreenCreditElement(AVList params, String paramKey, Element context, String path) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (paramKey == null) - { + if (paramKey == null) { String message = Logging.getMessage("nullValue.ParameterKeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = params.getValue(paramKey); - if (o != null && o instanceof ScreenCredit) - { + if (o != null && o instanceof ScreenCredit) { appendScreenCredit(context, path, (ScreenCredit) o); } } - public static String fixGetMapString(String gms) - { - if (gms == null) - { + public static String fixGetMapString(String gms) { + if (gms == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3640,11 +3257,13 @@ public static String fixGetMapString(String gms) gms = gms.trim(); int qMarkIndex = gms.indexOf("?"); - if (qMarkIndex < 0) + if (qMarkIndex < 0) { gms += "?"; - else if (qMarkIndex != gms.length() - 1) - if (gms.lastIndexOf("&") != gms.length() - 1) + } else if (qMarkIndex != gms.length() - 1) { + if (gms.lastIndexOf("&") != gms.length() - 1) { gms += "&"; + } + } return gms; } @@ -3660,20 +3279,19 @@ else if (qMarkIndex != gms.length() - 1) * * @throws IllegalArgumentException if the string is null. */ - public static String parseByteOrder(String s) - { - if (s == null) - { + public static String parseByteOrder(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } s = s.trim().toLowerCase(); - if (s.startsWith("little")) + if (s.startsWith("little")) { return AVKey.LITTLE_ENDIAN; - else if (s.startsWith("big")) + } else if (s.startsWith("big")) { return AVKey.BIG_ENDIAN; + } // Warn that the byte order is unrecognized. String message = Logging.getMessage("generic.UnrecognizedByteOrder", s); @@ -3693,19 +3311,18 @@ else if (s.startsWith("big")) * * @throws IllegalArgumentException if the byte order is null. */ - public static String byteOrderAsText(String byteOrder) - { - if (byteOrder == null) - { + public static String byteOrderAsText(String byteOrder) { + if (byteOrder == null) { String message = Logging.getMessage("nullValue.ByteOrderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (byteOrder.equals(AVKey.LITTLE_ENDIAN)) + if (byteOrder.equals(AVKey.LITTLE_ENDIAN)) { return "LittleEndian"; - else if (byteOrder.equals(AVKey.BIG_ENDIAN)) + } else if (byteOrder.equals(AVKey.BIG_ENDIAN)) { return "BigEndian"; + } // Warn that the byte order is unrecognized. String message = Logging.getMessage("generic.UnrecognizedByteOrder", byteOrder); @@ -3716,7 +3333,8 @@ else if (byteOrder.equals(AVKey.BIG_ENDIAN)) /** * Returns the data type constant for a specified string. This performs a mapping between text and an AVKey - * constant:

          "); // Insert the schema name, if the schema can be resolved. Otherwise just use the data name. - if (schema != null && !WWUtil.isEmpty(schema.getName()) && !WWUtil.isEmpty(dataName)) - { + if (schema != null && !WWUtil.isEmpty(schema.getName()) && !WWUtil.isEmpty(dataName)) { sb.append("$[").append(schema.getName()).append("/").append(dataName).append("/displayName]"); - } - else - { + } else { sb.append(dataName); } @@ -328,11 +312,10 @@ protected void createDefaultSchemaDataText(StringBuilder sb, List * * @return True if URLs should be converted links. Returns true if a <html> tag is found in the text. */ - protected boolean mustAddHyperlinks(String text) - { + protected boolean mustAddHyperlinks(String text) { return text != null - && !text.contains("" // Match all text between anchor tags - + "|" // or - + "[^'\"]" // Non-quote (avoids matching quoted urls in code) - + "(" // Capture group 1 + String regex + = "" // Match all text between anchor tags + + "|" // or + + "[^'\"]" // Non-quote (avoids matching quoted urls in code) + + "(" // Capture group 1 + "(?:https?://|www\\.)" // HTTP(S) protocol or www. (non-capturing group) - + "[a-z0-9.$%&#+/_-]+" // Match until a non-URL character + + "[a-z0-9.$%&#+/_-]+" // Match until a non-URL character + ")"; StringBuffer sb = new StringBuffer(); Matcher matcher = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(text); - while (matcher.find()) - { + while (matcher.find()) { // If the match is a URL then group 1 holds the matched URL. If group 1 is null then the match is an anchor // tag, in which case we just skip it to avoid adding links to text that is already part of a link. String url = matcher.group(1); - if (url != null) - { + if (url != null) { String prefix = url.toLowerCase().startsWith("www") ? "http://" : ""; matcher.appendReplacement(sb, "$1"); } @@ -389,27 +369,23 @@ protected String addHyperlinks(String text) * * @return Initial balloon attributes. */ - protected BalloonAttributes getInitialBalloonAttributes() - { + protected BalloonAttributes getInitialBalloonAttributes() { BalloonAttributes attrs; - if (this.isHighlighted()) - { + if (this.isHighlighted()) { attrs = this.getHighlightAttributes(); // Copy the normal attributes if there are no highlight attributes - if (attrs == null && this.getAttributes() != null) - { + if (attrs == null && this.getAttributes() != null) { attrs = new BasicBalloonAttributes(this.getAttributes()); } - } - else - { + } else { attrs = this.getAttributes(); } - if (attrs == null) + if (attrs == null) { attrs = new BasicBalloonAttributes(); + } return attrs; } @@ -417,26 +393,28 @@ protected BalloonAttributes getInitialBalloonAttributes() /** * Apply a KML BalloonStyle to the balloon attributes object. * - * @param style KML style to apply. + * @param style KML style to apply. * @param balloonAttributes Attributes to modify. */ - protected void assembleBalloonAttributes(KMLBalloonStyle style, BalloonAttributes balloonAttributes) - { + protected void assembleBalloonAttributes(KMLBalloonStyle style, BalloonAttributes balloonAttributes) { // Attempt to use the bgColor property. This is the preferred method for encoding a BalloonStyle's background // color since KML 2.1, therefore we give it priority. String bgColor = style.getBgColor(); // If the bgColor property is null, attempt to use the deprecated color property. color was deprecated in // KML 2.1, but must be supported for backward compatibility. See the KML 2.1 reference, section 7.1.3. - if (bgColor == null) + if (bgColor == null) { bgColor = style.getColor(); + } - if (bgColor != null) + if (bgColor != null) { balloonAttributes.setInteriorMaterial(new Material(WWUtil.decodeColorABGR(bgColor))); + } String textColor = style.getTextColor(); - if (textColor != null) + if (textColor != null) { balloonAttributes.setTextColor(WWUtil.decodeColorABGR(textColor)); + } } /** @@ -446,8 +424,7 @@ protected void assembleBalloonAttributes(KMLBalloonStyle style, BalloonAttribute * * @return New text decoder. */ - protected TextDecoder createTextDecoder(KMLAbstractFeature feature) - { + protected TextDecoder createTextDecoder(KMLAbstractFeature feature) { return new KMLBalloonTextDecoder(feature); } @@ -458,8 +435,7 @@ protected TextDecoder createTextDecoder(KMLAbstractFeature feature) * * @see #setDisplayMode(String) */ - public String getDisplayMode() - { + public String getDisplayMode() { return this.displayMode; } @@ -471,10 +447,8 @@ public String getDisplayMode() * * @see #getDisplayMode() */ - public void setDisplayMode(String displayMode) - { - if (displayMode == null) - { + public void setDisplayMode(String displayMode) { + if (displayMode == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -493,25 +467,21 @@ public void setDisplayMode(String displayMode) *

          * This returns null if the specified address is null. */ - public URL resolve(String address) - { - if (address == null) + public URL resolve(String address) { + if (address == null) { return null; + } - try - { + try { // Resolve the relative path against the KMLDoc, and convert it to a URL. We use makeURL variant that // accepts a default protocol, because we know the path is an absolute file path. If the path does not // define a valid URL, makeURL returns null and the balloon treats this as an unresolved resource. String absolutePath = this.parent.getRoot().getKMLDoc().getSupportFilePath(address); - if (!WWUtil.isEmpty(absolutePath)) - { + if (!WWUtil.isEmpty(absolutePath)) { File file = new File(absolutePath); return file.toURI().toURL(); } - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().log(Level.WARNING, Logging.getMessage("KML.UnableToResolvePath", address), e.getMessage()); } @@ -523,250 +493,286 @@ public URL resolve(String address) * * @param evt Event to forward. */ - public void propertyChange(PropertyChangeEvent evt) - { + public void propertyChange(PropertyChangeEvent evt) { this.parent.getRoot().firePropertyChange(evt); } //***************************************************************************// //********************** Balloon implementation ***************************// //**************************************************************************// - - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public boolean isHighlighted() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public boolean isHighlighted() { return this.getBalloon().isHighlighted(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setHighlighted(boolean highlighted) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setHighlighted(boolean highlighted) { this.getBalloon().setHighlighted(highlighted); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public boolean isAlwaysOnTop() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public boolean isAlwaysOnTop() { return this.getBalloon().isAlwaysOnTop(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setAlwaysOnTop(boolean alwaysOnTop) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setAlwaysOnTop(boolean alwaysOnTop) { this.getBalloon().setAlwaysOnTop(alwaysOnTop); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public boolean isPickEnabled() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public boolean isPickEnabled() { return this.getBalloon().isPickEnabled(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setPickEnabled(boolean enable) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setPickEnabled(boolean enable) { this.getBalloon().setPickEnabled(enable); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public String getText() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public String getText() { return this.getBalloon().getText(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setText(String text) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setText(String text) { this.getBalloon().setText(text); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public BalloonAttributes getAttributes() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public BalloonAttributes getAttributes() { return this.getBalloon().getAttributes(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setAttributes(BalloonAttributes attrs) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setAttributes(BalloonAttributes attrs) { this.getBalloon().setAttributes(attrs); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public BalloonAttributes getHighlightAttributes() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public BalloonAttributes getHighlightAttributes() { return this.getBalloon().getHighlightAttributes(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setHighlightAttributes(BalloonAttributes attrs) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setHighlightAttributes(BalloonAttributes attrs) { this.getBalloon().setHighlightAttributes(attrs); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public TextDecoder getTextDecoder() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public TextDecoder getTextDecoder() { return this.getBalloon().getTextDecoder(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setTextDecoder(TextDecoder decoder) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setTextDecoder(TextDecoder decoder) { this.getBalloon().setTextDecoder(decoder); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Object getDelegateOwner() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Object getDelegateOwner() { return this.getBalloon().getDelegateOwner(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setDelegateOwner(Object owner) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setDelegateOwner(Object owner) { this.getBalloon().setDelegateOwner(owner); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public boolean isVisible() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public boolean isVisible() { return this.getBalloon().isVisible(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setVisible(boolean visible) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setVisible(boolean visible) { this.getBalloon().setVisible(visible); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Rectangle getBounds(DrawContext dc) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Rectangle getBounds(DrawContext dc) { return this.getBalloon().getBounds(dc); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public double getMinActiveAltitude() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public double getMinActiveAltitude() { return this.getBalloon().getMinActiveAltitude(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setMinActiveAltitude(double minActiveAltitude) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setMinActiveAltitude(double minActiveAltitude) { this.getBalloon().setMinActiveAltitude(minActiveAltitude); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public double getMaxActiveAltitude() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public double getMaxActiveAltitude() { return this.getBalloon().getMaxActiveAltitude(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setMaxActiveAltitude(double maxActiveAltitude) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setMaxActiveAltitude(double maxActiveAltitude) { this.getBalloon().setMaxActiveAltitude(maxActiveAltitude); } //***************************************************************************// //********************** AVList implementation ***************************// //**************************************************************************// - - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Object setValue(String key, Object value) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Object setValue(String key, Object value) { return this.getBalloon().setValue(key, value); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public AVList setValues(AVList avList) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public AVList setValues(AVList avList) { return this.getBalloon().setValues(avList); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Object getValue(String key) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Object getValue(String key) { return this.getBalloon().getValue(key); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Collection getValues() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Collection getValues() { return this.getBalloon().getValues(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public String getStringValue(String key) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public String getStringValue(String key) { return this.getBalloon().getStringValue(key); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Set> getEntries() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Set> getEntries() { return this.getBalloon().getEntries(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public boolean hasKey(String key) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public boolean hasKey(String key) { return this.getBalloon().hasKey(key); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Object removeKey(String key) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Object removeKey(String key) { return this.getBalloon().removeKey(key); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { this.getBalloon().addPropertyChangeListener(propertyName, listener); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { this.getBalloon().removePropertyChangeListener(propertyName, listener); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void addPropertyChangeListener(PropertyChangeListener listener) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void addPropertyChangeListener(PropertyChangeListener listener) { this.getBalloon().addPropertyChangeListener(listener); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void removePropertyChangeListener(PropertyChangeListener listener) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void removePropertyChangeListener(PropertyChangeListener listener) { this.getBalloon().removePropertyChangeListener(listener); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { this.getBalloon().firePropertyChange(propertyName, oldValue, newValue); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void firePropertyChange(PropertyChangeEvent propertyChangeEvent) { this.getBalloon().firePropertyChange(propertyChangeEvent); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public AVList copy() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public AVList copy() { return this.getBalloon().copy(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public AVList clearList() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public AVList clearList() { return this.getBalloon().clearList(); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLBalloonTextDecoder.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLBalloonTextDecoder.java index e8d71afd3f..5dfb6eeb22 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLBalloonTextDecoder.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLBalloonTextDecoder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.ogc.kml.*; @@ -18,8 +17,8 @@ * @author pabercrombie * @version $Id: KMLBalloonTextDecoder.java 1944 2014-04-18 16:50:49Z tgaskins $ */ -public class KMLBalloonTextDecoder extends BasicTextDecoder -{ +public class KMLBalloonTextDecoder extends BasicTextDecoder { + /** * True if there are entities in the balloon text which may refer to unresolved schema. False if all entities have * been resolved, or are known to be unresolvable (because the data they refer to does not exist). @@ -32,7 +31,9 @@ public class KMLBalloonTextDecoder extends BasicTextDecoder */ protected Map entityCache = new HashMap(); - /** Feature to use as context for entity replacements. */ + /** + * Feature to use as context for entity replacements. + */ protected KMLAbstractFeature feature; /** @@ -41,10 +42,8 @@ public class KMLBalloonTextDecoder extends BasicTextDecoder * * @param feature Feature that is the context of entity replacements. */ - public KMLBalloonTextDecoder(KMLAbstractFeature feature) - { - if (feature == null) - { + public KMLBalloonTextDecoder(KMLAbstractFeature feature) { + if (feature == null) { String message = Logging.getMessage("nullValue.FeatureIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -61,45 +60,46 @@ public KMLBalloonTextDecoder(KMLAbstractFeature feature) * @return String after replacements have been made. Returns null if the input text is null. */ @Override - public synchronized String getDecodedText() - { - if (this.decodedText == null) + public synchronized String getDecodedText() { + if (this.decodedText == null) { this.lastUpdateTime = System.currentTimeMillis(); + } - if (this.decodedText == null || this.isUnresolved) + if (this.decodedText == null || this.isUnresolved) { this.decodedText = this.decode(this.text); + } // If the text was fully decoded we can release our reference to the original text. - if (!this.isUnresolved) + if (!this.isUnresolved) { this.text = null; + } return this.decodedText; } - /** Perform entity substitution. */ + /** + * Perform entity substitution. + */ @Override - protected String decode(String textToDecode) - { - if (textToDecode == null) + protected String decode(String textToDecode) { + if (textToDecode == null) { return null; + } this.isUnresolved = false; Pattern p = Pattern.compile("\\$\\[(.*?)\\]"); Matcher m = p.matcher(textToDecode); StringBuffer sb = new StringBuffer(); - while (m.find()) - { + while (m.find()) { String entity = m.group(1); // Check the entity cache to see if we've already resolved this entity. String r = this.entityCache.get(entity); - if (r == null) - { + if (r == null) { // Try to resolve the entity r = this.resolveEntityReference(entity); - if (r != null) - { + if (r != null) { // Save the resolved entity in the cache, and set the last update time. Resolving this entity // has changed the decoded string. this.entityCache.put(entity, r); @@ -113,10 +113,11 @@ protected String decode(String textToDecode) return sb.toString(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public synchronized void setText(String input) - { + public synchronized void setText(String input) { super.setText(input); this.entityCache.clear(); } @@ -129,26 +130,26 @@ public synchronized void setText(String input) * DataField/displayName * SchemaName/SchemaField * SchemaName/SchemaField/displayName - * - * See the KML spec for details. + * See the KML spec for details. * * @param pattern Pattern of entity to resolve. * * @return Return the replacement string for the entity, or null if no replacement can be found. */ - protected String resolveEntityReference(String pattern) - { + protected String resolveEntityReference(String pattern) { KMLAbstractFeature feature = this.getFeature(); - if ("geDirections".equals(pattern)) + if ("geDirections".equals(pattern)) { return this.getGeDirectionsText(); + } // First look for a field in the Feature Object replacement = feature.getField(pattern); - if (replacement instanceof KMLAbstractObject) + if (replacement instanceof KMLAbstractObject) { return ((KMLAbstractObject) replacement).getCharacters(); - else if (replacement != null) + } else if (replacement != null) { return replacement.toString(); + } // Before searching data fields, split the pattern into name, field, and display name components String name; // Name of data element or schema @@ -168,22 +169,17 @@ else if (replacement != null) // Next look for a data field in the Feature's extended data KMLExtendedData extendedData = feature.getExtendedData(); - if (extendedData != null) - { + if (extendedData != null) { // Search through untyped data first - for (KMLData data : extendedData.getData()) - { - if (name.equals(data.getName())) - { - if (isDisplayName) - { - if (!WWUtil.isEmpty(data.getDisplayName())) + for (KMLData data : extendedData.getData()) { + if (name.equals(data.getName())) { + if (isDisplayName) { + if (!WWUtil.isEmpty(data.getDisplayName())) { return data.getDisplayName(); - else + } else { return data.getName(); - } - else - { + } + } else { return data.getValue(); } } @@ -192,49 +188,37 @@ else if (replacement != null) // Search through typed schema data fields boolean schemaUnresolved = false; List schemaDataList = extendedData.getSchemaData(); - for (KMLSchemaData schemaData : schemaDataList) - { + for (KMLSchemaData schemaData : schemaDataList) { // Try to resolve the schema. The schema may not be available immediately final String url = schemaData.getSchemaUrl(); KMLSchema schema = (KMLSchema) feature.getRoot().resolveReference(url); - if (schema != null && name.equals(schema.getName())) - { + if (schema != null && name.equals(schema.getName())) { // We found the schema. Now we are looking for either the display name or the value of // one of the fields. - if (isDisplayName) - { + if (isDisplayName) { // Search schema fields - for (KMLSimpleField simpleField : schema.getSimpleFields()) - { - if (field.equals(simpleField.getName())) - { + for (KMLSimpleField simpleField : schema.getSimpleFields()) { + if (field.equals(simpleField.getName())) { return simpleField.getDisplayName(); } } - } - else - { + } else { // Search data fields - for (KMLSimpleData simpleData : schemaData.getSimpleData()) - { - if (field.equals(simpleData.getName())) - { + for (KMLSimpleData simpleData : schemaData.getSimpleData()) { + if (field.equals(simpleData.getName())) { return simpleData.getCharacters(); } } } - } - else if (schema == null) - { + } else if (schema == null) { schemaUnresolved = true; } } // Set the balloon text to unresolved if we still haven't found a match, and there is at least one // unresolved schema, and the pattern could refer to a schema - if (schemaUnresolved && !WWUtil.isEmpty(name) && !WWUtil.isEmpty(field)) - { + if (schemaUnresolved && !WWUtil.isEmpty(name) && !WWUtil.isEmpty(field)) { this.isUnresolved = true; } } @@ -247,8 +231,7 @@ else if (schema == null) * * @return The context feature. */ - public KMLAbstractFeature getFeature() - { + public KMLAbstractFeature getFeature() { return this.feature; } @@ -258,8 +241,7 @@ public KMLAbstractFeature getFeature() * * @return Text to replace the $[geDirections] entity. */ - protected String getGeDirectionsText() - { + protected String getGeDirectionsText() { return ""; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLController.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLController.java index bbc9418413..b8494849f8 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLController.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.WWObjectImpl; @@ -18,53 +17,48 @@ * @author tag * @version $Id: KMLController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLController extends WWObjectImpl implements PreRenderable, Renderable, MessageListener -{ +public class KMLController extends WWObjectImpl implements PreRenderable, Renderable, MessageListener { + protected KMLRoot kmlRoot; protected KMLTraversalContext tc; - public KMLController(KMLRoot root) - { + public KMLController(KMLRoot root) { this.setKmlRoot(root); this.setTraversalContext(new KMLTraversalContext()); } - public KMLRoot getKmlRoot() - { + public KMLRoot getKmlRoot() { return this.kmlRoot; } - public void setKmlRoot(KMLRoot kmlRoot) - { + public void setKmlRoot(KMLRoot kmlRoot) { // Stop listening for property changes in previous KMLRoot KMLRoot oldRoot = this.getKmlRoot(); - if (oldRoot != null) + if (oldRoot != null) { oldRoot.removePropertyChangeListener(this); + } this.kmlRoot = kmlRoot; - if (kmlRoot != null) + if (kmlRoot != null) { kmlRoot.addPropertyChangeListener(this); + } } - public void setTraversalContext(KMLTraversalContext tc) - { + public void setTraversalContext(KMLTraversalContext tc) { this.tc = tc; } - public KMLTraversalContext getTraversalContext() - { + public KMLTraversalContext getTraversalContext() { return this.tc; } - public void preRender(DrawContext dc) - { + public void preRender(DrawContext dc) { this.initializeTraversalContext(this.getTraversalContext()); this.kmlRoot.preRender(this.getTraversalContext(), dc); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { this.initializeTraversalContext(this.getTraversalContext()); this.kmlRoot.render(this.getTraversalContext(), dc); } @@ -76,16 +70,15 @@ public void render(DrawContext dc) * * @param tc the KML traversal context to initialize. */ - protected void initializeTraversalContext(KMLTraversalContext tc) - { + protected void initializeTraversalContext(KMLTraversalContext tc) { tc.initialize(); tc.setDetailHint(this.kmlRoot.getDetailHint()); } @Override - public void onMessage(Message msg) - { - if (this.kmlRoot != null) + public void onMessage(Message msg) { + if (this.kmlRoot != null) { this.kmlRoot.onMessage(msg); + } } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLExportUtil.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLExportUtil.java index cbed63f5df..512e3b5a8a 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLExportUtil.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLExportUtil.java @@ -20,8 +20,8 @@ * @author tag * @version $Id: KMLExportUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLExportUtil -{ +public class KMLExportUtil { + /** * Convert a WorldWind altitude mode to a KML altitude mode. * @@ -31,11 +31,9 @@ public class KMLExportUtil * * @throws IllegalArgumentException If {@code altitudeMode} is not a valid WorldWind altitude mode. */ - public static String kmlAltitudeMode(int altitudeMode) - { + public static String kmlAltitudeMode(int altitudeMode) { final String kmlAltitude; - switch (altitudeMode) - { + switch (altitudeMode) { case WorldWind.CLAMP_TO_GROUND: kmlAltitude = "clampToGround"; break; @@ -59,20 +57,17 @@ public static String kmlAltitudeMode(int altitudeMode) * Export ShapeAttributes as KML Pair element in a StyleMap. This method assumes that the StyleMap tag has already * been written; it writes the Pair tag. * - * @param xmlWriter Writer to receive the Style element. - * @param styleType The type of style: normal or highlight. Value should match either {@link KMLConstants#NORMAL} - * or {@link KMLConstants#HIGHLIGHT} + * @param xmlWriter Writer to receive the Style element. + * @param styleType The type of style: normal or highlight. Value should match either {@link KMLConstants#NORMAL} or + * {@link KMLConstants#HIGHLIGHT} * @param attributes Attributes to export. The method takes no action if this parameter is null. * - * @throws javax.xml.stream.XMLStreamException - * if exception occurs writing XML. + * @throws javax.xml.stream.XMLStreamException if exception occurs writing XML. * @throws java.io.IOException if exception occurs exporting data. */ public static void exportAttributesAsKML(XMLStreamWriter xmlWriter, String styleType, ShapeAttributes attributes) - throws XMLStreamException, IOException - { - if (attributes != null) - { + throws XMLStreamException, IOException { + if (attributes != null) { xmlWriter.writeStartElement("Pair"); xmlWriter.writeStartElement("key"); xmlWriter.writeCharacters(styleType); @@ -87,16 +82,13 @@ public static void exportAttributesAsKML(XMLStreamWriter xmlWriter, String style * Export an {@link Offset} as a KML element. * * @param xmlWriter Writer to receive the Style element. - * @param offset The offset to export. If {@code offset} is null, nothing is written to the stream. - * @param tagName The name of the KML tag to create. + * @param offset The offset to export. If {@code offset} is null, nothing is written to the stream. + * @param tagName The name of the KML tag to create. * - * @throws javax.xml.stream.XMLStreamException - * if exception occurs writing XML. + * @throws javax.xml.stream.XMLStreamException if exception occurs writing XML. */ - public static void exportOffset(XMLStreamWriter xmlWriter, Offset offset, String tagName) throws XMLStreamException - { - if (offset != null) - { + public static void exportOffset(XMLStreamWriter xmlWriter, Offset offset, String tagName) throws XMLStreamException { + if (offset != null) { xmlWriter.writeStartElement(tagName); xmlWriter.writeAttribute("x", Double.toString(offset.getX())); xmlWriter.writeAttribute("y", Double.toString(offset.getY())); @@ -111,55 +103,45 @@ public static void exportOffset(XMLStreamWriter xmlWriter, Offset offset, String * * @param xmlWriter Writer to receive the Style element. * @param dimension The dimension to export. If {@code dimension} is null, nothing is written to the stream. - * @param tagName The name of the KML tag to create. + * @param tagName The name of the KML tag to create. * - * @throws javax.xml.stream.XMLStreamException - * if exception occurs writing XML. + * @throws javax.xml.stream.XMLStreamException if exception occurs writing XML. */ public static void exportDimension(XMLStreamWriter xmlWriter, Size dimension, String tagName) - throws XMLStreamException - { - if (dimension != null) - { + throws XMLStreamException { + if (dimension != null) { xmlWriter.writeStartElement(tagName); exportDimensionAttributes("x", xmlWriter, dimension.getWidthMode(), dimension.getWidth(), - dimension.getWidthUnits()); + dimension.getWidthUnits()); exportDimensionAttributes("y", xmlWriter, dimension.getHeightMode(), dimension.getHeight(), - dimension.getHeightUnits()); + dimension.getHeightUnits()); xmlWriter.writeEndElement(); } } /** - * Export the attributes of a Size. This method assumes that the dimension start tag has already been - * written to the stream. + * Export the attributes of a Size. This method assumes that the dimension start tag has already been written to the + * stream. * - * @param axes "x" or "y". + * @param axes "x" or "y". * @param xmlWriter Writer that will received exported data. - * @param sizeMode Size mode for this dimension. - * @param size The size of the dimension. - * @param units Units of {@code size}. + * @param sizeMode Size mode for this dimension. + * @param size The size of the dimension. + * @param units Units of {@code size}. * - * @throws javax.xml.stream.XMLStreamException - * if exception occurs writing XML. + * @throws javax.xml.stream.XMLStreamException if exception occurs writing XML. */ private static void exportDimensionAttributes(String axes, XMLStreamWriter xmlWriter, String sizeMode, double size, - String units) - throws XMLStreamException - { - if (Size.NATIVE_DIMENSION.equals(sizeMode)) - { + String units) + throws XMLStreamException { + if (Size.NATIVE_DIMENSION.equals(sizeMode)) { xmlWriter.writeAttribute(axes, "-1"); - } - else if (Size.MAINTAIN_ASPECT_RATIO.equals(sizeMode)) + } else if (Size.MAINTAIN_ASPECT_RATIO.equals(sizeMode)) { xmlWriter.writeAttribute(axes, "0"); - else if (Size.EXPLICIT_DIMENSION.equals(sizeMode)) - { + } else if (Size.EXPLICIT_DIMENSION.equals(sizeMode)) { xmlWriter.writeAttribute(axes, Double.toString(size)); xmlWriter.writeAttribute(axes + "units", KMLUtil.wwUnitsToKMLUnits(units)); - } - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnknownSizeMode", sizeMode)); } } @@ -170,45 +152,41 @@ else if (Size.EXPLICIT_DIMENSION.equals(sizeMode)) * @param hexString String to manipulate. * * @return The portion of {@code hexString} after the 0X. For example: "0X00FF00" => "00FF00". If the string does - * not begin with 0X, {@code hexString} is returned. The comparison is not case sensitive. + * not begin with 0X, {@code hexString} is returned. The comparison is not case sensitive. */ - public static String stripHexPrefix(String hexString) - { - if (hexString.startsWith("0x") || hexString.startsWith("0X")) + public static String stripHexPrefix(String hexString) { + if (hexString.startsWith("0x") || hexString.startsWith("0X")) { return hexString.substring(2); - else + } else { return hexString; + } } /** * Export the boundary of a polygon as a KML LinearRing. * * @param xmlWriter Writer to receive generated XML. - * @param boundary Boundary to export. - * @param altitude Altitude of the points in the ring. + * @param boundary Boundary to export. + * @param altitude Altitude of the points in the ring. * * @throws XMLStreamException if exception occurs writing XML. */ public static void exportBoundaryAsLinearRing(XMLStreamWriter xmlWriter, Iterable boundary, - Double altitude) - throws XMLStreamException - { + Double altitude) + throws XMLStreamException { String altitudeString = null; - if (altitude != null) - { + if (altitude != null) { altitudeString = Double.toString(altitude); } xmlWriter.writeStartElement("LinearRing"); xmlWriter.writeStartElement("coordinates"); - for (LatLon location : boundary) - { + for (LatLon location : boundary) { xmlWriter.writeCharacters(Double.toString(location.getLongitude().getDegrees())); xmlWriter.writeCharacters(","); xmlWriter.writeCharacters(Double.toString(location.getLatitude().getDegrees())); - if (altitudeString != null) - { + if (altitudeString != null) { xmlWriter.writeCharacters(","); xmlWriter.writeCharacters(altitudeString); } @@ -226,8 +204,7 @@ public static void exportBoundaryAsLinearRing(XMLStreamWriter xmlWriter, Iterabl * * @return "1" if {@code value} is true, otherwise "0". */ - public static String kmlBoolean(boolean value) - { + public static String kmlBoolean(boolean value) { return value ? "1" : "0"; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLExtrudedPolygonImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLExtrudedPolygonImpl.java index a831afd34a..2a872d1dda 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLExtrudedPolygonImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLExtrudedPolygonImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.WorldWind; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLExtrudedPolygonImpl.java 2151 2014-07-15 17:12:46Z tgaskins $ */ -public class KMLExtrudedPolygonImpl extends ExtrudedPolygon implements KMLRenderable -{ +public class KMLExtrudedPolygonImpl extends ExtrudedPolygon implements KMLRenderable { + protected final KMLAbstractFeature parent; protected boolean highlightAttributesResolved = false; protected boolean normalAttributesResolved = false; @@ -28,24 +27,21 @@ public class KMLExtrudedPolygonImpl extends ExtrudedPolygon implements KMLRender /** * Create an instance. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param placemark the Placemark element containing the LineString. - * @param geom the {@link KMLPolygon} geometry. + * @param geom the {@link KMLPolygon} geometry. * - * @throws NullPointerException if the geomtry is null. + * @throws NullPointerException if the geomtry is null. * @throws IllegalArgumentException if the parent placemark or the traversal context is null. */ - public KMLExtrudedPolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) - { - if (tc == null) - { + public KMLExtrudedPolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (placemark == null) - { + if (placemark == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -58,89 +54,82 @@ public KMLExtrudedPolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KM this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); // KML default String altMode = polygon.getAltitudeMode(); - if (!WWUtil.isEmpty(altMode)) - { - if ("clampToGround".equals(altMode)) + if (!WWUtil.isEmpty(altMode)) { + if ("clampToGround".equals(altMode)) { this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - else if ("relativeToGround".equals(altMode)) + } else if ("relativeToGround".equals(altMode)) { this.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); - else if ("absolute".equals(altMode)) + } else if ("absolute".equals(altMode)) { this.setAltitudeMode(WorldWind.ABSOLUTE); + } } KMLLinearRing outerBoundary = polygon.getOuterBoundary(); - if (outerBoundary != null) - { + if (outerBoundary != null) { Position.PositionList coords = outerBoundary.getCoordinates(); - if (coords != null && coords.list != null) + if (coords != null && coords.list != null) { this.setOuterBoundary(outerBoundary.getCoordinates().list); + } } Iterable innerBoundaries = polygon.getInnerBoundaries(); - if (innerBoundaries != null) - { - for (KMLLinearRing ring : innerBoundaries) - { + if (innerBoundaries != null) { + for (KMLLinearRing ring : innerBoundaries) { Position.PositionList coords = ring.getCoordinates(); - if (coords != null && coords.list != null) + if (coords != null && coords.list != null) { this.addInnerBoundary(ring.getCoordinates().list); + } } } - if (placemark.getName() != null) + if (placemark.getName() != null) { this.setValue(AVKey.DISPLAY_NAME, placemark.getName()); + } - if (placemark.getDescription() != null) + if (placemark.getDescription() != null) { this.setValue(AVKey.DESCRIPTION, placemark.getDescription()); + } - if (placemark.getSnippetText() != null) + if (placemark.getSnippetText() != null) { this.setValue(AVKey.SHORT_DESCRIPTION, placemark.getSnippetText()); + } this.setValue(AVKey.CONTEXT, this.parent); } - public void preRender(KMLTraversalContext tc, DrawContext dc) - { + public void preRender(KMLTraversalContext tc, DrawContext dc) { super.preRender(dc); } - public void render(KMLTraversalContext tc, DrawContext dc) - { + public void render(KMLTraversalContext tc, DrawContext dc) { // If the attributes are not inline or internal then they might not be resolved until the external KML // document is resolved. Therefore check to see if resolution has occurred. - if (this.isHighlighted()) - { - if (!this.highlightAttributesResolved) - { + if (this.isHighlighted()) { + if (!this.highlightAttributesResolved) { ShapeAttributes a = this.getCapHighlightAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.HIGHLIGHT); - if (a != null) - { + if (a != null) { this.setCapHighlightAttributes(a); this.setSideHighlightAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.highlightAttributesResolved = true; + } } } } - } - else - { - if (!this.normalAttributesResolved) - { + } else { + if (!this.normalAttributesResolved) { ShapeAttributes a = this.getCapAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.NORMAL); - if (a != null) - { + if (a != null) { this.setCapAttributes(a); this.setSideAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.normalAttributesResolved = true; + } } } } @@ -149,10 +138,11 @@ public void render(KMLTraversalContext tc, DrawContext dc) this.render(dc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected PickedObject createPickedObject(int colorCode) - { + protected PickedObject createPickedObject(int colorCode) { PickedObject po = super.createPickedObject(colorCode); // Add the KMLPlacemark to the picked object as the context of the picked object. @@ -167,29 +157,26 @@ protected PickedObject createPickedObject(int colorCode) * * @return the new attributes. */ - protected ShapeAttributes makeAttributesCurrent(String attrType) - { + protected ShapeAttributes makeAttributesCurrent(String attrType) { ShapeAttributes attrs = this.getInitialAttributes( - this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); + this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); // Get the KML sub-style for Line attributes. Map them to Shape attributes. - KMLAbstractSubStyle lineSubStyle = this.parent.getSubStyle(new KMLLineStyle(null), attrType); - if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) - { + if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) { KMLUtil.assembleLineAttributes(attrs, (KMLLineStyle) lineSubStyle); - if (lineSubStyle.hasField(AVKey.UNRESOLVED)) + if (lineSubStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } // Get the KML sub-style for interior attributes. Map them to Shape attributes. - KMLAbstractSubStyle fillSubStyle = this.parent.getSubStyle(new KMLPolyStyle(null), attrType); - if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) - { + if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) { KMLUtil.assembleInteriorAttributes(attrs, (KMLPolyStyle) fillSubStyle); - if (fillSubStyle.hasField(AVKey.UNRESOLVED)) + if (fillSubStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } attrs.setDrawInterior(((KMLPolyStyle) fillSubStyle).isFill()); attrs.setDrawOutline(((KMLPolyStyle) fillSubStyle).isOutline()); @@ -198,17 +185,13 @@ protected ShapeAttributes makeAttributesCurrent(String attrType) return attrs; } - protected ShapeAttributes getInitialAttributes(String attrType) - { + protected ShapeAttributes getInitialAttributes(String attrType) { ShapeAttributes attrs = new BasicShapeAttributes(); - if (KMLConstants.HIGHLIGHT.equals(attrType)) - { + if (KMLConstants.HIGHLIGHT.equals(attrType)) { attrs.setOutlineMaterial(Material.RED); attrs.setInteriorMaterial(Material.PINK); - } - else - { + } else { attrs.setOutlineMaterial(Material.WHITE); attrs.setInteriorMaterial(Material.LIGHT_GRAY); } @@ -217,19 +200,19 @@ protected ShapeAttributes getInitialAttributes(String attrType) } @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { super.onMessage(message); - if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) - { + if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) { this.normalAttributesResolved = false; this.highlightAttributesResolved = false; - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.getAttributes().setUnresolved(true); - if (this.getHighlightAttributes() != null) + } + if (this.getHighlightAttributes() != null) { this.getHighlightAttributes().setUnresolved(true); + } } } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLGlobeBalloonImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLGlobeBalloonImpl.java index 66aa59fe65..c330c7a09b 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLGlobeBalloonImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLGlobeBalloonImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.geom.Position; @@ -17,9 +16,11 @@ * @author pabercrombie * @version $Id: KMLGlobeBalloonImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLGlobeBalloonImpl extends KMLAbstractBalloon implements GlobeBalloon -{ - /** The contained balloon. */ +public class KMLGlobeBalloonImpl extends KMLAbstractBalloon implements GlobeBalloon { + + /** + * The contained balloon. + */ protected GlobeBalloon balloon; /** @@ -28,12 +29,10 @@ public class KMLGlobeBalloonImpl extends KMLAbstractBalloon implements GlobeBall * @param balloon Balloon to apply KML styling to. * @param feature The feature that defines the balloon style. */ - public KMLGlobeBalloonImpl(GlobeBalloon balloon, KMLAbstractFeature feature) - { + public KMLGlobeBalloonImpl(GlobeBalloon balloon, KMLAbstractFeature feature) { super(feature); - if (balloon == null) - { + if (balloon == null) { String msg = Logging.getMessage("nullValue.BalloonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -42,33 +41,38 @@ public KMLGlobeBalloonImpl(GlobeBalloon balloon, KMLAbstractFeature feature) this.initialize(balloon); } - /** {@inheritDoc} */ - public GlobeBalloon getBalloon() - { + /** + * {@inheritDoc} + */ + public GlobeBalloon getBalloon() { return this.balloon; } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setPosition(Position position) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setPosition(Position position) { this.getBalloon().setPosition(position); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Position getPosition() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Position getPosition() { return this.getBalloon().getPosition(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public int getAltitudeMode() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public int getAltitudeMode() { return this.getBalloon().getAltitudeMode(); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setAltitudeMode(int altitudeMode) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setAltitudeMode(int altitudeMode) { this.getBalloon().setAltitudeMode(altitudeMode); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLGroundOverlayPolygonImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLGroundOverlayPolygonImpl.java index 715b766a2c..e263faaf7c 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLGroundOverlayPolygonImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLGroundOverlayPolygonImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.WorldWind; @@ -23,8 +22,8 @@ * @author pabercrombie * @version $Id: KMLGroundOverlayPolygonImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLGroundOverlayPolygonImpl extends Polygon implements KMLRenderable -{ +public class KMLGroundOverlayPolygonImpl extends Polygon implements KMLRenderable { + protected final KMLGroundOverlay parent; protected boolean attributesResolved; @@ -32,23 +31,20 @@ public class KMLGroundOverlayPolygonImpl extends Polygon implements KMLRenderabl /** * Create an instance. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param overlay the {@link gov.nasa.worldwind.ogc.kml.KMLGroundOverlay} to render as a polygon. * - * @throws NullPointerException if the geomtry is null. + * @throws NullPointerException if the geomtry is null. * @throws IllegalArgumentException if the parent placemark or the traversal context is null. */ - public KMLGroundOverlayPolygonImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) - { - if (tc == null) - { + public KMLGroundOverlayPolygonImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (overlay == null) - { + if (overlay == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -57,12 +53,10 @@ public KMLGroundOverlayPolygonImpl(KMLTraversalContext tc, KMLGroundOverlay over this.parent = overlay; String altMode = overlay.getAltitudeMode(); - if (!WWUtil.isEmpty(altMode)) - { - if ("relativeToGround".equals(altMode)) + if (!WWUtil.isEmpty(altMode)) { + if ("relativeToGround".equals(altMode)) { this.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); - else if ("absolute".equals(altMode)) - { + } else if ("absolute".equals(altMode)) { this.setAltitudeMode(WorldWind.ABSOLUTE); } } @@ -73,26 +67,26 @@ else if ("absolute".equals(altMode)) // Apply rotation if the overlay includes a LatLonBox KMLLatLonBox box = overlay.getLatLonBox(); - if (box != null) - { + if (box != null) { this.setRotation(box.getRotation()); } - if (overlay.getName() != null) + if (overlay.getName() != null) { this.setValue(AVKey.DISPLAY_NAME, overlay.getName()); + } - if (overlay.getDescription() != null) + if (overlay.getDescription() != null) { this.setValue(AVKey.BALLOON_TEXT, overlay.getDescription()); + } - if (overlay.getSnippetText() != null) + if (overlay.getSnippetText() != null) { this.setValue(AVKey.SHORT_DESCRIPTION, overlay.getSnippetText()); + } // If no image is specified, draw a filled rectangle - if (this.parent.getIcon() == null || this.parent.getIcon().getHref() == null) - { + if (this.parent.getIcon() == null || this.parent.getIcon().getHref() == null) { String colorStr = overlay.getColor(); - if (!WWUtil.isEmpty(colorStr)) - { + if (!WWUtil.isEmpty(colorStr)) { Color color = WWUtil.decodeColorABGR(colorStr); ShapeAttributes attributes = new BasicShapeAttributes(); @@ -103,46 +97,45 @@ else if ("absolute".equals(altMode)) } } - /** {@inheritDoc} */ - public void preRender(KMLTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void preRender(KMLTraversalContext tc, DrawContext dc) { // Intentionally left blank; KML polygon does nothing during the preRender phase. } - protected boolean mustResolveHref() - { + protected boolean mustResolveHref() { return this.getTextureImageSource() == null - && this.parent.getIcon() != null - && this.parent.getIcon().getHref() != null; + && this.parent.getIcon() != null + && this.parent.getIcon().getHref() != null; } - /** {@inheritDoc} */ - public void render(KMLTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(KMLTraversalContext tc, DrawContext dc) { if (this.mustResolveHref()) // resolve the href to either a local file or a remote URL { // The icon reference may be to a support file within a KMZ file, so check for that. If it's not, then just // let the normal Polygon code resolve the reference. String href = this.parent.getIcon().getHref(); String localAddress = null; - try - { + try { localAddress = this.parent.getRoot().getSupportFilePath(href); - } - catch (IOException ignored) - { + } catch (IOException ignored) { } - float[] texCoords = new float[] {0, 0, 1, 0, 1, 1, 0, 1}; + float[] texCoords = new float[]{0, 0, 1, 0, 1, 1, 0, 1}; this.setTextureImageSource((localAddress != null ? localAddress : href), texCoords, 4); } this.render(dc); } - /** {@inheritDoc} */ - public boolean isHighlighted() - { + /** + * {@inheritDoc} + */ + public boolean isHighlighted() { return false; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLLineStringPlacemarkImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLLineStringPlacemarkImpl.java index 81e8c3c130..527f83512a 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLLineStringPlacemarkImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLLineStringPlacemarkImpl.java @@ -17,8 +17,8 @@ * @author tag * @version $Id: KMLLineStringPlacemarkImpl.java 2151 2014-07-15 17:12:46Z tgaskins $ */ -public class KMLLineStringPlacemarkImpl extends Path implements KMLRenderable -{ +public class KMLLineStringPlacemarkImpl extends Path implements KMLRenderable { + protected final KMLAbstractFeature parent; protected boolean highlightAttributesResolved = false; protected boolean normalAttributesResolved = false; @@ -26,26 +26,23 @@ public class KMLLineStringPlacemarkImpl extends Path implements KMLRenderable /** * Create an instance. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param placemark the Placemark element containing the LineString. - * @param geom the {@link KMLLineString} geometry. + * @param geom the {@link KMLLineString} geometry. * - * @throws NullPointerException if the geometry is null. + * @throws NullPointerException if the geometry is null. * @throws IllegalArgumentException if the parent placemark or the traversal context is null. */ - public KMLLineStringPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) - { + public KMLLineStringPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) { super(((KMLLineString) geom).getCoordinates()); - if (tc == null) - { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (placemark == null) - { + if (placemark == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -54,83 +51,80 @@ public KMLLineStringPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark this.parent = placemark; KMLLineString lineString = (KMLLineString) geom; - if (lineString.isExtrude()) + if (lineString.isExtrude()) { this.setExtrude(true); + } - if (lineString.getTessellate() != null && lineString.getTessellate()) + if (lineString.getTessellate() != null && lineString.getTessellate()) { this.setFollowTerrain(true); + } this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); // KML default String altMode = lineString.getAltitudeMode(); - if (!WWUtil.isEmpty(altMode)) - { - if ("clampToGround".equals(altMode)) + if (!WWUtil.isEmpty(altMode)) { + if ("clampToGround".equals(altMode)) { this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - else if ("relativeToGround".equals(altMode)) + } else if ("relativeToGround".equals(altMode)) { this.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); - else if ("absolute".equals(altMode)) + } else if ("absolute".equals(altMode)) { this.setAltitudeMode(WorldWind.ABSOLUTE); + } } // If the path is clamped to the ground and terrain conforming, draw as a great circle. Otherwise draw // as linear segments. - if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND && this.isFollowTerrain()) + if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND && this.isFollowTerrain()) { this.setPathType(AVKey.GREAT_CIRCLE); - else + } else { this.setPathType(AVKey.LINEAR); + } - if (placemark.getName() != null) + if (placemark.getName() != null) { this.setValue(AVKey.DISPLAY_NAME, placemark.getName()); + } - if (placemark.getDescription() != null) + if (placemark.getDescription() != null) { this.setValue(AVKey.DESCRIPTION, placemark.getDescription()); + } - if (placemark.getSnippetText() != null) + if (placemark.getSnippetText() != null) { this.setValue(AVKey.SHORT_DESCRIPTION, placemark.getSnippetText()); + } this.setValue(AVKey.CONTEXT, this.parent); } - public void preRender(KMLTraversalContext tc, DrawContext dc) - { + public void preRender(KMLTraversalContext tc, DrawContext dc) { super.preRender(dc); } - public void render(KMLTraversalContext tc, DrawContext dc) - { + public void render(KMLTraversalContext tc, DrawContext dc) { // If the attributes are not inline or internal then they might not be resolved until the external KML // document is resolved. Therefore check to see if resolution has occurred. - if (this.isHighlighted()) - { - if (!this.highlightAttributesResolved) - { + if (this.isHighlighted()) { + if (!this.highlightAttributesResolved) { ShapeAttributes a = this.getHighlightAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.HIGHLIGHT); - if (a != null) - { + if (a != null) { this.setHighlightAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.highlightAttributesResolved = true; + } } } } - } - else - { - if (!this.normalAttributesResolved) - { + } else { + if (!this.normalAttributesResolved) { ShapeAttributes a = this.getAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.NORMAL); - if (a != null) - { + if (a != null) { this.setAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.normalAttributesResolved = true; + } } } } @@ -139,10 +133,11 @@ public void render(KMLTraversalContext tc, DrawContext dc) this.render(dc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected PickedObject createPickedObject(int colorCode) - { + protected PickedObject createPickedObject(int colorCode) { PickedObject po = super.createPickedObject(colorCode); // Add the KMLPlacemark to the picked object as the context of the picked object. @@ -157,49 +152,43 @@ protected PickedObject createPickedObject(int colorCode) * * @return the new attributes. */ - protected ShapeAttributes makeAttributesCurrent(String attrType) - { + protected ShapeAttributes makeAttributesCurrent(String attrType) { ShapeAttributes attrs = this.getInitialAttributes( - this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); + this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); // Get the KML sub-style for Line attributes. Map them to Shape attributes. - KMLAbstractSubStyle lineSubStyle = this.parent.getSubStyle(new KMLLineStyle(null), attrType); - if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) - { + if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) { KMLUtil.assembleLineAttributes(attrs, (KMLLineStyle) lineSubStyle); - if (lineSubStyle.hasField(AVKey.UNRESOLVED)) + if (lineSubStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } // Get the KML sub-style for interior attributes. Map them to Shape attributes. - KMLAbstractSubStyle fillSubStyle = this.parent.getSubStyle(new KMLPolyStyle(null), attrType); - if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) - { + if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) { KMLUtil.assembleInteriorAttributes(attrs, (KMLPolyStyle) fillSubStyle); - if (fillSubStyle.hasField(AVKey.UNRESOLVED)) + if (fillSubStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } attrs.setDrawInterior(((KMLPolyStyle) fillSubStyle).isFill()); - if (this.isExtrude()) + if (this.isExtrude()) { attrs.setDrawOutline(((KMLPolyStyle) fillSubStyle).isOutline()); + } } return attrs; } - protected ShapeAttributes getInitialAttributes(String attrType) - { + protected ShapeAttributes getInitialAttributes(String attrType) { ShapeAttributes attrs = new BasicShapeAttributes(); - if (KMLConstants.HIGHLIGHT.equals(attrType)) - { + if (KMLConstants.HIGHLIGHT.equals(attrType)) { attrs.setOutlineMaterial(Material.RED); attrs.setInteriorMaterial(Material.PINK); - } - else - { + } else { attrs.setOutlineMaterial(Material.WHITE); attrs.setInteriorMaterial(Material.LIGHT_GRAY); } @@ -208,19 +197,19 @@ protected ShapeAttributes getInitialAttributes(String attrType) } @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { super.onMessage(message); - if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) - { + if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) { this.normalAttributesResolved = false; this.highlightAttributesResolved = false; - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.getAttributes().setUnresolved(true); - if (this.getHighlightAttributes() != null) + } + if (this.getHighlightAttributes() != null) { this.getHighlightAttributes().setUnresolved(true); + } } } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLModelPlacemarkImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLModelPlacemarkImpl.java index d8e207a992..eb2eddcae7 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLModelPlacemarkImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLModelPlacemarkImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.*; @@ -26,13 +25,19 @@ * @author pabercrombie * @version $Id: KMLModelPlacemarkImpl.java 1838 2014-02-05 20:48:12Z dcollins $ */ -public class KMLModelPlacemarkImpl extends WWObjectImpl implements KMLRenderable, ColladaResourceResolver -{ - /** Model rendered by this class. */ +public class KMLModelPlacemarkImpl extends WWObjectImpl implements KMLRenderable, ColladaResourceResolver { + + /** + * Model rendered by this class. + */ protected KMLModel model; - /** Placemark that contains the model. */ + /** + * Placemark that contains the model. + */ protected KMLPlacemark parent; - /** Reference to the COLLADA root that contains the parsed COLLADA file. */ + /** + * Reference to the COLLADA root that contains the parsed COLLADA file. + */ protected AtomicReference colladaRoot = new AtomicReference(); /** * Time, in milliseconds since the Epoch, at which this placemark's model resource was last retrieved. Initially @@ -46,37 +51,35 @@ public class KMLModelPlacemarkImpl extends WWObjectImpl implements KMLRenderable */ protected Map resourceMap; - /** Traversal context for rendering the ColladaRoot. */ + /** + * Traversal context for rendering the ColladaRoot. + */ protected ColladaTraversalContext colladaTraversalContext = new ColladaTraversalContext(); /** * Create an instance. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param placemark the Placemark element containing the Point. - * @param geom the {@link gov.nasa.worldwind.ogc.kml.KMLPoint} geometry. + * @param geom the {@link gov.nasa.worldwind.ogc.kml.KMLPoint} geometry. * - * @throws NullPointerException if the geometry is null. + * @throws NullPointerException if the geometry is null. * @throws IllegalArgumentException if the parent placemark or the traversal context is null. */ - public KMLModelPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) - { - if (tc == null) - { + public KMLModelPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (placemark == null) - { + if (placemark == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (geom == null) - { + if (geom == null) { String msg = Logging.getMessage("nullValue.GeometryIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -95,18 +98,16 @@ public KMLModelPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark, KML * * @return Map that relates relative paths in the COLLADA document to paths relative to the KML document. */ - protected Map createResourceMap(KMLModel model) - { + protected Map createResourceMap(KMLModel model) { Map map = new HashMap(); KMLResourceMap resourceMap = model.getResourceMap(); - if (resourceMap == null) + if (resourceMap == null) { return Collections.emptyMap(); + } - for (KMLAlias alias : resourceMap.getAliases()) - { - if (alias != null && !WWUtil.isEmpty(alias.getSourceRef()) && !WWUtil.isEmpty(alias.getTargetHref())) - { + for (KMLAlias alias : resourceMap.getAliases()) { + if (alias != null && !WWUtil.isEmpty(alias.getSourceRef()) && !WWUtil.isEmpty(alias.getTargetHref())) { map.put(alias.getSourceRef(), alias.getTargetHref()); } } @@ -120,10 +121,10 @@ protected Map createResourceMap(KMLModel model) * * @param root the Collada resource referenced by this placemark. May be null. */ - protected void setColladaRoot(ColladaRoot root) - { - if (root != null) + protected void setColladaRoot(ColladaRoot root) { + if (root != null) { this.configureColladaRoot(root); + } this.colladaRoot.set(root); } @@ -136,8 +137,7 @@ protected void setColladaRoot(ColladaRoot root) * * @see #setColladaRoot(gov.nasa.worldwind.ogc.collada.ColladaRoot) */ - protected ColladaRoot getColladaRoot() - { + protected ColladaRoot getColladaRoot() { return this.colladaRoot.get(); } @@ -146,8 +146,7 @@ protected ColladaRoot getColladaRoot() * * @param root COLLADA root to configure. */ - protected void configureColladaRoot(ColladaRoot root) - { + protected void configureColladaRoot(ColladaRoot root) { root.setResourceResolver(this); Position refPosition = this.model.getLocation().getPosition(); @@ -155,57 +154,59 @@ protected void configureColladaRoot(ColladaRoot root) root.setAltitudeMode(KMLUtil.convertAltitudeMode(this.model.getAltitudeMode(), WorldWind.CLAMP_TO_GROUND)); // KML default KMLOrientation orientation = this.model.getOrientation(); - if (orientation != null) - { + if (orientation != null) { Double d = orientation.getHeading(); - if (d != null) + if (d != null) { root.setHeading(Angle.fromDegrees(d)); + } d = orientation.getTilt(); - if (d != null) + if (d != null) { root.setPitch(Angle.fromDegrees(-d)); + } d = orientation.getRoll(); - if (d != null) + if (d != null) { root.setRoll(Angle.fromDegrees(-d)); + } } KMLScale scale = this.model.getScale(); - if (scale != null) - { + if (scale != null) { Double x = scale.getX(); Double y = scale.getY(); Double z = scale.getZ(); Vec4 modelScale = new Vec4( - x != null ? x : 1.0, - y != null ? y : 1.0, - z != null ? z : 1.0); + x != null ? x : 1.0, + y != null ? y : 1.0, + z != null ? z : 1.0); root.setModelScale(modelScale); } } - /** {@inheritDoc} */ - public void preRender(KMLTraversalContext tc, DrawContext dc) - { - if (this.mustRetrieveResource()) + /** + * {@inheritDoc} + */ + public void preRender(KMLTraversalContext tc, DrawContext dc) { + if (this.mustRetrieveResource()) { this.requestResource(dc); + } ColladaRoot root = this.getColladaRoot(); - if (root != null) - { + if (root != null) { this.colladaTraversalContext.initialize(); root.preRender(this.colladaTraversalContext, dc); } } - /** {@inheritDoc} */ - public void render(KMLTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(KMLTraversalContext tc, DrawContext dc) { ColladaRoot root = this.getColladaRoot(); - if (root != null) - { + if (root != null) { this.colladaTraversalContext.initialize(); root.render(this.colladaTraversalContext, dc); } @@ -216,39 +217,37 @@ public void render(KMLTraversalContext tc, DrawContext dc) * relative to the .dae file, not the kml file. If the COLLADA document may be contained in a KMZ archive the * resources will be resolved relative to the .dae file within the archive. Normally references in a KMZ are * resolved relative to the root of the archive, but Model references are an exception. See - * https://developers.google.com/kml/documentation/kmzarchives and https://developers.google.com/kml/documentation/kmlreference#model + * https://developers.google.com/kml/documentation/kmzarchives and + * https://developers.google.com/kml/documentation/kmlreference#model *

          * {@inheritDoc}. */ - public String resolveFilePath(String path) throws IOException - { + public String resolveFilePath(String path) throws IOException { KMLLink link = this.model.getLink(); // Check the resource map to see if an alias is defined for this resource. String alias = this.resourceMap.get(path); - if (alias != null) + if (alias != null) { path = alias; + } // If the path is relative then resolve it relative to the COLLADA file. File f = new File(path); - if (!f.isAbsolute() && link != null && link.getHref() != null) - { - try - { + if (!f.isAbsolute() && link != null && link.getHref() != null) { + try { URI base = new URI(null, link.getHref(), null); URI ref = new URI(null, path, null); path = base.resolve(ref).getPath(); - } - catch (URISyntaxException ignored) - { + } catch (URISyntaxException ignored) { // Ignored } } Object o = this.parent.getRoot().resolveReference(path); - if (o instanceof URL || o instanceof String) + if (o instanceof URL || o instanceof String) { return o.toString(); + } return null; } @@ -259,11 +258,11 @@ public String resolveFilePath(String path) throws IOException * * @return true if this placemark must retrieve its model resource, otherwise false. */ - protected boolean mustRetrieveResource() - { + protected boolean mustRetrieveResource() { KMLLink link = this.model.getLink(); - if (link == null) + if (link == null) { return false; + } // The resource must be retrieved if the link has been updated since the resource was // last retrieved, or if the resource has never been retrieved. @@ -276,21 +275,24 @@ protected boolean mustRetrieveResource() * * @param dc the current draw context. */ - protected void requestResource(DrawContext dc) - { - if (WorldWind.getTaskService().isFull()) + protected void requestResource(DrawContext dc) { + if (WorldWind.getTaskService().isFull()) { return; + } KMLLink link = this.model.getLink(); - if (link == null) + if (link == null) { return; + } String address = link.getAddress(dc); - if (address != null) + if (address != null) { address = address.trim(); + } - if (WWUtil.isEmpty(address)) + if (WWUtil.isEmpty(address)) { return; + } WorldWind.getTaskService().addTask(new RequestTask(this, address)); } @@ -306,46 +308,50 @@ protected void requestResource(DrawContext dc) * @throws java.io.IOException if a reading error occurs. * @throws javax.xml.stream.XMLStreamException if a parsing error occurs. */ - protected void retrieveModel(String address) throws IOException, XMLStreamException - { + protected void retrieveModel(String address) throws IOException, XMLStreamException { Object o = this.parent.getRoot().resolveReference(address); - if (o == null) + if (o == null) { return; + } ColladaRoot root = ColladaRoot.createAndParse(o); - if (root == null) + if (root == null) { return; + } this.setColladaRoot(root); this.resourceRetrievalTime.set(System.currentTimeMillis()); this.parent.getRoot().requestRedraw(); } - /** Attempts to find this model link resource file locally, and if that fails attempts to find it remotely. */ - protected static class RequestTask implements Runnable - { - /** The link associated with this request. */ + /** + * Attempts to find this model link resource file locally, and if that fails attempts to find it remotely. + */ + protected static class RequestTask implements Runnable { + + /** + * The link associated with this request. + */ protected final KMLModelPlacemarkImpl placemark; - /** The resource's address. */ + /** + * The resource's address. + */ protected final String address; /** * Construct a request task for a specified network link resource. * * @param placemark the placemark for which to construct the request task. - * @param address the address of the resource to request. + * @param address the address of the resource to request. */ - protected RequestTask(KMLModelPlacemarkImpl placemark, String address) - { - if (placemark == null) - { + protected RequestTask(KMLModelPlacemarkImpl placemark, String address) { + if (placemark == null) { String message = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (address == null) - { + if (address == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -355,58 +361,53 @@ protected RequestTask(KMLModelPlacemarkImpl placemark, String address) this.address = address; } - public void run() - { - if (Thread.currentThread().isInterrupted()) + public void run() { + if (Thread.currentThread().isInterrupted()) { return; // the task was cancelled because it's a duplicate or for some other reason - - try - { - this.placemark.retrieveModel(this.address); } - catch (IOException e) - { + try { + this.placemark.retrieveModel(this.address); + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionWhileReading", e.getMessage()); Logging.logger().warning(message); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", e.getMessage()); Logging.logger().warning(message); } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } RequestTask that = (RequestTask) o; - if (!this.address.equals(that.address)) + if (!this.address.equals(that.address)) { return false; + } //noinspection RedundantIfStatement - if (!this.placemark.equals(that.placemark)) + if (!this.placemark.equals(that.placemark)) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = placemark.hashCode(); result = 31 * result + address.hashCode(); return result; } @Override - public String toString() - { + public String toString() { return this.address; } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLPointPlacemarkImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLPointPlacemarkImpl.java index 6f87f6b187..42cafcd630 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLPointPlacemarkImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLPointPlacemarkImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.WorldWind; @@ -23,15 +22,19 @@ * @author tag * @version $Id: KMLPointPlacemarkImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLPointPlacemarkImpl extends PointPlacemark implements KMLRenderable -{ +public class KMLPointPlacemarkImpl extends PointPlacemark implements KMLRenderable { + protected final KMLPlacemark parent; protected boolean highlightAttributesResolved = false; protected boolean normalAttributesResolved = false; - /** Indicates the time at which the image source was specified. */ + /** + * Indicates the time at which the image source was specified. + */ protected long iconRetrievalTime; - /** Indicates the time at which the highlight image source was specified. */ + /** + * Indicates the time at which the highlight image source was specified. + */ protected long highlightIconRetrievalTime; public static final double DEFAULT_LABEL_SCALE_THRESHOLD = 1.0; @@ -45,26 +48,23 @@ public class KMLPointPlacemarkImpl extends PointPlacemark implements KMLRenderab /** * Create an instance. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param placemark the Placemark element containing the Point. - * @param geom the {@link KMLPoint} geometry. + * @param geom the {@link KMLPoint} geometry. * - * @throws NullPointerException if the geometry is null. + * @throws NullPointerException if the geometry is null. * @throws IllegalArgumentException if the parent placemark or the traversal context is null. */ - public KMLPointPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) - { + public KMLPointPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) { super(((KMLPoint) geom).getCoordinates()); - if (tc == null) - { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (placemark == null) - { + if (placemark == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -76,88 +76,78 @@ public KMLPointPlacemarkImpl(KMLTraversalContext tc, KMLPlacemark placemark, KML this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); // KML default - if (point.isExtrude()) + if (point.isExtrude()) { this.setLineEnabled(true); + } String altMode = point.getAltitudeMode(); - if (!WWUtil.isEmpty(altMode)) - { - if ("clampToGround".equals(altMode)) + if (!WWUtil.isEmpty(altMode)) { + if ("clampToGround".equals(altMode)) { this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); - else if ("relativeToGround".equals(altMode)) + } else if ("relativeToGround".equals(altMode)) { this.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); - else if ("absolute".equals(altMode)) + } else if ("absolute".equals(altMode)) { this.setAltitudeMode(WorldWind.ABSOLUTE); + } } - if (this.parent.getVisibility() != null) + if (this.parent.getVisibility() != null) { this.setVisible(this.parent.getVisibility()); + } - if (placemark.getName() != null) - { + if (placemark.getName() != null) { this.setLabelText(placemark.getName()); this.setValue(AVKey.DISPLAY_NAME, placemark.getName()); } String description = placemark.getDescription(); - if (description != null) + if (description != null) { this.setValue(AVKey.DESCRIPTION, description); + } - if (placemark.getSnippetText() != null) + if (placemark.getSnippetText() != null) { this.setValue(AVKey.SHORT_DESCRIPTION, placemark.getSnippetText()); + } this.setValue(AVKey.CONTEXT, this.parent); } - public void preRender(KMLTraversalContext tc, DrawContext dc) - { + public void preRender(KMLTraversalContext tc, DrawContext dc) { // Intentionally left blank; KML point placemark does nothing during the preRender phase. } - public void render(KMLTraversalContext tc, DrawContext dc) - { + public void render(KMLTraversalContext tc, DrawContext dc) { // If the attributes are not inline or internal then they might not be resolved until the external KML // document is resolved. Therefore check to see if resolution has occurred. - if (this.isHighlighted()) - { - if (!this.highlightAttributesResolved) - { + if (this.isHighlighted()) { + if (!this.highlightAttributesResolved) { PointPlacemarkAttributes a = this.getHighlightAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.HIGHLIGHT); - if (a != null) - { + if (a != null) { this.setHighlightAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.highlightAttributesResolved = true; - } - else - { + } + } else { // There are no highlight attributes, so we can stop looking for them. Note that this is // different from having unresolved highlight attributes (handled above). this.highlightAttributesResolved = true; } } } - } - else - { - if (!this.normalAttributesResolved) - { + } else { + if (!this.normalAttributesResolved) { PointPlacemarkAttributes a = this.getAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.NORMAL); - if (a != null) - { + if (a != null) { this.setAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.normalAttributesResolved = true; - } - else - { + } + } else { // There are no normal attributes, so we can stop looking for them. Note that this is different // from having unresolved attributes (handled above). this.normalAttributesResolved = true; @@ -169,21 +159,18 @@ public void render(KMLTraversalContext tc, DrawContext dc) this.render(dc); } - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); - if (this.mustRefreshIcon()) - { + if (this.mustRefreshIcon()) { String path = this.getActiveAttributes().getImageAddress(); - if (!WWUtil.isEmpty(path)) - { + if (!WWUtil.isEmpty(path)) { // Evict the resource from the file store if there is a cached resource older than the icon update // time. This prevents fetching a stale resource out of the cache when the Icon is updated. boolean highlighted = this.isHighlighted(); this.parent.getRoot().evictIfExpired(path, - highlighted ? this.highlightIconRetrievalTime : this.iconRetrievalTime); + highlighted ? this.highlightIconRetrievalTime : this.iconRetrievalTime); this.textures.remove(path); } } @@ -194,18 +181,14 @@ protected void determineActiveAttributes() * * @return True if the icon has expired and must be refreshed. */ - protected boolean mustRefreshIcon() - { + protected boolean mustRefreshIcon() { String mode; long retrievalTime; - if (this.isHighlighted()) - { + if (this.isHighlighted()) { mode = KMLConstants.HIGHLIGHT; retrievalTime = this.highlightIconRetrievalTime; - } - else - { + } else { mode = KMLConstants.NORMAL; retrievalTime = this.iconRetrievalTime; } @@ -219,11 +202,9 @@ protected boolean mustRefreshIcon() * {@inheritDoc} Overridden to set the expiration time of the placemark's icon based on the HTTP headers of the * linked resource. */ - protected WWTexture initializeTexture(String address) - { + protected WWTexture initializeTexture(String address) { WWTexture texture = super.initializeTexture(address); - if (texture != null) - { + if (texture != null) { // Query the KMLRoot for the expiration time. long expiration = this.parent.getRoot().getExpiration(address); @@ -231,22 +212,25 @@ protected WWTexture initializeTexture(String address) String mode = this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL; KMLIconStyle iconStyle = (KMLIconStyle) this.parent.getSubStyle(new KMLIconStyle(null), mode); KMLIcon icon = iconStyle.getIcon(); - if (icon != null) + if (icon != null) { icon.setExpirationTime(expiration); + } - if (this.isHighlighted()) + if (this.isHighlighted()) { this.highlightIconRetrievalTime = System.currentTimeMillis(); - else + } else { this.iconRetrievalTime = System.currentTimeMillis(); + } } return texture; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected PickedObject createPickedObject(DrawContext dc, Color pickColor) - { + protected PickedObject createPickedObject(DrawContext dc, Color pickColor) { PickedObject po = super.createPickedObject(dc, pickColor); // Add the KMLPlacemark to the picked object as the context of the picked object. @@ -261,12 +245,11 @@ protected PickedObject createPickedObject(DrawContext dc, Color pickColor) * @return True if the label must be drawn. */ @Override - protected boolean mustDrawLabel() - { + protected boolean mustDrawLabel() { double labelScale = this.getActiveAttributes().getLabelScale() != null - ? this.getActiveAttributes().getLabelScale() : PointPlacemarkAttributes.DEFAULT_LABEL_SCALE; + ? this.getActiveAttributes().getLabelScale() : PointPlacemarkAttributes.DEFAULT_LABEL_SCALE; double imageScale = this.getActiveAttributes().getScale() != null - ? this.getActiveAttributes().getScale() : PointPlacemarkAttributes.DEFAULT_IMAGE_SCALE; + ? this.getActiveAttributes().getScale() : PointPlacemarkAttributes.DEFAULT_IMAGE_SCALE; return this.isHighlighted() || labelScale >= this.getLabelScaleThreshold() || imageScale == 0; } @@ -277,106 +260,96 @@ protected boolean mustDrawLabel() * @param attrType the type of attributes, either {@link KMLConstants#NORMAL} or {@link KMLConstants#HIGHLIGHT}. * * @return The new attributes, or null if there are no attributes defined. Returns a partially empty attributes - * bundle marked unresolved if any of placemark KML styles are unresolved. + * bundle marked unresolved if any of placemark KML styles are unresolved. */ - protected PointPlacemarkAttributes makeAttributesCurrent(String attrType) - { + protected PointPlacemarkAttributes makeAttributesCurrent(String attrType) { boolean hasLineStyle = false; boolean hasIconStyle = false; boolean hasLabelStyle = false; PointPlacemarkAttributes attrs = this.getInitialAttributes( - this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); + this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); // Get the KML sub-style for Line attributes. Map them to Shape attributes. - KMLAbstractSubStyle subStyle = this.parent.getSubStyle(new KMLLineStyle(null), attrType); - if (subStyle.hasFields() && (!this.isHighlighted() || KMLUtil.isHighlightStyleState(subStyle))) - { + if (subStyle.hasFields() && (!this.isHighlighted() || KMLUtil.isHighlightStyleState(subStyle))) { hasLineStyle = true; this.assembleLineAttributes(attrs, (KMLLineStyle) subStyle); - if (subStyle.hasField(AVKey.UNRESOLVED)) + if (subStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } subStyle = this.parent.getSubStyle(new KMLIconStyle(null), attrType); - if (subStyle.hasFields() && (!this.isHighlighted() || KMLUtil.isHighlightStyleState(subStyle))) - { + if (subStyle.hasFields() && (!this.isHighlighted() || KMLUtil.isHighlightStyleState(subStyle))) { hasIconStyle = true; this.assemblePointAttributes(attrs, (KMLIconStyle) subStyle); - if (subStyle.hasField(AVKey.UNRESOLVED)) + if (subStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } subStyle = this.parent.getSubStyle(new KMLLabelStyle(null), attrType); - if (subStyle.hasFields() && (!this.isHighlighted() || KMLUtil.isHighlightStyleState(subStyle))) - { + if (subStyle.hasFields() && (!this.isHighlighted() || KMLUtil.isHighlightStyleState(subStyle))) { hasLabelStyle = true; this.assembleLabelAttributes(attrs, (KMLLabelStyle) subStyle); - if (subStyle.hasField(AVKey.UNRESOLVED)) + if (subStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } // Return the attributes only if we actually found a KML style. If no style was found, return null instead of an // empty attributes bundle. If a style was found, but could not be resolved, we will return a partially empty // attributes bundle that is marked unresolved. - if (hasLineStyle || hasIconStyle || hasLabelStyle) + if (hasLineStyle || hasIconStyle || hasLabelStyle) { return attrs; - else + } else { return null; + } } - protected PointPlacemarkAttributes assemblePointAttributes(PointPlacemarkAttributes attrs, KMLIconStyle style) - { + protected PointPlacemarkAttributes assemblePointAttributes(PointPlacemarkAttributes attrs, KMLIconStyle style) { KMLIcon icon = style.getIcon(); - if (icon != null && icon.getHref() != null) - { + if (icon != null && icon.getHref() != null) { // The icon reference may be to a support file within a KMZ file, so check for that. If it's not, then just // let the normal PointPlacemark code resolve the reference. String href = icon.getHref(); String localAddress = null; - try - { + try { localAddress = this.parent.getRoot().getSupportFilePath(href); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.UnableToResolveReference", href); Logging.logger().warning(message); } attrs.setImageAddress((localAddress != null ? localAddress : href)); - } - // If the Icon element is present, but there is no href, draw a point instead of the default icon. - else if (icon != null && WWUtil.isEmpty(icon.getHref())) - { + } // If the Icon element is present, but there is no href, draw a point instead of the default icon. + else if (icon != null && WWUtil.isEmpty(icon.getHref())) { attrs.setUsePointAsDefaultImage(true); } // Assign the other attributes defined in the KML Feature element. - - if (style.getColor() != null) + if (style.getColor() != null) { attrs.setImageColor(WWUtil.decodeColorABGR(style.getColor())); + } - if (style.getColorMode() != null && "random".equals(style.getColorMode())) + if (style.getColorMode() != null && "random".equals(style.getColorMode())) { attrs.setImageColor(WWUtil.makeRandomColor(attrs.getImageColor())); + } - if (style.getScale() != null) + if (style.getScale() != null) { attrs.setScale(style.getScale()); + } - if (style.getHeading() != null) - { + if (style.getHeading() != null) { attrs.setHeading(style.getHeading()); attrs.setHeadingReference(AVKey.RELATIVE_TO_GLOBE); // KML spec is not clear about this } - if (style.getHotSpot() != null) - { + if (style.getHotSpot() != null) { KMLVec2 hs = style.getHotSpot(); attrs.setImageOffset(new Offset(hs.getX(), hs.getY(), KMLUtil.kmlUnitsToWWUnits(hs.getXunits()), - KMLUtil.kmlUnitsToWWUnits(hs.getYunits()))); - } - else - { + KMLUtil.kmlUnitsToWWUnits(hs.getYunits()))); + } else { // By default, use the center of the image as the offset. attrs.setImageOffset(new Offset(0.5, 0.5, AVKey.FRACTION, AVKey.FRACTION)); } @@ -384,34 +357,38 @@ else if (icon != null && WWUtil.isEmpty(icon.getHref())) return attrs; } - protected PointPlacemarkAttributes assembleLineAttributes(PointPlacemarkAttributes attrs, KMLLineStyle style) - { + protected PointPlacemarkAttributes assembleLineAttributes(PointPlacemarkAttributes attrs, KMLLineStyle style) { // Assign the attributes defined in the KML Feature element. - if (style.getWidth() != null) + if (style.getWidth() != null) { attrs.setLineWidth(style.getWidth()); + } - if (style.getColor() != null) + if (style.getColor() != null) { attrs.setLineColor(style.getColor()); + } - if (style.getColorMode() != null && "random".equals(style.getColorMode())) + if (style.getColorMode() != null && "random".equals(style.getColorMode())) { attrs.setLineMaterial(new Material(WWUtil.makeRandomColor(attrs.getLineColor()))); + } return attrs; } - protected PointPlacemarkAttributes assembleLabelAttributes(PointPlacemarkAttributes attrs, KMLLabelStyle style) - { + protected PointPlacemarkAttributes assembleLabelAttributes(PointPlacemarkAttributes attrs, KMLLabelStyle style) { // Assign the attributes defined in the KML Feature element. - if (style.getScale() != null) + if (style.getScale() != null) { attrs.setLabelScale(style.getScale()); + } - if (style.getColor() != null) + if (style.getColor() != null) { attrs.setLabelColor(style.getColor()); + } - if (style.getColorMode() != null && "random".equals(style.getColorMode())) + if (style.getColorMode() != null && "random".equals(style.getColorMode())) { attrs.setLabelMaterial(new Material(WWUtil.makeRandomColor(attrs.getLabelColor()))); + } return attrs; } @@ -424,8 +401,7 @@ protected PointPlacemarkAttributes assembleLabelAttributes(PointPlacemarkAttribu * @return New placemark attributes. */ @SuppressWarnings({"UnusedDeclaration"}) - protected PointPlacemarkAttributes getInitialAttributes(String attrType) - { + protected PointPlacemarkAttributes getInitialAttributes(String attrType) { return new PointPlacemarkAttributes(); } @@ -437,8 +413,7 @@ protected PointPlacemarkAttributes getInitialAttributes(String attrType) * * @see #setLabelScaleThreshold(double) */ - public double getLabelScaleThreshold() - { + public double getLabelScaleThreshold() { return this.labelScaleThreshold; } @@ -450,25 +425,24 @@ public double getLabelScaleThreshold() * * @see #getLabelScaleThreshold() */ - public void setLabelScaleThreshold(double labelScaleThreshold) - { + public void setLabelScaleThreshold(double labelScaleThreshold) { this.labelScaleThreshold = labelScaleThreshold; } @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { super.onMessage(message); - if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) - { + if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) { this.normalAttributesResolved = false; this.highlightAttributesResolved = false; - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.getAttributes().setUnresolved(true); - if (this.getHighlightAttributes() != null) + } + if (this.getHighlightAttributes() != null) { this.getHighlightAttributes().setUnresolved(true); + } } } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLPolygonImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLPolygonImpl.java index 3b4acf2c6d..4383196622 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLPolygonImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLPolygonImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.WorldWind; @@ -19,8 +18,8 @@ * @author tag * @version $Id: KMLPolygonImpl.java 2151 2014-07-15 17:12:46Z tgaskins $ */ -public class KMLPolygonImpl extends Polygon implements KMLRenderable -{ +public class KMLPolygonImpl extends Polygon implements KMLRenderable { + protected final KMLAbstractFeature parent; protected boolean highlightAttributesResolved = false; protected boolean normalAttributesResolved = false; @@ -28,24 +27,21 @@ public class KMLPolygonImpl extends Polygon implements KMLRenderable /** * Create an instance. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param placemark the Placemark element containing the LineString. - * @param geom the {@link gov.nasa.worldwind.ogc.kml.KMLPolygon} geometry. + * @param geom the {@link gov.nasa.worldwind.ogc.kml.KMLPolygon} geometry. * - * @throws NullPointerException if the geometry is null. + * @throws NullPointerException if the geometry is null. * @throws IllegalArgumentException if the parent placemark or the traversal context is null. */ - public KMLPolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) - { - if (tc == null) - { + public KMLPolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (placemark == null) - { + if (placemark == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -58,85 +54,78 @@ public KMLPolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstrac this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); // KML default String altMode = polygon.getAltitudeMode(); - if (!WWUtil.isEmpty(altMode)) - { - if ("relativeToGround".equals(altMode)) + if (!WWUtil.isEmpty(altMode)) { + if ("relativeToGround".equals(altMode)) { this.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); - else if ("absolute".equals(altMode)) + } else if ("absolute".equals(altMode)) { this.setAltitudeMode(WorldWind.ABSOLUTE); + } } KMLLinearRing outerBoundary = polygon.getOuterBoundary(); - if (outerBoundary != null) - { + if (outerBoundary != null) { Position.PositionList coords = outerBoundary.getCoordinates(); - if (coords != null && coords.list != null) + if (coords != null && coords.list != null) { this.setOuterBoundary(outerBoundary.getCoordinates().list); + } } Iterable innerBoundaries = polygon.getInnerBoundaries(); - if (innerBoundaries != null) - { - for (KMLLinearRing ring : innerBoundaries) - { + if (innerBoundaries != null) { + for (KMLLinearRing ring : innerBoundaries) { Position.PositionList coords = ring.getCoordinates(); - if (coords != null && coords.list != null) + if (coords != null && coords.list != null) { this.addInnerBoundary(ring.getCoordinates().list); + } } } - if (placemark.getName() != null) + if (placemark.getName() != null) { this.setValue(AVKey.DISPLAY_NAME, placemark.getName()); + } - if (placemark.getDescription() != null) + if (placemark.getDescription() != null) { this.setValue(AVKey.DESCRIPTION, placemark.getDescription()); + } - if (placemark.getSnippetText() != null) + if (placemark.getSnippetText() != null) { this.setValue(AVKey.SHORT_DESCRIPTION, placemark.getSnippetText()); + } this.setValue(AVKey.CONTEXT, this.parent); } - public void preRender(KMLTraversalContext tc, DrawContext dc) - { + public void preRender(KMLTraversalContext tc, DrawContext dc) { super.preRender(dc); } - public void render(KMLTraversalContext tc, DrawContext dc) - { + public void render(KMLTraversalContext tc, DrawContext dc) { // If the attributes are not inline or internal then they might not be resolved until the external KML // document is resolved. Therefore check to see if resolution has occurred. - if (this.isHighlighted()) - { - if (!this.highlightAttributesResolved) - { + if (this.isHighlighted()) { + if (!this.highlightAttributesResolved) { ShapeAttributes a = this.getHighlightAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.HIGHLIGHT); - if (a != null) - { + if (a != null) { this.setHighlightAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.highlightAttributesResolved = true; + } } } } - } - else - { - if (!this.normalAttributesResolved) - { + } else { + if (!this.normalAttributesResolved) { ShapeAttributes a = this.getAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.NORMAL); - if (a != null) - { + if (a != null) { this.setAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.normalAttributesResolved = true; + } } } } @@ -145,10 +134,11 @@ public void render(KMLTraversalContext tc, DrawContext dc) this.render(dc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected PickedObject createPickedObject(int colorCode) - { + protected PickedObject createPickedObject(int colorCode) { PickedObject po = super.createPickedObject(colorCode); // Add the KMLPlacemark to the picked object as the context of the picked object. @@ -163,29 +153,26 @@ protected PickedObject createPickedObject(int colorCode) * * @return the new attributes. */ - protected ShapeAttributes makeAttributesCurrent(String attrType) - { + protected ShapeAttributes makeAttributesCurrent(String attrType) { ShapeAttributes attrs = this.getInitialAttributes( - this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); + this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); // Get the KML sub-style for Line attributes. Map them to Shape attributes. - KMLAbstractSubStyle lineSubStyle = this.parent.getSubStyle(new KMLLineStyle(null), attrType); - if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) - { + if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) { KMLUtil.assembleLineAttributes(attrs, (KMLLineStyle) lineSubStyle); - if (lineSubStyle.hasField(AVKey.UNRESOLVED)) + if (lineSubStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } // Get the KML sub-style for interior attributes. Map them to Shape attributes. - KMLAbstractSubStyle fillSubStyle = this.parent.getSubStyle(new KMLPolyStyle(null), attrType); - if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) - { + if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) { KMLUtil.assembleInteriorAttributes(attrs, (KMLPolyStyle) fillSubStyle); - if (fillSubStyle.hasField(AVKey.UNRESOLVED)) + if (fillSubStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } attrs.setDrawInterior(((KMLPolyStyle) fillSubStyle).isFill()); @@ -194,17 +181,13 @@ protected ShapeAttributes makeAttributesCurrent(String attrType) return attrs; } - protected ShapeAttributes getInitialAttributes(String attrType) - { + protected ShapeAttributes getInitialAttributes(String attrType) { ShapeAttributes attrs = new BasicShapeAttributes(); - if (KMLConstants.HIGHLIGHT.equals(attrType)) - { + if (KMLConstants.HIGHLIGHT.equals(attrType)) { attrs.setOutlineMaterial(Material.RED); attrs.setInteriorMaterial(Material.PINK); - } - else - { + } else { attrs.setOutlineMaterial(Material.WHITE); attrs.setInteriorMaterial(Material.LIGHT_GRAY); } @@ -213,19 +196,19 @@ protected ShapeAttributes getInitialAttributes(String attrType) } @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { super.onMessage(message); - if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) - { + if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) { this.normalAttributesResolved = false; this.highlightAttributesResolved = false; - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.getAttributes().setUnresolved(true); - if (this.getHighlightAttributes() != null) + } + if (this.getHighlightAttributes() != null) { this.getHighlightAttributes().setUnresolved(true); + } } } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLRenderable.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLRenderable.java index b0de297d9d..4297f9cbbe 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLRenderable.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLRenderable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.event.MessageListener; @@ -15,8 +14,8 @@ * @author tag * @version $Id: KMLRenderable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface KMLRenderable extends MessageListener -{ +public interface KMLRenderable extends MessageListener { + /** * Pre-render this element. * diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLScreenBalloonImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLScreenBalloonImpl.java index 5762cfbf52..e0ba9dcb90 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLScreenBalloonImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLScreenBalloonImpl.java @@ -17,9 +17,11 @@ * @author pabercrombie * @version $Id: KMLScreenBalloonImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLScreenBalloonImpl extends KMLAbstractBalloon implements ScreenBalloon -{ - /** The contained balloon. */ +public class KMLScreenBalloonImpl extends KMLAbstractBalloon implements ScreenBalloon { + + /** + * The contained balloon. + */ protected ScreenBalloon balloon; /** @@ -28,12 +30,10 @@ public class KMLScreenBalloonImpl extends KMLAbstractBalloon implements ScreenBa * @param balloon Balloon to apply KML styling to. * @param feature The feature that defines the balloon style. */ - public KMLScreenBalloonImpl(ScreenBalloon balloon, KMLAbstractFeature feature) - { + public KMLScreenBalloonImpl(ScreenBalloon balloon, KMLAbstractFeature feature) { super(feature); - if (balloon == null) - { + if (balloon == null) { String msg = Logging.getMessage("nullValue.BalloonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -42,21 +42,24 @@ public KMLScreenBalloonImpl(ScreenBalloon balloon, KMLAbstractFeature feature) this.initialize(balloon); } - /** {@inheritDoc} */ - public ScreenBalloon getBalloon() - { + /** + * {@inheritDoc} + */ + public ScreenBalloon getBalloon() { return this.balloon; } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public void setScreenLocation(Point point) - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public void setScreenLocation(Point point) { this.getBalloon().setScreenLocation(point); } - /** {@inheritDoc}. This method passes through to the contained balloon. */ - public Point getScreenLocation() - { + /** + * {@inheritDoc}. This method passes through to the contained balloon. + */ + public Point getScreenLocation() { return this.getBalloon().getScreenLocation(); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLScreenImageImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLScreenImageImpl.java index 797a5092d7..4688e9ae69 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLScreenImageImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLScreenImageImpl.java @@ -18,80 +18,78 @@ * @author pabercrombie * @version $Id: KMLScreenImageImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLScreenImageImpl extends ScreenImage implements KMLRenderable -{ - /** Size value that KML uses to indicate that the native image dimension should be maintained. */ +public class KMLScreenImageImpl extends ScreenImage implements KMLRenderable { + + /** + * Size value that KML uses to indicate that the native image dimension should be maintained. + */ protected static final int KML_NATIVE_DIMENSION = -1; - /** Size value that KML uses to indicate that the image aspect ration should be maintained. */ + /** + * Size value that KML uses to indicate that the image aspect ration should be maintained. + */ protected static final int KML_MAINTAIN_ASPECT_RATIO = 0; protected final KMLScreenOverlay parent; - /** Indicates the time at which the image source was specified. */ + /** + * Indicates the time at which the image source was specified. + */ protected long iconRetrievalTime; /** * Create an screen image. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param overlay the Overlay element containing. * - * @throws NullPointerException if the traversal context is null. + * @throws NullPointerException if the traversal context is null. * @throws IllegalArgumentException if the parent overlay or the traversal context is null. */ - public KMLScreenImageImpl(KMLTraversalContext tc, KMLScreenOverlay overlay) - { + public KMLScreenImageImpl(KMLTraversalContext tc, KMLScreenOverlay overlay) { this.parent = overlay; - if (tc == null) - { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (overlay == null) - { + if (overlay == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } KMLVec2 xy = this.parent.getScreenXY(); - if (xy != null) - { + if (xy != null) { this.screenOffset = new Offset(xy.getX(), xy.getY(), KMLUtil.kmlUnitsToWWUnits(xy.getXunits()), - KMLUtil.kmlUnitsToWWUnits(xy.getYunits())); + KMLUtil.kmlUnitsToWWUnits(xy.getYunits())); } xy = this.parent.getOverlayXY(); - if (xy != null) - { + if (xy != null) { this.imageOffset = new Offset(xy.getX(), xy.getY(), KMLUtil.kmlUnitsToWWUnits(xy.getXunits()), - KMLUtil.kmlUnitsToWWUnits(xy.getYunits())); + KMLUtil.kmlUnitsToWWUnits(xy.getYunits())); } this.setRotation(overlay.getRotation()); xy = this.parent.getRotationXY(); - if (xy != null) - { + if (xy != null) { setRotationOffset(new Offset(xy.getX(), xy.getY(), KMLUtil.kmlUnitsToWWUnits(xy.getXunits()), - KMLUtil.kmlUnitsToWWUnits(xy.getYunits()))); + KMLUtil.kmlUnitsToWWUnits(xy.getYunits()))); } String colorStr = overlay.getColor(); - if (colorStr != null) - { + if (colorStr != null) { Color color = WWUtil.decodeColorABGR(colorStr); this.setColor(color); } // Compute desired image size, and the scale factor that will make it that size KMLVec2 kmlSize = this.parent.getSize(); - if (kmlSize != null) - { + if (kmlSize != null) { Size size = new Size(); size.setWidth(getSizeMode(kmlSize.getX()), kmlSize.getX(), KMLUtil.kmlUnitsToWWUnits(kmlSize.getXunits())); size.setHeight(getSizeMode(kmlSize.getY()), kmlSize.getY(), KMLUtil.kmlUnitsToWWUnits(kmlSize.getYunits())); @@ -99,9 +97,10 @@ public KMLScreenImageImpl(KMLTraversalContext tc, KMLScreenOverlay overlay) } } - /** {@inheritDoc} */ - public void preRender(KMLTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void preRender(KMLTraversalContext tc, DrawContext dc) { // No pre-rendering } @@ -111,12 +110,12 @@ public void preRender(KMLTraversalContext tc, DrawContext dc) * * @return True if the image source must be resolved. */ - protected boolean mustResolveHref() - { + protected boolean mustResolveHref() { KMLIcon icon = this.parent.getIcon(); //noinspection SimplifiableIfStatement - if (icon == null || icon.getHref() == null) + if (icon == null || icon.getHref() == null) { return false; + } // Resolve the reference if the image hasn't been retrieved, or if the link has expired. return this.getImageSource() == null || icon.getUpdateTime() > this.iconRetrievalTime; @@ -127,18 +126,14 @@ protected boolean mustResolveHref() * * @return The resolved path to the image source. */ - protected String resolveHref() - { + protected String resolveHref() { // The icon reference may be to a support file within a KMZ file, so check for that. If it's not, then just // let the normal ScreenImage code resolve the reference. String href = this.parent.getIcon().getHref(); String localAddress = null; - try - { + try { localAddress = this.parent.getRoot().getSupportFilePath(href); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.UnableToResolveReference", href); Logging.logger().warning(message); } @@ -146,9 +141,10 @@ protected String resolveHref() return localAddress != null ? localAddress : href; } - /** {@inheritDoc} */ - public void render(KMLTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(KMLTraversalContext tc, DrawContext dc) { if (this.mustResolveHref()) // resolve the href to either a local file or a remote URL { String path = this.resolveHref(); @@ -167,11 +163,9 @@ public void render(KMLTraversalContext tc, DrawContext dc) * {@inheritDoc} Overridden to set the link expiration time based on HTTP headers after the image has been * retrieved. */ - protected BasicWWTexture initializeTexture() - { + protected BasicWWTexture initializeTexture() { BasicWWTexture ret = super.initializeTexture(); - if (this.texture != null) - { + if (this.texture != null) { this.iconRetrievalTime = System.currentTimeMillis(); String path = this.resolveHref(); @@ -193,22 +187,24 @@ protected BasicWWTexture initializeTexture() * * @param size The KML size attribute * - * @return One of {@link gov.nasa.worldwind.render.Size#NATIVE_DIMENSION}, {@link gov.nasa.worldwind.render.Size#MAINTAIN_ASPECT_RATIO}, - * or {@link gov.nasa.worldwind.render.Size#EXPLICIT_DIMENSION}. + * @return One of + * {@link gov.nasa.worldwind.render.Size#NATIVE_DIMENSION}, {@link gov.nasa.worldwind.render.Size#MAINTAIN_ASPECT_RATIO}, + * or {@link gov.nasa.worldwind.render.Size#EXPLICIT_DIMENSION}. */ - protected String getSizeMode(Double size) - { + protected String getSizeMode(Double size) { // KML spec requires a value, but if there isn't one, use the image's native size. - if (size == null) + if (size == null) { return Size.NATIVE_DIMENSION; + } int s = (int) size.doubleValue(); - if (s == KML_NATIVE_DIMENSION) + if (s == KML_NATIVE_DIMENSION) { return Size.NATIVE_DIMENSION; - else if (size == KML_MAINTAIN_ASPECT_RATIO) + } else if (size == KML_MAINTAIN_ASPECT_RATIO) { return Size.MAINTAIN_ASPECT_RATIO; - else + } else { return Size.EXPLICIT_DIMENSION; + } } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLSurfaceImageImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLSurfaceImageImpl.java index 404282567d..7e706ad3f7 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLSurfaceImageImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLSurfaceImageImpl.java @@ -19,15 +19,19 @@ * @author pabercrombie * @version $Id: KMLSurfaceImageImpl.java 1551 2013-08-17 18:00:09Z pabercrombie $ */ -public class KMLSurfaceImageImpl extends SurfaceImage implements KMLRenderable -{ +public class KMLSurfaceImageImpl extends SurfaceImage implements KMLRenderable { + protected KMLGroundOverlay parent; protected boolean attributesResolved; - /** Indicates that the source texture has been resolved and loaded. */ + /** + * Indicates that the source texture has been resolved and loaded. + */ protected boolean textureResolved; - /** Indicates the time at which the image source was specified. */ + /** + * Indicates the time at which the image source was specified. + */ protected long iconRetrievalTime; /** @@ -39,25 +43,22 @@ public class KMLSurfaceImageImpl extends SurfaceImage implements KMLRenderable /** * Create an screen image. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param overlay the Overlay element containing. * - * @throws NullPointerException if the traversal context is null. + * @throws NullPointerException if the traversal context is null. * @throws IllegalArgumentException if the parent overlay or the traversal context is null. */ - public KMLSurfaceImageImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) - { + public KMLSurfaceImageImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) { this.parent = overlay; - if (tc == null) - { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (overlay == null) - { + if (overlay == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -65,32 +66,26 @@ public KMLSurfaceImageImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) // Positions are specified either as a kml:LatLonBox or a gx:LatLonQuad KMLLatLonBox box = overlay.getLatLonBox(); - if (box != null) - { + if (box != null) { Sector sector = KMLUtil.createSectorFromLatLonBox(box); this.initializeGeometry(sector); // Check to see if a rotation is provided. The rotation will be applied when the image is rendered, because // how the rotation is performed depends on the globe. Double rotation = box.getRotation(); - if (rotation != null) - { + if (rotation != null) { this.mustApplyRotation = true; } - } - else - { + } else { GXLatLongQuad latLonQuad = overlay.getLatLonQuad(); - if (latLonQuad != null && latLonQuad.getCoordinates() != null) - { + if (latLonQuad != null && latLonQuad.getCoordinates() != null) { this.initializeGeometry(latLonQuad.getCoordinates().list); } } // Apply opacity to the surface image String colorStr = overlay.getColor(); - if (!WWUtil.isEmpty(colorStr)) - { + if (!WWUtil.isEmpty(colorStr)) { Color color = WWUtil.decodeColorABGR(colorStr); int alpha = color.getAlpha(); @@ -100,8 +95,7 @@ public KMLSurfaceImageImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) this.setPickEnabled(false); } - public void preRender(KMLTraversalContext tc, DrawContext dc) - { + public void preRender(KMLTraversalContext tc, DrawContext dc) { if (this.mustResolveHref()) // resolve the href to either a local file or a remote URL { String path = this.resolveHref(); @@ -118,9 +112,8 @@ public void preRender(KMLTraversalContext tc, DrawContext dc) // Set the Icon's expiration time the first time that the image is rendered after the texture has been retrieved. // The expiration time comes from the HTTP headers, so we can't do this until the resource is available. boolean mustSetExpiration = !this.textureResolved && this.sourceTexture != null - && this.sourceTexture.isTextureCurrent(dc); - if (mustSetExpiration) - { + && this.sourceTexture.isTextureCurrent(dc); + if (mustSetExpiration) { String path = this.resolveHref(); // Query the KMLRoot for the expiration time. @@ -132,8 +125,7 @@ public void preRender(KMLTraversalContext tc, DrawContext dc) } // Apply rotation the first time the overlay is rendered - if (this.mustApplyRotation) - { + if (this.mustApplyRotation) { this.applyRotation(dc); this.mustApplyRotation = false; } @@ -147,12 +139,12 @@ public void preRender(KMLTraversalContext tc, DrawContext dc) * * @return True if the image source must be resolved. */ - protected boolean mustResolveHref() - { + protected boolean mustResolveHref() { KMLIcon icon = this.parent.getIcon(); //noinspection SimplifiableIfStatement - if (icon == null || icon.getHref() == null) + if (icon == null || icon.getHref() == null) { return false; + } // Resolve the reference if the image hasn't been retrieved, or if the link has expired. return this.getImageSource() == null || icon.getUpdateTime() > this.iconRetrievalTime; @@ -163,26 +155,23 @@ protected boolean mustResolveHref() * * @return The resolved path to the image source. */ - protected String resolveHref() - { + protected String resolveHref() { // The icon reference may be to a support file within a KMZ file, so check for that. If it's not, then just // let the normal SurfaceImage code resolve the reference. String href = this.parent.getIcon().getHref(); String localAddress = null; - try - { + try { localAddress = this.parent.getRoot().getSupportFilePath(href); - } - catch (IOException ignored) - { + } catch (IOException ignored) { } return localAddress != null ? localAddress : href; } - /** {@inheritDoc} */ - public void render(KMLTraversalContext tc, DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(KMLTraversalContext tc, DrawContext dc) { // We've already resolved the SurfaceImage's attributes during the preRender pass. During the render pass we // simply draw the SurfaceImage. super.render(dc); @@ -193,16 +182,13 @@ public void render(KMLTraversalContext tc, DrawContext dc) * * @param dc Current draw context. */ - protected void applyRotation(DrawContext dc) - { + protected void applyRotation(DrawContext dc) { KMLLatLonBox box = this.parent.getLatLonBox(); - if (box != null) - { + if (box != null) { Double rotation = box.getRotation(); - if (rotation != null) - { + if (rotation != null) { List corners = KMLUtil.rotateSector(dc.getGlobe(), this.getSector(), - Angle.fromDegrees(rotation)); + Angle.fromDegrees(rotation)); this.setCorners(corners); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLSurfacePolygonImpl.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLSurfacePolygonImpl.java index a7c20a3df4..82448373a8 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLSurfacePolygonImpl.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLSurfacePolygonImpl.java @@ -19,8 +19,8 @@ * @author dcollins * @version $Id: KMLSurfacePolygonImpl.java 1551 2013-08-17 18:00:09Z pabercrombie $ */ -public class KMLSurfacePolygonImpl extends SurfacePolygon implements KMLRenderable -{ +public class KMLSurfacePolygonImpl extends SurfacePolygon implements KMLRenderable { + protected final KMLAbstractFeature parent; protected boolean highlightAttributesResolved = false; protected boolean normalAttributesResolved = false; @@ -34,24 +34,21 @@ public class KMLSurfacePolygonImpl extends SurfacePolygon implements KMLRenderab /** * Create an instance. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param placemark the Placemark element containing the LineString. - * @param geom the {@link gov.nasa.worldwind.ogc.kml.KMLPolygon} geometry. + * @param geom the {@link gov.nasa.worldwind.ogc.kml.KMLPolygon} geometry. * - * @throws NullPointerException if the geometry is null. + * @throws NullPointerException if the geometry is null. * @throws IllegalArgumentException if the parent placemark or the traversal context is null. */ - public KMLSurfacePolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) - { - if (tc == null) - { + public KMLSurfacePolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KMLAbstractGeometry geom) { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (placemark == null) - { + if (placemark == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -67,34 +64,35 @@ public KMLSurfacePolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KML // Note: SurfacePolygon implies altitude mode "clampToGround", therefore KMLSurfacePolygonImpl ignores the // KMLPolygon's altitude mode property. - KMLLinearRing outerBoundary = polygon.getOuterBoundary(); - if (outerBoundary != null) - { + if (outerBoundary != null) { Position.PositionList coords = outerBoundary.getCoordinates(); - if (coords != null && coords.list != null) + if (coords != null && coords.list != null) { this.setOuterBoundary(outerBoundary.getCoordinates().list); + } } Iterable innerBoundaries = polygon.getInnerBoundaries(); - if (innerBoundaries != null) - { - for (KMLLinearRing ring : innerBoundaries) - { + if (innerBoundaries != null) { + for (KMLLinearRing ring : innerBoundaries) { Position.PositionList coords = ring.getCoordinates(); - if (coords != null && coords.list != null) + if (coords != null && coords.list != null) { this.addInnerBoundary(ring.getCoordinates().list); + } } } - if (placemark.getName() != null) + if (placemark.getName() != null) { this.setValue(AVKey.DISPLAY_NAME, placemark.getName()); + } - if (placemark.getDescription() != null) + if (placemark.getDescription() != null) { this.setValue(AVKey.DESCRIPTION, placemark.getDescription()); + } - if (placemark.getSnippetText() != null) + if (placemark.getSnippetText() != null) { this.setValue(AVKey.SHORT_DESCRIPTION, placemark.getSnippetText()); + } this.setValue(AVKey.CONTEXT, this.parent); } @@ -102,23 +100,20 @@ public KMLSurfacePolygonImpl(KMLTraversalContext tc, KMLPlacemark placemark, KML /** * Create a surface polygon from a KML GroundOverlay. * - * @param tc the current {@link KMLTraversalContext}. + * @param tc the current {@link KMLTraversalContext}. * @param overlay the {@link gov.nasa.worldwind.ogc.kml.KMLGroundOverlay} to render as a polygon. * - * @throws NullPointerException if the geometry is null. + * @throws NullPointerException if the geometry is null. * @throws IllegalArgumentException if the parent placemark or the traversal context is null. */ - public KMLSurfacePolygonImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) - { - if (tc == null) - { + public KMLSurfacePolygonImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) { + if (tc == null) { String msg = Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (overlay == null) - { + if (overlay == null) { String msg = Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -133,23 +128,24 @@ public KMLSurfacePolygonImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) // Check to see if a rotation is provided. The rotation will be applied when the image is rendered, because // how the rotation is performed depends on the globe. KMLLatLonBox box = overlay.getLatLonBox(); - if (box != null && box.getRotation() != null) - { + if (box != null && box.getRotation() != null) { this.mustApplyRotation = true; } - if (overlay.getName() != null) + if (overlay.getName() != null) { this.setValue(AVKey.DISPLAY_NAME, overlay.getName()); + } - if (overlay.getDescription() != null) + if (overlay.getDescription() != null) { this.setValue(AVKey.BALLOON_TEXT, overlay.getDescription()); + } - if (overlay.getSnippetText() != null) + if (overlay.getSnippetText() != null) { this.setValue(AVKey.SHORT_DESCRIPTION, overlay.getSnippetText()); + } String colorStr = overlay.getColor(); - if (!WWUtil.isEmpty(colorStr)) - { + if (!WWUtil.isEmpty(colorStr)) { Color color = WWUtil.decodeColorABGR(colorStr); ShapeAttributes attributes = new BasicShapeAttributes(); @@ -159,41 +155,33 @@ public KMLSurfacePolygonImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) } } - public void preRender(KMLTraversalContext tc, DrawContext dc) - { + public void preRender(KMLTraversalContext tc, DrawContext dc) { // If the attributes are not inline or internal then they might not be resolved until the external KML // document is resolved. Therefore check to see if resolution has occurred. - if (this.isHighlighted()) - { - if (!this.highlightAttributesResolved) - { + if (this.isHighlighted()) { + if (!this.highlightAttributesResolved) { ShapeAttributes a = this.getHighlightAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.HIGHLIGHT); - if (a != null) - { + if (a != null) { this.setHighlightAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.highlightAttributesResolved = true; + } } } } - } - else - { - if (!this.normalAttributesResolved) - { + } else { + if (!this.normalAttributesResolved) { ShapeAttributes a = this.getAttributes(); - if (a == null || a.isUnresolved()) - { + if (a == null || a.isUnresolved()) { a = this.makeAttributesCurrent(KMLConstants.NORMAL); - if (a != null) - { + if (a != null) { this.setAttributes(a); - if (!a.isUnresolved()) + if (!a.isUnresolved()) { this.normalAttributesResolved = true; + } } } } @@ -201,8 +189,7 @@ public void preRender(KMLTraversalContext tc, DrawContext dc) // Apply rotation the first time the polygon is rendered. This feature only applies to ground overlays with // position specified using a rotated LatLon box. - if (this.mustApplyRotation) - { + if (this.mustApplyRotation) { this.applyRotation(dc); this.mustApplyRotation = false; } @@ -210,17 +197,17 @@ public void preRender(KMLTraversalContext tc, DrawContext dc) this.preRender(dc); } - public void render(KMLTraversalContext tc, DrawContext dc) - { + public void render(KMLTraversalContext tc, DrawContext dc) { // We've already resolved the SurfacePolygon's attributes during the preRender pass. During the render pass we // simply draw the SurfacePolygon. this.render(dc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected PickedObject createPickedObject(DrawContext dc, Color pickColor) - { + protected PickedObject createPickedObject(DrawContext dc, Color pickColor) { PickedObject po = super.createPickedObject(dc, pickColor); // Add the KMLPlacemark to the picked object as the context of the picked object. @@ -235,29 +222,26 @@ protected PickedObject createPickedObject(DrawContext dc, Color pickColor) * * @return the new attributes. */ - protected ShapeAttributes makeAttributesCurrent(String attrType) - { + protected ShapeAttributes makeAttributesCurrent(String attrType) { ShapeAttributes attrs = this.getInitialAttributes( - this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); + this.isHighlighted() ? KMLConstants.HIGHLIGHT : KMLConstants.NORMAL); // Get the KML sub-style for Line attributes. Map them to Shape attributes. - KMLAbstractSubStyle lineSubStyle = this.parent.getSubStyle(new KMLLineStyle(null), attrType); - if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) - { + if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) { KMLUtil.assembleLineAttributes(attrs, (KMLLineStyle) lineSubStyle); - if (lineSubStyle.hasField(AVKey.UNRESOLVED)) + if (lineSubStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } // Get the KML sub-style for interior attributes. Map them to Shape attributes. - KMLAbstractSubStyle fillSubStyle = this.parent.getSubStyle(new KMLPolyStyle(null), attrType); - if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) - { + if (!this.isHighlighted() || KMLUtil.isHighlightStyleState(lineSubStyle)) { KMLUtil.assembleInteriorAttributes(attrs, (KMLPolyStyle) fillSubStyle); - if (fillSubStyle.hasField(AVKey.UNRESOLVED)) + if (fillSubStyle.hasField(AVKey.UNRESOLVED)) { attrs.setUnresolved(true); + } } attrs.setDrawInterior(((KMLPolyStyle) fillSubStyle).isFill()); @@ -266,17 +250,13 @@ protected ShapeAttributes makeAttributesCurrent(String attrType) return attrs; } - protected ShapeAttributes getInitialAttributes(String attrType) - { + protected ShapeAttributes getInitialAttributes(String attrType) { ShapeAttributes attrs = new BasicShapeAttributes(); - if (KMLConstants.HIGHLIGHT.equals(attrType)) - { + if (KMLConstants.HIGHLIGHT.equals(attrType)) { attrs.setOutlineMaterial(Material.RED); attrs.setInteriorMaterial(Material.PINK); - } - else - { + } else { attrs.setOutlineMaterial(Material.WHITE); attrs.setInteriorMaterial(Material.LIGHT_GRAY); } @@ -285,19 +265,19 @@ protected ShapeAttributes getInitialAttributes(String attrType) } @Override - public void onMessage(Message message) - { + public void onMessage(Message message) { super.onMessage(message); - if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) - { + if (KMLAbstractObject.MSG_STYLE_CHANGED.equals(message.getName())) { this.normalAttributesResolved = false; this.highlightAttributesResolved = false; - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.getAttributes().setUnresolved(true); - if (this.getHighlightAttributes() != null) + } + if (this.getHighlightAttributes() != null) { this.getHighlightAttributes().setUnresolved(true); + } } } @@ -307,21 +287,19 @@ public void onMessage(Message message) * * @param dc Current draw context. */ - protected void applyRotation(DrawContext dc) - { + protected void applyRotation(DrawContext dc) { // Rotation applies only to ground overlay position with a LatLon box. - if (!(this.parent instanceof KMLGroundOverlay)) + if (!(this.parent instanceof KMLGroundOverlay)) { return; + } KMLLatLonBox box = ((KMLGroundOverlay) this.parent).getLatLonBox(); - if (box != null) - { + if (box != null) { Double rotation = box.getRotation(); - if (rotation != null) - { + if (rotation != null) { Sector sector = KMLUtil.createSectorFromLatLonBox(box); java.util.List corners = KMLUtil.rotateSector(dc.getGlobe(), sector, - Angle.fromDegrees(rotation)); + Angle.fromDegrees(rotation)); this.setOuterBoundary(corners); } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLTraversalContext.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLTraversalContext.java index 154b905e3e..600dfc5e2d 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLTraversalContext.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLTraversalContext.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.ogc.kml.KMLRegion; @@ -18,8 +17,8 @@ * @author tag * @version $Id: KMLTraversalContext.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLTraversalContext -{ +public class KMLTraversalContext { + /** * The Deque as this KML traversal context's Region stack. The region stack is used to implement * Regions inheritance of from a KML containers to their descendant KML features. @@ -32,17 +31,17 @@ public class KMLTraversalContext */ protected double detailHint; - /** Constructs a new KML traversal context in a default state, but otherwise does nothing. */ - public KMLTraversalContext() - { + /** + * Constructs a new KML traversal context in a default state, but otherwise does nothing. + */ + public KMLTraversalContext() { } /** * Initializes this KML traversal context to its default state. This should be called at the beginning of each frame * to prepare this traversal context for the coming render pass. */ - public void initialize() - { + public void initialize() { this.regionStack.clear(); this.detailHint = 0.0; } @@ -57,10 +56,8 @@ public void initialize() * * @throws IllegalArgumentException if region is null. */ - public void pushRegion(KMLRegion region) - { - if (region == null) - { + public void pushRegion(KMLRegion region) { + if (region == null) { String message = Logging.getMessage("nullValue.RegionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,8 +73,7 @@ public void pushRegion(KMLRegion region) * * @return the Region on the top of this context's stack, or null if the stack is empty. */ - public KMLRegion peekRegion() - { + public KMLRegion peekRegion() { return this.regionStack.peek(); } @@ -90,8 +86,7 @@ public KMLRegion peekRegion() * * @throws NoSuchElementException if the Region stack is empty. */ - public KMLRegion popRegion() - { + public KMLRegion popRegion() { return this.regionStack.pop(); } @@ -103,8 +98,7 @@ public KMLRegion popRegion() * * @see #setDetailHint(double) */ - public double getDetailHint() - { + public double getDetailHint() { return this.detailHint; } @@ -116,11 +110,10 @@ public double getDetailHint() * 0. Values typically range between -0.5 and 0.5. * * @param detailHint the degree to modify the default relationship of KML scene resolution to screen resolution as - * viewing distance changes. Values greater than 0 increase the resolution. Values less than 0 - * decrease the resolution. The default value is 0. + * viewing distance changes. Values greater than 0 increase the resolution. Values less than 0 decrease the + * resolution. The default value is 0. */ - public void setDetailHint(double detailHint) - { + public void setDetailHint(double detailHint) { this.detailHint = detailHint; } } diff --git a/src/gov/nasa/worldwind/ogc/kml/impl/KMLUtil.java b/src/gov/nasa/worldwind/ogc/kml/impl/KMLUtil.java index f50a0a086b..bf9dfed280 100644 --- a/src/gov/nasa/worldwind/ogc/kml/impl/KMLUtil.java +++ b/src/gov/nasa/worldwind/ogc/kml/impl/KMLUtil.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.impl; import gov.nasa.worldwind.WorldWind; @@ -21,42 +20,43 @@ * @author tag * @version $Id: KMLUtil.java 1838 2014-02-05 20:48:12Z dcollins $ */ -public class KMLUtil -{ +public class KMLUtil { + public static final String KML_PIXELS = "pixels"; public static final String KML_FRACTION = "fraction"; public static final String KML_INSET_PIXELS = "insetPixels"; - public static ShapeAttributes assembleLineAttributes(ShapeAttributes attrs, KMLLineStyle style) - { + public static ShapeAttributes assembleLineAttributes(ShapeAttributes attrs, KMLLineStyle style) { // Assign the attributes defined in the KML Feature element. - if (style.getWidth() != null) + if (style.getWidth() != null) { attrs.setOutlineWidth(style.getWidth()); + } - if (style.getColor() != null) + if (style.getColor() != null) { attrs.setOutlineMaterial(new Material(WWUtil.decodeColorABGR(style.getColor()))); + } - if (style.getColorMode() != null && "random".equals(style.getColorMode())) + if (style.getColorMode() != null && "random".equals(style.getColorMode())) { attrs.setOutlineMaterial(new Material(WWUtil.makeRandomColor(attrs.getOutlineMaterial().getDiffuse()))); + } return attrs; } - public static ShapeAttributes assembleInteriorAttributes(ShapeAttributes attrs, KMLPolyStyle style) - { + public static ShapeAttributes assembleInteriorAttributes(ShapeAttributes attrs, KMLPolyStyle style) { // Assign the attributes defined in the KML Feature element. - if (style.getColor() != null) - { + if (style.getColor() != null) { Color color = WWUtil.decodeColorABGR(style.getColor()); attrs.setInteriorMaterial(new Material(color)); attrs.setInteriorOpacity((double) color.getAlpha() / 255); } - if (style.getColorMode() != null && "random".equals(style.getColorMode())) + if (style.getColorMode() != null && "random".equals(style.getColorMode())) { attrs.setInteriorMaterial(new Material(WWUtil.makeRandomColor(attrs.getOutlineMaterial().getDiffuse()))); + } return attrs; } @@ -68,25 +68,25 @@ public static ShapeAttributes assembleInteriorAttributes(ShapeAttributes attrs, * * @return true if the sub-style has the "highlight" field, otherwise false. */ - public static boolean isHighlightStyleState(KMLAbstractSubStyle subStyle) - { - if (subStyle == null) + public static boolean isHighlightStyleState(KMLAbstractSubStyle subStyle) { + if (subStyle == null) { return false; + } String styleState = (String) subStyle.getField(KMLConstants.STYLE_STATE); return styleState != null && styleState.equals(KMLConstants.HIGHLIGHT); } - public static int convertAltitudeMode(String altMode, int defaultAltMode) - { - if ("clampToGround".equals(altMode)) + public static int convertAltitudeMode(String altMode, int defaultAltMode) { + if ("clampToGround".equals(altMode)) { return WorldWind.CLAMP_TO_GROUND; - else if ("relativeToGround".equals(altMode)) + } else if ("relativeToGround".equals(altMode)) { return WorldWind.RELATIVE_TO_GROUND; - else if ("absolute".equals(altMode)) + } else if ("absolute".equals(altMode)) { return WorldWind.ABSOLUTE; - else + } else { return defaultAltMode; + } } /** @@ -97,16 +97,16 @@ else if ("absolute".equals(altMode)) * * @return WW units, or null if the argument is not a valid KML unit. */ - public static String kmlUnitsToWWUnits(String units) - { - if (KML_PIXELS.equals(units)) + public static String kmlUnitsToWWUnits(String units) { + if (KML_PIXELS.equals(units)) { return AVKey.PIXELS; - else if (KML_FRACTION.equals(units)) + } else if (KML_FRACTION.equals(units)) { return AVKey.FRACTION; - else if (KML_INSET_PIXELS.equals(units)) + } else if (KML_INSET_PIXELS.equals(units)) { return AVKey.INSET_PIXELS; - else + } else { return null; + } } /** @@ -117,16 +117,16 @@ else if (KML_INSET_PIXELS.equals(units)) * * @return KML units, or null if the argument is not a valid WW unit. */ - public static String wwUnitsToKMLUnits(String units) - { - if (AVKey.PIXELS.equals(units)) + public static String wwUnitsToKMLUnits(String units) { + if (AVKey.PIXELS.equals(units)) { return KML_PIXELS; - else if (AVKey.FRACTION.equals(units)) + } else if (AVKey.FRACTION.equals(units)) { return KML_FRACTION; - else if (AVKey.INSET_PIXELS.equals(units)) + } else if (AVKey.INSET_PIXELS.equals(units)) { return KML_INSET_PIXELS; - else + } else { return null; + } } /** @@ -140,17 +140,16 @@ else if (AVKey.INSET_PIXELS.equals(units)) * * @throws IllegalArgumentException if the box is null. */ - public static Sector createSectorFromLatLonBox(KMLAbstractLatLonBoxType box) - { - if (box == null) - { + public static Sector createSectorFromLatLonBox(KMLAbstractLatLonBoxType box) { + if (box == null) { String message = Logging.getMessage("nullValue.BoxIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (box.getNorth() == null || box.getSouth() == null || box.getEast() == null || box.getWest() == null) + if (box.getNorth() == null || box.getSouth() == null || box.getEast() == null || box.getWest() == null) { return null; + } double north = box.getNorth(); double south = box.getSouth(); @@ -169,51 +168,41 @@ public static Sector createSectorFromLatLonBox(KMLAbstractLatLonBoxType box) * Get all of the positions that make up a {@link KMLAbstractGeometry}. If the geometry contains other geometries, * this method collects all the points from all of the geometries. * - * @param globe Globe to use to determine altitude above terrain. - * @param geometry Geometry to collect positions from. + * @param globe Globe to use to determine altitude above terrain. + * @param geometry Geometry to collect positions from. * @param positions Placemark positions will be added to this list. */ - public static void getPositions(Globe globe, KMLAbstractGeometry geometry, java.util.List positions) - { - if (geometry instanceof KMLPoint) - { + public static void getPositions(Globe globe, KMLAbstractGeometry geometry, java.util.List positions) { + if (geometry instanceof KMLPoint) { KMLPoint kmlPoint = (KMLPoint) geometry; Position pos = kmlPoint.getCoordinates(); - if (pos != null) + if (pos != null) { positions.add(computeAltitude(globe, pos, kmlPoint.getAltitudeMode())); - } - else if (geometry instanceof KMLModel) - { + } + } else if (geometry instanceof KMLModel) { KMLModel model = (KMLModel) geometry; KMLLocation location = model.getLocation(); - if (location != null) - { + if (location != null) { Position pos = location.getPosition(); - if (pos != null) + if (pos != null) { positions.add(computeAltitude(globe, pos, model.getAltitudeMode())); + } } - } - else if (geometry instanceof KMLLineString) // Also handles KMLLinearRing, since KMLLineString is a subclass of KMLLinearRing + } else if (geometry instanceof KMLLineString) // Also handles KMLLinearRing, since KMLLineString is a subclass of KMLLinearRing { KMLLineString lineString = (KMLLineString) geometry; Position.PositionList positionList = lineString.getCoordinates(); - if (positionList != null) - { + if (positionList != null) { positions.addAll(computeAltitude(globe, positionList.list, lineString.getAltitudeMode())); } - } - else if (geometry instanceof KMLPolygon) - { + } else if (geometry instanceof KMLPolygon) { KMLLinearRing ring = ((KMLPolygon) geometry).getOuterBoundary(); // Recurse and let the LineString/LinearRing code handle the boundary positions getPositions(globe, ring, positions); - } - else if (geometry instanceof KMLMultiGeometry) - { + } else if (geometry instanceof KMLMultiGeometry) { java.util.List geoms = ((KMLMultiGeometry) geometry).getGeometries(); - for (KMLAbstractGeometry g : geoms) - { + for (KMLAbstractGeometry g : geoms) { // Recurse, adding positions for the sub-geometry getPositions(globe, g, positions); } @@ -223,18 +212,16 @@ else if (geometry instanceof KMLMultiGeometry) /** * Compute the altitude of each position in a list, based on altitude mode. * - * @param globe Globe to use to determine altitude above terrain. - * @param positions Positions to compute altitude for. + * @param globe Globe to use to determine altitude above terrain. + * @param positions Positions to compute altitude for. * @param altitudeMode A KML altitude mode string. * * @return A new list of positions with altitudes set based on {@code altitudeMode}. */ public static java.util.List computeAltitude(Globe globe, java.util.List positions, - String altitudeMode) - { + String altitudeMode) { java.util.List outPositions = new ArrayList(positions.size()); - for (Position p : positions) - { + for (Position p : positions) { outPositions.add(computeAltitude(globe, p, altitudeMode)); } @@ -244,25 +231,25 @@ public static java.util.List computeAltitude(Globe globe, java.util.Li /** * Create a {@link Position}, taking into account an altitude mode. * - * @param globe Globe to use to determine altitude above terrain. - * @param position Position to evaluate. + * @param globe Globe to use to determine altitude above terrain. + * @param position Position to evaluate. * @param altitudeMode A KML altitude mode string. * * @return New Position. */ - public static Position computeAltitude(Globe globe, Position position, String altitudeMode) - { + public static Position computeAltitude(Globe globe, Position position, String altitudeMode) { double height; Angle latitude = position.getLatitude(); Angle longitude = position.getLongitude(); int altMode = convertAltitudeMode(altitudeMode, WorldWind.CLAMP_TO_GROUND); // KML default - if (altMode == WorldWind.CLAMP_TO_GROUND) + if (altMode == WorldWind.CLAMP_TO_GROUND) { height = globe.getElevation(latitude, longitude); - else if (altMode == WorldWind.RELATIVE_TO_GROUND) + } else if (altMode == WorldWind.RELATIVE_TO_GROUND) { height = globe.getElevation(latitude, longitude) + position.getAltitude(); - else + } else { height = position.getAltitude(); + } return new Position(latitude, longitude, height); } @@ -270,28 +257,24 @@ else if (altMode == WorldWind.RELATIVE_TO_GROUND) /** * Rotate the corners of a sector around a normal vector through the sector centroid. * - * @param globe Globe to use to compute rotated positions. - * @param sector Sector to rotate. + * @param globe Globe to use to compute rotated positions. + * @param sector Sector to rotate. * @param rotation Rotation angle. Positive angles produce counterclockwise rotation. * * @return List of rotated corners. */ - public static java.util.List rotateSector(Globe globe, Sector sector, Angle rotation) - { - if (globe == null) - { + public static java.util.List rotateSector(Globe globe, Sector sector, Angle rotation) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rotation == null) - { + if (rotation == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -309,8 +292,7 @@ public static java.util.List rotateSector(Globe globe, Sector sector, An Vec4 centerPoint = sector.computeCenterPoint(globe, 1); // Rotate each point around the surface normal, and convert back to geographic - for (Vec4 point : verts) - { + for (Vec4 point : verts) { point = point.subtract3(centerPoint).transformBy3(rotationMatrix).add3(centerPoint); LatLon ll = globe.computePositionFromPoint(point); diff --git a/src/gov/nasa/worldwind/ogc/kml/io/KMLDoc.java b/src/gov/nasa/worldwind/ogc/kml/io/KMLDoc.java index 060c5fbcbf..094017340c 100644 --- a/src/gov/nasa/worldwind/ogc/kml/io/KMLDoc.java +++ b/src/gov/nasa/worldwind/ogc/kml/io/KMLDoc.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.io; import java.io.*; @@ -15,8 +14,8 @@ * @author tag * @version $Id: KMLDoc.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface KMLDoc -{ +public interface KMLDoc { + /** * Returns an {@link InputStream} to the associated KML document within either a KML file or stream or a KMZ file or * stream. @@ -40,7 +39,7 @@ public interface KMLDoc * @return an input stream positioned to the start of the requested file, or null if the file cannot be found. * * @throws IllegalArgumentException if the path is null. - * @throws IOException if an error occurs while attempting to create or open the input stream. + * @throws IOException if an error occurs while attempting to create or open the input stream. */ InputStream getSupportFileStream(String path) throws IOException; diff --git a/src/gov/nasa/worldwind/ogc/kml/io/KMLFile.java b/src/gov/nasa/worldwind/ogc/kml/io/KMLFile.java index 0f9e74e952..190739d012 100644 --- a/src/gov/nasa/worldwind/ogc/kml/io/KMLFile.java +++ b/src/gov/nasa/worldwind/ogc/kml/io/KMLFile.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.io; import gov.nasa.worldwind.util.Logging; @@ -19,9 +18,11 @@ * @author tag * @version $Id: KMLFile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLFile implements KMLDoc -{ - /** The {@link File} reference specified to the constructor. */ +public class KMLFile implements KMLDoc { + + /** + * The {@link File} reference specified to the constructor. + */ protected File kmlFile; /** @@ -31,10 +32,8 @@ public class KMLFile implements KMLDoc * * @throws IllegalArgumentException if the specified file is null. */ - public KMLFile(File file) - { - if (file == null) - { + public KMLFile(File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -48,8 +47,7 @@ public KMLFile(File file) * * @return the file specified to the constructor. */ - public File getZipFile() - { + public File getZipFile() { return this.kmlFile; } @@ -60,8 +58,7 @@ public File getZipFile() * * @throws IOException if an error occurs attempting to create the input stream. */ - public InputStream getKMLStream() throws IOException - { + public InputStream getKMLStream() throws IOException { return new FileInputStream(this.kmlFile); } @@ -74,36 +71,34 @@ public InputStream getKMLStream() throws IOException * * @throws IOException if an error occurs while attempting to query or open the file. */ - public InputStream getSupportFileStream(String path) throws IOException - { - if (path == null) - { + public InputStream getSupportFileStream(String path) throws IOException { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File pathFile = new File(path); - if (pathFile.isAbsolute()) + if (pathFile.isAbsolute()) { return null; + } pathFile = new File(this.kmlFile.getParentFile(), path); return pathFile.exists() ? new FileInputStream(pathFile) : null; } - public String getSupportFilePath(String path) - { - if (path == null) - { + public String getSupportFilePath(String path) { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File pathFile = new File(path); - if (pathFile.isAbsolute()) + if (pathFile.isAbsolute()) { return null; + } pathFile = new File(this.kmlFile.getParentFile(), path); diff --git a/src/gov/nasa/worldwind/ogc/kml/io/KMLInputStream.java b/src/gov/nasa/worldwind/ogc/kml/io/KMLInputStream.java index 54a609b1fd..5febd2da53 100644 --- a/src/gov/nasa/worldwind/ogc/kml/io/KMLInputStream.java +++ b/src/gov/nasa/worldwind/ogc/kml/io/KMLInputStream.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.io; import gov.nasa.worldwind.util.*; @@ -17,28 +16,30 @@ * @author tag * @version $Id: KMLInputStream.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLInputStream implements KMLDoc -{ - /** The {@link InputStream} specified to the constructor. */ +public class KMLInputStream implements KMLDoc { + + /** + * The {@link InputStream} specified to the constructor. + */ protected InputStream inputStream; - /** The URI of this KML document. May be {@code null}. */ + /** + * The URI of this KML document. May be {@code null}. + */ protected URI uri; /** * Construct a KMLInputStream instance. * * @param sourceStream the KML stream. - * @param uri the URI of this KML document. This URI is used to resolve relative references. May be {@code + * @param uri the URI of this KML document. This URI is used to resolve relative references. May be {@code * null}. * * @throws IllegalArgumentException if the specified input stream is null. - * @throws IOException if an error occurs while attempting to read from the stream. + * @throws IOException if an error occurs while attempting to read from the stream. */ - public KMLInputStream(InputStream sourceStream, URI uri) throws IOException - { - if (sourceStream == null) - { + public KMLInputStream(InputStream sourceStream, URI uri) throws IOException { + if (sourceStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -53,8 +54,7 @@ public KMLInputStream(InputStream sourceStream, URI uri) throws IOException * * @return the input stream reference passed to the constructor. */ - public InputStream getKMLStream() throws IOException - { + public InputStream getKMLStream() throws IOException { return this.inputStream; } @@ -67,21 +67,19 @@ public InputStream getKMLStream() throws IOException * * @throws IOException if an error occurs while attempting to query or open the file. */ - public InputStream getSupportFileStream(String path) throws IOException - { - if (path == null) - { + public InputStream getSupportFileStream(String path) throws IOException { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String ref = this.getSupportFilePath(path); - if (ref != null) - { + if (ref != null) { URL url = WWIO.makeURL(path); - if (url != null) + if (url != null) { return url.openStream(); + } } return null; } @@ -93,20 +91,18 @@ public InputStream getSupportFileStream(String path) throws IOException * * @return a URL to the requested file, or {@code null} if the document does not have a base URI. */ - public String getSupportFilePath(String path) - { - if (path == null) - { + public String getSupportFilePath(String path) { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.uri != null) - { + if (this.uri != null) { URI remoteFile = uri.resolve(path); - if (remoteFile != null) + if (remoteFile != null) { return remoteFile.toString(); + } } return null; } diff --git a/src/gov/nasa/worldwind/ogc/kml/io/KMZFile.java b/src/gov/nasa/worldwind/ogc/kml/io/KMZFile.java index 66879567f5..7cfd41aa27 100644 --- a/src/gov/nasa/worldwind/ogc/kml/io/KMZFile.java +++ b/src/gov/nasa/worldwind/ogc/kml/io/KMZFile.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.io; import gov.nasa.worldwind.util.*; @@ -21,15 +20,21 @@ * @author tag * @version $Id: KMZFile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMZFile implements KMLDoc -{ - /** The {@link ZipFile} reference specified to the constructor. */ +public class KMZFile implements KMLDoc { + + /** + * The {@link ZipFile} reference specified to the constructor. + */ protected ZipFile zipFile; - /** A mapping of the files in the KMZ file to their location in the temporary directory. */ + /** + * A mapping of the files in the KMZ file to their location in the temporary directory. + */ protected Map files = new HashMap(); - /** The directory to hold files copied from the KMZ file. The directory and the files copied there are temporary. */ + /** + * The directory to hold files copied from the KMZ file. The directory and the files copied there are temporary. + */ protected File tempDir; /** @@ -37,14 +42,12 @@ public class KMZFile implements KMLDoc * * @param file path to the KMZ file. * - * @throws IOException if an error occurs while attempting to query or open the file. + * @throws IOException if an error occurs while attempting to query or open the file. * @throws IllegalArgumentException if the specified file is null. - * @throws ZipException if a Zip error occurs. + * @throws ZipException if a Zip error occurs. */ - public KMZFile(File file) throws IOException - { - if (file == null) - { + public KMZFile(File file) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -58,8 +61,7 @@ public KMZFile(File file) throws IOException * * @return the file specified to the constructor, as a ZipFile. */ - public ZipFile getZipFile() - { + public ZipFile getZipFile() { return this.zipFile; } @@ -67,16 +69,13 @@ public ZipFile getZipFile() * Returns an {@link InputStream} to the first KML file in the KMZ file. * * @return an input stream positioned to the first KML file in the KMZ file, or null if the KMZ file does not - * contain a KML file. + * contain a KML file. */ - public synchronized InputStream getKMLStream() throws IOException - { + public synchronized InputStream getKMLStream() throws IOException { Enumeration zipEntries = this.zipFile.entries(); - while (zipEntries.hasMoreElements()) - { + while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); - if (entry.getName().toLowerCase().endsWith(".kml")) - { + if (entry.getName().toLowerCase().endsWith(".kml")) { return this.zipFile.getInputStream(entry); } } @@ -94,30 +93,26 @@ public synchronized InputStream getKMLStream() throws IOException * @param path the path of the requested file. * * @return an input stream positioned to the start of the requested file, or null if the file does not exist or the - * specified path is absolute. + * specified path is absolute. * * @throws IllegalArgumentException if the path is null. - * @throws IOException if an error occurs while attempting to create or open the input stream. + * @throws IOException if an error occurs while attempting to create or open the input stream. */ - public synchronized InputStream getSupportFileStream(String path) throws IOException - { + public synchronized InputStream getSupportFileStream(String path) throws IOException { // This method is called by the native WebView implementation to resolve resources in KMZ balloons. It may // not perform any synchronization with the EDT (such as calling invokeAndWait), or it will introduce a // potential deadlock when called by the WebView's native UI thread. - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Enumeration zipEntries = this.zipFile.entries(); - while (zipEntries.hasMoreElements()) - { + while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); - if (entry.getName().equals(path)) - { + if (entry.getName().equals(path)) { return this.zipFile.getInputStream(entry); } } @@ -135,34 +130,31 @@ public synchronized InputStream getSupportFileStream(String path) throws IOExcep * @param path the path of the requested file. * * @return an absolute path to the requested file, or null if the file does not exist or the specified path is - * absolute. + * absolute. * * @throws IllegalArgumentException if the path is null. - * @throws IOException if an error occurs while attempting to create a temporary file. + * @throws IOException if an error occurs while attempting to create a temporary file. */ - public synchronized String getSupportFilePath(String path) throws IOException - { + public synchronized String getSupportFilePath(String path) throws IOException { // This method is called by the native WebView implementation to resolve resources in KMZ balloons. It may // not perform any synchronization with the EDT (such as calling invokeAndWait), or it will introduce a // potential deadlock when called by the WebView's native UI thread. - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } File file = this.files.get(path); - if (file != null) + if (file != null) { return file.getPath(); + } Enumeration zipEntries = this.zipFile.entries(); - while (zipEntries.hasMoreElements()) - { + while (zipEntries.hasMoreElements()) { ZipEntry entry = zipEntries.nextElement(); - if (entry.getName().equals(path)) - { + if (entry.getName().equals(path)) { return this.copyEntryToTempDir(entry); } } @@ -179,13 +171,14 @@ public synchronized String getSupportFilePath(String path) throws IOException * * @throws IOException if an error occurs during the copy. */ - protected String copyEntryToTempDir(ZipEntry entry) throws IOException - { - if (entry.isDirectory()) + protected String copyEntryToTempDir(ZipEntry entry) throws IOException { + if (entry.isDirectory()) { return null; + } - if (this.tempDir == null) + if (this.tempDir == null) { this.tempDir = WWIO.makeTempDir(); + } if (this.tempDir == null) // unlikely to occur, but define a reaction { diff --git a/src/gov/nasa/worldwind/ogc/kml/io/KMZInputStream.java b/src/gov/nasa/worldwind/ogc/kml/io/KMZInputStream.java index fd70a7afc5..4376b2643d 100644 --- a/src/gov/nasa/worldwind/ogc/kml/io/KMZInputStream.java +++ b/src/gov/nasa/worldwind/ogc/kml/io/KMZInputStream.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.kml.io; import gov.nasa.worldwind.util.*; @@ -18,9 +17,11 @@ * @author tag * @version $Id: KMZInputStream.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMZInputStream implements KMLDoc -{ - /** The zip stream created for the specified input stream. */ +public class KMZInputStream implements KMLDoc { + + /** + * The zip stream created for the specified input stream. + */ protected ZipInputStream zipStream; /** @@ -30,10 +31,14 @@ public class KMZInputStream implements KMLDoc */ protected ZipEntry currentEntry; - /** A mapping of the files in the KMZ stream to their location in the temporary directory. */ + /** + * A mapping of the files in the KMZ stream to their location in the temporary directory. + */ protected Map files; - /** The directory to hold files copied from the stream. Both the directory and the files copied there are temporary. */ + /** + * The directory to hold files copied from the stream. Both the directory and the files copied there are temporary. + */ protected File tempDir; /** @@ -43,12 +48,10 @@ public class KMZInputStream implements KMLDoc * @param sourceStream the input stream to read from. * * @throws IllegalArgumentException if the specified stream is null. - * @throws java.io.IOException if an error occurs while accessing the stream. + * @throws java.io.IOException if an error occurs while accessing the stream. */ - public KMZInputStream(InputStream sourceStream) throws IOException - { - if (sourceStream == null) - { + public KMZInputStream(InputStream sourceStream) throws IOException { + if (sourceStream == null) { String message = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -64,13 +67,13 @@ public KMZInputStream(InputStream sourceStream) throws IOException * * @throws IOException if an exception occurs while attempting to more the stream to the next entry. */ - protected void moveToNextEntry() throws IOException - { + protected void moveToNextEntry() throws IOException { ZipEntry nextEntry = this.zipStream.getNextEntry(); // Close the stream if there's nothing more to read from it. - if (nextEntry == null && this.currentEntry != null) + if (nextEntry == null && this.currentEntry != null) { this.zipStream.close(); + } this.currentEntry = nextEntry; } @@ -79,27 +82,22 @@ protected void moveToNextEntry() throws IOException * Returns an {@link java.io.InputStream} to the first KML file within the stream. * * @return an input stream positioned to the first KML file in the stream, or null if the stream does not contain a - * KML file. + * KML file. * * @throws IOException if an error occurs while reading the stream. */ - public synchronized InputStream getKMLStream() throws IOException - { + public synchronized InputStream getKMLStream() throws IOException { // Iterate through the stream's entries to find the KML file. It will normally be the first entry, but there's // no guarantee of that. If another file is encountered before the KML file, copy it to temp dir created to // capture the KMZ document's directory hierarchy. - while (this.currentEntry != null) - { - if (this.currentEntry.getName().toLowerCase().endsWith(".kml")) - { + while (this.currentEntry != null) { + if (this.currentEntry.getName().toLowerCase().endsWith(".kml")) { String kmlEntryName = this.currentEntry.getName(); this.copyCurrentEntryToTempDir(); // copies the current entry to a temp file and adds it to this.files File file = this.files.get(kmlEntryName); return file != null ? new FileInputStream(file) : null; - } - else - { + } else { this.copyCurrentEntryToTempDir(); } } @@ -118,19 +116,17 @@ public synchronized InputStream getKMLStream() throws IOException * @param path the path of the requested file. * * @return an input stream positioned to the start of the requested file, or null if the file does not exist or the - * specified path is absolute. + * specified path is absolute. * * @throws IllegalArgumentException if the path is null. - * @throws IOException if an error occurs while attempting to read the input stream. + * @throws IOException if an error occurs while attempting to read the input stream. */ - public synchronized InputStream getSupportFileStream(String path) throws IOException - { + public synchronized InputStream getSupportFileStream(String path) throws IOException { // This method is called by the native WebView implementation to resolve resources in KMZ balloons. It may // not perform any synchronization with the EDT (such as calling invokeAndWait), or it will introduce a // potential deadlock when called by the WebView's native UI thread. - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -140,13 +136,15 @@ public synchronized InputStream getSupportFileStream(String path) throws IOExcep // the temporary directory created to represent the directory hierarchy in the KMZ document. If the most // recently copied file is the requested file, return it and suspend reading and copying until it's again // necessary. This prevents bogging down performance until everything is copied. - File file = files.get(path); - if (file != null) + if (file != null) { return new FileInputStream(file); + } if (this.currentEntry == null) // no more entries in the zip stream + { return null; + } this.copyCurrentEntryToTempDir(); @@ -165,19 +163,17 @@ public synchronized InputStream getSupportFileStream(String path) throws IOExcep * @param path the path of the requested file. * * @return an absolute path for the requested file, or null if the file does not exist or the specified path is - * absolute. + * absolute. * * @throws IllegalArgumentException if the path is null. - * @throws IOException if an error occurs while attempting to create a temporary file. + * @throws IOException if an error occurs while attempting to create a temporary file. */ - public synchronized String getSupportFilePath(String path) throws IOException - { + public synchronized String getSupportFilePath(String path) throws IOException { // This method is called by the native WebView implementation to resolve resources in KMZ balloons. It may // not perform any synchronization with the EDT (such as calling invokeAndWait), or it will introduce a // potential deadlock when called by the WebView's native UI thread. - if (path == null) - { + if (path == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -187,13 +183,15 @@ public synchronized String getSupportFilePath(String path) throws IOException // the temporary directory created to represent the directory hierarchy in the KMZ document. If the most // recently copied file is the requested file, return it and suspend reading and copying until it's again // necessary. This prevents bogging down performance until everything is copied. - File file = files.get(path); - if (file != null) + if (file != null) { return file.getPath(); + } if (this.currentEntry == null) // no more entries in the zip stream + { return null; + } this.copyCurrentEntryToTempDir(); @@ -210,19 +208,20 @@ public synchronized String getSupportFilePath(String path) throws IOException * * @throws IOException if an error occurs during the copy. */ - protected void copyCurrentEntryToTempDir() throws IOException - { + protected void copyCurrentEntryToTempDir() throws IOException { if (this.currentEntry == null) // no more entries in the zip stream + { return; + } - if (this.currentEntry.isDirectory()) - { + if (this.currentEntry.isDirectory()) { this.moveToNextEntry(); return; } - if (this.tempDir == null) + if (this.tempDir == null) { this.tempDir = WWIO.makeTempDir(); + } if (this.tempDir == null) // unlikely to occur, but define a reaction { diff --git a/src/gov/nasa/worldwind/ogc/kml/io/package-info.java b/src/gov/nasa/worldwind/ogc/kml/io/package-info.java index 33da549ebb..20f4c28b02 100644 --- a/src/gov/nasa/worldwind/ogc/kml/io/package-info.java +++ b/src/gov/nasa/worldwind/ogc/kml/io/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

          * Provides classes for KML and KMZ file and stream I/O and relative-path resolution.

          diff --git a/src/gov/nasa/worldwind/ogc/kml/package-info.java b/src/gov/nasa/worldwind/ogc/kml/package-info.java index 4ace6c848b..879b21cb83 100644 --- a/src/gov/nasa/worldwind/ogc/kml/package-info.java +++ b/src/gov/nasa/worldwind/ogc/kml/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

          * Provides classes for parsing KML and KMZ files and streams.

          @@ -38,14 +37,14 @@ * able to provide its own, and in some cases is expected to. *

          Extending the Classes

          * -

          + *

          * This package's classes are designed for easy behavior modification and replacement, and for straightforward addition * of operations to be performed during parsing. See the description of {@link * gov.nasa.worldwind.util.xml.AbstractXMLEventParser} for further information.

          * -

          Relative References

          + *

          Relative References

          * -

          + *

          * Because the KML specification requires relative references within KML files to be resolved relative to the location * of the file, a context is provided to resolve these references. The context is specific to the document type — * file, stream, KML or KMZ — and is provided by the {@link gov.nasa.worldwind.ogc.kml.io.KMLDoc} interface and its diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSAddress.java b/src/gov/nasa/worldwind/ogc/ows/OWSAddress.java index 34e032eaf1..756919589f 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSAddress.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSAddress.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.WWUtil; @@ -17,79 +16,66 @@ * @author tag * @version $Id: OWSAddress.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSAddress extends AbstractXMLEventParser -{ +public class OWSAddress extends AbstractXMLEventParser { + protected List deliveryPoints = new ArrayList(1); protected List postalCodes = new ArrayList(1); protected List countries = new ArrayList(1); protected List emails = new ArrayList(1); - public OWSAddress(String namespaceURI) - { + public OWSAddress(String namespaceURI) { super(namespaceURI); } - public String getCity() - { + public String getCity() { return (String) (this.getField("City") != null ? this.getField("City") : this.getField("city")); } - public String getAdministrativeArea() - { + public String getAdministrativeArea() { return (String) (this.getField("AdministrativeArea") != null - ? this.getField("AdministrativeArea") : this.getField("administrativeArea")); + ? this.getField("AdministrativeArea") : this.getField("administrativeArea")); } - public List getDeliveryPoints() - { + public List getDeliveryPoints() { return this.deliveryPoints; } - public List getPostalCodes() - { + public List getPostalCodes() { return this.postalCodes; } - public List getCountries() - { + public List getCountries() { return this.countries; } - public List getElectronicMailAddresses() - { + public List getElectronicMailAddresses() { return this.emails; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "DeliveryPoint") || ctx.isStartElement(event, "deliveryPoint")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "DeliveryPoint") || ctx.isStartElement(event, "deliveryPoint")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.deliveryPoints.add(s); - } - else if (ctx.isStartElement(event, "PostalCode") || ctx.isStartElement(event, "postalCode")) - { + } + } else if (ctx.isStartElement(event, "PostalCode") || ctx.isStartElement(event, "postalCode")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.postalCodes.add(s); - } - else if (ctx.isStartElement(event, "Country") || ctx.isStartElement(event, "country")) - { + } + } else if (ctx.isStartElement(event, "Country") || ctx.isStartElement(event, "country")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.countries.add(s); - } - else if (ctx.isStartElement(event, "ElectronicMailAddress") - || ctx.isStartElement(event, "electronicMailAddress")) - { + } + } else if (ctx.isStartElement(event, "ElectronicMailAddress") + || ctx.isStartElement(event, "electronicMailAddress")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.emails.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSAllowedValues.java b/src/gov/nasa/worldwind/ogc/ows/OWSAllowedValues.java index 46d2e17625..66cb229ca0 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSAllowedValues.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSAllowedValues.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.WWUtil; @@ -17,31 +16,26 @@ * @author tag * @version $Id: OWSAllowedValues.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSAllowedValues extends AbstractXMLEventParser -{ +public class OWSAllowedValues extends AbstractXMLEventParser { + protected List values = new ArrayList(2); - public OWSAllowedValues(String namespaceURI) - { + public OWSAllowedValues(String namespaceURI) { super(namespaceURI); } - public List getValues() - { + public List getValues() { return this.values; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Value")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Value")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.values.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSCapabilities.java b/src/gov/nasa/worldwind/ogc/ows/OWSCapabilities.java index 938431c9cb..2b663e8774 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSCapabilities.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSCapabilities.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.WWXML; @@ -19,8 +18,8 @@ * @author tag * @version $Id: OWSCapabilities.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public abstract class OWSCapabilities extends AbstractXMLEventParser -{ +public abstract class OWSCapabilities extends AbstractXMLEventParser { + abstract protected void determineNamespaces(); protected String owsNamespaceURI; @@ -32,13 +31,12 @@ public abstract class OWSCapabilities extends AbstractXMLEventParser * Create a new capabilities parser. * * @param namespaceURI the default namespace URI. - * @param docSource the XML source. May be a filename, file, stream or other type allowed by {@link + * @param docSource the XML source. May be a filename, file, stream or other type allowed by {@link * WWXML#openEventReader(Object)}. * * @throws IllegalArgumentException if the document source is null. */ - public OWSCapabilities(String namespaceURI, Object docSource) - { + public OWSCapabilities(String namespaceURI, Object docSource) { super(namespaceURI); this.eventReader = this.createReader(docSource); @@ -46,26 +44,22 @@ public OWSCapabilities(String namespaceURI, Object docSource) this.initialize(); } - protected void initialize() - { + protected void initialize() { this.parserContext = this.createParserContext(this.eventReader); } - protected XMLEventReader createReader(Object docSource) - { + protected XMLEventReader createReader(Object docSource) { return WWXML.openEventReader(docSource); } - protected XMLEventParserContext createParserContext(XMLEventReader reader) - { + protected XMLEventParserContext createParserContext(XMLEventReader reader) { this.parserContext = new BasicXMLEventParserContext(reader); this.parserContext.setDefaultNamespaceURI(this.getNamespaceURI()); return this.parserContext; } - public XMLEventParserContext getParserContext() - { + public XMLEventParserContext getParserContext() { return this.parserContext; } @@ -74,8 +68,7 @@ public XMLEventParserContext getParserContext() * * @return the document's version number. */ - public String getVersion() - { + public String getVersion() { return (String) this.getField("version"); } @@ -84,23 +77,19 @@ public String getVersion() * * @return the document's update sequence. */ - public String getUpdateSequence() - { + public String getUpdateSequence() { return (String) this.getField("updateSequence"); } - public OWSServiceIdentification getServiceIdentification() - { + public OWSServiceIdentification getServiceIdentification() { return (OWSServiceIdentification) this.getField("ServiceIdentification"); } - public OWSServiceProvider getServiceProvider() - { + public OWSServiceProvider getServiceProvider() { return (OWSServiceProvider) this.getField("ServiceProvider"); } - public OWSOperationsMetadata getOperationsMetadata() - { + public OWSOperationsMetadata getOperationsMetadata() { return (OWSOperationsMetadata) this.getField("OperationsMetadata"); } @@ -110,23 +99,20 @@ public OWSOperationsMetadata getOperationsMetadata() * * @param args optional arguments to pass to parsers of sub-elements. * - * @return this if parsing is successful, otherwise null. + * @return this if parsing is successful, otherwise null. * - * @throws javax.xml.stream.XMLStreamException - * if an exception occurs while attempting to read the event stream. + * @throws javax.xml.stream.XMLStreamException if an exception occurs while attempting to read the event stream. */ - public OWSCapabilities parse(Object... args) throws XMLStreamException - { + public OWSCapabilities parse(Object... args) throws XMLStreamException { XMLEventParserContext ctx = this.parserContext; QName capsName = new QName(this.getNamespaceURI(), "Capabilities"); - for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isStartElement() && event.asStartElement().getName().equals(capsName)) - { + if (event.isStartElement() && event.asStartElement().getName().equals(capsName)) { // Parse the attributes in order to get the version number in order to determine the namespaces. this.doParseEventAttributes(ctx, event); this.determineNamespaces(); // calls the subclass to do this @@ -143,106 +129,102 @@ public OWSCapabilities parse(Object... args) throws XMLStreamException return null; } - protected void setOWSNamespaceURI(String ns) - { + protected void setOWSNamespaceURI(String ns) { this.owsNamespaceURI = ns; } - public String getOWSNamespaceURI() - { + public String getOWSNamespaceURI() { return owsNamespaceURI; } - protected void registerParsers(XMLEventParserContext ctx) - { - ctx.addStringParsers(this.getOWSNamespaceURI(), new String[] - { - "Abstract", - "AccessConstraints", - "AdministrativeArea", - "City", - "ContactInstructions", - "Country", - "DeliveryPoint", - "ElectronicMailAddress", - "Facsimile", - "Fees", - "HoursOfService", - "IndividualName", - "Keyword", - "LowerCorner", - "PositionName", - "PostalCode", - "Profile", - "ProviderName", - "Role", - "ServiceType", - "ServiceTypeVersion", - "Title", - "UpperCorner", - "Value", - "Voice" - }); + protected void registerParsers(XMLEventParserContext ctx) { + ctx.addStringParsers(this.getOWSNamespaceURI(), new String[]{ + "Abstract", + "AccessConstraints", + "AdministrativeArea", + "City", + "ContactInstructions", + "Country", + "DeliveryPoint", + "ElectronicMailAddress", + "Facsimile", + "Fees", + "HoursOfService", + "IndividualName", + "Keyword", + "LowerCorner", + "PositionName", + "PostalCode", + "Profile", + "ProviderName", + "Role", + "ServiceType", + "ServiceTypeVersion", + "Title", + "UpperCorner", + "Value", + "Voice" + }); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "Address"), - new OWSAddress(this.getOWSNamespaceURI())); + new OWSAddress(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "AllowedValues"), - new OWSAllowedValues(this.getOWSNamespaceURI())); + new OWSAllowedValues(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "WGS84BoundingBox"), - new OWSWGS84BoundingBox(this.getOWSNamespaceURI())); + new OWSWGS84BoundingBox(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "Constraint"), - new OWSConstraint(this.getOWSNamespaceURI())); + new OWSConstraint(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "ContactInfo"), - new OWSContactInfo(this.getOWSNamespaceURI())); + new OWSContactInfo(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "DCP"), - new OWSDCP(this.getOWSNamespaceURI())); + new OWSDCP(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "Get"), - new AttributesOnlyXMLEventParser(this.getOWSNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "HTTP"), - new OWSHTTP(this.getOWSNamespaceURI())); + new OWSHTTP(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "Keywords"), - new StringListXMLEventParser(this.getOWSNamespaceURI(), new QName(this.getOWSNamespaceURI(), "Keyword"))); + new StringListXMLEventParser(this.getOWSNamespaceURI(), new QName(this.getOWSNamespaceURI(), "Keyword"))); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "OnlineResource"), - new AttributesOnlyXMLEventParser(this.getOWSNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "Operation"), - new OWSOperation(this.getOWSNamespaceURI())); + new OWSOperation(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "OperationsMetadata"), - new OWSOperationsMetadata(this.getOWSNamespaceURI())); + new OWSOperationsMetadata(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "Parameter"), - new OWSParameter(this.getOWSNamespaceURI())); + new OWSParameter(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "Phone"), - new OWSPhone(this.getOWSNamespaceURI())); + new OWSPhone(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "Post"), - new AttributesOnlyXMLEventParser(this.getOWSNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "ProviderSite"), - new AttributesOnlyXMLEventParser(this.getOWSNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "ServiceContact"), - new OWSServiceContact(this.getOWSNamespaceURI())); + new OWSServiceContact(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "ServiceIdentification"), - new OWSServiceIdentification(this.getOWSNamespaceURI())); + new OWSServiceIdentification(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "ServiceProvider"), - new OWSServiceProvider(this.getOWSNamespaceURI())); + new OWSServiceProvider(this.getOWSNamespaceURI())); ctx.registerParser(new QName(this.getOWSNamespaceURI(), "WGS84BoundingBox"), - new OWSWGS84BoundingBox(this.getOWSNamespaceURI())); + new OWSWGS84BoundingBox(this.getOWSNamespaceURI())); // Protocol specific parsers are registered by subclass. } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSConstraint.java b/src/gov/nasa/worldwind/ogc/ows/OWSConstraint.java index b87fd5ef5b..f08b2803e4 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSConstraint.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSConstraint.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.*; @@ -16,40 +15,33 @@ * @author tag * @version $Id: OWSConstraint.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSConstraint extends AbstractXMLEventParser -{ +public class OWSConstraint extends AbstractXMLEventParser { + protected List allowedValues = new ArrayList(1); - public OWSConstraint(String namespaceURI) - { + public OWSConstraint(String namespaceURI) { super(namespaceURI); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public List getAllowedValues() - { + public List getAllowedValues() { return this.allowedValues; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "AllowedValues")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "AllowedValues")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OWSAllowedValues) + if (o != null && o instanceof OWSAllowedValues) { this.allowedValues.add((OWSAllowedValues) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSContactInfo.java b/src/gov/nasa/worldwind/ogc/ows/OWSContactInfo.java index 738e63a084..b9429b586f 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSContactInfo.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSContactInfo.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.*; @@ -12,38 +11,31 @@ * @author tag * @version $Id: OWSContactInfo.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSContactInfo extends AbstractXMLEventParser -{ - public OWSContactInfo(String namespaceURI) - { +public class OWSContactInfo extends AbstractXMLEventParser { + + public OWSContactInfo(String namespaceURI) { super(namespaceURI); } - public String getHoursOfService() - { + public String getHoursOfService() { return (String) this.getField("HoursOfService"); } - public String getContactInstructions() - { + public String getContactInstructions() { return (String) this.getField("ContactInstructions"); } - public OWSAddress getAddress() - { + public OWSAddress getAddress() { return (OWSAddress) (this.getField("Address") != null ? this.getField("Address") : this.getField("address")); } - public OWSPhone getPhone() - { + public OWSPhone getPhone() { return (OWSPhone) (this.getField("Phone") != null ? this.getField("Phone") : this.getField("phone")); } - public String getOnlineResource() - { - AttributesOnlyXMLEventParser parser = (AttributesOnlyXMLEventParser) - (this.getField("OnlineResource") != null ? this.getField("OnlineResource") - : this.getField("onlineResource")); + public String getOnlineResource() { + AttributesOnlyXMLEventParser parser = (AttributesOnlyXMLEventParser) (this.getField("OnlineResource") != null ? this.getField("OnlineResource") + : this.getField("onlineResource")); return parser != null ? (String) parser.getField("href") : null; } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSDCP.java b/src/gov/nasa/worldwind/ogc/ows/OWSDCP.java index a5d917e218..f54942e1d0 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSDCP.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSDCP.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,15 +11,13 @@ * @author tag * @version $Id: OWSDCP.java 1981 2014-05-08 03:59:04Z tgaskins $ */ -public class OWSDCP extends AbstractXMLEventParser -{ - public OWSDCP(String namespaceURI) - { +public class OWSDCP extends AbstractXMLEventParser { + + public OWSDCP(String namespaceURI) { super(namespaceURI); } - public OWSHTTP getHTTP() - { + public OWSHTTP getHTTP() { return (OWSHTTP) this.getField("HTTP"); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSHTTP.java b/src/gov/nasa/worldwind/ogc/ows/OWSHTTP.java index 8590133de6..abbe2a39b6 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSHTTP.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSHTTP.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.*; @@ -16,56 +15,53 @@ * @author tag * @version $Id: OWSHTTP.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSHTTP extends AbstractXMLEventParser -{ +public class OWSHTTP extends AbstractXMLEventParser { + protected List gets = new ArrayList(1); protected List posts = new ArrayList(1); - public OWSHTTP(String namespaceURI) - { + public OWSHTTP(String namespaceURI) { super(namespaceURI); } - public List getGetAddresses() - { - if (this.gets == null) + public List getGetAddresses() { + if (this.gets == null) { return null; + } List addresses = new ArrayList(this.gets.size()); - for (AttributesOnlyXMLEventParser parser : this.gets) - { - if (parser != null) + for (AttributesOnlyXMLEventParser parser : this.gets) { + if (parser != null) { addresses.add((String) parser.getField("href")); + } } return addresses; } - public List getPostAddresses() - { - if (this.posts == null) + public List getPostAddresses() { + if (this.posts == null) { return null; + } List addresses = new ArrayList(this.posts.size()); - for (AttributesOnlyXMLEventParser parser : this.posts) - { - if (parser != null) + for (AttributesOnlyXMLEventParser parser : this.posts) { + if (parser != null) { addresses.add((String) parser.getField("href")); + } } return addresses; } - public String getGetAddress() - { + public String getGetAddress() { List addresses = this.getGetAddresses(); Iterator iter = addresses.iterator(); return iter.hasNext() ? iter.next() : null; } - public String getPostAddress() - { + public String getPostAddress() { List addresses = this.getPostAddresses(); Iterator iter = addresses.iterator(); @@ -73,30 +69,24 @@ public String getPostAddress() } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Get")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Get")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof AttributesOnlyXMLEventParser) + if (o != null && o instanceof AttributesOnlyXMLEventParser) { this.gets.add((AttributesOnlyXMLEventParser) o); + } } - } - else if (ctx.isStartElement(event, "Post")) - { + } else if (ctx.isStartElement(event, "Post")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof AttributesOnlyXMLEventParser) + if (o != null && o instanceof AttributesOnlyXMLEventParser) { this.posts.add((AttributesOnlyXMLEventParser) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSOperation.java b/src/gov/nasa/worldwind/ogc/ows/OWSOperation.java index c549c5803e..ecdf3da187 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSOperation.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSOperation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.*; @@ -16,74 +15,60 @@ * @author tag * @version $Id: OWSOperation.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSOperation extends AbstractXMLEventParser -{ +public class OWSOperation extends AbstractXMLEventParser { // TODO: Operation Metadata element protected List dcps = new ArrayList(2); protected List parameters = new ArrayList(1); protected List constraints = new ArrayList(1); - public OWSOperation(String namespaceURI) - { + public OWSOperation(String namespaceURI) { super(namespaceURI); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public List getDCPs() - { + public List getDCPs() { return this.dcps; } - public List getParameters() - { + public List getParameters() { return this.parameters; } - public List getConstraints() - { + public List getConstraints() { return this.constraints; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "DCP")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "DCP")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OWSDCP) + if (o != null && o instanceof OWSDCP) { this.dcps.add((OWSDCP) o); + } } - } - else if (ctx.isStartElement(event, "Parameter")) - { + } else if (ctx.isStartElement(event, "Parameter")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OWSParameter) + if (o != null && o instanceof OWSParameter) { this.parameters.add((OWSParameter) o); + } } - } - else if (ctx.isStartElement(event, "Constraint")) - { + } else if (ctx.isStartElement(event, "Constraint")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OWSConstraint) + if (o != null && o instanceof OWSConstraint) { this.constraints.add((OWSConstraint) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSOperationsMetadata.java b/src/gov/nasa/worldwind/ogc/ows/OWSOperationsMetadata.java index f040f55a5a..6d35d83f9d 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSOperationsMetadata.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSOperationsMetadata.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.*; @@ -16,51 +15,44 @@ * @author tag * @version $Id: OWSOperationsMetadata.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSOperationsMetadata extends AbstractXMLEventParser -{ +public class OWSOperationsMetadata extends AbstractXMLEventParser { + protected List operations = new ArrayList(2); protected List constraints = new ArrayList(1); - public OWSOperationsMetadata(String namespaceURI) - { + public OWSOperationsMetadata(String namespaceURI) { super(namespaceURI); } - public List getOperations() - { + public List getOperations() { return this.operations; } - public List getConstraints() - { + public List getConstraints() { return this.constraints; } - public OWSOperation getOperation(String opName) - { - for (OWSOperation op : this.getOperations()) - { - if (op.getName().equals(opName)) + public OWSOperation getOperation(String opName) { + for (OWSOperation op : this.getOperations()) { + if (op.getName().equals(opName)) { return op; + } } return null; } - public String getGetOperationAddress(String opProtocol, String opName) - { + public String getGetOperationAddress(String opProtocol, String opName) { OWSOperation op = this.getOperation(opName); - if (opName != null) - { - for (OWSDCP dcp : op.getDCPs()) - { + if (opName != null) { + for (OWSDCP dcp : op.getDCPs()) { OWSHTTP http = dcp.getHTTP(); - if (http != null) - { - if (opProtocol.equals("Get") && http.getGetAddress() != null) + if (http != null) { + if (opProtocol.equals("Get") && http.getGetAddress() != null) { return http.getGetAddress(); - else if (opProtocol.equals("Post") && http.getPostAddress() != null) + } else if (opProtocol.equals("Post") && http.getPostAddress() != null) { return http.getPostAddress(); + } } } } @@ -69,30 +61,24 @@ else if (opProtocol.equals("Post") && http.getPostAddress() != null) } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Operation")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Operation")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OWSOperation) + if (o != null && o instanceof OWSOperation) { this.operations.add((OWSOperation) o); + } } - } - else if (ctx.isStartElement(event, "Constraint")) - { + } else if (ctx.isStartElement(event, "Constraint")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OWSConstraint) + if (o != null && o instanceof OWSConstraint) { this.constraints.add((OWSConstraint) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSParameter.java b/src/gov/nasa/worldwind/ogc/ows/OWSParameter.java index b0412752d6..9784fdc5d9 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSParameter.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSParameter.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.*; @@ -16,40 +15,33 @@ * @author tag * @version $Id: OWSParameter.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSParameter extends AbstractXMLEventParser -{ +public class OWSParameter extends AbstractXMLEventParser { + protected List allowedValues = new ArrayList(1); - public OWSParameter(String namespaceURI) - { + public OWSParameter(String namespaceURI) { super(namespaceURI); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public List getAllowedValues() - { + public List getAllowedValues() { return this.allowedValues; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "AllowedValues")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "AllowedValues")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OWSAllowedValues) + if (o != null && o instanceof OWSAllowedValues) { this.allowedValues.add((OWSAllowedValues) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSPhone.java b/src/gov/nasa/worldwind/ogc/ows/OWSPhone.java index eecea53f6a..2767174160 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSPhone.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSPhone.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.WWUtil; @@ -17,43 +16,36 @@ * @author tag * @version $Id: OWSPhone.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSPhone extends AbstractXMLEventParser -{ +public class OWSPhone extends AbstractXMLEventParser { + protected List voices = new ArrayList(1); protected List faxes = new ArrayList(1); - public OWSPhone(String namespaceURI) - { + public OWSPhone(String namespaceURI) { super(namespaceURI); } - public List getVoices() - { + public List getVoices() { return this.voices; } - public List getFacsimiles() - { + public List getFacsimiles() { return this.faxes; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Voice") || ctx.isStartElement(event, "voice")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Voice") || ctx.isStartElement(event, "voice")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.voices.add(s); - } - else if (ctx.isStartElement(event, "Facsimile") || ctx.isStartElement(event, "facsimile")) - { + } + } else if (ctx.isStartElement(event, "Facsimile") || ctx.isStartElement(event, "facsimile")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.faxes.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSServiceContact.java b/src/gov/nasa/worldwind/ogc/ows/OWSServiceContact.java index 5487d0ac4f..5ac5ec0d91 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSServiceContact.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSServiceContact.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.*; @@ -12,40 +11,33 @@ * @author tag * @version $Id: OWSServiceContact.java 1981 2014-05-08 03:59:04Z tgaskins $ */ -public class OWSServiceContact extends AbstractXMLEventParser -{ - public OWSServiceContact(String namespaceURI) - { +public class OWSServiceContact extends AbstractXMLEventParser { + + public OWSServiceContact(String namespaceURI) { super(namespaceURI); } - public String getIndividualName() - { + public String getIndividualName() { return (String) this.getField("IndividualName"); } - public String getPositionName() - { + public String getPositionName() { return (String) this.getField("PositionName"); } - public String getRole() - { + public String getRole() { return (String) this.getField("Role"); } - public OWSContactInfo getContactInfo() - { + public OWSContactInfo getContactInfo() { return (OWSContactInfo) this.getField("ContactInfo"); } - public OWSPhone getPhone() - { + public OWSPhone getPhone() { return (OWSPhone) this.getField("Phone"); } - public OWSAddress getAddress() - { + public OWSAddress getAddress() { return (OWSAddress) getField("Address"); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSServiceIdentification.java b/src/gov/nasa/worldwind/ogc/ows/OWSServiceIdentification.java index e08b986aad..706921dd6d 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSServiceIdentification.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSServiceIdentification.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.WWUtil; @@ -17,94 +16,78 @@ * @author tag * @version $Id: OWSServiceIdentification.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class OWSServiceIdentification extends AbstractXMLEventParser -{ +public class OWSServiceIdentification extends AbstractXMLEventParser { + protected List abstracts = new ArrayList(1); protected List accessConstraints = new ArrayList(1); protected List profiles = new ArrayList(1); protected List titles = new ArrayList(1); protected List serviceTypeVersions = new ArrayList(1); - public OWSServiceIdentification(String namespaceURI) - { + public OWSServiceIdentification(String namespaceURI) { super(namespaceURI); } - public List getTitles() - { + public List getTitles() { return this.titles; } - public List getAbstracts() - { + public List getAbstracts() { return this.abstracts; } - public List getKeywords() - { + public List getKeywords() { return ((StringListXMLEventParser) this.getField("Keywords")).getStrings(); } - public String getServiceType() - { + public String getServiceType() { return (String) this.getField("ServiceType"); } - public List getServiceTypeVersions() - { + public List getServiceTypeVersions() { return this.serviceTypeVersions; } - public String getFees() - { + public String getFees() { return (String) this.getField("Fees"); } - public List getAccessConstraints() - { + public List getAccessConstraints() { return this.accessConstraints; } - public List getProfiles() - { + public List getProfiles() { return this.profiles; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "ServiceTypeVersion")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "ServiceTypeVersion")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.serviceTypeVersions.add(s); - } - else if (ctx.isStartElement(event, "Abstract")) - { + } + } else if (ctx.isStartElement(event, "Abstract")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.abstracts.add(s); - } - else if (ctx.isStartElement(event, "AccessConstraints")) - { + } + } else if (ctx.isStartElement(event, "AccessConstraints")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.accessConstraints.add(s); - } - else if (ctx.isStartElement(event, "Title")) - { + } + } else if (ctx.isStartElement(event, "Title")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.titles.add(s); - } - else if (ctx.isStartElement(event, "Profile")) - { + } + } else if (ctx.isStartElement(event, "Profile")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.profiles.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSServiceProvider.java b/src/gov/nasa/worldwind/ogc/ows/OWSServiceProvider.java index 8c1515a51b..a6c5917066 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSServiceProvider.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSServiceProvider.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.*; @@ -12,27 +11,23 @@ * @author tag * @version $Id: OWSServiceProvider.java 1981 2014-05-08 03:59:04Z tgaskins $ */ -public class OWSServiceProvider extends AbstractXMLEventParser -{ - public OWSServiceProvider(String namespaceURI) - { +public class OWSServiceProvider extends AbstractXMLEventParser { + + public OWSServiceProvider(String namespaceURI) { super(namespaceURI); } - public String getProviderName() - { + public String getProviderName() { return (String) this.getField("ProviderName"); } - public String getProviderSite() - { + public String getProviderSite() { AttributesOnlyXMLEventParser parser = (AttributesOnlyXMLEventParser) this.getField("ProviderSite"); return parser != null ? (String) parser.getField("href") : null; } - public OWSServiceContact getServiceContact() - { + public OWSServiceContact getServiceContact() { return (OWSServiceContact) this.getField("ServiceContact"); } } diff --git a/src/gov/nasa/worldwind/ogc/ows/OWSWGS84BoundingBox.java b/src/gov/nasa/worldwind/ogc/ows/OWSWGS84BoundingBox.java index 2cc49048a9..ac67b465bf 100644 --- a/src/gov/nasa/worldwind/ogc/ows/OWSWGS84BoundingBox.java +++ b/src/gov/nasa/worldwind/ogc/ows/OWSWGS84BoundingBox.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.ows; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,20 +11,17 @@ * @author tag * @version $Id: OWSWGS84BoundingBox.java 1981 2014-05-08 03:59:04Z tgaskins $ */ -public class OWSWGS84BoundingBox extends AbstractXMLEventParser -{ - public OWSWGS84BoundingBox(String namespaceURI) - { +public class OWSWGS84BoundingBox extends AbstractXMLEventParser { + + public OWSWGS84BoundingBox(String namespaceURI) { super(namespaceURI); } - public String getLowerCorner() - { + public String getLowerCorner() { return (String) this.getField("LowerCorner"); } - public String getUpperCorner() - { + public String getUpperCorner() { return (String) this.getField("UpperCorner"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/WCSCapabilities.java b/src/gov/nasa/worldwind/ogc/wcs/WCSCapabilities.java index 015d2e82db..592bc36763 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/WCSCapabilities.java +++ b/src/gov/nasa/worldwind/ogc/wcs/WCSCapabilities.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs; import gov.nasa.worldwind.ogc.OGCConstants; @@ -17,73 +16,61 @@ * @author tag * @version $Id: WCSCapabilities.java 1981 2014-05-08 03:59:04Z tgaskins $ */ -public class WCSCapabilities extends OWSCapabilities -{ - public WCSCapabilities(Object docSource) - { +public class WCSCapabilities extends OWSCapabilities { + + public WCSCapabilities(Object docSource) { super(OGCConstants.WCS_1_1_1_NAMESPACE_URI, docSource); } - public WCSContents getContents() - { + public WCSContents getContents() { return (WCSContents) this.getField("Contents"); } - public String getOtherSource() - { + public String getOtherSource() { AttributesOnlyXMLEventParser parser = (AttributesOnlyXMLEventParser) this.getField("OtherSource"); return parser != null ? (String) parser.getField("href") : null; } - public String getDefaultNamespaceURI() - { + public String getDefaultNamespaceURI() { return this.namespaceURI; } - public String getWCSNamespace() - { + public String getWCSNamespace() { return this.namespaceURI; } - protected void determineNamespaces() - { + protected void determineNamespaces() { String version = this.getVersion(); - if (version == null) - { + if (version == null) { this.setOWSNamespaceURI(OGCConstants.OWS_1_1_0_NAMESPACE_URI); this.setNamespaceURI(OGCConstants.WCS_1_1_1_NAMESPACE_URI); - } - else if (WWUtil.compareVersion(version, "1.1.1") == 0) - { + } else if (WWUtil.compareVersion(version, "1.1.1") == 0) { this.setOWSNamespaceURI(OGCConstants.OWS_1_1_0_NAMESPACE_URI); this.setNamespaceURI(OGCConstants.WCS_1_1_1_NAMESPACE_URI); - } - else - { + } else { this.setOWSNamespaceURI(OGCConstants.OWS_1_1_0_NAMESPACE_URI); this.setNamespaceURI(OGCConstants.WCS_1_1_1_NAMESPACE_URI); } } @Override - protected void registerParsers(XMLEventParserContext ctx) - { + protected void registerParsers(XMLEventParserContext ctx) { super.registerParsers(ctx); - ctx.addStringParsers(this.namespaceURI, new String[] { + ctx.addStringParsers(this.namespaceURI, new String[]{ "Identifier", "SupportedCRS", "SupportedFormat" }); ctx.registerParser(new QName(this.getWCSNamespace(), "Contents"), - new WCSContents(this.namespaceURI)); + new WCSContents(this.namespaceURI)); ctx.registerParser(new QName(this.getWCSNamespace(), "CoverageSummary"), - new WCSCoverageSummary(this.namespaceURI)); + new WCSCoverageSummary(this.namespaceURI)); ctx.registerParser(new QName(this.getWCSNamespace(), "OtherSource"), - new AttributesOnlyXMLEventParser(this.namespaceURI)); + new AttributesOnlyXMLEventParser(this.namespaceURI)); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/WCSContents.java b/src/gov/nasa/worldwind/ogc/wcs/WCSContents.java index be58976965..b5e868a273 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/WCSContents.java +++ b/src/gov/nasa/worldwind/ogc/wcs/WCSContents.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs; import gov.nasa.worldwind.util.WWUtil; @@ -17,84 +16,71 @@ * @author tag * @version $Id: WCSContents.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCSContents extends AbstractXMLEventParser -{ +public class WCSContents extends AbstractXMLEventParser { + protected List coverageSummaries = new ArrayList(1); protected List otherSources = new ArrayList(1); protected List supportedCRSs = new ArrayList(1); protected List supportedFormats = new ArrayList(1); - public WCSContents(String namespaceURI) - { + public WCSContents(String namespaceURI) { super(namespaceURI); } - public List getCoverageSummaries() - { + public List getCoverageSummaries() { return this.coverageSummaries; } - public List getSupportedCRSs() - { + public List getSupportedCRSs() { return this.supportedCRSs; } - public List getSupportedFormats() - { + public List getSupportedFormats() { return this.supportedFormats; } - public List getOtherSources() - { + public List getOtherSources() { List strings = new ArrayList(1); - for (AttributesOnlyXMLEventParser parser : this.otherSources) - { + for (AttributesOnlyXMLEventParser parser : this.otherSources) { String url = (String) parser.getField("href"); - if (url != null) + if (url != null) { strings.add(url); + } } return strings.size() > 0 ? strings : null; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "CoverageSummary")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "CoverageSummary")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCSCoverageSummary) + if (o != null && o instanceof WCSCoverageSummary) { this.coverageSummaries.add((WCSCoverageSummary) o); + } } - } - else if (ctx.isStartElement(event, "OtherSource")) - { + } else if (ctx.isStartElement(event, "OtherSource")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof AttributesOnlyXMLEventParser) + if (o != null && o instanceof AttributesOnlyXMLEventParser) { this.otherSources.add((AttributesOnlyXMLEventParser) o); + } } - } - else if (ctx.isStartElement(event, "SupportedCRS")) - { + } else if (ctx.isStartElement(event, "SupportedCRS")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.supportedCRSs.add(s); - } - else if (ctx.isStartElement(event, "SupportedFormat")) - { + } + } else if (ctx.isStartElement(event, "SupportedFormat")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.supportedFormats.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/WCSCoverageSummary.java b/src/gov/nasa/worldwind/ogc/wcs/WCSCoverageSummary.java index fe27bce30d..c081c346bb 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/WCSCoverageSummary.java +++ b/src/gov/nasa/worldwind/ogc/wcs/WCSCoverageSummary.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs; import gov.nasa.worldwind.ogc.ows.OWSWGS84BoundingBox; @@ -18,8 +17,7 @@ * @author tag * @version $Id: WCSCoverageSummary.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCSCoverageSummary extends AbstractXMLEventParser -{ +public class WCSCoverageSummary extends AbstractXMLEventParser { // TODO: metadata protected List abstracts = new ArrayList(1); @@ -29,121 +27,99 @@ public class WCSCoverageSummary extends AbstractXMLEventParser protected List supportedFormats = new ArrayList(1); protected List titles = new ArrayList(1); - public WCSCoverageSummary(String namespaceURI) - { + public WCSCoverageSummary(String namespaceURI) { super(namespaceURI); } - public List getAbstracts() - { + public List getAbstracts() { return this.abstracts; } - public String getAbstract() - { + public String getAbstract() { Iterator iter = this.abstracts.iterator(); return iter.hasNext() ? iter.next() : null; } - public List getBoundingBoxes() - { + public List getBoundingBoxes() { return this.boundingBoxes; } - public OWSWGS84BoundingBox getBoundingBox() - { + public OWSWGS84BoundingBox getBoundingBox() { Iterator iter = this.boundingBoxes.iterator(); return iter.hasNext() ? iter.next() : null; } - public List getCoverageSummaries() - { + public List getCoverageSummaries() { return this.coverageSummaries; } - public String getIdentifier() - { + public String getIdentifier() { return (String) this.getField("Identifier"); } - public List getKeywords() - { + public List getKeywords() { return ((StringListXMLEventParser) this.getField("Keywords")).getStrings(); } - public List getSupportedCRSs() - { + public List getSupportedCRSs() { return this.supportedCRSs; } - public List getSupportedFormats() - { + public List getSupportedFormats() { return this.supportedFormats; } - public List getTitles() - { + public List getTitles() { return this.titles; } - public String getTitle() - { + public String getTitle() { Iterator iter = this.titles.iterator(); return iter.hasNext() ? iter.next() : null; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Abstract")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Abstract")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.abstracts.add(s); - } - else if (ctx.isStartElement(event, "WGS84BoundingBox")) - { + } + } else if (ctx.isStartElement(event, "WGS84BoundingBox")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OWSWGS84BoundingBox) + if (o != null && o instanceof OWSWGS84BoundingBox) { this.boundingBoxes.add((OWSWGS84BoundingBox) o); + } } - } - else if (ctx.isStartElement(event, "CoverageSummary")) - { + } else if (ctx.isStartElement(event, "CoverageSummary")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCSCoverageSummary) + if (o != null && o instanceof WCSCoverageSummary) { this.coverageSummaries.add((WCSCoverageSummary) o); + } } - } - else if (ctx.isStartElement(event, "SupportedCRS")) - { + } else if (ctx.isStartElement(event, "SupportedCRS")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.supportedCRSs.add(s); - } - else if (ctx.isStartElement(event, "SupportedFormat")) - { + } + } else if (ctx.isStartElement(event, "SupportedFormat")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.supportedFormats.add(s); - } - else if (ctx.isStartElement(event, "Title")) - { + } + } else if (ctx.isStartElement(event, "Title")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.titles.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100AxisDescription.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100AxisDescription.java index 95aaac0d72..96ac770801 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100AxisDescription.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100AxisDescription.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.WWUtil; @@ -17,58 +16,48 @@ * @author tag * @version $Id: WCS100AxisDescription.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100AxisDescription extends AbstractXMLEventParser -{ +public class WCS100AxisDescription extends AbstractXMLEventParser { + protected List axisNames = new ArrayList(2); protected List offsetVectors = new ArrayList(2); - public WCS100AxisDescription(String namespaceURI) - { + public WCS100AxisDescription(String namespaceURI) { super(namespaceURI); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public String getLabel() - { + public String getLabel() { return (String) this.getField("label"); } - public String getDescription() - { + public String getDescription() { return (String) this.getField("description"); } - public WCS100MetadataLink getMetadataLink() - { + public WCS100MetadataLink getMetadataLink() { return (WCS100MetadataLink) this.getField("metadataLink"); } - public WCS100Values getValues() - { + public WCS100Values getValues() { return (WCS100Values) this.getField("values"); } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "axisName")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "axisName")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.axisNames.add(s); - } - else if (ctx.isStartElement(event, "offsetVector")) - { + } + } else if (ctx.isStartElement(event, "offsetVector")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.offsetVectors.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100AxisDescriptionHolder.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100AxisDescriptionHolder.java index cb7932afa4..2b4aa8175d 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100AxisDescriptionHolder.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100AxisDescriptionHolder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,15 +11,13 @@ * @author tag * @version $Id: WCS100AxisDescriptionHolder.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100AxisDescriptionHolder extends AbstractXMLEventParser -{ - public WCS100AxisDescriptionHolder(String namespaceURI) - { +public class WCS100AxisDescriptionHolder extends AbstractXMLEventParser { + + public WCS100AxisDescriptionHolder(String namespaceURI) { super(namespaceURI); } - public WCS100AxisDescription getAxisDescription() - { + public WCS100AxisDescription getAxisDescription() { return (WCS100AxisDescription) this.getField("AxisDescription"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Capabilities.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Capabilities.java index 714eb685b4..40cf168117 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Capabilities.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Capabilities.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.ogc.OGCConstants; @@ -22,8 +21,8 @@ * @author tag * @version $Id: WCS100Capabilities.java 2072 2014-06-21 21:20:25Z tgaskins $ */ -public class WCS100Capabilities extends AbstractXMLEventParser -{ +public class WCS100Capabilities extends AbstractXMLEventParser { + protected XMLEventReader eventReader; protected XMLEventParserContext parserContext; @@ -36,28 +35,22 @@ public class WCS100Capabilities extends AbstractXMLEventParser * @throws java.lang.Exception if a general error occurs. * * @throws IllegalArgumentException if the specified URI is invalid. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if an error occurs retrieving the document. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if an error occurs retrieving the document. */ - public static WCS100Capabilities retrieve(URI uri) throws Exception - { - try - { + public static WCS100Capabilities retrieve(URI uri) throws Exception { + try { CapabilitiesRequest request = new CapabilitiesRequest(uri, "WCS"); request.setVersion("1.0.0"); return new WCS100Capabilities(request.toString()); - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { String message = Logging.getMessage("OGC.GetCapabilitiesURIInvalid", uri); Logging.logger().warning(message); throw new IllegalArgumentException(message); } } - public WCS100Capabilities(Object docSource) - { + public WCS100Capabilities(Object docSource) { super(OGCConstants.WCS_1_0_0_NAMESPACE_URI); this.eventReader = this.createReader(docSource); @@ -65,26 +58,22 @@ public WCS100Capabilities(Object docSource) this.initialize(); } - protected void initialize() - { + protected void initialize() { this.parserContext = this.createParserContext(this.eventReader); } - protected XMLEventReader createReader(Object docSource) - { + protected XMLEventReader createReader(Object docSource) { return WWXML.openEventReader(docSource); } - protected XMLEventParserContext createParserContext(XMLEventReader reader) - { + protected XMLEventParserContext createParserContext(XMLEventReader reader) { this.parserContext = new BasicXMLEventParserContext(reader); this.parserContext.setDefaultNamespaceURI(this.getNamespaceURI()); return this.parserContext; } - public XMLEventParserContext getParserContext() - { + public XMLEventParserContext getParserContext() { return this.parserContext; } @@ -93,8 +82,7 @@ public XMLEventParserContext getParserContext() * * @return the document's version number. */ - public String getVersion() - { + public String getVersion() { return (String) this.getField("version"); } @@ -103,23 +91,19 @@ public String getVersion() * * @return the document's update sequence. */ - public String getUpdateSequence() - { + public String getUpdateSequence() { return (String) this.getField("updateSequence"); } - public WCS100Service getService() - { + public WCS100Service getService() { return (WCS100Service) this.getField("Service"); } - public WCS100Capability getCapability() - { + public WCS100Capability getCapability() { return (WCS100Capability) this.getField("Capability"); } - public WCS100ContentMetadata getContentMetadata() - { + public WCS100ContentMetadata getContentMetadata() { return (WCS100ContentMetadata) this.getField("ContentMetadata"); } @@ -129,23 +113,20 @@ public WCS100ContentMetadata getContentMetadata() * * @param args optional arguments to pass to parsers of sub-elements. * - * @return this if parsing is successful, otherwise null. + * @return this if parsing is successful, otherwise null. * - * @throws javax.xml.stream.XMLStreamException - * if an exception occurs while attempting to read the event stream. + * @throws javax.xml.stream.XMLStreamException if an exception occurs while attempting to read the event stream. */ - public WCS100Capabilities parse(Object... args) throws XMLStreamException - { + public WCS100Capabilities parse(Object... args) throws XMLStreamException { XMLEventParserContext ctx = this.parserContext; QName capsName = new QName(this.getNamespaceURI(), "WCS_Capabilities"); - for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isStartElement() && event.asStartElement().getName().equals(capsName)) - { + if (event.isStartElement() && event.asStartElement().getName().equals(capsName)) { // Parse the attributes in order to get the version number. this.doParseEventAttributes(ctx, event); ctx.setDefaultNamespaceURI(this.getNamespaceURI()); @@ -162,102 +143,97 @@ public WCS100Capabilities parse(Object... args) throws XMLStreamException return null; } - protected void registerParsers(XMLEventParserContext ctx) - { - ctx.addStringParsers(this.getNamespaceURI(), new String[] - { - "accessConstraints", - "administrativeArea", - "city", - "country", - "deliveryPoint", - "description", - "electronicMailAddress", - "facsimile", - "fees", - "Format", - "individualName", - "label", - "keyword", - "name", - "organisationName", - "positionName", - "postalCode", - "voice", - }); - - ctx.addStringParsers(OGCConstants.GML_NAMESPACE_URI, new String[] - { - "timePosition", - }); + protected void registerParsers(XMLEventParserContext ctx) { + ctx.addStringParsers(this.getNamespaceURI(), new String[]{ + "accessConstraints", + "administrativeArea", + "city", + "country", + "deliveryPoint", + "description", + "electronicMailAddress", + "facsimile", + "fees", + "Format", + "individualName", + "label", + "keyword", + "name", + "organisationName", + "positionName", + "postalCode", + "voice",}); + + ctx.addStringParsers(OGCConstants.GML_NAMESPACE_URI, new String[]{ + "timePosition",}); ctx.registerParser(new QName(this.getNamespaceURI(), "address"), - new OWSAddress(this.getNamespaceURI())); + new OWSAddress(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "Capability"), - new WCS100Capability(this.getNamespaceURI())); + new WCS100Capability(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "contactInfo"), - new OWSContactInfo(this.getNamespaceURI())); + new OWSContactInfo(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "ContentMetadata"), - new WCS100ContentMetadata(this.getNamespaceURI())); + new WCS100ContentMetadata(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "CoverageOfferingBrief"), - new WCS100CoverageOfferingBrief(this.getNamespaceURI())); + new WCS100CoverageOfferingBrief(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "DCPType"), - new WCS100DCPType(this.getNamespaceURI())); + new WCS100DCPType(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "DescribeCoverage"), - new WCS100RequestDescription(this.getNamespaceURI())); + new WCS100RequestDescription(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "Exception"), - new WCS100Exception(this.getNamespaceURI())); + new WCS100Exception(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "Get"), - new AttributesOnlyXMLEventParser(this.getNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "GetCapabilities"), - new WCS100RequestDescription(this.getNamespaceURI())); + new WCS100RequestDescription(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "GetCoverage"), - new WCS100RequestDescription(this.getNamespaceURI())); + new WCS100RequestDescription(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "HTTP"), - new WCS100HTTP(this.getNamespaceURI())); + new WCS100HTTP(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "keywords"), - new StringListXMLEventParser(this.getNamespaceURI(), new QName(this.getNamespaceURI(), "keyword"))); + new StringListXMLEventParser(this.getNamespaceURI(), new QName(this.getNamespaceURI(), "keyword"))); ctx.registerParser(new QName(this.getNamespaceURI(), "lonLatEnvelope"), - new WCS100LonLatEnvelope(this.getNamespaceURI())); + new WCS100LonLatEnvelope(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "metadataLink"), - new WCS100MetadataLink(this.getNamespaceURI())); + new WCS100MetadataLink(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "OnlineResource"), - new AttributesOnlyXMLEventParser(this.getNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "onlineResource"), - new AttributesOnlyXMLEventParser(this.getNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "phone"), - new OWSPhone(this.getNamespaceURI())); + new OWSPhone(this.getNamespaceURI())); ctx.registerParser(new QName(OGCConstants.GML_NAMESPACE_URI, "pos"), - new GMLPos(OGCConstants.GML_NAMESPACE_URI)); + new GMLPos(OGCConstants.GML_NAMESPACE_URI)); ctx.registerParser(new QName(this.getNamespaceURI(), "Post"), - new AttributesOnlyXMLEventParser(this.getNamespaceURI())); + new AttributesOnlyXMLEventParser(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "Request"), - new WCS100Request(this.getNamespaceURI())); + new WCS100Request(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "responsibleParty"), - new WCS100ResponsibleParty(this.getNamespaceURI())); + new WCS100ResponsibleParty(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "Service"), - new WCS100Service(this.getNamespaceURI())); + new WCS100Service(this.getNamespaceURI())); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Capability.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Capability.java index 2caaba5dc4..59b81dca49 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Capability.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Capability.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,33 +11,29 @@ * @author tag * @version $Id$ */ -public class WCS100Capability extends AbstractXMLEventParser -{ - public WCS100Capability(String namespaceURI) - { +public class WCS100Capability extends AbstractXMLEventParser { + + public WCS100Capability(String namespaceURI) { super(namespaceURI); } - public WCS100Request getRequest() - { + public WCS100Request getRequest() { return (WCS100Request) this.getField("Request"); } - public WCS100Exception getException() - { + public WCS100Exception getException() { return (WCS100Exception) this.getField("Exception"); } - public String getGetOperationAddress(String opName) - { + public String getGetOperationAddress(String opName) { WCS100Request request = this.getRequest(); WCS100RequestDescription description = request.getRequest(opName); - for (WCS100DCPType dcpType : description.getDCPTypes()) - { + for (WCS100DCPType dcpType : description.getDCPTypes()) { WCS100HTTP http = dcpType.getHTTP(); String address = http.getGetAddress(); - if (address != null) + if (address != null) { return address; + } } return null; diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100ContentMetadata.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100ContentMetadata.java index 25419fea1f..717ae5e10b 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100ContentMetadata.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100ContentMetadata.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.*; @@ -16,35 +15,29 @@ * @author tag * @version $Id$ */ -public class WCS100ContentMetadata extends AbstractXMLEventParser -{ +public class WCS100ContentMetadata extends AbstractXMLEventParser { + protected List coverageOfferings = new ArrayList(1); - public WCS100ContentMetadata(String namespaceURI) - { + public WCS100ContentMetadata(String namespaceURI) { super(namespaceURI); } - public List getCoverageOfferings() - { + public List getCoverageOfferings() { return this.coverageOfferings; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "CoverageOfferingBrief")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "CoverageOfferingBrief")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCS100CoverageOfferingBrief) + if (o != null && o instanceof WCS100CoverageOfferingBrief) { this.coverageOfferings.add((WCS100CoverageOfferingBrief) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100CoverageOffering.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100CoverageOffering.java index a408aecf84..c9d97ef2b1 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100CoverageOffering.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100CoverageOffering.java @@ -3,47 +3,39 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; /** * @author tag * @version $Id: WCS100CoverageOffering.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100CoverageOffering extends WCS100CoverageOfferingBrief -{ - public WCS100CoverageOffering(String namespaceURI) - { +public class WCS100CoverageOffering extends WCS100CoverageOfferingBrief { + + public WCS100CoverageOffering(String namespaceURI) { super(namespaceURI); } - public WCS100LonLatEnvelope getLonLatEnvelope() - { + public WCS100LonLatEnvelope getLonLatEnvelope() { return (WCS100LonLatEnvelope) this.getField("lonLatEnvelope"); } - public WCS100DomainSet getDomainSet() - { + public WCS100DomainSet getDomainSet() { return (WCS100DomainSet) this.getField("domainSet"); } - public WCS100RangeSetHolder getRangeSet() - { + public WCS100RangeSetHolder getRangeSet() { return (WCS100RangeSetHolder) this.getField("rangeSet"); } - public WCS100SupportedFormats getSupportedFormats() - { + public WCS100SupportedFormats getSupportedFormats() { return (WCS100SupportedFormats) this.getField("supportedFormats"); } - public WCS100SupportedCRSs getSupportedCRSs() - { + public WCS100SupportedCRSs getSupportedCRSs() { return (WCS100SupportedCRSs) this.getField("supportedCRSs"); } - public WCS100SupportedInterpolations getSupportedInterpolations() - { + public WCS100SupportedInterpolations getSupportedInterpolations() { return (WCS100SupportedInterpolations) this.getField("supportedInterpolations"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100CoverageOfferingBrief.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100CoverageOfferingBrief.java index e676e6442e..b5561e5bcf 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100CoverageOfferingBrief.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100CoverageOfferingBrief.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.*; @@ -14,40 +13,33 @@ * @author tag * @version $Id: WCS100CoverageOfferingBrief.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100CoverageOfferingBrief extends AbstractXMLEventParser -{ - public WCS100CoverageOfferingBrief(String namespaceURI) - { +public class WCS100CoverageOfferingBrief extends AbstractXMLEventParser { + + public WCS100CoverageOfferingBrief(String namespaceURI) { super(namespaceURI); } - public String getDescription() - { + public String getDescription() { return (String) this.getField("description"); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public String getLabel() - { + public String getLabel() { return (String) this.getField("label"); } - public AttributesOnlyXMLEventParser getMetadataLink() - { + public AttributesOnlyXMLEventParser getMetadataLink() { return (AttributesOnlyXMLEventParser) this.getField("metadataLink"); } - public List getKeywords() - { + public List getKeywords() { return ((StringListXMLEventParser) this.getField("keywords")).getStrings(); } - public WCS100LonLatEnvelope getLonLatEnvelope() - { + public WCS100LonLatEnvelope getLonLatEnvelope() { return (WCS100LonLatEnvelope) this.getField("lonLatEnvelope"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DCPType.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DCPType.java index 7443a2a00b..300b14a2bd 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DCPType.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DCPType.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,15 +11,13 @@ * @author tag * @version $Id$ */ -public class WCS100DCPType extends AbstractXMLEventParser -{ - public WCS100DCPType(String namespaceURI) - { +public class WCS100DCPType extends AbstractXMLEventParser { + + public WCS100DCPType(String namespaceURI) { super(namespaceURI); } - public WCS100HTTP getHTTP() - { + public WCS100HTTP getHTTP() { return (WCS100HTTP) this.getField("HTTP"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DescribeCoverage.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DescribeCoverage.java index 70383934a7..6160fafb7e 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DescribeCoverage.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DescribeCoverage.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.ogc.OGCConstants; @@ -22,19 +21,16 @@ * @author tag * @version $Id: WCS100DescribeCoverage.java 2072 2014-06-21 21:20:25Z tgaskins $ */ -public class WCS100DescribeCoverage extends AbstractXMLEventParser -{ +public class WCS100DescribeCoverage extends AbstractXMLEventParser { + protected XMLEventReader eventReader; protected XMLEventParserContext parserContext; protected List coverageOfferings = new ArrayList(1); - public static WCS100DescribeCoverage retrieve(URI uri, final String coverageName) throws URISyntaxException - { - Request request = new Request(uri, "WCS") - { + public static WCS100DescribeCoverage retrieve(URI uri, final String coverageName) throws URISyntaxException { + Request request = new Request(uri, "WCS") { @Override - protected void initialize(String service) - { + protected void initialize(String service) { super.initialize(service); this.setParam("REQUEST", "DescribeCoverage"); this.setParam("VERSION", "1.0.0"); @@ -45,8 +41,7 @@ protected void initialize(String service) return new WCS100DescribeCoverage(request.toString()); } - public WCS100DescribeCoverage(Object docSource) - { + public WCS100DescribeCoverage(Object docSource) { super(OGCConstants.WCS_1_0_0_NAMESPACE_URI); this.eventReader = this.createReader(docSource); @@ -54,26 +49,22 @@ public WCS100DescribeCoverage(Object docSource) this.initialize(); } - protected void initialize() - { + protected void initialize() { this.parserContext = this.createParserContext(this.eventReader); } - protected XMLEventReader createReader(Object docSource) - { + protected XMLEventReader createReader(Object docSource) { return WWXML.openEventReader(docSource); } - protected XMLEventParserContext createParserContext(XMLEventReader reader) - { + protected XMLEventParserContext createParserContext(XMLEventReader reader) { this.parserContext = new BasicXMLEventParserContext(reader); this.parserContext.setDefaultNamespaceURI(this.getNamespaceURI()); return this.parserContext; } - public XMLEventParserContext getParserContext() - { + public XMLEventParserContext getParserContext() { return this.parserContext; } @@ -82,8 +73,7 @@ public XMLEventParserContext getParserContext() * * @return the document's version number. */ - public String getVersion() - { + public String getVersion() { return (String) this.getField("version"); } @@ -92,31 +82,25 @@ public String getVersion() * * @return the document's update sequence. */ - public String getUpdateSequence() - { + public String getUpdateSequence() { return (String) this.getField("updateSequence"); } - public List getCoverageOfferings() - { + public List getCoverageOfferings() { return this.coverageOfferings; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "CoverageOffering")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "CoverageOffering")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCS100CoverageOffering) + if (o != null && o instanceof WCS100CoverageOffering) { this.coverageOfferings.add((WCS100CoverageOffering) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } @@ -127,23 +111,20 @@ protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Ob * * @param args optional arguments to pass to parsers of sub-elements. * - * @return this if parsing is successful, otherwise null. + * @return this if parsing is successful, otherwise null. * - * @throws javax.xml.stream.XMLStreamException - * if an exception occurs while attempting to read the event stream. + * @throws javax.xml.stream.XMLStreamException if an exception occurs while attempting to read the event stream. */ - public WCS100DescribeCoverage parse(Object... args) throws XMLStreamException - { + public WCS100DescribeCoverage parse(Object... args) throws XMLStreamException { XMLEventParserContext ctx = this.parserContext; QName docName = new QName(this.getNamespaceURI(), "CoverageDescription"); - for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) - { - if (event == null) + for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) { + if (event == null) { continue; + } - if (event.isStartElement() && event.asStartElement().getName().equals(docName)) - { + if (event.isStartElement() && event.asStartElement().getName().equals(docName)) { // Parse the attributes in order to get the version number. this.doParseEventAttributes(ctx, event); ctx.setDefaultNamespaceURI(this.getNamespaceURI()); @@ -160,106 +141,101 @@ public WCS100DescribeCoverage parse(Object... args) throws XMLStreamException return null; } - protected void registerParsers(XMLEventParserContext ctx) - { - ctx.addStringParsers(this.getNamespaceURI(), new String[] - { - "description", - "label", - "keyword", - "name", - "res", - "singleValue", - }); - - ctx.addStringParsers(OGCConstants.GML_NAMESPACE_URI, new String[] - { - "axisName", - "high", - "low", - "offsetVector", - "timePosition", - }); + protected void registerParsers(XMLEventParserContext ctx) { + ctx.addStringParsers(this.getNamespaceURI(), new String[]{ + "description", + "label", + "keyword", + "name", + "res", + "singleValue",}); + + ctx.addStringParsers(OGCConstants.GML_NAMESPACE_URI, new String[]{ + "axisName", + "high", + "low", + "offsetVector", + "timePosition",}); ctx.registerParser(new QName(this.getNamespaceURI(), "axisDescription"), - new WCS100AxisDescriptionHolder(this.getNamespaceURI())); + new WCS100AxisDescriptionHolder(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "AxisDescription"), - new WCS100AxisDescription(this.getNamespaceURI())); + new WCS100AxisDescription(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "CoverageOffering"), - new WCS100CoverageOffering(this.getNamespaceURI())); + new WCS100CoverageOffering(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "domainSet"), - new WCS100DomainSet(this.getNamespaceURI())); + new WCS100DomainSet(this.getNamespaceURI())); ctx.registerParser(new QName(OGCConstants.GML_NAMESPACE_URI, "Envelope"), - new GMLEnvelope(OGCConstants.GML_NAMESPACE_URI)); + new GMLEnvelope(OGCConstants.GML_NAMESPACE_URI)); ctx.registerParser(new QName(OGCConstants.GML_NAMESPACE_URI, "Grid"), - new GMLGrid(OGCConstants.GML_NAMESPACE_URI)); + new GMLGrid(OGCConstants.GML_NAMESPACE_URI)); ctx.registerParser(new QName(OGCConstants.GML_NAMESPACE_URI, "GridEnvelope"), - new GMLGridEnvelope(OGCConstants.GML_NAMESPACE_URI)); + new GMLGridEnvelope(OGCConstants.GML_NAMESPACE_URI)); ctx.registerParser(new QName(this.getNamespaceURI(), "interval"), - new WCS100Interval(this.getNamespaceURI())); + new WCS100Interval(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "keywords"), - new StringListXMLEventParser(this.getNamespaceURI(), new QName(this.getNamespaceURI(), "keyword"))); + new StringListXMLEventParser(this.getNamespaceURI(), new QName(this.getNamespaceURI(), "keyword"))); ctx.registerParser(new QName(OGCConstants.GML_NAMESPACE_URI, "limits"), - new GMLLimits(OGCConstants.GML_NAMESPACE_URI)); + new GMLLimits(OGCConstants.GML_NAMESPACE_URI)); ctx.registerParser(new QName(this.getNamespaceURI(), "lonLatEnvelope"), - new WCS100LonLatEnvelope(this.getNamespaceURI())); + new WCS100LonLatEnvelope(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "max"), - new WCS100Max(this.getNamespaceURI())); + new WCS100Max(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "metadataLink"), - new WCS100MetadataLink(this.getNamespaceURI())); + new WCS100MetadataLink(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "min"), - new WCS100Min(this.getNamespaceURI())); + new WCS100Min(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "nullValues"), - new WCS100Values(this.getNamespaceURI())); + new WCS100Values(this.getNamespaceURI())); ctx.registerParser(new QName(OGCConstants.GML_NAMESPACE_URI, "origin"), - new GMLOrigin(OGCConstants.GML_NAMESPACE_URI)); + new GMLOrigin(OGCConstants.GML_NAMESPACE_URI)); ctx.registerParser(new QName(OGCConstants.GML_NAMESPACE_URI, "pos"), - new GMLPos(OGCConstants.GML_NAMESPACE_URI)); + new GMLPos(OGCConstants.GML_NAMESPACE_URI)); ctx.registerParser(new QName(this.getNamespaceURI(), "rangeSet"), - new WCS100RangeSetHolder(this.getNamespaceURI())); + new WCS100RangeSetHolder(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "rangeSet"), - new WCS100RangeSetHolder(this.getNamespaceURI())); + new WCS100RangeSetHolder(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "RangeSet"), - new WCS100RangeSet(this.getNamespaceURI())); + new WCS100RangeSet(this.getNamespaceURI())); ctx.registerParser(new QName(OGCConstants.GML_NAMESPACE_URI, "RectifiedGrid"), - new GMLRectifiedGrid(OGCConstants.GML_NAMESPACE_URI)); + new GMLRectifiedGrid(OGCConstants.GML_NAMESPACE_URI)); ctx.registerParser(new QName(this.getNamespaceURI(), "supportedFormats"), - new WCS100SupportedFormats(this.getNamespaceURI())); + new WCS100SupportedFormats(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "supportedInterpolations"), - new WCS100SupportedInterpolations(this.getNamespaceURI())); + new WCS100SupportedInterpolations(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "singleValue"), - new WCS100SingleValue(this.getNamespaceURI())); + new WCS100SingleValue(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "spatialDomain"), - new WCS100SpatialDomain(this.getNamespaceURI())); + new WCS100SpatialDomain(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "supportedCRSs"), - new WCS100SupportedCRSs(this.getNamespaceURI())); + new WCS100SupportedCRSs(this.getNamespaceURI())); ctx.registerParser(new QName(this.getNamespaceURI(), "values"), - new WCS100Values(this.getNamespaceURI())); + new WCS100Values(this.getNamespaceURI())); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DomainSet.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DomainSet.java index eb308ac147..5872d0ac10 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DomainSet.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100DomainSet.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,15 +11,13 @@ * @author tag * @version $Id: WCS100DomainSet.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100DomainSet extends AbstractXMLEventParser -{ - public WCS100DomainSet(String namespaceURI) - { +public class WCS100DomainSet extends AbstractXMLEventParser { + + public WCS100DomainSet(String namespaceURI) { super(namespaceURI); } - public WCS100SpatialDomain getSpatialDomain() - { + public WCS100SpatialDomain getSpatialDomain() { return (WCS100SpatialDomain) this.getField("spatialDomain"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Exception.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Exception.java index 3e08251847..eefac6015f 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Exception.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Exception.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.WWUtil; @@ -17,31 +16,26 @@ * @author tag * @version $Id: WCS100Exception.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100Exception extends AbstractXMLEventParser -{ +public class WCS100Exception extends AbstractXMLEventParser { + protected List formats = new ArrayList(1); - public WCS100Exception(String namespaceURI) - { + public WCS100Exception(String namespaceURI) { super(namespaceURI); } - public List getFormats() - { + public List getFormats() { return this.formats; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Format")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Format")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.formats.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100HTTP.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100HTTP.java index 8d39f2a01d..7de2b7556c 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100HTTP.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100HTTP.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.*; @@ -16,66 +15,61 @@ * @author tag * @version $Id: WCS100HTTP.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100HTTP extends AbstractXMLEventParser -{ +public class WCS100HTTP extends AbstractXMLEventParser { + protected List gets = new ArrayList(1); protected List posts = new ArrayList(1); - public WCS100HTTP(String namespaceURI) - { + public WCS100HTTP(String namespaceURI) { super(namespaceURI); } - public List getGetAddresses() - { - if (this.gets == null) + public List getGetAddresses() { + if (this.gets == null) { return null; + } List addresses = new ArrayList(this.gets.size()); - for (AttributesOnlyXMLEventParser parser : this.gets) - { - if (parser != null) - { - AttributesOnlyXMLEventParser onlineResource = - (AttributesOnlyXMLEventParser) parser.getField("OnlineResource"); - if (onlineResource != null) + for (AttributesOnlyXMLEventParser parser : this.gets) { + if (parser != null) { + AttributesOnlyXMLEventParser onlineResource + = (AttributesOnlyXMLEventParser) parser.getField("OnlineResource"); + if (onlineResource != null) { addresses.add((String) onlineResource.getField("href")); + } } } return addresses; } - public List getPostAddresses() - { - if (this.posts == null) + public List getPostAddresses() { + if (this.posts == null) { return null; + } List addresses = new ArrayList(this.posts.size()); - for (AttributesOnlyXMLEventParser parser : this.posts) - { - if (parser != null) - { - AttributesOnlyXMLEventParser onlineResource = - (AttributesOnlyXMLEventParser) parser.getField("OnlineResource"); - if (onlineResource != null) + for (AttributesOnlyXMLEventParser parser : this.posts) { + if (parser != null) { + AttributesOnlyXMLEventParser onlineResource + = (AttributesOnlyXMLEventParser) parser.getField("OnlineResource"); + if (onlineResource != null) { addresses.add((String) onlineResource.getField("href")); + } } } return addresses; } - public String getGetAddress() - { + public String getGetAddress() { List addresses = this.getGetAddresses(); Iterator iter = addresses.iterator(); return iter.hasNext() ? iter.next() : null; } - public String getPostAddress() - { + public String getPostAddress() { List addresses = this.getPostAddresses(); Iterator iter = addresses.iterator(); @@ -83,30 +77,24 @@ public String getPostAddress() } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Get")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Get")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof AttributesOnlyXMLEventParser) + if (o != null && o instanceof AttributesOnlyXMLEventParser) { this.gets.add((AttributesOnlyXMLEventParser) o); + } } - } - else if (ctx.isStartElement(event, "Post")) - { + } else if (ctx.isStartElement(event, "Post")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof AttributesOnlyXMLEventParser) + if (o != null && o instanceof AttributesOnlyXMLEventParser) { this.posts.add((AttributesOnlyXMLEventParser) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Interval.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Interval.java index 4a11d30f1d..915d3f6292 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Interval.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Interval.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,40 +11,33 @@ * @author tag * @version $Id: WCS100Interval.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100Interval extends AbstractXMLEventParser -{ - public WCS100Interval(String namespaceURI) - { +public class WCS100Interval extends AbstractXMLEventParser { + + public WCS100Interval(String namespaceURI) { super(namespaceURI); } - public String getType() - { + public String getType() { return (String) this.getField("type"); } - public String getSemantic() - { + public String getSemantic() { return (String) this.getField("semantic"); } - public String getAtomic() - { + public String getAtomic() { return (String) this.getField("atomic"); } - public WCS100Min getMin() - { + public WCS100Min getMin() { return (WCS100Min) this.getField("min"); } - public WCS100Max getMax() - { + public WCS100Max getMax() { return (WCS100Max) this.getField("max"); } - public String getRes() - { + public String getRes() { return (String) this.getField("res"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100LonLatEnvelope.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100LonLatEnvelope.java index 83904f0b36..32c2792077 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100LonLatEnvelope.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100LonLatEnvelope.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.ogc.gml.GMLPos; @@ -18,47 +17,39 @@ * @author tag * @version $Id: WCS100LonLatEnvelope.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100LonLatEnvelope extends AbstractXMLEventParser -{ +public class WCS100LonLatEnvelope extends AbstractXMLEventParser { + List positions = new ArrayList(2); List timePositions = new ArrayList(2); - public WCS100LonLatEnvelope(String namespaceURI) - { + public WCS100LonLatEnvelope(String namespaceURI) { super(namespaceURI); } - public String getSRSName() - { + public String getSRSName() { return (String) this.getField("srsName"); } - public List getPositions() - { + public List getPositions() { return this.positions; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "pos")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "pos")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof GMLPos) + if (o != null && o instanceof GMLPos) { this.positions.add((GMLPos) o); + } } - } - else if (ctx.isStartElement(event, "timePosition")) - { + } else if (ctx.isStartElement(event, "timePosition")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.timePositions.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Max.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Max.java index ff21c405e7..f37548d866 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Max.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Max.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,20 +11,17 @@ * @author tag * @version $Id: WCS100Max.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100Max extends AbstractXMLEventParser -{ - public WCS100Max(String namespaceURI) - { +public class WCS100Max extends AbstractXMLEventParser { + + public WCS100Max(String namespaceURI) { super(namespaceURI); } - public String getClosure() - { + public String getClosure() { return (String) this.getField("closure"); } - public String getMax() - { + public String getMax() { return (String) this.getField("CharactersContent"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100MetadataLink.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100MetadataLink.java index f27bc26557..789d8af188 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100MetadataLink.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100MetadataLink.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,30 +11,25 @@ * @author tag * @version $Id$ */ -public class WCS100MetadataLink extends AbstractXMLEventParser -{ - public WCS100MetadataLink(String namespaceURI) - { +public class WCS100MetadataLink extends AbstractXMLEventParser { + + public WCS100MetadataLink(String namespaceURI) { super(namespaceURI); } - public String getAbout() - { + public String getAbout() { return (String) this.getField("about"); } - public String getMetadataType() - { + public String getMetadataType() { return (String) this.getField("metadataType"); } - public String getType() - { + public String getType() { return (String) this.getField("type"); } - public String getHref() - { + public String getHref() { return (String) this.getField("href"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Min.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Min.java index 25d52c6308..400bb82863 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Min.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Min.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,20 +11,17 @@ * @author tag * @version $Id: WCS100Min.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100Min extends AbstractXMLEventParser -{ - public WCS100Min(String namespaceURI) - { +public class WCS100Min extends AbstractXMLEventParser { + + public WCS100Min(String namespaceURI) { super(namespaceURI); } - public String getClosure() - { + public String getClosure() { return (String) this.getField("closure"); } - public String getMin() - { + public String getMin() { return (String) this.getField("CharactersContent"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RangeSet.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RangeSet.java index 0b168c25ba..c4de23b893 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RangeSet.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RangeSet.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.*; @@ -16,60 +15,49 @@ * @author tag * @version $Id: WCS100RangeSet.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100RangeSet extends AbstractXMLEventParser -{ +public class WCS100RangeSet extends AbstractXMLEventParser { + protected List axisDescriptions = new ArrayList(1); - public WCS100RangeSet(String namespaceURI) - { + public WCS100RangeSet(String namespaceURI) { super(namespaceURI); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public String getLabel() - { + public String getLabel() { return (String) this.getField("label"); } - public String getDescription() - { + public String getDescription() { return (String) this.getField("description"); } - public WCS100MetadataLink getMetadataLink() - { + public WCS100MetadataLink getMetadataLink() { return (WCS100MetadataLink) this.getField("metadataLink"); } - public WCS100Values getNullValues() - { + public WCS100Values getNullValues() { return (WCS100Values) this.getField("nullValues"); } - public List getAxisDescriptions() - { + public List getAxisDescriptions() { return this.axisDescriptions; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "axisDescription")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "axisDescription")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCS100AxisDescriptionHolder) + if (o != null && o instanceof WCS100AxisDescriptionHolder) { this.axisDescriptions.add((WCS100AxisDescriptionHolder) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RangeSetHolder.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RangeSetHolder.java index 383a1cdc00..86856b2e7c 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RangeSetHolder.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RangeSetHolder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,30 +11,25 @@ * @author tag * @version $Id: WCS100RangeSetHolder.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100RangeSetHolder extends AbstractXMLEventParser -{ - public WCS100RangeSetHolder(String namespaceURI) - { +public class WCS100RangeSetHolder extends AbstractXMLEventParser { + + public WCS100RangeSetHolder(String namespaceURI) { super(namespaceURI); } - public String getSemantic() - { + public String getSemantic() { return (String) this.getField("semantic"); } - public String getRefSys() - { + public String getRefSys() { return (String) this.getField("refSys"); } - public String getRefSysLabel() - { + public String getRefSysLabel() { return (String) this.getField("refSysLabel"); } - public WCS100RangeSet getRangeSet() - { + public WCS100RangeSet getRangeSet() { return (WCS100RangeSet) this.getField("RangeSet"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Request.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Request.java index 0479e286a8..accb858a5a 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Request.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Request.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.*; @@ -16,65 +15,54 @@ * @author tag * @version $Id: WCS100Request.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100Request extends AbstractXMLEventParser -{ - private static final String[] rNames = new String[] - { - "GetCapabilities", "DescribeCoverage", "GetCoverage" - }; +public class WCS100Request extends AbstractXMLEventParser { + + private static final String[] rNames = new String[]{ + "GetCapabilities", "DescribeCoverage", "GetCoverage" + }; protected List requests = new ArrayList(2); - public WCS100Request(String namespaceURI) - { + public WCS100Request(String namespaceURI) { super(namespaceURI); } - public List getRequests() - { + public List getRequests() { return this.requests; } - public WCS100RequestDescription getRequest(String requestName) - { - for (WCS100RequestDescription description : this.requests) - { - if (description.getRequestName().equalsIgnoreCase(requestName)) + public WCS100RequestDescription getRequest(String requestName) { + for (WCS100RequestDescription description : this.requests) { + if (description.getRequestName().equalsIgnoreCase(requestName)) { return description; + } } return null; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { + throws XMLStreamException { String requestName = this.isRequestName(ctx, event); - if (requestName != null) - { + if (requestName != null) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCS100RequestDescription) - { + if (o != null && o instanceof WCS100RequestDescription) { ((WCS100RequestDescription) o).setRequestName(requestName); this.requests.add((WCS100RequestDescription) o); } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } - protected String isRequestName(XMLEventParserContext ctx, XMLEvent event) - { - for (String requestName : rNames) - { - if (ctx.isStartElement(event, requestName)) + protected String isRequestName(XMLEventParserContext ctx, XMLEvent event) { + for (String requestName : rNames) { + if (ctx.isStartElement(event, requestName)) { return requestName; + } } return null; diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RequestDescription.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RequestDescription.java index 1996418559..2a41b8bd7a 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RequestDescription.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100RequestDescription.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.*; @@ -16,46 +15,38 @@ * @author tag * @version $Id: WCS100RequestDescription.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100RequestDescription extends AbstractXMLEventParser -{ +public class WCS100RequestDescription extends AbstractXMLEventParser { + protected String requestName; protected List dcpTypes = new ArrayList(2); - public WCS100RequestDescription(String namespaceURI) - { + public WCS100RequestDescription(String namespaceURI) { super(namespaceURI); } - public void setRequestName(String requestName) - { + public void setRequestName(String requestName) { this.requestName = requestName; } - public String getRequestName() - { + public String getRequestName() { return this.requestName; } - public List getDCPTypes() - { + public List getDCPTypes() { return this.dcpTypes; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "DCPType")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "DCPType")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCS100DCPType) + if (o != null && o instanceof WCS100DCPType) { this.dcpTypes.add((WCS100DCPType) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100ResponsibleParty.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100ResponsibleParty.java index 4fb7c379dc..7741ec867c 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100ResponsibleParty.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100ResponsibleParty.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.ogc.ows.OWSContactInfo; @@ -13,30 +12,25 @@ * @author tag * @version $Id: WCS100ResponsibleParty.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100ResponsibleParty extends AbstractXMLEventParser -{ - public WCS100ResponsibleParty(String namespaceURI) - { +public class WCS100ResponsibleParty extends AbstractXMLEventParser { + + public WCS100ResponsibleParty(String namespaceURI) { super(namespaceURI); } - public String getIndividualName() - { + public String getIndividualName() { return (String) this.getField("individualName"); } - public String getOrganisationName() - { + public String getOrganisationName() { return (String) this.getField("organisationName"); } - public String getPositionName() - { + public String getPositionName() { return (String) this.getField("positionName"); } - public OWSContactInfo getContactInfo() - { + public OWSContactInfo getContactInfo() { return (OWSContactInfo) this.getField("contactInfo"); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Service.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Service.java index 3ac31f4278..8e110e9d76 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Service.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Service.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.WWUtil; @@ -17,66 +16,54 @@ * @author tag * @version $Id: WCS100Service.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100Service extends AbstractXMLEventParser -{ +public class WCS100Service extends AbstractXMLEventParser { + protected List accessConstraints = new ArrayList(1); - public WCS100Service(String namespaceURI) - { + public WCS100Service(String namespaceURI) { super(namespaceURI); } - public String getDescription() - { + public String getDescription() { return (String) this.getField("description"); } - public String getName() - { + public String getName() { return (String) this.getField("name"); } - public String getLabel() - { + public String getLabel() { return (String) this.getField("label"); } - public List getAccessConstraints() - { + public List getAccessConstraints() { return this.accessConstraints; } - public String getFees() - { + public String getFees() { return (String) this.getField("fees"); } - public WCS100MetadataLink getMetadataLink() - { + public WCS100MetadataLink getMetadataLink() { return (WCS100MetadataLink) this.getField("metadataLink"); } - public List getKeywords() - { + public List getKeywords() { return ((StringListXMLEventParser) this.getField("keywords")).getStrings(); } - public WCS100ResponsibleParty getResponsibleParty() - { + public WCS100ResponsibleParty getResponsibleParty() { return (WCS100ResponsibleParty) this.getField("responsibleParty"); } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "accessConstraints")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "accessConstraints")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.accessConstraints.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SingleValue.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SingleValue.java index d48364edfe..0af4ed0de5 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SingleValue.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SingleValue.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.Logging; @@ -15,39 +14,32 @@ * @author tag * @version $Id: WCS100SingleValue.java 2066 2014-06-20 20:41:46Z tgaskins $ */ -public class WCS100SingleValue extends AbstractXMLEventParser -{ - public WCS100SingleValue(String namespaceURI) - { +public class WCS100SingleValue extends AbstractXMLEventParser { + + public WCS100SingleValue(String namespaceURI) { super(namespaceURI); } - public String getType() - { + public String getType() { return (String) this.getField("type"); } - public String getSemantic() - { + public String getSemantic() { return (String) this.getField("semantic"); } - public String getSingleValueString() - { + public String getSingleValueString() { return (String) this.getField("CharactersContent"); } - public Double getSingleValue() - { - if (this.getSingleValueString() == null) + public Double getSingleValue() { + if (this.getSingleValueString() == null) { return null; + } - try - { + try { return Double.parseDouble(this.getSingleValueString()); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.NumberFormatException"); Logging.logger().log(Level.WARNING, message, e); return null; diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SpatialDomain.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SpatialDomain.java index 7941e6b820..170cbaf6cf 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SpatialDomain.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SpatialDomain.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.ogc.gml.*; @@ -17,67 +16,55 @@ * @author tag * @version $Id: WCS100SpatialDomain.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100SpatialDomain extends AbstractXMLEventParser -{ +public class WCS100SpatialDomain extends AbstractXMLEventParser { + protected List envelopes = new ArrayList(1); protected List rectifiedGrids = new ArrayList(1); protected List grids = new ArrayList(1); - public WCS100SpatialDomain(String namespaceURI) - { + public WCS100SpatialDomain(String namespaceURI) { super(namespaceURI); } - public List getEnvelopes() - { + public List getEnvelopes() { return this.envelopes; } - public List getRectifiedGrids() - { + public List getRectifiedGrids() { return this.rectifiedGrids; } - public List getGrids() - { + public List getGrids() { return this.grids; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "Envelope") || ctx.isStartElement(event, "EnvelopeWithTimePeriod")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "Envelope") || ctx.isStartElement(event, "EnvelopeWithTimePeriod")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof GMLEnvelope) + if (o != null && o instanceof GMLEnvelope) { this.envelopes.add((GMLEnvelope) o); + } } - } - else if (ctx.isStartElement(event, "RectifiedGrid")) - { + } else if (ctx.isStartElement(event, "RectifiedGrid")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof GMLRectifiedGrid) + if (o != null && o instanceof GMLRectifiedGrid) { this.rectifiedGrids.add((GMLRectifiedGrid) o); + } } - } - else if (ctx.isStartElement(event, "Grid")) - { + } else if (ctx.isStartElement(event, "Grid")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof GMLGrid) + if (o != null && o instanceof GMLGrid) { this.grids.add((GMLGrid) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedCRSs.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedCRSs.java index 7774a7a796..2c85bcf86e 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedCRSs.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedCRSs.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.WWUtil; @@ -17,67 +16,56 @@ * @author tag * @version $Id: WCS100SupportedCRSs.java 2062 2014-06-19 20:10:41Z tgaskins $ */ -public class WCS100SupportedCRSs extends AbstractXMLEventParser -{ +public class WCS100SupportedCRSs extends AbstractXMLEventParser { + protected List requestResponseCRSs = new ArrayList(1); protected List requestCRSs = new ArrayList(1); protected List responseCRSs = new ArrayList(1); protected List nativeCRSs = new ArrayList(1); - public WCS100SupportedCRSs(String namespaceURI) - { + public WCS100SupportedCRSs(String namespaceURI) { super(namespaceURI); } - public List getRequestResponseCRSs() - { + public List getRequestResponseCRSs() { return requestResponseCRSs; } - public List getRequestCRSs() - { + public List getRequestCRSs() { return requestCRSs; } - public List getResponseCRSs() - { + public List getResponseCRSs() { return responseCRSs; } - public List getNativeCRSs() - { + public List getNativeCRSs() { return nativeCRSs; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "requestResponseCRSs")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "requestResponseCRSs")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.requestResponseCRSs.add(s); - } - else if (ctx.isStartElement(event, "requestCRSs")) - { + } + } else if (ctx.isStartElement(event, "requestCRSs")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.requestCRSs.add(s); - } - else if (ctx.isStartElement(event, "responseCRSs")) - { + } + } else if (ctx.isStartElement(event, "responseCRSs")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.responseCRSs.add(s); - } - else if (ctx.isStartElement(event, "nativeCRSs")) - { + } + } else if (ctx.isStartElement(event, "nativeCRSs")) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.nativeCRSs.add(s); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedFormats.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedFormats.java index 722aa61b33..d4b7085398 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedFormats.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedFormats.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.StringListXMLEventParser; @@ -15,20 +14,17 @@ * @author tag * @version $Id: WCS100SupportedFormats.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100SupportedFormats extends StringListXMLEventParser -{ - public WCS100SupportedFormats(String namespaceURI) - { +public class WCS100SupportedFormats extends StringListXMLEventParser { + + public WCS100SupportedFormats(String namespaceURI) { super(namespaceURI, new QName(namespaceURI, "formats")); } - public String getNativeFormat() - { + public String getNativeFormat() { return (String) this.getField("nativeFormat"); } - List getSupportedFormats() - { + List getSupportedFormats() { return this.getStrings(); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedInterpolations.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedInterpolations.java index ecdb47e597..9f1ce3fa0d 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedInterpolations.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100SupportedInterpolations.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.StringListXMLEventParser; @@ -15,20 +14,17 @@ * @author tag * @version $Id: WCS100SupportedInterpolations.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100SupportedInterpolations extends StringListXMLEventParser -{ - public WCS100SupportedInterpolations(String namespaceURI) - { +public class WCS100SupportedInterpolations extends StringListXMLEventParser { + + public WCS100SupportedInterpolations(String namespaceURI) { super(namespaceURI, new QName(namespaceURI, "interpolationMethod")); } - public String getDefault() - { + public String getDefault() { return (String) this.getField("default"); } - List getSupportedInterpolations() - { + List getSupportedInterpolations() { return this.getStrings(); } } diff --git a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Values.java b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Values.java index fd12128e9f..44e7e21555 100644 --- a/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Values.java +++ b/src/gov/nasa/worldwind/ogc/wcs/wcs100/WCS100Values.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wcs.wcs100; import gov.nasa.worldwind.util.xml.*; @@ -16,66 +15,54 @@ * @author tag * @version $Id: WCS100Values.java 2061 2014-06-19 19:59:40Z tgaskins $ */ -public class WCS100Values extends AbstractXMLEventParser -{ +public class WCS100Values extends AbstractXMLEventParser { + protected List singleValues = new ArrayList(1); private List intervals = new ArrayList(1); - public WCS100Values(String namespaceURI) - { + public WCS100Values(String namespaceURI) { super(namespaceURI); } - public List getSingleValues() - { + public List getSingleValues() { return this.singleValues; } - public String getDefault() - { + public String getDefault() { return (String) this.getField("default"); } - public String getType() - { + public String getType() { return (String) this.getField("type"); } - public String getSemantic() - { + public String getSemantic() { return (String) this.getField("semantic"); } - public List getIntervals() - { + public List getIntervals() { return this.intervals; } protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, "singleValue")) - { + throws XMLStreamException { + if (ctx.isStartElement(event, "singleValue")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCS100SingleValue) + if (o != null && o instanceof WCS100SingleValue) { this.singleValues.add((WCS100SingleValue) o); + } } - } - else if (ctx.isStartElement(event, "interval")) - { + } else if (ctx.isStartElement(event, "interval")) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WCS100Interval) + if (o != null && o instanceof WCS100Interval) { this.intervals.add((WCS100Interval) o); + } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSAuthorityURL.java b/src/gov/nasa/worldwind/ogc/wms/WMSAuthorityURL.java index c5d2457e12..528775b434 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSAuthorityURL.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSAuthorityURL.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -17,37 +16,34 @@ * @author tag * @version $Id: WMSAuthorityURL.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSAuthorityURL extends WMSLayerInfoURL -{ +public class WMSAuthorityURL extends WMSLayerInfoURL { + protected String authority; - public WMSAuthorityURL(String namespaceURI) - { + public WMSAuthorityURL(String namespaceURI) { super(namespaceURI); } @SuppressWarnings({"UnusedDeclaration"}) - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("authority") && attr.getValue() != null) + if (attr.getName().getLocalPart().equals("authority") && attr.getValue() != null) { this.setAuthority(attr.getValue()); + } } } - public String getAuthority() - { + public String getAuthority() { return authority; } - protected void setAuthority(String authority) - { + protected void setAuthority(String authority) { this.authority = authority; } } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSCapabilities.java b/src/gov/nasa/worldwind/ogc/wms/WMSCapabilities.java index a7f4c734f8..e573c40fad 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSCapabilities.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSCapabilities.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.ogc.*; @@ -22,8 +21,8 @@ * @author tag * @version $Id: WMSCapabilities.java 2072 2014-06-21 21:20:25Z tgaskins $ */ -public class WMSCapabilities extends OGCCapabilities -{ +public class WMSCapabilities extends OGCCapabilities { + protected static final QName ROOT_ELEMENT_NAME_1_1_1 = new QName("WMT_MS_Capabilities"); protected static final QName ROOT_ELEMENT_NAME_1_3_0 = new QName("WMS_Capabilities"); @@ -33,26 +32,19 @@ public class WMSCapabilities extends OGCCapabilities * @param uri The URI of the server. * * @return The WMS capabilities document for the specified server. - * @throws java.lang.Exception if a general error occurs. + * @throws java.lang.Exception if a general error occurs. * * @throws IllegalArgumentException if the specified URI is invalid. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if an error occurs retrieving the document. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if an error occurs retrieving the document. */ - public static WMSCapabilities retrieve(URI uri) throws Exception - { - try - { + public static WMSCapabilities retrieve(URI uri) throws Exception { + try { CapabilitiesRequest request = new CapabilitiesRequest(uri); return new WMSCapabilities(request); - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { e.printStackTrace(); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { e.printStackTrace(); } @@ -67,51 +59,45 @@ public static WMSCapabilities retrieve(URI uri) throws Exception * * @throws IllegalArgumentException if the document source is null. */ - public WMSCapabilities(Object docSource) - { + public WMSCapabilities(Object docSource) { super(OGCConstants.WMS_NAMESPACE_URI, docSource); this.initialize(); } - public WMSCapabilities(CapabilitiesRequest docSource) throws URISyntaxException, MalformedURLException - { + public WMSCapabilities(CapabilitiesRequest docSource) throws URISyntaxException, MalformedURLException { super(OGCConstants.WMS_NAMESPACE_URI, docSource.getUri().toURL()); this.initialize(); } - private void initialize() - { + private void initialize() { this.getParserContext().registerParser(new QName(this.getDefaultNamespaceURI(), "Service"), - new WMSServiceInformation(this.getNamespaceURI())); + new WMSServiceInformation(this.getNamespaceURI())); this.getParserContext().registerParser(new QName("Capability"), - new WMSCapabilityInformation(this.getNamespaceURI())); + new WMSCapabilityInformation(this.getNamespaceURI())); } @Override - public String getDefaultNamespaceURI() - { + public String getDefaultNamespaceURI() { return OGCConstants.WMS_NAMESPACE_URI; } - public boolean isRootElementName(QName candidate) - { + public boolean isRootElementName(QName candidate) { return this.getParserContext().isSameName(candidate, ROOT_ELEMENT_NAME_1_1_1) - || this.getParserContext().isSameName(candidate, ROOT_ELEMENT_NAME_1_3_0); + || this.getParserContext().isSameName(candidate, ROOT_ELEMENT_NAME_1_3_0); } - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { - if (ctx.isStartElement(event, CAPABILITY)) + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { + if (ctx.isStartElement(event, CAPABILITY)) { return ctx.allocate(event, new WMSCapabilityInformation(this.getNamespaceURI())); - else + } else { return super.allocate(ctx, event); + } } @Override - public WMSCapabilities parse(Object... args) throws XMLStreamException - { + public WMSCapabilities parse(Object... args) throws XMLStreamException { return (WMSCapabilities) super.parse(args); } @@ -120,57 +106,52 @@ public WMSCapabilities parse(Object... args) throws XMLStreamException * * @return an unordered list of the document's named layers. */ - public List getNamedLayers() - { - if (this.getCapabilityInformation() == null || this.getCapabilityInformation().getLayerCapabilities() == null) + public List getNamedLayers() { + if (this.getCapabilityInformation() == null || this.getCapabilityInformation().getLayerCapabilities() == null) { return null; + } List namedLayers = new ArrayList(); - for (WMSLayerCapabilities layer : this.getCapabilityInformation().getLayerCapabilities()) - { + for (WMSLayerCapabilities layer : this.getCapabilityInformation().getLayerCapabilities()) { namedLayers.addAll(layer.getNamedLayers()); } return namedLayers; } - public WMSLayerCapabilities getLayerByName(String name) - { - if (WWUtil.isEmpty(name)) + public WMSLayerCapabilities getLayerByName(String name) { + if (WWUtil.isEmpty(name)) { return null; + } List namedLayers = this.getNamedLayers(); - for (WMSLayerCapabilities layer : namedLayers) - { - if (layer.getName().equals(name)) + for (WMSLayerCapabilities layer : namedLayers) { + if (layer.getName().equals(name)) { return layer; + } } return null; } - public WMSCapabilityInformation getCapabilityInformation() - { + public WMSCapabilityInformation getCapabilityInformation() { return (WMSCapabilityInformation) super.getCapabilityInformation(); } - public Set getImageFormats() - { + public Set getImageFormats() { Set requestDescriptions = this.getCapabilityInformation().getRequestDescriptions(); - for (OGCRequestDescription rd : requestDescriptions) - { - if (rd.getRequestName().equals("GetMap")) + for (OGCRequestDescription rd : requestDescriptions) { + if (rd.getRequestName().equals("GetMap")) { return rd.getFormats(); + } } return null; } - public Long getLayerLatestLastUpdateTime(String[] layerNames) - { - if (layerNames == null) - { + public Long getLayerLatestLastUpdateTime(String[] layerNames) { + if (layerNames == null) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -178,25 +159,22 @@ public Long getLayerLatestLastUpdateTime(String[] layerNames) String lastUpdate = null; - for (String name : layerNames) - { + for (String name : layerNames) { WMSLayerCapabilities layer = this.getLayerByName(name); - if (layer == null) + if (layer == null) { continue; + } String update = this.getLayerLastUpdate(layer); - if (update != null && update.length() > 0 && (lastUpdate == null || update.compareTo(lastUpdate) > 0)) + if (update != null && update.length() > 0 && (lastUpdate == null || update.compareTo(lastUpdate) > 0)) { lastUpdate = update; + } } - if (lastUpdate != null) - { - try - { + if (lastUpdate != null) { + try { return Long.parseLong(lastUpdate); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", lastUpdate); Logging.logger().warning(message); } @@ -213,19 +191,17 @@ public Long getLayerLatestLastUpdateTime(String[] layerNames) * * @return A string representation of the epoch time for the last update string, if any, otherwise null. */ - protected String getLayerLastUpdate(WMSLayerCapabilities layerCaps) - { + protected String getLayerLastUpdate(WMSLayerCapabilities layerCaps) { // See if there's an explicit element. This is what the original WW servers contained in their caps docs. String update = layerCaps.getLastUpdate(); - if (update != null) + if (update != null) { return update; + } // See if there's a last-update keyword. This is the new mechanism for WW servers passing a last-update. Set keywords = layerCaps.getKeywords(); - for (String keyword : keywords) - { - if (keyword.startsWith("LastUpdate=")) - { + for (String keyword : keywords) { + if (keyword.startsWith("LastUpdate=")) { return parseLastUpdate(keyword); } } @@ -236,39 +212,36 @@ protected String getLayerLastUpdate(WMSLayerCapabilities layerCaps) /** * Parse a LastUpdate string. * - * @param lastUpdateString The string containing the LastUpdate string in the format "LastUpdate=yyyy-MM-dd'T'HH:mm:ssZ" + * @param lastUpdateString The string containing the LastUpdate string in the format + * "LastUpdate=yyyy-MM-dd'T'HH:mm:ssZ" * * @return A string representation of the epoch time for the last update string, of null if the string can't be - * parsed as a date. + * parsed as a date. */ - protected String parseLastUpdate(String lastUpdateString) - { + protected String parseLastUpdate(String lastUpdateString) { String[] splitKeyword = lastUpdateString.split("="); - if (splitKeyword.length != 2) + if (splitKeyword.length != 2) { return null; + } String dateString = splitKeyword[1]; - if (dateString == null || dateString.length() == 0) + if (dateString == null || dateString.length() == 0) { return null; + } - try - { + try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); // ISO 8601:2000 format dateString = dateString.replaceAll("Z", "-0000"); // replace the UTC designator return Long.toString(dateFormat.parse(dateString).getTime()); - } - catch (ParseException e) - { + } catch (ParseException e) { String message = Logging.getMessage("WMS.LastUpdateFormatUnrecognized", dateString); Logging.logger().info(message); return null; } } - public Double[] getLayerExtremeElevations(String[] layerNames) - { - if (layerNames == null) - { + public Double[] getLayerExtremeElevations(String[] layerNames) { + if (layerNames == null) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -277,29 +250,32 @@ public Double[] getLayerExtremeElevations(String[] layerNames) Double extremeMin = null; Double extremeMax = null; - for (String name : layerNames) - { + for (String name : layerNames) { WMSLayerCapabilities layer = this.getLayerByName(name); - if (layer == null) + if (layer == null) { continue; + } Double min = layer.getExtremeElevationMin(); - if (min != null && (extremeMin == null || min.compareTo(min) > 0)) + if (min != null && (extremeMin == null || min.compareTo(min) > 0)) { extremeMin = min; + } Double max = layer.getExtremeElevationMax(); - if (max != null && (extremeMax == null || max.compareTo(max) > 0)) + if (max != null && (extremeMax == null || max.compareTo(max) > 0)) { extremeMax = max; + } } - if (extremeMin != null || extremeMax != null) - { - Double[] extremes = new Double[] {null, null}; + if (extremeMin != null || extremeMax != null) { + Double[] extremes = new Double[]{null, null}; - if (extremeMin != null) + if (extremeMin != null) { extremes[0] = extremeMin; - if (extremeMax != null) + } + if (extremeMax != null) { extremes[1] = extremeMax; + } return extremes; } @@ -307,22 +283,19 @@ public Double[] getLayerExtremeElevations(String[] layerNames) return null; } - public OGCRequestDescription getRequestDescription(String requestName) - { - for (OGCRequestDescription rd : this.getCapabilityInformation().getRequestDescriptions()) - { - if (rd.getRequestName().equalsIgnoreCase(requestName)) + public OGCRequestDescription getRequestDescription(String requestName) { + for (OGCRequestDescription rd : this.getCapabilityInformation().getRequestDescriptions()) { + if (rd.getRequestName().equalsIgnoreCase(requestName)) { return rd; + } } return null; } - public String getRequestURL(String requestName, String protocol, String requestMethod) - { + public String getRequestURL(String requestName, String protocol, String requestMethod) { OGCRequestDescription rd = this.getRequestDescription(requestName); - if (rd != null) - { + if (rd != null) { OGCOnlineResource ol = rd.getOnlineResouce(protocol, requestMethod); return ol != null ? ol.getHref() : null; } @@ -335,34 +308,31 @@ public String getRequestURL(String requestName, String protocol, String requestM * system. If any of the named layers are not in this capabilities document, false is returned. * * @param layerNames The names of the layers to check. - * @param coordSys The coordinate system to search for, e.g., "EPSG:4326". + * @param coordSys The coordinate system to search for, e.g., "EPSG:4326". * * @return true if all the layers support the specified coordinate system, otherwise false. * * @throws IllegalArgumentException if the layer names array is null or empty or the specified coordinate system is - * null or the empty string. + * null or the empty string. */ - public boolean layerHasCoordinateSystem(String[] layerNames, String coordSys) - { - if (layerNames == null || layerNames.length == 0) - { + public boolean layerHasCoordinateSystem(String[] layerNames, String coordSys) { + if (layerNames == null || layerNames.length == 0) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(coordSys)) - { + if (WWUtil.isEmpty(coordSys)) { String message = Logging.getMessage("nullValue.WMSCoordSys"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (String name : layerNames) - { + for (String name : layerNames) { WMSLayerCapabilities layerCaps = this.getLayerByName(name); - if (layerCaps == null || !layerCaps.hasCoordinateSystem(coordSys)) + if (layerCaps == null || !layerCaps.hasCoordinateSystem(coordSys)) { return false; + } } return true; @@ -375,8 +345,7 @@ public String toString() // TODO: Complete this method sb.append("LAYERS\n"); - for (WMSLayerCapabilities layerCaps : this.getNamedLayers()) - { + for (WMSLayerCapabilities layerCaps : this.getNamedLayers()) { sb.append(layerCaps.toString()).append("\n"); } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSCapabilityInformation.java b/src/gov/nasa/worldwind/ogc/wms/WMSCapabilityInformation.java index 373531aeb1..e387490687 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSCapabilityInformation.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSCapabilityInformation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.ogc.*; @@ -20,32 +19,28 @@ * @author tag * @version $Id: WMSCapabilityInformation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSCapabilityInformation extends OGCCapabilityInformation -{ - private static final String[] rNames = new String[] - { - "GetCapabilities", "GetMap", "GetFeatureInfo", "DescribeLayer", "GetLegendGraphic" - }; +public class WMSCapabilityInformation extends OGCCapabilityInformation { + + private static final String[] rNames = new String[]{ + "GetCapabilities", "GetMap", "GetFeatureInfo", "DescribeLayer", "GetLegendGraphic" + }; protected QName LAYER; protected List requestNames; protected List layerCapabilities; - public WMSCapabilityInformation(String namespaceURI) - { + public WMSCapabilityInformation(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { LAYER = new QName(this.getNamespaceURI(), "Layer"); this.requestNames = new ArrayList(rNames.length); - for (String name : rNames) - { + for (String name : rNames) { this.requestNames.add(new QName(this.getNamespaceURI(), name)); } @@ -53,67 +48,57 @@ private void initialize() } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { - if (ctx.isStartElement(event, LAYER)) + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { + if (ctx.isStartElement(event, LAYER)) { return ctx.allocate(event, new WMSLayerCapabilities(this.getNamespaceURI())); - else + } else { return super.allocate(ctx, event); + } } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, LAYER)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, LAYER)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerCapabilities) - { + if (o != null && o instanceof WMSLayerCapabilities) { WMSLayerCapabilities caps = (WMSLayerCapabilities) o; caps.setEnclosingCapabilityInformation(this); caps.resolveAttributes(null); this.getLayerCapabilities().add(caps); } } - } - else - { + } else { super.doParseEventContent(ctx, event, args); } } - protected boolean isRequestName(XMLEventParserContext ctx, QName name) - { - for (QName requestName : this.requestNames) - { - if (ctx.isSameName(requestName, name)) + protected boolean isRequestName(XMLEventParserContext ctx, QName name) { + for (QName requestName : this.requestNames) { + if (ctx.isSameName(requestName, name)) { return true; + } } return false; } - public List getLayerCapabilities() - { + public List getLayerCapabilities() { return layerCapabilities; } - protected void setLayerCapabilities(List layerCapabilities) - { + protected void setLayerCapabilities(List layerCapabilities) { this.layerCapabilities = layerCapabilities; } - public Set getImageFormats() - { + public Set getImageFormats() { Set requestDescriptions = this.getRequestDescriptions(); - for (OGCRequestDescription rd : requestDescriptions) - { - if (rd.getRequestName().equals("GetMap")) + for (OGCRequestDescription rd : requestDescriptions) { + if (rd.getRequestName().equals("GetMap")) { return rd.getFormats(); + } } return null; diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSLayerAttribution.java b/src/gov/nasa/worldwind/ogc/wms/WMSLayerAttribution.java index 405abe9a5f..fc0630ee61 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSLayerAttribution.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSLayerAttribution.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.ogc.OGCOnlineResource; @@ -19,8 +18,8 @@ * @author tag * @version $Id: WMSLayerAttribution.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSLayerAttribution extends AbstractXMLEventParser -{ +public class WMSLayerAttribution extends AbstractXMLEventParser { + protected QName TITLE; protected QName ONLINE_RESOURCE; protected QName LOGO_URL; @@ -29,90 +28,76 @@ public class WMSLayerAttribution extends AbstractXMLEventParser protected OGCOnlineResource onlineResource; protected WMSLogoURL logoURL; - public WMSLayerAttribution(String namespaceURI) - { + public WMSLayerAttribution(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { TITLE = new QName(this.getNamespaceURI(), "Title"); ONLINE_RESOURCE = new QName(this.getNamespaceURI(), "OnlineResource"); LOGO_URL = new QName(this.getNamespaceURI(), "LogoURL"); } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; - if (ctx.isStartElement(event, ONLINE_RESOURCE)) + if (ctx.isStartElement(event, ONLINE_RESOURCE)) { defaultParser = new OGCOnlineResource(this.getNamespaceURI()); - else if (ctx.isStartElement(event, LOGO_URL)) + } else if (ctx.isStartElement(event, LOGO_URL)) { defaultParser = new WMSLayerInfoURL(this.getNamespaceURI()); + } return ctx.allocate(event, defaultParser); } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, TITLE)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, TITLE)) { this.setTitle(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, ONLINE_RESOURCE)) - { + } else if (ctx.isStartElement(event, ONLINE_RESOURCE)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCOnlineResource) + if (o != null && o instanceof OGCOnlineResource) { this.setOnlineResource((OGCOnlineResource) o); + } } - } - else if (ctx.isStartElement(event, LOGO_URL)) - { + } else if (ctx.isStartElement(event, LOGO_URL)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLogoURL) + if (o != null && o instanceof WMSLogoURL) { this.setLogoURL((WMSLogoURL) o); + } } } } - public String getTitle() - { + public String getTitle() { return title; } - protected void setTitle(String title) - { + protected void setTitle(String title) { this.title = title; } - public OGCOnlineResource getOnlineResource() - { + public OGCOnlineResource getOnlineResource() { return onlineResource; } - protected void setOnlineResource(OGCOnlineResource onlineResource) - { + protected void setOnlineResource(OGCOnlineResource onlineResource) { this.onlineResource = onlineResource; } - public WMSLogoURL getLogoURL() - { + public WMSLogoURL getLogoURL() { return logoURL; } - protected void setLogoURL(WMSLogoURL logoURL) - { + protected void setLogoURL(WMSLogoURL logoURL) { this.logoURL = logoURL; } } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSLayerCapabilities.java b/src/gov/nasa/worldwind/ogc/wms/WMSLayerCapabilities.java index 9fcaaf0681..e40dfe29b9 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSLayerCapabilities.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSLayerCapabilities.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.geom.Sector; @@ -22,8 +21,8 @@ * @author tag * @version $Id: WMSLayerCapabilities.java 1931 2014-04-14 21:31:43Z tgaskins $ */ -public class WMSLayerCapabilities extends AbstractXMLEventParser -{ +public class WMSLayerCapabilities extends AbstractXMLEventParser { + protected QName ABSTRACT; protected QName ATTRIBUTION; protected QName AUTHORITY_URL; @@ -84,15 +83,13 @@ public class WMSLayerCapabilities extends AbstractXMLEventParser protected WMSLayerCapabilities parent; protected WMSCapabilityInformation enclosingCapabilityInformation; - public WMSLayerCapabilities(String namespaceURI) - { + public WMSLayerCapabilities(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { ABSTRACT = new QName(this.getNamespaceURI(), "Abstract"); ATTRIBUTION = new QName(this.getNamespaceURI(), "Attribution"); AUTHORITY_URL = new QName(this.getNamespaceURI(), "AuthorityURL"); @@ -121,103 +118,114 @@ private void initialize() } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; XMLEventParser parser = super.allocate(ctx, event); - if (parser != null) + if (parser != null) { return parser; + } - if (ctx.isStartElement(event, LAYER)) + if (ctx.isStartElement(event, LAYER)) { defaultParser = new WMSLayerCapabilities(this.getNamespaceURI()); - else if (ctx.isStartElement(event, STYLE)) + } else if (ctx.isStartElement(event, STYLE)) { defaultParser = new WMSLayerStyle(this.getNamespaceURI()); - else if (ctx.isStartElement(event, KEYWORD_LIST)) + } else if (ctx.isStartElement(event, KEYWORD_LIST)) { defaultParser = new StringSetXMLEventParser(this.getNamespaceURI(), KEYWORD); - else if (ctx.isStartElement(event, BOUNDING_BOX)) + } else if (ctx.isStartElement(event, BOUNDING_BOX)) { defaultParser = new OGCBoundingBox(this.getNamespaceURI()); - else if (ctx.isStartElement(event, ATTRIBUTION)) + } else if (ctx.isStartElement(event, ATTRIBUTION)) { defaultParser = new WMSLayerAttribution(this.getNamespaceURI()); - else if (ctx.isStartElement(event, IDENTIFIER)) + } else if (ctx.isStartElement(event, IDENTIFIER)) { defaultParser = new WMSLayerIdentifier(this.getNamespaceURI()); - else if (ctx.isStartElement(event, DIMENSION)) + } else if (ctx.isStartElement(event, DIMENSION)) { defaultParser = new WMSLayerDimension(this.getNamespaceURI()); - else if (ctx.isStartElement(event, EXTENT)) + } else if (ctx.isStartElement(event, EXTENT)) { defaultParser = new WMSLayerExtent(this.getNamespaceURI()); - else if (ctx.isStartElement(event, AUTHORITY_URL)) + } else if (ctx.isStartElement(event, AUTHORITY_URL)) { defaultParser = new WMSAuthorityURL(this.getNamespaceURI()); - else if (ctx.isStartElement(event, DATA_URL)) + } else if (ctx.isStartElement(event, DATA_URL)) { defaultParser = new WMSLayerInfoURL(this.getNamespaceURI()); - else if (ctx.isStartElement(event, FEATURE_LIST_URL)) + } else if (ctx.isStartElement(event, FEATURE_LIST_URL)) { defaultParser = new WMSLayerInfoURL(this.getNamespaceURI()); - else if (ctx.isStartElement(event, METADATA_URL)) + } else if (ctx.isStartElement(event, METADATA_URL)) { defaultParser = new WMSLayerInfoURL(this.getNamespaceURI()); + } return ctx.allocate(event, defaultParser); } - public boolean isLeaf() - { + public boolean isLeaf() { return this.getLayers().size() == 0; } - public void setEnclosingCapabilityInformation(WMSCapabilityInformation caps) - { + public void setEnclosingCapabilityInformation(WMSCapabilityInformation caps) { this.enclosingCapabilityInformation = caps; // Resolve inherited attributes for children. - for (WMSLayerCapabilities lc : this.getLayers()) - { + for (WMSLayerCapabilities lc : this.getLayers()) { lc.setEnclosingCapabilityInformation(caps); } } - public WMSCapabilityInformation getEnclosingCapabilityInformation() - { + public WMSCapabilityInformation getEnclosingCapabilityInformation() { return enclosingCapabilityInformation; } - public void resolveAttributes(WMSLayerCapabilities parentLayer) - { + public void resolveAttributes(WMSLayerCapabilities parentLayer) { this.parent = parentLayer; // The following are inherited from parent if not specified in child, otherwise they're assigned a default. - if (this.getCascaded() == null) + if (this.getCascaded() == null) { this.setCascaded(this.parent != null ? this.parent.getCascaded() : false); + } - if (this.queryable == null) + if (this.queryable == null) { this.setQueryable(this.parent != null ? this.parent.isQueryable() : false); + } - if (this.noSubsets == null) + if (this.noSubsets == null) { this.setNoSubsets(this.parent != null ? this.parent.isNoSubsets() : false); + } - if (this.opaque == null) + if (this.opaque == null) { this.setOpaque(this.parent != null ? this.parent.isOpaque() : false); + } - if (this.getFixedWidth() == null) + if (this.getFixedWidth() == null) { this.setFixedWidth(this.parent != null ? this.parent.getFixedWidth() : 0); + } - if (this.getFixedHeight() == null) + if (this.getFixedHeight() == null) { this.setFixedHeight(this.parent != null ? this.parent.getFixedHeight() : 0); + } // The rest have add or replace inheritance and no default. - if (this.parent != null) - { + if (this.parent != null) { if (this.getGeographicBoundingBox() == null) // geo box inherited from parent if not specified in child + { this.setGeographicBoundingBox(this.parent.getGeographicBoundingBox()); + } if (this.getMinScaleDenominator() == null) // scales are inherited from parent if not specified in child + { this.setMinScaleDenominator(this.parent.getMinScaleDenominator()); + } if (this.getMaxScaleDenominator() == null) // scales are inherited from parent if not specified in child + { this.setMaxScaleDenominator(this.parent.getMaxScaleDenominator()); + } if (this.getExtremeElevationMin() == null) // extremes are inherited from parent if not specified in child + { this.setExtremeElevationMin(this.parent.getExtremeElevationMin()); + } if (this.getExtremeElevationMax() == null) // extremes are inherited from parent if not specified in child + { this.setExtremeElevationMax(this.parent.getExtremeElevationMax()); + } // The following are additive. this.addStyles(this.parent.getStyles()); @@ -229,330 +237,275 @@ public void resolveAttributes(WMSLayerCapabilities parentLayer) } // Resolve inherited attributes for children. - for (WMSLayerCapabilities caps : this.getLayers()) - { + for (WMSLayerCapabilities caps : this.getLayers()) { caps.resolveAttributes(this); } } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, LAYER)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, LAYER)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerCapabilities) + if (o != null && o instanceof WMSLayerCapabilities) { this.addLayer(((WMSLayerCapabilities) o)); + } } - } - else if (ctx.isStartElement(event, TITLE)) - { + } else if (ctx.isStartElement(event, TITLE)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.setTitle(s); - } - else if (ctx.isStartElement(event, NAME)) - { + } + } else if (ctx.isStartElement(event, NAME)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.setName(s); - } - else if (ctx.isStartElement(event, STYLE)) - { + } + } else if (ctx.isStartElement(event, STYLE)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerStyle) + if (o != null && o instanceof WMSLayerStyle) { this.addStyle(((WMSLayerStyle) o)); + } } - } - else if (ctx.isStartElement(event, SRS)) - { + } else if (ctx.isStartElement(event, SRS)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.addSRS(s); - } - else if (ctx.isStartElement(event, CRS)) - { + } + } else if (ctx.isStartElement(event, CRS)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.addCRS(s); - } - else if (ctx.isStartElement(event, GEOGRAPHIC_BOUNDING_BOX)) - { + } + } else if (ctx.isStartElement(event, GEOGRAPHIC_BOUNDING_BOX)) { this.parseGeographicBoundingBox(ctx, event); - } - else if (ctx.isStartElement(event, LAT_LON_BOUNDING_BOX)) - { + } else if (ctx.isStartElement(event, LAT_LON_BOUNDING_BOX)) { this.parseGeographicBoundingBoxV111(ctx, event); - } - else if (ctx.isStartElement(event, ABSTRACT)) - { + } else if (ctx.isStartElement(event, ABSTRACT)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.setLayerAbstract(s); - } - else if (ctx.isStartElement(event, LAST_UPDATE)) - { + } + } else if (ctx.isStartElement(event, LAST_UPDATE)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.setLastUpdate(s); - } - else if (ctx.isStartElement(event, MAX_SCALE_DENOMINATOR)) - { + } + } else if (ctx.isStartElement(event, MAX_SCALE_DENOMINATOR)) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { this.setMaxScaleDenominator(d); - } - else if (ctx.isStartElement(event, MIN_SCALE_DENOMINATOR)) - { + } + } else if (ctx.isStartElement(event, MIN_SCALE_DENOMINATOR)) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { this.setMinScaleDenominator(d); - } - else if (ctx.isStartElement(event, EXTREME_ELEVATIONS)) - { + } + } else if (ctx.isStartElement(event, EXTREME_ELEVATIONS)) { this.parseExtremeElevations(ctx, event); - } - else if (ctx.isStartElement(event, SCALE_HINT)) - { + } else if (ctx.isStartElement(event, SCALE_HINT)) { this.parseScaleHint(ctx, event); - } - else if (ctx.isStartElement(event, BOUNDING_BOX)) - { + } else if (ctx.isStartElement(event, BOUNDING_BOX)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCBoundingBox) + if (o != null && o instanceof OGCBoundingBox) { this.addBoundingBox((OGCBoundingBox) o); + } } - } - else if (ctx.isStartElement(event, ATTRIBUTION)) - { + } else if (ctx.isStartElement(event, ATTRIBUTION)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerAttribution) + if (o != null && o instanceof WMSLayerAttribution) { this.addAttribution((WMSLayerAttribution) o); + } } - } - else if (ctx.isStartElement(event, KEYWORD_LIST)) - { + } else if (ctx.isStartElement(event, KEYWORD_LIST)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof StringSetXMLEventParser) + if (o != null && o instanceof StringSetXMLEventParser) { this.setKeywords(((StringSetXMLEventParser) o).getStrings()); + } } - } - else if (ctx.isStartElement(event, IDENTIFIER)) - { + } else if (ctx.isStartElement(event, IDENTIFIER)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerIdentifier) + if (o != null && o instanceof WMSLayerIdentifier) { this.addIdentifer((WMSLayerIdentifier) o); + } } - } - else if (ctx.isStartElement(event, DIMENSION)) - { + } else if (ctx.isStartElement(event, DIMENSION)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerDimension) + if (o != null && o instanceof WMSLayerDimension) { this.addDimension((WMSLayerDimension) o); + } } - } - else if (ctx.isStartElement(event, EXTENT)) - { + } else if (ctx.isStartElement(event, EXTENT)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerExtent) + if (o != null && o instanceof WMSLayerExtent) { this.addExtent((WMSLayerExtent) o); + } } - } - else if (ctx.isStartElement(event, AUTHORITY_URL)) - { + } else if (ctx.isStartElement(event, AUTHORITY_URL)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSAuthorityURL) + if (o != null && o instanceof WMSAuthorityURL) { this.addAuthorityURL((WMSAuthorityURL) o); + } } - } - else if (ctx.isStartElement(event, DATA_URL)) - { + } else if (ctx.isStartElement(event, DATA_URL)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerInfoURL) + if (o != null && o instanceof WMSLayerInfoURL) { this.addDataURL((WMSLayerInfoURL) o); + } } - } - else if (ctx.isStartElement(event, FEATURE_LIST_URL)) - { + } else if (ctx.isStartElement(event, FEATURE_LIST_URL)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerInfoURL) + if (o != null && o instanceof WMSLayerInfoURL) { this.addFeatureListURL((WMSLayerInfoURL) o); + } } - } - else if (ctx.isStartElement(event, METADATA_URL)) - { + } else if (ctx.isStartElement(event, METADATA_URL)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerInfoURL) + if (o != null && o instanceof WMSLayerInfoURL) { this.addMetadataURL((WMSLayerInfoURL) o); + } } } } @SuppressWarnings({"UnusedDeclaration"}) - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent layerEvent, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent layerEvent, Object... args) { Iterator iter = layerEvent.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("queryable") && attr.getValue() != null) - { + if (attr.getName().getLocalPart().equals("queryable") && attr.getValue() != null) { Boolean b = this.parseBooleanLayerAttribute(attr.getValue()); - if (b != null) + if (b != null) { this.setQueryable(b); - } - else if (attr.getName().getLocalPart().equals("cascaded") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("cascaded") && attr.getValue() != null) { Boolean b = this.parseBooleanLayerAttribute(attr.getValue()); - if (b != null) + if (b != null) { this.setCascaded(b); - } - else if (attr.getName().getLocalPart().equals("opaque") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("opaque") && attr.getValue() != null) { Boolean b = this.parseBooleanLayerAttribute(attr.getValue()); - if (b != null) + if (b != null) { this.setOpaque(b); - } - else if (attr.getName().getLocalPart().equals("noSubsets") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("noSubsets") && attr.getValue() != null) { Boolean b = this.parseBooleanLayerAttribute(attr.getValue()); - if (b != null) + if (b != null) { this.setNoSubsets(b); - } - else if (attr.getName().getLocalPart().equals("fixedWidth") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("fixedWidth") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setFixedWidth(d.intValue()); - } - else if (attr.getName().getLocalPart().equals("fixedHeight") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("fixedHeight") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setFixedHeight(d.intValue()); + } } } } - protected Boolean parseBooleanLayerAttribute(String s) - { - if (WWUtil.isEmpty(s)) + protected Boolean parseBooleanLayerAttribute(String s) { + if (WWUtil.isEmpty(s)) { return false; + } - if (s.equalsIgnoreCase("false")) + if (s.equalsIgnoreCase("false")) { return false; - else if (s.equalsIgnoreCase("true")) + } else if (s.equalsIgnoreCase("true")) { return true; + } Boolean d = WWUtil.convertStringToBoolean(s); return (d != null && d); } @SuppressWarnings({"UnusedDeclaration"}) - protected void parseExtremeElevations(XMLEventParserContext ctx, XMLEvent layerEvent) - { + protected void parseExtremeElevations(XMLEventParserContext ctx, XMLEvent layerEvent) { Iterator iter = layerEvent.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("min") && attr.getValue() != null) - { + if (attr.getName().getLocalPart().equals("min") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setExtremeElevationMin(d); - } - else if (attr.getName().getLocalPart().equals("max") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("max") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setExtremeElevationMax(d); + } } } } - protected void parseGeographicBoundingBox(XMLEventParserContext ctx, XMLEvent bboxEvent) throws XMLStreamException - { + protected void parseGeographicBoundingBox(XMLEventParserContext ctx, XMLEvent bboxEvent) throws XMLStreamException { Double minLat = null; Double minLon = null; Double maxLat = null; Double maxLon = null; - for (XMLEvent event = ctx.nextEvent(); event != null; event = ctx.nextEvent()) - { - if (ctx.isEndElement(event, bboxEvent)) - { - if (minLat != null && minLon != null && maxLat != null && maxLon != null) + for (XMLEvent event = ctx.nextEvent(); event != null; event = ctx.nextEvent()) { + if (ctx.isEndElement(event, bboxEvent)) { + if (minLat != null && minLon != null && maxLat != null && maxLon != null) { this.setGeographicBoundingBox(Sector.fromDegreesAndClamp(minLat, maxLat, minLon, maxLon)); + } return; - } - else if (event.isStartElement()) - { - if (event.asStartElement().getName().getLocalPart().equals("westBoundLongitude")) - { + } else if (event.isStartElement()) { + if (event.asStartElement().getName().getLocalPart().equals("westBoundLongitude")) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { minLon = d; - } - else if (event.asStartElement().getName().getLocalPart().equals("eastBoundLongitude")) - { + } + } else if (event.asStartElement().getName().getLocalPart().equals("eastBoundLongitude")) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { maxLon = d; - } - else if (event.asStartElement().getName().getLocalPart().equals("southBoundLatitude")) - { + } + } else if (event.asStartElement().getName().getLocalPart().equals("southBoundLatitude")) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { minLat = d; - } - else if (event.asStartElement().getName().getLocalPart().equals("northBoundLatitude")) - { + } + } else if (event.asStartElement().getName().getLocalPart().equals("northBoundLatitude")) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { maxLat = d; + } } } } @@ -560,670 +513,600 @@ else if (event.asStartElement().getName().getLocalPart().equals("northBoundLatit @SuppressWarnings({"UnusedDeclaration"}) protected void parseGeographicBoundingBoxV111(XMLEventParserContext ctx, XMLEvent bboxEvent) - throws XMLStreamException - { + throws XMLStreamException { Double minLat = null; Double minLon = null; Double maxLat = null; Double maxLon = null; Iterator iter = bboxEvent.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("minx") && attr.getValue() != null) - { + if (attr.getName().getLocalPart().equals("minx") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { minLon = d; - } - else if (attr.getName().getLocalPart().equals("miny") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("miny") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { minLat = d; - } - else if (attr.getName().getLocalPart().equals("maxx") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("maxx") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { maxLon = d; - } - else if (attr.getName().getLocalPart().equals("maxy") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("maxy") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { maxLat = d; + } } } - if (minLat != null && minLon != null && maxLat != null && maxLon != null) + if (minLat != null && minLon != null && maxLat != null && maxLon != null) { this.setGeographicBoundingBox(Sector.fromDegrees(minLat, maxLat, minLon, maxLon)); + } } @SuppressWarnings({"UnusedDeclaration"}) - protected void parseScaleHint(XMLEventParserContext ctx, XMLEvent bboxEvent) throws XMLStreamException - { + protected void parseScaleHint(XMLEventParserContext ctx, XMLEvent bboxEvent) throws XMLStreamException { Iterator iter = bboxEvent.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("min") && attr.getValue() != null) - { + if (attr.getName().getLocalPart().equals("min") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setMinScaleHint(d); - } - else if (attr.getName().getLocalPart().equals("max") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("max") && attr.getValue() != null) { Double d = WWUtil.convertStringToDouble(attr.getValue()); - if (d != null) + if (d != null) { this.setMaxScaleHint(d); + } } } } - public List getNamedLayers() - { + public List getNamedLayers() { List namedLayers = new ArrayList(); - if (this.getName() != null) + if (this.getName() != null) { namedLayers.add(this); + } - for (WMSLayerCapabilities layer : this.getLayers()) - { + for (WMSLayerCapabilities layer : this.getLayers()) { namedLayers.addAll(layer.getNamedLayers()); } return namedLayers; } - public WMSLayerCapabilities getLayerByName(String name) - { - if (WWUtil.isEmpty(name)) + public WMSLayerCapabilities getLayerByName(String name) { + if (WWUtil.isEmpty(name)) { return null; + } - if (this.getName() != null && this.getName().equals(name)) + if (this.getName() != null && this.getName().equals(name)) { return this; + } - for (WMSLayerCapabilities lc : this.getLayers()) - { - if (lc.getName() != null && lc.getName().equals(name)) + for (WMSLayerCapabilities lc : this.getLayers()) { + if (lc.getName() != null && lc.getName().equals(name)) { return lc; + } } return null; } - public WMSLayerStyle getStyleByName(String name) - { - if (WWUtil.isEmpty(name)) + public WMSLayerStyle getStyleByName(String name) { + if (WWUtil.isEmpty(name)) { return null; + } - for (WMSLayerStyle style : this.getStyles()) - { - if (style.getName().equals(name)) + for (WMSLayerStyle style : this.getStyles()) { + if (style.getName().equals(name)) { return style; + } } return null; } - public Double getExtremeElevationMin() - { + public Double getExtremeElevationMin() { return extremeElevationMin; } - protected void setExtremeElevationMin(Double extremeElevationMin) - { + protected void setExtremeElevationMin(Double extremeElevationMin) { this.extremeElevationMin = extremeElevationMin; } - public Double getExtremeElevationMax() - { + public Double getExtremeElevationMax() { return extremeElevationMax; } - protected void setExtremeElevationMax(Double extremeElevationMax) - { + protected void setExtremeElevationMax(Double extremeElevationMax) { this.extremeElevationMax = extremeElevationMax; } - public String getLastUpdate() - { + public String getLastUpdate() { return lastUpdate; } - protected void setLastUpdate(String lastUpdate) - { + protected void setLastUpdate(String lastUpdate) { this.lastUpdate = lastUpdate; } - public Double getMinScaleHint() - { + public Double getMinScaleHint() { return this.minScaleHint; } - protected void setMinScaleHint(Double scaleHint) - { + protected void setMinScaleHint(Double scaleHint) { this.minScaleHint = scaleHint; } - public Double getMaxScaleHint() - { + public Double getMaxScaleHint() { return this.maxScaleHint; } - protected void setMaxScaleHint(Double scaleHint) - { + protected void setMaxScaleHint(Double scaleHint) { this.maxScaleHint = scaleHint; } - public Set getDimensions() - { - if (this.dimensions != null) + public Set getDimensions() { + if (this.dimensions != null) { return this.dimensions; - else + } else { return Collections.emptySet(); + } } - protected void addDimension(WMSLayerDimension dimension) - { - if (this.dimensions == null) + protected void addDimension(WMSLayerDimension dimension) { + if (this.dimensions == null) { this.dimensions = new HashSet(); + } this.getDimensions().add(dimension); } - protected void addDimensions(Set dims) - { - if (dims.size() == 0) + protected void addDimensions(Set dims) { + if (dims.size() == 0) { return; + } - for (WMSLayerDimension dim : dims) - { + for (WMSLayerDimension dim : dims) { this.addDimension(dim); } } - protected void setDimensions(Set dimensions) - { + protected void setDimensions(Set dimensions) { this.dimensions = dimensions; } - public Set getExtents() - { - if (this.extents != null) + public Set getExtents() { + if (this.extents != null) { return this.extents; - else + } else { return Collections.emptySet(); + } } - protected void addExtent(WMSLayerExtent extent) - { - if (this.extents == null) + protected void addExtent(WMSLayerExtent extent) { + if (this.extents == null) { this.extents = new HashSet(); + } this.getExtents().add(extent); } - protected void addExtents(Set inExtents) - { - if (inExtents.size() == 0) + protected void addExtents(Set inExtents) { + if (inExtents.size() == 0) { return; + } - for (WMSLayerExtent extent : inExtents) - { + for (WMSLayerExtent extent : inExtents) { this.addExtent(extent); } } - public Boolean getCascaded() - { + public Boolean getCascaded() { return cascaded; } - protected void setCascaded(Boolean cascaded) - { + protected void setCascaded(Boolean cascaded) { this.cascaded = cascaded; } - public Integer getFixedHeight() - { + public Integer getFixedHeight() { return fixedHeight; } - protected void setFixedHeight(Integer height) - { + protected void setFixedHeight(Integer height) { this.fixedHeight = height; } - public Integer getFixedWidth() - { + public Integer getFixedWidth() { return fixedWidth; } - protected void setFixedWidth(Integer width) - { + protected void setFixedWidth(Integer width) { this.fixedWidth = width; } - public Boolean isNoSubsets() - { + public Boolean isNoSubsets() { return noSubsets; } - protected void setNoSubsets(Boolean noSubsets) - { + protected void setNoSubsets(Boolean noSubsets) { this.noSubsets = noSubsets; } - public Boolean isOpaque() - { + public Boolean isOpaque() { return opaque; } - protected void setOpaque(Boolean opaque) - { + protected void setOpaque(Boolean opaque) { this.opaque = opaque; } - public Boolean isQueryable() - { + public Boolean isQueryable() { return queryable; } - protected void setQueryable(Boolean queryable) - { + protected void setQueryable(Boolean queryable) { this.queryable = queryable; } - public Set getAttributions() - { - if (this.attributions != null) + public Set getAttributions() { + if (this.attributions != null) { return attributions; - else + } else { return Collections.emptySet(); + } } - protected void setAttributions(Set attributions) - { + protected void setAttributions(Set attributions) { this.attributions = attributions; } - protected void addAttribution(WMSLayerAttribution attribution) - { - if (this.attributions == null) + protected void addAttribution(WMSLayerAttribution attribution) { + if (this.attributions == null) { this.attributions = new HashSet(); + } this.getAttributions().add(attribution); } - protected void addAttributions(Set attribs) - { - for (WMSLayerAttribution attrib : attribs) - { + protected void addAttributions(Set attribs) { + for (WMSLayerAttribution attrib : attribs) { this.addAttribution(attrib); } } - public Set getAuthorityURLs() - { - if (this.authorityURLs != null) + public Set getAuthorityURLs() { + if (this.authorityURLs != null) { return this.authorityURLs; - else + } else { return Collections.emptySet(); + } } - protected void setAuthorityURLs(Set urls) - { + protected void setAuthorityURLs(Set urls) { this.authorityURLs = urls; } - protected void addAuthorityURL(WMSAuthorityURL authorityURL) - { - if (this.authorityURLs == null) + protected void addAuthorityURL(WMSAuthorityURL authorityURL) { + if (this.authorityURLs == null) { this.authorityURLs = new HashSet(); + } this.getAuthorityURLs().add(authorityURL); } - protected void addAuthorityURLs(Set urls) - { - for (WMSAuthorityURL url : urls) - { + protected void addAuthorityURLs(Set urls) { + for (WMSAuthorityURL url : urls) { this.addAuthorityURL(url); } } - public Set getIdentifiers() - { - if (this.identifiers != null) + public Set getIdentifiers() { + if (this.identifiers != null) { return this.identifiers; - else + } else { return Collections.emptySet(); + } } - protected void addIdentifer(WMSLayerIdentifier identifier) - { - if (this.identifiers == null) + protected void addIdentifer(WMSLayerIdentifier identifier) { + if (this.identifiers == null) { this.identifiers = new HashSet(); + } this.getIdentifiers().add(identifier); } - protected void addIdentifiers(Set ids) - { - for (WMSLayerIdentifier id : ids) - { + protected void addIdentifiers(Set ids) { + for (WMSLayerIdentifier id : ids) { this.addIdentifer(id); } } - public Set getMetadataURLs() - { - if (this.metadataURLs != null) + public Set getMetadataURLs() { + if (this.metadataURLs != null) { return this.metadataURLs; - else + } else { return Collections.emptySet(); + } } - protected void addMetadataURL(WMSLayerInfoURL url) - { - if (this.metadataURLs == null) + protected void addMetadataURL(WMSLayerInfoURL url) { + if (this.metadataURLs == null) { this.metadataURLs = new HashSet(); + } this.getMetadataURLs().add(url); } - protected void addMetadataURLs(Set urls) - { - for (WMSLayerInfoURL url : urls) - { + protected void addMetadataURLs(Set urls) { + for (WMSLayerInfoURL url : urls) { this.addMetadataURL(url); } } - public Set getFeatureListURLs() - { - if (this.featureListURLs != null) + public Set getFeatureListURLs() { + if (this.featureListURLs != null) { return this.featureListURLs; - else + } else { return Collections.emptySet(); + } } - protected void addFeatureListURL(WMSLayerInfoURL url) - { - if (this.featureListURLs == null) + protected void addFeatureListURL(WMSLayerInfoURL url) { + if (this.featureListURLs == null) { this.featureListURLs = new HashSet(); + } this.getFeatureListURLs().add(url); } - protected void addFeatureListURLs(Set urls) - { - for (WMSLayerInfoURL url : urls) - { + protected void addFeatureListURLs(Set urls) { + for (WMSLayerInfoURL url : urls) { this.addFeatureListURL(url); } } - public Set getDataURLs() - { - if (this.dataURLs != null) + public Set getDataURLs() { + if (this.dataURLs != null) { return this.dataURLs; - else + } else { return Collections.emptySet(); + } } - protected void addDataURL(WMSLayerInfoURL url) - { - if (this.dataURLs == null) + protected void addDataURL(WMSLayerInfoURL url) { + if (this.dataURLs == null) { this.dataURLs = new HashSet(); + } this.getDataURLs().add(url); } - protected void addDataURLs(Set urls) - { - for (WMSLayerInfoURL url : urls) - { + protected void addDataURLs(Set urls) { + for (WMSLayerInfoURL url : urls) { this.addDataURL(url); } } - public List getLayers() - { - if (this.layers != null) + public List getLayers() { + if (this.layers != null) { return this.layers; - else + } else { return Collections.emptyList(); + } } - protected void addLayer(WMSLayerCapabilities layer) - { - if (this.layers == null) + protected void addLayer(WMSLayerCapabilities layer) { + if (this.layers == null) { this.layers = new ArrayList(); + } this.getLayers().add(layer); } - protected void addLayers(Set inLayers) - { - for (WMSLayerCapabilities layer : inLayers) - { + protected void addLayers(Set inLayers) { + for (WMSLayerCapabilities layer : inLayers) { this.addLayer(layer); } } - public Set getStyles() - { - if (this.styles != null) + public Set getStyles() { + if (this.styles != null) { return this.styles; - else + } else { return Collections.emptySet(); + } } - protected void setStyles(Set styles) - { + protected void setStyles(Set styles) { this.styles = styles; } - protected void addStyle(WMSLayerStyle style) - { - if (this.styles == null) + protected void addStyle(WMSLayerStyle style) { + if (this.styles == null) { this.styles = new HashSet(); + } this.getStyles().add(style); } - protected void addStyles(Set inStyles) - { - for (WMSLayerStyle style : inStyles) - { + protected void addStyles(Set inStyles) { + for (WMSLayerStyle style : inStyles) { this.addStyle(style); } } - public Set getBoundingBoxes() - { - if (this.boundingBoxes != null) + public Set getBoundingBoxes() { + if (this.boundingBoxes != null) { return this.boundingBoxes; - else + } else { return Collections.emptySet(); + } } - protected void setBoundingBoxes(Set boxes) - { + protected void setBoundingBoxes(Set boxes) { this.boundingBoxes = boxes; } - protected void addBoundingBox(OGCBoundingBox box) - { - if (this.boundingBoxes == null) + protected void addBoundingBox(OGCBoundingBox box) { + if (this.boundingBoxes == null) { this.boundingBoxes = new HashSet(); + } this.getBoundingBoxes().add(box); } - protected void addBoundingBoxes(Set boxes) - { - for (OGCBoundingBox bbox : boxes) - { + protected void addBoundingBoxes(Set boxes) { + for (OGCBoundingBox bbox : boxes) { this.addBoundingBox(bbox); } } - public Sector getGeographicBoundingBox() - { + public Sector getGeographicBoundingBox() { return geographicBoundingBox; } - protected void setGeographicBoundingBox(Sector geographicBoundingBox) - { + protected void setGeographicBoundingBox(Sector geographicBoundingBox) { this.geographicBoundingBox = geographicBoundingBox; } - public Set getKeywords() - { - if (this.keywords != null) + public Set getKeywords() { + if (this.keywords != null) { return this.keywords; - else + } else { return Collections.emptySet(); + } } - protected void setKeywords(Set keywords) - { + protected void setKeywords(Set keywords) { this.keywords = keywords; } - public String getLayerAbstract() - { + public String getLayerAbstract() { return layerAbstract; } - protected void setLayerAbstract(String layerAbstract) - { + protected void setLayerAbstract(String layerAbstract) { this.layerAbstract = layerAbstract; } - public Double getMaxScaleDenominator() - { + public Double getMaxScaleDenominator() { return maxScaleDenominator; } - protected void setMaxScaleDenominator(Double maxScaleDenominator) - { + protected void setMaxScaleDenominator(Double maxScaleDenominator) { this.maxScaleDenominator = maxScaleDenominator; } - public Double getMinScaleDenominator() - { + public Double getMinScaleDenominator() { return minScaleDenominator; } - protected void setMinScaleDenominator(Double minScaleDenominator) - { + protected void setMinScaleDenominator(Double minScaleDenominator) { this.minScaleDenominator = minScaleDenominator; } - public String getName() - { + public String getName() { return name; } - protected void setName(String name) - { + protected void setName(String name) { this.name = name; } - public String getTitle() - { + public String getTitle() { return title; } - protected void setTitle(String title) - { + protected void setTitle(String title) { this.title = title; } - public Set getSRS() - { - if (this.srs != null) + public Set getSRS() { + if (this.srs != null) { return this.srs; - else + } else { return Collections.emptySet(); + } } - protected void setSRS(Set srs) - { + protected void setSRS(Set srs) { this.srs = srs; } - protected void addSRS(String srs) - { - if (this.srs == null) + protected void addSRS(String srs) { + if (this.srs == null) { this.srs = new HashSet(); + } this.srs.add(srs); } - protected void addSRS(Set srss) - { - for (String c : srss) - { + protected void addSRS(Set srss) { + for (String c : srss) { this.addSRS(c); } } - public Set getCRS() - { - if (this.crs != null) + public Set getCRS() { + if (this.crs != null) { return this.crs; - else + } else { return Collections.emptySet(); + } } - protected void setCRS(Set crs) - { + protected void setCRS(Set crs) { this.crs = crs; } - protected void addCRS(String crs) - { - if (this.crs == null) + protected void addCRS(String crs) { + if (this.crs == null) { this.crs = new HashSet(); + } this.crs.add(crs); } - protected void addCRS(Set crss) - { - for (String c : crss) - { + protected void addCRS(Set crss) { + for (String c : crss) { this.addCRS(c); } } - public boolean hasCoordinateSystem(String coordSys) - { - if (coordSys == null) + public boolean hasCoordinateSystem(String coordSys) { + if (coordSys == null) { return false; + } Collection coordSystems = this.crs != null ? this.crs : this.srs; - if (coordSystems == null) + if (coordSystems == null) { return false; + } - for (String s : coordSystems) - { - if (coordSys.equals(s)) + for (String s : coordSystems) { + if (coordSys.equals(s)) { return true; + } } return false; @@ -1234,8 +1117,9 @@ public String toString() // TODO: Complete this method { StringBuilder sb = new StringBuilder("LAYER "); - if (!WWUtil.isEmpty(this.getName())) + if (!WWUtil.isEmpty(this.getName())) { sb.append(this.getName()).append(": "); + } sb.append("queryable = ").append(this.isQueryable()); return sb.toString(); diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSLayerDimension.java b/src/gov/nasa/worldwind/ogc/wms/WMSLayerDimension.java index 1bedaa3922..ce22f3a8db 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSLayerDimension.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSLayerDimension.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.util.WWUtil; @@ -19,8 +18,8 @@ * @author tag * @version $Id: WMSLayerDimension.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSLayerDimension extends AbstractXMLEventParser -{ +public class WMSLayerDimension extends AbstractXMLEventParser { + protected StringBuilder dimension; protected String name; protected String units; @@ -30,22 +29,19 @@ public class WMSLayerDimension extends AbstractXMLEventParser protected Boolean nearestValue; protected Boolean current; - public WMSLayerDimension(String namespaceURI) - { + public WMSLayerDimension(String namespaceURI) { super(namespaceURI); } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (event.isCharacters()) - { + throws XMLStreamException { + if (event.isCharacters()) { String s = ctx.getCharacters(event); - if (!WWUtil.isEmpty(s)) - { - if (this.dimension == null) + if (!WWUtil.isEmpty(s)) { + if (this.dimension == null) { this.dimension = new StringBuilder(); + } this.dimension.append(s); } @@ -53,123 +49,102 @@ protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Ob } @Override - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("name") && attr.getValue() != null) + if (attr.getName().getLocalPart().equals("name") && attr.getValue() != null) { this.setName(attr.getValue()); - - else if (attr.getName().getLocalPart().equals("units") && attr.getValue() != null) + } else if (attr.getName().getLocalPart().equals("units") && attr.getValue() != null) { this.setUnits(attr.getValue()); - - else if (attr.getName().getLocalPart().equals("unitSymbol") && attr.getValue() != null) + } else if (attr.getName().getLocalPart().equals("unitSymbol") && attr.getValue() != null) { this.setUnitSymbol(attr.getValue()); - - else if (attr.getName().getLocalPart().equals("default") && attr.getValue() != null) + } else if (attr.getName().getLocalPart().equals("default") && attr.getValue() != null) { this.setDefaultValue(attr.getValue()); - - else if (attr.getName().getLocalPart().equals("multipleValues") && attr.getValue() != null) - { + } else if (attr.getName().getLocalPart().equals("multipleValues") && attr.getValue() != null) { Boolean d = WWUtil.convertStringToBoolean(attr.getValue()); - if (d != null) + if (d != null) { this.setMultipleValues(d); - } - else if (attr.getName().getLocalPart().equals("nearestValue") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("nearestValue") && attr.getValue() != null) { Boolean d = WWUtil.convertStringToBoolean(attr.getValue()); - if (d != null) + if (d != null) { this.setNearestValue(d); - } - else if (attr.getName().getLocalPart().equals("current") && attr.getValue() != null) - { + } + } else if (attr.getName().getLocalPart().equals("current") && attr.getValue() != null) { Boolean d = WWUtil.convertStringToBoolean(attr.getValue()); - if (d != null) + if (d != null) { this.setCurrent(d); + } } } } - public String getDimension() - { - if (this.dimension == null) + public String getDimension() { + if (this.dimension == null) { this.dimension = new StringBuilder(); + } return dimension.toString(); } - public String getName() - { + public String getName() { return name; } - protected void setName(String name) - { + protected void setName(String name) { this.name = name; } - public String getUnits() - { + public String getUnits() { return units; } - protected void setUnits(String units) - { + protected void setUnits(String units) { this.units = units; } - public String getUnitSymbol() - { + public String getUnitSymbol() { return unitSymbol; } - protected void setUnitSymbol(String unitSymbol) - { + protected void setUnitSymbol(String unitSymbol) { this.unitSymbol = unitSymbol; } - public String getDefaultValue() - { + public String getDefaultValue() { return defaultValue; } - protected void setDefaultValue(String defaultValue) - { + protected void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } - public Boolean isMultipleValues() - { + public Boolean isMultipleValues() { return multipleValues; } - protected void setMultipleValues(Boolean multipleValues) - { + protected void setMultipleValues(Boolean multipleValues) { this.multipleValues = multipleValues; } - public Boolean isNearestValue() - { + public Boolean isNearestValue() { return nearestValue; } - protected void setNearestValue(Boolean nearestValue) - { + protected void setNearestValue(Boolean nearestValue) { this.nearestValue = nearestValue; } - public Boolean isCurrent() - { + public Boolean isCurrent() { return current; } - protected void setCurrent(Boolean current) - { + protected void setCurrent(Boolean current) { this.current = current; } } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSLayerExtent.java b/src/gov/nasa/worldwind/ogc/wms/WMSLayerExtent.java index 30e8b06762..86e68f95d9 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSLayerExtent.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSLayerExtent.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.util.WWUtil; @@ -18,75 +17,64 @@ * @author tag * @version $Id: WMSLayerExtent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSLayerExtent extends AbstractXMLEventParser -{ +public class WMSLayerExtent extends AbstractXMLEventParser { + protected String extent; protected String name; protected String defaultValue; protected Boolean nearestValue; - public WMSLayerExtent(String namespaceURI) - { + public WMSLayerExtent(String namespaceURI) { super(namespaceURI); } @Override - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("name") && attr.getValue() != null) + if (attr.getName().getLocalPart().equals("name") && attr.getValue() != null) { this.setName(attr.getValue()); - - else if (attr.getName().getLocalPart().equals("default") && attr.getValue() != null) + } else if (attr.getName().getLocalPart().equals("default") && attr.getValue() != null) { this.setDefaultValue(attr.getValue()); - - else if (attr.getName().getLocalPart().equals("nearestValue") && attr.getValue() != null) - { + } else if (attr.getName().getLocalPart().equals("nearestValue") && attr.getValue() != null) { Boolean d = WWUtil.convertStringToBoolean(attr.getValue()); - if (d != null) + if (d != null) { this.setNearestValue(d); + } } } } - public String getExtent() - { + public String getExtent() { return this.getCharacters(); } - public String getName() - { + public String getName() { return name; } - protected void setName(String name) - { + protected void setName(String name) { this.name = name; } - public String getDefaultValue() - { + public String getDefaultValue() { return defaultValue; } - protected void setDefaultValue(String defaultValue) - { + protected void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } - public Boolean isNearestValue() - { + public Boolean isNearestValue() { return nearestValue; } - protected void setNearestValue(Boolean nearestValue) - { + protected void setNearestValue(Boolean nearestValue) { this.nearestValue = nearestValue; } } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSLayerIdentifier.java b/src/gov/nasa/worldwind/ogc/wms/WMSLayerIdentifier.java index ac10f50cab..8d1cfa8db5 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSLayerIdentifier.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSLayerIdentifier.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.util.xml.*; @@ -17,43 +16,39 @@ * @author tag * @version $Id: WMSLayerIdentifier.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSLayerIdentifier extends AbstractXMLEventParser -{ +public class WMSLayerIdentifier extends AbstractXMLEventParser { + protected String identifier; protected String authority; - public WMSLayerIdentifier(String namespaceURI) - { + public WMSLayerIdentifier(String namespaceURI) { super(namespaceURI); } @Override - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("authority") && attr.getValue() != null) + if (attr.getName().getLocalPart().equals("authority") && attr.getValue() != null) { this.setAuthority(attr.getValue()); + } } } - public String getIdentifier() - { + public String getIdentifier() { return this.getCharacters(); } - public String getAuthority() - { + public String getAuthority() { return authority; } - protected void setAuthority(String authority) - { + protected void setAuthority(String authority) { this.authority = authority; } } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSLayerInfoURL.java b/src/gov/nasa/worldwind/ogc/wms/WMSLayerInfoURL.java index 095be6b4b7..93848ff071 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSLayerInfoURL.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSLayerInfoURL.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.ogc.OGCOnlineResource; @@ -21,8 +20,8 @@ * @author tag * @version $Id: WMSLayerInfoURL.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSLayerInfoURL extends AbstractXMLEventParser -{ +public class WMSLayerInfoURL extends AbstractXMLEventParser { + protected QName FORMAT; protected QName ONLINE_RESOURCE; @@ -30,92 +29,80 @@ public class WMSLayerInfoURL extends AbstractXMLEventParser protected String name; protected String format; - public WMSLayerInfoURL(String namespaceURI) - { + public WMSLayerInfoURL(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { FORMAT = new QName(this.getNamespaceURI(), "Format"); ONLINE_RESOURCE = new QName(this.getNamespaceURI(), "OnlineResource"); } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; - if (ctx.isStartElement(event, ONLINE_RESOURCE)) + if (ctx.isStartElement(event, ONLINE_RESOURCE)) { defaultParser = new OGCOnlineResource(this.getNamespaceURI()); + } return ctx.allocate(event, defaultParser); } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, FORMAT)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, FORMAT)) { this.setFormat(ctx.getStringParser().parseString(ctx, event)); - } - else if (ctx.isStartElement(event, ONLINE_RESOURCE)) - { + } else if (ctx.isStartElement(event, ONLINE_RESOURCE)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof OGCOnlineResource) + if (o != null && o instanceof OGCOnlineResource) { this.setOnlineResource((OGCOnlineResource) o); + } } } } @SuppressWarnings({"UnusedDeclaration"}) - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("name") && attr.getValue() != null) + if (attr.getName().getLocalPart().equals("name") && attr.getValue() != null) { this.setName(attr.getValue()); + } } } - public OGCOnlineResource getOnlineResource() - { + public OGCOnlineResource getOnlineResource() { return onlineResource; } - protected void setOnlineResource(OGCOnlineResource onlineResource) - { + protected void setOnlineResource(OGCOnlineResource onlineResource) { this.onlineResource = onlineResource; } - public String getName() - { + public String getName() { return name; } - protected void setName(String name) - { + protected void setName(String name) { this.name = name; } - public String getFormat() - { + public String getFormat() { return format; } - protected void setFormat(String format) - { + protected void setFormat(String format) { this.format = format; } } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSLayerStyle.java b/src/gov/nasa/worldwind/ogc/wms/WMSLayerStyle.java index 4ca6c876eb..c098265d96 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSLayerStyle.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSLayerStyle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.util.WWUtil; @@ -20,8 +19,8 @@ * @author tag * @version $Id: WMSLayerStyle.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSLayerStyle extends AbstractXMLEventParser -{ +public class WMSLayerStyle extends AbstractXMLEventParser { + protected QName NAME; protected QName TITLE; protected QName ABSTRACT; @@ -36,15 +35,13 @@ public class WMSLayerStyle extends AbstractXMLEventParser protected WMSLayerInfoURL styleURL; protected Set legendURLs; - public WMSLayerStyle(String namespaceURI) - { + public WMSLayerStyle(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { NAME = new QName(this.getNamespaceURI(), "Name"); TITLE = new QName(this.getNamespaceURI(), "Title"); ABSTRACT = new QName(this.getNamespaceURI(), "Abstract"); @@ -54,145 +51,126 @@ private void initialize() } @Override - public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) - { + public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) { XMLEventParser defaultParser = null; XMLEventParser parser = super.allocate(ctx, event); - if (parser != null) + if (parser != null) { return parser; + } - if (ctx.isStartElement(event, LEGEND_URL)) + if (ctx.isStartElement(event, LEGEND_URL)) { defaultParser = new WMSLogoURL(this.getNamespaceURI()); - else if (ctx.isStartElement(event, STYLE_SHEET_URL)) + } else if (ctx.isStartElement(event, STYLE_SHEET_URL)) { defaultParser = new WMSLayerInfoURL(this.getNamespaceURI()); - else if (ctx.isStartElement(event, STYLE_URL)) + } else if (ctx.isStartElement(event, STYLE_URL)) { defaultParser = new WMSLayerInfoURL(this.getNamespaceURI()); + } return ctx.allocate(event, defaultParser); } @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, TITLE)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, TITLE)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.setTitle(s); - } - else if (ctx.isStartElement(event, NAME)) - { + } + } else if (ctx.isStartElement(event, NAME)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.setName(s); - } - else if (ctx.isStartElement(event, ABSTRACT)) - { + } + } else if (ctx.isStartElement(event, ABSTRACT)) { String s = ctx.getStringParser().parseString(ctx, event); - if (!WWUtil.isEmpty(s)) + if (!WWUtil.isEmpty(s)) { this.setStyleAbstract(s); - } - else if (ctx.isStartElement(event, LEGEND_URL)) - { + } + } else if (ctx.isStartElement(event, LEGEND_URL)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLogoURL) + if (o != null && o instanceof WMSLogoURL) { this.addLegendURL((WMSLogoURL) o); + } } - } - else if (ctx.isStartElement(event, STYLE_SHEET_URL)) - { + } else if (ctx.isStartElement(event, STYLE_SHEET_URL)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerInfoURL) + if (o != null && o instanceof WMSLayerInfoURL) { this.setStyleSheetURL((WMSLayerInfoURL) o); + } } - } - else if (ctx.isStartElement(event, STYLE_URL)) - { + } else if (ctx.isStartElement(event, STYLE_URL)) { XMLEventParser parser = this.allocate(ctx, event); - if (parser != null) - { + if (parser != null) { Object o = parser.parse(ctx, event, args); - if (o != null && o instanceof WMSLayerInfoURL) + if (o != null && o instanceof WMSLayerInfoURL) { this.setStyleURL((WMSLayerInfoURL) o); + } } } } - public String getName() - { + public String getName() { return name; } - protected void setName(String name) - { + protected void setName(String name) { this.name = name; } - public String getTitle() - { + public String getTitle() { return title; } - protected void setTitle(String title) - { + protected void setTitle(String title) { this.title = title; } - public String getStyleAbstract() - { + public String getStyleAbstract() { return styleAbstract; } - protected void setStyleAbstract(String styleAbstract) - { + protected void setStyleAbstract(String styleAbstract) { this.styleAbstract = styleAbstract; } - public WMSLayerInfoURL getStyleSheetURL() - { + public WMSLayerInfoURL getStyleSheetURL() { return styleSheetURL; } - protected void setStyleSheetURL(WMSLayerInfoURL styleSheetURL) - { + protected void setStyleSheetURL(WMSLayerInfoURL styleSheetURL) { this.styleSheetURL = styleSheetURL; } - public WMSLayerInfoURL getStyleURL() - { + public WMSLayerInfoURL getStyleURL() { return styleURL; } - protected void setStyleURL(WMSLayerInfoURL styleURL) - { + protected void setStyleURL(WMSLayerInfoURL styleURL) { this.styleURL = styleURL; } - public Set getLegendURLs() - { - if (this.legendURLs != null) + public Set getLegendURLs() { + if (this.legendURLs != null) { return legendURLs; - else + } else { return Collections.emptySet(); + } } - protected void setLegendURLs(Set legendURLs) - { + protected void setLegendURLs(Set legendURLs) { this.legendURLs = legendURLs; } - protected void addLegendURL(WMSLogoURL url) - { - if (this.legendURLs == null) + protected void addLegendURL(WMSLogoURL url) { + if (this.legendURLs == null) { this.legendURLs = new HashSet(); + } this.getLegendURLs().add(url); } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSLogoURL.java b/src/gov/nasa/worldwind/ogc/wms/WMSLogoURL.java index 0810eede14..34487baa9a 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSLogoURL.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSLogoURL.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.util.WWUtil; @@ -18,62 +17,56 @@ * @author tag * @version $Id: WMSLogoURL.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSLogoURL extends WMSLayerInfoURL -{ +public class WMSLogoURL extends WMSLayerInfoURL { + protected Integer width; protected Integer height; - public WMSLogoURL(String namespaceURI) - { + public WMSLogoURL(String namespaceURI) { super(namespaceURI); } @Override - protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) - { + protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args) { super.doParseEventAttributes(ctx, event, args); Iterator iter = event.asStartElement().getAttributes(); - if (iter == null) + if (iter == null) { return; + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); - if (attr.getName().getLocalPart().equals("width") && attr.getValue() != null) - { + if (attr.getName().getLocalPart().equals("width") && attr.getValue() != null) { Integer i = WWUtil.convertStringToInteger(attr.getValue()); - if (i != null) + if (i != null) { this.setWidth(i); + } } - if (attr.getName().getLocalPart().equals("height") && attr.getValue() != null) - { + if (attr.getName().getLocalPart().equals("height") && attr.getValue() != null) { Integer i = WWUtil.convertStringToInteger(attr.getValue()); - if (i != null) + if (i != null) { this.setHeight(i); + } } } } - public Integer getWidth() - { + public Integer getWidth() { return width; } - protected void setWidth(Integer width) - { + protected void setWidth(Integer width) { this.width = width; } - public Integer getHeight() - { + public Integer getHeight() { return height; } - protected void setHeight(Integer height) - { + protected void setHeight(Integer height) { this.height = height; } } diff --git a/src/gov/nasa/worldwind/ogc/wms/WMSServiceInformation.java b/src/gov/nasa/worldwind/ogc/wms/WMSServiceInformation.java index db724c1109..9a5fe2effc 100644 --- a/src/gov/nasa/worldwind/ogc/wms/WMSServiceInformation.java +++ b/src/gov/nasa/worldwind/ogc/wms/WMSServiceInformation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.ogc.wms; import gov.nasa.worldwind.ogc.OGCServiceInformation; @@ -19,8 +18,8 @@ * @author tag * @version $Id: WMSServiceInformation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSServiceInformation extends OGCServiceInformation -{ +public class WMSServiceInformation extends OGCServiceInformation { + protected QName MAX_WIDTH; protected QName MAX_HEIGHT; protected QName LAYER_LIMIT; @@ -29,15 +28,13 @@ public class WMSServiceInformation extends OGCServiceInformation protected int maxHeight; protected int layerLimit; - public WMSServiceInformation(String namespaceURI) - { + public WMSServiceInformation(String namespaceURI) { super(namespaceURI); this.initialize(); } - private void initialize() - { + private void initialize() { MAX_WIDTH = new QName(this.getNamespaceURI(), "MaxWidth"); MAX_HEIGHT = new QName(this.getNamespaceURI(), "MaxHeight"); LAYER_LIMIT = new QName(this.getNamespaceURI(), "LayerLimit"); @@ -45,55 +42,45 @@ private void initialize() @Override protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (ctx.isStartElement(event, MAX_WIDTH)) - { + throws XMLStreamException { + if (ctx.isStartElement(event, MAX_WIDTH)) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { this.maxWidth = d.intValue(); - } - else if (ctx.isStartElement(event, MAX_HEIGHT)) - { + } + } else if (ctx.isStartElement(event, MAX_HEIGHT)) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { this.maxHeight = d.intValue(); - } - else if (ctx.isStartElement(event, LAYER_LIMIT)) - { + } + } else if (ctx.isStartElement(event, LAYER_LIMIT)) { Double d = ctx.getDoubleParser().parseDouble(ctx, event); - if (d != null) + if (d != null) { this.layerLimit = d.intValue(); - } - else - { + } + } else { super.doParseEventContent(ctx, event, args); } } - public int getMaxWidth() - { + public int getMaxWidth() { return maxWidth; } - protected void setMaxWidth(int maxWidth) - { + protected void setMaxWidth(int maxWidth) { this.maxWidth = maxWidth; } - public int getMaxHeight() - { + public int getMaxHeight() { return maxHeight; } - protected void setMaxHeight(int maxHeight) - { + protected void setMaxHeight(int maxHeight) { this.maxHeight = maxHeight; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(super.toString()); sb.append("Max width = ").append(this.getMaxWidth()); diff --git a/src/gov/nasa/worldwind/pick/PickSupport.java b/src/gov/nasa/worldwind/pick/PickSupport.java index b262d5fcbd..10b1f7feb8 100644 --- a/src/gov/nasa/worldwind/pick/PickSupport.java +++ b/src/gov/nasa/worldwind/pick/PickSupport.java @@ -18,8 +18,8 @@ * @author tag * @version $Id: PickSupport.java 2281 2014-08-29 23:08:04Z dcollins $ */ -public class PickSupport -{ +public class PickSupport { + /** * The picked objects currently registered with this PickSupport, represented as a map of color codes to picked * objects. This maps provides constant time access to a picked object when its color code is known. @@ -37,33 +37,28 @@ public class PickSupport */ protected int[] minAndMaxColorCodes; - public void clearPickList() - { + public void clearPickList() { this.getPickableObjects().clear(); this.getPickableObjectRanges().clear(); this.minAndMaxColorCodes = null; // Reset the min and max color codes. } - public void addPickableObject(int colorCode, Object o, Position position, boolean isTerrain) - { + public void addPickableObject(int colorCode, Object o, Position position, boolean isTerrain) { this.getPickableObjects().put(colorCode, new PickedObject(colorCode, o, position, isTerrain)); this.adjustExtremeColorCodes(colorCode); } - public void addPickableObject(int colorCode, Object o, Position position) - { + public void addPickableObject(int colorCode, Object o, Position position) { this.getPickableObjects().put(colorCode, new PickedObject(colorCode, o, position, false)); this.adjustExtremeColorCodes(colorCode); } - public void addPickableObject(int colorCode, Object o) - { + public void addPickableObject(int colorCode, Object o) { this.getPickableObjects().put(colorCode, new PickedObject(colorCode, o)); this.adjustExtremeColorCodes(colorCode); } - public void addPickableObject(PickedObject po) - { + public void addPickableObject(PickedObject po) { this.getPickableObjects().put(po.getColorCode(), po); this.adjustExtremeColorCodes(po.getColorCode()); } @@ -75,29 +70,32 @@ public void addPickableObject(PickedObject po) * actually be picked. * * @param colorCode the first color code associated with the range of sequential color codes. - * @param count the number of sequential color codes in the range of sequential color codes. - * @param factory the PickedObjectFactory to use when creating a PickedObject for a color in the specified range. + * @param count the number of sequential color codes in the range of sequential color codes. + * @param factory the PickedObjectFactory to use when creating a PickedObject for a color in the specified range. */ - public void addPickableObjectRange(int colorCode, int count, PickedObjectFactory factory) - { + public void addPickableObjectRange(int colorCode, int count, PickedObjectFactory factory) { Range range = new Range(colorCode, count); this.pickableObjectRanges.put(range, factory); this.adjustExtremeColorCodes(colorCode); this.adjustExtremeColorCodes(colorCode + count - 1); // max code is last element in sequence of count codes } - public PickedObject getTopObject(DrawContext dc, Point pickPoint) - { + public PickedObject getTopObject(DrawContext dc, Point pickPoint) { if (!this.hasPickableObjects()) // avoid reading the current GL color when no pickable objects are registered + { return null; + } int colorCode = this.getTopColor(dc, pickPoint); if (colorCode == 0) // getTopColor returns 0 if the pick point selects the clear color. + { return null; + } PickedObject pickedObject = this.lookupPickableObject(colorCode); - if (pickedObject == null) + if (pickedObject == null) { return null; + } return pickedObject; } @@ -112,31 +110,34 @@ public PickedObject getTopObject(DrawContext dc, Point pickPoint) * rectangle and does not attempt to determine which picked objects intersect it. This does nothing if no picked * objects are currently registered with this PickSupport. * - * @param dc the draw context which receives the picked object. + * @param dc the draw context which receives the picked object. * @param pickPoint the point in AWT screen coordinates. - * @param layer the layer associated with the picked object. + * @param layer the layer associated with the picked object. * * @return the picked object added to the draw context, or null if no picked object is drawn at the - * specified point. + * specified point. */ - public PickedObject resolvePick(DrawContext dc, Point pickPoint, Layer layer) - { + public PickedObject resolvePick(DrawContext dc, Point pickPoint, Layer layer) { if (!this.hasPickableObjects()) // avoid reading the current GL color when no pickable objects are registered + { return null; + } PickedObject po = null; // Resolve the object at the pick point, if any, adding it to the draw context's list of objects at the pick // point. If any object is at the pick point we return it. Note that the pick point can be null when the pick // rectangle is specified but the pick point is not. - if (pickPoint != null) + if (pickPoint != null) { po = this.doResolvePick(dc, pickPoint, layer); + } // Resolve the objects in the pick rectangle, if any, adding them to the draw context's list of objects // intersecting the pick rectangle. Note that the pick rectangle can be null when the pick point is specified // but the pick rectangle is not. - if (dc.getPickRectangle() != null && !dc.getPickRectangle().isEmpty()) + if (dc.getPickRectangle() != null && !dc.getPickRectangle().isEmpty()) { this.doResolvePick(dc, dc.getPickRectangle(), layer); + } this.clearPickList(); @@ -147,20 +148,19 @@ public PickedObject resolvePick(DrawContext dc, Point pickPoint, Layer layer) * Adds a picked object registered with this PickSupport that is drawn at the specified point in AWT screen * coordinates (if one exists) to the draw context's list of picked objects. * - * @param dc the draw context which receives the picked object. + * @param dc the draw context which receives the picked object. * @param pickPoint the point in AWT screen coordinates. - * @param layer the layer associated with the picked object. + * @param layer the layer associated with the picked object. * * @return the picked object added to the draw context, or null if no picked object is drawn at the - * specified point. + * specified point. */ - protected PickedObject doResolvePick(DrawContext dc, Point pickPoint, Layer layer) - { + protected PickedObject doResolvePick(DrawContext dc, Point pickPoint, Layer layer) { PickedObject pickedObject = this.getTopObject(dc, pickPoint); - if (pickedObject != null) - { - if (layer != null) + if (pickedObject != null) { + if (layer != null) { pickedObject.setParentLayer(layer); + } dc.addPickedObject(pickedObject); } @@ -172,32 +172,35 @@ protected PickedObject doResolvePick(DrawContext dc, Point pickPoint, Layer laye * Adds all picked objects that are registered with this PickSupport and intersect the specified rectangle in AWT * screen coordinates (if any) to the draw context's list of picked objects. * - * @param dc the draw context which receives the picked objects. + * @param dc the draw context which receives the picked objects. * @param pickRect the rectangle in AWT screen coordinates. - * @param layer the layer associated with the picked objects. + * @param layer the layer associated with the picked objects. */ - protected void doResolvePick(DrawContext dc, Rectangle pickRect, Layer layer) - { + protected void doResolvePick(DrawContext dc, Rectangle pickRect, Layer layer) { // Get the unique pick colors in the specified screen rectangle. Use the minimum and maximum color codes to cull // the number of colors that the draw context must consider with identifying the unique pick colors in the // specified rectangle. int[] colorCodes = dc.getPickColorsInRectangle(pickRect, this.minAndMaxColorCodes); - if (colorCodes == null || colorCodes.length == 0) + if (colorCodes == null || colorCodes.length == 0) { return; + } // Lookup the pickable object (if any) for each unique color code appearing in the pick rectangle. Each picked // object that corresponds to a picked color is added to the draw context. - for (int colorCode : colorCodes) - { + for (int colorCode : colorCodes) { if (colorCode == 0) // This should never happen, but we check anyway. + { continue; + } PickedObject po = this.lookupPickableObject(colorCode); - if (po == null) + if (po == null) { continue; + } - if (layer != null) + if (layer != null) { po.setParentLayer(layer); + } dc.addObjectInPickRectangle(po); } @@ -212,20 +215,18 @@ protected void doResolvePick(DrawContext dc, Rectangle pickRect, Layer layer) * This returns 0 if the point is null, if the point contains the clear color, or if the point is * outside the draw context's drawable area. * - * @param dc the draw context to return a color for. + * @param dc the draw context to return a color for. * @param pickPoint the point to return a color for, in AWT screen coordinates. * * @return the RGB color corresponding to the specified point. */ - public int getTopColor(DrawContext dc, Point pickPoint) - { + public int getTopColor(DrawContext dc, Point pickPoint) { // This method's implementation has been moved into DrawContext.getPickColor in order to consolidate this logic // into one place. We've left this method here to avoid removing an interface that applications may rely on. return pickPoint != null ? dc.getPickColorAtPoint(pickPoint) : 0; } - public void beginPicking(DrawContext dc) - { + public void beginPicking(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glPushAttrib(GL2.GL_ENABLE_BIT | GL2.GL_CURRENT_BIT); @@ -236,12 +237,12 @@ public void beginPicking(DrawContext dc) gl.glDisable(GL.GL_BLEND); gl.glDisable(GL.GL_TEXTURE_2D); - if (dc.isDeepPickingEnabled()) + if (dc.isDeepPickingEnabled()) { gl.glDisable(GL.GL_DEPTH_TEST); + } } - public void endPicking(DrawContext dc) - { + public void endPicking(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glPopAttrib(); @@ -250,36 +251,33 @@ public void endPicking(DrawContext dc) gl.glColor3ub((byte) 255, (byte) 255, (byte) 255); } - protected Map getPickableObjects() - { + protected Map getPickableObjects() { return this.pickableObjects; } - protected Map getPickableObjectRanges() - { + protected Map getPickableObjectRanges() { return this.pickableObjectRanges; } - protected boolean hasPickableObjects() - { + protected boolean hasPickableObjects() { return this.getPickableObjects().size() > 0 || this.getPickableObjectRanges().size() > 0; } - protected PickedObject lookupPickableObject(int colorCode) - { + protected PickedObject lookupPickableObject(int colorCode) { // Try looking up the color code in the pickable object map. PickedObject po = this.getPickableObjects().get(colorCode); - if (po != null) + if (po != null) { return po; + } // Try matching the color code to one of the pickable object ranges. - for (Map.Entry entry : this.getPickableObjectRanges().entrySet()) - { + for (Map.Entry entry : this.getPickableObjectRanges().entrySet()) { Range range = entry.getKey(); PickedObjectFactory factory = entry.getValue(); - if (range.contains(colorCode) && factory != null) + if (range.contains(colorCode) && factory != null) { return factory.createPickedObject(colorCode); + } } return null; @@ -292,16 +290,16 @@ protected PickedObject lookupPickableObject(int colorCode) * * @param colorCode the code used to adjust the current min and max codes. */ - protected void adjustExtremeColorCodes(int colorCode) - { - if (this.minAndMaxColorCodes == null) - this.minAndMaxColorCodes = new int[] {colorCode, colorCode}; - else - { - if (this.minAndMaxColorCodes[0] > colorCode) + protected void adjustExtremeColorCodes(int colorCode) { + if (this.minAndMaxColorCodes == null) { + this.minAndMaxColorCodes = new int[]{colorCode, colorCode}; + } else { + if (this.minAndMaxColorCodes[0] > colorCode) { this.minAndMaxColorCodes[0] = colorCode; - if (this.minAndMaxColorCodes[1] < colorCode) + } + if (this.minAndMaxColorCodes[1] < colorCode) { this.minAndMaxColorCodes[1] = colorCode; + } } } @@ -313,8 +311,7 @@ protected void adjustExtremeColorCodes(int colorCode) * * @return true if both objects are not null and they refer to the same user object, otherwise false. */ - public static boolean areSelectionsTheSame(PickedObject a, PickedObject b) - { + public static boolean areSelectionsTheSame(PickedObject a, PickedObject b) { return a != null && b != null && a.getObject() == b.getObject(); } } diff --git a/src/gov/nasa/worldwind/pick/PickedObject.java b/src/gov/nasa/worldwind/pick/PickedObject.java index 7149476a47..baa72eb3b8 100644 --- a/src/gov/nasa/worldwind/pick/PickedObject.java +++ b/src/gov/nasa/worldwind/pick/PickedObject.java @@ -15,16 +15,15 @@ * @author lado * @version $Id: PickedObject.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PickedObject extends AVListImpl -{ +public class PickedObject extends AVListImpl { + private final Point pickPoint; private final int colorCode; private final Object userObject; private boolean isOnTop = false; private boolean isTerrain = false; - public PickedObject(int colorCode, Object userObject) - { + public PickedObject(int colorCode, Object userObject) { super(); this.pickPoint = null; @@ -34,8 +33,7 @@ public PickedObject(int colorCode, Object userObject) this.isTerrain = false; } - public PickedObject(int colorCode, Object userObject, Position position, boolean isTerrain) - { + public PickedObject(int colorCode, Object userObject, Position position, boolean isTerrain) { super(); this.pickPoint = null; @@ -47,8 +45,7 @@ public PickedObject(int colorCode, Object userObject, Position position, boolean } public PickedObject(Point pickPoint, int colorCode, Object userObject, Angle lat, Angle lon, double elev, - boolean isTerrain) - { + boolean isTerrain) { super(); this.pickPoint = pickPoint; @@ -59,83 +56,75 @@ public PickedObject(Point pickPoint, int colorCode, Object userObject, Angle lat this.setPosition(new Position(lat, lon, elev)); } - public Point getPickPoint() - { + public Point getPickPoint() { return pickPoint; } - public int getColorCode() - { + public int getColorCode() { return this.colorCode; } - public Object getObject() - { + public Object getObject() { return userObject; } - public void setOnTop() - { + public void setOnTop() { this.isOnTop = true; } - public boolean isOnTop() - { + public boolean isOnTop() { return this.isOnTop; } - public boolean isTerrain() - { + public boolean isTerrain() { return this.isTerrain; } - public void setParentLayer(Layer layer) - { + public void setParentLayer(Layer layer) { this.setValue(AVKey.PICKED_OBJECT_PARENT_LAYER, layer); } - public Layer getParentLayer() - { + public Layer getParentLayer() { return (Layer) this.getValue(AVKey.PICKED_OBJECT_PARENT_LAYER); } - public void setPosition(Position position) - { + public void setPosition(Position position) { this.setValue(AVKey.POSITION, position); } - public Position getPosition() - { + public Position getPosition() { return (Position) this.getValue(AVKey.POSITION); } - public boolean hasPosition() - { + public boolean hasPosition() { return this.hasKey(AVKey.POSITION); } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } PickedObject that = (PickedObject) o; - if (colorCode != that.colorCode) + if (colorCode != that.colorCode) { return false; - if (isOnTop != that.isOnTop) + } + if (isOnTop != that.isOnTop) { return false; + } //noinspection RedundantIfStatement - if (userObject != null ? !userObject.equals(that.userObject) : that.userObject != null) + if (userObject != null ? !userObject.equals(that.userObject) : that.userObject != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result; result = colorCode; result = 31 * result + (userObject != null ? userObject.hashCode() : 0); diff --git a/src/gov/nasa/worldwind/pick/PickedObjectFactory.java b/src/gov/nasa/worldwind/pick/PickedObjectFactory.java index d011cd1edf..b2c9787aa2 100644 --- a/src/gov/nasa/worldwind/pick/PickedObjectFactory.java +++ b/src/gov/nasa/worldwind/pick/PickedObjectFactory.java @@ -16,8 +16,8 @@ * @author dcollins * @version $Id: PickedObjectFactory.java 2281 2014-08-29 23:08:04Z dcollins $ */ -public interface PickedObjectFactory -{ +public interface PickedObjectFactory { + /** * Create a picked object from the specified pick color code. * diff --git a/src/gov/nasa/worldwind/pick/PickedObjectList.java b/src/gov/nasa/worldwind/pick/PickedObjectList.java index 981f349343..1c1fc9b3b0 100644 --- a/src/gov/nasa/worldwind/pick/PickedObjectList.java +++ b/src/gov/nasa/worldwind/pick/PickedObjectList.java @@ -11,10 +11,9 @@ * @author tag * @version $Id: PickedObjectList.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PickedObjectList extends ArrayList -{ - public PickedObjectList() - { +public class PickedObjectList extends ArrayList { + + public PickedObjectList() { } public PickedObjectList(PickedObjectList list) // clone a shallow copy @@ -22,46 +21,40 @@ public PickedObjectList(PickedObjectList list) // clone a shallow copy super(list); } - public PickedObject getTopPickedObject() - { + public PickedObject getTopPickedObject() { int size = this.size(); - if (1 < size) - { - for (PickedObject po : this) - { - if (po.isOnTop()) + if (1 < size) { + for (PickedObject po : this) { + if (po.isOnTop()) { return po; + } } } - if (0 < size) - { // if we are here, then no objects were mark as 'top' + if (0 < size) { // if we are here, then no objects were mark as 'top' return this.get(0); } return null; } - public Object getTopObject() - { + public Object getTopObject() { PickedObject po = this.getTopPickedObject(); return po != null ? po.getObject() : null; } - public PickedObject getTerrainObject() - { - for (PickedObject po : this) - { - if (po.isTerrain()) + public PickedObject getTerrainObject() { + for (PickedObject po : this) { + if (po.isTerrain()) { return po; + } } return null; } - public PickedObject getMostRecentPickedObject() - { + public PickedObject getMostRecentPickedObject() { return this.size() > 0 ? this.get(this.size() - 1) : null; } @@ -71,16 +64,14 @@ public PickedObject getMostRecentPickedObject() * * @return a new list of the picked objects marked as on top, or null if nothing is marked as on top. */ - public List getAllTopPickedObjects() - { + public List getAllTopPickedObjects() { List list = null; // Lazily create the list to avoid unnecessary allocations. - for (PickedObject po : this) - { - if (po.isOnTop()) - { - if (list == null) + for (PickedObject po : this) { + if (po.isOnTop()) { + if (list == null) { list = new ArrayList(); + } list.add(po); } } @@ -93,18 +84,16 @@ public List getAllTopPickedObjects() * returns null if this list is empty, or does not contain any picked objects marked as on top. * * @return a new list of the objects associated with a picked object marked as on top, or null if - * nothing is marked as on top. + * nothing is marked as on top. */ - public List getAllTopObjects() - { + public List getAllTopObjects() { List list = null; // Lazily create the list to avoid unnecessary allocations. - for (PickedObject po : this) - { - if (po.isOnTop()) - { - if (list == null) + for (PickedObject po : this) { + if (po.isOnTop()) { + if (list == null) { list = new ArrayList(); + } list.add(po.getObject()); } } @@ -112,8 +101,7 @@ public List getAllTopObjects() return list; } - public boolean hasNonTerrainObjects() - { + public boolean hasNonTerrainObjects() { return this.size() > 1 || (this.size() == 1 && this.getTerrainObject() == null); } } diff --git a/src/gov/nasa/worldwind/poi/BasicPointOfInterest.java b/src/gov/nasa/worldwind/poi/BasicPointOfInterest.java index 40c7204d46..f5311ed1f0 100644 --- a/src/gov/nasa/worldwind/poi/BasicPointOfInterest.java +++ b/src/gov/nasa/worldwind/poi/BasicPointOfInterest.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.poi; import gov.nasa.worldwind.WWObjectImpl; @@ -14,26 +13,24 @@ * @author tag * @version $Id: BasicPointOfInterest.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicPointOfInterest extends WWObjectImpl implements PointOfInterest -{ - public BasicPointOfInterest(LatLon latlon) - { +public class BasicPointOfInterest extends WWObjectImpl implements PointOfInterest { + + public BasicPointOfInterest(LatLon latlon) { this.latlon = latlon; } protected final LatLon latlon; - public LatLon getLatlon() - { + public LatLon getLatlon() { return latlon; } - public String toString() - { + public String toString() { String str = this.getStringValue(AVKey.DISPLAY_NAME); - if (str != null) + if (str != null) { return str; - else + } else { return latlon.toString(); + } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/poi/Gazetteer.java b/src/gov/nasa/worldwind/poi/Gazetteer.java index ecd8746f54..6c9b28f99d 100644 --- a/src/gov/nasa/worldwind/poi/Gazetteer.java +++ b/src/gov/nasa/worldwind/poi/Gazetteer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.poi; import gov.nasa.worldwind.exception.*; @@ -16,8 +15,8 @@ * @author tag * @version $Id: Gazetteer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Gazetteer -{ +public interface Gazetteer { + /** * Find places identified in a string of free text. * @@ -25,7 +24,7 @@ public interface Gazetteer * * @return the points-of-interest that match the place description. * - * @throws NoItemException if the place description cannot be matched. + * @throws NoItemException if the place description cannot be matched. * @throws ServiceException if the lookup service is not available or invocation of it fails. */ public List findPlaces(String placeInfo) throws NoItemException, ServiceException; diff --git a/src/gov/nasa/worldwind/poi/POIUtils.java b/src/gov/nasa/worldwind/poi/POIUtils.java index 4fa4649b02..5bf738be22 100644 --- a/src/gov/nasa/worldwind/poi/POIUtils.java +++ b/src/gov/nasa/worldwind/poi/POIUtils.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.poi; import gov.nasa.worldwind.exception.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: POIUtils.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class POIUtils -{ +public class POIUtils { + protected static final String DEFAULT_CHARSET_NAME = "UTF-8"; /** @@ -28,18 +27,17 @@ public class POIUtils * * @param urlString the URL to use to invoke the service. * @return the service results. - * @throws NoItemException if HTTP_BAD_REQUEST is returned from the service. + * @throws NoItemException if HTTP_BAD_REQUEST is returned from the service. * @throws ServiceException if there is a problem invoking the service or retrieving its results. */ - public static String callService(String urlString) throws NoItemException, ServiceException - { - if (urlString == null || urlString.length() < 1) + public static String callService(String urlString) throws NoItemException, ServiceException { + if (urlString == null || urlString.length() < 1) { return null; + } InputStream inputStream = null; - try - { + try { URL url = new URL(urlString); URLConnection connection = url.openConnection(); @@ -48,67 +46,52 @@ public static String callService(String urlString) throws NoItemException, Servi String responseMessage = htpc.getResponseMessage(); String contentType = htpc.getContentType(); - if (responseCode == HttpURLConnection.HTTP_OK) - { + if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); ByteBuffer buffer = WWIO.readStreamToBuffer(inputStream); String charsetName = getCharsetName(contentType); return decodeBuffer(buffer, charsetName); - } - else if (responseCode == HttpURLConnection.HTTP_BAD_REQUEST) - { + } else if (responseCode == HttpURLConnection.HTTP_BAD_REQUEST) { throw new NoItemException(responseMessage); - } - else - { + } else { throw new ServiceException(responseMessage); } - } - catch (MalformedURLException e) // occurs only if protocol of URL is unknown + } catch (MalformedURLException e) // occurs only if protocol of URL is unknown { String msg = Logging.getMessage("generic.MalformedURL", urlString); Logging.logger().log(java.util.logging.Level.SEVERE, msg); throw new WWRuntimeException(msg); - } - catch (IOException e) - { + } catch (IOException e) { String msg = Logging.getMessage("POI.ServiceError", urlString); Logging.logger().log(java.util.logging.Level.SEVERE, msg); throw new ServiceException(msg); - } - finally - { + } finally { WWIO.closeStream(inputStream, urlString); } } - protected static String decodeBuffer(ByteBuffer buffer, String charsetName) - { + protected static String decodeBuffer(ByteBuffer buffer, String charsetName) { byte[] bytes = new byte[buffer.limit()]; buffer.get(bytes); - try - { + try { return new String(bytes, charsetName); - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { return new String(bytes); } } - protected static String getCharsetName(String contentType) - { - if (contentType == null || contentType.toLowerCase().indexOf("charset") == -1) + protected static String getCharsetName(String contentType) { + if (contentType == null || contentType.toLowerCase().indexOf("charset") == -1) { return DEFAULT_CHARSET_NAME; + } String[] pairs = contentType.split(";"); - for (String pair : pairs) - { - if (pair.toLowerCase().trim().startsWith("charset")) - { + for (String pair : pairs) { + if (pair.toLowerCase().trim().startsWith("charset")) { String[] av = pair.split("="); - if (av.length > 1 && av[1].trim().length() > 0) + if (av.length > 1 && av[1].trim().length() > 0) { return av[1].trim(); + } } } diff --git a/src/gov/nasa/worldwind/poi/PointOfInterest.java b/src/gov/nasa/worldwind/poi/PointOfInterest.java index de65f948c1..8e2b71ce0f 100644 --- a/src/gov/nasa/worldwind/poi/PointOfInterest.java +++ b/src/gov/nasa/worldwind/poi/PointOfInterest.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.poi; import gov.nasa.worldwind.WWObject; @@ -13,7 +12,7 @@ * @author tag * @version $Id: PointOfInterest.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface PointOfInterest extends WWObject -{ +public interface PointOfInterest extends WWObject { + LatLon getLatlon(); } diff --git a/src/gov/nasa/worldwind/poi/YahooGazetteer.java b/src/gov/nasa/worldwind/poi/YahooGazetteer.java index 76db9797df..6e3f0a5d11 100644 --- a/src/gov/nasa/worldwind/poi/YahooGazetteer.java +++ b/src/gov/nasa/worldwind/poi/YahooGazetteer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.poi; import gov.nasa.worldwind.avlist.*; @@ -24,52 +23,44 @@ * @author tag * @version $Id: YahooGazetteer.java 1395 2013-06-03 22:59:07Z tgaskins $ */ -public class YahooGazetteer implements Gazetteer -{ - protected static final String GEOCODE_SERVICE = - "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D"; - - public List findPlaces(String lookupString) throws NoItemException, ServiceException - { - if (lookupString == null || lookupString.length() < 1) - { +public class YahooGazetteer implements Gazetteer { + + protected static final String GEOCODE_SERVICE + = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D"; + + public List findPlaces(String lookupString) throws NoItemException, ServiceException { + if (lookupString == null || lookupString.length() < 1) { return null; } String urlString; - try - { + try { urlString = GEOCODE_SERVICE + "%22" + URLEncoder.encode(lookupString, "UTF-8") + "%22"; - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { urlString = GEOCODE_SERVICE + "%22" + lookupString.replaceAll(" ", "+") + "%22"; } - if (isNumber(lookupString)) + if (isNumber(lookupString)) { lookupString += "%20and%20gflags%3D%22R%22"; + } String locationString = POIUtils.callService(urlString); - if (locationString == null || locationString.length() < 1) - { + if (locationString == null || locationString.length() < 1) { return null; } return this.parseLocationString(locationString); } - protected boolean isNumber(String lookupString) - { + protected boolean isNumber(String lookupString) { lookupString = lookupString.trim(); return lookupString.startsWith("-") || lookupString.startsWith("+") || Character.isDigit(lookupString.charAt(0)); } - protected ArrayList parseLocationString(String locationString) throws WWRuntimeException - { - try - { + protected ArrayList parseLocationString(String locationString) throws WWRuntimeException { + try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(false); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); @@ -78,13 +69,12 @@ protected ArrayList parseLocationString(String locationString) XPathFactory xpFactory = XPathFactory.newInstance(); XPath xpath = xpFactory.newXPath(); - org.w3c.dom.NodeList resultNodes = - (org.w3c.dom.NodeList) xpath.evaluate("/query/results/place", doc, XPathConstants.NODESET); + org.w3c.dom.NodeList resultNodes + = (org.w3c.dom.NodeList) xpath.evaluate("/query/results/place", doc, XPathConstants.NODESET); ArrayList positions = new ArrayList(resultNodes.getLength()); - for (int i = 0; i < resultNodes.getLength(); i++) - { + for (int i = 0; i < resultNodes.getLength(); i++) { org.w3c.dom.Node location = resultNodes.item(i); String lat = xpath.evaluate("centroid/latitude", location); String lon = xpath.evaluate("centroid/longitude", location); @@ -95,31 +85,25 @@ protected ArrayList parseLocationString(String locationString) String locality = xpath.evaluate("locality1", location); String admin = xpath.evaluate("admin1", location); - if (placeType != null && !placeType.equals("")) - { + if (placeType != null && !placeType.equals("")) { displayName.append(placeType); displayName.append(": "); } - if (name != null && !name.equals("")) - { + if (name != null && !name.equals("")) { displayName.append(name); displayName.append(". "); } - if (locality != null && !locality.equals("")) - { + if (locality != null && !locality.equals("")) { displayName.append(locality); displayName.append(", "); } - if (admin != null && !admin.equals("")) - { + if (admin != null && !admin.equals("")) { displayName.append(admin); displayName.append(", "); } displayName.append(xpath.evaluate("country", location)); - - if (lat != null && lon != null) - { + if (lat != null && lon != null) { LatLon latlon = LatLon.fromDegrees(Double.parseDouble(lat), Double.parseDouble(lon)); PointOfInterest loc = new BasicPointOfInterest(latlon); loc.setValue(AVKey.DISPLAY_NAME, displayName.toString()); @@ -128,9 +112,7 @@ protected ArrayList parseLocationString(String locationString) } return positions; - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("Gazetteer.URLException", locationString); Logging.logger().log(Level.SEVERE, msg); throw new WWRuntimeException(msg); diff --git a/src/gov/nasa/worldwind/render/AbstractAnnotation.java b/src/gov/nasa/worldwind/render/AbstractAnnotation.java index caf15264b4..6c0f76040c 100644 --- a/src/gov/nasa/worldwind/render/AbstractAnnotation.java +++ b/src/gov/nasa/worldwind/render/AbstractAnnotation.java @@ -16,12 +16,13 @@ /** * An {@link Annotation} represent a text label and its rendering attributes. Annotations must be attached either to a - * globe Position ({@link GlobeAnnotation}) or a viewport Point (ScreenAnnotation). + * globe Position ({@link GlobeAnnotation}) or a viewport Point (ScreenAnnotation). *
            * GlobeAnnotation ga = new  GlobeAnnotation("Lat-Lon zero", Position.fromDegrees(0, 0, 0)));
            * ScreenAnnotation sa = new ScreenAnnotation("Message...", new Point(10,10));
            * 
          - *

          Each Annotation refers to an {@link AnnotationAttributes} object which defines how the text will be rendered. + *

          + * Each Annotation refers to an {@link AnnotationAttributes} object which defines how the text will be rendered. *

          Rendering attributes allow to set:
          • the size of the bounding rectangle into which the text will be * displayed
          • its frame shape, border color, width and stippling pattern
          • the text font, size, style and * color
          • the background color or image
          • how much an annotation scales and fades with distance
          • @@ -31,35 +32,42 @@ * ga.getAttributes().setFont(Font.decode("Arial-BOLD-24"); * ... * - *

            Annotations are usually handled by an {@link gov.nasa.worldwind.layers.AnnotationLayer}. Although they also - * implement the {@link Renderable} interface and thus can be handled by a {@link gov.nasa.worldwind.layers.RenderableLayer} - * too. + *

            + * Annotations are usually handled by an {@link gov.nasa.worldwind.layers.AnnotationLayer}. Although they also implement + * the {@link Renderable} interface and thus can be handled by a {@link gov.nasa.worldwind.layers.RenderableLayer} too. *

              * AnnotationLayer layer = new AnnotationLayer();
              * layer.addAnnotation(new GlobeAnnotation("Text...", Position.fromDegrees(0, 0, 0)));
              * 
            - *

            Each Annotation starts its life with a fresh attribute set that can be altered to produce the desired effect. + *

            + * Each Annotation starts its life with a fresh attribute set that can be altered to produce the desired effect. * However, AnnotationAttributes can be set and shared between annotations allowing to control the - * rendering attributes of many annotations from a single AnnotationAttributes object. + * rendering attributes of many annotations from a single AnnotationAttributes object. *

              * AnnotationAttributes attr = new AnnotationAttributes();
              * attr.setTextColor(Color.WHITE);
              * attr.setFont(Font.decode("Arial-BOLD-24");
              * ga.setAttributes(attr);
              * 
            - *

            In the above example changing the text color of the attributes set will affect all annotations referring it. - * However, changing the text color of one of those annotations will also affect all others since it will in fact change - * the common attributes set.

            To use an attributes object only as default values for a series of annotations use: + *

            + * In the above example changing the text color of the attributes set will affect all annotations referring it. However, + * changing the text color of one of those annotations will also affect all others since it will in fact change the + * common attributes set. + *

            + * To use an attributes object only as default values for a series of annotations use: *

            *
              * ga.getAttributes().setDefaults(attr);
              * 
            - *

            which can also be done in the Annotation constructor: + *

            + * which can also be done in the Annotation constructor: *

              * GlobeAnnotation ga = new GlobeAnnotation(text, position, attr);
              * 
            - *

            Finer control over attributes inheritance can be achieved using default or fallback attributes set.

            Most - * attributes can be set to a 'use default' value which is minus one for numeric values and null for + *

            + * Finer control over attributes inheritance can be achieved using default or fallback attributes set. + *

            + * Most attributes can be set to a 'use default' value which is minus one for numeric values and null for * attributes referring objects (colors, dimensions, insets..). In such a case the value of an attribute will be that of * the default attribute set. New annotations have all their attributes set to use default values.

            *

            @@ -88,15 +96,17 @@ * Saint Helens attributes could be changed without affecting other mountains. However, changes on the geoFeatures * attributes would affect all mountains and lakes. *

            - * Background images are specified by setting the Annotation attribute {@link gov.nasa.worldwind.render.AnnotationAttributes#setImageSource(Object)}. - * The source can be either a path to a valid image file, or a {@link java.awt.image.BufferedImage}. By default, - * background images are aligned with the annotation as follows: the image's upper left corner is aligned with the - * annotation's upper left corner, and the image's lower right corner is aligned with a point (imageWidth, + * Background images are specified by setting the Annotation attribute + * {@link gov.nasa.worldwind.render.AnnotationAttributes#setImageSource(Object)}. The source can be either a path to a + * valid image file, or a {@link java.awt.image.BufferedImage}. By default, background images are aligned with the + * annotation as follows: the image's upper left corner is aligned with the annotation's upper left corner, and the + * image's lower right corner is aligned with a point (imageWidth, * imageHeight) pixels right and down from the annotation's upper left corner. Thus the background image * coordinate system has its origin at the annotation's upper left corner, has the +X axis pointing to the right, and * has the +Y axis pointing down. Units are in image pixels, where one image pixel corresponds to one screen pixel. The - * background image may be translated or scaled by setting the attributes {@link gov.nasa.worldwind.render.AnnotationAttributes#setImageOffset(java.awt.Point)} - * and {@link gov.nasa.worldwind.render.AnnotationAttributes#setImageScale(double)}, respectively. The offset attribute + * background image may be translated or scaled by setting the attributes + * {@link gov.nasa.worldwind.render.AnnotationAttributes#setImageOffset(java.awt.Point)} and + * {@link gov.nasa.worldwind.render.AnnotationAttributes#setImageScale(double)}, respectively. The offset attribute * defines an offset right and down in background image coordinates. The scale attribute is unitless, and defines the * background image's magnification or minification factor relative to the annotation. For example, a scale of * 0.5 indicates the image should be 1/2 its original size relative to the annotation, while a scale of @@ -122,8 +132,8 @@ * @see AnnotationAttributes * @see AnnotationRenderer */ -public abstract class AbstractAnnotation extends AVListImpl implements Annotation -{ +public abstract class AbstractAnnotation extends AVListImpl implements Annotation { + protected boolean alwaysOnTop; protected boolean pickEnabled; protected String text; @@ -141,8 +151,7 @@ public abstract class AbstractAnnotation extends AVListImpl implements Annotatio protected double minActiveAltitude = -Double.MAX_VALUE; protected double maxActiveAltitude = Double.MAX_VALUE; - protected AbstractAnnotation() - { + protected AbstractAnnotation() { this.alwaysOnTop = false; this.pickEnabled = true; this.attributes = new AnnotationAttributes(); @@ -153,35 +162,28 @@ protected AbstractAnnotation() this.textBoundsMap = new java.util.HashMap(); } - public boolean isAlwaysOnTop() - { + public boolean isAlwaysOnTop() { return alwaysOnTop; } - public void setAlwaysOnTop(boolean alwaysOnTop) - { + public void setAlwaysOnTop(boolean alwaysOnTop) { this.alwaysOnTop = alwaysOnTop; } - public boolean isPickEnabled() - { + public boolean isPickEnabled() { return this.pickEnabled; } - public void setPickEnabled(boolean enable) - { + public void setPickEnabled(boolean enable) { this.pickEnabled = enable; } - public String getText() - { + public String getText() { return this.text; } - public void setText(String text) - { - if (text == null) - { + public void setText(String text) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -190,15 +192,12 @@ public void setText(String text) this.text = text; } - public AnnotationAttributes getAttributes() - { + public AnnotationAttributes getAttributes() { return this.attributes; } - public void setAttributes(AnnotationAttributes attributes) - { - if (attributes == null) - { + public void setAttributes(AnnotationAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AnnotationAttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -207,35 +206,28 @@ public void setAttributes(AnnotationAttributes attributes) this.attributes = attributes; } - public double getMinActiveAltitude() - { + public double getMinActiveAltitude() { return this.minActiveAltitude; } - public void setMinActiveAltitude(double minActiveAltitude) - { + public void setMinActiveAltitude(double minActiveAltitude) { this.minActiveAltitude = minActiveAltitude; } - public double getMaxActiveAltitude() - { + public double getMaxActiveAltitude() { return maxActiveAltitude; } - public void setMaxActiveAltitude(double maxActiveAltitude) - { + public void setMaxActiveAltitude(double maxActiveAltitude) { this.maxActiveAltitude = maxActiveAltitude; } - public java.util.List getChildren() - { + public java.util.List getChildren() { return java.util.Collections.unmodifiableList(this.childList); } - public void addChild(Annotation annotation) - { - if (annotation == null) - { + public void addChild(Annotation annotation) { + if (annotation == null) { String message = Logging.getMessage("nullValue.AnnotationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -244,10 +236,8 @@ public void addChild(Annotation annotation) this.childList.add(annotation); } - public boolean removeChild(Annotation annotation) - { - if (annotation == null) - { + public boolean removeChild(Annotation annotation) { + if (annotation == null) { String message = Logging.getMessage("nullValue.AnnotationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -256,20 +246,16 @@ public boolean removeChild(Annotation annotation) return this.childList.remove(annotation); } - public void removeAllChildren() - { + public void removeAllChildren() { this.childList.clear(); } - public AnnotationLayoutManager getLayout() - { + public AnnotationLayoutManager getLayout() { return this.layoutManager; } - public void setLayout(AnnotationLayoutManager layoutManager) - { - if (layoutManager == null) - { + public void setLayout(AnnotationLayoutManager layoutManager) { + if (layoutManager == null) { String message = Logging.getMessage("nullValue.LayoutIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -278,15 +264,12 @@ public void setLayout(AnnotationLayoutManager layoutManager) this.layoutManager = layoutManager; } - public PickSupport getPickSupport() - { + public PickSupport getPickSupport() { return this.pickSupport; } - public void setPickSupport(PickSupport pickSupport) - { - if (pickSupport == null) - { + public void setPickSupport(PickSupport pickSupport) { + if (pickSupport == null) { String message = Logging.getMessage("nullValue.PickSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -295,13 +278,11 @@ public void setPickSupport(PickSupport pickSupport) this.pickSupport = pickSupport; } - public Object getDelegateOwner() - { + public Object getDelegateOwner() { return delegateOwner; } - public void setDelegateOwner(Object delegateOwner) - { + public void setDelegateOwner(Object delegateOwner) { this.delegateOwner = delegateOwner; } @@ -310,17 +291,16 @@ public void setDelegateOwner(Object delegateOwner) * * @param dc the current DrawContext. */ - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.getAttributes().isVisible()) + if (!this.getAttributes().isVisible()) { return; + } dc.getAnnotationRenderer().render(dc, this, null, dc.getCurrentLayer()); } @@ -328,35 +308,32 @@ public void render(DrawContext dc) /** * Pick at the annotation. Called as a Pickable. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param pickPoint the screen coordinate point. */ - public void pick(DrawContext dc, java.awt.Point pickPoint) - { - if (dc == null) - { + public void pick(DrawContext dc, java.awt.Point pickPoint) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.getAttributes().isVisible()) + if (!this.getAttributes().isVisible()) { return; + } - if (!this.isPickEnabled()) + if (!this.isPickEnabled()) { return; + } dc.getAnnotationRenderer().pick(dc, this, null, pickPoint, null); } - public void dispose() - { + public void dispose() { } - public java.awt.Dimension getPreferredSize(DrawContext dc) - { - if (dc == null) - { + public java.awt.Dimension getPreferredSize(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -364,10 +341,12 @@ public java.awt.Dimension getPreferredSize(DrawContext dc) // Clamp the caller specified size. java.awt.Dimension size = new java.awt.Dimension(this.getAttributes().getSize()); - if (size.width < 1) + if (size.width < 1) { size.width = 1; - if (size.height < 0) + } + if (size.height < 0) { size.height = 0; + } // Compute the size of this annotation's inset region. java.awt.Rectangle insetBounds = this.computeInsetBounds(size.width, size.height); @@ -382,32 +361,30 @@ public java.awt.Dimension getPreferredSize(DrawContext dc) java.awt.Insets insets = this.getAttributes().getInsets(); return new java.awt.Dimension( - insetSize.width + (insets.left + insets.right), - insetSize.height + (insets.top + insets.bottom)); + insetSize.width + (insets.left + insets.right), + insetSize.height + (insets.top + insets.bottom)); } - public void renderNow(DrawContext dc) - { - if (dc == null) - { + public void renderNow(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.getAttributes().isVisible()) + if (!this.getAttributes().isVisible()) { return; + } - if (dc.isPickingMode() && !this.isPickEnabled()) + if (dc.isPickingMode() && !this.isPickEnabled()) { return; + } this.doRenderNow(dc); } - public void draw(DrawContext dc, int width, int height, double opacity, Position pickPosition) - { - if (dc == null) - { + public void draw(DrawContext dc, int width, int height, double opacity, Position pickPosition) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -418,10 +395,8 @@ public void draw(DrawContext dc, int width, int height, double opacity, Position } protected void drawTopLevelAnnotation(DrawContext dc, int x, int y, int width, int height, double scale, - double opacity, Position pickPosition) - { - if (dc == null) - { + double opacity, Position pickPosition) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -429,20 +404,16 @@ protected void drawTopLevelAnnotation(DrawContext dc, int x, int y, int width, i OGLStackHandler stackHandler = new OGLStackHandler(); this.beginDraw(dc, stackHandler); - try - { + try { this.applyScreenTransform(dc, x, y, width, height, scale); this.draw(dc, width, height, opacity, pickPosition); - } - finally - { + } finally { this.endDraw(dc, stackHandler); } } @SuppressWarnings({"UnusedDeclaration"}) - protected void applyScreenTransform(DrawContext dc, int x, int y, int width, int height, double scale) - { + protected void applyScreenTransform(DrawContext dc, int x, int y, int width, int height, double scale) { double finalScale = scale * this.computeScale(dc); java.awt.Point offset = this.getAttributes().getDrawOffset(); @@ -454,13 +425,11 @@ protected void applyScreenTransform(DrawContext dc, int x, int y, int width, int } @SuppressWarnings({"UnusedDeclaration"}) - protected double computeScale(DrawContext dc) - { + protected double computeScale(DrawContext dc) { double scale = this.attributes.getScale(); // Factor in highlight scale. - if (this.attributes.isHighlighted()) - { + if (this.attributes.isHighlighted()) { scale *= this.attributes.getHighlightScale(); } @@ -468,13 +437,11 @@ protected double computeScale(DrawContext dc) } @SuppressWarnings({"UnusedDeclaration"}) - protected double computeOpacity(DrawContext dc) - { + protected double computeOpacity(DrawContext dc) { double opacity = this.attributes.getOpacity(); // Remove transparency if highlighted. - if (this.attributes.isHighlighted()) - { + if (this.attributes.isHighlighted()) { opacity = 1; } @@ -484,7 +451,6 @@ protected double computeOpacity(DrawContext dc) //**************************************************************// //******************** Rendering *****************************// //**************************************************************// - protected abstract void doRenderNow(DrawContext dc); protected abstract Rectangle computeBounds(DrawContext dc); @@ -502,17 +468,16 @@ protected double computeOpacity(DrawContext dc) * * @throws IllegalArgumentException if dc is null. */ - public java.awt.Rectangle getBounds(DrawContext dc) - { - if (dc == null) - { + public java.awt.Rectangle getBounds(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getView().getViewport() == null) + if (dc.getView().getViewport() == null) { return null; + } return this.computeBounds(dc); } @@ -521,44 +486,40 @@ public java.awt.Rectangle getBounds(DrawContext dc) * Draws an annotation with the given dimensions and opacity. Current GL state has ortho identity model view active * with origin at the screen point. * - * @param dc current DrawContext. - * @param width annotation callout width - * @param height annotation callout height - * @param opacity opacity to apply + * @param dc current DrawContext. + * @param width annotation callout width + * @param height annotation callout height + * @param opacity opacity to apply * @param pickPosition Position that will be associated with any PickedObject produced - * during picking. + * during picking. */ - protected void doDraw(DrawContext dc, int width, int height, double opacity, Position pickPosition) - { - if (!this.getAttributes().isVisible()) + protected void doDraw(DrawContext dc, int width, int height, double opacity, Position pickPosition) { + if (!this.getAttributes().isVisible()) { return; + } // If this annotation is not pickable, then do not draw any of its contents. However this annotation's children // may be pickable, so we still process them. - if (!dc.isPickingMode() || this.isPickEnabled()) - { + if (!dc.isPickingMode() || this.isPickEnabled()) { this.drawContent(dc, width, height, opacity, pickPosition); } this.drawChildren(dc, width, height, opacity, pickPosition); } - protected void drawContent(DrawContext dc, int width, int height, double opacity, Position pickPosition) - { + protected void drawContent(DrawContext dc, int width, int height, double opacity, Position pickPosition) { this.drawBackground(dc, width, height, opacity, pickPosition); this.drawBackgroundImage(dc, width, height, opacity, pickPosition); this.drawBorder(dc, width, height, opacity, pickPosition); this.drawText(dc, width, height, opacity, pickPosition); } - protected void beginDraw(DrawContext dc, OGLStackHandler stackHandler) - { + protected void beginDraw(DrawContext dc, OGLStackHandler stackHandler) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. stackHandler.pushModelviewIdentity(gl); } - protected void endDraw(DrawContext dc, OGLStackHandler stackHandler) - { + protected void endDraw(DrawContext dc, OGLStackHandler stackHandler) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. stackHandler.pop(gl); } @@ -566,11 +527,8 @@ protected void endDraw(DrawContext dc, OGLStackHandler stackHandler) //**************************************************************// //******************** Background Rendering ******************// //**************************************************************// - - protected void drawBackground(DrawContext dc, int width, int height, double opacity, Position pickPosition) - { - if (dc.isPickingMode()) - { + protected void drawBackground(DrawContext dc, int width, int height, double opacity, Position pickPosition) { + if (dc.isPickingMode()) { this.bindPickableObject(dc, pickPosition); } @@ -581,33 +539,30 @@ protected void drawBackground(DrawContext dc, int width, int height, double opac //**************************************************************// //******************** Background Image Rendering ************// //**************************************************************// - - protected void drawBackgroundImage(DrawContext dc, int width, int height, double opacity, Position pickPosition) - { - if (dc.isPickingMode()) + protected void drawBackgroundImage(DrawContext dc, int width, int height, double opacity, Position pickPosition) { + if (dc.isPickingMode()) { return; + } WWTexture texture = this.getAttributes().getBackgroundTexture(dc); - if (texture == null) + if (texture == null) { return; + } this.doDrawBackgroundTexture(dc, width, height, opacity, pickPosition, texture); } @SuppressWarnings({"UnusedDeclaration"}) protected void doDrawBackgroundTexture(DrawContext dc, int width, int height, double opacity, Position pickPosition, - WWTexture texture) - { + WWTexture texture) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Save the current texture matrix state, and configure the texture matrix with the identity matrix. gl.glMatrixMode(GL2.GL_TEXTURE); gl.glPushMatrix(); gl.glLoadIdentity(); - try - { - if (texture.bind(dc)) - { + try { + if (texture.bind(dc)) { // Enable OGL texture application. gl.glEnable(GL.GL_TEXTURE_2D); @@ -623,9 +578,7 @@ protected void doDrawBackgroundTexture(DrawContext dc, int width, int height, do // Draw the annotaiton callout with the background texture enabled. this.drawCallout(dc, GL.GL_TRIANGLE_FAN, width, height, true); } - } - finally - { + } finally { // Restore the previous texture matrix and the matrix mode. gl.glPopMatrix(); gl.glMatrixMode(GL2.GL_MODELVIEW); @@ -640,16 +593,15 @@ protected void doDrawBackgroundTexture(DrawContext dc, int width, int height, do @SuppressWarnings({"UnusedDeclaration"}) protected void applyBackgroundTextureState(DrawContext dc, int width, int height, double opacity, - WWTexture texture) - { + WWTexture texture) { GL gl = dc.getGL(); // Apply texture wrap state. String imageRepeat = this.getAttributes().getImageRepeat(); - int sWrap = (imageRepeat.equals(AVKey.REPEAT_X) || imageRepeat.equals(AVKey.REPEAT_XY)) ? - GL.GL_REPEAT : GL2.GL_CLAMP_TO_BORDER; - int tWrap = (imageRepeat.equals(AVKey.REPEAT_Y) || imageRepeat.equals(AVKey.REPEAT_XY)) ? - GL.GL_REPEAT : GL2.GL_CLAMP_TO_BORDER; + int sWrap = (imageRepeat.equals(AVKey.REPEAT_X) || imageRepeat.equals(AVKey.REPEAT_XY)) + ? GL.GL_REPEAT : GL2.GL_CLAMP_TO_BORDER; + int tWrap = (imageRepeat.equals(AVKey.REPEAT_Y) || imageRepeat.equals(AVKey.REPEAT_XY)) + ? GL.GL_REPEAT : GL2.GL_CLAMP_TO_BORDER; gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, sWrap); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, tWrap); @@ -665,12 +617,11 @@ protected void applyBackgroundTextureState(DrawContext dc, int width, int height * the image's upper left corner, and (imageWidth, imageHeight) maps to the image's lower right corner. * This assumes the current OGL matrix mode is GL_TEXTURE. * - * @param dc the DrawContext to receive the texture coordinate transform. + * @param dc the DrawContext to receive the texture coordinate transform. * @param texture the texture to transform from standard GL image coordinates to Annotation background image - * coordinates. + * coordinates. */ - protected void transformImageCoordsToBackgroundImageCoords(DrawContext dc, WWTexture texture) - { + protected void transformImageCoordsToBackgroundImageCoords(DrawContext dc, WWTexture texture) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Apply texture's internal transform state. This ensures we start with standard GL coordinates: the origin is @@ -693,16 +644,15 @@ protected void transformImageCoordsToBackgroundImageCoords(DrawContext dc, WWTex * height) maps to the Annotation's upper right corner in window coordinates (screen pixels). This assumes * the current OGL matrix mode is GL_TEXTURE. * - * @param dc the DrawContext to receive the texture coordinate transform. - * @param width the Annotation's width, in window coordinates (screen pixels). - * @param height the Annotation's height, in window coordinates (screen pixels). + * @param dc the DrawContext to receive the texture coordinate transform. + * @param width the Annotation's width, in window coordinates (screen pixels). + * @param height the Annotation's height, in window coordinates (screen pixels). * @param texture the texture to transform from Annotation background image coordinates to Annotation geometry - * coordinates. + * coordinates. */ @SuppressWarnings({"UnusedDeclaration"}) protected void transformBackgroundImageCoordsToAnnotationCoords(DrawContext dc, int width, int height, - WWTexture texture) - { + WWTexture texture) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Apply the Annotation's image scale. The scale is applied inversely because texture coordinates and the @@ -713,8 +663,7 @@ protected void transformBackgroundImageCoordsToAnnotationCoords(DrawContext dc, // Apply the Annotation's image offset in screen pixels. The offset is applied inversely because texture // coordinates and the texture's position on the Annotation are inversely related. java.awt.Point imageOffset = this.getAttributes().getImageOffset(); - if (imageOffset != null) - { + if (imageOffset != null) { gl.glTranslated(-imageOffset.x, -imageOffset.y, 0); } @@ -727,37 +676,30 @@ protected void transformBackgroundImageCoordsToAnnotationCoords(DrawContext dc, //**************************************************************// //******************** Border Rendering **********************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) - protected void drawBorder(DrawContext dc, int width, int height, double opacity, Position pickPosition) - { - if (this.getAttributes().getBorderWidth() <= 0) + protected void drawBorder(DrawContext dc, int width, int height, double opacity, Position pickPosition) { + if (this.getAttributes().getBorderWidth() <= 0) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Apply line smoothing state. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glDisable(GL.GL_LINE_SMOOTH); - } - else - { + } else { gl.glEnable(GL.GL_LINE_SMOOTH); gl.glHint(GL.GL_LINE_SMOOTH_HINT, this.getAttributes().getAntiAliasHint()); } // Apply line stipple state. - if (dc.isPickingMode() || (this.getAttributes().getBorderStippleFactor() <= 0)) - { + if (dc.isPickingMode() || (this.getAttributes().getBorderStippleFactor() <= 0)) { gl.glDisable(GL2.GL_LINE_STIPPLE); - } - else - { + } else { gl.glEnable(GL2.GL_LINE_STIPPLE); gl.glLineStipple( - this.getAttributes().getBorderStippleFactor(), - this.getAttributes().getBorderStipplePattern()); + this.getAttributes().getBorderStippleFactor(), + this.getAttributes().getBorderStipplePattern()); } // Apply line width state. @@ -772,57 +714,51 @@ protected void drawBorder(DrawContext dc, int width, int height, double opacity, //**************************************************************// //******************** Text Rendering ************************// //**************************************************************// - - protected void drawText(DrawContext dc, int width, int height, double opacity, Position pickPosition) - { + protected void drawText(DrawContext dc, int width, int height, double opacity, Position pickPosition) { AnnotationAttributes attribs = this.getAttributes(); String text = this.getText(); - if (text == null || text.length() == 0) + if (text == null || text.length() == 0) { return; + } java.awt.Rectangle insetBounds = this.computeInsetBounds(width, height); // If we're in picking mode and the pick point does not intersect the annotation's inset bounds in screen space, // then exit. - if (dc.isPickingMode()) - { - if (dc.getPickPoint() == null) + if (dc.isPickingMode()) { + if (dc.getPickPoint() == null) { return; + } java.awt.Rectangle screenInsetBounds = this.transformByModelview(dc, insetBounds); java.awt.Point glPickPoint = this.glPointFromAWTPoint(dc, dc.getPickPoint()); - if (!screenInsetBounds.contains(glPickPoint)) + if (!screenInsetBounds.contains(glPickPoint)) { return; + } } // Wrap the text to the annotation's inset bounds. String wrappedText = this.getWrappedText(dc, insetBounds.width, insetBounds.height, text, attribs.getFont(), - attribs.getTextAlign()); + attribs.getTextAlign()); java.awt.Rectangle wrappedTextBounds = this.getTextBounds(dc, wrappedText, attribs.getFont(), - attribs.getTextAlign()); + attribs.getTextAlign()); int baselineOffset = (int) (wrappedTextBounds.y / 6.0); // TODO: why is baseline offset computed this way? int x = insetBounds.x; int y = insetBounds.y + baselineOffset + 2; // TODO: why does this y-coordinate have an additional +2? // Adjust the text x-coordinate according to the text alignment property. - if (attribs.getTextAlign().equals(AVKey.CENTER)) - { + if (attribs.getTextAlign().equals(AVKey.CENTER)) { x = (int) insetBounds.getCenterX(); - } - else if (attribs.getTextAlign().equals(AVKey.RIGHT)) - { + } else if (attribs.getTextAlign().equals(AVKey.RIGHT)) { x = (int) insetBounds.getMaxX(); } // Adjust the text y-coordinate to fit inside the annotation's inset region. - if (insetBounds.height > 0) - { + if (insetBounds.height > 0) { y += insetBounds.height; - } - else - { + } else { y += wrappedTextBounds.height; } @@ -833,22 +769,17 @@ else if (attribs.getTextAlign().equals(AVKey.RIGHT)) } protected void drawText(DrawContext dc, int x, int y, int lineHeight, double opacity, Object pickObject, - Position pickPosition, String text) - { + Position pickPosition, String text) { boolean isHTML = MultiLineTextRenderer.containsHTML(text); - if (isHTML) - { + if (isHTML) { this.drawHTML(dc, x, y, lineHeight, opacity, pickObject, pickPosition, text); - } - else - { + } else { this.drawPlainText(dc, x, y, lineHeight, opacity, pickObject, pickPosition, text); } } protected void drawPlainText(DrawContext dc, int x, int y, int lineHeight, double opacity, Object pickObject, - Position pickPosition, String text) - { + Position pickPosition, String text) { AnnotationAttributes attribs = this.getAttributes(); MultiLineTextRenderer mltr = this.getMultiLineTextRenderer(dc, attribs.getFont(), attribs.getTextAlign()); @@ -857,19 +788,13 @@ protected void drawPlainText(DrawContext dc, int x, int y, int lineHeight, doubl mltr.setTextColor(textColor); mltr.setBackColor(backColor); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { mltr.pick(text, x, y, lineHeight, dc, this.pickSupport, pickObject, pickPosition); - } - else - { + } else { mltr.getTextRenderer().begin3DRendering(); - try - { + try { mltr.draw(text, x, y, lineHeight, attribs.getEffect()); - } - finally - { + } finally { mltr.getTextRenderer().end3DRendering(); } } @@ -877,8 +802,7 @@ protected void drawPlainText(DrawContext dc, int x, int y, int lineHeight, doubl @SuppressWarnings({"UnusedDeclaration"}) protected void drawHTML(DrawContext dc, int x, int y, int lineHeight, double opacity, Object pickObject, - Position pickPosition, String text) - { + Position pickPosition, String text) { AnnotationAttributes attribs = this.getAttributes(); MultiLineTextRenderer mltr = this.getMultiLineTextRenderer(dc, attribs.getFont(), attribs.getTextAlign()); @@ -887,12 +811,9 @@ protected void drawHTML(DrawContext dc, int x, int y, int lineHeight, double opa mltr.setTextColor(textColor); mltr.setBackColor(backColor); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { mltr.pickHTML(text, x, y, dc.getTextRendererCache(), dc, this.pickSupport, pickObject, pickPosition); - } - else - { + } else { mltr.drawHTML(text, x, y, dc.getTextRendererCache()); } } @@ -900,49 +821,40 @@ protected void drawHTML(DrawContext dc, int x, int y, int lineHeight, double opa //**************************************************************// //******************** Recursive Child Rendering *************// //**************************************************************// - - protected void drawChildren(DrawContext dc, int width, int height, double opacity, Position pickPosition) - { - if (this.childList.isEmpty()) + protected void drawChildren(DrawContext dc, int width, int height, double opacity, Position pickPosition) { + if (this.childList.isEmpty()) { return; + } java.awt.Rectangle insetBounds = this.computeInsetBounds(width, height); this.beginDrawChildren(dc, insetBounds); - try - { + try { this.doDrawChildren(dc, insetBounds, opacity, pickPosition); - } - finally - { + } finally { this.endDrawChildren(dc); } } @SuppressWarnings({"UnusedDeclaration"}) - protected void doDrawChildren(DrawContext dc, java.awt.Rectangle bounds, double opacity, Position pickPosition) - { + protected void doDrawChildren(DrawContext dc, java.awt.Rectangle bounds, double opacity, Position pickPosition) { this.layoutManager.setPickSupport(this.pickSupport); this.layoutManager.drawAnnotations(dc, bounds, this.childList, opacity, pickPosition); } @SuppressWarnings({"UnusedDeclaration"}) - protected void beginDrawChildren(DrawContext dc, java.awt.Rectangle bounds) - { + protected void beginDrawChildren(DrawContext dc, java.awt.Rectangle bounds) { this.layoutManager.beginDrawAnnotations(dc, bounds); } - protected void endDrawChildren(DrawContext dc) - { + protected void endDrawChildren(DrawContext dc) { this.layoutManager.endDrawAnnotations(dc); } //**************************************************************// //******************** Rendering Support *********************// //**************************************************************// - - protected void bindPickableObject(DrawContext dc, Position position) - { + protected void bindPickableObject(DrawContext dc, Position position) { java.awt.Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); Object object = (this.delegateOwner != null) ? this.delegateOwner : this; @@ -952,11 +864,11 @@ protected void bindPickableObject(DrawContext dc, Position position) gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); } - protected void drawCallout(DrawContext dc, int mode, int width, int height, boolean useTexCoords) - { + protected void drawCallout(DrawContext dc, int mode, int width, int height, boolean useTexCoords) { String shape = this.getAttributes().getFrameShape(); - if (shape == null) + if (shape == null) { return; + } java.awt.Point offset = this.getAttributes().getDrawOffset(); java.awt.Point leaderOffset = new java.awt.Point((width / 2) - offset.x, -offset.y); @@ -964,38 +876,34 @@ protected void drawCallout(DrawContext dc, int mode, int width, int height, bool int cornerRadius = this.getAttributes().getCornerRadius(); java.nio.DoubleBuffer buffer = vertexBuffer; - if (this.getAttributes().getLeader().equals(AVKey.SHAPE_TRIANGLE)) - { + if (this.getAttributes().getLeader().equals(AVKey.SHAPE_TRIANGLE)) { buffer = FrameFactory.createShapeWithLeaderBuffer(shape, width, height, leaderOffset, leaderGapWidth, - cornerRadius, buffer); - } - else - { + cornerRadius, buffer); + } else { buffer = FrameFactory.createShapeBuffer(shape, width, height, cornerRadius, buffer); } - if (buffer != null) + if (buffer != null) { vertexBuffer = buffer; + } - if (buffer == null) + if (buffer == null) { return; + } int count = buffer.remaining() / 2; - if (useTexCoords) - { + if (useTexCoords) { FrameFactory.drawBuffer(dc, mode, count, buffer, buffer); - } - else - { + } else { FrameFactory.drawBuffer(dc, mode, count, buffer); } } - protected void applyColor(DrawContext dc, java.awt.Color color, double opacity, boolean premultiplyColors) - { - if (dc.isPickingMode()) + protected void applyColor(DrawContext dc, java.awt.Color color, double opacity, boolean premultiplyColors) { + if (dc.isPickingMode()) { return; + } double finalOpacity = opacity * (color.getAlpha() / 255.0); @@ -1005,8 +913,7 @@ protected void applyColor(DrawContext dc, java.awt.Color color, double opacity, OGLUtil.applyColor(gl, color, finalOpacity, premultiplyColors); } - protected java.awt.Color modulateColorOpacity(java.awt.Color color, double opacity) - { + protected java.awt.Color modulateColorOpacity(java.awt.Color color, double opacity) { float[] compArray = new float[4]; color.getRGBComponents(compArray); compArray[3] *= (float) opacity; @@ -1014,8 +921,7 @@ protected java.awt.Color modulateColorOpacity(java.awt.Color color, double opaci return new java.awt.Color(compArray[0], compArray[1], compArray[2], compArray[3]); } - protected java.awt.Rectangle transformByModelview(DrawContext dc, java.awt.Rectangle rectangle) - { + protected java.awt.Rectangle transformByModelview(DrawContext dc, java.awt.Rectangle rectangle) { double[] compArray = new double[16]; GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glGetDoublev(GL2.GL_MODELVIEW_MATRIX, compArray, 0); @@ -1029,10 +935,10 @@ protected java.awt.Rectangle transformByModelview(DrawContext dc, java.awt.Recta return new java.awt.Rectangle((int) origin.x, (int) origin.y, (int) size.x, (int) size.y); } - protected java.awt.Point glPointFromAWTPoint(DrawContext dc, java.awt.Point awtPoint) - { - if (dc.getView() == null || dc.getView().getViewport() == null) + protected java.awt.Point glPointFromAWTPoint(DrawContext dc, java.awt.Point awtPoint) { + if (dc.getView() == null || dc.getView().getViewport() == null) { return null; + } java.awt.Rectangle viewport = dc.getView().getViewport(); return new java.awt.Point(awtPoint.x, viewport.height - awtPoint.y - 1); @@ -1041,14 +947,11 @@ protected java.awt.Point glPointFromAWTPoint(DrawContext dc, java.awt.Point awtP //**************************************************************// //******************** Text Utilities ************************// //**************************************************************// - - protected TextRenderer getTextRenderer(DrawContext dc, java.awt.Font font) - { + protected TextRenderer getTextRenderer(DrawContext dc, java.awt.Font font) { return OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); } - protected MultiLineTextRenderer getMultiLineTextRenderer(DrawContext dc, java.awt.Font font, String align) - { + protected MultiLineTextRenderer getMultiLineTextRenderer(DrawContext dc, java.awt.Font font, String align) { TextRenderer tr = this.getTextRenderer(dc, font); MultiLineTextRenderer mltr = new MultiLineTextRenderer(tr); @@ -1060,12 +963,10 @@ protected MultiLineTextRenderer getMultiLineTextRenderer(DrawContext dc, java.aw } protected String getWrappedText(DrawContext dc, int width, int height, String text, java.awt.Font font, - String align) - { + String align) { Object key = new TextCacheKey(width, height, text, font, align); String wrappedText = this.wrappedTextMap.get(key); - if (wrappedText == null) - { + if (wrappedText == null) { wrappedText = this.wrapText(dc, width, height, text, font, align); this.wrappedTextMap.put(key, wrappedText); } @@ -1073,12 +974,10 @@ protected String getWrappedText(DrawContext dc, int width, int height, String te return wrappedText; } - protected java.awt.Rectangle getTextBounds(DrawContext dc, String text, java.awt.Font font, String align) - { + protected java.awt.Rectangle getTextBounds(DrawContext dc, String text, java.awt.Font font, String align) { Object key = new TextCacheKey(0, 0, text, font, align); java.awt.Rectangle bounds = this.textBoundsMap.get(key); - if (bounds == null) - { + if (bounds == null) { bounds = this.computeTextBounds(dc, text, font, align); this.textBoundsMap.put(key, bounds); } @@ -1086,19 +985,14 @@ protected java.awt.Rectangle getTextBounds(DrawContext dc, String text, java.awt return new java.awt.Rectangle(bounds); } - protected String wrapText(DrawContext dc, int width, int height, String text, java.awt.Font font, String align) - { - if (text.length() > 0) - { + protected String wrapText(DrawContext dc, int width, int height, String text, java.awt.Font font, String align) { + if (text.length() > 0) { MultiLineTextRenderer mltr = this.getMultiLineTextRenderer(dc, font, align); - if (MultiLineTextRenderer.containsHTML(text)) - { + if (MultiLineTextRenderer.containsHTML(text)) { text = MultiLineTextRenderer.processLineBreaksHTML(text); text = mltr.wrapHTML(text, width, height, dc.getTextRendererCache()); - } - else - { + } else { text = mltr.wrap(text, width, height); } } @@ -1106,37 +1000,29 @@ protected String wrapText(DrawContext dc, int width, int height, String text, ja return text; } - protected java.awt.Rectangle computeTextBounds(DrawContext dc, String text, java.awt.Font font, String align) - { - if (text.length() > 0) - { + protected java.awt.Rectangle computeTextBounds(DrawContext dc, String text, java.awt.Font font, String align) { + if (text.length() > 0) { MultiLineTextRenderer mltr = this.getMultiLineTextRenderer(dc, font, align); - if (MultiLineTextRenderer.containsHTML(text)) - { + if (MultiLineTextRenderer.containsHTML(text)) { return mltr.getBoundsHTML(text, dc.getTextRendererCache()); - } - else - { + } else { return mltr.getBounds(text); } - } - else - { + } else { return new java.awt.Rectangle(); } } - protected static class TextCacheKey - { + protected static class TextCacheKey { + private final int width; private final int height; private final String text; private final java.awt.Font font; private final String align; - public TextCacheKey(int width, int height, String text, java.awt.Font font, String align) - { + public TextCacheKey(int width, int height, String text, java.awt.Font font, String align) { this.width = width; this.height = height; this.text = text; @@ -1144,23 +1030,23 @@ public TextCacheKey(int width, int height, String text, java.awt.Font font, Stri this.align = align; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } TextCacheKey that = (TextCacheKey) o; return (this.width == that.width) - && (this.height == that.height) - && (this.align.equals(that.align)) - && (this.text != null ? this.text.equals(that.text) : that.text == null) - && (this.font != null ? this.font.equals(that.font) : that.font == null); + && (this.height == that.height) + && (this.align.equals(that.align)) + && (this.text != null ? this.text.equals(that.text) : that.text == null) + && (this.font != null ? this.font.equals(that.font) : that.font == null); } - public int hashCode() - { + public int hashCode() { int result = this.width; result = 31 * result + this.height; result = 31 * result + (this.text != null ? this.text.hashCode() : 0); @@ -1173,28 +1059,27 @@ public int hashCode() //**************************************************************// //******************** Bound Computations *********************// //**************************************************************// - - protected java.awt.Rectangle computeInsetBounds(int width, int height) - { + protected java.awt.Rectangle computeInsetBounds(int width, int height) { // TODO: factor in border width? java.awt.Insets insets = this.getAttributes().getInsets(); int insetWidth = width - (insets.left + insets.right); int insetHeight = height - (insets.bottom + insets.top); - if (insetWidth < 0) + if (insetWidth < 0) { insetWidth = 0; + } - if (insetHeight < 0 && height > 0) + if (insetHeight < 0 && height > 0) { insetHeight = 1; - else if (insetHeight < 0) + } else if (insetHeight < 0) { insetHeight = 0; + } return new java.awt.Rectangle(insets.left, insets.bottom, insetWidth, insetHeight); } - protected java.awt.Rectangle computeFreeBounds(DrawContext dc, int width, int height) - { + protected java.awt.Rectangle computeFreeBounds(DrawContext dc, int width, int height) { AnnotationAttributes attribs = this.getAttributes(); // Start with the inset bounds. @@ -1202,16 +1087,15 @@ protected java.awt.Rectangle computeFreeBounds(DrawContext dc, int width, int he // Adjust the free bounds by the text bounds. String wrappedText = this.getWrappedText(dc, width, height, this.getText(), attribs.getFont(), - attribs.getTextAlign()); + attribs.getTextAlign()); java.awt.Rectangle textBounds = this.getTextBounds(dc, wrappedText, attribs.getFont(), - attribs.getTextAlign()); + attribs.getTextAlign()); bounds.height -= textBounds.height; return bounds; } - protected java.awt.Dimension adjustSizeToText(DrawContext dc, int width, int height) - { + protected java.awt.Dimension adjustSizeToText(DrawContext dc, int width, int height) { AnnotationAttributes attribs = this.getAttributes(); String text = this.getWrappedText(dc, width, height, this.getText(), attribs.getFont(), attribs.getTextAlign()); @@ -1219,61 +1103,52 @@ protected java.awt.Dimension adjustSizeToText(DrawContext dc, int width, int hei // If the attributes specify to fit the annotation to the wrapped text width, then set the inset width to // the wrapped text width. - if (attribs.getAdjustWidthToText().equals(AVKey.SIZE_FIT_TEXT) && text.length() > 0) - { + if (attribs.getAdjustWidthToText().equals(AVKey.SIZE_FIT_TEXT) && text.length() > 0) { width = textBounds.width; } // If the inset height is less than or equal to zero, then override the inset height with the the wrapped // text height. - if (height <= 0) - { + if (height <= 0) { height = textBounds.height; } return new java.awt.Dimension(width, height); } - protected java.awt.Dimension adjustSizeToChildren(DrawContext dc, int width, int height) - { - if (this.layoutManager != null) - { + protected java.awt.Dimension adjustSizeToChildren(DrawContext dc, int width, int height) { + if (this.layoutManager != null) { java.awt.Dimension preferredSize = this.layoutManager.getPreferredSize(dc, this.childList); - if (preferredSize != null) - { - if (width < preferredSize.width) + if (preferredSize != null) { + if (width < preferredSize.width) { width = preferredSize.width; - if (height < preferredSize.height) + } + if (height < preferredSize.height) { height = preferredSize.height; + } } } return new java.awt.Dimension(width, height); } - protected Rectangle computeBoundingRectangle(Rectangle rect, int px, int py) - { - if (rect.contains(px, py)) + protected Rectangle computeBoundingRectangle(Rectangle rect, int px, int py) { + if (rect.contains(px, py)) { return rect; + } int dx = 0, dy = 0, dw = 0, dh = 0; - if (px < rect.x) - { + if (px < rect.x) { dx = px - rect.x; dw = -dx; - } - else if (px > rect.x + rect.width - 1) - { + } else if (px > rect.x + rect.width - 1) { dw = px - (rect.x + rect.width - 1); } - if (py < rect.y) - { + if (py < rect.y) { dy = py - rect.y; dh = -dy; - } - else if (py > rect.y + rect.height - 1) - { + } else if (py > rect.y + rect.height - 1) { dh = py - (rect.y + rect.height - 1); } @@ -1284,47 +1159,43 @@ else if (py > rect.y + rect.height - 1) //**************************************************************// //******************** Restorable State **********************// //**************************************************************// - /** * Returns an XML state document String describing the public attributes of this AbstractAnnotation. * * @return XML state document string describing this AbstractAnnotation. */ - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport restorableSupport = null; // This should never be the case, but we check to be thorough. - if (this.attributes != null) - { + if (this.attributes != null) { // Allow AnnotationAttributes to define it's restorable state, if any. String attributesStateInXml = this.attributes.getRestorableState(); - if (attributesStateInXml != null) - { - try - { + if (attributesStateInXml != null) { + try { restorableSupport = RestorableSupport.parse(attributesStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by the superclass failed. - String message = - Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", attributesStateInXml); + String message + = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", attributesStateInXml); Logging.logger().severe(message); } } } // Create our own state document from scratch. - if (restorableSupport == null) + if (restorableSupport == null) { restorableSupport = RestorableSupport.newRestorableSupport(); + } // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (restorableSupport == null) + if (restorableSupport == null) { return null; + } // Escape the text property when saving it to preserve markup characters. - if (this.text != null) + if (this.text != null) { restorableSupport.addStateValueAsString("text", this.text, true); + } restorableSupport.addStateValueAsBoolean("alwaysOnTop", this.alwaysOnTop); @@ -1340,24 +1211,19 @@ public String getRestorableState() * @param stateInXml an XML document String describing an AbstractAnnotation. * * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not a well - * formed XML document String. + * formed XML document String. */ - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport restorableSupport; - try - { + try { restorableSupport = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -1366,19 +1232,22 @@ public void restoreState(String stateInXml) AnnotationAttributes attribs = this.attributes; // Annotation's attributes should not be null. Therefore we assign it a new one as a fallback. - if (attribs == null) + if (attribs == null) { attribs = new AnnotationAttributes(); + } // Restore any AnnotationAttributes state found in "stateInXml". attribs.restoreState(stateInXml); setAttributes(attribs); // No special processing is required to restore the escaped text property. String textState = restorableSupport.getStateValueAsString("text"); - if (textState != null) + if (textState != null) { setText(textState); + } Boolean booleanState = restorableSupport.getStateValueAsBoolean("alwaysOnTop"); - if (booleanState != null) + if (booleanState != null) { setAlwaysOnTop(booleanState); + } } } diff --git a/src/gov/nasa/worldwind/render/AbstractAnnotationBalloon.java b/src/gov/nasa/worldwind/render/AbstractAnnotationBalloon.java index 012b879653..3734f33710 100644 --- a/src/gov/nasa/worldwind/render/AbstractAnnotationBalloon.java +++ b/src/gov/nasa/worldwind/render/AbstractAnnotationBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.avlist.AVKey; @@ -17,21 +16,21 @@ * @author pabercrombie * @version $Id: AbstractAnnotationBalloon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractAnnotationBalloon extends AbstractBalloon -{ +public abstract class AbstractAnnotationBalloon extends AbstractBalloon { + /** * Create a new annotation balloon. * * @param text Balloon text. May not be null. */ - public AbstractAnnotationBalloon(String text) - { + public AbstractAnnotationBalloon(String text) { super(text); } - /** {@inheritDoc} */ - public Rectangle getBounds(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public Rectangle getBounds(DrawContext dc) { return this.getAnnotation().getBounds(dc); } @@ -56,11 +55,13 @@ public Rectangle getBounds(DrawContext dc) */ protected abstract void computePosition(DrawContext dc); - /** {@inheritDoc} */ - public void render(DrawContext dc) - { - if (!this.isVisible()) + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { + if (!this.isVisible()) { return; + } this.determineActiveAttributes(); this.applyAttributesToAnnotation(); @@ -72,9 +73,10 @@ public void render(DrawContext dc) this.getAnnotation().render(dc); } - /** Apply the balloon attributes to the annotation. */ - protected void applyAttributesToAnnotation() - { + /** + * Apply the balloon attributes to the annotation. + */ + protected void applyAttributesToAnnotation() { Annotation annotation = this.getAnnotation(); Object delegateOwner = this.getDelegateOwner(); @@ -84,8 +86,9 @@ protected void applyAttributesToAnnotation() annotation.setPickEnabled(this.isPickEnabled()); String text = this.getDecodedText(); - if (text != null) + if (text != null) { annotation.setText(text); + } annotation.setMinActiveAltitude(this.getMinActiveAltitude()); annotation.setMaxActiveAltitude(this.getMaxActiveAltitude()); @@ -97,8 +100,7 @@ protected void applyAttributesToAnnotation() BalloonAttributes balloonAttrs = this.getActiveAttributes(); - if (balloonAttrs != null) - { + if (balloonAttrs != null) { annotationAttrs.setTextColor(balloonAttrs.getTextColor()); annotationAttrs.setBorderWidth(balloonAttrs.getOutlineWidth()); annotationAttrs.setBorderStippleFactor(balloonAttrs.getOutlineStippleFactor()); @@ -118,7 +120,7 @@ protected void applyAttributesToAnnotation() // Annotation attributes does not have an antialiasing enable/disable flag. Map the antialiasing flag to the // annotation attributes' antialias hint. annotationAttrs.setAntiAliasHint( - balloonAttrs.isEnableAntialiasing() ? Annotation.ANTIALIAS_NICEST : Annotation.ANTIALIAS_FASTEST); + balloonAttrs.isEnableAntialiasing() ? Annotation.ANTIALIAS_NICEST : Annotation.ANTIALIAS_FASTEST); annotationAttrs.setImageSource(balloonAttrs.getImageSource()); annotationAttrs.setImageOffset(balloonAttrs.getImageOffset()); @@ -130,15 +132,12 @@ protected void applyAttributesToAnnotation() // disable drawing the interior. We use the annotation's background color to accomplish both by storing the // interior opacity in the background color alpha channel, and setting the background color to transparent // black if interior drawing is disabled. - if (balloonAttrs.isDrawInterior() && balloonAttrs.getInteriorOpacity() > 0) - { + if (balloonAttrs.isDrawInterior() && balloonAttrs.getInteriorOpacity() > 0) { Color color = balloonAttrs.getInteriorMaterial().getDiffuse(); double opacity = balloonAttrs.getInteriorOpacity(); annotationAttrs.setBackgroundColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), - (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255))); - } - else - { + (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255))); + } else { annotationAttrs.setBackgroundColor(new Color(0, 0, 0, 0)); } @@ -146,15 +145,12 @@ protected void applyAttributesToAnnotation() // drawing the outline. We use the annotation's background color to accomplish both by storing the outline // opacity in the border color alpha channel, and setting the border color to transparent black if outline // drawing is disabled. - if (balloonAttrs.isDrawOutline() && balloonAttrs.getOutlineOpacity() > 0) - { + if (balloonAttrs.isDrawOutline() && balloonAttrs.getOutlineOpacity() > 0) { Color color = balloonAttrs.getOutlineMaterial().getDiffuse(); double opacity = balloonAttrs.getOutlineOpacity(); annotationAttrs.setBorderColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), - (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255))); - } - else - { + (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255))); + } else { annotationAttrs.setBorderColor(new Color(0, 0, 0, 0)); } } @@ -167,23 +163,21 @@ protected void applyAttributesToAnnotation() * * @param dc DrawContext in which the balloon is being rendered. */ - protected void computeOffsets(DrawContext dc) - { + protected void computeOffsets(DrawContext dc) { Annotation annotation = this.getAnnotation(); BalloonAttributes balloonAttrs = this.getActiveAttributes(); AnnotationAttributes annotationAttrs = annotation.getAttributes(); - if (balloonAttrs != null) - { + if (balloonAttrs != null) { // Compute the balloon's preferred size and the current screen viewport size. Dimension prefSize = annotation.getPreferredSize(dc); Rectangle viewport = dc.getView().getViewport(); // Compute the balloon's current size on screen, and its offset in screen coordinates. Dimension screenSize = balloonAttrs.getSize().compute(prefSize.width, prefSize.height, viewport.width, - viewport.height); + viewport.height); Point2D.Double screenOffset = balloonAttrs.getOffset().computeOffset(screenSize.width, screenSize.height, - 1.0, 1.0); + 1.0, 1.0); // Apply the computed balloon size and offset to the internal annotation's attributes. Adjust the screen // offset so that an offset of (0, 0) pixels maps to the annotation's lower left corner, and an offset of @@ -192,7 +186,7 @@ protected void computeOffsets(DrawContext dc) // center. We apply an additional offset of width/2 to compensate for this. annotationAttrs.setSize(screenSize); annotationAttrs.setDrawOffset( - new Point((int) -screenOffset.x + screenSize.width / 2, (int) -screenOffset.y)); + new Point((int) -screenOffset.x + screenSize.width / 2, (int) -screenOffset.y)); } } } diff --git a/src/gov/nasa/worldwind/render/AbstractAnnotationLayout.java b/src/gov/nasa/worldwind/render/AbstractAnnotationLayout.java index 26280d6413..98cb221bb9 100644 --- a/src/gov/nasa/worldwind/render/AbstractAnnotationLayout.java +++ b/src/gov/nasa/worldwind/render/AbstractAnnotationLayout.java @@ -15,37 +15,31 @@ * @author dcollins * @version $Id: AbstractAnnotationLayout.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractAnnotationLayout implements AnnotationLayoutManager -{ +public abstract class AbstractAnnotationLayout implements AnnotationLayoutManager { + protected OGLStackHandler stackHandler; protected PickSupport pickSupport; - protected AbstractAnnotationLayout() - { + protected AbstractAnnotationLayout() { this.stackHandler = new OGLStackHandler(); } - public PickSupport getPickSupport() - { + public PickSupport getPickSupport() { return this.pickSupport; } - public void setPickSupport(PickSupport pickSupport) - { + public void setPickSupport(PickSupport pickSupport) { this.pickSupport = pickSupport; } - public void beginDrawAnnotations(DrawContext dc, java.awt.Rectangle bounds) - { - if (dc == null) - { + public void beginDrawAnnotations(DrawContext dc, java.awt.Rectangle bounds) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bounds == null) - { + if (bounds == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -55,10 +49,8 @@ public void beginDrawAnnotations(DrawContext dc, java.awt.Rectangle bounds) this.stackHandler.pushModelview(gl); } - public void endDrawAnnotations(DrawContext dc) - { - if (dc == null) - { + public void endDrawAnnotations(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -68,14 +60,10 @@ public void endDrawAnnotations(DrawContext dc) this.stackHandler.pop(gl); } - protected java.awt.Dimension getAnnotationSize(DrawContext dc, Annotation annotation) - { - try - { + protected java.awt.Dimension getAnnotationSize(DrawContext dc, Annotation annotation) { + try { return annotation.getPreferredSize(dc); - } - catch (Exception e) - { + } catch (Exception e) { // Trap and log exceptions thrown by computing an annotation's preferred size. This will prevent one // annotation from throwing an exception and preventing all other anotations from reporting their // preferred size. @@ -87,17 +75,14 @@ protected java.awt.Dimension getAnnotationSize(DrawContext dc, Annotation annota } protected void drawAnnotation(DrawContext dc, Annotation annotation, int width, int height, double opacity, - Position pickPosition) - { - try - { - if (this.pickSupport != null) + Position pickPosition) { + try { + if (this.pickSupport != null) { annotation.setPickSupport(this.pickSupport); + } annotation.draw(dc, width, height, opacity, pickPosition); - } - catch (Exception e) - { + } catch (Exception e) { // Trap and log exceptions thrown by rendering an annotation. This will prevent one annotation from // throwing an exception and preventing all other anotations from rendering. String message = Logging.getMessage("generic.ExceptionWhileRenderingAnnotation", annotation); diff --git a/src/gov/nasa/worldwind/render/AbstractBalloon.java b/src/gov/nasa/worldwind/render/AbstractBalloon.java index be5d99a9f5..f89fee9a7b 100644 --- a/src/gov/nasa/worldwind/render/AbstractBalloon.java +++ b/src/gov/nasa/worldwind/render/AbstractBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.WWObjectImpl; @@ -15,8 +14,8 @@ * @author pabercrombie * @version $Id: AbstractBalloon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractBalloon extends WWObjectImpl implements Balloon -{ +public abstract class AbstractBalloon extends WWObjectImpl implements Balloon { + protected boolean alwaysOnTop = false; protected boolean pickEnabled = true; protected Object delegateOwner; @@ -33,17 +32,19 @@ public abstract class AbstractBalloon extends WWObjectImpl implements Balloon protected double minActiveAltitude = -Double.MAX_VALUE; protected double maxActiveAltitude = Double.MAX_VALUE; - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static final BalloonAttributes defaultAttributes; - static - { + static { defaultAttributes = new BasicBalloonAttributes(); } - /** Create a balloon. */ - protected AbstractBalloon() - { + /** + * Create a balloon. + */ + protected AbstractBalloon() { } /** @@ -51,10 +52,8 @@ protected AbstractBalloon() * * @param text The balloon text. */ - protected AbstractBalloon(String text) - { - if (text == null) - { + protected AbstractBalloon(String text) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -63,33 +62,38 @@ protected AbstractBalloon(String text) this.setText(text); } - /** {@inheritDoc} */ - public boolean isAlwaysOnTop() - { + /** + * {@inheritDoc} + */ + public boolean isAlwaysOnTop() { return this.alwaysOnTop; } - /** {@inheritDoc} */ - public void setAlwaysOnTop(boolean alwaysOnTop) - { + /** + * {@inheritDoc} + */ + public void setAlwaysOnTop(boolean alwaysOnTop) { this.alwaysOnTop = alwaysOnTop; } - /** {@inheritDoc} */ - public boolean isPickEnabled() - { + /** + * {@inheritDoc} + */ + public boolean isPickEnabled() { return this.pickEnabled; } - /** {@inheritDoc} */ - public void setPickEnabled(boolean enable) - { + /** + * {@inheritDoc} + */ + public void setPickEnabled(boolean enable) { this.pickEnabled = enable; } - /** {@inheritDoc} */ - public String getText() - { + /** + * {@inheritDoc} + */ + public String getText() { return this.text; } @@ -103,16 +107,15 @@ public String getText() * @see #setTextDecoder(gov.nasa.worldwind.util.TextDecoder) * @see #getTextDecoder() */ - protected String getDecodedText() - { + protected String getDecodedText() { return this.getTextDecoder().getDecodedText(); } - /** {@inheritDoc} */ - public void setText(String text) - { - if (text == null) - { + /** + * {@inheritDoc} + */ + public void setText(String text) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -122,29 +125,32 @@ public void setText(String text) this.getTextDecoder().setText(text); } - /** {@inheritDoc} */ - public Object getDelegateOwner() - { + /** + * {@inheritDoc} + */ + public Object getDelegateOwner() { return this.delegateOwner; } - /** {@inheritDoc} */ - public void setDelegateOwner(Object delegateOwner) - { + /** + * {@inheritDoc} + */ + public void setDelegateOwner(Object delegateOwner) { this.delegateOwner = delegateOwner; } - /** {@inheritDoc} */ - public BalloonAttributes getAttributes() - { + /** + * {@inheritDoc} + */ + public BalloonAttributes getAttributes() { return this.attributes; } - /** {@inheritDoc} */ - public void setAttributes(BalloonAttributes attributes) - { - if (attributes == null) - { + /** + * {@inheritDoc} + */ + public void setAttributes(BalloonAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.BalloonAttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -153,17 +159,18 @@ public void setAttributes(BalloonAttributes attributes) this.attributes = attributes; } - /** {@inheritDoc} */ - public BalloonAttributes getHighlightAttributes() - { + /** + * {@inheritDoc} + */ + public BalloonAttributes getHighlightAttributes() { return this.highlightAttributes; } - /** {@inheritDoc} */ - public void setHighlightAttributes(BalloonAttributes highlightAttributes) - { - if (highlightAttributes == null) - { + /** + * {@inheritDoc} + */ + public void setHighlightAttributes(BalloonAttributes highlightAttributes) { + if (highlightAttributes == null) { String message = Logging.getMessage("nullValue.BalloonAttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,28 +179,24 @@ public void setHighlightAttributes(BalloonAttributes highlightAttributes) this.highlightAttributes = highlightAttributes; } - /** Determines which attributes -- normal, highlight or default -- to use each frame. */ - protected void determineActiveAttributes() - { - if (this.isHighlighted()) - { - if (this.getHighlightAttributes() != null) + /** + * Determines which attributes -- normal, highlight or default -- to use each frame. + */ + protected void determineActiveAttributes() { + if (this.isHighlighted()) { + if (this.getHighlightAttributes() != null) { this.activeAttributes.copy(this.getHighlightAttributes()); - else - { + } else { // If no highlight attributes have been specified we will use the normal attributes. - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); - else + } else { this.activeAttributes.copy(defaultAttributes); + } } - } - else if (this.getAttributes() != null) - { + } else if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); - } - else - { + } else { this.activeAttributes.copy(defaultAttributes); } } @@ -203,22 +206,22 @@ else if (this.getAttributes() != null) * * @return Highlight attributes if the balloon is highlighted, or normal attributes otherwise. */ - protected BalloonAttributes getActiveAttributes() - { + protected BalloonAttributes getActiveAttributes() { return this.activeAttributes; } - /** {@inheritDoc} */ - public TextDecoder getTextDecoder() - { + /** + * {@inheritDoc} + */ + public TextDecoder getTextDecoder() { return this.textDecoder; } - /** {@inheritDoc} */ - public void setTextDecoder(TextDecoder decoder) - { - if (decoder == null) - { + /** + * {@inheritDoc} + */ + public void setTextDecoder(TextDecoder decoder) { + if (decoder == null) { String message = Logging.getMessage("nullValue.TextDecoderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -228,51 +231,59 @@ public void setTextDecoder(TextDecoder decoder) this.textDecoder.setText(this.getText()); } - /** {@inheritDoc} */ - public boolean isHighlighted() - { + /** + * {@inheritDoc} + */ + public boolean isHighlighted() { return highlighted; } - /** {@inheritDoc} */ - public void setHighlighted(boolean highlighted) - { + /** + * {@inheritDoc} + */ + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } - /** {@inheritDoc} */ - public boolean isVisible() - { + /** + * {@inheritDoc} + */ + public boolean isVisible() { return visible; } - /** {@inheritDoc} */ - public void setVisible(boolean visible) - { + /** + * {@inheritDoc} + */ + public void setVisible(boolean visible) { this.visible = visible; } - /** {@inheritDoc} */ - public double getMinActiveAltitude() - { + /** + * {@inheritDoc} + */ + public double getMinActiveAltitude() { return this.minActiveAltitude; } - /** {@inheritDoc} */ - public void setMinActiveAltitude(double minActiveAltitude) - { + /** + * {@inheritDoc} + */ + public void setMinActiveAltitude(double minActiveAltitude) { this.minActiveAltitude = minActiveAltitude; } - /** {@inheritDoc} */ - public double getMaxActiveAltitude() - { + /** + * {@inheritDoc} + */ + public double getMaxActiveAltitude() { return this.maxActiveAltitude; } - /** {@inheritDoc} */ - public void setMaxActiveAltitude(double maxActiveAltitude) - { + /** + * {@inheritDoc} + */ + public void setMaxActiveAltitude(double maxActiveAltitude) { this.maxActiveAltitude = maxActiveAltitude; } } diff --git a/src/gov/nasa/worldwind/render/AbstractBrowserBalloon.java b/src/gov/nasa/worldwind/render/AbstractBrowserBalloon.java index 7adaadb778..aebe06de6d 100644 --- a/src/gov/nasa/worldwind/render/AbstractBrowserBalloon.java +++ b/src/gov/nasa/worldwind/render/AbstractBrowserBalloon.java @@ -50,7 +50,7 @@ * Browser balloons provide a default resize control that is activated by dragging the balloon's border. When the user * drags the border, a SelectEvent is generated with the PickedObject's AVKey.ACTION value set * to AVKey.RESIZE. The PickedObject's AVKey.BOUNDS value holds the Balloon's - * screen bounds in AWT coordinates (origin at the upper left corner) as a java.awt.Rectangle. The resize + * screen bounds in AWT coordinates (origin at the upper left corner) as a java.awt.Rectangle. The resize * control may be enabled or disabled by calling setDrawResizeControl (it is enabled by default). *

            * Balloon Size @@ -94,11 +94,10 @@ * @author dcollins * @version $Id: AbstractBrowserBalloon.java 2148 2014-07-14 16:27:49Z tgaskins $ */ -public abstract class AbstractBrowserBalloon extends AbstractBalloon implements HotSpot, Disposable -{ +public abstract class AbstractBrowserBalloon extends AbstractBalloon implements HotSpot, Disposable { + + public static class BrowserControl extends AVListImpl { - public static class BrowserControl extends AVListImpl - { protected static final Color DEFAULT_COLOR = new Color(255, 255, 255, 153); protected static final Color DEFAULT_HIGHLIGHT_COLOR = new Color(255, 255, 255, 255); @@ -110,17 +109,14 @@ public static class BrowserControl extends AVListImpl protected Color highlightColor; protected WWTexture texture; - public BrowserControl(String action, Offset offset, Object imageSource) - { - if (offset == null) - { + public BrowserControl(String action, Offset offset, Object imageSource) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(imageSource)) - { + if (WWUtil.isEmpty(imageSource)) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -132,24 +128,20 @@ public BrowserControl(String action, Offset offset, Object imageSource) this.imageSource = imageSource; } - public BrowserControl(String action, Offset offset, Size size, Object imageSource) - { - if (offset == null) - { + public BrowserControl(String action, Offset offset, Size size, Object imageSource) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (size == null) - { + if (size == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(imageSource)) - { + if (WWUtil.isEmpty(imageSource)) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -161,35 +153,28 @@ public BrowserControl(String action, Offset offset, Size size, Object imageSourc this.imageSource = imageSource; } - public boolean isVisible() - { + public boolean isVisible() { return this.visible; } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.visible = visible; } - public String getAction() - { + public String getAction() { return this.getStringValue(AVKey.ACTION); } - public void setAction(String action) - { + public void setAction(String action) { this.setValue(AVKey.ACTION, action); } - public Offset getOffset() - { + public Offset getOffset() { return this.offset; } - public void setOffset(Offset offset) - { - if (offset == null) - { + public void setOffset(Offset offset) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -198,15 +183,12 @@ public void setOffset(Offset offset) this.offset = offset; } - public Size getSize() - { + public Size getSize() { return size; } - public void setSize(Size size) - { - if (size == null) - { + public void setSize(Size size) { + if (size == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -215,35 +197,28 @@ public void setSize(Size size) this.size = size; } - public Color getColor() - { + public Color getColor() { return color; } - public void setColor(Color color) - { + public void setColor(Color color) { this.color = color; } - public Color getHighlightColor() - { + public Color getHighlightColor() { return highlightColor; } - public void setHighlightColor(Color highlightColor) - { + public void setHighlightColor(Color highlightColor) { this.highlightColor = highlightColor; } - public Object getImageSource() - { + public Object getImageSource() { return imageSource; } - public void setImageSource(Object imageSource) - { - if (WWUtil.isEmpty(imageSource)) - { + public void setImageSource(Object imageSource) { + if (WWUtil.isEmpty(imageSource)) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -253,10 +228,8 @@ public void setImageSource(Object imageSource) this.texture = null; // Force a texture to be re-created with the new image source. } - protected WWTexture getTexture() - { - if (this.texture == null && this.getImageSource() != null) - { + protected WWTexture getTexture() { + if (this.texture == null && this.getImageSource() != null) { this.texture = new BasicWWTexture(this.getImageSource(), true); } @@ -271,8 +244,8 @@ protected WWTexture getTexture() * leaderWidth, and cornerRadius are the frame geometry's defining properties. These are * used to determine when the frame geometry is invalid and must be recomputed. */ - protected static class FrameGeometryInfo - { + protected static class FrameGeometryInfo { + protected FloatBuffer vertexBuffer; protected Dimension size; protected Point offset; @@ -281,48 +254,58 @@ protected static class FrameGeometryInfo protected int leaderWidth; protected int cornerRadius; - public FrameGeometryInfo() - { + public FrameGeometryInfo() { } } - protected class OrderedBrowserBalloon implements OrderedRenderable - { - /** The location and size of the balloon's content frame in the viewport (on the screen). */ + protected class OrderedBrowserBalloon implements OrderedRenderable { + + /** + * The location and size of the balloon's content frame in the viewport (on the screen). + */ protected Rectangle screenRect; - /** The extent of the balloon's geometry in the viewport (on the screen). */ + /** + * The extent of the balloon's geometry in the viewport (on the screen). + */ protected Rectangle screenExtent; /** - * The extend of the balloon's pickable geometry in the viewport (on the screen). Includes this balloon's outline - * where it exceeds the screen extent. + * The extend of the balloon's pickable geometry in the viewport (on the screen). Includes this balloon's + * outline where it exceeds the screen extent. */ protected Rectangle screenPickExtent; - /** The location and size of the WebView's content frame in the viewport (on the screen). */ + /** + * The location and size of the WebView's content frame in the viewport (on the screen). + */ protected Rectangle webViewRect; - /** The balloon geometry vertices passed to OpenGL. */ + /** + * The balloon geometry vertices passed to OpenGL. + */ protected FrameGeometryInfo frameInfo; - /** Used to order the balloon as an ordered renderable. */ + /** + * Used to order the balloon as an ordered renderable. + */ protected double eyeDistance; - /** Identifies the frame used to calculate the balloon's geometry. */ + /** + * Identifies the frame used to calculate the balloon's geometry. + */ protected long geomTimeStamp = -1; - /** Identifies the frame used to calculate the balloon's active attributes and points. */ + /** + * Identifies the frame used to calculate the balloon's active attributes and points. + */ protected long frameTimeStamp = -1; @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } @Override - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { AbstractBrowserBalloon.this.pick(dc, pickPoint, this); } @Override - public void render(DrawContext dc) - { + public void render(DrawContext dc) { AbstractBrowserBalloon.this.drawOrderedRenderable(dc, this); } } @@ -345,9 +328,13 @@ public void render(DrawContext dc) * WebView factory. */ protected static final String DEFAULT_WEB_VIEW_FACTORY = BasicWebViewFactory.class.getName(); - /** The number of slices used to display a balloon frame as an ellipse: 64. */ + /** + * The number of slices used to display a balloon frame as an ellipse: 64. + */ protected static final int FRAME_GEOMETRY_ELLIPSE_SLICES = 64; - /** The number of slices used to display each of a rectangular balloon frame's rounded corners: 16. */ + /** + * The number of slices used to display each of a rectangular balloon frame's rounded corners: 16. + */ protected static final int FRAME_GEOMETRY_RECTANGLE_CORNER_SLICES = 16; /** @@ -364,19 +351,20 @@ public void render(DrawContext dc) * * @return a list containing the browser balloon's default browser controls. */ - protected static List createDefaultBrowserControls() - { + protected static List createDefaultBrowserControls() { return Arrays.asList( - new BrowserControl(AVKey.CLOSE, new Offset(30.0, 25.0, AVKey.INSET_PIXELS, AVKey.INSET_PIXELS), - "images/browser-close-16x16.gif"), - new BrowserControl(AVKey.BACK, new Offset(15.0, 25.0, AVKey.PIXELS, AVKey.INSET_PIXELS), - "images/browser-back-16x16.gif"), - new BrowserControl(AVKey.FORWARD, new Offset(35.0, 25.0, AVKey.PIXELS, AVKey.INSET_PIXELS), - "images/browser-forward-16x16.gif") + new BrowserControl(AVKey.CLOSE, new Offset(30.0, 25.0, AVKey.INSET_PIXELS, AVKey.INSET_PIXELS), + "images/browser-close-16x16.gif"), + new BrowserControl(AVKey.BACK, new Offset(15.0, 25.0, AVKey.PIXELS, AVKey.INSET_PIXELS), + "images/browser-back-16x16.gif"), + new BrowserControl(AVKey.FORWARD, new Offset(35.0, 25.0, AVKey.PIXELS, AVKey.INSET_PIXELS), + "images/browser-forward-16x16.gif") ); } - /** Action that will occur when the balloon is made invisible. */ + /** + * Action that will occur when the balloon is made invisible. + */ protected String visibilityAction = AVKey.VISIBILITY_ACTION_RELEASE; protected boolean drawTitleBar = true; protected boolean drawBrowserControls = true; @@ -394,18 +382,26 @@ protected static List createDefaultBrowserControls() * specify that relative paths should be interpreted as unresolved references. Initially null. */ protected Object resourceResolver; - /** Identifies the time when the balloon text was updated. Initially -1. */ + /** + * Identifies the time when the balloon text was updated. Initially -1. + */ protected long textUpdateTime = -1; /** * Denotes whether or not an attempt at WebView creation failed. When true the balloon does not perform * subsequent attempts to create the WebView. Initially false. */ protected boolean webViewCreationFailed; - /** Interface for interacting with the operating system's web browser control. Initially null. */ + /** + * Interface for interacting with the operating system's web browser control. Initially null. + */ protected WebView webView; - /** Identifies the frame used to update the WebView's state. */ + /** + * Identifies the frame used to update the WebView's state. + */ protected long webViewTimeStamp = -1; - /** The location of the balloon's content frame relative to the balloon's screen point in the viewport. */ + /** + * The location of the balloon's content frame relative to the balloon's screen point in the viewport. + */ protected Point screenOffset; /** * The size of the WebView's HTML content size, in pixels. This is the size that the WebView can be displayed at @@ -413,22 +409,28 @@ protected static List createDefaultBrowserControls() * HTML content size is unknown. Initially null. */ protected Dimension webViewContentSize; - /** The layer active during the most recent pick pass. */ + /** + * The layer active during the most recent pick pass. + */ protected Layer pickLayer; - /** The screen coordinate of the last SelectEvent sent to this balloon's select method. */ + /** + * The screen coordinate of the last SelectEvent sent to this balloon's select method. + */ protected Point lastPickPoint; - /** Support for setting up and restoring picking state, and resolving the picked object. */ + /** + * Support for setting up and restoring picking state, and resolving the picked object. + */ protected PickSupport pickSupport = new PickSupport(); - /** Support for setting up and restoring OpenGL state during rendering. */ + /** + * Support for setting up and restoring OpenGL state during rendering. + */ protected OGLStackHandler osh = new OGLStackHandler(); protected long screenBalloonPickFrame; protected long screenBalloonRenderFrame; - protected HashMap - orderedRenderables = new HashMap(1); + protected HashMap orderedRenderables = new HashMap(1); - protected AbstractBrowserBalloon(String text) - { + protected AbstractBrowserBalloon(String text) { super(text); } @@ -449,38 +451,31 @@ protected AbstractBrowserBalloon(String text) * if the balloon is already disposed. */ @Override - public void dispose() - { + public void dispose() { this.disposeWebView(); } - public boolean isDrawTitleBar() - { + public boolean isDrawTitleBar() { return this.drawTitleBar; } - public void setDrawTitleBar(boolean draw) - { + public void setDrawTitleBar(boolean draw) { this.drawTitleBar = draw; } - public boolean isDrawBrowserControls() - { + public boolean isDrawBrowserControls() { return this.drawBrowserControls; } - public void setDrawBrowserControls(boolean draw) - { + public void setDrawBrowserControls(boolean draw) { this.drawBrowserControls = draw; } - public boolean isDrawResizeControl() - { + public boolean isDrawResizeControl() { return this.drawResizeControl; } - public void setDrawResizeControl(boolean draw) - { + public void setDrawResizeControl(boolean draw) { this.drawResizeControl = draw; } @@ -493,28 +488,25 @@ public void setDrawResizeControl(boolean draw) * @see #setVisibilityAction(String) */ @Override - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { super.setVisible(visible); // If the balloon is not visible and the visibility action indicates to release the browser, dispose of the web // view to release native resources. - if (!this.isVisible() && AVKey.VISIBILITY_ACTION_RELEASE.equals(this.getVisibilityAction())) - { + if (!this.isVisible() && AVKey.VISIBILITY_ACTION_RELEASE.equals(this.getVisibilityAction())) { this.disposeWebView(); } } /** - * Indicates the outline line width (in pixels) used during picking. A larger width than normal typically makes the + * Indicates the outline line width (in pixels) used during picking. A larger width than normal typically makes the * outline easier to pick. * * @return the outline line width (in pixels) used during picking. * * @see #setOutlinePickWidth(int) */ - public int getOutlinePickWidth() - { + public int getOutlinePickWidth() { return this.outlinePickWidth; } @@ -534,10 +526,8 @@ public int getOutlinePickWidth() * @see #getOutlinePickWidth() * @see #setDrawResizeControl(boolean) */ - public void setOutlinePickWidth(int width) - { - if (width < 0) - { + public void setOutlinePickWidth(int width) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -546,15 +536,12 @@ public void setOutlinePickWidth(int width) this.outlinePickWidth = width; } - public Iterable getBrowserControls() - { + public Iterable getBrowserControls() { return this.browserControls; } - public void addBrowserControl(BrowserControl browserControl) - { - if (browserControl == null) - { + public void addBrowserControl(BrowserControl browserControl) { + if (browserControl == null) { String message = Logging.getMessage("nullValue.BrowserControlIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -563,17 +550,14 @@ public void addBrowserControl(BrowserControl browserControl) this.browserControls.add(browserControl); } - public BrowserControl addBrowserControl(String action, Offset offset, Object imageSource) - { - if (offset == null) - { + public BrowserControl addBrowserControl(String action, Offset offset, Object imageSource) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(imageSource)) - { + if (WWUtil.isEmpty(imageSource)) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -585,24 +569,20 @@ public BrowserControl addBrowserControl(String action, Offset offset, Object ima return browserControl; } - public BrowserControl addBrowserControl(String action, Offset offset, Size size, Object imageSource) - { - if (offset == null) - { + public BrowserControl addBrowserControl(String action, Offset offset, Size size, Object imageSource) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (size == null) - { + if (size == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(imageSource)) - { + if (WWUtil.isEmpty(imageSource)) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -614,28 +594,22 @@ public BrowserControl addBrowserControl(String action, Offset offset, Size size, return browserControl; } - public void addAllBrowserControls(Iterable iterable) - { - if (iterable == null) - { + public void addAllBrowserControls(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (BrowserControl browserControl : iterable) - { - if (browserControl != null) - { + for (BrowserControl browserControl : iterable) { + if (browserControl != null) { this.browserControls.add(browserControl); } } } - public void removeBrowserControl(BrowserControl browserControl) - { - if (browserControl == null) - { + public void removeBrowserControl(BrowserControl browserControl) { + if (browserControl == null) { String message = Logging.getMessage("nullValue.BrowserControlIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -644,8 +618,7 @@ public void removeBrowserControl(BrowserControl browserControl) this.browserControls.remove(browserControl); } - public void removeAllBrowserControls() - { + public void removeAllBrowserControls() { this.browserControls.clear(); } @@ -654,13 +627,12 @@ public void removeAllBrowserControls() * * @return the object used to resolve relative resource paths in HTML content. One of the following: {@link * gov.nasa.worldwind.util.webview.WebResourceResolver}, {@link java.net.URL}, - * {@link String} containing a valid URL description, or null to indicate that - * relative paths are interpreted as unresolved references. + * {@link String} containing a valid URL description, or null to indicate that relative + * paths are interpreted as unresolved references. * * @see #setResourceResolver(Object) */ - public Object getResourceResolver() - { + public Object getResourceResolver() { return this.resourceResolver; } @@ -674,15 +646,13 @@ public Object getResourceResolver() * balloon interprets relative resource paths as unresolved references. * * @param resourceResolver the object to use when resolving relative resource paths in HTML content. May be one of - * the following: {@link gov.nasa.worldwind.util.webview.WebResourceResolver}, - * {@link java.net.URL}, {@link String} containing a valid URL - * description, or null to specify that relative paths should be interpreted as - * unresolved references. + * the following: {@link gov.nasa.worldwind.util.webview.WebResourceResolver}, + * {@link java.net.URL}, {@link String} containing a valid URL description, or + * null to specify that relative paths should be interpreted as unresolved references. * * @see #getResourceResolver() */ - public void setResourceResolver(Object resourceResolver) - { + public void setResourceResolver(Object resourceResolver) { this.resourceResolver = resourceResolver; // Setting a new resource resolver may change how the WebView content is rendered. Set the textUpdate time to @@ -699,8 +669,7 @@ public void setResourceResolver(Object resourceResolver) * @see #setVisibilityAction(String) * @see #setVisible(boolean) */ - public String getVisibilityAction() - { + public String getVisibilityAction() { return visibilityAction; } @@ -715,10 +684,8 @@ public String getVisibilityAction() * * @param visibilityAction Either {@link AVKey#VISIBILITY_ACTION_RELEASE} or {@link AVKey#VISIBILITY_ACTION_RETAIN}. */ - public void setVisibilityAction(String visibilityAction) - { - if (visibilityAction == null) - { + public void setVisibilityAction(String visibilityAction) { + if (visibilityAction == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -727,18 +694,22 @@ public void setVisibilityAction(String visibilityAction) this.visibilityAction = visibilityAction; } - /** Navigate the browser to the previous page in the browsing history. Has no effect if there is previous page. */ - public void goBack() - { - if (this.webView != null) + /** + * Navigate the browser to the previous page in the browsing history. Has no effect if there is previous page. + */ + public void goBack() { + if (this.webView != null) { this.webView.goBack(); + } } - /** Navigate the browser to the next page in the browsing history. Has no effect if there is no next page. */ - public void goForward() - { - if (this.webView != null) + /** + * Navigate the browser to the next page in the browsing history. Has no effect if there is no next page. + */ + public void goForward() { + if (this.webView != null) { this.webView.goForward(); + } } /** @@ -749,30 +720,29 @@ public void goForward() * false. */ @Override - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (!this.isVisible() && propertyChangeEvent != null - && AVKey.REPAINT.equals(propertyChangeEvent.getPropertyName())) - { + && AVKey.REPAINT.equals(propertyChangeEvent.getPropertyName())) { return; } super.propertyChange(propertyChangeEvent); } - /** {@inheritDoc} */ - public Rectangle getBounds(DrawContext dc) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public Rectangle getBounds(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } OrderedBrowserBalloon obb = this.orderedRenderables.get(dc.getGlobe().getGlobeStateKey()); - if (obb == null) + if (obb == null) { obb = this.createOrderedRenderable(); + } // Update the balloon's active attributes and points if that hasn't already been done this frame. this.updateRenderStateIfNeeded(dc, obb); @@ -781,41 +751,37 @@ public Rectangle getBounds(DrawContext dc) return obb.screenExtent; } - public void pick(DrawContext dc, Point pickPoint, OrderedBrowserBalloon obb) - { + public void pick(DrawContext dc, Point pickPoint, OrderedBrowserBalloon obb) { // This method is called only when ordered renderables are being drawn. - if (!this.isPickEnabled()) + if (!this.isPickEnabled()) { return; + } this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.drawOrderedRenderable(dc, obb); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { // This render method is called twice during frame generation. It's first called as a {@link Renderable} // during Renderable picking. It's called again during normal rendering. These two calls determine // whether to add the placemark and its optional line to the ordered renderable list during pick and render. - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } this.makeOrderedRenderable(dc); } @@ -832,21 +798,20 @@ public void render(DrawContext dc) * * @param dc the current draw context. */ - protected void makeOrderedRenderable(DrawContext dc) - { + protected void makeOrderedRenderable(DrawContext dc) { // Prevent screen balloons from drawing more than once per frame for 2D continuous globes. - if (this instanceof ScreenBrowserBalloon && dc.isContinuous2DGlobe()) - { - if (dc.isPickingMode() && this.screenBalloonPickFrame == dc.getFrameTimeStamp()) + if (this instanceof ScreenBrowserBalloon && dc.isContinuous2DGlobe()) { + if (dc.isPickingMode() && this.screenBalloonPickFrame == dc.getFrameTimeStamp()) { return; + } - if (!dc.isPickingMode() && this.screenBalloonRenderFrame == dc.getFrameTimeStamp()) + if (!dc.isPickingMode() && this.screenBalloonRenderFrame == dc.getFrameTimeStamp()) { return; + } } OrderedBrowserBalloon obb = this.orderedRenderables.get(dc.getGlobe().getGlobeStateKey()); - if (obb == null) - { + if (obb == null) { obb = this.createOrderedRenderable(); this.orderedRenderables.put(dc.getGlobe().getGlobeStateKey(), obb); } @@ -856,39 +821,40 @@ protected void makeOrderedRenderable(DrawContext dc) // Exit immediately if either the balloon's active attributes or its screen rectangle are null. In either case // we cannot compute the balloon's geometry nor can we determine where to render the balloon. - if (this.getActiveAttributes() == null || obb.screenRect == null) + if (this.getActiveAttributes() == null || obb.screenRect == null) { return; + } // Re-use geometry already calculated this frame. - if (dc.getFrameTimeStamp() != obb.geomTimeStamp) - { + if (dc.getFrameTimeStamp() != obb.geomTimeStamp) { // Recompute this balloon's geometry only when an attribute change requires us to. - if (this.mustRegenerateGeometry(obb)) + if (this.mustRegenerateGeometry(obb)) { this.computeGeometry(obb); + } obb.geomTimeStamp = dc.getFrameTimeStamp(); } // Update the balloon's WebView to be current with the BrowserBalloon's properties. This must be done after // updating the render state; this balloon's active attributes are applied to the WebView. Re-use WebView state // already calculated this frame. - if (dc.getFrameTimeStamp() != this.webViewTimeStamp) - { + if (dc.getFrameTimeStamp() != this.webViewTimeStamp) { this.updateWebView(dc, obb); this.webViewTimeStamp = dc.getFrameTimeStamp(); } - if (this.intersectsFrustum(dc, obb)) - { + if (this.intersectsFrustum(dc, obb)) { dc.addOrderedRenderable(obb); - if (dc.isPickingMode()) + if (dc.isPickingMode()) { this.screenBalloonPickFrame = dc.getFrameTimeStamp(); - else + } else { this.screenBalloonRenderFrame = dc.getFrameTimeStamp(); + } } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { this.pickLayer = dc.getCurrentLayer(); + } } /** @@ -901,21 +867,19 @@ protected void makeOrderedRenderable(DrawContext dc) * @param dc the current draw context. * @param obb The balloon to update. */ - protected void updateRenderStateIfNeeded(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void updateRenderStateIfNeeded(DrawContext dc, OrderedBrowserBalloon obb) { // Re-use rendering state values already calculated this frame. - if (dc.getFrameTimeStamp() != obb.frameTimeStamp) - { + if (dc.getFrameTimeStamp() != obb.frameTimeStamp) { this.updateRenderState(dc, obb); obb.frameTimeStamp = dc.getFrameTimeStamp(); } } - protected void updateRenderState(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void updateRenderState(DrawContext dc, OrderedBrowserBalloon obb) { this.determineActiveAttributes(); - if (this.getActiveAttributes() == null) + if (this.getActiveAttributes() == null) { return; + } this.determineWebViewContentSize(); this.computeBalloonPoints(dc, obb); @@ -925,13 +889,12 @@ protected void updateRenderState(DrawContext dc, OrderedBrowserBalloon obb) * Computes the size of this balloon's frame in the viewport (on the screen). If this balloon's maximum size is not * null, the returned size is no larger than the maximum size. * - * @param dc the current draw context. + * @param dc the current draw context. * @param activeAttrs the attributes used to compute the balloon's size. * * @return this balloon frame's screen size, in pixels. */ - protected Dimension computeSize(DrawContext dc, BalloonAttributes activeAttrs) - { + protected Dimension computeSize(DrawContext dc, BalloonAttributes activeAttrs) { // Determine the balloon's current native size. If the WebView's content size is non-null and nonzero, then use // that as the basis for the balloon's native size. Otherwise use a default native size. This handles the case // where the balloon's size is computed either before the WebView is created or before the WebView's content @@ -940,37 +903,34 @@ protected Dimension computeSize(DrawContext dc, BalloonAttributes activeAttrs) // native dimension, this size is ignored. Dimension nativeSize; if (this.webViewContentSize != null && this.webViewContentSize.width != 0 - && this.webViewContentSize.height != 0) - { + && this.webViewContentSize.height != 0) { // Convert the WebView's content size to a balloon frame size. nativeSize = this.computeFrameRectForWebViewRect(activeAttrs, - new Rectangle(this.webViewContentSize)).getSize(); - } - else - { + new Rectangle(this.webViewContentSize)).getSize(); + } else { nativeSize = DEFAULT_NATIVE_SIZE; } Dimension size = activeAttrs.getSize().compute(nativeSize.width, nativeSize.height, - dc.getView().getViewport().width, dc.getView().getViewport().height); + dc.getView().getViewport().width, dc.getView().getViewport().height); - if (activeAttrs.getMaximumSize() != null) - { + if (activeAttrs.getMaximumSize() != null) { Dimension maxSize = activeAttrs.getMaximumSize().compute(nativeSize.width, nativeSize.height, - dc.getView().getViewport().width, dc.getView().getViewport().height); + dc.getView().getViewport().width, dc.getView().getViewport().height); - if (size.width > maxSize.width) + if (size.width > maxSize.width) { size.width = maxSize.width; - if (size.height > maxSize.height) + } + if (size.height > maxSize.height) { size.height = maxSize.height; + } } return size; } @SuppressWarnings({"UnusedDeclaration"}) - protected Point computeOffset(DrawContext dc, BalloonAttributes activeAttrs, int width, int height) - { + protected Point computeOffset(DrawContext dc, BalloonAttributes activeAttrs, int width, int height) { Point2D.Double offset = activeAttrs.getOffset().computeOffset(width, height, 1d, 1d); return new Point((int) offset.getX(), (int) offset.getY()); } @@ -982,35 +942,38 @@ protected Point computeOffset(DrawContext dc, BalloonAttributes activeAttrs, int * @param obb The balloon to check. * @return true if this balloon's geometry must be recomputed, otherwise false. */ - protected boolean mustRegenerateGeometry(OrderedBrowserBalloon obb) - { - if (obb.frameInfo == null) + protected boolean mustRegenerateGeometry(OrderedBrowserBalloon obb) { + if (obb.frameInfo == null) { return true; + } - if (!obb.screenRect.getSize().equals(obb.frameInfo.size) || !this.screenOffset.equals(obb.frameInfo.offset)) + if (!obb.screenRect.getSize().equals(obb.frameInfo.size) || !this.screenOffset.equals(obb.frameInfo.offset)) { return true; + } BalloonAttributes activeAttrs = this.getActiveAttributes(); return !activeAttrs.getBalloonShape().equals(obb.frameInfo.balloonShape) - || !activeAttrs.getLeaderShape().equals(obb.frameInfo.leaderShape) - || activeAttrs.getLeaderWidth() != obb.frameInfo.leaderWidth - || activeAttrs.getCornerRadius() != obb.frameInfo.cornerRadius; + || !activeAttrs.getLeaderShape().equals(obb.frameInfo.leaderShape) + || activeAttrs.getLeaderWidth() != obb.frameInfo.leaderWidth + || activeAttrs.getCornerRadius() != obb.frameInfo.cornerRadius; } /** * Updates the balloon's screen-coordinate geometry in frameInfo according to the current screen * bounds, screen offset, and active attributes. + * * @param obb The balloon to update. */ - protected void computeGeometry(OrderedBrowserBalloon obb) - { - if (obb.screenRect == null) + protected void computeGeometry(OrderedBrowserBalloon obb) { + if (obb.screenRect == null) { return; + } BalloonAttributes activeAttrs = this.getActiveAttributes(); - if (obb.frameInfo == null) + if (obb.frameInfo == null) { obb.frameInfo = new FrameGeometryInfo(); + } // Regenerate the frame's vertex buffer. obb.frameInfo.vertexBuffer = this.createFrameVertices(obb); @@ -1030,22 +993,20 @@ protected void computeGeometry(OrderedBrowserBalloon obb) * @param obb The balloon. * @return a buffer containing the frame's x and y locations. */ - protected FloatBuffer createFrameVertices(OrderedBrowserBalloon obb) - { + protected FloatBuffer createFrameVertices(OrderedBrowserBalloon obb) { BalloonAttributes activeAttrs = this.getActiveAttributes(); - if (AVKey.SHAPE_NONE.equals(activeAttrs.getBalloonShape())) + if (AVKey.SHAPE_NONE.equals(activeAttrs.getBalloonShape())) { return this.makeDefaultFrameVertices(obb); - - else if (AVKey.SHAPE_ELLIPSE.equals(activeAttrs.getBalloonShape())) + } else if (AVKey.SHAPE_ELLIPSE.equals(activeAttrs.getBalloonShape())) { return this.makeEllipseFrameVertices(obb); - - else // Default to AVKey.SHAPE_RECTANGLE + } else // Default to AVKey.SHAPE_RECTANGLE + { return this.makeRectangleFrameVertices(obb); + } } - protected FloatBuffer makeDefaultFrameVertices(OrderedBrowserBalloon obb) - { + protected FloatBuffer makeDefaultFrameVertices(OrderedBrowserBalloon obb) { BalloonAttributes activeAttrs = this.getActiveAttributes(); GeometryBuilder gb = new GeometryBuilder(); @@ -1053,22 +1014,19 @@ protected FloatBuffer makeDefaultFrameVertices(OrderedBrowserBalloon obb) int y = obb.webViewRect.y - obb.screenRect.y; // Return a rectangle that represents the WebView's screen rectangle. - if (AVKey.SHAPE_TRIANGLE.equals(activeAttrs.getLeaderShape())) - { + if (AVKey.SHAPE_TRIANGLE.equals(activeAttrs.getLeaderShape())) { // The balloon's leader location is equivalent to its screen offset because the screen offset specifies the // location of the screen reference point relative to the frame, and the leader points from the frame to the // screen reference point. return gb.makeRectangleWithLeader(x, y, obb.webViewRect.width, obb.webViewRect.height, - this.screenOffset.x, this.screenOffset.y, activeAttrs.getLeaderWidth()); - } - else // Default to AVKey.SHAPE_NONE + this.screenOffset.x, this.screenOffset.y, activeAttrs.getLeaderWidth()); + } else // Default to AVKey.SHAPE_NONE { return gb.makeRectangle(x, y, obb.webViewRect.width, obb.webViewRect.height); } } - protected FloatBuffer makeEllipseFrameVertices(OrderedBrowserBalloon obb) - { + protected FloatBuffer makeEllipseFrameVertices(OrderedBrowserBalloon obb) { BalloonAttributes activeAttrs = this.getActiveAttributes(); GeometryBuilder gb = new GeometryBuilder(); @@ -1080,39 +1038,34 @@ protected FloatBuffer makeEllipseFrameVertices(OrderedBrowserBalloon obb) // Return an ellipse centered at the balloon's center and with major and minor axes equal to the balloon's // width and height, respectively. We use integer coordinates for the center and the radii to ensure that // these vertices align image texels exactly with screen pixels when used as texture coordinates. - if (AVKey.SHAPE_TRIANGLE.equals(activeAttrs.getLeaderShape())) - { + if (AVKey.SHAPE_TRIANGLE.equals(activeAttrs.getLeaderShape())) { // The balloon's leader location is equivalent to its screen offset because the screen offset specifies the // location of the screen reference point relative to the frame, and the leader points from the frame to the // screen reference point. return gb.makeEllipseWithLeader(x, y, majorRadius, minorRadius, FRAME_GEOMETRY_ELLIPSE_SLICES, - this.screenOffset.x, this.screenOffset.y, activeAttrs.getLeaderWidth()); - } - else // Default to AVKey.SHAPE_NONE + this.screenOffset.x, this.screenOffset.y, activeAttrs.getLeaderWidth()); + } else // Default to AVKey.SHAPE_NONE { return gb.makeEllipse(x, y, majorRadius, minorRadius, FRAME_GEOMETRY_ELLIPSE_SLICES); } } - protected FloatBuffer makeRectangleFrameVertices(OrderedBrowserBalloon obb) - { + protected FloatBuffer makeRectangleFrameVertices(OrderedBrowserBalloon obb) { BalloonAttributes activeAttrs = this.getActiveAttributes(); GeometryBuilder gb = new GeometryBuilder(); // Return a rectangle that represents the balloon's screen rectangle, with optional rounded corners. - if (AVKey.SHAPE_TRIANGLE.equals(activeAttrs.getLeaderShape())) - { + if (AVKey.SHAPE_TRIANGLE.equals(activeAttrs.getLeaderShape())) { // The balloon's leader location is equivalent to its screen offset because the screen offset specifies the // location of the screen reference point relative to the frame, and the leader points from the frame to the // screen reference point. return gb.makeRectangleWithLeader(0, 0, obb.screenRect.width, obb.screenRect.height, - activeAttrs.getCornerRadius(), FRAME_GEOMETRY_RECTANGLE_CORNER_SLICES, this.screenOffset.x, - this.screenOffset.y, activeAttrs.getLeaderWidth()); - } - else // Default to AVKey.SHAPE_NONE + activeAttrs.getCornerRadius(), FRAME_GEOMETRY_RECTANGLE_CORNER_SLICES, this.screenOffset.x, + this.screenOffset.y, activeAttrs.getLeaderWidth()); + } else // Default to AVKey.SHAPE_NONE { return gb.makeRectangle(0, 0, obb.screenRect.width, obb.screenRect.height, activeAttrs.getCornerRadius(), - FRAME_GEOMETRY_RECTANGLE_CORNER_SLICES); + FRAME_GEOMETRY_RECTANGLE_CORNER_SLICES); } } @@ -1124,35 +1077,30 @@ protected FloatBuffer makeRectangleFrameVertices(OrderedBrowserBalloon obb) * * @return true If the balloon intersects the frustum, otherwise false. */ - protected boolean intersectsFrustum(DrawContext dc, OrderedBrowserBalloon obb) - { + protected boolean intersectsFrustum(DrawContext dc, OrderedBrowserBalloon obb) { // During picking, use the balloon's pickable screen extent. This extent includes this balloon's outline where // it exceeds the screen extent. - if (dc.isPickingMode()) + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(obb.screenPickExtent); + } return dc.getView().getViewport().intersects(obb.screenExtent); } - protected void drawOrderedRenderable(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void drawOrderedRenderable(DrawContext dc, OrderedBrowserBalloon obb) { this.beginDrawing(dc); - try - { + try { this.doDrawOrderedRenderable(dc, obb); - } - finally - { + } finally { this.endDrawing(dc); } } - protected void beginDrawing(DrawContext dc) - { + protected void beginDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - int attrMask = - GL2.GL_COLOR_BUFFER_BIT // For alpha enable, blend enable, alpha func, blend func. + int attrMask + = GL2.GL_COLOR_BUFFER_BIT // For alpha enable, blend enable, alpha func, blend func. | GL2.GL_CURRENT_BIT // For current color | GL2.GL_DEPTH_BUFFER_BIT // For depth test enable/disable, depth func, depth mask. | GL2.GL_LINE_BIT // For line smooth enable, line stipple enable, line width, line stipple factor, @@ -1171,25 +1119,21 @@ protected void beginDrawing(DrawContext dc) gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); // All drawing uses vertex arrays. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); // Enable interior and outline alpha blending when not picking. OGLUtil.applyBlending(gl, false); } } - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.osh.pop(gl); } - protected void doDrawOrderedRenderable(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void doDrawOrderedRenderable(DrawContext dc, OrderedBrowserBalloon obb) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { // Set up the pick color used during interior and outline rendering. Color pickColor = dc.getUniquePickColor(); this.pickSupport.addPickableObject(this.createPickedObject(dc, pickColor)); @@ -1200,34 +1144,38 @@ protected void doDrawOrderedRenderable(DrawContext dc, OrderedBrowserBalloon obb // aligned exactly with screen pixels. gl.glTranslatef(obb.screenRect.x, obb.screenRect.y, 0); - if (!dc.isDeepPickingEnabled()) + if (!dc.isDeepPickingEnabled()) { this.setupDepthTest(dc, obb); + } // Draw the balloon frame geometry. This draws the WebView as a texture applied to the balloon frame's interior. this.drawFrame(dc, obb); - if (this.isDrawTitleBar(dc)) + if (this.isDrawTitleBar(dc)) { this.drawTitleBar(dc, obb); + } - if (this.isDrawResizeControl(dc)) + if (this.isDrawResizeControl(dc)) { this.drawResizeControl(dc, obb); + } - if (this.isDrawBrowserControls(dc)) + if (this.isDrawBrowserControls(dc)) { this.drawBrowserControls(dc, obb); + } // We draw the links last to ensure that their picked objects are on top. We do this to ensure that link picking // is consistent with mouse events sent to the WebView. Currently, all select events that occur in this balloon // are send to the WebView. We want link pick areas to be on top to ensure that the application has a chance to // veto any link click select events before they are sent to the WebView. - if (this.isDrawLinks(dc)) + if (this.isDrawLinks(dc)) { this.drawLinks(dc, obb); + } } @SuppressWarnings({"UnusedDeclaration"}) - protected PickedObject createPickedObject(DrawContext dc, Color pickColor) - { + protected PickedObject createPickedObject(DrawContext dc, Color pickColor) { PickedObject po = new PickedObject(pickColor.getRGB(), - this.getDelegateOwner() != null ? this.getDelegateOwner() : this); + this.getDelegateOwner() != null ? this.getDelegateOwner() : this); // Attach the balloon to the picked object's AVList under the key HOT_SPOT. The application can then find that // the balloon is a HotSpot by looking in the picked object's AVList. This is critical when the delegate owner @@ -1239,8 +1187,7 @@ protected PickedObject createPickedObject(DrawContext dc, Color pickColor) } @SuppressWarnings({"UnusedDeclaration"}) - protected PickedObject createLinkPickedObject(DrawContext dc, Color pickColor, AVList linkParams) - { + protected PickedObject createLinkPickedObject(DrawContext dc, Color pickColor, AVList linkParams) { PickedObject po = new PickedObject(pickColor.getRGB(), this); // Apply all of the link parameters to the picked object. This provides the application with the link's URL, @@ -1255,56 +1202,49 @@ protected PickedObject createLinkPickedObject(DrawContext dc, Color pickColor, A } @SuppressWarnings({"UnusedDeclaration"}) - protected boolean isDrawInterior(DrawContext dc) - { + protected boolean isDrawInterior(DrawContext dc) { return this.getActiveAttributes().isDrawInterior() && this.getActiveAttributes().getInteriorOpacity() > 0; } @SuppressWarnings({"UnusedDeclaration"}) - protected boolean isDrawOutline(DrawContext dc) - { + protected boolean isDrawOutline(DrawContext dc) { return this.getActiveAttributes().isDrawOutline() && this.getActiveAttributes().getOutlineOpacity() > 0; } - protected boolean isDrawTitleBar(DrawContext dc) - { + protected boolean isDrawTitleBar(DrawContext dc) { return this.isDrawTitleBar() && this.isDrawInterior(dc) && !dc.isPickingMode(); } - protected boolean isDrawResizeControl(DrawContext dc) - { + protected boolean isDrawResizeControl(DrawContext dc) { // There is no visible control so only proceed in picking mode. return this.isDrawResizeControl() && (this.isDrawInterior(dc) || this.isDrawOutline(dc)) && dc.isPickingMode(); } - protected boolean isDrawBrowserControls(DrawContext dc) - { + protected boolean isDrawBrowserControls(DrawContext dc) { return this.isDrawBrowserControls() && this.isDrawInterior(dc); } - protected boolean isDrawLinks(DrawContext dc) - { + protected boolean isDrawLinks(DrawContext dc) { return this.isDrawInterior(dc) && dc.isPickingMode(); } - protected void drawFrame(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void drawFrame(DrawContext dc, OrderedBrowserBalloon obb) { if (obb.frameInfo.vertexBuffer == null) // This should never happen, but we check anyway. + { return; + } // Bind the balloon's vertex buffer as source of GL vertex coordinates. This buffer is used by both interior // and outline rendering. We bind it once here to avoid loading the buffer twice. GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glVertexPointer(2, GL.GL_FLOAT, 0, obb.frameInfo.vertexBuffer); - if (this.isDrawInterior(dc)) - { + if (this.isDrawInterior(dc)) { this.prepareToDrawInterior(dc); this.drawFrameInterior(dc, obb); } - if (this.isDrawOutline(dc)) - { + if (this.isDrawOutline(dc)) { this.prepareToDrawOutline(dc); this.drawFrameOutline(dc, obb); } @@ -1326,22 +1266,21 @@ protected void drawFrame(DrawContext dc, OrderedBrowserBalloon obb) * @param dc the current draw context. * @param obb The balloon to draw. */ - protected void drawFrameInterior(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void drawFrameInterior(DrawContext dc, OrderedBrowserBalloon obb) { if (obb.frameInfo.vertexBuffer == null) // This should never happen, but we check anyway. + { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. boolean textureApplied = false; - try - { + try { // Bind the WebView's texture representation as the current texture source if we're in normal rendering // mode. This also configures the texture matrix to transform texture coordinates from the balloon's vertex // coordinates to the WebView's screen rectangle. For this reason we use the balloon's vertex coordinates as // its texture coordinates. - if (!dc.isPickingMode() && this.bindWebViewTexture(dc, obb)) - { + if (!dc.isPickingMode() && this.bindWebViewTexture(dc, obb)) { // The WebView's texture is successfully bound. Enable GL texturing and set up the texture // environment to apply the texture in decal mode. Decal mode uses the texture color where the // texture's alpha is 1, and uses the balloon's background color where it's 0. The texture's @@ -1359,14 +1298,11 @@ protected void drawFrameInterior(DrawContext dc, OrderedBrowserBalloon obb) // represented by (x,y) pairs in screen coordinates. The number of vertices to draw is computed by dividing // the number of coordinates by 2, because each vertex has exactly two coordinates: x and y. gl.glDrawArrays(GL.GL_TRIANGLE_FAN, 0, obb.frameInfo.vertexBuffer.remaining() / 2); - } - finally - { + } finally { // Restore the previous texture state and client array state. We do this to avoid pushing and popping the // texture attribute bit, which is expensive. We disable textures, disable texture coordinate arrays, bind // texture id 0, set the default texture environment mode, and and set the texture coord pointer to 0. - if (textureApplied) - { + if (textureApplied) { gl.glDisable(GL.GL_TEXTURE_2D); gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); @@ -1376,73 +1312,68 @@ protected void drawFrameInterior(DrawContext dc, OrderedBrowserBalloon obb) } } - protected void drawFrameOutline(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void drawFrameOutline(DrawContext dc, OrderedBrowserBalloon obb) { if (obb.frameInfo.vertexBuffer == null) // This should never happen, but we check anyway. + { return; + } // Draw the balloon's geometry as a line loop to display the outline. The balloon's vertices are in screen // coordinates. dc.getGL().glDrawArrays(GL.GL_LINE_LOOP, 0, obb.frameInfo.vertexBuffer.remaining() / 2); } - protected void prepareToDrawInterior(DrawContext dc) - { + protected void prepareToDrawInterior(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Apply the balloon's background color and opacity if we're in normal rendering mode. Color color = this.getActiveAttributes().getInteriorMaterial().getDiffuse(); double opacity = this.getActiveAttributes().getInteriorOpacity(); gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue(), - (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); + (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); } } - protected void prepareToDrawOutline(DrawContext dc) - { + protected void prepareToDrawOutline(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Apply the balloon's outline color and opacity and apply the balloon's normal outline width if we're in // normal rendering mode. Color color = this.getActiveAttributes().getOutlineMaterial().getDiffuse(); double opacity = this.getActiveAttributes().getOutlineOpacity(); gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue(), - (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); + (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); // Apply line smoothing if we're in normal rendering mode. - if (this.getActiveAttributes().isEnableAntialiasing()) - { + if (this.getActiveAttributes().isEnableAntialiasing()) { gl.glEnable(GL.GL_LINE_SMOOTH); } - if (this.getActiveAttributes().getOutlineStippleFactor() > 0) - { + if (this.getActiveAttributes().getOutlineStippleFactor() > 0) { gl.glEnable(GL2.GL_LINE_STIPPLE); gl.glLineStipple(this.getActiveAttributes().getOutlineStippleFactor(), - this.getActiveAttributes().getOutlineStipplePattern()); + this.getActiveAttributes().getOutlineStipplePattern()); } } // Apply the balloon's outline width. Use the outline pick width if we're in picking mode and the pick width is // greater than the normal line width. Otherwise use the normal line width. - if (dc.isPickingMode()) + if (dc.isPickingMode()) { gl.glLineWidth((float) this.computeOutlinePickWidth()); - else + } else { gl.glLineWidth((float) this.getActiveAttributes().getOutlineWidth()); + } } - protected Rectangle computeFramePickRect(Rectangle frameRect) - { + protected Rectangle computeFramePickRect(Rectangle frameRect) { double outlinePickWidth = this.computeOutlinePickWidth(); return new Rectangle( - frameRect.x - (int) outlinePickWidth / 2, - frameRect.y - (int) outlinePickWidth / 2, - frameRect.width + (int) outlinePickWidth, - frameRect.height + (int) outlinePickWidth); + frameRect.x - (int) outlinePickWidth / 2, + frameRect.y - (int) outlinePickWidth / 2, + frameRect.width + (int) outlinePickWidth, + frameRect.height + (int) outlinePickWidth); } /** @@ -1451,21 +1382,19 @@ protected Rectangle computeFramePickRect(Rectangle frameRect) * * @return the line width to use during picking, in pixels. */ - protected double computeOutlinePickWidth() - { + protected double computeOutlinePickWidth() { return Math.max(this.getActiveAttributes().getOutlineWidth(), this.getOutlinePickWidth()); } - protected void updateWebView(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void updateWebView(DrawContext dc, OrderedBrowserBalloon obb) { // Attempt to create the balloon's WebView. - if (this.webView == null) - { + if (this.webView == null) { this.makeWebView(dc, obb.webViewRect.getSize()); // Exit immediately if WebView creation failed. - if (this.webView == null) + if (this.webView == null) { return; + } } // The WebView's frame size and background color can change each frame. Synchronize the WebView's background @@ -1479,43 +1408,32 @@ protected void updateWebView(DrawContext dc, OrderedBrowserBalloon obb) // application makes to the decoded text are reflected in the browser balloon's content. If we ignore those // changes when the user navigates to another page, the application cannot retain control over the balloon's // content. - if (this.getTextDecoder().getLastUpdateTime() != this.textUpdateTime) - { + if (this.getTextDecoder().getLastUpdateTime() != this.textUpdateTime) { this.setWebViewContent(); this.textUpdateTime = this.getTextDecoder().getLastUpdateTime(); } } - protected void setWebViewContent() - { + protected void setWebViewContent() { String text = this.getTextDecoder().getDecodedText(); Object resourceResolver = this.getResourceResolver(); - if (resourceResolver instanceof WebResourceResolver) - { + if (resourceResolver instanceof WebResourceResolver) { this.webView.setHTMLString(text, (WebResourceResolver) resourceResolver); - } - else if (resourceResolver instanceof URL) - { + } else if (resourceResolver instanceof URL) { this.webView.setHTMLString(text, (URL) resourceResolver); - } - else if (resourceResolver instanceof String) - { + } else if (resourceResolver instanceof String) { // If the string is not a valid URL, then makeURL returns null and the WebView treats any relative paths as // unresolved references. URL url = WWIO.makeURL((String) resourceResolver); - if (url == null) - { + if (url == null) { Logging.logger().warning(Logging.getMessage("generic.URIInvalid", resourceResolver)); } this.webView.setHTMLString(text, url); - } - else - { - if (resourceResolver != null) - { + } else { + if (resourceResolver != null) { Logging.logger().warning(Logging.getMessage("generic.UnrecognizedResourceResolver", resourceResolver)); } @@ -1523,21 +1441,18 @@ else if (resourceResolver instanceof String) } } - protected void makeWebView(DrawContext dc, Dimension frameSize) - { - if (this.webView != null || this.webViewCreationFailed) + protected void makeWebView(DrawContext dc, Dimension frameSize) { + if (this.webView != null || this.webViewCreationFailed) { return; + } - try - { + try { // Attempt to get the WebViewFactory class name from configuration. Fall back on the BrowserBalloon's // default factory if the configuration does not specify a one. String className = Configuration.getStringValue(AVKey.WEB_VIEW_FACTORY, DEFAULT_WEB_VIEW_FACTORY); WebViewFactory factory = (WebViewFactory) WorldWind.createComponent(className); this.webView = factory.createWebView(frameSize); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = Logging.getMessage("WebView.ExceptionCreatingWebView", t); Logging.logger().severe(message); @@ -1549,14 +1464,15 @@ protected void makeWebView(DrawContext dc, Dimension frameSize) } // Configure the balloon to forward the WebView's property change events to its listeners. - if (this.webView != null) + if (this.webView != null) { this.webView.addPropertyChangeListener(this); + } } - protected void disposeWebView() - { - if (this.webView == null) + protected void disposeWebView() { + if (this.webView == null) { return; + } this.webView.removePropertyChangeListener(this); this.webView.dispose(); @@ -1565,8 +1481,7 @@ protected void disposeWebView() this.webViewContentSize = null; } - protected void determineWebViewContentSize() - { + protected void determineWebViewContentSize() { // Update the WebView's HTML content size when the WebView is non-null and has not navigated to a another page // (indicated by a non-null URL). The latter case indicates that the WebView is not displaying this balloon's // text. We avoid updating the content size in this case to ensure that the balloon's size always fits the @@ -1574,44 +1489,43 @@ protected void determineWebViewContentSize() // content causes the balloon to abruptly change size as the user navigates. Note that the content size may be // null or (0, 0), indicating that the WebView does not know its content size. The balloon handles this by // falling back to a default content size. - if (this.webView != null && this.webView.getContentURL() == null) - { + if (this.webView != null && this.webView.getContentURL() == null) { this.webViewContentSize = this.webView.getContentSize(); } } - protected Rectangle computeWebViewRectForFrameRect(BalloonAttributes activeAttrs, Rectangle frameRect) - { + protected Rectangle computeWebViewRectForFrameRect(BalloonAttributes activeAttrs, Rectangle frameRect) { // Compute the WebView rectangle as an inset of the balloon's screen rectangle, given the current inset values. Insets insets = activeAttrs.getInsets(); return new Rectangle( - frameRect.x + insets.left, - frameRect.y + insets.bottom, - frameRect.width - (insets.left + insets.right), - frameRect.height - (insets.bottom + insets.top)); + frameRect.x + insets.left, + frameRect.y + insets.bottom, + frameRect.width - (insets.left + insets.right), + frameRect.height - (insets.bottom + insets.top)); } - protected Rectangle computeFrameRectForWebViewRect(BalloonAttributes activeAttrs, Rectangle webViewRect) - { + protected Rectangle computeFrameRectForWebViewRect(BalloonAttributes activeAttrs, Rectangle webViewRect) { Insets insets = activeAttrs.getInsets(); return new Rectangle( - webViewRect.x - insets.left, - webViewRect.y - insets.bottom, - webViewRect.width + (insets.left + insets.right), - webViewRect.height + (insets.bottom + insets.top)); + webViewRect.x - insets.left, + webViewRect.y - insets.bottom, + webViewRect.width + (insets.left + insets.right), + webViewRect.height + (insets.bottom + insets.top)); } - protected boolean bindWebViewTexture(DrawContext dc, OrderedBrowserBalloon obb) - { - if (this.webView == null) + protected boolean bindWebViewTexture(DrawContext dc, OrderedBrowserBalloon obb) { + if (this.webView == null) { return false; + } WWTexture texture = this.webView.getTextureRepresentation(dc); - if (texture == null) + if (texture == null) { return false; + } - if (!texture.bind(dc)) + if (!texture.bind(dc)) { return false; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -1634,34 +1548,37 @@ protected boolean bindWebViewTexture(DrawContext dc, OrderedBrowserBalloon obb) return true; } - protected void drawWebViewLinks(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void drawWebViewLinks(DrawContext dc, OrderedBrowserBalloon obb) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (this.webView == null) + if (this.webView == null) { return; + } Iterable links = this.webView.getLinks(); - if (links == null) + if (links == null) { return; + } - for (AVList linkParams : links) - { + for (AVList linkParams : links) { // This should never happen, but we check anyway. - if (linkParams == null) + if (linkParams == null) { continue; + } // Ignore any links that have no bounds or no rectangles; they cannot be drawn. - if (linkParams.getValue(AVKey.BOUNDS) == null || linkParams.getValue(AVKey.RECTANGLES) == null) + if (linkParams.getValue(AVKey.BOUNDS) == null || linkParams.getValue(AVKey.RECTANGLES) == null) { continue; + } // Translate the bounds from WebView coordinates to WorldWindow screen coordinates. Rectangle bounds = new Rectangle((Rectangle) linkParams.getValue(AVKey.BOUNDS)); bounds.translate(obb.webViewRect.x, obb.webViewRect.y); // Ignore link rectangles that do not intersect any of the current pick rectangles. - if (!dc.getPickFrustums().intersectsAny(bounds)) + if (!dc.getPickFrustums().intersectsAny(bounds)) { continue; + } Color pickColor = dc.getUniquePickColor(); gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue()); @@ -1671,22 +1588,19 @@ protected void drawWebViewLinks(DrawContext dc, OrderedBrowserBalloon obb) int y = obb.webViewRect.y - obb.screenRect.y; gl.glBegin(GL2.GL_QUADS); - try - { - for (Rectangle rect : (Rectangle[]) linkParams.getValue(AVKey.RECTANGLES)) - { + try { + for (Rectangle rect : (Rectangle[]) linkParams.getValue(AVKey.RECTANGLES)) { // This should never happen, but we check anyway. - if (rect == null) + if (rect == null) { continue; + } gl.glVertex2i(x + rect.x, y + rect.y); gl.glVertex2i(x + rect.x + rect.width, y + rect.y); gl.glVertex2i(x + rect.x + rect.width, y + rect.y + rect.height); gl.glVertex2i(x + rect.x, y + rect.y + rect.height); } - } - finally - { + } finally { gl.glEnd(); } } @@ -1698,17 +1612,18 @@ protected void drawWebViewLinks(DrawContext dc, OrderedBrowserBalloon obb) * @param dc Draw context. * @param obb The balloon. */ - protected void drawResizeControl(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void drawResizeControl(DrawContext dc, OrderedBrowserBalloon obb) { if (obb.frameInfo.vertexBuffer == null) // This should never happen, but we check anyway. + { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Compute the screen rectangle in AWT coordinates (origin top left). Rectangle awtScreenRect = new Rectangle(obb.screenRect.x, - dc.getView().getViewport().height - obb.screenRect.y - obb.screenRect.height, - obb.screenRect.width, obb.screenRect.height); + dc.getView().getViewport().height - obb.screenRect.y - obb.screenRect.height, + obb.screenRect.width, obb.screenRect.height); Color color = dc.getUniquePickColor(); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); @@ -1725,53 +1640,50 @@ protected void drawResizeControl(DrawContext dc, OrderedBrowserBalloon obb) gl.glDrawArrays(GL.GL_LINE_LOOP, 0, obb.frameInfo.vertexBuffer.remaining() / 2); } - protected void drawBrowserControls(DrawContext dc, OrderedBrowserBalloon obb) - { - for (BrowserControl control : this.getBrowserControls()) - { + protected void drawBrowserControls(DrawContext dc, OrderedBrowserBalloon obb) { + for (BrowserControl control : this.getBrowserControls()) { if (control == null) // This should never happen, but we check anyway. + { continue; + } - if (!control.isVisible()) + if (!control.isVisible()) { continue; + } - try - { + try { this.drawBrowserControl(dc, control, obb); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().severe(Logging.getMessage("generic.ExceptionWhileRenderingBrowserControl", control)); } } } - protected void drawBrowserControl(DrawContext dc, BrowserControl control, OrderedBrowserBalloon obb) - { + protected void drawBrowserControl(DrawContext dc, BrowserControl control, OrderedBrowserBalloon obb) { WWTexture texture = control.getTexture(); - if (texture == null) + if (texture == null) { return; + } Point2D offset = control.getOffset().computeOffset(obb.screenRect.width, obb.screenRect.height, 1d, 1d); Dimension size = control.getSize().compute(texture.getWidth(dc), texture.getHeight(dc), - obb.screenRect.width, obb.screenRect.height); + obb.screenRect.width, obb.screenRect.height); Rectangle rect = new Rectangle(obb.screenRect.x + (int) offset.getX(), obb.screenRect.y + (int) offset.getY(), - size.width, size.height); - if (rect.isEmpty()) + size.width, size.height); + if (rect.isEmpty()) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushTextureIdentity(gl); ogsh.pushModelviewIdentity(gl); - try - { + try { gl.glTranslated(rect.x, rect.y, 0); gl.glScaled(rect.width, rect.height, 1); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { Color pickColor = dc.getUniquePickColor(); gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue()); @@ -1784,19 +1696,14 @@ protected void drawBrowserControl(DrawContext dc, BrowserControl control, Ordere this.pickSupport.addPickableObject(po); dc.drawUnitQuad(); - } - else - { + } else { // Determine the control's active color: either the highlight color or the normal color, depending on // whether a pick point is over the control. Color color; - if (dc.getPickFrustums().intersectsAny(rect)) - { + if (dc.getPickFrustums().intersectsAny(rect)) { color = control.getHighlightColor() != null ? control.getHighlightColor() - : BrowserControl.DEFAULT_HIGHLIGHT_COLOR; - } - else - { + : BrowserControl.DEFAULT_HIGHLIGHT_COLOR; + } else { color = control.getColor() != null ? control.getColor() : BrowserControl.DEFAULT_COLOR; } @@ -1806,8 +1713,9 @@ protected void drawBrowserControl(DrawContext dc, BrowserControl control, Ordere // Multiply the color's opacity by the balloon's interior opacity so that controls maintain the same // relative opacity to the balloon's interior. float alpha = compArray[3] * (float) this.getActiveAttributes().getInteriorOpacity(); - if (alpha > 1f) + if (alpha > 1f) { alpha = 1f; + } // Apply the control's color and enable blending in premultiplied alpha mode. We must enable use the // correct blending function for premultiplied alpha colors, because textures loaded by JOGL contain @@ -1816,14 +1724,11 @@ protected void drawBrowserControl(DrawContext dc, BrowserControl control, Ordere gl.glColor4f(compArray[0] * alpha, compArray[1] * alpha, compArray[2] * alpha, alpha); gl.glEnable(GL.GL_TEXTURE_2D); - if (texture.bind(dc)) - { + if (texture.bind(dc)) { dc.drawUnitQuad(texture.getTexCoords()); } } - } - finally - { + } finally { ogsh.pop(gl); // Restore the previous texture state. We do this to avoid pushing and popping the texture attribute bit, // which is expensive. We disable textures and bind texture id 0. @@ -1832,15 +1737,14 @@ protected void drawBrowserControl(DrawContext dc, BrowserControl control, Ordere } } - protected void drawTitleBar(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void drawTitleBar(DrawContext dc, OrderedBrowserBalloon obb) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Apply the balloon's outline color, but use the interior opacity. Color color = this.getActiveAttributes().getOutlineMaterial().getDiffuse(); double opacity = this.getActiveAttributes().getInteriorOpacity(); gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue(), - (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); + (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); // Disable line smoothing and specify a line with of 1.0. This ensures that the title separator line appears // sharp and thin. @@ -1851,32 +1755,31 @@ protected void drawTitleBar(DrawContext dc, OrderedBrowserBalloon obb) int y = obb.webViewRect.y - obb.screenRect.y; gl.glBegin(GL2.GL_LINES); - try - { + try { gl.glVertex2i(x, y + obb.webViewRect.height); gl.glVertex2i(x + obb.webViewRect.width, y + obb.webViewRect.height); - } - finally - { + } finally { gl.glEnd(); } } - protected void drawLinks(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void drawLinks(DrawContext dc, OrderedBrowserBalloon obb) { this.drawWebViewLinks(dc, obb); } - /** {@inheritDoc} */ - public void setActive(boolean active) - { - if (this.webView != null) + /** + * {@inheritDoc} + */ + public void setActive(boolean active) { + if (this.webView != null) { this.webView.setActive(active); + } } - /** {@inheritDoc} */ - public boolean isActive() - { + /** + * {@inheritDoc} + */ + public boolean isActive() { return (this.webView != null) && this.webView.isActive(); } @@ -1888,57 +1791,57 @@ public boolean isActive() * * @param event The event to handle. */ - public void selected(SelectEvent event) - { - if (event == null || event.isConsumed()) + public void selected(SelectEvent event) { + if (event == null || event.isConsumed()) { return; + } this.handleSelectEvent(event); } /** - * Forwards the key typed event to the balloon's internal {@link gov.nasa.worldwind.util.webview.WebView} - * and consumes the event. This consumes the event so the {@link gov.nasa.worldwind.View} doesn't - * respond to it. + * Forwards the key typed event to the balloon's internal + * {@link gov.nasa.worldwind.util.webview.WebView} and consumes the event. This consumes the event so + * the {@link gov.nasa.worldwind.View} doesn't respond to it. * * @param event The event to forward. */ - public void keyTyped(KeyEvent event) - { - if (event == null || event.isConsumed()) + public void keyTyped(KeyEvent event) { + if (event == null || event.isConsumed()) { return; + } this.handleKeyEvent(event); event.consume(); // Consume the event so the View doesn't respond to it. } /** - * Forwards the key pressed event to the balloon's internal {@link gov.nasa.worldwind.util.webview.WebView} - * and consumes the event. This consumes the event so the {@link gov.nasa.worldwind.View} doesn't - * respond to it. The + * Forwards the key pressed event to the balloon's internal + * {@link gov.nasa.worldwind.util.webview.WebView} and consumes the event. This consumes the event so + * the {@link gov.nasa.worldwind.View} doesn't respond to it. The * * @param event The event to forward. */ - public void keyPressed(KeyEvent event) - { - if (event == null || event.isConsumed()) + public void keyPressed(KeyEvent event) { + if (event == null || event.isConsumed()) { return; + } this.handleKeyEvent(event); event.consume(); // Consume the event so the View doesn't respond to it. } /** - * Forwards the key released event to the balloon's internal {@link gov.nasa.worldwind.util.webview.WebView} - * and consumes the event. This consumes the event so the {@link gov.nasa.worldwind.View} doesn't - * respond to it. + * Forwards the key released event to the balloon's internal + * {@link gov.nasa.worldwind.util.webview.WebView} and consumes the event. This consumes the event so + * the {@link gov.nasa.worldwind.View} doesn't respond to it. * * @param event The event to forward. */ - public void keyReleased(KeyEvent event) - { - if (event == null || event.isConsumed()) + public void keyReleased(KeyEvent event) { + if (event == null || event.isConsumed()) { return; + } this.handleKeyEvent(event); event.consume(); // Consume the event so the View doesn't respond to it. @@ -1949,8 +1852,7 @@ public void keyReleased(KeyEvent event) * * @param event The event to handle. */ - public void mouseClicked(MouseEvent event) - { + public void mouseClicked(MouseEvent event) { } /** @@ -1958,8 +1860,7 @@ public void mouseClicked(MouseEvent event) * * @param event The event to handle. */ - public void mousePressed(MouseEvent event) - { + public void mousePressed(MouseEvent event) { } /** @@ -1967,8 +1868,7 @@ public void mousePressed(MouseEvent event) * * @param event The event to handle. */ - public void mouseReleased(MouseEvent event) - { + public void mouseReleased(MouseEvent event) { } /** @@ -1976,8 +1876,7 @@ public void mouseReleased(MouseEvent event) * * @param event The event to handle. */ - public void mouseEntered(MouseEvent event) - { + public void mouseEntered(MouseEvent event) { } /** @@ -1985,8 +1884,7 @@ public void mouseEntered(MouseEvent event) * * @param event The event to handle. */ - public void mouseExited(MouseEvent event) - { + public void mouseExited(MouseEvent event) { } /** @@ -1994,42 +1892,42 @@ public void mouseExited(MouseEvent event) * * @param event The event to handle. */ - public void mouseDragged(MouseEvent event) - { + public void mouseDragged(MouseEvent event) { } /** - * Forwards the mouse moved event to the balloon's internal {@link gov.nasa.worldwind.util.webview.WebView}. - * This does not consume the event, because the {@link gov.nasa.worldwind.event.InputHandler} - * implements the policy for consuming or forwarding mouse moved events to other objects. + * Forwards the mouse moved event to the balloon's internal + * {@link gov.nasa.worldwind.util.webview.WebView}. This does not consume the event, because the + * {@link gov.nasa.worldwind.event.InputHandler} implements the policy for consuming or forwarding + * mouse moved events to other objects. *

            * Unlike mouse clicked, mouse pressed, and mouse dragged events, mouse move events cannot be forwarded to the * WebView via SelectEvents in selected, because mouse movement events are not selection events. * * @param event The event to forward. */ - public void mouseMoved(MouseEvent event) - { - if (event == null || event.isConsumed()) + public void mouseMoved(MouseEvent event) { + if (event == null || event.isConsumed()) { return; + } this.handleMouseEvent(event); } /** - * Forwards the mouse wheel event to the balloon's internal {@link gov.nasa.worldwind.util.webview.WebView} - * and consumes the event. This consumes the event so the {@link gov.nasa.worldwind.View} doesn't - * respond to it. + * Forwards the mouse wheel event to the balloon's internal + * {@link gov.nasa.worldwind.util.webview.WebView} and consumes the event. This consumes the event so + * the {@link gov.nasa.worldwind.View} doesn't respond to it. *

            * Unlike mouse clicked, mouse pressed, and mouse dragged events, mouse wheel events cannot be forwarded to the * WebView via SelectEvents in selected, because mouse wheel events are not selection events. * * @param event The event to forward. */ - public void mouseWheelMoved(MouseWheelEvent event) - { - if (event == null || event.isConsumed()) + public void mouseWheelMoved(MouseWheelEvent event) { + if (event == null || event.isConsumed()) { return; + } this.handleMouseEvent(event); event.consume(); // Consume the event so the View doesn't respond to it. @@ -2042,8 +1940,7 @@ public void mouseWheelMoved(MouseWheelEvent event) * * @return A null Cursor. */ - public Cursor getCursor() - { + public Cursor getCursor() { return null; } @@ -2053,14 +1950,15 @@ public Cursor getCursor() * * @param event the event to send. */ - protected void handleSelectEvent(SelectEvent event) - { - if (this.webView == null) + protected void handleSelectEvent(SelectEvent event) { + if (this.webView == null) { return; + } // Ignore box selection events. These currently have no mapping to a WebView internal event. - if (event.isBoxSelect()) + if (event.isBoxSelect()) { return; + } // Convert the mouse event's screen point to the WebView's local coordinate system. Note that we send the mouse // event to the WebView even when its screen point is outside the WebView's bounding rectangle. This gives the @@ -2069,70 +1967,66 @@ protected void handleSelectEvent(SelectEvent event) // The SelectEvent's pick point is null if its a drag end event. In this case, use pick point of the last // SelectEvent we received, which should be a drag event with a non-null pick point. - if (pickPoint == null) + if (pickPoint == null) { pickPoint = this.lastPickPoint; + } // If the last SelectEvent's pick point is null and the current SelectEvent's pick point is null, then we cannot // send this event to the WebView. - if (pickPoint == null) + if (pickPoint == null) { return; + } Point webViewPoint = this.convertToWebView(event.getSource(), pickPoint); - if (event.isLeftPress() || event.isRightPress()) - { + if (event.isLeftPress() || event.isRightPress()) { int modifiers = event.isLeftPress() ? MouseEvent.BUTTON1_DOWN_MASK : MouseEvent.BUTTON3_DOWN_MASK; this.webView.sendEvent( - new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_PRESSED, - System.currentTimeMillis(), modifiers, // when, modifiers. - webViewPoint.x, webViewPoint.y, 0, // x, y, clickCount. - event.isRightPress(), // isPopupTrigger. - event.isRightPress() ? MouseEvent.BUTTON3 : MouseEvent.BUTTON1)); - } - else if (event.isLeftClick() || event.isRightClick() || event.isLeftDoubleClick()) - { + new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_PRESSED, + System.currentTimeMillis(), modifiers, // when, modifiers. + webViewPoint.x, webViewPoint.y, 0, // x, y, clickCount. + event.isRightPress(), // isPopupTrigger. + event.isRightPress() ? MouseEvent.BUTTON3 : MouseEvent.BUTTON1)); + } else if (event.isLeftClick() || event.isRightClick() || event.isLeftDoubleClick()) { int clickCount = event.isLeftDoubleClick() ? 2 : 1; int modifiers = (event.isLeftClick() || event.isLeftDoubleClick()) ? MouseEvent.BUTTON1_DOWN_MASK - : MouseEvent.BUTTON3_DOWN_MASK; + : MouseEvent.BUTTON3_DOWN_MASK; this.webView.sendEvent( - new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_RELEASED, - System.currentTimeMillis(), 0, // when, modifiers. - webViewPoint.x, webViewPoint.y, clickCount, // x, y, clickCount. - false, // isPopupTrigger. - event.isRightClick() ? MouseEvent.BUTTON3 : MouseEvent.BUTTON1)); + new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_RELEASED, + System.currentTimeMillis(), 0, // when, modifiers. + webViewPoint.x, webViewPoint.y, clickCount, // x, y, clickCount. + false, // isPopupTrigger. + event.isRightClick() ? MouseEvent.BUTTON3 : MouseEvent.BUTTON1)); this.webView.sendEvent( - new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_CLICKED, - System.currentTimeMillis(), modifiers, // when, modifiers. - webViewPoint.x, webViewPoint.y, clickCount, // x, y, clickCount - false, // isPopupTrigger. - event.isRightClick() ? MouseEvent.BUTTON3 : MouseEvent.BUTTON1)); - } - else if (event.isDrag()) - { + new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_CLICKED, + System.currentTimeMillis(), modifiers, // when, modifiers. + webViewPoint.x, webViewPoint.y, clickCount, // x, y, clickCount + false, // isPopupTrigger. + event.isRightClick() ? MouseEvent.BUTTON3 : MouseEvent.BUTTON1)); + } else if (event.isDrag()) { this.webView.sendEvent( - new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_DRAGGED, - System.currentTimeMillis(), MouseEvent.BUTTON1_DOWN_MASK, // when, modifiers. - webViewPoint.x, webViewPoint.y, 0, // x, y, clickCount. - false, // isPopupTrigger. - MouseEvent.BUTTON1)); - } - else if (event.isDragEnd()) - { + new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_DRAGGED, + System.currentTimeMillis(), MouseEvent.BUTTON1_DOWN_MASK, // when, modifiers. + webViewPoint.x, webViewPoint.y, 0, // x, y, clickCount. + false, // isPopupTrigger. + MouseEvent.BUTTON1)); + } else if (event.isDragEnd()) { this.webView.sendEvent( - new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_RELEASED, - System.currentTimeMillis(), 0, // when, modifiers. - webViewPoint.x, webViewPoint.y, 0, // x, y, clickCount. - false, // isPopupTrigger. - MouseEvent.BUTTON1)); + new MouseEvent((Component) event.getSource(), MouseEvent.MOUSE_RELEASED, + System.currentTimeMillis(), 0, // when, modifiers. + webViewPoint.x, webViewPoint.y, 0, // x, y, clickCount. + false, // isPopupTrigger. + MouseEvent.BUTTON1)); } this.lastPickPoint = event.getPickPoint(); // Consume the SelectEvent now that it has been passed on to the WebView as a mouse event. We avoid consuming // left press events, since doing so prevents the WorldWindow from gaining focus. - if (!event.isLeftPress()) + if (!event.isLeftPress()) { event.consume(); + } } /** @@ -2142,10 +2036,10 @@ else if (event.isDragEnd()) * * @param event the event to send. */ - protected void handleKeyEvent(KeyEvent event) - { - if (this.webView != null) + protected void handleKeyEvent(KeyEvent event) { + if (this.webView != null) { this.webView.sendEvent(event); + } } /** @@ -2156,10 +2050,10 @@ protected void handleKeyEvent(KeyEvent event) * * @param event the event to send. */ - protected void handleMouseEvent(MouseEvent event) - { - if (this.webView == null) + protected void handleMouseEvent(MouseEvent event) { + if (this.webView == null) { return; + } // Convert the mouse event's screen point to the WebView's local coordinate system. Note that we send the mouse // event to the WebView even when its screen point is outside the WebView's bounding rectangle. This gives the @@ -2167,51 +2061,47 @@ protected void handleMouseEvent(MouseEvent event) Point webViewPoint = this.convertToWebView(event.getSource(), event.getPoint()); // Send a copy of the mouse event using the point in the WebView's local coordinate system. - if (event instanceof MouseWheelEvent) - { + if (event instanceof MouseWheelEvent) { this.webView.sendEvent( - new MouseWheelEvent((Component) event.getSource(), event.getID(), event.getWhen(), event.getModifiers(), - webViewPoint.x, webViewPoint.y, event.getClickCount(), event.isPopupTrigger(), - ((MouseWheelEvent) event).getScrollType(), ((MouseWheelEvent) event).getScrollAmount(), - ((MouseWheelEvent) event).getWheelRotation())); - } - else - { + new MouseWheelEvent((Component) event.getSource(), event.getID(), event.getWhen(), event.getModifiers(), + webViewPoint.x, webViewPoint.y, event.getClickCount(), event.isPopupTrigger(), + ((MouseWheelEvent) event).getScrollType(), ((MouseWheelEvent) event).getScrollAmount(), + ((MouseWheelEvent) event).getWheelRotation())); + } else { this.webView.sendEvent( - new MouseEvent((Component) event.getSource(), event.getID(), event.getWhen(), event.getModifiers(), - webViewPoint.x, webViewPoint.y, event.getClickCount(), event.isPopupTrigger(), event.getButton())); + new MouseEvent((Component) event.getSource(), event.getID(), event.getWhen(), event.getModifiers(), + webViewPoint.x, webViewPoint.y, event.getClickCount(), event.isPopupTrigger(), event.getButton())); } } /** * Converts the specified screen point from AWT coordinates to local WebView coordinates. * - * @param point The point to convert. + * @param point The point to convert. * @param context the component who's coordinate system the point is in. * * @return A new Point in the WebView's local coordinate system. */ - protected Point convertToWebView(Object context, Point point) - { + protected Point convertToWebView(Object context, Point point) { int x = point.x; int y = point.y; // Translate AWT coordinates to OpenGL screen coordinates by moving the Y origin from the upper left corner to // the lower left corner and flipping the direction of the Y axis. - if (context instanceof Component) + if (context instanceof Component) { y = ((Component) context).getHeight() - point.y; + } // Find the ordered renderable that contains the point. Rectangle rect = null; - for (OrderedBrowserBalloon obb : this.orderedRenderables.values()) - { + for (OrderedBrowserBalloon obb : this.orderedRenderables.values()) { rect = obb.webViewRect; - if (x >= rect.x && x <= rect.x && y >= rect.y && y <= rect.y) + if (x >= rect.x && x <= rect.x && y >= rect.y && y <= rect.y) { break; + } } - if (rect != null) - { + if (rect != null) { x -= rect.x; y -= rect.y; } diff --git a/src/gov/nasa/worldwind/render/AbstractGeneralShape.java b/src/gov/nasa/worldwind/render/AbstractGeneralShape.java index 42a4eeef75..9273be4d4e 100644 --- a/src/gov/nasa/worldwind/render/AbstractGeneralShape.java +++ b/src/gov/nasa/worldwind/render/AbstractGeneralShape.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.WorldWind; @@ -33,28 +32,28 @@ * archive. *

            * This class applies {@link ShapeAttributes} to the shape, but the effect of some of those attributes, such as {@link - * ShapeAttributes#isDrawOutline()} is dependent on the specific implementation of this AbstractGeneralShape. See - * the class description of those shapes to determine how shape attributes are applied. + * ShapeAttributes#isDrawOutline()} is dependent on the specific implementation of this + * AbstractGeneralShape. See the class description of those shapes to determine how shape attributes are + * applied. * * @author tag * @version $Id: AbstractGeneralShape.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractGeneralShape extends AbstractShape -{ +public abstract class AbstractGeneralShape extends AbstractShape { + /** * This class holds globe-specific data for this shape. It's managed via the shape-data cache in {@link * gov.nasa.worldwind.render.AbstractShape.AbstractShapeData}. */ - protected static class ShapeData extends AbstractShapeData - { + protected static class ShapeData extends AbstractShapeData { + /** * Construct a cache entry for this shape. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape this shape. */ - public ShapeData(DrawContext dc, AbstractGeneralShape shape) - { + public ShapeData(DrawContext dc, AbstractGeneralShape shape) { super(dc, shape.minExpiryTime, shape.maxExpiryTime); } } @@ -64,14 +63,17 @@ public ShapeData(DrawContext dc, AbstractGeneralShape shape) * * @return the current data cache entry. */ - protected ShapeData getCurrent() - { + protected ShapeData getCurrent() { return (ShapeData) this.getCurrentData(); } - /** This shape's geographic location. The altitude is relative to this shapes altitude mode. */ + /** + * This shape's geographic location. The altitude is relative to this shapes altitude mode. + */ protected Position modelPosition; - /** This shape's heading, positive values are clockwise from north. Null is an allowed value. */ + /** + * This shape's heading, positive values are clockwise from north. Null is an allowed value. + */ protected Angle heading; /** * This shape's pitch (often called tilt), its rotation about the model's X axis. Positive values are clockwise. @@ -83,23 +85,25 @@ protected ShapeData getCurrent() * Value. */ protected Angle roll; - /** A scale to apply to the model. Null is an allowed value. */ + /** + * A scale to apply to the model. Null is an allowed value. + */ protected Vec4 modelScale; - /** A map indicating the actual location of resources named in the model. Null is an allowed value. */ + /** + * A map indicating the actual location of resources named in the model. Null is an allowed value. + */ protected Map resourceMap; /** * Constructs a shape at 0 latitude, longitude and altitude. Because the shape's default altitude mode is * ABSOLUTE, the default altitude is relative to mean sea level. */ - public AbstractGeneralShape() - { + public AbstractGeneralShape() { this.modelPosition = Position.ZERO; } @Override - protected void initialize() - { + protected void initialize() { // Overridden to specify a default altitude mode unique to AbstractGeneralShape. this.altitudeMode = WorldWind.CLAMP_TO_GROUND; } @@ -109,8 +113,7 @@ protected void initialize() * * @return this shape's resource map, or null if this shape has no resource map. */ - public Map getResourceMap() - { + public Map getResourceMap() { return resourceMap; } @@ -119,8 +122,7 @@ public Map getResourceMap() * * @param resourceMap the resource map for this shape. May be null, in which case no resource map is used. */ - public void setResourceMap(Map resourceMap) - { + public void setResourceMap(Map resourceMap) { this.resourceMap = resourceMap; } @@ -129,8 +131,7 @@ public void setResourceMap(Map resourceMap) * * @return this shape's geographic position. The position's altitude is relative to this shape's altitude mode. */ - public Position getModelPosition() - { + public Position getModelPosition() { return modelPosition; } @@ -141,8 +142,7 @@ public Position getModelPosition() * * @throws IllegalArgumentException if the position is null. */ - public void setModelPosition(Position modelPosition) - { + public void setModelPosition(Position modelPosition) { this.modelPosition = modelPosition; } @@ -151,8 +151,7 @@ public void setModelPosition(Position modelPosition) * * @return this shape's scale, or null if no scale has been specified. */ - public Vec4 getModelScale() - { + public Vec4 getModelScale() { return modelScale; } @@ -162,8 +161,7 @@ public Vec4 getModelScale() * * @param modelScale this shape's scale. May be null, in which case no scaling is applied. */ - public void setModelScale(Vec4 modelScale) - { + public void setModelScale(Vec4 modelScale) { this.modelScale = modelScale; } @@ -172,8 +170,7 @@ public void setModelScale(Vec4 modelScale) * * @return this shape's heading, or null if no heading has been specified. */ - public Angle getHeading() - { + public Angle getHeading() { return heading; } @@ -182,8 +179,7 @@ public Angle getHeading() * * @param heading this shape's heading. May be null. */ - public void setHeading(Angle heading) - { + public void setHeading(Angle heading) { this.heading = heading; } @@ -192,10 +188,9 @@ public void setHeading(Angle heading) * axis. * * @return this shape's pitch, or null if no pitch has been specified. Positive values are clockwise as observed - * looking along the model's X axis toward the model's origin. + * looking along the model's X axis toward the model's origin. */ - public Angle getPitch() - { + public Angle getPitch() { return pitch; } @@ -204,10 +199,9 @@ public Angle getPitch() * axis. * * @param pitch this shape's pitch. Positive values are clockwise as observed looking along the model's X axis - * toward the model's origin. May be null. + * toward the model's origin. May be null. */ - public void setPitch(Angle pitch) - { + public void setPitch(Angle pitch) { this.pitch = pitch; } @@ -215,10 +209,9 @@ public void setPitch(Angle pitch) * Indicates this shape's roll, the angle to rotate this shape's model about its Y axis. * * @return this shape's roll, or null if no roll has been specified. Positive values are clockwise as observed - * looking along the model's Y axis toward the origin. + * looking along the model's Y axis toward the origin. */ - public Angle getRoll() - { + public Angle getRoll() { return roll; } @@ -226,27 +219,26 @@ public Angle getRoll() * Specifies this shape's roll, the angle to rotate this shape's model about its Y axis. * * @param roll this shape's roll. May be null. Positive values are clockwise as observed looking along the model's Y - * axis toward the origin. + * axis toward the origin. */ - public void setRoll(Angle roll) - { + public void setRoll(Angle roll) { this.roll = roll; } - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.getModelPosition(); } - protected Vec4 computeReferencePoint(Terrain terrain) - { + protected Vec4 computeReferencePoint(Terrain terrain) { Position refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return null; + } Vec4 refPt = terrain.getSurfacePoint(refPos.getLatitude(), refPos.getLongitude(), 0); - if (refPt == null) + if (refPt == null) { return null; + } return refPt; } @@ -256,43 +248,43 @@ protected Vec4 computeReferencePoint(Terrain terrain) *

            * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shapeData the current shape data for this shape. * * @return the minimum distance from the shape to the eye point. */ - protected double computeEyeDistance(DrawContext dc, ShapeData shapeData) - { + protected double computeEyeDistance(DrawContext dc, ShapeData shapeData) { Vec4 eyePoint = dc.getView().getEyePoint(); // TODO: compute distance using extent.getEffectiveRadius(Plane) Extent extent = shapeData.getExtent(); - if (extent != null) + if (extent != null) { return extent.getCenter().distanceTo3(eyePoint) + extent.getRadius(); + } Vec4 refPt = shapeData.getReferencePoint(); - if (refPt != null) + if (refPt != null) { return refPt.distanceTo3(eyePoint); + } return 0; } - public void moveTo(Position position) - { + public void moveTo(Position position) { this.setModelPosition(position); } @Override - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { String message = Logging.getMessage("unsupportedOperation.doExportAsKML"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } - /** {@inheritDoc} Not currently supported. */ - public Sector getSector() - { + /** + * {@inheritDoc} Not currently supported. + */ + public Sector getSector() { return null; } } diff --git a/src/gov/nasa/worldwind/render/AbstractShape.java b/src/gov/nasa/worldwind/render/AbstractShape.java index 129f77caa8..80e1a648f4 100644 --- a/src/gov/nasa/worldwind/render/AbstractShape.java +++ b/src/gov/nasa/worldwind/render/AbstractShape.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.*; @@ -36,29 +35,44 @@ * @version $Id: AbstractShape.java 3306 2015-07-08 22:00:14Z tgaskins $ */ public abstract class AbstractShape extends WWObjectImpl - implements Highlightable, OrderedRenderable, Movable, Movable2, ExtentHolder, GeographicExtent, Exportable, - Restorable, PreRenderable, Attributable, Draggable -{ - /** The default interior color. */ + implements Highlightable, OrderedRenderable, Movable, Movable2, ExtentHolder, GeographicExtent, Exportable, + Restorable, PreRenderable, Attributable, Draggable { + + /** + * The default interior color. + */ protected static final Material DEFAULT_INTERIOR_MATERIAL = Material.LIGHT_GRAY; - /** The default outline color. */ + /** + * The default outline color. + */ protected static final Material DEFAULT_OUTLINE_MATERIAL = Material.DARK_GRAY; - /** The default highlight color. */ + /** + * The default highlight color. + */ protected static final Material DEFAULT_HIGHLIGHT_MATERIAL = Material.WHITE; - /** The default altitude mode. */ + /** + * The default altitude mode. + */ protected static final int DEFAULT_ALTITUDE_MODE = WorldWind.ABSOLUTE; - /** The default outline pick width. */ + /** + * The default outline pick width. + */ protected static final int DEFAULT_OUTLINE_PICK_WIDTH = 10; - /** The default geometry regeneration interval. */ + /** + * The default geometry regeneration interval. + */ protected static final int DEFAULT_GEOMETRY_GENERATION_INTERVAL = 3000; - /** Indicates the number of vertices that must be present in order for VBOs to be used to render this shape. */ + /** + * Indicates the number of vertices that must be present in order for VBOs to be used to render this shape. + */ protected static final int VBO_THRESHOLD = Configuration.getIntegerValue(AVKey.VBO_THRESHOLD, 30); - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static ShapeAttributes defaultAttributes; - static - { + static { // Create and populate the default attributes. defaultAttributes = new BasicShapeAttributes(); defaultAttributes.setInteriorMaterial(DEFAULT_INTERIOR_MATERIAL); @@ -71,7 +85,7 @@ public abstract class AbstractShape extends WWObjectImpl * used during rendering, which may be at lower level of detail than required for accurate intersection * determination. * - * @param line the line to intersect. + * @param line the line to intersect. * @param terrain the {@link Terrain} to use when computing the shape's geometry. * * @return a list of intersections identifying where the line intersects the shape, or null if the line does not @@ -163,7 +177,7 @@ public abstract class AbstractShape extends WWObjectImpl * * @param xmlWriter the export writer to write to. * - * @throws IOException if an IO error occurs while writing to the output destination. + * @throws IOException if an IO error occurs while writing to the output destination. * @throws XMLStreamException if an exception occurs converting this shape's fields to XML. */ abstract protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException; @@ -177,9 +191,13 @@ public abstract class AbstractShape extends WWObjectImpl */ protected abstract AbstractShapeData createCacheEntry(DrawContext dc); - /** This shape's normal, non-highlighted attributes. */ + /** + * This shape's normal, non-highlighted attributes. + */ protected ShapeAttributes normalAttrs; - /** This shape's highlighted attributes. */ + /** + * This shape's highlighted attributes. + */ protected ShapeAttributes highlightAttrs; /** * The attributes active for a particular pick and render pass. These are determined according to the highlighting @@ -208,7 +226,9 @@ public abstract class AbstractShape extends WWObjectImpl protected Layer pickLayer; protected PickSupport pickSupport = new PickSupport(); - /** Holds globe-dependent computed data. One entry per globe encountered during {@link #render(DrawContext)}. */ + /** + * Holds globe-dependent computed data. One entry per globe encountered during {@link #render(DrawContext)}. + */ protected ShapeDataCache shapeDataCache = new ShapeDataCache(60000); // Additional drag context @@ -225,21 +245,30 @@ public abstract class AbstractShape extends WWObjectImpl * * @return the data cache entry for the current rendering. */ - protected AbstractShapeData getCurrentData() - { + protected AbstractShapeData getCurrentData() { return this.currentData; } - /** Holds the globe-dependent data captured in this shape's data cache. */ - protected static class AbstractShapeData extends ShapeDataCache.ShapeDataCacheEntry - { - /** Identifies the frame used to calculate this entry's values. */ + /** + * Holds the globe-dependent data captured in this shape's data cache. + */ + protected static class AbstractShapeData extends ShapeDataCache.ShapeDataCacheEntry { + + /** + * Identifies the frame used to calculate this entry's values. + */ protected long frameNumber = -1; - /** This entry's reference point. */ + /** + * This entry's reference point. + */ protected Vec4 referencePoint; - /** A quick-to-compute metric to determine eye distance changes that invalidate this entry's geometry. */ + /** + * A quick-to-compute metric to determine eye distance changes that invalidate this entry's geometry. + */ protected Double referenceDistance; - /** The GPU-resource cache key to use for this entry's VBOs, if VBOs are used. */ + /** + * The GPU-resource cache key to use for this entry's VBOs, if VBOs are used. + */ protected Object vboCacheKey = new Object(); /** @@ -247,103 +276,88 @@ protected static class AbstractShapeData extends ShapeDataCache.ShapeDataCacheEn * draw context and capture the current vertical exaggeration. The entry becomes invalid when these values * change or when the entry's expiration timer expires. * - * @param dc the current draw context. + * @param dc the current draw context. * @param minExpiryTime the minimum number of milliseconds to use this shape before regenerating its geometry. * @param maxExpiryTime the maximum number of milliseconds to use this shape before regenerating its geometry. */ - protected AbstractShapeData(DrawContext dc, long minExpiryTime, long maxExpiryTime) - { + protected AbstractShapeData(DrawContext dc, long minExpiryTime, long maxExpiryTime) { super(dc, minExpiryTime, maxExpiryTime); } - public long getFrameNumber() - { + public long getFrameNumber() { return frameNumber; } - public void setFrameNumber(long frameNumber) - { + public void setFrameNumber(long frameNumber) { this.frameNumber = frameNumber; } - public Vec4 getReferencePoint() - { + public Vec4 getReferencePoint() { return referencePoint; } - public void setReferencePoint(Vec4 referencePoint) - { + public void setReferencePoint(Vec4 referencePoint) { this.referencePoint = referencePoint; } - public Object getVboCacheKey() - { + public Object getVboCacheKey() { return vboCacheKey; } - public void setVboCacheKey(Object vboCacheKey) - { + public void setVboCacheKey(Object vboCacheKey) { this.vboCacheKey = vboCacheKey; } - public Double getReferenceDistance() - { + public Double getReferenceDistance() { return referenceDistance; } - public void setReferenceDistance(Double referenceDistance) - { + public void setReferenceDistance(Double referenceDistance) { this.referenceDistance = referenceDistance; } } - /** Outlined shapes are drawn as {@link gov.nasa.worldwind.render.OutlinedShape}s. */ - protected OutlinedShape outlineShapeRenderer = new OutlinedShape() - { - public boolean isDrawOutline(DrawContext dc, Object shape) - { + /** + * Outlined shapes are drawn as {@link gov.nasa.worldwind.render.OutlinedShape}s. + */ + protected OutlinedShape outlineShapeRenderer = new OutlinedShape() { + public boolean isDrawOutline(DrawContext dc, Object shape) { return ((AbstractShape) shape).mustDrawOutline(); } - public boolean isDrawInterior(DrawContext dc, Object shape) - { + public boolean isDrawInterior(DrawContext dc, Object shape) { return ((AbstractShape) shape).mustDrawInterior(); } - public boolean isEnableDepthOffset(DrawContext dc, Object shape) - { + public boolean isEnableDepthOffset(DrawContext dc, Object shape) { return ((AbstractShape) shape).isEnableDepthOffset(); } - public void drawOutline(DrawContext dc, Object shape) - { + public void drawOutline(DrawContext dc, Object shape) { ((AbstractShape) shape).drawOutline(dc); } - public void drawInterior(DrawContext dc, Object shape) - { + public void drawInterior(DrawContext dc, Object shape) { ((AbstractShape) shape).drawInterior(dc); } - public Double getDepthOffsetFactor(DrawContext dc, Object shape) - { + public Double getDepthOffsetFactor(DrawContext dc, Object shape) { return null; } - public Double getDepthOffsetUnits(DrawContext dc, Object shape) - { + public Double getDepthOffsetUnits(DrawContext dc, Object shape) { return null; } }; - /** Invokes {@link #initialize()} during construction and sets the data cache's expiration time to a default value. */ - protected AbstractShape() - { + /** + * Invokes {@link #initialize()} during construction and sets the data cache's expiration time to a default value. + */ + protected AbstractShape() { this.initialize(); } - protected AbstractShape(AbstractShape source) - { + protected AbstractShape(AbstractShape source) { this.normalAttrs = new BasicShapeAttributes(source.normalAttrs); this.highlightAttrs = new BasicShapeAttributes(source.highlightAttrs); this.highlighted = source.highlighted; @@ -360,9 +374,10 @@ protected AbstractShape(AbstractShape source) this.initialize(); } - /** Invalidates computed values. Called when this shape's contents or certain attributes change. */ - protected void reset() - { + /** + * Invalidates computed values. Called when this shape's contents or certain attributes change. + */ + protected void reset() { this.shapeDataCache.removeAllEntries(); this.sector = null; this.surfaceShape = null; @@ -373,8 +388,7 @@ protected void reset() * * @return this shape's normal attributes. May be null. */ - public ShapeAttributes getAttributes() - { + public ShapeAttributes getAttributes() { return this.normalAttrs; } @@ -383,12 +397,12 @@ public ShapeAttributes getAttributes() * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public void setAttributes(ShapeAttributes normalAttrs) - { + public void setAttributes(ShapeAttributes normalAttrs) { this.normalAttrs = normalAttrs; - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.surfaceShape.setAttributes(normalAttrs); + } } /** @@ -396,8 +410,7 @@ public void setAttributes(ShapeAttributes normalAttrs) * * @return this shape's highlight attributes. May be null. */ - public ShapeAttributes getHighlightAttributes() - { + public ShapeAttributes getHighlightAttributes() { return highlightAttrs; } @@ -406,21 +419,19 @@ public ShapeAttributes getHighlightAttributes() * * @param highlightAttrs the highlight attributes. May be null, in which case default attributes are used. */ - public void setHighlightAttributes(ShapeAttributes highlightAttrs) - { + public void setHighlightAttributes(ShapeAttributes highlightAttrs) { this.highlightAttrs = highlightAttrs; - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.surfaceShape.setHighlightAttributes(highlightAttrs); + } } - public boolean isHighlighted() - { + public boolean isHighlighted() { return highlighted; } - public void setHighlighted(boolean highlighted) - { + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } @@ -431,8 +442,7 @@ public void setHighlighted(boolean highlighted) * * @see #setVisible(boolean) */ - public boolean isVisible() - { + public boolean isVisible() { return visible; } @@ -443,8 +453,7 @@ public boolean isVisible() * * @see #setAttributes(ShapeAttributes) */ - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.visible = visible; } @@ -455,8 +464,7 @@ public void setVisible(boolean visible) * * @see #setAltitudeMode(int) */ - public int getAltitudeMode() - { + public int getAltitudeMode() { return altitudeMode; } @@ -470,17 +478,16 @@ public int getAltitudeMode() * * @param altitudeMode the altitude mode. The default value is {@link WorldWind#ABSOLUTE}. */ - public void setAltitudeMode(int altitudeMode) - { - if (this.altitudeMode == altitudeMode) + public void setAltitudeMode(int altitudeMode) { + if (this.altitudeMode == altitudeMode) { return; + } this.altitudeMode = altitudeMode; this.reset(); } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.getCurrentData() != null ? this.getCurrentData().getEyeDistance() : 0; } @@ -491,8 +498,7 @@ public double getDistanceFromEye() * * @see #setEnableBatchRendering(boolean) */ - public boolean isEnableBatchRendering() - { + public boolean isEnableBatchRendering() { return enableBatchRendering; } @@ -503,8 +509,7 @@ public boolean isEnableBatchRendering() * * @param enableBatchRendering true to enable batch rendering, otherwise false. */ - public void setEnableBatchRendering(boolean enableBatchRendering) - { + public void setEnableBatchRendering(boolean enableBatchRendering) { this.enableBatchRendering = enableBatchRendering; } @@ -515,8 +520,7 @@ public void setEnableBatchRendering(boolean enableBatchRendering) * * @see #setEnableBatchPicking(boolean) */ - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return enableBatchPicking; } @@ -530,8 +534,7 @@ public boolean isEnableBatchPicking() * * @param enableBatchPicking true to enable batch rendering, otherwise false. */ - public void setEnableBatchPicking(boolean enableBatchPicking) - { + public void setEnableBatchPicking(boolean enableBatchPicking) { this.enableBatchPicking = enableBatchPicking; } @@ -541,8 +544,7 @@ public void setEnableBatchPicking(boolean enableBatchPicking) * * @return the outline line width used during picking. */ - public int getOutlinePickWidth() - { + public int getOutlinePickWidth() { return this.outlinePickWidth; } @@ -556,10 +558,8 @@ public int getOutlinePickWidth() * * @throws IllegalArgumentException if the width is less than 0. */ - public void setOutlinePickWidth(int outlinePickWidth) - { - if (outlinePickWidth < 0) - { + public void setOutlinePickWidth(int outlinePickWidth) { + if (outlinePickWidth < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -574,8 +574,7 @@ public void setOutlinePickWidth(int outlinePickWidth) * * @return true if depth offset is applied, otherwise false. */ - public boolean isEnableDepthOffset() - { + public boolean isEnableDepthOffset() { return this.enableDepthOffset; } @@ -586,8 +585,7 @@ public boolean isEnableDepthOffset() * * @param enableDepthOffset true if depth offset is applied, otherwise false. */ - public void setEnableDepthOffset(boolean enableDepthOffset) - { + public void setEnableDepthOffset(boolean enableDepthOffset) { this.enableDepthOffset = enableDepthOffset; } @@ -599,8 +597,7 @@ public void setEnableDepthOffset(boolean enableDepthOffset) * * @see #setGeometryRegenerationInterval(int) */ - public long getGeometryRegenerationInterval() - { + public long getGeometryRegenerationInterval() { return this.maxExpiryTime; } @@ -613,17 +610,16 @@ public long getGeometryRegenerationInterval() * other than geometry regeneration. * * @param geometryRegenerationInterval the geometry regeneration interval, in milliseconds. The default is two - * seconds. + * seconds. */ - public void setGeometryRegenerationInterval(int geometryRegenerationInterval) - { + public void setGeometryRegenerationInterval(int geometryRegenerationInterval) { this.maxExpiryTime = Math.max(geometryRegenerationInterval, 0); this.minExpiryTime = (long) (0.6 * (double) this.maxExpiryTime); - for (ShapeDataCache.ShapeDataCacheEntry shapeData : this.shapeDataCache) - { - if (shapeData != null) + for (ShapeDataCache.ShapeDataCacheEntry shapeData : this.shapeDataCache) { + if (shapeData != null) { shapeData.getTimer().setExpiryTime(this.minExpiryTime, this.maxExpiryTime); + } } } @@ -632,21 +628,18 @@ public void setGeometryRegenerationInterval(int geometryRegenerationInterval) * the default value of the first position in the polygon's outer boundary. * * @param referencePosition the reference position. May be null, in which case the first position of the outer - * boundary is the reference position. + * boundary is the reference position. */ - public void setReferencePosition(Position referencePosition) - { + public void setReferencePosition(Position referencePosition) { this.referencePosition = referencePosition; this.reset(); } - public Object getDelegateOwner() - { + public Object getDelegateOwner() { return delegateOwner; } - public void setDelegateOwner(Object delegateOwner) - { + public void setDelegateOwner(Object delegateOwner) { this.delegateOwner = delegateOwner; } @@ -655,8 +648,7 @@ public void setDelegateOwner(Object delegateOwner) * * @return this shape's extent, or null if an extent has not been computed. */ - public Extent getExtent() - { + public Extent getExtent() { return this.getCurrentData().getExtent(); } @@ -667,15 +659,14 @@ public Extent getExtent() * @return the Cartesian coordinates corresponding to this shape's reference position, or null if the point has not * been computed. */ - public Vec4 getReferencePoint() - { + public Vec4 getReferencePoint() { return this.currentData.getReferencePoint(); } - public Extent getExtent(Globe globe, double verticalExaggeration) - { - if (globe == null) + public Extent getExtent(Globe globe, double verticalExaggeration) { + if (globe == null) { return null; + } ShapeDataCache.ShapeDataCacheEntry entry = this.shapeDataCache.getEntry(globe); @@ -688,31 +679,25 @@ public Extent getExtent(Globe globe, double verticalExaggeration) * * @see #getActiveAttributes() */ - protected void determineActiveAttributes() - { - if (this.isHighlighted()) - { - if (this.getHighlightAttributes() != null) + protected void determineActiveAttributes() { + if (this.isHighlighted()) { + if (this.getHighlightAttributes() != null) { this.activeAttributes.copy(this.getHighlightAttributes()); - else - { + } else { // If no highlight attributes have been specified we need to use the normal attributes but adjust them // to cause highlighting. - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); - else + } else { this.activeAttributes.copy(defaultAttributes); + } this.activeAttributes.setOutlineMaterial(DEFAULT_HIGHLIGHT_MATERIAL); this.activeAttributes.setInteriorMaterial(DEFAULT_HIGHLIGHT_MATERIAL); } - } - else if (this.getAttributes() != null) - { + } else if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); - } - else - { + } else { this.activeAttributes.copy(defaultAttributes); } } @@ -725,8 +710,7 @@ else if (this.getAttributes() != null) * * @return this shape's currently active attributes. */ - public ShapeAttributes getActiveAttributes() - { + public ShapeAttributes getActiveAttributes() { return this.activeAttributes; } @@ -740,8 +724,7 @@ public ShapeAttributes getActiveAttributes() * * @return true if this shape's geometry must be regenerated, otherwise false. */ - protected boolean mustRegenerateGeometry(DrawContext dc) - { + protected boolean mustRegenerateGeometry(DrawContext dc) { return this.getCurrentData().isExpired(dc) || !this.getCurrentData().isValid(dc); } @@ -752,8 +735,7 @@ protected boolean mustRegenerateGeometry(DrawContext dc) * * @return true if this shape should use vertex buffer objects, otherwise false. */ - protected boolean shouldUseVBOs(DrawContext dc) - { + protected boolean shouldUseVBOs(DrawContext dc) { return dc.getGLRuntimeCapabilities().isUseVertexBufferObject(); } @@ -762,8 +744,7 @@ protected boolean shouldUseVBOs(DrawContext dc) * * @return true if an interior must be drawn, otherwise false. */ - protected boolean mustDrawInterior() - { + protected boolean mustDrawInterior() { return this.getActiveAttributes().isDrawInterior(); } @@ -772,8 +753,7 @@ protected boolean mustDrawInterior() * * @return true if the outline should be drawn, otherwise false. */ - protected boolean mustDrawOutline() - { + protected boolean mustDrawOutline() { return this.getActiveAttributes().isDrawOutline(); } @@ -785,8 +765,7 @@ protected boolean mustDrawOutline() * * @return true if lighting must be applied, otherwise false. */ - protected boolean mustApplyLighting(DrawContext dc) - { + protected boolean mustApplyLighting(DrawContext dc) { return this.mustApplyLighting(dc, null); } @@ -794,14 +773,13 @@ protected boolean mustApplyLighting(DrawContext dc) * Indicates whether standard lighting must be applied by consulting either the specified active attributes or the * current active attributes. * - * @param dc the current draw context + * @param dc the current draw context * @param activeAttrs the attribute bundle to consider when determining whether lighting is applied. May be null, in - * which case the current active attributes are used. + * which case the current active attributes are used. * * @return true if lighting must be applied, otherwise false. */ - protected boolean mustApplyLighting(DrawContext dc, ShapeAttributes activeAttrs) - { + protected boolean mustApplyLighting(DrawContext dc, ShapeAttributes activeAttrs) { return activeAttrs != null ? activeAttrs.isEnableLighting() : this.activeAttributes.isEnableLighting(); } @@ -813,8 +791,7 @@ protected boolean mustApplyLighting(DrawContext dc, ShapeAttributes activeAttrs) * * @return true if normal vectors must be computed, otherwise false. */ - protected boolean mustCreateNormals(DrawContext dc) - { + protected boolean mustCreateNormals(DrawContext dc) { return this.mustCreateNormals(dc, null); } @@ -823,14 +800,13 @@ protected boolean mustCreateNormals(DrawContext dc) * current active attributes. Calls {@link #mustApplyLighting(DrawContext, ShapeAttributes)}, passing the specified * active attrs. * - * @param dc the current draw context + * @param dc the current draw context * @param activeAttrs the attribute bundle to consider when determining whether normals should be computed. May be - * null, in which case the current active attributes are used. + * null, in which case the current active attributes are used. * * @return true if normal vectors must be computed, otherwise false. */ - protected boolean mustCreateNormals(DrawContext dc, ShapeAttributes activeAttrs) - { + protected boolean mustCreateNormals(DrawContext dc, ShapeAttributes activeAttrs) { return this.mustApplyLighting(dc, activeAttrs); } @@ -843,21 +819,18 @@ protected boolean mustCreateNormals(DrawContext dc, ShapeAttributes activeAttrs) * * @throws IllegalArgumentException if the image source is null. */ - protected WWTexture makeTexture(Object imageSource) - { + protected WWTexture makeTexture(Object imageSource) { return new LazilyLoadedTexture(imageSource, true); } @Override - public void preRender(DrawContext dc) - { - if (dc.getGlobe() instanceof Globe2D) - { - if (this.surfaceShape == null) - { + public void preRender(DrawContext dc) { + if (dc.getGlobe() instanceof Globe2D) { + if (this.surfaceShape == null) { this.surfaceShape = this.createSurfaceShape(); - if (this.surfaceShape == null) + if (this.surfaceShape == null) { return; + } this.surfaceShape.setAttributes(this.getAttributes()); this.surfaceShape.setHighlightAttributes(this.getHighlightAttributes()); @@ -873,8 +846,7 @@ public void preRender(DrawContext dc) * * @return The surface shape to represent this Path on a 2D globe. */ - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return null; } @@ -883,8 +855,7 @@ protected SurfaceShape createSurfaceShape() * globes. Subclasses should override this method if they need to update more than the highlighted state, visibility * state and delegate owner. */ - protected void updateSurfaceShape() - { + protected void updateSurfaceShape() { this.surfaceShape.setHighlighted(this.isHighlighted()); this.surfaceShape.setVisible(this.isVisible()); @@ -892,46 +863,38 @@ protected void updateSurfaceShape() this.surfaceShape.setDelegateOwner(o != null ? o : this); } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { // This method is called only when ordered renderables are being drawn. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.render(dc); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { // This render method is called three times during frame generation. It's first called as a {@link Renderable} // during Renderable picking. It's called again during normal rendering. And it's called a third // time as an OrderedRenderable. The first two calls determine whether to add the shape to the ordered renderable // list during pick and render. The third call just draws the ordered renderable. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc.getGlobe() instanceof Globe2D && this.surfaceShape != null) - { + if (dc.getGlobe() instanceof Globe2D && this.surfaceShape != null) { this.surfaceShape.render(dc); return; } @@ -939,40 +902,44 @@ public void render(DrawContext dc) // Retrieve the cached data for the current globe. If it doesn't yet exist, create it. Most code subsequently // executed depends on currentData being non-null. this.currentData = (AbstractShapeData) this.shapeDataCache.getEntry(dc.getGlobe()); - if (this.currentData == null) - { + if (this.currentData == null) { this.currentData = this.createCacheEntry(dc); this.shapeDataCache.addEntry(this.currentData); } - if (dc.getSurfaceGeometry() == null) + if (dc.getSurfaceGeometry() == null) { return; + } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } - if (this.isTerrainDependent()) + if (this.isTerrainDependent()) { this.checkViewDistanceExpiration(dc); + } // Invalidate the extent if the vertical exaggeration has changed. if (this.currentData.getVerticalExaggeration() != dc.getVerticalExaggeration()) { this.currentData.setExtent(null); } - if (this.getExtent() != null) - { - if (!this.intersectsFrustum(dc)) + if (this.getExtent() != null) { + if (!this.intersectsFrustum(dc)) { return; + } // If the shape is less that a pixel in size, don't render it. - if (dc.isSmall(this.getExtent(), 1)) + if (dc.isSmall(this.getExtent(), 1)) { return; + } } - if (dc.isOrderedRenderingMode()) + if (dc.isOrderedRenderingMode()) { this.drawOrderedRenderable(dc); - else + } else { this.makeOrderedRenderable(dc); + } } /** @@ -983,23 +950,23 @@ public void render(DrawContext dc) * * @param dc the current draw context. */ - protected void makeOrderedRenderable(DrawContext dc) - { + protected void makeOrderedRenderable(DrawContext dc) { // Re-use values already calculated this frame. - if (dc.getFrameTimeStamp() != this.getCurrentData().getFrameNumber()) - { + if (dc.getFrameTimeStamp() != this.getCurrentData().getFrameNumber()) { this.determineActiveAttributes(); - if (this.getActiveAttributes() == null) + if (this.getActiveAttributes() == null) { return; + } // Regenerate the positions and shape at a specified frequency. - if (this.mustRegenerateGeometry(dc)) - { - if (!this.doMakeOrderedRenderable(dc)) + if (this.mustRegenerateGeometry(dc)) { + if (!this.doMakeOrderedRenderable(dc)) { return; + } - if (this.shouldUseVBOs(dc)) + if (this.shouldUseVBOs(dc)) { this.fillVBO(dc); + } this.getCurrentData().restartTimer(dc); } @@ -1007,11 +974,13 @@ protected void makeOrderedRenderable(DrawContext dc) this.getCurrentData().setFrameNumber(dc.getFrameTimeStamp()); } - if (!this.isOrderedRenderableValid(dc)) + if (!this.isOrderedRenderableValid(dc)) { return; + } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { this.pickLayer = dc.getCurrentLayer(); + } this.addOrderedRenderable(dc); } @@ -1021,8 +990,7 @@ protected void makeOrderedRenderable(DrawContext dc) * * @param dc the current draw context. */ - protected void addOrderedRenderable(DrawContext dc) - { + protected void addOrderedRenderable(DrawContext dc) { dc.addOrderedRenderable(this); } @@ -1031,8 +999,7 @@ protected void addOrderedRenderable(DrawContext dc) * * @return true if this shape's geometry depends on the terrain, otherwise false. */ - protected boolean isTerrainDependent() - { + protected boolean isTerrainDependent() { return this.getAltitudeMode() != WorldWind.ABSOLUTE; } @@ -1044,8 +1011,7 @@ protected boolean isTerrainDependent() * @return true if the terrain dependent geometry is updated as the eye distance changes, otherwise false. The * default is true. */ - public boolean isViewDistanceExpiration() - { + public boolean isViewDistanceExpiration() { return viewDistanceExpiration; } @@ -1056,8 +1022,7 @@ public boolean isViewDistanceExpiration() * * @param viewDistanceExpiration true to enable view distance expiration, otherwise false. */ - public void setViewDistanceExpiration(boolean viewDistanceExpiration) - { + public void setViewDistanceExpiration(boolean viewDistanceExpiration) { this.viewDistanceExpiration = viewDistanceExpiration; } @@ -1067,22 +1032,22 @@ public void setViewDistanceExpiration(boolean viewDistanceExpiration) * * @param dc the current draw context. */ - protected void checkViewDistanceExpiration(DrawContext dc) - { + protected void checkViewDistanceExpiration(DrawContext dc) { // Determine whether the distance of this shape from the eye has changed significantly. Invalidate the previous // extent and expire the shape geometry if it has. "Significantly" is considered a 10% difference. - if (!this.isViewDistanceExpiration()) + if (!this.isViewDistanceExpiration()) { return; + } Vec4 refPt = this.currentData.getReferencePoint(); - if (refPt == null) + if (refPt == null) { return; + } double newRefDistance = dc.getView().getEyePoint().distanceTo3(refPt); Double oldRefDistance = this.currentData.getReferenceDistance(); - if (oldRefDistance == null || Math.abs(newRefDistance - oldRefDistance) / oldRefDistance > 0.10) - { + if (oldRefDistance == null || Math.abs(newRefDistance - oldRefDistance) / oldRefDistance > 0.10) { this.currentData.setExpired(true); this.currentData.setExtent(null); this.currentData.setReferenceDistance(newRefDistance); @@ -1098,13 +1063,13 @@ protected void checkViewDistanceExpiration(DrawContext dc) * * @return true if this shape intersects the frustum, otherwise false. */ - protected boolean intersectsFrustum(DrawContext dc) - { - if (this.getExtent() == null) + protected boolean intersectsFrustum(DrawContext dc) { + if (this.getExtent() == null) { return true; // don't know the visibility, shape hasn't been computed yet - - if (dc.isPickingMode()) + } + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(this.getExtent()); + } return dc.getView().getFrustumInModelCoordinates().intersects(this.getExtent()); } @@ -1116,18 +1081,15 @@ protected boolean intersectsFrustum(DrawContext dc) * * @param dc the current draw context. */ - protected void drawOrderedRenderable(DrawContext dc) - { + protected void drawOrderedRenderable(DrawContext dc) { this.beginDrawing(dc, 0); - try - { + try { this.doDrawOrderedRenderable(dc, this.pickSupport); - if (this.isEnableBatchRendering()) + if (this.isEnableBatchRendering()) { this.drawBatched(dc); - } - finally - { + } + } finally { this.endDrawing(dc); } } @@ -1140,35 +1102,33 @@ protected void drawOrderedRenderable(DrawContext dc) * * @param dc the current draw context. */ - protected void drawBatched(DrawContext dc) - { + protected void drawBatched(DrawContext dc) { // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - if (!dc.isPickingMode()) - { - while (nextItem != null && nextItem.getClass() == this.getClass()) - { + if (!dc.isPickingMode()) { + while (nextItem != null && nextItem.getClass() == this.getClass()) { AbstractShape shape = (AbstractShape) nextItem; - if (!shape.isEnableBatchRendering()) + if (!shape.isEnableBatchRendering()) { break; + } dc.pollOrderedRenderables(); // take it off the queue shape.doDrawOrderedRenderable(dc, this.pickSupport); nextItem = dc.peekOrderedRenderables(); } - } - else if (this.isEnableBatchPicking()) - { - while (nextItem != null && nextItem.getClass() == this.getClass()) - { + } else if (this.isEnableBatchPicking()) { + while (nextItem != null && nextItem.getClass() == this.getClass()) { AbstractShape shape = (AbstractShape) nextItem; - if (!shape.isEnableBatchRendering() || !shape.isEnableBatchPicking()) + if (!shape.isEnableBatchRendering() || !shape.isEnableBatchPicking()) { break; + } if (shape.pickLayer != this.pickLayer) // batch pick only within a single layer + { break; + } dc.pollOrderedRenderables(); // take it off the queue shape.doDrawOrderedRenderable(dc, this.pickSupport); @@ -1186,19 +1146,17 @@ else if (this.isEnableBatchPicking()) *

            * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickCandidates a pick support holding the picked object list to add this shape to. */ - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) - { + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) { this.currentData = (AbstractShapeData) this.shapeDataCache.getEntry(dc.getGlobe()); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. dc.getView().setReferenceCenter(dc, this.getCurrentData().getReferencePoint()); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { Color pickColor = dc.getUniquePickColor(); pickCandidates.addPickableObject(this.createPickedObject(pickColor.getRGB())); gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue()); @@ -1211,7 +1169,7 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate * Creates a {@link gov.nasa.worldwind.pick.PickedObject} for this shape and the specified unique pick color. The * PickedObject returned by this method will be added to the pick list to represent the current shape. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickColor the unique color for this shape. * * @return a new picked object. @@ -1219,8 +1177,7 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate * @deprecated Use the more general {@link #createPickedObject(int)} instead. */ @SuppressWarnings({"UnusedParameters"}) - protected PickedObject createPickedObject(DrawContext dc, Color pickColor) - { + protected PickedObject createPickedObject(DrawContext dc, Color pickColor) { return this.createPickedObject(pickColor.getRGB()); } @@ -1232,8 +1189,7 @@ protected PickedObject createPickedObject(DrawContext dc, Color pickColor) * * @return a new picked object. */ - protected PickedObject createPickedObject(int colorCode) - { + protected PickedObject createPickedObject(int colorCode) { return new PickedObject(colorCode, this.getDelegateOwner() != null ? this.getDelegateOwner() : this); } @@ -1242,16 +1198,14 @@ protected PickedObject createPickedObject(int colorCode) *

            * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * - * @param dc the current draw context. - * @param attrMask an attribute mask indicating state the caller will set. This base class implementation sets - * GL_CURRENT_BIT, GL_LINE_BIT, GL_HINT_BIT, GL_POLYGON_BIT, GL_COLOR_BUFFER_BIT, and + * @param dc the current draw context. + * @param attrMask an attribute mask indicating state the caller will set. This base class implementation sets GL_CURRENT_BIT, GL_LINE_BIT, GL_HINT_BIT, GL_POLYGON_BIT, GL_COLOR_BUFFER_BIT, and * GL_TRANSFORM_BIT. * * @return the stack handler used to set the OpenGL state. Callers should use this to set additional state, * especially state indicated in the attribute mask argument. */ - protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) - { + protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.BEogsh.clear(); @@ -1259,23 +1213,20 @@ protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) // for this shape, e.g. if (mustApplyBlending...), it doesn't work with batch rendering because subsequent // shapes in the batch may have the feature enabled. attrMask |= GL2.GL_CURRENT_BIT - | GL2.GL_DEPTH_BUFFER_BIT - | GL2.GL_LINE_BIT | GL2.GL_HINT_BIT // for outlines - | GL2.GL_COLOR_BUFFER_BIT // for blending - | GL2.GL_TRANSFORM_BIT // for texture - | GL2.GL_POLYGON_BIT; // for culling + | GL2.GL_DEPTH_BUFFER_BIT + | GL2.GL_LINE_BIT | GL2.GL_HINT_BIT // for outlines + | GL2.GL_COLOR_BUFFER_BIT // for blending + | GL2.GL_TRANSFORM_BIT // for texture + | GL2.GL_POLYGON_BIT; // for culling this.BEogsh.pushAttrib(gl, attrMask); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.beginStandardLighting(); gl.glEnable(GL.GL_LINE_SMOOTH); gl.glEnable(GL.GL_BLEND); OGLUtil.applyBlending(gl, false); - } - else - { + } else { gl.glDisable(GL.GL_LINE_SMOOTH); gl.glDisable(GL.GL_BLEND); } @@ -1297,16 +1248,14 @@ protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) * * @param dc the current draw context. */ - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. dc.getView().popReferenceCenter(dc); gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); // explicitly disable normal array client state; fixes WWJ-450 - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.endStandardLighting(); gl.glDisable(GL.GL_TEXTURE_2D); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); @@ -1322,8 +1271,7 @@ protected void endDrawing(DrawContext dc) * * @param dc the current draw context. */ - protected void drawOutline(DrawContext dc) - { + protected void drawOutline(DrawContext dc) { ShapeAttributes activeAttrs = this.getActiveAttributes(); this.prepareToDrawOutline(dc, activeAttrs, defaultAttributes); @@ -1335,36 +1283,33 @@ protected void drawOutline(DrawContext dc) * Establishes OpenGL state for drawing the outline, including setting the color/material, line smoothing, line * width and stipple. Disables texture. * - * @param dc the current draw context. - * @param activeAttrs the attributes indicating the state value to set. + * @param dc the current draw context. + * @param activeAttrs the attributes indicating the state value to set. * @param defaultAttrs the attributes to use if activeAttrs does not contain a necessary value. */ - protected void prepareToDrawOutline(DrawContext dc, ShapeAttributes activeAttrs, ShapeAttributes defaultAttrs) - { - if (activeAttrs == null || !activeAttrs.isDrawOutline()) + protected void prepareToDrawOutline(DrawContext dc, ShapeAttributes activeAttrs, ShapeAttributes defaultAttrs) { + if (activeAttrs == null || !activeAttrs.isDrawOutline()) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { Material material = activeAttrs.getOutlineMaterial(); - if (material == null) + if (material == null) { material = defaultAttrs.getOutlineMaterial(); + } - if (this.mustApplyLighting(dc, activeAttrs)) - { + if (this.mustApplyLighting(dc, activeAttrs)) { material.apply(gl, GL2.GL_FRONT_AND_BACK, (float) activeAttrs.getOutlineOpacity()); gl.glEnable(GL2.GL_LIGHTING); gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); - } - else - { + } else { Color sc = material.getDiffuse(); double opacity = activeAttrs.getOutlineOpacity(); gl.glColor4ub((byte) sc.getRed(), (byte) sc.getGreen(), (byte) sc.getBlue(), - (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); + (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); gl.glDisable(GL2.GL_LIGHTING); gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); @@ -1373,18 +1318,16 @@ protected void prepareToDrawOutline(DrawContext dc, ShapeAttributes activeAttrs, gl.glHint(GL.GL_LINE_SMOOTH_HINT, activeAttrs.isEnableAntialiasing() ? GL.GL_NICEST : GL.GL_DONT_CARE); } - if (dc.isPickingMode() && activeAttrs.getOutlineWidth() < this.getOutlinePickWidth()) + if (dc.isPickingMode() && activeAttrs.getOutlineWidth() < this.getOutlinePickWidth()) { gl.glLineWidth(this.getOutlinePickWidth()); - else + } else { gl.glLineWidth((float) activeAttrs.getOutlineWidth()); + } - if (activeAttrs.getOutlineStippleFactor() > 0) - { + if (activeAttrs.getOutlineStippleFactor() > 0) { gl.glEnable(GL2.GL_LINE_STIPPLE); gl.glLineStipple(activeAttrs.getOutlineStippleFactor(), activeAttrs.getOutlineStipplePattern()); - } - else - { + } else { gl.glDisable(GL2.GL_LINE_STIPPLE); } @@ -1398,8 +1341,7 @@ protected void prepareToDrawOutline(DrawContext dc, ShapeAttributes activeAttrs, * * @param dc the current draw context. */ - protected void drawInterior(DrawContext dc) - { + protected void drawInterior(DrawContext dc) { this.prepareToDrawInterior(dc, this.getActiveAttributes(), defaultAttributes); this.doDrawInterior(dc); @@ -1409,60 +1351,58 @@ protected void drawInterior(DrawContext dc) * Establishes OpenGL state for drawing the interior, including setting the color/material. Enabling texture is left * to the subclass. * - * @param dc the current draw context. - * @param activeAttrs the attributes indicating the state value to set. + * @param dc the current draw context. + * @param activeAttrs the attributes indicating the state value to set. * @param defaultAttrs the attributes to use if activeAttrs does not contain a necessary value. */ - protected void prepareToDrawInterior(DrawContext dc, ShapeAttributes activeAttrs, ShapeAttributes defaultAttrs) - { - if (!activeAttrs.isDrawInterior()) + protected void prepareToDrawInterior(DrawContext dc, ShapeAttributes activeAttrs, ShapeAttributes defaultAttrs) { + if (!activeAttrs.isDrawInterior()) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { Material material = activeAttrs.getInteriorMaterial(); - if (material == null) + if (material == null) { material = defaultAttrs.getInteriorMaterial(); + } - if (this.mustApplyLighting(dc, activeAttrs)) - { + if (this.mustApplyLighting(dc, activeAttrs)) { material.apply(gl, GL2.GL_FRONT_AND_BACK, (float) activeAttrs.getInteriorOpacity()); gl.glEnable(GL2.GL_LIGHTING); gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); - } - else - { + } else { Color sc = material.getDiffuse(); double opacity = activeAttrs.getInteriorOpacity(); gl.glColor4ub((byte) sc.getRed(), (byte) sc.getGreen(), (byte) sc.getBlue(), - (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); + (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); gl.glDisable(GL2.GL_LIGHTING); gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); } - if (activeAttrs.getInteriorOpacity() < 1) + if (activeAttrs.getInteriorOpacity() < 1) { gl.glDepthMask(false); + } } } /** * Computes a model-coordinate point from a position, applying this shape's altitude mode. * - * @param terrain the terrain to compute a point relative to the globe's surface. + * @param terrain the terrain to compute a point relative to the globe's surface. * @param position the position to compute a point for. * * @return the model-coordinate point corresponding to the position and this shape's shape type. */ - protected Vec4 computePoint(Terrain terrain, Position position) - { - if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND) + protected Vec4 computePoint(Terrain terrain, Position position) { + if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND) { return terrain.getSurfacePoint(position.getLatitude(), position.getLongitude(), 0d); - else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) + } else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { return terrain.getSurfacePoint(position); + } // Raise the shape to accommodate vertical exaggeration applied to the terrain. double height = position.getElevation() * terrain.getVerticalExaggeration(); @@ -1474,18 +1414,18 @@ else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) * Computes a model-coordinate point from a position, applying this shape's altitude mode, and using * CLAMP_TO_GROUND if the current globe is 2D. * - * @param dc the current draw context. - * @param terrain the terrain to compute a point relative to the globe's surface. + * @param dc the current draw context. + * @param terrain the terrain to compute a point relative to the globe's surface. * @param position the position to compute a point for. * * @return the model-coordinate point corresponding to the position and this shape's shape type. */ - protected Vec4 computePoint(DrawContext dc, Terrain terrain, Position position) - { - if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) + protected Vec4 computePoint(DrawContext dc, Terrain terrain, Position position) { + if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) { return terrain.getSurfacePoint(position.getLatitude(), position.getLongitude(), 0d); - else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) + } else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { return terrain.getSurfacePoint(position); + } // Raise the shape to accommodate vertical exaggeration applied to the terrain. double height = position.getElevation() * terrain.getVerticalExaggeration(); @@ -1496,42 +1436,42 @@ else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) /** * Computes this shape's approximate extent from its positions. * - * @param globe the globe to use to compute the extent. + * @param globe the globe to use to compute the extent. * @param verticalExaggeration the vertical exaggeration to apply to computed terrain points. - * @param positions the positions to compute the extent for. + * @param positions the positions to compute the extent for. * * @return the extent, or null if an extent cannot be computed. Null is returned if either globe or * positions is null. */ protected Extent computeExtentFromPositions(Globe globe, double verticalExaggeration, - Iterable positions) - { - if (globe == null || positions == null) + Iterable positions) { + if (globe == null || positions == null) { return null; + } Sector mySector = this.getSector(); - if (mySector == null) + if (mySector == null) { return null; + } double[] extremes; double[] minAndMaxElevations = globe.getMinAndMaxElevations(mySector); - if (this.getAltitudeMode() != WorldWind.CLAMP_TO_GROUND) - { - extremes = new double[] {Double.MAX_VALUE, -Double.MAX_VALUE}; - for (LatLon pos : positions) - { + if (this.getAltitudeMode() != WorldWind.CLAMP_TO_GROUND) { + extremes = new double[]{Double.MAX_VALUE, -Double.MAX_VALUE}; + for (LatLon pos : positions) { double elevation = pos instanceof Position ? ((Position) pos).getElevation() : 0; - if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) + if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { elevation += minAndMaxElevations[1]; + } - if (extremes[0] > elevation) + if (extremes[0] > elevation) { extremes[0] = elevation * verticalExaggeration; // min - if (extremes[1] < elevation) + } + if (extremes[1] < elevation) { extremes[1] = elevation * verticalExaggeration; // max + } } - } - else - { + } else { extremes = minAndMaxElevations; } @@ -1548,8 +1488,7 @@ protected Extent computeExtentFromPositions(Globe globe, double verticalExaggera * @return an array containing the coordinate vertex buffer ID in the first position and the index vertex buffer ID * in the second position. */ - protected int[] getVboIds(DrawContext dc) - { + protected int[] getVboIds(DrawContext dc) { return (int[]) dc.getGpuResourceCache().get(this.getCurrentData().getVboCacheKey()); } @@ -1560,20 +1499,16 @@ protected int[] getVboIds(DrawContext dc) * * @param dc the current draw context. */ - protected void clearCachedVbos(DrawContext dc) - { + protected void clearCachedVbos(DrawContext dc) { dc.getGpuResourceCache().remove(this.getCurrentData().getVboCacheKey()); } protected int countTriangleVertices(java.util.List> prims, - java.util.List primTypes) - { + java.util.List primTypes) { int numVertices = 0; - for (int i = 0; i < prims.size(); i++) - { - switch (primTypes.get(i)) - { + for (int i = 0; i < prims.size(); i++) { + switch (primTypes.get(i)) { case GL.GL_TRIANGLES: numVertices += prims.get(i).size(); break; @@ -1591,10 +1526,8 @@ protected int countTriangleVertices(java.util.List> prim return numVertices; } - public void move(Position delta) - { - if (delta == null) - { + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1605,93 +1538,81 @@ public void move(Position delta) // The reference position is null if this shape has no positions. In this case moving the shape by a // relative delta is meaningless because the shape has no geographic location. Therefore we fail softly by // exiting and doing nothing. - if (refPos == null) + if (refPos == null) { return; + } this.moveTo(refPos.add(delta)); } @Override - public void moveTo(Globe globe, Position position) - { + public void moveTo(Globe globe, Position position) { this.moveTo(position); // TODO: Update all implementers of this method to use the Movable2 interface } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, this.getAltitudeMode()); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } - public String isExportFormatSupported(String mimeType) - { - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) + public String isExportFormatSupported(String mimeType) { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { return Exportable.FORMAT_SUPPORTED; - else + } else { return Exportable.FORMAT_NOT_SUPPORTED; + } } - public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException - { - if (mimeType == null) - { + public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException { + if (mimeType == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output == null) - { + if (output == null) { String message = Logging.getMessage("nullValue.OutputBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String supported = this.isExportFormatSupported(mimeType); - if (FORMAT_NOT_SUPPORTED.equals(supported)) - { + if (FORMAT_NOT_SUPPORTED.equals(supported)) { String message = Logging.getMessage("Export.UnsupportedFormat", mimeType); Logging.logger().warning(message); throw new UnsupportedOperationException(message); } - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) - { - try - { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { + try { exportAsKML(output); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { Logging.logger().throwing(getClass().getName(), "export", e); throw new IOException(e); } - } - else - { + } else { String message = Logging.getMessage("Export.UnsupportedFormat", mimeType); Logging.logger().warning(message); throw new UnsupportedOperationException(message); @@ -1705,31 +1626,24 @@ public void export(String mimeType, Object output) throws IOException, Unsupport * @param output Object to receive the generated KML. * * @throws XMLStreamException If an exception occurs while writing the KML - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -1738,8 +1652,7 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("Placemark"); String property = getStringValue(AVKey.DISPLAY_NAME); - if (property != null) - { + if (property != null) { xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(property); xmlWriter.writeEndElement(); @@ -1750,16 +1663,14 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); String shortDescription = (String) getValue(AVKey.SHORT_DESCRIPTION); - if (shortDescription != null) - { + if (shortDescription != null) { xmlWriter.writeStartElement("Snippet"); xmlWriter.writeCharacters(shortDescription); xmlWriter.writeEndElement(); } String description = (String) getValue(AVKey.BALLOON_TEXT); - if (description != null) - { + if (description != null) { xmlWriter.writeStartElement("description"); xmlWriter.writeCharacters(description); xmlWriter.writeEndElement(); @@ -1770,8 +1681,7 @@ else if (output instanceof OutputStream) final ShapeAttributes highlightAttributes = getHighlightAttributes(); // Write style map - if (normalAttributes != null || highlightAttributes != null) - { + if (normalAttributes != null || highlightAttributes != null) { xmlWriter.writeStartElement("StyleMap"); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.NORMAL, normalAttributes); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.HIGHLIGHT, highlightAttributes); @@ -1783,30 +1693,27 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); // Placemark xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } //**************************************************************// //********************* Restorable *****************// //**************************************************************// - - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { // Method is invoked by subclasses to have superclass add its state and only its state this.doMyGetRestorableState(rs, context); } - private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { rs.addStateValueAsBoolean(context, "highlighted", this.isHighlighted()); rs.addStateValueAsBoolean(context, "visible", this.isVisible()); rs.addStateValueAsInteger(context, "altitudeMode", this.getAltitudeMode()); @@ -1815,22 +1722,17 @@ private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.Stat //this.highlightAttrs.getRestorableState(rs, rs.addStateObject(context, "highlightAttrs")); } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -1840,30 +1742,30 @@ public void restoreState(String stateInXml) this.doRestoreState(rs, null); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Method is invoked by subclasses to have superclass add its state and only its state this.doMyRestoreState(rs, context); } - private void doMyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + private void doMyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { Boolean booleanState = rs.getStateValueAsBoolean(context, "highlighted"); - if (booleanState != null) + if (booleanState != null) { this.setHighlighted(booleanState); + } booleanState = rs.getStateValueAsBoolean(context, "visible"); - if (booleanState != null) + if (booleanState != null) { this.setVisible(booleanState); + } Integer integerState = rs.getStateValueAsInteger(context, "altitudeMode"); - if (integerState != null) + if (integerState != null) { this.setAltitudeMode(integerState); + } RestorableSupport.StateObject so = rs.getStateObject(context, "attributes"); - if (so != null) - { + if (so != null) { ShapeAttributes attrs = (this.getAttributes() != null) ? this.getAttributes() : new BasicShapeAttributes(); attrs.restoreState(rs, so); this.setAttributes(attrs); @@ -1878,6 +1780,6 @@ private void doMyRestoreState(RestorableSupport rs, RestorableSupport.StateObjec attrs.restoreState(rs, so); this.setHighlightAttributes(attrs); } - */ + */ } } diff --git a/src/gov/nasa/worldwind/render/AbstractSurfaceObject.java b/src/gov/nasa/worldwind/render/AbstractSurfaceObject.java index 6fd188a4d0..704a36ba42 100644 --- a/src/gov/nasa/worldwind/render/AbstractSurfaceObject.java +++ b/src/gov/nasa/worldwind/render/AbstractSurfaceObject.java @@ -42,8 +42,8 @@ * @author dcollins * @version $Id: AbstractSurfaceObject.java 3240 2015-06-22 23:38:49Z tgaskins $ */ -public abstract class AbstractSurfaceObject extends WWObjectImpl implements SurfaceObject -{ +public abstract class AbstractSurfaceObject extends WWObjectImpl implements SurfaceObject { + // Public interface properties. protected boolean visible; protected final long uniqueId; @@ -55,7 +55,9 @@ public abstract class AbstractSurfaceObject extends WWObjectImpl implements Surf // Picking properties. protected Layer pickLayer; protected PickSupport pickSupport = new PickSupport(); - /** Support class used to build surface tiles used to draw the pick representation. */ + /** + * Support class used to build surface tiles used to draw the pick representation. + */ protected SurfaceObjectTileBuilder pickTileBuilder; /* The next unique ID. This property is shared by all instances of AbstractSurfaceObject. */ protected static long nextUniqueId = 1; @@ -64,8 +66,7 @@ public abstract class AbstractSurfaceObject extends WWObjectImpl implements Surf * Creates a new AbstractSurfaceObject, assigning it a unique ID and initializing its last modified time to the * current system time. */ - public AbstractSurfaceObject() - { + public AbstractSurfaceObject() { this.visible = true; this.uniqueId = nextUniqueId(); this.lastModifiedTime = System.currentTimeMillis(); @@ -77,8 +78,7 @@ public AbstractSurfaceObject() * * @param source the shape to copy. */ - public AbstractSurfaceObject(AbstractSurfaceObject source) - { + public AbstractSurfaceObject(AbstractSurfaceObject source) { super(source); this.visible = source.visible; @@ -95,45 +95,50 @@ public AbstractSurfaceObject(AbstractSurfaceObject source) * * @return the next unique integer. */ - protected static synchronized long nextUniqueId() - { + protected static synchronized long nextUniqueId() { return nextUniqueId++; } - /** {@inheritDoc} */ - public boolean isVisible() - { + /** + * {@inheritDoc} + */ + public boolean isVisible() { return this.visible; } - /** {@inheritDoc} */ - public void setVisible(boolean visible) - { + /** + * {@inheritDoc} + */ + public void setVisible(boolean visible) { this.visible = visible; this.updateModifiedTime(); } - /** {@inheritDoc} */ - public Object getStateKey(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public Object getStateKey(DrawContext dc) { return new SurfaceObjectStateKey(this.getUniqueId(), this.lastModifiedTime); } - /** {@inheritDoc} */ - public double getDistanceFromEye() - { + /** + * {@inheritDoc} + */ + public double getDistanceFromEye() { return 0; } - /** {@inheritDoc} */ - public Object getDelegateOwner() - { + /** + * {@inheritDoc} + */ + public Object getDelegateOwner() { return this.delegateOwner; } - /** {@inheritDoc} */ - public void setDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + public void setDelegateOwner(Object owner) { this.delegateOwner = owner; } @@ -144,8 +149,7 @@ public void setDelegateOwner(Object owner) * * @see #setDrawBoundingSectors(boolean) */ - public boolean isDrawBoundingSectors() - { + public boolean isDrawBoundingSectors() { return this.drawBoundingSectors; } @@ -155,75 +159,75 @@ public boolean isDrawBoundingSectors() * * @param draw true to draw the shape's outline; false otherwise. */ - public void setDrawBoundingSectors(boolean draw) - { + public void setDrawBoundingSectors(boolean draw) { this.drawBoundingSectors = draw; // Update the modified time so the object's composite representation is updated. We draw the bounding sector // along with the object's composite representation. this.updateModifiedTime(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return this.enableBatchPicking; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setEnableBatchPicking(boolean enable) - { + public void setEnableBatchPicking(boolean enable) { this.enableBatchPicking = enable; } - /** {@inheritDoc} */ - public Extent getExtent(DrawContext dc) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public Extent getExtent(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } CacheEntry entry = this.extentCache.get(dc.getGlobe().getGlobeStateKey()); - if (entry != null) - { + if (entry != null) { return (Extent) entry.object; - } - else - { + } else { entry = new CacheEntry(this.computeExtent(dc), dc); this.extentCache.put(dc.getGlobe().getGlobeStateKey(), entry); return (Extent) entry.object; } } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } // Ordered pre-rendering is a no-op for this object. The SceneController prepares a composite representation of // this object for rendering and calls this object's render method when doing so. - if (!dc.isOrderedRenderingMode()) + if (!dc.isOrderedRenderingMode()) { this.makeOrderedPreRenderable(dc); + } } - /** {@inheritDoc} */ - public void pick(DrawContext dc, Point pickPoint) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public void pick(DrawContext dc, Point pickPoint) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -234,43 +238,43 @@ public void pick(DrawContext dc, Point pickPoint) // draws a separate representation of itself during picking. Using a separate call stack enables us to use // common rendering code to draw both the pick and render representations, by setting the draw context's // isPickingMode flag to control which representation is drawn. - - if (!this.isVisible()) + if (!this.isVisible()) { return; + } this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.pickOrderedRenderable(dc, this.pickSupport); - if (this.isEnableBatchPicking()) + if (this.isEnableBatchPicking()) { this.pickBatched(dc, this.pickSupport); - } - finally - { + } + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } } - /** {@inheritDoc} */ - public void render(DrawContext dc) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } - if (dc.isOrderedRenderingMode()) + if (dc.isOrderedRenderingMode()) { this.drawOrderedRenderable(dc); - else + } else { this.makeOrderedRenderable(dc); + } } /** @@ -279,8 +283,7 @@ public void render(DrawContext dc) * * @return the surface object's unique identifier. */ - protected long getUniqueId() - { + protected long getUniqueId() { return this.uniqueId; } @@ -288,20 +291,19 @@ protected long getUniqueId() * Sets the SurfaceObject's modified time to the current system time. This causes cached representations of this * SurfaceObject to be refreshed. */ - protected void updateModifiedTime() - { + protected void updateModifiedTime() { this.lastModifiedTime = System.currentTimeMillis(); } - /** Clears this SurfaceObject's internal extent cache. */ - protected void clearCaches() - { + /** + * Clears this SurfaceObject's internal extent cache. + */ + protected void clearCaches() { this.extentCache.clear(); } /* Updates this SurfaceObject's modified time and clears its internal caches. */ - protected void onShapeChanged() - { + protected void onShapeChanged() { this.updateModifiedTime(); this.clearCaches(); } @@ -309,7 +311,6 @@ protected void onShapeChanged() //**************************************************************// //******************** Extent ********************************// //**************************************************************// - /** * Computes the surface object's extent. Uses the sector list returned by {@link #getSectors(DrawContext)} to * compute the extent bounding this object's sectors on the draw context's surface. This returns null if the surface @@ -319,11 +320,11 @@ protected void onShapeChanged() * * @return the surface object's extent. Returns null if the surface object has no sectors. */ - protected Extent computeExtent(DrawContext dc) - { + protected Extent computeExtent(DrawContext dc) { List sectors = this.getSectors(dc); - if (sectors == null) + if (sectors == null) { return null; + } return this.computeExtent(dc.getGlobe(), dc.getVerticalExaggeration(), sectors); } @@ -335,33 +336,26 @@ protected Extent computeExtent(DrawContext dc) * gov.nasa.worldwind.geom.Box} containing the corners of the boxes bounding each sector. This returns null if the * sector list is empty. * - * @param globe the globe the extent relates to. + * @param globe the globe the extent relates to. * @param verticalExaggeration the globe's vertical surface exaggeration. - * @param sectors the sectors to bound. + * @param sectors the sectors to bound. * * @return an extent for the specified sectors on the specified Globe. */ - protected Extent computeExtent(Globe globe, double verticalExaggeration, List sectors) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration, List sectors) { // This should never happen, but we check anyway. - if (sectors.size() == 0) - { + if (sectors.size() == 0) { return null; - } - // This surface shape does not cross the international dateline, and therefore has a single bounding sector. + } // This surface shape does not cross the international dateline, and therefore has a single bounding sector. // Return the box which contains that sector. - else if (sectors.size() == 1) - { + else if (sectors.size() == 1) { return Sector.computeBoundingBox(globe, verticalExaggeration, sectors.get(0)); - } - // This surface crosses the international dateline, and its bounding sectors are split along the dateline. + } // This surface crosses the international dateline, and its bounding sectors are split along the dateline. // Return a box which contains the corners of the boxes bounding each sector. - else - { + else { ArrayList boxCorners = new ArrayList(); - for (Sector s : sectors) - { + for (Sector s : sectors) { Box box = Sector.computeBoundingBox(globe, verticalExaggeration, s); boxCorners.addAll(Arrays.asList(box.getCorners())); } @@ -379,16 +373,17 @@ else if (sectors.size() == 1) * * @return true if this SurfaceObject intersects the draw context's frustum; false otherwise. */ - protected boolean intersectsFrustum(DrawContext dc) - { + protected boolean intersectsFrustum(DrawContext dc) { // A null extent indicates an object which has no location. Extent extent = this.getExtent(dc); - if (extent == null) + if (extent == null) { return false; + } // Test this object's extent against the pick frustum list - if (dc.isPickingMode()) + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(extent); + } // Test this object's extent against the viewing frustum. return dc.getView().getFrustumInModelCoordinates().intersects(extent); @@ -401,8 +396,7 @@ protected boolean intersectsFrustum(DrawContext dc) * * @return true if this SurfaceObject intersects any of the draw context's pick frustums; false otherwise. */ - protected boolean intersectsPickFrustum(DrawContext dc) - { + protected boolean intersectsPickFrustum(DrawContext dc) { // Test this object's extent against the pick frustum list. A null extent indicates the object has no location. Extent extent = this.getExtent(dc); return extent != null && dc.getPickFrustums().intersectsAny(extent); @@ -416,19 +410,20 @@ protected boolean intersectsPickFrustum(DrawContext dc) * * @return true if this SurfaceObject intersects the draw context's visible sector; false otherwise. */ - protected boolean intersectsVisibleSector(DrawContext dc) - { - if (dc.getVisibleSector() == null) + protected boolean intersectsVisibleSector(DrawContext dc) { + if (dc.getVisibleSector() == null) { return false; + } List sectors = this.getSectors(dc); - if (sectors == null) + if (sectors == null) { return false; + } - for (Sector s : sectors) - { - if (s.intersects(dc.getVisibleSector())) + for (Sector s : sectors) { + if (s.intersects(dc.getVisibleSector())) { return true; + } } return false; @@ -437,7 +432,6 @@ protected boolean intersectsVisibleSector(DrawContext dc) //**************************************************************// //******************** Rendering *****************************// //**************************************************************// - /** * Prepares the SurfaceObject as an {@link gov.nasa.worldwind.render.OrderedRenderable} and adds it to the * DrawContext's ordered surface renderable list. Additionally, this prepares the SurfaceObject's pickable @@ -451,27 +445,29 @@ protected boolean intersectsVisibleSector(DrawContext dc) * * @param dc the DrawContext to add to. */ - protected void makeOrderedPreRenderable(DrawContext dc) - { + protected void makeOrderedPreRenderable(DrawContext dc) { // Test for visibility against the draw context's visible sector prior to preparing this object for // preRendering. - if (!this.intersectsVisibleSector(dc)) + if (!this.intersectsVisibleSector(dc)) { return; + } // Create a representation of this object that can be used during picking. No need for a pickable representation // if this object's parent layer isn't pickable or if this object doesn't intersect the pick frustum. We do not // test visibility against the view frustum, because it's possible for the pick frustum to slightly exceed the // view frustum when the cursor is on the viewport edge. - if ((dc.getCurrentLayer() == null || dc.getCurrentLayer().isPickEnabled()) && this.intersectsPickFrustum(dc)) + if ((dc.getCurrentLayer() == null || dc.getCurrentLayer().isPickEnabled()) && this.intersectsPickFrustum(dc)) { this.buildPickRepresentation(dc); + } // If this object is visible, add it to the draw context's ordered surface renderable queue. This queue is // processed by the SceneController during the preRender pass as follows: the SceneController builds a composite // representation of this object and any other SurfaceObject on the queue, and calls this object's preRender // method (we ignore this call with a conditional in preRender). While building a composite representation the // SceneController calls this object's render method in ordered rendering mode. - if (this.intersectsFrustum(dc)) + if (this.intersectsFrustum(dc)) { dc.addOrderedSurfaceRenderable(this); + } } /** @@ -485,8 +481,7 @@ protected void makeOrderedPreRenderable(DrawContext dc) * * @param dc the DrawContext to add to. */ - protected void makeOrderedRenderable(DrawContext dc) - { + protected void makeOrderedRenderable(DrawContext dc) { // Add this object to the draw context's ordered surface renderable queue only during picking mode. This queue // is processed by the SceneController during each rendering pass as follows: // @@ -497,13 +492,15 @@ protected void makeOrderedRenderable(DrawContext dc) // composite representation during preRendering, we suppress this call by not adding to the ordered surface // renderable queue during rendering. - if (!dc.isPickingMode()) + if (!dc.isPickingMode()) { return; + } // Test for visibility prior to adding this object to the draw context's ordered renderable queue. Note that // there's no need to test again during ordered rendering mode. - if (!this.intersectsVisibleSector(dc) || !this.intersectsFrustum(dc)) + if (!this.intersectsVisibleSector(dc) || !this.intersectsFrustum(dc)) { return; + } this.pickLayer = dc.getCurrentLayer(); // Keep track of the object's parent layer for use during picking. dc.addOrderedSurfaceRenderable(this); @@ -513,11 +510,10 @@ protected void makeOrderedRenderable(DrawContext dc) * Causes the SurfaceObject to draw itself in a unique pick color, and add itself as a pickable object to the * specified pickSupport. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param pickSupport the PickSupport to add the SurfaceObject to. */ - protected void pickOrderedRenderable(DrawContext dc, PickSupport pickSupport) - { + protected void pickOrderedRenderable(DrawContext dc, PickSupport pickSupport) { // Register a unique pick color with the PickSupport. We define the pickable object to be the caller specified // delegate owner, or this object if the delegate owner is null. We define the picked position to be the // terrain's picked position to maintain backwards compatibility with previous implementations of SurfaceObject. @@ -535,16 +531,15 @@ protected void pickOrderedRenderable(DrawContext dc, PickSupport pickSupport) * Create a {@link gov.nasa.worldwind.pick.PickedObject} for this surface object. The PickedObject created by this * method will be added to the pick list to represent the current surface object. * - * @param dc Active draw context. + * @param dc Active draw context. * @param pickColor Unique color for this PickedObject. * * @return A new picked object. */ - protected PickedObject createPickedObject(DrawContext dc, Color pickColor) - { + protected PickedObject createPickedObject(DrawContext dc, Color pickColor) { Object pickedObject = this.getDelegateOwner() != null ? this.getDelegateOwner() : this; Position pickedPos = dc.getPickedObjects().getTerrainObject() != null - ? dc.getPickedObjects().getTerrainObject().getPosition() : null; + ? dc.getPickedObjects().getTerrainObject().getPosition() : null; return new PickedObject(pickColor.getRGB(), pickedObject, pickedPos, false); } @@ -555,21 +550,20 @@ protected PickedObject createPickedObject(DrawContext dc, Color pickColor) * are removed from the DrawContext's list and processed until one is encountered that has a different containing * layer or is not enabled for batch picking. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param pickSupport the PickSupport to add the SurfaceObject to. */ - protected void pickBatched(DrawContext dc, PickSupport pickSupport) - { + protected void pickBatched(DrawContext dc, PickSupport pickSupport) { // Draw as many as we can in a batch to save pick resolution. Object nextItem = dc.getOrderedSurfaceRenderables().peek(); - while (nextItem != null && nextItem instanceof AbstractSurfaceObject) - { + while (nextItem != null && nextItem instanceof AbstractSurfaceObject) { AbstractSurfaceObject so = (AbstractSurfaceObject) nextItem; // Batch pick only within a single layer, and for objects which are enabled for batch picking. - if (so.pickLayer != this.pickLayer || !so.isEnableBatchPicking()) + if (so.pickLayer != this.pickLayer || !so.isEnableBatchPicking()) { break; + } dc.getOrderedSurfaceRenderables().poll(); // take it off the queue so.pickOrderedRenderable(dc, pickSupport); @@ -588,8 +582,7 @@ protected void pickBatched(DrawContext dc, PickSupport pickSupport) * * @param dc the current DrawContext. */ - protected void drawOrderedRenderable(DrawContext dc) - { + protected void drawOrderedRenderable(DrawContext dc) { // This method is invoked by the SceneController during ordered rendering mode while building a composite // representation of the SurfaceObjects during ordered preRendering. Since we use this method to draw a // composite representation during preRendering, we prevent this method from being invoked during ordered @@ -597,8 +590,7 @@ protected void drawOrderedRenderable(DrawContext dc) // instead. SurfaceTileDrawContext sdc = (SurfaceTileDrawContext) dc.getValue(AVKey.SURFACE_TILE_DRAW_CONTEXT); - if (sdc == null) - { + if (sdc == null) { Logging.logger().warning(Logging.getMessage("nullValue.SurfaceTileDrawContextIsNull")); return; } @@ -606,15 +598,16 @@ protected void drawOrderedRenderable(DrawContext dc) this.drawGeographic(dc, sdc); // Draw the diagnostic bounding sectors during ordered rendering mode. - if (this.isDrawBoundingSectors() && !dc.isPickingMode()) + if (this.isDrawBoundingSectors() && !dc.isPickingMode()) { this.drawBoundingSectors(dc, sdc); + } } /** * Causes the SurfaceObject to render itself to the specified region in geographic coordinates. The specified * viewport denotes the geographic region and its corresponding screen viewport. * - * @param dc the current draw context. + * @param dc the current draw context. * @param sdc the context containing a geographic region and screen viewport corresponding to a surface tile. */ protected abstract void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc); @@ -622,20 +615,19 @@ protected void drawOrderedRenderable(DrawContext dc) //**************************************************************// //******************** Picking *******************************// //**************************************************************// - /** * Builds this AbstractSurfaceObject's pickable representation. This method is called during the preRender phase, * and is therefore free to modify the framebuffer contents to create the pickable representation. * * @param dc the draw context to build a representation for. */ - protected void buildPickRepresentation(DrawContext dc) - { + protected void buildPickRepresentation(DrawContext dc) { // Lazily create the support object used to build the pick representation. We keep a reference to the // SurfaceObjectTileBuilder used to build the tiles because it acts as a cache key to the tiles and determines // when the tiles must be updated. - if (this.pickTileBuilder == null) + if (this.pickTileBuilder == null) { this.pickTileBuilder = this.createPickTileBuilder(); + } // Build the pickable representation of this surface object as a list of surface tiles. Set the DrawContext into // ordered picking mode while the surface object's pickable representation is built. During ordered picking mode @@ -643,20 +635,19 @@ protected void buildPickRepresentation(DrawContext dc) // the pick frustum. boolean prevPickingMode = dc.isPickingMode(); boolean prevOrderedRenderingMode = dc.isOrderedRenderingMode(); - try - { - if (!prevPickingMode) + try { + if (!prevPickingMode) { dc.enablePickingMode(); + } dc.setOrderedRenderingMode(true); // Build the pick representation as a list of surface tiles. this.pickTileBuilder.buildTiles(dc, Arrays.asList(this)); - } - finally - { + } finally { // Restore the DrawContext's previous picking and ordered rendering modes. - if (!prevPickingMode) + if (!prevPickingMode) { dc.disablePickingMode(); + } dc.setOrderedRenderingMode(prevOrderedRenderingMode); } } @@ -666,28 +657,25 @@ protected void buildPickRepresentation(DrawContext dc) * * @param dc the current DrawContext. */ - protected void drawPickRepresentation(DrawContext dc) - { + protected void drawPickRepresentation(DrawContext dc) { // The pick representation is stored as a list of surface tiles. If the list is empty, then this surface object // was not picked. This method might be called when the list is null or empty because of an upstream // exception that prevented creation of the list. - if (this.pickTileBuilder == null || this.pickTileBuilder.getTileCount(dc) == 0) + if (this.pickTileBuilder == null || this.pickTileBuilder.getTileCount(dc) == 0) { return; + } // Draw the pickable representation of this surface object created during preRendering. GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushAttrib(gl, GL2.GL_POLYGON_BIT); // For cull face enable, cull face, polygon mode. - try - { + try { gl.glEnable(GL.GL_CULL_FACE); gl.glCullFace(GL.GL_BACK); gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL); dc.getGeographicSurfaceTileRenderer().renderTiles(dc, this.pickTileBuilder.getTiles(dc)); - } - finally - { + } finally { ogsh.pop(gl); // Clear the list of pick tiles to avoid retaining references to them in case we're never picked again. this.pickTileBuilder.clearTiles(dc); @@ -702,44 +690,41 @@ protected void drawPickRepresentation(DrawContext dc) * * @return a SurfaceObjectTileBuilder used for building and drawing the surface object's pickable representation. */ - protected SurfaceObjectTileBuilder createPickTileBuilder() - { + protected SurfaceObjectTileBuilder createPickTileBuilder() { return new SurfaceObjectTileBuilder(new Dimension(512, 512), GL2.GL_ALPHA8, false, false); } //**************************************************************// //******************** Diagnostic Support ********************// //**************************************************************// - /** * Causes this SurfaceObject to render its bounding sectors to the specified region in geographic coordinates. The * specified viewport denotes the geographic region and its corresponding screen viewport. *

            * The bounding sectors are rendered as a 1 pixel wide green outline. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param sdc the context containing a geographic region and screen viewport corresponding to a surface tile. * * @see #getSectors(DrawContext) */ - protected void drawBoundingSectors(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawBoundingSectors(DrawContext dc, SurfaceTileDrawContext sdc) { List sectors = this.getSectors(dc); - if (sectors == null) + if (sectors == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - int attributeMask = - GL2.GL_COLOR_BUFFER_BIT // For alpha test enable, blend enable, alpha func, blend func. - | GL2.GL_CURRENT_BIT // For current color. + int attributeMask + = GL2.GL_COLOR_BUFFER_BIT // For alpha test enable, blend enable, alpha func, blend func. + | GL2.GL_CURRENT_BIT // For current color. | GL2.GL_LINE_BIT; // For line smooth, line width. OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushAttrib(gl, attributeMask); ogsh.pushModelview(gl); - try - { + try { gl.glEnable(GL.GL_BLEND); OGLUtil.applyBlending(gl, false); @@ -752,8 +737,7 @@ protected void drawBoundingSectors(DrawContext dc, SurfaceTileDrawContext sdc) Matrix matrix = sdc.getModelviewMatrix(); gl.glMultMatrixd(matrix.toArray(new double[16], 0, false), 0); - for (Sector s : sectors) - { + for (Sector s : sectors) { LatLon[] corners = s.getCorners(); gl.glBegin(GL2.GL_LINE_LOOP); gl.glVertex2f((float) corners[0].getLongitude().degrees, (float) corners[0].getLatitude().degrees); @@ -762,9 +746,7 @@ protected void drawBoundingSectors(DrawContext dc, SurfaceTileDrawContext sdc) gl.glVertex2f((float) corners[3].getLongitude().degrees, (float) corners[3].getLatitude().degrees); gl.glEnd(); } - } - finally - { + } finally { ogsh.pop(gl); } } @@ -772,53 +754,55 @@ protected void drawBoundingSectors(DrawContext dc, SurfaceTileDrawContext sdc) //**************************************************************// //******************** State Key *****************************// //**************************************************************// - /** * Represents a surface object's current state. StateKey uniquely identifies a surface object's current state as * follows:

            • The StateKey class distinguishes the key from other object types.
            • The object's unique * ID distinguishes one surface object instances from another.
            • The object's modified time distinguishes an - * object's internal state from any of its previous states.
            Using the unique ID to distinguish between objects - * ensures that the StateKey does not store dangling references to the surface object itself. Should the StateKey - * live longer than the surface object that created it, the StateKey does not prevent the object from being garbage - * collected. - */ - protected static class SurfaceObjectStateKey implements Cacheable - { - /** The SurfaceObject's unique ID. This is unique to all instances of SurfaceObject. */ + * object's internal state from any of its previous states.
          Using the unique ID to distinguish between + * objects ensures that the StateKey does not store dangling references to the surface object itself. Should the + * StateKey live longer than the surface object that created it, the StateKey does not prevent the object from being + * garbage collected. + */ + protected static class SurfaceObjectStateKey implements Cacheable { + + /** + * The SurfaceObject's unique ID. This is unique to all instances of SurfaceObject. + */ protected final long uniqueId; - /** The SurfaceObject's modified time. */ + /** + * The SurfaceObject's modified time. + */ protected final long modifiedTime; /** * Constructs a new SurfaceObjectStateKey with the specified unique ID and modified time. * - * @param uniqueId the SurfaceObject's unique ID. + * @param uniqueId the SurfaceObject's unique ID. * @param modifiedTime the SurfaceObject's modified time. */ - public SurfaceObjectStateKey(long uniqueId, long modifiedTime) - { + public SurfaceObjectStateKey(long uniqueId, long modifiedTime) { this.uniqueId = uniqueId; this.modifiedTime = modifiedTime; } @Override @SuppressWarnings({"SimplifiableIfStatement"}) - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } SurfaceObjectStateKey that = (SurfaceObjectStateKey) o; return this.uniqueId == that.uniqueId && this.modifiedTime == that.modifiedTime; } @Override - public int hashCode() - { + public int hashCode() { return 31 * (int) (this.uniqueId ^ (this.uniqueId >>> 32)) - + (int) (this.modifiedTime ^ (this.modifiedTime >>> 32)); + + (int) (this.modifiedTime ^ (this.modifiedTime >>> 32)); } /** @@ -826,8 +810,7 @@ public int hashCode() * * @return the state key's size in bytes. */ - public long getSizeInBytes() - { + public long getSizeInBytes() { return 16; // Return the size of two long integers. } } @@ -835,15 +818,15 @@ public long getSizeInBytes() //**************************************************************// //******************** Cache Entry ***************************// //**************************************************************// + /** + * Represents a globe dependent cache entry. + */ + protected static class CacheEntry { - /** Represents a globe dependent cache entry. */ - protected static class CacheEntry - { public Object object; protected Object globeStateKey; - public CacheEntry(Object object, DrawContext dc) - { + public CacheEntry(Object object, DrawContext dc) { this.object = object; this.globeStateKey = dc.getGlobe().getStateKey(dc); } diff --git a/src/gov/nasa/worldwind/render/AbstractSurfaceRenderable.java b/src/gov/nasa/worldwind/render/AbstractSurfaceRenderable.java index f9ed831f2e..4f11bd5c34 100644 --- a/src/gov/nasa/worldwind/render/AbstractSurfaceRenderable.java +++ b/src/gov/nasa/worldwind/render/AbstractSurfaceRenderable.java @@ -21,65 +21,58 @@ * @author Patrick Murris * @version $Id: AbstractSurfaceRenderable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractSurfaceRenderable extends AbstractSurfaceObject -{ +public abstract class AbstractSurfaceRenderable extends AbstractSurfaceObject { + private double opacity = 1d; - public double getOpacity() - { + public double getOpacity() { return this.opacity; } - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { this.opacity = opacity < 0 ? 0 : opacity > 1 ? 1 : opacity; // clamp to 0..1 this.updateModifiedTime(); } // *** Utility methods - - protected Angle getViewHeading(DrawContext dc) - { + protected Angle getViewHeading(DrawContext dc) { Angle heading = Angle.ZERO; - if (dc.getView() instanceof OrbitView) + if (dc.getView() instanceof OrbitView) { heading = dc.getView().getHeading(); + } return heading; } - protected double computePixelSizeAtLocation(DrawContext dc, LatLon location) - { + protected double computePixelSizeAtLocation(DrawContext dc, LatLon location) { Globe globe = dc.getGlobe(); Vec4 locationPoint = globe.computePointFromPosition(location.getLatitude(), location.getLongitude(), - globe.getElevation(location.getLatitude(), location.getLongitude())); + globe.getElevation(location.getLatitude(), location.getLongitude())); double distance = dc.getView().getEyePoint().distanceTo3(locationPoint); return dc.getView().computePixelSizeAtDistance(distance); } - protected double computeDrawPixelSize(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected double computeDrawPixelSize(DrawContext dc, SurfaceTileDrawContext sdc) { return dc.getGlobe().getRadius() * sdc.getSector().getDeltaLatRadians() / sdc.getViewport().height; } - protected Vec4 computeDrawPoint(LatLon location, SurfaceTileDrawContext sdc) - { + protected Vec4 computeDrawPoint(LatLon location, SurfaceTileDrawContext sdc) { Vec4 point = new Vec4(location.getLongitude().degrees, location.getLatitude().degrees, 1); return point.transformBy4(sdc.getModelviewMatrix()); } - protected Sector computeRotatedSectorBounds(Sector sector, LatLon location, Angle heading) - { - if (Math.abs(heading.degrees) < .001) + protected Sector computeRotatedSectorBounds(Sector sector, LatLon location, Angle heading) { + if (Math.abs(heading.degrees) < .001) { return sector; + } - LatLon[] corners = new LatLon[] { - new LatLon(sector.getMaxLatitude(), sector.getMinLongitude()), // nw - new LatLon(sector.getMaxLatitude(), sector.getMaxLongitude()), // ne - new LatLon(sector.getMinLatitude(), sector.getMinLongitude()), // sw - new LatLon(sector.getMinLatitude(), sector.getMaxLongitude()), // se + LatLon[] corners = new LatLon[]{ + new LatLon(sector.getMaxLatitude(), sector.getMinLongitude()), // nw + new LatLon(sector.getMaxLatitude(), sector.getMaxLongitude()), // ne + new LatLon(sector.getMinLatitude(), sector.getMinLongitude()), // sw + new LatLon(sector.getMinLatitude(), sector.getMaxLongitude()), // se }; // Rotate corners around location - for (int i = 0; i < corners.length; i++) - { + for (int i = 0; i < corners.length; i++) { Angle azimuth = LatLon.greatCircleAzimuth(location, corners[i]); Angle distance = LatLon.greatCircleDistance(location, corners[i]); corners[i] = LatLon.greatCircleEndPosition(location, azimuth.add(heading), distance); @@ -88,8 +81,7 @@ protected Sector computeRotatedSectorBounds(Sector sector, LatLon location, Angl return Sector.boundingSector(Arrays.asList(corners)); } - protected List computeNormalizedSectors(Sector sector) - { + protected List computeNormalizedSectors(Sector sector) { Angle minLat = sector.getMinLatitude(); Angle maxLat = sector.getMaxLatitude(); Angle minLon = sector.getMinLongitude(); @@ -98,36 +90,25 @@ protected List computeNormalizedSectors(Sector sector) maxLat = maxLat.degrees <= 90 ? maxLat : Angle.POS90; java.util.List sectors = new ArrayList(); - if (minLon.degrees >= -180 && maxLon.degrees <= 180) - { + if (minLon.degrees >= -180 && maxLon.degrees <= 180) { // No date line crossing on both sides sectors.add(new Sector(minLat, maxLat, minLon, maxLon)); - } - else - { - if (minLon.degrees < -180 && maxLon.degrees > 180) - { + } else { + if (minLon.degrees < -180 && maxLon.degrees > 180) { // min and max lon overlap at the date line - span the whole ongitude range sectors.add(new Sector(minLat, maxLat, Angle.NEG180, Angle.POS180)); - } - else - { + } else { // Date line crossing, produce two sectors, one on each side of the date line - while (minLon.degrees < -180) - { + while (minLon.degrees < -180) { minLon = minLon.addDegrees(360); } - while (maxLon.degrees > 180) - { + while (maxLon.degrees > 180) { maxLon = maxLon.subtractDegrees(360); } - if (minLat.degrees > maxLat.degrees) - { + if (minLat.degrees > maxLat.degrees) { sector = new Sector(minLat, maxLat, minLon, maxLon); sectors.addAll(Arrays.asList(Sector.splitBoundingSectors(sector))); - } - else - { + } else { // min and max lon overlap - span the whole ongitude range sectors.add(new Sector(minLat, maxLat, Angle.NEG180, Angle.POS180)); } @@ -137,21 +118,18 @@ protected List computeNormalizedSectors(Sector sector) return sectors; } - protected int computeHemisphereOffset(Sector sector, LatLon location) - { + protected int computeHemisphereOffset(Sector sector, LatLon location) { Angle sectorLon = sector.getCentroid().getLongitude(); Angle locationLon = location.getLongitude(); if (Math.abs(locationLon.degrees - sectorLon.degrees) > 180 - && Math.signum(locationLon.degrees) != Math.signum(sectorLon.degrees)) - { + && Math.signum(locationLon.degrees) != Math.signum(sectorLon.degrees)) { return (int) (360 * Math.signum(sectorLon.degrees)); } return 0; } - protected void applyPremultipliedAlphaColor(GL2 gl, Color color, double opacity) - { + protected void applyPremultipliedAlphaColor(GL2 gl, Color color, double opacity) { float[] compArray = new float[4]; color.getRGBComponents(compArray); compArray[3] = (float) WWMath.clamp(opacity, 0, 1); @@ -161,8 +139,7 @@ protected void applyPremultipliedAlphaColor(GL2 gl, Color color, double opacity) gl.glColor4fv(compArray, 0); } - protected void applyNonPremultipliedAlphaColor(GL2 gl, Color color, double opacity) - { + protected void applyNonPremultipliedAlphaColor(GL2 gl, Color color, double opacity) { float[] compArray = new float[4]; color.getRGBComponents(compArray); compArray[3] = (float) WWMath.clamp(opacity, 0, 1); diff --git a/src/gov/nasa/worldwind/render/AbstractSurfaceShape.java b/src/gov/nasa/worldwind/render/AbstractSurfaceShape.java index d9c75974a6..f5edeeae0f 100644 --- a/src/gov/nasa/worldwind/render/AbstractSurfaceShape.java +++ b/src/gov/nasa/worldwind/render/AbstractSurfaceShape.java @@ -42,27 +42,42 @@ * @version $Id: AbstractSurfaceShape.java 3240 2015-06-22 23:38:49Z tgaskins $ */ public abstract class AbstractSurfaceShape extends AbstractSurfaceObject implements SurfaceShape, Movable, Movable2, - Combinable, Draggable -{ - /** The default interior color. */ + Combinable, Draggable { + + /** + * The default interior color. + */ protected static final Material DEFAULT_INTERIOR_MATERIAL = Material.LIGHT_GRAY; - /** The default outline color. */ + /** + * The default outline color. + */ protected static final Material DEFAULT_OUTLINE_MATERIAL = Material.DARK_GRAY; - /** The default highlight color. */ + /** + * The default highlight color. + */ protected static final Material DEFAULT_HIGHLIGHT_MATERIAL = Material.WHITE; - /** The default path type. */ + /** + * The default path type. + */ protected static final String DEFAULT_PATH_TYPE = AVKey.GREAT_CIRCLE; - /** The default number of texels per shape edge interval. */ + /** + * The default number of texels per shape edge interval. + */ protected static final int DEFAULT_TEXELS_PER_EDGE_INTERVAL = 50; - /** The default minimum number of shape edge intervals. */ + /** + * The default minimum number of shape edge intervals. + */ protected static final int DEFAULT_MIN_EDGE_INTERVALS = 0; - /** The default maximum number of shape edge intervals. */ + /** + * The default maximum number of shape edge intervals. + */ protected static final int DEFAULT_MAX_EDGE_INTERVALS = 100; - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static final ShapeAttributes defaultAttrs; - static - { + static { defaultAttrs = new BasicShapeAttributes(); defaultAttrs.setInteriorMaterial(DEFAULT_INTERIOR_MATERIAL); defaultAttrs.setOutlineMaterial(DEFAULT_OUTLINE_MATERIAL); @@ -91,9 +106,10 @@ public abstract class AbstractSurfaceShape extends AbstractSurfaceObject impleme protected AreaMeasurer areaMeasurer; protected long areaMeasurerLastModifiedTime; - /** Constructs a new surface shape with the default attributes. */ - public AbstractSurfaceShape() - { + /** + * Constructs a new surface shape with the default attributes. + */ + public AbstractSurfaceShape() { } /** @@ -102,8 +118,7 @@ public AbstractSurfaceShape() * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public AbstractSurfaceShape(ShapeAttributes normalAttrs) - { + public AbstractSurfaceShape(ShapeAttributes normalAttrs) { this.setAttributes(normalAttrs); } @@ -112,8 +127,7 @@ public AbstractSurfaceShape(ShapeAttributes normalAttrs) * * @param source the shape to copy. */ - public AbstractSurfaceShape(AbstractSurfaceShape source) - { + public AbstractSurfaceShape(AbstractSurfaceShape source) { super(source); this.highlighted = source.highlighted; @@ -125,54 +139,57 @@ public AbstractSurfaceShape(AbstractSurfaceShape source) this.maxEdgeIntervals = source.maxEdgeIntervals; } - /** {@inheritDoc} */ - public boolean isHighlighted() - { + /** + * {@inheritDoc} + */ + public boolean isHighlighted() { return this.highlighted; } - /** {@inheritDoc} */ - public void setHighlighted(boolean highlighted) - { + /** + * {@inheritDoc} + */ + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; this.updateModifiedTime(); } - /** {@inheritDoc} */ - public ShapeAttributes getAttributes() - { + /** + * {@inheritDoc} + */ + public ShapeAttributes getAttributes() { return this.normalAttrs; } - /** {@inheritDoc} */ - public void setAttributes(ShapeAttributes normalAttrs) - { + /** + * {@inheritDoc} + */ + public void setAttributes(ShapeAttributes normalAttrs) { this.normalAttrs = normalAttrs; this.updateModifiedTime(); } - /** {@inheritDoc} */ - public ShapeAttributes getHighlightAttributes() - { + /** + * {@inheritDoc} + */ + public ShapeAttributes getHighlightAttributes() { return highlightAttrs; } - /** {@inheritDoc} */ - public void setHighlightAttributes(ShapeAttributes highlightAttrs) - { + /** + * {@inheritDoc} + */ + public void setHighlightAttributes(ShapeAttributes highlightAttrs) { this.highlightAttrs = highlightAttrs; this.updateModifiedTime(); } - public String getPathType() - { + public String getPathType() { return this.pathType; } - public void setPathType(String pathType) - { - if (pathType == null) - { + public void setPathType(String pathType) { + if (pathType == null) { String message = Logging.getMessage("nullValue.PathTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -182,15 +199,12 @@ public void setPathType(String pathType) this.onShapeChanged(); } - public double getTexelsPerEdgeInterval() - { + public double getTexelsPerEdgeInterval() { return this.texelsPerEdgeInterval; } - public void setTexelsPerEdgeInterval(double texelsPerEdgeInterval) - { - if (texelsPerEdgeInterval <= 0) - { + public void setTexelsPerEdgeInterval(double texelsPerEdgeInterval) { + if (texelsPerEdgeInterval <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "texelsPerEdgeInterval <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -200,22 +214,18 @@ public void setTexelsPerEdgeInterval(double texelsPerEdgeInterval) this.onShapeChanged(); } - public int[] getMinAndMaxEdgeIntervals() - { - return new int[] {this.minEdgeIntervals, this.maxEdgeIntervals}; + public int[] getMinAndMaxEdgeIntervals() { + return new int[]{this.minEdgeIntervals, this.maxEdgeIntervals}; } - public void setMinAndMaxEdgeIntervals(int minEdgeIntervals, int maxEdgeIntervals) - { - if (minEdgeIntervals < 0) - { + public void setMinAndMaxEdgeIntervals(int minEdgeIntervals, int maxEdgeIntervals) { + if (minEdgeIntervals < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "minEdgeIntervals < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (maxEdgeIntervals < 0) - { + if (maxEdgeIntervals < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "maxEdgeIntervals < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -234,31 +244,25 @@ public void setMinAndMaxEdgeIntervals(int minEdgeIntervals, int maxEdgeIntervals * that depend on the Globe should return a state key that include the globe's state key. */ @Override - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { // Store a copy of the active attributes to insulate the key from changes made to the shape's active attributes. // Use a null globe state key because SurfaceShape does not depend on the globe by default. return new SurfaceShapeStateKey(this.getUniqueId(), this.lastModifiedTime, this.getActiveAttributes().copy(), - null); + null); } @SuppressWarnings({"unchecked"}) - public List getSectors(DrawContext dc) - { - if (dc == null) - { + public List getSectors(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } CacheEntry entry = this.sectorCache.get(dc.getGlobe().getGlobeStateKey()); - if (entry != null) - { + if (entry != null) { return (List) entry.object; - } - else - { + } else { entry = new CacheEntry(this.computeSectors(dc), dc); this.sectorCache.put(dc.getGlobe().getGlobeStateKey(), entry); return (List) entry.object; @@ -273,8 +277,7 @@ public List getSectors(DrawContext dc) * * @return Bounding sectors for the shape. */ - protected List computeSectors(DrawContext dc) - { + protected List computeSectors(DrawContext dc) { return this.computeSectors(dc.getGlobe()); } @@ -286,49 +289,46 @@ protected List computeSectors(DrawContext dc) * * @return Bounding sectors for the shape. */ - protected List computeSectors(Globe globe) - { + protected List computeSectors(Globe globe) { Iterable locations = this.getLocations(globe); - if (locations == null) + if (locations == null) { return null; + } List sectors = null; String pole = this.containsPole(locations); - if (pole != null) - { + if (pole != null) { // If the shape contains a pole, then the bounding sector is defined by the shape's extreme latitude, the // latitude of the pole, and the full range of longitude. Sector s = Sector.boundingSector(locations); - if (AVKey.NORTH.equals(pole)) + if (AVKey.NORTH.equals(pole)) { s = new Sector(s.getMinLatitude(), Angle.POS90, Angle.NEG180, Angle.POS180); - else + } else { s = new Sector(Angle.NEG90, s.getMaxLatitude(), Angle.NEG180, Angle.POS180); + } sectors = Arrays.asList(s); - } - else if (LatLon.locationsCrossDateLine(locations)) - { + } else if (LatLon.locationsCrossDateLine(locations)) { Sector[] array = Sector.splitBoundingSectors(locations); - if (array != null && array.length == 2 && !isSectorEmpty(array[0]) && !isSectorEmpty(array[1])) + if (array != null && array.length == 2 && !isSectorEmpty(array[0]) && !isSectorEmpty(array[1])) { sectors = Arrays.asList(array); - } - else - { + } + } else { Sector s = Sector.boundingSector(locations); - if (!isSectorEmpty(s)) + if (!isSectorEmpty(s)) { sectors = Arrays.asList(s); + } } - if (sectors == null) + if (sectors == null) { return null; + } // Great circle paths between two latitudes may result in a latitude which is greater or smaller than either of // the two latitudes. All other path types are bounded by the defining locations. - if (AVKey.GREAT_CIRCLE.equals(this.getPathType())) - { - for (int i = 0; i < sectors.size(); i++) - { + if (AVKey.GREAT_CIRCLE.equals(this.getPathType())) { + for (int i = 0; i < sectors.size(); i++) { Sector s = sectors.get(i); LatLon[] extremes = LatLon.greatCircleArcExtremeLocations(locations); @@ -336,10 +336,12 @@ else if (LatLon.locationsCrossDateLine(locations)) double minLatDegrees = s.getMinLatitude().degrees; double maxLatDegrees = s.getMaxLatitude().degrees; - if (minLatDegrees > extremes[0].getLatitude().degrees) + if (minLatDegrees > extremes[0].getLatitude().degrees) { minLatDegrees = extremes[0].getLatitude().degrees; - if (maxLatDegrees < extremes[1].getLatitude().degrees) + } + if (maxLatDegrees < extremes[1].getLatitude().degrees) { maxLatDegrees = extremes[1].getLatitude().degrees; + } Angle minLat = Angle.fromDegreesLatitude(minLatDegrees); Angle maxLat = Angle.fromDegreesLatitude(maxLatDegrees); @@ -351,17 +353,18 @@ else if (LatLon.locationsCrossDateLine(locations)) return sectors; } - protected static boolean isSectorEmpty(Sector sector) - { - if (sector == null) + protected static boolean isSectorEmpty(Sector sector) { + if (sector == null) { return true; + } //noinspection SimplifiableIfStatement - if (sector.equals(Sector.EMPTY_SECTOR)) + if (sector.equals(Sector.EMPTY_SECTOR)) { return true; + } return sector.getMinLatitude().equals(sector.getMaxLatitude()) - && sector.getMinLongitude().equals(sector.getMaxLongitude()); + && sector.getMinLongitude().equals(sector.getMaxLongitude()); } /** @@ -369,53 +372,46 @@ protected static boolean isSectorEmpty(Sector sector) * given a specified {@link gov.nasa.worldwind.globes.Globe} and vertical exaggeration (see {@link * gov.nasa.worldwind.SceneController#getVerticalExaggeration()}. * - * @param globe the Globe this SurfaceShape is related to. + * @param globe the Globe this SurfaceShape is related to. * @param verticalExaggeration the vertical exaggeration of the scene containing this SurfaceShape. * * @return this SurfaceShape's Extent in model coordinates. * * @throws IllegalArgumentException if the Globe is null. */ - public Extent getExtent(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + public Extent getExtent(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } List sectors = this.computeSectors(globe); - if (sectors == null) + if (sectors == null) { return null; + } return this.computeExtent(globe, verticalExaggeration, sectors); } - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -425,10 +421,8 @@ public void restoreState(String stateInXml) this.doRestoreState(rs, null); } - public double getArea(Globe globe) - { - if (globe == null) - { + public double getArea(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -438,10 +432,8 @@ public double getArea(Globe globe) return areaMeasurer.getArea(globe); } - public double getArea(Globe globe, boolean terrainConformant) - { - if (globe == null) - { + public double getArea(Globe globe, boolean terrainConformant) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -452,10 +444,8 @@ public double getArea(Globe globe, boolean terrainConformant) return areaMeasurer.getArea(globe); } - public double getPerimeter(Globe globe) - { - if (globe == null) - { + public double getPerimeter(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -465,10 +455,8 @@ public double getPerimeter(Globe globe) return areaMeasurer.getPerimeter(globe); } - public double getWidth(Globe globe) - { - if (globe == null) - { + public double getWidth(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -478,10 +466,8 @@ public double getWidth(Globe globe) return areaMeasurer.getWidth(globe); } - public double getHeight(Globe globe) - { - if (globe == null) - { + public double getHeight(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -491,10 +477,8 @@ public double getHeight(Globe globe) return areaMeasurer.getHeight(globe); } - public double getLength(Globe globe) - { - if (globe == null) - { + public double getLength(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -504,103 +488,100 @@ public double getLength(Globe globe) return areaMeasurer.getLength(globe); } - public void move(Position position) - { - if (position == null) - { + public void move(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Position referencePosition = this.getReferencePosition(); - if (referencePosition == null) + if (referencePosition == null) { return; + } this.moveTo(referencePosition.add(position)); } - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Position oldReferencePosition = this.getReferencePosition(); - if (oldReferencePosition == null) + if (oldReferencePosition == null) { return; + } this.doMoveTo(oldReferencePosition, position); } - public void moveTo(Globe globe, Position position) - { - if (position == null) - { + public void moveTo(Globe globe, Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Position oldReferencePosition = this.getReferencePosition(); - if (oldReferencePosition == null) + if (oldReferencePosition == null) { return; + } this.doMoveTo(globe, oldReferencePosition, position); } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, WorldWind.CLAMP_TO_GROUND); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void combine(CombineContext cc) - { - if (cc == null) - { + public void combine(CombineContext cc) { + if (cc == null) { String msg = Logging.getMessage("nullValue.CombineContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (cc.isBoundingSectorMode()) + if (cc.isBoundingSectorMode()) { this.combineBounds(cc); - else + } else { this.combineContours(cc); + } } public abstract Position getReferencePosition(); protected abstract void doMoveTo(Position oldReferencePosition, Position newReferencePosition); + protected abstract void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition); /** @@ -609,8 +590,7 @@ public void combine(CombineContext cc) * Overridden to clear this SurfaceShape's internal sector and geometry caches. */ @Override - protected void clearCaches() - { + protected void clearCaches() { super.clearCaches(); this.sectorCache.clear(); this.geometryCache.clear(); @@ -619,7 +599,6 @@ protected void clearCaches() //**************************************************************// //******************** Rendering *****************************// //**************************************************************// - /** * Overridden to determine the shape's active attributes during preRendering, prior to building the shape's pickable * representation and the SceneController's composite representation. @@ -627,49 +606,41 @@ protected void clearCaches() * @param dc the current draw context. */ @Override - protected void makeOrderedPreRenderable(DrawContext dc) - { + protected void makeOrderedPreRenderable(DrawContext dc) { this.determineActiveAttributes(); super.makeOrderedPreRenderable(dc); } - protected void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) - { - if (dc == null) - { + protected void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sdc == null) - { + if (sdc == null) { String message = Logging.getMessage("nullValue.SurfaceTileDrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.beginDrawing(dc, sdc); - try - { + try { this.doDrawGeographic(dc, sdc); - } - finally - { + } finally { this.endDrawing(dc); } } - protected void beginDrawing(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void beginDrawing(DrawContext dc, SurfaceTileDrawContext sdc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.stackHandler.pushAttrib(gl, - GL2.GL_COLOR_BUFFER_BIT // For alpha test func and ref, blend func - | GL2.GL_CURRENT_BIT // For current color. - | GL2.GL_ENABLE_BIT // For disable depth test. - | GL2.GL_LINE_BIT // For line width, line smooth, line stipple. - | GL2.GL_POLYGON_BIT // For cull enable and cull face. + GL2.GL_COLOR_BUFFER_BIT // For alpha test func and ref, blend func + | GL2.GL_CURRENT_BIT // For current color. + | GL2.GL_ENABLE_BIT // For disable depth test. + | GL2.GL_LINE_BIT // For line width, line smooth, line stipple. + | GL2.GL_POLYGON_BIT // For cull enable and cull face. | GL2.GL_TRANSFORM_BIT); // For matrix mode. this.stackHandler.pushClientAttrib(gl, GL2.GL_CLIENT_VERTEX_ARRAY_BIT); @@ -693,20 +664,17 @@ protected void beginDrawing(DrawContext dc, SurfaceTileDrawContext sdc) gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); // Enable blending. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); } this.applyModelviewTransform(dc, sdc); } - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (texture != null && !dc.isPickingMode()) - { + if (texture != null && !dc.isPickingMode()) { gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, OGLUtil.DEFAULT_TEXTURE_GEN_MODE); gl.glTexGeni(GL2.GL_T, GL2.GL_TEXTURE_GEN_MODE, OGLUtil.DEFAULT_TEXTURE_GEN_MODE); gl.glTexGendv(GL2.GL_S, GL2.GL_OBJECT_PLANE, OGLUtil.DEFAULT_TEXTURE_GEN_S_OBJECT_PLANE, 0); @@ -717,27 +685,26 @@ protected void endDrawing(DrawContext dc) this.stackHandler.pop(gl); } - protected void doDrawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void doDrawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) { this.determineActiveGeometry(dc, sdc); - if (this.getActiveAttributes().isDrawInterior() && this.getActiveAttributes().getInteriorOpacity() > 0) + if (this.getActiveAttributes().isDrawInterior() && this.getActiveAttributes().getInteriorOpacity() > 0) { this.drawInterior(dc, sdc); + } - if (this.getActiveAttributes().isDrawOutline() && this.getActiveAttributes().getOutlineOpacity() > 0) + if (this.getActiveAttributes().isDrawOutline() && this.getActiveAttributes().getOutlineOpacity() > 0) { this.drawOutline(dc, sdc); + } } - protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sdc) { // Apply the geographic to surface tile coordinate transform. Matrix modelview = sdc.getModelviewMatrix(); // If the SurfaceShape has a non-null reference position, transform to the local coordinate system that has its // origin at the reference position. Position refPos = this.getReferencePosition(); - if (refPos != null) - { + if (refPos != null) { Matrix refMatrix = Matrix.fromTranslation(refPos.getLongitude().degrees, refPos.getLatitude().degrees, 0); modelview = modelview.multiply(refMatrix); } @@ -746,77 +713,65 @@ protected void applyModelviewTransform(DrawContext dc, SurfaceTileDrawContext sd gl.glMultMatrixd(modelview.toArray(new double[16], 0, false), 0); } - /** Determines which attributes -- normal, highlight or default -- to use each frame. */ - protected void determineActiveAttributes() - { - if (this.isHighlighted()) - { - if (this.getHighlightAttributes() != null) + /** + * Determines which attributes -- normal, highlight or default -- to use each frame. + */ + protected void determineActiveAttributes() { + if (this.isHighlighted()) { + if (this.getHighlightAttributes() != null) { this.activeAttrs.copy(this.getHighlightAttributes()); - else - { + } else { // If no highlight attributes have been specified we need to use the normal attributes but adjust them // to cause highlighting. - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.activeAttrs.copy(this.getAttributes()); + } this.activeAttrs.setOutlineMaterial(DEFAULT_HIGHLIGHT_MATERIAL); this.activeAttrs.setInteriorMaterial(DEFAULT_HIGHLIGHT_MATERIAL); this.activeAttrs.setOutlineOpacity(1); this.activeAttrs.setInteriorOpacity(1); } - } - else if (this.getAttributes() != null) - { + } else if (this.getAttributes() != null) { this.activeAttrs.copy(this.getAttributes()); - } - else - { + } else { this.activeAttrs.copy(defaultAttrs); } } - protected ShapeAttributes createActiveAttributes() - { + protected ShapeAttributes createActiveAttributes() { return new BasicShapeAttributes(); } - protected ShapeAttributes getActiveAttributes() - { + protected ShapeAttributes getActiveAttributes() { return this.activeAttrs; } - protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) { this.activeGeometry.clear(); this.activeOutlineGeometry.clear(); List> geom = this.getCachedGeometry(dc, sdc); - if (geom == null) + if (geom == null) { return; + } - for (List locations : geom) - { + for (List locations : geom) { List drawLocations = new ArrayList(locations); String pole = this.containsPole(drawLocations); - if (pole != null) - { + if (pole != null) { // Wrap the shape interior around the pole and along the anti-meridian. See WWJ-284. List poleLocations = this.cutAlongDateLine(drawLocations, pole, dc.getGlobe()); this.activeGeometry.add(poleLocations); // The outline need only compensate for dateline crossing. See WWJ-452. List> datelineLocations = this.repeatAroundDateline(drawLocations); this.activeOutlineGeometry.addAll(datelineLocations); - } - else if (LatLon.locationsCrossDateLine(drawLocations)) - { + } else if (LatLon.locationsCrossDateLine(drawLocations)) { List> datelineLocations = this.repeatAroundDateline(drawLocations); this.activeGeometry.addAll(datelineLocations); this.activeOutlineGeometry.addAll(datelineLocations); - } - else - { + } else { this.activeGeometry.add(drawLocations); this.activeOutlineGeometry.add(drawLocations); } @@ -831,10 +786,9 @@ else if (LatLon.locationsCrossDateLine(drawLocations)) * partway around the pole) then the bounding sector is 80 to 85 lat, -100 to 100 lon. * * @return True if the shape is a closed polygon that can contain a pole, or false if it is treated as an open path - * that cannot contain a pole. + * that cannot contain a pole. */ - protected boolean canContainPole() - { + protected boolean canContainPole() { return true; } @@ -846,13 +800,13 @@ protected boolean canContainPole() * @param locations Locations to test. * * @return AVKey.NORTH if the North Pole is enclosed, AVKey.SOUTH if the South Pole is enclosed, or null if neither - * pole is enclosed. Always returns null if {@link #canContainPole()} returns false. + * pole is enclosed. Always returns null if {@link #canContainPole()} returns false. */ // TODO handle a shape that contains both poles. - protected String containsPole(Iterable locations) - { - if (!this.canContainPole()) + protected String containsPole(Iterable locations) { + if (!this.canContainPole()) { return null; + } return LatLon.locationsContainPole(locations); } @@ -863,46 +817,44 @@ protected String containsPole(Iterable locations) * This allows the shape to be "unrolled" when projected in a lat-lon projection. * * @param locations Locations to cut at date line. This list is not modified. - * @param pole Pole contained by locations, either AVKey.NORTH or AVKey.SOUTH. - * @param globe Current globe. + * @param pole Pole contained by locations, either AVKey.NORTH or AVKey.SOUTH. + * @param globe Current globe. * * @return New location list with locations added to correctly handle date line intersection. */ - protected List cutAlongDateLine(List locations, String pole, Globe globe) - { + protected List cutAlongDateLine(List locations, String pole, Globe globe) { // If the locations do not contain a pole, then there's nothing to do. - if (pole == null) + if (pole == null) { return locations; + } return LatLon.cutLocationsAlongDateLine(locations, pole, globe); } /** * Returns a list containing two copies of the specified list of locations crossing the dateline: one that extends - * across the -180 longitude boundary and one that extends across the +180 longitude boundary. If the list of + * across the -180 longitude boundary and one that extends across the +180 longitude boundary. If the list of * locations does not cross the dateline this returns a list containing a copy of the original list. * * @param locations Locations to repeat. This is list not modified. * * @return A list containing two new location lists, one copy for either side of the date line. */ - protected List> repeatAroundDateline(List locations) - { + protected List> repeatAroundDateline(List locations) { return LatLon.repeatLocationsAroundDateline(locations); } - protected List> getActiveGeometry() - { + protected List> getActiveGeometry() { return this.activeGeometry; } - protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) - { - if (this.getActiveGeometry().isEmpty()) + protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) { + if (this.getActiveGeometry().isEmpty()) { return; + } this.applyInteriorState(dc, sdc, this.getActiveAttributes(), this.getInteriorTexture(), - this.getReferencePosition()); + this.getReferencePosition()); // Tessellate and draw the interior, making no assumptions about the nature or structure of the shape's // vertices. The interior is treated as a potentially complex polygon, and this code will do its best to @@ -911,31 +863,30 @@ protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) this.tessellateInterior(dc); } - protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) - { - if (this.activeOutlineGeometry.isEmpty()) + protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) { + if (this.activeOutlineGeometry.isEmpty()) { return; + } this.applyOutlineState(dc, this.getActiveAttributes()); - for (List drawLocations : this.activeOutlineGeometry) - { + for (List drawLocations : this.activeOutlineGeometry) { this.drawLineStrip(dc, drawLocations); } } - protected void drawLineStrip(DrawContext dc, List locations) - { + protected void drawLineStrip(DrawContext dc, List locations) { Position refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return; + } - if (vertexBuffer == null || vertexBuffer.capacity() < 2 * locations.size()) + if (vertexBuffer == null || vertexBuffer.capacity() < 2 * locations.size()) { vertexBuffer = Buffers.newDirectFloatBuffer(2 * locations.size()); + } vertexBuffer.clear(); - for (LatLon ll : locations) - { + for (LatLon ll : locations) { vertexBuffer.put((float) (ll.getLongitude().degrees - refPos.getLongitude().degrees)); vertexBuffer.put((float) (ll.getLatitude().degrees - refPos.getLatitude().degrees)); } @@ -946,15 +897,11 @@ protected void drawLineStrip(DrawContext dc, List locations) gl.glDrawArrays(GL.GL_LINE_STRIP, 0, locations.size()); } - protected WWTexture getInteriorTexture() - { - if (this.getActiveAttributes().getImageSource() == null) - { + protected WWTexture getInteriorTexture() { + if (this.getActiveAttributes().getImageSource() == null) { this.texture = null; - } - else if (this.texture == null - || this.texture.getImageSource() != this.getActiveAttributes().getImageSource()) - { + } else if (this.texture == null + || this.texture.getImageSource() != this.getActiveAttributes().getImageSource()) { this.texture = new BasicWWTexture(this.getActiveAttributes().getImageSource(), true); } @@ -962,10 +909,8 @@ else if (this.texture == null } @SuppressWarnings({"unchecked"}) - protected List> getCachedGeometry(DrawContext dc, SurfaceTileDrawContext sdc) - { - if (dc == null) - { + protected List> getCachedGeometry(DrawContext dc, SurfaceTileDrawContext sdc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -973,44 +918,37 @@ protected List> getCachedGeometry(DrawContext dc, SurfaceTileDrawCo Object key = this.createGeometryKey(dc, sdc); CacheEntry entry = this.geometryCache.get(key); - if (entry != null) - { + if (entry != null) { return (List>) entry.object; - } - else - { + } else { entry = new CacheEntry(this.createGeometry(dc.getGlobe(), sdc), dc); this.geometryCache.put(key, entry); return (List>) entry.object; } } - protected List> createGeometry(Globe globe, SurfaceTileDrawContext sdc) - { + protected List> createGeometry(Globe globe, SurfaceTileDrawContext sdc) { double edgeIntervalsPerDegree = this.computeEdgeIntervalsPerDegree(sdc); return this.createGeometry(globe, edgeIntervalsPerDegree); } protected abstract List> createGeometry(Globe globe, double edgeIntervalsPerDegree); - protected Object createGeometryKey(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected Object createGeometryKey(DrawContext dc, SurfaceTileDrawContext sdc) { return new GeometryKey(dc, this.computeEdgeIntervalsPerDegree(sdc)); } - protected double computeEdgeIntervalsPerDegree(SurfaceTileDrawContext sdc) - { + protected double computeEdgeIntervalsPerDegree(SurfaceTileDrawContext sdc) { double texelsPerDegree = Math.max( - sdc.getViewport().width / sdc.getSector().getDeltaLonDegrees(), - sdc.getViewport().getHeight() / sdc.getSector().getDeltaLatDegrees()); + sdc.getViewport().width / sdc.getSector().getDeltaLonDegrees(), + sdc.getViewport().getHeight() / sdc.getSector().getDeltaLatDegrees()); double intervalsPerTexel = 1.0 / this.getTexelsPerEdgeInterval(); return intervalsPerTexel * texelsPerDegree; } @SuppressWarnings("UnnecessaryLocalVariable") - protected double computeEdgeIntervalsPerDegree(double resolution) - { + protected double computeEdgeIntervalsPerDegree(double resolution) { double degreesPerInterval = resolution * 180.0 / Math.PI; double intervalsPerDegree = 1.0 / degreesPerInterval; @@ -1020,72 +958,59 @@ protected double computeEdgeIntervalsPerDegree(double resolution) //**************************************************************// //******************** Combinable ****************************// //**************************************************************// - - protected void combineBounds(CombineContext cc) - { + protected void combineBounds(CombineContext cc) { List sectorList = this.computeSectors(cc.getGlobe()); - if (sectorList == null) + if (sectorList == null) { return; // no caller specified locations to bound - + } cc.addBoundingSector(Sector.union(sectorList)); } - protected void combineContours(CombineContext cc) - { + protected void combineContours(CombineContext cc) { List sectorList = this.computeSectors(cc.getGlobe()); - if (sectorList == null) + if (sectorList == null) { return; // no caller specified locations to draw - - if (!cc.getSector().intersectsAny(sectorList)) + } + if (!cc.getSector().intersectsAny(sectorList)) { return; // this shape does not intersect the region of interest - + } this.doCombineContours(cc); } - protected void doCombineContours(CombineContext cc) - { + protected void doCombineContours(CombineContext cc) { double edgeIntervalsPerDegree = this.computeEdgeIntervalsPerDegree(cc.getResolution()); List> contours = this.createGeometry(cc.getGlobe(), edgeIntervalsPerDegree); - if (contours == null) + if (contours == null) { return; // shape has no caller specified data - - for (List contour : contours) - { + } + for (List contour : contours) { String pole = this.containsPole(contour); if (pole != null) // Wrap the contour around the pole and along the anti-meridian. See WWJ-284. { List poleContour = this.cutAlongDateLine(contour, pole, cc.getGlobe()); this.doCombineContour(cc, poleContour); - } - else if (LatLon.locationsCrossDateLine(contour)) // Split the contour along the anti-meridian. + } else if (LatLon.locationsCrossDateLine(contour)) // Split the contour along the anti-meridian. { List> datelineContours = this.repeatAroundDateline(contour); this.doCombineContour(cc, datelineContours.get(0)); this.doCombineContour(cc, datelineContours.get(1)); - } - else - { + } else { this.doCombineContour(cc, contour); } } } - protected void doCombineContour(CombineContext cc, Iterable contour) - { + protected void doCombineContour(CombineContext cc, Iterable contour) { GLUtessellator tess = cc.getTessellator(); - try - { + try { GLU.gluTessBeginContour(tess); - for (LatLon location : contour) - { + for (LatLon location : contour) { double[] vertex = {location.longitude.degrees, location.latitude.degrees, 0}; GLU.gluTessVertex(tess, vertex, 0, vertex); } - } - finally - { + } finally { GLU.gluTessEndContour(tess); } } @@ -1093,20 +1018,14 @@ protected void doCombineContour(CombineContext cc, Iterable co //**************************************************************// //******************** Rendering State ***********************// //**************************************************************// - protected void applyInteriorState(DrawContext dc, SurfaceTileDrawContext sdc, ShapeAttributes attributes, - WWTexture texture, LatLon refLocation) - { + WWTexture texture, LatLon refLocation) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (texture != null && !dc.isPickingMode()) - { + if (texture != null && !dc.isPickingMode()) { this.applyInteriorTextureState(dc, sdc, attributes, texture, refLocation); - } - else - { - if (!dc.isPickingMode()) - { + } else { + if (!dc.isPickingMode()) { // Apply blending in non-premultiplied color mode. OGLUtil.applyBlending(gl, false); // Set the current RGBA color to the outline color and opacity. Convert the floating point opacity from the @@ -1123,44 +1042,36 @@ protected void applyInteriorState(DrawContext dc, SurfaceTileDrawContext sdc, Sh } } - protected void applyOutlineState(DrawContext dc, ShapeAttributes attributes) - { + protected void applyOutlineState(DrawContext dc, ShapeAttributes attributes) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Apply line width state double lineWidth = attributes.getOutlineWidth(); - if (dc.isPickingMode() && !attributes.isDrawInterior()) - { - if (lineWidth != 0) + if (dc.isPickingMode() && !attributes.isDrawInterior()) { + if (lineWidth != 0) { lineWidth += 5; + } } gl.glLineWidth((float) lineWidth); // Apply line smooth state - if (!dc.isPickingMode() && attributes.isEnableAntialiasing()) - { + if (!dc.isPickingMode() && attributes.isEnableAntialiasing()) { gl.glEnable(GL.GL_LINE_SMOOTH); - } - else - { + } else { gl.glDisable(GL.GL_LINE_SMOOTH); } // Apply line stipple state. - if (dc.isPickingMode() || (attributes.getOutlineStippleFactor() <= 0)) - { + if (dc.isPickingMode() || (attributes.getOutlineStippleFactor() <= 0)) { gl.glDisable(GL2.GL_LINE_STIPPLE); - } - else - { + } else { gl.glEnable(GL2.GL_LINE_STIPPLE); gl.glLineStipple( - attributes.getOutlineStippleFactor(), - attributes.getOutlineStipplePattern()); + attributes.getOutlineStippleFactor(), + attributes.getOutlineStipplePattern()); } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Apply blending in non-premultiplied color mode. OGLUtil.applyBlending(gl, false); // Set the current RGBA color to the outline color and opacity. Convert the floating point opacity from the @@ -1177,15 +1088,14 @@ protected void applyOutlineState(DrawContext dc, ShapeAttributes attributes) } protected void applyInteriorTextureState(DrawContext dc, SurfaceTileDrawContext sdc, ShapeAttributes attributes, - WWTexture texture, LatLon refLocation) - { + WWTexture texture, LatLon refLocation) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!texture.bind(dc)) + if (!texture.bind(dc)) { return; + } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Apply blending in premultiplied color mode, and set the current RGBA color to white, with the specified // opacity. OGLUtil.applyBlending(gl, true); @@ -1193,8 +1103,8 @@ protected void applyInteriorTextureState(DrawContext dc, SurfaceTileDrawContext } // Apply texture coordinate generation. - double[] planeS = new double[] {1, 0, 0, 1}; - double[] planeT = new double[] {0, 1, 0, 1}; + double[] planeS = new double[]{1, 0, 0, 1}; + double[] planeT = new double[]{0, 1, 0, 1}; gl.glEnable(GL2.GL_TEXTURE_GEN_S); gl.glEnable(GL2.GL_TEXTURE_GEN_T); gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR); @@ -1205,8 +1115,7 @@ protected void applyInteriorTextureState(DrawContext dc, SurfaceTileDrawContext // Apply texture transform. Matrix transform = Matrix.IDENTITY; // Translate geographic coordinates to the reference location. - if (refLocation != null) - { + if (refLocation != null) { double refLatDegrees = refLocation.getLatitude().degrees; double refLonDegrees = refLocation.getLongitude().degrees; transform = Matrix.fromTranslation(refLonDegrees, refLatDegrees, 0d).multiply(transform); @@ -1217,7 +1126,7 @@ protected void applyInteriorTextureState(DrawContext dc, SurfaceTileDrawContext transform = Matrix.fromScale(cosLat / scale, 1d / scale, 1d).multiply(transform); // To maintain the pattern apparent size, we scale it so that one texture pixel match one draw tile pixel. double regionPixelSize = dc.getGlobe().getRadius() * sdc.getSector().getDeltaLatRadians() - / sdc.getViewport().height; + / sdc.getViewport().height; double texturePixelSize = dc.getGlobe().getRadius() * Angle.fromDegrees(1).radians / texture.getHeight(dc); double drawScale = texturePixelSize / regionPixelSize; transform = Matrix.fromScale(drawScale, drawScale, 1d).multiply(transform); // Pre multiply @@ -1238,22 +1147,17 @@ protected void applyInteriorTextureState(DrawContext dc, SurfaceTileDrawContext //**************************************************************// //******************** Intermediate Locations ****************// //**************************************************************// - protected void generateIntermediateLocations(Iterable iterable, double edgeIntervalsPerDegree, - boolean makeClosedPath, List locations) - { + boolean makeClosedPath, List locations) { LatLon firstLocation = null; LatLon lastLocation = null; - for (LatLon ll : iterable) - { - if (firstLocation == null) - { + for (LatLon ll : iterable) { + if (firstLocation == null) { firstLocation = ll; } - if (lastLocation != null) - { + if (lastLocation != null) { this.addIntermediateLocations(lastLocation, ll, edgeIntervalsPerDegree, locations); } @@ -1264,10 +1168,8 @@ protected void generateIntermediateLocations(Iterable iterable // If the caller has instructed us to generate locations for a closed path, then check to see if the specified // locations define a closed path. If not, then we need to generate intermediate locations between the last // and first locations, then close the path by repeating the first location. - if (makeClosedPath) - { - if (firstLocation != null && lastLocation != null && !firstLocation.equals(lastLocation)) - { + if (makeClosedPath) { + if (firstLocation != null && lastLocation != null && !firstLocation.equals(lastLocation)) { this.addIntermediateLocations(lastLocation, firstLocation, edgeIntervalsPerDegree, locations); locations.add(firstLocation); } @@ -1275,47 +1177,38 @@ protected void generateIntermediateLocations(Iterable iterable } @SuppressWarnings({"StringEquality"}) - protected void addIntermediateLocations(LatLon a, LatLon b, double edgeIntervalsPerDegree, List locations) - { - if (this.pathType != null && this.pathType == AVKey.GREAT_CIRCLE) - { + protected void addIntermediateLocations(LatLon a, LatLon b, double edgeIntervalsPerDegree, List locations) { + if (this.pathType != null && this.pathType == AVKey.GREAT_CIRCLE) { Angle pathLength = LatLon.greatCircleDistance(a, b); double edgeIntervals = WWMath.clamp(edgeIntervalsPerDegree * pathLength.degrees, - this.minEdgeIntervals, this.maxEdgeIntervals); + this.minEdgeIntervals, this.maxEdgeIntervals); int numEdgeIntervals = (int) Math.ceil(edgeIntervals); - if (numEdgeIntervals > 1) - { + if (numEdgeIntervals > 1) { double headingRadians = LatLon.greatCircleAzimuth(a, b).radians; double stepSizeRadians = pathLength.radians / (numEdgeIntervals + 1); - for (int i = 1; i <= numEdgeIntervals; i++) - { + for (int i = 1; i <= numEdgeIntervals; i++) { locations.add(LatLon.greatCircleEndPosition(a, headingRadians, i * stepSizeRadians)); } } - } - else if (this.pathType != null && (this.pathType == AVKey.RHUMB_LINE || this.pathType == AVKey.LOXODROME)) - { + } else if (this.pathType != null && (this.pathType == AVKey.RHUMB_LINE || this.pathType == AVKey.LOXODROME)) { Angle pathLength = LatLon.rhumbDistance(a, b); double edgeIntervals = WWMath.clamp(edgeIntervalsPerDegree * pathLength.degrees, - this.minEdgeIntervals, this.maxEdgeIntervals); + this.minEdgeIntervals, this.maxEdgeIntervals); int numEdgeIntervals = (int) Math.ceil(edgeIntervals); - if (numEdgeIntervals > 1) - { + if (numEdgeIntervals > 1) { double headingRadians = LatLon.rhumbAzimuth(a, b).radians; double stepSizeRadians = pathLength.radians / (numEdgeIntervals + 1); - for (int i = 1; i <= numEdgeIntervals; i++) - { + for (int i = 1; i <= numEdgeIntervals; i++) { locations.add(LatLon.rhumbEndPosition(a, headingRadians, i * stepSizeRadians)); } } - } - else // Default to linear interpolation in latitude and longitude. + } else // Default to linear interpolation in latitude and longitude. { // Linear interpolation between 2D coordinates is already performed by GL during shape rasterization. // There is no need to duplicate that effort here. @@ -1325,22 +1218,16 @@ else if (this.pathType != null && (this.pathType == AVKey.RHUMB_LINE || this.pat //**************************************************************// //******************** Interior Tessellation *****************// //**************************************************************// - - protected Integer tessellateInterior(DrawContext dc) - { - if (dc == null) - { + protected Integer tessellateInterior(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return this.doTessellateInterior(dc); - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { String message = Logging.getMessage("generic.ExceptionWhileTessellating", this); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); @@ -1353,8 +1240,7 @@ protected Integer tessellateInterior(DrawContext dc) } } - protected Integer doTessellateInterior(DrawContext dc) - { + protected Integer doTessellateInterior(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. GLUtessellatorCallback cb = GLUTessellatorSupport.createOGLDrawPrimitivesCallback(gl); @@ -1362,12 +1248,9 @@ protected Integer doTessellateInterior(DrawContext dc) // expected tessellation when the shape's contours all have a counter-clockwise winding. GLUTessellatorSupport glts = new GLUTessellatorSupport(); glts.beginTessellation(cb, new Vec4(0, 0, 1)); - try - { + try { return this.tessellateInteriorVertices(glts.getGLUtessellator()); - } - finally - { + } finally { // Free any heap memory used for tessellation immediately. If tessellation has consumed all available heap // memory, we must free memory used by tessellation immediately or subsequent operations such as message // logging will fail. @@ -1375,23 +1258,22 @@ protected Integer doTessellateInterior(DrawContext dc) } } - protected Integer tessellateInteriorVertices(GLUtessellator tess) - { - if (this.getActiveGeometry().isEmpty()) + protected Integer tessellateInteriorVertices(GLUtessellator tess) { + if (this.getActiveGeometry().isEmpty()) { return null; + } Position referencePos = this.getReferencePosition(); - if (referencePos == null) + if (referencePos == null) { return null; + } int numBytes = 0; GLU.gluTessBeginPolygon(tess, null); - for (List drawLocations : this.getActiveGeometry()) - { + for (List drawLocations : this.getActiveGeometry()) { GLU.gluTessBeginContour(tess); - for (LatLon ll : drawLocations) - { + for (LatLon ll : drawLocations) { double[] vertex = new double[3]; vertex[0] = ll.getLongitude().degrees - referencePos.getLongitude().degrees; vertex[1] = ll.getLatitude().degrees - referencePos.getLatitude().degrees; @@ -1406,47 +1288,40 @@ protected Integer tessellateInteriorVertices(GLUtessellator tess) return numBytes; } - protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) - { + protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) { } //**************************************************************// //******************** Measurement ***************************// //**************************************************************// - - protected AreaMeasurer setupAreaMeasurer(Globe globe) - { - if (globe == null) - { + protected AreaMeasurer setupAreaMeasurer(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.areaMeasurer == null) - { + if (this.areaMeasurer == null) { this.areaMeasurer = new AreaMeasurer(); } // Try to use the currently cached locations. If the AreaMeasurer is out of sync with this shape's state, // then update the AreaMeasurer's internal location list. - if (this.areaMeasurerLastModifiedTime < this.lastModifiedTime) - { + if (this.areaMeasurerLastModifiedTime < this.lastModifiedTime) { // The AreaMeasurer requires an ArrayList reference, but SurfaceShapes use an opaque iterable. Copy the // iterable contents into an ArrayList to satisfy AreaMeasurer without compromising the generality of the // shape's iterator. ArrayList arrayList = new ArrayList(); Iterable locations = this.getLocations(globe); - if (locations != null) - { - for (LatLon ll : locations) - { + if (locations != null) { + for (LatLon ll : locations) { arrayList.add(ll); } - if (arrayList.size() > 1 && !arrayList.get(0).equals(arrayList.get(arrayList.size() - 1))) + if (arrayList.size() > 1 && !arrayList.get(0).equals(arrayList.get(arrayList.size() - 1))) { arrayList.add(arrayList.get(0)); + } } this.areaMeasurer.setPositions(arrayList, 0); @@ -1462,9 +1337,7 @@ protected AreaMeasurer setupAreaMeasurer(Globe globe) //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { // Note: drawBoundingSectors is a diagnostic flag, therefore it is not saved or restored. rs.addStateValueAsBoolean(context, "visible", this.isVisible()); @@ -1476,87 +1349,88 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsInteger(context, "minEdgeIntervals", minAndMaxEdgeIntervals[0]); rs.addStateValueAsInteger(context, "maxEdgeIntervals", minAndMaxEdgeIntervals[1]); - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.getAttributes().getRestorableState(rs, rs.addStateObject(context, "attributes")); + } - if (this.getHighlightAttributes() != null) + if (this.getHighlightAttributes() != null) { this.getHighlightAttributes().getRestorableState(rs, rs.addStateObject(context, "highlightAttrs")); + } RestorableSupport.StateObject so = rs.addStateObject(null, "avlist"); - for (Map.Entry avp : this.getEntries()) - { + for (Map.Entry avp : this.getEntries()) { this.getRestorableStateForAVPair(avp.getKey(), avp.getValue() != null ? avp.getValue() : "", rs, so); } } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Invoke the legacy restore functionality. This will enable the shape to recognize state XML elements // from the previous version of SurfaceShape. this.legacyRestoreState(rs, context); // Note: drawBoundingSectors is a diagnostic flag, therefore it is not saved or restored. - Boolean b = rs.getStateValueAsBoolean(context, "visible"); - if (b != null) + if (b != null) { this.setVisible(b); + } b = rs.getStateValueAsBoolean(context, "highlighted"); - if (b != null) + if (b != null) { this.setHighlighted(b); + } String s = rs.getStateValueAsString(context, "pathType"); - if (s != null) - { + if (s != null) { String pathType = this.pathTypeFromString(s); - if (pathType != null) + if (pathType != null) { this.setPathType(pathType); + } } Double d = rs.getStateValueAsDouble(context, "texelsPerEdgeInterval"); - if (d != null) + if (d != null) { this.setTexelsPerEdgeInterval(d); + } int[] minAndMaxEdgeIntervals = this.getMinAndMaxEdgeIntervals(); Integer minEdgeIntervals = rs.getStateValueAsInteger(context, "minEdgeIntervals"); - if (minEdgeIntervals != null) + if (minEdgeIntervals != null) { minAndMaxEdgeIntervals[0] = minEdgeIntervals; + } Integer maxEdgeIntervals = rs.getStateValueAsInteger(context, "maxEdgeIntervals"); - if (maxEdgeIntervals != null) + if (maxEdgeIntervals != null) { minAndMaxEdgeIntervals[1] = maxEdgeIntervals; + } - if (minEdgeIntervals != null || maxEdgeIntervals != null) + if (minEdgeIntervals != null || maxEdgeIntervals != null) { this.setMinAndMaxEdgeIntervals(minAndMaxEdgeIntervals[0], minAndMaxEdgeIntervals[1]); + } RestorableSupport.StateObject so = rs.getStateObject(context, "attributes"); - if (so != null) - { + if (so != null) { ShapeAttributes attrs = (this.getAttributes() != null) ? this.getAttributes() : new BasicShapeAttributes(); attrs.restoreState(rs, so); this.setAttributes(attrs); } so = rs.getStateObject(context, "highlightAttrs"); - if (so != null) - { + if (so != null) { ShapeAttributes attrs = (this.getHighlightAttributes() != null) ? this.getHighlightAttributes() - : new BasicShapeAttributes(); + : new BasicShapeAttributes(); attrs.restoreState(rs, so); this.setHighlightAttributes(attrs); } so = rs.getStateObject(null, "avlist"); - if (so != null) - { + if (so != null) { RestorableSupport.StateObject[] avpairs = rs.getAllStateObjects(so, ""); - if (avpairs != null) - { - for (RestorableSupport.StateObject avp : avpairs) - { - if (avp != null) + if (avpairs != null) { + for (RestorableSupport.StateObject avp : avpairs) { + if (avp != null) { this.setValue(avp.getName(), avp.getValue()); + } } } } @@ -1573,79 +1447,75 @@ protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObjec * restored in {@link #doRestoreState(gov.nasa.worldwind.util.RestorableSupport, * gov.nasa.worldwind.util.RestorableSupport.StateObject)}. * - * @param rs RestorableSupport object which contains the state value properties. + * @param rs RestorableSupport object which contains the state value properties. * @param context active context in the RestorableSupport to read state from. */ - protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Ignore texture width and height parameters, they're no longer used. //Integer width = rs.getStateValueAsInteger(context, "textureWidth"); //Integer height = rs.getStateValueAsInteger(context, "textureHeight"); //if (width != null && height != null) // this.setTextureSize(new Dimension(width, height)); - ShapeAttributes attrs = this.getAttributes(); java.awt.Color color = rs.getStateValueAsColor(context, "color"); - if (color != null) + if (color != null) { (attrs != null ? attrs : (attrs = new BasicShapeAttributes())).setInteriorMaterial(new Material(color)); + } color = rs.getStateValueAsColor(context, "borderColor"); - if (color != null) + if (color != null) { (attrs != null ? attrs : (attrs = new BasicShapeAttributes())).setOutlineMaterial(new Material(color)); + } Double dub = rs.getStateValueAsDouble(context, "lineWidth"); - if (dub != null) + if (dub != null) { (attrs != null ? attrs : (attrs = new BasicShapeAttributes())).setOutlineWidth(dub); + } // Ignore numEdgeIntervalsPerDegree, since it's no longer used. //Double intervals = rs.getStateValueAsDouble(context, "numEdgeIntervalsPerDegree"); //if (intervals != null) // this.setEdgeIntervalsPerDegree(intervals.intValue()); - Boolean booleanState = rs.getStateValueAsBoolean(context, "drawBorder"); - if (booleanState != null) + if (booleanState != null) { (attrs != null ? attrs : (attrs = new BasicShapeAttributes())).setDrawOutline(booleanState); + } booleanState = rs.getStateValueAsBoolean(context, "drawInterior"); - if (booleanState != null) + if (booleanState != null) { (attrs != null ? attrs : (attrs = new BasicShapeAttributes())).setDrawInterior(booleanState); + } booleanState = rs.getStateValueAsBoolean(context, "antialias"); - if (booleanState != null) + if (booleanState != null) { (attrs != null ? attrs : (attrs = new BasicShapeAttributes())).setEnableAntialiasing(booleanState); + } - if (attrs != null) + if (attrs != null) { this.setAttributes(attrs); + } // Positions data is a per object property now. This value is recognized by SurfacePolygon, SurfacePolyline, and // SurfaceSector. Other shapes ignore this property. - //ArrayList locations = rs.getStateValueAsLatLonList(context, "locations"); //if (locations != null) // this.positions = locations; } - protected String pathTypeFromString(String s) - { - if (s == null) + protected String pathTypeFromString(String s) { + if (s == null) { return null; + } - if (s.equals(AVKey.GREAT_CIRCLE)) - { + if (s.equals(AVKey.GREAT_CIRCLE)) { return AVKey.GREAT_CIRCLE; - } - else if (s.equals(AVKey.LINEAR)) - { + } else if (s.equals(AVKey.LINEAR)) { return AVKey.LINEAR; - } - else if (s.equals(AVKey.LOXODROME)) - { + } else if (s.equals(AVKey.LOXODROME)) { return AVKey.LOXODROME; - } - else if (s.equals(AVKey.RHUMB_LINE)) - { + } else if (s.equals(AVKey.RHUMB_LINE)) { return AVKey.RHUMB_LINE; } @@ -1655,7 +1525,6 @@ else if (s.equals(AVKey.RHUMB_LINE)) //**************************************************************// //******************** State Key *****************************// //**************************************************************// - /** * Represents a surface shapes's current state. SurfaceShapeStateKey extends {@link * gov.nasa.worldwind.render.AbstractSurfaceObject.SurfaceObjectStateKey} by adding the shape's current {@link @@ -1665,26 +1534,29 @@ else if (s.equals(AVKey.RHUMB_LINE)) * but also distinguishes the shape's active ShapeAttributes from any previous attributes, and distinguishes between * different globes via the globe state key. */ - protected static class SurfaceShapeStateKey extends SurfaceObjectStateKey - { - /** The SurfaceShape's attributes. May be null if the shape has no attributes. */ + protected static class SurfaceShapeStateKey extends SurfaceObjectStateKey { + + /** + * The SurfaceShape's attributes. May be null if the shape has no attributes. + */ protected final ShapeAttributes attributes; - /** The Globe's state key. May be null if the shape's state does not depend on the globe. */ + /** + * The Globe's state key. May be null if the shape's state does not depend on the globe. + */ protected final Object globeStateKey; /** * Constructs a new SurfaceShapeStateKey with the specified unique ID, modified time, attributes, and globe * state key. The globe state key should be null if the surface shape does not depend on the globe. * - * @param uniqueID the SurfaceShape's unique ID. - * @param modifiedTime the SurfaceShape's modified time. - * @param attributes the SurfaceShape's attributes, or null if the shape has no attributes. + * @param uniqueID the SurfaceShape's unique ID. + * @param modifiedTime the SurfaceShape's modified time. + * @param attributes the SurfaceShape's attributes, or null if the shape has no attributes. * @param globeStateKey the globe's state key, or null if the shape does not depend on the globe. * * @see gov.nasa.worldwind.globes.Globe#getStateKey(DrawContext) */ - public SurfaceShapeStateKey(long uniqueID, long modifiedTime, ShapeAttributes attributes, Object globeStateKey) - { + public SurfaceShapeStateKey(long uniqueID, long modifiedTime, ShapeAttributes attributes, Object globeStateKey) { super(uniqueID, modifiedTime); this.attributes = attributes; @@ -1693,23 +1565,23 @@ public SurfaceShapeStateKey(long uniqueID, long modifiedTime, ShapeAttributes at @Override @SuppressWarnings({"SimplifiableIfStatement"}) - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } SurfaceShapeStateKey that = (SurfaceShapeStateKey) o; return super.equals(o) - && (this.attributes != null ? this.attributes.equals(that.attributes) : that.attributes == null) - && (this.globeStateKey != null ? this.globeStateKey.equals(that.globeStateKey) - : that.globeStateKey == null); + && (this.attributes != null ? this.attributes.equals(that.attributes) : that.attributes == null) + && (this.globeStateKey != null ? this.globeStateKey.equals(that.globeStateKey) + : that.globeStateKey == null); } @Override - public int hashCode() - { + public int hashCode() { int result = super.hashCode(); result = 31 * result + (this.attributes != null ? this.attributes.hashCode() : 0); result = 31 * result + (this.globeStateKey != null ? this.globeStateKey.hashCode() : 0); @@ -1723,8 +1595,7 @@ public int hashCode() * @return The state key's size in bytes. */ @Override - public long getSizeInBytes() - { + public long getSizeInBytes() { return super.getSizeInBytes() + 64; // Add the shape attributes and the references. } } @@ -1732,36 +1603,34 @@ public long getSizeInBytes() //**************************************************************// //******************** Cache Key, Cache Entry ****************// //**************************************************************// + protected static class GeometryKey { - protected static class GeometryKey - { protected Globe globe; protected double edgeIntervalsPerDegree; - public GeometryKey(DrawContext dc, double edgeIntervalsPerDegree) - { + public GeometryKey(DrawContext dc, double edgeIntervalsPerDegree) { this.globe = dc.getGlobe(); this.edgeIntervalsPerDegree = edgeIntervalsPerDegree; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } GeometryKey that = (GeometryKey) o; return this.globe.equals(that.globe) && this.edgeIntervalsPerDegree == that.edgeIntervalsPerDegree; } @Override - public int hashCode() - { + public int hashCode() { int hash = this.globe.hashCode(); long temp = this.edgeIntervalsPerDegree != +0.0d ? Double.doubleToLongBits(this.edgeIntervalsPerDegree) - : 0L; + : 0L; return 31 * hash + (int) (temp ^ (temp >>> 32)); } } @@ -1776,12 +1645,12 @@ public int hashCode() * * @see #export(String, Object) */ - public String isExportFormatSupported(String format) - { - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) + public String isExportFormatSupported(String format) { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) { return Exportable.FORMAT_SUPPORTED; - else + } else { return Exportable.FORMAT_NOT_SUPPORTED; + } } /** @@ -1796,51 +1665,41 @@ public String isExportFormatSupported(String format) * * * @param mimeType MIME type of desired export format. - * @param output An object that will receive the exported data. The type of this object depends on the export - * format (see above). + * @param output An object that will receive the exported data. The type of this object depends on the export format + * (see above). * - * @throws java.io.IOException If an exception occurs writing to the output object. + * @throws java.io.IOException If an exception occurs writing to the output object. * @throws UnsupportedOperationException if the format is not supported by this object, or if the {@code output} - * argument is not of a supported type. + * argument is not of a supported type. */ - public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException - { - if (mimeType == null) - { + public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException { + if (mimeType == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output == null) - { + if (output == null) { String message = Logging.getMessage("nullValue.OutputBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) - { - try - { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { + try { exportAsKML(output); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { Logging.logger().throwing(getClass().getName(), "export", e); throw new IOException(e); } - } - else - { + } else { String message = Logging.getMessage("Export.UnsupportedFormat", mimeType); Logging.logger().warning(message); throw new UnsupportedOperationException(message); } } - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { // This is a dummy method, here to enable a call to it above. It's expected to be overridden by subclasses. } } diff --git a/src/gov/nasa/worldwind/render/Annotation.java b/src/gov/nasa/worldwind/render/Annotation.java index 2ab7c6f19d..277090ba2c 100644 --- a/src/gov/nasa/worldwind/render/Annotation.java +++ b/src/gov/nasa/worldwind/render/Annotation.java @@ -18,18 +18,26 @@ * @author Patrick Murris * @version $Id: Annotation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Annotation extends Renderable, Disposable, Restorable -{ - /** @deprecated Use {@link AVKey#REPEAT_NONE} instead. */ +public interface Annotation extends Renderable, Disposable, Restorable { + + /** + * @deprecated Use {@link AVKey#REPEAT_NONE} instead. + */ @Deprecated public static final String IMAGE_REPEAT_NONE = AVKey.REPEAT_NONE; - /** @deprecated Use {@link AVKey#REPEAT_X} instead. */ + /** + * @deprecated Use {@link AVKey#REPEAT_X} instead. + */ @Deprecated public static final String IMAGE_REPEAT_X = AVKey.REPEAT_X; - /** @deprecated Use {@link AVKey#REPEAT_Y} instead. */ + /** + * @deprecated Use {@link AVKey#REPEAT_Y} instead. + */ @Deprecated public static final String IMAGE_REPEAT_Y = AVKey.REPEAT_Y; - /** @deprecated Use {@link AVKey#REPEAT_XY} instead. */ + /** + * @deprecated Use {@link AVKey#REPEAT_XY} instead. + */ @Deprecated public static final String IMAGE_REPEAT_XY = AVKey.REPEAT_XY; @@ -37,10 +45,14 @@ public interface Annotation extends Renderable, Disposable, Restorable public final static int ANTIALIAS_FASTEST = GL.GL_FASTEST; public final static int ANTIALIAS_NICEST = GL.GL_NICEST; - /** @deprecated Use {@link AVKey#SIZE_FIXED} instead. */ + /** + * @deprecated Use {@link AVKey#SIZE_FIXED} instead. + */ @Deprecated public final static String SIZE_FIXED = AVKey.SIZE_FIXED; - /** @deprecated Use {@link AVKey#SIZE_FIT_TEXT} instead. */ + /** + * @deprecated Use {@link AVKey#SIZE_FIT_TEXT} instead. + */ @Deprecated public final static String SIZE_FIT_TEXT = AVKey.SIZE_FIT_TEXT; @@ -98,10 +110,10 @@ public interface Annotation extends Renderable, Disposable, Restorable * draw with the specified width, height, and opacity. The GL should have its model view set to whatever * transformation is desired. * - * @param dc the current DrawContext. - * @param width the width of the Annotation. - * @param height the height of the Annotation. - * @param opacity the opacity of the Annotation. + * @param dc the current DrawContext. + * @param width the width of the Annotation. + * @param height the height of the Annotation. + * @param opacity the opacity of the Annotation. * @param pickPosition the picked Position assigned to the Annotation, if picking is enabled. * * @throws IllegalArgumentException if dc is null. diff --git a/src/gov/nasa/worldwind/render/AnnotationAttributes.java b/src/gov/nasa/worldwind/render/AnnotationAttributes.java index 274f3ef34d..25091462b4 100644 --- a/src/gov/nasa/worldwind/render/AnnotationAttributes.java +++ b/src/gov/nasa/worldwind/render/AnnotationAttributes.java @@ -14,25 +14,29 @@ /** * {@link Annotation} attributes set. All {@link AbstractAnnotation} objects start life referencing a new instance of - * this object.

          This class also defines a static default attributes bundle containing default values for all - * attributes. New AnnotationAttributes refer this static bundle as their default values source when an - * attribute has not been set.

          New AnnotationAttributes set have all their attributes pointing to - * the default values until they are set by the application. Most attributes refer to the default value by using minus - * one (-1) for numerics and null for objects.

          The default attributes set can be - * changed for a non static one under the application control. The process can be extended or cascaded to handle - * multiple levels of inheritance for default attributes.

          + * this object. + *

          + * This class also defines a static default attributes bundle containing default values for all attributes. New + * AnnotationAttributes refer this static bundle as their default values source when an attribute has not + * been set.

          + *

          + * New AnnotationAttributes set have all their attributes pointing to the default values until they are set + * by the application. Most attributes refer to the default value by using minus one (-1) for numerics and + * null for objects.

          + *

          + * The default attributes set can be changed for a non static one under the application control. The process can be + * extended or cascaded to handle multiple levels of inheritance for default attributes.

          * * @author Patrick Murris * @version $Id: AnnotationAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ * @see AbstractAnnotation * @see MultiLineTextRenderer */ -public class AnnotationAttributes implements Restorable -{ +public class AnnotationAttributes implements Restorable { + private static final AnnotationAttributes defaults = new AnnotationAttributes(); - static - { + static { defaults.setFrameShape(AVKey.SHAPE_RECTANGLE); defaults.setSize(new Dimension(160, 0)); defaults.setScale(1); @@ -100,16 +104,13 @@ public class AnnotationAttributes implements Restorable protected boolean unresolved; //** Public properties ********************************************************************** - /** * Set the fallback default attributes set. * * @param attr the default attributes set. */ - public void setDefaults(AnnotationAttributes attr) - { - if (attr == null) - { + public void setDefaults(AnnotationAttributes attr) { + if (attr == null) { String message = Logging.getMessage("nullValue.AnnotationAttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -123,23 +124,23 @@ public void setDefaults(AnnotationAttributes attr) * * @return the callout frame shape. */ - public String getFrameShape() - { + public String getFrameShape() { return this.frameShape != null ? this.frameShape : defaultAttributes.getFrameShape(); } /** * Set the callout frame shape. Can be one of AVKey.SHAPE_RECTANGLE (default), * AVKey.SHAPE_ELLIPSE or AVKey.SHAPE_NONE. Set to null to use the default - * shape.

          Note that AVKey.SHAPE_ELLIPSE draws an ellipse inside the callout bounding - * rectangle set by its size (see setSize()) or its text bounding rectangle (see setAdjustWidthToText() and - * setSize() with height set to zero). It is often necessary to have larger Insets dimensions (see setInsets()) to - * avoid having the text drawn outside the shape border.

          + * shape. + *

          + * Note that AVKey.SHAPE_ELLIPSE draws an ellipse inside the callout bounding rectangle set by + * its size (see setSize()) or its text bounding rectangle (see setAdjustWidthToText() and setSize() with height set + * to zero). It is often necessary to have larger Insets dimensions (see setInsets()) to avoid having the text drawn + * outside the shape border.

          * * @param shape the callout frame shape. */ - public void setFrameShape(String shape) - { + public void setFrameShape(String shape) { this.frameShape = shape; } @@ -148,8 +149,7 @@ public void setFrameShape(String shape) * * @return true if highlighted. */ - public boolean isHighlighted() - { + public boolean isHighlighted() { return isHighlighted; } @@ -158,8 +158,7 @@ public boolean isHighlighted() * * @param highlighted true if highlighted. */ - public void setHighlighted(boolean highlighted) - { + public void setHighlighted(boolean highlighted) { isHighlighted = highlighted; } @@ -168,8 +167,7 @@ public void setHighlighted(boolean highlighted) * * @return the scaling factor applied to highlighted Annotations. */ - public double getHighlightScale() - { + public double getHighlightScale() { return highlightScale > 0 ? this.highlightScale : defaultAttributes.getHighlightScale(); } @@ -179,8 +177,7 @@ public double getHighlightScale() * * @param highlightScale the scaling factor applied to highlighted Annotations. */ - public void setHighlightScale(double highlightScale) - { + public void setHighlightScale(double highlightScale) { this.highlightScale = highlightScale; } @@ -189,25 +186,27 @@ public void setHighlightScale(double highlightScale) * * @return the callout preferred total dimension in pixels. */ - public Dimension getSize() - { + public Dimension getSize() { return this.size != null ? this.size : defaultAttributes.getSize(); } /** - * Set the annotation callout preferred total dimension in pixels.

          If necessary, the text will be wrapped into - * several lines so as not to exceed the callout preferred width (minus the Insets - * left and right dimensions - see {@link #setInsets(java.awt.Insets) setInsets}). - * However, if {@link #setAdjustWidthToText(String) setAdjustWidthToText} is set to AVKey.SIZE_FIT_TEXT, the final - * callout width will follow that of the final text bounding rectangle.

          If necessary, the text will also be - * truncated so as not to exceed the given height. A zero value (default) will have - * the callout follow the final text bounding rectangle height (including the Insets top - * and bottom).

          Set to null to use the default size. + * Set the annotation callout preferred total dimension in pixels. + *

          + * If necessary, the text will be wrapped into several lines so as not to exceed the callout preferred + * width (minus the Insets left and right dimensions - + * see {@link #setInsets(java.awt.Insets) setInsets}). However, if + * {@link #setAdjustWidthToText(String) setAdjustWidthToText} is set to AVKey.SIZE_FIT_TEXT, the final callout width + * will follow that of the final text bounding rectangle.

          + *

          + * If necessary, the text will also be truncated so as not to exceed the given height. A + * zero value (default) will have the callout follow the final text bounding rectangle height + * (including the Insets top and bottom).

          Set to null to + * use the default size. * * @param size the callout preferred total dimension in pixels. */ - public void setSize(Dimension size) - { + public void setSize(Dimension size) { this.size = size; } @@ -216,8 +215,7 @@ public void setSize(Dimension size) * * @return the scaling factor applied to the annotation */ - public double getScale() - { + public double getScale() { return this.scale >= 0 ? this.scale : defaultAttributes.getScale(); } @@ -227,8 +225,7 @@ public double getScale() * * @param scale the scaling factor to apply to the annotation */ - public void setScale(double scale) - { + public void setScale(double scale) { this.scale = scale; } @@ -237,8 +234,7 @@ public void setScale(double scale) * * @return the opacity factor applied to the annotation */ - public double getOpacity() - { + public double getOpacity() { return this.opacity >= 0 ? this.opacity : defaultAttributes.getOpacity(); } @@ -248,8 +244,7 @@ public double getOpacity() * * @param opacity the opacity factor to apply to the annotation */ - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { this.opacity = opacity; } @@ -259,8 +254,7 @@ public void setOpacity(double opacity) * * @return the callout shape leader type. */ - public String getLeader() - { + public String getLeader() { return this.leader != null ? this.leader : defaultAttributes.getLeader(); } @@ -270,8 +264,7 @@ public String getLeader() * * @param leader the callout shape leader type. */ - public void setLeader(String leader) - { + public void setLeader(String leader) { this.leader = leader; } @@ -280,8 +273,7 @@ public void setLeader(String leader) * * @return the callout shape leader gap width. */ - public int getLeaderGapWidth() - { + public int getLeaderGapWidth() { return this.leaderGapWidth >= 0 ? this.leaderGapWidth : defaultAttributes.getLeaderGapWidth(); } @@ -291,8 +283,7 @@ public int getLeaderGapWidth() * * @param width the callout shape leader gap width in pixels. */ - public void setLeaderGapWidth(int width) - { + public void setLeaderGapWidth(int width) { this.leaderGapWidth = width; } @@ -301,8 +292,7 @@ public void setLeaderGapWidth(int width) * * @return the callout shape rounded corners radius in pixels. */ - public int getCornerRadius() - { + public int getCornerRadius() { return this.cornerRadius >= 0 ? this.cornerRadius : defaultAttributes.getCornerRadius(); } @@ -312,8 +302,7 @@ public int getCornerRadius() * * @param radius the callout shape rounded corners radius in pixels. */ - public void setCornerRadius(int radius) - { + public void setCornerRadius(int radius) { this.cornerRadius = radius; } @@ -324,8 +313,7 @@ public void setCornerRadius(int radius) * * @return whether the callout width is adjusted to follow the text bounding rectangle width. */ - public String getAdjustWidthToText() - { + public String getAdjustWidthToText() { return this.adjustWidthToText != null ? this.adjustWidthToText : defaultAttributes.getAdjustWidthToText(); } @@ -337,8 +325,7 @@ public String getAdjustWidthToText() * * @param state whether the callout width should adjust to follow the text bounding rectangle width. */ - public void setAdjustWidthToText(String state) - { + public void setAdjustWidthToText(String state) { this.adjustWidthToText = state; } @@ -350,8 +337,7 @@ public void setAdjustWidthToText(String state) * * @return the callout displacement offset in pixels */ - public Point getDrawOffset() - { + public Point getDrawOffset() { return this.drawOffset != null ? this.drawOffset : defaultAttributes.getDrawOffset(); } @@ -364,8 +350,7 @@ public Point getDrawOffset() * * @param offset the callout displacement offset in pixels */ - public void setDrawOffset(Point offset) - { + public void setDrawOffset(Point offset) { this.drawOffset = offset; } @@ -375,8 +360,7 @@ public void setDrawOffset(Point offset) * * @return the callout Insets dimensions in pixels. */ - public Insets getInsets() - { + public Insets getInsets() { return this.insets != null ? this.insets : defaultAttributes.getInsets(); } @@ -387,8 +371,7 @@ public Insets getInsets() * * @param insets the callout Insets dimensions in pixels. */ - public void setInsets(Insets insets) - { + public void setInsets(Insets insets) { this.insets = insets; } @@ -397,8 +380,7 @@ public void setInsets(Insets insets) * * @return the callout border line width. */ - public double getBorderWidth() - { + public double getBorderWidth() { return this.borderWidth >= 0 ? this.borderWidth : defaultAttributes.getBorderWidth(); } @@ -408,8 +390,7 @@ public double getBorderWidth() * * @param width the callout border line width. */ - public void setBorderWidth(double width) - { + public void setBorderWidth(double width) { this.borderWidth = width; } @@ -419,8 +400,7 @@ public void setBorderWidth(double width) * * @return the stipple factor used for the callout border line. */ - public int getBorderStippleFactor() - { + public int getBorderStippleFactor() { return this.borderStippleFactor >= 0 ? this.borderStippleFactor : defaultAttributes.getBorderStippleFactor(); } @@ -430,8 +410,7 @@ public int getBorderStippleFactor() * * @param factor the stipple factor used for the callout border line. */ - public void setBorderStippleFactor(int factor) - { + public void setBorderStippleFactor(int factor) { this.borderStippleFactor = factor; } @@ -440,10 +419,9 @@ public void setBorderStippleFactor(int factor) * * @return the stipple pattern used for the callout border line. */ - public short getBorderStipplePattern() - { + public short getBorderStipplePattern() { return this.borderStipplePattern != 0x0000 ? this.borderStipplePattern - : defaultAttributes.getBorderStipplePattern(); + : defaultAttributes.getBorderStipplePattern(); } /** @@ -451,8 +429,7 @@ public short getBorderStipplePattern() * * @param pattern the stipple pattern used for the callout border line. */ - public void setBorderStipplePattern(short pattern) - { + public void setBorderStipplePattern(short pattern) { this.borderStipplePattern = pattern; } @@ -462,8 +439,7 @@ public void setBorderStipplePattern(short pattern) * * @return the GL antialias hint used for rendering the callout border line. */ - protected int getAntiAliasHint() - { + protected int getAntiAliasHint() { return this.antiAliasHint >= 0 ? this.antiAliasHint : defaultAttributes.getAntiAliasHint(); } @@ -474,8 +450,7 @@ protected int getAntiAliasHint() * * @param hint the GL antialias hint used for rendering the callout border line. */ - protected void setAntiAliasHint(int hint) - { + protected void setAntiAliasHint(int hint) { this.antiAliasHint = hint; } @@ -484,8 +459,7 @@ protected void setAntiAliasHint(int hint) * * @return true if the annotation is visible and should be rendered. */ - public boolean isVisible() - { + public boolean isVisible() { return isVisible; } @@ -494,8 +468,7 @@ public boolean isVisible() * * @param visible true if the annotation is visible and should be rendered. */ - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { isVisible = visible; } @@ -504,8 +477,7 @@ public void setVisible(boolean visible) * * @return the Font used for text rendering. */ - public Font getFont() - { + public Font getFont() { return this.font != null ? this.font : defaultAttributes.getFont(); } @@ -514,8 +486,7 @@ public Font getFont() * * @param font the Font used for text rendering. */ - public void setFont(Font font) - { + public void setFont(Font font) { this.font = font; } @@ -525,8 +496,7 @@ public void setFont(Font font) * * @return align the text alignement. Can be one of MultiLineTextRenderer.ALIGN_LEFT, ALIGN_CENTER or ALIGN_RIGHT. */ - public String getTextAlign() - { + public String getTextAlign() { return this.textAlign != null ? this.textAlign : defaultAttributes.getTextAlign(); } @@ -536,8 +506,7 @@ public String getTextAlign() * * @param align the text alignement. */ - public void setTextAlign(String align) - { + public void setTextAlign(String align) { this.textAlign = align; } @@ -546,8 +515,7 @@ public void setTextAlign(String align) * * @return the text Color. */ - public Color getTextColor() - { + public Color getTextColor() { return this.textColor != null ? this.textColor : defaultAttributes.getTextColor(); } @@ -556,8 +524,7 @@ public Color getTextColor() * * @param color the text Color. */ - public void setTextColor(Color color) - { + public void setTextColor(Color color) { this.textColor = color; } @@ -566,8 +533,7 @@ public void setTextColor(Color color) * * @return the callout background Color. */ - public Color getBackgroundColor() - { + public Color getBackgroundColor() { return this.backgroundColor != null ? this.backgroundColor : defaultAttributes.getBackgroundColor(); } @@ -576,8 +542,7 @@ public Color getBackgroundColor() * * @param color the callout background Color. */ - public void setBackgroundColor(Color color) - { + public void setBackgroundColor(Color color) { this.backgroundColor = color; } @@ -586,8 +551,7 @@ public void setBackgroundColor(Color color) * * @return the callout border Color. */ - public Color getBorderColor() - { + public Color getBorderColor() { return this.borderColor != null ? this.borderColor : defaultAttributes.getBorderColor(); } @@ -596,8 +560,7 @@ public Color getBorderColor() * * @param color the callout border Color. */ - public void setBorderColor(Color color) - { + public void setBorderColor(Color color) { this.borderColor = color; } @@ -607,8 +570,7 @@ public void setBorderColor(Color color) * * @return the background image source. */ - public Object getImageSource() - { + public Object getImageSource() { return (this.backgroundTexture != null) ? this.backgroundTexture.getImageSource() : null; } @@ -618,13 +580,11 @@ public Object getImageSource() * * @param imageSource the background image source. */ - public void setImageSource(Object imageSource) - { + public void setImageSource(Object imageSource) { this.previousBackgroundTexture = this.backgroundTexture; this.backgroundTexture = null; - if (imageSource != null) - { + if (imageSource != null) { this.backgroundTexture = new BasicWWTexture(imageSource, true); } } @@ -635,13 +595,10 @@ public void setImageSource(Object imageSource) * * @param dc the current draw context. * - * @return the background image as a WWTexture, or null if this AnnotationAttributes has no background image - * source. + * @return the background image as a WWTexture, or null if this AnnotationAttributes has no background image source. */ - public WWTexture getBackgroundTexture(DrawContext dc) - { - if (this.previousBackgroundTexture != null) - { + public WWTexture getBackgroundTexture(DrawContext dc) { + if (this.previousBackgroundTexture != null) { dc.getTextureCache().remove(this.previousBackgroundTexture.getImageSource()); this.previousBackgroundTexture = null; } @@ -654,8 +611,7 @@ public WWTexture getBackgroundTexture(DrawContext dc) * * @return the background image scaling factor. */ - public double getImageScale() - { + public double getImageScale() { return this.imageScale >= 0 ? this.imageScale : defaultAttributes.getImageScale(); } @@ -664,8 +620,7 @@ public double getImageScale() * * @param scale the background image scaling factor. */ - public void setImageScale(double scale) - { + public void setImageScale(double scale) { this.imageScale = scale; } @@ -674,8 +629,7 @@ public void setImageScale(double scale) * * @return the background image offset in pixels */ - public Point getImageOffset() - { + public Point getImageOffset() { return this.imageOffset != null ? this.imageOffset : defaultAttributes.getImageOffset(); } @@ -685,8 +639,7 @@ public Point getImageOffset() * * @param offset the background image offset in pixels */ - public void setImageOffset(Point offset) - { + public void setImageOffset(Point offset) { this.imageOffset = offset; } @@ -695,8 +648,7 @@ public void setImageOffset(Point offset) * * @return the opacity of the background image (0 to 1). */ - public double getImageOpacity() - { + public double getImageOpacity() { return this.imageOpacity >= 0 ? this.imageOpacity : defaultAttributes.getImageOpacity(); } @@ -705,8 +657,7 @@ public double getImageOpacity() * * @param opacity the opacity of the background image (0 to 1). */ - public void setImageOpacity(double opacity) - { + public void setImageOpacity(double opacity) { this.imageOpacity = opacity; } @@ -716,8 +667,7 @@ public void setImageOpacity(double opacity) * * @return the repeat behavior or the background image. */ - public String getImageRepeat() - { + public String getImageRepeat() { return this.imageRepeat != null ? this.imageRepeat : defaultAttributes.getImageRepeat(); } @@ -727,8 +677,7 @@ public String getImageRepeat() * * @param repeat the repeat behavior or the background image. */ - public void setImageRepeat(String repeat) - { + public void setImageRepeat(String repeat) { this.imageRepeat = repeat; } @@ -738,8 +687,7 @@ public void setImageRepeat(String repeat) * * @return the path to the image used for background image. */ - public String getPath() - { + public String getPath() { Object imageSource = this.getImageSource(); return (imageSource instanceof String) ? (String) imageSource : null; } @@ -750,8 +698,7 @@ public String getPath() * * @return the minimum scale that can be applied to an annotation when it gets away from the eye */ - public double getDistanceMinScale() - { + public double getDistanceMinScale() { return this.distanceMinScale >= 0 ? this.distanceMinScale : defaultAttributes.getDistanceMinScale(); } @@ -761,8 +708,7 @@ public double getDistanceMinScale() * * @param scale the minimum scale that can be applied to an annotation when it gets away from the eye */ - public void setDistanceMinScale(double scale) - { + public void setDistanceMinScale(double scale) { this.distanceMinScale = scale; } @@ -772,8 +718,7 @@ public void setDistanceMinScale(double scale) * * @return the maximum scale that can be applied to an annotation when it gets closer to the eye */ - public double getDistanceMaxScale() - { + public double getDistanceMaxScale() { return this.distanceMaxScale >= 0 ? this.distanceMaxScale : defaultAttributes.getDistanceMaxScale(); } @@ -783,8 +728,7 @@ public double getDistanceMaxScale() * * @param scale the maximum scale that can be applied to an annotation when it gets closer to the eye */ - public void setDistanceMaxScale(double scale) - { + public void setDistanceMaxScale(double scale) { this.distanceMaxScale = scale; } @@ -793,8 +737,7 @@ public void setDistanceMaxScale(double scale) * * @return the minimum opacity an annotation can have when fading away from the eye. */ - public double getDistanceMinOpacity() - { + public double getDistanceMinOpacity() { return this.distanceMinOpacity >= 0 ? this.distanceMinOpacity : defaultAttributes.getDistanceMinOpacity(); } @@ -804,8 +747,7 @@ public double getDistanceMinOpacity() * * @param opacity the minimum opacity an annotation can have when fading away from the eye. */ - public void setDistanceMinOpacity(double opacity) - { + public void setDistanceMinOpacity(double opacity) { this.distanceMinOpacity = opacity; } @@ -815,8 +757,7 @@ public void setDistanceMinOpacity(double opacity) * * @return the effect used for text rendering */ - public String getEffect() - { + public String getEffect() { return this.effect != null ? this.effect : defaultAttributes.getEffect(); } @@ -827,8 +768,7 @@ public String getEffect() * * @param effect the effect to use for text rendering */ - public void setEffect(String effect) - { + public void setEffect(String effect) { this.effect = effect; } @@ -838,8 +778,7 @@ public void setEffect(String effect) * * @return true if there are unresolved fields, false if no fields remain unresolved. */ - public boolean isUnresolved() - { + public boolean isUnresolved() { return unresolved; } @@ -849,8 +788,7 @@ public boolean isUnresolved() * * @param unresolved true if there are unresolved fields, false if no fields remain unresolved. */ - public void setUnresolved(boolean unresolved) - { + public void setUnresolved(boolean unresolved) { this.unresolved = unresolved; } @@ -860,22 +798,21 @@ public void setUnresolved(boolean unresolved) * * @return XML state document string describing this AnnotationAttributes. */ - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport restorableSupport = RestorableSupport.newRestorableSupport(); // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (restorableSupport == null) + if (restorableSupport == null) { return null; + } // Save application set attributes to the document root. saveAttributes(this, restorableSupport, null); // We only save this AnnotationAttributes' defaultAttributes when the application has set them to // something other than the static member "defaults". - if (this.defaultAttributes != AnnotationAttributes.defaults) - { - RestorableSupport.StateObject defaultAttributesStateObj = - restorableSupport.addStateObject("defaultAttributes"); + if (this.defaultAttributes != AnnotationAttributes.defaults) { + RestorableSupport.StateObject defaultAttributesStateObj + = restorableSupport.addStateObject("defaultAttributes"); saveAttributes(this.defaultAttributes, restorableSupport, defaultAttributesStateObj); } @@ -891,24 +828,19 @@ public String getRestorableState() * @param stateInXml an XML document String describing an AnnotationAttributes. * * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not a well - * formed XML document String. + * formed XML document String. */ - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport restorableSupport; - try - { + try { restorableSupport = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -919,15 +851,15 @@ public void restoreState(String stateInXml) restoreAttributes(restorableSupport, null, this); // Restore application set default attributes from under the "defaultAttributes" state element. - RestorableSupport.StateObject defaultAttributesStateObj = - restorableSupport.getStateObject("defaultAttributes"); - if (defaultAttributesStateObj != null) - { + RestorableSupport.StateObject defaultAttributesStateObj + = restorableSupport.getStateObject("defaultAttributes"); + if (defaultAttributesStateObj != null) { AnnotationAttributes newDefaultAttributes = this.defaultAttributes; // We do not want to write to the static member "defaults". So if this AnnotationAttributes' does not // have it's own defaultAttributes instance, we create one for it - if (newDefaultAttributes == AnnotationAttributes.defaults) + if (newDefaultAttributes == AnnotationAttributes.defaults) { newDefaultAttributes = new AnnotationAttributes(); + } restoreAttributes(restorableSupport, defaultAttributesStateObj, newDefaultAttributes); setDefaults(newDefaultAttributes); } @@ -939,70 +871,72 @@ public void restoreState(String stateInXml) * If context is not null, attributes will be saved beneath it. Otherwise, they will be saved at the * document root. * - * @param source the AnnotationAttriubutes to save. + * @param source the AnnotationAttriubutes to save. * @param restorableSupport RestorableSupport to write attribute values to. - * @param context RestorableSupport.StateObject that attributes will be saved under, if not null. + * @param context RestorableSupport.StateObject that attributes will be saved under, if not null. * * @throws IllegalArgumentException If either source or restorableSupport is null. */ private static void saveAttributes(AnnotationAttributes source, - RestorableSupport restorableSupport, - RestorableSupport.StateObject context) - { - if (source == null || restorableSupport == null) + RestorableSupport restorableSupport, + RestorableSupport.StateObject context) { + if (source == null || restorableSupport == null) { throw new IllegalArgumentException(); + } - if (source.frameShape != null) + if (source.frameShape != null) { restorableSupport.addStateValueAsString(context, "frameShape", source.frameShape); + } restorableSupport.addStateValueAsBoolean(context, "highlighted", source.isHighlighted); - if (source.highlightScale >= 0) + if (source.highlightScale >= 0) { restorableSupport.addStateValueAsDouble(context, "highlightScale", source.highlightScale); + } - if (source.size != null) - { + if (source.size != null) { RestorableSupport.StateObject sizeStateObj = restorableSupport.addStateObject(context, "size"); - if (sizeStateObj != null) - { + if (sizeStateObj != null) { restorableSupport.addStateValueAsDouble(sizeStateObj, "width", source.size.getWidth()); restorableSupport.addStateValueAsDouble(sizeStateObj, "height", source.size.getHeight()); } } - if (source.scale >= 0) + if (source.scale >= 0) { restorableSupport.addStateValueAsDouble(context, "scale", source.scale); + } - if (source.opacity >= 0) + if (source.opacity >= 0) { restorableSupport.addStateValueAsDouble(context, "opacity", source.opacity); + } - if (source.leader != null) + if (source.leader != null) { restorableSupport.addStateValueAsString(context, "leader", source.leader); + } - if (source.leaderGapWidth >= 0) + if (source.leaderGapWidth >= 0) { restorableSupport.addStateValueAsInteger(context, "leaderGapWidth", source.leaderGapWidth); + } - if (source.cornerRadius >= 0) + if (source.cornerRadius >= 0) { restorableSupport.addStateValueAsInteger(context, "cornerRadius", source.cornerRadius); + } - if (source.adjustWidthToText != null) + if (source.adjustWidthToText != null) { restorableSupport.addStateValueAsString(context, "adjustWidthToText", source.adjustWidthToText); + } - if (source.drawOffset != null) - { + if (source.drawOffset != null) { RestorableSupport.StateObject drawOffsetStateObj = restorableSupport.addStateObject(context, "drawOffset"); - if (drawOffsetStateObj != null) - { + if (drawOffsetStateObj != null) { restorableSupport.addStateValueAsDouble(drawOffsetStateObj, "x", source.drawOffset.getX()); restorableSupport.addStateValueAsDouble(drawOffsetStateObj, "y", source.drawOffset.getY()); } } - if (source.insets != null) - { + if (source.insets != null) { RestorableSupport.StateObject insetsStateObj = restorableSupport.addStateObject(context, "insets"); - if (insetsStateObj != null) - { + if (insetsStateObj != null) { restorableSupport.addStateValueAsInteger(insetsStateObj, "top", source.insets.top); restorableSupport.addStateValueAsInteger(insetsStateObj, "left", source.insets.left); restorableSupport.addStateValueAsInteger(insetsStateObj, "bottom", source.insets.bottom); @@ -1010,94 +944,103 @@ private static void saveAttributes(AnnotationAttributes source, } } - if (source.borderWidth >= 0) + if (source.borderWidth >= 0) { restorableSupport.addStateValueAsDouble(context, "borderWidth", source.borderWidth); + } - if (source.borderStippleFactor >= 0) + if (source.borderStippleFactor >= 0) { restorableSupport.addStateValueAsInteger(context, "borderStippleFactor", source.borderStippleFactor); + } - if (source.borderStipplePattern != (short) 0x0000) + if (source.borderStipplePattern != (short) 0x0000) { restorableSupport.addStateValueAsInteger(context, "borderStipplePattern", source.borderStipplePattern); + } - if (source.antiAliasHint >= 0) + if (source.antiAliasHint >= 0) { restorableSupport.addStateValueAsInteger(context, "antiAliasHint", source.antiAliasHint); + } restorableSupport.addStateValueAsBoolean(context, "visible", source.isVisible); // Save the name, style, and size of the font. These will be used to restore the font using the // constructor: new Font(name, style, size). - if (source.font != null) - { + if (source.font != null) { RestorableSupport.StateObject fontStateObj = restorableSupport.addStateObject(context, "font"); - if (fontStateObj != null) - { + if (fontStateObj != null) { restorableSupport.addStateValueAsString(fontStateObj, "name", source.font.getName()); restorableSupport.addStateValueAsInteger(fontStateObj, "style", source.font.getStyle()); restorableSupport.addStateValueAsInteger(fontStateObj, "size", source.font.getSize()); } } - if (source.textAlign != null) + if (source.textAlign != null) { restorableSupport.addStateValueAsString(context, "textAlign", source.textAlign); + } - if (source.textColor != null) - { + if (source.textColor != null) { String encodedColor = RestorableSupport.encodeColor(source.textColor); - if (encodedColor != null) + if (encodedColor != null) { restorableSupport.addStateValueAsString(context, "textColor", encodedColor); + } } - if (source.backgroundColor != null) - { + if (source.backgroundColor != null) { String encodedColor = RestorableSupport.encodeColor(source.backgroundColor); - if (encodedColor != null) + if (encodedColor != null) { restorableSupport.addStateValueAsString(context, "backgroundColor", encodedColor); + } } - if (source.borderColor != null) - { + if (source.borderColor != null) { String encodedColor = RestorableSupport.encodeColor(source.borderColor); - if (encodedColor != null) + if (encodedColor != null) { restorableSupport.addStateValueAsString(context, "borderColor", encodedColor); + } } // Save the imagePath property only when the imageSource property is a simple String path. If the imageSource // property is a BufferedImage (or some other object), we make no effort to save that state. We save under // the name "imagePath" to denote that it is a special case of "imageSource". - if (source.getPath() != null) + if (source.getPath() != null) { restorableSupport.addStateValueAsString(context, "imagePath", source.getPath(), true); + } - if (source.imageScale >= 0) + if (source.imageScale >= 0) { restorableSupport.addStateValueAsDouble(context, "imageScale", source.imageScale); + } - if (source.imageOffset != null) - { - RestorableSupport.StateObject imageOffsetStateObj = - restorableSupport.addStateObject(context, "imageOffset"); - if (imageOffsetStateObj != null) - { + if (source.imageOffset != null) { + RestorableSupport.StateObject imageOffsetStateObj + = restorableSupport.addStateObject(context, "imageOffset"); + if (imageOffsetStateObj != null) { restorableSupport.addStateValueAsDouble(imageOffsetStateObj, "x", source.imageOffset.getX()); restorableSupport.addStateValueAsDouble(imageOffsetStateObj, "y", source.imageOffset.getY()); } } - if (source.imageOpacity >= 0) + if (source.imageOpacity >= 0) { restorableSupport.addStateValueAsDouble(context, "imageOpacity", source.imageOpacity); + } - if (source.imageRepeat != null) + if (source.imageRepeat != null) { restorableSupport.addStateValueAsString(context, "imageRepeat", source.imageRepeat); + } - if (source.distanceMinScale >= 0) + if (source.distanceMinScale >= 0) { restorableSupport.addStateValueAsDouble(context, "distanceMinScale", source.distanceMinScale); + } - if (source.distanceMaxScale >= 0) + if (source.distanceMaxScale >= 0) { restorableSupport.addStateValueAsDouble(context, "distanceMaxScale", source.distanceMaxScale); + } - if (source.distanceMinOpacity >= 0) + if (source.distanceMinOpacity >= 0) { restorableSupport.addStateValueAsDouble(context, "distanceMinOpacity", source.distanceMinOpacity); + } - if (source.effect != null) + if (source.effect != null) { restorableSupport.addStateValueAsString(context, "effect", source.effect); + } } /** @@ -1106,15 +1049,14 @@ private static void saveAttributes(AnnotationAttributes source, * document root. * * @param restorableSupport RestorableSupport to read attribute values from. - * @param context RestorableSupport.StateObject under which attributes will be looked, if not null. - * @param dest the AnnotationAttributes to restore. + * @param context RestorableSupport.StateObject under which attributes will be looked, if not null. + * @param dest the AnnotationAttributes to restore. * * @throws IllegalArgumentException If either restorableSupport or dest is null. */ private static void restoreAttributes(RestorableSupport restorableSupport, - RestorableSupport.StateObject context, - AnnotationAttributes dest) - { + RestorableSupport.StateObject context, + AnnotationAttributes dest) { // Map legacy versions of the Annotation constants and FrameFactory constants to the new AVKey constants. Map legacySupport = new HashMap(); legacySupport.put("render.Annotation.RepeatNone", AVKey.REPEAT_NONE); @@ -1129,73 +1071,80 @@ private static void restoreAttributes(RestorableSupport restorableSupport, legacySupport.put("Render.FrameFactory.LeaderTriangle", AVKey.SHAPE_TRIANGLE); legacySupport.put("Render.FrameFactory.LeaderNone", AVKey.SHAPE_NONE); - if (restorableSupport == null || dest == null) + if (restorableSupport == null || dest == null) { throw new IllegalArgumentException(); + } String frameShapeState = restorableSupport.getStateValueAsString(context, "frameShape"); - if (frameShapeState != null) - { + if (frameShapeState != null) { // Map legacy versions using FrameFactory frame shape constants to the new AVKey constants. String updatedValue = legacySupport.get(frameShapeState); - if (updatedValue != null) + if (updatedValue != null) { frameShapeState = updatedValue; + } dest.setFrameShape(frameShapeState); } Boolean highlightedState = restorableSupport.getStateValueAsBoolean(context, "highlighted"); - if (highlightedState != null) + if (highlightedState != null) { dest.setHighlighted(highlightedState); + } Double highlightScaleState = restorableSupport.getStateValueAsDouble(context, "highlightScale"); - if (highlightScaleState != null) + if (highlightScaleState != null) { dest.setHighlightScale(highlightScaleState); + } // Restore the size property only if all parts are available. // We will not restore a partial size (for example, just the width). RestorableSupport.StateObject sizeStateObj = restorableSupport.getStateObject(context, "size"); - if (sizeStateObj != null) - { + if (sizeStateObj != null) { Double widthState = restorableSupport.getStateValueAsDouble(sizeStateObj, "width"); Double heightState = restorableSupport.getStateValueAsDouble(sizeStateObj, "height"); - if (widthState != null && heightState != null) + if (widthState != null && heightState != null) { dest.setSize(new Dimension(widthState.intValue(), heightState.intValue())); + } } Double scaleState = restorableSupport.getStateValueAsDouble(context, "scale"); - if (scaleState != null) + if (scaleState != null) { dest.setScale(scaleState); + } Double opacityState = restorableSupport.getStateValueAsDouble(context, "opacity"); - if (opacityState != null) + if (opacityState != null) { dest.setOpacity(opacityState); + } String leaderState = restorableSupport.getStateValueAsString(context, "leader"); - if (leaderState != null) - { + if (leaderState != null) { // Map legacy versions using FrameFactory leader shape constants to the new AVKey constants. String updatedValue = legacySupport.get(leaderState); - if (updatedValue != null) + if (updatedValue != null) { leaderState = updatedValue; + } dest.setLeader(leaderState); } Integer leaderGapWidthState = restorableSupport.getStateValueAsInteger(context, "leaderGapWidth"); - if (leaderGapWidthState != null) + if (leaderGapWidthState != null) { dest.setLeaderGapWidth(leaderGapWidthState); + } Integer cornerRadiusState = restorableSupport.getStateValueAsInteger(context, "cornerRadius"); - if (cornerRadiusState != null) + if (cornerRadiusState != null) { dest.setCornerRadius(cornerRadiusState); + } String adjustWidthToTextState = restorableSupport.getStateValueAsString(context, "adjustWidthToText"); - if (adjustWidthToTextState != null) - { + if (adjustWidthToTextState != null) { // Map legacy versions using Annotation size constants to the new AVKey constants. String updatedValue = legacySupport.get(adjustWidthToTextState); - if (updatedValue != null) + if (updatedValue != null) { adjustWidthToTextState = updatedValue; + } dest.setAdjustWidthToText(adjustWidthToTextState); } @@ -1203,153 +1152,161 @@ private static void restoreAttributes(RestorableSupport restorableSupport, // Restore the drawOffset property only if all parts are available. // We will not restore a partial drawOffset (for example, just the x value). RestorableSupport.StateObject drawOffsetStateObj = restorableSupport.getStateObject(context, "drawOffset"); - if (drawOffsetStateObj != null) - { + if (drawOffsetStateObj != null) { Double xState = restorableSupport.getStateValueAsDouble(drawOffsetStateObj, "x"); Double yState = restorableSupport.getStateValueAsDouble(drawOffsetStateObj, "y"); - if (xState != null && yState != null) + if (xState != null && yState != null) { dest.setDrawOffset(new Point(xState.intValue(), yState.intValue())); + } } // Restore the insets property only if all parts are available. // We will not restore a partial insets (for example, just the top value). RestorableSupport.StateObject insetsStateObj = restorableSupport.getStateObject(context, "insets"); - if (insetsStateObj != null) - { + if (insetsStateObj != null) { Integer topState = restorableSupport.getStateValueAsInteger(insetsStateObj, "top"); Integer leftState = restorableSupport.getStateValueAsInteger(insetsStateObj, "left"); Integer bottomState = restorableSupport.getStateValueAsInteger(insetsStateObj, "bottom"); Integer rightState = restorableSupport.getStateValueAsInteger(insetsStateObj, "right"); - if (topState != null && leftState != null && bottomState != null && rightState != null) + if (topState != null && leftState != null && bottomState != null && rightState != null) { dest.setInsets(new Insets(topState, leftState, bottomState, rightState)); + } } Double borderWidthState = restorableSupport.getStateValueAsDouble(context, "borderWidth"); - if (borderWidthState != null) + if (borderWidthState != null) { dest.setBorderWidth(borderWidthState); + } Integer borderStippleFactorState = restorableSupport.getStateValueAsInteger(context, "borderStippleFactor"); - if (borderStippleFactorState != null) + if (borderStippleFactorState != null) { dest.setBorderStippleFactor(borderStippleFactorState); + } Integer borderStipplePatternState = restorableSupport.getStateValueAsInteger(context, "borderStipplePattern"); - if (borderStipplePatternState != null) + if (borderStipplePatternState != null) { dest.setBorderStipplePattern(borderStipplePatternState.shortValue()); + } Integer antiAliasHintState = restorableSupport.getStateValueAsInteger(context, "antiAliasHint"); - if (antiAliasHintState != null) + if (antiAliasHintState != null) { dest.setAntiAliasHint(antiAliasHintState); + } Boolean visibleState = restorableSupport.getStateValueAsBoolean(context, "visible"); - if (visibleState != null) + if (visibleState != null) { dest.setVisible(visibleState); + } // Restore the font property only if all parts are available. // We will not restore a partial font (for example, just the size). RestorableSupport.StateObject fontStateObj = restorableSupport.getStateObject(context, "font"); - if (fontStateObj != null) - { + if (fontStateObj != null) { // The "font name" of toolTipFont. String nameState = restorableSupport.getStateValueAsString(fontStateObj, "name"); // The style attributes. Integer styleState = restorableSupport.getStateValueAsInteger(fontStateObj, "style"); // The simple font size. Integer sizeState = restorableSupport.getStateValueAsInteger(fontStateObj, "size"); - if (nameState != null && styleState != null && sizeState != null) + if (nameState != null && styleState != null && sizeState != null) { dest.setFont(new Font(nameState, styleState, sizeState)); + } } String textAlignState = restorableSupport.getStateValueAsString(context, "textAlign"); - if (textAlignState != null) - { + if (textAlignState != null) { // Attempt to convert the textAlign string to an integer to handle legacy textAlign restorable state. // WWUtil.makeInteger returns null without logging a message if the string cannot be converted to an int. Integer textAlignInt = WWUtil.makeInteger(textAlignState); - if (textAlignInt != null) - { + if (textAlignInt != null) { dest.setTextAlign(textAlignInt == 0 ? AVKey.LEFT : (textAlignInt == 1 ? AVKey.CENTER : AVKey.RIGHT)); - } - else - { + } else { dest.setTextAlign(textAlignState); } } String textColorState = restorableSupport.getStateValueAsString(context, "textColor"); - if (textColorState != null) - { + if (textColorState != null) { Color color = RestorableSupport.decodeColor(textColorState); - if (color != null) + if (color != null) { dest.setTextColor(color); + } } String backgroundColorState = restorableSupport.getStateValueAsString(context, "backgroundColor"); - if (backgroundColorState != null) - { + if (backgroundColorState != null) { Color color = RestorableSupport.decodeColor(backgroundColorState); - if (color != null) + if (color != null) { dest.setBackgroundColor(color); + } } String borderColorState = restorableSupport.getStateValueAsString(context, "borderColor"); - if (borderColorState != null) - { + if (borderColorState != null) { Color color = RestorableSupport.decodeColor(borderColorState); - if (color != null) + if (color != null) { dest.setBorderColor(color); + } } // The imagePath property should exist only if the imageSource property was a simple String path. // If the imageSource property was a BufferedImage (or some other object), it should not exist in the // state document. We save under the name "imagePath" to denote that it is a special case of "imageSource". String imagePathState = restorableSupport.getStateValueAsString(context, "imagePath"); - if (imagePathState != null) + if (imagePathState != null) { dest.setImageSource(imagePathState); + } Double imageScaleState = restorableSupport.getStateValueAsDouble(context, "imageScale"); - if (imageScaleState != null) + if (imageScaleState != null) { dest.setImageScale(imageScaleState); + } // Restore the imageOffset property only if all parts are available. // We will not restore a partial imageOffset (for example, just the x value). RestorableSupport.StateObject imageOffsetStateObj = restorableSupport.getStateObject(context, "imageOffset"); - if (imageOffsetStateObj != null) - { + if (imageOffsetStateObj != null) { Double xState = restorableSupport.getStateValueAsDouble(imageOffsetStateObj, "x"); Double yState = restorableSupport.getStateValueAsDouble(imageOffsetStateObj, "y"); - if (xState != null && yState != null) + if (xState != null && yState != null) { dest.setImageOffset(new Point(xState.intValue(), yState.intValue())); + } } Double imageOpacityState = restorableSupport.getStateValueAsDouble(context, "imageOpacity"); - if (imageOpacityState != null) + if (imageOpacityState != null) { dest.setImageOpacity(imageOpacityState); + } String imageRepeatState = restorableSupport.getStateValueAsString(context, "imageRepeat"); - if (imageRepeatState != null) - { + if (imageRepeatState != null) { // Map legacy versions using Annotation repeat constants to the new AVKey constants. String updatedValue = legacySupport.get(imageRepeatState); - if (updatedValue != null) + if (updatedValue != null) { imageRepeatState = updatedValue; + } dest.setImageRepeat(imageRepeatState); } Double distanceMinScaleState = restorableSupport.getStateValueAsDouble(context, "distanceMinScale"); - if (distanceMinScaleState != null) + if (distanceMinScaleState != null) { dest.setDistanceMinScale(distanceMinScaleState); + } Double distanceMaxScaleState = restorableSupport.getStateValueAsDouble(context, "distanceMaxScale"); - if (distanceMaxScaleState != null) + if (distanceMaxScaleState != null) { dest.setDistanceMaxScale(distanceMaxScaleState); + } Double distanceMinOpacityState = restorableSupport.getStateValueAsDouble(context, "distanceMinOpacity"); - if (distanceMinOpacityState != null) + if (distanceMinOpacityState != null) { dest.setDistanceMinOpacity(distanceMinOpacityState); + } String effectState = restorableSupport.getStateValueAsString(context, "effect"); - if (effectState != null) + if (effectState != null) { dest.setEffect(effectState); + } } } diff --git a/src/gov/nasa/worldwind/render/AnnotationFlowLayout.java b/src/gov/nasa/worldwind/render/AnnotationFlowLayout.java index 8f28b51f8a..1bc84887b9 100644 --- a/src/gov/nasa/worldwind/render/AnnotationFlowLayout.java +++ b/src/gov/nasa/worldwind/render/AnnotationFlowLayout.java @@ -15,17 +15,15 @@ * @author dcollins * @version $Id: AnnotationFlowLayout.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AnnotationFlowLayout extends AbstractAnnotationLayout -{ +public class AnnotationFlowLayout extends AbstractAnnotationLayout { + private String orientation; private String alignment; private int hgap; private int vgap; - public AnnotationFlowLayout(String orientation, String alignment, int hgap, int vgap) - { - if (orientation == null) - { + public AnnotationFlowLayout(String orientation, String alignment, int hgap, int vgap) { + if (orientation == null) { String message = Logging.getMessage("nullValue.AlignmentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -33,59 +31,47 @@ public AnnotationFlowLayout(String orientation, String alignment, int hgap, int // A null alignment is permitted. This tells the layout to choose the default alignment for the current // orientation. - this.orientation = orientation; this.alignment = alignment; this.hgap = hgap; this.vgap = vgap; } - public AnnotationFlowLayout(String orientation, int hgap, int vgap) - { + public AnnotationFlowLayout(String orientation, int hgap, int vgap) { this(orientation, null, hgap, vgap); } @SuppressWarnings({"StringEquality"}) - protected static String getDefaultAlignment(String orientation) - { - if (orientation == null) - { + protected static String getDefaultAlignment(String orientation) { + if (orientation == null) { String message = Logging.getMessage("nullValue.OrientationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (orientation == AVKey.HORIZONTAL) - { + if (orientation == AVKey.HORIZONTAL) { return AVKey.BOTTOM; - } - else if (orientation == AVKey.VERTICAL) - { + } else if (orientation == AVKey.VERTICAL) { return AVKey.LEFT; } return null; } - public AnnotationFlowLayout(String orientation) - { + public AnnotationFlowLayout(String orientation) { this(orientation, 0, 0); } - public AnnotationFlowLayout() - { + public AnnotationFlowLayout() { this(AVKey.HORIZONTAL); } - public String getOrientation() - { + public String getOrientation() { return this.orientation; } - public void setOrientation(String orientation) - { - if (orientation == null) - { + public void setOrientation(String orientation) { + if (orientation == null) { String message = Logging.getMessage("nullValue.OrientationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -94,61 +80,49 @@ public void setOrientation(String orientation) this.orientation = orientation; } - public String getAlignment() - { + public String getAlignment() { return this.alignment; } - public void setAlignment(String alignment) - { + public void setAlignment(String alignment) { // A null alignment is permitted. This tells the layout to choose the default alignment for the current // orientation. this.alignment = alignment; } - public int getHorizontalGap() - { + public int getHorizontalGap() { return this.hgap; } - public void setHorizontalGap(int hgap) - { + public void setHorizontalGap(int hgap) { this.hgap = hgap; } - public int getVerticalGap() - { + public int getVerticalGap() { return this.vgap; } - public void setVerticalGap(int vgap) - { + public void setVerticalGap(int vgap) { this.vgap = vgap; } @SuppressWarnings({"StringEquality"}) - public java.awt.Dimension getPreferredSize(DrawContext dc, Iterable annotations) - { - if (dc == null) - { + public java.awt.Dimension getPreferredSize(DrawContext dc, Iterable annotations) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (annotations == null) - { + if (annotations == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.orientation == AVKey.HORIZONTAL) - { + if (this.orientation == AVKey.HORIZONTAL) { return this.horizontalPreferredSize(dc, annotations); - } - else if (this.orientation == AVKey.VERTICAL) - { + } else if (this.orientation == AVKey.VERTICAL) { return this.verticalPerferredSize(dc, annotations); } @@ -157,51 +131,41 @@ else if (this.orientation == AVKey.VERTICAL) @SuppressWarnings({"StringEquality"}) public void drawAnnotations(DrawContext dc, java.awt.Rectangle bounds, - Iterable annotations, double opacity, Position pickPosition) - { - if (dc == null) - { + Iterable annotations, double opacity, Position pickPosition) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bounds == null) - { + if (bounds == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (annotations == null) - { + if (annotations == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.orientation == AVKey.HORIZONTAL) - { + if (this.orientation == AVKey.HORIZONTAL) { this.drawHorizontal(dc, bounds, annotations, opacity, pickPosition); - } - else if (this.orientation == AVKey.VERTICAL) - { + } else if (this.orientation == AVKey.VERTICAL) { this.drawVertical(dc, bounds, annotations, opacity, pickPosition); } } @SuppressWarnings({"StringEquality"}) - public void beginDrawAnnotations(DrawContext dc, java.awt.Rectangle bounds) - { - if (dc == null) - { + public void beginDrawAnnotations(DrawContext dc, java.awt.Rectangle bounds) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bounds == null) - { + if (bounds == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -209,66 +173,63 @@ public void beginDrawAnnotations(DrawContext dc, java.awt.Rectangle bounds) super.beginDrawAnnotations(dc, bounds); - if (this.orientation == AVKey.HORIZONTAL) - { + if (this.orientation == AVKey.HORIZONTAL) { this.beginHorizontal(dc, bounds); - } - else if (this.orientation == AVKey.VERTICAL) - { + } else if (this.orientation == AVKey.VERTICAL) { this.beginVertical(dc, bounds); } } - protected java.awt.Dimension horizontalPreferredSize(DrawContext dc, Iterable annotations) - { + protected java.awt.Dimension horizontalPreferredSize(DrawContext dc, Iterable annotations) { int preferredWidth = 0; int preferredHeight = 0; java.util.Iterator iter = annotations.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return new java.awt.Dimension(preferredWidth, preferredHeight); + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Annotation annotation = iter.next(); java.awt.Dimension size = this.getAnnotationSize(dc, annotation); - if (size != null) - { + if (size != null) { preferredWidth += size.width; - if (preferredHeight < size.height) + if (preferredHeight < size.height) { preferredHeight = size.height; + } - if (iter.hasNext()) + if (iter.hasNext()) { preferredWidth += this.hgap; + } } } return new java.awt.Dimension(preferredWidth, preferredHeight); } - protected java.awt.Dimension verticalPerferredSize(DrawContext dc, Iterable annotations) - { + protected java.awt.Dimension verticalPerferredSize(DrawContext dc, Iterable annotations) { int preferredWidth = 0; int preferredHeight = 0; java.util.Iterator iter = annotations.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return new java.awt.Dimension(preferredWidth, preferredHeight); + } - while (iter.hasNext()) - { + while (iter.hasNext()) { Annotation annotation = iter.next(); java.awt.Dimension size = this.getAnnotationSize(dc, annotation); - if (size != null) - { + if (size != null) { preferredHeight += size.height; - if (preferredWidth < size.width) + if (preferredWidth < size.width) { preferredWidth = size.width; + } - if (iter.hasNext()) + if (iter.hasNext()) { preferredHeight += this.vgap; + } } } @@ -276,19 +237,16 @@ protected java.awt.Dimension verticalPerferredSize(DrawContext dc, Iterable annotations, double opacity, Position pickPosition) - { + Iterable annotations, double opacity, Position pickPosition) { String align = this.getAlignment(); - if (align == null) - { + if (align == null) { align = getDefaultAlignment(AVKey.HORIZONTAL); } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler stackHandler = new OGLStackHandler(); - for (Annotation annotation : annotations) - { + for (Annotation annotation : annotations) { java.awt.Dimension size = annotation.getPreferredSize(dc); stackHandler.pushModelview(gl); @@ -302,19 +260,16 @@ protected void drawHorizontal(DrawContext dc, java.awt.Rectangle bounds, } protected void drawVertical(DrawContext dc, java.awt.Rectangle bounds, - Iterable annotations, double opacity, Position pickPosition) - { + Iterable annotations, double opacity, Position pickPosition) { String align = this.getAlignment(); - if (align == null) - { + if (align == null) { align = getDefaultAlignment(AVKey.VERTICAL); } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler stackHandler = new OGLStackHandler(); - for (Annotation annotation : annotations) - { + for (Annotation annotation : annotations) { java.awt.Dimension size = annotation.getPreferredSize(dc); gl.glTranslated(0, -size.height, 0); @@ -328,55 +283,42 @@ protected void drawVertical(DrawContext dc, java.awt.Rectangle bounds, } @SuppressWarnings({"StringEquality"}) - protected void alignHorizontal(DrawContext dc, java.awt.Rectangle bounds, java.awt.Dimension size, String align) - { + protected void alignHorizontal(DrawContext dc, java.awt.Rectangle bounds, java.awt.Dimension size, String align) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (align == AVKey.BOTTOM) - { + if (align == AVKey.BOTTOM) { // This is the default. - } - else if (align == AVKey.TOP) - { + } else if (align == AVKey.TOP) { int dy = bounds.height - size.height; gl.glTranslated(0, dy, 0); - } - else if (align == AVKey.CENTER) - { + } else if (align == AVKey.CENTER) { int dy = (bounds.height / 2) - (size.height / 2); gl.glTranslated(0, dy, 0); } } @SuppressWarnings({"StringEquality"}) - protected void alignVertical(DrawContext dc, java.awt.Rectangle bounds, java.awt.Dimension size, String align) - { + protected void alignVertical(DrawContext dc, java.awt.Rectangle bounds, java.awt.Dimension size, String align) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (align == AVKey.LEFT) - { + if (align == AVKey.LEFT) { // This is the default. } - if (align == AVKey.RIGHT) - { + if (align == AVKey.RIGHT) { int dx = bounds.width - size.width; gl.glTranslated(dx, 0, 0); - } - else if (align == AVKey.CENTER) - { + } else if (align == AVKey.CENTER) { int dx = (bounds.width / 2) - (size.width / 2); gl.glTranslated(dx, 0, 0); } } - protected void beginHorizontal(DrawContext dc, java.awt.Rectangle bounds) - { + protected void beginHorizontal(DrawContext dc, java.awt.Rectangle bounds) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glTranslated(bounds.getMinX(), bounds.getMinY(), 0); } - protected void beginVertical(DrawContext dc, java.awt.Rectangle bounds) - { + protected void beginVertical(DrawContext dc, java.awt.Rectangle bounds) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glTranslated(bounds.getMinX(), bounds.getMaxY(), 0); } diff --git a/src/gov/nasa/worldwind/render/AnnotationLayoutManager.java b/src/gov/nasa/worldwind/render/AnnotationLayoutManager.java index e6513e18d5..6b8b0c51f3 100644 --- a/src/gov/nasa/worldwind/render/AnnotationLayoutManager.java +++ b/src/gov/nasa/worldwind/render/AnnotationLayoutManager.java @@ -12,8 +12,7 @@ * @author dcollins * @version $Id: AnnotationLayoutManager.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AnnotationLayoutManager -{ +public interface AnnotationLayoutManager { // TODO: Create javadocus, including pictures, illustrating how annotation layouts work PickSupport getPickSupport(); @@ -23,7 +22,7 @@ public interface AnnotationLayoutManager java.awt.Dimension getPreferredSize(DrawContext dc, Iterable annotations); void drawAnnotations(DrawContext dc, java.awt.Rectangle bounds, - Iterable annotations, double opacity, Position pickPosition); + Iterable annotations, double opacity, Position pickPosition); void beginDrawAnnotations(DrawContext dc, java.awt.Rectangle bounds); diff --git a/src/gov/nasa/worldwind/render/AnnotationNullLayout.java b/src/gov/nasa/worldwind/render/AnnotationNullLayout.java index 5834aa961d..17871864de 100644 --- a/src/gov/nasa/worldwind/render/AnnotationNullLayout.java +++ b/src/gov/nasa/worldwind/render/AnnotationNullLayout.java @@ -15,19 +15,16 @@ * @author dcollins * @version $Id: AnnotationNullLayout.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AnnotationNullLayout extends AbstractAnnotationLayout -{ +public class AnnotationNullLayout extends AbstractAnnotationLayout { + protected java.util.Map constraintMap; - public AnnotationNullLayout() - { + public AnnotationNullLayout() { this.constraintMap = new java.util.HashMap(); } - public Object getConstraint(Annotation annotation) - { - if (annotation == null) - { + public Object getConstraint(Annotation annotation) { + if (annotation == null) { String message = Logging.getMessage("nullValue.AnnotationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -36,10 +33,8 @@ public Object getConstraint(Annotation annotation) return this.constraintMap.get(annotation); } - public void setConstraint(Annotation annotation, Object constraint) - { - if (annotation == null) - { + public void setConstraint(Annotation annotation, Object constraint) { + if (annotation == null) { String message = Logging.getMessage("nullValue.AnnotationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -48,17 +43,14 @@ public void setConstraint(Annotation annotation, Object constraint) this.constraintMap.put(annotation, constraint); } - public java.awt.Dimension getPreferredSize(DrawContext dc, Iterable annotations) - { - if (dc == null) - { + public java.awt.Dimension getPreferredSize(DrawContext dc, Iterable annotations) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (annotations == null) - { + if (annotations == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -67,11 +59,9 @@ public java.awt.Dimension getPreferredSize(DrawContext dc, Iterable annotations, double opacity, Position pickPosition) - { - if (dc == null) - { + Iterable annotations, double opacity, Position pickPosition) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bounds == null) - { + if (bounds == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (annotations == null) - { + if (annotations == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -106,8 +92,7 @@ public void drawAnnotations(DrawContext dc, java.awt.Rectangle bounds, GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler stackHandler = new OGLStackHandler(); - for (Annotation annotation : annotations) - { + for (Annotation annotation : annotations) { java.awt.Rectangle annotationBounds = this.getAnnotationBounds(dc, annotation); annotationBounds = this.adjustAnnotationBounds(dc, bounds, annotation, annotationBounds); @@ -121,65 +106,49 @@ public void drawAnnotations(DrawContext dc, java.awt.Rectangle bounds, } } - protected java.awt.Rectangle getAnnotationBounds(DrawContext dc, Annotation annotation) - { + protected java.awt.Rectangle getAnnotationBounds(DrawContext dc, Annotation annotation) { java.awt.Dimension size = this.getAnnotationSize(dc, annotation); - if (size == null) + if (size == null) { return null; + } java.awt.Point offset = annotation.getAttributes().getDrawOffset(); - if (offset == null) + if (offset == null) { offset = new java.awt.Point(); + } return new java.awt.Rectangle(offset, size); } @SuppressWarnings({"UnusedDeclaration"}) protected java.awt.Rectangle adjustAnnotationBounds(DrawContext dc, java.awt.Rectangle parentBounds, - Annotation annotation, java.awt.Rectangle bounds) - { + Annotation annotation, java.awt.Rectangle bounds) { int x = bounds.x; int y = bounds.y; Object constraint = this.getConstraint(annotation); - if (constraint == AVKey.WEST) - { + if (constraint == AVKey.WEST) { y += parentBounds.height / 2 - bounds.height / 2; - } - else if (constraint == AVKey.NORTHWEST) - { + } else if (constraint == AVKey.NORTHWEST) { y += parentBounds.height - bounds.height; - } - else if (constraint == AVKey.NORTH) - { + } else if (constraint == AVKey.NORTH) { x += parentBounds.width / 2 - bounds.width / 2; y += parentBounds.height - bounds.height; - } - else if (constraint == AVKey.NORTHEAST) - { + } else if (constraint == AVKey.NORTHEAST) { x += parentBounds.width - bounds.width; y += parentBounds.height - bounds.height; - } - else if (constraint == AVKey.EAST) - { + } else if (constraint == AVKey.EAST) { x += parentBounds.width - bounds.width; y += parentBounds.height / 2 - bounds.height / 2; - } - else if (constraint == AVKey.SOUTHEAST) - { + } else if (constraint == AVKey.SOUTHEAST) { x += parentBounds.width - bounds.width; - } - else if (constraint == AVKey.SOUTH) - { + } else if (constraint == AVKey.SOUTH) { x += parentBounds.width / 2 - bounds.width / 2; - } - else if (constraint == AVKey.CENTER) - { + } else if (constraint == AVKey.CENTER) { x += parentBounds.width / 2 - bounds.width / 2; y += parentBounds.height / 2 - bounds.height / 2; - } - else // Default to anchoring in the south west corner. + } else // Default to anchoring in the south west corner. { } diff --git a/src/gov/nasa/worldwind/render/AnnotationRenderer.java b/src/gov/nasa/worldwind/render/AnnotationRenderer.java index 08dc94f838..f7ed9968aa 100644 --- a/src/gov/nasa/worldwind/render/AnnotationRenderer.java +++ b/src/gov/nasa/worldwind/render/AnnotationRenderer.java @@ -14,8 +14,8 @@ * @author Patrick Murris * @version $Id: AnnotationRenderer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AnnotationRenderer -{ +public interface AnnotationRenderer { + void pick(DrawContext dc, Iterable annotations, Point pickPoint, Layer annotationLayer); void pick(DrawContext dc, Annotation annotation, Vec4 annotationPoint, Point pickPoint, Layer annotationLayer); diff --git a/src/gov/nasa/worldwind/render/Attributable.java b/src/gov/nasa/worldwind/render/Attributable.java index 3b69927122..6e41de3f10 100644 --- a/src/gov/nasa/worldwind/render/Attributable.java +++ b/src/gov/nasa/worldwind/render/Attributable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; /** @@ -12,8 +11,8 @@ * @author tag * @version $Id: Attributable.java 2339 2014-09-22 18:22:37Z tgaskins $ */ -public interface Attributable -{ +public interface Attributable { + /** * Set the shape's attributes. * diff --git a/src/gov/nasa/worldwind/render/Balloon.java b/src/gov/nasa/worldwind/render/Balloon.java index 7f4db5b0a9..d7cee18db5 100644 --- a/src/gov/nasa/worldwind/render/Balloon.java +++ b/src/gov/nasa/worldwind/render/Balloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.avlist.AVList; @@ -16,8 +15,8 @@ * @version $Id: Balloon.java 1171 2013-02-11 21:45:02Z dcollins $ * @see BalloonAttributes */ -public interface Balloon extends Renderable, Highlightable, AVList -{ +public interface Balloon extends Renderable, Highlightable, AVList { + /** * Is the balloon always on top? * @@ -110,14 +109,13 @@ public interface Balloon extends Renderable, Highlightable, AVList * object returned during picking. If null, the balloon itself is the pickable object returned during picking. * * @return the object used as the pickable object returned during picking, or null to indicate the the balloon is - * returned during picking. + * returned during picking. */ Object getDelegateOwner(); /** - * Specifies the delegate owner of the balloon. If non-null, the delegate owner replaces the balloon as the - * pickable object returned during picking. If null, the balloon itself is the pickable object returned during - * picking. + * Specifies the delegate owner of the balloon. If non-null, the delegate owner replaces the balloon as the pickable + * object returned during picking. If null, the balloon itself is the pickable object returned during picking. * * @param owner the object to use as the pickable object returned during picking, or null to return the balloon. */ diff --git a/src/gov/nasa/worldwind/render/BalloonAttributes.java b/src/gov/nasa/worldwind/render/BalloonAttributes.java index 0bc0c9de36..ed1ec771f2 100644 --- a/src/gov/nasa/worldwind/render/BalloonAttributes.java +++ b/src/gov/nasa/worldwind/render/BalloonAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import java.awt.*; @@ -18,8 +17,8 @@ * @version $Id: BalloonAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ * @see Balloon */ -public interface BalloonAttributes extends ShapeAttributes -{ +public interface BalloonAttributes extends ShapeAttributes { + /** * Indicates the width and height of the balloon's shape in the viewport. If the balloon's shape is * AVKey.SHAPE_RECTANGLE, then the returned Size indicates the rectangle's width and @@ -56,7 +55,7 @@ public interface BalloonAttributes extends ShapeAttributes * size. * * @return the maximum width and height of the balloon's shape in the viewport, or null if the balloon - * has no maximum size. + * has no maximum size. */ Size getMaximumSize(); @@ -67,7 +66,7 @@ public interface BalloonAttributes extends ShapeAttributes * x- and y-radii. Specifying a null size causes the balloon to have no maximum size. * * @param size the desired maximum width and height of the balloon's shape in the viewport, or null if - * the balloon should have no maximum size. + * the balloon should have no maximum size. */ void setMaximumSize(Size size); @@ -159,7 +158,7 @@ public interface BalloonAttributes extends ShapeAttributes * radius attribute is ignored. * * @param shape the frame shape to use, either AVKey.SHAPE_NONE AVKey.SHAPE_RECTANGLE or - * AVKey.SHAPE_ELLIPSE. + * AVKey.SHAPE_ELLIPSE. * * @throws IllegalArgumentException if shape is null. * @see #getBalloonShape() @@ -353,7 +352,7 @@ public interface BalloonAttributes extends ShapeAttributes * the X and Y axes, respectively. The texture is repeated after its offset and scale are applied. * * @param repeat the texture's repeat mode to use, one of AVKey.REPEAT_NONE, - * AVKey.REPEAT_X, AVKey.REPEAT_Y, or AVKey.REPEAT_XY. + * AVKey.REPEAT_X, AVKey.REPEAT_Y, or AVKey.REPEAT_XY. * * @throws IllegalArgumentException if repeat is null. * @see #getImageRepeat() diff --git a/src/gov/nasa/worldwind/render/BasicAnnotationRenderer.java b/src/gov/nasa/worldwind/render/BasicAnnotationRenderer.java index 7f0b9a743a..451fd5ccff 100644 --- a/src/gov/nasa/worldwind/render/BasicAnnotationRenderer.java +++ b/src/gov/nasa/worldwind/render/BasicAnnotationRenderer.java @@ -27,77 +27,74 @@ * @see AnnotationAttributes * @see AnnotationLayer */ -public class BasicAnnotationRenderer implements AnnotationRenderer -{ +public class BasicAnnotationRenderer implements AnnotationRenderer { + protected PickSupport pickSupport = new PickSupport(); protected long currentFrameTime; protected HashSet currentPickAnnotations = new HashSet(); protected HashSet currentDrawAnnotations = new HashSet(); - protected static boolean isAnnotationValid(Annotation annotation, boolean checkPosition) - { - if (annotation == null || annotation.getText() == null) + protected static boolean isAnnotationValid(Annotation annotation, boolean checkPosition) { + if (annotation == null || annotation.getText() == null) { return false; + } //noinspection RedundantIfStatement,SimplifiableIfStatement - if (checkPosition && annotation instanceof Locatable) + if (checkPosition && annotation instanceof Locatable) { return ((Locatable) annotation).getPosition() != null; + } return true; } - public void pick(DrawContext dc, Iterable annotations, Point pickPoint, Layer layer) - { + public void pick(DrawContext dc, Iterable annotations, Point pickPoint, Layer layer) { this.drawMany(dc, annotations, layer); } - public void pick(DrawContext dc, Annotation annotation, Vec4 annotationPoint, java.awt.Point pickPoint, Layer layer) - { - if (!isAnnotationValid(annotation, false)) + public void pick(DrawContext dc, Annotation annotation, Vec4 annotationPoint, java.awt.Point pickPoint, Layer layer) { + if (!isAnnotationValid(annotation, false)) { return; + } this.drawOne(dc, annotation, annotationPoint, layer); } - public void render(DrawContext dc, Iterable annotations, Layer layer) - { + public void render(DrawContext dc, Iterable annotations, Layer layer) { this.drawMany(dc, annotations, layer); } - public void render(DrawContext dc, Annotation annotation, Vec4 annotationPoint, Layer layer) - { - if (!isAnnotationValid(annotation, false)) + public void render(DrawContext dc, Annotation annotation, Vec4 annotationPoint, Layer layer) { + if (!isAnnotationValid(annotation, false)) { return; + } this.drawOne(dc, annotation, annotationPoint, layer); } - protected void drawMany(DrawContext dc, Iterable annotations, Layer layer) - { - if (dc == null) - { + protected void drawMany(DrawContext dc, Iterable annotations, Layer layer) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc.getVisibleSector() == null) + if (dc.getVisibleSector() == null) { return; + } SectorGeometryList geos = dc.getSurfaceGeometry(); //noinspection RedundantIfStatement - if (geos == null) + if (geos == null) { return; + } - if (annotations == null) - { + if (annotations == null) { String msg = Logging.getMessage("nullValue.AnnotationIterator"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc.isContinuous2DGlobe() && this.currentFrameTime != dc.getFrameTimeStamp()) - { + if (dc.isContinuous2DGlobe() && this.currentFrameTime != dc.getFrameTimeStamp()) { // Keep track of which annotations are added to the ordered renderable list so that they are not added // to that list more than once per frame. this.currentPickAnnotations.clear(); @@ -107,80 +104,82 @@ protected void drawMany(DrawContext dc, Iterable annotations, Layer Iterator iterator = annotations.iterator(); - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return; + } double altitude = dc.getView().getEyePosition().getElevation(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Annotation annotation = iterator.next(); - if (!isAnnotationValid(annotation, true)) + if (!isAnnotationValid(annotation, true)) { continue; + } - if (!annotation.getAttributes().isVisible()) + if (!annotation.getAttributes().isVisible()) { continue; + } // Do not draw the pick pass if not at pick point range; - if (dc.isPickingMode() && !this.isAtPickRange(dc, annotation)) + if (dc.isPickingMode() && !this.isAtPickRange(dc, annotation)) { continue; + } - if (altitude < annotation.getMinActiveAltitude() || altitude > annotation.getMaxActiveAltitude()) + if (altitude < annotation.getMinActiveAltitude() || altitude > annotation.getMaxActiveAltitude()) { continue; + } - if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation) - { - if (dc.isPickingMode() && this.currentPickAnnotations.contains(annotation)) + if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation) { + if (dc.isPickingMode() && this.currentPickAnnotations.contains(annotation)) { continue; + } - if (currentDrawAnnotations.contains(annotation)) + if (currentDrawAnnotations.contains(annotation)) { continue; + } } // TODO: cull annotations that are beyond the horizon double eyeDistance = 1; - if (annotation instanceof Locatable) - { + if (annotation instanceof Locatable) { // Determine Cartesian position from the surface geometry if the annotation is near the surface, // otherwise draw it from the globe. Vec4 annotationPoint = getAnnotationDrawPoint(dc, annotation); - if (annotationPoint == null) + if (annotationPoint == null) { continue; + } eyeDistance = annotation.isAlwaysOnTop() ? 0 : dc.getView().getEyePoint().distanceTo3(annotationPoint); } - if (annotation instanceof ScreenAnnotation) - { + if (annotation instanceof ScreenAnnotation) { Rectangle screenBounds = annotation.getBounds(dc); - if (screenBounds != null && !dc.getView().getViewport().intersects(screenBounds)) + if (screenBounds != null && !dc.getView().getViewport().intersects(screenBounds)) { return; + } } // The annotations aren't drawn here, but added to the ordered queue to be drawn back-to-front. dc.addOrderedRenderable(new OrderedAnnotation(annotation, layer, eyeDistance)); - if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation) - { - if (dc.isPickingMode()) + if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation) { + if (dc.isPickingMode()) { this.currentPickAnnotations.add(annotation); - else + } else { this.currentDrawAnnotations.add(annotation); + } } } } - protected void drawOne(DrawContext dc, Annotation annotation, Vec4 annotationPoint, Layer layer) - { - if (dc == null) - { + protected void drawOne(DrawContext dc, Annotation annotation, Vec4 annotationPoint, Layer layer) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation - && this.currentFrameTime != dc.getFrameTimeStamp()) - { + && this.currentFrameTime != dc.getFrameTimeStamp()) { // Keep track of which screen annotations are added to the ordered renderable list so that they are not added // to that list more than once per frame. this.currentPickAnnotations.clear(); @@ -188,84 +187,90 @@ protected void drawOne(DrawContext dc, Annotation annotation, Vec4 annotationPoi this.currentFrameTime = dc.getFrameTimeStamp(); } - if (dc.getVisibleSector() == null) + if (dc.getVisibleSector() == null) { return; + } SectorGeometryList geos = dc.getSurfaceGeometry(); //noinspection RedundantIfStatement - if (geos == null) + if (geos == null) { return; + } - if (!annotation.getAttributes().isVisible()) + if (!annotation.getAttributes().isVisible()) { return; + } // Do not draw the pick pass if not at pick point range; - if (dc.isPickingMode() && !this.isAtPickRange(dc, annotation)) + if (dc.isPickingMode() && !this.isAtPickRange(dc, annotation)) { return; + } - if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation) - { - if (dc.isPickingMode() && this.currentPickAnnotations.contains(annotation)) + if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation) { + if (dc.isPickingMode() && this.currentPickAnnotations.contains(annotation)) { return; + } - if (currentDrawAnnotations.contains(annotation)) + if (currentDrawAnnotations.contains(annotation)) { return; + } } double altitude = dc.getView().getEyePosition().getElevation(); - if (altitude < annotation.getMinActiveAltitude() || altitude > annotation.getMaxActiveAltitude()) + if (altitude < annotation.getMinActiveAltitude() || altitude > annotation.getMaxActiveAltitude()) { return; + } double eyeDistance = 1; - if (annotation instanceof Locatable) - { - if (annotationPoint == null) - { + if (annotation instanceof Locatable) { + if (annotationPoint == null) { Position pos = ((Locatable) annotation).getPosition(); - if (!dc.getVisibleSector().contains(pos.getLatitude(), pos.getLongitude())) + if (!dc.getVisibleSector().contains(pos.getLatitude(), pos.getLongitude())) { return; + } // Determine Cartesian position from the surface geometry if the annotation is near the surface, // otherwise draw it from the globe. annotationPoint = getAnnotationDrawPoint(dc, annotation); - if (annotationPoint == null) + if (annotationPoint == null) { return; + } } - if (!dc.getView().getFrustumInModelCoordinates().contains(annotationPoint)) + if (!dc.getView().getFrustumInModelCoordinates().contains(annotationPoint)) { return; + } - if (!dc.isContinuous2DGlobe()) - { + if (!dc.isContinuous2DGlobe()) { double horizon = dc.getView().getHorizonDistance(); eyeDistance = annotation.isAlwaysOnTop() ? 0 : dc.getView().getEyePoint().distanceTo3(annotationPoint); - if (eyeDistance > horizon) + if (eyeDistance > horizon) { return; + } } } - if (annotation instanceof ScreenAnnotation) - { + if (annotation instanceof ScreenAnnotation) { Rectangle screenBounds = annotation.getBounds(dc); - if (screenBounds != null && !dc.getView().getViewport().intersects(screenBounds)) + if (screenBounds != null && !dc.getView().getViewport().intersects(screenBounds)) { return; + } } // The annotation isn't drawn here, but added to the ordered queue to be drawn back-to-front. dc.addOrderedRenderable(new OrderedAnnotation(annotation, layer, eyeDistance)); - if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation) - { - if (dc.isPickingMode()) + if (dc.isContinuous2DGlobe() && annotation instanceof ScreenAnnotation) { + if (dc.isPickingMode()) { this.currentPickAnnotations.add(annotation); - else + } else { this.currentDrawAnnotations.add(annotation); + } } } - protected boolean isAtPickRange(DrawContext dc, Annotation annotation) - { + protected boolean isAtPickRange(DrawContext dc, Annotation annotation) { Rectangle screenBounds = annotation.getBounds(dc); return screenBounds != null && dc.getPickFrustums().intersectsAny(screenBounds); } @@ -275,139 +280,113 @@ protected boolean isAtPickRange(DrawContext dc, Annotation annotation) * the highest elevation on the globe, it will be drawn above the ground using its elevation as an offset. * Otherwise, the original elevation will be used. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param annotation the annotation * * @return the annotation draw cartesian point */ - protected Vec4 getAnnotationDrawPoint(DrawContext dc, Annotation annotation) - { + protected Vec4 getAnnotationDrawPoint(DrawContext dc, Annotation annotation) { Vec4 drawPoint = null; - if (annotation instanceof Locatable) - { + if (annotation instanceof Locatable) { Position pos = ((Locatable) annotation).getPosition(); - if (pos.getElevation() < dc.getGlobe().getMaxElevation()) + if (pos.getElevation() < dc.getGlobe().getMaxElevation()) { drawPoint = dc.getSurfaceGeometry().getSurfacePoint(pos.getLatitude(), pos.getLongitude(), - pos.getElevation()); - if (drawPoint == null) + pos.getElevation()); + } + if (drawPoint == null) { drawPoint = dc.getGlobe().computePointFromPosition(pos); + } } return drawPoint; } - protected class OrderedAnnotation implements OrderedRenderable - { + protected class OrderedAnnotation implements OrderedRenderable { + protected Annotation annotation; protected double eyeDistance; protected Layer layer; - public OrderedAnnotation(Annotation annotation, double eyeDistance) - { + public OrderedAnnotation(Annotation annotation, double eyeDistance) { this.annotation = annotation; this.eyeDistance = eyeDistance; } - public OrderedAnnotation(Annotation annotation, Layer layer, double eyeDistance) - { + public OrderedAnnotation(Annotation annotation, Layer layer, double eyeDistance) { this.annotation = annotation; this.eyeDistance = eyeDistance; this.layer = layer; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { OGLStackHandler stackHandler = new OGLStackHandler(); BasicAnnotationRenderer.this.beginDrawAnnotations(dc, stackHandler); - try - { + try { this.doRender(dc, this); // Draw as many as we can in a batch to save ogl state switching. - while (dc.peekOrderedRenderables() instanceof OrderedAnnotation) - { + while (dc.peekOrderedRenderables() instanceof OrderedAnnotation) { OrderedAnnotation oa = (OrderedAnnotation) dc.pollOrderedRenderables(); this.doRender(dc, oa); } - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { Logging.logger().log(Level.SEVERE, "generic.ExceptionWhileRenderingAnnotation", e); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, "generic.ExceptionWhileRenderingAnnotation", e); - } - finally - { + } finally { BasicAnnotationRenderer.this.endDrawAnnotations(dc, stackHandler); } } - public void pick(DrawContext dc, java.awt.Point pickPoint) - { + public void pick(DrawContext dc, java.awt.Point pickPoint) { OGLStackHandler stackHandler = new OGLStackHandler(); BasicAnnotationRenderer.this.pickSupport.clearPickList(); BasicAnnotationRenderer.this.beginDrawAnnotations(dc, stackHandler); - try - { + try { this.annotation.setPickSupport(BasicAnnotationRenderer.this.pickSupport); this.doRender(dc, this); // Draw as many as we can in a batch to save ogl state switching. - while (dc.peekOrderedRenderables() instanceof OrderedAnnotation) - { + while (dc.peekOrderedRenderables() instanceof OrderedAnnotation) { OrderedAnnotation oa = (OrderedAnnotation) dc.pollOrderedRenderables(); oa.annotation.setPickSupport(BasicAnnotationRenderer.this.pickSupport); this.doRender(dc, oa); } - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { Logging.logger().log(Level.SEVERE, "generic.ExceptionWhilePickingAnnotation", e); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, "generic.ExceptionWhilePickingAnnotation", e); - } - finally - { + } finally { BasicAnnotationRenderer.this.endDrawAnnotations(dc, stackHandler); BasicAnnotationRenderer.this.pickSupport.resolvePick(dc, pickPoint, this.layer); BasicAnnotationRenderer.this.pickSupport.clearPickList(); // to ensure entries can be garbage collected } } - protected void doRender(DrawContext dc, OrderedAnnotation oa) - { + protected void doRender(DrawContext dc, OrderedAnnotation oa) { // Swap the draw context's current layer with that of the ordered annotation Layer previousCurrentLayer = dc.getCurrentLayer(); - try - { + try { dc.setCurrentLayer(oa.layer); oa.annotation.renderNow(dc); - } - finally - { + } finally { dc.setCurrentLayer(previousCurrentLayer); // restore the original layer } } } - protected void beginDrawAnnotations(DrawContext dc, OGLStackHandler stackHandler) - { + protected void beginDrawAnnotations(DrawContext dc, OGLStackHandler stackHandler) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int attributeMask = GL2.GL_COLOR_BUFFER_BIT // for alpha test func and ref, blend func - | GL2.GL_CURRENT_BIT // for current color - | GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask, depth func - | GL2.GL_ENABLE_BIT // for enable/disable changes - | GL2.GL_HINT_BIT // for line smoothing hint - | GL2.GL_LINE_BIT // for line width, line stipple - | GL2.GL_TRANSFORM_BIT // for matrix mode - | GL2.GL_VIEWPORT_BIT; // for viewport, depth range + | GL2.GL_CURRENT_BIT // for current color + | GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask, depth func + | GL2.GL_ENABLE_BIT // for enable/disable changes + | GL2.GL_HINT_BIT // for line smoothing hint + | GL2.GL_LINE_BIT // for line width, line stipple + | GL2.GL_TRANSFORM_BIT // for matrix mode + | GL2.GL_VIEWPORT_BIT; // for viewport, depth range stackHandler.pushAttrib(gl, attributeMask); // Load a parallel projection with dimensions (viewportWidth, viewportHeight) @@ -423,32 +402,28 @@ protected void beginDrawAnnotations(DrawContext dc, OGLStackHandler stackHandler gl.glAlphaFunc(GL2.GL_GREATER, 0.0f); // Apply the depth buffer but don't change it. - if ((!dc.isDeepPickingEnabled())) + if ((!dc.isDeepPickingEnabled())) { gl.glEnable(GL.GL_DEPTH_TEST); + } gl.glDepthMask(false); // Disable lighting and backface culling. gl.glDisable(GL2.GL_LIGHTING); gl.glDisable(GL.GL_CULL_FACE); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Enable blending in premultiplied color mode. gl.glEnable(GL.GL_BLEND); OGLUtil.applyBlending(gl, true); - } - else - { + } else { this.pickSupport.beginPicking(dc); } } - protected void endDrawAnnotations(DrawContext dc, OGLStackHandler stackHandler) - { + protected void endDrawAnnotations(DrawContext dc, OGLStackHandler stackHandler) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.endPicking(dc); } diff --git a/src/gov/nasa/worldwind/render/BasicBalloonAttributes.java b/src/gov/nasa/worldwind/render/BasicBalloonAttributes.java index 84008c7a58..8dbdc8f436 100644 --- a/src/gov/nasa/worldwind/render/BasicBalloonAttributes.java +++ b/src/gov/nasa/worldwind/render/BasicBalloonAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.avlist.AVKey; @@ -20,33 +19,59 @@ * @author pabercrombie * @version $Id: BasicBalloonAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicBalloonAttributes extends BasicShapeAttributes implements BalloonAttributes -{ - /** Indicates the width and height of the balloon's shape in the viewport. Initially null. */ +public class BasicBalloonAttributes extends BasicShapeAttributes implements BalloonAttributes { + + /** + * Indicates the width and height of the balloon's shape in the viewport. Initially null. + */ protected Size size; - /** Indicates the maximum width and height of the balloon's shape in the viewport. Initially null. */ + /** + * Indicates the maximum width and height of the balloon's shape in the viewport. Initially null. + */ protected Size maxSize; - /** Indicates the location at which the balloon's lower left corner is aligned. Initially null. */ + /** + * Indicates the location at which the balloon's lower left corner is aligned. Initially null. + */ protected Offset offset; - /** Indicates the padding between the balloon's content and its frame, in pixels. Initially null. */ + /** + * Indicates the padding between the balloon's content and its frame, in pixels. Initially null. + */ protected Insets insets; - /** Indicates the shape of the balloon's frame. Initially null. */ + /** + * Indicates the shape of the balloon's frame. Initially null. + */ protected String balloonShape; - /** Indicates the shape of the balloon's leader. Initially null. */ + /** + * Indicates the shape of the balloon's leader. Initially null. + */ protected String leaderShape; - /** Indicates the width of the balloon's leader, in pixels. Initially 0. */ + /** + * Indicates the width of the balloon's leader, in pixels. Initially 0. + */ protected int leaderWidth; - /** Indicates the radius of each rounded corner on the balloon's rectangular frame, in pixels. Initially 0. */ + /** + * Indicates the radius of each rounded corner on the balloon's rectangular frame, in pixels. Initially 0. + */ protected int cornerRadius; - /** Indicates the font used to display the balloon's text. Initially null. */ + /** + * Indicates the font used to display the balloon's text. Initially null. + */ protected Font font; - /** Indicates the color used to display the balloon's text. Initially null. */ + /** + * Indicates the color used to display the balloon's text. Initially null. + */ protected Color textColor; - /** Indicates the location of the image source in pixels. Initially null. */ + /** + * Indicates the location of the image source in pixels. Initially null. + */ protected Point imageOffset; - /** Indicates the balloon texture's opacity as a floating-point value from 0.0 to 1.0. Initially 0.0. */ + /** + * Indicates the balloon texture's opacity as a floating-point value from 0.0 to 1.0. Initially 0.0. + */ protected double imageOpacity; - /** Specifies the balloon texture's horizontal and vertical repeat mode. Initially null. */ + /** + * Specifies the balloon texture's horizontal and vertical repeat mode. Initially null. + */ protected String imageRepeat; /** @@ -55,23 +80,25 @@ public class BasicBalloonAttributes extends BasicShapeAttributes implements Ball * * * - * + * + * * * * * - * + * + * * * * + * AVKey#SHAPE_TRIANGLE} + * * * *
          Attributes
          AttributeDefault Value
          unresolvedtrue
          drawInteriortrue
          drawOutlinetrue
          enableAntialiasingtrue
          enableLightingfalse
          enableAntialiasingtrue
          enableLightingfalse
          interiorMaterial{@link gov.nasa.worldwind.render.Material#WHITE}
          outlineMaterial171, 171, 171 (red, green, blue)
          interiorOpacity1.0
          outlineOpacity1.0
          outlineWidth1.0
          outlineStippleFactor0
          outlineStipplePattern0xF0F0
          interiorImageSourcenull
          outlineStipplePattern0xF0F0
          interiorImageSourcenull
          interiorImageScale1.0
          size350x350 pixels (width x height)
          maximumSizenull
          offset40,60 pixels (x, * y)
          insets30,15,15,15 (top, left, bottom, right)
          balloonShape{@link AVKey#SHAPE_RECTANGLE}
          leaderShape{@link - * AVKey#SHAPE_TRIANGLE}
          leaderWidth40.0
          cornerRadius20.0
          leaderWidth40.0
          cornerRadius20.0
          fontArial Plain 12
          textColor{@link java.awt.Color#BLACK}
          imageOffset0,0 (x, y)
          imageOpacity1
          imageRepeat{@link gov.nasa.worldwind.avlist.AVKey#REPEAT_XY}
          */ - public BasicBalloonAttributes() - { + public BasicBalloonAttributes() { // Note: update the above constructor comment if these defaults change. // Common shape attributes. @@ -99,10 +126,8 @@ public BasicBalloonAttributes() * * @throws IllegalArgumentException if attributes is null. */ - public BasicBalloonAttributes(BalloonAttributes attributes) - { - if (attributes == null) - { + public BasicBalloonAttributes(BalloonAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -117,8 +142,7 @@ public BasicBalloonAttributes(BalloonAttributes attributes) *

          * Overrides the superclass' behavior to return a new BasicBalloonAttributes. */ - public ShapeAttributes copy() - { + public ShapeAttributes copy() { return new BasicBalloonAttributes(this); } @@ -128,14 +152,12 @@ public ShapeAttributes copy() * Extends the superclass' behavior to copy BalloonAttributes if the specified attributes * is an instance of BalloonAttributes. */ - public void copy(ShapeAttributes attributes) - { + public void copy(ShapeAttributes attributes) { // Copy the common attributes inherited from ShapeAttributes. super.copy(attributes); // Copy the balloon-specific attributes. - if (attributes instanceof BalloonAttributes) - { + if (attributes instanceof BalloonAttributes) { BalloonAttributes balloonAttrs = (BalloonAttributes) attributes; this.size = balloonAttrs.getSize(); this.maxSize = balloonAttrs.getMaximumSize(); @@ -153,17 +175,18 @@ public void copy(ShapeAttributes attributes) } } - /** {@inheritDoc} */ - public String getBalloonShape() - { + /** + * {@inheritDoc} + */ + public String getBalloonShape() { return this.balloonShape; } - /** {@inheritDoc} */ - public void setBalloonShape(String shape) - { - if (shape == null) - { + /** + * {@inheritDoc} + */ + public void setBalloonShape(String shape) { + if (shape == null) { String message = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,17 +195,18 @@ public void setBalloonShape(String shape) this.balloonShape = shape; } - /** {@inheritDoc} */ - public Size getSize() - { + /** + * {@inheritDoc} + */ + public Size getSize() { return this.size; } - /** {@inheritDoc} */ - public void setSize(Size size) - { - if (size == null) - { + /** + * {@inheritDoc} + */ + public void setSize(Size size) { + if (size == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -191,29 +215,32 @@ public void setSize(Size size) this.size = size; } - /** {@inheritDoc} */ - public Size getMaximumSize() - { + /** + * {@inheritDoc} + */ + public Size getMaximumSize() { return this.maxSize; } - /** {@inheritDoc} */ - public void setMaximumSize(Size maxSize) - { + /** + * {@inheritDoc} + */ + public void setMaximumSize(Size maxSize) { this.maxSize = maxSize; } - /** {@inheritDoc} */ - public String getLeaderShape() - { + /** + * {@inheritDoc} + */ + public String getLeaderShape() { return this.leaderShape; } - /** {@inheritDoc} */ - public void setLeaderShape(String shape) - { - if (shape == null) - { + /** + * {@inheritDoc} + */ + public void setLeaderShape(String shape) { + if (shape == null) { String message = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -222,17 +249,18 @@ public void setLeaderShape(String shape) this.leaderShape = shape; } - /** {@inheritDoc} */ - public int getLeaderWidth() - { + /** + * {@inheritDoc} + */ + public int getLeaderWidth() { return this.leaderWidth; } - /** {@inheritDoc} */ - public void setLeaderWidth(int width) - { - if (width < 0) - { + /** + * {@inheritDoc} + */ + public void setLeaderWidth(int width) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -241,17 +269,18 @@ public void setLeaderWidth(int width) this.leaderWidth = width; } - /** {@inheritDoc} */ - public int getCornerRadius() - { + /** + * {@inheritDoc} + */ + public int getCornerRadius() { return this.cornerRadius; } - /** {@inheritDoc} */ - public void setCornerRadius(int radius) - { - if (radius < 0) - { + /** + * {@inheritDoc} + */ + public void setCornerRadius(int radius) { + if (radius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -260,17 +289,18 @@ public void setCornerRadius(int radius) this.cornerRadius = radius; } - /** {@inheritDoc} */ - public Offset getOffset() - { + /** + * {@inheritDoc} + */ + public Offset getOffset() { return this.offset; } - /** {@inheritDoc} */ - public void setOffset(Offset offset) - { - if (offset == null) - { + /** + * {@inheritDoc} + */ + public void setOffset(Offset offset) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -279,17 +309,18 @@ public void setOffset(Offset offset) this.offset = offset; } - /** {@inheritDoc} */ - public Insets getInsets() - { + /** + * {@inheritDoc} + */ + public Insets getInsets() { return this.insets; } - /** {@inheritDoc} */ - public void setInsets(Insets insets) - { - if (insets == null) - { + /** + * {@inheritDoc} + */ + public void setInsets(Insets insets) { + if (insets == null) { String message = Logging.getMessage("nullValue.InsetsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -298,17 +329,18 @@ public void setInsets(Insets insets) this.insets = insets; } - /** {@inheritDoc} */ - public Font getFont() - { + /** + * {@inheritDoc} + */ + public Font getFont() { return this.font; } - /** {@inheritDoc} */ - public void setFont(Font font) - { - if (font == null) - { + /** + * {@inheritDoc} + */ + public void setFont(Font font) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -317,17 +349,18 @@ public void setFont(Font font) this.font = font; } - /** {@inheritDoc} */ - public Color getTextColor() - { + /** + * {@inheritDoc} + */ + public Color getTextColor() { return this.textColor; } - /** {@inheritDoc} */ - public void setTextColor(Color color) - { - if (color == null) - { + /** + * {@inheritDoc} + */ + public void setTextColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -336,17 +369,18 @@ public void setTextColor(Color color) this.textColor = color; } - /** {@inheritDoc} */ - public Point getImageOffset() - { + /** + * {@inheritDoc} + */ + public Point getImageOffset() { return this.imageOffset; } - /** {@inheritDoc} */ - public void setImageOffset(Point offset) - { - if (offset == null) - { + /** + * {@inheritDoc} + */ + public void setImageOffset(Point offset) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -355,17 +389,18 @@ public void setImageOffset(Point offset) this.imageOffset = offset; } - /** {@inheritDoc} */ - public double getImageOpacity() - { + /** + * {@inheritDoc} + */ + public double getImageOpacity() { return this.imageOpacity; } - /** {@inheritDoc} */ - public void setImageOpacity(double opacity) - { - if (opacity < 0 || opacity > 1) - { + /** + * {@inheritDoc} + */ + public void setImageOpacity(double opacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -374,17 +409,18 @@ public void setImageOpacity(double opacity) this.imageOpacity = opacity; } - /** {@inheritDoc} */ - public String getImageRepeat() - { + /** + * {@inheritDoc} + */ + public String getImageRepeat() { return this.imageRepeat; } - /** {@inheritDoc} */ - public void setImageRepeat(String repeat) - { - if (repeat == null) - { + /** + * {@inheritDoc} + */ + public void setImageRepeat(String repeat) { + if (repeat == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -393,11 +429,11 @@ public void setImageRepeat(String repeat) this.imageRepeat = repeat; } - /** {@inheritDoc} */ - public void getRestorableState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) - { - if (restorableSupport == null) - { + /** + * {@inheritDoc} + */ + public void getRestorableState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) { + if (restorableSupport == null) { String message = Logging.getMessage("nullValue.RestorableSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -406,24 +442,25 @@ public void getRestorableState(RestorableSupport restorableSupport, RestorableSu super.getRestorableState(restorableSupport, context); RestorableSupport.StateObject so = restorableSupport.addStateObject(context, "size"); - if (so != null) + if (so != null) { this.getSize().getRestorableState(restorableSupport, so); + } Size maxSize = this.getMaximumSize(); - if (maxSize != null) - { + if (maxSize != null) { so = restorableSupport.addStateObject(context, "maxSize"); - if (so != null) + if (so != null) { this.getMaximumSize().getRestorableState(restorableSupport, so); + } } so = restorableSupport.addStateObject(context, "drawOffset"); - if (so != null) + if (so != null) { this.getOffset().getRestorableState(restorableSupport, so); + } so = restorableSupport.addStateObject(context, "insets"); - if (so != null) - { + if (so != null) { restorableSupport.addStateValueAsInteger(so, "top", this.getInsets().top); restorableSupport.addStateValueAsInteger(so, "left", this.getInsets().left); restorableSupport.addStateValueAsInteger(so, "bottom", this.getInsets().bottom); @@ -439,20 +476,19 @@ public void getRestorableState(RestorableSupport restorableSupport, RestorableSu // Save the name, style, and size of the font. These will be used to restore the font using the // constructor: new Font(name, style, size). so = restorableSupport.addStateObject(context, "font"); - if (so != null) - { + if (so != null) { restorableSupport.addStateValueAsString(so, "name", this.getFont().getName()); restorableSupport.addStateValueAsInteger(so, "style", this.getFont().getStyle()); restorableSupport.addStateValueAsInteger(so, "size", this.getFont().getSize()); } String encodedColor = RestorableSupport.encodeColor(this.getTextColor()); - if (encodedColor != null) + if (encodedColor != null) { restorableSupport.addStateValueAsString(context, "textColor", encodedColor); + } so = restorableSupport.addStateObject(context, "imageOffset"); - if (so != null) - { + if (so != null) { restorableSupport.addStateValueAsDouble(so, "x", this.getImageOffset().getX()); restorableSupport.addStateValueAsDouble(so, "y", this.getImageOffset().getY()); } @@ -461,11 +497,11 @@ public void getRestorableState(RestorableSupport restorableSupport, RestorableSu restorableSupport.addStateValueAsString(context, "imageRepeat", this.getImageRepeat()); } - /** {@inheritDoc} */ - public void restoreState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) - { - if (restorableSupport == null) - { + /** + * {@inheritDoc} + */ + public void restoreState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) { + if (restorableSupport == null) { String message = Logging.getMessage("nullValue.RestorableSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -482,153 +518,172 @@ public void restoreState(RestorableSupport restorableSupport, RestorableSupport. legacySupport.put("Render.FrameFactory.LeaderNone", AVKey.SHAPE_NONE); RestorableSupport.StateObject so = restorableSupport.getStateObject(context, "size"); - if (so != null) + if (so != null) { this.getSize().restoreState(restorableSupport, so); + } so = restorableSupport.getStateObject(context, "maxSize"); - if (so != null) - { + if (so != null) { Size maxSize = new Size(); maxSize.restoreState(restorableSupport, so); this.setMaximumSize(maxSize); } so = restorableSupport.getStateObject(context, "drawOffset"); - if (so != null) + if (so != null) { this.getOffset().restoreState(restorableSupport, so); + } // Restore the insets property only if all parts are available. // We will not restore a partial insets (for example, just the top value). so = restorableSupport.getStateObject(context, "insets"); - if (so != null) - { + if (so != null) { Integer topState = restorableSupport.getStateValueAsInteger(so, "top"); Integer leftState = restorableSupport.getStateValueAsInteger(so, "left"); Integer bottomState = restorableSupport.getStateValueAsInteger(so, "bottom"); Integer rightState = restorableSupport.getStateValueAsInteger(so, "right"); - if (topState != null && leftState != null && bottomState != null && rightState != null) + if (topState != null && leftState != null && bottomState != null && rightState != null) { this.setInsets(new Insets(topState, leftState, bottomState, rightState)); + } } String s = restorableSupport.getStateValueAsString(context, "balloonShape"); - if (s != null) - { + if (s != null) { // Map legacy versions using the FrameFactory constants to new AVKey constants. String updatedValue = legacySupport.get(s); - if (updatedValue != null) + if (updatedValue != null) { s = updatedValue; + } this.setBalloonShape(s); } s = restorableSupport.getStateValueAsString(context, "leader"); - if (s != null) - { + if (s != null) { // Map legacy versions using the FrameFactory constants to new AVKey constants. String updatedValue = legacySupport.get(s); - if (updatedValue != null) + if (updatedValue != null) { s = updatedValue; + } this.setLeaderShape(s); } Integer i = restorableSupport.getStateValueAsInteger(context, "leaderGapWidth"); - if (i != null) + if (i != null) { this.setLeaderWidth(i); + } i = restorableSupport.getStateValueAsInteger(context, "cornerRadius"); - if (i != null) + if (i != null) { this.setCornerRadius(i); + } // Restore the font property only if all parts are available. // We will not restore a partial font (for example, just the size). so = restorableSupport.getStateObject(context, "font"); - if (so != null) - { + if (so != null) { // The "font name" of toolTipFont. String name = restorableSupport.getStateValueAsString(so, "name"); // The style attributes. Integer style = restorableSupport.getStateValueAsInteger(so, "style"); // The simple font size. Integer size = restorableSupport.getStateValueAsInteger(so, "size"); - if (name != null && style != null && size != null) + if (name != null && style != null && size != null) { this.setFont(new Font(name, style, size)); + } } s = restorableSupport.getStateValueAsString(context, "textColor"); - if (s != null) - { + if (s != null) { Color color = RestorableSupport.decodeColor(s); - if (color != null) + if (color != null) { this.setTextColor(color); + } } // Restore the imageOffset property only if all parts are available. // We will not restore a partial imageOffset (for example, just the x value). so = restorableSupport.getStateObject(context, "imageOffset"); - if (so != null) - { + if (so != null) { Double x = restorableSupport.getStateValueAsDouble(so, "x"); Double y = restorableSupport.getStateValueAsDouble(so, "y"); - if (x != null && y != null) + if (x != null && y != null) { this.setImageOffset(new Point(x.intValue(), y.intValue())); + } } Double d = restorableSupport.getStateValueAsDouble(context, "imageOpacity"); - if (d != null) + if (d != null) { this.setImageOpacity(d); + } s = restorableSupport.getStateValueAsString(context, "imageRepeat"); - if (s != null) + if (s != null) { this.setImageRepeat(s); + } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; - if (!super.equals(o)) + } + if (!super.equals(o)) { return false; + } BasicBalloonAttributes that = (BasicBalloonAttributes) o; - if (this.size != null ? !this.size.equals(that.size) : that.size != null) + if (this.size != null ? !this.size.equals(that.size) : that.size != null) { return false; - if (this.maxSize != null ? !this.maxSize.equals(that.maxSize) : that.maxSize != null) + } + if (this.maxSize != null ? !this.maxSize.equals(that.maxSize) : that.maxSize != null) { return false; - if (this.offset != null ? !this.offset.equals(that.offset) : that.offset != null) + } + if (this.offset != null ? !this.offset.equals(that.offset) : that.offset != null) { return false; - if (this.insets != null ? !this.insets.equals(that.insets) : that.insets != null) + } + if (this.insets != null ? !this.insets.equals(that.insets) : that.insets != null) { return false; - if (this.balloonShape != null ? !this.balloonShape.equals(that.balloonShape) : that.balloonShape != null) + } + if (this.balloonShape != null ? !this.balloonShape.equals(that.balloonShape) : that.balloonShape != null) { return false; - if (this.leaderShape != null ? !this.leaderShape.equals(that.leaderShape) : that.leaderShape != null) + } + if (this.leaderShape != null ? !this.leaderShape.equals(that.leaderShape) : that.leaderShape != null) { return false; - if (this.leaderWidth != that.leaderWidth) + } + if (this.leaderWidth != that.leaderWidth) { return false; - if (this.cornerRadius != that.cornerRadius) + } + if (this.cornerRadius != that.cornerRadius) { return false; - if (this.font != null ? !this.font.equals(that.font) : that.font != null) + } + if (this.font != null ? !this.font.equals(that.font) : that.font != null) { return false; - if (this.textColor != null ? !this.textColor.equals(that.textColor) : that.textColor != null) + } + if (this.textColor != null ? !this.textColor.equals(that.textColor) : that.textColor != null) { return false; - if (this.imageOffset != null ? !this.imageOffset.equals(that.imageOffset) : that.imageOffset != null) + } + if (this.imageOffset != null ? !this.imageOffset.equals(that.imageOffset) : that.imageOffset != null) { return false; - if (Double.compare(this.imageOpacity, that.imageOpacity) != 0) + } + if (Double.compare(this.imageOpacity, that.imageOpacity) != 0) { return false; + } //noinspection RedundantIfStatement - if (this.imageRepeat != null ? !this.imageRepeat.equals(that.imageRepeat) : that.imageRepeat != null) + if (this.imageRepeat != null ? !this.imageRepeat.equals(that.imageRepeat) : that.imageRepeat != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = super.hashCode(); result = 31 * result + (this.size != null ? this.size.hashCode() : 0); diff --git a/src/gov/nasa/worldwind/render/BasicLightingModel.java b/src/gov/nasa/worldwind/render/BasicLightingModel.java index 6173c6ed9f..2558a32405 100644 --- a/src/gov/nasa/worldwind/render/BasicLightingModel.java +++ b/src/gov/nasa/worldwind/render/BasicLightingModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.geom.Vec4; @@ -17,26 +16,24 @@ * @author tag * @version $Id: BasicLightingModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicLightingModel implements LightingModel -{ +public class BasicLightingModel implements LightingModel { + protected OGLStackHandler lightingStackHandler = new OGLStackHandler(); protected Vec4 lightDirection = new Vec4(1.0, 0.5, 1.0); protected Material lightMaterial = Material.WHITE; protected long frameID; - public void beginLighting(DrawContext dc) - { - if (this.lightingStackHandler.isActive()) + public void beginLighting(DrawContext dc) { + if (this.lightingStackHandler.isActive()) { return; // lighting is already enabled - + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.lightingStackHandler.pushAttrib(gl, GL2.GL_LIGHTING_BIT); this.apply(dc); } - public void endLighting(DrawContext dc) - { + public void endLighting(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.lightingStackHandler.pop(gl); this.lightingStackHandler.clear(); @@ -47,8 +44,7 @@ public void endLighting(DrawContext dc) * * @return the model's light direction. */ - public Vec4 getLightDirection() - { + public Vec4 getLightDirection() { return lightDirection; } @@ -59,10 +55,8 @@ public Vec4 getLightDirection() * * @throws IllegalArgumentException if the light direction is null. */ - public void setLightDirection(Vec4 lightDirection) - { - if (lightDirection == null) - { + public void setLightDirection(Vec4 lightDirection) { + if (lightDirection == null) { String message = Logging.getMessage("nullValue.LightDirectionIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -76,8 +70,7 @@ public void setLightDirection(Vec4 lightDirection) * * @return the model's light material. */ - public Material getLightMaterial() - { + public Material getLightMaterial() { return lightMaterial; } @@ -88,10 +81,8 @@ public Material getLightMaterial() * * @throws IllegalArgumentException if the light material is null. */ - public void setLightMaterial(Material lightMaterial) - { - if (lightMaterial == null) - { + public void setLightMaterial(Material lightMaterial) { + if (lightMaterial == null) { String message = Logging.getMessage("nullValue.LightMaterialIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -100,8 +91,7 @@ public void setLightMaterial(Material lightMaterial) this.lightMaterial = lightMaterial; } - protected void apply(DrawContext dc) - { + protected void apply(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glEnable(GL2.GL_LIGHTING); @@ -113,8 +103,7 @@ protected void apply(DrawContext dc) applyStandardLightDirection(gl, GL2.GL_LIGHT0, this.lightDirection); } - protected void applyStandardLightModel(GL2 gl) - { + protected void applyStandardLightModel(GL2 gl) { float[] modelAmbient = new float[4]; modelAmbient[0] = 1.0f; modelAmbient[1] = 1.0f; @@ -127,13 +116,11 @@ protected void applyStandardLightModel(GL2 gl) gl.glLightModeli(GL2.GL_LIGHT_MODEL_TWO_SIDE, GL2.GL_TRUE); } - protected void applyStandardShadeModel(GL2 gl) - { + protected void applyStandardShadeModel(GL2 gl) { gl.glShadeModel(GL2.GL_SMOOTH); } - protected static void applyStandardLightMaterial(GL2 gl, int light, Material material) - { + protected static void applyStandardLightMaterial(GL2 gl, int light, Material material) { // The alpha value at a vertex is taken only from the diffuse material's alpha channel, without any // lighting computations applied. Therefore we specify alpha=0 for all lighting ambient, specular and // emission values. This will have no effect on material alpha. @@ -150,8 +137,7 @@ protected static void applyStandardLightMaterial(GL2 gl, int light, Material mat gl.glLightfv(light, GL2.GL_SPECULAR, specular, 0); } - protected void applyStandardLightDirection(GL2 gl, int light, Vec4 direction) - { + protected void applyStandardLightDirection(GL2 gl, int light, Vec4 direction) { // Setup the light as a directional light coming from the viewpoint. This requires two state changes // (a) Set the light position as direction x, y, z, and set the w-component to 0, which tells OpenGL this is // a directional light. diff --git a/src/gov/nasa/worldwind/render/BasicShapeAttributes.java b/src/gov/nasa/worldwind/render/BasicShapeAttributes.java index cfaf46d167..c4ec07821e 100644 --- a/src/gov/nasa/worldwind/render/BasicShapeAttributes.java +++ b/src/gov/nasa/worldwind/render/BasicShapeAttributes.java @@ -22,43 +22,73 @@ * @author dcollins * @version $Id: BasicShapeAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicShapeAttributes implements ShapeAttributes -{ - /** Indicates whether or not some of the shape's attributes are unresolved. Initially false. */ +public class BasicShapeAttributes implements ShapeAttributes { + + /** + * Indicates whether or not some of the shape's attributes are unresolved. Initially false. + */ protected boolean unresolved; - /** Indicates whether or not the shape's interior is drawn. Initially false. */ + /** + * Indicates whether or not the shape's interior is drawn. Initially false. + */ protected boolean drawInterior; - /** Indicates whether or not the shape's outline is drawn. Initially false. */ + /** + * Indicates whether or not the shape's outline is drawn. Initially false. + */ protected boolean drawOutline; - /** Indicates whether or not the shape should be rendered with smooth lines and edges. Initially false. */ + /** + * Indicates whether or not the shape should be rendered with smooth lines and edges. Initially false. + */ protected boolean enableAntialiasing; - /** Indicates whether lighting is applied to the shape. Initially false. */ + /** + * Indicates whether lighting is applied to the shape. Initially false. + */ protected boolean enableLighting; - /** Indicates the material properties of the shape's interior. Initially null. */ + /** + * Indicates the material properties of the shape's interior. Initially null. + */ protected Material interiorMaterial; - /** Indicates the material properties of the shape's outline. Initially null. */ + /** + * Indicates the material properties of the shape's outline. Initially null. + */ protected Material outlineMaterial; - /** Indicates the opacity of the shape's interior as a floating-point value in the range 0.0 to 1.0. Initially 0.0. */ + /** + * Indicates the opacity of the shape's interior as a floating-point value in the range 0.0 to 1.0. Initially 0.0. + */ protected double interiorOpacity; - /** Indicates the opacity of the shape's outline as a floating-point value in the range 0.0 to 1.0. Initially 0.0. */ + /** + * Indicates the opacity of the shape's outline as a floating-point value in the range 0.0 to 1.0. Initially 0.0. + */ protected double outlineOpacity; - /** Indicates the line width (in pixels) used when rendering the shape's outline. Initially 0.0. */ + /** + * Indicates the line width (in pixels) used when rendering the shape's outline. Initially 0.0. + */ protected double outlineWidth; - /** Indicates the number of times each bit in the outline stipple pattern is repeated. Initially 0. */ + /** + * Indicates the number of times each bit in the outline stipple pattern is repeated. Initially 0. + */ protected int outlineStippleFactor; - /** Indicates the 16-bit integer that defines which pixels are rendered in the shape's outline. Initially 0. */ + /** + * Indicates the 16-bit integer that defines which pixels are rendered in the shape's outline. Initially 0. + */ protected short outlineStipplePattern; - /** Indicates the image source that is applied as a texture to the shape's interior. Initially null. */ + /** + * Indicates the image source that is applied as a texture to the shape's interior. Initially null. + */ protected Object imageSource; - /** Indicates the amount the balloon's texture is scaled by as a floating-point value. Initially 0.0. */ + /** + * Indicates the amount the balloon's texture is scaled by as a floating-point value. Initially 0.0. + */ protected double imageScale; /** * Creates a new BasicShapeAttributes with the default attributes. The default attributes are as * follows: - * + *
          Default Attributes
          AttributeDefault Value
          unresolvedtrue
          * - * + * + * * * * @@ -66,8 +96,7 @@ public class BasicShapeAttributes implements ShapeAttributes * *
          Default Attributes
          AttributeDefault + * Value
          unresolvedtrue
          drawInteriortrue
          drawOutlinetrue
          enableAntialiasingtrue
          enableLightingfalse
          enableAntialiasingtrue
          enableLightingfalse
          interiorMaterial{@link gov.nasa.worldwind.render.Material#WHITE}
          outlineMaterial{@link gov.nasa.worldwind.render.Material#BLACK}
          interiorOpacity1.0
          outlineOpacity1.0
          outlineStipplePattern0xF0F0
          imageSourcenull
          imageScale1.0
          */ - public BasicShapeAttributes() - { + public BasicShapeAttributes() { // Note: update the above constructor comment if these defaults change. this.drawInterior = true; @@ -92,10 +121,8 @@ public BasicShapeAttributes() * * @throws IllegalArgumentException if attributes is null. */ - public BasicShapeAttributes(ShapeAttributes attributes) - { - if (attributes == null) - { + public BasicShapeAttributes(ShapeAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -116,17 +143,18 @@ public BasicShapeAttributes(ShapeAttributes attributes) this.imageScale = attributes.getImageScale(); } - /** {@inheritDoc} */ - public ShapeAttributes copy() - { + /** + * {@inheritDoc} + */ + public ShapeAttributes copy() { return new BasicShapeAttributes(this); } - /** {@inheritDoc} */ - public void copy(ShapeAttributes attributes) - { - if (attributes != null) - { + /** + * {@inheritDoc} + */ + public void copy(ShapeAttributes attributes) { + if (attributes != null) { this.drawInterior = attributes.isDrawInterior(); this.drawOutline = attributes.isDrawOutline(); this.enableAntialiasing = attributes.isEnableAntialiasing(); @@ -143,77 +171,88 @@ public void copy(ShapeAttributes attributes) } } - /** {@inheritDoc} */ - public boolean isUnresolved() - { + /** + * {@inheritDoc} + */ + public boolean isUnresolved() { return unresolved; } - /** {@inheritDoc} */ - public void setUnresolved(boolean unresolved) - { + /** + * {@inheritDoc} + */ + public void setUnresolved(boolean unresolved) { this.unresolved = unresolved; } - /** {@inheritDoc} */ - public boolean isDrawInterior() - { + /** + * {@inheritDoc} + */ + public boolean isDrawInterior() { return this.drawInterior; } - /** {@inheritDoc} */ - public void setDrawInterior(boolean draw) - { + /** + * {@inheritDoc} + */ + public void setDrawInterior(boolean draw) { this.drawInterior = draw; } - /** {@inheritDoc} */ - public boolean isDrawOutline() - { + /** + * {@inheritDoc} + */ + public boolean isDrawOutline() { return this.drawOutline; } - /** {@inheritDoc} */ - public void setDrawOutline(boolean draw) - { + /** + * {@inheritDoc} + */ + public void setDrawOutline(boolean draw) { this.drawOutline = draw; } - /** {@inheritDoc} */ - public boolean isEnableAntialiasing() - { + /** + * {@inheritDoc} + */ + public boolean isEnableAntialiasing() { return this.enableAntialiasing; } - /** {@inheritDoc} */ - public void setEnableAntialiasing(boolean enable) - { + /** + * {@inheritDoc} + */ + public void setEnableAntialiasing(boolean enable) { this.enableAntialiasing = enable; } - /** {@inheritDoc} */ - public boolean isEnableLighting() - { + /** + * {@inheritDoc} + */ + public boolean isEnableLighting() { return enableLighting; } - /** {@inheritDoc} */ - public void setEnableLighting(boolean enableLighting) - { + /** + * {@inheritDoc} + */ + public void setEnableLighting(boolean enableLighting) { this.enableLighting = enableLighting; } - /** {@inheritDoc} */ - public Material getInteriorMaterial() - { + /** + * {@inheritDoc} + */ + public Material getInteriorMaterial() { return this.interiorMaterial; } - /** {@inheritDoc} */ - public void setInteriorMaterial(Material material) - { - if (material == null) - { + /** + * {@inheritDoc} + */ + public void setInteriorMaterial(Material material) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -222,17 +261,18 @@ public void setInteriorMaterial(Material material) this.interiorMaterial = material; } - /** {@inheritDoc} */ - public Material getOutlineMaterial() - { + /** + * {@inheritDoc} + */ + public Material getOutlineMaterial() { return this.outlineMaterial; } - /** {@inheritDoc} */ - public void setOutlineMaterial(Material material) - { - if (material == null) - { + /** + * {@inheritDoc} + */ + public void setOutlineMaterial(Material material) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -241,17 +281,18 @@ public void setOutlineMaterial(Material material) this.outlineMaterial = material; } - /** {@inheritDoc} */ - public double getInteriorOpacity() - { + /** + * {@inheritDoc} + */ + public double getInteriorOpacity() { return this.interiorOpacity; } - /** {@inheritDoc} */ - public void setInteriorOpacity(double opacity) - { - if (opacity < 0 || opacity > 1) - { + /** + * {@inheritDoc} + */ + public void setInteriorOpacity(double opacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -260,17 +301,18 @@ public void setInteriorOpacity(double opacity) this.interiorOpacity = opacity; } - /** {@inheritDoc} */ - public double getOutlineOpacity() - { + /** + * {@inheritDoc} + */ + public double getOutlineOpacity() { return this.outlineOpacity; } - /** {@inheritDoc} */ - public void setOutlineOpacity(double opacity) - { - if (opacity < 0 || opacity > 1) - { + /** + * {@inheritDoc} + */ + public void setOutlineOpacity(double opacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -279,17 +321,18 @@ public void setOutlineOpacity(double opacity) this.outlineOpacity = opacity; } - /** {@inheritDoc} */ - public double getOutlineWidth() - { + /** + * {@inheritDoc} + */ + public double getOutlineWidth() { return this.outlineWidth; } - /** {@inheritDoc} */ - public void setOutlineWidth(double width) - { - if (width < 0) - { + /** + * {@inheritDoc} + */ + public void setOutlineWidth(double width) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -298,17 +341,18 @@ public void setOutlineWidth(double width) this.outlineWidth = width; } - /** {@inheritDoc} */ - public int getOutlineStippleFactor() - { + /** + * {@inheritDoc} + */ + public int getOutlineStippleFactor() { return this.outlineStippleFactor; } - /** {@inheritDoc} */ - public void setOutlineStippleFactor(int factor) - { - if (factor < 0) - { + /** + * {@inheritDoc} + */ + public void setOutlineStippleFactor(int factor) { + if (factor < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "factor < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -317,42 +361,47 @@ public void setOutlineStippleFactor(int factor) this.outlineStippleFactor = factor; } - /** {@inheritDoc} */ - public short getOutlineStipplePattern() - { + /** + * {@inheritDoc} + */ + public short getOutlineStipplePattern() { return this.outlineStipplePattern; } - /** {@inheritDoc} */ - public void setOutlineStipplePattern(short pattern) - { + /** + * {@inheritDoc} + */ + public void setOutlineStipplePattern(short pattern) { this.outlineStipplePattern = pattern; } - /** {@inheritDoc} */ - public Object getImageSource() - { + /** + * {@inheritDoc} + */ + public Object getImageSource() { return this.imageSource; } - /** {@inheritDoc} */ - public void setImageSource(Object imageSource) - { + /** + * {@inheritDoc} + */ + public void setImageSource(Object imageSource) { // Can be null this.imageSource = imageSource; } - /** {@inheritDoc} */ - public double getImageScale() - { + /** + * {@inheritDoc} + */ + public double getImageScale() { return this.imageScale; } - /** {@inheritDoc} */ - public void setImageScale(double scale) - { - if (scale <= 0) - { + /** + * {@inheritDoc} + */ + public void setImageScale(double scale) { + if (scale <= 0) { String message = Logging.getMessage("generic.ScaleOutOfRange", scale); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -361,11 +410,11 @@ public void setImageScale(double scale) this.imageScale = scale; } - /** {@inheritDoc} */ - public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject so) - { - if (rs == null) - { + /** + * {@inheritDoc} + */ + public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject so) { + if (rs == null) { String message = Logging.getMessage("nullValue.RestorableSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -393,123 +442,151 @@ public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObje rs.addStateValueAsInteger(so, "outlineStipplePattern", this.getOutlineStipplePattern()); - if (this.getImageSource() != null && this.getImageSource() instanceof String) + if (this.getImageSource() != null && this.getImageSource() instanceof String) { rs.addStateValueAsString(so, "interiorImagePath", (String) this.getImageSource()); + } rs.addStateValueAsDouble(so, "interiorImageScale", this.getImageScale()); } - /** {@inheritDoc} */ - public void restoreState(RestorableSupport rs, RestorableSupport.StateObject so) - { - if (rs == null) - { + /** + * {@inheritDoc} + */ + public void restoreState(RestorableSupport rs, RestorableSupport.StateObject so) { + if (rs == null) { String message = Logging.getMessage("nullValue.RestorableSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Boolean b = rs.getStateValueAsBoolean(so, "drawInterior"); - if (b != null) + if (b != null) { this.setDrawInterior(b); + } b = rs.getStateValueAsBoolean(so, "drawOutline"); - if (b != null) + if (b != null) { this.setDrawOutline(b); + } b = rs.getStateValueAsBoolean(so, "enableAntialiasing"); - if (b != null) + if (b != null) { this.setEnableAntialiasing(b); + } b = rs.getStateValueAsBoolean(so, "enableLighting"); - if (b != null) + if (b != null) { this.setEnableLighting(b); + } RestorableSupport.StateObject mo = rs.getStateObject(so, "interiorMaterial"); - if (mo != null) + if (mo != null) { this.setInteriorMaterial(this.getInteriorMaterial().restoreState(rs, mo)); + } mo = rs.getStateObject(so, "outlineMaterial"); - if (mo != null) + if (mo != null) { this.setOutlineMaterial(this.getOutlineMaterial().restoreState(rs, mo)); + } Double d = rs.getStateValueAsDouble(so, "interiorOpacity"); - if (d != null) + if (d != null) { this.setInteriorOpacity(d); + } d = rs.getStateValueAsDouble(so, "outlineOpacity"); - if (d != null) + if (d != null) { this.setOutlineOpacity(d); + } d = rs.getStateValueAsDouble(so, "outlineWidth"); - if (d != null) + if (d != null) { this.setOutlineWidth(d); + } Integer i = rs.getStateValueAsInteger(so, "outlineStippleFactor"); - if (i != null) + if (i != null) { this.setOutlineStippleFactor(i); + } i = rs.getStateValueAsInteger(so, "outlineStipplePattern"); - if (i != null) + if (i != null) { this.setOutlineStipplePattern(i.shortValue()); + } String s = rs.getStateValueAsString(so, "interiorImagePath"); - if (s != null) + if (s != null) { this.setImageSource(s); + } d = rs.getStateValueAsDouble(so, "interiorImageScale"); - if (d != null) + if (d != null) { this.setImageScale(d); + } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } BasicShapeAttributes that = (BasicShapeAttributes) o; - if (this.unresolved != that.unresolved) + if (this.unresolved != that.unresolved) { return false; - if (this.drawInterior != that.drawInterior) + } + if (this.drawInterior != that.drawInterior) { return false; - if (this.drawOutline != that.drawOutline) + } + if (this.drawOutline != that.drawOutline) { return false; - if (this.enableAntialiasing != that.enableAntialiasing) + } + if (this.enableAntialiasing != that.enableAntialiasing) { return false; - if (this.enableLighting != that.enableLighting) + } + if (this.enableLighting != that.enableLighting) { return false; + } if (this.interiorMaterial != null ? !this.interiorMaterial.equals(that.interiorMaterial) - : that.interiorMaterial != null) + : that.interiorMaterial != null) { return false; + } if (this.outlineMaterial != null ? !this.outlineMaterial.equals(that.outlineMaterial) - : that.outlineMaterial != null) + : that.outlineMaterial != null) { return false; - if (Double.compare(this.interiorOpacity, that.interiorOpacity) != 0) + } + if (Double.compare(this.interiorOpacity, that.interiorOpacity) != 0) { return false; - if (Double.compare(this.outlineOpacity, that.outlineOpacity) != 0) + } + if (Double.compare(this.outlineOpacity, that.outlineOpacity) != 0) { return false; - if (Double.compare(this.outlineWidth, that.outlineWidth) != 0) + } + if (Double.compare(this.outlineWidth, that.outlineWidth) != 0) { return false; - if (this.outlineStippleFactor != that.outlineStippleFactor) + } + if (this.outlineStippleFactor != that.outlineStippleFactor) { return false; - if (this.outlineStipplePattern != that.outlineStipplePattern) + } + if (this.outlineStipplePattern != that.outlineStipplePattern) { return false; - if (this.imageSource != null ? !this.imageSource.equals(that.imageSource) : that.imageSource != null) + } + if (this.imageSource != null ? !this.imageSource.equals(that.imageSource) : that.imageSource != null) { return false; + } //noinspection RedundantIfStatement - if (Double.compare(this.imageScale, that.imageScale) != 0) + if (Double.compare(this.imageScale, that.imageScale) != 0) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; long temp; @@ -535,46 +612,41 @@ public int hashCode() return result; } - /** {@inheritDoc} */ - public String isExportFormatSupported(String mimeType) - { - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) + /** + * {@inheritDoc} + */ + public String isExportFormatSupported(String mimeType) { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { return Exportable.FORMAT_SUPPORTED; - else + } else { return Exportable.FORMAT_NOT_SUPPORTED; + } } - /** {@inheritDoc} */ - public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException - { - if (mimeType == null) - { + /** + * {@inheritDoc} + */ + public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException { + if (mimeType == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output == null) - { + if (output == null) { String message = Logging.getMessage("nullValue.OutputBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) - { - try - { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { + try { exportAsKML(output); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { Logging.logger().throwing(getClass().getName(), "export", e); throw new IOException(e); } - } - else - { + } else { String message = Logging.getMessage("Export.UnsupportedFormat", mimeType); Logging.logger().warning(message); throw new UnsupportedOperationException(message); @@ -590,28 +662,21 @@ public void export(String mimeType, Object output) throws IOException, Unsupport * @throws XMLStreamException If an exception occurs while writing the KML * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws XMLStreamException - { + protected void exportAsKML(Object output) throws XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -623,8 +688,7 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("LineStyle"); final Color lineColor = this.getOutlineMaterial().getDiffuse(); - if (lineColor != null) - { + if (lineColor != null) { xmlWriter.writeStartElement("color"); xmlWriter.writeCharacters(KMLExportUtil.stripHexPrefix(WWUtil.encodeColorABGR(lineColor))); xmlWriter.writeEndElement(); @@ -635,8 +699,7 @@ else if (output instanceof OutputStream) } final Double lineWidth = this.getOutlineWidth(); - if (lineWidth != null) - { + if (lineWidth != null) { xmlWriter.writeStartElement("width"); xmlWriter.writeCharacters(Double.toString(lineWidth)); xmlWriter.writeEndElement(); @@ -648,8 +711,7 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("PolyStyle"); final Color fillColor = this.getInteriorMaterial().getDiffuse(); - if (fillColor != null) - { + if (fillColor != null) { xmlWriter.writeStartElement("color"); xmlWriter.writeCharacters(KMLExportUtil.stripHexPrefix(WWUtil.encodeColorABGR(fillColor))); xmlWriter.writeEndElement(); @@ -671,7 +733,8 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); // Style xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } } diff --git a/src/gov/nasa/worldwind/render/BasicWWTexture.java b/src/gov/nasa/worldwind/render/BasicWWTexture.java index ef7ab78be2..5b15d0bbb2 100644 --- a/src/gov/nasa/worldwind/render/BasicWWTexture.java +++ b/src/gov/nasa/worldwind/render/BasicWWTexture.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.opengl.util.texture.*; @@ -30,8 +29,8 @@ * @version $Id: BasicWWTexture.java 1171 2013-02-11 21:45:02Z dcollins $ * @see LazilyLoadedTexture */ -public class BasicWWTexture implements WWTexture -{ +public class BasicWWTexture implements WWTexture { + private Object imageSource; private boolean useMipMaps; private boolean useAnisotropy = true; @@ -48,12 +47,11 @@ public class BasicWWTexture implements WWTexture * displayed the image source is not read. * * @param imageSource the source of the image, either a file path {@link String} or a {@link BufferedImage}. - * @param useMipMaps Indicates whether to generate and use mipmaps for the image. + * @param useMipMaps Indicates whether to generate and use mipmaps for the image. * * @throws IllegalArgumentException if the imageSource is null. */ - public BasicWWTexture(Object imageSource, boolean useMipMaps) - { + public BasicWWTexture(Object imageSource, boolean useMipMaps) { initialize(imageSource, useMipMaps); } @@ -67,15 +65,12 @@ public BasicWWTexture(Object imageSource, boolean useMipMaps) * * @throws IllegalArgumentException if the imageSource is null. */ - public BasicWWTexture(Object imageSource) - { + public BasicWWTexture(Object imageSource) { this(imageSource, false); } - protected void initialize(Object imageSource, boolean useMipMaps) - { - if (imageSource == null) - { + protected void initialize(Object imageSource, boolean useMipMaps) { + if (imageSource == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -85,25 +80,24 @@ protected void initialize(Object imageSource, boolean useMipMaps) this.useMipMaps = useMipMaps; } - public Object getImageSource() - { + public Object getImageSource() { return imageSource; } - public int getWidth(DrawContext dc) - { - if (this.width != null) + public int getWidth(DrawContext dc) { + if (this.width != null) { return this.width; + } Texture t = this.getTexture(dc, true); return t != null ? t.getWidth() : 0; } - public int getHeight(DrawContext dc) - { - if (this.height != null) + public int getHeight(DrawContext dc) { + if (this.height != null) { return this.height; + } Texture t = this.getTexture(dc, true); @@ -113,20 +107,17 @@ public int getHeight(DrawContext dc) /** * Indicates whether the texture creates and uses mipmaps. * - * @return true if mipmaps are used, false if not. + * @return true if mipmaps are used, false if not. */ - public boolean isUseMipMaps() - { + public boolean isUseMipMaps() { return useMipMaps; } - public TextureCoords getTexCoords() - { + public TextureCoords getTexCoords() { return texCoords; } - public boolean isTextureCurrent(DrawContext dc) - { + public boolean isTextureCurrent(DrawContext dc) { return true; } @@ -135,8 +126,7 @@ public boolean isTextureCurrent(DrawContext dc) * * @return useAnisotropy true if anisotropy is to be applied, otherwise false. */ - public boolean isUseAnisotropy() - { + public boolean isUseAnisotropy() { return useAnisotropy; } @@ -145,31 +135,27 @@ public boolean isUseAnisotropy() * * @param useAnisotropy true if anisotropy is to be applied, otherwise false. */ - public void setUseAnisotropy(boolean useAnisotropy) - { + public void setUseAnisotropy(boolean useAnisotropy) { this.useAnisotropy = useAnisotropy; } - public boolean isTextureInitializationFailed() - { + public boolean isTextureInitializationFailed() { return textureInitializationFailed; } - protected Texture getTexture(DrawContext dc, boolean initialize) - { + protected Texture getTexture(DrawContext dc, boolean initialize) { Texture t = this.getTextureFromCache(dc); - if (t == null && initialize) + if (t == null && initialize) { t = this.initializeTexture(dc, this.imageSource); + } return t; } - protected Texture getTextureFromCache(DrawContext dc) - { + protected Texture getTextureFromCache(DrawContext dc) { Texture t = dc.getTextureCache().getTexture(this.imageSource); - if (t != null && this.width == null) - { + if (t != null && this.width == null) { this.width = t.getWidth(); this.height = t.getHeight(); this.texCoords = t.getImageTexCoords(); @@ -178,28 +164,26 @@ protected Texture getTextureFromCache(DrawContext dc) return t; } - public boolean bind(DrawContext dc) - { - if (dc == null) - { + public boolean bind(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } Texture t = this.getTextureFromCache(dc); - if (t == null) - { + if (t == null) { t = this.initializeTexture(dc, this.imageSource); - if (t != null) + if (t != null) { return true; // texture was bound during initialization. + } } - if (t != null) + if (t != null) { t.bind(dc.getGL()); + } - if (t != null && this.width == 0 && this.height == 0) - { + if (t != null && this.width == 0 && this.height == 0) { this.width = t.getWidth(); this.height = t.getHeight(); this.texCoords = t.getImageTexCoords(); @@ -208,10 +192,8 @@ public boolean bind(DrawContext dc) return t != null; } - public void applyInternalTransform(DrawContext dc) - { - if (dc == null) - { + public void applyInternalTransform(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -219,13 +201,12 @@ public void applyInternalTransform(DrawContext dc) // Use the tile's texture if available. Texture t = this.getTextureFromCache(dc); - if (t == null) + if (t == null) { t = this.initializeTexture(dc, this.imageSource); + } - if (t != null) - { - if (t.getMustFlipVertically()) - { + if (t != null) { + if (t.getMustFlipVertically()) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glMatrixMode(GL2.GL_TEXTURE); gl.glLoadIdentity(); @@ -235,77 +216,62 @@ public void applyInternalTransform(DrawContext dc) } } - protected Texture initializeTexture(DrawContext dc, Object imageSource) - { - if (dc == null) - { + protected Texture initializeTexture(DrawContext dc, Object imageSource) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.textureInitializationFailed) + if (this.textureInitializationFailed) { return null; + } Texture t; boolean haveMipMapData; GL gl = dc.getGL(); - if (imageSource instanceof String) - { + if (imageSource instanceof String) { String path = (String) imageSource; Object streamOrException = WWIO.getFileOrResourceAsStream(path, this.getClass()); - if (streamOrException == null || streamOrException instanceof Exception) - { + if (streamOrException == null || streamOrException instanceof Exception) { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionAttemptingToReadImageFile", - streamOrException != null ? streamOrException : path); + streamOrException != null ? streamOrException : path); this.textureInitializationFailed = true; return null; } - try - { + try { TextureData td = OGLUtil.newTextureData(gl.getGLProfile(), (InputStream) streamOrException, - this.useMipMaps); + this.useMipMaps); t = TextureIO.newTexture(td); haveMipMapData = td.getMipmapData() != null; - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("layers.TextureLayer.ExceptionAttemptingToReadTextureFile", - imageSource); + imageSource); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.textureInitializationFailed = true; return null; } - } - else if (imageSource instanceof BufferedImage) - { - try - { + } else if (imageSource instanceof BufferedImage) { + try { TextureData td = AWTTextureIO.newTextureData(gl.getGLProfile(), (BufferedImage) imageSource, - this.useMipMaps); + this.useMipMaps); t = TextureIO.newTexture(td); haveMipMapData = td.getMipmapData() != null; - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.IOExceptionDuringTextureInitialization"); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.textureInitializationFailed = true; return null; } - } - else if (imageSource instanceof URL) - { - try - { + } else if (imageSource instanceof URL) { + try { InputStream stream = ((URL) imageSource).openStream(); - if (stream == null) - { + if (stream == null) { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionAttemptingToReadImageFile", - imageSource); + imageSource); this.textureInitializationFailed = true; return null; } @@ -313,20 +279,16 @@ else if (imageSource instanceof URL) TextureData td = OGLUtil.newTextureData(gl.getGLProfile(), stream, this.useMipMaps); t = TextureIO.newTexture(td); haveMipMapData = td.getMipmapData() != null; - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("layers.TextureLayer.ExceptionAttemptingToReadTextureFile", - imageSource); + imageSource); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.textureInitializationFailed = true; return null; } - } - else - { + } else { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.UnrecognizedImageSourceType", - imageSource.getClass().getName()); + imageSource.getClass().getName()); this.textureInitializationFailed = true; return null; } @@ -334,7 +296,7 @@ else if (imageSource instanceof URL) if (t == null) // In case JOGL TextureIO returned null { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.TextureUnreadable", - imageSource instanceof String ? imageSource : imageSource.getClass().getName()); + imageSource instanceof String ? imageSource : imageSource.getClass().getName()); this.textureInitializationFailed = true; return null; } @@ -348,16 +310,14 @@ else if (imageSource instanceof URL) // enabled, and the texture itself supports mip-mapping. boolean useMipMapFilter = this.useMipMaps && (haveMipMapData || t.isUsingAutoMipmapGeneration()); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, - useMipMapFilter ? GL.GL_LINEAR_MIPMAP_LINEAR : GL.GL_LINEAR); + useMipMapFilter ? GL.GL_LINEAR_MIPMAP_LINEAR : GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); - if (this.isUseAnisotropy() && useMipMapFilter) - { + if (this.isUseAnisotropy() && useMipMapFilter) { double maxAnisotropy = dc.getGLRuntimeCapabilities().getMaxTextureAnisotropy(); - if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) - { + if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) { gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, (float) maxAnisotropy); } } diff --git a/src/gov/nasa/worldwind/render/Box.java b/src/gov/nasa/worldwind/render/Box.java index 918ffea27e..166b0dce49 100644 --- a/src/gov/nasa/worldwind/render/Box.java +++ b/src/gov/nasa/worldwind/render/Box.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -25,8 +24,8 @@ * @author ccrick * @version $Id: Box.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Box extends RigidShape -{ +public class Box extends RigidShape { + protected static final int DEFAULT_SUBDIVISIONS = 0; @SuppressWarnings({"FieldCanBeLocal"}) @@ -40,33 +39,31 @@ public class Box extends RigidShape // face 5: bottom face protected int subdivisions = DEFAULT_SUBDIVISIONS; - /** Construct a box with default parameters */ - public Box() - { + /** + * Construct a box with default parameters + */ + public Box() { this.setUpGeometryCache(); } /** * Construct a box from a specified center position and axes lengths. * - * @param centerPosition the box's center position. + * @param centerPosition the box's center position. * @param northSouthRadius the box's north-south radius, in meters. - * @param verticalRadius the box's vertical radius, in meters. - * @param eastWestRadius the box's east-west radius, in meters. + * @param verticalRadius the box's vertical radius, in meters. + * @param eastWestRadius the box's east-west radius, in meters. * * @throws IllegalArgumentException if the center position is null or any of the radii are not greater than 0. */ - public Box(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) - { - if (centerPosition == null) - { + public Box(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -83,26 +80,23 @@ public Box(Position centerPosition, double northSouthRadius, double verticalRadi * Construct a Box from a specified center position, axes lengths and rotation angles. All angles are specified in * degrees and positive angles are counter-clockwise. * - * @param centerPosition the Box's center position. + * @param centerPosition the Box's center position. * @param northSouthRadius the Box's north-south radius, in meters. - * @param verticalRadius the Box's vertical radius, in meters. - * @param eastWestRadius the Box's east-west radius, in meters. - * @param heading the Box's azimuth, its rotation about its vertical axis. - * @param tilt the Box pitch, its rotation about its east-west axis. - * @param roll the Box's roll, its rotation about its north-south axis. + * @param verticalRadius the Box's vertical radius, in meters. + * @param eastWestRadius the Box's east-west radius, in meters. + * @param heading the Box's azimuth, its rotation about its vertical axis. + * @param tilt the Box pitch, its rotation about its east-west axis. + * @param roll the Box's roll, its rotation about its north-south axis. */ public Box(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius, - Angle heading, Angle tilt, Angle roll) - { - if (centerPosition == null) - { + Angle heading, Angle tilt, Angle roll) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -120,13 +114,11 @@ public Box(Position centerPosition, double northSouthRadius, double verticalRadi } @Override - public int getFaceCount() - { + public int getFaceCount() { return this.faceCount; } - public int getSubdivisions() - { + public int getSubdivisions() { return this.subdivisions; } @@ -134,48 +126,44 @@ public int getSubdivisions() * Computes the number of subdivisions necessary to achieve the expected Level of Detail given the shape's * relationship to the viewer. * - * @param dc the current drawContext. + * @param dc the current drawContext. * @param shapeData the current globe-specific shape data */ - protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) - { + protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) { } //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - /** * Sets the Geometry mesh for this Box, either by pulling it from the geometryCache, or by creating it anew if the * appropriate geometry does not yet exist in the cache. * * @param shapeData this shape's current shape data. */ - protected void makeGeometry(ShapeData shapeData) - { + protected void makeGeometry(ShapeData shapeData) { // attempt to retrieve a cached unit box with the same number of subdivisions Object cacheKey = new Geometry.CacheKey(this.getClass(), "Box0", this.subdivisions); Geometry geom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null) - { + if (geom == null) { // if none exists, create a new one makeUnitBox(this.subdivisions, shapeData.getMeshes()); - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } // add the new mesh pieces to the cache cacheKey = new Geometry.CacheKey(this.getClass(), "Box" + piece, this.subdivisions); this.getGeometryCache().add(cacheKey, shapeData.getMesh(piece)); } - } - else - { + } else { // otherwise, just use the one from the cache - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } cacheKey = new Geometry.CacheKey(this.getClass(), "Box" + piece, this.subdivisions); geom = (Geometry) this.getGeometryCache().getObject(cacheKey); shapeData.addMesh(piece, geom); @@ -188,7 +176,7 @@ protected void makeGeometry(ShapeData shapeData) * the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit box geometry - * @param dest the Geometry container to hold the computed points, etc. + * @param dest the Geometry container to hold the computed points, etc. */ /* protected void makeUnitBox(int subdivisions, Geometry dest) @@ -213,28 +201,25 @@ protected void makeUnitBox(int subdivisions, Geometry dest) dest.setNormalData(normalBuffer.limit(), normalBuffer); dest.setTextureCoordData(textureCoordBuffer.limit(), textureCoordBuffer); } - */ - + */ /** * Generates a unit box geometry, including the vertices, indices, normals and texture coordinates, tessellated with * the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit box geometry - * @param meshes the Geometry list to hold the computed points, etc. for all Geometries + * @param meshes the Geometry list to hold the computed points, etc. for all Geometries */ - protected void makeUnitBox(int subdivisions, List meshes) - { + protected void makeUnitBox(int subdivisions, List meshes) { float radius = 1.0f; Geometry dest; GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(GeometryBuilder.OUTSIDE); - for (int index = 0; index < getFaceCount(); index++) - { + for (int index = 0; index < getFaceCount(); index++) { // create box in model space - GeometryBuilder.IndexedTriangleBuffer itb = - gb.tessellateBoxBuffer(index, radius, subdivisions); + GeometryBuilder.IndexedTriangleBuffer itb + = gb.tessellateBoxBuffer(index, radius, subdivisions); FloatBuffer normalBuffer = Buffers.newDirectFloatBuffer(3 * itb.getVertexCount()); gb.makeIndexedTriangleBufferNormals(itb, normalBuffer); @@ -256,18 +241,16 @@ protected void makeUnitBox(int subdivisions, List meshes) /** * Renders the Box, using data from the provided buffer and the given parameters. * - * @param dc the current draw context - * @param mode the render mode - * @param count the number of elements to be drawn - * @param type the data type of the elements to be drawn + * @param dc the current draw context + * @param mode the render mode + * @param count the number of elements to be drawn + * @param type the data type of the elements to be drawn * @param elementBuffer the buffer containing the list of elements to be drawn - * @param shapeData this shape's current globe-specific shape data + * @param shapeData this shape's current globe-specific shape data */ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffer elementBuffer, - ShapeData shapeData, int face) - { - if (elementBuffer == null) - { + ShapeData shapeData, int face) { + if (elementBuffer == null) { String message = "nullValue.ElementBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -275,8 +258,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe Geometry mesh = shapeData.getMesh(face); - if (mesh.getBuffer(Geometry.VERTEX) == null) - { + if (mesh.getBuffer(Geometry.VERTEX) == null) { String message = "nullValue.VertexBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -293,17 +275,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe vertexBuffer = mesh.getBuffer(Geometry.VERTEX); normalBuffer = null; - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { normalBuffer = mesh.getBuffer(Geometry.NORMAL); - if (normalBuffer == null) - { + if (normalBuffer == null) { gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); - } - else - { + } else { glType = mesh.getGLType(Geometry.NORMAL); stride = mesh.getStride(Geometry.NORMAL); gl.glNormalPointer(glType, stride, normalBuffer); @@ -314,14 +291,11 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // cull the back face //gl.glEnable(GL.GL_CULL_FACE); //gl.glFrontFace(GL.GL_CCW); - // Testing: disable VBO's // boolean vboState = dc.getGLRuntimeCapabilities().isVertexBufferObjectEnabled(); // dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(true); - // decide whether to draw with VBO's or VA's - if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) - { + if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) { // render using VBO's gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getVboIds(getSubdivisions(), dc)[2 * face]); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, this.getVboIds(getSubdivisions(), dc)[2 * face + 1]); @@ -331,9 +305,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); - } - else - { + } else { // render using vertex arrays gl.glVertexPointer(size, glType, stride, vertexBuffer.rewind()); gl.glDrawElements(mode, count, type, elementBuffer); @@ -344,24 +316,20 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // Testing: restore VBO state // dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(false); - // disable back face culling // gl.glDisable(GL.GL_CULL_FACE); - - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { // re-enable normals if we temporarily turned them off earlier - if (normalBuffer == null) + if (normalBuffer == null) { gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); + } } // this.logGeometryStatistics(dc, geom); } } - protected ShapeData createIntersectionGeometry(Terrain terrain) - { + protected ShapeData createIntersectionGeometry(Terrain terrain) { // TODO: add error checking ShapeData shapeData = new ShapeData(null, this); @@ -372,36 +340,34 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) Matrix matrix = computeRenderMatrix(terrain.getGlobe(), terrain.getVerticalExaggeration()); - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { mesh = shapeData.getMesh(i); // transform the vertices from local to world coords FloatBuffer newVertices = computeTransformedVertices((FloatBuffer) mesh.getBuffer(Geometry.VERTEX), - mesh.getCount(Geometry.VERTEX), matrix); + mesh.getCount(Geometry.VERTEX), matrix); mesh.setVertexData(mesh.getCount(Geometry.VERTEX), newVertices); } shapeData.setReferencePoint(this.computeReferencePoint(terrain.getGlobe(), - terrain.getVerticalExaggeration())); + terrain.getVerticalExaggeration())); shapeData.setExtent(getExtent(terrain.getGlobe(), terrain.getVerticalExaggeration())); return shapeData; } - /** No export formats supported. */ + /** + * No export formats supported. + */ @Override - public String isExportFormatSupported(String mimeType) - { + public String isExportFormatSupported(String mimeType) { // Overridden because this shape does not support export to KML. return Exportable.FORMAT_NOT_SUPPORTED; } @Override - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { String message = Logging.getMessage("generic.UnsupportedOperation", "doExportAsKML"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } } - diff --git a/src/gov/nasa/worldwind/render/Cone.java b/src/gov/nasa/worldwind/render/Cone.java index 1ed507fee6..df4782fb0c 100644 --- a/src/gov/nasa/worldwind/render/Cone.java +++ b/src/gov/nasa/worldwind/render/Cone.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -25,8 +24,8 @@ * @author ccrick * @version $Id: Cone.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Cone extends RigidShape -{ +public class Cone extends RigidShape { + protected static final int DEFAULT_SUBDIVISIONS = 2; // Geometry. @@ -37,9 +36,10 @@ public class Cone extends RigidShape // face 1: Cone pointed core protected int subdivisions = DEFAULT_SUBDIVISIONS; - /** Construct a cone with default parameters */ - public Cone() - { + /** + * Construct a cone with default parameters + */ + public Cone() { this.setUpGeometryCache(); } @@ -47,29 +47,25 @@ public Cone() * Constructs a Cone from a specified center position, height and radius. * * @param centerPosition the Cone's center position. - * @param height the Cone's height, in meters. - * @param radius the radius of the Cone's base, in meters. + * @param height the Cone's height, in meters. + * @param radius the radius of the Cone's base, in meters. * * @throws IllegalArgumentException if the center position is null or any of the radii are not greater than 0. */ - public Cone(Position centerPosition, double height, double radius) - { - if (centerPosition == null) - { + public Cone(Position centerPosition, double height, double radius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius <= 0) - { + if (radius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -86,24 +82,21 @@ public Cone(Position centerPosition, double height, double radius) /** * Constructs a cone from a specified center position and axes lengths. * - * @param centerPosition the cone's center position. + * @param centerPosition the cone's center position. * @param northSouthRadius the cone's north-south radius, in meters. - * @param verticalRadius the cone's vertical radius, in meters. - * @param eastWestRadius the cone's east-west radius, in meters. + * @param verticalRadius the cone's vertical radius, in meters. + * @param eastWestRadius the cone's east-west radius, in meters. * * @throws IllegalArgumentException if the center position is null or any of the radii are not greater than 0. */ - public Cone(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) - { - if (centerPosition == null) - { + public Cone(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -120,26 +113,23 @@ public Cone(Position centerPosition, double northSouthRadius, double verticalRad * Constructs a cone from a specified center position, axes lengths and rotation angles. All angles are specified in * degrees and positive angles are counter-clockwise. * - * @param centerPosition the cone's center position. + * @param centerPosition the cone's center position. * @param northSouthRadius the cone's north-south radius, in meters. - * @param verticalRadius the cone's vertical radius, in meters. - * @param eastWestRadius the cone's east-west radius, in meters. - * @param heading the cone's azimuth, its rotation about its vertical axis. - * @param tilt the cone pitch, its rotation about its east-west axis. - * @param roll the cone's roll, its rotation about its north-south axis. + * @param verticalRadius the cone's vertical radius, in meters. + * @param eastWestRadius the cone's east-west radius, in meters. + * @param heading the cone's azimuth, its rotation about its vertical axis. + * @param tilt the cone pitch, its rotation about its east-west axis. + * @param roll the cone's roll, its rotation about its north-south axis. */ public Cone(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius, - Angle heading, Angle tilt, Angle roll) - { - if (centerPosition == null) - { + Angle heading, Angle tilt, Angle roll) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -157,13 +147,11 @@ public Cone(Position centerPosition, double northSouthRadius, double verticalRad } @Override - public int getFaceCount() - { + public int getFaceCount() { return this.faceCount; } - public int getSubdivisions() - { + public int getSubdivisions() { return this.subdivisions; } @@ -172,8 +160,7 @@ public int getSubdivisions() * * @return the detailThreshold */ - protected double computeDetailThreshold() - { + protected double computeDetailThreshold() { // these values must be calibrated on a shape-by-shape basis double detailThreshold = 20; double rangeDetailThreshold = 40; @@ -187,47 +174,44 @@ protected double computeDetailThreshold() * Computes the number of subdivisions necessary to achieve the expected Level of Detail given the shape's * relationship to the viewer. * - * @param dc the current drawContext. + * @param dc the current drawContext. * @param shapeData the current globe-specific shape data */ - protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) - { + protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) { // test again possible subdivision values int minDivisions = 0; int maxDivisions = 6; - if (shapeData.getExtent() != null) - { - for (int divisions = minDivisions; divisions <= maxDivisions; divisions++) - { + if (shapeData.getExtent() != null) { + for (int divisions = minDivisions; divisions <= maxDivisions; divisions++) { this.subdivisions = divisions; - if (this.sufficientDetail(dc, divisions, shapeData)) + if (this.sufficientDetail(dc, divisions, shapeData)) { break; + } } } } - protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData shapeData) - { - if (dc.getView() == null) - { + protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData shapeData) { + if (dc.getView() == null) { String message = "nullValue.DrawingContextViewIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (shapeData == null) + if (shapeData == null) { return false; + } Extent extent = shapeData.getExtent(); - if (extent == null) + if (extent == null) { return true; + } double thresholdDensity = this.computeDetailThreshold(); @@ -240,13 +224,13 @@ protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData s return vertexDensity > thresholdDensity; } - protected boolean mustRegenerateGeometry(DrawContext dc) - { + protected boolean mustRegenerateGeometry(DrawContext dc) { // check if current LOD is sufficient int oldDivisions = this.subdivisions; computeSubdivisions(dc, this.getCurrentShapeData()); - if (oldDivisions != this.subdivisions) + if (oldDivisions != this.subdivisions) { return true; + } return super.mustRegenerateGeometry(dc); } @@ -254,38 +238,35 @@ protected boolean mustRegenerateGeometry(DrawContext dc) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - /** * Sets the Geometry mesh for this cone, either by pulling it from the geometryCache, or by creating it anew if the * appropriate geometry does not yet exist in the cache. * * @param shapeData this shape's current shape data. */ - protected void makeGeometry(ShapeData shapeData) - { + protected void makeGeometry(ShapeData shapeData) { // attempt to retrieve a cached unit box with the same number of subdivisions Object cacheKey = new Geometry.CacheKey(this.getClass(), "Cone0", this.subdivisions); Geometry geom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null) - { + if (geom == null) { // if none exists, create a new one makeUnitCone(this.subdivisions, shapeData.getMeshes()); - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } // add the new mesh pieces to the cache cacheKey = new Geometry.CacheKey(this.getClass(), "Cone" + piece, this.subdivisions); this.getGeometryCache().add(cacheKey, shapeData.getMesh(piece)); } - } - else - { + } else { // otherwise, just use the one from the cache - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } cacheKey = new Geometry.CacheKey(this.getClass(), "Cone" + piece, this.subdivisions); geom = (Geometry) this.getGeometryCache().getObject(cacheKey); shapeData.addMesh(piece, geom); @@ -298,7 +279,7 @@ protected void makeGeometry(ShapeData shapeData) * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit cone geometry - * @param dest the Geometry container to hold the computed points, etc. + * @param dest the Geometry container to hold the computed points, etc. */ /* protected void makeUnitCone(int subdivisions, Geometry dest) @@ -323,28 +304,25 @@ protected void makeUnitCone(int subdivisions, Geometry dest) dest.setNormalData(normalBuffer.limit(), normalBuffer); dest.setTextureCoordData(textureCoordBuffer.limit(), textureCoordBuffer); } - */ - + */ /** * Generates a unit cone geometry, including the vertices, indices, normals and texture coordinates, tessellated * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit cone geometry - * @param meshes the Geometry list to hold the computed points, etc. for all Geometries + * @param meshes the Geometry list to hold the computed points, etc. for all Geometries */ - protected void makeUnitCone(int subdivisions, List meshes) - { + protected void makeUnitCone(int subdivisions, List meshes) { float radius = 1.0f; Geometry dest; GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(GeometryBuilder.OUTSIDE); - for (int index = 0; index < getFaceCount(); index++) - { + for (int index = 0; index < getFaceCount(); index++) { // create box in model space - GeometryBuilder.IndexedTriangleBuffer itb = - gb.tessellateConeBuffer(index, radius, subdivisions); + GeometryBuilder.IndexedTriangleBuffer itb + = gb.tessellateConeBuffer(index, radius, subdivisions); FloatBuffer normalBuffer = Buffers.newDirectFloatBuffer(3 * itb.getVertexCount()); gb.makeIndexedTriangleBufferNormals(itb, normalBuffer); @@ -366,18 +344,16 @@ protected void makeUnitCone(int subdivisions, List meshes) /** * Renders the cone, using data from the provided buffer and the given parameters. * - * @param dc the current draw context - * @param mode the render mode - * @param count the number of elements to be drawn - * @param type the data type of the elements to be drawn + * @param dc the current draw context + * @param mode the render mode + * @param count the number of elements to be drawn + * @param type the data type of the elements to be drawn * @param elementBuffer the buffer containing the list of elements to be drawn - * @param shapeData this shape's current globe-specific shape data + * @param shapeData this shape's current globe-specific shape data */ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffer elementBuffer, - ShapeData shapeData, int face) - { - if (elementBuffer == null) - { + ShapeData shapeData, int face) { + if (elementBuffer == null) { String message = "nullValue.ElementBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -385,8 +361,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe Geometry mesh = shapeData.getMesh(face); - if (mesh.getBuffer(Geometry.VERTEX) == null) - { + if (mesh.getBuffer(Geometry.VERTEX) == null) { String message = "nullValue.VertexBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -403,17 +378,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe vertexBuffer = mesh.getBuffer(Geometry.VERTEX); normalBuffer = null; - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { normalBuffer = mesh.getBuffer(Geometry.NORMAL); - if (normalBuffer == null) - { + if (normalBuffer == null) { gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); - } - else - { + } else { glType = mesh.getGLType(Geometry.NORMAL); stride = mesh.getStride(Geometry.NORMAL); gl.glNormalPointer(glType, stride, normalBuffer); @@ -424,14 +394,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // cull the back face //gl.glEnable(GL.GL_CULL_FACE); //gl.glFrontFace(GL.GL_CCW); - // testing boolean vboState = dc.getGLRuntimeCapabilities().isVertexBufferObjectEnabled(); //dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(true); // decide whether to draw with VBO's or VA's - if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) - { + if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) { // render using VBO's gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getVboIds(getSubdivisions(), dc)[2 * face]); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, this.getVboIds(getSubdivisions(), dc)[2 * face + 1]); @@ -441,9 +409,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); - } - else - { + } else { // render using vertex arrays gl.glVertexPointer(size, glType, stride, vertexBuffer.rewind()); gl.glDrawElements(mode, count, type, elementBuffer); @@ -454,23 +420,20 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // disable back face culling // gl.glDisable(GL.GL_CULL_FACE); - dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(vboState); - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { // re-enable normals if we temporarily turned them off earlier - if (normalBuffer == null) + if (normalBuffer == null) { gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); + } } // this.logGeometryStatistics(dc, geom); } } - protected ShapeData createIntersectionGeometry(Terrain terrain) - { + protected ShapeData createIntersectionGeometry(Terrain terrain) { ShapeData shapeData = new ShapeData(null, this); shapeData.setGlobeStateKey(terrain.getGlobe().getGlobeStateKey()); Geometry mesh; @@ -480,33 +443,32 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) // transform the vertices from local to world coords Matrix matrix = computeRenderMatrix(terrain.getGlobe(), terrain.getVerticalExaggeration()); - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { mesh = shapeData.getMesh(i); // transform the vertices from local to world coords FloatBuffer newVertices = computeTransformedVertices((FloatBuffer) mesh.getBuffer(Geometry.VERTEX), - mesh.getCount(Geometry.VERTEX), matrix); + mesh.getCount(Geometry.VERTEX), matrix); mesh.setVertexData(mesh.getCount(Geometry.VERTEX), newVertices); } shapeData.setReferencePoint(this.computeReferencePoint(terrain.getGlobe(), - terrain.getVerticalExaggeration())); + terrain.getVerticalExaggeration())); shapeData.setExtent(getExtent(terrain.getGlobe(), terrain.getVerticalExaggeration())); return shapeData; } - /** No export formats supported. */ + /** + * No export formats supported. + */ @Override - public String isExportFormatSupported(String mimeType) - { + public String isExportFormatSupported(String mimeType) { // Overridden because this shape does not support export to KML. return Exportable.FORMAT_NOT_SUPPORTED; } @Override - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { String message = Logging.getMessage("generic.UnsupportedOperation", "doExportAsKML"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); diff --git a/src/gov/nasa/worldwind/render/ContourLine.java b/src/gov/nasa/worldwind/render/ContourLine.java index 864e7f25f2..4fa310c793 100644 --- a/src/gov/nasa/worldwind/render/ContourLine.java +++ b/src/gov/nasa/worldwind/render/ContourLine.java @@ -20,8 +20,8 @@ * @author Patrick Murris * @version $Id: ContourLine.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ContourLine implements Renderable -{ +public class ContourLine implements Renderable { + private double elevation; private Sector sector; private Color color = Color.CYAN; @@ -37,26 +37,21 @@ public class ContourLine implements Renderable // Segments connection criteria protected int maxConnectingDistance = 10; // meters - public ContourLine() - { + public ContourLine() { this(0, Sector.FULL_SPHERE); } - public ContourLine(double elevation) - { + public ContourLine(double elevation) { this(elevation, Sector.FULL_SPHERE); } - @SuppressWarnings( {"UnusedDeclaration"}) - public ContourLine(Sector sector) - { + @SuppressWarnings({"UnusedDeclaration"}) + public ContourLine(Sector sector) { this(0, sector); } - public ContourLine(double elevation, Sector sector) - { - if (sector == null) - { + public ContourLine(double elevation, Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -71,8 +66,7 @@ public ContourLine(double elevation, Sector sector) * * @return the contour line current elevation. */ - public double getElevation() - { + public double getElevation() { return this.elevation; } @@ -81,10 +75,8 @@ public double getElevation() * * @param elevation the contour line elevation. */ - public void setElevation(double elevation) - { - if (this.elevation != elevation) - { + public void setElevation(double elevation) { + if (this.elevation != elevation) { this.elevation = elevation; this.update(); } @@ -95,8 +87,7 @@ public void setElevation(double elevation) * * @return the contour line current bounding sector. */ - public Sector getSector() - { + public Sector getSector() { return this.sector; } @@ -105,17 +96,14 @@ public Sector getSector() * * @param sector the contour line bounding sector. */ - public void setSector(Sector sector) - { - if (sector == null) - { + public void setSector(Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.sector.equals(sector)) - { + if (!this.sector.equals(sector)) { this.sector = sector; this.update(); } @@ -126,8 +114,7 @@ public void setSector(Sector sector) * * @return the contour line color. */ - public Color getColor() - { + public Color getColor() { return this.color; } @@ -136,22 +123,19 @@ public Color getColor() * * @param color the contour line color. */ - public void setColor(Color color) - { - if (color == null) - { + public void setColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.color.equals(color)) - { + if (!this.color.equals(color)) { this.color = color; - for (Renderable r : this.getRenderables()) - { - if (r instanceof Polyline) + for (Renderable r : this.getRenderables()) { + if (r instanceof Polyline) { ((Polyline) r).setColor(color); + } } } } @@ -161,8 +145,7 @@ public void setColor(Color color) * * @return the contour line width. */ - public double getLineWidth() - { + public double getLineWidth() { return this.lineWidth; } @@ -171,26 +154,22 @@ public double getLineWidth() * * @param width the contour line width. */ - public void setLineWidth(double width) - { - if (this.lineWidth != width) - { + public void setLineWidth(double width) { + if (this.lineWidth != width) { this.lineWidth = width; - for (Renderable r : this.getRenderables()) - { - if (r instanceof Polyline) + for (Renderable r : this.getRenderables()) { + if (r instanceof Polyline) { ((Polyline) r).setLineWidth(width); + } } } } - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean state) - { + public void setEnabled(boolean state) { this.enabled = state; } @@ -199,8 +178,7 @@ public void setEnabled(boolean state) * * @return true if view volume clipping is performed, otherwise false (the default). */ - public boolean isViewClippingEnabled() - { + public boolean isViewClippingEnabled() { return viewClippingEnabled; } @@ -208,57 +186,54 @@ public boolean isViewClippingEnabled() * Set whether view volume clipping is performed. * * @param viewClippingEnabled true if view clipping should be performed, otherwise false - * (the default). + * (the default). */ - @SuppressWarnings( {"UnusedDeclaration"}) - public void setViewClippingEnabled(boolean viewClippingEnabled) - { + @SuppressWarnings({"UnusedDeclaration"}) + public void setViewClippingEnabled(boolean viewClippingEnabled) { this.viewClippingEnabled = viewClippingEnabled; } - /** Update the contour line according to the current terrain geometry. */ - public void update() - { + /** + * Update the contour line according to the current terrain geometry. + */ + public void update() { this.expirySupport.setExpired(true); } - public List getRenderables() - { + public List getRenderables() { return this.renderables; } - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.isEnabled()) + if (!this.isEnabled()) { return; + } - if (!this.getSector().intersects(dc.getVisibleSector())) + if (!this.getSector().intersects(dc.getVisibleSector())) { return; + } - if (!this.isValid(dc)) - { + if (!this.isValid(dc)) { makeContourLine(dc); this.expirySupport.restart(dc); this.globeStateKey = dc.getGlobe().getGlobeStateKey(dc); } - for (Renderable r : this.getRenderables()) - { + for (Renderable r : this.getRenderables()) { r.render(dc); } } - protected boolean isValid(DrawContext dc) - { - if (this.expirySupport.isExpired(dc)) + protected boolean isValid(DrawContext dc) { + if (this.expirySupport.isExpired(dc)) { return false; + } return this.globeStateKey != null && this.globeStateKey.equals(dc.getGlobe().getStateKey(dc)); } @@ -268,10 +243,8 @@ protected boolean isValid(DrawContext dc) * * @param dc the current DrawContext. */ - protected void makeContourLine(DrawContext dc) - { - if (dc == null) - { + protected void makeContourLine(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -283,14 +256,14 @@ protected void makeContourLine(DrawContext dc) double ve = dc.getVerticalExaggeration(); Intersection[] interArray = dc.getSurfaceGeometry().intersect(this.getElevation() * ve, this.getSector()); - if (interArray != null) - { + if (interArray != null) { ArrayList inter = new ArrayList( - Arrays.asList(interArray)); + Arrays.asList(interArray)); // Filter intersection segment list - if (isViewClippingEnabled()) + if (isViewClippingEnabled()) { inter = filterIntersectionsOnViewFrustum(dc, inter); + } inter = filterIntersections(dc, inter); // Create polyline segments @@ -301,23 +274,20 @@ protected void makeContourLine(DrawContext dc) /** * Filters the given intersection segments list according to the current view frustum. * - * @param dc the current DrawContext + * @param dc the current DrawContext * @param list the list of Intersection to be filtered. * * @return the filtered list. */ - protected ArrayList filterIntersectionsOnViewFrustum(DrawContext dc, ArrayList list) - { + protected ArrayList filterIntersectionsOnViewFrustum(DrawContext dc, ArrayList list) { Frustum vf = dc.getView().getFrustumInModelCoordinates(); int i = 0; - while (i < list.size()) - { + while (i < list.size()) { if (vf.contains(list.get(i).getIntersectionPoint()) - || vf.contains(list.get(i + 1).getIntersectionPoint())) - // Keep segment - i += 2; - else + || vf.contains(list.get(i + 1).getIntersectionPoint())) // Keep segment { + i += 2; + } else { // Remove segment list.remove(i); list.remove(i); @@ -330,27 +300,25 @@ protected ArrayList filterIntersectionsOnViewFrustum(DrawContext d * Filters the given intersection segments list according to some criteria - here the inclusion inside the bounding * sector. * - * @param dc the current DrawContext + * @param dc the current DrawContext * @param list the list of Intersection to be filtered. * * @return the filtered list. */ - protected ArrayList filterIntersections(DrawContext dc, ArrayList list) - { - if (getSector().equals(Sector.FULL_SPHERE)) + protected ArrayList filterIntersections(DrawContext dc, ArrayList list) { + if (getSector().equals(Sector.FULL_SPHERE)) { return list; + } Globe globe = dc.getGlobe(); Sector s = getSector(); int i = 0; - while (i < list.size()) - { + while (i < list.size()) { if (s.contains(globe.computePositionFromPoint(list.get(i).getIntersectionPoint())) - && s.contains(globe.computePositionFromPoint(list.get(i + 1).getIntersectionPoint()))) - // Keep segment - i += 2; - else + && s.contains(globe.computePositionFromPoint(list.get(i + 1).getIntersectionPoint()))) // Keep segment { + i += 2; + } else { // Remove segment list.remove(i); list.remove(i); @@ -363,24 +331,23 @@ protected ArrayList filterIntersections(DrawContext dc, ArrayList< * Add a set of Polyline objects to the contour line renderable list by connecting as much as possible * the segments from the given Intersection array. * - * @param dc the current DrawContext. - * @param inter the list of Intersection to sort out. + * @param dc the current DrawContext. + * @param inter the list of Intersection to sort out. * @param tolerance how far in meter can two points be considered connected. * * @return the number of Polyline objects added. */ - protected int makePolylinesConnected(DrawContext dc, ArrayList inter, int tolerance) - { - if (inter == null) + protected int makePolylinesConnected(DrawContext dc, ArrayList inter, int tolerance) { + if (inter == null) { return 0; + } Globe globe = dc.getGlobe(); Vec4 start, end, p; Polyline line; int tolerance2 = tolerance * tolerance; // distance squared in meters int count = 0; - while (inter.size() > 0) - { + while (inter.size() > 0) { ArrayList positions = new ArrayList(); // Start with first segment start = inter.remove(0).getIntersectionPoint(); @@ -388,12 +355,10 @@ protected int makePolylinesConnected(DrawContext dc, ArrayList int positions.add(globe.computePositionFromPoint(start)); positions.add(globe.computePositionFromPoint(end)); // Try to connect remaining segments - for (int i = 0; i < inter.size();) - { + for (int i = 0; i < inter.size();) { // Try segment start point p = inter.get(i).getIntersectionPoint(); - if (p.distanceToSquared3(start) < tolerance2) - { + if (p.distanceToSquared3(start) < tolerance2) { // Connect segment to start inter.remove(i); start = inter.remove(i).getIntersectionPoint(); @@ -401,8 +366,7 @@ protected int makePolylinesConnected(DrawContext dc, ArrayList int i = 0; continue; } - if (p.distanceToSquared3(end) < tolerance2) - { + if (p.distanceToSquared3(end) < tolerance2) { // Connect segment to end inter.remove(i); end = inter.remove(i).getIntersectionPoint(); @@ -412,8 +376,7 @@ protected int makePolylinesConnected(DrawContext dc, ArrayList int } // Try segment end point p = inter.get(i + 1).getIntersectionPoint(); - if (p.distanceToSquared3(start) < tolerance2) - { + if (p.distanceToSquared3(start) < tolerance2) { // Connect segment to start inter.remove(i + 1); start = inter.remove(i).getIntersectionPoint(); @@ -421,8 +384,7 @@ protected int makePolylinesConnected(DrawContext dc, ArrayList int i = 0; continue; } - if (p.distanceToSquared3(end) < tolerance2) - { + if (p.distanceToSquared3(end) < tolerance2) { // Connect segment to end inter.remove(i + 1); end = inter.remove(i).getIntersectionPoint(); diff --git a/src/gov/nasa/worldwind/render/ContourLinePolygon.java b/src/gov/nasa/worldwind/render/ContourLinePolygon.java index 499f4f58a1..c7a30da44a 100644 --- a/src/gov/nasa/worldwind/render/ContourLinePolygon.java +++ b/src/gov/nasa/worldwind/render/ContourLinePolygon.java @@ -18,22 +18,19 @@ * @author Patrick Murris * @version $Id: ContourLinePolygon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ContourLinePolygon extends ContourLine -{ +public class ContourLinePolygon extends ContourLine { + private ArrayList positions; - public ContourLinePolygon() - { + public ContourLinePolygon() { super(); } - public ContourLinePolygon(double elevation) - { + public ContourLinePolygon(double elevation) { super(elevation); } - public ContourLinePolygon(double elevation, ArrayList positions) - { + public ContourLinePolygon(double elevation, ArrayList positions) { super(elevation); this.setPositions(positions); } @@ -43,8 +40,7 @@ public ContourLinePolygon(double elevation, ArrayList position * * @return the list of {@link LatLon} that describe the current bounding polygon. */ - public List getPositions() - { + public List getPositions() { return this.positions; } @@ -56,10 +52,8 @@ public List getPositions() * * @throws IllegalArgumentException if positions is null. */ - public void setPositions(ArrayList positions) - { - if (positions == null) - { + public void setPositions(ArrayList positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -74,32 +68,30 @@ public void setPositions(ArrayList positions) * Filters the given intersection segments list according to some criteria - here the inclusion inside the current * polygon. * - * @param dc the current {@link DrawContext} + * @param dc the current {@link DrawContext} * @param list the list of {@link Intersection} to be filtered. * * @return the filtered list. */ - protected ArrayList filterIntersections(DrawContext dc, ArrayList list) - { + protected ArrayList filterIntersections(DrawContext dc, ArrayList list) { // Filter against the bounding sector first list = super.filterIntersections(dc, list); // Filter the remaining segments against the polygon - if (this.getPositions() == null) + if (this.getPositions() == null) { return list; + } Globe globe = dc.getGlobe(); int i = 0; - while (i < list.size()) - { + while (i < list.size()) { if (WWMath.isLocationInside(globe.computePositionFromPoint(list.get(i).getIntersectionPoint()), - this.positions) && - WWMath.isLocationInside(globe.computePositionFromPoint(list.get(i + 1).getIntersectionPoint()), - this.positions)) - // Keep segment - i += 2; - else + this.positions) + && WWMath.isLocationInside(globe.computePositionFromPoint(list.get(i + 1).getIntersectionPoint()), + this.positions)) // Keep segment { + i += 2; + } else { // Remove segment list.remove(i); list.remove(i); diff --git a/src/gov/nasa/worldwind/render/Cylinder.java b/src/gov/nasa/worldwind/render/Cylinder.java index a436091fd4..2ce080f73f 100644 --- a/src/gov/nasa/worldwind/render/Cylinder.java +++ b/src/gov/nasa/worldwind/render/Cylinder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -25,8 +24,8 @@ * @author ccrick * @version $Id: Cylinder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Cylinder extends RigidShape -{ +public class Cylinder extends RigidShape { + protected static final int DEFAULT_SUBDIVISIONS = 2; // Geometry. @@ -38,9 +37,10 @@ public class Cylinder extends RigidShape // face 2: rounded Cylinder wall protected int subdivisions = DEFAULT_SUBDIVISIONS; - /** Construct a cylinder with default parameters */ - public Cylinder() - { + /** + * Construct a cylinder with default parameters + */ + public Cylinder() { this.setUpGeometryCache(); } @@ -48,29 +48,25 @@ public Cylinder() * Constructs a Cylinder from a specified center position, height and radius. * * @param centerPosition the Cylinder's center position. - * @param height the Cylinder's height, in meters. - * @param radius the radius of the Cylinder's base, in meters. + * @param height the Cylinder's height, in meters. + * @param radius the radius of the Cylinder's base, in meters. * * @throws IllegalArgumentException if the center position is null or any of the radii are not greater than 0. */ - public Cylinder(Position centerPosition, double height, double radius) - { - if (centerPosition == null) - { + public Cylinder(Position centerPosition, double height, double radius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius <= 0) - { + if (radius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -87,24 +83,21 @@ public Cylinder(Position centerPosition, double height, double radius) /** * Constructs a cylinder from a specified center position and axes lengths. * - * @param centerPosition the cylinder's center position. + * @param centerPosition the cylinder's center position. * @param northSouthRadius the cylinder's north-south radius, in meters. - * @param verticalRadius the cylinder's vertical radius, in meters. - * @param eastWestRadius the cylinder's east-west radius, in meters. + * @param verticalRadius the cylinder's vertical radius, in meters. + * @param eastWestRadius the cylinder's east-west radius, in meters. * * @throws IllegalArgumentException if the center position is null or any of the radii are not greater than 0. */ - public Cylinder(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) - { - if (centerPosition == null) - { + public Cylinder(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -121,26 +114,23 @@ public Cylinder(Position centerPosition, double northSouthRadius, double vertica * Constructs a cylinder from a specified center position, axes lengths and rotation angles. All angles are * specified in degrees and positive angles are counter-clockwise. * - * @param centerPosition the cylinder's center position. + * @param centerPosition the cylinder's center position. * @param northSouthRadius the cylinder's north-south radius, in meters. - * @param verticalRadius the cylinder's vertical radius, in meters. - * @param eastWestRadius the cylinder's east-west radius, in meters. - * @param heading the cylinder's azimuth, its rotation about its vertical axis. - * @param tilt the cylinder pitch, its rotation about its east-west axis. - * @param roll the cylinder's roll, its rotation about its north-south axis. + * @param verticalRadius the cylinder's vertical radius, in meters. + * @param eastWestRadius the cylinder's east-west radius, in meters. + * @param heading the cylinder's azimuth, its rotation about its vertical axis. + * @param tilt the cylinder pitch, its rotation about its east-west axis. + * @param roll the cylinder's roll, its rotation about its north-south axis. */ public Cylinder(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius, - Angle heading, Angle tilt, Angle roll) - { - if (centerPosition == null) - { + Angle heading, Angle tilt, Angle roll) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -158,13 +148,11 @@ public Cylinder(Position centerPosition, double northSouthRadius, double vertica } @Override - public int getFaceCount() - { + public int getFaceCount() { return this.faceCount; } - public int getSubdivisions() - { + public int getSubdivisions() { return this.subdivisions; } @@ -173,8 +161,7 @@ public int getSubdivisions() * * @return the detailThreshold */ - protected double computeDetailThreshold() - { + protected double computeDetailThreshold() { // these values must be calibrated on a shape-by-shape basis double detailThreshold = 20; double rangeDetailThreshold = 40; @@ -188,47 +175,44 @@ protected double computeDetailThreshold() * Computes the number of subdivisions necessary to achieve the expected Level of Detail given the shape's * relationship to the viewer. * - * @param dc the current drawContext. + * @param dc the current drawContext. * @param shapeData the current globe-specific shape data */ - protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) - { + protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) { // test again possible subdivision values int minDivisions = 0; int maxDivisions = 6; - if (shapeData.getExtent() != null) - { - for (int divisions = minDivisions; divisions <= maxDivisions; divisions++) - { + if (shapeData.getExtent() != null) { + for (int divisions = minDivisions; divisions <= maxDivisions; divisions++) { this.subdivisions = divisions; - if (this.sufficientDetail(dc, divisions, shapeData)) + if (this.sufficientDetail(dc, divisions, shapeData)) { break; + } } } } - protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData shapeData) - { - if (dc.getView() == null) - { + protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData shapeData) { + if (dc.getView() == null) { String message = "nullValue.DrawingContextViewIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (shapeData == null) + if (shapeData == null) { return false; + } Extent extent = shapeData.getExtent(); - if (extent == null) + if (extent == null) { return true; + } double thresholdDensity = this.computeDetailThreshold(); @@ -241,13 +225,13 @@ protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData s return vertexDensity > thresholdDensity; } - protected boolean mustRegenerateGeometry(DrawContext dc) - { + protected boolean mustRegenerateGeometry(DrawContext dc) { // check if current LOD is sufficient int oldDivisions = this.subdivisions; computeSubdivisions(dc, this.getCurrentShapeData()); - if (oldDivisions != this.subdivisions) + if (oldDivisions != this.subdivisions) { return true; + } return super.mustRegenerateGeometry(dc); } @@ -255,38 +239,35 @@ protected boolean mustRegenerateGeometry(DrawContext dc) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - /** * Sets the Geometry mesh for this cylinder, either by pulling it from the geometryCache, or by creating it anew if * the appropriate geometry does not yet exist in the cache. * * @param shapeData this shape's current shape data. */ - protected void makeGeometry(ShapeData shapeData) - { + protected void makeGeometry(ShapeData shapeData) { // attempt to retrieve a cached unit box with the same number of subdivisions Object cacheKey = new Geometry.CacheKey(this.getClass(), "Cylinder0", this.subdivisions); Geometry geom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null) - { + if (geom == null) { // if none exists, create a new one makeUnitCylinder(this.subdivisions, shapeData.getMeshes()); - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } // add the new mesh pieces to the cache cacheKey = new Geometry.CacheKey(this.getClass(), "Cylinder" + piece, this.subdivisions); this.getGeometryCache().add(cacheKey, shapeData.getMesh(piece)); } - } - else - { + } else { // otherwise, just use the one from the cache - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } cacheKey = new Geometry.CacheKey(this.getClass(), "Cylinder" + piece, this.subdivisions); geom = (Geometry) this.getGeometryCache().getObject(cacheKey); shapeData.addMesh(piece, geom); @@ -299,7 +280,7 @@ protected void makeGeometry(ShapeData shapeData) * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit cylinder geometry - * @param dest the Geometry container to hold the computed points, etc. + * @param dest the Geometry container to hold the computed points, etc. */ /* protected void makeUnitCylinder(int subdivisions, Geometry dest) @@ -324,34 +305,34 @@ protected void makeUnitCylinder(int subdivisions, Geometry dest) dest.setNormalData(normalBuffer.limit(), normalBuffer); dest.setTextureCoordData(textureCoordBuffer.limit(), textureCoordBuffer); } - */ - + */ /** * Generates a unit cylinder geometry, including the vertices, indices, normals and texture coordinates, tessellated * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit cylinder geometry - * @param meshes the Geometry list to hold the computed points, etc. for all Geometries + * @param meshes the Geometry list to hold the computed points, etc. for all Geometries */ - protected void makeUnitCylinder(int subdivisions, List meshes) - { + protected void makeUnitCylinder(int subdivisions, List meshes) { float radius = 1.0f; Geometry dest; GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(GeometryBuilder.OUTSIDE); - for (int face = 0; face < getFaceCount(); face++) - { + for (int face = 0; face < getFaceCount(); face++) { // create cylinder in model space - GeometryBuilder.IndexedTriangleBuffer itb = - gb.tessellateCylinderBuffer(face, radius, subdivisions); + GeometryBuilder.IndexedTriangleBuffer itb + = gb.tessellateCylinderBuffer(face, radius, subdivisions); FloatBuffer normalBuffer = Buffers.newDirectFloatBuffer(3 * itb.getVertexCount()); - if (face == 0 || face == 1) // Cylinder top or bottom + if (face == 0 || face == 1) // Cylinder top or bottom + { gb.makeIndexedTriangleBufferNormals(itb, normalBuffer); - else // round Cylinder core + } else // round Cylinder core + { gb.makeCylinderNormals(itb, normalBuffer); + } FloatBuffer textureCoordBuffer = Buffers.newDirectFloatBuffer(2 * itb.getVertexCount()); gb.makeUnitCylinderTextureCoordinates(face, textureCoordBuffer, subdivisions); @@ -370,19 +351,17 @@ protected void makeUnitCylinder(int subdivisions, List meshes) /** * Renders the cylinder, using data from the provided buffer and the given parameters. * - * @param dc the current draw context - * @param mode the render mode - * @param count the number of elements to be drawn - * @param type the data type of the elements to be drawn + * @param dc the current draw context + * @param mode the render mode + * @param count the number of elements to be drawn + * @param type the data type of the elements to be drawn * @param elementBuffer the buffer containing the list of elements to be drawn - * @param shapeData this shape's current globe-specific shape data - * @param face the shape face currently being drawn + * @param shapeData this shape's current globe-specific shape data + * @param face the shape face currently being drawn */ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffer elementBuffer, - ShapeData shapeData, int face) - { - if (elementBuffer == null) - { + ShapeData shapeData, int face) { + if (elementBuffer == null) { String message = "nullValue.ElementBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -390,8 +369,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe Geometry mesh = shapeData.getMesh(face); - if (mesh.getBuffer(Geometry.VERTEX) == null) - { + if (mesh.getBuffer(Geometry.VERTEX) == null) { String message = "nullValue.VertexBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -408,17 +386,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe vertexBuffer = mesh.getBuffer(Geometry.VERTEX); normalBuffer = null; - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { normalBuffer = mesh.getBuffer(Geometry.NORMAL); - if (normalBuffer == null) - { + if (normalBuffer == null) { gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); - } - else - { + } else { glType = mesh.getGLType(Geometry.NORMAL); stride = mesh.getStride(Geometry.NORMAL); gl.glNormalPointer(glType, stride, normalBuffer); @@ -429,14 +402,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // cull the back face //gl.glEnable(GL.GL_CULL_FACE); //gl.glFrontFace(GL.GL_CCW); - // testing boolean vboState = dc.getGLRuntimeCapabilities().isVertexBufferObjectEnabled(); //dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(true); // decide whether to draw with VBO's or VA's - if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) - { + if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) { // render using VBO's gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getVboIds(getSubdivisions(), dc)[2 * face]); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, this.getVboIds(getSubdivisions(), dc)[2 * face + 1]); @@ -446,9 +417,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); - } - else - { + } else { // render using vertex arrays gl.glVertexPointer(size, glType, stride, vertexBuffer.rewind()); gl.glDrawElements(mode, count, type, elementBuffer); @@ -459,23 +428,20 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // disable back face culling // gl.glDisable(GL.GL_CULL_FACE); - dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(vboState); - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { // re-enable normals if we temporarily turned them off earlier - if (normalBuffer == null) + if (normalBuffer == null) { gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); + } } // this.logGeometryStatistics(dc, geom); } } - protected ShapeData createIntersectionGeometry(Terrain terrain) - { + protected ShapeData createIntersectionGeometry(Terrain terrain) { ShapeData shapeData = new ShapeData(null, this); shapeData.setGlobeStateKey(terrain.getGlobe().getGlobeStateKey()); Geometry mesh; @@ -485,36 +451,34 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) // transform the vertices from local to world coords Matrix matrix = computeRenderMatrix(terrain.getGlobe(), terrain.getVerticalExaggeration()); - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { mesh = shapeData.getMesh(i); // transform the vertices from local to world coords FloatBuffer newVertices = computeTransformedVertices((FloatBuffer) mesh.getBuffer(Geometry.VERTEX), - mesh.getCount(Geometry.VERTEX), matrix); + mesh.getCount(Geometry.VERTEX), matrix); mesh.setVertexData(mesh.getCount(Geometry.VERTEX), newVertices); } shapeData.setReferencePoint(this.computeReferencePoint(terrain.getGlobe(), - terrain.getVerticalExaggeration())); + terrain.getVerticalExaggeration())); shapeData.setExtent(getExtent(terrain.getGlobe(), terrain.getVerticalExaggeration())); return shapeData; } - /** No export formats supported. */ + /** + * No export formats supported. + */ @Override - public String isExportFormatSupported(String mimeType) - { + public String isExportFormatSupported(String mimeType) { // Overridden because this shape does not support export to KML. return Exportable.FORMAT_NOT_SUPPORTED; } @Override - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { String message = Logging.getMessage("generic.UnsupportedOperation", "doExportAsKML"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } } - diff --git a/src/gov/nasa/worldwind/render/Declutterable.java b/src/gov/nasa/worldwind/render/Declutterable.java index ae38e6e1dd..4e837f969d 100644 --- a/src/gov/nasa/worldwind/render/Declutterable.java +++ b/src/gov/nasa/worldwind/render/Declutterable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import java.awt.geom.*; @@ -14,8 +13,8 @@ * @author tag * @version $Id: Declutterable.java 704 2012-07-21 03:16:21Z tgaskins $ */ -public interface Declutterable extends OrderedRenderable -{ +public interface Declutterable extends OrderedRenderable { + /** * Indicates whether this object actually participates in decluttering. * diff --git a/src/gov/nasa/worldwind/render/DeclutterableText.java b/src/gov/nasa/worldwind/render/DeclutterableText.java index 7f0a06edee..b0c243c14f 100644 --- a/src/gov/nasa/worldwind/render/DeclutterableText.java +++ b/src/gov/nasa/worldwind/render/DeclutterableText.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.geom.Vec4; @@ -18,8 +17,8 @@ * @author tag * @version $Id: DeclutterableText.java 704 2012-07-21 03:16:21Z tgaskins $ */ -public class DeclutterableText implements Declutterable -{ +public class DeclutterableText implements Declutterable { + protected GeographicText text; protected Vec4 point; protected double eyeDistance; @@ -31,13 +30,12 @@ public class DeclutterableText implements Declutterable /** * Construct an object for specified text and position. * - * @param text the text to display. - * @param point the Cartesian location of the text. - * @param eyeDistance the distance to consider the text from the eye. + * @param text the text to display. + * @param point the Cartesian location of the text. + * @param eyeDistance the distance to consider the text from the eye. * @param textRenderer the text renderer to use to draw the text. */ - DeclutterableText(GeographicText text, Vec4 point, double eyeDistance, DeclutteringTextRenderer textRenderer) - { + DeclutterableText(GeographicText text, Vec4 point, double eyeDistance, DeclutteringTextRenderer textRenderer) { this.text = text; this.point = point; this.eyeDistance = eyeDistance; @@ -49,66 +47,58 @@ public class DeclutterableText implements Declutterable * * @return true (the default) if it should participate, otherwise false. */ - public boolean isEnableDecluttering() - { + public boolean isEnableDecluttering() { return this.enableDecluttering; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - public GeographicText getText() - { + public GeographicText getText() { return text; } - public Vec4 getPoint() - { + public Vec4 getPoint() { return point; } - public Rectangle2D getBounds(DrawContext dc) - { + public Rectangle2D getBounds(DrawContext dc) { Font font = this.getText().getFont(); - if (font == null) + if (font == null) { font = this.textRenderer.getDefaultFont(); + } - if (this.textBounds != null && this.boundsFont == font) + if (this.textBounds != null && this.boundsFont == font) { return this.textBounds; + } - try - { + try { this.textBounds = this.textRenderer.computeTextBounds(dc, this); this.boundsFont = font; - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionWhileRenderingText", e); } return this.textBounds; } - /** {@inheritDoc} */ - public void render(DrawContext dc) - { - try - { - if (this.getBounds(dc) == null) + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { + try { + if (this.getBounds(dc) == null) { return; + } this.textRenderer.drawText(dc, this, 1, 1); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionWhileRenderingText", e); } } - public void pick(DrawContext dc, java.awt.Point pickPoint) - { + public void pick(DrawContext dc, java.awt.Point pickPoint) { // TODO } } diff --git a/src/gov/nasa/worldwind/render/DeclutteringTextRenderer.java b/src/gov/nasa/worldwind/render/DeclutteringTextRenderer.java index 91a825d4a9..b8a959a1fa 100644 --- a/src/gov/nasa/worldwind/render/DeclutteringTextRenderer.java +++ b/src/gov/nasa/worldwind/render/DeclutteringTextRenderer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.geom.*; @@ -26,8 +25,8 @@ * @author tag * @version $Id: DeclutteringTextRenderer.java 2392 2014-10-20 20:02:44Z tgaskins $ */ -public class DeclutteringTextRenderer -{ +public class DeclutteringTextRenderer { + protected static final Font DEFAULT_FONT = Font.decode("Arial-PLAIN-12"); protected static final Color DEFAULT_COLOR = Color.white; @@ -36,115 +35,116 @@ public class DeclutteringTextRenderer // Flag indicating a JOGL text rendering problem. Set to avoid continual exception logging. protected boolean hasJOGLv111Bug = false; - public Font getDefaultFont() - { + public Font getDefaultFont() { return DEFAULT_FONT; } /** * Returns either a cached or new text renderer for a specified font. * - * @param dc the current draw context. + * @param dc the current draw context. * @param font the text font. * * @return a text renderer. */ - public TextRenderer getTextRenderer(DrawContext dc, Font font) - { + public TextRenderer getTextRenderer(DrawContext dc, Font font) { return OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); } /** * Adds ordered renderables to the ordered renderable list. * - * @param dc the current draw context. + * @param dc the current draw context. * @param textIterable a collection of text shapes to add to the ordered-renderable list. */ - public void render(DrawContext dc, Iterable textIterable) - { - if (dc == null) - { + public void render(DrawContext dc, Iterable textIterable) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (textIterable == null) - { + if (textIterable == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (dc.getVisibleSector() == null) + if (dc.getVisibleSector() == null) { return; + } SectorGeometryList surfaceGeometry = dc.getSurfaceGeometry(); - if (surfaceGeometry == null) + if (surfaceGeometry == null) { return; + } Iterator iterator = textIterable.iterator(); - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return; + } Frustum frustumInModelCoords = dc.getView().getFrustumInModelCoordinates(); double horizon = dc.getView().getHorizonDistance(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { GeographicText text = iterator.next(); - if (!isTextValid(text, true)) + if (!isTextValid(text, true)) { continue; + } - if (!text.isVisible()) + if (!text.isVisible()) { continue; + } - if (dc.is2DGlobe()) - { - Sector limits = ((Globe2D)dc.getGlobe()).getProjection().getProjectionLimits(); - if (limits != null && !limits.contains(text.getPosition())) + if (dc.is2DGlobe()) { + Sector limits = ((Globe2D) dc.getGlobe()).getProjection().getProjectionLimits(); + if (limits != null && !limits.contains(text.getPosition())) { continue; + } } Angle lat = text.getPosition().getLatitude(); Angle lon = text.getPosition().getLongitude(); - if (!dc.getVisibleSector().contains(lat, lon)) + if (!dc.getVisibleSector().contains(lat, lon)) { continue; + } Vec4 textPoint = surfaceGeometry.getSurfacePoint(lat, lon, - text.getPosition().getElevation() * dc.getVerticalExaggeration()); - if (textPoint == null) + text.getPosition().getElevation() * dc.getVerticalExaggeration()); + if (textPoint == null) { continue; + } double eyeDistance = dc.getView().getEyePoint().distanceTo3(textPoint); - if (!dc.is2DGlobe() && eyeDistance > horizon) + if (!dc.is2DGlobe() && eyeDistance > horizon) { continue; + } - if (!frustumInModelCoords.contains(textPoint)) + if (!frustumInModelCoords.contains(textPoint)) { continue; + } dc.addOrderedRenderable(new DeclutterableText(text, textPoint, eyeDistance, this)); } } - protected void beginRendering(DrawContext dc) - { - if (dc == null) - { + protected void beginRendering(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - int attribBits = - GL2.GL_ENABLE_BIT // for enable/disable changes + int attribBits + = GL2.GL_ENABLE_BIT // for enable/disable changes | GL2.GL_COLOR_BUFFER_BIT // for alpha test func and ref, and blend - | GL2.GL_CURRENT_BIT // for current color + | GL2.GL_CURRENT_BIT // for current color | GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth func, and depth mask - | GL2.GL_TRANSFORM_BIT // for modelview and perspective + | GL2.GL_TRANSFORM_BIT // for modelview and perspective | GL2.GL_VIEWPORT_BIT; // for depth range gl.glPushAttrib(attribBits); @@ -173,10 +173,8 @@ protected void beginRendering(DrawContext dc) gl.glAlphaFunc(GL2.GL_GREATER, 0.001f); } - protected void endRendering(DrawContext dc) - { - if (dc == null) - { + protected void endRendering(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -194,10 +192,8 @@ protected void endRendering(DrawContext dc) gl.glPopAttrib(); } - protected Vec4 drawText(DrawContext dc, DeclutterableText uText, double scale, double opacity) throws Exception - { - if (uText.getPoint() == null) - { + protected Vec4 drawText(DrawContext dc, DeclutterableText uText, double scale, double opacity) throws Exception { + if (uText.getPoint() == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().fine(msg); return null; @@ -207,48 +203,49 @@ protected Vec4 drawText(DrawContext dc, DeclutterableText uText, double scale, d GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. final CharSequence charSequence = geographicText.getText(); - if (charSequence == null) + if (charSequence == null) { return null; + } final Vec4 screenPoint = dc.getView().project(uText.getPoint()); - if (screenPoint == null) + if (screenPoint == null) { return null; + } Font font = geographicText.getFont(); - if (font == null) + if (font == null) { font = DEFAULT_FONT; + } TextRenderer textRenderer = this.getTextRenderer(dc, font); this.beginRendering(dc); - try - { + try { textRenderer.begin3DRendering(); this.setDepthFunc(dc, screenPoint); Rectangle2D textBounds = uText.getBounds(dc); - if (textBounds == null) + if (textBounds == null) { return null; + } Point.Float drawPoint = this.computeDrawPoint(textBounds, screenPoint); - if (drawPoint != null) - { - if (scale != 1d) - { + if (drawPoint != null) { + if (scale != 1d) { gl.glScaled(scale, scale, 1d); drawPoint.setLocation(drawPoint.x / (float) scale, drawPoint.y / (float) scale); } Color color = geographicText.getColor(); - if (color == null) + if (color == null) { color = DEFAULT_COLOR; + } color = this.applyOpacity(color, opacity); Color background = geographicText.getBackgroundColor(); - if (background != null) - { + if (background != null) { background = this.applyOpacity(background, opacity); textRenderer.setColor(background); textRenderer.draw3D(charSequence, drawPoint.x + 1, drawPoint.y - 1, 0, 1); @@ -258,16 +255,13 @@ protected Vec4 drawText(DrawContext dc, DeclutterableText uText, double scale, d textRenderer.draw3D(charSequence, drawPoint.x, drawPoint.y, 0, 1); textRenderer.flush(); - if (scale != 1d) + if (scale != 1d) { gl.glLoadIdentity(); + } } - } - catch (Exception e) - { + } catch (Exception e) { handleTextRendererExceptions(e); - } - finally - { + } finally { textRenderer.end3DRendering(); this.endRendering(dc); } @@ -275,27 +269,22 @@ protected Vec4 drawText(DrawContext dc, DeclutterableText uText, double scale, d return screenPoint; } - protected void setDepthFunc(DrawContext dc, Vec4 screenPoint) - { + protected void setDepthFunc(DrawContext dc, Vec4 screenPoint) { GL gl = dc.getGL(); Position eyePos = dc.getView().getEyePosition(); - if (eyePos == null) - { + if (eyePos == null) { gl.glDepthFunc(GL.GL_ALWAYS); return; } double altitude = eyePos.getElevation(); - if (altitude < (dc.getGlobe().getMaxElevation() * dc.getVerticalExaggeration())) - { + if (altitude < (dc.getGlobe().getMaxElevation() * dc.getVerticalExaggeration())) { double depth = screenPoint.z - (8d * 0.00048875809d); depth = depth < 0d ? 0d : (depth > 1d ? 1d : depth); gl.glDepthFunc(GL.GL_LESS); gl.glDepthRange(depth, depth); - } - else - { + } else { gl.glDepthFunc(GL.GL_ALWAYS); } } @@ -304,54 +293,55 @@ protected void setDepthFunc(DrawContext dc, Vec4 screenPoint) * Computes the final draw point for the given rectangle lower left corner and target screen point. If the returned * point is null the text will not be drawn. * - * @param rect the text rectangle to draw. + * @param rect the text rectangle to draw. * @param screenPoint the projected screen point the text relates to. * * @return the final draw point for the given rectangle lower left corner or null. */ - protected Point.Float computeDrawPoint(Rectangle2D rect, Vec4 screenPoint) - { + protected Point.Float computeDrawPoint(Rectangle2D rect, Vec4 screenPoint) { return new Point.Float((float) (screenPoint.x - rect.getWidth() / 2d), (float) (screenPoint.y)); } - protected static boolean isTextValid(GeographicText text, boolean checkPosition) - { - if (text == null || text.getText() == null) + protected static boolean isTextValid(GeographicText text, boolean checkPosition) { + if (text == null || text.getText() == null) { return false; + } - if (checkPosition && text.getPosition() == null) + if (checkPosition && text.getPosition() == null) { return false; + } return true; } - protected Color applyOpacity(Color color, double opacity) - { - if (opacity >= 1) + protected Color applyOpacity(Color color, double opacity) { + if (opacity >= 1) { return color; + } float[] compArray = color.getRGBComponents(null); return new Color(compArray[0], compArray[1], compArray[2], compArray[3] * (float) opacity); } - protected Rectangle2D computeTextBounds(DrawContext dc, DeclutterableText text) throws Exception - { + protected Rectangle2D computeTextBounds(DrawContext dc, DeclutterableText text) throws Exception { GeographicText geographicText = text.getText(); final CharSequence charSequence = geographicText.getText(); - if (charSequence == null) + if (charSequence == null) { return null; + } final Vec4 screenPoint = dc.getView().project(text.getPoint()); - if (screenPoint == null) + if (screenPoint == null) { return null; + } Font font = geographicText.getFont(); - if (font == null) + if (font == null) { font = this.getDefaultFont(); + } - try - { + try { TextRenderer textRenderer = this.getTextRenderer(dc, font); Rectangle2D textBound = textRenderer.getBounds(charSequence); @@ -360,28 +350,21 @@ protected Rectangle2D computeTextBounds(DrawContext dc, DeclutterableText text) bounds.setRect(x, screenPoint.y, textBound.getWidth(), textBound.getHeight()); return bounds; - } - catch (Exception e) - { + } catch (Exception e) { handleTextRendererExceptions(e); return null; } } - protected void handleTextRendererExceptions(Exception e) throws Exception - { - if (e instanceof IOException) - { - if (!this.hasJOGLv111Bug) - { + protected void handleTextRendererExceptions(Exception e) throws Exception { + if (e instanceof IOException) { + if (!this.hasJOGLv111Bug) { // This is likely a known JOGL 1.1.1 bug - see AMZN-287 or 343 // Log once and then ignore. Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionWhileRenderingText", e); this.hasJOGLv111Bug = true; } - } - else - { + } else { throw e; } } diff --git a/src/gov/nasa/worldwind/render/DrawContext.java b/src/gov/nasa/worldwind/render/DrawContext.java index ac1206b8f7..5f4f449052 100644 --- a/src/gov/nasa/worldwind/render/DrawContext.java +++ b/src/gov/nasa/worldwind/render/DrawContext.java @@ -27,8 +27,8 @@ * @author Tom Gaskins * @version $Id: DrawContext.java 2281 2014-08-29 23:08:04Z dcollins $ */ -public interface DrawContext extends WWObject, Disposable -{ +public interface DrawContext extends WWObject, Disposable { + /** * Assigns this DrawContext a new com.jogamp.opengl.GLContext. May throw a * NullPointerException if glContext is null. @@ -236,7 +236,7 @@ public interface DrawContext extends WWObject, Disposable * Retrieves a list of all the sectors rendered so far this frame. * * @return a SectorGeometryList containing every SectorGeometry rendered so far this - * render pass. + * render pass. * * @since 1.5 */ @@ -311,7 +311,7 @@ public interface DrawContext extends WWObject, Disposable * @param count the number of unique colors to allocate. * * @return the first unique pick color if there are sufficient unique colors remaining and count is - * greater than 0, otherwise null. + * greater than 0, otherwise null. */ Color getUniquePickColorRange(int count); @@ -354,18 +354,20 @@ public interface DrawContext extends WWObject, Disposable * the colors that must be considered by this method and the caller. When specified, these integers must be * formatted exactly as the integers this method returns. * - * @param rectangle the rectangle to return unique colors for, in AWT screen coordinates. + * @param rectangle the rectangle to return unique colors for, in AWT screen coordinates. * @param minAndMaxColorCodes an two element array representing the minimum and maximum RGB colors to return. May be - * null to specify that all color codes must be returned. + * null to specify that all color codes must be returned. * * @return the unique RGB colors corresponding to the specified rectangle, or null if the rectangle is - * empty or the rectangle contains only the clear color. + * empty or the rectangle contains only the clear color. * * @throws IllegalArgumentException if the rectangle is null. */ int[] getPickColorsInRectangle(Rectangle rectangle, int[] minAndMaxColorCodes); - /** Specifies that the scene controller is beginning its pick traversal. */ + /** + * Specifies that the scene controller is beginning its pick traversal. + */ void enablePickingMode(); /** @@ -375,7 +377,9 @@ public interface DrawContext extends WWObject, Disposable */ boolean isPickingMode(); - /** Specifies that the scene controller has ended its pick traversal. */ + /** + * Specifies that the scene controller has ended its pick traversal. + */ void disablePickingMode(); /** @@ -410,9 +414,8 @@ public interface DrawContext extends WWObject, Disposable * those ordered renderables are drawn according to the order in which they are added. * * @param orderedRenderable the ordered renderable to add. - * @param isBehind true to specify that the ordered renderable is behind all other ordered - * renderables, or false to interpret the ordered renderable according to its - * eye distance. + * @param isBehind true to specify that the ordered renderable is behind all other ordered renderables, + * or false to interpret the ordered renderable according to its eye distance. */ void addOrderedRenderable(OrderedRenderable orderedRenderable, boolean isBehind); @@ -465,7 +468,7 @@ public interface DrawContext extends WWObject, Disposable /** * Computes a location's Cartesian point on the currently visible terrain. * - * @param latitude the location's latitude. + * @param latitude the location's latitude. * @param longitude the location's longitude. * * @return the location's corresponding Cartesian point, or null if the location is not currently visible. @@ -561,7 +564,7 @@ public interface DrawContext extends WWObject, Disposable * null. If either is null then statistics are not gathered. * * @param statKeys the keys identifying the statistics to monitor. - * @param stats a list in which the statistics are placed as they're monitored. + * @param stats a list in which the statistics are placed as they're monitored. */ void setPerFrameStatisticsKeys(Set statKeys, Collection stats); @@ -569,9 +572,9 @@ public interface DrawContext extends WWObject, Disposable * Specifies a performance statistic that's assigned for each frame. Use this method to update the value of a * specific statistic. * - * @param key the key identifying the statistic to monitor. + * @param key the key identifying the statistic to monitor. * @param displayName the name to use when displaying this statistic. - * @param statistic the statistic's value. May be null. + * @param statistic the statistic's value. May be null. * * @throws IllegalArgumentException if either the key or display name are null. * @see #setPerFrameStatistics(java.util.Collection) @@ -613,7 +616,7 @@ public interface DrawContext extends WWObject, Disposable * Indicates the geographic coordinates of the point on the terrain at the current viewport's center. * * @return the geographic coordinates of the current viewport's center. Returns null if the globe's surface is not - * under the viewport's center point. + * under the viewport's center point. */ Position getViewportCenterPosition(); @@ -686,12 +689,12 @@ public interface DrawContext extends WWObject, Disposable * The search may take more than the specified time, but will terminate if no time is left before starting a * higher-resolution search. * - * @param resolutions the resolutions of the sectors to return, in latitude. - * @param timeLimit the amount of time, in milliseconds, to allow for searching. + * @param resolutions the resolutions of the sectors to return, in latitude. + * @param timeLimit the amount of time, in milliseconds, to allow for searching. * @param searchSector the sector to decompose into visible sectors. * * @return the visible sectors at the best resolution achievable given the time limit. The actual resolution can be - * determined by examining the delta-latitude value of any of the returned sectors. + * determined by examining the delta-latitude value of any of the returned sectors. * * @throws IllegalArgumentException if the resolutions array or the search sector is null. */ @@ -786,7 +789,7 @@ public interface DrawContext extends WWObject, Disposable * this DrawContext does not accumulate rendering exceptions. * * @return the Collection used to accumulate rendering exceptions, or null if this DrawContext does not accumulate - * rendering exceptions. + * rendering exceptions. */ Collection getRenderingExceptions(); @@ -797,7 +800,7 @@ public interface DrawContext extends WWObject, Disposable * indicates this DrawContext should not accumulate rendering exceptions. * * @param exceptions the Collection of exceptions to be used to accumulate rendering exceptions, or null to disable - * accumulation of rendering exception. + * accumulation of rendering exception. */ void setRenderingExceptions(Collection exceptions); @@ -819,12 +822,12 @@ public interface DrawContext extends WWObject, Disposable * Note: This capability is meant to be applied only within a single Renderable. It is not intended as a * means to offset a whole Renderable or collection of Renderables. *

          - * See "Mathematics for Game Programming and 3D Computer Graphics, 2 ed." by Eric Lengyel, Section 9.1, "Depth - * Value Offset" for a description of this technique. + * See "Mathematics for Game Programming and 3D Computer Graphics, 2 ed." by Eric Lengyel, Section 9.1, "Depth Value + * Offset" for a description of this technique. * * @param offset a reference to an offset value, typically near 1.0, or null to request use of the default value. - * Values less than 1.0 pull objects toward the eye point, values greater than 1.0 push objects away - * from the eye point. The default value is 0.99. + * Values less than 1.0 pull objects toward the eye point, values greater than 1.0 push objects away from the eye + * point. The default value is 0.99. * * @see #popProjectionOffest() */ @@ -863,8 +866,8 @@ public interface DrawContext extends WWObject, Disposable * shapes previously drawn in favor of the current shape. * * @param renderer an object implementing the {@link gov.nasa.worldwind.render.OutlinedShape} interface for the - * shape. - * @param shape the shape to render. + * shape. + * @param shape the shape to render. * * @see gov.nasa.worldwind.render.OutlinedShape */ @@ -879,7 +882,9 @@ public interface DrawContext extends WWObject, Disposable */ void beginStandardLighting(); - /** Pops the OpenGL state previously established by {@link #beginStandardLighting()}. */ + /** + * Pops the OpenGL state previously established by {@link #beginStandardLighting()}. + */ void endStandardLighting(); /** @@ -899,8 +904,8 @@ public interface DrawContext extends WWObject, Disposable /** * Compute a model-coordinate point on the terrain. * - * @param lat the point's latitude. - * @param lon the point's longitude. + * @param lat the point's latitude. + * @param lon the point's longitude. * @param offset an distance in meters to place the point above or below the terrain. * * @return a model-coordinate point offset the specified amount from the current terrain. @@ -912,7 +917,7 @@ public interface DrawContext extends WWObject, Disposable /** * Indicates whether a specified extent is smaller than a specified number of pixels for the current view. * - * @param extent the extent to test. May be null, in which case this method returns false. + * @param extent the extent to test. May be null, in which case this method returns false. * @param numPixels the number of pixels at and below which the extent is considered too small. * * @return true if the projected extent is smaller than the specified number of pixels, otherwise false. @@ -923,8 +928,8 @@ public interface DrawContext extends WWObject, Disposable * This is a diagnostic method to display normal vectors. * * @param length the length to draw the vectors, in meters. - * @param vBuf a vertex buffer. If null, no vectors are drawn. - * @param nBuf a buffer of normal vectors corresponding to the vertex buffer. If null, no vectors are drawn. + * @param vBuf a vertex buffer. If null, no vectors are drawn. + * @param nBuf a buffer of normal vectors corresponding to the vertex buffer. If null, no vectors are drawn. */ void drawNormals(float length, FloatBuffer vBuf, FloatBuffer nBuf); @@ -952,13 +957,19 @@ public interface DrawContext extends WWObject, Disposable */ Terrain getTerrain(); - /** Restores the current OpenGL context's blending state to its default. */ + /** + * Restores the current OpenGL context's blending state to its default. + */ void restoreDefaultBlending(); - /** Restores the current OpenGL context's current color to its default. */ + /** + * Restores the current OpenGL context's current color to its default. + */ void restoreDefaultCurrentColor(); - /** Restores the current OpenGL context's depth testing state to its default. */ + /** + * Restores the current OpenGL context's depth testing state to its default. + */ void restoreDefaultDepthTesting(); /** @@ -982,7 +993,7 @@ public interface DrawContext extends WWObject, Disposable /** * Computes a Cartesian point from a specified geographic position, applying a specified altitude mode. * - * @param position the position to convert. + * @param position the position to convert. * @param altitudeMode the altitude mode. * * @return the Cartesian point corresponding to the specified position and this context's current globe or terrain. @@ -998,7 +1009,9 @@ public interface DrawContext extends WWObject, Disposable */ DeclutteringTextRenderer getDeclutteringTextRenderer(); - /** Filter overlapping text from the ordered renderable list. */ + /** + * Filter overlapping text from the ordered renderable list. + */ void applyClutterFilter(); // // void applyGroupingFilters(); diff --git a/src/gov/nasa/worldwind/render/DrawContextImpl.java b/src/gov/nasa/worldwind/render/DrawContextImpl.java index 410b0b94cb..7779bf6972 100644 --- a/src/gov/nasa/worldwind/render/DrawContextImpl.java +++ b/src/gov/nasa/worldwind/render/DrawContextImpl.java @@ -29,8 +29,8 @@ * @author Tom Gaskins * @version $Id: DrawContextImpl.java 2281 2014-08-29 23:08:04Z dcollins $ */ -public class DrawContextImpl extends WWObjectImpl implements DrawContext -{ +public class DrawContextImpl extends WWObjectImpl implements DrawContext { + protected long frameTimestamp; protected GLContext glContext; protected GLRuntimeCapabilities glRuntimeCaps; @@ -53,7 +53,9 @@ public class DrawContextImpl extends WWObjectImpl implements DrawContext protected PickedObjectList objectsInPickRect = new PickedObjectList(); protected int uniquePickNumber = 0; protected Color clearColor = new Color(0, 0, 0, 0); - /** Buffer of RGB colors used to read back the framebuffer's colors and store them in client memory. */ + /** + * Buffer of RGB colors used to read back the framebuffer's colors and store them in client memory. + */ protected ByteBuffer pixelColors; /** * Set of ints used by {@link #getPickColorsInRectangle(java.awt.Rectangle, int[])} to identify the unique color @@ -95,51 +97,45 @@ public class DrawContextImpl extends WWObjectImpl implements DrawContext protected ClutterFilter clutterFilter; // protected Map groupingFilters; - protected static class OrderedRenderableEntry - { + protected static class OrderedRenderableEntry { + protected OrderedRenderable or; protected double distanceFromEye; protected long time; protected int globeOffset; protected SectorGeometryList surfaceGeometry; - public OrderedRenderableEntry(OrderedRenderable orderedRenderable, long insertionTime, DrawContext dc) - { + public OrderedRenderableEntry(OrderedRenderable orderedRenderable, long insertionTime, DrawContext dc) { this.or = orderedRenderable; this.distanceFromEye = orderedRenderable.getDistanceFromEye(); this.time = insertionTime; - if (dc.isContinuous2DGlobe()) - { + if (dc.isContinuous2DGlobe()) { this.globeOffset = ((Globe2D) dc.getGlobe()).getOffset(); this.surfaceGeometry = dc.getSurfaceGeometry(); } } public OrderedRenderableEntry(OrderedRenderable orderedRenderable, double distanceFromEye, long insertionTime, - DrawContext dc) - { + DrawContext dc) { this.or = orderedRenderable; this.distanceFromEye = distanceFromEye; this.time = insertionTime; - if (dc.isContinuous2DGlobe()) - { + if (dc.isContinuous2DGlobe()) { this.globeOffset = ((Globe2D) dc.getGlobe()).getOffset(); this.surfaceGeometry = dc.getSurfaceGeometry(); } } } - protected PriorityQueue orderedRenderables = - new PriorityQueue(100, new Comparator() - { - public int compare(OrderedRenderableEntry orA, OrderedRenderableEntry orB) - { - double eA = orA.distanceFromEye; - double eB = orB.distanceFromEye; + protected PriorityQueue orderedRenderables + = new PriorityQueue(100, new Comparator() { + public int compare(OrderedRenderableEntry orA, OrderedRenderableEntry orB) { + double eA = orA.distanceFromEye; + double eB = orB.distanceFromEye; - return eA > eB ? -1 : eA == eB ? (orA.time < orB.time ? -1 : orA.time == orB.time ? 0 : 1) : 1; - } - }); + return eA > eB ? -1 : eA == eB ? (orA.time < orB.time ? -1 : orA.time == orB.time ? 0 : 1) : 1; + } + }); // Use a standard Queue to store the ordered surface object renderables. Ordered surface renderables are processed // in the order they were submitted. protected Queue orderedSurfaceRenderables = new ArrayDeque(); @@ -149,50 +145,40 @@ public int compare(OrderedRenderableEntry orA, OrderedRenderableEntry orB) * * @throws com.jogamp.opengl.GLException - If an OpenGL context is not current when this method is called. */ - public void dispose() - { + public void dispose() { this.geographicSurfaceTileRenderer.dispose(); } - public final GL getGL() - { + public final GL getGL() { return this.getGLContext().getGL(); } - public final GLU getGLU() - { + public final GLU getGLU() { return this.glu; } - public final GLContext getGLContext() - { + public final GLContext getGLContext() { return this.glContext; } - public final int getDrawableHeight() - { + public final int getDrawableHeight() { return this.getGLDrawable().getSurfaceHeight(); } - public final int getDrawableWidth() - { + public final int getDrawableWidth() { return this.getGLDrawable().getSurfaceWidth(); } - public final GLDrawable getGLDrawable() - { + public final GLDrawable getGLDrawable() { return this.getGLContext().getGLDrawable(); } - public GLRuntimeCapabilities getGLRuntimeCapabilities() - { + public GLRuntimeCapabilities getGLRuntimeCapabilities() { return this.glRuntimeCaps; } - public void setGLRuntimeCapabilities(GLRuntimeCapabilities capabilities) - { - if (capabilities == null) - { + public void setGLRuntimeCapabilities(GLRuntimeCapabilities capabilities) { + if (capabilities == null) { String message = Logging.getMessage("nullValue.GLRuntimeCapabilitiesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -201,10 +187,8 @@ public void setGLRuntimeCapabilities(GLRuntimeCapabilities capabilities) this.glRuntimeCaps = capabilities; } - public final void initialize(GLContext glContext) - { - if (glContext == null) - { + public final void initialize(GLContext glContext) { + if (glContext == null) { String message = Logging.getMessage("nullValue.GLContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -213,8 +197,9 @@ public final void initialize(GLContext glContext) this.glContext = glContext; this.visibleSector = null; - if (this.surfaceGeometry != null) + if (this.surfaceGeometry != null) { this.surfaceGeometry.clear(); + } this.surfaceGeometry = null; this.pickedObjects.clear(); @@ -230,67 +215,57 @@ public final void initialize(GLContext glContext) this.currentLayer = null; } - public final void setModel(Model model) - { + public final void setModel(Model model) { this.model = model; - if (this.model == null) + if (this.model == null) { return; + } Globe g = this.model.getGlobe(); - if (g != null) + if (g != null) { this.globe = g; + } } - public final Model getModel() - { + public final Model getModel() { return this.model; } - public final LayerList getLayers() - { + public final LayerList getLayers() { return this.model.getLayers(); } - public final Sector getVisibleSector() - { + public final Sector getVisibleSector() { return this.visibleSector; } - public final void setVisibleSector(Sector s) - { + public final void setVisibleSector(Sector s) { // don't check for null - it is possible that no globe is active, no view is active, no sectors visible, etc. this.visibleSector = s; } - public void setSurfaceGeometry(SectorGeometryList surfaceGeometry) - { + public void setSurfaceGeometry(SectorGeometryList surfaceGeometry) { this.surfaceGeometry = surfaceGeometry; } - public SectorGeometryList getSurfaceGeometry() - { + public SectorGeometryList getSurfaceGeometry() { return surfaceGeometry; } - public final Globe getGlobe() - { + public final Globe getGlobe() { return this.globe != null ? this.globe : this.model.getGlobe(); } - public final void setView(View view) - { + public final void setView(View view) { this.view = view; } - public final View getView() - { + public final View getView() { return this.view; } - public final void setGLContext(GLContext glContext) - { - if (glContext == null) - { + public final void setGLContext(GLContext glContext) { + if (glContext == null) { String message = Logging.getMessage("nullValue.GLContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -299,30 +274,24 @@ public final void setGLContext(GLContext glContext) this.glContext = glContext; } - public final double getVerticalExaggeration() - { + public final double getVerticalExaggeration() { return verticalExaggeration; } - public final void setVerticalExaggeration(double verticalExaggeration) - { + public final void setVerticalExaggeration(double verticalExaggeration) { this.verticalExaggeration = verticalExaggeration; } - public GpuResourceCache getTextureCache() - { + public GpuResourceCache getTextureCache() { return this.gpuResourceCache; } - public GpuResourceCache getGpuResourceCache() - { + public GpuResourceCache getGpuResourceCache() { return this.gpuResourceCache; } - public void setGpuResourceCache(GpuResourceCache gpuResourceCache) - { - if (gpuResourceCache == null) - { + public void setGpuResourceCache(GpuResourceCache gpuResourceCache) { + if (gpuResourceCache == null) { String msg = Logging.getMessage("nullValue.GpuResourceCacheIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -331,15 +300,12 @@ public void setGpuResourceCache(GpuResourceCache gpuResourceCache) this.gpuResourceCache = gpuResourceCache; } - public TextRendererCache getTextRendererCache() - { + public TextRendererCache getTextRendererCache() { return textRendererCache; } - public void setTextRendererCache(TextRendererCache textRendererCache) - { - if (textRendererCache == null) - { + public void setTextRendererCache(TextRendererCache textRendererCache) { + if (textRendererCache == null) { String msg = Logging.getMessage("nullValue.TextRendererCacheIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -348,15 +314,12 @@ public void setTextRendererCache(TextRendererCache textRendererCache) this.textRendererCache = textRendererCache; } - public AnnotationRenderer getAnnotationRenderer() - { + public AnnotationRenderer getAnnotationRenderer() { return annotationRenderer; } - public void setAnnotationRenderer(AnnotationRenderer ar) - { - if (ar == null) - { + public void setAnnotationRenderer(AnnotationRenderer ar) { + if (ar == null) { String msg = Logging.getMessage("nullValue.RendererIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -364,106 +327,87 @@ public void setAnnotationRenderer(AnnotationRenderer ar) annotationRenderer = ar; } - public LightingModel getStandardLightingModel() - { + public LightingModel getStandardLightingModel() { return standardLighting; } - public void setStandardLightingModel(LightingModel standardLighting) - { + public void setStandardLightingModel(LightingModel standardLighting) { this.standardLighting = standardLighting; } - public Point getPickPoint() - { + public Point getPickPoint() { return this.pickPoint; } - public void setPickPoint(Point pickPoint) - { + public void setPickPoint(Point pickPoint) { this.pickPoint = pickPoint; } - public Rectangle getPickRectangle() - { + public Rectangle getPickRectangle() { return this.pickRect; } - public void setPickRectangle(Rectangle pickRect) - { + public void setPickRectangle(Rectangle pickRect) { this.pickRect = pickRect; } - public Point getViewportCenterScreenPoint() - { + public Point getViewportCenterScreenPoint() { return viewportCenterScreenPoint; } - public void setViewportCenterScreenPoint(Point viewportCenterScreenPoint) - { + public void setViewportCenterScreenPoint(Point viewportCenterScreenPoint) { this.viewportCenterScreenPoint = viewportCenterScreenPoint; } - public Position getViewportCenterPosition() - { + public Position getViewportCenterPosition() { return viewportCenterPosition; } - public void setViewportCenterPosition(Position viewportCenterPosition) - { + public void setViewportCenterPosition(Position viewportCenterPosition) { this.viewportCenterPosition = viewportCenterPosition; } - public void addPickedObjects(PickedObjectList pickedObjects) - { - if (pickedObjects == null) - { + public void addPickedObjects(PickedObjectList pickedObjects) { + if (pickedObjects == null) { String msg = Logging.getMessage("nullValue.PickedObjectList"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.pickedObjects == null) - { + if (this.pickedObjects == null) { this.pickedObjects = pickedObjects; return; } - for (PickedObject po : pickedObjects) - { + for (PickedObject po : pickedObjects) { this.pickedObjects.add(po); } } - public void addPickedObject(PickedObject pickedObject) - { - if (null == pickedObject) - { + public void addPickedObject(PickedObject pickedObject) { + if (null == pickedObject) { String msg = Logging.getMessage("nullValue.PickedObject"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (null == this.pickedObjects) + if (null == this.pickedObjects) { this.pickedObjects = new PickedObjectList(); + } this.pickedObjects.add(pickedObject); } - public PickedObjectList getPickedObjects() - { + public PickedObjectList getPickedObjects() { return this.pickedObjects; } - public PickedObjectList getObjectsInPickRectangle() - { + public PickedObjectList getObjectsInPickRectangle() { return this.objectsInPickRect; } - public void addObjectInPickRectangle(PickedObject pickedObject) - { - if (pickedObject == null) - { + public void addObjectInPickRectangle(PickedObject pickedObject) { + if (pickedObject == null) { String msg = Logging.getMessage("nullValue.PickedObject"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -472,54 +416,59 @@ public void addObjectInPickRectangle(PickedObject pickedObject) this.objectsInPickRect.add(pickedObject); } - public Color getUniquePickColor() - { + public Color getUniquePickColor() { this.uniquePickNumber++; int clearColorCode = this.getClearColor().getRGB(); if (clearColorCode == this.uniquePickNumber) // skip the clear color + { this.uniquePickNumber++; + } - if (this.uniquePickNumber >= 0x00FFFFFF) - { + if (this.uniquePickNumber >= 0x00FFFFFF) { this.uniquePickNumber = 1; // no black, no white if (clearColorCode == this.uniquePickNumber) // skip the clear color + { this.uniquePickNumber++; + } } return new Color(this.uniquePickNumber, true); // has alpha } - public Color getUniquePickColorRange(int count) - { - if (count < 1) + public Color getUniquePickColorRange(int count) { + if (count < 1) { return null; + } Range range = new Range(this.uniquePickNumber + 1, count); // compute the requested range int clearColorCode = this.getClearColor().getRGB(); if (range.contains(clearColorCode)) // skip the clear color when it's in the range + { range.location = clearColorCode + 1; + } int maxColorCode = range.location + range.length - 1; if (maxColorCode >= 0x00FFFFFF) // not enough colors to satisfy the requested range + { return null; + } this.uniquePickNumber = maxColorCode; // set the unique color to the last color in the requested range return new Color(range.location, true); // return a pointer to the beginning of the requested range } - public Color getClearColor() - { + public Color getClearColor() { return this.clearColor; } - /** {@inheritDoc} */ - public int getPickColorAtPoint(Point point) - { - if (point == null) - { + /** + * {@inheritDoc} + */ + public int getPickColorAtPoint(Point point) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -531,23 +480,24 @@ public int getPickColorAtPoint(Point point) int y = viewport.height - point.y - 1; // Read the framebuffer color at the specified point in OpenGL screen coordinates as a 24-bit RGB value. - if (this.pixelColors == null || this.pixelColors.capacity() < 3) + if (this.pixelColors == null || this.pixelColors.capacity() < 3) { this.pixelColors = Buffers.newDirectByteBuffer(3); + } this.pixelColors.clear(); this.getGL().glReadPixels(x, y, 1, 1, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, this.pixelColors); int colorCode = ((this.pixelColors.get(0) & 0xff) << 16) // Red, bits 16-23 - | ((this.pixelColors.get(1) & 0xff) << 8) // Green, bits 8-16 - | (this.pixelColors.get(2) & 0xff); // Blue, bits 0-7 + | ((this.pixelColors.get(1) & 0xff) << 8) // Green, bits 8-16 + | (this.pixelColors.get(2) & 0xff); // Blue, bits 0-7 return colorCode != this.clearColor.getRGB() ? colorCode : 0; } - /** {@inheritDoc} */ - public int[] getPickColorsInRectangle(Rectangle rectangle, int[] minAndMaxColorCodes) - { - if (rectangle == null) - { + /** + * {@inheritDoc} + */ + public int[] getPickColorsInRectangle(Rectangle rectangle, int[] minAndMaxColorCodes) { + if (rectangle == null) { String msg = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -562,30 +512,31 @@ public int[] getPickColorsInRectangle(Rectangle rectangle, int[] minAndMaxColorC r = r.intersection(viewport); if (r.isEmpty()) // Return null if the rectangle is empty. + { return null; + } - if (minAndMaxColorCodes == null) - minAndMaxColorCodes = new int[] {0, Integer.MAX_VALUE}; + if (minAndMaxColorCodes == null) { + minAndMaxColorCodes = new int[]{0, Integer.MAX_VALUE}; + } // Allocate a native byte buffer to hold the framebuffer RGB colors. int numPixels = r.width * r.height; - if (this.pixelColors == null || this.pixelColors.capacity() < 3 * numPixels) + if (this.pixelColors == null || this.pixelColors.capacity() < 3 * numPixels) { this.pixelColors = Buffers.newDirectByteBuffer(3 * numPixels); + } this.pixelColors.clear(); GL gl = this.getGL(); int[] packAlignment = new int[1]; gl.glGetIntegerv(GL.GL_PACK_ALIGNMENT, packAlignment, 0); - try - { + try { // Read the framebuffer colors in the specified rectangle as 24-bit RGB values. We're reading multiple rows // of pixels, and our row lengths are not aligned with the default 4-byte boundary, so we must set the GL // pack alignment state to 1. gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1); gl.glReadPixels(r.x, r.y, r.width, r.height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, this.pixelColors); - } - finally - { + } finally { // Restore the previous GL pack alignment state. gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, packAlignment[0]); } @@ -595,17 +546,15 @@ public int[] getPickColorsInRectangle(Rectangle rectangle, int[] minAndMaxColorC // reduces the number of colors we need to return to the caller, and ensures that callers creating picked // objects based on the returned colors do not create duplicates. int clearColorCode = this.clearColor.getRGB(); - for (int i = 0; i < numPixels; i++) - { + for (int i = 0; i < numPixels; i++) { int colorCode = ((this.pixelColors.get() & 0xff) << 16) // Red, bits 16-23 - | ((this.pixelColors.get() & 0xff) << 8) // Green, bits 8-16 - | (this.pixelColors.get() & 0xff); // Blue, bits 0-7 + | ((this.pixelColors.get() & 0xff) << 8) // Green, bits 8-16 + | (this.pixelColors.get() & 0xff); // Blue, bits 0-7 // Add a 24-bit integer corresponding to each unique RGB color that's not the clear color, and is in the // specifies range of colors. if (colorCode != clearColorCode && colorCode >= minAndMaxColorCodes[0] - && colorCode <= minAndMaxColorCodes[1]) - { + && colorCode <= minAndMaxColorCodes[1]) { this.uniquePixelColors.add(colorCode); } } @@ -619,72 +568,58 @@ public int[] getPickColorsInRectangle(Rectangle rectangle, int[] minAndMaxColorC return array; } - public boolean isPickingMode() - { + public boolean isPickingMode() { return this.pickingMode; } - public void enablePickingMode() - { + public void enablePickingMode() { this.pickingMode = true; } - public void disablePickingMode() - { + public void disablePickingMode() { this.pickingMode = false; } - public boolean isDeepPickingEnabled() - { + public boolean isDeepPickingEnabled() { return this.deepPickingMode; } - public void setDeepPickingEnabled(boolean tf) - { + public void setDeepPickingEnabled(boolean tf) { this.deepPickingMode = tf; } - public boolean isPreRenderMode() - { + public boolean isPreRenderMode() { return preRenderMode; } - public void setPreRenderMode(boolean preRenderMode) - { + public void setPreRenderMode(boolean preRenderMode) { this.preRenderMode = preRenderMode; } - public boolean isOrderedRenderingMode() - { + public boolean isOrderedRenderingMode() { return this.isOrderedRenderingMode; } - public void setOrderedRenderingMode(boolean tf) - { + public void setOrderedRenderingMode(boolean tf) { this.isOrderedRenderingMode = tf; } - public DeclutteringTextRenderer getDeclutteringTextRenderer() - { + public DeclutteringTextRenderer getDeclutteringTextRenderer() { return declutteringTextRenderer; } @Override - public boolean is2DGlobe() - { + public boolean is2DGlobe() { return this.globe instanceof Globe2D; } @Override - public boolean isContinuous2DGlobe() - { + public boolean isContinuous2DGlobe() { return this.globe instanceof Globe2D && ((Globe2D) this.getGlobe()).isContinuous(); } - public void addOrderedRenderable(OrderedRenderable orderedRenderable) - { - if (null == orderedRenderable) - { + public void addOrderedRenderable(OrderedRenderable orderedRenderable) { + if (null == orderedRenderable) { String msg = Logging.getMessage("nullValue.OrderedRenderable"); Logging.logger().warning(msg); return; // benign event @@ -693,11 +628,11 @@ public void addOrderedRenderable(OrderedRenderable orderedRenderable) this.orderedRenderables.add(new OrderedRenderableEntry(orderedRenderable, System.nanoTime(), this)); } - /** {@inheritDoc} */ - public void addOrderedRenderable(OrderedRenderable orderedRenderable, boolean isBehind) - { - if (null == orderedRenderable) - { + /** + * {@inheritDoc} + */ + public void addOrderedRenderable(OrderedRenderable orderedRenderable, boolean isBehind) { + if (null == orderedRenderable) { String msg = Logging.getMessage("nullValue.OrderedRenderable"); Logging.logger().warning(msg); return; // benign event @@ -709,22 +644,19 @@ public void addOrderedRenderable(OrderedRenderable orderedRenderable, boolean is // are added. double eyeDistance = isBehind ? Double.MAX_VALUE : orderedRenderable.getDistanceFromEye(); this.orderedRenderables.add( - new OrderedRenderableEntry(orderedRenderable, eyeDistance, System.nanoTime(), this)); + new OrderedRenderableEntry(orderedRenderable, eyeDistance, System.nanoTime(), this)); } - public OrderedRenderable peekOrderedRenderables() - { + public OrderedRenderable peekOrderedRenderables() { OrderedRenderableEntry ore = this.orderedRenderables.peek(); return ore != null ? ore.or : null; } - public OrderedRenderable pollOrderedRenderables() - { + public OrderedRenderable pollOrderedRenderables() { OrderedRenderableEntry ore = this.orderedRenderables.poll(); - if (ore != null && this.isContinuous2DGlobe()) - { + if (ore != null && this.isContinuous2DGlobe()) { ((Globe2D) this.getGlobe()).setOffset(ore.globeOffset); this.setSurfaceGeometry(ore.surfaceGeometry); } @@ -777,35 +709,31 @@ public OrderedRenderable pollOrderedRenderables() // } @Override - public void setClutterFilter(ClutterFilter filter) - { + public void setClutterFilter(ClutterFilter filter) { this.clutterFilter = filter; } @Override - public ClutterFilter getClutterFilter() - { + public ClutterFilter getClutterFilter() { return this.clutterFilter; } - public void applyClutterFilter() - { - if (this.getClutterFilter() == null) + public void applyClutterFilter() { + if (this.getClutterFilter() == null) { return; + } // Collect all the active declutterables. ArrayList declutterableArray = new ArrayList(); - for (OrderedRenderableEntry ore : this.orderedRenderables) - { - if (ore.or instanceof Declutterable && ((Declutterable) ore.or).isEnableDecluttering()) + for (OrderedRenderableEntry ore : this.orderedRenderables) { + if (ore.or instanceof Declutterable && ((Declutterable) ore.or).isEnableDecluttering()) { declutterableArray.add(ore); + } } // Sort the declutterables front-to-back. - Collections.sort(declutterableArray, new Comparator() - { - public int compare(OrderedRenderableEntry orA, OrderedRenderableEntry orB) - { + Collections.sort(declutterableArray, new Comparator() { + public int compare(OrderedRenderableEntry orA, OrderedRenderableEntry orB) { double eA = orA.distanceFromEye; double eB = orB.distanceFromEye; @@ -813,15 +741,15 @@ public int compare(OrderedRenderableEntry orA, OrderedRenderableEntry orB) } }); - if (declutterableArray.size() == 0) + if (declutterableArray.size() == 0) { return; + } // Prepare the declutterable list for the filter and remove eliminated ordered renderables from the renderable // list. The clutter filter will add those it wants displayed back to the list, or it will add some other // representation. List declutterables = new ArrayList(declutterableArray.size()); - for (OrderedRenderableEntry ore : declutterableArray) - { + for (OrderedRenderableEntry ore : declutterableArray) { declutterables.add((Declutterable) ore.or); orderedRenderables.remove(ore); @@ -831,11 +759,11 @@ public int compare(OrderedRenderableEntry orA, OrderedRenderableEntry orB) this.getClutterFilter().apply(this, declutterables); } - /** {@inheritDoc} */ - public void addOrderedSurfaceRenderable(OrderedRenderable orderedRenderable) - { - if (orderedRenderable == null) - { + /** + * {@inheritDoc} + */ + public void addOrderedSurfaceRenderable(OrderedRenderable orderedRenderable) { + if (orderedRenderable == null) { String msg = Logging.getMessage("nullValue.OrderedRenderable"); Logging.logger().warning(msg); return; // benign event @@ -844,9 +772,10 @@ public void addOrderedSurfaceRenderable(OrderedRenderable orderedRenderable) this.orderedSurfaceRenderables.add(orderedRenderable); } - /** {@inheritDoc} */ - public Queue getOrderedSurfaceRenderables() - { + /** + * {@inheritDoc} + */ + public Queue getOrderedSurfaceRenderables() { return this.orderedSurfaceRenderables; } // @@ -881,8 +810,7 @@ public Queue getOrderedSurfaceRenderables() // } // } - public void drawUnitQuad() - { + public void drawUnitQuad() { GL2 gl = this.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_QUADS); @@ -893,8 +821,7 @@ public void drawUnitQuad() gl.glEnd(); } - public void drawUnitQuad(TextureCoords texCoords) - { + public void drawUnitQuad(TextureCoords texCoords) { GL2 gl = this.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_QUADS); @@ -909,8 +836,7 @@ public void drawUnitQuad(TextureCoords texCoords) gl.glEnd(); } - public void drawUnitQuadOutline() - { + public void drawUnitQuadOutline() { GL2 gl = this.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_LINE_LOOP); @@ -921,10 +847,10 @@ public void drawUnitQuadOutline() gl.glEnd(); } - public void drawNormals(float length, FloatBuffer vBuf, FloatBuffer nBuf) - { - if (vBuf == null || nBuf == null) + public void drawNormals(float length, FloatBuffer vBuf, FloatBuffer nBuf) { + if (vBuf == null || nBuf == null) { return; + } GL2 gl = this.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -933,8 +859,7 @@ public void drawNormals(float length, FloatBuffer vBuf, FloatBuffer nBuf) gl.glBegin(GL2.GL_LINES); - while (nBuf.hasRemaining()) - { + while (nBuf.hasRemaining()) { float x = vBuf.get(); float y = vBuf.get(); float z = vBuf.get(); @@ -949,133 +874,122 @@ public void drawNormals(float length, FloatBuffer vBuf, FloatBuffer nBuf) gl.glEnd(); } - public Vec4 getPointOnTerrain(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public Vec4 getPointOnTerrain(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.getVisibleSector() == null) + if (this.getVisibleSector() == null) { return null; + } - if (!this.getVisibleSector().contains(latitude, longitude)) + if (!this.getVisibleSector().contains(latitude, longitude)) { return null; + } SectorGeometryList sectorGeometry = this.getSurfaceGeometry(); - if (sectorGeometry != null) - { + if (sectorGeometry != null) { Vec4 p = sectorGeometry.getSurfacePoint(latitude, longitude); - if (p != null) + if (p != null) { return p; + } } return null; } - public SurfaceTileRenderer getGeographicSurfaceTileRenderer() - { + public SurfaceTileRenderer getGeographicSurfaceTileRenderer() { return this.geographicSurfaceTileRenderer; } - public Collection getPerFrameStatistics() - { + public Collection getPerFrameStatistics() { return this.perFrameStatistics; } - public void setPerFrameStatisticsKeys(Set statKeys, Collection stats) - { + public void setPerFrameStatisticsKeys(Set statKeys, Collection stats) { this.perFrameStatisticsKeys = statKeys; this.perFrameStatistics = stats; } - public Set getPerFrameStatisticsKeys() - { + public Set getPerFrameStatisticsKeys() { return perFrameStatisticsKeys; } - public void setPerFrameStatistic(String key, String displayName, Object value) - { - if (this.perFrameStatistics == null || this.perFrameStatisticsKeys == null) + public void setPerFrameStatistic(String key, String displayName, Object value) { + if (this.perFrameStatistics == null || this.perFrameStatisticsKeys == null) { return; + } - if (key == null) - { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (displayName == null) - { + if (displayName == null) { String message = Logging.getMessage("nullValue.DisplayNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.perFrameStatisticsKeys.contains(key) || this.perFrameStatisticsKeys.contains(PerformanceStatistic.ALL)) + if (this.perFrameStatisticsKeys.contains(key) || this.perFrameStatisticsKeys.contains(PerformanceStatistic.ALL)) { this.perFrameStatistics.add(new PerformanceStatistic(key, displayName, value)); + } } - public void setPerFrameStatistics(Collection stats) - { - if (stats == null) - { + public void setPerFrameStatistics(Collection stats) { + if (stats == null) { String message = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.perFrameStatistics == null || this.perFrameStatisticsKeys == null) + if (this.perFrameStatistics == null || this.perFrameStatisticsKeys == null) { return; + } - for (PerformanceStatistic stat : stats) - { + for (PerformanceStatistic stat : stats) { this.perFrameStatistics.add(stat); } } - public long getFrameTimeStamp() - { + public long getFrameTimeStamp() { return this.frameTimestamp; } - public void setFrameTimeStamp(long frameTimeStamp) - { + public void setFrameTimeStamp(long frameTimeStamp) { this.frameTimestamp = frameTimeStamp; } - public List getVisibleSectors(double[] resolutions, long timeLimit, Sector sector) - { - if (resolutions == null) - { + public List getVisibleSectors(double[] resolutions, long timeLimit, Sector sector) { + if (resolutions == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (timeLimit <= 0) - { + if (timeLimit <= 0) { String message = Logging.getMessage("generic.TimeNegative", timeLimit); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) + if (sector == null) { sector = this.visibleSector; + } - if (this.visibleSectors == null) + if (this.visibleSectors == null) { this.visibleSectors = new SectorVisibilityTree(); - else if (this.visibleSectors.getSectorSize() == resolutions[resolutions.length - 1] - && this.visibleSectors.getTimeStamp() == this.frameTimestamp) + } else if (this.visibleSectors.getSectorSize() == resolutions[resolutions.length - 1] + && this.visibleSectors.getTimeStamp() == this.frameTimestamp) { return this.visibleSectors.getSectors(); + } long start = System.currentTimeMillis(); List sectors = this.visibleSectors.refresh(this, resolutions[0], sector); - for (int i = 1; i < resolutions.length && (System.currentTimeMillis() < start + timeLimit); i++) - { + for (int i = 1; i < resolutions.length && (System.currentTimeMillis() < start + timeLimit); i++) { sectors = this.visibleSectors.refresh(this, resolutions[i], sectors); } @@ -1084,22 +998,18 @@ else if (this.visibleSectors.getSectorSize() == resolutions[resolutions.length - return this.visibleSectors.getSectors(); } - public void setCurrentLayer(Layer layer) - { + public void setCurrentLayer(Layer layer) { this.currentLayer = layer; } - public Layer getCurrentLayer() - { + public Layer getCurrentLayer() { return this.currentLayer; } protected LinkedHashMap credits = new LinkedHashMap(); - public void addScreenCredit(ScreenCredit credit) - { - if (credit == null) - { + public void addScreenCredit(ScreenCredit credit) { + if (credit == null) { String message = Logging.getMessage("nullValue.ScreenCreditIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1108,37 +1018,30 @@ public void addScreenCredit(ScreenCredit credit) this.credits.put(credit, this.frameTimestamp); } - public Map getScreenCredits() - { + public Map getScreenCredits() { return this.credits; } - public int getRedrawRequested() - { + public int getRedrawRequested() { return redrawRequested; } - public void setRedrawRequested(int redrawRequested) - { + public void setRedrawRequested(int redrawRequested) { this.redrawRequested = redrawRequested; } - public PickPointFrustumList getPickFrustums() - { + public PickPointFrustumList getPickFrustums() { return this.pickFrustumList; } - public void setPickPointFrustumDimension(Dimension dim) - { - if (dim == null) - { + public void setPickPointFrustumDimension(Dimension dim) { + if (dim == null) { String message = Logging.getMessage("nullValue.DimensionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dim.width < 3 || dim.height < 3) - { + if (dim.width < 3 || dim.height < 3) { String message = Logging.getMessage("DrawContext.PickPointFrustumDimensionTooSmall"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1147,16 +1050,13 @@ public void setPickPointFrustumDimension(Dimension dim) this.pickPointFrustumDimension = new Dimension(dim); } - public Dimension getPickPointFrustumDimension() - { + public Dimension getPickPointFrustumDimension() { return this.pickPointFrustumDimension; } - public void addPickPointFrustum() - { + public void addPickPointFrustum() { //Compute the current picking frustum - if (getPickPoint() != null) - { + if (getPickPoint() != null) { Rectangle viewport = getView().getViewport(); double viewportWidth = viewport.getWidth() <= 0.0 ? 1.0 : viewport.getWidth(); @@ -1172,8 +1072,9 @@ public void addPickPointFrustum() int offsetY = pickPointFrustumDimension.height / 2; //If the frustum is not valid then don't add it and return silently - if (offsetX == 0 || offsetY == 0) + if (offsetX == 0 || offsetY == 0) { return; + } //Compute the distance to the near plane in screen coordinates double width = getView().getFieldOfView().tanHalfAngle() * getView().getNearClipDistance(); @@ -1188,28 +1089,29 @@ public void addPickPointFrustum() //Compute the frustum from these four vectors Frustum frustum = Frustum.fromPerspectiveVecs(vTL, vTR, vBL, vBR, - getView().getNearClipDistance(), getView().getFarClipDistance()); + getView().getNearClipDistance(), getView().getFarClipDistance()); //Create the screen rectangle associated with this frustum Rectangle rectScreen = new Rectangle(getPickPoint().x - offsetX, - (int) viewportHeight - getPickPoint().y - offsetY, - pickPointFrustumDimension.width, - pickPointFrustumDimension.height); + (int) viewportHeight - getPickPoint().y - offsetY, + pickPointFrustumDimension.width, + pickPointFrustumDimension.height); //Transform the frustum to Model Coordinates Matrix modelviewTranspose = getView().getModelviewMatrix().getTranspose(); - if (modelviewTranspose != null) + if (modelviewTranspose != null) { frustum = frustum.transformBy(modelviewTranspose); + } this.pickFrustumList.add(new PickPointFrustum(frustum, rectScreen)); } } - public void addPickRectangleFrustum() - { + public void addPickRectangleFrustum() { // Do nothing if the pick rectangle is either null or has zero dimension. - if (this.getPickRectangle() == null || this.getPickRectangle().isEmpty()) + if (this.getPickRectangle() == null || this.getPickRectangle().isEmpty()) { return; + } View view = this.getView(); @@ -1233,12 +1135,13 @@ public void addPickRectangleFrustum() // Compute the frustum from these four vectors. Frustum frustum = Frustum.fromPerspectiveVecs(vTL, vTR, vBL, vBR, view.getNearClipDistance(), - view.getFarClipDistance()); + view.getFarClipDistance()); // Transform the frustum from eye coordinates to model coordinates. Matrix modelviewTranspose = view.getModelviewMatrix().getTranspose(); - if (modelviewTranspose != null) + if (modelviewTranspose != null) { frustum = frustum.transformBy(modelviewTranspose); + } // Create the screen rectangle in OpenGL screen coordinates associated with this frustum. We translate the // specified pick rectangle from AWT coordinates to GL coordinates by inverting the y axis. @@ -1248,25 +1151,22 @@ public void addPickRectangleFrustum() this.pickFrustumList.add(new PickPointFrustum(frustum, screenRect)); } - public Collection getRenderingExceptions() - { + public Collection getRenderingExceptions() { return this.renderingExceptions; } - public void setRenderingExceptions(Collection exceptions) - { + public void setRenderingExceptions(Collection exceptions) { this.renderingExceptions = exceptions; } - public void addRenderingException(Throwable t) - { + public void addRenderingException(Throwable t) { // If the renderingExceptions Collection is non-null, it's used as the data structure that accumulates rendering // exceptions. Otherwise this DrawContext ignores all rendering exceptions passed to this method. - if (this.renderingExceptions == null) + if (this.renderingExceptions == null) { return; + } - if (t == null) - { + if (t == null) { String message = Logging.getMessage("nullValue.ThrowableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1275,8 +1175,7 @@ public void addRenderingException(Throwable t) this.renderingExceptions.add(t); } - public void pushProjectionOffest(Double offset) - { + public void pushProjectionOffest(Double offset) { // Modify the projection transform to shift the depth values slightly toward the camera in order to // ensure the lines are selected during depth buffering. GL2 gl = this.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -1291,8 +1190,7 @@ public void pushProjectionOffest(Double offset) gl.glLoadMatrixf(pm, 0); } - public void popProjectionOffest() - { + public void popProjectionOffest() { GL2 gl = this.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glMatrixMode(GL2.GL_PROJECTION); @@ -1303,8 +1201,7 @@ public void popProjectionOffest() public static final float DEFAULT_DEPTH_OFFSET_FACTOR = 1f; public static final float DEFAULT_DEPTH_OFFSET_UNITS = 1f; - public void drawOutlinedShape(OutlinedShape renderer, Object shape) - { + public void drawOutlinedShape(OutlinedShape renderer, Object shape) { // Draw the outlined shape using a multiple pass algorithm. The motivation for this algorithm is twofold: // // * The outline appears both in front of and behind the shape. If the outline is drawn using GL line smoothing @@ -1318,20 +1215,21 @@ public void drawOutlinedShape(OutlinedShape renderer, Object shape) GL2 gl = this.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (this.isDeepPickingEnabled()) - { - if (renderer.isDrawInterior(this, shape)) + if (this.isDeepPickingEnabled()) { + if (renderer.isDrawInterior(this, shape)) { renderer.drawInterior(this, shape); + } if (renderer.isDrawOutline(this, shape)) // the line might extend outside the interior's projection + { renderer.drawOutline(this, shape); + } return; } // Optimize the outline-only case. - if (renderer.isDrawOutline(this, shape) && !renderer.isDrawInterior(this, shape)) - { + if (renderer.isDrawOutline(this, shape) && !renderer.isDrawInterior(this, shape)) { renderer.drawOutline(this, shape); return; } @@ -1340,16 +1238,14 @@ public void drawOutlinedShape(OutlinedShape renderer, Object shape) int attribMask = GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_POLYGON_BIT; ogsh.pushAttrib(gl, attribMask); - try - { + try { gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(GL.GL_LEQUAL); // If the outline and interior are enabled, then draw the outline but do not affect the depth buffer. The // fill pixels contribute the depth values. When the interior is drawn, it draws on top of these colors, and // the outline is be visible behind the potentially transparent interior. - if (renderer.isDrawOutline(this, shape) && renderer.isDrawInterior(this, shape)) - { + if (renderer.isDrawOutline(this, shape) && renderer.isDrawInterior(this, shape)) { gl.glColorMask(true, true, true, true); gl.glDepthMask(false); @@ -1363,10 +1259,8 @@ public void drawOutlinedShape(OutlinedShape renderer, Object shape) // priority over the fill, and gives the fill depth priority over other shapes drawn with depth offset // enabled. By drawing the colors without depth offset, we avoid the problem of having to use ever // increasing depth offsets. - if (renderer.isDrawInterior(this, shape)) - { - if (renderer.isEnableDepthOffset(this, shape)) - { + if (renderer.isDrawInterior(this, shape)) { + if (renderer.isEnableDepthOffset(this, shape)) { // Draw depth. gl.glColorMask(false, false, false, false); gl.glDepthMask(true); @@ -1374,8 +1268,8 @@ public void drawOutlinedShape(OutlinedShape renderer, Object shape) Double depthOffsetFactor = renderer.getDepthOffsetFactor(this, shape); Double depthOffsetUnits = renderer.getDepthOffsetUnits(this, shape); gl.glPolygonOffset( - depthOffsetFactor != null ? depthOffsetFactor.floatValue() : DEFAULT_DEPTH_OFFSET_FACTOR, - depthOffsetUnits != null ? depthOffsetUnits.floatValue() : DEFAULT_DEPTH_OFFSET_UNITS); + depthOffsetFactor != null ? depthOffsetFactor.floatValue() : DEFAULT_DEPTH_OFFSET_FACTOR, + depthOffsetUnits != null ? depthOffsetUnits.floatValue() : DEFAULT_DEPTH_OFFSET_UNITS); renderer.drawInterior(this, shape); @@ -1385,9 +1279,7 @@ public void drawOutlinedShape(OutlinedShape renderer, Object shape) gl.glDisable(GL.GL_POLYGON_OFFSET_FILL); renderer.drawInterior(this, shape); - } - else - { + } else { gl.glColorMask(true, true, true, true); gl.glDepthMask(true); @@ -1397,135 +1289,117 @@ public void drawOutlinedShape(OutlinedShape renderer, Object shape) // If the outline is enabled, then draw the outline color and depth values. This blends outline colors with // the interior colors. - if (renderer.isDrawOutline(this, shape)) - { + if (renderer.isDrawOutline(this, shape)) { gl.glColorMask(true, true, true, true); gl.glDepthMask(true); renderer.drawOutline(this, shape); } - } - finally - { + } finally { ogsh.pop(gl); } } - public void beginStandardLighting() - { - if (this.standardLighting != null) - { + public void beginStandardLighting() { + if (this.standardLighting != null) { this.standardLighting.beginLighting(this); this.getGL().glEnable(GL2.GL_LIGHTING); } } - public void endStandardLighting() - { - if (this.standardLighting != null) - { + public void endStandardLighting() { + if (this.standardLighting != null) { this.standardLighting.endLighting(this); } } - public boolean isSmall(Extent extent, int numPixels) - { + public boolean isSmall(Extent extent, int numPixels) { return extent != null && extent.getDiameter() <= numPixels * this.getView().computePixelSizeAtDistance( - // burkey couldnt we make this minimum dimension - this.getView().getEyePoint().distanceTo3( - extent.getCenter())); // -- so box could return small when one dim is narrow? + // burkey couldnt we make this minimum dimension + this.getView().getEyePoint().distanceTo3( + extent.getCenter())); // -- so box could return small when one dim is narrow? } // i see really skinny telephone poles that dont need to be rendered at distance but are tall - public Terrain getTerrain() - { + public Terrain getTerrain() { return this.terrain; } - public Vec4 computeTerrainPoint(Angle lat, Angle lon, double offset) - { + public Vec4 computeTerrainPoint(Angle lat, Angle lon, double offset) { return this.getTerrain().getSurfacePoint(lat, lon, offset); } - protected Terrain terrain = new Terrain() - { - public Globe getGlobe() - { + protected Terrain terrain = new Terrain() { + public Globe getGlobe() { return DrawContextImpl.this.getGlobe(); } - public double getVerticalExaggeration() - { + public double getVerticalExaggeration() { return DrawContextImpl.this.getVerticalExaggeration(); } - public Vec4 getSurfacePoint(Position position) - { - if (position == null) - { + public Vec4 getSurfacePoint(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } SectorGeometryList sectorGeometry = DrawContextImpl.this.getSurfaceGeometry(); - if (sectorGeometry == null) + if (sectorGeometry == null) { return null; + } Vec4 pt = sectorGeometry.getSurfacePoint(position); - if (pt == null) - { + if (pt == null) { double elevation = this.getGlobe().getElevation(position.getLatitude(), position.getLongitude()); pt = this.getGlobe().computePointFromPosition(position, - position.getAltitude() + elevation * this.getVerticalExaggeration()); + position.getAltitude() + elevation * this.getVerticalExaggeration()); } return pt; } - public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset) - { - if (latitude == null || longitude == null) - { + public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } SectorGeometryList sectorGeometry = DrawContextImpl.this.getSurfaceGeometry(); - if (sectorGeometry == null) + if (sectorGeometry == null) { return null; + } Vec4 pt = sectorGeometry.getSurfacePoint(latitude, longitude, metersOffset); - if (pt == null) - { + if (pt == null) { double elevation = this.getGlobe().getElevation(latitude, longitude); pt = this.getGlobe().computePointFromPosition(latitude, longitude, - metersOffset + elevation * this.getVerticalExaggeration()); + metersOffset + elevation * this.getVerticalExaggeration()); } return pt; } - public Intersection[] intersect(Position pA, Position pB) - { + public Intersection[] intersect(Position pA, Position pB) { SectorGeometryList sectorGeometry = DrawContextImpl.this.getSurfaceGeometry(); - if (sectorGeometry == null) + if (sectorGeometry == null) { return null; + } Vec4 ptA = this.getSurfacePoint(pA); Vec4 ptB = this.getSurfacePoint(pB); - if (pA == null || pB == null) + if (pA == null || pB == null) { return null; + } return sectorGeometry.intersect(new Line(ptA, ptB.subtract3(ptA))); } - public Intersection[] intersect(Position pA, Position pB, int altitudeMode) - { - if (pA == null || pB == null) - { + public Intersection[] intersect(Position pA, Position pB, int altitudeMode) { + if (pA == null || pB == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1534,13 +1408,10 @@ public Intersection[] intersect(Position pA, Position pB, int altitudeMode) // The intersect method expects altitudes to be relative to ground, so make them so if they aren't already. double altitudeA = pA.getAltitude(); double altitudeB = pB.getAltitude(); - if (altitudeMode == WorldWind.ABSOLUTE) - { + if (altitudeMode == WorldWind.ABSOLUTE) { altitudeA -= this.getElevation(pA); altitudeB -= this.getElevation(pB); - } - else if (altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + } else if (altitudeMode == WorldWind.CLAMP_TO_GROUND) { altitudeA = 0; altitudeB = 0; } @@ -1548,18 +1419,17 @@ else if (altitudeMode == WorldWind.CLAMP_TO_GROUND) return this.intersect(new Position(pA, altitudeA), new Position(pB, altitudeB)); } - public Double getElevation(LatLon location) - { - if (location == null) - { + public Double getElevation(LatLon location) { + if (location == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Vec4 pt = this.getSurfacePoint(location.getLatitude(), location.getLongitude(), 0); - if (pt == null) + if (pt == null) { return null; + } Vec4 p = this.getGlobe().computePointFromPosition(location.getLatitude(), location.getLongitude(), 0); @@ -1567,28 +1437,23 @@ public Double getElevation(LatLon location) } }; - public void restoreDefaultBlending() - { + public void restoreDefaultBlending() { this.getGL().glBlendFunc(GL.GL_ONE, GL.GL_ZERO); this.getGL().glDisable(GL.GL_BLEND); } - public void restoreDefaultCurrentColor() - { + public void restoreDefaultCurrentColor() { GL2 gl = this.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glColor4f(1, 1, 1, 1); } - public void restoreDefaultDepthTesting() - { + public void restoreDefaultDepthTesting() { this.getGL().glEnable(GL.GL_DEPTH_TEST); this.getGL().glDepthMask(true); } - public Vec4 computePointFromPosition(Position position, int altitudeMode) - { - if (position == null) - { + public Vec4 computePointFromPosition(Position position, int altitudeMode) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1596,20 +1461,16 @@ public Vec4 computePointFromPosition(Position position, int altitudeMode) Vec4 point; - if (altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + if (altitudeMode == WorldWind.CLAMP_TO_GROUND) { point = this.computeTerrainPoint(position.getLatitude(), position.getLongitude(), 0); - } - else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) { point = this.computeTerrainPoint(position.getLatitude(), position.getLongitude(), - position.getAltitude()); - } - else // ABSOLUTE + position.getAltitude()); + } else // ABSOLUTE { double height = position.getElevation() * this.getVerticalExaggeration(); point = this.getGlobe().computePointFromPosition(position.getLatitude(), - position.getLongitude(), height); + position.getLongitude(), height); } return point; diff --git a/src/gov/nasa/worldwind/render/Ellipsoid.java b/src/gov/nasa/worldwind/render/Ellipsoid.java index 3fd509a56b..00c143e629 100644 --- a/src/gov/nasa/worldwind/render/Ellipsoid.java +++ b/src/gov/nasa/worldwind/render/Ellipsoid.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -27,40 +26,38 @@ * @author tag * @version $Id: Ellipsoid.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Ellipsoid extends RigidShape -{ +public class Ellipsoid extends RigidShape { + protected static final int DEFAULT_SUBDIVISIONS = 2; // Geometry. protected int subdivisions = DEFAULT_SUBDIVISIONS; - /** Construct a default ellipsoid with centerPosition ZERO and radii all equal to one. */ - public Ellipsoid() - { + /** + * Construct a default ellipsoid with centerPosition ZERO and radii all equal to one. + */ + public Ellipsoid() { this.setUpGeometryCache(); } /** * Construct an ellipsoid from a specified center position and axes lengths. * - * @param centerPosition the ellipsoid's center position. + * @param centerPosition the ellipsoid's center position. * @param northSouthRadius the ellipsoid's north-south radius, in meters. - * @param verticalRadius the ellipsoid's vertical radius, in meters. - * @param eastWestRadius the ellipsoid's east-west radius, in meters. + * @param verticalRadius the ellipsoid's vertical radius, in meters. + * @param eastWestRadius the ellipsoid's east-west radius, in meters. * * @throws IllegalArgumentException if the center position is null or any of the radii are not greater than 0. */ - public Ellipsoid(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) - { - if (centerPosition == null) - { + public Ellipsoid(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -78,26 +75,23 @@ public Ellipsoid(Position centerPosition, double northSouthRadius, double vertic * Construct an ellipsoid from a specified center position, axes lengths and rotation angles. All angles are * specified in degrees and positive angles are counter-clockwise. * - * @param centerPosition the ellipsoid's center position. + * @param centerPosition the ellipsoid's center position. * @param northSouthRadius the ellipsoid's north-south radius, in meters. - * @param verticalRadius the ellipsoid's vertical radius, in meters. - * @param eastWestRadius the ellipsoid's east-west radius, in meters. - * @param heading the ellipsoid's azimuth, its rotation about its vertical axis. - * @param tilt the ellipsoids pitch, its rotation about its east-west axis. - * @param roll the ellipsoid's roll, its rotation about its north-south axis. + * @param verticalRadius the ellipsoid's vertical radius, in meters. + * @param eastWestRadius the ellipsoid's east-west radius, in meters. + * @param heading the ellipsoid's azimuth, its rotation about its vertical axis. + * @param tilt the ellipsoids pitch, its rotation about its east-west axis. + * @param roll the ellipsoid's roll, its rotation about its north-south axis. */ public Ellipsoid(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius, - Angle heading, Angle tilt, Angle roll) - { - if (centerPosition == null) - { + Angle heading, Angle tilt, Angle roll) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -114,8 +108,7 @@ public Ellipsoid(Position centerPosition, double northSouthRadius, double vertic this.setUpGeometryCache(); } - public int getSubdivisions() - { + public int getSubdivisions() { return this.subdivisions; } @@ -124,8 +117,7 @@ public int getSubdivisions() * * @return the detailThreshold */ - protected double computeDetailThreshold() - { + protected double computeDetailThreshold() { // these values must be calibrated on a shape-by-shape basis double detailThreshold = 20; double rangeDetailThreshold = 40; @@ -139,47 +131,44 @@ protected double computeDetailThreshold() * Computes the number of subdivisions necessary to achieve the expected Level of Detail given the shape's * relationship to the viewer. * - * @param dc the current drawContext. + * @param dc the current drawContext. * @param shapeData the current globe-specific shape data */ - protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) - { + protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) { // test again possible subdivision values int minDivisions = 0; int maxDivisions = 6; - if (shapeData.getExtent() != null) - { - for (int divisions = minDivisions; divisions <= maxDivisions; divisions++) - { + if (shapeData.getExtent() != null) { + for (int divisions = minDivisions; divisions <= maxDivisions; divisions++) { this.subdivisions = divisions; - if (this.sufficientDetail(dc, divisions, shapeData)) + if (this.sufficientDetail(dc, divisions, shapeData)) { break; + } } } } - protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData shapeData) - { - if (dc.getView() == null) - { + protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData shapeData) { + if (dc.getView() == null) { String message = "nullValue.DrawingContextViewIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (shapeData == null) + if (shapeData == null) { return false; + } Extent extent = shapeData.getExtent(); - if (extent == null) + if (extent == null) { return true; + } double thresholdDensity = this.computeDetailThreshold(); @@ -193,13 +182,13 @@ protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData s return vertexDensity > thresholdDensity; } - protected boolean mustRegenerateGeometry(DrawContext dc) - { + protected boolean mustRegenerateGeometry(DrawContext dc) { // check if current LOD is sufficient int oldDivisions = this.subdivisions; computeSubdivisions(dc, this.getCurrentShapeData()); - if (oldDivisions != this.subdivisions) + if (oldDivisions != this.subdivisions) { return true; + } return super.mustRegenerateGeometry(dc); } @@ -207,28 +196,23 @@ protected boolean mustRegenerateGeometry(DrawContext dc) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - /** * Sets the Geometry mesh for this Ellipsoid, either by pulling it from the geometryCache, or by creating it anew if * the appropriate geometry does not yet exist in the cache. * * @param shapeData the current shape data. */ - protected void makeGeometry(ShapeData shapeData) - { + protected void makeGeometry(ShapeData shapeData) { // attempt to retrieve a cached unit ellipsoid with the same number of subdivisions Object cacheKey = new Geometry.CacheKey(this.getClass(), "Sphere", this.subdivisions); Geometry geom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null) - { + if (geom == null) { // if none exists, create a new one shapeData.addMesh(0, new Geometry()); makeUnitSphere(this.subdivisions, shapeData.getMesh(0)); //this.restart(dc, geom); this.getGeometryCache().add(cacheKey, shapeData.getMesh(0)); - } - else - { + } else { // otherwise, just use the one from the cache shapeData.addMesh(0, geom); } @@ -239,18 +223,17 @@ protected void makeGeometry(ShapeData shapeData) * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit sphere geometry - * @param dest the Geometry container to hold the computed points, etc. + * @param dest the Geometry container to hold the computed points, etc. */ - protected void makeUnitSphere(int subdivisions, Geometry dest) - { + protected void makeUnitSphere(int subdivisions, Geometry dest) { float radius = 1.0f; GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(GeometryBuilder.OUTSIDE); // create ellipsoid in model space - GeometryBuilder.IndexedTriangleBuffer itb = - gb.tessellateSphereBuffer(radius, subdivisions); + GeometryBuilder.IndexedTriangleBuffer itb + = gb.tessellateSphereBuffer(radius, subdivisions); // add extra vertices so that texture will not have a seam int seamVerticesIndex = itb.getVertexCount(); @@ -271,19 +254,17 @@ protected void makeUnitSphere(int subdivisions, Geometry dest) /** * Renders the Ellipsoid, using data from the provided buffer and the given parameters. * - * @param dc the current draw context - * @param mode the render mode - * @param count the number of elements to be drawn - * @param type the data type of the elements to be drawn + * @param dc the current draw context + * @param mode the render mode + * @param count the number of elements to be drawn + * @param type the data type of the elements to be drawn * @param elementBuffer the buffer containing the list of elements to be drawn - * @param shapeData this shape's current globe-specific shape data - * @param face the shape face currently being drawn + * @param shapeData this shape's current globe-specific shape data + * @param face the shape face currently being drawn */ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffer elementBuffer, - ShapeData shapeData, int face) - { - if (elementBuffer == null) - { + ShapeData shapeData, int face) { + if (elementBuffer == null) { String message = "nullValue.ElementBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -291,8 +272,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe Geometry mesh = shapeData.getMesh(face); - if (mesh.getBuffer(Geometry.VERTEX) == null) - { + if (mesh.getBuffer(Geometry.VERTEX) == null) { String message = "nullValue.VertexBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -309,17 +289,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe vertexBuffer = mesh.getBuffer(Geometry.VERTEX); normalBuffer = null; - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { normalBuffer = mesh.getBuffer(Geometry.NORMAL); - if (normalBuffer == null) - { + if (normalBuffer == null) { gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); - } - else - { + } else { glType = mesh.getGLType(Geometry.NORMAL); stride = mesh.getStride(Geometry.NORMAL); gl.glNormalPointer(glType, stride, normalBuffer); @@ -334,10 +309,8 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // testing: disable VBO's // boolean vboState = dc.getGLRuntimeCapabilities().isVertexBufferObjectEnabled(); // dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(true); - // decide whether to draw with VBO's or VA's - if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) - { + if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) { // render using VBO's gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getVboIds(getSubdivisions(), dc)[2 * face]); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, this.getVboIds(getSubdivisions(), dc)[2 * face + 1]); @@ -347,9 +320,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); - } - else - { + } else { // render using vertex arrays gl.glVertexPointer(size, glType, stride, vertexBuffer.rewind()); gl.glDrawElements(mode, count, type, elementBuffer); @@ -360,17 +331,15 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // restore VBO state // testing: dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(false); - // disable back face culling gl.glDisable(GL.GL_CULL_FACE); - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { // re-enable normals if we temporarily turned them off earlier - if (normalBuffer == null) + if (normalBuffer == null) { gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); + } } // this.logGeometryStatistics(dc, geom); } @@ -380,21 +349,19 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe * Generates ellipsoidal geometry, including the vertices, indices, normals and texture coordinates, tessellated * with the specified number of divisions. * - * @param a the Ellipsoid radius along the east-west axis - * @param b the Ellipsoid radius along the vertical axis - * @param c the Ellipsoid radius along the north-south axis + * @param a the Ellipsoid radius along the east-west axis + * @param b the Ellipsoid radius along the vertical axis + * @param c the Ellipsoid radius along the north-south axis * @param subdivisions the number of times to subdivide the unit sphere geometry - * @param dest the Geometry container to hold the computed points, etc. + * @param dest the Geometry container to hold the computed points, etc. */ - - protected void makeEllipsoid(double a, double b, double c, int subdivisions, Geometry dest) - { + protected void makeEllipsoid(double a, double b, double c, int subdivisions, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(GeometryBuilder.OUTSIDE); // create ellipsoid in model space - GeometryBuilder.IndexedTriangleBuffer itb = - gb.tessellateEllipsoidBuffer((float) a, (float) b, (float) c, subdivisions); + GeometryBuilder.IndexedTriangleBuffer itb + = gb.tessellateEllipsoidBuffer((float) a, (float) b, (float) c, subdivisions); FloatBuffer normalBuffer = Buffers.newDirectFloatBuffer(3 * itb.getVertexCount()); gb.makeIndexedTriangleBufferNormals(itb, normalBuffer); @@ -404,8 +371,7 @@ protected void makeEllipsoid(double a, double b, double c, int subdivisions, Geo dest.setNormalData(normalBuffer.limit(), normalBuffer); } - protected ShapeData createIntersectionGeometry(Terrain terrain) - { + protected ShapeData createIntersectionGeometry(Terrain terrain) { ShapeData shapeData = new ShapeData(null, this); shapeData.setGlobeStateKey(terrain.getGlobe().getGlobeStateKey()); @@ -415,28 +381,28 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) // transform the vertices from local to world coords Matrix matrix = computeRenderMatrix(terrain.getGlobe(), terrain.getVerticalExaggeration()); FloatBuffer newVertices = computeTransformedVertices((FloatBuffer) geom.getBuffer(Geometry.VERTEX), - geom.getCount(Geometry.VERTEX), matrix); + geom.getCount(Geometry.VERTEX), matrix); geom.setVertexData(geom.getCount(Geometry.VERTEX), newVertices); shapeData.addMesh(0, geom); shapeData.setReferencePoint(this.computeReferencePoint(terrain.getGlobe(), - terrain.getVerticalExaggeration())); + terrain.getVerticalExaggeration())); shapeData.setExtent(getExtent(terrain.getGlobe(), terrain.getVerticalExaggeration())); return shapeData; } - /** No export formats supported. */ + /** + * No export formats supported. + */ @Override - public String isExportFormatSupported(String mimeType) - { + public String isExportFormatSupported(String mimeType) { // Overridden because this shape does not support export to KML. return Exportable.FORMAT_NOT_SUPPORTED; } @Override - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { String message = Logging.getMessage("generic.UnsupportedOperation", "doExportAsKML"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); diff --git a/src/gov/nasa/worldwind/render/ExtrudedPolygon.java b/src/gov/nasa/worldwind/render/ExtrudedPolygon.java index fafa5e873a..129bc4eb8c 100644 --- a/src/gov/nasa/worldwind/render/ExtrudedPolygon.java +++ b/src/gov/nasa/worldwind/render/ExtrudedPolygon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -70,73 +69,95 @@ * @author tag * @version $Id: ExtrudedPolygon.java 2111 2014-06-30 18:09:45Z tgaskins $ */ -public class ExtrudedPolygon extends AbstractShape -{ - /** The default interior color for sides. */ +public class ExtrudedPolygon extends AbstractShape { + + /** + * The default interior color for sides. + */ protected static final Material DEFAULT_SIDES_INTERIOR_MATERIAL = Material.LIGHT_GRAY; - /** The default altitude mode. */ + /** + * The default altitude mode. + */ protected static final int DEFAULT_ALTITUDE_MODE = WorldWind.CONSTANT; - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static final ShapeAttributes defaultSideAttributes; protected double baseDepth; - static - { + static { defaultSideAttributes = new BasicShapeAttributes(); defaultSideAttributes.setInteriorMaterial(DEFAULT_SIDES_INTERIOR_MATERIAL); } - /** The ShapeData class holds globe-specific data for this shape. */ - protected static class ShapeData extends AbstractShapeData implements Iterable - { - /** The boundary locations of the associated shape. Copied from that shape during construction. */ + /** + * The ShapeData class holds globe-specific data for this shape. + */ + protected static class ShapeData extends AbstractShapeData implements Iterable { + + /** + * The boundary locations of the associated shape. Copied from that shape during construction. + */ protected List boundaries = new ArrayList(); - /** A buffer holding the Cartesian cap vertices of all the shape's boundaries. */ + /** + * A buffer holding the Cartesian cap vertices of all the shape's boundaries. + */ protected FloatBuffer capVertexBuffer; - /** A buffer holding the cap normals of all the shape's boundaries. */ + /** + * A buffer holding the cap normals of all the shape's boundaries. + */ protected FloatBuffer capNormalBuffer; - /** A buffer holding the Cartesian vertices of all the shape's side vertices. */ + /** + * A buffer holding the Cartesian vertices of all the shape's side vertices. + */ protected FloatBuffer sideVertexBuffer; - /** A buffer holding the side normals of all the shape's boundaries. */ + /** + * A buffer holding the side normals of all the shape's boundaries. + */ protected FloatBuffer sideNormalBuffer; - /** A buffer holding the texture coordinates of all the shape's faces. Non-null only when texture is applied. */ + /** + * A buffer holding the texture coordinates of all the shape's faces. Non-null only when texture is applied. + */ protected FloatBuffer sideTextureCoordsBuffer; // Tessellation fields - /** This shape's tessellation. */ + /** + * This shape's tessellation. + */ protected GLUTessellatorSupport.CollectIndexListsCallback cb; /** * The indices identifying the cap vertices in a shape data's vertex buffer. Determined when this shape is * tessellated, which occurs only once unless the shape's boundaries are re-specified. */ protected IntBuffer capFillIndices; - /** Slices of capFillIndices, one per boundary. */ + /** + * Slices of capFillIndices, one per boundary. + */ protected List capFillIndexBuffers; - /** Indicates whether a tessellation error occurred. No more attempts to tessellate will be made if set to true. */ + /** + * Indicates whether a tessellation error occurred. No more attempts to tessellate will be made if set to true. + */ protected boolean tessellationError = false; /** * Constructs an instance using the boundaries of a specified extruded polygon. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape this shape. */ - public ShapeData(DrawContext dc, ExtrudedPolygon shape) - { + public ShapeData(DrawContext dc, ExtrudedPolygon shape) { super(dc, shape.minExpiryTime, shape.maxExpiryTime); - if (shape.boundaries.size() < 1) - { + if (shape.boundaries.size() < 1) { // add a placeholder for the outer boundary this.boundaries.add(new ExtrudedBoundaryInfo(new ArrayList())); return; } // Copy the shape's boundaries. - for (List boundary : shape.boundaries) - { + for (List boundary : shape.boundaries) { this.boundaries.add(new ExtrudedBoundaryInfo(boundary)); } @@ -144,15 +165,13 @@ public ShapeData(DrawContext dc, ExtrudedPolygon shape) this.copySideTextureReferences(shape); } - protected void copySideTextureReferences(ExtrudedPolygon shape) - { - if (shape.sideTextures != null) - { - for (int i = 0; i < this.boundaries.size() && i < shape.sideTextures.size(); i++) - { + protected void copySideTextureReferences(ExtrudedPolygon shape) { + if (shape.sideTextures != null) { + for (int i = 0; i < this.boundaries.size() && i < shape.sideTextures.size(); i++) { ExtrudedBoundaryInfo ebi = this.boundaries.get(i); - if (ebi != null) + if (ebi != null) { this.boundaries.get(i).sideTextures = shape.sideTextures.get(i); + } } } } @@ -162,8 +181,7 @@ protected void copySideTextureReferences(ExtrudedPolygon shape) * * @return this shape data's outer boundary information. */ - protected ExtrudedBoundaryInfo getOuterBoundaryInfo() - { + protected ExtrudedBoundaryInfo getOuterBoundaryInfo() { return this.boundaries.get(0); } @@ -172,15 +190,13 @@ protected ExtrudedBoundaryInfo getOuterBoundaryInfo() * * @return an iterator over this shape data's boundary info. */ - public Iterator iterator() - { + public Iterator iterator() { return this.boundaries.iterator(); } } @Override - protected AbstractShapeData createCacheEntry(DrawContext dc) - { + protected AbstractShapeData createCacheEntry(DrawContext dc) { return new ShapeData(dc, this); } @@ -189,8 +205,7 @@ protected AbstractShapeData createCacheEntry(DrawContext dc) * * @return the currently active shape data. */ - protected ShapeData getCurrent() - { + protected ShapeData getCurrent() { return (ShapeData) this.getCurrentData(); } @@ -198,36 +213,62 @@ protected ShapeData getCurrent() * Holds globe-specific information for each contour of the polygon. This class is meant only to be used as a way to * group per-boundary information in globe-specific ShapeData. */ - protected static class ExtrudedBoundaryInfo - { - /** The boundary vertices. This is merely a reference to the paren't shape's boundaries. */ + protected static class ExtrudedBoundaryInfo { + + /** + * The boundary vertices. This is merely a reference to the paren't shape's boundaries. + */ protected List locations; - /** The number of faces in the boundary. (The number of positions - 1.) */ + /** + * The number of faces in the boundary. (The number of positions - 1.) + */ protected int faceCount; - /** The vertices defining the boundary's cap. */ + /** + * The vertices defining the boundary's cap. + */ protected Vec4[] capVertices; - /** The vertices defining the boundary's base. These are always on the terrain. */ + /** + * The vertices defining the boundary's base. These are always on the terrain. + */ protected Vec4[] baseVertices; - /** Indices identifying the cap vertices in the vertex buffer. */ + /** + * Indices identifying the cap vertices in the vertex buffer. + */ protected IntBuffer capFillIndices; - /** Indices identifying the cap edges in the vertex buffer. */ + /** + * Indices identifying the cap edges in the vertex buffer. + */ protected IntBuffer capEdgeIndices; - /** A buffer holding the vertices defining the boundary's cap. */ + /** + * A buffer holding the vertices defining the boundary's cap. + */ protected FloatBuffer capVertexBuffer; - /** A buffer holding the boundary cap's vertex normals. Non-null only when lighting is applied. */ + /** + * A buffer holding the boundary cap's vertex normals. Non-null only when lighting is applied. + */ protected FloatBuffer capNormalBuffer; - /** The indices identifying the boundary's side faces in the side-vertex buffer. */ + /** + * The indices identifying the boundary's side faces in the side-vertex buffer. + */ protected IntBuffer sideIndices; - /** The indices identifying the boundary's edge indices in the side-vertex buffer. */ + /** + * The indices identifying the boundary's edge indices in the side-vertex buffer. + */ protected IntBuffer sideEdgeIndices; - /** A buffer holding the side vertices. These are passed to OpenGL. */ + /** + * A buffer holding the side vertices. These are passed to OpenGL. + */ protected FloatBuffer sideVertexBuffer; - /** A buffer holding per-vertex normals. Non-null only when lighting is applied. */ + /** + * A buffer holding per-vertex normals. Non-null only when lighting is applied. + */ protected FloatBuffer sideNormalBuffer; - /** The textures to apply to this boundary, one per face. */ + /** + * The textures to apply to this boundary, one per face. + */ protected List sideTextures; /** * The texture coordinates to use when applying side textures, a coordinate pair for each of 4 corners. These @@ -241,8 +282,7 @@ protected static class ExtrudedBoundaryInfo * * @param locations the boundary locations. Only this reference is kept; the boundaries are not copied. */ - public ExtrudedBoundaryInfo(List locations) - { + public ExtrudedBoundaryInfo(List locations) { this.locations = locations; this.faceCount = locations.size() - 1; } @@ -254,7 +294,9 @@ public ExtrudedBoundaryInfo(List locations) protected static HashMap sideFillIndexBuffers = new HashMap(); protected static HashMap sideEdgeIndexBuffers = new HashMap(); - /** Indicates the number of vertices that must be present in order for VBOs to be used to render this shape. */ + /** + * Indicates the number of vertices that must be present in order for VBOs to be used to render this shape. + */ protected static final int VBO_THRESHOLD = Configuration.getIntegerValue(AVKey.VBO_THRESHOLD, 30); /** @@ -262,42 +304,71 @@ public ExtrudedBoundaryInfo(List locations) * for the outer boundary, but its list is empty if an outer boundary has not been specified. */ protected List> boundaries; - /** The total number of locations in all boundaries. */ + /** + * The total number of locations in all boundaries. + */ protected int totalNumLocations; - /** The total number of faces in all this shape's boundaries. */ + /** + * The total number of faces in all this shape's boundaries. + */ protected int totalFaceCount; - /** This shape's height. Default is 1. */ + /** + * This shape's height. Default is 1. + */ protected double height = 1; - /** The attributes to use when drawing this shape's sides. */ + /** + * The attributes to use when drawing this shape's sides. + */ protected ShapeAttributes sideAttributes; - /** The attributes to use when drawing this shape's sides in highlight mode. */ + /** + * The attributes to use when drawing this shape's sides in highlight mode. + */ protected ShapeAttributes sideHighlightAttributes; - /** The currently active side attributes, derived from the specified attributes. Current only during rendering. */ + /** + * The currently active side attributes, derived from the specified attributes. Current only during rendering. + */ protected ShapeAttributes activeSideAttributes = new BasicShapeAttributes(); - /** This shape's side textures. */ + /** + * This shape's side textures. + */ protected List> sideTextures; - /** This shape's cap texture. */ + /** + * This shape's cap texture. + */ protected WWTexture capTexture; - /** This shape's cap texture coordinates. */ + /** + * This shape's cap texture coordinates. + */ protected FloatBuffer capTextureCoords; - /** Indicates whether the cap should be drawn. */ + /** + * Indicates whether the cap should be drawn. + */ protected boolean enableCap = true; - /** Indicates whether the sides should be drawn. */ + /** + * Indicates whether the sides should be drawn. + */ protected boolean enableSides = true; // Intersection fields - /** The terrain used in the most recent intersection calculations. */ + /** + * The terrain used in the most recent intersection calculations. + */ protected Terrain previousIntersectionTerrain; - /** The globe state key for the globe used in the most recent intersection calculation. */ + /** + * The globe state key for the globe used in the most recent intersection calculation. + */ protected Object previousIntersectionGlobeStateKey; - /** The shape data used for the previous intersection calculation. */ + /** + * The shape data used for the previous intersection calculation. + */ protected ShapeData previousIntersectionShapeData; - /** Constructs an extruded polygon with an empty outer boundary and a default height of 1 meter. */ - public ExtrudedPolygon() - { + /** + * Constructs an extruded polygon with an empty outer boundary and a default height of 1 meter. + */ + public ExtrudedPolygon() { this.boundaries = new ArrayList>(); this.boundaries.add(new ArrayList()); // placeholder for outer boundary } @@ -306,10 +377,9 @@ public ExtrudedPolygon() * Constructs an extruded polygon of a specified height and an empty outer boundary. * * @param height the shape height, in meters. May be null, in which case a height of 1 is used. The height is used - * only when the altitude mode is {@link WorldWind#CONSTANT}, which is the default for this shape. + * only when the altitude mode is {@link WorldWind#CONSTANT}, which is the default for this shape. */ - public ExtrudedPolygon(Double height) - { + public ExtrudedPolygon(Double height) { this(); // to initialize the instance this.setHeight(height); @@ -319,25 +389,22 @@ public ExtrudedPolygon(Double height) * Constructs an extruded polygon for a specified list of outer boundary locations and a height. * * @param corners the list of locations defining this extruded polygon's outer boundary. - * @param height the shape height, in meters. May be null, in which case a height of 1 is used. The height is used - * only when the altitude mode is {@link WorldWind#CONSTANT}, which is the default for this shape. + * @param height the shape height, in meters. May be null, in which case a height of 1 is used. The height is used + * only when the altitude mode is {@link WorldWind#CONSTANT}, which is the default for this shape. * * @throws IllegalArgumentException if the location list is null or the height is specified but less than or equal - * to zero. + * to zero. */ - public ExtrudedPolygon(Iterable corners, Double height) - { + public ExtrudedPolygon(Iterable corners, Double height) { this(); // to initialize the instance - if (corners == null) - { + if (corners == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height != null && height <= 0) - { + if (height != null && height <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -349,22 +416,19 @@ public ExtrudedPolygon(Iterable corners, Double height) /** * Constructs an extruded polygon from an outer boundary, a height, and images for its outer faces. * - * @param corners the list of locations defining this polygon's outer boundary. - * @param height the shape height, in meters. May be null, in which case a height of 1 is used. The height is - * used only when the altitude mode is {@link WorldWind#CONSTANT}, which is the default for this - * shape. + * @param corners the list of locations defining this polygon's outer boundary. + * @param height the shape height, in meters. May be null, in which case a height of 1 is used. The height is used + * only when the altitude mode is {@link WorldWind#CONSTANT}, which is the default for this shape. * @param imageSources images to apply to the polygon's outer faces. One image for each face must be included. May - * also be null. + * also be null. * * @throws IllegalArgumentException if the location list is null or the height is specified but less than or equal - * to zero. + * to zero. */ - public ExtrudedPolygon(Iterable corners, double height, Iterable imageSources) - { + public ExtrudedPolygon(Iterable corners, double height, Iterable imageSources) { this(corners, height); - if (imageSources != null) - { + if (imageSources != null) { this.sideTextures = new ArrayList>(); this.sideTextures.add(this.fillImageList(imageSources)); } @@ -374,13 +438,12 @@ public ExtrudedPolygon(Iterable corners, double height, Iterab * Constructs an extruded polygon from an outer boundary. * * @param corners the list of outer boundary positions -- latitude longitude and altitude. The altitude mode - * determines whether the positions are considered relative to mean sea level (they are "absolute") - * or the ground elevation at the associated latitude and longitude. + * determines whether the positions are considered relative to mean sea level (they are "absolute") or the ground + * elevation at the associated latitude and longitude. * * @throws IllegalArgumentException if the position list is null. */ - public ExtrudedPolygon(Iterable corners) - { + public ExtrudedPolygon(Iterable corners) { this(corners, 1d); // the height field is ignored when positions are specified, so any value will do } @@ -388,55 +451,51 @@ public ExtrudedPolygon(Iterable corners) * Constructs an extruded polygon from an outer boundary specified with position heights. * * @param corners the list of positions -- latitude longitude and altitude -- defining the polygon's outer boundary. - * The altitude mode determines whether the positions are considered relative to mean sea level (they - * are "absolute") or the ground elevation at the associated latitude and longitude. + * The altitude mode determines whether the positions are considered relative to mean sea level (they are + * "absolute") or the ground elevation at the associated latitude and longitude. * * @throws IllegalArgumentException if the position list is null. */ - public ExtrudedPolygon(Position.PositionList corners) - { + public ExtrudedPolygon(Position.PositionList corners) { this(corners.list, 1d); // the height field is ignored when positions are specified, so any value will do } /** * Constructs an extruded polygon from an outer boundary and apply specified textures to its outer faces. * - * @param corners the list of positions -- latitude longitude and altitude -- defining the polygon. The - * altitude mode determines whether the positions are considered relative to mean sea level - * (they are "absolute") or the ground elevation at the associated latitude and longitude. + * @param corners the list of positions -- latitude longitude and altitude -- defining the polygon. The altitude + * mode determines whether the positions are considered relative to mean sea level (they are "absolute") or the + * ground elevation at the associated latitude and longitude. * @param imageSources textures to apply to the polygon's outer faces. One texture for each face must be included. - * May also be null. + * May also be null. * * @throws IllegalArgumentException if the position list is null. */ - public ExtrudedPolygon(Iterable corners, Iterable imageSources) - { + public ExtrudedPolygon(Iterable corners, Iterable imageSources) { this(corners); - if (imageSources != null) - { + if (imageSources != null) { this.sideTextures = new ArrayList>(); this.sideTextures.add(this.fillImageList(imageSources)); } } - protected void initialize() - { + protected void initialize() { // Overridden to specify a default altitude mode unique to extruded polygons. this.altitudeMode = DEFAULT_ALTITUDE_MODE; } - protected void reset() - { + protected void reset() { // Assumes that the boundary lists have already been established. - for (List locations : this.boundaries) - { - if (locations == null || locations.size() < 3) + for (List locations : this.boundaries) { + if (locations == null || locations.size() < 3) { continue; + } - if (!WWMath.computeWindingOrderOfLocations(locations).equals(AVKey.COUNTER_CLOCKWISE)) + if (!WWMath.computeWindingOrderOfLocations(locations).equals(AVKey.COUNTER_CLOCKWISE)) { Collections.reverse(locations); + } } this.totalNumLocations = this.countLocations(); @@ -454,12 +513,10 @@ protected void reset() * * @return the number of locations in the polygon boundaries. */ - protected int countLocations() - { + protected int countLocations() { int count = 0; - for (List locations : this.boundaries) - { + for (List locations : this.boundaries) { count += locations.size(); } @@ -473,8 +530,7 @@ protected int countLocations() * * @return this polygon's positions. */ - public Iterable getOuterBoundary() - { + public Iterable getOuterBoundary() { return this.outerBoundary(); } @@ -483,8 +539,7 @@ public Iterable getOuterBoundary() * * @return this polygon's outer boundary. */ - protected List outerBoundary() - { + protected List outerBoundary() { return this.boundaries.get(0); } @@ -493,8 +548,7 @@ protected List outerBoundary() * * @return true if the outer boundary is valid, otherwise false.s */ - protected boolean isOuterBoundaryValid() - { + protected boolean isOuterBoundaryValid() { return this.boundaries.size() > 0 && this.boundaries.get(0).size() > 2; } @@ -506,8 +560,7 @@ protected boolean isOuterBoundaryValid() * * @throws IllegalArgumentException if the location list is null or contains fewer than three locations. */ - public void setOuterBoundary(Iterable corners) - { + public void setOuterBoundary(Iterable corners) { this.setOuterBoundary(corners, this.getHeight()); } @@ -515,33 +568,33 @@ public void setOuterBoundary(Iterable corners) * Specifies the latitudes, longitudes and outer-boundary images for the outer boundary of this polygon. To specify * altitudes, pass {@link Position}s rather than {@link LatLon}s. * - * @param corners the polygon locations. + * @param corners the polygon locations. * @param imageSources images to apply to the outer faces. One image must be specified for each face. May be null. * * @throws IllegalArgumentException if the location list is null. */ - public void setOuterBoundary(Iterable corners, Iterable imageSources) - { + public void setOuterBoundary(Iterable corners, Iterable imageSources) { this.setOuterBoundary(corners); - if (imageSources == null && this.sideTextures == null) + if (imageSources == null && this.sideTextures == null) { return; + } // Must install or replace the side textures - - if (this.sideTextures == null) + if (this.sideTextures == null) { this.sideTextures = new ArrayList>(); + } // Add or replace the first element, the outer boundary's element, in the list of side textures. List textures = this.fillImageList(imageSources); this.sideTextures.set(0, textures); // Update the shape cache - for (ShapeDataCache.ShapeDataCacheEntry entry : this.shapeDataCache) - { + for (ShapeDataCache.ShapeDataCacheEntry entry : this.shapeDataCache) { ShapeData sd = (ShapeData) entry; - if (sd.boundaries != null) + if (sd.boundaries != null) { sd.copySideTextureReferences(this); + } } } @@ -551,14 +604,12 @@ public void setOuterBoundary(Iterable corners, Iterable ima * {@link LatLon}s, but those altitudes are used only when the shape's altitude mode is {@link WorldWind#ABSOLUTE}. * * @param corners the outer boundary locations. - * @param height the shape height, in meters. + * @param height the shape height, in meters. * * @throws IllegalArgumentException if the location list is null or contains fewer than three locations. */ - public void setOuterBoundary(Iterable corners, Double height) - { - if (corners == null) - { + public void setOuterBoundary(Iterable corners, Double height) { + if (corners == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -566,31 +617,31 @@ public void setOuterBoundary(Iterable corners, Double height) this.getBoundaries().set(0, this.fillBoundary(corners)); - if (height != null) + if (height != null) { this.height = height; + } this.reset(); } - protected List fillBoundary(Iterable corners) - { + protected List fillBoundary(Iterable corners) { ArrayList list = new ArrayList(); - for (LatLon corner : corners) - { - if (corner != null) + for (LatLon corner : corners) { + if (corner != null) { list.add(corner); + } } - if (list.size() < 3) - { + if (list.size() < 3) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Close the list if not already closed. - if (list.size() > 0 && !list.get(0).equals(list.get(list.size() - 1))) + if (list.size() > 0 && !list.get(0).equals(list.get(list.size() - 1))) { list.add(list.get(0)); + } list.trimToSize(); @@ -604,10 +655,8 @@ protected List fillBoundary(Iterable corners * * @throws IllegalArgumentException if the location list is null or contains fewer than three locations. */ - public void addInnerBoundary(Iterable corners) - { - if (corners == null) - { + public void addInnerBoundary(Iterable corners) { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationInListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -622,16 +671,14 @@ public void addInnerBoundary(Iterable corners) * Add an inner boundary to this polygon and specify images to apply to each of the boundary's faces. Specify {@link * LatLon}s to use the polygon's single height, or {@link Position}s, to include individual altitudes. * - * @param corners the boundary's locations. + * @param corners the boundary's locations. * @param imageSources images to apply to the boundary's faces. One image must be specified for each face. May be - * null. + * null. * * @throws IllegalArgumentException if the location list is null. */ - public void addInnerBoundary(Iterable corners, Iterable imageSources) - { - if (corners == null) - { + public void addInnerBoundary(Iterable corners, Iterable imageSources) { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationInListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -639,10 +686,8 @@ public void addInnerBoundary(Iterable corners, Iterable ima this.getBoundaries().add(this.fillBoundary(corners)); - if (imageSources != null) - { - if (this.sideTextures == null) - { + if (imageSources != null) { + if (this.sideTextures == null) { this.sideTextures = new ArrayList>(); this.sideTextures.add(new ArrayList()); // placeholder for outer boundary } @@ -658,8 +703,7 @@ public void addInnerBoundary(Iterable corners, Iterable ima * * @return this shape's boundaries. */ - protected List> getBoundaries() - { + protected List> getBoundaries() { return this.boundaries; } @@ -670,19 +714,19 @@ protected List> getBoundaries() * * @return the list of texture objects, or null if the imageSources argument is null. */ - protected List fillImageList(Iterable imageSources) - { - if (imageSources == null) + protected List fillImageList(Iterable imageSources) { + if (imageSources == null) { return null; + } ArrayList textures = new ArrayList(); - for (Object source : imageSources) - { - if (source != null) + for (Object source : imageSources) { + if (source != null) { textures.add(this.makeTexture(source)); - else + } else { textures.add(null); + } } textures.trimToSize(); @@ -695,42 +739,36 @@ protected List fillImageList(Iterable imageSources) * * @return the texture image source, or null if no source has been specified. */ - public Object getCapImageSource() - { + public Object getCapImageSource() { return this.capTexture != null ? this.capTexture.getImageSource() : null; } /** * Specifies the image to apply to this extruded polygon's cap. * - * @param imageSource the image source. May be a {@link String} identifying a file path or URL, a {@link File}, or - * a {@link java.net.URL}. - * @param texCoords the (s, t) texture coordinates aligning the image to the polygon. There must be one texture - * coordinate pair, (s, t), for each location in the polygon's outer boundary. + * @param imageSource the image source. May be a {@link String} identifying a file path or URL, a {@link File}, or a + * {@link java.net.URL}. + * @param texCoords the (s, t) texture coordinates aligning the image to the polygon. There must be one texture + * coordinate pair, (s, t), for each location in the polygon's outer boundary. * @param texCoordCount the number of texture coordinates, (s, v) pairs, specified. * * @throws IllegalArgumentException if the image source is not null and either the texture coordinates are null or - * inconsistent with the specified texture-coordinate count, or there are fewer - * than three texture coordinate pairs. + * inconsistent with the specified texture-coordinate count, or there are fewer than three texture coordinate pairs. */ - public void setCapImageSource(Object imageSource, float[] texCoords, int texCoordCount) - { - if (imageSource == null) - { + public void setCapImageSource(Object imageSource, float[] texCoords, int texCoordCount) { + if (imageSource == null) { this.capTexture = null; this.capTextureCoords = null; return; } - if (texCoords == null) - { + if (texCoords == null) { String message = Logging.getMessage("generic.ListIsEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoordCount < 3 || texCoords.length < 2 * texCoordCount) - { + if (texCoordCount < 3 || texCoords.length < 2 * texCoordCount) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -742,13 +780,11 @@ public void setCapImageSource(Object imageSource, float[] texCoords, int texCoor boolean closeIt = texCoords[0] != texCoords[texCoordCount - 2] || texCoords[1] != texCoords[texCoordCount - 1]; this.capTextureCoords = Buffers.newDirectFloatBuffer(2 * (texCoordCount + (closeIt ? 1 : 0))); - for (int i = 0; i < 2 * texCoordCount; i++) - { + for (int i = 0; i < 2 * texCoordCount; i++) { this.capTextureCoords.put(texCoords[i]); } - if (closeIt) - { + if (closeIt) { this.capTextureCoords.put(this.capTextureCoords.get(0)); this.capTextureCoords.put(this.capTextureCoords.get(1)); } @@ -759,10 +795,10 @@ public void setCapImageSource(Object imageSource, float[] texCoords, int texCoor * * @return the texture coordinates, or null if no cap texture coordinates have been specified. */ - public float[] getTextureCoords() - { - if (this.capTextureCoords == null) + public float[] getTextureCoords() { + if (this.capTextureCoords == null) { return null; + } float[] retCoords = new float[this.capTextureCoords.limit()]; this.capTextureCoords.get(retCoords, 0, retCoords.length); @@ -775,8 +811,7 @@ public float[] getTextureCoords() * * @return The texture, or null if there is no texture or the texture is not yet available. */ - protected WWTexture getCapTexture() - { + protected WWTexture getCapTexture() { return this.capTexture; } @@ -785,8 +820,7 @@ protected WWTexture getCapTexture() * * @return the height originally specified, in meters. */ - public double getHeight() - { + public double getHeight() { return height; } @@ -797,13 +831,12 @@ public double getHeight() * * @throws IllegalArgumentException if the height is less than or equal to zero. */ - public void setHeight(double height) - { - if (this.height == height) + public void setHeight(double height) { + if (this.height == height) { return; + } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -818,8 +851,7 @@ public void setHeight(double height) * * @return true to draw the cap, otherwise false. */ - public boolean isEnableCap() - { + public boolean isEnableCap() { return enableCap; } @@ -828,8 +860,7 @@ public boolean isEnableCap() * * @param enableCap true to draw the cap, otherwise false. */ - public void setEnableCap(boolean enableCap) - { + public void setEnableCap(boolean enableCap) { this.enableCap = enableCap; } @@ -838,8 +869,7 @@ public void setEnableCap(boolean enableCap) * * @return true to draw the sides, otherwise false. */ - public boolean isEnableSides() - { + public boolean isEnableSides() { return enableSides; } @@ -848,8 +878,7 @@ public boolean isEnableSides() * * @param enableSides true to draw the sides, otherwise false. */ - public void setEnableSides(boolean enableSides) - { + public void setEnableSides(boolean enableSides) { this.enableSides = enableSides; } @@ -858,8 +887,7 @@ public void setEnableSides(boolean enableSides) * * @return this polygon's side attributes. */ - public ShapeAttributes getSideAttributes() - { + public ShapeAttributes getSideAttributes() { return this.sideAttributes; } @@ -870,10 +898,8 @@ public ShapeAttributes getSideAttributes() * * @throws IllegalArgumentException if attributes is null. */ - public void setSideAttributes(ShapeAttributes attributes) - { - if (attributes == null) - { + public void setSideAttributes(ShapeAttributes attributes) { + if (attributes == null) { String message = "nullValue.AttributesIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -887,8 +913,7 @@ public void setSideAttributes(ShapeAttributes attributes) * * @return this polygon's cap attributes. */ - public ShapeAttributes getCapAttributes() - { + public ShapeAttributes getCapAttributes() { return this.getAttributes(); } @@ -899,8 +924,7 @@ public ShapeAttributes getCapAttributes() * * @throws IllegalArgumentException if attributes is null. */ - public void setCapAttributes(ShapeAttributes attributes) - { + public void setCapAttributes(ShapeAttributes attributes) { this.setAttributes(attributes); } @@ -909,8 +933,7 @@ public void setCapAttributes(ShapeAttributes attributes) * * @return this polygon's side highlight attributes. */ - public ShapeAttributes getSideHighlightAttributes() - { + public ShapeAttributes getSideHighlightAttributes() { return sideHighlightAttributes; } @@ -921,10 +944,8 @@ public ShapeAttributes getSideHighlightAttributes() * * @throws IllegalArgumentException if attributes is null. */ - public void setSideHighlightAttributes(ShapeAttributes attributes) - { - if (attributes == null) - { + public void setSideHighlightAttributes(ShapeAttributes attributes) { + if (attributes == null) { String message = "nullValue.AttributesIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -938,8 +959,7 @@ public void setSideHighlightAttributes(ShapeAttributes attributes) * * @return this polygon's cap highlight attributes. */ - public ShapeAttributes getCapHighlightAttributes() - { + public ShapeAttributes getCapHighlightAttributes() { return this.getHighlightAttributes(); } @@ -950,8 +970,7 @@ public ShapeAttributes getCapHighlightAttributes() * * @throws IllegalArgumentException if attributes is null. */ - public void setCapHighlightAttributes(ShapeAttributes attributes) - { + public void setCapHighlightAttributes(ShapeAttributes attributes) { this.setHighlightAttributes(attributes); } @@ -961,8 +980,7 @@ public void setCapHighlightAttributes(ShapeAttributes attributes) * * @return the currently active attributes for this polygon's side faces. */ - protected ShapeAttributes getActiveSideAttributes() - { + protected ShapeAttributes getActiveSideAttributes() { return this.activeSideAttributes; } @@ -972,15 +990,14 @@ protected ShapeAttributes getActiveSideAttributes() * * @return the currently active attributes for this polygon's cap. */ - protected ShapeAttributes getActiveCapAttributes() - { + protected ShapeAttributes getActiveCapAttributes() { return this.getActiveAttributes(); } - public Sector getSector() - { - if (this.sector == null && this.outerBoundary().size() > 2) + public Sector getSector() { + if (this.sector == null && this.outerBoundary().size() > 2) { this.sector = Sector.boundingSector(this.getOuterBoundary()); + } return this.sector; } @@ -992,8 +1009,7 @@ public Sector getSector() * * @see #getReferencePosition() */ - public LatLon getReferenceLocation() - { + public LatLon getReferenceLocation() { return this.getReferencePosition(); } @@ -1002,14 +1018,12 @@ public LatLon getReferenceLocation() * to the default, which is the first location in the extruded polygon's outer boundary. * * @param referenceLocation the reference location. May be null, in which case the first location of the outer - * boundary is the reference location. + * boundary is the reference location. * * @see #setReferencePosition(gov.nasa.worldwind.geom.Position) */ - public void setReferenceLocation(LatLon referenceLocation) - { - if (referenceLocation == null) - { + public void setReferenceLocation(LatLon referenceLocation) { + if (referenceLocation == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1023,17 +1037,17 @@ public void setReferenceLocation(LatLon referenceLocation) * * @return the reference position, or null if no reference position has been specified. */ - public Position getReferencePosition() - { - if (this.referencePosition != null) + public Position getReferencePosition() { + if (this.referencePosition != null) { return this.referencePosition; + } - if (this.boundaries.size() > 0 && this.outerBoundary().size() > 0) - { - if (this.outerBoundary().get(0) instanceof Position) + if (this.boundaries.size() > 0 && this.outerBoundary().size() > 0) { + if (this.outerBoundary().get(0) instanceof Position) { this.referencePosition = (Position) this.outerBoundary().get(0); - else + } else { this.referencePosition = new Position(this.outerBoundary().get(0), 0); + } } return this.referencePosition; @@ -1046,8 +1060,7 @@ public Position getReferencePosition() * * @see #setBaseDepth(double) */ - public double getBaseDepth() - { + public double getBaseDepth() { return baseDepth; } @@ -1058,11 +1071,9 @@ public double getBaseDepth() * position on the terrain. * * @param baseDepth the depth in meters to position the base vertices below the terrain. Specify positive values to - * position the base vertices below the terrain. (Negative values position the base vertices above - * the terrain.) + * position the base vertices below the terrain. (Negative values position the base vertices above the terrain.) */ - public void setBaseDepth(double baseDepth) - { + public void setBaseDepth(double baseDepth) { this.baseDepth = baseDepth; } @@ -1070,41 +1081,35 @@ public void setBaseDepth(double baseDepth) * Returns this extruded polygon's side images. * * @return a collection of lists each identifying the image sources for the associated outer or inner polygon - * boundary. + * boundary. */ - public List> getImageSources() - { - if (this.sideTextures == null) + public List> getImageSources() { + if (this.sideTextures == null) { return null; + } boolean hasTextures = false; - for (List textures : this.sideTextures) - { - if (textures != null && textures.size() > 0) - { + for (List textures : this.sideTextures) { + if (textures != null && textures.size() > 0) { hasTextures = true; break; } } - if (!hasTextures) + if (!hasTextures) { return null; + } List> imageSources = new ArrayList>(this.getBoundaries().size()); - for (List textures : this.sideTextures) - { - if (textures == null) - { + for (List textures : this.sideTextures) { + if (textures == null) { imageSources.add(null); - } - else - { + } else { ArrayList images = new ArrayList(textures.size()); imageSources.add(images); - for (WWTexture image : textures) - { + for (WWTexture image : textures) { images.add(image.getImageSource()); } } @@ -1118,37 +1123,35 @@ public List> getImageSources() * * @return true if side textures have been specified, otherwise false. */ - public boolean hasSideTextures() - { - if (this.sideTextures == null) + public boolean hasSideTextures() { + if (this.sideTextures == null) { return false; + } - for (List textures : this.sideTextures) - { - if (textures != null && textures.size() > 0) + for (List textures : this.sideTextures) { + if (textures != null && textures.size() > 0) { return true; + } } return false; } @Override - protected boolean mustApplyTexture(DrawContext dc) - { - if (this.getCapTexture() != null && this.capTextureCoords != null) + protected boolean mustApplyTexture(DrawContext dc) { + if (this.getCapTexture() != null && this.capTextureCoords != null) { return true; + } return this.mustApplySideTextures(); } @Override - protected boolean isTerrainDependent() - { + protected boolean isTerrainDependent() { return true; // this shape is terrain dependent regardless of the altitude mode } - protected boolean mustApplySideTextures() - { + protected boolean mustApplySideTextures() { return this.hasSideTextures(); } @@ -1157,8 +1160,7 @@ protected boolean mustApplySideTextures() * * @return true if an interior must be drawn, otherwise false. */ - protected boolean mustDrawInterior() - { + protected boolean mustDrawInterior() { return super.mustDrawInterior() || this.getActiveSideAttributes().isDrawInterior(); } @@ -1167,51 +1169,51 @@ protected boolean mustDrawInterior() * * @return true if the outline should be drawn, otherwise false. */ - protected boolean mustDrawOutline() - { + protected boolean mustDrawOutline() { return super.mustDrawOutline() || this.getActiveSideAttributes().isDrawOutline(); } - protected boolean mustRegenerateGeometry(DrawContext dc) - { + protected boolean mustRegenerateGeometry(DrawContext dc) { ShapeData shapeData = this.getCurrent(); - if (shapeData.capVertexBuffer == null || shapeData.sideVertexBuffer == null) + if (shapeData.capVertexBuffer == null || shapeData.sideVertexBuffer == null) { return true; + } - if (dc.getVerticalExaggeration() != shapeData.getVerticalExaggeration()) + if (dc.getVerticalExaggeration() != shapeData.getVerticalExaggeration()) { return true; + } if ((this.mustApplyLighting(dc, this.getActiveCapAttributes()) && shapeData.capNormalBuffer == null) - || (this.mustApplyLighting(dc, this.getActiveSideAttributes()) && shapeData.sideNormalBuffer == null)) + || (this.mustApplyLighting(dc, this.getActiveSideAttributes()) && shapeData.sideNormalBuffer == null)) { return true; + } return super.mustRegenerateGeometry(dc); } - public Extent getExtent(Globe globe, double verticalExaggeration) - { + public Extent getExtent(Globe globe, double verticalExaggeration) { // See if we've cached an extent associated with the globe. Extent extent = super.getExtent(globe, verticalExaggeration); - if (extent != null) + if (extent != null) { return extent; + } return super.computeExtentFromPositions(globe, verticalExaggeration, this.getOuterBoundary()); } /** - * Computes this shapes extent. If a reference point is specified, the extent is translated to that reference - * point. + * Computes this shapes extent. If a reference point is specified, the extent is translated to that reference point. * * @param outerBoundary the shape's outer boundary. - * @param refPoint a reference point to which the extent is translated. May be null. + * @param refPoint a reference point to which the extent is translated. May be null. * * @return the computed extent, or null if the extent cannot be computed. */ - protected Extent computeExtent(ExtrudedBoundaryInfo outerBoundary, Vec4 refPoint) - { - if (outerBoundary == null || outerBoundary.capVertices == null || outerBoundary.baseVertices == null) + protected Extent computeExtent(ExtrudedBoundaryInfo outerBoundary, Vec4 refPoint) { + if (outerBoundary == null || outerBoundary.capVertices == null || outerBoundary.baseVertices == null) { return null; + } Vec4[] topVertices = outerBoundary.capVertices; Vec4[] botVertices = outerBoundary.baseVertices; @@ -1227,98 +1229,91 @@ protected Extent computeExtent(ExtrudedBoundaryInfo outerBoundary, Vec4 refPoint return boundingBox != null ? boundingBox.translate(refPoint) : null; } - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // determine active cap attributes in super class - if (this.isHighlighted()) - { - if (this.getSideHighlightAttributes() != null) + if (this.isHighlighted()) { + if (this.getSideHighlightAttributes() != null) { this.activeSideAttributes.copy(this.getSideHighlightAttributes()); - else - { + } else { // If no highlight attributes have been specified we need to use the normal attributes but adjust them // to cause highlighting. - if (this.getSideAttributes() != null) + if (this.getSideAttributes() != null) { this.activeSideAttributes.copy(this.getSideAttributes()); - else + } else { this.activeSideAttributes.copy(defaultSideAttributes); + } this.activeSideAttributes.setOutlineMaterial(DEFAULT_HIGHLIGHT_MATERIAL); this.activeSideAttributes.setInteriorMaterial(DEFAULT_HIGHLIGHT_MATERIAL); } - } - else - { - if (this.getSideAttributes() != null) + } else { + if (this.getSideAttributes() != null) { this.activeSideAttributes.copy(this.getSideAttributes()); - else + } else { this.activeSideAttributes.copy(defaultSideAttributes); + } } } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { SurfacePolygon polygon = new SurfacePolygon(); this.setSurfacePolygonBoundaries(polygon); return polygon; } - protected void setSurfacePolygonBoundaries(SurfaceShape shape) - { + protected void setSurfacePolygonBoundaries(SurfaceShape shape) { SurfacePolygon polygon = (SurfacePolygon) shape; polygon.setLocations(this.getOuterBoundary()); List> bounds = this.getBoundaries(); - for (int i = 1; i < bounds.size(); i++) - { + for (int i = 1; i < bounds.size(); i++) { polygon.addInnerBoundary(bounds.get(i)); } } - public void render(DrawContext dc) - { - if (!this.isOuterBoundaryValid()) + public void render(DrawContext dc) { + if (!this.isOuterBoundaryValid()) { return; + } super.render(dc); } @Override - protected boolean isOrderedRenderableValid(DrawContext dc) - { + protected boolean isOrderedRenderableValid(DrawContext dc) { return this.getCurrent().capVertexBuffer != null || this.getCurrent().sideVertexBuffer != null; } @Override - protected boolean doMakeOrderedRenderable(DrawContext dc) - { - if (dc.getSurfaceGeometry() == null || !this.isOuterBoundaryValid()) + protected boolean doMakeOrderedRenderable(DrawContext dc) { + if (dc.getSurfaceGeometry() == null || !this.isOuterBoundaryValid()) { return false; + } this.createMinimalGeometry(dc, this.getCurrent()); // If the shape is less that a pixel in size, don't render it. - if (this.getExtent() == null || dc.isSmall(this.getExtent(), 1)) + if (this.getExtent() == null || dc.isSmall(this.getExtent(), 1)) { return false; + } - if (!this.intersectsFrustum(dc)) + if (!this.intersectsFrustum(dc)) { return false; + } this.createFullGeometry(dc, dc.getTerrain(), this.getCurrent(), true); return true; } - protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) - { + protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) { OGLStackHandler ogsh = super.beginDrawing(dc, attrMask); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Push an identity texture matrix. This prevents drawSides() from leaking GL texture matrix state. The // texture matrix stack is popped from OGLStackHandler.pop() within {@link #endRendering}. GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -1329,23 +1324,25 @@ protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) } @Override - public void drawOutline(DrawContext dc) - { - if (this.isEnableSides() && getActiveSideAttributes().isDrawOutline()) + public void drawOutline(DrawContext dc) { + if (this.isEnableSides() && getActiveSideAttributes().isDrawOutline()) { this.drawSideOutline(dc, this.getCurrent()); + } - if (this.isEnableCap() && getActiveCapAttributes().isDrawOutline()) + if (this.isEnableCap() && getActiveCapAttributes().isDrawOutline()) { this.drawCapOutline(dc, this.getCurrent()); + } } @Override - public void drawInterior(DrawContext dc) - { - if (this.isEnableSides() && getActiveSideAttributes().isDrawInterior()) + public void drawInterior(DrawContext dc) { + if (this.isEnableSides() && getActiveSideAttributes().isDrawInterior()) { this.drawSideInteriors(dc, this.getCurrent()); + } - if (this.isEnableCap() && getActiveCapAttributes().isDrawInterior()) + if (this.isEnableCap() && getActiveCapAttributes().isDrawInterior()) { this.drawCapInterior(dc, this.getCurrent()); + } } /** @@ -1354,8 +1351,7 @@ public void drawInterior(DrawContext dc) * @param dc not used. */ @Override - protected void doDrawOutline(DrawContext dc) - { + protected void doDrawOutline(DrawContext dc) { return; // this class overrides super.drawOutline so doesn't use this "do" method } @@ -1365,19 +1361,18 @@ protected void doDrawOutline(DrawContext dc) * This base implementation draws the outline of the basic polygon. Subclasses should override it to draw their * outline or an alternate outline of the basic polygon. * - * @param dc the draw context. + * @param dc the draw context. * @param shapeData the current shape data. */ - public void drawCapOutline(DrawContext dc, ShapeData shapeData) - { + public void drawCapOutline(DrawContext dc, ShapeData shapeData) { this.prepareToDrawOutline(dc, this.getActiveCapAttributes(), defaultAttributes); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - for (ExtrudedBoundaryInfo boundary : shapeData) - { - if (!dc.isPickingMode() && this.mustApplyLighting(dc, this.getActiveCapAttributes())) + for (ExtrudedBoundaryInfo boundary : shapeData) { + if (!dc.isPickingMode() && this.mustApplyLighting(dc, this.getActiveCapAttributes())) { gl.glNormalPointer(GL.GL_FLOAT, 0, boundary.capNormalBuffer.rewind()); + } IntBuffer indices = boundary.capEdgeIndices; gl.glVertexPointer(3, GL.GL_FLOAT, 0, boundary.capVertexBuffer.rewind()); @@ -1392,26 +1387,24 @@ public void drawCapOutline(DrawContext dc, ShapeData shapeData) /** * Draws this extruded polygon's side outline. * - * @param dc the draw context. + * @param dc the draw context. * @param shapeData the current shape data. */ - protected void drawSideOutline(DrawContext dc, ShapeData shapeData) - { + protected void drawSideOutline(DrawContext dc, ShapeData shapeData) { this.prepareToDrawOutline(dc, this.getActiveSideAttributes(), defaultSideAttributes); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - for (ExtrudedBoundaryInfo boundary : shapeData) - { - if (!dc.isPickingMode() && this.mustApplyLighting(dc, this.getActiveSideAttributes())) + for (ExtrudedBoundaryInfo boundary : shapeData) { + if (!dc.isPickingMode() && this.mustApplyLighting(dc, this.getActiveSideAttributes())) { gl.glNormalPointer(GL.GL_FLOAT, 0, boundary.sideNormalBuffer.rewind()); + } IntBuffer indices = boundary.sideEdgeIndices; indices.rewind(); // Don't draw the top outline if the cap will draw it. - if (this.isEnableCap() && this.getActiveCapAttributes().isDrawOutline()) - { + if (this.isEnableCap() && this.getActiveCapAttributes().isDrawOutline()) { indices = indices.slice(); indices.position(2 * boundary.faceCount); } @@ -1427,46 +1420,41 @@ protected void drawSideOutline(DrawContext dc, ShapeData shapeData) * @param dc not used. */ @Override - protected void doDrawInterior(DrawContext dc) - { + protected void doDrawInterior(DrawContext dc) { return; } /** * Draws the filled interior of this shape's cap. * - * @param dc the draw context. + * @param dc the draw context. * @param shapeData this shape's current globe-specific data. */ - public void drawCapInterior(DrawContext dc, ShapeData shapeData) - { + public void drawCapInterior(DrawContext dc, ShapeData shapeData) { super.prepareToDrawInterior(dc, this.getActiveCapAttributes(), defaultAttributes); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!dc.isPickingMode() && this.mustApplyLighting(dc, this.getActiveCapAttributes())) + if (!dc.isPickingMode() && this.mustApplyLighting(dc, this.getActiveCapAttributes())) { gl.glNormalPointer(GL.GL_FLOAT, 0, shapeData.capNormalBuffer.rewind()); + } WWTexture texture = this.getCapTexture(); - if (!dc.isPickingMode() && texture != null && this.capTextureCoords != null) - { + if (!dc.isPickingMode() && texture != null && this.capTextureCoords != null) { texture.bind(dc); texture.applyInternalTransform(dc); gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, this.capTextureCoords.rewind()); dc.getGL().glEnable(GL.GL_TEXTURE_2D); gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); - } - else - { + } else { dc.getGL().glDisable(GL.GL_TEXTURE_2D); gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY); } gl.glVertexPointer(3, GL.GL_FLOAT, 0, shapeData.capVertexBuffer.rewind()); - for (int i = 0; i < shapeData.cb.getPrimTypes().size(); i++) - { + for (int i = 0; i < shapeData.cb.getPrimTypes().size(); i++) { IntBuffer ib = shapeData.capFillIndexBuffers.get(i); gl.glDrawElements(shapeData.cb.getPrimTypes().get(i), ib.limit(), GL.GL_UNSIGNED_INT, ib.rewind()); } @@ -1475,28 +1463,24 @@ public void drawCapInterior(DrawContext dc, ShapeData shapeData) /** * Draws this shape's sides. * - * @param dc the draw context. + * @param dc the draw context. * @param shapeData this shape's current globe-specific data. */ - protected void drawSideInteriors(DrawContext dc, ShapeData shapeData) - { + protected void drawSideInteriors(DrawContext dc, ShapeData shapeData) { super.prepareToDrawInterior(dc, this.getActiveSideAttributes(), defaultSideAttributes); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - for (ExtrudedBoundaryInfo boundary : shapeData) - { - if (!dc.isPickingMode() && this.mustApplyLighting(dc, this.getActiveSideAttributes())) + for (ExtrudedBoundaryInfo boundary : shapeData) { + if (!dc.isPickingMode() && this.mustApplyLighting(dc, this.getActiveSideAttributes())) { gl.glNormalPointer(GL.GL_FLOAT, 0, boundary.sideNormalBuffer.rewind()); + } - if (!dc.isPickingMode() && boundary.sideTextureCoords != null) - { + if (!dc.isPickingMode() && boundary.sideTextureCoords != null) { gl.glEnable(GL.GL_TEXTURE_2D); gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, boundary.sideTextureCoords.rewind()); - } - else - { + } else { gl.glDisable(GL.GL_TEXTURE_2D); gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY); } @@ -1504,12 +1488,11 @@ protected void drawSideInteriors(DrawContext dc, ShapeData shapeData) gl.glVertexPointer(3, GL.GL_FLOAT, 0, boundary.sideVertexBuffer.rewind()); boundary.sideIndices.rewind(); - for (int j = 0; j < boundary.faceCount; j++) - { - if (!dc.isPickingMode() && boundary.sideTextureCoords != null) - { - if (!boundary.sideTextures.get(j).bind(dc)) + for (int j = 0; j < boundary.faceCount; j++) { + if (!dc.isPickingMode() && boundary.sideTextureCoords != null) { + if (!boundary.sideTextures.get(j).bind(dc)) { continue; + } boundary.sideTextures.get(j).applyInternalTransform(dc); } @@ -1524,19 +1507,20 @@ protected void drawSideInteriors(DrawContext dc, ShapeData shapeData) /** * Computes the information necessary to determine this extruded polygon's extent. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shapeData this shape's current globe-specific data. */ - protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) - { + protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) { this.computeReferencePoint(dc.getTerrain(), shapeData); - if (shapeData.getReferencePoint() == null) + if (shapeData.getReferencePoint() == null) { return; + } this.computeBoundaryVertices(dc.getTerrain(), shapeData.getOuterBoundaryInfo(), shapeData.getReferencePoint()); - if (this.getExtent() == null || this.getAltitudeMode() != WorldWind.ABSOLUTE) + if (this.getExtent() == null || this.getAltitudeMode() != WorldWind.ABSOLUTE) { shapeData.setExtent(this.computeExtent(shapeData.getOuterBoundaryInfo(), shapeData.getReferencePoint())); + } shapeData.setEyeDistance(this.computeEyeDistance(dc, shapeData)); shapeData.setGlobeStateKey(dc.getGlobe().getGlobeStateKey(dc)); @@ -1546,21 +1530,20 @@ protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) /** * Computes the minimum distance between this shape and the eye point. * - * @param dc the draw context. + * @param dc the draw context. * @param shapeData this shape's current globe-specific data. * * @return the minimum distance from the shape to the eye point. */ - protected double computeEyeDistance(DrawContext dc, ShapeData shapeData) - { + protected double computeEyeDistance(DrawContext dc, ShapeData shapeData) { double minDistance = Double.MAX_VALUE; Vec4 eyePoint = dc.getView().getEyePoint(); - for (Vec4 point : shapeData.getOuterBoundaryInfo().capVertices) - { + for (Vec4 point : shapeData.getOuterBoundaryInfo().capVertices) { double d = point.add3(shapeData.getReferencePoint()).distanceTo3(eyePoint); - if (d < minDistance) + if (d < minDistance) { minDistance = d; + } } return minDistance; @@ -1569,15 +1552,15 @@ protected double computeEyeDistance(DrawContext dc, ShapeData shapeData) /** * Computes and sets this shape's reference point, the Cartesian position corresponding to its geographic location. * - * @param terrain the terrain to use when computing the reference point. The reference point is always on the - * terrain. + * @param terrain the terrain to use when computing the reference point. The reference point is always on the + * terrain. * @param shapeData the current shape data. */ - protected void computeReferencePoint(Terrain terrain, ShapeData shapeData) - { + protected void computeReferencePoint(Terrain terrain, ShapeData shapeData) { LatLon refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return; + } shapeData.setReferencePoint(terrain.getSurfacePoint(refPos.getLatitude(), refPos.getLongitude(), 0)); } @@ -1585,77 +1568,77 @@ protected void computeReferencePoint(Terrain terrain, ShapeData shapeData) /** * Computes a boundary set's full geometry. * - * @param dc the current draw context. - * @param terrain the terrain to use when computing the geometry. - * @param shapeData the boundary set to compute the geometry for. + * @param dc the current draw context. + * @param terrain the terrain to use when computing the geometry. + * @param shapeData the boundary set to compute the geometry for. * @param skipOuterBoundary true if outer boundaries vertices do not need to be calculated, otherwise false. */ protected void createFullGeometry(DrawContext dc, Terrain terrain, ShapeData shapeData, - boolean skipOuterBoundary) - { - for (ExtrudedBoundaryInfo boundary : shapeData) - { + boolean skipOuterBoundary) { + for (ExtrudedBoundaryInfo boundary : shapeData) { boundary.capEdgeIndices = this.getCapEdgeIndices(boundary.locations.size()); boundary.sideIndices = this.getSideIndices(boundary.locations.size()); boundary.sideEdgeIndices = this.getSideEdgeIndices(boundary.locations.size()); } - if (this.isEnableSides() || this.isEnableCap()) + if (this.isEnableSides() || this.isEnableCap()) { this.createVertices(terrain, shapeData, skipOuterBoundary); + } - if (this.isEnableSides()) - { + if (this.isEnableSides()) { this.createSideGeometry(shapeData); - if (this.mustApplyLighting(dc, this.getActiveSideAttributes())) + if (this.mustApplyLighting(dc, this.getActiveSideAttributes())) { this.createSideNormals(shapeData); + } - if (!dc.isPickingMode() && this.mustApplySideTextures()) + if (!dc.isPickingMode() && this.mustApplySideTextures()) { this.createSideTextureCoords(shapeData); + } } - if (this.isEnableCap()) - { + if (this.isEnableCap()) { this.createCapGeometry(dc, shapeData); - if (this.mustApplyLighting(dc, this.getActiveCapAttributes())) + if (this.mustApplyLighting(dc, this.getActiveCapAttributes())) { this.createCapNormals(shapeData); + } } } /** * Creates this shape's Cartesian vertices. * - * @param terrain the terrain to use when computing the vertices. - * @param shapeData the current shape data. + * @param terrain the terrain to use when computing the vertices. + * @param shapeData the current shape data. * @param skipOuterBoundary if true, do not compute the outer boundary's vertices because they have already been - * computed. + * computed. */ - protected void createVertices(Terrain terrain, ShapeData shapeData, boolean skipOuterBoundary) - { - for (ExtrudedBoundaryInfo boundary : shapeData) - { - if (boundary != shapeData.getOuterBoundaryInfo() || !skipOuterBoundary) + protected void createVertices(Terrain terrain, ShapeData shapeData, boolean skipOuterBoundary) { + for (ExtrudedBoundaryInfo boundary : shapeData) { + if (boundary != shapeData.getOuterBoundaryInfo() || !skipOuterBoundary) { this.computeBoundaryVertices(terrain, boundary, shapeData.getReferencePoint()); + } } } /** * Compute and set the Cartesian vertices for one specified boundary of this shape. * - * @param terrain the terrain to use when computing the vertices. + * @param terrain the terrain to use when computing the vertices. * @param boundary the boundary for which to compute the vertices. * @param refPoint the reference point specifying the coordinate origin of the vertices. */ - protected void computeBoundaryVertices(Terrain terrain, ExtrudedBoundaryInfo boundary, Vec4 refPoint) - { + protected void computeBoundaryVertices(Terrain terrain, ExtrudedBoundaryInfo boundary, Vec4 refPoint) { Vec4[] topVertices = boundary.capVertices; - if (topVertices == null || topVertices.length < boundary.locations.size()) + if (topVertices == null || topVertices.length < boundary.locations.size()) { topVertices = new Vec4[boundary.locations.size()]; + } Vec4[] bottomVertices = boundary.baseVertices; - if (bottomVertices == null || bottomVertices.length < boundary.locations.size()) + if (bottomVertices == null || bottomVertices.length < boundary.locations.size()) { bottomVertices = new Vec4[boundary.locations.size()]; + } // These variables are used to compute the independent length of each cap vertex for CONSTANT altitude mode. Vec4 N = null; @@ -1664,8 +1647,7 @@ protected void computeBoundaryVertices(Terrain terrain, ExtrudedBoundaryInfo bou double vaLength = 0; boundary.faceCount = boundary.locations.size() - 1; - for (int i = 0; i < boundary.faceCount; i++) - { + for (int i = 0; i < boundary.faceCount; i++) { // The order for both top and bottom is CCW as one looks down from space onto the base polygon. For a // 4-sided polygon (defined by 5 lat/lon locations) the vertex order is 0-1-2-3-4. @@ -1674,29 +1656,24 @@ protected void computeBoundaryVertices(Terrain terrain, ExtrudedBoundaryInfo bou // Compute the bottom point, which is on the terrain. Vec4 vert = terrain.getSurfacePoint(location.getLatitude(), location.getLongitude(), 0); - if (this.getBaseDepth() == 0) - { + if (this.getBaseDepth() == 0) { // Place the base vertex on the terrain. bottomVertices[i] = vert.subtract3(refPoint); - } - else - { + } else { // Place the base vertex below the terrain (if base depth is positive). double length = vert.getLength3(); bottomVertices[i] = vert.multiply3((length - this.getBaseDepth()) / length).subtract3(refPoint); } // Compute the top/cap point. - if (this.getAltitudeMode() == WorldWind.CONSTANT || !(location instanceof Position)) - { + if (this.getAltitudeMode() == WorldWind.CONSTANT || !(location instanceof Position)) { // The shape's base is on the terrain, and all the cap vertices are at a common altitude // relative to the reference position. This means that the distance between the cap and base vertices // at the boundary locations varies. Further, the vector between the base vertex and cap vertex at each // boundary location is parallel to that at the reference position. The calculation below first // determines that reference-position vector, then applies scaled versions of it to determine the cap // vertex at all the other boundary positions. - if (vaa == null) - { + if (vaa == null) { Position refPos = this.getReferencePosition(); N = terrain.getGlobe().computeSurfaceNormalAtLocation(refPos.getLatitude(), refPos.getLongitude()); vaa = N.multiply3(this.getHeight()); @@ -1706,16 +1683,13 @@ protected void computeBoundaryVertices(Terrain terrain, ExtrudedBoundaryInfo bou double delta = vert.dot3(N) - vaLength; vert = vert.add3(vaa.multiply3(1d - delta / vaaLength)); - } - else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) - { + } else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { vert = terrain.getSurfacePoint(location.getLatitude(), location.getLongitude(), - ((Position) location).getAltitude()); - } - else // WorldWind.ABSOLUTE + ((Position) location).getAltitude()); + } else // WorldWind.ABSOLUTE { vert = terrain.getGlobe().computePointFromPosition(location.getLatitude(), location.getLongitude(), - ((Position) location).getAltitude() * terrain.getVerticalExaggeration()); + ((Position) location).getAltitude() * terrain.getVerticalExaggeration()); } topVertices[i] = vert.subtract3(refPoint); @@ -1733,42 +1707,40 @@ else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) * * @param shapeData the current shape data. */ - protected void createSideGeometry(ShapeData shapeData) - { + protected void createSideGeometry(ShapeData shapeData) { // The side vertex buffer requires 4 vertices of x,y,z for each polygon face. int vertexCoordCount = this.totalFaceCount * 4 * 3; // 4 vertices of x,y,z per face - if (shapeData.sideVertexBuffer != null && shapeData.sideVertexBuffer.capacity() >= vertexCoordCount) + if (shapeData.sideVertexBuffer != null && shapeData.sideVertexBuffer.capacity() >= vertexCoordCount) { shapeData.sideVertexBuffer.clear(); - else + } else { shapeData.sideVertexBuffer = Buffers.newDirectFloatBuffer(vertexCoordCount); + } // Create individual buffer slices for each boundary. - for (ExtrudedBoundaryInfo boundary : shapeData) - { + for (ExtrudedBoundaryInfo boundary : shapeData) { boundary.sideVertexBuffer = this.fillSideVertexBuffer(boundary.capVertices, boundary.baseVertices, - shapeData.sideVertexBuffer.slice()); + shapeData.sideVertexBuffer.slice()); shapeData.sideVertexBuffer.position( - shapeData.sideVertexBuffer.position() + boundary.sideVertexBuffer.limit()); + shapeData.sideVertexBuffer.position() + boundary.sideVertexBuffer.limit()); } } - protected void createSideNormals(ShapeData shapeData) - { + protected void createSideNormals(ShapeData shapeData) { int vertexCoordCount = this.totalFaceCount * 4 * 3; // 4 vertices of x,y,z per face - if (shapeData.sideNormalBuffer != null && shapeData.sideNormalBuffer.capacity() >= vertexCoordCount) + if (shapeData.sideNormalBuffer != null && shapeData.sideNormalBuffer.capacity() >= vertexCoordCount) { shapeData.sideNormalBuffer.clear(); - else + } else { shapeData.sideNormalBuffer = Buffers.newDirectFloatBuffer(vertexCoordCount); + } // Create individual buffer slices for each boundary. - for (ExtrudedBoundaryInfo boundary : shapeData) - { + for (ExtrudedBoundaryInfo boundary : shapeData) { boundary.sideNormalBuffer = this.fillSideNormalBuffer(boundary.capVertices, boundary.baseVertices, - shapeData.sideNormalBuffer.slice()); + shapeData.sideNormalBuffer.slice()); shapeData.sideNormalBuffer.position( - shapeData.sideNormalBuffer.position() + boundary.sideNormalBuffer.limit()); + shapeData.sideNormalBuffer.position() + boundary.sideNormalBuffer.limit()); } } @@ -1777,24 +1749,22 @@ protected void createSideNormals(ShapeData shapeData) * * @param shapeData the current shape data. */ - protected void createSideTextureCoords(ShapeData shapeData) - { + protected void createSideTextureCoords(ShapeData shapeData) { // Create individual buffer slices for each boundary. - for (ExtrudedBoundaryInfo boundary : shapeData) - { + for (ExtrudedBoundaryInfo boundary : shapeData) { boolean applyTextureToThisBoundary = this.hasSideTextures() - && boundary.sideTextures != null && boundary.sideTextures.size() == boundary.faceCount; + && boundary.sideTextures != null && boundary.sideTextures.size() == boundary.faceCount; - if (applyTextureToThisBoundary) - { + if (applyTextureToThisBoundary) { int texCoordSize = boundary.faceCount * 4 * 2; // n sides of 4 verts w/s,t - if (boundary.sideTextureCoords != null && boundary.sideTextureCoords.capacity() >= texCoordSize) + if (boundary.sideTextureCoords != null && boundary.sideTextureCoords.capacity() >= texCoordSize) { boundary.sideTextureCoords.clear(); - else + } else { boundary.sideTextureCoords = Buffers.newDirectFloatBuffer(texCoordSize); + } this.fillSideTexCoordBuffer(boundary.capVertices, boundary.baseVertices, - boundary.sideTextureCoords); + boundary.sideTextureCoords); } } } @@ -1802,47 +1772,47 @@ protected void createSideTextureCoords(ShapeData shapeData) /** * Compute the cap geometry. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shapeData boundary vertices are calculated during {@link #createMinimalGeometry(DrawContext, * gov.nasa.worldwind.render.ExtrudedPolygon.ShapeData)}). */ - protected void createCapGeometry(DrawContext dc, ShapeData shapeData) - { + protected void createCapGeometry(DrawContext dc, ShapeData shapeData) { if (shapeData.capVertexBuffer != null - && shapeData.capVertexBuffer.capacity() >= this.totalNumLocations * 3) + && shapeData.capVertexBuffer.capacity() >= this.totalNumLocations * 3) { shapeData.capVertexBuffer.clear(); - else + } else { shapeData.capVertexBuffer = Buffers.newDirectFloatBuffer(this.totalNumLocations * 3); + } // Fill the vertex buffer. Simultaneously create individual buffer slices for each boundary. These are used to // draw the outline. - for (ExtrudedBoundaryInfo boundary : shapeData) - { + for (ExtrudedBoundaryInfo boundary : shapeData) { boundary.capVertexBuffer = WWBufferUtil.copyArrayToBuffer(boundary.capVertices, - shapeData.capVertexBuffer.slice()); + shapeData.capVertexBuffer.slice()); shapeData.capVertexBuffer.position( - shapeData.capVertexBuffer.position() + boundary.capVertexBuffer.limit()); + shapeData.capVertexBuffer.position() + boundary.capVertexBuffer.limit()); } if (shapeData.cb == null) // need to tessellate only once + { this.createTessllationGeometry(dc, shapeData); + } this.generateCapInteriorIndices(shapeData); } - protected void createCapNormals(ShapeData shapeData) - { + protected void createCapNormals(ShapeData shapeData) { if (shapeData.capNormalBuffer != null - && shapeData.capNormalBuffer.capacity() >= this.totalNumLocations * 3) + && shapeData.capNormalBuffer.capacity() >= this.totalNumLocations * 3) { shapeData.capNormalBuffer.clear(); - else + } else { shapeData.capNormalBuffer = Buffers.newDirectFloatBuffer(shapeData.capVertexBuffer.capacity()); + } - for (ExtrudedBoundaryInfo boundary : shapeData) - { + for (ExtrudedBoundaryInfo boundary : shapeData) { boundary.capNormalBuffer = this.computeCapNormals(boundary, shapeData.capNormalBuffer.slice()); shapeData.capNormalBuffer.position( - shapeData.capNormalBuffer.position() + boundary.capNormalBuffer.limit()); + shapeData.capNormalBuffer.position() + boundary.capNormalBuffer.limit()); } } @@ -1850,29 +1820,27 @@ protected void createCapNormals(ShapeData shapeData) * Compute normal vectors for an extruded polygon's cap vertices. * * @param boundary the boundary to compute normals for. - * @param nBuf the buffer in which to place the computed normals. Must have enough remaining space to hold the - * normals. + * @param nBuf the buffer in which to place the computed normals. Must have enough remaining space to hold the + * normals. * * @return the buffer specified as input, with its limit incremented by the number of vertices copied, and its - * position set to 0. + * position set to 0. */ - protected FloatBuffer computeCapNormals(ExtrudedBoundaryInfo boundary, FloatBuffer nBuf) - { + protected FloatBuffer computeCapNormals(ExtrudedBoundaryInfo boundary, FloatBuffer nBuf) { int nVerts = boundary.locations.size(); Vec4[] verts = boundary.capVertices; double avgX, avgY, avgZ; // Compute normal for first point of boundary. - Vec4 va = verts[1].subtract3(verts[0]); + Vec4 va = verts[1].subtract3(verts[0]); Vec4 vb = verts[nVerts - 2].subtract3(verts[0]); // nverts - 2 because last and first are same avgX = (va.y * vb.z) - (va.z * vb.y); avgY = (va.z * vb.x) - (va.x * vb.z); avgZ = (va.x * vb.y) - (va.y * vb.x); // Compute normals for interior boundary points. - for (int i = 1; i < nVerts - 1; i++) - { - va = verts[i + 1].subtract3(verts[i]); + for (int i = 1; i < nVerts - 1; i++) { + va = verts[i + 1].subtract3(verts[i]); vb = verts[i - 1].subtract3(verts[i]); avgX += (va.y * vb.z) - (va.z * vb.y); avgY += (va.z * vb.x) - (va.x * vb.z); @@ -1884,8 +1852,7 @@ protected FloatBuffer computeCapNormals(ExtrudedBoundaryInfo boundary, FloatBuff avgZ /= nVerts - 1; double length = Math.sqrt(avgX * avgX + avgY * avgY + avgZ * avgZ); - for (int i = 0; i < nVerts; i++) - { + for (int i = 0; i < nVerts; i++) { nBuf.put((float) (avgX / length)).put((float) (avgY / length)).put((float) (avgZ / length)); } @@ -1894,8 +1861,7 @@ protected FloatBuffer computeCapNormals(ExtrudedBoundaryInfo boundary, FloatBuff return nBuf; } - protected FloatBuffer fillSideVertexBuffer(Vec4[] topVerts, Vec4[] bottomVerts, FloatBuffer vBuf) - { + protected FloatBuffer fillSideVertexBuffer(Vec4[] topVerts, Vec4[] bottomVerts, FloatBuffer vBuf) { // Forms the polygon's faces from its vertices, simultaneously copying the Cartesian coordinates from a Vec4 // array to a FloatBuffer. @@ -1906,8 +1872,7 @@ protected FloatBuffer fillSideVertexBuffer(Vec4[] topVerts, Vec4[] bottomVerts, // Fill the vertex buffer with coordinates for each independent face -- 4 vertices per face. Vertices need to be // independent in order to have different texture coordinates and normals per face. // For an n-sided polygon the vertex order is b0-b1-t1-t0, b1-b2-t2-t1, ... Note the counter-clockwise ordering. - for (int i = 0; i < faceCount; i++) - { + for (int i = 0; i < faceCount; i++) { int v = i; vBuf.put((float) bottomVerts[v].x).put((float) bottomVerts[v].y).put((float) bottomVerts[v].z); v = i + 1; @@ -1923,17 +1888,15 @@ protected FloatBuffer fillSideVertexBuffer(Vec4[] topVerts, Vec4[] bottomVerts, return vBuf; } - protected FloatBuffer fillSideNormalBuffer(Vec4[] topVerts, Vec4[] bottomVerts, FloatBuffer nBuf) - { + protected FloatBuffer fillSideNormalBuffer(Vec4[] topVerts, Vec4[] bottomVerts, FloatBuffer nBuf) { // This method parallels fillVertexBuffer. The normals are stored in exactly the same order. int faceCount = topVerts.length - 1; int size = faceCount * 4 * 3; // n sides of 4 verts of x,y,z nBuf.limit(size); - for (int i = 0; i < faceCount; i++) - { - Vec4 va = topVerts[i + 1].subtract3(bottomVerts[i]); + for (int i = 0; i < faceCount; i++) { + Vec4 va = topVerts[i + 1].subtract3(bottomVerts[i]); Vec4 vb = topVerts[i].subtract3(bottomVerts[i + 1]); Vec4 normal = va.cross3(vb).normalize3(); @@ -1951,18 +1914,16 @@ protected FloatBuffer fillSideNormalBuffer(Vec4[] topVerts, Vec4[] bottomVerts, /** * Computes the texture coordinates for a boundary of this shape. * - * @param topVerts the boundary's top Cartesian coordinates. + * @param topVerts the boundary's top Cartesian coordinates. * @param bottomVerts the boundary's bottom Cartesian coordinates. - * @param tBuf the buffer in which to place the computed texture coordinates. + * @param tBuf the buffer in which to place the computed texture coordinates. */ - protected void fillSideTexCoordBuffer(Vec4[] topVerts, Vec4[] bottomVerts, FloatBuffer tBuf) - { + protected void fillSideTexCoordBuffer(Vec4[] topVerts, Vec4[] bottomVerts, FloatBuffer tBuf) { int faceCount = topVerts.length - 1; double lengths[] = new double[faceCount + 1]; // Find the top-to-bottom lengths of the corners in order to determine their relative lengths. - for (int i = 0; i < faceCount; i++) - { + for (int i = 0; i < faceCount; i++) { lengths[i] = bottomVerts[i].distanceTo3(topVerts[i]); } lengths[faceCount] = lengths[0]; // duplicate the first length to ease iteration below @@ -1970,16 +1931,12 @@ protected void fillSideTexCoordBuffer(Vec4[] topVerts, Vec4[] bottomVerts, Float // Fill the vertex buffer with texture coordinates for each independent face in the same order as the vertices // in the vertex buffer. int b = 0; - for (int i = 0; i < faceCount; i++) - { + for (int i = 0; i < faceCount; i++) { // Set the base texture coord to 0 for the longer side and a proportional value for the shorter side. - if (lengths[i] > lengths[i + 1]) - { + if (lengths[i] > lengths[i + 1]) { tBuf.put(b++, 0).put(b++, 0); tBuf.put(b++, 1).put(b++, (float) (1d - lengths[i + 1] / lengths[i])); - } - else - { + } else { tBuf.put(b++, 0).put(b++, (float) (1d - lengths[i] / lengths[i + 1])); tBuf.put(b++, 1).put(b++, 0); } @@ -1995,16 +1952,15 @@ protected void fillSideTexCoordBuffer(Vec4[] topVerts, Vec4[] bottomVerts, Float * * @return a buffer of indices that can be passed to OpenGL to draw all the shape's edges. */ - protected IntBuffer getCapEdgeIndices(int n) - { + protected IntBuffer getCapEdgeIndices(int n) { IntBuffer ib = capEdgeIndexBuffers.get(n); - if (ib != null) + if (ib != null) { return ib; + } // The edges are two-point lines connecting vertex pairs. ib = Buffers.newDirectIntBuffer(2 * (n - 1) * 3); - for (int i = 0; i < n - 1; i++) - { + for (int i = 0; i < n - 1; i++) { ib.put(i).put(i + 1); } @@ -2020,18 +1976,17 @@ protected IntBuffer getCapEdgeIndices(int n) * * @return a buffer of indices that can be passed to OpenGL to draw all face of the shape. */ - protected IntBuffer getSideIndices(int n) - { + protected IntBuffer getSideIndices(int n) { IntBuffer ib = sideFillIndexBuffers.get(n); - if (ib != null) + if (ib != null) { return ib; + } // Compute them if not already computed. Each side is two triangles defined by one triangle strip. All edges // can't be combined into one tri-strip because each side may have its own texture and therefore different // texture coordinates. ib = Buffers.newDirectIntBuffer(n * 4); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { ib.put(4 * i + 3).put(4 * i).put(4 * i + 2).put(4 * i + 1); } @@ -2047,33 +2002,29 @@ protected IntBuffer getSideIndices(int n) * * @return a buffer of indices that can be passed to OpenGL to draw all the boundary's edges. */ - protected IntBuffer getSideEdgeIndices(int n) - { + protected IntBuffer getSideEdgeIndices(int n) { IntBuffer ib = sideEdgeIndexBuffers.get(n); - if (ib != null) + if (ib != null) { return ib; + } int nn = n - 1; // the boundary is closed so don't add an edge for the redundant position. // The edges are two-point lines connecting vertex pairs. - ib = Buffers.newDirectIntBuffer((2 * nn) * 3); // 2n each for top, bottom and corners // Top. Keep this first so that the top edge can be turned off independently. - for (int i = 0; i < nn; i++) - { + for (int i = 0; i < nn; i++) { ib.put(4 * i + 2).put(4 * i + 3); } // Bottom - for (int i = 0; i < nn; i++) - { + for (int i = 0; i < nn; i++) { ib.put(4 * i).put(4 * i + 1); } // Corners - for (int i = 0; i < nn; i++) - { + for (int i = 0; i < nn; i++) { ib.put(4 * i).put(4 * i + 3); } @@ -2083,8 +2034,7 @@ protected IntBuffer getSideEdgeIndices(int n) } @Override - protected void fillVBO(DrawContext dc) - { + protected void fillVBO(DrawContext dc) { // VBOs are not used by this shape type } @@ -2093,21 +2043,18 @@ protected void fillVBO(DrawContext dc) * context is not null passes the exception to the rendering exception listener (see {@link * WorldWindow#addRenderingExceptionListener(gov.nasa.worldwind.event.RenderingExceptionListener)}). * - * @param dc the draw context. + * @param dc the draw context. * @param shapeData the boundary set to tessellate */ - protected void createTessllationGeometry(DrawContext dc, ShapeData shapeData) - { + protected void createTessllationGeometry(DrawContext dc, ShapeData shapeData) { // Wrap polygon tessellation in a try/catch block. We do this to catch and handle OutOfMemoryErrors caused during // tessellation of the polygon vertices. - try - { + try { Vec4 normal = this.computePolygonNormal(shapeData); // There's a fallback for non-computable normal in computePolygonNormal, but test here in case the fallback // doesn't work either. - if (normal == null) - { + if (normal == null) { String message = Logging.getMessage("Geom.ShapeNormalVectorNotComputable", this); Logging.logger().log(java.util.logging.Level.SEVERE, message); shapeData.tessellationError = true; @@ -2115,35 +2062,31 @@ protected void createTessllationGeometry(DrawContext dc, ShapeData shapeData) } this.tessellatePolygon(shapeData, normal.normalize3()); - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { String message = Logging.getMessage("generic.ExceptionWhileTessellating", this); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); shapeData.tessellationError = true; - if (dc != null) - { + if (dc != null) { //noinspection ThrowableInstanceNeverThrown dc.addRenderingException(new WWRuntimeException(message, e)); } } } - protected Vec4 computePolygonNormal(ShapeData shapeData) - { + protected Vec4 computePolygonNormal(ShapeData shapeData) { Vec4 normal = WWMath.computeBufferNormal(shapeData.capVertexBuffer, 0); // The normal vector is null if this is a degenerate polygon representing a line or a single point. We fall // back to using the globe's surface normal at the reference point. This allows the tessellator to process // the degenerate polygon without generating an exception. - if (normal == null) - { + if (normal == null) { Globe globe = shapeData.getGlobeStateKey().getGlobe(); - if (globe != null) + if (globe != null) { normal = globe.computeSurfaceNormalAtLocation( - this.getReferencePosition().getLatitude(), this.getReferencePosition().getLongitude()); + this.getReferencePosition().getLatitude(), this.getReferencePosition().getLongitude()); + } } return normal; @@ -2153,28 +2096,24 @@ protected Vec4 computePolygonNormal(ShapeData shapeData) * Tessellates the polygon from its vertices. * * @param shapeData the polygon boundaries. - * @param normal a unit normal vector for the plane containing the polygon vertices. Even though the the vertices - * might not be coplanar, only one representative normal is used for tessellation. + * @param normal a unit normal vector for the plane containing the polygon vertices. Even though the the vertices + * might not be coplanar, only one representative normal is used for tessellation. */ - protected void tessellatePolygon(ShapeData shapeData, Vec4 normal) - { + protected void tessellatePolygon(ShapeData shapeData, Vec4 normal) { GLUTessellatorSupport glts = new GLUTessellatorSupport(); shapeData.cb = new GLUTessellatorSupport.CollectIndexListsCallback(); glts.beginTessellation(shapeData.cb, normal); - try - { + try { double[] coords = new double[3]; GLU.gluTessBeginPolygon(glts.getGLUtessellator(), null); int k = 0; - for (ExtrudedBoundaryInfo boundary : shapeData) - { + for (ExtrudedBoundaryInfo boundary : shapeData) { GLU.gluTessBeginContour(glts.getGLUtessellator()); FloatBuffer vBuf = boundary.capVertexBuffer; - for (int i = 0; i < boundary.locations.size(); i++) - { + for (int i = 0; i < boundary.locations.size(); i++) { coords[0] = vBuf.get(i * 3); coords[1] = vBuf.get(i * 3 + 1); coords[2] = vBuf.get(i * 3 + 2); @@ -2185,9 +2124,7 @@ protected void tessellatePolygon(ShapeData shapeData, Vec4 normal) } GLU.gluTessEndPolygon(glts.getGLUtessellator()); - } - finally - { + } finally { // Free any heap memory used for tessellation immediately. If tessellation has consumed all available // heap memory, we must free memory used by tessellation immediately or subsequent operations such as // message logging will fail. @@ -2200,25 +2137,24 @@ protected void tessellatePolygon(ShapeData shapeData, Vec4 normal) * * @param shapeData the current shape data. */ - protected void generateCapInteriorIndices(ShapeData shapeData) - { + protected void generateCapInteriorIndices(ShapeData shapeData) { GLUTessellatorSupport.CollectIndexListsCallback cb = shapeData.cb; - if (shapeData.capFillIndices == null || shapeData.capFillIndices.capacity() < cb.getNumIndices()) + if (shapeData.capFillIndices == null || shapeData.capFillIndices.capacity() < cb.getNumIndices()) { shapeData.capFillIndices = Buffers.newDirectIntBuffer(cb.getNumIndices()); - else + } else { shapeData.capFillIndices.clear(); + } - if (shapeData.capFillIndexBuffers == null || shapeData.capFillIndexBuffers.size() < cb.getPrimTypes().size()) + if (shapeData.capFillIndexBuffers == null || shapeData.capFillIndexBuffers.size() < cb.getPrimTypes().size()) { shapeData.capFillIndexBuffers = new ArrayList(cb.getPrimTypes().size()); - else + } else { shapeData.capFillIndexBuffers.clear(); + } - for (List prim : cb.getPrims()) - { + for (List prim : cb.getPrims()) { IntBuffer ib = shapeData.capFillIndices.slice(); - for (Integer i : prim) - { + for (Integer i : prim) { ib.put(i); } ib.flip(); @@ -2227,17 +2163,18 @@ protected void generateCapInteriorIndices(ShapeData shapeData) } } - protected boolean isSameAsPreviousTerrain(Terrain terrain) - { - if (terrain == null || terrain != this.previousIntersectionTerrain) + protected boolean isSameAsPreviousTerrain(Terrain terrain) { + if (terrain == null || terrain != this.previousIntersectionTerrain) { return false; + } //noinspection SimplifiableIfStatement - if (terrain.getVerticalExaggeration() != this.previousIntersectionTerrain.getVerticalExaggeration()) + if (terrain.getVerticalExaggeration() != this.previousIntersectionTerrain.getVerticalExaggeration()) { return false; + } - return this.previousIntersectionGlobeStateKey != null && - terrain.getGlobe().getGlobeStateKey().equals(this.previousIntersectionGlobeStateKey); + return this.previousIntersectionGlobeStateKey != null + && terrain.getGlobe().getGlobeStateKey().equals(this.previousIntersectionGlobeStateKey); } /** @@ -2246,65 +2183,69 @@ protected boolean isSameAsPreviousTerrain(Terrain terrain) * rather than the terrain used during rendering, which may be at lower level of detail than required for accurate * intersection determination. * - * @param line the line to intersect. + * @param line the line to intersect. * @param terrain the {@link Terrain} to use when computing the extruded polygon's geometry. * * @return a list of intersections identifying where the line intersects the extruded polygon, or null if the line - * does not intersect the extruded polygon. + * does not intersect the extruded polygon. * * @throws InterruptedException if the operation is interrupted. * @see Terrain */ - public List intersect(Line line, Terrain terrain) throws InterruptedException - { - if (!this.isEnableSides() && !this.isEnableCap()) + public List intersect(Line line, Terrain terrain) throws InterruptedException { + if (!this.isEnableSides() && !this.isEnableCap()) { return null; + } Position refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return null; + } - if (!this.isOuterBoundaryValid()) + if (!this.isOuterBoundaryValid()) { return null; + } // Reuse the previously computed high-res boundary set if the terrain is the same. ShapeData highResShapeData = this.isSameAsPreviousTerrain(terrain) ? this.previousIntersectionShapeData - : null; + : null; - if (highResShapeData == null) - { + if (highResShapeData == null) { highResShapeData = this.createIntersectionGeometry(terrain); - if (highResShapeData == null) + if (highResShapeData == null) { return null; + } this.previousIntersectionShapeData = highResShapeData; this.previousIntersectionTerrain = terrain; this.previousIntersectionGlobeStateKey = terrain.getGlobe().getGlobeStateKey(); } - if (highResShapeData.getExtent() != null && highResShapeData.getExtent().intersect(line) == null) + if (highResShapeData.getExtent() != null && highResShapeData.getExtent().intersect(line) == null) { return null; + } final Line localLine = new Line(line.getOrigin().subtract3(highResShapeData.getReferencePoint()), - line.getDirection()); + line.getDirection()); List intersections = new ArrayList(); - for (ExtrudedBoundaryInfo boundary : highResShapeData) - { + for (ExtrudedBoundaryInfo boundary : highResShapeData) { List boundaryIntersections = this.intersectBoundarySides(localLine, boundary); - if (boundaryIntersections != null && boundaryIntersections.size() > 0) + if (boundaryIntersections != null && boundaryIntersections.size() > 0) { intersections.addAll(boundaryIntersections); + } } - if (this.isEnableCap()) + if (this.isEnableCap()) { this.intersectCap(localLine, highResShapeData, intersections); + } - if (intersections.size() == 0) + if (intersections.size() == 0) { return null; + } - for (Intersection intersection : intersections) - { + for (Intersection intersection : intersections) { Vec4 pt = intersection.getIntersectionPoint().add3(highResShapeData.getReferencePoint()); intersection.setIntersectionPoint(pt); @@ -2320,23 +2261,25 @@ public List intersect(Line line, Terrain terrain) throws Interrupt return intersections; } - protected ShapeData createIntersectionGeometry(Terrain terrain) - { + protected ShapeData createIntersectionGeometry(Terrain terrain) { ShapeData shapeData = new ShapeData(null, this); shapeData.setGlobeStateKey(terrain.getGlobe().getGlobeStateKey()); this.computeReferencePoint(terrain, shapeData); - if (shapeData.getReferencePoint() == null) + if (shapeData.getReferencePoint() == null) { return null; + } // Compute the boundary vertices first. this.createVertices(terrain, shapeData, false); - if (this.isEnableSides()) + if (this.isEnableSides()) { this.createSideGeometry(shapeData); + } - if (this.isEnableCap()) + if (this.isEnableCap()) { this.createCapGeometry(null, shapeData); + } shapeData.setExtent(this.computeExtent(shapeData.getOuterBoundaryInfo(), shapeData.getReferencePoint())); @@ -2346,7 +2289,7 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) /** * Intersects a line with the sides of an individual boundary. * - * @param line the line to intersect. + * @param line the line to intersect. * @param boundary the boundary to intersect. * * @return the computed intersections, or null if there are no intersections. @@ -2354,47 +2297,47 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) * @throws InterruptedException if the operation is interrupted. */ protected List intersectBoundarySides(Line line, ExtrudedBoundaryInfo boundary) - throws InterruptedException - { + throws InterruptedException { List intersections = new ArrayList(); Vec4[] topVertices = boundary.capVertices; Vec4[] bottomVertices = boundary.baseVertices; - for (int i = 0; i < boundary.baseVertices.length - 1; i++) - { - Vec4 va = bottomVertices[i]; + for (int i = 0; i < boundary.baseVertices.length - 1; i++) { + Vec4 va = bottomVertices[i]; Vec4 vb = topVertices[i + 1]; Vec4 vc = topVertices[i]; Intersection intersection = Triangle.intersect(line, va, vb, vc); - if (intersection != null) + if (intersection != null) { intersections.add(intersection); + } vc = bottomVertices[i + 1]; intersection = Triangle.intersect(line, va, vb, vc); - if (intersection != null) + if (intersection != null) { intersections.add(intersection); + } } return intersections.size() > 0 ? intersections : null; } protected void intersectCap(Line line, ShapeData shapeData, List intersections) - throws InterruptedException - { - if (shapeData.cb.getPrimTypes() == null) + throws InterruptedException { + if (shapeData.cb.getPrimTypes() == null) { return; + } - for (int i = 0; i < shapeData.cb.getPrimTypes().size(); i++) - { + for (int i = 0; i < shapeData.cb.getPrimTypes().size(); i++) { IntBuffer ib = shapeData.capFillIndexBuffers.get(i); ib.rewind(); List ti = Triangle.intersectTriangleTypes(line, shapeData.capVertexBuffer, ib, - shapeData.cb.getPrimTypes().get(i)); + shapeData.cb.getPrimTypes().get(i)); - if (ti != null && ti.size() > 0) + if (ti != null && ti.size() > 0) { intersections.addAll(ti); + } } } @@ -2406,38 +2349,39 @@ protected void intersectCap(Line line, ShapeData shapeData, List i * * @param position the new position of the shape's reference position. */ - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isOuterBoundaryValid()) + if (!this.isOuterBoundaryValid()) { return; + } Position oldPosition = this.getReferencePosition(); - if (oldPosition == null) + if (oldPosition == null) { return; + } List> newLocations = new ArrayList>(this.boundaries.size()); - for (List boundary : this.boundaries) - { - if (boundary == null || boundary.size() == 0) + for (List boundary : this.boundaries) { + if (boundary == null || boundary.size() == 0) { continue; + } List newList = LatLon.computeShiftedLocations(oldPosition, position, boundary); - if (newList == null) + if (newList == null) { continue; + } // Must convert the new locations to positions if the old ones were positions. - for (int i = 0; i < boundary.size(); i++) - { - if (boundary.get(i) instanceof Position) + for (int i = 0; i < boundary.size(); i++) { + if (boundary.get(i) instanceof Position) { newList.set(i, new Position(newList.get(i), ((Position) boundary.get(i)).getAltitude())); + } } newLocations.add(newList); @@ -2448,8 +2392,7 @@ public void moveTo(Position position) this.reset(); } - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { // Write geometry xmlWriter.writeStartElement("Polygon"); @@ -2467,34 +2410,33 @@ protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLS xmlWriter.writeEndElement(); // Polygon } - protected void writeKMLBoundaries(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void writeKMLBoundaries(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { // Outer boundary Iterable outerBoundary = this.getOuterBoundary(); - if (outerBoundary != null) - { + if (outerBoundary != null) { xmlWriter.writeStartElement("outerBoundaryIs"); - if (outerBoundary.iterator().hasNext() && outerBoundary.iterator().next() instanceof Position) + if (outerBoundary.iterator().hasNext() && outerBoundary.iterator().next() instanceof Position) { this.exportBoundaryAsLinearRing(xmlWriter, outerBoundary); - else + } else { KMLExportUtil.exportBoundaryAsLinearRing(xmlWriter, outerBoundary, getHeight()); + } xmlWriter.writeEndElement(); // outerBoundaryIs } // Inner boundaries Iterator> boundaryIterator = this.boundaries.iterator(); - if (boundaryIterator.hasNext()) + if (boundaryIterator.hasNext()) { boundaryIterator.next(); // Skip outer boundary, we already dealt with it above - - while (boundaryIterator.hasNext()) - { + } + while (boundaryIterator.hasNext()) { List boundary = boundaryIterator.next(); xmlWriter.writeStartElement("innerBoundaryIs"); - if (boundary.iterator().hasNext() && boundary.iterator().next() instanceof Position) + if (boundary.iterator().hasNext() && boundary.iterator().next() instanceof Position) { this.exportBoundaryAsLinearRing(xmlWriter, outerBoundary); - else + } else { KMLExportUtil.exportBoundaryAsLinearRing(xmlWriter, boundary, getHeight()); + } xmlWriter.writeEndElement(); // innerBoundaryIs } } @@ -2504,29 +2446,24 @@ protected void writeKMLBoundaries(XMLStreamWriter xmlWriter) throws IOException, * type originally specified. * * @param xmlWriter the XML writer. - * @param boundary the boundary to write. + * @param boundary the boundary to write. * * @throws XMLStreamException if an error occurs during writing. */ protected void exportBoundaryAsLinearRing(XMLStreamWriter xmlWriter, Iterable boundary) - throws XMLStreamException - { + throws XMLStreamException { xmlWriter.writeStartElement("LinearRing"); xmlWriter.writeStartElement("coordinates"); - for (LatLon location : boundary) - { - if (location instanceof Position) - { + for (LatLon location : boundary) { + if (location instanceof Position) { xmlWriter.writeCharacters(String.format(Locale.US, "%f,%f,%f ", - location.getLongitude().getDegrees(), - location.getLatitude().getDegrees(), - ((Position) location).getAltitude())); - } - else - { + location.getLongitude().getDegrees(), + location.getLatitude().getDegrees(), + ((Position) location).getAltitude())); + } else { xmlWriter.writeCharacters(String.format(Locale.US, "%f,%f ", - location.getLongitude().getDegrees(), - location.getLatitude().getDegrees())); + location.getLongitude().getDegrees(), + location.getLatitude().getDegrees())); } } xmlWriter.writeEndElement(); // coordinates diff --git a/src/gov/nasa/worldwind/render/FBOTexture.java b/src/gov/nasa/worldwind/render/FBOTexture.java index 8c1b4bea96..5d1060c911 100644 --- a/src/gov/nasa/worldwind/render/FBOTexture.java +++ b/src/gov/nasa/worldwind/render/FBOTexture.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -18,26 +17,26 @@ * @author tag * @version $Id: FBOTexture.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FBOTexture extends FramebufferTexture -{ - public FBOTexture(WWTexture imageSource, Sector sector, List corners) - { +public class FBOTexture extends FramebufferTexture { + + public FBOTexture(WWTexture imageSource, Sector sector, List corners) { super(imageSource, sector, corners); this.width = 1024; this.height = 1024; } - protected Texture initializeTexture(DrawContext dc) - { + protected Texture initializeTexture(DrawContext dc) { // Bind actually binds the source texture only if the image source is available, otherwise it initiates image // source retrieval. If bind returns false, the image source is not yet available. - if (this.sourceTexture == null || !this.sourceTexture.bind(dc)) + if (this.sourceTexture == null || !this.sourceTexture.bind(dc)) { return null; + } // Ensure that the source texture size is available so that the FBO can be sized to match the source image. - if (sourceTexture.getWidth(dc) < 1 || sourceTexture.getHeight(dc) < 1) + if (sourceTexture.getWidth(dc) < 1 || sourceTexture.getHeight(dc) < 1) { return null; + } // Limit FBO size to the max OGL size or 4k, whichever is smaller int maxSize = Math.min(dc.getGLRuntimeCapabilities().getMaxTextureSize(), 4096); @@ -53,13 +52,12 @@ protected Texture initializeTexture(DrawContext dc) int[] fbo = new int[1]; gl.glGenFramebuffers(1, fbo, 0); - try - { + try { gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbo[0]); TextureData td = new TextureData(gl.getGLProfile(), GL.GL_RGBA, this.width, this.height, 0, GL.GL_RGBA, - GL.GL_UNSIGNED_BYTE, false, false, true, Buffers.newDirectByteBuffer(this.width * this.height * 4), - null); + GL.GL_UNSIGNED_BYTE, false, false, true, Buffers.newDirectByteBuffer(this.width * this.height * 4), + null); Texture t = TextureIO.newTexture(td); t.bind(gl); @@ -69,15 +67,12 @@ protected Texture initializeTexture(DrawContext dc) gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, - t.getTextureObject(gl), 0); + t.getTextureObject(gl), 0); int status = gl.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER); - if (status == GL.GL_FRAMEBUFFER_COMPLETE) - { + if (status == GL.GL_FRAMEBUFFER_COMPLETE) { this.generateTexture(dc, this.width, this.height); - } - else - { + } else { String msg = Logging.getMessage("FBOTexture.TextureNotCreated"); throw new IllegalStateException(msg); } @@ -85,9 +80,7 @@ protected Texture initializeTexture(DrawContext dc) dc.getTextureCache().put(this, t); return t; - } - finally - { + } finally { gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, previousFbo[0]); gl.glDeleteFramebuffers(1, fbo, 0); } diff --git a/src/gov/nasa/worldwind/render/FrameFactory.java b/src/gov/nasa/worldwind/render/FrameFactory.java index 5c7b00e34b..f5f48618e5 100644 --- a/src/gov/nasa/worldwind/render/FrameFactory.java +++ b/src/gov/nasa/worldwind/render/FrameFactory.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -15,29 +14,41 @@ import java.nio.DoubleBuffer; /** - * Static class for drawing 2D frames.

          All shapes are drawn inside a bounding rectangle whose lower left corner is - * at the origin. Shapes with a leader use an offset point that indicate where the leader triangle should point at - it - * usually has a negative y since the leader connects at the bottom of the frame (at y = 0).

          + * Static class for drawing 2D frames. + *

          + * All shapes are drawn inside a bounding rectangle whose lower left corner is at the origin. Shapes with a leader use + * an offset point that indicate where the leader triangle should point at - it usually has a negative y since the + * leader connects at the bottom of the frame (at y = 0).

          * * @author Patrick Murris * @version $Id: FrameFactory.java 1171 2013-02-11 21:45:02Z dcollins $ * @see AbstractAnnotation */ -public class FrameFactory -{ - /** @deprecated Use {@link AVKey#SHAPE_RECTANGLE} instead. */ +public class FrameFactory { + + /** + * @deprecated Use {@link AVKey#SHAPE_RECTANGLE} instead. + */ @Deprecated public static final String SHAPE_RECTANGLE = AVKey.SHAPE_RECTANGLE; - /** @deprecated Use {@link AVKey#SHAPE_ELLIPSE} instead. */ + /** + * @deprecated Use {@link AVKey#SHAPE_ELLIPSE} instead. + */ @Deprecated public static final String SHAPE_ELLIPSE = AVKey.SHAPE_ELLIPSE; - /** @deprecated Use {@link AVKey#SHAPE_NONE} instead. */ + /** + * @deprecated Use {@link AVKey#SHAPE_NONE} instead. + */ @Deprecated public static final String SHAPE_NONE = AVKey.SHAPE_NONE; - /** @deprecated Use {@link AVKey#SHAPE_TRIANGLE} instead. */ + /** + * @deprecated Use {@link AVKey#SHAPE_TRIANGLE} instead. + */ @Deprecated public static final String LEADER_TRIANGLE = AVKey.SHAPE_TRIANGLE; - /** @deprecated Use {@link AVKey#SHAPE_NONE} instead. */ + /** + * @deprecated Use {@link AVKey#SHAPE_NONE} instead. + */ @Deprecated public static final String LEADER_NONE = AVKey.SHAPE_NONE; @@ -49,18 +60,18 @@ public class FrameFactory * GL.GL_TRIANGLE_FAN and GL.LINE_STRIP. Corner radius only apply to * SHAPE_RECTANGLE - set to zero for square corners. * - * @param dc the current DrawContext. - * @param shape the shape - can be one of SHAPE_RECTANGLE or SHAPE_ELLIPSE. - * @param width the width of the overall shape. - * @param height the height of the shape. - * @param glMode the GL mode - can be one of GL.GL_TRIANGLE_FAN and GL.LINE_STRIP. + * @param dc the current DrawContext. + * @param shape the shape - can be one of SHAPE_RECTANGLE or SHAPE_ELLIPSE. + * @param width the width of the overall shape. + * @param height the height of the shape. + * @param glMode the GL mode - can be one of GL.GL_TRIANGLE_FAN and GL.LINE_STRIP. * @param cornerRadius the rounded corners radius. Set to zero for square corners. */ public static void drawShape(DrawContext dc, String shape, double width, double height, int glMode, - int cornerRadius) - { - if (!shape.equals(AVKey.SHAPE_NONE)) + int cornerRadius) { + if (!shape.equals(AVKey.SHAPE_NONE)) { drawBuffer(dc, glMode, createShapeBuffer(shape, width, height, cornerRadius, null)); + } } /** @@ -69,48 +80,47 @@ public static void drawShape(DrawContext dc, String shape, double width, double * GL.LINE_STRIP. Corner radius only apply to SHAPE_RECTANGLE - set to zero for square * corners. * - * @param dc the current DrawContext. - * @param shape the shape - can be one of SHAPE_RECTANGLE or SHAPE_ELLIPSE. - * @param width the width of the overall shape. - * @param height the height of the shape excluding the leader. - * @param leaderOffset the coordinates of the point to which the leader leads. + * @param dc the current DrawContext. + * @param shape the shape - can be one of SHAPE_RECTANGLE or SHAPE_ELLIPSE. + * @param width the width of the overall shape. + * @param height the height of the shape excluding the leader. + * @param leaderOffset the coordinates of the point to which the leader leads. * @param leaderGapWidth the starting width of the leader shape. - * @param glMode the GL mode - can be one of GL.GL_TRIANGLE_FAN and - * GL.LINE_STRIP. - * @param cornerRadius the rounded corners radius. Set to zero for square corners. + * @param glMode the GL mode - can be one of GL.GL_TRIANGLE_FAN and GL.LINE_STRIP. + * @param cornerRadius the rounded corners radius. Set to zero for square corners. */ public static void drawShapeWithLeader(DrawContext dc, String shape, double width, double height, - Point leaderOffset, double leaderGapWidth, int glMode, int cornerRadius) - { - if (!shape.equals(AVKey.SHAPE_NONE)) + Point leaderOffset, double leaderGapWidth, int glMode, int cornerRadius) { + if (!shape.equals(AVKey.SHAPE_NONE)) { drawBuffer(dc, glMode, - createShapeWithLeaderBuffer(shape, width, height, leaderOffset, leaderGapWidth, cornerRadius, null)); + createShapeWithLeaderBuffer(shape, width, height, leaderOffset, leaderGapWidth, cornerRadius, null)); + } } /** * Create a vertex buffer for a shape with the specified width, height and corner radius. Corner radius only apply * to SHAPE_RECTANGLE - set to zero for square corners. * - * @param shape the shape - can be one of SHAPE_RECTANGLE or SHAPE_ELLIPSE. - * @param width the width of the overall shape. - * @param height the height of the shape. + * @param shape the shape - can be one of SHAPE_RECTANGLE or SHAPE_ELLIPSE. + * @param width the width of the overall shape. + * @param height the height of the shape. * @param cornerRadius the rounded corners radius. Set to zero for square corners. - * @param buffer the buffer to store shape vertices, or null to allocate a new buffer. + * @param buffer the buffer to store shape vertices, or null to allocate a new buffer. * * @return the vertex buffer. */ public static DoubleBuffer createShapeBuffer(String shape, double width, double height, int cornerRadius, - DoubleBuffer buffer) - { - if (shape.equals(AVKey.SHAPE_RECTANGLE)) + DoubleBuffer buffer) { + if (shape.equals(AVKey.SHAPE_RECTANGLE)) { return createRoundedRectangleBuffer(width, height, cornerRadius, buffer); - else if (shape.equals(AVKey.SHAPE_ELLIPSE)) + } else if (shape.equals(AVKey.SHAPE_ELLIPSE)) { return createEllipseBuffer(width, height, circleSteps, buffer); - else if (shape.equals(AVKey.SHAPE_NONE)) + } else if (shape.equals(AVKey.SHAPE_NONE)) { return null; - else - // default to rectangle if shape unknown + } else // default to rectangle if shape unknown + { return createRoundedRectangleBuffer(width, height, cornerRadius, buffer); + } } /** @@ -118,51 +128,48 @@ else if (shape.equals(AVKey.SHAPE_NONE)) * leader triangle pointing to a specified point. Corner radius only apply to SHAPE_RECTANGLE - set to * zero for square corners. * - * @param shape the shape - can be one of SHAPE_RECTANGLE or SHAPE_ELLIPSE. - * @param width the width of the overall shape. - * @param height the height of the shape excluding the leader. - * @param leaderOffset the coordinates of the point to which the leader leads. + * @param shape the shape - can be one of SHAPE_RECTANGLE or SHAPE_ELLIPSE. + * @param width the width of the overall shape. + * @param height the height of the shape excluding the leader. + * @param leaderOffset the coordinates of the point to which the leader leads. * @param leaderGapWidth the starting width of the leader shape. - * @param cornerRadius the rounded corners radius. Set to zero for square corners. - * @param buffer the buffer to store shape vertices, or null to allocate a new buffer. + * @param cornerRadius the rounded corners radius. Set to zero for square corners. + * @param buffer the buffer to store shape vertices, or null to allocate a new buffer. * * @return the vertex buffer. */ public static DoubleBuffer createShapeWithLeaderBuffer(String shape, double width, double height, - Point leaderOffset, double leaderGapWidth, int cornerRadius, DoubleBuffer buffer) - { - if (shape.equals(AVKey.SHAPE_RECTANGLE)) + Point leaderOffset, double leaderGapWidth, int cornerRadius, DoubleBuffer buffer) { + if (shape.equals(AVKey.SHAPE_RECTANGLE)) { return createRoundedRectangleWithLeaderBuffer(width, height, leaderOffset, leaderGapWidth, cornerRadius, - buffer); - else if (shape.equals(AVKey.SHAPE_ELLIPSE)) + buffer); + } else if (shape.equals(AVKey.SHAPE_ELLIPSE)) { return createEllipseWithLeaderBuffer(width, height, leaderOffset, leaderGapWidth, circleSteps, buffer); - else if (shape.equals(AVKey.SHAPE_NONE)) + } else if (shape.equals(AVKey.SHAPE_NONE)) { return null; - else - // default to rectangle if shape unknown + } else // default to rectangle if shape unknown + { return createRoundedRectangleWithLeaderBuffer(width, height, leaderOffset, leaderGapWidth, cornerRadius, - buffer); + buffer); + } } /** * Draw a vertex buffer in a given gl mode. Vertex buffers coming from the createShapeBuffer() methods support both * GL.GL_TRIANGLE_FAN and GL.LINE_STRIP. * - * @param dc the current DrawContext. - * @param mode the desired drawing GL mode. + * @param dc the current DrawContext. + * @param mode the desired drawing GL mode. * @param count the number of vertices to draw. * @param verts the vertex buffer to draw. */ - public static void drawBuffer(DrawContext dc, int mode, int count, DoubleBuffer verts) - { - if (dc == null) - { + public static void drawBuffer(DrawContext dc, int mode, int count, DoubleBuffer verts) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (verts == null) - { + if (verts == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -183,22 +190,19 @@ public static void drawBuffer(DrawContext dc, int mode, int count, DoubleBuffer * Draw a vertex buffer with texture coordinates in a given gl mode. Vertex buffers coming from the * createShapeBuffer() methods support both GL.GL_TRIANGLE_FAN and GL.LINE_STRIP. * - * @param dc the current DrawContext. - * @param mode the desired drawing GL mode. - * @param count the number of vertices to draw. - * @param verts the vertex buffer to draw. + * @param dc the current DrawContext. + * @param mode the desired drawing GL mode. + * @param count the number of vertices to draw. + * @param verts the vertex buffer to draw. * @param coords the buffer containing the shape texture coordinates. */ - public static void drawBuffer(DrawContext dc, int mode, int count, DoubleBuffer verts, DoubleBuffer coords) - { - if (dc == null) - { + public static void drawBuffer(DrawContext dc, int mode, int count, DoubleBuffer verts, DoubleBuffer coords) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (verts == null || coords == null) - { + if (verts == null || coords == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -217,16 +221,13 @@ public static void drawBuffer(DrawContext dc, int mode, int count, DoubleBuffer gl.glPopClientAttrib(); } - public static void drawBuffer(DrawContext dc, int mode, DoubleBuffer verts) - { - if (dc == null) - { + public static void drawBuffer(DrawContext dc, int mode, DoubleBuffer verts) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (verts == null) - { + if (verts == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -238,10 +239,8 @@ public static void drawBuffer(DrawContext dc, int mode, DoubleBuffer verts) //-- Shape creation //-- Rectangle ------------------------------------------------------------------ - private static DoubleBuffer createRoundedRectangleBuffer(double width, double height, int cornerRadius, - DoubleBuffer buffer) - { + DoubleBuffer buffer) { int numVertices = 9 + (cornerRadius < 1 ? 0 : 4 * (cornerSteps - 2)); buffer = allocateVertexBuffer(numVertices, buffer); @@ -259,14 +258,14 @@ private static DoubleBuffer createRoundedRectangleBuffer(double width, double he buffer.put(idx++, width); buffer.put(idx++, height - cornerRadius); idx = drawCorner(width - cornerRadius, height - cornerRadius, cornerRadius, 0, Math.PI / 2, cornerSteps, buffer, - idx); + idx); // Top buffer.put(idx++, width - cornerRadius); buffer.put(idx++, height); buffer.put(idx++, (double) cornerRadius); buffer.put(idx++, height); idx = drawCorner(cornerRadius, height - cornerRadius, cornerRadius, Math.PI / 2, Math.PI, cornerSteps, buffer, - idx); + idx); // Left buffer.put(idx++, 0d); buffer.put(idx++, height - cornerRadius); @@ -282,8 +281,7 @@ private static DoubleBuffer createRoundedRectangleBuffer(double width, double he } private static DoubleBuffer createRoundedRectangleWithLeaderBuffer(double width, double height, Point leaderOffset, - double leaderGapWidth, int cornerRadius, DoubleBuffer buffer) - { + double leaderGapWidth, int cornerRadius, DoubleBuffer buffer) { int numVertices = 12 + (cornerRadius < 1 ? 0 : 4 * (cornerSteps - 2)); buffer = allocateVertexBuffer(numVertices, buffer); @@ -302,14 +300,14 @@ private static DoubleBuffer createRoundedRectangleWithLeaderBuffer(double width, buffer.put(idx++, width); buffer.put(idx++, height - cornerRadius); idx = drawCorner(width - cornerRadius, height - cornerRadius, cornerRadius, 0, Math.PI / 2, cornerSteps, buffer, - idx); + idx); // Top buffer.put(idx++, width - cornerRadius); buffer.put(idx++, height); buffer.put(idx++, (double) cornerRadius); buffer.put(idx++, height); idx = drawCorner(cornerRadius, height - cornerRadius, cornerRadius, Math.PI / 2, Math.PI, cornerSteps, buffer, - idx); + idx); // Left buffer.put(idx++, 0d); buffer.put(idx++, height - cornerRadius); @@ -332,14 +330,13 @@ private static DoubleBuffer createRoundedRectangleWithLeaderBuffer(double width, } private static int drawCorner(double x0, double y0, double cornerRadius, double start, double end, int steps, - DoubleBuffer buffer, int startIdx) - { - if (cornerRadius < 1) + DoubleBuffer buffer, int startIdx) { + if (cornerRadius < 1) { return startIdx; + } double step = (end - start) / (steps - 1); - for (int i = 1; i < steps - 1; i++) - { + for (int i = 1; i < steps - 1; i++) { double a = start + step * i; double x = x0 + Math.cos(a) * cornerRadius; double y = y0 + Math.sin(a) * cornerRadius; @@ -351,9 +348,7 @@ private static int drawCorner(double x0, double y0, double cornerRadius, double } //-- Circle / Ellipse ----------------------------------------------------------- - - private static DoubleBuffer createEllipseBuffer(double width, double height, int steps, DoubleBuffer buffer) - { + private static DoubleBuffer createEllipseBuffer(double width, double height, int steps, DoubleBuffer buffer) { int numVertices = steps + 1; buffer = allocateVertexBuffer(numVertices, buffer); @@ -366,8 +361,7 @@ private static DoubleBuffer createEllipseBuffer(double width, double height, int double step = Math.PI * 2 / steps; int idx = 0; - for (int i = 0; i <= steps; i++) - { + for (int i = 0; i <= steps; i++) { double a = step * i - halfPI; double x = x0 + Math.cos(a) * halfWidth; double y = y0 + Math.sin(a) * halfHeight; @@ -380,8 +374,7 @@ private static DoubleBuffer createEllipseBuffer(double width, double height, int } private static DoubleBuffer createEllipseWithLeaderBuffer(double width, double height, Point leaderOffset, - double leaderGapWidth, int steps, DoubleBuffer buffer) - { + double leaderGapWidth, int steps, DoubleBuffer buffer) { int numVertices = steps + 3; buffer = allocateVertexBuffer(numVertices, buffer); @@ -396,13 +389,14 @@ private static DoubleBuffer createEllipseWithLeaderBuffer(double width, double h double halfGap = leaderGapWidth / 2 / halfWidth; int idx = 0; - for (int i = 0; i <= steps; i++) - { + for (int i = 0; i <= steps; i++) { double a = step * i - halfPI; - if (i == 0) + if (i == 0) { a += halfGap; - if (i == steps) + } + if (i == steps) { a -= halfGap; + } double x = x0 + Math.cos(a) * halfWidth; double y = y0 + Math.sin(a) * halfHeight; buffer.put(idx++, x); @@ -420,16 +414,16 @@ private static DoubleBuffer createEllipseWithLeaderBuffer(double width, double h } //-- Utility Methods - - private static DoubleBuffer allocateVertexBuffer(int numVertices, DoubleBuffer buffer) - { + private static DoubleBuffer allocateVertexBuffer(int numVertices, DoubleBuffer buffer) { int numCoords = 2 * numVertices; - if (buffer != null) + if (buffer != null) { buffer.clear(); + } - if (buffer == null || buffer.capacity() < numCoords) + if (buffer == null || buffer.capacity() < numCoords) { buffer = Buffers.newDirectDoubleBuffer(numCoords); + } return buffer; } diff --git a/src/gov/nasa/worldwind/render/FramebufferTexture.java b/src/gov/nasa/worldwind/render/FramebufferTexture.java index e3b16b9c02..1241f24178 100644 --- a/src/gov/nasa/worldwind/render/FramebufferTexture.java +++ b/src/gov/nasa/worldwind/render/FramebufferTexture.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.opengl.util.texture.*; @@ -17,8 +16,8 @@ * @author tag * @version $Id: FramebufferTexture.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FramebufferTexture implements WWTexture -{ +public class FramebufferTexture implements WWTexture { + protected WWTexture sourceTexture; protected Sector sector; protected List corners; @@ -26,30 +25,30 @@ public class FramebufferTexture implements WWTexture protected int width; protected int height; protected TextureCoords textureCoords = new TextureCoords(0f, 0f, 1f, 1f); - /** The density of explicit texture coordinates to specify for the quadrilateral the texture's applied to. */ + /** + * The density of explicit texture coordinates to specify for the quadrilateral the texture's applied to. + */ protected int tessellationDensity; - /** The default density of texture coordinates to specify for the quadrilateral the texture's applied to. */ + /** + * The default density of texture coordinates to specify for the quadrilateral the texture's applied to. + */ protected static final int DEFAULT_TESSELLATION_DENSITY = 32; - public FramebufferTexture(WWTexture imageSource, Sector sector, List corners) - { - if (imageSource == null) - { + public FramebufferTexture(WWTexture imageSource, Sector sector, List corners) { + if (imageSource == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (corners == null) - { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -62,50 +61,40 @@ public FramebufferTexture(WWTexture imageSource, Sector sector, List cor this.tessellationDensity = DEFAULT_TESSELLATION_DENSITY; } - public int getWidth(DrawContext dc) - { + public int getWidth(DrawContext dc) { return width; } - public int getHeight(DrawContext dc) - { + public int getHeight(DrawContext dc) { return height; } - public Sector getSector() - { + public Sector getSector() { return sector; } - public List getCorners() - { + public List getCorners() { return corners; } - public boolean isTextureCurrent(DrawContext dc) - { + public boolean isTextureCurrent(DrawContext dc) { return dc.getTextureCache().getTexture(this) != null; } - public Object getImageSource() - { + public Object getImageSource() { return this.sourceTexture; } - public TextureCoords getTexCoords() - { + public TextureCoords getTexCoords() { return this.textureCoords; } - public boolean isTextureInitializationFailed() - { + public boolean isTextureInitializationFailed() { return this.sourceTexture != null && this.sourceTexture.isTextureInitializationFailed(); } - public boolean bind(DrawContext dc) - { - if (dc == null) - { + public boolean bind(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -113,39 +102,41 @@ public boolean bind(DrawContext dc) Texture t = dc.getTextureCache().getTexture(this); - if (t == null) + if (t == null) { t = this.initializeTexture(dc); + } - if (t != null) + if (t != null) { t.bind(dc.getGL()); + } return t != null; } - public void applyInternalTransform(DrawContext dc) - { + public void applyInternalTransform(DrawContext dc) { // Framebuffer textures don't have an internal transform. } - protected int getTessellationDensity() - { + protected int getTessellationDensity() { return this.tessellationDensity; } - protected Texture initializeTexture(DrawContext dc) - { + protected Texture initializeTexture(DrawContext dc) { // The frame buffer can be used only during pre-rendering. - if (!dc.isPreRenderMode()) + if (!dc.isPreRenderMode()) { return null; + } // Bind actually binds the source texture only if the image source is available, otherwise it initiates image // source retrieval. If bind returns false, the image source is not yet available. - if (this.sourceTexture == null || !this.sourceTexture.bind(dc)) + if (this.sourceTexture == null || !this.sourceTexture.bind(dc)) { return null; + } // Ensure that the source texture size is available so that the FBO can be sized to match the source image. - if (this.sourceTexture.getWidth(dc) < 1 || this.sourceTexture.getHeight(dc) < 1) + if (this.sourceTexture.getWidth(dc) < 1 || this.sourceTexture.getHeight(dc) < 1) { return null; + } int potSourceWidth = WWMath.powerOfTwoCeiling(this.sourceTexture.getWidth(dc)); int potSourceHeight = WWMath.powerOfTwoCeiling(this.sourceTexture.getHeight(dc)); @@ -153,13 +144,14 @@ protected Texture initializeTexture(DrawContext dc) this.width = Math.min(potSourceWidth, dc.getView().getViewport().width); this.height = Math.min(potSourceHeight, dc.getView().getViewport().height); - if (!this.generateTexture(dc, this.width, this.height)) + if (!this.generateTexture(dc, this.width, this.height)) { return null; + } GL gl = dc.getGL(); TextureData td = new TextureData(gl.getGLProfile(), GL.GL_RGBA, this.width, this.height, 0, GL.GL_RGBA, - GL.GL_UNSIGNED_BYTE, false, false, false, null, null); + GL.GL_UNSIGNED_BYTE, false, false, false, null, null); Texture t = TextureIO.newTexture(td); t.bind(gl); // must do this after generating texture because another texture is bound then @@ -169,26 +161,24 @@ protected Texture initializeTexture(DrawContext dc) gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); gl.glCopyTexImage2D(GL.GL_TEXTURE_2D, 0, td.getInternalFormat(), 0, 0, td.getWidth(), td.getHeight(), - td.getBorder()); + td.getBorder()); dc.getTextureCache().put(this, t); return t; } - protected boolean generateTexture(DrawContext dc, int width, int height) - { + protected boolean generateTexture(DrawContext dc, int width, int height) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); Matrix geoToCartesian = this.computeGeographicToCartesianTransform(this.sector); - try - { + try { ogsh.pushAttrib(gl, GL2.GL_COLOR_BUFFER_BIT - | GL2.GL_ENABLE_BIT - | GL2.GL_TRANSFORM_BIT - | GL2.GL_VIEWPORT_BIT); + | GL2.GL_ENABLE_BIT + | GL2.GL_TRANSFORM_BIT + | GL2.GL_VIEWPORT_BIT); // Fill the frame buffer with transparent black. gl.glClearColor(0f, 0f, 0f, 0f); @@ -208,13 +198,12 @@ protected boolean generateTexture(DrawContext dc, int width, int height) ogsh.pushModelviewIdentity(gl); ogsh.pushTextureIdentity(gl); - if (this.sourceTexture != null) - { - try - { + if (this.sourceTexture != null) { + try { gl.glEnable(GL.GL_TEXTURE_2D); - if (!this.sourceTexture.bind(dc)) + if (!this.sourceTexture.bind(dc)) { return false; + } this.sourceTexture.applyInternalTransform(dc); @@ -223,24 +212,19 @@ protected boolean generateTexture(DrawContext dc, int width, int height) int tessellationDensity = this.getTessellationDensity(); this.drawQuad(dc, geoToCartesian, tessellationDensity, tessellationDensity); - } - finally - { + } finally { gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, OGLUtil.DEFAULT_TEX_ENV_MODE); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); } } - } - finally - { + } finally { ogsh.pop(gl); } return true; } - protected Matrix computeGeographicToCartesianTransform(Sector sector) - { + protected Matrix computeGeographicToCartesianTransform(Sector sector) { // Compute a transform that will map the geographic region defined by sector onto a cartesian region of width // and height 2.0 centered at the origin. @@ -258,13 +242,11 @@ protected Matrix computeGeographicToCartesianTransform(Sector sector) return transform; } - protected Vec4 transformToQuadCoordinates(Matrix geoToCartesian, LatLon latLon) - { + protected Vec4 transformToQuadCoordinates(Matrix geoToCartesian, LatLon latLon) { return new Vec4(latLon.getLongitude().degrees, latLon.getLatitude().degrees, 0.0).transformBy4(geoToCartesian); } - protected void drawQuad(DrawContext dc, Matrix geoToCartesian, int slices, int stacks) - { + protected void drawQuad(DrawContext dc, Matrix geoToCartesian, int slices, int stacks) { Vec4 ll = this.transformToQuadCoordinates(geoToCartesian, this.corners.get(0)); Vec4 lr = this.transformToQuadCoordinates(geoToCartesian, this.corners.get(1)); Vec4 ur = this.transformToQuadCoordinates(geoToCartesian, this.corners.get(2)); @@ -274,31 +256,25 @@ protected void drawQuad(DrawContext dc, Matrix geoToCartesian, int slices, int s GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_TRIANGLE_STRIP); - try - { + try { this.drawQuad(dc, interp, slices, stacks); - } - finally - { + } finally { gl.glEnd(); } } - protected void drawQuad(DrawContext dc, BilinearInterpolator interp, int slices, int stacks) - { + protected void drawQuad(DrawContext dc, BilinearInterpolator interp, int slices, int stacks) { double[] compArray = new double[4]; double du = 1.0f / (float) slices; double dv = 1.0f / (float) stacks; GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - for (int vi = 0; vi < stacks; vi++) - { + for (int vi = 0; vi < stacks; vi++) { double v = vi * dv; double vn = (vi + 1) * dv; - if (vi != 0) - { + if (vi != 0) { interp.interpolate(slices * du, v, compArray); gl.glTexCoord2d(slices * du, v); gl.glVertex3dv(compArray, 0); @@ -308,8 +284,7 @@ protected void drawQuad(DrawContext dc, BilinearInterpolator interp, int slices, gl.glVertex3dv(compArray, 0); } - for (int ui = 0; ui <= slices; ui++) - { + for (int ui = 0; ui <= slices; ui++) { double u = ui * du; interp.interpolate(u, v, compArray); diff --git a/src/gov/nasa/worldwind/render/GLRuntimeCapabilities.java b/src/gov/nasa/worldwind/render/GLRuntimeCapabilities.java index a474bcbf78..d0665aeb27 100644 --- a/src/gov/nasa/worldwind/render/GLRuntimeCapabilities.java +++ b/src/gov/nasa/worldwind/render/GLRuntimeCapabilities.java @@ -31,8 +31,8 @@ * @author dcollins * @version $Id: GLRuntimeCapabilities.java 1933 2014-04-14 22:54:19Z dcollins $ */ -public class GLRuntimeCapabilities -{ +public class GLRuntimeCapabilities { + protected static final String GL_EXT_FRAMEBUFFER_OBJECT_STRING = "GL_EXT_framebuffer_object"; protected static final String GL_EXT_TEXTURE_FILTER_ANISOTROPIC_STRING = "GL_EXT_texture_filter_anisotropic"; @@ -59,8 +59,7 @@ public class GLRuntimeCapabilities * "gov.nasa.worldwind.avkey.VBOUsage". If that key is not specified in the configuration then vertex-buffer usage * defaults to true. */ - public GLRuntimeCapabilities() - { + public GLRuntimeCapabilities() { this.isAnisotropicTextureFilterEnabled = true; this.isFramebufferObjectEnabled = true; this.isVertexBufferObjectEnabled = Configuration.getBooleanValue(AVKey.VBO_USAGE, true); @@ -77,10 +76,8 @@ public GLRuntimeCapabilities() * * @throws IllegalArgumentException if the glContext is null. */ - public void initialize(GLContext glContext) - { - if (glContext == null) - { + public void initialize(GLContext glContext) { + if (glContext == null) { String message = Logging.getMessage("nullValue.GLContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -88,15 +85,14 @@ public void initialize(GLContext glContext) GL gl = glContext.getGL(); - if (this.glVersion < 1.0) - { + if (this.glVersion < 1.0) { String s = gl.glGetString(GL.GL_VERSION); - if (s != null) - { + if (s != null) { s = s.substring(0, 3); Double d = WWUtil.convertStringToDouble(s); - if (d != null) + if (d != null) { this.glVersion = d; + } } } @@ -108,8 +104,7 @@ public void initialize(GLContext glContext) String glVendor = gl.glGetString(GL.GL_VENDOR); String glRenderer = gl.glGetString(GL.GL_RENDERER); if (glVendor != null && glVendor.toLowerCase().contains("vmware") - && glRenderer != null && glRenderer.toLowerCase().contains("svga3d")) - { + && glRenderer != null && glRenderer.toLowerCase().contains("svga3d")) { this.isVMwareSVGA3D = true; } @@ -118,8 +113,7 @@ public void initialize(GLContext glContext) // Vertex Buffer Objects are supported in version 1.5 or greater only. this.isVertexBufferObjectAvailable = this.glVersion >= 1.5; - if (this.depthBits == 0) - { + if (this.depthBits == 0) { int[] params = new int[1]; gl.glGetIntegerv(GL.GL_DEPTH_BITS, params, 0); this.depthBits = params[0]; @@ -127,12 +121,10 @@ public void initialize(GLContext glContext) // Texture max anisotropy defaults to -1. A value less than 2.0 indicates that this graphics context does not // support texture anisotropy. - if (this.maxTextureAnisotropy < 0) - { + if (this.maxTextureAnisotropy < 0) { // Documentation on the anisotropic texture filter is available at // http://www.opengl.org/registry/specs/EXT/texture_filter_anisotropic.txt - if (this.isAnisotropicTextureFilterAvailable) - { + if (this.isAnisotropicTextureFilterAvailable) { // The maxAnisotropy value can be any real value. A value less than 2.0 indicates that the graphics // context does not support texture anisotropy. float[] params = new float[1]; @@ -141,15 +133,13 @@ public void initialize(GLContext glContext) } } - if (this.numTextureUnits == 0) - { + if (this.numTextureUnits == 0) { int[] params = new int[1]; gl.glGetIntegerv(GL2.GL_MAX_TEXTURE_UNITS, params, 0); this.numTextureUnits = params[0]; } - if (this.maxTextureSize == 0) - { + if (this.maxTextureSize == 0) { int[] params = new int[1]; gl.glGetIntegerv(GL.GL_MAX_TEXTURE_SIZE, params, 0); this.maxTextureSize = params[0]; @@ -162,8 +152,7 @@ public void initialize(GLContext glContext) * * @return GL version as a number. */ - public double getGLVersion() - { + public double getGLVersion() { return this.glVersion; } @@ -173,55 +162,53 @@ public double getGLVersion() * * @param version the GL version as a number. */ - public void setGLVersion(double version) - { + public void setGLVersion(double version) { this.glVersion = version; } /** - * Returns true if the OpenGL implementation is provided by the VMware SVGA 3D driver. Otherwise this returns - * false. + * Returns true if the OpenGL implementation is provided by the VMware SVGA 3D driver. Otherwise this returns false. *

          * This flag is used to work around bugs and unusual behavior in the VMware SVGA 3D driver. For details on VMware - * graphics drivers, see http://www.vmware.com/files/pdf/techpaper/vmware-horizon-view-graphics-acceleration-deployment.pdf. + * graphics drivers, see + * http://www.vmware.com/files/pdf/techpaper/vmware-horizon-view-graphics-acceleration-deployment.pdf. * * @return true if the OpenGL implementation is VMware SVGA 3D, and false otherwise. */ - public boolean isVMwareSVGA3D() - { + public boolean isVMwareSVGA3D() { return this.isVMwareSVGA3D; } /** * Returns true if anisotropic texture filtering is available in the current GL runtime, and is enabled. Otherwise - * this returns false. For details on GL anisotropic texture filtering, see http://www.opengl.org/registry/specs/EXT/texture_filter_anisotropic.txt. + * this returns false. For details on GL anisotropic texture filtering, see + * http://www.opengl.org/registry/specs/EXT/texture_filter_anisotropic.txt. * * @return true if anisotropic texture filtering is available and enabled, and false otherwise. */ - public boolean isUseAnisotropicTextureFilter() - { + public boolean isUseAnisotropicTextureFilter() { return this.isAnisotropicTextureFilterAvailable && this.isAnisotropicTextureFilterEnabled; } /** * Returns true if framebuffer objects are available in the current GL runtime, and are enabled. Otherwise this - * returns false. For details on GL framebuffer objects, see http://www.opengl.org/registry/specs/EXT/framebuffer_object.txt. + * returns false. For details on GL framebuffer objects, see + * http://www.opengl.org/registry/specs/EXT/framebuffer_object.txt. * * @return true if framebuffer objects are available and enabled, and false otherwise. */ - public boolean isUseFramebufferObject() - { + public boolean isUseFramebufferObject() { return this.isFramebufferObjectAvailable && this.isFramebufferObjectEnabled; } /** * Returns true if vertex buffer objects are available in the current GL runtime, and are enabled. Otherwise this - * returns false. For details on GL vertex buffer objects, see http://www.opengl.org/registry/specs/ARB/vertex_buffer_object.txt. + * returns false. For details on GL vertex buffer objects, see + * http://www.opengl.org/registry/specs/ARB/vertex_buffer_object.txt. * * @return true if vertex buffer objects are available and enabled, and false otherwise. */ - public boolean isUseVertexBufferObject() - { + public boolean isUseVertexBufferObject() { return this.isVertexBufferObjectAvailable && this.isVertexBufferObjectEnabled; } @@ -230,8 +217,7 @@ public boolean isUseVertexBufferObject() * * @return true if anisotropic texture filtering is available, and false otherwise. */ - public boolean isAnisotropicTextureFilterAvailable() - { + public boolean isAnisotropicTextureFilterAvailable() { return this.isAnisotropicTextureFilterAvailable; } @@ -240,8 +226,7 @@ public boolean isAnisotropicTextureFilterAvailable() * * @param available true to flag anisotropic texture filtering as available, and false otherwise. */ - public void setAnisotropicTextureFilterAvailable(boolean available) - { + public void setAnisotropicTextureFilterAvailable(boolean available) { this.isAnisotropicTextureFilterAvailable = available; } @@ -251,8 +236,7 @@ public void setAnisotropicTextureFilterAvailable(boolean available) * * @return true if anisotropic texture filtering is enabled, and false otherwise. */ - public boolean isAnisotropicTextureFilterEnabled() - { + public boolean isAnisotropicTextureFilterEnabled() { return this.isAnisotropicTextureFilterEnabled; } @@ -261,8 +245,7 @@ public boolean isAnisotropicTextureFilterEnabled() * * @param enable true to enable anisotropic texture filtering, false to disable it. */ - public void setAnisotropicTextureFilterEnabled(boolean enable) - { + public void setAnisotropicTextureFilterEnabled(boolean enable) { this.isAnisotropicTextureFilterEnabled = enable; } @@ -271,8 +254,7 @@ public void setAnisotropicTextureFilterEnabled(boolean enable) * * @return true if framebuffer objects are available, and false otherwise. */ - public boolean isFramebufferObjectAvailable() - { + public boolean isFramebufferObjectAvailable() { return this.isFramebufferObjectAvailable; } @@ -281,8 +263,7 @@ public boolean isFramebufferObjectAvailable() * * @param available true to flag framebuffer objects as available, and false otherwise. */ - public void setFramebufferObjectAvailable(boolean available) - { + public void setFramebufferObjectAvailable(boolean available) { this.isFramebufferObjectAvailable = available; } @@ -292,8 +273,7 @@ public void setFramebufferObjectAvailable(boolean available) * * @return true if framebuffer objects are enabled, and false otherwise. */ - public boolean isFramebufferObjectEnabled() - { + public boolean isFramebufferObjectEnabled() { return this.isFramebufferObjectEnabled; } @@ -302,8 +282,7 @@ public boolean isFramebufferObjectEnabled() * * @param enable true to enable framebuffer objects, false to disable them. */ - public void setFramebufferObjectEnabled(boolean enable) - { + public void setFramebufferObjectEnabled(boolean enable) { this.isFramebufferObjectEnabled = enable; } @@ -312,8 +291,7 @@ public void setFramebufferObjectEnabled(boolean enable) * * @return true if vertex buffer objects are available, and false otherwise. */ - public boolean isVertexBufferObjectAvailable() - { + public boolean isVertexBufferObjectAvailable() { return this.isVertexBufferObjectAvailable; } @@ -322,8 +300,7 @@ public boolean isVertexBufferObjectAvailable() * * @param available true to flag vertex buffer objects as available, and false otherwise. */ - public void setVertexBufferObjectAvailable(boolean available) - { + public void setVertexBufferObjectAvailable(boolean available) { this.isVertexBufferObjectAvailable = available; } @@ -333,8 +310,7 @@ public void setVertexBufferObjectAvailable(boolean available) * * @return true if anisotropic vertex buffer objects are, and false otherwise. */ - public boolean isVertexBufferObjectEnabled() - { + public boolean isVertexBufferObjectEnabled() { return this.isVertexBufferObjectEnabled; } @@ -343,8 +319,7 @@ public boolean isVertexBufferObjectEnabled() * * @param enable true to enable vertex buffer objects, false to disable them. */ - public void setVertexBufferObjectEnabled(boolean enable) - { + public void setVertexBufferObjectEnabled(boolean enable) { this.isVertexBufferObjectEnabled = enable; } @@ -356,8 +331,7 @@ public void setVertexBufferObjectEnabled(boolean enable) * * @return the number of bitplanes in the current GL depth buffer. */ - public int getDepthBits() - { + public int getDepthBits() { return this.depthBits; } @@ -368,10 +342,8 @@ public int getDepthBits() * * @throws IllegalArgumentException if depthBits is less than one. */ - public void setDepthBits(int depthBits) - { - if (maxTextureSize < 1) - { + public void setDepthBits(int depthBits) { + if (maxTextureSize < 1) { String message = Logging.getMessage("generic.DepthBitsLessThanOne"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -387,20 +359,18 @@ public void setDepthBits(int depthBits) * * @return the maximum degree of texture anisotropy supported. */ - public double getMaxTextureAnisotropy() - { + public double getMaxTextureAnisotropy() { return this.maxTextureAnisotropy; } /** - * Sets the maximum degree of texture anisotropy supported by the current GL runtime. This value defines the - * maximum ratio of the an anisotropic texture filter. So 2.0 would define a maximum ratio of 2:1. A valueless than - * 2 denotes that the anisotropic texture filter is not supported by the current GL runtime. + * Sets the maximum degree of texture anisotropy supported by the current GL runtime. This value defines the maximum + * ratio of the an anisotropic texture filter. So 2.0 would define a maximum ratio of 2:1. A valueless than 2 + * denotes that the anisotropic texture filter is not supported by the current GL runtime. * * @param maxAnisotropy the maximum degree of texture anisotropy supported. */ - public void setMaxTextureAnisotropy(double maxAnisotropy) - { + public void setMaxTextureAnisotropy(double maxAnisotropy) { this.maxTextureAnisotropy = maxAnisotropy; } @@ -411,8 +381,7 @@ public void setMaxTextureAnisotropy(double maxAnisotropy) * * @return the maximum texture size supported, in texels. */ - public int getMaxTextureSize() - { + public int getMaxTextureSize() { return this.maxTextureSize; } @@ -425,10 +394,8 @@ public int getMaxTextureSize() * * @throws IllegalArgumentException if the size is less than one. */ - public void setMaxTextureSize(int maxTextureSize) - { - if (maxTextureSize < 1) - { + public void setMaxTextureSize(int maxTextureSize) { + if (maxTextureSize < 1) { String message = Logging.getMessage("generic.MaxTextureSizeLessThanOne"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -442,8 +409,7 @@ public void setMaxTextureSize(int maxTextureSize) * * @return the number of texture units supported. */ - public int getNumTextureUnits() - { + public int getNumTextureUnits() { return this.numTextureUnits; } @@ -454,10 +420,8 @@ public int getNumTextureUnits() * * @throws IllegalArgumentException if the number of texture units is less than one. */ - public void setNumTextureUnits(int numTextureUnits) - { - if (numTextureUnits < 1) - { + public void setNumTextureUnits(int numTextureUnits) { + if (numTextureUnits < 1) { String message = Logging.getMessage("generic.NumTextureUnitsLessThanOne"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/render/GeographicExtent.java b/src/gov/nasa/worldwind/render/GeographicExtent.java index ddb0a8197d..8469cceeb8 100644 --- a/src/gov/nasa/worldwind/render/GeographicExtent.java +++ b/src/gov/nasa/worldwind/render/GeographicExtent.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.geom.Sector; @@ -16,6 +15,7 @@ */ public interface GeographicExtent extends Renderable//, AVList { + /** * Returns the object's geographic extent. * diff --git a/src/gov/nasa/worldwind/render/GeographicSurfaceTileRenderer.java b/src/gov/nasa/worldwind/render/GeographicSurfaceTileRenderer.java index 99f8b04d76..3f4b07674d 100644 --- a/src/gov/nasa/worldwind/render/GeographicSurfaceTileRenderer.java +++ b/src/gov/nasa/worldwind/render/GeographicSurfaceTileRenderer.java @@ -14,15 +14,14 @@ * @author tag * @version $Id: GeographicSurfaceTileRenderer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeographicSurfaceTileRenderer extends SurfaceTileRenderer -{ +public class GeographicSurfaceTileRenderer extends SurfaceTileRenderer { + private double sgWidth; private double sgHeight; private double sgMinWE; private double sgMinSN; - protected void preComputeTextureTransform(DrawContext dc, SectorGeometry sg, Transform t) - { + protected void preComputeTextureTransform(DrawContext dc, SectorGeometry sg, Transform t) { Sector st = sg.getSector(); this.sgWidth = st.getDeltaLonRadians(); this.sgHeight = st.getDeltaLatRadians(); @@ -30,8 +29,7 @@ protected void preComputeTextureTransform(DrawContext dc, SectorGeometry sg, Tra this.sgMinSN = st.getMinLatitude().radians; } - protected void computeTextureTransform(DrawContext dc, SurfaceTile tile, Transform t) - { + protected void computeTextureTransform(DrawContext dc, SurfaceTile tile, Transform t) { Sector st = tile.getSector(); double tileWidth = st.getDeltaLonRadians(); double tileHeight = st.getDeltaLatRadians(); @@ -45,17 +43,18 @@ protected void computeTextureTransform(DrawContext dc, SurfaceTile tile, Transfo } protected Iterable getIntersectingTiles(DrawContext dc, SectorGeometry sg, - Iterable tiles) - { + Iterable tiles) { ArrayList intersectingTiles = null; - for (SurfaceTile tile : tiles) - { - if (!tile.getSector().intersectsInterior(sg.getSector())) + for (SurfaceTile tile : tiles) { + if (!tile.getSector().intersectsInterior(sg.getSector())) { continue; + } if (intersectingTiles == null) // lazy creation because most common case is no intersecting tiles + { intersectingTiles = new ArrayList(); + } intersectingTiles.add(tile); } diff --git a/src/gov/nasa/worldwind/render/GeographicText.java b/src/gov/nasa/worldwind/render/GeographicText.java index da708f0d93..66f48494cf 100644 --- a/src/gov/nasa/worldwind/render/GeographicText.java +++ b/src/gov/nasa/worldwind/render/GeographicText.java @@ -15,8 +15,8 @@ * @author dcollins * @version $Id: GeographicText.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface GeographicText -{ +public interface GeographicText { + /** * Indicates the text contained in this object. * diff --git a/src/gov/nasa/worldwind/render/GeographicTextRenderer.java b/src/gov/nasa/worldwind/render/GeographicTextRenderer.java index 2d12b11bfe..3f64c640a9 100644 --- a/src/gov/nasa/worldwind/render/GeographicTextRenderer.java +++ b/src/gov/nasa/worldwind/render/GeographicTextRenderer.java @@ -25,8 +25,8 @@ * @author dcollins * @version $Id: GeographicTextRenderer.java 2392 2014-10-20 20:02:44Z tgaskins $ */ -public class GeographicTextRenderer -{ +public class GeographicTextRenderer { + private TextRenderer lastTextRenderer = null; private final GLU glu = new GLUgl2(); @@ -45,8 +45,7 @@ public class GeographicTextRenderer private boolean hasJOGLv111Bug = false; - public GeographicTextRenderer() - { + public GeographicTextRenderer() { } /** @@ -56,8 +55,7 @@ public GeographicTextRenderer() * * @return true if overlapping text are culled. */ - public boolean isCullTextEnabled() - { + public boolean isCullTextEnabled() { return cullText; } @@ -68,8 +66,7 @@ public boolean isCullTextEnabled() * * @param cullText true if overlapping text should be culled. */ - public void setCullTextEnabled(boolean cullText) - { + public void setCullTextEnabled(boolean cullText) { this.cullText = cullText; } @@ -80,8 +77,7 @@ public void setCullTextEnabled(boolean cullText) * * @return the empty margin that surrounds a text item - in pixels. */ - public int getCullTextMargin() - { + public int getCullTextMargin() { return this.cullTextMargin; } @@ -92,8 +88,7 @@ public int getCullTextMargin() * * @param margin the empty margin that surrounds a text item - in pixels. */ - public void setCullTextMargin(int margin) - { + public void setCullTextMargin(int margin) { this.cullTextMargin = margin; } @@ -103,8 +98,7 @@ public void setCullTextMargin(int margin) * * @return the effect used for text rendering. */ - public String getEffect() - { + public String getEffect() { return this.effect; } @@ -114,10 +108,8 @@ public String getEffect() * * @param effect the effect to use for text rendering. */ - public void setEffect(String effect) - { - if (effect == null) - { + public void setEffect(String effect) { + if (effect == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -132,8 +124,7 @@ public void setEffect(String effect) * * @return the minimum scale that can be applied to a text item when it gets away from the eye. */ - public double getDistanceMinScale() - { + public double getDistanceMinScale() { return this.distanceMinScale; } @@ -144,8 +135,7 @@ public double getDistanceMinScale() * * @param scale the minimum scale that can be applied to a text item when it gets away from the eye. */ - public void setDistanceMinScale(double scale) - { + public void setDistanceMinScale(double scale) { this.distanceMinScale = scale; } @@ -155,8 +145,7 @@ public void setDistanceMinScale(double scale) * * @return the maximum scale that can be applied to a text item when it closer to the eye. */ - public double getDistanceMaxScale() - { + public double getDistanceMaxScale() { return this.distanceMaxScale; } @@ -167,8 +156,7 @@ public double getDistanceMaxScale() * * @param scale the maximum scale that can be applied to a text item when it closer to the eye. */ - public void setDistanceMaxScale(double scale) - { + public void setDistanceMaxScale(double scale) { this.distanceMaxScale = scale; } @@ -178,8 +166,7 @@ public void setDistanceMaxScale(double scale) * * @return the minimum opacity that can be applied to a text item when it gets away from the eye. */ - public double getDistanceMinOpacity() - { + public double getDistanceMinOpacity() { return this.distanceMinOpacity; } @@ -190,207 +177,207 @@ public double getDistanceMinOpacity() * * @param opacity the minimum opacity that can be applied to a text item when it gets away from the eye. */ - public void setDistanceMinOpacity(double opacity) - { + public void setDistanceMinOpacity(double opacity) { this.distanceMinOpacity = opacity; } - public void render(DrawContext dc, Iterable text) - { + public void render(DrawContext dc, Iterable text) { this.drawMany(dc, text); } - public void render(DrawContext dc, GeographicText text, Vec4 textPoint) - { - if (!isTextValid(text, false)) + public void render(DrawContext dc, GeographicText text, Vec4 textPoint) { + if (!isTextValid(text, false)) { return; + } this.drawOne(dc, text, textPoint); } - private void drawMany(DrawContext dc, Iterable textIterable) - { - if (dc == null) - { + private void drawMany(DrawContext dc, Iterable textIterable) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (textIterable == null) - { + if (textIterable == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (dc.getVisibleSector() == null) + if (dc.getVisibleSector() == null) { return; + } SectorGeometryList geos = dc.getSurfaceGeometry(); - if (geos == null) + if (geos == null) { return; + } Iterator iterator = textIterable.iterator(); - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return; + } Frustum frustumInModelCoords = dc.getView().getFrustumInModelCoordinates(); double horizon = dc.getView().getHorizonDistance(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { GeographicText text = iterator.next(); - if (!isTextValid(text, true)) + if (!isTextValid(text, true)) { continue; + } - if (!text.isVisible()) + if (!text.isVisible()) { continue; + } - if (dc.is2DGlobe()) - { - Sector limits = ((Globe2D)dc.getGlobe()).getProjection().getProjectionLimits(); - if (limits != null && !limits.contains(text.getPosition())) + if (dc.is2DGlobe()) { + Sector limits = ((Globe2D) dc.getGlobe()).getProjection().getProjectionLimits(); + if (limits != null && !limits.contains(text.getPosition())) { continue; + } } Angle lat = text.getPosition().getLatitude(); Angle lon = text.getPosition().getLongitude(); - if (!dc.getVisibleSector().contains(lat, lon)) + if (!dc.getVisibleSector().contains(lat, lon)) { continue; + } Vec4 textPoint = geos.getSurfacePoint(lat, lon, - text.getPosition().getElevation() * dc.getVerticalExaggeration()); - if (textPoint == null) + text.getPosition().getElevation() * dc.getVerticalExaggeration()); + if (textPoint == null) { continue; + } double eyeDistance = dc.getView().getEyePoint().distanceTo3(textPoint); - if (!dc.is2DGlobe() && eyeDistance > horizon) + if (!dc.is2DGlobe() && eyeDistance > horizon) { continue; + } - if (!frustumInModelCoords.contains(textPoint)) + if (!frustumInModelCoords.contains(textPoint)) { continue; + } dc.addOrderedRenderable(new OrderedText(text, textPoint, eyeDistance)); } } - private void drawOne(DrawContext dc, GeographicText text, Vec4 textPoint) - { - if (dc == null) - { + private void drawOne(DrawContext dc, GeographicText text, Vec4 textPoint) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (dc.getView() == null) - { + if (dc.getView() == null) { String msg = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (dc.getVisibleSector() == null) + if (dc.getVisibleSector() == null) { return; + } SectorGeometryList geos = dc.getSurfaceGeometry(); - if (geos == null) + if (geos == null) { return; + } - if (!text.isVisible()) + if (!text.isVisible()) { return; + } - if (textPoint == null) - { - if (text.getPosition() == null) + if (textPoint == null) { + if (text.getPosition() == null) { return; + } Angle lat = text.getPosition().getLatitude(); Angle lon = text.getPosition().getLongitude(); - if (!dc.getVisibleSector().contains(lat, lon)) + if (!dc.getVisibleSector().contains(lat, lon)) { return; + } textPoint = geos.getSurfacePoint(lat, lon, - text.getPosition().getElevation() * dc.getVerticalExaggeration()); - if (textPoint == null) + text.getPosition().getElevation() * dc.getVerticalExaggeration()); + if (textPoint == null) { return; + } } double horizon = dc.getView().getHorizonDistance(); double eyeDistance = dc.getView().getEyePoint().distanceTo3(textPoint); - if (!dc.is2DGlobe() && eyeDistance > horizon) + if (!dc.is2DGlobe() && eyeDistance > horizon) { return; + } - if (!dc.getView().getFrustumInModelCoordinates().contains(textPoint)) + if (!dc.getView().getFrustumInModelCoordinates().contains(textPoint)) { return; + } dc.addOrderedRenderable(new OrderedText(text, textPoint, eyeDistance)); } - protected static boolean isTextValid(GeographicText text, boolean checkPosition) - { - if (text == null || text.getText() == null) + protected static boolean isTextValid(GeographicText text, boolean checkPosition) { + if (text == null || text.getText() == null) { return false; + } //noinspection RedundantIfStatement - if (checkPosition && text.getPosition() == null) + if (checkPosition && text.getPosition() == null) { return false; + } return true; } - protected class OrderedText implements OrderedRenderable, Comparable - { + protected class OrderedText implements OrderedRenderable, Comparable { + GeographicText text; Vec4 point; double eyeDistance; - OrderedText(GeographicText text, Vec4 point, double eyeDistance) - { + OrderedText(GeographicText text, Vec4 point, double eyeDistance) { this.text = text; this.point = point; this.eyeDistance = eyeDistance; } // When overlapping text are culled we want to sort them front to back by priority. - public int compareTo(OrderedText t) - { - if (t.text.getPriority() - this.text.getPriority() == 0) - { + public int compareTo(OrderedText t) { + if (t.text.getPriority() - this.text.getPriority() == 0) { return (int) (this.eyeDistance - t.eyeDistance); - } - else + } else { return (int) (t.text.getPriority() - this.text.getPriority()); + } } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - private GeographicTextRenderer getRenderer() - { + private GeographicTextRenderer getRenderer() { return GeographicTextRenderer.this; } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { GeographicTextRenderer.this.beginRendering(dc); - try - { - if (cullText) - { + try { + if (cullText) { ArrayList textList = new ArrayList(); textList.add(this); // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - while (nextItem != null && nextItem instanceof OrderedText) - { + while (nextItem != null && nextItem instanceof OrderedText) { OrderedText ot = (OrderedText) nextItem; - if (ot.getRenderer() != GeographicTextRenderer.this) + if (ot.getRenderer() != GeographicTextRenderer.this) { break; + } textList.add(ot); dc.pollOrderedRenderables(); // take it off the queue @@ -400,40 +387,38 @@ public void render(DrawContext dc) Collections.sort(textList); // sort for rendering priority then front to back ArrayList textBounds = new ArrayList(); - for (OrderedText ot : textList) - { + for (OrderedText ot : textList) { double[] scaleAndOpacity = GeographicTextRenderer.this.computeDistanceScaleAndOpacity(dc, ot); Rectangle2D newBounds = GeographicTextRenderer.this.computeTextBounds(dc, ot, - scaleAndOpacity[0]); - if (newBounds == null) + scaleAndOpacity[0]); + if (newBounds == null) { continue; + } boolean overlap = false; newBounds = GeographicTextRenderer.this.computeExpandedBounds(newBounds, cullTextMargin); - for (Rectangle2D rect : textBounds) - { - if (rect.intersects(newBounds)) + for (Rectangle2D rect : textBounds) { + if (rect.intersects(newBounds)) { overlap = true; + } } - if (!overlap) - { + if (!overlap) { textBounds.add(newBounds); GeographicTextRenderer.this.drawText(dc, ot, scaleAndOpacity[0], scaleAndOpacity[1]); } } - } - else //just draw each label + } else //just draw each label { double[] scaleAndOpacity = GeographicTextRenderer.this.computeDistanceScaleAndOpacity(dc, this); GeographicTextRenderer.this.drawText(dc, this, scaleAndOpacity[0], scaleAndOpacity[1]); // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - while (nextItem != null && nextItem instanceof OrderedText) - { + while (nextItem != null && nextItem instanceof OrderedText) { OrderedText ot = (OrderedText) nextItem; - if (ot.getRenderer() != GeographicTextRenderer.this) + if (ot.getRenderer() != GeographicTextRenderer.this) { break; + } scaleAndOpacity = GeographicTextRenderer.this.computeDistanceScaleAndOpacity(dc, ot); GeographicTextRenderer.this.drawText(dc, ot, scaleAndOpacity[0], scaleAndOpacity[1]); @@ -441,49 +426,43 @@ public void render(DrawContext dc) nextItem = dc.peekOrderedRenderables(); } } - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionWhileRenderingText", e); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionWhileRenderingText", e); - } - finally - { + } finally { GeographicTextRenderer.this.endRendering(dc); } } - public void pick(DrawContext dc, java.awt.Point pickPoint) - { + public void pick(DrawContext dc, java.awt.Point pickPoint) { } } - protected Rectangle2D computeTextBounds(DrawContext dc, OrderedText uText, double scale) throws Exception - { + protected Rectangle2D computeTextBounds(DrawContext dc, OrderedText uText, double scale) throws Exception { GeographicText geographicText = uText.text; final CharSequence charSequence = geographicText.getText(); - if (charSequence == null) + if (charSequence == null) { return null; + } final Vec4 screenPoint = dc.getView().project(uText.point); - if (screenPoint == null) + if (screenPoint == null) { return null; + } Font font = geographicText.getFont(); - if (font == null) + if (font == null) { font = DEFAULT_FONT; + } - try - { + try { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); - if (textRenderer != this.lastTextRenderer) - { - if (this.lastTextRenderer != null) + if (textRenderer != this.lastTextRenderer) { + if (this.lastTextRenderer != null) { this.lastTextRenderer.end3DRendering(); + } textRenderer.begin3DRendering(); this.lastTextRenderer = textRenderer; } @@ -494,67 +473,63 @@ protected Rectangle2D computeTextBounds(DrawContext dc, OrderedText uText, doubl bounds.setRect(x, screenPoint.y, textBound.getWidth(), textBound.getHeight()); return computeScaledBounds(bounds, scale); - } - catch (Exception e) - { + } catch (Exception e) { handleTextRendererExceptions(e); return null; } } - protected Rectangle2D computeScaledBounds(Rectangle2D bounds, double scale) - { - if (scale == 1) + protected Rectangle2D computeScaledBounds(Rectangle2D bounds, double scale) { + if (scale == 1) { return bounds; + } // Scale rectangle from bottom center double halfWidth = bounds.getWidth() / 2; bounds.setRect(bounds.getX() + halfWidth - halfWidth * scale, bounds.getY(), - bounds.getWidth() * scale, bounds.getHeight() * scale); + bounds.getWidth() * scale, bounds.getHeight() * scale); return bounds; } - protected Rectangle2D computeExpandedBounds(Rectangle2D bounds, int margin) - { - if (margin == 0) + protected Rectangle2D computeExpandedBounds(Rectangle2D bounds, int margin) { + if (margin == 0) { return bounds; + } // Add margin around rectangle bounds.setRect(bounds.getX() - margin, bounds.getY() - margin, - bounds.getWidth() + margin * 2, bounds.getHeight() + margin * 2); + bounds.getWidth() + margin * 2, bounds.getHeight() + margin * 2); return bounds; } @SuppressWarnings({"UnusedDeclaration"}) - protected double[] computeDistanceScaleAndOpacity(DrawContext dc, OrderedText ot) - { - if (!this.isDistanceScaling) - return new double[] {1, 1}; + protected double[] computeDistanceScaleAndOpacity(DrawContext dc, OrderedText ot) { + if (!this.isDistanceScaling) { + return new double[]{1, 1}; + } // Determine scale and opacity factors based on distance from eye vs the distance to the look at point. double lookAtDistance = this.lookAtDistance; double eyeDistance = ot.getDistanceFromEye(); double distanceFactor = Math.sqrt(lookAtDistance / eyeDistance); double scale = WWMath.clamp(distanceFactor, - this.getDistanceMinScale(), this.getDistanceMaxScale()); + this.getDistanceMinScale(), this.getDistanceMaxScale()); double opacity = WWMath.clamp(distanceFactor, - this.getDistanceMinOpacity(), 1); + this.getDistanceMinOpacity(), 1); - return new double[] {scale, opacity}; + return new double[]{scale, opacity}; } - protected double computeLookAtDistance(DrawContext dc) - { + protected double computeLookAtDistance(DrawContext dc) { View view = dc.getView(); // Get point in the middle of the screen // TODO: Get a point on the surface rather then the geoid Position groundPos = view.computePositionFromScreenPoint( - view.getViewport().getCenterX(), view.getViewport().getCenterY()); + view.getViewport().getCenterX(), view.getViewport().getCenterY()); // Update look at distance if center point found - if (groundPos != null) - { + if (groundPos != null) { // Compute distance from eye to the position in the middle of the screen this.lookAtDistance = view.getEyePoint().distanceTo3(dc.getGlobe().computePointFromPosition(groundPos)); } @@ -562,15 +537,14 @@ protected double computeLookAtDistance(DrawContext dc) return this.lookAtDistance; } - protected void beginRendering(DrawContext dc) - { + protected void beginRendering(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - int attribBits = - GL2.GL_ENABLE_BIT // for enable/disable changes + int attribBits + = GL2.GL_ENABLE_BIT // for enable/disable changes | GL2.GL_COLOR_BUFFER_BIT // for alpha test func and ref, and blend - | GL2.GL_CURRENT_BIT // for current color + | GL2.GL_CURRENT_BIT // for current color | GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth func, and depth mask - | GL2.GL_TRANSFORM_BIT // for modelview and perspective + | GL2.GL_TRANSFORM_BIT // for modelview and perspective | GL2.GL_VIEWPORT_BIT; // for depth range gl.glPushAttrib(attribBits); @@ -600,14 +574,12 @@ protected void beginRendering(DrawContext dc) // Cache distance scaling values this.isDistanceScaling = this.getDistanceMinScale() != 1 || this.getDistanceMaxScale() != 1 - || this.distanceMinOpacity != 1; + || this.distanceMinOpacity != 1; this.computeLookAtDistance(dc); } - protected void endRendering(DrawContext dc) - { - if (this.lastTextRenderer != null) - { + protected void endRendering(DrawContext dc) { + if (this.lastTextRenderer != null) { this.lastTextRenderer.end3DRendering(); this.lastTextRenderer = null; } @@ -624,10 +596,8 @@ protected void endRendering(DrawContext dc) gl.glPopAttrib(); } - protected Vec4 drawText(DrawContext dc, OrderedText uText, double scale, double opacity) throws Exception - { - if (uText.point == null) - { + protected Vec4 drawText(DrawContext dc, OrderedText uText, double scale, double opacity) throws Exception { + if (uText.point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().fine(msg); return null; @@ -637,24 +607,26 @@ protected Vec4 drawText(DrawContext dc, OrderedText uText, double scale, double GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. final CharSequence charSequence = geographicText.getText(); - if (charSequence == null) + if (charSequence == null) { return null; + } final Vec4 screenPoint = dc.getView().project(uText.point); - if (screenPoint == null) + if (screenPoint == null) { return null; + } Font font = geographicText.getFont(); - if (font == null) + if (font == null) { font = DEFAULT_FONT; + } - try - { + try { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); - if (textRenderer != this.lastTextRenderer) - { - if (this.lastTextRenderer != null) + if (textRenderer != this.lastTextRenderer) { + if (this.lastTextRenderer != null) { this.lastTextRenderer.end3DRendering(); + } textRenderer.begin3DRendering(); this.lastTextRenderer = textRenderer; } @@ -662,34 +634,29 @@ protected Vec4 drawText(DrawContext dc, OrderedText uText, double scale, double this.setDepthFunc(dc, uText, screenPoint); Rectangle2D textBounds = textRenderer.getBounds( - charSequence);//note:may already be calculated during culling + charSequence);//note:may already be calculated during culling textBounds = this.computeScaledBounds(textBounds, scale); Point.Float drawPoint = computeDrawPoint(dc, textBounds, screenPoint); - if (drawPoint != null) - { - if (scale != 1d) - { + if (drawPoint != null) { + if (scale != 1d) { gl.glScaled(scale, scale, 1d); drawPoint.setLocation(drawPoint.x / (float) scale, drawPoint.y / (float) scale); } Color color = geographicText.getColor(); - if (color == null) + if (color == null) { color = DEFAULT_COLOR; + } color = this.applyOpacity(color, opacity); Color background = geographicText.getBackgroundColor(); - if (background != null) - { + if (background != null) { background = this.applyOpacity(background, opacity); textRenderer.setColor(background); - if (this.effect.equals(AVKey.TEXT_EFFECT_SHADOW)) - { + if (this.effect.equals(AVKey.TEXT_EFFECT_SHADOW)) { textRenderer.draw3D(charSequence, drawPoint.x + 1, drawPoint.y - 1, 0, 1); - } - else if (this.effect.equals(AVKey.TEXT_EFFECT_OUTLINE)) - { + } else if (this.effect.equals(AVKey.TEXT_EFFECT_OUTLINE)) { textRenderer.draw3D(charSequence, drawPoint.x + 1, drawPoint.y - 1, 0, 1); textRenderer.draw3D(charSequence, drawPoint.x + 1, drawPoint.y + 1, 0, 1); textRenderer.draw3D(charSequence, drawPoint.x - 1, drawPoint.y - 1, 0, 1); @@ -701,41 +668,35 @@ else if (this.effect.equals(AVKey.TEXT_EFFECT_OUTLINE)) textRenderer.draw3D(charSequence, drawPoint.x, drawPoint.y, 0, 1); textRenderer.flush(); - if (scale != 1d) + if (scale != 1d) { gl.glLoadIdentity(); + } } - } - catch (Exception e) - { + } catch (Exception e) { handleTextRendererExceptions(e); } return screenPoint; } - protected Color applyOpacity(Color color, double opacity) - { - if (opacity >= 1) + protected Color applyOpacity(Color color, double opacity) { + if (opacity >= 1) { return color; + } float[] compArray = color.getRGBComponents(null); return new Color(compArray[0], compArray[1], compArray[2], compArray[3] * (float) opacity); } - private void handleTextRendererExceptions(Exception e) throws Exception - { - if (e instanceof IOException) - { - if (!this.hasJOGLv111Bug) - { + private void handleTextRendererExceptions(Exception e) throws Exception { + if (e instanceof IOException) { + if (!this.hasJOGLv111Bug) { // This is likely a known JOGL 1.1.1 bug - see AMZN-287 or 343 // Log once and then ignore. Logging.logger().log(java.util.logging.Level.SEVERE, "generic.ExceptionWhileRenderingText", e); this.hasJOGLv111Bug = true; } - } - else - { + } else { throw e; } } @@ -744,21 +705,19 @@ private void handleTextRendererExceptions(Exception e) throws Exception * Computes the final draw point for the given rectangle lower left corner and target screen point. If the returned * point is null the text will not be drawn. * - * @param dc the current {@link DrawContext} - * @param rect the text rectangle to draw. + * @param dc the current {@link DrawContext} + * @param rect the text rectangle to draw. * @param screenPoint the projected screen point the text relates to. * * @return the final draw point for the given rectangle lower left corner or null. */ @SuppressWarnings({"UnusedDeclaration"}) - protected Point.Float computeDrawPoint(DrawContext dc, Rectangle2D rect, Vec4 screenPoint) - { + protected Point.Float computeDrawPoint(DrawContext dc, Rectangle2D rect, Vec4 screenPoint) { return new Point.Float((float) (screenPoint.x - rect.getWidth() / 2d), (float) (screenPoint.y)); } @SuppressWarnings({"UnusedDeclaration"}) - protected void setDepthFunc(DrawContext dc, OrderedText uText, Vec4 screenPoint) - { + protected void setDepthFunc(DrawContext dc, OrderedText uText, Vec4 screenPoint) { GL gl = dc.getGL(); //if (uText.text.isAlwaysOnTop()) @@ -766,29 +725,24 @@ protected void setDepthFunc(DrawContext dc, OrderedText uText, Vec4 screenPoint) // gl.glDepthFunc(GL.GL_ALWAYS); // return; //} - Position eyePos = dc.getView().getEyePosition(); - if (eyePos == null) - { + if (eyePos == null) { gl.glDepthFunc(GL.GL_ALWAYS); return; } double altitude = eyePos.getElevation(); - if (altitude < (dc.getGlobe().getMaxElevation() * dc.getVerticalExaggeration())) - { + if (altitude < (dc.getGlobe().getMaxElevation() * dc.getVerticalExaggeration())) { double depth = screenPoint.z - (8d * 0.00048875809d); depth = depth < 0d ? 0d : (depth > 1d ? 1d : depth); gl.glDepthFunc(GL.GL_LESS); gl.glDepthRange(depth, depth); - } - //else if (screenPoint.z >= 1d) + } //else if (screenPoint.z >= 1d) //{ // gl.glDepthFunc(GL.GL_EQUAL); // gl.glDepthRange(1d, 1d); //} - else - { + else { gl.glDepthFunc(GL.GL_ALWAYS); } } diff --git a/src/gov/nasa/worldwind/render/GlobeAnnotation.java b/src/gov/nasa/worldwind/render/GlobeAnnotation.java index 32b3baab96..080212e099 100644 --- a/src/gov/nasa/worldwind/render/GlobeAnnotation.java +++ b/src/gov/nasa/worldwind/render/GlobeAnnotation.java @@ -21,8 +21,8 @@ * @see AbstractAnnotation * @see AnnotationAttributes */ -public class GlobeAnnotation extends AbstractAnnotation implements Locatable, Movable, Draggable -{ +public class GlobeAnnotation extends AbstractAnnotation implements Locatable, Movable, Draggable { + protected Position position; protected boolean dragEnabled = true; protected DraggableSupport draggableSupport = null; @@ -33,38 +33,35 @@ public class GlobeAnnotation extends AbstractAnnotation implements Locatable, Mo /** * Creates a GlobeAnnotation with the given text, at the given globe Position. * - * @param text the annotation text. + * @param text the annotation text. * @param position the annotation Position. */ - public GlobeAnnotation(String text, Position position) - { + public GlobeAnnotation(String text, Position position) { this.init(text, position, null, null); } /** - * Creates a GlobeAnnotation with the given text, at the given globe Position. Specify - * the Font to be used. + * Creates a GlobeAnnotation with the given text, at the given globe Position. Specify the + * Font to be used. * - * @param text the annotation text. + * @param text the annotation text. * @param position the annotation Position. - * @param font the Font to use. + * @param font the Font to use. */ - public GlobeAnnotation(String text, Position position, Font font) - { + public GlobeAnnotation(String text, Position position, Font font) { this.init(text, position, font, null); } /** - * Creates a GlobeAnnotation with the given text, at the given globe Position. Specify - * the Font and text Color to be used. + * Creates a GlobeAnnotation with the given text, at the given globe Position. Specify the + * Font and text Color to be used. * - * @param text the annotation text. - * @param position the annotation Position. - * @param font the Font to use. + * @param text the annotation text. + * @param position the annotation Position. + * @param font the Font to use. * @param textColor the text Color. */ - public GlobeAnnotation(String text, Position position, Font font, Color textColor) - { + public GlobeAnnotation(String text, Position position, Font font, Color textColor) { this.init(text, position, font, textColor); } @@ -72,28 +69,24 @@ public GlobeAnnotation(String text, Position position, Font font, Color textColo * Creates a GlobeAnnotation with the given text, at the given globe Position. Specify the * default {@link AnnotationAttributes} set. * - * @param text the annotation text. + * @param text the annotation text. * @param position the annotation Position. * @param defaults the default {@link AnnotationAttributes} set. */ - public GlobeAnnotation(String text, Position position, AnnotationAttributes defaults) - { - if (text == null) - { + public GlobeAnnotation(String text, Position position, AnnotationAttributes defaults) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (defaults == null) - { + if (defaults == null) { String message = Logging.getMessage("nullValue.AnnotationAttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -104,17 +97,14 @@ public GlobeAnnotation(String text, Position position, AnnotationAttributes defa this.getAttributes().setDefaults(defaults); } - private void init(String text, Position position, Font font, Color textColor) - { - if (text == null) - { + private void init(String text, Position position, Font font, Color textColor) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -126,13 +116,11 @@ private void init(String text, Position position, Font font, Color textColor) this.getAttributes().setTextColor(textColor); } - public Position getPosition() - { + public Position getPosition() { return this.position; } - public void setPosition(Position position) - { + public void setPosition(Position position) { this.position = position; } @@ -150,8 +138,7 @@ public void setPosition(Position position) * * @see #setAltitudeMode(Integer) */ - public Integer getAltitudeMode() - { + public Integer getAltitudeMode() { return altitudeMode; } @@ -159,53 +146,47 @@ public Integer getAltitudeMode() * Set the annotation's altitude mode. * * @param altitudeMode The altitude mode, one of {@link WorldWind#CLAMP_TO_GROUND}, {@link - * WorldWind#RELATIVE_TO_GROUND}, or {@link WorldWind#ABSOLUTE}. {@code null} indicates that the - * legacy altitude mode should be used. See {@link #getAltitudeMode()} for details on this - * mode. + * WorldWind#RELATIVE_TO_GROUND}, or {@link WorldWind#ABSOLUTE}. {@code null} indicates that the legacy altitude + * mode should be used. See {@link #getAltitudeMode()} for details on this mode. * * @see #getAltitudeMode() */ - public void setAltitudeMode(Integer altitudeMode) - { + public void setAltitudeMode(Integer altitudeMode) { this.altitudeMode = altitudeMode; } /** * Returns the real world height of the annotation frame in meter. If this dimension is greater then zero, the * annotation will be scaled so as to maintain this fixed dimension, which makes it appear as part of the - * surrounding terrain. This overrides min and max distance scaling - however min distance opacity is still accounted - * for. + * surrounding terrain. This overrides min and max distance scaling - however min distance opacity is still + * accounted for. *

          * If this dimension is zero, the annotation always maintains the same apparent size with possible scaling relative * to the viewport center point if min and max distance scale factors are not one. * * @return the real world height of the annotation frame in meter. */ - public double getHeightInMeter() - { + public double getHeightInMeter() { return this.heightInMeter; } /** * Set the real world height of the annotation frame in meter. If this dimension is greater then zero, the * annotation will be scaled so as to maintain this fixed dimension, which makes it appear as part of the - * surrounding terrain. This overrides min and max distance scaling - however min distance opacity is still accounted - * for. + * surrounding terrain. This overrides min and max distance scaling - however min distance opacity is still + * accounted for. *

          * If this dimension is zero, the annotation always maintains the same apparent size with possible scaling relative * to the viewport center point if min and max distance scale factors are not one. * * @param meters the real world height of the annotation frame in meter. */ - public void setHeightInMeter(double meters) - { + public void setHeightInMeter(double meters) { this.heightInMeter = meters; } - public void move(Position position) - { - if (position == null) - { + public void move(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -214,10 +195,8 @@ public void move(Position position) this.position = this.position.add(position); } - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -227,39 +206,30 @@ public void moveTo(Position position) } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) - { + if (this.draggableSupport == null) { // The following addresses the special case described in {@link GlobeAnnotation#getAltitudeMode} - if (this.getAltitudeMode() == null) - { - if (this.position.getElevation() > dragContext.getGlobe().getMaxElevation()) - { + if (this.getAltitudeMode() == null) { + if (this.position.getElevation() > dragContext.getGlobe().getMaxElevation()) { this.draggableSupport = new DraggableSupport(this, WorldWind.ABSOLUTE); - } - else - { + } else { this.draggableSupport = new DraggableSupport(this, WorldWind.RELATIVE_TO_GROUND); } - } - else - { + } else { this.draggableSupport = new DraggableSupport(this, this.getAltitudeMode()); } } @@ -267,29 +237,27 @@ public void drag(DragContext dragContext) this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragScreenSizeConstant(dragContext); } - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.position; } //**************************************************************// //******************** Rendering *****************************// //**************************************************************// - - protected Rectangle computeBounds(DrawContext dc) - { + protected Rectangle computeBounds(DrawContext dc) { Vec4 point = this.getAnnotationDrawPoint(dc); - if (point == null) + if (point == null) { return null; + } Vec4 screenPoint = dc.getView().project(point); - if (screenPoint == null) + if (screenPoint == null) { return null; + } java.awt.Dimension size = this.getPreferredSize(dc); double[] scaleAndOpacity = computeDistanceScaleAndOpacity(dc, point, size); @@ -309,21 +277,24 @@ protected Rectangle computeBounds(DrawContext dc) return this.computeBoundingRectangle(frameRect, (int) screenPoint.x, (int) screenPoint.y); } - protected void doRenderNow(DrawContext dc) - { - if (dc.isPickingMode() && this.getPickSupport() == null) + protected void doRenderNow(DrawContext dc) { + if (dc.isPickingMode() && this.getPickSupport() == null) { return; + } Vec4 point = this.getAnnotationDrawPoint(dc); - if (point == null) + if (point == null) { return; + } - if (dc.getView().getFrustumInModelCoordinates().getNear().distanceTo(point) < 0) + if (dc.getView().getFrustumInModelCoordinates().getNear().distanceTo(point) < 0) { return; + } Vec4 screenPoint = dc.getView().project(point); - if (screenPoint == null) + if (screenPoint == null) { return; + } java.awt.Dimension size = this.getPreferredSize(dc); Position pos = dc.getGlobe().computePositionFromPoint(point); @@ -333,29 +304,24 @@ protected void doRenderNow(DrawContext dc) this.setDepthFunc(dc, screenPoint); this.drawTopLevelAnnotation(dc, (int) screenPoint.x, (int) screenPoint.y, size.width, size.height, - scaleAndOpacity[0], scaleAndOpacity[1], pos); + scaleAndOpacity[0], scaleAndOpacity[1], pos); } - protected double[] computeDistanceScaleAndOpacity(DrawContext dc, Vec4 point, Dimension size) - { + protected double[] computeDistanceScaleAndOpacity(DrawContext dc, Vec4 point, Dimension size) { double scale = 1, opacity = 1; - if (this.heightInMeter <= 0) - { + if (this.heightInMeter <= 0) { // Determine scale and opacity factors based on distance from eye vs the distance to the look at point. Double lookAtDistance = this.computeLookAtDistance(dc); - if (lookAtDistance != null) - { + if (lookAtDistance != null) { double eyeDistance = dc.getView().getEyePoint().distanceTo3(point); double distanceFactor = Math.sqrt(lookAtDistance / eyeDistance); scale = WWMath.clamp(distanceFactor, - this.attributes.getDistanceMinScale(), this.attributes.getDistanceMaxScale()); + this.attributes.getDistanceMinScale(), this.attributes.getDistanceMaxScale()); opacity = WWMath.clamp(distanceFactor, - this.attributes.getDistanceMinOpacity(), 1); + this.attributes.getDistanceMinOpacity(), 1); } - } - else - { + } else { // Determine scale and opacity so as to maintain real world dimension double distance = dc.getView().getEyePoint().distanceTo3(point); double pixelSize = dc.getView().computePixelSizeAtDistance(distance); @@ -364,63 +330,54 @@ protected double[] computeDistanceScaleAndOpacity(DrawContext dc, Vec4 point, Di opacity = WWMath.clamp(scale, this.attributes.getDistanceMinOpacity(), 1); } - return new double[] {scale, opacity}; + return new double[]{scale, opacity}; } - protected Double computeLookAtDistance(DrawContext dc) - { + protected Double computeLookAtDistance(DrawContext dc) { // TODO: Remove this method once the new mechanism for scaling and opacity is in place. View view = dc.getView(); // Get point in the middle of the screen Position groundPos = view.computePositionFromScreenPoint( - view.getViewport().getCenterX(), view.getViewport().getCenterY()); + view.getViewport().getCenterX(), view.getViewport().getCenterY()); - if (groundPos == null) - { + if (groundPos == null) { // Decrease the point's y coordinate until it intersects the globe. Rectangle vp = view.getViewport(); double y = view.getViewport().getCenterY() + 1; - while (groundPos == null && y < vp.height - 1) - { + while (groundPos == null && y < vp.height - 1) { groundPos = view.computePositionFromScreenPoint(view.getViewport().getCenterX(), y++); } } // Update look at distance if center point found - if (groundPos != null) - // Compute distance from eye to the position in the middle of the screen + if (groundPos != null) // Compute distance from eye to the position in the middle of the screen + { return view.getEyePoint().distanceTo3(dc.getGlobe().computePointFromPosition(groundPos)); - else + } else { return null; + } } - protected void setDepthFunc(DrawContext dc, Vec4 screenPoint) - { + protected void setDepthFunc(DrawContext dc, Vec4 screenPoint) { GL gl = dc.getGL(); Position eyePos = dc.getView().getEyePosition(); - if (eyePos == null) - { + if (eyePos == null) { gl.glDepthFunc(GL.GL_ALWAYS); return; } double altitude = eyePos.getElevation(); - if (altitude < (dc.getGlobe().getMaxElevation() * dc.getVerticalExaggeration())) - { + if (altitude < (dc.getGlobe().getMaxElevation() * dc.getVerticalExaggeration())) { double depth = screenPoint.z - (8d * 0.00048875809d); depth = depth < 0d ? 0d : (depth > 1d ? 1d : depth); gl.glDepthFunc(GL.GL_LESS); gl.glDepthRange(depth, depth); - } - else if (screenPoint.z >= 1d) - { + } else if (screenPoint.z >= 1d) { gl.glDepthFunc(GL.GL_EQUAL); gl.glDepthRange(1d, 1d); - } - else - { + } else { gl.glDepthFunc(GL.GL_ALWAYS); } } @@ -436,30 +393,21 @@ else if (screenPoint.z >= 1d) * * @see #getAltitudeMode() */ - public Vec4 getAnnotationDrawPoint(DrawContext dc) - { + public Vec4 getAnnotationDrawPoint(DrawContext dc) { Vec4 drawPoint; Position pos = this.getPosition(); Integer altitudeMode = this.getAltitudeMode(); - if (dc.is2DGlobe()) - { + if (dc.is2DGlobe()) { drawPoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), 0); - } - else if (altitudeMode == null) - { + } else if (altitudeMode == null) { drawPoint = getAnnotationDrawPointLegacy(dc); - } - else if (altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + } else if (altitudeMode == WorldWind.CLAMP_TO_GROUND) { drawPoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), 0); - } - else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) { drawPoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), pos.getAltitude()); - } - else // ABSOLUTE + } else // ABSOLUTE { double height = pos.getElevation() * dc.getVerticalExaggeration(); drawPoint = dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), height); @@ -478,19 +426,20 @@ else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) * * @see #getAltitudeMode() */ - protected Vec4 getAnnotationDrawPointLegacy(DrawContext dc) - { + protected Vec4 getAnnotationDrawPointLegacy(DrawContext dc) { Vec4 drawPoint = null; Position pos = this.getPosition(); - if (pos.getElevation() < dc.getGlobe().getMaxElevation()) + if (pos.getElevation() < dc.getGlobe().getMaxElevation()) { drawPoint = dc.getSurfaceGeometry().getSurfacePoint(pos.getLatitude(), pos.getLongitude(), - pos.getElevation() * dc.getVerticalExaggeration()); + pos.getElevation() * dc.getVerticalExaggeration()); + } - if (drawPoint == null) + if (drawPoint == null) { drawPoint = dc.getGlobe().computePointFromPosition( - dc.getVerticalExaggeration() == 1 ? pos + dc.getVerticalExaggeration() == 1 ? pos : new Position(pos, pos.getElevation() * dc.getVerticalExaggeration())); + } return drawPoint; } @@ -498,26 +447,20 @@ protected Vec4 getAnnotationDrawPointLegacy(DrawContext dc) //**************************************************************// //******************** Restorable State **********************// //**************************************************************// - /** * Returns an XML state document String describing the public attributes of this GlobeAnnotation. * * @return XML state document string describing this GlobeAnnotation. */ - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport restorableSupport = null; // Try to parse the superclass' xml state document, if it defined one. String superStateInXml = super.getRestorableState(); - if (superStateInXml != null) - { - try - { + if (superStateInXml != null) { + try { restorableSupport = RestorableSupport.parse(superStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by the superclass failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", superStateInXml); Logging.logger().severe(message); @@ -525,27 +468,27 @@ public String getRestorableState() } // Create our own state document from scratch. - if (restorableSupport == null) + if (restorableSupport == null) { restorableSupport = RestorableSupport.newRestorableSupport(); + } // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (restorableSupport == null) + if (restorableSupport == null) { return null; + } // Save the position property only if all parts (latitude, longitude, and elevation) can be saved. // We will not save a partial position (for example, just the elevation). if (this.position != null - && this.position.getLatitude() != null - && this.position.getLongitude() != null) - { + && this.position.getLatitude() != null + && this.position.getLongitude() != null) { RestorableSupport.StateObject positionStateObj = restorableSupport.addStateObject("position"); - if (positionStateObj != null) - { + if (positionStateObj != null) { restorableSupport.addStateValueAsDouble(positionStateObj, "latitude", - this.position.getLatitude().degrees); + this.position.getLatitude().degrees); restorableSupport.addStateValueAsDouble(positionStateObj, "longitude", - this.position.getLongitude().degrees); + this.position.getLongitude().degrees); restorableSupport.addStateValueAsDouble(positionStateObj, "elevation", - this.position.getElevation()); + this.position.getElevation()); } } @@ -561,34 +504,26 @@ public String getRestorableState() * @param stateInXml an XML document String describing a GlobeAnnotation. * * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not a well - * formed XML document String. + * formed XML document String. */ - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Allow the superclass to restore it's state. - try - { + try { super.restoreState(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Superclass will log the exception. } RestorableSupport restorableSupport; - try - { + try { restorableSupport = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -598,13 +533,13 @@ public void restoreState(String stateInXml) // Restore the position property only if all parts are available. // We will not restore a partial position (for example, just the latitude). RestorableSupport.StateObject positionStateObj = restorableSupport.getStateObject("position"); - if (positionStateObj != null) - { + if (positionStateObj != null) { Double latitudeState = restorableSupport.getStateValueAsDouble(positionStateObj, "latitude"); Double longitudeState = restorableSupport.getStateValueAsDouble(positionStateObj, "longitude"); Double elevationState = restorableSupport.getStateValueAsDouble(positionStateObj, "elevation"); - if (latitudeState != null && elevationState != null) + if (latitudeState != null && elevationState != null) { setPosition(Position.fromDegrees(latitudeState, longitudeState, elevationState)); + } } } } diff --git a/src/gov/nasa/worldwind/render/GlobeAnnotationBalloon.java b/src/gov/nasa/worldwind/render/GlobeAnnotationBalloon.java index acf2a861f7..4aa1309093 100644 --- a/src/gov/nasa/worldwind/render/GlobeAnnotationBalloon.java +++ b/src/gov/nasa/worldwind/render/GlobeAnnotationBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.geom.Position; @@ -15,26 +14,26 @@ * @author pabercrombie * @version $Id: GlobeAnnotationBalloon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GlobeAnnotationBalloon extends AbstractAnnotationBalloon implements GlobeBalloon -{ +public class GlobeAnnotationBalloon extends AbstractAnnotationBalloon implements GlobeBalloon { + protected Position position; protected int altitudeMode; - /** Annotation used to render the balloon. */ + /** + * Annotation used to render the balloon. + */ protected GlobeAnnotation annotation; /** * Create the balloon. * - * @param text Text to display in the balloon. May not be null. + * @param text Text to display in the balloon. May not be null. * @param position The balloon's initial position. May not be null. */ - public GlobeAnnotationBalloon(String text, Position position) - { + public GlobeAnnotationBalloon(String text, Position position) { super(text); - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -45,9 +44,10 @@ public GlobeAnnotationBalloon(String text, Position position) this.annotation = this.createAnnotation(); } - /** {@inheritDoc} */ - protected GlobeAnnotation createAnnotation() - { + /** + * {@inheritDoc} + */ + protected GlobeAnnotation createAnnotation() { GlobeAnnotation annotation = new GlobeAnnotation(this.getDecodedText(), this.position); // Don't make the balloon bigger when it is highlighted, the text looks blurry when it is scaled up. @@ -56,25 +56,27 @@ protected GlobeAnnotation createAnnotation() return annotation; } - /** {@inheritDoc} */ - protected GlobeAnnotation getAnnotation() - { + /** + * {@inheritDoc} + */ + protected GlobeAnnotation getAnnotation() { return this.annotation; } - /** {@inheritDoc} */ - protected void computePosition(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected void computePosition(DrawContext dc) { GlobeAnnotation annotation = this.getAnnotation(); annotation.setPosition(this.getPosition()); annotation.setAltitudeMode(this.getAltitudeMode()); } - /** {@inheritDoc} */ - public void setPosition(Position position) - { - if (position == null) - { + /** + * {@inheritDoc} + */ + public void setPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -83,21 +85,24 @@ public void setPosition(Position position) this.position = position; } - /** {@inheritDoc} */ - public Position getPosition() - { + /** + * {@inheritDoc} + */ + public Position getPosition() { return this.position; } - /** {@inheritDoc} */ - public int getAltitudeMode() - { + /** + * {@inheritDoc} + */ + public int getAltitudeMode() { return altitudeMode; } - /** {@inheritDoc} */ - public void setAltitudeMode(int altitudeMode) - { + /** + * {@inheritDoc} + */ + public void setAltitudeMode(int altitudeMode) { this.altitudeMode = altitudeMode; } } diff --git a/src/gov/nasa/worldwind/render/GlobeBalloon.java b/src/gov/nasa/worldwind/render/GlobeBalloon.java index bcb5e86aa7..816c517c6b 100644 --- a/src/gov/nasa/worldwind/render/GlobeBalloon.java +++ b/src/gov/nasa/worldwind/render/GlobeBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.geom.Position; @@ -14,8 +13,8 @@ * @author pabercrombie * @version $Id: GlobeBalloon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface GlobeBalloon extends Balloon -{ +public interface GlobeBalloon extends Balloon { + /** * Get the position of the balloon. * @@ -41,7 +40,8 @@ public interface GlobeBalloon extends Balloon * Specifies the balloon's altitude mode. Recognized modes are:

          • @link WorldWind#CLAMP_TO_GROUND} -- * the balloon is placed on the terrain at the latitude and longitude of its position.
          • @link * WorldWind#RELATIVE_TO_GROUND} -- the balloon is placed above the terrain at the latitude and longitude of its - * position and the distance specified by its elevation.
          • {@link gov.nasa.worldwind.WorldWind#ABSOLUTE} + * position and the distance specified by its elevation.
          • + *
          • {@link gov.nasa.worldwind.WorldWind#ABSOLUTE} * -- the balloon is placed at its specified position.
          * * @param altitudeMode the altitude mode diff --git a/src/gov/nasa/worldwind/render/GlobeBrowserBalloon.java b/src/gov/nasa/worldwind/render/GlobeBrowserBalloon.java index 5b3c0161a0..bd8a34748b 100644 --- a/src/gov/nasa/worldwind/render/GlobeBrowserBalloon.java +++ b/src/gov/nasa/worldwind/render/GlobeBrowserBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.*; @@ -22,11 +21,13 @@ * @version $Id: GlobeBrowserBalloon.java 2272 2014-08-25 23:24:45Z tgaskins $ * @see gov.nasa.worldwind.render.AbstractBrowserBalloon */ -public class GlobeBrowserBalloon extends AbstractBrowserBalloon implements GlobeBalloon -{ - protected class OrderedGlobeBrowserBalloon extends OrderedBrowserBalloon - { - /** The model-coordinate point corresponding to this balloon's position. May be null. */ +public class GlobeBrowserBalloon extends AbstractBrowserBalloon implements GlobeBalloon { + + protected class OrderedGlobeBrowserBalloon extends OrderedBrowserBalloon { + + /** + * The model-coordinate point corresponding to this balloon's position. May be null. + */ protected Vec4 placePoint; /** * The projection of this balloon's placePoint in the viewport (on the screen). May be @@ -50,17 +51,15 @@ protected class OrderedGlobeBrowserBalloon extends OrderedBrowserBalloon /** * Constructs a new GlobeBrowserBalloon with the specified text content and position. * - * @param text the balloon's initial text content. + * @param text the balloon's initial text content. * @param position the balloon's initial position. * * @throws IllegalArgumentException if either text or position are null. */ - public GlobeBrowserBalloon(String text, Position position) - { + public GlobeBrowserBalloon(String text, Position position) { super(text); - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -69,17 +68,18 @@ public GlobeBrowserBalloon(String text, Position position) this.position = position; } - /** {@inheritDoc} */ - public Position getPosition() - { + /** + * {@inheritDoc} + */ + public Position getPosition() { return this.position; } - /** {@inheritDoc} */ - public void setPosition(Position position) - { - if (position == null) - { + /** + * {@inheritDoc} + */ + public void setPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -88,21 +88,22 @@ public void setPosition(Position position) this.position = position; } - /** {@inheritDoc} */ - public int getAltitudeMode() - { + /** + * {@inheritDoc} + */ + public int getAltitudeMode() { return altitudeMode; } - /** {@inheritDoc} */ - public void setAltitudeMode(int altitudeMode) - { + /** + * {@inheritDoc} + */ + public void setAltitudeMode(int altitudeMode) { this.altitudeMode = altitudeMode; } @Override - protected OrderedBrowserBalloon createOrderedRenderable() - { + protected OrderedBrowserBalloon createOrderedRenderable() { return new OrderedGlobeBrowserBalloon(); } @@ -120,8 +121,7 @@ protected OrderedBrowserBalloon createOrderedRenderable() * * @param dc the current draw context. */ - protected void computeBalloonPoints(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void computeBalloonPoints(DrawContext dc, OrderedBrowserBalloon obb) { OrderedGlobeBrowserBalloon ogpm = (OrderedGlobeBrowserBalloon) obb; ogpm.placePoint = null; @@ -133,27 +133,24 @@ protected void computeBalloonPoints(DrawContext dc, OrderedBrowserBalloon obb) obb.webViewRect = null; obb.eyeDistance = 0; - if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) - { + if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) { ogpm.placePoint = dc.computeTerrainPoint( - this.position.getLatitude(), this.position.getLongitude(), 0); - } - else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + this.position.getLatitude(), this.position.getLongitude(), 0); + } else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) { ogpm.placePoint = dc.computeTerrainPoint( - this.position.getLatitude(), this.position.getLongitude(), this.position.getAltitude()); - } - else // Default to ABSOLUTE + this.position.getLatitude(), this.position.getLongitude(), this.position.getAltitude()); + } else // Default to ABSOLUTE { double height = this.position.getElevation() * dc.getVerticalExaggeration(); ogpm.placePoint = dc.getGlobe().computePointFromPosition( - this.position.getLatitude(), this.position.getLongitude(), height); + this.position.getLatitude(), this.position.getLongitude(), height); } // Exit immediately if the place point is null. In this case we cannot compute the data that depends on the // place point: screen place point, screen rectangle, WebView rectangle, and eye distance. - if (ogpm.placePoint == null) + if (ogpm.placePoint == null) { return; + } BalloonAttributes activeAttrs = this.getActiveAttributes(); Dimension size = this.computeSize(dc, activeAttrs); @@ -168,8 +165,8 @@ else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) // of the frame. Since the screen reference point is fixed, the frame appears to move relative to the reference // point. obb.screenRect = new Rectangle((int) (ogpm.screenPlacePoint.x - this.screenOffset.x), - (int) (ogpm.screenPlacePoint.y - this.screenOffset.y), - size.width, size.height); + (int) (ogpm.screenPlacePoint.y - this.screenOffset.y), + size.width, size.height); // Compute the screen extent as the rectangle containing the balloon's screen rectangle and its place point. obb.screenExtent = new Rectangle(obb.screenRect); obb.screenExtent.add(ogpm.screenPlacePoint.x, ogpm.screenPlacePoint.y); @@ -183,17 +180,17 @@ else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) obb.eyeDistance = this.isAlwaysOnTop() ? 0 : dc.getView().getEyePoint().distanceTo3(ogpm.placePoint); } - /** {@inheritDoc} */ - protected void setupDepthTest(DrawContext dc, OrderedBrowserBalloon obb) - { + /** + * {@inheritDoc} + */ + protected void setupDepthTest(DrawContext dc, OrderedBrowserBalloon obb) { OrderedGlobeBrowserBalloon ogpm = (OrderedGlobeBrowserBalloon) obb; GL gl = dc.getGL(); if (!this.isAlwaysOnTop() && ogpm.screenPlacePoint != null - && dc.getView().getEyePosition().getElevation() < (dc.getGlobe().getMaxElevation() - * dc.getVerticalExaggeration())) - { + && dc.getView().getEyePosition().getElevation() < (dc.getGlobe().getMaxElevation() + * dc.getVerticalExaggeration())) { gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthMask(false); @@ -202,9 +199,7 @@ protected void setupDepthTest(DrawContext dc, OrderedBrowserBalloon obb) depth = depth < 0d ? 0d : (depth > 1d ? 1d : depth); gl.glDepthFunc(GL.GL_LESS); gl.glDepthRange(depth, depth); - } - else - { + } else { gl.glDisable(GL.GL_DEPTH_TEST); } } @@ -217,8 +212,7 @@ protected void setupDepthTest(DrawContext dc, OrderedBrowserBalloon obb) * class' behavior. */ @Override - protected boolean intersectsFrustum(DrawContext dc, OrderedBrowserBalloon obb) - { + protected boolean intersectsFrustum(DrawContext dc, OrderedBrowserBalloon obb) { OrderedGlobeBrowserBalloon ogpm = (OrderedGlobeBrowserBalloon) obb; View view = dc.getView(); @@ -227,9 +221,8 @@ protected boolean intersectsFrustum(DrawContext dc, OrderedBrowserBalloon obb) Frustum frustum = view.getFrustumInModelCoordinates(); //noinspection SimplifiableIfStatement if (ogpm.placePoint != null - && (frustum.getNear().distanceTo(ogpm.placePoint) < 0 - || frustum.getFar().distanceTo(ogpm.placePoint) < 0)) - { + && (frustum.getNear().distanceTo(ogpm.placePoint) < 0 + || frustum.getFar().distanceTo(ogpm.placePoint) < 0)) { return false; } @@ -242,8 +235,7 @@ protected boolean intersectsFrustum(DrawContext dc, OrderedBrowserBalloon obb) * Overridden to use this balloon's position as the picked object's position. */ @Override - protected PickedObject createPickedObject(DrawContext dc, Color pickColor) - { + protected PickedObject createPickedObject(DrawContext dc, Color pickColor) { PickedObject po = super.createPickedObject(dc, pickColor); // Set the picked object's position to the balloon's position. po.setPosition(this.position); diff --git a/src/gov/nasa/worldwind/render/Highlightable.java b/src/gov/nasa/worldwind/render/Highlightable.java index 167d2f8865..d9e9607080 100644 --- a/src/gov/nasa/worldwind/render/Highlightable.java +++ b/src/gov/nasa/worldwind/render/Highlightable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; /** @@ -13,8 +12,8 @@ * @author tag * @version $Id: Highlightable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Highlightable -{ +public interface Highlightable { + /** * Indicates whether to highlight the shape. * diff --git a/src/gov/nasa/worldwind/render/IconRenderer.java b/src/gov/nasa/worldwind/render/IconRenderer.java index 4254d625ad..7a89da1f89 100644 --- a/src/gov/nasa/worldwind/render/IconRenderer.java +++ b/src/gov/nasa/worldwind/render/IconRenderer.java @@ -38,8 +38,8 @@ * @author tag * @version $Id: IconRenderer.java 2260 2014-08-23 00:14:06Z tgaskins $ */ -public class IconRenderer -{ +public class IconRenderer { + protected Pedestal pedestal; protected boolean horizonClippingEnabled = false; protected boolean viewClippingEnabled = true; @@ -50,17 +50,14 @@ public class IconRenderer protected PickSupport pickSupport = new PickSupport(); - public IconRenderer() - { + public IconRenderer() { } - public Pedestal getPedestal() - { + public Pedestal getPedestal() { return pedestal; } - public void setPedestal(Pedestal pedestal) - { + public void setPedestal(Pedestal pedestal) { this.pedestal = pedestal; } @@ -71,8 +68,7 @@ public void setPedestal(Pedestal pedestal) * * @see #setHorizonClippingEnabled(boolean) */ - public boolean isHorizonClippingEnabled() - { + public boolean isHorizonClippingEnabled() { return horizonClippingEnabled; } @@ -81,12 +77,11 @@ public boolean isHorizonClippingEnabled() * view volume inclusion. The default is false, horizon clipping is not performed. * * @param horizonClippingEnabled true if horizon clipping should be performed, otherwise - * false. + * false. * * @see #setViewClippingEnabled(boolean) */ - public void setHorizonClippingEnabled(boolean horizonClippingEnabled) - { + public void setHorizonClippingEnabled(boolean horizonClippingEnabled) { this.horizonClippingEnabled = horizonClippingEnabled; } @@ -97,8 +92,7 @@ public void setHorizonClippingEnabled(boolean horizonClippingEnabled) * * @see #setViewClippingEnabled(boolean) */ - public boolean isViewClippingEnabled() - { + public boolean isViewClippingEnabled() { return viewClippingEnabled; } @@ -112,8 +106,7 @@ public boolean isViewClippingEnabled() * * @see #setHorizonClippingEnabled(boolean) */ - public void setViewClippingEnabled(boolean viewClippingEnabled) - { + public void setViewClippingEnabled(boolean viewClippingEnabled) { this.viewClippingEnabled = viewClippingEnabled; } @@ -124,8 +117,7 @@ public void setViewClippingEnabled(boolean viewClippingEnabled) * * @see #setPickFrustumClippingEnabled(boolean) */ - public boolean isPickFrustumClippingEnabled() - { + public boolean isPickFrustumClippingEnabled() { return pickFrustumClippingEnabled; } @@ -135,21 +127,21 @@ public boolean isPickFrustumClippingEnabled() * clipping not be performed. The default is false, picking volume clipping is not performed. * * @param pickFrustumClippingEnabled true if picking clipping should be performed, otherwise - * false. + * false. */ - public void setPickFrustumClippingEnabled(boolean pickFrustumClippingEnabled) - { + public void setPickFrustumClippingEnabled(boolean pickFrustumClippingEnabled) { this.pickFrustumClippingEnabled = pickFrustumClippingEnabled; } - protected static boolean isIconValid(WWIcon icon, boolean checkPosition) - { - if (icon == null || icon.getImageTexture() == null) + protected static boolean isIconValid(WWIcon icon, boolean checkPosition) { + if (icon == null || icon.getImageTexture() == null) { return false; + } //noinspection RedundantIfStatement - if (checkPosition && icon.getPosition() == null) + if (checkPosition && icon.getPosition() == null) { return false; + } return true; } @@ -159,10 +151,9 @@ protected static boolean isIconValid(WWIcon icon, boolean checkPosition) * level. * * @return true if icon elevations are treated as absolute, false if they're treated as - * offsets from the terrain. + * offsets from the terrain. */ - public boolean isAlwaysUseAbsoluteElevation() - { + public boolean isAlwaysUseAbsoluteElevation() { return alwaysUseAbsoluteElevation; } @@ -172,10 +163,9 @@ public boolean isAlwaysUseAbsoluteElevation() * absolute elevation above sea level. * * @param alwaysUseAbsoluteElevation true to treat icon elevations as absolute, false to - * treat them as offsets from the terrain. + * treat them as offsets from the terrain. */ - public void setAlwaysUseAbsoluteElevation(boolean alwaysUseAbsoluteElevation) - { + public void setAlwaysUseAbsoluteElevation(boolean alwaysUseAbsoluteElevation) { this.alwaysUseAbsoluteElevation = alwaysUseAbsoluteElevation; } @@ -188,8 +178,7 @@ public void setAlwaysUseAbsoluteElevation(boolean alwaysUseAbsoluteElevation) * * @see #setAllowBatchPicking(boolean) */ - public boolean isAllowBatchPicking() - { + public boolean isAllowBatchPicking() { return this.allowBatchPicking; } @@ -200,41 +189,37 @@ public boolean isAllowBatchPicking() * * @param allowBatchPicking true if batch picking is allowed, otherwise false. */ - public void setAllowBatchPicking(boolean allowBatchPicking) - { + public void setAllowBatchPicking(boolean allowBatchPicking) { this.allowBatchPicking = allowBatchPicking; } @SuppressWarnings({"UnusedDeclaration"}) - public void pick(DrawContext dc, Iterable icons, java.awt.Point pickPoint, Layer layer) - { + public void pick(DrawContext dc, Iterable icons, java.awt.Point pickPoint, Layer layer) { this.drawMany(dc, icons, layer); } - public void render(DrawContext dc, Iterable icons) - { + public void render(DrawContext dc, Iterable icons) { this.drawMany(dc, icons, null); } - protected void drawMany(DrawContext dc, Iterable icons, Layer layer) - { - if (dc == null) - { + protected void drawMany(DrawContext dc, Iterable icons, Layer layer) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc.getVisibleSector() == null) + if (dc.getVisibleSector() == null) { return; + } SectorGeometryList geos = dc.getSurfaceGeometry(); //noinspection RedundantIfStatement - if (geos == null) + if (geos == null) { return; + } - if (icons == null) - { + if (icons == null) { String msg = Logging.getMessage("nullValue.IconIterator"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -242,25 +227,24 @@ protected void drawMany(DrawContext dc, Iterable icons, Layer Iterator iterator = icons.iterator(); - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return; + } double horizon = dc.getView().getHorizonDistance(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { WWIcon icon = iterator.next(); - if (!isIconValid(icon, true)) - { + if (!isIconValid(icon, true)) { // Record feedback data for this WWIcon if feedback is enabled. - if (icon != null) + if (icon != null) { this.recordFeedback(dc, icon, null, null); + } continue; } - if (!icon.isVisible()) - { + if (!icon.isVisible()) { // Record feedback data for this WWIcon if feedback is enabled. this.recordFeedback(dc, icon, null, null); @@ -271,29 +255,25 @@ protected void drawMany(DrawContext dc, Iterable icons, Layer // otherwise draw it from the globe. Position pos = icon.getPosition(); Vec4 iconPoint = null; - if (dc.is2DGlobe()) - { + if (dc.is2DGlobe()) { iconPoint = dc.getGlobe().computePointFromLocation(pos); - } - else if (pos.getElevation() < dc.getGlobe().getMaxElevation() && !this.isAlwaysUseAbsoluteElevation()) - { + } else if (pos.getElevation() < dc.getGlobe().getMaxElevation() && !this.isAlwaysUseAbsoluteElevation()) { iconPoint = dc.getSurfaceGeometry().getSurfacePoint(icon.getPosition()); } - if (iconPoint == null) - { + if (iconPoint == null) { Angle lat = pos.getLatitude(); Angle lon = pos.getLongitude(); double elevation = pos.getElevation(); - if (!this.isAlwaysUseAbsoluteElevation()) + if (!this.isAlwaysUseAbsoluteElevation()) { elevation += dc.getGlobe().getElevation(lat, lon); + } iconPoint = dc.getGlobe().computePointFromPosition(lat, lon, elevation); } double eyeDistance = icon.isAlwaysOnTop() ? 0 : dc.getView().getEyePoint().distanceTo3(iconPoint); - if (this.isHorizonClippingEnabled() && !dc.is2DGlobe() && eyeDistance > horizon) - { + if (this.isHorizonClippingEnabled() && !dc.is2DGlobe() && eyeDistance > horizon) { // Record feedback data for this WWIcon if feedback is enabled. this.recordFeedback(dc, icon, iconPoint, null); @@ -302,8 +282,7 @@ else if (pos.getElevation() < dc.getGlobe().getMaxElevation() && !this.isAlwaysU // If enabled, eliminate icons outside the view volume. Primarily used to control icon visibility beyond // the view volume's far clipping plane. - if (this.isViewClippingEnabled() && !dc.getView().getFrustumInModelCoordinates().contains(iconPoint)) - { + if (this.isViewClippingEnabled() && !dc.getView().getFrustumInModelCoordinates().contains(iconPoint)) { // Record feedback data for this WWIcon if feedback is enabled. this.recordFeedback(dc, icon, iconPoint, null); @@ -313,30 +292,33 @@ else if (pos.getElevation() < dc.getGlobe().getMaxElevation() && !this.isAlwaysU // The icons aren't drawn here, but added to the ordered queue to be drawn back-to-front. dc.addOrderedRenderable(new OrderedIcon(icon, iconPoint, layer, eyeDistance, horizon)); - if (icon.isShowToolTip()) + if (icon.isShowToolTip()) { this.addToolTip(dc, icon, iconPoint); + } } } - protected void addToolTip(DrawContext dc, WWIcon icon, Vec4 iconPoint) - { - if (icon.getToolTipFont() == null && icon.getToolTipText() == null) + protected void addToolTip(DrawContext dc, WWIcon icon, Vec4 iconPoint) { + if (icon.getToolTipFont() == null && icon.getToolTipText() == null) { return; + } Vec4 screenPoint = dc.getView().project(iconPoint); - if (screenPoint == null) + if (screenPoint == null) { return; + } - if (icon.getToolTipOffset() != null) + if (icon.getToolTipOffset() != null) { screenPoint = screenPoint.add3(icon.getToolTipOffset()); + } OrderedText tip = new OrderedText(icon.getToolTipText(), icon.getToolTipFont(), screenPoint, - icon.getToolTipTextColor(), 0d); + icon.getToolTipTextColor(), 0d); dc.addOrderedRenderable(tip); } - protected class OrderedText implements OrderedRenderable - { + protected class OrderedText implements OrderedRenderable { + protected Font font; protected String text; protected Vec4 point; @@ -345,8 +327,7 @@ protected class OrderedText implements OrderedRenderable protected Layer layer; protected java.awt.Color color; - public OrderedText(String text, Font font, Vec4 point, java.awt.Color color, double eyeDistance) - { + public OrderedText(String text, Font font, Vec4 point, java.awt.Color color, double eyeDistance) { this.text = text; this.font = font; this.point = point; @@ -355,8 +336,7 @@ public OrderedText(String text, Font font, Vec4 point, java.awt.Color color, dou } public OrderedText(String text, Font font, Vec4 point, java.awt.Point pickPoint, Layer layer, - double eyeDistance) - { + double eyeDistance) { this.text = text; this.font = font; this.point = point; @@ -365,34 +345,27 @@ public OrderedText(String text, Font font, Vec4 point, java.awt.Point pickPoint, this.layer = layer; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { ToolTipRenderer toolTipRenderer = this.getToolTipRenderer(dc); toolTipRenderer.render(dc, this.text, (int) this.point.x, (int) this.point.y); } - public void pick(DrawContext dc, java.awt.Point pickPoint) - { + public void pick(DrawContext dc, java.awt.Point pickPoint) { } @SuppressWarnings({"UnusedDeclaration"}) - protected ToolTipRenderer getToolTipRenderer(DrawContext dc) - { + protected ToolTipRenderer getToolTipRenderer(DrawContext dc) { ToolTipRenderer tr = (this.font != null) ? new ToolTipRenderer(this.font) : new ToolTipRenderer(); - if (this.color != null) - { + if (this.color != null) { tr.setTextColor(this.color); tr.setOutlineColor(this.color); tr.setInteriorColor(ToolTipRenderer.getContrastingColor(this.color)); - } - else - { + } else { tr.setUseSystemLookAndFeel(true); } @@ -400,16 +373,15 @@ protected ToolTipRenderer getToolTipRenderer(DrawContext dc) } } - protected class OrderedIcon implements OrderedRenderable, Locatable - { + protected class OrderedIcon implements OrderedRenderable, Locatable { + protected WWIcon icon; protected Vec4 point; protected double eyeDistance; protected double horizonDistance; protected Layer layer; - public OrderedIcon(WWIcon icon, Vec4 point, Layer layer, double eyeDistance, double horizonDistance) - { + public OrderedIcon(WWIcon icon, Vec4 point, Layer layer, double eyeDistance, double horizonDistance) { this.icon = icon; this.point = point; this.eyeDistance = eyeDistance; @@ -417,84 +389,62 @@ public OrderedIcon(WWIcon icon, Vec4 point, Layer layer, double eyeDistance, dou this.layer = layer; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - public Position getPosition() - { + public Position getPosition() { return this.icon.getPosition(); } - public IconRenderer getRenderer() - { + public IconRenderer getRenderer() { return IconRenderer.this; } - public Vec4 getPoint() - { + public Vec4 getPoint() { return this.point; } - public WWIcon getIcon() - { + public WWIcon getIcon() { return this.icon; } - public double getHorizonDistance() - { + public double getHorizonDistance() { return horizonDistance; } - public Layer getLayer() - { + public Layer getLayer() { return layer; } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { IconRenderer.this.beginDrawIcons(dc); - try - { + try { IconRenderer.this.drawIconsInBatch(dc, this); - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { Logging.logger().log(Level.SEVERE, "generic.ExceptionWhileRenderingIcon", e); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, "generic.ExceptionWhileRenderingIcon", e); - } - finally - { + } finally { IconRenderer.this.endDrawIcons(dc); } } - public void pick(DrawContext dc, java.awt.Point pickPoint) - { + public void pick(DrawContext dc, java.awt.Point pickPoint) { IconRenderer.this.pickSupport.clearPickList(); IconRenderer.this.beginDrawIcons(dc); - try - { - if (IconRenderer.this.isAllowBatchPicking()) + try { + if (IconRenderer.this.isAllowBatchPicking()) { IconRenderer.this.pickIconsInBatch(dc, this); - else + } else { IconRenderer.this.drawIcon(dc, this); - } - catch (WWRuntimeException e) - { + } + } catch (WWRuntimeException e) { Logging.logger().log(Level.SEVERE, "generic.ExceptionWhileRenderingIcon", e); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, "generic.ExceptionWhilePickingIcon", e); - } - finally - { + } finally { IconRenderer.this.endDrawIcons(dc); IconRenderer.this.pickSupport.resolvePick(dc, pickPoint, layer); IconRenderer.this.pickSupport.clearPickList(); // to ensure entries can be garbage collected @@ -502,14 +452,13 @@ public void pick(DrawContext dc, java.awt.Point pickPoint) } } - protected void beginDrawIcons(DrawContext dc) - { + protected void beginDrawIcons(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.oglStackHandler.clear(); - int attributeMask = - GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask and depth func + int attributeMask + = GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask and depth func | GL2.GL_TRANSFORM_BIT // for modelview and perspective | GL2.GL_VIEWPORT_BIT // for depth range | GL2.GL_CURRENT_BIT // for current color @@ -519,8 +468,9 @@ protected void beginDrawIcons(DrawContext dc) this.oglStackHandler.pushAttrib(gl, attributeMask); // Apply the depth buffer but don't change it. - if ((!dc.isDeepPickingEnabled())) + if ((!dc.isDeepPickingEnabled())) { gl.glEnable(GL.GL_DEPTH_TEST); + } gl.glDepthMask(false); // Suppress any fully transparent image pixels @@ -534,8 +484,7 @@ protected void beginDrawIcons(DrawContext dc) this.oglStackHandler.pushModelview(gl); this.oglStackHandler.pushTexture(gl); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.beginPicking(dc); // Set up to replace the non-transparent texture colors with the single pick color. @@ -543,24 +492,21 @@ protected void beginDrawIcons(DrawContext dc) gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_COMBINE); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, GL2.GL_PREVIOUS); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_COMBINE_RGB, GL2.GL_REPLACE); - } - else - { + } else { gl.glEnable(GL.GL_TEXTURE_2D); gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); } } - protected void endDrawIcons(DrawContext dc) - { - if (dc.isPickingMode()) + protected void endDrawIcons(DrawContext dc) { + if (dc.isPickingMode()) { this.pickSupport.endPicking(dc); + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, OGLUtil.DEFAULT_TEX_ENV_MODE); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, OGLUtil.DEFAULT_SRC0_RGB); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_COMBINE_RGB, OGLUtil.DEFAULT_COMBINE_RGB); @@ -571,17 +517,16 @@ protected void endDrawIcons(DrawContext dc) this.oglStackHandler.pop(gl); } - protected void drawIconsInBatch(DrawContext dc, OrderedIcon uIcon) - { + protected void drawIconsInBatch(DrawContext dc, OrderedIcon uIcon) { this.drawIcon(dc, uIcon); // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - while (nextItem != null && nextItem instanceof OrderedIcon) - { + while (nextItem != null && nextItem instanceof OrderedIcon) { OrderedIcon oi = (OrderedIcon) nextItem; - if (oi.getRenderer() != this) + if (oi.getRenderer() != this) { return; + } dc.pollOrderedRenderables(); // take it off the queue this.drawIcon(dc, oi); @@ -590,8 +535,7 @@ protected void drawIconsInBatch(DrawContext dc, OrderedIcon uIcon) } } - protected void pickIconsInBatch(DrawContext dc, OrderedIcon uIcon) - { + protected void pickIconsInBatch(DrawContext dc, OrderedIcon uIcon) { this.drawIcon(dc, uIcon); // Draw as many as we can in a batch to save ogl state switching. @@ -600,11 +544,11 @@ protected void pickIconsInBatch(DrawContext dc, OrderedIcon uIcon) // associates the item's layer with the resolved picked object. Object nextItem = dc.peekOrderedRenderables(); while (nextItem != null && nextItem instanceof OrderedIcon - && ((OrderedIcon) nextItem).layer == uIcon.layer) - { + && ((OrderedIcon) nextItem).layer == uIcon.layer) { OrderedIcon oi = (OrderedIcon) nextItem; - if (oi.getRenderer() != this) + if (oi.getRenderer() != this) { return; + } dc.pollOrderedRenderables(); // take it off the queue this.drawIcon(dc, oi); @@ -613,23 +557,21 @@ protected void pickIconsInBatch(DrawContext dc, OrderedIcon uIcon) } } - protected Vec4 drawIcon(DrawContext dc, OrderedIcon uIcon) - { - if (uIcon.point == null) - { + protected Vec4 drawIcon(DrawContext dc, OrderedIcon uIcon) { + if (uIcon.point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); // Record feedback data for this WWIcon if feedback is enabled. - if (uIcon.icon != null) + if (uIcon.icon != null) { this.recordFeedback(dc, uIcon.icon, null, null); + } return null; } WWIcon icon = uIcon.icon; - if (dc.getView().getFrustumInModelCoordinates().getNear().distanceTo(uIcon.point) < 0) - { + if (dc.getView().getFrustumInModelCoordinates().getNear().distanceTo(uIcon.point) < 0) { // Record feedback data for this WWIcon if feedback is enabled. this.recordFeedback(dc, icon, uIcon.point, null); @@ -637,8 +579,7 @@ protected Vec4 drawIcon(DrawContext dc, OrderedIcon uIcon) } final Vec4 screenPoint = dc.getView().project(uIcon.point); - if (screenPoint == null) - { + if (screenPoint == null) { // Record feedback data for this WWIcon if feedback is enabled. this.recordFeedback(dc, icon, uIcon.point, null); @@ -647,13 +588,10 @@ protected Vec4 drawIcon(DrawContext dc, OrderedIcon uIcon) double pedestalScale; double pedestalSpacing; - if (this.pedestal != null) - { + if (this.pedestal != null) { pedestalScale = this.pedestal.getScale(); pedestalSpacing = pedestal.getSpacingPixels(); - } - else - { + } else { pedestalScale = 0d; pedestalSpacing = 0d; } @@ -670,8 +608,7 @@ protected Vec4 drawIcon(DrawContext dc, OrderedIcon uIcon) double height = size != null ? size.getHeight() : icon.getImageTexture().getHeight(dc); gl.glTranslated(screenPoint.x - width / 2, screenPoint.y + (pedestalScale * height) + pedestalSpacing, 0d); - if (icon.isHighlighted()) - { + if (icon.isHighlighted()) { double heightDelta = this.pedestal != null ? 0 : height / 2; // expand only above the pedestal gl.glTranslated(width / 2, heightDelta, 0); gl.glScaled(icon.getHighlightScale(), icon.getHighlightScale(), icon.getHighlightScale()); @@ -679,20 +616,16 @@ protected Vec4 drawIcon(DrawContext dc, OrderedIcon uIcon) } Rectangle rect = new Rectangle((int) (screenPoint.x - width / 2), (int) (screenPoint.y), (int) width, - (int) (height + (pedestalScale * height) + pedestalSpacing)); + (int) (height + (pedestalScale * height) + pedestalSpacing)); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { //If in picking mode and pick clipping is enabled, check to see if the icon is within the pick volume. - if (this.isPickFrustumClippingEnabled() && !dc.getPickFrustums().intersectsAny(rect)) - { + if (this.isPickFrustumClippingEnabled() && !dc.getPickFrustums().intersectsAny(rect)) { // Record feedback data for this WWIcon if feedback is enabled. this.recordFeedback(dc, icon, uIcon.point, rect); return screenPoint; - } - else - { + } else { java.awt.Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); this.pickSupport.addPickableObject(colorCode, icon, uIcon.getPosition(), false); @@ -700,24 +633,22 @@ protected Vec4 drawIcon(DrawContext dc, OrderedIcon uIcon) } } - if (icon.getBackgroundTexture() != null) + if (icon.getBackgroundTexture() != null) { this.applyBackground(dc, icon, screenPoint, width, height, pedestalSpacing, pedestalScale); + } - if (icon.getImageTexture().bind(dc)) - { + if (icon.getImageTexture().bind(dc)) { TextureCoords texCoords = icon.getImageTexture().getTexCoords(); gl.glScaled(width, height, 1d); dc.drawUnitQuad(texCoords); } - if (this.pedestal != null && this.pedestal.getImageTexture() != null) - { + if (this.pedestal != null && this.pedestal.getImageTexture() != null) { gl.glLoadIdentity(); gl.glTranslated(screenPoint.x - (pedestalScale * (width / 2)), screenPoint.y, 0d); gl.glScaled(width * pedestalScale, height * pedestalScale, 1d); - if (this.pedestal.getImageTexture().bind(dc)) - { + if (this.pedestal.getImageTexture().bind(dc)) { TextureCoords texCoords = this.pedestal.getImageTexture().getTexCoords(); dc.drawUnitQuad(texCoords); } @@ -730,17 +661,14 @@ protected Vec4 drawIcon(DrawContext dc, OrderedIcon uIcon) } protected void applyBackground(DrawContext dc, WWIcon icon, Vec4 screenPoint, double width, double height, - double pedestalSpacing, double pedestalScale) - { + double pedestalSpacing, double pedestalScale) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. double backgroundScale; backgroundScale = icon.getBackgroundScale(); - if (icon.getBackgroundTexture() != null) - { - if (icon.getBackgroundTexture().bind(dc)) - { + if (icon.getBackgroundTexture() != null) { + if (icon.getBackgroundTexture().bind(dc)) { TextureCoords texCoords = icon.getBackgroundTexture().getTexCoords(); gl.glPushMatrix(); gl.glLoadIdentity(); @@ -763,64 +691,54 @@ protected void applyBackground(DrawContext dc, WWIcon icon, Vec4 screenPoint, do } } - protected void setDepthFunc(DrawContext dc, OrderedIcon uIcon, Vec4 screenPoint) - { + protected void setDepthFunc(DrawContext dc, OrderedIcon uIcon, Vec4 screenPoint) { GL gl = dc.getGL(); - if (uIcon.icon.isAlwaysOnTop()) - { + if (uIcon.icon.isAlwaysOnTop()) { gl.glDepthFunc(GL.GL_ALWAYS); return; } Position eyePos = dc.getView().getEyePosition(); - if (eyePos == null) - { + if (eyePos == null) { gl.glDepthFunc(GL.GL_ALWAYS); return; } double altitude = eyePos.getElevation(); - if (altitude < (dc.getGlobe().getMaxElevation() * dc.getVerticalExaggeration())) - { + if (altitude < (dc.getGlobe().getMaxElevation() * dc.getVerticalExaggeration())) { double depth = screenPoint.z - (8d * 0.00048875809d); depth = depth < 0d ? 0d : (depth > 1d ? 1d : depth); gl.glDepthFunc(GL.GL_LESS); gl.glDepthRange(depth, depth); - } - else if (uIcon.eyeDistance > uIcon.horizonDistance) - { + } else if (uIcon.eyeDistance > uIcon.horizonDistance) { gl.glDepthFunc(GL.GL_EQUAL); gl.glDepthRange(1d, 1d); - } - else - { + } else { gl.glDepthFunc(GL.GL_ALWAYS); } } @Override - public String toString() - { + public String toString() { return Logging.getMessage("layers.IconLayer.Name"); } //**************************************************************// //******************** Feedback ******************************// //**************************************************************// - /** * Returns true if the IconRenderer should record feedback about how the specified WWIcon has been processed. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param icon the WWIcon to record feedback information for. * * @return true to record feedback; false otherwise. */ - protected boolean isFeedbackEnabled(DrawContext dc, WWIcon icon) - { - if (dc.isPickingMode()) + protected boolean isFeedbackEnabled(DrawContext dc, WWIcon icon) { + if (dc.isPickingMode()) { return false; + } Boolean b = (Boolean) icon.getValue(AVKey.FEEDBACK_ENABLED); return (b != null && b); @@ -830,15 +748,15 @@ protected boolean isFeedbackEnabled(DrawContext dc, WWIcon icon) * If feedback is enabled for the specified WWIcon, this method records feedback about how the specified WWIcon has * been processed. * - * @param dc the current DrawContext. - * @param icon the icon which the feedback information refers to. + * @param dc the current DrawContext. + * @param icon the icon which the feedback information refers to. * @param modelPoint the icon's reference point in model coordinates. * @param screenRect the icon's bounding rectangle in screen coordinates. */ - protected void recordFeedback(DrawContext dc, WWIcon icon, Vec4 modelPoint, Rectangle screenRect) - { - if (!this.isFeedbackEnabled(dc, icon)) + protected void recordFeedback(DrawContext dc, WWIcon icon, Vec4 modelPoint, Rectangle screenRect) { + if (!this.isFeedbackEnabled(dc, icon)) { return; + } this.doRecordFeedback(dc, icon, modelPoint, screenRect); } @@ -846,14 +764,13 @@ protected void recordFeedback(DrawContext dc, WWIcon icon, Vec4 modelPoint, Rect /** * Records feedback about how the specified WWIcon has been processed. * - * @param dc the current DrawContext. - * @param icon the icon which the feedback information refers to. + * @param dc the current DrawContext. + * @param icon the icon which the feedback information refers to. * @param modelPoint the icon's reference point in model coordinates. * @param screenRect the icon's bounding rectangle in screen coordinates. */ @SuppressWarnings({"UnusedDeclaration"}) - protected void doRecordFeedback(DrawContext dc, WWIcon icon, Vec4 modelPoint, Rectangle screenRect) - { + protected void doRecordFeedback(DrawContext dc, WWIcon icon, Vec4 modelPoint, Rectangle screenRect) { icon.setValue(AVKey.FEEDBACK_REFERENCE_POINT, modelPoint); icon.setValue(AVKey.FEEDBACK_SCREEN_BOUNDS, screenRect); } diff --git a/src/gov/nasa/worldwind/render/LazilyLoadedTexture.java b/src/gov/nasa/worldwind/render/LazilyLoadedTexture.java index 6c60b86147..7e2f85b576 100644 --- a/src/gov/nasa/worldwind/render/LazilyLoadedTexture.java +++ b/src/gov/nasa/worldwind/render/LazilyLoadedTexture.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.opengl.util.texture.*; @@ -35,20 +34,32 @@ * @author tag * @version $Id: LazilyLoadedTexture.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class LazilyLoadedTexture extends AVListImpl implements WWTexture -{ - /** The original image source specified at construction. */ +public class LazilyLoadedTexture extends AVListImpl implements WWTexture { + + /** + * The original image source specified at construction. + */ protected Object imageSource; - /** The mip-map flag specified at construction. */ + /** + * The mip-map flag specified at construction. + */ protected boolean useMipMaps; - /** The current anisotropy flag. */ + /** + * The current anisotropy flag. + */ protected boolean useAnisotropy = true; - /** The texture width, if the width is known. Otherwise it's -1. */ + /** + * The texture width, if the width is known. Otherwise it's -1. + */ protected Integer width; - /** The texture height, if the height is known. Otherwise it's -1. */ + /** + * The texture height, if the height is known. Otherwise it's -1. + */ protected Integer height; - /** The texture's texture coordinates, as determined by JOGL when the texture is created. */ + /** + * The texture's texture coordinates, as determined by JOGL when the texture is created. + */ protected TextureCoords texCoords; /** * The texture data created as the image source is read. It's removed - set to null - once the textures is fully @@ -57,13 +68,21 @@ public class LazilyLoadedTexture extends AVListImpl implements WWTexture * image source is BufferedImage. */ protected volatile TextureData textureData; // if non-null, then must be converted to a Texture - /** Indicates that texture initialization failed. This texture should not be used if true. */ + /** + * Indicates that texture initialization failed. This texture should not be used if true. + */ protected boolean textureInitializationFailed = false; - /** Indicates whether the image read from the image source has mip-map data. */ + /** + * Indicates whether the image read from the image source has mip-map data. + */ protected boolean hasMipmapData = false; - /** Identifies the {@link gov.nasa.worldwind.cache.FileStore} of the supporting file cache for this model. */ + /** + * Identifies the {@link gov.nasa.worldwind.cache.FileStore} of the supporting file cache for this model. + */ protected FileStore fileStore = WorldWind.getDataFileStore(); - /** Provides a semaphore to synchronize access to the texture file if duplicate request tasks are active. */ + /** + * Provides a semaphore to synchronize access to the texture file if duplicate request tasks are active. + */ protected final Object fileLock = new Object(); /** @@ -80,8 +99,7 @@ public class LazilyLoadedTexture extends AVListImpl implements WWTexture * * @throws IllegalArgumentException if the imageSource is null. */ - public LazilyLoadedTexture(Object imageSource) - { + public LazilyLoadedTexture(Object imageSource) { this(imageSource, true); } @@ -90,12 +108,11 @@ public LazilyLoadedTexture(Object imageSource) * * @param imageSource the source of the image, either a file path {@link String} or a {@link * java.awt.image.BufferedImage}. - * @param useMipMaps Indicates whether to generate and use mip-maps for the image. + * @param useMipMaps Indicates whether to generate and use mip-maps for the image. * * @throws IllegalArgumentException if the imageSource is null. */ - public LazilyLoadedTexture(Object imageSource, boolean useMipMaps) - { + public LazilyLoadedTexture(Object imageSource, boolean useMipMaps) { initialize(imageSource, useMipMaps, null); } @@ -103,15 +120,13 @@ public LazilyLoadedTexture(Object imageSource, boolean useMipMaps) * Initializes this object's fields during construction. * * @param imageSource the image source. - * @param useMipMaps the mip-map flag. - * @param listener the change listener. + * @param useMipMaps the mip-map flag. + * @param listener the change listener. * * @throws IllegalArgumentException if the image source is null. */ - protected void initialize(Object imageSource, boolean useMipMaps, PropertyChangeListener listener) - { - if (imageSource == null) - { + protected void initialize(Object imageSource, boolean useMipMaps, PropertyChangeListener listener) { + if (imageSource == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -120,12 +135,12 @@ protected void initialize(Object imageSource, boolean useMipMaps, PropertyChange this.imageSource = imageSource; this.useMipMaps = useMipMaps; - if (listener != null) + if (listener != null) { this.addPropertyChangeListener(listener); + } } - public Object getImageSource() - { + public Object getImageSource() { return this.imageSource; } @@ -134,8 +149,7 @@ public Object getImageSource() * * @return true if the image source is a BufferedImage, otherwise false. */ - protected boolean isBufferedImageSource() - { + protected boolean isBufferedImageSource() { return this.getImageSource() instanceof BufferedImage; } @@ -146,8 +160,7 @@ protected boolean isBufferedImageSource() * * @return the texture's width if the texture has been retrieved, otherwise -1. */ - public int getWidth() - { + public int getWidth() { return this.width != null ? this.width : -1; } @@ -158,8 +171,7 @@ public int getWidth() * * @return the texture's height if the texture has been retrieved, otherwise -1. */ - public int getHeight() - { + public int getHeight() { return this.height != null ? this.height : -1; } @@ -172,8 +184,7 @@ public int getHeight() * * @return the texture's width if the texture has been retrieved, otherwise -1. */ - public int getWidth(DrawContext dc) - { + public int getWidth(DrawContext dc) { return this.getWidth(); } @@ -186,8 +197,7 @@ public int getWidth(DrawContext dc) * * @return the texture's height if the texture has been retrieved, otherwise -1. */ - public int getHeight(DrawContext dc) - { + public int getHeight(DrawContext dc) { return this.getHeight(); } @@ -195,20 +205,17 @@ public int getHeight(DrawContext dc) * Indicates whether the texture should use mip-maps. If they are not available in the source image they are * created. * - * @return true if mip-maps are used, false if not. + * @return true if mip-maps are used, false if not. */ - public boolean isUseMipMaps() - { + public boolean isUseMipMaps() { return this.useMipMaps; } - public TextureCoords getTexCoords() - { + public TextureCoords getTexCoords() { return this.texCoords; } - public boolean isTextureCurrent(DrawContext dc) - { + public boolean isTextureCurrent(DrawContext dc) { return this.getTexture(dc) != null; } @@ -217,8 +224,7 @@ public boolean isTextureCurrent(DrawContext dc) * * @return useAnisotropy true if anisotropy is to be applied, otherwise false. */ - public boolean isUseAnisotropy() - { + public boolean isUseAnisotropy() { return this.useAnisotropy; } @@ -227,8 +233,7 @@ public boolean isUseAnisotropy() * * @param useAnisotropy true if anisotropy is to be applied, otherwise false. */ - public void setUseAnisotropy(boolean useAnisotropy) - { + public void setUseAnisotropy(boolean useAnisotropy) { this.useAnisotropy = useAnisotropy; } @@ -237,10 +242,9 @@ public void setUseAnisotropy(boolean useAnisotropy) * texture should not be used. * * @return true if texture retrieval or creation failed, otherwise true, even if the image source has not yet been - * retrieved. + * retrieved. */ - public boolean isTextureInitializationFailed() - { + public boolean isTextureInitializationFailed() { return this.textureInitializationFailed; } @@ -251,15 +255,14 @@ public boolean isTextureInitializationFailed() * * @return this instance's texture, or null if the texture does not currently exist. */ - protected Texture getTexture(DrawContext dc) - { - if (this.getImageSource() == null) + protected Texture getTexture(DrawContext dc) { + if (this.getImageSource() == null) { return null; + } Texture texture = dc.getTextureCache().getTexture(this.getImageSource()); - if (this.width == null && texture != null) - { + if (this.width == null && texture != null) { this.width = texture.getWidth(); this.height = texture.getHeight(); this.texCoords = texture.getImageTexCoords(); @@ -276,10 +279,9 @@ protected Texture getTexture(DrawContext dc) * next bound or otherwise initialized. This object's texture data field is then set to null. * * @return the texture data, which may be null indicating that the image source has not been read or that a texture - * has been created. + * has been created. */ - protected TextureData getTextureData() - { + protected TextureData getTextureData() { return this.textureData; } @@ -292,11 +294,11 @@ protected TextureData getTextureData() * * @param textureData the texture data, which may be null. */ - protected void setTextureData(TextureData textureData) - { + protected void setTextureData(TextureData textureData) { this.textureData = textureData; - if (textureData != null && textureData.getMipmapData() != null) + if (textureData != null && textureData.getMipmapData() != null) { this.hasMipmapData = true; + } } /** @@ -307,51 +309,47 @@ protected void setTextureData(TextureData textureData) * * @return true if the texture was bound, otherwise false. */ - public boolean bind(DrawContext dc) - { - if (this.isTextureInitializationFailed()) + public boolean bind(DrawContext dc) { + if (this.isTextureInitializationFailed()) { return false; + } - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } Texture texture = this.getTexture(dc); - if (texture == null) + if (texture == null) { texture = this.requestTexture(dc); + } - if (texture != null) - { + if (texture != null) { texture.bind(dc.getGL()); return true; - } - else - { + } else { return false; } } - public void applyInternalTransform(DrawContext dc) - { - if (dc == null) - { + public void applyInternalTransform(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } Texture texture = this.getTexture(dc); - if (texture == null) + if (texture == null) { texture = this.requestTexture(dc); + } - if (texture == null) + if (texture == null) { return; + } - if (texture.getMustFlipVertically()) - { + if (texture.getMustFlipVertically()) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glMatrixMode(GL2.GL_TEXTURE); gl.glLoadIdentity(); @@ -368,20 +366,23 @@ public void applyInternalTransform(DrawContext dc) * * @return the new texture, or null if the texture is not yet available. */ - protected Texture requestTexture(DrawContext dc) - { - if (this.isBufferedImageSource()) + protected Texture requestTexture(DrawContext dc) { + if (this.isBufferedImageSource()) { return this.makeBufferedImageTexture(dc); + } - if (this.getTextureData() != null && this.getTexture(dc) == null) + if (this.getTextureData() != null && this.getTexture(dc) == null) { return this.makeTextureFromTextureData(dc); + } - if (WorldWind.getTaskService().isFull()) + if (WorldWind.getTaskService().isFull()) { return null; + } Runnable task = this.createRequestTask(); - if (WorldWind.getTaskService().contains(task)) + if (WorldWind.getTaskService().contains(task)) { return null; + } // Use either the current layer or the layer list as the listener to notify when the request completes. The // latter is used when the image source is requested during ordered rendering and the current layer is null. @@ -398,8 +399,7 @@ protected Texture requestTexture(DrawContext dc) * * @return a new request task that retrieves and loads this texture's image source. */ - protected Runnable createRequestTask() - { + protected Runnable createRequestTask() { return new RequestTask(this); } @@ -412,28 +412,24 @@ protected Runnable createRequestTask() * * @throws IllegalStateException if the image source is null or not a BufferedImage. */ - protected Texture makeBufferedImageTexture(DrawContext dc) - { - if (this.getImageSource() == null || !(this.getImageSource() instanceof BufferedImage)) - { + protected Texture makeBufferedImageTexture(DrawContext dc) { + if (this.getImageSource() == null || !(this.getImageSource() instanceof BufferedImage)) { String message = Logging.getMessage("generic.NotABufferedImage"); Logging.logger().severe(message); throw new IllegalStateException(message); } - try - { + try { TextureData td = AWTTextureIO.newTextureData(Configuration.getMaxCompatibleGLProfile(), - (BufferedImage) this.getImageSource(), this.isUseMipMaps()); - if (td == null) + (BufferedImage) this.getImageSource(), this.isUseMipMaps()); + if (td == null) { return null; + } this.setTextureData(td); return this.makeTextureFromTextureData(dc); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.IOExceptionDuringTextureInitialization"); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.textureInitializationFailed = true; @@ -447,12 +443,10 @@ protected Texture makeBufferedImageTexture(DrawContext dc) * @param dc the current draw context. * * @return the newly created texture, or null if this instance has no current TextureData or if texture - * creation failed. + * creation failed. */ - protected Texture makeTextureFromTextureData(DrawContext dc) - { - if (dc == null) - { + protected Texture makeTextureFromTextureData(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -465,11 +459,9 @@ protected Texture makeTextureFromTextureData(DrawContext dc) throw new IllegalStateException(msg); } - try - { + try { Texture texture = TextureIO.newTexture(this.getTextureData()); - if (texture == null) - { + if (texture == null) { this.textureInitializationFailed = true; return null; } @@ -485,9 +477,7 @@ protected Texture makeTextureFromTextureData(DrawContext dc) this.setTextureData(null); return texture; - } - catch (Exception e) - { + } catch (Exception e) { String name = this.isBufferedImageSource() ? "BufferedImage" : this.getImageSource().toString(); String msg = Logging.getMessage("generic.ExceptionAttemptingToCreateTexture", name); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); @@ -498,46 +488,45 @@ protected Texture makeTextureFromTextureData(DrawContext dc) /** * Sets a specified texture's OpenGL Texture parameters. * - * @param dc the current draw context. + * @param dc the current draw context. * @param texture the texture whose parameters to set. */ - protected void setTextureParameters(DrawContext dc, Texture texture) - { + protected void setTextureParameters(DrawContext dc, Texture texture) { // Enable the appropriate mip-mapping texture filters if the caller has specified that mip-mapping should be // enabled, and the texture itself supports mip-mapping. boolean useMipMapFilter = this.useMipMaps && (this.getTextureData().getMipmapData() != null - || texture.isUsingAutoMipmapGeneration()); + || texture.isUsingAutoMipmapGeneration()); GL gl = dc.getGL(); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, - useMipMapFilter ? GL.GL_LINEAR_MIPMAP_LINEAR : GL.GL_LINEAR); + useMipMapFilter ? GL.GL_LINEAR_MIPMAP_LINEAR : GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); - if (this.isUseAnisotropy() && useMipMapFilter) - { + if (this.isUseAnisotropy() && useMipMapFilter) { double maxAnisotropy = dc.getGLRuntimeCapabilities().getMaxTextureAnisotropy(); - if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) - { + if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) { gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, (float) maxAnisotropy); } } } - protected void notifyTextureLoaded() - { - if (this.listener != null) - { + protected void notifyTextureLoaded() { + if (this.listener != null) { this.listener.propertyChange(new PropertyChangeEvent(this, AVKey.TEXTURE, null, this)); this.listener = null; // forget the listener to avoid dangling references } } - /** Attempts to find this texture's image file locally, and if that fails attempts to find it remotely. */ - protected static class RequestTask implements Runnable - { - /** The BasicWWTexture associated with this request. */ + /** + * Attempts to find this texture's image file locally, and if that fails attempts to find it remotely. + */ + protected static class RequestTask implements Runnable { + + /** + * The BasicWWTexture associated with this request. + */ protected final LazilyLoadedTexture wwTexture; /** @@ -545,10 +534,8 @@ protected static class RequestTask implements Runnable * * @param wwTexture the texture object for which to construct the request task. */ - protected RequestTask(LazilyLoadedTexture wwTexture) - { - if (wwTexture == null) - { + protected RequestTask(LazilyLoadedTexture wwTexture) { + if (wwTexture == null) { String message = Logging.getMessage("nullValue.TextureIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -557,41 +544,37 @@ protected RequestTask(LazilyLoadedTexture wwTexture) this.wwTexture = wwTexture; } - public void run() - { - if (Thread.currentThread().isInterrupted()) + public void run() { + if (Thread.currentThread().isInterrupted()) { return; // the task was cancelled because it's a duplicate or for some other reason - + } URL fileUrl = this.wwTexture.fileStore.requestFile(this.wwTexture.getImageSource().toString()); - if (fileUrl != null) - { - if (this.wwTexture.loadTextureData(fileUrl)) - { + if (fileUrl != null) { + if (this.wwTexture.loadTextureData(fileUrl)) { this.wwTexture.notifyTextureLoaded(); } } } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final RequestTask that = (RequestTask) o; return !(this.wwTexture != null ? !this.wwTexture.equals(that.wwTexture) : that.wwTexture != null); } - public int hashCode() - { + public int hashCode() { return (this.wwTexture != null ? this.wwTexture.hashCode() : 0); } - public String toString() - { + public String toString() { return this.wwTexture.getImageSource().toString(); } } @@ -604,16 +587,15 @@ public String toString() * * @return true if the image was successfully loaded, otherwise false. */ - protected boolean loadTextureData(URL fileUrl) - { + protected boolean loadTextureData(URL fileUrl) { TextureData td; - synchronized (this.fileLock) - { + synchronized (this.fileLock) { td = readImage(fileUrl); - if (td != null) + if (td != null) { this.setTextureData(td); + } } return this.getTextureData() != null; @@ -626,16 +608,12 @@ protected boolean loadTextureData(URL fileUrl) * * @return a TextureData instance for the image. */ - protected TextureData readImage(URL fileUrl) - { - try - { + protected TextureData readImage(URL fileUrl) { + try { return OGLUtil.newTextureData(Configuration.getMaxCompatibleGLProfile(), fileUrl, this.isUseMipMaps()); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("layers.TextureLayer.ExceptionAttemptingToReadTextureFile", - this.getImageSource()); + this.getImageSource()); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.textureInitializationFailed = true; return null; @@ -643,25 +621,26 @@ protected TextureData readImage(URL fileUrl) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } LazilyLoadedTexture that = (LazilyLoadedTexture) o; //noinspection RedundantIfStatement - if (imageSource != null ? !imageSource.equals(that.imageSource) : that.imageSource != null) + if (imageSource != null ? !imageSource.equals(that.imageSource) : that.imageSource != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { return imageSource != null ? imageSource.hashCode() : 0; } } diff --git a/src/gov/nasa/worldwind/render/LightingModel.java b/src/gov/nasa/worldwind/render/LightingModel.java index a9e587e8eb..dc80eeb2fc 100644 --- a/src/gov/nasa/worldwind/render/LightingModel.java +++ b/src/gov/nasa/worldwind/render/LightingModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; /** @@ -12,8 +11,8 @@ * @author tag * @version $Id: LightingModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface LightingModel -{ +public interface LightingModel { + /** * Initializes the OpenGL state necessary to effect the lighting model. * diff --git a/src/gov/nasa/worldwind/render/Material.java b/src/gov/nasa/worldwind/render/Material.java index 91e8383eca..38734ec06d 100644 --- a/src/gov/nasa/worldwind/render/Material.java +++ b/src/gov/nasa/worldwind/render/Material.java @@ -14,8 +14,8 @@ * @author tag * @version $Id: Material.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Material -{ +public class Material { + private final Color ambient; private final Color diffuse; private final Color specular; @@ -36,10 +36,8 @@ public class Material public static final Material CYAN = new Material(Color.CYAN); public static final Material BLUE = new Material(Color.BLUE); - public Material(Color specular, Color diffuse, Color ambient, Color emission, float shininess) - { - if (specular == null || diffuse == null || ambient == null || emission == null) - { + public Material(Color specular, Color diffuse, Color ambient, Color emission, float shininess) { + if (specular == null || diffuse == null || ambient == null || emission == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -52,10 +50,8 @@ public Material(Color specular, Color diffuse, Color ambient, Color emission, fl this.shininess = shininess; } - public Material(Color color, float shininess) - { - if (color == null) - { + public Material(Color color, float shininess) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -68,10 +64,8 @@ public Material(Color color, float shininess) this.shininess = shininess; } - public Material(Color color) - { - if (color == null) - { + public Material(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -84,35 +78,28 @@ public Material(Color color) this.shininess = 80.0f; } - public final Color getAmbient() - { + public final Color getAmbient() { return this.ambient; } - public final Color getDiffuse() - { + public final Color getDiffuse() { return this.diffuse; } - public final Color getSpecular() - { + public final Color getSpecular() { return this.specular; } - public final Color getEmission() - { + public final Color getEmission() { return this.emission; } - public final double getShininess() - { + public final double getShininess() { return this.shininess; } - public void apply(GL2 gl, int face) - { - if (gl == null) - { + public void apply(GL2 gl, int face) { + if (gl == null) { String msg = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -125,10 +112,8 @@ public void apply(GL2 gl, int face) gl.glMaterialf(face, GL2.GL_SHININESS, (float) this.shininess); } - public void apply(GL2 gl, int face, float alpha) - { - if (gl == null) - { + public void apply(GL2 gl, int face, float alpha) { + if (gl == null) { String msg = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -143,16 +128,13 @@ public void apply(GL2 gl, int face, float alpha) gl.glMaterialf(face, GL2.GL_SHININESS, (float) this.shininess); } - protected void glMaterial(GL2 gl, int face, int name, Color color) - { - if (gl == null) - { + protected void glMaterial(GL2 gl, int face, int name, Color color) { + if (gl == null) { String msg = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (color == null) - { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -163,16 +145,13 @@ protected void glMaterial(GL2 gl, int face, int name, Color color) gl.glMaterialfv(face, name, compArray, 0); } - protected void glMaterial(GL2 gl, int face, int name, Color color, float alpha) - { - if (gl == null) - { + protected void glMaterial(GL2 gl, int face, int name, Color color, float alpha) { + if (gl == null) { String msg = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (color == null) - { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -193,7 +172,6 @@ protected void glMaterial(GL2 gl, int face, int name, Color color, float alpha) // compArray[2] = compArray[2] * compArray[3]; // gl.glMaterialfv(face, name, compArray, 0); //} - //protected void glMaterialfvPremult(GL2 gl, int face, int name, Color color, float alpha) //{ // float[] compArray = new float[4]; @@ -204,11 +182,8 @@ protected void glMaterial(GL2 gl, int face, int name, Color color, float alpha) // compArray[3] = alpha; // gl.glMaterialfv(face, name, compArray, 0); //} - - protected Color makeDarker(Color color) - { - if (color == null) - { + protected Color makeDarker(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -221,89 +196,101 @@ protected Color makeDarker(Color color) int a = color.getAlpha(); return new Color( - Math.max(0, (int) (r * factor)), - Math.max(0, (int) (g * factor)), - Math.max(0, (int) (b * factor)), - a); + Math.max(0, (int) (r * factor)), + Math.max(0, (int) (g * factor)), + Math.max(0, (int) (b * factor)), + a); } - public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject so) - { + public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject so) { String encodedColor = RestorableSupport.encodeColor(this.ambient); - if (encodedColor != null) + if (encodedColor != null) { rs.addStateValueAsString(so, "ambient", encodedColor); + } encodedColor = RestorableSupport.encodeColor(this.diffuse); - if (encodedColor != null) + if (encodedColor != null) { rs.addStateValueAsString(so, "diffuse", encodedColor); + } encodedColor = RestorableSupport.encodeColor(this.specular); - if (encodedColor != null) + if (encodedColor != null) { rs.addStateValueAsString(so, "specular", encodedColor); + } encodedColor = RestorableSupport.encodeColor(this.emission); - if (encodedColor != null) + if (encodedColor != null) { rs.addStateValueAsString(so, "emission", encodedColor); + } rs.addStateValueAsDouble(so, "shininess", this.shininess); } - public Material restoreState(RestorableSupport rs, RestorableSupport.StateObject so) - { + public Material restoreState(RestorableSupport rs, RestorableSupport.StateObject so) { double shininess = this.getShininess(); Double d = rs.getStateValueAsDouble(so, "shininess"); - if (d != null) + if (d != null) { shininess = d; + } String as = rs.getStateValueAsString(so, "ambient"); Color ambient = RestorableSupport.decodeColor(as); - if (ambient == null) + if (ambient == null) { ambient = this.getAmbient(); + } String ds = rs.getStateValueAsString(so, "diffuse"); Color diffuse = RestorableSupport.decodeColor(ds); - if (diffuse == null) + if (diffuse == null) { diffuse = this.getDiffuse(); + } String ss = rs.getStateValueAsString(so, "specular"); Color specular = RestorableSupport.decodeColor(ss); - if (specular == null) + if (specular == null) { specular = this.getSpecular(); + } String es = rs.getStateValueAsString(so, "emission"); Color emission = RestorableSupport.decodeColor(es); - if (emission == null) + if (emission == null) { emission = this.getEmission(); + } return new Material(specular, diffuse, ambient, emission, (float) shininess); } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } Material that = (Material) o; - if (Double.compare(this.shininess, that.shininess) != 0) + if (Double.compare(this.shininess, that.shininess) != 0) { return false; - if (this.ambient != null ? !this.ambient.equals(that.ambient) : that.ambient != null) + } + if (this.ambient != null ? !this.ambient.equals(that.ambient) : that.ambient != null) { return false; - if (this.diffuse != null ? !this.diffuse.equals(that.diffuse) : that.diffuse != null) + } + if (this.diffuse != null ? !this.diffuse.equals(that.diffuse) : that.diffuse != null) { return false; - if (this.specular != null ? !this.specular.equals(that.specular) : that.specular != null) + } + if (this.specular != null ? !this.specular.equals(that.specular) : that.specular != null) { return false; + } //noinspection RedundantIfStatement - if (this.emission != null ? !this.emission.equals(that.emission) : that.emission != null) + if (this.emission != null ? !this.emission.equals(that.emission) : that.emission != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result; long temp = (this.shininess != +0.0d) ? Double.doubleToLongBits(this.shininess) : 0L; result = (int) (temp ^ (temp >>> 32)); diff --git a/src/gov/nasa/worldwind/render/MultiLineTextRenderer.java b/src/gov/nasa/worldwind/render/MultiLineTextRenderer.java index 456dcdafcf..d66b47aedf 100644 --- a/src/gov/nasa/worldwind/render/MultiLineTextRenderer.java +++ b/src/gov/nasa/worldwind/render/MultiLineTextRenderer.java @@ -17,23 +17,32 @@ import java.util.regex.*; /** - * Multi line, rectangle bound text renderer with (very) minimal html support.

          The {@link MultiLineTextRenderer} - * (MLTR) handles wrapping, measuring and drawing of multiline text strings using Sun's JOGL {@link TextRenderer}.

          - *

          A multiline text string is a character string containing new line characters in between lines.

          MLTR can - * handle both regular text with new line separators and a very minimal implementation of HTML. Each type of text has - * its own methods though.

          Usage:

          Instantiation:

          The MLTR needs a Font or a - * TextRenderer to be instantiated. This will be the font used for text drawing, wrapping and measuring. For HTML - * methods this font will be considered as the document default font.

          + * Multi line, rectangle bound text renderer with (very) minimal html support. + *

          + * The {@link MultiLineTextRenderer} (MLTR) handles wrapping, measuring and drawing of multiline text strings using + * Sun's JOGL {@link TextRenderer}.

          + *

          + * A multiline text string is a character string containing new line characters in between lines.

          + *

          + * MLTR can handle both regular text with new line separators and a very minimal implementation of HTML. Each type of + * text has its own methods though.

          + *

          + * Usage:

          + *

          + * Instantiation:

          + *

          + * The MLTR needs a Font or a TextRenderer to be instantiated. This will be the font used for text drawing, wrapping and + * measuring. For HTML methods this font will be considered as the document default font.

          *
            * Font font = Font.decode("Arial-PLAIN-12");
            * MultiLineTextRenderer mltr = new MultiLineTextRenderer(font);
          - * 
          - * or + * or *
            * TextRenderer tr = new TextRenderer(Font.decode("Arial-PLAIN-10"));
            * MultiLineTextRenderer mltr = new MultiLineTextRenderer(tr);
            * 
          - *

          Drawing regular text:

          + *

          + * Drawing regular text:

          *
            * String text = "Line one.\nLine two.\nLine three...";
            * int x = 10;             // Upper left corner of text rectangle.
          @@ -45,33 +54,45 @@
            * mltr.draw(text, x, y, lineHeight);
            * mltr.getTextRenderer().end3DRendering();
            * 
          - *

          Wrapping text to fit inside a width and optionally a height

          The MLTR wrap method will insert new line - * characters inside the text so that it fits a given width in pixels.

          If a height dimension above zero is - * specified too, the text will be truncated if needed, and a continuation string will be appended to the last line. The - * continuation string can be set with mltr.setContinuationString();

          + *

          + * Wrapping text to fit inside a width and optionally a height

          + *

          + * The MLTR wrap method will insert new line characters inside the text so that it fits a given width in pixels.

          + *

          + * If a height dimension above zero is specified too, the text will be truncated if needed, and a continuation string + * will be appended to the last line. The continuation string can be set with mltr.setContinuationString();

          *
            * // Fit inside 300 pixels, no height constraint
            * String wrappedText = mltr.wrap(text, new Dimension(300, 0));
            * // Fit inside 300x400 pixels, text may be truncated
            * String wrappedText = mltr.wrap(text, new Dimension(300, 400));
            * 
          - *

          Measuring text

          + *

          + * Measuring text

          *
            * Rectangle2D textBounds = mltr.getBounds(text);
            * 
          - *

          The textBounds rectangle returned contains the width and height of the text as it would be drawn with the current - * font.

          Note that textBounds.minX is the number of lines found and textBounds.minY is the maximum line height - * for the font used. This value can be safely used as the lineHeight argument when drawing - or can even be ommited - * after a getBounds: draw(text, x, y); ...

          HTML support

          Supported tags are:

            + *

            + * The textBounds rectangle returned contains the width and height of the text as it would be drawn with the current + * font.

            + *

            + * Note that textBounds.minX is the number of lines found and textBounds.minY is the maximum line height for the font + * used. This value can be safely used as the lineHeight argument when drawing - or can even be ommited after a + * getBounds: draw(text, x, y); ...

            + *

            + * HTML support

            + *

            + * Supported tags are:

              *
            • <p></p>, <br> <br />
            • <b></b>
            • <i></i>
            • - *
            • <a href="..."></a>
            • <font color="#ffffff"></font>
            ... - *

            See {@link AbstractAnnotation}.drawAnnotation() for more usage details.

            + *
          • <a href="..."></a>
          • <font color="#ffffff"></font>
          ... + *

          + * See {@link AbstractAnnotation}.drawAnnotation() for more usage details.

          * * @author Patrick Murris * @version $Id: MultiLineTextRenderer.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class MultiLineTextRenderer -{ +public class MultiLineTextRenderer { + protected TextRenderer textRenderer; protected int lineSpacing = 0; // Inter line spacing in pixels protected int lineHeight = 14; // Will be set by getBounds() or by application @@ -88,10 +109,8 @@ public class MultiLineTextRenderer protected Object pickObject; protected Position pickPosition; - public MultiLineTextRenderer(TextRenderer textRenderer) - { - if (textRenderer == null) - { + public MultiLineTextRenderer(TextRenderer textRenderer) { + if (textRenderer == null) { String msg = Logging.getMessage("nullValue.TextRendererIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -99,10 +118,8 @@ public MultiLineTextRenderer(TextRenderer textRenderer) this.textRenderer = textRenderer; } - public MultiLineTextRenderer(Font font) - { - if (font == null) - { + public MultiLineTextRenderer(Font font) { + if (font == null) { String msg = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -116,8 +133,7 @@ public MultiLineTextRenderer(Font font) * * @return the current TextRenderer. */ - public TextRenderer getTextRenderer() - { + public TextRenderer getTextRenderer() { return this.textRenderer; } @@ -126,8 +142,7 @@ public TextRenderer getTextRenderer() * * @return the current line spacing height in pixels. */ - public int getLineSpacing() - { + public int getLineSpacing() { return this.lineSpacing; } @@ -136,8 +151,7 @@ public int getLineSpacing() * * @param height the line spacing height in pixels. */ - public void setLineSpacing(int height) - { + public void setLineSpacing(int height) { this.lineSpacing = height; } @@ -146,8 +160,7 @@ public void setLineSpacing(int height) * * @return the current line height in pixels. */ - public int getLineHeight() - { + public int getLineHeight() { return this.lineHeight; } @@ -156,8 +169,7 @@ public int getLineHeight() * * @param height the current line height in pixels. */ - public void setLineHeight(int height) - { + public void setLineHeight(int height) { this.lineHeight = height; } @@ -167,8 +179,7 @@ public void setLineHeight(int height) * * @return the current text alignment. */ - public String getTextAlign() - { + public String getTextAlign() { return this.textAlign; } @@ -178,10 +189,8 @@ public String getTextAlign() * * @param align the current text alignment. */ - public void setTextAlign(String align) - { - if (!align.equals(AVKey.LEFT) && !align.equals(AVKey.CENTER) && !align.equals(AVKey.RIGHT)) - { + public void setTextAlign(String align) { + if (!align.equals(AVKey.LEFT) && !align.equals(AVKey.CENTER) && !align.equals(AVKey.RIGHT)) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", align); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -194,8 +203,7 @@ public void setTextAlign(String align) * * @return the current text color. */ - public Color getTextColor() - { + public Color getTextColor() { return this.textColor; } @@ -204,10 +212,8 @@ public Color getTextColor() * * @param color the color to use when drawing text. */ - public void setTextColor(Color color) - { - if (color == null) - { + public void setTextColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -221,8 +227,7 @@ public void setTextColor(Color color) * * @return the current background color used when drawing shadow or outline.. */ - public Color getBackColor() - { + public Color getBackColor() { return this.backColor; } @@ -231,10 +236,8 @@ public Color getBackColor() * * @param color the color to use when drawing shadow or outline. */ - public void setBackColor(Color color) - { - if (color == null) - { + public void setBackColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -247,8 +250,7 @@ public void setBackColor(Color color) * * @return the current link color. */ - public Color getLinkColor() - { + public Color getLinkColor() { return this.linkColor; } @@ -257,10 +259,8 @@ public Color getLinkColor() * * @param color the color to use when drawing hyperlinks. */ - public void setLinkColor(Color color) - { - if (color == null) - { + public void setLinkColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -274,8 +274,7 @@ public void setLinkColor(Color color) * * @param s the continuation character string. */ - public void setContinuationString(String s) - { + public void setContinuationString(String s) { this.continuationString = s; } @@ -286,15 +285,13 @@ public void setContinuationString(String s) * * @return the maximum line height. */ - public double getMaxLineHeight(TextRenderer tr) - { + public double getMaxLineHeight(TextRenderer tr) { // Check underscore + capital E with acute accent return tr.getBounds("_\u00c9").getHeight(); } //** Plain text support ****************************************************** //**************************************************************************** - /** * Returns the bounding rectangle for a multi-line string. *

          @@ -307,10 +304,8 @@ public double getMaxLineHeight(TextRenderer tr) * * @return the bounding rectangle for the string. */ - public Rectangle getBounds(String text) - { - if (text == null) - { + public Rectangle getBounds(String text) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -319,8 +314,7 @@ public Rectangle getBounds(String text) int width = 0; int maxLineHeight = 0; String[] lines = text.split("\n"); - for (String line : lines) - { + for (String line : lines) { Rectangle2D lineBounds = this.textRenderer.getBounds(line); width = (int) Math.max(lineBounds.getWidth(), width); maxLineHeight = (int) Math.max(lineBounds.getHeight(), lineHeight); @@ -331,7 +325,7 @@ public Rectangle getBounds(String text) this.lineHeight = maxLineHeight; // Compute final height using maxLineHeight and number of lines return new Rectangle(lines.length, lineHeight, width, - lines.length * maxLineHeight + (lines.length - 1) * this.lineSpacing); + lines.length * maxLineHeight + (lines.length - 1) * this.lineSpacing); } /** @@ -341,11 +335,10 @@ public Rectangle getBounds(String text) * Uses the current line height. * * @param text the multi-line text to draw. - * @param x the x position for top left corner of text rectangle. - * @param y the y position for top left corner of the text rectangle. + * @param x the x position for top left corner of text rectangle. + * @param y the y position for top left corner of the text rectangle. */ - public void draw(String text, int x, int y) - { + public void draw(String text, int x, int y) { this.draw(text, x, y, this.lineHeight); } @@ -355,14 +348,13 @@ public void draw(String text, int x, int y) *

          * Uses the current line height and the given effect. * - * @param text the multi-line text to draw. - * @param x the x position for top left corner of text rectangle. - * @param y the y position for top left corner of the text rectangle. + * @param text the multi-line text to draw. + * @param x the x position for top left corner of text rectangle. + * @param y the y position for top left corner of the text rectangle. * @param effect the effect to use for the text rendering. Can be one of EFFECT_NONE, - * EFFECT_SHADOW or EFFECT_OUTLINE. + * EFFECT_SHADOW or EFFECT_OUTLINE. */ - public void draw(String text, int x, int y, String effect) - { + public void draw(String text, int x, int y, String effect) { this.draw(text, x, y, this.lineHeight, effect); } @@ -372,30 +364,25 @@ public void draw(String text, int x, int y, String effect) *

          * Uses the given line height and effect. * - * @param text the multi-line text to draw. - * @param x the x position for top left corner of text rectangle. - * @param y the y position for top left corner of the text rectangle. + * @param text the multi-line text to draw. + * @param x the x position for top left corner of text rectangle. + * @param y the y position for top left corner of the text rectangle. * @param textLineHeight the line height in pixels. - * @param effect the effect to use for the text rendering. Can be one of EFFECT_NONE, - * EFFECT_SHADOW or EFFECT_OUTLINE. + * @param effect the effect to use for the text rendering. Can be one of EFFECT_NONE, + * EFFECT_SHADOW or EFFECT_OUTLINE. */ - public void draw(String text, int x, int y, int textLineHeight, String effect) - { - if (effect == null) - { + public void draw(String text, int x, int y, int textLineHeight, String effect) { + if (effect == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (effect.equals(AVKey.TEXT_EFFECT_SHADOW)) - { + if (effect.equals(AVKey.TEXT_EFFECT_SHADOW)) { this.textRenderer.setColor(backColor); this.draw(text, x + 1, y - 1, textLineHeight); this.textRenderer.setColor(textColor); - } - else if (effect.equals(AVKey.TEXT_EFFECT_OUTLINE)) - { + } else if (effect.equals(AVKey.TEXT_EFFECT_OUTLINE)) { this.textRenderer.setColor(backColor); this.draw(text, x, y + 1, textLineHeight); this.draw(text, x + 1, y, textLineHeight); @@ -413,28 +400,26 @@ else if (effect.equals(AVKey.TEXT_EFFECT_OUTLINE)) *

          * Uses the given line height. * - * @param text the multi-line text to draw. - * @param x the x position for top left corner of text rectangle. - * @param y the y position for top left corner of the text rectangle. + * @param text the multi-line text to draw. + * @param x the x position for top left corner of text rectangle. + * @param y the y position for top left corner of the text rectangle. * @param textLineHeight the line height in pixels. */ - public void draw(String text, int x, int y, int textLineHeight) - { - if (text == null) - { + public void draw(String text, int x, int y, int textLineHeight) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } String[] lines = text.split("\n"); - for (String line : lines) - { + for (String line : lines) { int xAligned = x; - if (this.textAlign.equals(AVKey.CENTER)) + if (this.textAlign.equals(AVKey.CENTER)) { xAligned = x - (int) (this.textRenderer.getBounds(line).getWidth() / 2); - else if (this.textAlign.equals(AVKey.RIGHT)) + } else if (this.textAlign.equals(AVKey.RIGHT)) { xAligned = x - (int) (this.textRenderer.getBounds(line).getWidth()); + } y -= textLineHeight; this.textRenderer.draw3D(line, xAligned, y, 0, 1); y -= this.lineSpacing; @@ -445,45 +430,41 @@ else if (this.textAlign.equals(AVKey.RIGHT)) * Draw text with unique colors word bounding rectangles and add each as a pickable object to the provided * PickSupport instance. * - * @param text the multi-line text to draw. - * @param x the x position for top left corner of text rectangle. - * @param y the y position for top left corner of the text rectangle. + * @param text the multi-line text to draw. + * @param x the x position for top left corner of text rectangle. + * @param y the y position for top left corner of the text rectangle. * @param textLineHeight the line height in pixels. - * @param dc the current DrawContext. - * @param pickSupport the PickSupport instance to be used. - * @param refObject the user reference object associated with every picked word. - * @param refPosition the user reference Position associated with every picked word. + * @param dc the current DrawContext. + * @param pickSupport the PickSupport instance to be used. + * @param refObject the user reference object associated with every picked word. + * @param refPosition the user reference Position associated with every picked word. */ public void pick(String text, int x, int y, int textLineHeight, - DrawContext dc, PickSupport pickSupport, Object refObject, Position refPosition) - { - if (text == null) - { + DrawContext dc, PickSupport pickSupport, Object refObject, Position refPosition) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (pickSupport == null) - { + if (pickSupport == null) { String msg = Logging.getMessage("nullValue.PickSupportIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } String[] lines = text.split("\n"); - for (String line : lines) - { + for (String line : lines) { int xAligned = x; - if (this.textAlign.equals(AVKey.CENTER)) + if (this.textAlign.equals(AVKey.CENTER)) { xAligned = x - (int) (this.textRenderer.getBounds(line).getWidth() / 2); - else if (this.textAlign.equals(AVKey.RIGHT)) + } else if (this.textAlign.equals(AVKey.RIGHT)) { xAligned = x - (int) (this.textRenderer.getBounds(line).getWidth()); + } y -= textLineHeight; drawLineWithUniqueColors(line, xAligned, y, dc, pickSupport, refObject, refPosition); y -= this.lineSpacing; @@ -491,8 +472,7 @@ else if (this.textAlign.equals(AVKey.RIGHT)) } protected void drawLineWithUniqueColors(String text, int x, int y, - DrawContext dc, PickSupport pickSupport, Object refObject, Position refPosition) - { + DrawContext dc, PickSupport pickSupport, Object refObject, Position refPosition) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. //float spaceWidth = this.textRenderer.getCharWidth(' '); @@ -500,11 +480,10 @@ protected void drawLineWithUniqueColors(String text, int x, int y, String source = text.trim(); int start = 0; int end = source.indexOf(' ', start + 1); - while (start < source.length()) - { - if (end == -1) + while (start < source.length()) { + if (end == -1) { end = source.length(); // last word - // Extract a 'word' which is in fact a space and a word except for first word + } // Extract a 'word' which is in fact a space and a word except for first word String word = source.substring(start, end); // Measure word and already draw line part - from line beginning Rectangle2D wordBounds = this.textRenderer.getBounds(word); @@ -519,11 +498,10 @@ protected void drawLineWithUniqueColors(String text, int x, int y, // Draw word rectangle gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); drawFilledRectangle(dc, drawX + wordBounds.getX(), y - wordBounds.getHeight() - wordBounds.getY(), - wordBounds.getWidth(), wordBounds.getHeight()); + wordBounds.getWidth(), wordBounds.getHeight()); // Move forward in source string start = end; - if (start < source.length() - 1) - { + if (start < source.length() - 1) { end = source.indexOf(' ', start + 1); } } @@ -539,16 +517,14 @@ protected void drawLineWithUniqueColors(String text, int x, int y, * Note that words will not be split and at least one word will be used per line so the longest word defines the * final width of the bounding rectangle. Each line is trimmed of leading and trailing spaces. * - * @param text the text string to wrap - * @param width the maximum width in pixels the text can occupy. + * @param text the text string to wrap + * @param width the maximum width in pixels the text can occupy. * @param height if not zero, the maximum height in pixels the text can occupy. * * @return the wrapped string. */ - public String wrap(String text, int width, int height) - { - if (text == null) - { + public String wrap(String text, int width, int height) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -557,8 +533,7 @@ public String wrap(String text, int width, int height) String[] lines = text.split("\n"); StringBuffer wrappedText = new StringBuffer(); // Wrap each line - for (int i = 0; i < lines.length; i++) - { + for (int i = 0; i < lines.length; i++) { lines[i] = this.wrapLine(lines[i], width); } // Concatenate all lines in one string with new line separators @@ -567,90 +542,75 @@ public String wrap(String text, int width, int height) int currentHeight = 0; boolean heightExceeded = false; double maxLineHeight = getMaxLineHeight(this.textRenderer); - for (int i = 0; i < lines.length && !heightExceeded; i++) - { + for (int i = 0; i < lines.length && !heightExceeded; i++) { String[] subLines = lines[i].split("\n"); - for (int j = 0; j < subLines.length && !heightExceeded; j++) - { - if (height <= 0 || currentHeight + maxLineHeight <= height) - { + for (int j = 0; j < subLines.length && !heightExceeded; j++) { + if (height <= 0 || currentHeight + maxLineHeight <= height) { wrappedText.append(subLines[j]); currentHeight += maxLineHeight + this.lineSpacing; - if (j < subLines.length - 1) + if (j < subLines.length - 1) { wrappedText.append('\n'); - } - else - { + } + } else { heightExceeded = true; } } - if (i < lines.length - 1 && !heightExceeded) + if (i < lines.length - 1 && !heightExceeded) { wrappedText.append('\n'); + } } // Add continuation string if text truncated - if (heightExceeded) - { - if (wrappedText.length() > 0) + if (heightExceeded) { + if (wrappedText.length() > 0) { wrappedText.deleteCharAt(wrappedText.length() - 1); // Remove excess new line + } wrappedText.append(this.continuationString); } return wrappedText.toString(); } // Wrap one line to fit the given width - protected String wrapLine(String text, int width) - { + protected String wrapLine(String text, int width) { StringBuffer wrappedText = new StringBuffer(); // Single line - trim leading and trailing spaces String source = text.trim(); Rectangle2D lineBounds = this.textRenderer.getBounds(source); - if (lineBounds.getWidth() > width) - { + if (lineBounds.getWidth() > width) { // Split single line to fit preferred width StringBuffer line = new StringBuffer(); int start = 0; int end = source.indexOf(' ', start + 1); - while (start < source.length()) - { - if (end == -1) + while (start < source.length()) { + if (end == -1) { end = source.length(); // last word - // Extract a 'word' which is in fact a space and a word + } // Extract a 'word' which is in fact a space and a word String word = source.substring(start, end); String linePlusWord = line + word; - if (this.textRenderer.getBounds(linePlusWord).getWidth() <= width) - { + if (this.textRenderer.getBounds(linePlusWord).getWidth() <= width) { // Keep adding to the current line line.append(word); - } - else - { + } else { // Width exceeded - if (line.length() != 0) - { + if (line.length() != 0) { // Finish current line and start new one wrappedText.append(line); wrappedText.append('\n'); line.delete(0, line.length()); line.append(word.trim()); // get read of leading space(s) - } - else - { + } else { // Line is empty, force at least one word line.append(word.trim()); } } // Move forward in source string start = end; - if (start < source.length() - 1) - { + if (start < source.length() - 1) { end = source.indexOf(' ', start + 1); } } // Gather last line wrappedText.append(line); - } - else - { + } else { // Line doesn't need to be wrapped wrappedText.append(source); } @@ -661,7 +621,6 @@ protected String wrapLine(String text, int width) // Handles

          ,
          or
          , , , // and . //**************************************************************************** - protected static Pattern SGMLPattern = Pattern.compile("<[^\\s].*?>"); // Find sgml tags protected static Pattern SGMLOrSpacePattern = Pattern.compile("(<[^\\s].*?>)|(\\s)"); // Find sgml tags or spaces @@ -672,10 +631,8 @@ protected String wrapLine(String text, int width) * * @return true if the string contains sgml or html tags */ - public static boolean containsHTML(String text) - { - if (text == null) - { + public static boolean containsHTML(String text) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -692,10 +649,8 @@ public static boolean containsHTML(String text) * * @return The processed text string. */ - public static String processLineBreaksHTML(String text) - { - if (text == null) - { + public static String processLineBreaksHTML(String text) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -715,10 +670,8 @@ public static String processLineBreaksHTML(String text) * * @return the filtered string. */ - public static String removeTagsHTML(String text) - { - if (text == null) - { + public static String removeTagsHTML(String text) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -731,15 +684,13 @@ public static String removeTagsHTML(String text) * Extract an attribute value from a HTML tag string. The attribute is expected to be formed on the pattern: * name="...". Other variants will likely fail. * - * @param text the HTML tage string. + * @param text the HTML tage string. * @param attributeName the attribute name. * * @return the attribute value found. Null if empty or not found. */ - public static String getAttributeFromTagHTML(String text, String attributeName) - { - if (text == null || attributeName == null) - { + public static String getAttributeFromTagHTML(String text, String attributeName) { + if (text == null || attributeName == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -748,32 +699,29 @@ public static String getAttributeFromTagHTML(String text, String attributeName) // Look for name="..." - will not work for other variants Pattern pattern = Pattern.compile("(?i)" + attributeName.toLowerCase() + "=\"([^\"].*?)\""); Matcher matcher = pattern.matcher(text); - if (matcher.find()) + if (matcher.find()) { return matcher.group(1); + } return null; } // --- HTML Word iterator based methods -------------------------------- - /** * Returns the bounding rectangle for a multi-line html string. * - * @param text the multi-line html text to evaluate. + * @param text the multi-line html text to evaluate. * @param renderers a {@link TextRendererCache} instance. * * @return the bounding rectangle for the rendered text. */ - public Rectangle getBoundsHTML(String text, TextRendererCache renderers) - { - if (text == null) - { + public Rectangle getBoundsHTML(String text, TextRendererCache renderers) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (renderers == null) - { + if (renderers == null) { String msg = Logging.getMessage("nullValue.TextRendererCacheIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -783,13 +731,11 @@ public Rectangle getBoundsHTML(String text, TextRendererCache renderers) return getTextBoundsHTML(text, ds).getBounds(); } - protected Rectangle2D getTextBoundsHTML(String text, DrawState ds) - { + protected Rectangle2D getTextBoundsHTML(String text, DrawState ds) { double width = 0; double height = 0; String[] lines = text.split("\n"); - for (String line : lines) - { + for (String line : lines) { Rectangle2D lineBounds = getLineBoundsHTML(line, ds); width = Math.max(lineBounds.getWidth(), width); height += lineBounds.getHeight() + this.lineSpacing; @@ -799,39 +745,35 @@ protected Rectangle2D getTextBoundsHTML(String text, DrawState ds) return new Rectangle2D.Double(0, 0, width, height); } - protected Rectangle2D getLineBoundsHTML(String line, DrawState ds) - { + protected Rectangle2D getLineBoundsHTML(String line, DrawState ds) { double width = 0; double height = getMaxLineHeight(ds.textRenderer); Iterator wi = new WordIteratorHTML(line); - while (wi.hasNext()) - { + while (wi.hasNext()) { // Acumulate words dimensions Rectangle2D wordBounds = getWordBoundsHTML((String) wi.next(), ds); width += wordBounds.getWidth(); height = Math.max(wordBounds.getHeight(), height); // Count a space between words - not after last. - if (wi.hasNext()) + if (wi.hasNext()) { width += ds.textRenderer.getCharWidth(' '); + } } return new Rectangle2D.Double(0, 0, width, height); } - protected Rectangle2D getWordBoundsHTML(String word, DrawState ds) - { + protected Rectangle2D getWordBoundsHTML(String word, DrawState ds) { double width = 0; double height = getMaxLineHeight(ds.textRenderer); int start = 0; String part; Rectangle2D partBounds; Matcher matcher = SGMLOrSpacePattern.matcher(word); // html tags or spaces - while (matcher.find()) - { - if (!matcher.group().equals(" ")) // html tag - not a space + while (matcher.find()) { + if (!matcher.group().equals(" ")) // html tag - not a space { - if (matcher.start() > start) - { + if (matcher.start() > start) { // Measure part part = word.substring(start, matcher.start()); partBounds = ds.textRenderer.getBounds(part); @@ -843,8 +785,7 @@ protected Rectangle2D getWordBoundsHTML(String word, DrawState ds) start = matcher.end(); } } - if (start < word.length()) - { + if (start < word.length()) { // Measure remaining part if any part = word.substring(start, word.length()); partBounds = ds.textRenderer.getBounds(part); @@ -864,23 +805,20 @@ protected Rectangle2D getWordBoundsHTML(String word, DrawState ds) * Note that words will not be split and at least one word will be used per line so the longest word defines the * final width of the bounding rectangle. Each line is trimmed of leading and trailing spaces. * - * @param text the html text string to wrap - * @param width the maximum width in pixels one text line can occupy. - * @param height if not zero, the maximum height the text can occupy. + * @param text the html text string to wrap + * @param width the maximum width in pixels one text line can occupy. + * @param height if not zero, the maximum height the text can occupy. * @param renderers a {@link TextRendererCache} instance. * * @return the wrapped html string */ - public String wrapHTML(String text, double width, double height, TextRendererCache renderers) - { - if (text == null) - { + public String wrapHTML(String text, double width, double height, TextRendererCache renderers) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (renderers == null) - { + if (renderers == null) { String msg = Logging.getMessage("nullValue.TextRendererCacheIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -890,41 +828,35 @@ public String wrapHTML(String text, double width, double height, TextRendererCac return wrapTextHTML(text, width, height, ds); } - protected String wrapTextHTML(String text, double width, double height, DrawState ds) - { + protected String wrapTextHTML(String text, double width, double height, DrawState ds) { // Save passed draw state in case we need to trim text later DrawState savedState = new DrawState(ds); StringBuffer wrappedText = new StringBuffer(); String[] lines = text.split("\n"); - for (String line : lines) - { + for (String line : lines) { wrappedText.append(wrappedText.length() > 0 ? "\n" : ""); wrappedText.append(wrapLineHTML(line, width, ds)); } - if (height > 0) + if (height > 0) { return trimTextHTML(wrappedText.toString(), height, savedState); + } return wrappedText.toString(); } - protected String trimTextHTML(String text, double height, DrawState ds) - { + protected String trimTextHTML(String text, double height, DrawState ds) { StringBuffer wrappedText = new StringBuffer(); double currentHeight = 0; String[] lines = text.split("\n"); - for (String line : lines) - { + for (String line : lines) { Rectangle2D lineBounds = getLineBoundsHTML(line, ds); - if (currentHeight + lineBounds.getHeight() <= height) - { + if (currentHeight + lineBounds.getHeight() <= height) { wrappedText.append(wrappedText.length() > 0 ? "\n" : ""); wrappedText.append(line); currentHeight += lineBounds.getHeight() + this.lineSpacing; - } - else - { + } else { // Text is longer then allowed. Truncate and add continuation string wrappedText.append(this.continuationString); break; @@ -934,34 +866,30 @@ protected String trimTextHTML(String text, double height, DrawState ds) return wrappedText.toString(); } - protected String wrapLineHTML(String line, double width, DrawState ds) - { + protected String wrapLineHTML(String line, double width, DrawState ds) { // Save passed draw state in case we need to wrap DrawState savedState = new DrawState(ds); // Measure line - note this updates the caller draw state Rectangle2D lineBounds = getLineBoundsHTML(line, ds); - if (lineBounds.getWidth() <= width) + if (lineBounds.getWidth() <= width) { return line; + } // The line needs to be wrapped double spaceWidth, wordWidth, lineWidth = 0; StringBuffer wrappedText = new StringBuffer(); WordIteratorHTML wi = new WordIteratorHTML(line); - while (wi.hasNext()) - { + while (wi.hasNext()) { String word = wi.next(); spaceWidth = savedState.textRenderer.getCharWidth(' '); wordWidth = getWordBoundsHTML(word, savedState).getWidth(); - if (lineWidth == 0 || lineWidth + wordWidth + (lineWidth > 0 ? spaceWidth : 0) <= width) - { + if (lineWidth == 0 || lineWidth + wordWidth + (lineWidth > 0 ? spaceWidth : 0) <= width) { // Add space and word to line wrappedText.append(lineWidth > 0 ? " " : ""); wrappedText.append(word); lineWidth += wordWidth + (lineWidth > 0 ? spaceWidth : 0); - } - else - { + } else { // Width exceeded, start new line wrappedText.append("\n"); wrappedText.append(word); @@ -976,26 +904,23 @@ protected String wrapLineHTML(String line, double width, DrawState ds) * Draw text with unique colors word bounding rectangles and add each as a pickable object to the provided * PickSupport instance. * - * @param text the multi-line text to draw. - * @param x the x position for top left corner of text rectangle. - * @param y the y position for top left corner of the text rectangle. - * @param renderers a {@link TextRendererCache} instance. - * @param dc the current DrawContext. + * @param text the multi-line text to draw. + * @param x the x position for top left corner of text rectangle. + * @param y the y position for top left corner of the text rectangle. + * @param renderers a {@link TextRendererCache} instance. + * @param dc the current DrawContext. * @param pickSupport the PickSupport instance to be used. - * @param refObject the user reference object associated with every picked word. + * @param refObject the user reference object associated with every picked word. * @param refPosition the user reference Position associated with every picked word. */ public void pickHTML(String text, int x, int y, TextRendererCache renderers, DrawContext dc, - PickSupport pickSupport, Object refObject, Position refPosition) - { - if (dc == null) - { + PickSupport pickSupport, Object refObject, Position refPosition) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (pickSupport == null) - { + if (pickSupport == null) { String msg = Logging.getMessage("nullValue.PickSupportIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1009,12 +934,9 @@ public void pickHTML(String text, int x, int y, TextRendererCache renderers, Dra this.isPicking = true; // Draw - try - { + try { drawHTML(text, x, y, renderers); - } - finally - { + } finally { this.isPicking = false; } } @@ -1023,21 +945,18 @@ public void pickHTML(String text, int x, int y, TextRendererCache renderers, Dra * Draw a multi-line html text string with bounding rectangle top starting at the y position. The x position is * eiher the rectangle left side, middle or right side depending on the current text alignement. * - * @param text the multi-line text to draw - * @param x the x position for top left corner of text rectangle - * @param y the y position for top left corner of the text rectangle + * @param text the multi-line text to draw + * @param x the x position for top left corner of text rectangle + * @param y the y position for top left corner of the text rectangle * @param renderers a {@link TextRendererCache} instance. */ - public void drawHTML(String text, double x, double y, TextRendererCache renderers) - { - if (text == null) - { + public void drawHTML(String text, double x, double y, TextRendererCache renderers) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (renderers == null) - { + if (renderers == null) { String msg = Logging.getMessage("nullValue.TextRendererCacheIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1048,26 +967,25 @@ public void drawHTML(String text, double x, double y, TextRendererCache renderer drawTextHTML(text, x, y, ds); } - protected void drawTextHTML(String text, double x, double y, DrawState ds) - { - if (!this.isPicking) + protected void drawTextHTML(String text, double x, double y, DrawState ds) { + if (!this.isPicking) { ds.textRenderer.begin3DRendering(); - try - { + } + try { ds.textRenderer.setColor(this.textColor); Rectangle2D lineBounds; double drawX, drawY = y; String[] lines = text.split("\n"); - for (String line : lines) - { + for (String line : lines) { // Set line start x drawX = x; lineBounds = getTextBoundsHTML(line, new DrawState(ds)); - if (this.textAlign.equals(AVKey.CENTER)) + if (this.textAlign.equals(AVKey.CENTER)) { drawX = x - lineBounds.getWidth() / 2; - else if (this.textAlign.equals(AVKey.RIGHT)) + } else if (this.textAlign.equals(AVKey.RIGHT)) { drawX = x - lineBounds.getWidth(); + } // Skip line height drawY -= lineBounds.getHeight(); @@ -1076,45 +994,40 @@ else if (this.textAlign.equals(AVKey.RIGHT)) // Skip line spacing drawY -= this.lineSpacing; } - } - finally - { - if (!this.isPicking) + } finally { + if (!this.isPicking) { ds.textRenderer.end3DRendering(); + } } } - protected void drawLineHTML(String line, double x, double y, DrawState ds) - { + protected void drawLineHTML(String line, double x, double y, DrawState ds) { String word; Rectangle2D wordBounds; WordIteratorHTML wi = new WordIteratorHTML(line); double drawX = x; - while (wi.hasNext()) - { + while (wi.hasNext()) { word = wi.next(); wordBounds = getWordBoundsHTML(word, new DrawState(ds)); - if (this.isPicking) + if (this.isPicking) { pickWordHTML(word, drawX, y, ds); - else + } else { drawWordHTML(word, drawX, y, ds); + } drawX += wordBounds.getWidth() + ds.textRenderer.getCharWidth(' '); } } - protected void drawWordHTML(String word, double x, double y, DrawState ds) - { + protected void drawWordHTML(String word, double x, double y, DrawState ds) { double drawX = x; int start = 0; String part; Rectangle2D partBounds; Matcher matcher = SGMLOrSpacePattern.matcher(word); // html tags or spaces - while (matcher.find()) - { - if (!matcher.group().equals(" ")) // html tag - not a space + while (matcher.find()) { + if (!matcher.group().equals(" ")) // html tag - not a space { - if (matcher.start() > start) - { + if (matcher.start() > start) { // Draw part part = word.substring(start, matcher.start()); partBounds = ds.textRenderer.getBounds(part); @@ -1126,28 +1039,24 @@ protected void drawWordHTML(String word, double x, double y, DrawState ds) start = matcher.end(); } } - if (start < word.length()) - { + if (start < word.length()) { // Draw remaining part if any part = word.substring(start, word.length()); ds.textRenderer.draw(part, (int) drawX, (int) y); } } - protected void pickWordHTML(String word, double x, double y, DrawState ds) - { + protected void pickWordHTML(String word, double x, double y, DrawState ds) { double drawX = x; int start = 0; String part; Rectangle2D partBounds; boolean expandStart = true; Matcher matcher = SGMLOrSpacePattern.matcher(word); // html tags or spaces - while (matcher.find()) - { - if (!matcher.group().equals(" ")) // html tag - not a space + while (matcher.find()) { + if (!matcher.group().equals(" ")) // html tag - not a space { - if (matcher.start() > start) - { + if (matcher.start() > start) { // Pick part part = word.substring(start, matcher.start()); partBounds = ds.textRenderer.getBounds(part); @@ -1160,8 +1069,7 @@ protected void pickWordHTML(String word, double x, double y, DrawState ds) start = matcher.end(); } } - if (start < word.length()) - { + if (start < word.length()) { // Pick remaining part if any part = word.substring(start, word.length()); partBounds = ds.textRenderer.getBounds(part); @@ -1170,33 +1078,28 @@ protected void pickWordHTML(String word, double x, double y, DrawState ds) } protected void pickWordPartHTML(String word, double x, double y, Rectangle2D partBounds, DrawState ds, - boolean expandStart) - { + boolean expandStart) { String hyperlink = ds.getDrawAttributes().hyperlink; // Extend pick rectangle width to fill a bit more then half a space before and after the word. // Extend height a little too. double spaceWidth = ds.textRenderer.getCharWidth(' ') * 1.5; double height = this.getMaxLineHeight(ds.textRenderer); Rectangle2D pickBounds; - if (expandStart) - { + if (expandStart) { pickBounds = new Rectangle2D.Double(0, 0, partBounds.getWidth() + partBounds.getX() + spaceWidth, - height * 1.1); + height * 1.1); x -= spaceWidth / 2; - } - else - { + } else { pickBounds = new Rectangle2D.Double(0, 0, partBounds.getWidth() + partBounds.getX() + spaceWidth / 2, - height * 1.1); + height * 1.1); } pickWord(word, hyperlink, x, y, pickBounds, - this.drawContext, this.pickSupport, this.pickObject, this.pickPosition); + this.drawContext, this.pickSupport, this.pickObject, this.pickPosition); } protected void pickWord(String word, String hyperlink, double drawX, double drawY, Rectangle2D wordBounds, - DrawContext dc, PickSupport pickSupport, Object refObject, Position refPosition) - { + DrawContext dc, PickSupport pickSupport, Object refObject, Position refPosition) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Add pickable object @@ -1204,18 +1107,18 @@ protected void pickWord(String word, String hyperlink, double drawX, double draw int colorCode = color.getRGB(); PickedObject po = new PickedObject(colorCode, refObject, refPosition, false); po.setValue(AVKey.TEXT, removeTagsHTML(word.trim())); - if (hyperlink != null) + if (hyperlink != null) { po.setValue(AVKey.URL, hyperlink); + } pickSupport.addPickableObject(po); // Draw word rectangle gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); - drawFilledRectangle(dc, drawX, drawY - wordBounds.getHeight() / 4, // TODO: handle font descent properly - wordBounds.getWidth(), wordBounds.getHeight()); + drawFilledRectangle(dc, drawX, drawY - wordBounds.getHeight() / 4, // TODO: handle font descent properly + wordBounds.getWidth(), wordBounds.getHeight()); } // Draw a filled rectangle - protected void drawFilledRectangle(DrawContext dc, double x, double y, double width, double height) - { + protected void drawFilledRectangle(DrawContext dc, double x, double y, double width, double height) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_POLYGON); gl.glVertex3d(x, y, 0); @@ -1227,75 +1130,68 @@ protected void drawFilledRectangle(DrawContext dc, double x, double y, double wi } // -- HTML word iterator ------------------------------------ - /** * Iterates through words from an HTML text line. Note that returned 'words' can contain html tags at any place, * before, inside or after the word. */ - public static class WordIteratorHTML implements Iterator - { + public static class WordIteratorHTML implements Iterator { + protected ArrayList words; protected int nextWord = -1; protected static Pattern SGMLOrSpacePattern = Pattern.compile("(<[^\\s].*?>)|(\\s)"); - public WordIteratorHTML(String text) - { + public WordIteratorHTML(String text) { Matcher matcher = SGMLOrSpacePattern.matcher(text); this.words = new ArrayList(); int start = 0; - while (matcher.find()) - { - if (matcher.group().equals(" ")) - { + while (matcher.find()) { + if (matcher.group().equals(" ")) { // Space found, add word to list addWord(text.substring(start, matcher.end())); start = matcher.end(); // move after space found } } // Add end of text if any - if (start < text.length()) + if (start < text.length()) { addWord(text.substring(start)); + } // Set next word index - if (this.words.size() > 0) + if (this.words.size() > 0) { this.nextWord = 0; + } } - protected void addWord(String word) - { + protected void addWord(String word) { word = word.trim(); - if (word.length() > 0) + if (word.length() > 0) { words.add(word); + } } - public boolean hasNext() - { + public boolean hasNext() { return this.nextWord != -1 && this.nextWord < words.size(); } - public String next() - { + public String next() { return words.get(this.nextWord++); } - public void remove() - { + public void remove() { } } // -- HTML Draw state handling ----------------------------------- + protected class DrawState { + + protected class DrawAttributes { - protected class DrawState - { - protected class DrawAttributes - { protected final Font font; protected String hyperlink; protected final Color color; - public DrawAttributes(Font font, String hyperlink, Color color) - { + public DrawAttributes(Font font, String hyperlink, Color color) { this.font = font; this.hyperlink = hyperlink; this.color = color; @@ -1307,150 +1203,124 @@ public DrawAttributes(Font font, String hyperlink, Color color) public TextRenderer textRenderer; protected Pattern SGMLPattern = Pattern.compile("(<[^\\s].*?>)"); - public DrawState(TextRendererCache renderers, Font font, String hyperlink, Color color) - { + public DrawState(TextRendererCache renderers, Font font, String hyperlink, Color color) { this.push(new DrawAttributes(font, hyperlink, color)); this.renderers = renderers; this.textRenderer = getTextRenderer(font); } - public DrawState(DrawState ds) - { - for (DrawAttributes da : ds.stack) - { + public DrawState(DrawState ds) { + for (DrawAttributes da : ds.stack) { this.push(new DrawAttributes(da.font, da.hyperlink, da.color)); } this.renderers = ds.renderers; this.textRenderer = ds.textRenderer; } - public DrawAttributes getDrawAttributes() - { - if (this.stack.size() < 1) + public DrawAttributes getDrawAttributes() { + if (this.stack.size() < 1) { return null; + } return this.stack.get(this.stack.size() - 1); } - protected TextRenderer getTextRenderer(Font font) - { + protected TextRenderer getTextRenderer(Font font) { return OGLTextRenderer.getOrCreateTextRenderer(this.renderers, font); } - protected Font getFont(Font font, boolean isBold, boolean isItalic) - { + protected Font getFont(Font font, boolean isBold, boolean isItalic) { int fontStyle = isBold ? (isItalic ? Font.BOLD | Font.ITALIC : Font.BOLD) - : (isItalic ? Font.ITALIC : Font.PLAIN); + : (isItalic ? Font.ITALIC : Font.PLAIN); return font.deriveFont(fontStyle); } // Update DrawState from html text - public void updateFromHTMLText(String text, boolean startStopRendering) - { + public void updateFromHTMLText(String text, boolean startStopRendering) { Matcher matcher = SGMLPattern.matcher(text); - while (matcher.find()) - { + while (matcher.find()) { updateFromHTMLTag(matcher.group(), startStopRendering); } } // Update DrawState from html tag - public void updateFromHTMLTag(String tag, boolean startStopRendering) - { + public void updateFromHTMLTag(String tag, boolean startStopRendering) { DrawAttributes da = getDrawAttributes(); boolean fontChanged = false; - if (tag.equalsIgnoreCase("")) - { + if (tag.equalsIgnoreCase("")) { this.push(new DrawAttributes(getFont(da.font, true, da.font.isItalic()), - da.hyperlink, da.color)); + da.hyperlink, da.color)); fontChanged = true; - } - else if (tag.equalsIgnoreCase("")) - { + } else if (tag.equalsIgnoreCase("")) { this.pop(); fontChanged = true; - } - else if (tag.equalsIgnoreCase("")) - { + } else if (tag.equalsIgnoreCase("")) { this.push(new DrawAttributes(getFont(da.font, da.font.isBold(), true), - da.hyperlink, da.color)); + da.hyperlink, da.color)); fontChanged = true; - } - else if (tag.equalsIgnoreCase("")) - { + } else if (tag.equalsIgnoreCase("")) { this.pop(); fontChanged = true; - } - else if (tag.toLowerCase().startsWith("")) - { + } + } else if (tag.equalsIgnoreCase("")) { this.pop(); - if (startStopRendering) + if (startStopRendering) { this.textRenderer.setColor(getDrawAttributes().color); - } - else if (tag.toLowerCase().startsWith("")) - { + } else if (tag.equalsIgnoreCase("")) { this.pop(); - if (startStopRendering) + if (startStopRendering) { this.textRenderer.setColor(getDrawAttributes().color); + } } - if (fontChanged) - { + if (fontChanged) { // Terminate current rendering - if (startStopRendering) + if (startStopRendering) { this.textRenderer.end3DRendering(); + } // Get new text renderer da = getDrawAttributes(); this.textRenderer = getTextRenderer(da.font); // Resume rendering - if (startStopRendering) - { + if (startStopRendering) { this.textRenderer.begin3DRendering(); this.textRenderer.setColor(da.color); } } } - protected void push(DrawAttributes da) - { + protected void push(DrawAttributes da) { this.stack.add(da); } - protected void pop() - { - if (this.stack.size() > 1) + protected void pop() { + if (this.stack.size() > 1) { this.stack.remove(this.stack.size() - 1); + } } - protected Color applyTextAlpha(Color color) - { + protected Color applyTextAlpha(Color color) { return new Color(color.getRed(), color.getGreen(), color.getBlue(), - color.getAlpha() * textColor.getAlpha() / 255); + color.getAlpha() * textColor.getAlpha() / 255); } } } diff --git a/src/gov/nasa/worldwind/render/MultiResolutionPath.java b/src/gov/nasa/worldwind/render/MultiResolutionPath.java index 00c0ffdb30..c9b3e34211 100644 --- a/src/gov/nasa/worldwind/render/MultiResolutionPath.java +++ b/src/gov/nasa/worldwind/render/MultiResolutionPath.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -28,21 +27,21 @@ * @deprecated */ @Deprecated -public class MultiResolutionPath extends Path -{ +public class MultiResolutionPath extends Path { + /** * This interface provides the means for the application to specify the algorithm used to determine the number of * specified positions skipped during path tessellation. *

          * This class overrides the method {@link Path#makePositions(DrawContext, PathData)}. */ - public interface SkipCountComputer - { + public interface SkipCountComputer { + /** * Determines the number of positions to skip for the current viewing state. Determines the number of positions * to skip for the current viewing state. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pathData this shape's current path data. * * @return the number of positions to skip when computing the tessellated or non-tessellated path. @@ -50,20 +49,23 @@ public interface SkipCountComputer public int computeSkipCount(DrawContext dc, PathData pathData); } - /** Subclass of PathData that adds the capability to map which ordinal number corresponds to each rendered position. */ - protected static class MultiResolutionPathData extends PathData - { - /** Maps indices of rendered positions to their corresponding ordinal numbers. */ + /** + * Subclass of PathData that adds the capability to map which ordinal number corresponds to each rendered position. + */ + protected static class MultiResolutionPathData extends PathData { + + /** + * Maps indices of rendered positions to their corresponding ordinal numbers. + */ protected IntBuffer positionOrdinals; /** * Creates a new MultiResolutionPathData with the specified draw context and path. * - * @param dc the draw context associated with this path data. + * @param dc the draw context associated with this path data. * @param shape the shape associated with this path data. */ - public MultiResolutionPathData(DrawContext dc, Path shape) - { + public MultiResolutionPathData(DrawContext dc, Path shape) { super(dc, shape); } @@ -72,8 +74,7 @@ public MultiResolutionPathData(DrawContext dc, Path shape) * * @return a buffer mapping positions to ordinal numbers. */ - public IntBuffer getPositionOrdinals() - { + public IntBuffer getPositionOrdinals() { return this.positionOrdinals; } @@ -82,8 +83,7 @@ public IntBuffer getPositionOrdinals() * * @param posOrdinals a buffer that maps positions to ordinal numbers. */ - public void setPositionOrdinals(IntBuffer posOrdinals) - { + public void setPositionOrdinals(IntBuffer posOrdinals) { this.positionOrdinals = posOrdinals; } } @@ -93,10 +93,8 @@ public void setPositionOrdinals(IntBuffer posOrdinals) * eye distance to the path is greater than 10e3, a value of 2 when the eye distance is greater than 1e3 meters but * less then 10e3, and a value of 1 when the eye distance is less than 1e3. */ - protected SkipCountComputer skipCountComputer = new SkipCountComputer() - { - public int computeSkipCount(DrawContext dc, PathData pathData) - { + protected SkipCountComputer skipCountComputer = new SkipCountComputer() { + public int computeSkipCount(DrawContext dc, PathData pathData) { double d = getDistanceMetric(dc, pathData); return d > 10e3 ? 4 : d > 1e3 ? 2 : 1; @@ -111,13 +109,12 @@ public int computeSkipCount(DrawContext dc, PathData pathData) * Note: If fewer than two positions are specified, no path is drawn. * * @param positions the path positions. This reference is retained by this shape; the positions are not copied. If - * any positions in the set change, {@link #setPositions(Iterable)} must be called to inform this - * shape of the change. + * any positions in the set change, {@link #setPositions(Iterable)} must be called to inform this shape of the + * change. * * @throws IllegalArgumentException if positions is null. */ - public MultiResolutionPath(Iterable positions) - { + public MultiResolutionPath(Iterable positions) { super(positions); } @@ -130,13 +127,12 @@ public MultiResolutionPath(Iterable positions) * Note: If fewer than two positions are specified, no path is drawn. * * @param positions the path positions. This reference is retained by this shape; the positions are not copied. If - * any positions in the set change, {@link #setPositions(Iterable)} must be called to inform this - * shape of the change. + * any positions in the set change, {@link #setPositions(Iterable)} must be called to inform this shape of the + * change. * * @throws IllegalArgumentException if positions is null. */ - public MultiResolutionPath(Position.PositionList positions) - { + public MultiResolutionPath(Position.PositionList positions) { super(positions); } @@ -146,8 +142,7 @@ public MultiResolutionPath(Position.PositionList positions) * * @return the SkipCountComputer used during path tessellation. */ - public SkipCountComputer getSkipCountComputer() - { + public SkipCountComputer getSkipCountComputer() { return this.skipCountComputer; } @@ -159,10 +154,8 @@ public SkipCountComputer getSkipCountComputer() * * @throws IllegalArgumentException if the computer is null. */ - public void setSkipCountComputer(SkipCountComputer computer) - { - if (computer == null) - { + public void setSkipCountComputer(SkipCountComputer computer) { + if (computer == null) { String message = Logging.getMessage("nullValue.CallbackIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -177,8 +170,7 @@ public void setSkipCountComputer(SkipCountComputer computer) * Overridden to return a new instance of MultiResolutionPathData. */ @Override - protected AbstractShapeData createCacheEntry(DrawContext dc) - { + protected AbstractShapeData createCacheEntry(DrawContext dc) { return new MultiResolutionPathData(dc, this); } @@ -188,16 +180,17 @@ protected AbstractShapeData createCacheEntry(DrawContext dc) * Overridden to initialize and build the PathData's positionOrdinals buffer. */ @Override - protected void makeTessellatedPositions(DrawContext dc, PathData pathData) - { - if (this.numPositions < 2) + protected void makeTessellatedPositions(DrawContext dc, PathData pathData) { + if (this.numPositions < 2) { return; + } MultiResolutionPathData mrpd = (MultiResolutionPathData) pathData; - if (mrpd.positionOrdinals == null || mrpd.positionOrdinals.capacity() < this.numPositions) + if (mrpd.positionOrdinals == null || mrpd.positionOrdinals.capacity() < this.numPositions) { mrpd.positionOrdinals = Buffers.newDirectIntBuffer(this.numPositions); - else + } else { mrpd.positionOrdinals.clear(); + } super.makeTessellatedPositions(dc, pathData); @@ -213,8 +206,7 @@ protected void makeTessellatedPositions(DrawContext dc, PathData pathData) * either very small or not visible. */ @Override - protected void makePositions(DrawContext dc, PathData pathData) - { + protected void makePositions(DrawContext dc, PathData pathData) { Iterator iter = this.positions.iterator(); Position posA = iter.next(); int ordinalA = 0; @@ -226,12 +218,10 @@ protected void makePositions(DrawContext dc, PathData pathData) // Tessellate each segment of the path. Vec4 ptA = this.computePoint(dc.getTerrain(), posA); - for (int i = 1; iter.hasNext(); i++) - { + for (int i = 1; iter.hasNext(); i++) { Position posB = iter.next(); - if (i % skipCount != 0 && iter.hasNext()) - { + if (i % skipCount != 0 && iter.hasNext()) { continue; } @@ -240,8 +230,9 @@ protected void makePositions(DrawContext dc, PathData pathData) if (iter.hasNext()) // if this is not the final position { // If the segment is very small or not visible, don't use it. - if (this.isSmall(dc, ptA, ptB, 8) || !this.isSegmentVisible(dc, posA, posB, ptA, ptB)) + if (this.isSmall(dc, ptA, ptB, 8) || !this.isSegmentVisible(dc, posA, posB, ptA, ptB)) { continue; + } } Color colorB = this.getColor(posB, i); @@ -260,10 +251,8 @@ protected void makePositions(DrawContext dc, PathData pathData) * is not null. */ @Override - protected void addTessellatedPosition(Position pos, Color color, Integer ordinal, PathData pathData) - { - if (ordinal != null) - { + protected void addTessellatedPosition(Position pos, Color color, Integer ordinal, PathData pathData) { + if (ordinal != null) { // NOTE: Assign these indices before adding the new position to the tessellatedPositions list. MultiResolutionPathData mrpd = (MultiResolutionPathData) pathData; mrpd.positionOrdinals.put(ordinal); @@ -279,8 +268,7 @@ protected void addTessellatedPosition(Position pos, Color color, Integer ordinal * its corresponding ordinal number. */ @Override - protected Integer getOrdinal(int positionIndex) - { + protected Integer getOrdinal(int positionIndex) { MultiResolutionPathData mrpd = (MultiResolutionPathData) this.getCurrentPathData(); return mrpd.positionOrdinals.get(positionIndex); } diff --git a/src/gov/nasa/worldwind/render/Offset.java b/src/gov/nasa/worldwind/render/Offset.java index e6d7897fac..213ce5f7d9 100644 --- a/src/gov/nasa/worldwind/render/Offset.java +++ b/src/gov/nasa/worldwind/render/Offset.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.avlist.AVKey; @@ -26,8 +25,8 @@ * @author tag * @version $Id: Offset.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Offset -{ +public class Offset { + public static final Offset CENTER = Offset.fromFraction(0.5, 0.5); public static final Offset BOTTOM_CENTER = Offset.fromFraction(0.5, 0.0); public static final Offset TOP_CENTER = Offset.fromFraction(0.5, 1.0); @@ -39,8 +38,7 @@ public class Offset protected String xUnits; protected String yUnits; - public Offset(Double x, Double y, String xUnits, String yUnits) - { + public Offset(Double x, Double y, String xUnits, String yUnits) { this.x = x; this.y = y; this.xUnits = xUnits; @@ -55,8 +53,7 @@ public Offset(Double x, Double y, String xUnits, String yUnits) * * @return a new offset with the specified X and Y coordinates. */ - public static Offset fromFraction(double xFraction, double yFraction) - { + public static Offset fromFraction(double xFraction, double yFraction) { return new Offset(xFraction, yFraction, AVKey.FRACTION, AVKey.FRACTION); } @@ -65,8 +62,7 @@ public static Offset fromFraction(double xFraction, double yFraction) * * @return the hot spot's X coordinate. */ - public Double getX() - { + public Double getX() { return x; } @@ -75,8 +71,7 @@ public Double getX() * * @param x the hot spot's X coordinate. May be null, in which case 0 is used during rendering. */ - public void setX(Double x) - { + public void setX(Double x) { this.x = x; } @@ -85,8 +80,7 @@ public void setX(Double x) * * @return the hot spot's Y coordinate. */ - public Double getY() - { + public Double getY() { return y; } @@ -95,8 +89,7 @@ public Double getY() * * @param y the hot spot's Y coordinate. May be null, in which case 0 is used during rendering. */ - public void setY(Double y) - { + public void setY(Double y) { this.y = y; } @@ -106,8 +99,7 @@ public void setY(Double y) * * @return the units of the offset X value, or null. */ - public String getXUnits() - { + public String getXUnits() { return xUnits; } @@ -119,8 +111,7 @@ public String getXUnits() * * @param units the units of the offset X value. If null, {@link AVKey#PIXELS} is used during rendering. */ - public void setXUnits(String units) - { + public void setXUnits(String units) { this.xUnits = units; } @@ -130,8 +121,7 @@ public void setXUnits(String units) * * @return the units of the offset Y value, or null. */ - public String getYUnits() - { + public String getYUnits() { return yUnits; } @@ -143,92 +133,94 @@ public String getYUnits() * * @param units the units of the offset Y value. If null, {@link AVKey#PIXELS} is used during rendering. */ - public void setYUnits(String units) - { + public void setYUnits(String units) { this.yUnits = units; } /** * Computes the X and Y offset specified by this offset applied to a specified rectangle. * - * @param width the rectangle width. + * @param width the rectangle width. * @param height the rectangle height. * @param xScale an optional scale to apply to the X coordinate of the offset. May be null. * @param yScale an optional scale to apply to the Y coordinate of the offset. May be null. * * @return the result of applying this offset to the specified rectangle and incorporating the optional scales. */ - public Point.Double computeOffset(double width, double height, Double xScale, Double yScale) - { + public Point.Double computeOffset(double width, double height, Double xScale, Double yScale) { double dx = 0; double dy = 0; - if (this.getX() != null) - { + if (this.getX() != null) { String units = this.getXUnits(); - if (AVKey.PIXELS.equals(units)) + if (AVKey.PIXELS.equals(units)) { dx = this.getX(); - else if (AVKey.INSET_PIXELS.equals(units)) + } else if (AVKey.INSET_PIXELS.equals(units)) { dx = width - this.getX(); - else if (AVKey.FRACTION.equals(units)) + } else if (AVKey.FRACTION.equals(units)) { dx = (width * this.getX()); - else + } else { dx = this.getX(); // treat as pixels + } } - if (this.getY() != null) - { + if (this.getY() != null) { String units = this.getYUnits(); - if (AVKey.PIXELS.equals(units)) + if (AVKey.PIXELS.equals(units)) { dy = this.getY(); - else if (AVKey.INSET_PIXELS.equals(units)) + } else if (AVKey.INSET_PIXELS.equals(units)) { dy = height - this.getY(); - else if (AVKey.FRACTION.equals(units)) + } else if (AVKey.FRACTION.equals(units)) { dy = (height * this.getY()); - else + } else { dy = this.getY(); // treat as pixels + } } - if (xScale != null) + if (xScale != null) { dx *= xScale; + } - if (yScale != null) + if (yScale != null) { dy *= yScale; + } return new Point.Double(dx, dy); } /** * Saves the offset's current state in the specified restorableSupport. If context is not - * null, the state is appended to it. Otherwise the state is added to the + * null, the state is appended to it. Otherwise the state is added to the * RestorableSupport root. This state can be restored later by calling {@link * #restoreState(gov.nasa.worldwind.util.RestorableSupport, gov.nasa.worldwind.util.RestorableSupport.StateObject)}. * * @param restorableSupport the RestorableSupport that receives the offset's state. - * @param context the StateObject the state is appended to, if not null. + * @param context the StateObject the state is appended to, if not null. * * @throws IllegalArgumentException if restorableSupport is null. */ - public void getRestorableState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) - { - if (restorableSupport == null) - { + public void getRestorableState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) { + if (restorableSupport == null) { String message = Logging.getMessage("nullValue.RestorableSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.getX() != null) + if (this.getX() != null) { restorableSupport.addStateValueAsDouble(context, "x", this.getX()); + } - if (this.getY() != null) + if (this.getY() != null) { restorableSupport.addStateValueAsDouble(context, "y", this.getY()); + } - if (this.getXUnits() != null) + if (this.getXUnits() != null) { restorableSupport.addStateValueAsString(context, "xUnits", this.getXUnits()); + } - if (this.getYUnits() != null) + if (this.getYUnits() != null) { restorableSupport.addStateValueAsString(context, "yUnits", this.getYUnits()); + } } /** @@ -237,62 +229,68 @@ public void getRestorableState(RestorableSupport restorableSupport, RestorableSu * RestorableSupport root is searched. * * @param restorableSupport the RestorableSupport that contains the offset's state. - * @param context the StateObject to search for state values, if not null. + * @param context the StateObject to search for state values, if not null. * * @throws IllegalArgumentException if restorableSupport is null. */ - public void restoreState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) - { - if (restorableSupport == null) - { + public void restoreState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) { + if (restorableSupport == null) { String message = Logging.getMessage("nullValue.RestorableSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Double d = restorableSupport.getStateValueAsDouble(context, "x"); - if (d != null) + if (d != null) { this.setX(d); + } d = restorableSupport.getStateValueAsDouble(context, "y"); - if (d != null) + if (d != null) { this.setY(d); + } String s = restorableSupport.getStateValueAsString(context, "xUnits"); - if (s != null) + if (s != null) { this.setXUnits(s); + } s = restorableSupport.getStateValueAsString(context, "yUnits"); - if (s != null) + if (s != null) { this.setYUnits(s); + } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } Offset that = (Offset) o; - if (this.x != null ? !this.x.equals(that.x) : that.x != null) + if (this.x != null ? !this.x.equals(that.x) : that.x != null) { return false; - if (this.y != null ? !this.y.equals(that.y) : that.y != null) + } + if (this.y != null ? !this.y.equals(that.y) : that.y != null) { return false; - if (this.xUnits != null ? !this.xUnits.equals(that.xUnits) : that.xUnits != null) + } + if (this.xUnits != null ? !this.xUnits.equals(that.xUnits) : that.xUnits != null) { return false; + } //noinspection RedundantIfStatement - if (this.yUnits != null ? !this.yUnits.equals(that.yUnits) : that.yUnits != null) + if (this.yUnits != null ? !this.yUnits.equals(that.yUnits) : that.yUnits != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = this.x != null ? this.x.hashCode() : 0; result = 31 * result + (this.y != null ? this.y.hashCode() : 0); result = 31 * result + (this.xUnits != null ? this.xUnits.hashCode() : 0); diff --git a/src/gov/nasa/worldwind/render/OffsetsList.java b/src/gov/nasa/worldwind/render/OffsetsList.java index 1718914714..b1cefa7f46 100644 --- a/src/gov/nasa/worldwind/render/OffsetsList.java +++ b/src/gov/nasa/worldwind/render/OffsetsList.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import java.util.*; @@ -14,30 +13,26 @@ * @author ccrick * @version $Id: OffsetsList.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OffsetsList -{ +public class OffsetsList { + protected Map offsets; - public OffsetsList() - { + public OffsetsList() { offsets = new HashMap(); // set default values to zero offset float[] zeroOffset = {0.0f, 0.0f}; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { offsets.put(i, zeroOffset); } } - public float[] getOffset(int index) - { + public float[] getOffset(int index) { return offsets.get(index); } - public void setOffset(int index, float uOffset, float vOffset) - { + public void setOffset(int index, float uOffset, float vOffset) { float[] offsetPair = {uOffset, vOffset}; offsets.put(index, offsetPair); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/render/OrderedRenderable.java b/src/gov/nasa/worldwind/render/OrderedRenderable.java index 588fcf1241..777d3b0b32 100644 --- a/src/gov/nasa/worldwind/render/OrderedRenderable.java +++ b/src/gov/nasa/worldwind/render/OrderedRenderable.java @@ -9,8 +9,8 @@ * @author tag * @version $Id: OrderedRenderable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface OrderedRenderable extends Renderable -{ +public interface OrderedRenderable extends Renderable { + /** * Returns the ordered renderable's distance from the current view's eye point. Intended to be used only to sort a * list of ordered renderables according to eye distance, and only during frame generation when a view is active. @@ -22,7 +22,7 @@ public interface OrderedRenderable extends Renderable /** * Executes a pick of the ordered renderable. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickPoint the pick point. */ public void pick(DrawContext dc, java.awt.Point pickPoint); diff --git a/src/gov/nasa/worldwind/render/OutlinedShape.java b/src/gov/nasa/worldwind/render/OutlinedShape.java index 0634de2cb5..2a7add317b 100644 --- a/src/gov/nasa/worldwind/render/OutlinedShape.java +++ b/src/gov/nasa/worldwind/render/OutlinedShape.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; /** @@ -15,12 +14,12 @@ * @author tag * @version $Id: OutlinedShape.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface OutlinedShape -{ +public interface OutlinedShape { + /** * Indicates whether the shape's outline is drawn. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape the shape being drawn. * * @return true if the shape's outline should be drawn, otherwise false. @@ -30,7 +29,7 @@ public interface OutlinedShape /** * Indicates whether the shape's faces are drawn. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape the shape being drawn. * * @return true if the shape's faces should be drawn, otherwise false. @@ -41,7 +40,7 @@ public interface OutlinedShape * Indicates whether the shape's depth should be adjusted to give its filled faces priority over coincident items * previously drawn. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape the shape being drawn. * * @return true if the shape should have priority, otherwise false. @@ -51,7 +50,7 @@ public interface OutlinedShape /** * Draws the shape's outline. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape the shape being drawn. */ void drawOutline(DrawContext dc, Object shape); @@ -59,7 +58,7 @@ public interface OutlinedShape /** * Draws the shape's filled faces. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape the shape being drawn. */ void drawInterior(DrawContext dc, Object shape); @@ -67,12 +66,13 @@ public interface OutlinedShape /** * Returns the depth-offset factor. *

          - * The amount of depth offset when depth offset is enabled is computed by the formula factor * DZ + r * + * The amount of depth offset when depth offset is enabled is computed by the formula factor * DZ + r + * * units, where DZ is a measurement of the change in depth relative to the screen area of the shape, and r is * the smallest value guaranteed to produce a resolvable offset. units is the value return by {@link * #getDepthOffsetUnits(DrawContext, Object)}. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape the shape being drawn. * * @return the depth offset factor to use for the shape. @@ -82,12 +82,13 @@ public interface OutlinedShape /** * Returns the depth-offset units. *

          - * The amount of depth offset when depth offset is enabled is computed by the formula factor * DZ + r * + * The amount of depth offset when depth offset is enabled is computed by the formula factor * DZ + r + * * units, where DZ is a measurement of the change in depth relative to the screen area of the shape, and r is * the smallest value guaranteed to produce a resolvable offset. factor is the value return by {@link * #getDepthOffsetFactor(DrawContext, Object)}. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shape the shape being drawn. * * @return the depth units to use for the shape. diff --git a/src/gov/nasa/worldwind/render/Path.java b/src/gov/nasa/worldwind/render/Path.java index c30cea5e02..b94e1288b0 100644 --- a/src/gov/nasa/worldwind/render/Path.java +++ b/src/gov/nasa/worldwind/render/Path.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -31,7 +30,6 @@ import static gov.nasa.worldwind.ogc.kml.impl.KMLExportUtil.kmlBoolean; // TODO: Measurement (getLength), Texture, lighting - /** * Displays a line or curve between positions. The path is drawn between input positions to achieve a specified path * type, e.g., {@link AVKey#GREAT_CIRCLE}. It can also conform to the underlying terrain. A curtain may be formed by @@ -81,13 +79,19 @@ * @author tag * @version $Id: Path.java 3032 2015-04-17 17:53:35Z dcollins $ */ -public class Path extends AbstractShape -{ - /** The default interior color. */ +public class Path extends AbstractShape { + + /** + * The default interior color. + */ protected static final Material DEFAULT_INTERIOR_MATERIAL = Material.PINK; - /** The default outline color. */ + /** + * The default outline color. + */ protected static final Material DEFAULT_OUTLINE_MATERIAL = Material.RED; - /** The default path type. */ + /** + * The default path type. + */ protected static final String DEFAULT_PATH_TYPE = AVKey.LINEAR; /** * The offset applied to a terrain following Path's depth values to to ensure it shows over the terrain: 0.99. @@ -95,18 +99,28 @@ public class Path extends AbstractShape * terrain. */ protected static final double SURFACE_PATH_DEPTH_OFFSET = 0.99; - /** The default number of tessellation points between the specified path positions. */ + /** + * The default number of tessellation points between the specified path positions. + */ protected static final int DEFAULT_NUM_SUBSEGMENTS = 10; - /** The default terrain conformance target. */ + /** + * The default terrain conformance target. + */ protected static final double DEFAULT_TERRAIN_CONFORMANCE = 10; - /** The default distance from the eye beyond which positions dots are not drawn. */ + /** + * The default distance from the eye beyond which positions dots are not drawn. + */ protected static final double DEFAULT_DRAW_POSITIONS_THRESHOLD = 1e6; - /** The default scale for position dots. The scale is applied to the current outline width to produce the dot size. */ + /** + * The default scale for position dots. The scale is applied to the current outline width to produce the dot size. + */ protected static final double DEFAULT_DRAW_POSITIONS_SCALE = 10; - /** The PositionColors interface defines an RGBA color for each of a path's original positions. */ - public static interface PositionColors - { + /** + * The PositionColors interface defines an RGBA color for each of a path's original positions. + */ + public static interface PositionColors { + /** * Returns an RGBA color corresponding to the specified position and ordinal. This returns null if * a color cannot be determined for the specified position and ordinal. The specified position is @@ -120,7 +134,7 @@ public static interface PositionColors * The returned color's RGB components must not be premultiplied by its Alpha component. * * @param position the path position the color corresponds to. - * @param ordinal the ordinal number of the specified position. + * @param ordinal the ordinal number of the specified position. * * @return an RGBA color corresponding to the position and ordinal, or null if a color cannot be * determined. @@ -133,9 +147,11 @@ public static interface PositionColors * distinct globe that this shape encounters in calls to {@link AbstractShape#render(DrawContext)}. See {@link * AbstractShape}. */ - protected static class PathData extends AbstractShapeData - { - /** The positions formed from applying path type and terrain conformance. */ + protected static class PathData extends AbstractShapeData { + + /** + * The positions formed from applying path type and terrain conformance. + */ protected ArrayList tessellatedPositions; /** * The colors corresponding to each tessellated position, or null if the path's @@ -167,7 +183,9 @@ protected static class PathData extends AbstractShapeData * line. Used only when the path's positions span the dateline and a 2D globe is being used. */ protected ArrayList splitPositions; - /** Indicates whether the rendered path has extrusion points in addition to path points. */ + /** + * Indicates whether the rendered path has extrusion points in addition to path points. + */ protected boolean hasExtrusionPoints; // true when the rendered path contains extrusion points /** * Indicates the offset in number of floats to the first RGBA color tuple in renderedPath. This is @@ -179,11 +197,12 @@ protected static class PathData extends AbstractShapeData * renderedPath. */ protected int vertexStride; - /** Indicates the number of vertices represented by renderedPath. */ + /** + * Indicates the number of vertices represented by renderedPath. + */ protected int vertexCount; - public PathData(DrawContext dc, Path shape) - { + public PathData(DrawContext dc, Path shape) { super(dc, shape.minExpiryTime, shape.maxExpiryTime); } @@ -193,13 +212,11 @@ public PathData(DrawContext dc, Path shape) * * @return the positions computed by path tessellation. */ - public List getTessellatedPositions() - { + public List getTessellatedPositions() { return this.tessellatedPositions; } - public void setTessellatedPositions(ArrayList tessellatedPositions) - { + public void setTessellatedPositions(ArrayList tessellatedPositions) { this.tessellatedPositions = tessellatedPositions; } @@ -210,8 +227,7 @@ public void setTessellatedPositions(ArrayList tessellatedPositions) * @return the colors corresponding to each path position, or null if the path does not have * per-position colors. */ - public List getTessellatedColors() - { + public List getTessellatedColors() { return this.tessellatedColors; } @@ -221,10 +237,9 @@ public List getTessellatedColors() * list must have a one-to-one correspondence with the entries in tessellatedPositions. * * @param tessellatedColors the colors corresponding to each path position, or null if the path - * does not have per-position colors. + * does not have per-position colors. */ - public void setTessellatedColors(ArrayList tessellatedColors) - { + public void setTessellatedColors(ArrayList tessellatedColors) { this.tessellatedColors = tessellatedColors; } @@ -234,30 +249,25 @@ public void setTessellatedColors(ArrayList tessellatedColors) * * @return the Cartesian coordinates of the tessellated positions. */ - public FloatBuffer getRenderedPath() - { + public FloatBuffer getRenderedPath() { return this.renderedPath; } - public void setRenderedPath(FloatBuffer renderedPath) - { + public void setRenderedPath(FloatBuffer renderedPath) { this.renderedPath = renderedPath; } /** * Returns a buffer of indices into the rendered path ({@link #renderedPath} that identify the originally - * specified positions that remain after tessellation. These positions are those of the position dots, if - * drawn. + * specified positions that remain after tessellation. These positions are those of the position dots, if drawn. * * @return the path's originally specified positions that survived tessellation. */ - public IntBuffer getPositionPoints() - { + public IntBuffer getPositionPoints() { return this.positionPoints; } - public void setPositionPoints(IntBuffer posPoints) - { + public void setPositionPoints(IntBuffer posPoints) { this.positionPoints = posPoints; } @@ -267,13 +277,11 @@ public void setPositionPoints(IntBuffer posPoints) * * @return the path's pole positions. */ - public IntBuffer getPolePositions() - { + public IntBuffer getPolePositions() { return this.polePositions; } - public void setPolePositions(IntBuffer polePositions) - { + public void setPolePositions(IntBuffer polePositions) { this.polePositions = polePositions; } @@ -282,13 +290,11 @@ public void setPolePositions(IntBuffer polePositions) * * @return true if the path is extruded and the extrusion points are computed, otherwise false. */ - public boolean isHasExtrusionPoints() - { + public boolean isHasExtrusionPoints() { return this.hasExtrusionPoints; } - public void setHasExtrusionPoints(boolean hasExtrusionPoints) - { + public void setHasExtrusionPoints(boolean hasExtrusionPoints) { this.hasExtrusionPoints = hasExtrusionPoints; } @@ -298,8 +304,7 @@ public void setHasExtrusionPoints(boolean hasExtrusionPoints) * * @return the offset in number of floats to the first RGBA color tuple in renderedPath. */ - public int getColorOffset() - { + public int getColorOffset() { return this.colorOffset; } @@ -309,8 +314,7 @@ public int getColorOffset() * * @param offset the offset in number of floats to the first RGBA color tuple in renderedPath. */ - public void setColorOffset(int offset) - { + public void setColorOffset(int offset) { this.colorOffset = offset; } @@ -320,8 +324,7 @@ public void setColorOffset(int offset) * * @return the stride in number of floats between vertices in in renderedPath. */ - public int getVertexStride() - { + public int getVertexStride() { return this.vertexStride; } @@ -331,8 +334,7 @@ public int getVertexStride() * * @param stride the stride in number of floats between vertices in in renderedPath. */ - public void setVertexStride(int stride) - { + public void setVertexStride(int stride) { this.vertexStride = stride; } @@ -341,8 +343,7 @@ public void setVertexStride(int stride) * * @return the the number of verices in renderedPath. */ - public int getVertexCount() - { + public int getVertexCount() { return this.vertexCount; } @@ -352,25 +353,23 @@ public int getVertexCount() * * @param count the the number of vertices in renderedPath. */ - public void setVertexCount(int count) - { + public void setVertexCount(int count) { this.vertexCount = count; } } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { SurfacePolyline polyline = new SurfacePolyline(); - if (this.getPositions() != null) + if (this.getPositions() != null) { polyline.setLocations(this.getPositions()); + } return polyline; } @Override - protected void updateSurfaceShape() - { + protected void updateSurfaceShape() { super.updateSurfaceShape(); this.surfaceShape.setPathType(this.getPathType()); @@ -381,15 +380,20 @@ protected void updateSurfaceShape() * colors that the Path's position points are drawn in. The color codes represent ARGB colors packed into a 32-bit * integer. */ - protected static class PickablePositions - { + protected static class PickablePositions { // TODO: Replace this class with usage of PickSupport.addPickableObjectRange. - /** The minimum color code, inclusive. */ + /** + * The minimum color code, inclusive. + */ public final int minColorCode; - /** The maximum color code, inclusive. */ + /** + * The maximum color code, inclusive. + */ public final int maxColorCode; - /** The Path who's position points are associated with the specified color code range. */ + /** + * The Path who's position points are associated with the specified color code range. + */ public final Path path; /** @@ -398,10 +402,9 @@ protected static class PickablePositions * * @param minColorCode the minimum color code, inclusive. * @param maxColorCode the maximum color code, inclusive. - * @param path the Path who's position points are associated with the specified color code range. + * @param path the Path who's position points are associated with the specified color code range. */ - public PickablePositions(int minColorCode, int maxColorCode, Path path) - { + public PickablePositions(int minColorCode, int maxColorCode, Path path) { this.minColorCode = minColorCode; this.maxColorCode = maxColorCode; this.path = path; @@ -418,8 +421,7 @@ public PickablePositions(int minColorCode, int maxColorCode, Path path) * PickedObject that specifies the picked Path. If a position point is picked, the PickedObject's AVList contains * the position and ordinal number of the picked position. */ - protected static class PathPickSupport extends PickSupport - { + protected static class PathPickSupport extends PickSupport { // TODO: Replace this subclass with usage of PickSupport.addPickableObjectRange. // TODO: Take care to retain the behavior in doResolvePick below that merges multiple picks from a single path. @@ -442,8 +444,7 @@ protected static class PathPickSupport extends PickSupport * Overridden to clear the list of pickable positions. */ @Override - public void clearPickList() - { + public void clearPickList() { super.clearPickList(); this.pickablePositions.clear(); } @@ -456,8 +457,7 @@ public void clearPickList() * * @return the list of Path pickable positions. */ - public List getPickablePositions() - { + public List getPickablePositions() { return this.pickablePositions; } @@ -467,14 +467,12 @@ public List getPickablePositions() * * @param minColorCode the minimum color code, inclusive. * @param maxColorCode the maximum color code, inclusive. - * @param path the Path who's position points are associated with the specified color code range. + * @param path the Path who's position points are associated with the specified color code range. * * @throws IllegalArgumentException if the path is null. */ - public void addPickablePositions(int minColorCode, int maxColorCode, Path path) - { - if (path == null) - { + public void addPickablePositions(int minColorCode, int maxColorCode, Path path) { + if (path == null) { String message = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -497,7 +495,7 @@ public void addPickablePositions(int minColorCode, int maxColorCode, Path path) * This returns null if the pickPoint is null, or if there is no Path or Path position point at the specified * pick point. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickPoint the screen-coordinate point in question. * * @return a new picked object instances indicating the Path or Path position point at the specified pick point, @@ -506,30 +504,29 @@ public void addPickablePositions(int minColorCode, int maxColorCode, Path path) * @throws IllegalArgumentException if the draw context is null. */ @Override - public PickedObject getTopObject(DrawContext dc, Point pickPoint) - { - if (dc == null) - { + public PickedObject getTopObject(DrawContext dc, Point pickPoint) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.getPickableObjects().isEmpty() && this.getPickablePositions().isEmpty()) + if (this.getPickableObjects().isEmpty() && this.getPickablePositions().isEmpty()) { return null; + } int colorCode = this.getTopColor(dc, pickPoint); - if (colorCode == dc.getClearColor().getRGB()) + if (colorCode == dc.getClearColor().getRGB()) { return null; + } PickedObject pickedObject = this.getPickableObjects().get(colorCode); - if (pickedObject != null) + if (pickedObject != null) { return pickedObject; + } - for (PickablePositions positions : this.getPickablePositions()) - { - if (colorCode >= positions.minColorCode && colorCode <= positions.maxColorCode) - { + for (PickablePositions positions : this.getPickablePositions()) { + if (colorCode >= positions.minColorCode && colorCode <= positions.maxColorCode) { // If the top color code matches a Path's position color, convert the color code to a position index // and delegate to the Path to resolve the index to a PickedObject. minColorCode corresponds to // index 0, and minColorCode+i corresponds to index i. @@ -548,21 +545,17 @@ public PickedObject getTopObject(DrawContext dc, Point pickPoint) * positions intersect the rectangle, the picked object's AVList contains the ordinal numbers in the key * AVKey.ORDINAL_LIST. * - * @param dc the draw context which receives the picked objects. + * @param dc the draw context which receives the picked objects. * @param pickRect the rectangle in AWT screen coordinates. - * @param layer the layer associated with the picked objects. + * @param layer the layer associated with the picked objects. */ @SuppressWarnings({"unchecked"}) @Override - protected void doResolvePick(DrawContext dc, Rectangle pickRect, Layer layer) - { - if (this.pickableObjects.isEmpty() && this.pickablePositions.isEmpty()) - { + protected void doResolvePick(DrawContext dc, Rectangle pickRect, Layer layer) { + if (this.pickableObjects.isEmpty() && this.pickablePositions.isEmpty()) { // There's nothing to do if both the pickable objects and pickable positions are empty. return; - } - else if (this.pickablePositions.isEmpty()) - { + } else if (this.pickablePositions.isEmpty()) { // Fall back to the superclass version of this method if we have pickable objects but no pickable // positions. This avoids the additional overhead of consolidating multiple objects picked from the same // path. @@ -574,40 +567,39 @@ else if (this.pickablePositions.isEmpty()) // cull the number of colors that the draw context must consider with identifying the unique pick colors in // the specified rectangle. int[] colorCodes = dc.getPickColorsInRectangle(pickRect, this.minAndMaxColorCodes); - if (colorCodes == null || colorCodes.length == 0) + if (colorCodes == null || colorCodes.length == 0) { return; + } // Lookup the pickable object (if any) for each unique color code appearing in the pick rectangle. Each // picked object that corresponds to a picked color is added to the draw context. Since the - for (int colorCode : colorCodes) - { + for (int colorCode : colorCodes) { if (colorCode == 0) // This should never happen, but we check anyway. + { continue; + } PickedObject po = this.pickableObjects.get(colorCode); - if (po != null) - { + if (po != null) { // The color code corresponds to a path's line, so we add the path and its picked object to the map // of picked objects if one doesn't already exist. If one already exists, then this picked object // provides no additional information and we just ignore it. Note that if multiple parts of a path // are picked, we use the pick color of the first part we encounter. - if (!this.pathPickedObjects.containsKey(po.getObject())) + if (!this.pathPickedObjects.containsKey(po.getObject())) { this.pathPickedObjects.put(po.getObject(), po); - } - else - { - for (PickablePositions positions : this.getPickablePositions()) - { - if (colorCode >= positions.minColorCode && colorCode <= positions.maxColorCode) - { + } + } else { + for (PickablePositions positions : this.getPickablePositions()) { + if (colorCode >= positions.minColorCode && colorCode <= positions.maxColorCode) { Path path = positions.path; // The color code corresponds to a path's position, so we incorporate that position's // ordinal into the picked object. Note that if multiple parts of a path are picked, we use // the pick color of the first part we encounter. po = this.pathPickedObjects.get(path); - if (po == null) + if (po == null) { this.pathPickedObjects.put(path, po = path.createPickedObject(colorCode)); + } // Convert the color code to a position index and delegate to the Path to resolve the // ordinal. minColorCode corresponds to position index 0, and minColorCode+i corresponds to @@ -616,8 +608,9 @@ else if (this.pickablePositions.isEmpty()) // Add the ordinal to the list of picked ordinals on the path's picked object. List ordinalList = (List) po.getValue(AVKey.ORDINAL_LIST); - if (ordinalList == null) + if (ordinalList == null) { po.setValue(AVKey.ORDINAL_LIST, ordinalList = new ArrayList()); + } ordinalList.add(ordinal); break; // No need to check the remaining paths. @@ -628,10 +621,10 @@ else if (this.pickablePositions.isEmpty()) // We've consolidated the information about what parts of each path are picked into a map of picked objects. // The values in this map contain all the information we need, so we just add them to the draw context. - for (PickedObject po : this.pathPickedObjects.values()) - { - if (layer != null) + for (PickedObject po : this.pathPickedObjects.values()) { + if (layer != null) { po.setParentLayer(layer); + } dc.addObjectInPickRectangle(po); } @@ -643,13 +636,11 @@ else if (this.pickablePositions.isEmpty()) } @Override - protected AbstractShapeData createCacheEntry(DrawContext dc) - { + protected AbstractShapeData createCacheEntry(DrawContext dc) { return new PathData(dc, this); } - protected PathData getCurrentPathData() - { + protected PathData getCurrentPathData() { return (PathData) this.getCurrentData(); } @@ -669,18 +660,17 @@ protected PathData getCurrentPathData() protected double showPositionsScale = DEFAULT_DRAW_POSITIONS_SCALE; protected boolean positionsSpanDateline; - /** Creates a path with no positions. */ - public Path() - { + /** + * Creates a path with no positions. + */ + public Path() { } - public Path(Path source) - { + public Path(Path source) { super(source); List copiedPositions = new ArrayList(); - for (Position position : source.positions) - { + for (Position position : source.positions) { copiedPositions.add(position); } this.setPositions(copiedPositions); @@ -702,13 +692,12 @@ public Path(Path source) * Note: If fewer than two positions is specified, no path is drawn. * * @param positions the path positions. This reference is retained by this shape; the positions are not copied. If - * any positions in the set change, {@link #setPositions(Iterable)} must be called to inform this - * shape of the change. + * any positions in the set change, {@link #setPositions(Iterable)} must be called to inform this shape of the + * change. * * @throws IllegalArgumentException if positions is null. */ - public Path(Iterable positions) - { + public Path(Iterable positions) { this.setPositions(positions); } @@ -718,15 +707,13 @@ public Path(Iterable positions) * Note: If fewer than two positions is specified, the path is not drawn. * * @param positions the path positions. This reference is retained by this shape; the positions are not copied. If - * any positions in the set change, {@link #setPositions(Iterable)} must be called to inform this - * shape of the change. + * any positions in the set change, {@link #setPositions(Iterable)} must be called to inform this shape of the + * change. * * @throws IllegalArgumentException if positions is null. */ - public Path(Position.PositionList positions) - { - if (positions == null) - { + public Path(Position.PositionList positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -743,10 +730,8 @@ public Path(Position.PositionList positions) * * @throws IllegalArgumentException if either position is null. */ - public Path(Position posA, Position posB) - { - if (posA == null || posB == null) - { + public Path(Position posA, Position posB) { + if (posA == null || posB == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -764,16 +749,13 @@ public Path(Position posA, Position posB) * Overridden to assign this Path's pickSupport property to a new PathPickSupport instance. */ @Override - protected void initialize() - { + protected void initialize() { this.pickSupport = new PathPickSupport(); } @Override - protected void reset() - { - for (ShapeDataCache.ShapeDataCacheEntry entry : this.shapeDataCache) - { + protected void reset() { + for (ShapeDataCache.ShapeDataCacheEntry entry : this.shapeDataCache) { ((PathData) entry).tessellatedPositions = null; ((PathData) entry).tessellatedColors = null; } @@ -786,8 +768,7 @@ protected void reset() * * @return this path's positions. Will be null if no positions have been specified. */ - public Iterable getPositions() - { + public Iterable getPositions() { return this.positions; } @@ -800,10 +781,8 @@ public Iterable getPositions() * * @throws IllegalArgumentException if positions is null. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -818,16 +797,14 @@ public void setPositions(Iterable positions) /** * Indicates the PositionColors that defines the RGBA color for each of this path's positions. A return value of - * null is valid and indicates that this path's positions are colored according to its - * ShapeAttributes. + * null is valid and indicates that this path's positions are colored according to its ShapeAttributes. * * @return this Path's PositionColors, or null if this path is colored according to its * ShapeAttributes. * * @see #setPositionColors(gov.nasa.worldwind.render.Path.PositionColors) */ - public PositionColors getPositionColors() - { + public PositionColors getPositionColors() { return this.positionColors; } @@ -848,13 +825,12 @@ public PositionColors getPositionColors() * according to its ShapeAttributes. This path's position colors reference is null by default. * * @param positionColors the PositionColors that defines an RGBA color for each of this path's positions, or - * null to color this path's positions according to its ShapeAttributes. + * null to color this path's positions according to its ShapeAttributes. * * @see #getPositionColors() * @see PositionColors */ - public void setPositionColors(PositionColors positionColors) - { + public void setPositionColors(PositionColors positionColors) { this.positionColors = positionColors; this.reset(); } @@ -867,8 +843,7 @@ public void setPositionColors(PositionColors positionColors) * * @see #setExtrude(boolean) */ - public boolean isExtrude() - { + public boolean isExtrude() { return extrude; } @@ -878,8 +853,7 @@ public boolean isExtrude() * * @param extrude true to extrude this path, otherwise false. The default value is false. */ - public void setExtrude(boolean extrude) - { + public void setExtrude(boolean extrude) { this.extrude = extrude; this.reset(); } @@ -891,8 +865,7 @@ public void setExtrude(boolean extrude) * * @see #setFollowTerrain(boolean) */ - public boolean isFollowTerrain() - { + public boolean isFollowTerrain() { return this.followTerrain; } @@ -901,10 +874,10 @@ public boolean isFollowTerrain() * * @param followTerrain true if terrain following, otherwise false. The default value is false. */ - public void setFollowTerrain(boolean followTerrain) - { - if (this.followTerrain == followTerrain) + public void setFollowTerrain(boolean followTerrain) { + if (this.followTerrain == followTerrain) { return; + } this.followTerrain = followTerrain; this.reset(); @@ -921,8 +894,7 @@ public void setFollowTerrain(boolean followTerrain) * * @see #setNumSubsegments(int) */ - public int getNumSubsegments() - { + public int getNumSubsegments() { return numSubsegments; } @@ -935,8 +907,7 @@ public int getNumSubsegments() * * @param numSubsegments the number of sub-segments. The default is 10. */ - public void setNumSubsegments(int numSubsegments) - { + public void setNumSubsegments(int numSubsegments) { this.numSubsegments = numSubsegments; this.reset(); } @@ -950,8 +921,7 @@ public void setNumSubsegments(int numSubsegments) * * @see #setTerrainConformance(double) */ - public double getTerrainConformance() - { + public double getTerrainConformance() { return terrainConformance; } @@ -962,8 +932,7 @@ public double getTerrainConformance() * * @param terrainConformance the number of pixels between tessellation points. */ - public void setTerrainConformance(double terrainConformance) - { + public void setTerrainConformance(double terrainConformance) { this.terrainConformance = terrainConformance; this.reset(); } @@ -975,8 +944,7 @@ public void setTerrainConformance(double terrainConformance) * * @see #setPathType(String) */ - public String getPathType() - { + public String getPathType() { return pathType; } @@ -988,8 +956,7 @@ public String getPathType() * * @see Path Types */ - public void setPathType(String pathType) - { + public void setPathType(String pathType) { this.pathType = pathType; this.reset(); } @@ -1001,8 +968,7 @@ public void setPathType(String pathType) * * @see #setDrawVerticals(boolean) */ - public boolean isDrawVerticals() - { + public boolean isDrawVerticals() { return drawVerticals; } @@ -1011,8 +977,7 @@ public boolean isDrawVerticals() * * @param drawVerticals true to draw the lines, otherwise false. The default value is true. */ - public void setDrawVerticals(boolean drawVerticals) - { + public void setDrawVerticals(boolean drawVerticals) { this.drawVerticals = drawVerticals; this.reset(); } @@ -1022,8 +987,7 @@ public void setDrawVerticals(boolean drawVerticals) * * @return true if dots are drawn, otherwise false. */ - public boolean isShowPositions() - { + public boolean isShowPositions() { return showPositions; } @@ -1033,8 +997,7 @@ public boolean isShowPositions() * * @param showPositions true if dots are drawn at each original (not tessellated) position, otherwise false. */ - public void setShowPositions(boolean showPositions) - { + public void setShowPositions(boolean showPositions) { this.showPositions = showPositions; } @@ -1045,8 +1008,7 @@ public void setShowPositions(boolean showPositions) * * @return the shape's draw-position scale. The default scale is 10. */ - public double getShowPositionsScale() - { + public double getShowPositionsScale() { return showPositionsScale; } @@ -1057,8 +1019,7 @@ public double getShowPositionsScale() * * @param showPositionsScale the new draw-position scale. */ - public void setShowPositionsScale(double showPositionsScale) - { + public void setShowPositionsScale(double showPositionsScale) { this.showPositionsScale = showPositionsScale; } @@ -1068,8 +1029,7 @@ public void setShowPositionsScale(double showPositionsScale) * @return the eye distance at which to enable or disable position dot drawing. The default is 1e6 meters, which * typically causes the dots to always be drawn. */ - public double getShowPositionsThreshold() - { + public double getShowPositionsThreshold() { return showPositionsThreshold; } @@ -1078,59 +1038,55 @@ public double getShowPositionsThreshold() * * @param showPositionsThreshold the eye distance at which to enable or disable position dot drawing. */ - public void setShowPositionsThreshold(double showPositionsThreshold) - { + public void setShowPositionsThreshold(double showPositionsThreshold) { this.showPositionsThreshold = showPositionsThreshold; } - public Sector getSector() - { - if (this.sector == null && this.positions != null) + public Sector getSector() { + if (this.sector == null && this.positions != null) { this.sector = Sector.boundingSector(this.positions); + } return this.sector; } @Override - protected boolean mustDrawInterior() - { + protected boolean mustDrawInterior() { return super.mustDrawInterior() && this.getCurrentPathData().hasExtrusionPoints; } @Override - protected boolean mustApplyLighting(DrawContext dc, ShapeAttributes activeAttrs) - { + protected boolean mustApplyLighting(DrawContext dc, ShapeAttributes activeAttrs) { return false; // TODO: Lighting; need to compute normals } @Override - protected boolean mustApplyTexture(DrawContext dc) - { + protected boolean mustApplyTexture(DrawContext dc) { return false; } - protected boolean mustRegenerateGeometry(DrawContext dc) - { - if (this.getCurrentPathData() == null || this.getCurrentPathData().renderedPath == null) + protected boolean mustRegenerateGeometry(DrawContext dc) { + if (this.getCurrentPathData() == null || this.getCurrentPathData().renderedPath == null) { return true; + } - if (this.getCurrentPathData().tessellatedPositions == null) + if (this.getCurrentPathData().tessellatedPositions == null) { return true; + } - if (dc.getVerticalExaggeration() != this.getCurrentPathData().getVerticalExaggeration()) + if (dc.getVerticalExaggeration() != this.getCurrentPathData().getVerticalExaggeration()) { return true; + } //noinspection SimplifiableIfStatement // if (this.getAltitudeMode() == WorldWind.ABSOLUTE // && this.getCurrentPathData().getGlobeStateKey() != null // && this.getCurrentPathData().getGlobeStateKey().equals(dc.getGlobe().getGlobeStateKey(dc))) // return false; - return super.mustRegenerateGeometry(dc); } - protected boolean shouldUseVBOs(DrawContext dc) - { + protected boolean shouldUseVBOs(DrawContext dc) { return this.getCurrentPathData().tessellatedPositions.size() > VBO_THRESHOLD && super.shouldUseVBOs(dc); } @@ -1143,70 +1099,73 @@ protected boolean shouldUseVBOs(DrawContext dc) * @return true if this Path's positions and the positions in between are located on the underlying * terrain, and false otherwise. */ - protected boolean isSurfacePath(DrawContext dc) - { + protected boolean isSurfacePath(DrawContext dc) { return (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND && this.isFollowTerrain()) || dc.is2DGlobe(); } @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { // When the interior is drawn the vertex buffer has a different layout, so it may need to be rebuilt. boolean isDrawInterior = this.activeAttributes != null && this.activeAttributes.isDrawInterior(); super.determineActiveAttributes(); - if (this.activeAttributes != null && this.activeAttributes.isDrawInterior() != isDrawInterior) + if (this.activeAttributes != null && this.activeAttributes.isDrawInterior() != isDrawInterior) { this.getCurrentData().setExpired(true); + } } - /** Counts the number of positions in this path's specified positions. */ - protected void computePositionCount() - { + /** + * Counts the number of positions in this path's specified positions. + */ + protected void computePositionCount() { this.numPositions = 0; - if (this.positions != null) - { + if (this.positions != null) { //noinspection UnusedDeclaration - for (Position pos : this.positions) - { + for (Position pos : this.positions) { ++this.numPositions; } } } @Override - protected boolean doMakeOrderedRenderable(DrawContext dc) - { + protected boolean doMakeOrderedRenderable(DrawContext dc) { // currentData must be set prior to calling this method PathData pathData = this.getCurrentPathData(); pathData.setReferencePoint(this.computeReferenceCenter(dc)); - if (pathData.getReferencePoint() == null) + if (pathData.getReferencePoint() == null) { return false; + } // Recompute tessellated positions because the geometry or view may have changed. this.makeTessellatedPositions(dc, pathData); - if (pathData.tessellatedPositions == null || pathData.tessellatedPositions.size() < 2) + if (pathData.tessellatedPositions == null || pathData.tessellatedPositions.size() < 2) { return false; + } // Create the rendered Cartesian points. int previousSize = pathData.renderedPath != null ? pathData.renderedPath.limit() : 0; this.computePath(dc, pathData.tessellatedPositions, pathData); - if (pathData.renderedPath == null || pathData.renderedPath.limit() < 6) + if (pathData.renderedPath == null || pathData.renderedPath.limit() < 6) { return false; + } - if (pathData.renderedPath.limit() > previousSize && this.shouldUseVBOs(dc)) + if (pathData.renderedPath.limit() > previousSize && this.shouldUseVBOs(dc)) { this.clearCachedVbos(dc); + } pathData.setExtent(this.computeExtent(pathData)); // If the shape is less that a pixel in size, don't render it. - if (this.getExtent() == null || dc.isSmall(this.getExtent(), 1)) + if (this.getExtent() == null || dc.isSmall(this.getExtent(), 1)) { return false; + } - if (!this.intersectsFrustum(dc)) + if (!this.intersectsFrustum(dc)) { return false; + } pathData.setEyeDistance(this.computeEyeDistance(dc, pathData)); pathData.setGlobeStateKey(dc.getGlobe().getGlobeStateKey(dc)); @@ -1221,10 +1180,8 @@ protected boolean doMakeOrderedRenderable(DrawContext dc) * Overridden to add this Path's pickable positions to the pick candidates. */ @Override - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) - { - if (dc.isPickingMode()) - { + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) { + if (dc.isPickingMode()) { // Add the pickable objects used to resolve picks against individual position points. This must be done // before we call super.doDrawOrderedRenderable in order to populate the pickPositionColors buffer before // outline rendering. @@ -1243,21 +1200,16 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate * the terrain, they are drawn with respect to their layer ordering. */ @Override - protected void addOrderedRenderable(DrawContext dc) - { - if (this.isSurfacePath(dc)) - { + protected void addOrderedRenderable(DrawContext dc) { + if (this.isSurfacePath(dc)) { dc.addOrderedRenderable(this, true); // Specify that this Path is behind other renderables. - } - else - { + } else { super.addOrderedRenderable(dc); } } @Override - protected boolean isOrderedRenderableValid(DrawContext dc) - { + protected boolean isOrderedRenderableValid(DrawContext dc) { return this.getCurrentPathData().renderedPath != null && this.getCurrentPathData().vertexCount >= 2; } @@ -1272,48 +1224,38 @@ protected boolean isOrderedRenderableValid(DrawContext dc) * values and we can be certain that other ordered renderables should appear on top of it. */ @Override - protected void doDrawOutline(DrawContext dc) - { + protected void doDrawOutline(DrawContext dc) { boolean projectionOffsetPushed = false; // keep track for error recovery - try - { - if (this.isSurfacePath(dc)) - { + try { + if (this.isSurfacePath(dc)) { // Pull the line forward just a bit to ensure it shows over the terrain. dc.pushProjectionOffest(SURFACE_PATH_DEPTH_OFFSET); dc.getGL().glDepthMask(false); projectionOffsetPushed = true; } - if (this.shouldUseVBOs(dc)) - { + if (this.shouldUseVBOs(dc)) { int[] vboIds = this.getVboIds(dc); - if (vboIds != null) + if (vboIds != null) { this.doDrawOutlineVBO(dc, vboIds, this.getCurrentPathData()); - else + } else { this.doDrawOutlineVA(dc, this.getCurrentPathData()); - } - else - { + } + } else { this.doDrawOutlineVA(dc, this.getCurrentPathData()); } - } - finally - { - if (projectionOffsetPushed) - { + } finally { + if (projectionOffsetPushed) { dc.popProjectionOffest(); dc.getGL().glDepthMask(true); } } } - protected void doDrawOutlineVBO(DrawContext dc, int[] vboIds, PathData pathData) - { + protected void doDrawOutlineVBO(DrawContext dc, int[] vboIds, PathData pathData) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { int stride = pathData.hasExtrusionPoints ? 2 * pathData.vertexStride : pathData.vertexStride; int count = pathData.hasExtrusionPoints ? pathData.vertexCount / 2 : pathData.vertexCount; boolean useVertexColors = !dc.isPickingMode() && pathData.tessellatedColors != null; @@ -1324,41 +1266,37 @@ protected void doDrawOutlineVBO(DrawContext dc, int[] vboIds, PathData pathData) // Apply this path's per-position colors if we're in normal rendering mode (not picking) and this path's // positionColors is non-null. - if (useVertexColors) - { + if (useVertexColors) { // Convert stride and offset from number of elements to number of bytes. gl.glEnableClientState(GL2.GL_COLOR_ARRAY); gl.glColorPointer(4, GL.GL_FLOAT, 4 * stride, 4 * pathData.colorOffset); } - if (this.positionsSpanDateline && dc.is2DGlobe()) - { + if (this.positionsSpanDateline && dc.is2DGlobe()) { gl.glDrawElements(GL.GL_LINES, pathData.path2DIndices.limit(), GL.GL_UNSIGNED_INT, - pathData.path2DIndices.rewind()); - } - else - { + pathData.path2DIndices.rewind()); + } else { gl.glDrawArrays(GL.GL_LINE_STRIP, 0, count); } - if (useVertexColors) + if (useVertexColors) { gl.glDisableClientState(GL2.GL_COLOR_ARRAY); + } - if (pathData.hasExtrusionPoints && this.isDrawVerticals()) + if (pathData.hasExtrusionPoints && this.isDrawVerticals()) { this.drawVerticalOutlineVBO(dc, vboIds, pathData); + } - if (this.isShowPositions()) + if (this.isShowPositions()) { this.drawPointsVBO(dc, vboIds, pathData); - } - finally - { + } + } finally { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); } } - protected void doDrawOutlineVA(DrawContext dc, PathData pathData) - { + protected void doDrawOutlineVA(DrawContext dc, PathData pathData) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int stride = pathData.hasExtrusionPoints ? 2 * pathData.vertexStride : pathData.vertexStride; int count = pathData.hasExtrusionPoints ? pathData.vertexCount / 2 : pathData.vertexCount; @@ -1369,8 +1307,7 @@ protected void doDrawOutlineVA(DrawContext dc, PathData pathData) // Apply this path's per-position colors if we're in normal rendering mode (not picking) and this path's // positionColors is non-null. - if (useVertexColors) - { + if (useVertexColors) { // Convert stride from number of elements to number of bytes, and position the vertex buffer at the first // color. gl.glEnableClientState(GL2.GL_COLOR_ARRAY); @@ -1378,31 +1315,31 @@ protected void doDrawOutlineVA(DrawContext dc, PathData pathData) pathData.renderedPath.rewind(); } - if (this.positionsSpanDateline && dc.is2DGlobe()) - { + if (this.positionsSpanDateline && dc.is2DGlobe()) { gl.glDrawElements(GL.GL_LINES, pathData.path2DIndices.limit(), GL.GL_UNSIGNED_INT, - pathData.path2DIndices.rewind()); - } - else - { + pathData.path2DIndices.rewind()); + } else { gl.glDrawArrays(GL.GL_LINE_STRIP, 0, count); } - if (useVertexColors) + if (useVertexColors) { gl.glDisableClientState(GL2.GL_COLOR_ARRAY); + } - if (pathData.hasExtrusionPoints && this.isDrawVerticals()) + if (pathData.hasExtrusionPoints && this.isDrawVerticals()) { this.drawVerticalOutlineVA(dc, pathData); + } - if (this.isShowPositions()) + if (this.isShowPositions()) { this.drawPointsVA(dc, pathData); + } } - protected void drawVerticalOutlineVBO(DrawContext dc, int[] vboIds, PathData pathData) - { + protected void drawVerticalOutlineVBO(DrawContext dc, int[] vboIds, PathData pathData) { IntBuffer polePositions = pathData.polePositions; - if (polePositions == null || polePositions.limit() < 1) + if (polePositions == null || polePositions.limit() < 1) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -1417,14 +1354,14 @@ protected void drawVerticalOutlineVBO(DrawContext dc, int[] vboIds, PathData pat /** * Draws vertical lines at this path's specified positions. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pathData the current globe-specific path data. */ - protected void drawVerticalOutlineVA(DrawContext dc, PathData pathData) - { + protected void drawVerticalOutlineVA(DrawContext dc, PathData pathData) { IntBuffer polePositions = pathData.polePositions; - if (polePositions == null || polePositions.limit() < 1) + if (polePositions == null || polePositions.limit() < 1) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -1436,37 +1373,35 @@ protected void drawVerticalOutlineVA(DrawContext dc, PathData pathData) /** * Draws vertical lines at this path's specified positions. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pathData the current globe-specific path data. */ - protected void drawPointsVA(DrawContext dc, PathData pathData) - { + protected void drawPointsVA(DrawContext dc, PathData pathData) { double d = this.getDistanceMetric(dc, pathData); - if (d > this.getShowPositionsThreshold()) + if (d > this.getShowPositionsThreshold()) { return; + } IntBuffer posPoints = pathData.positionPoints; - if (posPoints == null || posPoints.limit() < 1) + if (posPoints == null || posPoints.limit() < 1) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Convert stride from number of elements to number of bytes. gl.glVertexPointer(3, GL.GL_FLOAT, 4 * pathData.vertexStride, pathData.renderedPath.rewind()); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glEnableClientState(GL2.GL_COLOR_ARRAY); gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, pickPositionColors); - } - else if (pathData.tessellatedColors != null) - { + } else if (pathData.tessellatedColors != null) { // Apply this path's per-position colors if we're in normal rendering mode (not picking) and this path's // positionColors is non-null. Convert stride from number of elements to number of bytes, and position the // vertex buffer at the first color. gl.glEnableClientState(GL2.GL_COLOR_ARRAY); gl.glColorPointer(4, GL.GL_FLOAT, 4 * pathData.vertexStride, - pathData.renderedPath.position(pathData.colorOffset)); + pathData.renderedPath.position(pathData.colorOffset)); } this.prepareToDrawPoints(dc); @@ -1476,8 +1411,9 @@ else if (pathData.tessellatedColors != null) gl.glPointSize(1f); gl.glDisable(GL2.GL_POINT_SMOOTH); - if (dc.isPickingMode() || pathData.tessellatedColors != null) + if (dc.isPickingMode() || pathData.tessellatedColors != null) { gl.glDisableClientState(GL2.GL_COLOR_ARRAY); + } } /** @@ -1488,33 +1424,31 @@ else if (pathData.tessellatedColors != null) * previous state. If the caller intends to use that buffer after this method returns, the caller must bind the * buffer again. * - * @param dc the current draw context. - * @param vboIds the ids of this shapes buffers. + * @param dc the current draw context. + * @param vboIds the ids of this shapes buffers. * @param pathData the current globe-specific path data. */ - protected void drawPointsVBO(DrawContext dc, int[] vboIds, PathData pathData) - { + protected void drawPointsVBO(DrawContext dc, int[] vboIds, PathData pathData) { double d = this.getDistanceMetric(dc, pathData); - if (d > this.getShowPositionsThreshold()) + if (d > this.getShowPositionsThreshold()) { return; + } IntBuffer posPoints = pathData.positionPoints; - if (posPoints == null || posPoints.limit() < 1) + if (posPoints == null || posPoints.limit() < 1) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Convert stride from number of elements to number of bytes. gl.glVertexPointer(3, GL.GL_FLOAT, 4 * pathData.vertexStride, 0); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glEnableClientState(GL2.GL_COLOR_ARRAY); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, pickPositionColors); - } - else if (pathData.tessellatedColors != null) - { + } else if (pathData.tessellatedColors != null) { // Apply this path's per-position colors if we're in normal rendering mode (not picking) and this path's // positionColors is non-null. Convert the stride and offset from number of elements to number of bytes. gl.glEnableClientState(GL2.GL_COLOR_ARRAY); @@ -1530,16 +1464,15 @@ else if (pathData.tessellatedColors != null) gl.glDisable(GL2.GL_POINT_SMOOTH); // Restore the previous GL color array state. - if (dc.isPickingMode() || pathData.tessellatedColors != null) + if (dc.isPickingMode() || pathData.tessellatedColors != null) { gl.glDisableClientState(GL2.GL_COLOR_ARRAY); + } } - protected void prepareToDrawPoints(DrawContext dc) - { + protected void prepareToDrawPoints(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { // During picking, compute the GL point size as the product of the active outline width and the show // positions scale, plus the positive difference (if any) between the outline pick width and the outline // width. During picking, the outline width is set to the larger of the outline width and the outline pick @@ -1549,11 +1482,9 @@ protected void prepareToDrawPoints(DrawContext dc) // obscure the other nearby points. ShapeAttributes activeAttrs = this.getActiveAttributes(); double deltaWidth = activeAttrs.getOutlineWidth() < this.getOutlinePickWidth() - ? this.getOutlinePickWidth() - activeAttrs.getOutlineWidth() : 0; + ? this.getOutlinePickWidth() - activeAttrs.getOutlineWidth() : 0; gl.glPointSize((float) (this.getShowPositionsScale() * activeAttrs.getOutlineWidth() + deltaWidth)); - } - else - { + } else { // During normal rendering mode, compute the GL point size as the product of the active outline width and // the show positions scale. This computation is consistent with the documentation for the methods // setShowPositionsScale and getShowPositionsScale. @@ -1575,24 +1506,20 @@ protected void prepareToDrawPoints(DrawContext dc) * * @param dc the current draw context. */ - protected void doDrawInterior(DrawContext dc) - { - if (this.shouldUseVBOs(dc)) - { + protected void doDrawInterior(DrawContext dc) { + if (this.shouldUseVBOs(dc)) { int[] vboIds = this.getVboIds(dc); - if (vboIds != null) + if (vboIds != null) { this.doDrawInteriorVBO(dc, vboIds, this.getCurrentPathData()); - else + } else { this.doDrawInteriorVA(dc, this.getCurrentPathData()); - } - else - { + } + } else { this.doDrawInteriorVA(dc, this.getCurrentPathData()); } } - protected void doDrawInteriorVBO(DrawContext dc, int[] vboIds, PathData pathData) - { + protected void doDrawInteriorVBO(DrawContext dc, int[] vboIds, PathData pathData) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Convert stride from number of elements to number of bytes. @@ -1603,8 +1530,7 @@ protected void doDrawInteriorVBO(DrawContext dc, int[] vboIds, PathData pathData gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } - protected void doDrawInteriorVA(DrawContext dc, PathData pathData) - { + protected void doDrawInteriorVA(DrawContext dc, PathData pathData) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Convert stride from number of elements to number of bytes. @@ -1616,22 +1542,22 @@ protected void doDrawInteriorVA(DrawContext dc, PathData pathData) * Computes the shape's model-coordinate path from a list of positions. Applies the path's terrain-conformance * settings. Adds extrusion points -- those on the ground -- when the path is extruded. * - * @param dc the current draw context. + * @param dc the current draw context. * @param positions the positions to create a path for. - * @param pathData the current globe-specific path data. + * @param pathData the current globe-specific path data. */ - protected void computePath(DrawContext dc, List positions, PathData pathData) - { + protected void computePath(DrawContext dc, List positions, PathData pathData) { pathData.hasExtrusionPoints = false; FloatBuffer path = pathData.renderedPath; - if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) + if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) { path = this.computePointsRelativeToTerrain(dc, positions, 0d, path, pathData); - else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) + } else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { path = this.computePointsRelativeToTerrain(dc, positions, null, path, pathData); - else + } else { path = this.computeAbsolutePoints(dc, positions, path, pathData); + } path.flip(); // since the path is reused the limit might not be the same as the previous usage @@ -1644,33 +1570,32 @@ else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) * or the altitudes in the specified positions. Adds extrusion points -- those on the ground -- when the path is * extruded and the specified single altitude is not 0. * - * @param dc the current draw context. + * @param dc the current draw context. * @param positions the positions to create a path for. - * @param altitude if non-null, the height above the terrain to use for all positions. If null, each position's - * altitude is used as the height above the terrain. - * @param path a buffer in which to store the computed points. May be null. The buffer is not used if it is - * null or tool small for the required number of points. A new buffer is created in that case and - * returned by this method. This method modifies the buffer,s position and limit fields. - * @param pathData the current globe-specific path data. + * @param altitude if non-null, the height above the terrain to use for all positions. If null, each position's + * altitude is used as the height above the terrain. + * @param path a buffer in which to store the computed points. May be null. The buffer is not used if it is null or + * tool small for the required number of points. A new buffer is created in that case and returned by this method. + * This method modifies the buffer,s position and limit fields. + * @param pathData the current globe-specific path data. * * @return the buffer in which to place the computed points. */ protected FloatBuffer computePointsRelativeToTerrain(DrawContext dc, List positions, - Double altitude, FloatBuffer path, PathData pathData) - { + Double altitude, FloatBuffer path, PathData pathData) { boolean extrudeIt = this.isExtrude() && !(altitude != null && altitude == 0); int numPoints = extrudeIt ? 2 * positions.size() : positions.size(); int elemsPerPoint = (pathData.tessellatedColors != null ? 7 : 3); Iterator colorIter = (pathData.tessellatedColors != null ? pathData.tessellatedColors.iterator() : null); float[] color = (pathData.tessellatedColors != null ? new float[4] : null); - if (path == null || path.capacity() < elemsPerPoint * numPoints) + if (path == null || path.capacity() < elemsPerPoint * numPoints) { path = Buffers.newDirectFloatBuffer(elemsPerPoint * numPoints); + } path.clear(); - for (Position pos : positions) - { + for (Position pos : positions) { double height = altitude != null ? altitude : pos.getAltitude(); Vec4 referencePoint = pathData.getReferencePoint(); Vec4 pt = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), height); @@ -1678,14 +1603,14 @@ protected FloatBuffer computePointsRelativeToTerrain(DrawContext dc, List positions, FloatBuffer path, - PathData pathData) - { + PathData pathData) { int numPoints = this.isExtrude() ? 2 * positions.size() : positions.size(); int elemsPerPoint = (pathData.tessellatedColors != null ? 7 : 3); Iterator colorIter = (pathData.tessellatedColors != null ? pathData.tessellatedColors.iterator() : null); float[] color = (pathData.tessellatedColors != null ? new float[4] : null); - if (path == null || path.capacity() < elemsPerPoint * numPoints) + if (path == null || path.capacity() < elemsPerPoint * numPoints) { path = Buffers.newDirectFloatBuffer(elemsPerPoint * numPoints); + } path.clear(); Globe globe = dc.getGlobe(); Vec4 referencePoint = pathData.getReferencePoint(); - if (dc.getVerticalExaggeration() != 1) - { + if (dc.getVerticalExaggeration() != 1) { double ve = dc.getVerticalExaggeration(); - for (Position pos : positions) - { + for (Position pos : positions) { Vec4 pt = globe.computePointFromPosition(pos.getLatitude(), pos.getLongitude(), - ve * (pos.getAltitude())); + ve * (pos.getAltitude())); path.put((float) (pt.x - referencePoint.x)); path.put((float) (pt.y - referencePoint.y)); path.put((float) (pt.z - referencePoint.z)); - if (colorIter != null && colorIter.hasNext()) - { + if (colorIter != null && colorIter.hasNext()) { colorIter.next().getRGBComponents(color); path.put(color); } - if (this.isExtrude()) + if (this.isExtrude()) { this.appendTerrainPoint(dc, pos, color, path, pathData); + } } - } - else - { - for (Position pos : positions) - { + } else { + for (Position pos : positions) { Vec4 pt = globe.computePointFromPosition(pos); path.put((float) (pt.x - referencePoint.x)); path.put((float) (pt.y - referencePoint.y)); path.put((float) (pt.z - referencePoint.z)); - if (colorIter != null && colorIter.hasNext()) - { + if (colorIter != null && colorIter.hasNext()) { colorIter.next().getRGBComponents(color); path.put(color); } - if (this.isExtrude()) + if (this.isExtrude()) { this.appendTerrainPoint(dc, pos, color, path, pathData); + } } } @@ -1773,24 +1693,24 @@ protected FloatBuffer computeAbsolutePoints(DrawContext dc, List posit /** * Computes a point on a path and adds it to the renderable geometry. Used to generate extrusion vertices. * - * @param dc the current draw context. + * @param dc the current draw context. * @param position the path position. - * @param color an array of length 4 containing the position's corresponding color as RGBA values in the range - * [0, 1], or null if the position has no associated color. - * @param path the path to append to. Assumes that the path has adequate capacity. + * @param color an array of length 4 containing the position's corresponding color as RGBA values in the range [0, + * 1], or null if the position has no associated color. + * @param path the path to append to. Assumes that the path has adequate capacity. * @param pathData the current globe-specific path data. */ protected void appendTerrainPoint(DrawContext dc, Position position, float[] color, FloatBuffer path, - PathData pathData) - { + PathData pathData) { Vec4 referencePoint = pathData.getReferencePoint(); Vec4 pt = dc.computeTerrainPoint(position.getLatitude(), position.getLongitude(), 0d); path.put((float) (pt.x - referencePoint.x)); path.put((float) (pt.y - referencePoint.y)); path.put((float) (pt.z - referencePoint.z)); - if (color != null) + if (color != null) { path.put(color); + } pathData.hasExtrusionPoints = true; } @@ -1799,25 +1719,28 @@ protected void appendTerrainPoint(DrawContext dc, Position position, float[] col * Registers this Path's pickable position color codes with the specified pickCandidates. The pickCandidates must be * an instance of PathPickSupport. This does nothing if this Path's position points are not drawn. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickCandidates the PickSupport to register with. Must be an instance of PathPickSupport. */ - protected void addPickablePositions(DrawContext dc, PickSupport pickCandidates) - { - if (!this.isShowPositions()) + protected void addPickablePositions(DrawContext dc, PickSupport pickCandidates) { + if (!this.isShowPositions()) { return; + } PathData pathData = this.getCurrentPathData(); double d = this.getDistanceMetric(dc, pathData); - if (d > this.getShowPositionsThreshold()) + if (d > this.getShowPositionsThreshold()) { return; + } IntBuffer posPoints = pathData.positionPoints; - if (posPoints == null || posPoints.limit() < 1) + if (posPoints == null || posPoints.limit() < 1) { return; + } - if (pickPositionColors == null || pickPositionColors.capacity() < 3 * pathData.vertexCount) + if (pickPositionColors == null || pickPositionColors.capacity() < 3 * pathData.vertexCount) { pickPositionColors = ByteBuffer.allocateDirect(3 * pathData.vertexCount); + } pickPositionColors.clear(); posPoints.rewind(); // Rewind the position points buffer before use to ensure it starts at position 0. @@ -1827,18 +1750,18 @@ protected void addPickablePositions(DrawContext dc, PickSupport pickCandidates) int minColorCode = pickColor.getRGB(); int maxColorCode = minColorCode; - for (int i = 0; i < pathData.vertexCount; i++) - { - if (i == nextPosition) - { + for (int i = 0; i < pathData.vertexCount; i++) { + if (i == nextPosition) { if (posPoints.remaining() > 0) // Don't advance beyond the last position index. + { nextPosition = posPoints.get(); + } pickColor = dc.getUniquePickColor(); maxColorCode = pickColor.getRGB(); } pickPositionColors.put((byte) pickColor.getRed()).put((byte) pickColor.getGreen()).put( - (byte) pickColor.getBlue()); + (byte) pickColor.getBlue()); } pickPositionColors.flip(); // Since this buffer is shared, the limit will likely be different each use. @@ -1852,22 +1775,23 @@ protected void addPickablePositions(DrawContext dc, PickSupport pickCandidates) * PickedObject's AVList contains the picked position's geographic position in the key AVKey.POSITION and its * ordinal number in the key AVKey.ORDINAL. * - * @param colorCode the color code corresponding to the picked position point. + * @param colorCode the color code corresponding to the picked position point. * @param positionIndex the position point's index. * * @return a PickedObject corresponding to the position point at the specified index. */ - protected PickedObject resolvePickedPosition(int colorCode, int positionIndex) - { + protected PickedObject resolvePickedPosition(int colorCode, int positionIndex) { PickedObject po = this.createPickedObject(colorCode); Position pos = this.getPosition(positionIndex); - if (pos != null) + if (pos != null) { po.setPosition(pos); + } Integer ordinal = this.getOrdinal(positionIndex); - if (ordinal != null) + if (ordinal != null) { po.setValue(AVKey.ORDINAL, ordinal); + } return po; } @@ -1877,36 +1801,36 @@ protected PickedObject resolvePickedPosition(int colorCode, int positionIndex) * path's tessellatedPositions and polePositions fields. * * @param pathData the current globe-specific path data. - * @param dc the current draw context. + * @param dc the current draw context. */ - protected void makeTessellatedPositions(DrawContext dc, PathData pathData) - { - if (this.numPositions < 2) + protected void makeTessellatedPositions(DrawContext dc, PathData pathData) { + if (this.numPositions < 2) { return; + } - if (pathData.tessellatedPositions == null || pathData.tessellatedPositions.size() < this.numPositions) - { + if (pathData.tessellatedPositions == null || pathData.tessellatedPositions.size() < this.numPositions) { int size = (this.numSubsegments * (this.numPositions - 1) + 1) * (this.isExtrude() ? 2 : 1); pathData.tessellatedPositions = new ArrayList(size); pathData.tessellatedColors = (this.positionColors != null) ? new ArrayList(size) : null; - } - else - { + } else { pathData.tessellatedPositions.clear(); - if (pathData.tessellatedColors != null) + if (pathData.tessellatedColors != null) { pathData.tessellatedColors.clear(); + } } - if (pathData.polePositions == null || pathData.polePositions.capacity() < this.numPositions * 2) + if (pathData.polePositions == null || pathData.polePositions.capacity() < this.numPositions * 2) { pathData.polePositions = Buffers.newDirectIntBuffer(this.numPositions * 2); - else + } else { pathData.polePositions.clear(); + } - if (pathData.positionPoints == null || pathData.positionPoints.capacity() < this.numPositions) + if (pathData.positionPoints == null || pathData.positionPoints.capacity() < this.numPositions) { pathData.positionPoints = Buffers.newDirectIntBuffer(this.numPositions); - else + } else { pathData.positionPoints.clear(); + } this.makePositions(dc, pathData); @@ -1914,31 +1838,31 @@ protected void makeTessellatedPositions(DrawContext dc, PathData pathData) pathData.polePositions.flip(); pathData.positionPoints.flip(); - if (pathData.tessellatedColors != null) + if (pathData.tessellatedColors != null) { pathData.tessellatedColors.trimToSize(); + } } /** * Computes this Path's distance from the eye point, for use in determining when to show positions points. The value * returned is only an approximation because the eye distance varies along the path. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pathData this path's current shape data. * * @return the distance of the shape from the eye point. If the eye distance cannot be computed, the eye position's * elevation is returned instead. */ - protected double getDistanceMetric(DrawContext dc, PathData pathData) - { + protected double getDistanceMetric(DrawContext dc, PathData pathData) { return pathData.getExtent() != null - ? WWMath.computeDistanceFromEye(dc, pathData.getExtent()) - : dc.getView().getEyePosition().getElevation(); + ? WWMath.computeDistanceFromEye(dc, pathData.getExtent()) + : dc.getView().getEyePosition().getElevation(); } - protected void makePositions(DrawContext dc, PathData pathData) - { - if (pathData.splitPositions != null) + protected void makePositions(DrawContext dc, PathData pathData) { + if (pathData.splitPositions != null) { pathData.splitPositions.clear(); + } Iterator iter = this.positions.iterator(); Position posA = iter.next(); @@ -1950,17 +1874,15 @@ protected void makePositions(DrawContext dc, PathData pathData) // Tessellate each segment of the path. Vec4 ptA = this.computePoint(dc.getTerrain(), posA); - while (iter.hasNext()) - { + while (iter.hasNext()) { Position posB = iter.next(); int ordinalB = ordinalA + 1; Color colorB = this.getColor(posB, ordinalB); Vec4 ptB = this.computePoint(dc.getTerrain(), posB); if (this.positionsSpanDateline && dc.is2DGlobe() - && posA.getLongitude().degrees != posB.getLongitude().degrees - && LatLon.locationsCrossDateline(posA, posB)) - { + && posA.getLongitude().degrees != posB.getLongitude().degrees + && LatLon.locationsCrossDateline(posA, posB)) { // Introduce two points at the dateline that cause the rendered path to break, with one side positive // longitude and the other side negative longitude. This break causes the rendered path to break into // separate lines during rendering. @@ -1968,13 +1890,12 @@ protected void makePositions(DrawContext dc, PathData pathData) // Compute the split position on the dateline. LatLon splitLocation = LatLon.intersectionWithMeridian(posA, posB, Angle.POS180, dc.getGlobe()); Position splitPosition = Position.fromDegrees(splitLocation.getLatitude().degrees, - 180 * Math.signum(posA.getLongitude().degrees), posA.getAltitude()); + 180 * Math.signum(posA.getLongitude().degrees), posA.getAltitude()); Vec4 splitPoint = this.computePoint(dc.getTerrain(), splitPosition); // Compute the color at the split position. Color splitColor = null; - if (colorA != null && colorB != null) - { + if (colorA != null && colorB != null) { double originalSegmentLength = this.computeSegmentLength(dc, posA, posB); double truncatedSegmentLength = this.computeSegmentLength(dc, posA, splitPosition); double s = truncatedSegmentLength / originalSegmentLength; @@ -1985,27 +1906,24 @@ protected void makePositions(DrawContext dc, PathData pathData) this.makeSegment(dc, posA, splitPosition, ptA, splitPoint, colorA, splitColor, ordinalA, -1, pathData); // Mark where the split position is so a new line is started there during rendering. - if (pathData.splitPositions == null) + if (pathData.splitPositions == null) { pathData.splitPositions = new ArrayList(1); + } pathData.splitPositions.add(pathData.tessellatedPositions.size()); // Make the corresponding split position on the dateline side with opposite sign of the first split // position. splitPosition = Position.fromDegrees(splitPosition.getLatitude().degrees, - -1 * splitPosition.getLongitude().degrees, splitPosition.getAltitude()); + -1 * splitPosition.getLongitude().degrees, splitPosition.getAltitude()); splitPoint = this.computePoint(dc.getTerrain(), splitPosition); // Create the tessellated-positions segment from the split position to the end position. this.addTessellatedPosition(splitPosition, splitColor, -1, pathData); this.makeSegment(dc, splitPosition, posB, splitPoint, ptB, splitColor, colorB, -1, ordinalB, pathData); - } - else if (this.isSmall(dc, ptA, ptB, 8) || !this.isSegmentVisible(dc, posA, posB, ptA, ptB)) - { + } else if (this.isSmall(dc, ptA, ptB, 8) || !this.isSegmentVisible(dc, posA, posB, ptA, ptB)) { // If the segment is very small or not visible, don't tessellate, just add the segment's end position. this.addTessellatedPosition(posB, colorB, ordinalB, pathData); - } - else - { + } else { this.makeSegment(dc, posA, posB, ptA, ptB, colorA, colorB, ordinalA, ordinalB, pathData); } @@ -2015,8 +1933,9 @@ else if (this.isSmall(dc, ptA, ptB, 8) || !this.isSegmentVisible(dc, posA, posB, colorA = colorB; } - if (this.positionsSpanDateline && dc.is2DGlobe()) + if (this.positionsSpanDateline && dc.is2DGlobe()) { this.makePath2DIndices(pathData); + } } /** @@ -2025,47 +1944,43 @@ else if (this.isSmall(dc, ptA, ptB, 8) || !this.isSegmentVisible(dc, posA, posB, * ordinal is not null, this adds the position's index to the polePositions and * positionPoints index buffers. * - * @param pos the position to add. - * @param color the color corresponding to the position. May be null to indicate that the position - * has no associated color. - * @param ordinal the ordinal number corresponding to the position's location in the original position list. May be - * null to indicate that the position is not one of the originally specified - * positions. + * @param pos the position to add. + * @param color the color corresponding to the position. May be null to indicate that the position has + * no associated color. + * @param ordinal the ordinal number corresponding to the position's location in the original position list. May be + * null to indicate that the position is not one of the originally specified positions. * @param pathData the current globe-specific path data. */ - protected void addTessellatedPosition(Position pos, Color color, Integer ordinal, PathData pathData) - { - if (ordinal != null && ordinal >= 0) - { + protected void addTessellatedPosition(Position pos, Color color, Integer ordinal, PathData pathData) { + if (ordinal != null && ordinal >= 0) { // NOTE: Assign these indices before adding the new position to the tessellatedPositions list. int index = pathData.tessellatedPositions.size() * 2; pathData.polePositions.put(index).put(index + 1); - if (pathData.hasExtrusionPoints) + if (pathData.hasExtrusionPoints) { pathData.positionPoints.put(index); - else + } else { pathData.positionPoints.put(pathData.tessellatedPositions.size()); + } } pathData.tessellatedPositions.add(pos); // be sure to do the add after the pole position is set - if (color != null) + if (color != null) { pathData.tessellatedColors.add(color); + } } - protected void makePath2DIndices(PathData pathData) - { + protected void makePath2DIndices(PathData pathData) { int size = pathData.tessellatedPositions.size() * 2 - 2; - if (pathData.path2DIndices == null || pathData.path2DIndices.capacity() != size) + if (pathData.path2DIndices == null || pathData.path2DIndices.capacity() != size) { pathData.path2DIndices = Buffers.newDirectIntBuffer(size); + } int currentIndex = 0; - if (pathData.splitPositions != null) - { - for (Integer splitIndex : pathData.splitPositions) - { - for (int i = currentIndex; i < splitIndex - 1; i++) - { + if (pathData.splitPositions != null) { + for (Integer splitIndex : pathData.splitPositions) { + for (int i = currentIndex; i < splitIndex - 1; i++) { pathData.path2DIndices.put(i).put(i + 1); } pathData.path2DIndices.put(splitIndex).put(splitIndex + 1); @@ -2073,8 +1988,7 @@ protected void makePath2DIndices(PathData pathData) } } - for (int i = currentIndex; i < pathData.tessellatedPositions.size() - 1; i++) - { + for (int i = currentIndex; i < pathData.tessellatedPositions.size() - 1; i++) { pathData.path2DIndices.put(i).put(i + 1); } @@ -2089,14 +2003,13 @@ protected void makePath2DIndices(PathData pathData) * * @return the Position corresponding to the specified index. */ - protected Position getPosition(int positionIndex) - { + protected Position getPosition(int positionIndex) { PathData pathData = this.getCurrentPathData(); // Get an index into the tessellatedPositions list. int index = pathData.positionPoints.get(positionIndex); // Return the originally specified position, which is stored in the tessellatedPositions list. - return (index >= 0 && index < pathData.tessellatedPositions.size()) ? - pathData.tessellatedPositions.get(index) : null; + return (index >= 0 && index < pathData.tessellatedPositions.size()) + ? pathData.tessellatedPositions.get(index) : null; } /** @@ -2107,8 +2020,7 @@ protected Position getPosition(int positionIndex) * * @return the ordinal number corresponding to the specified position index. */ - protected Integer getOrdinal(int positionIndex) - { + protected Integer getOrdinal(int positionIndex) { return positionIndex; } @@ -2118,16 +2030,16 @@ protected Integer getOrdinal(int positionIndex) * if this path's positionColors property is null. This returns white if a color cannot be determined * for the specified position and ordinal. * - * @param pos the path position the color corresponds to. + * @param pos the path position the color corresponds to. * @param ordinal the ordinal number of the specified position. * * @return an RGBA color corresponding to the position and ordinal, or null if this path's * positionColors property is null. */ - protected Color getColor(Position pos, Integer ordinal) - { - if (this.positionColors == null) + protected Color getColor(Position pos, Integer ordinal) { + if (this.positionColors == null) { return null; + } Color color = this.positionColors.getColor(pos, ordinal); return color != null ? color : Color.WHITE; @@ -2136,31 +2048,34 @@ protected Color getColor(Position pos, Integer ordinal) /** * Determines whether the segment between two path positions is visible. * - * @param dc the current draw context. + * @param dc the current draw context. * @param posA the segment's first position. * @param posB the segment's second position. - * @param ptA the model-coordinate point corresponding to the segment's first position. - * @param ptB the model-coordinate point corresponding to the segment's second position. + * @param ptA the model-coordinate point corresponding to the segment's first position. + * @param ptB the model-coordinate point corresponding to the segment's second position. * * @return true if the segment is visible relative to the current view frustum, otherwise false. */ - protected boolean isSegmentVisible(DrawContext dc, Position posA, Position posB, Vec4 ptA, Vec4 ptB) - { + protected boolean isSegmentVisible(DrawContext dc, Position posA, Position posB, Vec4 ptA, Vec4 ptB) { Frustum f = dc.getView().getFrustumInModelCoordinates(); - if (f.contains(ptA)) + if (f.contains(ptA)) { return true; + } - if (f.contains(ptB)) + if (f.contains(ptB)) { return true; + } - if (ptA.equals(ptB)) + if (ptA.equals(ptB)) { return false; + } Position posC = Position.interpolateRhumb(0.5, posA, posB); Vec4 ptC = this.computePoint(dc.getTerrain(), posC); - if (f.contains(ptC)) + if (f.contains(ptC)) { return true; + } double r = Line.distanceToSegment(ptA, ptB, ptC); Cylinder cyl = new Cylinder(ptA, ptB, r == 0 ? 1 : r); @@ -2170,38 +2085,38 @@ protected boolean isSegmentVisible(DrawContext dc, Position posA, Position posB, /** * Creates the interior segment positions to adhere to the current path type and terrain-following settings. * - * @param dc the current draw context. - * @param posA the segment's first position. - * @param posB the segment's second position. - * @param ptA the model-coordinate point corresponding to the segment's first position. - * @param ptB the model-coordinate point corresponding to the segment's second position. - * @param colorA the color corresponding to the segment's first position, or null if the first - * position has no associated color. - * @param colorB the color corresponding to the segment's second position, or null if the first - * position has no associated color. + * @param dc the current draw context. + * @param posA the segment's first position. + * @param posB the segment's second position. + * @param ptA the model-coordinate point corresponding to the segment's first position. + * @param ptB the model-coordinate point corresponding to the segment's second position. + * @param colorA the color corresponding to the segment's first position, or null if the first position + * has no associated color. + * @param colorB the color corresponding to the segment's second position, or null if the first + * position has no associated color. * @param ordinalA the ordinal number corresponding to the segment's first position in the original position list. * @param ordinalB the ordinal number corresponding to the segment's second position in the original position list. * @param pathData the current globe-specific path data. */ @SuppressWarnings({"StringEquality", "UnusedParameters"}) protected void makeSegment(DrawContext dc, Position posA, Position posB, Vec4 ptA, Vec4 ptB, Color colorA, - Color colorB, int ordinalA, int ordinalB, PathData pathData) - { + Color colorB, int ordinalA, int ordinalB, PathData pathData) { // This method does not add the first position of the segment to the position list. It adds only the // subsequent positions, including the segment's last position. boolean straightLine = this.getPathType() == AVKey.LINEAR && !this.isSurfacePath(dc); double arcLength; - if (straightLine) + if (straightLine) { arcLength = ptA.distanceTo3(ptB); - else + } else { arcLength = this.computeSegmentLength(dc, posA, posB); + } - if (arcLength <= 0 || straightLine) - { - if (!ptA.equals(ptB) || (this.positionsSpanDateline && dc.is2DGlobe())) + if (arcLength <= 0 || straightLine) { + if (!ptA.equals(ptB) || (this.positionsSpanDateline && dc.is2DGlobe())) { this.addTessellatedPosition(posB, colorB, ordinalB, pathData); + } return; } @@ -2209,25 +2124,23 @@ protected void makeSegment(DrawContext dc, Position posA, Position posB, Vec4 pt Angle segmentAzimuth = null; Angle segmentDistance = null; - for (double s = 0, p = 0; s < 1; ) - { - if (this.isFollowTerrain() || dc.is2DGlobe()) + for (double s = 0, p = 0; s < 1;) { + if (this.isFollowTerrain() || dc.is2DGlobe()) { p += this.terrainConformance * dc.getView().computePixelSizeAtDistance( - ptA.distanceTo3(dc.getView().getEyePoint())); - else + ptA.distanceTo3(dc.getView().getEyePoint())); + } else { p += arcLength / this.numSubsegments; + } - if (arcLength < p || arcLength - p < 1e-9) + if (arcLength < p || arcLength - p < 1e-9) { break; // position is either beyond the arc length or the remaining distance is in millimeters on Earth - + } Position pos; Color color; s = p / arcLength; - if (this.pathType == AVKey.LINEAR) - { - if (segmentAzimuth == null) - { + if (this.pathType == AVKey.LINEAR) { + if (segmentAzimuth == null) { segmentAzimuth = LatLon.linearAzimuth(posA, posB); segmentDistance = LatLon.linearDistance(posA, posB); } @@ -2235,11 +2148,8 @@ protected void makeSegment(DrawContext dc, Position posA, Position posB, Vec4 pt LatLon latLon = LatLon.linearEndPosition(posA, segmentAzimuth, distance); pos = new Position(latLon, (1 - s) * posA.getElevation() + s * posB.getElevation()); color = (colorA != null && colorB != null) ? WWUtil.interpolateColor(s, colorA, colorB) : null; - } - else if (this.pathType == AVKey.RHUMB_LINE || this.pathType == AVKey.LOXODROME) - { - if (segmentAzimuth == null) - { + } else if (this.pathType == AVKey.RHUMB_LINE || this.pathType == AVKey.LOXODROME) { + if (segmentAzimuth == null) { segmentAzimuth = LatLon.rhumbAzimuth(posA, posB); segmentDistance = LatLon.rhumbDistance(posA, posB); } @@ -2247,11 +2157,9 @@ else if (this.pathType == AVKey.RHUMB_LINE || this.pathType == AVKey.LOXODROME) LatLon latLon = LatLon.rhumbEndPosition(posA, segmentAzimuth, distance); pos = new Position(latLon, (1 - s) * posA.getElevation() + s * posB.getElevation()); color = (colorA != null && colorB != null) ? WWUtil.interpolateColor(s, colorA, colorB) : null; - } - else // GREAT_CIRCLE + } else // GREAT_CIRCLE { - if (segmentAzimuth == null) - { + if (segmentAzimuth == null) { segmentAzimuth = LatLon.greatCircleAzimuth(posA, posB); segmentDistance = LatLon.greatCircleDistance(posA, posB); } @@ -2273,29 +2181,31 @@ else if (this.pathType == AVKey.RHUMB_LINE || this.pathType == AVKey.LOXODROME) * Computes the approximate model-coordinate, path length between two positions. The length of the path depends on * the path type: great circle, rhumb, or linear. * - * @param dc the current draw context. + * @param dc the current draw context. * @param posA the first position. * @param posB the second position. * * @return the distance between the positions. */ @SuppressWarnings({"StringEquality"}) - protected double computeSegmentLength(DrawContext dc, Position posA, Position posB) - { + protected double computeSegmentLength(DrawContext dc, Position posA, Position posB) { LatLon llA = new LatLon(posA.getLatitude(), posA.getLongitude()); LatLon llB = new LatLon(posB.getLatitude(), posB.getLongitude()); Angle ang; String pathType = this.getPathType(); - if (pathType == AVKey.LINEAR) + if (pathType == AVKey.LINEAR) { ang = LatLon.linearDistance(llA, llB); - else if (pathType == AVKey.RHUMB_LINE || pathType == AVKey.LOXODROME) + } else if (pathType == AVKey.RHUMB_LINE || pathType == AVKey.LOXODROME) { ang = LatLon.rhumbDistance(llA, llB); - else // Great circle + } else // Great circle + { ang = LatLon.greatCircleDistance(llA, llB); + } - if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND) + if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND) { return ang.radians * (dc.getGlobe().getRadius()); + } double height = 0.5 * (posA.getElevation() + posB.getElevation()); return ang.radians * (dc.getGlobe().getRadius() + height * dc.getVerticalExaggeration()); @@ -2308,17 +2218,18 @@ else if (pathType == AVKey.RHUMB_LINE || pathType == AVKey.LOXODROME) * * @return the computed reference center, or null if it cannot be computed. */ - protected Vec4 computeReferenceCenter(DrawContext dc) - { - if (this.positions == null) + protected Vec4 computeReferenceCenter(DrawContext dc) { + if (this.positions == null) { return null; + } Position pos = this.getReferencePosition(); - if (pos == null) + if (pos == null) { return null; + } return dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), - dc.getVerticalExaggeration() * pos.getAltitude()); + dc.getVerticalExaggeration() * pos.getAltitude()); } /** @@ -2326,32 +2237,32 @@ protected Vec4 computeReferenceCenter(DrawContext dc) *

          * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * - * @param dc the draw context. + * @param dc the draw context. * @param pathData the current shape data for this shape. * * @return the minimum distance from the shape to the eye point. */ - protected double computeEyeDistance(DrawContext dc, PathData pathData) - { + protected double computeEyeDistance(DrawContext dc, PathData pathData) { double minDistanceSquared = Double.MAX_VALUE; Vec4 eyePoint = dc.getView().getEyePoint(); Vec4 refPt = pathData.getReferencePoint(); pathData.renderedPath.rewind(); - while (pathData.renderedPath.hasRemaining()) - { + while (pathData.renderedPath.hasRemaining()) { double x = eyePoint.x - (pathData.renderedPath.get() + refPt.x); double y = eyePoint.y - (pathData.renderedPath.get() + refPt.y); double z = eyePoint.z - (pathData.renderedPath.get() + refPt.z); double d = x * x + y * y + z * z; - if (d < minDistanceSquared) + if (d < minDistanceSquared) { minDistanceSquared = d; + } // If the renderedPath contains RGBA color tuples in between each XYZ coordinate tuple, advance the // renderedPath's position to the next XYZ coordinate tuple. - if (pathData.vertexStride > 3) + if (pathData.vertexStride > 3) { pathData.renderedPath.position(pathData.renderedPath.position() + pathData.vertexStride - 3); + } } return Math.sqrt(minDistanceSquared); @@ -2364,14 +2275,14 @@ protected double computeEyeDistance(DrawContext dc, PathData pathData) * * @return the computed extent. */ - protected Extent computeExtent(PathData current) - { - if (current.renderedPath == null) + protected Extent computeExtent(PathData current) { + if (current.renderedPath == null) { return null; + } current.renderedPath.rewind(); Box box = Box.computeBoundingBox(new BufferWrapper.FloatBufferWrapper(current.renderedPath), - current.vertexStride); + current.vertexStride); // The path points are relative to the reference center, so translate the extent to the reference center. box = box.translate(current.getReferencePoint()); @@ -2379,22 +2290,24 @@ protected Extent computeExtent(PathData current) return box; } - public Extent getExtent(Globe globe, double verticalExaggeration) - { + public Extent getExtent(Globe globe, double verticalExaggeration) { // See if we've cached an extent associated with the globe. Extent extent = super.getExtent(globe, verticalExaggeration); - if (extent != null) + if (extent != null) { return extent; + } PathData current = (PathData) this.shapeDataCache.getEntry(globe); - if (current == null) + if (current == null) { return null; + } // Use the tessellated positions if they exist because they best represent the actual shape. Iterable posits = current.tessellatedPositions != null - ? current.tessellatedPositions : this.getPositions(); - if (posits == null) + ? current.tessellatedPositions : this.getPositions(); + if (posits == null) { return null; + } return super.computeExtentFromPositions(globe, verticalExaggeration, posits); } @@ -2405,19 +2318,16 @@ public Extent getExtent(Globe globe, double verticalExaggeration) * * @return the computed reference position. */ - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.numPositions < 1 ? null : this.positions.iterator().next(); // use the first position } - protected void fillVBO(DrawContext dc) - { + protected void fillVBO(DrawContext dc) { PathData pathData = this.getCurrentPathData(); int numIds = this.isShowPositions() ? 3 : pathData.hasExtrusionPoints && this.isDrawVerticals() ? 2 : 1; int[] vboIds = (int[]) dc.getGpuResourceCache().get(pathData.getVboCacheKey()); - if (vboIds != null && vboIds.length != numIds) - { + if (vboIds != null && vboIds.length != numIds) { this.clearCachedVbos(dc); vboIds = null; } @@ -2426,40 +2336,35 @@ protected void fillVBO(DrawContext dc) int vSize = pathData.renderedPath.limit() * 4; int iSize = pathData.hasExtrusionPoints - && this.isDrawVerticals() ? pathData.tessellatedPositions.size() * 2 * 4 : 0; - if (this.isShowPositions()) + && this.isDrawVerticals() ? pathData.tessellatedPositions.size() * 2 * 4 : 0; + if (this.isShowPositions()) { iSize += pathData.tessellatedPositions.size(); + } - if (vboIds == null) - { + if (vboIds == null) { vboIds = new int[numIds]; gl.glGenBuffers(vboIds.length, vboIds, 0); dc.getGpuResourceCache().put(pathData.getVboCacheKey(), vboIds, GpuResourceCache.VBO_BUFFERS, - vSize + iSize); + vSize + iSize); } - try - { + try { FloatBuffer vb = pathData.renderedPath; gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]); gl.glBufferData(GL.GL_ARRAY_BUFFER, vb.limit() * 4, vb.rewind(), GL.GL_STATIC_DRAW); - if (pathData.hasExtrusionPoints && this.isDrawVerticals()) - { + if (pathData.hasExtrusionPoints && this.isDrawVerticals()) { IntBuffer ib = pathData.polePositions; gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboIds[1]); gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, ib.limit() * 4, ib.rewind(), GL.GL_STATIC_DRAW); } - if (this.isShowPositions()) - { + if (this.isShowPositions()) { IntBuffer ib = pathData.positionPoints; gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboIds[2]); gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, ib.limit() * 4, ib.rewind(), GL.GL_STATIC_DRAW); } - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); } @@ -2471,10 +2376,8 @@ public List intersect(Line line, Terrain terrain) throws Interrupt return null; } - public void move(Position delta) - { - if (delta == null) - { + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -2485,76 +2388,77 @@ public void move(Position delta) // The reference position is null if this Path has no positions. In this case moving the Path by a // relative delta is meaningless because the Path has no geographic location. Therefore we fail softly by // exiting and doing nothing. - if (refPos == null) + if (refPos == null) { return; + } this.moveTo(refPos.add(delta)); } - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.numPositions == 0) + if (this.numPositions == 0) { return; + } Position oldPosition = this.getReferencePosition(); // The reference position is null if this Path has no positions. In this case moving the Path to a new // reference position is meaningless because the Path has no geographic location. Therefore we fail softly // by exiting and doing nothing. - if (oldPosition == null) + if (oldPosition == null) { return; + } List newPositions = Position.computeShiftedPositions(oldPosition, position, this.positions); - if (newPositions != null) + if (newPositions != null) { this.setPositions(newPositions); + } } @Override - public void moveTo(Globe globe, Position position) - { - if (position == null) - { + public void moveTo(Globe globe, Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.numPositions == 0) + if (this.numPositions == 0) { return; + } Position oldPosition = this.getReferencePosition(); // The reference position is null if this Path has no positions. In this case moving the Path to a new // reference position is meaningless because the Path has no geographic location. Therefore we fail softly // by exiting and doing nothing. - if (oldPosition == null) + if (oldPosition == null) { return; + } List newPositions = Position.computeShiftedPositions(globe, oldPosition, position, this.positions); - if (newPositions != null) - { + if (newPositions != null) { this.setPositions(newPositions); } } - protected boolean isSmall(DrawContext dc, Vec4 ptA, Vec4 ptB, int numPixels) - { + protected boolean isSmall(DrawContext dc, Vec4 ptA, Vec4 ptB, int numPixels) { return ptA.distanceTo3(ptB) <= numPixels * dc.getView().computePixelSizeAtDistance( - dc.getView().getEyePoint().distanceTo3(ptA)); + dc.getView().getEyePoint().distanceTo3(ptA)); } - /** {@inheritDoc} */ - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + /** + * {@inheritDoc} + */ + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { // Write geometry xmlWriter.writeStartElement("LineString"); @@ -2572,12 +2476,11 @@ protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLS xmlWriter.writeEndElement(); xmlWriter.writeStartElement("coordinates"); - for (Position position : this.positions) - { + for (Position position : this.positions) { xmlWriter.writeCharacters(String.format(Locale.US, "%f,%f,%f ", - position.getLongitude().getDegrees(), - position.getLatitude().getDegrees(), - position.getElevation())); + position.getLongitude().getDegrees(), + position.getLatitude().getDegrees(), + position.getElevation())); } xmlWriter.writeEndElement(); diff --git a/src/gov/nasa/worldwind/render/PatternFactory.java b/src/gov/nasa/worldwind/render/PatternFactory.java index 8ed3df8b92..360f49d2ec 100644 --- a/src/gov/nasa/worldwind/render/PatternFactory.java +++ b/src/gov/nasa/worldwind/render/PatternFactory.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import java.awt.image.*; @@ -21,6 +20,7 @@ * With a scale of zero no pattern will be produced. With a scale of one the pattern will * cover all the background. *

          + * * @author Patrick Murris * @version $Id: PatternFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ @@ -46,83 +46,84 @@ public class PatternFactory { private static Color defaultBackColor = new Color(0f, 0f, 0f, 0f); /** - * Draws a pattern using the default scale (.5), bitmap dimensions (32x32) and colors (light grey over - * a transparent background). + * Draws a pattern using the default scale (.5), bitmap dimensions (32x32) and colors (light grey over a transparent + * background). + * * @param pattern the pattern to draw. See {@link PatternFactory} static constants. * @return the corresponding BufferedImage. */ - public static BufferedImage createPattern(String pattern) - { + public static BufferedImage createPattern(String pattern) { return createPattern(pattern, defaultDimension, defaultScale, defaultLineColor, defaultBackColor); } /** - * Draws a pattern with a given Color using the default scale (.5), bitmap dimensions (32x32) - * and backgound color (transparent). + * Draws a pattern with a given Color using the default scale (.5), bitmap dimensions (32x32) and + * backgound color (transparent). + * * @param pattern the pattern to draw. See {@link PatternFactory} static constants. * @param lineColor the pattern Color. * @return the corresponding BufferedImage. */ - public static BufferedImage createPattern(String pattern, Color lineColor) - { + public static BufferedImage createPattern(String pattern, Color lineColor) { return createPattern(pattern, defaultDimension, defaultScale, lineColor, defaultBackColor); } /** - * Draws a pattern with a given scale using the default bitmap dimensions (32x32) and colors - * (light grey over a transparent background). + * Draws a pattern with a given scale using the default bitmap dimensions (32x32) and colors (light + * grey over a transparent background). + * * @param pattern the pattern to draw. See {@link PatternFactory} static constants. * @param scale the scale at which the pattern should be drawn (0 to 1). * @return the corresponding BufferedImage. */ - public static BufferedImage createPattern(String pattern, float scale) - { + public static BufferedImage createPattern(String pattern, float scale) { return createPattern(pattern, defaultDimension, scale, defaultLineColor, defaultBackColor); } /** - * Draws a pattern with a given scale and Color using the default bitmap - * dimensions (32x32) and backgound color (transparent). + * Draws a pattern with a given scale and Color using the default bitmap dimensions + * (32x32) and backgound color (transparent). + * * @param pattern the pattern to draw. See {@link PatternFactory} static constants. * @param scale the scale at which the pattern should be drawn (0 to 1). * @param lineColor the pattern Color. * @return the corresponding BufferedImage. */ - public static BufferedImage createPattern(String pattern, float scale, Color lineColor) - { + public static BufferedImage createPattern(String pattern, float scale, Color lineColor) { return createPattern(pattern, defaultDimension, scale, lineColor, defaultBackColor); } /** - * Draws a pattern with a given scale and Colors using the default bitmap - * dimensions (32x32). + * Draws a pattern with a given scale and Colors using the default bitmap dimensions + * (32x32). + * * @param pattern the pattern to draw. See {@link PatternFactory} static constants. * @param scale the scale at which the pattern should be drawn (0 to 1). * @param lineColor the pattern Color. * @param backColor the pattern background Color. * @return the corresponding BufferedImage. */ - public static BufferedImage createPattern(String pattern, float scale, Color lineColor, Color backColor) - { + public static BufferedImage createPattern(String pattern, float scale, Color lineColor, Color backColor) { return createPattern(pattern, defaultDimension, scale, lineColor, backColor); } /** - * Draws a pattern with a given scale, Color and bitmap - * dimensions, using the default backgound color (transparent). + * Draws a pattern with a given scale, Color and bitmap dimensions, using the default + * backgound color (transparent). + * * @param pattern the pattern to draw. See {@link PatternFactory} static constants. * @param size the Dimension of the BufferedImage produced. * @param scale the scale at which the pattern should be drawn (0 to 1). * @param lineColor the pattern Color. * @return the corresponding BufferedImage. */ - public static BufferedImage createPattern(String pattern, Dimension size, float scale, Color lineColor) - { + public static BufferedImage createPattern(String pattern, Dimension size, float scale, Color lineColor) { return createPattern(pattern, size, scale, lineColor, defaultBackColor); } /** * Draws a pattern with the given scale, Colors and bitmap dimensions. + * * @param pattern the pattern to draw. See {@link PatternFactory} static constants. * @param size the Dimension of the BufferedImage produced. * @param scale the scale at which the pattern should be drawn (0 to 1). @@ -130,49 +131,41 @@ public static BufferedImage createPattern(String pattern, Dimension size, float * @param backColor the pattern background Color. * @return the corresponding BufferedImage. */ - public static BufferedImage createPattern(String pattern, Dimension size, float scale, Color lineColor, Color backColor) - { + public static BufferedImage createPattern(String pattern, Dimension size, float scale, Color lineColor, Color backColor) { int halfWidth = size.width / 2; int halfHeight = size.height / 2; - int dim = (int)(size.width * scale); - BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_4BYTE_ABGR); + int dim = (int) (size.width * scale); + BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Background g2.setPaint(backColor); g2.fillRect(0, 0, size.width, size.height); - if (scale <= 0) + if (scale <= 0) { return image; + } // Pattern g2.setPaint(lineColor); g2.setStroke(new BasicStroke(dim)); - if (pattern.equals(PATTERN_HLINE)) - { + if (pattern.equals(PATTERN_HLINE)) { int y = halfHeight - 1 - dim / 2; g2.fillRect(0, y, size.width, dim); - } - else if (pattern.equals(PATTERN_VLINE)) - { + } else if (pattern.equals(PATTERN_VLINE)) { int x = halfWidth - 1 - dim / 2; g2.fillRect(x, 0, dim, size.height); } - if (pattern.equals(PATTERN_HVLINE)) - { + if (pattern.equals(PATTERN_HVLINE)) { int x = halfWidth - 1 - dim / 2; g2.fillRect(x, 0, dim, size.height); int y = halfHeight - 1 - dim / 2; g2.fillRect(0, y, size.width, dim); - } - else if (pattern.equals(PATTERN_SQUARE)) - { + } else if (pattern.equals(PATTERN_SQUARE)) { int x = halfWidth - dim / 2; int y = halfHeight - dim / 2; g2.fillRect(x, y, dim, dim); - } - else if (pattern.equals(PATTERN_SQUARES)) - { + } else if (pattern.equals(PATTERN_SQUARES)) { int x = halfWidth - 1 - dim / 2; int y = halfHeight - 1 - dim / 2; g2.fillRect(x, y, dim, dim); @@ -180,15 +173,11 @@ else if (pattern.equals(PATTERN_SQUARES)) g2.fillRect(x - halfWidth, y + halfHeight, dim, dim); g2.fillRect(x + halfWidth, y - halfHeight, dim, dim); g2.fillRect(x + halfWidth, y + halfHeight, dim, dim); - } - else if (pattern.equals(PATTERN_CIRCLE)) - { + } else if (pattern.equals(PATTERN_CIRCLE)) { int x = halfWidth - dim / 2; int y = halfHeight - dim / 2; g2.fillOval(x, y, dim, dim); - } - else if (pattern.equals(PATTERN_CIRCLES)) - { + } else if (pattern.equals(PATTERN_CIRCLES)) { int x = halfWidth - 1 - dim / 2; int y = halfHeight - 1 - dim / 2; g2.fillOval(x, y, dim, dim); @@ -196,36 +185,27 @@ else if (pattern.equals(PATTERN_CIRCLES)) g2.fillOval(x - halfWidth, y + halfHeight, dim, dim); g2.fillOval(x + halfWidth, y - halfHeight, dim, dim); g2.fillOval(x + halfWidth, y + halfHeight, dim, dim); - } - else if (pattern.equals(PATTERN_TRIANGLE_UP)) - { + } else if (pattern.equals(PATTERN_TRIANGLE_UP)) { GeneralPath path = new GeneralPath(); path.moveTo(halfWidth - 1 - dim / 2, halfHeight - 1 + dim / 2); path.lineTo(halfWidth - 1, halfHeight - 1 - dim / 2); path.lineTo(halfWidth - 1 + dim / 2, halfHeight - 1 + dim / 2); path.lineTo(halfWidth - 1 - dim / 2, halfHeight - 1 + dim / 2); g2.fill(path); - } - else if (pattern.equals(PATTERN_DIAGONAL_UP) || pattern.equals(PATTERN_DIAGONAL_DOWN)) - { - if (pattern.equals(PATTERN_DIAGONAL_DOWN)) - { + } else if (pattern.equals(PATTERN_DIAGONAL_UP) || pattern.equals(PATTERN_DIAGONAL_DOWN)) { + if (pattern.equals(PATTERN_DIAGONAL_DOWN)) { AffineTransform at = AffineTransform.getScaleInstance(-1, 1); at.translate(-size.width, 0); g2.setTransform(at); } - g2.drawLine(-dim, size.height - 1 + dim, size.width - 1 + dim, - dim); - g2.drawLine(-dim - 1, dim, dim - 1, - dim); + g2.drawLine(-dim, size.height - 1 + dim, size.width - 1 + dim, -dim); + g2.drawLine(-dim - 1, dim, dim - 1, -dim); g2.drawLine(size.width - dim, size.height - 1 + dim, size.width + dim, size.height - 1 - dim); - } - else if (pattern.equals(GRADIENT_VLINEAR)) - { - g2.setPaint(new GradientPaint((float)halfWidth, 0f, lineColor, (float)halfWidth, (float)size.height - 1, backColor)); + } else if (pattern.equals(GRADIENT_VLINEAR)) { + g2.setPaint(new GradientPaint((float) halfWidth, 0f, lineColor, (float) halfWidth, (float) size.height - 1, backColor)); g2.fillRect(0, 0, size.width, size.height); - } - else if (pattern.equals(GRADIENT_HLINEAR)) - { - g2.setPaint(new GradientPaint(0f, halfHeight, lineColor, (float)size.width - 1, halfHeight, backColor)); + } else if (pattern.equals(GRADIENT_HLINEAR)) { + g2.setPaint(new GradientPaint(0f, halfHeight, lineColor, (float) size.width - 1, halfHeight, backColor)); g2.fillRect(0, 0, size.width, size.height); } @@ -233,32 +213,32 @@ else if (pattern.equals(GRADIENT_HLINEAR)) } // Convolution processing - /** * Blurs an image. + * * @param sourceImage the image to blur. * @return the blurred image. */ - public static BufferedImage blur(BufferedImage sourceImage) - { + public static BufferedImage blur(BufferedImage sourceImage) { return blur(sourceImage, 3); } /** * Blurs an image with a specified convolution matrix size. + * * @param sourceImage the image to blur. * @param kernelSize the convolution matrix size. * @return the blurred image. */ - public static BufferedImage blur(BufferedImage sourceImage, int kernelSize) - { + public static BufferedImage blur(BufferedImage sourceImage, int kernelSize) { int size = kernelSize * kernelSize; float value = 1f / size; float[] matrix = new float[size]; - for (int i = 0; i < size; i++) + for (int i = 0; i < size; i++) { matrix[i] = value; - BufferedImage destImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); - BufferedImageOp op = new ConvolveOp( new Kernel(kernelSize, kernelSize, matrix) ); + } + BufferedImage destImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); + BufferedImageOp op = new ConvolveOp(new Kernel(kernelSize, kernelSize, matrix)); op.filter(sourceImage, destImage); return destImage; } diff --git a/src/gov/nasa/worldwind/render/Pedestal.java b/src/gov/nasa/worldwind/render/Pedestal.java index 378aa37e73..56f5363842 100644 --- a/src/gov/nasa/worldwind/render/Pedestal.java +++ b/src/gov/nasa/worldwind/render/Pedestal.java @@ -13,33 +13,28 @@ * @author tag * @version $Id: Pedestal.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Pedestal extends UserFacingIcon -{ +public class Pedestal extends UserFacingIcon { + private double spacingPixels = 2d; private double scale = 1d; - public Pedestal(String iconPath, Position iconPosition) - { + public Pedestal(String iconPath, Position iconPosition) { super(iconPath, iconPosition); } - public double getSpacingPixels() - { + public double getSpacingPixels() { return spacingPixels; } - public void setSpacingPixels(double spacingPixels) - { + public void setSpacingPixels(double spacingPixels) { this.spacingPixels = spacingPixels; } - public double getScale() - { + public double getScale() { return scale; } - public void setScale(double scale) - { + public void setScale(double scale) { this.scale = scale; } @@ -48,20 +43,15 @@ public void setScale(double scale) * * @return XML state document string describing this Pedestal. */ - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport restorableSupport = null; // Try to parse the superclass' xml state document, if it defined one. String superStateInXml = super.getRestorableState(); - if (superStateInXml != null) - { - try - { + if (superStateInXml != null) { + try { restorableSupport = RestorableSupport.parse(superStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by the superclass failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", superStateInXml); Logging.logger().severe(message); @@ -69,11 +59,13 @@ public String getRestorableState() } // Create our own state document from scratch. - if (restorableSupport == null) + if (restorableSupport == null) { restorableSupport = RestorableSupport.newRestorableSupport(); + } // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (restorableSupport == null) + if (restorableSupport == null) { return null; + } restorableSupport.addStateValueAsDouble("spacingPixels", this.spacingPixels); restorableSupport.addStateValueAsDouble("scale", this.scale); @@ -82,41 +74,33 @@ public String getRestorableState() } /** - * Restores publicly settable attribute values found in the specified XML state document String. The - * document specified by stateInXml must be a well formed XML document String, or this will throw an - * IllegalArgumentException. Unknown structures in stateInXml are benign, because they will - * simply be ignored. + * Restores publicly settable attribute values found in the specified XML state document String. The document + * specified by stateInXml must be a well formed XML document String, or this will throw an + * IllegalArgumentException. Unknown structures in stateInXml are benign, because they will simply be + * ignored. * * @param stateInXml an XML document String describing a Pedestal. - * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not - * a well formed XML document String. + * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not a well + * formed XML document String. */ - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Allow the superclass to restore it's state. - try - { + try { super.restoreState(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Superclass will log the exception. } RestorableSupport restorableSupport; - try - { + try { restorableSupport = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -124,11 +108,13 @@ public void restoreState(String stateInXml) } Double spacingPixelsState = restorableSupport.getStateValueAsDouble("spacingPixels"); - if (spacingPixelsState != null) + if (spacingPixelsState != null) { setSpacingPixels(spacingPixelsState); + } Double scaleState = restorableSupport.getStateValueAsDouble("scale"); - if (scaleState != null) + if (scaleState != null) { setScale(scaleState); + } } } diff --git a/src/gov/nasa/worldwind/render/PointPlacemark.java b/src/gov/nasa/worldwind/render/PointPlacemark.java index b8bb7953c3..d31c705fad 100644 --- a/src/gov/nasa/worldwind/render/PointPlacemark.java +++ b/src/gov/nasa/worldwind/render/PointPlacemark.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.*; @@ -48,32 +47,38 @@ * @version $Id: PointPlacemark.java 3028 2015-04-17 00:10:19Z tgaskins $ */ public class PointPlacemark extends WWObjectImpl - implements Renderable, Locatable, Movable, Highlightable, Exportable, Draggable -{ + implements Renderable, Locatable, Movable, Highlightable, Exportable, Draggable { + /** * An interface to enable application selection of placemark level of detail. */ - public interface LODSelector - { + public interface LODSelector { + /** - * Modifies the placemark's attributes and properties to achieve a desired level of detail during rendering. This - * method is called during rendering in order to provide the application an opportunity to adjust the placemark's - * attributes and properties to achieve a level of detail based on the placemark's distance from the view's eye - * point or other criteria. + * Modifies the placemark's attributes and properties to achieve a desired level of detail during rendering. + * This method is called during rendering in order to provide the application an opportunity to adjust the + * placemark's attributes and properties to achieve a level of detail based on the placemark's distance from the + * view's eye point or other criteria. * - * @param dc the current draw context. - * @param placemark the placemark about to be rendered. + * @param dc the current draw context. + * @param placemark the placemark about to be rendered. * @param eyeDistance the distance in meters from the view's eye point to the placemark's geographic position. */ void selectLOD(DrawContext dc, PointPlacemark placemark, double eyeDistance); } - /** The scale to use when highlighting if no highlight attributes are specified. */ + /** + * The scale to use when highlighting if no highlight attributes are specified. + */ protected static final Double DEFAULT_HIGHLIGHT_SCALE = 1.3; - /** The label offset to use if none is specified but an image has been specified. */ + /** + * The label offset to use if none is specified but an image has been specified. + */ protected static final Offset DEFAULT_LABEL_OFFSET_IF_UNSPECIFIED = new Offset(1d, 0.6d, AVKey.FRACTION, - AVKey.FRACTION); - /** The point size to use when none is specified. */ + AVKey.FRACTION); + /** + * The point size to use when none is specified. + */ protected static final Double DEFAULT_POINT_SIZE = 5d; /** * The address of the transparent image used when attributes.isDrawImage is false. @@ -84,11 +89,12 @@ public interface LODSelector protected static final int PICK_Y_OFFSET = -5; protected static final int PICK_Y_SIZE_DELTA = 2; - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static final PointPlacemarkAttributes defaultAttributes = new PointPlacemarkAttributes(); - static - { + static { defaultAttributes.setImageAddress(PointPlacemarkAttributes.DEFAULT_IMAGE_PATH); defaultAttributes.setImageOffset(PointPlacemarkAttributes.DEFAULT_IMAGE_OFFSET); defaultAttributes.setLabelOffset(PointPlacemarkAttributes.DEFAULT_LABEL_OFFSET); @@ -96,86 +102,72 @@ public interface LODSelector defaultAttributes.setLabelScale(PointPlacemarkAttributes.DEFAULT_LABEL_SCALE); } - public class OrderedPlacemark implements OrderedRenderable, Declutterable - { + public class OrderedPlacemark implements OrderedRenderable, Declutterable { + protected Vec4 placePoint; // the Cartesian point corresponding to the placemark position protected Vec4 terrainPoint; // point on the terrain extruded from the placemark position. protected Vec4 screenPoint; // the projection of the place-point in the viewport (on the screen) protected double eyeDistance; // used to order the placemark as an ordered renderable protected Rectangle imageBounds; - public PointPlacemark getPlacemark() - { + public PointPlacemark getPlacemark() { return PointPlacemark.this; } @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - public Vec4 getScreenPoint() - { + public Vec4 getScreenPoint() { return this.screenPoint; } - public boolean isEnableBatchRendering() - { + public boolean isEnableBatchRendering() { return PointPlacemark.this.isEnableBatchRendering(); } - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return PointPlacemark.this.isEnableBatchPicking(); } - public Layer getPickLayer() - { + public Layer getPickLayer() { return PointPlacemark.this.pickLayer; } @Override - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { PointPlacemark.this.pick(dc, pickPoint, this); } @Override - public void render(DrawContext dc) - { + public void render(DrawContext dc) { PointPlacemark.this.drawOrderedRenderable(dc, this); } - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) - { + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) { PointPlacemark.this.doDrawOrderedRenderable(dc, pickCandidates, this); } @Override - public boolean isEnableDecluttering() - { + public boolean isEnableDecluttering() { return PointPlacemark.this.isEnableDecluttering(); } @Override - public Rectangle2D getBounds(DrawContext dc) - { + public Rectangle2D getBounds(DrawContext dc) { return PointPlacemark.this.getLabelBounds(dc, this); } - public Rectangle getImageBounds() - { + public Rectangle getImageBounds() { return imageBounds; } - public Vec4 getPlacePoint() - { + public Vec4 getPlacePoint() { return placePoint; } - public Vec4 getTerrainPoint() - { + public Vec4 getTerrainPoint() { return terrainPoint; } } @@ -224,10 +216,8 @@ public Vec4 getTerrainPoint() * * @throws IllegalArgumentException if the position is null. */ - public PointPlacemark(Position position) - { - if (position == null) - { + public PointPlacemark(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -243,10 +233,8 @@ public PointPlacemark(Position position) * * @throws IllegalArgumentException if the position is null. */ - public void setPosition(Position position) - { - if (position == null) - { + public void setPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -260,8 +248,7 @@ public void setPosition(Position position) * * @return the placemark's position. */ - public Position getPosition() - { + public Position getPosition() { return this.position; } @@ -270,8 +257,7 @@ public Position getPosition() * * @return true if the placemark is drawn when in view, otherwise false. */ - public boolean isVisible() - { + public boolean isVisible() { return this.visible; } @@ -280,8 +266,7 @@ public boolean isVisible() * * @param visible true if the placemark is drawn when in view, otherwise false. */ - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.visible = visible; } @@ -290,8 +275,7 @@ public void setVisible(boolean visible) * * @return the placemark's altitude mode. */ - public int getAltitudeMode() - { + public int getAltitudeMode() { return this.altitudeMode; } @@ -304,8 +288,7 @@ public int getAltitudeMode() * * @param altitudeMode the altitude mode */ - public void setAltitudeMode(int altitudeMode) - { + public void setAltitudeMode(int altitudeMode) { this.altitudeMode = altitudeMode; } @@ -314,8 +297,7 @@ public void setAltitudeMode(int altitudeMode) * * @return the distance from the placemark to the current view's eye point. */ - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } @@ -324,8 +306,7 @@ public double getDistanceFromEye() * * @return true if the line is drawn, otherwise false. */ - public boolean isLineEnabled() - { + public boolean isLineEnabled() { return lineEnabled; } @@ -334,8 +315,7 @@ public boolean isLineEnabled() * * @param lineEnabled true if the line is drawn, otherwise false. */ - public void setLineEnabled(boolean lineEnabled) - { + public void setLineEnabled(boolean lineEnabled) { this.lineEnabled = lineEnabled; } @@ -344,10 +324,10 @@ public void setLineEnabled(boolean lineEnabled) * * @param attrs the attributes to use in normal mode. May be null to indicate use of default attributes. */ - public void setAttributes(PointPlacemarkAttributes attrs) - { - if (this.normalAttrs != null && this.normalAttrs.getImageAddress() != null) + public void setAttributes(PointPlacemarkAttributes attrs) { + if (this.normalAttrs != null && this.normalAttrs.getImageAddress() != null) { this.textures.remove(this.normalAttrs.getImageAddress()); + } this.normalAttrs = attrs; } @@ -357,8 +337,7 @@ public void setAttributes(PointPlacemarkAttributes attrs) * * @return the attributes used in normal mode. May be null to indicate use of default attributes. */ - public PointPlacemarkAttributes getAttributes() - { + public PointPlacemarkAttributes getAttributes() { return this.normalAttrs; } @@ -367,10 +346,10 @@ public PointPlacemarkAttributes getAttributes() * * @param attrs the attributes to use in normal mode. May be null to indicate use of the normal attributes. */ - public void setHighlightAttributes(PointPlacemarkAttributes attrs) - { - if (this.highlightAttrs != null && this.highlightAttrs.getImageAddress() != null) + public void setHighlightAttributes(PointPlacemarkAttributes attrs) { + if (this.highlightAttrs != null && this.highlightAttrs.getImageAddress() != null) { this.textures.remove(this.highlightAttrs.getImageAddress()); + } this.highlightAttrs = attrs; } @@ -380,8 +359,7 @@ public void setHighlightAttributes(PointPlacemarkAttributes attrs) * * @return the attributes used in normal mode. May be null to indicate use of the normal attributes. */ - public PointPlacemarkAttributes getHighlightAttributes() - { + public PointPlacemarkAttributes getHighlightAttributes() { return this.highlightAttrs; } @@ -390,8 +368,7 @@ public PointPlacemarkAttributes getHighlightAttributes() * * @return the default attributes. */ - public PointPlacemarkAttributes getDefaultAttributes() - { + public PointPlacemarkAttributes getDefaultAttributes() { return defaultAttributes; } @@ -400,8 +377,7 @@ public PointPlacemarkAttributes getDefaultAttributes() * * @return true if the placemark is drawn highlighted, otherwise false. */ - public boolean isHighlighted() - { + public boolean isHighlighted() { return this.highlighted; } @@ -410,8 +386,7 @@ public boolean isHighlighted() * * @param highlighted true if the placemark is drawn highlighted, otherwise false. */ - public void setHighlighted(boolean highlighted) - { + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } @@ -420,8 +395,7 @@ public void setHighlighted(boolean highlighted) * * @return the placemark's label next, which man be null. */ - public String getLabelText() - { + public String getLabelText() { return labelText; } @@ -430,28 +404,23 @@ public String getLabelText() * * @param labelText the placemark label text. If null, no label is displayed. */ - public void setLabelText(String labelText) - { + public void setLabelText(String labelText) { this.labelText = labelText != null ? labelText.trim() : null; } - public boolean isApplyVerticalExaggeration() - { + public boolean isApplyVerticalExaggeration() { return applyVerticalExaggeration; } - public void setApplyVerticalExaggeration(boolean applyVerticalExaggeration) - { + public void setApplyVerticalExaggeration(boolean applyVerticalExaggeration) { this.applyVerticalExaggeration = applyVerticalExaggeration; } - public int getLinePickWidth() - { + public int getLinePickWidth() { return linePickWidth; } - public void setLinePickWidth(int linePickWidth) - { + public void setLinePickWidth(int linePickWidth) { this.linePickWidth = linePickWidth; } @@ -462,8 +431,7 @@ public void setLinePickWidth(int linePickWidth) * * @see #setEnableBatchRendering(boolean) */ - public boolean isEnableBatchRendering() - { + public boolean isEnableBatchRendering() { return enableBatchRendering; } @@ -473,8 +441,7 @@ public boolean isEnableBatchRendering() * * @param enableBatchRendering true to enable batch rendering, otherwise false. */ - public void setEnableBatchRendering(boolean enableBatchRendering) - { + public void setEnableBatchRendering(boolean enableBatchRendering) { this.enableBatchRendering = enableBatchRendering; } @@ -485,8 +452,7 @@ public void setEnableBatchRendering(boolean enableBatchRendering) * * @see #setEnableBatchPicking(boolean) */ - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return enableBatchPicking; } @@ -498,8 +464,7 @@ public boolean isEnableBatchPicking() * @return the object used as the pickable object returned during picking, or null to indicate the the placemark is * returned during picking. */ - public Object getDelegateOwner() - { + public Object getDelegateOwner() { return this.delegateOwner; } @@ -510,13 +475,11 @@ public Object getDelegateOwner() * * @param owner the object to use as the pickable object returned during picking, or null to return the placemark. */ - public void setDelegateOwner(Object owner) - { + public void setDelegateOwner(Object owner) { this.delegateOwner = owner; } - protected PointPlacemarkAttributes getActiveAttributes() - { + protected PointPlacemarkAttributes getActiveAttributes() { return this.activeAttributes; } @@ -530,8 +493,7 @@ protected PointPlacemarkAttributes getActiveAttributes() * * @param enableBatchPicking true to enable batch rendering, otherwise false. */ - public void setEnableBatchPicking(boolean enableBatchPicking) - { + public void setEnableBatchPicking(boolean enableBatchPicking) { this.enableBatchPicking = enableBatchPicking; } @@ -541,8 +503,7 @@ public void setEnableBatchPicking(boolean enableBatchPicking) * @return the value of the clip-to-horizon flag. {@code true} if horizon clipping is enabled, otherwise {@code * false}. The default value is {@code true}. */ - public boolean isClipToHorizon() - { + public boolean isClipToHorizon() { return clipToHorizon; } @@ -552,8 +513,7 @@ public boolean isClipToHorizon() * @param clipToHorizon {@code true} if this placemark should not be shown when beyond the horizon, otherwise {@code * false}. */ - public void setClipToHorizon(boolean clipToHorizon) - { + public void setClipToHorizon(boolean clipToHorizon) { this.clipToHorizon = clipToHorizon; } @@ -563,8 +523,7 @@ public void setClipToHorizon(boolean clipToHorizon) * @return {@code true} if this placemark participates in global text decluttering, otherwise false. The default * value is {@code false}. Only the placemark's label is considered during decluttering. */ - public boolean isEnableDecluttering() - { + public boolean isEnableDecluttering() { return enableDecluttering; } @@ -572,11 +531,9 @@ public boolean isEnableDecluttering() * Specifies whether this placemark participates in globe text decluttering. * * @param enableDecluttering {@code true} if the placemark participates in global text decluttering, otherwise - * {@code false}. The default value is {@code false}. Only the placemark lable is - * considered during decluttering. + * {@code false}. The default value is {@code false}. Only the placemark lable is considered during decluttering. */ - public void setEnableDecluttering(boolean enableDecluttering) - { + public void setEnableDecluttering(boolean enableDecluttering) { this.enableDecluttering = enableDecluttering; } @@ -585,8 +542,7 @@ public void setEnableDecluttering(boolean enableDecluttering) * * @return true if this placemark's label is considered during picking, otherwise false. */ - public boolean isEnableLabelPicking() - { + public boolean isEnableLabelPicking() { return enableLabelPicking; } @@ -596,8 +552,7 @@ public boolean isEnableLabelPicking() * * @param enableLabelPicking true to consider the label during picking, otherwise false. */ - public void setEnableLabelPicking(boolean enableLabelPicking) - { + public void setEnableLabelPicking(boolean enableLabelPicking) { this.enableLabelPicking = enableLabelPicking; } @@ -606,8 +561,7 @@ public void setEnableLabelPicking(boolean enableLabelPicking) * * @return true if the always-on-top flag is set, otherwise false. */ - public boolean isAlwaysOnTop() - { + public boolean isAlwaysOnTop() { return alwaysOnTop; } @@ -618,8 +572,7 @@ public boolean isAlwaysOnTop() * * @param alwaysOnTop true if the placemark should appear always on top, otherwise false. */ - public void setAlwaysOnTop(boolean alwaysOnTop) - { + public void setAlwaysOnTop(boolean alwaysOnTop) { this.alwaysOnTop = alwaysOnTop; } @@ -628,8 +581,7 @@ public void setAlwaysOnTop(boolean alwaysOnTop) * * @return this placemark's level of detail selector, or null if one has not been specified. */ - public LODSelector getLODSelector() - { + public LODSelector getLODSelector() { return this.LODSelector; } @@ -637,10 +589,9 @@ public LODSelector getLODSelector() * Specifies this placemark's level of detail selector. * * @param LODSelector the level of detail selector. May be null, the default, to indicate no level of detail - * selector. + * selector. */ - public void setLODSelector(LODSelector LODSelector) - { + public void setLODSelector(LODSelector LODSelector) { this.LODSelector = LODSelector; } @@ -652,52 +603,47 @@ public void setLODSelector(LODSelector LODSelector) * @return true if a point should be drawn, otherwise false. */ @SuppressWarnings({"UnusedParameters"}) - protected boolean isDrawPoint(DrawContext dc) - { + protected boolean isDrawPoint(DrawContext dc) { return this.activeTexture == null && this.getActiveAttributes().isUsePointAsDefaultImage() - && this.getActiveAttributes().isDrawImage(); + && this.getActiveAttributes().isDrawImage(); } - public void pick(DrawContext dc, Point pickPoint, OrderedPlacemark opm) - { + public void pick(DrawContext dc, Point pickPoint, OrderedPlacemark opm) { // This method is called only when ordered renderables are being drawn. this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.drawOrderedRenderable(dc, opm); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { // This render method is called twice during frame generation. It's first called as a {@link Renderable} // during Renderable picking. It's called again during normal rendering. These two calls determine // whether to add the placemark and its optional line to the ordered renderable list during pick and render. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc.getSurfaceGeometry() == null) + if (dc.getSurfaceGeometry() == null) { return; + } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } - if (dc.is2DGlobe()) - { + if (dc.is2DGlobe()) { Sector limits = ((Globe2D) dc.getGlobe()).getProjection().getProjectionLimits(); - if (limits != null && !limits.contains(this.getPosition())) + if (limits != null && !limits.contains(this.getPosition())) { return; + } } this.makeOrderedRenderable(dc); @@ -705,64 +651,62 @@ public void render(DrawContext dc) /** * If the scene controller is rendering ordered renderables, this method draws this placemark's image as an ordered - * renderable. Otherwise the method determines whether this instance should be added to the ordered renderable - * list. + * renderable. Otherwise the method determines whether this instance should be added to the ordered renderable list. *

          * The Cartesian and screen points of the placemark are computed during the first call per frame and re-used in * subsequent calls of that frame. * * @param dc the current draw context. */ - protected void makeOrderedRenderable(DrawContext dc) - { + protected void makeOrderedRenderable(DrawContext dc) { // The code in this method determines whether to queue an ordered renderable for the placemark // and its optional line. OrderedPlacemark opm = new OrderedPlacemark(); // Try to re-use values already calculated this frame, unless we're rendering a continuous 2D globe. - if (dc.getFrameTimeStamp() != this.frameNumber || dc.isContinuous2DGlobe()) - { + if (dc.getFrameTimeStamp() != this.frameNumber || dc.isContinuous2DGlobe()) { this.computePlacemarkPoints(dc, opm); - if (opm.placePoint == null || opm.screenPoint == null) + if (opm.placePoint == null || opm.screenPoint == null) { return; + } - if (this.getLODSelector() != null) + if (this.getLODSelector() != null) { this.getLODSelector().selectLOD(dc, this, opm.placePoint.distanceTo3(dc.getView().getEyePoint())); + } this.determineActiveAttributes(); - if (this.activeTexture == null && !this.getActiveAttributes().isUsePointAsDefaultImage()) + if (this.activeTexture == null && !this.getActiveAttributes().isUsePointAsDefaultImage()) { return; + } this.computeImageOffset(dc); // calculates offsets to align the image with the hotspot this.frameNumber = dc.getFrameTimeStamp(); - } - else - { + } else { opm.placePoint = this.placePoint; opm.screenPoint = this.screenPoint; opm.terrainPoint = this.terrainPoint; opm.eyeDistance = this.eyeDistance; } - if (this.isClipToHorizon() && !dc.is2DGlobe()) - { + if (this.isClipToHorizon() && !dc.is2DGlobe()) { // Don't draw if beyond the horizon. double horizon = dc.getView().getHorizonDistance(); - if (this.eyeDistance > horizon) + if (this.eyeDistance > horizon) { return; + } } this.computeImageBounds(dc, opm); - if (this.intersectsFrustum(dc, opm) || this.isDrawLine(dc, opm)) - { + if (this.intersectsFrustum(dc, opm) || this.isDrawLine(dc, opm)) { dc.addOrderedRenderable(opm); // add the image ordered renderable } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { this.pickLayer = dc.getCurrentLayer(); + } } /** @@ -773,47 +717,38 @@ protected void makeOrderedRenderable(DrawContext dc) * * @return true if the image intersects the frustum, otherwise false. */ - protected boolean intersectsFrustum(DrawContext dc, OrderedPlacemark opm) - { + protected boolean intersectsFrustum(DrawContext dc, OrderedPlacemark opm) { View view = dc.getView(); // Test the placemark's model coordinate point against the near and far clipping planes. if (opm.placePoint != null - && (view.getFrustumInModelCoordinates().getNear().distanceTo(opm.placePoint) < 0 - || view.getFrustumInModelCoordinates().getFar().distanceTo(opm.placePoint) < 0)) - { + && (view.getFrustumInModelCoordinates().getNear().distanceTo(opm.placePoint) < 0 + || view.getFrustumInModelCoordinates().getFar().distanceTo(opm.placePoint) < 0)) { return false; } Rectangle rect = opm.getImageBounds(); - if (dc.isPickingMode()) - { - if (this.isEnableDecluttering()) - { + if (dc.isPickingMode()) { + if (this.isEnableDecluttering()) { // If decluttering then we need everything within the viewport drawn. return view.getViewport().intersects(rect); - } - else - { + } else { // Test image rect against pick frustums. - if (dc.getPickFrustums().intersectsAny(rect)) + if (dc.getPickFrustums().intersectsAny(rect)) { return true; + } - if (this.getLabelText() != null && this.isEnableLabelPicking()) - { + if (this.getLabelText() != null && this.isEnableLabelPicking()) { rect = this.getLabelBounds(dc, opm); rect = new Rectangle(rect.x, rect.y + PICK_Y_OFFSET, rect.width, rect.height + PICK_Y_SIZE_DELTA); - if (dc.getPickFrustums().intersectsAny(rect)) + if (dc.getPickFrustums().intersectsAny(rect)) { return true; + } } } - } - else if (rect.getWidth() > 0) - { + } else if (rect.getWidth() > 0) { return view.getViewport().intersects(rect); - } - else if (mustDrawLabel()) - { + } else if (mustDrawLabel()) { // We are drawing a label but not an image. Determine if the placemark point is visible. This case comes up // when the image scale is zero and the label scale is non-zero. return view.getViewport().contains((int) opm.screenPoint.x, (int) opm.screenPoint.y); @@ -827,12 +762,11 @@ else if (mustDrawLabel()) * * @param dc the current draw context. */ - protected void beginDrawing(DrawContext dc) - { + protected void beginDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - int attrMask = - GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask and depth func + int attrMask + = GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask and depth func | GL2.GL_TRANSFORM_BIT // for modelview and perspective | GL2.GL_VIEWPORT_BIT // for depth range | GL2.GL_CURRENT_BIT // for current color @@ -843,8 +777,7 @@ protected void beginDrawing(DrawContext dc) gl.glPushAttrib(attrMask); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); OGLUtil.applyBlending(gl, false); } @@ -855,8 +788,7 @@ protected void beginDrawing(DrawContext dc) * * @param dc the current draw context. */ - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBindTexture(GL.GL_TEXTURE_2D, 0); gl.glPopAttrib(); @@ -868,18 +800,15 @@ protected void endDrawing(DrawContext dc) * @param dc the current draw context. * @param opm The object to draw. */ - protected void drawOrderedRenderable(DrawContext dc, OrderedPlacemark opm) - { + protected void drawOrderedRenderable(DrawContext dc, OrderedPlacemark opm) { this.beginDrawing(dc); - try - { + try { this.doDrawOrderedRenderable(dc, this.pickSupport, opm); - if (this.isEnableBatchRendering()) + if (this.isEnableBatchRendering()) { this.drawBatched(dc); - } - finally - { + } + } finally { this.endDrawing(dc); } } @@ -890,35 +819,33 @@ protected void drawOrderedRenderable(DrawContext dc, OrderedPlacemark opm) * * @param dc the current draw context. */ - protected void drawBatched(DrawContext dc) - { + protected void drawBatched(DrawContext dc) { // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - if (!dc.isPickingMode()) - { - while (nextItem != null && nextItem instanceof OrderedPlacemark) - { + if (!dc.isPickingMode()) { + while (nextItem != null && nextItem instanceof OrderedPlacemark) { OrderedPlacemark opm = (OrderedPlacemark) nextItem; - if (!opm.isEnableBatchRendering()) + if (!opm.isEnableBatchRendering()) { break; + } dc.pollOrderedRenderables(); // take it off the queue opm.doDrawOrderedRenderable(dc, this.pickSupport); nextItem = dc.peekOrderedRenderables(); } - } - else if (this.isEnableBatchPicking()) - { - while (nextItem != null && nextItem instanceof OrderedPlacemark) - { + } else if (this.isEnableBatchPicking()) { + while (nextItem != null && nextItem instanceof OrderedPlacemark) { OrderedPlacemark opm = (OrderedPlacemark) nextItem; - if (!opm.isEnableBatchRendering() || !opm.isEnableBatchPicking()) + if (!opm.isEnableBatchRendering() || !opm.isEnableBatchPicking()) { break; + } if (opm.getPickLayer() != this.pickLayer) // batch pick only within a single layer + { break; + } dc.pollOrderedRenderables(); // take it off the queue opm.doDrawOrderedRenderable(dc, this.pickSupport); @@ -930,33 +857,31 @@ else if (this.isEnableBatchPicking()) /** * Draw this placemark as an ordered renderable.If in picking mode, add it to the picked object list of specified - {@link PickSupport}. The PickSupport may not be the one associated with this instance. During batch + * {@link PickSupport}. The PickSupport may not be the one associated with this instance. During batch * picking the PickSupport of the instance initiating the batch picking is used so that all shapes * rendered in batch are added to the same pick list. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickCandidates a pick support holding the picked object list to add this shape to. * @param opm The placemark to draw. */ - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates, OrderedPlacemark opm) - { - if (this.isDrawLine(dc, opm)) + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates, OrderedPlacemark opm) { + if (this.isDrawLine(dc, opm)) { this.drawLine(dc, pickCandidates, opm); + } - if (this.activeTexture == null) - { - if (this.isDrawPoint(dc)) + if (this.activeTexture == null) { + if (this.isDrawPoint(dc)) { this.drawPoint(dc, pickCandidates, opm); + } return; } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler osh = new OGLStackHandler(); - try - { - if (dc.isPickingMode()) - { + try { + if (dc.isPickingMode()) { // Set up to replace the non-transparent texture colors with the single pick color. gl.glEnable(GL.GL_TEXTURE_2D); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_COMBINE); @@ -966,15 +891,14 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate Color pickColor = dc.getUniquePickColor(); pickCandidates.addPickableObject(this.createPickedObject(dc, pickColor)); gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue()); - } - else - { + } else { gl.glEnable(GL.GL_TEXTURE_2D); Color color = this.getActiveAttributes().getImageColor(); - if (color == null) + if (color == null) { color = PointPlacemarkAttributes.DEFAULT_IMAGE_COLOR; + } gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue(), - (byte) color.getAlpha()); + (byte) color.getAlpha()); } // The image is drawn using a parallel projection. @@ -982,8 +906,9 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate gl.glOrtho(0d, dc.getView().getViewport().width, 0d, dc.getView().getViewport().height, -1d, 1d); // Apply the depth buffer but don't change it (for screen-space shapes). - if ((!dc.isDeepPickingEnabled())) + if ((!dc.isDeepPickingEnabled())) { gl.glEnable(GL.GL_DEPTH_TEST); + } gl.glDepthMask(false); // Suppress any fully transparent image pixels. @@ -1004,61 +929,62 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate // Compute the scale double xscale; Double scale = this.getActiveAttributes().getScale(); - if (scale != null) + if (scale != null) { xscale = scale * this.activeTexture.getWidth(dc); - else + } else { xscale = this.activeTexture.getWidth(dc); + } double yscale; - if (scale != null) + if (scale != null) { yscale = scale * this.activeTexture.getHeight(dc); - else + } else { yscale = this.activeTexture.getHeight(dc); + } Double heading = getActiveAttributes().getHeading(); Double pitch = getActiveAttributes().getPitch(); // Adjust heading to be relative to globe or screen - if (heading != null) - { - if (AVKey.RELATIVE_TO_GLOBE.equals(this.getActiveAttributes().getHeadingReference())) + if (heading != null) { + if (AVKey.RELATIVE_TO_GLOBE.equals(this.getActiveAttributes().getHeadingReference())) { heading = dc.getView().getHeading().degrees - heading; - else + } else { heading = -heading; + } } // Apply the heading and pitch if specified. - if (heading != null || pitch != null) - { + if (heading != null || pitch != null) { gl.glTranslated(xscale / 2, yscale / 2, 0); - if (pitch != null) + if (pitch != null) { gl.glRotated(pitch, 1, 0, 0); - if (heading != null) + } + if (heading != null) { gl.glRotated(heading, 0, 0, 1); + } gl.glTranslated(-xscale / 2, -yscale / 2, 0); } // Scale the unit quad gl.glScaled(xscale, yscale, 1); - if (this.activeTexture.bind(dc)) + if (this.activeTexture.bind(dc)) { dc.drawUnitQuad(activeTexture.getTexCoords()); + } gl.glDepthRange(0, 1); // reset depth range to the OGL default // // gl.glDisable(GL.GL_TEXTURE_2D); // dc.drawUnitQuadOutline(); // for debugging label placement - if (this.mustDrawLabel()) - { - if (!dc.isPickingMode() || this.isEnableLabelPicking()) + if (this.mustDrawLabel()) { + if (!dc.isPickingMode() || this.isEnableLabelPicking()) { this.drawLabel(dc, pickCandidates, opm); + } } - } - finally - { - if (dc.isPickingMode()) - { + } finally { + if (dc.isPickingMode()) { gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, OGLUtil.DEFAULT_TEX_ENV_MODE); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, OGLUtil.DEFAULT_SRC0_RGB); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_COMBINE_RGB, OGLUtil.DEFAULT_COMBINE_RGB); @@ -1073,13 +999,12 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate * Create a {@link PickedObject} for this placemark. The PickedObject returned by this method will be added to the * pick list to represent the current placemark. * - * @param dc Active draw context. + * @param dc Active draw context. * @param pickColor Unique color for this PickedObject. * * @return A new picked object. */ - protected PickedObject createPickedObject(DrawContext dc, Color pickColor) - { + protected PickedObject createPickedObject(DrawContext dc, Color pickColor) { Object delegateOwner = this.getDelegateOwner(); return new PickedObject(pickColor.getRGB(), delegateOwner != null ? delegateOwner : this); } @@ -1089,44 +1014,42 @@ protected PickedObject createPickedObject(DrawContext dc, Color pickColor) * * @return True if the label must be drawn. */ - protected boolean mustDrawLabel() - { + protected boolean mustDrawLabel() { return this.getLabelText() != null && this.getActiveAttributes().isDrawLabel(); } /** * Determines the screen coordinate boundaries of this placemark's label. * - * @param dc the current draw context. + * @param dc the current draw context. * @param opm the ordered renderable for the placemark. * * @return the label bounds, in lower-left origin screen coordinates, or null if there is no label. */ - protected Rectangle getLabelBounds(DrawContext dc, OrderedPlacemark opm) - { - if (this.getLabelText() == null) + protected Rectangle getLabelBounds(DrawContext dc, OrderedPlacemark opm) { + if (this.getLabelText() == null) { return null; + } Vec4 labelPoint = this.computeLabelPoint(dc, opm); Font font = this.getActiveAttributes().getLabelFont(); - if (font == null) - + if (font == null) { font = PointPlacemarkAttributes.DEFAULT_LABEL_FONT; + } TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); Rectangle2D bounds = textRenderer.getBounds(this.getLabelText()); double width = bounds.getWidth(); double height = bounds.getHeight(); Double labelScale = this.getActiveAttributes().getLabelScale(); - if (labelScale != null) - { + if (labelScale != null) { width *= labelScale; height *= labelScale; } return new Rectangle((int) labelPoint.x, (int) labelPoint.getY(), (int) Math.ceil(width), - (int) Math.ceil(height)); + (int) Math.ceil(height)); } /** @@ -1136,19 +1059,21 @@ protected Rectangle getLabelBounds(DrawContext dc, OrderedPlacemark opm) * @param pickCandidates The list of pick candidates. * @param opm The placemark to label. */ - protected void drawLabel(DrawContext dc, PickSupport pickCandidates, OrderedPlacemark opm) - { - if (this.getLabelText() == null) + protected void drawLabel(DrawContext dc, PickSupport pickCandidates, OrderedPlacemark opm) { + if (this.getLabelText() == null) { return; + } Color color = this.getActiveAttributes().getLabelColor(); // Use the default color if the active attributes do not specify one. - if (color == null) + if (color == null) { color = PointPlacemarkAttributes.DEFAULT_LABEL_COLOR; + } // If the label color's alpha component is 0 or less, then the label is completely transparent. Exit // immediately; the label does not need to be rendered. - if (color.getAlpha() <= 0) + if (color.getAlpha() <= 0) { return; + } // Apply the label color's alpha component to the background color. This causes both the label foreground and // background to blend evenly into the frame. If the alpha component is 255 we just use the pre-defined constant @@ -1165,8 +1090,7 @@ protected void drawLabel(DrawContext dc, PickSupport pickCandidates, OrderedPlac gl.glLoadIdentity(); Double labelScale = this.getActiveAttributes().getLabelScale(); - if (labelScale != null) - { + if (labelScale != null) { gl.glTranslatef(x, y, 0); // Assumes matrix mode is MODELVIEW gl.glScaled(labelScale, labelScale, 1); gl.glTranslatef(-x, -y, 0); @@ -1177,11 +1101,11 @@ protected void drawLabel(DrawContext dc, PickSupport pickCandidates, OrderedPlac gl.glDepthMask(false); Font font = this.getActiveAttributes().getLabelFont(); - if (font == null) + if (font == null) { font = PointPlacemarkAttributes.DEFAULT_LABEL_FONT; + } - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { // Pick the text box, not just the text. Rectangle textBounds = this.getLabelBounds(dc, opm); @@ -1196,20 +1120,15 @@ protected void drawLabel(DrawContext dc, PickSupport pickCandidates, OrderedPlac gl.glScaled(textBounds.getWidth(), textBounds.getHeight() + PICK_Y_SIZE_DELTA, 1); gl.glDisable(GL.GL_TEXTURE_2D); dc.drawUnitQuad(); - } - else - { + } else { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); - try - { + try { textRenderer.begin3DRendering(); textRenderer.setColor(backgroundColor); textRenderer.draw3D(this.getLabelText(), x + 1, y - 1, 0, 1); textRenderer.setColor(color); textRenderer.draw3D(this.getLabelText(), x, y, 0, 1); - } - finally - { + } finally { textRenderer.end3DRendering(); } } @@ -1218,21 +1137,20 @@ protected void drawLabel(DrawContext dc, PickSupport pickCandidates, OrderedPlac /** * Draws the placemark's line. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickCandidates the pick support object to use when adding this as a pick candidate. * @param opm The placemark to draw the line for. */ - protected void drawLine(DrawContext dc, PickSupport pickCandidates, OrderedPlacemark opm) - { + protected void drawLine(DrawContext dc, PickSupport pickCandidates, OrderedPlacemark opm) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if ((!dc.isDeepPickingEnabled())) + if ((!dc.isDeepPickingEnabled())) { gl.glEnable(GL.GL_DEPTH_TEST); + } gl.glDepthFunc(GL.GL_LEQUAL); gl.glDepthMask(true); - try - { + try { dc.getView().pushReferenceCenter(dc, opm.placePoint); // draw relative to the place point this.setLineWidth(dc); @@ -1241,11 +1159,9 @@ protected void drawLine(DrawContext dc, PickSupport pickCandidates, OrderedPlace gl.glBegin(GL2.GL_LINE_STRIP); gl.glVertex3d(Vec4.ZERO.x, Vec4.ZERO.y, Vec4.ZERO.z); gl.glVertex3d(opm.terrainPoint.x - opm.placePoint.x, opm.terrainPoint.y - opm.placePoint.y, - opm.terrainPoint.z - opm.placePoint.z); + opm.terrainPoint.z - opm.placePoint.z); gl.glEnd(); - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); } } @@ -1253,17 +1169,15 @@ protected void drawLine(DrawContext dc, PickSupport pickCandidates, OrderedPlace /** * Draws the placemark's line. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickCandidates the pick support object to use when adding this as a pick candidate. * @param opm The placemark to draw the point for. */ - protected void drawPoint(DrawContext dc, PickSupport pickCandidates, OrderedPlacemark opm) - { + protected void drawPoint(DrawContext dc, PickSupport pickCandidates, OrderedPlacemark opm) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler osh = new OGLStackHandler(); - try - { + try { osh.pushAttrib(gl, GL2.GL_POINT_BIT); this.setLineColor(dc, pickCandidates); @@ -1276,8 +1190,9 @@ protected void drawPoint(DrawContext dc, PickSupport pickCandidates, OrderedPlac osh.pushModelviewIdentity(gl); // Apply the depth buffer but don't change it (for screen-space shapes). - if ((!dc.isDeepPickingEnabled())) + if ((!dc.isDeepPickingEnabled())) { gl.glEnable(GL.GL_DEPTH_TEST); + } gl.glDepthMask(false); // Suppress any fully transparent pixels. @@ -1296,14 +1211,12 @@ protected void drawPoint(DrawContext dc, PickSupport pickCandidates, OrderedPlac gl.glDepthRange(0, 1); // reset depth range to the OGL default - if (this.mustDrawLabel()) - { - if (!dc.isPickingMode() || this.isEnableLabelPicking()) + if (this.mustDrawLabel()) { + if (!dc.isPickingMode() || this.isEnableLabelPicking()) { this.drawLabel(dc, pickCandidates, opm); + } } - } - finally - { + } finally { osh.pop(gl); } } @@ -1316,16 +1229,17 @@ protected void drawPoint(DrawContext dc, PickSupport pickCandidates, OrderedPlac * * @return true if the line should be drawn and it intersects the view frustum, otherwise false. */ - protected boolean isDrawLine(DrawContext dc, OrderedPlacemark opm) - { + protected boolean isDrawLine(DrawContext dc, OrderedPlacemark opm) { if (!this.isLineEnabled() || dc.is2DGlobe() || this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND - || opm.terrainPoint == null) + || opm.terrainPoint == null) { return false; + } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(opm.placePoint, opm.terrainPoint); - else + } else { return dc.getView().getFrustumInModelCoordinates().intersectsSegment(opm.placePoint, opm.terrainPoint); + } } /** @@ -1333,22 +1247,18 @@ protected boolean isDrawLine(DrawContext dc, OrderedPlacemark opm) * * @param dc the current draw context. */ - protected void setLineWidth(DrawContext dc) - { + protected void setLineWidth(DrawContext dc) { Double lineWidth = this.getActiveAttributes().getLineWidth(); - if (lineWidth != null) - { + if (lineWidth != null) { GL gl = dc.getGL(); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glLineWidth(lineWidth.floatValue() + this.getLinePickWidth()); - } - else + } else { gl.glLineWidth(lineWidth.floatValue()); + } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glHint(GL.GL_LINE_SMOOTH_HINT, this.getActiveAttributes().getAntiAliasHint()); gl.glEnable(GL.GL_LINE_SMOOTH); } @@ -1360,21 +1270,21 @@ protected void setLineWidth(DrawContext dc) * * @param dc the current draw context. */ - protected void setPointSize(DrawContext dc) - { + protected void setPointSize(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Double scale = this.getActiveAttributes().getScale(); - if (scale == null) + if (scale == null) { scale = DEFAULT_POINT_SIZE; + } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { gl.glPointSize(scale.floatValue() + this.getLinePickWidth()); - else + } else { gl.glPointSize(scale.floatValue()); + } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL2.GL_POINT_SMOOTH); gl.glHint(GL2.GL_POINT_SMOOTH_HINT, GL2.GL_NICEST); } @@ -1383,84 +1293,72 @@ protected void setPointSize(DrawContext dc) /** * Sets the color of the placemark's line during rendering. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickCandidates the pick support object to use when adding this as a pick candidate. */ - protected void setLineColor(DrawContext dc, PickSupport pickCandidates) - { + protected void setLineColor(DrawContext dc, PickSupport pickCandidates) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { Color color = this.getActiveAttributes().getLineColor(); - if (color == null) + if (color == null) { color = PointPlacemarkAttributes.DEFAULT_LINE_COLOR; + } gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue(), - (byte) color.getAlpha()); - } - else - { + (byte) color.getAlpha()); + } else { Color pickColor = dc.getUniquePickColor(); Object delegateOwner = this.getDelegateOwner(); pickCandidates.addPickableObject(pickColor.getRGB(), delegateOwner != null ? delegateOwner : this, - this.getPosition()); + this.getPosition()); gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue()); } } - /** Determines which attributes -- normal, highlight or default -- to use each frame. */ - protected void determineActiveAttributes() - { + /** + * Determines which attributes -- normal, highlight or default -- to use each frame. + */ + protected void determineActiveAttributes() { PointPlacemarkAttributes actAttrs = this.getActiveAttributes(); - if (this.isHighlighted()) - { - if (this.getHighlightAttributes() != null) - { + if (this.isHighlighted()) { + if (this.getHighlightAttributes() != null) { actAttrs.copy(this.getHighlightAttributes()); // Even though there are highlight attributes, there may not be an image for them, so use the normal image. if (WWUtil.isEmpty(actAttrs.getImageAddress()) - && this.getAttributes() != null && !WWUtil.isEmpty(this.getAttributes().getImageAddress())) - { + && this.getAttributes() != null && !WWUtil.isEmpty(this.getAttributes().getImageAddress())) { actAttrs.setImageAddress(this.getAttributes().getImageAddress()); - if (this.getAttributes().getScale() != null) + if (this.getAttributes().getScale() != null) { actAttrs.setScale(DEFAULT_HIGHLIGHT_SCALE * this.getAttributes().getScale()); - else + } else { actAttrs.setScale(DEFAULT_HIGHLIGHT_SCALE); + } } - } - else - { + } else { // If no highlight attributes have been specified we need to use the normal attributes but adjust them // for highlighting. - if (this.getAttributes() != null) - { + if (this.getAttributes() != null) { actAttrs.copy(this.getAttributes()); - if (getAttributes().getScale() != null) + if (getAttributes().getScale() != null) { actAttrs.setScale(DEFAULT_HIGHLIGHT_SCALE * this.getAttributes().getScale()); - else + } else { actAttrs.setScale(DEFAULT_HIGHLIGHT_SCALE); - } - else - { + } + } else { actAttrs.copy(defaultAttributes); - if (defaultAttributes.getScale() != null) + if (defaultAttributes.getScale() != null) { actAttrs.setScale(DEFAULT_HIGHLIGHT_SCALE * defaultAttributes.getScale()); - else + } else { actAttrs.setScale(DEFAULT_HIGHLIGHT_SCALE); + } } } - } - else if (this.getAttributes() != null) - { + } else if (this.getAttributes() != null) { actAttrs.copy(this.getAttributes()); - } - else - { + } else { actAttrs.copy(defaultAttributes); - if (this.activeTexture == null && actAttrs.isUsePointAsDefaultImage()) - { + if (this.activeTexture == null && actAttrs.isUsePointAsDefaultImage()) { actAttrs.setImageAddress(null); actAttrs.setScale(DEFAULT_POINT_SIZE); } @@ -1468,12 +1366,12 @@ else if (this.getAttributes() != null) this.activeTexture = this.chooseTexture(actAttrs); - if (this.activeTexture == null && actAttrs.isUsePointAsDefaultImage()) - { + if (this.activeTexture == null && actAttrs.isUsePointAsDefaultImage()) { actAttrs.setImageAddress(null); actAttrs.setImageOffset(null); - if (actAttrs.getScale() == null) + if (actAttrs.getScale() == null) { actAttrs.setScale(DEFAULT_POINT_SIZE); + } } } @@ -1484,16 +1382,12 @@ else if (this.getAttributes() != null) * * @return the appropriate texture, or null if an image is not available. */ - protected WWTexture chooseTexture(PointPlacemarkAttributes attrs) - { - if (!attrs.isDrawImage()) - { + protected WWTexture chooseTexture(PointPlacemarkAttributes attrs) { + if (!attrs.isDrawImage()) { WWTexture texture = this.textures.get(TRANSPARENT_IMAGE_ADDRESS); - if (texture == null) - { + if (texture == null) { URL localUrl = WorldWind.getDataFileStore().requestFile(TRANSPARENT_IMAGE_ADDRESS); - if (localUrl != null) - { + if (localUrl != null) { texture = new BasicWWTexture(localUrl, true); this.textures.put(TRANSPARENT_IMAGE_ADDRESS, texture); } @@ -1502,35 +1396,34 @@ protected WWTexture chooseTexture(PointPlacemarkAttributes attrs) return texture; } - if (!WWUtil.isEmpty(attrs.getImageAddress())) - { + if (!WWUtil.isEmpty(attrs.getImageAddress())) { WWTexture texture = this.textures.get(attrs.getImageAddress()); - if (texture != null) + if (texture != null) { return texture; + } texture = this.initializeTexture(attrs.getImageAddress()); - if (texture != null) - { + if (texture != null) { this.textures.put(attrs.getImageAddress(), texture); return texture; } } - if (this.getActiveAttributes().usePointAsDefaultImage) + if (this.getActiveAttributes().usePointAsDefaultImage) { return null; + } // Use the default image if no other is defined or it's not yet available. WWTexture texture = this.textures.get(defaultAttributes.getImageAddress()); this.getActiveAttributes().setImageOffset(defaultAttributes.getImageOffset()); - if (attrs.getScale() != null) + if (attrs.getScale() != null) { this.getActiveAttributes().setScale(defaultAttributes.getScale() * attrs.getScale()); - else + } else { this.getActiveAttributes().setScale(defaultAttributes.getScale()); - if (texture == null) - { + } + if (texture == null) { URL localUrl = WorldWind.getDataFileStore().requestFile(defaultAttributes.getImageAddress()); - if (localUrl != null) - { + if (localUrl != null) { texture = new BasicWWTexture(localUrl, true); this.textures.put(defaultAttributes.getImageAddress(), texture); } @@ -1548,18 +1441,15 @@ protected WWTexture chooseTexture(PointPlacemarkAttributes attrs) * @return The new texture, or null if the texture could not be created because the resource is not yet available * locally. */ - protected WWTexture initializeTexture(String address) - { - if (this.getActiveAttributes().getImage() != null) - { + protected WWTexture initializeTexture(String address) { + if (this.getActiveAttributes().getImage() != null) { // App has specified a buffered image. return new BasicWWTexture(this.getActiveAttributes().getImage(), true); } URL localUrl = WorldWind.getDataFileStore().requestFile(address); - if (localUrl != null) - { + if (localUrl != null) { return new BasicWWTexture(localUrl, true); } @@ -1574,37 +1464,35 @@ protected WWTexture initializeTexture(String address) * @param dc the current draw context. * @param opm The placemark to compute the location of. */ - protected void computePlacemarkPoints(DrawContext dc, OrderedPlacemark opm) - { + protected void computePlacemarkPoints(DrawContext dc, OrderedPlacemark opm) { opm.placePoint = null; opm.terrainPoint = null; opm.screenPoint = null; Position pos = this.getPosition(); - if (pos == null) + if (pos == null) { return; + } - if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) - { + if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) { opm.placePoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), 0); - } - else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) { opm.placePoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), pos.getAltitude()); - } - else // ABSOLUTE + } else // ABSOLUTE { double height = pos.getElevation() - * (this.isApplyVerticalExaggeration() ? dc.getVerticalExaggeration() : 1); + * (this.isApplyVerticalExaggeration() ? dc.getVerticalExaggeration() : 1); opm.placePoint = dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), height); } - if (opm.placePoint == null) + if (opm.placePoint == null) { return; + } // Compute a terrain point if needed. - if (this.isLineEnabled() && this.altitudeMode != WorldWind.CLAMP_TO_GROUND && !dc.is2DGlobe()) + if (this.isLineEnabled() && this.altitudeMode != WorldWind.CLAMP_TO_GROUND && !dc.is2DGlobe()) { opm.terrainPoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), 0); + } // Compute the placemark point's screen location. opm.screenPoint = dc.getView().project(opm.placePoint); @@ -1620,12 +1508,11 @@ else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) /** * Computes the screen-space rectangle bounding the placemark image. * - * @param dc the current draw context. + * @param dc the current draw context. * @param opm the ordered placemark. * */ - protected void computeImageBounds(DrawContext dc, OrderedPlacemark opm) - { + protected void computeImageBounds(DrawContext dc, OrderedPlacemark opm) { double s = this.getActiveAttributes().getScale() != null ? this.getActiveAttributes().getScale() : 1; double width = s * (this.activeTexture != null ? this.activeTexture.getWidth(dc) : 1); @@ -1640,23 +1527,24 @@ protected void computeImageBounds(DrawContext dc, OrderedPlacemark opm) /** * Computes the screen coordinate (lower-left origin) location of this placemark's label. * - * @param dc the current draw context. + * @param dc the current draw context. * @param opm the ordered renderable for the placemark. * * @return the 2D label location, or null if there is no label. */ - protected Vec4 computeLabelPoint(DrawContext dc, OrderedPlacemark opm) - { - if (this.getLabelText() == null) + protected Vec4 computeLabelPoint(DrawContext dc, OrderedPlacemark opm) { + if (this.getLabelText() == null) { return null; + } float x = (float) (opm.screenPoint.x + this.dx); float y = (float) (opm.screenPoint.y + this.dy); Double imageScale = this.getActiveAttributes().getScale(); Offset os = this.getActiveAttributes().getLabelOffset(); - if (os == null) + if (os == null) { os = DEFAULT_LABEL_OFFSET_IF_UNSPECIFIED; + } double w = this.activeTexture != null ? this.activeTexture.getWidth(dc) : 1; double h = this.activeTexture != null ? this.activeTexture.getHeight(dc) : 1; Point.Double offset = os.computeOffset(w, h, imageScale, imageScale); @@ -1666,48 +1554,52 @@ protected Vec4 computeLabelPoint(DrawContext dc, OrderedPlacemark opm) return new Vec4(x, y); } - protected void computeImageOffset(DrawContext dc) - { + protected void computeImageOffset(DrawContext dc) { // Determine the screen-space offset needed to align the image hot spot with the placemark point. this.dx = 0; this.dy = 0; - if (this.isDrawPoint(dc)) + if (this.isDrawPoint(dc)) { return; + } Offset os = this.getActiveAttributes().getImageOffset(); - if (os == null) + if (os == null) { return; + } double w = this.activeTexture != null ? this.activeTexture.getWidth(dc) : 1; double h = this.activeTexture != null ? this.activeTexture.getHeight(dc) : 1; Point.Double offset = os.computeOffset(w, h, - this.getActiveAttributes().getScale(), this.getActiveAttributes().getScale()); + this.getActiveAttributes().getScale(), this.getActiveAttributes().getScale()); this.dx = -offset.x; this.dy = -offset.y; } - /** {@inheritDoc} */ - public String isExportFormatSupported(String format) - { - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) + /** + * {@inheritDoc} + */ + public String isExportFormatSupported(String format) { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) { return Exportable.FORMAT_SUPPORTED; - else + } else { return Exportable.FORMAT_NOT_SUPPORTED; + } } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.getPosition(); } - /** {@inheritDoc} */ - public void move(Position delta) - { - if (delta == null) - { + /** + * {@inheritDoc} + */ + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1719,17 +1611,18 @@ public void move(Position delta) // because its position must always be non-null. We check and this case anyway to handle a subclass overriding // getReferencePosition and returning null. In this case moving the shape by a relative delta is meaningless // because the shape has no geographic location. Therefore we fail softly by exiting and doing nothing. - if (refPos == null) + if (refPos == null) { return; + } this.moveTo(refPos.add(delta)); } - /** {@inheritDoc} */ - public void moveTo(Position position) - { - if (position == null) - { + /** + * {@inheritDoc} + */ + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1739,31 +1632,29 @@ public void moveTo(Position position) } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, this.getAltitudeMode()); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragScreenSizeConstant(dragContext); } @@ -1779,41 +1670,32 @@ protected void doDrag(DragContext dragContext) * * * @param mimeType MIME type of desired export format. - * @param output An object that will receive the exported data. The type of this object depends on the export - * format (see above). + * @param output An object that will receive the exported data. The type of this object depends on the export format + * (see above). * * @throws IOException If an exception occurs writing to the output object. */ - public void export(String mimeType, Object output) throws IOException - { - if (mimeType == null) - { + public void export(String mimeType, Object output) throws IOException { + if (mimeType == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output == null) - { + if (output == null) { String message = Logging.getMessage("nullValue.OutputBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) - { - try - { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { + try { exportAsKML(output); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { Logging.logger().throwing(getClass().getName(), "export", e); throw new IOException(e); } - } - else - { + } else { String message = Logging.getMessage("Export.UnsupportedFormat", mimeType); Logging.logger().warning(message); throw new UnsupportedOperationException(message); @@ -1827,31 +1709,24 @@ public void export(String mimeType, Object output) throws IOException * @param output Object to receive the generated KML. * * @throws XMLStreamException If an exception occurs while writing the KML - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -1867,16 +1742,14 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); String shortDescription = (String) getValue(AVKey.SHORT_DESCRIPTION); - if (shortDescription != null) - { + if (shortDescription != null) { xmlWriter.writeStartElement("Snippet"); xmlWriter.writeCharacters(shortDescription); xmlWriter.writeEndElement(); } String description = (String) getValue(AVKey.BALLOON_TEXT); - if (description != null) - { + if (description != null) { xmlWriter.writeStartElement("description"); xmlWriter.writeCharacters(description); xmlWriter.writeEndElement(); @@ -1886,8 +1759,7 @@ else if (output instanceof OutputStream) final PointPlacemarkAttributes highlightAttributes = getHighlightAttributes(); // Write style map - if (normalAttributes != null || highlightAttributes != null) - { + if (normalAttributes != null || highlightAttributes != null) { xmlWriter.writeStartElement("StyleMap"); exportAttributesAsKML(xmlWriter, KMLConstants.NORMAL, normalAttributes); exportAttributesAsKML(xmlWriter, KMLConstants.HIGHLIGHT, highlightAttributes); @@ -1907,9 +1779,9 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); final String coordString = String.format(Locale.US, "%f,%f,%f", - position.getLongitude().getDegrees(), - position.getLatitude().getDegrees(), - position.getElevation()); + position.getLongitude().getDegrees(), + position.getLatitude().getDegrees(), + position.getElevation()); xmlWriter.writeStartElement("coordinates"); xmlWriter.writeCharacters(coordString); xmlWriter.writeEndElement(); @@ -1918,26 +1790,25 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); // Placemark xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } /** * Export PointPlacemarkAttributes as KML Style element. * - * @param xmlWriter Writer to receive the Style element. - * @param styleType The type of style: normal or highlight. Value should match either {@link KMLConstants#NORMAL} - * or {@link KMLConstants#HIGHLIGHT} + * @param xmlWriter Writer to receive the Style element. + * @param styleType The type of style: normal or highlight. Value should match either {@link KMLConstants#NORMAL} or + * {@link KMLConstants#HIGHLIGHT} * @param attributes Attributes to export. The method takes no action if this parameter is null. * * @throws XMLStreamException if exception occurs writing XML. - * @throws IOException if exception occurs exporting data. + * @throws IOException if exception occurs exporting data. */ private void exportAttributesAsKML(XMLStreamWriter xmlWriter, String styleType, PointPlacemarkAttributes attributes) - throws XMLStreamException, IOException - { - if (attributes != null) - { + throws XMLStreamException, IOException { + if (attributes != null) { xmlWriter.writeStartElement("Pair"); xmlWriter.writeStartElement("key"); xmlWriter.writeCharacters(styleType); diff --git a/src/gov/nasa/worldwind/render/PointPlacemarkAttributes.java b/src/gov/nasa/worldwind/render/PointPlacemarkAttributes.java index 55dd205295..fbf6ca9b77 100644 --- a/src/gov/nasa/worldwind/render/PointPlacemarkAttributes.java +++ b/src/gov/nasa/worldwind/render/PointPlacemarkAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.*; @@ -19,9 +18,11 @@ import java.io.*; import java.util.UUID; -/** Holds attributes for {@link gov.nasa.worldwind.render.PointPlacemark}s. */ -public class PointPlacemarkAttributes implements Exportable -{ +/** + * Holds attributes for {@link gov.nasa.worldwind.render.PointPlacemark}s. + */ +public class PointPlacemarkAttributes implements Exportable { + protected String imageAddress; protected BufferedImage image; protected Double scale; @@ -46,35 +47,52 @@ public class PointPlacemarkAttributes implements Exportable protected boolean drawImage = true; protected boolean drawLabel = true; - /** The image file to use for the placemark's icon if no image file is specified in the placemark attributes. */ - public static final String DEFAULT_IMAGE_PATH = - Configuration.getStringValue("gov.nasa.worldwind.render.PointPlacemarkAttributes.DefaultImagePath", - "images/pushpins/plain-yellow.png"); - /** The image offset to use if none specified. This value is that required by the default image. */ + /** + * The image file to use for the placemark's icon if no image file is specified in the placemark attributes. + */ + public static final String DEFAULT_IMAGE_PATH + = Configuration.getStringValue("gov.nasa.worldwind.render.PointPlacemarkAttributes.DefaultImagePath", + "images/pushpins/plain-yellow.png"); + /** + * The image offset to use if none specified. This value is that required by the default image. + */ public static final Offset DEFAULT_IMAGE_OFFSET = new Offset(19d, 8d, AVKey.PIXELS, AVKey.PIXELS); - /** The image scale to use if none specified. This value is appropriate for the default image. */ + /** + * The image scale to use if none specified. This value is appropriate for the default image. + */ public static final Double DEFAULT_IMAGE_SCALE = 0.6; - /** The label scale to use if none specified. */ + /** + * The label scale to use if none specified. + */ public static final Double DEFAULT_LABEL_SCALE = 1.0; - /** The default image color. */ + /** + * The default image color. + */ protected static final Color DEFAULT_IMAGE_COLOR = Color.WHITE; - /** The default label offset. This value is appropriate for the default image. */ + /** + * The default label offset. This value is appropriate for the default image. + */ public static final Offset DEFAULT_LABEL_OFFSET = new Offset(0.9d, 0.6d, AVKey.FRACTION, AVKey.FRACTION); - /** The default font to use for the placemark's label. */ + /** + * The default font to use for the placemark's label. + */ public static final Font DEFAULT_LABEL_FONT = Font.decode( - Configuration.getStringValue("gov.nasa.worldwind.render.PointPlacemarkAttributes.DefaultLabelFont", - "Arial-BOLD-14")); - /** The default label color. */ + Configuration.getStringValue("gov.nasa.worldwind.render.PointPlacemarkAttributes.DefaultLabelFont", + "Arial-BOLD-14")); + /** + * The default label color. + */ protected static final Color DEFAULT_LABEL_COLOR = Color.WHITE; - /** The default line color. */ + /** + * The default line color. + */ protected static final Color DEFAULT_LINE_COLOR = Color.WHITE; /** * Constructs an instance with default values for image address, image offset, image scale, label offset, label font * and label color. */ - public PointPlacemarkAttributes() - { + public PointPlacemarkAttributes() { } /** @@ -82,8 +100,7 @@ public PointPlacemarkAttributes() * * @param attrs the instance from which to copy the initial attribute values of this. May be null. */ - public PointPlacemarkAttributes(PointPlacemarkAttributes attrs) - { + public PointPlacemarkAttributes(PointPlacemarkAttributes attrs) { this.copy(attrs); } @@ -92,10 +109,8 @@ public PointPlacemarkAttributes(PointPlacemarkAttributes attrs) * * @param attrs the instance to copy values from. */ - public void copy(PointPlacemarkAttributes attrs) - { - if (attrs != null) - { + public void copy(PointPlacemarkAttributes attrs) { + if (attrs != null) { this.setImageAddress(attrs.getImageAddress()); this.setScale(attrs.getScale()); this.setHeading(attrs.getHeading()); @@ -124,8 +139,7 @@ public void copy(PointPlacemarkAttributes attrs) * * @return the line width. */ - public Double getLineWidth() - { + public Double getLineWidth() { return lineWidth; } @@ -134,8 +148,7 @@ public Double getLineWidth() * * @param lineWidth the line width. May be null, in which case a width of 1 is used during rendering. */ - public void setLineWidth(Double lineWidth) - { + public void setLineWidth(Double lineWidth) { this.lineWidth = lineWidth; } @@ -144,8 +157,7 @@ public void setLineWidth(Double lineWidth) * * @return the line color. */ - public Material getLineMaterial() - { + public Material getLineMaterial() { return this.lineMaterial; } @@ -154,8 +166,7 @@ public Material getLineMaterial() * * @return the label's diffuse color. */ - public Color getLineColor() - { + public Color getLineColor() { return lineMaterial == null ? null : this.lineMaterial.getDiffuse(); } @@ -164,8 +175,7 @@ public Color getLineColor() * * @param lineColor the line color. May be null. */ - public void setLineMaterial(Material lineColor) - { + public void setLineMaterial(Material lineColor) { this.lineMaterial = lineColor; } @@ -174,8 +184,7 @@ public void setLineMaterial(Material lineColor) * * @param lineColorString the line color. May be null. */ - public void setLineColor(String lineColorString) - { + public void setLineColor(String lineColorString) { this.setLineMaterial(new Material(WWUtil.decodeColorABGR(lineColorString))); } @@ -187,8 +196,7 @@ public void setLineColor(String lineColorString) * * @see #setImageColor(java.awt.Color) */ - public Color getImageColor() - { + public Color getImageColor() { return this.imageColor; } @@ -200,8 +208,7 @@ public Color getImageColor() * * @see #getImageColor() */ - public void setImageColor(Color imageColor) - { + public void setImageColor(Color imageColor) { this.imageColor = imageColor; } @@ -210,8 +217,7 @@ public void setImageColor(Color imageColor) * * @return the anti-alias hint. */ - public int getAntiAliasHint() - { + public int getAntiAliasHint() { return antiAliasHint; } @@ -221,8 +227,7 @@ public int getAntiAliasHint() * * @param antiAliasHint the anti-alias hint. */ - public void setAntiAliasHint(int antiAliasHint) - { + public void setAntiAliasHint(int antiAliasHint) { this.antiAliasHint = antiAliasHint; } @@ -231,8 +236,7 @@ public void setAntiAliasHint(int antiAliasHint) * * @return the address of the placemark's image. May be null. */ - public String getImageAddress() - { + public String getImageAddress() { return this.imageAddress; } @@ -241,8 +245,7 @@ public String getImageAddress() * * @param address the address of the placemark's image. May be null, in which case a default image is used. */ - public void setImageAddress(String address) - { + public void setImageAddress(String address) { this.imageAddress = address; } @@ -252,8 +255,7 @@ public void setImageAddress(String address) * * @return The image previously specified for this attribute bundle. */ - public BufferedImage getImage() - { + public BufferedImage getImage() { return image; } @@ -263,10 +265,9 @@ public BufferedImage getImage() * set to a unique identifier for the image. * * @param image the buffered image to use for the associated point placemarks. May be null, in which case this - * attribute bundle's image address is set to null by this method. + * attribute bundle's image address is set to null by this method. */ - public void setImage(BufferedImage image) - { + public void setImage(BufferedImage image) { this.image = image; this.setImageAddress(this.image != null ? UUID.randomUUID().toString() : null); @@ -277,8 +278,7 @@ public void setImage(BufferedImage image) * * @return the placemark image scale. */ - public Double getScale() - { + public Double getScale() { return this.scale; } @@ -288,8 +288,7 @@ public Double getScale() * * @param scale the placemark image scale. May be null, in which case no scaling is applied. */ - public void setScale(Double scale) - { + public void setScale(Double scale) { this.scale = scale; } @@ -298,8 +297,7 @@ public void setScale(Double scale) * * @return the placemark image heading. */ - public Double getHeading() - { + public Double getHeading() { return this.heading; } @@ -308,10 +306,9 @@ public Double getHeading() * image. * * @param heading the placemark heading in degrees clockwise from North. May be null, in which case no heading is - * applied during rendering. + * applied during rendering. */ - public void setHeading(Double heading) - { + public void setHeading(Double heading) { this.heading = heading; } @@ -322,8 +319,7 @@ public void setHeading(Double heading) * * @see #setHeadingReference(String) */ - public String getHeadingReference() - { + public String getHeadingReference() { return headingReference; } @@ -338,8 +334,7 @@ public String getHeadingReference() * * @param headingReference the heading reference. See the description for possible values. */ - public void setHeadingReference(String headingReference) - { + public void setHeadingReference(String headingReference) { this.headingReference = headingReference; } @@ -348,8 +343,7 @@ public void setHeadingReference(String headingReference) * * @return the placemark image pitch. */ - public Double getPitch() - { + public Double getPitch() { return this.pitch; } @@ -358,8 +352,7 @@ public Double getPitch() * * @param pitch the placemark pitch in degrees. May be null, in which case no pitch is applied during rendering. */ - public void setPitch(Double pitch) - { + public void setPitch(Double pitch) { this.pitch = pitch; } @@ -368,8 +361,7 @@ public void setPitch(Double pitch) * * @return the image offset. */ - public Offset getImageOffset() - { + public Offset getImageOffset() { return imageOffset; } @@ -377,10 +369,9 @@ public Offset getImageOffset() * Specifies a location within the placemark image to align with the placemark point. * * @param offset the hot spot controlling the image's placement relative to the placemark point. May be null to - * indicate that the image's lower left corner is aligned with the placemark point. + * indicate that the image's lower left corner is aligned with the placemark point. */ - public void setImageOffset(Offset offset) - { + public void setImageOffset(Offset offset) { this.imageOffset = offset; } @@ -390,8 +381,7 @@ public void setImageOffset(Offset offset) * * @return true if there are unresolved fields, false if no fields remain unresolved. */ - public boolean isUnresolved() - { + public boolean isUnresolved() { return unresolved; } @@ -401,18 +391,15 @@ public boolean isUnresolved() * * @param unresolved true if there are unresolved fields, false if no fields remain unresolved. */ - public void setUnresolved(boolean unresolved) - { + public void setUnresolved(boolean unresolved) { this.unresolved = unresolved; } - public Font getLabelFont() - { + public Font getLabelFont() { return labelFont; } - public void setLabelFont(Font labelFont) - { + public void setLabelFont(Font labelFont) { this.labelFont = labelFont; } @@ -421,8 +408,7 @@ public void setLabelFont(Font labelFont) * * @return the label offset. */ - public Offset getLabelOffset() - { + public Offset getLabelOffset() { return labelOffset; } @@ -437,10 +423,9 @@ public Offset getLabelOffset() * the same level as the top of the image. (An offset of (X = 1.0, Y = 0.6, both in fraction units.) * * @param offset the hot spot controlling the image's placement relative to the placemark point. May be null to - * indicate the default label offset. + * indicate the default label offset. */ - public void setLabelOffset(Offset offset) - { + public void setLabelOffset(Offset offset) { this.labelOffset = offset; } @@ -449,8 +434,7 @@ public void setLabelOffset(Offset offset) * * @return the label material. */ - public Material getLabelMaterial() - { + public Material getLabelMaterial() { return labelMaterial; } @@ -459,8 +443,7 @@ public Material getLabelMaterial() * * @return the label's diffuse color. */ - public Color getLabelColor() - { + public Color getLabelColor() { return labelMaterial == null ? null : this.labelMaterial.getDiffuse(); } @@ -469,8 +452,7 @@ public Color getLabelColor() * * @param color the line material. May be null. */ - public void setLabelMaterial(Material color) - { + public void setLabelMaterial(Material color) { this.labelMaterial = color; } @@ -479,8 +461,7 @@ public void setLabelMaterial(Material color) * * @param labelColorString the line color. May be null. */ - public void setLabelColor(String labelColorString) - { + public void setLabelColor(String labelColorString) { this.setLabelMaterial(new Material(WWUtil.decodeColorABGR(labelColorString))); } @@ -489,8 +470,7 @@ public void setLabelColor(String labelColorString) * * @return the placemark label scale. */ - public Double getLabelScale() - { + public Double getLabelScale() { return labelScale; } @@ -500,8 +480,7 @@ public Double getLabelScale() * * @param scale the placemark image scale. May be null, in which case no scaling is applied. */ - public void setLabelScale(Double scale) - { + public void setLabelScale(Double scale) { this.labelScale = scale; } @@ -512,8 +491,7 @@ public void setLabelScale(Double scale) * * @see #setUsePointAsDefaultImage(boolean) */ - public boolean isUsePointAsDefaultImage() - { + public boolean isUsePointAsDefaultImage() { return usePointAsDefaultImage; } @@ -526,18 +504,19 @@ public boolean isUsePointAsDefaultImage() * * @see #isUsePointAsDefaultImage() */ - public void setUsePointAsDefaultImage(boolean usePointAsDefaultImage) - { + public void setUsePointAsDefaultImage(boolean usePointAsDefaultImage) { this.usePointAsDefaultImage = usePointAsDefaultImage; } - /** {@inheritDoc} */ - public String isExportFormatSupported(String format) - { - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) + /** + * {@inheritDoc} + */ + public String isExportFormatSupported(String format) { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) { return Exportable.FORMAT_SUPPORTED; - else + } else { return Exportable.FORMAT_NOT_SUPPORTED; + } } /** @@ -545,8 +524,7 @@ public String isExportFormatSupported(String format) * * @return true if the image is drawn, otherwise false. */ - public boolean isDrawImage() - { + public boolean isDrawImage() { return drawImage; } @@ -556,8 +534,7 @@ public boolean isDrawImage() * * @param drawImage true to draw the image, otherwise false. */ - public void setDrawImage(boolean drawImage) - { + public void setDrawImage(boolean drawImage) { this.drawImage = drawImage; } @@ -566,8 +543,7 @@ public void setDrawImage(boolean drawImage) * * @return true if the label is drawn, otherwise false. */ - public boolean isDrawLabel() - { + public boolean isDrawLabel() { return drawLabel; } @@ -576,8 +552,7 @@ public boolean isDrawLabel() * * @param drawLabel true to draw the label, otherwise false. */ - public void setDrawLabel(boolean drawLabel) - { + public void setDrawLabel(boolean drawLabel) { this.drawLabel = drawLabel; } @@ -593,41 +568,32 @@ public void setDrawLabel(boolean drawLabel) * * * @param mimeType MIME type of desired export format. - * @param output An object that will receive the exported data. The type of this object depends on the export - * format (see above). + * @param output An object that will receive the exported data. The type of this object depends on the export format + * (see above). * * @throws IOException If an exception occurs writing to the output object. */ - public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException - { - if (mimeType == null) - { + public void export(String mimeType, Object output) throws IOException, UnsupportedOperationException { + if (mimeType == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output == null) - { + if (output == null) { String message = Logging.getMessage("nullValue.OutputBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) - { - try - { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { + try { exportAsKML(output); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { Logging.logger().throwing(getClass().getName(), "export", e); throw new IOException(e); } - } - else - { + } else { String message = Logging.getMessage("Export.UnsupportedFormat", mimeType); Logging.logger().warning(message); throw new UnsupportedOperationException(message); @@ -643,28 +609,21 @@ public void export(String mimeType, Object output) throws IOException, Unsupport * @throws XMLStreamException If an exception occurs while writing the KML * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws XMLStreamException - { + protected void exportAsKML(Object output) throws XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -676,8 +635,7 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("IconStyle"); final Color imageColor = this.getImageColor(); - if (imageColor != null) - { + if (imageColor != null) { xmlWriter.writeStartElement("color"); xmlWriter.writeCharacters(KMLExportUtil.stripHexPrefix(WWUtil.encodeColorABGR(imageColor))); xmlWriter.writeEndElement(); @@ -692,16 +650,14 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); final Double heading = this.getHeading(); - if (heading != null) - { + if (heading != null) { xmlWriter.writeStartElement("heading"); xmlWriter.writeCharacters(Double.toString(this.getHeading())); xmlWriter.writeEndElement(); } String imgAddress = this.getImageAddress(); - if (imgAddress != null) - { + if (imgAddress != null) { xmlWriter.writeStartElement("Icon"); xmlWriter.writeStartElement("href"); xmlWriter.writeCharacters(imgAddress); @@ -710,8 +666,7 @@ else if (output instanceof OutputStream) } Offset offset = this.getImageOffset(); - if (offset != null) - { + if (offset != null) { KMLExportUtil.exportOffset(xmlWriter, offset, "hotSpot"); } @@ -721,16 +676,14 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("LabelStyle"); final Double labelScale = this.getLabelScale(); - if (labelScale != null) - { + if (labelScale != null) { xmlWriter.writeStartElement("scale"); xmlWriter.writeCharacters(Double.toString(labelScale)); xmlWriter.writeEndElement(); } final Color labelColor = this.getLabelColor(); - if (labelColor != null) - { + if (labelColor != null) { xmlWriter.writeStartElement("color"); xmlWriter.writeCharacters(KMLExportUtil.stripHexPrefix(WWUtil.encodeColorABGR(labelColor))); xmlWriter.writeEndElement(); @@ -746,16 +699,14 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("LineStyle"); final Double lineWidth = this.getLineWidth(); - if (lineWidth != null) - { + if (lineWidth != null) { xmlWriter.writeStartElement("width"); xmlWriter.writeCharacters(Double.toString(lineWidth)); xmlWriter.writeEndElement(); } final Color lineColor = this.getLineColor(); - if (lineColor != null) - { + if (lineColor != null) { xmlWriter.writeStartElement("color"); xmlWriter.writeCharacters(KMLExportUtil.stripHexPrefix(WWUtil.encodeColorABGR(lineColor))); xmlWriter.writeEndElement(); @@ -769,7 +720,8 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); // Style xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/render/Polygon.java b/src/gov/nasa/worldwind/render/Polygon.java index 9b1ef14b38..c2195c6c94 100644 --- a/src/gov/nasa/worldwind/render/Polygon.java +++ b/src/gov/nasa/worldwind/render/Polygon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -40,8 +39,7 @@ * @author tag * @version $Id: Polygon.java 3431 2015-10-01 04:29:15Z dcollins $ */ -public class Polygon extends AbstractShape -{ +public class Polygon extends AbstractShape { // TODO: Merge texture coordinates into the vertex+normal buffer rather than specifying them in a separate buffer. // TODO: Tessellate polygon's interior to follow globe curvature when in ABSOLUTE altitude mode. @@ -49,31 +47,45 @@ public class Polygon extends AbstractShape * This class holds globe-specific data for this shape. It's managed via the shape-data cache in {@link * gov.nasa.worldwind.render.AbstractShape.AbstractShapeData}. */ - protected static class ShapeData extends AbstractShapeData implements Iterable - { - /** This class holds the per-globe data for this shape. */ + protected static class ShapeData extends AbstractShapeData implements Iterable { + + /** + * This class holds the per-globe data for this shape. + */ protected List boundaries = new ArrayList(); - /** The rotation matrix for this shape data. */ + /** + * The rotation matrix for this shape data. + */ protected Matrix rotationMatrix; // will vary among globes /** * The vertex data buffer for this shape data. The first half contains vertex coordinates, the second half * contains normals. */ protected FloatBuffer coordBuffer; // contains boundary vertices in first half and normals in second half - /** The slice of the coordBuffer that contains normals. */ + /** + * The slice of the coordBuffer that contains normals. + */ protected FloatBuffer normalBuffer; - /** The index of the first normal in the coordBuffer. */ + /** + * The index of the first normal in the coordBuffer. + */ protected int normalBufferPosition; - /** This shape's tessellation indices. */ + /** + * This shape's tessellation indices. + */ protected GLUTessellatorSupport.CollectIndexListsCallback cb; // the tessellated polygon indices /** * The indices identifying the cap vertices in a shape data's vertex buffer. Determined when this shape is * tessellated, which occurs only once unless the shape's boundaries are re-specified. */ protected IntBuffer interiorIndicesBuffer; - /** Indicates whether a tessellation error occurred. No more attempts to tessellate will be made if set to true. */ + /** + * Indicates whether a tessellation error occurred. No more attempts to tessellate will be made if set to true. + */ protected boolean tessellationError = false; // set to true if the tessellator fails - /** Indicates whether the index buffer needs to be filled because a new buffer is used or some other reason. */ + /** + * Indicates whether the index buffer needs to be filled because a new buffer is used or some other reason. + */ protected boolean refillIndexBuffer = true; // set to true if the index buffer needs to be refilled /** * Indicates whether the index buffer's VBO needs to be filled because a new buffer is used or some other @@ -84,23 +96,20 @@ protected static class ShapeData extends AbstractShapeData implements Iterable())); return; } // Copy the shape's boundaries. - for (List boundary : shape.boundaries) - { + for (List boundary : shape.boundaries) { this.boundaries.add(new BoundaryInfo(boundary)); } } @@ -110,13 +119,11 @@ public ShapeData(DrawContext dc, Polygon shape) * * @return this shape data's outer boundary info. */ - protected BoundaryInfo getOuterBoundaryInfo() - { + protected BoundaryInfo getOuterBoundaryInfo() { return this.boundaries.get(0); } - public Iterator iterator() - { + public Iterator iterator() { return this.boundaries.iterator(); } @@ -125,8 +132,7 @@ public Iterator iterator() * * @return this shape data's rotation matrix, or null if there isn't one. */ - public Matrix getRotationMatrix() - { + public Matrix getRotationMatrix() { return this.rotationMatrix; } @@ -135,14 +141,12 @@ public Matrix getRotationMatrix() * * @param matrix the new rotation matrix. */ - public void setRotationMatrix(Matrix matrix) - { + public void setRotationMatrix(Matrix matrix) { this.rotationMatrix = matrix; } } - protected AbstractShapeData createCacheEntry(DrawContext dc) - { + protected AbstractShapeData createCacheEntry(DrawContext dc) { return new ShapeData(dc, this); } @@ -151,19 +155,26 @@ protected AbstractShapeData createCacheEntry(DrawContext dc) * * @return the current data cache entry. */ - protected ShapeData getCurrent() - { + protected ShapeData getCurrent() { return (ShapeData) this.getCurrentData(); } - /** Holds information for each contour of the polygon. The vertex values are updated at every geometry regeneration. */ - protected static class BoundaryInfo - { - /** The shape's boundary positions. */ + /** + * Holds information for each contour of the polygon. The vertex values are updated at every geometry regeneration. + */ + protected static class BoundaryInfo { + + /** + * The shape's boundary positions. + */ protected List positions; - /** The shape's computed vertices, arranged in one array. */ + /** + * The shape's computed vertices, arranged in one array. + */ protected Vec4[] vertices; // TODO: eliminate need for this; use the vertex buffer instead - /** The shape's computed vertices, arranged in a buffer. */ + /** + * The shape's computed vertices, arranged in a buffer. + */ protected FloatBuffer vertexBuffer; // vertices passed to OpenGL /** @@ -171,8 +182,7 @@ protected static class BoundaryInfo * * @param positions the boundary positions. */ - public BoundaryInfo(List positions) - { + public BoundaryInfo(List positions) { this.positions = positions; } } @@ -183,7 +193,9 @@ public BoundaryInfo(List positions) */ protected static HashMap edgeIndexBuffers = new HashMap(); - /** Indicates the number of vertices that must be present in order for VBOs to be used to render this shape. */ + /** + * Indicates the number of vertices that must be present in order for VBOs to be used to render this shape. + */ protected static final int VBO_THRESHOLD = Configuration.getIntegerValue(AVKey.VBO_THRESHOLD, 30); /** @@ -191,27 +203,42 @@ public BoundaryInfo(List positions) * for the outer boundary, but its list is empty if an outer boundary has not been specified. */ protected List> boundaries; // the defining locations or positions of the boundary - /** The total number of positions in the entire polygon. */ + /** + * The total number of positions in the entire polygon. + */ protected int numPositions; - /** If an image source was specified, this is the WWTexture form. */ + /** + * If an image source was specified, this is the WWTexture form. + */ protected WWTexture texture; // an optional texture for the base polygon - /** This shape's rotation, in degrees positive counterclockwise. */ + /** + * This shape's rotation, in degrees positive counterclockwise. + */ protected Double rotation; // in degrees; positive is CCW - /** This shape's texture coordinates. */ + /** + * This shape's texture coordinates. + */ protected FloatBuffer textureCoordsBuffer; // texture coords if texturing // Fields used in intersection calculations - /** The terrain used in the most recent intersection calculations. */ + /** + * The terrain used in the most recent intersection calculations. + */ protected Terrain previousIntersectionTerrain; - /** The globe state key for the globe used in the most recent intersection calculation. */ + /** + * The globe state key for the globe used in the most recent intersection calculation. + */ protected Object previousIntersectionGlobeStateKey; - /** The shape data used for the previous intersection calculation. */ + /** + * The shape data used for the previous intersection calculation. + */ protected ShapeData previousIntersectionShapeData; - /** Construct a polygon with an empty outer boundary. */ - public Polygon() - { + /** + * Construct a polygon with an empty outer boundary. + */ + public Polygon() { this.boundaries = new ArrayList>(); this.boundaries.add(new ArrayList()); // placeholder for outer boundary } @@ -223,12 +250,10 @@ public Polygon() * * @throws IllegalArgumentException if the location list is null. */ - public Polygon(Iterable corners) - { + public Polygon(Iterable corners) { this(); // to initialize the instance - if (corners == null) - { + if (corners == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -241,17 +266,15 @@ public Polygon(Iterable corners) * Construct a polygon for a specified list of outer-boundary positions. * * @param corners the list of positions -- latitude longitude and altitude -- defining the polygon. The current - * altitude mode determines whether the positions are considered relative to mean sea level (they are - * "absolute") or the ground elevation at the associated latitude and longitude. + * altitude mode determines whether the positions are considered relative to mean sea level (they are "absolute") or + * the ground elevation at the associated latitude and longitude. * * @throws IllegalArgumentException if the position list is null. */ - public Polygon(Position.PositionList corners) - { + public Polygon(Position.PositionList corners) { this(); // to initialize the boundaries - if (corners == null) - { + if (corners == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -261,24 +284,25 @@ public Polygon(Position.PositionList corners) } @Override - protected void initialize() - { + protected void initialize() { // Nothing unique to initialize in this class. } - /** Void any computed data. Called when a factor affecting the computed data is changed. */ - protected void reset() - { + /** + * Void any computed data. Called when a factor affecting the computed data is changed. + */ + protected void reset() { // Assumes that the boundary lists have already been established. - for (List boundary : this.boundaries) - { - if (boundary == null || boundary.size() < 3) + for (List boundary : this.boundaries) { + if (boundary == null || boundary.size() < 3) { continue; + } //noinspection StringEquality - if (WWMath.computeWindingOrderOfLocations(boundary) != AVKey.COUNTER_CLOCKWISE) + if (WWMath.computeWindingOrderOfLocations(boundary) != AVKey.COUNTER_CLOCKWISE) { Collections.reverse(boundary); + } } this.numPositions = this.countPositions(); @@ -295,12 +319,10 @@ protected void reset() * * @return the number of positions in this shape. */ - protected int countPositions() - { + protected int countPositions() { int count = 0; - for (List boundary : this.boundaries) - { + for (List boundary : this.boundaries) { count += boundary.size(); } @@ -312,8 +334,7 @@ protected int countPositions() * * @return this polygon's outer boundary positions. The list may be empty but will not be null. */ - public Iterable getOuterBoundary() - { + public Iterable getOuterBoundary() { return this.outerBoundary(); } @@ -322,13 +343,11 @@ public Iterable getOuterBoundary() * * @return this polygon's outer boundary. The list may be empty but will not be null. */ - public List outerBoundary() - { + public List outerBoundary() { return this.boundaries.get(0); } - protected boolean isOuterBoundaryValid() - { + protected boolean isOuterBoundaryValid() { return this.boundaries.size() > 0 && this.boundaries.get(0).size() > 2; } @@ -336,22 +355,21 @@ protected boolean isOuterBoundaryValid() * Specifies the latitude, longitude and altitude of the outer boundary positions defining this polygon. * * @param corners this polygon's positions. A copy of the list is made and retained, and a duplicate of the first - * position is appended to the copy if the first and last positions are not identical. + * position is appended to the copy if the first and last positions are not identical. * * @throws IllegalArgumentException if the location list is null or contains fewer than three locations. */ - public void setOuterBoundary(Iterable corners) - { - if (corners == null) - { + public void setOuterBoundary(Iterable corners) { + if (corners == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.boundaries.set(0, this.fillBoundary(corners)); - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.setSurfacePolygonBoundaries(this.surfaceShape); + } this.reset(); } @@ -364,26 +382,25 @@ public void setOuterBoundary(Iterable corners) * * @return a list of the boundary positions. */ - protected List fillBoundary(Iterable corners) - { + protected List fillBoundary(Iterable corners) { ArrayList list = new ArrayList(); - for (Position corner : corners) - { - if (corner != null) + for (Position corner : corners) { + if (corner != null) { list.add(corner); + } } - if (list.size() < 3) - { + if (list.size() < 3) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Close the list if not already closed. - if (list.size() > 0 && !list.get(0).equals(list.get(list.size() - 1))) + if (list.size() > 0 && !list.get(0).equals(list.get(list.size() - 1))) { list.add(list.get(0)); + } list.trimToSize(); @@ -395,22 +412,21 @@ protected List fillBoundary(Iterable cor * last position is not identical to the first. * * @param corners the new boundary positions. A copy of the list is created and retained, and a duplicate of the - * first position is added to the list if the first and last positions are not identical. + * first position is added to the list if the first and last positions are not identical. * * @throws IllegalArgumentException if the location list is null or contains fewer than three locations. */ - public void addInnerBoundary(Iterable corners) - { - if (corners == null) - { + public void addInnerBoundary(Iterable corners) { + if (corners == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.boundaries.add(this.fillBoundary(corners)); - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.setSurfacePolygonBoundaries(this.surfaceShape); + } this.reset(); } @@ -420,8 +436,7 @@ public void addInnerBoundary(Iterable corners) * * @return this shape's boundaries. */ - public List> getBoundaries() - { + public List> getBoundaries() { return this.boundaries; } @@ -430,8 +445,7 @@ public List> getBoundaries() * * @return the texture image source, or null if no source has been specified. */ - public Object getTextureImageSource() - { + public Object getTextureImageSource() { return this.getTexture() != null ? this.getTexture().getImageSource() : null; } @@ -441,8 +455,7 @@ public Object getTextureImageSource() * * @return the texture, or null if there is no texture or the texture is not yet available. */ - protected WWTexture getTexture() - { + protected WWTexture getTexture() { return this.texture; } @@ -451,10 +464,10 @@ protected WWTexture getTexture() * * @return the texture coordinates, or null if no texture coordinates have been specified. */ - public float[] getTextureCoords() - { - if (this.textureCoordsBuffer == null) + public float[] getTextureCoords() { + if (this.textureCoordsBuffer == null) { return null; + } float[] retCoords = new float[this.textureCoordsBuffer.limit()]; this.textureCoordsBuffer.get(retCoords, 0, retCoords.length); @@ -466,38 +479,34 @@ public float[] getTextureCoords() /** * Specifies the texture to apply to this polygon. * - * @param imageSource the texture image source. May be a {@link String} identifying a file path or URL, a {@link + * @param imageSource the texture image source. May be a {@link String} identifying a file path or URL, a {@link * File}, or a {@link java.net.URL}. - * @param texCoords the (s, t) texture coordinates aligning the image to the polygon. There must be one texture - * coordinate pair, (s, t), for each polygon location in the polygon's outer boundary. + * @param texCoords the (s, t) texture coordinates aligning the image to the polygon. There must be one texture + * coordinate pair, (s, t), for each polygon location in the polygon's outer boundary. * @param texCoordCount the number of texture coordinates, (s, v) pairs, specified. * * @throws IllegalArgumentException if the image source is not null and either the texture coordinates are null or - * inconsistent with the specified texture-coordinate count, or there are fewer - * than three texture coordinate pairs. + * inconsistent with the specified texture-coordinate count, or there are fewer than three texture coordinate pairs. */ - public void setTextureImageSource(Object imageSource, float[] texCoords, int texCoordCount) - { - if (imageSource == null) - { + public void setTextureImageSource(Object imageSource, float[] texCoords, int texCoordCount) { + if (imageSource == null) { this.texture = null; this.textureCoordsBuffer = null; - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.setSurfacePolygonTexImageSource(this.surfaceShape); + } return; } - if (texCoords == null) - { + if (texCoords == null) { String message = Logging.getMessage("generic.ListIsEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoordCount < 3 || texCoords.length < 2 * texCoordCount) - { + if (texCoordCount < 3 || texCoords.length < 2 * texCoordCount) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -509,40 +518,37 @@ public void setTextureImageSource(Object imageSource, float[] texCoords, int tex boolean closeIt = texCoords[0] != texCoords[texCoordCount - 2] || texCoords[1] != texCoords[texCoordCount - 1]; int size = 2 * (texCoordCount + (closeIt ? 1 : 0)); - if (this.textureCoordsBuffer == null || this.textureCoordsBuffer.capacity() < size) - { + if (this.textureCoordsBuffer == null || this.textureCoordsBuffer.capacity() < size) { this.textureCoordsBuffer = Buffers.newDirectFloatBuffer(size); - } - else - { + } else { this.textureCoordsBuffer.limit(this.textureCoordsBuffer.capacity()); this.textureCoordsBuffer.rewind(); } - for (int i = 0; i < 2 * texCoordCount; i++) - { + for (int i = 0; i < 2 * texCoordCount; i++) { this.textureCoordsBuffer.put(texCoords[i]); } - if (closeIt) - { + if (closeIt) { this.textureCoordsBuffer.put(this.textureCoordsBuffer.get(0)); this.textureCoordsBuffer.put(this.textureCoordsBuffer.get(1)); } this.textureCoordsBuffer.rewind(); - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.setSurfacePolygonTexImageSource(this.surfaceShape); + } } - public Position getReferencePosition() - { - if (this.referencePosition != null) + public Position getReferencePosition() { + if (this.referencePosition != null) { return this.referencePosition; + } - if (this.outerBoundary().size() > 0) + if (this.outerBoundary().size() > 0) { this.referencePosition = this.outerBoundary().get(0); + } return this.referencePosition; } @@ -552,8 +558,7 @@ public Position getReferencePosition() * * @return the rotation in degrees, or null if no rotation is specified. */ - public Double getRotation() - { + public Double getRotation() { return this.rotation; } @@ -562,15 +567,13 @@ public Double getRotation() * * @param rotation the amount of rotation to apply, in degrees, or null to apply no rotation. */ - public void setRotation(Double rotation) - { + public void setRotation(Double rotation) { this.rotation = rotation; this.reset(); } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { SurfacePolygon polygon = new SurfacePolygon(); this.setSurfacePolygonBoundaries(polygon); this.setSurfacePolygonTexImageSource(polygon); @@ -578,21 +581,18 @@ protected SurfaceShape createSurfaceShape() return polygon; } - protected void setSurfacePolygonBoundaries(SurfaceShape shape) - { + protected void setSurfacePolygonBoundaries(SurfaceShape shape) { SurfacePolygon polygon = (SurfacePolygon) shape; polygon.setLocations(this.getOuterBoundary()); List> bounds = this.getBoundaries(); - for (int i = 1; i < bounds.size(); i++) - { + for (int i = 1; i < bounds.size(); i++) { polygon.addInnerBoundary(bounds.get(i)); } } - protected void setSurfacePolygonTexImageSource(SurfaceShape shape) - { + protected void setSurfacePolygonTexImageSource(SurfaceShape shape) { SurfacePolygon polygon = (SurfacePolygon) shape; float[] texCoords = this.getTextureCoords(); @@ -600,12 +600,12 @@ protected void setSurfacePolygonTexImageSource(SurfaceShape shape) polygon.setTextureImageSource(this.getTextureImageSource(), texCoords, texCoordCount); } - public Extent getExtent(Globe globe, double verticalExaggeration) - { + public Extent getExtent(Globe globe, double verticalExaggeration) { // See if we've cached an extent associated with the globe. Extent extent = super.getExtent(globe, verticalExaggeration); - if (extent != null) + if (extent != null) { return extent; + } return super.computeExtentFromPositions(globe, verticalExaggeration, this.getOuterBoundary()); } @@ -618,10 +618,10 @@ public Extent getExtent(Globe globe, double verticalExaggeration) * * @return the boundary's extent. Returns null if the boundary's vertices have not been computed. */ - protected Extent computeExtent(BoundaryInfo boundary, Vec4 refPoint) - { - if (boundary == null || boundary.vertices == null) + protected Extent computeExtent(BoundaryInfo boundary, Vec4 refPoint) { + if (boundary == null || boundary.vertices == null) { return null; + } // The bounding box is computed relative to the polygon's reference point, so it needs to be translated to // model coordinates in order to indicate its model-coordinate extent. @@ -630,84 +630,84 @@ protected Extent computeExtent(BoundaryInfo boundary, Vec4 refPoint) return boundingBox != null ? boundingBox.translate(refPoint) : null; } - public Sector getSector() - { - if (this.sector == null && this.isOuterBoundaryValid()) + public Sector getSector() { + if (this.sector == null && this.isOuterBoundaryValid()) { this.sector = Sector.boundingSector(this.getOuterBoundary()); + } return this.sector; } - protected boolean mustApplyTexture(DrawContext dc) - { + protected boolean mustApplyTexture(DrawContext dc) { return this.getTexture() != null && this.textureCoordsBuffer != null; } - protected boolean shouldUseVBOs(DrawContext dc) - { + protected boolean shouldUseVBOs(DrawContext dc) { return this.numPositions > VBO_THRESHOLD && super.shouldUseVBOs(dc); } - protected boolean mustRegenerateGeometry(DrawContext dc) - { - if (this.getCurrent().coordBuffer == null) + protected boolean mustRegenerateGeometry(DrawContext dc) { + if (this.getCurrent().coordBuffer == null) { return true; + } - if (dc.getVerticalExaggeration() != this.getCurrent().getVerticalExaggeration()) + if (dc.getVerticalExaggeration() != this.getCurrent().getVerticalExaggeration()) { return true; + } - if (this.mustApplyLighting(dc, null) && this.getCurrent().normalBuffer == null) + if (this.mustApplyLighting(dc, null) && this.getCurrent().normalBuffer == null) { return true; + } if (this.getAltitudeMode() == WorldWind.ABSOLUTE - && this.getCurrent().getGlobeStateKey() != null - && this.getCurrent().getGlobeStateKey().equals(dc.getGlobe().getGlobeStateKey(dc))) + && this.getCurrent().getGlobeStateKey() != null + && this.getCurrent().getGlobeStateKey().equals(dc.getGlobe().getGlobeStateKey(dc))) { return false; + } return super.mustRegenerateGeometry(dc); } - public void render(DrawContext dc) - { - if (!this.isOuterBoundaryValid()) + public void render(DrawContext dc) { + if (!this.isOuterBoundaryValid()) { return; + } super.render(dc); } - protected boolean doMakeOrderedRenderable(DrawContext dc) - { - if (dc.getSurfaceGeometry() == null || !this.isOuterBoundaryValid()) + protected boolean doMakeOrderedRenderable(DrawContext dc) { + if (dc.getSurfaceGeometry() == null || !this.isOuterBoundaryValid()) { return false; + } - this.getCurrent().setRotationMatrix(this.getRotation() != null ? - this.computeRotationMatrix(dc.getGlobe()) : null); + this.getCurrent().setRotationMatrix(this.getRotation() != null + ? this.computeRotationMatrix(dc.getGlobe()) : null); this.createMinimalGeometry(dc, this.getCurrent()); // If the shape is less that a pixel in size, don't render it. - if (this.getCurrent().getExtent() == null || dc.isSmall(this.getExtent(), 1)) + if (this.getCurrent().getExtent() == null || dc.isSmall(this.getExtent(), 1)) { return false; + } - if (!this.intersectsFrustum(dc)) + if (!this.intersectsFrustum(dc)) { return false; + } this.createFullGeometry(dc, dc.getTerrain(), this.getCurrent(), true); return true; } - protected boolean isOrderedRenderableValid(DrawContext dc) - { + protected boolean isOrderedRenderableValid(DrawContext dc) { return this.getCurrent().coordBuffer != null && this.isOuterBoundaryValid(); } - protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) - { + protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) { OGLStackHandler ogsh = super.beginDrawing(dc, attrMask); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Push an identity texture matrix. This prevents drawSides() from leaking GL texture matrix state. The // texture matrix stack is popped from OGLStackHandler.pop(), in the finally block below. GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -717,34 +717,30 @@ protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) return ogsh; } - protected void doDrawOutline(DrawContext dc) - { - if (this.shouldUseVBOs(dc)) - { + protected void doDrawOutline(DrawContext dc) { + if (this.shouldUseVBOs(dc)) { int[] vboIds = this.getVboIds(dc); - if (vboIds != null) + if (vboIds != null) { this.doDrawOutlineVBO(dc, vboIds, this.getCurrent()); - else + } else { this.doDrawOutlineVA(dc, this.getCurrent()); - } - else - { + } + } else { this.doDrawOutlineVA(dc, this.getCurrent()); } } - protected void doDrawOutlineVA(DrawContext dc, ShapeData shapeData) - { + protected void doDrawOutlineVA(DrawContext dc, ShapeData shapeData) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glVertexPointer(3, GL.GL_FLOAT, 0, shapeData.coordBuffer.rewind()); - if (!dc.isPickingMode() && this.mustApplyLighting(dc, null)) + if (!dc.isPickingMode() && this.mustApplyLighting(dc, null)) { gl.glNormalPointer(GL.GL_FLOAT, 0, shapeData.normalBuffer.rewind()); + } int k = 0; - for (BoundaryInfo boundary : shapeData) - { + for (BoundaryInfo boundary : shapeData) { gl.glDrawArrays(GL.GL_LINE_STRIP, k, boundary.vertices.length); k += boundary.vertices.length; } @@ -754,19 +750,18 @@ protected void doDrawOutlineVA(DrawContext dc, ShapeData shapeData) // dc.drawNormals(1000, this.boundarySet.coordBuffer, this.boundarySet.normalBuffer); } - protected void doDrawOutlineVBO(DrawContext dc, int[] vboIds, ShapeData shapeData) - { + protected void doDrawOutlineVBO(DrawContext dc, int[] vboIds, ShapeData shapeData) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]); gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0); - if (!dc.isPickingMode() && this.mustApplyLighting(dc, null)) + if (!dc.isPickingMode() && this.mustApplyLighting(dc, null)) { gl.glNormalPointer(GL.GL_FLOAT, 0, 4 * shapeData.normalBufferPosition); + } int k = 0; - for (BoundaryInfo boundary : shapeData) - { + for (BoundaryInfo boundary : shapeData) { // TODO: check use glMultiDrawArrays gl.glDrawArrays(GL.GL_LINE_STRIP, k, boundary.vertices.length); k += boundary.vertices.length; @@ -775,8 +770,7 @@ protected void doDrawOutlineVBO(DrawContext dc, int[] vboIds, ShapeData shapeDat gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } - protected void doDrawInterior(DrawContext dc) - { + protected void doDrawInterior(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. if (!dc.isPickingMode() && mustApplyTexture(dc) && this.getTexture().bind(dc)) // bind initiates retrieval @@ -786,33 +780,29 @@ protected void doDrawInterior(DrawContext dc) gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, this.textureCoordsBuffer.rewind()); dc.getGL().glEnable(GL.GL_TEXTURE_2D); gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); - } - else - { + } else { dc.getGL().glDisable(GL.GL_TEXTURE_2D); gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY); } - if (this.shouldUseVBOs(dc)) - { + if (this.shouldUseVBOs(dc)) { int[] vboIds = this.getVboIds(dc); - if (vboIds != null) + if (vboIds != null) { this.doDrawInteriorVBO(dc, vboIds, this.getCurrent()); - else + } else { this.doDrawInteriorVA(dc, this.getCurrent()); - } - else - { + } + } else { this.doDrawInteriorVA(dc, this.getCurrent()); } } - protected void doDrawInteriorVA(DrawContext dc, ShapeData shapeData) - { + protected void doDrawInteriorVA(DrawContext dc, ShapeData shapeData) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!dc.isPickingMode() && this.mustApplyLighting(dc, null)) + if (!dc.isPickingMode() && this.mustApplyLighting(dc, null)) { gl.glNormalPointer(GL.GL_FLOAT, 0, shapeData.normalBuffer.rewind()); + } FloatBuffer vb = shapeData.coordBuffer; gl.glVertexPointer(3, GL.GL_FLOAT, 0, vb.rewind()); @@ -821,8 +811,7 @@ protected void doDrawInteriorVA(DrawContext dc, ShapeData shapeData) gl.glDrawElements(GL.GL_TRIANGLES, ib.limit(), GL.GL_UNSIGNED_INT, ib); } - protected void doDrawInteriorVBO(DrawContext dc, int[] vboIds, ShapeData shapeData) - { + protected void doDrawInteriorVBO(DrawContext dc, int[] vboIds, ShapeData shapeData) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]); @@ -830,8 +819,9 @@ protected void doDrawInteriorVBO(DrawContext dc, int[] vboIds, ShapeData shapeDa gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0); - if (!dc.isPickingMode() && this.mustApplyLighting(dc, null)) + if (!dc.isPickingMode() && this.mustApplyLighting(dc, null)) { gl.glNormalPointer(GL.GL_FLOAT, 0, 4 * shapeData.normalBufferPosition); + } gl.glDrawElements(GL.GL_TRIANGLES, shapeData.interiorIndicesBuffer.limit(), GL.GL_UNSIGNED_INT, 0); @@ -839,20 +829,18 @@ protected void doDrawInteriorVBO(DrawContext dc, int[] vboIds, ShapeData shapeDa gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); } - protected Matrix computeRotationMatrix(Globe globe) - { - if (this.getRotation() == null) + protected Matrix computeRotationMatrix(Globe globe) { + if (this.getRotation() == null) { return null; + } // Find the centroid of the polygon with all altitudes 0 and rotate around that using the surface normal at // that point as the rotation axis. - double cx = 0; double cy = 0; double cz = 0; double outerBoundarySize = outerBoundary().size(); - for (int i = 0; i < this.outerBoundary().size(); i++) - { + for (int i = 0; i < this.outerBoundary().size(); i++) { Vec4 vert = globe.computePointFromPosition(this.outerBoundary().get(i), 0); cx += vert.x / outerBoundarySize; @@ -874,25 +862,26 @@ protected Matrix computeRotationMatrix(Globe globe) *

          * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shapeData the current shape data for this shape. */ - protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) - { + protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) { Matrix rotationMatrix = shapeData.getRotationMatrix(); Vec4 refPt = this.computeReferencePoint(dc.getTerrain(), rotationMatrix); - if (refPt == null) + if (refPt == null) { return; + } shapeData.setReferencePoint(refPt); // Need only the outer-boundary vertices. this.computeBoundaryVertices(dc.getTerrain(), shapeData.getOuterBoundaryInfo(), - shapeData.getReferencePoint(), rotationMatrix); + shapeData.getReferencePoint(), rotationMatrix); - if (shapeData.getExtent() == null || this.getAltitudeMode() != WorldWind.ABSOLUTE) + if (shapeData.getExtent() == null || this.getAltitudeMode() != WorldWind.ABSOLUTE) { shapeData.setExtent(this.computeExtent(shapeData.getOuterBoundaryInfo(), - shapeData.getReferencePoint())); + shapeData.getReferencePoint())); + } shapeData.setEyeDistance(this.computeEyeDistance(dc, shapeData)); shapeData.setGlobeStateKey(dc.getGlobe().getGlobeStateKey(dc)); @@ -904,35 +893,35 @@ protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData) *

          * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * - * @param dc the draw context. + * @param dc the draw context. * @param shapeData the current shape data for this shape. * * @return the minimum distance from the shape to the eye point. */ - protected double computeEyeDistance(DrawContext dc, ShapeData shapeData) - { + protected double computeEyeDistance(DrawContext dc, ShapeData shapeData) { double minDistance = Double.MAX_VALUE; Vec4 eyePoint = dc.getView().getEyePoint(); - for (Vec4 point : shapeData.getOuterBoundaryInfo().vertices) - { + for (Vec4 point : shapeData.getOuterBoundaryInfo().vertices) { double d = point.add3(shapeData.getReferencePoint()).distanceTo3(eyePoint); - if (d < minDistance) + if (d < minDistance) { minDistance = d; + } } return minDistance; } - protected Vec4 computeReferencePoint(Terrain terrain, Matrix rotationMatrix) - { + protected Vec4 computeReferencePoint(Terrain terrain, Matrix rotationMatrix) { Position refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return null; + } Vec4 refPt = terrain.getSurfacePoint(refPos.getLatitude(), refPos.getLongitude(), 0); - if (refPt == null) + if (refPt == null) { return null; + } return rotationMatrix != null ? refPt.transformBy4(rotationMatrix) : refPt; } @@ -940,62 +929,60 @@ protected Vec4 computeReferencePoint(Terrain terrain, Matrix rotationMatrix) /** * Computes a shape's full geometry. * - * @param dc the current draw context. - * @param terrain the terrain to use when computing the geometry. - * @param shapeData the current shape data for this shape. + * @param dc the current draw context. + * @param terrain the terrain to use when computing the geometry. + * @param shapeData the current shape data for this shape. * @param skipOuterBoundary true if outer boundaries vertices do not need to be calculated, otherwise false. */ protected void createFullGeometry(DrawContext dc, Terrain terrain, ShapeData shapeData, - boolean skipOuterBoundary) - { + boolean skipOuterBoundary) { this.createVertices(terrain, shapeData, skipOuterBoundary); this.createGeometry(dc, shapeData); - if (this.mustApplyLighting(dc, null)) + if (this.mustApplyLighting(dc, null)) { this.createNormals(shapeData); - else + } else { shapeData.normalBuffer = null; + } } /** * Computes the Cartesian vertices for this shape. * - * @param terrain the terrain to use if the altitude mode is relative to the terrain. - * @param shapeData the current shape data for this shape. + * @param terrain the terrain to use if the altitude mode is relative to the terrain. + * @param shapeData the current shape data for this shape. * @param skipOuterBoundary if true, don't calculate the vertices for the outer boundary. This is used when the - * outer boundary vertices were computed as minimal geometry. + * outer boundary vertices were computed as minimal geometry. */ - protected void createVertices(Terrain terrain, ShapeData shapeData, boolean skipOuterBoundary) - { - for (BoundaryInfo boundary : shapeData) - { - if (boundary != shapeData.getOuterBoundaryInfo() || !skipOuterBoundary) + protected void createVertices(Terrain terrain, ShapeData shapeData, boolean skipOuterBoundary) { + for (BoundaryInfo boundary : shapeData) { + if (boundary != shapeData.getOuterBoundaryInfo() || !skipOuterBoundary) { this.computeBoundaryVertices(terrain, boundary, shapeData.getReferencePoint(), - shapeData.getRotationMatrix()); + shapeData.getRotationMatrix()); + } } } /** * Compute the vertices associated with a specified boundary. * - * @param terrain the terrain to use when calculating vertices relative to the ground. - * @param boundary the boundary to compute vertices for. - * @param refPoint the reference point. Vertices are computed relative to this point, which is usually the - * shape's reference point. + * @param terrain the terrain to use when calculating vertices relative to the ground. + * @param boundary the boundary to compute vertices for. + * @param refPoint the reference point. Vertices are computed relative to this point, which is usually the shape's + * reference point. * @param rotationMatrix the rotation matrix to apply to the vertices. */ - protected void computeBoundaryVertices(Terrain terrain, BoundaryInfo boundary, Vec4 refPoint, Matrix rotationMatrix) - { + protected void computeBoundaryVertices(Terrain terrain, BoundaryInfo boundary, Vec4 refPoint, Matrix rotationMatrix) { int n = boundary.positions.size(); Vec4[] boundaryVertices = new Vec4[n]; - for (int i = 0; i < n; i++) - { - if (rotationMatrix == null) + for (int i = 0; i < n; i++) { + if (rotationMatrix == null) { boundaryVertices[i] = this.computePoint(terrain, boundary.positions.get(i)).subtract3(refPoint); - else + } else { boundaryVertices[i] = this.computePoint(terrain, boundary.positions.get(i)).transformBy4( - rotationMatrix).subtract3(refPoint); + rotationMatrix).subtract3(refPoint); + } } boundary.vertices = boundaryVertices; @@ -1006,50 +993,49 @@ protected void computeBoundaryVertices(Terrain terrain, BoundaryInfo boundary, V *

          * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shapeData boundary vertices are calculated during {@link #createMinimalGeometry(DrawContext, * gov.nasa.worldwind.render.Polygon.ShapeData)}). */ - protected void createGeometry(DrawContext dc, ShapeData shapeData) - { + protected void createGeometry(DrawContext dc, ShapeData shapeData) { int size = this.numPositions * (this.mustApplyLighting(dc, null) ? 6 : 3); - if (shapeData.coordBuffer != null && shapeData.coordBuffer.capacity() >= size) + if (shapeData.coordBuffer != null && shapeData.coordBuffer.capacity() >= size) { shapeData.coordBuffer.clear(); - else + } else { shapeData.coordBuffer = Buffers.newDirectFloatBuffer(size); + } // Capture the position position at which normals buffer starts (in case there are normals) shapeData.normalBufferPosition = this.numPositions * 3; // Fill the vertex buffer. Simultaneously create individual buffer slices for each boundary. - for (BoundaryInfo boundary : shapeData) - { + for (BoundaryInfo boundary : shapeData) { boundary.vertexBuffer = WWBufferUtil.copyArrayToBuffer(boundary.vertices, shapeData.coordBuffer.slice()); shapeData.coordBuffer.position(shapeData.coordBuffer.position() + boundary.vertexBuffer.limit()); } - if (shapeData.cb == null && !shapeData.tessellationError) + if (shapeData.cb == null && !shapeData.tessellationError) { this.createTessllationGeometry(dc, shapeData); + } - if (shapeData.refillIndexBuffer) + if (shapeData.refillIndexBuffer) { this.generateInteriorIndices(shapeData); + } } /** * Create this shape's vertex normals. * * @param shapeData the current shape data holding the vertex coordinates and in which the normal vectors are added. - * The normal vectors are appended to the vertex coordinates in the same buffer. The shape data's - * coordinate buffer must have sufficient capacity to hold the vertex normals. + * The normal vectors are appended to the vertex coordinates in the same buffer. The shape data's coordinate buffer + * must have sufficient capacity to hold the vertex normals. */ - protected void createNormals(ShapeData shapeData) - { + protected void createNormals(ShapeData shapeData) { shapeData.coordBuffer.position(shapeData.normalBufferPosition); shapeData.normalBuffer = shapeData.coordBuffer.slice(); - for (BoundaryInfo boundary : shapeData) - { + for (BoundaryInfo boundary : shapeData) { this.computeBoundaryNormals(boundary, shapeData.normalBuffer); } } @@ -1059,14 +1045,12 @@ protected void createNormals(ShapeData shapeData) * * @param dc the current draw context. */ - protected void fillVBO(DrawContext dc) - { + protected void fillVBO(DrawContext dc) { GL gl = dc.getGL(); ShapeData shapeData = this.getCurrent(); int[] vboIds = (int[]) dc.getGpuResourceCache().get(shapeData.getVboCacheKey()); - if (vboIds == null) - { + if (vboIds == null) { int size = shapeData.coordBuffer.limit() * 4; size += shapeData.interiorIndicesBuffer.limit() * 4; @@ -1076,30 +1060,23 @@ protected void fillVBO(DrawContext dc) shapeData.refillIndexVBO = true; } - if (shapeData.refillIndexVBO) - { - try - { + if (shapeData.refillIndexVBO) { + try { IntBuffer ib = shapeData.interiorIndicesBuffer; gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboIds[1]); gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, ib.limit() * 4, ib.rewind(), GL.GL_DYNAMIC_DRAW); shapeData.refillIndexVBO = false; - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); } } - try - { + try { FloatBuffer vb = this.getCurrent().coordBuffer; gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]); gl.glBufferData(GL.GL_ARRAY_BUFFER, vb.limit() * 4, vb.rewind(), GL.GL_STATIC_DRAW); - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } } @@ -1108,29 +1085,27 @@ protected void fillVBO(DrawContext dc) * Compute normal vectors for a boundary's vertices. * * @param boundary the boundary to compute normals for. - * @param nBuf the buffer in which to place the computed normals. Must have enough remaining space to hold the - * normals. + * @param nBuf the buffer in which to place the computed normals. Must have enough remaining space to hold the + * normals. * * @return the buffer specified as input, with its limit incremented by the number of vertices copied, and its * position set to 0. */ - protected FloatBuffer computeBoundaryNormals(BoundaryInfo boundary, FloatBuffer nBuf) - { + protected FloatBuffer computeBoundaryNormals(BoundaryInfo boundary, FloatBuffer nBuf) { int nVerts = boundary.positions.size(); Vec4[] verts = boundary.vertices; double avgX, avgY, avgZ; // Compute normal for first point of boundary. - Vec4 va = verts[1].subtract3(verts[0]); + Vec4 va = verts[1].subtract3(verts[0]); Vec4 vb = verts[nVerts - 2].subtract3(verts[0]); // nverts - 2 because last and first are same avgX = (va.y * vb.z) - (va.z * vb.y); avgY = (va.z * vb.x) - (va.x * vb.z); avgZ = (va.x * vb.y) - (va.y * vb.x); // Compute normals for interior boundary points. - for (int i = 1; i < nVerts - 1; i++) - { - va = verts[i + 1].subtract3(verts[i]); + for (int i = 1; i < nVerts - 1; i++) { + va = verts[i + 1].subtract3(verts[i]); vb = verts[i - 1].subtract3(verts[i]); avgX += (va.y * vb.z) - (va.z * vb.y); avgY += (va.z * vb.x) - (va.x * vb.z); @@ -1142,8 +1117,7 @@ protected FloatBuffer computeBoundaryNormals(BoundaryInfo boundary, FloatBuffer avgZ /= nVerts - 1; double length = Math.sqrt(avgX * avgX + avgY * avgY + avgZ * avgZ); - for (int i = 0; i < nVerts; i++) - { + for (int i = 0; i < nVerts; i++) { nBuf.put((float) (avgX / length)).put((float) (avgY / length)).put((float) (avgZ / length)); } @@ -1154,25 +1128,23 @@ protected FloatBuffer computeBoundaryNormals(BoundaryInfo boundary, FloatBuffer * Tessellates the polygon. *

          * This method catches {@link OutOfMemoryError} exceptions and if the draw context is not null passes the exception - * to the rendering exception listener (see {@link WorldWindow#addRenderingExceptionListener(gov.nasa.worldwind.event.RenderingExceptionListener)}). + * to the rendering exception listener (see + * {@link WorldWindow#addRenderingExceptionListener(gov.nasa.worldwind.event.RenderingExceptionListener)}). * - * @param dc the draw context. + * @param dc the draw context. * @param shapeData the current shape data for this shape. */ - protected void createTessllationGeometry(DrawContext dc, ShapeData shapeData) - { + protected void createTessllationGeometry(DrawContext dc, ShapeData shapeData) { // Wrap polygon tessellation in a try/catch block. We do this to catch and handle OutOfMemoryErrors caused during // tessellation of the polygon vertices. If the polygon cannot be tessellated, we replace the polygon's locations // with an empty list to prevent subsequent tessellation attempts, and to avoid rendering a misleading // representation by omitting the polygon. - try - { + try { Vec4 normal = this.computePolygonNormal(dc, shapeData); // There's a fallback for non-computable normal in computePolygonNormal, but test here in case the fallback // doesn't work either. - if (normal == null) - { + if (normal == null) { String message = Logging.getMessage("Geom.ShapeNormalVectorNotComputable", this); Logging.logger().log(java.util.logging.Level.SEVERE, message); shapeData.tessellationError = true; @@ -1180,24 +1152,20 @@ protected void createTessllationGeometry(DrawContext dc, ShapeData shapeData) } this.tessellatePolygon(shapeData, normal.normalize3()); - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { String message = Logging.getMessage("generic.ExceptionWhileTessellating", this); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); shapeData.tessellationError = true; - if (dc != null) - { + if (dc != null) { //noinspection ThrowableInstanceNeverThrown dc.addRenderingException(new WWRuntimeException(message, e)); } } } - protected Vec4 computePolygonNormal(DrawContext dc, ShapeData shapeData) - { + protected Vec4 computePolygonNormal(DrawContext dc, ShapeData shapeData) { // The coord buffer might contain space for normals, but use only the vertices to compute the polygon normal. shapeData.coordBuffer.rewind(); FloatBuffer coordsOnly = shapeData.coordBuffer.slice(); @@ -1208,9 +1176,10 @@ protected Vec4 computePolygonNormal(DrawContext dc, ShapeData shapeData) // The normal vector is null if this is a degenerate polygon representing a line or a single point. We fall // back to using the globe's surface normal at the reference point. This allows the tessellator to process // the degenerate polygon without generating an exception. - if (normal == null) + if (normal == null) { normal = dc.getGlobe().computeSurfaceNormalAtLocation( - this.getReferencePosition().getLatitude(), this.getReferencePosition().getLongitude()); + this.getReferencePosition().getLatitude(), this.getReferencePosition().getLongitude()); + } return normal; } @@ -1219,28 +1188,24 @@ protected Vec4 computePolygonNormal(DrawContext dc, ShapeData shapeData) * Tessellates the polygon from its vertices. * * @param shapeData the polygon boundaries. - * @param normal a unit normal vector for the plane containing the polygon vertices. Even though the the vertices - * might not be coplanar, only one representative normal is used for tessellation. + * @param normal a unit normal vector for the plane containing the polygon vertices. Even though the the vertices + * might not be coplanar, only one representative normal is used for tessellation. */ - protected void tessellatePolygon(ShapeData shapeData, Vec4 normal) - { + protected void tessellatePolygon(ShapeData shapeData, Vec4 normal) { GLUTessellatorSupport glts = new GLUTessellatorSupport(); shapeData.cb = new GLUTessellatorSupport.CollectIndexListsCallback(); glts.beginTessellation(shapeData.cb, normal); - try - { + try { double[] coords = new double[3]; GLU.gluTessBeginPolygon(glts.getGLUtessellator(), null); int k = 0; - for (BoundaryInfo boundary : shapeData) - { + for (BoundaryInfo boundary : shapeData) { GLU.gluTessBeginContour(glts.getGLUtessellator()); FloatBuffer vBuf = boundary.vertexBuffer; - for (int i = 0; i < boundary.positions.size(); i++) - { + for (int i = 0; i < boundary.positions.size(); i++) { coords[0] = vBuf.get(i * 3); coords[1] = vBuf.get(i * 3 + 1); coords[2] = vBuf.get(i * 3 + 2); @@ -1251,9 +1216,7 @@ protected void tessellatePolygon(ShapeData shapeData, Vec4 normal) } GLU.gluTessEndPolygon(glts.getGLUtessellator()); - } - finally - { + } finally { // Free any heap memory used for tessellation immediately. If tessellation has consumed all available // heap memory, we must free memory used by tessellation immediately or subsequent operations such as // message logging will fail. @@ -1261,20 +1224,18 @@ protected void tessellatePolygon(ShapeData shapeData, Vec4 normal) } } - protected void generateInteriorIndices(ShapeData shapeData) - { + protected void generateInteriorIndices(ShapeData shapeData) { GLUTessellatorSupport.CollectIndexListsCallback cb = shapeData.cb; int size = this.countTriangleVertices(cb.getPrims(), cb.getPrimTypes()); - if (shapeData.interiorIndicesBuffer == null || shapeData.interiorIndicesBuffer.capacity() < size) + if (shapeData.interiorIndicesBuffer == null || shapeData.interiorIndicesBuffer.capacity() < size) { shapeData.interiorIndicesBuffer = Buffers.newDirectIntBuffer(size); - else + } else { shapeData.interiorIndicesBuffer.clear(); + } - for (int i = 0; i < cb.getPrims().size(); i++) - { - switch (cb.getPrimTypes().get(i)) - { + for (int i = 0; i < cb.getPrims().size(); i++) { + switch (cb.getPrimTypes().get(i)) { case GL.GL_TRIANGLES: Triangle.expandTriangles(cb.getPrims().get(i), shapeData.interiorIndicesBuffer); break; @@ -1294,20 +1255,20 @@ protected void generateInteriorIndices(ShapeData shapeData) shapeData.refillIndexVBO = true; } - protected boolean isSameAsPreviousTerrain(Terrain terrain) - { - if (terrain == null || this.previousIntersectionTerrain == null || terrain != this.previousIntersectionTerrain) + protected boolean isSameAsPreviousTerrain(Terrain terrain) { + if (terrain == null || this.previousIntersectionTerrain == null || terrain != this.previousIntersectionTerrain) { return false; + } - if (terrain.getVerticalExaggeration() != this.previousIntersectionTerrain.getVerticalExaggeration()) + if (terrain.getVerticalExaggeration() != this.previousIntersectionTerrain.getVerticalExaggeration()) { return false; + } - return this.previousIntersectionGlobeStateKey != null && - terrain.getGlobe().getGlobeStateKey().equals(this.previousIntersectionGlobeStateKey); + return this.previousIntersectionGlobeStateKey != null + && terrain.getGlobe().getGlobeStateKey().equals(this.previousIntersectionGlobeStateKey); } - public void clearIntersectionGeometry() - { + public void clearIntersectionGeometry() { this.previousIntersectionGlobeStateKey = null; this.previousIntersectionShapeData = null; this.previousIntersectionTerrain = null; @@ -1319,7 +1280,7 @@ public void clearIntersectionGeometry() * terrain used during rendering, which may be at lower level of detail than required for accurate intersection * determination. * - * @param line the line to intersect. + * @param line the line to intersect. * @param terrain the {@link Terrain} to use when computing the polygon's geometry. * * @return a list of intersections identifying where the line intersects the polygon, or null if the line does not @@ -1328,44 +1289,46 @@ public void clearIntersectionGeometry() * @throws InterruptedException if the operation is interrupted. * @see Terrain */ - public List intersect(Line line, Terrain terrain) throws InterruptedException - { + public List intersect(Line line, Terrain terrain) throws InterruptedException { Position refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return null; + } - if (!this.isOuterBoundaryValid()) + if (!this.isOuterBoundaryValid()) { return null; + } // Reuse the previously computed high-res shape data if the terrain is the same. ShapeData highResShapeData = this.isSameAsPreviousTerrain(terrain) ? this.previousIntersectionShapeData - : null; + : null; - if (highResShapeData == null) - { + if (highResShapeData == null) { highResShapeData = this.createIntersectionGeometry(terrain); - if (highResShapeData == null) + if (highResShapeData == null) { return null; + } this.previousIntersectionShapeData = highResShapeData; this.previousIntersectionTerrain = terrain; this.previousIntersectionGlobeStateKey = terrain.getGlobe().getGlobeStateKey(); } - if (highResShapeData.getExtent() != null && highResShapeData.getExtent().intersect(line) == null) + if (highResShapeData.getExtent() != null && highResShapeData.getExtent().intersect(line) == null) { return null; + } final Line localLine = new Line(line.getOrigin().subtract3(highResShapeData.getReferencePoint()), - line.getDirection()); + line.getDirection()); List intersections = new ArrayList(); this.intersect(localLine, highResShapeData, intersections); - if (intersections.size() == 0) + if (intersections.size() == 0) { return null; + } - for (Intersection intersection : intersections) - { + for (Intersection intersection : intersections) { Vec4 pt = intersection.getIntersectionPoint().add3(highResShapeData.getReferencePoint()); intersection.setIntersectionPoint(pt); @@ -1381,15 +1344,15 @@ public List intersect(Line line, Terrain terrain) throws Interrupt return intersections; } - protected ShapeData createIntersectionGeometry(Terrain terrain) - { + protected ShapeData createIntersectionGeometry(Terrain terrain) { ShapeData shapeData = new ShapeData(null, this); Matrix rotationMatrix = this.getRotation() != null ? this.computeRotationMatrix(terrain.getGlobe()) : null; shapeData.setReferencePoint(this.computeReferencePoint(terrain, rotationMatrix)); - if (shapeData.getReferencePoint() == null) + if (shapeData.getReferencePoint() == null) { return null; + } // Compute the boundary vertices first. this.createVertices(terrain, shapeData, false); @@ -1401,18 +1364,19 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) } protected void intersect(Line line, ShapeData shapeData, List intersections) - throws InterruptedException - { - if (shapeData.cb.getPrims() == null) + throws InterruptedException { + if (shapeData.cb.getPrims() == null) { return; + } IntBuffer ib = shapeData.interiorIndicesBuffer; ib.rewind(); List ti = Triangle.intersectTriangleTypes(line, shapeData.coordBuffer, ib, - GL.GL_TRIANGLES); + GL.GL_TRIANGLES); - if (ti != null && ti.size() > 0) + if (ti != null && ti.size() > 0) { intersections.addAll(ti); + } } /** @@ -1425,32 +1389,33 @@ protected void intersect(Line line, ShapeData shapeData, List inte * * @throws java.lang.IllegalArgumentException if the position is null. */ - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isOuterBoundaryValid()) + if (!this.isOuterBoundaryValid()) { return; + } Position oldPosition = this.getReferencePosition(); - if (oldPosition == null) + if (oldPosition == null) { return; + } List> newBoundaries = new ArrayList>(this.boundaries.size()); - for (List boundary : this.boundaries) - { - if (boundary == null || boundary.size() == 0) + for (List boundary : this.boundaries) { + if (boundary == null || boundary.size() == 0) { continue; + } List newList = Position.computeShiftedPositions(oldPosition, position, boundary); - if (newList != null) + if (newList != null) { newBoundaries.add(newList); + } } this.boundaries = newBoundaries; @@ -1464,44 +1429,44 @@ public void moveTo(Position position) * Note that this method overwrites the boundary locations lists, and therefore no longer refer to the originally * specified boundary lists. * - * @param globe the globe on which to move this shape. + * @param globe the globe on which to move this shape. * @param position the new position of the shape's reference position. * * @throws java.lang.IllegalArgumentException if the globe or position is null. */ - public void moveTo(Globe globe, Position position) - { - if (globe == null) - { + public void moveTo(Globe globe, Position position) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (position == null) - { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isOuterBoundaryValid()) + if (!this.isOuterBoundaryValid()) { return; + } Position oldPosition = this.getReferencePosition(); - if (oldPosition == null) + if (oldPosition == null) { return; + } List> newBoundaries = new ArrayList>(this.boundaries.size()); - for (List boundary : this.boundaries) - { - if (boundary == null || boundary.size() == 0) + for (List boundary : this.boundaries) { + if (boundary == null || boundary.size() == 0) { continue; + } List newList = Position.computeShiftedPositions(globe, oldPosition, position, boundary); - if (newList != null) + if (newList != null) { newBoundaries.add(newList); + } } this.boundaries = newBoundaries; @@ -1509,9 +1474,10 @@ public void moveTo(Globe globe, Position position) this.reset(); } - /** {@inheritDoc} */ - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + /** + * {@inheritDoc} + */ + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { // Write geometry xmlWriter.writeStartElement("Polygon"); @@ -1534,24 +1500,20 @@ protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLS * * @param xmlWriter XML writer to receive the output. * - * @throws IOException If an exception occurs writing the XML stream. + * @throws IOException If an exception occurs writing the XML stream. * @throws XMLStreamException If an exception occurs writing the XML stream. */ - protected void writeKMLBoundaries(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void writeKMLBoundaries(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { // Outer boundary Iterable outerBoundary = this.getOuterBoundary(); - if (outerBoundary != null) - { + if (outerBoundary != null) { xmlWriter.writeStartElement("outerBoundaryIs"); exportBoundaryAsLinearRing(xmlWriter, outerBoundary); xmlWriter.writeEndElement(); // outerBoundaryIs } // Inner boundaries. Skip outer boundary, we already dealt with it above - - for (int i = 1; i < this.boundaries.size(); i++) - { + for (int i = 1; i < this.boundaries.size(); i++) { xmlWriter.writeStartElement("innerBoundaryIs"); exportBoundaryAsLinearRing(xmlWriter, this.boundaries.get(i)); xmlWriter.writeEndElement(); // innerBoundaryIs @@ -1563,29 +1525,24 @@ protected void writeKMLBoundaries(XMLStreamWriter xmlWriter) throws IOException, * type originally specified. * * @param xmlWriter the XML writer. - * @param boundary the boundary to write. + * @param boundary the boundary to write. * * @throws XMLStreamException if an error occurs during writing. */ protected void exportBoundaryAsLinearRing(XMLStreamWriter xmlWriter, Iterable boundary) - throws XMLStreamException - { + throws XMLStreamException { xmlWriter.writeStartElement("LinearRing"); xmlWriter.writeStartElement("coordinates"); - for (LatLon location : boundary) - { - if (location instanceof Position) - { + for (LatLon location : boundary) { + if (location instanceof Position) { xmlWriter.writeCharacters(String.format(Locale.US, "%f,%f,%f ", - location.getLongitude().getDegrees(), - location.getLatitude().getDegrees(), - ((Position) location).getAltitude())); - } - else - { + location.getLongitude().getDegrees(), + location.getLatitude().getDegrees(), + ((Position) location).getAltitude())); + } else { xmlWriter.writeCharacters(String.format(Locale.US, "%f,%f ", - location.getLongitude().getDegrees(), - location.getLatitude().getDegrees())); + location.getLongitude().getDegrees(), + location.getLatitude().getDegrees())); } } xmlWriter.writeEndElement(); // coordinates diff --git a/src/gov/nasa/worldwind/render/PolygonTessellator.java b/src/gov/nasa/worldwind/render/PolygonTessellator.java index 688ab603ca..34ac2a4eed 100644 --- a/src/gov/nasa/worldwind/render/PolygonTessellator.java +++ b/src/gov/nasa/worldwind/render/PolygonTessellator.java @@ -12,37 +12,32 @@ * @author dcollins * @version $Id: PolygonTessellator.java 2067 2014-06-20 20:59:29Z dcollins $ */ -public class PolygonTessellator -{ - protected static class TessCallbackAdapter extends GLUtessellatorCallbackAdapter - { +public class PolygonTessellator { + + protected static class TessCallbackAdapter extends GLUtessellatorCallbackAdapter { + @Override - public void beginData(int type, Object userData) - { + public void beginData(int type, Object userData) { ((PolygonTessellator) userData).tessBegin(type); } @Override - public void edgeFlagData(boolean boundaryEdge, Object userData) - { + public void edgeFlagData(boolean boundaryEdge, Object userData) { ((PolygonTessellator) userData).tessEdgeFlag(boundaryEdge); } @Override - public void vertexData(Object vertexData, Object userData) - { + public void vertexData(Object vertexData, Object userData) { ((PolygonTessellator) userData).tessVertex(vertexData); } @Override - public void endData(Object userData) - { + public void endData(Object userData) { ((PolygonTessellator) userData).tessEnd(); } @Override - public void combineData(double[] coords, Object[] vertexData, float[] weight, Object[] outData, Object userData) - { + public void combineData(double[] coords, Object[] vertexData, float[] weight, Object[] outData, Object userData) { ((PolygonTessellator) userData).tessCombine(coords, vertexData, weight, outData); } } @@ -54,8 +49,7 @@ public void combineData(double[] coords, Object[] vertexData, float[] weight, Ob protected boolean isBoundaryEdge; protected double[] vertexCoord = new double[3]; - public PolygonTessellator() - { + public PolygonTessellator() { this.tess = GLU.gluNewTess(); TessCallbackAdapter callback = new TessCallbackAdapter(); GLU.gluTessCallback(this.tess, GLU.GLU_TESS_BEGIN_DATA, callback); @@ -68,63 +62,59 @@ public PolygonTessellator() this.boundaryIndices = IntBuffer.allocate(10); } - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; } - public IntBuffer getInteriorIndices() - { + public IntBuffer getInteriorIndices() { return this.interiorIndices; } - public IntBuffer getBoundaryIndices() - { + public IntBuffer getBoundaryIndices() { return this.boundaryIndices; } - public void reset() - { - if (!this.enabled) + public void reset() { + if (!this.enabled) { return; + } this.interiorIndices.clear(); this.boundaryIndices.clear(); } - public void setPolygonNormal(double x, double y, double z) - { - if (!this.enabled) + public void setPolygonNormal(double x, double y, double z) { + if (!this.enabled) { return; + } GLU.gluTessNormal(this.tess, x, y, z); } - public void beginPolygon() - { - if (!this.enabled) + public void beginPolygon() { + if (!this.enabled) { return; + } GLU.gluTessBeginPolygon(this.tess, this); // Use this as the polygon user data to enable callbacks to this instance. } - public void beginContour() - { - if (!this.enabled) + public void beginContour() { + if (!this.enabled) { return; + } GLU.gluTessBeginContour(this.tess); } - public void addVertex(double x, double y, double z, int index) - { - if (!this.enabled) + public void addVertex(double x, double y, double z, int index) { + if (!this.enabled) { return; + } this.vertexCoord[0] = x; this.vertexCoord[1] = y; @@ -133,34 +123,31 @@ public void addVertex(double x, double y, double z, int index) GLU.gluTessVertex(this.tess, this.vertexCoord, 0, index); // Associate the vertex with its index in the vertex array. } - public void endContour() - { - if (!this.enabled) + public void endContour() { + if (!this.enabled) { return; + } GLU.gluTessEndContour(this.tess); } - public void endPolygon() - { - if (!this.enabled) + public void endPolygon() { + if (!this.enabled) { return; + } GLU.gluTessEndPolygon(this.tess); } - protected void tessBegin(int type) - { + protected void tessBegin(int type) { // Intentionally left blank. } - protected void tessEdgeFlag(boolean boundaryEdge) - { + protected void tessEdgeFlag(boolean boundaryEdge) { this.isBoundaryEdge = boundaryEdge; } - protected void tessVertex(Object vertexData) - { + protected void tessVertex(Object vertexData) { // Accumulate interior indices appropriate for use as GL_interiorIndices primitives. Based on the GLU tessellator // documentation we can assume that the tessellator is providing interiorIndices because it's configured with the // edgeFlag callback. @@ -169,17 +156,14 @@ protected void tessVertex(Object vertexData) // Accumulate outline indices appropriate for use as GL_boundaryIndices. The tessBoundaryEdge flag indicates whether or // not the triangle edge starting with the current vertex is a boundary edge. - if ((this.boundaryIndices.position() % 2) == 1) - { + if ((this.boundaryIndices.position() % 2) == 1) { this.boundaryIndices = this.addIndex(this.boundaryIndices, index); } - if (this.isBoundaryEdge) - { + if (this.isBoundaryEdge) { this.boundaryIndices = this.addIndex(this.boundaryIndices, index); int interiorCount = this.interiorIndices.position(); - if (interiorCount > 0 && (interiorCount % 3) == 0) - { + if (interiorCount > 0 && (interiorCount % 3) == 0) { int firstTriIndex = this.interiorIndices.get(interiorCount - 3); this.boundaryIndices = this.addIndex(this.boundaryIndices, firstTriIndex); } @@ -187,27 +171,21 @@ protected void tessVertex(Object vertexData) } - protected void tessEnd() - { + protected void tessEnd() { // Intentionally left blank. } - protected void tessCombine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) - { + protected void tessCombine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) { // TODO: Implement the combine callback to handle complex polygons. } - protected IntBuffer addIndex(IntBuffer buffer, int index) - { - if (!buffer.hasRemaining()) - { + protected IntBuffer addIndex(IntBuffer buffer, int index) { + if (!buffer.hasRemaining()) { int newCapacity = buffer.capacity() + buffer.capacity() / 2; // increase capacity by 50% IntBuffer newBuffer = IntBuffer.allocate(newCapacity); newBuffer.put((IntBuffer) buffer.flip()); return newBuffer.put(index); - } - else - { + } else { return buffer.put(index); } } diff --git a/src/gov/nasa/worldwind/render/Polyline.java b/src/gov/nasa/worldwind/render/Polyline.java index 807b1c52f9..97d87d1ae1 100644 --- a/src/gov/nasa/worldwind/render/Polyline.java +++ b/src/gov/nasa/worldwind/render/Polyline.java @@ -25,14 +25,14 @@ * @author tag * @version $Id: Polyline.java 2188 2014-07-30 15:01:16Z tgaskins $ * @deprecated Use {@link Path} instead. - *

          - * When drawn on a 2D globe, this shape uses either a {@link SurfacePolyline} or {@link SurfacePolygon} to - * represent itself. + *

          + * When drawn on a 2D globe, this shape uses either a {@link SurfacePolyline} or {@link SurfacePolygon} to represent + * itself. */ @Deprecated public class Polyline extends AVListImpl implements Renderable, OrderedRenderable, Movable, Restorable, - MeasurableLength, ExtentHolder, PreRenderable, Highlightable, Draggable -{ + MeasurableLength, ExtentHolder, PreRenderable, Highlightable, Draggable { + public final static int GREAT_CIRCLE = WorldWind.GREAT_CIRCLE; public final static int LINEAR = WorldWind.LINEAR; public final static int RHUMB_LINE = WorldWind.RHUMB_LINE; @@ -72,68 +72,60 @@ public class Polyline extends AVListImpl implements Renderable, OrderedRenderabl protected SurfaceShape surfaceShape; // Manage an extent for each globe the polyline's associated with. - protected static class ExtentInfo - { + protected static class ExtentInfo { + // The extent depends on the state of the globe used to compute it, and the vertical exaggeration. protected Extent extent; protected double verticalExaggeration; protected Globe globe; protected Object globeStateKey; - public ExtentInfo(Extent extent, DrawContext dc) - { + public ExtentInfo(Extent extent, DrawContext dc) { this.extent = extent; this.verticalExaggeration = dc.getVerticalExaggeration(); this.globe = dc.getGlobe(); this.globeStateKey = dc.getGlobe().getStateKey(dc); } - protected boolean isValid(DrawContext dc) - { + protected boolean isValid(DrawContext dc) { return this.verticalExaggeration == dc.getVerticalExaggeration() && this.globe == dc.getGlobe() - && globeStateKey.equals(dc.getGlobe().getStateKey(dc)); + && globeStateKey.equals(dc.getGlobe().getStateKey(dc)); } } protected HashMap extents = new HashMap(2); // usually only 1, but few at most - public Polyline() - { + public Polyline() { this.setPositions(null); this.measurer.setFollowTerrain(this.followTerrain); this.measurer.setPathType(this.pathType); } - public Polyline(Iterable positions) - { + public Polyline(Iterable positions) { this.setPositions(positions); this.measurer.setFollowTerrain(this.followTerrain); this.measurer.setPathType(this.pathType); } - public Polyline(Iterable positions, double elevation) - { + public Polyline(Iterable positions, double elevation) { this.setPositions(positions, elevation); this.measurer.setFollowTerrain(this.followTerrain); this.measurer.setPathType(this.pathType); } - private void reset() - { - if (this.currentSpans != null) + private void reset() { + if (this.currentSpans != null) { this.currentSpans.clear(); + } this.currentSpans = null; } - public Color getColor() - { + public Color getColor() { return color; } - public void setColor(Color color) - { - if (color == null) - { + public void setColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -141,8 +133,7 @@ public void setColor(Color color) this.color = color; - if (this.surfaceShape != null) - { + if (this.surfaceShape != null) { ShapeAttributes attrs = this.surfaceShape.getAttributes(); attrs.setOutlineMaterial(new Material(this.color)); attrs.setOutlineOpacity(this.color.getAlpha() / 255.0); @@ -152,15 +143,12 @@ public void setColor(Color color) } - public int getAntiAliasHint() - { + public int getAntiAliasHint() { return antiAliasHint; } - public void setAntiAliasHint(int hint) - { - if (!(hint == ANTIALIAS_DONT_CARE || hint == ANTIALIAS_FASTEST || hint == ANTIALIAS_NICEST)) - { + public void setAntiAliasHint(int hint) { + if (!(hint == ANTIALIAS_DONT_CARE || hint == ANTIALIAS_FASTEST || hint == ANTIALIAS_NICEST)) { String msg = Logging.getMessage("generic.InvalidHint"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -169,19 +157,17 @@ public void setAntiAliasHint(int hint) this.antiAliasHint = hint; } - public boolean isFilled() - { + public boolean isFilled() { return filled; } - public void setFilled(boolean filled) - { - if (this.surfaceShape != null && filled != this.filled) - { - if (filled) + public void setFilled(boolean filled) { + if (this.surfaceShape != null && filled != this.filled) { + if (filled) { this.surfaceShape = new SurfacePolygon(this.getPositions()); - else + } else { this.surfaceShape = new SurfacePolyline(this.getPositions()); + } this.setSurfaceShapeAttributes(); } @@ -189,15 +175,13 @@ public void setFilled(boolean filled) this.filled = filled; } - public int getPathType() - { + public int getPathType() { return pathType; } - public String getPathTypeString() - { + public String getPathTypeString() { return this.getPathType() == GREAT_CIRCLE ? AVKey.GREAT_CIRCLE - : this.getPathType() == RHUMB_LINE ? AVKey.RHUMB_LINE : AVKey.LINEAR; + : this.getPathType() == RHUMB_LINE ? AVKey.RHUMB_LINE : AVKey.LINEAR; } /** @@ -209,14 +193,14 @@ public String getPathTypeString() * * @see Path Types */ - public void setPathType(int pathType) - { + public void setPathType(int pathType) { this.reset(); this.pathType = pathType; this.measurer.setPathType(pathType); - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.surfaceShape.setPathType(this.pathType == GREAT_CIRCLE ? AVKey.GREAT_CIRCLE - : pathType == RHUMB_LINE ? AVKey.RHUMB_LINE : AVKey.LINEAR); + : pathType == RHUMB_LINE ? AVKey.RHUMB_LINE : AVKey.LINEAR); + } } /** @@ -229,21 +213,18 @@ public void setPathType(int pathType) * * @see Path Types */ - public void setPathType(String pathType) - { - if (pathType == null) - { + public void setPathType(String pathType) { + if (pathType == null) { String msg = Logging.getMessage("nullValue.PathTypeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.setPathType(pathType.equals(AVKey.GREAT_CIRCLE) ? GREAT_CIRCLE - : pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME) ? RHUMB_LINE : LINEAR); + : pathType.equals(AVKey.RHUMB_LINE) || pathType.equals(AVKey.LOXODROME) ? RHUMB_LINE : LINEAR); } - public boolean isFollowTerrain() - { + public boolean isFollowTerrain() { return followTerrain; } @@ -255,16 +236,14 @@ public boolean isFollowTerrain() * * @param followTerrain true to follow the terrain, otherwise false. */ - public void setFollowTerrain(boolean followTerrain) - { + public void setFollowTerrain(boolean followTerrain) { this.reset(); this.followTerrain = followTerrain; this.measurer.setFollowTerrain(followTerrain); this.extents.clear(); } - public double getOffset() - { + public double getOffset() { return offset; } @@ -274,15 +253,13 @@ public double getOffset() * * @param offset the path pffset in meters. */ - public void setOffset(double offset) - { + public void setOffset(double offset) { this.reset(); this.offset = offset; this.extents.clear(); } - public double getTerrainConformance() - { + public double getTerrainConformance() { return terrainConformance; } @@ -293,22 +270,20 @@ public double getTerrainConformance() * * @param terrainConformance the path conformance in pixels. */ - public void setTerrainConformance(double terrainConformance) - { + public void setTerrainConformance(double terrainConformance) { this.terrainConformance = terrainConformance; } - public double getLineWidth() - { + public double getLineWidth() { return this.lineWidth; } - public void setLineWidth(double lineWidth) - { + public void setLineWidth(double lineWidth) { this.lineWidth = lineWidth; - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.surfaceShape.getAttributes().setOutlineWidth(this.getLineWidth()); + } } /** @@ -318,25 +293,21 @@ public void setLineWidth(double lineWidth) * * @return the path's length in meters. */ - public double getLength() - { + public double getLength() { Iterator infos = this.extents.values().iterator(); return infos.hasNext() ? this.measurer.getLength(infos.next().globe) : 0; } - public double getLength(Globe globe) - { + public double getLength(Globe globe) { // The length measurer will throw an exception and log the error if globe is null return this.measurer.getLength(globe); } - public LengthMeasurer getMeasurer() - { + public LengthMeasurer getMeasurer() { return this.measurer; } - public short getStipplePattern() - { + public short getStipplePattern() { return stipplePattern; } @@ -347,16 +318,15 @@ public short getStipplePattern() * * @param stipplePattern the stipple pattern. */ - public void setStipplePattern(short stipplePattern) - { + public void setStipplePattern(short stipplePattern) { this.stipplePattern = stipplePattern; - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.surfaceShape.getAttributes().setOutlineStipplePattern(this.stipplePattern); + } } - public int getStippleFactor() - { + public int getStippleFactor() { return stippleFactor; } @@ -367,16 +337,15 @@ public int getStippleFactor() * * @param stippleFactor the stipple factor. */ - public void setStippleFactor(int stippleFactor) - { + public void setStippleFactor(int stippleFactor) { this.stippleFactor = stippleFactor; - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.surfaceShape.getAttributes().setOutlineStippleFactor(this.stippleFactor); + } } - public int getNumSubsegments() - { + public int getNumSubsegments() { return numSubsegments; } @@ -386,31 +355,25 @@ public int getNumSubsegments() * * @param numSubsegments the number of intermediate subsegments. */ - public void setNumSubsegments(int numSubsegments) - { + public void setNumSubsegments(int numSubsegments) { this.reset(); this.numSubsegments = numSubsegments; } - public boolean isHighlighted() - { + public boolean isHighlighted() { return highlighted; } - public void setHighlighted(boolean highlighted) - { + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } - public Color getHighlightColor() - { + public Color getHighlightColor() { return this.highlightColor; } - public void setHighlightColor(Color highlightColor) - { - if (highlightColor == null) - { + public void setHighlightColor(Color highlightColor) { + if (highlightColor == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -418,8 +381,9 @@ public void setHighlightColor(Color highlightColor) this.highlightColor = highlightColor; - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.surfaceShape.getHighlightAttributes().setOutlineMaterial(new Material(this.highlightColor)); + } } /** @@ -427,25 +391,22 @@ public void setHighlightColor(Color highlightColor) * * @param inPositions the path positions. */ - public void setPositions(Iterable inPositions) - { + public void setPositions(Iterable inPositions) { this.reset(); this.positions = new ArrayList(); this.extents.clear(); - if (inPositions != null) - { - for (Position position : inPositions) - { + if (inPositions != null) { + for (Position position : inPositions) { this.positions.add(position); } this.measurer.setPositions(this.positions); - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.setSurfaceShapeLocations(); + } } - if ((this.filled && this.positions.size() < 3)) - { + if ((this.filled && this.positions.size() < 3)) { String msg = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -456,45 +417,39 @@ public void setPositions(Iterable inPositions) * Sets the paths positions as latitude and longitude values at a constant altitude. * * @param inPositions the latitudes and longitudes of the positions. - * @param altitude the elevation to assign each position. + * @param altitude the elevation to assign each position. */ - public void setPositions(Iterable inPositions, double altitude) - { + public void setPositions(Iterable inPositions, double altitude) { this.reset(); this.positions = new ArrayList(); this.extents.clear(); - if (inPositions != null) - { - for (LatLon position : inPositions) - { + if (inPositions != null) { + for (LatLon position : inPositions) { this.positions.add(new Position(position, altitude)); } this.measurer.setPositions(this.positions); - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.setSurfaceShapeLocations(); + } } - if (this.filled && this.positions.size() < 3) - { + if (this.filled && this.positions.size() < 3) { String msg = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } } - public Iterable getPositions() - { + public Iterable getPositions() { return this.positions; } - public boolean isClosed() - { + public boolean isClosed() { return closed; } - public void setClosed(boolean closed) - { + public void setClosed(boolean closed) { this.closed = closed; } @@ -504,10 +459,9 @@ public void setClosed(boolean closed) * picking. * * @return the object used as the pickable object returned during picking, or null to indicate that the Polyline is - * returned during picking. + * returned during picking. */ - public Object getDelegateOwner() - { + public Object getDelegateOwner() { return this.delegateOwner; } @@ -518,8 +472,7 @@ public Object getDelegateOwner() * * @param owner the object to use as the pickable object returned during picking, or null to return the Polyline. */ - public void setDelegateOwner(Object owner) - { + public void setDelegateOwner(Object owner) { this.delegateOwner = owner; } @@ -528,17 +481,15 @@ public void setDelegateOwner(Object owner) * a specified {@link gov.nasa.worldwind.globes.Globe} and vertical exaggeration (see {@link * gov.nasa.worldwind.SceneController#getVerticalExaggeration()}. * - * @param globe the Globe this Polyline is related to. + * @param globe the Globe this Polyline is related to. * @param verticalExaggeration the vertical exaggeration to apply. * * @return this Polyline's Extent in model coordinates. * * @throws IllegalArgumentException if the Globe is null. */ - public Extent getExtent(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + public Extent getExtent(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -560,81 +511,68 @@ public Extent getExtent(Globe globe, double verticalExaggeration) * * @throws IllegalArgumentException if the DrawContext is null, or if the Globe held by the DrawContext is null. */ - public Extent getExtent(DrawContext dc) - { - if (dc == null) - { + public Extent getExtent(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } ExtentInfo extentInfo = this.extents.get(dc.getGlobe()); - if (extentInfo != null && extentInfo.isValid(dc)) - { + if (extentInfo != null && extentInfo.isValid(dc)) { return extentInfo.extent; - } - else - { + } else { extentInfo = new ExtentInfo(this.computeExtent(dc), dc); this.extents.put(dc.getGlobe(), extentInfo); return extentInfo.extent; } } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { Sector sector = Sector.boundingSector(this.getPositions()); double[] minAndMaxElevations; - if (this.isFollowTerrain()) - { + if (this.isFollowTerrain()) { minAndMaxElevations = globe.getMinAndMaxElevations(sector); - } - else - { + } else { minAndMaxElevations = computeElevationExtremes(this.getPositions()); } minAndMaxElevations[0] += this.getOffset(); minAndMaxElevations[1] += this.getOffset(); return Sector.computeBoundingBox(globe, verticalExaggeration, sector, minAndMaxElevations[0], - minAndMaxElevations[1]); + minAndMaxElevations[1]); } - protected Extent computeExtent(DrawContext dc) - { + protected Extent computeExtent(DrawContext dc) { return this.computeExtent(dc.getGlobe(), dc.getVerticalExaggeration()); } - protected static double[] computeElevationExtremes(Iterable positions) - { - double[] extremes = new double[] {Double.MAX_VALUE, -Double.MAX_VALUE}; - for (Position pos : positions) - { - if (extremes[0] > pos.getElevation()) + protected static double[] computeElevationExtremes(Iterable positions) { + double[] extremes = new double[]{Double.MAX_VALUE, -Double.MAX_VALUE}; + for (Position pos : positions) { + if (extremes[0] > pos.getElevation()) { extremes[0] = pos.getElevation(); // min - if (extremes[1] < pos.getElevation()) + } + if (extremes[1] < pos.getElevation()) { extremes[1] = pos.getElevation(); // max + } } return extremes; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - protected void setSurfaceShapeAttributes() - { + protected void setSurfaceShapeAttributes() { ShapeAttributes attrs = new BasicShapeAttributes(); attrs.setOutlineMaterial(new Material(this.color)); attrs.setOutlineOpacity(this.color.getAlpha() / 255.0); @@ -651,24 +589,20 @@ protected void setSurfaceShapeAttributes() this.surfaceShape.setHighlightAttributes(attrs); } - protected void setSurfaceShapeLocations() - { + protected void setSurfaceShapeLocations() { Iterable locations; - if (!this.isClosed()) - { + if (!this.isClosed()) { locations = this.getPositions(); - } - else - { + } else { ArrayList temp = new ArrayList(); Position firstPosition = null; - for (Position pos : this.getPositions()) - { + for (Position pos : this.getPositions()) { temp.add(pos); - if (firstPosition == null) + if (firstPosition == null) { firstPosition = pos; + } } temp.add(firstPosition); @@ -676,27 +610,26 @@ protected void setSurfaceShapeLocations() locations = temp; } - if (this.isFilled()) + if (this.isFilled()) { ((SurfacePolygon) this.surfaceShape).setLocations(locations); - else + } else { ((SurfacePolyline) this.surfaceShape).setLocations(locations); + } } - public void preRender(DrawContext dc) - { - if (dc.is2DGlobe()) - { - if (this.surfaceShape == null) - { - if (this.isFilled()) + public void preRender(DrawContext dc) { + if (dc.is2DGlobe()) { + if (this.surfaceShape == null) { + if (this.isFilled()) { this.surfaceShape = new SurfacePolygon(); - else + } else { this.surfaceShape = new SurfacePolyline(); + } this.setSurfaceShapeLocations(); this.setSurfaceShapeAttributes(); this.surfaceShape.setPathType(this.pathType == GREAT_CIRCLE ? AVKey.GREAT_CIRCLE - : pathType == RHUMB_LINE ? AVKey.RHUMB_LINE : AVKey.LINEAR); + : pathType == RHUMB_LINE ? AVKey.RHUMB_LINE : AVKey.LINEAR); } this.surfaceShape.setHighlighted(this.isHighlighted()); @@ -707,42 +640,36 @@ public void preRender(DrawContext dc) } } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { // This method is called only when ordered renderables are being drawn. // Arg checked within call to render. this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.render(dc); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { // This render method is called three times during frame generation. It's first called as a {@link Renderable} // during Renderable picking. It's called again during normal rendering. And it's called a third // time as an OrderedRenderable. The first two calls determine whether to add the polyline to the ordered // renderable list during pick and render. The third call just draws the ordered renderable. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc.getSurfaceGeometry() == null) + if (dc.getSurfaceGeometry() == null) { return; + } - if (dc.is2DGlobe() && this.surfaceShape != null) - { + if (dc.is2DGlobe() && this.surfaceShape != null) { this.surfaceShape.render(dc); return; } @@ -752,31 +679,27 @@ public void render(DrawContext dc) /** * If the scene controller is rendering ordered renderables, this method draws this placemark's image as an ordered - * renderable. Otherwise the method determines whether this instance should be added to the ordered renderable - * list. + * renderable. Otherwise the method determines whether this instance should be added to the ordered renderable list. *

          * The Cartesian and screen points of the placemark are computed during the first call per frame and re-used in * subsequent calls of that frame. * * @param dc the current draw context. */ - protected void draw(DrawContext dc) - { - if (dc.isOrderedRenderingMode()) - { + protected void draw(DrawContext dc) { + if (dc.isOrderedRenderingMode()) { this.drawOrderedRenderable(dc); return; } // The rest of the code in this method determines whether to queue an ordered renderable for the polyline. - - if (this.positions.size() < 2) + if (this.positions.size() < 2) { return; + } // vertices potentially computed every frame to follow terrain changes if (this.currentSpans == null || (this.followTerrain && this.geomGenTimeStamp != dc.getFrameTimeStamp()) - || this.geomGenVE != dc.getVerticalExaggeration()) - { + || this.geomGenVE != dc.getVerticalExaggeration()) { // Reference center must be computed prior to computing vertices. this.computeReferenceCenter(dc); this.eyeDistance = this.referenceCenterPoint.distanceTo3(dc.getView().getEyePoint()); @@ -785,27 +708,27 @@ protected void draw(DrawContext dc) this.geomGenVE = dc.getVerticalExaggeration(); } - if (this.currentSpans == null || this.currentSpans.size() < 1) + if (this.currentSpans == null || this.currentSpans.size() < 1) { return; + } - if (this.intersectsFrustum(dc)) - { - if (dc.isPickingMode()) + if (this.intersectsFrustum(dc)) { + if (dc.isPickingMode()) { this.pickLayer = dc.getCurrentLayer(); + } dc.addOrderedRenderable(this); // add the ordered renderable } } - protected void drawOrderedRenderable(DrawContext dc) - { + protected void drawOrderedRenderable(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int attrBits = GL2.GL_HINT_BIT | GL2.GL_CURRENT_BIT | GL2.GL_LINE_BIT; - if (!dc.isPickingMode()) - { - if (this.color.getAlpha() != 255) + if (!dc.isPickingMode()) { + if (this.color.getAlpha() != 255) { attrBits |= GL.GL_COLOR_BUFFER_BIT; + } } gl.glPushAttrib(attrBits); @@ -813,20 +736,15 @@ protected void drawOrderedRenderable(DrawContext dc) boolean projectionOffsetPushed = false; // keep track for error recovery - try - { - if (!dc.isPickingMode()) - { - if (this.color.getAlpha() != 255) - { + try { + if (!dc.isPickingMode()) { + if (this.color.getAlpha() != 255) { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); } gl.glColor4ub((byte) this.color.getRed(), (byte) this.color.getGreen(), - (byte) this.color.getBlue(), (byte) this.color.getAlpha()); - } - else - { + (byte) this.color.getBlue(), (byte) this.color.getAlpha()); + } else { // We cannot depend on the layer to set a pick color for us because this Polyline is picked during ordered // rendering. Therefore we set the pick color ourselves. Color pickColor = dc.getUniquePickColor(); @@ -835,87 +753,81 @@ protected void drawOrderedRenderable(DrawContext dc) gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue()); } - if (this.stippleFactor > 0) - { + if (this.stippleFactor > 0) { gl.glEnable(GL2.GL_LINE_STIPPLE); gl.glLineStipple(this.stippleFactor, this.stipplePattern); - } - else - { + } else { gl.glDisable(GL2.GL_LINE_STIPPLE); } int hintAttr = GL2.GL_LINE_SMOOTH_HINT; - if (this.filled) + if (this.filled) { hintAttr = GL2.GL_POLYGON_SMOOTH_HINT; + } gl.glHint(hintAttr, this.antiAliasHint); int primType = GL2.GL_LINE_STRIP; - if (this.filled) + if (this.filled) { primType = GL2.GL_POLYGON; + } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { gl.glLineWidth((float) this.getLineWidth() + 8); - else + } else { gl.glLineWidth((float) this.getLineWidth()); + } - if (this.followTerrain) - { + if (this.followTerrain) { dc.pushProjectionOffest(0.99); projectionOffsetPushed = true; } - if (this.currentSpans == null) + if (this.currentSpans == null) { return; + } - for (List span : this.currentSpans) - { - if (span == null) + for (List span : this.currentSpans) { + if (span == null) { continue; + } // Since segments can very often be very short -- two vertices -- use explicit rendering. The // overhead of batched rendering, e.g., gl.glDrawArrays, is too high because it requires copying // the vertices into a DoubleBuffer, and DoubleBuffer creation and access performs relatively poorly. gl.glBegin(primType); - for (Vec4 p : span) - { + for (Vec4 p : span) { gl.glVertex3d(p.x, p.y, p.z); } gl.glEnd(); } - if (this.isHighlighted()) - { - if (!dc.isPickingMode()) - { - if (this.highlightColor.getAlpha() != 255) - { + if (this.isHighlighted()) { + if (!dc.isPickingMode()) { + if (this.highlightColor.getAlpha() != 255) { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); } gl.glColor4ub((byte) this.highlightColor.getRed(), (byte) this.highlightColor.getGreen(), - (byte) this.highlightColor.getBlue(), (byte) this.highlightColor.getAlpha()); + (byte) this.highlightColor.getBlue(), (byte) this.highlightColor.getAlpha()); gl.glLineWidth((float) this.getLineWidth() + 2); - for (List span : this.currentSpans) - { - if (span == null) + for (List span : this.currentSpans) { + if (span == null) { continue; + } gl.glBegin(primType); - for (Vec4 p : span) - { + for (Vec4 p : span) { gl.glVertex3d(p.x, p.y, p.z); } gl.glEnd(); } } } - } - finally - { - if (projectionOffsetPushed) + } finally { + if (projectionOffsetPushed) { dc.popProjectionOffest(); + } gl.glPopAttrib(); dc.getView().popReferenceCenter(dc); @@ -929,44 +841,44 @@ protected void drawOrderedRenderable(DrawContext dc) * * @return true if the shape is visible, otherwise false. */ - protected boolean intersectsFrustum(DrawContext dc) - { + protected boolean intersectsFrustum(DrawContext dc) { Extent extent = this.getExtent(dc); - if (extent == null) + if (extent == null) { return true; // don't know the visibility, shape hasn't been computed yet - - if (dc.isPickingMode()) + } + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(extent); + } return dc.getView().getFrustumInModelCoordinates().intersects(extent); } - protected void makeVertices(DrawContext dc) - { - if (this.currentSpans == null) + protected void makeVertices(DrawContext dc) { + if (this.currentSpans == null) { this.currentSpans = new ArrayList>(); - else + } else { this.currentSpans.clear(); + } - if (this.positions.size() < 1) + if (this.positions.size() < 1) { return; + } Position posA = this.positions.get(0); Vec4 ptA = this.computePoint(dc, posA, true); - for (int i = 1; i <= this.positions.size(); i++) - { + for (int i = 1; i <= this.positions.size(); i++) { Position posB; - if (i < this.positions.size()) + if (i < this.positions.size()) { posB = this.positions.get(i); - else if (this.closed) + } else if (this.closed) { posB = this.positions.get(0); - else + } else { break; + } Vec4 ptB = this.computePoint(dc, posB, true); - if (this.followTerrain && !this.isSegmentVisible(dc, posA, posB, ptA, ptB)) - { + if (this.followTerrain && !this.isSegmentVisible(dc, posA, posB, ptA, ptB)) { posA = posB; ptA = ptB; continue; @@ -975,135 +887,123 @@ else if (this.closed) ArrayList span; span = this.makeSegment(dc, posA, posB, ptA, ptB); - if (span != null) + if (span != null) { this.addSpan(span); + } posA = posB; ptA = ptB; } } - protected void addSpan(ArrayList span) - { - if (span != null && span.size() > 0) + protected void addSpan(ArrayList span) { + if (span != null && span.size() > 0) { this.currentSpans.add(span); + } } - protected boolean isSegmentVisible(DrawContext dc, Position posA, Position posB, Vec4 ptA, Vec4 ptB) - { + protected boolean isSegmentVisible(DrawContext dc, Position posA, Position posB, Vec4 ptA, Vec4 ptB) { Frustum f = dc.getView().getFrustumInModelCoordinates(); - if (f.contains(ptA)) + if (f.contains(ptA)) { return true; + } - if (f.contains(ptB)) + if (f.contains(ptB)) { return true; + } - if (ptA.equals(ptB)) + if (ptA.equals(ptB)) { return false; + } Position posC = Position.interpolateRhumb(0.5, posA, posB); Vec4 ptC = this.computePoint(dc, posC, true); - if (f.contains(ptC)) + if (f.contains(ptC)) { return true; + } double r = Line.distanceToSegment(ptA, ptB, ptC); Cylinder cyl = new Cylinder(ptA, ptB, r == 0 ? 1 : r); return cyl.intersects(dc.getView().getFrustumInModelCoordinates()); } - protected Vec4 computePoint(DrawContext dc, Position pos, boolean applyOffset) - { - if (this.followTerrain) - { + protected Vec4 computePoint(DrawContext dc, Position pos, boolean applyOffset) { + if (this.followTerrain) { double height = !applyOffset ? 0 : this.offset; // computeTerrainPoint will apply vertical exaggeration return dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), height); - } - else - { + } else { double height = pos.getElevation() + (applyOffset ? this.offset : 0); return dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), - height * dc.getVerticalExaggeration()); + height * dc.getVerticalExaggeration()); } } - protected double computeSegmentLength(DrawContext dc, Position posA, Position posB) - { + protected double computeSegmentLength(DrawContext dc, Position posA, Position posB) { LatLon llA = new LatLon(posA.getLatitude(), posA.getLongitude()); LatLon llB = new LatLon(posB.getLatitude(), posB.getLongitude()); Angle ang = LatLon.greatCircleDistance(llA, llB); - if (this.followTerrain) - { + if (this.followTerrain) { return ang.radians * (dc.getGlobe().getRadius() + this.offset * dc.getVerticalExaggeration()); - } - else - { + } else { double height = this.offset + 0.5 * (posA.getElevation() + posB.getElevation()); return ang.radians * (dc.getGlobe().getRadius() + height * dc.getVerticalExaggeration()); } } - protected ArrayList makeSegment(DrawContext dc, Position posA, Position posB, Vec4 ptA, Vec4 ptB) - { + protected ArrayList makeSegment(DrawContext dc, Position posA, Position posB, Vec4 ptA, Vec4 ptB) { ArrayList span = null; double arcLength = this.computeSegmentLength(dc, posA, posB); if (arcLength <= 0) // points differing only in altitude { span = this.addPointToSpan(ptA, span); - if (!ptA.equals(ptB)) + if (!ptA.equals(ptB)) { span = this.addPointToSpan(ptB, span); + } return span; } // Variables for great circle and rhumb computation. Angle segmentAzimuth = null; Angle segmentDistance = null; - for (double s = 0, p = 0; s < 1; ) - { - if (this.followTerrain) + for (double s = 0, p = 0; s < 1;) { + if (this.followTerrain) { p += this.terrainConformance * dc.getView().computePixelSizeAtDistance( - ptA.distanceTo3(dc.getView().getEyePoint())); - else + ptA.distanceTo3(dc.getView().getEyePoint())); + } else { p += arcLength / this.numSubsegments; + } s = p / arcLength; Position pos; - if (s >= 1) - { + if (s >= 1) { pos = posB; - } - else if (this.pathType == LINEAR) - { - if (segmentAzimuth == null) - { + } else if (this.pathType == LINEAR) { + if (segmentAzimuth == null) { segmentAzimuth = LatLon.linearAzimuth(posA, posB); segmentDistance = LatLon.linearDistance(posA, posB); } Angle distance = Angle.fromRadians(s * segmentDistance.radians); LatLon latLon = LatLon.linearEndPosition(posA, segmentAzimuth, distance); pos = new Position(latLon, (1 - s) * posA.getElevation() + s * posB.getElevation()); - } - else if (this.pathType - == RHUMB_LINE) // or LOXODROME (note that loxodrome is translated to RHUMB_LINE in setPathType) + } else if (this.pathType + == RHUMB_LINE) // or LOXODROME (note that loxodrome is translated to RHUMB_LINE in setPathType) { - if (segmentAzimuth == null) - { + if (segmentAzimuth == null) { segmentAzimuth = LatLon.rhumbAzimuth(posA, posB); segmentDistance = LatLon.rhumbDistance(posA, posB); } Angle distance = Angle.fromRadians(s * segmentDistance.radians); LatLon latLon = LatLon.rhumbEndPosition(posA, segmentAzimuth, distance); pos = new Position(latLon, (1 - s) * posA.getElevation() + s * posB.getElevation()); - } - else // GREAT_CIRCLE + } else // GREAT_CIRCLE { - if (segmentAzimuth == null) - { + if (segmentAzimuth == null) { segmentAzimuth = LatLon.greatCircleAzimuth(posA, posB); segmentDistance = LatLon.greatCircleDistance(posA, posB); } @@ -1122,8 +1022,7 @@ else if (this.pathType } @SuppressWarnings({"UnusedDeclaration"}) - protected ArrayList clipAndAdd(DrawContext dc, Vec4 ptA, Vec4 ptB, ArrayList span) - { + protected ArrayList clipAndAdd(DrawContext dc, Vec4 ptA, Vec4 ptB, ArrayList span) { // Line clipping appears to be useful only for long lines with few segments. It's costly otherwise. // TODO: Investigate trade-off of line clipping. // if (Line.clipToFrustum(ptA, ptB, dc.getView().getFrustumInModelCoordinates()) == null) @@ -1136,55 +1035,48 @@ protected ArrayList clipAndAdd(DrawContext dc, Vec4 ptA, Vec4 ptB, ArrayLi // return span; // } - if (span == null) + if (span == null) { span = this.addPointToSpan(ptA, span); + } return this.addPointToSpan(ptB, span); } - protected ArrayList addPointToSpan(Vec4 p, ArrayList span) - { - if (span == null) + protected ArrayList addPointToSpan(Vec4 p, ArrayList span) { + if (span == null) { span = new ArrayList(); + } span.add(p.subtract3(this.referenceCenterPoint)); return span; } - protected void computeReferenceCenter(DrawContext dc) - { + protected void computeReferenceCenter(DrawContext dc) { // The reference position is null if this Polyline has no positions. In this case computing the Polyline's // Cartesian reference point is meaningless because the Polyline has no geographic location. Therefore we exit // without updating the reference point. Position refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return; + } this.referenceCenterPoint = dc.computeTerrainPoint(refPos.getLatitude(), refPos.getLongitude(), - this.offset); + this.offset); } - public Position getReferencePosition() - { - if (this.positions.size() < 1) - { + public Position getReferencePosition() { + if (this.positions.size() < 1) { return null; - } - else if (this.positions.size() < 3) - { + } else if (this.positions.size() < 3) { return this.positions.get(0); - } - else - { + } else { return this.positions.get(this.positions.size() / 2); } } - public void move(Position delta) - { - if (delta == null) - { + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1195,16 +1087,15 @@ public void move(Position delta) // The reference position is null if this Polyline has no positions. In this case moving the Polyline by a // relative delta is meaningless because the Polyline has no geographic location. Therefore we fail softly by // exiting and doing nothing. - if (refPos == null) + if (refPos == null) { return; + } this.moveTo(refPos.add(delta)); } - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1218,13 +1109,13 @@ public void moveTo(Position position) // The reference position is null if this Polyline has no positions. In this case moving the Polyline to a new // reference position is meaningless because the Polyline has no geographic location. Therefore we fail softly // by exiting and doing nothing. - if (oldRef == null) + if (oldRef == null) { return; + } double elevDelta = position.getElevation() - oldRef.getElevation(); - for (int i = 0; i < this.positions.size(); i++) - { + for (int i = 0; i < this.positions.size(); i++) { Position pos = this.positions.get(i); Angle distance = LatLon.greatCircleDistance(oldRef, pos); @@ -1237,32 +1128,30 @@ public void moveTo(Position position) } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, this.isFollowTerrain() - ? WorldWind.RELATIVE_TO_GROUND : WorldWind.ABSOLUTE); + ? WorldWind.RELATIVE_TO_GROUND : WorldWind.ABSOLUTE); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } @@ -1271,50 +1160,45 @@ protected void doDrag(DragContext dragContext) * * @return XML state document string describing this Polyline. */ - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (rs == null) + if (rs == null) { return null; + } - if (this.color != null) - { + if (this.color != null) { String encodedColor = RestorableSupport.encodeColor(this.color); - if (encodedColor != null) + if (encodedColor != null) { rs.addStateValueAsString("color", encodedColor); + } } - if (this.highlightColor != null) - { + if (this.highlightColor != null) { String encodedColor = RestorableSupport.encodeColor(this.highlightColor); - if (encodedColor != null) + if (encodedColor != null) { rs.addStateValueAsString("highlightColor", encodedColor); + } } - if (this.positions != null) - { + if (this.positions != null) { // Create the base "positions" state object. RestorableSupport.StateObject positionsStateObj = rs.addStateObject("positions"); - if (positionsStateObj != null) - { - for (Position p : this.positions) - { + if (positionsStateObj != null) { + for (Position p : this.positions) { // Save each position only if all parts (latitude, longitude, and elevation) can be // saved. We will not save a partial iconPosition (for example, just the elevation). - if (p != null && p.getLatitude() != null && p.getLongitude() != null) - { + if (p != null && p.getLatitude() != null && p.getLongitude() != null) { // Create a nested "position" element underneath the base "positions". - RestorableSupport.StateObject pStateObj = - rs.addStateObject(positionsStateObj, "position"); - if (pStateObj != null) - { + RestorableSupport.StateObject pStateObj + = rs.addStateObject(positionsStateObj, "position"); + if (pStateObj != null) { rs.addStateValueAsDouble(pStateObj, "latitudeDegrees", - p.getLatitude().degrees); + p.getLatitude().degrees); rs.addStateValueAsDouble(pStateObj, "longitudeDegrees", - p.getLongitude().degrees); + p.getLongitude().degrees); rs.addStateValueAsDouble(pStateObj, "elevation", - p.getElevation()); + p.getElevation()); } } } @@ -1335,8 +1219,7 @@ public String getRestorableState() rs.addStateValueAsInteger("numSubsegments", this.numSubsegments); RestorableSupport.StateObject so = rs.addStateObject(null, "avlist"); - for (Map.Entry avp : this.getEntries()) - { + for (Map.Entry avp : this.getEntries()) { this.getRestorableStateForAVPair(avp.getKey(), avp.getValue() != null ? avp.getValue() : "", rs, so); } @@ -1352,24 +1235,19 @@ public String getRestorableState() * @param stateInXml an XML document String describing a Polyline. * * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not a well - * formed XML document String. + * formed XML document String. */ - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport restorableSupport; - try - { + try { restorableSupport = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -1377,42 +1255,39 @@ public void restoreState(String stateInXml) } String colorState = restorableSupport.getStateValueAsString("color"); - if (colorState != null) - { + if (colorState != null) { Color color = RestorableSupport.decodeColor(colorState); - if (color != null) + if (color != null) { setColor(color); + } } colorState = restorableSupport.getStateValueAsString("highlightColor"); - if (colorState != null) - { + if (colorState != null) { Color color = RestorableSupport.decodeColor(colorState); - if (color != null) + if (color != null) { setHighlightColor(color); + } } // Get the base "positions" state object. RestorableSupport.StateObject positionsStateObj = restorableSupport.getStateObject("positions"); - if (positionsStateObj != null) - { + if (positionsStateObj != null) { ArrayList newPositions = new ArrayList(); // Get the nested "position" states beneath the base "positions". - RestorableSupport.StateObject[] positionStateArray = - restorableSupport.getAllStateObjects(positionsStateObj, "position"); - if (positionStateArray != null && positionStateArray.length != 0) - { - for (RestorableSupport.StateObject pStateObj : positionStateArray) - { - if (pStateObj != null) - { + RestorableSupport.StateObject[] positionStateArray + = restorableSupport.getAllStateObjects(positionsStateObj, "position"); + if (positionStateArray != null && positionStateArray.length != 0) { + for (RestorableSupport.StateObject pStateObj : positionStateArray) { + if (pStateObj != null) { // Restore each position only if all parts are available. // We will not restore a partial position (for example, just the elevation). Double latitudeState = restorableSupport.getStateValueAsDouble(pStateObj, "latitudeDegrees"); Double longitudeState = restorableSupport.getStateValueAsDouble(pStateObj, "longitudeDegrees"); Double elevationState = restorableSupport.getStateValueAsDouble(pStateObj, "elevation"); - if (latitudeState != null && longitudeState != null && elevationState != null) + if (latitudeState != null && longitudeState != null && elevationState != null) { newPositions.add(Position.fromDegrees(latitudeState, longitudeState, elevationState)); + } } } } @@ -1423,63 +1298,73 @@ public void restoreState(String stateInXml) } Integer antiAliasHintState = restorableSupport.getStateValueAsInteger("antiAliasHint"); - if (antiAliasHintState != null) + if (antiAliasHintState != null) { setAntiAliasHint(antiAliasHintState); + } Boolean isFilledState = restorableSupport.getStateValueAsBoolean("filled"); - if (isFilledState != null) + if (isFilledState != null) { setFilled(isFilledState); + } Boolean isClosedState = restorableSupport.getStateValueAsBoolean("closed"); - if (isClosedState != null) + if (isClosedState != null) { setClosed(isClosedState); + } Boolean isHighlightedState = restorableSupport.getStateValueAsBoolean("highlighted"); - if (isHighlightedState != null) + if (isHighlightedState != null) { setHighlighted(isHighlightedState); + } Integer pathTypeState = restorableSupport.getStateValueAsInteger("pathType"); - if (pathTypeState != null) + if (pathTypeState != null) { setPathType(pathTypeState); + } Boolean isFollowTerrainState = restorableSupport.getStateValueAsBoolean("followTerrain"); - if (isFollowTerrainState != null) + if (isFollowTerrainState != null) { setFollowTerrain(isFollowTerrainState); + } Double offsetState = restorableSupport.getStateValueAsDouble("offset"); - if (offsetState != null) + if (offsetState != null) { setOffset(offsetState); + } Double terrainConformanceState = restorableSupport.getStateValueAsDouble("terrainConformance"); - if (terrainConformanceState != null) + if (terrainConformanceState != null) { setTerrainConformance(terrainConformanceState); + } Double lineWidthState = restorableSupport.getStateValueAsDouble("lineWidth"); - if (lineWidthState != null) + if (lineWidthState != null) { setLineWidth(lineWidthState); + } Integer stipplePatternState = restorableSupport.getStateValueAsInteger("stipplePattern"); - if (stipplePatternState != null) + if (stipplePatternState != null) { setStipplePattern(stipplePatternState.shortValue()); + } Integer stippleFactorState = restorableSupport.getStateValueAsInteger("stippleFactor"); - if (stippleFactorState != null) + if (stippleFactorState != null) { setStippleFactor(stippleFactorState); + } Integer numSubsegmentsState = restorableSupport.getStateValueAsInteger("numSubsegments"); - if (numSubsegmentsState != null) + if (numSubsegmentsState != null) { setNumSubsegments(numSubsegmentsState); + } RestorableSupport.StateObject so = restorableSupport.getStateObject(null, "avlist"); - if (so != null) - { + if (so != null) { RestorableSupport.StateObject[] avpairs = restorableSupport.getAllStateObjects(so, ""); - if (avpairs != null) - { - for (RestorableSupport.StateObject avp : avpairs) - { - if (avp != null) + if (avpairs != null) { + for (RestorableSupport.StateObject avp : avpairs) { + if (avp != null) { this.setValue(avp.getName(), avp.getValue()); + } } } } diff --git a/src/gov/nasa/worldwind/render/PolylineTessellator.java b/src/gov/nasa/worldwind/render/PolylineTessellator.java index 348642b8d5..2bc11b4af1 100644 --- a/src/gov/nasa/worldwind/render/PolylineTessellator.java +++ b/src/gov/nasa/worldwind/render/PolylineTessellator.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import java.nio.IntBuffer; @@ -12,40 +11,33 @@ * @author dcollins * @version $Id: PolylineTessellator.java 2290 2014-08-30 21:27:27Z dcollins $ */ -public class PolylineTessellator -{ +public class PolylineTessellator { + protected IntBuffer indices; protected int lastIndex = -1; - public PolylineTessellator() - { + public PolylineTessellator() { this.indices = IntBuffer.allocate(10); } - public IntBuffer getIndices() - { + public IntBuffer getIndices() { return this.indices; } - public void reset() - { + public void reset() { this.indices.clear(); } - public void beginPolyline() - { + public void beginPolyline() { this.lastIndex = -1; } - public void endPolyline() - { + public void endPolyline() { this.lastIndex = -1; } - public void addVertex(double x, double y, double z, int index) - { - if (this.lastIndex >= 0) - { + public void addVertex(double x, double y, double z, int index) { + if (this.lastIndex >= 0) { this.indices = this.addIndex(this.indices, this.lastIndex); this.indices = this.addIndex(this.indices, index); } @@ -53,17 +45,13 @@ public void addVertex(double x, double y, double z, int index) this.lastIndex = index; } - protected IntBuffer addIndex(IntBuffer buffer, int index) - { - if (!buffer.hasRemaining()) - { + protected IntBuffer addIndex(IntBuffer buffer, int index) { + if (!buffer.hasRemaining()) { int newCapacity = buffer.capacity() + buffer.capacity() / 2; // increase capacity by 50% IntBuffer newBuffer = IntBuffer.allocate(newCapacity); newBuffer.put((IntBuffer) buffer.flip()); return newBuffer.put(index); - } - else - { + } else { return buffer.put(index); } } diff --git a/src/gov/nasa/worldwind/render/PreRenderable.java b/src/gov/nasa/worldwind/render/PreRenderable.java index 6360282704..844f9cbbb7 100644 --- a/src/gov/nasa/worldwind/render/PreRenderable.java +++ b/src/gov/nasa/worldwind/render/PreRenderable.java @@ -3,14 +3,13 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; /** * @author tag * @version $Id: PreRenderable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface PreRenderable -{ +public interface PreRenderable { + void preRender(DrawContext dc); } diff --git a/src/gov/nasa/worldwind/render/Pyramid.java b/src/gov/nasa/worldwind/render/Pyramid.java index 0662205b5c..c1936845e7 100644 --- a/src/gov/nasa/worldwind/render/Pyramid.java +++ b/src/gov/nasa/worldwind/render/Pyramid.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -25,8 +24,8 @@ * @author ccrick * @version $Id: Pyramid.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Pyramid extends RigidShape -{ +public class Pyramid extends RigidShape { + protected static final int DEFAULT_SUBDIVISIONS = 0; // Geometry. @@ -39,9 +38,10 @@ public class Pyramid extends RigidShape // face 4: square base protected int subdivisions = DEFAULT_SUBDIVISIONS; - /** Construct a Pyramid with default parameters */ - public Pyramid() - { + /** + * Construct a Pyramid with default parameters + */ + public Pyramid() { this.setUpGeometryCache(); } @@ -49,22 +49,19 @@ public Pyramid() * Construct a Pyramid from a specified center position, height and width. * * @param centerPosition the Pyramid's center position. - * @param height the Pyramid's height, in meters. - * @param width the width of the Pyramid's base, in meters. + * @param height the Pyramid's height, in meters. + * @param width the width of the Pyramid's base, in meters. * * @throws IllegalArgumentException if the center position is null or any of the radii are not greater than 0. */ - public Pyramid(Position centerPosition, double height, double width) - { - if (centerPosition == null) - { + public Pyramid(Position centerPosition, double height, double width) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0 || width <= 0) - { + if (height <= 0 || width <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -80,24 +77,21 @@ public Pyramid(Position centerPosition, double height, double width) /** * Construct a Pyramid from a specified center position and axes lengths. * - * @param centerPosition the Pyramid's center position. + * @param centerPosition the Pyramid's center position. * @param northSouthRadius the Pyramid's north-south radius, in meters. - * @param verticalRadius the Pyramid's vertical radius, in meters. - * @param eastWestRadius the Pyramid's east-west radius, in meters. + * @param verticalRadius the Pyramid's vertical radius, in meters. + * @param eastWestRadius the Pyramid's east-west radius, in meters. * * @throws IllegalArgumentException if the center position is null or any of the radii are not greater than 0. */ - public Pyramid(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) - { - if (centerPosition == null) - { + public Pyramid(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -114,26 +108,23 @@ public Pyramid(Position centerPosition, double northSouthRadius, double vertical * Construct a Pyramid from a specified center position, axes lengths and rotation angles. All angles are specified * in degrees and positive angles are counter-clockwise. * - * @param centerPosition the Pyramid's center position. + * @param centerPosition the Pyramid's center position. * @param northSouthRadius the Pyramid's north-south radius, in meters. - * @param verticalRadius the Pyramid's vertical radius, in meters. - * @param eastWestRadius the Pyramid's east-west radius, in meters. - * @param heading the Pyramid's azimuth, its rotation about its vertical axis. - * @param tilt the Pyramid pitch, its rotation about its east-west axis. - * @param roll the Pyramid's roll, its rotation about its north-south axis. + * @param verticalRadius the Pyramid's vertical radius, in meters. + * @param eastWestRadius the Pyramid's east-west radius, in meters. + * @param heading the Pyramid's azimuth, its rotation about its vertical axis. + * @param tilt the Pyramid pitch, its rotation about its east-west axis. + * @param roll the Pyramid's roll, its rotation about its north-south axis. */ public Pyramid(Position centerPosition, double northSouthRadius, double verticalRadius, double eastWestRadius, - Angle heading, Angle tilt, Angle roll) - { - if (centerPosition == null) - { + Angle heading, Angle tilt, Angle roll) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -151,8 +142,7 @@ public Pyramid(Position centerPosition, double northSouthRadius, double vertical } @Override - protected void initialize() - { + protected void initialize() { // Nothing to override } @@ -161,8 +151,7 @@ protected void initialize() * * @return this Pyramid's height. */ - public double getHeight() - { + public double getHeight() { return verticalRadius * 2; } @@ -174,10 +163,8 @@ public double getHeight() * * @throws IllegalArgumentException if the height is not greater than 0. */ - public void setHeight(double height) - { - if (height <= 0) - { + public void setHeight(double height) { + if (height <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -196,10 +183,8 @@ public void setHeight(double height) * * @throws IllegalArgumentException if the width is not greater than 0. */ - public void setWidth(double width) - { - if (width <= 0) - { + public void setWidth(double width) { + if (width <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -211,13 +196,11 @@ public void setWidth(double width) } @Override - public int getFaceCount() - { + public int getFaceCount() { return this.faceCount; } - public int getSubdivisions() - { + public int getSubdivisions() { return this.subdivisions; } @@ -225,48 +208,44 @@ public int getSubdivisions() * Computes the number of subdivisions necessary to achieve the expected Level of Detail given the shape's * relationship to the viewer. * - * @param dc the current drawContext. + * @param dc the current drawContext. * @param shapeData the current globe-specific shape data */ - protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) - { + protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) { } //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - /** * Sets the Geometry mesh for this Pyramid, either by pulling it from the geometryCache, or by creating it anew if * the appropriate geometry does not yet exist in the cache. * * @param shapeData the current shape data. */ - protected void makeGeometry(ShapeData shapeData) - { + protected void makeGeometry(ShapeData shapeData) { // attempt to retrieve a cached unit box with the same number of subdivisions Object cacheKey = new Geometry.CacheKey(this.getClass(), "Pyramid0", this.subdivisions); Geometry geom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null) - { + if (geom == null) { // if none exists, create a new one makeUnitPyramid(this.subdivisions, shapeData.getMeshes()); - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } // add the new mesh pieces to the cache cacheKey = new Geometry.CacheKey(this.getClass(), "Pyramid" + piece, this.subdivisions); this.getGeometryCache().add(cacheKey, shapeData.getMesh(piece)); } - } - else - { + } else { // otherwise, just use the one from the cache - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } cacheKey = new Geometry.CacheKey(this.getClass(), "Pyramid" + piece, this.subdivisions); geom = (Geometry) this.getGeometryCache().getObject(cacheKey); shapeData.addMesh(piece, geom); @@ -279,7 +258,7 @@ protected void makeGeometry(ShapeData shapeData) * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit pyramid geometry - * @param dest the Geometry container to hold the computed points, etc. + * @param dest the Geometry container to hold the computed points, etc. */ /* protected void makeUnitPyramid(int subdivisions, Geometry dest) @@ -304,28 +283,25 @@ protected void makeUnitPyramid(int subdivisions, Geometry dest) dest.setNormalData(normalBuffer.limit(), normalBuffer); dest.setTextureCoordData(textureCoordBuffer.limit(), textureCoordBuffer); } - */ - + */ /** * Generates a unit pyramid geometry, including the vertices, indices, normals and texture coordinates, tessellated * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit pyramid geometry - * @param meshes the Geometry list to hold the computed points, etc. for all Geometries + * @param meshes the Geometry list to hold the computed points, etc. for all Geometries */ - protected void makeUnitPyramid(int subdivisions, List meshes) - { + protected void makeUnitPyramid(int subdivisions, List meshes) { float radius = 1.0f; Geometry dest; GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(GeometryBuilder.OUTSIDE); - for (int index = 0; index < getFaceCount(); index++) - { + for (int index = 0; index < getFaceCount(); index++) { // create box in model space - GeometryBuilder.IndexedTriangleBuffer itb = - gb.tessellatePyramidBuffer(index, radius, subdivisions); + GeometryBuilder.IndexedTriangleBuffer itb + = gb.tessellatePyramidBuffer(index, radius, subdivisions); FloatBuffer normalBuffer = Buffers.newDirectFloatBuffer(3 * itb.getVertexCount()); gb.makeIndexedTriangleBufferNormals(itb, normalBuffer); @@ -347,18 +323,16 @@ protected void makeUnitPyramid(int subdivisions, List meshes) /** * Renders the Pyramid, using data from the provided buffer and the given parameters * - * @param dc the current draw context - * @param mode the render mode - * @param count the number of elements to be drawn - * @param type the data type of the elements to be drawn + * @param dc the current draw context + * @param mode the render mode + * @param count the number of elements to be drawn + * @param type the data type of the elements to be drawn * @param elementBuffer the buffer containing the list of elements to be drawn - * @param shapeData the current globe-specific shape data + * @param shapeData the current globe-specific shape data */ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffer elementBuffer, - ShapeData shapeData, int face) - { - if (elementBuffer == null) - { + ShapeData shapeData, int face) { + if (elementBuffer == null) { String message = "nullValue.ElementBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -366,8 +340,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe Geometry mesh = shapeData.getMesh(face); - if (mesh.getBuffer(Geometry.VERTEX) == null) - { + if (mesh.getBuffer(Geometry.VERTEX) == null) { String message = "nullValue.VertexBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -384,17 +357,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe vertexBuffer = mesh.getBuffer(Geometry.VERTEX); normalBuffer = null; - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { normalBuffer = mesh.getBuffer(Geometry.NORMAL); - if (normalBuffer == null) - { + if (normalBuffer == null) { gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); - } - else - { + } else { glType = mesh.getGLType(Geometry.NORMAL); stride = mesh.getStride(Geometry.NORMAL); gl.glNormalPointer(glType, stride, normalBuffer); @@ -405,14 +373,11 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // cull the back face //gl.glEnable(GL.GL_CULL_FACE); //gl.glFrontFace(GL.GL_CCW); - // Testing: disable VBO's // boolean vboState = dc.getGLRuntimeCapabilities().isVertexBufferObjectEnabled(); // dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(true); - // decide whether to draw with VBO's or VA's - if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) - { + if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) { // render using VBO's gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getVboIds(getSubdivisions(), dc)[2 * face]); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, this.getVboIds(getSubdivisions(), dc)[2 * face + 1]); @@ -422,9 +387,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); - } - else - { + } else { // render using vertex arrays gl.glVertexPointer(size, glType, stride, vertexBuffer.rewind()); gl.glDrawElements(mode, count, type, elementBuffer); @@ -435,24 +398,20 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // Testing: restore VBO state // dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(false); - // disable back face culling // gl.glDisable(GL.GL_CULL_FACE); - - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { // re-enable normals if we temporarily turned them off earlier - if (normalBuffer == null) + if (normalBuffer == null) { gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); + } } // this.logGeometryStatistics(dc, geom); } } - protected ShapeData createIntersectionGeometry(Terrain terrain) - { + protected ShapeData createIntersectionGeometry(Terrain terrain) { ShapeData shapeData = new ShapeData(null, this); shapeData.setGlobeStateKey(terrain.getGlobe().getGlobeStateKey()); Geometry mesh; @@ -462,33 +421,32 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) // transform the vertices from local to world coords Matrix matrix = computeRenderMatrix(terrain.getGlobe(), terrain.getVerticalExaggeration()); - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { mesh = shapeData.getMesh(i); // transform the vertices from local to world coords FloatBuffer newVertices = computeTransformedVertices((FloatBuffer) mesh.getBuffer(Geometry.VERTEX), - mesh.getCount(Geometry.VERTEX), matrix); + mesh.getCount(Geometry.VERTEX), matrix); mesh.setVertexData(mesh.getCount(Geometry.VERTEX), newVertices); } shapeData.setReferencePoint(this.computeReferencePoint(terrain.getGlobe(), - terrain.getVerticalExaggeration())); + terrain.getVerticalExaggeration())); shapeData.setExtent(getExtent(terrain.getGlobe(), terrain.getVerticalExaggeration())); return shapeData; } - /** No export formats supported. */ + /** + * No export formats supported. + */ @Override - public String isExportFormatSupported(String mimeType) - { + public String isExportFormatSupported(String mimeType) { // Overridden because this shape does not support export to KML. return Exportable.FORMAT_NOT_SUPPORTED; } @Override - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { String message = Logging.getMessage("generic.UnsupportedOperation", "doExportAsKML"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); diff --git a/src/gov/nasa/worldwind/render/Quadrilateral.java b/src/gov/nasa/worldwind/render/Quadrilateral.java index 40c7152838..cf43589df0 100644 --- a/src/gov/nasa/worldwind/render/Quadrilateral.java +++ b/src/gov/nasa/worldwind/render/Quadrilateral.java @@ -20,8 +20,9 @@ * @version $Id: Quadrilateral.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class Quadrilateral implements Renderable, Movable, - Draggable // TODO: rename this class; it's a sector, not a quad + Draggable // TODO: rename this class; it's a sector, not a quad { + private LatLon southwestCorner; private LatLon northeastCorner; private double elevation; @@ -35,10 +36,8 @@ public class Quadrilateral implements Renderable, Movable, protected boolean dragEnabled = true; protected DraggableSupport draggableSupport = null; - public Quadrilateral(LatLon southwestCorner, LatLon northeastCorner, double elevation) - { - if (southwestCorner == null || northeastCorner == null) - { + public Quadrilateral(LatLon southwestCorner, LatLon northeastCorner, double elevation) { + if (southwestCorner == null || northeastCorner == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -49,10 +48,8 @@ public Quadrilateral(LatLon southwestCorner, LatLon northeastCorner, double elev this.elevation = elevation; } - public Quadrilateral(Sector sector, double elevation) - { - if (sector == null) - { + public Quadrilateral(Sector sector, double elevation) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -63,15 +60,12 @@ public Quadrilateral(Sector sector, double elevation) this.elevation = elevation; } - public Color getColor() - { + public Color getColor() { return color; } - public void setColor(Color color) - { - if (color == null) - { + public void setColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -80,10 +74,8 @@ public void setColor(Color color) this.color = color; } - public void setImageSource(Object imageSource) - { - if (imageSource == null) - { + public void setImageSource(Object imageSource) { + if (imageSource == null) { this.texture = null; return; } @@ -91,20 +83,16 @@ public void setImageSource(Object imageSource) this.texture = new BasicWWTexture(imageSource); } - public Object getImageSource() - { + public Object getImageSource() { return this.texture != null ? this.texture.getImageSource() : null; } - public int getAntiAliasHint() - { + public int getAntiAliasHint() { return antiAliasHint; } - public void setAntiAliasHint(int hint) - { - if (!(hint == GL.GL_DONT_CARE || hint == GL.GL_FASTEST || hint == GL.GL_NICEST)) - { + public void setAntiAliasHint(int hint) { + if (!(hint == GL.GL_DONT_CARE || hint == GL.GL_FASTEST || hint == GL.GL_NICEST)) { String msg = Logging.getMessage("generic.InvalidHint"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -113,15 +101,13 @@ public void setAntiAliasHint(int hint) this.antiAliasHint = hint; } - public void setCorners(LatLon southWest, LatLon northEast) - { + public void setCorners(LatLon southWest, LatLon northEast) { this.southwestCorner = southWest; this.northeastCorner = northEast; this.vertices = null; } - public LatLon[] getCorners() - { + public LatLon[] getCorners() { LatLon[] retVal = new LatLon[2]; retVal[0] = this.southwestCorner; @@ -130,39 +116,35 @@ public LatLon[] getCorners() return retVal; } - public double getElevation() - { + public double getElevation() { return elevation; } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.elevation = elevation; this.vertices = null; } - private void intializeGeometry(DrawContext dc) - { + private void intializeGeometry(DrawContext dc) { DoubleBuffer verts = Buffers.newDirectDoubleBuffer(12); Vec4[] p = new Vec4[4]; p[0] = dc.getGlobe().computePointFromPosition(this.southwestCorner.getLatitude(), - this.southwestCorner.getLongitude(), this.elevation); + this.southwestCorner.getLongitude(), this.elevation); p[1] = dc.getGlobe().computePointFromPosition(this.southwestCorner.getLatitude(), - this.northeastCorner.getLongitude(), this.elevation); + this.northeastCorner.getLongitude(), this.elevation); p[2] = dc.getGlobe().computePointFromPosition(this.northeastCorner.getLatitude(), - this.northeastCorner.getLongitude(), this.elevation); + this.northeastCorner.getLongitude(), this.elevation); p[3] = dc.getGlobe().computePointFromPosition(this.northeastCorner.getLatitude(), - this.southwestCorner.getLongitude(), this.elevation); + this.southwestCorner.getLongitude(), this.elevation); Vec4 refcenter = new Vec4( - (p[0].x + p[2].x) / 2.0, - (p[0].y + p[2].y) / 2.0, - (p[0].z + p[2].z) / 2.0); + (p[0].x + p[2].x) / 2.0, + (p[0].y + p[2].y) / 2.0, + (p[0].z + p[2].z) / 2.0); - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { verts.put(p[i].x - refcenter.x); verts.put(p[i].y - refcenter.y); verts.put(p[i].z - refcenter.z); @@ -172,8 +154,7 @@ private void intializeGeometry(DrawContext dc) this.vertices = verts; } - protected void initializeTextureCoordinates() - { + protected void initializeTextureCoordinates() { this.textureCoordinates = Buffers.newDirectDoubleBuffer(8); this.textureCoordinates.put(0).put(0); // sw @@ -182,51 +163,47 @@ protected void initializeTextureCoordinates() this.textureCoordinates.put(0).put(1); // nw } - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.vertices == null) + if (this.vertices == null) { this.intializeGeometry(dc); + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. boolean textureMatrixPushed = false; int attrBits = GL2.GL_HINT_BIT | GL2.GL_CURRENT_BIT | GL2.GL_COLOR_BUFFER_BIT; - if (!dc.isPickingMode()) - { - if (this.color.getAlpha() != 255) + if (!dc.isPickingMode()) { + if (this.color.getAlpha() != 255) { attrBits |= GL2.GL_COLOR_BUFFER_BIT; + } - if (this.texture != null) + if (this.texture != null) { attrBits |= GL2.GL_ENABLE_BIT | GL2.GL_TRANSFORM_BIT; + } } gl.glPushAttrib(attrBits); gl.glPushClientAttrib(GL2.GL_CLIENT_VERTEX_ARRAY_BIT); dc.getView().pushReferenceCenter(dc, this.referenceCenter); - try - { - if (!dc.isPickingMode()) - { + try { + if (!dc.isPickingMode()) { double layerOpacity = dc.getCurrentLayer() != null ? dc.getCurrentLayer().getOpacity() : 1; - if (this.color.getAlpha() != 255 || layerOpacity < 1) - { + if (this.color.getAlpha() != 255 || layerOpacity < 1) { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); } gl.glColor4ub((byte) this.color.getRed(), (byte) this.color.getGreen(), - (byte) this.color.getBlue(), (byte) (this.color.getAlpha() * layerOpacity)); + (byte) this.color.getBlue(), (byte) (this.color.getAlpha() * layerOpacity)); - if (this.texture != null) - { + if (this.texture != null) { gl.glMatrixMode(GL2.GL_TEXTURE); gl.glPushMatrix(); textureMatrixPushed = true; @@ -235,8 +212,9 @@ public void render(DrawContext dc) gl.glEnable(GL.GL_TEXTURE_2D); - if (this.textureCoordinates == null) + if (this.textureCoordinates == null) { this.initializeTextureCoordinates(); + } gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL2.GL_DOUBLE, 0, this.textureCoordinates.rewind()); @@ -251,11 +229,8 @@ public void render(DrawContext dc) gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL2.GL_DOUBLE, 0, this.vertices.rewind()); gl.glDrawArrays(GL2.GL_QUADS, 0, 4); - } - finally - { - if (textureMatrixPushed) - { + } finally { + if (textureMatrixPushed) { gl.glMatrixMode(GL2.GL_TEXTURE); gl.glPopMatrix(); } @@ -266,15 +241,12 @@ public void render(DrawContext dc) } } - public Position getReferencePosition() - { + public Position getReferencePosition() { return new Position(this.southwestCorner, this.elevation); } - public void move(Position delta) - { - if (delta == null) - { + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -286,48 +258,45 @@ public void move(Position delta) this.vertices = null; } - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Position delta = position.subtract(this.getReferencePosition()); - if (delta == null) + if (delta == null) { return; + } this.move(delta); } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, WorldWind.ABSOLUTE); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } } diff --git a/src/gov/nasa/worldwind/render/Renderable.java b/src/gov/nasa/worldwind/render/Renderable.java index 6b875986f8..9f05fa8949 100644 --- a/src/gov/nasa/worldwind/render/Renderable.java +++ b/src/gov/nasa/worldwind/render/Renderable.java @@ -9,8 +9,8 @@ * @author Tom Gaskins * @version $Id: Renderable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Renderable -{ +public interface Renderable { + /** * Causes this Renderable to render itself using the provided draw context. * diff --git a/src/gov/nasa/worldwind/render/RigidShape.java b/src/gov/nasa/worldwind/render/RigidShape.java index 639f36c602..5ed21130d0 100644 --- a/src/gov/nasa/worldwind/render/RigidShape.java +++ b/src/gov/nasa/worldwind/render/RigidShape.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -24,84 +23,81 @@ /** * A general rigid volume defined by a center position and the three axis radii. If A is the radius in the north-south * direction, and b is the radius in the east-west direction, and c is the radius in the vertical direction (increasing - * altitude), then A == B == C defines a unit shape, A == B > C defines a vertically flattened shape (disk-shaped), A == - * B < C defines a vertically stretched shape. + * altitude), then A == B == C defines a unit shape, A == B > C defines a vertically flattened shape (disk-shaped), A + * == B < C defines a vertically stretched shape. * * @author ccrick * @version $Id: RigidShape.java 2990 2015-04-07 19:06:15Z tgaskins $ */ -public abstract class RigidShape extends AbstractShape -{ +public abstract class RigidShape extends AbstractShape { + /** * Maintains globe-dependent computed data such as Cartesian vertices and extents. One entry exists for each * distinct globe that this shape encounters in calls to {@link AbstractShape#render(DrawContext)}. See {@link * AbstractShape}. */ - protected static class ShapeData extends AbstractShapeData - { - /** Holds the computed tessellation of the shape in model coordinates. */ + protected static class ShapeData extends AbstractShapeData { + + /** + * Holds the computed tessellation of the shape in model coordinates. + */ protected List meshes = new ArrayList(); - /** The GPU-resource cache keys to use for this entry's VBOs (one for eack LOD), if VBOs are used. */ + /** + * The GPU-resource cache keys to use for this entry's VBOs (one for eack LOD), if VBOs are used. + */ protected Map vboCacheKeys = new HashMap(); - /** Indicates whether the index buffer needs to be filled because a new buffer is used or some other reason. */ + /** + * Indicates whether the index buffer needs to be filled because a new buffer is used or some other reason. + */ protected boolean refillIndexBuffer = true; // set to true if the index buffer needs to be refilled - /** Indicates whether the index buffer's VBO needs to be filled because a new buffer is used or other reason. */ + /** + * Indicates whether the index buffer's VBO needs to be filled because a new buffer is used or other reason. + */ protected boolean refillIndexVBO = true; // set to true if the index VBO needs to be refilled - public ShapeData(DrawContext dc, RigidShape shape) - { + public ShapeData(DrawContext dc, RigidShape shape) { super(dc, shape.minExpiryTime, shape.maxExpiryTime); //super(dc, 0, 0); // specify 0 as expiry time since only size/position transform changes with time } - public Geometry getMesh() - { + public Geometry getMesh() { return meshes.get(0); } - public Geometry getMesh(int index) - { + public Geometry getMesh(int index) { return meshes.get(index); } - public List getMeshes() - { + public List getMeshes() { return meshes; } - public void setMesh(Geometry mesh) - { + public void setMesh(Geometry mesh) { this.addMesh(0, mesh); } - public void setMeshes(List meshes) - { + public void setMeshes(List meshes) { this.meshes = meshes; } - public void addMesh(Geometry mesh) - { + public void addMesh(Geometry mesh) { this.addMesh(this.meshes.size(), mesh); } - public void addMesh(int index, Geometry mesh) - { + public void addMesh(int index, Geometry mesh) { this.meshes.add(index, mesh); } - public Object getVboCacheKey(int index) - { + public Object getVboCacheKey(int index) { return vboCacheKeys.get(index); } - public void setVboCacheKey(int index, Object vboCacheKey) - { + public void setVboCacheKey(int index, Object vboCacheKey) { this.vboCacheKeys.put(index, vboCacheKey); } - public int getVboCacheSize() - { + public int getVboCacheSize() { return this.vboCacheKeys.size(); } } @@ -111,34 +107,29 @@ public int getVboCacheSize() * * @return the current data cache entry. */ - protected ShapeData getCurrentShapeData() - { + protected ShapeData getCurrentShapeData() { return (ShapeData) this.getCurrentData(); } - public class Offsets - { + public class Offsets { + protected Map offsets; - public Offsets() - { + public Offsets() { offsets = new HashMap(); // set default values to zero offset float[] zeroOffset = {0.0f, 0.0f}; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { offsets.put(i, zeroOffset); } } - public float[] getOffset(int index) - { + public float[] getOffset(int index) { return offsets.get(index); } - public void setOffset(int index, float uOffset, float vOffset) - { + public void setOffset(int index, float uOffset, float vOffset) { float[] offsetPair = {uOffset, vOffset}; offsets.put(index, offsetPair); } @@ -169,10 +160,14 @@ public void setOffset(int index, float uOffset, float vOffset) protected static final long DEFAULT_GEOMETRY_CACHE_SIZE = 16777216L; // 16 megabytes protected static final String GEOMETRY_CACHE_NAME = "Airspace Geometry"; // use same cache as Airspaces - /** The image source of the shape's texture. */ + /** + * The image source of the shape's texture. + */ protected Map imageSources = new HashMap(); // image sources for the textures for each piece of geometry - /** The {@link WWTexture} created for the image source, if any. */ + /** + * The {@link WWTexture} created for the image source, if any. + */ protected Map textures = new HashMap(); // optional textures for each piece of geometry @@ -183,16 +178,21 @@ public void setOffset(int index, float uOffset, float vOffset) protected Map offsetTextureCoords = new HashMap(); // Fields used in intersection calculations - /** The terrain used in the most recent intersection calculations. */ + /** + * The terrain used in the most recent intersection calculations. + */ protected Terrain previousIntersectionTerrain; - /** The globe state key for the globe used in the most recent intersection calculation. */ + /** + * The globe state key for the globe used in the most recent intersection calculation. + */ protected Object previousIntersectionGlobeStateKey; - /** The shape data used for the previous intersection calculation. */ + /** + * The shape data used for the previous intersection calculation. + */ protected ShapeData previousIntersectionShapeData; @Override - protected void reset() - { + protected void reset() { this.previousIntersectionShapeData = null; this.previousIntersectionTerrain = null; this.previousIntersectionGlobeStateKey = null; @@ -208,19 +208,17 @@ protected void reset() * * @return the texture, or null if there is no texture or the texture is not yet available. */ - protected WWTexture getTexture(int index) - { + protected WWTexture getTexture(int index) { return textures.get(index); } /** * Establishes the texture for this piece of the shape's geometry. * - * @param index the index of the piece of geometry for which we are setting the texture. + * @param index the index of the piece of geometry for which we are setting the texture. * @param texture the texture for this shape. */ - protected void setTexture(int index, WWTexture texture) - { + protected void setTexture(int index, WWTexture texture) { this.textures.put(index, texture); } @@ -231,8 +229,7 @@ protected void setTexture(int index, WWTexture texture) * * @return the image source of #index texture. */ - public Object getImageSource(int index) - { + public Object getImageSource(int index) { return this.imageSources.get(index); } @@ -240,15 +237,11 @@ public Object getImageSource(int index) * Specifies the single image source for this shape's optional texture, to be placed on every face. * * @param imageSource the texture image source. May be a {@link java.io.File}, file path, a stream, a URL or a - * {@link java.awt.image.BufferedImage}. + * {@link java.awt.image.BufferedImage}. */ - - public void setImageSources(Object imageSource) - { - if (imageSource != null) - { - for (int i = 0; i < getFaceCount(); i++) - { + public void setImageSources(Object imageSource) { + if (imageSource != null) { + for (int i = 0; i < getFaceCount(); i++) { setImageSource(i, imageSource); } } @@ -258,15 +251,12 @@ public void setImageSources(Object imageSource) * Specifies the image sources for this shape's optional textures. * * @param imageSources the list of texture image sources. May be {@link java.io.File}, file path, a stream, a URL or - * a {@link java.awt.image.BufferedImage}. + * a {@link java.awt.image.BufferedImage}. */ - public void setImageSources(Iterable imageSources) - { - if (imageSources != null) - { + public void setImageSources(Iterable imageSources) { + if (imageSources != null) { int index = 0; - for (Object imageSource : imageSources) - { + for (Object imageSource : imageSources) { setImageSource(index, imageSource); index++; } @@ -276,20 +266,16 @@ public void setImageSources(Iterable imageSources) /** * Specifies the image source for this shape's #index optional texture. * - * @param index the index of the piece of geometry for which we are setting the imageSource. + * @param index the index of the piece of geometry for which we are setting the imageSource. * @param imageSource the texture image source. May be a {@link java.io.File}, file path, a stream, a URL or a - * {@link java.awt.image.BufferedImage}. + * {@link java.awt.image.BufferedImage}. */ - public void setImageSource(int index, Object imageSource) - { + public void setImageSource(int index, Object imageSource) { // check if a texture has already been created for this imageSource before creating one - if (imageSource != null) - { + if (imageSource != null) { WWTexture newTexture = null; - for (Integer key : imageSources.keySet()) - { - if (imageSource.equals(imageSources.get(key))) - { + for (Integer key : imageSources.keySet()) { + if (imageSource.equals(imageSources.get(key))) { newTexture = textures.get(key); break; } @@ -305,8 +291,7 @@ public void setImageSource(int index, Object imageSource) * * @return number of faces */ - public int getFaceCount() - { + public int getFaceCount() { return this.faceCount; } @@ -315,8 +300,7 @@ public int getFaceCount() * * @param faces integer indicating how many different faces this shape has */ - protected void setFaceCount(int faces) - { + protected void setFaceCount(int faces) { this.faceCount = faces; } @@ -326,28 +310,25 @@ protected void setFaceCount(int faces) * Returns the pair of texture coordinate offsets corresponding to the shape face and texture coordinate specified * by the faceIndex and offsetIndex. * - * @param faceIndex the shape face from which to retrieve the offset pair + * @param faceIndex the shape face from which to retrieve the offset pair * @param offsetIndex the index of the specific texture coordinate on the face whose offsets we wish to retrieve * * @return the specified texture offset pair */ - public float[] getOffsets(int faceIndex, int offsetIndex) - { + public float[] getOffsets(int faceIndex, int offsetIndex) { return this.offsets.get(faceIndex) != null ? this.offsets.get(faceIndex).getOffset(offsetIndex) : null; } /** * Sets the u and v texture coordinate offsets for the specified texture coordinate on the specified shape face. * - * @param faceIndex the shape face on which we would like to set the texture coordinate offsets + * @param faceIndex the shape face on which we would like to set the texture coordinate offsets * @param offsetIndex the index of the particular texture coordinate we would like to set offsets for - * @param uOffset the offset in the u direction - * @param vOffset the offset in the v direction + * @param uOffset the offset in the u direction + * @param vOffset the offset in the v direction */ - public void setOffset(int faceIndex, int offsetIndex, float uOffset, float vOffset) - { - if (this.offsets.get(faceIndex) != null) - { + public void setOffset(int faceIndex, int offsetIndex, float uOffset, float vOffset) { + if (this.offsets.get(faceIndex) != null) { this.offsets.get(faceIndex).setOffset(offsetIndex, uOffset, vOffset); } } @@ -357,8 +338,7 @@ public void setOffset(int faceIndex, int offsetIndex, float uOffset, float vOffs * * @return this shape's center position. */ - public Position getCenterPosition() - { + public Position getCenterPosition() { return centerPosition; } @@ -367,10 +347,8 @@ public Position getCenterPosition() * * @param centerPosition this shape's center position. */ - public void setCenterPosition(Position centerPosition) - { - if (centerPosition == null) - { + public void setCenterPosition(Position centerPosition) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -385,8 +363,7 @@ public void setCenterPosition(Position centerPosition) * * @return the centerPosition of the shape */ - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.centerPosition; } @@ -395,8 +372,7 @@ public Position getReferencePosition() * * @return this shape's radius in the north-south direction. */ - public double getNorthSouthRadius() - { + public double getNorthSouthRadius() { return northSouthRadius; } @@ -408,10 +384,8 @@ public double getNorthSouthRadius() * * @throws IllegalArgumentException if the radius is not greater than 0. */ - public void setNorthSouthRadius(double northSouthRadius) - { - if (northSouthRadius <= 0) - { + public void setNorthSouthRadius(double northSouthRadius) { + if (northSouthRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "northSouthRadius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -427,8 +401,7 @@ public void setNorthSouthRadius(double northSouthRadius) * * @return this shape's radius in the east-west direction. */ - public double getEastWestRadius() - { + public double getEastWestRadius() { return eastWestRadius; } @@ -440,10 +413,8 @@ public double getEastWestRadius() * * @throws IllegalArgumentException if the radius is not greater than 0. */ - public void setEastWestRadius(double eastWestRadius) - { - if (eastWestRadius <= 0) - { + public void setEastWestRadius(double eastWestRadius) { + if (eastWestRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "eastWestRadius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -459,8 +430,7 @@ public void setEastWestRadius(double eastWestRadius) * * @return this shape's radius in the vertical direction. */ - public double getVerticalRadius() - { + public double getVerticalRadius() { return verticalRadius; } @@ -472,10 +442,8 @@ public double getVerticalRadius() * * @throws IllegalArgumentException if the radius is not greater than 0. */ - public void setVerticalRadius(double verticalRadius) - { - if (verticalRadius <= 0) - { + public void setVerticalRadius(double verticalRadius) { + if (verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "verticalRadius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -492,8 +460,7 @@ public void setVerticalRadius(double verticalRadius) * * @return this shape's azimuth. */ - public Angle getHeading() - { + public Angle getHeading() { return this.heading; } @@ -503,16 +470,13 @@ public Angle getHeading() * * @param heading the shape's azimuth, in degrees. */ - public void setHeading(Angle heading) - { + public void setHeading(Angle heading) { // constrain values to 0 to 360 (aka 0 to 2PI) for compatibility with KML double degrees = heading.getDegrees(); - while (degrees < 0) - { + while (degrees < 0) { degrees += 360; } - while (degrees > 360) - { + while (degrees > 360) { degrees -= 360; } @@ -526,8 +490,7 @@ public void setHeading(Angle heading) * * @return this shape's azimuth. */ - public Angle getTilt() - { + public Angle getTilt() { return this.tilt; } @@ -536,16 +499,13 @@ public Angle getTilt() * * @param tilt the shape's pitch, in degrees. */ - public void setTilt(Angle tilt) - { + public void setTilt(Angle tilt) { // constrain values to 0 to 360 (aka 0 to 2PI) for compatibility with KML double degrees = tilt.getDegrees(); - while (degrees < 0) - { + while (degrees < 0) { degrees += 360; } - while (degrees > 360) - { + while (degrees > 360) { degrees -= 360; } @@ -559,8 +519,7 @@ public void setTilt(Angle tilt) * * @return this shape's azimuth. */ - public Angle getRoll() - { + public Angle getRoll() { return this.roll; } @@ -570,16 +529,13 @@ public Angle getRoll() * * @param roll the shape's roll, in degrees. */ - public void setRoll(Angle roll) - { + public void setRoll(Angle roll) { // constrain values to 0 to 360 (aka 0 to 2PI) for compatibility with KML double degrees = roll.getDegrees(); - while (degrees < 0) - { + while (degrees < 0) { degrees += 360; } - while (degrees > 360) - { + while (degrees > 360) { degrees -= 360; } @@ -593,8 +549,7 @@ public void setRoll(Angle roll) * * @return this shape's North-South skew. */ - public Angle getSkewNorthSouth() - { + public Angle getSkewNorthSouth() { return skewNorthSouth; } @@ -604,12 +559,10 @@ public Angle getSkewNorthSouth() * * @param skew the shape's skew in the North-South direction. */ - public void setSkewNorthSouth(Angle skew) - { - if (skew.compareTo(Angle.POS180) >= 0 || skew.compareTo(Angle.ZERO) <= 0) - { + public void setSkewNorthSouth(Angle skew) { + if (skew.compareTo(Angle.POS180) >= 0 || skew.compareTo(Angle.ZERO) <= 0) { String message = Logging.getMessage("generic.AngleOutOfRange", - "skew >= 180 degrees or skew <= 0 degrees"); + "skew >= 180 degrees or skew <= 0 degrees"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -624,8 +577,7 @@ public void setSkewNorthSouth(Angle skew) * * @return this shape's East-West skew. */ - public Angle getSkewEastWest() - { + public Angle getSkewEastWest() { return skewEastWest; } @@ -635,12 +587,10 @@ public Angle getSkewEastWest() * * @param skew the shape's skew in the East-West direction. */ - public void setSkewEastWest(Angle skew) - { - if (skew.compareTo(Angle.POS180) >= 0 || skew.compareTo(Angle.ZERO) <= 0) - { + public void setSkewEastWest(Angle skew) { + if (skew.compareTo(Angle.POS180) >= 0 || skew.compareTo(Angle.ZERO) <= 0) { String message = Logging.getMessage("generic.AngleOutOfRange", - "skew >= 180 degrees or skew <= 0 degrees"); + "skew >= 180 degrees or skew <= 0 degrees"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -651,8 +601,7 @@ public void setSkewEastWest(Angle skew) } @Override - protected void initialize() - { + protected void initialize() { // Nothing to override } @@ -663,8 +612,7 @@ protected void initialize() * * @see #setDetailHint(double) */ - public double getDetailHint() - { + public double getDetailHint() { return this.detailHint; } @@ -675,21 +623,19 @@ public double getDetailHint() * range between -0.5 and 0.5. * * @param detailHint the degree to modify the default tessellation resolution of the shape. Values greater than 1 - * increase the resolution. Values less than zero decrease the resolution. The default value is - * 0. + * increase the resolution. Values less than zero decrease the resolution. The default value is 0. */ - public void setDetailHint(double detailHint) - { + public void setDetailHint(double detailHint) { this.detailHint = detailHint; reset(); } - /** Create the geometry cache supporting the Level of Detail system. */ - protected void setUpGeometryCache() - { - if (!WorldWind.getMemoryCacheSet().containsCache(GEOMETRY_CACHE_KEY)) - { + /** + * Create the geometry cache supporting the Level of Detail system. + */ + protected void setUpGeometryCache() { + if (!WorldWind.getMemoryCacheSet().containsCache(GEOMETRY_CACHE_KEY)) { long size = Configuration.getLongValue(AVKey.AIRSPACE_GEOMETRY_CACHE_SIZE, DEFAULT_GEOMETRY_CACHE_SIZE); MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size); cache.setName(GEOMETRY_CACHE_NAME); @@ -702,27 +648,22 @@ protected void setUpGeometryCache() * * @return the geometry cache. */ - protected MemoryCache getGeometryCache() - { + protected MemoryCache getGeometryCache() { return WorldWind.getMemoryCache(GEOMETRY_CACHE_KEY); } @Override - protected AbstractShapeData createCacheEntry(DrawContext dc) - { + protected AbstractShapeData createCacheEntry(DrawContext dc) { return new ShapeData(dc, this); } @Override - protected boolean mustApplyTexture(DrawContext dc) - { + protected boolean mustApplyTexture(DrawContext dc) { boolean applyTexture = false; - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { // TODO add error checking here? - if (this.getTexture(i) != null && this.getCurrentShapeData().getMesh(i).getBuffer(Geometry.TEXTURE) != null) - { + if (this.getTexture(i) != null && this.getCurrentShapeData().getMesh(i).getBuffer(Geometry.TEXTURE) != null) { applyTexture = true; break; } @@ -730,44 +671,46 @@ protected boolean mustApplyTexture(DrawContext dc) return applyTexture; } - protected boolean mustApplyTexture(int index) - { - return this.getTexture(index) != null && - this.getCurrentShapeData().getMesh(index).getBuffer(Geometry.TEXTURE) != null; + protected boolean mustApplyTexture(int index) { + return this.getTexture(index) != null + && this.getCurrentShapeData().getMesh(index).getBuffer(Geometry.TEXTURE) != null; } - protected boolean mustRegenerateGeometry(DrawContext dc) - { + protected boolean mustRegenerateGeometry(DrawContext dc) { ShapeData shapedata = this.getCurrentShapeData(); if (shapedata == null || shapedata.getMeshes() == null - || shapedata.getMeshes().size() < 1) + || shapedata.getMeshes().size() < 1) { return true; + } if (shapedata.getMesh(0) == null - || shapedata.getMesh(0).getBuffer(Geometry.VERTEX) == null) + || shapedata.getMesh(0).getBuffer(Geometry.VERTEX) == null) { return true; + } - if (dc.getVerticalExaggeration() != shapedata.getVerticalExaggeration()) + if (dc.getVerticalExaggeration() != shapedata.getVerticalExaggeration()) { return true; + } //noinspection SimplifiableIfStatement if (this.getAltitudeMode() == WorldWind.ABSOLUTE - && shapedata.getGlobeStateKey() != null - && shapedata.getGlobeStateKey().equals(dc.getGlobe().getGlobeStateKey(dc))) + && shapedata.getGlobeStateKey() != null + && shapedata.getGlobeStateKey().equals(dc.getGlobe().getGlobeStateKey(dc))) { return false; + } return super.mustRegenerateGeometry(dc); } @Override - protected boolean doMakeOrderedRenderable(DrawContext dc) - { + protected boolean doMakeOrderedRenderable(DrawContext dc) { ShapeData shapeData = this.getCurrentShapeData(); Vec4 refPt = this.computeReferencePoint(dc); - if (refPt == null) + if (refPt == null) { return false; + } shapeData.setReferencePoint(refPt); shapeData.setEyeDistance(dc.getView().getEyePoint().distanceTo3(refPt)); @@ -788,30 +731,29 @@ protected boolean doMakeOrderedRenderable(DrawContext dc) this.makeGeometry(shapeData); // If the shape is less that a pixel in size, don't render it. - if (shapeData.getExtent() == null || dc.isSmall(shapeData.getExtent(), 1)) + if (shapeData.getExtent() == null || dc.isSmall(shapeData.getExtent(), 1)) { return false; + } //noinspection SimplifiableIfStatement - if (!this.intersectsFrustum(dc)) + if (!this.intersectsFrustum(dc)) { return false; + } return !(shapeData.getMesh(0) == null || shapeData.getMesh(0).getBuffer(Geometry.VERTEX) == null - || shapeData.getMesh(0).getCount(Geometry.VERTEX) < 2); + || shapeData.getMesh(0).getCount(Geometry.VERTEX) < 2); } @Override - protected boolean isOrderedRenderableValid(DrawContext dc) - { + protected boolean isOrderedRenderableValid(DrawContext dc) { return this.getCurrentShapeData().getMesh(0).getBuffer(Geometry.VERTEX) != null; } @Override - protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) - { + protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) { OGLStackHandler ogsh = super.beginDrawing(dc, attrMask); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Push an identity texture matrix. This prevents drawGeometry() from leaking GL texture matrix state. The // texture matrix stack is popped from OGLStackHandler.pop(). GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -822,10 +764,8 @@ protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask) } @Override - protected void doDrawOutline(DrawContext dc) - { - for (int i = 0; i < getFaceCount(); i++) - { + protected void doDrawOutline(DrawContext dc) { + for (int i = 0; i < getFaceCount(); i++) { Geometry mesh = this.getCurrentShapeData().getMesh(i); // set to draw using GL_LINES @@ -842,13 +782,11 @@ protected void doDrawOutline(DrawContext dc) } @Override - protected void doDrawInterior(DrawContext dc) - { + protected void doDrawInterior(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // render extent if specified - if (this.renderExtent) - { + if (this.renderExtent) { Box extent = (Box) this.getCurrentShapeData().getExtent(); extent.render(dc); } @@ -856,17 +794,16 @@ protected void doDrawInterior(DrawContext dc) // set up MODELVIEW matrix to properly position, orient and scale this shape setModelViewMatrix(dc); - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { // set up the texture if one exists if (!dc.isPickingMode() && mustApplyTexture(i) && this.getTexture(i).bind( - dc)) // bind initiates retrieval + dc)) // bind initiates retrieval { this.getTexture(i).applyInternalTransform(dc); Geometry mesh = this.getCurrentShapeData().getMesh(i); - if (getOffsets(i, 0) != null) // if texture offsets exist + if (getOffsets(i, 0) != null) // if texture offsets exist { // apply offsets to texture coords to properly position and warp the texture // TODO: should only do this when offsets have changed, e.g. during editing! @@ -874,32 +811,29 @@ protected void doDrawInterior(DrawContext dc) FloatBuffer texCoords = (FloatBuffer) mesh.getBuffer(Geometry.TEXTURE); FloatBuffer offsetCoords = Buffers.newDirectFloatBuffer(bufferSize); - for (int j = 0; j < bufferSize; j += 2) - { + for (int j = 0; j < bufferSize; j += 2) { float u = texCoords.get(j); float v = texCoords.get(j + 1); // bilinear interpolation of the uv corner offsets float uOffset = -getOffsets(i, 0)[0] * (1 - u) * (v) - - getOffsets(i, 1)[0] * (u) * (v) - - getOffsets(i, 2)[0] * (1 - u) * (1 - v) - - getOffsets(i, 3)[0] * (u) * (1 - v) - + u; + - getOffsets(i, 1)[0] * (u) * (v) + - getOffsets(i, 2)[0] * (1 - u) * (1 - v) + - getOffsets(i, 3)[0] * (u) * (1 - v) + + u; float vOffset = -getOffsets(i, 0)[1] * (1 - u) * (v) - - getOffsets(i, 1)[1] * (u) * (v) - - getOffsets(i, 2)[1] * (1 - u) * (1 - v) - - getOffsets(i, 3)[1] * (u) * (1 - v) - + v; + - getOffsets(i, 1)[1] * (u) * (v) + - getOffsets(i, 2)[1] * (1 - u) * (1 - v) + - getOffsets(i, 3)[1] * (u) * (1 - v) + + v; offsetCoords.put(j, uOffset); offsetCoords.put(j + 1, vOffset); } gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, offsetCoords.rewind()); - } - else - { + } else { gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, mesh.getBuffer(Geometry.TEXTURE).rewind()); } gl.glEnable(GL.GL_TEXTURE_2D); @@ -907,9 +841,7 @@ protected void doDrawInterior(DrawContext dc) gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT); - } - else - { + } else { gl.glDisable(GL.GL_TEXTURE_2D); gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY); } @@ -930,8 +862,7 @@ protected void doDrawInterior(DrawContext dc) * * @return the computed extent. */ - protected Extent computeExtent(DrawContext dc) - { + protected Extent computeExtent(DrawContext dc) { Matrix matrix = computeRenderMatrix(dc); // create a list of vertices representing the extrema of the unit sphere @@ -955,17 +886,15 @@ protected Extent computeExtent(DrawContext dc) /** * Computes the shape's extent using a bounding box. * - * @param globe the current globe + * @param globe the current globe * @param verticalExaggeration the current vertical exaggeration * * @return the computed extent. * * @throws IllegalArgumentException if the globe is null. */ - public Extent getExtent(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + public Extent getExtent(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -989,8 +918,9 @@ public Extent getExtent(Globe globe, double verticalExaggeration) // get - or compute - the center point, in global coordinates Position pos = this.getCenterPosition(); - if (pos == null) + if (pos == null) { return null; + } Vec4 centerPoint = this.computeReferencePoint(globe, verticalExaggeration); @@ -999,34 +929,31 @@ public Extent getExtent(Globe globe, double verticalExaggeration) } /** - * Computes the shape's sector. Not currently supported. + * Computes the shape's sector. Not currently supported. * * @return the bounding sector for this shape */ - public Sector getSector() - { + public Sector getSector() { return null; } /** * Transform all vertices with the provided matrix * - * @param vertices the buffer of vertices to transform + * @param vertices the buffer of vertices to transform * @param numVertices the number of distinct vertices in the buffer (assume 3-space) - * @param matrix the matrix for transforming the vertices + * @param matrix the matrix for transforming the vertices * * @return the transformed vertices. */ - protected FloatBuffer computeTransformedVertices(FloatBuffer vertices, int numVertices, Matrix matrix) - { + protected FloatBuffer computeTransformedVertices(FloatBuffer vertices, int numVertices, Matrix matrix) { int size = numVertices * 3; FloatBuffer newVertices = Buffers.newDirectFloatBuffer(size); // transform all vertices by the render matrix - for (int i = 0; i < numVertices; i++) - { + for (int i = 0; i < numVertices; i++) { Vec4 point = matrix.transformBy3(matrix, vertices.get(3 * i), vertices.get(3 * i + 1), - vertices.get(3 * i + 2)); + vertices.get(3 * i + 2)); newVertices.put((float) point.getX()).put((float) point.getY()).put((float) point.getZ()); } @@ -1042,11 +969,11 @@ protected FloatBuffer computeTransformedVertices(FloatBuffer vertices, int numVe * * @return the computed reference point relative to the globe associated with the draw context. */ - public Vec4 computeReferencePoint(DrawContext dc) - { + public Vec4 computeReferencePoint(DrawContext dc) { Position pos = this.getCenterPosition(); - if (pos == null) + if (pos == null) { return null; + } return computePoint(dc.getTerrain(), pos); } @@ -1054,25 +981,25 @@ public Vec4 computeReferencePoint(DrawContext dc) /** * Sets the shape's referencePoint, which is essentially its centerPosition in Cartesian coordinates. * - * @param globe the current globe + * @param globe the current globe * @param verticalExaggeration the current vertical exaggeration * * @return the computed reference point, or null if the point could not be computed. */ - protected Vec4 computeReferencePoint(Globe globe, double verticalExaggeration) - { + protected Vec4 computeReferencePoint(Globe globe, double verticalExaggeration) { Position pos = this.getCenterPosition(); - if (pos == null) + if (pos == null) { return null; + } double elevation = globe.getElevation(pos.latitude, pos.longitude); double height; - if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND) + if (this.getAltitudeMode() == WorldWind.CLAMP_TO_GROUND) { height = 0d + elevation * verticalExaggeration; - else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) + } else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) { height = pos.getAltitude() + elevation * verticalExaggeration; - else // ABSOLUTE elevation mode + } else // ABSOLUTE elevation mode { // Raise the shape to accommodate vertical exaggeration applied to the terrain. height = pos.getAltitude() * verticalExaggeration; @@ -1085,17 +1012,15 @@ else if (this.getAltitudeMode() == WorldWind.RELATIVE_TO_GROUND) * Computes the transform to use during rendering to convert the unit sphere geometry representation of this shape * to its correct shape location, orientation and scale * - * @param globe the current globe + * @param globe the current globe * @param verticalExaggeration the current vertical exaggeration * * @return the modelview transform for this shape * * @throws IllegalArgumentException if globe is null */ - public Matrix computeRenderMatrix(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + public Matrix computeRenderMatrix(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1108,16 +1033,18 @@ public Matrix computeRenderMatrix(Globe globe, double verticalExaggeration) // now apply the user-specified heading/tilt/roll: // order corresponds to KML rotations (YXZ, positive clockwise) - // roll - if (roll != null) + if (roll != null) { matrix = matrix.multiply(Matrix.fromRotationY(Angle.POS360.subtract(this.roll))); + } // tilt - if (tilt != null) + if (tilt != null) { matrix = matrix.multiply(Matrix.fromRotationX(Angle.POS360.subtract(this.tilt))); + } // heading - if (heading != null) + if (heading != null) { matrix = matrix.multiply(Matrix.fromRotationZ(Angle.POS360.subtract(this.heading))); + } //matrix = matrix.multiply(Matrix.fromRotationZ(this.heading)); // apply skew (aka shear) matrix @@ -1125,7 +1052,7 @@ public Matrix computeRenderMatrix(Globe globe, double verticalExaggeration) // finally, scale it along each of the axis matrix = matrix.multiply(Matrix.fromScale(this.getEastWestRadius(), - this.getNorthSouthRadius(), this.getVerticalRadius())); + this.getNorthSouthRadius(), this.getVerticalRadius())); return matrix; } @@ -1140,8 +1067,7 @@ public Matrix computeRenderMatrix(Globe globe, double verticalExaggeration) * * @throws IllegalArgumentException if draw context is null or the referencePoint is null */ - public Matrix computeRenderMatrix(DrawContext dc) - { + public Matrix computeRenderMatrix(DrawContext dc) { Matrix matrix = Matrix.IDENTITY; // translate and orient, accounting for altitude mode @@ -1150,16 +1076,18 @@ public Matrix computeRenderMatrix(DrawContext dc) // now apply the user-specified heading/tilt/roll // order corresponds to KML rotations (YXZ, positive clockwise) - // roll - if (roll != null) + if (roll != null) { matrix = matrix.multiply(Matrix.fromRotationY(Angle.POS360.subtract(this.roll))); + } // tilt - if (tilt != null) + if (tilt != null) { matrix = matrix.multiply(Matrix.fromRotationX(Angle.POS360.subtract(this.tilt))); + } // heading - if (heading != null) + if (heading != null) { matrix = matrix.multiply(Matrix.fromRotationZ(Angle.POS360.subtract(this.heading))); + } //matrix = matrix.multiply(Matrix.fromRotationZ(this.heading)); // apply skew (aka shear) matrix @@ -1167,7 +1095,7 @@ public Matrix computeRenderMatrix(DrawContext dc) // finally, scale it along each of the axis matrix = matrix.multiply(Matrix.fromScale(this.getEastWestRadius(), - this.getNorthSouthRadius(), this.getVerticalRadius())); + this.getNorthSouthRadius(), this.getVerticalRadius())); return matrix; } @@ -1177,17 +1105,15 @@ public Matrix computeRenderMatrix(DrawContext dc) * shape to its correct shape location, orientation and scale, essentially bringing the shape back into local * coordinate space. * - * @param globe the current globe + * @param globe the current globe * @param verticalExaggeration the current vertical exaggeration * * @return the inverse of the modelview transform for this shape * * @throws IllegalArgumentException if draw context is null or the referencePoint is null */ - public Matrix computeRenderMatrixInverse(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + public Matrix computeRenderMatrixInverse(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1197,22 +1123,25 @@ public Matrix computeRenderMatrixInverse(Globe globe, double verticalExaggeratio // inverse scale along each of the axis matrix = matrix.multiply(Matrix.fromScale(1 / this.getEastWestRadius(), - 1 / this.getNorthSouthRadius(), 1 / this.getVerticalRadius())); + 1 / this.getNorthSouthRadius(), 1 / this.getVerticalRadius())); // apply inverse skew (aka shear) matrix matrix = matrix.multiply(Matrix.fromSkew(Angle.POS180.subtract(this.skewEastWest), - Angle.POS180.subtract(this.skewNorthSouth))); + Angle.POS180.subtract(this.skewNorthSouth))); // inverse heading - if (heading != null) + if (heading != null) { matrix = matrix.multiply(Matrix.fromRotationZ(this.heading)); + } //matrix = matrix.multiply(Matrix.fromRotationZ(this.heading)); // inverse tilt - if (tilt != null) + if (tilt != null) { matrix = matrix.multiply(Matrix.fromRotationX(this.tilt)); + } // roll - if (roll != null) + if (roll != null) { matrix = matrix.multiply(Matrix.fromRotationY(this.roll)); + } // translate and orient Position refPosition = globe.computePositionFromPoint(this.computeReferencePoint(globe, verticalExaggeration)); @@ -1231,8 +1160,7 @@ public Matrix computeRenderMatrixInverse(Globe globe, double verticalExaggeratio matrix = matrix.multiply(Matrix.fromRotationY(refPosition.getLongitude().multiply(-1.0))); // Transform to the cartesian coordinates of (latitude, longitude, metersElevation). matrix = matrix.multiply(Matrix.fromTranslation(point.multiply3(-1.0))); - */ - + */ return matrix; } @@ -1244,10 +1172,8 @@ public Matrix computeRenderMatrixInverse(Globe globe, double verticalExaggeratio * * @throws IllegalArgumentException if draw context is null or the draw context GL is null */ - protected void setModelViewMatrix(DrawContext dc) - { - if (dc.getGL() == null) - { + protected void setModelViewMatrix(DrawContext dc) { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1274,18 +1200,17 @@ protected void setModelViewMatrix(DrawContext dc) * * @param position the position to move the shape to */ - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Position oldPosition = this.getReferencePosition(); - if (oldPosition == null) + if (oldPosition == null) { return; + } setCenterPosition(position); @@ -1296,7 +1221,7 @@ public void moveTo(Position position) * Computes the number of subdivisions necessary to achieve the expected Level of Detail given the shape's * relationship to the viewer. * - * @param dc the current drawContext. + * @param dc the current drawContext. * @param shapeData the current globe-specific shape data */ abstract protected void computeSubdivisions(DrawContext dc, ShapeData shapeData); @@ -1304,7 +1229,6 @@ public void moveTo(Position position) //*****************************************************************// //*********************** Geometry Rendering ********************// //*****************************************************************// - /** * Sets the Geometry mesh for this shape, either by pulling it from the geometryCache, or by creating it anew if the * appropriate geometry does not yet exist in the cache. @@ -1313,26 +1237,23 @@ public void moveTo(Position position) */ abstract protected void makeGeometry(ShapeData shapeData); - protected GeometryBuilder getGeometryBuilder() - { + protected GeometryBuilder getGeometryBuilder() { return this.geometryBuilder; } /** * Renders the Rigid Shape * - * @param dc the current draw context + * @param dc the current draw context * @param shapeData the current shape data - * @param index the index of the shape face to render + * @param index the index of the shape face to render * * @throws IllegalArgumentException if the draw context is null or the element buffer is null */ - protected void drawGeometry(DrawContext dc, ShapeData shapeData, int index) - { + protected void drawGeometry(DrawContext dc, ShapeData shapeData, int index) { Geometry mesh = shapeData.getMesh(index); - if (mesh.getBuffer(Geometry.ELEMENT) == null) - { + if (mesh.getBuffer(Geometry.ELEMENT) == null) { String message = "nullValue.ElementBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1352,40 +1273,38 @@ protected void drawGeometry(DrawContext dc, ShapeData shapeData, int index) /** * Renders the shape, using data from the provided buffer and the given parameters. * - * @param dc the current draw context - * @param mode the render mode - * @param count the number of elements to be drawn - * @param type the data type of the elements to be drawn + * @param dc the current draw context + * @param mode the render mode + * @param count the number of elements to be drawn + * @param type the data type of the elements to be drawn * @param elementBuffer the buffer containing the list of elements to be drawn - * @param shapeData this shape's current globe-specific shape data - * @param index the index of the shape face to render + * @param shapeData this shape's current globe-specific shape data + * @param index the index of the shape face to render */ abstract protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffer elementBuffer, - ShapeData shapeData, int index); + ShapeData shapeData, int index); //*****************************************************************// //********************* VBOs *****************// //*****************************************************************// - /** * Get or create OpenGL resource IDs for the current data cache entry. *

          * A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called. * * @param index the index of the LOD whose VboID's will be retrieved. - * @param dc the current draw context. + * @param dc the current draw context. * * @return an array containing the coordinate vertex buffer ID in the first position and the index vertex buffer ID - * in the second position. + * in the second position. */ - protected int[] getVboIds(int index, DrawContext dc) - { + protected int[] getVboIds(int index, DrawContext dc) { ShapeData data = ((ShapeData) this.getCurrentData()); - if (data != null) - { + if (data != null) { Object key = data.getVboCacheKey(index); - if (key != null) + if (key != null) { return (int[]) dc.getGpuResourceCache().get(key); + } } return null; @@ -1399,10 +1318,8 @@ protected int[] getVboIds(int index, DrawContext dc) * @param dc the current draw context. */ @Override - protected void clearCachedVbos(DrawContext dc) - { - for (Integer key : ((ShapeData) this.getCurrentData()).vboCacheKeys.keySet()) - { + protected void clearCachedVbos(DrawContext dc) { + for (Integer key : ((ShapeData) this.getCurrentData()).vboCacheKeys.keySet()) { dc.getGpuResourceCache().remove(((ShapeData) this.getCurrentData()).getVboCacheKey(key)); } } @@ -1412,23 +1329,19 @@ protected void clearCachedVbos(DrawContext dc) * * @param dc the current draw context. */ - protected void fillVBO(DrawContext dc) - { + protected void fillVBO(DrawContext dc) { GL gl = dc.getGL(); ShapeData shapeData = this.getCurrentShapeData(); List meshes = shapeData.getMeshes(); // create the cacheKey for this LOD if it doesn't yet exist - if (shapeData.getVboCacheKey(getSubdivisions()) == null) - { + if (shapeData.getVboCacheKey(getSubdivisions()) == null) { shapeData.setVboCacheKey(getSubdivisions(), this.getClass().toString() + getSubdivisions()); } int[] vboIds = (int[]) dc.getGpuResourceCache().get(shapeData.getVboCacheKey(getSubdivisions())); - if (vboIds == null) - { + if (vboIds == null) { int size = 0; - for (int face = 0; face < getFaceCount(); face++) - { + for (int face = 0; face < getFaceCount(); face++) { size += meshes.get(face).getBuffer(Geometry.VERTEX).limit() * Buffers.SIZEOF_FLOAT; size += meshes.get(face).getBuffer(Geometry.ELEMENT).limit() * Buffers.SIZEOF_FLOAT; } @@ -1436,43 +1349,34 @@ protected void fillVBO(DrawContext dc) vboIds = new int[2 * getFaceCount()]; gl.glGenBuffers(vboIds.length, vboIds, 0); dc.getGpuResourceCache().put(shapeData.getVboCacheKey(getSubdivisions()), vboIds, - GpuResourceCache.VBO_BUFFERS, size); + GpuResourceCache.VBO_BUFFERS, size); shapeData.refillIndexVBO = true; } - if (shapeData.refillIndexVBO) - { - try - { - for (int face = 0; face < getFaceCount(); face++) - { + if (shapeData.refillIndexVBO) { + try { + for (int face = 0; face < getFaceCount(); face++) { IntBuffer ib = (IntBuffer) meshes.get(face).getBuffer(Geometry.ELEMENT); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboIds[2 * face + 1]); gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, ib.limit() * Buffers.SIZEOF_FLOAT, ib.rewind(), - GL.GL_DYNAMIC_DRAW); + GL.GL_DYNAMIC_DRAW); } shapeData.refillIndexVBO = false; - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); } } - try - { - for (int face = 0; face < getFaceCount(); face++) - { + try { + for (int face = 0; face < getFaceCount(); face++) { FloatBuffer vb = (FloatBuffer) meshes.get(face).getBuffer(Geometry.VERTEX); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[2 * face]); gl.glBufferData(GL.GL_ARRAY_BUFFER, vb.limit() * Buffers.SIZEOF_FLOAT, vb.rewind(), - GL.GL_STATIC_DRAW); + GL.GL_STATIC_DRAW); } - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } } @@ -1480,22 +1384,21 @@ protected void fillVBO(DrawContext dc) //*****************************************************************// //********************* Intersections *****************// //*****************************************************************// - - protected boolean isSameAsPreviousTerrain(Terrain terrain) - { - if (terrain == null || this.previousIntersectionTerrain == null || terrain != this.previousIntersectionTerrain) + protected boolean isSameAsPreviousTerrain(Terrain terrain) { + if (terrain == null || this.previousIntersectionTerrain == null || terrain != this.previousIntersectionTerrain) { return false; + } //noinspection SimplifiableIfStatement - if (terrain.getVerticalExaggeration() != this.previousIntersectionTerrain.getVerticalExaggeration()) + if (terrain.getVerticalExaggeration() != this.previousIntersectionTerrain.getVerticalExaggeration()) { return false; + } - return this.previousIntersectionGlobeStateKey != null && - terrain.getGlobe().getGlobeStateKey().equals(this.previousIntersectionGlobeStateKey); + return this.previousIntersectionGlobeStateKey != null + && terrain.getGlobe().getGlobeStateKey().equals(this.previousIntersectionGlobeStateKey); } - public void clearIntersectionGeometry() - { + public void clearIntersectionGeometry() { this.previousIntersectionGlobeStateKey = null; this.previousIntersectionShapeData = null; this.previousIntersectionTerrain = null; @@ -1507,73 +1410,73 @@ public void clearIntersectionGeometry() * used during rendering, which may be at lower level of detail than required for accurate intersection * determination. * - * @param line the line to intersect. + * @param line the line to intersect. * @param terrain the {@link Terrain} to use when computing the wedge's geometry. * * @return a list of intersections identifying where the line intersects the shape, or null if the line does not - * intersect the shape. + * intersect the shape. * * @throws InterruptedException if the operation is interrupted. * @see Terrain */ - public List intersect(Line line, Terrain terrain) throws InterruptedException - { + public List intersect(Line line, Terrain terrain) throws InterruptedException { List shapeIntersections = new ArrayList(); List faceIntersections; - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { faceIntersections = intersect(line, terrain, i); - if (faceIntersections != null) + if (faceIntersections != null) { shapeIntersections.addAll(faceIntersections); + } } return shapeIntersections; } - public List intersect(Line line, Terrain terrain, int index) throws InterruptedException - { + public List intersect(Line line, Terrain terrain, int index) throws InterruptedException { Position refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return null; + } // check that the geometry exists - if (this.getCurrentShapeData().getMesh(index).getBuffer(Geometry.VERTEX) == null) + if (this.getCurrentShapeData().getMesh(index).getBuffer(Geometry.VERTEX) == null) { return null; + } // Reuse the previously computed high-res shape data if the terrain is the same. ShapeData highResShapeData = this.isSameAsPreviousTerrain(terrain) ? this.previousIntersectionShapeData - : null; + : null; - if (highResShapeData == null) - { + if (highResShapeData == null) { highResShapeData = this.createIntersectionGeometry(terrain); - if (highResShapeData.getMesh(index) == null) + if (highResShapeData.getMesh(index) == null) { return null; + } this.previousIntersectionShapeData = highResShapeData; this.previousIntersectionTerrain = terrain; this.previousIntersectionGlobeStateKey = terrain.getGlobe().getGlobeStateKey(); } - if (highResShapeData.getExtent() != null && highResShapeData.getExtent().intersect(line) == null) + if (highResShapeData.getExtent() != null && highResShapeData.getExtent().intersect(line) == null) { return null; + } final Line localLine = new Line(line.getOrigin().subtract3(highResShapeData.getReferencePoint()), - line.getDirection()); + line.getDirection()); List shapeIntersections = new ArrayList(); - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { List intersections = new ArrayList(); this.intersect(localLine, highResShapeData, intersections, index); - if (intersections.size() == 0) + if (intersections.size() == 0) { continue; + } - for (Intersection intersection : intersections) - { + for (Intersection intersection : intersections) { Vec4 pt = intersection.getIntersectionPoint().add3(highResShapeData.getReferencePoint()); intersection.setIntersectionPoint(pt); @@ -1586,15 +1489,15 @@ public List intersect(Line line, Terrain terrain, int index) throw intersection.setObject(this); } - if (intersections.size() > 0) + if (intersections.size() > 0) { shapeIntersections.addAll(intersections); + } } return shapeIntersections; } protected void intersect(Line line, ShapeData shapeData, List intersections, int index) - throws InterruptedException - { + throws InterruptedException { IntBuffer indices = (IntBuffer) shapeData.getMesh(index).getBuffer(Geometry.ELEMENT); indices.rewind(); @@ -1602,45 +1505,45 @@ protected void intersect(Line line, ShapeData shapeData, List inte vertices.rewind(); List ti = Triangle.intersectTriangleTypes(line, vertices, indices, - GL.GL_TRIANGLES); + GL.GL_TRIANGLES); - if (ti != null && ti.size() > 0) + if (ti != null && ti.size() > 0) { intersections.addAll(ti); + } } abstract protected ShapeData createIntersectionGeometry(Terrain terrain); /** - * Returns intersections of line with the ith face of this shape, Assumes we already know the line intersects the + * Returns intersections of line with the ith face of this shape, Assumes we already know the line intersects the * shape somewhere (but perhaps not on this face) * - * @param line the line to intersect. - * @param index the index of the face to test for intersections + * @param line the line to intersect. + * @param index the index of the face to test for intersections * @param renderMatrix the current renderMatrix * * @return a list of intersections identifying where the line intersects this shape face, or null if the line does - * not intersect this face. + * not intersect this face. * * @throws InterruptedException if the operation is interrupted. */ - public List intersectFace(Line line, int index, Matrix renderMatrix) throws InterruptedException - { + public List intersectFace(Line line, int index, Matrix renderMatrix) throws InterruptedException { final Line localLine = new Line(line.getOrigin().subtract3(this.getCurrentShapeData().getReferencePoint()), - line.getDirection()); + line.getDirection()); Geometry mesh = this.getCurrentShapeData().getMesh(index); // transform the vertices from local to world coords FloatBuffer vertices = computeTransformedVertices((FloatBuffer) mesh.getBuffer(Geometry.VERTEX), - mesh.getCount(Geometry.VERTEX), renderMatrix); + mesh.getCount(Geometry.VERTEX), renderMatrix); List intersections = Triangle.intersectTriangleTypes(localLine, vertices, - (IntBuffer) mesh.getBuffer(Geometry.ELEMENT), GL.GL_TRIANGLES); + (IntBuffer) mesh.getBuffer(Geometry.ELEMENT), GL.GL_TRIANGLES); - if (intersections == null || intersections.size() == 0) + if (intersections == null || intersections.size() == 0) { return null; + } - for (Intersection intersection : intersections) - { + for (Intersection intersection : intersections) { // translate the intersection to world coordinates Vec4 pt = intersection.getIntersectionPoint().add3(this.getCurrentShapeData().getReferencePoint()); intersection.setIntersectionPoint(pt); @@ -1654,23 +1557,19 @@ public List intersectFace(Line line, int index, Matrix renderMatri //**************************************************************// //********************* Restorable *****************// //**************************************************************// - - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { // Method is invoked by subclasses to have superclass add its state and only its state this.doMyGetRestorableState(rs, context); } - private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsPosition(context, "centerPosition", this.getCenterPosition()); @@ -1686,22 +1585,17 @@ private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsImageSourceList(context, "imageSources", this.imageSources, getFaceCount()); } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -1711,61 +1605,67 @@ public void restoreState(String stateInXml) this.doRestoreState(rs, null); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Method is invoked by subclasses to have superclass add its state and only its state this.doMyRestoreState(rs, context); } - private void doMyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + private void doMyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Position positionState = rs.getStateValueAsPosition(context, "centerPosition"); - if (positionState != null) + if (positionState != null) { this.setCenterPosition(positionState); + } Double doubleState = rs.getStateValueAsDouble(context, "northSouthRadius"); - if (doubleState != null) + if (doubleState != null) { this.setNorthSouthRadius(doubleState); + } doubleState = rs.getStateValueAsDouble(context, "eastWestRadius"); - if (doubleState != null) + if (doubleState != null) { this.setEastWestRadius(doubleState); + } doubleState = rs.getStateValueAsDouble(context, "verticalRadius"); - if (doubleState != null) + if (doubleState != null) { this.setVerticalRadius(doubleState); + } doubleState = rs.getStateValueAsDouble(context, "heading"); - if (doubleState != null) + if (doubleState != null) { this.setHeading(Angle.fromDegrees(doubleState)); + } doubleState = rs.getStateValueAsDouble(context, "tilt"); - if (doubleState != null) + if (doubleState != null) { this.setTilt(Angle.fromDegrees(doubleState)); + } doubleState = rs.getStateValueAsDouble(context, "roll"); - if (doubleState != null) + if (doubleState != null) { this.setRoll(Angle.fromDegrees(doubleState)); + } doubleState = rs.getStateValueAsDouble(context, "skewNorthSouth"); - if (doubleState != null) + if (doubleState != null) { this.setSkewNorthSouth(Angle.fromDegrees(doubleState)); + } doubleState = rs.getStateValueAsDouble(context, "skewEastWest"); - if (doubleState != null) + if (doubleState != null) { this.setSkewEastWest(Angle.fromDegrees(doubleState)); + } HashMap offsetsListState = rs.getStateValueAsOffsetsList(context, "offsets"); - if (offsetsListState != null) + if (offsetsListState != null) { this.offsets = offsetsListState; + } HashMap imageSourceListState = rs.getStateValueAsImageSourceList(context, "imageSources"); - if (imageSourceListState != null) - { - for (int i = 0; i < imageSourceListState.size(); i++) - { + if (imageSourceListState != null) { + for (int i = 0; i < imageSourceListState.size(); i++) { setImageSource(i, imageSourceListState.get(i)); } } diff --git a/src/gov/nasa/worldwind/render/ScreenAnnotation.java b/src/gov/nasa/worldwind/render/ScreenAnnotation.java index 53b8ff9858..f73e969f41 100644 --- a/src/gov/nasa/worldwind/render/ScreenAnnotation.java +++ b/src/gov/nasa/worldwind/render/ScreenAnnotation.java @@ -21,19 +21,18 @@ * @see AbstractAnnotation * @see AnnotationAttributes */ -public class ScreenAnnotation extends AbstractAnnotation -{ +public class ScreenAnnotation extends AbstractAnnotation { + protected Point screenPoint; protected Position position; /** * Creates a ScreenAnnotation with the given text, at the given viewport position. * - * @param text the annotation text. + * @param text the annotation text. * @param position the annotation viewport position. */ - public ScreenAnnotation(String text, Point position) - { + public ScreenAnnotation(String text, Point position) { this.init(text, position, null, null); } @@ -41,12 +40,11 @@ public ScreenAnnotation(String text, Point position) * Creates a ScreenAnnotation with the given text, at the given viewport position. Specifiy the * Font to be used. * - * @param text the annotation text. + * @param text the annotation text. * @param position the annotation viewport position. - * @param font the Font to use. + * @param font the Font to use. */ - public ScreenAnnotation(String text, Point position, Font font) - { + public ScreenAnnotation(String text, Point position, Font font) { this.init(text, position, font, null); } @@ -54,13 +52,12 @@ public ScreenAnnotation(String text, Point position, Font font) * Creates a ScreenAnnotation with the given text, at the given viewport position. Specifiy the * Font and text Color to be used. * - * @param text the annotation text. - * @param position the annotation viewport position. - * @param font the Font to use. + * @param text the annotation text. + * @param position the annotation viewport position. + * @param font the Font to use. * @param textColor the text Color. */ - public ScreenAnnotation(String text, Point position, Font font, Color textColor) - { + public ScreenAnnotation(String text, Point position, Font font, Color textColor) { this.init(text, position, font, textColor); } @@ -68,28 +65,24 @@ public ScreenAnnotation(String text, Point position, Font font, Color textColor) * Creates a ScreenAnnotation with the given text, at the given viewport position. Specify the default * {@link AnnotationAttributes} set. * - * @param text the annotation text. + * @param text the annotation text. * @param position the annotation viewport position. * @param defaults the default {@link AnnotationAttributes} set. */ - public ScreenAnnotation(String text, Point position, AnnotationAttributes defaults) - { - if (text == null) - { + public ScreenAnnotation(String text, Point position, AnnotationAttributes defaults) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (defaults == null) - { + if (defaults == null) { String message = Logging.getMessage("nullValue.AnnotationAttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -102,17 +95,14 @@ public ScreenAnnotation(String text, Point position, AnnotationAttributes defaul this.getAttributes().setDrawOffset(new Point(0, 0)); } - private void init(String text, Point position, Font font, Color textColor) - { - if (text == null) - { + private void init(String text, Point position, Font font, Color textColor) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -131,8 +121,7 @@ private void init(String text, Point position, Font font, Color textColor) * * @return the Point where the annotation is drawn in the viewport. */ - public Point getScreenPoint() - { + public Point getScreenPoint() { return this.screenPoint; } @@ -144,19 +133,16 @@ public Point getScreenPoint() * @return the Point where the annotation is drawn in the viewport. */ @SuppressWarnings({"UnusedDeclaration"}) - protected Point getScreenPoint(DrawContext dc) - { + protected Point getScreenPoint(DrawContext dc) { return this.position != null ? this.computeAnnotationPosition(dc, this.position) : this.screenPoint; } - protected Point computeAnnotationPosition(DrawContext dc, Position pos) - { + protected Point computeAnnotationPosition(DrawContext dc, Position pos) { Vec4 surfacePoint = dc.getTerrain().getSurfacePoint(pos); - if (surfacePoint == null) - { + if (surfacePoint == null) { Globe globe = dc.getGlobe(); surfacePoint = globe.computePointFromPosition(pos.getLatitude(), pos.getLongitude(), - globe.getElevation(pos.getLatitude(), pos.getLongitude())); + globe.getElevation(pos.getLatitude(), pos.getLongitude())); } Vec4 pt = dc.getView().project(surfacePoint); @@ -169,10 +155,8 @@ protected Point computeAnnotationPosition(DrawContext dc, Position pos) * * @param position the Point where the annotation will be drawn in the viewport. */ - public void setScreenPoint(Point position) - { - if (position == null) - { + public void setScreenPoint(Point position) { + if (position == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -185,8 +169,7 @@ public void setScreenPoint(Point position) * * @return The position previously set. */ - public Position getPosition() - { + public Position getPosition() { return position; } @@ -195,20 +178,18 @@ public Position getPosition() * overrides this object's screen point and computes it anew each time this annotation is drawn. * * @param position This annotation's geographic position. May be null, in which case this annotation's screen point - * is used directly. + * is used directly. * * @see #setScreenPoint(java.awt.Point) */ - public void setPosition(Position position) - { + public void setPosition(Position position) { this.position = position; } //**************************************************************// //******************** Rendering *****************************// //**************************************************************// - protected Rectangle computeBounds(DrawContext dc) - { + protected Rectangle computeBounds(DrawContext dc) { java.awt.Dimension size = this.getPreferredSize(dc); double finalScale = this.computeScale(dc); java.awt.Point offset = this.getAttributes().getDrawOffset(); @@ -228,26 +209,24 @@ protected Rectangle computeBounds(DrawContext dc) return this.computeBoundingRectangle(frameRect, sp.x, sp.y); } - protected Point computeSize(DrawContext dc) - { + protected Point computeSize(DrawContext dc) { double finalScale = this.computeScale(dc); java.awt.Dimension size = this.getPreferredSize(dc); return new Point((int) (size.width * finalScale), (int) (size.height * finalScale)); } - protected double[] computeOffset(DrawContext dc) - { + protected double[] computeOffset(DrawContext dc) { double finalScale = this.computeScale(dc); Point offset = this.getAttributes().getDrawOffset(); - return new double[] {offset.x * finalScale, offset.y * finalScale}; + return new double[]{offset.x * finalScale, offset.y * finalScale}; } - protected void doRenderNow(DrawContext dc) - { - if (dc.isPickingMode() && this.getPickSupport() == null) + protected void doRenderNow(DrawContext dc) { + if (dc.isPickingMode() && this.getPickSupport() == null) { return; + } GL gl = dc.getGL(); gl.glDepthFunc(GL.GL_ALWAYS); @@ -261,26 +240,20 @@ protected void doRenderNow(DrawContext dc) //**************************************************************// //******************** Restorable State **********************// //**************************************************************// - /** * Returns an XML state document String describing the public attributes of this ScreenAnnotation. * * @return XML state document string describing this ScreenAnnotation. */ - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport restorableSupport = null; // Try to parse the superclass' xml state document, if it defined one. String superStateInXml = super.getRestorableState(); - if (superStateInXml != null) - { - try - { + if (superStateInXml != null) { + try { restorableSupport = RestorableSupport.parse(superStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by the superclass failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", superStateInXml); Logging.logger().severe(message); @@ -288,17 +261,17 @@ public String getRestorableState() } // Create our own state document from scratch. - if (restorableSupport == null) + if (restorableSupport == null) { restorableSupport = RestorableSupport.newRestorableSupport(); + } // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (restorableSupport == null) + if (restorableSupport == null) { return null; + } - if (this.screenPoint != null) - { + if (this.screenPoint != null) { RestorableSupport.StateObject screenPointStateObj = restorableSupport.addStateObject("screenPoint"); - if (screenPointStateObj != null) - { + if (screenPointStateObj != null) { restorableSupport.addStateValueAsDouble(screenPointStateObj, "x", this.screenPoint.getX()); restorableSupport.addStateValueAsDouble(screenPointStateObj, "y", this.screenPoint.getY()); } @@ -316,34 +289,26 @@ public String getRestorableState() * @param stateInXml an XML document String describing a ScreenAnnotation. * * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not a well - * formed XML document String. + * formed XML document String. */ - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Allow the superclass to restore it's state. - try - { + try { super.restoreState(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Superclass will log the exception. } RestorableSupport restorableSupport; - try - { + try { restorableSupport = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -353,12 +318,12 @@ public void restoreState(String stateInXml) // Restore the screenPoint property only if all parts are available. // We will not restore a partial screenPoint (for example, just the x value). RestorableSupport.StateObject screenPointStateObj = restorableSupport.getStateObject("screenPoint"); - if (screenPointStateObj != null) - { + if (screenPointStateObj != null) { Double xState = restorableSupport.getStateValueAsDouble(screenPointStateObj, "x"); Double yState = restorableSupport.getStateValueAsDouble(screenPointStateObj, "y"); - if (xState != null && yState != null) + if (xState != null && yState != null) { setScreenPoint(new Point(xState.intValue(), yState.intValue())); + } } } } diff --git a/src/gov/nasa/worldwind/render/ScreenAnnotationBalloon.java b/src/gov/nasa/worldwind/render/ScreenAnnotationBalloon.java index 166adf1b84..3780c0337a 100644 --- a/src/gov/nasa/worldwind/render/ScreenAnnotationBalloon.java +++ b/src/gov/nasa/worldwind/render/ScreenAnnotationBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.util.Logging; @@ -16,25 +15,25 @@ * @author pabercrombie * @version $Id: ScreenAnnotationBalloon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScreenAnnotationBalloon extends AbstractAnnotationBalloon implements ScreenBalloon -{ +public class ScreenAnnotationBalloon extends AbstractAnnotationBalloon implements ScreenBalloon { + protected Point screenPoint; - /** Annotation used to render the balloon. */ + /** + * Annotation used to render the balloon. + */ protected ScreenAnnotation annotation; /** * Create the balloon. * - * @param text Text to display in the balloon. May not be null. + * @param text Text to display in the balloon. May not be null. * @param point The balloon's screen point. This point is interpreted in a coordinate system with the origin at the - * upper left corner of the screen. + * upper left corner of the screen. */ - public ScreenAnnotationBalloon(String text, Point point) - { + public ScreenAnnotationBalloon(String text, Point point) { super(text); - if (point == null) - { + if (point == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -45,9 +44,10 @@ public ScreenAnnotationBalloon(String text, Point point) this.annotation = this.createAnnotation(); } - /** {@inheritDoc} */ - protected ScreenAnnotation createAnnotation() - { + /** + * {@inheritDoc} + */ + protected ScreenAnnotation createAnnotation() { ScreenAnnotation annotation = new ScreenAnnotation(this.getDecodedText(), this.screenPoint); // Don't make the balloon bigger when it is highlighted, the text looks blurry when it is scaled up. @@ -56,26 +56,28 @@ protected ScreenAnnotation createAnnotation() return annotation; } - /** {@inheritDoc} */ - protected ScreenAnnotation getAnnotation() - { + /** + * {@inheritDoc} + */ + protected ScreenAnnotation getAnnotation() { return this.annotation; } - /** {@inheritDoc} */ - protected void computePosition(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected void computePosition(DrawContext dc) { Rectangle viewport = dc.getView().getViewport(); int y = (int) viewport.getHeight() - this.screenPoint.y - 1; this.getAnnotation().setScreenPoint(new Point(this.screenPoint.x, y)); } - /** {@inheritDoc} */ - public void setScreenLocation(Point point) - { - if (point == null) - { + /** + * {@inheritDoc} + */ + public void setScreenLocation(Point point) { + if (point == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -84,9 +86,10 @@ public void setScreenLocation(Point point) this.screenPoint = point; } - /** {@inheritDoc} */ - public Point getScreenLocation() - { + /** + * {@inheritDoc} + */ + public Point getScreenLocation() { return this.screenPoint; } } diff --git a/src/gov/nasa/worldwind/render/ScreenBalloon.java b/src/gov/nasa/worldwind/render/ScreenBalloon.java index 2cd280ec75..238bcd46be 100644 --- a/src/gov/nasa/worldwind/render/ScreenBalloon.java +++ b/src/gov/nasa/worldwind/render/ScreenBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import java.awt.*; @@ -14,8 +13,8 @@ * @author pabercrombie * @version $Id: ScreenBalloon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface ScreenBalloon extends Balloon -{ +public interface ScreenBalloon extends Balloon { + /** * Get the position of the balloon on the screen. * diff --git a/src/gov/nasa/worldwind/render/ScreenBrowserBalloon.java b/src/gov/nasa/worldwind/render/ScreenBrowserBalloon.java index d4afb99ada..344bdedd9d 100644 --- a/src/gov/nasa/worldwind/render/ScreenBrowserBalloon.java +++ b/src/gov/nasa/worldwind/render/ScreenBrowserBalloon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.util.Logging; @@ -19,8 +18,8 @@ * @version $Id: ScreenBrowserBalloon.java 2148 2014-07-14 16:27:49Z tgaskins $ * @see gov.nasa.worldwind.render.AbstractBrowserBalloon */ -public class ScreenBrowserBalloon extends AbstractBrowserBalloon implements ScreenBalloon -{ +public class ScreenBrowserBalloon extends AbstractBrowserBalloon implements ScreenBalloon { + /** * Indicates this balloon's screen location. The screen location's coordinate system has its origin in the upper * left corner of the WorldWindow, with the y-axis pointing right and the x-axis pointing down. @@ -31,18 +30,16 @@ public class ScreenBrowserBalloon extends AbstractBrowserBalloon implements Scre /** * Constructs a new ScreenBrowserBalloon with the specified text content and screen location. * - * @param text the balloon's initial text content. + * @param text the balloon's initial text content. * @param point the balloon's initial screen location, in AWT coordinates (origin at upper left corner of the - * WorldWindow). + * WorldWindow). * * @throws IllegalArgumentException if either text or point are null. */ - public ScreenBrowserBalloon(String text, Point point) - { + public ScreenBrowserBalloon(String text, Point point) { super(text); - if (point == null) - { + if (point == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -52,22 +49,22 @@ public ScreenBrowserBalloon(String text, Point point) } @Override - protected OrderedBrowserBalloon createOrderedRenderable() - { + protected OrderedBrowserBalloon createOrderedRenderable() { return new OrderedBrowserBalloon(); } - /** {@inheritDoc} */ - public Point getScreenLocation() - { + /** + * {@inheritDoc} + */ + public Point getScreenLocation() { return this.screenLocation; } - /** {@inheritDoc} */ - public void setScreenLocation(Point point) - { - if (point == null) - { + /** + * {@inheritDoc} + */ + public void setScreenLocation(Point point) { + if (point == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -87,8 +84,7 @@ public void setScreenLocation(Point point) * * @param dc the current draw context. */ - protected void computeBalloonPoints(DrawContext dc, OrderedBrowserBalloon obb) - { + protected void computeBalloonPoints(DrawContext dc, OrderedBrowserBalloon obb) { this.screenOffset = null; obb.screenRect = null; obb.screenExtent = null; @@ -108,7 +104,7 @@ protected void computeBalloonPoints(DrawContext dc, OrderedBrowserBalloon obb) // Since the screen reference point is fixed, the frame appears to move relative to the reference point. int y = dc.getView().getViewport().height - this.screenLocation.y; obb.screenRect = new Rectangle(this.screenLocation.x - this.screenOffset.x, y - this.screenOffset.y, - size.width, size.height); + size.width, size.height); // Compute the screen extent as the rectangle containing the balloon's screen rectangle and its screen point. obb.screenExtent = new Rectangle(obb.screenRect); obb.screenExtent.add(this.screenLocation.x, y); @@ -122,9 +118,10 @@ protected void computeBalloonPoints(DrawContext dc, OrderedBrowserBalloon obb) obb.eyeDistance = 0; } - /** {@inheritDoc} */ - protected void setupDepthTest(DrawContext dc, OrderedBrowserBalloon obb) - { + /** + * {@inheritDoc} + */ + protected void setupDepthTest(DrawContext dc, OrderedBrowserBalloon obb) { dc.getGL().glDisable(GL.GL_DEPTH_TEST); } } diff --git a/src/gov/nasa/worldwind/render/ScreenCredit.java b/src/gov/nasa/worldwind/render/ScreenCredit.java index c809ba729a..26e806897a 100644 --- a/src/gov/nasa/worldwind/render/ScreenCredit.java +++ b/src/gov/nasa/worldwind/render/ScreenCredit.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import java.awt.*; @@ -12,8 +11,8 @@ * @author tag * @version $Id: ScreenCredit.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface ScreenCredit extends Renderable -{ +public interface ScreenCredit extends Renderable { + void setViewport(Rectangle viewport); Rectangle getViewport(); diff --git a/src/gov/nasa/worldwind/render/ScreenCreditController.java b/src/gov/nasa/worldwind/render/ScreenCreditController.java index 2dc0981613..5c6c99f209 100644 --- a/src/gov/nasa/worldwind/render/ScreenCreditController.java +++ b/src/gov/nasa/worldwind/render/ScreenCreditController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: ScreenCreditController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScreenCreditController implements Renderable, SelectListener, Disposable -{ +public class ScreenCreditController implements Renderable, SelectListener, Disposable { + private int creditWidth = 32; private int creditHeight = 32; private int leftMargin = 240; @@ -30,10 +29,8 @@ public class ScreenCreditController implements Renderable, SelectListener, Dispo private WorldWindow wwd; private boolean enabled = true; - public ScreenCreditController(WorldWindow wwd) - { - if (wwd == null) - { + public ScreenCreditController(WorldWindow wwd) { + if (wwd == null) { String msg = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -41,52 +38,50 @@ public ScreenCreditController(WorldWindow wwd) this.wwd = wwd; - if (wwd.getSceneController().getScreenCreditController() != null) + if (wwd.getSceneController().getScreenCreditController() != null) { wwd.getSceneController().getScreenCreditController().dispose(); + } wwd.getSceneController().setScreenCreditController(this); wwd.addSelectListener(this); } - public void dispose() - { + public void dispose() { wwd.removeSelectListener(this); - if (wwd.getSceneController() == this) + if (wwd.getSceneController() == this) { wwd.getSceneController().setScreenCreditController(null); + } } - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; } - public void pick(DrawContext dc, Point pickPoint) - { - if (dc == null) - { + public void pick(DrawContext dc, Point pickPoint) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isEnabled()) + if (!this.isEnabled()) { return; + } - if (dc.getScreenCredits() == null || dc.getScreenCredits().size() < 1) + if (dc.getScreenCredits() == null || dc.getScreenCredits().size() < 1) { return; + } Set> credits = dc.getScreenCredits().entrySet(); int y = dc.getView().getViewport().height - (bottomMargin + creditHeight / 2); int x = leftMargin + creditWidth / 2; - for (Map.Entry entry : credits) - { + for (Map.Entry entry : credits) { ScreenCredit credit = entry.getKey(); Rectangle viewport = new Rectangle(x, y, creditWidth, creditHeight); @@ -97,34 +92,32 @@ public void pick(DrawContext dc, Point pickPoint) } } - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc.getScreenCredits() == null || dc.getScreenCredits().size() < 1) + if (dc.getScreenCredits() == null || dc.getScreenCredits().size() < 1) { return; + } - if (!this.isEnabled()) + if (!this.isEnabled()) { return; + } Set> credits = dc.getScreenCredits().entrySet(); int y = dc.getView().getViewport().height - (bottomMargin + creditHeight / 2); int x = leftMargin + creditWidth / 2; - for (Map.Entry entry : credits) - { + for (Map.Entry entry : credits) { ScreenCredit credit = entry.getKey(); Rectangle viewport = new Rectangle(x, y, creditWidth, creditHeight); credit.setViewport(viewport); - if (entry.getValue() == dc.getFrameTimeStamp()) - { + if (entry.getValue() == dc.getFrameTimeStamp()) { Object po = dc.getPickedObjects().getTopObject(); credit.setOpacity(po != null && po instanceof ScreenCredit ? this.highlightOpacity : this.baseOpacity); credit.render(dc); @@ -134,17 +127,15 @@ public void render(DrawContext dc) } } - public void selected(SelectEvent event) - { - if (event.getMouseEvent() != null && event.getMouseEvent().isConsumed()) + public void selected(SelectEvent event) { + if (event.getMouseEvent() != null && event.getMouseEvent().isConsumed()) { return; + } Object po = event.getTopObject(); - if (po != null && po instanceof ScreenCredit) - { - if (event.getEventAction().equals(SelectEvent.LEFT_DOUBLE_CLICK)) - { + if (po != null && po instanceof ScreenCredit) { + if (event.getEventAction().equals(SelectEvent.LEFT_DOUBLE_CLICK)) { openBrowser((ScreenCredit) po); } } @@ -152,28 +143,21 @@ public void selected(SelectEvent event) private Set badURLsReported = new HashSet(); - protected void openBrowser(ScreenCredit credit) - { - if (credit.getLink() != null && credit.getLink().length() > 0) - { - try - { + protected void openBrowser(ScreenCredit credit) { + if (credit.getLink() != null && credit.getLink().length() > 0) { + try { BrowserOpener.browse(new URL(credit.getLink())); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { if (!badURLsReported.contains(credit.getLink())) // report it only once { String msg = Logging.getMessage("generic.URIInvalid", - credit.getLink() != null ? credit.getLink() : "null"); + credit.getLink() != null ? credit.getLink() : "null"); Logging.logger().warning(msg); badURLsReported.add(credit.getLink()); } - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToInvokeWebBrower for URL", - credit.getLink()); + credit.getLink()); Logging.logger().warning(msg); } } diff --git a/src/gov/nasa/worldwind/render/ScreenCreditImage.java b/src/gov/nasa/worldwind/render/ScreenCreditImage.java index 4b41aa419e..a80c85e297 100644 --- a/src/gov/nasa/worldwind/render/ScreenCreditImage.java +++ b/src/gov/nasa/worldwind/render/ScreenCreditImage.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.util.Logging; @@ -14,16 +13,14 @@ * @author tag * @version $Id: ScreenCreditImage.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScreenCreditImage extends ScreenImage implements ScreenCredit -{ +public class ScreenCreditImage extends ScreenImage implements ScreenCredit { + private String name; private String link; private Rectangle viewport; - public ScreenCreditImage(String name, Object imageSource) - { - if (imageSource == null) - { + public ScreenCreditImage(String name, Object imageSource) { + if (imageSource == null) { String msg = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -33,10 +30,8 @@ public ScreenCreditImage(String name, Object imageSource) this.setImageSource(imageSource); } - public void setViewport(Rectangle viewport) - { - if (viewport == null) - { + public void setViewport(Rectangle viewport) { + if (viewport == null) { String msg = Logging.getMessage("nullValue.ViewportIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -46,63 +41,57 @@ public void setViewport(Rectangle viewport) this.setScreenLocation(new Point(viewport.x, viewport.y)); } - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } - public Rectangle getViewport() - { + public Rectangle getViewport() { return this.viewport; } - public void setLink(String link) - { + public void setLink(String link) { this.link = link; } - public String getLink() - { + public String getLink() { return this.link; } @Override - public int getImageWidth(DrawContext dc) - { + public int getImageWidth(DrawContext dc) { return (int) this.getViewport().getWidth(); } @Override - public int getImageHeight(DrawContext dc) - { + public int getImageHeight(DrawContext dc) { return (int) this.getViewport().getHeight(); } @SuppressWarnings({"RedundantIfStatement"}) @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } ScreenCreditImage that = (ScreenCreditImage) o; - if (name != null ? !name.equals(that.name) : that.name != null) + if (name != null ? !name.equals(that.name) : that.name != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { return name != null ? name.hashCode() : 0; } } diff --git a/src/gov/nasa/worldwind/render/ScreenImage.java b/src/gov/nasa/worldwind/render/ScreenImage.java index 360cce4c91..9666c3b890 100644 --- a/src/gov/nasa/worldwind/render/ScreenImage.java +++ b/src/gov/nasa/worldwind/render/ScreenImage.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.opengl.util.texture.TextureCoords; @@ -28,8 +27,8 @@ * @author tag * @version $Id: ScreenImage.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScreenImage extends WWObjectImpl implements Renderable, Exportable -{ +public class ScreenImage extends WWObjectImpl implements Renderable, Exportable { + protected Object imageSource; protected BasicWWTexture texture; protected OrderedImage orderedImage = new OrderedImage(); @@ -67,20 +66,17 @@ public class ScreenImage extends WWObjectImpl implements Renderable, Exportable protected double dy; protected Layer pickLayer; - protected class OrderedImage implements OrderedRenderable - { - public double getDistanceFromEye() - { + protected class OrderedImage implements OrderedRenderable { + + public double getDistanceFromEye() { return 0; } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { ScreenImage.this.draw(dc); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { ScreenImage.this.draw(dc); } } @@ -98,8 +94,7 @@ public void render(DrawContext dc) * @see #getImageOffset() * @see #getScreenOffset() */ - public Point getScreenLocation() - { + public Point getScreenLocation() { return this.awtScreenLocation; } @@ -111,8 +106,7 @@ public Point getScreenLocation() * * @return the current screen position. */ - public Point getScreenLocation(DrawContext dc) - { + public Point getScreenLocation(DrawContext dc) { this.computeOffsets(dc); return this.awtScreenLocation; } @@ -122,13 +116,12 @@ public Point getScreenLocation(DrawContext dc) * is relative to the upper-left corner of the WorldWindow, and the image is centered on this location. * * @param screenLocation the screen location on which to center the image. May be null, in which case the image is - * not displayed. + * not displayed. * * @see #setScreenOffset(Offset) * @see #setImageOffset(Offset) */ - public void setScreenLocation(Point screenLocation) - { + public void setScreenLocation(Point screenLocation) { // Use units PIXELS for the X screen offset, and and INSET_PIXELS for the Y screen offset. The Offset is in // OpenGL coordinates with the origin in the lower-left corner, but the Point is in AWT coordinates with the // origin in the upper-left corner. This offset translates the origin from the lower-left to the upper-left @@ -149,8 +142,7 @@ public void setScreenLocation(Point screenLocation) * * @see #getImageOffset() */ - public Offset getScreenOffset() - { + public Offset getScreenOffset() { return screenOffset; } @@ -162,8 +154,7 @@ public Offset getScreenOffset() * * @see #setImageOffset(Offset) */ - public void setScreenOffset(Offset screenOffset) - { + public void setScreenOffset(Offset screenOffset) { this.screenOffset = screenOffset; } @@ -174,8 +165,7 @@ public void setScreenOffset(Offset screenOffset) * * @see #getScreenOffset() */ - public Offset getImageOffset() - { + public Offset getImageOffset() { return imageOffset; } @@ -186,8 +176,7 @@ public Offset getImageOffset() * * @see #setScreenOffset(Offset) */ - public void setImageOffset(Offset imageOffset) - { + public void setImageOffset(Offset imageOffset) { this.imageOffset = imageOffset; } @@ -198,8 +187,7 @@ public void setImageOffset(Offset imageOffset) * * @see #getRotationOffset() */ - public Double getRotation() - { + public Double getRotation() { return rotation; } @@ -210,8 +198,7 @@ public Double getRotation() * * @see #setRotationOffset(Offset) */ - public void setRotation(Double rotation) - { + public void setRotation(Double rotation) { this.rotation = rotation; } @@ -219,12 +206,11 @@ public void setRotation(Double rotation) * Get the point about which the image is rotated. * * @return Rotation point in image coordinates, or null if there is no rotation point set. The origin of the - * coordinate system is at the lower left corner of the image. + * coordinate system is at the lower left corner of the image. * * @see #getRotation() */ - public Offset getRotationOffset() - { + public Offset getRotationOffset() { return rotationOffset; } @@ -235,8 +221,7 @@ public Offset getRotationOffset() * * @see #setRotation(Double) */ - public void setRotationOffset(Offset rotationOffset) - { + public void setRotationOffset(Offset rotationOffset) { this.rotationOffset = rotationOffset; } @@ -245,8 +230,7 @@ public void setRotationOffset(Offset rotationOffset) * * @return Image dimension. */ - public Size getSize() - { + public Size getSize() { return size; } @@ -256,10 +240,8 @@ public Size getSize() * * @param size Image dimension. May not be null. */ - public void setSize(Size size) - { - if (size == null) - { + public void setSize(Size size) { + if (size == null) { String msg = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -275,8 +257,7 @@ public void setSize(Size size) * * @see #getImageSource() */ - public Object getImageSource() - { + public Object getImageSource() { return this.imageSource; } @@ -289,10 +270,8 @@ public Object getImageSource() * * @throws IllegalArgumentException if the imageSource is null. */ - public void setImageSource(Object imageSource) - { - if (imageSource == null) - { + public void setImageSource(Object imageSource) { + if (imageSource == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -308,20 +287,15 @@ public void setImageSource(Object imageSource) * * @return The texture, or null if the texture is not yet available. */ - protected BasicWWTexture initializeTexture() - { + protected BasicWWTexture initializeTexture() { Object imageSource = this.getImageSource(); - if (imageSource instanceof String || imageSource instanceof URL) - { + if (imageSource instanceof String || imageSource instanceof URL) { URL imageURL = WorldWind.getDataFileStore().requestFile(imageSource.toString()); - if (imageURL != null) - { + if (imageURL != null) { this.texture = new BasicWWTexture(imageURL, true); this.texture.setUseAnisotropy(false); } - } - else if (imageSource != null) - { + } else if (imageSource != null) { this.texture = new BasicWWTexture(imageSource, true); return this.texture; } @@ -335,8 +309,7 @@ else if (imageSource != null) * * @return the surface opacity. */ - public double getOpacity() - { + public double getOpacity() { return opacity; } @@ -345,8 +318,7 @@ public double getOpacity() * * @return The color for the default rectangle. */ - public Color getColor() - { + public Color getColor() { return this.color; } @@ -356,8 +328,7 @@ public Color getColor() * * @param defaultColor New color for the default rectangle. */ - public void setColor(Color defaultColor) - { + public void setColor(Color defaultColor) { this.color = defaultColor; } @@ -369,10 +340,8 @@ public void setColor(Color defaultColor) * * @throws IllegalArgumentException if the specified opacity is less than zero. */ - public void setOpacity(double opacity) - { - if (opacity < 0) - { + public void setOpacity(double opacity) { + if (opacity < 0) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -391,10 +360,8 @@ public void setOpacity(double opacity) * * @see #getSize() */ - public int getImageWidth(DrawContext dc) - { - if (dc == null) - { + public int getImageWidth(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -413,10 +380,8 @@ public int getImageWidth(DrawContext dc) * * @see #getSize() */ - public int getImageHeight(DrawContext dc) - { - if (dc == null) - { + public int getImageHeight(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -430,8 +395,7 @@ public int getImageHeight(DrawContext dc) * * @return the object identified as the picked object. */ - public Object getDelegateOwner() - { + public Object getDelegateOwner() { return delegateOwner; } @@ -440,8 +404,7 @@ public Object getDelegateOwner() * * @param delegateOwner the object included in {@link gov.nasa.worldwind.event.SelectEvent}s as the picked object. */ - public void setDelegateOwner(Object delegateOwner) - { + public void setDelegateOwner(Object delegateOwner) { this.delegateOwner = delegateOwner; } @@ -452,41 +415,33 @@ public void setDelegateOwner(Object delegateOwner) * * @param dc DrawContext into which the image will be rendered. */ - protected void computeOffsets(DrawContext dc) - { - if (dc.getFrameTimeStamp() != this.frameNumber) - { + protected void computeOffsets(DrawContext dc) { + if (dc.getFrameTimeStamp() != this.frameNumber) { final BasicWWTexture texture = this.getTexture(); final int viewportWidth = dc.getView().getViewport().width; final int viewportHeight = dc.getView().getViewport().height; // Compute image size - if (texture != null) - { + if (texture != null) { this.originalImageWidth = texture.getWidth(dc); this.originalImageHeight = texture.getHeight(dc); - } - else if (this.getImageSource() == null) // If no image source is set, draw a rectangle + } else if (this.getImageSource() == null) // If no image source is set, draw a rectangle { this.originalImageWidth = 1; this.originalImageHeight = 1; - } - else // If an image source is set, but the image is not available yet, don't draw anything + } else // If an image source is set, but the image is not available yet, don't draw anything { this.frameNumber = dc.getFrameTimeStamp(); return; } - if (this.size != null) - { + if (this.size != null) { Dimension d = this.size.compute(this.originalImageWidth, this.originalImageHeight, - viewportWidth, viewportHeight); + viewportWidth, viewportHeight); this.width = d.width; this.height = d.height; - } - else - { + } else { this.width = this.originalImageWidth; this.height = this.originalImageHeight; } @@ -495,31 +450,25 @@ else if (this.getImageSource() == null) // If no image source is set, draw a rec Offset rotationOffset = this.getRotationOffset(); // If no rotation offset is set, rotate around the center of the image. - if (rotationOffset != null) - { + if (rotationOffset != null) { // The KML specification according to both OGC and Google states that the rotation point is specified in // a coordinate system with the origin at the lower left corner of the screen (0.5, 0.5 is the center // of the screen). But Google Earth interprets the point in a coordinate system with origin at the lower // left corner of the image (0.5, 0.5 is the center of the image), so we'll do that too. Point.Double pointD = rotationOffset.computeOffset(this.width, this.height, null, null); rotationPoint = new Point((int) pointD.x, (int) pointD.y); - } - else - { + } else { this.rotationPoint = new Point(this.width, this.height); } // Compute position - if (this.screenOffset != null) - { + if (this.screenOffset != null) { // Compute the screen location in OpenGL coordinates. There is no need to convert from AWT to OpenGL // coordinates because the Offset is already in OpenGL coordinates with its origin in the lower-left // corner. Point.Double pointD = this.screenOffset.computeOffset(viewportWidth, viewportHeight, null, null); this.screenLocation = new Point((int) pointD.x, (int) (pointD.y)); - } - else - { + } else { this.screenLocation = new Point(viewportWidth / 2, viewportHeight / 2); } @@ -529,10 +478,11 @@ else if (this.getImageSource() == null) // If no image source is set, draw a rec this.awtScreenLocation = new Point(this.screenLocation.x, viewportHeight - this.screenLocation.y); Point.Double overlayPoint; - if (this.imageOffset != null) + if (this.imageOffset != null) { overlayPoint = this.imageOffset.computeOffset(this.width, this.height, null, null); - else + } else { overlayPoint = new Point.Double(this.originalImageWidth / 2.0, this.originalImageHeight / 2.0); + } this.dx = -overlayPoint.x; this.dy = -overlayPoint.y; @@ -547,38 +497,36 @@ else if (this.getImageSource() == null) // If no image source is set, draw a rec * * @return The texture or null if the texture is not yet available. */ - protected BasicWWTexture getTexture() - { - if (this.texture != null) + protected BasicWWTexture getTexture() { + if (this.texture != null) { return this.texture; - else + } else { return this.initializeTexture(); + } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { this.computeOffsets(dc); this.doRender(dc); } @SuppressWarnings({"UnusedParameters"}) - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { this.doRender(dc); } - protected void doRender(DrawContext dc) - { - if (dc.isPickingMode()) + protected void doRender(DrawContext dc) { + if (dc.isPickingMode()) { this.pickLayer = dc.getCurrentLayer(); + } dc.addOrderedRenderable(this.orderedImage); } - protected void draw(DrawContext dc) - { - if (this.screenLocation == null) + protected void draw(DrawContext dc) { + if (this.screenLocation == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -586,14 +534,13 @@ protected void draw(DrawContext dc) boolean modelviewPushed = false; boolean projectionPushed = false; - try - { + try { gl.glPushAttrib(GL2.GL_DEPTH_BUFFER_BIT - | GL2.GL_COLOR_BUFFER_BIT - | GL2.GL_ENABLE_BIT - | GL2.GL_TRANSFORM_BIT - | GL2.GL_VIEWPORT_BIT - | GL2.GL_CURRENT_BIT); + | GL2.GL_COLOR_BUFFER_BIT + | GL2.GL_ENABLE_BIT + | GL2.GL_TRANSFORM_BIT + | GL2.GL_VIEWPORT_BIT + | GL2.GL_CURRENT_BIT); attribsPushed = true; // Don't depth buffer. @@ -620,8 +567,7 @@ protected void draw(DrawContext dc) gl.glTranslated(this.screenLocation.x + this.dx, this.screenLocation.y + this.dy, 0d); Double rotation = this.getRotation(); - if (rotation != null) - { + if (rotation != null) { gl.glTranslated(rotationPoint.x, rotationPoint.y, 0); gl.glRotated(rotation, 0, 0, 1); gl.glTranslated(-rotationPoint.x, -rotationPoint.y, 0); @@ -630,32 +576,28 @@ protected void draw(DrawContext dc) double xscale = (double) this.getImageWidth(dc) / originalImageWidth; double yscale = (double) this.getImageHeight(dc) / originalImageHeight; - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Draw either an image or a filled rectangle boolean drawImage = this.getTexture() != null; gl.glEnable(GL.GL_TEXTURE_2D); - if (drawImage) - { - if (this.getTexture().bind(dc)) + if (drawImage) { + if (this.getTexture().bind(dc)) { gl.glColor4d(1d, 1d, 1d, this.opacity); - else + } else { drawImage = false; // Can't bind texture, draw rectangle instead + } } gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); - if (drawImage) - { + if (drawImage) { TextureCoords texCoords = this.getTexture().getTexCoords(); gl.glScaled(xscale * this.originalImageWidth, yscale * this.originalImageHeight, 1d); dc.drawUnitQuad(texCoords); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); - } - else - { + } else { // Set color of the rectangle that will be drawn instead of an image final Color color = this.getColor(); float[] colorRGB = color.getRGBColorComponents(null); @@ -665,46 +607,43 @@ protected void draw(DrawContext dc) gl.glScaled(xscale, yscale, 1d); dc.drawUnitQuad(); } - } - else - { + } else { this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); this.pickSupport.addPickableObject(colorCode, this.delegateOwner != null ? this.delegateOwner : this, - null, false); + null, false); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); gl.glScaled(xscale * this.originalImageWidth, yscale * this.originalImageHeight, 1d); dc.drawUnitQuad(); this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, dc.getPickPoint(), this.pickLayer); } - } - finally - { - if (projectionPushed) - { + } finally { + if (projectionPushed) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); } - if (modelviewPushed) - { + if (modelviewPushed) { gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); } - if (attribsPushed) + if (attribsPushed) { gl.glPopAttrib(); + } } } - /** {@inheritDoc} */ - public String isExportFormatSupported(String format) - { - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) + /** + * {@inheritDoc} + */ + public String isExportFormatSupported(String format) { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) { return Exportable.FORMAT_SUPPORTED; - else + } else { return Exportable.FORMAT_NOT_SUPPORTED; + } } /** @@ -719,41 +658,32 @@ public String isExportFormatSupported(String format) * * * @param mimeType MIME type of desired export format. - * @param output An object that will receive the exported data. The type of this object depends on the export - * format (see above). + * @param output An object that will receive the exported data. The type of this object depends on the export format + * (see above). * * @throws java.io.IOException If an exception occurs writing to the output object. */ - public void export(String mimeType, Object output) throws IOException - { - if (mimeType == null) - { + public void export(String mimeType, Object output) throws IOException { + if (mimeType == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output == null) - { + if (output == null) { String message = Logging.getMessage("nullValue.OutputBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) - { - try - { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { + try { exportAsKML(output); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { Logging.logger().throwing(getClass().getName(), "export", e); throw new IOException(e); } - } - else - { + } else { String message = Logging.getMessage("Export.UnsupportedFormat", mimeType); Logging.logger().warning(message); throw new UnsupportedOperationException(message); @@ -770,31 +700,24 @@ public void export(String mimeType, Object output) throws IOException * @param output Object to receive the generated KML. * * @throws XMLStreamException If an exception occurs while writing the KML - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -808,26 +731,23 @@ else if (output instanceof OutputStream) String imgSrcString = null; Object imageSource = this.getImageSource(); - if (imageSource instanceof String) + if (imageSource instanceof String) { imgSrcString = (String) imageSource; - else if (imageSource instanceof URL) + } else if (imageSource instanceof URL) { imgSrcString = imageSource.toString(); + } // We can only export a link to the image if the image source is a path or URL. - if (imgSrcString != null) - { + if (imgSrcString != null) { xmlWriter.writeStartElement("Icon"); xmlWriter.writeStartElement("href"); xmlWriter.writeCharacters(imgSrcString); xmlWriter.writeEndElement(); // href xmlWriter.writeEndElement(); // Icon - } - else - { + } else { // No image string, try to export the color Color color = this.getColor(); - if (color != null) - { + if (color != null) { xmlWriter.writeStartElement("color"); xmlWriter.writeCharacters(KMLExportUtil.stripHexPrefix(WWUtil.encodeColorABGR(color))); xmlWriter.writeEndElement(); @@ -838,8 +758,7 @@ else if (imageSource instanceof URL) KMLExportUtil.exportOffset(xmlWriter, this.getScreenOffset(), "screenXY"); Double rotation = this.getRotation(); - if (rotation != null) - { + if (rotation != null) { xmlWriter.writeStartElement("rotation"); xmlWriter.writeCharacters(rotation.toString()); xmlWriter.writeEndElement(); // rotation @@ -852,7 +771,8 @@ else if (imageSource instanceof URL) xmlWriter.writeEndElement(); // ScreenOverlay xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } } diff --git a/src/gov/nasa/worldwind/render/ScreenRelativeAnnotation.java b/src/gov/nasa/worldwind/render/ScreenRelativeAnnotation.java index 33b8e07b4c..31e013f328 100644 --- a/src/gov/nasa/worldwind/render/ScreenRelativeAnnotation.java +++ b/src/gov/nasa/worldwind/render/ScreenRelativeAnnotation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.util.*; @@ -22,8 +21,8 @@ * @author tag * @version $Id: ScreenRelativeAnnotation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScreenRelativeAnnotation extends ScreenAnnotation -{ +public class ScreenRelativeAnnotation extends ScreenAnnotation { + private static Point DUMMY_POINT = new Point(); private double xFraction; @@ -35,25 +34,23 @@ public class ScreenRelativeAnnotation extends ScreenAnnotation /** * Create an annotation with spedified text and relative position. * - * @param text the text to display in the annotation. + * @param text the text to display in the annotation. * @param xFraction the relative X position of the annotation. A value of 0 indicates the window's left edge, a - * value of 1 indicates its right edge. The annotation is centered horizontally on this position - * prior to applying any X offest specified in the annotation's attributes. + * value of 1 indicates its right edge. The annotation is centered horizontally on this position prior to applying + * any X offest specified in the annotation's attributes. * @param yFraction the relative Y position of the annotation. A value of 0 indicates the window's bottom edge, a - * value of 1 indicates the window's top edge. The annotation's lower edge is justified to this - * position prior to applying any Y offset specified in the annotation's attributes. + * value of 1 indicates the window's top edge. The annotation's lower edge is justified to this position prior to + * applying any Y offset specified in the annotation's attributes. * * @throws IllegalArgumentException if the text string is null. */ - public ScreenRelativeAnnotation(String text, double xFraction, double yFraction) - { + public ScreenRelativeAnnotation(String text, double xFraction, double yFraction) { super(text, DUMMY_POINT); this.init(xFraction, yFraction); } - private void init(double xFraction, double yFraction) - { + private void init(double xFraction, double yFraction) { this.xFraction = xFraction; this.yFraction = yFraction; } @@ -63,8 +60,7 @@ private void init(double xFraction, double yFraction) * * @return true if annotation is kept fully visible, otherwise false. */ - public boolean isKeepFullyVisible() - { + public boolean isKeepFullyVisible() { return this.keepFullyVisible; } @@ -75,8 +71,7 @@ public boolean isKeepFullyVisible() * * @param keepFullyVisible true to keep the annotation fully visible, otherwise false. */ - public void setKeepFullyVisible(boolean keepFullyVisible) - { + public void setKeepFullyVisible(boolean keepFullyVisible) { this.keepFullyVisible = keepFullyVisible; } @@ -85,8 +80,7 @@ public void setKeepFullyVisible(boolean keepFullyVisible) * * @return the annotation's relative X position, as specified to the constructor or {@link #setXFraction(double)}. */ - public double getXFraction() - { + public double getXFraction() { return this.xFraction; } @@ -96,8 +90,7 @@ public double getXFraction() * * @param xFraction the annotation's relative X position. */ - public void setXFraction(double xFraction) - { + public void setXFraction(double xFraction) { this.xFraction = xFraction; } @@ -106,8 +99,7 @@ public void setXFraction(double xFraction) * * @return the annotation's relative Y position, as specified to the constructor or {@link #setYFraction(double)}. */ - public double getYFraction() - { + public double getYFraction() { return this.yFraction; } @@ -117,8 +109,7 @@ public double getYFraction() * * @param yFraction the annotation's relative Y position. */ - public void setYFraction(double yFraction) - { + public void setYFraction(double yFraction) { this.yFraction = yFraction; } @@ -127,8 +118,7 @@ public void setYFraction(double yFraction) * * @return the annotation's X margin, in pixels. */ - public int getXMargin() - { + public int getXMargin() { return this.xMargin; } @@ -138,8 +128,7 @@ public int getXMargin() * * @param xMargin the X margin, in pixels. */ - public void setXMargin(int xMargin) - { + public void setXMargin(int xMargin) { this.xMargin = xMargin; } @@ -148,8 +137,7 @@ public void setXMargin(int xMargin) * * @return the annotation's Y margin, in pixels. */ - public int getYMargin() - { + public int getYMargin() { return this.yMargin; } @@ -159,8 +147,7 @@ public int getYMargin() * * @param yMargin the Y margin, in pixels. */ - public void setYMargin(int yMargin) - { + public void setYMargin(int yMargin) { this.yMargin = yMargin; } @@ -169,11 +156,10 @@ public void setYMargin(int yMargin) * and the current window size. * * @return the pixel coordinates corresponding to the annotation's relative coordinates. The pixel coordinate origin - * is the lower left of the window. + * is the lower left of the window. */ @Override - protected Point getScreenPoint(DrawContext dc) - { + protected Point getScreenPoint(DrawContext dc) { Rectangle vp = dc.getView().getViewport(); double x = vp.getX() + this.xFraction * vp.getWidth(); @@ -182,8 +168,7 @@ protected Point getScreenPoint(DrawContext dc) Point size = this.computeSize(dc); double[] offset = this.computeOffset(dc); - if (this.keepFullyVisible) - { + if (this.keepFullyVisible) { // Compute the eventual screen position double xx = x - size.x / 2 + offset[0]; double yy = y + offset[1]; @@ -192,17 +177,21 @@ protected Point getScreenPoint(DrawContext dc) double dE = (vp.x + vp.getWidth()) - (xx + size.x + this.xMargin); double dN = (vp.y + vp.getHeight()) - (yy + size.y + this.yMargin); - if (dE < 0) + if (dE < 0) { x += dE; + } - if (xx < vp.x + xMargin) + if (xx < vp.x + xMargin) { x = vp.x + this.xMargin + size.x / 2; + } - if (dN < 0) + if (dN < 0) { y += dN; + } - if (yy < vp.y + this.yMargin) + if (yy < vp.y + this.yMargin) { y = vp.y + this.yMargin; + } } Point p = new Point((int) x, (int) y); @@ -214,26 +203,20 @@ protected Point getScreenPoint(DrawContext dc) //**************************************************************// //******************** Restorable State **********************// //**************************************************************// - /** * Returns an XML state document String describing the public attributes of this ScreenAnnotation. * * @return XML state document string describing this ScreenAnnotation. */ - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport restorableSupport = null; // Try to parse the superclass' xml state document, if it defined one. String superStateInXml = super.getRestorableState(); - if (superStateInXml != null) - { - try - { + if (superStateInXml != null) { + try { restorableSupport = RestorableSupport.parse(superStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by the superclass failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", superStateInXml); Logging.logger().severe(message); @@ -241,11 +224,13 @@ public String getRestorableState() } // Create our own state document from scratch. - if (restorableSupport == null) + if (restorableSupport == null) { restorableSupport = RestorableSupport.newRestorableSupport(); + } // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (restorableSupport == null) + if (restorableSupport == null) { return null; + } restorableSupport.addStateValueAsDouble("xFraction", this.getXFraction()); restorableSupport.addStateValueAsDouble("yFraction", this.getYFraction()); @@ -267,34 +252,26 @@ public String getRestorableState() * @param stateInXml an XML document String describing a ScreenAnnotation. * * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not a well - * formed XML document String. + * formed XML document String. */ - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Allow the superclass to restore it's state. - try - { + try { super.restoreState(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Superclass will log the exception. } RestorableSupport restorableSupport; - try - { + try { restorableSupport = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -302,23 +279,28 @@ public void restoreState(String stateInXml) } Double xFractionRS = restorableSupport.getStateValueAsDouble("xFraction"); - if (xFractionRS != null) + if (xFractionRS != null) { this.setXFraction(xFractionRS); + } Double yFractionRS = restorableSupport.getStateValueAsDouble("yFraction"); - if (xFractionRS != null) + if (xFractionRS != null) { this.setYFraction(yFractionRS); + } Integer xMarginRS = restorableSupport.getStateValueAsInteger("xMargin"); - if (xFractionRS != null) + if (xFractionRS != null) { this.setXMargin(xMarginRS); + } Integer yMarginRS = restorableSupport.getStateValueAsInteger("yMargin"); - if (xFractionRS != null) + if (xFractionRS != null) { this.setYMargin(yMarginRS); + } Boolean keepVisibleRS = restorableSupport.getStateValueAsBoolean("keepFullyVisible"); - if (keepVisibleRS != null) + if (keepVisibleRS != null) { this.setKeepFullyVisible(keepVisibleRS); + } } } diff --git a/src/gov/nasa/worldwind/render/ShapeAttributes.java b/src/gov/nasa/worldwind/render/ShapeAttributes.java index 4d61e0008f..571332bd6c 100644 --- a/src/gov/nasa/worldwind/render/ShapeAttributes.java +++ b/src/gov/nasa/worldwind/render/ShapeAttributes.java @@ -18,8 +18,8 @@ * @author dcollins * @version $Id: ShapeAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface ShapeAttributes extends Exportable -{ +public interface ShapeAttributes extends Exportable { + /** * Returns a new ShapeAttributes instance of the same type as this ShapeAttributes who's properties are configured * exactly as this ShapeAttributes. @@ -52,7 +52,7 @@ public interface ShapeAttributes extends Exportable * attributes knows that the attributes are complete when unresolved is false. * * @param unresolved true to specify that one or more attributes are unresolved, otherwise - * false. + * false. * * @see #isUnresolved() */ @@ -315,7 +315,7 @@ public interface ShapeAttributes extends Exportable * shape is rendered. * * @param imageSource the source of the shape's texture, either a String path, a URL, a - * BufferedImage, or null. + * BufferedImage, or null. * * @see #getImageSource() */ @@ -324,8 +324,8 @@ public interface ShapeAttributes extends Exportable /** * Indicates the amount the shape's texture is scaled by as a floating-point value. * - * @return the amount the shape's texture is scaled by as a floating-point value. This value is always greater - * than zero. + * @return the amount the shape's texture is scaled by as a floating-point value. This value is always greater than + * zero. * * @see #setImageScale(double) */ diff --git a/src/gov/nasa/worldwind/render/Size.java b/src/gov/nasa/worldwind/render/Size.java index f3694bd3f0..60a9334180 100644 --- a/src/gov/nasa/worldwind/render/Size.java +++ b/src/gov/nasa/worldwind/render/Size.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.avlist.AVKey; @@ -42,12 +41,16 @@ * @author pabercrombie * @version $Id: Size.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Size -{ - /** Size mode to indicate that the content's native dimension must be used. */ +public class Size { + + /** + * Size mode to indicate that the content's native dimension must be used. + */ public static final String NATIVE_DIMENSION = "gov.nasa.worldwind.render.Size.NativeDimension"; - /** Size mode to indicate that the content's aspect ratio must be maintained. */ + /** + * Size mode to indicate that the content's aspect ratio must be maintained. + */ public static final String MAINTAIN_ASPECT_RATIO = "gov.nasa.worldwind.render.Size.MaintainAspectRatio"; /** @@ -61,9 +64,13 @@ public class Size * #EXPLICIT_DIMENSION}. */ protected String widthMode = NATIVE_DIMENSION; - /** Units of width. */ + /** + * Units of width. + */ protected String widthUnits = AVKey.PIXELS; - /** Width size parameter. */ + /** + * Width size parameter. + */ protected double widthParam; /** @@ -71,24 +78,29 @@ public class Size * #EXPLICIT_DIMENSION}. */ protected String heightMode = NATIVE_DIMENSION; - /** Units of height. */ + /** + * Units of height. + */ protected String heightUnits = AVKey.PIXELS; - /** Height size parameter. */ + /** + * Height size parameter. + */ protected double heightParam; - /** Create a Size object that will preserve native dimensions. */ - public Size() - { + /** + * Create a Size object that will preserve native dimensions. + */ + public Size() { } /** * Create a Size with specified dimensions. * - * @param widthMode Width mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link + * @param widthMode Width mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link * #EXPLICIT_DIMENSION}. - * @param widthParam The width (applies only to {@link #EXPLICIT_DIMENSION} mode). - * @param widthUnits Units of {@code width}. Either {@link AVKey#PIXELS} or {@link AVKey#PIXELS}. - * @param heightMode height mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link + * @param widthParam The width (applies only to {@link #EXPLICIT_DIMENSION} mode). + * @param widthUnits Units of {@code width}. Either {@link AVKey#PIXELS} or {@link AVKey#PIXELS}. + * @param heightMode height mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link * #EXPLICIT_DIMENSION}. * @param heightParam The height (applies only to {@link #EXPLICIT_DIMENSION} mode). * @param heightUnits Units of {@code height}. Either {@link AVKey#PIXELS} or {@link AVKey#PIXELS}. @@ -97,8 +109,7 @@ public Size() * @see #setHeight(String, double, String) */ public Size(String widthMode, double widthParam, String widthUnits, String heightMode, double heightParam, - String heightUnits) - { + String heightUnits) { this.setWidth(widthMode, widthParam, widthUnits); this.setHeight(heightMode, heightParam, heightUnits); } @@ -106,45 +117,41 @@ public Size(String widthMode, double widthParam, String widthUnits, String heigh /** * Create a size from explicit pixel dimensions. * - * @param widthInPixels Width of rectangle in pixels. + * @param widthInPixels Width of rectangle in pixels. * @param heightInPixels Height of rectangle in pixels. * * @return New size object. */ - public static Size fromPixels(int widthInPixels, int heightInPixels) - { + public static Size fromPixels(int widthInPixels, int heightInPixels) { return new Size(EXPLICIT_DIMENSION, widthInPixels, AVKey.PIXELS, - EXPLICIT_DIMENSION, heightInPixels, AVKey.PIXELS); + EXPLICIT_DIMENSION, heightInPixels, AVKey.PIXELS); } /** * Creates a new size from explicit fraction dimensions. * - * @param widthFraction the size's width as a fraction of the containing rectangle. + * @param widthFraction the size's width as a fraction of the containing rectangle. * @param heightFraction the size's height as a fraction of the containing rectangle. * * @return a new size with the specified width and height. */ - public static Size fromFraction(double widthFraction, double heightFraction) - { + public static Size fromFraction(double widthFraction, double heightFraction) { return new Size(EXPLICIT_DIMENSION, widthFraction, AVKey.FRACTION, - EXPLICIT_DIMENSION, heightFraction, AVKey.FRACTION); + EXPLICIT_DIMENSION, heightFraction, AVKey.FRACTION); } /** * Set the width. * - * @param mode Width mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link + * @param mode Width mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link * #EXPLICIT_DIMENSION}. * @param width The width (applies only to {@link #EXPLICIT_DIMENSION} mode). * @param units Units of {@code width}. Either {@link AVKey#PIXELS} or {@link AVKey#PIXELS}. * * @throws IllegalArgumentException if {@code mode} is null. */ - public void setWidth(String mode, double width, String units) - { - if (mode == null) - { + public void setWidth(String mode, double width, String units) { + if (mode == null) { String message = Logging.getMessage("nullValue.SizeModeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -158,17 +165,15 @@ public void setWidth(String mode, double width, String units) /** * Set the height. * - * @param mode Width mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link + * @param mode Width mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link * #EXPLICIT_DIMENSION}. * @param height The width (applies only to {@link #EXPLICIT_DIMENSION} mode). - * @param units Units of {@code width}. Either {@link AVKey#PIXELS} or {@link AVKey#FRACTION}. + * @param units Units of {@code width}. Either {@link AVKey#PIXELS} or {@link AVKey#FRACTION}. * * @throws IllegalArgumentException if {@code mode} is null. */ - public void setHeight(String mode, double height, String units) - { - if (mode == null) - { + public void setHeight(String mode, double height, String units) { + if (mode == null) { String message = Logging.getMessage("nullValue.SizeModeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -185,8 +190,7 @@ public void setHeight(String mode, double height, String units) * * @return the units of the offset X value, or null. */ - public String getWidthUnits() - { + public String getWidthUnits() { return widthUnits; } @@ -196,8 +200,7 @@ public String getWidthUnits() * * @return the units of the offset Y value, or null. */ - public String getHeightUnits() - { + public String getHeightUnits() { return heightUnits; } @@ -207,8 +210,7 @@ public String getHeightUnits() * @return Width mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link * #EXPLICIT_DIMENSION}. */ - public String getWidthMode() - { + public String getWidthMode() { return this.widthMode; } @@ -218,8 +220,7 @@ public String getWidthMode() * @return Height mode, one of {@link #NATIVE_DIMENSION}, {@link #MAINTAIN_ASPECT_RATIO}, or {@link * #EXPLICIT_DIMENSION}. */ - public String getHeightMode() - { + public String getHeightMode() { return this.heightMode; } @@ -231,8 +232,7 @@ public String getHeightMode() * @see #getWidthMode() * @see #getWidthUnits() */ - public double getWidth() - { + public double getWidth() { return widthParam; } @@ -244,56 +244,51 @@ public double getWidth() * @see #getHeightMode() * @see #getHeightUnits() */ - public double getHeight() - { + public double getHeight() { return heightParam; } /** * Computes the width and height of a rectangle within a container rectangle. * - * @param rectWidth The width of the rectangle to size. - * @param rectHeight The height of the rectangle to size. - * @param containerWidth The width of the container. + * @param rectWidth The width of the rectangle to size. + * @param rectHeight The height of the rectangle to size. + * @param containerWidth The width of the container. * @param containerHeight The height of the container. * * @return The desired image dimensions. */ - public Dimension compute(int rectWidth, int rectHeight, int containerWidth, int containerHeight) - { - if (rectWidth < 0) - { + public Dimension compute(int rectWidth, int rectHeight, int containerWidth, int containerHeight) { + if (rectWidth < 0) { String message = Logging.getMessage("generic.InvalidWidth", rectWidth); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rectHeight < 0) - { + if (rectHeight < 0) { String message = Logging.getMessage("generic.InvalidHeight", rectHeight); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (containerWidth < 0) - { + if (containerWidth < 0) { String message = Logging.getMessage("generic.InvalidWidth", containerWidth); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (containerHeight < 0) - { + if (containerHeight < 0) { String message = Logging.getMessage("generic.InvalidHeight", containerHeight); Logging.logger().severe(message); throw new IllegalArgumentException(message); } double aspectRatio; - if (rectHeight != 0) + if (rectHeight != 0) { aspectRatio = (double) rectWidth / rectHeight; - else + } else { aspectRatio = 0; + } String xMode = this.getWidthMode(); String yMode = this.getHeightMode(); @@ -301,40 +296,36 @@ public Dimension compute(int rectWidth, int rectHeight, int containerWidth, int double width, height; if (NATIVE_DIMENSION.equals(xMode) && NATIVE_DIMENSION.equals(yMode) - || NATIVE_DIMENSION.equals(xMode) && MAINTAIN_ASPECT_RATIO.equals(yMode) - || MAINTAIN_ASPECT_RATIO.equals(xMode) && NATIVE_DIMENSION.equals(yMode) - || MAINTAIN_ASPECT_RATIO.equals(xMode) && MAINTAIN_ASPECT_RATIO.equals(yMode)) - { + || NATIVE_DIMENSION.equals(xMode) && MAINTAIN_ASPECT_RATIO.equals(yMode) + || MAINTAIN_ASPECT_RATIO.equals(xMode) && NATIVE_DIMENSION.equals(yMode) + || MAINTAIN_ASPECT_RATIO.equals(xMode) && MAINTAIN_ASPECT_RATIO.equals(yMode)) { // Keep original dimensions width = rectWidth; height = rectHeight; - } - else if (MAINTAIN_ASPECT_RATIO.equals(xMode)) - { + } else if (MAINTAIN_ASPECT_RATIO.equals(xMode)) { // y dimension is specified, scale x to maintain aspect ratio height = computeSize(this.heightParam, this.heightUnits, containerHeight); width = height * aspectRatio; - } - else if (MAINTAIN_ASPECT_RATIO.equals(yMode)) - { + } else if (MAINTAIN_ASPECT_RATIO.equals(yMode)) { // x dimension is specified, scale y to maintain aspect ratio width = computeSize(this.widthParam, this.widthUnits, containerWidth); - if (aspectRatio != 0) + if (aspectRatio != 0) { height = width / aspectRatio; - else + } else { height = 0; - } - else - { - if (NATIVE_DIMENSION.equals(xMode)) + } + } else { + if (NATIVE_DIMENSION.equals(xMode)) { width = rectWidth; - else + } else { width = computeSize(this.widthParam, this.widthUnits, containerWidth); + } - if (NATIVE_DIMENSION.equals(yMode)) + if (NATIVE_DIMENSION.equals(yMode)) { height = rectHeight; - else + } else { height = computeSize(this.heightParam, this.heightUnits, containerHeight); + } } return new Dimension((int) width, (int) height); @@ -343,59 +334,58 @@ else if (MAINTAIN_ASPECT_RATIO.equals(yMode)) /** * Compute a dimension taking into account the units of the dimension. * - * @param size The size parameter. - * @param units One of {@link AVKey#PIXELS} or {@link AVKey#FRACTION}. If the {@code units} value is - * not one of the expected options, {@link AVKey#PIXELS} is used as the default. + * @param size The size parameter. + * @param units One of {@link AVKey#PIXELS} or {@link AVKey#FRACTION}. If the {@code units} value is not one of the + * expected options, {@link AVKey#PIXELS} is used as the default. * @param containerDimension The viewport dimension. * * @return Size in pixels */ - protected double computeSize(double size, String units, double containerDimension) - { - if (AVKey.FRACTION.equals(units)) + protected double computeSize(double size, String units, double containerDimension) { + if (AVKey.FRACTION.equals(units)) { return size * containerDimension; - else // Default to pixel + } else // Default to pixel + { return size; + } } /** * Saves the size's current state in the specified restorableSupport. If context is not - * null, the state is appended to it. Otherwise the state is added to the + * null, the state is appended to it. Otherwise the state is added to the * RestorableSupport root. This state can be restored later by calling {@link * #restoreState(gov.nasa.worldwind.util.RestorableSupport, gov.nasa.worldwind.util.RestorableSupport.StateObject)}. * * @param restorableSupport the RestorableSupport that receives the size's state. - * @param context the StateObject the state is appended to, if not null. + * @param context the StateObject the state is appended to, if not null. * * @throws IllegalArgumentException if restorableSupport is null. */ - public void getRestorableState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) - { - if (restorableSupport == null) - { + public void getRestorableState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) { + if (restorableSupport == null) { String message = Logging.getMessage("nullValue.RestorableSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject so = restorableSupport.addStateObject(context, "width"); - if (so != null) - { + if (so != null) { restorableSupport.addStateValueAsString(so, "mode", this.getWidthMode()); restorableSupport.addStateValueAsDouble(so, "param", this.getWidth()); - if (this.getWidthUnits() != null) + if (this.getWidthUnits() != null) { restorableSupport.addStateValueAsString(so, "units", this.getWidthUnits()); + } } so = restorableSupport.addStateObject(context, "height"); - if (so != null) - { + if (so != null) { restorableSupport.addStateValueAsString(so, "mode", this.getHeightMode()); restorableSupport.addStateValueAsDouble(so, "param", this.getHeight()); - if (this.getHeightUnits() != null) + if (this.getHeightUnits() != null) { restorableSupport.addStateValueAsString(so, "units", this.getHeightUnits()); + } } } @@ -405,22 +395,19 @@ public void getRestorableState(RestorableSupport restorableSupport, RestorableSu * RestorableSupport root is searched. * * @param restorableSupport the RestorableSupport that contains the size's state. - * @param context the StateObject to search for state values, if not null. + * @param context the StateObject to search for state values, if not null. * * @throws IllegalArgumentException if restorableSupport is null. */ - public void restoreState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) - { - if (restorableSupport == null) - { + public void restoreState(RestorableSupport restorableSupport, RestorableSupport.StateObject context) { + if (restorableSupport == null) { String message = Logging.getMessage("nullValue.RestorableSupportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport.StateObject so = restorableSupport.getStateObject(context, "width"); - if (so != null) - { + if (so != null) { String mode = restorableSupport.getStateValueAsString(so, "mode"); mode = convertLegacyModeString(mode); @@ -428,13 +415,13 @@ public void restoreState(RestorableSupport restorableSupport, RestorableSupport. String units = restorableSupport.getStateValueAsString(so, "units"); // Restore the width only when the mode and param are specified. null is an acceptable value for units. - if (mode != null && param != null) + if (mode != null && param != null) { this.setWidth(mode, param, units); + } } so = restorableSupport.getStateObject(context, "height"); - if (so != null) - { + if (so != null) { String mode = restorableSupport.getStateValueAsString(so, "mode"); mode = convertLegacyModeString(mode); @@ -442,8 +429,9 @@ public void restoreState(RestorableSupport restorableSupport, RestorableSupport. String units = restorableSupport.getStateValueAsString(so, "units"); // Restore the height only when the mode and param are specified. null is an acceptable value for units. - if (mode != null && param != null) + if (mode != null && param != null) { this.setHeight(mode, param, units); + } } } @@ -457,48 +445,54 @@ public void restoreState(RestorableSupport restorableSupport, RestorableSupport. * * @return a size mode constant, or the input string if string is not a legacy size mode. */ - protected String convertLegacyModeString(String string) - { - if ("NativeDimension".equals(string)) + protected String convertLegacyModeString(String string) { + if ("NativeDimension".equals(string)) { return NATIVE_DIMENSION; - else if ("MaintainAspectRatio".equals(string)) + } else if ("MaintainAspectRatio".equals(string)) { return MAINTAIN_ASPECT_RATIO; - else if ("ExplicitDimension".equals(string)) + } else if ("ExplicitDimension".equals(string)) { return EXPLICIT_DIMENSION; - else + } else { return string; + } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } Size that = (Size) o; - if (Double.compare(this.widthParam, that.widthParam) != 0) + if (Double.compare(this.widthParam, that.widthParam) != 0) { return false; - if (Double.compare(this.heightParam, that.heightParam) != 0) + } + if (Double.compare(this.heightParam, that.heightParam) != 0) { return false; - if (this.widthUnits != null ? !this.widthUnits.equals(that.widthUnits) : that.widthUnits != null) + } + if (this.widthUnits != null ? !this.widthUnits.equals(that.widthUnits) : that.widthUnits != null) { return false; - if (this.heightUnits != null ? !this.heightUnits.equals(that.heightUnits) : that.heightUnits != null) + } + if (this.heightUnits != null ? !this.heightUnits.equals(that.heightUnits) : that.heightUnits != null) { return false; - if (this.widthMode != null ? !this.widthMode.equals(that.widthMode) : that.widthMode != null) + } + if (this.widthMode != null ? !this.widthMode.equals(that.widthMode) : that.widthMode != null) { return false; + } //noinspection RedundantIfStatement - if (this.heightMode != null ? !this.heightMode.equals(that.heightMode) : that.heightMode != null) + if (this.heightMode != null ? !this.heightMode.equals(that.heightMode) : that.heightMode != null) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; long temp; temp = this.widthParam != +0.0d ? Double.doubleToLongBits(this.widthParam) : 0L; diff --git a/src/gov/nasa/worldwind/render/SurfaceCircle.java b/src/gov/nasa/worldwind/render/SurfaceCircle.java index 715dd2df64..ef76d0ba61 100644 --- a/src/gov/nasa/worldwind/render/SurfaceCircle.java +++ b/src/gov/nasa/worldwind/render/SurfaceCircle.java @@ -12,11 +12,12 @@ * @author dcollins * @version $Id: SurfaceCircle.java 2302 2014-09-08 20:40:47Z tgaskins $ */ -public class SurfaceCircle extends SurfaceEllipse -{ - /** Constructs a new surface circle with the default attributes, default center location and default radius. */ - public SurfaceCircle() - { +public class SurfaceCircle extends SurfaceEllipse { + + /** + * Constructs a new surface circle with the default attributes, default center location and default radius. + */ + public SurfaceCircle() { } /** @@ -24,8 +25,7 @@ public SurfaceCircle() * * @param source the shape to copy. */ - public SurfaceCircle(SurfaceCircle source) - { + public SurfaceCircle(SurfaceCircle source) { super(source); } @@ -36,8 +36,7 @@ public SurfaceCircle(SurfaceCircle source) * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public SurfaceCircle(ShapeAttributes normalAttrs) - { + public SurfaceCircle(ShapeAttributes normalAttrs) { super(normalAttrs); } @@ -50,8 +49,7 @@ public SurfaceCircle(ShapeAttributes normalAttrs) * * @throws IllegalArgumentException if the center is null, or if the radius is negative. */ - public SurfaceCircle(LatLon center, double radius) - { + public SurfaceCircle(LatLon center, double radius) { super(center, radius, radius); } @@ -59,15 +57,14 @@ public SurfaceCircle(LatLon center, double radius) * Constructs a new surface circle with the default attributes, the specified center location, radius (in meters), * and initial number of geometry intervals. * - * @param center the circle's center location. - * @param radius the circle's radius, in meters. + * @param center the circle's center location. + * @param radius the circle's radius, in meters. * @param intervals the initial number of intervals (or slices) defining the circle's geometry. * * @throws IllegalArgumentException if the center is null, if the radius is negative, or if the number of intervals - * is less than 8. + * is less than 8. */ - public SurfaceCircle(LatLon center, double radius, int intervals) - { + public SurfaceCircle(LatLon center, double radius, int intervals) { super(center, radius, radius, Angle.ZERO, intervals); } @@ -77,43 +74,38 @@ public SurfaceCircle(LatLon center, double radius, int intervals) * this shape's appearance to change accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the circle's center location. - * @param radius the circle's radius, in meters. + * @param center the circle's center location. + * @param radius the circle's radius, in meters. * * @throws IllegalArgumentException if the center is null, or if the radius is negative. */ - public SurfaceCircle(ShapeAttributes normalAttrs, LatLon center, double radius) - { + public SurfaceCircle(ShapeAttributes normalAttrs, LatLon center, double radius) { super(normalAttrs, center, radius, radius); } /** * Constructs a new surface circle with the specified normal (as opposed to highlight) attributes, the specified - * center location, radius (in meters), and initial number of geometry intervals. Modifying the attribute reference + * center location, radius (in meters), and initial number of geometry intervals. Modifying the attribute reference * after calling this constructor causes this shape's appearance to change accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the circle's center location. - * @param radius the circle's radius, in meters. - * @param intervals the initial number of intervals (or slices) defining the circle's geometry. + * @param center the circle's center location. + * @param radius the circle's radius, in meters. + * @param intervals the initial number of intervals (or slices) defining the circle's geometry. * * @throws IllegalArgumentException if the center is null, if the radius is negative, or if the number of intervals - * is less than 8. + * is less than 8. */ - public SurfaceCircle(ShapeAttributes normalAttrs, LatLon center, double radius, int intervals) - { + public SurfaceCircle(ShapeAttributes normalAttrs, LatLon center, double radius, int intervals) { super(normalAttrs, center, radius, radius, Angle.ZERO, intervals); } - public double getRadius() - { + public double getRadius() { return this.getMajorRadius(); } - public void setRadius(double radius) - { - if (radius < 0) - { + public void setRadius(double radius) { + if (radius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/render/SurfaceEllipse.java b/src/gov/nasa/worldwind/render/SurfaceEllipse.java index f42aa05286..09a9c93adc 100644 --- a/src/gov/nasa/worldwind/render/SurfaceEllipse.java +++ b/src/gov/nasa/worldwind/render/SurfaceEllipse.java @@ -15,8 +15,8 @@ * @author dcollins * @version $Id: SurfaceEllipse.java 2406 2014-10-29 23:39:29Z dcollins $ */ -public class SurfaceEllipse extends AbstractSurfaceShape -{ +public class SurfaceEllipse extends AbstractSurfaceShape { + protected static final int MIN_NUM_INTERVALS = 8; protected static final int DEFAULT_NUM_INTERVALS = 32; @@ -30,8 +30,7 @@ public class SurfaceEllipse extends AbstractSurfaceShape * Constructs a new surface ellipse with the default attributes, default center location, default radii, and default * heading. */ - public SurfaceEllipse() - { + public SurfaceEllipse() { } /** @@ -39,8 +38,7 @@ public SurfaceEllipse() * * @param source the shape to copy. */ - public SurfaceEllipse(SurfaceEllipse source) - { + public SurfaceEllipse(SurfaceEllipse source) { super(source); this.center = source.center; @@ -57,8 +55,7 @@ public SurfaceEllipse(SurfaceEllipse source) * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public SurfaceEllipse(ShapeAttributes normalAttrs) - { + public SurfaceEllipse(ShapeAttributes normalAttrs) { super(normalAttrs); } @@ -66,30 +63,26 @@ public SurfaceEllipse(ShapeAttributes normalAttrs) * Constructs a new surface ellipse with the default attributes, the specified center location and radii (in * meters). * - * @param center the ellipse's center location. + * @param center the ellipse's center location. * @param majorRadius the ellipse's major radius, in meters. * @param minorRadius the ellipse's minor radius, in meters. * * @throws IllegalArgumentException if the center is null, or if either radii is negative. */ - public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius) - { - if (center == null) - { + public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius) { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (majorRadius < 0) - { + if (majorRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", majorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minorRadius < 0) - { + if (minorRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", majorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -104,19 +97,17 @@ public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius) * Constructs a new surface ellipse with the default attributes, the specified center location, radii (in meters), * and heading clockwise from North. * - * @param center the ellipse's center location. + * @param center the ellipse's center location. * @param majorRadius the ellipse's major radius, in meters. * @param minorRadius the ellipse's minor radius, in meters. - * @param heading the ellipse's heading, clockwise from North. + * @param heading the ellipse's heading, clockwise from North. * * @throws IllegalArgumentException if the center or heading are null, or if either radii is negative. */ - public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius, Angle heading) - { + public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius, Angle heading) { this(center, majorRadius, minorRadius); - if (heading == null) - { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -129,21 +120,19 @@ public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius, Ang * Constructs a new surface ellipse with the default attributes, the specified center location, radii (in meters), * heading clockwise from North, and initial number of geometry intervals. * - * @param center the ellipse's center location. + * @param center the ellipse's center location. * @param majorRadius the ellipse's major radius, in meters. * @param minorRadius the ellipse's minor radius, in meters. - * @param heading the ellipse's heading, clockwise from North. - * @param intervals the initial number of intervals (or slices) defining the ellipse's geometry. + * @param heading the ellipse's heading, clockwise from North. + * @param intervals the initial number of intervals (or slices) defining the ellipse's geometry. * * @throws IllegalArgumentException if the center or heading are null, if either radii is negative, or if the number - * of intervals is less than 8. + * of intervals is less than 8. */ - public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius, Angle heading, int intervals) - { + public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius, Angle heading, int intervals) { this(center, majorRadius, minorRadius, heading); - if (intervals < MIN_NUM_INTERVALS) - { + if (intervals < MIN_NUM_INTERVALS) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -158,32 +147,28 @@ public SurfaceEllipse(LatLon center, double majorRadius, double minorRadius, Ang * this shape's appearance to change accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the ellipse's center location. + * @param center the ellipse's center location. * @param majorRadius the ellipse's major radius, in meters. * @param minorRadius the ellipse's minor radius, in meters. * * @throws IllegalArgumentException if the center is null, or if either radii is negative. */ - public SurfaceEllipse(ShapeAttributes normalAttrs, LatLon center, double majorRadius, double minorRadius) - { + public SurfaceEllipse(ShapeAttributes normalAttrs, LatLon center, double majorRadius, double minorRadius) { super(normalAttrs); - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (majorRadius < 0) - { + if (majorRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", majorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minorRadius < 0) - { + if (minorRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", majorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -200,20 +185,18 @@ public SurfaceEllipse(ShapeAttributes normalAttrs, LatLon center, double majorRa * calling this constructor causes this shape's appearance to change accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the ellipse's center location. + * @param center the ellipse's center location. * @param majorRadius the ellipse's major radius, in meters. * @param minorRadius the ellipse's minor radius, in meters. - * @param heading the ellipse's heading, clockwise from North. + * @param heading the ellipse's heading, clockwise from North. * * @throws IllegalArgumentException if the center or heading are null, or if either radii is negative. */ public SurfaceEllipse(ShapeAttributes normalAttrs, LatLon center, double majorRadius, double minorRadius, - Angle heading) - { + Angle heading) { this(normalAttrs, center, majorRadius, minorRadius); - if (heading == null) - { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -229,22 +212,20 @@ public SurfaceEllipse(ShapeAttributes normalAttrs, LatLon center, double majorRa * accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the ellipse's center location. + * @param center the ellipse's center location. * @param majorRadius the ellipse's major radius, in meters. * @param minorRadius the ellipse's minor radius, in meters. - * @param heading the ellipse's heading, clockwise from North. - * @param intervals the initial number of intervals (or slices) defining the ellipse's geometry. + * @param heading the ellipse's heading, clockwise from North. + * @param intervals the initial number of intervals (or slices) defining the ellipse's geometry. * * @throws IllegalArgumentException if the center or heading are null, if either radii is negative, or if the number - * of intervals is less than 8. + * of intervals is less than 8. */ public SurfaceEllipse(ShapeAttributes normalAttrs, LatLon center, double majorRadius, double minorRadius, - Angle heading, int intervals) - { + Angle heading, int intervals) { this(normalAttrs, center, majorRadius, minorRadius, heading); - if (intervals < MIN_NUM_INTERVALS) - { + if (intervals < MIN_NUM_INTERVALS) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -253,15 +234,12 @@ public SurfaceEllipse(ShapeAttributes normalAttrs, LatLon center, double majorRa this.intervals = intervals; } - public LatLon getCenter() - { + public LatLon getCenter() { return this.center; } - public void setCenter(LatLon center) - { - if (center == null) - { + public void setCenter(LatLon center) { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -271,20 +249,16 @@ public void setCenter(LatLon center) this.onShapeChanged(); } - public double getMajorRadius() - { + public double getMajorRadius() { return this.majorRadius; } - public double getMinorRadius() - { + public double getMinorRadius() { return this.minorRadius; } - public void setMajorRadius(double radius) - { - if (radius < 0) - { + public void setMajorRadius(double radius) { + if (radius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -294,10 +268,8 @@ public void setMajorRadius(double radius) this.onShapeChanged(); } - public void setMinorRadius(double radius) - { - if (radius < 0) - { + public void setMinorRadius(double radius) { + if (radius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative", radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -307,21 +279,17 @@ public void setMinorRadius(double radius) this.onShapeChanged(); } - public void setRadii(double majorRadius, double minorRadius) - { + public void setRadii(double majorRadius, double minorRadius) { this.setMajorRadius(majorRadius); this.setMinorRadius(minorRadius); } - public Angle getHeading() - { + public Angle getHeading() { return this.heading; } - public void setHeading(Angle heading) - { - if (heading == null) - { + public void setHeading(Angle heading) { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -331,15 +299,12 @@ public void setHeading(Angle heading) this.onShapeChanged(); } - public int getIntervals() - { + public int getIntervals() { return this.intervals; } - public void setIntervals(int intervals) - { - if (intervals < MIN_NUM_INTERVALS) - { + public void setIntervals(int intervals) { + if (intervals < MIN_NUM_INTERVALS) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -357,17 +322,14 @@ public void setIntervals(int intervals) * @see gov.nasa.worldwind.globes.Globe#getStateKey(DrawContext) */ @Override - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { // Store a copy of the active attributes to insulate the key from changes made to the shape's active attributes. return new SurfaceShapeStateKey(this.getUniqueId(), this.lastModifiedTime, this.getActiveAttributes().copy(), - dc.getGlobe().getStateKey(dc)); + dc.getGlobe().getStateKey(dc)); } - public Iterable getLocations(Globe globe) - { - if (globe == null) - { + public Iterable getLocations(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -376,38 +338,34 @@ public Iterable getLocations(Globe globe) return this.computeLocations(globe, this.intervals); } - public Position getReferencePosition() - { + public Position getReferencePosition() { return new Position(this.center, 0); } - protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) - { + protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) { Angle heading = LatLon.greatCircleAzimuth(oldReferencePosition, this.center); Angle pathLength = LatLon.greatCircleDistance(oldReferencePosition, this.center); this.setCenter(LatLon.greatCircleEndPosition(newReferencePosition, heading, pathLength)); } - protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) - { + protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) { List locations = new ArrayList(1); locations.add(this.getCenter()); List newLocations = LatLon.computeShiftedLocations(globe, oldReferencePosition, newReferencePosition, - locations); + locations); this.setCenter(newLocations.get(0)); } - protected List computeLocations(Globe globe, int intervals) - { - if (globe == null) - { + protected List computeLocations(Globe globe, int intervals) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.majorRadius == 0 && this.minorRadius == 0) + if (this.majorRadius == 0 && this.minorRadius == 0) { return null; + } int numLocations = 1 + Math.max(MIN_NUM_INTERVALS, intervals); double da = (2 * Math.PI) / (numLocations - 1); @@ -415,15 +373,14 @@ protected List computeLocations(Globe globe, int intervals) LatLon[] locations = new LatLon[numLocations]; - for (int i = 0; i < numLocations; i++) - { + for (int i = 0; i < numLocations; i++) { double angle = (i != numLocations - 1) ? i * da : 0; double xLength = this.majorRadius * Math.cos(angle); double yLength = this.minorRadius * Math.sin(angle); double distance = Math.sqrt(xLength * xLength + yLength * yLength); // azimuth runs positive clockwise from north and through 360 degrees. double azimuth = (Math.PI / 2.0) - (Math.acos(xLength / distance) * Math.signum(yLength) - - this.heading.radians); + - this.heading.radians); locations[i] = LatLon.greatCircleEndPosition(this.center, azimuth, distance / globeRadius); } @@ -431,13 +388,13 @@ protected List computeLocations(Globe globe, int intervals) return Arrays.asList(locations); } - protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) - { + protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) { int intervals = this.computeNumIntervals(globe, edgeIntervalsPerDegree); List drawLocations = this.computeLocations(globe, intervals); - if (drawLocations == null) + if (drawLocations == null) { return null; + } ArrayList> geom = new ArrayList>(); geom.add(drawLocations); @@ -445,10 +402,8 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer return geom; } - protected int computeNumIntervals(Globe globe, double edgeIntervalsPerDegree) - { - if (globe == null) - { + protected int computeNumIntervals(Globe globe, double edgeIntervalsPerDegree) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -458,10 +413,8 @@ protected int computeNumIntervals(Globe globe, double edgeIntervalsPerDegree) return numEdgeIntervals * this.intervals; } - protected int computeNumEdgeIntervals(Globe globe, double edgeIntervalsPerDegree) - { - if (globe == null) - { + protected int computeNumEdgeIntervals(Globe globe, double edgeIntervalsPerDegree) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -473,7 +426,7 @@ protected int computeNumEdgeIntervals(Globe globe, double edgeIntervalsPerDegree Angle edgePathLength = Angle.fromRadians(da * radius / globe.getRadiusAt(this.center)); double edgeIntervals = WWMath.clamp(edgeIntervalsPerDegree * edgePathLength.degrees, - this.minEdgeIntervals, this.maxEdgeIntervals); + this.minEdgeIntervals, this.maxEdgeIntervals); return (int) Math.ceil(edgeIntervals); } @@ -481,9 +434,7 @@ protected int computeNumEdgeIntervals(Globe globe, double edgeIntervalsPerDegree //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsLatLon(context, "center", this.getCenter()); @@ -493,33 +444,36 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsInteger(context, "intervals", this.getIntervals()); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); LatLon ll = rs.getStateValueAsLatLon(context, "center"); - if (ll != null) + if (ll != null) { this.setCenter(ll); + } Double d = rs.getStateValueAsDouble(context, "majorRadius"); - if (d != null) + if (d != null) { this.setMajorRadius(d); + } d = rs.getStateValueAsDouble(context, "minorRadius"); - if (d != null) + if (d != null) { this.setMinorRadius(d); + } d = rs.getStateValueAsDouble(context, "headingDegrees"); - if (d != null) + if (d != null) { this.setHeading(Angle.fromDegrees(d)); + } Integer i = rs.getStateValueAsInteger(context, "intervals"); - if (d != null) + if (d != null) { this.setIntervals(i); + } } - protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.legacyRestoreState(rs, context); // These properties has not changed since the last version, but they're shown here for reference. @@ -527,20 +481,17 @@ protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateO //Double minor = rs.getStateValueAsDouble(context, "minorRadius"); //if (major != null && minor != null) // this.setAxisLengths(major, minor); - // This property has not changed since the last version, but it's shown here for reference. //LatLon center = rs.getStateValueAsLatLon(context, "center"); //if (center != null) // this.setCenter(center); - // This property has not changed since the last version, but it's shown here for reference. //Integer intervals = rs.getStateValueAsInteger(context, "intervals"); //if (intervals != null) // this.setIntervals(intervals); - Double od = rs.getStateValueAsDouble(context, "orientationDegrees"); - if (od != null) + if (od != null) { this.setHeading(Angle.fromDegrees(od)); + } } } - diff --git a/src/gov/nasa/worldwind/render/SurfaceIcon.java b/src/gov/nasa/worldwind/render/SurfaceIcon.java index 421681e862..a9f9fc3ce2 100644 --- a/src/gov/nasa/worldwind/render/SurfaceIcon.java +++ b/src/gov/nasa/worldwind/render/SurfaceIcon.java @@ -23,8 +23,8 @@ * @author Patrick Murris * @version $Id: SurfaceIcon.java 1772 2013-12-18 02:43:27Z tgaskins $ */ -public class SurfaceIcon extends AbstractSurfaceRenderable implements Movable, Draggable -{ +public class SurfaceIcon extends AbstractSurfaceRenderable implements Movable, Draggable { + private Object imageSource; private boolean useMipMaps = true; private LatLon location; @@ -42,16 +42,15 @@ public class SurfaceIcon extends AbstractSurfaceRenderable implements Movable, D protected boolean dragEnabled = true; protected DraggableSupport draggableSupport = null; - public SurfaceIcon(Object imageSource) - { + public SurfaceIcon(Object imageSource) { this(imageSource, null); } - public SurfaceIcon(Object imageSource, LatLon location) - { + public SurfaceIcon(Object imageSource, LatLon location) { this.setImageSource(imageSource); - if (location != null) + if (location != null) { this.setLocation(location); + } } /** @@ -59,8 +58,7 @@ public SurfaceIcon(Object imageSource, LatLon location) * * @return the icon reference location on the globe. */ - public LatLon getLocation() - { + public LatLon getLocation() { return this.location; } @@ -71,10 +69,8 @@ public LatLon getLocation() * * @throws IllegalArgumentException if location is null. */ - public void setLocation(LatLon location) - { - if (location == null) - { + public void setLocation(LatLon location) { + if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -85,7 +81,7 @@ public void setLocation(LatLon location) } /** - * Get the icon displacement in pixels relative to the reference location. Can be null. + * Get the icon displacement in pixels relative to the reference location. Can be null. *

          * When null the icon will be drawn with it's image center on top of it's reference location - see * {@link #setLocation(LatLon)}. Otherwise the icon will be shifted of a distance equivalent to the number of pixels @@ -94,8 +90,7 @@ public void setLocation(LatLon location) * * @return the icon displacement in pixels relative to the reference location. */ - public Vec4 getLocationOffset() - { + public Vec4 getLocationOffset() { return this.locationOffset; } @@ -109,8 +104,7 @@ public Vec4 getLocationOffset() * * @param locationOffset the icon displacement in pixels relative to the reference location. */ - public void setLocationOffset(Vec4 locationOffset) - { + public void setLocationOffset(Vec4 locationOffset) { this.locationOffset = locationOffset; // can be null this.onShapeChanged(); } @@ -121,8 +115,7 @@ public void setLocationOffset(Vec4 locationOffset) * * @return the source for the icon image. */ - public Object getImageSource() - { + public Object getImageSource() { return this.imageSource; } @@ -134,10 +127,8 @@ public Object getImageSource() * * @throws IllegalArgumentException if imageSource is null. */ - public void setImageSource(Object imageSource) - { - if (imageSource == null) - { + public void setImageSource(Object imageSource) { + if (imageSource == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -155,8 +146,7 @@ public void setImageSource(Object imageSource) * * @return true if the icon image is drawn with mip-map filtering; false otherwise. */ - public boolean isUseMipMaps() - { + public boolean isUseMipMaps() { return this.useMipMaps; } @@ -166,10 +156,9 @@ public boolean isUseMipMaps() * image is drawn smaller than it's native size in pixels. * * @param useMipMaps true if the icon image should be drawn with mip-map filtering; false - * otherwise. + * otherwise. */ - public void setUseMipMaps(boolean useMipMaps) - { + public void setUseMipMaps(boolean useMipMaps) { this.useMipMaps = useMipMaps; this.texture = null; this.onShapeChanged(); @@ -180,8 +169,7 @@ public void setUseMipMaps(boolean useMipMaps) * * @return the current scaling factor applied to the source image. */ - public double getScale() - { + public double getScale() { return this.scale; } @@ -193,10 +181,8 @@ public double getScale() * * @throws IllegalArgumentException if scale is zero or negative. */ - public void setScale(double scale) - { - if (scale <= 0) - { + public void setScale(double scale) { + if (scale <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "scale must be greater then zero"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -210,8 +196,7 @@ public void setScale(double scale) * * @return the current heading {@link Angle}, clockwise from North or null. */ - public Angle getHeading() - { + public Angle getHeading() { return this.heading; } @@ -221,8 +206,7 @@ public Angle getHeading() * * @param heading the heading {@link Angle}, clockwise from North or null. */ - public void setHeading(Angle heading) - { + public void setHeading(Angle heading) { this.heading = heading; // can be null this.onShapeChanged(); } @@ -235,8 +219,7 @@ public void setHeading(Angle heading) * * @return true if the icon constantly maintains it's apparent size. */ - public boolean isMaintainSize() - { + public boolean isMaintainSize() { return this.maintainSize; } @@ -248,8 +231,7 @@ public boolean isMaintainSize() * * @param state true if the icon should constantly maintains it's apparent size. */ - public void setMaintainSize(boolean state) - { + public void setMaintainSize(boolean state) { this.maintainSize = state; } @@ -263,8 +245,7 @@ public void setMaintainSize(boolean state) * * @return the minimum size of the icon in meter. */ - public double getMinSize() - { + public double getMinSize() { return this.minSize; } @@ -278,8 +259,7 @@ public double getMinSize() * * @param sizeInMeter the minimum size of the icon in meter. */ - public void setMinSize(double sizeInMeter) - { + public void setMinSize(double sizeInMeter) { this.minSize = sizeInMeter; this.onShapeChanged(); } @@ -294,8 +274,7 @@ public void setMinSize(double sizeInMeter) * * @return the maximum size of the icon in meter. */ - public double getMaxSize() - { + public double getMaxSize() { return this.maxSize; } @@ -309,8 +288,7 @@ public double getMaxSize() * * @param sizeInMeter the maximum size of the icon in meter. */ - public void setMaxSize(double sizeInMeter) - { + public void setMaxSize(double sizeInMeter) { this.maxSize = sizeInMeter; this.onShapeChanged(); } @@ -320,8 +298,7 @@ public void setMaxSize(double sizeInMeter) * * @return the {@link Color} the source image is combined with. */ - public Color getColor() - { + public Color getColor() { return this.color; } @@ -335,10 +312,8 @@ public Color getColor() * * @throws IllegalArgumentException if color is null. */ - public void setColor(Color color) - { - if (color == null) - { + public void setColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -347,13 +322,11 @@ public void setColor(Color color) this.onShapeChanged(); } - protected boolean isMaintainAppearance() - { + protected boolean isMaintainAppearance() { return this.getHeading() == null || this.isMaintainSize(); // always facing or constant size } // *** SurfaceObject interface *** - /** * {@inheritDoc} *

          @@ -365,19 +338,17 @@ protected boolean isMaintainAppearance() * @see #isMaintainSize() */ @Override - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { // If the icon always redraws, return a unique object that is not equivalent to any other state key. - if (this.isMaintainAppearance()) + if (this.isMaintainAppearance()) { return new Object(); + } return super.getStateKey(dc); } - public List getSectors(DrawContext dc) - { - if (dc == null) - { + public List getSectors(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -386,10 +357,8 @@ public List getSectors(DrawContext dc) return this.computeSectors(dc); } - public Extent getExtent(DrawContext dc) - { - if (dc == null) - { + public Extent getExtent(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -398,17 +367,15 @@ public Extent getExtent(DrawContext dc) return this.computeExtent(dc); } - public void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) - { + public void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) { WWTexture texture = getTexture(); - if (texture == null) + if (texture == null) { return; + } this.beginDraw(dc); - try - { - if (texture.bind(dc)) - { + try { + if (texture.bind(dc)) { // Update image width and height this.imageWidth = texture.getWidth(dc); this.imageHeight = texture.getHeight(dc); @@ -424,29 +391,24 @@ public void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) //Draw this.drawIcon(dc, sdc); } - } - catch (Exception e) - { + } catch (Exception e) { // TODO: log error - } - finally - { + } finally { // Restore gl state this.endDraw(dc); } } - protected List computeSectors(DrawContext dc) - { - if (this.location == null) + protected List computeSectors(DrawContext dc) { + if (this.location == null) { return null; + } Globe globe = dc.getGlobe(); // Compute real world icon extent depending on distance from eye Rectangle2D.Double rect = computeDrawDimension(dc, this.location); // meter // If the icon does not redraw all the time, double it's dimension - if (!this.isMaintainAppearance()) - { + if (!this.isMaintainAppearance()) { rect.setRect(rect.x, rect.y, rect.width * 2, rect.height * 2); } // Compute bounding sector and apply location offset to it @@ -456,10 +418,10 @@ protected List computeSectors(DrawContext dc) double offsetLatRadians = locationOffset != null ? locationOffset.y * dLatRadians / this.imageHeight : 0; double offsetLonRadians = locationOffset != null ? locationOffset.x * dLonRadians / this.imageWidth : 0; Sector sector = new Sector( - this.location.getLatitude().subtractRadians(dLatRadians / 2).addRadians(offsetLatRadians), - this.location.getLatitude().addRadians(dLatRadians / 2).addRadians(offsetLatRadians), - this.location.getLongitude().subtractRadians(dLonRadians / 2).addRadians(offsetLonRadians), - this.location.getLongitude().addRadians(dLonRadians / 2).addRadians(offsetLonRadians) + this.location.getLatitude().subtractRadians(dLatRadians / 2).addRadians(offsetLatRadians), + this.location.getLatitude().addRadians(dLatRadians / 2).addRadians(offsetLatRadians), + this.location.getLongitude().subtractRadians(dLonRadians / 2).addRadians(offsetLonRadians), + this.location.getLongitude().addRadians(dLonRadians / 2).addRadians(offsetLonRadians) ); // Rotate sector around location sector = computeRotatedSectorBounds(sector, this.location, computeDrawHeading(dc)); @@ -467,15 +429,13 @@ protected List computeSectors(DrawContext dc) return computeNormalizedSectors(sector); } - protected Rectangle2D.Double computeDrawDimension(DrawContext dc, LatLon location) - { + protected Rectangle2D.Double computeDrawDimension(DrawContext dc, LatLon location) { // Compute icon extent at 1:1 depending on distance from eye double pixelSize = computePixelSizeAtLocation(dc, location); return computeDrawDimension(pixelSize); } - protected Rectangle2D.Double computeDrawDimension(double pixelSize) - { + protected Rectangle2D.Double computeDrawDimension(double pixelSize) { // Compute icon extent at 1:1 depending on target tile pixel size double height = this.imageHeight * this.scale * pixelSize; double width = this.imageWidth * this.scale * pixelSize; @@ -486,22 +446,21 @@ protected Rectangle2D.Double computeDrawDimension(double pixelSize) return new Rectangle2D.Double(0, 0, width * scale, height * scale); // meter } - protected Angle computeDrawHeading(DrawContext dc) - { - if (this.heading != null) + protected Angle computeDrawHeading(DrawContext dc) { + if (this.heading != null) { return this.heading; + } return getViewHeading(dc); } - protected void beginDraw(DrawContext dc) - { + protected void beginDraw(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int attributeMask = GL2.GL_TRANSFORM_BIT // for modelview - | GL2.GL_CURRENT_BIT // for current color - | GL2.GL_COLOR_BUFFER_BIT // for alpha test func and ref, and blend - | GL2.GL_ENABLE_BIT; // for enable/disable changes + | GL2.GL_CURRENT_BIT // for current color + | GL2.GL_COLOR_BUFFER_BIT // for alpha test func and ref, and blend + | GL2.GL_ENABLE_BIT; // for enable/disable changes gl.glPushAttrib(attributeMask); // Suppress any fully transparent image pixels @@ -514,28 +473,23 @@ protected void beginDraw(DrawContext dc) gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { // Set up to replace the non-transparent texture colors with the single pick color. gl.glEnable(GL.GL_TEXTURE_2D); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_COMBINE); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, GL2.GL_PREVIOUS); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_COMBINE_RGB, GL2.GL_REPLACE); - } - else - { + } else { gl.glEnable(GL.GL_TEXTURE_2D); gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); } } - protected void endDraw(DrawContext dc) - { + protected void endDraw(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, OGLUtil.DEFAULT_TEX_ENV_MODE); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, OGLUtil.DEFAULT_SRC0_RGB); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_COMBINE_RGB, OGLUtil.DEFAULT_COMBINE_RGB); @@ -553,8 +507,7 @@ protected void endDraw(DrawContext dc) } @SuppressWarnings({"UnusedDeclaration"}) - protected void applyDrawTransform(DrawContext dc, SurfaceTileDrawContext sdc, LatLon location, double drawScale) - { + protected void applyDrawTransform(DrawContext dc, SurfaceTileDrawContext sdc, LatLon location, double drawScale) { // Compute icon viewport point // Apply hemisphere offset if needed - for icons that may cross the date line double offset = computeHemisphereOffset(sdc.getSector(), location); @@ -571,35 +524,33 @@ protected void applyDrawTransform(DrawContext dc, SurfaceTileDrawContext sdc, La // Translate to lower left corner gl.glTranslated(-this.imageWidth / 2, -this.imageHeight / 2, 0); // Apply location offset if any - if (this.locationOffset != null) + if (this.locationOffset != null) { gl.glTranslated(this.locationOffset.x, this.locationOffset.y, 0); + } } - protected double computeDrawScale(DrawContext dc, SurfaceTileDrawContext sdc, LatLon location) - { + protected double computeDrawScale(DrawContext dc, SurfaceTileDrawContext sdc, LatLon location) { // Compute scaling to maintain apparent size double drawPixelSize; double regionPixelSize = this.computeDrawPixelSize(dc, sdc); - if (this.isMaintainAppearance()) - // Compute precise size depending on eye distance + if (this.isMaintainAppearance()) // Compute precise size depending on eye distance + { drawPixelSize = this.computeDrawDimension(dc, location).width / this.imageWidth; - else - // Compute size according to draw tile resolution + } else // Compute size according to draw tile resolution + { drawPixelSize = this.computeDrawDimension(regionPixelSize).width / this.imageWidth; + } return drawPixelSize / regionPixelSize; } - protected void applyDrawColor(DrawContext dc) - { - if (!dc.isPickingMode()) - { + protected void applyDrawColor(DrawContext dc) { + if (!dc.isPickingMode()) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. applyPremultipliedAlphaColor(gl, this.color, getOpacity()); } } - protected void drawIcon(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawIcon(DrawContext dc, SurfaceTileDrawContext sdc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glMatrixMode(GL2.GL_MODELVIEW); double drawScale = this.computeDrawScale(dc, sdc, this.location); @@ -608,41 +559,36 @@ protected void drawIcon(DrawContext dc, SurfaceTileDrawContext sdc) dc.drawUnitQuad(new TextureCoords(0, 0, 1, 1)); } - protected WWTexture getTexture() - { - if (this.texture == null) + protected WWTexture getTexture() { + if (this.texture == null) { this.texture = new BasicWWTexture(this.imageSource, this.useMipMaps); + } return this.texture; } // *** Movable interface - - public Position getReferencePosition() - { + public Position getReferencePosition() { return new Position(this.location, 0); } - public void move(Position delta) - { - if (delta == null) - { + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Position referencePos = this.getReferencePosition(); - if (referencePos == null) + if (referencePos == null) { return; + } this.moveTo(referencePos.add(delta)); } - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -652,52 +598,47 @@ public void moveTo(Position position) } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, WorldWind.CLAMP_TO_GROUND); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } //**************************************************************// //******************** Sector Cache Info *********************// //**************************************************************// + protected static class SectorInfo { - protected static class SectorInfo - { protected List sectors; protected Object globeStateKey; - public SectorInfo(List sectors, DrawContext dc) - { + public SectorInfo(List sectors, DrawContext dc) { // Surface icon sectors depend on the state of the globe used to compute it. this.sectors = sectors; this.globeStateKey = dc.getGlobe().getStateKey(dc); } - public boolean isValid(DrawContext dc) - { + public boolean isValid(DrawContext dc) { return this.globeStateKey.equals(dc.getGlobe().getStateKey(dc)); } } diff --git a/src/gov/nasa/worldwind/render/SurfaceIcons.java b/src/gov/nasa/worldwind/render/SurfaceIcons.java index 625f5a64e7..3d24c7be86 100644 --- a/src/gov/nasa/worldwind/render/SurfaceIcons.java +++ b/src/gov/nasa/worldwind/render/SurfaceIcons.java @@ -19,31 +19,28 @@ * @author Patrick Murris * @version $Id: SurfaceIcons.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SurfaceIcons extends SurfaceIcon -{ +public class SurfaceIcons extends SurfaceIcon { + private Iterable locations; - public SurfaceIcons(Object imageSource, Iterable locations) - { + public SurfaceIcons(Object imageSource, Iterable locations) { super(imageSource); this.setLocations(locations); } - public Iterable getLocations() - { + public Iterable getLocations() { return this.locations; } - public void setLocations(Iterable newLocations) - { + public void setLocations(Iterable newLocations) { this.locations = newLocations; this.onShapeChanged(); } - protected List computeSectors(DrawContext dc) - { - if (this.locations == null || !this.locations.iterator().hasNext()) + protected List computeSectors(DrawContext dc) { + if (this.locations == null || !this.locations.iterator().hasNext()) { return null; + } // Compute all locations bounding sector, then add some padding for the icon half diagonal extent Sector sector = Sector.boundingSector(this.locations); @@ -52,7 +49,7 @@ protected List computeSectors(DrawContext dc) minCosLat = Math.max(minCosLat, .01); // avoids division by zero at the poles Rectangle2D iconDimension = this.computeDrawDimension(dc, sector.getCentroid()); double diagonalLength = Math.sqrt(iconDimension.getWidth() * iconDimension.getWidth() - + iconDimension.getHeight() * iconDimension.getHeight()); + + iconDimension.getHeight() * iconDimension.getHeight()); double padLatRadians = diagonalLength / 2 / dc.getGlobe().getRadius(); double padLonRadians = diagonalLength / 2 / dc.getGlobe().getRadius() / minCosLat; // Apply padding to sector @@ -64,10 +61,10 @@ protected List computeSectors(DrawContext dc) return this.computeNormalizedSectors(new Sector(minLat, maxLat, minLon, maxLon)); } - protected void drawIcon(DrawContext dc, SurfaceTileDrawContext sdc) - { - if (this.locations == null) + protected void drawIcon(DrawContext dc, SurfaceTileDrawContext sdc) { + if (this.locations == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glMatrixMode(GL2.GL_MODELVIEW); @@ -75,17 +72,18 @@ protected void drawIcon(DrawContext dc, SurfaceTileDrawContext sdc) TextureCoords textureCoords = new TextureCoords(0, 0, 1, 1); // Compute draw scale only once if not maintaining strict appearance - if (!this.isMaintainAppearance()) + if (!this.isMaintainAppearance()) { drawScale = this.computeDrawScale(dc, sdc, null); + } // Determine which locations are to be drawn Iterable drawLocations = this.computeDrawLocations(dc, sdc); // Draw icons - for (LatLon location : drawLocations) - { + for (LatLon location : drawLocations) { gl.glPushMatrix(); - if (this.isMaintainAppearance()) + if (this.isMaintainAppearance()) { drawScale = this.computeDrawScale(dc, sdc, location); + } this.applyDrawTransform(dc, sdc, location, drawScale); gl.glScaled(this.imageWidth, this.imageHeight, 1d); dc.drawUnitQuad(textureCoords); @@ -94,38 +92,35 @@ protected void drawIcon(DrawContext dc, SurfaceTileDrawContext sdc) } } - protected Iterable computeDrawLocations(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected Iterable computeDrawLocations(DrawContext dc, SurfaceTileDrawContext sdc) { ArrayList drawList = new ArrayList(); double safeDistanceDegreesSquared = Math.pow(this.computeSafeRadius(dc, sdc).degrees, 2); - for (LatLon location : this.getLocations()) - { - if (this.computeLocationDistanceDegreesSquared(sdc.getSector(), location) <= safeDistanceDegreesSquared) + for (LatLon location : this.getLocations()) { + if (this.computeLocationDistanceDegreesSquared(sdc.getSector(), location) <= safeDistanceDegreesSquared) { drawList.add(location); + } } return drawList; } - protected Angle computeSafeRadius(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected Angle computeSafeRadius(DrawContext dc, SurfaceTileDrawContext sdc) { double regionPixelSize = this.computeDrawPixelSize(dc, sdc); Angle sectorRadius = this.computeSectorRadius(sdc.getSector()); Angle iconRadius = this.computeIconRadius(dc, regionPixelSize, sdc.getSector()); return sectorRadius.add(iconRadius); } - protected Angle computeSectorRadius(Sector sector) - { + protected Angle computeSectorRadius(Sector sector) { double dLat = sector.getDeltaLatRadians(); double dLon = sector.getDeltaLonRadians(); return Angle.fromRadians(Math.sqrt(dLat * dLat + dLon * dLon) / 2); } - protected Angle computeIconRadius(DrawContext dc, double regionPixelSize, Sector drawSector) - { + protected Angle computeIconRadius(DrawContext dc, double regionPixelSize, Sector drawSector) { double minCosLat = Math.min(drawSector.getMinLatitude().cos(), drawSector.getMaxLatitude().cos()); - if (minCosLat < 0.001) + if (minCosLat < 0.001) { return Angle.POS180; + } Rectangle2D iconDimension = this.computeDrawDimension(regionPixelSize); // Meter double dLat = iconDimension.getHeight() / dc.getGlobe().getRadius(); @@ -133,8 +128,7 @@ protected Angle computeIconRadius(DrawContext dc, double regionPixelSize, Sector return Angle.fromRadians(Math.sqrt(dLat * dLat + dLon * dLon) / 2); } - protected double computeLocationDistanceDegreesSquared(Sector drawSector, LatLon location) - { + protected double computeLocationDistanceDegreesSquared(Sector drawSector, LatLon location) { double lonOffset = computeHemisphereOffset(drawSector, location); double dLat = location.getLatitude().degrees - drawSector.getCentroid().getLatitude().degrees; double dLon = location.getLongitude().degrees - drawSector.getCentroid().getLongitude().degrees + lonOffset; diff --git a/src/gov/nasa/worldwind/render/SurfaceImage.java b/src/gov/nasa/worldwind/render/SurfaceImage.java index 03c277239c..9510ec67c5 100644 --- a/src/gov/nasa/worldwind/render/SurfaceImage.java +++ b/src/gov/nasa/worldwind/render/SurfaceImage.java @@ -33,8 +33,7 @@ * @version $Id: SurfaceImage.java 3419 2015-08-28 00:09:50Z dcollins $ */ public class SurfaceImage extends WWObjectImpl - implements SurfaceTile, OrderedRenderable, PreRenderable, Movable, Disposable, Exportable, Draggable -{ + implements SurfaceTile, OrderedRenderable, PreRenderable, Movable, Disposable, Exportable, Draggable { // TODO: Handle date-line spanning sectors private Sector sector; @@ -61,28 +60,26 @@ public class SurfaceImage extends WWObjectImpl */ protected List thisList = Arrays.asList(this); - /** Create a new surface image with no image source. The image will not be rendered until an image source is set. */ - public SurfaceImage() - { + /** + * Create a new surface image with no image source. The image will not be rendered until an image source is set. + */ + public SurfaceImage() { } /** * Renders a single image tile from a local image source. * * @param imageSource either the file path to a local image or a BufferedImage reference. - * @param sector the sector covered by the image. + * @param sector the sector covered by the image. */ - public SurfaceImage(Object imageSource, Sector sector) - { - if (imageSource == null) - { + public SurfaceImage(Object imageSource, Sector sector) { + if (imageSource == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -91,17 +88,14 @@ public SurfaceImage(Object imageSource, Sector sector) this.setImageSource(imageSource, sector); } - public SurfaceImage(Object imageSource, Iterable corners) - { - if (imageSource == null) - { + public SurfaceImage(Object imageSource, Iterable corners) { + if (imageSource == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (corners == null) - { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,18 +104,15 @@ public SurfaceImage(Object imageSource, Iterable corners) this.setImageSource(imageSource, corners); } - public void dispose() - { + public void dispose() { this.generatedTexture = null; } - public void setImageSource(Object imageSource, Sector sector) - { + public void setImageSource(Object imageSource, Sector sector) { this.setImageSource(imageSource, (Iterable) sector); } - public void setImageSource(Object imageSource, Iterable corners) - { + public void setImageSource(Object imageSource, Iterable corners) { // If the current source texture or generated texture are non-null, keep track of them and remove their textures // from the GPU resource cache on the next frame. This prevents SurfaceImage from leaking memory when the caller // continuously specifies the image source to display an animation. We ignore null textures to avoid clearing @@ -129,10 +120,12 @@ public void setImageSource(Object imageSource, Iterable corner // frame, this still keeps track of the previous texture. Clearing of the source texture is necessary only for // BufferedImage sources. Other types will clear automatically through the GPU resource cache. Clearing of the // generated texture is necessary because those are FBO textures and therefore require significant memory. - if (this.sourceTexture != null && imageSource instanceof BufferedImage) + if (this.sourceTexture != null && imageSource instanceof BufferedImage) { this.previousSourceTexture = this.sourceTexture; - if (this.generatedTexture != null) + } + if (this.generatedTexture != null) { this.previousGeneratedTexture = this.generatedTexture; + } // Assign the new image source and clear the current source texture. We initialize the source texture during the // next frame. This enables SurfaceImage to retrieve remote images during each frame on a separate thread. @@ -143,13 +136,11 @@ public void setImageSource(Object imageSource, Iterable corner initializeGeometry(corners); } - public boolean isPickEnabled() - { + public boolean isPickEnabled() { return this.pickEnabled; } - public void setPickEnabled(boolean pickEnabled) - { + public void setPickEnabled(boolean pickEnabled) { this.pickEnabled = pickEnabled; } @@ -160,8 +151,7 @@ public void setPickEnabled(boolean pickEnabled) * * @see #setAlwaysOnTop(boolean) */ - public boolean isAlwaysOnTop() - { + public boolean isAlwaysOnTop() { return this.alwaysOnTop; } @@ -172,18 +162,15 @@ public boolean isAlwaysOnTop() * in the layer list, and appears beneath all surface shapes. The default is false. * * @param alwaysOnTop true if the surface image should appear always on top, otherwise - * false. + * false. */ - public void setAlwaysOnTop(boolean alwaysOnTop) - { + public void setAlwaysOnTop(boolean alwaysOnTop) { this.alwaysOnTop = alwaysOnTop; } - protected void initializeGeometry(Iterable corners) - { + protected void initializeGeometry(Iterable corners) { this.corners = new ArrayList(4); - for (LatLon ll : corners) - { + for (LatLon ll : corners) { this.corners.add(ll); } @@ -192,32 +179,25 @@ protected void initializeGeometry(Iterable corners) this.generatedTextureExpired = true; } - public Object getImageSource() - { + public Object getImageSource() { return this.imageSource; } - public double getOpacity() - { + public double getOpacity() { return opacity; } - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { this.opacity = opacity; } // SurfaceTile interface - - public Sector getSector() - { + public Sector getSector() { return this.sector; } - public void setCorners(Iterable corners) - { - if (corners == null) - { + public void setCorners(Iterable corners) { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -226,15 +206,12 @@ public void setCorners(Iterable corners) this.initializeGeometry(corners); } - public List getCorners() - { + public List getCorners() { return new ArrayList(this.corners); } - public Extent getExtent(DrawContext dc) - { - if (dc == null) - { + public Extent getExtent(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -243,53 +220,47 @@ public Extent getExtent(DrawContext dc) return Sector.computeBoundingCylinder(dc.getGlobe(), dc.getVerticalExaggeration(), this.getSector()); } - public boolean bind(DrawContext dc) - { + public boolean bind(DrawContext dc) { return this.generatedTexture != null && this.generatedTexture.bind(dc); } - public void applyInternalTransform(DrawContext dc, boolean textureIdentityActive) - { - if (this.generatedTexture != null) + public void applyInternalTransform(DrawContext dc, boolean textureIdentityActive) { + if (this.generatedTexture != null) { this.generatedTexture.applyInternalTransform(dc); + } } // Renderable interface - @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return 0; // Method required by the ordered surface renderable contract but never used. The return value is meaningless. } - public void preRender(DrawContext dc) - { - if (dc.isOrderedRenderingMode()) + public void preRender(DrawContext dc) { + if (dc.isOrderedRenderingMode()) { return; // preRender is called twice - during layer rendering then again during ordered surface rendering - - if (this.previousSourceTexture != null) - { + } + if (this.previousSourceTexture != null) { dc.getTextureCache().remove(this.previousSourceTexture.getImageSource()); this.previousSourceTexture = null; } // Initialize the source texture if the caller specified a new image source. - if (this.getImageSource() != null && this.sourceTexture == null) + if (this.getImageSource() != null && this.sourceTexture == null) { this.initializeSourceTexture(dc); + } // Exit if the source texture could not be initialized. - if (this.sourceTexture == null) + if (this.sourceTexture == null) { return; + } - if (this.generatedTexture == null || this.generatedTextureExpired) - { + if (this.generatedTexture == null || this.generatedTextureExpired) { WWTexture gt = this.initializeGeneratedTexture(dc); - if (gt != null) - { + if (gt != null) { this.generatedTexture = gt; this.generatedTextureExpired = false; - if (this.previousGeneratedTexture != null) - { + if (this.previousGeneratedTexture != null) { dc.getTextureCache().remove(this.previousGeneratedTexture); this.previousGeneratedTexture = null; } @@ -297,26 +268,26 @@ public void preRender(DrawContext dc) } } - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (dc.isPickingMode() && !this.isPickEnabled()) + if (dc.isPickingMode() && !this.isPickEnabled()) { return; + } - if (this.getSector() == null || !this.getSector().intersects(dc.getVisibleSector())) + if (this.getSector() == null || !this.getSector().intersects(dc.getVisibleSector())) { return; + } - if (this.sourceTexture == null && this.generatedTexture == null) + if (this.sourceTexture == null && this.generatedTexture == null) { return; + } - if (!dc.isOrderedRenderingMode() && this.isAlwaysOnTop()) - { + if (!dc.isOrderedRenderingMode() && this.isAlwaysOnTop()) { this.pickLayer = dc.getCurrentLayer(); dc.addOrderedSurfaceRenderable(this); return; @@ -326,14 +297,13 @@ public void render(DrawContext dc) } @Override - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { // Lazily allocate the pick support property, since it's only used when alwaysOnTop is set to true. - if (this.pickSupport == null) + if (this.pickSupport == null) { this.pickSupport = new PickSupport(); + } - try - { + try { this.pickSupport.beginPicking(dc); java.awt.Color color = dc.getUniquePickColor(); @@ -341,39 +311,29 @@ public void pick(DrawContext dc, Point pickPoint) this.pickSupport.addPickableObject(color.getRGB(), this); this.draw(dc); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } } - protected void draw(DrawContext dc) - { + protected void draw(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { - if (!dc.isPickingMode()) - { + try { + if (!dc.isPickingMode()) { double opacity = dc.getCurrentLayer() != null - ? this.getOpacity() * dc.getCurrentLayer().getOpacity() : this.getOpacity(); + ? this.getOpacity() * dc.getCurrentLayer().getOpacity() : this.getOpacity(); - if (opacity < 1) - { + if (opacity < 1) { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_POLYGON_BIT | GL2.GL_CURRENT_BIT); // Enable blending using white premultiplied by the current opacity. gl.glColor4d(opacity, opacity, opacity, opacity); - } - else - { + } else { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_POLYGON_BIT); } gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); - } - else - { + } else { gl.glPushAttrib(GL2.GL_POLYGON_BIT); } @@ -382,41 +342,31 @@ protected void draw(DrawContext dc) gl.glCullFace(GL.GL_BACK); dc.getGeographicSurfaceTileRenderer().renderTiles(dc, this.thisList); - } - finally - { + } finally { gl.glPopAttrib(); } } @SuppressWarnings({"UnusedParameters"}) - protected void initializeSourceTexture(DrawContext dc) - { + protected void initializeSourceTexture(DrawContext dc) { this.sourceTexture = new LazilyLoadedTexture(this.getImageSource(), true); } - protected WWTexture initializeGeneratedTexture(DrawContext dc) - { + protected WWTexture initializeGeneratedTexture(DrawContext dc) { // If this SurfaceImage's is configured with a sector there's no need to generate a texture; we can // use the source texture to render the SurfaceImage. - if (Sector.isSector(this.corners) && this.sector.isSameSector(this.corners)) - { - if (this.sourceTexture.bind(dc)) - { + if (Sector.isSector(this.corners) && this.sector.isSameSector(this.corners)) { + if (this.sourceTexture.bind(dc)) { this.generatedTexture = this.sourceTexture; return this.generatedTexture; - } - else - { + } else { return null; } - } - else - { - FramebufferTexture t = dc.getGLRuntimeCapabilities().isUseFramebufferObject() ? - new FBOTexture(this.sourceTexture, this.sector, this.corners) - : new FramebufferTexture(this.sourceTexture, this.sector, this.corners); + } else { + FramebufferTexture t = dc.getGLRuntimeCapabilities().isUseFramebufferObject() + ? new FBOTexture(this.sourceTexture, this.sector, this.corners) + : new FramebufferTexture(this.sourceTexture, this.sector, this.corners); // Bind the texture to cause it to generate its internal texture. t.bind(dc); @@ -426,11 +376,8 @@ protected WWTexture initializeGeneratedTexture(DrawContext dc) } // --- Movable interface --- - - public void move(Position delta) - { - if (delta == null) - { + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -439,14 +386,13 @@ public void move(Position delta) this.moveTo(this.getReferencePosition().add(delta)); } - public void moveTo(Position position) - { + public void moveTo(Position position) { LatLon oldRef = this.getReferencePosition(); - if (oldRef == null) + if (oldRef == null) { return; + } - for (int i = 0; i < this.corners.size(); i++) - { + for (int i = 0; i < this.corners.size(); i++) { LatLon p = this.corners.get(i); double distance = LatLon.greatCircleDistance(oldRef, p).radians; double azimuth = LatLon.greatCircleAzimuth(oldRef, p).radians; @@ -457,80 +403,80 @@ public void moveTo(Position position) this.setCorners(this.corners); } - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.referencePosition; } @SuppressWarnings({"UnusedDeclaration"}) - protected void setReferencePosition(Position referencePosition) - { + protected void setReferencePosition(Position referencePosition) { this.referencePosition = referencePosition; } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, WorldWind.CLAMP_TO_GROUND); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; + } - if (o == null || this.getClass() != o.getClass()) + if (o == null || this.getClass() != o.getClass()) { return false; + } SurfaceImage that = (SurfaceImage) o; - if (this.getSector() == null || that.getSector() == null) + if (this.getSector() == null || that.getSector() == null) { return false; + } - if (this.getImageSource() == null) + if (this.getImageSource() == null) { return that.imageSource == null && this.getSector().equals(that.getSector()); + } return this.getImageSource().equals(that.getImageSource()) && this.getSector().equals(that.getSector()); } - public int hashCode() - { + public int hashCode() { int result; result = this.getImageSource() != null ? this.getImageSource().hashCode() : 0; result = 31 * result + this.getSector().hashCode(); return result; } - /** {@inheritDoc} */ - public String isExportFormatSupported(String format) - { - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) + /** + * {@inheritDoc} + */ + public String isExportFormatSupported(String format) { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(format)) { return Exportable.FORMAT_SUPPORTED; - else + } else { return Exportable.FORMAT_NOT_SUPPORTED; + } } /** @@ -545,41 +491,32 @@ public String isExportFormatSupported(String format) * * * @param mimeType MIME type of desired export format. - * @param output An object that will receive the exported data. The type of this object depends on the export - * format (see above). + * @param output An object that will receive the exported data. The type of this object depends on the export format + * (see above). * * @throws java.io.IOException If an exception occurs writing to the output object. */ - public void export(String mimeType, Object output) throws IOException - { - if (mimeType == null) - { + public void export(String mimeType, Object output) throws IOException { + if (mimeType == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (output == null) - { + if (output == null) { String message = Logging.getMessage("nullValue.OutputBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) - { - try - { + if (KMLConstants.KML_MIME_TYPE.equalsIgnoreCase(mimeType)) { + try { exportAsKML(output); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { Logging.logger().throwing(getClass().getName(), "export", e); throw new IOException(e); } - } - else - { + } else { String message = Logging.getMessage("Export.UnsupportedFormat", mimeType); Logging.logger().warning(message); throw new UnsupportedOperationException(message); @@ -593,31 +530,24 @@ public void export(String mimeType, Object output) throws IOException * @param output Object to receive the generated KML. * * @throws XMLStreamException If an exception occurs while writing the KML - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -629,22 +559,20 @@ else if (output instanceof OutputStream) // nothing we can do. String imgSourceStr = null; Object imgSource = this.getImageSource(); - if (imgSource instanceof String || imgSource instanceof URL) + if (imgSource instanceof String || imgSource instanceof URL) { imgSourceStr = imgSource.toString(); + } - if (imgSourceStr != null) - { + if (imgSourceStr != null) { // Write geometry xmlWriter.writeStartElement("Icon"); xmlWriter.writeStartElement("href"); xmlWriter.writeCharacters(imgSourceStr); xmlWriter.writeEndElement(); // href xmlWriter.writeEndElement(); // Icon - } - else - { + } else { String message = Logging.getMessage("Export.UnableToExportImageSource", - (imgSource != null ? imgSource.getClass().getName() : "null")); + (imgSource != null ? imgSource.getClass().getName() : "null")); Logging.logger().info(message); } @@ -654,24 +582,21 @@ else if (output instanceof OutputStream) // If the corners of the image are aligned to a sector, we can export the position as a KML LatLonBox. If not, // we'll need to use a gx:LatLonQuad. - if (Sector.isSector(this.corners)) - { + if (Sector.isSector(this.corners)) { exportKMLLatLonBox(xmlWriter); - } - else - { + } else { exportKMLLatLonQuad(xmlWriter); } xmlWriter.writeEndElement(); // GroundOverlay xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } - protected void exportKMLLatLonBox(XMLStreamWriter xmlWriter) throws XMLStreamException - { + protected void exportKMLLatLonBox(XMLStreamWriter xmlWriter) throws XMLStreamException { xmlWriter.writeStartElement("LatLonBox"); xmlWriter.writeStartElement("north"); xmlWriter.writeCharacters(Double.toString(this.sector.getMaxLatitude().getDegrees())); @@ -691,13 +616,11 @@ protected void exportKMLLatLonBox(XMLStreamWriter xmlWriter) throws XMLStreamExc xmlWriter.writeEndElement(); // LatLonBox } - protected void exportKMLLatLonQuad(XMLStreamWriter xmlWriter) throws XMLStreamException - { + protected void exportKMLLatLonQuad(XMLStreamWriter xmlWriter) throws XMLStreamException { xmlWriter.writeStartElement(GXConstants.GX_NAMESPACE, "LatLonQuad"); xmlWriter.writeStartElement("coordinates"); - for (LatLon ll : this.corners) - { + for (LatLon ll : this.corners) { xmlWriter.writeCharacters(Double.toString(ll.getLongitude().getDegrees())); xmlWriter.writeCharacters(","); xmlWriter.writeCharacters(Double.toString(ll.getLatitude().getDegrees())); diff --git a/src/gov/nasa/worldwind/render/SurfaceMultiPolygon.java b/src/gov/nasa/worldwind/render/SurfaceMultiPolygon.java index b68721a3f1..bbbea402c3 100644 --- a/src/gov/nasa/worldwind/render/SurfaceMultiPolygon.java +++ b/src/gov/nasa/worldwind/render/SurfaceMultiPolygon.java @@ -17,31 +17,28 @@ * @author dcollins * @version $Id: SurfaceMultiPolygon.java 2409 2014-10-29 23:47:03Z dcollins $ */ -public class SurfaceMultiPolygon extends AbstractSurfaceShape -{ +public class SurfaceMultiPolygon extends AbstractSurfaceShape { + protected ContourList boundaries = new ContourList(); - /** Constructs a new surface multi polygon with the default attributes and no locations. */ - public SurfaceMultiPolygon() - { + /** + * Constructs a new surface multi polygon with the default attributes and no locations. + */ + public SurfaceMultiPolygon() { } - public SurfaceMultiPolygon(SurfaceMultiPolygon source) - { + public SurfaceMultiPolygon(SurfaceMultiPolygon source) { super(source); this.boundaries.addAllContours(source.boundaries); } - public SurfaceMultiPolygon(ShapeAttributes normalAttrs) - { + public SurfaceMultiPolygon(ShapeAttributes normalAttrs) { super(normalAttrs); } - public SurfaceMultiPolygon(Iterable iterable) - { - if (iterable == null) - { + public SurfaceMultiPolygon(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -50,10 +47,8 @@ public SurfaceMultiPolygon(Iterable iterable) this.boundaries.addContour(iterable); } - public SurfaceMultiPolygon(ContourList contours) - { - if (contours == null) - { + public SurfaceMultiPolygon(ContourList contours) { + if (contours == null) { String message = Logging.getMessage("nullValue.ContourListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -62,12 +57,10 @@ public SurfaceMultiPolygon(ContourList contours) this.boundaries.addAllContours(contours); } - public SurfaceMultiPolygon(ShapeAttributes normalAttrs, Iterable iterable) - { + public SurfaceMultiPolygon(ShapeAttributes normalAttrs, Iterable iterable) { super(normalAttrs); - if (iterable == null) - { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,12 +69,10 @@ public SurfaceMultiPolygon(ShapeAttributes normalAttrs, Iterable getBoundary(int index) - { + public Iterable getBoundary(int index) { return this.boundaries.getContour(index); } - public void addBoundary(Iterable iterable) - { - if (iterable == null) - { + public void addBoundary(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -112,10 +99,8 @@ public void addBoundary(Iterable iterable) this.boundaries.addContour(iterable); } - public void addAllBoundaries(ContourList contours) - { - if (contours == null) - { + public void addAllBoundaries(ContourList contours) { + if (contours == null) { String message = Logging.getMessage("nullValue.ContourListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -124,36 +109,34 @@ public void addAllBoundaries(ContourList contours) this.boundaries.addAllContours(contours); } - public void removeAllBoundaries() - { + public void removeAllBoundaries() { this.boundaries.removeAllContours(); } @Override - public Position getReferencePosition() - { - if (this.boundaries.getContourCount() == 0) + public Position getReferencePosition() { + if (this.boundaries.getContourCount() == 0) { return null; + } Iterator iterator = this.boundaries.getContour(0).iterator(); - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return null; + } return new Position(iterator.next(), 0); } @Override - protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) - { - if (this.boundaries.getContourCount() == 0) + protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) { + if (this.boundaries.getContourCount() == 0) { return; + } - for (int i = 0; i < this.boundaries.getContourCount(); i++) - { + for (int i = 0; i < this.boundaries.getContourCount(); i++) { ArrayList newLocations = new ArrayList(); - for (LatLon ll : this.boundaries.getContour(i)) - { + for (LatLon ll : this.boundaries.getContour(i)) { Angle heading = LatLon.greatCircleAzimuth(oldReferencePosition, ll); Angle pathLength = LatLon.greatCircleDistance(oldReferencePosition, ll); newLocations.add(LatLon.greatCircleEndPosition(newReferencePosition, heading, pathLength)); @@ -167,15 +150,14 @@ protected void doMoveTo(Position oldReferencePosition, Position newReferencePosi } @Override - protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) - { - if (this.boundaries.getContourCount() == 0) + protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) { + if (this.boundaries.getContourCount() == 0) { return; + } - for (int i = 0; i < this.boundaries.getContourCount(); i++) - { + for (int i = 0; i < this.boundaries.getContourCount(); i++) { List newLocations = LatLon.computeShiftedLocations(globe, oldReferencePosition, - newReferencePosition, this.boundaries.getContour(i)); + newReferencePosition, this.boundaries.getContour(i)); this.boundaries.setContour(i, newLocations); } @@ -185,15 +167,14 @@ protected void doMoveTo(Globe globe, Position oldReferencePosition, Position new } @Override - protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) - { - if (this.boundaries.getContourCount() == 0) + protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) { + if (this.boundaries.getContourCount() == 0) { return null; + } ArrayList> geom = new ArrayList>(); - for (int i = 0; i < this.boundaries.getContourCount(); i++) - { + for (int i = 0; i < this.boundaries.getContourCount(); i++) { ArrayList locations = new ArrayList(); this.generateIntermediateLocations(this.boundaries.getContour(i), edgeIntervalsPerDegree, true, locations); geom.add(locations); @@ -203,17 +184,15 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer } @Override - public Iterable getLocations(Globe globe) - { - if (this.boundaries.getContourCount() == 0) + public Iterable getLocations(Globe globe) { + if (this.boundaries.getContourCount() == 0) { return null; + } ArrayList combinedBoundaries = new ArrayList(); - for (int i = 0; i < this.boundaries.getContourCount(); i++) - { - for (LatLon location : this.boundaries.getContour(i)) - { + for (int i = 0; i < this.boundaries.getContourCount(); i++) { + for (LatLon location : this.boundaries.getContour(i)) { combinedBoundaries.add(location); } } @@ -228,8 +207,7 @@ public Iterable getLocations(Globe globe) * @param dc the current DrawContext. */ @Override - protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) - { + protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) { super.handleUnsuccessfulInteriorTessellation(dc); // If tessellating the multi-polygon's interior was unsuccessful, we clear the boundary list to avoid any @@ -238,40 +216,35 @@ protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) this.onShapeChanged(); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); - if (this.boundaries.getContourCount() > 0) - { + if (this.boundaries.getContourCount() > 0) { RestorableSupport.StateObject so = rs.addStateObject(context, "boundaries"); - for (int i = 0; i < this.boundaries.getContourCount(); i++) - { + for (int i = 0; i < this.boundaries.getContourCount(); i++) { rs.addStateValueAsLatLonList(so, "boundary", this.boundaries.getContour(i)); } } } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); RestorableSupport.StateObject so = rs.getStateObject(context, "boundaries"); - if (so != null) - { + if (so != null) { this.boundaries.removeAllContours(); RestorableSupport.StateObject[] sos = rs.getAllStateObjects(so, "boundary"); - if (sos != null) - { - for (RestorableSupport.StateObject boundary : sos) - { - if (boundary == null) + if (sos != null) { + for (RestorableSupport.StateObject boundary : sos) { + if (boundary == null) { continue; + } Iterable locations = rs.getStateObjectAsLatLonList(boundary); - if (locations != null) + if (locations != null) { this.boundaries.addContour(locations); + } } } @@ -281,8 +254,7 @@ protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObjec } @Override - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { throw new UnsupportedOperationException("KML output not supported for SurfaceMultiPolygon"); } } diff --git a/src/gov/nasa/worldwind/render/SurfaceObject.java b/src/gov/nasa/worldwind/render/SurfaceObject.java index dd60b58ce5..d5ae13d872 100644 --- a/src/gov/nasa/worldwind/render/SurfaceObject.java +++ b/src/gov/nasa/worldwind/render/SurfaceObject.java @@ -28,8 +28,8 @@ * @author dcollins * @version $Id: SurfaceObject.java 2283 2014-08-30 15:58:43Z dcollins $ */ -public interface SurfaceObject extends OrderedRenderable, SurfaceRenderable, PreRenderable, AVList -{ +public interface SurfaceObject extends OrderedRenderable, SurfaceRenderable, PreRenderable, AVList { + /** * Indicates whether the surface object should be drawn during rendering. * @@ -77,7 +77,7 @@ public interface SurfaceObject extends OrderedRenderable, SurfaceRenderable, Pre * during picking. * * @return the object used as the pickable object returned during picking, or null to indicate the the surface - * object is returned during picking. + * object is returned during picking. */ Object getDelegateOwner(); @@ -87,7 +87,7 @@ public interface SurfaceObject extends OrderedRenderable, SurfaceRenderable, Pre * returned during picking. * * @param owner the object to use as the pickable object returned during picking, or null to return the surface - * object. + * object. */ void setDelegateOwner(Object owner); @@ -115,7 +115,7 @@ public interface SurfaceObject extends OrderedRenderable, SurfaceRenderable, Pre * Causes the surface object to draw a pickable representation of itself on the surface terrain, using the provided * draw context. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickPoint the pick point. * * @throws IllegalArgumentException if the draw context is null. diff --git a/src/gov/nasa/worldwind/render/SurfaceObjectTileBuilder.java b/src/gov/nasa/worldwind/render/SurfaceObjectTileBuilder.java index 006e0d34f3..6cee69fd6e 100644 --- a/src/gov/nasa/worldwind/render/SurfaceObjectTileBuilder.java +++ b/src/gov/nasa/worldwind/render/SurfaceObjectTileBuilder.java @@ -31,7 +31,8 @@ * context, then draws the surface renderables into those offscreen surface tiles by calling render on each instance. * This process may temporarily use the framebuffer to perform offscreen rendering, and therefore should be called * during the preRender method of a WorldWind layer. See the {@link gov.nasa.worldwind.render.PreRenderable} interface - * for details. Once built, the surface tiles can be rendered by a {@link gov.nasa.worldwind.render.SurfaceTileRenderer}. + * for details. Once built, the surface tiles can be rendered by a + * {@link gov.nasa.worldwind.render.SurfaceTileRenderer}. *

          * By default, SurfaceObjectTileBuilder creates texture tiles with a width and height of 512 pixels, and with internal * format GL_RGBA. These parameters are configurable by calling {@link @@ -65,27 +66,37 @@ * @author dcollins * @version $Id: SurfaceObjectTileBuilder.java 3108 2015-05-26 19:07:06Z dcollins $ */ -public class SurfaceObjectTileBuilder -{ - /** The default surface tile texture dimension, in pixels. */ +public class SurfaceObjectTileBuilder { + + /** + * The default surface tile texture dimension, in pixels. + */ protected static final int DEFAULT_TEXTURE_DIMENSION = 512; - /** The default OpenGL internal format used to create surface tile textures. */ + /** + * The default OpenGL internal format used to create surface tile textures. + */ protected static final int DEFAULT_TEXTURE_INTERNAL_FORMAT = GL.GL_RGBA8; - /** The default OpenGL pixel format used to create surface tile textures. */ + /** + * The default OpenGL pixel format used to create surface tile textures. + */ protected static final int DEFAULT_TEXTURE_PIXEL_FORMAT = GL.GL_RGBA; /** * The default split scale. The split scale 2.9 has been empirically determined to render sharp lines and edges with * the SurfaceShapes such as SurfacePolyline and SurfacePolygon. */ protected static final double DEFAULT_SPLIT_SCALE = 2.9; - /** The default level zero tile delta used to construct a LevelSet. */ + /** + * The default level zero tile delta used to construct a LevelSet. + */ protected static final LatLon DEFAULT_LEVEL_ZERO_TILE_DELTA = LatLon.fromDegrees(36, 36); /** * The default number of levels used to construct a LevelSet. Approximately 0.1 meters per pixel at the Earth's * equator. */ protected static final int DEFAULT_NUM_LEVELS = 17; - /** The next unique ID. This property is shared by all instances of SurfaceObjectTileBuilder. */ + /** + * The next unique ID. This property is shared by all instances of SurfaceObjectTileBuilder. + */ protected static long nextUniqueId = 1; /** * Map associating a tile texture dimension to its corresponding LevelSet. This map is a class property in order to @@ -98,34 +109,49 @@ public class SurfaceObjectTileBuilder * DEFAULT_TEXTURE_DIMENSION. */ protected Dimension tileDimension = new Dimension(DEFAULT_TEXTURE_DIMENSION, DEFAULT_TEXTURE_DIMENSION); - /** The surface tile OpenGL texture format. 0 indicates the default format is used. */ + /** + * The surface tile OpenGL texture format. 0 indicates the default format is used. + */ protected int tileTextureFormat; - /** Controls if surface tiles are rendered using a linear filter or a nearest-neighbor filter. */ + /** + * Controls if surface tiles are rendered using a linear filter or a nearest-neighbor filter. + */ protected boolean useLinearFilter = true; - /** Controls if mip-maps are generated for surface tile textures. */ + /** + * Controls if mip-maps are generated for surface tile textures. + */ protected boolean useMipmaps = true; - /** Controls if tiles are forced to update during {@link #buildTiles(DrawContext, Iterable)}. */ + /** + * Controls if tiles are forced to update during {@link #buildTiles(DrawContext, Iterable)}. + */ protected boolean forceTileUpdates; - /** Controls the tile resolution as distance changes between the globe's surface and the eye point. */ + /** + * Controls the tile resolution as distance changes between the globe's surface and the eye point. + */ protected double splitScale = DEFAULT_SPLIT_SCALE; /** * List of currently assembled surface renderables. Valid only during the execution of {@link * #buildTiles(DrawContext, Iterable)}. */ protected List currentSurfaceObjects = new ArrayList(); - /** List of currently assembled surface tiles. */ + /** + * List of currently assembled surface tiles. + */ protected Map tileInfoMap = new HashMap(); - /** The currently active TileInfo. Valid only during the execution of {@link #buildTiles(DrawContext, Iterable)}. */ + /** + * The currently active TileInfo. Valid only during the execution of {@link #buildTiles(DrawContext, Iterable)}. + */ protected TileInfo currentInfo; - /** Support class used to render to an offscreen surface tile. */ + /** + * Support class used to render to an offscreen surface tile. + */ protected OGLRenderToTextureSupport rttSupport = new OGLRenderToTextureSupport(); /** * Constructs a new SurfaceObjectTileBuilder with a tile width and height of 512, with the default tile * texture format, with linear filtering enabled, and with mip-mapping disabled. */ - public SurfaceObjectTileBuilder() - { + public SurfaceObjectTileBuilder() { } /** @@ -133,18 +159,16 @@ public SurfaceObjectTileBuilder() * specifying if linear filtering and mip-mapping are enabled. * * @param tileTextureDimension the surface tile texture dimension, in pixels. - * @param tileTextureFormat the surface tile OpenGL texture format, or 0 to use the default format. - * @param useLinearFilter true to use linear filtering while rendering surface tiles; false to use - * nearest-neighbor filtering. - * @param useMipmaps true to generate mip-maps for surface tile textures; false otherwise. + * @param tileTextureFormat the surface tile OpenGL texture format, or 0 to use the default format. + * @param useLinearFilter true to use linear filtering while rendering surface tiles; false to use nearest-neighbor + * filtering. + * @param useMipmaps true to generate mip-maps for surface tile textures; false otherwise. * * @throws IllegalArgumentException if the tile dimension is null. */ public SurfaceObjectTileBuilder(Dimension tileTextureDimension, int tileTextureFormat, boolean useLinearFilter, - boolean useMipmaps) - { - if (tileTextureDimension == null) - { + boolean useMipmaps) { + if (tileTextureDimension == null) { String message = Logging.getMessage("nullValue.DimensionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -161,8 +185,7 @@ public SurfaceObjectTileBuilder(Dimension tileTextureDimension, int tileTextureF * * @return the surface tile dimension, in pixels. */ - public Dimension getTileDimension() - { + public Dimension getTileDimension() { return this.tileDimension; } @@ -175,10 +198,8 @@ public Dimension getTileDimension() * * @throws IllegalArgumentException if the dimension is null. */ - public void setTileDimension(Dimension dimension) - { - if (dimension == null) - { + public void setTileDimension(Dimension dimension) { + if (dimension == null) { String message = Logging.getMessage("nullValue.DimensionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -194,8 +215,7 @@ public void setTileDimension(Dimension dimension) * * @see #setTileTextureFormat(int) */ - public int getTileTextureFormat() - { + public int getTileTextureFormat() { return tileTextureFormat; } @@ -214,7 +234,7 @@ public int getTileTextureFormat() *

        • GL_RGB10
        • GL_RGB12
        • GL_RGB16
        • GL_RGBA
        • GL_RGBA2
        • GL_RGBA4
        • *
        • GL_RGB5_A1
        • GL_RGBA8
        • GL_RGB10_A2
        • GL_RGBA12
        • GL_RGBA16
        • *
        • GL_SLUMINANCE
        • GL_SLUMINANCE8
        • GL_SLUMINANCE_ALPHA
        • GL_SLUMINANCE8_ALPHA8
        • - *
        • GL_SRGB
        • GL_SRGB8
        • GL_SRGB_ALPHA
        • GL_SRGB8_ALPHA8
        • + *
        • GL_SRGB
        • GL_SRGB8
        • GL_SRGB_ALPHA
        • GL_SRGB8_ALPHA8
        • *

          * If the texture format is any of GL_RGB, GL_RGB8, GL_RGBA, or GL_RGBA8, the tile builder attempts to * use OpenGL framebuffer objects to render shapes to the texture tiles. Otherwise, this renders shapes to the @@ -222,8 +242,7 @@ public int getTileTextureFormat() * * @param textureFormat the OpenGL texture format, or 0 to use the default format. */ - public void setTileTextureFormat(int textureFormat) - { + public void setTileTextureFormat(int textureFormat) { this.tileTextureFormat = textureFormat; } @@ -232,8 +251,7 @@ public void setTileTextureFormat(int textureFormat) * * @return true if linear filtering is used; false if nearest-neighbor filtering is used. */ - public boolean isUseLinearFilter() - { + public boolean isUseLinearFilter() { return useLinearFilter; } @@ -242,8 +260,7 @@ public boolean isUseLinearFilter() * * @param useLinearFilter true to use linear filtering; false to use nearest-neighbor filtering. */ - public void setUseLinearFilter(boolean useLinearFilter) - { + public void setUseLinearFilter(boolean useLinearFilter) { this.useLinearFilter = useLinearFilter; } @@ -252,8 +269,7 @@ public void setUseLinearFilter(boolean useLinearFilter) * * @return true if mip-maps are generated; false otherwise. */ - public boolean isUseMipmaps() - { + public boolean isUseMipmaps() { return this.useMipmaps; } @@ -262,8 +278,7 @@ public boolean isUseMipmaps() * * @param useMipmaps true to generate mip-maps; false otherwise. */ - public void setUseMipmaps(boolean useMipmaps) - { + public void setUseMipmaps(boolean useMipmaps) { this.useMipmaps = useMipmaps; } @@ -275,8 +290,7 @@ public void setUseMipmaps(boolean useMipmaps) * @return true if tile textures always update their contents, false if tile textures only update when the surface * renderables change. */ - public boolean isForceTileUpdates() - { + public boolean isForceTileUpdates() { return this.forceTileUpdates; } @@ -286,10 +300,9 @@ public boolean isForceTileUpdates() * textures only update their contents when the surface renderables change. * * @param forceTileUpdates true if tile textures should always update their contents, false if tile textures should - * only update when the surface renderables change. + * only update when the surface renderables change. */ - public void setForceTileUpdates(boolean forceTileUpdates) - { + public void setForceTileUpdates(boolean forceTileUpdates) { this.forceTileUpdates = forceTileUpdates; } @@ -299,11 +312,10 @@ public void setForceTileUpdates(boolean forceTileUpdates) * split scale decreases from 1.0. The default value is 2.9. * * @param splitScale a value near 1.0 that controls the tile's surface texel resolution as the distance between the - * globe's surface and the eye point change. Increasing values select higher resolution, - * decreasing values select lower resolution. The default value is 2.9. + * globe's surface and the eye point change. Increasing values select higher resolution, decreasing values select + * lower resolution. The default value is 2.9. */ - public void setSplitScale(double splitScale) - { + public void setSplitScale(double splitScale) { this.splitScale = splitScale; } @@ -315,8 +327,7 @@ public void setSplitScale(double splitScale) * * @see #setSplitScale(double) */ - public double getSplitScale() - { + public double getSplitScale() { return this.splitScale; } @@ -329,10 +340,8 @@ public double getSplitScale() * * @throws IllegalArgumentException if the draw context is null. */ - public int getTileCount(DrawContext dc) - { - if (dc == null) - { + public int getTileCount(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -352,10 +361,8 @@ public int getTileCount(DrawContext dc) * * @throws IllegalArgumentException if the draw context is null. */ - public Collection getTiles(DrawContext dc) - { - if (dc == null) - { + public Collection getTiles(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -374,15 +381,13 @@ public Collection getTiles(DrawContext dc) *

          * This does nothing if the specified iterable is null, is empty or contains no surface renderables. * - * @param dc the draw context to build tiles for. + * @param dc the draw context to build tiles for. * @param iterable the iterable to gather surface renderables from. * * @throws IllegalArgumentException if the draw context is null. */ - public void buildTiles(DrawContext dc, Iterable iterable) - { - if (dc == null) - { + public void buildTiles(DrawContext dc, Iterable iterable) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -390,8 +395,7 @@ public void buildTiles(DrawContext dc, Iterable iterable) TileInfoKey tileInfoKey = this.createTileInfoKey(dc); this.currentInfo = this.tileInfoMap.get(tileInfoKey); - if (this.currentInfo == null) - { + if (this.currentInfo == null) { this.currentInfo = this.createTileInfo(dc); this.tileInfoMap.put(tileInfoKey, this.currentInfo); } @@ -399,16 +403,18 @@ public void buildTiles(DrawContext dc, Iterable iterable) this.currentSurfaceObjects.clear(); this.currentInfo.tiles.clear(); - if (iterable == null) + if (iterable == null) { return; + } // Assemble the list of current surface renderables from the specified iterable. this.assembleSurfaceObjects(iterable); // We've cleared any tile assembly state from the last rendering pass. Determine if we can assemble and update // the tiles. If not, we're done. - if (this.currentSurfaceObjects.isEmpty() || !this.canAssembleTiles(dc)) + if (this.currentSurfaceObjects.isEmpty() || !this.canAssembleTiles(dc)) { return; + } // Assemble the current visible tiles and update their associated textures if necessary. this.assembleTiles(dc); @@ -417,8 +423,7 @@ public void buildTiles(DrawContext dc, Iterable iterable) // Clear references to surface renderables to avoid dangling references. The surface renderable list is no // longer needed, no are the lists held by each tile. this.currentSurfaceObjects.clear(); - for (SurfaceObjectTile tile : this.currentInfo.tiles) - { + for (SurfaceObjectTile tile : this.currentInfo.tiles) { tile.clearObjectList(); } } @@ -431,10 +436,8 @@ public void buildTiles(DrawContext dc, Iterable iterable) * * @throws IllegalArgumentException if the draw context is null. */ - public void clearTiles(DrawContext dc) - { - if (dc == null) - { + public void clearTiles(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -442,8 +445,7 @@ public void clearTiles(DrawContext dc) Object tileInfoKey = this.createTileInfoKey(dc); TileInfo tileInfo = this.tileInfoMap.get(tileInfoKey); - if (tileInfo != null) - { + if (tileInfo != null) { tileInfo.tiles.clear(); } } @@ -458,10 +460,8 @@ public void clearTiles(DrawContext dc) * * @throws IllegalArgumentException if the draw context is null. */ - public Collection getPickCandidates(DrawContext dc) - { - if (dc == null) - { + public Collection getPickCandidates(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -480,10 +480,8 @@ public Collection getPickCandidates(DrawContext dc) * * @throws IllegalArgumentException if the draw context is null. */ - public void clearPickCandidates(DrawContext dc) - { - if (dc == null) - { + public void clearPickCandidates(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -491,8 +489,7 @@ public void clearPickCandidates(DrawContext dc) Object tileInfoKey = this.createTileInfoKey(dc); TileInfo tileInfo = this.tileInfoMap.get(tileInfoKey); - if (tileInfo != null) - { + if (tileInfo != null) { tileInfo.pickCandidates.clear(); } } @@ -500,7 +497,6 @@ public void clearPickCandidates(DrawContext dc) //**************************************************************// //******************** Tile Updating *************************// //**************************************************************// - /** * Updates each {@link SurfaceObjectTileBuilder.SurfaceObjectTile} in the {@link #currentInfo}. This is typically * called after {@link #assembleTiles(DrawContext)} to update the assembled tiles. @@ -509,10 +505,10 @@ public void clearPickCandidates(DrawContext dc) * * @param dc the draw context the tiles relate to. */ - protected void updateTiles(DrawContext dc) - { - if (this.currentInfo.tiles.isEmpty()) + protected void updateTiles(DrawContext dc) { + if (this.currentInfo.tiles.isEmpty()) { return; + } // The tile drawing rectangle has the same dimension as the current tile viewport, but it's lower left corner // is placed at the origin. This is because the orthographic projection setup by OGLRenderToTextureSupport @@ -520,27 +516,23 @@ protected void updateTiles(DrawContext dc) // drawing pixels to the texture, as (0, 0) is automatically mapped to (x, y). Since we've created the tiles // from a LevelSet where each level has equivalent dimension, we assume that tiles in the current tile list // have equivalent dimension. - // The OpenGL framebuffer object extension used by RenderToTextureSupport works only for texture formats // GL_RGB and GL_RGBA. Disable framebuffer objects if the tile builder has been configured with a different // format. this.rttSupport.setEnableFramebufferObject( - this.tileTextureFormat == 0 || // Default format is GL_RGB8. - this.tileTextureFormat == GL.GL_RGB || - this.tileTextureFormat == GL.GL_RGB8 || - this.tileTextureFormat == GL.GL_RGBA || - this.tileTextureFormat == GL.GL_RGBA8); + this.tileTextureFormat == 0 + || // Default format is GL_RGB8. + this.tileTextureFormat == GL.GL_RGB + || this.tileTextureFormat == GL.GL_RGB8 + || this.tileTextureFormat == GL.GL_RGBA + || this.tileTextureFormat == GL.GL_RGBA8); this.rttSupport.beginRendering(dc, 0, 0, this.currentInfo.tileWidth, this.currentInfo.tileHeight); - try - { - for (SurfaceObjectTile tile : this.currentInfo.tiles) - { + try { + for (SurfaceObjectTile tile : this.currentInfo.tiles) { this.updateTile(dc, tile); } - } - finally - { + } finally { this.rttSupport.endRendering(dc); } } @@ -551,11 +543,10 @@ protected void updateTiles(DrawContext dc) * those objects. The tile is updated if the list changes, if any of the state keys change, or if the tile has no * texture. Otherwise the tile is left unchanged and the update is skipped. * - * @param dc the draw context the tile relates to. + * @param dc the draw context the tile relates to. * @param tile the tile to update. */ - protected void updateTile(DrawContext dc, SurfaceObjectTile tile) - { + protected void updateTile(DrawContext dc, SurfaceObjectTile tile) { // Get the tile's texture from the draw context's texture cache. If null we create a new texture and update the // texture cache below. Texture texture = tile.getTexture(dc.getTextureCache()); @@ -567,11 +558,11 @@ protected void updateTile(DrawContext dc, SurfaceObjectTile tile) // * The tile has no state. // * The list of intersecting objects has changed. // * An intersecting object's state key is different than one stored in the tile's previous state key. - if (!this.isForceTileUpdates()) - { + if (!this.isForceTileUpdates()) { Object tileStateKey = tile.getStateKey(dc); - if (texture != null && tileStateKey.equals(tile.lastUpdateStateKey)) + if (texture != null && tileStateKey.equals(tile.lastUpdateStateKey)) { return; + } // If the tile needs to be updated, then assign its lastUpdateStateKey before its texture is created. This // ensures that the lastUpdateStateKey is current when the tile is added to the cache. @@ -590,8 +581,7 @@ protected void updateTile(DrawContext dc, SurfaceObjectTile tile) return; } - try - { + try { // Surface renderables expect the SurfaceTileDrawContext to be attached to the draw context's AVList. Create // a SurfaceTileDrawContext with the tile's Sector and viewport. The Sector defines the context's geographic // extent, and the viewport defines the context's corresponding viewport in pixels. @@ -600,16 +590,12 @@ protected void updateTile(DrawContext dc, SurfaceObjectTile tile) this.rttSupport.setColorTarget(dc, texture); this.rttSupport.clear(dc, new Color(0, 0, 0, 0)); // Set all texture pixels to transparent black. - if (tile.hasObjects()) - { - for (SurfaceRenderable so : tile.getObjectList()) - { + if (tile.hasObjects()) { + for (SurfaceRenderable so : tile.getObjectList()) { so.render(dc); } } - } - finally - { + } finally { this.rttSupport.setColorTarget(dc, null); dc.removeKey(AVKey.SURFACE_TILE_DRAW_CONTEXT); @@ -622,44 +608,47 @@ protected void updateTile(DrawContext dc, SurfaceObjectTile tile) * The returned texture's internal format is specified by tilePixelFormat. If * tilePixelFormat is zero, this returns a texture with internal format GL_RGBA8. *

          - * The returned texture's parameters are configured as follows: + *
          Parameters
          Parameter - * NameValue
          GL.GL_TEXTURE_MIN_FILTERGL_LINEAR_MIPMAP_LINEAR - * if useLinearFilter and useMipmaps are both true, GL_LINEAR if + * The returned texture's parameters are configured as follows: + * + * + * useLinearFilter is false. + * + * *
          Parameters
          Parameter NameValue
          GL.GL_TEXTURE_MIN_FILTERGL_LINEAR_MIPMAP_LINEAR if + * useLinearFilter and useMipmaps are both true, GL_LINEAR if * useLinearFilter is true and useMipmaps is false, and GL_NEAREST if - * useLinearFilter is false.
          GL.GL_TEXTURE_MAG_FILTERGL_LINEAR - * if useLinearFilter is true, GL_NEAREST if useLinearFilter is - * false.
          GL.GL_TEXTURE_WRAP_SGL_CLAMP_TO_EDGE
          GL.GL_TEXTURE_MAG_FILTERGL_LINEAR if useLinearFilter is + * true, GL_NEAREST if useLinearFilter is false.
          GL.GL_TEXTURE_WRAP_SGL_CLAMP_TO_EDGE
          GL.GL_TEXTURE_WRAP_TGL_CLAMP_TO_EDGE
          * - * @param dc the draw context to create a texture for. - * @param width the texture's width, in pixels. + * @param dc the draw context to create a texture for. + * @param width the texture's width, in pixels. * @param height the texture's height, in pixels. * * @return a new texture with the specified width and height. */ - protected Texture createTileTexture(DrawContext dc, int width, int height) - { + protected Texture createTileTexture(DrawContext dc, int width, int height) { int internalFormat = this.tileTextureFormat; - if (internalFormat == 0) + if (internalFormat == 0) { internalFormat = DEFAULT_TEXTURE_INTERNAL_FORMAT; + } int pixelFormat = OGLUtil.computeTexturePixelFormat(internalFormat); - if (pixelFormat == 0) + if (pixelFormat == 0) { pixelFormat = DEFAULT_TEXTURE_PIXEL_FORMAT; + } Texture t; GL gl = dc.getGL(); TextureData td = new TextureData( - gl.getGLProfile(), // GL profile - internalFormat, // internal format - width, height, // dimension - 0, // border - pixelFormat, // pixel format - GL.GL_UNSIGNED_BYTE, // pixel type - this.isUseMipmaps(), // mipmap - false, false, // dataIsCompressed, mustFlipVertically - null, null) // buffer, flusher + gl.getGLProfile(), // GL profile + internalFormat, // internal format + width, height, // dimension + 0, // border + pixelFormat, // pixel format + GL.GL_UNSIGNED_BYTE, // pixel type + this.isUseMipmaps(), // mipmap + false, false, // dataIsCompressed, mustFlipVertically + null, null) // buffer, flusher { /** * Overridden to return a non-zero size. TextureData does not compute an estimated memory size if the buffer @@ -667,12 +656,12 @@ protected Texture createTileTexture(DrawContext dc, int width, int height) * texture with the common pixel formats. */ @Override - public int getEstimatedMemorySize() - { + public int getEstimatedMemorySize() { int sizeInBytes = OGLUtil.estimateTextureMemorySize(this.getInternalFormat(), this.getWidth(), - this.getHeight(), this.getMipmap()); - if (sizeInBytes > 0) + this.getHeight(), this.getMipmap()); + if (sizeInBytes > 0) { return sizeInBytes; + } return super.getEstimatedMemorySize(); } @@ -681,18 +670,16 @@ public int getEstimatedMemorySize() t = TextureIO.newTexture(td); t.bind(gl); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, this.isUseLinearFilter() ? - (this.isUseMipmaps() ? GL.GL_LINEAR_MIPMAP_LINEAR : GL.GL_LINEAR) : GL.GL_NEAREST); - gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, this.isUseLinearFilter() ? - GL.GL_LINEAR : GL.GL_NEAREST); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, this.isUseLinearFilter() + ? (this.isUseMipmaps() ? GL.GL_LINEAR_MIPMAP_LINEAR : GL.GL_LINEAR) : GL.GL_NEAREST); + gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, this.isUseLinearFilter() + ? GL.GL_LINEAR : GL.GL_NEAREST); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); - if (this.isUseMipmaps()) - { + if (this.isUseMipmaps()) { double maxAnisotropy = dc.getGLRuntimeCapabilities().getMaxTextureAnisotropy(); - if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) - { + if (dc.getGLRuntimeCapabilities().isUseAnisotropicTextureFilter() && maxAnisotropy >= 2.0) { gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, (float) maxAnisotropy); } } @@ -708,34 +695,30 @@ public int getEstimatedMemorySize() * * @return a new drawing context for the specified tile. */ - protected Object createSurfaceTileDrawContext(SurfaceObjectTile tile) - { + protected Object createSurfaceTileDrawContext(SurfaceObjectTile tile) { return new SurfaceTileDrawContext(tile, this.currentInfo.pickCandidates); } //**************************************************************// //******************** Surface Renderable Assembly ***********// //**************************************************************// - /** * Adds any SurfaceRenderables in the specified Iterable to the tile builder's {@link #currentSurfaceObjects} list. * * @param iterable the Iterable to gather SurfaceRenderables from. */ - protected void assembleSurfaceObjects(Iterable iterable) - { + protected void assembleSurfaceObjects(Iterable iterable) { // Gather up all the SurfaceRenderables, ignoring null references and non SurfaceRenderables. - for (Object o : iterable) - { - if (o instanceof SurfaceRenderable) + for (Object o : iterable) { + if (o instanceof SurfaceRenderable) { this.currentSurfaceObjects.add((SurfaceRenderable) o); + } } } //**************************************************************// //******************** LevelSet Assembly *********************// //**************************************************************// - /** * Returns a shared LevelSet for the specified tileDimension. All instances of * SurfaceObjectTileBuilder share common LevelSets to determine which tiles are visible, but create @@ -750,22 +733,19 @@ protected void assembleSurfaceObjects(Iterable iterable) * retained once constructed. Retaining references to the LevelSets means we're able to re-use the * texture resources associated with each LevelSet in the DrawContext's texture cache. *

          - * Subsequent calls are guaranteed to return the same LevelSet for the same - * tileDimension. + * Subsequent calls are guaranteed to return the same LevelSet for the same tileDimension. * - * @param tileWidth the tile width, in pixels. + * @param tileWidth the tile width, in pixels. * @param tileHeight the tile height, in pixels. * * @return a LevelSet with the specified tile dimensions. */ - protected LevelSet getLevelSet(int tileWidth, int tileHeight) - { + protected LevelSet getLevelSet(int tileWidth, int tileHeight) { // If we already have a LevelSet for the dimension, just return it. Otherwise create it and put it in a map for // use during subsequent calls. Dimension key = new Dimension(tileWidth, tileHeight); LevelSet levelSet = levelSetMap.get(key); - if (levelSet == null) - { + if (levelSet == null) { levelSet = createLevelSet(tileWidth, tileHeight); levelSetMap.put(key, levelSet); } @@ -779,13 +759,12 @@ protected LevelSet getLevelSet(int tileWidth, int tileHeight) * #DEFAULT_NUM_LEVELS} (with no empty levels). The LevelSets' cache name and dataset name dummy values, and should * not be used. * - * @param tileWidth the LevelSet's tile width, in pixels. + * @param tileWidth the LevelSet's tile width, in pixels. * @param tileHeight the LevelSet's tile height, in pixels. * * @return a new LevelSet configured to with */ - protected static LevelSet createLevelSet(int tileWidth, int tileHeight) - { + protected static LevelSet createLevelSet(int tileWidth, int tileHeight) { AVList params = new AVListImpl(); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, DEFAULT_LEVEL_ZERO_TILE_DELTA); params.setValue(AVKey.SECTOR, Sector.FULL_SPHERE); @@ -805,7 +784,6 @@ protected static LevelSet createLevelSet(int tileWidth, int tileHeight) //**************************************************************// //******************** Tile Assembly *************************// //**************************************************************// - /** * Returns true if the draw context's viewport width and height are greater than zero. * @@ -813,8 +791,7 @@ protected static LevelSet createLevelSet(int tileWidth, int tileHeight) * * @return true if the DrawContext's has a non-zero viewport; false otherwise. */ - protected boolean canAssembleTiles(DrawContext dc) - { + protected boolean canAssembleTiles(DrawContext dc) { Rectangle viewport = dc.getView().getViewport(); return viewport.getWidth() > 0 && viewport.getHeight() > 0; } @@ -834,8 +811,7 @@ protected boolean canAssembleTiles(DrawContext dc) * * @param dc the DrawContext to assemble tiles for. */ - protected void assembleTiles(DrawContext dc) - { + protected void assembleTiles(DrawContext dc) { LevelSet levelSet = this.currentInfo.levelSet; String tileCacheName = this.currentInfo.cacheName; @@ -856,14 +832,13 @@ protected void assembleTiles(DrawContext dc) // and add object to those tiles. This has the effect of quickly sorting the objects into the top level tiles. // We collect the top level tiles in a HashSet to ensure there are no duplicates when multiple objects intersect // the same top level tiles. - for (SurfaceRenderable so : this.currentSurfaceObjects) - { + for (SurfaceRenderable so : this.currentSurfaceObjects) { List sectors = so.getSectors(dc); - if (sectors == null) + if (sectors == null) { continue; + } - for (Sector s : sectors) - { + for (Sector s : sectors) { // Use the LevelSets tiling scheme to index the surface renderable's sector into the top level tiles. // This index operation is faster than computing an intersection test between each tile and the list of // surface renderables. @@ -873,14 +848,12 @@ protected void assembleTiles(DrawContext dc) int lastCol = Tile.computeColumn(dLon, s.getMaxLongitude(), lonOrigin); Angle p1 = Tile.computeRowLatitude(firstRow, dLat, latOrigin); - for (int row = firstRow; row <= lastRow; row++) - { + for (int row = firstRow; row <= lastRow; row++) { Angle p2; p2 = p1.add(dLat); Angle t1 = Tile.computeColumnLongitude(firstCol, dLon, lonOrigin); - for (int col = firstCol; col <= lastCol; col++) - { + for (int col = firstCol; col <= lastCol; col++) { Angle t2; t2 = t1.add(dLon); @@ -888,12 +861,12 @@ protected void assembleTiles(DrawContext dc) // Ignore this tile if the surface renderable has already been added to it. This handles // dateline spanning surface renderables which have two sectors that share a common boundary. - if (intersectingTileKeys.contains(tileKey)) + if (intersectingTileKeys.contains(tileKey)) { continue; + } SurfaceObjectTile tile = (SurfaceObjectTile) TextureTile.getMemoryCache().getObject(tileKey); - if (tile == null) - { + if (tile == null) { tile = this.createTile(new Sector(p1, p2, t1, t2), level, row, col, tileCacheName); TextureTile.getMemoryCache().add(tileKey, tile); } @@ -912,8 +885,7 @@ protected void assembleTiles(DrawContext dc) } // Add each top level tile or its descendants to the current tile list. - for (SurfaceObjectTile tile : topLevelTiles) - { + for (SurfaceObjectTile tile : topLevelTiles) { this.addTileOrDescendants(dc, levelSet, null, tile); } } @@ -927,17 +899,15 @@ protected void assembleTiles(DrawContext dc) * currentTiles list. Otherwise, it's split into four sub-tiles and each tile is recursively processed. * See {@link #meetsRenderCriteria(DrawContext, gov.nasa.worldwind.util.LevelSet, gov.nasa.worldwind.util.Tile)}. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param levelSet the tile's LevelSet. - * @param parent the tile's parent, or null if the tile is a top level tile. - * @param tile the tile to add. + * @param parent the tile's parent, or null if the tile is a top level tile. + * @param tile the tile to add. */ protected void addTileOrDescendants(DrawContext dc, LevelSet levelSet, SurfaceObjectTile parent, - SurfaceObjectTile tile) - { + SurfaceObjectTile tile) { // Ignore this tile if it falls completely outside the DrawContext's visible sector. - if (!this.intersectsVisibleSector(dc, tile)) - { + if (!this.intersectsVisibleSector(dc, tile)) { // This tile is not added to the current tile list, so we clear it's object list to prepare it for use // during the next frame. tile.clearObjectList(); @@ -946,8 +916,7 @@ protected void addTileOrDescendants(DrawContext dc, LevelSet levelSet, SurfaceOb // Ignore this tile if it falls completely outside the frustum. This may be the viewing frustum or the pick // frustum, depending on the implementation. - if (!this.intersectsFrustum(dc, tile)) - { + if (!this.intersectsFrustum(dc, tile)) { // This tile is not added to the current tile list, so we clear it's object list to prepare it for use // during the next frame. tile.clearObjectList(); @@ -955,24 +924,24 @@ protected void addTileOrDescendants(DrawContext dc, LevelSet levelSet, SurfaceOb } // If the parent tile is not null, add any parent surface renderables that intersect this tile. - if (parent != null) + if (parent != null) { this.addIntersectingObjects(dc, parent, tile); + } // Ignore tiles that do not intersect any surface renderables. - if (!tile.hasObjects()) + if (!tile.hasObjects()) { return; + } // If this tile meets the current rendering criteria, add it to the current tile list. This tile's object list // is cleared after the tile update operation. - if (this.meetsRenderCriteria(dc, levelSet, tile)) - { + if (this.meetsRenderCriteria(dc, levelSet, tile)) { this.addTile(tile); return; } Level nextLevel = levelSet.getLevel(tile.getLevelNumber() + 1); - for (TextureTile subTile : tile.createSubTiles(nextLevel)) - { + for (TextureTile subTile : tile.createSubTiles(nextLevel)) { this.addTileOrDescendants(dc, levelSet, tile, (SurfaceObjectTile) subTile); } @@ -986,44 +955,40 @@ protected void addTileOrDescendants(DrawContext dc, LevelSet levelSet, SurfaceOb * does not intersect the sector bounding the parent's object list, this does nothing. Otherwise, this adds any of * the parent's surface renderables that intersect the tile's sector to the tile's object list. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param parent the tile's parent. - * @param tile the tile to add intersecting surface renderables to. + * @param tile the tile to add intersecting surface renderables to. */ - protected void addIntersectingObjects(DrawContext dc, SurfaceObjectTile parent, SurfaceObjectTile tile) - { + protected void addIntersectingObjects(DrawContext dc, SurfaceObjectTile parent, SurfaceObjectTile tile) { // If the parent has no objects, then there's nothing to add to this tile and we exit immediately. - if (!parent.hasObjects()) + if (!parent.hasObjects()) { return; + } // If this tile does not intersect the parent's object bounding sector, then none of the parent's objects // intersect this tile. Therefore we exit immediately, and do not add any objects to this tile. - if (!tile.getSector().intersects(parent.getObjectSector())) + if (!tile.getSector().intersects(parent.getObjectSector())) { return; + } // If this tile contains the parent's object bounding sector, then all of the parent's objects intersect this // tile. Therefore we just add all of the parent's objects to this tile. Additionally, the parent's object // bounding sector becomes this tile's object bounding sector. - if (tile.getSector().contains(parent.getObjectSector())) - { + if (tile.getSector().contains(parent.getObjectSector())) { tile.addAllSurfaceObjects(parent.getObjectList(), parent.getObjectSector()); - } - // Otherwise, the tile may intersect some of the parent's object list. Compute which objects intersect this + } // Otherwise, the tile may intersect some of the parent's object list. Compute which objects intersect this // tile, and compute this tile's bounding sector as the union of those object's sectors. - else - { - for (SurfaceRenderable so : parent.getObjectList()) - { + else { + for (SurfaceRenderable so : parent.getObjectList()) { List sectors = so.getSectors(dc); - if (sectors == null) + if (sectors == null) { continue; + } // Test intersection against each of the surface renderable's sectors. We break after finding an // intersection to avoid adding the same object to the tile more than once. - for (Sector s : sectors) - { - if (tile.getSector().intersects(s)) - { + for (Sector s : sectors) { + if (tile.getSector().intersects(s)) { tile.addSurfaceObject(so, s); break; } @@ -1037,8 +1002,7 @@ protected void addIntersectingObjects(DrawContext dc, SurfaceObjectTile parent, * * @param tile the tile to add. */ - protected void addTile(SurfaceObjectTile tile) - { + protected void addTile(SurfaceObjectTile tile) { this.currentInfo.tiles.add(tile); TextureTile.getMemoryCache().add(tile.getTileKey(), tile); } @@ -1048,19 +1012,20 @@ protected void addTile(SurfaceObjectTile tile) * against all of the draw context's pick frustums. During rendering mode, this tests intersection against the draw * context's viewing frustum. * - * @param dc the draw context the surface renderable is related to. + * @param dc the draw context the surface renderable is related to. * @param tile the tile to test for intersection. * * @return true if the tile intersects the draw context's frustum; false otherwise. */ - protected boolean intersectsFrustum(DrawContext dc, TextureTile tile) - { + protected boolean intersectsFrustum(DrawContext dc, TextureTile tile) { Extent extent = tile.getExtent(dc); - if (extent == null) + if (extent == null) { return false; + } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(extent); + } return dc.getView().getFrustumInModelCoordinates().intersects(extent); } @@ -1069,13 +1034,12 @@ protected boolean intersectsFrustum(DrawContext dc, TextureTile tile) * Test if the specified tile intersects the draw context's visible sector. This returns false if the draw context's * visible sector is null. * - * @param dc the current draw context. + * @param dc the current draw context. * @param tile the tile to test for intersection. * * @return true if the tile intersects the draw context's visible sector; false otherwise. */ - protected boolean intersectsVisibleSector(DrawContext dc, TextureTile tile) - { + protected boolean intersectsVisibleSector(DrawContext dc, TextureTile tile) { return dc.getVisibleSector() != null && dc.getVisibleSector().intersects(tile.getSector()); } @@ -1083,14 +1047,13 @@ protected boolean intersectsVisibleSector(DrawContext dc, TextureTile tile) * Tests if the specified tile meets the rendering criteria on the specified draw context. This returns true if the * tile is from the level set's final level, or if the tile achieves the desired resolution on the draw context. * - * @param dc the current draw context. + * @param dc the current draw context. * @param levelSet the level set the tile belongs to. - * @param tile the tile to test. + * @param tile the tile to test. * * @return true if the tile meets the rendering criteria; false otherwise. */ - protected boolean meetsRenderCriteria(DrawContext dc, LevelSet levelSet, Tile tile) - { + protected boolean meetsRenderCriteria(DrawContext dc, LevelSet levelSet, Tile tile) { return levelSet.isFinalLevel(tile.getLevel().getLevelNumber()) || !this.needToSplit(dc, tile); } @@ -1099,13 +1062,12 @@ protected boolean meetsRenderCriteria(DrawContext dc, LevelSet levelSet, Tile ti * compares the distance form the eye point to the tile to determine if the tile meets the desired resolution for * the {@link gov.nasa.worldwind.View} attached to the draw context. * - * @param dc the current draw context. + * @param dc the current draw context. * @param tile the tile to test. * * @return true if the tile must be split; false otherwise. */ - protected boolean needToSplit(DrawContext dc, Tile tile) - { + protected boolean needToSplit(DrawContext dc, Tile tile) { // Compute the height in meters of a texel from the specified tile. Take care to convert from the radians to // meters by multiplying by the globe's radius, not the length of a Cartesian point. Using the length of a // Cartesian point is incorrect when the globe is flat. @@ -1120,8 +1082,9 @@ protected boolean needToSplit(DrawContext dc, Tile tile) // 50% has the same effect on object size as decreasing the distance between the eye and the object by 50%. // The detail hint is reduced for tiles above 75 degrees north and below 75 degrees south. double s = this.getSplitScale(); - if (tile.getSector().getMinLatitude().degrees >= 75 || tile.getSector().getMaxLatitude().degrees <= -75) + if (tile.getSector().getMinLatitude().degrees >= 75 || tile.getSector().getMaxLatitude().degrees <= -75) { s *= 0.85; + } double detailScale = Math.pow(10, -s); double fieldOfViewScale = dc.getView().getFieldOfView().tanHalfAngle() / Angle.fromDegrees(45).tanHalfAngle(); fieldOfViewScale = WWMath.clamp(fieldOfViewScale, 0, 1); @@ -1143,7 +1106,6 @@ protected boolean needToSplit(DrawContext dc, Tile tile) //**************************************************************// //******************** Tile Info *****************************// //**************************************************************// - /** * Creates a key to address the tile information associated with the specified draw context. Each key is unique to * this instance, the tile dimensions that fit in the draw context's viewport, and the globe offset when a 2D globe @@ -1157,8 +1119,7 @@ protected boolean needToSplit(DrawContext dc, Tile tile) * * @return the tile info key for the specified draw context. */ - protected TileInfoKey createTileInfoKey(DrawContext dc) - { + protected TileInfoKey createTileInfoKey(DrawContext dc) { Dimension tileDimension = this.computeTextureTileDimension(dc); return new TileInfoKey(dc, tileDimension.width, tileDimension.height); } @@ -1170,8 +1131,7 @@ protected TileInfoKey createTileInfoKey(DrawContext dc) * * @return the tile info for the specified draw context. */ - protected TileInfo createTileInfo(DrawContext dc) - { + protected TileInfo createTileInfo(DrawContext dc) { // Use a LevelSet shared by all instances of this class to save memory and prevent a conflict in the tile and // texture caches. Use a cache name unique to this tile info instance. Dimension tileDimension = this.computeTextureTileDimension(dc); @@ -1189,22 +1149,22 @@ protected TileInfo createTileInfo(DrawContext dc) * * @return a texture tile dimension appropriate for the specified DrawContext. */ - protected Dimension computeTextureTileDimension(DrawContext dc) - { + protected Dimension computeTextureTileDimension(DrawContext dc) { // Force a square dimension by using the maximum of the tile builder's tileWidth and tileHeight. int maxSize = Math.max(this.tileDimension.width, this.tileDimension.height); // The viewport may be smaller than the desired dimension. For that reason, we constrain the desired tile // dimension by the viewport width and height. Rectangle viewport = dc.getView().getViewport(); - if (maxSize > viewport.width) + if (maxSize > viewport.width) { maxSize = viewport.width; - if (maxSize > viewport.height) + } + if (maxSize > viewport.height) { maxSize = viewport.height; + } // The final dimension used to render all surface tiles will be the power of two which is less than or equal to // the preferred dimension, and which fits into the viewport. - int potSize = WWMath.powerOfTwoFloor(maxSize); return new Dimension(potSize, potSize); } @@ -1214,8 +1174,7 @@ protected Dimension computeTextureTileDimension(DrawContext dc) * * @return a unique cache name. */ - protected String uniqueCacheName() - { + protected String uniqueCacheName() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getName()); sb.append("/"); @@ -1224,36 +1183,35 @@ protected String uniqueCacheName() return sb.toString(); } - protected static class TileInfoKey - { + protected static class TileInfoKey { + public final int globeOffset; public final int tileWidth; public final int tileHeight; - public TileInfoKey(DrawContext dc, int tileWidth, int tileHeight) - { + public TileInfoKey(DrawContext dc, int tileWidth, int tileHeight) { this.globeOffset = (dc.getGlobe() instanceof Globe2D) ? ((Globe2D) dc.getGlobe()).getOffset() : 0; this.tileWidth = tileWidth; this.tileHeight = tileHeight; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } TileInfoKey that = (TileInfoKey) o; return this.globeOffset == that.globeOffset - && this.tileWidth == that.tileWidth - && this.tileHeight == that.tileHeight; + && this.tileWidth == that.tileWidth + && this.tileHeight == that.tileHeight; } @Override - public int hashCode() - { + public int hashCode() { int result = this.globeOffset; result = 31 * result + this.tileWidth; result = 31 * result + this.tileHeight; @@ -1261,8 +1219,8 @@ public int hashCode() } } - protected static class TileInfo - { + protected static class TileInfo { + public ArrayList tiles = new ArrayList(); public ArrayList pickCandidates = new ArrayList(); public LevelSet levelSet; @@ -1270,8 +1228,7 @@ protected static class TileInfo public int tileWidth; public int tileHeight; - public TileInfo(LevelSet levelSet, String cacheName, int tileWidth, int tileHeight) - { + public TileInfo(LevelSet levelSet, String cacheName, int tileWidth, int tileHeight) { this.levelSet = levelSet; this.cacheName = cacheName; this.tileWidth = tileWidth; @@ -1282,21 +1239,19 @@ public TileInfo(LevelSet levelSet, String cacheName, int tileWidth, int tileHeig //**************************************************************// //******************** Surface Object Tile *******************// //**************************************************************// - /** * Returns a new SurfaceObjectTile corresponding to the specified {@code sector}, {@code level}, {@code row}, {@code * column}, and {@code cacheName}. * - * @param sector The tile's Sector. - * @param level The tile's Level in a {@link LevelSet}. - * @param row The tile's row in the Level, starting from 0 and increasing to the right. - * @param column The tile's column in the Level, starting from 0 and increasing upward. + * @param sector The tile's Sector. + * @param level The tile's Level in a {@link LevelSet}. + * @param row The tile's row in the Level, starting from 0 and increasing to the right. + * @param column The tile's column in the Level, starting from 0 and increasing upward. * @param cacheName Tile tile's cache name. * * @return a new SurfaceObjectTile. */ - protected SurfaceObjectTile createTile(Sector sector, Level level, int row, int column, String cacheName) - { + protected SurfaceObjectTile createTile(Sector sector, Level level, int row, int column, String cacheName) { return new SurfaceObjectTile(sector, level, row, column, cacheName); } @@ -1304,15 +1259,14 @@ protected SurfaceObjectTile createTile(Sector sector, Level level, int row, int * Returns a new tile key corresponding to the tile with the specified {@code level}, {@code row}, {@code column}, * and {@code cacheName}. * - * @param level The tile's Level in a {@link LevelSet}. - * @param row The tile's row in the Level, starting from 0 and increasing to the right. - * @param column The tile's column in the Level, starting from 0 and increasing upward. + * @param level The tile's Level in a {@link LevelSet}. + * @param row The tile's row in the Level, starting from 0 and increasing to the right. + * @param column The tile's column in the Level, starting from 0 and increasing upward. * @param cacheName Tile tile's cache name. * * @return a tile key. */ - protected Object createTileKey(Level level, int row, int column, String cacheName) - { + protected Object createTileKey(Level level, int row, int column, String cacheName) { return new TileKey(level.getLevelNumber(), row, column, cacheName); } @@ -1320,33 +1274,37 @@ protected Object createTileKey(Level level, int row, int column, String cacheNam * Represents a {@link gov.nasa.worldwind.layers.TextureTile} who's contents is constructed by a set of surface * objects. The tile maintains a collection of surface renderables that intersect the tile, and provides methods for * to modify and retrieve that collection. Additionally, the method {@link #getStateKey(DrawContext)} provides a - * mechanism to uniquely identify the tile's current state, including the state of each intersecting surface - * object. + * mechanism to uniquely identify the tile's current state, including the state of each intersecting surface object. */ - protected static class SurfaceObjectTile extends TextureTile - { - /** The sector that bounds the surface renderables intersecting the tile. */ + protected static class SurfaceObjectTile extends TextureTile { + + /** + * The sector that bounds the surface renderables intersecting the tile. + */ protected Sector objectSector; - /** List of surface renderables intersecting the tile. */ + /** + * List of surface renderables intersecting the tile. + */ protected List intersectingObjects; - /** The state key that was valid when the tile was last updated. */ + /** + * The state key that was valid when the tile was last updated. + */ protected Object lastUpdateStateKey; /** * Constructs a tile for a given sector, level, row and column of the tile's containing tile set. * - * @param sector The sector corresponding with the tile. - * @param level The tile's level within a containing level set. - * @param row The row index (0 origin) of the tile within the indicated level. - * @param column The column index (0 origin) of the tile within the indicated level. + * @param sector The sector corresponding with the tile. + * @param level The tile's level within a containing level set. + * @param row The row index (0 origin) of the tile within the indicated level. + * @param column The column index (0 origin) of the tile within the indicated level. * @param cacheName The tile's cache name. Overrides the Level's cache name to associates the tile with it's - * tile builder in a global cache. + * tile builder in a global cache. * * @throws IllegalArgumentException if any of the {@code sector}, {@code level}, or {@code cacheName } are - * {@code null}. + * {@code null}. */ - public SurfaceObjectTile(Sector sector, Level level, int row, int column, String cacheName) - { + public SurfaceObjectTile(Sector sector, Level level, int row, int column, String cacheName) { super(sector, level, row, column, cacheName); } @@ -1357,15 +1315,14 @@ public SurfaceObjectTile(Sector sector, Level level, int row, int column, String * @return The tile's size in bytes. */ @Override - public long getSizeInBytes() - { + public long getSizeInBytes() { long size = super.getSizeInBytes(); - if (this.lastUpdateStateKey instanceof Cacheable) + if (this.lastUpdateStateKey instanceof Cacheable) { size += ((Cacheable) this.lastUpdateStateKey).getSizeInBytes(); - else if (this.lastUpdateStateKey != null) + } else if (this.lastUpdateStateKey != null) { size += 4; // If the object doesn't implement Cacheable, just account for the reference to it. - + } return size; } @@ -1377,8 +1334,7 @@ else if (this.lastUpdateStateKey != null) * * @return an object representing surface renderable's current state. */ - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { return new SurfaceObjectTileStateKey(dc, this); } @@ -1388,8 +1344,7 @@ public Object getStateKey(DrawContext dc) * * @return a sector bounding the tile's intersecting objects. */ - public Sector getObjectSector() - { + public Sector getObjectSector() { return this.objectSector; } @@ -1399,8 +1354,7 @@ public Sector getObjectSector() * @return {@code true} if the list of surface renderables intersecting this tile has elements, and {@code * false} otherwise. */ - public boolean hasObjects() - { + public boolean hasObjects() { return this.intersectingObjects != null && !this.intersectingObjects.isEmpty(); } @@ -1409,8 +1363,7 @@ public boolean hasObjects() * * @return a tile's intersecting objects. */ - public List getObjectList() - { + public List getObjectList() { return this.intersectingObjects; } @@ -1418,8 +1371,7 @@ public List getObjectList() * Clears the tile's list of intersecting objects. {@link #getObjectSector()} returns null after calling this * method. */ - public void clearObjectList() - { + public void clearObjectList() { this.intersectingObjects = null; this.objectSector = null; } @@ -1427,13 +1379,13 @@ public void clearObjectList() /** * Adds the specified surface renderable to the tile's list of intersecting objects. * - * @param so the surface renderable to add. + * @param so the surface renderable to add. * @param sector the sector bounding the specified surface renderable. */ - public void addSurfaceObject(SurfaceRenderable so, Sector sector) - { - if (this.intersectingObjects == null) + public void addSurfaceObject(SurfaceRenderable so, Sector sector) { + if (this.intersectingObjects == null) { this.intersectingObjects = new ArrayList(); + } this.intersectingObjects.add(so); this.objectSector = (this.objectSector != null) ? this.objectSector.union(sector) : sector; @@ -1442,13 +1394,13 @@ public void addSurfaceObject(SurfaceRenderable so, Sector sector) /** * Adds the specified collection of surface renderables to the tile's list of intersecting objects. * - * @param c the collection of surface renderables to add. + * @param c the collection of surface renderables to add. * @param sector the sector bounding the specified surface renderable collection. */ - public void addAllSurfaceObjects(List c, Sector sector) - { - if (this.intersectingObjects == null) + public void addAllSurfaceObjects(List c, Sector sector) { + if (this.intersectingObjects == null) { this.intersectingObjects = new ArrayList(); + } this.intersectingObjects.addAll(c); this.objectSector = (this.objectSector != null) ? this.objectSector.union(sector) : sector; @@ -1461,8 +1413,7 @@ public void addAllSurfaceObjects(List c, Sector sector) * tile. */ @Override - protected TextureTile createSubTile(Sector sector, Level level, int row, int col) - { + protected TextureTile createSubTile(Sector sector, Level level, int row, int col) { return new SurfaceObjectTile(sector, level, row, col, this.getCacheName()); } @@ -1472,8 +1423,7 @@ protected TextureTile createSubTile(Sector sector, Level level, int row, int col * Overridden to return a TileKey with the same cache name as this tile. */ @Override - protected TileKey createSubTileKey(Level level, int row, int col) - { + protected TileKey createSubTileKey(Level level, int row, int col) { return new TileKey(level.getLevelNumber(), row, col, this.getCacheName()); } } @@ -1484,56 +1434,51 @@ protected TileKey createSubTileKey(Level level, int row, int col) * to the surface renderables themselves. Should the tile state key live longer than the surface renderables, the * state key does not prevent those objects from being reclaimed by the garbage collector. */ - protected static class SurfaceObjectTileStateKey implements Cacheable - { + protected static class SurfaceObjectTileStateKey implements Cacheable { + protected final TileKey tileKey; protected final Object[] intersectingObjectKeys; /** * Construsts a tile state key for the specified surface renderable tile. * - * @param dc the draw context the state key is related to. + * @param dc the draw context the state key is related to. * @param tile the tile to construct a state key for. */ - public SurfaceObjectTileStateKey(DrawContext dc, SurfaceObjectTile tile) - { - if (tile != null && tile.hasObjects()) - { + public SurfaceObjectTileStateKey(DrawContext dc, SurfaceObjectTile tile) { + if (tile != null && tile.hasObjects()) { this.tileKey = tile.getTileKey(); this.intersectingObjectKeys = new Object[tile.getObjectList().size()]; int index = 0; - for (SurfaceRenderable so : tile.getObjectList()) - { + for (SurfaceRenderable so : tile.getObjectList()) { this.intersectingObjectKeys[index++] = so.getStateKey(dc); } - } - else - { + } else { this.tileKey = null; this.intersectingObjectKeys = null; } } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } // Compare the tile keys and each state key in the array. The state keys are equal if the tile keys are // equal, the arrays equivalent length, and each array element is equivalent. Arrays.equals() correctly // handles null references. SurfaceObjectTileStateKey that = (SurfaceObjectTileStateKey) o; return (this.tileKey != null ? this.tileKey.equals(that.tileKey) : that.tileKey == null) - && Arrays.equals(this.intersectingObjectKeys, that.intersectingObjectKeys); + && Arrays.equals(this.intersectingObjectKeys, that.intersectingObjectKeys); } @Override - public int hashCode() - { + public int hashCode() { int result = this.tileKey != null ? this.tileKey.hashCode() : 0; result = 31 * result + Arrays.hashCode(this.intersectingObjectKeys); // Correctly handles a null reference. return result; @@ -1546,19 +1491,19 @@ public int hashCode() * * @return The state key's size in bytes. */ - public long getSizeInBytes() - { - if (this.intersectingObjectKeys == null) + public long getSizeInBytes() { + if (this.intersectingObjectKeys == null) { return 0; + } long size = 4 * this.intersectingObjectKeys.length; // For the array references. - for (Object o : this.intersectingObjectKeys) - { - if (o instanceof Cacheable) + for (Object o : this.intersectingObjectKeys) { + if (o instanceof Cacheable) { size += ((Cacheable) o).getSizeInBytes(); - else if (o != null) + } else if (o != null) { size += 4; // If the object doesn't implement Cacheable, just account for the reference to it. + } } return size; diff --git a/src/gov/nasa/worldwind/render/SurfacePolygon.java b/src/gov/nasa/worldwind/render/SurfacePolygon.java index 6e5d73a2c3..dce1d9dd7e 100644 --- a/src/gov/nasa/worldwind/render/SurfacePolygon.java +++ b/src/gov/nasa/worldwind/render/SurfacePolygon.java @@ -28,10 +28,10 @@ * @version $Id: SurfacePolygon.java 3436 2015-10-28 17:43:24Z tgaskins $ */ @SuppressWarnings("unchecked") -public class SurfacePolygon extends AbstractSurfaceShape implements Exportable -{ - protected static class ShapeData - { +public class SurfacePolygon extends AbstractSurfaceShape implements Exportable { + + protected static class ShapeData { + public int vertexStride; public boolean hasTexCoords; public FloatBuffer vertices; @@ -39,19 +39,17 @@ protected static class ShapeData public IntBuffer outlineIndices; } - protected static class Vertex extends LatLon - { + protected static class Vertex extends LatLon { + public double u; public double v; public boolean edgeFlag = true; - public Vertex(LatLon location) - { + public Vertex(LatLon location) { super(location); } - public Vertex(Angle latitude, Angle longitude, double u, double v) - { + public Vertex(Angle latitude, Angle longitude, double u, double v) { super(latitude, longitude); this.u = u; this.v = v; @@ -60,18 +58,23 @@ public Vertex(Angle latitude, Angle longitude, double u, double v) /* The polygon's boundaries. */ protected List> boundaries = new ArrayList>(); - /** If an image source was specified, this is the WWTexture form. */ + /** + * If an image source was specified, this is the WWTexture form. + */ protected WWTexture explicitTexture; - /** This shape's texture coordinates. */ + /** + * This shape's texture coordinates. + */ protected float[] explicitTextureCoords; protected Map shapeDataCache = new HashMap(); protected static GLUtessellator tess; protected static GLUTessellatorSupport.CollectPrimitivesCallback tessCallback; - /** Constructs a new surface polygon with the default attributes and no locations. */ - public SurfacePolygon() - { + /** + * Constructs a new surface polygon with the default attributes and no locations. + */ + public SurfacePolygon() { } /** @@ -79,8 +82,7 @@ public SurfacePolygon() * * @param source the shape to copy. */ - public SurfacePolygon(SurfacePolygon source) - { + public SurfacePolygon(SurfacePolygon source) { super(source); this.boundaries.addAll(source.boundaries); @@ -93,8 +95,7 @@ public SurfacePolygon(SurfacePolygon source) * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public SurfacePolygon(ShapeAttributes normalAttrs) - { + public SurfacePolygon(ShapeAttributes normalAttrs) { super(normalAttrs); } @@ -107,10 +108,8 @@ public SurfacePolygon(ShapeAttributes normalAttrs) * * @throws IllegalArgumentException if the locations iterable is null. */ - public SurfacePolygon(Iterable iterable) - { - if (iterable == null) - { + public SurfacePolygon(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -127,16 +126,14 @@ public SurfacePolygon(Iterable iterable) * Note: If fewer than three locations is specified, no polygon is drawn. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param iterable the polygon locations. + * @param iterable the polygon locations. * * @throws IllegalArgumentException if the locations iterable is null. */ - public SurfacePolygon(ShapeAttributes normalAttrs, Iterable iterable) - { + public SurfacePolygon(ShapeAttributes normalAttrs, Iterable iterable) { super(normalAttrs); - if (iterable == null) - { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -145,25 +142,20 @@ public SurfacePolygon(ShapeAttributes normalAttrs, Iterable it this.setOuterBoundary(iterable); } - public Iterable getLocations(Globe globe) - { + public Iterable getLocations(Globe globe) { return this.getOuterBoundary(); } - public Iterable getLocations() - { + public Iterable getLocations() { return this.getOuterBoundary(); } - public List> getBoundaries() - { + public List> getBoundaries() { return this.boundaries; } - public void setLocations(Iterable iterable) - { - if (iterable == null) - { + public void setLocations(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,32 +164,28 @@ public void setLocations(Iterable iterable) this.setOuterBoundary(iterable); } - public Iterable getOuterBoundary() - { + public Iterable getOuterBoundary() { return this.boundaries.size() > 0 ? this.boundaries.get(0) : null; } - public void setOuterBoundary(Iterable iterable) - { - if (iterable == null) - { + public void setOuterBoundary(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.boundaries.size() > 0) + if (this.boundaries.size() > 0) { this.boundaries.set(0, iterable); - else + } else { this.boundaries.add(iterable); + } this.onShapeChanged(); } - public void addInnerBoundary(Iterable iterable) - { - if (iterable == null) - { + public void addInnerBoundary(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -212,8 +200,7 @@ public void addInnerBoundary(Iterable iterable) * * @return the texture image source, or null if no source has been specified. */ - public Object getTextureImageSource() - { + public Object getTextureImageSource() { return this.explicitTexture != null ? this.explicitTexture.getImageSource() : null; } @@ -222,43 +209,37 @@ public Object getTextureImageSource() * * @return the texture coordinates, or null if no texture coordinates have been specified. */ - public float[] getTextureCoords() - { + public float[] getTextureCoords() { return this.explicitTextureCoords; } /** * Specifies the texture to apply to this polygon. * - * @param imageSource the texture image source. May be a {@link String} identifying a file path or URL, a {@link + * @param imageSource the texture image source. May be a {@link String} identifying a file path or URL, a {@link * File}, or a {@link java.net.URL}. - * @param texCoords the (s, t) texture coordinates aligning the image to the polygon. There must be one texture - * coordinate pair, (s, t), for each polygon location in the polygon's outer boundary. + * @param texCoords the (s, t) texture coordinates aligning the image to the polygon. There must be one texture + * coordinate pair, (s, t), for each polygon location in the polygon's outer boundary. * @param texCoordCount the number of texture coordinates, (s, v) pairs, specified. * * @throws IllegalArgumentException if the image source is not null and either the texture coordinates are null or - * inconsistent with the specified texture-coordinate count, or there are fewer - * than three texture coordinate pairs. + * inconsistent with the specified texture-coordinate count, or there are fewer than three texture coordinate pairs. */ - public void setTextureImageSource(Object imageSource, float[] texCoords, int texCoordCount) - { - if (imageSource == null) - { + public void setTextureImageSource(Object imageSource, float[] texCoords, int texCoordCount) { + if (imageSource == null) { this.explicitTexture = null; this.explicitTextureCoords = null; this.onShapeChanged(); return; } - if (texCoords == null) - { + if (texCoords == null) { String message = Logging.getMessage("generic.ListIsEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoordCount < 3 || texCoords.length < 2 * texCoordCount) - { + if (texCoordCount < 3 || texCoords.length < 2 * texCoordCount) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -269,40 +250,38 @@ public void setTextureImageSource(Object imageSource, float[] texCoords, int tex this.onShapeChanged(); } - public Position getReferencePosition() - { - if (this.getOuterBoundary() == null) + public Position getReferencePosition() { + if (this.getOuterBoundary() == null) { return null; + } Iterator iterator = this.getOuterBoundary().iterator(); - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return null; + } return new Position(iterator.next(), 0); } - protected void clearCaches() - { + protected void clearCaches() { super.clearCaches(); this.shapeDataCache.clear(); } - protected void doDrawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) - { - if (this.boundaries.isEmpty()) + protected void doDrawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) { + if (this.boundaries.isEmpty()) { return; + } Object key = this.createGeometryKey(dc, sdc); ShapeData shapeData = this.shapeDataCache.get(key); - if (shapeData == null) - { + if (shapeData == null) { Angle degreesPerInterval = Angle.fromDegrees(1.0 / this.computeEdgeIntervalsPerDegree(sdc)); List> contours = this.assembleContours(degreesPerInterval); shapeData = this.tessellateContours(contours); - if (shapeData == null) - { + if (shapeData == null) { String msg = Logging.getMessage("generic.ExceptionWhileTessellating", this); dc.addRenderingException(new WWRuntimeException(msg)); this.handleUnsuccessfulInteriorTessellation(dc); // clears boundaries, preventing repeat attempts @@ -315,76 +294,63 @@ protected void doDrawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glVertexPointer(2, GL.GL_FLOAT, shapeData.vertexStride, shapeData.vertices.position(0)); - if (shapeData.hasTexCoords) - { + if (shapeData.hasTexCoords) { gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL.GL_FLOAT, shapeData.vertexStride, shapeData.vertices.position(2)); } ShapeAttributes attrs = this.getActiveAttributes(); - if (attrs.isDrawInterior()) - { + if (attrs.isDrawInterior()) { this.applyInteriorState(dc, sdc, attrs, this.getInteriorTexture(), this.getReferencePosition()); IntBuffer indices = shapeData.interiorIndices; gl.glDrawElements(GL.GL_TRIANGLES, indices.remaining(), GL.GL_UNSIGNED_INT, indices); } - if (attrs.isDrawOutline()) - { + if (attrs.isDrawOutline()) { this.applyOutlineState(dc, attrs); IntBuffer indices = shapeData.outlineIndices; gl.glDrawElements(GL.GL_LINES, indices.remaining(), GL.GL_UNSIGNED_INT, indices); } - if (shapeData.hasTexCoords) - { + if (shapeData.hasTexCoords) { gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY); } } protected void applyInteriorState(DrawContext dc, SurfaceTileDrawContext sdc, ShapeAttributes attributes, - WWTexture texture, LatLon refLocation) - { - if (this.explicitTexture != null && !dc.isPickingMode()) - { + WWTexture texture, LatLon refLocation) { + if (this.explicitTexture != null && !dc.isPickingMode()) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLUtil.applyBlending(gl, true); OGLUtil.applyColor(gl, attributes.getInteriorMaterial().getDiffuse(), attributes.getInteriorOpacity(), - true); + true); - if (this.explicitTexture.bind(dc)) - { + if (this.explicitTexture.bind(dc)) { this.explicitTexture.applyInternalTransform(dc); gl.glEnable(GL.GL_TEXTURE_2D); gl.glDisable(GL2.GL_TEXTURE_GEN_S); gl.glDisable(GL2.GL_TEXTURE_GEN_T); } - } - else - { + } else { super.applyInteriorState(dc, sdc, attributes, this.getInteriorTexture(), this.getReferencePosition()); } } - protected List> assembleContours(Angle maxEdgeLength) - { + protected List> assembleContours(Angle maxEdgeLength) { List> result = new ArrayList>(); - for (int b = 0; b < this.boundaries.size(); b++) - { + for (int b = 0; b < this.boundaries.size(); b++) { Iterable locations = this.boundaries.get(b); float[] texCoords = (b == 0) ? this.explicitTextureCoords : null; int c = 0; // Merge the boundary locations with their respective texture coordinates, if any. List contour = new ArrayList(); - for (LatLon location : locations) - { + for (LatLon location : locations) { Vertex vertex = new Vertex(location); contour.add(vertex); - if (texCoords != null && texCoords.length > c) - { + if (texCoords != null && texCoords.length > c) { vertex.u = texCoords[c++]; vertex.v = texCoords[c++]; } @@ -396,16 +362,11 @@ protected List> assembleContours(Angle maxEdgeLength) // Modify the contour vertices to compensate for the spherical nature of geographic coordinates. String pole = LatLon.locationsContainPole(contour); - if (pole != null) - { + if (pole != null) { result.add(this.clipWithPole(contour, pole, maxEdgeLength)); - } - else if (LatLon.locationsCrossDateLine(contour)) - { + } else if (LatLon.locationsCrossDateLine(contour)) { result.addAll(this.clipWithDateline(contour)); - } - else - { + } else { result.add(contour); } } @@ -413,22 +374,18 @@ else if (LatLon.locationsCrossDateLine(contour)) return result; } - protected void closeContour(List contour) - { - if (!contour.get(0).equals(contour.get(contour.size() - 1))) - { + protected void closeContour(List contour) { + if (!contour.get(0).equals(contour.get(contour.size() - 1))) { contour.add(contour.get(0)); } } - protected void subdivideContour(List contour, Angle maxEdgeLength) - { + protected void subdivideContour(List contour, Angle maxEdgeLength) { List original = new ArrayList(contour.size()); original.addAll(contour); contour.clear(); - for (int i = 0; i < original.size() - 1; i++) - { + for (int i = 0; i < original.size() - 1; i++) { Vertex begin = original.get(i); Vertex end = original.get(i + 1); contour.add(begin); @@ -439,40 +396,32 @@ protected void subdivideContour(List contour, Angle maxEdgeLength) contour.add(last); } - protected void subdivideEdge(Vertex begin, Vertex end, Angle maxEdgeLength, List result) - { + protected void subdivideEdge(Vertex begin, Vertex end, Angle maxEdgeLength, List result) { Vertex center = new Vertex(LatLon.interpolate(this.pathType, 0.5, begin, end)); center.u = 0.5 * (begin.u + end.u); center.v = 0.5 * (begin.v + end.v); center.edgeFlag = begin.edgeFlag || end.edgeFlag; Angle edgeLength = LatLon.linearDistance(begin, end); - if (edgeLength.compareTo(maxEdgeLength) > 0) - { + if (edgeLength.compareTo(maxEdgeLength) > 0) { this.subdivideEdge(begin, center, maxEdgeLength, result); result.add(center); this.subdivideEdge(center, end, maxEdgeLength, result); - } - else - { + } else { result.add(center); } } - protected List clipWithPole(List contour, String pole, Angle maxEdgeLength) - { + protected List clipWithPole(List contour, String pole, Angle maxEdgeLength) { List newVertices = new ArrayList(); Angle poleLat = AVKey.NORTH.equals(pole) ? Angle.POS90 : Angle.NEG90; Vertex vertex = null; - for (Vertex nextVertex : contour) - { - if (vertex != null) - { + for (Vertex nextVertex : contour) { + if (vertex != null) { newVertices.add(vertex); - if (LatLon.locationsCrossDateline(vertex, nextVertex)) - { + if (LatLon.locationsCrossDateline(vertex, nextVertex)) { // Determine where the segment crosses the dateline. LatLon separation = LatLon.intersectionWithMeridian(vertex, nextVertex, Angle.POS180); double sign = Math.signum(vertex.getLongitude().degrees); @@ -521,12 +470,10 @@ protected List clipWithPole(List contour, String pole, Angle max return newVertices; } - protected double[] uvWeightedAverage(List contour, Vertex vertex) - { + protected double[] uvWeightedAverage(List contour, Vertex vertex) { double[] weight = new double[contour.size()]; double sumOfWeights = 0; - for (int i = 0; i < contour.size(); i++) - { + for (int i = 0; i < contour.size(); i++) { double distance = LatLon.greatCircleDistance(contour.get(i), vertex).degrees; weight[i] = 1 / distance; sumOfWeights += weight[i]; @@ -534,38 +481,32 @@ protected double[] uvWeightedAverage(List contour, Vertex vertex) double u = 0; double v = 0; - for (int i = 0; i < contour.size(); i++) - { + for (int i = 0; i < contour.size(); i++) { double factor = weight[i] / sumOfWeights; u += contour.get(i).u * factor; v += contour.get(i).v * factor; } - return new double[] {u, v}; + return new double[]{u, v}; } - protected List> clipWithDateline(List contour) - { + protected List> clipWithDateline(List contour) { List result = new ArrayList(); Vertex prev = null; Angle offset = null; boolean applyOffset = false; - for (Vertex cur : contour) - { - if (prev != null && LatLon.locationsCrossDateline(prev, cur)) - { - if (offset == null) + for (Vertex cur : contour) { + if (prev != null && LatLon.locationsCrossDateline(prev, cur)) { + if (offset == null) { offset = (prev.longitude.degrees < 0 ? Angle.NEG360 : Angle.POS360); + } applyOffset = !applyOffset; } - if (applyOffset) - { + if (applyOffset) { result.add(new Vertex(cur.latitude, cur.longitude.add(offset), cur.u, cur.v)); - } - else - { + } else { result.add(cur); } @@ -573,29 +514,24 @@ protected List> clipWithDateline(List contour) } List mirror = new ArrayList(); - for (Vertex cur : result) - { + for (Vertex cur : result) { mirror.add(new Vertex(cur.latitude, cur.longitude.subtract(offset), cur.u, cur.v)); } return Arrays.asList(result, mirror); } - protected ShapeData tessellateContours(List> contours) - { + protected ShapeData tessellateContours(List> contours) { List polygonData = new ArrayList(); double[] coords = {0, 0, 0}; - if (tess == null) - { + if (tess == null) { tess = GLU.gluNewTess(); tessCallback = new GLUTessellatorSupport.CollectPrimitivesCallback(); tessCallback.attach(tess); - GLU.gluTessCallback(tess, GLU.GLU_TESS_COMBINE_DATA, new GLUtessellatorCallbackAdapter() - { + GLU.gluTessCallback(tess, GLU.GLU_TESS_COMBINE_DATA, new GLUtessellatorCallbackAdapter() { @Override - public void combineData(double[] coords, Object[] vertexData, float[] weight, Object[] outData, Object polygonData) - { + public void combineData(double[] coords, Object[] vertexData, float[] weight, Object[] outData, Object polygonData) { List vertexList = (List) polygonData; Vertex vertex = new Vertex(LatLon.fromDegrees(coords[1], coords[0])); vertex.edgeFlag = false; // set to true if any of the combined vertices have the edge flag @@ -618,18 +554,15 @@ public void combineData(double[] coords, Object[] vertexData, float[] weight, Ob }); } - try - { + try { tessCallback.reset(); GLU.gluTessNormal(tess, 0, 0, 1); GLU.gluTessBeginPolygon(tess, polygonData); - for (List contour : contours) - { + for (List contour : contours) { GLU.gluTessBeginContour(tess); - for (Vertex vertex : contour) - { + for (Vertex vertex : contour) { coords[0] = vertex.longitude.degrees; coords[1] = vertex.latitude.degrees; int index = polygonData.size(); @@ -642,18 +575,15 @@ public void combineData(double[] coords, Object[] vertexData, float[] weight, Ob } GLU.gluTessEndPolygon(tess); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhileTessellating", e.getMessage()); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); return null; } - if (tessCallback.getError() != 0) - { + if (tessCallback.getError() != 0) { String msg = Logging.getMessage("generic.ExceptionWhileTessellating", - GLUTessellatorSupport.convertGLUTessErrorToString(tessCallback.getError())); + GLUTessellatorSupport.convertGLUTessErrorToString(tessCallback.getError())); Logging.logger().log(java.util.logging.Level.SEVERE, msg); return null; } @@ -664,13 +594,11 @@ public void combineData(double[] coords, Object[] vertexData, float[] weight, Ob shapeData.vertices = Buffers.newDirectFloatBuffer(polygonData.size() * (shapeData.hasTexCoords ? 4 : 2)); double lonOffset = this.getReferencePosition().longitude.degrees; double latOffset = this.getReferencePosition().latitude.degrees; - for (Vertex vertex : polygonData) - { + for (Vertex vertex : polygonData) { shapeData.vertices.put((float) (vertex.longitude.degrees - lonOffset)); shapeData.vertices.put((float) (vertex.latitude.degrees - latOffset)); - if (shapeData.hasTexCoords) - { + if (shapeData.hasTexCoords) { shapeData.vertices.put((float) vertex.u); shapeData.vertices.put((float) vertex.v); } @@ -690,15 +618,14 @@ public void combineData(double[] coords, Object[] vertexData, float[] weight, Ob return shapeData; } - protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) - { - if (this.boundaries.isEmpty()) + protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) { + if (this.boundaries.isEmpty()) { return null; + } ArrayList> geom = new ArrayList>(); - for (Iterable boundary : this.boundaries) - { + for (Iterable boundary : this.boundaries) { ArrayList drawLocations = new ArrayList(); this.generateIntermediateLocations(boundary, edgeIntervalsPerDegree, true, drawLocations); @@ -707,29 +634,29 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer // these contours is configured to recognize interior holes when all contours have counter clockwise winding // order. //noinspection StringEquality - if (WWMath.computeWindingOrderOfLocations(drawLocations) != AVKey.COUNTER_CLOCKWISE) + if (WWMath.computeWindingOrderOfLocations(drawLocations) != AVKey.COUNTER_CLOCKWISE) { Collections.reverse(drawLocations); + } geom.add(drawLocations); } - if (geom.isEmpty() || geom.get(0).size() < 3) + if (geom.isEmpty() || geom.get(0).size() < 3) { return null; + } return geom; } - protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) - { - if (this.boundaries.isEmpty()) + protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) { + if (this.boundaries.isEmpty()) { return; + } - for (int i = 0; i < this.boundaries.size(); i++) - { + for (int i = 0; i < this.boundaries.size(); i++) { ArrayList newLocations = new ArrayList(); - for (LatLon ll : this.boundaries.get(i)) - { + for (LatLon ll : this.boundaries.get(i)) { Angle heading = LatLon.greatCircleAzimuth(oldReferencePosition, ll); Angle pathLength = LatLon.greatCircleDistance(oldReferencePosition, ll); newLocations.add(LatLon.greatCircleEndPosition(newReferencePosition, heading, pathLength)); @@ -742,15 +669,14 @@ protected void doMoveTo(Position oldReferencePosition, Position newReferencePosi this.onShapeChanged(); } - protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) - { - if (this.boundaries.isEmpty()) + protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) { + if (this.boundaries.isEmpty()) { return; + } - for (int i = 0; i < this.boundaries.size(); i++) - { + for (int i = 0; i < this.boundaries.size(); i++) { List newLocations = LatLon.computeShiftedLocations(globe, oldReferencePosition, - newReferencePosition, this.boundaries.get(i)); + newReferencePosition, this.boundaries.get(i)); this.boundaries.set(i, newLocations); } @@ -762,7 +688,6 @@ protected void doMoveTo(Globe globe, Position oldReferencePosition, Position new //**************************************************************// //******************** Interior Tessellation *****************// //**************************************************************// - /** * Overridden to clear the polygon's locations iterable upon an unsuccessful tessellation attempt. This ensures the * polygon won't attempt to re-tessellate itself each frame. @@ -770,8 +695,7 @@ protected void doMoveTo(Globe globe, Position oldReferencePosition, Position new * @param dc the current DrawContext. */ @Override - protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) - { + protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) { super.handleUnsuccessfulInteriorTessellation(dc); // If tessellating the polygon's interior was unsuccessful, we modify the polygon's to avoid any additional @@ -784,41 +708,35 @@ protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); - if (!this.boundaries.isEmpty()) - { + if (!this.boundaries.isEmpty()) { RestorableSupport.StateObject so = rs.addStateObject(context, "boundaries"); - for (Iterable boundary : this.boundaries) - { + for (Iterable boundary : this.boundaries) { rs.addStateValueAsLatLonList(so, "boundary", boundary); } } } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); RestorableSupport.StateObject so = rs.getStateObject(context, "boundaries"); - if (so != null) - { + if (so != null) { this.boundaries.clear(); RestorableSupport.StateObject[] sos = rs.getAllStateObjects(so, "boundary"); - if (sos != null) - { - for (RestorableSupport.StateObject boundary : sos) - { - if (boundary == null) + if (sos != null) { + for (RestorableSupport.StateObject boundary : sos) { + if (boundary == null) { continue; + } Iterable locations = rs.getStateObjectAsLatLonList(boundary); - if (locations != null) + if (locations != null) { this.boundaries.add(locations); + } } } @@ -827,17 +745,18 @@ protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObjec } } - protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.legacyRestoreState(rs, context); Iterable locations = rs.getStateValueAsLatLonList(context, "locationList"); - if (locations == null) + if (locations == null) { locations = rs.getStateValueAsLatLonList(context, "locations"); + } - if (locations != null) + if (locations != null) { this.setOuterBoundary(locations); + } } /** @@ -847,31 +766,24 @@ protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateO * @param output Object to receive the generated KML. * * @throws XMLStreamException If an exception occurs while writing the KML - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -880,8 +792,7 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("Placemark"); String property = getStringValue(AVKey.DISPLAY_NAME); - if (property != null) - { + if (property != null) { xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(property); xmlWriter.writeEndElement(); @@ -892,16 +803,14 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); String shortDescription = (String) getValue(AVKey.SHORT_DESCRIPTION); - if (shortDescription != null) - { + if (shortDescription != null) { xmlWriter.writeStartElement("Snippet"); xmlWriter.writeCharacters(shortDescription); xmlWriter.writeEndElement(); } String description = (String) getValue(AVKey.BALLOON_TEXT); - if (description != null) - { + if (description != null) { xmlWriter.writeStartElement("description"); xmlWriter.writeCharacters(description); xmlWriter.writeEndElement(); @@ -912,8 +821,7 @@ else if (output instanceof OutputStream) final ShapeAttributes highlightAttributes = getHighlightAttributes(); // Write style map - if (normalAttributes != null || highlightAttributes != null) - { + if (normalAttributes != null || highlightAttributes != null) { xmlWriter.writeStartElement("StyleMap"); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.NORMAL, normalAttributes); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.HIGHLIGHT, highlightAttributes); @@ -933,8 +841,7 @@ else if (output instanceof OutputStream) // Outer boundary Iterable outerBoundary = this.getOuterBoundary(); - if (outerBoundary != null) - { + if (outerBoundary != null) { xmlWriter.writeStartElement("outerBoundaryIs"); KMLExportUtil.exportBoundaryAsLinearRing(xmlWriter, outerBoundary, null); xmlWriter.writeEndElement(); // outerBoundaryIs @@ -942,11 +849,10 @@ else if (output instanceof OutputStream) // Inner boundaries Iterator> boundaryIterator = boundaries.iterator(); - if (boundaryIterator.hasNext()) + if (boundaryIterator.hasNext()) { boundaryIterator.next(); // Skip outer boundary, we already dealt with it above - - while (boundaryIterator.hasNext()) - { + } + while (boundaryIterator.hasNext()) { Iterable boundary = boundaryIterator.next(); xmlWriter.writeStartElement("innerBoundaryIs"); @@ -958,7 +864,8 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); // Placemark xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } } diff --git a/src/gov/nasa/worldwind/render/SurfacePolygons.java b/src/gov/nasa/worldwind/render/SurfacePolygons.java index 85d26ef4eb..614014c761 100644 --- a/src/gov/nasa/worldwind/render/SurfacePolygons.java +++ b/src/gov/nasa/worldwind/render/SurfacePolygons.java @@ -29,19 +29,18 @@ */ public class SurfacePolygons extends SurfacePolylines // TODO: Review { + protected int[] polygonRingGroups; protected String windingRule = AVKey.CLOCKWISE; protected boolean needsInteriorTessellation = true; protected WWTexture texture; protected Object interiorDisplayListCacheKey = new Object(); - public SurfacePolygons(CompoundVecBuffer buffer) - { + public SurfacePolygons(CompoundVecBuffer buffer) { super(buffer); } - public SurfacePolygons(Sector sector, CompoundVecBuffer buffer) - { + public SurfacePolygons(Sector sector, CompoundVecBuffer buffer) { super(sector, buffer); } @@ -57,8 +56,7 @@ public SurfacePolygons(Sector sector, CompoundVecBuffer buffer) * * @return a copy of the polygon ring groups array - can be null. */ - public int[] getPolygonRingGroups() - { + public int[] getPolygonRingGroups() { return this.polygonRingGroups.clone(); } @@ -74,8 +72,7 @@ public int[] getPolygonRingGroups() * * @param ringGroups a copy of the polygon ring groups array - can be null. */ - public void setPolygonRingGroups(int[] ringGroups) - { + public void setPolygonRingGroups(int[] ringGroups) { this.polygonRingGroups = ringGroups.clone(); this.onGeometryChanged(); } @@ -90,8 +87,7 @@ public void setPolygonRingGroups(int[] ringGroups) * * @return the winding rule used when tessellating polygons. */ - public String getWindingRule() - { + public String getWindingRule() { return this.windingRule; } @@ -105,67 +101,65 @@ public String getWindingRule() * * @param windingRule the winding rule to use when tessellating polygons. */ - public void setWindingRule(String windingRule) - { + public void setWindingRule(String windingRule) { this.windingRule = windingRule; this.onGeometryChanged(); } - protected void onGeometryChanged() - { + protected void onGeometryChanged() { this.needsInteriorTessellation = true; super.onGeometryChanged(); } - protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) { // Exit immediately if the polygon has no coordinate data. - if (this.buffer.size() == 0) + if (this.buffer.size() == 0) { return; + } Position referencePos = this.getReferencePosition(); - if (referencePos == null) + if (referencePos == null) { return; + } // Attempt to tessellate the polygon's interior if the polygon's interior display list is uninitialized, or if // the polygon is marked as needing tessellation. int[] dlResource = (int[]) dc.getGpuResourceCache().get(this.interiorDisplayListCacheKey); - if (dlResource == null || this.needsInteriorTessellation) + if (dlResource == null || this.needsInteriorTessellation) { dlResource = this.tessellateInterior(dc, referencePos); + } // Exit immediately if the polygon's interior failed to tessellate. The cause has already been logged by // tessellateInterior(). - if (dlResource == null) + if (dlResource == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.applyInteriorState(dc, sdc, this.getActiveAttributes(), this.getTexture(), referencePos); gl.glCallList(dlResource[0]); - if (this.crossesDateLine) - { + if (this.crossesDateLine) { gl.glPushMatrix(); - try - { + try { // Apply hemisphere offset and draw again double hemisphereSign = Math.signum(referencePos.getLongitude().degrees); gl.glTranslated(360 * hemisphereSign, 0, 0); gl.glCallList(dlResource[0]); - } - finally - { + } finally { gl.glPopMatrix(); } } } - protected WWTexture getTexture() - { - if (this.getActiveAttributes().getImageSource() == null) + protected WWTexture getTexture() { + if (this.getActiveAttributes().getImageSource() == null) { return null; + } - if (this.texture == null && this.getActiveAttributes().getImageSource() != null) + if (this.texture == null && this.getActiveAttributes().getImageSource() != null) { this.texture = new BasicWWTexture(this.getActiveAttributes().getImageSource(), true); + } return this.texture; } @@ -173,22 +167,16 @@ protected WWTexture getTexture() //**************************************************************// //******************** Interior Tessellation *****************// //**************************************************************// - - protected int[] tessellateInterior(DrawContext dc, LatLon referenceLocation) - { - if (dc == null) - { + protected int[] tessellateInterior(DrawContext dc, LatLon referenceLocation) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return this.doTessellateInterior(dc, referenceLocation); - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { String message = Logging.getMessage("generic.ExceptionWhileTessellating", this); Logging.logger().log(Level.SEVERE, message, e); @@ -201,16 +189,14 @@ protected int[] tessellateInterior(DrawContext dc, LatLon referenceLocation) } } - protected int[] doTessellateInterior(DrawContext dc, LatLon referenceLocation) - { + protected int[] doTessellateInterior(DrawContext dc, LatLon referenceLocation) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. GLUtessellatorCallback cb = GLUTessellatorSupport.createOGLDrawPrimitivesCallback(gl); - int[] dlResource = new int[] {gl.glGenLists(1), 1}; + int[] dlResource = new int[]{gl.glGenLists(1), 1}; GLUTessellatorSupport glts = new GLUTessellatorSupport(); - try - { + try { glts.beginTessellation(cb, new Vec4(0, 0, 1)); gl.glNewList(dlResource[0], GL2.GL_COMPILE); int numBytes = this.tessellateInteriorVertices(glts.getGLUtessellator(), referenceLocation); @@ -219,12 +205,10 @@ protected int[] doTessellateInterior(DrawContext dc, LatLon referenceLocation) this.needsInteriorTessellation = false; dc.getGpuResourceCache().put(this.interiorDisplayListCacheKey, dlResource, GpuResourceCache.DISPLAY_LISTS, - numBytes); + numBytes); return dlResource; - } - catch (Throwable e) - { + } catch (Throwable e) { // Free any heap memory used for tessellation immediately. If tessellation has consumed all available heap // memory, we must free memory used by tessellation immediately or subsequent operations such as message // logging will fail. @@ -244,8 +228,7 @@ protected int[] doTessellateInterior(DrawContext dc, LatLon referenceLocation) } } - protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) - { + protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) { // If tessellating the polygon's interior was unsuccessful, we modify the polygon to avoid any additional // tessellation attempts, and free any resources that the polygon won't use. @@ -257,61 +240,57 @@ protected void handleUnsuccessfulInteriorTessellation(DrawContext dc) this.onGeometryChanged(); } - protected int tessellateInteriorVertices(GLUtessellator tess, LatLon referenceLocation) - { + protected int tessellateInteriorVertices(GLUtessellator tess, LatLon referenceLocation) { // Setup the winding order to correctly tessellate the outer and inner rings. - GLU.gluTessProperty(tess, GLU.GLU_TESS_WINDING_RULE, this.windingRule.equals(AVKey.CLOCKWISE) ? - GLU.GLU_TESS_WINDING_NEGATIVE : GLU.GLU_TESS_WINDING_POSITIVE); + GLU.gluTessProperty(tess, GLU.GLU_TESS_WINDING_RULE, this.windingRule.equals(AVKey.CLOCKWISE) + ? GLU.GLU_TESS_WINDING_NEGATIVE : GLU.GLU_TESS_WINDING_POSITIVE); this.crossesDateLine = false; int numBytes = 0; int numRings = this.buffer.size(); - if (this.polygonRingGroups == null) - { + if (this.polygonRingGroups == null) { boolean inBeginPolygon = false; // Polygon rings are drawn following the sub buffers order. If the winding rule is CW all clockwise // rings are considered an outer ring possibly followed by counter clock wise inner rings. - for (int i = 0; i < numRings; i++) - { + for (int i = 0; i < numRings; i++) { VecBuffer vecBuffer = this.buffer.subBuffer(i); numBytes += vecBuffer.getSize() * 3 * 4; // 3 float coords per vertex // Start a new polygon for each outer ring - if (WWMath.computeWindingOrderOfLocations(vecBuffer.getLocations()).equals(this.getWindingRule())) - { - if (inBeginPolygon) + if (WWMath.computeWindingOrderOfLocations(vecBuffer.getLocations()).equals(this.getWindingRule())) { + if (inBeginPolygon) { GLU.gluTessEndPolygon(tess); + } GLU.gluTessBeginPolygon(tess, null); inBeginPolygon = true; } - if (tessellateRing(tess, vecBuffer, referenceLocation)) + if (tessellateRing(tess, vecBuffer, referenceLocation)) { this.crossesDateLine = true; + } } - if (inBeginPolygon) + if (inBeginPolygon) { GLU.gluTessEndPolygon(tess); - } - else - { + } + } else { // Tessellate one polygon per ring group int numGroups = this.polygonRingGroups.length; - for (int group = 0; group < numGroups; group++) - { + for (int group = 0; group < numGroups; group++) { int groupStart = this.polygonRingGroups[group]; int groupLength = (group == numGroups - 1) ? numRings - groupStart - : this.polygonRingGroups[group + 1] - groupStart; + : this.polygonRingGroups[group + 1] - groupStart; GLU.gluTessBeginPolygon(tess, null); - for (int i = 0; i < groupLength; i++) - { + for (int i = 0; i < groupLength; i++) { VecBuffer subBuffer = this.buffer.subBuffer(groupStart + i); numBytes += subBuffer.getSize() * 3 * 4; // 3 float coords per vertex - if (tessellateRing(tess, subBuffer, referenceLocation)) + if (tessellateRing(tess, subBuffer, referenceLocation)) { this.crossesDateLine = true; + } } GLU.gluTessEndPolygon(tess); } @@ -320,8 +299,7 @@ protected int tessellateInteriorVertices(GLUtessellator tess, LatLon referenceLo return numBytes; } - protected boolean tessellateRing(GLUtessellator tess, VecBuffer vecBuffer, LatLon referenceLocation) - { + protected boolean tessellateRing(GLUtessellator tess, VecBuffer vecBuffer, LatLon referenceLocation) { // Check for pole wrapping shape List dateLineCrossingPoints = this.computeDateLineCrossingPoints(vecBuffer); int pole = this.computePole(dateLineCrossingPoints); @@ -332,16 +310,14 @@ protected boolean tessellateRing(GLUtessellator tess, VecBuffer vecBuffer, LatLo boolean dateLineCrossed = false; int sign = 0; double[] previousPoint = null; - for (double[] coords : iterable) - { + for (double[] coords : iterable) { if (poleWrappingPoint != null && previousPoint != null - && poleWrappingPoint[0] == previousPoint[0] && poleWrappingPoint[1] == previousPoint[1]) - { + && poleWrappingPoint[0] == previousPoint[0] && poleWrappingPoint[1] == previousPoint[1]) { previousPoint = coords.clone(); // Wrapping a pole double[] dateLinePoint1 = this.computeDateLineEntryPoint(poleWrappingPoint, coords); - double[] polePoint1 = new double[] {180 * Math.signum(poleWrappingPoint[0]), 90d * pole, 0}; + double[] polePoint1 = new double[]{180 * Math.signum(poleWrappingPoint[0]), 90d * pole, 0}; double[] dateLinePoint2 = dateLinePoint1.clone(); double[] polePoint2 = polePoint1.clone(); dateLinePoint2[0] *= -1; @@ -359,11 +335,8 @@ protected boolean tessellateRing(GLUtessellator tess, VecBuffer vecBuffer, LatLo tessVertex(tess, coords, referenceLocation); dateLineCrossed = true; - } - else - { - if (previousPoint != null && Math.abs(previousPoint[0] - coords[0]) > 180) - { + } else { + if (previousPoint != null && Math.abs(previousPoint[0] - coords[0]) > 180) { // Crossing date line, sum departure point longitude sign for hemisphere offset sign += (int) Math.signum(previousPoint[0]); dateLineCrossed = true; @@ -380,8 +353,7 @@ protected boolean tessellateRing(GLUtessellator tess, VecBuffer vecBuffer, LatLo return dateLineCrossed; } - private static void tessVertex(GLUtessellator tess, double[] coords, LatLon referenceLocation) - { + private static void tessVertex(GLUtessellator tess, double[] coords, LatLon referenceLocation) { double[] vertex = new double[3]; vertex[0] = coords[0] - referenceLocation.getLongitude().degrees; vertex[1] = coords[1] - referenceLocation.getLatitude().degrees; @@ -389,49 +361,45 @@ private static void tessVertex(GLUtessellator tess, double[] coords, LatLon refe } // --- Pole wrapping shapes handling --- - - protected List computeDateLineCrossingPoints(VecBuffer vecBuffer) - { + protected List computeDateLineCrossingPoints(VecBuffer vecBuffer) { // Shapes that include a pole will yield an odd number of points List list = new ArrayList(); Iterable iterable = vecBuffer.getCoords(3); double[] previousPoint = null; - for (double[] coords : iterable) - { - if (previousPoint != null && Math.abs(previousPoint[0] - coords[0]) > 180) + for (double[] coords : iterable) { + if (previousPoint != null && Math.abs(previousPoint[0] - coords[0]) > 180) { list.add(previousPoint); + } previousPoint = coords; } return list; } - protected int computePole(List dateLineCrossingPoints) - { + protected int computePole(List dateLineCrossingPoints) { int sign = 0; - for (double[] point : dateLineCrossingPoints) - { + for (double[] point : dateLineCrossingPoints) { sign += Math.signum(point[0]); } - if (sign == 0) + if (sign == 0) { return 0; + } // If we cross the date line going west (from a negative longitude) with a clockwise polygon, // then the north pole (positive) is included. return this.getWindingRule().equals(AVKey.CLOCKWISE) && sign < 0 ? 1 : -1; } - protected double[] computePoleWrappingPoint(int pole, List dateLineCrossingPoints) - { - if (pole == 0) + protected double[] computePoleWrappingPoint(int pole, List dateLineCrossingPoints) { + if (pole == 0) { return null; + } // Find point with latitude closest to pole int idx = -1; double max = pole < 0 ? 90 : -90; - for (int i = 0; i < dateLineCrossingPoints.size(); i++) - { + for (int i = 0; i < dateLineCrossingPoints.size(); i++) { double[] point = dateLineCrossingPoints.get(i); if (pole < 0 && point[1] < max) // increasing latitude toward north pole { @@ -448,8 +416,7 @@ protected double[] computePoleWrappingPoint(int pole, List dateLineCro return dateLineCrossingPoints.get(idx); } - protected double[] computeDateLineEntryPoint(double[] from, double[] to) - { + protected double[] computeDateLineEntryPoint(double[] from, double[] to) { // Linear interpolation between from and to at the date line double dLat = to[1] - from[1]; double dLon = 360 - Math.abs(to[0] - from[0]); @@ -457,6 +424,6 @@ protected double[] computeDateLineEntryPoint(double[] from, double[] to) double lat = from[1] + dLat * s; double lon = 180 * Math.signum(from[0]); // same side as from - return new double[] {lon, lat, 0}; + return new double[]{lon, lat, 0}; } } diff --git a/src/gov/nasa/worldwind/render/SurfacePolyline.java b/src/gov/nasa/worldwind/render/SurfacePolyline.java index 513198eae3..ad118eda2b 100644 --- a/src/gov/nasa/worldwind/render/SurfacePolyline.java +++ b/src/gov/nasa/worldwind/render/SurfacePolyline.java @@ -23,14 +23,15 @@ * @author dcollins * @version $Id: SurfacePolyline.java 2406 2014-10-29 23:39:29Z dcollins $ */ -public class SurfacePolyline extends AbstractSurfaceShape implements Exportable -{ +public class SurfacePolyline extends AbstractSurfaceShape implements Exportable { + protected boolean closed; protected Iterable locations; - /** Constructs a new surface polyline with the default attributes and no locations. */ - public SurfacePolyline() - { + /** + * Constructs a new surface polyline with the default attributes and no locations. + */ + public SurfacePolyline() { } /** @@ -38,8 +39,7 @@ public SurfacePolyline() * * @param source the shape to copy. */ - public SurfacePolyline(SurfacePolyline source) - { + public SurfacePolyline(SurfacePolyline source) { super(source); this.closed = source.closed; @@ -53,8 +53,7 @@ public SurfacePolyline(SurfacePolyline source) * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public SurfacePolyline(ShapeAttributes normalAttrs) - { + public SurfacePolyline(ShapeAttributes normalAttrs) { super(normalAttrs); } @@ -67,10 +66,8 @@ public SurfacePolyline(ShapeAttributes normalAttrs) * * @throws IllegalArgumentException if the locations iterable is null. */ - public SurfacePolyline(Iterable iterable) - { - if (iterable == null) - { + public SurfacePolyline(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -87,16 +84,14 @@ public SurfacePolyline(Iterable iterable) * Note: If fewer than two locations is specified, no polyline is drawn. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param iterable the polyline locations. + * @param iterable the polyline locations. * * @throws IllegalArgumentException if the locations iterable is null. */ - public SurfacePolyline(ShapeAttributes normalAttrs, Iterable iterable) - { + public SurfacePolyline(ShapeAttributes normalAttrs, Iterable iterable) { super(normalAttrs); - if (iterable == null) - { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -105,31 +100,25 @@ public SurfacePolyline(ShapeAttributes normalAttrs, Iterable i this.locations = iterable; } - public boolean isClosed() - { + public boolean isClosed() { return this.closed; } - public void setClosed(boolean closed) - { + public void setClosed(boolean closed) { this.closed = closed; this.onShapeChanged(); // Potentially causes the shape's geometry to change. } - public Iterable getLocations(Globe globe) - { + public Iterable getLocations(Globe globe) { return this.getLocations(); } - public Iterable getLocations() - { + public Iterable getLocations() { return this.locations; } - public void setLocations(Iterable iterable) - { - if (iterable == null) - { + public void setLocations(Iterable iterable) { + if (iterable == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -139,28 +128,30 @@ public void setLocations(Iterable iterable) this.onShapeChanged(); } - public Position getReferencePosition() - { - if (this.locations == null) + public Position getReferencePosition() { + if (this.locations == null) { return null; + } Iterator iterator = this.locations.iterator(); - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return null; + } return new Position(iterator.next(), 0); } - protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) - { - if (this.locations == null) + protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) { + if (this.locations == null) { return null; + } ArrayList drawLocations = new ArrayList(); this.generateIntermediateLocations(this.locations, edgeIntervalsPerDegree, this.isClosed(), drawLocations); - if (drawLocations.size() < 2) + if (drawLocations.size() < 2) { return null; + } ArrayList> geom = new ArrayList>(); geom.add(drawLocations); @@ -168,15 +159,14 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer return geom; } - protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) - { - if (this.locations == null) + protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) { + if (this.locations == null) { return; + } ArrayList newLocations = new ArrayList(); - for (LatLon ll : this.locations) - { + for (LatLon ll : this.locations) { Angle heading = LatLon.greatCircleAzimuth(oldReferencePosition, ll); Angle pathLength = LatLon.greatCircleDistance(oldReferencePosition, ll); newLocations.add(LatLon.greatCircleEndPosition(newReferencePosition, heading, pathLength)); @@ -185,70 +175,69 @@ protected void doMoveTo(Position oldReferencePosition, Position newReferencePosi this.setLocations(newLocations); } - protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) - { - if (this.locations == null) + protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) { + if (this.locations == null) { return; + } List newLocations = LatLon.computeShiftedLocations(globe, oldReferencePosition, newReferencePosition, - this.getLocations()); + this.getLocations()); this.setLocations(newLocations); } - protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) { // Intentionally left blank; SurfacePolyline does not render an interior. } - /** {@inheritDoc} Overridden to treat the shape as an open path if the polyline is not closed. */ + /** + * {@inheritDoc} Overridden to treat the shape as an open path if the polyline is not closed. + */ @Override - protected boolean canContainPole() - { + protected boolean canContainPole() { return this.isClosed(); } //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); Iterable iterable = this.getLocations(); - if (iterable != null) + if (iterable != null) { rs.addStateValueAsLatLonList(context, "locationList", iterable); + } rs.addStateValueAsBoolean(context, "closed", this.isClosed()); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Iterable iterable = rs.getStateValueAsLatLonList(context, "locationList"); - if (iterable != null) + if (iterable != null) { this.setLocations(iterable); + } Boolean b = rs.getStateValueAsBoolean(context, "closed"); - if (b != null) + if (b != null) { this.setClosed(b); + } } - protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.legacyRestoreState(rs, context); List locations = rs.getStateValueAsLatLonList(context, "locations"); - if (locations != null) + if (locations != null) { this.setLocations(locations); + } } //**************************************************************// //************************* Export *****************************// //**************************************************************// - /** * Export the polyline to KML as a {@code } element. The {@code output} object will receive the data. * This object must be one of: java.io.Writer java.io.OutputStream javax.xml.stream.XMLStreamWriter @@ -256,31 +245,24 @@ protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateO * @param output Object to receive the generated KML. * * @throws XMLStreamException If an exception occurs while writing the KML - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -289,8 +271,7 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("Placemark"); String property = getStringValue(AVKey.DISPLAY_NAME); - if (property != null) - { + if (property != null) { xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(property); xmlWriter.writeEndElement(); @@ -301,16 +282,14 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); String shortDescription = (String) getValue(AVKey.SHORT_DESCRIPTION); - if (shortDescription != null) - { + if (shortDescription != null) { xmlWriter.writeStartElement("Snippet"); xmlWriter.writeCharacters(shortDescription); xmlWriter.writeEndElement(); } String description = (String) getValue(AVKey.BALLOON_TEXT); - if (description != null) - { + if (description != null) { xmlWriter.writeStartElement("description"); xmlWriter.writeCharacters(description); xmlWriter.writeEndElement(); @@ -320,8 +299,7 @@ else if (output instanceof OutputStream) final ShapeAttributes highlightAttributes = getHighlightAttributes(); // Write style map - if (normalAttributes != null || highlightAttributes != null) - { + if (normalAttributes != null || highlightAttributes != null) { xmlWriter.writeStartElement("StyleMap"); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.NORMAL, normalAttributes); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.HIGHLIGHT, highlightAttributes); @@ -344,8 +322,7 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); xmlWriter.writeStartElement("coordinates"); - for (LatLon position : this.getLocations()) - { + for (LatLon position : this.getLocations()) { xmlWriter.writeCharacters(Double.toString(position.getLongitude().getDegrees())); xmlWriter.writeCharacters(","); xmlWriter.writeCharacters(Double.toString(position.getLatitude().getDegrees())); @@ -357,7 +334,8 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); // Placemark xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } } diff --git a/src/gov/nasa/worldwind/render/SurfacePolylines.java b/src/gov/nasa/worldwind/render/SurfacePolylines.java index 76f98bb383..3f05332d88 100644 --- a/src/gov/nasa/worldwind/render/SurfacePolylines.java +++ b/src/gov/nasa/worldwind/render/SurfacePolylines.java @@ -20,18 +20,16 @@ * @author Patrick Murris * @version $Id: SurfacePolylines.java 2406 2014-10-29 23:39:29Z dcollins $ */ -public class SurfacePolylines extends AbstractSurfaceShape -{ +public class SurfacePolylines extends AbstractSurfaceShape { + protected List sectors; protected CompoundVecBuffer buffer; protected boolean needsOutlineTessellation = true; protected boolean crossesDateLine = false; protected Object outlineDisplayListCacheKey = new Object(); - public SurfacePolylines(CompoundVecBuffer buffer) - { - if (buffer == null) - { + public SurfacePolylines(CompoundVecBuffer buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -40,16 +38,13 @@ public SurfacePolylines(CompoundVecBuffer buffer) this.buffer = buffer; } - public SurfacePolylines(Sector sector, CompoundVecBuffer buffer) - { - if (sector == null) - { + public SurfacePolylines(Sector sector, CompoundVecBuffer buffer) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer == null) - { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -64,32 +59,28 @@ public SurfacePolylines(Sector sector, CompoundVecBuffer buffer) * * @return the underlying {@link CompoundVecBuffer}. */ - public CompoundVecBuffer getBuffer() - { + public CompoundVecBuffer getBuffer() { return this.buffer; } @Override - public List getSectors(DrawContext dc) - { - if (dc == null) - { + public List getSectors(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // SurfacePolylines does not interpolate between caller specified positions, therefore it has no path type. - if (this.sectors == null) + if (this.sectors == null) { this.sectors = this.computeSectors(dc); + } return this.sectors; } - public Iterable getLocations(Globe globe) - { - if (globe == null) - { + public Iterable getLocations(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -98,53 +89,47 @@ public Iterable getLocations(Globe globe) return this.getLocations(); } - protected List> createGeometry(Globe globe, SurfaceTileDrawContext sdc) - { + protected List> createGeometry(Globe globe, SurfaceTileDrawContext sdc) { // SurfacePolylines does not invoke this method, so return null indicating this method is not supported. // We avoid invoking computeGeometry by overriding determineActiveGeometry below. return null; } - protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) - { + protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) { return null; } - public Iterable getLocations() - { + public Iterable getLocations() { return this.buffer.getLocations(); } @SuppressWarnings({"UnusedDeclaration"}) - public void setLocations(Iterable iterable) - { + public void setLocations(Iterable iterable) { throw new UnsupportedOperationException(); } - public Position getReferencePosition() - { + public Position getReferencePosition() { Iterator iterator = this.getLocations().iterator(); - if (iterator.hasNext()) + if (iterator.hasNext()) { return new Position(iterator.next(), 0); + } return null; } - /** {@inheritDoc} Overridden to treat the polylines as open paths rather than closed polygons. */ + /** + * {@inheritDoc} Overridden to treat the polylines as open paths rather than closed polygons. + */ @Override - protected boolean canContainPole() - { + protected boolean canContainPole() { return false; } - protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) - { - for (int i = 0; i < this.buffer.size(); i++) - { + protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) { + for (int i = 0; i < this.buffer.size(); i++) { VecBuffer vb = this.buffer.subBuffer(i); - for (int pos = 0; pos < vb.getSize(); pos++) - { + for (int pos = 0; pos < vb.getSize(); pos++) { LatLon ll = vb.getLocation(pos); Angle heading = LatLon.greatCircleAzimuth(oldReferencePosition, ll); Angle pathLength = LatLon.greatCircleDistance(oldReferencePosition, ll); @@ -155,17 +140,14 @@ protected void doMoveTo(Position oldReferencePosition, Position newReferencePosi this.onGeometryChanged(); } - protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) - { - for (int i = 0; i < this.buffer.size(); i++) - { + protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) { + for (int i = 0; i < this.buffer.size(); i++) { VecBuffer vb = this.buffer.subBuffer(i); List newLocations = LatLon.computeShiftedLocations(globe, oldReferencePosition, - newReferencePosition, vb.getLocations()); + newReferencePosition, vb.getLocations()); - for (int pos = 0; pos < vb.getSize(); pos++) - { + for (int pos = 0; pos < vb.getSize(); pos++) { vb.putLocation(pos, newLocations.get(i)); } } @@ -173,86 +155,78 @@ protected void doMoveTo(Globe globe, Position oldReferencePosition, Position new this.onGeometryChanged(); } - protected void onGeometryChanged() - { + protected void onGeometryChanged() { this.sectors = null; this.needsOutlineTessellation = true; super.onShapeChanged(); } - protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) { // Intentionally left blank in order to override the superclass behavior with nothing. } - protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawInterior(DrawContext dc, SurfaceTileDrawContext sdc) { // Intentionally left blank; SurfacePolylines does not render an interior. } - protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) { // Exit immediately if the Polyline has no coordinate data. - if (this.buffer.size() == 0) + if (this.buffer.size() == 0) { return; + } Position referencePos = this.getReferencePosition(); - if (referencePos == null) + if (referencePos == null) { return; + } int hemisphereSign = (int) Math.signum(sdc.getSector().getCentroid().getLongitude().degrees); // Attempt to tessellate the Polyline's outline if the Polyline's outline display list is uninitialized, or if // the Polyline is marked as needing tessellation. int[] dlResource = (int[]) dc.getGpuResourceCache().get(this.outlineDisplayListCacheKey); - if (dlResource == null || this.needsOutlineTessellation) + if (dlResource == null || this.needsOutlineTessellation) { dlResource = this.tessellateOutline(dc, referencePos); + } // Exit immediately if the Polyline's interior failed to tessellate. The cause has already been logged by // tessellateInterior. - if (dlResource == null) + if (dlResource == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.applyOutlineState(dc, this.getActiveAttributes()); gl.glCallList(dlResource[0]); - if (this.crossesDateLine) - { + if (this.crossesDateLine) { gl.glPushMatrix(); - try - { + try { // Apply hemisphere offset and draw again gl.glTranslated(360 * hemisphereSign, 0, 0); gl.glCallList(dlResource[0]); - } - finally - { + } finally { gl.glPopMatrix(); } } } - protected int[] tessellateOutline(DrawContext dc, LatLon referenceLocation) - { + protected int[] tessellateOutline(DrawContext dc, LatLon referenceLocation) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.crossesDateLine = false; - int[] dlResource = new int[] {gl.glGenLists(1), 1}; + int[] dlResource = new int[]{gl.glGenLists(1), 1}; gl.glNewList(dlResource[0], GL2.GL_COMPILE); - try - { + try { // Tessellate each part, note if crossing date line - for (int i = 0; i < this.buffer.size(); i++) - { + for (int i = 0; i < this.buffer.size(); i++) { VecBuffer subBuffer = this.buffer.subBuffer(i); - if (this.tessellatePart(gl, subBuffer, referenceLocation)) + if (this.tessellatePart(gl, subBuffer, referenceLocation)) { this.crossesDateLine = true; + } } - } - finally - { + } finally { gl.glEndList(); } @@ -260,26 +234,22 @@ protected int[] tessellateOutline(DrawContext dc, LatLon referenceLocation) int numBytes = this.buffer.size() * 3 * 4; // 3 float coords dc.getGpuResourceCache().put(this.outlineDisplayListCacheKey, dlResource, GpuResourceCache.DISPLAY_LISTS, - numBytes); + numBytes); return dlResource; } - protected boolean tessellatePart(GL2 gl, VecBuffer vecBuffer, LatLon referenceLocation) - { + protected boolean tessellatePart(GL2 gl, VecBuffer vecBuffer, LatLon referenceLocation) { Iterable iterable = vecBuffer.getCoords(3); boolean dateLineCrossed = false; gl.glBegin(GL2.GL_LINE_STRIP); - try - { + try { int sign = 0; // hemisphere offset direction double previousLongitude = 0; - for (double[] coords : iterable) - { - if (Math.abs(previousLongitude - coords[0]) > 180) - { + for (double[] coords : iterable) { + if (Math.abs(previousLongitude - coords[0]) > 180) { // Crossing date line, sum departure point longitude sign for hemisphere offset sign += (int) Math.signum(previousLongitude); dateLineCrossed = true; @@ -292,9 +262,7 @@ protected boolean tessellatePart(GL2 gl, VecBuffer vecBuffer, LatLon referenceLo lonDegrees += sign * 360; // apply hemisphere offset gl.glVertex3f((float) lonDegrees, (float) latDegrees, 0); } - } - finally - { + } finally { gl.glEnd(); } diff --git a/src/gov/nasa/worldwind/render/SurfaceQuad.java b/src/gov/nasa/worldwind/render/SurfaceQuad.java index 6aa3b9e424..b7009a9dd1 100644 --- a/src/gov/nasa/worldwind/render/SurfaceQuad.java +++ b/src/gov/nasa/worldwind/render/SurfaceQuad.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: SurfaceQuad.java 2406 2014-10-29 23:39:29Z dcollins $ */ -public class SurfaceQuad extends AbstractSurfaceShape implements Exportable -{ +public class SurfaceQuad extends AbstractSurfaceShape implements Exportable { + protected LatLon center = LatLon.ZERO; protected double width; protected double height; @@ -32,8 +32,7 @@ public class SurfaceQuad extends AbstractSurfaceShape implements Exportable * Constructs a new surface quad with the default attributes, default center location, default dimensions, and * default heading. */ - public SurfaceQuad() - { + public SurfaceQuad() { } /** @@ -43,8 +42,7 @@ public SurfaceQuad() * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public SurfaceQuad(ShapeAttributes normalAttrs) - { + public SurfaceQuad(ShapeAttributes normalAttrs) { super(normalAttrs); } @@ -53,29 +51,25 @@ public SurfaceQuad(ShapeAttributes normalAttrs) * meters). * * @param center the quad's center location. - * @param width the quad's width, in meters. + * @param width the quad's width, in meters. * @param height the quad's height, in meters. * * @throws IllegalArgumentException if the center is null, or if the width or height are negative. */ - public SurfaceQuad(LatLon center, double width, double height) - { - if (center == null) - { + public SurfaceQuad(LatLon center, double width, double height) { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (width < 0) - { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("Geom.HeightIsNegative", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -90,19 +84,17 @@ public SurfaceQuad(LatLon center, double width, double height) * Constructs a new surface quad with the default attributes, the specified center location, dimensions (in meters), * and heading clockwise from North. * - * @param center the quad's center location. - * @param width the quad's width, in meters. - * @param height the quad's height, in meters. + * @param center the quad's center location. + * @param width the quad's width, in meters. + * @param height the quad's height, in meters. * @param heading the quad's heading, clockwise from North. * * @throws IllegalArgumentException if the center or heading are null, or if the width or height are negative. */ - public SurfaceQuad(LatLon center, double width, double height, Angle heading) - { + public SurfaceQuad(LatLon center, double width, double height, Angle heading) { this(center, width, height); - if (heading == null) - { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -117,32 +109,28 @@ public SurfaceQuad(LatLon center, double width, double height, Angle heading) * causes this shape's appearance to change accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the quad's center location. - * @param width the quad's width, in meters. - * @param height the quad's height, in meters. + * @param center the quad's center location. + * @param width the quad's width, in meters. + * @param height the quad's height, in meters. * * @throws IllegalArgumentException if the center is null, or if the width or height are negative. */ - public SurfaceQuad(ShapeAttributes normalAttrs, LatLon center, double width, double height) - { + public SurfaceQuad(ShapeAttributes normalAttrs, LatLon center, double width, double height) { super(normalAttrs); - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (width < 0) - { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("Geom.HeightIsNegative", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -158,8 +146,7 @@ public SurfaceQuad(ShapeAttributes normalAttrs, LatLon center, double width, dou * * @param source the shape to copy. */ - public SurfaceQuad(SurfaceQuad source) - { + public SurfaceQuad(SurfaceQuad source) { super(source); this.center = source.center; @@ -174,19 +161,17 @@ public SurfaceQuad(SurfaceQuad source) * causes this shape's appearance to change accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the quad's center location. - * @param width the quad's width, in meters. - * @param height the quad's height, in meters. - * @param heading the quad's heading, clockwise from North. + * @param center the quad's center location. + * @param width the quad's width, in meters. + * @param height the quad's height, in meters. + * @param heading the quad's heading, clockwise from North. * * @throws IllegalArgumentException if the center or heading are null, or if the width or height are negative. */ - public SurfaceQuad(ShapeAttributes normalAttrs, LatLon center, double width, double height, Angle heading) - { + public SurfaceQuad(ShapeAttributes normalAttrs, LatLon center, double width, double height, Angle heading) { this(normalAttrs, center, width, height); - if (heading == null) - { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -195,15 +180,12 @@ public SurfaceQuad(ShapeAttributes normalAttrs, LatLon center, double width, dou this.heading = heading; } - public LatLon getCenter() - { + public LatLon getCenter() { return this.center; } - public void setCenter(LatLon center) - { - if (center == null) - { + public void setCenter(LatLon center) { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -213,20 +195,16 @@ public void setCenter(LatLon center) this.onShapeChanged(); } - public double getWidth() - { + public double getWidth() { return this.width; } - public double getHeight() - { + public double getHeight() { return this.height; } - public void setWidth(double width) - { - if (width < 0) - { + public void setWidth(double width) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -236,10 +214,8 @@ public void setWidth(double width) this.onShapeChanged(); } - public void setHeight(double height) - { - if (height < 0) - { + public void setHeight(double height) { + if (height < 0) { String message = Logging.getMessage("Geom.HeightIsNegative", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -249,17 +225,14 @@ public void setHeight(double height) this.onShapeChanged(); } - public void setSize(double width, double height) - { - if (width < 0) - { + public void setSize(double width, double height) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("Geom.HeightIsNegative", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -270,15 +243,12 @@ public void setSize(double width, double height) this.onShapeChanged(); } - public Angle getHeading() - { + public Angle getHeading() { return this.heading; } - public void setHeading(Angle heading) - { - if (heading == null) - { + public void setHeading(Angle heading) { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -296,45 +266,40 @@ public void setHeading(Angle heading) * @see gov.nasa.worldwind.globes.Globe#getStateKey(DrawContext) */ @Override - public Object getStateKey(DrawContext dc) - { + public Object getStateKey(DrawContext dc) { // Store a copy of the active attributes to insulate the key from changes made to the shape's active attributes. return new SurfaceShapeStateKey(this.getUniqueId(), this.lastModifiedTime, this.getActiveAttributes().copy(), - dc.getGlobe().getStateKey(dc)); + dc.getGlobe().getStateKey(dc)); } - public Position getReferencePosition() - { + public Position getReferencePosition() { return new Position(this.center, 0); } - protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) - { + protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) { Angle heading = LatLon.greatCircleAzimuth(oldReferencePosition, this.center); Angle pathLength = LatLon.greatCircleDistance(oldReferencePosition, this.center); this.setCenter(LatLon.greatCircleEndPosition(newReferencePosition, heading, pathLength)); } - protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) - { + protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) { List locations = new ArrayList(1); locations.add(this.getCenter()); List newLocations = LatLon.computeShiftedLocations(globe, oldReferencePosition, newReferencePosition, - locations); + locations); this.setCenter(newLocations.get(0)); } - public Iterable getLocations(Globe globe) - { - if (globe == null) - { + public Iterable getLocations(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.width == 0 && this.height == 0) + if (this.width == 0 && this.height == 0) { return null; + } double hw = this.width / 2.0; double hh = this.height / 2.0; @@ -342,19 +307,16 @@ public Iterable getLocations(Globe globe) double distance = Math.sqrt(hw * hw + hh * hh); double pathLength = distance / globeRadius; - double[] cornerAngles = new double[] - { - Math.atan2(-hh, -hw), - Math.atan2(-hh, hw), - Math.atan2(hh, hw), - Math.atan2(hh, -hw), - Math.atan2(-hh, -hw), - }; + double[] cornerAngles = new double[]{ + Math.atan2(-hh, -hw), + Math.atan2(-hh, hw), + Math.atan2(hh, hw), + Math.atan2(hh, -hw), + Math.atan2(-hh, -hw),}; LatLon[] locations = new LatLon[cornerAngles.length]; - for (int i = 0; i < cornerAngles.length; i++) - { + for (int i = 0; i < cornerAngles.length; i++) { double azimuth = (Math.PI / 2.0) - (cornerAngles[i] - this.heading.radians); locations[i] = LatLon.greatCircleEndPosition(this.center, azimuth, pathLength); } @@ -362,11 +324,11 @@ public Iterable getLocations(Globe globe) return java.util.Arrays.asList(locations); } - protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) - { + protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) { Iterable originalLocations = this.getLocations(globe); - if (originalLocations == null) + if (originalLocations == null) { return null; + } ArrayList drawLocations = new ArrayList(); this.generateIntermediateLocations(originalLocations, edgeIntervalsPerDegree, false, drawLocations); @@ -380,9 +342,7 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsLatLon(context, "center", this.getCenter()); @@ -391,46 +351,49 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsDouble(context, "headingDegrees", this.getHeading().degrees); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); LatLon ll = rs.getStateValueAsLatLon(context, "center"); - if (ll != null) + if (ll != null) { this.setCenter(ll); + } Double d = rs.getStateValueAsDouble(context, "width"); - if (d != null) + if (d != null) { this.setWidth(d); + } d = rs.getStateValueAsDouble(context, "height"); - if (d != null) + if (d != null) { this.setHeight(d); + } d = rs.getStateValueAsDouble(context, "headingDegrees"); - if (d != null) + if (d != null) { this.setHeading(Angle.fromDegrees(d)); + } } - protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.legacyRestoreState(rs, context); // Previous versions of SurfaceQuad used half-width and half-height properties. We are now using standard // width and height, so these restored values must be converted. Double width = rs.getStateValueAsDouble(context, "halfWidth"); Double height = rs.getStateValueAsDouble(context, "halfHeight"); - if (width != null && height != null) + if (width != null && height != null) { this.setSize(2 * width, 2 * height); + } // This property has not changed since the previos version, but it's shown here for reference. //LatLon center = rs.getStateValueAsLatLon(context, "center"); //if (center != null) // this.setCenter(center); - Double od = rs.getStateValueAsDouble(context, "orientationDegrees"); - if (od != null) + if (od != null) { this.setHeading(Angle.fromDegrees(od)); + } } /** @@ -440,31 +403,24 @@ protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateO * @param output Object to receive the generated KML. * * @throws javax.xml.stream.XMLStreamException If an exception occurs while writing the KML - * @throws java.io.IOException if an exception occurs while exporting the data. + * @throws java.io.IOException if an exception occurs while exporting the data. * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -473,8 +429,7 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("Placemark"); String property = getStringValue(AVKey.DISPLAY_NAME); - if (property != null) - { + if (property != null) { xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(property); xmlWriter.writeEndElement(); @@ -485,16 +440,14 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); String shortDescription = (String) getValue(AVKey.SHORT_DESCRIPTION); - if (shortDescription != null) - { + if (shortDescription != null) { xmlWriter.writeStartElement("Snippet"); xmlWriter.writeCharacters(shortDescription); xmlWriter.writeEndElement(); } String description = (String) getValue(AVKey.BALLOON_TEXT); - if (description != null) - { + if (description != null) { xmlWriter.writeStartElement("description"); xmlWriter.writeCharacters(description); xmlWriter.writeEndElement(); @@ -505,8 +458,7 @@ else if (output instanceof OutputStream) final ShapeAttributes highlightAttributes = getHighlightAttributes(); // Write style map - if (normalAttributes != null || highlightAttributes != null) - { + if (normalAttributes != null || highlightAttributes != null) { xmlWriter.writeStartElement("StyleMap"); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.NORMAL, normalAttributes); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.HIGHLIGHT, highlightAttributes); @@ -529,8 +481,7 @@ else if (output instanceof OutputStream) // Outer boundary Iterable outerBoundary = this.getLocations(globe); - if (outerBoundary != null) - { + if (outerBoundary != null) { xmlWriter.writeStartElement("outerBoundaryIs"); KMLExportUtil.exportBoundaryAsLinearRing(xmlWriter, outerBoundary, null); xmlWriter.writeEndElement(); // outerBoundaryIs @@ -540,7 +491,8 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); // Placemark xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } } diff --git a/src/gov/nasa/worldwind/render/SurfaceRenderable.java b/src/gov/nasa/worldwind/render/SurfaceRenderable.java index b774009942..dd9b964b2f 100644 --- a/src/gov/nasa/worldwind/render/SurfaceRenderable.java +++ b/src/gov/nasa/worldwind/render/SurfaceRenderable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.geom.Sector; @@ -19,8 +18,8 @@ * @author dcollins * @version $Id: SurfaceRenderable.java 2283 2014-08-30 15:58:43Z dcollins $ */ -public interface SurfaceRenderable extends Renderable -{ +public interface SurfaceRenderable extends Renderable { + /** * Returns a list of sectors indicating the geographic region that bounds this renderable for the specified draw * context. diff --git a/src/gov/nasa/worldwind/render/SurfaceSector.java b/src/gov/nasa/worldwind/render/SurfaceSector.java index e3e53239cf..8384665bc2 100644 --- a/src/gov/nasa/worldwind/render/SurfaceSector.java +++ b/src/gov/nasa/worldwind/render/SurfaceSector.java @@ -21,13 +21,15 @@ * @author dcollins * @version $Id: SurfaceSector.java 2406 2014-10-29 23:39:29Z dcollins $ */ -public class SurfaceSector extends AbstractSurfaceShape implements Exportable -{ +public class SurfaceSector extends AbstractSurfaceShape implements Exportable { + protected Sector sector = Sector.EMPTY_SECTOR; - /** Constructs a new surface sector with the default attributes and the {@link gov.nasa.worldwind.geom.Sector#EMPTY_SECTOR}. */ - public SurfaceSector() - { + /** + * Constructs a new surface sector with the default attributes and the + * {@link gov.nasa.worldwind.geom.Sector#EMPTY_SECTOR}. + */ + public SurfaceSector() { } /** @@ -37,8 +39,7 @@ public SurfaceSector() * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public SurfaceSector(ShapeAttributes normalAttrs) - { + public SurfaceSector(ShapeAttributes normalAttrs) { super(normalAttrs); } @@ -49,10 +50,8 @@ public SurfaceSector(ShapeAttributes normalAttrs) * * @throws IllegalArgumentException if the sector is null. */ - public SurfaceSector(Sector sector) - { - if (sector == null) - { + public SurfaceSector(Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -67,16 +66,14 @@ public SurfaceSector(Sector sector) * accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param sector the shape's sector. + * @param sector the shape's sector. * * @throws IllegalArgumentException if the sector is null. */ - public SurfaceSector(ShapeAttributes normalAttrs, Sector sector) - { + public SurfaceSector(ShapeAttributes normalAttrs, Sector sector) { super(normalAttrs); - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -85,15 +82,12 @@ public SurfaceSector(ShapeAttributes normalAttrs, Sector sector) this.sector = sector; } - public Sector getSector() - { + public Sector getSector() { return this.sector; } - public void setSector(Sector sector) - { - if (sector == null) - { + public void setSector(Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -103,15 +97,14 @@ public void setSector(Sector sector) this.onShapeChanged(); } - public Position getReferencePosition() - { + public Position getReferencePosition() { return new Position(this.sector.getCentroid(), 0); } - public Iterable getLocations(Globe globe) - { - if (this.sector.equals(Sector.EMPTY_SECTOR)) + public Iterable getLocations(Globe globe) { + if (this.sector.equals(Sector.EMPTY_SECTOR)) { return null; + } LatLon[] locations = new LatLon[5]; System.arraycopy(this.sector.getCorners(), 0, locations, 0, 4); @@ -120,11 +113,11 @@ public Iterable getLocations(Globe globe) return Arrays.asList(locations); } - protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) - { + protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) { Iterable originalLocations = this.getLocations(globe); - if (originalLocations == null) + if (originalLocations == null) { return null; + } ArrayList drawLocations = new ArrayList(); this.generateIntermediateLocations(originalLocations, edgeIntervalsPerDegree, false, drawLocations); @@ -135,62 +128,57 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer return geom; } - protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) - { - LatLon[] locations = new LatLon[] - { - new LatLon(this.sector.getMinLatitude(), this.sector.getMinLongitude()), - new LatLon(this.sector.getMaxLatitude(), this.sector.getMaxLongitude()) - }; + protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) { + LatLon[] locations = new LatLon[]{ + new LatLon(this.sector.getMinLatitude(), this.sector.getMinLongitude()), + new LatLon(this.sector.getMaxLatitude(), this.sector.getMaxLongitude()) + }; LatLon[] newLocations = new LatLon[2]; - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { Angle heading = LatLon.greatCircleAzimuth(oldReferencePosition, locations[i]); Angle pathLength = LatLon.greatCircleDistance(oldReferencePosition, locations[i]); newLocations[i] = LatLon.greatCircleEndPosition(newReferencePosition, heading, pathLength); } this.setSector(new Sector( - newLocations[0].getLatitude(), newLocations[1].getLatitude(), - newLocations[0].getLongitude(), newLocations[1].getLongitude())); + newLocations[0].getLatitude(), newLocations[1].getLatitude(), + newLocations[0].getLongitude(), newLocations[1].getLongitude())); } @Override - protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) - { + protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) { this.doMoveTo(oldReferencePosition, newReferencePosition); } //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsSector(context, "sector", this.getSector()); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Sector sector = rs.getStateValueAsSector(context, "sector"); - if (sector != null) + if (sector != null) { this.setSector(sector); + } } - protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.legacyRestoreState(rs, context); // Previous versions of SurfaceSector would have stored the locations produced by treating the sector as a list // of polygon locations. To restore an shape saved from the previous version, we compute the bounding sector of // those locations to define a sector. List locations = rs.getStateValueAsLatLonList(context, "locations"); - if (locations != null) + if (locations != null) { this.setSector(Sector.boundingSector(locations)); + } } /** @@ -200,31 +188,24 @@ protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateO * @param output Object to receive the generated KML. * * @throws XMLStreamException If an exception occurs while writing the KML - * @throws IOException if an exception occurs while exporting the data. + * @throws IOException if an exception occurs while exporting the data. * @see #export(String, Object) */ - protected void exportAsKML(Object output) throws IOException, XMLStreamException - { + protected void exportAsKML(Object output) throws IOException, XMLStreamException { XMLStreamWriter xmlWriter = null; XMLOutputFactory factory = XMLOutputFactory.newInstance(); boolean closeWriterWhenFinished = true; - if (output instanceof XMLStreamWriter) - { + if (output instanceof XMLStreamWriter) { xmlWriter = (XMLStreamWriter) output; closeWriterWhenFinished = false; - } - else if (output instanceof Writer) - { + } else if (output instanceof Writer) { xmlWriter = factory.createXMLStreamWriter((Writer) output); - } - else if (output instanceof OutputStream) - { + } else if (output instanceof OutputStream) { xmlWriter = factory.createXMLStreamWriter((OutputStream) output); } - if (xmlWriter == null) - { + if (xmlWriter == null) { String message = Logging.getMessage("Export.UnsupportedOutputObject"); Logging.logger().warning(message); throw new IllegalArgumentException(message); @@ -233,8 +214,7 @@ else if (output instanceof OutputStream) xmlWriter.writeStartElement("Placemark"); String property = getStringValue(AVKey.DISPLAY_NAME); - if (property != null) - { + if (property != null) { xmlWriter.writeStartElement("name"); xmlWriter.writeCharacters(property); xmlWriter.writeEndElement(); @@ -245,16 +225,14 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); String shortDescription = (String) getValue(AVKey.SHORT_DESCRIPTION); - if (shortDescription != null) - { + if (shortDescription != null) { xmlWriter.writeStartElement("Snippet"); xmlWriter.writeCharacters(shortDescription); xmlWriter.writeEndElement(); } String description = (String) getValue(AVKey.BALLOON_TEXT); - if (description != null) - { + if (description != null) { xmlWriter.writeStartElement("description"); xmlWriter.writeCharacters(description); xmlWriter.writeEndElement(); @@ -264,8 +242,7 @@ else if (output instanceof OutputStream) final ShapeAttributes highlightAttributes = this.getHighlightAttributes(); // Write style map - if (normalAttributes != null || highlightAttributes != null) - { + if (normalAttributes != null || highlightAttributes != null) { xmlWriter.writeStartElement("StyleMap"); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.NORMAL, normalAttributes); KMLExportUtil.exportAttributesAsKML(xmlWriter, KMLConstants.HIGHLIGHT, highlightAttributes); @@ -294,7 +271,8 @@ else if (output instanceof OutputStream) xmlWriter.writeEndElement(); // Placemark xmlWriter.flush(); - if (closeWriterWhenFinished) + if (closeWriterWhenFinished) { xmlWriter.close(); + } } } diff --git a/src/gov/nasa/worldwind/render/SurfaceShape.java b/src/gov/nasa/worldwind/render/SurfaceShape.java index 7d0528f658..2efc008a47 100644 --- a/src/gov/nasa/worldwind/render/SurfaceShape.java +++ b/src/gov/nasa/worldwind/render/SurfaceShape.java @@ -21,8 +21,8 @@ * @version $Id: SurfaceShape.java 2339 2014-09-22 18:22:37Z tgaskins $ */ public interface SurfaceShape - extends SurfaceObject, Highlightable, ExtentHolder, MeasurableArea, MeasurableLength, Restorable, Attributable -{ + extends SurfaceObject, Highlightable, ExtentHolder, MeasurableArea, MeasurableLength, Restorable, Attributable { + /** * Indicates whether to highlight the surface shape. * @@ -133,7 +133,7 @@ public interface SurfaceShape * @param maxEdgeIntervals the maximum number of interpolated edge intervals. * * @throws IllegalArgumentException if either of minEdgeIntervals or maxEdgeIntervals is - * less than or equal to zero. + * less than or equal to zero. * @see #setTexelsPerEdgeInterval(double) */ void setMinAndMaxEdgeIntervals(int minEdgeIntervals, int maxEdgeIntervals); @@ -154,11 +154,11 @@ public interface SurfaceShape * Returns the shapes's area in square meters. If terrainConformant is true, the area returned is the * surface area of the terrain, including its hillsides and other undulations. * - * @param globe the globe the shape is related to. + * @param globe the globe the shape is related to. * @param terrainConformant whether or not the returned area should treat the shape as conforming to the terrain. * * @return the shape's area in square meters. Returns -1 if the object does not form an area due to an insufficient - * number of vertices or any other condition. + * number of vertices or any other condition. * * @throws IllegalArgumentException if globe is null. */ diff --git a/src/gov/nasa/worldwind/render/SurfaceSquare.java b/src/gov/nasa/worldwind/render/SurfaceSquare.java index ecc55c0e15..0325b48e9b 100644 --- a/src/gov/nasa/worldwind/render/SurfaceSquare.java +++ b/src/gov/nasa/worldwind/render/SurfaceSquare.java @@ -12,14 +12,13 @@ * @author dcollins * @version $Id: SurfaceSquare.java 2302 2014-09-08 20:40:47Z tgaskins $ */ -public class SurfaceSquare extends SurfaceQuad -{ +public class SurfaceSquare extends SurfaceQuad { + /** * Constructs a new surface square with the default attributes, default center location, default size, and default * heading. */ - public SurfaceSquare() - { + public SurfaceSquare() { } /** @@ -27,8 +26,7 @@ public SurfaceSquare() * * @param source the shape to copy. */ - public SurfaceSquare(SurfaceSquare source) - { + public SurfaceSquare(SurfaceSquare source) { super(source); } @@ -39,8 +37,7 @@ public SurfaceSquare(SurfaceSquare source) * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. */ - public SurfaceSquare(ShapeAttributes normalAttrs) - { + public SurfaceSquare(ShapeAttributes normalAttrs) { super(normalAttrs); } @@ -48,12 +45,11 @@ public SurfaceSquare(ShapeAttributes normalAttrs) * Constructs a new surface square with the default attributes, the specified center location and size (in meters). * * @param center the square's center location. - * @param size the square's width and height, in meters. + * @param size the square's width and height, in meters. * * @throws IllegalArgumentException if the center is null, or if the size is negative. */ - public SurfaceSquare(LatLon center, double size) - { + public SurfaceSquare(LatLon center, double size) { super(center, size, size); } @@ -61,14 +57,13 @@ public SurfaceSquare(LatLon center, double size) * Constructs a new surface square with the default attributes, the specified center location, size (in meters), and * heading clockwise from North. * - * @param center the square's center location. - * @param size the square's width and height, in meters. + * @param center the square's center location. + * @param size the square's width and height, in meters. * @param heading the square's heading, clockwise from North. * * @throws IllegalArgumentException if the center or heading are null, or if the size is negative. */ - public SurfaceSquare(LatLon center, double size, Angle heading) - { + public SurfaceSquare(LatLon center, double size, Angle heading) { super(center, size, size, heading); } @@ -78,13 +73,12 @@ public SurfaceSquare(LatLon center, double size, Angle heading) * this shape's appearance to change accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the square's center location. - * @param size the square's width and height, in meters. + * @param center the square's center location. + * @param size the square's width and height, in meters. * * @throws IllegalArgumentException if the center is null, or if the size is negative. */ - public SurfaceSquare(ShapeAttributes normalAttrs, LatLon center, double size) - { + public SurfaceSquare(ShapeAttributes normalAttrs, LatLon center, double size) { super(normalAttrs, center, size, size); } @@ -94,26 +88,22 @@ public SurfaceSquare(ShapeAttributes normalAttrs, LatLon center, double size) * causes this shape's appearance to change accordingly. * * @param normalAttrs the normal attributes. May be null, in which case default attributes are used. - * @param center the square's center location. - * @param size the square's width and height, in meters. - * @param heading the square's heading, clockwise from North. + * @param center the square's center location. + * @param size the square's width and height, in meters. + * @param heading the square's heading, clockwise from North. * * @throws IllegalArgumentException if the center or heading are null, or if the size is negative. */ - public SurfaceSquare(ShapeAttributes normalAttrs, LatLon center, double size, Angle heading) - { + public SurfaceSquare(ShapeAttributes normalAttrs, LatLon center, double size, Angle heading) { super(normalAttrs, center, size, size, heading); } - public double getSize() - { + public double getSize() { return this.getWidth(); } - public void setSize(double size) - { - if (size < 0) - { + public void setSize(double size) { + if (size < 0) { String message = Logging.getMessage("Geom.SizeIsNegative", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/render/SurfaceText.java b/src/gov/nasa/worldwind/render/SurfaceText.java index 3b8be4d20c..c63eb9317c 100644 --- a/src/gov/nasa/worldwind/render/SurfaceText.java +++ b/src/gov/nasa/worldwind/render/SurfaceText.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import gov.nasa.worldwind.*; @@ -27,44 +26,76 @@ * @version $Id: SurfaceText.java 3092 2015-05-14 22:21:32Z tgaskins $ */ // TODO: add support for heading -public class SurfaceText extends AbstractSurfaceObject implements GeographicText, Movable, Draggable -{ - /** Default text size. */ +public class SurfaceText extends AbstractSurfaceObject implements GeographicText, Movable, Draggable { + + /** + * Default text size. + */ public final static double DEFAULT_TEXT_SIZE_IN_METERS = 1000; - /** Default font. */ + /** + * Default font. + */ public static final Font DEFAULT_FONT = Font.decode("Arial-BOLD-24"); - /** Default text color. */ + /** + * Default text color. + */ public static final Color DEFAULT_COLOR = Color.WHITE; - /** Default offset. The default offset centers the text on its geographic position both horizontally and vertically. */ + /** + * Default offset. The default offset centers the text on its geographic position both horizontally and vertically. + */ public static final Offset DEFAULT_OFFSET = new Offset(-0.5d, -0.5d, AVKey.FRACTION, AVKey.FRACTION); - /** The text to draw. */ + /** + * The text to draw. + */ protected CharSequence text; - /** Location at which to draw the text. */ + /** + * Location at which to draw the text. + */ protected Position location; - /** The height of the text in meters. */ + /** + * The height of the text in meters. + */ protected double textSizeInMeters = DEFAULT_TEXT_SIZE_IN_METERS; - /** Dragging Support */ + /** + * Dragging Support + */ protected boolean dragEnabled = true; protected DraggableSupport draggableSupport = null; - /** Font to use to draw the text. Defaults to {@link #DEFAULT_FONT}. */ + /** + * Font to use to draw the text. Defaults to {@link #DEFAULT_FONT}. + */ protected Font font = DEFAULT_FONT; - /** Color to use to draw the text. Defaults to {@link #DEFAULT_COLOR}. */ + /** + * Color to use to draw the text. Defaults to {@link #DEFAULT_COLOR}. + */ protected Color color = DEFAULT_COLOR; - /** Background color for the text. By default color will be generated to contrast with the text color. */ + /** + * Background color for the text. By default color will be generated to contrast with the text color. + */ protected Color bgColor; - /** Text priority. Can be used to implement text culling. */ + /** + * Text priority. Can be used to implement text culling. + */ protected double priority; - /** Offset that specifies where to place the text in relation to it's geographic position. */ + /** + * Offset that specifies where to place the text in relation to it's geographic position. + */ protected Offset offset = DEFAULT_OFFSET; // Computed each time text is rendered - /** Bounds of the text in pixels. */ + /** + * Bounds of the text in pixels. + */ protected Rectangle2D textBounds; - /** Geographic size of a pixel. */ + /** + * Geographic size of a pixel. + */ protected double pixelSizeInMeters; - /** Scaling factor applied to the text to maintain a constant geographic size. */ + /** + * Scaling factor applied to the text to maintain a constant geographic size. + */ protected double scale; /** @@ -80,11 +111,10 @@ public class SurfaceText extends AbstractSurfaceObject implements GeographicText /** * Create a new surface text object. * - * @param text Text to draw. + * @param text Text to draw. * @param position Geographic location at which to draw the text. */ - public SurfaceText(String text, Position position) - { + public SurfaceText(String text, Position position) { this.setText(text); this.setPosition(position); } @@ -92,30 +122,30 @@ public SurfaceText(String text, Position position) /** * Create a new surface text object. * - * @param text Text to draw. + * @param text Text to draw. * @param position Geographic location at which to draw the text. - * @param font Font to use when drawing text. - * @param color Color to use when drawing text. + * @param font Font to use when drawing text. + * @param color Color to use when drawing text. */ - public SurfaceText(String text, Position position, Font font, Color color) - { + public SurfaceText(String text, Position position, Font font, Color color) { this.setText(text); this.setPosition(position); this.setFont(font); this.setColor(color); } - /** {@inheritDoc} */ - public CharSequence getText() - { + /** + * {@inheritDoc} + */ + public CharSequence getText() { return this.text; } - /** {@inheritDoc} */ - public void setText(CharSequence text) - { - if (text == null) - { + /** + * {@inheritDoc} + */ + public void setText(CharSequence text) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -126,9 +156,10 @@ public void setText(CharSequence text) this.onShapeChanged(); } - /** {@inheritDoc} */ - public Position getPosition() - { + /** + * {@inheritDoc} + */ + public Position getPosition() { return this.location; } @@ -140,10 +171,8 @@ public Position getPosition() * * @see #setOffset(Offset) */ - public void setPosition(Position position) - { - if (position == null) - { + public void setPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -153,86 +182,88 @@ public void setPosition(Position position) this.onShapeChanged(); } - /** {@inheritDoc} */ - public Font getFont() - { + /** + * {@inheritDoc} + */ + public Font getFont() { return this.font; } - /** {@inheritDoc} */ - public void setFont(Font font) - { - if (font == null) - { + /** + * {@inheritDoc} + */ + public void setFont(Font font) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Only set the font if it is different than the active font - if (!font.equals(this.font)) - { + if (!font.equals(this.font)) { this.font = font; this.textBounds = null; // Need to recompute bounds this.onShapeChanged(); } } - /** {@inheritDoc} */ - public Color getColor() - { + /** + * {@inheritDoc} + */ + public Color getColor() { return this.color; } - /** {@inheritDoc} */ - public void setColor(Color color) - { - if (color == null) - { + /** + * {@inheritDoc} + */ + public void setColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!color.equals(this.color)) - { + if (!color.equals(this.color)) { this.color = color; this.onShapeChanged(); } } - /** {@inheritDoc} */ - public Color getBackgroundColor() - { + /** + * {@inheritDoc} + */ + public Color getBackgroundColor() { return this.bgColor; } - /** {@inheritDoc} */ - public void setBackgroundColor(Color background) - { - if (background == null) - { + /** + * {@inheritDoc} + */ + public void setBackgroundColor(Color background) { + if (background == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bgColor == null || !bgColor.equals(background)) - { + if (bgColor == null || !bgColor.equals(background)) { this.bgColor = background; this.onShapeChanged(); } } - /** {@inheritDoc} */ - public void setPriority(double priority) - { + /** + * {@inheritDoc} + */ + public void setPriority(double priority) { this.priority = priority; } - /** {@inheritDoc} */ - public double getPriority() - { + /** + * {@inheritDoc} + */ + public double getPriority() { return this.priority; } @@ -243,8 +274,7 @@ public double getPriority() * * @see #setOffset(Offset) */ - public Offset getOffset() - { + public Offset getOffset() { return this.offset; } @@ -259,100 +289,97 @@ public Offset getOffset() * * @param offset Offset that controls where to position the label relative to its geographic location. */ - public void setOffset(Offset offset) - { - if (offset == null) - { + public void setOffset(Offset offset) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!offset.equals(this.offset)) - { + if (!offset.equals(this.offset)) { this.offset = offset; this.onShapeChanged(); } } - public double getTextSize() - { + public double getTextSize() { return this.textSizeInMeters; } - public void setTextSize(double meters) - { + public void setTextSize(double meters) { this.textSizeInMeters = meters; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void preRender(DrawContext dc) - { - if (this.textBounds == null) - { + public void preRender(DrawContext dc) { + if (this.textBounds == null) { this.updateTextBounds(dc); } super.preRender(dc); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return new Position(this.location, 0); } - /** {@inheritDoc} */ - public void move(Position position) - { + /** + * {@inheritDoc} + */ + public void move(Position position) { Position refPos = this.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return; + } this.moveTo(refPos.add(position)); } - /** {@inheritDoc} */ - public void moveTo(Position position) - { + /** + * {@inheritDoc} + */ + public void moveTo(Position position) { this.setPosition(position); } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, WorldWind.CLAMP_TO_GROUND); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } - /** {@inheritDoc} */ - public java.util.List getSectors(DrawContext dc) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public java.util.List getSectors(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -361,27 +388,26 @@ public java.util.List getSectors(DrawContext dc) return Arrays.asList(this.computeSector(dc)); } - /** {@inheritDoc} */ - protected void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) - { + /** + * {@inheritDoc} + */ + protected void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushAttrib(gl, - GL2.GL_CURRENT_BIT // For current color (used by JOGL TextRenderer). + GL2.GL_CURRENT_BIT // For current color (used by JOGL TextRenderer). | GL2.GL_TRANSFORM_BIT); // For matrix mode. ogsh.pushModelview(gl); - try - { + try { this.computeGeometry(dc, sdc); - if (this.isSmall()) + if (this.isSmall()) { return; + } this.applyDrawTransform(dc, sdc); this.drawText(dc); - } - finally - { + } finally { ogsh.pop(gl); } } @@ -391,18 +417,16 @@ protected void drawGeographic(DrawContext dc, SurfaceTileDrawContext sdc) * * @param dc Current draw context. */ - protected void drawText(DrawContext dc) - { + protected void drawText(DrawContext dc) { TextRenderer tr = this.getTextRenderer(dc); Point2D point = this.getOffset().computeOffset(this.textBounds.getWidth(), this.textBounds.getHeight(), null, - null); + null); int x = (int) point.getX(); int y = (int) point.getY(); - try - { + try { tr.begin3DRendering(); Color bgColor = this.determineBackgroundColor(this.color); @@ -412,9 +436,7 @@ protected void drawText(DrawContext dc) tr.draw(text, x + 1, y - 1); tr.setColor(this.getColor()); tr.draw(text, x, y); - } - finally - { + } finally { tr.end3DRendering(); } } @@ -422,11 +444,10 @@ protected void drawText(DrawContext dc) /** * Compute the text size and position. * - * @param dc Current draw context. + * @param dc Current draw context. * @param sdc Current surface tile draw context. */ - protected void computeGeometry(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void computeGeometry(DrawContext dc, SurfaceTileDrawContext sdc) { // Determine the geographic size of a pixel in the tile this.pixelSizeInMeters = this.computePixelSize(dc, sdc); @@ -440,16 +461,15 @@ protected void computeGeometry(DrawContext dc, SurfaceTileDrawContext sdc) /** * Apply a transform to the GL state to draw the text at the proper location and scale. * - * @param dc Current draw context. + * @param dc Current draw context. * @param sdc Current surface tile draw context. */ - protected void applyDrawTransform(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void applyDrawTransform(DrawContext dc, SurfaceTileDrawContext sdc) { Vec4 point = new Vec4(this.location.getLongitude().degrees, this.location.getLatitude().degrees, 1); // If the text box spans the anti-meridian and we're drawing tiles to the right of the anti-meridian, then we // need to map the translation into coordinates relative to that side of the anti-meridian. - if (this.spansAntimeridian && - Math.signum(sdc.getSector().getMinLongitude().degrees) != Math.signum(this.drawLocation.longitude.degrees)) { + if (this.spansAntimeridian + && Math.signum(sdc.getSector().getMinLongitude().degrees) != Math.signum(this.drawLocation.longitude.degrees)) { point = new Vec4(this.location.getLongitude().degrees - 360, this.location.getLatitude().degrees, 1); } point = point.transformBy4(sdc.getModelviewMatrix()); @@ -468,21 +488,19 @@ protected void applyDrawTransform(DrawContext dc, SurfaceTileDrawContext sdc) * * @return {@code true} if the height of the text is less than one pixel. */ - protected boolean isSmall() - { + protected boolean isSmall() { return this.scale * this.textSizeInMeters < this.pixelSizeInMeters; } /** * Compute the size of a pixel in the surface tile. * - * @param dc Current draw context. + * @param dc Current draw context. * @param sdc Current surface tile draw context. * * @return The size of a tile pixel in meters. */ - protected double computePixelSize(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected double computePixelSize(DrawContext dc, SurfaceTileDrawContext sdc) { return dc.getGlobe().getRadius() * sdc.getSector().getDeltaLatRadians() / sdc.getViewport().height; } @@ -494,12 +512,12 @@ protected double computePixelSize(DrawContext dc, SurfaceTileDrawContext sdc) * * @return the user specified background color, or a default color that contrasts with the text color. */ - protected Color determineBackgroundColor(Color color) - { + protected Color determineBackgroundColor(Color color) { // If the app specified a background color, use that. Color bgColor = this.getBackgroundColor(); - if (bgColor != null) + if (bgColor != null) { return bgColor; + } // Otherwise compute a color that contrasts with the text color. return this.computeBackgroundColor(color); @@ -512,16 +530,16 @@ protected Color determineBackgroundColor(Color color) * * @return a color that contrasts with the text color. */ - protected Color computeBackgroundColor(Color color) - { + protected Color computeBackgroundColor(Color color) { // Otherwise compute a color that contrasts with the text color. float[] colorArray = new float[4]; Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), colorArray); - if (colorArray[2] > 0.5) + if (colorArray[2] > 0.5) { return new Color(0, 0, 0, 0.7f); - else + } else { return new Color(1, 1, 1, 0.7f); + } } /** @@ -531,8 +549,7 @@ protected Color computeBackgroundColor(Color color) * * @return The sector covered by the surface text. */ - protected Sector[] computeSector(DrawContext dc) - { + protected Sector[] computeSector(DrawContext dc) { // Compute text extent depending on distance from eye Globe globe = dc.getGlobe(); @@ -571,7 +588,7 @@ protected Sector[] computeSector(DrawContext dc) return sectors; } else { this.spansAntimeridian = false; - return new Sector[] {Sector.fromDegrees(minLat, maxLat, minLon, maxLon)}; + return new Sector[]{Sector.fromDegrees(minLat, maxLat, minLon, maxLon)}; } } @@ -582,8 +599,7 @@ protected Sector[] computeSector(DrawContext dc) * * @return The text renderer that will be used to draw the surface text. */ - protected TextRenderer getTextRenderer(DrawContext dc) - { + protected TextRenderer getTextRenderer(DrawContext dc) { return OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), this.getFont(), true, false, false); } @@ -592,8 +608,7 @@ protected TextRenderer getTextRenderer(DrawContext dc) * * @param dc Current draw context. */ - protected void updateTextBounds(DrawContext dc) - { + protected void updateTextBounds(DrawContext dc) { this.textBounds = this.getTextRenderer(dc).getBounds(this.text); } } diff --git a/src/gov/nasa/worldwind/render/SurfaceTile.java b/src/gov/nasa/worldwind/render/SurfaceTile.java index 5cc637adc2..9c26a7765a 100644 --- a/src/gov/nasa/worldwind/render/SurfaceTile.java +++ b/src/gov/nasa/worldwind/render/SurfaceTile.java @@ -13,11 +13,15 @@ * @author tag * @version $Id: SurfaceTile.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface SurfaceTile -{ +public interface SurfaceTile { + boolean bind(DrawContext dc); + void applyInternalTransform(DrawContext dc, boolean textureIdentityActive); + Sector getSector(); + Extent getExtent(DrawContext dc); + List getCorners(); } diff --git a/src/gov/nasa/worldwind/render/SurfaceTileRenderer.java b/src/gov/nasa/worldwind/render/SurfaceTileRenderer.java index da4aaf1a78..23f315445c 100644 --- a/src/gov/nasa/worldwind/render/SurfaceTileRenderer.java +++ b/src/gov/nasa/worldwind/render/SurfaceTileRenderer.java @@ -20,8 +20,8 @@ * @author tag * @version $Id: SurfaceTileRenderer.java 2288 2014-08-30 20:24:56Z dcollins $ */ -public abstract class SurfaceTileRenderer implements Disposable -{ +public abstract class SurfaceTileRenderer implements Disposable { + private static final int DEFAULT_ALPHA_TEXTURE_SIZE = 1024; protected Texture alphaTexture; @@ -35,29 +35,29 @@ public abstract class SurfaceTileRenderer implements Disposable * * @throws com.jogamp.opengl.GLException - If an OpenGL context is not current when this method is called. */ - public void dispose() - { + public void dispose() { GLContext context = GLContext.getCurrent(); - if (context == null || context.getGL() == null) + if (context == null || context.getGL() == null) { return; + } GL gl = context.getGL(); - if (this.alphaTexture != null) + if (this.alphaTexture != null) { this.alphaTexture.destroy(gl); + } this.alphaTexture = null; - if (this.outlineTexture != null) + if (this.outlineTexture != null) { this.outlineTexture.destroy(gl); + } this.outlineTexture = null; } - public boolean isShowImageTileOutlines() - { + public boolean isShowImageTileOutlines() { return showImageTileOutlines; } - public void setShowImageTileOutlines(boolean showImageTileOutlines) - { + public void setShowImageTileOutlines(boolean showImageTileOutlines) { this.showImageTileOutlines = showImageTileOutlines; } @@ -67,10 +67,9 @@ public void setShowImageTileOutlines(boolean showImageTileOutlines) * Initially false. * * @return true if image tile RGB colors are drawn during picking, false if image tile RGB colors are replaced by - * the current RGB color. + * the current RGB color. */ - public boolean isUseImageTilePickColors() - { + public boolean isUseImageTilePickColors() { return this.useImageTilePickColors; } @@ -79,17 +78,14 @@ public boolean isUseImageTilePickColors() * colors are drawn during picking. When false, image tile RGB colors are replaced with the current RGB color. * * @param useImageTilePickColors true if image tile RGB colors should be drawn during picking, false if image tile - * RGB colors should be replaced by the current RGB color. + * RGB colors should be replaced by the current RGB color. */ - public void setUseImageTilePickColors(boolean useImageTilePickColors) - { + public void setUseImageTilePickColors(boolean useImageTilePickColors) { this.useImageTilePickColors = useImageTilePickColors; } - public void renderTile(DrawContext dc, SurfaceTile tile) - { - if (tile == null) - { + public void renderTile(DrawContext dc, SurfaceTile tile) { + if (tile == null) { String message = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -101,8 +97,8 @@ public void renderTile(DrawContext dc, SurfaceTile tile) al.clear(); } - protected static class Transform - { + protected static class Transform { + double HScale; double VScale; double HShift; @@ -115,19 +111,16 @@ protected static class Transform abstract protected void computeTextureTransform(DrawContext dc, SurfaceTile tile, Transform t); abstract protected Iterable getIntersectingTiles(DrawContext dc, SectorGeometry sg, - Iterable tiles); + Iterable tiles); - public void renderTiles(DrawContext dc, Iterable tiles) - { - if (tiles == null) - { + public void renderTiles(DrawContext dc, Iterable tiles) { + if (tiles == null) { String message = Logging.getMessage("nullValue.TileIterableIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -138,22 +131,21 @@ public void renderTiles(DrawContext dc, Iterable tiles) boolean showOutlines = this.showImageTileOutlines && dc.getGLRuntimeCapabilities().getNumTextureUnits() > 2; gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT // for alpha func - | GL2.GL_ENABLE_BIT - | GL2.GL_CURRENT_BIT - | GL2.GL_DEPTH_BUFFER_BIT // for depth func - | GL2.GL_TRANSFORM_BIT); + | GL2.GL_ENABLE_BIT + | GL2.GL_CURRENT_BIT + | GL2.GL_DEPTH_BUFFER_BIT // for depth func + | GL2.GL_TRANSFORM_BIT); - try - { + try { this.alphaTexture = dc.getTextureCache().getTexture(this); - if (this.alphaTexture == null) - { + if (this.alphaTexture == null) { this.initAlphaTexture(dc, DEFAULT_ALPHA_TEXTURE_SIZE); // TODO: choose size to match incoming tile size? dc.getTextureCache().put(this, this.alphaTexture); } - if (showOutlines && this.outlineTexture == null) + if (showOutlines && this.outlineTexture == null) { this.initOutlineTexture(dc, 128); + } gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(GL.GL_LEQUAL); @@ -168,12 +160,10 @@ public void renderTiles(DrawContext dc, Iterable tiles) if (!dc.isPickingMode()) // treat texture as an image; modulate RGBA with the current color { gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_MODULATE); - } - else if (this.useImageTilePickColors) // treat texture as pick colors; use texture RGBA directly + } else if (this.useImageTilePickColors) // treat texture as pick colors; use texture RGBA directly { gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_REPLACE); - } - else // treat texture as a pick mask; replace RGB with the current pick color + } else // treat texture as a pick mask; replace RGB with the current pick color { gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_COMBINE); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, GL2.GL_PREVIOUS); @@ -181,8 +171,7 @@ public void renderTiles(DrawContext dc, Iterable tiles) } int numTexUnitsUsed = 2; - if (showOutlines) - { + if (showOutlines) { numTexUnitsUsed = 3; alphaTextureUnit = GL.GL_TEXTURE2; gl.glActiveTexture(GL.GL_TEXTURE1); @@ -203,11 +192,11 @@ public void renderTiles(DrawContext dc, Iterable tiles) // For each current geometry tile, find the intersecting image tiles and render the geometry // tile once for each intersecting image tile. Transform transform = new Transform(); - for (SectorGeometry sg : dc.getSurfaceGeometry()) - { + for (SectorGeometry sg : dc.getSurfaceGeometry()) { Iterable tilesToRender = this.getIntersectingTiles(dc, sg, tiles); - if (tilesToRender == null) + if (tilesToRender == null) { continue; + } sg.beginRendering(dc, numTexUnitsUsed); // TODO: wrap in try/catch in case of exception @@ -219,12 +208,10 @@ public void renderTiles(DrawContext dc, Iterable tiles) // frame buffer where the image tile does not overlap the geometry tile. Render both the image and // alpha textures via multi-texture rendering. // TODO: Figure out how to apply multi-texture to more than one tile at a time. Use fragment shader? - for (SurfaceTile tile : tilesToRender) - { + for (SurfaceTile tile : tilesToRender) { gl.glActiveTexture(GL.GL_TEXTURE0); - if (tile.bind(dc)) - { + if (tile.bind(dc)) { gl.glMatrixMode(GL2.GL_TEXTURE); gl.glLoadIdentity(); tile.applyInternalTransform(dc, true); @@ -234,8 +221,7 @@ public void renderTiles(DrawContext dc, Iterable tiles) gl.glScaled(transform.HScale, transform.VScale, 1d); gl.glTranslated(transform.HShift, transform.VShift, 0d); - if (showOutlines) - { + if (showOutlines) { gl.glActiveTexture(GL.GL_TEXTURE1); this.outlineTexture.bind(gl); @@ -265,14 +251,10 @@ public void renderTiles(DrawContext dc, Iterable tiles) sg.endRendering(dc); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, - Logging.getMessage("generic.ExceptionWhileRenderingLayer", this.getClass().getName()), e); - } - finally - { + Logging.getMessage("generic.ExceptionWhileRenderingLayer", this.getClass().getName()), e); + } finally { dc.getSurfaceGeometry().endRendering(dc); gl.glActiveTexture(alphaTextureUnit); @@ -280,8 +262,7 @@ public void renderTiles(DrawContext dc, Iterable tiles) gl.glPopMatrix(); gl.glDisable(GL.GL_TEXTURE_2D); - if (showOutlines) - { + if (showOutlines) { gl.glActiveTexture(GL.GL_TEXTURE1); gl.glMatrixMode(GL2.GL_TEXTURE); gl.glPopMatrix(); @@ -294,8 +275,7 @@ public void renderTiles(DrawContext dc, Iterable tiles) gl.glDisable(GL.GL_TEXTURE_2D); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, OGLUtil.DEFAULT_TEX_ENV_MODE); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, OGLUtil.DEFAULT_SRC0_RGB); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_COMBINE_RGB, OGLUtil.DEFAULT_COMBINE_RGB); } @@ -304,23 +284,20 @@ public void renderTiles(DrawContext dc, Iterable tiles) } } - private static void fillByteBuffer(ByteBuffer buffer, byte value) - { - for (int i = 0; i < buffer.capacity(); i++) - { + private static void fillByteBuffer(ByteBuffer buffer, byte value) { + for (int i = 0; i < buffer.capacity(); i++) { buffer.put(value); } } - protected void initAlphaTexture(DrawContext dc, int size) - { + protected void initAlphaTexture(DrawContext dc, int size) { ByteBuffer textureBytes = Buffers.newDirectByteBuffer(size * size); fillByteBuffer(textureBytes, (byte) 0xff); GL gl = dc.getGL(); TextureData textureData = new TextureData(gl.getGLProfile(), GL.GL_ALPHA, size, size, 0, GL.GL_ALPHA, - GL.GL_UNSIGNED_BYTE, false, false, false, textureBytes.rewind(), null); + GL.GL_UNSIGNED_BYTE, false, false, false, textureBytes.rewind(), null); this.alphaTexture = TextureIO.newTexture(textureData); this.alphaTexture.bind(gl); @@ -331,18 +308,16 @@ protected void initAlphaTexture(DrawContext dc, int size) // Assume the default border color of (0, 0, 0, 0). } - protected void initOutlineTexture(DrawContext dc, int size) - { + protected void initOutlineTexture(DrawContext dc, int size) { ByteBuffer textureBytes = Buffers.newDirectByteBuffer(size * size); - for (int row = 0; row < size; row++) - { - for (int col = 0; col < size; col++) - { + for (int row = 0; row < size; row++) { + for (int col = 0; col < size; col++) { byte p; - if (row == 0 || col == 0 || row == size - 1 || col == size - 1) + if (row == 0 || col == 0 || row == size - 1 || col == size - 1) { p = (byte) 0xff; - else + } else { p = (byte) 0; + } textureBytes.put(row * size + col, p); } } @@ -350,7 +325,7 @@ protected void initOutlineTexture(DrawContext dc, int size) GL gl = dc.getGL(); TextureData textureData = new TextureData(gl.getGLProfile(), GL.GL_LUMINANCE, size, size, 0, GL.GL_LUMINANCE, - GL.GL_UNSIGNED_BYTE, false, false, false, textureBytes.rewind(), null); + GL.GL_UNSIGNED_BYTE, false, false, false, textureBytes.rewind(), null); this.outlineTexture = TextureIO.newTexture(textureData); this.outlineTexture.bind(gl); diff --git a/src/gov/nasa/worldwind/render/TextRenderer.java b/src/gov/nasa/worldwind/render/TextRenderer.java index c04a654333..47ee2e92f6 100644 --- a/src/gov/nasa/worldwind/render/TextRenderer.java +++ b/src/gov/nasa/worldwind/render/TextRenderer.java @@ -3,7 +3,7 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ -/* + /* * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. * @@ -45,7 +45,6 @@ /** * @version $Id: TextRenderer.java 2387 2014-10-15 20:25:02Z tgaskins $ */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -69,62 +68,55 @@ import java.util.List; // For debugging purposes - - -/** Renders bitmapped Java 2D text into an OpenGL window with high - performance, full Unicode support, and a simple API. Performs - appropriate caching of text rendering results in an OpenGL texture - internally to avoid repeated font rasterization. The caching is - completely automatic, does not require any user intervention, and - has no visible controls in the public API.

          - - Using the {@link TextRenderer TextRenderer} is simple. Add a - "TextRenderer renderer;" field to your {@link - com.jogamp.opengl.GLEventListener GLEventListener}. In your {@link - com.jogamp.opengl.GLEventListener#init init} method, add: - -

          -    renderer = new TextRenderer(new Font("SansSerif", Font.BOLD, 36));
          -    
          - -

          In the {@link com.jogamp.opengl.GLEventListener#display display} method of your - {@link com.jogamp.opengl.GLEventListener GLEventListener}, add: -

          -    renderer.beginRendering(drawable.getWidth(), drawable.getHeight());
          -    // optionally set the color
          -    renderer.setColor(1.0f, 0.2f, 0.2f, 0.8f);
          -    renderer.draw("Text to draw", xPosition, yPosition);
          -    // ... more draw commands, color changes, etc.
          -    renderer.endRendering();
          -    
          - - Unless you are sharing textures and display lists between OpenGL - contexts, you do not need to call the {@link #dispose dispose} - method of the TextRenderer; the OpenGL resources it uses - internally will be cleaned up automatically when the OpenGL - context is destroyed.

          - - Note that the TextRenderer may cause the vertex and texture - coordinate array buffer bindings to change, or to be unbound. This - is important to note if you are using Vertex Buffer Objects (VBOs) - in your application.

          - - Internally, the renderer uses a rectangle packing algorithm to - pack both glyphs and full Strings' rendering results (which are - variable size) onto a larger OpenGL texture. The internal backing - store is maintained using a {@link - com.jogamp.opengl.util.awt.TextureRenderer TextureRenderer}. A least - recently used (LRU) algorithm is used to discard previously - rendered strings; the specific algorithm is undefined, but is - currently implemented by flushing unused Strings' rendering - results every few hundred rendering cycles, where a rendering - cycle is defined as a pair of calls to {@link #beginRendering - beginRendering} / {@link #endRendering endRendering}. - - @author John Burkey - @author Kenneth Russell -*/ +/** + * Renders bitmapped Java 2D text into an OpenGL window with high performance, full Unicode support, and a simple API. + * Performs appropriate caching of text rendering results in an OpenGL texture internally to avoid repeated font + * rasterization. The caching is completely automatic, does not require any user intervention, and has no visible + * controls in the public API. + *

          + * + Using the {@link TextRenderer TextRenderer} is simple. Add a "TextRenderer renderer;" field to your {@link + * com.jogamp.opengl.GLEventListener GLEventListener}. In your {@link + * com.jogamp.opengl.GLEventListener#init init} method, add: + * + *

          + * renderer = new TextRenderer(new Font("SansSerif", Font.BOLD, 36));
          + * 
          + * + *

          + * In the {@link com.jogamp.opengl.GLEventListener#display display} method of your + * {@link com.jogamp.opengl.GLEventListener GLEventListener}, add: + *

          + * renderer.beginRendering(drawable.getWidth(), drawable.getHeight());
          + * // optionally set the color
          + * renderer.setColor(1.0f, 0.2f, 0.2f, 0.8f);
          + * renderer.draw("Text to draw", xPosition, yPosition);
          + * // ... more draw commands, color changes, etc.
          + * renderer.endRendering();
          + * 
          + * + * Unless you are sharing textures and display lists between OpenGL contexts, you do not need to call the + * {@link #dispose dispose} method of the TextRenderer; the OpenGL resources it uses internally will be cleaned up + * automatically when the OpenGL context is destroyed. + *

          + * + Note that the TextRenderer may cause the vertex and texture coordinate array buffer bindings to change, or to + * be unbound. This is important to note if you are using Vertex Buffer Objects (VBOs) in your application. + *

          + * + Internally, the renderer uses a rectangle packing algorithm to pack both glyphs and full Strings' rendering results + * (which are variable size) onto a larger OpenGL texture. The internal backing store is maintained using a {@link + * com.jogamp.opengl.util.awt.TextureRenderer TextureRenderer}. A least recently used (LRU) algorithm is used to discard + * previously rendered strings; the specific algorithm is undefined, but is currently implemented by flushing unused + * Strings' rendering results every few hundred rendering cycles, where a rendering cycle is defined as a pair of calls + * to {@link #beginRendering + * beginRendering} / {@link #endRendering endRendering}. + * + * @author John Burkey + * @author Kenneth Russell + */ public class TextRenderer { + private static final boolean DEBUG; static { @@ -135,11 +127,12 @@ public class TextRenderer { // These are occasionally useful for more in-depth debugging private static boolean DISABLE_GLYPH_CACHE = false; private static final boolean DRAW_BBOXES = false; - static - { + + static { String arg = System.getProperty("gov.nasa.worldwind.textrender.useglyphcache"); - if (arg != null && arg.toLowerCase().startsWith("f")) + if (arg != null && arg.toLowerCase().startsWith("f")) { DISABLE_GLYPH_CACHE = true; + } } static final int kSize = 256; @@ -214,88 +207,78 @@ public class TextRenderer { // Whether GL_LINEAR filtering is enabled for the backing store private boolean smoothing = true; - /** Creates a new TextRenderer with the given font, using no - antialiasing or fractional metrics, and the default - RenderDelegate. Equivalent to TextRenderer(font, false, - false). - - @param font the font to render with - */ + /** + * Creates a new TextRenderer with the given font, using no antialiasing or fractional metrics, and the default + * RenderDelegate. Equivalent to TextRenderer(font, false, + * false). + * + * @param font the font to render with + */ public TextRenderer(Font font) { this(font, false, false, null, false); } - /** Creates a new TextRenderer with the given font, using no - antialiasing or fractional metrics, and the default - RenderDelegate. If mipmap is true, attempts to use - OpenGL's automatic mipmap generation for better smoothing when - rendering the TextureRenderer's contents at a distance. - Equivalent to TextRenderer(font, false, false). - - @param font the font to render with - @param mipmap whether to attempt use of automatic mipmap generation - */ + /** + * Creates a new TextRenderer with the given font, using no antialiasing or fractional metrics, and the default + * RenderDelegate. If mipmap is true, attempts to use OpenGL's automatic mipmap generation for better + * smoothing when rendering the TextureRenderer's contents at a distance. Equivalent to + * TextRenderer(font, false, false). + * + * @param font the font to render with + * @param mipmap whether to attempt use of automatic mipmap generation + */ public TextRenderer(Font font, boolean mipmap) { this(font, false, false, null, mipmap); } - /** Creates a new TextRenderer with the given Font, specified font - properties, and default RenderDelegate. The - antialiased and useFractionalMetrics - flags provide control over the same properties at the Java 2D - level. No mipmap support is requested. Equivalent to - TextRenderer(font, antialiased, useFractionalMetrics, - null). - - @param font the font to render with - @param antialiased whether to use antialiased fonts - @param useFractionalMetrics whether to use fractional font - metrics at the Java 2D level - */ + /** + * Creates a new TextRenderer with the given Font, specified font properties, and default RenderDelegate. The + * antialiased and useFractionalMetrics flags provide control over the same properties at + * the Java 2D level. No mipmap support is requested. Equivalent to + * TextRenderer(font, antialiased, useFractionalMetrics, + * null). + * + * @param font the font to render with + * @param antialiased whether to use antialiased fonts + * @param useFractionalMetrics whether to use fractional font metrics at the Java 2D level + */ public TextRenderer(Font font, boolean antialiased, - boolean useFractionalMetrics) { + boolean useFractionalMetrics) { this(font, antialiased, useFractionalMetrics, null, false); } - /** Creates a new TextRenderer with the given Font, specified font - properties, and given RenderDelegate. The - antialiased and useFractionalMetrics - flags provide control over the same properties at the Java 2D - level. The renderDelegate provides more control - over the text rendered. No mipmap support is requested. - - @param font the font to render with - @param antialiased whether to use antialiased fonts - @param useFractionalMetrics whether to use fractional font - metrics at the Java 2D level - @param renderDelegate the render delegate to use to draw the - text's bitmap, or null to use the default one - */ + /** + * Creates a new TextRenderer with the given Font, specified font properties, and given RenderDelegate. The + * antialiased and useFractionalMetrics flags provide control over the same properties at + * the Java 2D level. The renderDelegate provides more control over the text rendered. No mipmap + * support is requested. + * + * @param font the font to render with + * @param antialiased whether to use antialiased fonts + * @param useFractionalMetrics whether to use fractional font metrics at the Java 2D level + * @param renderDelegate the render delegate to use to draw the text's bitmap, or null to use the default one + */ public TextRenderer(Font font, boolean antialiased, - boolean useFractionalMetrics, RenderDelegate renderDelegate) { + boolean useFractionalMetrics, RenderDelegate renderDelegate) { this(font, antialiased, useFractionalMetrics, renderDelegate, false); } - /** Creates a new TextRenderer with the given Font, specified font - properties, and given RenderDelegate. The - antialiased and useFractionalMetrics - flags provide control over the same properties at the Java 2D - level. The renderDelegate provides more control - over the text rendered. If mipmap is true, attempts - to use OpenGL's automatic mipmap generation for better smoothing - when rendering the TextureRenderer's contents at a distance. - - @param font the font to render with - @param antialiased whether to use antialiased fonts - @param useFractionalMetrics whether to use fractional font - metrics at the Java 2D level - @param renderDelegate the render delegate to use to draw the - text's bitmap, or null to use the default one - @param mipmap whether to attempt use of automatic mipmap generation - */ + /** + * Creates a new TextRenderer with the given Font, specified font properties, and given RenderDelegate. The + * antialiased and useFractionalMetrics flags provide control over the same properties at + * the Java 2D level. The renderDelegate provides more control over the text rendered. If + * mipmap is true, attempts to use OpenGL's automatic mipmap generation for better smoothing when + * rendering the TextureRenderer's contents at a distance. + * + * @param font the font to render with + * @param antialiased whether to use antialiased fonts + * @param useFractionalMetrics whether to use fractional font metrics at the Java 2D level + * @param renderDelegate the render delegate to use to draw the text's bitmap, or null to use the default one + * @param mipmap whether to attempt use of automatic mipmap generation + */ public TextRenderer(Font font, boolean antialiased, - boolean useFractionalMetrics, RenderDelegate renderDelegate, - boolean mipmap) { + boolean useFractionalMetrics, RenderDelegate renderDelegate, + boolean mipmap) { this.font = font; this.antialiased = antialiased; this.useFractionalMetrics = useFractionalMetrics; @@ -349,13 +332,13 @@ public Rectangle2D getBounds(CharSequence str) { // Reconstitute the Java 2D results based on the cached values return new Rectangle2D.Double(-data.origin().x, -data.origin().y, - r.w(), r.h()); + r.w(), r.h()); } // Must return a Rectangle compatible with the layout algorithm -- // must be idempotent return normalize(renderDelegate.getBounds(str, font, - getFontRenderContext())); + getFontRenderContext())); } /** @@ -368,8 +351,8 @@ public Font getFont() { } /** - * * Returns a FontRenderContext which can be used for external text-related size computations.This object should be - * considered transient and may become invalidated between + * * Returns a FontRenderContext which can be used for external text-related size computations.This object should + * be considered transient and may become invalidated between * {@link #beginRendering beginRendering} / {@link #endRendering endRendering} pairs. * * @return A FontRenderContext. @@ -382,72 +365,63 @@ public FontRenderContext getFontRenderContext() { return cachedFontRenderContext; } - /** Begins rendering with this {@link TextRenderer TextRenderer} - into the current OpenGL drawable, pushing the projection and - modelview matrices and some state bits and setting up a - two-dimensional orthographic projection with (0, 0) as the - lower-left coordinate and (width, height) as the upper-right - coordinate. Binds and enables the internal OpenGL texture - object, sets the texture environment mode to GL_MODULATE, and - changes the current color to the last color set with this - TextRenderer via {@link #setColor setColor}. This method - disables the depth test and is equivalent to - beginRendering(width, height, true). - - @param width the width of the current on-screen OpenGL drawable - @param height the height of the current on-screen OpenGL drawable - @throws com.jogamp.opengl.GLException If an OpenGL context is not current when this method is called - */ + /** + * Begins rendering with this {@link TextRenderer TextRenderer} into the current OpenGL drawable, pushing the + * projection and modelview matrices and some state bits and setting up a two-dimensional orthographic projection + * with (0, 0) as the lower-left coordinate and (width, height) as the upper-right coordinate. Binds and enables the + * internal OpenGL texture object, sets the texture environment mode to GL_MODULATE, and changes the current color + * to the last color set with this TextRenderer via {@link #setColor setColor}. This method disables the depth test + * and is equivalent to beginRendering(width, height, true). + * + * @param width the width of the current on-screen OpenGL drawable + * @param height the height of the current on-screen OpenGL drawable + * @throws com.jogamp.opengl.GLException If an OpenGL context is not current when this method is called + */ public void beginRendering(int width, int height) throws GLException { beginRendering(width, height, true); } - /** Begins rendering with this {@link TextRenderer TextRenderer} - into the current OpenGL drawable, pushing the projection and - modelview matrices and some state bits and setting up a - two-dimensional orthographic projection with (0, 0) as the - lower-left coordinate and (width, height) as the upper-right - coordinate. Binds and enables the internal OpenGL texture - object, sets the texture environment mode to GL_MODULATE, and - changes the current color to the last color set with this - TextRenderer via {@link #setColor setColor}. Disables the depth - test if the disableDepthTest argument is true. - - @param width the width of the current on-screen OpenGL drawable - @param height the height of the current on-screen OpenGL drawable - @param disableDepthTest whether to disable the depth test - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Begins rendering with this {@link TextRenderer TextRenderer} into the current OpenGL drawable, pushing the + * projection and modelview matrices and some state bits and setting up a two-dimensional orthographic projection + * with (0, 0) as the lower-left coordinate and (width, height) as the upper-right coordinate. Binds and enables the + * internal OpenGL texture object, sets the texture environment mode to GL_MODULATE, and changes the current color + * to the last color set with this TextRenderer via {@link #setColor setColor}. Disables the depth test if the + * disableDepthTest argument is true. + * + * @param width the width of the current on-screen OpenGL drawable + * @param height the height of the current on-screen OpenGL drawable + * @param disableDepthTest whether to disable the depth test + * @throws GLException If an OpenGL context is not current when this method is called + */ public void beginRendering(int width, int height, boolean disableDepthTest) - throws GLException { + throws GLException { beginRendering(true, width, height, disableDepthTest); } - /** Begins rendering of 2D text in 3D with this {@link TextRenderer - TextRenderer} into the current OpenGL drawable. Assumes the end - user is responsible for setting up the modelview and projection - matrices, and will render text using the {@link #draw3D draw3D} - method. This method pushes some OpenGL state bits, binds and - enables the internal OpenGL texture object, sets the texture - environment mode to GL_MODULATE, and changes the current color - to the last color set with this TextRenderer via {@link - #setColor setColor}. - - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Begins rendering of 2D text in 3D with this {@link TextRenderer + * TextRenderer} into the current OpenGL drawable. Assumes the end user is responsible for setting up the modelview + * and projection matrices, and will render text using the {@link #draw3D draw3D} method. This method pushes some + * OpenGL state bits, binds and enables the internal OpenGL texture object, sets the texture environment mode to + * GL_MODULATE, and changes the current color to the last color set with this TextRenderer via {@link + * #setColor setColor}. + * + * @throws GLException If an OpenGL context is not current when this method is called + */ public void begin3DRendering() throws GLException { beginRendering(false, 0, 0, false); } - /** Changes the current color of this TextRenderer to the supplied - one. The default color is opaque white. - - @param color the new color to use for rendering text - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Changes the current color of this TextRenderer to the supplied one. The default color is opaque white. + * + * @param color the new color to use for rendering text + * @throws GLException If an OpenGL context is not current when this method is called + */ public void setColor(Color color) throws GLException { - boolean noNeedForFlush = (haveCachedColor && (cachedColor != null) && - color.equals(cachedColor)); + boolean noNeedForFlush = (haveCachedColor && (cachedColor != null) + && color.equals(cachedColor)); if (!noNeedForFlush) { flushGlyphPipeline(); @@ -458,26 +432,24 @@ public void setColor(Color color) throws GLException { cachedColor = color; } - /** Changes the current color of this TextRenderer to the supplied - one, where each component ranges from 0.0f - 1.0f. The alpha - component, if used, does not need to be premultiplied into the - color channels as described in the documentation for {@link - com.jogamp.opengl.util.texture.Texture Texture}, although - premultiplied colors are used internally. The default color is - opaque white. - - @param r the red component of the new color - @param g the green component of the new color - @param b the blue component of the new color - @param a the alpha component of the new color, 0.0f = completely - transparent, 1.0f = completely opaque - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Changes the current color of this TextRenderer to the supplied one, where each component ranges from 0.0f - 1.0f. + * The alpha component, if used, does not need to be premultiplied into the color channels as described in the + * documentation for {@link + * com.jogamp.opengl.util.texture.Texture Texture}, although premultiplied colors are used internally. The default + * color is opaque white. + * + * @param r the red component of the new color + * @param g the green component of the new color + * @param b the blue component of the new color + * @param a the alpha component of the new color, 0.0f = completely transparent, 1.0f = completely opaque + * @throws GLException If an OpenGL context is not current when this method is called + */ public void setColor(float r, float g, float b, float a) - throws GLException { - boolean noNeedForFlush = (haveCachedColor && (cachedColor == null) && - (r == cachedR) && (g == cachedG) && (b == cachedB) && - (a == cachedA)); + throws GLException { + boolean noNeedForFlush = (haveCachedColor && (cachedColor == null) + && (r == cachedR) && (g == cachedG) && (b == cachedB) + && (a == cachedA)); if (!noNeedForFlush) { flushGlyphPipeline(); @@ -492,17 +464,16 @@ public void setColor(float r, float g, float b, float a) cachedColor = null; } - /** Draws the supplied CharSequence at the desired location using - the renderer's current color. The baseline of the leftmost - character is at position (x, y) specified in OpenGL coordinates, - where the origin is at the lower-left of the drawable and the Y - coordinate increases in the upward direction. - - @param str the string to draw - @param x the x coordinate at which to draw - @param y the y coordinate at which to draw - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Draws the supplied CharSequence at the desired location using the renderer's current color. The baseline of the + * leftmost character is at position (x, y) specified in OpenGL coordinates, where the origin is at the lower-left + * of the drawable and the Y coordinate increases in the upward direction. + * + * @param str the string to draw + * @param x the x coordinate at which to draw + * @param y the y coordinate at which to draw + * @throws GLException If an OpenGL context is not current when this method is called + */ public void draw(CharSequence str, int x, int y) throws GLException { draw3D(str, x, y, 0, 1); } @@ -519,20 +490,19 @@ public void draw(String str, int x, int y) throws GLException { draw3D(str, x, y, 0, 1); } - /** Draws the supplied CharSequence at the desired 3D location using - the renderer's current color. The baseline of the leftmost - character is placed at position (x, y, z) in the current - coordinate system. - - @param str the string to draw - @param x the x coordinate at which to draw - @param y the y coordinate at which to draw - @param z the z coordinate at which to draw - @param scaleFactor a uniform scale factor applied to the width and height of the drawn rectangle - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Draws the supplied CharSequence at the desired 3D location using the renderer's current color. The baseline of + * the leftmost character is placed at position (x, y, z) in the current coordinate system. + * + * @param str the string to draw + * @param x the x coordinate at which to draw + * @param y the y coordinate at which to draw + * @param z the z coordinate at which to draw + * @param scaleFactor a uniform scale factor applied to the width and height of the drawn rectangle + * @throws GLException If an OpenGL context is not current when this method is called + */ public void draw3D(CharSequence str, float x, float y, float z, - float scaleFactor) { + float scaleFactor) { internal_draw3D(str, x, y, z, scaleFactor); } @@ -560,41 +530,43 @@ public float getCharWidth(char inChar) { return mGlyphProducer.getGlyphPixelWidth(inChar); } - /** Causes the TextRenderer to flush any internal caches it may be - maintaining and draw its rendering results to the screen. This - should be called after each call to draw() if you are setting - OpenGL state such as the modelview matrix between calls to - draw(). */ + /** + * Causes the TextRenderer to flush any internal caches it may be maintaining and draw its rendering results to the + * screen. This should be called after each call to draw() if you are setting OpenGL state such as the modelview + * matrix between calls to draw(). + */ public void flush() { flushGlyphPipeline(); } - /** Ends a render cycle with this {@link TextRenderer TextRenderer}. - Restores the projection and modelview matrices as well as - several OpenGL state bits. Should be paired with {@link - #beginRendering beginRendering}. - - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Ends a render cycle with this {@link TextRenderer TextRenderer}. Restores the projection and modelview matrices + * as well as several OpenGL state bits. Should be paired with {@link + * #beginRendering beginRendering}. + * + * @throws GLException If an OpenGL context is not current when this method is called + */ public void endRendering() throws GLException { endRendering(true); } - /** Ends a 3D render cycle with this {@link TextRenderer TextRenderer}. - Restores several OpenGL state bits. Should be paired with {@link - #begin3DRendering begin3DRendering}. - - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Ends a 3D render cycle with this {@link TextRenderer TextRenderer}. Restores several OpenGL state bits. Should be + * paired with {@link + * #begin3DRendering begin3DRendering}. + * + * @throws GLException If an OpenGL context is not current when this method is called + */ public void end3DRendering() throws GLException { endRendering(false); } - /** Disposes of all resources this TextRenderer is using. It is not - valid to use the TextRenderer after this method is called. - - @throws GLException If an OpenGL context is not current when this method is called - */ + /** + * Disposes of all resources this TextRenderer is using. It is not valid to use the TextRenderer after this method + * is called. + * + * @throws GLException If an OpenGL context is not current when this method is called + */ public void dispose() throws GLException { packer.dispose(); packer = null; @@ -610,7 +582,6 @@ public void dispose() throws GLException { //---------------------------------------------------------------------- // Internals only below this point // - private static Rectangle2D preNormalize(Rectangle2D src) { // Need to round to integer coordinates // Also give ourselves a little slop around the reported @@ -623,7 +594,6 @@ private static Rectangle2D preNormalize(Rectangle2D src) { return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY); } - private Rectangle2D normalize(Rectangle2D src) { // Give ourselves a boundary around each entity on the backing // store in order to prevent bleeding of nearby Strings due to @@ -635,9 +605,9 @@ private Rectangle2D normalize(Rectangle2D src) { int boundary = (int) Math.max(1, 0.015 * font.getSize()); return new Rectangle2D.Double((int) Math.floor(src.getMinX() - boundary), - (int) Math.floor(src.getMinY() - boundary), - (int) Math.ceil(src.getWidth() + 2 * boundary), - (int) Math.ceil(src.getHeight()) + 2 * boundary); + (int) Math.floor(src.getMinY() - boundary), + (int) Math.ceil(src.getWidth() + 2 * boundary), + (int) Math.ceil(src.getHeight()) + 2 * boundary); } private TextureRenderer getBackingStore() { @@ -668,19 +638,19 @@ private Graphics2D getGraphics2D() { cachedGraphics.setColor(Color.WHITE); cachedGraphics.setFont(font); cachedGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, - (antialiased ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON - : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)); + (antialiased ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON + : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)); cachedGraphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, - (useFractionalMetrics - ? RenderingHints.VALUE_FRACTIONALMETRICS_ON - : RenderingHints.VALUE_FRACTIONALMETRICS_OFF)); + (useFractionalMetrics + ? RenderingHints.VALUE_FRACTIONALMETRICS_ON + : RenderingHints.VALUE_FRACTIONALMETRICS_OFF)); } return cachedGraphics; } private void beginRendering(boolean ortho, int width, int height, - boolean disableDepthTestForOrtho) { + boolean disableDepthTestForOrtho) { GL2 gl = GLContext.getCurrentGL().getGL2(); if (DEBUG && !debugged) { @@ -695,7 +665,7 @@ private void beginRendering(boolean ortho, int width, int height, if (ortho) { getBackingStore().beginOrthoRendering(width, height, - disableDepthTestForOrtho); + disableDepthTestForOrtho); } else { getBackingStore().begin3DRendering(); } @@ -734,8 +704,8 @@ private void beginRendering(boolean ortho, int width, int height, } /** - * emzic: here the call to glBindBuffer crashes on certain graphicscard/driver combinations - * this is why the ugly try-catch block has been added, which falls back to the old textrenderer + * emzic: here the call to glBindBuffer crashes on certain graphicscard/driver combinations this is why the ugly + * try-catch block has been added, which falls back to the old textrenderer * * @param ortho * @throws GLException @@ -784,17 +754,17 @@ private void clearUnusedEntries() { // Iterate through the contents of the backing store, removing // text strings that haven't been used recently packer.visit(new RectVisitor() { - @Override - public void visit(Rect rect) { - TextData data = (TextData) rect.getUserData(); + @Override + public void visit(Rect rect) { + TextData data = (TextData) rect.getUserData(); - if (data.used()) { - data.clearUsed(); - } else { - deadRects.add(rect); - } + if (data.used()) { + data.clearUsed(); + } else { + deadRects.add(rect); } - }); + } + }); for (Rect r : deadRects) { packer.remove(r); @@ -820,8 +790,8 @@ public void visit(Rect rect) { if (!deadRects.isEmpty() && (frag > MAX_VERTICAL_FRAGMENTATION)) { if (DEBUG) { System.err.println( - "Compacting TextRenderer backing store due to vertical fragmentation " + - frag); + "Compacting TextRenderer backing store due to vertical fragmentation " + + frag); } packer.compact(); @@ -829,12 +799,12 @@ public void visit(Rect rect) { if (DEBUG) { getBackingStore().markDirty(0, 0, getBackingStore().getWidth(), - getBackingStore().getHeight()); + getBackingStore().getHeight()); } } private void internal_draw3D(CharSequence str, float x, float y, float z, - float scaleFactor) { + float scaleFactor) { for (Glyph glyph : mGlyphProducer.getGlyphs(str)) { float advance = glyph.draw3D(x, y, z, scaleFactor); x += advance * scaleFactor; @@ -848,7 +818,7 @@ private void flushGlyphPipeline() { } private void draw3D_ROBUST(CharSequence str, float x, float y, float z, - float scaleFactor) { + float scaleFactor) { String curStr; if (str instanceof String) { curStr = (String) str; @@ -865,10 +835,10 @@ private void draw3D_ROBUST(CharSequence str, float x, float y, float z, Rectangle2D origBBox = preNormalize(renderDelegate.getBounds(curStr, font, getFontRenderContext())); Rectangle2D bbox = normalize(origBBox); Point origin = new Point((int) -bbox.getMinX(), - (int) -bbox.getMinY()); + (int) -bbox.getMinY()); rect = new Rect(0, 0, (int) bbox.getWidth(), - (int) bbox.getHeight(), - new TextData(curStr, origin, origBBox, -1)); + (int) bbox.getHeight(), + new TextData(curStr, origin, origBBox, -1)); packer.add(rect); stringLocations.put(curStr, rect); @@ -894,18 +864,18 @@ private void draw3D_ROBUST(CharSequence str, float x, float y, float z, TextData data = (TextData) rect.getUserData(); // Draw a bounding box on the backing store g.drawRect(strx - data.origOriginX(), - stry - data.origOriginY(), - (int) data.origRect().getWidth(), - (int) data.origRect().getHeight()); + stry - data.origOriginY(), + (int) data.origRect().getWidth(), + (int) data.origRect().getHeight()); g.drawRect(strx - data.origin().x, - stry - data.origin().y, - rect.w(), - rect.h()); + stry - data.origin().y, + rect.w(), + rect.h()); } // Mark this region of the TextureRenderer as dirty getBackingStore().markDirty(rect.x(), rect.y(), rect.w(), - rect.h()); + rect.h()); } // OK, now draw the portion of the backing store to the screen @@ -921,11 +891,11 @@ private void draw3D_ROBUST(CharSequence str, float x, float y, float z, // Align the leftmost point of the baseline to the (x, y, z) coordinate requested renderer.draw3DRect(x - (scaleFactor * data.origOriginX()), - y - (scaleFactor * ((float) origRect.getHeight() - data.origOriginY())), z, - rect.x() + (data.origin().x - data.origOriginX()), - renderer.getHeight() - rect.y() - (int) origRect.getHeight() - - (data.origin().y - data.origOriginY()), - (int) origRect.getWidth(), (int) origRect.getHeight(), scaleFactor); + y - (scaleFactor * ((float) origRect.getHeight() - data.origOriginY())), z, + rect.x() + (data.origin().x - data.origOriginX()), + renderer.getHeight() - rect.y() - (int) origRect.getHeight() + - (data.origin().y - data.origOriginY()), + (int) origRect.getWidth(), (int) origRect.getHeight(), scaleFactor); } //---------------------------------------------------------------------- @@ -941,35 +911,34 @@ private void debug(GL gl) { final FPSAnimator anim = new FPSAnimator(dbgCanvas, 10); dbgFrame.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - // Run this on another thread than the AWT event queue to - // make sure the call to Animator.stop() completes before - // exiting - new Thread(new Runnable() { - @Override - public void run() { - anim.stop(); - } - }).start(); - } - }); + @Override + public void windowClosing(WindowEvent e) { + // Run this on another thread than the AWT event queue to + // make sure the call to Animator.stop() completes before + // exiting + new Thread(new Runnable() { + @Override + public void run() { + anim.stop(); + } + }).start(); + } + }); dbgFrame.setSize(kSize, kSize); dbgFrame.setVisible(true); anim.start(); debugged = true; } - /** Class supporting more full control over the process of rendering - the bitmapped text. Allows customization of whether the backing - store text bitmap is full-color or intensity only, the size of - each individual rendered text rectangle, and the contents of - each individual rendered text string. The default implementation - of this interface uses an intensity-only texture, a - closely-cropped rectangle around the text, and renders text - using the color white, which is modulated by the set color - during the rendering process. */ + /** + * Class supporting more full control over the process of rendering the bitmapped text. Allows customization of + * whether the backing store text bitmap is full-color or intensity only, the size of each individual rendered text + * rectangle, and the contents of each individual rendered text string. The default implementation of this interface + * uses an intensity-only texture, a closely-cropped rectangle around the text, and renders text using the color + * white, which is modulated by the set color during the rendering process. + */ public static interface RenderDelegate { + /** * Indicates whether the backing store of this TextRenderer should be intensity-only (the default) or * full-color. @@ -987,7 +956,7 @@ public static interface RenderDelegate { * @return The bounds given the parameters. */ public Rectangle2D getBounds(String str, Font font, - FontRenderContext frc); + FontRenderContext frc); /** * Computes the bounds of the given character sequence relative to the origin. @@ -998,7 +967,7 @@ public Rectangle2D getBounds(String str, Font font, * @return The bounds given the parameters. */ public Rectangle2D getBounds(CharSequence str, Font font, - FontRenderContext frc); + FontRenderContext frc); /** * Computes the bounds of the given GlyphVector, already assumed to have been created for a particular Font, @@ -1041,10 +1010,11 @@ public Rectangle2D getBounds(CharSequence str, Font font, * @param y The y location. */ public void drawGlyphVector(Graphics2D graphics, GlyphVector str, - int x, int y); + int x, int y); } private static class CharSequenceIterator implements CharacterIterator { + CharSequence mSequence; int mLength; int mCurrentIndex; @@ -1136,6 +1106,7 @@ public char first() { // Data associated with each rectangle of text static class TextData { + // Back-pointer to String this TextData describes, if it // represents a String rather than a single glyph private final String str; @@ -1204,6 +1175,7 @@ void clearUsed() { } class Manager implements BackingStoreManager { + private Graphics2D g; @Override @@ -1222,8 +1194,8 @@ public Object allocateBackingStore(int w, int h) { renderer.setSmoothing(smoothing); if (DEBUG) { - System.err.println(" TextRenderer allocating backing store " + - w + " x " + h); + System.err.println(" TextRenderer allocating backing store " + + w + " x " + h); } return renderer; @@ -1253,8 +1225,8 @@ public boolean preExpand(Rect cause, int attemptNumber) { if (attemptNumber == 0) { if (DEBUG) { System.err.println( - "Clearing unused entries in preExpand(): attempt number " + - attemptNumber); + "Clearing unused entries in preExpand(): attempt number " + + attemptNumber); } if (inBeginEndPair) { @@ -1279,7 +1251,7 @@ public boolean additionFailed(Rect cause, int attemptNumber) { if (DEBUG) { System.err.println( - " *** Cleared all text because addition failed ***"); + " *** Cleared all text because addition failed ***"); } if (attemptNumber == 0) { @@ -1330,23 +1302,23 @@ public void beginMovement(Object oldBackingStore, Object newBackingStore) { @Override public void move(Object oldBackingStore, Rect oldLocation, - Object newBackingStore, Rect newLocation) { + Object newBackingStore, Rect newLocation) { TextureRenderer oldRenderer = (TextureRenderer) oldBackingStore; TextureRenderer newRenderer = (TextureRenderer) newBackingStore; if (oldRenderer == newRenderer) { // Movement on the same backing store -- easy case g.copyArea(oldLocation.x(), oldLocation.y(), oldLocation.w(), - oldLocation.h(), newLocation.x() - oldLocation.x(), - newLocation.y() - oldLocation.y()); + oldLocation.h(), newLocation.x() - oldLocation.x(), + newLocation.y() - oldLocation.y()); } else { // Need to draw from the old renderer's image into the new one Image img = oldRenderer.getImage(); g.drawImage(img, newLocation.x(), newLocation.y(), - newLocation.x() + newLocation.w(), - newLocation.y() + newLocation.h(), oldLocation.x(), - oldLocation.y(), oldLocation.x() + oldLocation.w(), - oldLocation.y() + oldLocation.h(), null); + newLocation.x() + newLocation.w(), + newLocation.y() + newLocation.h(), oldLocation.x(), + oldLocation.y(), oldLocation.x() + oldLocation.w(), + oldLocation.y() + oldLocation.h(), null); } } @@ -1357,13 +1329,13 @@ public void endMovement(Object oldBackingStore, Object newBackingStore) { // Sync the whole surface TextureRenderer newRenderer = (TextureRenderer) newBackingStore; newRenderer.markDirty(0, 0, newRenderer.getWidth(), - newRenderer.getHeight()); + newRenderer.getHeight()); // Re-enter the begin / end pair if necessary if (inBeginEndPair) { if (isOrthoMode) { ((TextureRenderer) newBackingStore).beginOrthoRendering(beginRenderingWidth, - beginRenderingHeight, beginRenderingDepthTestDisabled); + beginRenderingHeight, beginRenderingDepthTestDisabled); } else { ((TextureRenderer) newBackingStore).begin3DRendering(); } @@ -1375,7 +1347,7 @@ public void endMovement(Object oldBackingStore, Object newBackingStore) { if (haveCachedColor) { if (cachedColor == null) { ((TextureRenderer) newBackingStore).setColor(cachedR, - cachedG, cachedB, cachedA); + cachedG, cachedB, cachedA); } else { ((TextureRenderer) newBackingStore).setColor(cachedColor); } @@ -1387,6 +1359,7 @@ public void endMovement(Object oldBackingStore, Object newBackingStore) { } public static class DefaultRenderDelegate implements RenderDelegate { + @Override public boolean intensityOnly() { return true; @@ -1394,15 +1367,15 @@ public boolean intensityOnly() { @Override public Rectangle2D getBounds(CharSequence str, Font font, - FontRenderContext frc) { + FontRenderContext frc) { return getBounds(font.createGlyphVector(frc, - new CharSequenceIterator(str)), - frc); + new CharSequenceIterator(str)), + frc); } @Override public Rectangle2D getBounds(String str, Font font, - FontRenderContext frc) { + FontRenderContext frc) { return getBounds(font.createGlyphVector(frc, str), frc); } @@ -1413,7 +1386,7 @@ public Rectangle2D getBounds(GlyphVector gv, FontRenderContext frc) { @Override public void drawGlyphVector(Graphics2D graphics, GlyphVector str, - int x, int y) { + int x, int y) { graphics.drawGlyphVector(str, x, y); } @@ -1426,23 +1399,21 @@ public void draw(Graphics2D graphics, String str, int x, int y) { //---------------------------------------------------------------------- // Glyph-by-glyph rendering support // - // A temporary to prevent excessive garbage creation private final char[] singleUnicode = new char[1]; - /** A Glyph represents either a single unicode glyph or a - substring of characters to be drawn. The reason for the dual - behavior is so that we can take in a sequence of unicode - characters and partition them into runs of individual glyphs, - but if we encounter complex text and/or unicode sequences we - don't understand, we can render them using the - string-by-string method.

          - - Glyphs need to be able to re-upload themselves to the backing - store on demand as we go along in the render sequence. - */ - + /** + * A Glyph represents either a single unicode glyph or a substring of characters to be drawn. The reason for the + * dual behavior is so that we can take in a sequence of unicode characters and partition them into runs of + * individual glyphs, but if we encounter complex text and/or unicode sequences we don't understand, we can render + * them using the string-by-string method. + *

          + * + Glyphs need to be able to re-upload themselves to the backing store on demand as we go along in the render + * sequence. + */ class Glyph { + // If this Glyph represents an individual unicode glyph, this // is its unicode ID. If it represents a String, this is -1. private int unicodeID; @@ -1469,10 +1440,10 @@ class Glyph { // Creates a Glyph representing an individual Unicode character public Glyph(int unicodeID, - int glyphCode, - float advance, - GlyphVector singleUnicodeGlyphVector, - GlyphProducer producer) { + int glyphCode, + float advance, + GlyphVector singleUnicodeGlyphVector, + GlyphProducer producer) { this.unicodeID = unicodeID; this.glyphCode = glyphCode; this.advance = advance; @@ -1488,22 +1459,30 @@ public Glyph(String str, boolean needAdvance) { this.needAdvance = needAdvance; } - /** Returns this glyph's unicode ID */ + /** + * Returns this glyph's unicode ID + */ public int getUnicodeID() { return unicodeID; } - /** Returns this glyph's (font-specific) glyph code */ + /** + * Returns this glyph's (font-specific) glyph code + */ public int getGlyphCode() { return glyphCode; } - /** Returns the advance for this glyph */ + /** + * Returns the advance for this glyph + */ public float getAdvance() { return advance; } - /** Draws this glyph and returns the (x) advance for this glyph */ + /** + * Draws this glyph and returns the (x) advance for this glyph + */ public float draw3D(float inX, float inY, float z, float scaleFactor) { if (str != null) { draw3D_ROBUST(str, inX, inY, z, scaleFactor); @@ -1545,36 +1524,38 @@ public float draw3D(float inX, float inY, float z, float scaleFactor) { float y = inY - (scaleFactor * ((float) origRect.getHeight() - data.origOriginY())); int texturex = rect.x() + (data.origin().x - data.origOriginX()); - int texturey = renderer.getHeight() - rect.y() - (int) origRect.getHeight() - - (data.origin().y - data.origOriginY()); + int texturey = renderer.getHeight() - rect.y() - (int) origRect.getHeight() + - (data.origin().y - data.origOriginY()); int width = (int) origRect.getWidth(); int height = (int) origRect.getHeight(); float tx1 = xScale * texturex / renderer.getWidth(); - float ty1 = yScale * (1.0f - - ((float) texturey / (float) renderer.getHeight())); + float ty1 = yScale * (1.0f + - ((float) texturey / (float) renderer.getHeight())); float tx2 = xScale * (texturex + width) / renderer.getWidth(); - float ty2 = yScale * (1.0f - - ((float) (texturey + height) / (float) renderer.getHeight())); + float ty2 = yScale * (1.0f + - ((float) (texturey + height) / (float) renderer.getHeight())); mPipelinedQuadRenderer.glTexCoord2f(tx1, ty1); mPipelinedQuadRenderer.glVertex3f(x, y, z); mPipelinedQuadRenderer.glTexCoord2f(tx2, ty1); mPipelinedQuadRenderer.glVertex3f(x + (width * scaleFactor), y, - z); + z); mPipelinedQuadRenderer.glTexCoord2f(tx2, ty2); mPipelinedQuadRenderer.glVertex3f(x + (width * scaleFactor), - y + (height * scaleFactor), z); + y + (height * scaleFactor), z); mPipelinedQuadRenderer.glTexCoord2f(tx1, ty2); mPipelinedQuadRenderer.glVertex3f(x, - y + (height * scaleFactor), z); + y + (height * scaleFactor), z); } catch (Exception e) { e.printStackTrace(); } return advance; } - /** Notifies this glyph that it's been cleared out of the cache */ + /** + * Notifies this glyph that it's been cleared out of the cache + */ public void clear() { glyphRectForTextureMapping = null; } @@ -1584,10 +1565,10 @@ private void upload() { Rectangle2D origBBox = preNormalize(renderDelegate.getBounds(gv, getFontRenderContext())); Rectangle2D bbox = normalize(origBBox); Point origin = new Point((int) -bbox.getMinX(), - (int) -bbox.getMinY()); + (int) -bbox.getMinY()); Rect rect = new Rect(0, 0, (int) bbox.getWidth(), - (int) bbox.getHeight(), - new TextData(null, origin, origBBox, unicodeID)); + (int) bbox.getHeight(), + new TextData(null, origin, origBBox, unicodeID)); packer.add(rect); glyphRectForTextureMapping = rect; Graphics2D g = getGraphics2D(); @@ -1608,18 +1589,18 @@ private void upload() { TextData data = (TextData) rect.getUserData(); // Draw a bounding box on the backing store g.drawRect(strx - data.origOriginX(), - stry - data.origOriginY(), - (int) data.origRect().getWidth(), - (int) data.origRect().getHeight()); + stry - data.origOriginY(), + (int) data.origRect().getWidth(), + (int) data.origRect().getHeight()); g.drawRect(strx - data.origin().x, - stry - data.origin().y, - rect.w(), - rect.h()); + stry - data.origin().y, + rect.w(), + rect.h()); } // Mark this region of the TextureRenderer as dirty getBackingStore().markDirty(rect.x(), rect.y(), rect.w(), - rect.h()); + rect.h()); // Re-register ourselves with our producer producer.register(this); } @@ -1636,6 +1617,7 @@ private GlyphVector getGlyphVector() { } class GlyphProducer { + final int undefined = -2; FontRenderContext fontRenderContext; List glyphsOutput = new ArrayList(); @@ -1687,13 +1669,13 @@ public List getGlyphs(CharSequence inString) { // Assemble a run of characters that don't fit in // the cache StringBuilder buf = new StringBuilder(); - while (i < lengthInGlyphs && - getGlyph(inString, fullRunGlyphVector.getGlyphMetrics(i), i) == null) { + while (i < lengthInGlyphs + && getGlyph(inString, fullRunGlyphVector.getGlyphMetrics(i), i) == null) { buf.append(inString.charAt(i++)); } glyphsOutput.add(new Glyph(buf.toString(), - // Any more glyphs after this run? - i < lengthInGlyphs)); + // Any more glyphs after this run? + i < lengthInGlyphs)); } } return glyphsOutput; @@ -1731,7 +1713,7 @@ public float getGlyphPixelWidth(char unicodeID) { // Have to do this the hard / uncached way singleUnicode[0] = unicodeID; GlyphVector gv = font.createGlyphVector(fontRenderContext, - singleUnicode); + singleUnicode); return gv.getGlyphMetrics(0).getAdvance(); } @@ -1739,8 +1721,8 @@ public float getGlyphPixelWidth(char unicodeID) { // if the unicode or glyph ID would be out of bounds of the // glyph cache. private Glyph getGlyph(CharSequence inString, - GlyphMetrics glyphMetrics, - int index) { + GlyphMetrics glyphMetrics, + int index) { char unicodeID = inString.charAt(index); if (unicodeID >= unicodes2Glyphs.length) { @@ -1776,24 +1758,25 @@ private Glyph getGlyph(int unicodeID) { } private Glyph getGlyph(int unicodeID, - GlyphVector singleUnicodeGlyphVector, - GlyphMetrics metrics) { + GlyphVector singleUnicodeGlyphVector, + GlyphMetrics metrics) { int glyphCode = singleUnicodeGlyphVector.getGlyphCode(0); // Have seen huge glyph codes (65536) coming out of some fonts in some Unicode situations if (glyphCode >= glyphCache.length) { return null; } Glyph glyph = new Glyph(unicodeID, - glyphCode, - metrics.getAdvance(), - singleUnicodeGlyphVector, - this); + glyphCode, + metrics.getAdvance(), + singleUnicodeGlyphVector, + this); register(glyph); return glyph; } } private static class CharacterCache { + private CharacterCache() { } @@ -1814,6 +1797,7 @@ public static Character valueOf(char c) { } class Pipelined_QuadRenderer { + int mOutstandingGlyphsVerticesPipeline = 0; FloatBuffer mTexCoords; FloatBuffer mVertCoords; @@ -1837,14 +1821,14 @@ class Pipelined_QuadRenderer { mVBO_For_ResuableTileTexCoords = vbos[1]; gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, - mVBO_For_ResuableTileVertices); + mVBO_For_ResuableTileVertices); gl.glBufferData(GL2.GL_ARRAY_BUFFER, kTotalBufferSizeBytesVerts, - null, GL2.GL_STREAM_DRAW); // stream draw because this is a single quad use pipeline + null, GL2.GL_STREAM_DRAW); // stream draw because this is a single quad use pipeline gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, - mVBO_For_ResuableTileTexCoords); + mVBO_For_ResuableTileTexCoords); gl.glBufferData(GL2.GL_ARRAY_BUFFER, kTotalBufferSizeBytesTex, - null, GL2.GL_STREAM_DRAW); // stream draw because this is a single quad use pipeline + null, GL2.GL_STREAM_DRAW); // stream draw because this is a single quad use pipeline } catch (Exception e) { isExtensionAvailable_GL_VERSION_1_5 = false; usingVBOs = false; @@ -1891,10 +1875,10 @@ private void drawVertexArrays() { if (usingVBOs) { gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, - mVBO_For_ResuableTileVertices); + mVBO_For_ResuableTileVertices); gl.glBufferSubData(GL2.GL_ARRAY_BUFFER, 0, - mOutstandingGlyphsVerticesPipeline * kSizeInBytes_OneVertices_VertexData, - mVertCoords); // upload only the new stuff + mOutstandingGlyphsVerticesPipeline * kSizeInBytes_OneVertices_VertexData, + mVertCoords); // upload only the new stuff gl.glVertexPointer(3, GL2.GL_FLOAT, 0, 0); } else { gl.glVertexPointer(3, GL2.GL_FLOAT, 0, mVertCoords); @@ -1904,17 +1888,17 @@ private void drawVertexArrays() { if (usingVBOs) { gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, - mVBO_For_ResuableTileTexCoords); + mVBO_For_ResuableTileTexCoords); gl.glBufferSubData(GL2.GL_ARRAY_BUFFER, 0, - mOutstandingGlyphsVerticesPipeline * kSizeInBytes_OneVertices_TexData, - mTexCoords); // upload only the new stuff + mOutstandingGlyphsVerticesPipeline * kSizeInBytes_OneVertices_TexData, + mTexCoords); // upload only the new stuff gl.glTexCoordPointer(2, GL2.GL_FLOAT, 0, 0); } else { gl.glTexCoordPointer(2, GL2.GL_FLOAT, 0, mTexCoords); } gl.glDrawArrays(GL2.GL_QUADS, 0, - mOutstandingGlyphsVerticesPipeline); + mOutstandingGlyphsVerticesPipeline); mVertCoords.rewind(); mTexCoords.rewind(); @@ -1938,19 +1922,19 @@ private void drawIMMEDIATE() { for (int i = 0; i < numberOfQuads; i++) { gl.glTexCoord2f(mTexCoords.get(), mTexCoords.get()); gl.glVertex3f(mVertCoords.get(), mVertCoords.get(), - mVertCoords.get()); + mVertCoords.get()); gl.glTexCoord2f(mTexCoords.get(), mTexCoords.get()); gl.glVertex3f(mVertCoords.get(), mVertCoords.get(), - mVertCoords.get()); + mVertCoords.get()); gl.glTexCoord2f(mTexCoords.get(), mTexCoords.get()); gl.glVertex3f(mVertCoords.get(), mVertCoords.get(), - mVertCoords.get()); + mVertCoords.get()); gl.glTexCoord2f(mTexCoords.get(), mTexCoords.get()); gl.glVertex3f(mVertCoords.get(), mVertCoords.get(), - mVertCoords.get()); + mVertCoords.get()); } } catch (Exception e) { e.printStackTrace(); @@ -1965,6 +1949,7 @@ private void drawIMMEDIATE() { } class DebugListener implements GLEventListener { + private GLU glu; private Frame frame; @@ -1991,18 +1976,18 @@ public void display(GLAutoDrawable drawable) { if ((frame.getWidth() != w) || (frame.getHeight() != h)) { EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - frame.setSize(w, h); - } - }); + @Override + public void run() { + frame.setSize(w, h); + } + }); } } @Override public void dispose(GLAutoDrawable drawable) { - glu=null; - frame=null; + glu = null; + frame = null; } // Unused methods @@ -2012,11 +1997,11 @@ public void init(GLAutoDrawable drawable) { @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, - int height) { + int height) { } public void displayChanged(GLAutoDrawable drawable, - boolean modeChanged, boolean deviceChanged) { + boolean modeChanged, boolean deviceChanged) { } } @@ -2032,9 +2017,9 @@ public void setUseVertexArrays(boolean useVertexArrays) { } /** - * Indicates whether vertex arrays are being used internally for - * rendering, or whether text is rendered using the OpenGL - * immediate mode commands.Defaults to true. + * Indicates whether vertex arrays are being used internally for rendering, or whether text is rendered using the + * OpenGL immediate mode commands.Defaults to true. + * * @return whether userVertexArrays is on or off. */ public final boolean getUseVertexArrays() { diff --git a/src/gov/nasa/worldwind/render/TextRendererCache.java b/src/gov/nasa/worldwind/render/TextRendererCache.java index e2177995d7..dff4d1445c 100644 --- a/src/gov/nasa/worldwind/render/TextRendererCache.java +++ b/src/gov/nasa/worldwind/render/TextRendererCache.java @@ -14,19 +14,17 @@ * @author tag * @version $Id: TextRendererCache.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class TextRendererCache implements Disposable -{ - public static class CacheKey - { +public class TextRendererCache implements Disposable { + + public static class CacheKey { + private final java.awt.Font font; private final boolean antialiased; private final boolean useFractionalMetrics; private final boolean mipmap; - public CacheKey(java.awt.Font font, boolean antialiased, boolean useFractionalMetrics, boolean mipmap) - { - if (font == null) - { + public CacheKey(java.awt.Font font, boolean antialiased, boolean useFractionalMetrics, boolean mipmap) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -38,43 +36,39 @@ public CacheKey(java.awt.Font font, boolean antialiased, boolean useFractionalMe this.mipmap = mipmap; } - public final java.awt.Font getFont() - { + public final java.awt.Font getFont() { return this.font; } - public final boolean isAntialiased() - { + public final boolean isAntialiased() { return this.antialiased; } - public final boolean isUseFractionalMetrics() - { + public final boolean isUseFractionalMetrics() { return this.useFractionalMetrics; } - public final boolean isMipmap() - { + public final boolean isMipmap() { return this.mipmap; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } CacheKey that = (CacheKey) o; return (this.antialiased == that.antialiased) - && (this.useFractionalMetrics == that.useFractionalMetrics) - && (this.mipmap == that.mipmap) - && (this.font.equals(that.font)); + && (this.useFractionalMetrics == that.useFractionalMetrics) + && (this.mipmap == that.mipmap) + && (this.font.equals(that.font)); } - public int hashCode() - { + public int hashCode() { int result = this.font.hashCode(); result = 31 * result + (this.antialiased ? 1 : 0); result = 31 * result + (this.useFractionalMetrics ? 1 : 0); @@ -85,26 +79,21 @@ public int hashCode() protected java.util.concurrent.ConcurrentHashMap textRendererMap; - public TextRendererCache() - { + public TextRendererCache() { this.textRendererMap = new java.util.concurrent.ConcurrentHashMap(); } - public void dispose() - { + public void dispose() { this.disposeAll(); this.textRendererMap.clear(); } - public int getNumObjects() - { + public int getNumObjects() { return this.textRendererMap.size(); } - public TextRenderer get(Object key) - { - if (key == null) - { + public TextRenderer get(Object key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -113,10 +102,8 @@ public TextRenderer get(Object key) return this.textRendererMap.get(key); } - public void put(Object key, TextRenderer textRenderer) - { - if (key == null) - { + public void put(Object key, TextRenderer textRenderer) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -124,16 +111,13 @@ public void put(Object key, TextRenderer textRenderer) TextRenderer oldTextRenderer = this.textRendererMap.put(key, textRenderer); - if (oldTextRenderer != null) - { + if (oldTextRenderer != null) { this.dispose(oldTextRenderer); } } - public void remove(Object key) - { - if (key == null) - { + public void remove(Object key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -141,16 +125,13 @@ public void remove(Object key) TextRenderer textRenderer = this.textRendererMap.remove(key); - if (textRenderer != null) - { + if (textRenderer != null) { this.dispose(textRenderer); } } - public boolean contains(Object key) - { - if (key == null) - { + public boolean contains(Object key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -159,26 +140,20 @@ public boolean contains(Object key) return this.textRendererMap.containsKey(key); } - public void clear() - { + public void clear() { this.disposeAll(); this.textRendererMap.clear(); } - protected void dispose(TextRenderer textRenderer) - { - if (textRenderer != null) - { + protected void dispose(TextRenderer textRenderer) { + if (textRenderer != null) { textRenderer.dispose(); } } - protected void disposeAll() - { - for (java.util.Map.Entry e : this.textRendererMap.entrySet()) - { - if (e.getValue() != null) - { + protected void disposeAll() { + for (java.util.Map.Entry e : this.textRendererMap.entrySet()) { + if (e.getValue() != null) { this.dispose(e.getValue()); } } diff --git a/src/gov/nasa/worldwind/render/ToolTipRenderer.java b/src/gov/nasa/worldwind/render/ToolTipRenderer.java index cac626cbe4..49a88b57c7 100644 --- a/src/gov/nasa/worldwind/render/ToolTipRenderer.java +++ b/src/gov/nasa/worldwind/render/ToolTipRenderer.java @@ -16,8 +16,8 @@ * @author dcollins * @version $Id: ToolTipRenderer.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class ToolTipRenderer -{ +public class ToolTipRenderer { + private boolean useSystemLookAndFeel; private java.awt.Font font; private java.awt.Color textColor; @@ -27,10 +27,8 @@ public class ToolTipRenderer private double outlineWidth; private java.awt.Insets insets; - public ToolTipRenderer(java.awt.Font font) - { - if (font == null) - { + public ToolTipRenderer(java.awt.Font font) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -46,44 +44,36 @@ public ToolTipRenderer(java.awt.Font font) this.insets = new java.awt.Insets(1, 1, 1, 1); } - public ToolTipRenderer(boolean useSystemLookAndFeel) - { + public ToolTipRenderer(boolean useSystemLookAndFeel) { this(java.awt.Font.decode("Arial-PLAIN-12")); this.setUseSystemLookAndFeel(useSystemLookAndFeel); } - public ToolTipRenderer() - { + public ToolTipRenderer() { this(java.awt.Font.decode("Arial-PLAIN-12")); } - public static java.awt.Color getContrastingColor(java.awt.Color color) - { + public static java.awt.Color getContrastingColor(java.awt.Color color) { float[] hsbvals = new float[3]; java.awt.Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsbvals); java.awt.Color c = Color.getHSBColor(0, 0, (hsbvals[2] + 0.5f) % 1f); return new java.awt.Color(c.getRed(), c.getGreen(), c.getBlue(), color.getAlpha()); } - public boolean isUseSystemLookAndFeel() - { + public boolean isUseSystemLookAndFeel() { return this.useSystemLookAndFeel; } - public void setUseSystemLookAndFeel(boolean useSystemLookAndFeel) - { + public void setUseSystemLookAndFeel(boolean useSystemLookAndFeel) { this.useSystemLookAndFeel = useSystemLookAndFeel; } - public java.awt.Font getFont() - { + public java.awt.Font getFont() { return this.font; } - public void setFont(java.awt.Font font) - { - if (font == null) - { + public void setFont(java.awt.Font font) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -92,15 +82,12 @@ public void setFont(java.awt.Font font) this.font = font; } - public Color getTextColor() - { + public Color getTextColor() { return this.textColor; } - public void setTextColor(Color color) - { - if (color == null) - { + public void setTextColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -109,15 +96,12 @@ public void setTextColor(Color color) this.textColor = color; } - public Color getInteriorColor() - { + public Color getInteriorColor() { return this.interiorColor; } - public void setInteriorColor(Color color) - { - if (color == null) - { + public void setInteriorColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -126,15 +110,12 @@ public void setInteriorColor(Color color) this.interiorColor = color; } - public Color getOutlineColor() - { + public Color getOutlineColor() { return this.outlineColor; } - public void setOutlineColor(Color color) - { - if (color == null) - { + public void setOutlineColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -143,15 +124,12 @@ public void setOutlineColor(Color color) this.outlineColor = color; } - public double getOpacity() - { + public double getOpacity() { return this.opacity; } - public void setOpacity(double opacity) - { - if (opacity < 0 || opacity > 1) - { + public void setOpacity(double opacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "opacity < 0 or opacity > 1"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -160,15 +138,12 @@ public void setOpacity(double opacity) this.opacity = opacity; } - public double getOutlineWidth() - { + public double getOutlineWidth() { return this.outlineWidth; } - public void setOutlineWidth(double width) - { - if (width < 0) - { + public void setOutlineWidth(double width) { + if (width < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width < 0"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -177,16 +152,13 @@ public void setOutlineWidth(double width) this.outlineWidth = width; } - public java.awt.Insets getInsets() - { + public java.awt.Insets getInsets() { // Class java.awt.Insets is known to override the method Object.clone(). return (java.awt.Insets) this.insets.clone(); } - public void setInsets(java.awt.Insets insets) - { - if (insets == null) - { + public void setInsets(java.awt.Insets insets) { + if (insets == null) { String message = Logging.getMessage("nullValue.InsetsIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -196,17 +168,14 @@ public void setInsets(java.awt.Insets insets) this.insets = (java.awt.Insets) insets.clone(); } - public void render(DrawContext dc, String text, int x, int y) - { - if (dc == null) - { + public void render(DrawContext dc, String text, int x, int y) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (text == null) - { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -215,22 +184,20 @@ public void render(DrawContext dc, String text, int x, int y) this.doRender(dc, text, x, y); } - protected ToolTipAttributes getAttributes() - { + protected ToolTipAttributes getAttributes() { return new ToolTipAttributes( - this.getFont(), - this.getTextColor(), - this.getInteriorColor(), - this.getOutlineColor(), - this.getOpacity(), - this.getOpacity(), - this.getOpacity(), - this.getOutlineWidth(), - this.getInsets()); - } - - protected ToolTipAttributes getSystemLookAndFeelAttributes() - { + this.getFont(), + this.getTextColor(), + this.getInteriorColor(), + this.getOutlineColor(), + this.getOpacity(), + this.getOpacity(), + this.getOpacity(), + this.getOutlineWidth(), + this.getInsets()); + } + + protected ToolTipAttributes getSystemLookAndFeelAttributes() { Font font = UIManager.getFont("ToolTip.font"); Color textColor = UIManager.getColor("ToolTip.foreground"); Color interiorColor = UIManager.getColor("ToolTip.background"); @@ -248,61 +215,60 @@ protected ToolTipAttributes getSystemLookAndFeelAttributes() outlineWidth = ((LineBorder) border).getThickness(); } - if (border != null) + if (border != null) { insets = border.getBorderInsets(null); + } - if (font == null) + if (font == null) { font = this.getFont(); + } - if (textColor == null) + if (textColor == null) { textColor = this.getTextColor(); + } - if (interiorColor == null) + if (interiorColor == null) { interiorColor = this.getInteriorColor(); + } - if (outlineColor == null) + if (outlineColor == null) { outlineColor = this.getOutlineColor(); + } - if (insets == null) + if (insets == null) { insets = this.getInsets(); + } return new ToolTipAttributes(font, textColor, interiorColor, outlineColor, textOpacity, interiorOpacity, - outlineOpacity, outlineWidth, insets); + outlineOpacity, outlineWidth, insets); } //**************************************************************// //******************** Rendering *****************************// //**************************************************************// - - protected void doRender(DrawContext dc, String text, int x, int y) - { + protected void doRender(DrawContext dc, String text, int x, int y) { OGLStackHandler stackHandler = new OGLStackHandler(); this.beginRendering(dc, stackHandler); - try - { + try { this.draw(dc, dc.getView().getViewport(), text, x, y); - } - finally - { + } finally { this.endRendering(dc, stackHandler); } } - protected void draw(DrawContext dc, java.awt.Rectangle viewport, String text, int x, int y) - { - ToolTipAttributes attributes = this.isUseSystemLookAndFeel() ? - this.getSystemLookAndFeelAttributes() : this.getAttributes(); + protected void draw(DrawContext dc, java.awt.Rectangle viewport, String text, int x, int y) { + ToolTipAttributes attributes = this.isUseSystemLookAndFeel() + ? this.getSystemLookAndFeelAttributes() : this.getAttributes(); this.drawToolTip(dc, viewport, text, x, y, attributes); } protected void drawToolTip(DrawContext dc, java.awt.Rectangle viewport, String text, int x, int y, - ToolTipAttributes attributes) - { + ToolTipAttributes attributes) { java.awt.geom.Rectangle2D textBounds = this.computeTextBounds(dc, text, attributes.getFont()); java.awt.geom.Rectangle2D bgBounds = this.computeBackgroundBounds(dc, - textBounds.getWidth(), textBounds.getHeight(), attributes.getInsets()); + textBounds.getWidth(), textBounds.getHeight(), attributes.getInsets()); java.awt.Point screenPoint = this.adjustDrawPointToViewport(x, y, bgBounds, viewport); java.awt.geom.Point2D textTranslation = this.computeTextTranslation(dc, textBounds, attributes.getInsets()); @@ -311,25 +277,20 @@ protected void drawToolTip(DrawContext dc, java.awt.Rectangle viewport, String t OGLStackHandler stackHandler = new OGLStackHandler(); stackHandler.pushModelview(gl); - try - { + try { gl.glTranslated(screenPoint.getX() + bgBounds.getX(), screenPoint.getY() + bgBounds.getY(), 0); this.drawToolTipInterior(dc, bgBounds.getWidth(), bgBounds.getHeight(), attributes); this.drawToolTipOutline(dc, bgBounds.getWidth(), bgBounds.getHeight(), attributes); gl.glTranslated(textTranslation.getX(), textTranslation.getY(), 0); this.drawToolTipText(dc, text, 0, 0, attributes); - } - finally - { + } finally { stackHandler.pop(gl); } } - protected void beginRendering(DrawContext dc, OGLStackHandler stackHandler) - { - if (dc == null) - { + protected void beginRendering(DrawContext dc, OGLStackHandler stackHandler) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -338,10 +299,10 @@ protected void beginRendering(DrawContext dc, OGLStackHandler stackHandler) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int attribMask = GL2.GL_COLOR_BUFFER_BIT // for alpha test func and ref, blend func - | GL2.GL_CURRENT_BIT // for current color - | GL2.GL_ENABLE_BIT // for enable/disable - | GL2.GL_LINE_BIT // for line width - | GL2.GL_TRANSFORM_BIT; // for matrix mode + | GL2.GL_CURRENT_BIT // for current color + | GL2.GL_ENABLE_BIT // for enable/disable + | GL2.GL_LINE_BIT // for line width + | GL2.GL_TRANSFORM_BIT; // for matrix mode stackHandler.pushAttrib(gl, attribMask); stackHandler.pushTextureIdentity(gl); @@ -364,10 +325,8 @@ protected void beginRendering(DrawContext dc, OGLStackHandler stackHandler) gl.glDisable(GL.GL_TEXTURE_2D); } - protected void endRendering(DrawContext dc, OGLStackHandler stackHandler) - { - if (dc == null) - { + protected void endRendering(DrawContext dc, OGLStackHandler stackHandler) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -381,9 +340,7 @@ protected void endRendering(DrawContext dc, OGLStackHandler stackHandler) //**************************************************************// //******************** Background Rendering ******************// //**************************************************************// - - protected void drawToolTipInterior(DrawContext dc, double width, double height, ToolTipAttributes attributes) - { + protected void drawToolTipInterior(DrawContext dc, double width, double height, ToolTipAttributes attributes) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.applyColor(dc, attributes.getInteriorColor(), attributes.getInteriorOpacity()); @@ -392,8 +349,7 @@ protected void drawToolTipInterior(DrawContext dc, double width, double height, gl.glRectd(0, 0, width, height); } - protected void drawToolTipOutline(DrawContext dc, double width, double height, ToolTipAttributes attributes) - { + protected void drawToolTipOutline(DrawContext dc, double width, double height, ToolTipAttributes attributes) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.applyColor(dc, attributes.getOutlineColor(), attributes.getOutlineOpacity()); @@ -413,11 +369,9 @@ protected void drawToolTipOutline(DrawContext dc, double width, double height, T //**************************************************************// //******************** Text Rendering ************************// //**************************************************************// - - protected void drawToolTipText(DrawContext dc, String text, int x, int y, ToolTipAttributes attributes) - { + protected void drawToolTipText(DrawContext dc, String text, int x, int y, ToolTipAttributes attributes) { java.awt.Color textColor = this.modulateColorOpacity(attributes.getTextColor(), - attributes.getTextOpacity()); + attributes.getTextOpacity()); TextRenderer textRenderer = this.getTextRenderer(dc, attributes.getFont()); textRenderer.begin3DRendering(); @@ -429,24 +383,21 @@ protected void drawToolTipText(DrawContext dc, String text, int x, int y, ToolTi //**************************************************************// //******************** Rendering Utilities *******************// //**************************************************************// - - protected TextRenderer getTextRenderer(DrawContext dc, java.awt.Font font) - { + protected TextRenderer getTextRenderer(DrawContext dc, java.awt.Font font) { return OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); } - protected void applyColor(DrawContext dc, java.awt.Color color, double opacity) - { - if (dc.isPickingMode()) + protected void applyColor(DrawContext dc, java.awt.Color color, double opacity) { + if (dc.isPickingMode()) { return; + } double finalOpacity = opacity * (color.getAlpha() / 255.0); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLUtil.applyColor(gl, color, finalOpacity, true); } - protected java.awt.Color modulateColorOpacity(java.awt.Color color, double opacity) - { + protected java.awt.Color modulateColorOpacity(java.awt.Color color, double opacity) { float[] compArray = new float[4]; color.getRGBComponents(compArray); compArray[3] *= (float) opacity; @@ -457,48 +408,45 @@ protected java.awt.Color modulateColorOpacity(java.awt.Color color, double opaci //**************************************************************// //******************** Bounds Computation ********************// //**************************************************************// - - protected java.awt.geom.Rectangle2D computeTextBounds(DrawContext dc, String text, java.awt.Font font) - { + protected java.awt.geom.Rectangle2D computeTextBounds(DrawContext dc, String text, java.awt.Font font) { TextRenderer textRenderer = this.getTextRenderer(dc, font); return textRenderer.getBounds(text); } @SuppressWarnings({"UnusedDeclaration"}) protected java.awt.geom.Point2D computeTextTranslation(DrawContext dc, java.awt.geom.Rectangle2D textBounds, - java.awt.Insets insets) - { + java.awt.Insets insets) { // The text bounds are assumed to come from the return value of a call to TextRenderer.getBounds(). The bounds // place the origin in the upper left hand corner, with the y axis increasing downward. The y // coordinate in the bounds corresponds to the baseline of the leftmost character. return new java.awt.geom.Point2D.Double( - insets.left - textBounds.getX(), - insets.bottom + textBounds.getY() + textBounds.getHeight()); + insets.left - textBounds.getX(), + insets.bottom + textBounds.getY() + textBounds.getHeight()); } @SuppressWarnings({"UnusedDeclaration"}) protected java.awt.geom.Rectangle2D computeBackgroundBounds(DrawContext dc, double width, double height, - java.awt.Insets insets) - { + java.awt.Insets insets) { return new java.awt.geom.Rectangle2D.Double( - 0, 0, - width + (insets.left + insets.right), - height + (insets.top + insets.bottom)); + 0, 0, + width + (insets.left + insets.right), + height + (insets.top + insets.bottom)); } protected java.awt.Point adjustDrawPointToViewport(int x, int y, java.awt.geom.Rectangle2D bounds, - java.awt.Rectangle viewport) - { - if (x + bounds.getMaxX() > viewport.getWidth()) + java.awt.Rectangle viewport) { + if (x + bounds.getMaxX() > viewport.getWidth()) { x = (int) (viewport.getWidth() - bounds.getWidth()) - 1; - else if (x < 0) + } else if (x < 0) { x = 0; + } - if (y + bounds.getMaxY() > viewport.getHeight()) + if (y + bounds.getMaxY() > viewport.getHeight()) { y = (int) (viewport.getHeight() - bounds.getHeight()) - 1; - else if (y < 0) + } else if (y < 0) { y = 0; + } return new java.awt.Point(x, y); } @@ -506,9 +454,8 @@ else if (y < 0) //**************************************************************// //******************** ToolTip Attributes ********************// //**************************************************************// + protected static class ToolTipAttributes { - protected static class ToolTipAttributes - { protected java.awt.Font font; protected java.awt.Color textColor; protected java.awt.Color interiorColor; @@ -520,10 +467,9 @@ protected static class ToolTipAttributes protected java.awt.Insets insets; public ToolTipAttributes(java.awt.Font font, java.awt.Color textColor, - java.awt.Color interiorColor, java.awt.Color outlineColor, - double textOpacity, double interiorOpacity, double outlineOpacity, - double borderWidth, Insets insets) - { + java.awt.Color interiorColor, java.awt.Color outlineColor, + double textOpacity, double interiorOpacity, double outlineOpacity, + double borderWidth, Insets insets) { this.font = font; this.textColor = textColor; this.interiorColor = interiorColor; @@ -535,93 +481,75 @@ public ToolTipAttributes(java.awt.Font font, java.awt.Color textColor, this.insets = insets; } - public java.awt.Font getFont() - { + public java.awt.Font getFont() { return this.font; } - public void setFont(java.awt.Font font) - { + public void setFont(java.awt.Font font) { this.font = font; } - public java.awt.Color getTextColor() - { + public java.awt.Color getTextColor() { return this.textColor; } - public void setTextColor(java.awt.Color color) - { + public void setTextColor(java.awt.Color color) { this.textColor = color; } - public java.awt.Color getInteriorColor() - { + public java.awt.Color getInteriorColor() { return this.interiorColor; } - public void setInteriorColor(java.awt.Color color) - { + public void setInteriorColor(java.awt.Color color) { this.interiorColor = color; } - public java.awt.Color getOutlineColor() - { + public java.awt.Color getOutlineColor() { return this.outlineColor; } - public void setOutlineColor(java.awt.Color color) - { + public void setOutlineColor(java.awt.Color color) { this.outlineColor = color; } - public double getTextOpacity() - { + public double getTextOpacity() { return this.textOpacity; } - public void setTextOpacity(double textOpacity) - { + public void setTextOpacity(double textOpacity) { this.textOpacity = textOpacity; } - public double getInteriorOpacity() - { + public double getInteriorOpacity() { return this.interiorOpacity; } - public void setInteriorOpacity(double interiorOpacity) - { + public void setInteriorOpacity(double interiorOpacity) { this.interiorOpacity = interiorOpacity; } - public double getOutlineOpacity() - { + public double getOutlineOpacity() { return this.outlineOpacity; } - public void setOutlineOpacity(double outlineOpacity) - { + public void setOutlineOpacity(double outlineOpacity) { this.outlineOpacity = outlineOpacity; } - public double getBorderWidth() - { + public double getBorderWidth() { return this.borderWidth; } - public void setBorderWidth(double borderWidth) - { + public void setBorderWidth(double borderWidth) { this.borderWidth = borderWidth; } - public java.awt.Insets getInsets() - { + public java.awt.Insets getInsets() { return this.insets; } - public void setInsets(java.awt.Insets insets) - { + public void setInsets(java.awt.Insets insets) { this.insets = insets; } } diff --git a/src/gov/nasa/worldwind/render/TrackRenderer.java b/src/gov/nasa/worldwind/render/TrackRenderer.java index d0737ae66d..b0e5637a4d 100644 --- a/src/gov/nasa/worldwind/render/TrackRenderer.java +++ b/src/gov/nasa/worldwind/render/TrackRenderer.java @@ -23,8 +23,8 @@ * @author tag * @version $Id: TrackRenderer.java 1181 2013-02-15 22:27:10Z dcollins $ */ -public class TrackRenderer implements Disposable -{ +public class TrackRenderer implements Disposable { + protected int lowerLimit = 0; protected int upperLimit = Integer.MAX_VALUE; protected final Shape SPHERE = new Sphere(); @@ -41,118 +41,110 @@ public class TrackRenderer implements Disposable private Shape shape = SPHERE; private boolean keepSeparated = true; - public TrackRenderer() - { + public TrackRenderer() { } - public void dispose() - { + public void dispose() { this.CONE.dispose(); this.CYLINDER.dispose(); this.SPHERE.dispose(); } - public double getMarkerPixels() - { + public double getMarkerPixels() { return markerPixels; } - public void setMarkerPixels(double markerPixels) - { + public void setMarkerPixels(double markerPixels) { this.markerPixels = markerPixels; } - public double getMinMarkerSize() - { + public double getMinMarkerSize() { return minMarkerSize; } - public void setMinMarkerSize(double minMarkerSize) - { + public void setMinMarkerSize(double minMarkerSize) { this.minMarkerSize = minMarkerSize; } - public Material getMaterial() - { + public Material getMaterial() { return material; } - public void setMaterial(Material material) - { - if (material == null) - { + public void setMaterial(Material material) { + if (material == null) { String msg = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // don't validate material's colors - material does that. - this.material = material; } - public void setShapeType(String shapeName) - { - if (shapeName.equalsIgnoreCase("Cone")) + public void setShapeType(String shapeName) { + if (shapeName.equalsIgnoreCase("Cone")) { this.shape = CONE; - else if (shapeName.equalsIgnoreCase("Cylinder")) + } else if (shapeName.equalsIgnoreCase("Cylinder")) { this.shape = CYLINDER; - else + } else { this.shape = SPHERE; + } } - public boolean isKeepSeparated() - { + public boolean isKeepSeparated() { return keepSeparated; } - public void setKeepSeparated(boolean keepSeparated) - { + public void setKeepSeparated(boolean keepSeparated) { this.keepSeparated = keepSeparated; } - protected Vec4 draw(DrawContext dc, Iterator trackPositions) - { - if (dc.getVisibleSector() == null) + protected Vec4 draw(DrawContext dc, Iterator trackPositions) { + if (dc.getVisibleSector() == null) { return null; + } SectorGeometryList geos = dc.getSurfaceGeometry(); - if (geos == null) + if (geos == null) { return null; + } - if (!this.shape.isInitialized) + if (!this.shape.isInitialized) { this.shape.initialize(dc); + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Vec4 lastPointDrawn = null; this.begin(dc); { - if (!dc.isPickingMode()) + if (!dc.isPickingMode()) { this.material.apply(gl, GL2.GL_FRONT); + } Vec4 previousDrawnPoint = null; double radius; - for (int index = 0; trackPositions.hasNext(); index++) - { + for (int index = 0; trackPositions.hasNext(); index++) { TrackPoint tp = trackPositions.next(); - if (index < this.lowerLimit) + if (index < this.lowerLimit) { continue; + } - if (index > this.upperLimit) + if (index > this.upperLimit) { break; + } Vec4 point = this.computeSurfacePoint(dc, tp); - if (point == null) + if (point == null) { continue; + } - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { java.awt.Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); PickedObject po = new PickedObject(colorCode, - this.getClient() != null ? this.getClient() : tp.getPosition(), tp.getPosition(), false); + this.getClient() != null ? this.getClient() : tp.getPosition(), tp.getPosition(), false); po.setValue(AVKey.PICKED_OBJECT_ID, index); this.pickSupport.addPickableObject(po); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); @@ -160,8 +152,7 @@ protected Vec4 draw(DrawContext dc, Iterator trackPositions) radius = this.computeMarkerRadius(dc, point); - if (previousDrawnPoint == null) - { + if (previousDrawnPoint == null) { // It's the first point drawn previousDrawnPoint = point; this.shape.render(dc, point, radius); @@ -169,8 +160,7 @@ protected Vec4 draw(DrawContext dc, Iterator trackPositions) continue; } - if (!this.keepSeparated) - { + if (!this.keepSeparated) { previousDrawnPoint = point; this.shape.render(dc, point, radius); lastPointDrawn = point; @@ -179,8 +169,7 @@ protected Vec4 draw(DrawContext dc, Iterator trackPositions) double separation = point.distanceTo3(previousDrawnPoint); double minSeparation = 4d * radius; - if (separation > minSeparation) - { + if (separation > minSeparation) { previousDrawnPoint = point; this.shape.render(dc, point, radius); lastPointDrawn = point; @@ -192,102 +181,89 @@ protected Vec4 draw(DrawContext dc, Iterator trackPositions) return lastPointDrawn; } - private double computeMarkerRadius(DrawContext dc, Vec4 point) - { + private double computeMarkerRadius(DrawContext dc, Vec4 point) { double d = point.distanceTo3(dc.getView().getEyePoint()); double radius = this.markerPixels * dc.getView().computePixelSizeAtDistance(d); - if (radius < this.minMarkerSize) + if (radius < this.minMarkerSize) { radius = this.minMarkerSize; + } return radius; } - public int getLowerLimit() - { + public int getLowerLimit() { return this.lowerLimit; } - public void setLowerLimit(int lowerLimit) - { + public void setLowerLimit(int lowerLimit) { this.lowerLimit = lowerLimit; } - public int getUpperLimit() - { + public int getUpperLimit() { return this.upperLimit; } - public void setUpperLimit(int upperLimit) - { + public void setUpperLimit(int upperLimit) { this.upperLimit = upperLimit; } - public double getElevation() - { + public double getElevation() { return elevation; } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.elevation = elevation; } - public boolean isOverrideElevation() - { + public boolean isOverrideElevation() { return overrideMarkerElevation; } - public Object getClient() - { + public Object getClient() { return client; } - public void setClient(Object client) - { + public void setClient(Object client) { this.client = client; } - public void setOverrideElevation(boolean overrideMarkerElevation) - { + public void setOverrideElevation(boolean overrideMarkerElevation) { this.overrideMarkerElevation = overrideMarkerElevation; } - protected Vec4 computeSurfacePoint(DrawContext dc, TrackPoint tp) - { + protected Vec4 computeSurfacePoint(DrawContext dc, TrackPoint tp) { Position pos = tp.getPosition(); - if (!this.overrideMarkerElevation) + if (!this.overrideMarkerElevation) { return dc.getGlobe().computePointFromPosition(pos); + } // Compute points that are at the track-specified elevation Vec4 point = dc.getSurfaceGeometry().getSurfacePoint(pos.getLatitude(), pos.getLongitude(), this.elevation); - if (point != null) + if (point != null) { return point; + } // Point is outside the current sector geometry, so compute it from the globe. return dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), this.elevation); } - protected void begin(DrawContext dc) - { + protected void begin(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Vec4 cameraPosition = dc.getView().getEyePoint(); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.beginPicking(dc); gl.glPushAttrib(GL2.GL_ENABLE_BIT | GL2.GL_CURRENT_BIT | GL2.GL_TRANSFORM_BIT); gl.glDisable(GL.GL_TEXTURE_2D); gl.glDisable(GL2.GL_COLOR_MATERIAL); - } - else - { + } else { gl.glPushAttrib(GL2.GL_ENABLE_BIT | GL2.GL_CURRENT_BIT | GL2.GL_LIGHTING_BIT | GL2.GL_TRANSFORM_BIT); gl.glDisable(GL.GL_TEXTURE_2D); - float[] lightPosition = - {(float) (cameraPosition.x * 2), (float) (cameraPosition.y / 2), (float) (cameraPosition.z), 0.0f}; + float[] lightPosition + = {(float) (cameraPosition.x * 2), (float) (cameraPosition.y / 2), (float) (cameraPosition.z), 0.0f}; float[] lightDiffuse = {1.0f, 1.0f, 1.0f, 1.0f}; float[] lightAmbient = {1.0f, 1.0f, 1.0f, 1.0f}; float[] lightSpecular = {1.0f, 1.0f, 1.0f, 1.0f}; @@ -309,19 +285,15 @@ protected void begin(DrawContext dc) gl.glPushMatrix(); } - protected void end(DrawContext dc) - { + protected void end(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.endPicking(dc); - } - else - { + } else { gl.glDisable(GL2.GL_LIGHT1); gl.glEnable(GL2.GL_LIGHT0); gl.glDisable(GL2.GL_LIGHTING); @@ -331,8 +303,7 @@ protected void end(DrawContext dc) gl.glPopAttrib(); } - public Vec4 pick(DrawContext dc, Iterator trackPositions, java.awt.Point pickPoint, Layer layer) - { + public Vec4 pick(DrawContext dc, Iterator trackPositions, java.awt.Point pickPoint, Layer layer) { this.pickSupport.clearPickList(); Vec4 lastPointDrawn = this.draw(dc, trackPositions); this.pickSupport.resolvePick(dc, pickPoint, layer); @@ -341,13 +312,12 @@ public Vec4 pick(DrawContext dc, Iterator trackPositions, java.awt.P return lastPointDrawn; } - public Vec4 render(DrawContext dc, Iterator trackPositions) - { + public Vec4 render(DrawContext dc, Iterator trackPositions) { return this.draw(dc, trackPositions); } - protected static abstract class Shape - { + protected static abstract class Shape { + protected String name; protected int glListId; protected GLUquadric quadric; @@ -355,8 +325,7 @@ protected static abstract class Shape abstract protected void doRender(DrawContext dc, Vec4 point, double radius); - protected void initialize(DrawContext dc) - { + protected void initialize(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. GLU glu = dc.getGLU(); @@ -368,17 +337,16 @@ protected void initialize(DrawContext dc) glu.gluQuadricTexture(quadric, false); } - private void dispose() - { - if (this.isInitialized) - { + private void dispose() { + if (this.isInitialized) { GLU glu = new GLUgl2(); glu.gluDeleteQuadric(this.quadric); this.isInitialized = false; GLContext glc = GLContext.getCurrent(); - if (glc == null || glc.getGL() == null) + if (glc == null || glc.getGL() == null) { return; + } GL2 gl = glc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glDeleteLists(this.glListId, 1); @@ -387,18 +355,16 @@ private void dispose() } } - protected void render(DrawContext dc, Vec4 point, double radius) - { + protected void render(DrawContext dc, Vec4 point, double radius) { dc.getView().pushReferenceCenter(dc, point); this.doRender(dc, point, radius); dc.getView().popReferenceCenter(dc); } } - private static class Sphere extends Shape - { - protected void initialize(DrawContext dc) - { + private static class Sphere extends Shape { + + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Sphere"; @@ -416,18 +382,16 @@ protected void initialize(DrawContext dc) this.isInitialized = true; } - protected void doRender(DrawContext dc, Vec4 point, double radius) - { + protected void doRender(DrawContext dc, Vec4 point, double radius) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glScaled(radius, radius, radius); gl.glCallList(this.glListId); } } - private static class Cone extends Shape - { - protected void initialize(DrawContext dc) - { + private static class Cone extends Shape { + + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Cone"; @@ -447,8 +411,7 @@ protected void initialize(DrawContext dc) this.isInitialized = true; } - protected void doRender(DrawContext dc, Vec4 point, double size) - { + protected void doRender(DrawContext dc, Vec4 point, double size) { PolarPoint p = PolarPoint.fromCartesian(point); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -460,10 +423,9 @@ protected void doRender(DrawContext dc, Vec4 point, double size) } } - protected static class Cylinder extends Shape - { - protected void initialize(DrawContext dc) - { + protected static class Cylinder extends Shape { + + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Cylinder"; @@ -485,8 +447,7 @@ protected void initialize(DrawContext dc) this.isInitialized = true; } - protected void doRender(DrawContext dc, Vec4 point, double size) - { + protected void doRender(DrawContext dc, Vec4 point, double size) { PolarPoint p = PolarPoint.fromCartesian(point); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. diff --git a/src/gov/nasa/worldwind/render/UserFacingIcon.java b/src/gov/nasa/worldwind/render/UserFacingIcon.java index dfc858ede1..39e8af417b 100644 --- a/src/gov/nasa/worldwind/render/UserFacingIcon.java +++ b/src/gov/nasa/worldwind/render/UserFacingIcon.java @@ -18,8 +18,8 @@ * @author tag * @version $Id: UserFacingIcon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class UserFacingIcon extends AVListImpl implements WWIcon, Movable, Draggable -{ +public class UserFacingIcon extends AVListImpl implements WWIcon, Movable, Draggable { + // private final String iconPath; private Position iconPosition; // may be null because placement may be relative private Dimension iconSize; // may be null to indicate "use native image size" @@ -39,14 +39,11 @@ public class UserFacingIcon extends AVListImpl implements WWIcon, Movable, Dragg protected boolean dragEnabled = true; protected DraggableSupport draggableSupport = null; - public UserFacingIcon() - { + public UserFacingIcon() { } - public UserFacingIcon(String iconPath, Position iconPosition) - { - if (iconPath == null) - { + public UserFacingIcon(String iconPath, Position iconPosition) { + if (iconPath == null) { String message = Logging.getMessage("nullValue.IconFilePath"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -57,10 +54,8 @@ public UserFacingIcon(String iconPath, Position iconPosition) this.iconPosition = iconPosition; } - public UserFacingIcon(Object imageSource, Position iconPosition) - { - if (imageSource == null) - { + public UserFacingIcon(Object imageSource, Position iconPosition) { + if (imageSource == null) { String message = Logging.getMessage("nullValue.IconFilePath"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -71,49 +66,40 @@ public UserFacingIcon(Object imageSource, Position iconPosition) this.iconPosition = iconPosition; } - public BasicWWTexture getImageTexture() - { + public BasicWWTexture getImageTexture() { return imageTexture; } - public BasicWWTexture getBackgroundTexture() - { + public BasicWWTexture getBackgroundTexture() { return backgroundTexture; } - public Object getImageSource() - { + public Object getImageSource() { return this.getImageTexture() != null ? this.getImageTexture().getImageSource() : null; } - public void setImageSource(Object imageSource) - { + public void setImageSource(Object imageSource) { this.imageTexture = new BasicWWTexture(imageSource, true); this.imageTexture.setUseAnisotropy(false); } - public String getPath() - { + public String getPath() { return this.getImageSource() instanceof String ? (String) this.getImageSource() : null; } - public Position getPosition() - { + public Position getPosition() { return this.iconPosition; } - public void setPosition(Position iconPosition) - { + public void setPosition(Position iconPosition) { this.iconPosition = iconPosition; } - public boolean isHighlighted() - { + public boolean isHighlighted() { return isHighlighted; } - public void setHighlighted(boolean highlighted) - { + public void setHighlighted(boolean highlighted) { isHighlighted = highlighted; } @@ -122,126 +108,101 @@ public void setHighlighted(boolean highlighted) * * @return the icon's highlight scale. The default scale is 1.2. */ - public double getHighlightScale() - { + public double getHighlightScale() { return highlightScale; } - public void setHighlightScale(double highlightScale) - { + public void setHighlightScale(double highlightScale) { this.highlightScale = highlightScale; } - public Dimension getSize() - { + public Dimension getSize() { return this.iconSize; } - public void setSize(Dimension size) - { + public void setSize(Dimension size) { this.iconSize = size; } - public boolean isVisible() - { + public boolean isVisible() { return isVisible; } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { isVisible = visible; } - public String getToolTipText() - { + public String getToolTipText() { return toolTipText; } - public void setToolTipText(String toolTipText) - { + public void setToolTipText(String toolTipText) { this.toolTipText = toolTipText; } - public Font getToolTipFont() - { + public Font getToolTipFont() { return toolTipFont; } - public void setToolTipFont(Font toolTipFont) - { + public void setToolTipFont(Font toolTipFont) { this.toolTipFont = toolTipFont; } - public Vec4 getToolTipOffset() - { + public Vec4 getToolTipOffset() { return toolTipOffset; } - public void setToolTipOffset(Vec4 toolTipOffset) - { + public void setToolTipOffset(Vec4 toolTipOffset) { this.toolTipOffset = toolTipOffset; } - public boolean isShowToolTip() - { + public boolean isShowToolTip() { return showToolTip; } - public void setShowToolTip(boolean showToolTip) - { + public void setShowToolTip(boolean showToolTip) { this.showToolTip = showToolTip; } - public Color getToolTipTextColor() - { + public Color getToolTipTextColor() { return textColor; } - public void setToolTipTextColor(Color textColor) - { + public void setToolTipTextColor(Color textColor) { this.textColor = textColor; } - public boolean isAlwaysOnTop() - { + public boolean isAlwaysOnTop() { return alwaysOnTop; } - public void setAlwaysOnTop(boolean alwaysOnTop) - { + public void setAlwaysOnTop(boolean alwaysOnTop) { this.alwaysOnTop = alwaysOnTop; } - public Object getBackgroundImage() - { + public Object getBackgroundImage() { return this.getBackgroundTexture() != null ? this.getBackgroundTexture().getImageSource() : null; } - public void setBackgroundImage(Object background) - { - if (background != null) - { + public void setBackgroundImage(Object background) { + if (background != null) { this.backgroundTexture = new BasicWWTexture(background, true); this.backgroundTexture.setUseAnisotropy(false); - } - else + } else { this.backgroundTexture = null; + } } - public double getBackgroundScale() - { + public double getBackgroundScale() { return backgroundScale; } - public void setBackgroundScale(double backgroundScale) - { + public void setBackgroundScale(double backgroundScale) { this.backgroundScale = backgroundScale; } - public void move(Position position) - { - if (position == null) - { + public void move(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -250,10 +211,8 @@ public void move(Position position) this.iconPosition = this.iconPosition.add(position); } - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -262,42 +221,38 @@ public void moveTo(Position position) this.iconPosition = position; } - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.iconPosition; } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, WorldWind.RELATIVE_TO_GROUND); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragScreenSizeConstant(dragContext); } - public String toString() - { + public String toString() { return this.getImageSource() != null ? this.getImageSource().toString() : this.getClass().getName(); } @@ -306,75 +261,70 @@ public String toString() * * @return XML state document string describing this UserFacingIcon. */ - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (rs == null) + if (rs == null) { return null; + } // Save the imagePath property only when the imageSource property is a simple String path. If the imageSource // property is a BufferedImage (or some other object), we make no effort to save that state. We save under // the name "imagePath" to denote that it is a special case of "imageSource". - if (getPath() != null) + if (getPath() != null) { rs.addStateValueAsString("imagePath", getPath(), true); + } // Save the iconPosition property only if all parts (latitude, longitude, and elevation) can be saved. // We will not save a partial iconPosition (for example, just the elevation). if (this.iconPosition != null - && this.iconPosition.getLatitude() != null - && this.iconPosition.getLongitude() != null) - { + && this.iconPosition.getLatitude() != null + && this.iconPosition.getLongitude() != null) { RestorableSupport.StateObject positionStateObj = rs.addStateObject("position"); - if (positionStateObj != null) - { + if (positionStateObj != null) { rs.addStateValueAsDouble(positionStateObj, "latitude", - this.iconPosition.getLatitude().degrees); + this.iconPosition.getLatitude().degrees); rs.addStateValueAsDouble(positionStateObj, "longitude", - this.iconPosition.getLongitude().degrees); + this.iconPosition.getLongitude().degrees); rs.addStateValueAsDouble(positionStateObj, "elevation", - this.iconPosition.getElevation()); + this.iconPosition.getElevation()); } } - if (this.iconSize != null) - { + if (this.iconSize != null) { RestorableSupport.StateObject sizeStateObj = rs.addStateObject("size"); - if (sizeStateObj != null) - { + if (sizeStateObj != null) { rs.addStateValueAsDouble(sizeStateObj, "width", this.iconSize.getWidth()); rs.addStateValueAsDouble(sizeStateObj, "height", this.iconSize.getHeight()); } } - if (this.toolTipText != null) + if (this.toolTipText != null) { rs.addStateValueAsString("toolTipText", this.toolTipText, true); + } // Save the name, style, and size of the font. These will be used to restore the font using the // constructor: new Font(name, style, size). - if (this.toolTipFont != null) - { + if (this.toolTipFont != null) { RestorableSupport.StateObject toolTipFontStateObj = rs.addStateObject("toolTipFont"); - if (toolTipFontStateObj != null) - { + if (toolTipFontStateObj != null) { rs.addStateValueAsString(toolTipFontStateObj, "name", this.toolTipFont.getName()); rs.addStateValueAsInteger(toolTipFontStateObj, "style", this.toolTipFont.getStyle()); rs.addStateValueAsInteger(toolTipFontStateObj, "size", this.toolTipFont.getSize()); } } - if (this.textColor != null) - { + if (this.textColor != null) { String encodedColor = RestorableSupport.encodeColor(this.textColor); - if (encodedColor != null) + if (encodedColor != null) { rs.addStateValueAsString("toolTipTextColor", encodedColor); + } } // Save the backgroundImage property only when it is a simple String path. If the backgroundImage property is a // BufferedImage (or some other object), we make no effort to save that state. We save under the name // "backgroundImagePath" to denote that it is a special case of "backgroundImage". - if (this.getBackgroundTexture() != null && this.getBackgroundTexture().getImageSource() instanceof String) - { + if (this.getBackgroundTexture() != null && this.getBackgroundTexture().getImageSource() instanceof String) { String backgroundImagePath = (String) this.getBackgroundTexture().getImageSource(); rs.addStateValueAsString("backgroundImagePath", backgroundImagePath, true); } @@ -387,8 +337,7 @@ public String getRestorableState() rs.addStateValueAsDouble("backgroundScale", this.backgroundScale); RestorableSupport.StateObject so = rs.addStateObject(null, "avlist"); - for (Map.Entry avp : this.getEntries()) - { + for (Map.Entry avp : this.getEntries()) { this.getRestorableStateForAVPair(avp.getKey(), avp.getValue() != null ? avp.getValue() : "", rs, so); } @@ -404,24 +353,19 @@ public String getRestorableState() * @param stateInXml an XML document String describing a UserFacingIcon. * * @throws IllegalArgumentException If stateInXml is null, or if stateInXml is not a well - * formed XML document String. + * formed XML document String. */ - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport restorableSupport; - try - { + try { restorableSupport = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -432,57 +376,59 @@ public void restoreState(String stateInXml) // If the imageSource property was a BufferedImage (or some other object), it should not exist in the // state document. We save under the name "imagePath" to denote that it is a special case of "imageSource". String s = restorableSupport.getStateValueAsString("imagePath"); - if (s != null) + if (s != null) { this.setImageSource(s); + } // Restore the position property only if all parts are available. // We will not restore a partial position (for example, just the elevation). RestorableSupport.StateObject so = restorableSupport.getStateObject("position"); - if (so != null) - { + if (so != null) { Double lat = restorableSupport.getStateValueAsDouble(so, "latitude"); Double lon = restorableSupport.getStateValueAsDouble(so, "longitude"); Double elev = restorableSupport.getStateValueAsDouble(so, "elevation"); - if (lat != null && lon != null && elev != null) + if (lat != null && lon != null && elev != null) { this.setPosition(Position.fromDegrees(lat, lon, elev)); + } } // Restore the size property only if all parts are available. // We will not restore a partial size (for example, just the width). so = restorableSupport.getStateObject("size"); - if (so != null) - { + if (so != null) { Double width = restorableSupport.getStateValueAsDouble(so, "width"); Double height = restorableSupport.getStateValueAsDouble(so, "height"); - if (width != null && height != null) + if (width != null && height != null) { this.setSize(new Dimension(width.intValue(), height.intValue())); + } } s = restorableSupport.getStateValueAsString("toolTipText"); - if (s != null) + if (s != null) { this.setToolTipText(s); + } // Restore the toolTipFont property only if all parts are available. // We will not restore a partial toolTipFont (for example, just the size). so = restorableSupport.getStateObject("toolTipFont"); - if (so != null) - { + if (so != null) { // The "font name" of toolTipFont. String name = restorableSupport.getStateValueAsString(so, "name"); // The style attributes. Integer style = restorableSupport.getStateValueAsInteger(so, "style"); // The simple font size. Integer size = restorableSupport.getStateValueAsInteger(so, "size"); - if (name != null && style != null && size != null) + if (name != null && style != null && size != null) { this.setToolTipFont(new Font(name, style, size)); + } } s = restorableSupport.getStateValueAsString("toolTipTextColor"); - if (s != null) - { + if (s != null) { Color color = RestorableSupport.decodeColor(s); - if (color != null) + if (color != null) { this.setToolTipTextColor(color); + } } // The backgroundImagePath property should exist only if the backgroundImage property was a simple String path. @@ -490,43 +436,48 @@ public void restoreState(String stateInXml) // state document. We save under the name "backgroundImagePath" to denote that it is a special case of // "backgroundImage". s = restorableSupport.getStateValueAsString("backgroundImagePath"); - if (s != null) + if (s != null) { this.setBackgroundImage(s); + } Boolean b = restorableSupport.getStateValueAsBoolean("highlighted"); - if (b != null) + if (b != null) { this.setHighlighted(b); + } Double d = restorableSupport.getStateValueAsDouble("highlightScale"); - if (d != null) + if (d != null) { this.setHighlightScale(d); + } b = restorableSupport.getStateValueAsBoolean("visible"); - if (b != null) + if (b != null) { this.setVisible(b); + } b = restorableSupport.getStateValueAsBoolean("showToolTip"); - if (b != null) + if (b != null) { this.setShowToolTip(b); + } b = restorableSupport.getStateValueAsBoolean("alwaysOnTop"); - if (b != null) + if (b != null) { this.setAlwaysOnTop(b); + } d = restorableSupport.getStateValueAsDouble("backgroundScale"); - if (d != null) + if (d != null) { this.setBackgroundScale(d); + } so = restorableSupport.getStateObject(null, "avlist"); - if (so != null) - { + if (so != null) { RestorableSupport.StateObject[] avpairs = restorableSupport.getAllStateObjects(so, ""); - if (avpairs != null) - { - for (RestorableSupport.StateObject avp : avpairs) - { - if (avp != null) + if (avpairs != null) { + for (RestorableSupport.StateObject avp : avpairs) { + if (avp != null) { this.setValue(avp.getName(), avp.getValue()); + } } } } diff --git a/src/gov/nasa/worldwind/render/UserFacingText.java b/src/gov/nasa/worldwind/render/UserFacingText.java index 314c15d773..ef68d7e275 100644 --- a/src/gov/nasa/worldwind/render/UserFacingText.java +++ b/src/gov/nasa/worldwind/render/UserFacingText.java @@ -14,8 +14,8 @@ * @author dcollins * @version $Id: UserFacingText.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class UserFacingText implements GeographicText -{ +public class UserFacingText implements GeographicText { + private CharSequence text; private Position textPosition; private Font textFont; // Can be null to indicate the default font. @@ -24,10 +24,8 @@ public class UserFacingText implements GeographicText private boolean isVisible = true; double priority; //used for label culling - public UserFacingText(CharSequence text, Position textPosition) - { - if (text == null) - { + public UserFacingText(CharSequence text, Position textPosition) { + if (text == null) { String message = Logging.getMessage("nullValue.CharSequenceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -37,15 +35,12 @@ public UserFacingText(CharSequence text, Position textPosition) this.textPosition = textPosition; } - public CharSequence getText() - { + public CharSequence getText() { return this.text; } - public void setText(CharSequence text) - { - if (text == null) - { + public void setText(CharSequence text) { + if (text == null) { String message = Logging.getMessage("nullValue.CharSequenceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -54,63 +49,51 @@ public void setText(CharSequence text) this.text = text; } - public double getPriority() - { + public double getPriority() { return priority; } - public void setPriority(double priority) - { + public void setPriority(double priority) { this.priority = priority; } - public Position getPosition() - { + public Position getPosition() { return this.textPosition; } - public void setPosition(Position position) - { + public void setPosition(Position position) { this.textPosition = position; } - public Font getFont() - { + public Font getFont() { return this.textFont; } - public void setFont(Font font) - { + public void setFont(Font font) { this.textFont = font; } - public Color getColor() - { + public Color getColor() { return this.textColor; } - public void setColor(Color color) - { + public void setColor(Color color) { this.textColor = color; } - public Color getBackgroundColor() - { + public Color getBackgroundColor() { return this.textBackgroundColor; } - public void setBackgroundColor(Color background) - { + public void setBackgroundColor(Color background) { this.textBackgroundColor = background; } - public boolean isVisible() - { + public boolean isVisible() { return this.isVisible; } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.isVisible = visible; } } diff --git a/src/gov/nasa/worldwind/render/WWIcon.java b/src/gov/nasa/worldwind/render/WWIcon.java index bba9b26120..f1699b3913 100644 --- a/src/gov/nasa/worldwind/render/WWIcon.java +++ b/src/gov/nasa/worldwind/render/WWIcon.java @@ -20,8 +20,8 @@ * @author tag * @version $Id: WWIcon.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WWIcon extends AVList, Restorable -{ +public interface WWIcon extends AVList, Restorable { + /** * Specifies the source image for the icon. Implementations of this interface determine the allowed source types, * but generally allow at least a {@link String} file path and a {@link java.awt.image.BufferedImage}. @@ -50,7 +50,7 @@ public interface WWIcon extends AVList, Restorable * Sets the icon's geographic position. * * @param iconPosition the icon's geographic position. May be null to indicate that the icon has no current position - * and therefore should not be displayed. + * and therefore should not be displayed. */ void setPosition(Position iconPosition); @@ -166,7 +166,7 @@ public interface WWIcon extends AVList, Restorable * Indicates the color in which the icon's tool tip, if any, is drawn. * * @return the tool tip's text color. The default value is null, in which case an implementation dependent color is - * used. + * used. */ Color getToolTipTextColor(); @@ -174,7 +174,7 @@ public interface WWIcon extends AVList, Restorable * Specifies the color in which to display the icon's tool tip text, if any. * * @param textColor the tool tip text color. The default is null, in which case an implementation dependent color is - * used. + * used. */ void setToolTipTextColor(Color textColor); diff --git a/src/gov/nasa/worldwind/render/WWTexture.java b/src/gov/nasa/worldwind/render/WWTexture.java index b943597301..79d723307d 100644 --- a/src/gov/nasa/worldwind/render/WWTexture.java +++ b/src/gov/nasa/worldwind/render/WWTexture.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.opengl.util.texture.TextureCoords; @@ -18,8 +17,8 @@ * @author tag * @version $Id: WWTexture.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WWTexture -{ +public interface WWTexture { + /** * Returns the texture's image source. * diff --git a/src/gov/nasa/worldwind/render/Wedge.java b/src/gov/nasa/worldwind/render/Wedge.java index e051a4fd34..39615d66ed 100644 --- a/src/gov/nasa/worldwind/render/Wedge.java +++ b/src/gov/nasa/worldwind/render/Wedge.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render; import com.jogamp.common.nio.Buffers; @@ -25,8 +24,8 @@ * @author ccrick * @version $Id: Wedge.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Wedge extends RigidShape -{ +public class Wedge extends RigidShape { + protected static final int DEFAULT_SUBDIVISIONS = 2; protected Angle wedgeAngle = Angle.fromDegrees(220); // default value for angle consumed by the wedge @@ -42,9 +41,10 @@ public class Wedge extends RigidShape // face 4: right rectangular Wedge side protected int subdivisions = DEFAULT_SUBDIVISIONS; - /** Construct a wedge with default parameters */ - public Wedge() - { + /** + * Construct a wedge with default parameters + */ + public Wedge() { this.setUpGeometryCache(); } @@ -52,45 +52,39 @@ public Wedge() * Constructs a Wedge from a specified center position, height, radius and angle. * * @param centerPosition the Wedge's center position. - * @param height the Wedge's height, in meters. - * @param radius the radius of the Wedge's base, in meters. - * @param angle the angle covered by the wedge + * @param height the Wedge's height, in meters. + * @param radius the radius of the Wedge's base, in meters. + * @param angle the angle covered by the wedge * * @throws IllegalArgumentException if the center position is null, if the wedgeAngle is null or not in [0, 2*PI], - * or if any of the radii are not greater than 0. + * or if any of the radii are not greater than 0. */ - public Wedge(Position centerPosition, Angle angle, double height, double radius) - { - if (centerPosition == null) - { + public Wedge(Position centerPosition, Angle angle, double height, double radius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle == null) - { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius <= 0) - { + if (radius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0) - { + if (height <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) - { + if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "angle < 0 or angle > 2 PI"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -108,41 +102,36 @@ public Wedge(Position centerPosition, Angle angle, double height, double radius) /** * Constructs a wedge from a specified center position and axes lengths. * - * @param centerPosition the wedge's center position. - * @param angle the angle covered by the wedge + * @param centerPosition the wedge's center position. + * @param angle the angle covered by the wedge * @param northSouthRadius the wedge's north-south radius, in meters. - * @param verticalRadius the wedge's vertical radius, in meters. - * @param eastWestRadius the wedge's east-west radius, in meters. + * @param verticalRadius the wedge's vertical radius, in meters. + * @param eastWestRadius the wedge's east-west radius, in meters. * * @throws IllegalArgumentException if the center position is null, if the wedgeAngle is null or not in [0, 2*PI], - * or if any of the radii are not greater than 0. + * or if any of the radii are not greater than 0. */ public Wedge(Position centerPosition, Angle angle, double northSouthRadius, double verticalRadius, - double eastWestRadius) - { - if (centerPosition == null) - { + double eastWestRadius) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle == null) - { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) - { + if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "angle < 0 or angle > 2 PI"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -161,44 +150,39 @@ public Wedge(Position centerPosition, Angle angle, double northSouthRadius, doub * Constructs a wedge from a specified center position, axes lengths and rotation angles. All angles are specified * in degrees and positive angles are counter-clockwise. * - * @param centerPosition the wedge's center position. - * @param angle the angle covered by the wedge + * @param centerPosition the wedge's center position. + * @param angle the angle covered by the wedge * @param northSouthRadius the wedge's north-south radius, in meters. - * @param verticalRadius the wedge's vertical radius, in meters. - * @param eastWestRadius the wedge's east-west radius, in meters. - * @param heading the wedge's azimuth, its rotation about its vertical axis. - * @param tilt the wedge pitch, its rotation about its east-west axis. - * @param roll the wedge's roll, its rotation about its north-south axis. + * @param verticalRadius the wedge's vertical radius, in meters. + * @param eastWestRadius the wedge's east-west radius, in meters. + * @param heading the wedge's azimuth, its rotation about its vertical axis. + * @param tilt the wedge pitch, its rotation about its east-west axis. + * @param roll the wedge's roll, its rotation about its north-south axis. * * @throws IllegalArgumentException the centerPosition is null, or if the wedgeAngle is null or not in [0, 2*PI], or - * if any of the radii are not greater than 0. + * if any of the radii are not greater than 0. */ public Wedge(Position centerPosition, Angle angle, double northSouthRadius, double verticalRadius, - double eastWestRadius, Angle heading, Angle tilt, Angle roll) - { - if (centerPosition == null) - { + double eastWestRadius, Angle heading, Angle tilt, Angle roll) { + if (centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle == null) - { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) - { + if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "angle < 0 or angle > 2 PI"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) - { + if (northSouthRadius <= 0 || eastWestRadius <= 0 || verticalRadius <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -217,8 +201,7 @@ public Wedge(Position centerPosition, Angle angle, double northSouthRadius, doub } @Override - protected void initialize() - { + protected void initialize() { // Nothing to override } @@ -227,29 +210,25 @@ protected void initialize() * * @return the angle covered by the wedge. */ - public Angle getWedgeAngle() - { + public Angle getWedgeAngle() { return wedgeAngle; } /** - * Specifies the angle covered by the wedge. This angle must fall in [0, 2*PI]. + * Specifies the angle covered by the wedge. This angle must fall in [0, 2*PI]. * * @param angle the angle covered by the wedge. Must be in [0, 2*PI]. * * @throws IllegalArgumentException if the wedgeAngle is null, or is not in [0, 2*PI]. */ - public void setWedgeAngle(Angle angle) - { - if (angle == null) - { + public void setWedgeAngle(Angle angle) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) - { + if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "wedgeAngle < 0 or wedgeAngle > 2 PI"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -260,13 +239,11 @@ public void setWedgeAngle(Angle angle) } @Override - public int getFaceCount() - { + public int getFaceCount() { return this.faceCount; } - public int getSubdivisions() - { + public int getSubdivisions() { return this.subdivisions; } @@ -275,8 +252,7 @@ public int getSubdivisions() * * @return the detailThreshold */ - protected double computeDetailThreshold() - { + protected double computeDetailThreshold() { // these values must be calibrated on a shape-by-shape basis double detailThreshold = 8; double rangeDetailThreshold = 25; @@ -290,47 +266,44 @@ protected double computeDetailThreshold() * Computes the number of subdivisions necessary to achieve the expected Level of Detail given the shape's * relationship to the viewer. * - * @param dc the current drawContext. + * @param dc the current drawContext. * @param shapeData the current globe-specific shape data */ - protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) - { + protected void computeSubdivisions(DrawContext dc, ShapeData shapeData) { // test again possible subdivision values int minDivisions = 0; int maxDivisions = 6; - if (shapeData.getExtent() != null) - { - for (int divisions = minDivisions; divisions <= maxDivisions; divisions++) - { + if (shapeData.getExtent() != null) { + for (int divisions = minDivisions; divisions <= maxDivisions; divisions++) { this.subdivisions = divisions; - if (this.sufficientDetail(dc, divisions, shapeData)) + if (this.sufficientDetail(dc, divisions, shapeData)) { break; + } } } } - protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData shapeData) - { - if (dc.getView() == null) - { + protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData shapeData) { + if (dc.getView() == null) { String message = "nullValue.DrawingContextViewIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (shapeData == null) + if (shapeData == null) { return false; + } Extent extent = shapeData.getExtent(); - if (extent == null) + if (extent == null) { return true; + } double thresholdDensity = this.computeDetailThreshold(); @@ -343,13 +316,13 @@ protected boolean sufficientDetail(DrawContext dc, int subdivisions, ShapeData s return vertexDensity > thresholdDensity; } - protected boolean mustRegenerateGeometry(DrawContext dc) - { + protected boolean mustRegenerateGeometry(DrawContext dc) { // check if current LOD is sufficient int oldDivisions = this.subdivisions; computeSubdivisions(dc, this.getCurrentShapeData()); - if (oldDivisions != this.subdivisions) + if (oldDivisions != this.subdivisions) { return true; + } return super.mustRegenerateGeometry(dc); } @@ -357,7 +330,6 @@ protected boolean mustRegenerateGeometry(DrawContext dc) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - /** * Sets the Geometry mesh for this wedge, either by pulling it from the geometryCache, or by creating it anew if the * appropriate geometry does not yet exist in the cache. @@ -366,10 +338,8 @@ protected boolean mustRegenerateGeometry(DrawContext dc) * * @throws IllegalArgumentException if the wedgeAngle is null */ - protected void makeGeometry(ShapeData shapeData) - { - if (this.wedgeAngle == null) - { + protected void makeGeometry(ShapeData shapeData) { + if (this.wedgeAngle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -377,31 +347,30 @@ protected void makeGeometry(ShapeData shapeData) // attempt to retrieve a cached unit wedge with the same angle and number of subdivisions Object cacheKey = new Geometry.CacheKey(this.getClass(), "Wedge0-" + this.wedgeAngle.toString(), - this.subdivisions); + this.subdivisions); Geometry geom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null) - { + if (geom == null) { // if none exists, create a new one makeUnitWedge(this.subdivisions, shapeData.getMeshes()); - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } // add the new mesh pieces to the cache cacheKey = new Geometry.CacheKey(this.getClass(), "Wedge" + piece + "-" + this.wedgeAngle.toString(), - this.subdivisions); + this.subdivisions); this.getGeometryCache().add(cacheKey, shapeData.getMesh(piece)); } - } - else - { + } else { // otherwise, just use the one from the cache - for (int piece = 0; piece < getFaceCount(); piece++) - { - if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + for (int piece = 0; piece < getFaceCount(); piece++) { + if (offsets.get(piece) == null) // if texture offsets don't exist, set default values to 0 + { offsets.put(piece, new OffsetsList()); + } cacheKey = new Geometry.CacheKey(this.getClass(), "Wedge" + piece + "-" + this.wedgeAngle.toString(), - this.subdivisions); + this.subdivisions); geom = (Geometry) this.getGeometryCache().getObject(cacheKey); shapeData.addMesh(piece, geom); } @@ -413,7 +382,7 @@ protected void makeGeometry(ShapeData shapeData) * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit wedge geometry - * @param dest the Geometry container to hold the computed points, etc. + * @param dest the Geometry container to hold the computed points, etc. * * @throws IllegalArgumentException if the wedgeAngle is null */ @@ -447,21 +416,18 @@ protected void makeUnitWedge(int subdivisions, Geometry dest) dest.setNormalData(normalBuffer.limit(), normalBuffer); dest.setTextureCoordData(textureCoordBuffer.limit(), textureCoordBuffer); } - */ - + */ /** * Generates a unit wedge geometry, including the vertices, indices, normals and texture coordinates, tessellated * with the specified number of divisions. * * @param subdivisions the number of times to subdivide the unit wedge geometry - * @param meshes the Geometry list to hold the computed points, etc. for all wedge Geometries + * @param meshes the Geometry list to hold the computed points, etc. for all wedge Geometries * * @throws IllegalArgumentException if the wedgeAngle is null */ - protected void makeUnitWedge(int subdivisions, List meshes) - { - if (this.wedgeAngle == null) - { + protected void makeUnitWedge(int subdivisions, List meshes) { + if (this.wedgeAngle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -473,11 +439,10 @@ protected void makeUnitWedge(int subdivisions, List meshes) GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(GeometryBuilder.OUTSIDE); - for (int index = 0; index < getFaceCount(); index++) - { + for (int index = 0; index < getFaceCount(); index++) { // create wedge in model space - GeometryBuilder.IndexedTriangleBuffer itb = - gb.tessellateWedgeBuffer(index, radius, subdivisions, this.wedgeAngle); + GeometryBuilder.IndexedTriangleBuffer itb + = gb.tessellateWedgeBuffer(index, radius, subdivisions, this.wedgeAngle); FloatBuffer normalBuffer = Buffers.newDirectFloatBuffer(3 * itb.getVertexCount()); gb.makeIndexedTriangleBufferNormals(itb, normalBuffer); @@ -499,18 +464,16 @@ protected void makeUnitWedge(int subdivisions, List meshes) /** * Renders the wedge, using data from the provided buffer and the given parameters. * - * @param dc the current draw context - * @param mode the render mode - * @param count the number of elements to be drawn - * @param type the data type of the elements to be drawn + * @param dc the current draw context + * @param mode the render mode + * @param count the number of elements to be drawn + * @param type the data type of the elements to be drawn * @param elementBuffer the buffer containing the list of elements to be drawn - * @param shapeData this shape's current globe-specific shape data + * @param shapeData this shape's current globe-specific shape data */ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffer elementBuffer, - ShapeData shapeData, int face) - { - if (elementBuffer == null) - { + ShapeData shapeData, int face) { + if (elementBuffer == null) { String message = "nullValue.ElementBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -518,8 +481,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe Geometry mesh = shapeData.getMesh(face); - if (mesh.getBuffer(Geometry.VERTEX) == null) - { + if (mesh.getBuffer(Geometry.VERTEX) == null) { String message = "nullValue.VertexBufferIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -536,17 +498,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe vertexBuffer = mesh.getBuffer(Geometry.VERTEX); normalBuffer = null; - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { normalBuffer = mesh.getBuffer(Geometry.NORMAL); - if (normalBuffer == null) - { + if (normalBuffer == null) { gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); - } - else - { + } else { glType = mesh.getGLType(Geometry.NORMAL); stride = mesh.getStride(Geometry.NORMAL); gl.glNormalPointer(glType, stride, normalBuffer); @@ -557,14 +514,12 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // cull the back face //gl.glEnable(GL.GL_CULL_FACE); //gl.glFrontFace(GL.GL_CCW); - // disable VBO's because they are not equipped to handle the arbitrary wedge angle boolean vboState = dc.getGLRuntimeCapabilities().isVertexBufferObjectEnabled(); dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(false); // decide whether to draw with VBO's or VA's - if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) - { + if (this.shouldUseVBOs(dc) && (this.getVboIds(getSubdivisions(), dc)) != null) { // render using VBO's gl.glBindBuffer(GL.GL_ARRAY_BUFFER, getVboIds(getSubdivisions(), dc)[2 * face]); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, this.getVboIds(getSubdivisions(), dc)[2 * face + 1]); @@ -574,9 +529,7 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); - } - else - { + } else { // render using vertex arrays gl.glVertexPointer(size, glType, stride, vertexBuffer.rewind()); gl.glDrawElements(mode, count, type, elementBuffer); @@ -587,23 +540,20 @@ protected void drawGeometry(DrawContext dc, int mode, int count, int type, Buffe // disable back face culling // gl.glDisable(GL.GL_CULL_FACE); - dc.getGLRuntimeCapabilities().setVertexBufferObjectEnabled(vboState); - if (!dc.isPickingMode()) - { - if (mustApplyLighting(dc, null)) - { + if (!dc.isPickingMode()) { + if (mustApplyLighting(dc, null)) { // re-enable normals if we temporarily turned them off earlier - if (normalBuffer == null) + if (normalBuffer == null) { gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); + } } // this.logGeometryStatistics(dc, geom); } } - protected ShapeData createIntersectionGeometry(Terrain terrain) - { + protected ShapeData createIntersectionGeometry(Terrain terrain) { ShapeData shapeData = new ShapeData(null, this); shapeData.setGlobeStateKey(terrain.getGlobe().getGlobeStateKey()); Geometry mesh; @@ -613,53 +563,51 @@ protected ShapeData createIntersectionGeometry(Terrain terrain) // transform the vertices from local to world coords Matrix matrix = computeRenderMatrix(terrain.getGlobe(), terrain.getVerticalExaggeration()); - for (int i = 0; i < getFaceCount(); i++) - { + for (int i = 0; i < getFaceCount(); i++) { mesh = shapeData.getMesh(i); // transform the vertices from local to world coords FloatBuffer newVertices = computeTransformedVertices((FloatBuffer) mesh.getBuffer(Geometry.VERTEX), - mesh.getCount(Geometry.VERTEX), matrix); + mesh.getCount(Geometry.VERTEX), matrix); mesh.setVertexData(mesh.getCount(Geometry.VERTEX), newVertices); } shapeData.setReferencePoint(this.computeReferencePoint(terrain.getGlobe(), - terrain.getVerticalExaggeration())); + terrain.getVerticalExaggeration())); shapeData.setExtent(getExtent(terrain.getGlobe(), terrain.getVerticalExaggeration())); return shapeData; } - /** No export formats supported. */ + /** + * No export formats supported. + */ @Override - public String isExportFormatSupported(String mimeType) - { + public String isExportFormatSupported(String mimeType) { // Overridden because this shape does not support export to KML. return Exportable.FORMAT_NOT_SUPPORTED; } @Override - protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException - { + protected void doExportAsKML(XMLStreamWriter xmlWriter) throws IOException, XMLStreamException { String message = Logging.getMessage("generic.UnsupportedOperation", "doExportAsKML"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsDouble(context, "wedgeAngle", this.getWedgeAngle().degrees); } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Double doubleState = rs.getStateValueAsDouble(context, "wedgeAngle"); - if (doubleState != null) + if (doubleState != null) { this.setWedgeAngle(Angle.fromDegrees(doubleState)); + } } } diff --git a/src/gov/nasa/worldwind/render/airspaces/AbstractAirspace.java b/src/gov/nasa/worldwind/render/airspaces/AbstractAirspace.java index 6ee0f19925..8779de791e 100644 --- a/src/gov/nasa/worldwind/render/airspaces/AbstractAirspace.java +++ b/src/gov/nasa/worldwind/render/airspaces/AbstractAirspace.java @@ -27,8 +27,8 @@ * @version $Id: AbstractAirspace.java 3138 2015-06-02 19:13:16Z tgaskins $ */ public abstract class AbstractAirspace extends WWObjectImpl - implements Airspace, OrderedRenderable, PreRenderable, Movable, Movable2, Draggable -{ + implements Airspace, OrderedRenderable, PreRenderable, Movable, Movable2, Draggable { + protected static final String ARC_SLICES = "ArcSlices"; protected static final String DISABLE_TERRAIN_CONFORMANCE = "DisableTerrainConformance"; protected static final String EXPIRY_TIME = "ExpiryTime"; @@ -45,21 +45,30 @@ public abstract class AbstractAirspace extends WWObjectImpl protected static final String VERTICAL_EXAGGERATION = "VerticalExaggeration"; private static final long DEFAULT_GEOMETRY_CACHE_SIZE = 16777216L; // 16 megabytes - /** The default outline pick width. */ + /** + * The default outline pick width. + */ protected static final int DEFAULT_OUTLINE_PICK_WIDTH = 10; - /** The default interior color. */ + /** + * The default interior color. + */ protected static final Material DEFAULT_INTERIOR_MATERIAL = Material.LIGHT_GRAY; - /** The default outline color. */ + /** + * The default outline color. + */ protected static final Material DEFAULT_OUTLINE_MATERIAL = Material.DARK_GRAY; - /** The default highlight color. */ + /** + * The default highlight color. + */ protected static final Material DEFAULT_HIGHLIGHT_MATERIAL = Material.WHITE; - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static AirspaceAttributes defaultAttributes; - static - { + static { // Create and populate the default attributes. defaultAttributes = new BasicAirspaceAttributes(); defaultAttributes.setInteriorMaterial(DEFAULT_INTERIOR_MATERIAL); @@ -107,48 +116,39 @@ public abstract class AbstractAirspace extends WWObjectImpl // Elevation lookup map. protected Map elevationMap = new HashMap(); // Implements the the interface used by the draw context's outlined-shape renderer. - protected OutlinedShape outlineShapeRenderer = new OutlinedShape() - { - public boolean isDrawOutline(DrawContext dc, Object shape) - { + protected OutlinedShape outlineShapeRenderer = new OutlinedShape() { + public boolean isDrawOutline(DrawContext dc, Object shape) { return ((AbstractAirspace) shape).mustDrawOutline(dc); } - public boolean isDrawInterior(DrawContext dc, Object shape) - { + public boolean isDrawInterior(DrawContext dc, Object shape) { return ((AbstractAirspace) shape).mustDrawInterior(dc); } - public void drawOutline(DrawContext dc, Object shape) - { + public void drawOutline(DrawContext dc, Object shape) { ((AbstractAirspace) shape).drawOutline(dc); } - public void drawInterior(DrawContext dc, Object shape) - { + public void drawInterior(DrawContext dc, Object shape) { ((AbstractAirspace) shape).drawInterior(dc); } - public boolean isEnableDepthOffset(DrawContext dc, Object shape) - { + public boolean isEnableDepthOffset(DrawContext dc, Object shape) { return ((AbstractAirspace) shape).isEnableDepthOffset(); } - public Double getDepthOffsetFactor(DrawContext dc, Object shape) - { + public Double getDepthOffsetFactor(DrawContext dc, Object shape) { return null; } - public Double getDepthOffsetUnits(DrawContext dc, Object shape) - { + public Double getDepthOffsetUnits(DrawContext dc, Object shape) { return null; } }; // Airspaces perform about 5% better if their extent is cached, so do that here. + protected static class AirspaceInfo { - protected static class AirspaceInfo - { // The extent depends on the state of the globe used to compute it, and the vertical exaggeration. protected Extent extent; protected double eyeDistance; @@ -156,38 +156,32 @@ protected static class AirspaceInfo protected double verticalExaggeration; protected Object globeStateKey; - public AirspaceInfo(DrawContext dc, Extent extent, List minimalGeometry) - { + public AirspaceInfo(DrawContext dc, Extent extent, List minimalGeometry) { this.extent = extent; this.minimalGeometry = minimalGeometry; this.verticalExaggeration = dc.getVerticalExaggeration(); this.globeStateKey = dc.getGlobe().getStateKey(dc); } - public double getEyeDistance() - { + public double getEyeDistance() { return this.eyeDistance; } - public void setEyeDistance(double eyeDistance) - { + public void setEyeDistance(double eyeDistance) { this.eyeDistance = eyeDistance; } - public boolean isValid(DrawContext dc) - { + public boolean isValid(DrawContext dc) { return this.verticalExaggeration == dc.getVerticalExaggeration() - && (this.globeStateKey != null && this.globeStateKey.equals(dc.getGlobe().getStateKey(dc))); + && (this.globeStateKey != null && this.globeStateKey.equals(dc.getGlobe().getStateKey(dc))); } } // usually only 1, but few at most protected HashMap airspaceInfo = new HashMap(2); - public AbstractAirspace(AirspaceAttributes attributes) - { - if (attributes == null) - { + public AbstractAirspace(AirspaceAttributes attributes) { + if (attributes == null) { String message = "nullValue.AirspaceAttributesIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -195,8 +189,7 @@ public AbstractAirspace(AirspaceAttributes attributes) this.attributes = attributes; - if (!WorldWind.getMemoryCacheSet().containsCache(GEOMETRY_CACHE_KEY)) - { + if (!WorldWind.getMemoryCacheSet().containsCache(GEOMETRY_CACHE_KEY)) { long size = Configuration.getLongValue(AVKey.AIRSPACE_GEOMETRY_CACHE_SIZE, DEFAULT_GEOMETRY_CACHE_SIZE); MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size); cache.setName(GEOMETRY_CACHE_NAME); @@ -208,8 +201,7 @@ public AbstractAirspace(AirspaceAttributes attributes) protected abstract List computeMinimalGeometry(Globe globe, double verticalExaggeration); - public AbstractAirspace(AbstractAirspace source) - { + public AbstractAirspace(AbstractAirspace source) { this(source.getAttributes()); this.visible = source.visible; @@ -231,30 +223,24 @@ public AbstractAirspace(AbstractAirspace source) this.drawSurfaceShape = source.drawSurfaceShape; } - public AbstractAirspace() - { + public AbstractAirspace() { this(new BasicAirspaceAttributes()); } - public boolean isVisible() - { + public boolean isVisible() { return this.visible; } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.visible = visible; } - public AirspaceAttributes getAttributes() - { + public AirspaceAttributes getAttributes() { return this.attributes; } - public void setAttributes(AirspaceAttributes attributes) - { - if (attributes == null) - { + public void setAttributes(AirspaceAttributes attributes) { + if (attributes == null) { String message = "nullValue.AirspaceAttributesIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -264,73 +250,63 @@ public void setAttributes(AirspaceAttributes attributes) } @Override - public void setAttributes(ShapeAttributes attributes) - { + public void setAttributes(ShapeAttributes attributes) { this.setAttributes(new BasicAirspaceAttributes(attributes)); } @Override - public void setHighlightAttributes(ShapeAttributes highlightAttributes) - { + public void setHighlightAttributes(ShapeAttributes highlightAttributes) { this.setHighlightAttributes( - highlightAttributes != null ? new BasicAirspaceAttributes(highlightAttributes) : null); + highlightAttributes != null ? new BasicAirspaceAttributes(highlightAttributes) : null); } @Override - public AirspaceAttributes getHighlightAttributes() - { + public AirspaceAttributes getHighlightAttributes() { return highlightAttributes; } @Override - public void setHighlightAttributes(AirspaceAttributes highlightAttrs) - { + public void setHighlightAttributes(AirspaceAttributes highlightAttrs) { this.highlightAttributes = highlightAttrs; - if (this.surfaceShape != null) + if (this.surfaceShape != null) { this.surfaceShape.setHighlightAttributes(highlightAttrs); + } } - public boolean isHighlighted() - { + public boolean isHighlighted() { return highlighted; } - public void setHighlighted(boolean highlighted) - { + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } - public double[] getAltitudes() - { + public double[] getAltitudes() { double[] array = new double[2]; array[0] = this.lowerAltitude; array[1] = this.upperAltitude; return array; } - protected double[] getAltitudes(double verticalExaggeration) - { + protected double[] getAltitudes(double verticalExaggeration) { double[] array = this.getAltitudes(); array[0] = array[0] * verticalExaggeration; array[1] = array[1] * verticalExaggeration; return array; } - public void setAltitudes(double lowerAltitude, double upperAltitude) - { + public void setAltitudes(double lowerAltitude, double upperAltitude) { this.lowerAltitude = lowerAltitude; this.upperAltitude = upperAltitude; this.invalidateAirspaceData(); } - public void setAltitude(double altitude) - { + public void setAltitude(double altitude) { this.setAltitudes(altitude, altitude); } - public boolean[] isTerrainConforming() - { + public boolean[] isTerrainConforming() { // This method is here for backwards compatibility. The new scheme uses enumerations (in the form of Strings). boolean[] array = new boolean[2]; @@ -339,8 +315,7 @@ public boolean[] isTerrainConforming() return array; } - public void setTerrainConforming(boolean lowerTerrainConformant, boolean upperTerrainConformant) - { + public void setTerrainConforming(boolean lowerTerrainConformant, boolean upperTerrainConformant) { // This method is here for backwards compatibility. The new scheme uses enumerations (in the form of Strings). this.lowerTerrainConforming = lowerTerrainConformant; @@ -352,17 +327,13 @@ public void setTerrainConforming(boolean lowerTerrainConformant, boolean upperTe this.invalidateAirspaceData(); } - public String[] getAltitudeDatum() - { - return new String[] {this.lowerAltitudeDatum, this.upperAltitudeDatum}; + public String[] getAltitudeDatum() { + return new String[]{this.lowerAltitudeDatum, this.upperAltitudeDatum}; } // TODO: The altitude datum logic is currently implemented only for Polygon. Implement it for the rest of them. - - public void setAltitudeDatum(String lowerAltitudeDatum, String upperAltitudeDatum) - { - if (lowerAltitudeDatum == null || upperAltitudeDatum == null) - { + public void setAltitudeDatum(String lowerAltitudeDatum, String upperAltitudeDatum) { + if (lowerAltitudeDatum == null || upperAltitudeDatum == null) { String message = Logging.getMessage("nullValue.AltitudeDatumIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -372,81 +343,88 @@ public void setAltitudeDatum(String lowerAltitudeDatum, String upperAltitudeDatu this.upperAltitudeDatum = upperAltitudeDatum; if (lowerAltitudeDatum.equals(AVKey.ABOVE_GROUND_LEVEL) || lowerAltitudeDatum.equals( - AVKey.ABOVE_GROUND_REFERENCE)) + AVKey.ABOVE_GROUND_REFERENCE)) { this.lowerTerrainConforming = true; + } if (upperAltitudeDatum.equals(AVKey.ABOVE_GROUND_LEVEL) || upperAltitudeDatum.equals( - AVKey.ABOVE_GROUND_REFERENCE)) + AVKey.ABOVE_GROUND_REFERENCE)) { this.upperTerrainConforming = true; + } this.invalidateAirspaceData(); } - public LatLon getGroundReference() - { + public LatLon getGroundReference() { return this.groundReference; } - public void setGroundReference(LatLon groundReference) - { + public void setGroundReference(LatLon groundReference) { this.groundReference = groundReference; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isEnableBatchRendering() - { + public boolean isEnableBatchRendering() { return this.enableBatchRendering; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setEnableBatchRendering(boolean enableBatchRendering) - { + public void setEnableBatchRendering(boolean enableBatchRendering) { this.enableBatchRendering = enableBatchRendering; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return this.enableBatchPicking; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setEnableBatchPicking(boolean enableBatchPicking) - { + public void setEnableBatchPicking(boolean enableBatchPicking) { this.enableBatchPicking = enableBatchPicking; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public boolean isEnableDepthOffset() - { + public boolean isEnableDepthOffset() { return this.enableDepthOffset; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setEnableDepthOffset(boolean enableDepthOffset) - { + public void setEnableDepthOffset(boolean enableDepthOffset) { this.enableDepthOffset = enableDepthOffset; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public int getOutlinePickWidth() - { + public int getOutlinePickWidth() { return this.outlinePickWidth; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setOutlinePickWidth(int outlinePickWidth) - { - if (outlinePickWidth < 0) - { + public void setOutlinePickWidth(int outlinePickWidth) { + if (outlinePickWidth < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -456,109 +434,93 @@ public void setOutlinePickWidth(int outlinePickWidth) } @Override - public Object getDelegateOwner() - { + public Object getDelegateOwner() { return this.delegateOwner; } @Override - public void setDelegateOwner(Object delegateOwner) - { + public void setDelegateOwner(Object delegateOwner) { this.delegateOwner = delegateOwner; } @Override - public boolean isAlwaysOnTop() - { + public boolean isAlwaysOnTop() { return alwaysOnTop; } @Override - public void setAlwaysOnTop(boolean alwaysOnTop) - { + public void setAlwaysOnTop(boolean alwaysOnTop) { this.alwaysOnTop = alwaysOnTop; } @Override - public boolean isDrawSurfaceShape() - { + public boolean isDrawSurfaceShape() { return drawSurfaceShape; } @Override - public void setDrawSurfaceShape(boolean drawSurfaceShape) - { + public void setDrawSurfaceShape(boolean drawSurfaceShape) { this.drawSurfaceShape = drawSurfaceShape; } protected void adjustForGroundReference(DrawContext dc, boolean[] terrainConformant, double[] altitudes, - LatLon groundRef) - { - if (groundRef == null) + LatLon groundRef) { + if (groundRef == null) { return; // Can't apply the datum without a reference point. - - for (int i = 0; i < 2; i++) - { - if (this.getAltitudeDatum()[i].equals(AVKey.ABOVE_GROUND_REFERENCE)) - { + } + for (int i = 0; i < 2; i++) { + if (this.getAltitudeDatum()[i].equals(AVKey.ABOVE_GROUND_REFERENCE)) { altitudes[i] += this.computeElevationAt(dc, groundRef.getLatitude(), groundRef.getLongitude()); terrainConformant[i] = false; } } } - public boolean isAirspaceCollapsed() - { + public boolean isAirspaceCollapsed() { return this.lowerAltitude == this.upperAltitude && this.lowerTerrainConforming == this.upperTerrainConforming; } - public void setTerrainConforming(boolean terrainConformant) - { + public void setTerrainConforming(boolean terrainConformant) { this.setTerrainConforming(terrainConformant, terrainConformant); } - public boolean isEnableLevelOfDetail() - { + public boolean isEnableLevelOfDetail() { return this.enableLevelOfDetail; } - public void setEnableLevelOfDetail(boolean enableLevelOfDetail) - { + public void setEnableLevelOfDetail(boolean enableLevelOfDetail) { this.enableLevelOfDetail = enableLevelOfDetail; } - public Iterable getDetailLevels() - { + public Iterable getDetailLevels() { return this.detailLevels; } - public void setDetailLevels(Collection detailLevels) - { + public void setDetailLevels(Collection detailLevels) { this.detailLevels.clear(); this.addDetailLevels(detailLevels); } - protected void addDetailLevels(Collection newDetailLevels) - { - if (newDetailLevels != null) - for (DetailLevel level : newDetailLevels) - { - if (level != null) + protected void addDetailLevels(Collection newDetailLevels) { + if (newDetailLevels != null) { + for (DetailLevel level : newDetailLevels) { + if (level != null) { this.detailLevels.add(level); + } } + } } - /** {@inheritDoc} */ - public boolean isAirspaceVisible(DrawContext dc) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public boolean isAirspaceVisible(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getView() == null) - { + if (dc.getView() == null) { String message = "nullValue.DrawingContextViewIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -566,21 +528,21 @@ public boolean isAirspaceVisible(DrawContext dc) // A null extent indicates an airspace which has no geometry. Extent extent = this.getExtent(dc); - if (extent == null) + if (extent == null) { return false; + } // Test this airspace's extent against the pick frustum list. - if (dc.isPickingMode()) + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(extent); + } // Test this airspace's extent against the viewing frustum. return dc.getView().getFrustumInModelCoordinates().intersects(extent); } - public Extent getExtent(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + public Extent getExtent(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -589,17 +551,14 @@ public Extent getExtent(Globe globe, double verticalExaggeration) return this.computeExtent(globe, verticalExaggeration); } - public Extent getExtent(DrawContext dc) - { - if (dc == null) - { + public Extent getExtent(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -608,12 +567,10 @@ public Extent getExtent(DrawContext dc) return this.getAirspaceInfo(dc).extent; } - protected AirspaceInfo getAirspaceInfo(DrawContext dc) - { + protected AirspaceInfo getAirspaceInfo(DrawContext dc) { AirspaceInfo info = this.airspaceInfo.get(dc.getGlobe().getGlobeStateKey()); - if (info == null || !info.isValid(dc)) - { + if (info == null || !info.isValid(dc)) { info = new AirspaceInfo(dc, this.computeExtent(dc), this.computeMinimalGeometry(dc)); this.airspaceInfo.put(dc.getGlobe().getGlobeStateKey(), info); } @@ -621,64 +578,55 @@ protected AirspaceInfo getAirspaceInfo(DrawContext dc) return info; } - protected Extent computeExtent(DrawContext dc) - { + protected Extent computeExtent(DrawContext dc) { return this.getExtent(dc.getGlobe(), dc.getVerticalExaggeration()); } - protected List computeMinimalGeometry(DrawContext dc) - { + protected List computeMinimalGeometry(DrawContext dc) { return this.computeMinimalGeometry(dc.getGlobe(), dc.getVerticalExaggeration()); } - protected void invalidateAirspaceData() - { + protected void invalidateAirspaceData() { this.airspaceInfo.clear(); // Doesn't hurt to remove all cached extents because re-creation is cheap this.mustRegenerateSurfaceShape = true; } @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.isAlwaysOnTop() ? 0 : this.currentInfo.getEyeDistance(); } /** * Determines which attributes -- normal, highlight or default -- to use each frame. Places the result in this * shape's current active attributes. - * - * @param dc the current drawing context. + * + * @param dc the current drawing context. * * @see #getActiveAttributes() */ - protected void determineActiveAttributes(DrawContext dc) - { - if (this.frameTimeStamp == dc.getFrameTimeStamp()) + protected void determineActiveAttributes(DrawContext dc) { + if (this.frameTimeStamp == dc.getFrameTimeStamp()) { return; + } - if (this.isHighlighted()) - { - if (this.getHighlightAttributes() != null) + if (this.isHighlighted()) { + if (this.getHighlightAttributes() != null) { this.activeAttributes.copy(this.getHighlightAttributes()); - else - { + } else { // If no highlight attributes have been specified we need to use the normal attributes but adjust them // to cause highlighting. - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); - else + } else { this.activeAttributes.copy(defaultAttributes); + } this.activeAttributes.setOutlineMaterial(DEFAULT_HIGHLIGHT_MATERIAL); this.activeAttributes.setInteriorMaterial(DEFAULT_HIGHLIGHT_MATERIAL); } - } - else if (this.getAttributes() != null) - { + } else if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); - } - else - { + } else { this.activeAttributes.copy(defaultAttributes); } } @@ -691,36 +639,32 @@ else if (this.getAttributes() != null) * * @return this shape's currently active attributes. */ - public AirspaceAttributes getActiveAttributes() - { + public AirspaceAttributes getActiveAttributes() { return this.activeAttributes; } @Override - public void preRender(DrawContext dc) - { - if (dc == null) - { + public void preRender(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } - if (dc.is2DGlobe() || this.isDrawSurfaceShape()) - { - if (this.surfaceShape == null) - { + if (dc.is2DGlobe() || this.isDrawSurfaceShape()) { + if (this.surfaceShape == null) { this.surfaceShape = this.createSurfaceShape(); this.mustRegenerateSurfaceShape = true; - if (this.surfaceShape == null) + if (this.surfaceShape == null) { return; + } } - if (this.mustRegenerateSurfaceShape) - { + if (this.mustRegenerateSurfaceShape) { this.regenerateSurfaceShape(dc, this.surfaceShape); this.mustRegenerateSurfaceShape = false; } @@ -735,8 +679,7 @@ public void preRender(DrawContext dc) * * @return The surface shape to represent this Airspace on a 2D globe. */ - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return null; } @@ -745,17 +688,17 @@ protected SurfaceShape createSurfaceShape() * globes. Subclasses should override this method if they need to update more than the attributes and the delegate * owner. * - * @param dc the current drawing context. + * @param dc the current drawing context. * @param shape the surface shape to update. */ - protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) { this.determineActiveAttributes(dc); ShapeAttributes attrs = this.getActiveAttributes(); - if (shape.getAttributes() == null) + if (shape.getAttributes() == null) { shape.setAttributes(new BasicShapeAttributes(attrs)); - else + } else { shape.getAttributes().copy(attrs); + } Object o = this.getDelegateOwner(); shape.setDelegateOwner(o != null ? o : this); @@ -768,134 +711,121 @@ protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) * Regenerates surface shape geometry prior to picking and rendering the 2D shape used to represent this Airspace on * 2D globes. * - * @param dc the current drawing context. + * @param dc the current drawing context. * @param shape the surface shape to regenerate. */ - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { // Intentionally left blank. } @Override - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { // This method is called only when ordered renderables are being drawn. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.render(dc); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { // This render method is called three times during frame generation. It's first called as a {@link Renderable} // during Renderable picking. It's called again during normal rendering. And it's called a third // time as an OrderedRenderable. The first two calls determine whether to add the shape to the ordered renderable // list during pick and render. The third call just draws the ordered renderable. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } - if ((dc.is2DGlobe() || this.isDrawSurfaceShape()) && this.surfaceShape != null) - { + if ((dc.is2DGlobe() || this.isDrawSurfaceShape()) && this.surfaceShape != null) { this.surfaceShape.render(dc); return; } this.currentInfo = this.getAirspaceInfo(dc); - if (!this.isAirspaceVisible(dc)) + if (!this.isAirspaceVisible(dc)) { return; + } - if (dc.isOrderedRenderingMode()) + if (dc.isOrderedRenderingMode()) { this.drawOrderedRenderable(dc); - else + } else { this.makeOrderedRenderable(dc); + } this.frameTimeStamp = dc.getFrameTimeStamp(); } - protected void makeOrderedRenderable(DrawContext dc) - { + protected void makeOrderedRenderable(DrawContext dc) { this.determineActiveAttributes(dc); double eyeDistance = this.computeEyeDistance(dc); this.currentInfo.setEyeDistance(eyeDistance); - if (dc.isPickingMode()) + if (dc.isPickingMode()) { this.pickLayer = dc.getCurrentLayer(); + } dc.addOrderedRenderable(this); } - protected void drawOrderedRenderable(DrawContext dc) - { + protected void drawOrderedRenderable(DrawContext dc) { this.beginRendering(dc); - try - { + try { this.doDrawOrderedRenderable(dc, this.pickSupport); - if (this.isEnableBatchRendering()) - { + if (this.isEnableBatchRendering()) { this.drawBatched(dc); } - } - finally - { + } finally { this.endRendering(dc); } } - protected void drawBatched(DrawContext dc) - { + protected void drawBatched(DrawContext dc) { // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - if (!dc.isPickingMode()) - { - while (nextItem instanceof AbstractAirspace) - { + if (!dc.isPickingMode()) { + while (nextItem instanceof AbstractAirspace) { AbstractAirspace airspace = (AbstractAirspace) nextItem; - if (!airspace.isEnableBatchRendering()) + if (!airspace.isEnableBatchRendering()) { break; + } dc.pollOrderedRenderables(); // take it off the queue airspace.doDrawOrderedRenderable(dc, this.pickSupport); nextItem = dc.peekOrderedRenderables(); } - } - else if (this.isEnableBatchPicking()) - { - while (nextItem instanceof AbstractAirspace) - { + } else if (this.isEnableBatchPicking()) { + while (nextItem instanceof AbstractAirspace) { AbstractAirspace airspace = (AbstractAirspace) nextItem; - if (!airspace.isEnableBatchRendering() || !airspace.isEnableBatchPicking()) + if (!airspace.isEnableBatchRendering() || !airspace.isEnableBatchPicking()) { break; + } if (airspace.pickLayer != this.pickLayer) // batch pick only within a single layer + { break; + } dc.pollOrderedRenderables(); // take it off the queue airspace.doDrawOrderedRenderable(dc, this.pickSupport); @@ -905,10 +835,8 @@ else if (this.isEnableBatchPicking()) } } - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) - { - if (dc.isPickingMode()) - { + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) { + if (dc.isPickingMode()) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Color pickColor = dc.getUniquePickColor(); pickCandidates.addPickableObject(this.createPickedObject(pickColor.getRGB())); @@ -918,40 +846,37 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidate dc.drawOutlinedShape(this.outlineShapeRenderer, this); } - protected PickedObject createPickedObject(int colorCode) - { + protected PickedObject createPickedObject(int colorCode) { return new PickedObject(colorCode, this.getDelegateOwner() != null ? this.getDelegateOwner() : this); } - public void move(Position position) - { - if (position == null) - { + public void move(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Position referencePos = this.getReferencePosition(); - if (referencePos == null) + if (referencePos == null) { return; + } this.moveTo(referencePos.add(position)); } @Override - public void moveTo(Globe globe, Position position) - { - if (position == null) - { + public void moveTo(Globe globe, Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Position oldRef = this.getReferencePosition(); - if (oldRef == null) + if (oldRef == null) { return; + } //noinspection UnnecessaryLocalVariable Position newRef = position; @@ -959,68 +884,61 @@ public void moveTo(Globe globe, Position position) } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = true; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, this.isTerrainConforming()[0] - ? WorldWind.RELATIVE_TO_GROUND : WorldWind.ABSOLUTE); + ? WorldWind.RELATIVE_TO_GROUND : WorldWind.ABSOLUTE); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { this.doMoveTo(oldRef, newRef); } - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Position oldRef = this.getReferencePosition(); - if (oldRef == null) + if (oldRef == null) { return; + } //noinspection UnnecessaryLocalVariable Position newRef = position; this.doMoveTo(oldRef, newRef); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1031,49 +949,48 @@ protected void doMoveTo(Position oldRef, Position newRef) this.setAltitudes(altitudes[0] + elevDelta, altitudes[1] + elevDelta); } - protected Position computeReferencePosition(List locations, double[] altitudes) - { - if (locations == null) - { + protected Position computeReferencePosition(List locations, double[] altitudes) { + if (locations == null) { String message = "nullValue.LocationsIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (altitudes == null) - { + if (altitudes == null) { String message = "nullValue.AltitudesIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } int count = locations.size(); - if (count == 0) + if (count == 0) { return null; + } LatLon ll; - if (count < 3) + if (count < 3) { ll = locations.get(0); - else + } else { ll = locations.get(count / 2); + } return new Position(ll, altitudes[0]); } - protected double computeEyeDistance(DrawContext dc) - { + protected double computeEyeDistance(DrawContext dc) { AirspaceInfo info = this.currentInfo; - if (info == null || info.minimalGeometry == null || info.minimalGeometry.isEmpty()) + if (info == null || info.minimalGeometry == null || info.minimalGeometry.isEmpty()) { return 0.0; + } double minDistanceSquared = Double.MAX_VALUE; Vec4 eyePoint = dc.getView().getEyePoint(); - for (Vec4 point : info.minimalGeometry) - { + for (Vec4 point : info.minimalGeometry) { double d = point.distanceToSquared3(eyePoint); - if (d < minDistanceSquared) + if (d < minDistanceSquared) { minDistanceSquared = d; + } } return Math.sqrt(minDistanceSquared); @@ -1082,22 +999,19 @@ protected double computeEyeDistance(DrawContext dc) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - protected abstract void doRenderGeometry(DrawContext dc, String drawStyle); - protected void beginRendering(DrawContext dc) - { + protected void beginRendering(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); - if (!dc.isPickingMode()) - { - int attribMask = GL2.GL_COLOR_BUFFER_BIT // For color write mask, blending src and func, alpha func. - | GL2.GL_CURRENT_BIT // For current color. - | GL2.GL_LINE_BIT // For line width, line smoothing, line stipple. - | GL2.GL_POLYGON_BIT // For polygon offset. - | GL2.GL_TRANSFORM_BIT; // For matrix mode. + if (!dc.isPickingMode()) { + int attribMask = GL2.GL_COLOR_BUFFER_BIT // For color write mask, blending src and func, alpha func. + | GL2.GL_CURRENT_BIT // For current color. + | GL2.GL_LINE_BIT // For line width, line smoothing, line stipple. + | GL2.GL_POLYGON_BIT // For polygon offset. + | GL2.GL_TRANSFORM_BIT; // For matrix mode. gl.glPushAttrib(attribMask); // Setup blending for non-premultiplied colors. @@ -1106,23 +1020,19 @@ protected void beginRendering(DrawContext dc) // Setup standard lighting by default. This must be disabled by airspaces that don't enable lighting. dc.beginStandardLighting(); - } - else - { + } else { int attribMask = GL2.GL_CURRENT_BIT // For current color. - | GL2.GL_LINE_BIT; // For line width. + | GL2.GL_LINE_BIT; // For line width. gl.glPushAttrib(attribMask); } } - protected void endRendering(DrawContext dc) - { + protected void endRendering(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glDisableClientState(GL2.GL_VERTEX_ARRAY); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.endStandardLighting(); gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); // may have been enabled during rendering } @@ -1131,32 +1041,28 @@ protected void endRendering(DrawContext dc) } @SuppressWarnings("UnusedParameters") - protected boolean mustDrawInterior(DrawContext dc) - { + protected boolean mustDrawInterior(DrawContext dc) { return this.getActiveAttributes().isDrawInterior(); } - protected void drawInterior(DrawContext dc) - { + protected void drawInterior(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. AirspaceAttributes attrs = this.getActiveAttributes(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { if (attrs.isEnableLighting()) // Enable GL lighting state and set the current GL material state. { gl.glEnable(GL2.GL_LIGHTING); gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); attrs.getInteriorMaterial().apply(gl, GL2.GL_FRONT_AND_BACK, (float) attrs.getInteriorOpacity()); - } - else // Disable GL lighting state and set the current GL color state. + } else // Disable GL lighting state and set the current GL color state. { gl.glDisable(GL2.GL_LIGHTING); gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); Color sc = attrs.getInteriorMaterial().getDiffuse(); double opacity = attrs.getInteriorOpacity(); gl.glColor4ub((byte) sc.getRed(), (byte) sc.getGreen(), (byte) sc.getBlue(), - (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); + (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); } } @@ -1164,56 +1070,47 @@ protected void drawInterior(DrawContext dc) } @SuppressWarnings("UnusedParameters") - protected boolean mustDrawOutline(DrawContext dc) - { + protected boolean mustDrawOutline(DrawContext dc) { return this.getActiveAttributes().isDrawOutline(); } - protected void drawOutline(DrawContext dc) - { + protected void drawOutline(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. AirspaceAttributes attrs = this.getActiveAttributes(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Airspace outlines do not apply lighting. gl.glDisable(GL2.GL_LIGHTING); gl.glDisableClientState(GL2.GL_NORMAL_ARRAY); Color sc = attrs.getOutlineMaterial().getDiffuse(); double opacity = attrs.getOutlineOpacity(); gl.glColor4ub((byte) sc.getRed(), (byte) sc.getGreen(), (byte) sc.getBlue(), - (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); + (byte) (opacity < 1 ? (int) (opacity * 255 + 0.5) : 255)); - if (attrs.isEnableAntialiasing()) - { + if (attrs.isEnableAntialiasing()) { gl.glEnable(GL.GL_LINE_SMOOTH); - } - else - { + } else { gl.glDisable(GL.GL_LINE_SMOOTH); } } - if (dc.isPickingMode() && attrs.getOutlineWidth() < this.getOutlinePickWidth()) + if (dc.isPickingMode() && attrs.getOutlineWidth() < this.getOutlinePickWidth()) { gl.glLineWidth(this.getOutlinePickWidth()); - else + } else { gl.glLineWidth((float) attrs.getOutlineWidth()); + } - if (attrs.getOutlineStippleFactor() > 0) - { + if (attrs.getOutlineStippleFactor() > 0) { gl.glEnable(GL2.GL_LINE_STIPPLE); gl.glLineStipple(attrs.getOutlineStippleFactor(), attrs.getOutlineStipplePattern()); - } - else - { + } else { gl.glDisable(GL2.GL_LINE_STIPPLE); } this.doRenderGeometry(dc, Airspace.DRAW_STYLE_OUTLINE); } - protected void drawGeometry(DrawContext dc, Geometry indices, Geometry vertices) - { + protected void drawGeometry(DrawContext dc, Geometry indices, Geometry vertices) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. AirspaceAttributes attrs = this.getActiveAttributes(); @@ -1223,8 +1120,7 @@ protected void drawGeometry(DrawContext dc, Geometry indices, Geometry vertices) Buffer buffer = vertices.getBuffer(Geometry.VERTEX); gl.glVertexPointer(size, type, stride, buffer); - if (!dc.isPickingMode() && attrs.isEnableLighting()) - { + if (!dc.isPickingMode() && attrs.isEnableLighting()) { type = vertices.getGLType(Geometry.NORMAL); stride = vertices.getStride(Geometry.NORMAL); buffer = vertices.getBuffer(Geometry.NORMAL); @@ -1243,15 +1139,12 @@ protected void drawGeometry(DrawContext dc, Geometry indices, Geometry vertices) gl.glDrawRangeElements(mode, minElementIndex, maxElementIndex, count, type, buffer); } - protected GeometryBuilder getGeometryBuilder() - { + protected GeometryBuilder getGeometryBuilder() { return this.geometryBuilder; } - protected void setGeometryBuilder(GeometryBuilder gb) - { - if (gb == null) - { + protected void setGeometryBuilder(GeometryBuilder gb) { + if (gb == null) { String message = "nullValue.GeometryBuilderIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1260,84 +1153,77 @@ protected void setGeometryBuilder(GeometryBuilder gb) this.geometryBuilder = gb; } - protected DetailLevel computeDetailLevel(DrawContext dc) - { - if (dc == null) - { + protected DetailLevel computeDetailLevel(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Iterable detailLevels = this.getDetailLevels(); - if (detailLevels == null) + if (detailLevels == null) { return null; + } Iterator iter = detailLevels.iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return null; + } // Find the first detail level that meets rendering criteria. DetailLevel level = iter.next(); - while (iter.hasNext() && !level.meetsCriteria(dc, this)) - { + while (iter.hasNext() && !level.meetsCriteria(dc, this)) { level = iter.next(); } return level; } - protected MemoryCache getGeometryCache() - { + protected MemoryCache getGeometryCache() { return WorldWind.getMemoryCache(GEOMETRY_CACHE_KEY); } - protected boolean isExpired(DrawContext dc, Geometry geom) - { - if (dc == null) - { + protected boolean isExpired(DrawContext dc, Geometry geom) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (geom == null) - { + if (geom == null) { String message = "nullValue.AirspaceGeometryIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } Object o = geom.getValue(EXPIRY_TIME); - if (o != null && o instanceof Long && dc.getFrameTimeStamp() > (Long) o) + if (o != null && o instanceof Long && dc.getFrameTimeStamp() > (Long) o) { return true; + } o = geom.getValue(GLOBE_KEY); //noinspection RedundantIfStatement - if (o != null && !dc.getGlobe().getStateKey(dc).equals(o)) + if (o != null && !dc.getGlobe().getStateKey(dc).equals(o)) { return true; + } return false; } - protected void updateExpiryCriteria(DrawContext dc, Geometry geom) - { - if (dc == null) - { + protected void updateExpiryCriteria(DrawContext dc, Geometry geom) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1348,81 +1234,66 @@ protected void updateExpiryCriteria(DrawContext dc, Geometry geom) geom.setValue(GLOBE_KEY, dc.getGlobe().getStateKey(dc)); } - protected long getExpiryTime() - { + protected long getExpiryTime() { return this.expiryTime; } - protected void setExpiryTime(long timeMillis) - { + protected void setExpiryTime(long timeMillis) { this.expiryTime = timeMillis; } - protected long[] getExpiryRange() - { + protected long[] getExpiryRange() { long[] array = new long[2]; array[0] = this.minExpiryTime; array[1] = this.maxExpiryTime; return array; } - protected void setExpiryRange(long minTimeMillis, long maxTimeMillis) - { + protected void setExpiryRange(long minTimeMillis, long maxTimeMillis) { this.minExpiryTime = minTimeMillis; this.maxExpiryTime = maxTimeMillis; } - protected long nextExpiryTime(DrawContext dc, boolean[] terrainConformance) - { - if (dc == null) - { + protected long nextExpiryTime(DrawContext dc, boolean[] terrainConformance) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } long expiryTime; - if (terrainConformance[0] || terrainConformance[1]) - { + if (terrainConformance[0] || terrainConformance[1]) { long time = nextLong(this.minExpiryTime, this.maxExpiryTime); expiryTime = dc.getFrameTimeStamp() + time; - } - else - { + } else { expiryTime = -1L; } return expiryTime; } - private static long nextLong(long lo, long hi) - { + private static long nextLong(long lo, long hi) { long n = hi - lo + 1; long i = rand.nextLong() % n; return lo + ((i < 0) ? -i : i); } - protected void clearElevationMap() - { + protected void clearElevationMap() { this.elevationMap.clear(); } public Vec4 computePointFromPosition(DrawContext dc, Angle latitude, Angle longitude, double elevation, - boolean terrainConformant) - { - if (dc == null) - { + boolean terrainConformant) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (latitude == null || longitude == null) - { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1430,30 +1301,25 @@ public Vec4 computePointFromPosition(DrawContext dc, Angle latitude, Angle longi double newElevation = elevation; - if (terrainConformant) - { + if (terrainConformant) { newElevation += this.computeElevationAt(dc, latitude, longitude); } return dc.getGlobe().computePointFromPosition(latitude, longitude, newElevation); } - protected double computeElevationAt(DrawContext dc, Angle latitude, Angle longitude) - { - if (dc == null) - { + protected double computeElevationAt(DrawContext dc, Angle latitude, Angle longitude) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (latitude == null || longitude == null) - { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1468,19 +1334,15 @@ protected double computeElevationAt(DrawContext dc, Angle latitude, Angle longit latlon = new LatLon(latitude, longitude); elevation = this.elevationMap.get(latlon); - if (elevation == null) - { + if (elevation == null) { globe = dc.getGlobe(); elevation = 0.0; surfacePoint = dc.getPointOnTerrain(latitude, longitude); - if (surfacePoint != null) - { + if (surfacePoint != null) { surfacePos = globe.computePositionFromPoint(surfacePoint); elevation += surfacePos.getElevation(); - } - else - { + } else { elevation += dc.getVerticalExaggeration() * globe.getElevation(latitude, longitude); } @@ -1491,17 +1353,14 @@ protected double computeElevationAt(DrawContext dc, Angle latitude, Angle longit } protected void makeExtremePoints(Globe globe, double verticalExaggeration, Iterable locations, - List extremePoints) - { - if (globe == null) - { + List extremePoints) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (locations == null) - { + if (locations == null) { String message = "nullValue.LocationsIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1512,61 +1371,54 @@ protected void makeExtremePoints(Globe globe, double verticalExaggeration, Itera // If terrain conformance is enabled, add the minimum or maximum elevations around the locations to the // airspace's altitudes. - if (terrainConformant[0] || terrainConformant[1]) - { + if (terrainConformant[0] || terrainConformant[1]) { double[] extremeElevations = new double[2]; - if (LatLon.locationsCrossDateLine(locations)) - { + if (LatLon.locationsCrossDateLine(locations)) { Sector[] splitSector = Sector.splitBoundingSectors(locations); double[] a = globe.getMinAndMaxElevations(splitSector[0]); double[] b = globe.getMinAndMaxElevations(splitSector[1]); extremeElevations[0] = Math.min(a[0], b[0]); // Take the smallest min elevation. extremeElevations[1] = Math.max(a[1], b[1]); // Take the largest max elevation. - } - else - { + } else { Sector sector = Sector.boundingSector(locations); extremeElevations = globe.getMinAndMaxElevations(sector); } - if (terrainConformant[0]) + if (terrainConformant[0]) { altitudes[0] += extremeElevations[0]; + } - if (terrainConformant[1]) + if (terrainConformant[1]) { altitudes[1] += extremeElevations[1]; + } } // Get the points corresponding to the given locations at the lower and upper altitudes. - for (LatLon ll : locations) - { + for (LatLon ll : locations) { extremePoints.add(globe.computePointFromPosition(ll.getLatitude(), ll.getLongitude(), - verticalExaggeration * altitudes[0])); + verticalExaggeration * altitudes[0])); extremePoints.add(globe.computePointFromPosition(ll.getLatitude(), ll.getLongitude(), - verticalExaggeration * altitudes[1])); + verticalExaggeration * altitudes[1])); } } //**************************************************************// //******************** END Geometry Rendering *****************// //**************************************************************// - - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { // Method is invoked by subclasses to have superclass add its state and only its state this.doMyGetRestorableState(rs, context); } - private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { rs.addStateValueAsBoolean(context, "visible", this.isVisible()); rs.addStateValueAsBoolean(context, "highlighted", this.isHighlighted()); rs.addStateValueAsDouble(context, "lowerAltitude", this.getAltitudes()[0]); @@ -1575,8 +1427,9 @@ private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsBoolean(context, "upperTerrainConforming", this.isTerrainConforming()[1]); rs.addStateValueAsString(context, "lowerAltitudeDatum", this.getAltitudeDatum()[0]); rs.addStateValueAsString(context, "upperAltitudeDatum", this.getAltitudeDatum()[1]); - if (this.getGroundReference() != null) + if (this.getGroundReference() != null) { rs.addStateValueAsLatLon(context, "groundReference", this.getGroundReference()); + } rs.addStateValueAsBoolean(context, "enableBatchRendering", this.isEnableBatchRendering()); rs.addStateValueAsBoolean(context, "enableBatchPicking", this.isEnableBatchPicking()); rs.addStateValueAsBoolean(context, "enableDepthOffset", this.isEnableDepthOffset()); @@ -1585,29 +1438,26 @@ private void doMyGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsBoolean(context, "drawSurfaceShape", this.isDrawSurfaceShape()); rs.addStateValueAsBoolean(context, "enableLevelOfDetail", this.isEnableLevelOfDetail()); - if (this.attributes != null) + if (this.attributes != null) { this.attributes.getRestorableState(rs, rs.addStateObject(context, "attributes")); + } - if (this.highlightAttributes != null) + if (this.highlightAttributes != null) { this.highlightAttributes.getRestorableState(rs, rs.addStateObject(context, "highlightAttributes")); + } } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -1617,90 +1467,106 @@ public void restoreState(String stateInXml) this.doRestoreState(rs, null); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Method is invoked by subclasses to have superclass add its state and only its state this.doMyRestoreState(rs, context); } - private void doMyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + private void doMyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { Boolean booleanState = rs.getStateValueAsBoolean(context, "visible"); - if (booleanState != null) + if (booleanState != null) { this.setVisible(booleanState); + } booleanState = rs.getStateValueAsBoolean(context, "highlighted"); - if (booleanState != null) + if (booleanState != null) { this.setHighlighted(booleanState); + } Double lo = rs.getStateValueAsDouble(context, "lowerAltitude"); - if (lo == null) + if (lo == null) { lo = this.getAltitudes()[0]; + } Double hi = rs.getStateValueAsDouble(context, "upperAltitude"); - if (hi == null) + if (hi == null) { hi = this.getAltitudes()[1]; + } this.setAltitudes(lo, hi); Boolean loConform = rs.getStateValueAsBoolean(context, "lowerTerrainConforming"); - if (loConform == null) + if (loConform == null) { loConform = this.isTerrainConforming()[0]; + } Boolean hiConform = rs.getStateValueAsBoolean(context, "upperTerrainConforming"); - if (hiConform == null) + if (hiConform == null) { hiConform = this.isTerrainConforming()[1]; + } this.setTerrainConforming(loConform, hiConform); String lowerDatum = rs.getStateValueAsString(context, "lowerAltitudeDatum"); - if (lowerDatum == null) + if (lowerDatum == null) { lowerDatum = this.getAltitudeDatum()[0]; + } String upperDatum = rs.getStateValueAsString(context, "upperAltitudeDatum"); - if (upperDatum == null) + if (upperDatum == null) { upperDatum = this.getAltitudeDatum()[1]; + } this.setAltitudeDatum(lowerDatum, upperDatum); LatLon groundRef = rs.getStateValueAsLatLon(context, "groundReference"); - if (groundRef != null) + if (groundRef != null) { this.setGroundReference(groundRef); + } booleanState = rs.getStateValueAsBoolean(context, "enableBatchRendering"); - if (booleanState != null) + if (booleanState != null) { this.setEnableBatchRendering(booleanState); + } booleanState = rs.getStateValueAsBoolean(context, "enableBatchPicking"); - if (booleanState != null) + if (booleanState != null) { this.setEnableBatchPicking(booleanState); + } booleanState = rs.getStateValueAsBoolean(context, "enableDepthOffset"); - if (booleanState != null) + if (booleanState != null) { this.setEnableDepthOffset(booleanState); + } Integer intState = rs.getStateValueAsInteger(context, "outlinePickWidth"); - if (intState != null) + if (intState != null) { this.setOutlinePickWidth(intState); + } booleanState = rs.getStateValueAsBoolean(context, "alwaysOnTop"); - if (booleanState != null) + if (booleanState != null) { this.setAlwaysOnTop(booleanState); + } booleanState = rs.getStateValueAsBoolean(context, "drawSurfaceShape"); - if (booleanState != null) + if (booleanState != null) { this.setDrawSurfaceShape(booleanState); + } booleanState = rs.getStateValueAsBoolean(context, "enableLevelOfDetail"); - if (booleanState != null) + if (booleanState != null) { this.setEnableLevelOfDetail(booleanState); + } RestorableSupport.StateObject so = rs.getStateObject(context, "attributes"); - if (so != null) + if (so != null) { this.getAttributes().restoreState(rs, so); + } so = rs.getStateObject(context, "highlightAttributes"); - if (so != null) + if (so != null) { this.getHighlightAttributes().restoreState(rs, so); + } } } diff --git a/src/gov/nasa/worldwind/render/airspaces/Airspace.java b/src/gov/nasa/worldwind/render/airspaces/Airspace.java index 4bcf027170..a608c33d96 100644 --- a/src/gov/nasa/worldwind/render/airspaces/Airspace.java +++ b/src/gov/nasa/worldwind/render/airspaces/Airspace.java @@ -17,8 +17,8 @@ * @author dcollins * @version $Id: Airspace.java 2394 2014-10-22 01:16:43Z tgaskins $ */ -public interface Airspace extends Renderable, Restorable, AVList, ExtentHolder, Highlightable, Attributable -{ +public interface Airspace extends Renderable, Restorable, AVList, ExtentHolder, Highlightable, Attributable { + public static final String DRAW_STYLE_FILL = "Airspace.DrawStyleFill"; public static final String DRAW_STYLE_OUTLINE = "Airspace.DrawStyleOutline"; @@ -98,13 +98,13 @@ public interface Airspace extends Renderable, Restorable, AVList, ExtentHolder, * argument descriptions below for the mapping of the boolean values of this method to the altitude-datum values. * * @param lowerTerrainConformant the lower altitude datum. A value of true indicates a lower altitude datum of - * {@link AVKey#ABOVE_GROUND_LEVEL} (terrain conforming), a value of false indicates a - * lower altitude datum of {link AVKey#ABOVE_MEAN_SEA_LEVEL} (not terrain conforming). - * the terrain-conforming, a value of false indicates that it's not. + * {@link AVKey#ABOVE_GROUND_LEVEL} (terrain conforming), a value of false indicates a lower altitude datum of {link + * AVKey#ABOVE_MEAN_SEA_LEVEL} (not terrain conforming). the terrain-conforming, a value of false indicates that + * it's not. * @param upperTerrainConformant the upper altitude datum. A value of true indicates an upper altitude datum of - * {@link AVKey#ABOVE_GROUND_LEVEL} (terrain conforming), a value of false indicates - * an upper altitude datum of {link AVKey#ABOVE_MEAN_SEA_LEVEL} (not terrain - * conforming. the terrain-conforming, a value of false indicates that it's not. + * {@link AVKey#ABOVE_GROUND_LEVEL} (terrain conforming), a value of false indicates an upper altitude datum of + * {link AVKey#ABOVE_MEAN_SEA_LEVEL} (not terrain conforming. the terrain-conforming, a value of false indicates + * that it's not. * * @see #setAltitudeDatum(String, String) */ @@ -125,7 +125,7 @@ public interface Airspace extends Renderable, Restorable, AVList, ExtentHolder, * gov.nasa.worldwind.render.airspaces.Cake} airspaces. * * @param alwaysOnTop if true, this airspace is drawn after all others. Otherwise this airspace is - * drawn with its normal priority, which is its relative distance to the eye point. + * drawn with its normal priority, which is its relative distance to the eye point. */ void setAlwaysOnTop(boolean alwaysOnTop); @@ -141,7 +141,7 @@ public interface Airspace extends Renderable, Restorable, AVList, ExtentHolder, * specified in the shape. * * @param drawSurfaceShape true if this shape is drawn flat and on the surface, otherwise - * false. + * false. */ void setDrawSurfaceShape(boolean drawSurfaceShape); @@ -152,7 +152,7 @@ public interface Airspace extends Renderable, Restorable, AVList, ExtentHolder, * the boolean values of this method to the altitude-datum values. * * @param terrainConformant the altitude datum. See {@link #setTerrainConforming(boolean, boolean)} for a - * description of the possible values. + * description of the possible values. */ void setTerrainConforming(boolean terrainConformant); @@ -180,7 +180,7 @@ public interface Airspace extends Renderable, Restorable, AVList, ExtentHolder, * a specified {@link gov.nasa.worldwind.globes.Globe} and vertical exaggeration (see {@link * gov.nasa.worldwind.SceneController#getVerticalExaggeration()}. * - * @param globe the Globe this Airspace is related to. + * @param globe the Globe this Airspace is related to. * @param verticalExaggeration the vertical exaggeration of the scene containing this Airspace. * * @return this Airspace's Extent in model coordinates. @@ -253,9 +253,9 @@ public interface Airspace extends Renderable, Restorable, AVList, ExtentHolder, * than this. * * @param groundReference the location at which to compute the terrain elevation used to offset an upper or lower - * airspace surface. The location need not be within the airspace's bounds. If null, an - * airspace-specific position is chosen from those defining the airspace. See the method - * descriptions for the individual airspaces to determine the position used. + * airspace surface. The location need not be within the airspace's bounds. If null, an airspace-specific position + * is chosen from those defining the airspace. See the method descriptions for the individual airspaces to determine + * the position used. * * @see #setAltitudeDatum(String, String) */ diff --git a/src/gov/nasa/worldwind/render/airspaces/AirspaceAttributes.java b/src/gov/nasa/worldwind/render/airspaces/AirspaceAttributes.java index 107b79a691..556938f065 100644 --- a/src/gov/nasa/worldwind/render/airspaces/AirspaceAttributes.java +++ b/src/gov/nasa/worldwind/render/airspaces/AirspaceAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.render.*; @@ -18,8 +17,8 @@ * @author dcollins * @version $Id: AirspaceAttributes.java 2222 2014-08-13 21:25:29Z dcollins $ */ -public interface AirspaceAttributes extends ShapeAttributes -{ +public interface AirspaceAttributes extends ShapeAttributes { + /** * Get the Material used to draw the shape interior or volume. This method is deprecated, and should be * replaced with usage of {@link #getInteriorMaterial()}. @@ -45,7 +44,7 @@ public interface AirspaceAttributes extends ShapeAttributes * #getInteriorOpacity()}. * * @return the shape's opacity in the range [0, 1], where 0 indicates full transparency and 1 indicates full - * opacity. + * opacity. * * @deprecated Use {@link #getInteriorOpacity()} instead. */ @@ -56,7 +55,7 @@ public interface AirspaceAttributes extends ShapeAttributes * #setInteriorOpacity(double)}. * * @param opacity the shape's opacity in the range [0, 1], where 0 indicates full transparency and 1 indicates full - * opacity. + * opacity. * * @deprecated Use {@link #setInteriorOpacity(double)} instead. */ @@ -67,7 +66,7 @@ public interface AirspaceAttributes extends ShapeAttributes * OpenGL material state with the interior material and the interior opacity. Otherwise, this sets the current * OpenGL color state to the interior material's diffuse color. * - * @param dc the current drawing context. + * @param dc the current drawing context. * @param enableMaterial true to set OpenGL material state, false to set OpenGL color state. * * @throws IllegalArgumentException if the drawing context is null. @@ -80,7 +79,7 @@ public interface AirspaceAttributes extends ShapeAttributes * OpenGL material state with the outline material and the outline opacity. Otherwise, this sets the current OpenGL * color state to the outline material's diffuse color. * - * @param dc the current drawing context. + * @param dc the current drawing context. * @param enableMaterial true to set OpenGL material state, false to set OpenGL color state. * * @throws IllegalArgumentException if the drawing context is null. diff --git a/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java b/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java index cc0403e360..b02bbe2fbd 100644 --- a/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java +++ b/src/gov/nasa/worldwind/render/airspaces/BasicAirspaceAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.render.*; @@ -21,14 +20,16 @@ * @author tag * @version $Id: BasicAirspaceAttributes.java 2318 2014-09-17 18:26:33Z tgaskins $ */ -public class BasicAirspaceAttributes extends BasicShapeAttributes implements AirspaceAttributes -{ +public class BasicAirspaceAttributes extends BasicShapeAttributes implements AirspaceAttributes { + /** * Creates a new BasicAirspaceAttributes with the default attributes. The default attributes differ from * BasicShapeAttributes, and are as follows: - * + *
          Default Attributes
          AttributeDefault Value
          unresolvedtrue
          * - * + * + * * * * @@ -36,8 +37,7 @@ public class BasicAirspaceAttributes extends BasicShapeAttributes implements Air * *
          Default Attributes
          AttributeDefault + * Value
          unresolvedtrue
          drawInteriortrue
          drawOutlinefalse
          enableAntialiasingfalse
          enableLightingtrue
          enableAntialiasingfalse
          enableLightingtrue
          interiorMaterial{@link gov.nasa.worldwind.render.Material#WHITE}
          outlineMaterial{@link gov.nasa.worldwind.render.Material#BLACK}
          interiorOpacity1.0
          outlineOpacity1.0
          outlineStipplePattern0xF0F0
          imageSourcenull
          imageScale1.0
          */ - public BasicAirspaceAttributes() - { + public BasicAirspaceAttributes() { // Configure this AirspaceAttributes to preserve the original defaults of BasicAirspaceAttributes and // AirspaceRenderer. @@ -49,29 +49,28 @@ public BasicAirspaceAttributes() /** * Creates a new BasicAirspaceAttributes with the specified interior material and interior opacity. All other * attributes are set to the default values, which differ from BasicShapeAttributes, and are as follows: - * + *
          Default Attributes
          AttributeDefault Value
          unresolvedtrue
          * - * + * + * * * * *
          Default Attributes
          AttributeDefault + * Value
          unresolvedtrue
          drawInteriortrue
          drawOutlinefalse
          enableAntialiasingfalse
          enableLightingtrue
          enableAntialiasingfalse
          enableLightingtrue
          interiorMaterialmaterial
          outlineMaterial{@link * gov.nasa.worldwind.render.Material#BLACK}
          interiorOpacityopacity
          outlineOpacity1.0
          outlineWidth1.0
          outlineStippleFactor0
          outlineStipplePattern0xF0F0
          imageSourcenull
          imageScale1.0
          - * + * * @param material Material to apply. * @param opacity the opacity to set. */ - public BasicAirspaceAttributes(Material material, double opacity) - { - if (material == null) - { + public BasicAirspaceAttributes(Material material, double opacity) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (opacity < 0.0 || opacity > 1.0) - { + if (opacity < 0.0 || opacity > 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "opacity=" + opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -79,7 +78,6 @@ public BasicAirspaceAttributes(Material material, double opacity) // Configure this AirspaceAttributes to preserve the original defaults of BasicAirspaceAttributes and // AirspaceRenderer. - this.drawOutline = false; this.enableAntialiasing = false; this.enableLighting = true; @@ -95,8 +93,7 @@ public BasicAirspaceAttributes(Material material, double opacity) * * @throws IllegalArgumentException if attributes is null. */ - public BasicAirspaceAttributes(ShapeAttributes attributes) - { + public BasicAirspaceAttributes(ShapeAttributes attributes) { super(attributes); } @@ -107,20 +104,21 @@ public BasicAirspaceAttributes(ShapeAttributes attributes) * * @throws IllegalArgumentException if attributes is null. */ - public BasicAirspaceAttributes(AirspaceAttributes attributes) - { + public BasicAirspaceAttributes(AirspaceAttributes attributes) { super(attributes); } - /** {@inheritDoc} */ - public AirspaceAttributes copy() - { + /** + * {@inheritDoc} + */ + public AirspaceAttributes copy() { return new BasicAirspaceAttributes(this); } - /** {@inheritDoc} */ - public void copy(AirspaceAttributes attributes) - { + /** + * {@inheritDoc} + */ + public void copy(AirspaceAttributes attributes) { super.copy(attributes); } @@ -129,8 +127,7 @@ public void copy(AirspaceAttributes attributes) * * @deprecated Use {@link #getInteriorMaterial()} instead. */ - public Material getMaterial() - { + public Material getMaterial() { return this.getInteriorMaterial(); } @@ -139,10 +136,8 @@ public Material getMaterial() * * @deprecated Use {@link #setInteriorMaterial(gov.nasa.worldwind.render.Material)} instead. */ - public void setMaterial(Material material) - { - if (material == null) - { + public void setMaterial(Material material) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -156,8 +151,7 @@ public void setMaterial(Material material) * * @deprecated Use {@link #getInteriorOpacity()} instead. */ - public double getOpacity() - { + public double getOpacity() { return this.getInteriorOpacity(); } @@ -166,10 +160,8 @@ public double getOpacity() * * @deprecated Use {@link #setInteriorOpacity(double)} instead. */ - public void setOpacity(double opacity) - { - if (opacity < 0 || opacity > 1) - { + public void setOpacity(double opacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -183,10 +175,8 @@ public void setOpacity(double opacity) * * @deprecated Use {@link Material#apply(com.jogamp.opengl.GL2, int)} or make OpenGL state changes directly. */ - public void applyInterior(DrawContext dc, boolean enableMaterial) - { - if (dc == null) - { + public void applyInterior(DrawContext dc, boolean enableMaterial) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -200,10 +190,8 @@ public void applyInterior(DrawContext dc, boolean enableMaterial) * * @deprecated Use {@link Material#apply(com.jogamp.opengl.GL2, int)} or make OpenGL state changes directly. */ - public void applyOutline(DrawContext dc, boolean enableMaterial) - { - if (dc == null) - { + public void applyOutline(DrawContext dc, boolean enableMaterial) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -215,39 +203,36 @@ public void applyOutline(DrawContext dc, boolean enableMaterial) gl.glLineWidth((float) this.getOutlineWidth()); } - /** {@inheritDoc} */ - public void restoreState(RestorableSupport rs, RestorableSupport.StateObject so) - { + /** + * {@inheritDoc} + */ + public void restoreState(RestorableSupport rs, RestorableSupport.StateObject so) { super.restoreState(rs, so); this.restoreDeprecatedState(rs, so); } - protected void restoreDeprecatedState(RestorableSupport rs, RestorableSupport.StateObject so) - { + protected void restoreDeprecatedState(RestorableSupport rs, RestorableSupport.StateObject so) { // Restore deprecated interior material state used prior to integration with ShapeAttributes. RestorableSupport.StateObject mo = rs.getStateObject(so, "material"); - if (mo != null) + if (mo != null) { this.setInteriorMaterial(this.getInteriorMaterial().restoreState(rs, mo)); + } // Restore deprecated interior opacity state used prior to integration with ShapeAttributes. Double d = rs.getStateValueAsDouble(so, "opacity"); - if (d != null) + if (d != null) { this.setInteriorOpacity(d); + } } - protected void applyMaterial(DrawContext dc, Material material, double opacity, boolean enableMaterial) - { + protected void applyMaterial(DrawContext dc, Material material, double opacity, boolean enableMaterial) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (material != null) - { - if (enableMaterial) - { + if (material != null) { + if (enableMaterial) { material.apply(gl, GL2.GL_FRONT_AND_BACK, (float) opacity); - } - else - { + } else { float[] compArray = new float[4]; material.getDiffuse().getRGBComponents(compArray); compArray[3] = (float) opacity; diff --git a/src/gov/nasa/worldwind/render/airspaces/Box.java b/src/gov/nasa/worldwind/render/airspaces/Box.java index 9a534e6e86..2ca5cc0227 100644 --- a/src/gov/nasa/worldwind/render/airspaces/Box.java +++ b/src/gov/nasa/worldwind/render/airspaces/Box.java @@ -20,8 +20,8 @@ * @author lado * @version $Id: Box.java 2563 2014-12-12 19:29:38Z dcollins $ */ -public class Box extends AbstractAirspace -{ +public class Box extends AbstractAirspace { + protected static final int DEFAULT_PILLARS = 8; protected static final int DEFAULT_STACKS = 2; @@ -47,24 +47,20 @@ public class Box extends AbstractAirspace private Object geometryCacheKey = new Object(); - public Box(LatLon beginLocation, LatLon endLocation, double leftWidth, double rightWidth) - { - if (beginLocation == null || endLocation == null) - { + public Box(LatLon beginLocation, LatLon endLocation, double leftWidth, double rightWidth) { + if (beginLocation == null || endLocation == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (leftWidth < 0) - { + if (leftWidth < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "leftWidth < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rightWidth < 0) - { + if (rightWidth < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "rightWidth < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -77,8 +73,7 @@ public Box(LatLon beginLocation, LatLon endLocation, double leftWidth, double ri this.makeDefaultDetailLevels(); } - public Box(Box source) - { + public Box(Box source) { super(source); this.beginLocation = source.beginLocation; @@ -99,19 +94,16 @@ public Box(Box source) this.makeDefaultDetailLevels(); } - public Box(AirspaceAttributes attributes) - { + public Box(AirspaceAttributes attributes) { super(attributes); this.makeDefaultDetailLevels(); } - public Box() - { + public Box() { this.makeDefaultDetailLevels(); } - private void makeDefaultDetailLevels() - { + private void makeDefaultDetailLevels() { List levels = new ArrayList(); double[] ramp = ScreenSizeDetailLevel.computeDefaultScreenSizeRamp(5); @@ -149,9 +141,8 @@ private void makeDefaultDetailLevels() this.setDetailLevels(levels); } - public LatLon[] getLocations() - { - return new LatLon[] {this.beginLocation, this.endLocation}; + public LatLon[] getLocations() { + return new LatLon[]{this.beginLocation, this.endLocation}; } /** @@ -162,10 +153,8 @@ public LatLon[] getLocations() * * @throws IllegalArgumentException if location1 or location2 is null */ - public void setLocations(LatLon beginLocation, LatLon endLocation) - { - if (beginLocation == null || endLocation == null) - { + public void setLocations(LatLon beginLocation, LatLon endLocation) { + if (beginLocation == null || endLocation == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -176,24 +165,20 @@ public void setLocations(LatLon beginLocation, LatLon endLocation) this.invalidateGeometry(); } - public double[] getWidths() - { + public double[] getWidths() { double[] array = new double[2]; array[0] = this.leftWidth; array[1] = this.rightWidth; return array; } - public void setWidths(double leftWidth, double rightWidth) - { - if (leftWidth < 0.0) - { + public void setWidths(double leftWidth, double rightWidth) { + if (leftWidth < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "leftWidth=" + leftWidth); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rightWidth < 0.0) - { + if (rightWidth < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "rightWidth=" + rightWidth); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -211,23 +196,21 @@ public void setWidths(double leftWidth, double rightWidth) * * @return an array of length four indicating this box's corner azimuths. */ - public Angle[] getCornerAzimuths() - { - return new Angle[] {this.beginLeftAzimuth, this.beginRightAzimuth, this.endLeftAzimuth, this.endRightAzimuth}; + public Angle[] getCornerAzimuths() { + return new Angle[]{this.beginLeftAzimuth, this.beginRightAzimuth, this.endLeftAzimuth, this.endRightAzimuth}; } /** - * Specifies the azimuth angles for this box's four corners, relative to geographic north. Specifying a null + * Specifies the azimuth angles for this box's four corners, relative to geographic north. Specifying a null * argument indicates that the default angle should be used. - * + * * @param beginLeftAzimuth Beginning left corner azimuth. * @param beginRightAzimuth Beginning right corner azimuth. * @param endLeftAzimuth Ending left corner azimuth. * @param endRightAzimuth Ending right corner azimuth. */ public void setCornerAzimuths(Angle beginLeftAzimuth, Angle beginRightAzimuth, Angle endLeftAzimuth, - Angle endRightAzimuth) - { + Angle endRightAzimuth) { this.beginLeftAzimuth = beginLeftAzimuth; this.beginRightAzimuth = beginRightAzimuth; this.endLeftAzimuth = endLeftAzimuth; @@ -235,71 +218,61 @@ public void setCornerAzimuths(Angle beginLeftAzimuth, Angle beginRightAzimuth, A this.invalidateGeometry(); } - public boolean[] isEnableCaps() - { + public boolean[] isEnableCaps() { boolean[] array = new boolean[2]; array[0] = this.enableStartCap; array[1] = this.enableEndCap; return array; } - public void setEnableCaps(boolean enableStartCap, boolean enableEndCap) - { + public void setEnableCaps(boolean enableStartCap, boolean enableEndCap) { this.enableStartCap = enableStartCap; this.enableEndCap = enableEndCap; this.invalidateGeometry(); } - public void setEnableCaps(boolean enable) - { + public void setEnableCaps(boolean enable) { this.setEnableCaps(enable, enable); } - public void setEnableStartCap(boolean enable) - { + public void setEnableStartCap(boolean enable) { this.setEnableCaps(enable, this.enableEndCap); } - public void setEnableEndCap(boolean enable) - { + public void setEnableEndCap(boolean enable) { this.setEnableCaps(this.enableStartCap, enable); } - public boolean isEnableCenterLine() - { + public boolean isEnableCenterLine() { return this.enableCenterLine; } - public void setEnableCenterLine(boolean enable) - { + public void setEnableCenterLine(boolean enable) { this.enableCenterLine = enable; this.invalidateGeometry(); } - public Position getReferencePosition() - { + public Position getReferencePosition() { double[] altitudes = this.getAltitudes(); return new Position(this.beginLocation, altitudes[0]); } - protected void invalidateGeometry() - { + protected void invalidateGeometry() { this.invalidateAirspaceData(); this.geometryCacheKey = new Object(); } - protected gov.nasa.worldwind.geom.Box computeExtent(Globe globe, double verticalExaggeration) - { + protected gov.nasa.worldwind.geom.Box computeExtent(Globe globe, double verticalExaggeration) { List points = this.computeMinimalGeometry(globe, verticalExaggeration); - if (points == null || points.isEmpty()) + if (points == null || points.isEmpty()) { return null; + } return gov.nasa.worldwind.geom.Box.computeBoundingBox(points); } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { List locations = this.makeCapLocations(globe, DEFAULT_PILLARS, DEFAULT_STACKS); List points = new ArrayList(); this.makeExtremePoints(globe, verticalExaggeration, locations, points); @@ -308,14 +281,12 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return new SurfaceBox(); } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { int lengthSegments = this.getPillars(); int widthSegments = this.getStacks(); List locations = this.makeSideLocations(dc.getGlobe(), lengthSegments, widthSegments); @@ -327,16 +298,13 @@ protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) ((SurfaceBox) shape).setEnableCenterLine(this.isEnableCenterLine()); } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -352,16 +320,13 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) super.doMoveTo(oldRef, newRef); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -371,8 +336,7 @@ protected void doMoveTo(Position oldRef, Position newRef) LatLon[] locations = this.getLocations(); int count = locations.length; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { double distance = LatLon.greatCircleDistance(oldRef, locations[i]).radians; double azimuth = LatLon.greatCircleAzimuth(oldRef, locations[i]).radians; locations[i] = LatLon.greatCircleEndPosition(newRef, azimuth, distance); @@ -380,25 +344,20 @@ protected void doMoveTo(Position oldRef, Position newRef) this.setLocations(locations[0], locations[1]); } - protected boolean isForceCullFace() - { + protected boolean isForceCullFace() { return this.forceCullFace; } - protected void setForceCullFace(boolean forceCullFace) - { + protected void setForceCullFace(boolean forceCullFace) { this.forceCullFace = forceCullFace; } - protected int getPillars() - { + protected int getPillars() { return this.pillars; } - protected void setPillars(int pillars) - { - if (pillars < 0) - { + protected void setPillars(int pillars) { + if (pillars < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pillars=" + pillars); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -407,15 +366,12 @@ protected void setPillars(int pillars) this.pillars = pillars; } - protected int getStacks() - { + protected int getStacks() { return this.stacks; } - protected void setStacks(int stacks) - { - if (stacks < 0) - { + protected void setStacks(int stacks) { + if (stacks < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -424,31 +380,25 @@ protected void setStacks(int stacks) this.stacks = stacks; } - protected int getHeightStacks() - { + protected int getHeightStacks() { return 1; } //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected Vec4 computeReferenceCenter(DrawContext dc) - { + protected Vec4 computeReferenceCenter(DrawContext dc) { Extent extent = this.getExtent(dc); return extent != null ? extent.getCenter() : null; } - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { - if (dc == null) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -459,21 +409,23 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) int lengthSegments = this.getPillars(); int widthSegments = this.getStacks(); - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(PILLARS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { lengthSegments = (Integer) o; + } o = level.getValue(STACKS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { widthSegments = (Integer) o; + } o = level.getValue(DISABLE_TERRAIN_CONFORMANCE); - if (o != null && o instanceof Boolean && (Boolean) o) + if (o != null && o instanceof Boolean && (Boolean) o) { terrainConformant[0] = terrainConformant[1] = false; + } } this.setExpiryTime(this.nextExpiryTime(dc, this.isTerrainConforming())); @@ -481,37 +433,28 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { - if (this.forceCullFace || !this.enableStartCap || !this.enableEndCap) - { + try { + if (this.forceCullFace || !this.enableStartCap || !this.enableEndCap) { ogsh.pushAttrib(gl, GL2.GL_POLYGON_BIT); gl.glEnable(GL.GL_CULL_FACE); gl.glFrontFace(GL.GL_CCW); } - if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) - { + if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) { this.drawBox(dc, altitudes, terrainConformant, lengthSegments, widthSegments); - } - else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) - { + } else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) { this.drawBoxOutline(dc, altitudes, terrainConformant, lengthSegments, widthSegments); - if (this.enableCenterLine) - { + if (this.enableCenterLine) { this.drawBoxCenterLine(dc, altitudes, terrainConformant, lengthSegments, widthSegments); } } - } - finally - { + } finally { ogsh.pop(gl); } } - protected void applyCenterLineState(DrawContext dc) - { + protected void applyCenterLineState(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. AirspaceAttributes attrs = this.getActiveAttributes(); @@ -525,9 +468,8 @@ protected void applyCenterLineState(DrawContext dc) //**************************************************************// //******************** Box ***********************************// //**************************************************************// + private static class BoxGeometry implements Cacheable { - private static class BoxGeometry implements Cacheable - { public Geometry sideGeometry = new Geometry(); public Geometry capGeometry = new Geometry(); public Geometry outlineIndices = new Geometry(); @@ -535,17 +477,16 @@ private static class BoxGeometry implements Cacheable public Vec4 referencePoint; @Override - public long getSizeInBytes() - { + public long getSizeInBytes() { return this.sideGeometry.getSizeInBytes() - + this.capGeometry.getSizeInBytes() - + this.outlineIndices.getSizeInBytes() - + this.centerLineIndices.getSizeInBytes(); + + this.capGeometry.getSizeInBytes() + + this.outlineIndices.getSizeInBytes() + + this.centerLineIndices.getSizeInBytes(); } } - private static class BoxCorners - { + private static class BoxCorners { + public LatLon beginLeft; public LatLon beginRight; public LatLon endLeft; @@ -561,66 +502,55 @@ private static class BoxCorners } private void drawBox(DrawContext dc, double[] altitudes, boolean[] terrainConformant, int lengthSegments, - int widthSegments) - { + int widthSegments) { BoxGeometry geom = this.getBoxGeometry(dc, altitudes, terrainConformant, lengthSegments, widthSegments); - try - { + try { dc.getView().pushReferenceCenter(dc, geom.referencePoint); this.drawGeometry(dc, geom.sideGeometry, geom.sideGeometry); this.drawGeometry(dc, geom.capGeometry, geom.capGeometry); - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); } } private void drawBoxOutline(DrawContext dc, double[] altitudes, boolean[] terrainConformant, int lengthSegments, - int widthSegments) - { + int widthSegments) { BoxGeometry geom = this.getBoxGeometry(dc, altitudes, terrainConformant, lengthSegments, widthSegments); - try - { + try { dc.getView().pushReferenceCenter(dc, geom.referencePoint); this.drawGeometry(dc, geom.outlineIndices, geom.sideGeometry); - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); } } private void drawBoxCenterLine(DrawContext dc, double[] altitudes, boolean[] terrainConformant, int lengthSegments, - int widthSegments) - { + int widthSegments) { BoxGeometry geom = this.getBoxGeometry(dc, altitudes, terrainConformant, lengthSegments, widthSegments); - try - { + try { dc.getView().pushReferenceCenter(dc, geom.referencePoint); dc.pushProjectionOffest(DEFAULT_CENTER_LINE_OFFSET); // move center line depth slightly in front of fill this.applyCenterLineState(dc); this.drawGeometry(dc, geom.centerLineIndices, geom.capGeometry); - } - finally - { + } finally { dc.popProjectionOffest(); dc.getView().popReferenceCenter(dc); } } private BoxGeometry getBoxGeometry(DrawContext dc, double[] altitudes, boolean[] terrainConformant, - int lengthSegments, int widthSegments) - { + int lengthSegments, int widthSegments) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "Box.Geometry", this.geometryCacheKey, - altitudes, terrainConformant, lengthSegments, widthSegments); + altitudes, terrainConformant, lengthSegments, widthSegments); BoxGeometry geom = (BoxGeometry) this.getGeometryCache().getObject(cacheKey); - if (geom != null && !this.isExpired(dc, geom.sideGeometry)) + if (geom != null && !this.isExpired(dc, geom.sideGeometry)) { return geom; + } - if (geom == null) + if (geom == null) { geom = new BoxGeometry(); + } this.makeBoxGeometry(dc, altitudes, terrainConformant, lengthSegments, widthSegments, geom); this.updateExpiryCriteria(dc, geom.sideGeometry); @@ -630,16 +560,14 @@ private BoxGeometry getBoxGeometry(DrawContext dc, double[] altitudes, boolean[] } private void makeBoxGeometry(DrawContext dc, double[] altitudes, boolean[] terrainConformant, int lengthSegments, - int widthSegments, BoxGeometry geom) - { + int widthSegments, BoxGeometry geom) { geom.referencePoint = this.computeReferenceCenter(dc); this.makeSideGeometry(dc.getTerrain(), altitudes, terrainConformant, lengthSegments, widthSegments, geom); this.makeCapGeometry(dc.getTerrain(), altitudes, terrainConformant, lengthSegments, widthSegments, geom); } private void makeSideGeometry(Terrain terrain, double[] altitudes, boolean[] terrainConformant, int lengthSegments, - int widthSegments, BoxGeometry geom) - { + int widthSegments, BoxGeometry geom) { List locations = this.makeSideLocations(terrain.getGlobe(), lengthSegments, widthSegments); // Compute model coordinate vertex points. @@ -647,13 +575,12 @@ private void makeSideGeometry(Terrain terrain, double[] altitudes, boolean[] ter float[] pointArray = new float[3 * vertexCount]; FloatBuffer pointBuffer = FloatBuffer.wrap(pointArray); - for (LatLon ll : locations) - { + for (LatLon ll : locations) { for (int i = 1; i >= 0; i--) // upper altitude then lower altitude { - Vec4 p = terrainConformant[i] ? - terrain.getSurfacePoint(ll.latitude, ll.longitude, altitudes[i]) : - terrain.getGlobe().computePointFromPosition(ll.latitude, ll.longitude, altitudes[i]); + Vec4 p = terrainConformant[i] + ? terrain.getSurfacePoint(ll.latitude, ll.longitude, altitudes[i]) + : terrain.getGlobe().computePointFromPosition(ll.latitude, ll.longitude, altitudes[i]); pointBuffer.put((float) (p.x - geom.referencePoint.x)); pointBuffer.put((float) (p.y - geom.referencePoint.y)); pointBuffer.put((float) (p.z - geom.referencePoint.z)); @@ -667,10 +594,8 @@ private void makeSideGeometry(Terrain terrain, double[] altitudes, boolean[] ter int outlineCount = 8; // Count the number of triangle and line segment indices, depending on whether each end cap is enabled. - for (int i = 0; i < 4; i++) - { - if (sideFlag[i]) - { + for (int i = 0; i < 4; i++) { + if (sideFlag[i]) { indexCount += 6 * sideSegments[i]; outlineCount += 4 * sideSegments[i]; } @@ -682,12 +607,9 @@ private void makeSideGeometry(Terrain terrain, double[] altitudes, boolean[] ter IntBuffer indexBuffer = IntBuffer.wrap(indexArray); IntBuffer outlineBuffer = IntBuffer.wrap(outlineArray); - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < sideSegments[i]; j++) - { - if (sideFlag[i]) - { + for (int i = 0; i < 4; i++) { + for (int j = 0; j < sideSegments[i]; j++) { + if (sideFlag[i]) { indexBuffer.put(index).put(index + 1).put(index + 2); // upper left triangle indexBuffer.put(index + 2).put(index + 1).put(index + 3); // lower right triangle outlineBuffer.put(index).put(index + 2); // upper altitude segment @@ -712,8 +634,7 @@ private void makeSideGeometry(Terrain terrain, double[] altitudes, boolean[] ter } private void makeCapGeometry(Terrain terrain, double[] altitudes, boolean[] terrainConformant, int lengthSegments, - int widthSegments, BoxGeometry geom) - { + int widthSegments, BoxGeometry geom) { List locations = this.makeCapLocations(terrain.getGlobe(), lengthSegments, widthSegments); // Compute model coordinate vertex points. @@ -721,13 +642,12 @@ private void makeCapGeometry(Terrain terrain, double[] altitudes, boolean[] terr float[] pointArray = new float[3 * vertexCount]; FloatBuffer pointBuffer = FloatBuffer.wrap(pointArray); - for (LatLon ll : locations) - { + for (LatLon ll : locations) { for (int i = 1; i >= 0; i--) // upper altitude then lower altitude { - Vec4 p = terrainConformant[i] ? - terrain.getSurfacePoint(ll.latitude, ll.longitude, altitudes[i]) : - terrain.getGlobe().computePointFromPosition(ll.latitude, ll.longitude, altitudes[i]); + Vec4 p = terrainConformant[i] + ? terrain.getSurfacePoint(ll.latitude, ll.longitude, altitudes[i]) + : terrain.getGlobe().computePointFromPosition(ll.latitude, ll.longitude, altitudes[i]); pointBuffer.put((float) (p.x - geom.referencePoint.x)); pointBuffer.put((float) (p.y - geom.referencePoint.y)); pointBuffer.put((float) (p.z - geom.referencePoint.z)); @@ -744,10 +664,8 @@ private void makeCapGeometry(Terrain terrain, double[] altitudes, boolean[] terr int rowStride = 4 * widthSegments + 2; // left top and bottom - for (int i = 0; i < lengthSegments; i++) - { - for (int j = 0; j < 2 * widthSegments; j++) - { + for (int i = 0; i < lengthSegments; i++) { + for (int j = 0; j < 2 * widthSegments; j++) { // upper altitude triangles indexBuffer.put(index).put(index + 2).put(index + rowStride); indexBuffer.put(index + rowStride).put(index + 2).put(index + rowStride + 2); @@ -769,20 +687,17 @@ private void makeCapGeometry(Terrain terrain, double[] altitudes, boolean[] terr index = 2 * widthSegments; // start at the first center vertex - if (this.enableStartCap) - { + if (this.enableStartCap) { centerLineBuffer.put(index).put(index + 1); // begin vertical segment } - for (int i = 0; i < lengthSegments; i++) - { + for (int i = 0; i < lengthSegments; i++) { centerLineBuffer.put(index).put(index + rowStride); // upper altitude segment centerLineBuffer.put(index + 1).put(index + rowStride + 1); // lower altitude segment index += rowStride; } - if (this.enableEndCap) - { + if (this.enableEndCap) { centerLineBuffer.put(index).put(index + 1); // end vertical segment } @@ -797,8 +712,7 @@ private void makeCapGeometry(Terrain terrain, double[] altitudes, boolean[] terr geom.centerLineIndices.setElementData(GL.GL_LINES, centerLineCount, centerLineArray); } - private List makeSideLocations(Globe globe, int lengthSegments, int widthSegments) - { + private List makeSideLocations(Globe globe, int lengthSegments, int widthSegments) { ArrayList locations = new ArrayList(); BoxCorners corners = this.computeBoxCorners(globe); @@ -807,8 +721,7 @@ private List makeSideLocations(Globe globe, int lengthSegments, int widt // right side locations.add(corners.beginRight); - for (int i = 1; i < lengthSegments; i++) - { + for (int i = 1; i < lengthSegments; i++) { double amount = (double) i / (double) lengthSegments; LatLon rightProj = LatLon.interpolateGreatCircle(amount, corners.beginRightProj, corners.endRightProj); double rightAzimuth = LatLon.greatCircleAzimuth(rightProj, corners.endRightProj).radians + (Math.PI / 2); @@ -822,8 +735,7 @@ private List makeSideLocations(Globe globe, int lengthSegments, int widt // left side locations.add(corners.endLeft); - for (int i = 1; i < lengthSegments; i++) - { + for (int i = 1; i < lengthSegments; i++) { double amount = (double) i / (double) lengthSegments; LatLon leftProj = LatLon.interpolateGreatCircle(amount, corners.endLeftProj, corners.beginLeftProj); double leftAzimuth = LatLon.greatCircleAzimuth(leftProj, corners.endLeftProj).radians - (Math.PI / 2); @@ -835,8 +747,7 @@ private List makeSideLocations(Globe globe, int lengthSegments, int widt return locations; } - private List makeCapLocations(Globe globe, int lengthSegments, int widthSegments) - { + private List makeCapLocations(Globe globe, int lengthSegments, int widthSegments) { ArrayList locations = new ArrayList(); BoxCorners corners = this.computeBoxCorners(globe); @@ -844,8 +755,7 @@ private List makeCapLocations(Globe globe, int lengthSegments, int width this.appendLocations(corners.beginLeft, this.beginLocation, corners.beginRight, widthSegments, locations); // interior rows - for (int i = 1; i < lengthSegments; i++) - { + for (int i = 1; i < lengthSegments; i++) { double amount = (double) i / (double) lengthSegments; LatLon center = LatLon.interpolateGreatCircle(amount, this.beginLocation, this.endLocation); LatLon leftProj = LatLon.interpolateGreatCircle(amount, corners.beginLeftProj, corners.endLeftProj); @@ -864,8 +774,7 @@ private List makeCapLocations(Globe globe, int lengthSegments, int width return locations; } - private BoxCorners computeBoxCorners(Globe globe) - { + private BoxCorners computeBoxCorners(Globe globe) { BoxCorners corners = new BoxCorners(); double beginAzimuth = LatLon.greatCircleAzimuth(this.beginLocation, this.endLocation).radians; double endAzimuth = LatLon.greatCircleAzimuth(this.endLocation, this.beginLocation).radians; @@ -874,65 +783,57 @@ private BoxCorners computeBoxCorners(Globe globe) corners.rightArcLength = this.rightWidth / globe.getRadius(); corners.beginLeft = LatLon.greatCircleEndPosition(this.beginLocation, beginAzimuth - (Math.PI / 2), - corners.leftArcLength); + corners.leftArcLength); corners.beginLeftProj = this.beginLocation; - if (this.beginLeftAzimuth != null) - { + if (this.beginLeftAzimuth != null) { double arcAngle = beginAzimuth - this.beginLeftAzimuth.radians; double arcLength = Math.asin(Math.cos(arcAngle) * Math.sin(corners.leftArcLength) / Math.sin(arcAngle)); double sideLength = Math.asin(Math.sin(corners.leftArcLength) / Math.sin(arcAngle)); - if (arcLength < centerArcLength) - { + if (arcLength < centerArcLength) { corners.beginLeft = LatLon.greatCircleEndPosition(this.beginLocation, this.beginLeftAzimuth.radians, - sideLength); + sideLength); corners.beginLeftProj = LatLon.greatCircleEndPosition(this.beginLocation, beginAzimuth, arcLength); } } corners.beginRight = LatLon.greatCircleEndPosition(this.beginLocation, beginAzimuth + (Math.PI / 2), - corners.rightArcLength); + corners.rightArcLength); corners.beginRightProj = this.beginLocation; - if (this.beginRightAzimuth != null) - { + if (this.beginRightAzimuth != null) { double arcAngle = this.beginRightAzimuth.radians - beginAzimuth; double arcLength = Math.asin(Math.cos(arcAngle) * Math.sin(corners.rightArcLength) / Math.sin(arcAngle)); double sideLength = Math.asin(Math.sin(corners.rightArcLength) / Math.sin(arcAngle)); - if (arcLength < centerArcLength) - { + if (arcLength < centerArcLength) { corners.beginRight = LatLon.greatCircleEndPosition(this.beginLocation, this.beginRightAzimuth.radians, - sideLength); + sideLength); corners.beginRightProj = LatLon.greatCircleEndPosition(this.beginLocation, beginAzimuth, arcLength); } } corners.endLeft = LatLon.greatCircleEndPosition(this.endLocation, endAzimuth + (Math.PI / 2), - corners.leftArcLength); + corners.leftArcLength); corners.endLeftProj = this.endLocation; - if (this.endLeftAzimuth != null) - { + if (this.endLeftAzimuth != null) { double arcAngle = this.endLeftAzimuth.radians - endAzimuth; double arcLength = Math.asin(Math.cos(arcAngle) * Math.sin(corners.leftArcLength) / Math.sin(arcAngle)); double sideLength = Math.asin(Math.sin(corners.leftArcLength) / Math.sin(arcAngle)); - if (arcLength < centerArcLength) - { + if (arcLength < centerArcLength) { corners.endLeft = LatLon.greatCircleEndPosition(this.endLocation, this.endLeftAzimuth.radians, - sideLength); + sideLength); corners.endLeftProj = LatLon.greatCircleEndPosition(this.endLocation, endAzimuth, arcLength); } } corners.endRight = LatLon.greatCircleEndPosition(this.endLocation, endAzimuth - (Math.PI / 2), - corners.rightArcLength); + corners.rightArcLength); corners.endRightProj = this.endLocation; - if (this.endRightAzimuth != null) - { + if (this.endRightAzimuth != null) { double arcAngle = endAzimuth - this.endRightAzimuth.radians; double arcLength = Math.asin(Math.cos(arcAngle) * Math.sin(corners.rightArcLength) / Math.sin(arcAngle)); double sideLength = Math.asin(Math.sin(corners.rightArcLength) / Math.sin(arcAngle)); - if (arcLength < centerArcLength) - { + if (arcLength < centerArcLength) { corners.endRight = LatLon.greatCircleEndPosition(this.endLocation, this.endRightAzimuth.radians, - sideLength); + sideLength); corners.endRightProj = LatLon.greatCircleEndPosition(this.endLocation, endAzimuth, arcLength); } } @@ -940,10 +841,8 @@ private BoxCorners computeBoxCorners(Globe globe) return corners; } - private void appendLocations(LatLon begin, LatLon middle, LatLon end, int numSegments, List result) - { - for (int i = 0; i <= numSegments; i++) - { + private void appendLocations(LatLon begin, LatLon middle, LatLon end, int numSegments, List result) { + for (int i = 0; i <= numSegments; i++) { double amount = (double) i / (double) numSegments; result.add(LatLon.interpolateGreatCircle(amount, begin, middle)); } @@ -958,10 +857,8 @@ private void appendLocations(LatLon begin, LatLon middle, LatLon end, int numSeg //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsLatLon(context, "location1", this.beginLocation); @@ -973,37 +870,42 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); LatLon loc1 = rs.getStateValueAsLatLon(context, "location1"); - if (loc1 == null) + if (loc1 == null) { loc1 = this.getLocations()[0]; + } LatLon loc2 = rs.getStateValueAsLatLon(context, "location2"); - if (loc2 == null) + if (loc2 == null) { loc2 = this.getLocations()[1]; + } this.setLocations(loc1, loc2); Double lw = rs.getStateValueAsDouble(context, "leftWidth"); - if (lw == null) + if (lw == null) { lw = this.getWidths()[0]; + } Double rw = rs.getStateValueAsDouble(context, "rightWidth"); - if (rw == null) + if (rw == null) { rw = this.getWidths()[1]; + } this.setWidths(lw, rw); Boolean enableStart = rs.getStateValueAsBoolean(context, "enableStartCap"); - if (enableStart == null) + if (enableStart == null) { enableStart = this.isEnableCaps()[0]; + } Boolean enableEnd = rs.getStateValueAsBoolean(context, "enableEndCap"); - if (enableEnd == null) + if (enableEnd == null) { enableEnd = this.isEnableCaps()[1]; + } this.setEnableCaps(enableStart, enableEnd); } diff --git a/src/gov/nasa/worldwind/render/airspaces/Cake.java b/src/gov/nasa/worldwind/render/airspaces/Cake.java index 0df88082b3..41c2bdcfd4 100644 --- a/src/gov/nasa/worldwind/render/airspaces/Cake.java +++ b/src/gov/nasa/worldwind/render/airspaces/Cake.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.geom.*; @@ -22,52 +21,46 @@ * @author tag * @version $Id: Cake.java 2331 2014-09-19 19:45:55Z tgaskins $ */ -public class Cake extends AbstractAirspace -{ - /** An inner class of {@link Cake} defining the parameters of one of the cake's cylinders. */ - public static class Layer extends PartialCappedCylinder - { +public class Cake extends AbstractAirspace { + + /** + * An inner class of {@link Cake} defining the parameters of one of the cake's cylinders. + */ + public static class Layer extends PartialCappedCylinder { + public Layer(LatLon location, double radius, Angle leftAzimuth, Angle rightAzimuth, - double lowerAltitude, double upperAltitude) - { + double lowerAltitude, double upperAltitude) { super(location, radius, leftAzimuth, rightAzimuth); this.setAltitudes(lowerAltitude, upperAltitude); } - public Layer(LatLon location, double radius, Angle leftAzimuth, Angle rightAzimuth) - { + public Layer(LatLon location, double radius, Angle leftAzimuth, Angle rightAzimuth) { super(location, radius, leftAzimuth, rightAzimuth); } - public Layer(LatLon location, double radius) - { + public Layer(LatLon location, double radius) { super(location, radius); } - public Layer(AirspaceAttributes attributes) - { + public Layer(AirspaceAttributes attributes) { super(attributes); } - public Layer() - { + public Layer() { } } private List layers = new ArrayList(); - public Cake(Collection layers) - { + public Cake(Collection layers) { this.addLayers(layers); } - public Cake(AirspaceAttributes attributes) - { + public Cake(AirspaceAttributes attributes) { super(attributes); } - public Cake() - { + public Cake() { } /** @@ -75,8 +68,7 @@ public Cake() * * @return the cylinders comprising the shape, or an empty list if the shape contains no layers. */ - public List getLayers() - { + public List getLayers() { return Collections.unmodifiableList(this.layers); } @@ -87,72 +79,60 @@ public List getLayers() * * @throws IllegalArgumentException if the list reference is null. */ - public void setLayers(Collection layers) - { + public void setLayers(Collection layers) { this.layers.clear(); this.addLayers(layers); } - protected void addLayers(Iterable newLayers) - { - if (newLayers != null) - { - for (Layer l : newLayers) - { - if (l != null) + protected void addLayers(Iterable newLayers) { + if (newLayers != null) { + for (Layer l : newLayers) { + if (l != null) { this.layers.add(l); + } } } this.invalidateAirspaceData(); } - public void setEnableCaps(boolean enable) - { - for (Layer l : this.layers) - { + public void setEnableCaps(boolean enable) { + for (Layer l : this.layers) { l.setEnableCaps(enable); } } - public void setEnableDepthOffset(boolean enable) - { - for (Layer l : this.layers) - { + public void setEnableDepthOffset(boolean enable) { + for (Layer l : this.layers) { l.setEnableDepthOffset(enable); } } - public void setTerrainConforming(boolean lowerTerrainConformant, boolean upperTerrainConformant) - { + public void setTerrainConforming(boolean lowerTerrainConformant, boolean upperTerrainConformant) { super.setTerrainConforming(lowerTerrainConformant, upperTerrainConformant); - for (Layer l : this.layers) - { + for (Layer l : this.layers) { l.setTerrainConforming(lowerTerrainConformant, upperTerrainConformant); } } - public boolean isAirspaceVisible(DrawContext dc) - { - if (dc == null) - { + public boolean isAirspaceVisible(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // If the parent Cake is not visible, then return false immediately without testing the child layers. - if (!super.isAirspaceVisible(dc)) + if (!super.isAirspaceVisible(dc)) { return false; + } boolean visible = false; // The parent Cake is visible. Since the parent Cake's extent potentially contains volumes where no child // geometry exists, test that at least one of the child layers are visible. - for (Layer l : this.layers) - { - if (l.isAirspaceVisible(dc)) - { + for (Layer l : this.layers) { + if (l.isAirspaceVisible(dc)) { visible = true; break; } @@ -161,35 +141,26 @@ public boolean isAirspaceVisible(DrawContext dc) return visible; } - public Position getReferencePosition() - { + public Position getReferencePosition() { ArrayList locations = new ArrayList(this.layers.size()); - for (Layer l : this.layers) - { + for (Layer l : this.layers) { locations.add(l.getCenter()); } return this.computeReferencePosition(locations, this.getAltitudes()); } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { List cakeLayers = this.getLayers(); - if (cakeLayers == null || cakeLayers.isEmpty()) - { + if (cakeLayers == null || cakeLayers.isEmpty()) { return null; - } - else if (cakeLayers.size() == 1) - { + } else if (cakeLayers.size() == 1) { return cakeLayers.get(0).computeExtent(globe, verticalExaggeration); - } - else - { + } else { ArrayList extents = new ArrayList(); - for (Layer layer : cakeLayers) - { + for (Layer layer : cakeLayers) { extents.add(layer.computeExtent(globe, verticalExaggeration)); } @@ -198,21 +169,17 @@ else if (cakeLayers.size() == 1) } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { return null; // Cake is a geometry container, and therefore has no geometry itself. } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -220,24 +187,20 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) super.doMoveTo(oldRef, newRef); - for (Layer l : this.layers) - { + for (Layer l : this.layers) { l.doMoveTo(globe, oldRef, newRef); } this.invalidateAirspaceData(); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -245,8 +208,7 @@ protected void doMoveTo(Position oldRef, Position newRef) super.doMoveTo(oldRef, newRef); - for (Layer l : this.layers) - { + for (Layer l : this.layers) { l.doMoveTo(oldRef, newRef); } @@ -256,24 +218,21 @@ protected void doMoveTo(Position oldRef, Position newRef) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - @Override - public void preRender(DrawContext dc) - { - if (dc == null) - { + public void preRender(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } this.determineActiveAttributes(dc); - for (Layer layer : this.layers) - { + for (Layer layer : this.layers) { // Synchronize the layer's attributes with this cake's attributes, and setup this cake as the layer's pick // delegate. layer.setAttributes(this.getActiveAttributes()); @@ -283,69 +242,63 @@ public void preRender(DrawContext dc) } @Override - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } - if (!this.isAirspaceVisible(dc)) + if (!this.isAirspaceVisible(dc)) { return; + } - for (Layer layer : this.layers) - { + for (Layer layer : this.layers) { layer.render(dc); } } @Override - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { // Intentionally left blank. } //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); RestorableSupport.StateObject so = rs.addStateObject(context, "layers"); - for (Layer layer : this.layers) - { + for (Layer layer : this.layers) { RestorableSupport.StateObject lso = rs.addStateObject(so, "layer"); layer.doGetRestorableState(rs, lso); } } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); RestorableSupport.StateObject so = rs.getStateObject(context, "layers"); - if (so == null) + if (so == null) { return; + } RestorableSupport.StateObject[] lsos = rs.getAllStateObjects(so, "layer"); - if (lsos == null || lsos.length == 0) + if (lsos == null || lsos.length == 0) { return; + } ArrayList layerList = new ArrayList(lsos.length); - for (RestorableSupport.StateObject lso : lsos) - { - if (lso != null) - { + for (RestorableSupport.StateObject lso : lsos) { + if (lso != null) { Layer layer = new Layer(); layer.doRestoreState(rs, lso); layerList.add(layer); diff --git a/src/gov/nasa/worldwind/render/airspaces/CappedCylinder.java b/src/gov/nasa/worldwind/render/airspaces/CappedCylinder.java index 23f4d17c7a..4035abc267 100644 --- a/src/gov/nasa/worldwind/render/airspaces/CappedCylinder.java +++ b/src/gov/nasa/worldwind/render/airspaces/CappedCylinder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.geom.Box; @@ -22,8 +21,8 @@ * @author tag * @version $Id: CappedCylinder.java 2446 2014-11-20 21:15:11Z dcollins $ */ -public class CappedCylinder extends AbstractAirspace -{ +public class CappedCylinder extends AbstractAirspace { + protected static final int DEFAULT_SLICES = 32; protected static final int DEFAULT_STACKS = 1; protected static final int DEFAULT_LOOPS = 8; @@ -39,16 +38,13 @@ public class CappedCylinder extends AbstractAirspace private final int stacks = DEFAULT_STACKS; private int loops = DEFAULT_LOOPS; - public CappedCylinder(LatLon location, double radius) - { - if (location == null) - { + public CappedCylinder(LatLon location, double radius) { + if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius < 0.0) - { + if (radius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius=" + radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -59,8 +55,7 @@ public CappedCylinder(LatLon location, double radius) this.makeDefaultDetailLevels(); } - public CappedCylinder(CappedCylinder source) - { + public CappedCylinder(CappedCylinder source) { super(source); this.center = source.center; @@ -73,19 +68,16 @@ public CappedCylinder(CappedCylinder source) this.makeDefaultDetailLevels(); } - public CappedCylinder(AirspaceAttributes attributes) - { + public CappedCylinder(AirspaceAttributes attributes) { super(attributes); this.makeDefaultDetailLevels(); } - public CappedCylinder() - { + public CappedCylinder() { this.makeDefaultDetailLevels(); } - private void makeDefaultDetailLevels() - { + private void makeDefaultDetailLevels() { List levels = new ArrayList(); double[] ramp = ScreenSizeDetailLevel.computeDefaultScreenSizeRamp(5); @@ -133,8 +125,7 @@ private void makeDefaultDetailLevels() * * @return the cylinder's center */ - public LatLon getCenter() - { + public LatLon getCenter() { return this.center; } @@ -145,10 +136,8 @@ public LatLon getCenter() * * @throws IllegalArgumentException if the location is null. */ - public void setCenter(LatLon location) - { - if (location == null) - { + public void setCenter(LatLon location) { + if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -163,8 +152,7 @@ public void setCenter(LatLon location) * * @return the cylinder's inner and outer radius, in meters. */ - public double[] getRadii() - { + public double[] getRadii() { double[] array = new double[2]; array[0] = this.innerRadius; array[1] = this.outerRadius; @@ -179,16 +167,13 @@ public double[] getRadii() * * @throws IllegalArgumentException if either radius is less than zero. */ - public void setRadii(double innerRadius, double outerRadius) - { - if (innerRadius < 0.0) - { + public void setRadii(double innerRadius, double outerRadius) { + if (innerRadius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "innerRadius=" + innerRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (outerRadius < 0.0) - { + if (outerRadius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "outerRadius=" + outerRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -206,10 +191,8 @@ public void setRadii(double innerRadius, double outerRadius) * * @throws IllegalArgumentException if the radius is less than zero. */ - public void setRadius(double radius) - { - if (radius < 0.0) - { + public void setRadius(double radius) { + if (radius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius=" + radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -218,27 +201,24 @@ public void setRadius(double radius) this.setRadii(0.0, radius); } - public boolean isEnableCaps() - { + public boolean isEnableCaps() { return this.enableCaps; } - public void setEnableCaps(boolean enable) - { + public void setEnableCaps(boolean enable) { this.enableCaps = enable; } - public Position getReferencePosition() - { + public Position getReferencePosition() { double[] altitudes = this.getAltitudes(); return new Position(this.center, altitudes[0]); } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { List points = this.computeMinimalGeometry(globe, verticalExaggeration); - if (points == null || points.isEmpty()) + if (points == null || points.isEmpty()) { return null; + } Vec4 centerPoint = globe.computePointFromLocation(this.getCenter()); Vec4 cylinderAxis = globe.computeSurfaceNormalAtPoint(centerPoint); @@ -247,41 +227,39 @@ protected Extent computeExtent(Globe globe, double verticalExaggeration) double maxProj = -Double.MAX_VALUE; double maxPerp = -Double.MAX_VALUE; - for (Vec4 vec : points) - { + for (Vec4 vec : points) { Vec4 v = vec.subtract3(centerPoint); double proj = v.dot3(cylinderAxis); double perp = v.perpendicularTo3(cylinderAxis).getLengthSquared3(); - if (minProj > proj) + if (minProj > proj) { minProj = proj; + } - if (maxProj < proj) + if (maxProj < proj) { maxProj = proj; + } - if (maxPerp < perp) + if (maxPerp < perp) { maxPerp = perp; + } } - if (minProj != maxProj && maxPerp > 0.0) - { + if (minProj != maxProj && maxPerp > 0.0) { Vec4 bottomCenter = centerPoint.add3(cylinderAxis.multiply3(minProj)); Vec4 topCenter = centerPoint.add3(cylinderAxis.multiply3(maxProj)); double radius = Math.sqrt(maxPerp); return new Cylinder(bottomCenter, topCenter, radius); - } - else - { + } else { return Box.computeBoundingBox(points); } } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { GeometryBuilder gb = new GeometryBuilder(); LatLon[] locations = gb.makeDiskLocations(globe, this.center, this.innerRadius, this.outerRadius, - MINIMAL_GEOMETRY_SLICES, MINIMAL_GEOMETRY_LOOPS); + MINIMAL_GEOMETRY_SLICES, MINIMAL_GEOMETRY_LOOPS); ArrayList points = new ArrayList(); this.makeExtremePoints(globe, verticalExaggeration, Arrays.asList(locations), points); @@ -289,16 +267,13 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera return points; } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -312,16 +287,13 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) super.doMoveTo(oldRef, newRef); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -336,14 +308,12 @@ protected void doMoveTo(Position oldRef, Position newRef) } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return new SurfacePolygon(); } @Override - protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) { super.updateSurfaceShape(dc, shape); boolean mustDrawInterior = this.getActiveAttributes().isDrawInterior() && this.isEnableCaps(); @@ -351,29 +321,24 @@ protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { GeometryBuilder gb = new GeometryBuilder(); LatLon[] locations = gb.makeCylinderLocations(dc.getGlobe(), this.center, this.outerRadius, this.slices); ((SurfacePolygon) shape).getBoundaries().clear(); ((SurfacePolygon) shape).setOuterBoundary(Arrays.asList(locations)); - if (this.innerRadius > 0) - { + if (this.innerRadius > 0) { locations = gb.makeCylinderLocations(dc.getGlobe(), this.center, this.innerRadius, this.slices); ((SurfacePolygon) shape).addInnerBoundary(Arrays.asList(locations)); } } - protected int getSlices() - { + protected int getSlices() { return this.slices; } - protected void setSlices(int slices) - { - if (slices < 0) - { + protected void setSlices(int slices) { + if (slices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -382,20 +347,16 @@ protected void setSlices(int slices) this.slices = slices; } - protected int getStacks() - { + protected int getStacks() { return this.stacks; } - protected int getLoops() - { + protected int getLoops() { return this.loops; } - protected void setLoops(int loops) - { - if (loops < 0) - { + protected void setLoops(int loops) { + if (loops < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -407,17 +368,13 @@ protected void setLoops(int loops) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected Vec4 computeReferenceCenter(DrawContext dc) - { - if (dc == null) - { + protected Vec4 computeReferenceCenter(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -425,13 +382,11 @@ protected Vec4 computeReferenceCenter(DrawContext dc) double[] altitudes = this.getAltitudes(dc.getVerticalExaggeration()); return dc.getGlobe().computePointFromPosition(this.center.getLatitude(), this.center.getLongitude(), - altitudes[0]); // model-coordinate reference center + altitudes[0]); // model-coordinate reference center } - protected Matrix computeEllipsoidalTransform(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + protected Matrix computeEllipsoidalTransform(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -441,16 +396,13 @@ protected Matrix computeEllipsoidalTransform(Globe globe, double verticalExagger return globe.computeEllipsoidalOrientationAtPosition(this.center.latitude, this.center.longitude, altitudes[0]); } - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { - if (dc == null) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -464,25 +416,28 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) int stacks = this.stacks; int loops = this.loops; - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(SLICES); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { slices = (Integer) o; + } o = level.getValue(STACKS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { stacks = (Integer) o; + } o = level.getValue(LOOPS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { loops = (Integer) o; + } o = level.getValue(DISABLE_TERRAIN_CONFORMANCE); - if (o != null && o instanceof Boolean && ((Boolean) o)) + if (o != null && o instanceof Boolean && ((Boolean) o)) { terrainConformant[0] = terrainConformant[1] = false; + } } Vec4 refCenter = this.computeReferenceCenter(dc); @@ -491,70 +446,55 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { dc.getView().pushReferenceCenter(dc, refCenter); - if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) - { + if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) { // Outer cylinder isn't rendered if outer radius is zero. - if (radii[1] != 0.0) - { + if (radii[1] != 0.0) { this.drawCylinderOutline(dc, center, radii[1], altitudes, terrainConformant, slices, stacks, - GeometryBuilder.OUTSIDE, refCenter); + GeometryBuilder.OUTSIDE, refCenter); } // Inner cylinder isn't rendered if inner radius is zero. - if (radii[0] != 0.0) - { + if (radii[0] != 0.0) { this.drawCylinderOutline(dc, center, radii[0], altitudes, terrainConformant, slices, stacks, - GeometryBuilder.INSIDE, refCenter); + GeometryBuilder.INSIDE, refCenter); } - } - else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) - { - if (this.enableCaps) - { + } else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) { + if (this.enableCaps) { ogsh.pushAttrib(gl, GL2.GL_POLYGON_BIT); gl.glEnable(GL.GL_CULL_FACE); gl.glFrontFace(GL.GL_CCW); } - if (this.enableCaps) - { + if (this.enableCaps) { // Caps aren't rendered if radii are equal. - if (radii[0] != radii[1]) - { + if (radii[0] != radii[1]) { this.drawDisk(dc, center, radii, altitudes[1], terrainConformant[1], slices, loops, - GeometryBuilder.OUTSIDE, refCenter); + GeometryBuilder.OUTSIDE, refCenter); // Bottom cap isn't rendered if airspace is collapsed - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { this.drawDisk(dc, center, radii, altitudes[0], terrainConformant[0], slices, loops, - GeometryBuilder.INSIDE, refCenter); + GeometryBuilder.INSIDE, refCenter); } } } // Cylinders aren't rendered if airspace is collapsed - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { // Outer cylinder isn't rendered if outer radius is zero. - if (radii[1] != 0.0) - { + if (radii[1] != 0.0) { this.drawCylinder(dc, center, radii[1], altitudes, terrainConformant, slices, stacks, - GeometryBuilder.OUTSIDE, refCenter); + GeometryBuilder.OUTSIDE, refCenter); } // Inner cylinder isn't rendered if inner radius is zero. - if (radii[0] != 0.0) - { + if (radii[0] != 0.0) { this.drawCylinder(dc, center, radii[0], altitudes, terrainConformant, slices, stacks, - GeometryBuilder.INSIDE, refCenter); + GeometryBuilder.INSIDE, refCenter); } } } - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); ogsh.pop(gl); } @@ -563,17 +503,14 @@ else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) //**************************************************************// //******************** Cylinder ********************// //**************************************************************// - private void drawCylinder(DrawContext dc, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter) - { + boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter) { Geometry vertexGeom = this.createCylinderVertexGeometry(dc, center, radius, altitudes, terrainConformant, - slices, stacks, orientation, referenceCenter); + slices, stacks, orientation, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "Cylinder.Indices", slices, stacks, orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makeCylinderIndices(slices, stacks, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -583,16 +520,14 @@ private void drawCylinder(DrawContext dc, LatLon center, double radius, double[] } private void drawCylinderOutline(DrawContext dc, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter) - { + boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter) { Geometry vertexGeom = this.createCylinderVertexGeometry(dc, center, radius, altitudes, terrainConformant, - slices, stacks, orientation, referenceCenter); + slices, stacks, orientation, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "Cylinder.OutlineIndices", slices, stacks, - orientation); + orientation); Geometry outlineIndexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (outlineIndexGeom == null) - { + if (outlineIndexGeom == null) { outlineIndexGeom = new Geometry(); this.makeCylinderOutlineIndices(slices, stacks, orientation, outlineIndexGeom); this.getGeometryCache().add(cacheKey, outlineIndexGeom); @@ -602,18 +537,17 @@ private void drawCylinderOutline(DrawContext dc, LatLon center, double radius, d } private Geometry createCylinderVertexGeometry(DrawContext dc, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter) - { + boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "Cylinder.Vertices", center, radius, - altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], slices, stacks, orientation, - referenceCenter); + altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], slices, stacks, orientation, + referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makeCylinder(dc, center, radius, altitudes, terrainConformant, slices, stacks, orientation, - referenceCenter, vertexGeom); + referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } @@ -622,8 +556,7 @@ private Geometry createCylinderVertexGeometry(DrawContext dc, LatLon center, dou } private void makeCylinder(DrawContext dc, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter, Geometry dest) - { + boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -631,15 +564,14 @@ private void makeCylinder(DrawContext dc, LatLon center, double radius, double[] float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makeCylinderVertices(dc.getTerrain(), center, radius, altitudes, terrainConformant, slices, stacks, - referenceCenter, verts); + referenceCenter, verts); gb.makeCylinderNormals(slices, stacks, norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makeCylinderIndices(int slices, int stacks, int orientation, Geometry dest) - { + private void makeCylinderIndices(int slices, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -651,8 +583,7 @@ private void makeCylinderIndices(int slices, int stacks, int orientation, Geomet dest.setElementData(mode, count, indices); } - private void makeCylinderOutlineIndices(int slices, int stacks, int orientation, Geometry dest) - { + private void makeCylinderOutlineIndices(int slices, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -667,28 +598,25 @@ private void makeCylinderOutlineIndices(int slices, int stacks, int orientation, //**************************************************************// //******************** Disk ********************// //**************************************************************// - private void drawDisk(DrawContext dc, LatLon center, double[] radii, double altitude, boolean terrainConformant, - int slices, int loops, int orientation, Vec4 referenceCenter) - { + int slices, int loops, int orientation, Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "Disk.Vertices", - center, radii[0], radii[1], altitude, terrainConformant, - slices, loops, orientation, referenceCenter); + center, radii[0], radii[1], altitude, terrainConformant, + slices, loops, orientation, referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makeDisk(dc, center, radii, altitude, terrainConformant, - slices, loops, orientation, referenceCenter, vertexGeom); + slices, loops, orientation, referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } cacheKey = new Geometry.CacheKey(this.getClass(), "Disk.Indices", slices, loops, orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makeDiskIndices(slices, loops, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -698,8 +626,7 @@ private void drawDisk(DrawContext dc, LatLon center, double[] radii, double alti } private void makeDisk(DrawContext dc, LatLon center, double[] radii, double altitude, boolean terrainConformant, - int slices, int loops, int orientation, Vec4 referenceCenter, Geometry dest) - { + int slices, int loops, int orientation, Vec4 referenceCenter, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -707,15 +634,14 @@ private void makeDisk(DrawContext dc, LatLon center, double[] radii, double alti float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makeDiskVertices(dc.getTerrain(), center, radii[0], radii[1], altitude, terrainConformant, slices, loops, - referenceCenter, verts); + referenceCenter, verts); gb.makeDiskVertexNormals((float) radii[0], (float) radii[1], slices, loops, verts, norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makeDiskIndices(int slices, int loops, int orientation, Geometry dest) - { + private void makeDiskIndices(int slices, int loops, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -730,10 +656,8 @@ private void makeDiskIndices(int slices, int loops, int orientation, Geometry de //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsBoolean(context, "capsVisible", this.isEnableCaps()); @@ -743,25 +667,28 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Boolean booleanState = rs.getStateValueAsBoolean(context, "capsVisible"); - if (booleanState != null) + if (booleanState != null) { this.setEnableCaps(booleanState); + } LatLon ll = rs.getStateValueAsLatLon(context, "center"); - if (ll != null) + if (ll != null) { this.setCenter(ll); + } Double ir = rs.getStateValueAsDouble(context, "innerRadius"); - if (ir == null) + if (ir == null) { ir = this.getRadii()[0]; + } Double or = rs.getStateValueAsDouble(context, "outerRadius"); - if (or == null) + if (or == null) { or = this.getRadii()[1]; + } this.setRadii(ir, or); } diff --git a/src/gov/nasa/worldwind/render/airspaces/CappedEllipticalCylinder.java b/src/gov/nasa/worldwind/render/airspaces/CappedEllipticalCylinder.java index ac67013f67..e8694acb69 100644 --- a/src/gov/nasa/worldwind/render/airspaces/CappedEllipticalCylinder.java +++ b/src/gov/nasa/worldwind/render/airspaces/CappedEllipticalCylinder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.geom.*; @@ -23,8 +22,8 @@ * @author tag * @version $Id: CappedEllipticalCylinder.java 3424 2015-09-29 19:34:00Z tgaskins $ */ -public class CappedEllipticalCylinder extends AbstractAirspace -{ +public class CappedEllipticalCylinder extends AbstractAirspace { + protected static final int DEFAULT_SLICES = 32; protected static final int DEFAULT_STACKS = 1; protected static final int DEFAULT_LOOPS = 8; @@ -43,24 +42,20 @@ public class CappedEllipticalCylinder extends AbstractAirspace protected final int stacks = DEFAULT_STACKS; protected int loops = DEFAULT_LOOPS; - public CappedEllipticalCylinder(LatLon location, double minorRadius, double majorRadius, Angle heading) - { - if (location == null) - { + public CappedEllipticalCylinder(LatLon location, double minorRadius, double majorRadius, Angle heading) { + if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minorRadius < 0 | majorRadius < 0) - { + if (minorRadius < 0 | majorRadius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "minor radius=" + minorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (majorRadius < 0) - { + if (majorRadius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "major radius=" + majorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -73,8 +68,7 @@ public CappedEllipticalCylinder(LatLon location, double minorRadius, double majo this.makeDefaultDetailLevels(); } - public CappedEllipticalCylinder(CappedEllipticalCylinder source) - { + public CappedEllipticalCylinder(CappedEllipticalCylinder source) { super(source); this.center = source.center; @@ -90,19 +84,16 @@ public CappedEllipticalCylinder(CappedEllipticalCylinder source) this.makeDefaultDetailLevels(); } - public CappedEllipticalCylinder(AirspaceAttributes attributes) - { + public CappedEllipticalCylinder(AirspaceAttributes attributes) { super(attributes); this.makeDefaultDetailLevels(); } - public CappedEllipticalCylinder() - { + public CappedEllipticalCylinder() { this.makeDefaultDetailLevels(); } - private void makeDefaultDetailLevels() - { + private void makeDefaultDetailLevels() { List levels = new ArrayList(); double[] ramp = ScreenSizeDetailLevel.computeDefaultScreenSizeRamp(5); @@ -150,8 +141,7 @@ private void makeDefaultDetailLevels() * * @return the cylinder's center */ - public LatLon getCenter() - { + public LatLon getCenter() { return this.center; } @@ -162,10 +152,8 @@ public LatLon getCenter() * * @throws IllegalArgumentException if the location is null. */ - public void setCenter(LatLon location) - { - if (location == null) - { + public void setCenter(LatLon location) { + if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -181,8 +169,7 @@ public void setCenter(LatLon location) * @return the cylinder's radii, in meters. The returned array contains the inner minor radius, inner major radius, * outer minor radius and outer major radius, in that order. */ - public double[] getRadii() - { + public double[] getRadii() { double[] array = new double[4]; array[0] = this.innerMinorRadius; @@ -204,31 +191,26 @@ public double[] getRadii() * @throws IllegalArgumentException if either radius is less than zero. */ public void setRadii(double innerMinorRadius, double innerMajorRadius, double outerMinorRadius, - double outerMajorRadius) - { - if (innerMinorRadius < 0.0) - { + double outerMajorRadius) { + if (innerMinorRadius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "innerMinorRadius=" + innerMinorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (outerMinorRadius < 0.0) - { + if (outerMinorRadius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "outerMinorRadius=" + outerMinorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (innerMajorRadius < 0.0) - { + if (innerMajorRadius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "innerMajorRadius=" + innerMajorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (outerMajorRadius < 0.0) - { + if (outerMajorRadius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "outerMajorRadius=" + outerMajorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -250,17 +232,14 @@ public void setRadii(double innerMinorRadius, double innerMajorRadius, double ou * * @throws IllegalArgumentException if either radius is less than zero. */ - public void setRadii(double outerMinorRadius, double outerMajorRadius) - { - if (outerMinorRadius < 0.0) - { + public void setRadii(double outerMinorRadius, double outerMajorRadius) { + if (outerMinorRadius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "outerMinorRadius=" + outerMinorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (outerMajorRadius < 0.0) - { + if (outerMajorRadius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "outerMajorRadius=" + outerMajorRadius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -274,8 +253,7 @@ public void setRadii(double outerMinorRadius, double outerMajorRadius) * * @return This cylinder's heading, in degrees. */ - public Angle getHeading() - { + public Angle getHeading() { return heading; } @@ -284,33 +262,29 @@ public Angle getHeading() * * @param heading This cylinder's heading, in degrees. */ - public void setHeading(Angle heading) - { + public void setHeading(Angle heading) { this.heading = heading; this.invalidateAirspaceData(); } - public boolean isEnableCaps() - { + public boolean isEnableCaps() { return this.enableCaps; } - public void setEnableCaps(boolean enable) - { + public void setEnableCaps(boolean enable) { this.enableCaps = enable; } - public Position getReferencePosition() - { + public Position getReferencePosition() { double[] altitudes = this.getAltitudes(); return new Position(this.center, altitudes[0]); } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { List points = this.computeMinimalGeometry(globe, verticalExaggeration); - if (points == null || points.isEmpty()) + if (points == null || points.isEmpty()) { return null; + } Vec4 centerPoint = globe.computePointFromLocation(this.getCenter()); Vec4 cylinderAxis = globe.computeSurfaceNormalAtPoint(centerPoint); @@ -319,41 +293,39 @@ protected Extent computeExtent(Globe globe, double verticalExaggeration) double maxProj = -Double.MAX_VALUE; double maxPerp = -Double.MAX_VALUE; - for (Vec4 vec : points) - { + for (Vec4 vec : points) { Vec4 v = vec.subtract3(centerPoint); double proj = v.dot3(cylinderAxis); double perp = v.perpendicularTo3(cylinderAxis).getLengthSquared3(); - if (minProj > proj) + if (minProj > proj) { minProj = proj; + } - if (maxProj < proj) + if (maxProj < proj) { maxProj = proj; + } - if (maxPerp < perp) + if (maxPerp < perp) { maxPerp = perp; + } } - if (minProj != maxProj && maxPerp > 0.0) - { + if (minProj != maxProj && maxPerp > 0.0) { Vec4 bottomCenter = centerPoint.add3(cylinderAxis.multiply3(minProj)); Vec4 topCenter = centerPoint.add3(cylinderAxis.multiply3(maxProj)); double radius = Math.sqrt(maxPerp); return new Cylinder(bottomCenter, topCenter, radius); - } - else - { + } else { return Box.computeBoundingBox(points); } } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { GeometryBuilder gb = new GeometryBuilder(); LatLon[] locations = gb.makeDiskLocations(globe, this.center, this.getRadii(), - this.heading, MINIMAL_GEOMETRY_SLICES, MINIMAL_GEOMETRY_LOOPS); + this.heading, MINIMAL_GEOMETRY_SLICES, MINIMAL_GEOMETRY_LOOPS); ArrayList points = new ArrayList(); this.makeExtremePoints(globe, verticalExaggeration, Arrays.asList(locations), points); @@ -361,16 +333,13 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera return points; } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -384,16 +353,13 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) super.doMoveTo(oldRef, newRef); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -408,14 +374,12 @@ protected void doMoveTo(Position oldRef, Position newRef) } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return new SurfacePolygon(); } @Override - protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) { super.updateSurfaceShape(dc, shape); boolean mustDrawInterior = this.getActiveAttributes().isDrawInterior() && this.isEnableCaps(); @@ -423,31 +387,26 @@ protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { GeometryBuilder gb = new GeometryBuilder(); LatLon[] locations = gb.makeCylinderLocations(dc.getGlobe(), this.center, - this.outerMinorRadius, this.outerMajorRadius, this.heading, this.slices); + this.outerMinorRadius, this.outerMajorRadius, this.heading, this.slices); ((SurfacePolygon) shape).getBoundaries().clear(); ((SurfacePolygon) shape).setOuterBoundary(Arrays.asList(locations)); - if (this.innerMinorRadius > 0 && this.innerMajorRadius > 0) - { + if (this.innerMinorRadius > 0 && this.innerMajorRadius > 0) { locations = gb.makeCylinderLocations(dc.getGlobe(), this.center, - this.innerMinorRadius, this.innerMajorRadius, this.heading, this.slices); + this.innerMinorRadius, this.innerMajorRadius, this.heading, this.slices); ((SurfacePolygon) shape).addInnerBoundary(Arrays.asList(locations)); } } - public int getSlices() - { + public int getSlices() { return this.slices; } - public void setSlices(int slices) - { - if (slices < 0) - { + public void setSlices(int slices) { + if (slices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -456,20 +415,16 @@ public void setSlices(int slices) this.slices = slices; } - public int getStacks() - { + public int getStacks() { return this.stacks; } - public int getLoops() - { + public int getLoops() { return this.loops; } - public void setLoops(int loops) - { - if (loops < 0) - { + public void setLoops(int loops) { + if (loops < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -481,18 +436,14 @@ public void setLoops(int loops) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected Vec4 computeReferenceCenter(DrawContext dc) - { - if (dc == null) - { + protected Vec4 computeReferenceCenter(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -500,20 +451,17 @@ protected Vec4 computeReferenceCenter(DrawContext dc) double[] altitudes = this.getAltitudes(dc.getVerticalExaggeration()); return dc.getGlobe().computePointFromPosition(this.center.getLatitude(), this.center.getLongitude(), - altitudes[0]); // model-coordinate reference center + altitudes[0]); // model-coordinate reference center } - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { - if (dc == null) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -527,25 +475,28 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) int stacks = this.stacks; int loops = this.loops; - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(SLICES); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { slices = (Integer) o; + } o = level.getValue(STACKS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { stacks = (Integer) o; + } o = level.getValue(LOOPS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { loops = (Integer) o; + } o = level.getValue(DISABLE_TERRAIN_CONFORMANCE); - if (o != null && o instanceof Boolean && ((Boolean) o)) + if (o != null && o instanceof Boolean && ((Boolean) o)) { terrainConformant[0] = terrainConformant[1] = false; + } } Vec4 refCenter = this.computeReferenceCenter(dc); @@ -554,70 +505,55 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { dc.getView().pushReferenceCenter(dc, refCenter); - if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) - { + if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) { // Outer cylinder isn't rendered if outer radius is zero. - if (radii[2] != 0.0 && radii[3] != 0) - { + if (radii[2] != 0.0 && radii[3] != 0) { this.drawCylinderOutline(dc, center, radii[2], radii[3], this.heading, altitudes, - terrainConformant, slices, stacks, GeometryBuilder.OUTSIDE, refCenter); + terrainConformant, slices, stacks, GeometryBuilder.OUTSIDE, refCenter); } // Inner cylinder isn't rendered if inner radius is zero. - if (radii[0] != 0.0 && radii[1] != 0) - { + if (radii[0] != 0.0 && radii[1] != 0) { this.drawCylinderOutline(dc, center, radii[0], radii[1], this.heading, altitudes, - terrainConformant, slices, stacks, GeometryBuilder.INSIDE, refCenter); + terrainConformant, slices, stacks, GeometryBuilder.INSIDE, refCenter); } - } - else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) - { - if (this.enableCaps) - { + } else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) { + if (this.enableCaps) { ogsh.pushAttrib(gl, GL2.GL_POLYGON_BIT); gl.glEnable(GL.GL_CULL_FACE); gl.glFrontFace(GL.GL_CCW); } - if (this.enableCaps) - { + if (this.enableCaps) { // Caps aren't rendered if radii are equal. - if ((radii[0] != radii[2]) && (radii[1] != radii[3])) - { + if ((radii[0] != radii[2]) && (radii[1] != radii[3])) { this.drawDisk(dc, center, radii, this.heading, altitudes[1], terrainConformant[1], slices, loops, - GeometryBuilder.OUTSIDE, refCenter); + GeometryBuilder.OUTSIDE, refCenter); // Bottom cap isn't rendered if airspace is collapsed - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { this.drawDisk(dc, center, radii, this.heading, altitudes[0], terrainConformant[0], slices, loops, - GeometryBuilder.INSIDE, refCenter); + GeometryBuilder.INSIDE, refCenter); } } } // Cylinders aren't rendered if airspace is collapsed - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { // Outer cylinder isn't rendered if outer radius is zero. - if (radii[2] != 0.0 && radii[3] != 0) - { + if (radii[2] != 0.0 && radii[3] != 0) { this.drawCylinder(dc, center, radii[2], radii[3], this.heading, altitudes, terrainConformant, - slices, stacks, GeometryBuilder.OUTSIDE, refCenter); + slices, stacks, GeometryBuilder.OUTSIDE, refCenter); } // Inner cylinder isn't rendered if inner radius is zero. - if (radii[0] != 0.0) - { + if (radii[0] != 0.0) { this.drawCylinder(dc, center, radii[0], radii[1], this.heading, altitudes, terrainConformant, - slices, stacks, GeometryBuilder.INSIDE, refCenter); + slices, stacks, GeometryBuilder.INSIDE, refCenter); } } } - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); ogsh.pop(gl); } @@ -626,17 +562,14 @@ else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) //**************************************************************// //******************** Cylinder ********************// //**************************************************************// - private void drawCylinder(DrawContext dc, LatLon center, double minorRadius, double majorRadius, Angle heading, - double[] altitudes, boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter) - { + double[] altitudes, boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter) { Geometry vertexGeom = this.createCylinderVertexGeometry(dc, center, minorRadius, majorRadius, heading, - altitudes, terrainConformant, slices, stacks, orientation, referenceCenter); + altitudes, terrainConformant, slices, stacks, orientation, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "EllipticalCylinder.Indices", slices, stacks, orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makeCylinderIndices(slices, stacks, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -646,17 +579,15 @@ private void drawCylinder(DrawContext dc, LatLon center, double minorRadius, dou } private void drawCylinderOutline(DrawContext dc, LatLon center, double minorRadius, double majorRadius, - Angle heading, double[] altitudes, boolean[] terrainConformant, int slices, int stacks, int orientation, - Vec4 referenceCenter) - { + Angle heading, double[] altitudes, boolean[] terrainConformant, int slices, int stacks, int orientation, + Vec4 referenceCenter) { Geometry vertexGeom = this.createCylinderVertexGeometry(dc, center, minorRadius, majorRadius, heading, altitudes, - terrainConformant, slices, stacks, orientation, referenceCenter); + terrainConformant, slices, stacks, orientation, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "EllipticalCylinder.OutlineIndices", slices, stacks, - orientation); + orientation); Geometry outlineIndexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (outlineIndexGeom == null) - { + if (outlineIndexGeom == null) { outlineIndexGeom = new Geometry(); this.makeCylinderOutlineIndices(slices, stacks, orientation, outlineIndexGeom); this.getGeometryCache().add(cacheKey, outlineIndexGeom); @@ -666,20 +597,19 @@ private void drawCylinderOutline(DrawContext dc, LatLon center, double minorRadi } private Geometry createCylinderVertexGeometry(DrawContext dc, LatLon center, double minorRadius, double majorRadius, - Angle heading, double[] altitudes, boolean[] terrainConformant, int slices, int stacks, int orientation, - Vec4 referenceCenter) - { + Angle heading, double[] altitudes, boolean[] terrainConformant, int slices, int stacks, int orientation, + Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "EllipticalCylinder.Vertices", center, - minorRadius, majorRadius, heading, - altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], slices, stacks, orientation, - referenceCenter); + minorRadius, majorRadius, heading, + altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], slices, stacks, orientation, + referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makeCylinder(dc, center, minorRadius, majorRadius, heading, altitudes, terrainConformant, slices, - stacks, orientation, referenceCenter, vertexGeom); + stacks, orientation, referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } @@ -688,9 +618,8 @@ private Geometry createCylinderVertexGeometry(DrawContext dc, LatLon center, dou } private void makeCylinder(DrawContext dc, LatLon center, double minorRadius, double majorRadius, Angle heading, - double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter, Geometry dest) - { + double[] altitudes, + boolean[] terrainConformant, int slices, int stacks, int orientation, Vec4 referenceCenter, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -698,15 +627,14 @@ private void makeCylinder(DrawContext dc, LatLon center, double minorRadius, dou float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makeCylinderVertices(dc.getTerrain(), center, minorRadius, majorRadius, heading, altitudes, - terrainConformant, slices, stacks, referenceCenter, verts); + terrainConformant, slices, stacks, referenceCenter, verts); gb.makeEllipticalCylinderNormals(slices, stacks, minorRadius, majorRadius, heading, norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makeCylinderIndices(int slices, int stacks, int orientation, Geometry dest) - { + private void makeCylinderIndices(int slices, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -718,8 +646,7 @@ private void makeCylinderIndices(int slices, int stacks, int orientation, Geomet dest.setElementData(mode, count, indices); } - private void makeCylinderOutlineIndices(int slices, int stacks, int orientation, Geometry dest) - { + private void makeCylinderOutlineIndices(int slices, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -734,28 +661,25 @@ private void makeCylinderOutlineIndices(int slices, int stacks, int orientation, //**************************************************************// //******************** Disk ********************// //**************************************************************// - private void drawDisk(DrawContext dc, LatLon center, double[] radii, Angle heading, double altitude, - boolean terrainConformant, int slices, int loops, int orientation, Vec4 referenceCenter) - { + boolean terrainConformant, int slices, int loops, int orientation, Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "EllipticalDisk.Vertices", - center, radii[0], radii[1], radii[2], radii[3], heading, altitude, terrainConformant, - slices, loops, orientation, referenceCenter); + center, radii[0], radii[1], radii[2], radii[3], heading, altitude, terrainConformant, + slices, loops, orientation, referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makeDisk(dc, center, radii, heading, altitude, terrainConformant, - slices, loops, orientation, referenceCenter, vertexGeom); + slices, loops, orientation, referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } cacheKey = new Geometry.CacheKey(this.getClass(), "EllipticalDisk.Indices", slices, loops, orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makeDiskIndices(slices, loops, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -765,8 +689,7 @@ private void drawDisk(DrawContext dc, LatLon center, double[] radii, Angle headi } private void makeDisk(DrawContext dc, LatLon center, double[] radii, Angle heading, double altitude, - boolean terrainConformant, int slices, int loops, int orientation, Vec4 referenceCenter, Geometry dest) - { + boolean terrainConformant, int slices, int loops, int orientation, Vec4 referenceCenter, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -774,15 +697,14 @@ private void makeDisk(DrawContext dc, LatLon center, double[] radii, Angle headi float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makeDiskVertices(dc.getTerrain(), center, radii, heading, altitude, terrainConformant, slices, loops, - referenceCenter, verts); + referenceCenter, verts); gb.makeDiskVertexNormals(radii[0], radii[2], slices, loops, verts, norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makeDiskIndices(int slices, int loops, int orientation, Geometry dest) - { + private void makeDiskIndices(int slices, int loops, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -797,10 +719,8 @@ private void makeDiskIndices(int slices, int loops, int orientation, Geometry de //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsBoolean(context, "capsVisible", this.isEnableCaps()); @@ -813,39 +733,45 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Boolean booleanState = rs.getStateValueAsBoolean(context, "capsVisible"); - if (booleanState != null) + if (booleanState != null) { this.setEnableCaps(booleanState); + } LatLon ll = rs.getStateValueAsLatLon(context, "center"); - if (ll != null) + if (ll != null) { this.setCenter(ll); + } Double innerMinorRadius = rs.getStateValueAsDouble(context, "innerMinorRadius"); - if (innerMinorRadius == null) + if (innerMinorRadius == null) { innerMinorRadius = this.getRadii()[0]; + } Double innerMajorRadius = rs.getStateValueAsDouble(context, "innerMajorRadius"); - if (innerMajorRadius == null) + if (innerMajorRadius == null) { innerMajorRadius = this.getRadii()[1]; + } Double outerMinorRadius = rs.getStateValueAsDouble(context, "outerMinorRadius"); - if (outerMinorRadius == null) + if (outerMinorRadius == null) { outerMinorRadius = this.getRadii()[0]; + } Double outerMajorRadius = rs.getStateValueAsDouble(context, "outerMajorRadius"); - if (outerMajorRadius == null) + if (outerMajorRadius == null) { outerMajorRadius = this.getRadii()[1]; + } this.setRadii(innerMinorRadius, innerMajorRadius, outerMinorRadius, outerMajorRadius); Double heading = rs.getStateValueAsDouble(context, "heading"); - if (heading == null) + if (heading == null) { heading = this.getHeading().degrees; + } this.setHeading(Angle.fromDegrees(heading)); } diff --git a/src/gov/nasa/worldwind/render/airspaces/Curtain.java b/src/gov/nasa/worldwind/render/airspaces/Curtain.java index 5c3d41cfd2..73c4995d75 100644 --- a/src/gov/nasa/worldwind/render/airspaces/Curtain.java +++ b/src/gov/nasa/worldwind/render/airspaces/Curtain.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.avlist.AVKey; @@ -25,32 +24,28 @@ * @author tag * @version $Id: Curtain.java 2309 2014-09-17 00:04:08Z tgaskins $ */ -public class Curtain extends AbstractAirspace -{ +public class Curtain extends AbstractAirspace { + protected List locations = new ArrayList(); protected String pathType = AVKey.GREAT_CIRCLE; protected double splitThreshold = 2000.0; // 2 km protected boolean applyPositionAltitude = false; - public Curtain(Iterable locations) - { + public Curtain(Iterable locations) { this.addLocations(locations); this.makeDefaultDetailLevels(); } - public Curtain(AirspaceAttributes attributes) - { + public Curtain(AirspaceAttributes attributes) { super(attributes); this.makeDefaultDetailLevels(); } - public Curtain() - { + public Curtain() { this.makeDefaultDetailLevels(); } - public Curtain(Curtain source) - { + public Curtain(Curtain source) { super(source); this.addLocations(source.locations); @@ -61,8 +56,7 @@ public Curtain(Curtain source) this.makeDefaultDetailLevels(); } - protected void makeDefaultDetailLevels() - { + protected void makeDefaultDetailLevels() { List levels = new ArrayList(); double[] ramp = ScreenSizeDetailLevel.computeDefaultScreenSizeRamp(5); @@ -100,8 +94,7 @@ protected void makeDefaultDetailLevels() * * @return the curtain's locations in geographic coordinates. */ - public Iterable getLocations() - { + public Iterable getLocations() { return Collections.unmodifiableList(this.locations); } @@ -109,39 +102,33 @@ public Iterable getLocations() * Sets the curtain's locations, in geographic coordinates. * * @param locations a list of geographic coordinates (latitude and longitude) specifying the upper edge of the - * shape. + * shape. * * @throws IllegalArgumentException if the locations list is null or contains fewer than two points. */ - public void setLocations(Iterable locations) - { + public void setLocations(Iterable locations) { this.locations.clear(); this.addLocations(locations); } - protected void addLocations(Iterable newLocations) - { - if (newLocations != null) - { - for (LatLon ll : newLocations) - { - if (ll != null) + protected void addLocations(Iterable newLocations) { + if (newLocations != null) { + for (LatLon ll : newLocations) { + if (ll != null) { this.locations.add(ll); + } } } this.invalidateAirspaceData(); } - public String getPathType() - { + public String getPathType() { return this.pathType; } - public void setPathType(String pathType) - { - if (pathType == null) - { + public void setPathType(String pathType) { + if (pathType == null) { String message = "nullValue.PathTypeIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -151,38 +138,35 @@ public void setPathType(String pathType) this.invalidateAirspaceData(); } - public boolean isApplyPositionAltitude() - { + public boolean isApplyPositionAltitude() { return applyPositionAltitude; } - public void setApplyPositionAltitude(boolean applyPositionAltitude) - { + public void setApplyPositionAltitude(boolean applyPositionAltitude) { this.applyPositionAltitude = applyPositionAltitude; } - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.computeReferencePosition(this.locations, this.getAltitudes()); } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { List points = this.computeMinimalGeometry(globe, verticalExaggeration); - if (points == null || points.isEmpty()) + if (points == null || points.isEmpty()) { return null; + } return Box.computeBoundingBox(points); } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { ArrayList tessellatedLocations = new ArrayList(); this.makeTessellatedLocations(globe, tessellatedLocations); - if (tessellatedLocations.isEmpty()) + if (tessellatedLocations.isEmpty()) { return null; + } ArrayList points = new ArrayList(); this.makeExtremePoints(globe, verticalExaggeration, tessellatedLocations, points); @@ -191,42 +175,35 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return new SurfacePolyline(); } @Override - protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) { super.updateSurfaceShape(dc, shape); // Display the airspace's interior color when its outline is disabled but its interior is enabled. This causes // the surface shape to display the color most similar to the 3D airspace. - if (!this.getActiveAttributes().isDrawOutline() && this.getActiveAttributes().isDrawInterior()) - { + if (!this.getActiveAttributes().isDrawOutline() && this.getActiveAttributes().isDrawInterior()) { shape.getAttributes().setDrawOutline(true); shape.getAttributes().setOutlineMaterial(this.getActiveAttributes().getInteriorMaterial()); } } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { ((SurfacePolyline) this.surfaceShape).setLocations(this.getLocations()); this.surfaceShape.setPathType(this.getPathType()); } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -238,16 +215,13 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) super.doMoveTo(oldRef, newRef); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -257,8 +231,7 @@ protected void doMoveTo(Position oldRef, Position newRef) int count = this.locations.size(); LatLon[] newLocations = new LatLon[count]; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { LatLon ll = this.locations.get(i); double distance = LatLon.greatCircleDistance(oldRef, ll).radians; double azimuth = LatLon.greatCircleAzimuth(oldRef, ll).radians; @@ -268,15 +241,12 @@ protected void doMoveTo(Position oldRef, Position newRef) this.setLocations(Arrays.asList(newLocations)); } - protected double getSplitThreshold() - { + protected double getSplitThreshold() { return this.splitThreshold; } - protected void setSplitThreshold(double splitThreshold) - { - if (splitThreshold <= 0.0) - { + protected void setSplitThreshold(double splitThreshold) { + if (splitThreshold <= 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "splitThreshold=" + splitThreshold); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -288,23 +258,18 @@ protected void setSplitThreshold(double splitThreshold) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected Vec4 computeReferenceCenter(DrawContext dc) - { + protected Vec4 computeReferenceCenter(DrawContext dc) { Extent extent = this.getExtent(dc); return extent != null ? extent.getCenter() : null; } - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { - if (dc == null) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -319,17 +284,18 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) String pathType = this.getPathType(); double splitThreshold = this.splitThreshold; - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(SPLIT_THRESHOLD); - if (o != null && o instanceof Double) + if (o != null && o instanceof Double) { splitThreshold = (Double) o; + } o = level.getValue(DISABLE_TERRAIN_CONFORMANCE); - if (o != null && o instanceof Boolean && (Boolean) o) + if (o != null && o instanceof Boolean && (Boolean) o) { terrainConformant[0] = terrainConformant[1] = false; + } } Vec4 referenceCenter = this.computeReferenceCenter(dc); @@ -338,26 +304,20 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int[] lightModelTwoSide = new int[1]; - try - { + try { gl.glGetIntegerv(GL2.GL_LIGHT_MODEL_TWO_SIDE, lightModelTwoSide, 0); dc.getView().pushReferenceCenter(dc, referenceCenter); - if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) - { + if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) { gl.glLightModeli(GL2.GL_LIGHT_MODEL_TWO_SIDE, GL2.GL_TRUE); this.drawCurtainFill(dc, count, locationArray, pathType, splitThreshold, altitudes, terrainConformant, - referenceCenter); - } - else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) - { + referenceCenter); + } else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) { this.drawCurtainOutline(dc, count, locationArray, pathType, splitThreshold, altitudes, - terrainConformant, referenceCenter); + terrainConformant, referenceCenter); } - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); gl.glLightModeli(GL2.GL_LIGHT_MODEL_TWO_SIDE, lightModelTwoSide[0]); } @@ -366,37 +326,31 @@ else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) //**************************************************************// //******************** Curtain ********************// //**************************************************************// + protected static class CurtainGeometry implements Cacheable { - protected static class CurtainGeometry implements Cacheable - { private Geometry fillIndexGeometry; private Geometry outlineIndexGeometry; private Geometry vertexGeometry; - public CurtainGeometry() - { + public CurtainGeometry() { this.fillIndexGeometry = new Geometry(); this.outlineIndexGeometry = new Geometry(); this.vertexGeometry = new Geometry(); } - public Geometry getFillIndexGeometry() - { + public Geometry getFillIndexGeometry() { return this.fillIndexGeometry; } - public Geometry getOutlineIndexGeometry() - { + public Geometry getOutlineIndexGeometry() { return this.outlineIndexGeometry; } - public Geometry getVertexGeometry() - { + public Geometry getVertexGeometry() { return this.vertexGeometry; } - public long getSizeInBytes() - { + public long getSizeInBytes() { long sizeInBytes = 0L; sizeInBytes += (this.fillIndexGeometry != null) ? this.fillIndexGeometry.getSizeInBytes() : 0L; sizeInBytes += (this.outlineIndexGeometry != null) ? this.outlineIndexGeometry.getSizeInBytes() : 0L; @@ -407,21 +361,20 @@ public long getSizeInBytes() } protected CurtainGeometry getCurtainGeometry(DrawContext dc, int count, LatLon[] locations, String pathType, - double splitThreshold, - double[] altitudes, boolean[] terrainConformant, - Vec4 referenceCenter) - { + double splitThreshold, + double[] altitudes, boolean[] terrainConformant, + Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "Curtain", - locations, pathType, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], - splitThreshold, referenceCenter); + locations, pathType, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], + splitThreshold, referenceCenter); CurtainGeometry geom = (CurtainGeometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null || this.isExpired(dc, geom.getVertexGeometry())) - { - if (geom == null) + if (geom == null || this.isExpired(dc, geom.getVertexGeometry())) { + if (geom == null) { geom = new CurtainGeometry(); + } this.makeCurtainGeometry(dc, count, locations, pathType, splitThreshold, altitudes, terrainConformant, - referenceCenter, geom); + referenceCenter, geom); this.updateExpiryCriteria(dc, geom.getVertexGeometry()); this.getGeometryCache().add(cacheKey, geom); } @@ -430,33 +383,30 @@ protected CurtainGeometry getCurtainGeometry(DrawContext dc, int count, LatLon[] } protected void drawCurtainFill(DrawContext dc, int count, LatLon[] locations, String pathType, - double splitThreshold, - double[] altitudes, boolean[] terrainConformant, - Vec4 referenceCenter) - { + double splitThreshold, + double[] altitudes, boolean[] terrainConformant, + Vec4 referenceCenter) { CurtainGeometry geom = this.getCurtainGeometry(dc, count, locations, pathType, splitThreshold, - altitudes, terrainConformant, referenceCenter); + altitudes, terrainConformant, referenceCenter); this.drawGeometry(dc, geom.getFillIndexGeometry(), geom.getVertexGeometry()); } protected void drawCurtainOutline(DrawContext dc, int count, LatLon[] locations, String pathType, - double splitThreshold, - double[] altitudes, boolean[] terrainConformant, - Vec4 referenceCenter) - { + double splitThreshold, + double[] altitudes, boolean[] terrainConformant, + Vec4 referenceCenter) { CurtainGeometry geom = this.getCurtainGeometry(dc, count, locations, pathType, splitThreshold, - altitudes, terrainConformant, referenceCenter); + altitudes, terrainConformant, referenceCenter); this.drawGeometry(dc, geom.getOutlineIndexGeometry(), geom.getVertexGeometry()); } protected void makeCurtainGeometry(DrawContext dc, int count, LatLon[] locations, String pathType, - double splitThreshold, - double[] altitudes, boolean[] terrainConformant, - Vec4 referenceCenter, - CurtainGeometry dest) - { + double splitThreshold, + double[] altitudes, boolean[] terrainConformant, + Vec4 referenceCenter, + CurtainGeometry dest) { int sections = count - 1; int[] counts = new int[3]; SectionRenderInfo[] ri = new SectionRenderInfo[sections]; @@ -470,15 +420,14 @@ protected void makeCurtainGeometry(DrawContext dc, int count, LatLon[] locations float[] verts = new float[3 * counts[2]]; float[] norms = new float[3 * counts[2]]; - for (int s = 0; s < sections; s++) - { + for (int s = 0; s < sections; s++) { this.makeSectionFillIndices(ri[s].pillars, ri[s].firstVertex, ri[s].firstFillIndex, fillIndices); this.makeSectionOutlineIndices(ri[s].pillars, ri[s].firstVertex, ri[s].firstOutlineIndex, outlineIndices); this.makeSectionVertices(dc, ri[s].begin, ri[s].end, ri[s].pathType, altitudes, terrainConformant, - ri[s].pillars, ri[s].firstVertex, verts, referenceCenter); + ri[s].pillars, ri[s].firstVertex, verts, referenceCenter); this.getGeometryBuilder().makeIndexedTriangleStripNormals(ri[s].firstFillIndex, ri[s].fillIndexCount, - fillIndices, ri[s].firstVertex, ri[s].vertexCount, verts, norms); + fillIndices, ri[s].firstVertex, ri[s].vertexCount, verts, norms); } dest.getFillIndexGeometry().setElementData(fillDrawMode, counts[0], fillIndices); @@ -490,9 +439,8 @@ protected void makeCurtainGeometry(DrawContext dc, int count, LatLon[] locations //**************************************************************// //******************** Section ********************// //**************************************************************// + protected static class SectionRenderInfo { - protected static class SectionRenderInfo - { LatLon begin, end; String pathType; int pillars; @@ -500,8 +448,7 @@ protected static class SectionRenderInfo int firstFillIndex, fillIndexCount; int firstOutlineIndex, outlineIndexCount; - private SectionRenderInfo(LatLon begin, LatLon end, String pathType) - { + private SectionRenderInfo(LatLon begin, LatLon end, String pathType) { this.begin = begin; this.end = end; this.pathType = pathType; @@ -509,13 +456,11 @@ private SectionRenderInfo(LatLon begin, LatLon end, String pathType) } protected void makeSectionInfo(DrawContext dc, int count, LatLon[] locations, String pathType, - double splitThreshold, - SectionRenderInfo[] ri, int[] counts) - { + double splitThreshold, + SectionRenderInfo[] ri, int[] counts) { int sectionCount = count - 1; - for (int i = 0; i < sectionCount; i++) - { + for (int i = 0; i < sectionCount; i++) { ri[i] = new SectionRenderInfo(locations[i], locations[i + 1], pathType); ri[i].pillars = this.getSectionPillarCount(dc, ri[i].begin, ri[i].end, ri[i].pathType, splitThreshold); ri[i].firstFillIndex = counts[0]; @@ -531,19 +476,16 @@ protected void makeSectionInfo(DrawContext dc, int count, LatLon[] locations, St } protected int getSectionPillarCount(DrawContext dc, LatLon begin, LatLon end, String pathType, - double splitThreshold) - { + double splitThreshold) { Globe globe; double arcLength, distance; int pillars; globe = dc.getGlobe(); - if (AVKey.RHUMB_LINE.equalsIgnoreCase(pathType) || AVKey.LOXODROME.equalsIgnoreCase(pathType)) - { + if (AVKey.RHUMB_LINE.equalsIgnoreCase(pathType) || AVKey.LOXODROME.equalsIgnoreCase(pathType)) { arcLength = LatLon.rhumbDistance(begin, end).radians; - } - else // (AVKey.GREAT_CIRCLE.equalsIgnoreCase(pathType) + } else // (AVKey.GREAT_CIRCLE.equalsIgnoreCase(pathType) { arcLength = LatLon.greatCircleDistance(begin, end).radians; } @@ -555,47 +497,39 @@ protected int getSectionPillarCount(DrawContext dc, LatLon begin, LatLon end, St return pillars; } - protected int getSectionFillDrawMode() - { + protected int getSectionFillDrawMode() { return GL.GL_TRIANGLE_STRIP; } - protected int getSectionOutlineDrawMode() - { + protected int getSectionOutlineDrawMode() { return GL.GL_LINES; } - protected int getSectionFillIndexCount(int pillars) - { + protected int getSectionFillIndexCount(int pillars) { return 2 * (pillars + 1); } - protected int getSectionOutlineIndexCount(int pillars) - { + protected int getSectionOutlineIndexCount(int pillars) { return 4 * (pillars + 1); } - protected int getSectionVertexCount(int pillars) - { + protected int getSectionVertexCount(int pillars) { return 2 * (pillars + 1); } - protected void makeSectionFillIndices(int pillars, int vertexPos, int indexPos, int[] dest) - { + protected void makeSectionFillIndices(int pillars, int vertexPos, int indexPos, int[] dest) { int p; int index, vertex; index = indexPos; - for (p = 0; p <= pillars; p++) - { + for (p = 0; p <= pillars; p++) { vertex = vertexPos + 2 * p; dest[index++] = vertex + 1; dest[index++] = vertex; } } - protected void makeSectionOutlineIndices(int pillars, int vertexPos, int indexPos, int[] dest) - { + protected void makeSectionOutlineIndices(int pillars, int vertexPos, int indexPos, int[] dest) { int p; int index, vertex; index = indexPos; @@ -604,8 +538,7 @@ protected void makeSectionOutlineIndices(int pillars, int vertexPos, int indexPo dest[index++] = vertex + 1; dest[index++] = vertex; - for (p = 0; p < pillars; p++) - { + for (p = 0; p < pillars; p++) { vertex = vertexPos + 2 * p; dest[index++] = vertex; dest[index++] = vertex + 2; @@ -619,18 +552,15 @@ protected void makeSectionOutlineIndices(int pillars, int vertexPos, int indexPo } protected void makeSectionVertices(DrawContext dc, LatLon begin, LatLon end, String pathType, - double[] altitude, boolean terrainConformant[], - int pillars, int vertexPos, float[] dest, Vec4 referenceCenter) - { + double[] altitude, boolean terrainConformant[], + int pillars, int vertexPos, float[] dest, Vec4 referenceCenter) { Globe globe = dc.getGlobe(); double arcLength, azimuth; - if (AVKey.RHUMB_LINE.equalsIgnoreCase(pathType) || AVKey.LOXODROME.equalsIgnoreCase(pathType)) - { + if (AVKey.RHUMB_LINE.equalsIgnoreCase(pathType) || AVKey.LOXODROME.equalsIgnoreCase(pathType)) { arcLength = LatLon.rhumbDistance(begin, end).radians; azimuth = LatLon.rhumbAzimuth(begin, end).radians; - } - else // (AVKey.GREAT_CIRCLE.equalsIgnoreCase(pathType) + } else // (AVKey.GREAT_CIRCLE.equalsIgnoreCase(pathType) { arcLength = LatLon.greatCircleDistance(begin, end).radians; azimuth = LatLon.greatCircleAzimuth(begin, end).radians; @@ -641,31 +571,31 @@ protected void makeSectionVertices(DrawContext dc, LatLon begin, LatLon end, Str // Set up to take altitude from the curtain positions if Positions are specified. double alt0 = 0; Double dAlt = null; - if (this.isApplyPositionAltitude() && begin instanceof Position && end instanceof Position) - { + if (this.isApplyPositionAltitude() && begin instanceof Position && end instanceof Position) { alt0 = ((Position) begin).getAltitude(); dAlt = (((Position) end).getAltitude() - alt0) / (double) pillars; } - for (int p = 0; p <= pillars; p++) - { + for (int p = 0; p <= pillars; p++) { double length = p * dlength; LatLon ll; - if (AVKey.RHUMB_LINE.equalsIgnoreCase(pathType) || AVKey.LOXODROME.equalsIgnoreCase(pathType)) + if (AVKey.RHUMB_LINE.equalsIgnoreCase(pathType) || AVKey.LOXODROME.equalsIgnoreCase(pathType)) { ll = LatLon.rhumbEndPosition(begin, azimuth, length); - else // (AVKey.GREAT_CIRCLE.equalsIgnoreCase(pathType) + } else // (AVKey.GREAT_CIRCLE.equalsIgnoreCase(pathType) + { ll = LatLon.greatCircleEndPosition(begin, azimuth, length); + } - for (int s = 0; s < 2; s++) - { + for (int s = 0; s < 2; s++) { int index = s + 2 * p; index = 3 * (vertexPos + index); // For upper altitude, use the Position's if specified, otherwise the curtain's upper altitude. double elevation = (dAlt != null && s == 1) ? alt0 + p * dAlt : altitude[s]; - if (terrainConformant[s]) + if (terrainConformant[s]) { elevation += this.computeElevationAt(dc, ll.getLatitude(), ll.getLongitude()); + } Vec4 vec = globe.computePointFromPosition(ll.getLatitude(), ll.getLongitude(), elevation); dest[index] = (float) (vec.x - referenceCenter.x); @@ -675,47 +605,43 @@ protected void makeSectionVertices(DrawContext dc, LatLon begin, LatLon end, Str } } - protected void makeTessellatedLocations(Globe globe, List tessellatedLocations) - { - if (this.getLocations() == null) + protected void makeTessellatedLocations(Globe globe, List tessellatedLocations) { + if (this.getLocations() == null) { return; + } Iterator iter = this.getLocations().iterator(); - if (!iter.hasNext()) + if (!iter.hasNext()) { return; + } LatLon locA = iter.next(); tessellatedLocations.add(locA); // Add the curtain's first location. - while (iter.hasNext()) - { + while (iter.hasNext()) { LatLon locB = iter.next(); this.makeSegment(globe, locA, locB, tessellatedLocations); locA = locB; } } - protected void makeSegment(Globe globe, LatLon locA, LatLon locB, List tessellatedLocations) - { + protected void makeSegment(Globe globe, LatLon locA, LatLon locB, List tessellatedLocations) { Angle segmentAzimuth; Angle segmentDistance; boolean isRhumbSegment = AVKey.RHUMB_LINE.equalsIgnoreCase(this.getPathType()) - || AVKey.LOXODROME.equalsIgnoreCase(this.getPathType()); + || AVKey.LOXODROME.equalsIgnoreCase(this.getPathType()); - if (isRhumbSegment) - { + if (isRhumbSegment) { segmentAzimuth = LatLon.rhumbAzimuth(locA, locB); segmentDistance = LatLon.rhumbDistance(locA, locB); - } - else // Default to a great circle segment. + } else // Default to a great circle segment. { segmentAzimuth = LatLon.greatCircleAzimuth(locA, locB); segmentDistance = LatLon.greatCircleDistance(locA, locB); } double arcLength = segmentDistance.radians * globe.getRadius(); - if (arcLength <= this.getSplitThreshold()) - { + if (arcLength <= this.getSplitThreshold()) { tessellatedLocations.add(locB); return; } @@ -723,24 +649,20 @@ protected void makeSegment(Globe globe, LatLon locA, LatLon locB, List t int numSubsegments = (int) Math.ceil(arcLength / this.getSplitThreshold()); double segmentIncrement = segmentDistance.radians / (double) numSubsegments; - for (double s = 0; s < segmentDistance.radians; ) - { + for (double s = 0; s < segmentDistance.radians;) { // If we've reached or passed the second location, then add the second location and break. We handle this // case specially to ensure that the actual second location is added, instead of a computed location very // close to it. s += segmentIncrement; - if (s >= segmentDistance.radians) - { + if (s >= segmentDistance.radians) { tessellatedLocations.add(locB); break; } LatLon ll; - if (isRhumbSegment) - { + if (isRhumbSegment) { ll = LatLon.rhumbEndPosition(locA, segmentAzimuth, Angle.fromRadians(s)); - } - else // Default to a great circle segment. + } else // Default to a great circle segment. { ll = LatLon.greatCircleEndPosition(locA, segmentAzimuth, Angle.fromRadians(s)); } @@ -752,29 +674,29 @@ protected void makeSegment(Globe globe, LatLon locA, LatLon locB, List t //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); - if (this.locations != null) + if (this.locations != null) { rs.addStateValueAsLatLonList(context, "locations", this.locations); + } rs.addStateValueAsString(context, "pathType", this.getPathType()); } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); List locations = rs.getStateValueAsLatLonList(context, "locations"); - if (locations != null) + if (locations != null) { this.setLocations(locations); + } String s = rs.getStateValueAsString(context, "pathType"); - if (s != null) + if (s != null) { this.setPathType(s); + } } } diff --git a/src/gov/nasa/worldwind/render/airspaces/DetailLevel.java b/src/gov/nasa/worldwind/render/airspaces/DetailLevel.java index 8eac76dde5..3c4898cee9 100644 --- a/src/gov/nasa/worldwind/render/airspaces/DetailLevel.java +++ b/src/gov/nasa/worldwind/render/airspaces/DetailLevel.java @@ -12,8 +12,8 @@ * @author dcollins * @version $Id: DetailLevel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface DetailLevel extends Comparable, AVList -{ +public interface DetailLevel extends Comparable, AVList { + boolean meetsCriteria(DrawContext dc, Airspace airspace); int compareTo(DetailLevel level); diff --git a/src/gov/nasa/worldwind/render/airspaces/Geometry.java b/src/gov/nasa/worldwind/render/airspaces/Geometry.java index 0eb5eeb5e2..bf4355e3ad 100644 --- a/src/gov/nasa/worldwind/render/airspaces/Geometry.java +++ b/src/gov/nasa/worldwind/render/airspaces/Geometry.java @@ -18,60 +18,60 @@ * @author dcollins * @version $Id: Geometry.java 2210 2014-08-08 22:06:02Z tgaskins $ */ -public class Geometry extends AVListImpl implements Cacheable -{ - public static class CacheKey - { +public class Geometry extends AVListImpl implements Cacheable { + + public static class CacheKey { + private final GlobeStateKey globeStateKey; private final Class cls; private final String key; private final Object[] params; private int hash = 0; - public CacheKey(Globe globe, Class cls, String key, Object... params) - { + public CacheKey(Globe globe, Class cls, String key, Object... params) { this.globeStateKey = globe != null ? globe.getGlobeStateKey() : null; this.cls = cls; this.key = key; this.params = params; } - public CacheKey(Class cls, String key, Object... params) - { + public CacheKey(Class cls, String key, Object... params) { this(null, cls, key, params); } - public CacheKey(String key, Object... params) - { + public CacheKey(String key, Object... params) { this(null, null, key, params); } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } CacheKey that = (CacheKey) o; - if (this.globeStateKey != null ? !this.globeStateKey.equals(that.globeStateKey) : that.globeStateKey != null) + if (this.globeStateKey != null ? !this.globeStateKey.equals(that.globeStateKey) : that.globeStateKey != null) { return false; - if (this.cls != null ? !this.cls.equals(that.cls) : that.cls != null) + } + if (this.cls != null ? !this.cls.equals(that.cls) : that.cls != null) { return false; - if (this.key != null ? !this.key.equals(that.key) : that.key != null) + } + if (this.key != null ? !this.key.equals(that.key) : that.key != null) { return false; + } //noinspection RedundantIfStatement - if (!Arrays.deepEquals(this.params, that.params)) + if (!Arrays.deepEquals(this.params, that.params)) { return false; + } return true; } - public int hashCode() - { - if (this.hash == 0) - { + public int hashCode() { + if (this.hash == 0) { int result; result = (this.globeStateKey != null ? this.globeStateKey.hashCode() : 0); result = 31 * result + (this.cls != null ? this.cls.hashCode() : 0); @@ -96,8 +96,7 @@ public int hashCode() private int[] stride; private Buffer[] buffer; - public Geometry() - { + public Geometry() { this.mode = new int[4]; this.count = new int[4]; this.size = new int[4]; @@ -106,43 +105,35 @@ public Geometry() this.buffer = new Buffer[4]; } - public int getMode(int object) - { + public int getMode(int object) { return this.mode[object]; } - public void setMode(int type, int mode) - { + public void setMode(int type, int mode) { this.mode[type] = mode; } - public int getCount(int type) - { + public int getCount(int type) { return this.count[type]; } - public int getSize(int type) - { + public int getSize(int type) { return this.size[type]; } - public int getGLType(int type) - { + public int getGLType(int type) { return this.glType[type]; } - public int getStride(int type) - { + public int getStride(int type) { return this.stride[type]; } - public Buffer getBuffer(int type) - { + public Buffer getBuffer(int type) { return this.buffer[type]; } - public void setData(int type, int size, int glType, int stride, int count, int[] src, int srcPos) - { + public void setData(int type, int size, int glType, int stride, int count, int[] src, int srcPos) { this.size[type] = size; this.glType[type] = glType; this.stride[type] = stride; @@ -150,17 +141,15 @@ public void setData(int type, int size, int glType, int stride, int count, int[] int numCoords = size * count; if (this.buffer[type] == null - || this.buffer[type].capacity() < numCoords - || !(this.buffer[type] instanceof IntBuffer)) - { + || this.buffer[type].capacity() < numCoords + || !(this.buffer[type] instanceof IntBuffer)) { this.buffer[type] = Buffers.newDirectIntBuffer(numCoords); } this.bufferCopy(src, srcPos, (IntBuffer) this.buffer[type], 0, numCoords); } - public void setData(int type, int size, int stride, int count, float[] src, int srcPos) - { + public void setData(int type, int size, int stride, int count, float[] src, int srcPos) { this.size[type] = size; this.glType[type] = GL.GL_FLOAT; this.stride[type] = stride; @@ -168,9 +157,8 @@ public void setData(int type, int size, int stride, int count, float[] src, int int numCoords = size * count; if (this.buffer[type] == null - || this.buffer[type].capacity() < numCoords - || !(this.buffer[type] instanceof FloatBuffer)) - { + || this.buffer[type].capacity() < numCoords + || !(this.buffer[type] instanceof FloatBuffer)) { this.buffer[type] = Buffers.newDirectFloatBuffer(numCoords); } @@ -178,8 +166,7 @@ public void setData(int type, int size, int stride, int count, float[] src, int } // version using float buffer instead of array - public void setData(int type, int size, int stride, int count, FloatBuffer src) - { + public void setData(int type, int size, int stride, int count, FloatBuffer src) { this.size[type] = size; this.glType[type] = GL.GL_FLOAT; this.stride[type] = stride; @@ -187,22 +174,19 @@ public void setData(int type, int size, int stride, int count, FloatBuffer src) int numCoords = size * count; if (this.buffer[type] == null - || this.buffer[type].capacity() < numCoords - || !(this.buffer[type] instanceof FloatBuffer)) - { + || this.buffer[type].capacity() < numCoords + || !(this.buffer[type] instanceof FloatBuffer)) { this.buffer[type] = src; } } - public void setElementData(int mode, int count, int[] src) - { + public void setElementData(int mode, int count, int[] src) { this.setMode(ELEMENT, mode); this.setData(ELEMENT, 1, GL.GL_UNSIGNED_INT, 0, count, src, 0); } // version using buffer instead of array - public void setElementData(int mode, int count, IntBuffer src) - { + public void setElementData(int mode, int count, IntBuffer src) { this.setMode(ELEMENT, mode); this.buffer[ELEMENT] = src; this.size[ELEMENT] = 1; @@ -211,14 +195,12 @@ public void setElementData(int mode, int count, IntBuffer src) this.count[ELEMENT] = count; } - public void setVertexData(int count, float[] src) - { + public void setVertexData(int count, float[] src) { this.setData(VERTEX, 3, 0, count, src, 0); } // version using float buffer - public void setVertexData(int count, FloatBuffer src) - { + public void setVertexData(int count, FloatBuffer src) { this.buffer[VERTEX] = src; this.size[VERTEX] = 3; this.glType[VERTEX] = GL.GL_FLOAT; @@ -226,14 +208,12 @@ public void setVertexData(int count, FloatBuffer src) this.count[VERTEX] = count; } - public void setNormalData(int count, float[] src) - { + public void setNormalData(int count, float[] src) { this.setData(NORMAL, 3, 0, count, src, 0); } // version using float buffer - public void setNormalData(int count, FloatBuffer src) - { + public void setNormalData(int count, FloatBuffer src) { this.buffer[NORMAL] = src; this.size[NORMAL] = 3; this.glType[NORMAL] = GL.GL_FLOAT; @@ -241,14 +221,12 @@ public void setNormalData(int count, FloatBuffer src) this.count[NORMAL] = count; } - public void setTextureCoordData(int count, float[] src) - { + public void setTextureCoordData(int count, float[] src) { this.setData(TEXTURE, 2, 0, count, src, 0); } // version using float buffer - public void setTextureCoordData(int count, FloatBuffer src) - { + public void setTextureCoordData(int count, FloatBuffer src) { this.buffer[TEXTURE] = src; this.size[NORMAL] = 2; this.glType[NORMAL] = GL.GL_FLOAT; @@ -256,8 +234,7 @@ public void setTextureCoordData(int count, FloatBuffer src) this.count[NORMAL] = count; } - public void clear(int type) - { + public void clear(int type) { this.mode[type] = 0; this.count[type] = 0; this.size[type] = 0; @@ -266,24 +243,21 @@ public void clear(int type) this.buffer[type] = null; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return this.bufferSize(ELEMENT) + this.bufferSize(VERTEX) + this.bufferSize(NORMAL); } - private long bufferSize(int bufferType) - { + private long bufferSize(int bufferType) { long size = 0L; - if (this.buffer[bufferType] != null) + if (this.buffer[bufferType] != null) { size = this.sizeOf(this.glType[bufferType]) * this.buffer[bufferType].capacity(); + } return size; } - private long sizeOf(int glType) - { + private long sizeOf(int glType) { long size = 0L; - switch (glType) - { + switch (glType) { case GL2.GL_BYTE: size = 1L; break; @@ -303,15 +277,13 @@ private long sizeOf(int glType) return size; } - private void bufferCopy(int[] src, int srcPos, IntBuffer dest, int destPos, int length) - { + private void bufferCopy(int[] src, int srcPos, IntBuffer dest, int destPos, int length) { dest.position(destPos); dest.put(src, srcPos, length); dest.position(destPos); } - private void bufferCopy(float[] src, int srcPos, FloatBuffer dest, int destPos, int length) - { + private void bufferCopy(float[] src, int srcPos, FloatBuffer dest, int destPos, int length) { dest.position(destPos); dest.put(src, srcPos, length); dest.position(destPos); diff --git a/src/gov/nasa/worldwind/render/airspaces/Orbit.java b/src/gov/nasa/worldwind/render/airspaces/Orbit.java index b553a718ae..a02aa057f4 100644 --- a/src/gov/nasa/worldwind/render/airspaces/Orbit.java +++ b/src/gov/nasa/worldwind/render/airspaces/Orbit.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.geom.Box; @@ -19,10 +18,10 @@ * @author tag * @version $Id: Orbit.java 2454 2014-11-21 17:52:49Z dcollins $ */ -public class Orbit extends AbstractAirspace -{ - public interface OrbitType - { +public class Orbit extends AbstractAirspace { + + public interface OrbitType { + public static final String LEFT = "Left"; public static final String CENTER = "Center"; public static final String RIGHT = "Right"; @@ -47,28 +46,23 @@ public interface OrbitType private int stacks = DEFAULT_STACKS; private int loops = DEFAULT_LOOPS; - public Orbit(LatLon location1, LatLon location2, String orbitType, double width) - { - if (location1 == null) - { + public Orbit(LatLon location1, LatLon location2, String orbitType, double width) { + if (location1 == null) { String message = "nullValue.Location1IsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (location2 == null) - { + if (location2 == null) { String message = "nullValue.Location2IsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (orbitType == null) - { + if (orbitType == null) { String message = "nullValue.OrbitTypeIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (width < 0.0) - { + if (width < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width=" + width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -81,8 +75,7 @@ public Orbit(LatLon location1, LatLon location2, String orbitType, double width) this.makeDefaultDetailLevels(); } - public Orbit(Orbit source) - { + public Orbit(Orbit source) { super(source); this.location1 = source.location1; @@ -98,19 +91,16 @@ public Orbit(Orbit source) this.makeDefaultDetailLevels(); } - public Orbit(AirspaceAttributes attributes) - { + public Orbit(AirspaceAttributes attributes) { super(attributes); this.makeDefaultDetailLevels(); } - public Orbit() - { + public Orbit() { this.makeDefaultDetailLevels(); } - private void makeDefaultDetailLevels() - { + private void makeDefaultDetailLevels() { List levels = new ArrayList(); double[] ramp = ScreenSizeDetailLevel.computeDefaultScreenSizeRamp(5); @@ -158,24 +148,20 @@ private void makeDefaultDetailLevels() this.setDetailLevels(levels); } - public LatLon[] getLocations() - { + public LatLon[] getLocations() { LatLon[] array = new LatLon[2]; array[0] = this.location1; array[1] = this.location2; return array; } - public void setLocations(LatLon location1, LatLon location2) - { - if (location1 == null) - { + public void setLocations(LatLon location1, LatLon location2) { + if (location1 == null) { String message = "nullValue.Location1IsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (location2 == null) - { + if (location2 == null) { String message = "nullValue.Location2IsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -186,12 +172,10 @@ public void setLocations(LatLon location1, LatLon location2) this.invalidateAirspaceData(); } - protected LatLon[] getAdjustedLocations(Globe globe) - { + protected LatLon[] getAdjustedLocations(Globe globe) { LatLon[] locations = this.getLocations(); - if (OrbitType.CENTER.equals(this.getOrbitType())) - { + if (OrbitType.CENTER.equals(this.getOrbitType())) { return locations; } @@ -199,13 +183,10 @@ protected LatLon[] getAdjustedLocations(Globe globe) double az2 = LatLon.greatCircleAzimuth(locations[1], locations[0]).radians; double r = (this.getWidth() / 2) / globe.getRadius(); - if (Orbit.OrbitType.LEFT.equals(this.getOrbitType())) - { + if (Orbit.OrbitType.LEFT.equals(this.getOrbitType())) { locations[0] = LatLon.greatCircleEndPosition(locations[0], az1 - (Math.PI / 2), r); locations[1] = LatLon.greatCircleEndPosition(locations[1], az2 + (Math.PI / 2), r); - } - else if (Orbit.OrbitType.RIGHT.equals(this.getOrbitType())) - { + } else if (Orbit.OrbitType.RIGHT.equals(this.getOrbitType())) { locations[0] = LatLon.greatCircleEndPosition(locations[0], az1 + (Math.PI / 2), r); locations[1] = LatLon.greatCircleEndPosition(locations[1], az2 - (Math.PI / 2), r); } @@ -213,15 +194,12 @@ else if (Orbit.OrbitType.RIGHT.equals(this.getOrbitType())) return locations; } - public String getOrbitType() - { + public String getOrbitType() { return this.orbitType; } - public void setOrbitType(String orbitType) - { - if (orbitType == null) - { + public void setOrbitType(String orbitType) { + if (orbitType == null) { String message = "nullValue.OrbitTypeIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -231,15 +209,12 @@ public void setOrbitType(String orbitType) this.invalidateAirspaceData(); } - public double getWidth() - { + public double getWidth() { return this.width; } - public void setWidth(double width) - { - if (width < 0.0) - { + public void setWidth(double width) { + if (width < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width=" + width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -249,39 +224,35 @@ public void setWidth(double width) this.invalidateAirspaceData(); } - public boolean isEnableCaps() - { + public boolean isEnableCaps() { return this.enableCaps; } - public void setEnableCaps(boolean enable) - { + public void setEnableCaps(boolean enable) { this.enableCaps = enable; } - public Position getReferencePosition() - { + public Position getReferencePosition() { double[] altitudes = this.getAltitudes(); return new Position(this.location1, altitudes[0]); } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { List points = this.computeMinimalGeometry(globe, verticalExaggeration); - if (points == null || points.isEmpty()) + if (points == null || points.isEmpty()) { return null; + } return Box.computeBoundingBox(points); } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { LatLon[] center = this.getAdjustedLocations(globe); double radius = this.getWidth() / 2.0; GeometryBuilder gb = this.getGeometryBuilder(); LatLon[] locations = gb.makeLongDiskLocations(globe, center[0], center[1], 0, radius, - MINIMAL_GEOMETRY_ARC_SLICES, MINIMAL_GEOMETRY_LENGTH_SLICES, MINIMAL_GEOMETRY_LOOPS); + MINIMAL_GEOMETRY_ARC_SLICES, MINIMAL_GEOMETRY_LENGTH_SLICES, MINIMAL_GEOMETRY_LOOPS); ArrayList points = new ArrayList(); this.makeExtremePoints(globe, verticalExaggeration, Arrays.asList(locations), points); @@ -289,38 +260,32 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera return points; } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } List newLocations = LatLon.computeShiftedLocations(globe, oldRef, newRef, - Arrays.asList(this.getLocations())); + Arrays.asList(this.getLocations())); this.setLocations(newLocations.get(0), newLocations.get(1)); super.doMoveTo(oldRef, newRef); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -330,8 +295,7 @@ protected void doMoveTo(Position oldRef, Position newRef) LatLon[] locations = this.getLocations(); int count = locations.length; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { double distance = LatLon.greatCircleDistance(oldRef, locations[i]).radians; double azimuth = LatLon.greatCircleAzimuth(oldRef, locations[i]).radians; locations[i] = LatLon.greatCircleEndPosition(newRef, azimuth, distance); @@ -340,14 +304,12 @@ protected void doMoveTo(Position oldRef, Position newRef) } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return new SurfacePolygon(); } @Override - protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) { super.updateSurfaceShape(dc, shape); boolean mustDrawInterior = this.getActiveAttributes().isDrawInterior() && this.isEnableCaps(); @@ -355,25 +317,21 @@ protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { LatLon[] center = this.getAdjustedLocations(dc.getGlobe()); double radius = this.getWidth() / 2.0; GeometryBuilder gb = this.getGeometryBuilder(); LatLon[] locations = gb.makeLongCylinderLocations(dc.getGlobe(), center[0], center[1], radius, this.arcSlices, - this.lengthSlices); + this.lengthSlices); ((SurfacePolygon) shape).setOuterBoundary(Arrays.asList(locations)); } - protected int getArcSlices() - { + protected int getArcSlices() { return this.arcSlices; } - protected void setArcSlices(int arcSlices) - { - if (arcSlices < 0) - { + protected void setArcSlices(int arcSlices) { + if (arcSlices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -382,15 +340,12 @@ protected void setArcSlices(int arcSlices) this.arcSlices = arcSlices; } - protected int getLengthSlices() - { + protected int getLengthSlices() { return this.lengthSlices; } - protected void setLengthSlices(int lengthSlices) - { - if (lengthSlices < 0) - { + protected void setLengthSlices(int lengthSlices) { + if (lengthSlices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "lengthSlices=" + lengthSlices); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -399,20 +354,16 @@ protected void setLengthSlices(int lengthSlices) this.lengthSlices = lengthSlices; } - protected int getStacks() - { + protected int getStacks() { return this.stacks; } - protected int getLoops() - { + protected int getLoops() { return this.loops; } - protected void setLoops(int loops) - { - if (loops < 0) - { + protected void setLoops(int loops) { + if (loops < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -424,17 +375,13 @@ protected void setLoops(int loops) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected Vec4 computeReferenceCenter(DrawContext dc) - { - if (dc == null) - { + protected Vec4 computeReferenceCenter(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -443,19 +390,17 @@ protected Vec4 computeReferenceCenter(DrawContext dc) Globe globe = dc.getGlobe(); double[] altitudes = this.getAltitudes(dc.getVerticalExaggeration()); Vec4 point1 = globe.computeEllipsoidalPointFromPosition( - this.location1.latitude, this.location1.longitude, altitudes[0]); + this.location1.latitude, this.location1.longitude, altitudes[0]); Vec4 point2 = globe.computeEllipsoidalPointFromPosition( - this.location2.latitude, this.location2.longitude, altitudes[0]); + this.location2.latitude, this.location2.longitude, altitudes[0]); Vec4 centerPoint = Vec4.mix3(0.5, point1, point2); Position centerPos = globe.computePositionFromEllipsoidalPoint(centerPoint); return globe.computePointFromPosition(centerPos.latitude, centerPos.longitude, - altitudes[0]); // model-coordinate reference center + altitudes[0]); // model-coordinate reference center } - protected Matrix computeEllipsoidalTransform(Globe globe, double verticalExaggeration) - { - if (globe == null) - { + protected Matrix computeEllipsoidalTransform(Globe globe, double verticalExaggeration) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -465,9 +410,9 @@ protected Matrix computeEllipsoidalTransform(Globe globe, double verticalExagger double radius = this.width / 2.0; Vec4 point1 = globe.computeEllipsoidalPointFromPosition( - this.location1.getLatitude(), this.location1.getLongitude(), altitudes[0]); + this.location1.getLatitude(), this.location1.getLongitude(), altitudes[0]); Vec4 point2 = globe.computeEllipsoidalPointFromPosition( - this.location2.getLatitude(), this.location2.getLongitude(), altitudes[0]); + this.location2.getLatitude(), this.location2.getLongitude(), altitudes[0]); Vec4 centerPoint = Vec4.mix3(0.5, point1, point2); Position centerPos = globe.computePositionFromEllipsoidalPoint(centerPoint); Vec4 upVec = globe.computeEllipsoidalNormalAtLocation(centerPos.latitude, centerPos.longitude); @@ -475,30 +420,27 @@ protected Matrix computeEllipsoidalTransform(Globe globe, double verticalExagger axis = axis.normalize3(); Matrix transform = Matrix.fromModelLookAt(point1, point1.add3(upVec), axis); - if (OrbitType.LEFT.equals(this.orbitType)) + if (OrbitType.LEFT.equals(this.orbitType)) { transform = transform.multiply(Matrix.fromTranslation(-radius, 0.0, 0.0)); - else if (OrbitType.RIGHT.equals(this.orbitType)) + } else if (OrbitType.RIGHT.equals(this.orbitType)) { transform = transform.multiply(Matrix.fromTranslation(radius, 0.0, 0.0)); + } return transform; } - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { - if (dc == null) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -507,35 +449,39 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) LatLon[] locations = this.getAdjustedLocations(dc.getGlobe()); double[] altitudes = this.getAltitudes(dc.getVerticalExaggeration()); boolean[] terrainConformant = this.isTerrainConforming(); - double[] radii = new double[] {0.0, this.width / 2}; + double[] radii = new double[]{0.0, this.width / 2}; int arcSlices = this.arcSlices; int lengthSlices = this.lengthSlices; int stacks = this.stacks; int loops = this.loops; - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(ARC_SLICES); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { arcSlices = (Integer) o; + } o = level.getValue(LENGTH_SLICES); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { lengthSlices = (Integer) o; + } o = level.getValue(STACKS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { stacks = (Integer) o; + } o = level.getValue(LOOPS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { loops = (Integer) o; + } o = level.getValue(DISABLE_TERRAIN_CONFORMANCE); - if (o != null && o instanceof Boolean && ((Boolean) o)) + if (o != null && o instanceof Boolean && ((Boolean) o)) { terrainConformant[0] = terrainConformant[1] = false; + } } Vec4 referenceCenter = this.computeReferenceCenter(dc); @@ -544,50 +490,39 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { dc.getView().pushReferenceCenter(dc, referenceCenter); - if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) - { + if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) { this.drawLongCylinderOutline(dc, locations[0], locations[1], radii[1], altitudes, terrainConformant, - arcSlices, lengthSlices, stacks, GeometryBuilder.OUTSIDE, referenceCenter); - } - else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) - { - if (this.enableCaps) - { + arcSlices, lengthSlices, stacks, GeometryBuilder.OUTSIDE, referenceCenter); + } else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) { + if (this.enableCaps) { ogsh.pushAttrib(gl, GL2.GL_POLYGON_BIT); gl.glEnable(GL.GL_CULL_FACE); gl.glFrontFace(GL.GL_CCW); } - if (this.enableCaps) - { + if (this.enableCaps) { // Caps aren't rendered if radii are equal. - if (radii[0] != radii[1]) - { + if (radii[0] != radii[1]) { this.drawLongDisk(dc, locations[0], locations[1], radii, altitudes[1], terrainConformant[1], - arcSlices, lengthSlices, loops, GeometryBuilder.OUTSIDE, referenceCenter); + arcSlices, lengthSlices, loops, GeometryBuilder.OUTSIDE, referenceCenter); // Bottom cap isn't rendered if airspace is collapsed. - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { this.drawLongDisk(dc, locations[0], locations[1], radii, altitudes[0], terrainConformant[0], - arcSlices, lengthSlices, loops, GeometryBuilder.INSIDE, referenceCenter); + arcSlices, lengthSlices, loops, GeometryBuilder.INSIDE, referenceCenter); } } } // Long cylinder isn't rendered if airspace is collapsed. - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { this.drawLongCylinder(dc, locations[0], locations[1], radii[1], altitudes, terrainConformant, - arcSlices, lengthSlices, stacks, GeometryBuilder.OUTSIDE, referenceCenter); + arcSlices, lengthSlices, stacks, GeometryBuilder.OUTSIDE, referenceCenter); } } - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); ogsh.pop(gl); } @@ -596,18 +531,15 @@ else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) //**************************************************************// //******************** Long Cylinder ********************// //**************************************************************// - private void drawLongCylinder(DrawContext dc, LatLon center1, LatLon center2, double radius, double[] altitudes, - boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, int orientation, Vec4 referenceCenter) - { + boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, int orientation, Vec4 referenceCenter) { Geometry vertexGeom = this.createLongCylinderVertexGeometry(dc, center1, center2, radius, altitudes, - terrainConformant, arcSlices, lengthSlices, stacks, orientation, referenceCenter); + terrainConformant, arcSlices, lengthSlices, stacks, orientation, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "LongCylinder.Indices", arcSlices, lengthSlices, - stacks, orientation); + stacks, orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makeLongCylinderIndices(arcSlices, lengthSlices, stacks, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -617,17 +549,15 @@ private void drawLongCylinder(DrawContext dc, LatLon center1, LatLon center2, do } private void drawLongCylinderOutline(DrawContext dc, LatLon center1, LatLon center2, double radius, - double[] altitudes, boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, int orientation, - Vec4 referenceCenter) - { + double[] altitudes, boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, int orientation, + Vec4 referenceCenter) { Geometry vertexGeom = this.createLongCylinderVertexGeometry(dc, center1, center2, radius, altitudes, - terrainConformant, arcSlices, lengthSlices, stacks, orientation, referenceCenter); + terrainConformant, arcSlices, lengthSlices, stacks, orientation, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "LongCylinder.OutlineIndices", arcSlices, lengthSlices, - stacks, orientation); + stacks, orientation); Geometry outlineIndexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (outlineIndexGeom == null) - { + if (outlineIndexGeom == null) { outlineIndexGeom = new Geometry(); this.makeLongCylinderOutlineIndices(arcSlices, lengthSlices, stacks, orientation, outlineIndexGeom); this.getGeometryCache().add(cacheKey, outlineIndexGeom); @@ -637,19 +567,18 @@ private void drawLongCylinderOutline(DrawContext dc, LatLon center1, LatLon cent } private Geometry createLongCylinderVertexGeometry(DrawContext dc, LatLon center1, LatLon center2, double radius, - double[] altitudes, boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, int orientation, - Vec4 referenceCenter) - { + double[] altitudes, boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, int orientation, + Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "LongCylinder.Vertices", - center1, center2, radius, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], arcSlices, - lengthSlices, stacks, orientation, referenceCenter); + center1, center2, radius, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], arcSlices, + lengthSlices, stacks, orientation, referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makeLongCylinder(dc, center1, center2, radius, altitudes, terrainConformant, arcSlices, lengthSlices, - stacks, orientation, referenceCenter, vertexGeom); + stacks, orientation, referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } @@ -658,9 +587,8 @@ private Geometry createLongCylinderVertexGeometry(DrawContext dc, LatLon center1 } private void makeLongCylinder(DrawContext dc, LatLon center1, LatLon center2, double radius, double[] altitudes, - boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, int orientation, Vec4 referenceCenter, - Geometry dest) - { + boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, int orientation, Vec4 referenceCenter, + Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -668,15 +596,14 @@ private void makeLongCylinder(DrawContext dc, LatLon center1, LatLon center2, do float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makeLongCylinderVertices(dc.getTerrain(), center1, center2, radius, altitudes, terrainConformant, arcSlices, - lengthSlices, stacks, referenceCenter, verts); + lengthSlices, stacks, referenceCenter, verts); gb.makeLongCylinderNormals(arcSlices, lengthSlices, stacks, norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makeLongCylinderIndices(int arcSlices, int lengthSlices, int stacks, int orientation, Geometry dest) - { + private void makeLongCylinderIndices(int arcSlices, int lengthSlices, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -689,8 +616,7 @@ private void makeLongCylinderIndices(int arcSlices, int lengthSlices, int stacks } private void makeLongCylinderOutlineIndices(int arcSlices, int lengthSlices, int stacks, int orientation, - Geometry dest) - { + Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -705,29 +631,26 @@ private void makeLongCylinderOutlineIndices(int arcSlices, int lengthSlices, int //**************************************************************// //******************** Long Disk ********************// //**************************************************************// - private void drawLongDisk(DrawContext dc, LatLon center1, LatLon center2, double[] radii, double altitude, - boolean terrainConformant, int arcSlices, int lengthSlices, int loops, int orientation, Vec4 referenceCenter) - { + boolean terrainConformant, int arcSlices, int lengthSlices, int loops, int orientation, Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "LongDisk.Vertices", center1, center2, - radii[0], radii[1], altitude, terrainConformant, arcSlices, lengthSlices, loops, orientation, - referenceCenter); + radii[0], radii[1], altitude, terrainConformant, arcSlices, lengthSlices, loops, orientation, + referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makeLongDisk(dc, center1, center2, radii, altitude, terrainConformant, arcSlices, lengthSlices, loops, - orientation, referenceCenter, vertexGeom); + orientation, referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } cacheKey = new Geometry.CacheKey(this.getClass(), "LongDisk.Indices", arcSlices, lengthSlices, loops, - orientation); + orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makeLongDiskIndices(arcSlices, lengthSlices, loops, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -737,9 +660,8 @@ private void drawLongDisk(DrawContext dc, LatLon center1, LatLon center2, double } private void makeLongDisk(DrawContext dc, LatLon center1, LatLon center2, double[] radii, double altitude, - boolean terrainConformant, int arcSlices, int lengthSlices, int loops, int orientation, Vec4 referenceCenter, - Geometry dest) - { + boolean terrainConformant, int arcSlices, int lengthSlices, int loops, int orientation, Vec4 referenceCenter, + Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -747,16 +669,15 @@ private void makeLongDisk(DrawContext dc, LatLon center1, LatLon center2, double float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makeLongDiskVertices(dc.getTerrain(), center1, center2, radii[0], radii[1], altitude, terrainConformant, - arcSlices, lengthSlices, loops, referenceCenter, verts); + arcSlices, lengthSlices, loops, referenceCenter, verts); gb.makeLongDiskVertexNormals((float) radii[0], (float) radii[1], 0, arcSlices, lengthSlices, loops, verts, - norms); + norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makeLongDiskIndices(int arcSlices, int lengthSlices, int loops, int orientation, Geometry dest) - { + private void makeLongDiskIndices(int arcSlices, int lengthSlices, int loops, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -771,10 +692,8 @@ private void makeLongDiskIndices(int arcSlices, int lengthSlices, int loops, int //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsLatLon(context, "location1", this.location1); @@ -785,30 +704,34 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); LatLon loc1 = rs.getStateValueAsLatLon(context, "location1"); - if (loc1 == null) + if (loc1 == null) { loc1 = this.getLocations()[0]; + } LatLon loc2 = rs.getStateValueAsLatLon(context, "location2"); - if (loc2 == null) + if (loc2 == null) { loc2 = this.getLocations()[1]; + } this.setLocations(loc1, loc2); String s = rs.getStateValueAsString(context, "orbitType"); - if (s != null) + if (s != null) { this.setOrbitType(s); + } Double d = rs.getStateValueAsDouble(context, "width"); - if (d != null) + if (d != null) { this.setWidth(d); + } Boolean booleanState = rs.getStateValueAsBoolean(context, "enableCaps"); - if (booleanState != null) + if (booleanState != null) { this.setEnableCaps(booleanState); + } } } diff --git a/src/gov/nasa/worldwind/render/airspaces/PartialCappedCylinder.java b/src/gov/nasa/worldwind/render/airspaces/PartialCappedCylinder.java index 6d555f5f4b..1bcf3f26e6 100644 --- a/src/gov/nasa/worldwind/render/airspaces/PartialCappedCylinder.java +++ b/src/gov/nasa/worldwind/render/airspaces/PartialCappedCylinder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.geom.*; @@ -21,23 +20,20 @@ * @author tag * @version $Id: PartialCappedCylinder.java 2447 2014-11-20 21:19:17Z dcollins $ */ -public class PartialCappedCylinder extends CappedCylinder -{ +public class PartialCappedCylinder extends CappedCylinder { + private Angle leftAzimuth = Angle.ZERO; private Angle rightAzimuth = Angle.POS360; - public PartialCappedCylinder(LatLon location, double radius, Angle leftAzimuth, Angle rightAzimuth) - { + public PartialCappedCylinder(LatLon location, double radius, Angle leftAzimuth, Angle rightAzimuth) { super(location, radius); - if (leftAzimuth == null) - { + if (leftAzimuth == null) { String message = "nullValue.LeftAzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rightAzimuth == null) - { + if (rightAzimuth == null) { String message = "nullValue.RightAzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -47,46 +43,38 @@ public PartialCappedCylinder(LatLon location, double radius, Angle leftAzimuth, this.rightAzimuth = rightAzimuth; } - public PartialCappedCylinder(LatLon location, double radius) - { + public PartialCappedCylinder(LatLon location, double radius) { super(location, radius); } - public PartialCappedCylinder(AirspaceAttributes attributes) - { + public PartialCappedCylinder(AirspaceAttributes attributes) { super(attributes); } - public PartialCappedCylinder() - { + public PartialCappedCylinder() { } - public PartialCappedCylinder(PartialCappedCylinder source) - { + public PartialCappedCylinder(PartialCappedCylinder source) { super(source); this.leftAzimuth = source.leftAzimuth; this.rightAzimuth = source.rightAzimuth; } - public Angle[] getAzimuths() - { + public Angle[] getAzimuths() { Angle[] array = new Angle[2]; array[0] = this.leftAzimuth; array[1] = this.rightAzimuth; return array; } - public void setAzimuths(Angle leftAzimuth, Angle rightAzimuth) - { - if (leftAzimuth == null) - { + public void setAzimuths(Angle leftAzimuth, Angle rightAzimuth) { + if (leftAzimuth == null) { String message = "nullValue.LeftAzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rightAzimuth == null) - { + if (rightAzimuth == null) { String message = "nullValue.RightAzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -97,27 +85,27 @@ public void setAzimuths(Angle leftAzimuth, Angle rightAzimuth) this.invalidateAirspaceData(); } - protected Box computeExtent(Globe globe, double verticalExaggeration) - { + protected Box computeExtent(Globe globe, double verticalExaggeration) { List points = this.computeMinimalGeometry(globe, verticalExaggeration); - if (points == null || points.isEmpty()) + if (points == null || points.isEmpty()) { return null; + } // A bounding box typically provides a better fit for a partial capped cylinder than a bounding cylinder. return Box.computeBoundingBox(points); } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { double[] angles = this.computeAngles(); // Angles are equal, fall back to building a closed cylinder. - if (angles == null) + if (angles == null) { return super.computeMinimalGeometry(globe, verticalExaggeration); + } GeometryBuilder gb = this.getGeometryBuilder(); LatLon[] locations = gb.makePartialDiskLocations(globe, this.getCenter(), this.getRadii()[0], - this.getRadii()[1], MINIMAL_GEOMETRY_SLICES, MINIMAL_GEOMETRY_LOOPS, angles[0], angles[2]); + this.getRadii()[1], MINIMAL_GEOMETRY_SLICES, MINIMAL_GEOMETRY_LOOPS, angles[0], angles[2]); ArrayList points = new ArrayList(); this.makeExtremePoints(globe, verticalExaggeration, Arrays.asList(locations), points); @@ -126,8 +114,7 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { double[] angles = this.computeAngles(); if (angles == null) // angles are equal, fall back to drawing a closed cylinder { @@ -143,16 +130,15 @@ protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) if (radii[0] > 0) // inner radius is > 0; add inner loop { List innerLoop = Arrays.asList(gb.makePartialCylinderLocations(dc.getGlobe(), this.getCenter(), - this.getRadii()[0], this.getSlices(), angles[0], angles[2])); + this.getRadii()[0], this.getSlices(), angles[0], angles[2])); locations.addAll(innerLoop); - } - else // inner radius == 0 + } else // inner radius == 0 { locations.add(this.getCenter()); } List outerLoop = Arrays.asList(gb.makePartialCylinderLocations(dc.getGlobe(), this.getCenter(), - this.getRadii()[1], this.getSlices(), angles[0], angles[2])); + this.getRadii()[1], this.getSlices(), angles[0], angles[2])); Collections.reverse(outerLoop); locations.addAll(outerLoop); // outer loop in reverse @@ -163,9 +149,7 @@ protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected double[] computeAngles() - { + protected double[] computeAngles() { // Compute the start and sweep angles such that the partial cylinder shape tranverses a clockwise path from // the start angle to the stop angle. Angle startAngle, stopAngle, sweepAngle; @@ -174,13 +158,16 @@ protected double[] computeAngles() int i = startAngle.compareTo(stopAngle); // Angles are equal, fallback to building a closed cylinder. - if (i == 0) + if (i == 0) { return null; + } - if (i < 0) + if (i < 0) { sweepAngle = stopAngle.subtract(startAngle); - else // (i > 0) + } else // (i > 0) + { sweepAngle = Angle.POS360.subtract(startAngle).add(stopAngle); + } double[] array = new double[3]; array[0] = startAngle.radians; @@ -189,10 +176,8 @@ protected double[] computeAngles() return array; } - protected Angle normalizedAzimuth(Angle azimuth) - { - if (azimuth == null) - { + protected Angle normalizedAzimuth(Angle azimuth) { + if (azimuth == null) { String message = "nullValue.AzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -203,16 +188,13 @@ protected Angle normalizedAzimuth(Angle azimuth) return Angle.fromDegrees(normalizedDegrees); } - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { - if (dc == null) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -220,8 +202,7 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) double[] angles = this.computeAngles(); // Angles are equal, fallback to drawing a closed cylinder. - if (angles == null) - { + if (angles == null) { super.doRenderGeometry(dc, drawStyle); return; } @@ -234,25 +215,28 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) int stacks = this.getStacks(); int loops = this.getLoops(); - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(SLICES); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { slices = (Integer) o; + } o = level.getValue(STACKS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { stacks = (Integer) o; + } o = level.getValue(LOOPS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { loops = (Integer) o; + } o = level.getValue(DISABLE_TERRAIN_CONFORMANCE); - if (o != null && o instanceof Boolean && ((Boolean) o)) + if (o != null && o instanceof Boolean && ((Boolean) o)) { terrainConformant[0] = terrainConformant[1] = false; + } } Vec4 referenceCenter = this.computeReferenceCenter(dc); @@ -261,80 +245,65 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { dc.getView().pushReferenceCenter(dc, referenceCenter); - if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) - { + if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) { this.drawRadialWallOutline(dc, center, radii, angles[0], altitudes, terrainConformant, loops, stacks, - GeometryBuilder.INSIDE, referenceCenter); + GeometryBuilder.INSIDE, referenceCenter); this.drawRadialWallOutline(dc, center, radii, angles[1], altitudes, terrainConformant, loops, stacks, - GeometryBuilder.OUTSIDE, referenceCenter); + GeometryBuilder.OUTSIDE, referenceCenter); // Outer cylinder isn't rendered if outer radius is zero. - if (radii[1] != 0.0) - { + if (radii[1] != 0.0) { this.drawPartialCylinderOutline(dc, center, radii[1], altitudes, terrainConformant, slices, stacks, - GeometryBuilder.OUTSIDE, angles[0], angles[2], referenceCenter); + GeometryBuilder.OUTSIDE, angles[0], angles[2], referenceCenter); } // Inner cylinder isn't rendered if inner radius is zero. - if (radii[0] != 0.0) - { + if (radii[0] != 0.0) { this.drawPartialCylinderOutline(dc, center, radii[0], altitudes, terrainConformant, slices, stacks, - GeometryBuilder.INSIDE, angles[0], angles[2], referenceCenter); + GeometryBuilder.INSIDE, angles[0], angles[2], referenceCenter); } - } - else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) - { - if (this.isEnableCaps()) - { + } else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) { + if (this.isEnableCaps()) { ogsh.pushAttrib(gl, GL2.GL_POLYGON_BIT); gl.glEnable(GL.GL_CULL_FACE); gl.glFrontFace(GL.GL_CCW); } - if (this.isEnableCaps()) - { + if (this.isEnableCaps()) { // Caps aren't rendered if radii are equal. - if (radii[0] != radii[1]) - { + if (radii[0] != radii[1]) { this.drawPartialDisk(dc, center, radii, altitudes[1], terrainConformant[1], slices, loops, - GeometryBuilder.OUTSIDE, angles[0], angles[2], referenceCenter); + GeometryBuilder.OUTSIDE, angles[0], angles[2], referenceCenter); // Bottom cap isn't rendered if airspace is collapsed. - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { this.drawPartialDisk(dc, center, radii, altitudes[0], terrainConformant[0], slices, loops, - GeometryBuilder.INSIDE, angles[0], angles[2], referenceCenter); + GeometryBuilder.INSIDE, angles[0], angles[2], referenceCenter); } } } // Cylinders aren't rendered if airspace is collapsed. - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { this.drawRadialWall(dc, center, radii, angles[0], altitudes, terrainConformant, loops, stacks, - GeometryBuilder.INSIDE, referenceCenter); + GeometryBuilder.INSIDE, referenceCenter); this.drawRadialWall(dc, center, radii, angles[1], altitudes, terrainConformant, loops, stacks, - GeometryBuilder.OUTSIDE, referenceCenter); + GeometryBuilder.OUTSIDE, referenceCenter); // Outer cylinder isn't rendered if outer radius is zero. - if (radii[1] != 0.0) - { + if (radii[1] != 0.0) { this.drawPartialCylinder(dc, center, radii[1], altitudes, terrainConformant, slices, stacks, - GeometryBuilder.OUTSIDE, angles[0], angles[2], referenceCenter); + GeometryBuilder.OUTSIDE, angles[0], angles[2], referenceCenter); } // Inner cylinder isn't rendered if inner radius is zero. - if (radii[0] != 0.0) - { + if (radii[0] != 0.0) { this.drawPartialCylinder(dc, center, radii[0], altitudes, terrainConformant, slices, stacks, - GeometryBuilder.INSIDE, angles[0], angles[2], referenceCenter); + GeometryBuilder.INSIDE, angles[0], angles[2], referenceCenter); } } } - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); ogsh.pop(gl); } @@ -343,19 +312,16 @@ else if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) //**************************************************************// //******************** Partial Cylinder ********************// //**************************************************************// - private void drawPartialCylinder(DrawContext dc, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, int orientation, double start, double sweep, - Vec4 referenceCenter) - { + boolean[] terrainConformant, int slices, int stacks, int orientation, double start, double sweep, + Vec4 referenceCenter) { Geometry vertexGeom = this.createPartialCylinderVertexGeometry(dc, center, radius, altitudes, terrainConformant, - slices, stacks, orientation, start, sweep, referenceCenter); + slices, stacks, orientation, start, sweep, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "PartialCylinder.Indices", slices, stacks, - orientation); + orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makePartialCylinderIndices(slices, stacks, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -365,17 +331,15 @@ private void drawPartialCylinder(DrawContext dc, LatLon center, double radius, d } private void drawPartialCylinderOutline(DrawContext dc, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, int orientation, double start, double sweep, - Vec4 referenceCenter) - { + boolean[] terrainConformant, int slices, int stacks, int orientation, double start, double sweep, + Vec4 referenceCenter) { Geometry vertexGeom = this.createPartialCylinderVertexGeometry(dc, center, radius, altitudes, terrainConformant, - slices, stacks, orientation, start, sweep, referenceCenter); + slices, stacks, orientation, start, sweep, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "PartialCylinder.OutlineIndices", slices, stacks, - orientation); + orientation); Geometry outlineIndexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (outlineIndexGeom == null) - { + if (outlineIndexGeom == null) { outlineIndexGeom = new Geometry(); this.makePartialCylinderOutlineIndices(slices, stacks, orientation, outlineIndexGeom); this.getGeometryCache().add(cacheKey, outlineIndexGeom); @@ -385,19 +349,18 @@ private void drawPartialCylinderOutline(DrawContext dc, LatLon center, double ra } private Geometry createPartialCylinderVertexGeometry(DrawContext dc, LatLon center, double radius, - double[] altitudes, boolean[] terrainConformant, int slices, int stacks, int orientation, double start, - double sweep, Vec4 referenceCenter) - { + double[] altitudes, boolean[] terrainConformant, int slices, int stacks, int orientation, double start, + double sweep, Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "PartialCylinder.Vertices", center, - radius, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], slices, stacks, orientation, - start, sweep, referenceCenter); + radius, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], slices, stacks, orientation, + start, sweep, referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makePartialCylinder(dc, center, radius, altitudes, terrainConformant, slices, stacks, orientation, - start, sweep, referenceCenter, vertexGeom); + start, sweep, referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } @@ -406,9 +369,8 @@ private Geometry createPartialCylinderVertexGeometry(DrawContext dc, LatLon cent } private void makePartialCylinder(DrawContext dc, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, int orientation, double start, double sweep, - Vec4 referenceCenter, Geometry dest) - { + boolean[] terrainConformant, int slices, int stacks, int orientation, double start, double sweep, + Vec4 referenceCenter, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); float height = (float) (altitudes[1] - altitudes[0]); @@ -417,15 +379,14 @@ private void makePartialCylinder(DrawContext dc, LatLon center, double radius, d float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makePartialCylinderVertices(dc.getTerrain(), center, radius, altitudes, terrainConformant, slices, stacks, - start, sweep, referenceCenter, verts); + start, sweep, referenceCenter, verts); gb.makePartialCylinderNormals((float) radius, height, slices, stacks, (float) start, (float) sweep, norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makePartialCylinderIndices(int slices, int stacks, int orientation, Geometry dest) - { + private void makePartialCylinderIndices(int slices, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -437,8 +398,7 @@ private void makePartialCylinderIndices(int slices, int stacks, int orientation, dest.setElementData(mode, count, indices); } - private void makePartialCylinderOutlineIndices(int slices, int stacks, int orientation, Geometry dest) - { + private void makePartialCylinderOutlineIndices(int slices, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -453,28 +413,25 @@ private void makePartialCylinderOutlineIndices(int slices, int stacks, int orien //**************************************************************// //******************** Partial Disk ********************// //**************************************************************// - private void drawPartialDisk(DrawContext dc, LatLon center, double[] radii, double altitude, - boolean terrainConformant, int slices, int loops, int orientation, double start, double sweep, - Vec4 referenceCenter) - { + boolean terrainConformant, int slices, int loops, int orientation, double start, double sweep, + Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "PartialDisk.Vertices", center, - radii[0], radii[1], altitude, terrainConformant, slices, loops, orientation, start, sweep, referenceCenter); + radii[0], radii[1], altitude, terrainConformant, slices, loops, orientation, start, sweep, referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makePartialDisk(dc, center, radii, altitude, terrainConformant, slices, loops, orientation, start, - sweep, referenceCenter, vertexGeom); + sweep, referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } cacheKey = new Geometry.CacheKey(this.getClass(), "PartialDisk.Indices", slices, loops, orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makePartialDiskIndices(slices, loops, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -484,9 +441,8 @@ private void drawPartialDisk(DrawContext dc, LatLon center, double[] radii, doub } private void makePartialDisk(DrawContext dc, LatLon center, double[] radii, double altitude, - boolean terrainConformant, int slices, int loops, int orientation, double start, double sweep, - Vec4 referenceCenter, Geometry dest) - { + boolean terrainConformant, int slices, int loops, int orientation, double start, double sweep, + Vec4 referenceCenter, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -494,16 +450,15 @@ private void makePartialDisk(DrawContext dc, LatLon center, double[] radii, doub float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makePartialDiskVertices(dc.getTerrain(), center, radii[0], radii[1], altitude, terrainConformant, slices, - loops, start, sweep, referenceCenter, verts); + loops, start, sweep, referenceCenter, verts); gb.makePartialDiskVertexNormals((float) radii[0], (float) radii[1], slices, loops, (float) start, (float) sweep, - verts, norms); + verts, norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makePartialDiskIndices(int slices, int loops, int orientation, Geometry dest) - { + private void makePartialDiskIndices(int slices, int loops, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -518,17 +473,14 @@ private void makePartialDiskIndices(int slices, int loops, int orientation, Geom //**************************************************************// //******************** Radial Wall ********************// //**************************************************************// - private void drawRadialWall(DrawContext dc, LatLon center, double[] radii, double angle, double[] altitudes, - boolean[] terrainConformant, int pillars, int stacks, int orientation, Vec4 referenceCenter) - { + boolean[] terrainConformant, int pillars, int stacks, int orientation, Vec4 referenceCenter) { Geometry vertexGeom = this.createRadialWallVertexGeometry(dc, center, radii, angle, altitudes, - terrainConformant, pillars, stacks, orientation, referenceCenter); + terrainConformant, pillars, stacks, orientation, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "RadialWall.Indices", pillars, stacks, orientation); Geometry indexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (indexGeom == null) - { + if (indexGeom == null) { indexGeom = new Geometry(); this.makeRadialWallIndices(pillars, stacks, orientation, indexGeom); this.getGeometryCache().add(cacheKey, indexGeom); @@ -538,16 +490,14 @@ private void drawRadialWall(DrawContext dc, LatLon center, double[] radii, doubl } private void drawRadialWallOutline(DrawContext dc, LatLon center, double[] radii, double angle, double[] altitudes, - boolean[] terrainConformant, int pillars, int stacks, int orientation, Vec4 referenceCenter) - { + boolean[] terrainConformant, int pillars, int stacks, int orientation, Vec4 referenceCenter) { Geometry vertexGeom = this.createRadialWallVertexGeometry(dc, center, radii, angle, altitudes, - terrainConformant, pillars, stacks, orientation, referenceCenter); + terrainConformant, pillars, stacks, orientation, referenceCenter); Object cacheKey = new Geometry.CacheKey(this.getClass(), "RadialWall.OutlineIndices", pillars, stacks, - orientation); + orientation); Geometry outlineIndexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (outlineIndexGeom == null) - { + if (outlineIndexGeom == null) { outlineIndexGeom = new Geometry(); this.makeRadialWallOutlineIndices(pillars, stacks, orientation, outlineIndexGeom); this.getGeometryCache().add(cacheKey, outlineIndexGeom); @@ -557,18 +507,17 @@ private void drawRadialWallOutline(DrawContext dc, LatLon center, double[] radii } private Geometry createRadialWallVertexGeometry(DrawContext dc, LatLon center, double[] radii, double angle, - double[] altitudes, boolean[] terrainConformant, int pillars, int stacks, int orientation, Vec4 referenceCenter) - { + double[] altitudes, boolean[] terrainConformant, int pillars, int stacks, int orientation, Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "RadialWall.Vertices", center, radii[0], - radii[1], angle, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], pillars, stacks, - orientation, referenceCenter); + radii[1], angle, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], pillars, stacks, + orientation, referenceCenter); Geometry vertexGeom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (vertexGeom == null || this.isExpired(dc, vertexGeom)) - { - if (vertexGeom == null) + if (vertexGeom == null || this.isExpired(dc, vertexGeom)) { + if (vertexGeom == null) { vertexGeom = new Geometry(); + } this.makeRadialWall(dc, center, radii, angle, altitudes, terrainConformant, pillars, stacks, orientation, - referenceCenter, vertexGeom); + referenceCenter, vertexGeom); this.updateExpiryCriteria(dc, vertexGeom); this.getGeometryCache().add(cacheKey, vertexGeom); } @@ -577,8 +526,7 @@ private Geometry createRadialWallVertexGeometry(DrawContext dc, LatLon center, d } private void makeRadialWall(DrawContext dc, LatLon center, double[] radii, double angle, double[] altitudes, - boolean[] terrainConformant, int pillars, int stacks, int orientation, Vec4 referenceCenter, Geometry dest) - { + boolean[] terrainConformant, int pillars, int stacks, int orientation, Vec4 referenceCenter, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); float height = (float) (altitudes[1] - altitudes[0]); @@ -587,15 +535,14 @@ private void makeRadialWall(DrawContext dc, LatLon center, double[] radii, doubl float[] verts = new float[3 * count]; float[] norms = new float[3 * count]; gb.makeRadialWallVertices(dc.getTerrain(), center, radii[0], radii[1], angle, altitudes, terrainConformant, - pillars, stacks, referenceCenter, verts); + pillars, stacks, referenceCenter, verts); gb.makeRadialWallNormals((float) radii[0], (float) radii[1], height, (float) angle, pillars, stacks, norms); dest.setVertexData(count, verts); dest.setNormalData(count, norms); } - private void makeRadialWallIndices(int pillars, int stacks, int orientation, Geometry dest) - { + private void makeRadialWallIndices(int pillars, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -607,8 +554,7 @@ private void makeRadialWallIndices(int pillars, int stacks, int orientation, Geo dest.setElementData(mode, count, indices); } - private void makeRadialWallOutlineIndices(int pillars, int stacks, int orientation, Geometry dest) - { + private void makeRadialWallOutlineIndices(int pillars, int stacks, int orientation, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(orientation); @@ -623,10 +569,8 @@ private void makeRadialWallOutlineIndices(int pillars, int stacks, int orientati //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsDouble(context, "leftAzimuthDegrees", this.leftAzimuth.degrees); @@ -634,17 +578,18 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Double la = rs.getStateValueAsDouble(context, "leftAzimuthDegrees"); - if (la == null) + if (la == null) { la = this.leftAzimuth.degrees; + } Double ra = rs.getStateValueAsDouble(context, "rightAzimuthDegrees"); - if (ra == null) + if (ra == null) { ra = this.rightAzimuth.degrees; + } this.setAzimuths(Angle.fromDegrees(la), Angle.fromDegrees(ra)); } diff --git a/src/gov/nasa/worldwind/render/airspaces/PolyArc.java b/src/gov/nasa/worldwind/render/airspaces/PolyArc.java index 5e74296a90..f2101e2e0c 100644 --- a/src/gov/nasa/worldwind/render/airspaces/PolyArc.java +++ b/src/gov/nasa/worldwind/render/airspaces/PolyArc.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.geom.*; @@ -17,8 +16,8 @@ * @author tag * @version $Id: PolyArc.java 2450 2014-11-20 21:41:54Z dcollins $ */ -public class PolyArc extends Polygon -{ +public class PolyArc extends Polygon { + protected static final int DEFAULT_SLICES = 32; protected static final int MINIMAL_GEOMETRY_SLICES = 8; @@ -30,24 +29,20 @@ public class PolyArc extends Polygon private ArrayList polyArcLocations = new ArrayList(); private ArrayList edgeFlags = new ArrayList(); - public PolyArc(List locations, double radius, Angle leftAzimuth, Angle rightAzimuth) - { + public PolyArc(List locations, double radius, Angle leftAzimuth, Angle rightAzimuth) { super(locations); - if (radius < 0.0) - { + if (radius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius=" + radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (leftAzimuth == null) - { + if (leftAzimuth == null) { String message = "nullValue.LeftAzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rightAzimuth == null) - { + if (rightAzimuth == null) { String message = "nullValue.RightAzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -59,25 +54,21 @@ public PolyArc(List locations, double radius, Angle leftAzimut this.makeDefaultDetailLevels(); } - public PolyArc(List locations) - { + public PolyArc(List locations) { super(locations); this.makeDefaultDetailLevels(); } - public PolyArc(AirspaceAttributes attributes) - { + public PolyArc(AirspaceAttributes attributes) { super(attributes); this.makeDefaultDetailLevels(); } - public PolyArc() - { + public PolyArc() { this.makeDefaultDetailLevels(); } - private void makeDefaultDetailLevels() - { + private void makeDefaultDetailLevels() { List levels = new ArrayList(); double[] ramp = ScreenSizeDetailLevel.computeDefaultScreenSizeRamp(5); @@ -115,15 +106,12 @@ private void makeDefaultDetailLevels() this.setDetailLevels(levels); } - public double getRadius() - { + public double getRadius() { return this.radius; } - public void setRadius(double radius) - { - if (radius < 0.0) - { + public void setRadius(double radius) { + if (radius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius=" + radius); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -133,24 +121,20 @@ public void setRadius(double radius) this.invalidateAirspaceData(); } - public Angle[] getAzimuths() - { + public Angle[] getAzimuths() { Angle[] array = new Angle[2]; array[0] = this.leftAzimuth; array[1] = this.rightAzimuth; return array; } - public void setAzimuths(Angle leftAzimuth, Angle rightAzimuth) - { - if (leftAzimuth == null) - { + public void setAzimuths(Angle leftAzimuth, Angle rightAzimuth) { + if (leftAzimuth == null) { String message = "nullValue.LeftAzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (rightAzimuth == null) - { + if (rightAzimuth == null) { String message = "nullValue.RightAzimuthIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -161,15 +145,12 @@ public void setAzimuths(Angle leftAzimuth, Angle rightAzimuth) this.invalidateAirspaceData(); } - protected int getSlices() - { + protected int getSlices() { return this.slices; } - protected void setSlices(int slices) - { - if (slices < 0) - { + protected void setSlices(int slices) { + if (slices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -179,11 +160,11 @@ protected void setSlices(int slices) } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { List locations = this.getLocationList(); - if (locations == null || locations.isEmpty()) + if (locations == null || locations.isEmpty()) { return null; + } ArrayList arcLocations = new ArrayList(); ArrayList arcFlags = new ArrayList(); @@ -199,8 +180,7 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { ArrayList arcLocations = new ArrayList(); ArrayList arcFlags = new ArrayList(); this.makePolyArcLocations(dc.getGlobe(), this.getLocationList(), this.slices, arcLocations, arcFlags); @@ -211,16 +191,15 @@ protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected double[] computeAngles() - { + protected double[] computeAngles() { Angle startAngle = this.normalizedAzimuth(this.leftAzimuth); Angle stopAngle = this.normalizedAzimuth(this.rightAzimuth); Angle sweepAngle; - if (startAngle.compareTo(stopAngle) <= 0) + if (startAngle.compareTo(stopAngle) <= 0) { sweepAngle = stopAngle.subtract(startAngle); - else + } else { sweepAngle = Angle.POS360.subtract(startAngle).add(stopAngle); + } double[] array = new double[3]; array[0] = startAngle.radians; @@ -229,17 +208,16 @@ protected double[] computeAngles() return array; } - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { int slices = this.slices; - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(SLICES); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { slices = (Integer) o; + } } this.polyArcLocations.clear(); @@ -250,52 +228,43 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) } private void makePolyArcLocations(Globe globe, List locations, int slices, - List polyArcLocations, List edgeFlags) - { + List polyArcLocations, List edgeFlags) { int locationCount = locations.size(); - if (locationCount > 0) - { + if (locationCount > 0) { // Create arc locations. These are guaranteed to be in clockwise order about the first location. double[] angles = this.computeAngles(); double radius = this.radius; LatLon first = locations.get(0); LatLon[] arcLocations = this.makeArc(globe, first, radius, slices, angles[0], angles[2]); - for (LatLon ll : arcLocations) - { + for (LatLon ll : arcLocations) { polyArcLocations.add(ll); edgeFlags.add(false); } // Enable edge flags for the first and last poly arc locations. - if (edgeFlags.size() > 1) - { + if (edgeFlags.size() > 1) { edgeFlags.set(0, true); edgeFlags.set(edgeFlags.size() - 1, true); } // Add the remaining polygon locations (skipping the first). These winding order of these locations is // checked, then they are added in counter-clockwise order about the first location. - if (locationCount > 1) - { + if (locationCount > 1) { GeometryBuilder gb = this.getGeometryBuilder(); Vec4[] polyPoints = new Vec4[locationCount + 1]; Matrix[] polyTransform = new Matrix[1]; int polyCount = this.computeEllipsoidalPolygon(globe, locations, null, polyPoints, null, polyTransform); int polyWinding = gb.computePolygonWindingOrder2(0, polyCount, polyPoints); - if (polyWinding == GeometryBuilder.COUNTER_CLOCKWISE) - { - for (int i = 1; i < locationCount; i++) - { + if (polyWinding == GeometryBuilder.COUNTER_CLOCKWISE) { + for (int i = 1; i < locationCount; i++) { polyArcLocations.add(locations.get(i)); edgeFlags.add(true); } - } - else // (polyWinding == GeometryBuilder.CLOCKWISE) + } else // (polyWinding == GeometryBuilder.CLOCKWISE) { - for (int i = locationCount - 1; i >= 1; i--) - { + for (int i = locationCount - 1; i >= 1; i--) { polyArcLocations.add(locations.get(i)); edgeFlags.add(true); } @@ -304,14 +273,12 @@ private void makePolyArcLocations(Globe globe, List locations, } } - private LatLon[] makeArc(Globe globe, LatLon center, double radius, int slices, double start, double sweep) - { + private LatLon[] makeArc(Globe globe, LatLon center, double radius, int slices, double start, double sweep) { double da = sweep / slices; double r = radius / globe.getRadius(); LatLon[] locations = new LatLon[slices + 1]; - for (int i = 0; i <= slices; i++) - { + for (int i = 0; i <= slices; i++) { double a = i * da + start; locations[i] = LatLon.greatCircleEndPosition(center, a, r); } @@ -319,8 +286,7 @@ private LatLon[] makeArc(Globe globe, LatLon center, double radius, int slices, return locations; } - private Angle normalizedAzimuth(Angle azimuth) - { + private Angle normalizedAzimuth(Angle azimuth) { double degrees = azimuth.degrees; double normalizedDegrees = degrees < 0.0 ? degrees + 360.0 : (degrees >= 360.0 ? degrees - 360.0 : degrees); return Angle.fromDegrees(normalizedDegrees); @@ -329,10 +295,8 @@ private Angle normalizedAzimuth(Angle azimuth) //**************************************************************// //******************** END Geometry Rendering *****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsDouble(context, "leftAzimuthDegrees", this.leftAzimuth.degrees); @@ -341,21 +305,23 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Double d = rs.getStateValueAsDouble(context, "radius"); - if (d != null) + if (d != null) { this.setRadius(d); + } Double la = rs.getStateValueAsDouble(context, "leftAzimuthDegrees"); - if (la == null) + if (la == null) { la = this.leftAzimuth.degrees; + } Double ra = rs.getStateValueAsDouble(context, "rightAzimuthDegrees"); - if (ra == null) + if (ra == null) { ra = this.rightAzimuth.degrees; + } this.setAzimuths(Angle.fromDegrees(la), Angle.fromDegrees(ra)); } diff --git a/src/gov/nasa/worldwind/render/airspaces/Polygon.java b/src/gov/nasa/worldwind/render/airspaces/Polygon.java index 8f55e3fdfd..195c78b918 100644 --- a/src/gov/nasa/worldwind/render/airspaces/Polygon.java +++ b/src/gov/nasa/worldwind/render/airspaces/Polygon.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.avlist.AVKey; @@ -22,8 +21,8 @@ * @author tag * @version $Id: Polygon.java 2309 2014-09-17 00:04:08Z tgaskins $ */ -public class Polygon extends AbstractAirspace -{ +public class Polygon extends AbstractAirspace { + protected static final int DEFAULT_SUBDIVISIONS = 3; protected static final int MINIMAL_GEOMETRY_SUBDIVISIONS = 2; @@ -31,8 +30,7 @@ public class Polygon extends AbstractAirspace private boolean enableCaps = true; private int subdivisions = DEFAULT_SUBDIVISIONS; - public Polygon(Polygon source) - { + public Polygon(Polygon source) { super(source); this.enableCaps = source.enableCaps; @@ -42,25 +40,21 @@ public Polygon(Polygon source) this.makeDefaultDetailLevels(); } - public Polygon(Iterable locations) - { + public Polygon(Iterable locations) { this.addLocations(locations); this.makeDefaultDetailLevels(); } - public Polygon(AirspaceAttributes attributes) - { + public Polygon(AirspaceAttributes attributes) { super(attributes); this.makeDefaultDetailLevels(); } - public Polygon() - { + public Polygon() { this.makeDefaultDetailLevels(); } - private void makeDefaultDetailLevels() - { + private void makeDefaultDetailLevels() { List levels = new ArrayList(); double[] ramp = ScreenSizeDetailLevel.computeDefaultScreenSizeRamp(5); @@ -93,56 +87,48 @@ private void makeDefaultDetailLevels() this.setDetailLevels(levels); } - public List getLocations() - { + public List getLocations() { return Collections.unmodifiableList(this.locations); } - public void setLocations(Iterable locations) - { + public void setLocations(Iterable locations) { this.locations.clear(); this.addLocations(locations); } - protected List getLocationList() - { + protected List getLocationList() { return this.locations; } - protected void addLocations(Iterable newLocations) - { - if (newLocations != null) - { - for (LatLon ll : newLocations) - { - if (ll != null) + protected void addLocations(Iterable newLocations) { + if (newLocations != null) { + for (LatLon ll : newLocations) { + if (ll != null) { this.locations.add(ll); + } } } this.invalidateAirspaceData(); } - public boolean isEnableCaps() - { + public boolean isEnableCaps() { return this.enableCaps; } - public void setEnableCaps(boolean enable) - { + public void setEnableCaps(boolean enable) { this.enableCaps = enable; } - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.computeReferencePosition(this.locations, this.getAltitudes()); } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { List points = this.computeMinimalGeometry(globe, verticalExaggeration); - if (points == null || points.isEmpty()) + if (points == null || points.isEmpty()) { return null; + } // Add a point at the center of this polygon to the points used to compute its extent. The center point captures // the curvature of the globe when the polygon's minimal geometry only contain any points near the polygon's @@ -155,11 +141,11 @@ protected Extent computeExtent(Globe globe, double verticalExaggeration) } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { List locations = this.getLocations(); - if (locations == null || locations.isEmpty()) + if (locations == null || locations.isEmpty()) { return null; + } ArrayList copyOfLocations = new ArrayList(locations); ArrayList tessellatedLocations = new ArrayList(); @@ -171,16 +157,13 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera return points; } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -192,16 +175,13 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) super.doMoveTo(oldRef, newRef); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -211,8 +191,7 @@ protected void doMoveTo(Position oldRef, Position newRef) int count = this.locations.size(); LatLon[] newLocations = new LatLon[count]; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { LatLon ll = this.locations.get(i); double distance = LatLon.greatCircleDistance(oldRef, ll).radians; double azimuth = LatLon.greatCircleAzimuth(oldRef, ll).radians; @@ -222,14 +201,12 @@ protected void doMoveTo(Position oldRef, Position newRef) } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return new SurfacePolygon(); } @Override - protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) { super.updateSurfaceShape(dc, shape); boolean mustDrawInterior = this.getActiveAttributes().isDrawInterior() && this.isEnableCaps(); @@ -237,20 +214,16 @@ protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { ((SurfacePolygon) shape).setOuterBoundary(this.locations); } - protected int getSubdivisions() - { + protected int getSubdivisions() { return this.subdivisions; } - protected void setSubdivisions(int subdivisions) - { - if (subdivisions < 0) - { + protected void setSubdivisions(int subdivisions) { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions=" + subdivisions); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -262,41 +235,35 @@ protected void setSubdivisions(int subdivisions) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected Vec4 computeReferenceCenter(DrawContext dc) - { + protected Vec4 computeReferenceCenter(DrawContext dc) { Extent extent = this.getExtent(dc); return extent != null ? extent.getCenter() : null; } - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { this.doRenderGeometry(dc, drawStyle, this.locations, null); } - protected void doRenderGeometry(DrawContext dc, String drawStyle, List locations, List edgeFlags) - { - if (dc == null) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle, List locations, List edgeFlags) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (locations == null) - { + if (locations == null) { String message = "nullValue.LocationsIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (locations.size() == 0) + if (locations.size() == 0) { return; + } double[] altitudes = this.getAltitudes(dc.getVerticalExaggeration()); boolean[] terrainConformant = this.isTerrainConforming(); @@ -304,22 +271,22 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle, List l int subdivisions = this.subdivisions; if (this.getAltitudeDatum()[0].equals(AVKey.ABOVE_GROUND_REFERENCE) - || this.getAltitudeDatum()[1].equals(AVKey.ABOVE_GROUND_REFERENCE)) - { + || this.getAltitudeDatum()[1].equals(AVKey.ABOVE_GROUND_REFERENCE)) { this.adjustForGroundReference(dc, terrainConformant, altitudes); } - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(SUBDIVISIONS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { subdivisions = (Integer) o; + } o = level.getValue(DISABLE_TERRAIN_CONFORMANCE); - if (o != null && o instanceof Boolean && (Boolean) o) + if (o != null && o instanceof Boolean && (Boolean) o) { terrainConformant[0] = terrainConformant[1] = false; + } } Vec4 referenceCenter = this.computeReferenceCenter(dc); @@ -328,83 +295,69 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle, List l GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { dc.getView().pushReferenceCenter(dc, referenceCenter); - if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) - { - if (enableCaps && !this.isAirspaceCollapsed()) - { + if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) { + if (enableCaps && !this.isAirspaceCollapsed()) { ogsh.pushAttrib(gl, GL2.GL_POLYGON_BIT); gl.glEnable(GL.GL_CULL_FACE); gl.glFrontFace(GL.GL_CCW); } this.drawPolygonFill(dc, locations, edgeFlags, altitudes, terrainConformant, enableCaps, subdivisions, - referenceCenter); - } - else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) - { + referenceCenter); + } else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) { this.drawPolygonOutline(dc, locations, edgeFlags, altitudes, terrainConformant, enableCaps, - subdivisions, referenceCenter); + subdivisions, referenceCenter); } - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); ogsh.pop(gl); } } - protected void adjustForGroundReference(DrawContext dc, boolean[] terrainConformant, double[] altitudes) - { + protected void adjustForGroundReference(DrawContext dc, boolean[] terrainConformant, double[] altitudes) { LatLon groundRef = this.getGroundReference(); - if (groundRef == null && this.getLocationList().size() > 0) + if (groundRef == null && this.getLocationList().size() > 0) { groundRef = this.getLocationList().get(0); + } this.adjustForGroundReference(dc, terrainConformant, altitudes, groundRef); // no-op if groudRef is null } protected int computeEllipsoidalPolygon(Globe globe, List locations, List edgeFlags, - Vec4[] points, Boolean[] edgeFlagArray, Matrix[] transform) - { - if (globe == null) - { + Vec4[] points, Boolean[] edgeFlagArray, Matrix[] transform) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (locations == null) - { + if (locations == null) { String message = "nullValue.LocationsIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (points == null) - { + if (points == null) { String message = "nullValue.LocationsIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (points.length < (1 + locations.size())) - { + if (points.length < (1 + locations.size())) { String message = Logging.getMessage("generic.ArrayInvalidLength", - "points.length < " + (1 + locations.size())); + "points.length < " + (1 + locations.size())); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (transform == null) - { + if (transform == null) { String message = "nullValue.TransformIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (transform.length < 1) - { + if (transform.length < 1) { String message = Logging.getMessage("generic.ArrayInvalidLength", - "transform.length < 1"); + "transform.length < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -413,24 +366,24 @@ protected int computeEllipsoidalPolygon(Globe globe, List loca int locationCount = locations.size(); // Compute the cartesian points for each location. - for (int i = 0; i < locationCount; i++) - { + for (int i = 0; i < locationCount; i++) { LatLon ll = locations.get(i); points[i] = globe.computeEllipsoidalPointFromPosition(ll.getLatitude(), ll.getLongitude(), 0.0); - if (edgeFlagArray != null) + if (edgeFlagArray != null) { edgeFlagArray[i] = (edgeFlags != null) ? edgeFlags.get(i) : true; + } } // Compute the average of the cartesian points. Vec4 centerPoint = Vec4.computeAveragePoint(Arrays.asList(points)); // Test whether the polygon is closed. If it is not closed, repeat the first vertex. - if (!points[0].equals(points[locationCount - 1])) - { + if (!points[0].equals(points[locationCount - 1])) { points[locationCount] = points[0]; - if (edgeFlagArray != null) + if (edgeFlagArray != null) { edgeFlagArray[locationCount] = edgeFlagArray[0]; + } locationCount++; } @@ -439,11 +392,10 @@ protected int computeEllipsoidalPolygon(Globe globe, List loca // of the points and oriented with the globe surface. Position centerPos = globe.computePositionFromEllipsoidalPoint(centerPoint); Matrix tx = globe.computeEllipsoidalOrientationAtPosition(centerPos.latitude, centerPos.longitude, - centerPos.elevation); + centerPos.elevation); Matrix txInv = tx.getInverse(); // Map the cartesian points to a local coordinate space. - for (int i = 0; i < locationCount; i++) - { + for (int i = 0; i < locationCount; i++) { points[i] = points[i].transformBy4(txInv); } @@ -452,10 +404,8 @@ protected int computeEllipsoidalPolygon(Globe globe, List loca return locationCount; } - private void makePolygonVertices(int count, Vec4[] points, float[] vertices) - { - for (int i = 0; i < count; i++) - { + private void makePolygonVertices(int count, Vec4[] points, float[] vertices) { + for (int i = 0; i < count; i++) { int index = 3 * i; vertices[index] = (float) points[i].x; vertices[index + 1] = (float) points[i].y; @@ -466,37 +416,31 @@ private void makePolygonVertices(int count, Vec4[] points, float[] vertices) //**************************************************************// //******************** Polygon ******************// //**************************************************************// + protected static class PolygonGeometry implements Cacheable { - protected static class PolygonGeometry implements Cacheable - { private Geometry fillIndexGeometry; private Geometry outlineIndexGeometry; private Geometry vertexGeometry; - public PolygonGeometry() - { + public PolygonGeometry() { this.fillIndexGeometry = new Geometry(); this.outlineIndexGeometry = new Geometry(); this.vertexGeometry = new Geometry(); } - public Geometry getFillIndexGeometry() - { + public Geometry getFillIndexGeometry() { return this.fillIndexGeometry; } - public Geometry getOutlineIndexGeometry() - { + public Geometry getOutlineIndexGeometry() { return this.outlineIndexGeometry; } - public Geometry getVertexGeometry() - { + public Geometry getVertexGeometry() { return this.vertexGeometry; } - public long getSizeInBytes() - { + public long getSizeInBytes() { long sizeInBytes = 0L; sizeInBytes += (this.fillIndexGeometry != null) ? this.fillIndexGeometry.getSizeInBytes() : 0L; sizeInBytes += (this.outlineIndexGeometry != null) ? this.outlineIndexGeometry.getSizeInBytes() : 0L; @@ -507,35 +451,31 @@ public long getSizeInBytes() } private PolygonGeometry getPolygonGeometry(DrawContext dc, List locations, List edgeFlags, - double[] altitudes, boolean[] terrainConformant, - boolean enableCaps, int subdivisions, - Vec4 referenceCenter) - { + double[] altitudes, boolean[] terrainConformant, + boolean enableCaps, int subdivisions, + Vec4 referenceCenter) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "Polygon", - locations, edgeFlags, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], - enableCaps, subdivisions, referenceCenter); + locations, edgeFlags, altitudes[0], altitudes[1], terrainConformant[0], terrainConformant[1], + enableCaps, subdivisions, referenceCenter); // Wrap geometry creation in a try/catch block. We do this to catch and handle OutOfMemoryErrors caused during // tessellation of the polygon vertices. If the polygon cannot be tessellated, we replace the polygon's // locations with an empty list to prevent subsequent tessellation attempts, and to avoid rendering a misleading // representation by omitting any part of the geometry. - try - { + try { PolygonGeometry geom = (PolygonGeometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null || this.isExpired(dc, geom.getVertexGeometry())) - { - if (geom == null) + if (geom == null || this.isExpired(dc, geom.getVertexGeometry())) { + if (geom == null) { geom = new PolygonGeometry(); + } this.makePolygon(dc, locations, edgeFlags, altitudes, terrainConformant, enableCaps, subdivisions, - referenceCenter, geom); + referenceCenter, geom); this.updateExpiryCriteria(dc, geom.getVertexGeometry()); this.getGeometryCache().add(cacheKey, geom); } return geom; - } - catch (OutOfMemoryError e) - { + } catch (OutOfMemoryError e) { String message = Logging.getMessage("generic.ExceptionWhileTessellating", this); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); @@ -547,8 +487,7 @@ private PolygonGeometry getPolygonGeometry(DrawContext dc, List location } } - protected void handleUnsuccessfulGeometryCreation() - { + protected void handleUnsuccessfulGeometryCreation() { // If creating the polygon geometry was unsuccessful, we modify the polygon to avoid any additional creation // attempts, and free any resources that the polygon won't use. This is done to gracefully handle // OutOfMemoryErrors throws while tessellating the polygon geometry. @@ -561,35 +500,35 @@ protected void handleUnsuccessfulGeometryCreation() } private void drawPolygonFill(DrawContext dc, List locations, List edgeFlags, - double[] altitudes, boolean[] terrainConformant, - boolean enableCaps, int subdivisions, - Vec4 referenceCenter) - { + double[] altitudes, boolean[] terrainConformant, + boolean enableCaps, int subdivisions, + Vec4 referenceCenter) { PolygonGeometry geom = this.getPolygonGeometry(dc, locations, edgeFlags, altitudes, terrainConformant, - enableCaps, subdivisions, referenceCenter); - if (geom != null) + enableCaps, subdivisions, referenceCenter); + if (geom != null) { this.drawGeometry(dc, geom.getFillIndexGeometry(), geom.getVertexGeometry()); + } } private void drawPolygonOutline(DrawContext dc, List locations, List edgeFlags, - double[] altitudes, boolean[] terrainConformant, - boolean enableCaps, int subdivisions, - Vec4 referenceCenter) - { + double[] altitudes, boolean[] terrainConformant, + boolean enableCaps, int subdivisions, + Vec4 referenceCenter) { PolygonGeometry geom = this.getPolygonGeometry(dc, locations, edgeFlags, altitudes, terrainConformant, - enableCaps, subdivisions, referenceCenter); - if (geom != null) + enableCaps, subdivisions, referenceCenter); + if (geom != null) { this.drawGeometry(dc, geom.getOutlineIndexGeometry(), geom.getVertexGeometry()); + } } private void makePolygon(DrawContext dc, List locations, List edgeFlags, - double[] altitudes, boolean[] terrainConformant, - boolean enableCaps, int subdivisions, - Vec4 referenceCenter, - PolygonGeometry dest) - { - if (locations.size() == 0) + double[] altitudes, boolean[] terrainConformant, + boolean enableCaps, int subdivisions, + Vec4 referenceCenter, + PolygonGeometry dest) { + if (locations.size() == 0) { return; + } GeometryBuilder gb = this.getGeometryBuilder(); @@ -597,13 +536,12 @@ private void makePolygon(DrawContext dc, List locations, List e Boolean[] polyEdgeFlags = new Boolean[locations.size() + 1]; Matrix[] polyTransform = new Matrix[1]; int polyCount = this.computeEllipsoidalPolygon(dc.getGlobe(), locations, edgeFlags, polyPoints, polyEdgeFlags, - polyTransform); + polyTransform); // Compute the winding order of the planar cartesian points. If the order is not counter-clockwise, then // reverse the locations and points ordering. int winding = gb.computePolygonWindingOrder2(0, polyCount, polyPoints); - if (winding != GeometryBuilder.COUNTER_CLOCKWISE) - { + if (winding != GeometryBuilder.COUNTER_CLOCKWISE) { gb.reversePoints(0, polyCount, polyPoints); gb.reversePoints(0, polyCount, polyEdgeFlags); } @@ -624,19 +562,16 @@ private void makePolygon(DrawContext dc, List locations, List e outlineIndexCount += this.getEdgeOutlineIndexCount(polyCount, subdivisions, polyEdgeFlags); vertexCount += this.getEdgeVertexCount(polyCount, subdivisions); - if (enableCaps) - { + if (enableCaps) { ita = gb.tessellatePolygon2(0, polyCount, polyVertices); - for (int i = 0; i < subdivisions; i++) - { + for (int i = 0; i < subdivisions; i++) { gb.subdivideIndexedTriangleArray(ita); } fillIndexCount += ita.getIndexCount(); vertexCount += ita.getVertexCount(); // Bottom cap isn't drawn if airspace is collapsed. - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { fillIndexCount += ita.getIndexCount(); vertexCount += ita.getVertexCount(); } @@ -652,23 +587,21 @@ private void makePolygon(DrawContext dc, List locations, List e int vertexPos = 0; this.makeEdge(dc, polyCount, polyVertices, polyEdgeFlags, altitudes, terrainConformant, subdivisions, - GeometryBuilder.OUTSIDE, polyTransform[0], referenceCenter, - fillIndexPos, fillIndices, outlineIndexPos, outlineIndices, vertexPos, vertices, normals); + GeometryBuilder.OUTSIDE, polyTransform[0], referenceCenter, + fillIndexPos, fillIndices, outlineIndexPos, outlineIndices, vertexPos, vertices, normals); fillIndexPos += this.getEdgeFillIndexCount(polyCount, subdivisions); outlineIndexPos += this.getEdgeOutlineIndexCount(polyCount, subdivisions, polyEdgeFlags); vertexPos += this.getEdgeVertexCount(polyCount, subdivisions); - if (enableCaps) - { + if (enableCaps) { this.makeCap(dc, ita, altitudes[1], terrainConformant[1], GeometryBuilder.OUTSIDE, polyTransform[0], - referenceCenter, fillIndexPos, fillIndices, vertexPos, vertices, normals); + referenceCenter, fillIndexPos, fillIndices, vertexPos, vertices, normals); fillIndexPos += ita.getIndexCount(); vertexPos += ita.getVertexCount(); // Bottom cap isn't drawn if airspace is collapsed. - if (!this.isAirspaceCollapsed()) - { + if (!this.isAirspaceCollapsed()) { this.makeCap(dc, ita, altitudes[0], terrainConformant[0], GeometryBuilder.INSIDE, polyTransform[0], - referenceCenter, fillIndexPos, fillIndices, vertexPos, vertices, normals); + referenceCenter, fillIndexPos, fillIndices, vertexPos, vertices, normals); fillIndexPos += ita.getIndexCount(); vertexPos += ita.getVertexCount(); } @@ -681,17 +614,16 @@ private void makePolygon(DrawContext dc, List locations, List e } protected void makeTessellatedLocations(Globe globe, int subdivisions, List locations, - List tessellatedLocations) - { + List tessellatedLocations) { ArrayList points = new ArrayList(); - for (LatLon ll : locations) - { + for (LatLon ll : locations) { points.add(globe.computeEllipsoidalPointFromPosition(ll.latitude, ll.longitude, 0)); } //noinspection StringEquality - if (WWMath.computeWindingOrderOfLocations(locations) != AVKey.COUNTER_CLOCKWISE) + if (WWMath.computeWindingOrderOfLocations(locations) != AVKey.COUNTER_CLOCKWISE) { Collections.reverse(locations); + } Vec4 centerPoint = Vec4.computeAveragePoint(points); Position centerPos = globe.computePositionFromEllipsoidalPoint(centerPoint); @@ -699,22 +631,19 @@ protected void makeTessellatedLocations(Globe globe, int subdivisions, List locations = rs.getStateValueAsLatLonList(context, "locations"); - if (locations != null) + if (locations != null) { this.setLocations(locations); + } } } diff --git a/src/gov/nasa/worldwind/render/airspaces/Route.java b/src/gov/nasa/worldwind/render/airspaces/Route.java index 10a09aa6d0..dc4bc754c9 100644 --- a/src/gov/nasa/worldwind/render/airspaces/Route.java +++ b/src/gov/nasa/worldwind/render/airspaces/Route.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.geom.*; @@ -20,15 +19,13 @@ * @author garakl * @version $Id: Route.java 2563 2014-12-12 19:29:38Z dcollins $ */ -public class Route extends TrackAirspace -{ +public class Route extends TrackAirspace { + private List locations = new ArrayList(); private double width = 1.0; - public Route(List locations, double width) - { - if (width < 0.0) - { + public Route(List locations, double width) { + if (width < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width=" + width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -39,53 +36,44 @@ public Route(List locations, double width) this.setEnableInnerCaps(false); } - public Route(AirspaceAttributes attributes) - { + public Route(AirspaceAttributes attributes) { super(attributes); this.setEnableInnerCaps(false); } - public Route() - { + public Route() { this.setEnableInnerCaps(false); } - public Route(Route source) - { + public Route(Route source) { super(source); this.locations = new ArrayList(source.locations.size()); - for (LatLon location : source.locations) - { + for (LatLon location : source.locations) { this.locations.add(location); } this.width = source.width; } - public Iterable getLocations() - { + public Iterable getLocations() { return java.util.Collections.unmodifiableList(this.locations); } - public void setLocations(Iterable locations) - { + public void setLocations(Iterable locations) { this.locations.clear(); this.removeAllLegs(); this.addLocations(locations); } - protected void addLocations(Iterable newLocations) - { - if (newLocations != null) - { + protected void addLocations(Iterable newLocations) { + if (newLocations != null) { LatLon last = null; - for (LatLon cur : newLocations) - { - if (cur != null) - { - if (last != null) + for (LatLon cur : newLocations) { + if (cur != null) { + if (last != null) { this.addLeg(last, cur); + } last = cur; } } @@ -95,15 +83,12 @@ protected void addLocations(Iterable newLocations) this.setLegsOutOfDate(true); } - public double getWidth() - { + public double getWidth() { return this.width; } - public void setWidth(double width) - { - if (width < 0.0) - { + public void setWidth(double width) { + if (width < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width=" + width); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -112,8 +97,7 @@ public void setWidth(double width) this.width = width; double legWidth = this.width / 2.0; - for (Box l : this.getLegs()) - { + for (Box l : this.getLegs()) { l.setWidths(legWidth, legWidth); } @@ -121,35 +105,26 @@ public void setWidth(double width) this.setLegsOutOfDate(true); } - public Box addLeg(LatLon start, LatLon end) - { - if (start == null) - { + public Box addLeg(LatLon start, LatLon end) { + if (start == null) { String message = "nullValue.StartIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (end == null) - { + if (end == null) { String message = "nullValue.EndIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.locations.size() == 0) - { + if (this.locations.size() == 0) { this.locations.add(start); this.locations.add(end); - } - else - { + } else { LatLon last = this.locations.get(this.locations.size() - 1); - if (start.equals(last)) - { + if (start.equals(last)) { this.locations.add(end); - } - else - { + } else { String message = "Shapes.Route.DisjointLegDetected"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -174,8 +149,7 @@ public Box addLeg(LatLon start, LatLon end) /** * This method is not supported for {@link gov.nasa.worldwind.render.airspaces.Route}. */ - public void setLegs(Collection legs) - { + public void setLegs(Collection legs) { String message = Logging.getMessage("generic.UnsupportedOperation", "setLegs"); Logging.logger().severe(message); throw new UnsupportedOperationException(); @@ -206,8 +180,7 @@ public void setLegs(Collection legs) * This method is not supported for {@link gov.nasa.worldwind.render.airspaces.Route}. */ public Box addLeg(LatLon start, LatLon end, double lowerAltitude, double upperAltitude, double leftWidth, - double rightWidth) - { + double rightWidth) { String message = Logging.getMessage("generic.UnsupportedOperation", "addLeg"); Logging.logger().severe(message); throw new UnsupportedOperationException(); @@ -224,21 +197,17 @@ public Box addLeg(LatLon start, LatLon end, double lowerAltitude, double upperAl // return newLeg; } - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.computeReferencePosition(this.locations, this.getAltitudes()); } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -248,16 +217,13 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) this.setLocations(newLocations); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -267,8 +233,7 @@ protected void doMoveTo(Position oldRef, Position newRef) int count = this.locations.size(); LatLon[] newLocations = new LatLon[count]; - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { LatLon ll = this.locations.get(i); double distance = LatLon.greatCircleDistance(oldRef, ll).radians; double azimuth = LatLon.greatCircleAzimuth(oldRef, ll).radians; @@ -278,8 +243,7 @@ protected void doMoveTo(Position oldRef, Position newRef) } @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsDouble(context, "width", this.width); @@ -287,16 +251,17 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Double d = rs.getStateValueAsDouble(context, "width"); - if (d != null) + if (d != null) { this.setWidth(d); + } List locs = rs.getStateValueAsLatLonList(context, "locations"); - if (locs != null) + if (locs != null) { this.setLocations(locs); + } } } diff --git a/src/gov/nasa/worldwind/render/airspaces/ScreenSizeDetailLevel.java b/src/gov/nasa/worldwind/render/airspaces/ScreenSizeDetailLevel.java index cfdee926e8..14ea9bb711 100644 --- a/src/gov/nasa/worldwind/render/airspaces/ScreenSizeDetailLevel.java +++ b/src/gov/nasa/worldwind/render/airspaces/ScreenSizeDetailLevel.java @@ -14,81 +14,76 @@ * @author dcollins * @version $Id: ScreenSizeDetailLevel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScreenSizeDetailLevel extends AVListImpl implements DetailLevel -{ +public class ScreenSizeDetailLevel extends AVListImpl implements DetailLevel { + private static final double DEFAULT_MIN_SIZE = 40.0; private static final double DEFAULT_MAX_SIZE = 700.0; private final double screenSize; private final String key; - public ScreenSizeDetailLevel(double minimumScreenSize, String key) - { + public ScreenSizeDetailLevel(double minimumScreenSize, String key) { this.screenSize = minimumScreenSize; this.key = key; } - public double getScreenSize() - { + public double getScreenSize() { return this.screenSize; } - public String getKey() - { + public String getKey() { return this.key; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } ScreenSizeDetailLevel that = (ScreenSizeDetailLevel) o; return Double.compare(this.screenSize, that.screenSize) == 0; } - public int compareTo(DetailLevel level) - { - if (this == level) + public int compareTo(DetailLevel level) { + if (this == level) { return 0; - if (level == null || this.getClass() != level.getClass()) + } + if (level == null || this.getClass() != level.getClass()) { return -1; + } ScreenSizeDetailLevel that = (ScreenSizeDetailLevel) level; return Double.compare(this.screenSize, that.screenSize); } - public int hashCode() - { + public int hashCode() { long temp = this.screenSize != +0.0d ? Double.doubleToLongBits(this.screenSize) : 0L; return (int) (temp ^ (temp >>> 32)); } - public String toString() - { + public String toString() { return this.key; } - public boolean meetsCriteria(DrawContext dc, Airspace airspace) - { - if (dc == null) - { + public boolean meetsCriteria(DrawContext dc, Airspace airspace) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getView() == null) - { + if (dc.getView() == null) { String message = "nullValue.DrawingContextViewIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } Extent extent = airspace.getExtent(dc); - if (extent == null) + if (extent == null) { return false; + } double d = dc.getView().getEyePoint().distanceTo3(extent.getCenter()); double pixelSize = dc.getView().computePixelSizeAtDistance(d); @@ -96,18 +91,15 @@ public boolean meetsCriteria(DrawContext dc, Airspace airspace) return shapeScreenSize < this.screenSize; } - public static double[] computeDefaultScreenSizeRamp(int levels) - { + public static double[] computeDefaultScreenSizeRamp(int levels) { return computeLinearScreenSizeRamp(levels, DEFAULT_MIN_SIZE, DEFAULT_MAX_SIZE); } - public static double[] computeLinearScreenSizeRamp(int levels, double min, double max) - { + public static double[] computeLinearScreenSizeRamp(int levels, double min, double max) { double[] ramp = new double[levels]; double a; - for (int i = 0; i < levels; i++) - { + for (int i = 0; i < levels; i++) { a = (double) i / (double) (levels - 1); ramp[levels - i - 1] = min + a * (max - min); } diff --git a/src/gov/nasa/worldwind/render/airspaces/SphereAirspace.java b/src/gov/nasa/worldwind/render/airspaces/SphereAirspace.java index e106078a7b..39c68f6d70 100644 --- a/src/gov/nasa/worldwind/render/airspaces/SphereAirspace.java +++ b/src/gov/nasa/worldwind/render/airspaces/SphereAirspace.java @@ -24,8 +24,8 @@ * @author dcollins * @version $Id: SphereAirspace.java 2308 2014-09-16 19:27:22Z tgaskins $ */ -public class SphereAirspace extends AbstractAirspace -{ +public class SphereAirspace extends AbstractAirspace { + protected static final int DEFAULT_SUBDIVISIONS = 3; private LatLon location = LatLon.ZERO; @@ -33,16 +33,13 @@ public class SphereAirspace extends AbstractAirspace // Geometry. private int subdivisions = DEFAULT_SUBDIVISIONS; - public SphereAirspace(LatLon location, double radius) - { - if (location == null) - { + public SphereAirspace(LatLon location, double radius) { + if (location == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (radius < 0.0) - { + if (radius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -53,19 +50,16 @@ public SphereAirspace(LatLon location, double radius) this.makeDefaultDetailLevels(); } - public SphereAirspace(AirspaceAttributes attributes) - { + public SphereAirspace(AirspaceAttributes attributes) { super(attributes); this.makeDefaultDetailLevels(); } - public SphereAirspace() - { + public SphereAirspace() { this.makeDefaultDetailLevels(); } - public SphereAirspace(SphereAirspace source) - { + public SphereAirspace(SphereAirspace source) { super(source); this.location = source.location; @@ -75,8 +69,7 @@ public SphereAirspace(SphereAirspace source) this.makeDefaultDetailLevels(); } - private void makeDefaultDetailLevels() - { + private void makeDefaultDetailLevels() { List levels = new ArrayList(); double[] ramp = ScreenSizeDetailLevel.computeLinearScreenSizeRamp(7, 10.0, 600.0); @@ -124,8 +117,7 @@ private void makeDefaultDetailLevels() * * @return location of the sphere. */ - public LatLon getLocation() - { + public LatLon getLocation() { return this.location; } @@ -136,10 +128,8 @@ public LatLon getLocation() * * @throws IllegalArgumentException if location is null */ - public void setLocation(LatLon location) - { - if (location == null) - { + public void setLocation(LatLon location) { + if (location == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -154,8 +144,7 @@ public void setLocation(LatLon location) * * @return radius of the sphere in meters. */ - public double getRadius() - { + public double getRadius() { return this.radius; } @@ -167,10 +156,8 @@ public double getRadius() * * @throws IllegalArgumentException if radius is less than zero */ - public void setRadius(double radius) - { - if (radius < 0.0) - { + public void setRadius(double radius) { + if (radius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -180,44 +167,39 @@ public void setRadius(double radius) this.invalidateAirspaceData(); } - public Position getReferencePosition() - { + public Position getReferencePosition() { double[] altitudes = this.getAltitudes(); return new Position(this.location, altitudes[0]); } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { double altitude = this.getAltitudes(verticalExaggeration)[0]; boolean terrainConformant = this.isTerrainConforming()[0]; double radius = this.getRadius(); - if (terrainConformant) - { + if (terrainConformant) { double[] extremes = globe.getMinAndMaxElevations(this.location.getLatitude(), this.location.getLongitude()); double minAltitude = verticalExaggeration * extremes[0] + altitude - radius; double maxAltitude = verticalExaggeration * extremes[1] + altitude + radius; Vec4 bottomCenter = globe.computePointFromPosition(this.location, minAltitude); Vec4 topCenter = globe.computePointFromPosition(this.location, maxAltitude); return new Cylinder(bottomCenter, topCenter, radius); - } - else - { + } else { Vec4 centerPoint = globe.computePointFromPosition(this.location, altitude); return new Sphere(centerPoint, radius); } } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { return null; // Sphere has no need for a minimal geometry. } /** * Returns this SphereAirspace's {@link gov.nasa.worldwind.geom.Extent} for the specified DrawContext. This - * overrides {@link gov.nasa.worldwind.render.airspaces.AbstractAirspace#getExtent(gov.nasa.worldwind.render.DrawContext)} - * in order to bypass the superclass' extent caching. Unlike other Airspace's Extents, SphereAirspace's Extent is a + * overrides + * {@link gov.nasa.worldwind.render.airspaces.AbstractAirspace#getExtent(gov.nasa.worldwind.render.DrawContext)} in + * order to bypass the superclass' extent caching. Unlike other Airspace's Extents, SphereAirspace's Extent is a * perfect fitting {@link gov.nasa.worldwind.geom.Sphere}, who's center point depends on the current surface * geometry. For this reason SphereAirspace's exact bounding volume can be easily computed, and should not be * cached. @@ -228,17 +210,14 @@ protected List computeMinimalGeometry(Globe globe, double verticalExaggera * * @throws IllegalArgumentException if the DrawContext is null, or if the Globe held by the DrawContext is null. */ - public Extent getExtent(DrawContext dc) - { - if (dc == null) - { + public Extent getExtent(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -247,8 +226,7 @@ public Extent getExtent(DrawContext dc) return this.computeExtent(dc); } - protected Sphere computeExtent(DrawContext dc) - { + protected Sphere computeExtent(DrawContext dc) { double altitude = this.getAltitudes(dc.getVerticalExaggeration())[0]; boolean terrainConformant = this.isTerrainConforming()[0]; double radius = this.getRadius(); @@ -256,20 +234,17 @@ protected Sphere computeExtent(DrawContext dc) this.clearElevationMap(); Vec4 centerPoint = this.computePointFromPosition(dc, this.location.getLatitude(), this.location.getLongitude(), - altitude, terrainConformant); + altitude, terrainConformant); return new Sphere(centerPoint, radius); } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -283,16 +258,13 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) super.doMoveTo(oldRef, newRef); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -303,8 +275,7 @@ protected void doMoveTo(Position oldRef, Position newRef) this.setLocation(newRef); } - protected double computeEyeDistance(DrawContext dc) - { + protected double computeEyeDistance(DrawContext dc) { Sphere sphere = this.computeExtent(dc); Vec4 eyePoint = dc.getView().getEyePoint(); @@ -315,35 +286,29 @@ protected double computeEyeDistance(DrawContext dc) } @Override - protected SurfaceShape createSurfaceShape() - { + protected SurfaceShape createSurfaceShape() { return new SurfaceCircle(); } @Override - protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void updateSurfaceShape(DrawContext dc, SurfaceShape shape) { super.updateSurfaceShape(dc, shape); shape.getAttributes().setDrawOutline(false); // suppress the surface shape's outline } @Override - protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) - { + protected void regenerateSurfaceShape(DrawContext dc, SurfaceShape shape) { ((SurfaceCircle) shape).setCenter(this.location); ((SurfaceCircle) shape).setRadius(this.radius); } - protected int getSubdivisions() - { + protected int getSubdivisions() { return this.subdivisions; } - protected void setSubdivisions(int subdivisions) - { - if (subdivisions < 0) - { + protected void setSubdivisions(int subdivisions) { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -355,17 +320,13 @@ protected void setSubdivisions(int subdivisions) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { - if (dc == null) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -373,29 +334,25 @@ protected void doRenderGeometry(DrawContext dc, String drawStyle) this.clearElevationMap(); - if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) - { + if (Airspace.DRAW_STYLE_FILL.equals(drawStyle)) { this.drawSphere(dc); - } - else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) - { + } else if (Airspace.DRAW_STYLE_OUTLINE.equals(drawStyle)) { // Sphere airspaces do not display an outline. } } - protected void drawSphere(DrawContext dc) - { + protected void drawSphere(DrawContext dc) { double[] altitudes = this.getAltitudes(dc.getVerticalExaggeration()); boolean[] terrainConformant = this.isTerrainConforming(); int subdivisions = this.getSubdivisions(); - if (this.isEnableLevelOfDetail()) - { + if (this.isEnableLevelOfDetail()) { DetailLevel level = this.computeDetailLevel(dc); Object o = level.getValue(SUBDIVISIONS); - if (o != null && o instanceof Integer) + if (o != null && o instanceof Integer) { subdivisions = (Integer) o; + } //o = level.getValue(DISABLE_TERRAIN_CONFORMANCE); //if (o != null && o instanceof Boolean && (Boolean) o) @@ -403,7 +360,7 @@ protected void drawSphere(DrawContext dc) } Vec4 centerPoint = this.computePointFromPosition(dc, - this.location.getLatitude(), this.location.getLongitude(), altitudes[0], terrainConformant[0]); + this.location.getLatitude(), this.location.getLongitude(), altitudes[0], terrainConformant[0]); Matrix modelview = dc.getView().getModelviewMatrix(); modelview = modelview.multiply(Matrix.fromTranslation(centerPoint)); @@ -415,8 +372,7 @@ protected void drawSphere(DrawContext dc) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glPushAttrib(GL2.GL_POLYGON_BIT | GL2.GL_TRANSFORM_BIT); - try - { + try { gl.glEnable(GL.GL_CULL_FACE); gl.glFrontFace(GL.GL_CCW); @@ -428,30 +384,24 @@ protected void drawSphere(DrawContext dc) gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); - try - { + try { gl.glLoadMatrixd(matrixArray, 0); this.drawUnitSphere(dc, subdivisions); - } - finally - { + } finally { gl.glPopMatrix(); } - } - finally - { + } finally { gl.glPopAttrib(); } } - protected void drawUnitSphere(DrawContext dc, int subdivisions) - { + protected void drawUnitSphere(DrawContext dc, int subdivisions) { Object cacheKey = new Geometry.CacheKey(dc.getGlobe(), this.getClass(), "Sphere", subdivisions); Geometry geom = (Geometry) this.getGeometryCache().getObject(cacheKey); - if (geom == null || this.isExpired(dc, geom)) - { - if (geom == null) + if (geom == null || this.isExpired(dc, geom)) { + if (geom == null) { geom = new Geometry(); + } this.makeSphere(1.0, subdivisions, geom); this.updateExpiryCriteria(dc, geom); this.getGeometryCache().add(cacheKey, geom); @@ -460,8 +410,7 @@ protected void drawUnitSphere(DrawContext dc, int subdivisions) this.drawGeometry(dc, geom, geom); } - protected void makeSphere(double radius, int subdivisions, Geometry dest) - { + protected void makeSphere(double radius, int subdivisions, Geometry dest) { GeometryBuilder gb = this.getGeometryBuilder(); gb.setOrientation(GeometryBuilder.OUTSIDE); @@ -477,9 +426,7 @@ protected void makeSphere(double radius, int subdivisions, Geometry dest) //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsLatLon(context, "location", this.getLocation()); @@ -487,20 +434,22 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsInteger(context, "subdivisions", this.getSubdivisions()); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); LatLon ll = rs.getStateValueAsLatLon(context, "location"); - if (ll != null) + if (ll != null) { this.setLocation(ll); + } Double d = rs.getStateValueAsDouble(context, "radius"); - if (d != null) + if (d != null) { this.setRadius(d); + } Integer i = rs.getStateValueAsInteger(context, "subdivisions"); - if (i != null) + if (i != null) { this.setSubdivisions(i); + } } } diff --git a/src/gov/nasa/worldwind/render/airspaces/SurfaceBox.java b/src/gov/nasa/worldwind/render/airspaces/SurfaceBox.java index 1b5e0408b4..78b135cf58 100644 --- a/src/gov/nasa/worldwind/render/airspaces/SurfaceBox.java +++ b/src/gov/nasa/worldwind/render/airspaces/SurfaceBox.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.airspaces; import gov.nasa.worldwind.geom.*; @@ -14,8 +13,8 @@ import com.jogamp.opengl.GL2; import java.util.*; -public class SurfaceBox extends AbstractSurfaceShape -{ +public class SurfaceBox extends AbstractSurfaceShape { + protected List locations; protected int lengthSegments; protected int widthSegments; @@ -24,87 +23,73 @@ public class SurfaceBox extends AbstractSurfaceShape protected boolean enableCenterLine; protected List> activeCenterLineGeometry = new ArrayList>(); // re-determined each frame - public SurfaceBox() - { + public SurfaceBox() { } - public List getLocations() - { + public List getLocations() { return this.locations; } - public void setLocations(List locations) - { + public void setLocations(List locations) { this.locations = locations; this.onShapeChanged(); } - public int getLengthSegments() - { + public int getLengthSegments() { return this.lengthSegments; } - public void setLengthSegments(int lengthSegments) - { + public void setLengthSegments(int lengthSegments) { this.lengthSegments = lengthSegments; this.onShapeChanged(); } - public int getWidthSegments() - { + public int getWidthSegments() { return this.widthSegments; } - public void setWidthSegments(int widthSegments) - { + public void setWidthSegments(int widthSegments) { this.widthSegments = widthSegments; this.onShapeChanged(); } - public boolean[] isEnableCaps() - { - return new boolean[] {this.enableStartCap, this.enableEndCap}; + public boolean[] isEnableCaps() { + return new boolean[]{this.enableStartCap, this.enableEndCap}; } - public void setEnableCaps(boolean enableStartCap, boolean enableEndCap) - { + public void setEnableCaps(boolean enableStartCap, boolean enableEndCap) { this.enableStartCap = enableStartCap; this.enableEndCap = enableEndCap; this.onShapeChanged(); } - public boolean isEnableCenterLine() - { + public boolean isEnableCenterLine() { return this.enableCenterLine; } - public void setEnableCenterLine(boolean enable) - { + public void setEnableCenterLine(boolean enable) { this.enableCenterLine = enable; } @Override - public Position getReferencePosition() - { + public Position getReferencePosition() { return this.locations != null && this.locations.size() > 0 ? new Position(this.locations.get(0), 0) : null; } @Override - protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) - { + protected void doMoveTo(Position oldReferencePosition, Position newReferencePosition) { // Intentionally left blank. } @Override - protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) - { + protected void doMoveTo(Globe globe, Position oldReferencePosition, Position newReferencePosition) { // Intentionally left blank. } - protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) - { - if (this.locations == null) + protected List> createGeometry(Globe globe, double edgeIntervalsPerDegree) { + if (this.locations == null) { return null; + } ArrayList> geom = new ArrayList>(); @@ -112,8 +97,7 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer ArrayList interior = new ArrayList(); geom.add(interior); - for (int i = 0; i < this.locations.size() - 1; i++) - { + for (int i = 0; i < this.locations.size() - 1; i++) { LatLon a = this.locations.get(i); LatLon b = this.locations.get(i + 1); // first and last location are the same interior.add(a); @@ -125,10 +109,8 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer boolean[] sideFlag = {this.enableStartCap, true, this.enableEndCap, true}; int offset = 0; - for (int i = 0; i < 4; i++) - { - if (sideFlag[i]) - { + for (int i = 0; i < 4; i++) { + if (sideFlag[i]) { geom.add(this.makeLocations(offset, sideSegments[i], edgeIntervalsPerDegree)); } @@ -147,35 +129,34 @@ protected List> createGeometry(Globe globe, double edgeIntervalsPer return geom; } - protected ArrayList makeLocations(int offset, int count, double edgeIntervalsPerDegree) - { + protected ArrayList makeLocations(int offset, int count, double edgeIntervalsPerDegree) { ArrayList locations = new ArrayList(); - for (int i = offset; i < offset + count; i++) - { + for (int i = offset; i < offset + count; i++) { LatLon a = this.locations.get(i); LatLon b = this.locations.get(i + 1); locations.add(a); this.addIntermediateLocations(a, b, edgeIntervalsPerDegree, locations); - if (i == offset + count - 1) + if (i == offset + count - 1) { locations.add(b); + } } return locations; } @Override - protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sdc) { this.activeGeometry.clear(); this.activeOutlineGeometry.clear(); this.activeCenterLineGeometry.clear(); List> geom = this.getCachedGeometry(dc, sdc); // calls createGeometry - if (geom == null) + if (geom == null) { return; + } int index = 0; // interior geometry stored in index 0 List interior = geom.get(index++); @@ -183,13 +164,9 @@ protected void determineActiveGeometry(DrawContext dc, SurfaceTileDrawContext sd if (pole != null) // interior compensates for poles and dateline crossing, see WWJ-284 { this.activeGeometry.add(this.cutAlongDateLine(interior, pole, dc.getGlobe())); - } - else if (LatLon.locationsCrossDateLine(interior)) - { + } else if (LatLon.locationsCrossDateLine(interior)) { this.activeGeometry.addAll(this.repeatAroundDateline(interior)); - } - else - { + } else { this.activeGeometry.add(interior); } @@ -199,9 +176,7 @@ else if (LatLon.locationsCrossDateLine(interior)) if (LatLon.locationsCrossDateLine(outline)) // outlines compensate for dateline crossing, see WWJ-452 { this.activeOutlineGeometry.addAll(this.repeatAroundDateline(outline)); - } - else - { + } else { this.activeOutlineGeometry.add(outline); } } @@ -212,39 +187,33 @@ else if (LatLon.locationsCrossDateLine(interior)) if (LatLon.locationsCrossDateLine(centerLine)) // outlines compensate for dateline crossing, see WWJ-452 { this.activeCenterLineGeometry.addAll(this.repeatAroundDateline(centerLine)); - } - else - { + } else { this.activeCenterLineGeometry.add(centerLine); } } } - protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) - { + protected void drawOutline(DrawContext dc, SurfaceTileDrawContext sdc) { super.drawOutline(dc, sdc); - if (this.enableCenterLine) - { + if (this.enableCenterLine) { this.drawCenterLine(dc); } } - protected void drawCenterLine(DrawContext dc) - { - if (this.activeCenterLineGeometry.isEmpty()) + protected void drawCenterLine(DrawContext dc) { + if (this.activeCenterLineGeometry.isEmpty()) { return; + } this.applyCenterLineState(dc, this.getActiveAttributes()); - for (List drawLocations : this.activeCenterLineGeometry) - { + for (List drawLocations : this.activeCenterLineGeometry) { this.drawLineStrip(dc, drawLocations); } } - protected void applyCenterLineState(DrawContext dc, ShapeAttributes attributes) - { + protected void applyCenterLineState(DrawContext dc, ShapeAttributes attributes) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. if (!dc.isPickingMode() && attributes.getOutlineStippleFactor() <= 0) // don't override stipple in attributes @@ -255,10 +224,8 @@ protected void applyCenterLineState(DrawContext dc, ShapeAttributes attributes) } @Override - public Iterable getLocations(Globe globe) - { - if (globe == null) - { + public Iterable getLocations(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/render/airspaces/TrackAirspace.java b/src/gov/nasa/worldwind/render/airspaces/TrackAirspace.java index 64a69504b0..fe0869f727 100644 --- a/src/gov/nasa/worldwind/render/airspaces/TrackAirspace.java +++ b/src/gov/nasa/worldwind/render/airspaces/TrackAirspace.java @@ -19,8 +19,8 @@ * @author garakl * @version $Id: TrackAirspace.java 2565 2014-12-12 23:57:06Z dcollins $ */ -public class TrackAirspace extends AbstractAirspace -{ +public class TrackAirspace extends AbstractAirspace { + protected List legs = new ArrayList(); protected boolean legsOutOfDate = true; protected boolean enableInnerCaps = true; @@ -31,27 +31,22 @@ public class TrackAirspace extends AbstractAirspace */ protected Angle smallAngleThreshold = Angle.fromDegrees(22.5); - public TrackAirspace(Collection legs) - { + public TrackAirspace(Collection legs) { this.addLegs(legs); } - public TrackAirspace(AirspaceAttributes attributes) - { + public TrackAirspace(AirspaceAttributes attributes) { super(attributes); } - public TrackAirspace() - { + public TrackAirspace() { } - public TrackAirspace(TrackAirspace source) - { + public TrackAirspace(TrackAirspace source) { super(source); this.legs = new ArrayList(source.legs.size()); - for (Box leg : source.legs) - { + for (Box leg : source.legs) { this.legs.add(new Box(leg)); } @@ -60,25 +55,21 @@ public TrackAirspace(TrackAirspace source) this.smallAngleThreshold = source.smallAngleThreshold; } - public List getLegs() - { + public List getLegs() { return Collections.unmodifiableList(this.legs); } - public void setLegs(Collection legs) - { + public void setLegs(Collection legs) { this.legs.clear(); this.addLegs(legs); } - protected void addLegs(Iterable newLegs) - { - if (newLegs != null) - { - for (Box b : newLegs) - { - if (b != null) + protected void addLegs(Iterable newLegs) { + if (newLegs != null) { + for (Box b : newLegs) { + if (b != null) { this.addLeg(b); + } } } @@ -87,16 +78,13 @@ protected void addLegs(Iterable newLegs) } public Box addLeg(LatLon start, LatLon end, double lowerAltitude, double upperAltitude, - double leftWidth, double rightWidth) - { - if (start == null) - { + double leftWidth, double rightWidth) { + if (start == null) { String message = "nullValue.StartIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (end == null) - { + if (end == null) { String message = "nullValue.EndIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -113,10 +101,8 @@ public Box addLeg(LatLon start, LatLon end, double lowerAltitude, double upperAl return leg; } - protected void addLeg(Box leg) - { - if (leg == null) - { + protected void addLeg(Box leg) { + if (leg == null) { String message = "nullValue.LegIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -131,40 +117,33 @@ protected void addLeg(Box leg) this.setLegsOutOfDate(true); } - public void removeAllLegs() - { + public void removeAllLegs() { this.legs.clear(); } - public boolean isEnableInnerCaps() - { + public boolean isEnableInnerCaps() { return this.enableInnerCaps; } - public void setEnableInnerCaps(boolean draw) - { + public void setEnableInnerCaps(boolean draw) { this.enableInnerCaps = draw; this.invalidateAirspaceData(); this.setLegsOutOfDate(true); } - public boolean isEnableCenterLine() - { + public boolean isEnableCenterLine() { return this.enableCenterLine; } - public void setEnableCenterLine(boolean enable) - { + public void setEnableCenterLine(boolean enable) { this.enableCenterLine = enable; - for (Box leg : this.legs) - { + for (Box leg : this.legs) { leg.setEnableCenterLine(enable); } } - public void setEnableDepthOffset(boolean enable) - { + public void setEnableDepthOffset(boolean enable) { super.setEnableDepthOffset(enable); this.setLegsOutOfDate(true); } @@ -177,8 +156,7 @@ public void setEnableDepthOffset(boolean enable) * * @see #setSmallAngleThreshold(gov.nasa.worldwind.geom.Angle) */ - public Angle getSmallAngleThreshold() - { + public Angle getSmallAngleThreshold() { return smallAngleThreshold; } @@ -195,10 +173,8 @@ public Angle getSmallAngleThreshold() * @throws IllegalArgumentException if angle is null. * @see #getSmallAngleThreshold() */ - public void setSmallAngleThreshold(Angle angle) - { - if (angle == null) - { + public void setSmallAngleThreshold(Angle angle) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -207,12 +183,10 @@ public void setSmallAngleThreshold(Angle angle) this.smallAngleThreshold = angle; } - public void setAltitudes(double lowerAltitude, double upperAltitude) - { + public void setAltitudes(double lowerAltitude, double upperAltitude) { super.setAltitudes(lowerAltitude, upperAltitude); - for (Box l : this.legs) - { + for (Box l : this.legs) { l.setAltitudes(lowerAltitude, upperAltitude); } @@ -220,12 +194,10 @@ public void setAltitudes(double lowerAltitude, double upperAltitude) this.setLegsOutOfDate(true); } - public void setTerrainConforming(boolean lowerTerrainConformant, boolean upperTerrainConformant) - { + public void setTerrainConforming(boolean lowerTerrainConformant, boolean upperTerrainConformant) { super.setTerrainConforming(lowerTerrainConformant, upperTerrainConformant); - for (Box l : this.legs) - { + for (Box l : this.legs) { l.setTerrainConforming(lowerTerrainConformant, upperTerrainConformant); } @@ -234,48 +206,41 @@ public void setTerrainConforming(boolean lowerTerrainConformant, boolean upperTe } @Override - public void setAlwaysOnTop(boolean alwaysOnTop) - { + public void setAlwaysOnTop(boolean alwaysOnTop) { super.setAlwaysOnTop(alwaysOnTop); - for (Box l : this.getLegs()) - { + for (Box l : this.getLegs()) { l.setAlwaysOnTop(alwaysOnTop); } } @Override - public void setDrawSurfaceShape(boolean drawSurfaceShape) - { + public void setDrawSurfaceShape(boolean drawSurfaceShape) { super.setDrawSurfaceShape(drawSurfaceShape); - for (Box l : this.getLegs()) - { + for (Box l : this.getLegs()) { l.setDrawSurfaceShape(drawSurfaceShape); } } - public boolean isAirspaceVisible(DrawContext dc) - { - if (dc == null) - { + public boolean isAirspaceVisible(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // If the parent TrackAirspace is not visible, then return false immediately without testing the child legs. - if (!super.isAirspaceVisible(dc)) + if (!super.isAirspaceVisible(dc)) { return false; + } boolean visible = false; // The parent TrackAirspace is visible. Since the parent TrackAirspace's extent potentially contains volumes // where no child geometry exists, test that at least one of the child legs are visible. - for (Box b : this.legs) - { - if (b.isAirspaceVisible(dc)) - { + for (Box b : this.legs) { + if (b.isAirspaceVisible(dc)) { visible = true; break; } @@ -284,11 +249,9 @@ public boolean isAirspaceVisible(DrawContext dc) return visible; } - public Position getReferencePosition() - { + public Position getReferencePosition() { ArrayList locations = new ArrayList(2 * this.legs.size()); - for (Box box : this.legs) - { + for (Box box : this.legs) { LatLon[] ll = box.getLocations(); locations.add(ll[0]); locations.add(ll[1]); @@ -298,36 +261,27 @@ public Position getReferencePosition() } @Override - protected Extent computeExtent(DrawContext dc) - { + protected Extent computeExtent(DrawContext dc) { // Update the child leg vertices if they're out of date. Since the leg vertices are input to the parent // TrackAirspace's extent computation, they must be current before computing the parent's extent. - if (this.isLegsOutOfDate()) - { + if (this.isLegsOutOfDate()) { this.doUpdateLegs(); } return super.computeExtent(dc); } - protected Extent computeExtent(Globe globe, double verticalExaggeration) - { + protected Extent computeExtent(Globe globe, double verticalExaggeration) { List trackLegs = this.getLegs(); - if (trackLegs == null || trackLegs.isEmpty()) - { + if (trackLegs == null || trackLegs.isEmpty()) { return null; - } - else if (trackLegs.size() == 0) - { + } else if (trackLegs.size() == 0) { return trackLegs.get(0).computeExtent(globe, verticalExaggeration); - } - else - { + } else { ArrayList extents = new ArrayList(); - for (Box leg : trackLegs) - { + for (Box leg : trackLegs) { extents.add(leg.computeExtent(globe, verticalExaggeration)); } @@ -336,40 +290,33 @@ else if (trackLegs.size() == 0) } @Override - protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) - { + protected List computeMinimalGeometry(Globe globe, double verticalExaggeration) { return null; // Track is a geometry container, and therefore has no geometry itself. } @Override - protected void invalidateAirspaceData() - { + protected void invalidateAirspaceData() { super.invalidateAirspaceData(); - for (Box leg : this.legs) - { + for (Box leg : this.legs) { leg.invalidateAirspaceData(); } } - protected void doMoveTo(Globe globe, Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Globe globe, Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Don't call super.moveTo(). Each box should move itself according to the properties it was constructed with. - for (Box box : this.legs) - { + for (Box box : this.legs) { box.doMoveTo(globe, oldRef, newRef); } @@ -377,24 +324,20 @@ protected void doMoveTo(Globe globe, Position oldRef, Position newRef) this.setLegsOutOfDate(true); } - protected void doMoveTo(Position oldRef, Position newRef) - { - if (oldRef == null) - { + protected void doMoveTo(Position oldRef, Position newRef) { + if (oldRef == null) { String message = "nullValue.OldRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (newRef == null) - { + if (newRef == null) { String message = "nullValue.NewRefIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Don't call super.moveTo(). Each box should move itself according to the properties it was constructed with. - for (Box box : this.legs) - { + for (Box box : this.legs) { box.doMoveTo(oldRef, newRef); } @@ -402,24 +345,22 @@ protected void doMoveTo(Position oldRef, Position newRef) this.setLegsOutOfDate(true); } - protected boolean isLegsOutOfDate() - { + protected boolean isLegsOutOfDate() { return this.legsOutOfDate; } - protected void setLegsOutOfDate(boolean tf) - { + protected void setLegsOutOfDate(boolean tf) { this.legsOutOfDate = tf; } - protected void doUpdateLegs() - { + protected void doUpdateLegs() { // Assign the standard corner azimuths to each box and enable the starting and ending caps. We start by assuming // that each leg is independent, then join adjacent legs to give the appearance of a continuous track. - for (Box leg : this.legs) - { + for (Box leg : this.legs) { if (leg == null) // This should never happen, but we check anyway. + { continue; + } leg.setEnableCaps(true); leg.setEnableDepthOffset(this.isEnableDepthOffset()); @@ -430,18 +371,18 @@ protected void doUpdateLegs() // appearance of a continuous track. This loop never executes if the list of legs has less than two elements. // Each iteration works on the adjacent vertices of the current leg and the next leg. Therefore this does not // modify the starting corner azimuths of the first leg, or the ending corner azimuths of the last leg. - for (int i = 0; i < this.legs.size() - 1; i++) - { + for (int i = 0; i < this.legs.size() - 1; i++) { Box leg = this.legs.get(i); Box nextLeg = this.legs.get(i + 1); if (leg == null || nextLeg == null) // This should never happen, but we check anyway. + { continue; + } // If the two legs have equivalent locations, altitude, and altitude mode where they meet, then adjust each // leg's corner azimuths so the two legs appear to make a continuous shape. - if (this.mustJoinLegs(leg, nextLeg)) - { + if (this.mustJoinLegs(leg, nextLeg)) { this.joinLegs(leg, nextLeg); } } @@ -461,11 +402,10 @@ protected void doUpdateLegs() * * @return true if the legs must be joined, otherwise false. */ - protected boolean mustJoinLegs(Box leg1, Box leg2) - { + protected boolean mustJoinLegs(Box leg1, Box leg2) { return leg1.getLocations()[1].equals(leg2.getLocations()[0]) // leg1 end == leg2 begin - && Arrays.equals(leg1.getAltitudes(), leg2.getAltitudes()) - && Arrays.equals(leg1.isTerrainConforming(), leg2.isTerrainConforming()); + && Arrays.equals(leg1.getAltitudes(), leg2.getAltitudes()) + && Arrays.equals(leg1.isTerrainConforming(), leg2.isTerrainConforming()); } /** @@ -476,11 +416,10 @@ protected boolean mustJoinLegs(Box leg1, Box leg2) *

          * This has no effect if the legs cannot be joined for any reason. * - * @param leg1 the first leg. - * @param leg2 the second leg. + * @param leg1 the first leg. + * @param leg2 the second leg. */ - protected void joinLegs(Box leg1, Box leg2) - { + protected void joinLegs(Box leg1, Box leg2) { LatLon[] locations1 = leg1.getLocations(); LatLon[] locations2 = leg2.getLocations(); Angle[] azimuths1 = leg1.getCornerAzimuths(); @@ -504,15 +443,13 @@ protected void joinLegs(Box leg1, Box leg2) leg2.setEnableStartCap(widthsDifferent || this.isEnableInnerCaps()); leg1.setCornerAzimuths(azimuths1[0], azimuths1[1], leftAzimuth, rightAzimuth); // end of first leg leg2.setCornerAzimuths(leftAzimuth, rightAzimuth, azimuths2[2], azimuths2[3]); // begin of second leg - } - else if (isLeftTurn) // left turn; align only the left side + } else if (isLeftTurn) // left turn; align only the left side { leg1.setEnableEndCap(true); leg2.setEnableStartCap(true); leg1.setCornerAzimuths(azimuths1[0], azimuths1[1], shortAngle, azimuths1[3]); // end left of first leg leg2.setCornerAzimuths(shortAngle, azimuths2[1], azimuths2[2], azimuths2[3]); // begin left of second leg - } - else // right turn; align only the right side + } else // right turn; align only the right side { leg1.setEnableEndCap(true); leg2.setEnableStartCap(true); @@ -524,31 +461,27 @@ protected void joinLegs(Box leg1, Box leg2) //**************************************************************// //******************** Geometry Rendering ********************// //**************************************************************// - @Override - public void preRender(DrawContext dc) - { - if (dc == null) - { + public void preRender(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } this.determineActiveAttributes(dc); // Update the child leg vertices if they're out of date. Since the leg vertices are used to determine how each // leg is shaped with respect to its neighbors, the vertices must be current before rendering each leg. - if (this.isLegsOutOfDate()) - { + if (this.isLegsOutOfDate()) { this.doUpdateLegs(); } - for (Box leg : this.legs) - { + for (Box leg : this.legs) { // Synchronize the leg's attributes with this track's attributes, and setup this track as the leg's pick // delegate. leg.setAttributes(this.getActiveAttributes()); @@ -558,40 +491,36 @@ public void preRender(DrawContext dc) } @Override - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } - if (!this.isAirspaceVisible(dc)) + if (!this.isAirspaceVisible(dc)) { return; + } - for (Box leg : this.legs) - { + for (Box leg : this.legs) { leg.render(dc); } } @Override - protected void doRenderGeometry(DrawContext dc, String drawStyle) - { + protected void doRenderGeometry(DrawContext dc, String drawStyle) { // Intentionally left blank. } //**************************************************************// //******************** END Geometry Rendering ****************// //**************************************************************// - @Override - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); rs.addStateValueAsBoolean(context, "enableInnerCaps", this.isEnableInnerCaps()); @@ -599,44 +528,45 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsDouble(context, "smallAngleThresholdDegrees", this.getSmallAngleThreshold().degrees); RestorableSupport.StateObject so = rs.addStateObject(context, "legs"); - for (Box leg : this.legs) - { + for (Box leg : this.legs) { RestorableSupport.StateObject lso = rs.addStateObject(so, "leg"); leg.doGetRestorableState(rs, lso); } } @Override - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doRestoreState(rs, context); Boolean b = rs.getStateValueAsBoolean(context, "enableInnerCaps"); - if (b != null) + if (b != null) { this.setEnableInnerCaps(b); + } b = rs.getStateValueAsBoolean(context, "enableCenterLine"); - if (b != null) + if (b != null) { this.setEnableCenterLine(b); + } Double d = rs.getStateValueAsDouble(context, "smallAngleThresholdDegrees"); - if (d != null) + if (d != null) { this.setSmallAngleThreshold(Angle.fromDegrees(d)); + } RestorableSupport.StateObject so = rs.getStateObject(context, "legs"); - if (so == null) + if (so == null) { return; + } RestorableSupport.StateObject[] lsos = rs.getAllStateObjects(so, "leg"); - if (lsos == null || lsos.length == 0) + if (lsos == null || lsos.length == 0) { return; + } ArrayList legList = new ArrayList(lsos.length); - for (RestorableSupport.StateObject lso : lsos) - { - if (lso != null) - { + for (RestorableSupport.StateObject lso : lsos) { + if (lso != null) { Box leg = new Box(); leg.doRestoreState(rs, lso); legList.add(leg); diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/AbstractAirspaceEditor.java b/src/gov/nasa/worldwind/render/airspaces/editor/AbstractAirspaceEditor.java index d82660773a..19713668ef 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/AbstractAirspaceEditor.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/AbstractAirspaceEditor.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: AbstractAirspaceEditor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractAirspaceEditor extends AbstractLayer implements AirspaceEditor -{ +public abstract class AbstractAirspaceEditor extends AbstractLayer implements AirspaceEditor { + private boolean armed; private boolean useRubberBand; private boolean keepControlPointsAboveTerrain; @@ -35,10 +35,8 @@ public abstract class AbstractAirspaceEditor extends AbstractLayer implements Ai protected static final int LOWER_ALTITUDE = AirspaceEditorUtil.LOWER_ALTITUDE; protected static final int UPPER_ALTITUDE = AirspaceEditorUtil.UPPER_ALTITUDE; - public AbstractAirspaceEditor(AirspaceControlPointRenderer renderer) - { - if (renderer == null) - { + public AbstractAirspaceEditor(AirspaceControlPointRenderer renderer) { + if (renderer == null) { String message = Logging.getMessage("nullValue.RendererIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -50,50 +48,40 @@ public AbstractAirspaceEditor(AirspaceControlPointRenderer renderer) this.controlPointRenderer = renderer; } - public AbstractAirspaceEditor() - { + public AbstractAirspaceEditor() { this(new BasicAirspaceControlPointRenderer()); } - public boolean isArmed() - { + public boolean isArmed() { return this.armed; } - public void setArmed(boolean armed) - { + public void setArmed(boolean armed) { this.armed = armed; } - public boolean isUseRubberBand() - { + public boolean isUseRubberBand() { return this.useRubberBand; } - public void setUseRubberBand(boolean state) - { + public void setUseRubberBand(boolean state) { this.useRubberBand = state; } - public boolean isKeepControlPointsAboveTerrain() - { + public boolean isKeepControlPointsAboveTerrain() { return this.keepControlPointsAboveTerrain; } - public void setKeepControlPointsAboveTerrain(boolean state) - { + public void setKeepControlPointsAboveTerrain(boolean state) { this.keepControlPointsAboveTerrain = state; } - public AirspaceControlPointRenderer getControlPointRenderer() - { + public AirspaceControlPointRenderer getControlPointRenderer() { return this.controlPointRenderer; } - public void setControlPointRenderer(AirspaceControlPointRenderer renderer) - { - if (renderer == null) - { + public void setControlPointRenderer(AirspaceControlPointRenderer renderer) { + if (renderer == null) { String message = Logging.getMessage("nullValue.RendererIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -102,70 +90,59 @@ public void setControlPointRenderer(AirspaceControlPointRenderer renderer) this.controlPointRenderer = renderer; } - public AirspaceEditListener[] getEditListeners() - { + public AirspaceEditListener[] getEditListeners() { return this.eventListeners.getListeners(AirspaceEditListener.class); } - public void addEditListener(AirspaceEditListener listener) - { + public void addEditListener(AirspaceEditListener listener) { this.eventListeners.add(AirspaceEditListener.class, listener); } - public void removeEditListener(AirspaceEditListener listener) - { + public void removeEditListener(AirspaceEditListener listener) { this.eventListeners.remove(AirspaceEditListener.class, listener); } //**************************************************************// //******************** Control Point Rendering ***************// //**************************************************************// - - protected void doRender(DrawContext dc) - { - if (!this.isArmed()) + protected void doRender(DrawContext dc) { + if (!this.isArmed()) { return; + } this.draw(dc, null); } - protected void doPick(DrawContext dc, Point point) - { - if (!this.isArmed()) + protected void doPick(DrawContext dc, Point point) { + if (!this.isArmed()) { return; + } this.draw(dc, point); } - protected void draw(DrawContext dc, Point pickPoint) - { + protected void draw(DrawContext dc, Point pickPoint) { this.getCurrentControlPoints().clear(); this.assembleControlPoints(dc); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.getControlPointRenderer().pick(dc, this.getCurrentControlPoints(), pickPoint, this); - } - else - { + } else { this.getControlPointRenderer().render(dc, this.getCurrentControlPoints()); } } - protected java.util.List getCurrentControlPoints() - { + protected java.util.List getCurrentControlPoints() { return this.currentControlPoints; } - protected void setCurrentControlPoints(java.util.List controlPointList) - { + protected void setCurrentControlPoints(java.util.List controlPointList) { this.currentControlPoints.clear(); this.currentControlPoints.addAll(controlPointList); } @SuppressWarnings({"UnusedDeclaration"}) - protected void addControlPoint(DrawContext dc, AirspaceControlPoint controlPoint) - { + protected void addControlPoint(DrawContext dc, AirspaceControlPoint controlPoint) { this.currentControlPoints.add(controlPoint); } @@ -174,13 +151,10 @@ protected void addControlPoint(DrawContext dc, AirspaceControlPoint controlPoint //**************************************************************// //******************** Control Point Events ******************// //**************************************************************// - public void moveAirspaceLaterally(WorldWindow wwd, Airspace airspace, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Include this test to ensure any derived implementation performs it. - if (this.getAirspace() == null || this.getAirspace() != airspace) - { + if (this.getAirspace() == null || this.getAirspace() != airspace) { return; } @@ -188,11 +162,9 @@ public void moveAirspaceLaterally(WorldWindow wwd, Airspace airspace, } public void moveAirspaceVertically(WorldWindow wwd, Airspace airspace, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Include this test to ensure any derived implementation performs it. - if (this.getAirspace() == null || this.getAirspace() != airspace) - { + if (this.getAirspace() == null || this.getAirspace() != airspace) { return; } @@ -200,37 +172,30 @@ public void moveAirspaceVertically(WorldWindow wwd, Airspace airspace, } public AirspaceControlPoint addControlPoint(WorldWindow wwd, Airspace airspace, - Point mousePoint) - { + Point mousePoint) { // Include this test to ensure any derived implementation performs it. - if (this.getAirspace() == null || this.getAirspace() != airspace) - { + if (this.getAirspace() == null || this.getAirspace() != airspace) { return null; } - if (wwd == null || mousePoint == null) - { + if (wwd == null || mousePoint == null) { return null; } return this.doAddControlPoint(wwd, airspace, mousePoint); } - public void removeControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint) - { + public void removeControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint) { // Include this test to ensure any derived implementation performs it. - if (this.getAirspace() == null) - { + if (this.getAirspace() == null) { return; } - if (wwd == null || controlPoint == null) - { + if (wwd == null || controlPoint == null) { return; } - if (this != controlPoint.getEditor() || this.getAirspace() != controlPoint.getAirspace()) - { + if (this != controlPoint.getEditor() || this.getAirspace() != controlPoint.getAirspace()) { return; } @@ -238,16 +203,13 @@ public void removeControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoin } public void moveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Include this test to ensure any derived implementation performs it. - if (this.getAirspace() == null) - { + if (this.getAirspace() == null) { return; } - if (this != controlPoint.getEditor() || this.getAirspace() != controlPoint.getAirspace()) - { + if (this != controlPoint.getEditor() || this.getAirspace() != controlPoint.getAirspace()) { return; } @@ -255,102 +217,86 @@ public void moveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, } public void resizeAtControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Include this test to ensure any derived implementation performs it. - if (this.getAirspace() == null) - { + if (this.getAirspace() == null) { return; } - if (this != controlPoint.getEditor() || this.getAirspace() != controlPoint.getAirspace()) - { + if (this != controlPoint.getEditor() || this.getAirspace() != controlPoint.getAirspace()) { return; } this.doResizeAtControlPoint(wwd, controlPoint, mousePoint, previousMousePoint); } - protected void fireAirspaceMoved(AirspaceEditEvent e) - { + protected void fireAirspaceMoved(AirspaceEditEvent e) { // Iterate over the listener list in reverse order. This has the effect of notifying the listeners in the // order they were added. AirspaceEditListener[] listeners = this.eventListeners.getListeners(AirspaceEditListener.class); - for (int i = listeners.length - 1; i >= 0; i--) - { + for (int i = listeners.length - 1; i >= 0; i--) { listeners[i].airspaceMoved(e); } } - protected void fireAirspaceResized(AirspaceEditEvent e) - { + protected void fireAirspaceResized(AirspaceEditEvent e) { // Iterate over the listener list in reverse order. This has the effect of notifying the listeners in the // order they were added. AirspaceEditListener[] listeners = this.eventListeners.getListeners(AirspaceEditListener.class); - for (int i = listeners.length - 1; i >= 0; i--) - { + for (int i = listeners.length - 1; i >= 0; i--) { listeners[i].airspaceResized(e); } } - protected void fireControlPointAdded(AirspaceEditEvent e) - { + protected void fireControlPointAdded(AirspaceEditEvent e) { // Iterate over the listener list in reverse order. This has the effect of notifying the listeners in the // order they were added. AirspaceEditListener[] listeners = this.eventListeners.getListeners(AirspaceEditListener.class); - for (int i = listeners.length - 1; i >= 0; i--) - { + for (int i = listeners.length - 1; i >= 0; i--) { listeners[i].controlPointAdded(e); } } - protected void fireControlPointRemoved(AirspaceEditEvent e) - { + protected void fireControlPointRemoved(AirspaceEditEvent e) { // Iterate over the listener list in reverse order. This has the effect of notifying the listeners in the // order they were added. AirspaceEditListener[] listeners = this.eventListeners.getListeners(AirspaceEditListener.class); - for (int i = listeners.length - 1; i >= 0; i--) - { + for (int i = listeners.length - 1; i >= 0; i--) { listeners[i].controlPointRemoved(e); } } - protected void fireControlPointChanged(AirspaceEditEvent e) - { + protected void fireControlPointChanged(AirspaceEditEvent e) { // Iterate over the listener list in reverse order. This has the effect of notifying the listeners in the // order they were added. AirspaceEditListener[] listeners = this.eventListeners.getListeners(AirspaceEditListener.class); - for (int i = listeners.length - 1; i >= 0; i--) - { + for (int i = listeners.length - 1; i >= 0; i--) { listeners[i].controlPointChanged(e); } } protected abstract AirspaceControlPoint doAddControlPoint(WorldWindow wwd, Airspace airspace, - Point mousePoint); + Point mousePoint); protected abstract void doRemoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint); protected abstract void doMoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint); + Point mousePoint, Point previousMousePoint); protected abstract void doResizeAtControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint); + Point mousePoint, Point previousMousePoint); //**************************************************************// //******************** Default Event Handling ****************// //**************************************************************// - protected void doMoveAirspaceLaterally(WorldWindow wwd, Airspace airspace, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Intersect a ray throuh each mouse point, with a geoid passing through the reference elevation. Since // most airspace control points follow a fixed altitude, this will track close to the intended mouse position. // If either ray fails to intersect the geoid, then ignore this event. Use the difference between the two // intersected positions to move the control point's location. - if (!(airspace instanceof Movable)) - { + if (!(airspace instanceof Movable)) { return; } @@ -359,16 +305,19 @@ protected void doMoveAirspaceLaterally(WorldWindow wwd, Airspace airspace, Globe globe = wwd.getModel().getGlobe(); Position refPos = movable.getReferencePosition(); - if (refPos == null) + if (refPos == null) { return; + } // Convert the reference position into a cartesian point. This assumes that the reference elevation is defined // by the airspace's lower altitude. Vec4 refPoint = null; - if (airspace.isTerrainConforming()[LOWER_ALTITUDE]) + if (airspace.isTerrainConforming()[LOWER_ALTITUDE]) { refPoint = wwd.getSceneController().getTerrain().getSurfacePoint(refPos); - if (refPoint == null) + } + if (refPoint == null) { refPoint = globe.computePointFromPosition(refPos); + } // Convert back to a position. refPos = globe.computePositionFromPoint(refPoint); @@ -379,8 +328,7 @@ protected void doMoveAirspaceLaterally(WorldWindow wwd, Airspace airspace, Vec4 vec = AirspaceEditorUtil.intersectGlobeAt(wwd, refPos.getElevation(), ray); Vec4 previousVec = AirspaceEditorUtil.intersectGlobeAt(wwd, refPos.getElevation(), previousRay); - if (vec == null || previousVec == null) - { + if (vec == null || previousVec == null) { return; } @@ -394,8 +342,7 @@ protected void doMoveAirspaceLaterally(WorldWindow wwd, Airspace airspace, } protected void doMoveAirspaceVertically(WorldWindow wwd, Airspace airspace, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Find the closest points between the rays through each screen point, and the ray from the control point // and in the direction of the globe's surface normal. Compute the elevation difference between these two // points, and use that as the change in airspace altitude. @@ -403,20 +350,20 @@ protected void doMoveAirspaceVertically(WorldWindow wwd, Airspace airspace, // If the state keepControlPointsAboveTerrain is set, we prevent the control point from passing any lower than // the terrain elevation beneath it. - if (!(airspace instanceof Movable)) - { + if (!(airspace instanceof Movable)) { return; } Movable movable = (Movable) airspace; Position referencePos = movable.getReferencePosition(); - if (referencePos == null) + if (referencePos == null) { return; + } Vec4 referencePoint = wwd.getModel().getGlobe().computePointFromPosition(referencePos); Vec4 surfaceNormal = wwd.getModel().getGlobe().computeSurfaceNormalAtLocation(referencePos.getLatitude(), - referencePos.getLongitude()); + referencePos.getLongitude()); Line verticalRay = new Line(referencePoint, surfaceNormal); Line screenRay = wwd.getView().computeRayFromScreenPoint(previousMousePoint.getX(), previousMousePoint.getY()); Line previousScreenRay = wwd.getView().computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); @@ -431,19 +378,15 @@ protected void doMoveAirspaceVertically(WorldWindow wwd, Airspace airspace, double[] altitudes = this.getAirspace().getAltitudes(); boolean[] terrainConformance = this.getAirspace().isTerrainConforming(); - if (this.isKeepControlPointsAboveTerrain()) - { - if (terrainConformance[LOWER_ALTITUDE]) - { - if (altitudes[LOWER_ALTITUDE] + elevationChange < 0.0) + if (this.isKeepControlPointsAboveTerrain()) { + if (terrainConformance[LOWER_ALTITUDE]) { + if (altitudes[LOWER_ALTITUDE] + elevationChange < 0.0) { elevationChange = 0.0 - altitudes[LOWER_ALTITUDE]; - } - else - { + } + } else { double height = AirspaceEditorUtil.computeLowestHeightAboveSurface( - wwd, this.getCurrentControlPoints(), LOWER_ALTITUDE); - if (elevationChange <= -height) - { + wwd, this.getCurrentControlPoints(), LOWER_ALTITUDE); + if (elevationChange <= -height) { elevationChange = -height; } } diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceControlPoint.java b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceControlPoint.java index 7d97f80b5f..b0d4264035 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceControlPoint.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceControlPoint.java @@ -12,8 +12,8 @@ * @author dcollins * @version $Id: AirspaceControlPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AirspaceControlPoint -{ +public interface AirspaceControlPoint { + AirspaceEditor getEditor(); Airspace getAirspace(); diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceControlPointRenderer.java b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceControlPointRenderer.java index 4715e7803c..54156e6d72 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceControlPointRenderer.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceControlPointRenderer.java @@ -14,8 +14,8 @@ * @author dcollins * @version $Id: AirspaceControlPointRenderer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AirspaceControlPointRenderer -{ +public interface AirspaceControlPointRenderer { + void render(DrawContext dc, Iterable controlPoints); void pick(DrawContext dc, Iterable controlPoints, Point pickPoint, Layer layer); diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditEvent.java b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditEvent.java index 1eedcc2189..8b27322193 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditEvent.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditEvent.java @@ -13,37 +13,32 @@ * @author dcollins * @version $Id: AirspaceEditEvent.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AirspaceEditEvent extends EventObject -{ +public class AirspaceEditEvent extends EventObject { + private Airspace airspace; private AirspaceEditor editor; private AirspaceControlPoint controlPoint; - public AirspaceEditEvent(Object source, Airspace airspace, AirspaceEditor editor, AirspaceControlPoint controlPoint) - { + public AirspaceEditEvent(Object source, Airspace airspace, AirspaceEditor editor, AirspaceControlPoint controlPoint) { super(source); this.airspace = airspace; this.editor = editor; this.controlPoint = controlPoint; } - public AirspaceEditEvent(Object source, Airspace airspace, AirspaceEditor editor) - { + public AirspaceEditEvent(Object source, Airspace airspace, AirspaceEditor editor) { this(source, airspace, editor, null); } - public Airspace getAirspace() - { + public Airspace getAirspace() { return this.airspace; } - public AirspaceEditor getEditor() - { + public AirspaceEditor getEditor() { return this.editor; } - public AirspaceControlPoint getControlPoint() - { + public AirspaceControlPoint getControlPoint() { return this.controlPoint; } } diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditListener.java b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditListener.java index eabb84b598..479b6ee7bd 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditListener.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditListener.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: AirspaceEditListener.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AirspaceEditListener extends EventListener -{ +public interface AirspaceEditListener extends EventListener { + void airspaceMoved(AirspaceEditEvent e); void airspaceResized(AirspaceEditEvent e); diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditor.java b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditor.java index e7c1003c66..a592e34a2b 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditor.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditor.java @@ -15,8 +15,8 @@ * @author dcollins * @version $Id: AirspaceEditor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AirspaceEditor extends Layer -{ +public interface AirspaceEditor extends Layer { + Airspace getAirspace(); boolean isArmed(); @@ -49,21 +49,20 @@ public interface AirspaceEditor extends Layer // 2. they do not allow the editor any control over how to respond to input // // 3. they assume the editor can do something reasonable with the call - void moveAirspaceLaterally(WorldWindow wwd, Airspace airspace, - Point mousePoint, Point previousMousePoint); + Point mousePoint, Point previousMousePoint); void moveAirspaceVertically(WorldWindow wwd, Airspace airspace, - Point mousePoint, Point previousMousePoint); + Point mousePoint, Point previousMousePoint); - AirspaceControlPoint addControlPoint(WorldWindow wwd, Airspace airspace, - Point mousePoint); + AirspaceControlPoint addControlPoint(WorldWindow wwd, Airspace airspace, + Point mousePoint); void removeControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint); void moveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint); + Point mousePoint, Point previousMousePoint); void resizeAtControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint); + Point mousePoint, Point previousMousePoint); } diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditorController.java b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditorController.java index e5ae425c1c..315e3fd36a 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditorController.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditorController.java @@ -17,8 +17,8 @@ * @author dcollins * @version $Id: AirspaceEditorController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AirspaceEditorController implements KeyListener, MouseListener, MouseMotionListener -{ +public class AirspaceEditorController implements KeyListener, MouseListener, MouseMotionListener { + private boolean active; private String activeAction; private AirspaceEditor editor; // Can be null @@ -44,66 +44,54 @@ public class AirspaceEditorController implements KeyListener, MouseListener, Mou // 3. move control point // 4. resize // 5. move airspace - // TODO: allow the editor to define the action/behavior associated with a control point, so the correct cursor // will be displayed (or some future UI affordance). Currently the controller assumes that a control point implies // a move action. This really only affects the cursor display, since the editor ultimately decides what to do when // a control point is moved. - - public AirspaceEditorController(WorldWindow wwd) - { + public AirspaceEditorController(WorldWindow wwd) { this.active = false; this.setWorldWindow(wwd); this.setupActionCursorMap(); } - public AirspaceEditorController() - { + public AirspaceEditorController() { this(null); } - public boolean isActive() - { + public boolean isActive() { return this.active; } - protected void setActive(boolean active) - { + protected void setActive(boolean active) { this.active = active; } - public String getActiveAction() - { + public String getActiveAction() { return activeAction; } - protected void setActiveAction(String action) - { + protected void setActiveAction(String action) { this.activeAction = action; } - public AirspaceEditor getEditor() - { + public AirspaceEditor getEditor() { return this.editor; } - public void setEditor(AirspaceEditor editor) - { + public void setEditor(AirspaceEditor editor) { this.editor = editor; } - public WorldWindow getWorldWindow() - { + public WorldWindow getWorldWindow() { return this.wwd; } - public void setWorldWindow(WorldWindow wwd) - { - if (this.wwd == wwd) + public void setWorldWindow(WorldWindow wwd) { + if (this.wwd == wwd) { return; + } - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.getInputHandler().removeKeyListener(this); this.wwd.getInputHandler().removeMouseListener(this); this.wwd.getInputHandler().removeMouseMotionListener(this); @@ -111,73 +99,69 @@ public void setWorldWindow(WorldWindow wwd) this.wwd = wwd; - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.getInputHandler().addKeyListener(this); this.wwd.getInputHandler().addMouseListener(this); this.wwd.getInputHandler().addMouseMotionListener(this); } } - protected Point getMousePoint() - { + protected Point getMousePoint() { return this.mousePoint; } - protected void setMousePoint(Point point) - { + protected void setMousePoint(Point point) { this.mousePoint = point; } - protected AirspaceControlPoint getActiveControlPoint() - { + protected AirspaceControlPoint getActiveControlPoint() { return this.activeControlPoint; } - protected void setActiveControlPoint(AirspaceControlPoint controlPoint) - { + protected void setActiveControlPoint(AirspaceControlPoint controlPoint) { this.activeControlPoint = controlPoint; } - protected Airspace getActiveAirspace() - { + protected Airspace getActiveAirspace() { return activeAirspace; } - protected void setActiveAirspace(Airspace airspace) - { + protected void setActiveAirspace(Airspace airspace) { this.activeAirspace = airspace; } - protected Airspace getTopOwnedAirspaceAtCurrentPosition() - { + protected Airspace getTopOwnedAirspaceAtCurrentPosition() { // Without an editor, we cannot know if the airspace belongs to us. - if (this.getEditor() == null) + if (this.getEditor() == null) { return null; + } Object obj = this.getTopPickedObject(); // Airspace is compared by reference, because we're only concerned about the exact reference // an editor refers to, rather than an equivalent object. - if (this.getEditor().getAirspace() != obj) + if (this.getEditor().getAirspace() != obj) { return null; + } return (Airspace) obj; } - protected AirspaceControlPoint getTopOwnedControlPointAtCurrentPosition() - { + protected AirspaceControlPoint getTopOwnedControlPointAtCurrentPosition() { // Without an editor, we cannot know if the airspace belongs to us. - if (this.getEditor() == null) + if (this.getEditor() == null) { return null; + } Object obj = this.getTopPickedObject(); - if (!(obj instanceof AirspaceControlPoint)) + if (!(obj instanceof AirspaceControlPoint)) { return null; + } // AirspaceEditor is compared by reference, because we're only concerned about the exact reference // a control point refers to, rather than an equivalent object. - if (this.getEditor() != (((AirspaceControlPoint) obj).getEditor())) + if (this.getEditor() != (((AirspaceControlPoint) obj).getEditor())) { return null; + } return (AirspaceControlPoint) obj; } @@ -211,64 +195,53 @@ protected AirspaceControlPoint getTopOwnedControlPointAtCurrentPosition() // // return controlPoint; //} - - protected Object getTopPickedObject() - { - if (this.getWorldWindow() == null) + protected Object getTopPickedObject() { + if (this.getWorldWindow() == null) { return null; + } PickedObjectList pickedObjects = this.getWorldWindow().getObjectsAtCurrentPosition(); if (pickedObjects == null || pickedObjects.getTopPickedObject() == null - || pickedObjects.getTopPickedObject().isTerrain()) - { + || pickedObjects.getTopPickedObject().isTerrain()) { return null; } return pickedObjects.getTopPickedObject().getObject(); } - protected Map getActionCursorMap() - { + protected Map getActionCursorMap() { return this.actionCursorMap; } //**************************************************************// //******************** Key Events ****************************// //**************************************************************// - - public void keyTyped(KeyEvent e) - { + public void keyTyped(KeyEvent e) { } - public void keyPressed(KeyEvent e) - { - if (e == null) - { + public void keyPressed(KeyEvent e) { + if (e == null) { return; } this.updateCursor(e); // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { //noinspection UnnecessaryReturnStatement return; } } - public void keyReleased(KeyEvent e) - { - if (e == null) - { + public void keyReleased(KeyEvent e) { + if (e == null) { return; } this.updateCursor(e); - + // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { //noinspection UnnecessaryReturnStatement return; } @@ -277,30 +250,23 @@ public void keyReleased(KeyEvent e) //**************************************************************// //******************** Mouse Events **************************// //**************************************************************// - - public void mouseClicked(MouseEvent e) - { - if (e == null) - { + public void mouseClicked(MouseEvent e) { + if (e == null) { return; } this.updateCursor(e); // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return; } AirspaceControlPoint topControlPoint = this.getTopOwnedControlPointAtCurrentPosition(); - if (e.getButton() == MouseEvent.BUTTON1) - { - if (e.isControlDown()) - { - if (topControlPoint != null) - { + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + if (topControlPoint != null) { this.handleControlPointRemoved(topControlPoint, e); } e.consume(); @@ -314,10 +280,8 @@ public void mouseClicked(MouseEvent e) } } - public void mousePressed(MouseEvent e) - { - if (e == null) - { + public void mousePressed(MouseEvent e) { + if (e == null) { return; } @@ -325,49 +289,37 @@ public void mousePressed(MouseEvent e) this.updateCursor(e); // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return; } - Airspace topAirspace = this.getTopOwnedAirspaceAtCurrentPosition(); + Airspace topAirspace = this.getTopOwnedAirspaceAtCurrentPosition(); AirspaceControlPoint topControlPoint = this.getTopOwnedControlPointAtCurrentPosition(); - if (e.getButton() == MouseEvent.BUTTON1) - { - if (e.isControlDown()) - { + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { // Actual logic is handled in mouseClicked, but we consume the event here to keep the any other // system from receiving it. this.setActive(true); this.setActiveAction(REMOVE_CONTROL_POINT); e.consume(); - } - else if (e.isAltDown()) - { + } else if (e.isAltDown()) { this.setActive(true); this.setActiveAction(ADD_CONTROL_POINT); - if (topControlPoint == null) - { + if (topControlPoint == null) { AirspaceControlPoint p = this.handleControlPointAdded(this.getEditor().getAirspace(), e); - if (p != null) - { + if (p != null) { this.setActiveControlPoint(p); } - } + } e.consume(); - } - else - { - if (topControlPoint != null) - { + } else { + if (topControlPoint != null) { this.setActive(true); this.setActiveAction(null); // Don't know what action we'll perform until mouseDragged(). this.setActiveControlPoint(topControlPoint); e.consume(); - } - else if (topAirspace != null) - { + } else if (topAirspace != null) { this.setActive(true); this.setActiveAction(null); // Don't know what action we'll perform until mouseDragged(). this.setActiveAirspace(topAirspace); @@ -377,10 +329,8 @@ else if (topAirspace != null) } } - public void mouseReleased(MouseEvent e) - { - if (e == null) - { + public void mouseReleased(MouseEvent e) { + if (e == null) { return; } @@ -388,15 +338,12 @@ public void mouseReleased(MouseEvent e) this.updateCursor(e); // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return; } - if (e.getButton() == MouseEvent.BUTTON1) - { - if (this.isActive()) - { + if (e.getButton() == MouseEvent.BUTTON1) { + if (this.isActive()) { this.setActive(false); this.setActiveAction(null); this.setActiveAirspace(null); @@ -406,59 +353,48 @@ public void mouseReleased(MouseEvent e) } } - public void mouseEntered(MouseEvent e) - { - if (e == null) - { + public void mouseEntered(MouseEvent e) { + if (e == null) { return; } // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { //noinspection UnnecessaryReturnStatement return; } } - public void mouseExited(MouseEvent e) - { - if (e == null) - { + public void mouseExited(MouseEvent e) { + if (e == null) { return; } // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { //noinspection UnnecessaryReturnStatement return; } } - protected AirspaceControlPoint handleControlPointAdded(Airspace airspace, MouseEvent mouseEvent) - { + protected AirspaceControlPoint handleControlPointAdded(Airspace airspace, MouseEvent mouseEvent) { AirspaceControlPoint controlPoint = this.getEditor().addControlPoint(this.getWorldWindow(), airspace, - mouseEvent.getPoint()); + mouseEvent.getPoint()); this.getWorldWindow().redraw(); return controlPoint; } @SuppressWarnings({"UnusedDeclaration"}) - protected void handleControlPointRemoved(AirspaceControlPoint controlPoint, MouseEvent mouseEvent) - { + protected void handleControlPointRemoved(AirspaceControlPoint controlPoint, MouseEvent mouseEvent) { this.getEditor().removeControlPoint(this.getWorldWindow(), controlPoint); } //**************************************************************// //******************** Mouse Motion Events *******************// //**************************************************************// - - public void mouseDragged(MouseEvent e) - { - if (e == null) - { + public void mouseDragged(MouseEvent e) { + if (e == null) { return; } @@ -467,21 +403,15 @@ public void mouseDragged(MouseEvent e) this.updateCursor(e); // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return; } - - if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { - if (this.isActive()) - { - if (this.getActiveControlPoint() != null) - { + + if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { + if (this.isActive()) { + if (this.getActiveControlPoint() != null) { this.handleControlPointDragged(this.getActiveControlPoint(), e, lastMousePoint); - } - else if (this.getActiveAirspace() != null) - { + } else if (this.getActiveAirspace() != null) { this.handleAirspaceDragged(this.getActiveAirspace(), e, lastMousePoint); } e.consume(); @@ -489,10 +419,8 @@ else if (this.getActiveAirspace() != null) } } - public void mouseMoved(MouseEvent e) - { - if (e == null) - { + public void mouseMoved(MouseEvent e) { + if (e == null) { return; } @@ -500,36 +428,27 @@ public void mouseMoved(MouseEvent e) this.updateCursor(e); // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { //noinspection UnnecessaryReturnStatement return; } } - protected void handleControlPointDragged(AirspaceControlPoint controlPoint, MouseEvent e, Point lastMousePoint) - { - if (e.isShiftDown()) - { + protected void handleControlPointDragged(AirspaceControlPoint controlPoint, MouseEvent e, Point lastMousePoint) { + if (e.isShiftDown()) { this.setActiveAction(RESIZE_AIRSPACE); this.getEditor().resizeAtControlPoint(this.getWorldWindow(), controlPoint, e.getPoint(), lastMousePoint); - } - else - { + } else { this.setActiveAction(MOVE_CONTROL_POINT); this.getEditor().moveControlPoint(this.getWorldWindow(), controlPoint, e.getPoint(), lastMousePoint); } } - protected void handleAirspaceDragged(Airspace airspace, MouseEvent e, Point lastMousePoint) - { - if (e.isShiftDown()) - { + protected void handleAirspaceDragged(Airspace airspace, MouseEvent e, Point lastMousePoint) { + if (e.isShiftDown()) { this.setActiveAction(MOVE_AIRSPACE_VERTICALLY); this.getEditor().moveAirspaceVertically(this.getWorldWindow(), airspace, e.getPoint(), lastMousePoint); - } - else - { + } else { this.setActiveAction(MOVE_AIRSPACE_LATERALLY); this.getEditor().moveAirspaceLaterally(this.getWorldWindow(), airspace, e.getPoint(), lastMousePoint); } @@ -538,9 +457,7 @@ protected void handleAirspaceDragged(Airspace airspace, MouseEvent e, Point last //**************************************************************// //******************** Action/Cursor Pairing *****************// //**************************************************************// - - protected void setupActionCursorMap() - { + protected void setupActionCursorMap() { // TODO: find more suitable cursors for the remove control point action, and the move vertically action. this.getActionCursorMap().put(MOVE_AIRSPACE_LATERALLY, Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); this.getActionCursorMap().put(MOVE_AIRSPACE_VERTICALLY, Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); @@ -550,11 +467,9 @@ protected void setupActionCursorMap() this.getActionCursorMap().put(MOVE_CONTROL_POINT, Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } - protected void updateCursor(InputEvent e) - { + protected void updateCursor(InputEvent e) { // Include this test to ensure any derived implementation performs it. - if (e == null || e.getComponent() == null) - { + if (e == null || e.getComponent() == null) { return; } @@ -563,20 +478,17 @@ protected void updateCursor(InputEvent e) e.getComponent().repaint(); } - protected Cursor getCursorFor(InputEvent e) - { + protected Cursor getCursorFor(InputEvent e) { // If we're actively engaged in some action, then return the cursor associated with that action. Otherwise // return the cursor representing the action that would be invoked (if the user pressed the mouse) given the // current modifiers and pick list. - if (e == null) - { + if (e == null) { return null; } // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return null; } @@ -584,44 +496,28 @@ protected Cursor getCursorFor(InputEvent e) return this.getActionCursorMap().get(action); } - protected String getPotentialActionFor(InputEvent e) - { + protected String getPotentialActionFor(InputEvent e) { Airspace topAirspace = this.getTopOwnedAirspaceAtCurrentPosition(); AirspaceControlPoint topControlPoint = this.getTopOwnedControlPointAtCurrentPosition(); - if (e.isAltDown()) - { - if (topControlPoint == null) - { + if (e.isAltDown()) { + if (topControlPoint == null) { return ADD_CONTROL_POINT; } - } - else if (e.isControlDown()) - { - if (topControlPoint != null) - { + } else if (e.isControlDown()) { + if (topControlPoint != null) { return REMOVE_CONTROL_POINT; } - } - else if (e.isShiftDown()) - { - if (topControlPoint != null) - { + } else if (e.isShiftDown()) { + if (topControlPoint != null) { return RESIZE_AIRSPACE; - } - else if (topAirspace != null) - { + } else if (topAirspace != null) { return MOVE_AIRSPACE_VERTICALLY; } - } - else - { - if (topControlPoint != null) - { + } else { + if (topControlPoint != null) { return MOVE_CONTROL_POINT; - } - else if (topAirspace != null) - { + } else if (topAirspace != null) { return MOVE_AIRSPACE_LATERALLY; } } diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditorUtil.java b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditorUtil.java index 5f714207e6..71246ab2b4 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditorUtil.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/AirspaceEditorUtil.java @@ -15,8 +15,8 @@ * @author dcollins * @version $Id: AirspaceEditorUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AirspaceEditorUtil -{ +public class AirspaceEditorUtil { + // Airspace altitude constants. public static final int LOWER_ALTITUDE = 0; public static final int UPPER_ALTITUDE = 1; @@ -24,19 +24,14 @@ public class AirspaceEditorUtil //**************************************************************// //******************** Airspace/Control Point Utilities ******// //**************************************************************// - public static double computeLowestHeightAboveSurface(WorldWindow wwd, - Iterable controlPoints, int altitudeIndex) - { + Iterable controlPoints, int altitudeIndex) { double minHeight = Double.MAX_VALUE; - for (AirspaceControlPoint controlPoint : controlPoints) - { - if (altitudeIndex == controlPoint.getAltitudeIndex()) - { + for (AirspaceControlPoint controlPoint : controlPoints) { + if (altitudeIndex == controlPoint.getAltitudeIndex()) { double height = computeHeightAboveSurface(wwd, controlPoint.getPoint()); - if (height < minHeight) - { + if (height < minHeight) { minHeight = height; } } @@ -45,8 +40,7 @@ public static double computeLowestHeightAboveSurface(WorldWindow wwd, return minHeight; } - public static double computeHeightAboveSurface(WorldWindow wwd, Vec4 point) - { + public static double computeHeightAboveSurface(WorldWindow wwd, Vec4 point) { Position pos = wwd.getModel().getGlobe().computePositionFromPoint(point); Vec4 surfacePoint = computeSurfacePoint(wwd, pos.getLatitude(), pos.getLongitude()); Vec4 surfaceNormal = wwd.getModel().getGlobe().computeSurfaceNormalAtPoint(point); @@ -54,8 +48,7 @@ public static double computeHeightAboveSurface(WorldWindow wwd, Vec4 point) } public static double computeMinimumDistanceBetweenAltitudes(int numLocations, - Iterable controlPoints) - { + Iterable controlPoints) { // We cannot assume anything about the ordering of the control points handed to us, but we must be able to // access them by location index and altitude index. To achieve this we place them in a map that will be // indexable by location and altitude. @@ -63,24 +56,20 @@ public static double computeMinimumDistanceBetweenAltitudes(int numLocations, double minDistance = Double.MAX_VALUE; HashMap map = new HashMap(); - for (AirspaceControlPoint p : controlPoints) - { + for (AirspaceControlPoint p : controlPoints) { map.put(p.getKey(), p); } - for (int locationIndex = 0; locationIndex < numLocations; locationIndex++) - { + for (int locationIndex = 0; locationIndex < numLocations; locationIndex++) { Object lowerKey = BasicAirspaceControlPoint.keyFor(locationIndex, LOWER_ALTITUDE); Object upperKey = BasicAirspaceControlPoint.keyFor(locationIndex, UPPER_ALTITUDE); AirspaceControlPoint lowerControlPoint = map.get(lowerKey); AirspaceControlPoint upperControlPoint = map.get(upperKey); - if (lowerControlPoint != null && upperControlPoint != null) - { + if (lowerControlPoint != null && upperControlPoint != null) { double distance = lowerControlPoint.getPoint().distanceTo3(upperControlPoint.getPoint()); - if (distance < minDistance) - { + if (distance < minDistance) { minDistance = distance; } } @@ -92,17 +81,15 @@ public static double computeMinimumDistanceBetweenAltitudes(int numLocations, //**************************************************************// //******************** Control Point Edge ********************// //**************************************************************// + public static class EdgeInfo { - public static class EdgeInfo - { int locationIndex; int nextLocationIndex; int altitudeIndex; Vec4 point1; Vec4 point2; - public EdgeInfo(int locationIndex, int nextLocationIndex, int altitudeIndex, Vec4 point1, Vec4 point2) - { + public EdgeInfo(int locationIndex, int nextLocationIndex, int altitudeIndex, Vec4 point1, Vec4 point2) { this.locationIndex = locationIndex; this.nextLocationIndex = nextLocationIndex; this.altitudeIndex = altitudeIndex; @@ -112,8 +99,7 @@ public EdgeInfo(int locationIndex, int nextLocationIndex, int altitudeIndex, Vec } public static AirspaceControlPoint createControlPointFor(WorldWindow wwd, Line ray, - AirspaceEditor editor, Airspace airspace, EdgeInfo edge) - { + AirspaceEditor editor, Airspace airspace, EdgeInfo edge) { // If the nearest point occurs before the line segment, then insert the new point before the segment. If the // nearest point occurs after the line segment, then insert the new point after the segment. If the nearest // point occurs inside the line segment, then insert the new point in the segment. @@ -124,15 +110,11 @@ public static AirspaceControlPoint createControlPointFor(WorldWindow wwd, Line r int locationIndex; int altitudeIndex = edge.altitudeIndex; - if (pointOnEdge == edge.point1) - { + if (pointOnEdge == edge.point1) { locationIndex = edge.locationIndex; - } - else if (pointOnEdge == edge.point2) - { + } else if (pointOnEdge == edge.point2) { locationIndex = edge.nextLocationIndex + 1; - } - else // (o == Orientation.INSIDE) + } else // (o == Orientation.INSIDE) { locationIndex = edge.nextLocationIndex; } @@ -141,8 +123,7 @@ else if (pointOnEdge == edge.point2) } public static List computeEdgeInfoFor(int numLocations, - Iterable controlPoints) - { + Iterable controlPoints) { // Compute edge data structures for the segment between each successive pair of control points, including the // edge between the last and first control points. Do this for the upper and lower altitudes of the airspace. // We cannot assume anything about the ordering of the control points handed to us, but we must be able to @@ -152,15 +133,12 @@ public static List computeEdgeInfoFor(int numLocations, ArrayList edgeInfoList = new ArrayList(); HashMap map = new HashMap(); - for (AirspaceControlPoint p : controlPoints) - { + for (AirspaceControlPoint p : controlPoints) { map.put(p.getKey(), p); } - for (int altitudeIndex = 0; altitudeIndex < 2; altitudeIndex++) - { - for (int locationIndex = 0; locationIndex < numLocations; locationIndex++) - { + for (int altitudeIndex = 0; altitudeIndex < 2; altitudeIndex++) { + for (int locationIndex = 0; locationIndex < numLocations; locationIndex++) { int nextLocationIndex = (locationIndex < numLocations - 1) ? (locationIndex + 1) : 0; Object key = BasicAirspaceControlPoint.keyFor(locationIndex, altitudeIndex); Object nextKey = BasicAirspaceControlPoint.keyFor(nextLocationIndex, altitudeIndex); @@ -168,10 +146,9 @@ public static List computeEdgeInfoFor(int numLocations, AirspaceControlPoint controlPoint = map.get(key); AirspaceControlPoint nextControlPoint = map.get(nextKey); - if (controlPoint != null && nextControlPoint != null) - { + if (controlPoint != null && nextControlPoint != null) { edgeInfoList.add(new EdgeInfo(locationIndex, nextLocationIndex, altitudeIndex, - controlPoint.getPoint(), nextControlPoint.getPoint())); + controlPoint.getPoint(), nextControlPoint.getPoint())); } } } @@ -180,8 +157,7 @@ public static List computeEdgeInfoFor(int numLocations, } public static EdgeInfo selectBestEdgeMatch(WorldWindow wwd, Line ray, - Airspace airspace, List edgeInfoList) - { + Airspace airspace, List edgeInfoList) { // Try to find the edge that is closest to the given ray. This is used by the routine doAddNextLocation(), // which is trying to determine the user's intent as to which edge a new two control points should be added to. // Therefore consider the potential locations of a new control point on the ray: one for each of the lower @@ -195,16 +171,12 @@ public static EdgeInfo selectBestEdgeMatch(WorldWindow wwd, Line ray, EdgeInfo bestEdge = null; double nearestDistance = Double.MAX_VALUE; - for (EdgeInfo edge : edgeInfoList) - { - for (int index = 0; index < 2; index++) - { + for (EdgeInfo edge : edgeInfoList) { + for (int index = 0; index < 2; index++) { Vec4 pointOnEdge = nearestPointOnSegment(edge.point1, edge.point2, pointOnLine[index]); - if (!isPointBehindLineOrigin(ray, pointOnEdge)) - { + if (!isPointBehindLineOrigin(ray, pointOnEdge)) { double d = pointOnEdge.distanceTo3(pointOnLine[index]); - if (d < nearestDistance) - { + if (d < nearestDistance) { bestEdge = edge; nearestDistance = d; } @@ -218,20 +190,15 @@ public static EdgeInfo selectBestEdgeMatch(WorldWindow wwd, Line ray, //**************************************************************// //******************** Globe Utilities ***********************// //**************************************************************// - - public static Vec4 intersectAirspaceAltitudeAt(WorldWindow wwd, Airspace airspace, int altitudeIndex, Line ray) - { + public static Vec4 intersectAirspaceAltitudeAt(WorldWindow wwd, Airspace airspace, int altitudeIndex, Line ray) { double elevation = airspace.getAltitudes()[altitudeIndex]; boolean terrainConformant = airspace.isTerrainConforming()[altitudeIndex]; - if (terrainConformant) - { + if (terrainConformant) { Intersection[] intersections = wwd.getSceneController().getTerrain().intersect(ray); - if (intersections != null) - { + if (intersections != null) { Vec4 point = nearestIntersectionPoint(ray, intersections); - if (point != null) - { + if (point != null) { Position pos = wwd.getModel().getGlobe().computePositionFromPoint(point); elevation += pos.getElevation(); } @@ -241,31 +208,25 @@ public static Vec4 intersectAirspaceAltitudeAt(WorldWindow wwd, Airspace airspac return intersectGlobeAt(wwd, elevation, ray); } - public static Vec4 intersectGlobeAt(WorldWindow wwd, double elevation, Line ray) - { + public static Vec4 intersectGlobeAt(WorldWindow wwd, double elevation, Line ray) { Intersection[] intersections = wwd.getModel().getGlobe().intersect(ray, elevation); - if (intersections == null || intersections.length == 0) - { + if (intersections == null || intersections.length == 0) { return null; } return nearestIntersectionPoint(ray, intersections); } - public static double surfaceElevationAt(WorldWindow wwd, Line ray) - { + public static double surfaceElevationAt(WorldWindow wwd, Line ray) { // Try to find the surface elevation at the mouse point by intersecting a ray with the terrain. double surfaceElevation = 0.0; - if (wwd.getSceneController().getTerrain() != null) - { + if (wwd.getSceneController().getTerrain() != null) { Intersection[] intersections = wwd.getSceneController().getTerrain().intersect(ray); - if (intersections != null) - { + if (intersections != null) { Vec4 point = nearestIntersectionPoint(ray, intersections); - if (point != null) - { + if (point != null) { Position pos = wwd.getModel().getGlobe().computePositionFromPoint(point); surfaceElevation = pos.getElevation(); } @@ -275,11 +236,11 @@ public static double surfaceElevationAt(WorldWindow wwd, Line ray) return surfaceElevation; } - public static Vec4 computeSurfacePoint(WorldWindow wwd, Angle latitude, Angle longitude) - { + public static Vec4 computeSurfacePoint(WorldWindow wwd, Angle latitude, Angle longitude) { Vec4 point = wwd.getSceneController().getTerrain().getSurfacePoint(latitude, longitude); - if (point != null) + if (point != null) { return point; + } return wwd.getModel().getGlobe().computePointFromPosition(latitude, longitude, 0.0); } @@ -287,15 +248,12 @@ public static Vec4 computeSurfacePoint(WorldWindow wwd, Angle latitude, Angle lo //**************************************************************// //******************** Line Utilities ************************// //**************************************************************// - - public static boolean isPointBehindLineOrigin(Line line, Vec4 point) - { + public static boolean isPointBehindLineOrigin(Line line, Vec4 point) { double dot = point.subtract3(line.getOrigin()).dot3(line.getDirection()); return dot < 0.0; } - public static Vec4 nearestPointOnLine(Line source, Line target) - { + public static Vec4 nearestPointOnLine(Line source, Line target) { // Compute the points on each ray that are closest to one another. // Taken from "Mathematics for 3D Game Programming..." by Eric Lengyel, Section 4.1.2. @@ -308,40 +266,30 @@ public static Vec4 nearestPointOnLine(Line source, Line target) return source.getPointAt(t1); } - public static Vec4 nearestPointOnSegment(Vec4 p1, Vec4 p2, Vec4 point) - { + public static Vec4 nearestPointOnSegment(Vec4 p1, Vec4 p2, Vec4 point) { Vec4 segment = p2.subtract3(p1); Vec4 dir = segment.normalize3(); double dot = point.subtract3(p1).dot3(dir); - if (dot < 0.0) - { + if (dot < 0.0) { return p1; - } - else if (dot > segment.getLength3()) - { + } else if (dot > segment.getLength3()) { return p2; - } - else - { + } else { return Vec4.fromLine3(p1, dot, dir); } } - public static Vec4 nearestIntersectionPoint(Line line, Intersection[] intersections) - { + public static Vec4 nearestIntersectionPoint(Line line, Intersection[] intersections) { Vec4 intersectionPoint = null; // Find the nearest intersection that's in front of the ray origin. double nearestDistance = Double.MAX_VALUE; - for (Intersection intersection : intersections) - { + for (Intersection intersection : intersections) { // Ignore any intersections behind the line origin. - if (!isPointBehindLineOrigin(line, intersection.getIntersectionPoint())) - { + if (!isPointBehindLineOrigin(line, intersection.getIntersectionPoint())) { double d = intersection.getIntersectionPoint().distanceTo3(line.getOrigin()); - if (d < nearestDistance) - { + if (d < nearestDistance) { intersectionPoint = intersection.getIntersectionPoint(); nearestDistance = d; } diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/BasicAirspaceControlPoint.java b/src/gov/nasa/worldwind/render/airspaces/editor/BasicAirspaceControlPoint.java index cbff71e699..9326d30ca5 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/BasicAirspaceControlPoint.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/BasicAirspaceControlPoint.java @@ -12,42 +12,39 @@ * @author dcollins * @version $Id: BasicAirspaceControlPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicAirspaceControlPoint implements AirspaceControlPoint -{ - public static class BasicControlPointKey - { +public class BasicAirspaceControlPoint implements AirspaceControlPoint { + + public static class BasicControlPointKey { + private int locationIndex; private int altitudeIndex; - public BasicControlPointKey(int locationIndex, int altitudeIndex) - { + public BasicControlPointKey(int locationIndex, int altitudeIndex) { this.locationIndex = locationIndex; this.altitudeIndex = altitudeIndex; } - public int getLocationIndex() - { + public int getLocationIndex() { return this.locationIndex; } - public int getAltitudeIndex() - { + public int getAltitudeIndex() { return this.altitudeIndex; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } BasicControlPointKey that = (BasicControlPointKey) o; return (this.locationIndex == that.locationIndex) && (this.altitudeIndex == that.altitudeIndex); } - public int hashCode() - { + public int hashCode() { int result = this.locationIndex; result = 31 * result + this.altitudeIndex; return result; @@ -61,8 +58,7 @@ public int hashCode() private Vec4 point; public BasicAirspaceControlPoint(AirspaceEditor editor, Airspace airspace, int locationIndex, int altitudeIndex, - Vec4 point) - { + Vec4 point) { this.editor = editor; this.airspace = airspace; this.locationIndex = locationIndex; @@ -70,74 +66,71 @@ public BasicAirspaceControlPoint(AirspaceEditor editor, Airspace airspace, int l this.point = point; } - public BasicAirspaceControlPoint(AirspaceEditor editor, Airspace airspace, Vec4 point) - { + public BasicAirspaceControlPoint(AirspaceEditor editor, Airspace airspace, Vec4 point) { this(editor, airspace, -1, -1, point); } - public AirspaceEditor getEditor() - { + public AirspaceEditor getEditor() { return this.editor; } - public Airspace getAirspace() - { + public Airspace getAirspace() { return this.airspace; } - public int getLocationIndex() - { + public int getLocationIndex() { return this.locationIndex; } - public int getAltitudeIndex() - { + public int getAltitudeIndex() { return this.altitudeIndex; } - public Vec4 getPoint() - { + public Vec4 getPoint() { return this.point; } - public Object getKey() - { + public Object getKey() { return keyFor(this.locationIndex, this.altitudeIndex); } - public static Object keyFor(int locationIndex, int altitudeIndex) - { - return new BasicControlPointKey(locationIndex, altitudeIndex); + public static Object keyFor(int locationIndex, int altitudeIndex) { + return new BasicControlPointKey(locationIndex, altitudeIndex); } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } BasicAirspaceControlPoint that = (BasicAirspaceControlPoint) o; // Editor and airspace are compared by references, because we're only concerned about the exact reference // a control point refers to, rather than an equivalent object. - if (this.editor != that.editor) + if (this.editor != that.editor) { return false; - if (this.airspace != that.airspace) + } + if (this.airspace != that.airspace) { return false; - if (this.altitudeIndex != that.altitudeIndex) + } + if (this.altitudeIndex != that.altitudeIndex) { return false; - if (this.locationIndex != that.locationIndex) + } + if (this.locationIndex != that.locationIndex) { return false; + } //noinspection RedundantIfStatement - if (this.point != null ? !this.point.equals(that.point) : that.point != null) + if (this.point != null ? !this.point.equals(that.point) : that.point != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result = this.editor != null ? this.editor.hashCode() : 0; result = 31 * result + (this.airspace != null ? this.airspace.hashCode() : 0); result = 31 * result + this.locationIndex; diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/BasicAirspaceControlPointRenderer.java b/src/gov/nasa/worldwind/render/airspaces/editor/BasicAirspaceControlPointRenderer.java index 7c5a8bc028..0d567f5246 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/BasicAirspaceControlPointRenderer.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/BasicAirspaceControlPointRenderer.java @@ -20,13 +20,12 @@ // integrated into MarkerRenderer. There are two key pieces of additional functionality: // (1) an attribute representing the maximum marker size, and // (2) the ability to disable the depth test. - /** * @author dcollins * @version $Id: BasicAirspaceControlPointRenderer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicAirspaceControlPointRenderer implements AirspaceControlPointRenderer -{ +public class BasicAirspaceControlPointRenderer implements AirspaceControlPointRenderer { + private boolean enableLighting; private Marker controlPointMarker; private Material lightMaterial; @@ -36,10 +35,8 @@ public class BasicAirspaceControlPointRenderer implements AirspaceControlPointRe private double maxMarkerSize; private PickSupport pickSupport = new PickSupport(); - public BasicAirspaceControlPointRenderer(Marker controlPointMarker) - { - if (controlPointMarker == null) - { + public BasicAirspaceControlPointRenderer(Marker controlPointMarker) { + if (controlPointMarker == null) { String message = Logging.getMessage("nullValue.MarkerIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -52,38 +49,31 @@ public BasicAirspaceControlPointRenderer(Marker controlPointMarker) this.enableDepthTest = true; } - public BasicAirspaceControlPointRenderer() - { + public BasicAirspaceControlPointRenderer() { this(createDefaultMarker()); } - public static Marker createDefaultMarker() - { + public static Marker createDefaultMarker() { // Create an opaque blue sphere. By default the sphere has a 16 pixel radius, but its radius must be at least // 0.1 meters . MarkerAttributes attributes = new BasicMarkerAttributes(Material.BLUE, BasicMarkerShape.SPHERE, 1.0, 16, 0.1); return new BasicMarker(null, attributes, null); } - public boolean isEnableLighting() - { + public boolean isEnableLighting() { return this.enableLighting; } - public void setEnableLighting(boolean enable) - { + public void setEnableLighting(boolean enable) { this.enableLighting = enable; } - public Marker getControlPointMarker() - { + public Marker getControlPointMarker() { return controlPointMarker; } - public void setControlPointMarker(Marker marker) - { - if (marker == null) - { + public void setControlPointMarker(Marker marker) { + if (marker == null) { String message = Logging.getMessage("nullValue.MarkerIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -92,15 +82,12 @@ public void setControlPointMarker(Marker marker) this.controlPointMarker = marker; } - public Material getLightMaterial() - { + public Material getLightMaterial() { return this.lightMaterial; } - public void setLightMaterial(Material material) - { - if (material != null) - { + public void setLightMaterial(Material material) { + if (material != null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -109,15 +96,12 @@ public void setLightMaterial(Material material) this.lightMaterial = material; } - public Vec4 getLightDirection() - { + public Vec4 getLightDirection() { return this.lightDirection; } - public void setLightDirection(Vec4 direction) - { - if (direction != null) - { + public void setLightDirection(Vec4 direction) { + if (direction != null) { String message = Logging.getMessage("nullValue.DirectionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -126,26 +110,21 @@ public void setLightDirection(Vec4 direction) this.lightDirection = direction; } - public boolean isEnableDepthTest() - { + public boolean isEnableDepthTest() { return this.enableDepthTest; } - public void setEnableDepthTest(boolean enable) - { + public void setEnableDepthTest(boolean enable) { this.enableDepthTest = enable; } - public void render(DrawContext dc, Iterable controlPoints) - { - if (dc == null) - { + public void render(DrawContext dc, Iterable controlPoints) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -155,16 +134,13 @@ public void render(DrawContext dc, Iterable cont } public void pick(DrawContext dc, Iterable controlPoints, Point pickPoint, - Layer layer) - { - if (dc == null) - { + Layer layer) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (controlPoints == null) - { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -179,46 +155,35 @@ public void pick(DrawContext dc, Iterable contro //**************************************************************// //******************** Control Point Rendering ***************// //**************************************************************// - - protected void draw(DrawContext dc, Iterable controlPoints) - { + protected void draw(DrawContext dc, Iterable controlPoints) { this.begin(dc); - try - { + try { this.drawControlPoints(dc, controlPoints); - } - finally - { + } finally { this.end(dc); } } - protected void drawControlPoints(DrawContext dc, Iterable controlPoints) - { + protected void drawControlPoints(DrawContext dc, Iterable controlPoints) { // Render the control points from back-to front. SortedSet sortedPoints = this.sortControlPoints(dc, controlPoints); this.drawMarkers(dc, sortedPoints); } - protected void begin(DrawContext dc) - { + protected void begin(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.beginPicking(dc); gl.glPushAttrib(GL2.GL_CURRENT_BIT | GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_TRANSFORM_BIT); - } - else - { + } else { gl.glPushAttrib(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_CURRENT_BIT | GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_HINT_BIT - | GL2.GL_LIGHTING_BIT | GL2.GL_TRANSFORM_BIT); + | GL2.GL_LIGHTING_BIT | GL2.GL_TRANSFORM_BIT); gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); - if (this.isEnableLighting()) - { + if (this.isEnableLighting()) { this.setupLighting(dc); } @@ -231,12 +196,9 @@ protected void begin(DrawContext dc) gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST); } - if (this.isEnableDepthTest()) - { + if (this.isEnableDepthTest()) { gl.glEnable(GL.GL_DEPTH_TEST); - } - else - { + } else { gl.glDisable(GL.GL_DEPTH_TEST); } @@ -244,43 +206,34 @@ protected void begin(DrawContext dc) gl.glPushMatrix(); } - protected void end(DrawContext dc) - { + protected void end(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glPopMatrix(); gl.glPopAttrib(); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.endPicking(dc); } } - protected PickSupport getPickSupport() - { + protected PickSupport getPickSupport() { return this.pickSupport; } //**************************************************************// //******************** Marker Rendering **********************// //**************************************************************// - - protected void drawMarkers(DrawContext dc, Iterable controlPoints) - { + protected void drawMarkers(DrawContext dc, Iterable controlPoints) { // Compute the maximum marker size as a function of the control points to render. this.setMaxMarkerSize(this.computeMaxMarkerSize(controlPoints)); // Apply the marker attributes. - if (!dc.isPickingMode()) - { - if (this.isEnableLighting()) - { + if (!dc.isPickingMode()) { + if (this.isEnableLighting()) { this.getControlPointMarker().getAttributes().apply(dc); - } - else - { + } else { float[] compArray = new float[4]; Color color = this.getControlPointMarker().getAttributes().getMaterial().getDiffuse(); color.getRGBComponents(compArray); @@ -289,19 +242,17 @@ protected void drawMarkers(DrawContext dc, Iterable 0.0) - { - if (radius > this.getMaxMarkerSize()) - { + if (this.getMaxMarkerSize() > 0.0) { + if (radius > this.getMaxMarkerSize()) { radius = this.getMaxMarkerSize(); } } @@ -349,20 +294,16 @@ protected double computeMarkerRadius(DrawContext dc, Marker marker, Vec4 point) return radius; } - protected double computeMaxMarkerSize(Iterable controlPoints) - { + protected double computeMaxMarkerSize(Iterable controlPoints) { // Compute the maximum marker size as a fraction of the average distance between control points. This will // prevent all but the nearest control points from touching as the view moves away from the airspace. double totalDistance = 0.0; int count = 0; - for (AirspaceControlPoint p1 : controlPoints) - { - for (AirspaceControlPoint p2 : controlPoints) - { - if (p1 != p2) - { + for (AirspaceControlPoint p1 : controlPoints) { + for (AirspaceControlPoint p2 : controlPoints) { + if (p1 != p2) { double d = p1.getPoint().distanceTo3(p2.getPoint()); totalDistance += d; count++; @@ -379,9 +320,7 @@ protected double computeMaxMarkerSize(Iterable c //**************************************************************// //******************** Rendering Support *********************// //**************************************************************// - - protected void setupLighting(DrawContext dc) - { + protected void setupLighting(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. float[] modelAmbient = new float[4]; @@ -416,7 +355,6 @@ protected void setupLighting(DrawContext dc) // a directional light. // (b) Invoke the light position call with the identity matrix on the modelview stack. Since the position // is transfomed by the - Vec4 vec = getLightDirection().normalize3(); float[] params = new float[4]; params[0] = (float) vec.x; @@ -434,52 +372,37 @@ protected void setupLighting(DrawContext dc) } protected SortedSet sortControlPoints(DrawContext dc, - Iterable unsortedPoints) - { + Iterable unsortedPoints) { final Vec4 eyePoint = dc.getView().getEyePoint(); // Sort control points from lower altitude to upper altitude, then from back to front. This will give priority // to the upper altitude control points during picking. We give priority to the upper points, in case the // shape has been flattened against the terrain. In this case the lower points may not be movable, therefore // the user must be able to select an upper point to raise the shape and fix the problem. - - TreeSet set = new TreeSet(new Comparator() - { - public int compare(AirspaceControlPoint p1, AirspaceControlPoint p2) - { + TreeSet set = new TreeSet(new Comparator() { + public int compare(AirspaceControlPoint p1, AirspaceControlPoint p2) { double d1 = p1.getPoint().distanceTo3(eyePoint); double d2 = p2.getPoint().distanceTo3(eyePoint); int alt1 = p1.getAltitudeIndex(); int alt2 = p2.getAltitudeIndex(); - if (alt2 < alt1) - { + if (alt2 < alt1) { return -1; - } - else if (alt2 > alt1) - { + } else if (alt2 > alt1) { return 1; - } - else - { - if (d1 < d2) - { + } else { + if (d1 < d2) { return 1; - } - else if (d1 > d2) - { + } else if (d1 > d2) { return -1; - } - else - { + } else { return 0; } } } }); - for (AirspaceControlPoint p : unsortedPoints) - { + for (AirspaceControlPoint p : unsortedPoints) { set.add(p); } diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/PolygonEditor.java b/src/gov/nasa/worldwind/render/airspaces/editor/PolygonEditor.java index a5117168e2..865a9577ce 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/PolygonEditor.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/PolygonEditor.java @@ -19,52 +19,44 @@ * @author dcollins * @version $Id: PolygonEditor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PolygonEditor extends AbstractAirspaceEditor -{ +public class PolygonEditor extends AbstractAirspaceEditor { + private Polygon polygon; // Can be null private static final double DEFAULT_POLYGON_HEIGHT = 10.0; - public PolygonEditor(AirspaceControlPointRenderer renderer) - { + public PolygonEditor(AirspaceControlPointRenderer renderer) { super(renderer); } - public PolygonEditor() - { + public PolygonEditor() { } - public Airspace getAirspace() - { + public Airspace getAirspace() { return this.getPolygon(); } - public Polygon getPolygon() - { + public Polygon getPolygon() { return this.polygon; } - public void setPolygon(Polygon polygon) - { + public void setPolygon(Polygon polygon) { this.polygon = polygon; } //**************************************************************// //******************** Control Point Assembly ****************// //**************************************************************// - - protected void assembleControlPoints(DrawContext dc) - { - if (this.getPolygon() == null) + protected void assembleControlPoints(DrawContext dc) { + if (this.getPolygon() == null) { return; + } int numLocations = this.getPolygon().getLocations().size(); boolean isCollapsed = this.getPolygon().isAirspaceCollapsed(); - for (int locationIndex = 0; locationIndex < numLocations; locationIndex++) - { + for (int locationIndex = 0; locationIndex < numLocations; locationIndex++) { // If the polygon is not collapsed, then add the lower altitude control points. - if (!isCollapsed) - { + if (!isCollapsed) { this.addPolygonControlPoint(dc, locationIndex, LOWER_ALTITUDE); } @@ -73,8 +65,7 @@ protected void assembleControlPoints(DrawContext dc) } } - protected void addPolygonControlPoint(DrawContext dc, int locationIndex, int altitudeIndex) - { + protected void addPolygonControlPoint(DrawContext dc, int locationIndex, int altitudeIndex) { LatLon location = this.getPolygon().getLocations().get(locationIndex); double altitude = this.getPolygon().getAltitudes()[altitudeIndex]; boolean terrainConforming = this.getPolygon().isTerrainConforming()[altitudeIndex]; @@ -83,10 +74,10 @@ protected void addPolygonControlPoint(DrawContext dc, int locationIndex, int alt // vertex. We do this to match the logic in Polygon, which applies vertical exaggeration to the altitude of its // vertices. Vec4 point = this.getPolygon().computePointFromPosition(dc, location.getLatitude(), location.getLongitude(), - dc.getVerticalExaggeration() * altitude, terrainConforming); + dc.getVerticalExaggeration() * altitude, terrainConforming); - AirspaceControlPoint controlPoint = - new BasicAirspaceControlPoint(this, this.getPolygon(), locationIndex, altitudeIndex, point); + AirspaceControlPoint controlPoint + = new BasicAirspaceControlPoint(this, this.getPolygon(), locationIndex, altitudeIndex, point); this.addControlPoint(dc, controlPoint); } @@ -94,22 +85,16 @@ protected void addPolygonControlPoint(DrawContext dc, int locationIndex, int alt //**************************************************************// //******************** Control Point Events ******************// //**************************************************************// - protected AirspaceControlPoint doAddControlPoint(WorldWindow wwd, Airspace airspace, - Point mousePoint) - { - if (this.getPolygon().getLocations().isEmpty()) - { + Point mousePoint) { + if (this.getPolygon().getLocations().isEmpty()) { return this.doAddFirstLocation(wwd, mousePoint); - } - else - { + } else { return this.doAddNextLocation(wwd, mousePoint); } } - protected AirspaceControlPoint doAddFirstLocation(WorldWindow wwd, Point mousePoint) - { + protected AirspaceControlPoint doAddFirstLocation(WorldWindow wwd, Point mousePoint) { // Adding the first location is unique in two ways: // // First, the airspace has no existing locations, so the only reference we have to interpret the user's intent @@ -124,8 +109,7 @@ protected AirspaceControlPoint doAddFirstLocation(WorldWindow wwd, Point mousePo double surfaceElevation = AirspaceEditorUtil.surfaceElevationAt(wwd, ray); Vec4 newPoint = AirspaceEditorUtil.intersectGlobeAt(wwd, surfaceElevation, ray); - if (newPoint == null) - { + if (newPoint == null) { return null; } @@ -135,27 +119,25 @@ protected AirspaceControlPoint doAddFirstLocation(WorldWindow wwd, Point mousePo double[] altitudes = new double[2]; altitudes[LOWER_ALTITUDE] = terrainConformance[LOWER_ALTITUDE] ? 0.0 : newPosition.getElevation(); altitudes[UPPER_ALTITUDE] = terrainConformance[UPPER_ALTITUDE] ? 0.0 - : newPosition.getElevation() + DEFAULT_POLYGON_HEIGHT; + : newPosition.getElevation() + DEFAULT_POLYGON_HEIGHT; this.getPolygon().setAltitudes(altitudes[LOWER_ALTITUDE], altitudes[UPPER_ALTITUDE]); ArrayList locationList = new ArrayList(); locationList.add(new LatLon(newPosition)); // If rubber banding is enabled, add a second entry at the same location. - if (this.isUseRubberBand()) - { + if (this.isUseRubberBand()) { locationList.add(new LatLon(newPosition)); } this.getPolygon().setLocations(locationList); - AirspaceControlPoint controlPoint = - new BasicAirspaceControlPoint(this, this.getPolygon(), 0, LOWER_ALTITUDE, newPoint); + AirspaceControlPoint controlPoint + = new BasicAirspaceControlPoint(this, this.getPolygon(), 0, LOWER_ALTITUDE, newPoint); this.fireControlPointAdded(new AirspaceEditEvent(wwd, this.getAirspace(), this, controlPoint)); // If rubber banding is enabled, fire a second add event, and return a reference to the second location. - if (this.isUseRubberBand()) - { + if (this.isUseRubberBand()) { controlPoint = new BasicAirspaceControlPoint(this, this.getPolygon(), 1, LOWER_ALTITUDE, newPoint); this.fireControlPointAdded(new AirspaceEditEvent(wwd, this.getAirspace(), this, controlPoint)); } @@ -163,8 +145,7 @@ protected AirspaceControlPoint doAddFirstLocation(WorldWindow wwd, Point mousePo return controlPoint; } - protected AirspaceControlPoint doAddNextLocation(WorldWindow wwd, Point mousePoint) - { + protected AirspaceControlPoint doAddNextLocation(WorldWindow wwd, Point mousePoint) { // Try to find the edge that is closest to a ray passing through the screen point. We're trying to determine // the user's intent as to which edge a new two control points should be added to. We create a list of all // potentiall control point edges, then find the best match. We compute the new location by intersecting the @@ -172,24 +153,22 @@ protected AirspaceControlPoint doAddNextLocation(WorldWindow wwd, Point mousePoi // based on the points orientaton relative to the edge. List edgeInfoList = AirspaceEditorUtil.computeEdgeInfoFor( - this.getPolygon().getLocations().size(), this.getCurrentControlPoints()); + this.getPolygon().getLocations().size(), this.getCurrentControlPoints()); - if (edgeInfoList.isEmpty()) - { + if (edgeInfoList.isEmpty()) { return null; } Line ray = wwd.getView().computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); AirspaceEditorUtil.EdgeInfo bestMatch = AirspaceEditorUtil.selectBestEdgeMatch( - wwd, ray, this.getAirspace(), edgeInfoList); + wwd, ray, this.getAirspace(), edgeInfoList); - if (bestMatch == null) - { + if (bestMatch == null) { return null; } AirspaceControlPoint controlPoint = AirspaceEditorUtil.createControlPointFor( - wwd, ray, this, this.getAirspace(), bestMatch); + wwd, ray, this, this.getAirspace(), bestMatch); Vec4 newPoint = controlPoint.getPoint(); LatLon newLocation = new LatLon(wwd.getModel().getGlobe().computePositionFromPoint(newPoint)); @@ -203,8 +182,7 @@ protected AirspaceControlPoint doAddNextLocation(WorldWindow wwd, Point mousePoi return controlPoint; } - protected void doRemoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint) - { + protected void doRemoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint) { int index = controlPoint.getLocationIndex(); List newLocationList = new ArrayList(this.getPolygon().getLocations()); newLocationList.remove(index); @@ -214,8 +192,7 @@ protected void doRemoveControlPoint(WorldWindow wwd, AirspaceControlPoint contro } protected void doMoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Intersect a ray throuh each mouse point, with a geoid passing through the selected control point. Since // most airspace control points follow a fixed altitude, this will track close to the intended mouse position. // If either ray fails to intersect the geoid, then ignore this event. Use the difference between the two @@ -225,13 +202,12 @@ protected void doMoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlP Line ray = wwd.getView().computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); Line previousRay = wwd.getView().computeRayFromScreenPoint(previousMousePoint.getX(), - previousMousePoint.getY()); + previousMousePoint.getY()); Vec4 vec = AirspaceEditorUtil.intersectGlobeAt(wwd, controlPointPos.getElevation(), ray); Vec4 previousVec = AirspaceEditorUtil.intersectGlobeAt(wwd, controlPointPos.getElevation(), previousRay); - if (vec == null || previousVec == null) - { + if (vec == null || previousVec == null) { return; } @@ -249,8 +225,7 @@ protected void doMoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlP } protected void doResizeAtControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Find the closest points between the rays through each screen point, and the ray from the control point // and in the direction of the globe's surface normal. Compute the elevation difference between these two // points, and use that as the change in airspace altitude. @@ -275,45 +250,39 @@ protected void doResizeAtControlPoint(WorldWindow wwd, AirspaceControlPoint cont double elevationChange = previousPos.getElevation() - pos.getElevation(); int index; - if (this.getPolygon().isAirspaceCollapsed()) - { + if (this.getPolygon().isAirspaceCollapsed()) { index = (elevationChange < 0) ? LOWER_ALTITUDE : UPPER_ALTITUDE; - } - else - { + } else { index = controlPoint.getAltitudeIndex(); } double[] altitudes = controlPoint.getAirspace().getAltitudes(); boolean[] terrainConformance = controlPoint.getAirspace().isTerrainConforming(); - if (this.isKeepControlPointsAboveTerrain()) - { - if (terrainConformance[index]) - { - if (altitudes[index] + elevationChange < 0.0) + if (this.isKeepControlPointsAboveTerrain()) { + if (terrainConformance[index]) { + if (altitudes[index] + elevationChange < 0.0) { elevationChange = -altitudes[index]; - } - else - { + } + } else { double height = AirspaceEditorUtil.computeLowestHeightAboveSurface( - wwd, this.getCurrentControlPoints(), index); - if (elevationChange <= -height) + wwd, this.getCurrentControlPoints(), index); + if (elevationChange <= -height) { elevationChange = -height; + } } } double d = AirspaceEditorUtil.computeMinimumDistanceBetweenAltitudes(this.getPolygon().getLocations().size(), - this.getCurrentControlPoints()); - if (index == LOWER_ALTITUDE) - { - if (elevationChange > d) + this.getCurrentControlPoints()); + if (index == LOWER_ALTITUDE) { + if (elevationChange > d) { elevationChange = d; - } - else if (index == UPPER_ALTITUDE) - { - if (elevationChange < -d) + } + } else if (index == UPPER_ALTITUDE) { + if (elevationChange < -d) { elevationChange = -d; + } } altitudes[index] += elevationChange; diff --git a/src/gov/nasa/worldwind/render/airspaces/editor/SphereAirspaceEditor.java b/src/gov/nasa/worldwind/render/airspaces/editor/SphereAirspaceEditor.java index ad9db2163c..1a35cf39f8 100644 --- a/src/gov/nasa/worldwind/render/airspaces/editor/SphereAirspaceEditor.java +++ b/src/gov/nasa/worldwind/render/airspaces/editor/SphereAirspaceEditor.java @@ -18,8 +18,8 @@ * @author dcollins * @version $Id: SphereAirspaceEditor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SphereAirspaceEditor extends AbstractAirspaceEditor -{ +public class SphereAirspaceEditor extends AbstractAirspaceEditor { + private SphereAirspace sphere = null; // Can be null private double minRadius = 1.0; private double maxRadius = Double.MAX_VALUE; @@ -28,56 +28,46 @@ public class SphereAirspaceEditor extends AbstractAirspaceEditor public static final int RADIUS_CONTROL_ID = 1024; - public SphereAirspaceEditor(AirspaceControlPointRenderer renderer) - { + public SphereAirspaceEditor(AirspaceControlPointRenderer renderer) { super(renderer); } - public SphereAirspaceEditor() - { + public SphereAirspaceEditor() { this(getDefaultRenderer()); } - public static AirspaceControlPointRenderer getDefaultRenderer() - { + public static AirspaceControlPointRenderer getDefaultRenderer() { BasicAirspaceControlPointRenderer renderer = new BasicAirspaceControlPointRenderer(); renderer.setControlPointMarker(createDefaultMarker()); renderer.setEnableDepthTest(false); return renderer; } - public static Marker createDefaultMarker() - { + public static Marker createDefaultMarker() { // Create an opaque blue sphere. By default the sphere has a 12 pixel radius, but its radius must be at least // 0.1 meters . MarkerAttributes attributes = new BasicMarkerAttributes(Material.BLUE, BasicMarkerShape.SPHERE, 1.0, 12, 0.1); return new BasicMarker(null, attributes, null); } - public Airspace getAirspace() - { + public Airspace getAirspace() { return this.getSphere(); } - public SphereAirspace getSphere() - { + public SphereAirspace getSphere() { return this.sphere; } - public void setSphere(SphereAirspace sphere) - { + public void setSphere(SphereAirspace sphere) { this.sphere = sphere; } - public double getMinRadius() - { + public double getMinRadius() { return this.minRadius; } - public void setMinRadius(double radius) - { - if (radius < 0.0) - { + public void setMinRadius(double radius) { + if (radius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -86,15 +76,12 @@ public void setMinRadius(double radius) this.minRadius = radius; } - public double getMaxRadius() - { + public double getMaxRadius() { return this.maxRadius; } - public void setMaxRadius(double radius) - { - if (radius < 0.0) - { + public void setMaxRadius(double radius) { + if (radius < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -103,25 +90,20 @@ public void setMaxRadius(double radius) this.maxRadius = radius; } - public boolean isAlwaysShowRadiusControl() - { + public boolean isAlwaysShowRadiusControl() { return this.alwaysShowRadiusControl; } - public void setAlwaysShowRadiusControl(boolean alwaysShow) - { + public void setAlwaysShowRadiusControl(boolean alwaysShow) { this.alwaysShowRadiusControl = alwaysShow; } - public double getRadiusControlDrawDistance() - { + public double getRadiusControlDrawDistance() { return radiusControlDrawDistance; } - public void setRadiusControlDrawDistance(double distance) - { - if (distance < 0.0) - { + public void setRadiusControlDrawDistance(double distance) { + if (distance < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "distance < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -133,22 +115,23 @@ public void setRadiusControlDrawDistance(double distance) //**************************************************************// //******************** Control Point Assembly ****************// //**************************************************************// - - protected void assembleControlPoints(DrawContext dc) - { + protected void assembleControlPoints(DrawContext dc) { // If the cursor passes near the edge of the sphere, draw a tangent control point that can be used to // adjust the sphere's radius. - if (this.getSphere() == null) + if (this.getSphere() == null) { return; + } Extent bounds = this.getSphere().getExtent(dc); - if (bounds == null) + if (bounds == null) { return; + } Point pickPoint = dc.getPickPoint(); - if (pickPoint == null) + if (pickPoint == null) { return; + } Line pickRay = dc.getView().computeRayFromScreenPoint(pickPoint.getX(), pickPoint.getY()); @@ -163,18 +146,15 @@ protected void assembleControlPoints(DrawContext dc) Vec4 nearestScreenPointOnSphere = dc.getView().project(nearestPointOnSphere); double distance = nearestScreenPointOnLine.distanceTo3(nearestScreenPointOnSphere); - if (this.isAlwaysShowRadiusControl() || distance < this.getRadiusControlDrawDistance()) - { + if (this.isAlwaysShowRadiusControl() || distance < this.getRadiusControlDrawDistance()) { AirspaceControlPoint controlPoint = new BasicAirspaceControlPoint(this, this.getSphere(), - RADIUS_CONTROL_ID, RADIUS_CONTROL_ID, nearestPointOnSphere); + RADIUS_CONTROL_ID, RADIUS_CONTROL_ID, nearestPointOnSphere); this.addControlPoint(dc, controlPoint); } } - protected Vec4 getCenterPoint(WorldWindow wwd, Airspace airspace) - { - if (!(airspace instanceof SphereAirspace)) - { + protected Vec4 getCenterPoint(WorldWindow wwd, Airspace airspace) { + if (!(airspace instanceof SphereAirspace)) { return null; } @@ -184,25 +164,19 @@ protected Vec4 getCenterPoint(WorldWindow wwd, Airspace airspace) boolean terrainConforming = sphere.isTerrainConforming()[LOWER_ALTITUDE]; Vec4 point; - if (terrainConforming) - { - if (wwd.getSceneController().getTerrain() != null) - { + if (terrainConforming) { + if (wwd.getSceneController().getTerrain() != null) { point = wwd.getSceneController().getTerrain().getSurfacePoint( - location.getLatitude(), location.getLongitude(), altitude); - } - else - { + location.getLatitude(), location.getLongitude(), altitude); + } else { double elevation = wwd.getModel().getGlobe().getElevation( - location.getLatitude(), location.getLongitude()); + location.getLatitude(), location.getLongitude()); point = wwd.getModel().getGlobe().computePointFromPosition( - location.getLatitude(), location.getLongitude(), elevation + altitude); + location.getLatitude(), location.getLongitude(), elevation + altitude); } - } - else - { + } else { point = wwd.getModel().getGlobe().computePointFromPosition( - location.getLatitude(), location.getLongitude(), altitude); + location.getLatitude(), location.getLongitude(), altitude); } return point; @@ -211,10 +185,8 @@ protected Vec4 getCenterPoint(WorldWindow wwd, Airspace airspace) //**************************************************************// //******************** Control Point Events ******************// //**************************************************************// - protected void doMoveAirspaceVertically(WorldWindow wwd, Airspace airspace, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Find the closest points between the rays through each screen point, and the ray from the control point // and in the direction of the globe's surface normal. Compute the elevation difference between these two // points, and use that as the change in airspace altitude. @@ -238,18 +210,16 @@ protected void doMoveAirspaceVertically(WorldWindow wwd, Airspace airspace, Position previousPos = wwd.getModel().getGlobe().computePositionFromPoint(previousPointOnLine); double elevationChange = previousPos.getElevation() - pos.getElevation(); - if (this.isKeepControlPointsAboveTerrain()) - { - if (terrainConforming) - { - if (altitude + elevationChange < 0.0) + if (this.isKeepControlPointsAboveTerrain()) { + if (terrainConforming) { + if (altitude + elevationChange < 0.0) { elevationChange = -altitude; - } - else - { + } + } else { double height = AirspaceEditorUtil.computeHeightAboveSurface(wwd, centerPoint); - if (elevationChange <= -height) + if (elevationChange <= -height) { elevationChange = -height; + } } } @@ -260,32 +230,26 @@ protected void doMoveAirspaceVertically(WorldWindow wwd, Airspace airspace, } protected AirspaceControlPoint doAddControlPoint(WorldWindow wwd, Airspace airspace, - Point mousePoint) - { + Point mousePoint) { return null; } - protected void doRemoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint) - { + protected void doRemoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint) { } protected void doMoveControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint) - { - if (controlPoint.getLocationIndex() == RADIUS_CONTROL_ID) - { + Point mousePoint, Point previousMousePoint) { + if (controlPoint.getLocationIndex() == RADIUS_CONTROL_ID) { this.doMoveRadiusControlPoint(wwd, controlPoint, mousePoint, previousMousePoint); } } protected void doResizeAtControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { } protected void doMoveRadiusControlPoint(WorldWindow wwd, AirspaceControlPoint controlPoint, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { // Find the closest points between the rays through each screen point, and the ray from the sphere center to the // control point. Compute the signed difference between these two points, and use that as the change in radius. @@ -302,10 +266,12 @@ protected void doMoveRadiusControlPoint(WorldWindow wwd, AirspaceControlPoint co double radiusChange = previousDistance - distance; double radius = this.getSphere().getRadius() + radiusChange; - if (radius < this.getMinRadius()) + if (radius < this.getMinRadius()) { radius = this.getMinRadius(); - if (radius > this.getMaxRadius()) + } + if (radius > this.getMaxRadius()) { radius = this.getMaxRadius(); + } this.getSphere().setRadius(radius); diff --git a/src/gov/nasa/worldwind/render/markers/BasicMarker.java b/src/gov/nasa/worldwind/render/markers/BasicMarker.java index ac518b1c5a..440060cbc4 100644 --- a/src/gov/nasa/worldwind/render/markers/BasicMarker.java +++ b/src/gov/nasa/worldwind/render/markers/BasicMarker.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.markers; import gov.nasa.worldwind.geom.*; @@ -14,8 +13,8 @@ * @author tag * @version $Id: BasicMarker.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicMarker implements Marker -{ +public class BasicMarker implements Marker { + protected Position position; // may be null protected Angle heading; // may be null protected Angle pitch; // may be null @@ -25,10 +24,8 @@ public class BasicMarker implements Marker // required to be specified at construction. protected MarkerAttributes attributes; - public BasicMarker(Position position, MarkerAttributes attrs) - { - if (attrs == null) - { + public BasicMarker(Position position, MarkerAttributes attrs) { + if (attrs == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -38,10 +35,8 @@ public BasicMarker(Position position, MarkerAttributes attrs) this.attributes = attrs; } - public BasicMarker(Position position, MarkerAttributes attrs, Angle heading) - { - if (attrs == null) - { + public BasicMarker(Position position, MarkerAttributes attrs, Angle heading) { + if (attrs == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -52,69 +47,69 @@ public BasicMarker(Position position, MarkerAttributes attrs, Angle heading) this.attributes = attrs; } - public Position getPosition() - { + public Position getPosition() { return position; } - public void setPosition(Position position) - { + public void setPosition(Position position) { this.position = position; } - /** {@inheritDoc} */ - public Angle getHeading() - { + /** + * {@inheritDoc} + */ + public Angle getHeading() { return this.heading; } - /** {@inheritDoc} */ - public void setHeading(Angle heading) - { + /** + * {@inheritDoc} + */ + public void setHeading(Angle heading) { this.heading = heading; } - /** {@inheritDoc} */ - public Angle getRoll() - { + /** + * {@inheritDoc} + */ + public Angle getRoll() { return this.roll; } - /** {@inheritDoc} */ - public void setRoll(Angle roll) - { + /** + * {@inheritDoc} + */ + public void setRoll(Angle roll) { this.roll = roll; } - /** {@inheritDoc} */ - public Angle getPitch() - { + /** + * {@inheritDoc} + */ + public Angle getPitch() { return this.pitch; } - /** {@inheritDoc} */ - public void setPitch(Angle pitch) - { + /** + * {@inheritDoc} + */ + public void setPitch(Angle pitch) { this.pitch = pitch; } - public MarkerAttributes getAttributes() - { + public MarkerAttributes getAttributes() { return attributes; } - public void setAttributes(MarkerAttributes attributes) - { + public void setAttributes(MarkerAttributes attributes) { this.attributes = attributes; } - public void render(DrawContext dc, Vec4 point, double radius, boolean isRelative) - { + public void render(DrawContext dc, Vec4 point, double radius, boolean isRelative) { this.attributes.getShape(dc).render(dc, this, point, radius, isRelative); } - public void render(DrawContext dc, Vec4 point, double radius) - { + public void render(DrawContext dc, Vec4 point, double radius) { this.attributes.getShape(dc).render(dc, this, point, radius, false); } } diff --git a/src/gov/nasa/worldwind/render/markers/BasicMarkerAttributes.java b/src/gov/nasa/worldwind/render/markers/BasicMarkerAttributes.java index b56aa69ae6..73b301cd38 100644 --- a/src/gov/nasa/worldwind/render/markers/BasicMarkerAttributes.java +++ b/src/gov/nasa/worldwind/render/markers/BasicMarkerAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.markers; import gov.nasa.worldwind.render.*; @@ -15,8 +14,8 @@ * @author tag * @version $Id: BasicMarkerAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicMarkerAttributes implements MarkerAttributes -{ +public class BasicMarkerAttributes implements MarkerAttributes { + private Material material = Material.WHITE; private Material headingMaterial = Material.RED; protected double headingScale = 3; @@ -26,21 +25,17 @@ public class BasicMarkerAttributes implements MarkerAttributes private double minMarkerSize = 3d; private double maxMarkerSize = Double.MAX_VALUE; - public BasicMarkerAttributes() - { + public BasicMarkerAttributes() { } - public BasicMarkerAttributes(Material material, String shapeType, double opacity) - { - if (material == null) - { + public BasicMarkerAttributes(Material material, String shapeType, double opacity) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (shapeType == null) - { + if (shapeType == null) { String message = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -52,38 +47,32 @@ public BasicMarkerAttributes(Material material, String shapeType, double opacity } public BasicMarkerAttributes(Material material, String shapeType, double opacity, double markerPixels, - double minMarkerSize) - { - if (material == null) - { + double minMarkerSize) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (shapeType == null) - { + if (shapeType == null) { String message = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (opacity < 0) - { + if (opacity < 0) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (markerPixels < 0) - { + if (markerPixels < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", markerPixels); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minMarkerSize < 0) - { + if (minMarkerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", minMarkerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -97,45 +86,38 @@ public BasicMarkerAttributes(Material material, String shapeType, double opacity } public BasicMarkerAttributes(Material material, String shapeType, double opacity, double markerPixels, - double minMarkerSize, double maxMarkerSize) - { - if (material == null) - { + double minMarkerSize, double maxMarkerSize) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (shapeType == null) - { + if (shapeType == null) { String message = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (opacity < 0) - { + if (opacity < 0) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (markerPixels < 0) - { + if (markerPixels < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", markerPixels); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minMarkerSize < 0) - { + if (minMarkerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", minMarkerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (maxMarkerSize < 0) - { + if (maxMarkerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", maxMarkerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -149,10 +131,8 @@ public BasicMarkerAttributes(Material material, String shapeType, double opacity this.maxMarkerSize = maxMarkerSize; } - public BasicMarkerAttributes(BasicMarkerAttributes that) - { - if (that == null) - { + public BasicMarkerAttributes(BasicMarkerAttributes that) { + if (that == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -168,15 +148,12 @@ public BasicMarkerAttributes(BasicMarkerAttributes that) this.maxMarkerSize = that.maxMarkerSize; } - public Material getMaterial() - { + public Material getMaterial() { return material; } - public void setMaterial(Material material) - { - if (material == null) - { + public void setMaterial(Material material) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -185,15 +162,12 @@ public void setMaterial(Material material) this.material = material; } - public Material getHeadingMaterial() - { + public Material getHeadingMaterial() { return headingMaterial; } - public void setHeadingMaterial(Material headingMaterial) - { - if (material == null) - { + public void setHeadingMaterial(Material headingMaterial) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -202,15 +176,12 @@ public void setHeadingMaterial(Material headingMaterial) this.headingMaterial = headingMaterial; } - public double getHeadingScale() - { + public double getHeadingScale() { return headingScale; } - public void setHeadingScale(double headingScale) - { - if (headingScale < 0) - { + public void setHeadingScale(double headingScale) { + if (headingScale < 0) { String message = Logging.getMessage("generic.ScaleOutOfRange", headingScale); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -219,15 +190,12 @@ public void setHeadingScale(double headingScale) this.headingScale = headingScale; } - public String getShapeType() - { + public String getShapeType() { return shapeType; } - public void setShapeType(String shapeType) - { - if (shapeType == null) - { + public void setShapeType(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -236,12 +204,10 @@ public void setShapeType(String shapeType) this.shapeType = shapeType; } - public MarkerShape getShape(DrawContext dc) - { + public MarkerShape getShape(DrawContext dc) { MarkerShape shape = (MarkerShape) dc.getValue(this.shapeType); - if (shape == null) - { + if (shape == null) { shape = BasicMarkerShape.createShapeInstance(this.shapeType); dc.setValue(this.shapeType, shape); } @@ -249,15 +215,12 @@ public MarkerShape getShape(DrawContext dc) return shape; } - public double getOpacity() - { + public double getOpacity() { return opacity; } - public void setOpacity(double opacity) - { - if (opacity < 0) - { + public void setOpacity(double opacity) { + if (opacity < 0) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -266,15 +229,12 @@ public void setOpacity(double opacity) this.opacity = opacity; } - public double getMarkerPixels() - { + public double getMarkerPixels() { return markerPixels; } - public void setMarkerPixels(double markerPixels) - { - if (markerPixels < 0) - { + public void setMarkerPixels(double markerPixels) { + if (markerPixels < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", markerPixels); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -283,15 +243,12 @@ public void setMarkerPixels(double markerPixels) this.markerPixels = markerPixels; } - public double getMinMarkerSize() - { + public double getMinMarkerSize() { return minMarkerSize; } - public void setMinMarkerSize(double minMarkerSize) - { - if (minMarkerSize < 0) - { + public void setMinMarkerSize(double minMarkerSize) { + if (minMarkerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", minMarkerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -300,15 +257,12 @@ public void setMinMarkerSize(double minMarkerSize) this.minMarkerSize = minMarkerSize; } - public double getMaxMarkerSize() - { + public double getMaxMarkerSize() { return maxMarkerSize; } - public void setMaxMarkerSize(double markerSize) - { - if (markerSize < 0) - { + public void setMaxMarkerSize(double markerSize) { + if (markerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", markerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -317,16 +271,15 @@ public void setMaxMarkerSize(double markerSize) this.maxMarkerSize = markerSize; } - public void apply(DrawContext dc) - { - if (!dc.isPickingMode() && this.material != null) - { + public void apply(DrawContext dc) { + if (!dc.isPickingMode() && this.material != null) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (this.opacity < 1) + if (this.opacity < 1) { this.material.apply(gl, GL2.GL_FRONT, (float) this.opacity); - else + } else { this.material.apply(gl, GL2.GL_FRONT); + } } } } diff --git a/src/gov/nasa/worldwind/render/markers/BasicMarkerShape.java b/src/gov/nasa/worldwind/render/markers/BasicMarkerShape.java index fb2e498ee8..d1b6d531c0 100644 --- a/src/gov/nasa/worldwind/render/markers/BasicMarkerShape.java +++ b/src/gov/nasa/worldwind/render/markers/BasicMarkerShape.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.markers; import gov.nasa.worldwind.Disposable; @@ -24,8 +23,8 @@ * @author tag * @version $Id: BasicMarkerShape.java 2279 2014-08-29 21:32:19Z tgaskins $ */ -public class BasicMarkerShape -{ +public class BasicMarkerShape { + public static final String SPHERE = "gov.nasa.worldwind.render.markers.Sphere"; public static final String CUBE = "gov.nasa.worldwind.render.markers.Cube"; public static final String CONE = "gov.nasa.worldwind.render.markers.Cone"; @@ -41,89 +40,76 @@ public class BasicMarkerShape public static final String ORIENTED_CYLINDER_LINE = "gov.nasa.worldwind.render.markers.DirectionalCylinderLine"; @SuppressWarnings({"StringEquality"}) - public static MarkerShape createShapeInstance(String shapeType) - { - if (shapeType == null) - { + public static MarkerShape createShapeInstance(String shapeType) { + if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // String identity rather than equality is wanted here, to avoid a bunch of unnecessary string compares - if (shapeType == BasicMarkerShape.SPHERE) + if (shapeType == BasicMarkerShape.SPHERE) { return new Sphere(); - else if (shapeType == BasicMarkerShape.CUBE) + } else if (shapeType == BasicMarkerShape.CUBE) { return new Cube(); - else if (shapeType == BasicMarkerShape.CONE) + } else if (shapeType == BasicMarkerShape.CONE) { return new Cone(); - else if (shapeType == BasicMarkerShape.CYLINDER) + } else if (shapeType == BasicMarkerShape.CYLINDER) { return new Cylinder(); - else if (shapeType == BasicMarkerShape.HEADING_ARROW) + } else if (shapeType == BasicMarkerShape.HEADING_ARROW) { return new HeadingArrow(); - else if (shapeType == BasicMarkerShape.HEADING_LINE) + } else if (shapeType == BasicMarkerShape.HEADING_LINE) { return new HeadingLine(); - else if (shapeType == BasicMarkerShape.ORIENTED_SPHERE) + } else if (shapeType == BasicMarkerShape.ORIENTED_SPHERE) { return new CompoundShape(BasicMarkerShape.ORIENTED_SPHERE, "Oriented Sphere", new Sphere(), - new HeadingArrow()); - else if (shapeType == BasicMarkerShape.ORIENTED_CUBE) - { + new HeadingArrow()); + } else if (shapeType == BasicMarkerShape.ORIENTED_CUBE) { Cube cube = new Cube(); cube.setApplyOrientation(false); // Heading arrow shows orientation, do not rotate shape return new CompoundShape(BasicMarkerShape.ORIENTED_CUBE, "Oriented Cube", cube, new HeadingArrow(), - .6); - } - else if (shapeType == BasicMarkerShape.ORIENTED_CONE) - { + .6); + } else if (shapeType == BasicMarkerShape.ORIENTED_CONE) { Cone cone = new Cone(); cone.setApplyOrientation(false); // Heading arrow shows orientation, do not rotate shape return new CompoundShape(BasicMarkerShape.ORIENTED_CONE, "Oriented Cone", cone, new HeadingArrow(), 0.6); - } - else if (shapeType == BasicMarkerShape.ORIENTED_CYLINDER) - { + } else if (shapeType == BasicMarkerShape.ORIENTED_CYLINDER) { Cylinder cylinder = new Cylinder(); cylinder.setApplyOrientation(false); // Heading arrow shows orientation, do not rotate shape return new CompoundShape(BasicMarkerShape.ORIENTED_CYLINDER, "Oriented Cylinder", cylinder, - new HeadingArrow(), .6); - } - else if (shapeType == BasicMarkerShape.ORIENTED_SPHERE_LINE) + new HeadingArrow(), .6); + } else if (shapeType == BasicMarkerShape.ORIENTED_SPHERE_LINE) { return new CompoundShape(BasicMarkerShape.ORIENTED_SPHERE_LINE, "Oriented Sphere Line", new Sphere(), - new HeadingLine(), 1); - else if (shapeType == BasicMarkerShape.ORIENTED_CONE_LINE) - { + new HeadingLine(), 1); + } else if (shapeType == BasicMarkerShape.ORIENTED_CONE_LINE) { Cone cone = new Cone(); cone.setApplyOrientation(false); // Heading arrow shows orientation, do not rotate shape return new CompoundShape(BasicMarkerShape.ORIENTED_CONE_LINE, "Oriented Cone Line", cone, - new HeadingLine(), 2); - } - else if (shapeType == BasicMarkerShape.ORIENTED_CYLINDER_LINE) - { + new HeadingLine(), 2); + } else if (shapeType == BasicMarkerShape.ORIENTED_CYLINDER_LINE) { Cylinder cylinder = new Cylinder(); cylinder.setApplyOrientation(false); // Heading arrow shows orientation, do not rotate shape return new CompoundShape(BasicMarkerShape.ORIENTED_CYLINDER_LINE, "Oriented Cylinder Line", cylinder, - new HeadingLine(), 2); - } - else + new HeadingLine(), 2); + } else { return new Sphere(); + } } - protected static class CompoundShape implements MarkerShape, Disposable - { + protected static class CompoundShape implements MarkerShape, Disposable { + protected String name; protected String shapeType; protected ArrayList shapes = new ArrayList(2); protected double offset = 0; - public CompoundShape(String shapeType, String name, MarkerShape shape1, MarkerShape shape2) - { + public CompoundShape(String shapeType, String name, MarkerShape shape1, MarkerShape shape2) { this.name = name; this.shapeType = shapeType; this.shapes.add(shape1); this.shapes.add(shape2); } - public CompoundShape(String shapeType, String name, MarkerShape shape1, MarkerShape shape2, double offset) - { + public CompoundShape(String shapeType, String name, MarkerShape shape1, MarkerShape shape2, double offset) { this.name = name; this.shapeType = shapeType; this.shapes.add(shape1); @@ -131,66 +117,60 @@ public CompoundShape(String shapeType, String name, MarkerShape shape1, MarkerSh this.offset = offset; } - public void dispose() - { - for (MarkerShape shape : this.shapes) - { - if (shape instanceof Disposable) + public void dispose() { + for (MarkerShape shape : this.shapes) { + if (shape instanceof Disposable) { ((Disposable) shape).dispose(); + } } } - public String getName() - { + public String getName() { return name; } - public String getShapeType() - { + public String getShapeType() { return shapeType; } - public void render(DrawContext dc, Marker marker, Vec4 point, double radius) - { + public void render(DrawContext dc, Marker marker, Vec4 point, double radius) { this.shapes.get(0).render(dc, marker, point, radius, false); - if (this.offset != 0) - { + if (this.offset != 0) { Position pos = dc.getGlobe().computePositionFromPoint(point); point = dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), - pos.getElevation() + radius * this.offset); + pos.getElevation() + radius * this.offset); } this.shapes.get(1).render(dc, marker, point, radius, false); } - public void render(DrawContext dc, Marker marker, Vec4 point, double radius, boolean isRelative) - { + public void render(DrawContext dc, Marker marker, Vec4 point, double radius, boolean isRelative) { this.shapes.get(0).render(dc, marker, point, radius, isRelative); - if (this.offset != 0) - { + if (this.offset != 0) { Position pos = dc.getGlobe().computePositionFromPoint(point); point = dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), - pos.getElevation() + radius * this.offset); + pos.getElevation() + radius * this.offset); } this.shapes.get(1).render(dc, marker, point, radius, isRelative); } } - protected static abstract class Shape implements MarkerShape, Disposable - { + protected static abstract class Shape implements MarkerShape, Disposable { + protected String name; protected String shapeType; protected GLUquadric quadric; protected boolean isInitialized = false; protected Object displayListCacheKey = new Object(); - /** Indicates that the shape must apply heading, pitch, and roll. */ + /** + * Indicates that the shape must apply heading, pitch, and roll. + */ protected boolean applyOrientation = true; abstract protected void doRender(DrawContext dc, Marker marker, Vec4 point, double radius, int[] dlResource); abstract protected int drawShape(DrawContext dc, double radius); - protected void initialize(DrawContext dc) - { + protected void initialize(DrawContext dc) { this.quadric = dc.getGLU().gluNewQuadric(); dc.getGLU().gluQuadricDrawStyle(quadric, GLU.GLU_FILL); dc.getGLU().gluQuadricNormals(quadric, GLU.GLU_SMOOTH); @@ -198,23 +178,19 @@ protected void initialize(DrawContext dc) dc.getGLU().gluQuadricTexture(quadric, false); } - public void dispose() - { - if (this.isInitialized) - { + public void dispose() { + if (this.isInitialized) { GLU glu = new GLUgl2(); glu.gluDeleteQuadric(this.quadric); this.isInitialized = false; } } - public String getName() - { + public String getName() { return this.name; } - public String getShapeType() - { + public String getShapeType() { return this.shapeType; } @@ -224,8 +200,7 @@ public String getShapeType() * * @return {@code true} if orientation is applied to the rendered shape, {@code false} if not. */ - public boolean isApplyOrientation() - { + public boolean isApplyOrientation() { return this.applyOrientation; } @@ -233,46 +208,39 @@ public boolean isApplyOrientation() * Specifies whether or not the shape applies heading, pitch, and roll when it renders. * * @param applyOrientation {@code true} if the shape must apply heading, pitch, and roll (if they are supported - * by the shape), {@code false} if it the shape must not apply this orientation. + * by the shape), {@code false} if it the shape must not apply this orientation. */ - public void setApplyOrientation(boolean applyOrientation) - { + public void setApplyOrientation(boolean applyOrientation) { this.applyOrientation = applyOrientation; } - public void render(DrawContext dc, Marker marker, Vec4 point, double radius) - { + public void render(DrawContext dc, Marker marker, Vec4 point, double radius) { render(dc, marker, point, radius, true); } - public void render(DrawContext dc, Marker marker, Vec4 point, double radius, boolean isRelative) - { - if (!this.isInitialized) + public void render(DrawContext dc, Marker marker, Vec4 point, double radius, boolean isRelative) { + if (!this.isInitialized) { this.initialize(dc); + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!isRelative) - { + if (!isRelative) { dc.getView().pushReferenceCenter(dc, point); - } - else - { + } else { gl.glPushMatrix(); gl.glTranslated(point.x, point.y, point.z); } int[] dlResource = (int[]) dc.getGpuResourceCache().get(this.displayListCacheKey); - if (dlResource == null) + if (dlResource == null) { dlResource = this.createDisplayList(dc, radius); + } this.doRender(dc, marker, point, radius, dlResource); - if (!isRelative) - { + if (!isRelative) { dc.getView().popReferenceCenter(dc); - } - else - { + } else { gl.glPopMatrix(); } } @@ -280,23 +248,22 @@ public void render(DrawContext dc, Marker marker, Vec4 point, double radius, boo /** * Compute a direction vector given a point, heading and pitch. * - * @param dc current draw context - * @param point point at which to compute direction vector - * @param normal surface normal at {@code point} + * @param dc current draw context + * @param point point at which to compute direction vector + * @param normal surface normal at {@code point} * @param heading desired heading - * @param pitch desired pitch + * @param pitch desired pitch * * @return A vector pointing in the direction of the desired heading and pitch */ protected Vec4 computeOrientationVector(DrawContext dc, Vec4 point, Vec4 normal, Angle heading, - Angle pitch) - { + Angle pitch) { // To compute rotation of the shape toward the proper heading, find a second point in that direction. Globe globe = dc.getGlobe(); Position pos = globe.computePositionFromPoint(point); LatLon p2ll = LatLon.greatCircleEndPosition(pos, heading, Angle.fromDegrees(0.1)); Vec4 p2 = globe.computePointFromPosition(p2ll.getLatitude(), p2ll.getLongitude(), - pos.getElevation()); + pos.getElevation()); // Find vector in the direction of the heading Vec4 p1p2 = p2.subtract3(point).normalize3(); @@ -308,20 +275,16 @@ protected Vec4 computeOrientationVector(DrawContext dc, Vec4 point, Vec4 normal, return normal.transformBy3(Matrix.fromAxisAngle(pitch, pitchAxis)); } - protected int[] createDisplayList(DrawContext dc, double radius) - { + protected int[] createDisplayList(DrawContext dc, double radius) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - int[] dlResource = new int[] {gl.glGenLists(1), 1}; + int[] dlResource = new int[]{gl.glGenLists(1), 1}; int size; - try - { + try { gl.glNewList(dlResource[0], GL2.GL_COMPILE); size = this.drawShape(dc, radius); gl.glEndList(); - } - catch (Exception e) - { + } catch (Exception e) { gl.glEndList(); gl.glDeleteLists(dlResource[0], dlResource[1]); return null; @@ -333,11 +296,10 @@ protected int[] createDisplayList(DrawContext dc, double radius) } } - protected static class Sphere extends Shape - { + protected static class Sphere extends Shape { + @Override - protected void initialize(DrawContext dc) - { + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Sphere"; @@ -346,8 +308,7 @@ protected void initialize(DrawContext dc) this.isInitialized = true; } - protected void doRender(DrawContext dc, Marker marker, Vec4 point, double radius, int[] dlResource) - { + protected void doRender(DrawContext dc, Marker marker, Vec4 point, double radius, int[] dlResource) { // Sphere is symmetric about all axes, so no need to apply heading, pitch, or roll. GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glScaled(radius, radius, radius); @@ -355,8 +316,7 @@ protected void doRender(DrawContext dc, Marker marker, Vec4 point, double radius } @Override - protected int drawShape(DrawContext dc, double radius) - { + protected int drawShape(DrawContext dc, double radius) { int slices = 24; int stacks = 12; @@ -366,12 +326,13 @@ protected int drawShape(DrawContext dc, double radius) } } - /** Cube marker shape. The cube can be oriented using heading, pitch, and roll. */ - protected static class Cube extends Shape - { + /** + * Cube marker shape. The cube can be oriented using heading, pitch, and roll. + */ + protected static class Cube extends Shape { + @Override - protected void initialize(DrawContext dc) - { + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Cube"; @@ -381,11 +342,10 @@ protected void initialize(DrawContext dc) } @Override - protected int drawShape(DrawContext dc, double radius) - { + protected int drawShape(DrawContext dc, double radius) { // Vertices of a cube, 2 units on each side, with the center of the bottom face on the origin. float[][] v = {{-1f, 1f, 0f}, {-1f, 1f, 2f}, {1f, 1f, 2f}, {1f, 1f, 0f}, - {-1f, -1f, 2f}, {1f, -1f, 2f}, {1f, -1f, 0f}, {-1f, -1f, 0f}}; + {-1f, -1f, 2f}, {1f, -1f, 2f}, {1f, -1f, 0f}, {-1f, -1f, 0f}}; // Array to group vertices into faces int[][] faces = {{0, 1, 2, 3}, {2, 5, 6, 3}, {1, 4, 5, 2}, {0, 7, 4, 1}, {0, 7, 6, 3}, {4, 7, 6, 5}}; @@ -397,12 +357,10 @@ protected int drawShape(DrawContext dc, double radius) gl.glBegin(GL2.GL_QUADS); - for (int i = 0; i < faces.length; i++) - { + for (int i = 0; i < faces.length; i++) { gl.glNormal3f(n[i][0], n[i][1], n[i][2]); - for (int j = 0; j < faces[0].length; j++) - { + for (int j = 0; j < faces[0].length; j++) { gl.glVertex3f(v[faces[i][j]][0], v[faces[i][j]][1], v[faces[i][j]][2]); } } @@ -412,16 +370,14 @@ protected int drawShape(DrawContext dc, double radius) return (8 + 4) * 3 * 4; // assume 8 verts, 4 normals, all of them 3 float coords } - protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) - { + protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) { Vec4 normal = dc.getGlobe().computeSurfaceNormalAtPoint(point); // This performs the same operation as Vec4.axisAngle() but with a "v2" of <0, 0, 1>. // Compute rotation angle GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!(normal.equals(Vec4.UNIT_Z) || normal.equals(Vec4.UNIT_NEGATIVE_Z))) - { + if (!(normal.equals(Vec4.UNIT_Z) || normal.equals(Vec4.UNIT_NEGATIVE_Z))) { Angle angle = Angle.fromRadians(Math.acos(normal.z)); // Compute the direction cosine factors that define the rotation axis double A = -normal.y; @@ -431,7 +387,7 @@ protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, // Rotate the cube so that one of the faces points north Position position = dc.getGlobe().computePositionFromPoint(point); Vec4 north = dc.getGlobe().computeNorthPointingTangentAtLocation(position.getLatitude(), - position.getLongitude()); + position.getLongitude()); Vec4 rotatedY = Vec4.UNIT_NEGATIVE_Y.transformBy3(Matrix.fromAxisAngle(angle, A / L, B / L, 0)); Angle northAngle = rotatedY.angleBetween3(north); @@ -441,14 +397,16 @@ protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, } // Apply heading, pitch, and roll - if (this.isApplyOrientation()) - { - if (marker.getHeading() != null) + if (this.isApplyOrientation()) { + if (marker.getHeading() != null) { gl.glRotated(-marker.getHeading().degrees, 0, 0, 1); - if (marker.getPitch() != null) + } + if (marker.getPitch() != null) { gl.glRotated(marker.getPitch().degrees, 1, 0, 0); - if (marker.getRoll() != null) + } + if (marker.getRoll() != null) { gl.glRotated(marker.getRoll().degrees, 0, 0, 1); + } } gl.glScaled(size, size, size); @@ -456,12 +414,13 @@ protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, } } - /** A cone marker shape. The cone can be oriented using heading and pitch. */ - protected static class Cone extends Shape - { + /** + * A cone marker shape. The cone can be oriented using heading and pitch. + */ + protected static class Cone extends Shape { + @Override - protected void initialize(DrawContext dc) - { + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Cone"; @@ -469,25 +428,22 @@ protected void initialize(DrawContext dc) this.isInitialized = true; } - protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) - { + protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) { // By default, the shape is normal to the globe (0 heading, 0 pitch, 0 roll) Vec4 orientation = dc.getGlobe().computeSurfaceNormalAtPoint(point); // Heading only applies to cone if pitch is also specified. A heading without pitch spins the cone // around its axis. A heading with pitch spins the cone, and then tilts it in the direction of the // heading. - if (this.isApplyOrientation() && marker.getPitch() != null) - { + if (this.isApplyOrientation() && marker.getPitch() != null) { orientation = this.computeOrientationVector(dc, point, orientation, - marker.getHeading() != null ? marker.getHeading() : Angle.ZERO, - marker.getPitch()); + marker.getHeading() != null ? marker.getHeading() : Angle.ZERO, + marker.getPitch()); } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!(orientation.equals(Vec4.UNIT_Z) || orientation.equals(Vec4.UNIT_NEGATIVE_Z))) - { + if (!(orientation.equals(Vec4.UNIT_Z) || orientation.equals(Vec4.UNIT_NEGATIVE_Z))) { // This code performs the same operation as Vec4.axisAngle() but with a "v2" of <0, 0, 1>. // Compute rotation angle Angle angle = Angle.fromRadians(Math.acos(orientation.z)); @@ -497,9 +453,7 @@ protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, double L = Math.sqrt(A * A + B * B); gl.glRotated(angle.degrees, A / L, B / L, 0); // rotate shape to proper heading and pitch - } - else if (orientation.equals(Vec4.UNIT_NEGATIVE_Z)) - { + } else if (orientation.equals(Vec4.UNIT_NEGATIVE_Z)) { gl.glRotated(180, 1, 0, 0); // rotate to point cone away from globe's surface } @@ -508,8 +462,7 @@ else if (orientation.equals(Vec4.UNIT_NEGATIVE_Z)) } @Override - protected int drawShape(DrawContext dc, double radius) - { + protected int drawShape(DrawContext dc, double radius) { int slices = 20; int stacks = 20; int loops = 2; @@ -522,12 +475,13 @@ protected int drawShape(DrawContext dc, double radius) } } - /** A cylinder marker shape. The cylinder can be oriented using heading and pitch. */ - protected static class Cylinder extends Shape - { + /** + * A cylinder marker shape. The cylinder can be oriented using heading and pitch. + */ + protected static class Cylinder extends Shape { + @Override - protected void initialize(DrawContext dc) - { + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Cylinder"; @@ -535,24 +489,21 @@ protected void initialize(DrawContext dc) this.isInitialized = true; } - protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) - { + protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) { Vec4 orientation = dc.getGlobe().computeSurfaceNormalAtPoint(point); // Heading only applies to cylinder if pitch is also specified. A heading without pitch spins the cylinder // around its axis. A heading with pitch spins the cylinder, and then tilts it in the direction of the // heading. - if (this.isApplyOrientation() && marker.getPitch() != null) - { + if (this.isApplyOrientation() && marker.getPitch() != null) { orientation = this.computeOrientationVector(dc, point, orientation, - marker.getHeading() != null ? marker.getHeading() : Angle.ZERO, - marker.getPitch()); + marker.getHeading() != null ? marker.getHeading() : Angle.ZERO, + marker.getPitch()); } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (!(orientation.equals(Vec4.UNIT_Z) || orientation.equals(Vec4.UNIT_NEGATIVE_Z))) - { + if (!(orientation.equals(Vec4.UNIT_Z) || orientation.equals(Vec4.UNIT_NEGATIVE_Z))) { // This performs the same operation as Vec4.axisAngle() but with a "v2" of <0, 0, 1>. // Compute rotation angle Angle angle = Angle.fromRadians(Math.acos(orientation.z)); @@ -569,8 +520,7 @@ protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, } @Override - protected int drawShape(DrawContext dc, double radius) - { + protected int drawShape(DrawContext dc, double radius) { int slices = 20; int stacks = 1; int loops = 1; @@ -588,12 +538,13 @@ protected int drawShape(DrawContext dc, double radius) } } - /** A line that indicates heading. This shape indicates heading; it ignores pitch and roll. */ - protected static class HeadingLine extends Shape - { + /** + * A line that indicates heading. This shape indicates heading; it ignores pitch and roll. + */ + protected static class HeadingLine extends Shape { + @Override - protected void initialize(DrawContext dc) - { + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Heading Line"; @@ -601,36 +552,33 @@ protected void initialize(DrawContext dc) this.isInitialized = true; } - protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) - { + protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. MarkerAttributes attrs = marker.getAttributes(); - if (marker.getHeading() == null) + if (marker.getHeading() == null) { return; + } // Apply heading material if different from marker's if (!dc.isPickingMode() && attrs.getHeadingMaterial() != null - && !attrs.getHeadingMaterial().equals(attrs.getMaterial())) - { - if (attrs.getOpacity() < 1) + && !attrs.getHeadingMaterial().equals(attrs.getMaterial())) { + if (attrs.getOpacity() < 1) { attrs.getHeadingMaterial().apply(gl, GL2.GL_FRONT, (float) attrs.getOpacity()); - else + } else { attrs.getHeadingMaterial().apply(gl, GL2.GL_FRONT); + } } // Orient the unit shape to lie parallel to the globe's surface at its position and oriented to the // specified heading. - if (dc.is2DGlobe()) - { + if (dc.is2DGlobe()) { Vec4 npt = dc.getGlobe().computeNorthPointingTangentAtLocation(marker.getPosition().getLatitude(), - marker.getPosition().getLongitude()); + marker.getPosition().getLongitude()); //noinspection SuspiciousNameCombination double npta = Math.atan2(npt.x, npt.y); gl.glRotated(-marker.getHeading().degrees - npta * 180 / Math.PI, 0, 0, 1); - } - else - { + } else { gl.glRotated(marker.getPosition().getLongitude().degrees, 0, 1, 0); gl.glRotated(-marker.getPosition().getLatitude().degrees, 1, 0, 0); gl.glRotated(-marker.getHeading().degrees, 0, 0, 1); @@ -642,13 +590,13 @@ protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, // Restore the marker material if the heading material was applied if (!dc.isPickingMode() && attrs.getHeadingMaterial() != null - && !attrs.getHeadingMaterial().equals(attrs.getMaterial())) + && !attrs.getHeadingMaterial().equals(attrs.getMaterial())) { attrs.apply(dc); + } } @Override - protected int drawShape(DrawContext dc, double radius) - { + protected int drawShape(DrawContext dc, double radius) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_LINE_STRIP); gl.glNormal3f(0f, 0f, 1f); @@ -660,12 +608,13 @@ protected int drawShape(DrawContext dc, double radius) } } - /** An arrow that indicates heading. This shape indicates heading; it ignores pitch and roll. */ - protected static class HeadingArrow extends Shape - { + /** + * An arrow that indicates heading. This shape indicates heading; it ignores pitch and roll. + */ + protected static class HeadingArrow extends Shape { + @Override - protected void initialize(DrawContext dc) - { + protected void initialize(DrawContext dc) { super.initialize(dc); this.name = "Heading Arrow"; @@ -674,36 +623,33 @@ protected void initialize(DrawContext dc) this.isInitialized = true; } - protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) - { + protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, int[] dlResource) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. MarkerAttributes attrs = marker.getAttributes(); - if (marker.getHeading() == null) + if (marker.getHeading() == null) { return; + } // Apply heading material if different from marker's if (!dc.isPickingMode() && attrs.getHeadingMaterial() != null - && !attrs.getHeadingMaterial().equals(attrs.getMaterial())) - { - if (attrs.getOpacity() < 1) + && !attrs.getHeadingMaterial().equals(attrs.getMaterial())) { + if (attrs.getOpacity() < 1) { attrs.getHeadingMaterial().apply(gl, GL2.GL_FRONT, (float) attrs.getOpacity()); - else + } else { attrs.getHeadingMaterial().apply(gl, GL2.GL_FRONT); + } } // Orient the unit shape to lie parallel to the globe's surface at its position and oriented to the // specified heading. - if (dc.is2DGlobe()) - { + if (dc.is2DGlobe()) { Vec4 npt = dc.getGlobe().computeNorthPointingTangentAtLocation(marker.getPosition().getLatitude(), - marker.getPosition().getLongitude()); + marker.getPosition().getLongitude()); //noinspection SuspiciousNameCombination double npta = Math.atan2(npt.x, npt.y); gl.glRotated(-marker.getHeading().degrees - npta * 180 / Math.PI, 0, 0, 1); - } - else - { + } else { gl.glRotated(marker.getPosition().getLongitude().degrees, 0, 1, 0); gl.glRotated(-marker.getPosition().getLatitude().degrees, 1, 0, 0); gl.glRotated(-marker.getHeading().degrees, 0, 0, 1); @@ -715,13 +661,13 @@ protected void doRender(DrawContext dc, Marker marker, Vec4 point, double size, // Restore the marker material if the heading material was applied if (!dc.isPickingMode() && attrs.getHeadingMaterial() != null - && !attrs.getHeadingMaterial().equals(attrs.getMaterial())) + && !attrs.getHeadingMaterial().equals(attrs.getMaterial())) { attrs.apply(dc); + } } @Override - protected int drawShape(DrawContext dc, double radius) - { + protected int drawShape(DrawContext dc, double radius) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glBegin(GL2.GL_POLYGON); gl.glNormal3f(0f, 0f, 1f); diff --git a/src/gov/nasa/worldwind/render/markers/Marker.java b/src/gov/nasa/worldwind/render/markers/Marker.java index 014a85bc2c..2ed523a83a 100644 --- a/src/gov/nasa/worldwind/render/markers/Marker.java +++ b/src/gov/nasa/worldwind/render/markers/Marker.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.markers; import gov.nasa.worldwind.geom.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: Marker.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Marker -{ +public interface Marker { + void render(DrawContext dc, Vec4 point, double radius, boolean isRelative); void render(DrawContext dc, Vec4 point, double radius); @@ -44,7 +43,7 @@ public interface Marker * Specifies the heading of this marker. * * @param heading the marker heading in degrees clockwise from North. May be null, in which case no heading is - * applied. + * applied. */ void setHeading(Angle heading); @@ -61,8 +60,7 @@ public interface Marker * pitch, the pitch will be ignored. * * @param pitch the marker pitch in degrees from a surface normal. Positive values result in a rotation toward the - * marker heading, or toward North if there is no heading. May be null, in which case no pitch is - * applied. + * marker heading, or toward North if there is no heading. May be null, in which case no pitch is applied. */ void setPitch(Angle pitch); diff --git a/src/gov/nasa/worldwind/render/markers/MarkerAttributes.java b/src/gov/nasa/worldwind/render/markers/MarkerAttributes.java index a1013df1b8..1f742c1211 100644 --- a/src/gov/nasa/worldwind/render/markers/MarkerAttributes.java +++ b/src/gov/nasa/worldwind/render/markers/MarkerAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.markers; import gov.nasa.worldwind.render.Material; @@ -13,8 +12,8 @@ * @author tag * @version $Id: MarkerAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MarkerAttributes -{ +public interface MarkerAttributes { + Material getMaterial(); void setMaterial(Material material); diff --git a/src/gov/nasa/worldwind/render/markers/MarkerRenderer.java b/src/gov/nasa/worldwind/render/markers/MarkerRenderer.java index 641167b2d8..a47508f6b0 100644 --- a/src/gov/nasa/worldwind/render/markers/MarkerRenderer.java +++ b/src/gov/nasa/worldwind/render/markers/MarkerRenderer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.markers; import gov.nasa.worldwind.avlist.AVKey; @@ -23,8 +22,8 @@ * @author tag * @version $Id: MarkerRenderer.java 2325 2014-09-17 21:55:48Z tgaskins $ */ -public class MarkerRenderer -{ +public class MarkerRenderer { + private double elevation = 10d; private boolean overrideMarkerElevation = false; private boolean keepSeparated = true; @@ -35,57 +34,46 @@ public class MarkerRenderer private MarkerAttributes previousAttributes; // used only by drawSeparated and drawMarker protected PickSupport pickSupport = new PickSupport(); - public double getElevation() - { + public double getElevation() { return elevation; } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.elevation = elevation; } - public boolean isOverrideMarkerElevation() - { + public boolean isOverrideMarkerElevation() { return overrideMarkerElevation; } - public void setOverrideMarkerElevation(boolean overrideMarkerElevation) - { + public void setOverrideMarkerElevation(boolean overrideMarkerElevation) { this.overrideMarkerElevation = overrideMarkerElevation; } - public boolean isKeepSeparated() - { + public boolean isKeepSeparated() { return keepSeparated; } - public void setKeepSeparated(boolean keepSeparated) - { + public void setKeepSeparated(boolean keepSeparated) { this.keepSeparated = keepSeparated; } - public boolean isEnablePickSizeReturn() - { + public boolean isEnablePickSizeReturn() { return enablePickSizeReturn; } - public void setEnablePickSizeReturn(boolean enablePickSizeReturn) - { + public void setEnablePickSizeReturn(boolean enablePickSizeReturn) { this.enablePickSizeReturn = enablePickSizeReturn; } - public void render(DrawContext dc, Iterable markers) - { - if (dc == null) - { + public void render(DrawContext dc, Iterable markers) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (markers == null) - { + if (markers == null) { String message = Logging.getMessage("nullValue.MarkerListIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -97,33 +85,28 @@ public void render(DrawContext dc, Iterable markers) //**************************************************************// //******************** Rendering *****************************// //**************************************************************// - - protected void draw(DrawContext dc, Iterable markers) - { - if (this.isKeepSeparated()) + protected void draw(DrawContext dc, Iterable markers) { + if (this.isKeepSeparated()) { this.drawSeparated(dc, markers); - else + } else { this.drawAll(dc, markers); + } } - protected void drawSeparated(DrawContext dc, Iterable markers) - { + protected void drawSeparated(DrawContext dc, Iterable markers) { List markerList; - if (markers instanceof List) - { + if (markers instanceof List) { markerList = (List) markers; - } - else - { + } else { markerList = new ArrayList(); - for (Marker m : markers) - { + for (Marker m : markers) { markerList.add(m); } } - if (markerList.size() == 0) + if (markerList.size() == 0) { return; + } Layer parentLayer = dc.getCurrentLayer(); Vec4 eyePoint = dc.getView().getEyePoint(); @@ -132,34 +115,39 @@ protected void drawSeparated(DrawContext dc, Iterable markers) Vec4 p1 = this.computeSurfacePoint(dc, m1.getPosition()); double r1 = this.computeMarkerRadius(dc, p1, m1); - if (this.intersectsFrustum(dc, p1, r1)) + if (this.intersectsFrustum(dc, p1, r1)) { dc.addOrderedRenderable(new OrderedMarker(0, m1, p1, r1, parentLayer, eyePoint.distanceTo3(p1))); + } - if (markerList.size() < 2) + if (markerList.size() < 2) { return; + } int im2 = markerList.size() - 1; Marker m2 = markerList.get(im2); Vec4 p2 = this.computeSurfacePoint(dc, m2.getPosition()); double r2 = this.computeMarkerRadius(dc, p2, m2); - if (this.intersectsFrustum(dc, p2, r2)) + if (this.intersectsFrustum(dc, p2, r2)) { dc.addOrderedRenderable(new OrderedMarker(im2, m2, p2, r2, parentLayer, eyePoint.distanceTo3(p2))); + } - if (markerList.size() < 3) + if (markerList.size() < 3) { return; + } this.drawInBetweenMarkers(dc, 0, p1, r1, im2, p2, r2, markerList, parentLayer, eyePoint); } private void drawInBetweenMarkers(DrawContext dc, int im1, Vec4 p1, double r1, int im2, Vec4 p2, double r2, - List markerList, Layer parentLayer, Vec4 eyePoint) - { - if (im2 == im1 + 1) + List markerList, Layer parentLayer, Vec4 eyePoint) { + if (im2 == im1 + 1) { return; + } - if (p1.distanceTo3(p2) <= r1 + r2) + if (p1.distanceTo3(p2) <= r1 + r2) { return; + } int im = (im1 + im2) / 2; Marker m = markerList.get(im); @@ -167,36 +155,34 @@ private void drawInBetweenMarkers(DrawContext dc, int im1, Vec4 p1, double r1, i double r = this.computeMarkerRadius(dc, p, m); boolean b1 = false, b2 = false; - if (p.distanceTo3(p1) > r + r1) - { + if (p.distanceTo3(p1) > r + r1) { this.drawInBetweenMarkers(dc, im1, p1, r1, im, p, r, markerList, parentLayer, eyePoint); b1 = true; } - if (p.distanceTo3(p2) > r + r2) - { + if (p.distanceTo3(p2) > r + r2) { this.drawInBetweenMarkers(dc, im, p, r, im2, p2, r2, markerList, parentLayer, eyePoint); b2 = true; } - if (b1 && b2 && this.intersectsFrustum(dc, p, r)) + if (b1 && b2 && this.intersectsFrustum(dc, p, r)) { dc.addOrderedRenderable(new OrderedMarker(im, m, p, r, parentLayer, eyePoint.distanceTo3(p))); + } } - private void drawMarker(DrawContext dc, int index, Marker marker, Vec4 point, double radius) - { + private void drawMarker(DrawContext dc, int index, Marker marker, Vec4 point, double radius) { // This method is called from OrderedMarker's render and pick methods. We don't perform culling here, because // the marker has already been culled against the appropriate frustum prior adding OrderedMarker to the draw // context. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { java.awt.Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); PickedObject po = new PickedObject(colorCode, marker, marker.getPosition(), false); po.setValue(AVKey.PICKED_OBJECT_ID, index); - if (this.enablePickSizeReturn) + if (this.enablePickSizeReturn) { po.setValue(AVKey.PICKED_OBJECT_SIZE, 2 * radius); + } this.pickSupport.addPickableObject(po); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); @@ -212,15 +198,12 @@ private void drawMarker(DrawContext dc, int index, Marker marker, Vec4 point, do marker.render(dc, point, radius); } - protected void computeSurfacePoints(DrawContext dc, Iterable markers) - { + protected void computeSurfacePoints(DrawContext dc, Iterable markers) { surfacePoints.clear(); - for (Marker marker : markers) - { + for (Marker marker : markers) { // If the marker is null, add a null reference to the surfacePoints cache array so that it is // the same size as the marker iterator. - if (marker == null) - { + if (marker == null) { surfacePoints.add(null); continue; } @@ -230,8 +213,7 @@ protected void computeSurfacePoints(DrawContext dc, Iterable m // Check to see that the point is within the frustum. If it is not, place a null reference in the // surfacePoints array. This will let the drawAll method know not to render it on the 2nd pass. We always // cull against the view frustum here, because these points are used during both picking and rendering. - if (!dc.getView().getFrustumInModelCoordinates().contains(point)) - { + if (!dc.getView().getFrustumInModelCoordinates().contains(point)) { surfacePoints.add(null); continue; } @@ -240,68 +222,60 @@ protected void computeSurfacePoints(DrawContext dc, Iterable m } } - protected void drawAll(DrawContext dc, Iterable markers) - { + protected void drawAll(DrawContext dc, Iterable markers) { Layer parentLayer = dc.getCurrentLayer(); Vec4 eyePoint = dc.getView().getEyePoint(); // If this is a new frame, recompute surface points. - if (dc.getFrameTimeStamp() != this.frameTimeStamp || dc.isContinuous2DGlobe()) - { + if (dc.getFrameTimeStamp() != this.frameTimeStamp || dc.isContinuous2DGlobe()) { this.frameTimeStamp = dc.getFrameTimeStamp(); this.computeSurfacePoints(dc, markers); } Iterator markerIterator = markers.iterator(); - for (int index = 0; markerIterator.hasNext(); index++) - { + for (int index = 0; markerIterator.hasNext(); index++) { Marker marker = markerIterator.next(); Vec4 point = this.surfacePoints.get(index); // TODO: check performance of this buffer access // The surface point is null if the marker in this position is null or if the surface point is not in the // view frustum. - if (point == null) + if (point == null) { continue; + } double radius = this.computeMarkerRadius(dc, point, marker); // If we're in picking mode, cull the marker against the draw context's pick frustums. At this point we've // only culled against the viewing frustum. - if (dc.isPickingMode() && !this.intersectsFrustum(dc, point, radius)) + if (dc.isPickingMode() && !this.intersectsFrustum(dc, point, radius)) { continue; + } dc.addOrderedRenderable(new OrderedMarker(index, marker, point, radius, parentLayer, - eyePoint.distanceTo3(point))); + eyePoint.distanceTo3(point))); } } - protected void begin(DrawContext dc) - { + protected void begin(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Vec4 cameraPosition = dc.getView().getEyePoint(); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.beginPicking(dc); gl.glPushAttrib(GL2.GL_ENABLE_BIT | GL2.GL_CURRENT_BIT | GL2.GL_TRANSFORM_BIT); gl.glDisable(GL2.GL_COLOR_MATERIAL); - } - else - { + } else { gl.glPushAttrib(GL2.GL_ENABLE_BIT | GL2.GL_CURRENT_BIT | GL2.GL_LIGHTING_BIT | GL2.GL_TRANSFORM_BIT - | GL2.GL_COLOR_BUFFER_BIT); + | GL2.GL_COLOR_BUFFER_BIT); float[] lightPosition = new float[4]; - if (dc.is2DGlobe()) - { + if (dc.is2DGlobe()) { lightPosition[0] = 0.2f; lightPosition[1] = -0.5f; lightPosition[2] = 1f; lightPosition[3] = 0f; - } - else - { + } else { lightPosition[0] = (float) cameraPosition.x * 2; lightPosition[1] = (float) cameraPosition.y() / 2; lightPosition[2] = (float) cameraPosition.z(); @@ -337,19 +311,15 @@ protected void begin(DrawContext dc) this.previousAttributes = null; } - protected void end(DrawContext dc) - { + protected void end(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.endPicking(dc); - } - else - { + } else { gl.glDisable(GL2.GL_LIGHT1); gl.glEnable(GL2.GL_LIGHT0); gl.glDisable(GL2.GL_LIGHTING); @@ -362,41 +332,41 @@ protected void end(DrawContext dc) //**************************************************************// //******************** Rendering Utilities *******************// //**************************************************************// - - protected boolean intersectsFrustum(DrawContext dc, Vec4 point, double radius) - { - if (dc.isPickingMode()) + protected boolean intersectsFrustum(DrawContext dc, Vec4 point, double radius) { + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(new Sphere(point, radius)); + } // TODO: determine if culling markers against center point is intentional. return dc.getView().getFrustumInModelCoordinates().contains(point); } - protected Vec4 computeSurfacePoint(DrawContext dc, Position pos) - { + protected Vec4 computeSurfacePoint(DrawContext dc, Position pos) { double ve = dc.getVerticalExaggeration(); - if (!this.overrideMarkerElevation) + if (!this.overrideMarkerElevation) { return dc.getGlobe().computePointFromPosition(pos, dc.is2DGlobe() ? 0 : pos.getElevation() * ve); + } // Compute points that are at the renderer-specified elevation double effectiveElevation = dc.is2DGlobe() ? 0 : this.elevation; Vec4 point = dc.getSurfaceGeometry().getSurfacePoint(pos.getLatitude(), pos.getLongitude(), - effectiveElevation * ve); - if (point != null) + effectiveElevation * ve); + if (point != null) { return point; + } // Point is outside the current sector geometry, so compute it from the globe. return dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), effectiveElevation * ve); } - protected double computeMarkerRadius(DrawContext dc, Vec4 point, Marker marker) - { + protected double computeMarkerRadius(DrawContext dc, Vec4 point, Marker marker) { double d = point.distanceTo3(dc.getView().getEyePoint()); double radius = marker.getAttributes().getMarkerPixels() * dc.getView().computePixelSizeAtDistance(d); - if (radius < marker.getAttributes().getMinMarkerSize() && marker.getAttributes().getMinMarkerSize() > 0) + if (radius < marker.getAttributes().getMinMarkerSize() && marker.getAttributes().getMinMarkerSize() > 0) { radius = marker.getAttributes().getMinMarkerSize(); - else if (radius > marker.getAttributes().getMaxMarkerSize()) + } else if (radius > marker.getAttributes().getMaxMarkerSize()) { radius = marker.getAttributes().getMaxMarkerSize(); + } return radius; } @@ -404,9 +374,8 @@ else if (radius > marker.getAttributes().getMaxMarkerSize()) //**************************************************************// //******************** Ordered Renderable ********************// //**************************************************************// + protected class OrderedMarker implements OrderedRenderable { - protected class OrderedMarker implements OrderedRenderable - { protected int index; protected Marker marker; protected Vec4 point; @@ -414,8 +383,7 @@ protected class OrderedMarker implements OrderedRenderable protected Layer layer; protected double eyeDistance; - public OrderedMarker(int index, Marker marker, Vec4 point, double radius, Layer layer, double eyeDistance) - { + public OrderedMarker(int index, Marker marker, Vec4 point, double radius, Layer layer, double eyeDistance) { this.index = index; this.marker = marker; this.point = point; @@ -424,62 +392,46 @@ public OrderedMarker(int index, Marker marker, Vec4 point, double radius, Layer this.eyeDistance = eyeDistance; } - public MarkerRenderer getRenderer() - { + public MarkerRenderer getRenderer() { return MarkerRenderer.this; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { MarkerRenderer.this.begin(dc); // Calls pickSupport.beginPicking when in picking mode. - try - { + try { MarkerRenderer.this.pickOrderedMarkers(dc, this); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, Logging.getMessage("generic.ExceptionWhilePickingMarker", this), - e); - } - finally - { + e); + } finally { MarkerRenderer.this.end(dc); // Calls pickSupport.endPicking when in picking mode. MarkerRenderer.this.pickSupport.resolvePick(dc, pickPoint, this.layer); // Also clears the pick list. } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { MarkerRenderer.this.begin(dc); - try - { + try { MarkerRenderer.this.drawOrderedMarkers(dc, this); - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, Logging.getMessage("generic.ExceptionWhileRenderingMarker", this), - e); - } - finally - { + e); + } finally { MarkerRenderer.this.end(dc); } } } - protected void drawOrderedMarkers(DrawContext dc, OrderedMarker uMarker) - { + protected void drawOrderedMarkers(DrawContext dc, OrderedMarker uMarker) { this.drawMarker(dc, uMarker.index, uMarker.marker, uMarker.point, uMarker.radius); // Draw as many as we can in a batch to save ogl state switching. Object next = dc.peekOrderedRenderables(); - while (next != null && next instanceof OrderedMarker && ((OrderedMarker) next).getRenderer() == this) - { + while (next != null && next instanceof OrderedMarker && ((OrderedMarker) next).getRenderer() == this) { dc.pollOrderedRenderables(); // take it off the queue OrderedMarker om = (OrderedMarker) next; @@ -489,15 +441,13 @@ protected void drawOrderedMarkers(DrawContext dc, OrderedMarker uMarker) } } - protected void pickOrderedMarkers(DrawContext dc, OrderedMarker uMarker) - { + protected void pickOrderedMarkers(DrawContext dc, OrderedMarker uMarker) { this.drawMarker(dc, uMarker.index, uMarker.marker, uMarker.point, uMarker.radius); // Draw as many as we can in a batch to save ogl state switching. Object next = dc.peekOrderedRenderables(); while (next != null && next instanceof OrderedMarker && ((OrderedMarker) next).getRenderer() == this - && ((OrderedMarker) next).layer == uMarker.layer) - { + && ((OrderedMarker) next).layer == uMarker.layer) { dc.pollOrderedRenderables(); // take it off the queue OrderedMarker om = (OrderedMarker) next; diff --git a/src/gov/nasa/worldwind/render/markers/MarkerShape.java b/src/gov/nasa/worldwind/render/markers/MarkerShape.java index 0104882cd6..f8fd4d28d8 100644 --- a/src/gov/nasa/worldwind/render/markers/MarkerShape.java +++ b/src/gov/nasa/worldwind/render/markers/MarkerShape.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.render.markers; import gov.nasa.worldwind.render.DrawContext; @@ -13,10 +12,10 @@ * @author tag * @version $Id: MarkerShape.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MarkerShape -{ +public interface MarkerShape { + String getShapeType(); - + void render(DrawContext dc, Marker marker, Vec4 point, double radius); void render(DrawContext dc, Marker marker, Vec4 point, double radius, boolean isRelative); diff --git a/src/gov/nasa/worldwind/retrieve/AbstractRetrievalPostProcessor.java b/src/gov/nasa/worldwind/retrieve/AbstractRetrievalPostProcessor.java index 211c0d5032..19ca252226 100644 --- a/src/gov/nasa/worldwind/retrieve/AbstractRetrievalPostProcessor.java +++ b/src/gov/nasa/worldwind/retrieve/AbstractRetrievalPostProcessor.java @@ -25,11 +25,15 @@ * @author Tom Gaskins * @version $Id: AbstractRetrievalPostProcessor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractRetrievalPostProcessor implements RetrievalPostProcessor -{ - /** Holds miscellaneous parameters examined by this and subclasses. */ +public abstract class AbstractRetrievalPostProcessor implements RetrievalPostProcessor { + + /** + * Holds miscellaneous parameters examined by this and subclasses. + */ protected AVList avList; - /** The retriever associated with the post-processor. Only non-null after {@link #run(Retriever)} is called. */ + /** + * The retriever associated with the post-processor. Only non-null after {@link #run(Retriever)} is called. + */ protected Retriever retriever; /** @@ -40,9 +44,10 @@ public abstract class AbstractRetrievalPostProcessor implements RetrievalPostPro */ abstract protected File doGetOutputFile(); - /** Create a default post-processor. */ - public AbstractRetrievalPostProcessor() - { + /** + * Create a default post-processor. + */ + public AbstractRetrievalPostProcessor() { } /** @@ -50,8 +55,7 @@ public AbstractRetrievalPostProcessor() * * @param avList an attribute-value list with values that might be used during post-processing. */ - public AbstractRetrievalPostProcessor(AVList avList) - { + public AbstractRetrievalPostProcessor(AVList avList) { this.avList = avList; } @@ -61,14 +65,12 @@ public AbstractRetrievalPostProcessor(AVList avList) * @param retriever the retriever to associate with the post-processor. * * @return a buffer containing the downloaded data, perhaps converted during content handling. null is returned if a - * fatal problem occurred during post-processing. + * fatal problem occurred during post-processing. * * @throws IllegalArgumentException if the retriever is null. */ - public ByteBuffer run(Retriever retriever) - { - if (retriever == null) - { + public ByteBuffer run(Retriever retriever) { + if (retriever == null) { String message = Logging.getMessage("nullValue.RetrieverIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,14 +78,12 @@ public ByteBuffer run(Retriever retriever) this.retriever = retriever; - if (!retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) - { + if (!retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) { this.handleUnsuccessfulRetrieval(); return null; } - if (!this.validateResponseCode()) - { + if (!this.validateResponseCode()) { this.handleInvalidResponseCode(); return null; } @@ -96,8 +96,7 @@ public ByteBuffer run(Retriever retriever) * * @return the retriever associated with the post-processor, or null if no retriever is associated. */ - public Retriever getRetriever() - { + public Retriever getRetriever() { return this.retriever; } @@ -106,10 +105,10 @@ public Retriever getRetriever() * subclasses to handle special error cases. The default implementation calls {@link #markResourceAbsent()} if the * retrieval state is {@link Retriever#RETRIEVER_STATE_ERROR}. */ - protected void handleUnsuccessfulRetrieval() - { - if (this.getRetriever().getState().equals(Retriever.RETRIEVER_STATE_ERROR)) + protected void handleUnsuccessfulRetrieval() { + if (this.getRetriever().getState().equals(Retriever.RETRIEVER_STATE_ERROR)) { this.markResourceAbsent(); + } } /** @@ -117,14 +116,10 @@ protected void handleUnsuccessfulRetrieval() * * @return a buffer containing the downloaded data, perhaps converted during content handling. */ - protected ByteBuffer handleSuccessfulRetrieval() - { - try - { + protected ByteBuffer handleSuccessfulRetrieval() { + try { return this.handleContent(); - } - catch (Exception e) - { + } catch (Exception e) { this.handleContentException(e); return null; } @@ -134,17 +129,17 @@ protected ByteBuffer handleSuccessfulRetrieval() * Checks the retrieval response code. * * @return true if the response code is the OK value for the protocol, e.g., ({@link HttpURLConnection#HTTP_OK} for - * HTTP protocol), otherwise false. + * HTTP protocol), otherwise false. */ - protected boolean validateResponseCode() - { + protected boolean validateResponseCode() { //noinspection SimplifiableIfStatement - if (this.getRetriever() instanceof HTTPRetriever) + if (this.getRetriever() instanceof HTTPRetriever) { return this.validateHTTPResponseCode(); - else if (this.getRetriever() instanceof JarRetriever) + } else if (this.getRetriever() instanceof JarRetriever) { return this.validateJarResponseCode(); - else if (this.getRetriever() instanceof LocalRasterServerRetriever) + } else if (this.getRetriever() instanceof LocalRasterServerRetriever) { return true; + } return false; } @@ -155,8 +150,7 @@ else if (this.getRetriever() instanceof LocalRasterServerRetriever) * * @return true if the response code is {@link HttpURLConnection#HTTP_OK}, otherwise false. */ - protected boolean validateHTTPResponseCode() - { + protected boolean validateHTTPResponseCode() { HTTPRetriever htr = (HTTPRetriever) this.getRetriever(); return htr.getResponseCode() == HttpURLConnection.HTTP_OK; @@ -168,8 +162,7 @@ protected boolean validateHTTPResponseCode() * * @return true if the response code is {@link HttpURLConnection#HTTP_OK}, otherwise false. */ - protected boolean validateJarResponseCode() - { + protected boolean validateJarResponseCode() { JarRetriever htr = (JarRetriever) this.getRetriever(); return htr.getResponseCode() == HttpURLConnection.HTTP_OK; // Re-using the HTTP response code for OK @@ -180,23 +173,21 @@ protected boolean validateJarResponseCode() * default implementation calls {@link #markResourceAbsent()} and logs the contents of the retrieval buffer if it * contains content of type "text". */ - protected void handleInvalidResponseCode() - { + protected void handleInvalidResponseCode() { this.markResourceAbsent(); - if (this.isWMSException()) + if (this.isWMSException()) { this.handleWMSExceptionContent(); - - else if (this.isPrimaryContentType("text", this.getRetriever().getContentType())) + } else if (this.isPrimaryContentType("text", this.getRetriever().getContentType())) { this.logTextBuffer(this.getRetriever().getBuffer()); // the buffer might contain error info, so log it + } } /** * Marks the retrieval target absent. Subclasses should override this method if they keep track of absent-resources. * The default implementation does nothing. */ - protected void markResourceAbsent() - { + protected void markResourceAbsent() { } /** @@ -206,12 +197,11 @@ protected void markResourceAbsent() * of null. * * @return true if the buffer was saved, false if the output file could not be determined or already exists and not - * overwritten. + * overwritten. * * @throws IOException if an IO error occurs while attempting to save the buffer. */ - protected boolean saveBuffer() throws IOException - { + protected boolean saveBuffer() throws IOException { return this.saveBuffer(null); } @@ -222,19 +212,20 @@ protected boolean saveBuffer() throws IOException * @param buffer the buffer to save. * * @return true if the buffer was saved, false if the output file could not be determined or already exists and not - * overwritten. + * overwritten. * * @throws IOException if an IO error occurred when attempting to save the buffer. */ - protected boolean saveBuffer(ByteBuffer buffer) throws IOException - { + protected boolean saveBuffer(ByteBuffer buffer) throws IOException { File outFile = this.getOutputFile(); - if (outFile == null) + if (outFile == null) { return false; + } - if (outFile.exists() && !this.overwriteExistingFile()) + if (outFile.exists() && !this.overwriteExistingFile()) { return false; + } synchronized (this.getFileLock()) // synchronize with read of file in another class { @@ -249,12 +240,12 @@ protected boolean saveBuffer(ByteBuffer buffer) throws IOException * * @return the output file, or null if a file could not be determined. */ - protected File getOutputFile() - { + protected File getOutputFile() { File outFile = this.doGetOutputFile(); - if (outFile != null && this.isDeleteOnExit(outFile)) + if (outFile != null && this.isDeleteOnExit(outFile)) { outFile.deleteOnExit(); + } return outFile; } @@ -265,8 +256,7 @@ protected File getOutputFile() * * @return true if an existing file should be overwritten, otherwise false. */ - protected boolean overwriteExistingFile() - { + protected boolean overwriteExistingFile() { return false; } @@ -278,8 +268,7 @@ protected boolean overwriteExistingFile() * * @return true if the output file's delete-on-exit flag should be set, otherwise false. */ - protected boolean isDeleteOnExit(File outFile) - { + protected boolean isDeleteOnExit(File outFile) { return !outFile.exists() && this.avList != null && this.avList.getValue(AVKey.DELETE_CACHE_ON_EXIT) != null; } @@ -290,25 +279,24 @@ protected boolean isDeleteOnExit(File outFile) * * @return an object to use for read/write synchronization, or null if no lock is needed. */ - protected Object getFileLock() - { + protected Object getFileLock() { return this; } - protected boolean isPrimaryContentType(String typeOfContent, String contentType) - { - if (WWUtil.isEmpty(contentType) || WWUtil.isEmpty(typeOfContent)) + protected boolean isPrimaryContentType(String typeOfContent, String contentType) { + if (WWUtil.isEmpty(contentType) || WWUtil.isEmpty(typeOfContent)) { return false; + } return contentType.trim().toLowerCase().startsWith(typeOfContent); } - protected boolean isWMSException() - { + protected boolean isWMSException() { String contentType = this.getRetriever().getContentType(); - if (WWUtil.isEmpty(contentType)) + if (WWUtil.isEmpty(contentType)) { return false; + } return contentType.trim().equalsIgnoreCase("application/vnd.ogc.se_xml"); } @@ -322,38 +310,41 @@ protected boolean isWMSException() * * @throws IOException if an IO error occurs while processing the data. */ - protected ByteBuffer handleContent() throws IOException - { + protected ByteBuffer handleContent() throws IOException { String contentType = this.getRetriever().getContentType(); - if (WWUtil.isEmpty(contentType)) - { + if (WWUtil.isEmpty(contentType)) { // Try to determine the content type from the URL's suffix, if any. String suffix = WWIO.getSuffix(this.getRetriever().getName().split(";")[0]); - if (!WWUtil.isEmpty(suffix)) + if (!WWUtil.isEmpty(suffix)) { contentType = WWIO.makeMimeTypeForSuffix(suffix); + } - if (WWUtil.isEmpty(contentType)) - { + if (WWUtil.isEmpty(contentType)) { Logging.logger().severe(Logging.getMessage("nullValue.ContentTypeIsNullOrEmpty")); return null; } } contentType = contentType.trim().toLowerCase(); - if (this.isWMSException()) + if (this.isWMSException()) { return this.handleWMSExceptionContent(); + } - if (contentType.contains("zip")) + if (contentType.contains("zip")) { return this.handleZipContent(); + } - if (this.isPrimaryContentType("text", contentType)) + if (this.isPrimaryContentType("text", contentType)) { return this.handleTextContent(); + } - if (this.isPrimaryContentType("image", contentType)) + if (this.isPrimaryContentType("image", contentType)) { return this.handleImageContent(); + } - if (this.isPrimaryContentType("application", contentType)) + if (this.isPrimaryContentType("application", contentType)) { return this.handleApplicationContent(); + } return this.handleUnknownContentType(); } @@ -364,19 +355,15 @@ protected ByteBuffer handleContent() throws IOException * * @param e the exception to handle. */ - protected void handleContentException(Exception e) - { - if (e instanceof ClosedByInterruptException) - { + protected void handleContentException(Exception e) { + if (e instanceof ClosedByInterruptException) { Logging.logger().log(java.util.logging.Level.FINE, - Logging.getMessage("generic.OperationCancelled", - "retrieval post-processing for " + this.getRetriever().getName()), e); - } - else if (e instanceof IOException) - { + Logging.getMessage("generic.OperationCancelled", + "retrieval post-processing for " + this.getRetriever().getName()), e); + } else if (e instanceof IOException) { this.markResourceAbsent(); Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("generic.ExceptionWhileSavingRetreivedData", this.getRetriever().getName()), e); + Logging.getMessage("generic.ExceptionWhileSavingRetreivedData", this.getRetriever().getName()), e); } } @@ -386,10 +373,9 @@ else if (e instanceof IOException) * * @return null if no further processing should occur, otherwise the retrieved data, perhaps transformed. */ - protected ByteBuffer handleUnknownContentType() - { + protected ByteBuffer handleUnknownContentType() { Logging.logger().log(java.util.logging.Level.WARNING, - Logging.getMessage("generic.UnknownContentType", this.getRetriever().getContentType())); + Logging.getMessage("generic.UnknownContentType", this.getRetriever().getContentType())); return null; } @@ -403,15 +389,16 @@ protected ByteBuffer handleUnknownContentType() * * @throws IOException if an IO error occurs while processing the data. */ - protected ByteBuffer handleTextContent() throws IOException - { + protected ByteBuffer handleTextContent() throws IOException { String contentType = this.getRetriever().getContentType().trim().toLowerCase(); - if (contentType.contains("xml")) + if (contentType.contains("xml")) { return this.handleXMLContent(); + } - if (contentType.contains("html")) + if (contentType.contains("html")) { return this.handleHTMLContent(); + } this.logTextBuffer(this.getRetriever().getBuffer()); @@ -426,8 +413,7 @@ protected ByteBuffer handleTextContent() throws IOException * * @throws IOException if an IO error occurs while processing the data. */ - protected ByteBuffer handleXMLContent() throws IOException - { + protected ByteBuffer handleXMLContent() throws IOException { this.logTextBuffer(this.getRetriever().getBuffer()); return null; @@ -441,8 +427,7 @@ protected ByteBuffer handleXMLContent() throws IOException * * @throws IOException if an IO error occurs while processing the data. */ - protected ByteBuffer handleHTMLContent() throws IOException - { + protected ByteBuffer handleHTMLContent() throws IOException { this.logTextBuffer(this.getRetriever().getBuffer()); return null; @@ -454,10 +439,10 @@ protected ByteBuffer handleHTMLContent() throws IOException * * @param buffer the content to log. The content is assumed to be of type "text". */ - protected void logTextBuffer(ByteBuffer buffer) - { - if (buffer == null || !buffer.hasRemaining()) + protected void logTextBuffer(ByteBuffer buffer) { + if (buffer == null || !buffer.hasRemaining()) { return; + } Logging.logger().warning(WWIO.byteBufferToString(buffer, 2048, null)); } @@ -470,11 +455,11 @@ protected void logTextBuffer(ByteBuffer buffer) * * @throws IOException if an IO error occurs while processing the data. */ - protected ByteBuffer handleZipContent() throws IOException - { + protected ByteBuffer handleZipContent() throws IOException { File outFile = this.getOutputFile(); - if (outFile == null) + if (outFile == null) { return null; + } this.saveBuffer(); @@ -489,8 +474,7 @@ protected ByteBuffer handleZipContent() throws IOException * * @throws IOException if an IO error occurs while processing the data. */ - protected ByteBuffer handleApplicationContent() throws IOException - { + protected ByteBuffer handleApplicationContent() throws IOException { this.saveBuffer(); return this.getRetriever().getBuffer(); @@ -501,8 +485,7 @@ protected ByteBuffer handleApplicationContent() throws IOException * * @return a buffer containing the retrieved XML. */ - protected ByteBuffer handleWMSExceptionContent() - { + protected ByteBuffer handleWMSExceptionContent() { // TODO: Parse the xml and include only the message text in the log message. StringBuilder sb = new StringBuilder(this.getRetriever().getName()); @@ -525,29 +508,29 @@ protected ByteBuffer handleWMSExceptionContent() * * @throws IOException if an IO error occurs while processing the data. */ - protected ByteBuffer handleImageContent() throws IOException - { + protected ByteBuffer handleImageContent() throws IOException { // BE CAREFUL: This method may be overridden by subclasses to handle special image cases. It's also implemented // to handle elevations as images correctly (just save them to the filestore). File outFile = this.getOutputFile(); - if (outFile == null || (outFile.exists() && !this.overwriteExistingFile())) + if (outFile == null || (outFile.exists() && !this.overwriteExistingFile())) { return this.getRetriever().getBuffer(); + } - if (outFile.getPath().endsWith("dds")) + if (outFile.getPath().endsWith("dds")) { return this.saveDDS(); + } BufferedImage image = this.transformPixels(); - if (image != null) - { + if (image != null) { synchronized (this.getFileLock()) // synchronize with read of file in another class { ImageIO.write(image, this.getRetriever().getContentType().split("/")[1], outFile); } - } - else + } else { this.saveBuffer(); + } return this.getRetriever().getBuffer(); } @@ -560,13 +543,12 @@ protected ByteBuffer handleImageContent() throws IOException * * @return returns the transformed data if a transform is performed, otherwise returns the original data. */ - protected BufferedImage transformPixels() - { - if (this.avList != null) - { + protected BufferedImage transformPixels() { + if (this.avList != null) { int[] colors = (int[]) this.avList.getValue(AVKey.TRANSPARENCY_COLORS); - if (colors != null) + if (colors != null) { return ImageUtil.mapTransparencyColors(this.getRetriever().getBuffer(), colors); + } } return null; @@ -579,12 +561,12 @@ protected BufferedImage transformPixels() * * @throws IOException if an IO error occurs while converting or saving the image. */ - protected ByteBuffer saveDDS() throws IOException - { + protected ByteBuffer saveDDS() throws IOException { ByteBuffer buffer = this.getRetriever().getBuffer(); - if (!this.getRetriever().getContentType().contains("dds")) + if (!this.getRetriever().getContentType().contains("dds")) { buffer = this.convertToDDS(); + } this.saveBuffer(buffer); @@ -599,15 +581,15 @@ protected ByteBuffer saveDDS() throws IOException * * @throws IOException if an IO error occurs while converting the image. */ - protected ByteBuffer convertToDDS() throws IOException - { + protected ByteBuffer convertToDDS() throws IOException { ByteBuffer buffer; BufferedImage image = this.transformPixels(); - if (image != null) + if (image != null) { buffer = DDSCompressor.compressImage(image); - else + } else { buffer = DDSCompressor.compressImageBuffer(this.getRetriever().getBuffer()); + } return buffer; } diff --git a/src/gov/nasa/worldwind/retrieve/BasicRetrievalService.java b/src/gov/nasa/worldwind/retrieve/BasicRetrievalService.java index 38a44d2978..f0510346ed 100644 --- a/src/gov/nasa/worldwind/retrieve/BasicRetrievalService.java +++ b/src/gov/nasa/worldwind/retrieve/BasicRetrievalService.java @@ -21,8 +21,8 @@ * @version $Id: BasicRetrievalService.java 1171 2013-02-11 21:45:02Z dcollins $ */ public final class BasicRetrievalService extends WWObjectImpl - implements RetrievalService, Thread.UncaughtExceptionHandler -{ + implements RetrievalService, Thread.UncaughtExceptionHandler { + // These constants are last-ditch values in case Configuration lacks defaults private static final int DEFAULT_QUEUE_SIZE = 100; private static final int DEFAULT_POOL_SIZE = 5; @@ -30,43 +30,42 @@ public final class BasicRetrievalService extends WWObjectImpl private static final int DEFAULT_TIME_PRIORITY_GRANULARITY = 500; // milliseconds private static final String RUNNING_THREAD_NAME_PREFIX = Logging.getMessage( - "BasicRetrievalService.RunningThreadNamePrefix"); + "BasicRetrievalService.RunningThreadNamePrefix"); private static final String IDLE_THREAD_NAME_PREFIX = Logging.getMessage( - "BasicRetrievalService.IdleThreadNamePrefix"); + "BasicRetrievalService.IdleThreadNamePrefix"); private RetrievalExecutor executor; // thread pool for running retrievers private ConcurrentLinkedQueue activeTasks; // tasks currently allocated a thread private int queueSize; // maximum queue size - /** Encapsulates a single threaded retrieval as a {@link java.util.concurrent.FutureTask}. */ + /** + * Encapsulates a single threaded retrieval as a {@link java.util.concurrent.FutureTask}. + */ private static class RetrievalTask extends FutureTask - implements RetrievalFuture, Comparable - { + implements RetrievalFuture, Comparable { + private Retriever retriever; private double priority; // retrieval secondary priority (primary priority is submit time) - private RetrievalTask(Retriever retriever, double priority) - { + private RetrievalTask(Retriever retriever, double priority) { super(retriever); this.retriever = retriever; this.priority = priority; } - public double getPriority() - { + public double getPriority() { return priority; } - public Retriever getRetriever() - { + public Retriever getRetriever() { return this.retriever; } @Override - public void run() - { - if (this.isDone() || this.isCancelled()) + public void run() { + if (this.isDone() || this.isCancelled()) { return; + } super.run(); } @@ -78,10 +77,8 @@ public void run() * * @throws IllegalArgumentException if that is null */ - public int compareTo(RetrievalTask that) - { - if (that == null) - { + public int compareTo(RetrievalTask that) { + if (that == null) { String msg = Logging.getMessage("nullValue.RetrieverIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -94,20 +91,22 @@ public int compareTo(RetrievalTask that) long now = System.currentTimeMillis(); long thisElapsedTime = now - this.retriever.getSubmitTime(); long thatElapsedTime = now - that.retriever.getSubmitTime(); - if (((thisElapsedTime - thatElapsedTime) / DEFAULT_TIME_PRIORITY_GRANULARITY) != 0) + if (((thisElapsedTime - thatElapsedTime) / DEFAULT_TIME_PRIORITY_GRANULARITY) != 0) { return thisElapsedTime < thatElapsedTime ? -1 : 1; + } } // The client-specified priority is compared for requests submitted within the same granularity period. return this.priority == that.priority ? 0 : this.priority < that.priority ? -1 : 1; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final RetrievalTask that = (RetrievalTask) o; @@ -116,82 +115,71 @@ public boolean equals(Object o) // Priority and submit time are not factors in equality } - public int hashCode() - { + public int hashCode() { return this.retriever.getName().hashCode(); } } protected SSLExceptionListener sslExceptionListener; - public SSLExceptionListener getSSLExceptionListener() - { + public SSLExceptionListener getSSLExceptionListener() { return sslExceptionListener; } - public void setSSLExceptionListener(SSLExceptionListener sslExceptionListener) - { + public void setSSLExceptionListener(SSLExceptionListener sslExceptionListener) { this.sslExceptionListener = sslExceptionListener; } - public void uncaughtException(Thread thread, Throwable throwable) - { + public void uncaughtException(Thread thread, Throwable throwable) { Logging.logger().fine(Logging.getMessage("BasicRetrievalService.UncaughtExceptionDuringRetrieval", - thread.getName())); + thread.getName())); } - private class RetrievalExecutor extends ThreadPoolExecutor - { + private class RetrievalExecutor extends ThreadPoolExecutor { + private static final long THREAD_TIMEOUT = 2; // keep idle threads alive this many seconds private long staleRequestLimit; // reject requests older than this - private RetrievalExecutor(int poolSize, int queueSize) - { + private RetrievalExecutor(int poolSize, int queueSize) { super(poolSize, poolSize, THREAD_TIMEOUT, TimeUnit.SECONDS, new PriorityBlockingQueue(queueSize), - new ThreadFactory() - { - public Thread newThread(Runnable runnable) - { - Thread thread = new Thread(runnable); - thread.setDaemon(true); - thread.setPriority(Thread.MIN_PRIORITY); - thread.setUncaughtExceptionHandler(BasicRetrievalService.this); - return thread; - } - }, new ThreadPoolExecutor.DiscardPolicy() // abandon task when queue is full + new ThreadFactory() { + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + thread.setPriority(Thread.MIN_PRIORITY); + thread.setUncaughtExceptionHandler(BasicRetrievalService.this); + return thread; + } + }, new ThreadPoolExecutor.DiscardPolicy() // abandon task when queue is full { // This listener is invoked only when the executor queue is a bounded queue and runs out of room. // If the queue is a java.util.concurrent.PriorityBlockingQueue, this listener is never invoked. - public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) - { + public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) { // Interposes logging for rejected execution Logging.logger().finer(Logging.getMessage("BasicRetrievalService.ResourceRejected", - ((RetrievalTask) runnable).getRetriever().getName())); + ((RetrievalTask) runnable).getRetriever().getName())); super.rejectedExecution(runnable, threadPoolExecutor); } }); this.staleRequestLimit = Configuration.getLongValue(AVKey.RETRIEVAL_QUEUE_STALE_REQUEST_LIMIT, - DEFAULT_STALE_REQUEST_LIMIT); + DEFAULT_STALE_REQUEST_LIMIT); } /** - * @param thread the thread the task is running on + * @param thread the thread the task is running on * @param runnable the Retriever running on the thread * * @throws IllegalArgumentException if either thread or runnable is null */ - protected void beforeExecute(Thread thread, Runnable runnable) - { - if (thread == null) - { + protected void beforeExecute(Thread thread, Runnable runnable) { + if (thread == null) { String msg = Logging.getMessage("nullValue.ThreadIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (runnable == null) - { + if (runnable == null) { String msg = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -201,20 +189,18 @@ protected void beforeExecute(Thread thread, Runnable runnable) task.retriever.setBeginTime(System.currentTimeMillis()); long limit = task.retriever.getStaleRequestLimit() >= 0 - ? task.retriever.getStaleRequestLimit() : this.staleRequestLimit; - if (task.retriever.getBeginTime() - task.retriever.getSubmitTime() > limit) - { + ? task.retriever.getStaleRequestLimit() : this.staleRequestLimit; + if (task.retriever.getBeginTime() - task.retriever.getSubmitTime() > limit) { // Task has been sitting on the queue too long Logging.logger().finer(Logging.getMessage("BasicRetrievalService.CancellingTooOldRetrieval", - task.getRetriever().getName())); + task.getRetriever().getName())); task.cancel(true); } - if (BasicRetrievalService.this.activeTasks.contains(task)) - { + if (BasicRetrievalService.this.activeTasks.contains(task)) { // Task is a duplicate Logging.logger().finer(Logging.getMessage("BasicRetrievalService.CancellingDuplicateRetrieval", - task.getRetriever().getName())); + task.getRetriever().getName())); task.cancel(true); } @@ -228,15 +214,13 @@ protected void beforeExecute(Thread thread, Runnable runnable) } /** - * @param runnable the Retriever running on the thread + * @param runnable the Retriever running on the thread * @param throwable an exception thrown during retrieval, will be null if no exception occurred * * @throws IllegalArgumentException if runnable is null */ - protected void afterExecute(Runnable runnable, Throwable throwable) - { - if (runnable == null) - { + protected void afterExecute(Runnable runnable, Throwable throwable) { + if (runnable == null) { String msg = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -248,56 +232,41 @@ protected void afterExecute(Runnable runnable, Throwable throwable) BasicRetrievalService.this.activeTasks.remove(task); task.retriever.setEndTime(System.currentTimeMillis()); - try - { - if (throwable != null) - { + try { + if (throwable != null) { Logging.logger().log(Level.FINE, - Logging.getMessage("BasicRetrievalService.ExceptionDuringRetrieval", - task.getRetriever().getName()), throwable); + Logging.getMessage("BasicRetrievalService.ExceptionDuringRetrieval", + task.getRetriever().getName()), throwable); } task.get(); // Wait for task to finish, cancel or break - } - catch (java.util.concurrent.ExecutionException e) - { + } catch (java.util.concurrent.ExecutionException e) { String message = Logging.getMessage("BasicRetrievalService.ExecutionExceptionDuringRetrieval", - task.getRetriever().getName()); - if (e.getCause() instanceof SocketTimeoutException) - { + task.getRetriever().getName()); + if (e.getCause() instanceof SocketTimeoutException) { Logging.logger().fine(message + " " + e.getCause().getLocalizedMessage()); - } - else if (e.getCause() instanceof SSLHandshakeException) - { - if (sslExceptionListener != null) + } else if (e.getCause() instanceof SSLHandshakeException) { + if (sslExceptionListener != null) { sslExceptionListener.onException(e.getCause(), task.getRetriever().getName()); - else + } else { Logging.logger().fine(message + " " + e.getCause().getLocalizedMessage()); - } - else - { + } + } else { Logging.logger().log(Level.FINE, message, e); } - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Logging.logger().log(Level.FINE, Logging.getMessage("BasicRetrievalService.RetrievalInterrupted", - task.getRetriever().getName()), e); - } - catch (java.util.concurrent.CancellationException e) - { + task.getRetriever().getName()), e); + } catch (java.util.concurrent.CancellationException e) { Logging.logger().fine(Logging.getMessage("BasicRetrievalService.RetrievalCancelled", - task.getRetriever().getName())); - } - finally - { + task.getRetriever().getName())); + } finally { Thread.currentThread().setName(IDLE_THREAD_NAME_PREFIX); } } } - public BasicRetrievalService() - { + public BasicRetrievalService() { Integer poolSize = Configuration.getIntegerValue(AVKey.RETRIEVAL_POOL_SIZE, DEFAULT_POOL_SIZE); this.queueSize = Configuration.getIntegerValue(AVKey.RETRIEVAL_QUEUE_SIZE, DEFAULT_QUEUE_SIZE); @@ -308,12 +277,12 @@ public BasicRetrievalService() this.activeTasks = new ConcurrentLinkedQueue(); } - public void shutdown(boolean immediately) - { - if (immediately) + public void shutdown(boolean immediately) { + if (immediately) { this.executor.shutdownNow(); - else + } else { this.executor.shutdown(); + } this.activeTasks.clear(); } @@ -325,16 +294,13 @@ public void shutdown(boolean immediately) * * @throws IllegalArgumentException if retriever is null or has no name */ - public RetrievalFuture runRetriever(Retriever retriever) - { - if (retriever == null) - { + public RetrievalFuture runRetriever(Retriever retriever) { + if (retriever == null) { String msg = Logging.getMessage("nullValue.RetrieverIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (retriever.getName() == null) - { + if (retriever.getName() == null) { String message = Logging.getMessage("nullValue.RetrieverNameIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -346,30 +312,26 @@ public RetrievalFuture runRetriever(Retriever retriever) /** * @param retriever the retriever to run - * @param priority the secondary priority of the retriever, or negative if it is to be the primary priority + * @param priority the secondary priority of the retriever, or negative if it is to be the primary priority * * @return a future object that can be used to query the request status of cancel the request. * * @throws IllegalArgumentException if retriever is null or has no name */ - public synchronized RetrievalFuture runRetriever(Retriever retriever, double priority) - { - if (retriever == null) - { + public synchronized RetrievalFuture runRetriever(Retriever retriever, double priority) { + if (retriever == null) { String message = Logging.getMessage("nullValue.RetrieverIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (retriever.getName() == null) - { + if (retriever.getName() == null) { String message = Logging.getMessage("nullValue.RetrieverNameIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } - if (!this.isAvailable()) - { + if (!this.isAvailable()) { Logging.logger().finer(Logging.getMessage("BasicRetrievalService.ResourceRejected", retriever.getName())); } @@ -377,8 +339,9 @@ public synchronized RetrievalFuture runRetriever(Retriever retriever, double pri retriever.setSubmitTime(System.currentTimeMillis()); // Do not queue duplicates. - if (this.activeTasks.contains(task) || this.executor.getQueue().contains(task)) + if (this.activeTasks.contains(task) || this.executor.getQueue().contains(task)) { return null; + } this.executor.execute(task); @@ -390,10 +353,8 @@ public synchronized RetrievalFuture runRetriever(Retriever retriever, double pri * * @throws IllegalArgumentException if poolSize is non-positive */ - public void setRetrieverPoolSize(int poolSize) - { - if (poolSize < 1) - { + public void setRetrieverPoolSize(int poolSize) { + if (poolSize < 1) { String message = Logging.getMessage("BasicRetrievalService.RetrieverPoolSizeIsLessThanOne"); Logging.logger().fine(message); throw new IllegalArgumentException(message); @@ -403,36 +364,31 @@ public void setRetrieverPoolSize(int poolSize) this.executor.setMaximumPoolSize(poolSize); } - public int getRetrieverPoolSize() - { + public int getRetrieverPoolSize() { return this.executor.getCorePoolSize(); } - private boolean hasRetrievers() - { + private boolean hasRetrievers() { Thread[] threads = new Thread[Thread.activeCount()]; int numThreads = Thread.enumerate(threads); - for (int i = 0; i < numThreads; i++) - { - if (threads[i].getName().startsWith(RUNNING_THREAD_NAME_PREFIX)) + for (int i = 0; i < numThreads; i++) { + if (threads[i].getName().startsWith(RUNNING_THREAD_NAME_PREFIX)) { return true; + } } return false; } - public boolean hasActiveTasks() - { + public boolean hasActiveTasks() { return this.hasRetrievers(); } - public boolean isAvailable() - { + public boolean isAvailable() { return this.executor.getQueue().size() < this.queueSize; // && !WorldWind.getNetworkStatus().isNetworkUnavailable(); } - public int getNumRetrieversPending() - { + public int getNumRetrieversPending() { // Could use same method to determine active tasks as hasRetrievers() above, but this method only advisory. return this.activeTasks.size() + this.executor.getQueue().size(); } @@ -444,10 +400,8 @@ public int getNumRetrieversPending() * * @throws IllegalArgumentException if retriever is null */ - public boolean contains(Retriever retriever) - { - if (retriever == null) - { + public boolean contains(Retriever retriever) { + if (retriever == null) { String msg = Logging.getMessage("nullValue.RetrieverIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -456,65 +410,54 @@ public boolean contains(Retriever retriever) return (this.activeTasks.contains(task) || this.executor.getQueue().contains(task)); } - public double getProgress() - { + public double getProgress() { int totalContentLength = 0; int totalBytesRead = 0; - for (RetrievalTask task : this.activeTasks) - { - if (task.isDone()) + for (RetrievalTask task : this.activeTasks) { + if (task.isDone()) { continue; + } Retriever retriever = task.getRetriever(); - try - { + try { double tcl = retriever.getContentLength(); - if (tcl > 0) - { + if (tcl > 0) { totalContentLength += tcl; totalBytesRead += retriever.getContentLengthRead(); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.FINE, - Logging.getMessage("BasicRetrievalService.ExceptionRetrievingContentSizes", - retriever.getName() != null ? retriever.getName() : ""), e); + Logging.getMessage("BasicRetrievalService.ExceptionRetrievingContentSizes", + retriever.getName() != null ? retriever.getName() : ""), e); } } - for (Runnable runnable : this.executor.getQueue()) - { - RetrievalTask task = - (RetrievalTask) runnable; + for (Runnable runnable : this.executor.getQueue()) { + RetrievalTask task + = (RetrievalTask) runnable; Retriever retriever = task.getRetriever(); - try - { + try { double tcl = retriever.getContentLength(); - if (tcl > 0) - { + if (tcl > 0) { totalContentLength += tcl; totalBytesRead += retriever.getContentLengthRead(); } - } - catch (Exception e) - { - String message = Logging.getMessage("BasicRetrievalService.ExceptionRetrievingContentSizes") + ( - retriever.getName() != null ? retriever.getName() : ""); + } catch (Exception e) { + String message = Logging.getMessage("BasicRetrievalService.ExceptionRetrievingContentSizes") + (retriever.getName() != null ? retriever.getName() : ""); Logging.logger().log(Level.FINE, message, e); } } // Compute an aggregated progress notification. - double progress; - if (totalContentLength < 1) + if (totalContentLength < 1) { progress = 0; - else + } else { progress = Math.min(100.0, 100.0 * (double) totalBytesRead / (double) totalContentLength); + } return progress; } diff --git a/src/gov/nasa/worldwind/retrieve/BulkRetrievable.java b/src/gov/nasa/worldwind/retrieve/BulkRetrievable.java index a0670b2685..36e60da9c9 100644 --- a/src/gov/nasa/worldwind/retrieve/BulkRetrievable.java +++ b/src/gov/nasa/worldwind/retrieve/BulkRetrievable.java @@ -17,32 +17,32 @@ * @author Patrick Murris * @version $Id: BulkRetrievable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface BulkRetrievable -{ +public interface BulkRetrievable { + /** * Initiates data retrieval to the current WorldWind data cache. The method starts a new thread to perform the * retrieval. The thread terminates when either all the requested data has been retrieved or when any data not * retrieved is determined to be unretrievable. * - * @param sector the sector for which to retrieve the data. + * @param sector the sector for which to retrieve the data. * @param resolution the resolution desired. All data within the specified sector up to and including this - * resolution is downloaded. - * @param listener an optional bulk-download listener that can be used to monitor the success or failure of - * individual retrievals. Note: The listener is called on the thread performing the download, - * which is not the event dispatch thread. Therefore any interaction with AWT or Swing within the - * call must be done within a call to SwingUtilities.invokeLater(). + * resolution is downloaded. + * @param listener an optional bulk-download listener that can be used to monitor the success or failure of + * individual retrievals. Note: The listener is called on the thread performing the download, which is not the event + * dispatch thread. Therefore any interaction with AWT or Swing within the call must be done within a call to + * SwingUtilities.invokeLater(). * * @return returns the running thread created to perform the retrieval. */ BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetrievalListener listener); /** - * Estimates the amount of data, in bytes, that must be retrieved to the WorldWind data cache for a specified - * sector and resolution. + * Estimates the amount of data, in bytes, that must be retrieved to the WorldWind data cache for a specified sector + * and resolution. * - * @param sector the sector for which to retrieve the data. + * @param sector the sector for which to retrieve the data. * @param resolution the resolution desired. All data within the specified sector up to and including this - * resolution is downloaded. + * resolution is downloaded. * * @return the estimated data size, in bytes. */ @@ -52,33 +52,33 @@ public interface BulkRetrievable * Estimates the amount of data, in bytes, that must be retrieved to a specified filestore for a specified sector * and resolution. * - * @param sector the sector for which to retrieve the data. + * @param sector the sector for which to retrieve the data. * @param resolution the resolution desired. All data within the specified sector up to and including this - * resolution is downloaded. - * @param fileStore the location to place the data. If null, the current WorldWind cache is used. + * resolution is downloaded. + * @param fileStore the location to place the data. If null, the current WorldWind cache is used. * * @return the estimated data size, in bytes. */ long getEstimatedMissingDataSize(Sector sector, double resolution, FileStore fileStore); /** - * Initiates data retrieval to a specified filestore. The method starts a new thread to perform the - * retrieval. The thread terminates when either all the requested data has been retrieved or when any data not - * retrieved is determined to be unretrievable. + * Initiates data retrieval to a specified filestore. The method starts a new thread to perform the retrieval. The + * thread terminates when either all the requested data has been retrieved or when any data not retrieved is + * determined to be unretrievable. * - * @param sector the sector for which to retrieve the data. + * @param sector the sector for which to retrieve the data. * @param resolution the resolution desired. All data within the specified sector up to and including this - * resolution is downloaded. - * @param listener an optional bulk-download listener that can be used to monitor the success or failure of - * individual retrievals. Note: The listener is called on the thread performing the download, - * which is not the event dispatch thread. Therefore any interaction with AWT or Swing within the - * call must be done within a call to SwingUtilities.invokeLater(). - * @param fileStore the location to place the data. If null, the current WorldWind cache is used. + * resolution is downloaded. + * @param listener an optional bulk-download listener that can be used to monitor the success or failure of + * individual retrievals. Note: The listener is called on the thread performing the download, which is not the event + * dispatch thread. Therefore any interaction with AWT or Swing within the call must be done within a call to + * SwingUtilities.invokeLater(). + * @param fileStore the location to place the data. If null, the current WorldWind cache is used. * * @return returns the running thread created to perform the retrieval. */ BulkRetrievalThread makeLocal(Sector sector, double resolution, FileStore fileStore, - BulkRetrievalListener listener); - + BulkRetrievalListener listener); + String getName(); } diff --git a/src/gov/nasa/worldwind/retrieve/BulkRetrievalThread.java b/src/gov/nasa/worldwind/retrieve/BulkRetrievalThread.java index b96961c412..bf4e3ebd23 100644 --- a/src/gov/nasa/worldwind/retrieve/BulkRetrievalThread.java +++ b/src/gov/nasa/worldwind/retrieve/BulkRetrievalThread.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.retrieve; import gov.nasa.worldwind.cache.FileStore; @@ -19,8 +18,8 @@ * @author Patrick Murris * @version $Id: BulkRetrievalThread.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class BulkRetrievalThread extends Thread -{ +public abstract class BulkRetrievalThread extends Thread { + protected int RETRIEVAL_SERVICE_POLL_DELAY = 1000; protected final BulkRetrievable retrievable; @@ -35,39 +34,36 @@ public abstract class BulkRetrievalThread extends Thread * {@link Sector} and resolution. *

          * This method creates and starts a thread to perform the download. A reference to the thread is returned. To create - * a downloader that has not been started, construct a {@link gov.nasa.worldwind.terrain.BasicElevationModelBulkDownloader}. + * a downloader that has not been started, construct a + * {@link gov.nasa.worldwind.terrain.BasicElevationModelBulkDownloader}. *

          * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * * @param retrievable the retrievable to retrieve data for. - * @param sector the sector of interest. - * @param resolution the target resolution, provided in radians of latitude per texel. - * @param fileStore the file store to examine. - * @param listener an optional retrieval listener. May be null. + * @param sector the sector of interest. + * @param resolution the target resolution, provided in radians of latitude per texel. + * @param fileStore the file store to examine. + * @param listener an optional retrieval listener. May be null. * * @throws IllegalArgumentException if either the retrievable, sector or file store are null, or the resolution is - * less than or equal to zero. + * less than or equal to zero. */ public BulkRetrievalThread(BulkRetrievable retrievable, Sector sector, double resolution, FileStore fileStore, - BulkRetrievalListener listener) - { - if (retrievable == null) - { + BulkRetrievalListener listener) { + if (retrievable == null) { String msg = Logging.getMessage("nullValue.RetrievableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (fileStore == null) - { + if (fileStore == null) { String msg = Logging.getMessage("nullValue.FileStoreIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -86,8 +82,9 @@ public BulkRetrievalThread(BulkRetrievable retrievable, Sector sector, double re this.fileStore = fileStore; this.progress = new Progress(); - if (listener != null) + if (listener != null) { this.addRetrievalListener(listener); + } } public abstract void run(); @@ -97,8 +94,7 @@ public BulkRetrievalThread(BulkRetrievable retrievable, Sector sector, double re * * @return the {@link BulkRetrievable} instance. */ - public BulkRetrievable getRetrievable() - { + public BulkRetrievable getRetrievable() { return this.retrievable; } @@ -107,8 +103,7 @@ public BulkRetrievable getRetrievable() * * @return the requested {@link Sector}. */ - public Sector getSector() - { + public Sector getSector() { return this.sector; } @@ -117,8 +112,7 @@ public Sector getSector() * * @return the requested resolution. */ - public double getResolution() - { + public double getResolution() { return this.resolution; } @@ -127,8 +121,7 @@ public double getResolution() * * @return the file store associated with this downloader. */ - public FileStore getFileStore() - { + public FileStore getFileStore() { return fileStore; } @@ -137,32 +130,28 @@ public FileStore getFileStore() * * @return a {@link Progress} instance providing information about this task progress. */ - public Progress getProgress() - { + public Progress getProgress() { return this.progress; } - public void addRetrievalListener(BulkRetrievalListener listener) - { - if (listener != null) + public void addRetrievalListener(BulkRetrievalListener listener) { + if (listener != null) { this.retrievalListeners.add(BulkRetrievalListener.class, listener); + } } - public void removeRetrievalListener(BulkRetrievalListener listener) - { - if (listener != null) + public void removeRetrievalListener(BulkRetrievalListener listener) { + if (listener != null) { this.retrievalListeners.remove(BulkRetrievalListener.class, listener); + } } - protected boolean hasRetrievalListeners() - { + protected boolean hasRetrievalListeners() { return this.retrievalListeners.getListenerCount() > 0; } - protected void callRetrievalListeners(BulkRetrievalEvent event) - { - for (BulkRetrievalListener listener : this.retrievalListeners.getListeners(BulkRetrievalListener.class)) - { + protected void callRetrievalListeners(BulkRetrievalEvent event) { + for (BulkRetrievalListener listener : this.retrievalListeners.getListeners(BulkRetrievalListener.class)) { listener.eventOccurred(event); } } diff --git a/src/gov/nasa/worldwind/retrieve/HTTPRetriever.java b/src/gov/nasa/worldwind/retrieve/HTTPRetriever.java index f362cd66e3..c319839078 100644 --- a/src/gov/nasa/worldwind/retrieve/HTTPRetriever.java +++ b/src/gov/nasa/worldwind/retrieve/HTTPRetriever.java @@ -15,30 +15,25 @@ * @author Tom Gaskins * @version $Id: HTTPRetriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class HTTPRetriever extends URLRetriever -{ +public class HTTPRetriever extends URLRetriever { + private int responseCode; private String responseMessage; - public HTTPRetriever(URL url, RetrievalPostProcessor postProcessor) - { + public HTTPRetriever(URL url, RetrievalPostProcessor postProcessor) { super(url, postProcessor); } - public int getResponseCode() - { + public int getResponseCode() { return this.responseCode; } - public String getResponseMessage() - { + public String getResponseMessage() { return this.responseMessage; } - protected ByteBuffer doRead(URLConnection connection) throws Exception - { - if (connection == null) - { + protected ByteBuffer doRead(URLConnection connection) throws Exception { + if (connection == null) { String msg = Logging.getMessage("nullValue.ConnectionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -49,12 +44,13 @@ protected ByteBuffer doRead(URLConnection connection) throws Exception this.responseMessage = htpc.getResponseMessage(); String contentType = connection.getContentType(); - Logging.logger().log(Level.FINE, "HTTPRetriever.ResponseInfo", new Object[] {this.responseCode, + Logging.logger().log(Level.FINE, "HTTPRetriever.ResponseInfo", new Object[]{this.responseCode, connection.getContentLength(), contentType != null ? contentType : "content type not returned", connection.getURL()}); - if (this.responseCode == HttpURLConnection.HTTP_OK) + if (this.responseCode == HttpURLConnection.HTTP_OK) { return super.doRead(connection); + } return null; } diff --git a/src/gov/nasa/worldwind/retrieve/JarRetriever.java b/src/gov/nasa/worldwind/retrieve/JarRetriever.java index 6e68502adb..4c9adafccc 100644 --- a/src/gov/nasa/worldwind/retrieve/JarRetriever.java +++ b/src/gov/nasa/worldwind/retrieve/JarRetriever.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.retrieve; import gov.nasa.worldwind.util.Logging; @@ -20,30 +19,25 @@ * @author tag * @version $Id: JarRetriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class JarRetriever extends URLRetriever -{ +public class JarRetriever extends URLRetriever { + private int responseCode; private String responseMessage; - public JarRetriever(URL url, RetrievalPostProcessor postProcessor) - { + public JarRetriever(URL url, RetrievalPostProcessor postProcessor) { super(url, postProcessor); } - public int getResponseCode() - { + public int getResponseCode() { return this.responseCode; } - public String getResponseMessage() - { + public String getResponseMessage() { return this.responseMessage; } - protected ByteBuffer doRead(URLConnection connection) throws Exception - { - if (connection == null) - { + protected ByteBuffer doRead(URLConnection connection) throws Exception { + if (connection == null) { String msg = Logging.getMessage("nullValue.ConnectionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -54,12 +48,14 @@ protected ByteBuffer doRead(URLConnection connection) throws Exception this.responseMessage = this.responseCode >= 0 ? "OK" : "FAILED"; String contentType = connection.getContentType(); - Logging.logger().log(Level.FINE, "HTTPRetriever.ResponseInfo", new Object[] {this.responseCode, + Logging.logger().log(Level.FINE, "HTTPRetriever.ResponseInfo", new Object[]{this.responseCode, connection.getContentLength(), contentType != null ? contentType : "content type not returned", connection.getURL()}); if (this.responseCode == HttpURLConnection.HTTP_OK) // intentionally re-using HTTP constant + { return super.doRead(connection); + } return null; } diff --git a/src/gov/nasa/worldwind/retrieve/LocalRasterServerRetriever.java b/src/gov/nasa/worldwind/retrieve/LocalRasterServerRetriever.java index c3505e7e1b..ee165c2011 100644 --- a/src/gov/nasa/worldwind/retrieve/LocalRasterServerRetriever.java +++ b/src/gov/nasa/worldwind/retrieve/LocalRasterServerRetriever.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.retrieve; import gov.nasa.worldwind.WWObjectImpl; @@ -20,8 +19,8 @@ * @author tag * @version $Id: LocalRasterServerRetriever.java 2257 2014-08-22 18:02:19Z tgaskins $ */ -public class LocalRasterServerRetriever extends WWObjectImpl implements Retriever -{ +public class LocalRasterServerRetriever extends WWObjectImpl implements Retriever { + // protected AVList params; protected RetrievalPostProcessor postProcessor; @@ -35,52 +34,44 @@ public class LocalRasterServerRetriever extends WWObjectImpl implements Retrieve protected long beginTime; protected long endTime; - public LocalRasterServerRetriever(AVList params, RasterServer rasterServer, RetrievalPostProcessor postProcessor) - { - if (null != params) + public LocalRasterServerRetriever(AVList params, RasterServer rasterServer, RetrievalPostProcessor postProcessor) { + if (null != params) { this.setValues(params); + } this.server = rasterServer; this.postProcessor = postProcessor; } - public RasterServer getServer() - { + public RasterServer getServer() { return this.server; } - public void setServer(RasterServer server) - { + public void setServer(RasterServer server) { this.server = server; } - public ByteBuffer getBuffer() - { + public ByteBuffer getBuffer() { return this.byteBuffer; } - public int getContentLength() - { + public int getContentLength() { return this.contentLength; } - public int getContentLengthRead() - { + public int getContentLengthRead() { return this.contentLengthRead.get(); } - public String getName() - { + public String getName() { Object o = this.getStringValue(AVKey.DISPLAY_NAME); return (WWUtil.isEmpty(o)) ? null : (String) o; } - public String getState() - { + public String getState() { return this.state; } - public String getContentType() - { + public String getContentType() { Object o = this.getValue(AVKey.IMAGE_FORMAT); return (WWUtil.isEmpty(o)) ? null : (String) o; } @@ -90,79 +81,63 @@ public String getContentType() * * @return Always returns zero (no expiration). */ - public long getExpirationTime() - { + public long getExpirationTime() { return 0; } - public long getSubmitTime() - { + public long getSubmitTime() { return this.submitTime; } - public void setSubmitTime(long submitTime) - { + public void setSubmitTime(long submitTime) { this.submitTime = submitTime; } - public long getBeginTime() - { + public long getBeginTime() { return this.beginTime; } - public void setBeginTime(long beginTime) - { + public void setBeginTime(long beginTime) { this.beginTime = beginTime; } - public long getEndTime() - { + public long getEndTime() { return this.endTime; } - public void setEndTime(long endTime) - { + public void setEndTime(long endTime) { this.endTime = endTime; } - public int getConnectTimeout() - { + public int getConnectTimeout() { return 0;// Not applicable to this retriever type } - public int getReadTimeout() - { + public int getReadTimeout() { return 0;// Not applicable to this retriever type } - public void setReadTimeout(int readTimeout) - { + public void setReadTimeout(int readTimeout) { // Not applicable to this retriever type } - public void setConnectTimeout(int connectTimeout) - { + public void setConnectTimeout(int connectTimeout) { // Not applicable to this retriever type } - public int getStaleRequestLimit() - { + public int getStaleRequestLimit() { return this.staleRequestLimit; } - public void setStaleRequestLimit(int staleRequestLimit) - { + public void setStaleRequestLimit(int staleRequestLimit) { this.staleRequestLimit = staleRequestLimit; } - public Retriever call() throws Exception - { - try - { + public Retriever call() throws Exception { + try { this.setState(RETRIEVER_STATE_STARTED); - if (null == this.server) - { + if (null == this.server) { this.setState(RETRIEVER_STATE_ERROR); String message = Logging.getMessage("nullValue.RasterServerIsNull"); Logging.logger().severe(message); @@ -170,20 +145,18 @@ public Retriever call() throws Exception } this.byteBuffer = this.server.getRasterAsByteBuffer(this.copy()); - if (null != this.byteBuffer) - { + if (null != this.byteBuffer) { this.setState(RETRIEVER_STATE_SUCCESSFUL); this.contentLength = this.byteBuffer.capacity(); this.contentLengthRead.set(this.contentLength); - } - else + } else { this.setState(RETRIEVER_STATE_ERROR); + } - if (this.postProcessor != null) + if (this.postProcessor != null) { this.byteBuffer = this.postProcessor.run(this); - } - catch (Exception e) - { + } + } catch (Exception e) { this.setState(RETRIEVER_STATE_ERROR); Logging.logger().log(Level.SEVERE, Logging.getMessage("Retriever.ErrorPostProcessing", this.getName()), e); @@ -193,8 +166,7 @@ public Retriever call() throws Exception return this; } - protected void setState(String state) - { + protected void setState(String state) { String oldState = this.state; this.state = state; this.firePropertyChange(AVKey.RETRIEVER_STATE, oldState, this.state); diff --git a/src/gov/nasa/worldwind/retrieve/Progress.java b/src/gov/nasa/worldwind/retrieve/Progress.java index 3cb4f3ca98..e4238abedb 100644 --- a/src/gov/nasa/worldwind/retrieve/Progress.java +++ b/src/gov/nasa/worldwind/retrieve/Progress.java @@ -11,8 +11,8 @@ * @author Patrick Murris * @version $Id: Progress.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Progress -{ +public class Progress { + private long startTime; // from System.currentTimeMillis private long lastUpdateTime; // from System.currentTimeMillis private long totalSize; @@ -20,69 +20,55 @@ public class Progress private long totalCount; private long currentCount; - public Progress() - { + public Progress() { this.startTime = System.currentTimeMillis(); } - public long getStartTime() - { + public long getStartTime() { return this.startTime; } - public void setStartTime(long time) - { + public void setStartTime(long time) { this.startTime = time; } - public long getLastUpdateTime() - { + public long getLastUpdateTime() { return this.lastUpdateTime; } - public void setLastUpdateTime(long time) - { + public void setLastUpdateTime(long time) { this.lastUpdateTime = time; } - public long getTotalSize() - { + public long getTotalSize() { return this.totalSize; } - public void setTotalSize(long size) - { + public void setTotalSize(long size) { this.totalSize = size; } - public long getCurrentSize() - { + public long getCurrentSize() { return this.currentSize; } - public void setCurrentSize(long size) - { + public void setCurrentSize(long size) { this.currentSize = size; } - public long getTotalCount() - { + public long getTotalCount() { return this.totalCount; } - public void setTotalCount(long count) - { + public void setTotalCount(long count) { this.totalCount = count; } - public long getCurrentCount() - { + public long getCurrentCount() { return this.currentCount; } - public void setCurrentCount(long count) - { + public void setCurrentCount(long count) { this.currentCount = count; } } - diff --git a/src/gov/nasa/worldwind/retrieve/RetrievalFuture.java b/src/gov/nasa/worldwind/retrieve/RetrievalFuture.java index 277d6992c2..e57c500a91 100644 --- a/src/gov/nasa/worldwind/retrieve/RetrievalFuture.java +++ b/src/gov/nasa/worldwind/retrieve/RetrievalFuture.java @@ -9,7 +9,7 @@ * @author Tom Gaskins * @version $Id: RetrievalFuture.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface RetrievalFuture extends java.util.concurrent.Future -{ +public interface RetrievalFuture extends java.util.concurrent.Future { + public Retriever getRetriever(); } diff --git a/src/gov/nasa/worldwind/retrieve/RetrievalPostProcessor.java b/src/gov/nasa/worldwind/retrieve/RetrievalPostProcessor.java index 277242a8a9..341e84343d 100644 --- a/src/gov/nasa/worldwind/retrieve/RetrievalPostProcessor.java +++ b/src/gov/nasa/worldwind/retrieve/RetrievalPostProcessor.java @@ -9,7 +9,7 @@ * @author Tom Gaskins * @version $Id: RetrievalPostProcessor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface RetrievalPostProcessor -{ +public interface RetrievalPostProcessor { + public java.nio.ByteBuffer run(Retriever retriever); } diff --git a/src/gov/nasa/worldwind/retrieve/RetrievalService.java b/src/gov/nasa/worldwind/retrieve/RetrievalService.java index ea05eb4995..16fa7faefb 100644 --- a/src/gov/nasa/worldwind/retrieve/RetrievalService.java +++ b/src/gov/nasa/worldwind/retrieve/RetrievalService.java @@ -11,8 +11,8 @@ * @author Tom Gaskins * @version $Id: RetrievalService.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface RetrievalService extends WWObject -{ +public interface RetrievalService extends WWObject { + RetrievalFuture runRetriever(Retriever retriever); RetrievalFuture runRetriever(Retriever retriever, double priority); @@ -31,8 +31,8 @@ public interface RetrievalService extends WWObject void shutdown(boolean immediately); - public interface SSLExceptionListener - { + public interface SSLExceptionListener { + void onException(Throwable e, String path); } diff --git a/src/gov/nasa/worldwind/retrieve/Retriever.java b/src/gov/nasa/worldwind/retrieve/Retriever.java index d79247adb9..60565ddf15 100644 --- a/src/gov/nasa/worldwind/retrieve/Retriever.java +++ b/src/gov/nasa/worldwind/retrieve/Retriever.java @@ -11,8 +11,8 @@ * @author Tom Gaskins * @version $Id: Retriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Retriever extends WWObject, java.util.concurrent.Callable -{ +public interface Retriever extends WWObject, java.util.concurrent.Callable { + public final String RETRIEVER_STATE_NOT_STARTED = "gov.nasa.worldwind.RetrieverStatusNotStarted"; public final String RETRIEVER_STATE_STARTED = "gov.nasa.worldwind.RetrieverStatusStarted"; public final String RETRIEVER_STATE_CONNECTING = "gov.nasa.worldwind.RetrieverStatusConnecting"; @@ -37,7 +37,7 @@ public interface Retriever extends WWObject, java.util.concurrent.Callableurl. */ - public URLRetriever(URL url, RetrievalPostProcessor postProcessor) - { - if (url == null) - { + public URLRetriever(URL url, RetrievalPostProcessor postProcessor) { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -98,28 +95,23 @@ public URLRetriever(URL url, RetrievalPostProcessor postProcessor) this.postProcessor = postProcessor; } - public final URL getUrl() - { + public final URL getUrl() { return url; } - public final int getContentLength() - { + public final int getContentLength() { return this.contentLength; } - protected void setContentLengthRead(int length) - { + protected void setContentLengthRead(int length) { this.contentLengthRead.set(length); } - public final int getContentLengthRead() - { + public final int getContentLengthRead() { return this.contentLengthRead.get(); } - public final String getContentType() - { + public final String getContentType() { return this.contentType; } @@ -128,172 +120,137 @@ public final String getContentType() * Cache-Control header. Cache-Control has priority if both headers are specified (see section 14.9.3 of the HTTP Specification). */ - public long getExpirationTime() - { + public long getExpirationTime() { return this.expiration.get(); } - public final ByteBuffer getBuffer() - { + public final ByteBuffer getBuffer() { return this.byteBuffer; } - public final String getName() - { + public final String getName() { return this.url.toString(); } - public final URL getURL() - { + public final URL getURL() { return this.url; } - public final String getState() - { + public final String getState() { return this.state; } - protected final URLConnection getConnection() - { + protected final URLConnection getConnection() { return this.connection; } - public final RetrievalPostProcessor getPostProcessor() - { + public final RetrievalPostProcessor getPostProcessor() { return postProcessor; } - public final int getConnectTimeout() - { + public final int getConnectTimeout() { return connectTimeout; } - public int getReadTimeout() - { + public int getReadTimeout() { return readTimeout; } - public void setReadTimeout(int readTimeout) - { + public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } - public int getStaleRequestLimit() - { + public int getStaleRequestLimit() { return staleRequestLimit; } - public void setStaleRequestLimit(int staleRequestLimit) - { + public void setStaleRequestLimit(int staleRequestLimit) { this.staleRequestLimit = staleRequestLimit; } - public final void setConnectTimeout(int connectTimeout) - { + public final void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } - public long getSubmitTime() - { + public long getSubmitTime() { return submitTime; } - public void setSubmitTime(long submitTime) - { + public void setSubmitTime(long submitTime) { this.submitTime = submitTime; } - public long getBeginTime() - { + public long getBeginTime() { return beginTime; } - public void setBeginTime(long beginTime) - { + public void setBeginTime(long beginTime) { this.beginTime = beginTime; } - public long getEndTime() - { + public long getEndTime() { return endTime; } - public void setEndTime(long endTime) - { + public void setEndTime(long endTime) { this.endTime = endTime; } - public final Retriever call() throws Exception - { - if (this.interrupted()) + public final Retriever call() throws Exception { + if (this.interrupted()) { return this; + } - try - { + try { this.setState(RETRIEVER_STATE_STARTED); - if (!this.interrupted()) - { + if (!this.interrupted()) { this.setState(RETRIEVER_STATE_CONNECTING); this.connection = this.openConnection(); } - if (!this.interrupted()) - { + if (!this.interrupted()) { this.setState(RETRIEVER_STATE_READING); this.byteBuffer = this.read(); } - if (!this.interrupted()) + if (!this.interrupted()) { this.setState(RETRIEVER_STATE_SUCCESSFUL); + } WorldWind.getNetworkStatus().logAvailableHost(this.url); - } - catch (UnknownHostException e) - { + } catch (UnknownHostException e) { this.setState(RETRIEVER_STATE_ERROR); WorldWind.getNetworkStatus().logUnavailableHost(this.url); throw e; - } - catch (SocketException e) - { + } catch (SocketException e) { this.setState(RETRIEVER_STATE_ERROR); WorldWind.getNetworkStatus().logUnavailableHost(this.url); throw e; - } - catch (ClosedByInterruptException e) - { + } catch (ClosedByInterruptException e) { this.interrupted(); - } - catch (Exception e) - { + } catch (Exception e) { this.setState(RETRIEVER_STATE_ERROR); - if (!(e instanceof java.net.SocketTimeoutException)) - { + if (!(e instanceof java.net.SocketTimeoutException)) { Logging.logger().log(Level.SEVERE, - Logging.getMessage("URLRetriever.ErrorAttemptingToRetrieve", this.url.toString()), e); + Logging.getMessage("URLRetriever.ErrorAttemptingToRetrieve", this.url.toString()), e); } throw e; - } - finally - { + } finally { this.end(); } return this; } - protected void setState(String state) - { + protected void setState(String state) { String oldState = this.state; this.state = state; this.firePropertyChange(AVKey.RETRIEVER_STATE, oldState, this.state); } - protected boolean interrupted() - { - if (Thread.currentThread().isInterrupted()) - { + protected boolean interrupted() { + if (Thread.currentThread().isInterrupted()) { this.setState(RETRIEVER_STATE_INTERRUPTED); String message = Logging.getMessage("URLRetriever.RetrievalInterruptedFor", this.url.toString()); Logging.logger().fine(message); @@ -302,20 +259,17 @@ protected boolean interrupted() return false; } - protected URLConnection openConnection() throws IOException - { - try - { + protected URLConnection openConnection() throws IOException { + try { Proxy proxy = WWIO.configureProxy(); - if (proxy != null) + if (proxy != null) { this.connection = this.url.openConnection(proxy); - else + } else { this.connection = this.url.openConnection(); - } - catch (java.io.IOException e) - { + } + } catch (java.io.IOException e) { Logging.logger().log(Level.SEVERE, - Logging.getMessage("URLRetriever.ErrorOpeningConnection", this.url.toString()), e); + Logging.getMessage("URLRetriever.ErrorOpeningConnection", this.url.toString()), e); throw e; } @@ -326,8 +280,9 @@ protected URLConnection openConnection() throws IOException throw new IllegalStateException(message); } - if (this.connection instanceof HttpsURLConnection) + if (this.connection instanceof HttpsURLConnection) { this.configureSSLContext((HttpsURLConnection) this.connection); + } this.connection.setConnectTimeout(this.connectTimeout); this.connection.setReadTimeout(this.readTimeout); @@ -335,48 +290,39 @@ protected URLConnection openConnection() throws IOException return connection; } - protected void configureSSLContext(HttpsURLConnection connection) - { + protected void configureSSLContext(HttpsURLConnection connection) { SSLContext sslContext = (SSLContext) WorldWind.getValue(AVKey.HTTP_SSL_CONTEXT); - if (sslContext != null) + if (sslContext != null) { connection.setSSLSocketFactory(sslContext.getSocketFactory()); + } } - protected void end() throws Exception - { - try - { - if (this.postProcessor != null) - { + protected void end() throws Exception { + try { + if (this.postProcessor != null) { this.byteBuffer = this.postProcessor.run(this); } - } - catch (Exception e) - { + } catch (Exception e) { this.setState(RETRIEVER_STATE_ERROR); Logging.logger().log(Level.SEVERE, - Logging.getMessage("Retriever.ErrorPostProcessing", this.url.toString()), e); + Logging.getMessage("Retriever.ErrorPostProcessing", this.url.toString()), e); throw e; } } - protected ByteBuffer read() throws Exception - { - try - { + protected ByteBuffer read() throws Exception { + try { ByteBuffer buffer = this.doRead(this.connection); - if (buffer == null) + if (buffer == null) { this.contentLength = 0; + } return buffer; - } - catch (Exception e) - { + } catch (Exception e) { if (!(e instanceof java.net.SocketTimeoutException || e instanceof UnknownHostException - || e instanceof SocketException)) - { + || e instanceof SocketException)) { Logging.logger().log(Level.SEVERE, - Logging.getMessage("URLRetriever.ErrorReadingFromConnection", this.url.toString()), e); + Logging.getMessage("URLRetriever.ErrorReadingFromConnection", this.url.toString()), e); } throw e; } @@ -387,13 +333,11 @@ protected ByteBuffer read() throws Exception * * @return a buffer containing the content read from the connection * - * @throws Exception if connection is null or an exception occurs during reading. + * @throws Exception if connection is null or an exception occurs during reading. * @throws IllegalArgumentException if connection is null */ - protected ByteBuffer doRead(URLConnection connection) throws Exception - { - if (connection == null) - { + protected ByteBuffer doRead(URLConnection connection) throws Exception { + if (connection == null) { String msg = Logging.getMessage("nullValue.ConnectionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -403,11 +347,9 @@ protected ByteBuffer doRead(URLConnection connection) throws Exception ByteBuffer buffer; InputStream inputStream = null; - try - { + try { inputStream = this.connection.getInputStream(); - if (inputStream == null) - { + if (inputStream == null) { Logging.logger().log(Level.SEVERE, "URLRetriever.InputStreamFromConnectionNull", connection.getURL()); return null; } @@ -419,31 +361,27 @@ protected ByteBuffer doRead(URLConnection connection) throws Exception // automatically unzip the content if the content type is application/zip. this.contentType = connection.getContentType(); if (this.contentType != null && this.contentType.equalsIgnoreCase("application/zip") - && !WWUtil.isEmpty(this.getValue(EXTRACT_ZIP_ENTRY))) - // Assume single file in zip and decompress it + && !WWUtil.isEmpty(this.getValue(EXTRACT_ZIP_ENTRY))) // Assume single file in zip and decompress it + { buffer = this.readZipStream(inputStream, connection.getURL()); - else + } else { buffer = this.readNonSpecificStream(inputStream, connection); - } - finally - { + } + } finally { WWIO.closeStream(inputStream, connection.getURL().toString()); } return buffer; } - protected ByteBuffer readNonSpecificStream(InputStream inputStream, URLConnection connection) throws IOException - { - if (inputStream == null) - { + protected ByteBuffer readNonSpecificStream(InputStream inputStream, URLConnection connection) throws IOException { + if (inputStream == null) { String message = Logging.getMessage("URLRetriever.InputStreamNullFor", connection.getURL()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.contentLength < 1) - { + if (this.contentLength < 1) { return readNonSpecificStreamUnknownLength(inputStream); } @@ -452,26 +390,25 @@ protected ByteBuffer readNonSpecificStream(InputStream inputStream, URLConnectio // System.out.println(this.contentLength + " bytes to read"); int numBytesRead = 0; - while (!this.interrupted() && numBytesRead >= 0 && numBytesRead < buffer.limit()) - { + while (!this.interrupted() && numBytesRead >= 0 && numBytesRead < buffer.limit()) { int count = channel.read(buffer); - if (count > 0) - { + if (count > 0) { numBytesRead += count; this.contentLengthRead.getAndAdd(count); } - if (count < 0) + if (count < 0) { throw new WWRuntimeException("Premature end of stream from server."); + } } - if (buffer != null) + if (buffer != null) { buffer.flip(); + } return buffer; } - protected ByteBuffer readNonSpecificStreamUnknownLength(InputStream inputStream) throws IOException - { + protected ByteBuffer readNonSpecificStreamUnknownLength(InputStream inputStream) throws IOException { final int pageSize = (int) Math.ceil(Math.pow(2, 15)); ReadableByteChannel channel = Channels.newChannel(inputStream); @@ -479,67 +416,60 @@ protected ByteBuffer readNonSpecificStreamUnknownLength(InputStream inputStream) int count = 0; int numBytesRead = 0; - while (!this.interrupted() && count >= 0) - { + while (!this.interrupted() && count >= 0) { count = channel.read(buffer); - if (count > 0) - { + if (count > 0) { numBytesRead += count; this.contentLengthRead.getAndAdd(count); } - if (count > 0 && !buffer.hasRemaining()) - { + if (count > 0 && !buffer.hasRemaining()) { ByteBuffer biggerBuffer = ByteBuffer.allocate(buffer.limit() + pageSize); biggerBuffer.put((ByteBuffer) buffer.rewind()); buffer = biggerBuffer; } } - if (buffer != null) + if (buffer != null) { buffer.flip(); + } return buffer; } /** * @param inputStream a stream to the zip connection. - * @param url the URL of the zip resource. + * @param url the URL of the zip resource. * * @return a buffer containing the content read from the zip stream. * - * @throws java.io.IOException if the stream does not refer to a zip resource or an exception occurs during - * reading. + * @throws java.io.IOException if the stream does not refer to a zip resource or an exception occurs during reading. * @throws IllegalArgumentException if inputStream is null */ - protected ByteBuffer readZipStream(InputStream inputStream, URL url) throws IOException - { + protected ByteBuffer readZipStream(InputStream inputStream, URL url) throws IOException { ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry ze = zis.getNextEntry(); - if (ze == null) - { + if (ze == null) { Logging.logger().severe(Logging.getMessage("URLRetriever.NoZipEntryFor") + url); return null; } ByteBuffer buffer = null; - if (ze.getSize() > 0) - { + if (ze.getSize() > 0) { buffer = ByteBuffer.allocate((int) ze.getSize()); byte[] inputBuffer = new byte[8192]; - while (buffer.hasRemaining()) - { + while (buffer.hasRemaining()) { int count = zis.read(inputBuffer); - if (count > 0) - { + if (count > 0) { buffer.put(inputBuffer, 0, count); this.contentLengthRead.getAndAdd(buffer.position() + 1); } } } - if (buffer != null) + if (buffer != null) { buffer.flip(); + } return buffer; } @@ -555,22 +485,20 @@ protected ByteBuffer readZipStream(InputStream inputStream, URL url) throws IOEx * @param connection Connection for which to get expiration time. * * @return The expiration time, in milliseconds since the Epoch, specified by the HTTP headers, or zero if there is - * no expiration time. + * no expiration time. */ - protected long getExpiration(URLConnection connection) - { + protected long getExpiration(URLConnection connection) { // Read the expiration time from either the Cache-Control header or the Expires header. Cache-Control has // priority if both headers are specified. String cacheControl = connection.getHeaderField("cache-control"); - if (cacheControl != null) - { + if (cacheControl != null) { Pattern pattern = Pattern.compile("max-age=(\\d+)"); Matcher matcher = pattern.matcher(cacheControl); - if (matcher.find()) - { + if (matcher.find()) { Long maxAgeSec = WWUtil.makeLong(matcher.group(1)); - if (maxAgeSec != null) + if (maxAgeSec != null) { return maxAgeSec * 1000 + System.currentTimeMillis(); + } } } @@ -580,19 +508,21 @@ protected long getExpiration(URLConnection connection) long expiration = connection.getExpiration(); long date = connection.getDate(); - if (date > 0 && expiration > date) + if (date > 0 && expiration > date) { return System.currentTimeMillis() + (expiration - date); + } return expiration; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final URLRetriever that = (URLRetriever) o; @@ -602,16 +532,14 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result; result = (url != null ? url.hashCode() : 0); return result; } @Override - public String toString() - { + public String toString() { return this.getName() != null ? this.getName() : super.toString(); } } diff --git a/src/gov/nasa/worldwind/symbology/AbstractIconRetriever.java b/src/gov/nasa/worldwind/symbology/AbstractIconRetriever.java index 04c127c425..cafe42c10d 100644 --- a/src/gov/nasa/worldwind/symbology/AbstractIconRetriever.java +++ b/src/gov/nasa/worldwind/symbology/AbstractIconRetriever.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.util.*; @@ -69,9 +68,11 @@ * @author ccrick * @version $Id: AbstractIconRetriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractIconRetriever implements IconRetriever -{ - /** Path in the file system or network to the symbol repository. */ +public abstract class AbstractIconRetriever implements IconRetriever { + + /** + * Path in the file system or network to the symbol repository. + */ protected String retrieverPath; /** @@ -81,10 +82,8 @@ public abstract class AbstractIconRetriever implements IconRetriever * * @param retrieverPath URL to to the base symbol directory on the local file system or the network. */ - public AbstractIconRetriever(String retrieverPath) - { - if (retrieverPath == null || retrieverPath.length() == 0) - { + public AbstractIconRetriever(String retrieverPath) { + if (retrieverPath == null || retrieverPath.length() == 0) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -100,8 +99,7 @@ public AbstractIconRetriever(String retrieverPath) * * @return File system or network path to symbol repository. */ - public String getRetrieverPath() - { + public String getRetrieverPath() { return this.retrieverPath; } @@ -111,24 +109,26 @@ public String getRetrieverPath() * @param o Object to compare. * * @return {@code true} if {@code o} is an instance of AbstractIconRetriever and has the same retrieval path as this - * retriever. + * retriever. */ @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } AbstractIconRetriever that = (AbstractIconRetriever) o; return this.retrieverPath != null ? this.retrieverPath.equals(that.retrieverPath) : that.retrieverPath == null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public int hashCode() - { + public int hashCode() { return this.retrieverPath != null ? this.retrieverPath.hashCode() : 0; } @@ -141,10 +141,8 @@ public int hashCode() * * @return The requested icon as a BufferedImage, or null if the icon cannot be loaded. */ - protected BufferedImage readImage(String path) - { - if (path == null) - { + protected BufferedImage readImage(String path) { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -156,23 +154,20 @@ protected BufferedImage readImage(String path) sb.append(WWIO.stripLeadingSeparator(path)); InputStream is = null; - try - { + try { URL url = WWIO.makeURL(sb.toString()); - if (url != null) + if (url != null) { return ImageIO.read(url); + } is = WWIO.openFileOrResourceStream(sb.toString(), this.getClass()); - if (is != null) + if (is != null) { return ImageIO.read(is); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("generic.ExceptionWhileReading", sb.toString()); Logging.logger().fine(msg); - } - finally - { + } finally { WWIO.closeStream(is, sb.toString()); } @@ -182,37 +177,32 @@ protected BufferedImage readImage(String path) /** * Draw one image into another image. The image is drawn at location (0, 0). * - * @param src Image to draw. + * @param src Image to draw. * @param dest Image to draw into. * * @return {@code dest} BufferedImage. */ - protected BufferedImage drawImage(BufferedImage src, BufferedImage dest) - { - if (src == null) - { + protected BufferedImage drawImage(BufferedImage src, BufferedImage dest) { + if (src == null) { String msg = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dest == null) - { + if (dest == null) { String msg = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Graphics2D g = null; - try - { + try { g = dest.createGraphics(); g.drawImage(src, 0, 0, null); - } - finally - { - if (g != null) + } finally { + if (g != null) { g.dispose(); + } } return dest; @@ -227,17 +217,14 @@ protected BufferedImage drawImage(BufferedImage src, BufferedImage dest) * * @see #replaceColor(java.awt.image.BufferedImage, java.awt.Color) */ - protected void multiply(BufferedImage image, Color color) - { - if (image == null) - { + protected void multiply(BufferedImage image, Color color) { + if (image == null) { String msg = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (color == null) - { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -246,8 +233,9 @@ protected void multiply(BufferedImage image, Color color) int w = image.getWidth(); int h = image.getHeight(); - if (w == 0 || h == 0) + if (w == 0 || h == 0) { return; + } int[] pixels = new int[w]; int c = color.getRGB(); @@ -256,12 +244,10 @@ protected void multiply(BufferedImage image, Color color) float cg = ((c >> 8) & 0xff) / 255f; float cb = (c & 0xff) / 255f; - for (int y = 0; y < h; y++) - { + for (int y = 0; y < h; y++) { image.getRGB(0, y, w, 1, pixels, 0, w); - for (int x = 0; x < w; x++) - { + for (int x = 0; x < w; x++) { int s = pixels[x]; float sa = ((s >> 24) & 0xff) / 255f; float sr = ((s >> 16) & 0xff) / 255f; @@ -274,9 +260,9 @@ protected void multiply(BufferedImage image, Color color) int fb = (int) (cb * sb * 255 + 0.5); pixels[x] = (fa & 0xff) << 24 - | (fr & 0xff) << 16 - | (fg & 0xff) << 8 - | (fb & 0xff); + | (fr & 0xff) << 16 + | (fg & 0xff) << 8 + | (fb & 0xff); } image.setRGB(0, y, w, 1, pixels, 0, w); @@ -293,17 +279,14 @@ protected void multiply(BufferedImage image, Color color) * * @see #multiply(java.awt.image.BufferedImage, java.awt.Color) */ - protected void replaceColor(BufferedImage image, Color color) - { - if (image == null) - { + protected void replaceColor(BufferedImage image, Color color) { + if (image == null) { String msg = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (color == null) - { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -312,8 +295,9 @@ protected void replaceColor(BufferedImage image, Color color) int w = image.getWidth(); int h = image.getHeight(); - if (w == 0 || h == 0) + if (w == 0 || h == 0) { return; + } int[] pixels = new int[w]; int c = color.getRGB(); @@ -321,12 +305,10 @@ protected void replaceColor(BufferedImage image, Color color) float cg = ((c >> 8) & 0xff) / 255f; float cb = (c & 0xff) / 255f; - for (int y = 0; y < h; y++) - { + for (int y = 0; y < h; y++) { image.getRGB(0, y, w, 1, pixels, 0, w); - for (int x = 0; x < w; x++) - { + for (int x = 0; x < w; x++) { int s = pixels[x]; float sa = ((s >> 24) & 0xff) / 255f; @@ -336,9 +318,9 @@ protected void replaceColor(BufferedImage image, Color color) int fb = (int) (cb * 255 + 0.5); pixels[x] = (fa & 0xff) << 24 - | (fr & 0xff) << 16 - | (fg & 0xff) << 8 - | (fb & 0xff); + | (fr & 0xff) << 16 + | (fg & 0xff) << 8 + | (fb & 0xff); } image.setRGB(0, y, w, 1, pixels, 0, w); diff --git a/src/gov/nasa/worldwind/symbology/AbstractTacticalGraphic.java b/src/gov/nasa/worldwind/symbology/AbstractTacticalGraphic.java index f8c17327ee..e8c3aa87bb 100644 --- a/src/gov/nasa/worldwind/symbology/AbstractTacticalGraphic.java +++ b/src/gov/nasa/worldwind/symbology/AbstractTacticalGraphic.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.WorldWind; @@ -18,9 +17,9 @@ import java.util.List; /** - * Base class for tactical graphics. See the TacticalGraphic Tutorial - * for - * instructions on using TacticalGraphic in an application. This base class provides functionality for creating and + * Base class for tactical graphics. See the TacticalGraphic + * Tutorial + * for instructions on using TacticalGraphic in an application. This base class provides functionality for creating and * rendering a graphic that is made up of one or more shapes, and text labels. *

          * Implementations must implement at least {@link #doRenderGraphic(gov.nasa.worldwind.render.DrawContext) @@ -29,9 +28,11 @@ * @author pabercrombie * @version $Id: AbstractTacticalGraphic.java 560 2012-04-26 16:28:24Z pabercrombie $ */ -public abstract class AbstractTacticalGraphic extends AVListImpl implements TacticalGraphic, Renderable, Draggable -{ - /** The default highlight color. */ +public abstract class AbstractTacticalGraphic extends AVListImpl implements TacticalGraphic, Renderable, Draggable { + + /** + * The default highlight color. + */ protected static final Material DEFAULT_HIGHLIGHT_MATERIAL = Material.WHITE; /** * Opacity of label interiors. This value is multiplied by the label text opacity to determine the final interior @@ -45,17 +46,29 @@ public abstract class AbstractTacticalGraphic extends AVListImpl implements Tact */ protected String text; - /** Indicates whether or not the graphic is highlighted. */ + /** + * Indicates whether or not the graphic is highlighted. + */ protected boolean highlighted; - /** Indicates whether or not to render the graphic. */ + /** + * Indicates whether or not to render the graphic. + */ protected boolean visible = true; - /** Indicates whether or not to render text modifiers. */ + /** + * Indicates whether or not to render text modifiers. + */ protected boolean showTextModifiers = true; - /** Indicates whether or not to render graphic modifiers. */ + /** + * Indicates whether or not to render graphic modifiers. + */ protected boolean showGraphicModifiers = true; - /** Indicates whether this object can be dragged. */ + /** + * Indicates whether this object can be dragged. + */ protected boolean dragEnabled = true; - /** Provides additional information for dragging regarding this particular object. */ + /** + * Provides additional information for dragging regarding this particular object. + */ protected DraggableSupport draggableSupport = null; // Implementation note: by default, show the hostile indicator (the letters "ENY"). Note that this default is @@ -64,14 +77,22 @@ public abstract class AbstractTacticalGraphic extends AVListImpl implements Tact // display the indicator by default following the principle that by default hostile entities should look as // hostile as possible (to avoid being mistaken for friendly entities). In the case of tactical symbols, however, // the indicator is redundant to both the symbol frame and fill, so it is not displayed by default. - /** Indicates whether or not to render the hostile/enemy modifier. This modifier is displayed by default. */ + /** + * Indicates whether or not to render the hostile/enemy modifier. This modifier is displayed by default. + */ protected boolean showHostileIndicator = true; - /** Indicates whether or not to render the location modifier. */ + /** + * Indicates whether or not to render the location modifier. + */ protected boolean showLocation = true; - /** Object returned during picking to represent this graphic. */ + /** + * Object returned during picking to represent this graphic. + */ protected Object delegateOwner; - /** Unit format used to format location and altitude for text modifiers. */ + /** + * Unit format used to format location and altitude for text modifiers. + */ protected UnitsFormat unitsFormat = AbstractTacticalSymbol.DEFAULT_UNITS_FORMAT; /** @@ -85,9 +106,13 @@ public abstract class AbstractTacticalGraphic extends AVListImpl implements Tact */ protected TacticalGraphicAttributes highlightAttributes; - /** Offset applied to the graphic's main label. */ + /** + * Offset applied to the graphic's main label. + */ protected Offset labelOffset; - /** Labels to render with the graphic. */ + /** + * Labels to render with the graphic. + */ protected List labels; /** @@ -96,10 +121,14 @@ public abstract class AbstractTacticalGraphic extends AVListImpl implements Tact */ protected AVList modifiers; - /** Current frame timestamp. */ + /** + * Current frame timestamp. + */ protected long frameTimestamp = -1L; - /** Override attributes for the current frame. */ + /** + * Override attributes for the current frame. + */ protected TacticalGraphicAttributes activeOverrides = new BasicTacticalGraphicAttributes(); /** * Shape attributes shared by all shapes that make up this graphic. The graphic's active attributes are copied into @@ -107,7 +136,9 @@ public abstract class AbstractTacticalGraphic extends AVListImpl implements Tact */ protected ShapeAttributes activeShapeAttributes = new BasicShapeAttributes(); - /** Flag to indicate that labels must be recreated before the graphic is rendered. */ + /** + * Flag to indicate that labels must be recreated before the graphic is rendered. + */ protected boolean mustCreateLabels = true; /** @@ -129,144 +160,166 @@ public abstract class AbstractTacticalGraphic extends AVListImpl implements Tact */ protected abstract void applyDelegateOwner(Object owner); - /** {@inheritDoc} */ - public Object getModifier(String modifier) - { + /** + * {@inheritDoc} + */ + public Object getModifier(String modifier) { return this.modifiers != null ? this.modifiers.getValue(modifier) : null; } - /** {@inheritDoc} */ - public void setModifier(String modifier, Object value) - { - if (this.modifiers == null) + /** + * {@inheritDoc} + */ + public void setModifier(String modifier, Object value) { + if (this.modifiers == null) { this.modifiers = new AVListImpl(); + } this.modifiers.setValue(modifier, value); this.onModifierChanged(); } - /** {@inheritDoc} */ - public boolean isShowTextModifiers() - { + /** + * {@inheritDoc} + */ + public boolean isShowTextModifiers() { return this.showTextModifiers; } - /** {@inheritDoc} */ - public void setShowTextModifiers(boolean showModifiers) - { + /** + * {@inheritDoc} + */ + public void setShowTextModifiers(boolean showModifiers) { this.showTextModifiers = showModifiers; } - /** {@inheritDoc} */ - public boolean isShowGraphicModifiers() - { + /** + * {@inheritDoc} + */ + public boolean isShowGraphicModifiers() { return this.showGraphicModifiers; } - /** {@inheritDoc} */ - public void setShowGraphicModifiers(boolean showModifiers) - { + /** + * {@inheritDoc} + */ + public void setShowGraphicModifiers(boolean showModifiers) { this.showGraphicModifiers = showModifiers; } - /** {@inheritDoc} */ - public boolean isShowHostileIndicator() - { + /** + * {@inheritDoc} + */ + public boolean isShowHostileIndicator() { return this.showHostileIndicator; } - /** {@inheritDoc} */ - public void setShowHostileIndicator(boolean showHostileIndicator) - { + /** + * {@inheritDoc} + */ + public void setShowHostileIndicator(boolean showHostileIndicator) { this.showHostileIndicator = showHostileIndicator; this.onModifierChanged(); } - /** {@inheritDoc} */ - public boolean isShowLocation() - { + /** + * {@inheritDoc} + */ + public boolean isShowLocation() { return this.showLocation; } - /** {@inheritDoc} */ - public void setShowLocation(boolean showLocation) - { + /** + * {@inheritDoc} + */ + public void setShowLocation(boolean showLocation) { this.showLocation = showLocation; this.onModifierChanged(); } - /** {@inheritDoc} */ - public String getText() - { + /** + * {@inheritDoc} + */ + public String getText() { return this.text; } - /** {@inheritDoc} */ - public void setText(String text) - { + /** + * {@inheritDoc} + */ + public void setText(String text) { this.text = text; this.onModifierChanged(); } - /** {@inheritDoc} */ - public boolean isVisible() - { + /** + * {@inheritDoc} + */ + public boolean isVisible() { return this.visible; } - /** {@inheritDoc} */ - public void setVisible(boolean visible) - { + /** + * {@inheritDoc} + */ + public void setVisible(boolean visible) { this.visible = visible; } - /** {@inheritDoc} */ - public TacticalGraphicAttributes getAttributes() - { + /** + * {@inheritDoc} + */ + public TacticalGraphicAttributes getAttributes() { return this.normalAttributes; } - /** {@inheritDoc} */ - public void setAttributes(TacticalGraphicAttributes attributes) - { + /** + * {@inheritDoc} + */ + public void setAttributes(TacticalGraphicAttributes attributes) { this.normalAttributes = attributes; } - /** {@inheritDoc} */ - public TacticalGraphicAttributes getHighlightAttributes() - { + /** + * {@inheritDoc} + */ + public TacticalGraphicAttributes getHighlightAttributes() { return this.highlightAttributes; } - /** {@inheritDoc} */ - public void setHighlightAttributes(TacticalGraphicAttributes attributes) - { + /** + * {@inheritDoc} + */ + public void setHighlightAttributes(TacticalGraphicAttributes attributes) { this.highlightAttributes = attributes; } - /** {@inheritDoc} */ - public Object getDelegateOwner() - { + /** + * {@inheritDoc} + */ + public Object getDelegateOwner() { return this.delegateOwner; } - /** {@inheritDoc} */ - public void setDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + public void setDelegateOwner(Object owner) { this.delegateOwner = owner; } - /** {@inheritDoc} */ - public UnitsFormat getUnitsFormat() - { + /** + * {@inheritDoc} + */ + public UnitsFormat getUnitsFormat() { return this.unitsFormat; } - /** {@inheritDoc} */ - public void setUnitsFormat(UnitsFormat unitsFormat) - { - if (unitsFormat == null) - { + /** + * {@inheritDoc} + */ + public void setUnitsFormat(UnitsFormat unitsFormat) { + if (unitsFormat == null) { String msg = Logging.getMessage("nullValue.Format"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -275,39 +328,42 @@ public void setUnitsFormat(UnitsFormat unitsFormat) this.unitsFormat = unitsFormat; } - /** {@inheritDoc} */ - public Offset getLabelOffset() - { + /** + * {@inheritDoc} + */ + public Offset getLabelOffset() { return this.labelOffset; } - /** {@inheritDoc} */ - public void setLabelOffset(Offset labelOffset) - { + /** + * {@inheritDoc} + */ + public void setLabelOffset(Offset labelOffset) { this.labelOffset = labelOffset; } - /** {@inheritDoc} */ - public boolean isHighlighted() - { + /** + * {@inheritDoc} + */ + public boolean isHighlighted() { return this.highlighted; } - /** {@inheritDoc} */ - public void setHighlighted(boolean highlighted) - { + /** + * {@inheritDoc} + */ + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } ///////////////////////////// // Movable interface ///////////////////////////// - - /** {@inheritDoc} */ - public void move(Position delta) - { - if (delta == null) - { + /** + * {@inheritDoc} + */ + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -317,17 +373,18 @@ public void move(Position delta) // The reference position is null if this shape has no positions. In this case moving the shape by a // relative delta is meaningless. Therefore we fail softly by exiting and doing nothing. - if (refPos == null) + if (refPos == null) { return; + } this.moveTo(refPos.add(delta)); } - /** {@inheritDoc} */ - public void moveTo(Position position) - { - if (position == null) - { + /** + * {@inheritDoc} + */ + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -337,53 +394,52 @@ public void moveTo(Position position) // The reference position is null if this shape has no positions. In this case moving the shape to a new // reference position is meaningless. Therefore we fail softly by exiting and doing nothing. - if (oldPosition == null) + if (oldPosition == null) { return; + } List newPositions = Position.computeShiftedPositions(oldPosition, position, this.getPositions()); - if (newPositions != null) + if (newPositions != null) { this.setPositions(newPositions); + } } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, WorldWind.CLAMP_TO_GROUND); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragGlobeSizeConstant(dragContext); } ///////////// // Rendering ///////////// - - /** {@inheritDoc} */ - public void render(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { + if (!this.isVisible()) { return; } @@ -391,11 +447,13 @@ public void render(DrawContext dc) this.doRenderGraphic(dc); - if (this.isShowTextModifiers()) + if (this.isShowTextModifiers()) { this.doRenderTextModifiers(dc); + } - if (this.isShowGraphicModifiers()) + if (this.isShowGraphicModifiers()) { this.doRenderGraphicModifiers(dc); + } } /** @@ -404,16 +462,12 @@ public void render(DrawContext dc) * * @param dc Current draw context. */ - protected void determinePerFrameAttributes(DrawContext dc) - { + protected void determinePerFrameAttributes(DrawContext dc) { long timeStamp = dc.getFrameTimeStamp(); - if (this.frameTimestamp != timeStamp) - { + if (this.frameTimestamp != timeStamp) { // Allow the subclass to create labels, if necessary - if (this.mustCreateLabels) - { - if (this.labels != null) - { + if (this.mustCreateLabels) { + if (this.labels != null) { this.labels.clear(); } @@ -434,13 +488,12 @@ protected void determinePerFrameAttributes(DrawContext dc) * * @param dc Current draw context. */ - protected void doRenderTextModifiers(DrawContext dc) - { - if (this.labels == null) + protected void doRenderTextModifiers(DrawContext dc) { + if (this.labels == null) { return; + } - for (TacticalGraphicLabel label : this.labels) - { + for (TacticalGraphicLabel label : this.labels) { label.render(dc); } } @@ -451,8 +504,7 @@ protected void doRenderTextModifiers(DrawContext dc) * * @param dc Current draw context. */ - protected void doRenderGraphicModifiers(DrawContext dc) - { + protected void doRenderGraphicModifiers(DrawContext dc) { // Do nothing, but allow subclasses to override to add graphic modifiers. } @@ -460,8 +512,7 @@ protected void doRenderGraphicModifiers(DrawContext dc) * Invoked when a modifier is changed. This implementation marks the label text as invalid causing it to be * recreated based on the new modifiers. */ - protected void onModifierChanged() - { + protected void onModifierChanged() { // Text may need to change to reflect new modifiers. this.mustCreateLabels = true; } @@ -471,20 +522,18 @@ protected void onModifierChanged() * * @param dc Current draw context. */ - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { // Do nothing, but allow subclasses to override } - protected void createLabels() - { + protected void createLabels() { // Do nothing, but allow subclasses to override } - protected TacticalGraphicLabel addLabel(String text) - { - if (this.labels == null) + protected TacticalGraphicLabel addLabel(String text) { + if (this.labels == null) { this.labels = new ArrayList(); + } TacticalGraphicLabel label = new TacticalGraphicLabel(); label.setText(text); @@ -495,8 +544,7 @@ protected TacticalGraphicLabel addLabel(String text) return label; } - protected void computeGeometry(DrawContext dc) - { + protected void computeGeometry(DrawContext dc) { // Allow the subclass to decide where to put the labels this.determineLabelPositions(dc); } @@ -505,15 +553,12 @@ protected void computeGeometry(DrawContext dc) * Determine the delegate owner for the current frame, and apply the owner to all renderable objects used to draw * the graphic. */ - protected void determineDelegateOwner() - { + protected void determineDelegateOwner() { Object owner = this.getActiveDelegateOwner(); // Apply the delegate owner to all label objects. - if (this.labels != null) - { - for (TacticalGraphicLabel label : this.labels) - { + if (this.labels != null) { + for (TacticalGraphicLabel label : this.labels) { label.setDelegateOwner(owner); } } @@ -527,32 +572,28 @@ protected void determineDelegateOwner() * * @return Delegate owner, if specified, or {@code this} if an owner is not specified. */ - protected Object getActiveDelegateOwner() - { + protected Object getActiveDelegateOwner() { Object owner = this.getDelegateOwner(); return owner != null ? owner : this; } - /** Determine active attributes for this frame. */ - protected void determineActiveAttributes() - { + /** + * Determine active attributes for this frame. + */ + protected void determineActiveAttributes() { // Apply defaults for this graphic this.applyDefaultAttributes(this.activeShapeAttributes); - if (this.isHighlighted()) - { + if (this.isHighlighted()) { TacticalGraphicAttributes highlightAttributes = this.getHighlightAttributes(); // If the application specified overrides to the highlight attributes, then apply the overrides - if (highlightAttributes != null) - { + if (highlightAttributes != null) { this.activeOverrides.copy(highlightAttributes); // Apply overrides specified by application this.applyOverrideAttributes(highlightAttributes, this.activeShapeAttributes); - } - else - { + } else { // If no highlight attributes have been specified we need to use the normal attributes but adjust them // to cause highlighting. this.activeShapeAttributes.setOutlineMaterial(DEFAULT_HIGHLIGHT_MATERIAL); @@ -560,13 +601,10 @@ protected void determineActiveAttributes() this.activeShapeAttributes.setInteriorOpacity(1.0); this.activeShapeAttributes.setOutlineOpacity(1.0); } - } - else - { + } else { // Apply overrides specified by application TacticalGraphicAttributes normalAttributes = this.getAttributes(); - if (normalAttributes != null) - { + if (normalAttributes != null) { this.activeOverrides.copy(normalAttributes); this.applyOverrideAttributes(normalAttributes, this.activeShapeAttributes); } @@ -575,17 +613,20 @@ protected void determineActiveAttributes() this.applyLabelAttributes(); } - /** Apply the active attributes to the graphic's labels. */ - protected void applyLabelAttributes() - { - if (WWUtil.isEmpty(this.labels)) + /** + * Apply the active attributes to the graphic's labels. + */ + protected void applyLabelAttributes() { + if (WWUtil.isEmpty(this.labels)) { return; + } Material labelMaterial = this.getLabelMaterial(); Font font = this.activeOverrides.getTextModifierFont(); - if (font == null) + if (font == null) { font = TacticalGraphicLabel.DEFAULT_FONT; + } double opacity = this.getActiveShapeAttributes().getInteriorOpacity(); @@ -593,8 +634,7 @@ protected void applyLabelAttributes() // interior. double labelInteriorOpacity = this.computeLabelInteriorOpacity(opacity); - for (TacticalGraphicLabel label : this.labels) - { + for (TacticalGraphicLabel label : this.labels) { label.setMaterial(labelMaterial); label.setFont(font); label.setOpacity(opacity); @@ -603,8 +643,9 @@ protected void applyLabelAttributes() // Apply the offset to the main label. Offset offset = this.getLabelOffset(); - if (offset == null) + if (offset == null) { offset = this.getDefaultLabelOffset(); + } this.labels.get(0).setOffset(offset); } @@ -616,8 +657,7 @@ protected void applyLabelAttributes() * * @return Opacity of the label interior as a floating point number between 0.0 and 1.0. */ - protected double computeLabelInteriorOpacity(double textOpacity) - { + protected double computeLabelInteriorOpacity(double textOpacity) { return textOpacity * DEFAULT_LABEL_INTERIOR_OPACITY; } @@ -627,8 +667,7 @@ protected double computeLabelInteriorOpacity(double textOpacity) * * @return Offset to apply to the main label. */ - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { return TacticalGraphicLabel.DEFAULT_OFFSET; } @@ -637,8 +676,7 @@ protected Offset getDefaultLabelOffset() * * @return Override attributes. Values set in this bundle override defaults specified by the symbol set. */ - protected TacticalGraphicAttributes getActiveOverrideAttributes() - { + protected TacticalGraphicAttributes getActiveOverrideAttributes() { return this.activeOverrides; } @@ -648,8 +686,7 @@ protected TacticalGraphicAttributes getActiveOverrideAttributes() * * @return Active shape attributes. */ - protected ShapeAttributes getActiveShapeAttributes() - { + protected ShapeAttributes getActiveShapeAttributes() { return this.activeShapeAttributes; } @@ -659,13 +696,13 @@ protected ShapeAttributes getActiveShapeAttributes() * * @return The Material that should be used when drawing labels. May change each frame. */ - protected Material getLabelMaterial() - { + protected Material getLabelMaterial() { Material material = this.activeOverrides.getTextModifierMaterial(); - if (material != null) + if (material != null) { return material; - else + } else { return this.activeShapeAttributes.getOutlineMaterial(); + } } /** @@ -675,8 +712,7 @@ protected Material getLabelMaterial() * * @param attributes Attributes bundle to receive defaults. */ - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { // Do nothing but allow subclasses to override } @@ -685,37 +721,31 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) * non-null properties of {@code graphicAttributes} will be applied to {@code shapeAttributes}. * * @param graphicAttributes Override attributes. - * @param shapeAttributes Shape attributes to receive overrides. + * @param shapeAttributes Shape attributes to receive overrides. */ - protected void applyOverrideAttributes(TacticalGraphicAttributes graphicAttributes, ShapeAttributes shapeAttributes) - { + protected void applyOverrideAttributes(TacticalGraphicAttributes graphicAttributes, ShapeAttributes shapeAttributes) { Material material = graphicAttributes.getInteriorMaterial(); - if (material != null) - { + if (material != null) { shapeAttributes.setInteriorMaterial(material); } material = graphicAttributes.getOutlineMaterial(); - if (material != null) - { + if (material != null) { shapeAttributes.setOutlineMaterial(material); } Double value = graphicAttributes.getInteriorOpacity(); - if (value != null) - { + if (value != null) { shapeAttributes.setInteriorOpacity(value); } value = graphicAttributes.getOutlineOpacity(); - if (value != null) - { + if (value != null) { shapeAttributes.setOutlineOpacity(value); } value = graphicAttributes.getOutlineWidth(); - if (value != null) - { + if (value != null) { shapeAttributes.setOutlineWidth(value); } } diff --git a/src/gov/nasa/worldwind/symbology/AbstractTacticalSymbol.java b/src/gov/nasa/worldwind/symbology/AbstractTacticalSymbol.java index cd4100267d..45c5c2232a 100644 --- a/src/gov/nasa/worldwind/symbology/AbstractTacticalSymbol.java +++ b/src/gov/nasa/worldwind/symbology/AbstractTacticalSymbol.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import com.jogamp.opengl.util.texture.*; @@ -28,21 +27,19 @@ * @author dcollins * @version $Id: AbstractTacticalSymbol.java 2366 2014-10-02 23:16:31Z tgaskins $ */ -public abstract class AbstractTacticalSymbol extends WWObjectImpl implements TacticalSymbol, Movable, Draggable -{ - protected static class IconSource - { +public abstract class AbstractTacticalSymbol extends WWObjectImpl implements TacticalSymbol, Movable, Draggable { + + protected static class IconSource { + protected IconRetriever retriever; protected String symbolId; protected AVList retrieverParams; - public IconSource(IconRetriever retriever, String symbolId, AVList retrieverParams) - { + public IconSource(IconRetriever retriever, String symbolId, AVList retrieverParams) { this.retriever = retriever; this.symbolId = symbolId; - if (retrieverParams != null) - { + if (retrieverParams != null) { // If the specified parameters are non-null, then store a copy of the parameters in this key's params // property to insulate it from changes made by the caller. This params list must not change after // construction this key's properties must be immutable. @@ -51,39 +48,38 @@ public IconSource(IconRetriever retriever, String symbolId, AVList retrieverPara } } - public IconRetriever getRetriever() - { + public IconRetriever getRetriever() { return this.retriever; } - public String getSymbolId() - { + public String getSymbolId() { return this.symbolId; } - public AVList getRetrieverParams() - { + public AVList getRetrieverParams() { return this.retrieverParams; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } IconSource that = (IconSource) o; if (this.retriever != null ? !this.retriever.equals(that.retriever) - : that.retriever != null) + : that.retriever != null) { return false; - if (this.symbolId != null ? !this.symbolId.equals(that.symbolId) : that.symbolId != null) + } + if (this.symbolId != null ? !this.symbolId.equals(that.symbolId) : that.symbolId != null) { return false; + } - if (this.retrieverParams != null && that.retrieverParams != null) - { + if (this.retrieverParams != null && that.retrieverParams != null) { Set> theseEntries = this.retrieverParams.getEntries(); Set> thoseEntries = that.retrieverParams.getEntries(); @@ -93,8 +89,7 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result = this.retriever != null ? this.retriever.hashCode() : 0; result = 31 * result + (this.symbolId != null ? this.symbolId.hashCode() : 0); result = 31 * result + (this.retrieverParams != null ? this.retrieverParams.getEntries().hashCode() : 0); @@ -102,46 +97,40 @@ public int hashCode() } @Override - public String toString() - { + public String toString() { return this.symbolId; } } // Use an IconKey as the texture's image source. The image source is what defines the contents of this texture, // and is used as an address for the texture's contents in the cache. - protected static class IconTexture extends LazilyLoadedTexture - { - public IconTexture(IconSource imageSource) - { + protected static class IconTexture extends LazilyLoadedTexture { + + public IconTexture(IconSource imageSource) { super(imageSource); } - public IconTexture(IconSource imageSource, boolean useMipMaps) - { + public IconTexture(IconSource imageSource, boolean useMipMaps) { super(imageSource, useMipMaps); } - protected boolean loadTextureData() - { + protected boolean loadTextureData() { TextureData td = this.createIconTextureData(); - if (td != null) + if (td != null) { this.setTextureData(td); + } return td != null; } - protected TextureData createIconTextureData() - { - try - { + protected TextureData createIconTextureData() { + try { IconSource source = (IconSource) this.getImageSource(); BufferedImage image = source.getRetriever().createIcon(source.getSymbolId(), - source.getRetrieverParams()); + source.getRetrieverParams()); - if (image == null) - { + if (image == null) { // IconRetriever returns null if the symbol identifier is not recognized, or if the parameter list // specified an empty icon. In either case, we mark the texture initialization as having failed to // suppress any further requests. @@ -150,10 +139,8 @@ protected TextureData createIconTextureData() } return AWTTextureIO.newTextureData(Configuration.getMaxCompatibleGLProfile(), image, - this.isUseMipMaps()); - } - catch (Exception e) - { + this.isUseMipMaps()); + } catch (Exception e) { String msg = Logging.getMessage("Symbology.ExceptionRetrievingTacticalIcon", this.getImageSource()); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.textureInitializationFailed = true; // Suppress subsequent requests for this tactical icon. @@ -162,19 +149,16 @@ protected TextureData createIconTextureData() } @Override - protected Runnable createRequestTask() - { + protected Runnable createRequestTask() { return new IconRequestTask(this); } - protected static class IconRequestTask implements Runnable - { + protected static class IconRequestTask implements Runnable { + protected final IconTexture texture; - protected IconRequestTask(IconTexture texture) - { - if (texture == null) - { + protected IconRequestTask(IconTexture texture) { + if (texture == null) { String message = Logging.getMessage("nullValue.TextureIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -183,80 +167,75 @@ protected IconRequestTask(IconTexture texture) this.texture = texture; } - public void run() - { - if (Thread.currentThread().isInterrupted()) + public void run() { + if (Thread.currentThread().isInterrupted()) { return; // the task was cancelled because it's a duplicate or for some other reason - - if (this.texture.loadTextureData()) + } + if (this.texture.loadTextureData()) { this.texture.notifyTextureLoaded(); + } } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final IconRequestTask that = (IconRequestTask) o; return this.texture != null ? this.texture.equals(that.texture) : that.texture == null; } - public int hashCode() - { + public int hashCode() { return (this.texture != null ? this.texture.hashCode() : 0); } - public String toString() - { + public String toString() { return this.texture.getImageSource().toString(); } } } - protected static class IconAtlasElement extends TextureAtlasElement - { + protected static class IconAtlasElement extends TextureAtlasElement { + protected Point point; - /** Indicates the last time, in milliseconds, the element was requested or added. */ + /** + * Indicates the last time, in milliseconds, the element was requested or added. + */ protected long lastUsed = System.currentTimeMillis(); - public IconAtlasElement(TextureAtlas atlas, IconSource source) - { + public IconAtlasElement(TextureAtlas atlas, IconSource source) { super(atlas, source); } - public Point getPoint() - { + public Point getPoint() { return this.point; } - public void setPoint(Point point) - { + public void setPoint(Point point) { this.point = point; } @Override - protected boolean loadImage() - { + protected boolean loadImage() { BufferedImage image = this.createModifierImage(); - if (image != null) + if (image != null) { this.setImage(image); + } return image != null; } - protected BufferedImage createModifierImage() - { - try - { + protected BufferedImage createModifierImage() { + try { IconSource source = (IconSource) this.getImageSource(); BufferedImage image = source.getRetriever().createIcon(source.getSymbolId(), - source.getRetrieverParams()); + source.getRetrieverParams()); - if (image == null) - { + if (image == null) { // ModifierRetriever returns null if the modifier or its value is not recognized. In either case, we // mark the image initialization as having failed to suppress any further requests. this.imageInitializationFailed = true; @@ -264,11 +243,9 @@ protected BufferedImage createModifierImage() } return image; - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("Symbology.ExceptionRetrievingGraphicModifier", - this.getImageSource()); + this.getImageSource()); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); this.imageInitializationFailed = true; // Suppress subsequent requests for this modifier. return null; @@ -276,38 +253,33 @@ protected BufferedImage createModifierImage() } } - protected static class Label - { + protected static class Label { + protected String text; protected Point point; protected Font font; protected Color color; - public Label(String text, Point point, Font font, Color color) - { - if (text == null) - { + public Label(String text, Point point, Font font, Color color) { + if (text == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (point == null) - { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (font == null) - { + if (font == null) { String msg = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (color == null) - { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -319,39 +291,32 @@ public Label(String text, Point point, Font font, Color color) this.color = color; } - public String getText() - { + public String getText() { return this.text; } - public Point getPoint() - { + public Point getPoint() { return this.point; } - public Font getFont() - { + public Font getFont() { return this.font; } - public Color getColor() - { + public Color getColor() { return this.color; } } - protected static class Line - { + protected static class Line { + protected Iterable points; - public Line() - { + public Line() { } - public Line(Iterable points) - { - if (points == null) - { + public Line(Iterable points) { + if (points == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -360,19 +325,17 @@ public Line(Iterable points) this.points = points; } - public Iterable getPoints() - { + public Iterable getPoints() { return points; } - public void setPoints(Iterable points) - { + public void setPoints(Iterable points) { this.points = points; } } - protected class OrderedSymbol implements OrderedRenderable - { + protected class OrderedSymbol implements OrderedRenderable { + /** * Per-frame Cartesian point corresponding to this symbol's position. Calculated each frame in {@link * gov.nasa.worldwind.symbology.AbstractTacticalSymbol#computeSymbolPoints(gov.nasa.worldwind.render.DrawContext, @@ -387,32 +350,35 @@ protected class OrderedSymbol implements OrderedRenderable public Vec4 screenPoint; /** * Per-frame distance corresponding to the distance between the placePoint and the View's eye point. Used to - * order the symbol as an ordered renderable, and is returned by getDistanceFromEye. Calculated each frame in - * {@link gov.nasa.worldwind.symbology.AbstractTacticalSymbol#computeSymbolPoints(gov.nasa.worldwind.render.DrawContext, + * order the symbol as an ordered renderable, and is returned by getDistanceFromEye. Calculated each frame in {@link gov.nasa.worldwind.symbology.AbstractTacticalSymbol#computeSymbolPoints(gov.nasa.worldwind.render.DrawContext, * gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. Initially 0. */ public double eyeDistance; /** * Per-frame screen scale indicating this symbol's x-scale relative to the screen offset. Calculated each frame - * in {@link #computeTransform(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. + * in + * {@link #computeTransform(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. * Initially 0. */ public double sx; /** * Per-frame screen scale indicating this symbol's y-scale relative to the screen offset. Calculated each frame - * in {@link #computeTransform(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. + * in + * {@link #computeTransform(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. * Initially 0. */ public double sy; /** * Per-frame screen offset indicating this symbol's x-offset relative to the screenPoint. Calculated each frame - * in {@link #computeTransform(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. + * in + * {@link #computeTransform(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. * Initially 0. */ public double dx; /** * Per-frame screen offset indicating this symbol's y-offset relative to the screenPoint. Calculated each frame - * in {@link #computeTransform(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. + * in + * {@link #computeTransform(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol)}. * Initially 0. */ public double dy; @@ -420,57 +386,58 @@ protected class OrderedSymbol implements OrderedRenderable public Rectangle layoutRect; public Rectangle screenRect; - /** iconRect with scaling applied, used to lay out text. */ + /** + * iconRect with scaling applied, used to lay out text. + */ public Rectangle iconRectScaled; - /** layoutRect with scaling applied, used to lay out text. */ + /** + * layoutRect with scaling applied, used to lay out text. + */ public Rectangle layoutRectScaled; @Override - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.eyeDistance; } @Override - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { AbstractTacticalSymbol.this.pick(dc, pickPoint, this); } @Override - public void render(DrawContext dc) - { + public void render(DrawContext dc) { AbstractTacticalSymbol.this.drawOrderedRenderable(dc, this); } - public boolean isEnableBatchRendering() - { + public boolean isEnableBatchRendering() { return AbstractTacticalSymbol.this.isEnableBatchRendering(); } - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) - { + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates) { AbstractTacticalSymbol.this.doDrawOrderedRenderable(dc, pickCandidates, this); } - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return AbstractTacticalSymbol.this.isEnableBatchPicking(); } - public Layer getPickLayer() - { + public Layer getPickLayer() { return AbstractTacticalSymbol.this.pickLayer; } } - /** Default unit format. */ + /** + * Default unit format. + */ public static final UnitsFormat DEFAULT_UNITS_FORMAT = new UnitsFormat(); - /** The image file displayed while the icon is loading. */ - public static final String LOADING_IMAGE_PATH = - Configuration.getStringValue("gov.nasa.worldwind.avkey.MilStd2525LoadingIconPath", - "images/doc-loading-128x128.png"); + /** + * The image file displayed while the icon is loading. + */ + public static final String LOADING_IMAGE_PATH + = Configuration.getStringValue("gov.nasa.worldwind.avkey.MilStd2525LoadingIconPath", + "images/doc-loading-128x128.png"); protected static final String LAYOUT_ABSOLUTE = "gov.nasa.worldwind.symbology.TacticalSymbol.LayoutAbsolute"; protected static final String LAYOUT_RELATIVE = "gov.nasa.worldwind.symbology.TacticalSymbol.LayoutRelative"; @@ -493,14 +460,17 @@ public Layer getPickLayer() * symbol that is not visible, rather culling one that is visible. */ protected static final int MAX_SYMBOL_DIMENSION = 256; - /** The default number of label lines to expect when computing the minimum size of the text layout rectangle. */ + /** + * The default number of label lines to expect when computing the minimum size of the text layout rectangle. + */ protected static final int DEFAULT_LABEL_LINES = 5; - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static TacticalSymbolAttributes defaultAttrs; - static - { + static { // Create and populate the default attributes. defaultAttrs = new BasicTacticalSymbolAttributes(); defaultAttrs.setOpacity(BasicTacticalSymbolAttributes.DEFAULT_OPACITY); @@ -544,13 +514,19 @@ public Layer getPickLayer() */ protected boolean showTextModifiers = true; - /** Indicates an object to attach to the picked object list instead of this symbol. */ + /** + * Indicates an object to attach to the picked object list instead of this symbol. + */ protected Object delegateOwner; protected boolean enableBatchRendering = true; protected boolean enableBatchPicking = true; - /** Indicates whether or not to display the implicit location modifier. */ + /** + * Indicates whether or not to display the implicit location modifier. + */ protected boolean showLocation = true; - /** Indicates whether or not to display the implicit hostile indicator modifier. */ + /** + * Indicates whether or not to display the implicit hostile indicator modifier. + */ protected boolean showHostileIndicator; /** * Indicates the current text and graphic modifiers assigned to this symbol. This list of key-value pairs contains @@ -606,7 +582,9 @@ public Layer getPickLayer() */ protected Rectangle staticLayoutRect; - /** Indicates that one or more glyphs have not been resolved. */ + /** + * Indicates that one or more glyphs have not been resolved. + */ protected boolean unresolvedGlyph; protected List currentGlyphs = new ArrayList(); @@ -619,9 +597,13 @@ public Layer getPickLayer() protected Map glyphMap = new HashMap(); protected long maxTimeSinceLastUsed = DEFAULT_MAX_TIME_SINCE_LAST_USED; - /** Unit format used to format location and altitude for text modifiers. */ + /** + * Unit format used to format location and altitude for text modifiers. + */ protected UnitsFormat unitsFormat = DEFAULT_UNITS_FORMAT; - /** Current symbol position, formatted using the current unit format. */ + /** + * Current symbol position, formatted using the current unit format. + */ protected String formattedPosition; /** @@ -652,9 +634,10 @@ public Layer getPickLayer() */ protected LODSelector LODSelector; - /** Constructs a new symbol with no position. */ - protected AbstractTacticalSymbol() - { + /** + * Constructs a new symbol with no position. + */ + protected AbstractTacticalSymbol() { this.setGlyphAtlas(DEFAULT_GLYPH_ATLAS); } @@ -667,10 +650,8 @@ protected AbstractTacticalSymbol() * * @throws IllegalArgumentException if the position is null. */ - protected AbstractTacticalSymbol(Position position) - { - if (position == null) - { + protected AbstractTacticalSymbol(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -680,146 +661,160 @@ protected AbstractTacticalSymbol(Position position) this.setGlyphAtlas(DEFAULT_GLYPH_ATLAS); } - /** {@inheritDoc} */ - public boolean isVisible() - { + /** + * {@inheritDoc} + */ + public boolean isVisible() { return this.visible; } - /** {@inheritDoc} */ - public void setVisible(boolean visible) - { + /** + * {@inheritDoc} + */ + public void setVisible(boolean visible) { this.visible = visible; } - /** {@inheritDoc} */ - public boolean isHighlighted() - { + /** + * {@inheritDoc} + */ + public boolean isHighlighted() { return this.highlighted; } - /** {@inheritDoc} */ - public void setHighlighted(boolean highlighted) - { + /** + * {@inheritDoc} + */ + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } - /** {@inheritDoc} */ - public Position getPosition() - { + /** + * {@inheritDoc} + */ + public Position getPosition() { return this.position; } - /** {@inheritDoc} */ - public void setPosition(Position position) - { - if (position == null) - { + /** + * {@inheritDoc} + */ + public void setPosition(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // If a new position is set then it must be reformatted. - if (!position.equals(this.position)) + if (!position.equals(this.position)) { this.formattedPosition = null; + } this.position = position; } - /** {@inheritDoc} */ - public int getAltitudeMode() - { + /** + * {@inheritDoc} + */ + public int getAltitudeMode() { return this.altitudeMode; } - /** {@inheritDoc} */ - public void setAltitudeMode(int altitudeMode) - { + /** + * {@inheritDoc} + */ + public void setAltitudeMode(int altitudeMode) { this.altitudeMode = altitudeMode; } - /** {@inheritDoc} */ - public boolean isShowGraphicModifiers() - { + /** + * {@inheritDoc} + */ + public boolean isShowGraphicModifiers() { return this.showGraphicModifiers; } - /** {@inheritDoc} */ - public void setShowGraphicModifiers(boolean showGraphicModifiers) - { - if (this.showGraphicModifiers == showGraphicModifiers) + /** + * {@inheritDoc} + */ + public void setShowGraphicModifiers(boolean showGraphicModifiers) { + if (this.showGraphicModifiers == showGraphicModifiers) { return; + } this.showGraphicModifiers = showGraphicModifiers; this.reset(); } - /** {@inheritDoc} */ - public boolean isShowTextModifiers() - { + /** + * {@inheritDoc} + */ + public boolean isShowTextModifiers() { return this.showTextModifiers; } - /** {@inheritDoc} */ - public void setShowTextModifiers(boolean showTextModifiers) - { - if (this.showTextModifiers == showTextModifiers) + /** + * {@inheritDoc} + */ + public void setShowTextModifiers(boolean showTextModifiers) { + if (this.showTextModifiers == showTextModifiers) { return; + } this.showTextModifiers = showTextModifiers; this.reset(); } - /** {@inheritDoc} */ - public boolean isShowLocation() - { + /** + * {@inheritDoc} + */ + public boolean isShowLocation() { return this.showLocation; } - /** {@inheritDoc} */ - public void setShowLocation(boolean show) - { + /** + * {@inheritDoc} + */ + public void setShowLocation(boolean show) { this.showLocation = show; } - /** {@inheritDoc} */ - public boolean isShowHostileIndicator() - { + /** + * {@inheritDoc} + */ + public boolean isShowHostileIndicator() { return this.showHostileIndicator; } - /** {@inheritDoc} */ - public void setShowHostileIndicator(boolean show) - { + /** + * {@inheritDoc} + */ + public void setShowHostileIndicator(boolean show) { this.showHostileIndicator = show; } - public boolean isEnableBatchRendering() - { + public boolean isEnableBatchRendering() { return this.enableBatchRendering; } - public void setEnableBatchRendering(boolean enableBatchRendering) - { + public void setEnableBatchRendering(boolean enableBatchRendering) { this.enableBatchRendering = enableBatchRendering; } - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return this.enableBatchPicking; } - public void setEnableBatchPicking(boolean enableBatchPicking) - { + public void setEnableBatchPicking(boolean enableBatchPicking) { this.enableBatchPicking = enableBatchPicking; } - /** {@inheritDoc} */ - public Object getModifier(String modifier) - { - if (modifier == null) - { + /** + * {@inheritDoc} + */ + public Object getModifier(String modifier) { + if (modifier == null) { String msg = Logging.getMessage("nullValue.ModifierIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -828,11 +823,11 @@ public Object getModifier(String modifier) return this.modifiers.getValue(modifier); } - /** {@inheritDoc} */ - public void setModifier(String modifier, Object value) - { - if (modifier == null) - { + /** + * {@inheritDoc} + */ + public void setModifier(String modifier, Object value) { + if (modifier == null) { String msg = Logging.getMessage("nullValue.ModifierIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -841,88 +836,95 @@ public void setModifier(String modifier, Object value) this.modifiers.setValue(modifier, value); } - /** {@inheritDoc} */ - public TacticalSymbolAttributes getAttributes() - { + /** + * {@inheritDoc} + */ + public TacticalSymbolAttributes getAttributes() { return this.normalAttrs; } - /** {@inheritDoc} */ - public void setAttributes(TacticalSymbolAttributes normalAttrs) - { + /** + * {@inheritDoc} + */ + public void setAttributes(TacticalSymbolAttributes normalAttrs) { this.normalAttrs = normalAttrs; // Null is accepted, and indicates the default attributes are used. } - /** {@inheritDoc} */ - public TacticalSymbolAttributes getHighlightAttributes() - { + /** + * {@inheritDoc} + */ + public TacticalSymbolAttributes getHighlightAttributes() { return this.highlightAttrs; } - /** {@inheritDoc} */ - public void setHighlightAttributes(TacticalSymbolAttributes highlightAttrs) - { + /** + * {@inheritDoc} + */ + public void setHighlightAttributes(TacticalSymbolAttributes highlightAttrs) { this.highlightAttrs = highlightAttrs; // Null is accepted, and indicates the default highlight attributes. } - /** {@inheritDoc} */ - public Object getDelegateOwner() - { + /** + * {@inheritDoc} + */ + public Object getDelegateOwner() { return this.delegateOwner; } - /** {@inheritDoc} */ - public void setDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + public void setDelegateOwner(Object owner) { this.delegateOwner = owner; } - /** {@inheritDoc} */ - public UnitsFormat getUnitsFormat() - { + /** + * {@inheritDoc} + */ + public UnitsFormat getUnitsFormat() { return this.unitsFormat; } - /** {@inheritDoc} */ - public void setUnitsFormat(UnitsFormat unitsFormat) - { - if (unitsFormat == null) - { + /** + * {@inheritDoc} + */ + public void setUnitsFormat(UnitsFormat unitsFormat) { + if (unitsFormat == null) { String msg = Logging.getMessage("nullValue.Format"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // If the unit format is changing then the position needs to be reformatted. - if (this.unitsFormat != unitsFormat) + if (this.unitsFormat != unitsFormat) { this.formattedPosition = null; + } this.unitsFormat = unitsFormat; } @Override - public LODSelector getLODSelector() - { + public LODSelector getLODSelector() { return LODSelector; } @Override - public void setLODSelector(LODSelector LODSelector) - { + public void setLODSelector(LODSelector LODSelector) { this.LODSelector = LODSelector; } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.getPosition(); } - /** {@inheritDoc} */ - public void move(Position delta) - { - if (delta == null) - { + /** + * {@inheritDoc} + */ + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -934,17 +936,18 @@ public void move(Position delta) // because its position must always be non-null. We check and this case anyway to handle a subclass overriding // getReferencePosition and returning null. In this case moving the shape by a relative delta is meaningless // because the shape has no geographic location. Therefore we fail softly by exiting and doing nothing. - if (refPos == null) + if (refPos == null) { return; + } this.moveTo(refPos.add(delta)); } - /** {@inheritDoc} */ - public void moveTo(Position position) - { - if (position == null) - { + /** + * {@inheritDoc} + */ + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -954,31 +957,29 @@ public void moveTo(Position position) } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, this.getAltitudeMode()); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragScreenSizeConstant(dragContext); } @@ -989,8 +990,7 @@ protected void doDrag(DragContext dragContext) * @return the hot spot controlling the symbol's placement relative to the symbol point. null indicates default * alignment. */ - public Offset getOffset() - { + public Offset getOffset() { return this.offset; } @@ -1001,10 +1001,9 @@ public Offset getOffset() * setOffset(Offset.BOTTOM_CENTER)} aligns the center of the bottom edge with the symbol point. * * @param offset the hot spot controlling the symbol's placement relative to the symbol point. May be null to - * indicate default alignment. + * indicate default alignment. */ - public void setOffset(Offset offset) - { + public void setOffset(Offset offset) { this.offset = offset; } @@ -1014,58 +1013,51 @@ public void setOffset(Offset offset) * @return The current position formatted according to the current unit format. Returns null if the position is * null. */ - protected String getFormattedPosition() - { + protected String getFormattedPosition() { Position position = this.getPosition(); - if (position == null) + if (position == null) { return null; + } // Format the position to a string only when necessary. formattedPosition is set to null when either the // position or the units format is changed. - if (this.formattedPosition == null) + if (this.formattedPosition == null) { this.formattedPosition = this.getUnitsFormat().latLon(position); + } return this.formattedPosition; } - protected Double getDepthOffset() - { + protected Double getDepthOffset() { return this.depthOffset; } - protected void setDepthOffset(Double depthOffset) - { + protected void setDepthOffset(Double depthOffset) { this.depthOffset = depthOffset; // Null is accepted, and indicates the default depth offset is used. } - protected IconRetriever getIconRetriever() - { + protected IconRetriever getIconRetriever() { return this.iconRetriever; } - protected void setIconRetriever(IconRetriever retriever) - { + protected void setIconRetriever(IconRetriever retriever) { this.iconRetriever = retriever; } - protected IconRetriever getModifierRetriever() - { + protected IconRetriever getModifierRetriever() { return this.modifierRetriever; } - protected void setModifierRetriever(IconRetriever retriever) - { + protected void setModifierRetriever(IconRetriever retriever) { this.modifierRetriever = retriever; this.reset(); } - protected TextureAtlas getGlyphAtlas() - { + protected TextureAtlas getGlyphAtlas() { return this.glyphAtlas; } - protected void setGlyphAtlas(TextureAtlas atlas) - { + protected void setGlyphAtlas(TextureAtlas atlas) { // Note that we do not explicitly remove this symbol's glyphs from the old atlas. The modifier texture atlas // should be configured to evict the oldest glyphs when the atlas is full. Leaving this symbol's glyphs in the // atlas does not incur any additional overhead, and has the benefit of ensuring that we do not remove glyphs @@ -1074,76 +1066,75 @@ protected void setGlyphAtlas(TextureAtlas atlas) this.glyphAtlas = atlas; } - public void pick(DrawContext dc, Point pickPoint, OrderedSymbol osym) - { - if (dc == null) - { + public void pick(DrawContext dc, Point pickPoint, OrderedSymbol osym) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.drawOrderedRenderable(dc, osym); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } } - /** {@inheritDoc} */ - public void render(DrawContext dc) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.isVisible()) + if (!this.isVisible()) { return; + } this.makeOrderedRenderable(dc); } - protected void makeOrderedRenderable(DrawContext dc) - { + protected void makeOrderedRenderable(DrawContext dc) { OrderedSymbol osym; // Calculate this symbol's per-frame values, re-using values already calculated this frame. - if (dc.getFrameTimeStamp() != this.frameNumber || dc.isContinuous2DGlobe()) - { + if (dc.getFrameTimeStamp() != this.frameNumber || dc.isContinuous2DGlobe()) { osym = new OrderedSymbol(); // Compute the model and screen coordinate points corresponding to the position and altitude mode. this.computeSymbolPoints(dc, osym); - if (osym.placePoint == null || osym.screenPoint == null) + if (osym.placePoint == null || osym.screenPoint == null) { return; + } // Don't draw if beyond the horizon. double horizon = dc.getView().getHorizonDistance(); - if (!dc.is2DGlobe() && osym.eyeDistance > horizon) + if (!dc.is2DGlobe() && osym.eyeDistance > horizon) { return; + } // If the symbol has never been laid out perform a frustum test using estimated screen bounds. If the symbol // is not visible, then don't compute layout. This avoids downloading icons and laying out symbols that are // not yet visible. - if (osym.screenRect == null && !this.intersectsFrustum(dc, osym)) + if (osym.screenRect == null && !this.intersectsFrustum(dc, osym)) { return; + } - if (this.getLODSelector() != null) + if (this.getLODSelector() != null) { this.getLODSelector().selectLOD(dc, this, osym.eyeDistance); + } // Compute the currently active attributes from either the normal or the highlight attributes. this.determineActiveAttributes(); - if (this.getActiveAttributes() == null) + if (this.getActiveAttributes() == null) { return; + } // Compute the scale for this frame. This must happen before layout because the text layout may depend // on the scale. @@ -1158,78 +1149,69 @@ protected void makeOrderedRenderable(DrawContext dc) this.frameNumber = dc.getFrameTimeStamp(); this.thisFramesOrderedSymbol = osym; - } - else - { + } else { osym = thisFramesOrderedSymbol; } // Determine if the symbol is visible, now that the layout is known. - if (this.intersectsFrustum(dc, osym)) + if (this.intersectsFrustum(dc, osym)) { dc.addOrderedRenderable(osym); + } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { this.pickLayer = dc.getCurrentLayer(); + } } - protected void computeSymbolPoints(DrawContext dc, OrderedSymbol osym) - { + protected void computeSymbolPoints(DrawContext dc, OrderedSymbol osym) { osym.placePoint = null; osym.screenPoint = null; osym.eyeDistance = 0; Position pos = this.getPosition(); - if (pos == null) + if (pos == null) { return; + } - if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) - { + if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe()) { osym.placePoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), 0); - } - else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) { osym.placePoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), pos.getAltitude()); - } - else // Default to ABSOLUTE + } else // Default to ABSOLUTE { double height = pos.getElevation() * dc.getVerticalExaggeration(); osym.placePoint = dc.getGlobe().computePointFromPosition(pos.getLatitude(), pos.getLongitude(), height); } - if (osym.placePoint == null) + if (osym.placePoint == null) { return; + } // Compute the symbol's screen location the distance between the eye point and the place point. osym.screenPoint = dc.getView().project(osym.placePoint); osym.eyeDistance = osym.placePoint.distanceTo3(dc.getView().getEyePoint()); } - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { Font previousFont = this.activeAttrs.getTextModifierFont(); Double previousScale = this.activeAttrs.getScale(); Double previousOpacity = this.activeAttrs.getOpacity(); - if (this.isHighlighted()) - { - if (this.getHighlightAttributes() != null) + if (this.isHighlighted()) { + if (this.getHighlightAttributes() != null) { this.activeAttrs.copy(this.getHighlightAttributes()); - else - { + } else { // If no highlight attributes have been specified we need to use either the normal or default attributes // but adjust them to cause highlighting. - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.activeAttrs.copy(this.getAttributes()); - else + } else { this.activeAttrs.copy(defaultAttrs); + } } - } - else if (this.getAttributes() != null) - { + } else if (this.getAttributes() != null) { this.activeAttrs.copy(this.getAttributes()); - } - else - { + } else { this.activeAttrs.copy(defaultAttrs); } @@ -1237,8 +1219,7 @@ else if (this.getAttributes() != null) // different size. Font newFont = this.activeAttrs.getTextModifierFont(); if (newFont != null && !newFont.equals(previousFont) - || (newFont == null && previousFont != null)) - { + || (newFont == null && previousFont != null)) { this.reset(); } @@ -1246,34 +1227,31 @@ else if (this.getAttributes() != null) // has changed, then recreate the labels. Double newOpacity = this.activeAttrs.getOpacity(); if ((newOpacity != null && !newOpacity.equals(previousOpacity)) - || (newOpacity == null && previousOpacity != null)) - { + || (newOpacity == null && previousOpacity != null)) { this.reset(); } // If the scale has changed then the layout needs to be recomputed. Double newScale = this.activeAttrs.getScale(); if (newScale != null && !newScale.equals(previousScale) - || (newScale == null && previousScale != null)) - { + || (newScale == null && previousScale != null)) { this.reset(); } } - protected TacticalSymbolAttributes getActiveAttributes() - { + protected TacticalSymbolAttributes getActiveAttributes() { return this.activeAttrs; } - /** Invalidate the symbol layout, causing it to be recomputed on the next frame. */ - protected void reset() - { + /** + * Invalidate the symbol layout, causing it to be recomputed on the next frame. + */ + protected void reset() { this.staticScreenRect = null; this.staticLayoutRect = null; } - protected void layout(DrawContext dc, OrderedSymbol osym) - { + protected void layout(DrawContext dc, OrderedSymbol osym) { AVList modifierParams = new AVListImpl(); modifierParams.setValues(this.modifiers); this.applyImplicitModifiers(modifierParams); @@ -1285,19 +1263,20 @@ protected void layout(DrawContext dc, OrderedSymbol osym) IconSource iconSource = new IconSource(this.getIconRetriever(), this.getIdentifier(), retrieverParams); // Compute layout of icon and static modifiers only when necessary. - if (this.mustLayout(iconSource, modifierParams) || dc.isContinuous2DGlobe()) - { + if (this.mustLayout(iconSource, modifierParams) || dc.isContinuous2DGlobe()) { osym.screenRect = null; osym.layoutRect = null; // Set the unresolved flag false. addGlyph will set it to true if there are still unresolved resources. this.unresolvedGlyph = false; - if (this.mustDrawIcon(dc)) + if (this.mustDrawIcon(dc)) { this.layoutIcon(dc, iconSource, osym); + } - if (mustDrawModifiers) + if (mustDrawModifiers) { this.layoutStaticModifiers(dc, modifierParams, osym); + } // Save the static layout to reuse on subsequent frames. this.staticScreenRect = new Rectangle(osym.screenRect); @@ -1307,65 +1286,67 @@ protected void layout(DrawContext dc, OrderedSymbol osym) this.activeModifiers.setValues(modifierParams); this.removeDeadModifiers(System.currentTimeMillis()); - } - else - { + } else { // Reuse cached layout. osym.layoutRect = new Rectangle(this.staticLayoutRect); osym.screenRect = new Rectangle(this.staticScreenRect); } // Layout dynamic modifiers each frame because they are expected to change each frame. - if (mustDrawModifiers) + if (mustDrawModifiers) { this.layoutDynamicModifiers(dc, modifierParams, osym); + } } /** * Determines if the icon layout or static modifier layout must be computed. * * @param iconSource Current icon source. - * @param modifiers Current modifiers. + * @param modifiers Current modifiers. * * @return true if the layout must be recomputed. */ - protected boolean mustLayout(IconSource iconSource, AVList modifiers) - { + protected boolean mustLayout(IconSource iconSource, AVList modifiers) { // If one or more glyphs need to be resolved, then layout is not complete. - if (this.unresolvedGlyph) + if (this.unresolvedGlyph) { return true; + } // If there is no cached layout, then we need to layout. - if (this.staticScreenRect == null || this.staticLayoutRect == null) + if (this.staticScreenRect == null || this.staticLayoutRect == null) { return true; + } // If the modifiers have changed since layout was computed then it needs to be recomputed. - if (!this.activeModifiers.getEntries().equals(modifiers.getEntries())) + if (!this.activeModifiers.getEntries().equals(modifiers.getEntries())) { return true; + } // Layout may change if the icon is not update to date. - if (this.iconTexture == null || this.iconTexture != this.activeIconTexture) + if (this.iconTexture == null || this.iconTexture != this.activeIconTexture) { return true; + } // If the icon retrieval parameters have changed then the icon needs to be updated, which may affect layout. return !this.iconTexture.getImageSource().equals(iconSource); } - protected void layoutIcon(DrawContext dc, IconSource source, OrderedSymbol osym) - { - if (this.getIconRetriever() == null) + protected void layoutIcon(DrawContext dc, IconSource source, OrderedSymbol osym) { + if (this.getIconRetriever() == null) { return; + } // Lazily create the symbol icon texture when either the IconRetriever, the symbol ID, or the retriever // parameters change. - if (this.iconTexture == null || !this.iconTexture.getImageSource().equals(source)) + if (this.iconTexture == null || !this.iconTexture.getImageSource().equals(source)) { this.iconTexture = new IconTexture(source); + } // Use the currently active icon texture until the new icon texture (if any) has successfully loaded. This // ensures that the old icon texture continues to display until the new icon texture is ready, and avoids // temporarily displaying nothing. if (this.activeIconTexture != this.iconTexture && this.iconTexture != null - && this.iconTexture.bind(dc)) - { + && this.iconTexture.bind(dc)) { this.activeIconTexture = this.iconTexture; this.iconRect = null; // Recompute the icon rectangle when the active icon texture changes. } @@ -1374,50 +1355,50 @@ protected void layoutIcon(DrawContext dc, IconSource source, OrderedSymbol osym) // the icon is changed after loading then we will continue to draw the old icon until the new one becomes // available rather than going back to the default icon. boolean textureLoaded = this.activeIconTexture != null; - if (!textureLoaded) - { + if (!textureLoaded) { this.activeIconTexture = new BasicWWTexture(LOADING_IMAGE_PATH); textureLoaded = this.activeIconTexture.bind(dc); } // Lazily compute the symbol icon rectangle only when necessary, and only after the symbol icon texture has // successfully loaded. - if (this.iconRect == null && textureLoaded) - { + if (this.iconRect == null && textureLoaded) { // Compute the symbol icon's frame rectangle in local coordinates. This is used by the modifier layout to // determine where to place modifier graphics and modifier text. Note that we bind the texture in order to // load the texture image, and make the width and height available. int w = this.activeIconTexture.getWidth(dc); int h = this.activeIconTexture.getHeight(dc); Point2D point = this.iconOffset != null ? this.iconOffset.computeOffset(w, h, null, null) - : new Point(0, 0); + : new Point(0, 0); Dimension size = this.iconSize != null ? this.iconSize.compute(w, h, w, h) : new Dimension(w, h); this.iconRect = new Rectangle((int) point.getX(), (int) point.getY(), size.width, size.height); } // Add the symbol icon rectangle to the screen rectangle and layout rectangle every frame. - if (this.iconRect != null) - { - if (osym.screenRect != null) + if (this.iconRect != null) { + if (osym.screenRect != null) { osym.screenRect.add(this.iconRect); - else + } else { osym.screenRect = new Rectangle(this.iconRect); + } - if (osym.layoutRect != null) + if (osym.layoutRect != null) { osym.layoutRect.add(this.iconRect); - else + } else { osym.layoutRect = new Rectangle(this.iconRect); + } } } - protected AVList assembleIconRetrieverParameters(AVList params) - { - if (params == null) + protected AVList assembleIconRetrieverParameters(AVList params) { + if (params == null) { params = new AVListImpl(); + } Material interiorMaterial = this.getActiveAttributes().getInteriorMaterial(); - if (interiorMaterial != null) + if (interiorMaterial != null) { params.setValue(AVKey.COLOR, interiorMaterial.getDiffuse()); + } return params; } @@ -1430,9 +1411,9 @@ protected AVList assembleIconRetrieverParameters(AVList params) * #layoutTextModifiers(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.avlist.AVList, * gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol) layoutTextModifiers}. * - * @param dc Current draw context. + * @param dc Current draw context. * @param modifiers Current modifiers. - * @param osym The OrderedSymbol to hold the per-frame data. + * @param osym The OrderedSymbol to hold the per-frame data. * * @see #layoutDynamicModifiers(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.avlist.AVList, * gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol) @@ -1441,20 +1422,22 @@ protected AVList assembleIconRetrieverParameters(AVList params) * @see #layoutTextModifiers(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.avlist.AVList, * gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol) */ - protected void layoutStaticModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { - if (this.iconRect == null) + protected void layoutStaticModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { + if (this.iconRect == null) { return; + } - if (this.mustDrawGraphicModifiers(dc)) + if (this.mustDrawGraphicModifiers(dc)) { this.layoutGraphicModifiers(dc, modifiers, osym); + } // Compute the bounds of the symbol and graphic modifiers with scaling applied. The text will be laid out // based on this size (text is not scaled with the symbol). this.computeScaledBounds(dc, modifiers, osym); - if (this.mustDrawTextModifiers(dc)) + if (this.mustDrawTextModifiers(dc)) { this.layoutTextModifiers(dc, modifiers, osym); + } } /** @@ -1464,15 +1447,14 @@ protected void layoutStaticModifiers(DrawContext dc, AVList modifiers, OrderedSy * is best treated as a static modifier. However a direction of movement line that needs to be computed based on the * current eye position should be treated as a dynamic modifier. * - * @param dc Current draw context. + * @param dc Current draw context. * @param modifiers Current modifiers. - * @param osym The OrderedSymbol to hold the per-frame data. + * @param osym The OrderedSymbol to hold the per-frame data. * * @see #layoutDynamicModifiers(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.avlist.AVList, * gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol) */ - protected void layoutGraphicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutGraphicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { // Intentionally left blank. Subclasses can override this method in order to layout any modifiers associated // with this tactical symbol. } @@ -1484,15 +1466,14 @@ protected void layoutGraphicModifiers(DrawContext dc, AVList modifiers, OrderedS * is best treated as a static modifier. However a direction of movement line that needs to be computed based on the * current eye position should be treated as a dynamic modifier. * - * @param dc Current draw context. + * @param dc Current draw context. * @param modifiers Current modifiers. - * @param osym The OrderedSymbol to hold the per-frame data. + * @param osym The OrderedSymbol to hold the per-frame data. * * @see #layoutDynamicModifiers(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.avlist.AVList, * gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol) */ - protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { // Intentionally left blank. Subclasses can override this method in order to layout any modifiers associated // with this tactical symbol. } @@ -1502,15 +1483,14 @@ protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymb * and are laid out each frame. For example, a direction of movement line that is computed based on the current eye * position would be treated as a dynamic modifier. Dynamic modifiers are always laid out after static modifiers. * - * @param dc Current draw context. + * @param dc Current draw context. * @param modifiers Current modifiers. - * @param osym The OrderedSymbol to hold the per-frame data. + * @param osym The OrderedSymbol to hold the per-frame data. * * @see #layoutStaticModifiers(gov.nasa.worldwind.render.DrawContext, gov.nasa.worldwind.avlist.AVList, * gov.nasa.worldwind.symbology.AbstractTacticalSymbol.OrderedSymbol) */ - protected void layoutDynamicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutDynamicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { // Intentionally left blank. Subclasses can override this method in order to layout any modifiers associated // with this tactical symbol. } @@ -1522,8 +1502,7 @@ protected void layoutDynamicModifiers(DrawContext dc, AVList modifiers, OrderedS * * @param modifiers List of modifiers. This method may modify this list by adding implicit modifiers. */ - protected void applyImplicitModifiers(AVList modifiers) - { + protected void applyImplicitModifiers(AVList modifiers) { // Intentionally left blank. Subclasses can override this method in order to add modifiers that are implicitly // determined by the symbol state. } @@ -1531,37 +1510,36 @@ protected void applyImplicitModifiers(AVList modifiers) /** * Layout a rectangle relative to the current layout. * - * @param offset Offset into either the {@code iconRect} or {@code layoutRect} at which to align the hot spot. - * @param hotspot Offset into the rectangle of the hot spot. - * @param size Size of the rectangle. + * @param offset Offset into either the {@code iconRect} or {@code layoutRect} at which to align the hot spot. + * @param hotspot Offset into the rectangle of the hot spot. + * @param size Size of the rectangle. * @param layoutMode One of {@link #LAYOUT_ABSOLUTE}, {@link #LAYOUT_RELATIVE}, or {@link #LAYOUT_NONE}. - * @param osym The OrderedSymbol to hold the per-frame data. + * @param osym The OrderedSymbol to hold the per-frame data. * * @return the laid out rectangle. */ protected Rectangle layoutRect(Offset offset, Offset hotspot, Dimension size, Object layoutMode, - OrderedSymbol osym) - { + OrderedSymbol osym) { int x = 0; int y = 0; - if (offset != null) - { + if (offset != null) { Rectangle rect; - if (LAYOUT_ABSOLUTE.equals(layoutMode)) + if (LAYOUT_ABSOLUTE.equals(layoutMode)) { rect = this.iconRect; - else if (LAYOUT_RELATIVE.equals(layoutMode)) + } else if (LAYOUT_RELATIVE.equals(layoutMode)) { rect = osym.layoutRect; - else // LAYOUT_NONE + } else // LAYOUT_NONE + { rect = this.iconRect; + } Point2D p = offset.computeOffset(rect.getWidth(), rect.getHeight(), null, null); x += rect.getX() + p.getX(); y += rect.getY() + p.getY(); } - if (hotspot != null) - { + if (hotspot != null) { Point2D p = hotspot.computeOffset(size.getWidth(), size.getHeight(), null, null); x -= p.getX(); y -= p.getY(); @@ -1569,17 +1547,18 @@ else if (LAYOUT_RELATIVE.equals(layoutMode)) Rectangle rect = new Rectangle(x, y, size.width, size.height); - if (osym.screenRect != null) + if (osym.screenRect != null) { osym.screenRect.add(rect); - else + } else { osym.screenRect = new Rectangle(rect); + } - if (LAYOUT_ABSOLUTE.equals(layoutMode) || LAYOUT_RELATIVE.equals(layoutMode)) - { - if (osym.layoutRect != null) + if (LAYOUT_ABSOLUTE.equals(layoutMode) || LAYOUT_RELATIVE.equals(layoutMode)) { + if (osym.layoutRect != null) { osym.layoutRect.add(rect); - else + } else { osym.layoutRect = new Rectangle(rect); + } } return rect; @@ -1589,37 +1568,36 @@ else if (LAYOUT_RELATIVE.equals(layoutMode)) * Layout a label rectangle relative to the current layout. This method lays out text around the icon and graphic * modifiers after scaling has been applied (text is not scaled with the icon). * - * @param offset Offset into either the {@code iconRect} or {@code layoutRect} at which to align the hot spot. - * @param hotspot Offset into the rectangle of the hot spot. - * @param size Size of the rectangle. + * @param offset Offset into either the {@code iconRect} or {@code layoutRect} at which to align the hot spot. + * @param hotspot Offset into the rectangle of the hot spot. + * @param size Size of the rectangle. * @param layoutMode One of {@link #LAYOUT_ABSOLUTE}, {@link #LAYOUT_RELATIVE}, or {@link #LAYOUT_NONE}. - * @param osym The OrderedSymbol to hold the per-frame data. + * @param osym The OrderedSymbol to hold the per-frame data. * * @return the laid out rectangle. */ protected Rectangle layoutLabelRect(Offset offset, Offset hotspot, Dimension size, Object layoutMode, - OrderedSymbol osym) - { + OrderedSymbol osym) { int x = 0; int y = 0; - if (offset != null) - { + if (offset != null) { Rectangle rect; - if (LAYOUT_ABSOLUTE.equals(layoutMode)) + if (LAYOUT_ABSOLUTE.equals(layoutMode)) { rect = osym.iconRectScaled; - else if (LAYOUT_RELATIVE.equals(layoutMode)) + } else if (LAYOUT_RELATIVE.equals(layoutMode)) { rect = osym.layoutRectScaled; - else // LAYOUT_NONE + } else // LAYOUT_NONE + { rect = osym.iconRectScaled; + } Point2D p = offset.computeOffset(rect.getWidth(), rect.getHeight(), null, null); x += rect.getX() + p.getX(); y += rect.getY() + p.getY(); } - if (hotspot != null) - { + if (hotspot != null) { Point2D p = hotspot.computeOffset(size.getWidth(), size.getHeight(), null, null); x -= p.getX(); y -= p.getY(); @@ -1627,121 +1605,114 @@ else if (LAYOUT_RELATIVE.equals(layoutMode)) Rectangle rect = new Rectangle(x, y, size.width, size.height); - if (LAYOUT_ABSOLUTE.equals(layoutMode) || LAYOUT_RELATIVE.equals(layoutMode)) - { - if (osym.layoutRectScaled != null) - { + if (LAYOUT_ABSOLUTE.equals(layoutMode) || LAYOUT_RELATIVE.equals(layoutMode)) { + if (osym.layoutRectScaled != null) { osym.layoutRectScaled.add(rect); - } - else + } else { osym.layoutRectScaled = new Rectangle(rect); + } // Compute where the label rectangle falls in the icon layout before scaling is applied. This is necessary // to layout graphic modifiers such as the ground direction of movement indicator that are scaled down with // the icon, but should not overlap text which is not scaled with the icon. Rectangle scaledRect = this.computeScaledRect(rect, rect.getSize(), 1 / osym.sx, 1 / osym.sy); - if (osym.layoutRect != null) + if (osym.layoutRect != null) { osym.layoutRect.add(scaledRect); - else + } else { osym.layoutRect = new Rectangle(scaledRect); + } } return rect; } protected List layoutPoints(Offset offset, List points, Object layoutMode, - int numPointsInLayout, OrderedSymbol osym) - { + int numPointsInLayout, OrderedSymbol osym) { int x = 0; int y = 0; - if (offset != null) - { + if (offset != null) { Rectangle rect; - if (LAYOUT_ABSOLUTE.equals(layoutMode)) + if (LAYOUT_ABSOLUTE.equals(layoutMode)) { rect = this.iconRect; - else if (LAYOUT_RELATIVE.equals(layoutMode)) + } else if (LAYOUT_RELATIVE.equals(layoutMode)) { rect = osym.layoutRect; - else // LAYOUT_NONE + } else // LAYOUT_NONE + { rect = this.iconRect; + } Point2D p = offset.computeOffset(rect.getWidth(), rect.getHeight(), null, null); x += rect.getX() + p.getX(); y += rect.getY() + p.getY(); } - for (int i = 0; i < points.size(); i++) - { + for (int i = 0; i < points.size(); i++) { Point2D p = points.get(i); p.setLocation(x + p.getX(), y + p.getY()); - if (osym.screenRect != null) + if (osym.screenRect != null) { osym.screenRect.add(p); - else + } else { osym.screenRect = new Rectangle((int) p.getX(), (int) p.getY(), 0, 0); + } - if (i < numPointsInLayout && (LAYOUT_ABSOLUTE.equals(layoutMode) || LAYOUT_RELATIVE.equals(layoutMode))) - { - if (osym.layoutRect != null) + if (i < numPointsInLayout && (LAYOUT_ABSOLUTE.equals(layoutMode) || LAYOUT_RELATIVE.equals(layoutMode))) { + if (osym.layoutRect != null) { osym.layoutRect.add(p); - else + } else { osym.layoutRect = new Rectangle((int) p.getX(), (int) p.getY(), 0, 0); + } } } return points; } - protected void addGlyph(DrawContext dc, Offset offset, Offset hotspot, String modifierCode, OrderedSymbol osym) - { + protected void addGlyph(DrawContext dc, Offset offset, Offset hotspot, String modifierCode, OrderedSymbol osym) { this.addGlyph(dc, offset, hotspot, modifierCode, null, null, osym); } protected void addGlyph(DrawContext dc, Offset offset, Offset hotspot, String modifierCode, - AVList retrieverParams, Object layoutMode, OrderedSymbol osym) - { + AVList retrieverParams, Object layoutMode, OrderedSymbol osym) { IconAtlasElement elem = this.getGlyph(modifierCode, retrieverParams); - if (elem.load(dc)) - { + if (elem.load(dc)) { Rectangle rect = this.layoutRect(offset, hotspot, elem.getSize(), layoutMode, osym); elem.setPoint(rect.getLocation()); this.currentGlyphs.add(elem); - } - else - { + } else { this.unresolvedGlyph = true; } } protected void addLabel(DrawContext dc, Offset offset, Offset hotspot, String modifierText, - OrderedSymbol osym) - { + OrderedSymbol osym) { this.addLabel(dc, offset, hotspot, modifierText, null, null, null, osym); } protected void addLabel(DrawContext dc, Offset offset, Offset hotspot, String modifierText, Font font, - Color color, Object layoutMode, OrderedSymbol osym) - { - if (font == null) - { + Color color, Object layoutMode, OrderedSymbol osym) { + if (font == null) { // Use either the currently specified text modifier font or compute a default if no font is specified. font = this.getActiveAttributes().getTextModifierFont(); - if (font == null) + if (font == null) { font = BasicTacticalSymbolAttributes.DEFAULT_TEXT_MODIFIER_FONT; + } } - if (color == null) - { + if (color == null) { // Use either the currently specified text modifier material or the default if no material is specified. Material material = this.getActiveAttributes().getTextModifierMaterial(); - if (material == null) + if (material == null) { material = BasicTacticalSymbolAttributes.DEFAULT_TEXT_MODIFIER_MATERIAL; + } // Use either the currently specified opacity or the default if no opacity is specified. Double opacity = this.getActiveAttributes().getOpacity(); - if (opacity == null) + if (opacity == null) { opacity = BasicTacticalSymbolAttributes.DEFAULT_OPACITY; + } int alpha = (int) (255 * opacity + 0.5); Color diffuse = material.getDiffuse(); @@ -1759,28 +1730,25 @@ protected void addLabel(DrawContext dc, Offset offset, Offset hotspot, String mo this.currentLabels.add(new Label(modifierText, point, font, color)); } - protected void addLine(DrawContext dc, Offset offset, List points, OrderedSymbol osym) - { + protected void addLine(DrawContext dc, Offset offset, List points, OrderedSymbol osym) { this.addLine(dc, offset, points, null, 0, osym); } @SuppressWarnings({"UnusedParameters"}) protected void addLine(DrawContext dc, Offset offset, List points, Object layoutMode, - int numPointsInLayout, OrderedSymbol osym) - { + int numPointsInLayout, OrderedSymbol osym) { points = this.layoutPoints(offset, points, layoutMode, numPointsInLayout, osym); this.currentLines.add(new Line(points)); } - protected IconAtlasElement getGlyph(String modifierCode, AVList retrieverParams) - { - if (this.getGlyphAtlas() == null || this.getModifierRetriever() == null) + protected IconAtlasElement getGlyph(String modifierCode, AVList retrieverParams) { + if (this.getGlyphAtlas() == null || this.getModifierRetriever() == null) { return null; + } IconAtlasElement elem = this.glyphMap.get(modifierCode); - if (elem == null) - { + if (elem == null) { IconSource source = new IconSource(this.getModifierRetriever(), modifierCode, retrieverParams); elem = new IconAtlasElement(this.getGlyphAtlas(), source); this.glyphMap.put(modifierCode, elem); @@ -1791,57 +1759,48 @@ protected IconAtlasElement getGlyph(String modifierCode, AVList retrieverParams) return elem; } - protected void removeDeadModifiers(long now) - { - if (this.glyphMap.isEmpty()) + protected void removeDeadModifiers(long now) { + if (this.glyphMap.isEmpty()) { return; + } List deadKeys = null; // Lazily created below to avoid unnecessary allocation. - for (Map.Entry entry : this.glyphMap.entrySet()) - { - if (entry.getValue().lastUsed + this.maxTimeSinceLastUsed < now) - { - if (deadKeys == null) + for (Map.Entry entry : this.glyphMap.entrySet()) { + if (entry.getValue().lastUsed + this.maxTimeSinceLastUsed < now) { + if (deadKeys == null) { deadKeys = new ArrayList(); + } deadKeys.add(entry.getKey()); } } - if (deadKeys == null) + if (deadKeys == null) { return; + } - for (String key : deadKeys) - { + for (String key : deadKeys) { this.glyphMap.remove(key); } } - protected void computeScale(OrderedSymbol osym) - { - if (this.getActiveAttributes().getScale() != null) - { + protected void computeScale(OrderedSymbol osym) { + if (this.getActiveAttributes().getScale() != null) { osym.sx = this.getActiveAttributes().getScale(); osym.sy = this.getActiveAttributes().getScale(); - } - else - { + } else { osym.sx = BasicTacticalSymbolAttributes.DEFAULT_SCALE; osym.sy = BasicTacticalSymbolAttributes.DEFAULT_SCALE; } } - protected void computeTransform(DrawContext dc, OrderedSymbol osym) - { - if (this.getOffset() != null && this.iconRect != null) - { + protected void computeTransform(DrawContext dc, OrderedSymbol osym) { + if (this.getOffset() != null && this.iconRect != null) { Point2D p = this.getOffset().computeOffset(this.iconRect.getWidth(), this.iconRect.getHeight(), null, - null); + null); osym.dx = -this.iconRect.getX() - p.getX(); osym.dy = -this.iconRect.getY() - p.getY(); - } - else - { + } else { osym.dx = 0; osym.dy = 0; } @@ -1850,19 +1809,18 @@ protected void computeTransform(DrawContext dc, OrderedSymbol osym) /** * Compute the bounds of symbol after the scale has been applied. * - * @param dc Current draw context. + * @param dc Current draw context. * @param modifiers Current modifiers. - * @param osym The OrderedSymbol to hold the per-frame data. + * @param osym The OrderedSymbol to hold the per-frame data. */ - protected void computeScaledBounds(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void computeScaledBounds(DrawContext dc, AVList modifiers, OrderedSymbol osym) { Dimension maxDimension = this.computeMinTextLayout(dc, modifiers); osym.iconRectScaled = this.computeScaledRect(this.iconRect, maxDimension, osym.sx, osym.sy); osym.layoutRectScaled = this.computeScaledRect(osym.layoutRect, maxDimension, osym.sx, osym.sy); } /** - * Compute the dimension of the minimum layout rectangle for the text modifiers.A minimum dimension is enforced to + * Compute the dimension of the minimum layout rectangle for the text modifiers.A minimum dimension is enforced to * prevent the text from overlapping if the symbol is scaled to a very small size. * * @param dc Current draw context. @@ -1870,12 +1828,12 @@ protected void computeScaledBounds(DrawContext dc, AVList modifiers, OrderedSymb * * @return Minimum dimension for the label layout rectangle. */ - protected Dimension computeMinTextLayout(DrawContext dc, AVList modifiers) - { + protected Dimension computeMinTextLayout(DrawContext dc, AVList modifiers) { // Use either the currently specified text modifier font or compute a default if no font is specified. Font font = this.getActiveAttributes().getTextModifierFont(); - if (font == null) + if (font == null) { font = BasicTacticalSymbolAttributes.DEFAULT_TEXT_MODIFIER_FONT; + } TextRenderer tr = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); @@ -1890,13 +1848,11 @@ protected Dimension computeMinTextLayout(DrawContext dc, AVList modifiers) } @SuppressWarnings({"UnusedParameters"}) - protected int getMaxLabelLines(AVList modifiers) - { + protected int getMaxLabelLines(AVList modifiers) { return DEFAULT_LABEL_LINES; } - protected Rectangle computeScaledRect(Rectangle rect, Dimension maxDimension, double scaleX, double scaleY) - { + protected Rectangle computeScaledRect(Rectangle rect, Dimension maxDimension, double scaleX, double scaleY) { double x = rect.getX() * scaleX; double y = rect.getY() * scaleY; double width = rect.getWidth() * scaleX; @@ -1905,13 +1861,11 @@ protected Rectangle computeScaledRect(Rectangle rect, Dimension maxDimension, do double maxWidth = maxDimension.getWidth(); double maxHeight = maxDimension.getHeight(); - if (width < maxWidth) - { + if (width < maxWidth) { x = x + (width - maxWidth) / 2.0; width = maxWidth; } - if (height < maxHeight) - { + if (height < maxHeight) { y = y + (height - maxHeight) / 2.0; height = maxHeight; } @@ -1919,22 +1873,18 @@ protected Rectangle computeScaledRect(Rectangle rect, Dimension maxDimension, do return new Rectangle((int) x, (int) y, (int) Math.ceil(width), (int) Math.ceil(height)); } - protected Rectangle computeScreenExtent(OrderedSymbol osym) - { + protected Rectangle computeScreenExtent(OrderedSymbol osym) { double width; double height; double x; double y; - if (osym.screenRect != null) - { + if (osym.screenRect != null) { x = osym.screenPoint.x + osym.sx * (osym.dx + osym.screenRect.getX()); y = osym.screenPoint.y + osym.sy * (osym.dy + osym.screenRect.getY()); width = osym.sx * osym.screenRect.getWidth(); height = osym.sy * osym.screenRect.getHeight(); - } - else - { + } else { width = MAX_SYMBOL_DIMENSION; height = MAX_SYMBOL_DIMENSION; x = osym.screenPoint.x - width / 2.0; @@ -1951,80 +1901,72 @@ protected Rectangle computeScreenExtent(OrderedSymbol osym) * * @return Maximum size of a symbol, in pixels. */ - protected int getMaxSymbolDimension() - { + protected int getMaxSymbolDimension() { return MAX_SYMBOL_DIMENSION; } - protected boolean intersectsFrustum(DrawContext dc, OrderedSymbol osym) - { + protected boolean intersectsFrustum(DrawContext dc, OrderedSymbol osym) { View view = dc.getView(); // Test the symbol's model coordinate point against the near and far clipping planes. if (osym.placePoint != null - && (view.getFrustumInModelCoordinates().getNear().distanceTo(osym.placePoint) < 0 - || view.getFrustumInModelCoordinates().getFar().distanceTo(osym.placePoint) < 0)) - { + && (view.getFrustumInModelCoordinates().getNear().distanceTo(osym.placePoint) < 0 + || view.getFrustumInModelCoordinates().getFar().distanceTo(osym.placePoint) < 0)) { return false; } Rectangle screenExtent = this.computeScreenExtent(osym); - if (screenExtent != null) - { - if (dc.isPickingMode()) + if (screenExtent != null) { + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(screenExtent); - else + } else { return view.getViewport().intersects(screenExtent); + } } return true; } - protected void drawOrderedRenderable(DrawContext dc, OrderedSymbol osym) - { + protected void drawOrderedRenderable(DrawContext dc, OrderedSymbol osym) { this.beginDrawing(dc, 0); - try - { + try { this.doDrawOrderedRenderable(dc, this.pickSupport, osym); - if (this.isEnableBatchRendering()) + if (this.isEnableBatchRendering()) { this.drawBatched(dc, osym); - } - finally - { + } + } finally { this.endDrawing(dc); } } - protected void drawBatched(DrawContext dc, OrderedSymbol firstSymbol) - { + protected void drawBatched(DrawContext dc, OrderedSymbol firstSymbol) { // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - if (!dc.isPickingMode()) - { - while (nextItem != null && nextItem instanceof OrderedSymbol) - { + if (!dc.isPickingMode()) { + while (nextItem != null && nextItem instanceof OrderedSymbol) { OrderedSymbol ts = (OrderedSymbol) nextItem; - if (!ts.isEnableBatchRendering()) + if (!ts.isEnableBatchRendering()) { break; + } dc.pollOrderedRenderables(); // take it off the queue ts.doDrawOrderedRenderable(dc, this.pickSupport); nextItem = dc.peekOrderedRenderables(); } - } - else if (this.isEnableBatchPicking()) - { - while (nextItem != null && nextItem instanceof OrderedSymbol) - { + } else if (this.isEnableBatchPicking()) { + while (nextItem != null && nextItem instanceof OrderedSymbol) { OrderedSymbol ts = (OrderedSymbol) nextItem; - if (!ts.isEnableBatchRendering() || !ts.isEnableBatchPicking()) + if (!ts.isEnableBatchRendering() || !ts.isEnableBatchPicking()) { break; + } if (ts.getPickLayer() != firstSymbol.getPickLayer()) // batch pick only within a single layer + { break; + } dc.pollOrderedRenderables(); // take it off the queue ts.doDrawOrderedRenderable(dc, this.pickSupport); @@ -2034,14 +1976,13 @@ else if (this.isEnableBatchPicking()) } } - protected void beginDrawing(DrawContext dc, int attrMask) - { + protected void beginDrawing(DrawContext dc, int attrMask) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. attrMask |= GL2.GL_DEPTH_BUFFER_BIT // for depth test enable, depth func, depth mask - | GL2.GL_COLOR_BUFFER_BIT // for alpha test enable, alpha func, blend enable, blend func - | GL2.GL_CURRENT_BIT // for current color - | GL2.GL_LINE_BIT; // for line smooth enable and line width + | GL2.GL_COLOR_BUFFER_BIT // for alpha test enable, alpha func, blend enable, blend func + | GL2.GL_CURRENT_BIT // for current color + | GL2.GL_LINE_BIT; // for line smooth enable and line width Rectangle viewport = dc.getView().getViewport(); @@ -2062,8 +2003,9 @@ protected void beginDrawing(DrawContext dc, int attrMask) gl.glAlphaFunc(GL2.GL_GREATER, 0f); // Apply the depth buffer but don't change it (for screen-space symbols). - if (!dc.isDeepPickingEnabled()) + if (!dc.isDeepPickingEnabled()) { gl.glEnable(GL.GL_DEPTH_TEST); + } gl.glDepthFunc(GL.GL_LESS); gl.glDepthMask(false); @@ -2076,8 +2018,7 @@ protected void beginDrawing(DrawContext dc, int attrMask) // quads representing symbol icons and modifiers. gl.glEnable(GL.GL_TEXTURE_2D); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { // Set up to replace the non-transparent texture colors with the single pick color. gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_COMBINE); gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, GL2.GL_PREVIOUS); @@ -2085,9 +2026,7 @@ protected void beginDrawing(DrawContext dc, int attrMask) // Give symbol modifier lines a thicker width during picking in order to make them easier to select. gl.glLineWidth(9f); - } - else - { + } else { // Enable blending for RGB colors which have been premultiplied by their alpha component. We use this mode // because the icon texture and modifier textures RGB color components have been premultiplied by their color // component. @@ -2101,8 +2040,7 @@ protected void beginDrawing(DrawContext dc, int attrMask) } } - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Restore the default OpenGL vertex array state. @@ -2117,8 +2055,7 @@ protected void endDrawing(DrawContext dc) gl.glDisable(GL.GL_TEXTURE_2D); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, OGLUtil.DEFAULT_TEX_ENV_MODE); gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_SRC0_RGB, OGLUtil.DEFAULT_SRC0_RGB); gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_COMBINE_RGB, OGLUtil.DEFAULT_COMBINE_RGB); @@ -2127,50 +2064,44 @@ protected void endDrawing(DrawContext dc) this.BEogsh.pop(gl); } - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates, OrderedSymbol osym) - { + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickCandidates, OrderedSymbol osym) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { Color pickColor = dc.getUniquePickColor(); pickCandidates.addPickableObject(this.createPickedObject(pickColor.getRGB())); gl.glColor3ub((byte) pickColor.getRed(), (byte) pickColor.getGreen(), (byte) pickColor.getBlue()); - } - else - { + } else { // Set the current color to white with the symbol's current opacity. This applies the symbol's opacity to // its icon texture and graphic modifier textures by multiplying texture fragment colors by the opacity. We // pre-multiply the white RGB color components by the alpha since the texture's RGB color components have // also been pre-multiplied by their color component. float a = this.getActiveAttributes().getOpacity() != null - ? this.getActiveAttributes().getOpacity().floatValue() - : (float) BasicTacticalSymbolAttributes.DEFAULT_OPACITY; + ? this.getActiveAttributes().getOpacity().floatValue() + : (float) BasicTacticalSymbolAttributes.DEFAULT_OPACITY; gl.glColor4f(a, a, a, a); } Double depthOffsetUnits = this.getDepthOffset(); - try - { + try { // Apply any custom depth offset specified by the caller. This overrides the default depth offset specified // in beginRendering, and is therefore restored in the finally block below. - if (depthOffsetUnits != null) + if (depthOffsetUnits != null) { gl.glPolygonOffset(0f, depthOffsetUnits.floatValue()); + } this.prepareToDraw(dc, osym); this.draw(dc, osym); - } - finally - { + } finally { // If the caller specified a custom depth offset, we restore the default depth offset to the value specified // in beginRendering. - if (depthOffsetUnits != null) + if (depthOffsetUnits != null) { gl.glPolygonOffset(0f, (float) DEFAULT_DEPTH_OFFSET); + } } } - protected void prepareToDraw(DrawContext dc, OrderedSymbol osym) - { + protected void prepareToDraw(DrawContext dc, OrderedSymbol osym) { // Apply the symbol's offset in screen coordinates. We translate the X and Y coordinates so that the // symbol's hot spot (identified by its offset) is aligned with its screen point. We translate the Z // coordinate so that the symbol's depth values are appropriately computed by OpenGL according to its @@ -2181,148 +2112,131 @@ protected void prepareToDraw(DrawContext dc, OrderedSymbol osym) gl.glTranslated(osym.screenPoint.x, osym.screenPoint.y, osym.screenPoint.z); } - protected void draw(DrawContext dc, OrderedSymbol osym) - { + protected void draw(DrawContext dc, OrderedSymbol osym) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { gl.glPushMatrix(); gl.glScaled(osym.sx, osym.sy, 1d); gl.glTranslated(osym.dx, osym.dy, 0d); - if (this.mustDrawIcon(dc)) + if (this.mustDrawIcon(dc)) { this.drawIcon(dc); + } - if (this.mustDrawGraphicModifiers(dc)) + if (this.mustDrawGraphicModifiers(dc)) { this.drawGraphicModifiers(dc, osym); - } - finally - { + } + } finally { gl.glPopMatrix(); } - if (this.mustDrawTextModifiers(dc) && !dc.isPickingMode()) - { - try - { + if (this.mustDrawTextModifiers(dc) && !dc.isPickingMode()) { + try { // Do not apply scale to text modifiers. The size of the text is determined by the font. Do apply scale // to dx and dy to put the text in the right place. gl.glPushMatrix(); gl.glTranslated(osym.dx * osym.sx, osym.dy * osym.sy, 0d); this.drawTextModifiers(dc); - } - finally - { + } finally { gl.glPopMatrix(); } } } @SuppressWarnings({"UnusedParameters"}) - protected boolean mustDrawIcon(DrawContext dc) - { + protected boolean mustDrawIcon(DrawContext dc) { return true; } @SuppressWarnings({"UnusedParameters"}) - protected boolean mustDrawGraphicModifiers(DrawContext dc) - { + protected boolean mustDrawGraphicModifiers(DrawContext dc) { return this.isShowGraphicModifiers(); } @SuppressWarnings({"UnusedParameters"}) - protected boolean mustDrawTextModifiers(DrawContext dc) - { + protected boolean mustDrawTextModifiers(DrawContext dc) { return this.isShowTextModifiers(); } - protected void drawIcon(DrawContext dc) - { - if (this.activeIconTexture == null || this.iconRect == null) + protected void drawIcon(DrawContext dc) { + if (this.activeIconTexture == null || this.iconRect == null) { return; + } - if (!this.activeIconTexture.bind(dc)) + if (!this.activeIconTexture.bind(dc)) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { gl.glPushMatrix(); gl.glScaled(this.activeIconTexture.getWidth(dc), this.activeIconTexture.getHeight(dc), 1d); dc.drawUnitQuad(this.activeIconTexture.getTexCoords()); - } - finally - { + } finally { gl.glPopMatrix(); } } - protected void drawGraphicModifiers(DrawContext dc, OrderedSymbol osym) - { + protected void drawGraphicModifiers(DrawContext dc, OrderedSymbol osym) { this.drawGlyphs(dc); this.drawLines(dc, osym); } - protected void drawTextModifiers(DrawContext dc) - { + protected void drawTextModifiers(DrawContext dc) { this.drawLabels(dc); } - protected void drawGlyphs(DrawContext dc) - { - if (this.glyphAtlas == null || this.currentGlyphs.isEmpty()) + protected void drawGlyphs(DrawContext dc) { + if (this.glyphAtlas == null || this.currentGlyphs.isEmpty()) { return; + } - if (!this.glyphAtlas.bind(dc)) + if (!this.glyphAtlas.bind(dc)) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - for (IconAtlasElement atlasElem : this.currentGlyphs) - { + for (IconAtlasElement atlasElem : this.currentGlyphs) { Point point = atlasElem.getPoint(); Dimension size = atlasElem.getSize(); TextureCoords texCoords = atlasElem.getTexCoords(); - if (point == null || size == null || texCoords == null) + if (point == null || size == null || texCoords == null) { continue; + } - try - { + try { gl.glPushMatrix(); gl.glTranslated(point.getX(), point.getY(), 0d); gl.glScaled(size.getWidth(), size.getHeight(), 1d); dc.drawUnitQuad(texCoords); - } - finally - { + } finally { gl.glPopMatrix(); } } } - protected void drawLabels(DrawContext dc) - { - if (this.currentLabels.isEmpty()) + protected void drawLabels(DrawContext dc) { + if (this.currentLabels.isEmpty()) { return; + } GL gl = dc.getGL(); TextRenderer tr = null; TextRendererCache trCache = dc.getTextRendererCache(); - try - { + try { // Don't depth buffer labels. Depth buffering would cause the labels to intersect terrain, which is // usually a bigger usability problem for text than a label showing through a hill. gl.glDisable(GL.GL_DEPTH_TEST); - for (Label modifier : this.currentLabels) - { + for (Label modifier : this.currentLabels) { TextRenderer modifierRenderer = OGLTextRenderer.getOrCreateTextRenderer(trCache, modifier.getFont()); - if (tr == null || tr != modifierRenderer) - { - if (tr != null) + if (tr == null || tr != modifierRenderer) { + if (tr != null) { tr.end3DRendering(); + } tr = modifierRenderer; tr.begin3DRendering(); } @@ -2331,26 +2245,23 @@ protected void drawLabels(DrawContext dc) tr.setColor(modifier.getColor()); tr.draw(modifier.getText(), p.x, p.y); } - } - finally - { - if (tr != null) + } finally { + if (tr != null) { tr.end3DRendering(); + } gl.glEnable(GL.GL_DEPTH_TEST); } } - protected void drawLines(DrawContext dc, OrderedSymbol osym) - { + protected void drawLines(DrawContext dc, OrderedSymbol osym) { // Use either the currently specified opacity or the default if no opacity is specified. Double opacity = this.getActiveAttributes().getOpacity() != null ? this.getActiveAttributes().getOpacity() - : BasicTacticalSymbolAttributes.DEFAULT_OPACITY; + : BasicTacticalSymbolAttributes.DEFAULT_OPACITY; GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { gl.glDisable(GL.GL_TEXTURE_2D); // Apply an offset to move the line away from terrain. @@ -2361,41 +2272,35 @@ protected void drawLines(DrawContext dc, OrderedSymbol osym) // Set the current color to black with the current opacity value as the alpha component. Blending is set to // pre-multiplied alpha mode, but we can just specify 0 for the RGB components because multiplying them by // the alpha component has no effect. - if (!dc.isPickingMode()) + if (!dc.isPickingMode()) { gl.glColor4f(0f, 0f, 0f, opacity.floatValue()); + } - for (Line lm : this.currentLines) - { - try - { + for (Line lm : this.currentLines) { + try { gl.glBegin(GL2.GL_LINE_STRIP); - for (Point2D p : lm.getPoints()) - { + for (Point2D p : lm.getPoints()) { gl.glVertex2d(p.getX(), p.getY()); } - } - finally - { + } finally { gl.glEnd(); } } - } - finally - { + } finally { // Restore the depth range and texture 2D enable state to the values specified in beginDrawing. gl.glEnable(GL.GL_TEXTURE_2D); gl.glDepthRange(0.0, 1.0); // Restore the current color to that specified in doDrawOrderedRenderable. - if (!dc.isPickingMode()) + if (!dc.isPickingMode()) { gl.glColor4f(opacity.floatValue(), opacity.floatValue(), opacity.floatValue(), - opacity.floatValue()); + opacity.floatValue()); + } } } - protected PickedObject createPickedObject(int colorCode) - { + protected PickedObject createPickedObject(int colorCode) { Object owner = this.getDelegateOwner(); return new PickedObject(colorCode, owner != null ? owner : this); } diff --git a/src/gov/nasa/worldwind/symbology/BasicTacticalGraphicAttributes.java b/src/gov/nasa/worldwind/symbology/BasicTacticalGraphicAttributes.java index 4caefd0a76..c855fbf934 100644 --- a/src/gov/nasa/worldwind/symbology/BasicTacticalGraphicAttributes.java +++ b/src/gov/nasa/worldwind/symbology/BasicTacticalGraphicAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.render.Material; @@ -17,34 +16,46 @@ * @author pabercrombie * @version $Id: BasicTacticalGraphicAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicTacticalGraphicAttributes implements TacticalGraphicAttributes -{ +public class BasicTacticalGraphicAttributes implements TacticalGraphicAttributes { + /** * Indicates the symbol scale as a ratio of the symbol's original size, or null to use the symbol's * default scale. Initially null. */ protected Double scale; - /** Indicates the material properties of the graphic's interior. Initially null. */ + /** + * Indicates the material properties of the graphic's interior. Initially null. + */ protected Material interiorMaterial; - /** Indicates the material properties of the graphic's outline. Initially null. */ + /** + * Indicates the material properties of the graphic's outline. Initially null. + */ protected Material outlineMaterial; /** - * Indicates the opacity of the graphic's interior as a floating-point value in the range 0.0 to 1.0. Initially - * 0.0. + * Indicates the opacity of the graphic's interior as a floating-point value in the range 0.0 to 1.0. Initially 0.0. */ protected Double interiorOpacity; - /** Indicates the opacity of the graphic's outline as a floating-point value in the range 0.0 to 1.0. Initially 0.0. */ + /** + * Indicates the opacity of the graphic's outline as a floating-point value in the range 0.0 to 1.0. Initially 0.0. + */ protected Double outlineOpacity; - /** Indicates the line width (in pixels) used when rendering the shape's outline. Initially 0.0. */ + /** + * Indicates the line width (in pixels) used when rendering the shape's outline. Initially 0.0. + */ protected double outlineWidth; - /** Indicates the font used to render text modifiers. */ + /** + * Indicates the font used to render text modifiers. + */ protected Font font; - /** Indicates the material used to render text modifiers. */ + /** + * Indicates the material used to render text modifiers. + */ protected Material textMaterial; - /** Creates a new BasicTacticalGraphicAttributes. */ - public BasicTacticalGraphicAttributes() - { + /** + * Creates a new BasicTacticalGraphicAttributes. + */ + public BasicTacticalGraphicAttributes() { } /** @@ -54,10 +65,8 @@ public BasicTacticalGraphicAttributes() * * @throws IllegalArgumentException if attributes is null. */ - public BasicTacticalGraphicAttributes(TacticalGraphicAttributes attributes) - { - if (attributes == null) - { + public BasicTacticalGraphicAttributes(TacticalGraphicAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -73,17 +82,18 @@ public BasicTacticalGraphicAttributes(TacticalGraphicAttributes attributes) this.outlineWidth = attributes.getOutlineWidth(); } - /** {@inheritDoc} */ - public TacticalGraphicAttributes copy() - { + /** + * {@inheritDoc} + */ + public TacticalGraphicAttributes copy() { return new BasicTacticalGraphicAttributes(this); } - /** {@inheritDoc} */ - public void copy(TacticalGraphicAttributes attributes) - { - if (attributes != null) - { + /** + * {@inheritDoc} + */ + public void copy(TacticalGraphicAttributes attributes) { + if (attributes != null) { this.scale = attributes.getScale(); this.font = attributes.getTextModifierFont(); this.textMaterial = attributes.getTextModifierMaterial(); @@ -95,17 +105,18 @@ public void copy(TacticalGraphicAttributes attributes) } } - /** {@inheritDoc} */ - public Double getScale() - { + /** + * {@inheritDoc} + */ + public Double getScale() { return this.scale; } - /** {@inheritDoc} */ - public void setScale(Double scale) - { - if (scale != null && scale < 0d) - { + /** + * {@inheritDoc} + */ + public void setScale(Double scale) { + if (scale != null && scale < 0d) { String msg = Logging.getMessage("generic.ScaleOutOfRange", scale); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -114,41 +125,46 @@ public void setScale(Double scale) this.scale = scale; } - /** {@inheritDoc} */ - public Font getTextModifierFont() - { + /** + * {@inheritDoc} + */ + public Font getTextModifierFont() { return this.font; } - /** {@inheritDoc} */ - public void setTextModifierFont(Font font) - { + /** + * {@inheritDoc} + */ + public void setTextModifierFont(Font font) { this.font = font; } - /** {@inheritDoc} */ - public Material getTextModifierMaterial() - { + /** + * {@inheritDoc} + */ + public Material getTextModifierMaterial() { return this.textMaterial; } - /** {@inheritDoc} */ - public void setTextModifierMaterial(Material material) - { + /** + * {@inheritDoc} + */ + public void setTextModifierMaterial(Material material) { this.textMaterial = material; } - /** {@inheritDoc} */ - public Material getInteriorMaterial() - { + /** + * {@inheritDoc} + */ + public Material getInteriorMaterial() { return this.interiorMaterial; } - /** {@inheritDoc} */ - public void setInteriorMaterial(Material material) - { - if (material == null) - { + /** + * {@inheritDoc} + */ + public void setInteriorMaterial(Material material) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -157,29 +173,32 @@ public void setInteriorMaterial(Material material) this.interiorMaterial = material; } - /** {@inheritDoc} */ - public Material getOutlineMaterial() - { + /** + * {@inheritDoc} + */ + public Material getOutlineMaterial() { return this.outlineMaterial; } - /** {@inheritDoc} */ - public void setOutlineMaterial(Material material) - { + /** + * {@inheritDoc} + */ + public void setOutlineMaterial(Material material) { this.outlineMaterial = material; } - /** {@inheritDoc} */ - public Double getInteriorOpacity() - { + /** + * {@inheritDoc} + */ + public Double getInteriorOpacity() { return this.interiorOpacity; } - /** {@inheritDoc} */ - public void setInteriorOpacity(Double opacity) - { - if (opacity < 0 || opacity > 1) - { + /** + * {@inheritDoc} + */ + public void setInteriorOpacity(Double opacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -188,17 +207,18 @@ public void setInteriorOpacity(Double opacity) this.interiorOpacity = opacity; } - /** {@inheritDoc} */ - public Double getOutlineOpacity() - { + /** + * {@inheritDoc} + */ + public Double getOutlineOpacity() { return this.outlineOpacity; } - /** {@inheritDoc} */ - public void setOutlineOpacity(Double opacity) - { - if (opacity < 0 || opacity > 1) - { + /** + * {@inheritDoc} + */ + public void setOutlineOpacity(Double opacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -207,17 +227,18 @@ public void setOutlineOpacity(Double opacity) this.outlineOpacity = opacity; } - /** {@inheritDoc} */ - public Double getOutlineWidth() - { + /** + * {@inheritDoc} + */ + public Double getOutlineWidth() { return this.outlineWidth; } - /** {@inheritDoc} */ - public void setOutlineWidth(Double width) - { - if (width < 0) - { + /** + * {@inheritDoc} + */ + public void setOutlineWidth(Double width) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/symbology/BasicTacticalSymbolAttributes.java b/src/gov/nasa/worldwind/symbology/BasicTacticalSymbolAttributes.java index 56744b29a5..b6427b5fbc 100644 --- a/src/gov/nasa/worldwind/symbology/BasicTacticalSymbolAttributes.java +++ b/src/gov/nasa/worldwind/symbology/BasicTacticalSymbolAttributes.java @@ -16,8 +16,8 @@ * @author dcollins * @version $Id: BasicTacticalSymbolAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicTacticalSymbolAttributes implements TacticalSymbolAttributes -{ +public class BasicTacticalSymbolAttributes implements TacticalSymbolAttributes { + public static final double DEFAULT_SCALE = 1d; public static final double DEFAULT_OPACITY = 1d; public static final Font DEFAULT_TEXT_MODIFIER_FONT = Font.decode("Arial-PLAIN-18"); @@ -49,9 +49,10 @@ public class BasicTacticalSymbolAttributes implements TacticalSymbolAttributes */ protected Material textModifierMaterial; - /** Constructs a BasicTacticalSymbolAttributes with all attributes set to null. */ - public BasicTacticalSymbolAttributes() - { + /** + * Constructs a BasicTacticalSymbolAttributes with all attributes set to null. + */ + public BasicTacticalSymbolAttributes() { } /** @@ -62,32 +63,27 @@ public BasicTacticalSymbolAttributes() * null or a value between 0.0 and 1.0 (inclusive). The textModifierFont and textModifierMaterial * specify the font and material to use when drawing a symbol's text modifiers. * - * @param scale the symbol's scale. May be null, indicating that the default scale - * should be used. - * @param interiorMaterial the interior material. May be null, indicating that the default material - * should be used. - * @param opacity the symbol opacity. May be null, indicating that the default opacity - * should be used. - * @param textModifierFont the text modifier font. May be null, indicating that the default font - * should be used. + * @param scale the symbol's scale. May be null, indicating that the default scale should be used. + * @param interiorMaterial the interior material. May be null, indicating that the default material + * should be used. + * @param opacity the symbol opacity. May be null, indicating that the default opacity should be used. + * @param textModifierFont the text modifier font. May be null, indicating that the default font should + * be used. * @param textModifierMaterial the text modifier material. May be null, indicating that the default - * material should be used. + * material should be used. * * @throws IllegalArgumentException if the scale is less than 0.0, or if the opacity is less than 0.0 or greater - * than 1.0. + * than 1.0. */ public BasicTacticalSymbolAttributes(Double scale, Material interiorMaterial, Double opacity, Font textModifierFont, - Material textModifierMaterial) - { - if (scale != null && scale < 0d) - { + Material textModifierMaterial) { + if (scale != null && scale < 0d) { String msg = Logging.getMessage("generic.ScaleOutOfRange", scale); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (opacity != null && (opacity < 0d || opacity > 1d)) - { + if (opacity != null && (opacity < 0d || opacity > 1d)) { String msg = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -100,11 +96,11 @@ public BasicTacticalSymbolAttributes(Double scale, Material interiorMaterial, Do this.textModifierMaterial = textModifierMaterial; } - /** {@inheritDoc} */ - public void copy(TacticalSymbolAttributes attributes) - { - if (attributes != null) - { + /** + * {@inheritDoc} + */ + public void copy(TacticalSymbolAttributes attributes) { + if (attributes != null) { this.scale = attributes.getScale(); this.interiorMaterial = attributes.getInteriorMaterial(); this.opacity = attributes.getOpacity(); @@ -113,17 +109,18 @@ public void copy(TacticalSymbolAttributes attributes) } } - /** {@inheritDoc} */ - public Double getScale() - { + /** + * {@inheritDoc} + */ + public Double getScale() { return this.scale; } - /** {@inheritDoc} */ - public void setScale(Double scale) - { - if (scale != null && scale < 0d) - { + /** + * {@inheritDoc} + */ + public void setScale(Double scale) { + if (scale != null && scale < 0d) { String msg = Logging.getMessage("generic.ScaleOutOfRange", scale); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -132,27 +129,26 @@ public void setScale(Double scale) this.scale = scale; } - public Material getInteriorMaterial() - { + public Material getInteriorMaterial() { return this.interiorMaterial; } - public void setInteriorMaterial(Material material) - { + public void setInteriorMaterial(Material material) { this.interiorMaterial = material; } - /** {@inheritDoc} */ - public Double getOpacity() - { + /** + * {@inheritDoc} + */ + public Double getOpacity() { return this.opacity; } - /** {@inheritDoc} */ - public void setOpacity(Double opacity) - { - if (opacity != null && (opacity < 0d || opacity > 1d)) - { + /** + * {@inheritDoc} + */ + public void setOpacity(Double opacity) { + if (opacity != null && (opacity < 0d || opacity > 1d)) { String msg = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -161,27 +157,31 @@ public void setOpacity(Double opacity) this.opacity = opacity; } - /** {@inheritDoc} */ - public Font getTextModifierFont() - { + /** + * {@inheritDoc} + */ + public Font getTextModifierFont() { return this.textModifierFont; } - /** {@inheritDoc} */ - public void setTextModifierFont(Font font) - { + /** + * {@inheritDoc} + */ + public void setTextModifierFont(Font font) { this.textModifierFont = font; } - /** {@inheritDoc} */ - public Material getTextModifierMaterial() - { + /** + * {@inheritDoc} + */ + public Material getTextModifierMaterial() { return this.textModifierMaterial; } - /** {@inheritDoc} */ - public void setTextModifierMaterial(Material material) - { + /** + * {@inheritDoc} + */ + public void setTextModifierMaterial(Material material) { this.textModifierMaterial = material; } } diff --git a/src/gov/nasa/worldwind/symbology/IconRetriever.java b/src/gov/nasa/worldwind/symbology/IconRetriever.java index bf3431a71c..099697d565 100644 --- a/src/gov/nasa/worldwind/symbology/IconRetriever.java +++ b/src/gov/nasa/worldwind/symbology/IconRetriever.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.avlist.AVList; @@ -12,22 +11,23 @@ /** * Retrieves icons for symbols in a symbol set from a local disk or the network. Typically, an icon retriever will be - * implemented for a specific symbol set. For example, the {@link gov.nasa.worldwind.symbology.milstd2525.MilStd2525IconRetriever} - * retrieves icons for symbols in the MIL-STD-2525 symbology set. See the Icon Retriever Usage Guide for more information. * * @author ccrick * @version $Id: IconRetriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface IconRetriever -{ +public interface IconRetriever { + /** * Create an icon to represent a symbol in a symbol set. * * @param symbolId Identifier for the symbol. The format of this identifier depends on the symbology set. - * @param params Parameters that affect icon retrieval. + * @param params Parameters that affect icon retrieval. * * @return A BufferedImage containing the requested icon, or null if the icon cannot be retrieved. */ BufferedImage createIcon(String symbolId, AVList params); -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/SymbologyConstants.java b/src/gov/nasa/worldwind/symbology/SymbologyConstants.java index c72408f39e..9e03ba0c4b 100644 --- a/src/gov/nasa/worldwind/symbology/SymbologyConstants.java +++ b/src/gov/nasa/worldwind/symbology/SymbologyConstants.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import java.util.*; @@ -15,10 +14,10 @@ * @author dcollins * @version $Id: SymbologyConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface SymbologyConstants -{ +public interface SymbologyConstants { + /** - * The MIL-STD-2525 Additional Information modifier field ID. The meaning of this field is implementation specific. + * The MIL-STD-2525 Additional Information modifier field ID. The meaning of this field is implementation specific. * See MIL-STD-2525 section 5.3.4.10 (page 29), table IV (pages 22-24) and table XIV (pages 46-47). When used as a * key, the corresponding value must be a string containing up to 20 characters. */ @@ -55,10 +54,12 @@ public interface SymbologyConstants * and table VII (page 28). */ final String AUXILIARY_EQUIPMENT_TOWED_SONAR_ARRAY_SHORT = "NS"; - /** List containing all recognized MIL-STD-2525 auxiliary equipment codes. */ + /** + * List containing all recognized MIL-STD-2525 auxiliary equipment codes. + */ final List AUXILIARY_EQUIPMENT_ALL = Arrays.asList( - AUXILIARY_EQUIPMENT_TOWED_SONAR_ARRAY_SHORT, - AUXILIARY_EQUIPMENT_TOWED_SONAR_ARRAY_LONG + AUXILIARY_EQUIPMENT_TOWED_SONAR_ARRAY_SHORT, + AUXILIARY_EQUIPMENT_TOWED_SONAR_ARRAY_LONG ); /** @@ -124,26 +125,30 @@ public interface SymbologyConstants * determined or cannot be determined. See MIL-STD-2525C section 5.3.1.3 (page 17). */ final String BATTLE_DIMENSION_UNKNOWN = "Z"; - /** List containing all recognized MIL-STD-2525 battle dimension codes. */ + /** + * List containing all recognized MIL-STD-2525 battle dimension codes. + */ final List BATTLE_DIMENSION_ALL = Arrays.asList( - BATTLE_DIMENSION_UNKNOWN, - BATTLE_DIMENSION_SPACE, - BATTLE_DIMENSION_AIR, - BATTLE_DIMENSION_GROUND, - BATTLE_DIMENSION_SEA_SURFACE, - BATTLE_DIMENSION_SEA_SUBSURFACE, - BATTLE_DIMENSION_SOF, - BATTLE_DIMENSION_OTHER + BATTLE_DIMENSION_UNKNOWN, + BATTLE_DIMENSION_SPACE, + BATTLE_DIMENSION_AIR, + BATTLE_DIMENSION_GROUND, + BATTLE_DIMENSION_SEA_SURFACE, + BATTLE_DIMENSION_SEA_SUBSURFACE, + BATTLE_DIMENSION_SOF, + BATTLE_DIMENSION_OTHER ); - /** List containing all recognized MIL-STD-2525 battle dimension codes for the Signals Intelligence scheme. */ + /** + * List containing all recognized MIL-STD-2525 battle dimension codes for the Signals Intelligence scheme. + */ final List BATTLE_DIMENSION_ALL_INTELLIGENCE = Arrays.asList( - BATTLE_DIMENSION_UNKNOWN, - BATTLE_DIMENSION_SPACE, - BATTLE_DIMENSION_AIR, - BATTLE_DIMENSION_GROUND, - BATTLE_DIMENSION_SEA_SURFACE, - BATTLE_DIMENSION_SEA_SUBSURFACE, - BATTLE_DIMENSION_OTHER + BATTLE_DIMENSION_UNKNOWN, + BATTLE_DIMENSION_SPACE, + BATTLE_DIMENSION_AIR, + BATTLE_DIMENSION_GROUND, + BATTLE_DIMENSION_SEA_SURFACE, + BATTLE_DIMENSION_SEA_SUBSURFACE, + BATTLE_DIMENSION_OTHER ); /** @@ -173,28 +178,40 @@ public interface SymbologyConstants */ final String CATEGORY_COMMAND_CONTROL_GENERAL_MANEUVER = "G"; /** - * The MIL-STD-2525 Combat Service Support category code, used by symbols belonging to the Tactical Graphics - * scheme. + * The MIL-STD-2525 Combat Service Support category code, used by symbols belonging to the Tactical Graphics scheme. */ final String CATEGORY_COMBAT_SERVICE_SUPPORT = "S"; - /** The MIL-STD-2525 Fire Support category code, used by symbols belonging to the Tactical Graphics scheme. */ + /** + * The MIL-STD-2525 Fire Support category code, used by symbols belonging to the Tactical Graphics scheme. + */ final String CATEGORY_FIRE_SUPPORT = "F"; - /** The MIL-STD-2525 Incident category code, used by symbols belonging to the Emergency Management scheme. */ + /** + * The MIL-STD-2525 Incident category code, used by symbols belonging to the Emergency Management scheme. + */ final String CATEGORY_INCIDENT = "I"; - /** The MIL-STD-2525 Individual category code, used by symbols belonging to the Stability Operations scheme. */ + /** + * The MIL-STD-2525 Individual category code, used by symbols belonging to the Stability Operations scheme. + */ final String CATEGORY_INDIVIDUAL = "P"; - /** The MIL-STD-2525 Infrastructure category code, used by symbols belonging to the Emergency Management scheme. */ + /** + * The MIL-STD-2525 Infrastructure category code, used by symbols belonging to the Emergency Management scheme. + */ final String CATEGORY_INFRASTRUCTURE = "F"; - /** The MIL-STD-2525 Items category code, used by symbols belonging to the Stability Operations scheme. */ + /** + * The MIL-STD-2525 Items category code, used by symbols belonging to the Stability Operations scheme. + */ final String CATEGORY_ITEMS = "I"; - /** The MIL-STD-2525 Locations category code, used by symbols belonging to the Stability Operations scheme. */ + /** + * The MIL-STD-2525 Locations category code, used by symbols belonging to the Stability Operations scheme. + */ final String CATEGORY_LOCATIONS = "L"; /** - * The MIL-STD-2525 Mobility/Survivability category code, used by symbols belonging to the Tactical Graphics - * scheme. + * The MIL-STD-2525 Mobility/Survivability category code, used by symbols belonging to the Tactical Graphics scheme. */ final String CATEGORY_MOBILITY_SURVIVABILITY = "M"; - /** The MIL-STD-2525 Natural Events category code, used by symbols belonging to the Emergency Management scheme. */ + /** + * The MIL-STD-2525 Natural Events category code, used by symbols belonging to the Emergency Management scheme. + */ final String CATEGORY_NATURAL_EVENTS = "N"; /** * The MIL-STD-2525 Non-Military Group or Organization category code, used by symbols belonging to the Stability @@ -206,79 +223,103 @@ public interface SymbologyConstants * Management schemes. */ final String CATEGORY_OPERATIONS = "O"; - /** The MIL-STD-2525 Other category code, used by symbols belonging to the Tactical Graphics scheme. */ + /** + * The MIL-STD-2525 Other category code, used by symbols belonging to the Tactical Graphics scheme. + */ final String CATEGORY_OTHER = "O"; - /** The MIL-STD-2525 Rape category code, used by symbols belonging to the Stability Operations scheme. */ + /** + * The MIL-STD-2525 Rape category code, used by symbols belonging to the Stability Operations scheme. + */ final String CATEGORY_RAPE = "R"; - /** The MIL-STD-2525 Tasks category code, used by symbols belonging to the Tactical Graphics scheme. */ + /** + * The MIL-STD-2525 Tasks category code, used by symbols belonging to the Tactical Graphics scheme. + */ final String CATEGORY_TASKS = "T"; - /** The MIL-STD-2525 Violent Activities category code, used by symbols belonging to the Stability Operations scheme. */ + /** + * The MIL-STD-2525 Violent Activities category code, used by symbols belonging to the Stability Operations scheme. + */ final String CATEGORY_VIOLENT_ACTIVITIES = "V"; - /** The MIL-STD-2525 Atmospheric category code, used by symbols belonging to the METOC scheme. */ + /** + * The MIL-STD-2525 Atmospheric category code, used by symbols belonging to the METOC scheme. + */ final String CATEGORY_ATMOSPHERIC = "A"; - /** The MIL-STD-2525 Oceanic category code, used by symbols belonging to the METOC scheme. */ + /** + * The MIL-STD-2525 Oceanic category code, used by symbols belonging to the METOC scheme. + */ final String CATEGORY_OCEANIC = "O"; - /** The MIL-STD-2525 Space category code, used by symbols belonging to the METOC scheme. */ + /** + * The MIL-STD-2525 Space category code, used by symbols belonging to the METOC scheme. + */ final String CATEGORY_SPACE = "S"; - /** List containing all recognized MIL-STD-2525 category codes. */ + /** + * List containing all recognized MIL-STD-2525 category codes. + */ final List CATEGORY_ALL = Arrays.asList( - // Tactical Graphics category codes. - CATEGORY_TASKS, - CATEGORY_COMMAND_CONTROL_GENERAL_MANEUVER, - CATEGORY_MOBILITY_SURVIVABILITY, - CATEGORY_FIRE_SUPPORT, - CATEGORY_COMBAT_SERVICE_SUPPORT, - CATEGORY_OTHER, - // Stability Operations category codes. - CATEGORY_VIOLENT_ACTIVITIES, - CATEGORY_LOCATIONS, - CATEGORY_OPERATIONS, - CATEGORY_ITEMS, - CATEGORY_INDIVIDUAL, - CATEGORY_NONMILITARY_GROUP_ORGANIZATION, - CATEGORY_RAPE, - // Emergency Management category codes (CATEGORY_OPERATIONS already included from Tactical Graphics). - CATEGORY_INCIDENT, - CATEGORY_NATURAL_EVENTS, - CATEGORY_INFRASTRUCTURE, - // METOC category codes - CATEGORY_ATMOSPHERIC, - CATEGORY_OCEANIC, - CATEGORY_SPACE + // Tactical Graphics category codes. + CATEGORY_TASKS, + CATEGORY_COMMAND_CONTROL_GENERAL_MANEUVER, + CATEGORY_MOBILITY_SURVIVABILITY, + CATEGORY_FIRE_SUPPORT, + CATEGORY_COMBAT_SERVICE_SUPPORT, + CATEGORY_OTHER, + // Stability Operations category codes. + CATEGORY_VIOLENT_ACTIVITIES, + CATEGORY_LOCATIONS, + CATEGORY_OPERATIONS, + CATEGORY_ITEMS, + CATEGORY_INDIVIDUAL, + CATEGORY_NONMILITARY_GROUP_ORGANIZATION, + CATEGORY_RAPE, + // Emergency Management category codes (CATEGORY_OPERATIONS already included from Tactical Graphics). + CATEGORY_INCIDENT, + CATEGORY_NATURAL_EVENTS, + CATEGORY_INFRASTRUCTURE, + // METOC category codes + CATEGORY_ATMOSPHERIC, + CATEGORY_OCEANIC, + CATEGORY_SPACE ); - /** List containing all recognized MIL-STD-2525 category codes for the Tactical Graphics scheme. */ + /** + * List containing all recognized MIL-STD-2525 category codes for the Tactical Graphics scheme. + */ final List CATEGORY_ALL_TACTICAL_GRAPHICS = Arrays.asList( - CATEGORY_TASKS, - CATEGORY_COMMAND_CONTROL_GENERAL_MANEUVER, - CATEGORY_MOBILITY_SURVIVABILITY, - CATEGORY_FIRE_SUPPORT, - CATEGORY_COMBAT_SERVICE_SUPPORT, - CATEGORY_OTHER + CATEGORY_TASKS, + CATEGORY_COMMAND_CONTROL_GENERAL_MANEUVER, + CATEGORY_MOBILITY_SURVIVABILITY, + CATEGORY_FIRE_SUPPORT, + CATEGORY_COMBAT_SERVICE_SUPPORT, + CATEGORY_OTHER ); - /** List containing all recognized MIL-STD-2525 category codes for the Stability Operations scheme. */ + /** + * List containing all recognized MIL-STD-2525 category codes for the Stability Operations scheme. + */ final List CATEGORY_ALL_STABILITY_OPERATIONS = Arrays.asList( - CATEGORY_VIOLENT_ACTIVITIES, - CATEGORY_LOCATIONS, - CATEGORY_OPERATIONS, - CATEGORY_ITEMS, - CATEGORY_INDIVIDUAL, - CATEGORY_NONMILITARY_GROUP_ORGANIZATION, - CATEGORY_RAPE + CATEGORY_VIOLENT_ACTIVITIES, + CATEGORY_LOCATIONS, + CATEGORY_OPERATIONS, + CATEGORY_ITEMS, + CATEGORY_INDIVIDUAL, + CATEGORY_NONMILITARY_GROUP_ORGANIZATION, + CATEGORY_RAPE ); - /** List containing all recognized MIL-STD-2525 category codes for the Emergency Management scheme. */ + /** + * List containing all recognized MIL-STD-2525 category codes for the Emergency Management scheme. + */ final List CATEGORY_ALL_EMERGENCY_MANAGEMENT = Arrays.asList( - CATEGORY_INCIDENT, - CATEGORY_NATURAL_EVENTS, - CATEGORY_OPERATIONS, - CATEGORY_INFRASTRUCTURE + CATEGORY_INCIDENT, + CATEGORY_NATURAL_EVENTS, + CATEGORY_OPERATIONS, + CATEGORY_INFRASTRUCTURE ); - /** List containing all recognized MIL-STD-2525 category codes for the Meteorological and Oceanographic scheme. */ + /** + * List containing all recognized MIL-STD-2525 category codes for the Meteorological and Oceanographic scheme. + */ final List CATEGORY_ALL_METOC = Arrays.asList( - CATEGORY_ATMOSPHERIC, - CATEGORY_OCEANIC, - CATEGORY_SPACE + CATEGORY_ATMOSPHERIC, + CATEGORY_OCEANIC, + CATEGORY_SPACE ); /** @@ -407,22 +448,24 @@ public interface SymbologyConstants * table V (pages 25-26). */ final String ECHELON_REGION = "M"; - /** List containing all recognized MIL-STD-2525 echelon codes. */ + /** + * List containing all recognized MIL-STD-2525 echelon codes. + */ final List ECHELON_ALL = Arrays.asList( - ECHELON_TEAM_CREW, - ECHELON_SQUAD, - ECHELON_SECTION, - ECHELON_PLATOON_DETACHMENT, - ECHELON_COMPANY_BATTERY_TROOP, - ECHELON_BATTALION_SQUADRON, - ECHELON_REGIMENT_GROUP, - ECHELON_BRIGADE, - ECHELON_DIVISION, - ECHELON_CORPS, - ECHELON_ARMY, - ECHELON_ARMY_GROUP_FRONT, - ECHELON_REGION, - ECHELON_COMMAND + ECHELON_TEAM_CREW, + ECHELON_SQUAD, + ECHELON_SECTION, + ECHELON_PLATOON_DETACHMENT, + ECHELON_COMPANY_BATTERY_TROOP, + ECHELON_BATTALION_SQUADRON, + ECHELON_REGIMENT_GROUP, + ECHELON_BRIGADE, + ECHELON_DIVISION, + ECHELON_CORPS, + ECHELON_ARMY, + ECHELON_ARMY_GROUP_FRONT, + ECHELON_REGION, + ECHELON_COMMAND ); /** @@ -487,16 +530,22 @@ public interface SymbologyConstants *

          • GRAPHIC_TYPE_POINT
          • GRAPHIC_TYPE_LINE
          • GRAPHIC_TYPE_AREA
          */ final String GRAPHIC_TYPE = "gov.nasa.worldwind.symbology.GraphicType"; - /** The MIL-STD-2525 Point type, used by symbols belonging to the METOC scheme. */ + /** + * The MIL-STD-2525 Point type, used by symbols belonging to the METOC scheme. + */ final String GRAPHIC_TYPE_POINT = "P--"; - /** The MIL-STD-2525 Line type, used by symbols belonging to the METOC scheme. */ + /** + * The MIL-STD-2525 Line type, used by symbols belonging to the METOC scheme. + */ final String GRAPHIC_TYPE_LINE = "-L-"; - /** The MIL-STD-2525 Area type, used by symbols belonging to the METOC scheme. */ + /** + * The MIL-STD-2525 Area type, used by symbols belonging to the METOC scheme. + */ final String GRAPHIC_TYPE_AREA = "--A"; final List GRAPHIC_TYPE_ALL = Arrays.asList( - GRAPHIC_TYPE_POINT, - GRAPHIC_TYPE_LINE, - GRAPHIC_TYPE_AREA + GRAPHIC_TYPE_POINT, + GRAPHIC_TYPE_LINE, + GRAPHIC_TYPE_AREA ); /** @@ -556,12 +605,16 @@ public interface SymbologyConstants * 28). */ final String INSTALLATION_NORMAL = "H-"; - /** The MIL-STD-2525 Feint/Dummy installation code. See MIL-STD-2525 section 5.3.4.5 (page 28). */ + /** + * The MIL-STD-2525 Feint/Dummy installation code. See MIL-STD-2525 section 5.3.4.5 (page 28). + */ final String INSTALLATION_FEINT_DUMMY = "HB"; - /** List containing all recognized MIL-STD-2525 installation codes. */ + /** + * List containing all recognized MIL-STD-2525 installation codes. + */ final List INSTALLATION_ALL = Arrays.asList( - INSTALLATION_NORMAL, - INSTALLATION_FEINT_DUMMY + INSTALLATION_NORMAL, + INSTALLATION_FEINT_DUMMY ); /** @@ -593,7 +646,9 @@ public interface SymbologyConstants * (pages 26-27). */ final String MOBILITY_AMPHIBIOUS = "MY"; - /** The MIL-STD-2525 Barge mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). */ + /** + * The MIL-STD-2525 Barge mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). + */ final String MOBILITY_BARGE = "MX"; /** * The MIL-STD-2525 Cross Country mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages @@ -610,13 +665,21 @@ public interface SymbologyConstants * 26-27). */ final String MOBILITY_PACK_ANIMALS = "MW"; - /** The MIL-STD-2525 Rail mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). */ + /** + * The MIL-STD-2525 Rail mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). + */ final String MOBILITY_RAIL = "MT"; - /** The MIL-STD-2525 Sled mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). */ + /** + * The MIL-STD-2525 Sled mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). + */ final String MOBILITY_SLED = "MV"; - /** The MIL-STD-2525 Towed mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). */ + /** + * The MIL-STD-2525 Towed mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). + */ final String MOBILITY_TOWED = "MS"; - /** The MIL-STD-2525 Tracked mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). */ + /** + * The MIL-STD-2525 Tracked mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and table VI (pages 26-27). + */ final String MOBILITY_TRACKED = "MQ"; /** * The MIL-STD-2525 Wheeled/Limited Cross Country mobility code. See MIL-STD-2525 section 5.3.4.3 (page 26) and @@ -628,19 +691,21 @@ public interface SymbologyConstants * table VI (pages 26-27). */ final String MOBILITY_WHEELED_TRACKED_COMBINATION = "MR"; - /** List containing all recognized MIL-STD-2525 mobility codes. */ + /** + * List containing all recognized MIL-STD-2525 mobility codes. + */ final List MOBILITY_ALL = Arrays.asList( - MOBILITY_WHEELED, - MOBILITY_CROSS_COUNTRY, - MOBILITY_TRACKED, - MOBILITY_WHEELED_TRACKED_COMBINATION, - MOBILITY_TOWED, - MOBILITY_RAIL, - MOBILITY_OVER_THE_SNOW, - MOBILITY_SLED, - MOBILITY_PACK_ANIMALS, - MOBILITY_BARGE, - MOBILITY_AMPHIBIOUS + MOBILITY_WHEELED, + MOBILITY_CROSS_COUNTRY, + MOBILITY_TRACKED, + MOBILITY_WHEELED_TRACKED_COMBINATION, + MOBILITY_TOWED, + MOBILITY_RAIL, + MOBILITY_OVER_THE_SNOW, + MOBILITY_SLED, + MOBILITY_PACK_ANIMALS, + MOBILITY_BARGE, + MOBILITY_AMPHIBIOUS ); /** @@ -679,53 +744,54 @@ public interface SymbologyConstants * task force and a headquarters. Appears in SIDC position 11. See {@link #TASK_FORCE} and {@link #HEADQUARTERS}. */ final String MODIFIER_CODE_TASK_FORCE_HEADQUARTERS = "B"; - /** List containing all recognized MIL-STD-2525 units and equipment symbol modifier codes. */ + /** + * List containing all recognized MIL-STD-2525 units and equipment symbol modifier codes. + */ final List MODIFIER_CODE_ALL_UEI = Arrays.asList( - MODIFIER_CODE_HEADQUARTERS, - MODIFIER_CODE_TASK_FORCE_HEADQUARTERS, - MODIFIER_CODE_FEINT_DUMMY_HEADQUARTERS, - MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE_HEADQUARTERS, - MODIFIER_CODE_TASK_FORCE, - MODIFIER_CODE_FEINT_DUMMY, - MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE + MODIFIER_CODE_HEADQUARTERS, + MODIFIER_CODE_TASK_FORCE_HEADQUARTERS, + MODIFIER_CODE_FEINT_DUMMY_HEADQUARTERS, + MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE_HEADQUARTERS, + MODIFIER_CODE_TASK_FORCE, + MODIFIER_CODE_FEINT_DUMMY, + MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE ); /** * List containing all recognized MIL-STD-2525 units and equipment symbol modifier codes that indicate a * feint/dummy. */ final List MODIFIER_CODE_ALL_FEINT_DUMMY = Arrays.asList( - MODIFIER_CODE_FEINT_DUMMY_HEADQUARTERS, - MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE_HEADQUARTERS, - MODIFIER_CODE_FEINT_DUMMY, - MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE + MODIFIER_CODE_FEINT_DUMMY_HEADQUARTERS, + MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE_HEADQUARTERS, + MODIFIER_CODE_FEINT_DUMMY, + MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE ); /** * List containing all recognized MIL-STD-2525 units and equipment symbol modifier codes that indicate a * headquarters. */ final List MODIFIER_CODE_ALL_HEADQUARTERS = Arrays.asList( - MODIFIER_CODE_HEADQUARTERS, - MODIFIER_CODE_TASK_FORCE_HEADQUARTERS, - MODIFIER_CODE_FEINT_DUMMY_HEADQUARTERS, - MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE_HEADQUARTERS + MODIFIER_CODE_HEADQUARTERS, + MODIFIER_CODE_TASK_FORCE_HEADQUARTERS, + MODIFIER_CODE_FEINT_DUMMY_HEADQUARTERS, + MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE_HEADQUARTERS ); /** - * List containing all recognized MIL-STD-2525 units and equipment symbol modifier codes that indicate a task - * force. + * List containing all recognized MIL-STD-2525 units and equipment symbol modifier codes that indicate a task force. */ final List MODIFIER_CODE_ALL_TASK_FORCE = Arrays.asList( - MODIFIER_CODE_TASK_FORCE_HEADQUARTERS, - MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE_HEADQUARTERS, - MODIFIER_CODE_TASK_FORCE, - MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE + MODIFIER_CODE_TASK_FORCE_HEADQUARTERS, + MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE_HEADQUARTERS, + MODIFIER_CODE_TASK_FORCE, + MODIFIER_CODE_FEINT_DUMMY_TASK_FORCE ); final String OPERATIONAL_CONDITION = "gov.nasa.worldwind.symbology.OperationalCondition"; final String OPERATIONAL_CONDITION_DAMAGED = "OD"; final String OPERATIONAL_CONDITION_DESTROYED = "OX"; final List OPERATIONAL_CONDITION_ALL = Arrays.asList( - OPERATIONAL_CONDITION_DAMAGED, - OPERATIONAL_CONDITION_DESTROYED + OPERATIONAL_CONDITION_DAMAGED, + OPERATIONAL_CONDITION_DESTROYED ); final String OPERATIONAL_CONDITION_ALTERNATE = "gov.nasa.worldwind.symbology.OperationalConditionAlternate"; @@ -734,10 +800,10 @@ public interface SymbologyConstants final String OPERATIONAL_CONDITION_ALTERNATE_DESTROYED = "PX"; final String OPERATIONAL_CONDITION_ALTERNATE_FULL_TO_CAPACITY = "PF"; final List OPERATIONAL_CONDITION_ALTERNATE_ALL = Arrays.asList( - OPERATIONAL_CONDITION_ALTERNATE_FULLY_CAPABLE, - OPERATIONAL_CONDITION_ALTERNATE_DAMAGED, - OPERATIONAL_CONDITION_ALTERNATE_DESTROYED, - OPERATIONAL_CONDITION_ALTERNATE_FULL_TO_CAPACITY + OPERATIONAL_CONDITION_ALTERNATE_FULLY_CAPABLE, + OPERATIONAL_CONDITION_ALTERNATE_DAMAGED, + OPERATIONAL_CONDITION_ALTERNATE_DESTROYED, + OPERATIONAL_CONDITION_ALTERNATE_FULL_TO_CAPACITY ); /** @@ -750,52 +816,71 @@ public interface SymbologyConstants * MIL-STD-2525C section A.5.2.1.h (page 51), table A-I (page 51), section D.5.2.1.h (page 964), table D-I (page * 964), section E.5.2.1.h (page 991), table E-I (page 991), and table G-I (page 1032). *
          • ORDER_OF_BATTLE_AIR
          • ORDER_OF_BATTLE_ELECTRONIC
          • ORDER_OF_BATTLE_CIVILIAN
          • - *
          • ORDER_OF_BATTLE_GROUND
          • ORDER_OF_BATTLE_MARITIME
          • ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED
          • + *
          • ORDER_OF_BATTLE_GROUND
          • ORDER_OF_BATTLE_MARITIME
          • + *
          • ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED
          • *
          *

          * Tactical Graphics
          See MIL-STD-2525C section B5.2.1.h (page 304) and table B-I (page 305). *

          • ORDER_OF_BATTLE_CONTROL_MARKINGS
          */ final String ORDER_OF_BATTLE = "gov.nasa.worldwind.symbology.OrderOfBattle"; - /** The MIL-STD-2525 Air order of battle code. */ + /** + * The MIL-STD-2525 Air order of battle code. + */ final String ORDER_OF_BATTLE_AIR = "A"; - /** The MIL-STD-2525 Civilian order of battle code. */ + /** + * The MIL-STD-2525 Civilian order of battle code. + */ final String ORDER_OF_BATTLE_CIVILIAN = "C"; - /** The MIL-STD-2525 Control Markings order of battle code. */ + /** + * The MIL-STD-2525 Control Markings order of battle code. + */ final String ORDER_OF_BATTLE_CONTROL_MARKINGS = "X"; - /** The MIL-STD-2525 Electronic order of battle code. */ + /** + * The MIL-STD-2525 Electronic order of battle code. + */ final String ORDER_OF_BATTLE_ELECTRONIC = "E"; - /** The MIL-STD-2525 Ground order of battle code. */ + /** + * The MIL-STD-2525 Ground order of battle code. + */ final String ORDER_OF_BATTLE_GROUND = "G"; - /** The MIL-STD-2525 Maritime order of battle code. */ + /** + * The MIL-STD-2525 Maritime order of battle code. + */ final String ORDER_OF_BATTLE_MARITIME = "N"; - /** The MIL-STD-2525 Strategic Force Related order of battle code. */ + /** + * The MIL-STD-2525 Strategic Force Related order of battle code. + */ final String ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED = "S"; - /** List containing all recognized MIL-STD-2525 order of battle codes. */ + /** + * List containing all recognized MIL-STD-2525 order of battle codes. + */ final List ORDER_OF_BATTLE_ALL = Arrays.asList( - ORDER_OF_BATTLE_AIR, - ORDER_OF_BATTLE_CIVILIAN, - ORDER_OF_BATTLE_CONTROL_MARKINGS, - ORDER_OF_BATTLE_ELECTRONIC, - ORDER_OF_BATTLE_GROUND, - ORDER_OF_BATTLE_MARITIME, - ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED + ORDER_OF_BATTLE_AIR, + ORDER_OF_BATTLE_CIVILIAN, + ORDER_OF_BATTLE_CONTROL_MARKINGS, + ORDER_OF_BATTLE_ELECTRONIC, + ORDER_OF_BATTLE_GROUND, + ORDER_OF_BATTLE_MARITIME, + ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED ); /** * List containing all recognized MIL-STD-2525 order of battle codes for the Warfighting (UEI), Signals Intelligence * (SIGINT), Stability Operations (SO), and Emergency Management (EM) schemes. */ final List ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM = Arrays.asList( - ORDER_OF_BATTLE_AIR, - ORDER_OF_BATTLE_ELECTRONIC, - ORDER_OF_BATTLE_CIVILIAN, - ORDER_OF_BATTLE_GROUND, - ORDER_OF_BATTLE_MARITIME, - ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED + ORDER_OF_BATTLE_AIR, + ORDER_OF_BATTLE_ELECTRONIC, + ORDER_OF_BATTLE_CIVILIAN, + ORDER_OF_BATTLE_GROUND, + ORDER_OF_BATTLE_MARITIME, + ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED ); - /** List containing all recognized MIL-STD-2525 order of battle codes for the Tactical Graphics scheme. */ + /** + * List containing all recognized MIL-STD-2525 order of battle codes for the Tactical Graphics scheme. + */ final List ORDER_OF_BATTLE_ALL_TACTICAL_GRAPHICS = Arrays.asList( - ORDER_OF_BATTLE_CONTROL_MARKINGS + ORDER_OF_BATTLE_CONTROL_MARKINGS ); /** @@ -827,29 +912,41 @@ public interface SymbologyConstants *
        • SCHEME_INTELLIGENCE
        • SCHEME_STABILITY_OPERATIONS
        • SCHEME_EMERGENCY_MANAGEMENT
        • */ final String SCHEME = "gov.nasa.worldwind.symbology.Scheme"; - /** The MIL-STD-2525 Emergency Management (EM) scheme code. See MIL-STD-2525C table G-I (page 1032). */ + /** + * The MIL-STD-2525 Emergency Management (EM) scheme code. See MIL-STD-2525C table G-I (page 1032). + */ final String SCHEME_EMERGENCY_MANAGEMENT = "E"; - /** The MIL-STD-2525 Signals Intelligence (SIGINT) scheme code. See MIL-STD-2525C table D-I (page 964). */ + /** + * The MIL-STD-2525 Signals Intelligence (SIGINT) scheme code. See MIL-STD-2525C table D-I (page 964). + */ final String SCHEME_INTELLIGENCE = "I"; - /** The MIL-STD-2525 Meteorological and Oceanographic (METOC) scheme code. See MIL-STD-2525C table C-I (page 763). */ + /** + * The MIL-STD-2525 Meteorological and Oceanographic (METOC) scheme code. See MIL-STD-2525C table C-I (page 763). + */ final String SCHEME_METOC = "W"; - /** The MIL-STD-2525 Stability Operations (SO) scheme code. See MIL-STD-2525C table E-I (page 991). */ + /** + * The MIL-STD-2525 Stability Operations (SO) scheme code. See MIL-STD-2525C table E-I (page 991). + */ final String SCHEME_STABILITY_OPERATIONS = "O"; - /** The MIL-STD-2525 Tactical Graphics scheme code. See MIL-STD-2525C table B-I (page 305). */ + /** + * The MIL-STD-2525 Tactical Graphics scheme code. See MIL-STD-2525C table B-I (page 305). + */ final String SCHEME_TACTICAL_GRAPHICS = "G"; /** * The MIL-STD-2525 Warfighting scheme code. This scheme is also referred to as Units, Equipment, and Installations * (UEI). See MIL-STD-2525C table A-I (page 51). */ final String SCHEME_WARFIGHTING = "S"; - /** List containing all recognized MIL-STD-2525 scheme codes. */ + /** + * List containing all recognized MIL-STD-2525 scheme codes. + */ final List SCHEME_ALL = Arrays.asList( - SCHEME_WARFIGHTING, - SCHEME_TACTICAL_GRAPHICS, - SCHEME_METOC, - SCHEME_INTELLIGENCE, - SCHEME_STABILITY_OPERATIONS, - SCHEME_EMERGENCY_MANAGEMENT + SCHEME_WARFIGHTING, + SCHEME_TACTICAL_GRAPHICS, + SCHEME_METOC, + SCHEME_INTELLIGENCE, + SCHEME_STABILITY_OPERATIONS, + SCHEME_EMERGENCY_MANAGEMENT ); /** @@ -873,7 +970,7 @@ public interface SymbologyConstants /** * @deprecated Use {@link TacticalSymbol#setShowLocation(boolean)} to control the visibility of the location - * modifier. + * modifier. */ @Deprecated final String SHOW_LOCATION = "gov.nasa.worldwind.symbology.ShowLocation"; @@ -922,7 +1019,8 @@ public interface SymbologyConstants * identity defines the threat posed by the object being represented. See MIL-STD-2525C section 3.2.39 (page 10), * section 5.3.1.1 (page 17), table I (page 15), and table II (page 16). When used as a key, the corresponding value * must be one of the following: - *
          • STANDARD_IDENTITY_PENDING
          • STANDARD_IDENTITY_UNKNOWN
          • STANDARD_IDENTITY_ASSUMED_FRIEND
          • + *
            • STANDARD_IDENTITY_PENDING
            • STANDARD_IDENTITY_UNKNOWN
            • + *
            • STANDARD_IDENTITY_ASSUMED_FRIEND
            • *
            • STANDARD_IDENTITY_FRIEND
            • STANDARD_IDENTITY_NEUTRAL
            • STANDARD_IDENTITY_SUSPECT
            • *
            • STANDARD_IDENTITY_HOSTILE
            • STANDARD_IDENTITY_EXERCISE_PENDING
            • *
            • STANDARD_IDENTITY_EXERCISE_UNKNOWN
            • STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND
            • @@ -963,11 +1061,11 @@ public interface SymbologyConstants final String STANDARD_IDENTITY_EXERCISE_PENDING = "G"; /** * The MIL-STD-2525 Exercise Unknown standard identity code. Indicates a symbol that as been evaluated but not - * identified for exercise purposes. + * identified for exercise purposes. */ final String STANDARD_IDENTITY_EXERCISE_UNKNOWN = "W"; /** - * The MIL-STD-2525 Faker standard identity code. Indicates a friendly symbol acting as hostile for exercise + * The MIL-STD-2525 Faker standard identity code. Indicates a friendly symbol acting as hostile for exercise * purposes. See MIL-STD-2525C section 3.2.12 (page 8). */ final String STANDARD_IDENTITY_FAKER = "K"; @@ -1006,22 +1104,24 @@ public interface SymbologyConstants * See MIL-STD-2525C section 3.2.49 (page 10). */ final String STANDARD_IDENTITY_UNKNOWN = "U"; - /** List containing all recognized MIL-STD-2525 standard identity codes. */ + /** + * List containing all recognized MIL-STD-2525 standard identity codes. + */ final List STANDARD_IDENTITY_ALL = Arrays.asList( - STANDARD_IDENTITY_PENDING, - STANDARD_IDENTITY_UNKNOWN, - STANDARD_IDENTITY_FRIEND, - STANDARD_IDENTITY_NEUTRAL, - STANDARD_IDENTITY_HOSTILE, - STANDARD_IDENTITY_ASSUMED_FRIEND, - STANDARD_IDENTITY_SUSPECT, - STANDARD_IDENTITY_EXERCISE_PENDING, - STANDARD_IDENTITY_EXERCISE_UNKNOWN, - STANDARD_IDENTITY_EXERCISE_FRIEND, - STANDARD_IDENTITY_EXERCISE_NEUTRAL, - STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND, - STANDARD_IDENTITY_JOKER, - STANDARD_IDENTITY_FAKER + STANDARD_IDENTITY_PENDING, + STANDARD_IDENTITY_UNKNOWN, + STANDARD_IDENTITY_FRIEND, + STANDARD_IDENTITY_NEUTRAL, + STANDARD_IDENTITY_HOSTILE, + STANDARD_IDENTITY_ASSUMED_FRIEND, + STANDARD_IDENTITY_SUSPECT, + STANDARD_IDENTITY_EXERCISE_PENDING, + STANDARD_IDENTITY_EXERCISE_UNKNOWN, + STANDARD_IDENTITY_EXERCISE_FRIEND, + STANDARD_IDENTITY_EXERCISE_NEUTRAL, + STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND, + STANDARD_IDENTITY_JOKER, + STANDARD_IDENTITY_FAKER ); /** @@ -1030,13 +1130,17 @@ public interface SymbologyConstants *
              • STATIC
              • DYNAMIC
              */ final String STATIC_DYNAMIC = "gov.nasa.worldwind.symbology.StaticDynamic"; - /** The MIL-STD-2525 Static, used by symbols belonging to the METOC scheme. */ + /** + * The MIL-STD-2525 Static, used by symbols belonging to the METOC scheme. + */ final String STATIC = "S-"; - /** The MIL-STD-2525 Dynamic, used by symbols belonging to the METOC scheme. */ + /** + * The MIL-STD-2525 Dynamic, used by symbols belonging to the METOC scheme. + */ final String DYNAMIC = "-D"; final List STATIC_DYNAMIC_ALL = Arrays.asList( - STATIC, - DYNAMIC + STATIC, + DYNAMIC ); /** @@ -1047,9 +1151,9 @@ public interface SymbologyConstants * tables III and III-2 (pages 18-17). The recognized values depend on the specific MIL-STD-2525 symbology scheme * the symbol belongs to, and are defined in each appendix of the MIL-STD-2525C specification: *

              - * Warfighting, Signals Intelligence, Stability Operations
              See MIL-STD-2525C section - * A.5.2.1.d (page 51), table A-I (page 51), section D.5.2.1.d (page 964), table D-I (page 964), section E.5.2.1.d - * (page 991), and table E-I (page 991). + * Warfighting, Signals Intelligence, Stability Operations
              See MIL-STD-2525C section A.5.2.1.d + * (page 51), table A-I (page 51), section D.5.2.1.d (page 964), table D-I (page 964), section E.5.2.1.d (page 991), + * and table E-I (page 991). *

              • STATUS_ANTICIPATED
              • STATUS_PRESENT
              • STATUS_PRESENT_FULLY_CAPABLE
              • *
              • STATUS_PRESENT_DAMAGED
              • STATUS_PRESENT_DESTROYED
              • STATUS_PRESENT_FULL_TO_CAPACITY
              *

              @@ -1066,7 +1170,9 @@ public interface SymbologyConstants * exist at the symbol's location. See MIL-STD-2525C section 5.3.1.4 (pages 17-18). */ final String STATUS_ANTICIPATED = "A"; - /** The MIL-STD-2525 Known status code. See MIL-STD-2525C table B-I (page 305). */ + /** + * The MIL-STD-2525 Known status code. See MIL-STD-2525C table B-I (page 305). + */ final String STATUS_KNOWN = "K"; /** * The MIL-STD-2525 Present/Fully Capable status code. Indicates a symbol who's represented object currently exists @@ -1098,40 +1204,42 @@ public interface SymbologyConstants * symbol's location. See MIL-STD-2525C section 5.3.1.4 (pages 17-18). */ final String STATUS_SUSPECTED = "S"; - /** List containing all recognized MIL-STD-2525 status codes. */ + /** + * List containing all recognized MIL-STD-2525 status codes. + */ final List STATUS_ALL = Arrays.asList( - // UEI, SIGINT, SO, and EM status codes. - STATUS_ANTICIPATED, - STATUS_PRESENT, - STATUS_FULLY_CAPABLE, - STATUS_DAMAGED, - STATUS_DESTROYED, - STATUS_FULL_TO_CAPACITY, - // Tactical Graphics and METOC status codes (ANTICIPATED and PRESENT already included). - STATUS_SUSPECTED, - STATUS_KNOWN + // UEI, SIGINT, SO, and EM status codes. + STATUS_ANTICIPATED, + STATUS_PRESENT, + STATUS_FULLY_CAPABLE, + STATUS_DAMAGED, + STATUS_DESTROYED, + STATUS_FULL_TO_CAPACITY, + // Tactical Graphics and METOC status codes (ANTICIPATED and PRESENT already included). + STATUS_SUSPECTED, + STATUS_KNOWN ); /** * List containing all recognized MIL-STD-2525 status codes for the Warfighting (UEI), Signals Intelligence * (SIGINT), Stability Operations (SO), and Emergency Management schemes. TODO: EM scheme contradicts itself. */ final List STATUS_ALL_UEI_SIGINT_SO_EM = Arrays.asList( - STATUS_ANTICIPATED, - STATUS_PRESENT, - STATUS_FULLY_CAPABLE, - STATUS_DAMAGED, - STATUS_DESTROYED, - STATUS_FULL_TO_CAPACITY + STATUS_ANTICIPATED, + STATUS_PRESENT, + STATUS_FULLY_CAPABLE, + STATUS_DAMAGED, + STATUS_DESTROYED, + STATUS_FULL_TO_CAPACITY ); /** * List containing all recognized MIL-STD-2525 status codes for the Tactical Graphics and Meteorological and * Oceanographic (METOC) scheme. */ final List STATUS_ALL_TACTICAL_GRAPHICS_METOC = Arrays.asList( - STATUS_ANTICIPATED, - STATUS_SUSPECTED, - STATUS_PRESENT, - STATUS_KNOWN + STATUS_ANTICIPATED, + STATUS_SUSPECTED, + STATUS_PRESENT, + STATUS_KNOWN ); /** diff --git a/src/gov/nasa/worldwind/symbology/TacticalCircle.java b/src/gov/nasa/worldwind/symbology/TacticalCircle.java index ecb9b70add..2d32c33f91 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalCircle.java +++ b/src/gov/nasa/worldwind/symbology/TacticalCircle.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; /** @@ -13,10 +12,10 @@ * @author pabercrombie * @version $Id: TacticalCircle.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TacticalGraphicFactory#createCircle(String, gov.nasa.worldwind.geom.Position, double, - * gov.nasa.worldwind.avlist.AVList) + * gov.nasa.worldwind.avlist.AVList) */ -public interface TacticalCircle extends TacticalPoint -{ +public interface TacticalCircle extends TacticalPoint { + /** * Indicates the radius of this circle. Calling this method is equivalent to calling * getModifier(SymbologyConstants.DISTANCE ). diff --git a/src/gov/nasa/worldwind/symbology/TacticalGraphic.java b/src/gov/nasa/worldwind/symbology/TacticalGraphic.java index dca365192b..784da28543 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalGraphic.java +++ b/src/gov/nasa/worldwind/symbology/TacticalGraphic.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.Movable; @@ -15,26 +14,26 @@ /** * TacticalGraphic provides a common interface for displaying a graphic from a symbology set. A graphic can be an icon * that is drawn a geographic position, a vector graphic that is positioned using one or more control points, or a line - * or polygon that is styled according to the symbol set's specification. See the TacticalGraphic - * Tutorial + * or polygon that is styled according to the symbol set's specification. See the TacticalGraphic + * Tutorial * for instructions on using TacticalGraphic in an application. *

              - * See the {@link gov.nasa.worldwindx.examples.symbology.Symbology} and {@link gov.nasa.worldwindx.examples.symbology.TacticalGraphics} - * example applications for examples of how to use tactical graphics. + * See the {@link gov.nasa.worldwindx.examples.symbology.Symbology} and + * {@link gov.nasa.worldwindx.examples.symbology.TacticalGraphics} example applications for examples of how to use + * tactical graphics. *

              Construction

              *

              * TacticalGraphics are typically created by an instance of {@link TacticalGraphicFactory}. Each graphic within a symbol * set is identified by a string identifier. The format of this identifier depends on the symbol set. For example, a * MIL-STD-2525 Symbol Identification Code (SIDC) is a string of 15 characters. *

              - * You will need to instantiate the appropriate factory for the symbol set that you intend to use. For example, {@link + * You will need to instantiate the appropriate factory for the symbol set that you intend to use. For example, {@link * gov.nasa.worldwind.symbology.milstd2525.MilStd2525GraphicFactory} creates graphics for the MIL-STD-2525 symbology * set. *

              * The TacticalGraphic interface provides access to settings common to all tactical graphics. TacticalGraphic extends * the {@link Renderable} interface, so you can add a TacticalGraphic directly to a {@link - * gov.nasa.worldwind.layers.RenderableLayer}. Here's an example of creating a graphic from the MIL-STD-2525 symbol - * set: + * gov.nasa.worldwind.layers.RenderableLayer}. Here's an example of creating a graphic from the MIL-STD-2525 symbol set: *

                * // Create a graphic factory for MIL-STD-2525
                * TacticalGraphicFactory factory = new MilStd2525GraphicFactory();
              @@ -65,10 +64,10 @@
                * wwd.redraw();
                * 
              *

              - * The symbol identifier ({@code GHGPGLP----AUSX}) tells the factory what type of graphic to create, and how the - * graphic should be styled. In the example above we added a text modifier of "Alpha" to identify our shape. These - * parameters can be specified using a parameter list when the TacticalGraphic is created, as shown above. They can also - * be set after creation using setters in the TacticalGraphic interface. + * The symbol identifier ({@code GHGPGLP----AUSX}) tells the factory what type of graphic to create, and how the graphic + * should be styled. In the example above we added a text modifier of "Alpha" to identify our shape. These parameters + * can be specified using a parameter list when the TacticalGraphic is created, as shown above. They can also be set + * after creation using setters in the TacticalGraphic interface. *

              Modifiers

              *

              * Many graphics support text or graphic modifiers. Each modifier is identified by a String key. The set of possible @@ -95,7 +94,7 @@ *

              Position

              *

              * Each tactical graphic is positioned by one or more control points. How many points are required depends on the type - * of graphic. A point graphic will only require one point. A more complex shape may require three or four, and a line + * of graphic. A point graphic will only require one point. A more complex shape may require three or four, and a line * or area may allow any number. *

              * Here is an example of how to create a point graphic in the MIL-STD-2525 symbol set: @@ -133,8 +132,8 @@ * @version $Id: TacticalGraphic.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TacticalGraphicFactory */ -public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVList -{ +public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVList { + /** * Indicates whether this graphic is drawn when in view. * @@ -162,7 +161,7 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * Specifies the value of a text or graphic modifier. * * @param modifier Key that identifies the modifier to set. The possible modifiers depends on the symbol set. - * @param value New value for the modifier. + * @param value New value for the modifier. */ void setModifier(String modifier, Object value); @@ -198,8 +197,7 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * Indicates whether or not the graphic should display its location as a text modifier. Not all graphics support the * location modifier. * - * @return true if the graphic will display the location modifier. Note that not all graphics support this - * modifier. + * @return true if the graphic will display the location modifier. Note that not all graphics support this modifier. */ boolean isShowLocation(); @@ -208,7 +206,7 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * location modifier. Setting showLocation on a graphic that does not support the modifier will have no effect. * * @param show true if the graphic will display the location modifier. Note that not all graphics support this - * modifier. + * modifier. */ void setShowLocation(boolean show); @@ -217,8 +215,8 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * See comments on {@link #setShowHostileIndicator(boolean) setShowHostileIndicator} for more information. * * @return true if an indicator may be drawn when this graphic represents a hostile entity, if supported by the - * graphic implementation. Note that some graphics may not display an indicator, even when representing a - * hostile entity. + * graphic implementation. Note that some graphics may not display an indicator, even when representing a hostile + * entity. */ boolean isShowHostileIndicator(); @@ -228,8 +226,8 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * and may not apply to all graphics in the symbol set. * * @param show true if this graphic should display an indicator when this graphic represents a hostile entity and - * the graphic implementation supports such an indicator. Note that some graphics may not display an - * indicator, even when representing a hostile entity. + * the graphic implementation supports such an indicator. Note that some graphics may not display an indicator, even + * when representing a hostile entity. */ void setShowHostileIndicator(boolean show); @@ -265,7 +263,7 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * Indicates the positions of the control points that place and orient the graphic. * * @return positions that orient the graphic. How many positions are returned depends on the type of graphic. Some - * graphics require only a single position, others require many. + * graphics require only a single position, others require many. */ Iterable getPositions(); @@ -273,9 +271,8 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * Specifies the positions of the control points that place and orient the graphic. * * @param positions Positions that orient the graphic. How many positions are returned depends on the type of - * graphic. Some graphics require only a single position, others require many. The positions must - * be specified in the same order as the control points defined by the symbology set's template for - * this type of graphic. + * graphic. Some graphics require only a single position, others require many. The positions must be specified in + * the same order as the control points defined by the symbology set's template for this type of graphic. */ void setPositions(Iterable positions); @@ -310,7 +307,7 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * interpreted. * * @param attributes Attributes to apply to the graphic when it is highlighted. May be null, in which default - * attributes are used. + * attributes are used. */ void setHighlightAttributes(TacticalGraphicAttributes attributes); @@ -340,7 +337,7 @@ public interface TacticalGraphic extends Renderable, Highlightable, Movable, AVL * object returned during picking. If null, the graphic itself is the pickable object returned during picking. * * @return the object used as the pickable object returned during picking, or null to indicate the the graphic is - * returned during picking. + * returned during picking. */ Object getDelegateOwner(); diff --git a/src/gov/nasa/worldwind/symbology/TacticalGraphicAttributes.java b/src/gov/nasa/worldwind/symbology/TacticalGraphicAttributes.java index c600edc397..08b164c32d 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalGraphicAttributes.java +++ b/src/gov/nasa/worldwind/symbology/TacticalGraphicAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.render.Material; @@ -32,8 +31,8 @@ * @author pabercrombie * @version $Id: TacticalGraphicAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TacticalGraphicAttributes -{ +public interface TacticalGraphicAttributes { + /** * Returns a new TacticalGraphicAttributes instance of the same type as this TacticalGraphicAttributes who's * properties are configured exactly as this TacticalGraphicAttributes. diff --git a/src/gov/nasa/worldwind/symbology/TacticalGraphicFactory.java b/src/gov/nasa/worldwind/symbology/TacticalGraphicFactory.java index 6cc07eacf1..1f241523cf 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalGraphicFactory.java +++ b/src/gov/nasa/worldwind/symbology/TacticalGraphicFactory.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.avlist.AVList; @@ -28,8 +27,8 @@ * @version $Id: TacticalGraphicFactory.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TacticalGraphic */ -public interface TacticalGraphicFactory -{ +public interface TacticalGraphicFactory { + /** * Create a tactical graphic positioned by more than one control point. This method is general purpose, and may be * used to create any type of graphic. The other creation methods in the factory (for example, {@link @@ -37,12 +36,12 @@ public interface TacticalGraphicFactory * are provided for convenience, and may be used to specific categories of graphics. * * @param symbolIdentifier Identifier for the symbol within its symbol set. - * @param positions Control points to use to place the graphic. How many points are required depends on the - * type of graphic. - * @param modifiers Modifiers to apply to the graphic. + * @param positions Control points to use to place the graphic. How many points are required depends on the type of + * graphic. + * @param modifiers Modifiers to apply to the graphic. * * @return A new TacticalGraphic configured to render at the position indicated, or {@code null} if no graphic can - * be created for the given symbol identifier. + * be created for the given symbol identifier. */ TacticalGraphic createGraphic(String symbolIdentifier, Iterable positions, AVList modifiers); @@ -50,11 +49,11 @@ public interface TacticalGraphicFactory * Create a tactical graphic positioned by a single control point. * * @param symbolIdentifier Identifier for the symbol within its symbol set. - * @param position Control point to use to place the graphic. - * @param modifiers Modifiers to apply to the graphic. + * @param position Control point to use to place the graphic. + * @param modifiers Modifiers to apply to the graphic. * * @return A new TacticalGraphic configured to render at the position indicated, or {@code null} if no graphic can - * be created for the given symbol identifier. + * be created for the given symbol identifier. */ TacticalPoint createPoint(String symbolIdentifier, Position position, AVList modifiers); @@ -62,12 +61,12 @@ public interface TacticalGraphicFactory * Create a circular graphic. * * @param symbolIdentifier Identifier for the symbol within its symbol set. - * @param center The position of the center of the circle. - * @param radius The radius of the circle, in meters. - * @param modifiers Modifiers to apply to the graphic. + * @param center The position of the center of the circle. + * @param radius The radius of the circle, in meters. + * @param modifiers Modifiers to apply to the graphic. * * @return A new graphic configured to render at the position indicated, or {@code null} if no graphic can be - * created for the given symbol identifier. + * created for the given symbol identifier. * * @throws IllegalArgumentException if {@code symbolIdentifier} does not describe a circular graphic. */ @@ -77,12 +76,12 @@ public interface TacticalGraphicFactory * Create a graphic with four sides. * * @param symbolIdentifier Identifier for the symbol within its symbol set. - * @param positions Control points to use to place the graphic. How many points are required depends on the - * type of graphic. - * @param modifiers Modifiers to apply to the graphic. + * @param positions Control points to use to place the graphic. How many points are required depends on the type of + * graphic. + * @param modifiers Modifiers to apply to the graphic. * * @return A new graphic configured to render at the position indicated, or {@code null} if no graphic can be - * created for the given symbol identifier. + * created for the given symbol identifier. * * @throws IllegalArgumentException if {@code symbolIdentifier} does not describe a quad graphic. */ @@ -92,16 +91,16 @@ public interface TacticalGraphicFactory * Create a route graphic. A route is composed of point graphics connected by lines. * * @param symbolIdentifier Identifier for the symbol within its symbol set. - * @param controlPoints Graphics to place at the points along the route. - * @param modifiers Modifiers to apply to the graphic. + * @param controlPoints Graphics to place at the points along the route. + * @param modifiers Modifiers to apply to the graphic. * * @return A new graphic configured to render at the position indicated, or {@code null} if no graphic can be - * created for the given symbol identifier. + * created for the given symbol identifier. * * @throws IllegalArgumentException if {@code symbolIdentifier} does not describe a route graphic. */ TacticalRoute createRoute(String symbolIdentifier, Iterable controlPoints, - AVList modifiers); + AVList modifiers); /** * Determines if this factory can create a graphic for a given symbol identifier. @@ -109,7 +108,7 @@ TacticalRoute createRoute(String symbolIdentifier, Iterableopacity is less than 0.0 or greater than 1.0. */ - public void setOpacity(double opacity) - { - if (opacity < 0 || opacity > 1) - { + public void setOpacity(double opacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -467,8 +488,7 @@ public void setOpacity(double opacity) * * @return the opacity of the interior as a floating-point value from 0.0 to 1.0. */ - public double getInteriorOpacity() - { + public double getInteriorOpacity() { return this.interiorOpacity; } @@ -481,10 +501,8 @@ public double getInteriorOpacity() * * @throws IllegalArgumentException if opacity is less than 0.0 or greater than 1.0. */ - public void setInteriorOpacity(double interiorOpacity) - { - if (opacity < 0 || opacity > 1) - { + public void setInteriorOpacity(double interiorOpacity) { + if (opacity < 0 || opacity > 1) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -499,8 +517,7 @@ public void setInteriorOpacity(double interiorOpacity) * * @return Position used to orient the label. May be null. */ - public Position getOrientationPosition() - { + public Position getOrientationPosition() { return this.orientationPosition; } @@ -510,8 +527,7 @@ public Position getOrientationPosition() * * @param orientationPosition Draw label oriented toward this position. */ - public void setOrientationPosition(Position orientationPosition) - { + public void setOrientationPosition(Position orientationPosition) { this.orientationPosition = orientationPosition; } @@ -522,8 +538,7 @@ public void setOrientationPosition(Position orientationPosition) * * @see #setInsets(java.awt.Insets) */ - public Insets getInsets() - { + public Insets getInsets() { return this.insets; } @@ -535,10 +550,8 @@ public Insets getInsets() * @throws IllegalArgumentException if insets is null. * @see #getInsets() */ - public void setInsets(Insets insets) - { - if (insets == null) - { + public void setInsets(Insets insets) { + if (insets == null) { String message = Logging.getMessage("nullValue.InsetsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -553,8 +566,7 @@ public void setInsets(Insets insets) * * @return the effect used for text rendering */ - public String getEffect() - { + public String getEffect() { return this.effect; } @@ -564,10 +576,8 @@ public String getEffect() * * @param effect the effect to use for text rendering */ - public void setEffect(String effect) - { - if (effect == null) - { + public void setEffect(String effect) { + if (effect == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -583,8 +593,7 @@ public void setEffect(String effect) * @return the object used as the pickable object returned during picking, or null to indicate the the label is * returned during picking. */ - public Object getDelegateOwner() - { + public Object getDelegateOwner() { return this.delegateOwner; } @@ -594,8 +603,7 @@ public Object getDelegateOwner() * * @param owner the object to use as the pickable object returned during picking, or null to return the label. */ - public void setDelegateOwner(Object owner) - { + public void setDelegateOwner(Object owner) { this.delegateOwner = owner; } @@ -606,8 +614,7 @@ public void setDelegateOwner(Object owner) * * @see #setEnableBatchPicking(boolean) */ - public boolean isEnableBatchPicking() - { + public boolean isEnableBatchPicking() { return this.enableBatchPicking; } @@ -620,8 +627,7 @@ public boolean isEnableBatchPicking() * * @param enableBatchPicking true to enable batch rendering, otherwise false. */ - public void setEnableBatchPicking(boolean enableBatchPicking) - { + public void setEnableBatchPicking(boolean enableBatchPicking) { this.enableBatchPicking = enableBatchPicking; } @@ -632,8 +638,7 @@ public void setEnableBatchPicking(boolean enableBatchPicking) * * @see #setEnableBatchRendering(boolean) */ - public boolean isEnableBatchRendering() - { + public boolean isEnableBatchRendering() { return this.enableBatchRendering; } @@ -643,8 +648,7 @@ public boolean isEnableBatchRendering() * * @param enableBatchRendering true to enable batch rendering, otherwise false. */ - public void setEnableBatchRendering(boolean enableBatchRendering) - { + public void setEnableBatchRendering(boolean enableBatchRendering) { this.enableBatchRendering = enableBatchRendering; } @@ -659,10 +663,8 @@ public void setEnableBatchRendering(boolean enableBatchRendering) * * @throws IllegalArgumentException if dc is null. */ - public Rectangle getBounds(DrawContext dc) - { - if (dc == null) - { + public Rectangle getBounds(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -673,15 +675,13 @@ public Rectangle getBounds(DrawContext dc) return this.thisFramesOrderedLabel.screenExtent; } - protected void computeGeometryIfNeeded(DrawContext dc) - { + protected void computeGeometryIfNeeded(DrawContext dc) { // Re-use rendering state values already calculated this frame. If the screenExtent is null, recompute even if // the timestamp is the same. This prevents using a stale position if the application calls setPosition and // getBounds multiple times before the label is rendered. if (dc.getFrameTimeStamp() != this.frameTimeStamp || this.thisFramesOrderedLabel == null - || dc.isContinuous2DGlobe()) - { + || dc.isContinuous2DGlobe()) { OrderedLabel olbl = new OrderedLabel(); this.computeGeometry(dc, olbl); this.thisFramesOrderedLabel = olbl; @@ -694,22 +694,21 @@ protected void computeGeometryIfNeeded(DrawContext dc) * * @param dc the current DrawContext. */ - protected void computeBoundsIfNeeded(DrawContext dc) - { + protected void computeBoundsIfNeeded(DrawContext dc) { // Do not compute bounds if they are available. Computing text bounds is expensive, so only do this // calculation if necessary. - if (this.bounds != null) + if (this.bounds != null) { return; + } TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - this.getFont()); + this.getFont()); int width = 0; int maxLineHeight = 0; this.lineBounds = new Rectangle2D[this.lines.length]; - for (int i = 0; i < this.lines.length; i++) - { + for (int i = 0; i < this.lines.length; i++) { Rectangle2D lineBounds = textRenderer.getBounds(lines[i]); width = (int) Math.max(lineBounds.getWidth(), width); @@ -722,21 +721,21 @@ protected void computeBoundsIfNeeded(DrawContext dc) // Compute final height using maxLineHeight and number of lines this.bounds = new Rectangle(this.lines.length, maxLineHeight, width, - this.lines.length * maxLineHeight + this.lines.length * this.lineSpacing); + this.lines.length * maxLineHeight + this.lines.length * this.lineSpacing); } /** * Compute the label's screen position from its geographic position. * - * @param dc Current draw context. + * @param dc Current draw context. * @param olbl The ordered label to compute geometry for. */ - protected void computeGeometry(DrawContext dc, OrderedLabel olbl) - { + protected void computeGeometry(DrawContext dc, OrderedLabel olbl) { // Project the label position onto the viewport Position pos = this.getPosition(); - if (pos == null) + if (pos == null) { return; + } olbl.placePoint = dc.computeTerrainPoint(pos.getLatitude(), pos.getLongitude(), 0); olbl.screenPlacePoint = dc.getView().project(olbl.placePoint); @@ -744,11 +743,10 @@ protected void computeGeometry(DrawContext dc, OrderedLabel olbl) olbl.eyeDistance = olbl.placePoint.distanceTo3(dc.getView().getEyePoint()); boolean orientationReversed = false; - if (this.orientationPosition != null) - { + if (this.orientationPosition != null) { // Project the orientation point onto the screen Vec4 orientationPlacePoint = dc.computeTerrainPoint(this.orientationPosition.getLatitude(), - this.orientationPosition.getLongitude(), 0); + this.orientationPosition.getLongitude(), 0); Vec4 orientationScreenPoint = dc.getView().project(orientationPlacePoint); olbl.rotation = this.computeRotation(olbl.screenPlacePoint, orientationScreenPoint); @@ -767,16 +765,14 @@ protected void computeGeometry(DrawContext dc, OrderedLabel olbl) // If a rotation is applied to the text, then rotate the offset as well. An offset in the x direction // will move the text along the orientation line, and a offset in the y direction will move the text // perpendicular to the orientation line. - if (olbl.rotation != null) - { + if (olbl.rotation != null) { double dy = offsetPoint.getY(); // If the orientation is reversed we need to adjust the vertical offset to compensate for the flipped // text. For example, if the offset normally aligns the top of the text with the place point then without // this adjustment the bottom of the text would align with the place point when the orientation is // reversed. - if (orientationReversed) - { + if (orientationReversed) { dy = -(dy + this.bounds.getHeight()); } @@ -798,63 +794,58 @@ protected void computeGeometry(DrawContext dc, OrderedLabel olbl) /** * Determine if this label intersects the view or pick frustum. * - * @param dc Current draw context. + * @param dc Current draw context. * @param olbl The ordered label to intersect. * * @return True if this label intersects the active frustum (view or pick). Otherwise false. */ - protected boolean intersectsFrustum(DrawContext dc, OrderedLabel olbl) - { + protected boolean intersectsFrustum(DrawContext dc, OrderedLabel olbl) { View view = dc.getView(); Frustum frustum = view.getFrustumInModelCoordinates(); // Test the label's model coordinate point against the near and far clipping planes. if (olbl.placePoint != null - && (frustum.getNear().distanceTo(olbl.placePoint) < 0 - || frustum.getFar().distanceTo(olbl.placePoint) < 0)) - { + && (frustum.getNear().distanceTo(olbl.placePoint) < 0 + || frustum.getFar().distanceTo(olbl.placePoint) < 0)) { return false; } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(olbl.screenExtent); - else + } else { return view.getViewport().intersects(olbl.screenExtent); + } } /** * Compute the amount of rotation to apply to a label in order to keep it oriented toward its orientation position. * - * @param screenPoint Geographic position of the text, projected onto the screen. + * @param screenPoint Geographic position of the text, projected onto the screen. * @param orientationScreenPoint Orientation position, projected onto the screen. * * @return The rotation angle to apply when drawing the label. */ - protected Angle computeRotation(Vec4 screenPoint, Vec4 orientationScreenPoint) - { + protected Angle computeRotation(Vec4 screenPoint, Vec4 orientationScreenPoint) { // Determine delta between the orientation position and the label position double deltaX = screenPoint.x - orientationScreenPoint.x; double deltaY = screenPoint.y - orientationScreenPoint.y; - if (deltaX != 0) - { + if (deltaX != 0) { double angle = Math.atan(deltaY / deltaX); return Angle.fromRadians(angle); - } - else - { + } else { return Angle.POS90; // Vertical label } } - /** {@inheritDoc} */ - public void render(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { // This render method is called twice during frame generation. It's first called as a Renderable // during Renderable picking. It's called again during normal rendering. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -863,26 +854,21 @@ public void render(DrawContext dc) this.makeOrderedRenderable(dc); } - public void pick(DrawContext dc, Point pickPoint, OrderedLabel olbl) - { + public void pick(DrawContext dc, Point pickPoint, OrderedLabel olbl) { // This method is called only when ordered renderables are being drawn. // Arg checked within call to render. - if (dc == null) - { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.pickSupport.clearPickList(); - try - { + try { this.pickSupport.beginPicking(dc); this.drawOrderedRenderable(dc, olbl); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, pickPoint, this.pickLayer); } @@ -893,43 +879,43 @@ public void pick(DrawContext dc, Point pickPoint, OrderedLabel olbl) * * @param dc the current draw context. */ - protected void makeOrderedRenderable(DrawContext dc) - { - if (this.lines == null || this.position == null) + protected void makeOrderedRenderable(DrawContext dc) { + if (this.lines == null || this.position == null) { return; + } this.computeGeometryIfNeeded(dc); // Don't draw if beyond the horizon. double horizon = dc.getView().getHorizonDistance(); - if (!dc.is2DGlobe() && this.thisFramesOrderedLabel.eyeDistance > horizon) + if (!dc.is2DGlobe() && this.thisFramesOrderedLabel.eyeDistance > horizon) { return; + } - if (this.intersectsFrustum(dc, this.thisFramesOrderedLabel)) + if (this.intersectsFrustum(dc, this.thisFramesOrderedLabel)) { dc.addOrderedRenderable(this.thisFramesOrderedLabel); + } - if (dc.isPickingMode()) + if (dc.isPickingMode()) { this.pickLayer = dc.getCurrentLayer(); + } } /** * Draws the graphic as an ordered renderable. * - * @param dc the current draw context. + * @param dc the current draw context. * @param olbl The ordered label to draw. */ - protected void drawOrderedRenderable(DrawContext dc, OrderedLabel olbl) - { + protected void drawOrderedRenderable(DrawContext dc, OrderedLabel olbl) { this.beginDrawing(dc); - try - { + try { this.doDrawOrderedRenderable(dc, this.pickSupport, olbl); - if (this.isEnableBatchRendering()) + if (this.isEnableBatchRendering()) { this.drawBatched(dc, olbl); - } - finally - { + } + } finally { this.endDrawing(dc); } } @@ -937,19 +923,15 @@ protected void drawOrderedRenderable(DrawContext dc, OrderedLabel olbl) /** * Draw this label during ordered rendering. * - * @param dc Current draw context. + * @param dc Current draw context. * @param pickSupport Support object used during picking. - * @param olbl The ordered label to draw. + * @param olbl The ordered label to draw. */ - protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickSupport, OrderedLabel olbl) - { + protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickSupport, OrderedLabel olbl) { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.doPick(dc, pickSupport, olbl); - } - else - { + } else { this.drawText(dc, textRenderer, olbl); } } @@ -959,12 +941,11 @@ protected void doDrawOrderedRenderable(DrawContext dc, PickSupport pickSupport, * * @param dc the current draw context. */ - protected void beginDrawing(DrawContext dc) - { + protected void beginDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - int attrMask = - GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask and depth func + int attrMask + = GL2.GL_DEPTH_BUFFER_BIT // for depth test, depth mask and depth func | GL2.GL_TRANSFORM_BIT // for modelview and perspective | GL2.GL_VIEWPORT_BIT // for depth range | GL2.GL_CURRENT_BIT // for current color @@ -974,8 +955,7 @@ protected void beginDrawing(DrawContext dc) this.BEogsh.pushAttrib(gl, attrMask); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glEnable(GL.GL_BLEND); OGLUtil.applyBlending(gl, false); } @@ -996,8 +976,7 @@ protected void beginDrawing(DrawContext dc) * * @param dc the current draw context. */ - protected void endDrawing(DrawContext dc) - { + protected void endDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. this.BEogsh.pop(gl); @@ -1006,30 +985,28 @@ protected void endDrawing(DrawContext dc) /** * Draw labels for picking. * - * @param dc Current draw context. + * @param dc Current draw context. * @param pickSupport the PickSupport instance to be used. - * @param olbl The ordered label to pick. + * @param olbl The ordered label to pick. */ - protected void doPick(DrawContext dc, PickSupport pickSupport, OrderedLabel olbl) - { + protected void doPick(DrawContext dc, PickSupport pickSupport, OrderedLabel olbl) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Angle heading = olbl.rotation; double headingDegrees; - if (heading != null) + if (heading != null) { headingDegrees = heading.degrees; - else + } else { headingDegrees = 0; + } int x = olbl.screenPoint.x; int y = olbl.screenPoint.y; boolean matrixPushed = false; - try - { - if (headingDegrees != 0) - { + try { + if (headingDegrees != 0) { gl.glPushMatrix(); matrixPushed = true; @@ -1038,17 +1015,17 @@ protected void doPick(DrawContext dc, PickSupport pickSupport, OrderedLabel olbl gl.glTranslated(-x, -y, 0); } - for (int i = 0; i < this.lines.length; i++) - { + for (int i = 0; i < this.lines.length; i++) { Rectangle2D bounds = this.lineBounds[i]; double width = bounds.getWidth(); double height = bounds.getHeight(); x = olbl.screenPoint.x; - if (this.textAlign.equals(AVKey.CENTER)) + if (this.textAlign.equals(AVKey.CENTER)) { x = x - (int) (width / 2.0); - else if (this.textAlign.equals(AVKey.RIGHT)) + } else if (this.textAlign.equals(AVKey.RIGHT)) { x = x - (int) width; + } y -= this.lineHeight; Color color = dc.getUniquePickColor(); @@ -1059,27 +1036,21 @@ else if (this.textAlign.equals(AVKey.RIGHT)) // Draw line rectangle gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); - try - { + try { gl.glBegin(GL2.GL_POLYGON); gl.glVertex3d(x, y, 0); gl.glVertex3d(x + width - 1, y, 0); gl.glVertex3d(x + width - 1, y + height - 1, 0); gl.glVertex3d(x, y + height - 1, 0); gl.glVertex3d(x, y, 0); - } - finally - { + } finally { gl.glEnd(); } y -= this.lineSpacing; } - } - finally - { - if (matrixPushed) - { + } finally { + if (matrixPushed) { gl.glPopMatrix(); } } @@ -1089,30 +1060,28 @@ else if (this.textAlign.equals(AVKey.RIGHT)) * Draw the label's text. This method sets up the text renderer, and then calls {@link #doDrawText(TextRenderer, * gov.nasa.worldwind.symbology.TacticalGraphicLabel.OrderedLabel) doDrawText} to actually draw the text. * - * @param dc Current draw context. + * @param dc Current draw context. * @param textRenderer Text renderer. - * @param olbl The ordered label to draw. + * @param olbl The ordered label to draw. */ - protected void drawText(DrawContext dc, TextRenderer textRenderer, OrderedLabel olbl) - { + protected void drawText(DrawContext dc, TextRenderer textRenderer, OrderedLabel olbl) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Angle heading = olbl.rotation; double headingDegrees; - if (heading != null) + if (heading != null) { headingDegrees = heading.degrees; - else + } else { headingDegrees = 0; + } boolean matrixPushed = false; - try - { + try { int x = olbl.screenPoint.x; int y = olbl.screenPoint.y; - if (headingDegrees != 0) - { + if (headingDegrees != 0) { gl.glPushMatrix(); matrixPushed = true; @@ -1121,27 +1090,23 @@ protected void drawText(DrawContext dc, TextRenderer textRenderer, OrderedLabel gl.glTranslated(-x, -y, 0); } - if (this.isDrawInterior()) + if (this.isDrawInterior()) { this.drawInterior(dc, olbl); + } textRenderer.begin3DRendering(); - try - { + try { this.doDrawText(textRenderer, olbl); // Draw other labels that share the same text renderer configuration, if possible. - if (this.isEnableBatchRendering()) + if (this.isEnableBatchRendering()) { this.drawBatchedText(dc, textRenderer, olbl); - } - finally - { + } + } finally { textRenderer.end3DRendering(); } - } - finally - { - if (matrixPushed) - { + } finally { + if (matrixPushed) { gl.glPopMatrix(); } } @@ -1150,11 +1115,10 @@ protected void drawText(DrawContext dc, TextRenderer textRenderer, OrderedLabel /** * Render the label interior as a filled rectangle. * - * @param dc Current draw context. + * @param dc Current draw context. * @param olbl The ordered label to draw. */ - protected void drawInterior(DrawContext dc, OrderedLabel olbl) - { + protected void drawInterior(DrawContext dc, OrderedLabel olbl) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. double width = this.bounds.getWidth(); @@ -1165,10 +1129,11 @@ protected void drawInterior(DrawContext dc, OrderedLabel olbl) // Adjust x to account for text alignment int xAligned = x; - if (AVKey.CENTER.equals(textAlign)) + if (AVKey.CENTER.equals(textAlign)) { xAligned = x - (int) (width / 2); - else if (AVKey.RIGHT.equals(textAlign)) + } else if (AVKey.RIGHT.equals(textAlign)) { xAligned = x - (int) width; + } // We draw text top-down, so adjust y to compensate. int yAligned = (int) (y - height); @@ -1180,24 +1145,20 @@ else if (AVKey.RIGHT.equals(textAlign)) yAligned -= insets.bottom; height = height + insets.bottom + insets.top; - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Apply the frame background color and opacity if we're in normal rendering mode. Color color = this.computeBackgroundColor(this.getMaterial().getDiffuse()); gl.glColor4ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue(), - (byte) (this.interiorOpacity < 1 ? (int) (this.interiorOpacity * 255 + 0.5) : 255)); + (byte) (this.interiorOpacity < 1 ? (int) (this.interiorOpacity * 255 + 0.5) : 255)); } - try - { + try { // Draw a quad gl.glPushMatrix(); gl.glTranslated(xAligned, yAligned, 0); gl.glScaled(width, height, 1.0); dc.drawUnitQuad(); - } - finally - { + } finally { gl.glPopMatrix(); } } @@ -1206,10 +1167,9 @@ else if (AVKey.RIGHT.equals(textAlign)) * Draw the label's text. This method assumes that the text renderer context has already been set up. * * @param textRenderer renderer to use. - * @param olbl The ordered label to draw. + * @param olbl The ordered label to draw. */ - protected void doDrawText(TextRenderer textRenderer, OrderedLabel olbl) - { + protected void doDrawText(TextRenderer textRenderer, OrderedLabel olbl) { Color color = this.material.getDiffuse(); Color backgroundColor = this.computeBackgroundColor(color); float opacity = (float) this.getOpacity(); @@ -1218,8 +1178,7 @@ protected void doDrawText(TextRenderer textRenderer, OrderedLabel olbl) int y = olbl.screenPoint.y; float[] compArray = new float[3]; - if (AVKey.TEXT_EFFECT_SHADOW.equals(this.effect) && backgroundColor != null) - { + if (AVKey.TEXT_EFFECT_SHADOW.equals(this.effect) && backgroundColor != null) { backgroundColor.getRGBColorComponents(compArray); textRenderer.setColor(compArray[0], compArray[1], compArray[2], opacity); @@ -1231,25 +1190,23 @@ protected void doDrawText(TextRenderer textRenderer, OrderedLabel olbl) this.drawMultiLineText(textRenderer, x, y, olbl); } - protected void drawMultiLineText(TextRenderer textRenderer, int x, int y, OrderedLabel olbl) - { - if (this.lines == null) - { + protected void drawMultiLineText(TextRenderer textRenderer, int x, int y, OrderedLabel olbl) { + if (this.lines == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (int i = 0; i < this.lines.length; i++) - { + for (int i = 0; i < this.lines.length; i++) { String line = this.lines[i]; Rectangle2D bounds = this.lineBounds[i]; int xAligned = x; - if (this.textAlign.equals(AVKey.CENTER)) + if (this.textAlign.equals(AVKey.CENTER)) { xAligned = x - (int) (bounds.getWidth() / 2); - else if (this.textAlign.equals(AVKey.RIGHT)) + } else if (this.textAlign.equals(AVKey.RIGHT)) { xAligned = x - (int) (bounds.getWidth()); + } y -= this.lineHeight; textRenderer.draw3D(line, xAligned, y, 0, 1); @@ -1266,38 +1223,36 @@ else if (this.textAlign.equals(AVKey.RIGHT)) * text renderer configuration as this label, and this method attempts to draw as many labels as possible regardless * of the text renderer configuration of the subsequent labels. * - * @param dc the current draw context. + * @param dc the current draw context. * @param firstLabel the label drawn prior to calling this method. */ - protected void drawBatched(DrawContext dc, OrderedLabel firstLabel) - { + protected void drawBatched(DrawContext dc, OrderedLabel firstLabel) { // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - if (!dc.isPickingMode()) - { - while (nextItem != null && nextItem instanceof OrderedLabel) - { + if (!dc.isPickingMode()) { + while (nextItem != null && nextItem instanceof OrderedLabel) { OrderedLabel nextLabel = (OrderedLabel) nextItem; - if (!nextLabel.isEnableBatchRendering()) + if (!nextLabel.isEnableBatchRendering()) { break; + } dc.pollOrderedRenderables(); // take it off the queue nextLabel.doDrawOrderedRenderable(dc, this.pickSupport); nextItem = dc.peekOrderedRenderables(); } - } - else if (this.isEnableBatchPicking()) - { - while (nextItem != null && nextItem instanceof OrderedLabel) - { + } else if (this.isEnableBatchPicking()) { + while (nextItem != null && nextItem instanceof OrderedLabel) { OrderedLabel nextLabel = (OrderedLabel) nextItem; - if (!nextLabel.isEnableBatchRendering() || !nextLabel.isEnableBatchPicking()) + if (!nextLabel.isEnableBatchRendering() || !nextLabel.isEnableBatchPicking()) { break; + } if (nextLabel.getPickLayer() != firstLabel.getPickLayer()) // batch pick only within a single layer + { break; + } dc.pollOrderedRenderables(); // take it off the queue nextLabel.doDrawOrderedRenderable(dc, this.pickSupport); @@ -1315,33 +1270,32 @@ else if (this.isEnableBatchPicking()) * drawBatched} in that this method reuses the active text renderer context to draw as many labels as possible * without switching text renderer state. * - * @param dc the current draw context. + * @param dc the current draw context. * @param textRenderer Text renderer used to draw the label. - * @param firstLabel The first ordered renderable in the batch. + * @param firstLabel The first ordered renderable in the batch. */ - protected void drawBatchedText(DrawContext dc, TextRenderer textRenderer, OrderedLabel firstLabel) - { + protected void drawBatchedText(DrawContext dc, TextRenderer textRenderer, OrderedLabel firstLabel) { // Draw as many as we can in a batch to save ogl state switching. Object nextItem = dc.peekOrderedRenderables(); - if (!dc.isPickingMode()) - { - while (nextItem != null && nextItem instanceof OrderedLabel) - { + if (!dc.isPickingMode()) { + while (nextItem != null && nextItem instanceof OrderedLabel) { OrderedLabel nextLabel = (OrderedLabel) nextItem; - if (!nextLabel.isEnableBatchRendering()) + if (!nextLabel.isEnableBatchRendering()) { break; + } boolean sameFont = firstLabel.getFont().equals(nextLabel.getFont()); boolean sameRotation = (firstLabel.rotation == null && nextLabel.rotation == null) - || (firstLabel.rotation != null && firstLabel.rotation.equals(nextLabel.rotation)); + || (firstLabel.rotation != null && firstLabel.rotation.equals(nextLabel.rotation)); boolean drawInterior = nextLabel.isDrawInterior(); // We've already set up the text renderer state, so we can can't change the font or text rotation. // Also can't batch render if the next label needs an interior since that will require tearing down the // text renderer context. - if (!sameFont || !sameRotation || drawInterior) + if (!sameFont || !sameRotation || drawInterior) { break; + } dc.pollOrderedRenderables(); // take it off the queue nextLabel.doDrawText(textRenderer); @@ -1356,8 +1310,7 @@ protected void drawBatchedText(DrawContext dc, TextRenderer textRenderer, Ordere * * @return If a delegate owner is set, returns the delegate owner. Otherwise returns this label. */ - protected Object getPickedObject() - { + protected Object getPickedObject() { Object owner = this.getDelegateOwner(); return (owner != null) ? owner : this; } @@ -1368,32 +1321,31 @@ protected Object getPickedObject() * features on the surface then the extent will be the smallest screen rectangle that completely encloses the * rotated label. * - * @param x X coordinate at which to draw the label. - * @param y Y coordinate at which to draw the label. + * @param x X coordinate at which to draw the label. + * @param y Y coordinate at which to draw the label. * @param olbl The ordered label to compute extents for. * * @return The rectangle, in OGL screen coordinates (origin at bottom left corner), that is covered by the label. */ - protected Rectangle computeTextExtent(int x, int y, OrderedLabel olbl) - { + protected Rectangle computeTextExtent(int x, int y, OrderedLabel olbl) { double width = this.bounds.getWidth(); double height = this.bounds.getHeight(); String textAlign = this.getTextAlign(); int xAligned = x; - if (AVKey.CENTER.equals(textAlign)) + if (AVKey.CENTER.equals(textAlign)) { xAligned = x - (int) (width / 2); - else if (AVKey.RIGHT.equals(textAlign)) + } else if (AVKey.RIGHT.equals(textAlign)) { xAligned = x - (int) width; + } int yAligned = (int) (y - height); Rectangle screenRect = new Rectangle(xAligned, yAligned, (int) width, (int) height); // Compute bounds of the rotated rectangle, if there is a rotation angle. - if (olbl.rotation != null && olbl.rotation.degrees != 0) - { + if (olbl.rotation != null && olbl.rotation.degrees != 0) { screenRect = this.computeRotatedScreenExtent(screenRect, x, y, olbl.rotation); } @@ -1403,15 +1355,14 @@ else if (AVKey.RIGHT.equals(textAlign)) /** * Compute the bounding screen extent of a rotated rectangle. * - * @param rect Rectangle to rotate. - * @param x X coordinate of the rotation point. - * @param y Y coordinate of the rotation point. + * @param rect Rectangle to rotate. + * @param x X coordinate of the rotation point. + * @param y Y coordinate of the rotation point. * @param rotation Rotation angle. * * @return The smallest rectangle that completely contains {@code rect} when rotated by the specified angle. */ - protected Rectangle computeRotatedScreenExtent(Rectangle rect, int x, int y, Angle rotation) - { + protected Rectangle computeRotatedScreenExtent(Rectangle rect, int x, int y, Angle rotation) { Rectangle r = new Rectangle(rect); // Translate the rectangle to the rotation point. @@ -1427,8 +1378,7 @@ protected Rectangle computeRotatedScreenExtent(Rectangle rect, int x, int y, Ang // Rotate the rectangle Matrix rotationMatrix = Matrix.fromRotationZ(rotation); - for (int i = 0; i < corners.length; i++) - { + for (int i = 0; i < corners.length; i++) { corners[i] = corners[i].transformBy3(rotationMatrix); } @@ -1438,19 +1388,22 @@ protected Rectangle computeRotatedScreenExtent(Rectangle rect, int x, int y, Ang int maxX = -Integer.MAX_VALUE; int maxY = -Integer.MAX_VALUE; - for (Vec4 v : corners) - { - if (v.x > maxX) + for (Vec4 v : corners) { + if (v.x > maxX) { maxX = (int) v.x; + } - if (v.x < minX) + if (v.x < minX) { minX = (int) v.x; + } - if (v.y > maxY) + if (v.y > maxY) { maxY = (int) v.y; + } - if (v.y < minY) + if (v.y < minY) { minY = (int) v.y; + } } // Set bounds and translate the rectangle back to where it started. @@ -1467,14 +1420,14 @@ protected Rectangle computeRotatedScreenExtent(Rectangle rect, int x, int y, Ang * * @return A color that contrasts with {@code color}. */ - protected Color computeBackgroundColor(Color color) - { + protected Color computeBackgroundColor(Color color) { float[] colorArray = new float[4]; Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), colorArray); - if (colorArray[2] > 0.5) + if (colorArray[2] > 0.5) { return new Color(0, 0, 0, 0.7f); - else + } else { return new Color(1, 1, 1, 0.7f); + } } } diff --git a/src/gov/nasa/worldwind/symbology/TacticalGraphicUtil.java b/src/gov/nasa/worldwind/symbology/TacticalGraphicUtil.java index 80f8ee775b..faba590772 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalGraphicUtil.java +++ b/src/gov/nasa/worldwind/symbology/TacticalGraphicUtil.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.geom.*; @@ -19,21 +18,19 @@ * @author pabercrombie * @version $Id: TacticalGraphicUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TacticalGraphicUtil -{ +public class TacticalGraphicUtil { + /** * Convert a list of cartesian points to Positions. * - * @param globe Globe used to convert points to positions. + * @param globe Globe used to convert points to positions. * @param points Points to convert. * * @return List of positions computed from cartesian points. */ - public static List asPositionList(Globe globe, Vec4... points) - { + public static List asPositionList(Globe globe, Vec4... points) { List positions = new ArrayList(points.length); - for (Vec4 point : points) - { + for (Vec4 point : points) { positions.add(globe.computePositionFromPoint(point)); } return positions; @@ -49,31 +46,25 @@ public static List asPositionList(Globe globe, Vec4... points) * * @return A two element array containing the altitude modifiers. One or both elements may be null. */ - public static Object[] getDateRange(TacticalGraphic graphic) - { + public static Object[] getDateRange(TacticalGraphic graphic) { Object date1 = null; Object date2 = null; Object o = graphic.getModifier(SymbologyConstants.DATE_TIME_GROUP); - if (o instanceof Iterable) - { + if (o instanceof Iterable) { Iterator iterator = ((Iterable) o).iterator(); - if (iterator.hasNext()) - { + if (iterator.hasNext()) { date1 = iterator.next(); } - if (iterator.hasNext()) - { + if (iterator.hasNext()) { date2 = iterator.next(); } - } - else - { + } else { date1 = o; } - return new Object[] {date1, date2}; + return new Object[]{date1, date2}; } /** @@ -87,31 +78,25 @@ public static Object[] getDateRange(TacticalGraphic graphic) * * @return A two element array containing the altitude modifiers. One or both elements may be null. */ - public static Object[] getAltitudeRange(TacticalGraphic graphic) - { + public static Object[] getAltitudeRange(TacticalGraphic graphic) { Object alt1 = null; Object alt2 = null; Object o = graphic.getModifier(SymbologyConstants.ALTITUDE_DEPTH); - if (o instanceof Iterable) - { + if (o instanceof Iterable) { Iterator iterator = ((Iterable) o).iterator(); - if (iterator.hasNext()) - { + if (iterator.hasNext()) { alt1 = iterator.next(); } - if (iterator.hasNext()) - { + if (iterator.hasNext()) { alt2 = iterator.next(); } - } - else - { + } else { alt1 = o; } - return new Object[] {alt1, alt2}; + return new Object[]{alt1, alt2}; } /** @@ -119,16 +104,15 @@ public static Object[] getAltitudeRange(TacticalGraphic graphic) * below the same point, so this method supports positioning a pair of labels at the same point. The label offsets * determine how the labels draw in relation to the line. * - * @param dc Current draw context. + * @param dc Current draw context. * @param positions Positions that describe the path. - * @param label1 First label to position. - * @param label2 Second label to position. (May be null.) - * @param distance Distance along the path at which to position the labels. + * @param label1 First label to position. + * @param label2 Second label to position. (May be null.) + * @param distance Distance along the path at which to position the labels. */ public static void placeLabelsOnPath(DrawContext dc, Iterable positions, - TacticalGraphicLabel label1, - TacticalGraphicLabel label2, double distance) - { + TacticalGraphicLabel label1, + TacticalGraphicLabel label2, double distance) { Iterator iterator = positions.iterator(); Globe globe = dc.getGlobe(); @@ -142,8 +126,7 @@ public static void placeLabelsOnPath(DrawContext dc, Iterable 0) - { + if (pos1 != null && pos2 != null && thisDistance > 0) { double delta = length - distance; LatLon ll = LatLon.interpolateGreatCircle(delta / thisDistance, pos1, pos2); pos1 = new Position(ll, 0); @@ -163,8 +145,7 @@ public static void placeLabelsOnPath(DrawContext dc, Iterable * * @param controlPoints Control points for the curve. - * @param t Interpolation parameter in the range [0..1]. - * @param coefficients Array to store binomial coefficients between invocations of this function. On the first - * invocation, pass an int[] with length equal to the controlPoints array. bezierCurve will - * populate the array on the first invocation, and reuse the computed values on subsequent - * invocations. + * @param t Interpolation parameter in the range [0..1]. + * @param coefficients Array to store binomial coefficients between invocations of this function. On the first + * invocation, pass an int[] with length equal to the controlPoints array. bezierCurve will populate the array on + * the first invocation, and reuse the computed values on subsequent invocations. * * @return A point along the curve. */ - public static Vec4 bezierCurve(Vec4[] controlPoints, double t, int[] coefficients) - { - if (coefficients == null || controlPoints == null) - { + public static Vec4 bezierCurve(Vec4[] controlPoints, double t, int[] coefficients) { + if (coefficients == null || controlPoints == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (coefficients.length != controlPoints.length) - { + if (coefficients.length != controlPoints.length) { String message = Logging.getMessage("generic.ArrayInvalidLength", coefficients.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (coefficients[0] != 1) - { + if (coefficients[0] != 1) { binomial(coefficients.length - 1, coefficients); } int n = controlPoints.length - 1; Vec4 r = Vec4.ZERO; - for (int k = 0; k <= n; k++) - { + for (int k = 0; k <= n; k++) { double c = coefficients[k] * Math.pow(t, k) * Math.pow(1 - t, n - k); r = r.add3(controlPoints[k].multiply3(c)); } @@ -244,20 +219,17 @@ public static Vec4 bezierCurve(Vec4[] controlPoints, double t, int[] coefficient * Compute binomial coefficients for a polynomial of order n. Stated another way, computes the nth row of Pascal's * triangle. * - * @param n Order of polynomial for which to calculate coefficients. + * @param n Order of polynomial for which to calculate coefficients. * @param coefficients Array to receive coefficients. The length of this array must be n + 1. */ - protected static void binomial(int n, int[] coefficients) - { - if (coefficients == null) - { + protected static void binomial(int n, int[] coefficients) { + if (coefficients == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (coefficients.length != n + 1) - { + if (coefficients.length != n + 1) { String message = Logging.getMessage("generic.ArrayInvalidLength", coefficients.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -265,11 +237,9 @@ protected static void binomial(int n, int[] coefficients) // Algorithm from "Data Structures and Algorithms with Object-Oriented Design Patterns in Java" by Bruno R. // Preiss (http://www.brpreiss.com/books/opus5/html/page460.html) - for (int i = 0; i <= n; i++) - { + for (int i = 0; i <= n; i++) { coefficients[i] = 1; - for (int j = i - 1; j > 0; j--) - { + for (int j = i - 1; j > 0; j--) { coefficients[j] += coefficients[j - 1]; } } diff --git a/src/gov/nasa/worldwind/symbology/TacticalPoint.java b/src/gov/nasa/worldwind/symbology/TacticalPoint.java index ae6904c38d..4cf83f461c 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalPoint.java +++ b/src/gov/nasa/worldwind/symbology/TacticalPoint.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.geom.Position; @@ -15,8 +14,8 @@ * @version $Id: TacticalPoint.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TacticalGraphicFactory#createPoint(String, gov.nasa.worldwind.geom.Position, gov.nasa.worldwind.avlist.AVList) */ -public interface TacticalPoint extends TacticalGraphic -{ +public interface TacticalPoint extends TacticalGraphic { + /** * Indicates the position of the graphic. * diff --git a/src/gov/nasa/worldwind/symbology/TacticalQuad.java b/src/gov/nasa/worldwind/symbology/TacticalQuad.java index 3017a817ce..df71c9ecd3 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalQuad.java +++ b/src/gov/nasa/worldwind/symbology/TacticalQuad.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; /** @@ -14,8 +13,8 @@ * @version $Id: TacticalQuad.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TacticalGraphicFactory#createQuad(String, Iterable, gov.nasa.worldwind.avlist.AVList) */ -public interface TacticalQuad extends TacticalGraphic -{ +public interface TacticalQuad extends TacticalGraphic { + /** * Indicates the width of the quad. * diff --git a/src/gov/nasa/worldwind/symbology/TacticalRoute.java b/src/gov/nasa/worldwind/symbology/TacticalRoute.java index 6146c1ce70..3259d9243c 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalRoute.java +++ b/src/gov/nasa/worldwind/symbology/TacticalRoute.java @@ -3,22 +3,20 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; /** * An interface for tactical graphics that depict routes: a series of point graphics connected by lines. For example, * the MIL-STD-2525 symbology set defines an Air Control Route that is composed of Air Control Points. The route is * composed of many tactical graphics, but it is treated as a single graphic. If the route is highlighted all of the - * control points will also highlight, if the route is set invisible all the control points will be set invisible, - * etc. + * control points will also highlight, if the route is set invisible all the control points will be set invisible, etc. * * @author pabercrombie * @version $Id: TacticalRoute.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TacticalGraphicFactory#createRoute(String, Iterable, gov.nasa.worldwind.avlist.AVList) */ -public interface TacticalRoute extends TacticalGraphic -{ +public interface TacticalRoute extends TacticalGraphic { + /** * Indicates the control points along this route. * diff --git a/src/gov/nasa/worldwind/symbology/TacticalSymbol.java b/src/gov/nasa/worldwind/symbology/TacticalSymbol.java index 9f6ff6fb71..29e45c53d3 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalSymbol.java +++ b/src/gov/nasa/worldwind/symbology/TacticalSymbol.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.WWObject; @@ -14,7 +13,8 @@ /** * TacticalSymbol provides a common interface for displaying tactical point symbols from symbology sets. A tactical * symbol displays graphic and textual information about an object at a single geographic position at a particular point - * in time. See the Tutorial + * in time. See the + * Tutorial * for instructions on using TacticalSymbol in an application. *

              Construction

              Implementations of this interface provide support for symbols belonging to a specific symbology * set. For example, class {@link gov.nasa.worldwind.symbology.milstd2525.MilStd2525TacticalSymbol} provides support for @@ -106,21 +106,21 @@ * @author dcollins * @version $Id: TacticalSymbol.java 2370 2014-10-06 22:37:50Z tgaskins $ */ -public interface TacticalSymbol extends WWObject, Renderable, Highlightable -{ +public interface TacticalSymbol extends WWObject, Renderable, Highlightable { + /** * An interface to enable application selection of tactical symbol level of detail. */ - public interface LODSelector - { + public interface LODSelector { + /** * Modifies the symbol's attributes and properties to achieve a desired level of detail during rendering. This * method is called during rendering in order to provide the application an opportunity to adjust the symbol's * attributes and properties to achieve a level of detail based on the symbol's distance from the view's eye * point or other criteria. * - * @param dc the current draw context. - * @param symbol the symbol about to be rendered. + * @param dc the current draw context. + * @param symbol the symbol about to be rendered. * @param eyeDistance the distance in meters from the view's eye point to the symbol's geographic position. */ public void selectLOD(DrawContext dc, TacticalSymbol symbol, double eyeDistance); @@ -137,7 +137,7 @@ public interface LODSelector * Specifies this symbols level of detail selector. * * @param LODSelector the level of detail selector. May be null, the default, to indicate no level of detail - * selector. + * selector. */ void setLODSelector(LODSelector LODSelector); @@ -247,7 +247,7 @@ public interface LODSelector * location modifier. Setting showLocation on a symbol that does not support the modifier will have no effect. * * @param show true if the symbol will display the location modifier. Note that not some symbols may not support - * this modifier. + * this modifier. */ void setShowLocation(boolean show); @@ -262,11 +262,11 @@ public interface LODSelector /** * Specifies whether or not to display an indicator when the symbol represents a hostile entity. The indicator is - * determined by the symbology set, and may not apply to all symbols in the symbol set. In the case of + * determined by the symbology set, and may not apply to all symbols in the symbol set. In the case of * MIL-STD-2525C, the indicator is the letters "ENY" displayed at the lower right corner of the symbol. * * @param show true if this symbol will display an indicator when this symbol represents a hostile entity and the - * symbol specification supports such an indicator. + * symbol specification supports such an indicator. */ void setShowHostileIndicator(boolean show); @@ -293,8 +293,8 @@ public interface LODSelector * isShowGraphicModifiers or isShowTextModifiers, respectively, returns false. * * @param modifier the modifier key. - * @param value the modifier value. May be null, indicating that the modifier should be removed from - * this symbol. + * @param value the modifier value. May be null, indicating that the modifier should be removed from + * this symbol. * * @throws IllegalArgumentException if the modifier is null. */ @@ -327,7 +327,7 @@ public interface LODSelector * Specifies this symbol's highlight attributes. * * @param highlightAttrs the highlight attributes. May be null, in which case default highlight - * attributes are used. + * attributes are used. */ void setHighlightAttributes(TacticalSymbolAttributes highlightAttrs); @@ -362,4 +362,3 @@ public interface LODSelector */ void setUnitsFormat(UnitsFormat unitsFormat); } - diff --git a/src/gov/nasa/worldwind/symbology/TacticalSymbolAttributes.java b/src/gov/nasa/worldwind/symbology/TacticalSymbolAttributes.java index 815c53ac37..b712ebbb97 100644 --- a/src/gov/nasa/worldwind/symbology/TacticalSymbolAttributes.java +++ b/src/gov/nasa/worldwind/symbology/TacticalSymbolAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology; import gov.nasa.worldwind.render.Material; @@ -18,8 +17,8 @@ * @author dcollins * @version $Id: TacticalSymbolAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TacticalSymbolAttributes -{ +public interface TacticalSymbolAttributes { + /** * Copies the specified TacticalSymbolAttributes' properties into this object's properties. This does nothing if the * specified attributes is null. @@ -108,8 +107,9 @@ public interface TacticalSymbolAttributes void setTextModifierFont(Font font); /** - * Indicates the material used to draw text modifiers. See {@link #setTextModifierMaterial(gov.nasa.worldwind.render.Material)} - * for a description of how the text modifier material is used. + * Indicates the material used to draw text modifiers. See + * {@link #setTextModifierMaterial(gov.nasa.worldwind.render.Material)} for a description of how the text modifier + * material is used. * * @return the text modifier material. May be null, indicating that the default material is used. */ @@ -122,7 +122,7 @@ public interface TacticalSymbolAttributes * the color of 2D text. * * @param material the text modifier material. May be null, indicating that the default material should - * be used. + * be used. */ void setTextModifierMaterial(Material material); } diff --git a/src/gov/nasa/worldwind/symbology/milstd1477/MilStd1477IconRetriever.java b/src/gov/nasa/worldwind/symbology/milstd1477/MilStd1477IconRetriever.java index 9e7dc3d88f..940eed8d8b 100644 --- a/src/gov/nasa/worldwind/symbology/milstd1477/MilStd1477IconRetriever.java +++ b/src/gov/nasa/worldwind/symbology/milstd1477/MilStd1477IconRetriever.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd1477; import gov.nasa.worldwind.avlist.AVList; @@ -17,33 +16,26 @@ * @author ccrick * @version $Id: MilStd1477IconRetriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MilStd1477IconRetriever extends AbstractIconRetriever -{ +public class MilStd1477IconRetriever extends AbstractIconRetriever { // TODO: add more error checking - public MilStd1477IconRetriever(String retrieverPath) - { + public MilStd1477IconRetriever(String retrieverPath) { super(retrieverPath); } - public BufferedImage createIcon(String symbolId, AVList params) - { - if (symbolId == null) - { + public BufferedImage createIcon(String symbolId, AVList params) { + if (symbolId == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // retrieve desired symbol and convert to bufferedImage - // SymbolCode symbolCode = new SymbolCode(symbolIdentifier); - String filename = this.getFilename(symbolId); BufferedImage img = this.readImage(filename); - if (img == null) - { + if (img == null) { String msg = Logging.getMessage("Symbology.SymbolIconNotFound", symbolId); Logging.logger().severe(msg); throw new MissingResourceException(msg, BufferedImage.class.getName(), filename); @@ -52,8 +44,7 @@ public BufferedImage createIcon(String symbolId, AVList params) return img; } - protected String getFilename(String code) - { + protected String getFilename(String code) { return code.toLowerCase() + ".png"; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/AbstractMilStd2525TacticalGraphic.java b/src/gov/nasa/worldwind/symbology/milstd2525/AbstractMilStd2525TacticalGraphic.java index 84b2abab4c..382b523a93 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/AbstractMilStd2525TacticalGraphic.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/AbstractMilStd2525TacticalGraphic.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.geom.Position; @@ -18,13 +17,19 @@ * @version $Id: AbstractMilStd2525TacticalGraphic.java 1171 2013-02-11 21:45:02Z dcollins $ */ public abstract class AbstractMilStd2525TacticalGraphic extends AbstractTacticalGraphic - implements MilStd2525TacticalGraphic, Renderable -{ - /** Factor applied to the stipple pattern used to draw graphics in present state. */ + implements MilStd2525TacticalGraphic, Renderable { + + /** + * Factor applied to the stipple pattern used to draw graphics in present state. + */ protected static final int OUTLINE_STIPPLE_FACTOR_PRESENT = 0; - /** Factor applied to the stipple pattern used to draw graphics in anticipated state. */ + /** + * Factor applied to the stipple pattern used to draw graphics in anticipated state. + */ protected static final int OUTLINE_STIPPLE_FACTOR_ANTICIPATED = 6; - /** Stipple pattern applied to graphics in the anticipated state. */ + /** + * Stipple pattern applied to graphics in the anticipated state. + */ protected static final short OUTLINE_STIPPLE_PATTERN = (short) 0xAAAA; /** @@ -40,8 +45,7 @@ public abstract class AbstractMilStd2525TacticalGraphic extends AbstractTactical */ protected String maskedSymbolCode; - protected AbstractMilStd2525TacticalGraphic(String symbolCode) - { + protected AbstractMilStd2525TacticalGraphic(String symbolCode) { this.symbolCode = new SymbolCode(symbolCode); this.maskedSymbolCode = this.symbolCode.toMaskedString(); @@ -49,62 +53,62 @@ protected AbstractMilStd2525TacticalGraphic(String symbolCode) this.setUnitsFormat(MilStd2525TacticalSymbol.DEFAULT_UNITS_FORMAT); } - /** {@inheritDoc} */ - public String getIdentifier() - { + /** + * {@inheritDoc} + */ + public String getIdentifier() { return this.symbolCode.toString(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.UNIQUE_DESIGNATION.equals(modifier) && this.text != null) - { + public Object getModifier(String modifier) { + if (SymbologyConstants.UNIQUE_DESIGNATION.equals(modifier) && this.text != null) { return this.text; } return super.getModifier(modifier); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.UNIQUE_DESIGNATION.equals(modifier) && (value instanceof String)) - { + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.UNIQUE_DESIGNATION.equals(modifier) && (value instanceof String)) { this.setText((String) value); - } - else - { + } else { super.setModifier(modifier, value); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public String getText() - { + public String getText() { return this.text; } - /** {@inheritDoc} */ - public String getStatus() - { + /** + * {@inheritDoc} + */ + public String getStatus() { return this.symbolCode.getStatus(); } - /** {@inheritDoc} */ - public void setStatus(String value) - { - if (value == null) - { + /** + * {@inheritDoc} + */ + public void setStatus(String value) { + if (value == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!SymbologyConstants.STATUS_ALL.contains(value.toUpperCase())) - { + if (!SymbologyConstants.STATUS_ALL.contains(value.toUpperCase())) { String msg = Logging.getMessage("Symbology.InvalidStatus", value); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -119,13 +123,12 @@ public void setStatus(String value) * * @return true if {@link #isShowHostileIndicator()} is true, and the graphic represents a hostile entity. */ - protected boolean mustShowHostileIndicator() - { + protected boolean mustShowHostileIndicator() { String id = this.symbolCode.getStandardIdentity(); boolean isHostile = SymbologyConstants.STANDARD_IDENTITY_HOSTILE.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(id); + || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(id) + || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(id) + || SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(id); return this.isShowHostileIndicator() && isHostile; } @@ -138,8 +141,7 @@ protected boolean mustShowHostileIndicator() * @param attributes Attributes bundle to receive defaults. */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { Material material = this.getDefaultMaterial(); attributes.setOutlineMaterial(material); attributes.setInteriorMaterial(material); @@ -148,13 +150,10 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) // when in the Present status, and dashed lines when the status is not Present. Note that the default is // overridden by some graphics, which always draw with dashed lines. String status = this.getStatus(); - if (!SymbologyConstants.STATUS_PRESENT.equalsIgnoreCase(status)) - { + if (!SymbologyConstants.STATUS_PRESENT.equalsIgnoreCase(status)) { attributes.setOutlineStippleFactor(this.getOutlineStippleFactor()); attributes.setOutlineStipplePattern(this.getOutlineStipplePattern()); - } - else - { + } else { attributes.setOutlineStippleFactor(OUTLINE_STIPPLE_FACTOR_PRESENT); } @@ -170,8 +169,7 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) * * @see gov.nasa.worldwind.render.ShapeAttributes#getOutlineStippleFactor() */ - protected int getOutlineStippleFactor() - { + protected int getOutlineStippleFactor() { return OUTLINE_STIPPLE_FACTOR_ANTICIPATED; } @@ -182,8 +180,7 @@ protected int getOutlineStippleFactor() * * @see gov.nasa.worldwind.render.ShapeAttributes#getOutlineStipplePattern() */ - protected short getOutlineStipplePattern() - { + protected short getOutlineStipplePattern() { return OUTLINE_STIPPLE_PATTERN; } @@ -192,15 +189,13 @@ protected short getOutlineStipplePattern() * * @return The default material, determined by the graphic's standard identity. */ - protected Material getDefaultMaterial() - { + protected Material getDefaultMaterial() { return MilStd2525Util.getDefaultGraphicMaterial(this.symbolCode); } - protected TacticalSymbol createSymbol(String sidc, Position position, TacticalSymbolAttributes attrs) - { + protected TacticalSymbol createSymbol(String sidc, Position position, TacticalSymbolAttributes attrs) { TacticalSymbol symbol = new MilStd2525TacticalSymbol(sidc, - position != null ? position : Position.ZERO); + position != null ? position : Position.ZERO); symbol.setDelegateOwner(this); symbol.setAttributes(attrs); symbol.setShowTextModifiers(false); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525Constants.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525Constants.java index 445ad693e7..5df031503b 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525Constants.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525Constants.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.render.Material; @@ -16,8 +15,8 @@ * @author dcollins * @version $Id: MilStd2525Constants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MilStd2525Constants -{ +public interface MilStd2525Constants { + /** * The default location that MIL-STD-2525 tactical symbols and tactical point graphics retrieve their icons from: * https://worldwind.arc.nasa.gov/milstd2525c/rev1/ @@ -25,14 +24,24 @@ public interface MilStd2525Constants String DEFAULT_ICON_RETRIEVER_PATH = "https://worldwind.arc.nasa.gov/milstd2525c/rev1/"; // Color RGB values from MIL-STD-2525C Table XIII, pg. 44. - /** Default material used to color tactical graphics that represent friendly entities. */ + /** + * Default material used to color tactical graphics that represent friendly entities. + */ Material MATERIAL_FRIEND = Material.BLACK; - /** Default material used to color tactical graphics that represent hostile entities. */ + /** + * Default material used to color tactical graphics that represent hostile entities. + */ Material MATERIAL_HOSTILE = new Material(new Color(255, 48, 49)); - /** Default material used to color tactical graphics that represent neutral entities. */ + /** + * Default material used to color tactical graphics that represent neutral entities. + */ Material MATERIAL_NEUTRAL = new Material(new Color(0, 226, 0)); - /** Default material used to color tactical graphics that represent unknown entities. */ + /** + * Default material used to color tactical graphics that represent unknown entities. + */ Material MATERIAL_UNKNOWN = new Material(new Color(255, 255, 0)); - /** Default material used to color tactical graphics that represent obstacles. */ + /** + * Default material used to color tactical graphics that represent obstacles. + */ Material MATERIAL_OBSTACLE = new Material(new Color(0, 226, 0)); } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525GraphicFactory.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525GraphicFactory.java index d2b35999bc..2ee264b6ee 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525GraphicFactory.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525GraphicFactory.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.avlist.AVList; @@ -24,25 +23,28 @@ * @author pabercrombie * @version $Id: MilStd2525GraphicFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MilStd2525GraphicFactory implements TacticalGraphicFactory -{ - /** Map to associate MIL-STD-2525C function codes with implementation classes. */ +public class MilStd2525GraphicFactory implements TacticalGraphicFactory { + + /** + * Map to associate MIL-STD-2525C function codes with implementation classes. + */ protected Map classMap = new ConcurrentHashMap(); - /** Create a new factory. */ - public MilStd2525GraphicFactory() - { + /** + * Create a new factory. + */ + public MilStd2525GraphicFactory() { this.populateClassMap(); } - /** Populate the map that maps function IDs to implementation classes. */ - protected void populateClassMap() - { + /** + * Populate the map that maps function IDs to implementation classes. + */ + protected void populateClassMap() { // All point graphics are handled by one class this.mapClass(MilStd2525PointGraphic.class, MilStd2525PointGraphic.getSupportedGraphics()); // Command/Control/General Maneuver - this.mapClass(Boundary.class, Boundary.getSupportedGraphics()); this.mapClass(PhaseLine.class, PhaseLine.getSupportedGraphics()); this.mapClass(ForwardLineOfOwnTroops.class, ForwardLineOfOwnTroops.getSupportedGraphics()); @@ -81,13 +83,11 @@ protected void populateClassMap() this.mapClass(LimitedAccessArea.class, LimitedAccessArea.getSupportedGraphics()); // Mobility/survivability - this.mapClass(MinimumSafeDistanceZones.class, MinimumSafeDistanceZones.getSupportedGraphics()); this.mapClass(FilledArea.class, FilledArea.getSupportedGraphics()); this.mapClass(DoseRateContourLine.class, DoseRateContourLine.getSupportedGraphics()); // Fire support - this.mapClass(RectangularTarget.class, RectangularTarget.getSupportedGraphics()); this.mapClass(LinearTarget.class, LinearTarget.getSupportedGraphics()); this.mapClass(RectangularFireSupportArea.class, RectangularFireSupportArea.getSupportedGraphics()); @@ -109,13 +109,12 @@ protected void populateClassMap() * default implementation class, and can be used to customize the behavior of the factory without needing to extend * the class. * - * @param sidc Masked symbol identifier. + * @param sidc Masked symbol identifier. * @param clazz Implementation class. This class must have a constructor that accepts a string argument. * * @see gov.nasa.worldwind.symbology.milstd2525.SymbolCode#toMaskedString() */ - public void setImplementationClass(String sidc, Class clazz) - { + public void setImplementationClass(String sidc, Class clazz) { this.classMap.put(sidc, clazz); } @@ -123,12 +122,10 @@ public void setImplementationClass(String sidc, Class clazz) * Associate an implementation class with one or more symbol identifiers. * * @param clazz Class that implements one or more tactical graphics. - * @param ids Masked symbol IDs of the graphics implemented by {@code clazz}. + * @param ids Masked symbol IDs of the graphics implemented by {@code clazz}. */ - protected void mapClass(Class clazz, List ids) - { - for (String sidc : ids) - { + protected void mapClass(Class clazz, List ids) { + for (String sidc : ids) { this.classMap.put(sidc, clazz); } } @@ -140,43 +137,35 @@ protected void mapClass(Class clazz, List ids) */ @SuppressWarnings({"unchecked"}) public MilStd2525TacticalGraphic createGraphic(String sidc, Iterable positions, - AVList modifiers) - { + AVList modifiers) { SymbolCode symbolCode = new SymbolCode(sidc); Class clazz = this.getClassForCode(symbolCode); - if (clazz == null) - { + if (clazz == null) { return null; } - if (!MilStd2525TacticalGraphic.class.isAssignableFrom(clazz)) - { + if (!MilStd2525TacticalGraphic.class.isAssignableFrom(clazz)) { String msg = Logging.getMessage("Symbology.CannotCast", clazz, MilStd2525TacticalGraphic.class); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } MilStd2525TacticalGraphic graphic; - try - { + try { Constructor ct = clazz.getConstructor(String.class); graphic = (MilStd2525TacticalGraphic) ct.newInstance(sidc); - if (positions != null) - { + if (positions != null) { graphic.setPositions(positions); } - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("Symbology.ExceptionCreatingGraphic", e.getMessage()); Logging.logger().severe(msg); throw new WWRuntimeException(e); } - if (modifiers != null) - { + if (modifiers != null) { this.setModifiers(graphic, modifiers); } @@ -188,15 +177,11 @@ public MilStd2525TacticalGraphic createGraphic(String sidc, Iterable positions, AVList modifiers) - { + /** + * {@inheritDoc} + */ + public TacticalQuad createQuad(String sidc, Iterable positions, AVList modifiers) { TacticalGraphic graphic = this.createGraphic(sidc, positions, modifiers); - if (graphic instanceof TacticalQuad) - { + if (graphic instanceof TacticalQuad) { return (TacticalQuad) graphic; - } - else if (graphic != null) - { + } else if (graphic != null) { String className = graphic.getClass().getName(); String msg = Logging.getMessage("Symbology.CannotCast", className, TacticalQuad.class.getName()); Logging.logger().severe(msg); @@ -246,19 +227,17 @@ else if (graphic != null) return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ public TacticalRoute createRoute(String sidc, Iterable controlPoints, - AVList modifiers) - { + AVList modifiers) { TacticalGraphic graphic = this.createGraphic(sidc, null, modifiers); - if (graphic instanceof TacticalRoute) - { + if (graphic instanceof TacticalRoute) { TacticalRoute route = (TacticalRoute) graphic; route.setControlPoints(controlPoints); return route; - } - else if (graphic != null) - { + } else if (graphic != null) { String className = graphic.getClass().getName(); String msg = Logging.getMessage("Symbology.CannotCast", className, TacticalRoute.class.getName()); Logging.logger().severe(msg); @@ -268,18 +247,17 @@ else if (graphic != null) return null; } - /** {@inheritDoc} */ - public boolean isSupported(String sidc) - { + /** + * {@inheritDoc} + */ + public boolean isSupported(String sidc) { SymbolCode symbolCode = new SymbolCode(sidc); String key = symbolCode.toMaskedString(); return this.classMap.containsKey(key); } - protected void setModifiers(TacticalGraphic graphic, AVList props) - { - for (Map.Entry entry : props.getEntries()) - { + protected void setModifiers(TacticalGraphic graphic, AVList props) { + for (Map.Entry entry : props.getEntries()) { graphic.setModifier(entry.getKey(), entry.getValue()); } } @@ -291,8 +269,7 @@ protected void setModifiers(TacticalGraphic graphic, AVList props) * * @return The implementation class for the specified SIDC, or {@code null} if no implementation class is found. */ - protected Class getClassForCode(SymbolCode symbolCode) - { + protected Class getClassForCode(SymbolCode symbolCode) { String key = symbolCode.toMaskedString(); return key != null ? this.classMap.get(key) : null; } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525IconRetriever.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525IconRetriever.java index a8253e438b..f01c1fcafe 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525IconRetriever.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525IconRetriever.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.avlist.*; @@ -17,10 +16,10 @@ /** * Retriever to retrieve icons for symbols in the MIL-STD-2525 symbol set. The retriever can retrieve icons from either - * a local or remote symbol store. See the Symbology - * Usage Guide for details on how to configure a local symbol repository. For more information on how to use this - * class see the IconRetriever Usage Guide and the {@link gov.nasa.worldwindx.examples.symbology.IconRetrieverUsage} - * example. + * a local or remote symbol store. See the + * Symbology Usage Guide for + * details on how to configure a local symbol repository. For more information on how to use this class see the + * IconRetriever Usage Guide and the {@link gov.nasa.worldwindx.examples.symbology.IconRetrieverUsage} example. *

              Retrieval parameters

              *

              * Table IX (pg. 35) of MIL-STD-2525C defines a hierarchy for simplifying tactical symbols. This hierarchy is @@ -30,10 +29,12 @@ * the state of SHOW_FILL). *

              * {@link #createIcon(String, gov.nasa.worldwind.avlist.AVList) createIcon} accepts the following parameters: - * + * + *
              createIcon Parameters
              KeyTypeDescription
              SymbologyConstants.SHOW_ICONBooleanDetermines - * if the symbol will be created with an icon.
              SymbologyConstants.SHOW_FRAMEBooleanDetermines - * if the symbol will be created with a frame.
              SymbologyConstants.SHOW_FILLBooleanDetermines - * if the symbol will be created with a fill color.
              AVKey.COLOR
              createIcon Parameters
              KeyTypeDescription
              SymbologyConstants.SHOW_ICONBooleanDetermines if the symbol will be created with an + * icon.
              SymbologyConstants.SHOW_FRAMEBooleanDetermines if the symbol will be + * created with a frame.
              SymbologyConstants.SHOW_FILLBooleanDetermines if the symbol + * will be created with a fill color.
              AVKey.COLORjava.awt.ColorFill color applied to the symbol. If the symbol is drawn with a * frame, then this color will be used to fill the frame. If the symbol is not drawn with a frame, then the fill will be * applied to the icon itself. The fill color has no effect if Show Fill is False.
              @@ -41,8 +42,8 @@ * @author ccrick * @version $Id: MilStd2525IconRetriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MilStd2525IconRetriever extends AbstractIconRetriever -{ +public class MilStd2525IconRetriever extends AbstractIconRetriever { + protected static final String FILLS_PATH = "fills"; protected static final String FRAMES_PATH = "frames"; protected static final String ICONS_PATH = "icons"; @@ -71,9 +72,13 @@ public class MilStd2525IconRetriever extends AbstractIconRetriever protected static final Color DEFAULT_ICON_COLOR = Color.BLACK; protected static final String DEFAULT_IMAGE_FORMAT = "image/png"; - /** Radius (in pixels) of circle that is drawn to the represent the symbol when both frame and icon are off. */ + /** + * Radius (in pixels) of circle that is drawn to the represent the symbol when both frame and icon are off. + */ protected static final int CIRCLE_RADIUS = 16; - /** Line width used to stroke circle when fill is turned off. */ + /** + * Line width used to stroke circle when fill is turned off. + */ protected static final int CIRCLE_LINE_WIDTH = 2; // Static maps and sets providing fast access to attributes about a symbol ID. These data structures are populated @@ -93,8 +98,7 @@ public class MilStd2525IconRetriever extends AbstractIconRetriever * * @param retrieverPath File path or URL to the symbol directory, for example "http://myserver.com/milstd2525/". */ - public MilStd2525IconRetriever(String retrieverPath) - { + public MilStd2525IconRetriever(String retrieverPath) { super(retrieverPath); } @@ -103,16 +107,14 @@ public MilStd2525IconRetriever(String retrieverPath) * fill, frame, and icon can be turned off by setting retrieval parameters. If both frame and icon are turned off * then this method will return an image containing a circle. * - * @param sidc SIDC identifier for the symbol. + * @param sidc SIDC identifier for the symbol. * @param params Parameters that affect icon retrieval. See Parameters in class - * documentation. + * documentation. * * @return An BufferedImage containing the icon for the requested symbol, or null if the icon cannot be retrieved. */ - public BufferedImage createIcon(String sidc, AVList params) - { - if (sidc == null) - { + public BufferedImage createIcon(String sidc, AVList params) { + if (sidc == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -125,91 +127,87 @@ public BufferedImage createIcon(String sidc, AVList params) boolean mustDrawIcon = this.mustDrawIcon(symbolCode, params); boolean mustDrawFrame = this.mustDrawFrame(symbolCode, params); - if (mustDrawFrame || mustDrawIcon) - { - if (mustDrawFill && mustDrawFrame) + if (mustDrawFrame || mustDrawIcon) { + if (mustDrawFill && mustDrawFrame) { image = this.drawFill(symbolCode, params, null); + } - if (mustDrawFrame) + if (mustDrawFrame) { image = this.drawFrame(symbolCode, params, image); + } - if (mustDrawIcon) + if (mustDrawIcon) { image = this.drawIcon(symbolCode, params, image); + } } // Draw a dot if both frame and icon are turned off - if (image == null) + if (image == null) { image = this.drawCircle(symbolCode, params, image); + } return image; } - protected boolean mustDrawFill(SymbolCode symbolCode, AVList params) - { + protected boolean mustDrawFill(SymbolCode symbolCode, AVList params) { String maskedCode = symbolCode.toMaskedString().toLowerCase(); - if (unfilledIconMap.contains(maskedCode)) + if (unfilledIconMap.contains(maskedCode)) { return false; + } Object o = params != null ? params.getValue(SymbologyConstants.SHOW_FILL) : null; return o == null || o.equals(Boolean.TRUE); } - protected boolean mustDrawFrame(SymbolCode symbolCode, AVList params) - { + protected boolean mustDrawFrame(SymbolCode symbolCode, AVList params) { String maskedCode = symbolCode.toMaskedString().toLowerCase(); - if (unframedIconMap.contains(maskedCode)) + if (unframedIconMap.contains(maskedCode)) { return false; + } Object o = params != null ? params.getValue(SymbologyConstants.SHOW_FRAME) : null; return o == null || o.equals(Boolean.TRUE); } @SuppressWarnings({"UnusedParameters"}) - protected boolean mustDrawIcon(SymbolCode symbolCode, AVList params) - { + protected boolean mustDrawIcon(SymbolCode symbolCode, AVList params) { Object o = params != null ? params.getValue(SymbologyConstants.SHOW_ICON) : null; return o == null || o.equals(Boolean.TRUE); } - protected BufferedImage drawFill(SymbolCode symbolCode, AVList params, BufferedImage dest) - { + protected BufferedImage drawFill(SymbolCode symbolCode, AVList params, BufferedImage dest) { String path = this.composeFillPath(symbolCode); Color color = this.getFillColor(symbolCode, params); return path != null ? this.drawIconComponent(path, color, dest) : dest; } - protected BufferedImage drawFrame(SymbolCode symbolCode, AVList params, BufferedImage dest) - { + protected BufferedImage drawFrame(SymbolCode symbolCode, AVList params, BufferedImage dest) { String path = this.composeFramePath(symbolCode); Color color = this.getFrameColor(symbolCode, params); return path != null ? this.drawIconComponent(path, color, dest) : dest; } - protected BufferedImage drawIcon(SymbolCode symbolCode, AVList params, BufferedImage dest) - { + protected BufferedImage drawIcon(SymbolCode symbolCode, AVList params, BufferedImage dest) { String path = this.composeIconPath(symbolCode, params); Color color = this.getIconColor(symbolCode, params); return path != null ? this.drawIconComponent(path, color, dest) : dest; } - protected BufferedImage drawCircle(SymbolCode symbolCode, AVList params, BufferedImage dest) - { + protected BufferedImage drawCircle(SymbolCode symbolCode, AVList params, BufferedImage dest) { Color frameColor = DEFAULT_FRAME_COLOR; Color fillColor = this.mustDrawFill(symbolCode, params) ? this.getFillColor(symbolCode, params) - : DEFAULT_ICON_COLOR; + : DEFAULT_ICON_COLOR; - if (dest == null) - { + if (dest == null) { int diameter = CIRCLE_RADIUS * 2; dest = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB); } Graphics2D g = null; - try - { + try { g = dest.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); @@ -228,37 +226,35 @@ protected BufferedImage drawCircle(SymbolCode symbolCode, AVList params, Buffere g.setColor(frameColor); g.setStroke(new BasicStroke(CIRCLE_LINE_WIDTH)); g.draw(circle); - } - finally - { - if (g != null) + } finally { + if (g != null) { g.dispose(); + } } return dest; } - protected BufferedImage drawIconComponent(String path, Color color, BufferedImage dest) - { + protected BufferedImage drawIconComponent(String path, Color color, BufferedImage dest) { BufferedImage image = this.readImage(path); - if (image == null) - { + if (image == null) { String msg = Logging.getMessage("Symbology.MissingIconComponent", path); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (color != null) + if (color != null) { this.multiply(image, color); + } - if (dest != null) + if (dest != null) { image = this.drawImage(image, dest); + } return image; } - protected String composeFillPath(SymbolCode symbolCode) - { + protected String composeFillPath(SymbolCode symbolCode) { String maskedCode = this.getMaskedFillCode(symbolCode); StringBuilder sb = new StringBuilder(); @@ -270,8 +266,7 @@ protected String composeFillPath(SymbolCode symbolCode) return sb.toString(); } - protected String composeFramePath(SymbolCode symbolCode) - { + protected String composeFramePath(SymbolCode symbolCode) { String maskedCode = this.getMaskedFrameCode(symbolCode); StringBuilder sb = new StringBuilder(); @@ -283,13 +278,11 @@ protected String composeFramePath(SymbolCode symbolCode) return sb.toString(); } - protected String composeIconPath(SymbolCode symbolCode, AVList params) - { + protected String composeIconPath(SymbolCode symbolCode, AVList params) { String scheme = symbolCode.getScheme(); String bd = symbolCode.getBattleDimension(); - if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_UNKNOWN)) - { + if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_UNKNOWN)) { String maskedCode = this.getMaskedUnknownIconCode(symbolCode, params); StringBuilder sb = new StringBuilder(); sb.append(ICONS_PATH).append("/"); @@ -297,12 +290,10 @@ protected String composeIconPath(SymbolCode symbolCode, AVList params) sb.append(maskedCode.toLowerCase()); sb.append(WWIO.makeSuffixForMimeType(DEFAULT_IMAGE_FORMAT)); return sb.toString(); - } - else - { - if (SymbolCode.isFieldEmpty(symbolCode.getFunctionId())) + } else { + if (SymbolCode.isFieldEmpty(symbolCode.getFunctionId())) { return null; // Don't draw an icon if the function ID is empty. - + } String maskedCode = this.getMaskedIconCode(symbolCode, params); StringBuilder sb = new StringBuilder(); sb.append(ICONS_PATH).append("/"); @@ -313,43 +304,35 @@ protected String composeIconPath(SymbolCode symbolCode, AVList params) } } - protected Color getFillColor(SymbolCode symbolCode, AVList params) - { + protected Color getFillColor(SymbolCode symbolCode, AVList params) { Color color = this.getColorFromParams(params); return color != null ? color : fillColorMap.get(symbolCode.getStandardIdentity().toLowerCase()); } - protected Color getFrameColor(SymbolCode symbolCode, AVList params) - { - if (this.isDashedFrame(symbolCode)) + protected Color getFrameColor(SymbolCode symbolCode, AVList params) { + if (this.isDashedFrame(symbolCode)) { return null; // Dashed pending or exercise frames are not colored. - - if (this.mustDrawFill(symbolCode, params)) + } + if (this.mustDrawFill(symbolCode, params)) { return DEFAULT_FRAME_COLOR; // Use the default color if the fill is on. - + } Color color = this.getColorFromParams(params); return color != null ? color : frameColorMap.get(symbolCode.getStandardIdentity().toLowerCase()); } - protected Color getIconColor(SymbolCode symbolCode, AVList params) - { + protected Color getIconColor(SymbolCode symbolCode, AVList params) { String maskedCode = symbolCode.toMaskedString().toLowerCase(); - if (this.mustDrawFrame(symbolCode, params)) - { + if (this.mustDrawFrame(symbolCode, params)) { // When the frame is enabled, we draw the icon in either its specified custom color or the default color. In // this case the app-specified color override (if any) is applied to the frame, and does apply to the icon. return iconColorMap.containsKey(maskedCode) ? iconColorMap.get(maskedCode) : DEFAULT_ICON_COLOR; - } - else if (this.mustDrawFill(symbolCode, params)) - { + } else if (this.mustDrawFill(symbolCode, params)) { // When the frame is disabled and the fill is enabled, we draw the icon in its corresponding standard // identity color (or app-specified color override). Color color = this.getColorFromParams(params); return color != null ? color : fillColorMap.get(symbolCode.getStandardIdentity().toLowerCase()); - } - else - { + } else { // When the frame is disabled and the fill is disabled, we draw the icon in either its specified custom // color or the default color. In this case the app-specified color override (if any) is ignored. return iconColorMap.containsKey(maskedCode) ? iconColorMap.get(maskedCode) : DEFAULT_ICON_COLOR; @@ -362,20 +345,18 @@ else if (this.mustDrawFill(symbolCode, params)) * @param params Parameter list. * * @return The value of the AVKey.COLOR parameter, if such a parameter exists and is of type java.awt.Color. Returns - * null if the parameter list is null, if there is no value for key AVKey.COLOR, or if the value is not a - * Color. + * null if the parameter list is null, if there is no value for key AVKey.COLOR, or if the value is not a Color. */ - protected Color getColorFromParams(AVList params) - { - if (params == null) + protected Color getColorFromParams(AVList params) { + if (params == null) { return null; + } Object o = params.getValue(AVKey.COLOR); return (o instanceof Color) ? (Color) o : null; } - protected String getMaskedFillCode(SymbolCode symbolCode) - { + protected String getMaskedFillCode(SymbolCode symbolCode) { // Transform the symbol code to its equivalent code in the Warfighting scheme. This ensures that we can use // the generic fill shape lookup logic used by Warfighting symbols. symbolCode = this.transformToWarfightingScheme(symbolCode); @@ -397,8 +378,7 @@ protected String getMaskedFillCode(SymbolCode symbolCode) return sb.toString(); } - protected String getMaskedFrameCode(SymbolCode symbolCode) - { + protected String getMaskedFrameCode(SymbolCode symbolCode) { // Transform the symbol code to its equivalent code in the Warfighting scheme. This ensures that we can use // the generic fill shape lookup logic used by Warfighting symbols. symbolCode = this.transformToWarfightingScheme(symbolCode); @@ -421,8 +401,7 @@ protected String getMaskedFrameCode(SymbolCode symbolCode) return sb.toString(); } - protected SymbolCode transformToWarfightingScheme(SymbolCode symbolCode) - { + protected SymbolCode transformToWarfightingScheme(SymbolCode symbolCode) { String maskedCode = symbolCode.toMaskedString().toLowerCase(); String scheme = symbolCode.getScheme(); String bd = symbolCode.getBattleDimension(); @@ -432,45 +411,39 @@ protected SymbolCode transformToWarfightingScheme(SymbolCode symbolCode) newCode.setStandardIdentity(symbolCode.getStandardIdentity()); newCode.setStatus(symbolCode.getStatus()); - if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_INTELLIGENCE)) - { + if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_INTELLIGENCE)) { newCode.setBattleDimension(bd); // Signals Intelligence ground symbols are equivalent to Warfighting ground equipment. - if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND)) + if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND)) { newCode.setFunctionId("E-----"); + } return newCode; - } - else if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS)) - { + } else if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS)) { // Stability Operations symbols frames are equivalent to Warfighting ground units. newCode.setBattleDimension(SymbologyConstants.BATTLE_DIMENSION_GROUND); newCode.setFunctionId("U-----"); return newCode; - } - else if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)) - { + } else if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)) { // Emergency Management symbol frames are equivalent to either Warfighting ground units or ground equipment. newCode.setBattleDimension(SymbologyConstants.BATTLE_DIMENSION_GROUND); newCode.setFunctionId(emsEquipment.contains(maskedCode) ? "E-----" : "U-----"); return newCode; - } - else - { + } else { return symbolCode; } } - protected String getMaskedIconCode(SymbolCode symbolCode, AVList params) - { + protected String getMaskedIconCode(SymbolCode symbolCode, AVList params) { String si = this.getSimpleStandardIdentity(symbolCode); // Either Unknown, Friend, Neutral, or Hostile. String status = this.getSimpleStatus(symbolCode); // Either Present or Anticipated. - if (this.mustDrawFrame(symbolCode, params)) + if (this.mustDrawFrame(symbolCode, params)) { status = SymbologyConstants.STATUS_PRESENT; + } SymbolCode maskedCode = new SymbolCode(symbolCode.toString()); maskedCode.setStandardIdentity(si); @@ -482,14 +455,14 @@ protected String getMaskedIconCode(SymbolCode symbolCode, AVList params) return maskedCode.toString(); } - protected String getMaskedUnknownIconCode(SymbolCode symbolCode, AVList params) - { + protected String getMaskedUnknownIconCode(SymbolCode symbolCode, AVList params) { String si = this.getSimpleStandardIdentity(symbolCode); // Either Unknown, Friend, Neutral, or Hostile. String bd = symbolCode.getBattleDimension(); String status = this.getSimpleStatus(symbolCode); // Either Present or Anticipated. - if (this.mustDrawFrame(symbolCode, params)) + if (this.mustDrawFrame(symbolCode, params)) { status = SymbologyConstants.STATUS_PRESENT; + } StringBuilder sb = new StringBuilder(); SymbolCode.appendFieldValue(sb, null, 1); // Scheme @@ -504,81 +477,70 @@ protected String getMaskedUnknownIconCode(SymbolCode symbolCode, AVList params) return sb.toString(); } - protected boolean isDashedFrame(SymbolCode symbolCode) - { + protected boolean isDashedFrame(SymbolCode symbolCode) { String si = symbolCode.getStandardIdentity(); return si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_PENDING) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_ASSUMED_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_SUSPECT) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_PENDING) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND)); + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_ASSUMED_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_SUSPECT) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_PENDING) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND)); } - protected String getSimpleStandardIdentity(SymbolCode symbolCode) - { + protected String getSimpleStandardIdentity(SymbolCode symbolCode) { String si = symbolCode.getStandardIdentity(); if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_PENDING) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_UNKNOWN) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_PENDING) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_UNKNOWN))) - { + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_UNKNOWN) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_PENDING) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_UNKNOWN))) { return SymbologyConstants.STANDARD_IDENTITY_UNKNOWN; - } - else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_ASSUMED_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_JOKER) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FAKER))) - { + } else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_ASSUMED_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_JOKER) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FAKER))) { return SymbologyConstants.STANDARD_IDENTITY_FRIEND; - } - else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_NEUTRAL) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_NEUTRAL))) - { + } else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_NEUTRAL) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_NEUTRAL))) { return SymbologyConstants.STANDARD_IDENTITY_NEUTRAL; - } - else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_HOSTILE) || - si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_SUSPECT))) - { + } else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_HOSTILE) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_SUSPECT))) { return SymbologyConstants.STANDARD_IDENTITY_HOSTILE; } return si; } - protected String getSimpleStatus(SymbolCode symbolCode) - { + protected String getSimpleStatus(SymbolCode symbolCode) { String status = symbolCode.getStatus(); - if (status != null && status.equalsIgnoreCase(SymbologyConstants.STATUS_ANTICIPATED)) + if (status != null && status.equalsIgnoreCase(SymbologyConstants.STATUS_ANTICIPATED)) { return SymbologyConstants.STATUS_ANTICIPATED; - else + } else { return SymbologyConstants.STATUS_PRESENT; + } } - protected String getGroundFunctionId(SymbolCode symbolCode) - { + protected String getGroundFunctionId(SymbolCode symbolCode) { String scheme = symbolCode.getScheme(); String bd = symbolCode.getBattleDimension(); String fid = symbolCode.getFunctionId(); if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING) - && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND)) - { - if (fid != null && fid.toLowerCase().startsWith("u")) + && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND)) { + if (fid != null && fid.toLowerCase().startsWith("u")) { return "u-----"; - else if (fid != null && fid.toLowerCase().startsWith("e")) + } else if (fid != null && fid.toLowerCase().startsWith("e")) { return "e-----"; - else if (fid != null && fid.toLowerCase().startsWith("i")) + } else if (fid != null && fid.toLowerCase().startsWith("i")) { return "i-----"; + } } return null; } - static - { + static { schemePathMap.put("s", "war"); // Scheme Warfighting schemePathMap.put("i", "sigint"); // Scheme Signals Intelligence schemePathMap.put("o", "stbops"); // Scheme Stability Operations @@ -924,4 +886,3 @@ else if (fid != null && fid.toLowerCase().startsWith("i")) emsEquipment.add("e-f-mc---------"); } } - diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525ModifierRetriever.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525ModifierRetriever.java index 9f2fdb502f..65b3d4ed3a 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525ModifierRetriever.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525ModifierRetriever.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.avlist.*; @@ -21,8 +20,8 @@ * @author dcollins * @version $Id: MilStd2525ModifierRetriever.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MilStd2525ModifierRetriever extends AbstractIconRetriever -{ +public class MilStd2525ModifierRetriever extends AbstractIconRetriever { + protected static final Color DEFAULT_COLOR = Color.BLACK; protected static final String PATH_PREFIX = "modifiers"; @@ -34,8 +33,7 @@ public class MilStd2525ModifierRetriever extends AbstractIconRetriever * * @param retrieverPath File path or URL to the symbol directory, for example "http://myserver.com/milstd2525/". */ - public MilStd2525ModifierRetriever(String retrieverPath) - { + public MilStd2525ModifierRetriever(String retrieverPath) { super(retrieverPath); } @@ -43,16 +41,14 @@ public MilStd2525ModifierRetriever(String retrieverPath) * Create an icon for a symbol modifier. * * @param symbolId Identifier for the modifier. This identifier is fields 11 and 12 of a MIL-STD-2525C SIDC (see - * MIL-STD-2525C Table A-I, pg. 51). - * @param params Parameters that affect icon retrieval. This retriever accepts only one parameter: AVKey.COLOR, - * which determines the color of the modifier (default is black). + * MIL-STD-2525C Table A-I, pg. 51). + * @param params Parameters that affect icon retrieval. This retriever accepts only one parameter: AVKey.COLOR, + * which determines the color of the modifier (default is black). * * @return BufferedImage containing the requested modifier, or null if the modifier cannot be retrieved. */ - public BufferedImage createIcon(String symbolId, AVList params) - { - if (symbolId == null) - { + public BufferedImage createIcon(String symbolId, AVList params) { + if (symbolId == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -60,61 +56,59 @@ public BufferedImage createIcon(String symbolId, AVList params) // Compose a path from the modifier code and value. String path = this.composePath(symbolId, params); - if (path == null) - { + if (path == null) { String msg = Logging.getMessage("Symbology.SymbolIconNotFound", symbolId); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } BufferedImage image = this.readImage(path); - if (image == null) - { + if (image == null) { String msg = Logging.getMessage("Symbology.SymbolIconNotFound", symbolId); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } - if (this.mustApplyColor(symbolId)) - { + if (this.mustApplyColor(symbolId)) { // Apply the correct color the modifier. Color color = this.getColorFromParams(params); - if (color == null) + if (color == null) { color = DEFAULT_COLOR; + } this.multiply(image, color); } return image; } - protected String composePath(String symbolModifierCode, AVList params) - { + protected String composePath(String symbolModifierCode, AVList params) { AVList modifierParams = SymbolCode.parseSymbolModifierCode(symbolModifierCode, null); - if (modifierParams == null) + if (modifierParams == null) { return null; + } - if (params != null) + if (params != null) { modifierParams.setValues(params); + } StringBuilder sb = new StringBuilder(); sb.append(PATH_PREFIX).append("/"); sb.append(symbolModifierCode.toLowerCase()); - if (this.isVariableWidth(modifierParams)) - { + if (this.isVariableWidth(modifierParams)) { Integer i = this.chooseBestFittingWidth(modifierParams); - if (i != null) + if (i != null) { sb.append("_").append(i); + } } sb.append(PATH_SUFFIX); return sb.toString(); } - protected boolean isVariableWidth(AVList params) - { + protected boolean isVariableWidth(AVList params) { return params.hasKey(SymbologyConstants.FEINT_DUMMY) - || params.hasKey(SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE); + || params.hasKey(SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE); } /** @@ -125,26 +119,23 @@ protected boolean isVariableWidth(AVList params) * * @return True if color must be applied to the modifier. */ - protected boolean mustApplyColor(String symbolId) - { + protected boolean mustApplyColor(String symbolId) { return !SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE_ALL.contains(symbolId.toUpperCase()); } - protected Integer chooseBestFittingWidth(AVList params) - { + protected Integer chooseBestFittingWidth(AVList params) { Object o = params.getValue(AVKey.WIDTH); - if (o == null || !(o instanceof Number)) + if (o == null || !(o instanceof Number)) { return null; + } int value = ((Number) o).intValue(); int width = variableWidths[0]; int minDiff = Math.abs(value - width); - for (int i = 1; i < variableWidths.length; i++) - { + for (int i = 1; i < variableWidths.length; i++) { int diff = Math.abs(value - variableWidths[i]); - if (diff < minDiff) - { + if (diff < minDiff) { width = variableWidths[i]; minDiff = diff; } @@ -159,13 +150,12 @@ protected Integer chooseBestFittingWidth(AVList params) * @param params Parameter list. * * @return The value of the AVKey.COLOR parameter, if such a parameter exists and is of type java.awt.Color. Returns - * null if the parameter list is null, if there is no value for key AVKey.COLOR, or if the value is not a - * Color. + * null if the parameter list is null, if there is no value for key AVKey.COLOR, or if the value is not a Color. */ - protected Color getColorFromParams(AVList params) - { - if (params == null) + protected Color getColorFromParams(AVList params) { + if (params == null) { return null; + } Object o = params.getValue(AVKey.COLOR); return (o instanceof Color) ? (Color) o : null; diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525PointGraphic.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525PointGraphic.java index 9f5197c991..854bae99ce 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525PointGraphic.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525PointGraphic.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.avlist.AVListImpl; @@ -25,19 +24,24 @@ * @author pabercrombie * @version $Id: MilStd2525PointGraphic.java 560 2012-04-26 16:28:24Z pabercrombie $ */ -public class MilStd2525PointGraphic extends AVListImpl implements MilStd2525TacticalGraphic, TacticalPoint, Draggable -{ +public class MilStd2525PointGraphic extends AVListImpl implements MilStd2525TacticalGraphic, TacticalPoint, Draggable { // Implementation note: This class wraps an instance of TacticalGraphicSymbol. TacticalGraphicSymbol implements the // logic for rendering point graphics using the TacticalSymbol base classes. This class adapts the TacticalGraphic // interface to the TacticalSymbol interface. - /** Symbol used to render this graphic. */ + /** + * Symbol used to render this graphic. + */ protected TacticalGraphicSymbol symbol; - /** Indicates whether or not the graphic is highlighted. */ + /** + * Indicates whether or not the graphic is highlighted. + */ protected boolean highlighted; - /** Indicates whether the object is draggable and provides additional information for dragging about this object. */ + /** + * Indicates whether the object is draggable and provides additional information for dragging about this object. + */ protected boolean dragEnabled = true; protected DraggableSupport draggableSupport = null; @@ -52,9 +56,13 @@ public class MilStd2525PointGraphic extends AVListImpl implements MilStd2525Tact */ protected TacticalGraphicAttributes highlightAttributes; - /** Current frame timestamp. */ + /** + * Current frame timestamp. + */ protected long frameTimestamp = -1L; - /** Attributes to use for the current frame. */ + /** + * Attributes to use for the current frame. + */ protected TacticalSymbolAttributes activeSymbolAttributes = new BasicTacticalSymbolAttributes(); protected static TacticalSymbolAttributes defaultSymbolAttributes = new BasicTacticalSymbolAttributes(); @@ -64,8 +72,7 @@ public class MilStd2525PointGraphic extends AVListImpl implements MilStd2525Tact * * @param sidc MIL-STD-2525 SIDC code that identifies the graphic. */ - public MilStd2525PointGraphic(String sidc) - { + public MilStd2525PointGraphic(String sidc) { this.symbol = this.createSymbol(sidc); } @@ -76,113 +83,125 @@ public MilStd2525PointGraphic(String sidc) * * @return A new tactical symbol. */ - protected TacticalGraphicSymbol createSymbol(String sidc) - { + protected TacticalGraphicSymbol createSymbol(String sidc) { TacticalGraphicSymbol symbol = new TacticalGraphicSymbol(sidc); symbol.setAttributes(this.activeSymbolAttributes); symbol.setDelegateOwner(this); return symbol; } - /** {@inheritDoc} */ - public boolean isVisible() - { + /** + * {@inheritDoc} + */ + public boolean isVisible() { return this.symbol.isVisible(); } - /** {@inheritDoc} */ - public void setVisible(boolean visible) - { + /** + * {@inheritDoc} + */ + public void setVisible(boolean visible) { this.symbol.setVisible(visible); } - /** {@inheritDoc} */ - public Object getModifier(String modifier) - { + /** + * {@inheritDoc} + */ + public Object getModifier(String modifier) { return this.symbol.getModifier(modifier); } - /** {@inheritDoc} */ - public void setModifier(String modifier, Object value) - { + /** + * {@inheritDoc} + */ + public void setModifier(String modifier, Object value) { this.symbol.setModifier(modifier, value); } - /** {@inheritDoc} */ - public boolean isShowTextModifiers() - { + /** + * {@inheritDoc} + */ + public boolean isShowTextModifiers() { return this.symbol.isShowTextModifiers(); } - /** {@inheritDoc} */ - public void setShowTextModifiers(boolean showModifiers) - { + /** + * {@inheritDoc} + */ + public void setShowTextModifiers(boolean showModifiers) { this.symbol.setShowTextModifiers(showModifiers); } - /** {@inheritDoc} */ - public boolean isShowGraphicModifiers() - { + /** + * {@inheritDoc} + */ + public boolean isShowGraphicModifiers() { return this.symbol.isShowGraphicModifiers(); } - /** {@inheritDoc} */ - public void setShowGraphicModifiers(boolean showModifiers) - { + /** + * {@inheritDoc} + */ + public void setShowGraphicModifiers(boolean showModifiers) { this.symbol.setShowGraphicModifiers(showModifiers); } - /** {@inheritDoc} */ - public boolean isShowLocation() - { + /** + * {@inheritDoc} + */ + public boolean isShowLocation() { return this.symbol.isShowLocation(); } - /** {@inheritDoc} */ - public void setShowLocation(boolean show) - { + /** + * {@inheritDoc} + */ + public void setShowLocation(boolean show) { this.symbol.setShowLocation(show); } - /** {@inheritDoc} */ - public boolean isShowHostileIndicator() - { + /** + * {@inheritDoc} + */ + public boolean isShowHostileIndicator() { return this.symbol.isShowHostileIndicator(); } - /** {@inheritDoc} */ - public void setShowHostileIndicator(boolean show) - { + /** + * {@inheritDoc} + */ + public void setShowHostileIndicator(boolean show) { this.symbol.setShowHostileIndicator(show); } - /** {@inheritDoc} */ - public String getIdentifier() - { + /** + * {@inheritDoc} + */ + public String getIdentifier() { return this.symbol.getIdentifier(); } - /** {@inheritDoc} */ - public void setText(String text) - { + /** + * {@inheritDoc} + */ + public void setText(String text) { this.symbol.setModifier(SymbologyConstants.UNIQUE_DESIGNATION, text); } - /** {@inheritDoc} */ - public String getText() - { + /** + * {@inheritDoc} + */ + public String getText() { // Get the Unique Designation modifier. If it's an iterable, return the first value. Object value = this.getModifier(SymbologyConstants.UNIQUE_DESIGNATION); - if (value instanceof String) - { + if (value instanceof String) { return (String) value; - } - else if (value instanceof Iterable) - { + } else if (value instanceof Iterable) { Iterator iterator = ((Iterable) value).iterator(); Object o = iterator.hasNext() ? iterator.next() : null; - if (o != null) + if (o != null) { return o.toString(); + } } return null; } @@ -192,8 +211,7 @@ else if (value instanceof Iterable) * * @return Always returns an Iterable with only one position. */ - public Iterable getPositions() - { + public Iterable getPositions() { return Arrays.asList(this.getPosition()); } @@ -202,18 +220,15 @@ public Iterable getPositions() * * @param positions Control points. This graphic uses only one control point. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Iterator iterator = positions.iterator(); - if (!iterator.hasNext()) - { + if (!iterator.hasNext()) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -222,39 +237,45 @@ public void setPositions(Iterable positions) this.setPosition(iterator.next()); } - /** {@inheritDoc} */ - public TacticalGraphicAttributes getAttributes() - { + /** + * {@inheritDoc} + */ + public TacticalGraphicAttributes getAttributes() { return this.normalAttributes; } - /** {@inheritDoc} */ - public void setAttributes(TacticalGraphicAttributes attributes) - { + /** + * {@inheritDoc} + */ + public void setAttributes(TacticalGraphicAttributes attributes) { this.normalAttributes = attributes; } - /** {@inheritDoc} */ - public TacticalGraphicAttributes getHighlightAttributes() - { + /** + * {@inheritDoc} + */ + public TacticalGraphicAttributes getHighlightAttributes() { return this.highlightAttributes; } - /** {@inheritDoc} */ - public void setHighlightAttributes(TacticalGraphicAttributes attributes) - { + /** + * {@inheritDoc} + */ + public void setHighlightAttributes(TacticalGraphicAttributes attributes) { this.highlightAttributes = attributes; } - /** {@inheritDoc} */ - public Offset getLabelOffset() - { + /** + * {@inheritDoc} + */ + public Offset getLabelOffset() { return null; // Does not apply to point graphic } - /** {@inheritDoc} */ - public void setLabelOffset(Offset offset) - { + /** + * {@inheritDoc} + */ + public void setLabelOffset(Offset offset) { // Does not apply to point graphic } @@ -263,10 +284,9 @@ public void setLabelOffset(Offset offset) * #setOffset(gov.nasa.worldwind.render.Offset) setOffset} for more information. * * @return the hot spot controlling the symbol's placement relative to the symbol point. null indicates default - * alignment. + * alignment. */ - public Offset getOffset() - { + public Offset getOffset() { return this.symbol.getOffset(); } @@ -277,16 +297,16 @@ public Offset getOffset() * setOffset(Offset.BOTTOM_CENTER)} aligns the center of the bottom edge with the symbol point. * * @param offset the hot spot controlling the symbol's placement relative to the symbol point. May be null to - * indicate default alignment. + * indicate default alignment. */ - public void setOffset(Offset offset) - { + public void setOffset(Offset offset) { this.symbol.setOffset(offset); } - /** {@inheritDoc} */ - public Object getDelegateOwner() - { + /** + * {@inheritDoc} + */ + public Object getDelegateOwner() { // If the application has supplied a delegate owner, return that object. If the owner is this object (the // default), return null to keep the contract of getDelegateOwner, which specifies that a value of null // indicates that the graphic itself is used during picking. @@ -294,40 +314,45 @@ public Object getDelegateOwner() return owner != this ? owner : null; } - /** {@inheritDoc} */ - public void setDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + public void setDelegateOwner(Object owner) { // Apply new delegate owner if non-null. If the new owner is null, set this object as symbol's delegate owner // (the default). - if (owner != null) + if (owner != null) { this.symbol.setDelegateOwner(owner); - else + } else { this.symbol.setDelegateOwner(this); + } } - /** {@inheritDoc} */ - public UnitsFormat getUnitsFormat() - { + /** + * {@inheritDoc} + */ + public UnitsFormat getUnitsFormat() { return this.symbol.getUnitsFormat(); } - /** {@inheritDoc} */ - public void setUnitsFormat(UnitsFormat unitsFormat) - { + /** + * {@inheritDoc} + */ + public void setUnitsFormat(UnitsFormat unitsFormat) { this.symbol.setUnitsFormat(unitsFormat); } - /** {@inheritDoc} */ - public Position getPosition() - { + /** + * {@inheritDoc} + */ + public Position getPosition() { return this.symbol.getPosition(); } - /** {@inheritDoc} */ - public void setPosition(Position position) - { - if (position == null) - { + /** + * {@inheritDoc} + */ + public void setPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -342,8 +367,7 @@ public void setPosition(Position position) * * @return this symbol's altitude mode. */ - public int getAltitudeMode() - { + public int getAltitudeMode() { return this.symbol.getAltitudeMode(); } @@ -358,42 +382,42 @@ public int getAltitudeMode() * * @param altitudeMode this symbol's new altitude mode. */ - public void setAltitudeMode(int altitudeMode) - { + public void setAltitudeMode(int altitudeMode) { this.symbol.setAltitudeMode(altitudeMode); } //////////////////////////////////////// // MilStd2525TacticalGraphic interface //////////////////////////////////////// - - /** {@inheritDoc} */ - public String getStatus() - { + /** + * {@inheritDoc} + */ + public String getStatus() { return this.symbol.getStatus(); } - /** {@inheritDoc} */ - public void setStatus(String value) - { + /** + * {@inheritDoc} + */ + public void setStatus(String value) { this.symbol.setStatus(value); } ///////////////////////////// // Movable interface ///////////////////////////// - - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.getPosition(); } - /** {@inheritDoc} */ - public void move(Position delta) - { - if (delta == null) - { + /** + * {@inheritDoc} + */ + public void move(Position delta) { + if (delta == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -403,73 +427,73 @@ public void move(Position delta) // The reference position is null if this shape has no positions. In this case moving the shape by a // relative delta is meaningless. Therefore we fail softly by exiting and doing nothing. - if (refPos == null) + if (refPos == null) { return; + } this.moveTo(refPos.add(delta)); } - /** {@inheritDoc} */ - public void moveTo(Position position) - { + /** + * {@inheritDoc} + */ + public void moveTo(Position position) { this.symbol.setPosition(position); } @Override - public boolean isDragEnabled() - { + public boolean isDragEnabled() { return this.dragEnabled; } @Override - public void setDragEnabled(boolean enabled) - { + public void setDragEnabled(boolean enabled) { this.dragEnabled = enabled; } @Override - public void drag(DragContext dragContext) - { - if (!this.dragEnabled) + public void drag(DragContext dragContext) { + if (!this.dragEnabled) { return; + } - if (this.draggableSupport == null) + if (this.draggableSupport == null) { this.draggableSupport = new DraggableSupport(this, this.getAltitudeMode()); + } this.doDrag(dragContext); } - protected void doDrag(DragContext dragContext) - { + protected void doDrag(DragContext dragContext) { this.draggableSupport.dragScreenSizeConstant(dragContext); } ///////////////////////////// // Highlightable interface ///////////////////////////// - - /** {@inheritDoc} */ - public boolean isHighlighted() - { + /** + * {@inheritDoc} + */ + public boolean isHighlighted() { return this.highlighted; } - /** {@inheritDoc} */ - public void setHighlighted(boolean highlighted) - { + /** + * {@inheritDoc} + */ + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } ///////////////////////////// // Rendering ///////////////////////////// - - /** {@inheritDoc} */ - public void render(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { long timestamp = dc.getFrameTimeStamp(); - if (this.frameTimestamp != timestamp) - { + if (this.frameTimestamp != timestamp) { this.determineActiveAttributes(); this.frameTimestamp = timestamp; } @@ -477,29 +501,25 @@ public void render(DrawContext dc) this.symbol.render(dc); } - /** Determine active attributes for this frame. */ - protected void determineActiveAttributes() - { + /** + * Determine active attributes for this frame. + */ + protected void determineActiveAttributes() { // Reset symbol attributes to default before applying overrides. this.activeSymbolAttributes.copy(defaultSymbolAttributes); - if (this.isHighlighted()) - { + if (this.isHighlighted()) { TacticalGraphicAttributes highlightAttributes = this.getHighlightAttributes(); // If the application specified overrides to the highlight attributes, then apply the overrides - if (highlightAttributes != null) - { + if (highlightAttributes != null) { // Apply overrides specified by application this.applyAttributesToSymbol(highlightAttributes, this.activeSymbolAttributes); } - } - else - { + } else { // Apply overrides specified by application TacticalGraphicAttributes normalAttributes = this.getAttributes(); - if (normalAttributes != null) - { + if (normalAttributes != null) { this.applyAttributesToSymbol(normalAttributes, this.activeSymbolAttributes); } } @@ -509,22 +529,19 @@ protected void determineActiveAttributes() * Apply graphic attributes to the symbol. * * @param graphicAttributes Tactical graphic attributes to apply to the tactical symbol. - * @param symbolAttributes Symbol attributes to be modified. + * @param symbolAttributes Symbol attributes to be modified. */ protected void applyAttributesToSymbol(TacticalGraphicAttributes graphicAttributes, - TacticalSymbolAttributes symbolAttributes) - { + TacticalSymbolAttributes symbolAttributes) { // Line and area graphics distinguish between interior and outline opacity. Tactical symbols only support one // opacity, so use the interior opacity. Double value = graphicAttributes.getInteriorOpacity(); - if (value != null) - { + if (value != null) { symbolAttributes.setOpacity(value); } value = graphicAttributes.getScale(); - if (value != null) - { + if (value != null) { symbolAttributes.setScale(value); } @@ -532,14 +549,12 @@ protected void applyAttributesToSymbol(TacticalGraphicAttributes graphicAttribut symbolAttributes.setInteriorMaterial(material); Font font = graphicAttributes.getTextModifierFont(); - if (font != null) - { + if (font != null) { symbolAttributes.setTextModifierFont(font); } material = graphicAttributes.getTextModifierMaterial(); - if (material != null) - { + if (material != null) { symbolAttributes.setTextModifierMaterial(material); } } @@ -549,8 +564,7 @@ protected void applyAttributesToSymbol(TacticalGraphicAttributes graphicAttribut * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { List graphics = new ArrayList(); graphics.addAll(getTacGrpGraphics()); graphics.addAll(getMetocGraphics()); @@ -563,422 +577,419 @@ public static List getSupportedGraphics() * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getTacGrpGraphics() - { + public static List getTacGrpGraphics() { return Arrays.asList( - TacGrpSidc.TSK_DSTY, - TacGrpSidc.TSK_ITDT, - TacGrpSidc.TSK_NEUT, - TacGrpSidc.C2GM_GNL_PNT_USW_UH2_DTM, - TacGrpSidc.C2GM_GNL_PNT_USW_UH2_BCON, - TacGrpSidc.C2GM_GNL_PNT_USW_UH2_LCON, - TacGrpSidc.C2GM_GNL_PNT_USW_UH2_SNK, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_PTNCTR, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_DIFAR, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_LOFAR, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_CASS, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_DICASS, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_BT, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_ANM, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_VLAD, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_ATAC, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_RO, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_KGP, - TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_EXP, - TacGrpSidc.C2GM_GNL_PNT_USW_SRH, - TacGrpSidc.C2GM_GNL_PNT_USW_SRH_ARA, - TacGrpSidc.C2GM_GNL_PNT_USW_SRH_DIPPSN, - TacGrpSidc.C2GM_GNL_PNT_USW_SRH_CTR, - TacGrpSidc.C2GM_GNL_PNT_REFPNT, - TacGrpSidc.C2GM_GNL_PNT_REFPNT_NAVREF, - TacGrpSidc.C2GM_GNL_PNT_REFPNT_SPLPNT, - TacGrpSidc.C2GM_GNL_PNT_REFPNT_DLRP, - TacGrpSidc.C2GM_GNL_PNT_REFPNT_PIM, - TacGrpSidc.C2GM_GNL_PNT_REFPNT_MRSH, - TacGrpSidc.C2GM_GNL_PNT_REFPNT_WAP, - TacGrpSidc.C2GM_GNL_PNT_REFPNT_CRDRTB, - TacGrpSidc.C2GM_GNL_PNT_REFPNT_PNTINR, - TacGrpSidc.C2GM_GNL_PNT_WPN_AIMPNT, - TacGrpSidc.C2GM_GNL_PNT_WPN_DRPPNT, - TacGrpSidc.C2GM_GNL_PNT_WPN_ENTPNT, - TacGrpSidc.C2GM_GNL_PNT_WPN_GRDZRO, - TacGrpSidc.C2GM_GNL_PNT_WPN_MSLPNT, - TacGrpSidc.C2GM_GNL_PNT_WPN_IMTPNT, - TacGrpSidc.C2GM_GNL_PNT_WPN_PIPNT, - TacGrpSidc.C2GM_GNL_PNT_FRMN, - TacGrpSidc.C2GM_GNL_PNT_HBR, - TacGrpSidc.C2GM_GNL_PNT_HBR_PNTQ, - TacGrpSidc.C2GM_GNL_PNT_HBR_PNTA, - TacGrpSidc.C2GM_GNL_PNT_HBR_PNTY, - TacGrpSidc.C2GM_GNL_PNT_HBR_PNTX, - TacGrpSidc.C2GM_GNL_PNT_RTE, - TacGrpSidc.C2GM_GNL_PNT_RTE_RDV, - TacGrpSidc.C2GM_GNL_PNT_RTE_DVSN, - TacGrpSidc.C2GM_GNL_PNT_RTE_WAP, - TacGrpSidc.C2GM_GNL_PNT_RTE_PIM, - TacGrpSidc.C2GM_GNL_PNT_RTE_PNTR, - TacGrpSidc.C2GM_GNL_PNT_ACTL, - TacGrpSidc.C2GM_GNL_PNT_ACTL_CAP, - TacGrpSidc.C2GM_GNL_PNT_ACTL_ABNEW, - TacGrpSidc.C2GM_GNL_PNT_ACTL_TAK, - TacGrpSidc.C2GM_GNL_PNT_ACTL_ASBWF, - TacGrpSidc.C2GM_GNL_PNT_ACTL_ASBWR, - TacGrpSidc.C2GM_GNL_PNT_ACTL_SUWF, - TacGrpSidc.C2GM_GNL_PNT_ACTL_SUWR, - TacGrpSidc.C2GM_GNL_PNT_ACTL_MIWF, - TacGrpSidc.C2GM_GNL_PNT_ACTL_MIWR, - TacGrpSidc.C2GM_GNL_PNT_ACTL_SKEIP, - TacGrpSidc.C2GM_GNL_PNT_ACTL_TCN, - TacGrpSidc.C2GM_GNL_PNT_ACTL_TMC, - TacGrpSidc.C2GM_GNL_PNT_ACTL_RSC, - TacGrpSidc.C2GM_GNL_PNT_ACTL_RPH, - TacGrpSidc.C2GM_GNL_PNT_ACTL_UA, - TacGrpSidc.C2GM_GNL_PNT_ACTL_VTUA, - TacGrpSidc.C2GM_GNL_PNT_ACTL_ORB, - TacGrpSidc.C2GM_GNL_PNT_ACTL_ORBF8, - TacGrpSidc.C2GM_GNL_PNT_ACTL_ORBRT, - TacGrpSidc.C2GM_GNL_PNT_ACTL_ORBRD, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_CHKPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_CONPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_CRDPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_DCNPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_LNKUPT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_PSSPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_RAYPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_RELPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_STRPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_AMNPNT, - TacGrpSidc.C2GM_GNL_PNT_ACTPNT_WAP, - TacGrpSidc.C2GM_GNL_PNT_SCTL, - TacGrpSidc.C2GM_GNL_PNT_SCTL_USV, - TacGrpSidc.C2GM_GNL_PNT_SCTL_USV_RMV, - TacGrpSidc.C2GM_GNL_PNT_SCTL_USV_ASW, - TacGrpSidc.C2GM_GNL_PNT_SCTL_USV_SUW, - TacGrpSidc.C2GM_GNL_PNT_SCTL_USV_MIW, - TacGrpSidc.C2GM_GNL_PNT_SCTL_ASW, - TacGrpSidc.C2GM_GNL_PNT_SCTL_SUW, - TacGrpSidc.C2GM_GNL_PNT_SCTL_MIW, - TacGrpSidc.C2GM_GNL_PNT_SCTL_PKT, - TacGrpSidc.C2GM_GNL_PNT_SCTL_RDV, - TacGrpSidc.C2GM_GNL_PNT_SCTL_RSC, - TacGrpSidc.C2GM_GNL_PNT_SCTL_REP, - TacGrpSidc.C2GM_GNL_PNT_SCTL_NCBTT, - TacGrpSidc.C2GM_GNL_PNT_UCTL, - TacGrpSidc.C2GM_GNL_PNT_UCTL_UUV, - TacGrpSidc.C2GM_GNL_PNT_UCTL_UUV_ASW, - TacGrpSidc.C2GM_GNL_PNT_UCTL_UUV_SUW, - TacGrpSidc.C2GM_GNL_PNT_UCTL_UUV_MIW, - TacGrpSidc.C2GM_GNL_PNT_UCTL_SBSTN, - TacGrpSidc.C2GM_GNL_PNT_UCTL_SBSTN_ASW, - TacGrpSidc.C2GM_DEF_PNT_TGTREF, - TacGrpSidc.C2GM_DEF_PNT_OBSPST, - TacGrpSidc.C2GM_DEF_PNT_OBSPST_CBTPST, - TacGrpSidc.C2GM_DEF_PNT_OBSPST_RECON, - TacGrpSidc.C2GM_DEF_PNT_OBSPST_FWDOP, - TacGrpSidc.C2GM_DEF_PNT_OBSPST_SOP, - TacGrpSidc.C2GM_DEF_PNT_OBSPST_CBRNOP, - TacGrpSidc.C2GM_OFF_PNT_PNTD, - TacGrpSidc.C2GM_AVN_PNT_DAPP, - TacGrpSidc.MOBSU_OBST_ATO_TDTSM_FIXPFD, - TacGrpSidc.MOBSU_OBST_ATO_TDTSM_MVB, - TacGrpSidc.MOBSU_OBST_ATO_TDTSM_MVBPFD, - TacGrpSidc.MOBSU_OBST_BBY, - TacGrpSidc.MOBSU_OBST_MNE_USPMNE, - TacGrpSidc.MOBSU_OBST_MNE_ATMNE, - TacGrpSidc.MOBSU_OBST_MNE_ATMAHD, - TacGrpSidc.MOBSU_OBST_MNE_ATMDIR, - TacGrpSidc.MOBSU_OBST_MNE_APMNE, - TacGrpSidc.MOBSU_OBST_MNE_WAMNE, - TacGrpSidc.MOBSU_OBST_AVN_TWR_LOW, - TacGrpSidc.MOBSU_OBST_AVN_TWR_HIGH, - TacGrpSidc.MOBSU_OBSTBP_CSGSTE_ERP, - TacGrpSidc.MOBSU_SU_ESTOF, - TacGrpSidc.MOBSU_SU_FRT, - TacGrpSidc.MOBSU_SU_SUFSHL, - TacGrpSidc.MOBSU_SU_UGDSHL, - TacGrpSidc.MOBSU_CBRN_NDGZ, - TacGrpSidc.MOBSU_CBRN_FAOTP, - TacGrpSidc.MOBSU_CBRN_REEVNT_BIO, - TacGrpSidc.MOBSU_CBRN_REEVNT_CML, - TacGrpSidc.MOBSU_CBRN_DECONP_USP, - TacGrpSidc.MOBSU_CBRN_DECONP_ALTUSP, - TacGrpSidc.MOBSU_CBRN_DECONP_TRP, - TacGrpSidc.MOBSU_CBRN_DECONP_EQT, - TacGrpSidc.MOBSU_CBRN_DECONP_EQTTRP, - TacGrpSidc.MOBSU_CBRN_DECONP_OPDECN, - TacGrpSidc.MOBSU_CBRN_DECONP_TRGH, - TacGrpSidc.FSUPP_PNT_TGT_PTGT, - TacGrpSidc.FSUPP_PNT_TGT_NUCTGT, - TacGrpSidc.FSUPP_PNT_C2PNT_FSS, - TacGrpSidc.FSUPP_PNT_C2PNT_SCP, - TacGrpSidc.FSUPP_PNT_C2PNT_FP, - TacGrpSidc.FSUPP_PNT_C2PNT_RP, - TacGrpSidc.FSUPP_PNT_C2PNT_HP, - TacGrpSidc.FSUPP_PNT_C2PNT_LP, - TacGrpSidc.CSS_PNT_AEP, - TacGrpSidc.CSS_PNT_CBNP, - TacGrpSidc.CSS_PNT_CCP, - TacGrpSidc.CSS_PNT_CVP, - TacGrpSidc.CSS_PNT_DCP, - TacGrpSidc.CSS_PNT_EPWCP, - TacGrpSidc.CSS_PNT_LRP, - TacGrpSidc.CSS_PNT_MCP, - TacGrpSidc.CSS_PNT_RRRP, - TacGrpSidc.CSS_PNT_ROM, - TacGrpSidc.CSS_PNT_TCP, - TacGrpSidc.CSS_PNT_TTP, - TacGrpSidc.CSS_PNT_UMC, - TacGrpSidc.CSS_PNT_SPT_GNL, - TacGrpSidc.CSS_PNT_SPT_CLS1, - TacGrpSidc.CSS_PNT_SPT_CLS2, - TacGrpSidc.CSS_PNT_SPT_CLS3, - TacGrpSidc.CSS_PNT_SPT_CLS4, - TacGrpSidc.CSS_PNT_SPT_CLS5, - TacGrpSidc.CSS_PNT_SPT_CLS6, - TacGrpSidc.CSS_PNT_SPT_CLS7, - TacGrpSidc.CSS_PNT_SPT_CLS8, - TacGrpSidc.CSS_PNT_SPT_CLS9, - TacGrpSidc.CSS_PNT_SPT_CLS10, - TacGrpSidc.CSS_PNT_AP_ASP, - TacGrpSidc.CSS_PNT_AP_ATP, - TacGrpSidc.OTH_ER_DTHAC, - TacGrpSidc.OTH_ER_PIW, - TacGrpSidc.OTH_ER_DSTVES, - TacGrpSidc.OTH_HAZ_SML, - TacGrpSidc.OTH_HAZ_IB, - TacGrpSidc.OTH_HAZ_OLRG, - TacGrpSidc.OTH_SSUBSR_BTMRTN, - TacGrpSidc.OTH_SSUBSR_BTMRTN_INS, - TacGrpSidc.OTH_SSUBSR_BTMRTN_SBRSOO, - TacGrpSidc.OTH_SSUBSR_BTMRTN_WRKND, - TacGrpSidc.OTH_SSUBSR_BTMRTN_WRKD, - TacGrpSidc.OTH_SSUBSR_MARLFE, - TacGrpSidc.OTH_SSUBSR_SA, - TacGrpSidc.OTH_FIX_ACU, - TacGrpSidc.OTH_FIX_EM, - TacGrpSidc.OTH_FIX_EOP); - } - - public static List getMetocGraphics() - { + TacGrpSidc.TSK_DSTY, + TacGrpSidc.TSK_ITDT, + TacGrpSidc.TSK_NEUT, + TacGrpSidc.C2GM_GNL_PNT_USW_UH2_DTM, + TacGrpSidc.C2GM_GNL_PNT_USW_UH2_BCON, + TacGrpSidc.C2GM_GNL_PNT_USW_UH2_LCON, + TacGrpSidc.C2GM_GNL_PNT_USW_UH2_SNK, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_PTNCTR, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_DIFAR, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_LOFAR, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_CASS, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_DICASS, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_BT, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_ANM, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_VLAD, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_ATAC, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_RO, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_KGP, + TacGrpSidc.C2GM_GNL_PNT_USW_SNBY_EXP, + TacGrpSidc.C2GM_GNL_PNT_USW_SRH, + TacGrpSidc.C2GM_GNL_PNT_USW_SRH_ARA, + TacGrpSidc.C2GM_GNL_PNT_USW_SRH_DIPPSN, + TacGrpSidc.C2GM_GNL_PNT_USW_SRH_CTR, + TacGrpSidc.C2GM_GNL_PNT_REFPNT, + TacGrpSidc.C2GM_GNL_PNT_REFPNT_NAVREF, + TacGrpSidc.C2GM_GNL_PNT_REFPNT_SPLPNT, + TacGrpSidc.C2GM_GNL_PNT_REFPNT_DLRP, + TacGrpSidc.C2GM_GNL_PNT_REFPNT_PIM, + TacGrpSidc.C2GM_GNL_PNT_REFPNT_MRSH, + TacGrpSidc.C2GM_GNL_PNT_REFPNT_WAP, + TacGrpSidc.C2GM_GNL_PNT_REFPNT_CRDRTB, + TacGrpSidc.C2GM_GNL_PNT_REFPNT_PNTINR, + TacGrpSidc.C2GM_GNL_PNT_WPN_AIMPNT, + TacGrpSidc.C2GM_GNL_PNT_WPN_DRPPNT, + TacGrpSidc.C2GM_GNL_PNT_WPN_ENTPNT, + TacGrpSidc.C2GM_GNL_PNT_WPN_GRDZRO, + TacGrpSidc.C2GM_GNL_PNT_WPN_MSLPNT, + TacGrpSidc.C2GM_GNL_PNT_WPN_IMTPNT, + TacGrpSidc.C2GM_GNL_PNT_WPN_PIPNT, + TacGrpSidc.C2GM_GNL_PNT_FRMN, + TacGrpSidc.C2GM_GNL_PNT_HBR, + TacGrpSidc.C2GM_GNL_PNT_HBR_PNTQ, + TacGrpSidc.C2GM_GNL_PNT_HBR_PNTA, + TacGrpSidc.C2GM_GNL_PNT_HBR_PNTY, + TacGrpSidc.C2GM_GNL_PNT_HBR_PNTX, + TacGrpSidc.C2GM_GNL_PNT_RTE, + TacGrpSidc.C2GM_GNL_PNT_RTE_RDV, + TacGrpSidc.C2GM_GNL_PNT_RTE_DVSN, + TacGrpSidc.C2GM_GNL_PNT_RTE_WAP, + TacGrpSidc.C2GM_GNL_PNT_RTE_PIM, + TacGrpSidc.C2GM_GNL_PNT_RTE_PNTR, + TacGrpSidc.C2GM_GNL_PNT_ACTL, + TacGrpSidc.C2GM_GNL_PNT_ACTL_CAP, + TacGrpSidc.C2GM_GNL_PNT_ACTL_ABNEW, + TacGrpSidc.C2GM_GNL_PNT_ACTL_TAK, + TacGrpSidc.C2GM_GNL_PNT_ACTL_ASBWF, + TacGrpSidc.C2GM_GNL_PNT_ACTL_ASBWR, + TacGrpSidc.C2GM_GNL_PNT_ACTL_SUWF, + TacGrpSidc.C2GM_GNL_PNT_ACTL_SUWR, + TacGrpSidc.C2GM_GNL_PNT_ACTL_MIWF, + TacGrpSidc.C2GM_GNL_PNT_ACTL_MIWR, + TacGrpSidc.C2GM_GNL_PNT_ACTL_SKEIP, + TacGrpSidc.C2GM_GNL_PNT_ACTL_TCN, + TacGrpSidc.C2GM_GNL_PNT_ACTL_TMC, + TacGrpSidc.C2GM_GNL_PNT_ACTL_RSC, + TacGrpSidc.C2GM_GNL_PNT_ACTL_RPH, + TacGrpSidc.C2GM_GNL_PNT_ACTL_UA, + TacGrpSidc.C2GM_GNL_PNT_ACTL_VTUA, + TacGrpSidc.C2GM_GNL_PNT_ACTL_ORB, + TacGrpSidc.C2GM_GNL_PNT_ACTL_ORBF8, + TacGrpSidc.C2GM_GNL_PNT_ACTL_ORBRT, + TacGrpSidc.C2GM_GNL_PNT_ACTL_ORBRD, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_CHKPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_CONPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_CRDPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_DCNPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_LNKUPT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_PSSPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_RAYPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_RELPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_STRPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_AMNPNT, + TacGrpSidc.C2GM_GNL_PNT_ACTPNT_WAP, + TacGrpSidc.C2GM_GNL_PNT_SCTL, + TacGrpSidc.C2GM_GNL_PNT_SCTL_USV, + TacGrpSidc.C2GM_GNL_PNT_SCTL_USV_RMV, + TacGrpSidc.C2GM_GNL_PNT_SCTL_USV_ASW, + TacGrpSidc.C2GM_GNL_PNT_SCTL_USV_SUW, + TacGrpSidc.C2GM_GNL_PNT_SCTL_USV_MIW, + TacGrpSidc.C2GM_GNL_PNT_SCTL_ASW, + TacGrpSidc.C2GM_GNL_PNT_SCTL_SUW, + TacGrpSidc.C2GM_GNL_PNT_SCTL_MIW, + TacGrpSidc.C2GM_GNL_PNT_SCTL_PKT, + TacGrpSidc.C2GM_GNL_PNT_SCTL_RDV, + TacGrpSidc.C2GM_GNL_PNT_SCTL_RSC, + TacGrpSidc.C2GM_GNL_PNT_SCTL_REP, + TacGrpSidc.C2GM_GNL_PNT_SCTL_NCBTT, + TacGrpSidc.C2GM_GNL_PNT_UCTL, + TacGrpSidc.C2GM_GNL_PNT_UCTL_UUV, + TacGrpSidc.C2GM_GNL_PNT_UCTL_UUV_ASW, + TacGrpSidc.C2GM_GNL_PNT_UCTL_UUV_SUW, + TacGrpSidc.C2GM_GNL_PNT_UCTL_UUV_MIW, + TacGrpSidc.C2GM_GNL_PNT_UCTL_SBSTN, + TacGrpSidc.C2GM_GNL_PNT_UCTL_SBSTN_ASW, + TacGrpSidc.C2GM_DEF_PNT_TGTREF, + TacGrpSidc.C2GM_DEF_PNT_OBSPST, + TacGrpSidc.C2GM_DEF_PNT_OBSPST_CBTPST, + TacGrpSidc.C2GM_DEF_PNT_OBSPST_RECON, + TacGrpSidc.C2GM_DEF_PNT_OBSPST_FWDOP, + TacGrpSidc.C2GM_DEF_PNT_OBSPST_SOP, + TacGrpSidc.C2GM_DEF_PNT_OBSPST_CBRNOP, + TacGrpSidc.C2GM_OFF_PNT_PNTD, + TacGrpSidc.C2GM_AVN_PNT_DAPP, + TacGrpSidc.MOBSU_OBST_ATO_TDTSM_FIXPFD, + TacGrpSidc.MOBSU_OBST_ATO_TDTSM_MVB, + TacGrpSidc.MOBSU_OBST_ATO_TDTSM_MVBPFD, + TacGrpSidc.MOBSU_OBST_BBY, + TacGrpSidc.MOBSU_OBST_MNE_USPMNE, + TacGrpSidc.MOBSU_OBST_MNE_ATMNE, + TacGrpSidc.MOBSU_OBST_MNE_ATMAHD, + TacGrpSidc.MOBSU_OBST_MNE_ATMDIR, + TacGrpSidc.MOBSU_OBST_MNE_APMNE, + TacGrpSidc.MOBSU_OBST_MNE_WAMNE, + TacGrpSidc.MOBSU_OBST_AVN_TWR_LOW, + TacGrpSidc.MOBSU_OBST_AVN_TWR_HIGH, + TacGrpSidc.MOBSU_OBSTBP_CSGSTE_ERP, + TacGrpSidc.MOBSU_SU_ESTOF, + TacGrpSidc.MOBSU_SU_FRT, + TacGrpSidc.MOBSU_SU_SUFSHL, + TacGrpSidc.MOBSU_SU_UGDSHL, + TacGrpSidc.MOBSU_CBRN_NDGZ, + TacGrpSidc.MOBSU_CBRN_FAOTP, + TacGrpSidc.MOBSU_CBRN_REEVNT_BIO, + TacGrpSidc.MOBSU_CBRN_REEVNT_CML, + TacGrpSidc.MOBSU_CBRN_DECONP_USP, + TacGrpSidc.MOBSU_CBRN_DECONP_ALTUSP, + TacGrpSidc.MOBSU_CBRN_DECONP_TRP, + TacGrpSidc.MOBSU_CBRN_DECONP_EQT, + TacGrpSidc.MOBSU_CBRN_DECONP_EQTTRP, + TacGrpSidc.MOBSU_CBRN_DECONP_OPDECN, + TacGrpSidc.MOBSU_CBRN_DECONP_TRGH, + TacGrpSidc.FSUPP_PNT_TGT_PTGT, + TacGrpSidc.FSUPP_PNT_TGT_NUCTGT, + TacGrpSidc.FSUPP_PNT_C2PNT_FSS, + TacGrpSidc.FSUPP_PNT_C2PNT_SCP, + TacGrpSidc.FSUPP_PNT_C2PNT_FP, + TacGrpSidc.FSUPP_PNT_C2PNT_RP, + TacGrpSidc.FSUPP_PNT_C2PNT_HP, + TacGrpSidc.FSUPP_PNT_C2PNT_LP, + TacGrpSidc.CSS_PNT_AEP, + TacGrpSidc.CSS_PNT_CBNP, + TacGrpSidc.CSS_PNT_CCP, + TacGrpSidc.CSS_PNT_CVP, + TacGrpSidc.CSS_PNT_DCP, + TacGrpSidc.CSS_PNT_EPWCP, + TacGrpSidc.CSS_PNT_LRP, + TacGrpSidc.CSS_PNT_MCP, + TacGrpSidc.CSS_PNT_RRRP, + TacGrpSidc.CSS_PNT_ROM, + TacGrpSidc.CSS_PNT_TCP, + TacGrpSidc.CSS_PNT_TTP, + TacGrpSidc.CSS_PNT_UMC, + TacGrpSidc.CSS_PNT_SPT_GNL, + TacGrpSidc.CSS_PNT_SPT_CLS1, + TacGrpSidc.CSS_PNT_SPT_CLS2, + TacGrpSidc.CSS_PNT_SPT_CLS3, + TacGrpSidc.CSS_PNT_SPT_CLS4, + TacGrpSidc.CSS_PNT_SPT_CLS5, + TacGrpSidc.CSS_PNT_SPT_CLS6, + TacGrpSidc.CSS_PNT_SPT_CLS7, + TacGrpSidc.CSS_PNT_SPT_CLS8, + TacGrpSidc.CSS_PNT_SPT_CLS9, + TacGrpSidc.CSS_PNT_SPT_CLS10, + TacGrpSidc.CSS_PNT_AP_ASP, + TacGrpSidc.CSS_PNT_AP_ATP, + TacGrpSidc.OTH_ER_DTHAC, + TacGrpSidc.OTH_ER_PIW, + TacGrpSidc.OTH_ER_DSTVES, + TacGrpSidc.OTH_HAZ_SML, + TacGrpSidc.OTH_HAZ_IB, + TacGrpSidc.OTH_HAZ_OLRG, + TacGrpSidc.OTH_SSUBSR_BTMRTN, + TacGrpSidc.OTH_SSUBSR_BTMRTN_INS, + TacGrpSidc.OTH_SSUBSR_BTMRTN_SBRSOO, + TacGrpSidc.OTH_SSUBSR_BTMRTN_WRKND, + TacGrpSidc.OTH_SSUBSR_BTMRTN_WRKD, + TacGrpSidc.OTH_SSUBSR_MARLFE, + TacGrpSidc.OTH_SSUBSR_SA, + TacGrpSidc.OTH_FIX_ACU, + TacGrpSidc.OTH_FIX_EM, + TacGrpSidc.OTH_FIX_EOP); + } + + public static List getMetocGraphics() { return Arrays.asList( - MetocSidc.AMPHC_PRS_LOWCTR, - MetocSidc.AMPHC_PRS_LOWCTR_CYC, - MetocSidc.AMPHC_PRS_LOWCTR_TROPLW, - MetocSidc.AMPHC_PRS_HGHCTR, - MetocSidc.AMPHC_PRS_HGHCTR_ACYC, - MetocSidc.AMPHC_PRS_HGHCTR_TROPHG, - MetocSidc.AMPHC_TRB_LIT, - MetocSidc.AMPHC_TRB_MOD, - MetocSidc.AMPHC_TRB_SVR, - MetocSidc.AMPHC_TRB_EXT, - MetocSidc.AMPHC_TRB_MNTWAV, - MetocSidc.AMPHC_ICG_CLR_LIT, - MetocSidc.AMPHC_ICG_CLR_MOD, - MetocSidc.AMPHC_ICG_CLR_SVR, - MetocSidc.AMPHC_ICG_RIME_LIT, - MetocSidc.AMPHC_ICG_RIME_MOD, - MetocSidc.AMPHC_ICG_RIME_SVR, - MetocSidc.AMPHC_ICG_MIX_LIT, - MetocSidc.AMPHC_ICG_MIX_MOD, - MetocSidc.AMPHC_ICG_MIX_SVR, - MetocSidc.AMPHC_WND_CALM, -// MetocSidc.AMPHC_WND_PLT, - MetocSidc.AMPHC_CUDCOV_SYM_SKC, - MetocSidc.AMPHC_CUDCOV_SYM_FEW, - MetocSidc.AMPHC_CUDCOV_SYM_SCT, - MetocSidc.AMPHC_CUDCOV_SYM_BKN, - MetocSidc.AMPHC_CUDCOV_SYM_OVC, - MetocSidc.AMPHC_CUDCOV_SYM_STOPO, - MetocSidc.AMPHC_WTH_RA_INMLIT, - MetocSidc.AMPHC_WTH_RA_INMLIT_CTSLIT, - MetocSidc.AMPHC_WTH_RA_INMMOD, - MetocSidc.AMPHC_WTH_RA_INMMOD_CTSMOD, - MetocSidc.AMPHC_WTH_RA_INMHVY, - MetocSidc.AMPHC_WTH_RA_INMHVY_CTSHVY, - MetocSidc.AMPHC_WTH_FZRA_LIT, - MetocSidc.AMPHC_WTH_FZRA_MODHVY, - MetocSidc.AMPHC_WTH_RASWR_LIT, - MetocSidc.AMPHC_WTH_RASWR_MODHVY, - MetocSidc.AMPHC_WTH_RASWR_TOR, - MetocSidc.AMPHC_WTH_DZ_INMLIT, - MetocSidc.AMPHC_WTH_DZ_INMLIT_CTSLIT, - MetocSidc.AMPHC_WTH_DZ_INMMOD, - MetocSidc.AMPHC_WTH_DZ_INMMOD_CTSMOD, - MetocSidc.AMPHC_WTH_DZ_INMHVY, - MetocSidc.AMPHC_WTH_DZ_INMHVY_CTSHVY, - MetocSidc.AMPHC_WTH_FZDZ_LIT, - MetocSidc.AMPHC_WTH_FZDZ_MODHVY, - MetocSidc.AMPHC_WTH_RASN_RDSLIT, - MetocSidc.AMPHC_WTH_RASN_RDSMH, - MetocSidc.AMPHC_WTH_RASN_SWRLIT, - MetocSidc.AMPHC_WTH_RASN_SWRMOD, - MetocSidc.AMPHC_WTH_SN_INMLIT, - MetocSidc.AMPHC_WTH_SN_INMLIT_CTSLIT, - MetocSidc.AMPHC_WTH_SN_INMMOD, - MetocSidc.AMPHC_WTH_SN_INMMOD_CTSMOD, - MetocSidc.AMPHC_WTH_SN_INMHVY, - MetocSidc.AMPHC_WTH_SN_INMHVY_CTSHVY, - MetocSidc.AMPHC_WTH_SN_BLSNLM, - MetocSidc.AMPHC_WTH_SN_BLSNHY, - MetocSidc.AMPHC_WTH_SG, - MetocSidc.AMPHC_WTH_SSWR_LIT, - MetocSidc.AMPHC_WTH_SSWR_MODHVY, - MetocSidc.AMPHC_WTH_HL_LIT, - MetocSidc.AMPHC_WTH_HL_MODHVY, - MetocSidc.AMPHC_WTH_IC, - MetocSidc.AMPHC_WTH_PE_LIT, - MetocSidc.AMPHC_WTH_PE_MOD, - MetocSidc.AMPHC_WTH_PE_HVY, - MetocSidc.AMPHC_WTH_STMS_TS, - MetocSidc.AMPHC_WTH_STMS_TSLMNH, - MetocSidc.AMPHC_WTH_STMS_TSHVNH, - MetocSidc.AMPHC_WTH_STMS_TSLMWH, - MetocSidc.AMPHC_WTH_STMS_TSHVWH, - MetocSidc.AMPHC_WTH_STMS_FC, - MetocSidc.AMPHC_WTH_STMS_SQL, - MetocSidc.AMPHC_WTH_STMS_LTG, - MetocSidc.AMPHC_WTH_FG_SHWPTH, - MetocSidc.AMPHC_WTH_FG_SHWCTS, - MetocSidc.AMPHC_WTH_FG_PTHY, - MetocSidc.AMPHC_WTH_FG_SKYVSB, - MetocSidc.AMPHC_WTH_FG_SKYOBD, - MetocSidc.AMPHC_WTH_FG_FZSV, - MetocSidc.AMPHC_WTH_FG_FZSNV, - MetocSidc.AMPHC_WTH_MIST, - MetocSidc.AMPHC_WTH_FU, - MetocSidc.AMPHC_WTH_HZ, - MetocSidc.AMPHC_WTH_DTSD_LITMOD, - MetocSidc.AMPHC_WTH_DTSD_SVR, - MetocSidc.AMPHC_WTH_DTSD_DTDVL, -// MetocSidc.AMPHC_WTH_DTSD_BLDTSD, - MetocSidc.AMPHC_WTH_TPLSYS_TROPDN, - MetocSidc.AMPHC_WTH_TPLSYS_TROPSM, - MetocSidc.AMPHC_WTH_TPLSYS_HC, -// MetocSidc.AMPHC_WTH_TPLSYS_TSWADL, - MetocSidc.AMPHC_WTH_VOLERN, - MetocSidc.AMPHC_WTH_VOLERN_VOLASH, - MetocSidc.AMPHC_WTH_TROPLV, - MetocSidc.AMPHC_WTH_FZLVL, - MetocSidc.AMPHC_WTH_POUTAI, -// MetocSidc.AMPHC_STOG_WOSMIC_SUFDRY, -// MetocSidc.AMPHC_STOG_WOSMIC_SUFMST, -// MetocSidc.AMPHC_STOG_WOSMIC_SUFWET, -// MetocSidc.AMPHC_STOG_WOSMIC_SUFFLD, -// MetocSidc.AMPHC_STOG_WOSMIC_SUFFZN, - MetocSidc.AMPHC_STOG_WOSMIC_GLZGRD, -// MetocSidc.AMPHC_STOG_WOSMIC_LDNCGC, -// MetocSidc.AMPHC_STOG_WOSMIC_TLDCGC, -// MetocSidc.AMPHC_STOG_WOSMIC_MLDCGC, - MetocSidc.AMPHC_STOG_WOSMIC_EXTDWC, - MetocSidc.AMPHC_STOG_WSMIC_PDMIC, -// MetocSidc.AMPHC_STOG_WSMIC_CWSNLH, -// MetocSidc.AMPHC_STOG_WSMIC_CSNALH, -// MetocSidc.AMPHC_STOG_WSMIC_ELCSCG, -// MetocSidc.AMPHC_STOG_WSMIC_ULCSCG, -// MetocSidc.AMPHC_STOG_WSMIC_LDSNLH, -// MetocSidc.AMPHC_STOG_WSMIC_LDSALH, -// MetocSidc.AMPHC_STOG_WSMIC_ELDSCG, -// MetocSidc.AMPHC_STOG_WSMIC_ULDSCG, - MetocSidc.AMPHC_STOG_WSMIC_SCGC, - MetocSidc.OCA_ISYS_IB, - MetocSidc.OCA_ISYS_IB_MNY, - MetocSidc.OCA_ISYS_IB_BAS, - MetocSidc.OCA_ISYS_IB_GNL, - MetocSidc.OCA_ISYS_IB_MNYGNL, - MetocSidc.OCA_ISYS_IB_BB, - MetocSidc.OCA_ISYS_IB_MNYBB, - MetocSidc.OCA_ISYS_IB_GWL, - MetocSidc.OCA_ISYS_IB_MNYGWL, - MetocSidc.OCA_ISYS_IB_FBG, - MetocSidc.OCA_ISYS_IB_II, - MetocSidc.OCA_ISYS_ICN_BW, - MetocSidc.OCA_ISYS_ICN_WWRT, - MetocSidc.OCA_ISYS_ICN_IF, - MetocSidc.OCA_ISYS_DYNPRO_CNG, - MetocSidc.OCA_ISYS_DYNPRO_DVG, - MetocSidc.OCA_ISYS_DYNPRO_SHAZ, - MetocSidc.OCA_ISYS_SI, -// MetocSidc.OCA_ISYS_SI_ITOBS, -// MetocSidc.OCA_ISYS_SI_ITEST, - MetocSidc.OCA_ISYS_SI_MPOFI, - MetocSidc.OCA_ISYS_SC, - MetocSidc.OCA_ISYS_SC_SWO, - MetocSidc.OCA_ISYS_TOPFTR_HUM, - MetocSidc.OCA_ISYS_TOPFTR_RFTG, - MetocSidc.OCA_ISYS_TOPFTR_JBB, - MetocSidc.OCA_HYDGRY_DPH_SNDG, - MetocSidc.OCA_HYDGRY_PRTHBR_PRT_BRHSO, - MetocSidc.OCA_HYDGRY_PRTHBR_PRT_BRHSA, - MetocSidc.OCA_HYDGRY_PRTHBR_PRT_ANCRG1, - MetocSidc.OCA_HYDGRY_PRTHBR_PRT_CIP, - MetocSidc.OCA_HYDGRY_PRTHBR_FSG_FSGHBR, - MetocSidc.OCA_HYDGRY_PRTHBR_FSG_FSTK1, - MetocSidc.OCA_HYDGRY_PRTHBR_FAC_LNDPLC, - MetocSidc.OCA_HYDGRY_PRTHBR_FAC_OSLF1, - MetocSidc.OCA_HYDGRY_PRTHBR_FAC_LNDRNG, - MetocSidc.OCA_HYDGRY_PRTHBR_FAC_DOPN, - MetocSidc.OCA_HYDGRY_ATN_BCN, - MetocSidc.OCA_HYDGRY_ATN_BUOY, - MetocSidc.OCA_HYDGRY_ATN_MRK, - MetocSidc.OCA_HYDGRY_ATN_PRH1_PRH2, - MetocSidc.OCA_HYDGRY_ATN_LIT, - MetocSidc.OCA_HYDGRY_ATN_LITVES, - MetocSidc.OCA_HYDGRY_ATN_LITHSE, - MetocSidc.OCA_HYDGRY_DANHAZ_RCKSBM, - MetocSidc.OCA_HYDGRY_DANHAZ_RCKAWD, - MetocSidc.OCA_HYDGRY_DANHAZ_FLGRD1_FLGRD2, - MetocSidc.OCA_HYDGRY_DANHAZ_KLP1_KLP2, - MetocSidc.OCA_HYDGRY_DANHAZ_MNENAV_DBT, - MetocSidc.OCA_HYDGRY_DANHAZ_MNENAV_DEFN, - MetocSidc.OCA_HYDGRY_DANHAZ_SNAG, - MetocSidc.OCA_HYDGRY_DANHAZ_WRK_UCOV, - MetocSidc.OCA_HYDGRY_DANHAZ_WRK_SBM, - MetocSidc.OCA_HYDGRY_DANHAZ_EOTR, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_SD, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_MUD, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_CLAY, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_SLT, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_STNE, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_GVL, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_PBL, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_COBL, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_RCK, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_CRL, - MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_SHE, - MetocSidc.OCA_HYDGRY_BTMFAT_QLFYTM_FNE, - MetocSidc.OCA_HYDGRY_BTMFAT_QLFYTM_MDM, - MetocSidc.OCA_HYDGRY_BTMFAT_QLFYTM_CSE, - MetocSidc.OCA_HYDGRY_TDECUR_H2OTRB, - MetocSidc.OCA_HYDGRY_TDECUR_TDEDP, - MetocSidc.OCA_HYDGRY_TDECUR_TDEG, - MetocSidc.OCA_MMD_FRD, - MetocSidc.OCA_MMD_LCK, - MetocSidc.OCA_MMD_OLRG, - MetocSidc.OCA_MMD_PLE + MetocSidc.AMPHC_PRS_LOWCTR, + MetocSidc.AMPHC_PRS_LOWCTR_CYC, + MetocSidc.AMPHC_PRS_LOWCTR_TROPLW, + MetocSidc.AMPHC_PRS_HGHCTR, + MetocSidc.AMPHC_PRS_HGHCTR_ACYC, + MetocSidc.AMPHC_PRS_HGHCTR_TROPHG, + MetocSidc.AMPHC_TRB_LIT, + MetocSidc.AMPHC_TRB_MOD, + MetocSidc.AMPHC_TRB_SVR, + MetocSidc.AMPHC_TRB_EXT, + MetocSidc.AMPHC_TRB_MNTWAV, + MetocSidc.AMPHC_ICG_CLR_LIT, + MetocSidc.AMPHC_ICG_CLR_MOD, + MetocSidc.AMPHC_ICG_CLR_SVR, + MetocSidc.AMPHC_ICG_RIME_LIT, + MetocSidc.AMPHC_ICG_RIME_MOD, + MetocSidc.AMPHC_ICG_RIME_SVR, + MetocSidc.AMPHC_ICG_MIX_LIT, + MetocSidc.AMPHC_ICG_MIX_MOD, + MetocSidc.AMPHC_ICG_MIX_SVR, + MetocSidc.AMPHC_WND_CALM, + // MetocSidc.AMPHC_WND_PLT, + MetocSidc.AMPHC_CUDCOV_SYM_SKC, + MetocSidc.AMPHC_CUDCOV_SYM_FEW, + MetocSidc.AMPHC_CUDCOV_SYM_SCT, + MetocSidc.AMPHC_CUDCOV_SYM_BKN, + MetocSidc.AMPHC_CUDCOV_SYM_OVC, + MetocSidc.AMPHC_CUDCOV_SYM_STOPO, + MetocSidc.AMPHC_WTH_RA_INMLIT, + MetocSidc.AMPHC_WTH_RA_INMLIT_CTSLIT, + MetocSidc.AMPHC_WTH_RA_INMMOD, + MetocSidc.AMPHC_WTH_RA_INMMOD_CTSMOD, + MetocSidc.AMPHC_WTH_RA_INMHVY, + MetocSidc.AMPHC_WTH_RA_INMHVY_CTSHVY, + MetocSidc.AMPHC_WTH_FZRA_LIT, + MetocSidc.AMPHC_WTH_FZRA_MODHVY, + MetocSidc.AMPHC_WTH_RASWR_LIT, + MetocSidc.AMPHC_WTH_RASWR_MODHVY, + MetocSidc.AMPHC_WTH_RASWR_TOR, + MetocSidc.AMPHC_WTH_DZ_INMLIT, + MetocSidc.AMPHC_WTH_DZ_INMLIT_CTSLIT, + MetocSidc.AMPHC_WTH_DZ_INMMOD, + MetocSidc.AMPHC_WTH_DZ_INMMOD_CTSMOD, + MetocSidc.AMPHC_WTH_DZ_INMHVY, + MetocSidc.AMPHC_WTH_DZ_INMHVY_CTSHVY, + MetocSidc.AMPHC_WTH_FZDZ_LIT, + MetocSidc.AMPHC_WTH_FZDZ_MODHVY, + MetocSidc.AMPHC_WTH_RASN_RDSLIT, + MetocSidc.AMPHC_WTH_RASN_RDSMH, + MetocSidc.AMPHC_WTH_RASN_SWRLIT, + MetocSidc.AMPHC_WTH_RASN_SWRMOD, + MetocSidc.AMPHC_WTH_SN_INMLIT, + MetocSidc.AMPHC_WTH_SN_INMLIT_CTSLIT, + MetocSidc.AMPHC_WTH_SN_INMMOD, + MetocSidc.AMPHC_WTH_SN_INMMOD_CTSMOD, + MetocSidc.AMPHC_WTH_SN_INMHVY, + MetocSidc.AMPHC_WTH_SN_INMHVY_CTSHVY, + MetocSidc.AMPHC_WTH_SN_BLSNLM, + MetocSidc.AMPHC_WTH_SN_BLSNHY, + MetocSidc.AMPHC_WTH_SG, + MetocSidc.AMPHC_WTH_SSWR_LIT, + MetocSidc.AMPHC_WTH_SSWR_MODHVY, + MetocSidc.AMPHC_WTH_HL_LIT, + MetocSidc.AMPHC_WTH_HL_MODHVY, + MetocSidc.AMPHC_WTH_IC, + MetocSidc.AMPHC_WTH_PE_LIT, + MetocSidc.AMPHC_WTH_PE_MOD, + MetocSidc.AMPHC_WTH_PE_HVY, + MetocSidc.AMPHC_WTH_STMS_TS, + MetocSidc.AMPHC_WTH_STMS_TSLMNH, + MetocSidc.AMPHC_WTH_STMS_TSHVNH, + MetocSidc.AMPHC_WTH_STMS_TSLMWH, + MetocSidc.AMPHC_WTH_STMS_TSHVWH, + MetocSidc.AMPHC_WTH_STMS_FC, + MetocSidc.AMPHC_WTH_STMS_SQL, + MetocSidc.AMPHC_WTH_STMS_LTG, + MetocSidc.AMPHC_WTH_FG_SHWPTH, + MetocSidc.AMPHC_WTH_FG_SHWCTS, + MetocSidc.AMPHC_WTH_FG_PTHY, + MetocSidc.AMPHC_WTH_FG_SKYVSB, + MetocSidc.AMPHC_WTH_FG_SKYOBD, + MetocSidc.AMPHC_WTH_FG_FZSV, + MetocSidc.AMPHC_WTH_FG_FZSNV, + MetocSidc.AMPHC_WTH_MIST, + MetocSidc.AMPHC_WTH_FU, + MetocSidc.AMPHC_WTH_HZ, + MetocSidc.AMPHC_WTH_DTSD_LITMOD, + MetocSidc.AMPHC_WTH_DTSD_SVR, + MetocSidc.AMPHC_WTH_DTSD_DTDVL, + // MetocSidc.AMPHC_WTH_DTSD_BLDTSD, + MetocSidc.AMPHC_WTH_TPLSYS_TROPDN, + MetocSidc.AMPHC_WTH_TPLSYS_TROPSM, + MetocSidc.AMPHC_WTH_TPLSYS_HC, + // MetocSidc.AMPHC_WTH_TPLSYS_TSWADL, + MetocSidc.AMPHC_WTH_VOLERN, + MetocSidc.AMPHC_WTH_VOLERN_VOLASH, + MetocSidc.AMPHC_WTH_TROPLV, + MetocSidc.AMPHC_WTH_FZLVL, + MetocSidc.AMPHC_WTH_POUTAI, + // MetocSidc.AMPHC_STOG_WOSMIC_SUFDRY, + // MetocSidc.AMPHC_STOG_WOSMIC_SUFMST, + // MetocSidc.AMPHC_STOG_WOSMIC_SUFWET, + // MetocSidc.AMPHC_STOG_WOSMIC_SUFFLD, + // MetocSidc.AMPHC_STOG_WOSMIC_SUFFZN, + MetocSidc.AMPHC_STOG_WOSMIC_GLZGRD, + // MetocSidc.AMPHC_STOG_WOSMIC_LDNCGC, + // MetocSidc.AMPHC_STOG_WOSMIC_TLDCGC, + // MetocSidc.AMPHC_STOG_WOSMIC_MLDCGC, + MetocSidc.AMPHC_STOG_WOSMIC_EXTDWC, + MetocSidc.AMPHC_STOG_WSMIC_PDMIC, + // MetocSidc.AMPHC_STOG_WSMIC_CWSNLH, + // MetocSidc.AMPHC_STOG_WSMIC_CSNALH, + // MetocSidc.AMPHC_STOG_WSMIC_ELCSCG, + // MetocSidc.AMPHC_STOG_WSMIC_ULCSCG, + // MetocSidc.AMPHC_STOG_WSMIC_LDSNLH, + // MetocSidc.AMPHC_STOG_WSMIC_LDSALH, + // MetocSidc.AMPHC_STOG_WSMIC_ELDSCG, + // MetocSidc.AMPHC_STOG_WSMIC_ULDSCG, + MetocSidc.AMPHC_STOG_WSMIC_SCGC, + MetocSidc.OCA_ISYS_IB, + MetocSidc.OCA_ISYS_IB_MNY, + MetocSidc.OCA_ISYS_IB_BAS, + MetocSidc.OCA_ISYS_IB_GNL, + MetocSidc.OCA_ISYS_IB_MNYGNL, + MetocSidc.OCA_ISYS_IB_BB, + MetocSidc.OCA_ISYS_IB_MNYBB, + MetocSidc.OCA_ISYS_IB_GWL, + MetocSidc.OCA_ISYS_IB_MNYGWL, + MetocSidc.OCA_ISYS_IB_FBG, + MetocSidc.OCA_ISYS_IB_II, + MetocSidc.OCA_ISYS_ICN_BW, + MetocSidc.OCA_ISYS_ICN_WWRT, + MetocSidc.OCA_ISYS_ICN_IF, + MetocSidc.OCA_ISYS_DYNPRO_CNG, + MetocSidc.OCA_ISYS_DYNPRO_DVG, + MetocSidc.OCA_ISYS_DYNPRO_SHAZ, + MetocSidc.OCA_ISYS_SI, + // MetocSidc.OCA_ISYS_SI_ITOBS, + // MetocSidc.OCA_ISYS_SI_ITEST, + MetocSidc.OCA_ISYS_SI_MPOFI, + MetocSidc.OCA_ISYS_SC, + MetocSidc.OCA_ISYS_SC_SWO, + MetocSidc.OCA_ISYS_TOPFTR_HUM, + MetocSidc.OCA_ISYS_TOPFTR_RFTG, + MetocSidc.OCA_ISYS_TOPFTR_JBB, + MetocSidc.OCA_HYDGRY_DPH_SNDG, + MetocSidc.OCA_HYDGRY_PRTHBR_PRT_BRHSO, + MetocSidc.OCA_HYDGRY_PRTHBR_PRT_BRHSA, + MetocSidc.OCA_HYDGRY_PRTHBR_PRT_ANCRG1, + MetocSidc.OCA_HYDGRY_PRTHBR_PRT_CIP, + MetocSidc.OCA_HYDGRY_PRTHBR_FSG_FSGHBR, + MetocSidc.OCA_HYDGRY_PRTHBR_FSG_FSTK1, + MetocSidc.OCA_HYDGRY_PRTHBR_FAC_LNDPLC, + MetocSidc.OCA_HYDGRY_PRTHBR_FAC_OSLF1, + MetocSidc.OCA_HYDGRY_PRTHBR_FAC_LNDRNG, + MetocSidc.OCA_HYDGRY_PRTHBR_FAC_DOPN, + MetocSidc.OCA_HYDGRY_ATN_BCN, + MetocSidc.OCA_HYDGRY_ATN_BUOY, + MetocSidc.OCA_HYDGRY_ATN_MRK, + MetocSidc.OCA_HYDGRY_ATN_PRH1_PRH2, + MetocSidc.OCA_HYDGRY_ATN_LIT, + MetocSidc.OCA_HYDGRY_ATN_LITVES, + MetocSidc.OCA_HYDGRY_ATN_LITHSE, + MetocSidc.OCA_HYDGRY_DANHAZ_RCKSBM, + MetocSidc.OCA_HYDGRY_DANHAZ_RCKAWD, + MetocSidc.OCA_HYDGRY_DANHAZ_FLGRD1_FLGRD2, + MetocSidc.OCA_HYDGRY_DANHAZ_KLP1_KLP2, + MetocSidc.OCA_HYDGRY_DANHAZ_MNENAV_DBT, + MetocSidc.OCA_HYDGRY_DANHAZ_MNENAV_DEFN, + MetocSidc.OCA_HYDGRY_DANHAZ_SNAG, + MetocSidc.OCA_HYDGRY_DANHAZ_WRK_UCOV, + MetocSidc.OCA_HYDGRY_DANHAZ_WRK_SBM, + MetocSidc.OCA_HYDGRY_DANHAZ_EOTR, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_SD, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_MUD, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_CLAY, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_SLT, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_STNE, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_GVL, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_PBL, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_COBL, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_RCK, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_CRL, + MetocSidc.OCA_HYDGRY_BTMFAT_BTMCHR_SHE, + MetocSidc.OCA_HYDGRY_BTMFAT_QLFYTM_FNE, + MetocSidc.OCA_HYDGRY_BTMFAT_QLFYTM_MDM, + MetocSidc.OCA_HYDGRY_BTMFAT_QLFYTM_CSE, + MetocSidc.OCA_HYDGRY_TDECUR_H2OTRB, + MetocSidc.OCA_HYDGRY_TDECUR_TDEDP, + MetocSidc.OCA_HYDGRY_TDECUR_TDEG, + MetocSidc.OCA_MMD_FRD, + MetocSidc.OCA_MMD_LCK, + MetocSidc.OCA_MMD_OLRG, + MetocSidc.OCA_MMD_PLE ); } - public static List getEmsGraphics() - { + public static List getEmsGraphics() { return Arrays.asList( - EmsSidc.NATEVT_GEO_AFTSHK, - EmsSidc.NATEVT_GEO_AVL, - EmsSidc.NATEVT_GEO_EQKEPI, - EmsSidc.NATEVT_GEO_LNDSLD, - EmsSidc.NATEVT_GEO_SBSDNC, - EmsSidc.NATEVT_GEO_VLCTHT, - EmsSidc.NATEVT_HYDMET_DRGHT, - EmsSidc.NATEVT_HYDMET_FLD, - EmsSidc.NATEVT_HYDMET_INV, - EmsSidc.NATEVT_HYDMET_TSNMI, - EmsSidc.NATEVT_INFST_BIRD, - EmsSidc.NATEVT_INFST_INSCT, - EmsSidc.NATEVT_INFST_MICROB, - EmsSidc.NATEVT_INFST_REPT, - EmsSidc.NATEVT_INFST_RDNT + EmsSidc.NATEVT_GEO_AFTSHK, + EmsSidc.NATEVT_GEO_AVL, + EmsSidc.NATEVT_GEO_EQKEPI, + EmsSidc.NATEVT_GEO_LNDSLD, + EmsSidc.NATEVT_GEO_SBSDNC, + EmsSidc.NATEVT_GEO_VLCTHT, + EmsSidc.NATEVT_HYDMET_DRGHT, + EmsSidc.NATEVT_HYDMET_FLD, + EmsSidc.NATEVT_HYDMET_INV, + EmsSidc.NATEVT_HYDMET_TSNMI, + EmsSidc.NATEVT_INFST_BIRD, + EmsSidc.NATEVT_INFST_INSCT, + EmsSidc.NATEVT_INFST_MICROB, + EmsSidc.NATEVT_INFST_REPT, + EmsSidc.NATEVT_INFST_RDNT ); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525PointGraphicRetriever.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525PointGraphicRetriever.java index aefebb6061..0be42dec75 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525PointGraphicRetriever.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525PointGraphicRetriever.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.avlist.*; @@ -17,8 +16,8 @@ /** * Retriever to fetch icons for MIL-STD-2525C point graphics. The retriever can fetch images from either local or remote - * locations. See Offline - * Use for information on how to set the icon retrieval location. + * locations. See Offline Use + * for information on how to set the icon retrieval location. *

              * The retriever base URL must identify a location on a local or remote file system (including zip and jar files) that * holds the icon files in an expected directory structure. Each icon URL is constructed from three parts: @@ -32,18 +31,28 @@ * @author pabercrombie * @version $Id: MilStd2525PointGraphicRetriever.java 526 2012-04-13 21:07:09Z pabercrombie $ */ -public class MilStd2525PointGraphicRetriever extends AbstractIconRetriever -{ - /** Suffix added to file names to indicate the file type. */ +public class MilStd2525PointGraphicRetriever extends AbstractIconRetriever { + + /** + * Suffix added to file names to indicate the file type. + */ protected static final String PATH_SUFFIX = ".png"; - /** Subdirectory for graphics in the Tactical Graphics scheme. */ + /** + * Subdirectory for graphics in the Tactical Graphics scheme. + */ protected static final String DIR_ICON_TACGRP = "icons/tacgrp"; - /** Subdirectory for graphics in the Meteorological and Oceanographic scheme. */ + /** + * Subdirectory for graphics in the Meteorological and Oceanographic scheme. + */ protected static final String DIR_ICON_METOC = "icons/metoc"; - /** Subdirectory for graphics in the Emergency Management scheme. */ + /** + * Subdirectory for graphics in the Emergency Management scheme. + */ protected static final String DIR_ICON_EMS = "icons/ems"; - /** Subdirectory for fill graphics. */ + /** + * Subdirectory for fill graphics. + */ protected static final String DIR_FILL_TACGRP = "fills/tacgrp"; /** @@ -53,8 +62,7 @@ public class MilStd2525PointGraphicRetriever extends AbstractIconRetriever * * @param retrieverPath File path or URL to the symbol directory, for example "http://myserver.com/milstd2525/". */ - public MilStd2525PointGraphicRetriever(String retrieverPath) - { + public MilStd2525PointGraphicRetriever(String retrieverPath) { super(retrieverPath); } @@ -62,17 +70,14 @@ public MilStd2525PointGraphicRetriever(String retrieverPath) * Create an icon for a MIL-STD-2525C point graphic. Point graphics are defined in Appendixes B (Tactical Graphics), * C (Meteorological and Oceanographic), and G (Emergency Management). * - * @param sidc SIDC identifier for the symbol. + * @param sidc SIDC identifier for the symbol. * @param params Parameters that affect icon retrieval. This retriever accepts only one parameter: AVKey.COLOR, - * which determines the color of the image. By default the color will be determined from the standard - * identity. + * which determines the color of the image. By default the color will be determined from the standard identity. * * @return An BufferedImage containing the icon for the requested graphic, or null if the icon cannot be retrieved. */ - public BufferedImage createIcon(String sidc, AVList params) - { - if (sidc == null) - { + public BufferedImage createIcon(String sidc, AVList params) { + if (sidc == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -83,8 +88,7 @@ public BufferedImage createIcon(String sidc, AVList params) String filename = this.composeFilename(symbolCode); BufferedImage srcImg = this.readImage(filename); - if (srcImg == null) - { + if (srcImg == null) { String msg = Logging.getMessage("Symbology.SymbolIconNotFound", symbolCode); Logging.logger().severe(msg); throw new MissingResourceException(msg, BufferedImage.class.getName(), filename); @@ -100,19 +104,17 @@ public BufferedImage createIcon(String sidc, AVList params) // Non-Metoc symbols take their color from the standard identity. Metoc symbols do not have a standard identity, // so they take their color only from the override color. Color color = this.getColorFromParams(params); - if (!SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(symbolCode.getScheme())) - { - if (color == null) + if (!SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(symbolCode.getScheme())) { + if (color == null) { color = this.getColorForStandardIdentity(symbolCode); + } this.multiply(destImg, color); - if (this.mustDrawFill(symbolCode)) - { + if (this.mustDrawFill(symbolCode)) { destImg = this.composeFilledImage(destImg, symbolCode); } - } - else if (color != null) // Metoc symbol + } else if (color != null) // Metoc symbol { // There is not a clear use case for using an override color with Metoc so replace all colors in the // source image with the override rather than attempting to multiply colors and change only part of @@ -125,18 +127,16 @@ else if (color != null) // Metoc symbol /** * Create an image by drawing over a fill image. * - * @param srcImg Image to draw over fill. + * @param srcImg Image to draw over fill. * @param symbolCode Symbol code that identifies the graphic. * * @return A new image with the {@code srcImg} drawn over the appropriate fill. */ - protected BufferedImage composeFilledImage(BufferedImage srcImg, SymbolCode symbolCode) - { + protected BufferedImage composeFilledImage(BufferedImage srcImg, SymbolCode symbolCode) { String fillPath = this.composeFillPath(symbolCode); BufferedImage fill = this.readImage(fillPath); - if (fill == null) - { + if (fill == null) { String msg = Logging.getMessage("Symbology.SymbolIconNotFound", symbolCode); Logging.logger().severe(msg); throw new MissingResourceException(msg, BufferedImage.class.getName(), fillPath); @@ -159,16 +159,15 @@ protected BufferedImage composeFilledImage(BufferedImage srcImg, SymbolCode symb * @param code Symbol code of a point graphic. * * @return True if the graphic has a fill image. False if not. Only three graphics in MIL-STD-2525C Appendix B use a - * fill pattern: Nuclear Detonation Ground Zero (2.X.3.4.2), Biological Release Event (2.X.3.4.7.1), and - * Chemical Release Event (2.X.3.4.7.2). + * fill pattern: Nuclear Detonation Ground Zero (2.X.3.4.2), Biological Release Event (2.X.3.4.7.1), and Chemical + * Release Event (2.X.3.4.7.2). */ - protected boolean mustDrawFill(SymbolCode code) - { + protected boolean mustDrawFill(SymbolCode code) { String masked = code.toMaskedString(); return TacGrpSidc.MOBSU_CBRN_NDGZ.equalsIgnoreCase(masked) - || TacGrpSidc.MOBSU_CBRN_REEVNT_BIO.equalsIgnoreCase(masked) - || TacGrpSidc.MOBSU_CBRN_REEVNT_CML.equalsIgnoreCase(masked); + || TacGrpSidc.MOBSU_CBRN_REEVNT_BIO.equalsIgnoreCase(masked) + || TacGrpSidc.MOBSU_CBRN_REEVNT_CML.equalsIgnoreCase(masked); } /** @@ -177,13 +176,12 @@ protected boolean mustDrawFill(SymbolCode code) * @param params Parameter list. * * @return The value of the AVKey.COLOR parameter, if such a parameter exists and is of type java.awt.Color. Returns - * null if the parameter list is null, if there is no value for key AVKey.COLOR, or if the value is not a - * Color. + * null if the parameter list is null, if there is no value for key AVKey.COLOR, or if the value is not a Color. */ - protected Color getColorFromParams(AVList params) - { - if (params == null) + protected Color getColorFromParams(AVList params) { + if (params == null) { return null; + } Object o = params.getValue(AVKey.COLOR); return (o instanceof Color) ? (Color) o : null; @@ -196,8 +194,7 @@ protected Color getColorFromParams(AVList params) * * @return Color to apply based on the standard identity. (Red for hostile entities, black for friendly, etc.) */ - protected Color getColorForStandardIdentity(SymbolCode code) - { + protected Color getColorForStandardIdentity(SymbolCode code) { return MilStd2525Util.getDefaultGraphicMaterial(code).getDiffuse(); } @@ -208,8 +205,7 @@ protected Color getColorForStandardIdentity(SymbolCode code) * * @return Path to the appropriate fill image. */ - protected String composeFillPath(SymbolCode code) - { + protected String composeFillPath(SymbolCode code) { // Note: Metoc symbols currently do not use fill, so only handle tactical graphics here. return this.composeFilenameTacticalGraphic(code, DIR_FILL_TACGRP); } @@ -220,18 +216,18 @@ protected String composeFillPath(SymbolCode code) * @param code Code that identifies a graphic in MIL-STD-2525C. * * @return The file name of the image file that corresponds to the specified graphic, or null if the graphic's - * scheme is not recognized. + * scheme is not recognized. */ - protected String composeFilename(SymbolCode code) - { + protected String composeFilename(SymbolCode code) { String scheme = code.getScheme(); - if (SymbologyConstants.SCHEME_TACTICAL_GRAPHICS.equalsIgnoreCase(scheme)) + if (SymbologyConstants.SCHEME_TACTICAL_GRAPHICS.equalsIgnoreCase(scheme)) { return this.composeFilenameTacticalGraphic(code, DIR_ICON_TACGRP); - else if (SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(scheme)) + } else if (SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(scheme)) { return this.composeFilenameMetoc(code); - else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme)) + } else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme)) { return this.composeFilenameEms(code); + } return null; } @@ -240,12 +236,11 @@ else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme) * Indicates the filename of a graphic in the Tactical Graphics scheme (MIL-STD-2525C Appendix B). * * @param code Code that identifies a graphic in the Tactical Graphics scheme. - * @param dir Directory to prepend to file name. + * @param dir Directory to prepend to file name. * * @return The filename of the icon for the specified graphic. */ - protected String composeFilenameTacticalGraphic(SymbolCode code, String dir) - { + protected String composeFilenameTacticalGraphic(SymbolCode code, String dir) { String scheme = code.getScheme(); String category = code.getCategory(); String functionId = code.getFunctionId(); @@ -255,18 +250,19 @@ protected String composeFilenameTacticalGraphic(SymbolCode code, String dir) // dashed lines in other states. char status = SymbologyConstants.STATUS_PRESENT.equalsIgnoreCase(code.getStatus()) ? 'p' : 'a'; - if (functionId == null) + if (functionId == null) { functionId = "------"; + } StringBuilder sb = new StringBuilder(); sb.append(dir).append("/") - .append(scheme.toLowerCase()) - .append('-') // Standard identity - .append(category.toLowerCase()) - .append(status) - .append(functionId.toLowerCase()) - .append("-----") // Echelon, Country Code, Order of Battle - .append(PATH_SUFFIX); + .append(scheme.toLowerCase()) + .append('-') // Standard identity + .append(category.toLowerCase()) + .append(status) + .append(functionId.toLowerCase()) + .append("-----") // Echelon, Country Code, Order of Battle + .append(PATH_SUFFIX); return sb.toString(); } @@ -278,26 +274,26 @@ protected String composeFilenameTacticalGraphic(SymbolCode code, String dir) * * @return The filename of the icon for the specified graphic. */ - protected String composeFilenameMetoc(SymbolCode code) - { + protected String composeFilenameMetoc(SymbolCode code) { String scheme = code.getScheme(); String category = code.getCategory(); String staticDynamic = code.getStaticDynamic(); String functionId = code.getFunctionId(); String graphicType = code.getGraphicType(); - if (functionId == null) + if (functionId == null) { functionId = "------"; + } StringBuilder sb = new StringBuilder(); sb.append(DIR_ICON_METOC).append("/") - .append(scheme) - .append(category) - .append(staticDynamic) - .append(functionId) - .append(graphicType) - .append("--") // Positions 14, 15 unused - .append(PATH_SUFFIX); + .append(scheme) + .append(category) + .append(staticDynamic) + .append(functionId) + .append(graphicType) + .append("--") // Positions 14, 15 unused + .append(PATH_SUFFIX); return sb.toString().toLowerCase(); } @@ -309,8 +305,7 @@ protected String composeFilenameMetoc(SymbolCode code) * * @return The filename of the icon for the specified graphic. */ - protected String composeFilenameEms(SymbolCode code) - { + protected String composeFilenameEms(SymbolCode code) { String scheme = code.getScheme(); String category = code.getCategory(); String functionId = code.getFunctionId(); @@ -320,18 +315,19 @@ protected String composeFilenameEms(SymbolCode code) // dashed lines in other states. char status = SymbologyConstants.STATUS_PRESENT.equalsIgnoreCase(code.getStatus()) ? 'p' : 'a'; - if (functionId == null) + if (functionId == null) { functionId = "------"; + } StringBuilder sb = new StringBuilder(); sb.append(DIR_ICON_EMS).append("/") - .append(scheme.toLowerCase()) - .append('-') // Standard identity - .append(category.toLowerCase()) - .append(status) - .append(functionId.toLowerCase()) - .append("-----") // Echelon, Country Code, Order of Battle - .append(PATH_SUFFIX); + .append(scheme.toLowerCase()) + .append('-') // Standard identity + .append(category.toLowerCase()) + .append(status) + .append(functionId.toLowerCase()) + .append("-----") // Echelon, Country Code, Order of Battle + .append(PATH_SUFFIX); return sb.toString(); } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525TacticalGraphic.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525TacticalGraphic.java index 6248a772e2..6418ba8a03 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525TacticalGraphic.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525TacticalGraphic.java @@ -3,18 +3,20 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.symbology.TacticalGraphic; /** - * Interface to describe tactical graphics defined by MIL-STD-2525. - * See the TacticalGraphic Tutorial + * Interface to describe tactical graphics defined by + * MIL-STD-2525. See the + * TacticalGraphic + * Tutorial * for instructions on using TacticalGraphic in an application. *

              * The following table lists the modifiers supported by 2525 graphics. Note that not all graphics support all modifiers. - * + *
              2525 Graphics Modifiers
              FieldModifier keyData typeDescription
              * * * @@ -55,8 +57,8 @@ * @author pabercrombie * @version $Id: MilStd2525TacticalGraphic.java 555 2012-04-25 18:59:29Z pabercrombie $ */ -public interface MilStd2525TacticalGraphic extends TacticalGraphic -{ +public interface MilStd2525TacticalGraphic extends TacticalGraphic { + /** * Indicates the current value of graphic's Status/Operational Condition field. * @@ -83,7 +85,7 @@ public interface MilStd2525TacticalGraphic extends TacticalGraphic * @param value the new value for the Status/Operational Condition field. * * @throws IllegalArgumentException if the specified value is null or is not one of the accepted status - * values. + * values. */ void setStatus(String value); } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525TacticalSymbol.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525TacticalSymbol.java index ad81f29841..53e8ff832d 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525TacticalSymbol.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525TacticalSymbol.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.*; @@ -27,9 +26,11 @@ * @author dcollins * @version $Id: MilStd2525TacticalSymbol.java 2196 2014-08-06 19:42:15Z tgaskins $ */ -public class MilStd2525TacticalSymbol extends AbstractTacticalSymbol -{ - /** Default unit format. */ +public class MilStd2525TacticalSymbol extends AbstractTacticalSymbol { + + /** + * Default unit format. + */ public static final UnitsFormat DEFAULT_UNITS_FORMAT = new MilStd2525UnitsFormat(); protected static final Font DEFAULT_FRAME_SHAPE_FONT = Font.decode("Arial-BOLD-24"); @@ -39,8 +40,7 @@ public class MilStd2525TacticalSymbol extends AbstractTacticalSymbol protected static final Map symbolEchelonMap = new HashMap(); protected static final Set exerciseSymbols = new HashSet(); - static - { + static { // The MIL-STD-2525 symbols representing an echelon. symbolEchelonMap.put("e-o-bj---------", SymbologyConstants.ECHELON_TEAM_CREW); @@ -79,10 +79,9 @@ public class MilStd2525TacticalSymbol extends AbstractTacticalSymbol * @param position the latitude, longitude, and altitude where the symbol is drawn. * * @throws IllegalArgumentException if either the symbolId or the position are null, or if the symbolId - * is not a valid 15-character alphanumeric symbol identification code (SIDC). + * is not a valid 15-character alphanumeric symbol identification code (SIDC). */ - public MilStd2525TacticalSymbol(String symbolId, Position position) - { + public MilStd2525TacticalSymbol(String symbolId, Position position) { super(position); this.init(symbolId, null); @@ -104,36 +103,35 @@ public MilStd2525TacticalSymbol(String symbolId, Position position) * MilStd2525TacticalSymbol class documentation for the list of recognized modifiers. In the case where both the * symbol identifier and the modifiers list specify the same attribute, the modifiers list has priority. * - * @param symbolId a 15-character alphanumeric symbol identification code (SIDC). - * @param position the latitude, longitude, and altitude where the symbol is drawn. + * @param symbolId a 15-character alphanumeric symbol identification code (SIDC). + * @param position the latitude, longitude, and altitude where the symbol is drawn. * @param modifiers an optional list of key-value pairs specifying the symbol's modifiers. May be null - * to specify that the symbol contains only the attributes in its symbol identifier. + * to specify that the symbol contains only the attributes in its symbol identifier. * * @throws IllegalArgumentException if either the symbolId or the position are null, or if the symbolId - * is not a valid 15-character alphanumeric symbol identification code (SIDC). + * is not a valid 15-character alphanumeric symbol identification code (SIDC). */ - public MilStd2525TacticalSymbol(String symbolId, Position position, AVList modifiers) - { + public MilStd2525TacticalSymbol(String symbolId, Position position, AVList modifiers) { super(position); this.init(symbolId, modifiers); } - protected void init(String symbolId, AVList modifiers) - { + protected void init(String symbolId, AVList modifiers) { // Initialize the symbol code from the symbol identifier specified at construction. this.symbolCode = new SymbolCode(symbolId); // Parse the symbol code's 2-character modifier code and store the resulting pairs in the modifiers list. SymbolCode.parseSymbolModifierCode(this.symbolCode.getSymbolModifier(), this.modifiers); // Apply any caller-specified key-value pairs to the modifiers list. We apply these pairs last to give them // precedence. - if (modifiers != null) + if (modifiers != null) { this.modifiers.setValues(modifiers); + } // Configure this tactical symbol's icon retriever and modifier retriever with either the configuration value or // the default value (in that order of precedence). String iconRetrieverPath = Configuration.getStringValue(AVKey.MIL_STD_2525_ICON_RETRIEVER_PATH, - MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); + MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); this.setIconRetriever(new MilStd2525IconRetriever(iconRetrieverPath)); this.setModifierRetriever(new MilStd2525ModifierRetriever(iconRetrieverPath)); @@ -148,9 +146,10 @@ protected void init(String symbolId, AVList modifiers) this.setUnitsFormat(DEFAULT_UNITS_FORMAT); } - /** {@inheritDoc} */ - public String getIdentifier() - { + /** + * {@inheritDoc} + */ + public String getIdentifier() { return this.symbolCode.toString(); } @@ -161,8 +160,7 @@ public String getIdentifier() * * @see #setStatus(String) */ - public String getStatus() - { + public String getStatus() { return this.symbolCode.getStatus(); } @@ -185,19 +183,16 @@ public String getStatus() * @param value the new value for the Status/Operational Condition field. * * @throws IllegalArgumentException if the specified value is null or is not one of the accepted status - * values. + * values. */ - public void setStatus(String value) - { - if (value == null) - { + public void setStatus(String value) { + if (value == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!SymbologyConstants.STATUS_ALL.contains(value.toUpperCase())) - { + if (!SymbologyConstants.STATUS_ALL.contains(value.toUpperCase())) { String msg = Logging.getMessage("Symbology.InvalidStatus", value); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -207,13 +202,12 @@ public void setStatus(String value) } /** - * Indicates whether this symbol draws its frame. See {@link #setShowFrame(boolean)} for a description of how this + * Indicates whether this symbol draws its frame. See {@link #setShowFrame(boolean)} for a description of how this * property is used. * * @return true if this symbol draws its frame, otherwise false. */ - public boolean isShowFrame() - { + public boolean isShowFrame() { Object o = this.modifiers.getValue(SymbologyConstants.SHOW_FRAME); return o == null || o.equals(Boolean.TRUE); // No value indicates the default of true. } @@ -229,19 +223,17 @@ public boolean isShowFrame() * * @param showFrame true to draw this symbol's frame, otherwise false. */ - public void setShowFrame(boolean showFrame) - { + public void setShowFrame(boolean showFrame) { this.modifiers.setValue(SymbologyConstants.SHOW_FRAME, showFrame); } /** - * Indicates whether this symbol draws its fill. See {@link #setShowFill(boolean)} for a description of how this + * Indicates whether this symbol draws its fill. See {@link #setShowFill(boolean)} for a description of how this * property is used. * * @return true if this symbol draws its fill, otherwise false. */ - public boolean isShowFill() - { + public boolean isShowFill() { Object o = this.modifiers.getValue(SymbologyConstants.SHOW_FILL); return o == null || o.equals(Boolean.TRUE); // No value indicates the default of true. } @@ -257,19 +249,17 @@ public boolean isShowFill() * * @param showFill true to draw this symbol's fill, otherwise false. */ - public void setShowFill(boolean showFill) - { + public void setShowFill(boolean showFill) { this.modifiers.setValue(SymbologyConstants.SHOW_FILL, showFill); } /** - * Indicates whether this symbol draws its internal icon. See {@link #setShowIcon(boolean)} for a description of - * how this property is used. + * Indicates whether this symbol draws its internal icon. See {@link #setShowIcon(boolean)} for a description of how + * this property is used. * * @return true if this symbol draws its icon, otherwise false. */ - public boolean isShowIcon() - { + public boolean isShowIcon() { Object o = this.modifiers.getValue(SymbologyConstants.SHOW_ICON); return o == null || o.equals(Boolean.TRUE); // No value indicates the default of true. } @@ -285,25 +275,24 @@ public boolean isShowIcon() * * @param showIcon true to draw this symbol's icon, otherwise false. */ - public void setShowIcon(boolean showIcon) - { + public void setShowIcon(boolean showIcon) { this.modifiers.setValue(SymbologyConstants.SHOW_ICON, showIcon); } - protected void initIconLayout() - { + protected void initIconLayout() { MilStd2525Util.SymbolInfo info = MilStd2525Util.computeTacticalSymbolInfo(this.getIdentifier()); - if (info == null) + if (info == null) { return; + } this.iconOffset = info.iconOffset; this.iconSize = info.iconSize; - if (info.offset != null) + if (info.offset != null) { this.setOffset(info.offset); + } - if (info.isGroundSymbol) - { + if (info.isGroundSymbol) { this.isGroundSymbol = true; this.useGroundHeadingIndicator = info.offset == null; this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); @@ -311,65 +300,59 @@ protected void initIconLayout() } @Override - protected AVList assembleIconRetrieverParameters(AVList params) - { - if (params == null) + protected AVList assembleIconRetrieverParameters(AVList params) { + if (params == null) { params = new AVListImpl(); + } super.assembleIconRetrieverParameters(params); Object o = this.modifiers.getValue(SymbologyConstants.SHOW_FILL); - if (o != null) + if (o != null) { params.setValue(SymbologyConstants.SHOW_FILL, o); + } o = this.modifiers.getValue(SymbologyConstants.SHOW_FRAME); - if (o != null) + if (o != null) { params.setValue(SymbologyConstants.SHOW_FRAME, o); + } o = this.modifiers.getValue(SymbologyConstants.SHOW_ICON); - if (o != null) + if (o != null) { params.setValue(SymbologyConstants.SHOW_ICON, o); + } return params; } @Override - protected void applyImplicitModifiers(AVList modifiers) - { + protected void applyImplicitModifiers(AVList modifiers) { String maskedCode = this.symbolCode.toMaskedString().toLowerCase(); String si = this.symbolCode.getStandardIdentity(); // Set the Echelon modifier value according to the value implied by this symbol ID, if any. Give precedence to // the modifier value specified by the application, including null. - if (!modifiers.hasKey(SymbologyConstants.ECHELON)) - { + if (!modifiers.hasKey(SymbologyConstants.ECHELON)) { Object o = symbolEchelonMap.get(maskedCode); - if (o != null) + if (o != null) { modifiers.setValue(SymbologyConstants.ECHELON, o); + } } // Set the Frame Shape modifier value according to the value implied by this symbol ID, if any. Give precedence to // the modifier value specified by the application, including null. - if (!modifiers.hasKey(SymbologyConstants.FRAME_SHAPE)) - { - if (exerciseSymbols.contains(maskedCode)) - { + if (!modifiers.hasKey(SymbologyConstants.FRAME_SHAPE)) { + if (exerciseSymbols.contains(maskedCode)) { modifiers.setValue(SymbologyConstants.FRAME_SHAPE, SymbologyConstants.FRAME_SHAPE_EXERCISE); - } - else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_PENDING) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_UNKNOWN) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_NEUTRAL) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND))) - { + } else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_PENDING) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_UNKNOWN) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_NEUTRAL) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND))) { modifiers.setValue(SymbologyConstants.FRAME_SHAPE, SymbologyConstants.FRAME_SHAPE_EXERCISE); - } - else if (si != null && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_JOKER)) - { + } else if (si != null && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_JOKER)) { modifiers.setValue(SymbologyConstants.FRAME_SHAPE, SymbologyConstants.FRAME_SHAPE_JOKER); - } - else if (si != null && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FAKER)) - { + } else if (si != null && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FAKER)) { modifiers.setValue(SymbologyConstants.FRAME_SHAPE, SymbologyConstants.FRAME_SHAPE_FAKER); } } @@ -377,23 +360,20 @@ else if (si != null && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_ // If this symbol represents a hostile entity, and the "hostile/enemy" indicator is enabled, then set the // hostile modifier to "ENY". boolean isHostile = SymbologyConstants.STANDARD_IDENTITY_HOSTILE.equalsIgnoreCase(si) - || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(si) - || SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(si) - || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(si); - if (!modifiers.hasKey(SymbologyConstants.HOSTILE_ENEMY) && this.isShowHostileIndicator() && isHostile) - { + || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(si) + || SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(si) + || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(si); + if (!modifiers.hasKey(SymbologyConstants.HOSTILE_ENEMY) && this.isShowHostileIndicator() && isHostile) { modifiers.setValue(SymbologyConstants.HOSTILE_ENEMY, SymbologyConstants.HOSTILE_ENEMY); } // Determine location, if location modifier is enabled. - if (!modifiers.hasKey(SymbologyConstants.LOCATION) && this.isShowLocation()) - { + if (!modifiers.hasKey(SymbologyConstants.LOCATION) && this.isShowLocation()) { modifiers.setValue(SymbologyConstants.LOCATION, this.getFormattedPosition()); } // Determine altitude, if location modifier is enabled. - if (!modifiers.hasKey(SymbologyConstants.ALTITUDE_DEPTH) && this.isShowLocation()) - { + if (!modifiers.hasKey(SymbologyConstants.ALTITUDE_DEPTH) && this.isShowLocation()) { Position position = this.getPosition(); UnitsFormat format = this.getUnitsFormat(); @@ -401,19 +381,19 @@ else if (si != null && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_ // the altitude using the active units format, and append the datum. See MIL-STD-2525C section 5.5.2.5.2 (pg. 41). String altitude; int altitudeMode = this.getAltitudeMode(); - if (altitudeMode == WorldWind.CLAMP_TO_GROUND) + if (altitudeMode == WorldWind.CLAMP_TO_GROUND) { altitude = "GL"; - else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) + } else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) { altitude = format.eyeAltitude(position.getElevation()) + " AGL"; - else + } else { altitude = format.eyeAltitude(position.getElevation()) + " AMSL"; + } modifiers.setValue(SymbologyConstants.ALTITUDE_DEPTH, altitude); } } - protected void layoutGraphicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutGraphicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { this.currentGlyphs.clear(); this.currentLines.clear(); @@ -422,63 +402,51 @@ protected void layoutGraphicModifiers(DrawContext dc, AVList modifiers, OrderedS // Feint/Dummy Indicator modifier. Placed above the icon. String modifierCode = this.getModifierCode(modifiers, SymbologyConstants.FEINT_DUMMY); - if (modifierCode != null) - { + if (modifierCode != null) { this.addGlyph(dc, Offset.TOP_CENTER, Offset.BOTTOM_CENTER, modifierCode, retrieverParams, null, osym); } // Installation modifier. Placed at the top of the symbol layout. modifierCode = this.getModifierCode(modifiers, SymbologyConstants.INSTALLATION); - if (modifierCode != null) - { + if (modifierCode != null) { this.addGlyph(dc, Offset.TOP_CENTER, Offset.BOTTOM_CENTER, modifierCode, null, LAYOUT_RELATIVE, osym); } // Echelon / Task Force Indicator modifier. Placed at the top of the symbol layout. modifierCode = this.getModifierCode(modifiers, SymbologyConstants.TASK_FORCE); - if (modifierCode != null) - { + if (modifierCode != null) { this.addGlyph(dc, Offset.TOP_CENTER, Offset.BOTTOM_CENTER, modifierCode, null, LAYOUT_RELATIVE, osym); - } - // Echelon modifier. Placed at the top of the symbol layout. - else if ((modifierCode = this.getModifierCode(modifiers, SymbologyConstants.ECHELON)) != null) - { + } // Echelon modifier. Placed at the top of the symbol layout. + else if ((modifierCode = this.getModifierCode(modifiers, SymbologyConstants.ECHELON)) != null) { this.addGlyph(dc, Offset.TOP_CENTER, Offset.BOTTOM_CENTER, modifierCode, null, LAYOUT_RELATIVE, osym); } // Mobility Indicator modifier. Placed at the bottom of the symbol layout. modifierCode = this.getModifierCode(modifiers, SymbologyConstants.MOBILITY); - if (modifierCode != null) - { + if (modifierCode != null) { this.addGlyph(dc, Offset.BOTTOM_CENTER, Offset.TOP_CENTER, modifierCode, null, LAYOUT_RELATIVE, osym); } // Auxiliary Equipment Indicator modifier. Placed at the bottom of the symbol layout. modifierCode = this.getModifierCode(modifiers, SymbologyConstants.AUXILIARY_EQUIPMENT); - if (modifierCode != null) - { + if (modifierCode != null) { this.addGlyph(dc, Offset.BOTTOM_CENTER, Offset.TOP_CENTER, modifierCode, null, LAYOUT_RELATIVE, osym); } - if (this.mustUseAlternateOperationalCondition(modifiers)) - { + if (this.mustUseAlternateOperationalCondition(modifiers)) { // Alternate Status/Operational Condition. Always used by the Emergency Management scheme (see MIL-STD-2525C // spec section G.5.5.14, pg. 1030). May be used for other schemes if the OPERATIONAL_CONDITION_ALTERNATE // modifier is set. Placed at the bottom of the symbol layout. modifierCode = this.getModifierCode(modifiers, SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE); - if (modifierCode != null) - { + if (modifierCode != null) { this.addGlyph(dc, Offset.BOTTOM_CENTER, Offset.TOP_CENTER, modifierCode, retrieverParams, - LAYOUT_RELATIVE, osym); + LAYOUT_RELATIVE, osym); } - } - else - { + } else { // Status/Operational Condition. Used by all schemes except the Emergency Management scheme. Centered on // the icon. modifierCode = this.getModifierCode(modifiers, SymbologyConstants.OPERATIONAL_CONDITION); - if (modifierCode != null) - { + if (modifierCode != null) { this.addGlyph(dc, Offset.CENTER, Offset.CENTER, modifierCode, null, null, osym); } } @@ -494,49 +462,44 @@ else if ((modifierCode = this.getModifierCode(modifiers, SymbologyConstants.ECHE * * @return True if the symbol must use the alternate operational condition indicator. */ - protected boolean mustUseAlternateOperationalCondition(AVList modifiers) - { + protected boolean mustUseAlternateOperationalCondition(AVList modifiers) { return SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(this.symbolCode.getScheme()) - || modifiers.hasKey(SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE); + || modifiers.hasKey(SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE); } @Override - protected void layoutDynamicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutDynamicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { this.currentLines.clear(); - if (!this.isShowGraphicModifiers()) + if (!this.isShowGraphicModifiers()) { return; + } // Direction of Movement indicator. Placed either at the center of the icon or at the bottom of the symbol // layout. Object o = this.getModifier(SymbologyConstants.DIRECTION_OF_MOVEMENT); - if (o != null && o instanceof Angle) - { + if (o != null && o instanceof Angle) { // The length of the direction of movement line is equal to the height of the symbol frame. See // MIL-STD-2525C section 5.3.4.1.c, page 33. double length = this.iconRect.getHeight(); Object d = this.getModifier(SymbologyConstants.SPEED_LEADER_SCALE); - if (d != null && d instanceof Number) + if (d != null && d instanceof Number) { length *= ((Number) d).doubleValue(); + } - if (this.useGroundHeadingIndicator) - { + if (this.useGroundHeadingIndicator) { List points = MilStd2525Util.computeGroundHeadingIndicatorPoints(dc, osym.placePoint, - (Angle) o, length, this.iconRect.getHeight()); + (Angle) o, length, this.iconRect.getHeight()); this.addLine(dc, Offset.BOTTOM_CENTER, points, LAYOUT_RELATIVE, points.size() - 1, osym); - } - else - { + } else { List points = MilStd2525Util.computeCenterHeadingIndicatorPoints(dc, - osym.placePoint, (Angle) o, length); + osym.placePoint, (Angle) o, length); this.addLine(dc, Offset.CENTER, points, null, 0, osym); } } } - protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { this.currentLabels.clear(); StringBuilder sb = new StringBuilder(); @@ -546,22 +509,21 @@ protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymb // height must be 0.3x the symbol's frame height. Font font = this.getActiveAttributes().getTextModifierFont(); Font frameShapeFont = this.getActiveAttributes().getTextModifierFont(); - if (frameShapeFont == null) + if (frameShapeFont == null) { frameShapeFont = DEFAULT_FRAME_SHAPE_FONT; + } // Quantity modifier layout. Placed at the top of the symbol layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.QUANTITY, 9); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.TOP_CENTER, Offset.BOTTOM_CENTER, sb.toString(), font, null, LAYOUT_RELATIVE, - osym); + osym); sb.delete(0, sb.length()); } // Special C2 Headquarters modifier layout. Centered on the icon. this.appendTextModifier(sb, modifiers, SymbologyConstants.SPECIAL_C2_HEADQUARTERS, 9); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.CENTER, Offset.CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } @@ -569,10 +531,10 @@ protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymb // Frame Shape and Reinforced/Reduced modifier layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.FRAME_SHAPE, null); String s = this.getReinforcedReducedModifier(modifiers, SymbologyConstants.REINFORCED_REDUCED); - if (s != null) + if (s != null) { sb.append(sb.length() > 0 ? " " : "").append(s); - if (sb.length() > 0) - { + } + if (sb.length() > 0) { Offset offset = Offset.fromFraction(1.0, 1.1); this.addLabel(dc, offset, Offset.LEFT_CENTER, sb.toString(), frameShapeFont, null, null, osym); sb.delete(0, sb.length()); @@ -580,24 +542,21 @@ protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymb // Staff Comments modifier layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.STAFF_COMMENTS, 20); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(1.0, 0.8), Offset.LEFT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } // Additional Information modifier layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.ADDITIONAL_INFORMATION, 20); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(1.0, 0.5), Offset.LEFT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } // Higher Formation modifier layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.HIGHER_FORMATION, 21); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(1.0, 0.2), Offset.LEFT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } @@ -609,16 +568,14 @@ protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymb this.appendTextModifier(sb, modifiers, SymbologyConstants.SIGNATURE_EQUIPMENT, 1); this.appendTextModifier(sb, modifiers, SymbologyConstants.HOSTILE_ENEMY, 3); this.appendTextModifier(sb, modifiers, SymbologyConstants.IFF_SIF, 5); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(1.0, -0.1), Offset.LEFT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } // Date-Time-Group (DTG) modifier layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.DATE_TIME_GROUP, 16); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(0.0, 1.1), Offset.RIGHT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } @@ -627,121 +584,120 @@ protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymb this.appendTextModifier(sb, modifiers, SymbologyConstants.ALTITUDE_DEPTH, 14); this.appendTextModifier(sb, modifiers, SymbologyConstants.LOCATION, 19); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(0.0, 0.8), Offset.RIGHT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } // Type modifier layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.TYPE, 24); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(0.0, 0.5), Offset.RIGHT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } // Unique Designation modifier layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.UNIQUE_DESIGNATION, 21); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(0.0, 0.2), Offset.RIGHT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } // Speed modifier layout. this.appendTextModifier(sb, modifiers, SymbologyConstants.SPEED, 8); - if (sb.length() > 0) - { + if (sb.length() > 0) { this.addLabel(dc, Offset.fromFraction(0.0, -0.1), Offset.RIGHT_CENTER, sb.toString(), font, null, null, osym); sb.delete(0, sb.length()); } } @Override - protected int getMaxLabelLines(AVList modifiers) - { + protected int getMaxLabelLines(AVList modifiers) { // Determine how many lines of text are on the left side of the symbol. int leftLines = 0; - if (modifiers.hasKey(SymbologyConstants.DATE_TIME_GROUP)) + if (modifiers.hasKey(SymbologyConstants.DATE_TIME_GROUP)) { leftLines++; - if (modifiers.hasKey(SymbologyConstants.ALTITUDE_DEPTH) || modifiers.hasKey(SymbologyConstants.LOCATION)) + } + if (modifiers.hasKey(SymbologyConstants.ALTITUDE_DEPTH) || modifiers.hasKey(SymbologyConstants.LOCATION)) { leftLines++; - if (modifiers.hasKey(SymbologyConstants.TYPE)) + } + if (modifiers.hasKey(SymbologyConstants.TYPE)) { leftLines++; - if (modifiers.hasKey(SymbologyConstants.UNIQUE_DESIGNATION)) + } + if (modifiers.hasKey(SymbologyConstants.UNIQUE_DESIGNATION)) { leftLines++; - if (modifiers.hasKey(SymbologyConstants.SPEED)) + } + if (modifiers.hasKey(SymbologyConstants.SPEED)) { leftLines++; + } // Determine how many lines of text are on the right side of the symbol. int rightLines = 0; - if (modifiers.hasKey(SymbologyConstants.FRAME_SHAPE) || modifiers.hasKey(SymbologyConstants.REINFORCED_REDUCED)) + if (modifiers.hasKey(SymbologyConstants.FRAME_SHAPE) || modifiers.hasKey(SymbologyConstants.REINFORCED_REDUCED)) { rightLines++; - if (modifiers.hasKey(SymbologyConstants.STAFF_COMMENTS)) + } + if (modifiers.hasKey(SymbologyConstants.STAFF_COMMENTS)) { rightLines++; - if (modifiers.hasKey(SymbologyConstants.ADDITIONAL_INFORMATION)) + } + if (modifiers.hasKey(SymbologyConstants.ADDITIONAL_INFORMATION)) { rightLines++; - if (modifiers.hasKey(SymbologyConstants.HIGHER_FORMATION)) + } + if (modifiers.hasKey(SymbologyConstants.HIGHER_FORMATION)) { rightLines++; + } if (modifiers.hasKey(SymbologyConstants.COMBAT_EFFECTIVENESS) - || modifiers.hasKey(SymbologyConstants.SIGNATURE_EQUIPMENT) - || modifiers.hasKey(SymbologyConstants.HOSTILE_ENEMY) - || modifiers.hasKey(SymbologyConstants.IFF_SIF)) - { + || modifiers.hasKey(SymbologyConstants.SIGNATURE_EQUIPMENT) + || modifiers.hasKey(SymbologyConstants.HOSTILE_ENEMY) + || modifiers.hasKey(SymbologyConstants.IFF_SIF)) { rightLines++; } return Math.max(leftLines, rightLines); } - protected String getModifierCode(AVList modifiers, String modifierKey) - { + protected String getModifierCode(AVList modifiers, String modifierKey) { return SymbolCode.composeSymbolModifierCode(this.symbolCode, modifiers, modifierKey); } - protected String getReinforcedReducedModifier(AVList modifiers, String modifierKey) - { + protected String getReinforcedReducedModifier(AVList modifiers, String modifierKey) { Object o = modifiers.getValue(modifierKey); - if (o != null && o.toString().equalsIgnoreCase(SymbologyConstants.REINFORCED)) + if (o != null && o.toString().equalsIgnoreCase(SymbologyConstants.REINFORCED)) { return "+"; - else if (o != null && o.toString().equalsIgnoreCase(SymbologyConstants.REDUCED)) + } else if (o != null && o.toString().equalsIgnoreCase(SymbologyConstants.REDUCED)) { return "-"; - else if (o != null && o.toString().equalsIgnoreCase(SymbologyConstants.REINFORCED_AND_REDUCED)) + } else if (o != null && o.toString().equalsIgnoreCase(SymbologyConstants.REINFORCED_AND_REDUCED)) { return "+-"; - else + } else { return null; + } } - protected void appendTextModifier(StringBuilder sb, AVList modifiers, String modifierKey, Integer maxLength) - { + protected void appendTextModifier(StringBuilder sb, AVList modifiers, String modifierKey, Integer maxLength) { Object modifierValue = modifiers.getValue(modifierKey); - if (WWUtil.isEmpty(modifierValue)) + if (WWUtil.isEmpty(modifierValue)) { return; + } String modifierText = modifierValue.toString(); int len = maxLength != null && maxLength < modifierText.length() ? maxLength : modifierText.length(); - if (sb.length() > 0) + if (sb.length() > 0) { sb.append(" "); + } sb.append(modifierText, 0, len); } @Override - protected void computeTransform(DrawContext dc, OrderedSymbol osym) - { + protected void computeTransform(DrawContext dc, OrderedSymbol osym) { super.computeTransform(dc, osym); // Compute an appropriate default offset if the application has not specified an offset and this symbol has no // default offset. - if (this.getOffset() == null && this.iconRect != null && osym.layoutRect != null && this.isGroundSymbol) - { + if (this.getOffset() == null && this.iconRect != null && osym.layoutRect != null && this.isGroundSymbol) { osym.dx = -this.iconRect.getCenterX(); osym.dy = -osym.layoutRect.getMinY(); - } - else if (this.getOffset() == null && this.iconRect != null) - { + } else if (this.getOffset() == null && this.iconRect != null) { osym.dx = -this.iconRect.getCenterX(); osym.dy = -this.iconRect.getCenterY(); } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525UnitsFormat.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525UnitsFormat.java index 39b73d8af6..021e6223bc 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525UnitsFormat.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525UnitsFormat.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.geom.*; @@ -15,14 +14,13 @@ * @author pabercrombie * @version $Id: MilStd2525UnitsFormat.java 482 2012-03-27 01:27:15Z pabercrombie $ */ -public class MilStd2525UnitsFormat extends UnitsFormat -{ +public class MilStd2525UnitsFormat extends UnitsFormat { + /** * Construct an instance that displays length in kilometers, area in square kilometers and angles in degrees, * minutes, seconds. */ - public MilStd2525UnitsFormat() - { + public MilStd2525UnitsFormat() { this(UnitsFormat.KILOMETERS, UnitsFormat.SQUARE_KILOMETERS, true); } @@ -31,13 +29,12 @@ public MilStd2525UnitsFormat() * * @param lengthUnits the desired length units. Available length units are METERS, KILOMETERS, MILES, * NAUTICAL_MILES, YARDS and FEET. - * @param areaUnits the desired area units. Available area units are SQUARE_METERS, SQUARE_KILOMETERS, + * @param areaUnits the desired area units. Available area units are SQUARE_METERS, SQUARE_KILOMETERS, * HECTARE, ACRE, SQUARE_YARD and SQUARE_FEET. * * @throws IllegalArgumentException if either lengthUnits or areaUnits is null. */ - public MilStd2525UnitsFormat(String lengthUnits, String areaUnits) - { + public MilStd2525UnitsFormat(String lengthUnits, String areaUnits) { this(lengthUnits, areaUnits, true); } @@ -46,15 +43,14 @@ public MilStd2525UnitsFormat(String lengthUnits, String areaUnits) * * @param lengthUnits the desired length units. Available length units are METERS, KILOMETERS, MILES, * NAUTICAL_MILES, YARDS and FEET. - * @param areaUnits the desired area units. Available area units are SQUARE_METERS, SQUARE_KILOMETERS, + * @param areaUnits the desired area units. Available area units are SQUARE_METERS, SQUARE_KILOMETERS, * HECTARE, ACRE, SQUARE_YARD and SQUARE_FEET. - * @param showDMS true if the desired angle format is degrees-minutes-seconds, false if the format is decimal - * degrees. + * @param showDMS true if the desired angle format is degrees-minutes-seconds, false if the format is decimal + * degrees. * * @throws IllegalArgumentException if either lengthUnits or areaUnits is null. */ - public MilStd2525UnitsFormat(String lengthUnits, String areaUnits, boolean showDMS) - { + public MilStd2525UnitsFormat(String lengthUnits, String areaUnits, boolean showDMS) { super(lengthUnits, areaUnits, showDMS); this.setAltitudeUnits(FEET); } @@ -70,22 +66,17 @@ public MilStd2525UnitsFormat(String lengthUnits, String areaUnits, boolean showD * @throws IllegalArgumentException if the angle is null. */ @Override - public String latitude(Angle angle) - { - if (angle == null) - { + public String latitude(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.isShowDMS()) - { + if (this.isShowDMS()) { double[] dms = angle.toDMS(); return String.format("%02.0f%02.0f%04.1f%s", Math.abs(dms[0]), dms[1], dms[2], dms[0] < 0 ? "S" : "N"); - } - else - { + } else { return super.latitude(angle); } } @@ -101,32 +92,27 @@ public String latitude(Angle angle) * @throws IllegalArgumentException if the angle is null. */ @Override - public String longitude(Angle angle) - { - if (angle == null) - { + public String longitude(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.isShowDMS()) - { + if (this.isShowDMS()) { double[] dms = angle.toDMS(); return String.format("%03.0f%02.0f%04.1f%s", Math.abs(dms[0]), dms[1], dms[2], dms[0] < 0 ? "W" : "E"); - } - else - { + } else { return super.longitude(angle); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public String latLon(LatLon latlon) - { - if (latlon == null) - { + public String latLon(LatLon latlon) { + if (latlon == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -135,20 +121,22 @@ public String latLon(LatLon latlon) return this.latitude(latlon.getLatitude()) + this.longitude(latlon.getLongitude()); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setAltitudeUnits(String altitudeUnits) - { + public void setAltitudeUnits(String altitudeUnits) { super.setAltitudeUnits(altitudeUnits); // Convert the altitude symbol to upper case, as per MIL-STD-2525C section 5.5.2.5.2 (pg. 41). this.altitudeUnitsSymbol = this.altitudeUnitsSymbol.toUpperCase(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void setDefaultLabels() - { + protected void setDefaultLabels() { this.setLabel(LABEL_LATITUDE, ""); this.setLabel(LABEL_LONGITUDE, ""); this.setLabel(LABEL_EYE_ALTITUDE, ""); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525Util.java b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525Util.java index ecb13542a7..127e8b6001 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525Util.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/MilStd2525Util.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.View; @@ -20,8 +19,8 @@ * @author dcollins * @version $Id: MilStd2525Util.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MilStd2525Util -{ +public class MilStd2525Util { + protected static final Offset CLOVER_OFFSET = Offset.fromFraction(0.0625, 0.0625); protected static final Size CLOVER_SIZE = Size.fromFraction(0.890625, 0.890625); protected static final Offset CLOVER_C2_HQ_OFFSET = Offset.fromFraction(0.0, -0.0546875); @@ -65,18 +64,16 @@ public class MilStd2525Util protected static final Size DIAMOND_SIZE = Size.fromFraction(0.90625, 0.90625); protected static final Offset DIAMOND_C2_HQ_OFFSET = Offset.fromFraction(0.0, -0.05172); - public static class SymbolInfo - { + public static class SymbolInfo { + public Offset iconOffset; public Size iconSize; public Offset offset; public boolean isGroundSymbol; } - public static SymbolInfo computeTacticalSymbolInfo(String symbolId) - { - if (symbolId == null) - { + public static SymbolInfo computeTacticalSymbolInfo(String symbolId) { + if (symbolId == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -92,208 +89,161 @@ public static SymbolInfo computeTacticalSymbolInfo(String symbolId) // Clover, Clover Up, and Clover Down. if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_PENDING) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_UNKNOWN) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_PENDING) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_UNKNOWN))) - { + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_UNKNOWN) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_PENDING) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_UNKNOWN))) { // Clover icon. if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_UNKNOWN) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SURFACE) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SOF))) - { + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SURFACE) + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SOF))) { symbolInfo.iconOffset = CLOVER_OFFSET; symbolInfo.iconSize = CLOVER_SIZE; - } - // Clover icon for Special C2 Headquarters symbols. Must appear before Clover icon for Ground symbols. + } // Clover icon for Special C2 Headquarters symbols. Must appear before Clover icon for Ground symbols. else if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING) - && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_UNKNOWN) - && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) - && fi != null && fi.toUpperCase().equalsIgnoreCase("UH----")) - { + && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_UNKNOWN) + && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) + && fi != null && fi.toUpperCase().equalsIgnoreCase("UH----")) { symbolInfo.iconOffset = CLOVER_OFFSET; symbolInfo.iconSize = CLOVER_SIZE; symbolInfo.offset = CLOVER_C2_HQ_OFFSET; symbolInfo.isGroundSymbol = true; - } - // Clover icon for Ground symbols. + } // Clover icon for Ground symbols. else if ((bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND)) - || (scheme != null && (scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS) - || scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)))) - { + || (scheme != null && (scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS) + || scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)))) { symbolInfo.iconOffset = CLOVER_OFFSET; symbolInfo.iconSize = CLOVER_SIZE; symbolInfo.isGroundSymbol = true; - } - // Clover Up icon (Clover without a bottom leaf). + } // Clover Up icon (Clover without a bottom leaf). else if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SPACE) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_AIR))) - { + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_AIR))) { symbolInfo.iconOffset = CLOVER_UP_OFFSET; symbolInfo.iconSize = CLOVER_UP_SIZE; - } - // Clover Down icon (Clover without a top leaf). - else if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SUBSURFACE)) - { + } // Clover Down icon (Clover without a top leaf). + else if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SUBSURFACE)) { symbolInfo.iconOffset = CLOVER_DOWN_OFFSET; symbolInfo.iconSize = CLOVER_DOWN_SIZE; } - } - // Arch Up, Arch Down, Circle, and Rectangle. + } // Arch Up, Arch Down, Circle, and Rectangle. else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_ASSUMED_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_JOKER) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FAKER))) - { + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_ASSUMED_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_JOKER) + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FAKER))) { // Arch Up icon. if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SPACE) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_AIR))) - { + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_AIR))) { symbolInfo.iconOffset = ARCH_UP_OFFSET; symbolInfo.iconSize = ARCH_UP_SIZE; - } - // Arch Down icon. - else if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SUBSURFACE))) - { + } // Arch Down icon. + else if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SUBSURFACE))) { symbolInfo.iconOffset = ARCH_DOWN_OFFSET; symbolInfo.iconSize = ARCH_DOWN_SIZE; - } - // Circle icon. + } // Circle icon. else if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_UNKNOWN) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SURFACE))) - { + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SURFACE))) { symbolInfo.iconOffset = CIRCLE_OFFSET; symbolInfo.iconSize = CIRCLE_SIZE; - } - // Circle icon for Ground Symbols. + } // Circle icon for Ground Symbols. else if ((scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING) - && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) - && fi != null && fi.matches("E.....")) - || (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_INTELLIGENCE) - && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND))) - { + && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) + && fi != null && fi.matches("E.....")) + || (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_INTELLIGENCE) + && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND))) { symbolInfo.iconOffset = CIRCLE_OFFSET; symbolInfo.iconSize = CIRCLE_SIZE; symbolInfo.isGroundSymbol = true; - } - // Rectangle icon. - else if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SOF)) - { + } // Rectangle icon. + else if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SOF)) { symbolInfo.iconOffset = RECTANGLE_OFFSET; symbolInfo.iconSize = RECTANGLE_SIZE; - } - // Rectangle icon for Special C2 Headquarters symbols. Must appear before Rectangle icon for Ground symbols. + } // Rectangle icon for Special C2 Headquarters symbols. Must appear before Rectangle icon for Ground symbols. else if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING) - && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FRIEND) - && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) - && fi != null && fi.equalsIgnoreCase("UH----")) - { + && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_FRIEND) + && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) + && fi != null && fi.equalsIgnoreCase("UH----")) { symbolInfo.iconOffset = RECTANGLE_OFFSET; symbolInfo.iconSize = RECTANGLE_SIZE; symbolInfo.offset = RECTANGLE_C2_HQ_OFFSET; symbolInfo.isGroundSymbol = true; - } - // Rectangle icon for Ground symbols. + } // Rectangle icon for Ground symbols. else if ((scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING) - && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) - && (fi == null || (fi.equalsIgnoreCase("-----") || fi.toUpperCase().matches("U.....") - || fi.toUpperCase().matches("I.....")))) - || (scheme != null && (scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS) - || scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)))) - { + && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) + && (fi == null || (fi.equalsIgnoreCase("-----") || fi.toUpperCase().matches("U.....") + || fi.toUpperCase().matches("I.....")))) + || (scheme != null && (scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS) + || scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)))) { symbolInfo.iconOffset = RECTANGLE_OFFSET; symbolInfo.iconSize = RECTANGLE_SIZE; symbolInfo.isGroundSymbol = true; } - } - // Hat Up, Hat Down, and Square. + } // Hat Up, Hat Down, and Square. else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_NEUTRAL) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_NEUTRAL))) - { + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_EXERCISE_NEUTRAL))) { // Hat Up icon (tall rectangle without a bottom edge). if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SPACE) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_AIR))) - { + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_AIR))) { symbolInfo.iconOffset = HAT_UP_OFFSET; symbolInfo.iconSize = HAT_UP_SIZE; - } - // Hat Down icon (tall rectangle without a top edge). - else if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SUBSURFACE)) - { + } // Hat Down icon (tall rectangle without a top edge). + else if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SUBSURFACE)) { symbolInfo.iconOffset = HAT_DOWN_OFFSET; symbolInfo.iconSize = HAT_DOWN_SIZE; - } - // Square icon. + } // Square icon. else if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_UNKNOWN) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SURFACE) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SOF))) - { + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SURFACE) + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SOF))) { symbolInfo.iconOffset = SQUARE_OFFSET; symbolInfo.iconSize = SQUARE_SIZE; - } - // Square icon for Special C2 Headquarters symbols. Must appear before Square icon for Ground symbols. + } // Square icon for Special C2 Headquarters symbols. Must appear before Square icon for Ground symbols. else if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING) - && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_NEUTRAL) - && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) - && fi != null && fi.equalsIgnoreCase("UH----")) - { + && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_NEUTRAL) + && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) + && fi != null && fi.equalsIgnoreCase("UH----")) { symbolInfo.iconOffset = SQUARE_OFFSET; symbolInfo.iconSize = SQUARE_SIZE; symbolInfo.offset = SQUARE_C2_HQ_OFFSET; symbolInfo.isGroundSymbol = true; - } - // Square icon for Ground symbols. + } // Square icon for Ground symbols. else if ((bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND)) - || (scheme != null && (scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS) - || scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)))) - { + || (scheme != null && (scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS) + || scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)))) { symbolInfo.iconOffset = SQUARE_OFFSET; symbolInfo.iconSize = SQUARE_SIZE; symbolInfo.isGroundSymbol = true; } - } - // Tent Up, Tent Down, Diamond. + } // Tent Up, Tent Down, Diamond. else if (si != null && (si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_HOSTILE) - || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_SUSPECT))) - { + || si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_SUSPECT))) { // Tent Up icon. if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SPACE) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_AIR))) - { + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_AIR))) { symbolInfo.iconOffset = TENT_UP_OFFSET; symbolInfo.iconSize = TENT_UP_SIZE; - } - // Tent Down icon. - else if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SUBSURFACE)) - { + } // Tent Down icon. + else if (bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SUBSURFACE)) { symbolInfo.iconOffset = TENT_DOWN_OFFSET; symbolInfo.iconSize = TENT_DOWN_SIZE; - } - // Diamond icon. + } // Diamond icon. else if (bd != null && (bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_UNKNOWN) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SURFACE) - || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SOF))) - { + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SEA_SURFACE) + || bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_SOF))) { symbolInfo.iconOffset = DIAMOND_OFFSET; symbolInfo.iconSize = DIAMOND_SIZE; - } - // Diamond icon for Special C2 Headquarters symbols. Must appear before Diamond icon for Ground symbols. + } // Diamond icon for Special C2 Headquarters symbols. Must appear before Diamond icon for Ground symbols. else if (scheme != null && scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING) - && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_HOSTILE) - && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) - && fi != null && fi.equalsIgnoreCase("UH----")) - { + && si.equalsIgnoreCase(SymbologyConstants.STANDARD_IDENTITY_HOSTILE) + && bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND) + && fi != null && fi.equalsIgnoreCase("UH----")) { symbolInfo.iconOffset = DIAMOND_OFFSET; symbolInfo.iconSize = DIAMOND_SIZE; symbolInfo.offset = DIAMOND_C2_HQ_OFFSET; symbolInfo.isGroundSymbol = true; - } - // Diamond icon for Ground symbols. + } // Diamond icon for Ground symbols. else if ((bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_GROUND)) - || (scheme != null && (scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS) - || scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)))) - { + || (scheme != null && (scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS) + || scheme.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)))) { symbolInfo.iconOffset = DIAMOND_OFFSET; symbolInfo.iconSize = DIAMOND_SIZE; symbolInfo.isGroundSymbol = true; @@ -307,25 +257,22 @@ else if ((bd != null && bd.equalsIgnoreCase(SymbologyConstants.BATTLE_DIMENSION_ * Compute screen points required to draw a leader line on a tactical symbol. This method returns two points that * will draw a line out from the center of the symbol. * - * @param dc Current draw context. + * @param dc Current draw context. * @param symbolPoint Symbol position in model coordinates. - * @param heading Direction of movement, as a bearing clockwise from North. - * @param length Length of the indicator line, in pixels. + * @param heading Direction of movement, as a bearing clockwise from North. + * @param length Length of the indicator line, in pixels. * * @return List of screen points that describe the speed leader line. */ public static List computeCenterHeadingIndicatorPoints(DrawContext dc, Vec4 symbolPoint, - Angle heading, double length) - { - if (dc == null) - { + Angle heading, double length) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (heading == null) - { + if (heading == null) { String msg = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -339,34 +286,31 @@ public static List computeCenterHeadingIndicatorPoints(DrawCo Vec4 pt2 = view.project(symbolPoint.add3(dir)); return Arrays.asList( - new Point2D.Double(0, 0), - new Point2D.Double(pt2.x - pt1.x, pt2.y - pt1.y)); + new Point2D.Double(0, 0), + new Point2D.Double(pt2.x - pt1.x, pt2.y - pt1.y)); } /** * Compute screen points required to draw a leader line on a tactical ground symbol. This method returns three * points that will draw a line down from the base of the symbol and then out in the direction of movement. * - * @param dc Current draw context. + * @param dc Current draw context. * @param symbolPoint Symbol position in model coordinates. - * @param heading Direction of movement, as a bearing clockwise from North. - * @param length Length of the indicator line, in pixels. + * @param heading Direction of movement, as a bearing clockwise from North. + * @param length Length of the indicator line, in pixels. * @param frameHeight Height of the symbol's bounding rectangle, in pixels. * * @return List of screen points that describe the speed leader line. */ public static List computeGroundHeadingIndicatorPoints(DrawContext dc, Vec4 symbolPoint, - Angle heading, double length, double frameHeight) - { - if (dc == null) - { + Angle heading, double length, double frameHeight) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (heading == null) - { + if (heading == null) { String msg = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -380,25 +324,24 @@ public static List computeGroundHeadingIndicatorPoints(DrawCo Vec4 pt2 = view.project(symbolPoint.add3(dir)); return Arrays.asList( - new Point2D.Double(0, 0), - new Point2D.Double(0, -frameHeight / 2d), - new Point2D.Double(pt2.x - pt1.x, -frameHeight / 2d + (pt2.y - pt1.y))); + new Point2D.Double(0, 0), + new Point2D.Double(0, -frameHeight / 2d), + new Point2D.Double(pt2.x - pt1.x, -frameHeight / 2d + (pt2.y - pt1.y))); } /** * Compute a vector in the direction that a symbol is moving. * - * @param dc Current draw context. + * @param dc Current draw context. * @param symbolPoint Symbol position in model coordinates. - * @param heading Heading as a bearing clockwise from North. - * @param length Length of the leader line, in pixels. The computed vector will have magnitude equal to this - * distance in pixels multiplied by the size of a pixel (in meters) at the position of the symbol - * relative to the current view. + * @param heading Heading as a bearing clockwise from North. + * @param length Length of the leader line, in pixels. The computed vector will have magnitude equal to this + * distance in pixels multiplied by the size of a pixel (in meters) at the position of the symbol relative to the + * current view. * * @return A vector that points in the direction of a symbol's movement. */ - protected static Vec4 computeDirectionOfMovement(DrawContext dc, Vec4 symbolPoint, Angle heading, double length) - { + protected static Vec4 computeDirectionOfMovement(DrawContext dc, Vec4 symbolPoint, Angle heading, double length) { View view = dc.getView(); Globe globe = dc.getGlobe(); @@ -422,35 +365,29 @@ protected static Vec4 computeDirectionOfMovement(DrawContext dc, Vec4 symbolPoin * * @return Default material for the specified symbol. */ - public static Material getDefaultGraphicMaterial(SymbolCode symbolCode) - { - if (symbolCode == null) - { + public static Material getDefaultGraphicMaterial(SymbolCode symbolCode) { + if (symbolCode == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (isObstacle(symbolCode)) + if (isObstacle(symbolCode)) { return MilStd2525Constants.MATERIAL_OBSTACLE; + } String id = symbolCode.getStandardIdentity(); if (SymbologyConstants.STANDARD_IDENTITY_FRIEND.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_ASSUMED_FRIEND.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND.equalsIgnoreCase(id)) - { + || SymbologyConstants.STANDARD_IDENTITY_ASSUMED_FRIEND.equalsIgnoreCase(id) + || SymbologyConstants.STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND.equalsIgnoreCase(id)) { return MilStd2525Constants.MATERIAL_FRIEND; - } - else if (SymbologyConstants.STANDARD_IDENTITY_HOSTILE.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(id)) - { + } else if (SymbologyConstants.STANDARD_IDENTITY_HOSTILE.equalsIgnoreCase(id) + || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(id) + || SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(id) + || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(id)) { return MilStd2525Constants.MATERIAL_HOSTILE; - } - else if (SymbologyConstants.STANDARD_IDENTITY_NEUTRAL.equalsIgnoreCase(id) - || SymbologyConstants.STANDARD_IDENTITY_EXERCISE_NEUTRAL.equalsIgnoreCase(id)) - { + } else if (SymbologyConstants.STANDARD_IDENTITY_NEUTRAL.equalsIgnoreCase(id) + || SymbologyConstants.STANDARD_IDENTITY_EXERCISE_NEUTRAL.equalsIgnoreCase(id)) { return MilStd2525Constants.MATERIAL_NEUTRAL; } @@ -466,10 +403,10 @@ else if (SymbologyConstants.STANDARD_IDENTITY_NEUTRAL.equalsIgnoreCase(id) * * @return True if the symbol code represents an obstacle, otherwise false. */ - protected static boolean isObstacle(SymbolCode symbolCode) - { - if (symbolCode == null) + protected static boolean isObstacle(SymbolCode symbolCode) { + if (symbolCode == null) { return false; + } String scheme = symbolCode.getScheme(); String category = symbolCode.getCategory(); @@ -477,7 +414,7 @@ protected static boolean isObstacle(SymbolCode symbolCode) // Obstacle function IDs start with "O". return SymbologyConstants.SCHEME_TACTICAL_GRAPHICS.equalsIgnoreCase(scheme) - && SymbologyConstants.CATEGORY_MOBILITY_SURVIVABILITY.equalsIgnoreCase(category) - && (functionId.charAt(0) == 'o' || functionId.charAt(0) == 'O'); + && SymbologyConstants.CATEGORY_MOBILITY_SURVIVABILITY.equalsIgnoreCase(category) + && (functionId.charAt(0) == 'o' || functionId.charAt(0) == 'O'); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/SymbolCode.java b/src/gov/nasa/worldwind/symbology/milstd2525/SymbolCode.java index cda1ff086a..b4c59346e1 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/SymbolCode.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/SymbolCode.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525; import gov.nasa.worldwind.avlist.*; @@ -27,26 +26,34 @@ *

              * Which fields are populated after parsing a symbol code depends on the MIL-STD-2525 symbology set the symbol code * belongs to: - *

              2525 Graphics Modifiers
              FieldModifier + * keyData typeDescription
              ASymbologyConstants.SYMBOLStringSIDC for a MIL-STD-2525 Tactical Symbol
              BSymbologyConstants.ECHELONStringEchelon
              CSymbologyConstants.QUANTITYStringQuantity
              - * - * - * - * + *
              Populated Fields
              Symbology SetCoding SchemeStandard IdentityBattle - * DimensionCategoryStatusFunction IDSymbol ModifierEchelonCountry - * CodeOrder of Battle
              WarfightingYESYESYESNOYESYESYESNOYESYES
              Tactical GraphicsYESYESNOYESYESYESNOYESYESYES
              Signals IntelligenceYESYESYESNOYESYESNONOYESYES
              Stability OperationsYESYESNOYESYESYESYESNOYESYES
              Emergency ManagementYESYESNOYESYESYESYESNOYESYES
              + * + * + * + * + * *
              Populated Fields
              Symbology SetCoding + * SchemeStandard IdentityBattle DimensionCategoryStatusFunction + * IDSymbol ModifierEchelonCountry CodeOrder of Battle
              WarfightingYESYESYESNOYESYESYESNOYESYES
              Tactical + * GraphicsYESYESNOYESYESYESNOYESYESYES
              Signals + * IntelligenceYESYESYESNOYESYESNONOYESYES
              Stability + * OperationsYESYESNOYESYESYESYESNOYESYES
              Emergency + * ManagementYESYESNOYESYESYESYESNOYESYES
              * * @author pabercrombie * @version $Id: SymbolCode.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SymbolCode extends AVListImpl -{ - /** Indicates the character for an unused position in a MIL-STD-2525 symbol identification code */ +public class SymbolCode extends AVListImpl { + + /** + * Indicates the character for an unused position in a MIL-STD-2525 symbol identification code + */ protected static final String UNUSED_POSITION_CODE = "-"; - /** Creates a new symbol code, but otherwise does nothing. All fields are initialized to null. */ - public SymbolCode() - { + /** + * Creates a new symbol code, but otherwise does nothing. All fields are initialized to null. + */ + public SymbolCode() { // Intentionally left blank. All symbol code fields are null by default. } @@ -62,27 +69,23 @@ public SymbolCode() * @param symCode the symbol identification code to parse. * * @throws IllegalArgumentException if the symCode is null or has a length other than 15. - * @throws WWUnrecognizedException if any field in the symCode is invalid or cannot be recognized. + * @throws WWUnrecognizedException if any field in the symCode is invalid or cannot be recognized. */ - public SymbolCode(String symCode) - { - if (symCode == null) - { + public SymbolCode(String symCode) { + if (symCode == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (symCode.length() != 15) - { + if (symCode.length() != 15) { String msg = Logging.getMessage("Symbology.SymbolCodeLengthInvalid", symCode); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } String s = this.parseSymCode(symCode); - if (s != null) - { + if (s != null) { // A non-null return value indicates the symCode is unrecognized, and contains a message indicating the // problematic fields. Logging.logger().severe(s); @@ -97,21 +100,19 @@ public SymbolCode(String symCode) * * @see #setScheme(String) */ - public String getScheme() - { + public String getScheme() { return this.getStringValue(SymbologyConstants.SCHEME); } /** - * Specifies this symbol code's Coding Scheme field. A symbol code's Coding Scheme defines the specific - * MIL-STD-2525 symbology set that it belongs to. The value must be null or one of the following: + * Specifies this symbol code's Coding Scheme field. A symbol code's Coding Scheme defines the specific MIL-STD-2525 + * symbology set that it belongs to. The value must be null or one of the following: *

              • SCHEME_WARFIGHTING
              • SCHEME_TACTICAL_GRAPHICS
              • SCHEME_METOC
              • *
              • SCHEME_INTELLIGENCE
              • SCHEME_STABILITY_OPERATIONS
              • SCHEME_EMERGENCY_MANAGEMENT
              * * @param value the new value for the Coding Scheme field. May be null. */ - public void setScheme(String value) - { + public void setScheme(String value) { this.setValue(SymbologyConstants.SCHEME, value); } @@ -122,15 +123,15 @@ public void setScheme(String value) * * @see #setStandardIdentity(String) */ - public String getStandardIdentity() - { + public String getStandardIdentity() { return this.getStringValue(SymbologyConstants.STANDARD_IDENTITY); } /** * Specifies this symbol code's Standard Identity field. A symbol code's Standard Identity defines the threat posed * by the object being represented. The value must be null or one of the following: - *
              • STANDARD_IDENTITY_PENDING
              • STANDARD_IDENTITY_UNKNOWN
              • STANDARD_IDENTITY_ASSUMED_FRIEND
              • + *
                • STANDARD_IDENTITY_PENDING
                • STANDARD_IDENTITY_UNKNOWN
                • + *
                • STANDARD_IDENTITY_ASSUMED_FRIEND
                • *
                • STANDARD_IDENTITY_FRIEND
                • STANDARD_IDENTITY_NEUTRAL
                • STANDARD_IDENTITY_SUSPECT
                • *
                • STANDARD_IDENTITY_HOSTILE
                • STANDARD_IDENTITY_EXERCISE_PENDING
                • *
                • STANDARD_IDENTITY_EXERCISE_UNKNOWN
                • STANDARD_IDENTITY_EXERCISE_ASSUMED_FRIEND
                • @@ -139,8 +140,7 @@ public String getStandardIdentity() * * @param value the new value for the Standard Identity field. May be null. */ - public void setStandardIdentity(String value) - { + public void setStandardIdentity(String value) { this.setValue(SymbologyConstants.STANDARD_IDENTITY, value); } @@ -151,8 +151,7 @@ public void setStandardIdentity(String value) * * @see #setBattleDimension(String) */ - public String getBattleDimension() - { + public String getBattleDimension() { return this.getStringValue(SymbologyConstants.BATTLE_DIMENSION); } @@ -165,8 +164,7 @@ public String getBattleDimension() * * @param value the new value for the Battle Dimension field. May be null. */ - public void setBattleDimension(String value) - { + public void setBattleDimension(String value) { this.setValue(SymbologyConstants.BATTLE_DIMENSION, value); } @@ -177,8 +175,7 @@ public void setBattleDimension(String value) * * @see #setCategory(String) */ - public String getCategory() - { + public String getCategory() { return this.getStringValue(SymbologyConstants.CATEGORY); } @@ -202,8 +199,7 @@ public String getCategory() * * @param value the new value for the Category field. May be null. */ - public void setCategory(String value) - { + public void setCategory(String value) { this.setValue(SymbologyConstants.CATEGORY, value); } @@ -214,8 +210,7 @@ public void setCategory(String value) * * @see #setStatus(String) */ - public String getStatus() - { + public String getStatus() { return this.getStringValue(SymbologyConstants.STATUS); } @@ -237,8 +232,7 @@ public String getStatus() * * @param value the new value for the Status/Operational Condition field. May be null. */ - public void setStatus(String value) - { + public void setStatus(String value) { this.setValue(SymbologyConstants.STATUS, value); } @@ -249,8 +243,7 @@ public void setStatus(String value) * * @see #setFunctionId(String) */ - public String getFunctionId() - { + public String getFunctionId() { return this.getStringValue(SymbologyConstants.FUNCTION_ID); } @@ -265,8 +258,7 @@ public String getFunctionId() * * @param value the new value for the Function ID field. May be null. */ - public void setFunctionId(String value) - { + public void setFunctionId(String value) { this.setValue(SymbologyConstants.FUNCTION_ID, value); } @@ -277,8 +269,7 @@ public void setFunctionId(String value) * * @see #setSymbolModifier(String) */ - public String getSymbolModifier() - { + public String getSymbolModifier() { return this.getStringValue(SymbologyConstants.SYMBOL_MODIFIER); } @@ -294,8 +285,7 @@ public String getSymbolModifier() * * @param value the new value for the Symbol Modifier field. May be null. */ - public void setSymbolModifier(String value) - { + public void setSymbolModifier(String value) { this.setValue(SymbologyConstants.SYMBOL_MODIFIER, value); } @@ -306,8 +296,7 @@ public void setSymbolModifier(String value) * * @see #setEchelon(String) */ - public String getEchelon() - { + public String getEchelon() { return this.getStringValue(SymbologyConstants.ECHELON); } @@ -322,8 +311,7 @@ public String getEchelon() * * @param value the new value for the Echelon field. May be null. */ - public void setEchelon(String value) - { + public void setEchelon(String value) { this.setValue(SymbologyConstants.ECHELON, value); } @@ -334,8 +322,7 @@ public void setEchelon(String value) * * @see #setCountryCode(String) */ - public String getCountryCode() - { + public String getCountryCode() { return this.getStringValue(SymbologyConstants.COUNTRY_CODE); } @@ -346,8 +333,7 @@ public String getCountryCode() * * @param value the new value for the Country Code field. May be null. */ - public void setCountryCode(String value) - { + public void setCountryCode(String value) { this.setValue(SymbologyConstants.COUNTRY_CODE, value); } @@ -358,8 +344,7 @@ public void setCountryCode(String value) * * @see #setOrderOfBattle(String) */ - public String getOrderOfBattle() - { + public String getOrderOfBattle() { return this.getStringValue(SymbologyConstants.ORDER_OF_BATTLE); } @@ -370,7 +355,8 @@ public String getOrderOfBattle() *

                  * Warfighting, Signals Intelligence, Stability Operations, Emergency Management *

                  • ORDER_OF_BATTLE_AIR
                  • ORDER_OF_BATTLE_ELECTRONIC
                  • ORDER_OF_BATTLE_CIVILIAN
                  • - *
                  • ORDER_OF_BATTLE_GROUND
                  • ORDER_OF_BATTLE_MARITIME
                  • ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED
                  • + *
                  • ORDER_OF_BATTLE_GROUND
                  • ORDER_OF_BATTLE_MARITIME
                  • + *
                  • ORDER_OF_BATTLE_STRATEGIC_FORCE_RELATED
                  • *
                  *

                  * Tactical Graphics @@ -378,8 +364,7 @@ public String getOrderOfBattle() * * @param value the new value for the Order of Battle field. May be null. */ - public void setOrderOfBattle(String value) - { + public void setOrderOfBattle(String value) { this.setValue(SymbologyConstants.ORDER_OF_BATTLE, value); } @@ -390,8 +375,7 @@ public void setOrderOfBattle(String value) * * @see #setStaticDynamic(String) */ - public String getStaticDynamic() - { + public String getStaticDynamic() { return this.getStringValue(SymbologyConstants.STATIC_DYNAMIC); } @@ -401,8 +385,7 @@ public String getStaticDynamic() * * @param value the new value for the Static/Dynamic field. May be null. */ - public void setStaticDynamic(String value) - { + public void setStaticDynamic(String value) { this.setValue(SymbologyConstants.STATIC_DYNAMIC, value); } @@ -413,8 +396,7 @@ public void setStaticDynamic(String value) * * @see #setStaticDynamic(String) */ - public String getGraphicType() - { + public String getGraphicType() { return this.getStringValue(SymbologyConstants.GRAPHIC_TYPE); } @@ -424,8 +406,7 @@ public String getGraphicType() * * @param value the new value for the Graphic Type field. May be null. */ - public void setGraphicType(String value) - { + public void setGraphicType(String value) { this.setValue(SymbologyConstants.GRAPHIC_TYPE, value); } @@ -439,10 +420,9 @@ public void setGraphicType(String value) * This returns null if this SymbolCode's Coding Scheme is null or unrecognized. * * @return the MIL-STD-2525 15-character symbol identification code (SIDC) corresponding to this SymbolCode, or - * null if the Coding Scheme is unrecognized. + * null if the Coding Scheme is unrecognized. */ - public String toString() - { + public String toString() { return this.composeSymCode(); } @@ -454,8 +434,7 @@ public String toString() * * @return String representation of the symbol code with some fields replaced with hyphens. */ - public String toMaskedString() - { + public String toMaskedString() { SymbolCode masked = new SymbolCode(); masked.setValues(this); @@ -475,14 +454,16 @@ public String toMaskedString() * schemes: echelon, headquarters, task force, feint/dummy, installation, equipment mobility, and auxiliary * equipment. This adds modifier keys only for those modifiers present in the SymbolModifier field. Any modifiers * not in the SymbolModifier field are ignored. The following key-value pairs are used to indicate each modifier: - * - * + * + *
                  Key Value Pairs
                  ModifierKeyValue
                  EchelonSymbologyConstants.ECHELONSee - * {@link SymbologyConstants#ECHELON}
                  HeadquartersSymbologyConstants.HEADQUARTERSBoolean.TRUE - * or null
                  Task ForceSymbologyConstants.TASK_FORCEBoolean.TRUE or - * null
                  Feint/DummySymbologyConstants.FEINT_DUMMYBoolean.TRUE or - * null
                  InstallationSymbologyConstants.INSTALLATIONSee {@link - * SymbologyConstants#INSTALLATION}
                  Equipment MobilitySymbologyConstants.MOBILITYSee - * {@link SymbologyConstants#MOBILITY}
                  Auxiliary EquipmentSymbologyConstants.AUXILIARY_EQUIPMENTSee + * + * + * + * + * + * + * + *
                  Key Value Pairs
                  ModifierKeyValue
                  EchelonSymbologyConstants.ECHELONSee {@link SymbologyConstants#ECHELON}
                  HeadquartersSymbologyConstants.HEADQUARTERSBoolean.TRUE or null
                  Task ForceSymbologyConstants.TASK_FORCEBoolean.TRUE or null
                  Feint/DummySymbologyConstants.FEINT_DUMMYBoolean.TRUE or null
                  InstallationSymbologyConstants.INSTALLATIONSee {@link + * SymbologyConstants#INSTALLATION}
                  Equipment + * MobilitySymbologyConstants.MOBILITYSee {@link SymbologyConstants#MOBILITY}
                  Auxiliary EquipmentSymbologyConstants.AUXILIARY_EQUIPMENTSee * {@link SymbologyConstants#AUXILIARY_EQUIPMENT}
                  *

                  * Note that the installation modifier code indicates that an installation is either a normal installation or a @@ -490,19 +471,20 @@ public String toMaskedString() * Boolean.TRUE. This provides a consistent way to identify feint/dummy modifier status for both units/equipment and * installations. * - * @param code the symbol modifier code to parse. + * @param code the symbol modifier code to parse. * @param params a parameter list in which to place the modifier key-value pairs, or null to allocate - * and return a new parameter list. + * and return a new parameter list. * * @return a parameter list containing the modifier key-value pairs. */ - public static AVList parseSymbolModifierCode(String code, AVList params) - { - if (code == null || code.length() != 2 || code.equals("--")) + public static AVList parseSymbolModifierCode(String code, AVList params) { + if (code == null || code.length() != 2 || code.equals("--")) { return params; + } - if (params == null) + if (params == null) { params = new AVListImpl(); + } String firstChar = code.substring(0, 1); String secondChar = code.substring(1, 2); @@ -511,27 +493,28 @@ public static AVList parseSymbolModifierCode(String code, AVList params) String uppercaseSecondChar = secondChar.toUpperCase(); if (SymbologyConstants.MODIFIER_CODE_ALL_UEI.contains(uppercaseFirstChar) - || UNUSED_POSITION_CODE.equals(uppercaseFirstChar)) - { + || UNUSED_POSITION_CODE.equals(uppercaseFirstChar)) { // The symbol modifier code indicates units and equipment modifiers. The first character is either unused or // indicates the symbol's headquarters, task force, and feint/dummy status. MIL-STD-2525 supports any // combination of the headquarters, task force, and feint/dummy states, so we check for each independently. // The second character is either unused or indicates the symbol's echelon. - if (SymbologyConstants.ECHELON_ALL.contains(uppercaseSecondChar)) + if (SymbologyConstants.ECHELON_ALL.contains(uppercaseSecondChar)) { params.setValue(SymbologyConstants.ECHELON, secondChar); + } - if (SymbologyConstants.MODIFIER_CODE_ALL_HEADQUARTERS.contains(uppercaseFirstChar)) + if (SymbologyConstants.MODIFIER_CODE_ALL_HEADQUARTERS.contains(uppercaseFirstChar)) { params.setValue(SymbologyConstants.HEADQUARTERS, Boolean.TRUE); + } - if (SymbologyConstants.MODIFIER_CODE_ALL_TASK_FORCE.contains(uppercaseFirstChar)) + if (SymbologyConstants.MODIFIER_CODE_ALL_TASK_FORCE.contains(uppercaseFirstChar)) { params.setValue(SymbologyConstants.TASK_FORCE, Boolean.TRUE); + } - if (SymbologyConstants.MODIFIER_CODE_ALL_FEINT_DUMMY.contains(uppercaseFirstChar)) + if (SymbologyConstants.MODIFIER_CODE_ALL_FEINT_DUMMY.contains(uppercaseFirstChar)) { params.setValue(SymbologyConstants.FEINT_DUMMY, Boolean.TRUE); - } - else if (SymbologyConstants.INSTALLATION_ALL.contains(uppercaseCode)) - { + } + } else if (SymbologyConstants.INSTALLATION_ALL.contains(uppercaseCode)) { // The symbol modifier code indicates an installation modifier. Currently, this must either be a normal // installation or a feint/dummy installation. Though the installation modifier code indicates that an // installation is a feint/dummy, we check for this case and set the FEINT_DUMMY modifier key to TRUE. This @@ -539,98 +522,80 @@ else if (SymbologyConstants.INSTALLATION_ALL.contains(uppercaseCode)) params.setValue(SymbologyConstants.INSTALLATION, code); - if (SymbologyConstants.INSTALLATION_FEINT_DUMMY.equalsIgnoreCase(code)) + if (SymbologyConstants.INSTALLATION_FEINT_DUMMY.equalsIgnoreCase(code)) { params.setValue(SymbologyConstants.FEINT_DUMMY, Boolean.TRUE); - } - else if (SymbologyConstants.MOBILITY_ALL.contains(uppercaseCode)) - { + } + } else if (SymbologyConstants.MOBILITY_ALL.contains(uppercaseCode)) { // The symbol modifier code indicates an equipment mobility modifier. params.setValue(SymbologyConstants.MOBILITY, code); - } - else if (SymbologyConstants.AUXILIARY_EQUIPMENT_ALL.contains(uppercaseCode)) - { + } else if (SymbologyConstants.AUXILIARY_EQUIPMENT_ALL.contains(uppercaseCode)) { // The symbol modifier code indicates an auxiliary equipment modifier. Currently, this is limited to the // towed sonar array modifier. params.setValue(SymbologyConstants.AUXILIARY_EQUIPMENT, code); - } - else if (SymbologyConstants.OPERATIONAL_CONDITION_ALL.contains(uppercaseCode)) - { + } else if (SymbologyConstants.OPERATIONAL_CONDITION_ALL.contains(uppercaseCode)) { params.setValue(SymbologyConstants.OPERATIONAL_CONDITION, code); - } - else if (SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE_ALL.contains(uppercaseCode)) - { + } else if (SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE_ALL.contains(uppercaseCode)) { params.setValue(SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE, code); } return params; } - public static String composeSymbolModifierCode(SymbolCode symbolCode, AVList modifiers, String modifierKey) - { - if (symbolCode == null) + public static String composeSymbolModifierCode(SymbolCode symbolCode, AVList modifiers, String modifierKey) { + if (symbolCode == null) { return null; + } - if (modifiers == null || modifierKey == null) + if (modifiers == null || modifierKey == null) { return null; + } Object modifierValue = modifiers.getValue(modifierKey); String uppercaseValue = modifierValue != null ? modifierValue.toString().toUpperCase() : null; if (SymbologyConstants.ECHELON.equalsIgnoreCase(modifierKey) - && SymbologyConstants.ECHELON_ALL.contains(uppercaseValue)) - { + && SymbologyConstants.ECHELON_ALL.contains(uppercaseValue)) { return UNUSED_POSITION_CODE + uppercaseValue; - } - else if (SymbologyConstants.TASK_FORCE.equalsIgnoreCase(modifierKey) && Boolean.TRUE.equals(modifierValue)) - { + } else if (SymbologyConstants.TASK_FORCE.equalsIgnoreCase(modifierKey) && Boolean.TRUE.equals(modifierValue)) { Object echelonValue = modifiers.getValue(SymbologyConstants.ECHELON); - if (echelonValue != null && SymbologyConstants.ECHELON_ALL.contains(echelonValue.toString().toUpperCase())) + if (echelonValue != null && SymbologyConstants.ECHELON_ALL.contains(echelonValue.toString().toUpperCase())) { return SymbologyConstants.MODIFIER_CODE_TASK_FORCE + echelonValue.toString().toUpperCase(); - else + } else { return SymbologyConstants.MODIFIER_CODE_TASK_FORCE + UNUSED_POSITION_CODE; - } - else if (SymbologyConstants.FEINT_DUMMY.equalsIgnoreCase(modifierKey) && Boolean.TRUE.equals(modifierValue)) - { + } + } else if (SymbologyConstants.FEINT_DUMMY.equalsIgnoreCase(modifierKey) && Boolean.TRUE.equals(modifierValue)) { return SymbologyConstants.MODIFIER_CODE_FEINT_DUMMY + UNUSED_POSITION_CODE; - } - else if (SymbologyConstants.INSTALLATION.equalsIgnoreCase(modifierKey) - && SymbologyConstants.INSTALLATION_ALL.contains(uppercaseValue)) - { + } else if (SymbologyConstants.INSTALLATION.equalsIgnoreCase(modifierKey) + && SymbologyConstants.INSTALLATION_ALL.contains(uppercaseValue)) { return SymbologyConstants.INSTALLATION_NORMAL; - } - else if (SymbologyConstants.MOBILITY.equalsIgnoreCase(modifierKey) - && SymbologyConstants.MOBILITY_ALL.contains(uppercaseValue)) - { + } else if (SymbologyConstants.MOBILITY.equalsIgnoreCase(modifierKey) + && SymbologyConstants.MOBILITY_ALL.contains(uppercaseValue)) { return uppercaseValue; - } - else if (SymbologyConstants.AUXILIARY_EQUIPMENT.equalsIgnoreCase(modifierKey) - && SymbologyConstants.AUXILIARY_EQUIPMENT_ALL.contains(uppercaseValue)) - { + } else if (SymbologyConstants.AUXILIARY_EQUIPMENT.equalsIgnoreCase(modifierKey) + && SymbologyConstants.AUXILIARY_EQUIPMENT_ALL.contains(uppercaseValue)) { return uppercaseValue; - } - else if (SymbologyConstants.OPERATIONAL_CONDITION.equalsIgnoreCase(modifierKey)) - { + } else if (SymbologyConstants.OPERATIONAL_CONDITION.equalsIgnoreCase(modifierKey)) { Object status = symbolCode.getStatus(); String uppercaseStatus = (status != null ? status.toString().toUpperCase() : null); - if (SymbologyConstants.STATUS_DAMAGED.equalsIgnoreCase(uppercaseStatus)) + if (SymbologyConstants.STATUS_DAMAGED.equalsIgnoreCase(uppercaseStatus)) { return SymbologyConstants.OPERATIONAL_CONDITION_DAMAGED; - else if (SymbologyConstants.STATUS_DESTROYED.equalsIgnoreCase(uppercaseStatus)) + } else if (SymbologyConstants.STATUS_DESTROYED.equalsIgnoreCase(uppercaseStatus)) { return SymbologyConstants.OPERATIONAL_CONDITION_DESTROYED; - } - else if (SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE.equalsIgnoreCase(modifierKey)) - { + } + } else if (SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE.equalsIgnoreCase(modifierKey)) { Object status = symbolCode.getStatus(); String uppercaseStatus = (status != null ? status.toString().toUpperCase() : null); - if (SymbologyConstants.STATUS_FULLY_CAPABLE.equalsIgnoreCase(uppercaseStatus)) + if (SymbologyConstants.STATUS_FULLY_CAPABLE.equalsIgnoreCase(uppercaseStatus)) { return SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE_FULLY_CAPABLE; - else if (SymbologyConstants.STATUS_DAMAGED.equalsIgnoreCase(uppercaseStatus)) + } else if (SymbologyConstants.STATUS_DAMAGED.equalsIgnoreCase(uppercaseStatus)) { return SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE_DAMAGED; - else if (SymbologyConstants.STATUS_DESTROYED.equalsIgnoreCase(uppercaseStatus)) + } else if (SymbologyConstants.STATUS_DESTROYED.equalsIgnoreCase(uppercaseStatus)) { return SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE_DESTROYED; - else if (SymbologyConstants.STATUS_FULL_TO_CAPACITY.equalsIgnoreCase(uppercaseStatus)) + } else if (SymbologyConstants.STATUS_FULL_TO_CAPACITY.equalsIgnoreCase(uppercaseStatus)) { return SymbologyConstants.OPERATIONAL_CONDITION_ALTERNATE_FULL_TO_CAPACITY; + } } return null; @@ -641,42 +606,28 @@ else if (SymbologyConstants.STATUS_FULL_TO_CAPACITY.equalsIgnoreCase(uppercaseSt * each field. Fields that are either not part of the specified symbol code or are unspecified are left unchanged. * * @param symCode the symbol code to parse. Must be non-null and have length of 15 or greater. Any - * characters after the 15th character are ignored. + * characters after the 15th character are ignored. * * @return null if the symbol code is recognized, otherwise a non-null string listing the - * unrecognized symbol code fields. + * unrecognized symbol code fields. */ - protected String parseSymCode(String symCode) - { + protected String parseSymCode(String symCode) { // Coding Scheme (position 1). String scheme = symCode.substring(0, 1); - if (SymbologyConstants.SCHEME_WARFIGHTING.equalsIgnoreCase(scheme)) - { + if (SymbologyConstants.SCHEME_WARFIGHTING.equalsIgnoreCase(scheme)) { return this.parseWarfightingSymCode(symCode); - } - else if (SymbologyConstants.SCHEME_TACTICAL_GRAPHICS.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_TACTICAL_GRAPHICS.equalsIgnoreCase(scheme)) { return this.parseTacticalGraphicsSymCode(symCode); - } - else if (SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(scheme)) { return this.parseMetocSymCode(symCode); - } - else if (SymbologyConstants.SCHEME_INTELLIGENCE.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_INTELLIGENCE.equalsIgnoreCase(scheme)) { return this.parseIntelligenceSymCode(symCode); - } - else if (SymbologyConstants.SCHEME_STABILITY_OPERATIONS.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_STABILITY_OPERATIONS.equalsIgnoreCase(scheme)) { return this.parseStabilityOperationsSymCode(symCode); - } - else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme)) { return this.parseEmergencyManagementSymCode(symCode); - } - else - { + } else { return this.parseUnrecognizedSymCode(symCode); } } @@ -688,8 +639,7 @@ else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme) * * @return an error string. */ - protected String parseUnrecognizedSymCode(String symCode) - { + protected String parseUnrecognizedSymCode(String symCode) { // Return a message indicating that the symCode's scheme is not recognized. String scheme = symCode.substring(0, 1); return Logging.getMessage("Symbology.SymbolCodeSchemeUnrecognized", scheme, symCode); @@ -704,74 +654,83 @@ protected String parseUnrecognizedSymCode(String symCode) * The Warfighting coding scheme is defined in MIL-STD-2525C table A-I (page 51). * * @param symCode the symbol code to parse. Must be non-null and have length of 15 or greater. Any - * characters after the 15th character are ignored. + * characters after the 15th character are ignored. * * @return null if the symbol code is recognized, otherwise a non-null string listing the - * unrecognized symbol code fields. + * unrecognized symbol code fields. */ - protected String parseWarfightingSymCode(String symCode) - { + protected String parseWarfightingSymCode(String symCode) { StringBuilder sb = new StringBuilder(); // Coding Scheme (position 1). String s = symCode.substring(0, 1); - if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING)) + if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_WARFIGHTING)) { this.setScheme(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.scheme")); + } // Standard Identity/Exercise Amplifying Descriptor (position 2). s = symCode.substring(1, 2); - if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) { this.setStandardIdentity(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.standardIdentity")); + } // Battle Dimension (position 3). s = symCode.substring(2, 3); - if (SymbologyConstants.BATTLE_DIMENSION_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.BATTLE_DIMENSION_ALL.contains(s.toUpperCase())) { this.setBattleDimension(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.battleDimension")); + } // Status/Operational Condition (position 4). s = symCode.substring(3, 4); - if (SymbologyConstants.STATUS_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) + if (SymbologyConstants.STATUS_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) { this.setStatus(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.status")); + } // Function ID (positions 5-10). s = symCode.substring(4, 10); if (!"------".equals(s)) // "------" is accepted and indicates a null function ID. + { this.setFunctionId(s); + } // Symbol Modifier (positions 11-12). s = symCode.substring(10, 12); if (this.isUnitsAndEquipmentSymbolModifier(s) - || SymbologyConstants.INSTALLATION_ALL.contains(s.toUpperCase()) - || SymbologyConstants.MOBILITY_ALL.contains(s.toUpperCase()) - || SymbologyConstants.AUXILIARY_EQUIPMENT_ALL.contains(s.toUpperCase())) - { + || SymbologyConstants.INSTALLATION_ALL.contains(s.toUpperCase()) + || SymbologyConstants.MOBILITY_ALL.contains(s.toUpperCase()) + || SymbologyConstants.AUXILIARY_EQUIPMENT_ALL.contains(s.toUpperCase())) { this.setSymbolModifier(s); - } - else if (!"--".equals(s)) // "--" is accepted and indicates a null symbol modifier. + } else if (!"--".equals(s)) // "--" is accepted and indicates a null symbol modifier. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.symbolModifier")); + } // Country Code (positions 13-14). s = symCode.substring(12, 14); if (!"--".equals(s)) // "--" is accepted and indicates a null country code. + { this.setCountryCode(s); + } // Order Of Battle (position 15). s = symCode.substring(14, 15); - if (SymbologyConstants.ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) + if (SymbologyConstants.ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) { this.setOrderOfBattle(s); - else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + } else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.orderOfBattle")); + } return sb.length() > 0 - ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; + ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; } /** @@ -783,69 +742,80 @@ else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle * The Tactical Graphics coding scheme is defined in MIL-STD-2525C table B-I (page 305). * * @param symCode the symbol code to parse. Must be non-null and have length of 15 or greater. Any - * characters after the 15th character are ignored. + * characters after the 15th character are ignored. * * @return null if the symbol code is recognized, otherwise a non-null string listing the - * unrecognized symbol elements. + * unrecognized symbol elements. */ - protected String parseTacticalGraphicsSymCode(String symCode) - { + protected String parseTacticalGraphicsSymCode(String symCode) { StringBuilder sb = new StringBuilder(); // Coding Scheme (position 1). String s = symCode.substring(0, 1); - if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_TACTICAL_GRAPHICS)) + if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_TACTICAL_GRAPHICS)) { this.setScheme(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.scheme")); + } // Standard Identity/Exercise Amplifying Descriptor (position 2). s = symCode.substring(1, 2); - if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) { this.setStandardIdentity(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.standardIdentity")); + } // Category (position 3). s = symCode.substring(2, 3); - if (SymbologyConstants.CATEGORY_ALL_TACTICAL_GRAPHICS.contains(s.toUpperCase())) + if (SymbologyConstants.CATEGORY_ALL_TACTICAL_GRAPHICS.contains(s.toUpperCase())) { this.setCategory(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.category")); + } // Status/Operational Condition (position 4). s = symCode.substring(3, 4); - if (SymbologyConstants.STATUS_ALL_TACTICAL_GRAPHICS_METOC.contains(s.toUpperCase())) + if (SymbologyConstants.STATUS_ALL_TACTICAL_GRAPHICS_METOC.contains(s.toUpperCase())) { this.setStatus(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.status")); + } // Function ID (positions 5-10). s = symCode.substring(4, 10); if (!"------".equals(s)) // "------" is accepted and indicates a null function ID. + { this.setFunctionId(s); + } // Echelon (position 12, position 11 is unused). s = symCode.substring(11, 12); - if (SymbologyConstants.ECHELON_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.ECHELON_ALL.contains(s.toUpperCase())) { this.setEchelon(s); - else if (!UNUSED_POSITION_CODE.equals(s)) // "-" is accepted and indicates a null echelon. + } else if (!UNUSED_POSITION_CODE.equals(s)) // "-" is accepted and indicates a null echelon. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.echelon")); + } // Country Code (positions 13-14). s = symCode.substring(12, 14); if (!"--".equals(s)) // "--" is accepted and indicates a null country code. We don't validate country codes. + { this.setCountryCode(s); + } // Order Of Battle (position 15). s = symCode.substring(14, 15); - if (SymbologyConstants.ORDER_OF_BATTLE_ALL_TACTICAL_GRAPHICS.contains(s.toUpperCase())) + if (SymbologyConstants.ORDER_OF_BATTLE_ALL_TACTICAL_GRAPHICS.contains(s.toUpperCase())) { this.setOrderOfBattle(s); - else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + } else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.orderOfBattle")); + } return sb.length() > 0 - ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; + ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; } /** @@ -853,51 +823,55 @@ else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle * currently supported, and this returns a string indicating that the scheme is unrecognized. * * @param symCode the symbol code to parse. Must be non-null and have length of 15 or greater. Any - * characters after the 15th character are ignored. + * characters after the 15th character are ignored. * * @return an error string. */ - protected String parseMetocSymCode(String symCode) - { + protected String parseMetocSymCode(String symCode) { StringBuilder sb = new StringBuilder(); // Coding Scheme (position 1). String s = symCode.substring(0, 1); - if (SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(s)) + if (SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(s)) { this.setScheme(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.scheme")); + } // Category (position 2). s = symCode.substring(1, 2); - if (SymbologyConstants.CATEGORY_ALL_METOC.contains(s.toUpperCase())) + if (SymbologyConstants.CATEGORY_ALL_METOC.contains(s.toUpperCase())) { this.setCategory(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.category")); + } // Static/Dynamic (position 3,4). s = symCode.substring(2, 4); - if (SymbologyConstants.STATIC_DYNAMIC_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.STATIC_DYNAMIC_ALL.contains(s.toUpperCase())) { this.setStaticDynamic(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.status")); + } // Function ID (positions 5-10). s = symCode.substring(4, 10); if (!"------".equals(s)) // "------" is accepted and indicates a null function ID. + { this.setFunctionId(s); + } // Graphic Type (position 11-13). s = symCode.substring(10, 13); - if (SymbologyConstants.GRAPHIC_TYPE_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.GRAPHIC_TYPE_ALL.contains(s.toUpperCase())) { this.setGraphicType(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.echelon")); + } // Positions 14 and 15 unused - return sb.length() > 0 - ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; + ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; } /** @@ -908,67 +882,78 @@ protected String parseMetocSymCode(String symCode) * The Signals Intelligence coding scheme is defined in MIL-STD-2525C table D-I (page 964). * * @param symCode the symbol code to parse. Must be non-null and have length of 15 or greater. Any - * characters after the 15th character are ignored. + * characters after the 15th character are ignored. * * @return null if the symbol code is recognized, otherwise a non-null string listing the - * unrecognized symbol elements. + * unrecognized symbol elements. */ - protected String parseIntelligenceSymCode(String symCode) - { + protected String parseIntelligenceSymCode(String symCode) { StringBuilder sb = new StringBuilder(); // Coding Scheme (position 1). String s = symCode.substring(0, 1); - if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_INTELLIGENCE)) + if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_INTELLIGENCE)) { this.setScheme(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.scheme")); + } // Standard Identity/Exercise Amplifying Descriptor (position 2). s = symCode.substring(1, 2); - if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) { this.setStandardIdentity(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.standardIdentity")); + } // Battle Dimension (position 3). s = symCode.substring(2, 3); - if (SymbologyConstants.BATTLE_DIMENSION_ALL_INTELLIGENCE.contains(s.toUpperCase())) + if (SymbologyConstants.BATTLE_DIMENSION_ALL_INTELLIGENCE.contains(s.toUpperCase())) { this.setBattleDimension(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.battleDimension")); + } // Status/Operational Condition (position 4) s = symCode.substring(3, 4); - if (SymbologyConstants.STATUS_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) + if (SymbologyConstants.STATUS_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) { this.setStatus(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.status")); + } // Function ID (positions 5-10) s = symCode.substring(4, 10); if (!"------".equals(s)) // "------" is accepted and indicates a null function ID. + { this.setFunctionId(s); + } // Not Used (positions 11-12). s = symCode.substring(10, 12); if (!"--".equals(s)) // "--" is the only accepted string in positions 11-12. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.symbolModifier")); + } // Country Code (positions 13-14). s = symCode.substring(12, 14); if (!"--".equals(s)) // "--" is accepted and indicates a null country code. + { this.setCountryCode(s); + } // Order of Battle (position 15). s = symCode.substring(14, 15); - if (SymbologyConstants.ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) + if (SymbologyConstants.ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) { this.setOrderOfBattle(s); - else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + } else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.orderOfBattle")); + } return sb.length() > 0 - ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; + ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; } /** @@ -980,69 +965,80 @@ else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle * The Stability Operations coding scheme is defined in MIL-STD-2525C table E-I (page 991). * * @param symCode the symbol code to parse. Must be non-null and have length of 15 or greater. Any - * characters after the 15th character are ignored. + * characters after the 15th character are ignored. * * @return null if the symbol code is recognized, otherwise a non-null string listing the - * unrecognized symbol elements. + * unrecognized symbol elements. */ - protected String parseStabilityOperationsSymCode(String symCode) - { + protected String parseStabilityOperationsSymCode(String symCode) { StringBuilder sb = new StringBuilder(); // Coding Scheme (position 1). String s = symCode.substring(0, 1); - if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS)) + if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_STABILITY_OPERATIONS)) { this.setScheme(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.scheme")); + } // Standard Identity/Exercise Amplifying Descriptor (position 2). s = symCode.substring(1, 2); - if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) { this.setStandardIdentity(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.standardIdentity")); + } // Category (position 3). s = symCode.substring(2, 3); - if (SymbologyConstants.CATEGORY_ALL_STABILITY_OPERATIONS.contains(s.toUpperCase())) + if (SymbologyConstants.CATEGORY_ALL_STABILITY_OPERATIONS.contains(s.toUpperCase())) { this.setCategory(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.category")); + } // Status/Operational Condition (position 4). s = symCode.substring(3, 4); - if (SymbologyConstants.STATUS_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) + if (SymbologyConstants.STATUS_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) { this.setStatus(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.status")); + } // Function ID (positions 5-10). s = symCode.substring(4, 10); if (!"------".equals(s)) // "------" is accepted and indicates a null function ID. + { this.setFunctionId(s); + } // Symbol Modifier (positions 11-12). s = symCode.substring(10, 12); - if (this.isUnitsAndEquipmentSymbolModifier(s) || SymbologyConstants.INSTALLATION_ALL.contains(s.toUpperCase())) + if (this.isUnitsAndEquipmentSymbolModifier(s) || SymbologyConstants.INSTALLATION_ALL.contains(s.toUpperCase())) { this.setSymbolModifier(s); - else if (!"--".equals(s)) // "--" is accepted and indicates a null symbol modifier. + } else if (!"--".equals(s)) // "--" is accepted and indicates a null symbol modifier. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.symbolModifier")); + } // Country Code (positions 13-14). s = symCode.substring(12, 14); if (!"--".equals(s)) // "--" is accepted and indicates a null country code. + { this.setCountryCode(s); + } // Order Of Battle (position 15). s = symCode.substring(14, 15); - if (SymbologyConstants.ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) + if (SymbologyConstants.ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) { this.setOrderOfBattle(s); - else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + } else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.orderOfBattle")); + } return sb.length() > 0 - ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; + ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; } /** @@ -1054,93 +1050,101 @@ else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle * The Emergency Management coding scheme is defined in MIL-STD-2525C table G-I (page 1032). * * @param symCode the symbol code to parse. Must be non-null and have length of 15 or greater. Any - * characters after the 15th character are ignored. + * characters after the 15th character are ignored. * * @return null if the symbol code is recognized, otherwise a non-null string listing the - * unrecognized symbol elements. + * unrecognized symbol elements. */ - protected String parseEmergencyManagementSymCode(String symCode) - { + protected String parseEmergencyManagementSymCode(String symCode) { StringBuilder sb = new StringBuilder(); // Coding Scheme (position 1). String s = symCode.substring(0, 1); - if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)) + if (s != null && s.equalsIgnoreCase(SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT)) { this.setScheme(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.scheme")); + } // Standard Identity/Exercise Amplifying Descriptor (position 2). s = symCode.substring(1, 2); - if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) + if (SymbologyConstants.STANDARD_IDENTITY_ALL.contains(s.toUpperCase())) { this.setStandardIdentity(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.standardIdentity")); + } // Category (position 3). s = symCode.substring(2, 3); - if (SymbologyConstants.CATEGORY_ALL_EMERGENCY_MANAGEMENT.contains(s.toUpperCase())) + if (SymbologyConstants.CATEGORY_ALL_EMERGENCY_MANAGEMENT.contains(s.toUpperCase())) { this.setCategory(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.category")); + } // Status/Operational Condition (position 4). s = symCode.substring(3, 4); - if (SymbologyConstants.STATUS_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) + if (SymbologyConstants.STATUS_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) { this.setStatus(s); - else + } else { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.status")); + } // Function ID (positions 5-10). s = symCode.substring(4, 10); if (!"------".equals(s)) // "------" is accepted and indicates a null function ID. + { this.setFunctionId(s); + } // Symbol Modifier (positions 11-12). s = symCode.substring(10, 12); if (SymbologyConstants.INSTALLATION_ALL.contains(s.toUpperCase()) - || SymbologyConstants.MOBILITY_ALL.contains(s.toUpperCase())) - { + || SymbologyConstants.MOBILITY_ALL.contains(s.toUpperCase())) { this.setSymbolModifier(s); - } - else if (!"--".equals(s)) // "--" is accepted and indicates a null symbol modifier. + } else if (!"--".equals(s)) // "--" is accepted and indicates a null symbol modifier. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.symbolModifier")); + } // Country Code (positions 13-14). s = symCode.substring(12, 14); if (!"--".equals(s)) // "--" is accepted and indicates a null country code. + { this.setCountryCode(s); + } // Order Of Battle (position 15). s = symCode.substring(14, 15); - if (SymbologyConstants.ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) + if (SymbologyConstants.ORDER_OF_BATTLE_ALL_UEI_SIGINT_SO_EM.contains(s.toUpperCase())) { this.setOrderOfBattle(s); - else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + } else if (!"-".equals(s)) // "-" is accepted and indicates a null order of battle. + { sb.append(sb.length() > 0 ? ", " : "").append(Logging.getMessage("term.orderOfBattle")); + } return sb.length() > 0 - ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; + ? Logging.getMessage("Symbology.SymbolCodeFieldsUnrecognized", sb.toString(), symCode) : null; } /** * Indicates whether the specified 2-character Symbol Modifier code represents a units and equipment symbol modifier * code. * - * @param value the modifier code to test. Must be non-null and have length of 2 or greater. Any - * characters after the 2nd character are ignored. + * @param value the modifier code to test. Must be non-null and have length of 2 or greater. Any + * characters after the 2nd character are ignored. * * @return true if the specified code represents a units and equipment modifier code, and - * false otherwise. + * false otherwise. */ - protected boolean isUnitsAndEquipmentSymbolModifier(String value) - { + protected boolean isUnitsAndEquipmentSymbolModifier(String value) { String firstChar = value.substring(0, 1).toUpperCase(); String secondChar = value.substring(1, 2).toUpperCase(); return (UNUSED_POSITION_CODE.equals(firstChar) && SymbologyConstants.ECHELON_ALL.contains(secondChar)) - || (SymbologyConstants.MODIFIER_CODE_ALL_UEI.contains(firstChar) && UNUSED_POSITION_CODE.equals(secondChar)) - || (SymbologyConstants.MODIFIER_CODE_ALL_UEI.contains(firstChar) - && SymbologyConstants.ECHELON_ALL.contains(secondChar)); + || (SymbologyConstants.MODIFIER_CODE_ALL_UEI.contains(firstChar) && UNUSED_POSITION_CODE.equals(secondChar)) + || (SymbologyConstants.MODIFIER_CODE_ALL_UEI.contains(firstChar) + && SymbologyConstants.ECHELON_ALL.contains(secondChar)); } /** @@ -1153,38 +1157,24 @@ protected boolean isUnitsAndEquipmentSymbolModifier(String value) * This returns null if this SymbolCode's Coding Scheme is null or unrecognized. * * @return the MIL-STD-2525 15-character symbol identification code (SIDC) corresponding to this SymbolCode, or - * null if the Coding Scheme is unrecognized. + * null if the Coding Scheme is unrecognized. */ - protected String composeSymCode() - { + protected String composeSymCode() { String scheme = this.getScheme(); - if (SymbologyConstants.SCHEME_WARFIGHTING.equalsIgnoreCase(scheme)) - { + if (SymbologyConstants.SCHEME_WARFIGHTING.equalsIgnoreCase(scheme)) { return this.composeWarfightingSymCode(); - } - else if (SymbologyConstants.SCHEME_TACTICAL_GRAPHICS.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_TACTICAL_GRAPHICS.equalsIgnoreCase(scheme)) { return this.composeTacticalGraphicsSymCode(); - } - else if (SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_METOC.equalsIgnoreCase(scheme)) { return this.composeMetocSymCode(); - } - else if (SymbologyConstants.SCHEME_INTELLIGENCE.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_INTELLIGENCE.equalsIgnoreCase(scheme)) { return this.composeIntelligenceSymCode(); - } - else if (SymbologyConstants.SCHEME_STABILITY_OPERATIONS.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_STABILITY_OPERATIONS.equalsIgnoreCase(scheme)) { return this.composeStabilityOperationsSymCode(); - } - else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme)) - { + } else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme)) { return this.composeEmergencyManagementSymCode(); - } - else - { + } else { return this.composeUnrecognizedSymCode(); } } @@ -1194,8 +1184,7 @@ else if (SymbologyConstants.SCHEME_EMERGENCY_MANAGEMENT.equalsIgnoreCase(scheme) * * @return null. */ - protected String composeUnrecognizedSymCode() - { + protected String composeUnrecognizedSymCode() { return null; } @@ -1207,10 +1196,9 @@ protected String composeUnrecognizedSymCode() * The Warfighting coding scheme is defined in MIL-STD-2525C table A-I (page 51). * * @return the MIL-STD-2525 15-character symbol identification code (SIDC) corresponding to this SymbolCode, - * according to the Warfighting coding scheme. + * according to the Warfighting coding scheme. */ - protected String composeWarfightingSymCode() - { + protected String composeWarfightingSymCode() { StringBuilder sb = new StringBuilder(); appendFieldValue(sb, this.getScheme(), 1); // Position 1. @@ -1233,10 +1221,9 @@ protected String composeWarfightingSymCode() * The Tactical Graphics coding scheme is defined in MIL-STD-2525C table B-I (page 305). * * @return the MIL-STD-2525 15-character symbol identification code (SIDC) corresponding to this SymbolCode, - * according to the Tactical Graphics coding scheme. + * according to the Tactical Graphics coding scheme. */ - protected String composeTacticalGraphicsSymCode() - { + protected String composeTacticalGraphicsSymCode() { StringBuilder sb = new StringBuilder(); appendFieldValue(sb, this.getScheme(), 1); // Position 1. @@ -1260,10 +1247,9 @@ protected String composeTacticalGraphicsSymCode() * The Meteorological and Oceanographic coding scheme is defined in MIL-STD-2525C table C-I (page 763). * * @return the MIL-STD-2525 15-character symbol identification code (SIDC) corresponding to this SymbolCode, - * according to the METOC coding scheme. + * according to the METOC coding scheme. */ - protected String composeMetocSymCode() - { + protected String composeMetocSymCode() { StringBuilder sb = new StringBuilder(); appendFieldValue(sb, this.getScheme(), 1); // Position 1. @@ -1285,10 +1271,9 @@ protected String composeMetocSymCode() * The Signals Intelligence coding scheme is defined in MIL-STD-2525C table D-I (page 964). * * @return the MIL-STD-2525 15-character symbol identification code (SIDC) corresponding to this SymbolCode, - * according to the Signals Intelligence coding scheme. + * according to the Signals Intelligence coding scheme. */ - protected String composeIntelligenceSymCode() - { + protected String composeIntelligenceSymCode() { StringBuilder sb = new StringBuilder(); appendFieldValue(sb, this.getScheme(), 1); // Position 1. @@ -1311,10 +1296,9 @@ protected String composeIntelligenceSymCode() * The Stability Operations coding scheme is defined in MIL-STD-2525C table E-I (page 991). * * @return the MIL-STD-2525 15-character symbol identification code (SIDC) corresponding to this SymbolCode, - * according to the Stability Operations coding scheme. + * according to the Stability Operations coding scheme. */ - protected String composeStabilityOperationsSymCode() - { + protected String composeStabilityOperationsSymCode() { StringBuilder sb = new StringBuilder(); appendFieldValue(sb, this.getScheme(), 1); // Position 1. @@ -1337,10 +1321,9 @@ protected String composeStabilityOperationsSymCode() * The Emergency Management coding scheme is defined in MIL-STD-2525C table G-I (page 1032). * * @return the MIL-STD-2525 15-character symbol identification code (SIDC) corresponding to this SymbolCode, - * according to the Emergency Management coding scheme. + * according to the Emergency Management coding scheme. */ - protected String composeEmergencyManagementSymCode() - { + protected String composeEmergencyManagementSymCode() { StringBuilder sb = new StringBuilder(); appendFieldValue(sb, this.getScheme(), 1); // Position 1. @@ -1362,21 +1345,18 @@ protected String composeEmergencyManagementSymCode() * ignores the extra characters. If the value is null or empty, this appends unused characters to fill * the entire space used by the field. * - * @param sb the StringBuilder representing a MIL-STD-2525 symbol identification code (SIDC). - * @param value the field value to append. + * @param sb the StringBuilder representing a MIL-STD-2525 symbol identification code (SIDC). + * @param value the field value to append. * @param length the number of positions used by the field in the SIDC. */ - public static void appendFieldValue(StringBuilder sb, String value, int length) - { - if (sb == null) - { + public static void appendFieldValue(StringBuilder sb, String value, int length) { + if (sb == null) { String msg = Logging.getMessage("nullValue.StringBuilderIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (length < 0) - { + if (length < 0) { String msg = Logging.getMessage("generic.LengthIsInvalid", length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1386,13 +1366,13 @@ public static void appendFieldValue(StringBuilder sb, String value, int length) // assigned to the code have been reached or the code's characters are exhausted, whichever comes first. This // does nothing if the code is null or empty. If the code contains fewer characters then its assigned length, // then only those characters are appended. - if (value != null && value.length() > 0) + if (value != null && value.length() > 0) { sb.append(value, 0, value.length() < length ? value.length() : length); + } // Append the "unused" character for each unused character position assigned to the code. We encounter unused // positions when the code is null or its length is less than the number of assigned character positions. - for (int i = (value != null ? value.length() : 0); i < length; i++) - { + for (int i = (value != null ? value.length() : 0); i < length; i++) { sb.append(UNUSED_POSITION_CODE); } } @@ -1405,8 +1385,7 @@ public static void appendFieldValue(StringBuilder sb, String value, int length) * * @return true if the value is empty, and false otherwise. */ - public static boolean isFieldEmpty(String value) - { + public static boolean isFieldEmpty(String value) { return value == null || value.isEmpty() || value.replaceAll(UNUSED_POSITION_CODE, "").trim().isEmpty(); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/DefaultLabelLayouts.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/DefaultLabelLayouts.java index 110145d7a5..a06fbcbff9 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/DefaultLabelLayouts.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/DefaultLabelLayouts.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics; import gov.nasa.worldwind.render.Offset; @@ -22,14 +21,17 @@ * @author pabercrombie * @version $Id: DefaultLabelLayouts.java 552 2012-04-25 16:51:16Z pabercrombie $ */ -public class DefaultLabelLayouts -{ - /** Map to hold layouts. */ +public class DefaultLabelLayouts { + + /** + * Map to hold layouts. + */ protected Map> layouts = new HashMap>(); - /** Create the map and populate it with the default layouts. */ - public DefaultLabelLayouts() - { + /** + * Create the map and populate it with the default layouts. + */ + public DefaultLabelLayouts() { this.populateMap(); } @@ -39,167 +41,166 @@ public DefaultLabelLayouts() * @param sidc Symbol code of the graphic. * * @return Map that represents the label layout. The keys indicate the modifier key (unique designation, additional - * info, etc.). The values are lists of LabelLayout. Most modifiers will only specify a single layout, but - * some graphics support multiple instances of the same modifier, in which case the list will contain - * multiple layouts. + * info, etc.). The values are lists of LabelLayout. Most modifiers will only specify a single layout, but some + * graphics support multiple instances of the same modifier, in which case the list will contain multiple layouts. */ - public List get(String sidc) - { + public List get(String sidc) { List layout = this.layouts.get(sidc); return layout != null ? layout : Collections.emptyList(); } - /** Populate the map with the default layouts. */ - protected void populateMap() - { + /** + * Populate the map with the default layouts. + */ + protected void populateMap() { // The C2GM.GNL.PNT.HBR graphic supports the H modifier in the center of the graphic. this.layouts.put(C2GM_GNL_PNT_HBR, - this.createLayout(SymbologyConstants.ADDITIONAL_INFORMATION, Offset.CENTER, Offset.CENTER)); + this.createLayout(SymbologyConstants.ADDITIONAL_INFORMATION, Offset.CENTER, Offset.CENTER)); // C2GM.GNL.PNT.ACTPNT.DCNPNT supports the T modifier in the center of the graphic. this.layouts.put(C2GM_GNL_PNT_ACTPNT_DCNPNT, - this.createLayout(SymbologyConstants.UNIQUE_DESIGNATION, Offset.CENTER, Offset.CENTER)); + this.createLayout(SymbologyConstants.UNIQUE_DESIGNATION, Offset.CENTER, Offset.CENTER)); // Most pentagon shaped graphics support the same modifiers around the pentagon. List layout = new ArrayList(); this.addLayout(layout, SymbologyConstants.UNIQUE_DESIGNATION, - Offset.fromFraction(1.1, 1.0), - Offset.fromFraction(0.0, 1.0)); + Offset.fromFraction(1.1, 1.0), + Offset.fromFraction(0.0, 1.0)); this.addLayout(layout, SymbologyConstants.ADDITIONAL_INFORMATION, - Offset.TOP_CENTER, - Offset.BOTTOM_CENTER); + Offset.TOP_CENTER, + Offset.BOTTOM_CENTER); this.addLayout(layout, SymbologyConstants.HOSTILE_ENEMY, - Offset.fromFraction(1.1, 0.35), - Offset.fromFraction(0.0, 0.0)); + Offset.fromFraction(1.1, 0.35), + Offset.fromFraction(0.0, 0.0)); this.addLayout(layout, SymbologyConstants.DATE_TIME_GROUP, - Offset.fromFraction(-0.1, 0.8), - Offset.fromFraction(1.0, 0.0), - Offset.fromFraction(-0.1, 0.8), - Offset.fromFraction(1.0, 1.0)); + Offset.fromFraction(-0.1, 0.8), + Offset.fromFraction(1.0, 0.0), + Offset.fromFraction(-0.1, 0.8), + Offset.fromFraction(1.0, 1.0)); // Apply this layout to all the pentagon graphics that use it. this.putAll(layout, - C2GM_GNL_PNT_ACTPNT_CHKPNT, - C2GM_GNL_PNT_ACTPNT_LNKUPT, - C2GM_GNL_PNT_ACTPNT_PSSPNT, - C2GM_GNL_PNT_ACTPNT_RAYPNT, - C2GM_GNL_PNT_ACTPNT_RELPNT, - C2GM_GNL_PNT_ACTPNT_STRPNT, - C2GM_GNL_PNT_ACTPNT_AMNPNT, - C2GM_OFF_PNT_PNTD, - MOBSU_OBSTBP_CSGSTE_ERP, - MOBSU_CBRN_DECONP_USP, - MOBSU_CBRN_DECONP_ALTUSP, - MOBSU_CBRN_DECONP_TRP, - MOBSU_CBRN_DECONP_EQT, - MOBSU_CBRN_DECONP_EQTTRP, - MOBSU_CBRN_DECONP_OPDECN, - MOBSU_CBRN_DECONP_TRGH, - FSUPP_PNT_C2PNT_SCP, - FSUPP_PNT_C2PNT_FP, - FSUPP_PNT_C2PNT_RP, - FSUPP_PNT_C2PNT_HP, - FSUPP_PNT_C2PNT_LP, - CSS_PNT_CBNP, - CSS_PNT_CCP, - CSS_PNT_CVP, - CSS_PNT_DCP, - CSS_PNT_EPWCP, - CSS_PNT_LRP, - CSS_PNT_MCP, - CSS_PNT_RRRP, - CSS_PNT_ROM, - CSS_PNT_TCP, - CSS_PNT_TTP, - CSS_PNT_UMC, - CSS_PNT_SPT_GNL, - CSS_PNT_SPT_CLS1, - CSS_PNT_SPT_CLS2, - CSS_PNT_SPT_CLS3, - CSS_PNT_SPT_CLS4, - CSS_PNT_SPT_CLS5, - CSS_PNT_SPT_CLS6, - CSS_PNT_SPT_CLS7, - CSS_PNT_SPT_CLS8, - CSS_PNT_SPT_CLS9, - CSS_PNT_SPT_CLS10, - CSS_PNT_AP_ASP, - CSS_PNT_AP_ATP); + C2GM_GNL_PNT_ACTPNT_CHKPNT, + C2GM_GNL_PNT_ACTPNT_LNKUPT, + C2GM_GNL_PNT_ACTPNT_PSSPNT, + C2GM_GNL_PNT_ACTPNT_RAYPNT, + C2GM_GNL_PNT_ACTPNT_RELPNT, + C2GM_GNL_PNT_ACTPNT_STRPNT, + C2GM_GNL_PNT_ACTPNT_AMNPNT, + C2GM_OFF_PNT_PNTD, + MOBSU_OBSTBP_CSGSTE_ERP, + MOBSU_CBRN_DECONP_USP, + MOBSU_CBRN_DECONP_ALTUSP, + MOBSU_CBRN_DECONP_TRP, + MOBSU_CBRN_DECONP_EQT, + MOBSU_CBRN_DECONP_EQTTRP, + MOBSU_CBRN_DECONP_OPDECN, + MOBSU_CBRN_DECONP_TRGH, + FSUPP_PNT_C2PNT_SCP, + FSUPP_PNT_C2PNT_FP, + FSUPP_PNT_C2PNT_RP, + FSUPP_PNT_C2PNT_HP, + FSUPP_PNT_C2PNT_LP, + CSS_PNT_CBNP, + CSS_PNT_CCP, + CSS_PNT_CVP, + CSS_PNT_DCP, + CSS_PNT_EPWCP, + CSS_PNT_LRP, + CSS_PNT_MCP, + CSS_PNT_RRRP, + CSS_PNT_ROM, + CSS_PNT_TCP, + CSS_PNT_TTP, + CSS_PNT_UMC, + CSS_PNT_SPT_GNL, + CSS_PNT_SPT_CLS1, + CSS_PNT_SPT_CLS2, + CSS_PNT_SPT_CLS3, + CSS_PNT_SPT_CLS4, + CSS_PNT_SPT_CLS5, + CSS_PNT_SPT_CLS6, + CSS_PNT_SPT_CLS7, + CSS_PNT_SPT_CLS8, + CSS_PNT_SPT_CLS9, + CSS_PNT_SPT_CLS10, + CSS_PNT_AP_ASP, + CSS_PNT_AP_ATP); // C2GM.GNL.PNT.ACTPNT supports all the normal pentagon graphic modifiers, and also supports H1 in the // middle of the pentagon. layout = new ArrayList(layout); this.addLayout(layout, SymbologyConstants.ADDITIONAL_INFORMATION, - Offset.TOP_CENTER, - Offset.BOTTOM_CENTER, - Offset.fromFraction(0.5, 0.9), - Offset.TOP_CENTER); + Offset.TOP_CENTER, + Offset.BOTTOM_CENTER, + Offset.fromFraction(0.5, 0.9), + Offset.TOP_CENTER); this.layouts.put(C2GM_GNL_PNT_ACTPNT, layout); // CSS.PNT.AEP supports all the normal pentagon graphic modifiers, and also supports T1 in the // middle of the pentagon. layout = new ArrayList(layout); this.addLayout(layout, SymbologyConstants.UNIQUE_DESIGNATION, - Offset.fromFraction(1.1, 1.0), - Offset.fromFraction(0.0, 1.0), - Offset.CENTER, - Offset.CENTER); + Offset.fromFraction(1.1, 1.0), + Offset.fromFraction(0.0, 1.0), + Offset.CENTER, + Offset.CENTER); this.addLayout(layout, SymbologyConstants.ADDITIONAL_INFORMATION, - Offset.TOP_CENTER, - Offset.BOTTOM_CENTER); + Offset.TOP_CENTER, + Offset.BOTTOM_CENTER); this.layouts.put(CSS_PNT_AEP, layout); // The Chemical and Biological release graphics support the same modifiers. layout = new ArrayList(); this.addLayout(layout, SymbologyConstants.LOCATION, - Offset.fromFraction(0.5, -0.1), - Offset.TOP_CENTER); + Offset.fromFraction(0.5, -0.1), + Offset.TOP_CENTER); this.addLayout(layout, SymbologyConstants.DATE_TIME_GROUP, - Offset.fromFraction(0.0, 1.0), - Offset.fromFraction(1.0, 1.0)); + Offset.fromFraction(0.0, 1.0), + Offset.fromFraction(1.0, 1.0)); this.addLayout(layout, SymbologyConstants.ADDITIONAL_INFORMATION, - Offset.fromFraction(1.0, 1.0), - Offset.fromFraction(0.0, 1.0)); + Offset.fromFraction(1.0, 1.0), + Offset.fromFraction(0.0, 1.0)); this.addLayout(layout, SymbologyConstants.HOSTILE_ENEMY, - Offset.fromFraction(1.0, 0.0), - Offset.fromFraction(0.0, 0.0)); + Offset.fromFraction(1.0, 0.0), + Offset.fromFraction(0.0, 0.0)); this.addLayout(layout, SymbologyConstants.TYPE, - Offset.LEFT_CENTER, - Offset.RIGHT_CENTER); + Offset.LEFT_CENTER, + Offset.RIGHT_CENTER); this.addLayout(layout, SymbologyConstants.UNIQUE_DESIGNATION, - Offset.fromFraction(0.0, 0.0), - Offset.fromFraction(1.0, 0.0)); + Offset.fromFraction(0.0, 0.0), + Offset.fromFraction(1.0, 0.0)); this.layouts.put(MOBSU_CBRN_REEVNT_BIO, layout); this.layouts.put(MOBSU_CBRN_REEVNT_CML, layout); // The Nuclear graphic is mostly the same as chem/bio, but also supports the quantity modifier. layout = new ArrayList(layout); this.addLayout(layout, SymbologyConstants.QUANTITY, - Offset.TOP_CENTER, - Offset.BOTTOM_CENTER); + Offset.TOP_CENTER, + Offset.BOTTOM_CENTER); this.layouts.put(MOBSU_CBRN_NDGZ, layout); // C2GM.GNL.PNT.REFPNT.PNTINR supports the T modifier layout = this.createLayout(SymbologyConstants.UNIQUE_DESIGNATION, - Offset.fromFraction(0.5, 0.7), Offset.CENTER); + Offset.fromFraction(0.5, 0.7), Offset.CENTER); this.layouts.put(C2GM_GNL_PNT_REFPNT_PNTINR, layout); // Square flag layout = this.createLayout(SymbologyConstants.UNIQUE_DESIGNATION, - Offset.fromFraction(0.5, 0.65), Offset.CENTER); + Offset.fromFraction(0.5, 0.65), Offset.CENTER); this.layouts.put(C2GM_GNL_PNT_ACTPNT_CONPNT, layout); // X shaped graphics, T on left layout = this.createLayout(SymbologyConstants.UNIQUE_DESIGNATION, - Offset.fromFraction(0.75, 0.5), - Offset.LEFT_CENTER); + Offset.fromFraction(0.75, 0.5), + Offset.LEFT_CENTER); this.layouts.put(C2GM_GNL_PNT_ACTPNT_WAP, layout); this.layouts.put(FSUPP_PNT_C2PNT_FSS, layout); // Cross shaped graphics, T in upper right quad layout = this.createLayout(SymbologyConstants.UNIQUE_DESIGNATION, - Offset.fromFraction(0.75, 0.75), - Offset.fromFraction(0.0, 0.0)); + Offset.fromFraction(0.75, 0.75), + Offset.fromFraction(0.0, 0.0)); this.layouts.put(C2GM_DEF_PNT_TGTREF, layout); this.layouts.put(FSUPP_PNT_TGT_NUCTGT, layout); @@ -207,16 +208,16 @@ protected void populateMap() // the lower quads. layout = new ArrayList(layout); this.addLayout(layout, SymbologyConstants.ADDITIONAL_INFORMATION, - Offset.fromFraction(0.75, 0.25), - Offset.fromFraction(0.0, 1.0), - Offset.fromFraction(0.25, 0.25), - Offset.fromFraction(1.0, 1.0)); + Offset.fromFraction(0.75, 0.25), + Offset.fromFraction(0.0, 1.0), + Offset.fromFraction(0.25, 0.25), + Offset.fromFraction(1.0, 1.0)); this.layouts.put(FSUPP_PNT_TGT_PTGT, layout); // Tower graphics use the altitude modifier layout = this.createLayout(SymbologyConstants.ALTITUDE_DEPTH, - Offset.fromFraction(0.75, 0.75), - Offset.fromFraction(0.0, 0.0)); + Offset.fromFraction(0.75, 0.75), + Offset.fromFraction(0.0, 0.0)); this.layouts.put(MOBSU_OBST_AVN_TWR_LOW, layout); this.layouts.put(MOBSU_OBST_AVN_TWR_HIGH, layout); } @@ -224,14 +225,13 @@ protected void populateMap() /** * Create a simple layout map and populate it with one key value pair. * - * @param key Modifier key. - * @param offset Offset within the image at which to place the label. + * @param key Modifier key. + * @param offset Offset within the image at which to place the label. * @param hotspot Offset within the label to align with the label point in the image. * * @return New map, populated with one entry for the key/value pair specified in the parameters. */ - protected List createLayout(String key, Offset offset, Offset hotspot) - { + protected List createLayout(String key, Offset offset, Offset hotspot) { LabelLayout layout = new LabelLayout(key); layout.add(offset, hotspot); @@ -242,25 +242,22 @@ protected List createLayout(String key, Offset offset, Offset hotsp * Add a layout to a layout map, possibly replacing an existing layout. * * @param layoutList List to which to add an entry. - * @param key Modifier key. - * @param offsets List of offsets from which to create one or more LabelLayout objects. The offsets are specified - * in pairs: first the image offset and then the label offset. If multiple pairs are provided, - * then multiple LabelLayouts will be created and added to the map. + * @param key Modifier key. + * @param offsets List of offsets from which to create one or more LabelLayout objects. The offsets are specified in + * pairs: first the image offset and then the label offset. If multiple pairs are provided, then multiple + * LabelLayouts will be created and added to the map. * * @throws IllegalArgumentException if offsets does not have even length. */ - protected void addLayout(List layoutList, String key, Offset... offsets) - { - if (offsets.length % 2 != 0) - { + protected void addLayout(List layoutList, String key, Offset... offsets) { + if (offsets.length % 2 != 0) { String msg = Logging.getMessage("generic.ArrayInvalidLength", offsets.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } LabelLayout layout = new LabelLayout(key); - for (int i = 0; i < offsets.length; i += 2) - { + for (int i = 0; i < offsets.length; i += 2) { Offset offset = offsets[i]; Offset hotspot = offsets[i + 1]; @@ -274,12 +271,10 @@ protected void addLayout(List layoutList, String key, Offset... off * Map one value to many keys. * * @param value Value to add. - * @param keys Keys that map to the value. + * @param keys Keys that map to the value. */ - protected void putAll(List value, String... keys) - { - for (String sidc : keys) - { + protected void putAll(List value, String... keys) { + for (String sidc : keys) { this.layouts.put(sidc, value); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/DefaultOffsets.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/DefaultOffsets.java index a09a6b8c77..4b4d2e81ce 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/DefaultOffsets.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/DefaultOffsets.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics; import gov.nasa.worldwind.render.Offset; @@ -21,33 +20,50 @@ * @version $Id: DefaultOffsets.java 542 2012-04-24 19:08:12Z pabercrombie $ * @see gov.nasa.worldwind.symbology.AbstractTacticalSymbol#setOffset(gov.nasa.worldwind.render.Offset) */ -public class DefaultOffsets -{ - /** Offset to align the center of the graphic with the geographic position. */ +public class DefaultOffsets { + + /** + * Offset to align the center of the graphic with the geographic position. + */ protected static Offset DEFAULT_OFFSET = Offset.CENTER; - /** Offset to align a point 25% up from the bottom edge with the geographic position. */ + /** + * Offset to align a point 25% up from the bottom edge with the geographic position. + */ public static final Offset OFFSET_BOTTOM_QUARTER = Offset.fromFraction(0.5, 0.25); - /** Offset for the Drop Point graphic (2.X.2.1.1.3.2). */ + /** + * Offset for the Drop Point graphic (2.X.2.1.1.3.2). + */ public static final Offset OFFSET_C2GM_GNL_PNT_WPN_DRPPNT = Offset.fromFraction(0.5, 0.17); - /** Offset for the Antitank Mine with Anti-handling Device graphic (2.X.3.1.5.3). */ + /** + * Offset for the Antitank Mine with Anti-handling Device graphic (2.X.3.1.5.3). + */ public static final Offset OFFSET_MOBSU_OBST_MNE_ATMAHD = Offset.fromFraction(0.5, 0.75); - /** Offset for the Antipersonnel (AP) Mines graphic (2.X.3.1.5.5). */ + /** + * Offset for the Antipersonnel (AP) Mines graphic (2.X.3.1.5.5). + */ public static final Offset OFFSET_MOBSU_OBST_MNE_APMNE = Offset.fromFraction(0.5, 0.35); - /** Offset for the Wide Area Mines graphic (2.X.3.1.5.6). */ + /** + * Offset for the Wide Area Mines graphic (2.X.3.1.5.6). + */ public static final Offset OFFSET_MOBSU_OBST_MNE_WAMNE = Offset.fromFraction(0.5, 0.71); - /** Offset for the Sea Mine-Like Hazard graphic (2.X.6.2.1). */ + /** + * Offset for the Sea Mine-Like Hazard graphic (2.X.6.2.1). + */ public static final Offset OFFSET_OTH_HAZ_SML = Offset.fromFraction(0.5, 0.33); - /** Map to store defaults. */ + /** + * Map to store defaults. + */ protected Map offsets = new HashMap(); - /** Create the map and populate it with the default offsets. */ - public DefaultOffsets() - { + /** + * Create the map and populate it with the default offsets. + */ + public DefaultOffsets() { this.populate(); } @@ -58,134 +74,124 @@ public DefaultOffsets() * * @return Default offset for the specified graphic. */ - public Offset get(String sidc) - { + public Offset get(String sidc) { Offset offset = this.offsets.get(sidc); return offset != null ? offset : DEFAULT_OFFSET; } - /** Populate the map with default offsets. */ - protected void populate() - { + /** + * Populate the map with default offsets. + */ + protected void populate() { // A bunch of graphics are anchored on the bottom edge this.putAll(Offset.BOTTOM_CENTER, - C2GM_GNL_PNT_USW_UH2_BCON, - C2GM_GNL_PNT_USW_UH2_LCON, - C2GM_GNL_PNT_USW_UH2_SNK, - C2GM_GNL_PNT_USW_SNBY, - C2GM_GNL_PNT_USW_SNBY_BT, - - C2GM_GNL_PNT_REFPNT_PNTINR, - C2GM_GNL_PNT_WPN_ENTPNT, - C2GM_GNL_PNT_WPN_GRDZRO, - C2GM_GNL_PNT_WPN_MSLPNT, - - C2GM_GNL_PNT_ACTPNT, - C2GM_GNL_PNT_ACTPNT_CHKPNT, - C2GM_GNL_PNT_ACTPNT_CONPNT, - C2GM_GNL_PNT_ACTPNT_LNKUPT, - C2GM_GNL_PNT_ACTPNT_PSSPNT, - C2GM_GNL_PNT_ACTPNT_RAYPNT, - C2GM_GNL_PNT_ACTPNT_RELPNT, - C2GM_GNL_PNT_ACTPNT_STRPNT, - C2GM_GNL_PNT_ACTPNT_AMNPNT, - - C2GM_AVN_PNT_DAPP, - C2GM_OFF_PNT_PNTD, - - MOBSU_OBST_ATO_TDTSM_FIXPFD, - MOBSU_OBST_ATO_TDTSM_MVB, - MOBSU_OBST_ATO_TDTSM_MVBPFD, - MOBSU_OBST_AVN_TWR_LOW, - MOBSU_OBST_AVN_TWR_HIGH, - MOBSU_OBSTBP_CSGSTE_ERP, - - MOBSU_CBRN_NDGZ, - MOBSU_CBRN_FAOTP, - MOBSU_CBRN_REEVNT_BIO, - MOBSU_CBRN_REEVNT_CML, - MOBSU_CBRN_DECONP_USP, - MOBSU_CBRN_DECONP_ALTUSP, - MOBSU_CBRN_DECONP_TRP, - MOBSU_CBRN_DECONP_EQT, - MOBSU_CBRN_DECONP_EQTTRP, - MOBSU_CBRN_DECONP_OPDECN, - MOBSU_CBRN_DECONP_TRGH, - - FSUPP_PNT_C2PNT_SCP, - FSUPP_PNT_C2PNT_FP, - FSUPP_PNT_C2PNT_RP, - FSUPP_PNT_C2PNT_HP, - FSUPP_PNT_C2PNT_LP, - - CSS_PNT_AEP, - CSS_PNT_CBNP, - CSS_PNT_CCP, - CSS_PNT_CVP, - CSS_PNT_DCP, - CSS_PNT_EPWCP, - CSS_PNT_LRP, - CSS_PNT_MCP, - CSS_PNT_RRRP, - CSS_PNT_ROM, - CSS_PNT_TCP, - CSS_PNT_TTP, - CSS_PNT_UMC, - CSS_PNT_SPT_GNL, - CSS_PNT_SPT_CLS1, - CSS_PNT_SPT_CLS2, - CSS_PNT_SPT_CLS3, - CSS_PNT_SPT_CLS4, - CSS_PNT_SPT_CLS5, - CSS_PNT_SPT_CLS6, - CSS_PNT_SPT_CLS7, - CSS_PNT_SPT_CLS8, - CSS_PNT_SPT_CLS9, - CSS_PNT_SPT_CLS10, - CSS_PNT_AP_ASP, - CSS_PNT_AP_ATP, - - OTH_ER_DTHAC, - OTH_ER_PIW, - OTH_ER_DSTVES, - - OTH_SSUBSR_BTMRTN, - OTH_SSUBSR_BTMRTN_INS, - OTH_SSUBSR_BTMRTN_SBRSOO, - OTH_SSUBSR_SA, - - EmsSidc.NATEVT_GEO_AVL, - EmsSidc.NATEVT_GEO_LNDSLD, - EmsSidc.NATEVT_GEO_SBSDNC, - EmsSidc.NATEVT_GEO_VLCTHT, - EmsSidc.NATEVT_HYDMET_DRGHT, - EmsSidc.NATEVT_HYDMET_FLD, - EmsSidc.NATEVT_HYDMET_INV, - EmsSidc.NATEVT_HYDMET_TSNMI, - EmsSidc.NATEVT_INFST_BIRD, - EmsSidc.NATEVT_INFST_INSCT, - EmsSidc.NATEVT_INFST_MICROB, - EmsSidc.NATEVT_INFST_REPT, - EmsSidc.NATEVT_INFST_RDNT + C2GM_GNL_PNT_USW_UH2_BCON, + C2GM_GNL_PNT_USW_UH2_LCON, + C2GM_GNL_PNT_USW_UH2_SNK, + C2GM_GNL_PNT_USW_SNBY, + C2GM_GNL_PNT_USW_SNBY_BT, + C2GM_GNL_PNT_REFPNT_PNTINR, + C2GM_GNL_PNT_WPN_ENTPNT, + C2GM_GNL_PNT_WPN_GRDZRO, + C2GM_GNL_PNT_WPN_MSLPNT, + C2GM_GNL_PNT_ACTPNT, + C2GM_GNL_PNT_ACTPNT_CHKPNT, + C2GM_GNL_PNT_ACTPNT_CONPNT, + C2GM_GNL_PNT_ACTPNT_LNKUPT, + C2GM_GNL_PNT_ACTPNT_PSSPNT, + C2GM_GNL_PNT_ACTPNT_RAYPNT, + C2GM_GNL_PNT_ACTPNT_RELPNT, + C2GM_GNL_PNT_ACTPNT_STRPNT, + C2GM_GNL_PNT_ACTPNT_AMNPNT, + C2GM_AVN_PNT_DAPP, + C2GM_OFF_PNT_PNTD, + MOBSU_OBST_ATO_TDTSM_FIXPFD, + MOBSU_OBST_ATO_TDTSM_MVB, + MOBSU_OBST_ATO_TDTSM_MVBPFD, + MOBSU_OBST_AVN_TWR_LOW, + MOBSU_OBST_AVN_TWR_HIGH, + MOBSU_OBSTBP_CSGSTE_ERP, + MOBSU_CBRN_NDGZ, + MOBSU_CBRN_FAOTP, + MOBSU_CBRN_REEVNT_BIO, + MOBSU_CBRN_REEVNT_CML, + MOBSU_CBRN_DECONP_USP, + MOBSU_CBRN_DECONP_ALTUSP, + MOBSU_CBRN_DECONP_TRP, + MOBSU_CBRN_DECONP_EQT, + MOBSU_CBRN_DECONP_EQTTRP, + MOBSU_CBRN_DECONP_OPDECN, + MOBSU_CBRN_DECONP_TRGH, + FSUPP_PNT_C2PNT_SCP, + FSUPP_PNT_C2PNT_FP, + FSUPP_PNT_C2PNT_RP, + FSUPP_PNT_C2PNT_HP, + FSUPP_PNT_C2PNT_LP, + CSS_PNT_AEP, + CSS_PNT_CBNP, + CSS_PNT_CCP, + CSS_PNT_CVP, + CSS_PNT_DCP, + CSS_PNT_EPWCP, + CSS_PNT_LRP, + CSS_PNT_MCP, + CSS_PNT_RRRP, + CSS_PNT_ROM, + CSS_PNT_TCP, + CSS_PNT_TTP, + CSS_PNT_UMC, + CSS_PNT_SPT_GNL, + CSS_PNT_SPT_CLS1, + CSS_PNT_SPT_CLS2, + CSS_PNT_SPT_CLS3, + CSS_PNT_SPT_CLS4, + CSS_PNT_SPT_CLS5, + CSS_PNT_SPT_CLS6, + CSS_PNT_SPT_CLS7, + CSS_PNT_SPT_CLS8, + CSS_PNT_SPT_CLS9, + CSS_PNT_SPT_CLS10, + CSS_PNT_AP_ASP, + CSS_PNT_AP_ATP, + OTH_ER_DTHAC, + OTH_ER_PIW, + OTH_ER_DSTVES, + OTH_SSUBSR_BTMRTN, + OTH_SSUBSR_BTMRTN_INS, + OTH_SSUBSR_BTMRTN_SBRSOO, + OTH_SSUBSR_SA, + EmsSidc.NATEVT_GEO_AVL, + EmsSidc.NATEVT_GEO_LNDSLD, + EmsSidc.NATEVT_GEO_SBSDNC, + EmsSidc.NATEVT_GEO_VLCTHT, + EmsSidc.NATEVT_HYDMET_DRGHT, + EmsSidc.NATEVT_HYDMET_FLD, + EmsSidc.NATEVT_HYDMET_INV, + EmsSidc.NATEVT_HYDMET_TSNMI, + EmsSidc.NATEVT_INFST_BIRD, + EmsSidc.NATEVT_INFST_INSCT, + EmsSidc.NATEVT_INFST_MICROB, + EmsSidc.NATEVT_INFST_REPT, + EmsSidc.NATEVT_INFST_RDNT ); // Sonobouy and a few other graphics are anchored a point 25% up from the bottom edge. this.putAll(OFFSET_BOTTOM_QUARTER, - C2GM_GNL_PNT_USW_SNBY, - C2GM_GNL_PNT_USW_SNBY_PTNCTR, - C2GM_GNL_PNT_USW_SNBY_DIFAR, - C2GM_GNL_PNT_USW_SNBY_LOFAR, - C2GM_GNL_PNT_USW_SNBY_CASS, - C2GM_GNL_PNT_USW_SNBY_DICASS, - C2GM_GNL_PNT_USW_SNBY_BT, - C2GM_GNL_PNT_USW_SNBY_ANM, - C2GM_GNL_PNT_USW_SNBY_VLAD, - C2GM_GNL_PNT_USW_SNBY_ATAC, - C2GM_GNL_PNT_USW_SNBY_RO, - C2GM_GNL_PNT_USW_SNBY_KGP, - C2GM_GNL_PNT_USW_SNBY_EXP, - MOBSU_OBST_BBY, - MOBSU_OBST_MNE_ATMDIR); + C2GM_GNL_PNT_USW_SNBY, + C2GM_GNL_PNT_USW_SNBY_PTNCTR, + C2GM_GNL_PNT_USW_SNBY_DIFAR, + C2GM_GNL_PNT_USW_SNBY_LOFAR, + C2GM_GNL_PNT_USW_SNBY_CASS, + C2GM_GNL_PNT_USW_SNBY_DICASS, + C2GM_GNL_PNT_USW_SNBY_BT, + C2GM_GNL_PNT_USW_SNBY_ANM, + C2GM_GNL_PNT_USW_SNBY_VLAD, + C2GM_GNL_PNT_USW_SNBY_ATAC, + C2GM_GNL_PNT_USW_SNBY_RO, + C2GM_GNL_PNT_USW_SNBY_KGP, + C2GM_GNL_PNT_USW_SNBY_EXP, + MOBSU_OBST_BBY, + MOBSU_OBST_MNE_ATMDIR); // A handful of graphics have unique offsets this.offsets.put(C2GM_GNL_PNT_WPN_DRPPNT, OFFSET_C2GM_GNL_PNT_WPN_DRPPNT); @@ -200,12 +206,10 @@ protected void populate() * Map one value to many keys. * * @param value Value to add. - * @param keys Keys that map to the value. + * @param keys Keys that map to the value. */ - protected void putAll(Offset value, String... keys) - { - for (String sidc : keys) - { + protected void putAll(Offset value, String... keys) { + for (String sidc : keys) { this.offsets.put(sidc, value); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/EchelonSymbol.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/EchelonSymbol.java index 27c67ea275..4a23c01f3d 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/EchelonSymbol.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/EchelonSymbol.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics; import gov.nasa.worldwind.*; @@ -24,16 +23,22 @@ * @author pabercrombie * @version $Id: EchelonSymbol.java 2196 2014-08-06 19:42:15Z tgaskins $ */ -public class EchelonSymbol extends AbstractTacticalSymbol -{ +public class EchelonSymbol extends AbstractTacticalSymbol { + protected static final Offset DEFAULT_OFFSET = Offset.fromFraction(0.5, -0.5); - /** Identifier for this graphic. */ + /** + * Identifier for this graphic. + */ protected String sidc; - /** The label is drawn along a line from the label position to the orientation position. */ + /** + * The label is drawn along a line from the label position to the orientation position. + */ protected Position orientationPosition; - /** Rotation to apply to symbol, computed each frame. */ + /** + * Rotation to apply to symbol, computed each frame. + */ protected Angle rotation; /** @@ -45,12 +50,10 @@ public class EchelonSymbol extends AbstractTacticalSymbol * * @throws IllegalArgumentException if {@code sidc} is null, or does not contain a value for the Echelon field. */ - public EchelonSymbol(String sidc) - { + public EchelonSymbol(String sidc) { super(); - if (sidc == null) - { + if (sidc == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -58,8 +61,7 @@ public EchelonSymbol(String sidc) SymbolCode symbolCode = new SymbolCode(sidc); String echelon = symbolCode.getEchelon(); - if (SymbolCode.isFieldEmpty(echelon)) - { + if (SymbolCode.isFieldEmpty(echelon)) { String msg = Logging.getMessage("Symbology.InvalidSymbolCode", sidc); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -72,7 +74,7 @@ public EchelonSymbol(String sidc) // Configure this tactical point graphic's icon retriever and modifier retriever with either the // configuration value or the default value (in that order of precedence). String iconRetrieverPath = Configuration.getStringValue(AVKey.MIL_STD_2525_ICON_RETRIEVER_PATH, - MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); + MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); this.setIconRetriever(new MilStd2525ModifierRetriever(iconRetrieverPath)); } @@ -82,8 +84,7 @@ public EchelonSymbol(String sidc) * * @return Position used to orient the label. May be null. */ - public Position getOrientationPosition() - { + public Position getOrientationPosition() { return this.orientationPosition; } @@ -93,14 +94,14 @@ public Position getOrientationPosition() * * @param orientationPosition Draw label oriented toward this position. */ - public void setOrientationPosition(Position orientationPosition) - { + public void setOrientationPosition(Position orientationPosition) { this.orientationPosition = orientationPosition; } - /** {@inheritDoc} */ - public String getIdentifier() - { + /** + * {@inheritDoc} + */ + public String getIdentifier() { SymbolCode symbolCode = new SymbolCode(this.sidc); String echelon = symbolCode.getEchelon(); @@ -108,32 +109,31 @@ public String getIdentifier() } @Override - protected AVList assembleIconRetrieverParameters(AVList params) - { + protected AVList assembleIconRetrieverParameters(AVList params) { params = super.assembleIconRetrieverParameters(params); - if (params == null) + if (params == null) { params = new AVListImpl(); + } Material material = this.getActiveAttributes().getTextModifierMaterial(); - if (material != null) + if (material != null) { params.setValue(AVKey.COLOR, material.getDiffuse()); + } return params; } @Override - protected void computeTransform(DrawContext dc, OrderedSymbol osym) - { + protected void computeTransform(DrawContext dc, OrderedSymbol osym) { super.computeTransform(dc, osym); boolean orientationReversed = false; - if (this.orientationPosition != null) - { + if (this.orientationPosition != null) { // TODO apply altitude mode to orientation position // Project the orientation point onto the screen Vec4 orientationPlacePoint = dc.computeTerrainPoint(this.orientationPosition.getLatitude(), - this.orientationPosition.getLongitude(), 0); + this.orientationPosition.getLongitude(), 0); Vec4 orientationScreenPoint = dc.getView().project(orientationPlacePoint); this.rotation = this.computeRotation(osym.screenPoint, orientationScreenPoint); @@ -141,24 +141,21 @@ protected void computeTransform(DrawContext dc, OrderedSymbol osym) orientationReversed = (osym.screenPoint.x <= orientationScreenPoint.x); } - if (this.getOffset() != null && this.iconRect != null) - { + if (this.getOffset() != null && this.iconRect != null) { Point2D offsetPoint = this.getOffset().computeOffset(this.iconRect.getWidth(), this.iconRect.getHeight(), - null, null); + null, null); // If a rotation is applied to the image, then rotate the offset as well. An offset in the x direction // will move the image along the orientation line, and a offset in the y direction will move the image // perpendicular to the orientation line. - if (this.rotation != null) - { + if (this.rotation != null) { double dy = offsetPoint.getY(); // If the orientation is reversed we need to adjust the vertical offset to compensate for the flipped // image. For example, if the offset normally aligns the top of the image with the place point then without // this adjustment the bottom of the image would align with the place point when the orientation is // reversed. - if (orientationReversed) - { + if (orientationReversed) { dy = -(dy + this.iconRect.getHeight()); } @@ -172,24 +169,21 @@ protected void computeTransform(DrawContext dc, OrderedSymbol osym) osym.dx = -this.iconRect.getX() - offsetPoint.getX(); osym.dy = -(this.iconRect.getY() - offsetPoint.getY()); - } - else - { + } else { osym.dx = 0; osym.dy = 0; } } - /** Overridden to apply rotation. */ + /** + * Overridden to apply rotation. + */ @Override - protected void drawIcon(DrawContext dc) - { + protected void drawIcon(DrawContext dc) { boolean matrixPushed = false; GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { - if (this.rotation != null) - { + try { + if (this.rotation != null) { gl.glPushMatrix(); gl.glRotated(this.rotation.degrees, 0, 0, 1); matrixPushed = true; @@ -199,37 +193,32 @@ protected void drawIcon(DrawContext dc) gl.glDisable(GL.GL_DEPTH_TEST); super.drawIcon(dc); - } - finally - { + } finally { gl.glEnable(GL.GL_DEPTH_TEST); - if (matrixPushed) + if (matrixPushed) { gl.glPopMatrix(); + } } } /** * Compute the amount of rotation to apply to a label in order to keep it oriented toward its orientation position. * - * @param screenPoint Geographic position of the text, projected onto the screen. + * @param screenPoint Geographic position of the text, projected onto the screen. * @param orientationScreenPoint Orientation position, projected onto the screen. * * @return The rotation angle to apply when drawing the label. */ - protected Angle computeRotation(Vec4 screenPoint, Vec4 orientationScreenPoint) - { + protected Angle computeRotation(Vec4 screenPoint, Vec4 orientationScreenPoint) { // Determine delta between the orientation position and the label position double deltaX = screenPoint.x - orientationScreenPoint.x; double deltaY = screenPoint.y - orientationScreenPoint.y; - if (deltaX != 0) - { + if (deltaX != 0) { double angle = Math.atan(deltaY / deltaX); return Angle.fromRadians(angle); - } - else - { + } else { return Angle.POS90; // Vertical label } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/EmsSidc.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/EmsSidc.java index 9abb39c5b0..f862d611bc 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/EmsSidc.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/EmsSidc.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics; /** @@ -16,36 +15,66 @@ * @author pabercrombie * @version $Id$ */ -public interface EmsSidc -{ - /** Aftershock. */ +public interface EmsSidc { + + /** + * Aftershock. + */ final String NATEVT_GEO_AFTSHK = "E-N-AA---------"; - /** Avalanche. */ + /** + * Avalanche. + */ final String NATEVT_GEO_AVL = "E-N-AB---------"; - /** Earthquake epicenter. */ + /** + * Earthquake epicenter. + */ final String NATEVT_GEO_EQKEPI = "E-N-AC---------"; - /** Landslide. */ + /** + * Landslide. + */ final String NATEVT_GEO_LNDSLD = "E-N-AD---------"; - /** Subsidence. */ + /** + * Subsidence. + */ final String NATEVT_GEO_SBSDNC = "E-N-AE---------"; - /** Volcanic threat. */ + /** + * Volcanic threat. + */ final String NATEVT_GEO_VLCTHT = "E-N-AG---------"; - /** Drought. */ + /** + * Drought. + */ final String NATEVT_HYDMET_DRGHT = "E-N-BB---------"; - /** Flood. */ + /** + * Flood. + */ final String NATEVT_HYDMET_FLD = "E-N-BC---------"; - /** Inversion. */ + /** + * Inversion. + */ final String NATEVT_HYDMET_INV = "E-N-BF---------"; - /** Tsunami. */ + /** + * Tsunami. + */ final String NATEVT_HYDMET_TSNMI = "E-N-BM---------"; - /** Bird infestation. */ + /** + * Bird infestation. + */ final String NATEVT_INFST_BIRD = "E-N-CA---------"; - /** Insect infestation. */ + /** + * Insect infestation. + */ final String NATEVT_INFST_INSCT = "E-N-CB---------"; - /** Microbial infestation. */ + /** + * Microbial infestation. + */ final String NATEVT_INFST_MICROB = "E-N-CC---------"; - /** Reptile infestation. */ + /** + * Reptile infestation. + */ final String NATEVT_INFST_REPT = "E-N-CD---------"; - /** Rodent infestation. */ + /** + * Rodent infestation. + */ final String NATEVT_INFST_RDNT = "E-N-CE---------"; } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/MetocSidc.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/MetocSidc.java index 610a6fc2b7..3202253a5d 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/MetocSidc.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/MetocSidc.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics; /** @@ -14,700 +13,1394 @@ * @author pabercrombie * @version $Id: MetocSidc.java 442 2012-03-10 19:48:24Z pabercrombie $ */ -public interface MetocSidc -{ - /** Low pressure center. */ +public interface MetocSidc { + + /** + * Low pressure center. + */ final String AMPHC_PRS_LOWCTR = "WAS-PL----P----"; - /** Cyclone center. */ + /** + * Cyclone center. + */ final String AMPHC_PRS_LOWCTR_CYC = "WAS-PC----P----"; - /** Tropopause low. */ + /** + * Tropopause low. + */ final String AMPHC_PRS_LOWCTR_TROPLW = "WAS-PLT---P----"; - /** High pressure center. */ + /** + * High pressure center. + */ final String AMPHC_PRS_HGHCTR = "WAS-PH----P----"; - /** Anticyclone center. */ + /** + * Anticyclone center. + */ final String AMPHC_PRS_HGHCTR_ACYC = "WAS-PA----P----"; - /** Tropopause high. */ + /** + * Tropopause high. + */ final String AMPHC_PRS_HGHCTR_TROPHG = "WAS-PHT---P----"; - /** Frontal systems. */ + /** + * Frontal systems. + */ final String AMPHC_PRS_FRNSYS = "WA-DPF-----L---"; - /** Cold front. */ + /** + * Cold front. + */ final String AMPHC_PRS_FRNSYS_CLDFRN = "WA-DPFC----L---"; - /** Upper cold front. */ + /** + * Upper cold front. + */ final String AMPHC_PRS_FRNSYS_CLDFRN_UPP = "WA-DPFCU---L---"; - /** Cold frontogenesis. */ + /** + * Cold frontogenesis. + */ final String AMPHC_PRS_FRNSYS_CLDFRN_FRGS = "WA-DPFC-FG-L---"; - /** Cold frontolysis. */ + /** + * Cold frontolysis. + */ final String AMPHC_PRS_FRNSYS_CLDFRN_FRLS = "WA-DPFC-FY-L---"; - /** Warm front. */ + /** + * Warm front. + */ final String AMPHC_PRS_FRNSYS_WRMFRN = "WA-DPFW----L---"; - /** Upper warm front. */ + /** + * Upper warm front. + */ final String AMPHC_PRS_FRNSYS_WRMFRN_UPP = "WA-DPFWU---L---"; - /** Warm frontogenesis. */ + /** + * Warm frontogenesis. + */ final String AMPHC_PRS_FRNSYS_WRMFRN_FRGS = "WA-DPFW-FG-L---"; - /** Warm frontolysis. */ + /** + * Warm frontolysis. + */ final String AMPHC_PRS_FRNSYS_WRMFRN_FRLS = "WA-DPFW-FY-L---"; - /** Occluded front. */ + /** + * Occluded front. + */ final String AMPHC_PRS_FRNSYS_OCD = "WA-DPFO----L---"; - /** Upper occluded front. */ + /** + * Upper occluded front. + */ final String AMPHC_PRS_FRNSYS_OCD_UPP = "WA-DPFOU---L---"; - /** Occluded frontolysis. */ + /** + * Occluded frontolysis. + */ final String AMPHC_PRS_FRNSYS_OCD_FRLS = "WA-DPFO-FY-L---"; - /** Stationary front. */ + /** + * Stationary front. + */ final String AMPHC_PRS_FRNSYS_STAT = "WA-DPFS----L---"; - /** Upper stationary front. */ + /** + * Upper stationary front. + */ final String AMPHC_PRS_FRNSYS_STAT_UPP = "WA-DPFSU---L---"; - /** Stationary frontogenesis. */ + /** + * Stationary frontogenesis. + */ final String AMPHC_PRS_FRNSYS_STAT_FRGS = "WA-DPFS-FG-L---"; - /** Stationary frontolysis. */ + /** + * Stationary frontolysis. + */ final String AMPHC_PRS_FRNSYS_STAT_FRLS = "WA-DPFS-FY-L---"; - /** Pressure systems, trough axis. */ + /** + * Pressure systems, trough axis. + */ final String AMPHC_PRS_LNE_TRUAXS = "WA-DPXT----L---"; - /** Ridge axis. */ + /** + * Ridge axis. + */ final String AMPHC_PRS_LNE_RDGAXS = "WA-DPXR----L---"; - /** Severe squall line. */ + /** + * Severe squall line. + */ final String AMPHC_PRS_LNE_SSL = "WA-DPXSQ---L---"; - /** Instability line. */ + /** + * Instability line. + */ final String AMPHC_PRS_LNE_ISTB = "WA-DPXIL---L---"; - /** Shear line. */ + /** + * Shear line. + */ final String AMPHC_PRS_LNE_SHA = "WA-DPXSH---L---"; - /** Inter-tropical convergance zone. */ + /** + * Inter-tropical convergance zone. + */ final String AMPHC_PRS_LNE_ITCZ = "WA-DPXITCZ-L---"; - /** Convergance line. */ + /** + * Convergance line. + */ final String AMPHC_PRS_LNE_CNGLNE = "WA-DPXCV---L---"; - /** Inter-tropical discontinuity. */ + /** + * Inter-tropical discontinuity. + */ final String AMPHC_PRS_LNE_ITD = "WA-DPXITD--L---"; - /** Turbulence - light. */ + /** + * Turbulence - light. + */ final String AMPHC_TRB_LIT = "WAS-TL----P----"; - /** Turbulence - moderate. */ + /** + * Turbulence - moderate. + */ final String AMPHC_TRB_MOD = "WAS-TM----P----"; - /** Turbulence - severe. */ + /** + * Turbulence - severe. + */ final String AMPHC_TRB_SVR = "WAS-TS----P----"; - /** Turbulence - extreme. */ + /** + * Turbulence - extreme. + */ final String AMPHC_TRB_EXT = "WAS-TE----P----"; - /** Mountain waves. */ + /** + * Mountain waves. + */ final String AMPHC_TRB_MNTWAV = "WAS-T-MW--P----"; - /** Clear icing - light. */ + /** + * Clear icing - light. + */ final String AMPHC_ICG_CLR_LIT = "WAS-ICL---P----"; - /** Clear icing - moderate. */ + /** + * Clear icing - moderate. + */ final String AMPHC_ICG_CLR_MOD = "WAS-ICM---P----"; - /** Clear icing - severe. */ + /** + * Clear icing - severe. + */ final String AMPHC_ICG_CLR_SVR = "WAS-ICS---P----"; - /** Rime icing - light. */ + /** + * Rime icing - light. + */ final String AMPHC_ICG_RIME_LIT = "WAS-IRL---P----"; - /** Rime icing - moderate. */ + /** + * Rime icing - moderate. + */ final String AMPHC_ICG_RIME_MOD = "WAS-IRM---P----"; - /** Rime icing - severe. */ + /** + * Rime icing - severe. + */ final String AMPHC_ICG_RIME_SVR = "WAS-IRS---P----"; - /** Mixed icing - light. */ + /** + * Mixed icing - light. + */ final String AMPHC_ICG_MIX_LIT = "WAS-IML---P----"; - /** Mixed icing - moderate. */ + /** + * Mixed icing - moderate. + */ final String AMPHC_ICG_MIX_MOD = "WAS-IMM---P----"; - /** Mixed icing - severe. */ + /** + * Mixed icing - severe. + */ final String AMPHC_ICG_MIX_SVR = "WAS-IMS---P----"; - /** Calm winds. */ + /** + * Calm winds. + */ final String AMPHC_WND_CALM = "WAS-WC----P----"; - /** Wind plot. */ + /** + * Wind plot. + */ final String AMPHC_WND_PLT = "WAS-WP----P----"; - /** Jet stream. */ + /** + * Jet stream. + */ final String AMPHC_WND_JTSM = "WA-DWJ-----L---"; - /** Stream line. */ + /** + * Stream line. + */ final String AMPHC_WND_SMLNE = "WA-DWS-----L---"; - /** Clear sky. */ + /** + * Clear sky. + */ final String AMPHC_CUDCOV_SYM_SKC = "WAS-CCCSCSP----"; - /** Few coverage. */ + /** + * Few coverage. + */ final String AMPHC_CUDCOV_SYM_FEW = "WAS-CCCSFCP----"; - /** Scattered coverage. */ + /** + * Scattered coverage. + */ final String AMPHC_CUDCOV_SYM_SCT = "WAS-CCCSSCP----"; - /** Broken coverage. */ + /** + * Broken coverage. + */ final String AMPHC_CUDCOV_SYM_BKN = "WAS-CCCSBCP----"; - /** Overcast coverage. */ + /** + * Overcast coverage. + */ final String AMPHC_CUDCOV_SYM_OVC = "WAS-CCCSOCP----"; - /** Sky totally or partially obscured. */ + /** + * Sky totally or partially obscured. + */ final String AMPHC_CUDCOV_SYM_STOPO = "WAS-CCCSOBP----"; - /** Rain - intermittent light. */ + /** + * Rain - intermittent light. + */ final String AMPHC_WTH_RA_INMLIT = "WAS-WSR-LIP----"; - /** Rain - continuous light. */ + /** + * Rain - continuous light. + */ final String AMPHC_WTH_RA_INMLIT_CTSLIT = "WAS-WSR-LCP----"; - /** Rain - intermittent moderate. */ + /** + * Rain - intermittent moderate. + */ final String AMPHC_WTH_RA_INMMOD = "WAS-WSR-MIP----"; - /** Rain - continuous moderate. */ + /** + * Rain - continuous moderate. + */ final String AMPHC_WTH_RA_INMMOD_CTSMOD = "WAS-WSR-MCP----"; - /** Rain - intermittent heavy. */ + /** + * Rain - intermittent heavy. + */ final String AMPHC_WTH_RA_INMHVY = "WAS-WSR-HIP----"; - /** Rain - continuous heavy. */ + /** + * Rain - continuous heavy. + */ final String AMPHC_WTH_RA_INMHVY_CTSHVY = "WAS-WSR-HCP----"; - /** Freezing rain - light. */ + /** + * Freezing rain - light. + */ final String AMPHC_WTH_FZRA_LIT = "WAS-WSRFL-P----"; - /** Freezing rain - moderate/heavy. */ + /** + * Freezing rain - moderate/heavy. + */ final String AMPHC_WTH_FZRA_MODHVY = "WAS-WSRFMHP----"; - /** Rain showers - light. */ + /** + * Rain showers - light. + */ final String AMPHC_WTH_RASWR_LIT = "WAS-WSRSL-P----"; - /** Rain showers - moderate/heavy. */ + /** + * Rain showers - moderate/heavy. + */ final String AMPHC_WTH_RASWR_MODHVY = "WAS-WSRSMHP----"; - /** Rain showers - torrential. */ + /** + * Rain showers - torrential. + */ final String AMPHC_WTH_RASWR_TOR = "WAS-WSRST-P----"; - /** Drizzle - intermittent light. */ + /** + * Drizzle - intermittent light. + */ final String AMPHC_WTH_DZ_INMLIT = "WAS-WSD-LIP----"; - /** Drizzle - continuous light. */ + /** + * Drizzle - continuous light. + */ final String AMPHC_WTH_DZ_INMLIT_CTSLIT = "WAS-WSD-LCP----"; - /** Drizzle - intermittent moderate. */ + /** + * Drizzle - intermittent moderate. + */ final String AMPHC_WTH_DZ_INMMOD = "WAS-WSD-MIP----"; - /** Drizzle - continuous moderate. */ + /** + * Drizzle - continuous moderate. + */ final String AMPHC_WTH_DZ_INMMOD_CTSMOD = "WAS-WSD-MCP----"; - /** Drizzle - intermittent heavy. */ + /** + * Drizzle - intermittent heavy. + */ final String AMPHC_WTH_DZ_INMHVY = "WAS-WSD-HIP----"; - /** Drizzle - continuous heavy. */ + /** + * Drizzle - continuous heavy. + */ final String AMPHC_WTH_DZ_INMHVY_CTSHVY = "WAS-WSD-HCP----"; - /** Freezing drizzle - light. */ + /** + * Freezing drizzle - light. + */ final String AMPHC_WTH_FZDZ_LIT = "WAS-WSDFL-P----"; - /** Freezing drizzle - moderate/heavy. */ + /** + * Freezing drizzle - moderate/heavy. + */ final String AMPHC_WTH_FZDZ_MODHVY = "WAS-WSDFMHP----"; - /** Rain or drizzle and snow - light. */ + /** + * Rain or drizzle and snow - light. + */ final String AMPHC_WTH_RASN_RDSLIT = "WAS-WSM-L-P----"; - /** Rain or drizzle and snow - moderate/heavy. */ + /** + * Rain or drizzle and snow - moderate/heavy. + */ final String AMPHC_WTH_RASN_RDSMH = "WAS-WSM-MHP----"; - /** Rain and snow showers - light. */ + /** + * Rain and snow showers - light. + */ final String AMPHC_WTH_RASN_SWRLIT = "WAS-WSMSL-P----"; - /** Rain and snow showers - moderate/heavy. */ + /** + * Rain and snow showers - moderate/heavy. + */ final String AMPHC_WTH_RASN_SWRMOD = "WAS-WSMSMHP----"; - /** Snow - intermittent light. */ + /** + * Snow - intermittent light. + */ final String AMPHC_WTH_SN_INMLIT = "WAS-WSS-LIP----"; - /** Snow - continuous light. */ + /** + * Snow - continuous light. + */ final String AMPHC_WTH_SN_INMLIT_CTSLIT = "WAS-WSS-LCP----"; - /** Snow - intermittent moderate. */ + /** + * Snow - intermittent moderate. + */ final String AMPHC_WTH_SN_INMMOD = "WAS-WSS-MIP----"; - /** Snow - continuous moderate. */ + /** + * Snow - continuous moderate. + */ final String AMPHC_WTH_SN_INMMOD_CTSMOD = "WAS-WSS-MCP----"; - /** Snow - intermittent heavy. */ + /** + * Snow - intermittent heavy. + */ final String AMPHC_WTH_SN_INMHVY = "WAS-WSS-HIP----"; - /** Snow - continuous heavy. */ + /** + * Snow - continuous heavy. + */ final String AMPHC_WTH_SN_INMHVY_CTSHVY = "WAS-WSS-HCP----"; - /** Blowing snow - light/moderate. */ + /** + * Blowing snow - light/moderate. + */ final String AMPHC_WTH_SN_BLSNLM = "WAS-WSSBLMP----"; - /** Blowing snow - heavy. */ + /** + * Blowing snow - heavy. + */ final String AMPHC_WTH_SN_BLSNHY = "WAS-WSSBH-P----"; - /** Snow grains. */ + /** + * Snow grains. + */ final String AMPHC_WTH_SG = "WAS-WSSG--P----"; - /** Snow showers - light. */ + /** + * Snow showers - light. + */ final String AMPHC_WTH_SSWR_LIT = "WAS-WSSSL-P----"; - /** Snow showers - moderate/heavy. */ + /** + * Snow showers - moderate/heavy. + */ final String AMPHC_WTH_SSWR_MODHVY = "WAS-WSSSMHP----"; - /** Hail - light not associated with thunder. */ + /** + * Hail - light not associated with thunder. + */ final String AMPHC_WTH_HL_LIT = "WAS-WSGRL-P----"; - /** Hail - moderate/heavy not associated with thunder. */ + /** + * Hail - moderate/heavy not associated with thunder. + */ final String AMPHC_WTH_HL_MODHVY = "WAS-WSGRMHP----"; - /** Ice crystals (diamond dust). */ + /** + * Ice crystals (diamond dust). + */ final String AMPHC_WTH_IC = "WAS-WSIC--P----"; - /** Ice pellets - light. */ + /** + * Ice pellets - light. + */ final String AMPHC_WTH_PE_LIT = "WAS-WSPLL-P----"; - /** Ice pellets - moderate. */ + /** + * Ice pellets - moderate. + */ final String AMPHC_WTH_PE_MOD = "WAS-WSPLM-P----"; - /** Ice pellets - heavy. */ + /** + * Ice pellets - heavy. + */ final String AMPHC_WTH_PE_HVY = "WAS-WSPLH-P----"; - /** Thunderstorm - no precipitation. */ + /** + * Thunderstorm - no precipitation. + */ final String AMPHC_WTH_STMS_TS = "WAS-WST-NPP----"; - /** Thunderstorm light to moderate with rain/snow - no hail. */ + /** + * Thunderstorm light to moderate with rain/snow - no hail. + */ final String AMPHC_WTH_STMS_TSLMNH = "WAS-WSTMR-P----"; - /** Thunderstorm heavy with rain/snow - no hail. */ + /** + * Thunderstorm heavy with rain/snow - no hail. + */ final String AMPHC_WTH_STMS_TSHVNH = "WAS-WSTHR-P----"; - /** Thunderstorm light to moderate - with hail. */ + /** + * Thunderstorm light to moderate - with hail. + */ final String AMPHC_WTH_STMS_TSLMWH = "WAS-WSTMH-P----"; - /** Thunderstorm heavy - with hail. */ + /** + * Thunderstorm heavy - with hail. + */ final String AMPHC_WTH_STMS_TSHVWH = "WAS-WSTHH-P----"; - /** Funnel cloud (tornado/waterspout). */ + /** + * Funnel cloud (tornado/waterspout). + */ final String AMPHC_WTH_STMS_FC = "WAS-WST-FCP----"; - /** Squall. */ + /** + * Squall. + */ final String AMPHC_WTH_STMS_SQL = "WAS-WST-SQP----"; - /** Lightning. */ + /** + * Lightning. + */ final String AMPHC_WTH_STMS_LTG = "WAS-WST-LGP----"; - /** Fog - shallow patches. */ + /** + * Fog - shallow patches. + */ final String AMPHC_WTH_FG_SHWPTH = "WAS-WSFGPSP----"; - /** Fog -shallow continuous. */ + /** + * Fog -shallow continuous. + */ final String AMPHC_WTH_FG_SHWCTS = "WAS-WSFGCSP----"; - /** Fog - patchy. */ + /** + * Fog - patchy. + */ final String AMPHC_WTH_FG_PTHY = "WAS-WSFGP-P----"; - /** Fog - sky visible. */ + /** + * Fog - sky visible. + */ final String AMPHC_WTH_FG_SKYVSB = "WAS-WSFGSVP----"; - /** Fog - sky obscured. */ + /** + * Fog - sky obscured. + */ final String AMPHC_WTH_FG_SKYOBD = "WAS-WSFGSOP----"; - /** Fog - freezing, sky visible. */ + /** + * Fog - freezing, sky visible. + */ final String AMPHC_WTH_FG_FZSV = "WAS-WSFGFVP----"; - /** Fog - freezing, sky not visible. */ + /** + * Fog - freezing, sky not visible. + */ final String AMPHC_WTH_FG_FZSNV = "WAS-WSFGFOP----"; - /** Mist. */ + /** + * Mist. + */ final String AMPHC_WTH_MIST = "WAS-WSBR--P----"; - /** Smoke. */ + /** + * Smoke. + */ final String AMPHC_WTH_FU = "WAS-WSFU--P----"; - /** Haze. */ + /** + * Haze. + */ final String AMPHC_WTH_HZ = "WAS-WSHZ--P----"; - /** Dust/sand storm - light to moderate. */ + /** + * Dust/sand storm - light to moderate. + */ final String AMPHC_WTH_DTSD_LITMOD = "WAS-WSDSLMP----"; - /** Dust/sand storm - severe. */ + /** + * Dust/sand storm - severe. + */ final String AMPHC_WTH_DTSD_SVR = "WAS-WSDSS-P----"; - /** Dust devil. */ + /** + * Dust devil. + */ final String AMPHC_WTH_DTSD_DTDVL = "WAS-WSDD--P----"; - /** Blowing dust or sand. */ + /** + * Blowing dust or sand. + */ final String AMPHC_WTH_DTSD_BLDTSD = "WAS-WSDB--P----"; - /** Tropical depression. */ + /** + * Tropical depression. + */ final String AMPHC_WTH_TPLSYS_TROPDN = "WAS-WSTSD-P----"; - /** Tropical storm. */ + /** + * Tropical storm. + */ final String AMPHC_WTH_TPLSYS_TROPSM = "WAS-WSTSS-P----"; - /** Hurricane/typhoon. */ + /** + * Hurricane/typhoon. + */ final String AMPHC_WTH_TPLSYS_HC = "WAS-WSTSH-P----"; - /** Tropical storm wind areas and date/time labels. */ + /** + * Tropical storm wind areas and date/time labels. + */ final String AMPHC_WTH_TPLSYS_TSWADL = "WA-DWSTSWA--A--"; - /** Volcanic eruption. */ + /** + * Volcanic eruption. + */ final String AMPHC_WTH_VOLERN = "WAS-WSVE--P----"; - /** Volcanic ash. */ + /** + * Volcanic ash. + */ final String AMPHC_WTH_VOLERN_VOLASH = "WAS-WSVA--P----"; - /** Tropopause level. */ + /** + * Tropopause level. + */ final String AMPHC_WTH_TROPLV = "WAS-WST-LVP----"; - /** Freezing level. */ + /** + * Freezing level. + */ final String AMPHC_WTH_FZLVL = "WAS-WSF-LVP----"; - /** Precipitation of unknown type and intensity. */ + /** + * Precipitation of unknown type and intensity. + */ final String AMPHC_WTH_POUTAI = "WAS-WSUKP-P----"; - /** Instrument flight rule (IFR). */ + /** + * Instrument flight rule (IFR). + */ final String AMPHC_BDAWTH_IFR = "WA-DBAIF----A--"; - /** Marginal visual flight rule (MVFR). */ + /** + * Marginal visual flight rule (MVFR). + */ final String AMPHC_BDAWTH_MVFR = "WA-DBAMV----A--"; - /** Turbulence. */ + /** + * Turbulence. + */ final String AMPHC_BDAWTH_TRB = "WA-DBATB----A--"; - /** Icing. */ + /** + * Icing. + */ final String AMPHC_BDAWTH_ICG = "WA-DBAI-----A--"; - /** Liquid precipitation - non-convective continuous or intermittent. */ + /** + * Liquid precipitation - non-convective continuous or intermittent. + */ final String AMPHC_BDAWTH_LPNCI = "WA-DBALPNC--A--"; - /** Liquid precipitation - convective. */ + /** + * Liquid precipitation - convective. + */ final String AMPHC_BDAWTH_LPNCI_LPC = "WA-DBALPC---A--"; - /** Freezing/frozen precipitation. */ + /** + * Freezing/frozen precipitation. + */ final String AMPHC_BDAWTH_FZPPN = "WA-DBAFP----A--"; - /** Thunderstorms. */ + /** + * Thunderstorms. + */ final String AMPHC_BDAWTH_TS = "WA-DBAT-----A--"; - /** Fog. */ + /** + * Fog. + */ final String AMPHC_BDAWTH_FG = "WA-DBAFG----A--"; - /** Dust or sand. */ + /** + * Dust or sand. + */ final String AMPHC_BDAWTH_DTSD = "WA-DBAD-----A--"; - /** Operator-defined freeform. */ + /** + * Operator-defined freeform. + */ final String AMPHC_BDAWTH_ODFF = "WA-DBAFF----A--"; - /** Isobar - surface. */ + /** + * Isobar - surface. + */ final String AMPHC_ISP_ISB = "WA-DIPIB---L---"; - /** Contour - upper air. */ + /** + * Contour - upper air. + */ final String AMPHC_ISP_CTUR = "WA-DIPCO---L---"; - /** Isotherm. */ + /** + * Isotherm. + */ final String AMPHC_ISP_IST = "WA-DIPIS---L---"; - /** Isotach. */ + /** + * Isotach. + */ final String AMPHC_ISP_ISH = "WA-DIPIT---L---"; - /** Isodrosotherm. */ + /** + * Isodrosotherm. + */ final String AMPHC_ISP_ISD = "WA-DIPID---L---"; - /** Thickness. */ + /** + * Thickness. + */ final String AMPHC_ISP_THK = "WA-DIPTH---L---"; - /** Operator-defined freeform. */ + /** + * Operator-defined freeform. + */ final String AMPHC_ISP_ODFF = "WA-DIPFF---L---"; - /** Surface dry without cracks or appreciable dust or loose sand. */ + /** + * Surface dry without cracks or appreciable dust or loose sand. + */ // final String AMPHC_STOG_WOSMIC_SUFDRY = "WAS-GND-NCP----"; - /** Surface moist. */ + /** + * Surface moist. + */ final String AMPHC_STOG_WOSMIC_SUFMST = "WAS-GNM---P----"; - /** Surface wet, standing water in small or large pools. */ + /** + * Surface wet, standing water in small or large pools. + */ final String AMPHC_STOG_WOSMIC_SUFWET = "WAS-GNW-SWP----"; - /** Surface flooded. */ + /** + * Surface flooded. + */ final String AMPHC_STOG_WOSMIC_SUFFLD = "WAS-GNFL--P----"; - /** Surface frozen. */ + /** + * Surface frozen. + */ final String AMPHC_STOG_WOSMIC_SUFFZN = "WAS-GNFZ--P----"; - /** Glaze (thin ice) on ground. */ + /** + * Glaze (thin ice) on ground. + */ final String AMPHC_STOG_WOSMIC_GLZGRD = "WAS-GNG-TIP----"; - /** Loose dry dust or sand not covering ground completely. */ + /** + * Loose dry dust or sand not covering ground completely. + */ final String AMPHC_STOG_WOSMIC_LDNCGC = "WAS-GNLDN-P----"; - /** Thin loose dry dust or sand covering ground completely. */ + /** + * Thin loose dry dust or sand covering ground completely. + */ final String AMPHC_STOG_WOSMIC_TLDCGC = "WAS-GNLDTCP----"; - /** Moderate/thick loose dry dust or sand covering ground completely. */ + /** + * Moderate/thick loose dry dust or sand covering ground completely. + */ final String AMPHC_STOG_WOSMIC_MLDCGC = "WAS-GNLDMCP----"; - /** Extremely dry with cracks. */ + /** + * Extremely dry with cracks. + */ final String AMPHC_STOG_WOSMIC_EXTDWC = "WAS-GNDEWCP----"; - /** Predominately ice covered. */ + /** + * Predominately ice covered. + */ final String AMPHC_STOG_WSMIC_PDMIC = "WAS-GSI---P----"; - /** Compact or wet snow (with or without ice) covering less than one-half of ground. */ + /** + * Compact or wet snow (with or without ice) covering less than one-half of ground. + */ final String AMPHC_STOG_WSMIC_CWSNLH = "WAS-GSSCL-P----"; - /** Compact or wet snow (with or without ice) covering at least one-half ground, but ground not completely covered. */ + /** + * Compact or wet snow (with or without ice) covering at least one-half ground, but ground not completely covered. + */ final String AMPHC_STOG_WSMIC_CSNALH = "WAS-GSSCH-P----"; - /** Even layer of compact or wet snow covering ground completely. */ + /** + * Even layer of compact or wet snow covering ground completely. + */ final String AMPHC_STOG_WSMIC_ELCSCG = "WAS-GSSCCEP----"; - /** Uneven layer of compact or wet snow covering ground completely. */ + /** + * Uneven layer of compact or wet snow covering ground completely. + */ final String AMPHC_STOG_WSMIC_ULCSCG = "WAS-GSSCCUP----"; - /** Loose dry snow covering less than one-half of ground. */ + /** + * Loose dry snow covering less than one-half of ground. + */ final String AMPHC_STOG_WSMIC_LDSNLH = "WAS-GSSLL-P----"; - /** Loose dry snow covering at least one-half ground, but ground not completely covered. */ + /** + * Loose dry snow covering at least one-half ground, but ground not completely covered. + */ final String AMPHC_STOG_WSMIC_LDSALH = "WAS-GSSLH-P----"; - /** Even layer of loose dry snow covering ground completely. */ + /** + * Even layer of loose dry snow covering ground completely. + */ final String AMPHC_STOG_WSMIC_ELDSCG = "WAS-GSSLCEP----"; - /** Uneven layer of loose dry snow covering ground completely. */ + /** + * Uneven layer of loose dry snow covering ground completely. + */ final String AMPHC_STOG_WSMIC_ULDSCG = "WAS-GSSLCUP----"; - /** Snow covering ground completely; deep drifts. */ + /** + * Snow covering ground completely; deep drifts. + */ final String AMPHC_STOG_WSMIC_SCGC = "WAS-GSSDC-P----"; - /** Icebergs. */ + /** + * Icebergs. + */ final String OCA_ISYS_IB = "WOS-IB----P----"; - /** Many icebergs. */ + /** + * Many icebergs. + */ final String OCA_ISYS_IB_MNY = "WOS-IBM---P----"; - /** Belts and strips. */ + /** + * Belts and strips. + */ final String OCA_ISYS_IB_BAS = "WOS-IBBS--P----"; - /** Iceberg -general. */ + /** + * Iceberg -general. + */ final String OCA_ISYS_IB_GNL = "WOS-IBG---P----"; - /** Many icebergs -general. */ + /** + * Many icebergs -general. + */ final String OCA_ISYS_IB_MNYGNL = "WOS-IBMG--P----"; - /** Bergy bit. */ + /** + * Bergy bit. + */ final String OCA_ISYS_IB_BB = "WOS-IBBB--P----"; - /** Many bergy bits. */ + /** + * Many bergy bits. + */ final String OCA_ISYS_IB_MNYBB = "WOS-IBBBM-P----"; - /** Growler. */ + /** + * Growler. + */ final String OCA_ISYS_IB_GWL = "WOS-IBGL--P----"; - /** Many growlers. */ + /** + * Many growlers. + */ final String OCA_ISYS_IB_MNYGWL = "WOS-IBGLM-P----"; - /** Floeberg. */ + /** + * Floeberg. + */ final String OCA_ISYS_IB_FBG = "WOS-IBF---P----"; - /** Ice island. */ + /** + * Ice island. + */ final String OCA_ISYS_IB_II = "WOS-IBII--P----"; - /** Bergy water. */ + /** + * Bergy water. + */ final String OCA_ISYS_ICN_BW = "WOS-ICWB--P----"; - /** Water with radar targets. */ + /** + * Water with radar targets. + */ final String OCA_ISYS_ICN_WWRT = "WOS-ICWR--P----"; - /** Ice free. */ + /** + * Ice free. + */ final String OCA_ISYS_ICN_IF = "WOS-ICIF--P----"; - /** Convergence. */ + /** + * Convergence. + */ final String OCA_ISYS_DYNPRO_CNG = "WOS-IDC---P----"; - /** Divergence. */ + /** + * Divergence. + */ final String OCA_ISYS_DYNPRO_DVG = "WOS-IDD---P----"; - /** Shearing or shear zone. */ + /** + * Shearing or shear zone. + */ final String OCA_ISYS_DYNPRO_SHAZ = "WOS-IDS---P----"; - /** Ice drift (direction). */ + /** + * Ice drift (direction). + */ final String OCA_ISYS_DYNPRO_ID = "WO-DIDID---L---"; - /** Sea ice. */ + /** + * Sea ice. + */ final String OCA_ISYS_SI = "WOS-II----P----"; - /** Ice thickness (observed). */ + /** + * Ice thickness (observed). + */ final String OCA_ISYS_SI_ITOBS = "WOS-IITM--P----"; - /** Ice thickness (estimated). */ + /** + * Ice thickness (estimated). + */ final String OCA_ISYS_SI_ITEST = "WOS-IITE--P----"; - /** Melt puddles or flooded ice. */ + /** + * Melt puddles or flooded ice. + */ final String OCA_ISYS_SI_MPOFI = "WOS-IIP---P----"; - /** Limit of visual observation. */ + /** + * Limit of visual observation. + */ final String OCA_ISYS_LMT_LOVO = "WO-DILOV---L---"; - /** Limit of undercast. */ + /** + * Limit of undercast. + */ final String OCA_ISYS_LMT_LOU = "WO-DILUC---L---"; - /** Limit of radar observation. */ + /** + * Limit of radar observation. + */ final String OCA_ISYS_LMT_LORO = "WO-DILOR---L---"; - /** Observed ice edge or boundary. */ + /** + * Observed ice edge or boundary. + */ final String OCA_ISYS_LMT_OIEOB = "WO-DILIEO--L---"; - /** Estimated ice edge or boundary. */ + /** + * Estimated ice edge or boundary. + */ final String OCA_ISYS_LMT_EIEOB = "WO-DILIEE--L---"; - /** Ice edge or boundary from radar. */ + /** + * Ice edge or boundary from radar. + */ final String OCA_ISYS_LMT_IEOBFR = "WO-DILIER--L---"; - /** Openings in the ice, cracks. */ + /** + * Openings in the ice, cracks. + */ final String OCA_ISYS_OITI_CRK = "WO-DIOC----L---"; - /** Cracks at a specific location. */ + /** + * Cracks at a specific location. + */ final String OCA_ISYS_OITI_CRKASL = "WO-DIOCS---L---"; - /** Lead. */ + /** + * Lead. + */ final String OCA_ISYS_OITI_LED = "WO-DIOL----L---"; - /** Frozen lead. */ + /** + * Frozen lead. + */ final String OCA_ISYS_OITI_FZLED = "WO-DIOLF---L---"; - /** Snow cover. */ + /** + * Snow cover. + */ final String OCA_ISYS_SC = "WOS-ISC---P----"; - /** Sastrugi (with orientation). */ + /** + * Sastrugi (with orientation). + */ final String OCA_ISYS_SC_SWO = "WOS-ISS---P----"; - /** Ridges or hummocks. */ + /** + * Ridges or hummocks. + */ final String OCA_ISYS_TOPFTR_HUM = "WOS-ITRH--P----"; - /** Rafting. */ + /** + * Rafting. + */ final String OCA_ISYS_TOPFTR_RFTG = "WOS-ITR---P----"; - /** Jammed brash barrier. */ + /** + * Jammed brash barrier. + */ final String OCA_ISYS_TOPFTR_JBB = "WOS-ITBB--P----"; - /** Soundings. */ + /** + * Soundings. + */ final String OCA_HYDGRY_DPH_SNDG = "WOS-HDS---P----"; - /** Depth curve. */ + /** + * Depth curve. + */ final String OCA_HYDGRY_DPH_CRV = "WO-DHDDL---L---"; - /** Depth contour. */ + /** + * Depth contour. + */ final String OCA_HYDGRY_DPH_CTUR = "WO-DHDDC---L---"; - /** Depth area. */ + /** + * Depth area. + */ final String OCA_HYDGRY_DPH_ARA = "WO-DHDDA----A--"; - /** Coastline. */ + /** + * Coastline. + */ final String OCA_HYDGRY_CSTHYD_CSTLN = "WO-DHCC----L---"; - /** Island. */ + /** + * Island. + */ final String OCA_HYDGRY_CSTHYD_ISND = "WO-DHCI-----A--"; - /** Beach. */ + /** + * Beach. + */ final String OCA_HYDGRY_CSTHYD_BEH = "WO-DHCB-----A--"; - /** Water. */ + /** + * Water. + */ final String OCA_HYDGRY_CSTHYD_H2O = "WO-DHCW-----A--"; - /** Foreshore. */ + /** + * Foreshore. + */ final String OCA_HYDGRY_CSTHYD_FSH1_FSH2 = "WO-DHCF----L---"; - /** Foreshore. */ + /** + * Foreshore. + */ final String OCA_HYDGRY_CSTHYD_FSH1_FSH3 = "WO-DHCF-----A--"; - /** Berths (onshore). */ + /** + * Berths (onshore). + */ final String OCA_HYDGRY_PRTHBR_PRT_BRHSO = "WOS-HPB-O-P----"; - /** Berths (anchor). */ + /** + * Berths (anchor). + */ final String OCA_HYDGRY_PRTHBR_PRT_BRHSA = "WOS-HPB-A-P----"; - /** Anchorage. */ + /** + * Anchorage. + */ final String OCA_HYDGRY_PRTHBR_PRT_ANCRG1 = "WOS-HPBA--P----"; - /** Anchorage. */ + /** + * Anchorage. + */ final String OCA_HYDGRY_PRTHBR_PRT_ANCRG2 = "WO-DHPBA---L---"; - /** Anchorage. */ + /** + * Anchorage. + */ final String OCA_HYDGRY_PRTHBR_PRT_ANCRG3 = "WO-DHPBA----A--"; - /** Call in point. */ + /** + * Call in point. + */ final String OCA_HYDGRY_PRTHBR_PRT_CIP = "WOS-HPCP--P----"; - /** Pier/wharf/quay. */ + /** + * Pier/wharf/quay. + */ final String OCA_HYDGRY_PRTHBR_PRT_PWQ = "WO-DHPBP---L---"; - /** Fishing harbor. */ + /** + * Fishing harbor. + */ final String OCA_HYDGRY_PRTHBR_FSG_FSGHBR = "WOS-HPFH--P----"; - /** Fish stakes/traps/weirs. */ + /** + * Fish stakes/traps/weirs. + */ final String OCA_HYDGRY_PRTHBR_FSG_FSTK1 = "WOS-HPFS--P----"; - /** Fish stakes/traps/weirs. */ + /** + * Fish stakes/traps/weirs. + */ final String OCA_HYDGRY_PRTHBR_FSG_FSTK2 = "WOS-HPFS---L---"; - /** Fish stakes/traps/weirs. */ + /** + * Fish stakes/traps/weirs. + */ final String OCA_HYDGRY_PRTHBR_FSG_FSTK3 = "WOS-HPFF----A--"; - /** Drydock. */ + /** + * Drydock. + */ final String OCA_HYDGRY_PRTHBR_FAC_DDCK = "WO-DHPMD----A--"; - /** Landing place. */ + /** + * Landing place. + */ final String OCA_HYDGRY_PRTHBR_FAC_LNDPLC = "WOS-HPML--P----"; - /** Offshore loading facility. */ + /** + * Offshore loading facility. + */ final String OCA_HYDGRY_PRTHBR_FAC_OSLF1 = "WO-DHPMO--P----"; - /** Offshore loading facility. */ + /** + * Offshore loading facility. + */ final String OCA_HYDGRY_PRTHBR_FAC_OSLF2 = "WO-DHPMO---L---"; - /** Offshore loading facility. */ + /** + * Offshore loading facility. + */ final String OCA_HYDGRY_PRTHBR_FAC_OSLF3 = "WO-DHPMO----A--"; - /** Ramp (above water). */ + /** + * Ramp (above water). + */ final String OCA_HYDGRY_PRTHBR_FAC_RAMPAW = "WO-DHPMRA--L---"; - /** Ramp (below water). */ + /** + * Ramp (below water). + */ final String OCA_HYDGRY_PRTHBR_FAC_RAMPBW = "WO-DHPMRB--L---"; - /** Landing ring. */ + /** + * Landing ring. + */ final String OCA_HYDGRY_PRTHBR_FAC_LNDRNG = "WOS-HPM-R-P----"; - /** Ferry crossing. */ + /** + * Ferry crossing. + */ final String OCA_HYDGRY_PRTHBR_FAC_FRYCSG = "WOS-HPM-FC-L---"; - /** Cable ferry crossing. */ + /** + * Cable ferry crossing. + */ final String OCA_HYDGRY_PRTHBR_FAC_CFCSG = "WOS-HPM-CC-L---"; - /** Dolphin. */ + /** + * Dolphin. + */ final String OCA_HYDGRY_PRTHBR_FAC_DOPN = "WOS-HPD---P----"; - /** Breakwater/groin/jetty (above water). */ + /** + * Breakwater/groin/jetty (above water). + */ final String OCA_HYDGRY_PRTHBR_SHRLNE_BWGJAW = "WO-DHPSPA--L---"; - /** Breakwater/groin/jetty (below water). */ + /** + * Breakwater/groin/jetty (below water). + */ final String OCA_HYDGRY_PRTHBR_SHRLNE_BWGJBW = "WO-DHPSPB--L---"; - /** Seawall. */ + /** + * Seawall. + */ final String OCA_HYDGRY_PRTHBR_SHRLNE_SW = "WO-DHPSPS--L---"; - /** Beacon. */ + /** + * Beacon. + */ final String OCA_HYDGRY_ATN_BCN = "WOS-HABA--P----"; - /** Buoy default. */ + /** + * Buoy default. + */ final String OCA_HYDGRY_ATN_BUOY = "WOS-HABB--P----"; - /** Marker. */ + /** + * Marker. + */ final String OCA_HYDGRY_ATN_MRK = "WOS-HABM--P----"; - /** Perches/stakes. */ + /** + * Perches/stakes. + */ final String OCA_HYDGRY_ATN_PRH1_PRH2 = "WOS-HABP--P----"; - /** Perches/stakes. */ + /** + * Perches/stakes. + */ final String OCA_HYDGRY_ATN_PRH1_PRH3 = "WO-DHABP----A--"; - /** Light. */ + /** + * Light. + */ final String OCA_HYDGRY_ATN_LIT = "WOS-HAL---P----"; - /** Leading line. */ + /** + * Leading line. + */ final String OCA_HYDGRY_ATN_LDGLNE = "WO-DHALLA--L---"; - /** Light vessel/lightship. */ + /** + * Light vessel/lightship. + */ final String OCA_HYDGRY_ATN_LITVES = "WOS-HALV--P----"; - /** Lighthouse. */ + /** + * Lighthouse. + */ final String OCA_HYDGRY_ATN_LITHSE = "WOS-HALH--P----"; - /** Rock submergered. */ + /** + * Rock submergered. + */ final String OCA_HYDGRY_DANHAZ_RCKSBM = "WOS-HHRS--P----"; - /** Rock awashed. */ + /** + * Rock awashed. + */ final String OCA_HYDGRY_DANHAZ_RCKAWD = "WOS-HHRA--P----"; - /** Underwater danger/hazard. */ + /** + * Underwater danger/hazard. + */ final String OCA_HYDGRY_DANHAZ_UH2DAN = "WO-DHHD-----A--"; - /** Foul ground. */ + /** + * Foul ground. + */ final String OCA_HYDGRY_DANHAZ_FLGRD1_FLGRD2 = "WOS-HHDF--P----"; - /** Foul ground. */ + /** + * Foul ground. + */ final String OCA_HYDGRY_DANHAZ_FLGRD1_FLGRD3 = "WO-DHHDF----A--"; - /** Kelp/seaweed. */ + /** + * Kelp/seaweed. + */ final String OCA_HYDGRY_DANHAZ_KLP1_KLP2 = "WO-DHHDK--P----"; - /** Kelp/seaweed. */ + /** + * Kelp/seaweed. + */ final String OCA_HYDGRY_DANHAZ_KLP1_KLP3 = "WO-DHHDK----A--"; - /** Mine - naval (doubtful). */ + /** + * Mine - naval (doubtful). + */ final String OCA_HYDGRY_DANHAZ_MNENAV_DBT = "WOS-HHDMDBP----"; - /** Mine - naval (definite). */ + /** + * Mine - naval (definite). + */ final String OCA_HYDGRY_DANHAZ_MNENAV_DEFN = "WOS-HHDMDFP----"; - /** Snags/stumps. */ + /** + * Snags/stumps. + */ final String OCA_HYDGRY_DANHAZ_SNAG = "WOS-HHDS--P----"; - /** Wreck (uncovers). */ + /** + * Wreck (uncovers). + */ final String OCA_HYDGRY_DANHAZ_WRK_UCOV = "WOS-HHDWA-P----"; - /** Wreck (submerged). */ + /** + * Wreck (submerged). + */ final String OCA_HYDGRY_DANHAZ_WRK_SBM = "WOS-HHDWB-P----"; - /** Breakers. */ + /** + * Breakers. + */ final String OCA_HYDGRY_DANHAZ_BRKS = "WO-DHHDB---L---"; - /** Reef. */ + /** + * Reef. + */ final String OCA_HYDGRY_DANHAZ_REEF = "WOS-HHDR---L---"; - /** Eddies/overfalls/tide rips. */ + /** + * Eddies/overfalls/tide rips. + */ final String OCA_HYDGRY_DANHAZ_EOTR = "WOS-HHDE--P----"; - /** Discolored water. */ + /** + * Discolored water. + */ final String OCA_HYDGRY_DANHAZ_DCDH2O = "WO-DHHDD----A--"; - /** Sand. */ + /** + * Sand. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_SD = "WOS-BFC-S-P----"; - /** Mud. */ + /** + * Mud. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_MUD = "WOS-BFC-M-P----"; - /** Clay. */ + /** + * Clay. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_CLAY = "WOS-BFC-CLP----"; - /** Silt. */ + /** + * Silt. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_SLT = "WOS-BFC-SIP----"; - /** Stones. */ + /** + * Stones. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_STNE = "WOS-BFC-STP----"; - /** Gravel. */ + /** + * Gravel. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_GVL = "WOS-BFC-G-P----"; - /** Pebbles. */ + /** + * Pebbles. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_PBL = "WOS-BFC-P-P----"; - /** Cobbles. */ + /** + * Cobbles. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_COBL = "WOS-BFC-CBP----"; - /** Rock. */ + /** + * Rock. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_RCK = "WOS-BFC-R-P----"; - /** Coral. */ + /** + * Coral. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_CRL = "WOS-BFC-COP----"; - /** Shell. */ + /** + * Shell. + */ final String OCA_HYDGRY_BTMFAT_BTMCHR_SHE = "WOS-BFC-SHP----"; - /** Qualifying terms, fine. */ + /** + * Qualifying terms, fine. + */ final String OCA_HYDGRY_BTMFAT_QLFYTM_FNE = "WOS-BFQ-F-P----"; - /** Qualifying terms, medum. */ + /** + * Qualifying terms, medum. + */ final String OCA_HYDGRY_BTMFAT_QLFYTM_MDM = "WOS-BFQ-M-P----"; - /** Qualifying terms, coarse. */ + /** + * Qualifying terms, coarse. + */ final String OCA_HYDGRY_BTMFAT_QLFYTM_CSE = "WOS-BFQ-C-P----"; - /** Water turbulence. */ + /** + * Water turbulence. + */ final String OCA_HYDGRY_TDECUR_H2OTRB = "WOS-TCCW--P----"; - /** Current flow - ebb. */ + /** + * Current flow - ebb. + */ final String OCA_HYDGRY_TDECUR_EBB = "WO-DTCCCFE-L---"; - /** Current flow - flood. */ + /** + * Current flow - flood. + */ final String OCA_HYDGRY_TDECUR_FLOOD = "WO-DTCCCFF-L---"; - /** Tide data point. */ + /** + * Tide data point. + */ final String OCA_HYDGRY_TDECUR_TDEDP = "WOS-TCCTD-P----"; - /** Tide gauge. */ + /** + * Tide gauge. + */ final String OCA_HYDGRY_TDECUR_TDEG = "WOS-TCCTG-P----"; - /** Bioluminescence, vdr level 1-2. */ + /** + * Bioluminescence, vdr level 1-2. + */ final String OCA_OCNGRY_BIOLUM_VDR1_2 = "WO-DOBVA----A--"; - /** Bioluminescence, vdr level 2-3. */ + /** + * Bioluminescence, vdr level 2-3. + */ final String OCA_OCNGRY_BIOLUM_VDR2_3 = "WO-DOBVB----A--"; - /** Bioluminescence, vdr level 3-4. */ + /** + * Bioluminescence, vdr level 3-4. + */ final String OCA_OCNGRY_BIOLUM_VDR3_4 = "WO-DOBVC----A--"; - /** Bioluminescence, vdr level 4-5. */ + /** + * Bioluminescence, vdr level 4-5. + */ final String OCA_OCNGRY_BIOLUM_VDR4_5 = "WO-DOBVD----A--"; - /** Bioluminescence, vdr level 5-6. */ + /** + * Bioluminescence, vdr level 5-6. + */ final String OCA_OCNGRY_BIOLUM_VDR5_6 = "WO-DOBVE----A--"; - /** Bioluminescence, vdr level 6-7. */ + /** + * Bioluminescence, vdr level 6-7. + */ final String OCA_OCNGRY_BIOLUM_VDR6_7 = "WO-DOBVF----A--"; - /** Bioluminescence, vdr level 7-8. */ + /** + * Bioluminescence, vdr level 7-8. + */ final String OCA_OCNGRY_BIOLUM_VDR7_8 = "WO-DOBVG----A--"; - /** Bioluminescence, vdr level 8-9. */ + /** + * Bioluminescence, vdr level 8-9. + */ final String OCA_OCNGRY_BIOLUM_VDR8_9 = "WO-DOBVH----A--"; - /** Bioluminescence, vdr level 9-10. */ + /** + * Bioluminescence, vdr level 9-10. + */ final String OCA_OCNGRY_BIOLUM_VDR9_0 = "WO-DOBVI----A--"; - /** Flat. */ + /** + * Flat. + */ final String OCA_OCNGRY_BEHSPE_FLT = "WO-DBSF-----A--"; - /** Gentle. */ + /** + * Gentle. + */ final String OCA_OCNGRY_BEHSPE_GTL = "WO-DBSG-----A--"; - /** Moderate. */ + /** + * Moderate. + */ final String OCA_OCNGRY_BEHSPE_MOD = "WO-DBSM-----A--"; - /** Steep. */ + /** + * Steep. + */ final String OCA_OCNGRY_BEHSPE_STP = "WO-DBST-----A--"; - /** Miw-bottom sediments, solid rock. */ + /** + * Miw-bottom sediments, solid rock. + */ final String OCA_GPHY_MNEWBD_MIWBS_SLDRCK = "WO-DGMSR----A--"; - /** Miw-bottom sediments, clay. */ + /** + * Miw-bottom sediments, clay. + */ final String OCA_GPHY_MNEWBD_MIWBS_CLAY = "WO-DGMSC----A--"; - /** Very coarse sand. */ + /** + * Very coarse sand. + */ final String OCA_GPHY_MNEWBD_MIWBS_VCSESD = "WO-DGMSSVS--A--"; - /** Miw-bottom sediments, coarse sand. */ + /** + * Miw-bottom sediments, coarse sand. + */ final String OCA_GPHY_MNEWBD_MIWBS_CSESD = "WO-DGMSSC---A--"; - /** Miw-bottom sediments, medium sand. */ + /** + * Miw-bottom sediments, medium sand. + */ final String OCA_GPHY_MNEWBD_MIWBS_MDMSD = "WO-DGMSSM---A--"; - /** Miw-bottom sediments, fine sand. */ + /** + * Miw-bottom sediments, fine sand. + */ final String OCA_GPHY_MNEWBD_MIWBS_FNESD = "WO-DGMSSF---A--"; - /** Miw-bottom sediments, very fine sand. */ + /** + * Miw-bottom sediments, very fine sand. + */ final String OCA_GPHY_MNEWBD_MIWBS_VFNESD = "WO-DGMSSVF--A--"; - /** Miw-bottom sediments, very fine silt. */ + /** + * Miw-bottom sediments, very fine silt. + */ final String OCA_GPHY_MNEWBD_MIWBS_VFNSLT = "WO-DGMSIVF--A--"; - /** Miw-bottom sediments, file silt. */ + /** + * Miw-bottom sediments, file silt. + */ final String OCA_GPHY_MNEWBD_MIWBS_FNESLT = "WO-DGMSIF---A--"; - /** Miw-bottom sediments, medium silt. */ + /** + * Miw-bottom sediments, medium silt. + */ final String OCA_GPHY_MNEWBD_MIWBS_MDMSLT = "WO-DGMSIM---A--"; - /** Miw-bottom sediments, coarse silt. */ + /** + * Miw-bottom sediments, coarse silt. + */ final String OCA_GPHY_MNEWBD_MIWBS_CSESLT = "WO-DGMSIC---A--"; - /** Boulders. */ + /** + * Boulders. + */ final String OCA_GPHY_MNEWBD_MIWBS_BLDS = "WO-DGMSB----A--"; - /** Cobbles, oyster shells. */ + /** + * Cobbles, oyster shells. + */ final String OCA_GPHY_MNEWBD_MIWBS_COBLOS = "WO-DGMS-CO--A--"; - /** Pebbles, shells. */ + /** + * Pebbles, shells. + */ final String OCA_GPHY_MNEWBD_MIWBS_PBLSHE = "WO-DGMS-PH--A--"; - /** Sand and shells. */ + /** + * Sand and shells. + */ final String OCA_GPHY_MNEWBD_MIWBS_SD_SHE = "WO-DGMS-SH--A--"; - /** Miw-bottom sediments, land. */ + /** + * Miw-bottom sediments, land. + */ final String OCA_GPHY_MNEWBD_MIWBS_LND = "WO-DGML-----A--"; - /** No data. */ + /** + * No data. + */ final String OCA_GPHY_MNEWBD_MIWBS_NODAT = "WO-DGMN-----A--"; - /** Bottom roughness, smooth. */ + /** + * Bottom roughness, smooth. + */ final String OCA_GPHY_MNEWBD_BTMRGN_SMH = "WO-DGMRS----A--"; - /** Bottom roughness, moderate. */ + /** + * Bottom roughness, moderate. + */ final String OCA_GPHY_MNEWBD_BTMRGN_MOD = "WO-DGMRM----A--"; - /** Bottom roughness, rough. */ + /** + * Bottom roughness, rough. + */ final String OCA_GPHY_MNEWBD_BTMRGN_RGH = "WO-DGMRR----A--"; - /** Low. */ + /** + * Low. + */ final String OCA_GPHY_MNEWBD_CTRB_LW = "WO-DGMCL----A--"; - /** Medium. */ + /** + * Medium. + */ final String OCA_GPHY_MNEWBD_CTRB_MDM = "WO-DGMCM----A--"; - /** High. */ + /** + * High. + */ final String OCA_GPHY_MNEWBD_CTRB_HGH = "WO-DGMCH----A--"; - /** Impact burial, 0%. */ + /** + * Impact burial, 0%. + */ final String OCA_GPHY_MNEWBD_IMTBUR_0 = "WO-DGMIBA---A--"; - /** Impact burial, 0-10%. */ + /** + * Impact burial, 0-10%. + */ final String OCA_GPHY_MNEWBD_IMTBUR_0_10 = "WO-DGMIBB---A--"; - /** Impact burial, 10-20%. */ + /** + * Impact burial, 10-20%. + */ final String OCA_GPHY_MNEWBD_IMTBUR_10_20 = "WO-DGMIBC---A--"; - /** Impact burial, 20-75%. */ + /** + * Impact burial, 20-75%. + */ final String OCA_GPHY_MNEWBD_IMTBUR_20_75 = "WO-DGMIBD---A--"; - /** Impact burial, >75%. */ + /** + * Impact burial, >75%. + */ final String OCA_GPHY_MNEWBD_IMTBUR_75 = "WO-DGMIBE---A--"; - /** Miw bottom category, a. */ + /** + * Miw bottom category, a. + */ final String OCA_GPHY_MNEWBD_MIWBC_A = "WO-DGMBCA---A--"; - /** Miw bottom category, b. */ + /** + * Miw bottom category, b. + */ final String OCA_GPHY_MNEWBD_MIWBC_B = "WO-DGMBCB---A--"; - /** Miw bottom category, c. */ + /** + * Miw bottom category, c. + */ final String OCA_GPHY_MNEWBD_MIWBC_C = "WO-DGMBCC---A--"; - /** Miw bottom type, a1. */ + /** + * Miw bottom type, a1. + */ final String OCA_GPHY_MNEWBD_MIWBT_A1 = "WO-DGMBTA---A--"; - /** Miw bottom type, a2. */ + /** + * Miw bottom type, a2. + */ final String OCA_GPHY_MNEWBD_MIWBT_A2 = "WO-DGMBTB---A--"; - /** Miw bottom type, a3. */ + /** + * Miw bottom type, a3. + */ final String OCA_GPHY_MNEWBD_MIWBT_A3 = "WO-DGMBTC---A--"; - /** Miw bottom type, b1. */ + /** + * Miw bottom type, b1. + */ final String OCA_GPHY_MNEWBD_MIWBT_B1 = "WO-DGMBTD---A--"; - /** Miw bottom type, b2. */ + /** + * Miw bottom type, b2. + */ final String OCA_GPHY_MNEWBD_MIWBT_B2 = "WO-DGMBTE---A--"; - /** Miw bottom type, b3. */ + /** + * Miw bottom type, b3. + */ final String OCA_GPHY_MNEWBD_MIWBT_B3 = "WO-DGMBTF---A--"; - /** Miw bottom type, c1. */ + /** + * Miw bottom type, c1. + */ final String OCA_GPHY_MNEWBD_MIWBT_C1 = "WO-DGMBTG---A--"; - /** Miw bottom type, c2. */ + /** + * Miw bottom type, c2. + */ final String OCA_GPHY_MNEWBD_MIWBT_C2 = "WO-DGMBTH---A--"; - /** Miw bottom type, c3. */ + /** + * Miw bottom type, c3. + */ final String OCA_GPHY_MNEWBD_MIWBT_C3 = "WO-DGMBTI---A--"; - /** Maritime limit boundary. */ + /** + * Maritime limit boundary. + */ final String OCA_LMT_MARTLB = "WO-DL-ML---L---"; - /** Maritime area. */ + /** + * Maritime area. + */ final String OCA_LMT_MARTAR = "WO-DL-MA----A--"; - /** Restricted area. */ + /** + * Restricted area. + */ final String OCA_LMT_RSDARA = "WO-DL-RA---L---"; - /** Swept area. */ + /** + * Swept area. + */ final String OCA_LMT_SWPARA = "WO-DL-SA----A--"; - /** Training area. */ + /** + * Training area. + */ final String OCA_LMT_TRGARA = "WO-DL-TA----A--"; - /** Operator-defined. */ + /** + * Operator-defined. + */ final String OCA_LMT_OD = "WO-DL-O-----A--"; - /** Submarine cable. */ + /** + * Submarine cable. + */ final String OCA_MMD_SUBCBL = "WO-DMCA----L---"; - /** Submerged crib. */ + /** + * Submerged crib. + */ final String OCA_MMD_SBMCRB = "WO-DMCC-----A--"; - /** Canal. */ + /** + * Canal. + */ final String OCA_MMD_CNL = "WO-DMCD----L---"; - /** Ford. */ + /** + * Ford. + */ final String OCA_MMD_FRD = "WOS-MF----P----"; - /** Lock. */ + /** + * Lock. + */ final String OCA_MMD_LCK = "WOS-ML----P----"; - /** Oil/gas rig. */ + /** + * Oil/gas rig. + */ final String OCA_MMD_OLRG = "WOS-MOA---P----"; - /** Oil/gas rig field. */ + /** + * Oil/gas rig field. + */ final String OCA_MMD_OLRGFD = "WO-DMOA-----A--"; - /** Pipelines/pipe. */ + /** + * Pipelines/pipe. + */ final String OCA_MMD_PPELNE = "WO-DMPA----L---"; - /** Pile/piling/post. */ + /** + * Pile/piling/post. + */ final String OCA_MMD_PLE = "WOS-MPA---P----"; } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/TacGrpSidc.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/TacGrpSidc.java index 5edf5faff1..12a9216652 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/TacGrpSidc.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/TacGrpSidc.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics; /** @@ -14,901 +13,1761 @@ * @author pabercrombie * @version $Id: TacGrpSidc.java 429 2012-03-04 23:35:53Z pabercrombie $ */ -public interface TacGrpSidc -{ +public interface TacGrpSidc { /////////////////////////////// // Tasks /////////////////////////////// - /** Block */ + /** + * Block + */ final String TSK_BLK = "G-T-B----------"; - /** Breach */ + /** + * Breach + */ final String TSK_BRH = "G-T-H----------"; - /** Bypass */ + /** + * Bypass + */ final String TSK_BYS = "G-T-Y----------"; - /** Canalize */ + /** + * Canalize + */ final String TSK_CNZ = "G-T-C----------"; - /** Clear */ + /** + * Clear + */ final String TSK_CLR = "G-T-X----------"; - /** Contain */ + /** + * Contain + */ final String TSK_CNT = "G-T-J----------"; - /** Counterattack (CATK) */ + /** + * Counterattack (CATK) + */ final String TSK_CATK = "G-T-K----------"; - /** Counterattack By Fire */ + /** + * Counterattack By Fire + */ final String TSK_CATK_CATKF = "G-T-KF---------"; - /** Delay */ + /** + * Delay + */ final String TSK_DLY = "G-T-L----------"; - /** Destroy */ + /** + * Destroy + */ final String TSK_DSTY = "G-T-D----------"; - /** Disrupt */ + /** + * Disrupt + */ final String TSK_DRT = "G-T-T----------"; - /** Fix */ + /** + * Fix + */ final String TSK_FIX = "G-T-F----------"; - /** Follow And Assume */ + /** + * Follow And Assume + */ final String TSK_FLWASS = "G-T-A----------"; - /** Follow And Support */ + /** + * Follow And Support + */ final String TSK_FLWASS_FLWSUP = "G-T-AS---------"; - /** Interdict */ + /** + * Interdict + */ final String TSK_ITDT = "G-T-I----------"; - /** Isolate */ + /** + * Isolate + */ final String TSK_ISL = "G-T-E----------"; - /** Neutralize */ + /** + * Neutralize + */ final String TSK_NEUT = "G-T-N----------"; - /** Occupy */ + /** + * Occupy + */ final String TSK_OCC = "G-T-O----------"; - /** Penetrate */ + /** + * Penetrate + */ final String TSK_PNE = "G-T-P----------"; - /** Relief In Place (RIP) */ + /** + * Relief In Place (RIP) + */ final String TSK_RIP = "G-T-R----------"; - /** Retain */ + /** + * Retain + */ final String TSK_RTN = "G-T-Q----------"; - /** Retirement */ + /** + * Retirement + */ final String TSK_RTM = "G-T-M----------"; - /** Secure */ + /** + * Secure + */ final String TSK_SCE = "G-T-S----------"; - /** Screen */ + /** + * Screen + */ final String TSK_SEC_SCN = "G-T-US---------"; - /** Guard */ + /** + * Guard + */ final String TSK_SEC_GUD = "G-T-UG---------"; - /** Cover */ + /** + * Cover + */ final String TSK_SEC_COV = "G-T-UC---------"; - /** Seize */ + /** + * Seize + */ final String TSK_SZE = "G-T-Z----------"; - /** Withdraw */ + /** + * Withdraw + */ final String TSK_WDR = "G-T-W----------"; - /** Withdraw Under Pressure */ + /** + * Withdraw Under Pressure + */ final String TSK_WDR_WDRUP = "G-T-WP---------"; /////////////////////////////////////////// // Command, Control, and General Manuever /////////////////////////////////////////// - - /** Datum */ + /** + * Datum + */ final String C2GM_GNL_PNT_USW_UH2_DTM = "G-G-GPUUD------"; - /** Brief Contact */ + /** + * Brief Contact + */ final String C2GM_GNL_PNT_USW_UH2_BCON = "G-G-GPUUB------"; - /** Lost Contact */ + /** + * Lost Contact + */ final String C2GM_GNL_PNT_USW_UH2_LCON = "G-G-GPUUL------"; - /** Sinker */ + /** + * Sinker + */ final String C2GM_GNL_PNT_USW_UH2_SNK = "G-G-GPUUS------"; - /** Sonobuoy */ + /** + * Sonobuoy + */ final String C2GM_GNL_PNT_USW_SNBY = "G-G-GPUY-------"; - /** Pattern Center */ + /** + * Pattern Center + */ final String C2GM_GNL_PNT_USW_SNBY_PTNCTR = "G-G-GPUYP------"; - /** Directional Frequency Analyzing And Recording (DIFAR) */ + /** + * Directional Frequency Analyzing And Recording (DIFAR) + */ final String C2GM_GNL_PNT_USW_SNBY_DIFAR = "G-G-GPUYD------"; - /** Low Frequency Analyzing And Recording (LOFAR) */ + /** + * Low Frequency Analyzing And Recording (LOFAR) + */ final String C2GM_GNL_PNT_USW_SNBY_LOFAR = "G-G-GPUYL------"; - /** Command Active Sonobuoy System (CASS) */ + /** + * Command Active Sonobuoy System (CASS) + */ final String C2GM_GNL_PNT_USW_SNBY_CASS = "G-G-GPUYC------"; - /** Directional Command Active Sonobuoy System (DICASS) */ + /** + * Directional Command Active Sonobuoy System (DICASS) + */ final String C2GM_GNL_PNT_USW_SNBY_DICASS = "G-G-GPUYS------"; - /** Bathythermograph Transmitting (BT) */ + /** + * Bathythermograph Transmitting (BT) + */ final String C2GM_GNL_PNT_USW_SNBY_BT = "G-G-GPUYB------"; - /** ANM */ + /** + * ANM + */ final String C2GM_GNL_PNT_USW_SNBY_ANM = "G-G-GPUYA------"; - /** Vertical Line Array Difar (VLAD) */ + /** + * Vertical Line Array Difar (VLAD) + */ final String C2GM_GNL_PNT_USW_SNBY_VLAD = "G-G-GPUYV------"; - /** ATAC */ + /** + * ATAC + */ final String C2GM_GNL_PNT_USW_SNBY_ATAC = "G-G-GPUYT------"; - /** Range Only (RO) */ + /** + * Range Only (RO) + */ final String C2GM_GNL_PNT_USW_SNBY_RO = "G-G-GPUYR------"; - /** Kingpin */ + /** + * Kingpin + */ final String C2GM_GNL_PNT_USW_SNBY_KGP = "G-G-GPUYK------"; - /** Sonobuoy-Expired */ + /** + * Sonobuoy-Expired + */ final String C2GM_GNL_PNT_USW_SNBY_EXP = "G-G-GPUYX------"; - /** Search */ + /** + * Search + */ final String C2GM_GNL_PNT_USW_SRH = "G-G-GPUS-------"; - /** Search Area */ + /** + * Search Area + */ final String C2GM_GNL_PNT_USW_SRH_ARA = "G-G-GPUSA------"; - /** DIP Position */ + /** + * DIP Position + */ final String C2GM_GNL_PNT_USW_SRH_DIPPSN = "G-G-GPUSD------"; - /** Search Center */ + /** + * Search Center + */ final String C2GM_GNL_PNT_USW_SRH_CTR = "G-G-GPUSC------"; - /** Reference Point */ + /** + * Reference Point + */ final String C2GM_GNL_PNT_REFPNT = "G-G-GPR--------"; - /** Navigational Reference Point */ + /** + * Navigational Reference Point + */ final String C2GM_GNL_PNT_REFPNT_NAVREF = "G-G-GPRN-------"; - /** Special Point */ + /** + * Special Point + */ final String C2GM_GNL_PNT_REFPNT_SPLPNT = "G-G-GPRS-------"; - /** DLRP */ + /** + * DLRP + */ final String C2GM_GNL_PNT_REFPNT_DLRP = "G-G-GPRD-------"; - /** Point Of Intended Movement (PIM) */ + /** + * Point Of Intended Movement (PIM) + */ final String C2GM_GNL_PNT_REFPNT_PIM = "G-G-GPRP-------"; - /** Marshall Point */ + /** + * Marshall Point + */ final String C2GM_GNL_PNT_REFPNT_MRSH = "G-G-GPRM-------"; - /** Waypoint */ + /** + * Waypoint + */ final String C2GM_GNL_PNT_REFPNT_WAP = "G-G-GPRW-------"; - /** Corridor Tab */ + /** + * Corridor Tab + */ final String C2GM_GNL_PNT_REFPNT_CRDRTB = "G-G-GPRC-------"; - /** Point Of Interest */ + /** + * Point Of Interest + */ final String C2GM_GNL_PNT_REFPNT_PNTINR = "G-G-GPRI-------"; - /** Aim Point */ + /** + * Aim Point + */ final String C2GM_GNL_PNT_WPN_AIMPNT = "G-G-GPWA-------"; - /** Drop Point */ + /** + * Drop Point + */ final String C2GM_GNL_PNT_WPN_DRPPNT = "G-G-GPWD-------"; - /** Entry Point */ + /** + * Entry Point + */ final String C2GM_GNL_PNT_WPN_ENTPNT = "G-G-GPWE-------"; - /** Ground Zero */ + /** + * Ground Zero + */ final String C2GM_GNL_PNT_WPN_GRDZRO = "G-G-GPWG-------"; - /** MSL Detect Point */ + /** + * MSL Detect Point + */ final String C2GM_GNL_PNT_WPN_MSLPNT = "G-G-GPWM-------"; - /** Impact Point */ + /** + * Impact Point + */ final String C2GM_GNL_PNT_WPN_IMTPNT = "G-G-GPWI-------"; - /** Predicted Impact Point */ + /** + * Predicted Impact Point + */ final String C2GM_GNL_PNT_WPN_PIPNT = "G-G-GPWP-------"; - /** Formation */ + /** + * Formation + */ final String C2GM_GNL_PNT_FRMN = "G-G-GPF--------"; - /** Harbor (General) */ + /** + * Harbor (General) + */ final String C2GM_GNL_PNT_HBR = "G-G-GPH--------"; - /** Point Q */ + /** + * Point Q + */ final String C2GM_GNL_PNT_HBR_PNTQ = "G-G-GPHQ-------"; - /** Point A */ + /** + * Point A + */ final String C2GM_GNL_PNT_HBR_PNTA = "G-G-GPHA-------"; - /** Point Y */ + /** + * Point Y + */ final String C2GM_GNL_PNT_HBR_PNTY = "G-G-GPHY-------"; - /** Point X */ + /** + * Point X + */ final String C2GM_GNL_PNT_HBR_PNTX = "G-G-GPHX-------"; - /** Route */ + /** + * Route + */ final String C2GM_GNL_PNT_RTE = "G-G-GPO--------"; - /** Rendezvous */ + /** + * Rendezvous + */ final String C2GM_GNL_PNT_RTE_RDV = "G-G-GPOZ-------"; - /** Diversions */ + /** + * Diversions + */ final String C2GM_GNL_PNT_RTE_DVSN = "G-G-GPOD-------"; - /** Waypoint */ + /** + * Waypoint + */ final String C2GM_GNL_PNT_RTE_WAP = "G-G-GPOW-------"; - /** PIM */ + /** + * PIM + */ final String C2GM_GNL_PNT_RTE_PIM = "G-G-GPOP-------"; - /** Point R */ + /** + * Point R + */ final String C2GM_GNL_PNT_RTE_PNTR = "G-G-GPOR-------"; - /** Air Control */ + /** + * Air Control + */ final String C2GM_GNL_PNT_ACTL = "G-G-GPA--------"; - /** Combat Air Patrol (CAP) */ + /** + * Combat Air Patrol (CAP) + */ final String C2GM_GNL_PNT_ACTL_CAP = "G-G-GPAP-------"; - /** Airborne Early Warning (AEW) */ + /** + * Airborne Early Warning (AEW) + */ final String C2GM_GNL_PNT_ACTL_ABNEW = "G-G-GPAW-------"; - /** Tanking */ + /** + * Tanking + */ final String C2GM_GNL_PNT_ACTL_TAK = "G-G-GPAK-------"; - /** Antisubmarine Warfare, Fixed Wing */ + /** + * Antisubmarine Warfare, Fixed Wing + */ final String C2GM_GNL_PNT_ACTL_ASBWF = "G-G-GPAA-------"; - /** Antisubmarine Warfare, Rotary Wing */ + /** + * Antisubmarine Warfare, Rotary Wing + */ final String C2GM_GNL_PNT_ACTL_ASBWR = "G-G-GPAH-------"; - /** Sucap - Fixed Wing */ + /** + * Sucap - Fixed Wing + */ final String C2GM_GNL_PNT_ACTL_SUWF = "G-G-GPAB-------"; - /** Sucap - Rotary Wing */ + /** + * Sucap - Rotary Wing + */ final String C2GM_GNL_PNT_ACTL_SUWR = "G-G-GPAC-------"; - /** IW - Fixed Wing */ + /** + * IW - Fixed Wing + */ final String C2GM_GNL_PNT_ACTL_MIWF = "G-G-GPAD-------"; - /** MIW - Rotary Wing */ + /** + * MIW - Rotary Wing + */ final String C2GM_GNL_PNT_ACTL_MIWR = "G-G-GPAE-------"; - /** Strike Ip */ + /** + * Strike Ip + */ final String C2GM_GNL_PNT_ACTL_SKEIP = "G-G-GPAS-------"; - /** Tacan */ + /** + * Tacan + */ final String C2GM_GNL_PNT_ACTL_TCN = "G-G-GPAT-------"; - /** Tomcat */ + /** + * Tomcat + */ final String C2GM_GNL_PNT_ACTL_TMC = "G-G-GPAO-------"; - /** Rescue */ + /** + * Rescue + */ final String C2GM_GNL_PNT_ACTL_RSC = "G-G-GPAR-------"; - /** Replenish */ + /** + * Replenish + */ final String C2GM_GNL_PNT_ACTL_RPH = "G-G-GPAL-------"; - /** Unmanned Aerial System (UAS/UA) */ + /** + * Unmanned Aerial System (UAS/UA) + */ final String C2GM_GNL_PNT_ACTL_UA = "G-G-GPAF-------"; - /** VTUA */ + /** + * VTUA + */ final String C2GM_GNL_PNT_ACTL_VTUA = "G-G-GPAG-------"; - /** Orbit */ + /** + * Orbit + */ final String C2GM_GNL_PNT_ACTL_ORB = "G-G-GPAI-------"; - /** Orbit - Figure Eight */ + /** + * Orbit - Figure Eight + */ final String C2GM_GNL_PNT_ACTL_ORBF8 = "G-G-GPAJ-------"; - /** Orbit - Race Track */ + /** + * Orbit - Race Track + */ final String C2GM_GNL_PNT_ACTL_ORBRT = "G-G-GPAM-------"; - /** Orbit - Random, Closed */ + /** + * Orbit - Random, Closed + */ final String C2GM_GNL_PNT_ACTL_ORBRD = "G-G-GPAN-------"; - /** Action Points (General) */ + /** + * Action Points (General) + */ final String C2GM_GNL_PNT_ACTPNT = "G-G-GPP--------"; - /** Check Point */ + /** + * Check Point + */ final String C2GM_GNL_PNT_ACTPNT_CHKPNT = "G-G-GPPK-------"; - /** Contact Point */ + /** + * Contact Point + */ final String C2GM_GNL_PNT_ACTPNT_CONPNT = "G-G-GPPC-------"; - /** Coordination Point */ + /** + * Coordination Point + */ final String C2GM_GNL_PNT_ACTPNT_CRDPNT = "G-G-GPPO-------"; - /** Decision Point */ + /** + * Decision Point + */ final String C2GM_GNL_PNT_ACTPNT_DCNPNT = "G-G-GPPD-------"; - /** Linkup Point */ + /** + * Linkup Point + */ final String C2GM_GNL_PNT_ACTPNT_LNKUPT = "G-G-GPPL-------"; - /** Passage Point */ + /** + * Passage Point + */ final String C2GM_GNL_PNT_ACTPNT_PSSPNT = "G-G-GPPP-------"; - /** Rally Point */ + /** + * Rally Point + */ final String C2GM_GNL_PNT_ACTPNT_RAYPNT = "G-G-GPPR-------"; - /** Release Point */ + /** + * Release Point + */ final String C2GM_GNL_PNT_ACTPNT_RELPNT = "G-G-GPPE-------"; - /** Start Point */ + /** + * Start Point + */ final String C2GM_GNL_PNT_ACTPNT_STRPNT = "G-G-GPPS-------"; - /** Amnesty Point */ + /** + * Amnesty Point + */ final String C2GM_GNL_PNT_ACTPNT_AMNPNT = "G-G-GPPA-------"; - /** Waypoint */ + /** + * Waypoint + */ final String C2GM_GNL_PNT_ACTPNT_WAP = "G-G-GPPW-------"; - /** EA Surface Control Station */ + /** + * EA Surface Control Station + */ final String C2GM_GNL_PNT_SCTL = "G-G-GPC--------"; - /** Unmanned Surface Vehicle (USV) Control Station */ + /** + * Unmanned Surface Vehicle (USV) Control Station + */ final String C2GM_GNL_PNT_SCTL_USV = "G-G-GPCU-------"; - /** Remote Multimission Vehicle (RMV) Usv Control Station */ + /** + * Remote Multimission Vehicle (RMV) Usv Control Station + */ final String C2GM_GNL_PNT_SCTL_USV_RMV = "G-G-GPCUR------"; - /** USV - Antisubmarine Warfare Control Station */ + /** + * USV - Antisubmarine Warfare Control Station + */ final String C2GM_GNL_PNT_SCTL_USV_ASW = "G-G-GPCUA------"; - /** USV - Surface Warfare Control Station */ + /** + * USV - Surface Warfare Control Station + */ final String C2GM_GNL_PNT_SCTL_USV_SUW = "G-G-GPCUS------"; - /** USV - Mine Warfare Control Station */ + /** + * USV - Mine Warfare Control Station + */ final String C2GM_GNL_PNT_SCTL_USV_MIW = "G-G-GPCUM------"; - /** ASW Control Station */ + /** + * ASW Control Station + */ final String C2GM_GNL_PNT_SCTL_ASW = "G-G-GPCA-------"; - /** SUW Control Station */ + /** + * SUW Control Station + */ final String C2GM_GNL_PNT_SCTL_SUW = "G-G-GPCS-------"; - /** MIW Control Station */ + /** + * MIW Control Station + */ final String C2GM_GNL_PNT_SCTL_MIW = "G-G-GPCM-------"; - /** Picket Control Station */ + /** + * Picket Control Station + */ final String C2GM_GNL_PNT_SCTL_PKT = "G-G-GPCP-------"; - /** Rendezvous Control Point */ + /** + * Rendezvous Control Point + */ final String C2GM_GNL_PNT_SCTL_RDV = "G-G-GPCR-------"; - /** Rescue Control Point */ + /** + * Rescue Control Point + */ final String C2GM_GNL_PNT_SCTL_RSC = "G-G-GPCC-------"; - /** Replenishment Control Point */ + /** + * Replenishment Control Point + */ final String C2GM_GNL_PNT_SCTL_REP = "G-G-GPCE-------"; - /** Noncombatant Control Station */ + /** + * Noncombatant Control Station + */ final String C2GM_GNL_PNT_SCTL_NCBTT = "G-G-GPCN-------"; - /** Subsurface Control Station */ + /** + * Subsurface Control Station + */ final String C2GM_GNL_PNT_UCTL = "G-G-GPB--------"; - /** Unmanned Underwater Vehicle (UUV) Control Station */ + /** + * Unmanned Underwater Vehicle (UUV) Control Station + */ final String C2GM_GNL_PNT_UCTL_UUV = "G-G-GPBU-------"; - /** UUV - Antisubmarine Warfare Control Station */ + /** + * UUV - Antisubmarine Warfare Control Station + */ final String C2GM_GNL_PNT_UCTL_UUV_ASW = "G-G-GPBUA------"; - /** UUV - Surface Warfare Control Station */ + /** + * UUV - Surface Warfare Control Station + */ final String C2GM_GNL_PNT_UCTL_UUV_SUW = "G-G-GPBUS------"; - /** UUV - Mine Warfare Control Station */ + /** + * UUV - Mine Warfare Control Station + */ final String C2GM_GNL_PNT_UCTL_UUV_MIW = "G-G-GPBUM------"; - /** Submarine Control Station */ + /** + * Submarine Control Station + */ final String C2GM_GNL_PNT_UCTL_SBSTN = "G-G-GPBS-------"; - /** ASW Submarine Control Station */ + /** + * ASW Submarine Control Station + */ final String C2GM_GNL_PNT_UCTL_SBSTN_ASW = "G-G-GPBSA------"; - /** Boundaries */ + /** + * Boundaries + */ final String C2GM_GNL_LNE_BNDS = "G-G-GLB--------"; - /** Forward Line of Own Troops */ + /** + * Forward Line of Own Troops + */ final String C2GM_GNL_LNE_FLOT = "G-G-GLF--------"; - /** Line Of Contact */ + /** + * Line Of Contact + */ final String C2GM_GNL_LNE_LOC = "G-G-GLC--------"; - /** Phase Line */ + /** + * Phase Line + */ final String C2GM_GNL_LNE_PHELNE = "G-G-GLP--------"; - /** Light Line */ + /** + * Light Line + */ final String C2GM_GNL_LNE_LITLNE = "G-G-GLL--------"; - /** Areas */ + /** + * Areas + */ final String C2GM_GNL_ARS = "G-G-GA---------"; - /** General Area */ + /** + * General Area + */ final String C2GM_GNL_ARS_GENARA = "G-G-GAG--------"; - /** Assembly Area */ + /** + * Assembly Area + */ final String C2GM_GNL_ARS_ABYARA = "G-G-GAA--------"; - /** Engagement Area */ + /** + * Engagement Area + */ final String C2GM_GNL_ARS_EMTARA = "G-G-GAE--------"; - /** Fortified Area */ + /** + * Fortified Area + */ final String C2GM_GNL_ARS_FTFDAR = "G-G-GAF--------"; - /** Drop Zone */ + /** + * Drop Zone + */ final String C2GM_GNL_ARS_DRPZ = "G-G-GAD--------"; - /** Extraction Zone (EZ) */ + /** + * Extraction Zone (EZ) + */ final String C2GM_GNL_ARS_EZ = "G-G-GAX--------"; - /** Landing Zone (LZ) */ + /** + * Landing Zone (LZ) + */ final String C2GM_GNL_ARS_LZ = "G-G-GAL--------"; - /** Pickup Zone (PZ) */ + /** + * Pickup Zone (PZ) + */ final String C2GM_GNL_ARS_PZ = "G-G-GAP--------"; - /** Search Area/Reconnaissance Area */ + /** + * Search Area/Reconnaissance Area + */ final String C2GM_GNL_ARS_SRHARA = "G-G-GAS--------"; - /** Limited Access Area */ + /** + * Limited Access Area + */ final String C2GM_GNL_ARS_LAARA = "G-G-GAY--------"; - /** Airfield Zone */ + /** + * Airfield Zone + */ final String C2GM_GNL_ARS_AIRFZ = "G-G-GAZ--------"; - /** Air Control Point (ACP) */ + /** + * Air Control Point (ACP) + */ final String C2GM_AVN_PNT_ACP = "G-G-APP--------"; - /** Communications Checkpoint (CCP) */ + /** + * Communications Checkpoint (CCP) + */ final String C2GM_AVN_PNT_COMMCP = "G-G-APC--------"; - /** Pull-Up Point (PUP) */ + /** + * Pull-Up Point (PUP) + */ final String C2GM_AVN_PNT_PUP = "G-G-APU--------"; - /** Downed Aircrew Pickup Point */ + /** + * Downed Aircrew Pickup Point + */ final String C2GM_AVN_PNT_DAPP = "G-G-APD--------"; - /** Air Corridor */ + /** + * Air Corridor + */ final String C2GM_AVN_LNE_ACDR = "G-G-ALC--------"; - /** Minimum Risk Route (MRR) */ + /** + * Minimum Risk Route (MRR) + */ final String C2GM_AVN_LNE_MRR = "G-G-ALM--------"; - /** Standard-Use Army Aircraft Flight Route (SAAFR) */ + /** + * Standard-Use Army Aircraft Flight Route (SAAFR) + */ final String C2GM_AVN_LNE_SAAFR = "G-G-ALS--------"; - /** Unmanned Aircraft (UA) Route */ + /** + * Unmanned Aircraft (UA) Route + */ final String C2GM_AVN_LNE_UAR = "G-G-ALU--------"; - /** Low Level Transit Route (LLTR) */ + /** + * Low Level Transit Route (LLTR) + */ final String C2GM_AVN_LNE_LLTR = "G-G-ALL--------"; - /** Restricted Operations Zone (ROZ) */ + /** + * Restricted Operations Zone (ROZ) + */ final String C2GM_AVN_ARS_ROZ = "G-G-AAR--------"; - /** Short-Range Air Defense Engagement Zone (SHORADEZ) */ + /** + * Short-Range Air Defense Engagement Zone (SHORADEZ) + */ final String C2GM_AVN_ARS_SHRDEZ = "G-G-AAF--------"; - /** High Density Airspace Control Zone (HIDACZ) */ + /** + * High Density Airspace Control Zone (HIDACZ) + */ final String C2GM_AVN_ARS_HIDACZ = "G-G-AAH--------"; - /** Missile Engagement Zone (MEZ) */ + /** + * Missile Engagement Zone (MEZ) + */ final String C2GM_AVN_ARS_MEZ = "G-G-AAM--------"; - /** Low Altitude Mez */ + /** + * Low Altitude Mez + */ final String C2GM_AVN_ARS_MEZ_LAMEZ = "G-G-AAML-------"; - /** High Altitude Mez */ + /** + * High Altitude Mez + */ final String C2GM_AVN_ARS_MEZ_HAMEZ = "G-G-AAMH-------"; - /** Weapons Free Zone */ + /** + * Weapons Free Zone + */ final String C2GM_AVN_ARS_WFZ = "G-G-AAW--------"; - /** Dummy (Deception/Decoy) */ + /** + * Dummy (Deception/Decoy) + */ final String C2GM_DCPN_DMY = "G-G-PD---------"; - /** Axis Of Advance For Feint */ + /** + * Axis Of Advance For Feint + */ final String C2GM_DCPN_AAFF = "G-G-PA---------"; - /** Direction Of Attack For Feint */ + /** + * Direction Of Attack For Feint + */ final String C2GM_DCPN_DAFF = "G-G-PF---------"; - /** Decoy Mined Area */ + /** + * Decoy Mined Area + */ final String C2GM_DCPN_DMA = "G-G-PM---------"; - /** Decoy Mined Area, Fenced */ + /** + * Decoy Mined Area, Fenced + */ final String C2GM_DCPN_DMAF = "G-G-PY---------"; - /** Dummy Minefield (Static) */ + /** + * Dummy Minefield (Static) + */ final String C2GM_DCPN_DMYMS = "G-G-PN---------"; - /** Dummy Minefield (Dynamic) */ + /** + * Dummy Minefield (Dynamic) + */ final String C2GM_DCPN_DMYMD = "G-G-PC---------"; - /** Target Reference Point (TRP) */ + /** + * Target Reference Point (TRP) + */ final String C2GM_DEF_PNT_TGTREF = "G-G-DPT--------"; - /** Observation Post/Outpost */ + /** + * Observation Post/Outpost + */ final String C2GM_DEF_PNT_OBSPST = "G-G-DPO--------"; - /** Combat Outpost */ + /** + * Combat Outpost + */ final String C2GM_DEF_PNT_OBSPST_CBTPST = "G-G-DPOC-------"; - /** Observation Post Occupied By Dismounted Scouts Or Reconnaissance */ + /** + * Observation Post Occupied By Dismounted Scouts Or Reconnaissance + */ final String C2GM_DEF_PNT_OBSPST_RECON = "G-G-DPOR-------"; - /** Forward Observer Position */ + /** + * Forward Observer Position + */ final String C2GM_DEF_PNT_OBSPST_FWDOP = "G-G-DPOF-------"; - /** Sensor Outpost/Listening Post (OP/Lp) */ + /** + * Sensor Outpost/Listening Post (OP/Lp) + */ final String C2GM_DEF_PNT_OBSPST_SOP = "G-G-DPOS-------"; - /** Cbrn Observation Post (Dismounted) */ + /** + * Cbrn Observation Post (Dismounted) + */ final String C2GM_DEF_PNT_OBSPST_CBRNOP = "G-G-DPON-------"; - /** Forward Edge Of Battle Area (FEBA) */ + /** + * Forward Edge Of Battle Area (FEBA) + */ final String C2GM_DEF_LNE_FEBA = "G-G-DLF--------"; - /** Principal Direction Of Fire (PDF) */ + /** + * Principal Direction Of Fire (PDF) + */ final String C2GM_DEF_LNE_PDF = "G-G-DLP--------"; - /** Battle Position */ + /** + * Battle Position + */ final String C2GM_DEF_ARS_BTLPSN = "G-G-DAB--------"; - /** Prepared But Not Occupied */ + /** + * Prepared But Not Occupied + */ final String C2GM_DEF_ARS_BTLPSN_PBNO = "G-G-DABP-------"; - /** Engagement Area */ + /** + * Engagement Area + */ final String C2GM_DEF_ARS_EMTARA = "G-G-DAE--------"; - /** Point Of Departure */ + /** + * Point Of Departure + */ final String C2GM_OFF_PNT_PNTD = "G-G-OPP--------"; - /** Axis Of Advance */ + /** + * Axis Of Advance + */ final String C2GM_OFF_LNE_AXSADV = "G-G-OLA--------"; - /** Aviation */ + /** + * Aviation + */ final String C2GM_OFF_LNE_AXSADV_AVN = "G-G-OLAV-------"; - /** Airborne */ + /** + * Airborne + */ final String C2GM_OFF_LNE_AXSADV_ABN = "G-G-OLAA-------"; - /** Attack, Rotary Wing */ + /** + * Attack, Rotary Wing + */ final String C2GM_OFF_LNE_AXSADV_ATK = "G-G-OLAR-------"; - /** Ground */ + /** + * Ground + */ final String C2GM_OFF_LNE_AXSADV_GRD = "G-G-OLAG-------"; - /** Main Attack */ + /** + * Main Attack + */ final String C2GM_OFF_LNE_AXSADV_GRD_MANATK = "G-G-OLAGM------"; - /** Supporting Attack */ + /** + * Supporting Attack + */ final String C2GM_OFF_LNE_AXSADV_GRD_SUPATK = "G-G-OLAGS------"; - /** Aviation */ + /** + * Aviation + */ final String C2GM_OFF_LNE_DIRATK_AVN = "G-G-OLKA-------"; - /** Main Ground Attack */ + /** + * Main Ground Attack + */ final String C2GM_OFF_LNE_DIRATK_GRD_MANATK = "G-G-OLKGM------"; - /** Supporting Ground Attack */ + /** + * Supporting Ground Attack + */ final String C2GM_OFF_LNE_DIRATK_GRD_SUPATK = "G-G-OLKGS------"; - /** Final Coordination Line */ + /** + * Final Coordination Line + */ final String C2GM_OFF_LNE_FCL = "G-G-OLF--------"; - /** Infiltration Lane */ + /** + * Infiltration Lane + */ final String C2GM_OFF_LNE_INFNLE = "G-G-OLI--------"; - /** Limit Of Advance */ + /** + * Limit Of Advance + */ final String C2GM_OFF_LNE_LMTADV = "G-G-OLL--------"; - /** Line Of Departure */ + /** + * Line Of Departure + */ final String C2GM_OFF_LNE_LD = "G-G-OLT--------"; - /** Line Of Departure/Line Of Contact (LD/LC) */ + /** + * Line Of Departure/Line Of Contact (LD/LC) + */ final String C2GM_OFF_LNE_LDLC = "G-G-OLC--------"; - /** Probable Line Of Deployment (PLD) */ + /** + * Probable Line Of Deployment (PLD) + */ final String C2GM_OFF_LNE_PLD = "G-G-OLP--------"; - /** Assault Position */ + /** + * Assault Position + */ final String C2GM_OFF_ARS_ASTPSN = "G-G-OAA--------"; - /** Attack Position */ + /** + * Attack Position + */ final String C2GM_OFF_ARS_ATKPSN = "G-G-OAK--------"; - /** Attack By Fire Position */ + /** + * Attack By Fire Position + */ final String C2GM_OFF_ARS_AFP = "G-G-OAF--------"; - /** Support By Fire Position */ + /** + * Support By Fire Position + */ final String C2GM_OFF_ARS_SFP = "G-G-OAS--------"; - /** Objective */ + /** + * Objective + */ final String C2GM_OFF_ARS_OBJ = "G-G-OAO--------"; - /** Penetration Box */ + /** + * Penetration Box + */ final String C2GM_OFF_ARS_PBX = "G-G-OAP--------"; - /** Ambush */ + /** + * Ambush + */ final String C2GM_SPL_LNE_AMB = "G-G-SLA--------"; - /** Holding Line */ + /** + * Holding Line + */ final String C2GM_SPL_LNE_HGL = "G-G-SLH--------"; - /** Release Line */ + /** + * Release Line + */ final String C2GM_SPL_LNE_REL = "G-G-SLR--------"; - /** Bridgehead */ + /** + * Bridgehead + */ final String C2GM_SPL_LNE_BRGH = "G-G-SLB--------"; - /** Area */ + /** + * Area + */ final String C2GM_SPL_ARA = "G-G-SA---------"; - /** Area Of Operations (AO) */ + /** + * Area Of Operations (AO) + */ final String C2GM_SPL_ARA_AOO = "G-G-SAO--------"; - /** Airhead */ + /** + * Airhead + */ final String C2GM_SPL_ARA_AHD = "G-G-SAA--------"; - /** Encirclement */ + /** + * Encirclement + */ final String C2GM_SPL_ARA_ENCMT = "G-G-SAE--------"; - /** Named */ + /** + * Named + */ final String C2GM_SPL_ARA_NAI = "G-G-SAN--------"; - /** Targeted Area Of Interest (TAI) */ + /** + * Targeted Area Of Interest (TAI) + */ final String C2GM_SPL_ARA_TAI = "G-G-SAT--------"; /////////////////////////////////////////// // Mobility/Survivability /////////////////////////////////////////// - - /** Belt */ + /** + * Belt + */ final String MOBSU_OBST_GNL_BLT = "G-M-OGB--------"; - /** Line */ + /** + * Line + */ final String MOBSU_OBST_GNL_LNE = "G-M-OGL--------"; - /** Zone */ + /** + * Zone + */ final String MOBSU_OBST_GNL_Z = "G-M-OGZ--------"; - /** Obstacle Free Area */ + /** + * Obstacle Free Area + */ final String MOBSU_OBST_GNL_OFA = "G-M-OGF--------"; - /** Obstacle Restricted Area */ + /** + * Obstacle Restricted Area + */ final String MOBSU_OBST_GNL_ORA = "G-M-OGR--------"; - /** Abatis */ + /** + * Abatis + */ final String MOBSU_OBST_ABS = "G-M-OS---------"; - /** Antitank Ditch, Under Construction */ + /** + * Antitank Ditch, Under Construction + */ final String MOBSU_OBST_ATO_ATD_ATDUC = "G-M-OADU-------"; - /** Antitank Ditch, Complete */ + /** + * Antitank Ditch, Complete + */ final String MOBSU_OBST_ATO_ATD_ATDC = "G-M-OADC-------"; - /** Antitank Ditch Reinforced With Antitank Mines */ + /** + * Antitank Ditch Reinforced With Antitank Mines + */ final String MOBSU_OBST_ATO_ATDATM = "G-M-OAR--------"; - /** Fixed And Prefabricated */ + /** + * Fixed And Prefabricated + */ final String MOBSU_OBST_ATO_TDTSM_FIXPFD = "G-M-OAOF-------"; - /** Moveable */ + /** + * Moveable + */ final String MOBSU_OBST_ATO_TDTSM_MVB = "G-M-OAOM-------"; - /** Moveable And Prefabricated */ + /** + * Moveable And Prefabricated + */ final String MOBSU_OBST_ATO_TDTSM_MVBPFD = "G-M-OAOP-------"; - /** Antitank Wall */ + /** + * Antitank Wall + */ final String MOBSU_OBST_ATO_ATW = "G-M-OAW--------"; - /** Booby Trap */ + /** + * Booby Trap + */ final String MOBSU_OBST_BBY = "G-M-OB---------"; - /** Unspecified Mine */ + /** + * Unspecified Mine + */ final String MOBSU_OBST_MNE_USPMNE = "G-M-OMU--------"; - /** Antitank Mine (AT) */ + /** + * Antitank Mine (AT) + */ final String MOBSU_OBST_MNE_ATMNE = "G-M-OMT--------"; - /** Antitank Mine With Antihandling Device */ + /** + * Antitank Mine With Antihandling Device + */ final String MOBSU_OBST_MNE_ATMAHD = "G-M-OMD--------"; - /** Antitank Mine (Directional) */ + /** + * Antitank Mine (Directional) + */ final String MOBSU_OBST_MNE_ATMDIR = "G-M-OME--------"; - /** Antipersonnel (AP) Mines */ + /** + * Antipersonnel (AP) Mines + */ final String MOBSU_OBST_MNE_APMNE = "G-M-OMP--------"; - /** Wide Area Mines */ + /** + * Wide Area Mines + */ final String MOBSU_OBST_MNE_WAMNE = "G-M-OMW--------"; - /** Mine Cluster */ + /** + * Mine Cluster + */ final String MOBSU_OBST_MNE_MCLST = "G-M-OMC--------"; - /** Static Depiction */ + /** + * Static Depiction + */ final String MOBSU_OBST_MNEFLD_STC = "G-M-OFS--------"; - /** Dynamic Depiction */ + /** + * Dynamic Depiction + */ final String MOBSU_OBST_MNEFLD_DYN = "G-M-OFD--------"; - /** Gap */ + /** + * Gap + */ final String MOBSU_OBST_MNEFLD_GAP = "G-M-OFG--------"; - /** Mined Area */ + /** + * Mined Area + */ final String MOBSU_OBST_MNEFLD_MNDARA = "G-M-OFA--------"; - /** Block */ + /** + * Block + */ final String MOBSU_OBST_OBSEFT_BLK = "G-M-OEB--------"; - /** Fix */ + /** + * Fix + */ final String MOBSU_OBST_OBSEFT_FIX = "G-M-OEF--------"; - /** Turn */ + /** + * Turn + */ final String MOBSU_OBST_OBSEFT_TUR = "G-M-OET--------"; - /** Disrupt */ + /** + * Disrupt + */ final String MOBSU_OBST_OBSEFT_DRT = "G-M-OED--------"; - /** Unexploded Ordnance Area (UXO) */ + /** + * Unexploded Ordnance Area (UXO) + */ final String MOBSU_OBST_UXO = "G-M-OU---------"; - /** Planned */ + /** + * Planned + */ final String MOBSU_OBST_RCBB_PLND = "G-M-ORP--------"; - /** Explosives, State Of Readiness 1 (Safe) */ + /** + * Explosives, State Of Readiness 1 (Safe) + */ final String MOBSU_OBST_RCBB_SAFE = "G-M-ORS--------"; - /** Explosives, State Of Readiness 2 (Armed-But Passable) */ + /** + * Explosives, State Of Readiness 2 (Armed-But Passable) + */ final String MOBSU_OBST_RCBB_ABP = "G-M-ORA--------"; - /** Roadblock Complete (Executed) */ + /** + * Roadblock Complete (Executed) + */ final String MOBSU_OBST_RCBB_EXCD = "G-M-ORC--------"; - /** Trip Wire */ + /** + * Trip Wire + */ final String MOBSU_OBST_TRIPWR = "G-M-OT---------"; - /** Wire Obstacle */ + /** + * Wire Obstacle + */ final String MOBSU_OBST_WREOBS = "G-M-OW---------"; - /** Unspecified */ + /** + * Unspecified + */ final String MOBSU_OBST_WREOBS_USP = "G-M-OWU--------"; - /** Single Fence */ + /** + * Single Fence + */ final String MOBSU_OBST_WREOBS_SNGFNC = "G-M-OWS--------"; - /** Double Fence */ + /** + * Double Fence + */ final String MOBSU_OBST_WREOBS_DBLFNC = "G-M-OWD--------"; - /** Double Apron Fence */ + /** + * Double Apron Fence + */ final String MOBSU_OBST_WREOBS_DAFNC = "G-M-OWA--------"; - /** Low Wire Fence */ + /** + * Low Wire Fence + */ final String MOBSU_OBST_WREOBS_LWFNC = "G-M-OWL--------"; - /** High Wire Fence */ + /** + * High Wire Fence + */ final String MOBSU_OBST_WREOBS_HWFNC = "G-M-OWH--------"; - /** Single Concertina */ + /** + * Single Concertina + */ final String MOBSU_OBST_WREOBS_CCTA_SNG = "G-M-OWCS-------"; - /** Double Strand Concertina */ + /** + * Double Strand Concertina + */ final String MOBSU_OBST_WREOBS_CCTA_DBLSTD = "G-M-OWCD-------"; - /** Triple Strand Concertina */ + /** + * Triple Strand Concertina + */ final String MOBSU_OBST_WREOBS_CCTA_TRISTD = "G-M-OWCT-------"; - /** Low Tower */ + /** + * Low Tower + */ final String MOBSU_OBST_AVN_TWR_LOW = "G-M-OHTL-------"; - /** High Tower */ + /** + * High Tower + */ final String MOBSU_OBST_AVN_TWR_HIGH = "G-M-OHTH-------"; - /** Overhead Wire/Power Line */ + /** + * Overhead Wire/Power Line + */ final String MOBSU_OBST_AVN_OHWIRE = "G-M-OHO--------"; - /** Bypass Easy */ + /** + * Bypass Easy + */ final String MOBSU_OBSTBP_DFTY_ESY = "G-M-BDE--------"; - /** Bypass Difficult */ + /** + * Bypass Difficult + */ final String MOBSU_OBSTBP_DFTY_DFT = "G-M-BDD--------"; - /** Bypass Impossible */ + /** + * Bypass Impossible + */ final String MOBSU_OBSTBP_DFTY_IMP = "G-M-BDI--------"; - /** Crossing Site/Water Crossing */ + /** + * Crossing Site/Water Crossing + */ final String MOBSU_OBSTBP_CSGSTE = "G-M-BC---------"; - /** Assault Crossing Area */ + /** + * Assault Crossing Area + */ final String MOBSU_OBSTBP_CSGSTE_ASTCA = "G-M-BCA--------"; - /** Bridge or Gap */ + /** + * Bridge or Gap + */ final String MOBSU_OBSTBP_CSGSTE_BRG = "G-M-BCB--------"; - /** Ferry */ + /** + * Ferry + */ final String MOBSU_OBSTBP_CSGSTE_FRY = "G-M-BCF--------"; - /** Ford Easy */ + /** + * Ford Easy + */ final String MOBSU_OBSTBP_CSGSTE_FRDESY = "G-M-BCE--------"; - /** Ford Difficult */ + /** + * Ford Difficult + */ final String MOBSU_OBSTBP_CSGSTE_FRDDFT = "G-M-BCD--------"; - /** Lane */ + /** + * Lane + */ final String MOBSU_OBSTBP_CSGSTE_LANE = "G-M-BCL--------"; - /** Raft Site */ + /** + * Raft Site + */ final String MOBSU_OBSTBP_CSGSTE_RFT = "G-M-BCR--------"; - /** Engineer Regulating Point */ + /** + * Engineer Regulating Point + */ final String MOBSU_OBSTBP_CSGSTE_ERP = "G-M-BCP--------"; - /** Earthwork, Small Trench Or Fortification */ + /** + * Earthwork, Small Trench Or Fortification + */ final String MOBSU_SU_ESTOF = "G-M-SE---------"; - /** Fort */ + /** + * Fort + */ final String MOBSU_SU_FRT = "G-M-SF---------"; - /** Fortified Line */ + /** + * Fortified Line + */ final String MOBSU_SU_FTFDLN = "G-M-SL---------"; - /** Foxhole, Emplacement Or Weapon Site */ + /** + * Foxhole, Emplacement Or Weapon Site + */ final String MOBSU_SU_FEWS = "G-M-SW---------"; - /** Strong Point */ + /** + * Strong Point + */ final String MOBSU_SU_STRGPT = "G-M-SP---------"; - /** Surface Shelter */ + /** + * Surface Shelter + */ final String MOBSU_SU_SUFSHL = "G-M-SS---------"; - /** Underground Shelter */ + /** + * Underground Shelter + */ final String MOBSU_SU_UGDSHL = "G-M-SU---------"; - /** Minimum Safe Distance Zones */ + /** + * Minimum Safe Distance Zones + */ final String MOBSU_CBRN_MSDZ = "G-M-NM---------"; - /** Nuclear Detonations Ground Zero */ + /** + * Nuclear Detonations Ground Zero + */ final String MOBSU_CBRN_NDGZ = "G-M-NZ---------"; - /** Fallout Producing */ + /** + * Fallout Producing + */ final String MOBSU_CBRN_FAOTP = "G-M-NF---------"; - /** Radioactive Area */ + /** + * Radioactive Area + */ final String MOBSU_CBRN_RADA = "G-M-NR---------"; - /** Biologically Contaminated Area */ + /** + * Biologically Contaminated Area + */ final String MOBSU_CBRN_BIOCA = "G-M-NB---------"; - /** Chemically Contaminated Area */ + /** + * Chemically Contaminated Area + */ final String MOBSU_CBRN_CMLCA = "G-M-NC---------"; - /** Biological Release Event */ + /** + * Biological Release Event + */ final String MOBSU_CBRN_REEVNT_BIO = "G-M-NEB--------"; - /** Chemical Release Event */ + /** + * Chemical Release Event + */ final String MOBSU_CBRN_REEVNT_CML = "G-M-NEC--------"; - /** Decon Site/Point (Unspecified) */ + /** + * Decon Site/Point (Unspecified) + */ final String MOBSU_CBRN_DECONP_USP = "G-M-NDP--------"; - /** Alternate Decon Site/Point (Unspecified) */ + /** + * Alternate Decon Site/Point (Unspecified) + */ final String MOBSU_CBRN_DECONP_ALTUSP = "G-M-NDA--------"; - /** Decon Site/Point (Troops) */ + /** + * Decon Site/Point (Troops) + */ final String MOBSU_CBRN_DECONP_TRP = "G-M-NDT--------"; - /** Decon , */ + /** + * Decon , + */ final String MOBSU_CBRN_DECONP_EQT = "G-M-NDE--------"; - /** Decon Site/Point (Equipment And Troops) */ + /** + * Decon Site/Point (Equipment And Troops) + */ final String MOBSU_CBRN_DECONP_EQTTRP = "G-M-NDB--------"; - /** Decon Site/Point (Operational Decontamination) */ + /** + * Decon Site/Point (Operational Decontamination) + */ final String MOBSU_CBRN_DECONP_OPDECN = "G-M-NDO--------"; - /** Decon Site/Point (Thorough Decontamination) */ + /** + * Decon Site/Point (Thorough Decontamination) + */ final String MOBSU_CBRN_DECONP_TRGH = "G-M-NDD--------"; - /** Dose Rate Contour Lines */ + /** + * Dose Rate Contour Lines + */ final String MOBSU_CBRN_DRCL = "G-M-NL---------"; ///////////////////////////////////////////////// // Fire Support ///////////////////////////////////////////////// - - /** Point/Single Target */ + /** + * Point/Single Target + */ final String FSUPP_PNT_TGT_PTGT = "G-F-PTS--------"; - /** Nuclear Target */ + /** + * Nuclear Target + */ final String FSUPP_PNT_TGT_NUCTGT = "G-F-PTN--------"; - /** Fire Support Station */ + /** + * Fire Support Station + */ final String FSUPP_PNT_C2PNT_FSS = "G-F-PCF--------"; - /** Survey Control Point */ + /** + * Survey Control Point + */ final String FSUPP_PNT_C2PNT_SCP = "G-F-PCS--------"; - /** Firing Point */ + /** + * Firing Point + */ final String FSUPP_PNT_C2PNT_FP = "G-F-PCB--------"; - /** Reload Point */ + /** + * Reload Point + */ final String FSUPP_PNT_C2PNT_RP = "G-F-PCR--------"; - /** Hide Point */ + /** + * Hide Point + */ final String FSUPP_PNT_C2PNT_HP = "G-F-PCH--------"; - /** Launch Point */ + /** + * Launch Point + */ final String FSUPP_PNT_C2PNT_LP = "G-F-PCL--------"; - /** Linear Target */ + /** + * Linear Target + */ final String FSUPP_LNE_LNRTGT = "G-F-LT---------"; - /** Linear Smoke Target */ + /** + * Linear Smoke Target + */ final String FSUPP_LNE_LNRTGT_LSTGT = "G-F-LTS--------"; - /** Final Protective Fire (FPF) */ + /** + * Final Protective Fire (FPF) + */ final String FSUPP_LNE_LNRTGT_FPF = "G-F-LTF--------"; - /** Fire Support Coordination Line (FSCL) */ + /** + * Fire Support Coordination Line (FSCL) + */ final String FSUPP_LNE_C2LNE_FSCL = "G-F-LCF--------"; - /** Coordinated Fire Line (CFL) */ + /** + * Coordinated Fire Line (CFL) + */ final String FSUPP_LNE_C2LNE_CFL = "G-F-LCC--------"; - /** No-Fire Line (NFL) */ + /** + * No-Fire Line (NFL) + */ final String FSUPP_LNE_C2LNE_NFL = "G-F-LCN--------"; - /** Restrictive */ + /** + * Restrictive + */ final String FSUPP_LNE_C2LNE_RFL = "G-F-LCR--------"; - /** Munition Flight Path (MFP) */ + /** + * Munition Flight Path (MFP) + */ final String FSUPP_LNE_C2LNE_MFP = "G-F-LCM--------"; - /** Area Target */ + /** + * Area Target + */ final String FSUPP_ARS_ARATGT = "G-F-AT---------"; - /** Rectangular Target */ + /** + * Rectangular Target + */ final String FSUPP_ARS_ARATGT_RTGTGT = "G-F-ATR--------"; - /** Circular Target */ + /** + * Circular Target + */ final String FSUPP_ARS_ARATGT_CIRTGT = "G-F-ATC--------"; - /** Series Or Group Of Targets */ + /** + * Series Or Group Of Targets + */ final String FSUPP_ARS_ARATGT_SGTGT = "G-F-ATG--------"; - /** Smoke */ + /** + * Smoke + */ final String FSUPP_ARS_ARATGT_SMK = "G-F-ATS--------"; - /** Bomb Area */ + /** + * Bomb Area + */ final String FSUPP_ARS_ARATGT_BMARA = "G-F-ATB--------"; - /** Fire Support Area (FSA), Irregular */ + /** + * Fire Support Area (FSA), Irregular + */ final String FSUPP_ARS_C2ARS_FSA_IRR = "G-F-ACSI-------"; - /** Fire Support Area (FSA), Rectangular */ + /** + * Fire Support Area (FSA), Rectangular + */ final String FSUPP_ARS_C2ARS_FSA_RTG = "G-F-ACSR-------"; - /** Fire Support Area (FSA), Circular */ + /** + * Fire Support Area (FSA), Circular + */ final String FSUPP_ARS_C2ARS_FSA_CIRCLR = "G-F-ACSC-------"; - /** Airspace Coordination Area (ACA), Irregular */ + /** + * Airspace Coordination Area (ACA), Irregular + */ final String FSUPP_ARS_C2ARS_ACA_IRR = "G-F-ACAI-------"; - /** Airspace Coordination Area (ACA), Rectangular */ + /** + * Airspace Coordination Area (ACA), Rectangular + */ final String FSUPP_ARS_C2ARS_ACA_RTG = "G-F-ACAR-------"; - /** Airspace Coordination Area (ACA), Circular */ + /** + * Airspace Coordination Area (ACA), Circular + */ final String FSUPP_ARS_C2ARS_ACA_CIRCLR = "G-F-ACAC-------"; - /** Free Fire Area (FFA), Irregular */ + /** + * Free Fire Area (FFA), Irregular + */ final String FSUPP_ARS_C2ARS_FFA_IRR = "G-F-ACFI-------"; - /** Free Fire Area (FFA), Rectangular */ + /** + * Free Fire Area (FFA), Rectangular + */ final String FSUPP_ARS_C2ARS_FFA_RTG = "G-F-ACFR-------"; - /** Free Fire Area (FFA), Circular */ + /** + * Free Fire Area (FFA), Circular + */ final String FSUPP_ARS_C2ARS_FFA_CIRCLR = "G-F-ACFC-------"; - /** No Fire Area (NFA), Irregular */ + /** + * No Fire Area (NFA), Irregular + */ final String FSUPP_ARS_C2ARS_NFA_IRR = "G-F-ACNI-------"; - /** No Fire Area (NFA), Rectangular */ + /** + * No Fire Area (NFA), Rectangular + */ final String FSUPP_ARS_C2ARS_NFA_RTG = "G-F-ACNR-------"; - /** No , Circular */ + /** + * No , Circular + */ final String FSUPP_ARS_C2ARS_NFA_CIRCLR = "G-F-ACNC-------"; - /** Restrictive Fire Area (RFA), Irregular */ + /** + * Restrictive Fire Area (RFA), Irregular + */ final String FSUPP_ARS_C2ARS_RFA_IRR = "G-F-ACRI-------"; - /** Restrictive Fire Area (RFA), Rectangular */ + /** + * Restrictive Fire Area (RFA), Rectangular + */ final String FSUPP_ARS_C2ARS_RFA_RTG = "G-F-ACRR-------"; - /** Restrictive Fire Area (RFA), Circular */ + /** + * Restrictive Fire Area (RFA), Circular + */ final String FSUPP_ARS_C2ARS_RFA_CIRCLR = "G-F-ACRC-------"; - /** Position Area For Artillery (PAA), Rectangular */ + /** + * Position Area For Artillery (PAA), Rectangular + */ final String FSUPP_ARS_C2ARS_PAA_RTG = "G-F-ACPR-------"; - /** Position Area For Artillery (PAA), Circular */ + /** + * Position Area For Artillery (PAA), Circular + */ final String FSUPP_ARS_C2ARS_PAA_CIRCLR = "G-F-ACPC-------"; - /** Sensor Zone, Irregular */ + /** + * Sensor Zone, Irregular + */ final String FSUPP_ARS_C2ARS_SNSZ_IRR = "G-F-ACEI-------"; - /** Sensor Zone, Rectangular */ + /** + * Sensor Zone, Rectangular + */ final String FSUPP_ARS_C2ARS_SNSZ_RTG = "G-F-ACER-------"; - /** Sensor Zone , Circular */ + /** + * Sensor Zone , Circular + */ final String FSUPP_ARS_C2ARS_SNSZ_CIRCLR = "G-F-ACEC-------"; - /** Dead Space Area (DA), Irregular */ + /** + * Dead Space Area (DA), Irregular + */ final String FSUPP_ARS_C2ARS_DA_IRR = "G-F-ACDI-------"; - /** Dead Space Area (DA), Rectangular */ + /** + * Dead Space Area (DA), Rectangular + */ final String FSUPP_ARS_C2ARS_DA_RTG = "G-F-ACDR-------"; - /** Dead Space Area (DA), Circular */ + /** + * Dead Space Area (DA), Circular + */ final String FSUPP_ARS_C2ARS_DA_CIRCLR = "G-F-ACDC-------"; - /** Zone Of Responsibility (ZOR), Irregular */ + /** + * Zone Of Responsibility (ZOR), Irregular + */ final String FSUPP_ARS_C2ARS_ZOR_IRR = "G-F-ACZI-------"; - /** Zone Of Responsibility (ZOR), Rectangular */ + /** + * Zone Of Responsibility (ZOR), Rectangular + */ final String FSUPP_ARS_C2ARS_ZOR_RTG = "G-F-ACZR-------"; - /** Zone Of Responsibility (ZOR), Circular */ + /** + * Zone Of Responsibility (ZOR), Circular + */ final String FSUPP_ARS_C2ARS_ZOR_CIRCLR = "G-F-ACZC-------"; - /** Target Build Up Area (TBA), Irregular */ + /** + * Target Build Up Area (TBA), Irregular + */ final String FSUPP_ARS_C2ARS_TBA_IRR = "G-F-ACBI-------"; - /** Target Build Up Area (TBA),Rectangular */ + /** + * Target Build Up Area (TBA),Rectangular + */ final String FSUPP_ARS_C2ARS_TBA_RTG = "G-F-ACBR-------"; - /** Target Build Up Area (TBA), Circular */ + /** + * Target Build Up Area (TBA), Circular + */ final String FSUPP_ARS_C2ARS_TBA_CIRCLR = "G-F-ACBC-------"; - /** Target , Irregular */ + /** + * Target , Irregular + */ final String FSUPP_ARS_C2ARS_TVAR_IRR = "G-F-ACVI-------"; - /** Target Value Area (TVAR), Rectangular */ + /** + * Target Value Area (TVAR), Rectangular + */ final String FSUPP_ARS_C2ARS_TVAR_RTG = "G-F-ACVR-------"; - /** Target Value Area (TVAR), Circular */ + /** + * Target Value Area (TVAR), Circular + */ final String FSUPP_ARS_C2ARS_TVAR_CIRCLR = "G-F-ACVC-------"; - /** Terminally Guided Munition Footprint (TGMF) */ + /** + * Terminally Guided Munition Footprint (TGMF) + */ final String FSUPP_ARS_C2ARS_TGMF = "G-F-ACT--------"; - /** Artillery Target Intelligence (ATI) Zone, Irregular */ + /** + * Artillery Target Intelligence (ATI) Zone, Irregular + */ final String FSUPP_ARS_TGTAQZ_ATIZ_IRR = "G-F-AZII-------"; - /** Artillery Target Intelligence (ATI) Zone, Rectangular */ + /** + * Artillery Target Intelligence (ATI) Zone, Rectangular + */ final String FSUPP_ARS_TGTAQZ_ATIZ_RTG = "G-F-AZIR-------"; - /** Call For Fire Zone (CFFZ), Irregular */ + /** + * Call For Fire Zone (CFFZ), Irregular + */ final String FSUPP_ARS_TGTAQZ_CFFZ_IRR = "G-F-AZXI-------"; - /** Call For Fire Zone (CFFZ), Rectangular */ + /** + * Call For Fire Zone (CFFZ), Rectangular + */ final String FSUPP_ARS_TGTAQZ_CFFZ_RTG = "G-F-AZXR-------"; - /** Censor Zone, Irregular */ + /** + * Censor Zone, Irregular + */ final String FSUPP_ARS_TGTAQZ_CNS_IRR = "G-F-AZCI-------"; - /** Censor Zone, Rectangular */ + /** + * Censor Zone, Rectangular + */ final String FSUPP_ARS_TGTAQZ_CNS_RTG = "G-F-AZCR-------"; - /** Critical Friendly Zone (CFZ), Irregular */ + /** + * Critical Friendly Zone (CFZ), Irregular + */ final String FSUPP_ARS_TGTAQZ_CFZ_IRR = "G-F-AZFI-------"; - /** Critical Friendly Zone (CFZ), Rectangular */ + /** + * Critical Friendly Zone (CFZ), Rectangular + */ final String FSUPP_ARS_TGTAQZ_CFZ_RTG = "G-F-AZFR-------"; - /** Weapon/Sensor Range Fan, Circular */ + /** + * Weapon/Sensor Range Fan, Circular + */ final String FSUPP_ARS_WPNRF_CIRCLR = "G-F-AXC--------"; - /** Weapon/Sensor Range Fan, Sector */ + /** + * Weapon/Sensor Range Fan, Sector + */ final String FSUPP_ARS_WPNRF_SCR = "G-F-AXS--------"; - /** Blue Kill Box, Circular */ + /** + * Blue Kill Box, Circular + */ final String FSUPP_ARS_KLBOX_BLUE_CIRCLR = "G-F-AKBC-------"; - /** Blue Kill Box, Irregular */ + /** + * Blue Kill Box, Irregular + */ final String FSUPP_ARS_KLBOX_BLUE_IRR = "G-F-AKBI-------"; - /** Blue , Rectangular */ + /** + * Blue , Rectangular + */ final String FSUPP_ARS_KLBOX_BLUE_RTG = "G-F-AKBR-------"; - /** Purple Kill Box, Circular */ + /** + * Purple Kill Box, Circular + */ final String FSUPP_ARS_KLBOX_PURPLE_CIRCLR = "G-F-AKPC-------"; - /** Purple Kill Box, Irregular */ + /** + * Purple Kill Box, Irregular + */ final String FSUPP_ARS_KLBOX_PURPLE_IRR = "G-F-AKPI-------"; - /** Purple Kill Box, Rectangular */ + /** + * Purple Kill Box, Rectangular + */ final String FSUPP_ARS_KLBOX_PURPLE_RTG = "G-F-AKPR-------"; //////////////////////////////////////////////// // Combat Service Support //////////////////////////////////////////////// - - /** Ambulance Exchange Point */ + /** + * Ambulance Exchange Point + */ final String CSS_PNT_AEP = "G-S-PX---------"; - /** Cannibalization Point */ + /** + * Cannibalization Point + */ final String CSS_PNT_CBNP = "G-S-PC---------"; - /** Casualty Collection Point */ + /** + * Casualty Collection Point + */ final String CSS_PNT_CCP = "G-S-PY---------"; - /** Civilian Collection Point */ + /** + * Civilian Collection Point + */ final String CSS_PNT_CVP = "G-S-PT---------"; - /** Detainee Collection Point */ + /** + * Detainee Collection Point + */ final String CSS_PNT_DCP = "G-S-PD---------"; - /** Enemy Prisoner Of War (EPW) Collection Point */ + /** + * Enemy Prisoner Of War (EPW) Collection Point + */ final String CSS_PNT_EPWCP = "G-S-PE---------"; - /** Logistics Release Point (LRP) */ + /** + * Logistics Release Point (LRP) + */ final String CSS_PNT_LRP = "G-S-PL---------"; - /** Maintenance Collection Point */ + /** + * Maintenance Collection Point + */ final String CSS_PNT_MCP = "G-S-PM---------"; - /** Rearm, Refuel And Resupply Point */ + /** + * Rearm, Refuel And Resupply Point + */ final String CSS_PNT_RRRP = "G-S-PR---------"; - /** Refuel On The Move (ROM) Point */ + /** + * Refuel On The Move (ROM) Point + */ final String CSS_PNT_ROM = "G-S-PU---------"; - /** Traffic Control Post (TCP) */ + /** + * Traffic Control Post (TCP) + */ final String CSS_PNT_TCP = "G-S-PO---------"; - /** Trailer Transfer Point */ + /** + * Trailer Transfer Point + */ final String CSS_PNT_TTP = "G-S-PI---------"; - /** Unit Maintenance Collection Point */ + /** + * Unit Maintenance Collection Point + */ final String CSS_PNT_UMC = "G-S-PN---------"; - /** General */ + /** + * General + */ final String CSS_PNT_SPT_GNL = "G-S-PSZ--------"; - /** Class I */ + /** + * Class I + */ final String CSS_PNT_SPT_CLS1 = "G-S-PSA--------"; - /** Class Ii */ + /** + * Class Ii + */ final String CSS_PNT_SPT_CLS2 = "G-S-PSB--------"; - /** Class Iii */ + /** + * Class Iii + */ final String CSS_PNT_SPT_CLS3 = "G-S-PSC--------"; - /** Class Iv */ + /** + * Class Iv + */ final String CSS_PNT_SPT_CLS4 = "G-S-PSD--------"; - /** Class V */ + /** + * Class V + */ final String CSS_PNT_SPT_CLS5 = "G-S-PSE--------"; - /** Class Vi */ + /** + * Class Vi + */ final String CSS_PNT_SPT_CLS6 = "G-S-PSF--------"; - /** Class Vii */ + /** + * Class Vii + */ final String CSS_PNT_SPT_CLS7 = "G-S-PSG--------"; - /** Class Viii */ + /** + * Class Viii + */ final String CSS_PNT_SPT_CLS8 = "G-S-PSH--------"; - /** Class Ix */ + /** + * Class Ix + */ final String CSS_PNT_SPT_CLS9 = "G-S-PSI--------"; - /** Class X */ + /** + * Class X + */ final String CSS_PNT_SPT_CLS10 = "G-S-PSJ--------"; - /** Ammunition Supply Point (ASP) */ + /** + * Ammunition Supply Point (ASP) + */ final String CSS_PNT_AP_ASP = "G-S-PAS--------"; - /** Ammunition Transfer Point (ATP) */ + /** + * Ammunition Transfer Point (ATP) + */ final String CSS_PNT_AP_ATP = "G-S-PAT--------"; - /** Moving Convoy */ + /** + * Moving Convoy + */ final String CSS_LNE_CNY_MCNY = "G-S-LCM--------"; - /** Halted Convoy */ + /** + * Halted Convoy + */ final String CSS_LNE_CNY_HCNY = "G-S-LCH--------"; - /** Main Supply Route */ + /** + * Main Supply Route + */ final String CSS_LNE_SLPRUT_MSRUT = "G-S-LRM--------"; - /** Alternate Supply Route */ + /** + * Alternate Supply Route + */ final String CSS_LNE_SLPRUT_ASRUT = "G-S-LRA--------"; - /** One-Way Traffic */ + /** + * One-Way Traffic + */ final String CSS_LNE_SLPRUT_1WTRFF = "G-S-LRO--------"; - /** Alternating Traffic */ + /** + * Alternating Traffic + */ final String CSS_LNE_SLPRUT_ATRFF = "G-S-LRT--------"; - /** Two-Way Traffic */ + /** + * Two-Way Traffic + */ final String CSS_LNE_SLPRUT_2WTRFF = "G-S-LRW--------"; - /** Detainee Holding Area */ + /** + * Detainee Holding Area + */ final String CSS_ARA_DHA = "G-S-AD---------"; - /** Enemy Prisoner Of War (EPW) Holding Area */ + /** + * Enemy Prisoner Of War (EPW) Holding Area + */ final String CSS_ARA_EPWHA = "G-S-AE---------"; - /** Forward Arming And Refueling Area (FARP) */ + /** + * Forward Arming And Refueling Area (FARP) + */ final String CSS_ARA_FARP = "G-S-AR---------"; - /** Refugee Holding Area */ + /** + * Refugee Holding Area + */ final String CSS_ARA_RHA = "G-S-AH---------"; - /** Brigade (BSA) */ + /** + * Brigade (BSA) + */ final String CSS_ARA_SUPARS_BSA = "G-S-ASB--------"; - /** Division (DSA) */ + /** + * Division (DSA) + */ final String CSS_ARA_SUPARS_DSA = "G-S-ASD--------"; - /** Regimental (RSA) */ + /** + * Regimental (RSA) + */ final String CSS_ARA_SUPARS_RSA = "G-S-ASR--------"; ////////////////////////////////////////////// // Other ////////////////////////////////////////////// - - /** Ditched Aircraft */ + /** + * Ditched Aircraft + */ final String OTH_ER_DTHAC = "G-O-ED---------"; - /** Person In Water */ + /** + * Person In Water + */ final String OTH_ER_PIW = "G-O-EP---------"; - /** Distressed Vessel */ + /** + * Distressed Vessel + */ final String OTH_ER_DSTVES = "G-O-EV---------"; - /** Sea Mine-Like */ + /** + * Sea Mine-Like + */ final String OTH_HAZ_SML = "G-O-HM---------"; - /** Navigational */ + /** + * Navigational + */ final String OTH_HAZ_NVGL = "G-O-HN---------"; - /** Iceberg */ + /** + * Iceberg + */ final String OTH_HAZ_IB = "G-O-HI---------"; - /** Oil Rig */ + /** + * Oil Rig + */ final String OTH_HAZ_OLRG = "G-O-HO---------"; - /** Bottom Return/Non-Milco */ + /** + * Bottom Return/Non-Milco + */ final String OTH_SSUBSR_BTMRTN = "G-O-SB---------"; - /** Installation/Manmade */ + /** + * Installation/Manmade + */ final String OTH_SSUBSR_BTMRTN_INS = "G-O-SBM--------"; - /** Seabed Rock/Stone, Obstacle,Other */ + /** + * Seabed Rock/Stone, Obstacle,Other + */ final String OTH_SSUBSR_BTMRTN_SBRSOO = "G-O-SBN--------"; - /** Wreck, Non Dangerous */ + /** + * Wreck, Non Dangerous + */ final String OTH_SSUBSR_BTMRTN_WRKND = "G-O-SBW--------"; - /** Wreck, Dangerous */ + /** + * Wreck, Dangerous + */ final String OTH_SSUBSR_BTMRTN_WRKD = "G-O-SBX--------"; - /** Marine Life */ + /** + * Marine Life + */ final String OTH_SSUBSR_MARLFE = "G-O-SM---------"; - /** Sea Anomaly (Wake, Current, Knuckle) */ + /** + * Sea Anomaly (Wake, Current, Knuckle) + */ final String OTH_SSUBSR_SA = "G-O-SS---------"; - /** Bearing Line */ + /** + * Bearing Line + */ final String OTH_BERLNE = "G-O-B----------"; - /** Electronic Bearing Line */ + /** + * Electronic Bearing Line + */ final String OTH_BERLNE_ELC = "G-O-BE---------"; - /** Acoustic Bearing Line */ + /** + * Acoustic Bearing Line + */ final String OTH_BERLNE_ACU = "G-O-BA---------"; - /** Torpedo, Bearing Line */ + /** + * Torpedo, Bearing Line + */ final String OTH_BERLNE_TPD = "G-O-BT---------"; - /** Electro-Optical Intercept */ + /** + * Electro-Optical Intercept + */ final String OTH_BERLNE_EOPI = "G-O-BO---------"; - /** Acoustic Fix */ + /** + * Acoustic Fix + */ final String OTH_FIX_ACU = "G-O-FA---------"; - /** Electro-Magnetic Fix */ + /** + * Electro-Magnetic Fix + */ final String OTH_FIX_EM = "G-O-FE---------"; - /** Electro-Optical Fix */ + /** + * Electro-Optical Fix + */ final String OTH_FIX_EOP = "G-O-FO---------"; } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/TacticalGraphicSymbol.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/TacticalGraphicSymbol.java index 005398af30..8458b24519 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/TacticalGraphicSymbol.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/TacticalGraphicSymbol.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics; import gov.nasa.worldwind.*; @@ -32,54 +31,53 @@ * @version $Id: TacticalGraphicSymbol.java 2196 2014-08-06 19:42:15Z tgaskins $ * @see MilStd2525PointGraphic */ -public class TacticalGraphicSymbol extends AbstractTacticalSymbol -{ +public class TacticalGraphicSymbol extends AbstractTacticalSymbol { + /** * Object that provides the default offset for each point graphic. Most graphics are centered on their position, but * some require a different offset. */ protected static DefaultOffsets defaultOffsets = new DefaultOffsets(); - /** Object that provides the default label layouts for each point graphic. */ + /** + * Object that provides the default label layouts for each point graphic. + */ protected static DefaultLabelLayouts defaultLayouts = new DefaultLabelLayouts(); protected static final Offset BELOW_BOTTOM_CENTER_OFFSET = Offset.fromFraction(0.5, -0.1); - /** The default number of label lines to expect when computing the minimum size of the text layout rectangle. */ + /** + * The default number of label lines to expect when computing the minimum size of the text layout rectangle. + */ protected static final int DEFAULT_LABEL_LINES = 2; - public static class LabelLayout - { + public static class LabelLayout { + protected String modifier; protected List offsets = new ArrayList(); - public LabelLayout(String modifier) - { + public LabelLayout(String modifier) { this.modifier = modifier; } - public void add(Offset offset, Offset hotspot) - { + public void add(Offset offset, Offset hotspot) { this.offsets.add(new OffsetPair(offset, hotspot)); } - public String getModifier() - { + public String getModifier() { return modifier; } - public List getOffsets() - { + public List getOffsets() { return this.offsets; } } - public static class OffsetPair - { + public static class OffsetPair { + public Offset offset; public Offset hotSpot; - public OffsetPair(Offset offset, Offset hotSpot) - { + public OffsetPair(Offset offset, Offset hotSpot) { this.offset = offset; this.hotSpot = hotSpot; } @@ -103,8 +101,7 @@ public OffsetPair(Offset offset, Offset hotSpot) * * @param sidc Code that identifies the graphic. */ - public TacticalGraphicSymbol(String sidc) - { + public TacticalGraphicSymbol(String sidc) { super(); init(sidc); } @@ -114,13 +111,12 @@ public TacticalGraphicSymbol(String sidc) * where this symbol is drawn on the globe. The position's altitude component is interpreted according to the * altitudeMode. * - * @param sidc Code that identifies the graphic. + * @param sidc Code that identifies the graphic. * @param position The latitude, longitude, and altitude where the symbol is drawn. * * @throws IllegalArgumentException if the position is null. */ - public TacticalGraphicSymbol(String sidc, Position position) - { + public TacticalGraphicSymbol(String sidc, Position position) { super(position); init(sidc); } @@ -132,8 +128,7 @@ public TacticalGraphicSymbol(String sidc, Position position) * * @see #setStatus(String) */ - public String getStatus() - { + public String getStatus() { return this.symbolCode.getStatus(); } @@ -154,19 +149,16 @@ public String getStatus() * @param value the new value for the Status/Operational Condition field. * * @throws IllegalArgumentException if the specified value is null or is not one of the accepted status - * values. + * values. */ - public void setStatus(String value) - { - if (value == null) - { + public void setStatus(String value) { + if (value == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!SymbologyConstants.STATUS_ALL.contains(value.toUpperCase())) - { + if (!SymbologyConstants.STATUS_ALL.contains(value.toUpperCase())) { String msg = Logging.getMessage("Symbology.InvalidStatus", value); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -180,8 +172,7 @@ public void setStatus(String value) * * @param sidc Code that identifies the graphic. */ - protected void init(String sidc) - { + protected void init(String sidc) { this.symbolCode = new SymbolCode(sidc); this.maskedSymbolCode = this.symbolCode.toMaskedString(); @@ -190,7 +181,7 @@ protected void init(String sidc) // Configure this tactical point graphic's icon retriever and modifier retriever with either the // configuration value or the default value (in that order of precedence). String iconRetrieverPath = Configuration.getStringValue(AVKey.MIL_STD_2525_ICON_RETRIEVER_PATH, - MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); + MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); this.setIconRetriever(new MilStd2525PointGraphicRetriever(iconRetrieverPath)); Offset offset = defaultOffsets.get(this.symbolCode.toMaskedString()); @@ -208,43 +199,39 @@ protected void init(String sidc) this.setUnitsFormat(MilStd2525TacticalSymbol.DEFAULT_UNITS_FORMAT); } - /** {@inheritDoc} */ - public String getIdentifier() - { + /** + * {@inheritDoc} + */ + public String getIdentifier() { return this.symbolCode.toString(); } @Override - protected int getMaxLabelLines(AVList modifiers) - { + protected int getMaxLabelLines(AVList modifiers) { return DEFAULT_LABEL_LINES; } @Override - protected void applyImplicitModifiers(AVList modifiers) - { + protected void applyImplicitModifiers(AVList modifiers) { String si = this.symbolCode.getStandardIdentity(); // If this symbol represents a hostile entity, and the "hostile/enemy" indicator is enabled, then set the // hostile modifier to "ENY". boolean isHostile = SymbologyConstants.STANDARD_IDENTITY_HOSTILE.equalsIgnoreCase(si) - || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(si) - || SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(si) - || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(si); - if (!modifiers.hasKey(SymbologyConstants.HOSTILE_ENEMY) && this.isShowHostileIndicator() && isHostile) - { + || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(si) + || SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(si) + || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(si); + if (!modifiers.hasKey(SymbologyConstants.HOSTILE_ENEMY) && this.isShowHostileIndicator() && isHostile) { modifiers.setValue(SymbologyConstants.HOSTILE_ENEMY, SymbologyConstants.HOSTILE_ENEMY); } // Determine location, if location modifier is enabled. - if (!modifiers.hasKey(SymbologyConstants.LOCATION) && this.isShowLocation()) - { + if (!modifiers.hasKey(SymbologyConstants.LOCATION) && this.isShowLocation()) { modifiers.setValue(SymbologyConstants.LOCATION, this.getFormattedPosition()); } // Determine altitude, if location modifier is enabled. - if (!modifiers.hasKey(SymbologyConstants.ALTITUDE_DEPTH) && this.isShowLocation()) - { + if (!modifiers.hasKey(SymbologyConstants.ALTITUDE_DEPTH) && this.isShowLocation()) { Position position = this.getPosition(); UnitsFormat format = this.getUnitsFormat(); @@ -252,53 +239,53 @@ protected void applyImplicitModifiers(AVList modifiers) // the altitude using the active units format, and append the datum. See MIL-STD-2525C section 5.5.2.5.2 (pg. 41). String altitude; int altitudeMode = this.getAltitudeMode(); - if (altitudeMode == WorldWind.CLAMP_TO_GROUND) + if (altitudeMode == WorldWind.CLAMP_TO_GROUND) { altitude = "GL"; - else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) + } else if (altitudeMode == WorldWind.RELATIVE_TO_GROUND) { altitude = format.eyeAltitude(position.getElevation()) + " AGL"; - else + } else { altitude = format.eyeAltitude(position.getElevation()) + " AMSL"; + } modifiers.setValue(SymbologyConstants.ALTITUDE_DEPTH, altitude); } - if (!modifiers.hasKey(SymbologyConstants.TYPE)) - { - if (TacGrpSidc.MOBSU_CBRN_REEVNT_BIO.equalsIgnoreCase(this.maskedSymbolCode)) + if (!modifiers.hasKey(SymbologyConstants.TYPE)) { + if (TacGrpSidc.MOBSU_CBRN_REEVNT_BIO.equalsIgnoreCase(this.maskedSymbolCode)) { modifiers.setValue(SymbologyConstants.TYPE, "BIO"); - else if (TacGrpSidc.MOBSU_CBRN_REEVNT_CML.equalsIgnoreCase(this.maskedSymbolCode)) + } else if (TacGrpSidc.MOBSU_CBRN_REEVNT_CML.equalsIgnoreCase(this.maskedSymbolCode)) { modifiers.setValue(SymbologyConstants.TYPE, "CML"); + } } } /** * Layout text and graphic modifiers around the symbol. * - * @param dc Current draw context. + * @param dc Current draw context. * @param modifiers Modifiers applied to this graphic. */ @Override - protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { this.currentLabels.clear(); Font font = this.getActiveAttributes().getTextModifierFont(); List allLayouts = this.getLayouts(this.symbolCode.toMaskedString()); - for (LabelLayout layout : allLayouts) - { + for (LabelLayout layout : allLayouts) { java.util.List offsets = layout.offsets; - if (WWUtil.isEmpty(offsets)) + if (WWUtil.isEmpty(offsets)) { continue; + } Object value = modifiers.getValue(layout.modifier); - if (WWUtil.isEmpty(value)) + if (WWUtil.isEmpty(value)) { continue; + } // If we're retrieving the date modifier, maybe add a hyphen to the first value to indicate a date range. - if (SymbologyConstants.DATE_TIME_GROUP.equals(layout.modifier) && (value instanceof Iterable)) - { + if (SymbologyConstants.DATE_TIME_GROUP.equals(layout.modifier) && (value instanceof Iterable)) { value = this.addHyphenToDateRange((Iterable) value, offsets); } @@ -306,12 +293,9 @@ protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymb // Some graphics support multiple instances of the same modifier. Handle this case differently than the // single instance case. - if (value instanceof Iterable) - { + if (value instanceof Iterable) { this.layoutMultiLabel(dc, font, offsets, (Iterable) value, mode, osym); - } - else if (value != null) - { + } else if (value != null) { this.layoutLabel(dc, font, layout.offsets.get(0), value.toString(), mode, osym); } } @@ -324,30 +308,28 @@ else if (value != null) * * @return List of label layouts for the specified symbol. */ - protected List getLayouts(String sidc) - { + protected List getLayouts(String sidc) { return defaultLayouts.get(sidc); } @Override - protected void layoutDynamicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutDynamicModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { this.currentLines.clear(); - if (!this.isShowGraphicModifiers()) + if (!this.isShowGraphicModifiers()) { return; + } // Direction of Movement indicator. Placed at the bottom of the symbol layout. Direction of Movement applies // only to CBRN graphics (see MIL-STD-2525C table XI, pg. 38). Object o = modifiers.getValue(SymbologyConstants.DIRECTION_OF_MOVEMENT); - if (this.isShowDirectionOfMovement() && o instanceof Angle) - { + if (this.isShowDirectionOfMovement() && o instanceof Angle) { // The length of the direction of movement line is equal to the height of the symbol frame. See // MIL-STD-2525C section 5.3.4.1.c, page 33. double length = this.iconRect.getHeight(); java.util.List points = MilStd2525Util.computeGroundHeadingIndicatorPoints(dc, - osym.placePoint, (Angle) o, length, this.iconRect.getHeight()); + osym.placePoint, (Angle) o, length, this.iconRect.getHeight()); this.addLine(dc, BELOW_BOTTOM_CENTER_OFFSET, points, LAYOUT_RELATIVE, points.size() - 1, osym); } } @@ -355,22 +337,21 @@ protected void layoutDynamicModifiers(DrawContext dc, AVList modifiers, OrderedS ////////////////////////////////////////////// // Modifier layout ////////////////////////////////////////////// - /** * Add a hyphen to the first element in a list of dates to indicate a date range. This method only modifiers the * date list if exactly two dates are displayed in the graphic. * - * @param value Iterable of date modifiers. + * @param value Iterable of date modifiers. * @param offsets Layouts for the date modifiers. * * @return Iterable of modified dates. This may be a new, modified list, or the same list as {@code value} if no - * modification was required. + * modification was required. */ - protected Iterable addHyphenToDateRange(Iterable value, java.util.List offsets) - { + protected Iterable addHyphenToDateRange(Iterable value, java.util.List offsets) { // Only add a hyphen if exactly two dates are displayed in the graphic. - if (offsets.size() != 2) + if (offsets.size() != 2) { return value; + } // Make sure that two date values are provided. Iterator iterator = value.iterator(); @@ -379,34 +360,28 @@ protected Iterable addHyphenToDateRange(Iterable value, java.util.List layouts, Iterable values, - String mode, OrderedSymbol osym) - { + String mode, OrderedSymbol osym) { Iterator valueIterator = values.iterator(); Iterator layoutIterator = layouts.iterator(); - while (layoutIterator.hasNext() && valueIterator.hasNext()) - { + while (layoutIterator.hasNext() && valueIterator.hasNext()) { OffsetPair layout = layoutIterator.next(); Object value = valueIterator.next(); - if (value != null) - { + if (value != null) { this.layoutLabel(dc, font, layout, value.toString(), mode, osym); } } @@ -414,31 +389,28 @@ protected void layoutMultiLabel(DrawContext dc, Font font, java.util.List positions; - /** Globe used to compute geographic positions. */ + /** + * Globe used to compute geographic positions. + */ protected Globe globe; - /** Amplitude of the wave, in meters. */ + /** + * Amplitude of the wave, in meters. + */ protected double amplitude; - /** Wavelength, as a geographic angle. */ + /** + * Wavelength, as a geographic angle. + */ protected Angle halfWaveLength; - /** Current position. */ + /** + * Current position. + */ protected Position thisPosition; - /** Position of the next control point. */ + /** + * Position of the next control point. + */ protected Position nextControlPosition; - /** First position along the line. */ + /** + * First position along the line. + */ protected Position firstPosition; - /** End position for the current wave. */ + /** + * End position for the current wave. + */ protected Position waveEndPosition; - /** Distance (in meters) to the next wave start or end. */ + /** + * Distance (in meters) to the next wave start or end. + */ protected double thisStep; /** * Create a new iterator to compute the positions of a triangle wave. * - * @param positions Control positions for the triangle wave line. + * @param positions Control positions for the triangle wave line. * @param waveLength Distance (in meters) between waves. - * @param amplitude Amplitude (in meters) of the wave. This is the distance from the base line to the tip of each - * triangular wave. - * @param globe Globe used to compute geographic positions. + * @param amplitude Amplitude (in meters) of the wave. This is the distance from the base line to the tip of each + * triangular wave. + * @param globe Globe used to compute geographic positions. */ public TriangleWavePositionIterator(Iterable positions, double waveLength, double amplitude, - Globe globe) - { - if (positions == null) - { + Globe globe) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (waveLength <= 0 || amplitude <= 0) - { + if (waveLength <= 0 || amplitude <= 0) { String message = Logging.getMessage("generic.LengthIsInvalid"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -106,15 +129,17 @@ public TriangleWavePositionIterator(Iterable positions, doub this.nextControlPosition = this.thisPosition; } - /** {@inheritDoc} */ - public boolean hasNext() - { + /** + * {@inheritDoc} + */ + public boolean hasNext() { return this.nextControlPosition != null; } - /** {@inheritDoc} */ - public Position next() - { + /** + * {@inheritDoc} + */ + public Position next() { Position ret; // The iterator is implemented as a state machine. For each call to next() we return the appropriate @@ -132,9 +157,7 @@ public Position next() // Wave peak // | // Line - - switch (this.state) - { + switch (this.state) { // First call to the iterator. Just return the starting position. case STATE_FIRST: ret = this.thisPosition; @@ -195,42 +218,33 @@ public Position next() * * @return next position along the line. */ - protected Position computeNext() - { + protected Position computeNext() { Angle distToNext = LatLon.greatCircleDistance(this.thisPosition, this.nextControlPosition); double diff = distToNext.degrees - this.thisStep; - while (diff < 0) - { - if (this.positions.hasNext()) - { + while (diff < 0) { + if (this.positions.hasNext()) { this.thisPosition = this.nextControlPosition; this.nextControlPosition = this.positions.next(); // If we're drawing a line segment between waves then return the current control point and do not // transition states. We retain all of the control points between waves in order to keep the line // as close to the application's specification as possible. - if (this.state == STATE_LINE) - { + if (this.state == STATE_LINE) { this.thisStep -= distToNext.degrees; return this.thisPosition; } - } - // Handle a polygon that is not closed. - else if (this.firstPosition != null && !this.firstPosition.equals(this.nextControlPosition)) - { + } // Handle a polygon that is not closed. + else if (this.firstPosition != null && !this.firstPosition.equals(this.nextControlPosition)) { this.thisPosition = this.nextControlPosition; this.nextControlPosition = this.firstPosition; this.firstPosition = null; - if (this.state == STATE_LINE) - { + if (this.state == STATE_LINE) { this.thisStep -= distToNext.degrees; return this.thisPosition; } - } - else - { + } else { Position next = this.nextControlPosition; this.nextControlPosition = null; return next; @@ -248,8 +262,7 @@ else if (this.firstPosition != null && !this.firstPosition.equals(this.nextContr // Transition to the next state. If we were drawing a line we are now drawing a wave. If we were starting a // wave, we're now at the wave peak. - switch (this.state) - { + switch (this.state) { case STATE_LINE: this.state = STATE_WAVE_START; break; @@ -266,9 +279,10 @@ else if (this.firstPosition != null && !this.firstPosition.equals(this.nextContr return this.thisPosition; } - /** Not supported. */ - public void remove() - { + /** + * Not supported. + */ + public void remove() { throw new UnsupportedOperationException(); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AbstractCircularGraphic.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AbstractCircularGraphic.java index 6eb824ef1c..8aa0a979af 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AbstractCircularGraphic.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AbstractCircularGraphic.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.Position; @@ -21,8 +20,8 @@ * @version $Id: AbstractCircularGraphic.java 1171 2013-02-11 21:45:02Z dcollins $ */ public abstract class AbstractCircularGraphic extends AbstractMilStd2525TacticalGraphic - implements TacticalCircle, PreRenderable -{ + implements TacticalCircle, PreRenderable { + protected SurfaceCircle circle; /** @@ -30,35 +29,38 @@ public abstract class AbstractCircularGraphic extends AbstractMilStd2525Tactical * * @param sidc Symbol code the identifies the graphic. */ - public AbstractCircularGraphic(String sidc) - { + public AbstractCircularGraphic(String sidc) { super(sidc); this.circle = this.createShape(); } - /** {@inheritDoc} */ - public double getRadius() - { + /** + * {@inheritDoc} + */ + public double getRadius() { return this.circle.getRadius(); } - /** {@inheritDoc} */ - public void setRadius(double radius) - { + /** + * {@inheritDoc} + */ + public void setRadius(double radius) { this.circle.setRadius(radius); this.onModifierChanged(); this.reset(); } - /** {@inheritDoc} */ - public Position getPosition() - { + /** + * {@inheritDoc} + */ + public Position getPosition() { return this.getReferencePosition(); } - /** {@inheritDoc} */ - public void setPosition(Position position) - { + /** + * {@inheritDoc} + */ + public void setPosition(Position position) { this.moveTo(position); } @@ -66,20 +68,17 @@ public void setPosition(Position position) * {@inheritDoc} * * @param positions Control points. This graphic uses only one control point, which determines the center of the - * circle. + * circle. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Iterator iterator = positions.iterator(); - if (!iterator.hasNext()) - { + if (!iterator.hasNext()) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -89,43 +88,49 @@ public void setPositions(Iterable positions) this.reset(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.DISTANCE.equals(modifier) && (value instanceof Double)) + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.DISTANCE.equals(modifier) && (value instanceof Double)) { this.setRadius((Double) value); - else + } else { super.setModifier(modifier, value); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.DISTANCE.equals(modifier)) + public Object getModifier(String modifier) { + if (SymbologyConstants.DISTANCE.equals(modifier)) { return this.getRadius(); - else + } else { return super.getModifier(modifier); + } } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(new Position(this.circle.getCenter(), 0)); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.circle.getReferencePosition(); } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } @@ -139,8 +144,7 @@ public void preRender(DrawContext dc) * * @param dc Current draw context. */ - protected void doRenderGraphic(DrawContext dc) - { + protected void doRenderGraphic(DrawContext dc) { this.circle.render(dc); } @@ -148,41 +152,40 @@ protected void doRenderGraphic(DrawContext dc) * Invoked when the position or radius of the circle changes. This implementation does nothing, but subclasses can * override to invalid state when the graphic is changed. */ - protected void reset() - { + protected void reset() { // Do nothing, but allow subclasses to override. } - /** {@inheritDoc} Overridden to apply the delegate owner to shapes used to draw the circle. */ + /** + * {@inheritDoc} Overridden to apply the delegate owner to shapes used to draw the circle. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply the delegate owner to the circle, if an owner has been set. If no owner is set, make this graphic the // circle's owner. Object owner = this.getDelegateOwner(); - if (owner == null) + if (owner == null) { owner = this; + } this.circle.setDelegateOwner(owner); - if (this.labels != null) - { - for (TacticalGraphicLabel label : this.labels) - { + if (this.labels != null) { + for (TacticalGraphicLabel label : this.labels) { label.setDelegateOwner(owner); } } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { this.circle.setDelegateOwner(owner); } - protected SurfaceCircle createShape() - { + protected SurfaceCircle createShape() { SurfaceCircle circle = new SurfaceCircle(); circle.setDelegateOwner(this.getActiveDelegateOwner()); circle.setAttributes(this.activeShapeAttributes); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AbstractRectangularGraphic.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AbstractRectangularGraphic.java index 07897cfa36..d10a1bc0bb 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AbstractRectangularGraphic.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AbstractRectangularGraphic.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -20,8 +19,8 @@ * @author pabercrombie * @version $Id: AbstractRectangularGraphic.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AbstractRectangularGraphic extends AbstractMilStd2525TacticalGraphic implements TacticalQuad, PreRenderable -{ +public class AbstractRectangularGraphic extends AbstractMilStd2525TacticalGraphic implements TacticalQuad, PreRenderable { + protected Iterable positions; protected SurfaceQuad quad; @@ -32,35 +31,38 @@ public class AbstractRectangularGraphic extends AbstractMilStd2525TacticalGraphi * * @param sidc Symbol code the identifies the graphic. */ - public AbstractRectangularGraphic(String sidc) - { + public AbstractRectangularGraphic(String sidc) { super(sidc); this.quad = this.createShape(); } - /** {@inheritDoc} */ - public double getWidth() - { + /** + * {@inheritDoc} + */ + public double getWidth() { return this.quad.getHeight(); } - /** {@inheritDoc} */ - public void setWidth(double width) - { + /** + * {@inheritDoc} + */ + public void setWidth(double width) { //noinspection SuspiciousNameCombination this.quad.setHeight(width); this.onModifierChanged(); } - /** {@inheritDoc} */ - public double getLength() - { + /** + * {@inheritDoc} + */ + public double getLength() { return this.quad.getWidth(); } - /** {@inheritDoc} */ - public void setLength(double length) - { + /** + * {@inheritDoc} + */ + public void setLength(double length) { this.quad.setWidth(length); this.onModifierChanged(); } @@ -69,21 +71,18 @@ public void setLength(double length) * {@inheritDoc} * * @param positions Control points. This graphic uses only two control point, which determine the midpoints of two - * opposite sides of the quad. See Fire Support Area (2.X.4.3.2.1.2) on pg. 652 of MIL-STD-2525C - * for an example of how these points are interpreted. + * opposite sides of the quad. See Fire Support Area (2.X.4.3.2.1.2) on pg. 652 of MIL-STD-2525C for an example of + * how these points are interpreted. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Iterator iterator = positions.iterator(); - try - { + try { Position pos1 = iterator.next(); Position pos2 = iterator.next(); @@ -95,70 +94,66 @@ public void setPositions(Iterable positions) this.positions = positions; this.shapeInvalid = true; // Need to recompute quad size - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return this.positions; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.DISTANCE.equalsIgnoreCase(modifier)) - { - if (value instanceof Double) - { + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.DISTANCE.equalsIgnoreCase(modifier)) { + if (value instanceof Double) { this.setWidth((Double) value); - } - else if (value instanceof Iterable) - { + } else if (value instanceof Iterable) { // Only use the first value of the iterable. This graphic uses two control points and a width. Iterator iterator = ((Iterable) value).iterator(); this.setWidth((Double) iterator.next()); } - } - else - { + } else { super.setModifier(modifier, value); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.DISTANCE.equalsIgnoreCase(modifier)) + public Object getModifier(String modifier) { + if (SymbologyConstants.DISTANCE.equalsIgnoreCase(modifier)) { return this.getWidth(); - else + } else { return super.getModifier(modifier); + } } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.quad.getReferencePosition(); } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } - if (this.shapeInvalid) - { + if (this.shapeInvalid) { this.computeQuadSize(dc); this.shapeInvalid = false; } @@ -167,10 +162,10 @@ public void preRender(DrawContext dc) this.quad.preRender(dc); } - protected void computeQuadSize(DrawContext dc) - { - if (this.positions == null) + protected void computeQuadSize(DrawContext dc) { + if (this.positions == null) { return; + } Iterator iterator = this.positions.iterator(); @@ -188,22 +183,21 @@ protected void computeQuadSize(DrawContext dc) * * @param dc Current draw context. */ - protected void doRenderGraphic(DrawContext dc) - { + protected void doRenderGraphic(DrawContext dc) { this.quad.render(dc); } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { this.quad.setDelegateOwner(owner); } - protected SurfaceQuad createShape() - { + protected SurfaceQuad createShape() { SurfaceQuad quad = new SurfaceQuad(); quad.setDelegateOwner(this.getActiveDelegateOwner()); quad.setAttributes(this.getActiveShapeAttributes()); return quad; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AirfieldZone.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AirfieldZone.java index 45825960bb..0304f8f0a9 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AirfieldZone.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AirfieldZone.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.WorldWind; @@ -19,9 +18,11 @@ * @author pabercrombie * @version $Id: AirfieldZone.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AirfieldZone extends BasicArea -{ - /** Paths used to draw the airfield graphic. */ +public class AirfieldZone extends BasicArea { + + /** + * Paths used to draw the airfield graphic. + */ protected List airfieldPaths; /** @@ -29,32 +30,31 @@ public class AirfieldZone extends BasicArea * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_GNL_ARS_AIRFZ); } - public AirfieldZone(String sidc) - { + public AirfieldZone(String sidc) { super(sidc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setPositions(Iterable positions) - { + public void setPositions(Iterable positions) { super.setPositions(positions); this.airfieldPaths = null; // Need to regenerate } - /** {@inheritDoc} Overridden to draw airfield graphic. */ + /** + * {@inheritDoc} Overridden to draw airfield graphic. + */ @Override - protected void doRenderGraphic(DrawContext dc) - { + protected void doRenderGraphic(DrawContext dc) { super.doRenderGraphic(dc); - for (Path path : this.airfieldPaths) - { + for (Path path : this.airfieldPaths) { path.render(dc); } } @@ -65,8 +65,7 @@ protected void doRenderGraphic(DrawContext dc) * @return null, Airfield Zone does not support text modifiers. */ @Override - protected String createLabelText() - { + protected String createLabelText() { // Text modifier not supported return ""; } @@ -77,10 +76,8 @@ protected String createLabelText() * @param dc Current draw context. */ @Override - protected void makeShapes(DrawContext dc) - { - if (this.airfieldPaths == null) - { + protected void makeShapes(DrawContext dc) { + if (this.airfieldPaths == null) { this.airfieldPaths = this.createAirfieldPaths(dc); } } @@ -92,13 +89,11 @@ protected void makeShapes(DrawContext dc) * * @return List of Paths that make up the airfield graphic. */ - protected List createAirfieldPaths(DrawContext dc) - { + protected List createAirfieldPaths(DrawContext dc) { List paths = new ArrayList(); List sectors = this.polygon.getSectors(dc); - if (sectors == null) - { + if (sectors == null) { return Collections.emptyList(); } @@ -130,8 +125,7 @@ protected List createAirfieldPaths(DrawContext dc) * * @param path Path to configure. */ - protected void configurePath(Path path) - { + protected void configurePath(Path path) { path.setDelegateOwner(this); path.setFollowTerrain(true); path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Airhead.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Airhead.java index 9fc60ec05d..2546b8f368 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Airhead.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Airhead.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.avlist.AVKey; @@ -20,8 +19,8 @@ * @author pabercrombie * @version $Id: Airhead.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Airhead extends BasicArea -{ +public class Airhead extends BasicArea { + /** * Default offset to apply to the label. The default aligns the top center of the label with the label's geographic * position, in order to keep the text South of the area. @@ -33,8 +32,7 @@ public class Airhead extends BasicArea * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_SPL_ARA_AHD); } @@ -43,15 +41,13 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public Airhead(String sidc) - { + public Airhead(String sidc) { super(sidc); this.setShowHostileIndicator(false); } @Override - protected String createLabelText() - { + protected String createLabelText() { String text = this.getText(); StringBuilder sb = new StringBuilder(); @@ -59,8 +55,7 @@ protected String createLabelText() sb.append("AIRHEAD LINE\n"); sb.append("(PL "); - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { sb.append(text); } sb.append(")"); @@ -77,11 +72,11 @@ protected String createLabelText() * @return Position for the graphic's main label. */ @Override - protected Position determineMainLabelPosition(DrawContext dc) - { + protected Position determineMainLabelPosition(DrawContext dc) { Iterable locations = this.polygon.getLocations(); - if (locations == null) + if (locations == null) { return null; + } Sector sector = Sector.boundingSector(locations); @@ -92,10 +87,11 @@ protected Position determineMainLabelPosition(DrawContext dc) return new Position(minLat, avgLon, 0); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { return DEFAULT_OFFSET; } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Ambush.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Ambush.java index e6aa05d34a..103a2e7568 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Ambush.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Ambush.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.WorldWind; @@ -24,16 +23,20 @@ * @author pabercrombie * @version $Id: Ambush.java 1585 2013-09-06 00:12:52Z pabercrombie $ */ -public class Ambush extends AbstractMilStd2525TacticalGraphic -{ - /** Default length of the arrowhead, as a fraction of the total line length. */ +public class Ambush extends AbstractMilStd2525TacticalGraphic { + + /** + * Default length of the arrowhead, as a fraction of the total line length. + */ public final static double DEFAULT_ARROWHEAD_LENGTH = 0.2; /** * Default angle of the arc. Control points 2 and 3 define a chord of a circle. This chord and the arc angle fully * define the circle, of which the arc is a segment. */ public final static Angle DEFAULT_ARC_ANGLE = Angle.fromDegrees(60.0); - /** Default angle of the arrowhead. */ + /** + * Default angle of the arrowhead. + */ public final static Angle DEFAULT_ARROWHEAD_ANGLE = Angle.fromDegrees(70.0); /** * Default length of the legs of the graphic's base, as a fraction of the distance between the control points the @@ -41,20 +44,34 @@ public class Ambush extends AbstractMilStd2525TacticalGraphic */ public final static double DEFAULT_LEG_LENGTH = 0.5; - /** Default number of intervals used to draw the arc. */ + /** + * Default number of intervals used to draw the arc. + */ public final static int DEFAULT_NUM_INTERVALS = 32; - /** Default number of legs to draw on the graphic's arc. */ + /** + * Default number of legs to draw on the graphic's arc. + */ public final static int DEFAULT_NUM_LEGS = 6; - /** Number of intervals used to draw the arc. */ + /** + * Number of intervals used to draw the arc. + */ protected int intervals = DEFAULT_NUM_INTERVALS; - /** The arc is drawn as a segment of a circle intersected by this angle. */ + /** + * The arc is drawn as a segment of a circle intersected by this angle. + */ protected Angle arcAngle = DEFAULT_ARC_ANGLE; - /** Length of the arrowhead from base to tip, as a fraction of the total line length. */ + /** + * Length of the arrowhead from base to tip, as a fraction of the total line length. + */ protected Angle arrowAngle = DEFAULT_ARROWHEAD_ANGLE; - /** Angle of the arrowhead. */ + /** + * Angle of the arrowhead. + */ protected double arrowLength = DEFAULT_ARROWHEAD_LENGTH; - /** Number of "legs" drawn on this graphic's arc. */ + /** + * Number of "legs" drawn on this graphic's arc. + */ protected int numLegs = DEFAULT_NUM_LEGS; /** * Length of the legs on the graphic's base, as a fraction of the distance between the control points that define @@ -62,29 +79,45 @@ public class Ambush extends AbstractMilStd2525TacticalGraphic */ protected double legLength = DEFAULT_LEG_LENGTH; - /** First control point. */ + /** + * First control point. + */ protected Position position1; - /** Second control point. */ + /** + * Second control point. + */ protected Position position2; - /** Third control point. */ + /** + * Third control point. + */ protected Position position3; - /** Path used to render the graphic. */ + /** + * Path used to render the graphic. + */ protected Path[] paths; /** * Data required for intermediate calculations while generating the Ambush graphic. This object is created and * populated by {@link Ambush#computeArc(gov.nasa.worldwind.render.DrawContext)}. */ - protected static class ArcData - { - /** Position at the midpoint of the arc. This point falls on the arc. */ + protected static class ArcData { + + /** + * Position at the midpoint of the arc. This point falls on the arc. + */ Position midpoint; - /** Center of the circle, of which the arc is segment. */ + /** + * Center of the circle, of which the arc is segment. + */ LatLon center; - /** Radius of the circle. */ + /** + * Radius of the circle. + */ double radius; - /** Angle from North at which the arc begins. */ + /** + * Angle from North at which the arc begins. + */ Angle startAngle; /** * Angular length of the arc. Note that this is different than {@link Ambush#arcAngle}: this angle is signed, @@ -92,7 +125,9 @@ protected static class ArcData * {@code arcData.arcAngle + arcData.startAngle}. */ Angle arcAngle; - /** Direction of the arc. This vector points from the center of the circle to the midpoint of the arc. */ + /** + * Direction of the arc. This vector points from the center of the circle to the midpoint of the arc. + */ Vec4 direction; } @@ -101,8 +136,7 @@ protected static class ArcData * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_SPL_LNE_AMB); } @@ -111,8 +145,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public Ambush(String sidc) - { + public Ambush(String sidc) { super(sidc); } @@ -121,8 +154,7 @@ public Ambush(String sidc) * * @return Intervals used to draw arc. */ - public int getIntervals() - { + public int getIntervals() { return this.intervals; } @@ -132,10 +164,8 @@ public int getIntervals() * * @param intervals Number of intervals for drawing the arc. */ - public void setIntervals(int intervals) - { - if (intervals < 1) - { + public void setIntervals(int intervals) { + if (intervals < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -151,8 +181,7 @@ public void setIntervals(int intervals) * * @return Angle of the circular segment that forms this graphic's arc. */ - public Angle getArcAngle() - { + public Angle getArcAngle() { return this.arcAngle; } @@ -163,10 +192,8 @@ public Angle getArcAngle() * * @param arcAngle Angle of the circular segment that forms this graphic's arc. */ - public void setArcAngle(Angle arcAngle) - { - if (arcAngle == null) - { + public void setArcAngle(Angle arcAngle) { + if (arcAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -180,8 +207,7 @@ public void setArcAngle(Angle arcAngle) * * @return Angle of the arrowhead in the graphic. */ - public Angle getArrowAngle() - { + public Angle getArrowAngle() { return this.arrowAngle; } @@ -190,17 +216,14 @@ public Angle getArrowAngle() * * @param arrowAngle The angle of the arrowhead. Must be greater than zero degrees and less than 90 degrees. */ - public void setArrowAngle(Angle arrowAngle) - { - if (arrowAngle == null) - { + public void setArrowAngle(Angle arrowAngle) { + if (arrowAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) - { + if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) { String msg = Logging.getMessage("generic.AngleOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -215,8 +238,7 @@ public void setArrowAngle(Angle arrowAngle) * * @return The length of the arrowhead as a fraction of the total line length. */ - public double getArrowLength() - { + public double getArrowLength() { return this.arrowLength; } @@ -224,12 +246,10 @@ public double getArrowLength() * Specifies the length of the arrowhead. * * @param arrowLength Length of the arrowhead as a fraction of the total line length. If the arrowhead length is - * 0.25, then the arrowhead length will be one quarter of the total line length. + * 0.25, then the arrowhead length will be one quarter of the total line length. */ - public void setArrowLength(double arrowLength) - { - if (arrowLength < 0) - { + public void setArrowLength(double arrowLength) { + if (arrowLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -244,8 +264,7 @@ public void setArrowLength(double arrowLength) * * @return Number of legs drawn on the arc of this graphic. */ - public int getLegs() - { + public int getLegs() { return this.numLegs; } @@ -254,10 +273,8 @@ public int getLegs() * * @param numLegs Number of legs to draw on the arc of this graphic. */ - public void setLegs(int numLegs) - { - if (numLegs < 0) - { + public void setLegs(int numLegs) { + if (numLegs < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -271,10 +288,9 @@ public void setLegs(int numLegs) * Indicates the length of legs on the graphic's base. * * @return The length of the legs on the base, as a fraction of the distance between the control points that define - * the base. + * the base. */ - public double getLegLength() - { + public double getLegLength() { return this.legLength; } @@ -282,12 +298,10 @@ public double getLegLength() * Specifies the length of the legs on the graphic's base. * * @param legLength Length of the legs on the graphic's base, as a fraction of the distance between the control - * points that define the base. + * points that define the base. */ - public void setLegLength(double legLength) - { - if (legLength < 0) - { + public void setLegLength(double legLength) { + if (legLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -302,24 +316,19 @@ public void setLegLength(double legLength) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.position1 = iterator.next(); this.position2 = iterator.next(); this.position3 = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -328,46 +337,47 @@ public void setPositions(Iterable positions) this.onShapeChanged(); } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.position1, this.position2, this.position3); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.position1; } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - if (this.paths == null) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + if (this.paths == null) { this.createShapes(dc); } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths == null) { return; + } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.setDelegateOwner(owner); } } - protected void onShapeChanged() - { + protected void onShapeChanged() { this.paths = null; // Need to recompute paths } @@ -376,8 +386,7 @@ protected void onShapeChanged() * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { // This graphic requires three paths, plus one path for each of the legs. this.paths = new Path[3 + this.getLegs()]; @@ -406,8 +415,7 @@ protected void createShapes(DrawContext dc) * * @return Data that describes the arc. */ - protected ArcData computeArc(DrawContext dc) - { + protected ArcData computeArc(DrawContext dc) { Globe globe = dc.getGlobe(); // The graphic looks like this: @@ -418,7 +426,6 @@ protected ArcData computeArc(DrawContext dc) // | / // / // B / - Vec4 pA = globe.computePointFromPosition(this.position2); Vec4 pB = globe.computePointFromPosition(this.position3); @@ -461,17 +468,18 @@ protected ArcData computeArc(DrawContext dc) // Compute the angle between the start and end points. Note that we cannot use Angle.angularDistance because // we need a signed distance here. double diffDegrees = endAngle.subtract(arcData.startAngle).degrees; - if (diffDegrees < -180) + if (diffDegrees < -180) { diffDegrees += 360; - else if (diffDegrees > 180) + } else if (diffDegrees > 180) { diffDegrees -= 360; + } arcData.arcAngle = Angle.fromDegrees(diffDegrees); // Find the midpoint of the arc double globeRadius = globe.getRadiusAt(arcData.center.getLatitude(), arcData.center.getLongitude()); LatLon ll = LatLon.greatCircleEndPosition(arcData.center, - arcData.arcAngle.divide(2.0).radians + arcData.startAngle.radians, arcData.radius / globeRadius); + arcData.arcAngle.divide(2.0).radians + arcData.startAngle.radians, arcData.radius / globeRadius); arcData.midpoint = new Position(ll, 0); return arcData; @@ -480,13 +488,12 @@ else if (diffDegrees > 180) /** * Compute positions required to draw the arc. * - * @param dc Current draw context. + * @param dc Current draw context. * @param arcData Data that describes the arc. * * @return Positions along the arc. */ - protected List computeArcPositions(DrawContext dc, ArcData arcData) - { + protected List computeArcPositions(DrawContext dc, ArcData arcData) { Globe globe = dc.getGlobe(); Angle da = arcData.arcAngle.divide(this.intervals); @@ -497,8 +504,7 @@ protected List computeArcPositions(DrawContext dc, ArcData arcData) int intervals = this.getIntervals(); List positions = new ArrayList(intervals); - for (int i = 0; i < intervals; i++) - { + for (int i = 0; i < intervals; i++) { double angle = i * da.radians + arcData.startAngle.radians; LatLon ll = LatLon.greatCircleEndPosition(arcData.center, angle, radiusRadians); @@ -512,15 +518,14 @@ protected List computeArcPositions(DrawContext dc, ArcData arcData) /** * Create paths for the graphic's "legs". The legs stick out of the back side of the arc. * - * @param dc Current draw context. - * @param arcData Data that describes the graphic's arc. - * @param paths Array to receive the new paths. + * @param dc Current draw context. + * @param arcData Data that describes the graphic's arc. + * @param paths Array to receive the new paths. * @param startIndex Index into {@code paths} at which to place the first leg path. - * @param pathCount Number of leg paths to create. The {@code paths} array must have length of at least {@code + * @param pathCount Number of leg paths to create. The {@code paths} array must have length of at least {@code * startIndex + pathCount}. */ - protected void createLegs(DrawContext dc, ArcData arcData, Path[] paths, int startIndex, int pathCount) - { + protected void createLegs(DrawContext dc, ArcData arcData, Path[] paths, int startIndex, int pathCount) { Globe globe = dc.getGlobe(); Vec4 p1 = globe.computePointFromPosition(this.position1); @@ -533,7 +538,6 @@ protected void createLegs(DrawContext dc, ArcData arcData, Path[] paths, int sta // ___/ // / // ^ Legs^ - // The end point of each leg will be computed by adding an offset in the direction of the arrow to a point on // the arc. Vec4 vOffset = pMid.subtract3(p1); @@ -543,8 +547,7 @@ protected void createLegs(DrawContext dc, ArcData arcData, Path[] paths, int sta double globeRadius = globe.getRadiusAt(arcData.center.getLatitude(), arcData.center.getLongitude()); double radiusRadians = arcData.radius / globeRadius; - for (int i = 0; i < pathCount; i++) - { + for (int i = 0; i < pathCount; i++) { double angle = (i + 0.5) * da.radians + arcData.startAngle.radians; LatLon ll = LatLon.greatCircleEndPosition(arcData.center, angle, radiusRadians); @@ -559,14 +562,13 @@ protected void createLegs(DrawContext dc, ArcData arcData, Path[] paths, int sta /** * Determine the positions that make up the arrowhead. * - * @param dc Current draw context. - * @param tip Position of the arrow head tip. + * @param dc Current draw context. + * @param tip Position of the arrow head tip. * @param arcData Data that describes the arc of this graphic. * * @return Positions that define the arrowhead. */ - protected List computeArrowheadPositions(DrawContext dc, Position tip, ArcData arcData) - { + protected List computeArrowheadPositions(DrawContext dc, Position tip, ArcData arcData) { Globe globe = dc.getGlobe(); // _ // A\ | 1/2 width @@ -607,8 +609,7 @@ protected List computeArrowheadPositions(DrawContext dc, Position tip, * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(List positions) - { + protected Path createPath(List positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AttackByFirePosition.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AttackByFirePosition.java index aa1a6768f3..e60018901a 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AttackByFirePosition.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AttackByFirePosition.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.WorldWind; @@ -24,11 +23,15 @@ * @author pabercrombie * @version $Id: AttackByFirePosition.java 555 2012-04-25 18:59:29Z pabercrombie $ */ -public class AttackByFirePosition extends AbstractMilStd2525TacticalGraphic -{ - /** Default length of the arrowhead, as a fraction of the total line length. */ +public class AttackByFirePosition extends AbstractMilStd2525TacticalGraphic { + + /** + * Default length of the arrowhead, as a fraction of the total line length. + */ public final static double DEFAULT_ARROWHEAD_LENGTH = 0.2; - /** Default angle of the arrowhead. */ + /** + * Default angle of the arrowhead. + */ public final static Angle DEFAULT_ARROWHEAD_ANGLE = Angle.fromDegrees(70.0); /** * Default length of the legs of the graphic's base, as a fraction of the distance between the control points the @@ -36,9 +39,13 @@ public class AttackByFirePosition extends AbstractMilStd2525TacticalGraphic */ public final static double DEFAULT_LEG_LENGTH = 0.25; - /** Length of the arrowhead from base to tip, as a fraction of the total line length. */ + /** + * Length of the arrowhead from base to tip, as a fraction of the total line length. + */ protected Angle arrowAngle = DEFAULT_ARROWHEAD_ANGLE; - /** Angle of the arrowhead. */ + /** + * Angle of the arrowhead. + */ protected double arrowLength = DEFAULT_ARROWHEAD_LENGTH; /** * Length of the legs on the graphic's base, as a fraction of the distance between the control points that define @@ -46,14 +53,22 @@ public class AttackByFirePosition extends AbstractMilStd2525TacticalGraphic */ protected double legLength = DEFAULT_LEG_LENGTH; - /** First control point. */ + /** + * First control point. + */ protected Position position1; - /** Second control point. */ + /** + * Second control point. + */ protected Position position2; - /** Third control point. */ + /** + * Third control point. + */ protected Position position3; - /** Path used to render the graphic. */ + /** + * Path used to render the graphic. + */ protected Path[] paths; /** @@ -61,8 +76,7 @@ public class AttackByFirePosition extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_ARS_AFP); } @@ -71,8 +85,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public AttackByFirePosition(String sidc) - { + public AttackByFirePosition(String sidc) { super(sidc); } @@ -81,8 +94,7 @@ public AttackByFirePosition(String sidc) * * @return Angle of the arrowhead in the graphic. */ - public Angle getArrowAngle() - { + public Angle getArrowAngle() { return this.arrowAngle; } @@ -91,17 +103,14 @@ public Angle getArrowAngle() * * @param arrowAngle The angle of the arrowhead. Must be greater than zero degrees and less than 90 degrees. */ - public void setArrowAngle(Angle arrowAngle) - { - if (arrowAngle == null) - { + public void setArrowAngle(Angle arrowAngle) { + if (arrowAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) - { + if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) { String msg = Logging.getMessage("generic.AngleOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -115,8 +124,7 @@ public void setArrowAngle(Angle arrowAngle) * * @return The length of the arrowhead as a fraction of the total line length. */ - public double getArrowLength() - { + public double getArrowLength() { return this.arrowLength; } @@ -124,12 +132,10 @@ public double getArrowLength() * Specifies the length of the arrowhead. * * @param arrowLength Length of the arrowhead as a fraction of the total line length. If the arrowhead length is - * 0.25, then the arrowhead length will be one quarter of the total line length. + * 0.25, then the arrowhead length will be one quarter of the total line length. */ - public void setArrowLength(double arrowLength) - { - if (arrowLength < 0) - { + public void setArrowLength(double arrowLength) { + if (arrowLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -142,10 +148,9 @@ public void setArrowLength(double arrowLength) * Indicates the length of legs of the graphic's base. * * @return The length of the legs of the base, as a fraction of the distance between the control points that define - * the base. + * the base. */ - public double getLegLength() - { + public double getLegLength() { return this.arrowLength; } @@ -153,12 +158,10 @@ public double getLegLength() * Specifies the length of the legs of the graphic's base. * * @param legLength Length of the legs of the graphic's base, as a fraction of the distance between the control - * points that define the base. + * points that define the base. */ - public void setLegLength(double legLength) - { - if (legLength < 0) - { + public void setLegLength(double legLength) { + if (legLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -172,24 +175,19 @@ public void setLegLength(double legLength) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.position1 = iterator.next(); this.position2 = iterator.next(); this.position3 = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -198,40 +196,42 @@ public void setPositions(Iterable positions) this.paths = null; // Need to recompute path for the new control points } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.position1, this.position2, this.position3); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.position1; } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - if (this.paths == null) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + if (this.paths == null) { this.createShapes(dc); } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths == null) { return; + } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.setDelegateOwner(owner); } } @@ -241,8 +241,7 @@ protected void applyDelegateOwner(Object owner) * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { this.paths = new Path[3]; Position baseMidpoint = new Position(LatLon.interpolate(0.5, this.position2, this.position3), 0); @@ -261,17 +260,16 @@ protected void createShapes(DrawContext dc) /** * Determine the positions that make up the base of the graphic (a trapezoid missing one side). * - * @param dc Current draw context. - * @param position1 The first control point that defines the graphic base. - * @param position2 The second control point that defines the graphic base. + * @param dc Current draw context. + * @param position1 The first control point that defines the graphic base. + * @param position2 The second control point that defines the graphic base. * @param orientationPos A point on the arrow head side of the graphic. The legs of the base will point away from - * this position. + * this position. * * @return Positions that define the graphic's base. */ protected List computeBasePositions(DrawContext dc, Position position1, Position position2, - Position orientationPos) - { + Position orientationPos) { Globe globe = dc.getGlobe(); // A \ // \ @@ -323,14 +321,13 @@ protected List computeBasePositions(DrawContext dc, Position position1 /** * Determine the positions that make up the arrowhead. * - * @param dc Current draw context. + * @param dc Current draw context. * @param base Position of the arrow's starting point. - * @param tip Position of the arrow head tip. + * @param tip Position of the arrow head tip. * * @return Positions that define the arrowhead. */ - protected List computeArrowheadPositions(DrawContext dc, Position base, Position tip) - { + protected List computeArrowheadPositions(DrawContext dc, Position base, Position tip) { Globe globe = dc.getGlobe(); // _ // A\ | 1/2 width @@ -375,8 +372,7 @@ protected List computeArrowheadPositions(DrawContext dc, Position base * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(List positions) - { + protected Path createPath(List positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AviationZone.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AviationZone.java index f97347d2eb..838508efed 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AviationZone.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AviationZone.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.avlist.AVKey; @@ -23,9 +22,11 @@ * @author pabercrombie * @version $Id: AviationZone.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AviationZone extends BasicArea -{ - /** Center text block on label position. */ +public class AviationZone extends BasicArea { + + /** + * Center text block on label position. + */ protected final static Offset LABEL_OFFSET = new Offset(-0.5d, -0.5d, AVKey.FRACTION, AVKey.FRACTION); /** @@ -33,15 +34,14 @@ public class AviationZone extends BasicArea * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_AVN_ARS_ROZ, - TacGrpSidc.C2GM_AVN_ARS_SHRDEZ, - TacGrpSidc.C2GM_AVN_ARS_HIDACZ, - TacGrpSidc.C2GM_AVN_ARS_MEZ, - TacGrpSidc.C2GM_AVN_ARS_MEZ_LAMEZ, - TacGrpSidc.C2GM_AVN_ARS_MEZ_HAMEZ); + TacGrpSidc.C2GM_AVN_ARS_ROZ, + TacGrpSidc.C2GM_AVN_ARS_SHRDEZ, + TacGrpSidc.C2GM_AVN_ARS_HIDACZ, + TacGrpSidc.C2GM_AVN_ARS_MEZ, + TacGrpSidc.C2GM_AVN_ARS_MEZ_LAMEZ, + TacGrpSidc.C2GM_AVN_ARS_MEZ_HAMEZ); } /** @@ -49,28 +49,24 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public AviationZone(String sidc) - { + public AviationZone(String sidc) { super(sidc); // Do not draw "ENY" labels on hostile entities. this.setShowHostileIndicator(false); } @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { return LABEL_OFFSET; } @Override - protected String getLabelAlignment() - { + protected String getLabelAlignment() { return AVKey.LEFT; } @Override - protected String createLabelText() - { + protected String createLabelText() { return doCreateLabelText(true); } @@ -78,36 +74,30 @@ protected String createLabelText() * Create text for the area's label. * * @param includeAltitude Indicates whether to include altitude information in the label (if the - * SymbologyConstants.ALTITUDE_DEPTH modifier is set). Not all aviation area graphics support - * the altitude modifier. + * SymbologyConstants.ALTITUDE_DEPTH modifier is set). Not all aviation area graphics support the altitude modifier. * * @return Text for the label, based on the active modifiers. */ - protected String doCreateLabelText(boolean includeAltitude) - { + protected String doCreateLabelText(boolean includeAltitude) { StringBuilder sb = new StringBuilder(); sb.append(this.getGraphicLabel()); sb.append("\n"); Object o = this.getModifier(SymbologyConstants.UNIQUE_DESIGNATION); - if (o != null) - { + if (o != null) { sb.append(o); sb.append("\n"); } - if (includeAltitude) - { + if (includeAltitude) { Object[] altitudes = TacticalGraphicUtil.getAltitudeRange(this); - if (altitudes[0] != null) - { + if (altitudes[0] != null) { sb.append("MIN ALT: "); sb.append(altitudes[0]); sb.append("\n"); } - if (altitudes[1] != null) - { + if (altitudes[1] != null) { sb.append("MAX ALT: "); sb.append(altitudes[1]); sb.append("\n"); @@ -115,15 +105,13 @@ protected String doCreateLabelText(boolean includeAltitude) } Object[] dates = TacticalGraphicUtil.getDateRange(this); - if (dates[0] != null) - { + if (dates[0] != null) { sb.append("TIME FROM: "); sb.append(dates[0]); sb.append("\n"); } - if (dates[1] != null) - { + if (dates[1] != null) { sb.append("TIME TO: "); sb.append(dates[1]); } @@ -132,22 +120,22 @@ protected String doCreateLabelText(boolean includeAltitude) } @Override - protected String getGraphicLabel() - { + protected String getGraphicLabel() { String code = this.maskedSymbolCode; - if (TacGrpSidc.C2GM_AVN_ARS_ROZ.equalsIgnoreCase(code)) + if (TacGrpSidc.C2GM_AVN_ARS_ROZ.equalsIgnoreCase(code)) { return "ROZ"; - else if (TacGrpSidc.C2GM_AVN_ARS_SHRDEZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_ARS_SHRDEZ.equalsIgnoreCase(code)) { return "SHORADEZ"; - else if (TacGrpSidc.C2GM_AVN_ARS_HIDACZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_ARS_HIDACZ.equalsIgnoreCase(code)) { return "HIDACZ"; - else if (TacGrpSidc.C2GM_AVN_ARS_MEZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_ARS_MEZ.equalsIgnoreCase(code)) { return "MEZ"; - else if (TacGrpSidc.C2GM_AVN_ARS_MEZ_LAMEZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_ARS_MEZ_LAMEZ.equalsIgnoreCase(code)) { return "LOMEZ"; - else if (TacGrpSidc.C2GM_AVN_ARS_MEZ_HAMEZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_ARS_MEZ_HAMEZ.equalsIgnoreCase(code)) { return "HIMEZ"; + } return ""; } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/BasicArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/BasicArea.java index ce2cca7317..57f64292f1 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/BasicArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/BasicArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.avlist.AVKey; @@ -25,13 +24,17 @@ * @author pabercrombie * @version $Id: BasicArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicArea extends AbstractMilStd2525TacticalGraphic implements PreRenderable -{ +public class BasicArea extends AbstractMilStd2525TacticalGraphic implements PreRenderable { + protected SurfacePolygon polygon; - /** First "ENY" label, for hostile entities. */ + /** + * First "ENY" label, for hostile entities. + */ protected TacticalGraphicLabel identityLabel1; - /** Second "ENY" label, for hostile entities. */ + /** + * Second "ENY" label, for hostile entities. + */ protected TacticalGraphicLabel identityLabel2; /** @@ -39,64 +42,64 @@ public class BasicArea extends AbstractMilStd2525TacticalGraphic implements PreR * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_GNL_ARS_GENARA, - TacGrpSidc.C2GM_GNL_ARS_ABYARA, - TacGrpSidc.C2GM_GNL_ARS_EMTARA, - TacGrpSidc.C2GM_GNL_ARS_EZ, - TacGrpSidc.C2GM_GNL_ARS_LZ, - TacGrpSidc.C2GM_GNL_ARS_PZ, - TacGrpSidc.C2GM_GNL_ARS_DRPZ, - TacGrpSidc.C2GM_DEF_ARS_EMTARA); + TacGrpSidc.C2GM_GNL_ARS_GENARA, + TacGrpSidc.C2GM_GNL_ARS_ABYARA, + TacGrpSidc.C2GM_GNL_ARS_EMTARA, + TacGrpSidc.C2GM_GNL_ARS_EZ, + TacGrpSidc.C2GM_GNL_ARS_LZ, + TacGrpSidc.C2GM_GNL_ARS_PZ, + TacGrpSidc.C2GM_GNL_ARS_DRPZ, + TacGrpSidc.C2GM_DEF_ARS_EMTARA); } - public BasicArea(String sidc) - { + public BasicArea(String sidc) { super(sidc); this.polygon = this.createPolygon(); } - /** {@inheritDoc} */ - public void setPositions(Iterable positions) - { + /** + * {@inheritDoc} + */ + public void setPositions(Iterable positions) { this.polygon.setLocations(positions); } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { Iterable locations = this.polygon.getLocations(); ArrayList positions = new ArrayList(); - if (locations == null) - { + if (locations == null) { return null; } - for (LatLon ll : locations) - { - if (ll instanceof Position) + for (LatLon ll : locations) { + if (ll instanceof Position) { positions.add((Position) ll); - else + } else { positions.add(new Position(ll, 0)); + } } return positions; } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.polygon.getReferencePosition(); } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } @@ -107,8 +110,7 @@ public void preRender(DrawContext dc) this.polygon.preRender(dc); } - protected void makeShapes(DrawContext dc) - { + protected void makeShapes(DrawContext dc) { // Do nothing, but allow subclasses to override } @@ -117,8 +119,7 @@ protected void makeShapes(DrawContext dc) * * @param dc Current draw context. */ - protected void doRenderGraphic(DrawContext dc) - { + protected void doRenderGraphic(DrawContext dc) { this.polygon.render(dc); } @@ -127,49 +128,45 @@ protected void doRenderGraphic(DrawContext dc) * * @return Text for the main label. May return null if there is no text. */ - protected String createLabelText() - { + protected String createLabelText() { String label = this.getGraphicLabel(); String text = this.getText(); - if (label == null && text == null) - { + if (label == null && text == null) { return null; } StringBuilder sb = new StringBuilder(); - if (!WWUtil.isEmpty(label)) - { + if (!WWUtil.isEmpty(label)) { sb.append(label).append("\n"); } - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { sb.append(text); } return sb.toString(); } - protected String getGraphicLabel() - { + protected String getGraphicLabel() { String code = this.maskedSymbolCode; - if (TacGrpSidc.C2GM_GNL_ARS_GENARA.equalsIgnoreCase(code)) + if (TacGrpSidc.C2GM_GNL_ARS_GENARA.equalsIgnoreCase(code)) { return ""; - else if (TacGrpSidc.C2GM_GNL_ARS_ABYARA.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_GNL_ARS_ABYARA.equalsIgnoreCase(code)) { return "AA"; - else if (TacGrpSidc.C2GM_GNL_ARS_DRPZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_GNL_ARS_DRPZ.equalsIgnoreCase(code)) { return "DZ"; - else if (TacGrpSidc.C2GM_GNL_ARS_EMTARA.equalsIgnoreCase( - code) || TacGrpSidc.C2GM_DEF_ARS_EMTARA.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_GNL_ARS_EMTARA.equalsIgnoreCase( + code) || TacGrpSidc.C2GM_DEF_ARS_EMTARA.equalsIgnoreCase(code)) { return "EA"; - else if (TacGrpSidc.C2GM_GNL_ARS_EZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_GNL_ARS_EZ.equalsIgnoreCase(code)) { return "EZ"; - else if (TacGrpSidc.C2GM_GNL_ARS_LZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_GNL_ARS_LZ.equalsIgnoreCase(code)) { return "LZ"; - else if (TacGrpSidc.C2GM_GNL_ARS_PZ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_GNL_ARS_PZ.equalsIgnoreCase(code)) { return "PZ"; + } return ""; } @@ -179,25 +176,21 @@ else if (TacGrpSidc.C2GM_GNL_ARS_PZ.equalsIgnoreCase(code)) * * @return Alignment for the main label. One of AVKey.CENTER, AVKey.LEFT, or AVKey.RIGHT. */ - protected String getLabelAlignment() - { + protected String getLabelAlignment() { return AVKey.CENTER; } @Override - protected void createLabels() - { + protected void createLabels() { String labelText = this.createLabelText(); - if (!WWUtil.isEmpty(labelText)) - { + if (!WWUtil.isEmpty(labelText)) { TacticalGraphicLabel mainLabel = this.addLabel(labelText); mainLabel.setTextAlign(this.getLabelAlignment()); mainLabel.setOffset(this.getDefaultLabelOffset()); } - if (this.mustShowHostileIndicator()) - { + if (this.mustShowHostileIndicator()) { this.identityLabel1 = this.addLabel(SymbologyConstants.HOSTILE_ENEMY); this.identityLabel2 = this.addLabel(SymbologyConstants.HOSTILE_ENEMY); } @@ -209,16 +202,15 @@ protected void createLabels() * @param dc Current draw context. */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (this.labels == null || this.labels.isEmpty()) + protected void determineLabelPositions(DrawContext dc) { + if (this.labels == null || this.labels.isEmpty()) { return; + } Position mainLabelPosition = this.determineMainLabelPosition(dc); this.labels.get(0).setPosition(mainLabelPosition); - if (this.mustShowHostileIndicator()) - { + if (this.mustShowHostileIndicator()) { this.determineIdentityLabelPositions(); } } @@ -231,11 +223,9 @@ protected void determineLabelPositions(DrawContext dc) * * @return Position for the graphic's main label. */ - protected Position determineMainLabelPosition(DrawContext dc) - { + protected Position determineMainLabelPosition(DrawContext dc) { List sectors = this.polygon.getSectors(dc); - if (sectors != null) - { + if (sectors != null) { // TODO: centroid of bounding sector is not always a good choice for label position Sector sector = sectors.get(0); return new Position(sector.getCentroid(), 0); @@ -243,16 +233,14 @@ protected Position determineMainLabelPosition(DrawContext dc) return this.getReferencePosition(); } - protected void determineIdentityLabelPositions() - { + protected void determineIdentityLabelPositions() { // Position the first label between the first and second control points. Iterator iterator = this.getPositions().iterator(); Position first = iterator.next(); Position second = iterator.next(); LatLon midpoint = LatLon.interpolate(0.5, first, second); - if (this.identityLabel1 != null) - { + if (this.identityLabel1 != null) { this.identityLabel1.setPosition(new Position(midpoint, 0)); } @@ -260,38 +248,34 @@ protected void determineIdentityLabelPositions() // points are more or less evenly distributed, this will be about half way around the shape. int count = this.getPositionCount(); iterator = this.getPositions().iterator(); - for (int i = 0; i < count / 2 + 1; i++) - { + for (int i = 0; i < count / 2 + 1; i++) { first = iterator.next(); } second = iterator.next(); midpoint = LatLon.interpolate(0.5, first, second); - if (this.identityLabel2 != null) - { + if (this.identityLabel2 != null) { this.identityLabel2.setPosition(new Position(midpoint, 0)); } } - protected int getPositionCount() - { + protected int getPositionCount() { int count = 0; //noinspection UnusedDeclaration - for (Position p : this.getPositions()) - { + for (Position p : this.getPositions()) { count++; } return count; } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { this.polygon.setDelegateOwner(owner); } - protected SurfacePolygon createPolygon() - { + protected SurfacePolygon createPolygon() { SurfacePolygon polygon = new SurfacePolygon(); polygon.setDelegateOwner(this.getActiveDelegateOwner()); polygon.setAttributes(this.getActiveShapeAttributes()); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/BattlePosition.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/BattlePosition.java index e5ef2fbf5d..4adb8c25ba 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/BattlePosition.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/BattlePosition.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -25,14 +24,20 @@ * @author pabercrombie * @version $Id: BattlePosition.java 560 2012-04-26 16:28:24Z pabercrombie $ */ -public class BattlePosition extends BasicArea -{ - /** Factor applied to the stipple pattern used to draw the dashed line for a Prepared but not Occupied area. */ +public class BattlePosition extends BasicArea { + + /** + * Factor applied to the stipple pattern used to draw the dashed line for a Prepared but not Occupied area. + */ protected static final int PBNO_OUTLINE_STIPPLE_FACTOR = 12; - /** Tactical symbol used to render the echelon modifier. */ + /** + * Tactical symbol used to render the echelon modifier. + */ protected TacticalSymbol echelonSymbol; - /** Attribute bundle for the echelon symbol. */ + /** + * Attribute bundle for the echelon symbol. + */ protected TacticalSymbolAttributes symbolAttributes; /** @@ -40,11 +45,10 @@ public class BattlePosition extends BasicArea * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_DEF_ARS_BTLPSN, - TacGrpSidc.C2GM_DEF_ARS_BTLPSN_PBNO); + TacGrpSidc.C2GM_DEF_ARS_BTLPSN, + TacGrpSidc.C2GM_DEF_ARS_BTLPSN_PBNO); } /** @@ -52,47 +56,45 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public BattlePosition(String sidc) - { + public BattlePosition(String sidc) { super(sidc); String echelon = this.symbolCode.getEchelon(); - if (!SymbolCode.isFieldEmpty(echelon)) + if (!SymbolCode.isFieldEmpty(echelon)) { this.echelonSymbol = this.createEchelonSymbol(sidc); + } } - /** {@inheritDoc} Overridden to render the echelon modifier. */ + /** + * {@inheritDoc} Overridden to render the echelon modifier. + */ @Override - protected void doRenderGraphicModifiers(DrawContext dc) - { + protected void doRenderGraphicModifiers(DrawContext dc) { super.doRenderGraphicModifiers(dc); - if (this.echelonSymbol != null) - { + if (this.echelonSymbol != null) { this.echelonSymbol.render(dc); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected String createLabelText() - { + protected String createLabelText() { String label = this.getGraphicLabel(); String text = this.getText(); - if (label == null && text == null) - { + if (label == null && text == null) { return null; } StringBuilder sb = new StringBuilder(); - if (!WWUtil.isEmpty(label)) - { + if (!WWUtil.isEmpty(label)) { sb.append(label).append(" "); } - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { sb.append(text); } @@ -100,20 +102,22 @@ protected String createLabelText() } @Override - protected String getGraphicLabel() - { - if (TacGrpSidc.C2GM_DEF_ARS_BTLPSN_PBNO.equalsIgnoreCase(this.maskedSymbolCode)) + protected String getGraphicLabel() { + if (TacGrpSidc.C2GM_DEF_ARS_BTLPSN_PBNO.equalsIgnoreCase(this.maskedSymbolCode)) { return "(P)"; + } return null; } - /** {@inheritDoc} Overridden to determine the position of the echelon label. */ + /** + * {@inheritDoc} Overridden to determine the position of the echelon label. + */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (this.labels == null || this.labels.isEmpty()) + protected void determineLabelPositions(DrawContext dc) { + if (this.labels == null || this.labels.isEmpty()) { return; + } Position mainLabelPosition = this.determineMainLabelPosition(dc); this.labels.get(0).setPosition(mainLabelPosition); @@ -122,10 +126,11 @@ protected void determineLabelPositions(DrawContext dc) this.determineIdentityLabelPositions(); } - /** {@inheritDoc} Overridden to determine the position of the echelon label as well as the identity labels. */ + /** + * {@inheritDoc} Overridden to determine the position of the echelon label as well as the identity labels. + */ @Override - protected void determineIdentityLabelPositions() - { + protected void determineIdentityLabelPositions() { // Note: this method determines the position of the echelon modifier even though this modifier is implemented // as a tactical symbol and not as a label. The position of the echelon modifier is related to the position of // the identity labels, so it makes sense to handle them together. @@ -139,17 +144,14 @@ protected void determineIdentityLabelPositions() Position startPosition = first; LatLon midpoint = LatLon.interpolate(0.5, first, second); - if (this.echelonSymbol != null) - { + if (this.echelonSymbol != null) { this.echelonSymbol.setPosition(new Position(midpoint, 0)); } int count = this.getPositionCount(); - if (this.identityLabel1 != null) - { + if (this.identityLabel1 != null) { // Step one quarter of the way around the polygon and place the first identity label. - for (int i = 0; i < (count + 1) / 4; i++) - { + for (int i = 0; i < (count + 1) / 4; i++) { first = second; second = iterator.next(); } @@ -158,60 +160,55 @@ protected void determineIdentityLabelPositions() this.identityLabel1.setPosition(new Position(midpoint, 0)); } - if (this.identityLabel2 != null) - { + if (this.identityLabel2 != null) { // Step another quarter of the way and place the second identity label. If the control points are more or less // evenly distributed, this will put the identity labels on opposite sides of the polygon, and away from the // echelon label. - for (int i = 0; i <= count / 4; i++) - { + for (int i = 0; i <= count / 4; i++) { first = second; second = iterator.hasNext() ? iterator.next() : startPosition; } midpoint = LatLon.interpolate(0.5, first, second); - if (this.identityLabel2 != null) - { + if (this.identityLabel2 != null) { this.identityLabel2.setPosition(new Position(midpoint, 0)); } } } @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); // Prepared but not Occupied graphic always renders with dashed lines. - if (TacGrpSidc.C2GM_DEF_ARS_BTLPSN_PBNO.equalsIgnoreCase(this.maskedSymbolCode)) - { + if (TacGrpSidc.C2GM_DEF_ARS_BTLPSN_PBNO.equalsIgnoreCase(this.maskedSymbolCode)) { attributes.setOutlineStippleFactor(PBNO_OUTLINE_STIPPLE_FACTOR); attributes.setOutlineStipplePattern(this.getOutlineStipplePattern()); } } - /** {@inheritDoc} Overridden to update echelon symbol attributes. */ + /** + * {@inheritDoc} Overridden to update echelon symbol attributes. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply active attributes to the symbol. - if (this.symbolAttributes != null) - { + if (this.symbolAttributes != null) { ShapeAttributes activeAttributes = this.getActiveShapeAttributes(); this.symbolAttributes.setOpacity(activeAttributes.getInteriorOpacity()); this.symbolAttributes.setTextModifierMaterial(this.getLabelMaterial()); } } - /** {@inheritDoc} Overridden to apply delegate owner to echelon symbol. */ + /** + * {@inheritDoc} Overridden to apply delegate owner to echelon symbol. + */ @Override - protected void applyDelegateOwner(Object owner) - { + protected void applyDelegateOwner(Object owner) { super.applyDelegateOwner(owner); - if (this.echelonSymbol != null) - { + if (this.echelonSymbol != null) { this.echelonSymbol.setDelegateOwner(owner); } } @@ -223,12 +220,12 @@ protected void applyDelegateOwner(Object owner) * * @return A symbol to render the echelon modifier. */ - protected TacticalSymbol createEchelonSymbol(String sidc) - { + protected TacticalSymbol createEchelonSymbol(String sidc) { TacticalSymbol symbol = new EchelonSymbol(sidc); - if (this.symbolAttributes == null) + if (this.symbolAttributes == null) { this.symbolAttributes = new BasicTacticalSymbolAttributes(); + } symbol.setAttributes(this.symbolAttributes); return symbol; diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularFireSupportArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularFireSupportArea.java index 0f8335e82f..b6cdb7b38a 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularFireSupportArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularFireSupportArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.avlist.AVKey; @@ -26,11 +25,15 @@ * @author pabercrombie * @version $Id: CircularFireSupportArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CircularFireSupportArea extends AbstractCircularGraphic -{ - /** Path to the image used for the polygon fill pattern. */ +public class CircularFireSupportArea extends AbstractCircularGraphic { + + /** + * Path to the image used for the polygon fill pattern. + */ protected static final String DIAGONAL_FILL_PATH = "images/diagonal-fill-16x16.png"; - /** Center text block on label position when the text is left aligned. */ + /** + * Center text block on label position when the text is left aligned. + */ protected final static Offset LEFT_ALIGN_OFFSET = new Offset(-0.5d, -0.5d, AVKey.FRACTION, AVKey.FRACTION); /** @@ -38,22 +41,21 @@ public class CircularFireSupportArea extends AbstractCircularGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.FSUPP_ARS_ARATGT_CIRTGT, - TacGrpSidc.FSUPP_ARS_C2ARS_FSA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_FFA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_RFA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_ACA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_DA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_TBA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_NFA_CIRCLR, - TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_CIRCLR, - TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_CIRCLR); + TacGrpSidc.FSUPP_ARS_ARATGT_CIRTGT, + TacGrpSidc.FSUPP_ARS_C2ARS_FSA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_FFA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_RFA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_ACA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_DA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_TBA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_NFA_CIRCLR, + TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_CIRCLR, + TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_CIRCLR); } /** @@ -61,8 +63,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public CircularFireSupportArea(String sidc) - { + public CircularFireSupportArea(String sidc) { super(sidc); } @@ -72,53 +73,48 @@ public CircularFireSupportArea(String sidc) * template in MIL-STD-2525C. * * @return A Set containing the function IDs of graphics that support a date/time label separate from the graphic's - * main label. + * main label. */ - public static Set getGraphicsWithTimeLabel() - { + public static Set getGraphicsWithTimeLabel() { return new HashSet(Arrays.asList( - TacGrpSidc.FSUPP_ARS_C2ARS_FSA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_DA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_TBA_CIRCLR, - TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_CIRCLR)); + TacGrpSidc.FSUPP_ARS_C2ARS_FSA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_DA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_TBA_CIRCLR, + TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_CIRCLR)); } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { FireSupportTextBuilder textBuilder = this.createTextBuilder(); String[] allText = textBuilder.createText(this); String text = allText[0]; - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { TacticalGraphicLabel mainLabel = this.addLabel(text); mainLabel.setTextAlign(this.getMainLabelTextAlign()); - if (this.isFilled()) - { + if (this.isFilled()) { mainLabel.setEffect(AVKey.TEXT_EFFECT_NONE); mainLabel.setDrawInterior(true); } } - if (allText.length > 1) - { + if (allText.length > 1) { String timeText = allText[1]; - if (!WWUtil.isEmpty(timeText)) - { + if (!WWUtil.isEmpty(timeText)) { TacticalGraphicLabel timeLabel = this.addLabel(timeText); timeLabel.setTextAlign(AVKey.RIGHT); } } } - protected FireSupportTextBuilder createTextBuilder() - { + protected FireSupportTextBuilder createTextBuilder() { return new FireSupportTextBuilder(); } @@ -127,15 +123,15 @@ protected FireSupportTextBuilder createTextBuilder() * * @return Text alignment for the main label. */ - protected String getMainLabelTextAlign() - { + protected String getMainLabelTextAlign() { boolean isACA = TacGrpSidc.FSUPP_ARS_C2ARS_ACA_CIRCLR.equalsIgnoreCase(this.maskedSymbolCode); // Airspace Coordination Area labels are left aligned. All others are center aligned. - if (isACA) + if (isACA) { return AVKey.LEFT; - else + } else { return AVKey.CENTER; + } } /** @@ -145,46 +141,45 @@ protected String getMainLabelTextAlign() * @return Offset to apply to the main label. */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { boolean isACA = TacGrpSidc.FSUPP_ARS_C2ARS_ACA_CIRCLR.equalsIgnoreCase(this.maskedSymbolCode); // Airspace Coordination Area labels are left aligned. Adjust the offset to center the left aligned label // in the circle. (This is not necessary with a center aligned label because centering the text automatically // centers the label in the circle). - if (isACA) + if (isACA) { return LEFT_ALIGN_OFFSET; - else + } else { return super.getDefaultLabelOffset(); + } } @Override - protected void determineLabelPositions(DrawContext dc) - { - if (WWUtil.isEmpty(this.labels)) + protected void determineLabelPositions(DrawContext dc) { + if (WWUtil.isEmpty(this.labels)) { return; + } this.labels.get(0).setPosition(new Position(this.circle.getCenter(), 0)); Position center = new Position(this.circle.getCenter(), 0); double radiusRadians = this.circle.getRadius() / dc.getGlobe().getRadius(); - if (this.labels.size() > 1) - { + if (this.labels.size() > 1) { LatLon westEdge = LatLon.greatCircleEndPosition(center, Angle.NEG90 /* Due West */, - Angle.fromRadians(radiusRadians)); + Angle.fromRadians(radiusRadians)); this.labels.get(1).setPosition(new Position(westEdge, 0)); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); - if (this.isFilled()) - { + if (this.isFilled()) { // Enable the polygon interior and set the image source to draw a fill pattern of diagonal lines. attributes.setDrawInterior(true); attributes.setImageSource(this.getImageSource()); @@ -196,11 +191,10 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) * * @return true if the polygon must be filled, otherwise false. */ - protected boolean isFilled() - { + protected boolean isFilled() { return TacGrpSidc.FSUPP_ARS_C2ARS_NFA_CIRCLR.equalsIgnoreCase(this.maskedSymbolCode) - || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_CIRCLR.equalsIgnoreCase(this.maskedSymbolCode) - || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_CIRCLR.equalsIgnoreCase(this.maskedSymbolCode); + || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_CIRCLR.equalsIgnoreCase(this.maskedSymbolCode) + || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_CIRCLR.equalsIgnoreCase(this.maskedSymbolCode); } /** @@ -208,8 +202,7 @@ protected boolean isFilled() * * @return The source of the polygon fill pattern. */ - protected Object getImageSource() - { + protected Object getImageSource() { return DIAGONAL_FILL_PATH; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularPositionArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularPositionArea.java index e0f83a642b..8f6886e41d 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularPositionArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularPositionArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -18,15 +17,14 @@ * @author pabercrombie * @version $Id: CircularPositionArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CircularPositionArea extends AbstractCircularGraphic -{ +public class CircularPositionArea extends AbstractCircularGraphic { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.FSUPP_ARS_C2ARS_PAA_CIRCLR); } @@ -35,15 +33,15 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public CircularPositionArea(String sidc) - { + public CircularPositionArea(String sidc) { super(sidc); } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { // This graphic has labels at the top, bottom, left, and right of the circle. this.addLabel("PAA"); this.addLabel("PAA"); @@ -52,12 +50,11 @@ protected void createLabels() } @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { Position center = new Position(this.circle.getCenter(), 0); Angle radius = Angle.fromRadians(this.circle.getRadius() / dc.getGlobe().getRadius()); - Angle[] cardinalDirections = new Angle[] { + Angle[] cardinalDirections = new Angle[]{ Angle.NEG90, // Due West Angle.POS90, // Due East Angle.ZERO, // Due North @@ -65,11 +62,10 @@ protected void determineLabelPositions(DrawContext dc) }; int i = 0; - for (Angle dir : cardinalDirections) - { + for (Angle dir : cardinalDirections) { LatLon loc = LatLon.greatCircleEndPosition(center, dir, radius); this.labels.get(i).setPosition(new Position(loc, 0)); i += 1; } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularRangeFan.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularRangeFan.java index c6e0a71165..11d8a87fbc 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularRangeFan.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CircularRangeFan.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -21,18 +20,26 @@ * @author pabercrombie * @version $Id: CircularRangeFan.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CircularRangeFan extends AbstractMilStd2525TacticalGraphic implements PreRenderable -{ +public class CircularRangeFan extends AbstractMilStd2525TacticalGraphic implements PreRenderable { + protected final static Offset LABEL_OFFSET = Offset.fromFraction(0d, 0d); - /** Position of the center of the range fan. */ + /** + * Position of the center of the range fan. + */ protected Position position; - /** Rings that make up the range fan. */ + /** + * Rings that make up the range fan. + */ protected List rings; - /** Symbol drawn at the center of the range fan. */ + /** + * Symbol drawn at the center of the range fan. + */ protected TacticalSymbol symbol; - /** Attributes applied to the symbol. */ + /** + * Attributes applied to the symbol. + */ protected TacticalSymbolAttributes symbolAttributes; /** @@ -40,8 +47,7 @@ public class CircularRangeFan extends AbstractMilStd2525TacticalGraphic implemen * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.FSUPP_ARS_WPNRF_CIRCLR); } @@ -50,8 +56,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public CircularRangeFan(String sidc) - { + public CircularRangeFan(String sidc) { super(sidc); this.rings = new ArrayList(); } @@ -61,8 +66,7 @@ public CircularRangeFan(String sidc) * * @return The range fan center position. */ - public Position getPosition() - { + public Position getPosition() { return this.getReferencePosition(); } @@ -71,8 +75,7 @@ public Position getPosition() * * @param position The new center position. */ - public void setPosition(Position position) - { + public void setPosition(Position position) { this.moveTo(position); } @@ -80,20 +83,17 @@ public void setPosition(Position position) * {@inheritDoc} * * @param positions Control points. This graphic uses only one control point, which determines the center of the - * circle. + * circle. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Iterator iterator = positions.iterator(); - if (!iterator.hasNext()) - { + if (!iterator.hasNext()) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -101,58 +101,45 @@ public void setPositions(Iterable positions) this.position = iterator.next(); - for (SurfaceCircle ring : this.rings) - { + for (SurfaceCircle ring : this.rings) { ring.setCenter(this.position); } - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.setPosition(this.position); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override @SuppressWarnings("unchecked") - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.DISTANCE.equals(modifier)) - { - if (value instanceof Iterable) - { + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.DISTANCE.equals(modifier)) { + if (value instanceof Iterable) { //noinspection unchecked this.setRadii((Iterable) value); - } - else if (value instanceof Double) - { + } else if (value instanceof Double) { this.setRadii(Arrays.asList((Double) value)); } - } - else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) - { + } else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) { this.setSymbol((String) value); - } - else - { + } else { super.setModifier(modifier, value); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.DISTANCE.equals(modifier)) - { + public Object getModifier(String modifier) { + if (SymbologyConstants.DISTANCE.equals(modifier)) { return this.getRadii(); - } - else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) - { + } else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) { return this.getSymbol(); - } - else - { + } else { return super.getModifier(modifier); } } @@ -162,11 +149,9 @@ else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) * * @return List of radii, in meters. If there are no rings this returns an empty list. */ - public List getRadii() - { + public List getRadii() { List radii = new ArrayList(); - for (SurfaceCircle ring : this.rings) - { + for (SurfaceCircle ring : this.rings) { radii.add(ring.getRadius()); } return radii; @@ -177,18 +162,14 @@ public List getRadii() * * @param radii List of radii, in meters. A circle will be created for each radius. */ - public void setRadii(Iterable radii) - { + public void setRadii(Iterable radii) { this.rings.clear(); - for (Double d : radii) - { - if (d != null) - { + for (Double d : radii) { + if (d != null) { SurfaceCircle ring = this.createCircle(); ring.setRadius(d); - if (this.position != null) - { + if (this.position != null) { ring.setCenter(this.position); } @@ -204,8 +185,7 @@ public void setRadii(Iterable radii) * * @return The symbol drawn at the center of the range fan. May be null. */ - public String getSymbol() - { + public String getSymbol() { return this.symbol != null ? this.symbol.getIdentifier() : null; } @@ -215,19 +195,16 @@ public String getSymbol() * center position. * * @param sidc Identifier for a MIL-STD-2525C symbol to draw at the center of the range fan. May be null to indicate - * that no symbol is drawn. + * that no symbol is drawn. */ - public void setSymbol(String sidc) - { - if (sidc != null) - { - if (this.symbolAttributes == null) + public void setSymbol(String sidc) { + if (sidc != null) { + if (this.symbolAttributes == null) { this.symbolAttributes = new BasicTacticalSymbolAttributes(); + } this.symbol = this.createSymbol(sidc, this.getPosition(), this.symbolAttributes); - } - else - { + } else { // Null value indicates no symbol. this.symbol = null; this.symbolAttributes = null; @@ -235,30 +212,31 @@ public void setSymbol(String sidc) this.onModifierChanged(); } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.position); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.position; } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } this.determineActiveAttributes(); - for (SurfaceCircle ring : this.rings) - { + for (SurfaceCircle ring : this.rings) { ring.preRender(dc); } } @@ -268,56 +246,48 @@ public void preRender(DrawContext dc) * * @param dc Current draw context. */ - protected void doRenderGraphic(DrawContext dc) - { - for (SurfaceCircle ring : this.rings) - { + protected void doRenderGraphic(DrawContext dc) { + for (SurfaceCircle ring : this.rings) { ring.render(dc); } } - /** {@inheritDoc} Overridden to render symbol at the center of the range fan. */ + /** + * {@inheritDoc} Overridden to render symbol at the center of the range fan. + */ @Override - protected void doRenderGraphicModifiers(DrawContext dc) - { + protected void doRenderGraphicModifiers(DrawContext dc) { super.doRenderGraphicModifiers(dc); - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.render(dc); } } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { Iterator altIterator = null; // See if the altitude modifier is set. If so, use it's value to construct altitude labels. Object modifier = this.getModifier(SymbologyConstants.ALTITUDE_DEPTH); - if (modifier instanceof Iterable) - { + if (modifier instanceof Iterable) { altIterator = ((Iterable) modifier).iterator(); - } - else if (modifier != null) - { + } else if (modifier != null) { // Use the modifier as the altitude of the first ring altIterator = Arrays.asList(modifier).iterator(); } // Create a label for each ring - for (int i = 0; i < this.rings.size(); i++) - { + for (int i = 0; i < this.rings.size(); i++) { SurfaceCircle ring = this.rings.get(i); StringBuilder sb = new StringBuilder(); - if (i == 0) - { + if (i == 0) { sb.append("MIN RG "); - } - else - { + } else { sb.append("MAX RG("); sb.append(i); sb.append(") "); @@ -325,8 +295,7 @@ else if (modifier != null) sb.append(ring.getRadius()); // Append the altitude, if available - if (altIterator != null && altIterator.hasNext()) - { + if (altIterator != null && altIterator.hasNext()) { Object alt = altIterator.next(); sb.append("\n"); sb.append("ALT "); @@ -338,16 +307,16 @@ else if (modifier != null) } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { double dueSouth = Angle.POS180.radians; double globeRadius = dc.getGlobe().getRadius(); int i = 0; - for (SurfaceCircle ring : this.rings) - { + for (SurfaceCircle ring : this.rings) { double radius = ring.getRadius(); // Position the label at the Southern edge of the ring @@ -358,29 +327,30 @@ protected void determineLabelPositions(DrawContext dc) } } - /** {@inheritDoc} Overridden to update symbol attributes. */ + /** + * {@inheritDoc} Overridden to update symbol attributes. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply active attributes to the symbol. - if (this.symbolAttributes != null) - { + if (this.symbolAttributes != null) { ShapeAttributes activeAttributes = this.getActiveShapeAttributes(); this.symbolAttributes.setOpacity(activeAttributes.getInteriorOpacity()); this.symbolAttributes.setScale(this.activeOverrides.getScale()); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.rings == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.rings == null) { return; + } - for (SurfaceCircle ring : this.rings) - { + for (SurfaceCircle ring : this.rings) { ring.setDelegateOwner(owner); } } @@ -390,11 +360,10 @@ protected void applyDelegateOwner(Object owner) * * @return New circle. */ - protected SurfaceCircle createCircle() - { + protected SurfaceCircle createCircle() { SurfaceCircle circle = new SurfaceCircle(); circle.setDelegateOwner(this.getActiveDelegateOwner()); circle.setAttributes(this.activeShapeAttributes); return circle; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CombatSupportArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CombatSupportArea.java index d167228f67..8a65748122 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CombatSupportArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/CombatSupportArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.symbology.milstd2525.graphics.TacGrpSidc; @@ -20,23 +19,22 @@ * @author pabercrombie * @version $Id: CombatSupportArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CombatSupportArea extends BasicArea -{ +public class CombatSupportArea extends BasicArea { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.CSS_ARA_DHA, - TacGrpSidc.CSS_ARA_EPWHA, - TacGrpSidc.CSS_ARA_FARP, - TacGrpSidc.CSS_ARA_RHA, - TacGrpSidc.CSS_ARA_SUPARS_BSA, - TacGrpSidc.CSS_ARA_SUPARS_DSA, - TacGrpSidc.CSS_ARA_SUPARS_RSA); + TacGrpSidc.CSS_ARA_DHA, + TacGrpSidc.CSS_ARA_EPWHA, + TacGrpSidc.CSS_ARA_FARP, + TacGrpSidc.CSS_ARA_RHA, + TacGrpSidc.CSS_ARA_SUPARS_BSA, + TacGrpSidc.CSS_ARA_SUPARS_DSA, + TacGrpSidc.CSS_ARA_SUPARS_RSA); } /** @@ -44,34 +42,35 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public CombatSupportArea(String sidc) - { + public CombatSupportArea(String sidc) { super(sidc); // Do not draw "ENY" labels for hostile entities this.setShowHostileIndicator(false); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected String getGraphicLabel() - { + protected String getGraphicLabel() { String code = this.maskedSymbolCode; - if (TacGrpSidc.CSS_ARA_DHA.equalsIgnoreCase(code)) + if (TacGrpSidc.CSS_ARA_DHA.equalsIgnoreCase(code)) { return "DETAINEE\nHOLDING\nAREA"; - else if (TacGrpSidc.CSS_ARA_EPWHA.equalsIgnoreCase(code)) + } else if (TacGrpSidc.CSS_ARA_EPWHA.equalsIgnoreCase(code)) { return "EPW\nHOLDING\nAREA"; - else if (TacGrpSidc.CSS_ARA_FARP.equalsIgnoreCase(code)) + } else if (TacGrpSidc.CSS_ARA_FARP.equalsIgnoreCase(code)) { return "FARP"; - else if (TacGrpSidc.CSS_ARA_RHA.equalsIgnoreCase(code)) + } else if (TacGrpSidc.CSS_ARA_RHA.equalsIgnoreCase(code)) { return "REFUGEE\nHOLDING\nAREA"; - else if (TacGrpSidc.CSS_ARA_SUPARS_BSA.equalsIgnoreCase(code)) + } else if (TacGrpSidc.CSS_ARA_SUPARS_BSA.equalsIgnoreCase(code)) { return "BSA"; - else if (TacGrpSidc.CSS_ARA_SUPARS_DSA.equalsIgnoreCase(code)) + } else if (TacGrpSidc.CSS_ARA_SUPARS_DSA.equalsIgnoreCase(code)) { return "DSA"; - else if (TacGrpSidc.CSS_ARA_SUPARS_RSA.equalsIgnoreCase(code)) + } else if (TacGrpSidc.CSS_ARA_SUPARS_RSA.equalsIgnoreCase(code)) { return "RSA"; + } return ""; } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Dummy.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Dummy.java index dc78f3d078..f77e64cfa8 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Dummy.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Dummy.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.WorldWind; @@ -22,8 +21,8 @@ * @author pabercrombie * @version $Id: Dummy.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Dummy extends AbstractMilStd2525TacticalGraphic -{ +public class Dummy extends AbstractMilStd2525TacticalGraphic { + protected Path path; /** @@ -31,27 +30,27 @@ public class Dummy extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_DCPN_DMY); } - public Dummy(String sidc) - { + public Dummy(String sidc) { super(sidc); this.path = this.createPath(); this.path.setAttributes(this.getActiveShapeAttributes()); } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { this.path.render(dc); } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { this.path.setDelegateOwner(owner); } @@ -62,47 +61,43 @@ protected void applyDelegateOwner(Object owner) * * @throws IllegalArgumentException if less than three control points are provided. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); Position pt1 = iterator.next(); Position pt2 = iterator.next(); Position pt3 = iterator.next(); this.path.setPositions(Arrays.asList(pt2, pt1, pt3)); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return this.path.getPositions(); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.path.getReferencePosition(); } @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); attributes.setOutlineWidth(2.0); @@ -110,8 +105,7 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) attributes.setOutlineStipplePattern((short) 0xAAAA); } - protected Path createPath() - { + protected Path createPath() { Path path = new Path(); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Encirclement.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Encirclement.java index 012c095a11..f438a9d22e 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Encirclement.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Encirclement.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -20,12 +19,16 @@ * @author pabercrombie * @version $Id: Encirclement.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class Encirclement extends BasicArea -{ - /** Default number of wave lengths for a simple shape. This number is used to compute a default wave length. */ +public class Encirclement extends BasicArea { + + /** + * Default number of wave lengths for a simple shape. This number is used to compute a default wave length. + */ public static final int DEFAULT_NUM_WAVES = 10; - /** Original positions specified by the application. */ + /** + * Original positions specified by the application. + */ protected Iterable positions; /** * Positions computed from the original positions. This list includes the positions necessary to draw the triangle @@ -33,9 +36,13 @@ public class Encirclement extends BasicArea */ protected List computedPositions; - /** Indicates the wavelength of the triangle wave that forms the graphic's border. */ + /** + * Indicates the wavelength of the triangle wave that forms the graphic's border. + */ protected double waveLength; - /** The polygon with triangle wave. */ + /** + * The polygon with triangle wave. + */ protected SurfacePolygon wavePolygon = new SurfacePolygon(); /** @@ -43,8 +50,7 @@ public class Encirclement extends BasicArea * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_SPL_ARA_ENCMT); } @@ -53,33 +59,34 @@ public static List getSupportedGraphics() * * @param sidc MIL-STD-2525C identifier code. */ - public Encirclement(String sidc) - { + public Encirclement(String sidc) { super(sidc); this.wavePolygon = this.createPolygon(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setPositions(Iterable positions) - { + public void setPositions(Iterable positions) { this.positions = positions; this.computedPositions = null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Iterable getPositions() - { + public Iterable getPositions() { return this.positions; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -89,8 +96,9 @@ public void moveTo(Position position) // The reference position is null if this shape has no positions. In this case moving the shape to a new // reference position is meaningless. Therefore we fail softly by exiting and doing nothing. - if (oldPosition == null) + if (oldPosition == null) { return; + } this.positions = Position.computeShiftedPositions(oldPosition, position, this.getPositions()); @@ -111,8 +119,7 @@ public void moveTo(Position position) * * @return The wave length, in meters. */ - public double getWaveLength() - { + public double getWaveLength() { return this.waveLength; } @@ -122,16 +129,15 @@ public double getWaveLength() * * @param waveLength The wavelength, in meters. */ - public void setWaveLength(double waveLength) - { + public void setWaveLength(double waveLength) { this.waveLength = waveLength; } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } @@ -140,18 +146,17 @@ public void preRender(DrawContext dc) } @Override - protected void doRenderGraphic(DrawContext dc) - { + protected void doRenderGraphic(DrawContext dc) { super.doRenderGraphic(dc); this.wavePolygon.render(dc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void computeGeometry(DrawContext dc) - { - if (this.computedPositions == null && this.positions != null) - { + protected void computeGeometry(DrawContext dc) { + if (this.computedPositions == null && this.positions != null) { this.generateIntermediatePositions(dc, this.positions); this.polygon.setLocations(this.positions); this.wavePolygon.setLocations(this.computedPositions); @@ -162,25 +167,22 @@ protected void computeGeometry(DrawContext dc) /** * Generate the positions required to draw the polygon with a triangle wave boundary. * - * @param dc Current draw context. + * @param dc Current draw context. * @param positions Positions that define the polygon boundary. */ - protected void generateIntermediatePositions(DrawContext dc, Iterable positions) - { + protected void generateIntermediatePositions(DrawContext dc, Iterable positions) { Globe globe = dc.getGlobe(); List wavePositions = new ArrayList(); double waveLength = this.getWaveLength(); - if (waveLength == 0) - { + if (waveLength == 0) { waveLength = this.computeDefaultWavelength(dc.getGlobe()); } double amplitude = waveLength / 2.0; TriangleWavePositionIterator iterator = new TriangleWavePositionIterator(positions, waveLength, amplitude, - globe); - while (iterator.hasNext()) - { + globe); + while (iterator.hasNext()) { wavePositions.add(iterator.next()); } @@ -200,8 +202,7 @@ protected void generateIntermediatePositions(DrawContext dc, Iterable getSupportedGraphics() - { + public static java.util.List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.MOBSU_CBRN_RADA, - TacGrpSidc.MOBSU_CBRN_BIOCA, - TacGrpSidc.MOBSU_CBRN_CMLCA); + TacGrpSidc.MOBSU_CBRN_RADA, + TacGrpSidc.MOBSU_CBRN_BIOCA, + TacGrpSidc.MOBSU_CBRN_CMLCA); } /** @@ -40,15 +40,15 @@ public static java.util.List getSupportedGraphics() * * @param sidc Symbol code that identifies the graphic to create. */ - public FilledArea(String sidc) - { + public FilledArea(String sidc) { super(sidc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); // Enable the polygon interior and set the image source to draw a fill pattern of diagonal lines. @@ -61,8 +61,7 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) * * @return The source of the polygon fill pattern. */ - protected Object getImageSource() - { + protected Object getImageSource() { return DIAGONAL_FILL_PATH; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/FireSupportTextBuilder.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/FireSupportTextBuilder.java index cda5164136..3f63c883a4 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/FireSupportTextBuilder.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/FireSupportTextBuilder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.symbology.*; @@ -19,8 +18,8 @@ * @author pabercrombie * @version $Id: FireSupportTextBuilder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FireSupportTextBuilder -{ +public class FireSupportTextBuilder { + /** * Construct the text for labels in a Fire Support area graphic. All area graphics support main label placed inside * the area. Some also support a time range label placed at the left side of the graphic. This method returns text @@ -30,13 +29,11 @@ public class FireSupportTextBuilder * @param graphic Graphic for which to create text. * * @return Array of text for labels. This array will always include at least one string: the main label text. It may - * include a second element. The second element (if present) is text for a label that must be placed at the - * left side of the area. + * include a second element. The second element (if present) is text for a label that must be placed at the left + * side of the area. */ - public String[] createText(TacticalGraphic graphic) - { - if (graphic == null) - { + public String[] createText(TacticalGraphic graphic) { + if (graphic == null) { String message = Logging.getMessage("nullValue.GraphicIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -48,106 +45,84 @@ public String[] createText(TacticalGraphic graphic) SymbolCode symCode = new SymbolCode(graphic.getIdentifier()); String maskedSidc = symCode.toMaskedString(); - if (TacGrpSidc.FSUPP_ARS_ARATGT_CIRTGT.equalsIgnoreCase(maskedSidc)) - { + if (TacGrpSidc.FSUPP_ARS_ARATGT_CIRTGT.equalsIgnoreCase(maskedSidc)) { // Circular Target just uses the Unique Designation as a label. - result = new String[] {graphic.getText()}; - } - else if (TacGrpSidc.FSUPP_ARS_ARATGT_BMARA.equalsIgnoreCase(maskedSidc)) - { + result = new String[]{graphic.getText()}; + } else if (TacGrpSidc.FSUPP_ARS_ARATGT_BMARA.equalsIgnoreCase(maskedSidc)) { // Bomb graphic just says "BOMB" - result = new String[] {"BOMB"}; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_TGMF.equalsIgnoreCase(maskedSidc)) - { + result = new String[]{"BOMB"}; + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_TGMF.equalsIgnoreCase(maskedSidc)) { // Terminally guided munitions footprint says "TGMF", and does not support modifiers. - result = new String[] {"TGMF"}; - } - else - { + result = new String[]{"TGMF"}; + } else { boolean useSeparateTimeLabel = this.isShowSeparateTimeLabel(maskedSidc); String mainText; - if (this.isAirspaceCoordinationArea(maskedSidc)) - { + if (this.isAirspaceCoordinationArea(maskedSidc)) { mainText = this.createAirspaceCoordinationText(graphic); - } - else - { + } else { boolean includeTime = !useSeparateTimeLabel; boolean includeAltitude = this.isShowAltitude(maskedSidc); mainText = this.createMainText(graphic, maskedSidc, includeTime, includeAltitude); } - if (useSeparateTimeLabel) - { + if (useSeparateTimeLabel) { String timeText = this.createTimeRangeText(graphic); - result = new String[] {mainText, timeText}; - } - else - { - result = new String[] {mainText}; + result = new String[]{mainText, timeText}; + } else { + result = new String[]{mainText}; } } return result; } - protected boolean isShowSeparateTimeLabel(String maskedSidc) - { + protected boolean isShowSeparateTimeLabel(String maskedSidc) { return CircularFireSupportArea.getGraphicsWithTimeLabel().contains(maskedSidc) - || RectangularFireSupportArea.getGraphicsWithTimeLabel().contains(maskedSidc) - || IrregularFireSupportArea.getGraphicsWithTimeLabel().contains(maskedSidc); + || RectangularFireSupportArea.getGraphicsWithTimeLabel().contains(maskedSidc) + || IrregularFireSupportArea.getGraphicsWithTimeLabel().contains(maskedSidc); } - protected boolean isShowAltitude(String maskedSidc) - { + protected boolean isShowAltitude(String maskedSidc) { return TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_RTG.equalsIgnoreCase(maskedSidc) - || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_CIRCLR.equalsIgnoreCase(maskedSidc) - || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_IRR.equalsIgnoreCase(maskedSidc); + || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_CIRCLR.equalsIgnoreCase(maskedSidc) + || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_IRR.equalsIgnoreCase(maskedSidc); } - protected boolean isAirspaceCoordinationArea(String functionId) - { + protected boolean isAirspaceCoordinationArea(String functionId) { return TacGrpSidc.FSUPP_ARS_C2ARS_ACA_IRR.equalsIgnoreCase(functionId) - || TacGrpSidc.FSUPP_ARS_C2ARS_ACA_RTG.equalsIgnoreCase(functionId) - || TacGrpSidc.FSUPP_ARS_C2ARS_ACA_CIRCLR.equalsIgnoreCase(functionId); + || TacGrpSidc.FSUPP_ARS_C2ARS_ACA_RTG.equalsIgnoreCase(functionId) + || TacGrpSidc.FSUPP_ARS_C2ARS_ACA_CIRCLR.equalsIgnoreCase(functionId); } protected String createMainText(TacticalGraphic graphic, String functionId, boolean includeTime, - boolean includeAltitude) - { + boolean includeAltitude) { StringBuilder sb = new StringBuilder(); sb.append(this.getGraphicLabel(functionId)).append("\n"); String s = graphic.getText(); - if (!WWUtil.isEmpty(s)) - { + if (!WWUtil.isEmpty(s)) { sb.append(s).append("\n"); } - if (includeTime) - { + if (includeTime) { Object[] dates = TacticalGraphicUtil.getDateRange(graphic); - if (dates[0] != null) - { + if (dates[0] != null) { sb.append(dates[0]); sb.append("-"); } - if (dates[1] != null) - { + if (dates[1] != null) { sb.append(dates[1]); } } - if (includeAltitude) - { + if (includeAltitude) { Object[] alt = TacticalGraphicUtil.getAltitudeRange(graphic); - if (alt[0] != null) - { - if (sb.length() > 0) + if (alt[0] != null) { + if (sb.length() > 0) { sb.append('\n'); + } sb.append(alt[0]); } @@ -156,162 +131,122 @@ protected String createMainText(TacticalGraphic graphic, String functionId, bool return sb.toString(); } - protected String createTimeRangeText(TacticalGraphic graphic) - { + protected String createTimeRangeText(TacticalGraphic graphic) { StringBuilder sb = new StringBuilder(); Object[] dates = TacticalGraphicUtil.getDateRange(graphic); - if (dates[0] != null) - { + if (dates[0] != null) { sb.append(dates[0]); sb.append("-\n"); } - if (dates[1] != null) - { + if (dates[1] != null) { sb.append(dates[1]); } return sb.toString(); } - protected String getGraphicLabel(String sidc) - { + protected String getGraphicLabel(String sidc) { if (TacGrpSidc.FSUPP_ARS_C2ARS_FFA_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_FFA_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_FFA_IRR.equalsIgnoreCase(sidc)) - { + || TacGrpSidc.FSUPP_ARS_C2ARS_FFA_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_FFA_IRR.equalsIgnoreCase(sidc)) { return "FFA"; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_RFA_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_RFA_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_RFA_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_RFA_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_RFA_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_RFA_IRR.equalsIgnoreCase(sidc)) { return "RFA"; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_FSA_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_FSA_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_FSA_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_FSA_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_FSA_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_FSA_IRR.equalsIgnoreCase(sidc)) { return "FSA"; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_IRR.equalsIgnoreCase(sidc)) { return "SENSOR\nZONE"; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_DA_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_DA_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_DA_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_DA_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_DA_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_DA_IRR.equalsIgnoreCase(sidc)) { return "DA"; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_DA_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_DA_IRR.equalsIgnoreCase(sidc)) { return "ZOR"; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_TBA_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_TBA_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_TBA_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_TBA_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_TBA_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_TBA_IRR.equalsIgnoreCase(sidc)) { return "TBA"; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_IRR.equalsIgnoreCase(sidc)) { return "TVAR"; - } - else if (TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_IRR.equalsIgnoreCase(sidc)) { return "ATI ZONE"; - } - else if (TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_IRR.equalsIgnoreCase(sidc)) { return "CFF ZONE"; - } - else if (TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_IRR.equalsIgnoreCase(sidc)) { return "CENSOR ZONE"; - } - else if (TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_IRR.equalsIgnoreCase(sidc)) { return "CF ZONE"; - } - else if (TacGrpSidc.FSUPP_ARS_C2ARS_NFA_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_NFA_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_C2ARS_NFA_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_C2ARS_NFA_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_NFA_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_C2ARS_NFA_IRR.equalsIgnoreCase(sidc)) { return "NFA"; - } - else if (TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_IRR.equalsIgnoreCase(sidc)) { return "BKB"; - } - else if (TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_RTG.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_CIRCLR.equalsIgnoreCase(sidc) - || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_IRR.equalsIgnoreCase(sidc)) - { + } else if (TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_RTG.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_CIRCLR.equalsIgnoreCase(sidc) + || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_IRR.equalsIgnoreCase(sidc)) { return "PKB"; } return ""; } - protected String createAirspaceCoordinationText(TacticalGraphic graphic) - { + protected String createAirspaceCoordinationText(TacticalGraphic graphic) { StringBuilder sb = new StringBuilder(); sb.append("ACA\n"); Object o = graphic.getText(); - if (o != null) - { + if (o != null) { sb.append(o); sb.append("\n"); } Object[] altitudes = TacticalGraphicUtil.getAltitudeRange(graphic); - if (altitudes[0] != null) - { + if (altitudes[0] != null) { sb.append("MIN ALT: "); sb.append(altitudes[0]); sb.append("\n"); } - if (altitudes[1] != null) - { + if (altitudes[1] != null) { sb.append("MAX ALT: "); sb.append(altitudes[1]); sb.append("\n"); } o = graphic.getModifier(SymbologyConstants.ADDITIONAL_INFORMATION); - if (o != null) - { + if (o != null) { sb.append("Grids: "); sb.append(o); sb.append("\n"); } Object[] dates = TacticalGraphicUtil.getDateRange(graphic); - if (dates[0] != null) - { + if (dates[0] != null) { sb.append("EFF: "); sb.append(dates[0]); sb.append("\n"); } - if (dates[1] != null) - { + if (dates[1] != null) { sb.append(" "); // TODO do a better job of vertically aligning the start and end time labels sb.append(dates[1]); } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/FortifiedArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/FortifiedArea.java index 8d9e45c44d..a78a354b24 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/FortifiedArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/FortifiedArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -20,12 +19,16 @@ * @author pabercrombie * @version $Id: FortifiedArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FortifiedArea extends BasicArea -{ - /** Default number of wave lengths for a simple shape. This number is used to compute a default wave length. */ +public class FortifiedArea extends BasicArea { + + /** + * Default number of wave lengths for a simple shape. This number is used to compute a default wave length. + */ public static final int DEFAULT_NUM_WAVES = 20; - /** Original positions specified by the application. */ + /** + * Original positions specified by the application. + */ protected Iterable positions; /** * Positions computed from the original positions. This list includes the positions necessary to draw the square @@ -33,7 +36,9 @@ public class FortifiedArea extends BasicArea */ protected List computedPositions; - /** Indicates the wavelength of the square wave that forms the graphic's border. */ + /** + * Indicates the wavelength of the square wave that forms the graphic's border. + */ protected double waveLength; /** @@ -41,37 +46,37 @@ public class FortifiedArea extends BasicArea * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_GNL_ARS_FTFDAR); } - public FortifiedArea(String sidc) - { + public FortifiedArea(String sidc) { super(sidc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setPositions(Iterable positions) - { + public void setPositions(Iterable positions) { this.positions = positions; this.computedPositions = null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Iterable getPositions() - { + public Iterable getPositions() { return this.positions; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -81,8 +86,9 @@ public void moveTo(Position position) // The reference position is null if this shape has no positions. In this case moving the shape to a new // reference position is meaningless. Therefore we fail softly by exiting and doing nothing. - if (oldPosition == null) + if (oldPosition == null) { return; + } this.positions = Position.computeShiftedPositions(oldPosition, position, this.getPositions()); @@ -103,8 +109,7 @@ public void moveTo(Position position) * * @return The wave length, in meters. */ - public double getWaveLength() - { + public double getWaveLength() { return waveLength; } @@ -114,17 +119,16 @@ public double getWaveLength() * * @param waveLength The wavelength, in meters. */ - public void setWaveLength(double waveLength) - { + public void setWaveLength(double waveLength) { this.waveLength = waveLength; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void computeGeometry(DrawContext dc) - { - if (this.computedPositions == null && this.positions != null) - { + public void computeGeometry(DrawContext dc) { + if (this.computedPositions == null && this.positions != null) { this.generateIntermediatePositions(dc, this.positions); this.polygon.setLocations(this.computedPositions); } @@ -134,19 +138,17 @@ public void computeGeometry(DrawContext dc) /** * Generate the positions required to draw the polygon with a square wave boundary. * - * @param dc Current draw context. + * @param dc Current draw context. * @param positions Positions that define the polygon boundary. */ - protected void generateIntermediatePositions(DrawContext dc, Iterable positions) - { + protected void generateIntermediatePositions(DrawContext dc, Iterable positions) { Iterator iterator = positions.iterator(); Globe globe = dc.getGlobe(); List toothPositions = new ArrayList(); double waveLength = this.getWaveLength(); - if (waveLength == 0) - { + if (waveLength == 0) { waveLength = this.computeDefaultWavelength(dc.getGlobe()); } @@ -162,8 +164,7 @@ protected void generateIntermediatePositions(DrawContext dc, Iterable getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.FSUPP_ARS_ARATGT_SGTGT); } @@ -36,8 +34,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public GroupOfTargets(String sidc) - { + public GroupOfTargets(String sidc) { super(sidc); } @@ -50,11 +47,11 @@ public GroupOfTargets(String sidc) * @return Position for the graphic's main label. */ @Override - protected Position determineMainLabelPosition(DrawContext dc) - { + protected Position determineMainLabelPosition(DrawContext dc) { Iterable locations = this.polygon.getLocations(); - if (locations == null) + if (locations == null) { return null; + } Iterator iterator = locations.iterator(); @@ -63,16 +60,14 @@ protected Position determineMainLabelPosition(DrawContext dc) // Find the North-most segment in the polygon. The template in MIL-STD-2525C shows the label at the "top" // of the polygon. We will interpret this as the Northern edge of the polygon. - while (iterator.hasNext()) - { + while (iterator.hasNext()) { LatLon locB = locA; locA = iterator.next(); LatLon mid = LatLon.interpolateGreatCircle(0.5, locA, locB); // Determine if the midpoint of the segment is farther North our North-most point - if (mid.latitude.compareTo(northMost.latitude) > 0) - { + if (mid.latitude.compareTo(northMost.latitude) > 0) { northMost = mid; } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/IrregularFireSupportArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/IrregularFireSupportArea.java index f83cbebedb..38623073bd 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/IrregularFireSupportArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/IrregularFireSupportArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.avlist.AVKey; @@ -28,11 +27,15 @@ * @author pabercrombie * @version $Id: IrregularFireSupportArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class IrregularFireSupportArea extends BasicArea -{ - /** Path to the image used for the polygon fill pattern. */ +public class IrregularFireSupportArea extends BasicArea { + + /** + * Path to the image used for the polygon fill pattern. + */ protected static final String DIAGONAL_FILL_PATH = "images/diagonal-fill-16x16.png"; - /** Center text block on label position when the text is left aligned. */ + /** + * Center text block on label position when the text is left aligned. + */ protected final static Offset LEFT_ALIGN_OFFSET = new Offset(-0.5d, -0.5d, AVKey.FRACTION, AVKey.FRACTION); /** @@ -40,28 +43,27 @@ public class IrregularFireSupportArea extends BasicArea * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.FSUPP_ARS_ARATGT, - TacGrpSidc.FSUPP_ARS_ARATGT_BMARA, - TacGrpSidc.FSUPP_ARS_C2ARS_TGMF, - TacGrpSidc.FSUPP_ARS_C2ARS_FSA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_FFA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_RFA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_ACA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_DA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_TBA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_NFA_IRR, - TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_IRR, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_IRR, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_IRR, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_IRR, - TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_IRR, - TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_IRR); + TacGrpSidc.FSUPP_ARS_ARATGT, + TacGrpSidc.FSUPP_ARS_ARATGT_BMARA, + TacGrpSidc.FSUPP_ARS_C2ARS_TGMF, + TacGrpSidc.FSUPP_ARS_C2ARS_FSA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_FFA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_RFA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_ACA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_DA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_TBA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_NFA_IRR, + TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_IRR, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_IRR, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_IRR, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_IRR, + TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_IRR, + TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_IRR); } /** @@ -69,8 +71,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public IrregularFireSupportArea(String sidc) - { + public IrregularFireSupportArea(String sidc) { super(sidc); this.setShowHostileIndicator(false); } @@ -81,44 +82,39 @@ public IrregularFireSupportArea(String sidc) * template in MIL-STD-2525C. * * @return A Set containing the function IDs of graphics that support a date/time label separate from the graphic's - * main label. + * main label. */ - public static Set getGraphicsWithTimeLabel() - { + public static Set getGraphicsWithTimeLabel() { return new HashSet(Arrays.asList( - TacGrpSidc.FSUPP_ARS_C2ARS_FSA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_DA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_TBA_IRR, - TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_IRR, - TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_IRR, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_IRR, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_IRR, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_IRR)); + TacGrpSidc.FSUPP_ARS_C2ARS_FSA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_DA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_TBA_IRR, + TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_IRR, + TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_IRR, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_IRR, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_IRR, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_IRR)); } @Override - protected void createLabels() - { + protected void createLabels() { FireSupportTextBuilder textBuilder = new FireSupportTextBuilder(); String[] allText = textBuilder.createText(this); String text = allText[0]; - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { TacticalGraphicLabel mainLabel = this.addLabel(text); mainLabel.setTextAlign(this.getLabelAlignment()); - if (this.isFilled()) - { + if (this.isFilled()) { mainLabel.setEffect(AVKey.TEXT_EFFECT_NONE); mainLabel.setDrawInterior(true); } } - if (allText.length > 1 && !WWUtil.isEmpty(allText[1])) - { + if (allText.length > 1 && !WWUtil.isEmpty(allText[1])) { TacticalGraphicLabel timeLabel = this.addLabel(allText[1]); timeLabel.setTextAlign(AVKey.RIGHT); @@ -128,16 +124,13 @@ protected void createLabels() } @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { // Determine main label position super.determineLabelPositions(dc); - if (this.labels.size() > 1) - { + if (this.labels.size() > 1) { Position pos = this.computeTimeLabelPosition(dc); - if (pos != null) - { + if (pos != null) { this.labels.get(1).setPosition(pos); } } @@ -150,8 +143,7 @@ protected void determineLabelPositions(DrawContext dc) * * @return Position for the time range label, or null if the position cannot be determined. */ - protected Position computeTimeLabelPosition(DrawContext dc) - { + protected Position computeTimeLabelPosition(DrawContext dc) { Iterable positions = this.polygon.getLocations(dc.getGlobe()); // Find the North-West corner of the bounding sector. @@ -163,19 +155,16 @@ protected Position computeTimeLabelPosition(DrawContext dc) // We want to place the label at the North-West corner of the polygon. Loop through the locations // and find the one that is closest so the North-West corner of the bounding sector. - for (LatLon location : positions) - { + for (LatLon location : positions) { Angle dist = LatLon.greatCircleDistance(location, nwCorner); - if (dist.compareTo(minDistance) < 0) - { + if (dist.compareTo(minDistance) < 0) { minDistance = dist; nwMost = location; } } // Place the time label at the North-West position. - if (nwMost != null) - { + if (nwMost != null) { return new Position(nwMost, 0); } return null; @@ -187,15 +176,15 @@ protected Position computeTimeLabelPosition(DrawContext dc) * @return Alignment for the main label. One of AVKey.CENTER, AVKey.LEFT, or AVKey.RIGHT. */ @Override - protected String getLabelAlignment() - { + protected String getLabelAlignment() { boolean isACA = TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_IRR.equalsIgnoreCase(this.maskedSymbolCode); // Airspace Coordination Area labels are left aligned. All others are center aligned. - if (isACA) + if (isACA) { return AVKey.LEFT; - else + } else { return AVKey.CENTER; + } } /** @@ -205,27 +194,27 @@ protected String getLabelAlignment() * @return Offset to apply to the main label. */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { boolean isACA = TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_IRR.equalsIgnoreCase(this.maskedSymbolCode); // Airspace Coordination Area labels are left aligned. Adjust the offset to center the left aligned label // in the circle. (This is not necessary with a center aligned label because centering the text automatically // centers the label in the circle). - if (isACA) + if (isACA) { return LEFT_ALIGN_OFFSET; - else + } else { return super.getDefaultLabelOffset(); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); - if (this.isFilled()) - { + if (this.isFilled()) { // Enable the polygon interior and set the image source to draw a fill pattern of diagonal lines. attributes.setDrawInterior(true); attributes.setImageSource(this.getImageSource()); @@ -237,11 +226,10 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) * * @return true if the polygon must be filled, otherwise false. */ - protected boolean isFilled() - { + protected boolean isFilled() { return TacGrpSidc.FSUPP_ARS_C2ARS_NFA_IRR.equalsIgnoreCase(this.maskedSymbolCode) - || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_IRR.equalsIgnoreCase(this.maskedSymbolCode) - || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_IRR.equalsIgnoreCase(this.maskedSymbolCode); + || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_IRR.equalsIgnoreCase(this.maskedSymbolCode) + || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_IRR.equalsIgnoreCase(this.maskedSymbolCode); } /** @@ -249,8 +237,7 @@ protected boolean isFilled() * * @return The source of the polygon fill pattern. */ - protected Object getImageSource() - { + protected Object getImageSource() { return DIAGONAL_FILL_PATH; } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/LimitedAccessArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/LimitedAccessArea.java index 27eafdcdec..0c31b54ee2 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/LimitedAccessArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/LimitedAccessArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.WorldWind; @@ -26,18 +25,22 @@ * @author pabercrombie * @version $Id: LimitedAccessArea.java 555 2012-04-25 18:59:29Z pabercrombie $ */ -public class LimitedAccessArea extends AbstractMilStd2525TacticalGraphic -{ +public class LimitedAccessArea extends AbstractMilStd2525TacticalGraphic { + protected TacticalSymbol symbol; protected Path path; protected Position symbolPosition; protected Position attachmentPosition; - /** Altitude mode for this graphic. */ + /** + * Altitude mode for this graphic. + */ protected int altitudeMode = WorldWind.CLAMP_TO_GROUND; - /** Attributes applied to the symbol. */ + /** + * Attributes applied to the symbol. + */ protected TacticalSymbolAttributes symbolAttributes; /** @@ -45,40 +48,34 @@ public class LimitedAccessArea extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_GNL_ARS_LAARA); } - public LimitedAccessArea(String symbolCode) - { + public LimitedAccessArea(String symbolCode) { super(symbolCode); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) - { + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) { this.setSymbol((String) value); - } - else - { + } else { super.setModifier(modifier, value); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) - { + public Object getModifier(String modifier) { + if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) { return this.getSymbol(); - } - else - { + } else { return super.getModifier(modifier); } } @@ -88,8 +85,7 @@ public Object getModifier(String modifier) * * @return The symbol drawn at the center of the range fan. May be null. */ - public String getSymbol() - { + public String getSymbol() { return this.symbol != null ? this.symbol.getIdentifier() : null; } @@ -99,19 +95,16 @@ public String getSymbol() * center position. * * @param sidc Identifier for a MIL-STD-2525C symbol to draw at the center of the range fan. May be null to indicate - * that no symbol is drawn. + * that no symbol is drawn. */ - public void setSymbol(String sidc) - { - if (sidc != null) - { - if (this.symbolAttributes == null) + public void setSymbol(String sidc) { + if (sidc != null) { + if (this.symbolAttributes == null) { this.symbolAttributes = new BasicTacticalSymbolAttributes(); + } this.symbol = this.createSymbol(sidc); - } - else - { + } else { // Null value indicates no symbol. this.symbol = null; this.symbolAttributes = null; @@ -125,8 +118,7 @@ public void setSymbol(String sidc) * * @return this graphic's altitude mode. */ - public int getAltitudeMode() - { + public int getAltitudeMode() { return this.altitudeMode; } @@ -141,114 +133,121 @@ public int getAltitudeMode() * * @param altitudeMode this graphic new altitude mode. */ - public void setAltitudeMode(int altitudeMode) - { + public void setAltitudeMode(int altitudeMode) { this.altitudeMode = altitudeMode; - if (this.symbol != null) + if (this.symbol != null) { this.symbol.setAltitudeMode(altitudeMode); - if (this.path != null) + } + if (this.path != null) { this.path.setAltitudeMode(altitudeMode); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void doRenderGraphic(DrawContext dc) - { - if (this.symbol != null) + protected void doRenderGraphic(DrawContext dc) { + if (this.symbol != null) { this.symbol.render(dc); + } - if (this.path != null) + if (this.path != null) { this.path.render(dc); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void applyDelegateOwner(Object owner) - { - if (this.symbol != null) + protected void applyDelegateOwner(Object owner) { + if (this.symbol != null) { this.symbol.setDelegateOwner(owner); - if (this.path != null) + } + if (this.path != null) { this.path.setDelegateOwner(owner); + } } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { List positions = new ArrayList(); - if (this.symbolPosition != null) + if (this.symbolPosition != null) { positions.add(this.symbolPosition); - if (this.attachmentPosition != null) + } + if (this.attachmentPosition != null) { positions.add(this.attachmentPosition); + } return positions; } - /** {@inheritDoc} */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + /** + * {@inheritDoc} + */ + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Iterator iterator = positions.iterator(); - if (iterator.hasNext()) - { + if (iterator.hasNext()) { this.symbolPosition = iterator.next(); - } - else - { + } else { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (iterator.hasNext()) + if (iterator.hasNext()) { this.attachmentPosition = iterator.next(); + } - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.setPosition(this.symbolPosition); } - if (this.attachmentPosition != null) - { - if (this.path == null) + if (this.attachmentPosition != null) { + if (this.path == null) { this.path = this.createPath(); + } this.path.setPositions(Arrays.asList(this.symbolPosition, this.attachmentPosition)); } } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.symbolPosition; } - /** {@inheritDoc} Overridden to update symbol attributes. */ + /** + * {@inheritDoc} Overridden to update symbol attributes. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply active attributes to the symbol. - if (this.symbolAttributes != null) - { + if (this.symbolAttributes != null) { ShapeAttributes activeAttributes = this.getActiveShapeAttributes(); this.symbolAttributes.setOpacity(activeAttributes.getInteriorOpacity()); this.symbolAttributes.setScale(this.activeOverrides.getScale()); } } - protected TacticalSymbol createSymbol(String sidc) - { + protected TacticalSymbol createSymbol(String sidc) { Position symbolPosition = this.getReferencePosition(); TacticalSymbol symbol = new LimitedAccessSymbol(sidc, - symbolPosition != null ? symbolPosition : Position.ZERO); + symbolPosition != null ? symbolPosition : Position.ZERO); symbol.setDelegateOwner(this); symbol.setAttributes(this.symbolAttributes); symbol.setAltitudeMode(this.getAltitudeMode()); @@ -260,8 +259,7 @@ protected TacticalSymbol createSymbol(String sidc) * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath() - { + protected Path createPath() { Path path = new Path(); path.setFollowTerrain(true); path.setPathType(AVKey.LINEAR); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/LimitedAccessSymbol.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/LimitedAccessSymbol.java index 7d8907e233..01c73bf998 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/LimitedAccessSymbol.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/LimitedAccessSymbol.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.Configuration; @@ -24,50 +23,50 @@ * @version $Id: LimitedAccessSymbol.java 545 2012-04-24 22:29:21Z pabercrombie $ * @see LimitedAccessArea */ -public class LimitedAccessSymbol extends AbstractTacticalSymbol -{ - /** Identifier for the symbol. */ +public class LimitedAccessSymbol extends AbstractTacticalSymbol { + + /** + * Identifier for the symbol. + */ protected String symbolId; - public LimitedAccessSymbol(String sidc, Position position) - { + public LimitedAccessSymbol(String sidc, Position position) { super(position); this.init(sidc); } - protected void init(String symbolId) - { + protected void init(String symbolId) { this.symbolId = symbolId; // Configure this tactical symbol's icon retriever and modifier retriever with either the configuration value or // the default value (in that order of precedence). String iconRetrieverPath = Configuration.getStringValue(AVKey.MIL_STD_2525_ICON_RETRIEVER_PATH, - MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); + MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); this.setIconRetriever(new IconRetriever(iconRetrieverPath)); this.setModifierRetriever(new MilStd2525ModifierRetriever(iconRetrieverPath)); this.setOffset(Offset.fromFraction(0.5, 0.0)); } - /** {@inheritDoc} */ - public String getIdentifier() - { + /** + * {@inheritDoc} + */ + public String getIdentifier() { return this.symbolId; } - /** Icon retriever to retrieve an icon framed in a pentagon. */ - static class IconRetriever extends MilStd2525IconRetriever - { - public IconRetriever(String retrieverPath) - { + /** + * Icon retriever to retrieve an icon framed in a pentagon. + */ + static class IconRetriever extends MilStd2525IconRetriever { + + public IconRetriever(String retrieverPath) { super(retrieverPath); } @Override - public BufferedImage createIcon(String symbolId, AVList params) - { - if (symbolId == null) - { + public BufferedImage createIcon(String symbolId, AVList params) { + if (symbolId == null) { String msg = Logging.getMessage("nullValue.SymbolCodeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -94,18 +93,17 @@ public BufferedImage createIcon(String symbolId, AVList params) // \ / // \ / // \ / - BufferedImage pentagonImg = new BufferedImage(pentagonWidth, pentagonHeight, image.getType()); int lineWidth = (int) Math.max(imgWidth * 0.03, 1); Color color = this.getColorFromParams(params); - if (color == null) + if (color == null) { color = this.getColorForStandardIdentity(symbolCode); + } Graphics2D g = null; - try - { + try { g = pentagonImg.createGraphics(); g.setColor(color); g.setStroke(new BasicStroke(lineWidth)); @@ -118,11 +116,10 @@ public BufferedImage createIcon(String symbolId, AVList params) g.drawLine(pentagonWidth - 1, 0, pentagonWidth - 1, imgHeight); // Right edge of rect g.drawLine(0, imgHeight, pentagonWidth / 2, pentagonHeight); // Left side of triangle g.drawLine(pentagonWidth, imgHeight, pentagonWidth / 2, pentagonHeight); // Right side of triangle - } - finally - { - if (g != null) + } finally { + if (g != null) { g.dispose(); + } } return pentagonImg; @@ -134,13 +131,13 @@ public BufferedImage createIcon(String symbolId, AVList params) * @param params Parameter list. * * @return The value of the AVKey.COLOR parameter, if such a parameter exists and is of type java.awt.Color. - * Returns null if the parameter list is null, if there is no value for key AVKey.COLOR, or if the value - * is not a Color. + * Returns null if the parameter list is null, if there is no value for key AVKey.COLOR, or if the value is not + * a Color. */ - protected Color getColorFromParams(AVList params) - { - if (params == null) + protected Color getColorFromParams(AVList params) { + if (params == null) { return null; + } Object o = params.getValue(AVKey.COLOR); return (o instanceof Color) ? (Color) o : null; @@ -153,8 +150,7 @@ protected Color getColorFromParams(AVList params) * * @return Color to apply based on the standard identity. (Red for hostile entities, black for friendly, etc.) */ - protected Color getColorForStandardIdentity(SymbolCode code) - { + protected Color getColorForStandardIdentity(SymbolCode code) { return MilStd2525Util.getDefaultGraphicMaterial(code).getDiffuse(); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/MinimumSafeDistanceZones.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/MinimumSafeDistanceZones.java index b7b27ff52b..a27de2d18e 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/MinimumSafeDistanceZones.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/MinimumSafeDistanceZones.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -24,20 +23,26 @@ * @author pabercrombie * @version $Id: MinimumSafeDistanceZones.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MinimumSafeDistanceZones extends AbstractMilStd2525TacticalGraphic implements PreRenderable -{ +public class MinimumSafeDistanceZones extends AbstractMilStd2525TacticalGraphic implements PreRenderable { + /** * Default angle used to position the graphic's labels. This default angle (60 degrees) is chosen to match the * graphic template defined by MIL-STD-2525C, pg. 613. */ public final static Angle DEFAULT_LABEL_ANGLE = Angle.fromDegrees(60.0); - /** Position of the center of the range fan. */ + /** + * Position of the center of the range fan. + */ protected Iterable positions; - /** Rings that make up the range fan. */ + /** + * Rings that make up the range fan. + */ protected List rings; - /** Position the labels along a line radiating out from the center of the circle at this angle from North. */ + /** + * Position the labels along a line radiating out from the center of the circle at this angle from North. + */ protected Angle labelAngle = DEFAULT_LABEL_ANGLE; /** @@ -45,8 +50,7 @@ public class MinimumSafeDistanceZones extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.MOBSU_CBRN_MSDZ); } @@ -55,8 +59,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public MinimumSafeDistanceZones(String sidc) - { + public MinimumSafeDistanceZones(String sidc) { super(sidc); } @@ -66,8 +69,7 @@ public MinimumSafeDistanceZones(String sidc) * * @return The angle used to position this graphic's labels. */ - public Angle getLabelAngle() - { + public Angle getLabelAngle() { return this.labelAngle; } @@ -77,10 +79,8 @@ public Angle getLabelAngle() * * @param angle The angle used to position this graphic's labels. */ - public void setLabelAngle(Angle angle) - { - if (angle == null) - { + public void setLabelAngle(Angle angle) { + if (angle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -94,8 +94,7 @@ public void setLabelAngle(Angle angle) * * @return The range fan center position. */ - public Position getPosition() - { + public Position getPosition() { return this.getReferencePosition(); } @@ -104,8 +103,7 @@ public Position getPosition() * * @param position The new center position. */ - public void setPosition(Position position) - { + public void setPosition(Position position) { this.moveTo(position); } @@ -113,28 +111,22 @@ public void setPosition(Position position) * {@inheritDoc} * * @param positions Control points. This graphic uses only one control point, which determines the center of the - * circle. + * circle. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { // Ensure that the iterable provides at least four positions. Iterator iterator = positions.iterator(); - for (int i = 0; i < 3; i++) - { + for (int i = 0; i < 3; i++) { iterator.next(); } - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -144,41 +136,41 @@ public void setPositions(Iterable positions) this.rings = null; } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return this.positions; } - /** {@inheritDoc} */ - public Position getReferencePosition() - { - if (positions != null) - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { + if (positions != null) { Iterator iterator = this.positions.iterator(); - if (iterator.hasNext()) + if (iterator.hasNext()) { return iterator.next(); + } } return null; } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } - if (this.rings == null) - { + if (this.rings == null) { this.createShapes(dc); } this.determineActiveAttributes(); - for (SurfaceCircle ring : this.rings) - { + for (SurfaceCircle ring : this.rings) { ring.preRender(dc); } } @@ -188,22 +180,21 @@ public void preRender(DrawContext dc) * * @param dc Current draw context. */ - protected void doRenderGraphic(DrawContext dc) - { - for (SurfaceCircle ring : this.rings) - { + protected void doRenderGraphic(DrawContext dc) { + for (SurfaceCircle ring : this.rings) { ring.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.rings == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.rings == null) { return; + } - for (SurfaceCircle ring : this.rings) - { + for (SurfaceCircle ring : this.rings) { ring.setDelegateOwner(owner); } } @@ -213,10 +204,10 @@ protected void applyDelegateOwner(Object owner) * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { - if (this.positions == null) + protected void createShapes(DrawContext dc) { + if (this.positions == null) { return; + } this.rings = new ArrayList(); @@ -225,8 +216,7 @@ protected void createShapes(DrawContext dc) Position center = iterator.next(); double globeRadius = dc.getGlobe().getRadius(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { SurfaceCircle ring = this.createCircle(); ring.setCenter(center); @@ -240,23 +230,25 @@ protected void createShapes(DrawContext dc) } } - /** Create labels for each ring. */ + /** + * Create labels for each ring. + */ @Override - protected void createLabels() - { - for (int i = 1; i <= this.rings.size(); i++) - { + protected void createLabels() { + for (int i = 1; i <= this.rings.size(); i++) { this.addLabel(String.valueOf(i)); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { Position center = this.getReferencePosition(); - if (center == null) + if (center == null) { return; + } // Position the labels along a line radiating out from the center of the circle. The angle (60 degrees) is // chosen to match the graphic template defined by MIL-STD-2525C, pg. 613. @@ -265,8 +257,7 @@ protected void determineLabelPositions(DrawContext dc) Angle labelAngle = this.getLabelAngle(); int i = 0; - for (SurfaceCircle ring : this.rings) - { + for (SurfaceCircle ring : this.rings) { double radius = ring.getRadius(); LatLon ll = LatLon.greatCircleEndPosition(center, labelAngle.radians, radius / globeRadius); @@ -281,8 +272,7 @@ protected void determineLabelPositions(DrawContext dc) * * @return New circle. */ - protected SurfaceCircle createCircle() - { + protected SurfaceCircle createCircle() { SurfaceCircle circle = new SurfaceCircle(); circle.setDelegateOwner(this.getActiveDelegateOwner()); circle.setAttributes(this.getActiveShapeAttributes()); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/OffenseArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/OffenseArea.java index f715bb807a..afaca03dac 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/OffenseArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/OffenseArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.symbology.milstd2525.graphics.TacGrpSidc; @@ -18,20 +17,19 @@ * @author pabercrombie * @version $Id: OffenseArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OffenseArea extends BasicArea -{ +public class OffenseArea extends BasicArea { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_OFF_ARS_ASTPSN, - TacGrpSidc.C2GM_OFF_ARS_ATKPSN, - TacGrpSidc.C2GM_OFF_ARS_OBJ, - TacGrpSidc.C2GM_OFF_ARS_PBX); + TacGrpSidc.C2GM_OFF_ARS_ASTPSN, + TacGrpSidc.C2GM_OFF_ARS_ATKPSN, + TacGrpSidc.C2GM_OFF_ARS_OBJ, + TacGrpSidc.C2GM_OFF_ARS_PBX); } /** @@ -39,34 +37,35 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public OffenseArea(String sidc) - { + public OffenseArea(String sidc) { super(sidc); this.setShowHostileIndicator(false); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected String createLabelText() - { + protected String createLabelText() { // Penetration box graphic does not support text modifiers. - if (TacGrpSidc.C2GM_OFF_ARS_PBX.equalsIgnoreCase(this.maskedSymbolCode)) + if (TacGrpSidc.C2GM_OFF_ARS_PBX.equalsIgnoreCase(this.maskedSymbolCode)) { return null; + } return super.createLabelText(); } @Override - protected String getGraphicLabel() - { + protected String getGraphicLabel() { String code = this.maskedSymbolCode; - if (TacGrpSidc.C2GM_OFF_ARS_ASTPSN.equalsIgnoreCase(code)) + if (TacGrpSidc.C2GM_OFF_ARS_ASTPSN.equalsIgnoreCase(code)) { return "ASLT\nPSN"; - else if (TacGrpSidc.C2GM_OFF_ARS_ATKPSN.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_OFF_ARS_ATKPSN.equalsIgnoreCase(code)) { return "ATK"; - else if (TacGrpSidc.C2GM_OFF_ARS_OBJ.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_OFF_ARS_OBJ.equalsIgnoreCase(code)) { return "OBJ"; + } return ""; } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularFireSupportArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularFireSupportArea.java index 6f85400fd0..313a882510 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularFireSupportArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularFireSupportArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.avlist.AVKey; @@ -27,11 +26,15 @@ * @author pabercrombie * @version $Id: RectangularFireSupportArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RectangularFireSupportArea extends AbstractRectangularGraphic implements TacticalQuad, PreRenderable -{ - /** Path to the image used for the polygon fill pattern. */ +public class RectangularFireSupportArea extends AbstractRectangularGraphic implements TacticalQuad, PreRenderable { + + /** + * Path to the image used for the polygon fill pattern. + */ protected static final String DIAGONAL_FILL_PATH = "images/diagonal-fill-16x16.png"; - /** Center text block on label position when the text is left aligned. */ + /** + * Center text block on label position when the text is left aligned. + */ protected final static Offset LEFT_ALIGN_OFFSET = new Offset(-0.5d, -0.5d, AVKey.FRACTION, AVKey.FRACTION); /** @@ -39,25 +42,24 @@ public class RectangularFireSupportArea extends AbstractRectangularGraphic imple * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.FSUPP_ARS_C2ARS_FSA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_FFA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_RFA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_ACA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_DA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_TBA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_NFA_RTG, - TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_RTG, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_RTG, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_RTG, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_RTG, - TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_RTG, - TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_RTG); + TacGrpSidc.FSUPP_ARS_C2ARS_FSA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_FFA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_RFA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_ACA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_DA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_TBA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_NFA_RTG, + TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_RTG, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_RTG, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_RTG, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_RTG, + TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_RTG, + TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_RTG); } /** @@ -65,8 +67,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public RectangularFireSupportArea(String sidc) - { + public RectangularFireSupportArea(String sidc) { super(sidc); } @@ -76,45 +77,42 @@ public RectangularFireSupportArea(String sidc) * template in MIL-STD-2525C. * * @return A Set containing the function IDs of graphics that support a date/time label separate from the graphic's - * main label. + * main label. */ - public static Set getGraphicsWithTimeLabel() - { + public static Set getGraphicsWithTimeLabel() { return new HashSet(Arrays.asList( - TacGrpSidc.FSUPP_ARS_C2ARS_FSA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_DA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_TBA_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_RTG, - TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_RTG, - TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_RTG, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_RTG, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_RTG, - TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_RTG)); + TacGrpSidc.FSUPP_ARS_C2ARS_FSA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_DA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_ZOR_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_TBA_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_TVAR_RTG, + TacGrpSidc.FSUPP_ARS_C2ARS_SNSZ_RTG, + TacGrpSidc.FSUPP_ARS_TGTAQZ_ATIZ_RTG, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CFFZ_RTG, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CNS_RTG, + TacGrpSidc.FSUPP_ARS_TGTAQZ_CFZ_RTG)); } - /** Create labels for the graphic. */ + /** + * Create labels for the graphic. + */ @Override - protected void createLabels() - { + protected void createLabels() { FireSupportTextBuilder textBuilder = new FireSupportTextBuilder(); String[] allText = textBuilder.createText(this); String text = allText[0]; - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { TacticalGraphicLabel mainLabel = this.addLabel(text); mainLabel.setTextAlign(this.getMainLabelTextAlign()); - if (this.isFilled()) - { + if (this.isFilled()) { mainLabel.setEffect(AVKey.TEXT_EFFECT_NONE); mainLabel.setDrawInterior(true); } } - if (allText.length > 1 && !WWUtil.isEmpty(allText[1])) - { + if (allText.length > 1 && !WWUtil.isEmpty(allText[1])) { TacticalGraphicLabel timeLabel = this.addLabel(allText[1]); timeLabel.setTextAlign(AVKey.RIGHT); @@ -124,13 +122,11 @@ protected void createLabels() } @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { Position center = new Position(this.quad.getCenter(), 0); this.labels.get(0).setPosition(center); - if (this.labels.size() > 1) - { + if (this.labels.size() > 1) { double hw = this.quad.getWidth() / 2.0; double hh = this.quad.getHeight() / 2.0; double globeRadius = dc.getGlobe().getRadiusAt(center.getLatitude(), center.getLongitude()); @@ -153,15 +149,15 @@ protected void determineLabelPositions(DrawContext dc) * * @return Text alignment for the main label. */ - protected String getMainLabelTextAlign() - { + protected String getMainLabelTextAlign() { boolean isACA = TacGrpSidc.FSUPP_ARS_C2ARS_ACA_RTG.equalsIgnoreCase(this.maskedSymbolCode); // Airspace Coordination Area labels are left aligned. All others are center aligned. - if (isACA) + if (isACA) { return AVKey.LEFT; - else + } else { return AVKey.CENTER; + } } /** @@ -171,27 +167,27 @@ protected String getMainLabelTextAlign() * @return Offset to apply to the main label. */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { boolean isACA = TacGrpSidc.FSUPP_ARS_C2ARS_ACA_RTG.equalsIgnoreCase(this.maskedSymbolCode); // Airspace Coordination Area labels are left aligned. Adjust the offset to center the left aligned label // in the circle. (This is not necessary with a center aligned label because centering the text automatically // centers the label in the circle). - if (isACA) + if (isACA) { return LEFT_ALIGN_OFFSET; - else + } else { return super.getDefaultLabelOffset(); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); - if (this.isFilled()) - { + if (this.isFilled()) { // Enable the polygon interior and set the image source to draw a fill pattern of diagonal lines. attributes.setDrawInterior(true); attributes.setImageSource(this.getImageSource()); @@ -203,11 +199,10 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) * * @return true if the polygon must be filled, otherwise false. */ - protected boolean isFilled() - { + protected boolean isFilled() { return TacGrpSidc.FSUPP_ARS_C2ARS_NFA_RTG.equalsIgnoreCase(this.maskedSymbolCode) - || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_RTG.equalsIgnoreCase(this.maskedSymbolCode) - || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_RTG.equalsIgnoreCase(this.maskedSymbolCode); + || TacGrpSidc.FSUPP_ARS_KLBOX_BLUE_RTG.equalsIgnoreCase(this.maskedSymbolCode) + || TacGrpSidc.FSUPP_ARS_KLBOX_PURPLE_RTG.equalsIgnoreCase(this.maskedSymbolCode); } /** @@ -215,8 +210,7 @@ protected boolean isFilled() * * @return The source of the polygon fill pattern. */ - protected Object getImageSource() - { + protected Object getImageSource() { return DIAGONAL_FILL_PATH; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularPositionArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularPositionArea.java index 1050e2740d..f374a89047 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularPositionArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularPositionArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -18,15 +17,14 @@ * @author pabercrombie * @version $Id: RectangularPositionArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RectangularPositionArea extends AbstractRectangularGraphic -{ +public class RectangularPositionArea extends AbstractRectangularGraphic { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.FSUPP_ARS_C2ARS_PAA_RTG); } @@ -35,15 +33,15 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public RectangularPositionArea(String sidc) - { + public RectangularPositionArea(String sidc) { super(sidc); } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { // This graphic has labels at the top, bottom, left, and right of the quad. this.addLabel("PAA"); this.addLabel("PAA"); @@ -52,19 +50,18 @@ protected void createLabels() } @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { Iterable corners = this.quad.getLocations(dc.getGlobe()); - if (corners == null) + if (corners == null) { return; + } Iterator iterator = corners.iterator(); // Position the labels at the midpoint of each side of the quad. int i = 0; LatLon locA = iterator.next(); - while (iterator.hasNext() && i < this.labels.size()) - { + while (iterator.hasNext() && i < this.labels.size()) { LatLon locB = iterator.next(); // Find the midpoint of the two corners @@ -77,4 +74,4 @@ protected void determineLabelPositions(DrawContext dc) i += 1; } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularTarget.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularTarget.java index ad4613b13f..2300534361 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularTarget.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/RectangularTarget.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.*; @@ -20,15 +19,14 @@ * @author pabercrombie * @version $Id: RectangularTarget.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RectangularTarget extends AbstractRectangularGraphic -{ +public class RectangularTarget extends AbstractRectangularGraphic { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.FSUPP_ARS_ARATGT_RTGTGT); } @@ -37,8 +35,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public RectangularTarget(String sidc) - { + public RectangularTarget(String sidc) { super(sidc); } @@ -48,8 +45,7 @@ public RectangularTarget(String sidc) * * @return this shape's heading, or null if no heading has been specified. */ - public Angle getHeading() - { + public Angle getHeading() { return this.quad.getHeading(); } @@ -59,8 +55,7 @@ public Angle getHeading() * * @param heading this shape's heading. */ - public void setHeading(Angle heading) - { + public void setHeading(Angle heading) { this.quad.setHeading(heading); this.onModifierChanged(); } @@ -69,20 +64,17 @@ public void setHeading(Angle heading) * {@inheritDoc} * * @param positions Control points. This graphic uses only one control point, which determines the center of the - * quad. + * quad. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Iterator iterator = positions.iterator(); - if (!iterator.hasNext()) - { + if (!iterator.hasNext()) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -91,60 +83,57 @@ public void setPositions(Iterable positions) this.quad.setCenter(iterator.next()); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.DISTANCE.equals(modifier) && (value instanceof Iterable)) - { + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.DISTANCE.equals(modifier) && (value instanceof Iterable)) { Iterator iterator = ((Iterable) value).iterator(); this.setWidth((Double) iterator.next()); this.setLength((Double) iterator.next()); - } - else if (SymbologyConstants.AZIMUTH.equals(modifier) && (value instanceof Angle)) - { + } else if (SymbologyConstants.AZIMUTH.equals(modifier) && (value instanceof Angle)) { this.setHeading((Angle) value); - } - else - { + } else { super.setModifier(modifier, value); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.DISTANCE.equals(modifier)) + public Object getModifier(String modifier) { + if (SymbologyConstants.DISTANCE.equals(modifier)) { return Arrays.asList(this.getWidth(), this.getLength()); - else if (SymbologyConstants.AZIMUTH.equals(modifier)) + } else if (SymbologyConstants.AZIMUTH.equals(modifier)) { return this.quad.getHeading(); - else + } else { return super.getModifier(modifier); + } } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(new Position(this.quad.getCenter(), 0)); } - /** Create labels for the graphic. */ + /** + * Create labels for the graphic. + */ @Override - protected void createLabels() - { + protected void createLabels() { String text = this.getText(); - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { this.addLabel(this.getText()); } } @Override - protected void determineLabelPositions(DrawContext dc) - { - if (!WWUtil.isEmpty(this.labels)) - { + protected void determineLabelPositions(DrawContext dc) { + if (!WWUtil.isEmpty(this.labels)) { this.labels.get(0).setPosition(new Position(this.quad.getCenter(), 0)); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SearchArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SearchArea.java index ccc79fc550..fe8c19c9cc 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SearchArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SearchArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.WorldWind; @@ -24,35 +23,59 @@ * @author pabercrombie * @version $Id: SearchArea.java 560 2012-04-26 16:28:24Z pabercrombie $ */ -public class SearchArea extends AbstractMilStd2525TacticalGraphic implements PreRenderable -{ - /** Default length of the arrowhead, as a fraction of the total line length. */ +public class SearchArea extends AbstractMilStd2525TacticalGraphic implements PreRenderable { + + /** + * Default length of the arrowhead, as a fraction of the total line length. + */ public final static double DEFAULT_ARROWHEAD_LENGTH = 0.1; - /** Default angle of the arrowhead. */ + /** + * Default angle of the arrowhead. + */ public final static Angle DEFAULT_ARROWHEAD_ANGLE = Angle.fromDegrees(60.0); - /** Length of the arrowhead from base to tip, as a fraction of the total line length. */ + /** + * Length of the arrowhead from base to tip, as a fraction of the total line length. + */ protected Angle arrowAngle = DEFAULT_ARROWHEAD_ANGLE; - /** Angle of the arrowhead. */ + /** + * Angle of the arrowhead. + */ protected double arrowLength = DEFAULT_ARROWHEAD_LENGTH; - /** First control point. */ + /** + * First control point. + */ protected Position position1; - /** Second control point. */ + /** + * Second control point. + */ protected Position position2; - /** Third control point. */ + /** + * Third control point. + */ protected Position position3; - /** Path used to render the line. */ + /** + * Path used to render the line. + */ protected Path[] paths; - /** Symbol drawn at the center of the range fan. */ + /** + * Symbol drawn at the center of the range fan. + */ protected TacticalSymbol symbol; - /** Attributes applied to the symbol. */ + /** + * Attributes applied to the symbol. + */ protected TacticalSymbolAttributes symbolAttributes; - /** Polygon render an arrow head at the end of one of the graphic's legs. */ + /** + * Polygon render an arrow head at the end of one of the graphic's legs. + */ protected SurfacePolygon arrowHead2; - /** Polygon render an arrow head at the end of one of the graphic's legs. */ + /** + * Polygon render an arrow head at the end of one of the graphic's legs. + */ protected SurfacePolygon arrowHead1; /** @@ -60,8 +83,7 @@ public class SearchArea extends AbstractMilStd2525TacticalGraphic implements Pre * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_GNL_ARS_SRHARA); } @@ -70,8 +92,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public SearchArea(String sidc) - { + public SearchArea(String sidc) { super(sidc); } @@ -80,8 +101,7 @@ public SearchArea(String sidc) * * @return Angle of the arrowhead in the graphic. */ - public Angle getArrowAngle() - { + public Angle getArrowAngle() { return this.arrowAngle; } @@ -90,17 +110,14 @@ public Angle getArrowAngle() * * @param arrowAngle The angle of the arrowhead. Must be greater than zero degrees and less than 90 degrees. */ - public void setArrowAngle(Angle arrowAngle) - { - if (arrowAngle == null) - { + public void setArrowAngle(Angle arrowAngle) { + if (arrowAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) - { + if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) { String msg = Logging.getMessage("generic.AngleOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -114,8 +131,7 @@ public void setArrowAngle(Angle arrowAngle) * * @return The length of the arrowhead as a fraction of the total line length. */ - public double getArrowLength() - { + public double getArrowLength() { return this.arrowLength; } @@ -123,12 +139,10 @@ public double getArrowLength() * Specifies the length of the arrowhead. * * @param arrowLength Length of the arrowhead as a fraction of the total line length. If the arrowhead length is - * 0.25, then the arrowhead length will be one quarter of the total line length. + * 0.25, then the arrowhead length will be one quarter of the total line length. */ - public void setArrowLength(double arrowLength) - { - if (arrowLength < 0) - { + public void setArrowLength(double arrowLength) { + if (arrowLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -142,8 +156,7 @@ public void setArrowLength(double arrowLength) * * @return The symbol drawn at the center of the range fan. May be null. */ - public String getSymbol() - { + public String getSymbol() { return this.symbol != null ? this.symbol.getIdentifier() : null; } @@ -153,19 +166,16 @@ public String getSymbol() * center position. * * @param sidc Identifier for a MIL-STD-2525C symbol to draw at the center of the range fan. May be null to indicate - * that no symbol is drawn. + * that no symbol is drawn. */ - public void setSymbol(String sidc) - { - if (sidc != null) - { - if (this.symbolAttributes == null) + public void setSymbol(String sidc) { + if (sidc != null) { + if (this.symbolAttributes == null) { this.symbolAttributes = new BasicTacticalSymbolAttributes(); + } this.symbol = this.createSymbol(sidc, this.position1, this.symbolAttributes); - } - else - { + } else { // Null value indicates no symbol. this.symbol = null; this.symbolAttributes = null; @@ -178,24 +188,19 @@ public void setSymbol(String sidc) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.position1 = iterator.next(); this.position2 = iterator.next(); this.position3 = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -205,63 +210,59 @@ public void setPositions(Iterable positions) this.arrowHead1 = null; this.arrowHead2 = null; - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.setPosition(this.position1); } } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.position1, this.position2, this.position3); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.position1; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override @SuppressWarnings("unchecked") - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) - { + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) { this.setSymbol((String) value); - } - else - { + } else { super.setModifier(modifier, value); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) - { + public Object getModifier(String modifier) { + if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) { return this.getSymbol(); - } - else - { + } else { return super.getModifier(modifier); } } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } - if (this.paths == null) - { + if (this.paths == null) { this.createShapes(dc); } @@ -271,11 +272,11 @@ public void preRender(DrawContext dc) this.arrowHead2.preRender(dc); } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - for (Path path : this.paths) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + for (Path path : this.paths) { path.render(dc); } @@ -283,31 +284,33 @@ protected void doRenderGraphic(DrawContext dc) this.arrowHead2.render(dc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void doRenderGraphicModifiers(DrawContext dc) - { + protected void doRenderGraphicModifiers(DrawContext dc) { super.doRenderGraphicModifiers(dc); - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths == null) { return; + } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.setDelegateOwner(owner); } - if (this.symbol != null) + if (this.symbol != null) { this.symbol.setDelegateOwner(owner); + } this.arrowHead1.setDelegateOwner(owner); this.arrowHead2.setDelegateOwner(owner); @@ -318,8 +321,7 @@ protected void applyDelegateOwner(Object owner) * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { this.paths = new Path[2]; int i = 0; @@ -352,8 +354,7 @@ protected void createShapes(DrawContext dc) this.arrowHead2.setLocations(positions); } - protected List computePathPositions(Position startPosition, Position endPosition, Angle delta) - { + protected List computePathPositions(Position startPosition, Position endPosition, Angle delta) { Angle dist = LatLon.greatCircleDistance(startPosition, endPosition); dist = dist.multiply(0.6); @@ -370,17 +371,16 @@ protected List computePathPositions(Position startPosition, Position e /** * Compute the positions of the arrow head of the graphic's legs. * - * @param dc Current draw context - * @param base Position of the arrow's starting point. - * @param tip Position of the arrow head tip. + * @param dc Current draw context + * @param base Position of the arrow's starting point. + * @param tip Position of the arrow head tip. * @param arrowLength Length of the arrowhead as a fraction of the total line length. - * @param arrowAngle Angle of the arrow head. + * @param arrowAngle Angle of the arrow head. * * @return Positions required to draw the arrow head. */ protected List computeArrowheadPositions(DrawContext dc, Position base, Position tip, double arrowLength, - Angle arrowAngle) - { + Angle arrowAngle) { // Build a triangle to represent the arrowhead. The triangle is built from two vectors, one parallel to the // segment, and one perpendicular to it. @@ -413,14 +413,13 @@ protected List computeArrowheadPositions(DrawContext dc, Position base /** * Determine the positions that make up the arrowhead. * - * @param dc Current draw context. + * @param dc Current draw context. * @param startPosition Position of the arrow's base. - * @param endPosition Position of the arrow head tip. + * @param endPosition Position of the arrow head tip. * * @return Positions that define the arrowhead. */ - protected List computeArrowheadPositions(DrawContext dc, Position startPosition, Position endPosition) - { + protected List computeArrowheadPositions(DrawContext dc, Position startPosition, Position endPosition) { Globe globe = dc.getGlobe(); // Arrowhead looks like this: @@ -431,7 +430,6 @@ protected List computeArrowheadPositions(DrawContext dc, Position star // C/ // | | // Length - Vec4 p1 = globe.computePointFromPosition(startPosition); Vec4 pB = globe.computePointFromPosition(endPosition); @@ -460,10 +458,11 @@ protected List computeArrowheadPositions(DrawContext dc, Position star return TacticalGraphicUtil.asPositionList(globe, pA, pB, pC); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); // Enable the polygon interior for the "thick line" polygon. All other parts of the graphic are drawn with Path, @@ -471,15 +470,15 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) attributes.setDrawInterior(true); } - /** {@inheritDoc} Overridden to update symbol attributes. */ + /** + * {@inheritDoc} Overridden to update symbol attributes. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply active attributes to the symbol. - if (this.symbolAttributes != null) - { + if (this.symbolAttributes != null) { ShapeAttributes activeAttributes = this.getActiveShapeAttributes(); this.symbolAttributes.setOpacity(activeAttributes.getInteriorOpacity()); this.symbolAttributes.setScale(this.activeOverrides.getScale()); @@ -493,8 +492,7 @@ protected void determineActiveAttributes() * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(List positions) - { + protected Path createPath(List positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); @@ -504,8 +502,7 @@ protected Path createPath(List positions) return path; } - protected SurfacePolygon createPolygon(List positions) - { + protected SurfacePolygon createPolygon(List positions) { SurfacePolygon polygon = new SurfacePolygon(positions); polygon.setAttributes(this.getActiveShapeAttributes()); return polygon; diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SectorRangeFan.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SectorRangeFan.java index c6d60bb15e..b842ca617e 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SectorRangeFan.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SectorRangeFan.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.WorldWind; @@ -27,16 +26,24 @@ * @author pabercrombie * @version $Id: SectorRangeFan.java 1055 2013-01-01 17:09:32Z dcollins $ */ -public class SectorRangeFan extends AbstractMilStd2525TacticalGraphic implements PreRenderable -{ - /** Default number of intervals used to draw each arcs. */ +public class SectorRangeFan extends AbstractMilStd2525TacticalGraphic implements PreRenderable { + + /** + * Default number of intervals used to draw each arcs. + */ public final static int DEFAULT_NUM_INTERVALS = 32; - /** Default length of the Center Of Sector line, as a fraction of the final range fan radius. */ + /** + * Default length of the Center Of Sector line, as a fraction of the final range fan radius. + */ public final static double DEFAULT_CENTER_OF_SECTOR_LENGTH = 1.2; - /** Default length of the arrowhead, as a fraction of the Center Of Sector line length. */ + /** + * Default length of the arrowhead, as a fraction of the Center Of Sector line length. + */ public final static double DEFAULT_ARROWHEAD_LENGTH = 0.05; - /** Default angle of the arrowhead. */ + /** + * Default angle of the arrowhead. + */ public final static Angle DEFAULT_ARROWHEAD_ANGLE = Angle.fromDegrees(60.0); /** * Azimuth labels are placed to the side of the line that they label. This value specifies a percentage that is @@ -44,44 +51,78 @@ public class SectorRangeFan extends AbstractMilStd2525TacticalGraphic implements */ protected final static double AZIMUTH_LABEL_OFFSET = 0.03; - /** Default number format used to create azimuth and radius labels. */ + /** + * Default number format used to create azimuth and radius labels. + */ public final static NumberFormat DEFAULT_NUMBER_FORMAT = new DecimalFormat("#"); - /** Length of the arrowhead from base to tip, as a fraction of the Center Of Sector line length. */ + /** + * Length of the arrowhead from base to tip, as a fraction of the Center Of Sector line length. + */ protected Angle arrowAngle = DEFAULT_ARROWHEAD_ANGLE; - /** Angle of the arrowhead. */ + /** + * Angle of the arrowhead. + */ protected double arrowLength = DEFAULT_ARROWHEAD_LENGTH; - /** Length of the Center Of Sector line, as a fraction of the last range fan radius. */ + /** + * Length of the Center Of Sector line, as a fraction of the last range fan radius. + */ protected double centerOfSectorLength = DEFAULT_CENTER_OF_SECTOR_LENGTH; - /** Number of intervals used to draw each arcs. */ + /** + * Number of intervals used to draw each arcs. + */ protected int intervals = DEFAULT_NUM_INTERVALS; - /** Number format used to create azimuth labels. */ + /** + * Number format used to create azimuth labels. + */ protected NumberFormat azimuthFormat = DEFAULT_NUMBER_FORMAT; - /** Number format used to create radius labels. */ + /** + * Number format used to create radius labels. + */ protected NumberFormat radiusFormat = DEFAULT_NUMBER_FORMAT; - /** Position of the center of the range fan. */ + /** + * Position of the center of the range fan. + */ protected Position position; - /** Rings that make up the range fan. */ + /** + * Rings that make up the range fan. + */ protected List paths; - /** Polygon to draw a filled arrow head on the Center Of Sector line. */ + /** + * Polygon to draw a filled arrow head on the Center Of Sector line. + */ protected SurfacePolygon arrowHead; - /** Symbol drawn at the center of the range fan. */ + /** + * Symbol drawn at the center of the range fan. + */ protected TacticalSymbol symbol; - /** Attributes applied to the symbol. */ + /** + * Attributes applied to the symbol. + */ protected TacticalSymbolAttributes symbolAttributes; - /** Radii of the range fans, in meters. */ + /** + * Radii of the range fans, in meters. + */ protected Iterable radii; - /** Azimuths of the range fans. The azimuths are specified in pairs, first the left azimuth, then the right azimuth. */ + /** + * Azimuths of the range fans. The azimuths are specified in pairs, first the left azimuth, then the right azimuth. + */ protected Iterable azimuths; - /** Altitudes of the range fans. */ + /** + * Altitudes of the range fans. + */ protected Iterable altitudes; - /** Azimuth of the Center Of Sector arrow. */ + /** + * Azimuth of the Center Of Sector arrow. + */ protected Angle centerAzimuth; - /** Maximum radius in the range fan. */ + /** + * Maximum radius in the range fan. + */ protected double maxRadius; /** @@ -89,8 +130,7 @@ public class SectorRangeFan extends AbstractMilStd2525TacticalGraphic implements * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.FSUPP_ARS_WPNRF_SCR); } @@ -99,8 +139,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public SectorRangeFan(String sidc) - { + public SectorRangeFan(String sidc) { super(sidc); } @@ -109,8 +148,7 @@ public SectorRangeFan(String sidc) * * @return Angle of the arrowhead in the graphic. */ - public Angle getArrowAngle() - { + public Angle getArrowAngle() { return this.arrowAngle; } @@ -119,17 +157,14 @@ public Angle getArrowAngle() * * @param arrowAngle The angle of the arrowhead. Must be greater than zero degrees and less than 90 degrees. */ - public void setArrowAngle(Angle arrowAngle) - { - if (arrowAngle == null) - { + public void setArrowAngle(Angle arrowAngle) { + if (arrowAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) - { + if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) { String msg = Logging.getMessage("generic.AngleOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -143,8 +178,7 @@ public void setArrowAngle(Angle arrowAngle) * * @return The length of the arrowhead as a fraction of the total line length. */ - public double getArrowLength() - { + public double getArrowLength() { return this.arrowLength; } @@ -152,12 +186,10 @@ public double getArrowLength() * Specifies the length of the arrowhead. * * @param arrowLength Length of the arrowhead as a fraction of the total line length. If the arrowhead length is - * 0.25, then the arrowhead length will be one quarter of the total line length. + * 0.25, then the arrowhead length will be one quarter of the total line length. */ - public void setArrowLength(double arrowLength) - { - if (arrowLength < 0) - { + public void setArrowLength(double arrowLength) { + if (arrowLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -171,8 +203,7 @@ public void setArrowLength(double arrowLength) * * @return The length of the Center Of Sector as a fraction of the final range fan radius. */ - public double getCenterOfSectorLength() - { + public double getCenterOfSectorLength() { return this.centerOfSectorLength; } @@ -181,10 +212,8 @@ public double getCenterOfSectorLength() * * @param centerOfSectorLength Length of the Center Of Sector arrow as a fraction of the final range fan radius. */ - public void setCenterOfSector(double centerOfSectorLength) - { - if (centerOfSectorLength < 0) - { + public void setCenterOfSector(double centerOfSectorLength) { + if (centerOfSectorLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -198,8 +227,7 @@ public void setCenterOfSector(double centerOfSectorLength) * * @return Intervals used to draw arc. */ - public int getIntervals() - { + public int getIntervals() { return this.intervals; } @@ -209,10 +237,8 @@ public int getIntervals() * * @param intervals Number of intervals for drawing the arc. */ - public void setIntervals(int intervals) - { - if (intervals < 1) - { + public void setIntervals(int intervals) { + if (intervals < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -227,8 +253,7 @@ public void setIntervals(int intervals) * * @return NumberFormat used to create azimuth labels. */ - public NumberFormat getAzimuthFormat() - { + public NumberFormat getAzimuthFormat() { return this.azimuthFormat; } @@ -237,10 +262,8 @@ public NumberFormat getAzimuthFormat() * * @param azimuthFormat NumberFormat to create azimuth labels. */ - public void setAzimuthFormat(NumberFormat azimuthFormat) - { - if (azimuthFormat == null) - { + public void setAzimuthFormat(NumberFormat azimuthFormat) { + if (azimuthFormat == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -254,8 +277,7 @@ public void setAzimuthFormat(NumberFormat azimuthFormat) * * @return NumberFormat used to create radius labels. */ - public NumberFormat getRadiusFormat() - { + public NumberFormat getRadiusFormat() { return this.radiusFormat; } @@ -264,10 +286,8 @@ public NumberFormat getRadiusFormat() * * @param radiusFormat NumberFormat to create radius labels. */ - public void setRadiusFormat(NumberFormat radiusFormat) - { - if (radiusFormat == null) - { + public void setRadiusFormat(NumberFormat radiusFormat) { + if (radiusFormat == null) { String message = Logging.getMessage("nullValue.Format"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -281,8 +301,7 @@ public void setRadiusFormat(NumberFormat radiusFormat) * * @return The range fan center position. */ - public Position getPosition() - { + public Position getPosition() { return this.getReferencePosition(); } @@ -291,8 +310,7 @@ public Position getPosition() * * @param position The new center position. */ - public void setPosition(Position position) - { + public void setPosition(Position position) { this.moveTo(position); } @@ -300,20 +318,17 @@ public void setPosition(Position position) * {@inheritDoc} * * @param positions Control points. This graphic uses only one control point, which determines the center of the - * circle. + * circle. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Iterator iterator = positions.iterator(); - if (!iterator.hasNext()) - { + if (!iterator.hasNext()) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -322,88 +337,74 @@ public void setPositions(Iterable positions) this.position = iterator.next(); this.reset(); - if (this.symbol != null) + if (this.symbol != null) { this.symbol.setPosition(this.position); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override @SuppressWarnings("unchecked") - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.DISTANCE.equals(modifier)) - { - if (value instanceof Iterable) - { + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.DISTANCE.equals(modifier)) { + if (value instanceof Iterable) { this.setRadii((Iterable) value); - } - else if (value instanceof Double) - { + } else if (value instanceof Double) { this.setRadii(Arrays.asList((Double) value)); } - } - else if (SymbologyConstants.AZIMUTH.equals(modifier)) - { - if (value instanceof Iterable) - { + } else if (SymbologyConstants.AZIMUTH.equals(modifier)) { + if (value instanceof Iterable) { // Store the Iterable in an unnecessary variable to suppress Java 7 compiler warnings on Windows. Iterable iterable = (Iterable) value; this.setAzimuths(iterable); - } - else if (value instanceof Angle) - { + } else if (value instanceof Angle) { this.setAzimuths(Arrays.asList((Angle) value)); } - } - else if (SymbologyConstants.ALTITUDE_DEPTH.equals(modifier)) - { - if (value instanceof Iterable) - { + } else if (SymbologyConstants.ALTITUDE_DEPTH.equals(modifier)) { + if (value instanceof Iterable) { // Store the Iterable in an unnecessary variable to suppress Java 7 compiler warnings on Windows. Iterable iterable = (Iterable) value; this.setAltitudes(iterable); - } - else if (value != null) - { + } else if (value != null) { this.setAltitudes(Arrays.asList(value.toString())); } - } - else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) - { + } else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) { this.setSymbol((String) value); - } - else - { + } else { super.setModifier(modifier, value); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.DISTANCE.equals(modifier)) + public Object getModifier(String modifier) { + if (SymbologyConstants.DISTANCE.equals(modifier)) { return this.getRadii(); - else if (SymbologyConstants.AZIMUTH.equals(modifier)) + } else if (SymbologyConstants.AZIMUTH.equals(modifier)) { return this.getAzimuths(); - else if (SymbologyConstants.ALTITUDE_DEPTH.equals(modifier)) + } else if (SymbologyConstants.ALTITUDE_DEPTH.equals(modifier)) { return this.getAltitudes(); - else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) + } else if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) { return this.getSymbol(); - else + } else { return super.getModifier(modifier); + } } /** * Indicates the radii of the rings that make up the range fan. * * @return List of radii, in meters. This method never returns null. If there are no rings this returns an empty - * list. + * list. */ - public Iterable getRadii() - { - if (this.radii != null) + public Iterable getRadii() { + if (this.radii != null) { return this.radii; + } return Collections.emptyList(); } @@ -412,8 +413,7 @@ public Iterable getRadii() * * @param radii List of radii, in meters. A circle will be created for each radius. */ - public void setRadii(Iterable radii) - { + public void setRadii(Iterable radii) { this.radii = radii; this.onModifierChanged(); this.reset(); @@ -424,12 +424,12 @@ public void setRadii(Iterable radii) * left and then right. * * @return Left and right azimuths, measured clockwise from North. This method never returns null. If there are no - * azimuths, returns an empty list. + * azimuths, returns an empty list. */ - public Iterable getAzimuths() - { - if (this.azimuths != null) + public Iterable getAzimuths() { + if (this.azimuths != null) { return this.azimuths; + } return Collections.emptyList(); } @@ -439,10 +439,8 @@ public Iterable getAzimuths() * * @param azimuths Left and right azimuths, measured clockwise from North. */ - public void setAzimuths(Iterable azimuths) - { - if (azimuths == null) - { + public void setAzimuths(Iterable azimuths) { + if (azimuths == null) { String message = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -458,12 +456,12 @@ public void setAzimuths(Iterable azimuths) * surface. The altitude strings are displayed as text. * * @return List of altitude strings. This method never returns null. If there are no altitudes, returns an empty - * list. + * list. */ - public Iterable getAltitudes() - { - if (this.altitudes != null) + public Iterable getAltitudes() { + if (this.altitudes != null) { return this.altitudes; + } return Collections.emptyList(); } @@ -473,10 +471,8 @@ public Iterable getAltitudes() * * @param altitudes List of altitude strings. */ - public void setAltitudes(Iterable altitudes) - { - if (altitudes == null) - { + public void setAltitudes(Iterable altitudes) { + if (altitudes == null) { String message = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -490,8 +486,7 @@ public void setAltitudes(Iterable altitudes) * * @return The identifier of a symbol drawn at the center of the range fan. May be null. */ - public String getSymbol() - { + public String getSymbol() { return this.symbol != null ? this.symbol.getIdentifier() : null; } @@ -501,19 +496,16 @@ public String getSymbol() * center position. * * @param sidc The identifier of a MIL-STD-2525C tactical symbol to draw at the center of the range fan. May be null - * to indicate that no symbol is drawn. + * to indicate that no symbol is drawn. */ - public void setSymbol(String sidc) - { - if (sidc != null) - { - if (this.symbolAttributes == null) + public void setSymbol(String sidc) { + if (sidc != null) { + if (this.symbolAttributes == null) { this.symbolAttributes = new BasicTacticalSymbolAttributes(); + } this.symbol = this.createSymbol(sidc, this.getPosition(), this.symbolAttributes); - } - else - { + } else { // Null value indicates no symbol. this.symbol = null; this.symbolAttributes = null; @@ -521,35 +513,35 @@ public void setSymbol(String sidc) this.onModifierChanged(); } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.position); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.position; } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } this.determineActiveAttributes(); - if (this.paths == null) - { + if (this.paths == null) { this.createShapes(dc); } - if (this.arrowHead != null) - { + if (this.arrowHead != null) { this.arrowHead.preRender(dc); } } @@ -559,51 +551,47 @@ public void preRender(DrawContext dc) * * @param dc Current draw context. */ - protected void doRenderGraphic(DrawContext dc) - { - for (Path path : this.paths) - { + protected void doRenderGraphic(DrawContext dc) { + for (Path path : this.paths) { path.render(dc); } - if (this.arrowHead != null) - { + if (this.arrowHead != null) { this.arrowHead.render(dc); } } - /** {@inheritDoc} Overridden to render symbol at the center of the range fan. */ + /** + * {@inheritDoc} Overridden to render symbol at the center of the range fan. + */ @Override - protected void doRenderGraphicModifiers(DrawContext dc) - { + protected void doRenderGraphicModifiers(DrawContext dc) { super.doRenderGraphicModifiers(dc); - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths != null) - { - for (Path path : this.paths) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths != null) { + for (Path path : this.paths) { path.setDelegateOwner(owner); } } - if (this.arrowHead != null) - { + if (this.arrowHead != null) { this.arrowHead.setDelegateOwner(owner); } } - /** Regenerate the graphics positions on the next frame. */ - protected void reset() - { + /** + * Regenerate the graphics positions on the next frame. + */ + protected void reset() { this.paths = null; } @@ -612,8 +600,7 @@ protected void reset() * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { this.paths = new ArrayList(); Iterator radii = this.getRadii().iterator(); @@ -624,12 +611,12 @@ protected void createShapes(DrawContext dc) double prevRadius = 0; // Create range fan arcs. - while (radii.hasNext()) - { + while (radii.hasNext()) { double radius = radii.next(); - if (radius > this.maxRadius) + if (radius > this.maxRadius) { this.maxRadius = radius; + } Angle leftAzimuth = azimuths.hasNext() ? azimuths.next() : prevLeftAzimuth; Angle rightAzimuth = azimuths.hasNext() ? azimuths.next() : prevRightAzimuth; @@ -659,13 +646,10 @@ protected void createShapes(DrawContext dc) // Create the Center of Sector arrow if the fan is less than a full circle. If the fan is a full circle then it // doesn't make sense to draw an arbitrary arrow. boolean fullCircle = Math.abs(prevLeftAzimuth.subtract(prevRightAzimuth).degrees) >= 360; - if (!fullCircle) - { + if (!fullCircle) { this.centerAzimuth = this.computeCenterSectorAngle(prevLeftAzimuth, prevRightAzimuth); this.createCenterOfSectorArrow(dc, centerAzimuth, prevRadius); - } - else - { + } else { this.centerAzimuth = Angle.POS180; // Due South } } @@ -673,19 +657,18 @@ protected void createShapes(DrawContext dc) /** * Create shapes to draw the Center Of Sector arrow. This arrow bisects the final range fan. * - * @param dc Current draw context. + * @param dc Current draw context. * @param centerAzimuth Azimuth of the Center Of Sector arrow. - * @param finalRadius Radius, in meters, of the final range fan. + * @param finalRadius Radius, in meters, of the final range fan. */ - protected void createCenterOfSectorArrow(DrawContext dc, Angle centerAzimuth, double finalRadius) - { + protected void createCenterOfSectorArrow(DrawContext dc, Angle centerAzimuth, double finalRadius) { Position center = this.getPosition(); // Create the line par of the arrow. List positions = new ArrayList(); positions.add(center); this.createArc(dc, finalRadius * this.getCenterOfSectorLength(), centerAzimuth, centerAzimuth, - positions); + positions); this.paths.add(this.createPath(positions)); @@ -695,7 +678,7 @@ protected void createCenterOfSectorArrow(DrawContext dc, Angle centerAzimuth, do // Create a polygon to draw the arrow head. this.arrowHead = this.createPolygon(); positions = this.computeArrowheadPositions(dc, center, arrowTip, this.getArrowLength(), - this.getArrowAngle()); + this.getArrowAngle()); this.arrowHead.setLocations(positions); } @@ -705,13 +688,12 @@ protected void createCenterOfSectorArrow(DrawContext dc, Angle centerAzimuth, do * computed, but the graphic template (pg. 693) suggests that the Center Of Sector line should bisect the last range * fan arc. * - * @param finalLeftAzimuth Left azimuth of the last range fan in the graphic. + * @param finalLeftAzimuth Left azimuth of the last range fan in the graphic. * @param finalRightAzimuth Right azimuth of the last range fan in the graphic. * * @return Azimuth, from North, of the Center Of Sector line. */ - protected Angle computeCenterSectorAngle(Angle finalLeftAzimuth, Angle finalRightAzimuth) - { + protected Angle computeCenterSectorAngle(Angle finalLeftAzimuth, Angle finalRightAzimuth) { return finalLeftAzimuth.add(finalRightAzimuth).divide(2.0); } @@ -723,15 +705,14 @@ protected Angle computeCenterSectorAngle(Angle finalLeftAzimuth, Angle finalRigh * If the left and right azimuths are equal, then this methods adds a single position to the list at the desired * azimuth and radius. * - * @param dc Current draw context. - * @param radius Radius of the circular segment, in meters. - * @param leftAzimuth Azimuth (from North) of the left side of the arc. + * @param dc Current draw context. + * @param radius Radius of the circular segment, in meters. + * @param leftAzimuth Azimuth (from North) of the left side of the arc. * @param rightAzimuth Azimuth (from North) of teh right side of the arc. - * @param positions List to collect positions for the arc. + * @param positions List to collect positions for the arc. */ protected void createArc(DrawContext dc, double radius, Angle leftAzimuth, Angle rightAzimuth, - List positions) - { + List positions) { Globe globe = dc.getGlobe(); int intervals = this.getIntervals(); @@ -741,8 +722,7 @@ protected void createArc(DrawContext dc, double radius, Angle leftAzimuth, Angle double radiusRadians = radius / globeRadius; // If the left and right azimuths are equal then just add a single point and return. - if (leftAzimuth.equals(rightAzimuth)) - { + if (leftAzimuth.equals(rightAzimuth)) { LatLon ll = LatLon.greatCircleEndPosition(center, leftAzimuth.radians, radiusRadians); positions.add(new Position(ll, 0)); return; @@ -752,8 +732,7 @@ protected void createArc(DrawContext dc, double radius, Angle leftAzimuth, Angle Angle da = arcAngle.divide(intervals); - for (int i = 0; i < intervals + 1; i++) - { + for (int i = 0; i < intervals + 1; i++) { double angle = i * da.radians + leftAzimuth.radians; LatLon ll = LatLon.greatCircleEndPosition(center, angle, radiusRadians); @@ -764,17 +743,16 @@ protected void createArc(DrawContext dc, double radius, Angle leftAzimuth, Angle /** * Compute the positions of the arrow head for the sector center line. * - * @param dc Current draw context - * @param base Position of the arrow's starting point. - * @param tip Position of the arrow head tip. + * @param dc Current draw context + * @param base Position of the arrow's starting point. + * @param tip Position of the arrow head tip. * @param arrowLength Length of the arrowhead as a fraction of the total line length. - * @param arrowAngle Angle of the arrow head. + * @param arrowAngle Angle of the arrow head. * * @return Positions required to draw the arrow head. */ protected List computeArrowheadPositions(DrawContext dc, Position base, Position tip, double arrowLength, - Angle arrowAngle) - { + Angle arrowAngle) { // Build a triangle to represent the arrowhead. The triangle is built from two vectors, one parallel to the // segment, and one perpendicular to it. @@ -804,13 +782,15 @@ protected List computeArrowheadPositions(DrawContext dc, Position base return TacticalGraphicUtil.asPositionList(globe, vertex1, vertex2, ptB); } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { Iterable radii = this.getRadii(); - if (radii == null) + if (radii == null) { return; + } Iterator altitudes = this.getAltitudes().iterator(); Iterator azimuths = this.getAzimuths().iterator(); @@ -818,36 +798,41 @@ protected void createLabels() Angle leftAzimuth = null; Angle rightAzimuth = null; - for (Double radius : radii) - { - if (azimuths.hasNext()) + for (Double radius : radii) { + if (azimuths.hasNext()) { leftAzimuth = azimuths.next(); - if (azimuths.hasNext()) + } + if (azimuths.hasNext()) { rightAzimuth = azimuths.next(); + } String alt = null; - if (altitudes.hasNext()) + if (altitudes.hasNext()) { alt = altitudes.next(); + } this.addLabel(this.createRangeLabelString(radius, alt)); - if (leftAzimuth != null) + if (leftAzimuth != null) { this.addLabel(this.createAzimuthLabelString(leftAzimuth)); + } - if (rightAzimuth != null) + if (rightAzimuth != null) { this.addLabel(this.createAzimuthLabelString(rightAzimuth)); + } } } - /** Create azimuth labels. */ - protected void createAzimuthLabels() - { + /** + * Create azimuth labels. + */ + protected void createAzimuthLabels() { Iterable azimuths = this.getAzimuths(); - if (azimuths == null) + if (azimuths == null) { return; + } - for (Angle azimuth : azimuths) - { + for (Angle azimuth : azimuths) { this.addLabel(this.createAzimuthLabelString(azimuth)); } } @@ -855,20 +840,18 @@ protected void createAzimuthLabels() /** * Create text for a range label. * - * @param radius Range of the ring, in meters. + * @param radius Range of the ring, in meters. * @param altitude Altitude string. * * @return Range label text for this ring. */ - protected String createRangeLabelString(double radius, String altitude) - { + protected String createRangeLabelString(double radius, String altitude) { NumberFormat df = this.getRadiusFormat(); StringBuilder sb = new StringBuilder(); sb.append("RG ").append(df.format(radius)); - if (!WWUtil.isEmpty(altitude)) - { + if (!WWUtil.isEmpty(altitude)) { sb.append("\nALT ").append(altitude); } @@ -882,18 +865,19 @@ protected String createRangeLabelString(double radius, String altitude) * * @return Azimuth label text. */ - protected String createAzimuthLabelString(Angle azimuth) - { + protected String createAzimuthLabelString(Angle azimuth) { NumberFormat df = this.getAzimuthFormat(); return df.format(azimuth.degrees); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (this.labels == null) + protected void determineLabelPositions(DrawContext dc) { + if (this.labels == null) { return; + } Position center = this.getPosition(); @@ -907,12 +891,13 @@ protected void determineLabelPositions(DrawContext dc) double prevRadius = 0; double globeRadius = dc.getGlobe().getRadiusAt(center); - while (radii.hasNext() && labelIterator.hasNext()) - { - if (azimuths.hasNext()) + while (radii.hasNext() && labelIterator.hasNext()) { + if (azimuths.hasNext()) { leftAzimuth = azimuths.next(); - if (azimuths.hasNext()) + } + if (azimuths.hasNext()) { rightAzimuth = azimuths.next(); + } leftAzimuth = this.normalizeAzimuth(leftAzimuth); rightAzimuth = this.normalizeAzimuth(rightAzimuth); @@ -923,10 +908,12 @@ protected void determineLabelPositions(DrawContext dc) TacticalGraphicLabel leftLabel = null; // Left azimuth label TacticalGraphicLabel rightLabel = null; // Right azimuth label - if (leftAzimuth != null && labelIterator.hasNext()) + if (leftAzimuth != null && labelIterator.hasNext()) { leftLabel = labelIterator.next(); - if (rightAzimuth != null && labelIterator.hasNext()) + } + if (rightAzimuth != null && labelIterator.hasNext()) { rightLabel = labelIterator.next(); + } double radius = radii.next(); double avgRadius = (radius + prevRadius) / 2.0; @@ -934,22 +921,20 @@ protected void determineLabelPositions(DrawContext dc) // Find the range label position Position position = this.determineRangeLabelPosition(center, this.centerAzimuth, leftAzimuth, rightAzimuth, - radiusRadians); + radiusRadians); rangeLabel.setPosition(position); // Compute an angular offset that will put the label a little bit to the side of range fan line. double offset = this.computeAzimuthLabelOffset(avgRadius, this.maxRadius); // Find left azimuth label position - if (leftAzimuth != null && leftLabel != null) - { + if (leftAzimuth != null && leftLabel != null) { LatLon ll = LatLon.greatCircleEndPosition(center, leftAzimuth.radians - offset, radiusRadians); leftLabel.setPosition(new Position(ll, 0)); } // Find right azimuth label position - if (rightAzimuth != null && rightLabel != null) - { + if (rightAzimuth != null && rightLabel != null) { LatLon ll = LatLon.greatCircleEndPosition(center, rightAzimuth.radians + offset, radiusRadians); rightLabel.setPosition(new Position(ll, 0)); } @@ -962,13 +947,12 @@ protected void determineLabelPositions(DrawContext dc) * Compute an angular offset to apply to a azimuth label. This angle will be added to the azimuth of the label's * azimuth in order to place the label a little bit to the side of the line that it applies to. * - * @param radius Radius at which the label will be placed. + * @param radius Radius at which the label will be placed. * @param maxRadius Maximum radius in the range fan. * * @return Angle, in radians, to add to the range fan azimuth in order to determine the label position. */ - protected double computeAzimuthLabelOffset(double radius, double maxRadius) - { + protected double computeAzimuthLabelOffset(double radius, double maxRadius) { return Math.asin(AZIMUTH_LABEL_OFFSET * maxRadius / radius); } @@ -976,17 +960,16 @@ protected double computeAzimuthLabelOffset(double radius, double maxRadius) * Determine the position of a range label for a ring in the range fan. The method finds a point to either the left * or right of the center line, depending on which has more space for the label. * - * @param center Center of the range fan. + * @param center Center of the range fan. * @param centerAzimuth Azimuth of the Center Of Sector arrow. - * @param leftAzimuth Left azimuth of this ring. - * @param rightAzimuth Right azimuth of this ring. + * @param leftAzimuth Left azimuth of this ring. + * @param rightAzimuth Right azimuth of this ring. * @param radiusRadians Radius, in radians, at which to place the label. * * @return Position for the range label on this ring. */ protected Position determineRangeLabelPosition(Position center, Angle centerAzimuth, Angle leftAzimuth, - Angle rightAzimuth, double radiusRadians) - { + Angle rightAzimuth, double radiusRadians) { // If either left or right azimuth is not specified, use the center instead. leftAzimuth = (leftAzimuth != null) ? leftAzimuth : centerAzimuth; rightAzimuth = (rightAzimuth != null) ? rightAzimuth : centerAzimuth; @@ -1012,18 +995,19 @@ protected Position determineRangeLabelPosition(Position center, Angle centerAzim * * @return Normalized azimuth. Returns null if {@code azimuth} is null. */ - protected Angle normalizeAzimuth(Angle azimuth) - { + protected Angle normalizeAzimuth(Angle azimuth) { // The azimuth is not actually a longitude, but the normalization formula is the same as for longitude. - if (azimuth != null) + if (azimuth != null) { return Angle.normalizedLongitude(azimuth); + } return null; } - /** {@inheritDoc} Overridden to turn on shape interiors. */ + /** + * {@inheritDoc} Overridden to turn on shape interiors. + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); // Turn on the shape interior for the arrow head. All other parts of the graphic are Paths, which do not draw @@ -1034,15 +1018,15 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) attributes.setDrawInterior(true); } - /** {@inheritDoc} Overridden to update symbol attributes. */ + /** + * {@inheritDoc} Overridden to update symbol attributes. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply active attributes to the symbol. - if (this.symbolAttributes != null) - { + if (this.symbolAttributes != null) { ShapeAttributes activeAttributes = this.getActiveShapeAttributes(); this.symbolAttributes.setOpacity(activeAttributes.getInteriorOpacity()); this.symbolAttributes.setScale(this.activeOverrides.getScale()); @@ -1056,8 +1040,7 @@ protected void determineActiveAttributes() * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(List positions) - { + protected Path createPath(List positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); @@ -1072,11 +1055,10 @@ protected Path createPath(List positions) * * @return New surface polygon. */ - protected SurfacePolygon createPolygon() - { + protected SurfacePolygon createPolygon() { SurfacePolygon polygon = new SurfacePolygon(); polygon.setDelegateOwner(this.getActiveDelegateOwner()); polygon.setAttributes(this.getActiveShapeAttributes()); return polygon; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Smoke.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Smoke.java index 3cabfbf716..cd02121a35 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Smoke.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/Smoke.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.symbology.TacticalGraphicUtil; @@ -17,41 +16,38 @@ * @author pabercrombie * @version $Id: Smoke.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Smoke extends BasicArea -{ +public class Smoke extends BasicArea { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.FSUPP_ARS_ARATGT_SMK); } - public Smoke(String sidc) - { + public Smoke(String sidc) { super(sidc); // Do not draw "ENY" labels for hostile entities this.setShowHostileIndicator(false); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected String createLabelText() - { + protected String createLabelText() { StringBuilder sb = new StringBuilder(); sb.append("SMOKE\n"); Object[] dates = TacticalGraphicUtil.getDateRange(this); - if (dates[0] != null) - { + if (dates[0] != null) { sb.append(dates[0]); sb.append(" - \n"); } - if (dates[1] != null) - { + if (dates[1] != null) { sb.append(dates[1]); } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SpecialInterestArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SpecialInterestArea.java index fe740766d4..9789b34436 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SpecialInterestArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SpecialInterestArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.symbology.milstd2525.graphics.TacGrpSidc; @@ -18,19 +17,18 @@ * @author pabercrombie * @version $Id: SpecialInterestArea.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SpecialInterestArea extends BasicArea -{ +public class SpecialInterestArea extends BasicArea { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_SPL_ARA_AOO, - TacGrpSidc.C2GM_SPL_ARA_NAI, - TacGrpSidc.C2GM_SPL_ARA_TAI); + TacGrpSidc.C2GM_SPL_ARA_AOO, + TacGrpSidc.C2GM_SPL_ARA_NAI, + TacGrpSidc.C2GM_SPL_ARA_TAI); } /** @@ -38,24 +36,23 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public SpecialInterestArea(String sidc) - { + public SpecialInterestArea(String sidc) { super(sidc); this.setShowHostileIndicator(false); } @Override - protected String getGraphicLabel() - { + protected String getGraphicLabel() { String code = this.maskedSymbolCode; - if (TacGrpSidc.C2GM_SPL_ARA_AOO.equalsIgnoreCase(code)) + if (TacGrpSidc.C2GM_SPL_ARA_AOO.equalsIgnoreCase(code)) { return "AO"; - else if (TacGrpSidc.C2GM_SPL_ARA_NAI.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_SPL_ARA_NAI.equalsIgnoreCase(code)) { return "NAI"; - else if (TacGrpSidc.C2GM_SPL_ARA_TAI.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_SPL_ARA_TAI.equalsIgnoreCase(code)) { return "TAI"; + } return ""; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SupportByFirePosition.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SupportByFirePosition.java index 8f2486ec20..26802e62f4 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SupportByFirePosition.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/SupportByFirePosition.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.geom.Position; @@ -19,9 +18,11 @@ * @author pabercrombie * @version $Id: SupportByFirePosition.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class SupportByFirePosition extends AttackByFirePosition -{ - /** Fourth control point. */ +public class SupportByFirePosition extends AttackByFirePosition { + + /** + * Fourth control point. + */ protected Position position4; /** @@ -29,8 +30,7 @@ public class SupportByFirePosition extends AttackByFirePosition * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_ARS_SFP); } @@ -39,8 +39,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public SupportByFirePosition(String sidc) - { + public SupportByFirePosition(String sidc) { super(sidc); } @@ -50,25 +49,20 @@ public SupportByFirePosition(String sidc) * @param positions Control points that orient the graphic. Must provide at least four points. */ @Override - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.position1 = iterator.next(); this.position2 = iterator.next(); this.position3 = iterator.next(); this.position4 = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -77,10 +71,11 @@ public void setPositions(Iterable positions) this.paths = null; // Need to recompute path for the new control points } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Iterable getPositions() - { + public Iterable getPositions() { return Arrays.asList(this.position1, this.position2, this.position3, this.position4); } @@ -90,8 +85,7 @@ public Iterable getPositions() * @param dc Current draw context. */ @Override - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { this.paths = new Path[5]; // Create a path for the line parts of the arrows diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/WeaponsFreeZone.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/WeaponsFreeZone.java index 0aaf79177e..36a14e3787 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/WeaponsFreeZone.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/WeaponsFreeZone.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.avlist.AVKey; @@ -19,9 +18,11 @@ * @author pabercrombie * @version $Id: WeaponsFreeZone.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WeaponsFreeZone extends AviationZone -{ - /** Path to the image used for the polygon fill pattern. */ +public class WeaponsFreeZone extends AviationZone { + + /** + * Path to the image used for the polygon fill pattern. + */ protected static final String DIAGONAL_FILL_PATH = "images/diagonal-fill-16x16.png"; /** @@ -29,36 +30,35 @@ public class WeaponsFreeZone extends AviationZone * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static java.util.List getSupportedGraphics() - { + public static java.util.List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_AVN_ARS_WFZ); } - public WeaponsFreeZone(String sidc) - { + public WeaponsFreeZone(String sidc) { super(sidc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected String getGraphicLabel() - { + protected String getGraphicLabel() { return "WFZ"; } @Override - protected void createLabels() - { + protected void createLabels() { TacticalGraphicLabel label = this.addLabel(this.createLabelText()); label.setTextAlign(AVKey.LEFT); label.setEffect(AVKey.TEXT_EFFECT_NONE); label.setDrawInterior(true); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); // Enable the polygon interior and set the image source to draw a fill pattern of diagonal lines. @@ -71,8 +71,7 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) * altitude modifier. */ @Override - protected String createLabelText() - { + protected String createLabelText() { return this.doCreateLabelText(false); } @@ -81,8 +80,7 @@ protected String createLabelText() * * @return The source of the polygon fill pattern. */ - protected Object getImageSource() - { + protected Object getImageSource() { return DIAGONAL_FILL_PATH; } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/package-info.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/package-info.java index 98b1d4eb35..f78b8b745c 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/package-info.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

                  * MIL-STD-2525 area graphics. Applications should use {@link diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AbstractAxisArrow.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AbstractAxisArrow.java index 2f8df724b4..43e3d005cd 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AbstractAxisArrow.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AbstractAxisArrow.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -26,15 +25,21 @@ * @author pabercrombie * @version $Id: AbstractAxisArrow.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractAxisArrow extends AbstractMilStd2525TacticalGraphic -{ - /** Path used to render the line. */ +public abstract class AbstractAxisArrow extends AbstractMilStd2525TacticalGraphic { + + /** + * Path used to render the line. + */ protected Path[] paths; - /** Control points that define the shape. */ + /** + * Control points that define the shape. + */ protected Iterable positions; - /** Positions computed from the control points, used to draw the arrow path. */ + /** + * Positions computed from the control points, used to draw the arrow path. + */ protected List arrowPositions; /** @@ -48,8 +53,7 @@ public abstract class AbstractAxisArrow extends AbstractMilStd2525TacticalGraphi * * @param sidc Symbol code the identifies the graphic. */ - public AbstractAxisArrow(String sidc) - { + public AbstractAxisArrow(String sidc) { this(sidc, 1); } @@ -58,23 +62,20 @@ public AbstractAxisArrow(String sidc) * creates the requested number of paths. The first element in the array is the main path that outlines the arrow. * Subclasses are responsible for configuring the other paths. * - * @param sidc Symbol code the identifies the graphic. + * @param sidc Symbol code the identifies the graphic. * @param numPaths Number of paths to create. */ - public AbstractAxisArrow(String sidc, int numPaths) - { + public AbstractAxisArrow(String sidc, int numPaths) { super(sidc); - if (numPaths < 1) - { + if (numPaths < 1) { String message = Logging.getMessage("generic.ArrayInvalidLength", numPaths); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.paths = new Path[numPaths]; - for (int i = 0; i < numPaths; i++) - { + for (int i = 0; i < numPaths; i++) { this.paths[i] = this.createPath(); } } @@ -84,25 +85,20 @@ public AbstractAxisArrow(String sidc, int numPaths) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Ensure that the position list provides at least 3 control points. - try - { + try { Iterator iterator = positions.iterator(); iterator.next(); iterator.next(); iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -112,44 +108,45 @@ public void setPositions(Iterable positions) this.arrowPositions = null; // Need to recompute path for the new control points } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return this.positions; } - /** {@inheritDoc} */ - public Position getReferencePosition() - { - if (this.positions != null) - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { + if (this.positions != null) { return this.positions.iterator().next(); // use the first position } return null; } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - if (this.arrowPositions == null) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + if (this.arrowPositions == null) { this.createShapePositions(dc); } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths == null) { return; + } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.setDelegateOwner(owner); } } @@ -173,10 +170,9 @@ protected void applyDelegateOwner(Object owner) * * * @return True if the final control point determines the width of the route instead of the width of the arrow head - * (point B in the diagram above). + * (point B in the diagram above). */ - public boolean isFinalPointWidthOfRoute() - { + public boolean isFinalPointWidthOfRoute() { return this.finalPointWidthOfRoute; } @@ -185,10 +181,9 @@ public boolean isFinalPointWidthOfRoute() * {@link #isFinalPointWidthOfRoute()} for details. * * @param finalPointIsWidthOfRoute True if the final control point determines the width of the route instead of the - * width of the arrow head. + * width of the arrow head. */ - public void setFinalPointWidthOfRoute(boolean finalPointIsWidthOfRoute) - { + public void setFinalPointWidthOfRoute(boolean finalPointIsWidthOfRoute) { this.finalPointWidthOfRoute = finalPointIsWidthOfRoute; } @@ -197,8 +192,7 @@ public void setFinalPointWidthOfRoute(boolean finalPointIsWidthOfRoute) * * @param dc Current draw context. */ - protected void createShapePositions(DrawContext dc) - { + protected void createShapePositions(DrawContext dc) { Globe globe = dc.getGlobe(); // Collect positions in two lists, one for points on the left side of the control line, and one for the right side. @@ -237,32 +231,29 @@ protected void createShapePositions(DrawContext dc) * |/Pt N' * * - * @param leftPositions List to collect positions on the left arrow line. This list receives the position where - * the left line meets the arrow head. - * @param rightPositions List to collect positions on the right arrow line. This list receives the position - * where the right line meets the arrow head. + * @param leftPositions List to collect positions on the left arrow line. This list receives the position where the + * left line meets the arrow head. + * @param rightPositions List to collect positions on the right arrow line. This list receives the position where + * the right line meets the arrow head. * @param arrowHeadPositions List to collect positions that make up the arrow head. This list receives positions for - * Pt. N, Pt. 1, and Pt. N', in that order. - * @param globe Current globe. + * Pt. N, Pt. 1, and Pt. N', in that order. + * @param globe Current globe. * * @return The distance from the center line to the left and right lines. */ protected double createArrowHeadPositions(List leftPositions, List rightPositions, - List arrowHeadPositions, Globe globe) - { + List arrowHeadPositions, Globe globe) { Iterator iterator = this.positions.iterator(); Position pos1 = iterator.next(); Position pos2 = iterator.next(); Position posN = null; - while (iterator.hasNext()) - { + while (iterator.hasNext()) { posN = iterator.next(); } - if (posN == null) - { + if (posN == null) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -279,8 +270,7 @@ protected double createArrowHeadPositions(List leftPositions, List leftPositions, List leftPositions, List leftPositions, List rightPositions, double halfWidth, - Globe globe) - { + Globe globe) { Iterator iterator = positions.iterator(); Position posB = iterator.next(); @@ -347,12 +335,10 @@ protected void createLinePositions(List leftPositions, List // / // / // A / - Vec4 pA = globe.computePointFromLocation(posA); Vec4 pB = globe.computePointFromLocation(posB); Vec4 pC; - while (iterator.hasNext()) - { + while (iterator.hasNext()) { posA = iterator.next(); pC = pB; @@ -367,8 +353,7 @@ protected void createLinePositions(List leftPositions, List // Compute a vector perpendicular to segment BC, and the globe normal vector. Vec4 perpendicular = vBC.cross3(normal); - if (iterator.hasNext() && !Vec4.areColinear(pA, pB, pC)) - { + if (iterator.hasNext() && !Vec4.areColinear(pA, pB, pC)) { Vec4 vBA = pA.subtract3(pB); // Calculate the vector that bisects angle ABC. @@ -378,13 +363,10 @@ protected void createLinePositions(List leftPositions, List // Compute the scalar triple product of the vector BC, the normal vector, and the offset vector to // determine if the offset points to the left or the right of the control line. double tripleProduct = perpendicular.dot3(offset); - if (tripleProduct < 0) - { + if (tripleProduct < 0) { offset = offset.multiply3(-1); } - } - else - { + } else { // If this is the last control point then don't consider the surrounding points, just compute an offset // perpendicular to the control line. offset = perpendicular.normalize3(); @@ -414,8 +396,7 @@ protected void createLinePositions(List leftPositions, List * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath() - { + protected Path createPath() { Path path = new Path(); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AdvanceForFeint.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AdvanceForFeint.java index 1a2fd58316..eb6ff32f7b 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AdvanceForFeint.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AdvanceForFeint.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -20,15 +19,17 @@ * @author pabercrombie * @version $Id: AdvanceForFeint.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class AdvanceForFeint extends AbstractAxisArrow -{ +public class AdvanceForFeint extends AbstractAxisArrow { + /** * Factor used to compute the distance between the solid and dashed lines in the arrow head. A larger value will * move the dashed line farther from the solid line. */ protected static final double DASHED_LINE_DISTANCE = 0.2; - /** Shape attributes for the dashed part of the graphic. */ + /** + * Shape attributes for the dashed part of the graphic. + */ protected ShapeAttributes dashedAttributes = new BasicShapeAttributes(); /** @@ -36,8 +37,7 @@ public class AdvanceForFeint extends AbstractAxisArrow * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_DCPN_AAFF); } @@ -46,8 +46,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public AdvanceForFeint(String sidc) - { + public AdvanceForFeint(String sidc) { super(sidc, 2); // Path 1 is used to draw the dashed line. This path needs its own shape attributes because it is always drawn @@ -55,18 +54,20 @@ public AdvanceForFeint(String sidc) this.paths[1].setAttributes(this.dashedAttributes); } - /** {@inheritDoc} Overridden to compute positions for the dashed portion of the arrow head. */ + /** + * {@inheritDoc} Overridden to compute positions for the dashed portion of the arrow head. + */ @Override protected double createArrowHeadPositions(List leftPositions, List rightPositions, - List arrowHeadPositions, Globe globe) - { + List arrowHeadPositions, Globe globe) { // This graphic has a double line for the arrowhead, and the outer line is always drawn dashed. Take the // arrowhead computed by the super class and create the other line from it. double halfWidth = super.createArrowHeadPositions(leftPositions, rightPositions, arrowHeadPositions, globe); // The rest of the method assumes that the superclass populates arrowHeadPositions with three positions. - if (arrowHeadPositions == null || arrowHeadPositions.size() != 3) + if (arrowHeadPositions == null || arrowHeadPositions.size() != 3) { throw new IllegalStateException(); + } Iterator positions = this.positions.iterator(); Position pos1 = positions.next(); @@ -92,9 +93,9 @@ protected double createArrowHeadPositions(List leftPositions, List newPositions = Arrays.asList( - globe.computePositionFromPoint(ptN), - pos1, - globe.computePositionFromPoint(ptN_prime)); + globe.computePositionFromPoint(ptN), + pos1, + globe.computePositionFromPoint(ptN_prime)); this.paths[1].setPositions(new ArrayList(newPositions)); @@ -108,10 +109,11 @@ protected double createArrowHeadPositions(List leftPositions, List positions = this.positions.iterator(); Position pos1 = positions.next(); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Airborne.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Airborne.java index aa7c152096..e9e2bf395a 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Airborne.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Airborne.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -19,11 +18,15 @@ * @author pabercrombie * @version $Id: Airborne.java 560 2012-04-26 16:28:24Z pabercrombie $ */ -public class Airborne extends Aviation -{ - /** Symbol drawn at the center of the range fan. */ +public class Airborne extends Aviation { + + /** + * Symbol drawn at the center of the range fan. + */ protected TacticalSymbol symbol; - /** Attributes applied to the symbol. */ + /** + * Attributes applied to the symbol. + */ protected TacticalSymbolAttributes symbolAttributes; /** @@ -31,8 +34,7 @@ public class Airborne extends Aviation * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_LNE_AXSADV_ABN); } @@ -41,29 +43,32 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public Airborne(String sidc) - { + public Airborne(String sidc) { super(sidc, 1); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) { this.setSymbol((String) value); - else + } else { super.setModifier(modifier, value); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) + public Object getModifier(String modifier) { + if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) { return this.symbol != null ? this.symbol.getIdentifier() : null; - else + } else { return super.getModifier(modifier); + } } /** @@ -71,8 +76,7 @@ public Object getModifier(String modifier) * * @return The symbol drawn at the center of the range fan. May be null. */ - public String getSymbol() - { + public String getSymbol() { return this.symbol != null ? this.symbol.getIdentifier() : null; } @@ -82,19 +86,16 @@ public String getSymbol() * two control points of the Airborne arrow. * * @param sidc The identifier of a symbol in the MIL-STD-2525C symbology set, or null to indicate that no symbol - * will be drawn. + * will be drawn. */ - public void setSymbol(String sidc) - { - if (sidc != null) - { - if (this.symbolAttributes == null) + public void setSymbol(String sidc) { + if (sidc != null) { + if (this.symbolAttributes == null) { this.symbolAttributes = new BasicTacticalSymbolAttributes(); + } this.symbol = this.createSymbol(sidc, this.computeSymbolPosition(), this.symbolAttributes); - } - else - { + } else { // Null value indicates no symbol. this.symbol = null; this.symbolAttributes = null; @@ -102,27 +103,29 @@ public void setSymbol(String sidc) this.onModifierChanged(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setPositions(Iterable positions) - { + public void setPositions(Iterable positions) { super.setPositions(positions); // Update the position of the symbol. - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.setPosition(this.computeSymbolPosition()); } } - /** {@inheritDoc} Overridden to render tactical symbol. */ + /** + * {@inheritDoc} Overridden to render tactical symbol. + */ @Override - public void doRenderGraphicModifiers(DrawContext dc) - { + public void doRenderGraphicModifiers(DrawContext dc) { super.doRenderGraphicModifiers(dc); - if (this.symbol != null) + if (this.symbol != null) { this.symbol.render(dc); + } } /** @@ -130,11 +133,11 @@ public void doRenderGraphicModifiers(DrawContext dc) * * @return Position of the symbol, or null if the graphic has no positions. */ - protected Position computeSymbolPosition() - { + protected Position computeSymbolPosition() { Iterable positions = this.getPositions(); - if (positions == null) + if (positions == null) { return null; + } Iterator iterator = positions.iterator(); Position pos1 = iterator.next(); @@ -143,18 +146,18 @@ protected Position computeSymbolPosition() return new Position(LatLon.interpolateGreatCircle(0.1, pos2, pos1), 0); } - /** {@inheritDoc} Overridden to update symbol attributes. */ + /** + * {@inheritDoc} Overridden to update symbol attributes. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply active attributes to the symbol. - if (this.symbolAttributes != null) - { + if (this.symbolAttributes != null) { ShapeAttributes activeAttributes = this.getActiveShapeAttributes(); this.symbolAttributes.setOpacity(activeAttributes.getInteriorOpacity()); this.symbolAttributes.setScale(this.activeOverrides.getScale()); } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AttackRotaryWing.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AttackRotaryWing.java index 9b4ac5aa3f..6d0659a65b 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AttackRotaryWing.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/AttackRotaryWing.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -18,13 +17,19 @@ * @author pabercrombie * @version $Id: AttackRotaryWing.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AttackRotaryWing extends Aviation -{ - /** Index of the left vertical path in the {@code paths} array. */ +public class AttackRotaryWing extends Aviation { + + /** + * Index of the left vertical path in the {@code paths} array. + */ protected final static int LEFT_VERTICAL = 1; - /** Index of the right vertical path in the {@code paths} array. */ + /** + * Index of the right vertical path in the {@code paths} array. + */ protected final static int RIGHT_VERTICAL = 2; - /** Index of the rotor symbol path in the {@code paths} array. */ + /** + * Index of the rotor symbol path in the {@code paths} array. + */ protected final static int ROTOR_SYMBOL = 3; /** @@ -32,8 +37,7 @@ public class AttackRotaryWing extends Aviation * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_LNE_AXSADV_ATK); } @@ -42,15 +46,13 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public AttackRotaryWing(String sidc) - { + public AttackRotaryWing(String sidc) { super(sidc, 4); } @Override protected void createLinePositions(List leftPositions, List rightPositions, double halfWidth, - Globe globe) - { + Globe globe) { super.createLinePositions(leftPositions, rightPositions, halfWidth, globe); // Rotary Wing is based on the Aviation graphic, but adds a symbol for the rotor (an upward pointing arrow), @@ -65,7 +67,6 @@ protected void createLinePositions(List leftPositions, List // ____B/ \ D / // | / // |/ - Iterator iterator = this.positions.iterator(); final Position pos1 = iterator.next(); final Position pos2 = iterator.next(); @@ -124,7 +125,6 @@ protected void createLinePositions(List leftPositions, List // | // E ----- F // G - // Compute the width of the symbol base from the width of the entire graphic final double halfBaseWidth = halfWidth / 4; diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Aviation.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Aviation.java index 570d32fdf3..49751b15b3 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Aviation.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Aviation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.Position; @@ -18,15 +17,14 @@ * @author pabercrombie * @version $Id: Aviation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Aviation extends AbstractAxisArrow -{ +public class Aviation extends AbstractAxisArrow { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_LNE_AXSADV_AVN); } @@ -35,8 +33,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public Aviation(String sidc) - { + public Aviation(String sidc) { this(sidc, 1); } @@ -44,25 +41,24 @@ public Aviation(String sidc) * Create a new Aviation graphic, composed of more than one path. This constructor is for use by subclasses that * extend the base Aviation graphic by adding additional paths. * - * @param sidc Symbol code the identifies the graphic. + * @param sidc Symbol code the identifies the graphic. * @param numPaths Number of paths to create. */ - protected Aviation(String sidc, int numPaths) - { + protected Aviation(String sidc, int numPaths) { super(sidc, numPaths); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override protected double createArrowHeadPositions(List leftPositions, List rightPositions, - List arrowHeadPositions, Globe globe) - { + List arrowHeadPositions, Globe globe) { double halfWidth = super.createArrowHeadPositions(leftPositions, rightPositions, arrowHeadPositions, globe); // Aviation graphic is the same as the base graphic, except that the left and right lines cross between // points 1 and 2. Swap the control points in the left and right lists to achieve this effect. - if (rightPositions.size() > 0 && leftPositions.size() > 0) - { + if (rightPositions.size() > 0 && leftPositions.size() > 0) { Position temp = leftPositions.get(0); leftPositions.set(0, rightPositions.get(0)); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Boundary.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Boundary.java index 03c7c5a981..edddd292b8 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Boundary.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Boundary.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -21,8 +20,8 @@ * @author pabercrombie * @version $Id: Boundary.java 560 2012-04-26 16:28:24Z pabercrombie $ */ -public class Boundary extends PhaseLine -{ +public class Boundary extends PhaseLine { + /** * Offset applied to the graphic's upper label. This offset aligns the bottom edge of the label with the geographic * position, in order to keep the label above the graphic as the zoom changes. @@ -34,17 +33,27 @@ public class Boundary extends PhaseLine */ protected final static Offset BOTTOM_LABEL_OFFSET = Offset.fromFraction(0.0, -1.5); - /** Tactical symbols used to render the echelon modifiers. */ + /** + * Tactical symbols used to render the echelon modifiers. + */ protected List echelonSymbols = Collections.emptyList(); - /** Attribute bundle for the echelon symbols. */ + /** + * Attribute bundle for the echelon symbols. + */ protected TacticalSymbolAttributes symbolAttributes; // Determined when labels are created - /** Indicates whether or not there are labels above the boundary line. */ + /** + * Indicates whether or not there are labels above the boundary line. + */ protected boolean haveTopLabel; - /** Indicates whether or not there are labels below the boundary line. */ + /** + * Indicates whether or not there are labels below the boundary line. + */ protected boolean haveBottomLabel; - /** Indicates whether or not there are hostile indicator labels ("ENY") along the line. */ + /** + * Indicates whether or not there are hostile indicator labels ("ENY") along the line. + */ protected boolean haveHostileLabels; /** @@ -52,16 +61,16 @@ public class Boundary extends PhaseLine * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_GNL_LNE_BNDS); } /** * The value of an optional second text string for the graphic. This value is equivalent to the "T1" modifier * defined by MIL-STD-2525C. It can be set using {@link #setAdditionalText(String)}, or by passing an Iterable to - * {@link #setModifier(String, Object)} with a key of {@link gov.nasa.worldwind.symbology.SymbologyConstants#UNIQUE_DESIGNATION} - * (additional text is the second value in the iterable). + * {@link #setModifier(String, Object)} with a key of + * {@link gov.nasa.worldwind.symbology.SymbologyConstants#UNIQUE_DESIGNATION} (additional text is the second value + * in the iterable). */ protected String additionalText; @@ -70,8 +79,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public Boundary(String sidc) - { + public Boundary(String sidc) { super(sidc); } @@ -81,8 +89,7 @@ public Boundary(String sidc) * * @return The additional text. May be null. */ - public String getAdditionalText() - { + public String getAdditionalText() { return this.additionalText; } @@ -92,18 +99,15 @@ public String getAdditionalText() * * @param text The additional text. May be null. */ - public void setAdditionalText(String text) - { + public void setAdditionalText(String text) { this.additionalText = text; this.onModifierChanged(); } @Override - public Object getModifier(String key) - { + public Object getModifier(String key) { // If two values are set for the Unique Designation, return both in a list. - if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && this.additionalText != null) - { + if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && this.additionalText != null) { return Arrays.asList(this.getText(), this.getAdditionalText()); } @@ -111,47 +115,43 @@ public Object getModifier(String key) } @Override - public void setModifier(String key, Object value) - { - if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && value instanceof Iterable) - { + public void setModifier(String key, Object value) { + if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && value instanceof Iterable) { Iterator iterator = ((Iterable) value).iterator(); - if (iterator.hasNext()) - { + if (iterator.hasNext()) { this.setText((String) iterator.next()); } // The Final Protective Fire graphic supports a second Unique Designation value - if (iterator.hasNext()) - { + if (iterator.hasNext()) { this.setAdditionalText((String) iterator.next()); } - } - else - { + } else { super.setModifier(key, value); } } - /** {@inheritDoc} Overridden to render the echelon modifier. */ + /** + * {@inheritDoc} Overridden to render the echelon modifier. + */ @Override - protected void doRenderGraphicModifiers(DrawContext dc) - { + protected void doRenderGraphicModifiers(DrawContext dc) { super.doRenderGraphicModifiers(dc); - for (TacticalSymbol symbol : this.echelonSymbols) - { + for (TacticalSymbol symbol : this.echelonSymbols) { symbol.render(dc); } } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { Iterable positions = this.getPositions(); - if (positions == null) + if (positions == null) { return; + } Iterator iterator = positions.iterator(); @@ -176,28 +176,23 @@ protected void createLabels() // this order: top, bottom, hostile indicators. TacticalGraphicLabel label; iterator.next(); // Skip the first point. We are interested in line segments, not individual points. - while (iterator.hasNext()) - { - if (this.haveTopLabel) - { + while (iterator.hasNext()) { + if (this.haveTopLabel) { label = this.addLabel(text); label.setOffset(topLabelOffset); } - if (this.haveBottomLabel) - { + if (this.haveBottomLabel) { label = this.addLabel(additionalText); label.setOffset(bottomLabelOffset); } - if (this.haveHostileLabels) - { + if (this.haveHostileLabels) { this.addLabel(SymbologyConstants.HOSTILE_ENEMY); this.addLabel(SymbologyConstants.HOSTILE_ENEMY); } - if (haveEchelon) - { + if (haveEchelon) { this.echelonSymbols.add(this.createEchelonSymbol(sidc)); } @@ -205,10 +200,9 @@ protected void createLabels() } } - protected boolean mustCreateIdentityLabels() - { + protected boolean mustCreateIdentityLabels() { return this.isShowHostileIndicator() - && SymbologyConstants.STANDARD_IDENTITY_HOSTILE.equalsIgnoreCase(this.symbolCode.getStandardIdentity()); + && SymbologyConstants.STANDARD_IDENTITY_HOSTILE.equalsIgnoreCase(this.symbolCode.getStandardIdentity()); } /** @@ -217,26 +211,26 @@ protected boolean mustCreateIdentityLabels() * @param dc Current draw context. */ @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { Iterable positions = this.getPositions(); - if (positions == null) + if (positions == null) { return; + } Iterator iterator = positions.iterator(); Iterator echelonIterator = this.echelonSymbols.iterator(); Iterator labelIterator; - if (this.labels != null) + if (this.labels != null) { labelIterator = this.labels.iterator(); - else + } else { labelIterator = Collections.emptyList().iterator(); + } // There can be up to four labels for each segment of the path: top, bottom, and two hostile indicators. Expect // them in the label is in this order. Position posA = iterator.next(); - while (iterator.hasNext() && (labelIterator.hasNext() || echelonIterator.hasNext())) - { + while (iterator.hasNext() && (labelIterator.hasNext() || echelonIterator.hasNext())) { Position posB = iterator.next(); TacticalGraphicLabel topLabel = this.haveTopLabel ? labelIterator.next() : null; @@ -246,27 +240,23 @@ protected void determineLabelPositions(DrawContext dc) LatLon ll = LatLon.interpolate(0.5, posA, posB); Position labelPosition = new Position(ll, 0); - if (topLabel != null) - { + if (topLabel != null) { topLabel.setPosition(labelPosition); topLabel.setOrientationPosition(posB); } - if (bottomLabel != null) - { + if (bottomLabel != null) { bottomLabel.setPosition(labelPosition); bottomLabel.setOrientationPosition(posB); } - if (echelonIterator.hasNext()) - { + if (echelonIterator.hasNext()) { EchelonSymbol symbol = echelonIterator.next(); symbol.setPosition(labelPosition); symbol.setOrientationPosition(posB); } - if (this.haveHostileLabels) - { + if (this.haveHostileLabels) { // Position the first ENY label 25% of the distance from points A and B. TacticalGraphicLabel label = labelIterator.next(); @@ -285,32 +275,34 @@ protected void determineLabelPositions(DrawContext dc) } } - /** {@inheritDoc} Overridden to apply owner to echelon modifiers. */ + /** + * {@inheritDoc} Overridden to apply owner to echelon modifiers. + */ @Override - protected void applyDelegateOwner(Object owner) - { + protected void applyDelegateOwner(Object owner) { super.applyDelegateOwner(owner); - for (EchelonSymbol symbol : this.echelonSymbols) - { + for (EchelonSymbol symbol : this.echelonSymbols) { symbol.setDelegateOwner(owner); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { // The default offset is applied to the "main" label by AbstractTacticalGraphic if the application does // not specify an override offset. On a boundary there isn't really a "main" label, but the first label // in the list is considered the main label. If we have top labels, this will be either a top label, bottom // label, or hostile indicator. - if (this.haveTopLabel) + if (this.haveTopLabel) { return TOP_LABEL_OFFSET; - else if (this.haveBottomLabel) + } else if (this.haveBottomLabel) { return BOTTOM_LABEL_OFFSET; - else + } else { return TacticalGraphicLabel.DEFAULT_OFFSET; + } } /** @@ -318,8 +310,7 @@ else if (this.haveBottomLabel) * * @return Offset applied to the upper label. */ - protected Offset getTopLabelOffset() - { + protected Offset getTopLabelOffset() { return TOP_LABEL_OFFSET; } @@ -328,20 +319,19 @@ protected Offset getTopLabelOffset() * * @return Offset applied to the bottom label. */ - protected Offset getBottomLabelOffset() - { + protected Offset getBottomLabelOffset() { return BOTTOM_LABEL_OFFSET; } - /** {@inheritDoc} Overridden to update echelon symbol attributes. */ + /** + * {@inheritDoc} Overridden to update echelon symbol attributes. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply active attributes to the symbol. - if (this.symbolAttributes != null) - { + if (this.symbolAttributes != null) { ShapeAttributes activeAttributes = this.getActiveShapeAttributes(); this.symbolAttributes.setOpacity(activeAttributes.getInteriorOpacity()); this.symbolAttributes.setTextModifierMaterial(this.getLabelMaterial()); @@ -355,12 +345,12 @@ protected void determineActiveAttributes() * * @return A symbol to render the echelon modifier. */ - protected EchelonSymbol createEchelonSymbol(String sidc) - { + protected EchelonSymbol createEchelonSymbol(String sidc) { EchelonSymbol symbol = new EchelonSymbol(sidc); - if (this.symbolAttributes == null) + if (this.symbolAttributes == null) { this.symbolAttributes = new BasicTacticalSymbolAttributes(); + } symbol.setAttributes(this.symbolAttributes); return symbol; diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttack.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttack.java index 8a9ba02229..f3590d8bfb 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttack.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttack.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -26,28 +25,46 @@ * @author pabercrombie * @version $Id: DirectionOfAttack.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DirectionOfAttack extends AbstractMilStd2525TacticalGraphic -{ - /** Default length of the arrowhead, as a fraction of the total line length. */ +public class DirectionOfAttack extends AbstractMilStd2525TacticalGraphic { + + /** + * Default length of the arrowhead, as a fraction of the total line length. + */ public final static double DEFAULT_ARROWHEAD_LENGTH = 0.1; - /** Default angle of the arrowhead. */ + /** + * Default angle of the arrowhead. + */ public final static Angle DEFAULT_ARROWHEAD_ANGLE = Angle.fromDegrees(60.0); - /** Default width of the arrowhead outline. */ + /** + * Default width of the arrowhead outline. + */ public final static double DEFAULT_ARROWHEAD_OUTLINE_WIDTH = 0.3; - /** Length of the arrowhead from base to tip, as a fraction of the total line length. */ + /** + * Length of the arrowhead from base to tip, as a fraction of the total line length. + */ protected Angle arrowAngle = DEFAULT_ARROWHEAD_ANGLE; - /** Angle of the arrowhead. */ + /** + * Angle of the arrowhead. + */ protected double arrowLength = DEFAULT_ARROWHEAD_LENGTH; - /** Width of the arrowhead outline, as a fraction of the arrowhead length. */ + /** + * Width of the arrowhead outline, as a fraction of the arrowhead length. + */ protected double outlineWidth = DEFAULT_ARROWHEAD_OUTLINE_WIDTH; - /** First control point. */ + /** + * First control point. + */ protected Position startPosition; - /** Second control point. */ + /** + * Second control point. + */ protected Position endPosition; - /** Path used to render the line. */ + /** + * Path used to render the line. + */ protected Path[] paths; /** @@ -55,11 +72,10 @@ public class DirectionOfAttack extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_OFF_LNE_DIRATK_GRD_MANATK, - TacGrpSidc.C2GM_OFF_LNE_DIRATK_GRD_SUPATK + TacGrpSidc.C2GM_OFF_LNE_DIRATK_GRD_MANATK, + TacGrpSidc.C2GM_OFF_LNE_DIRATK_GRD_SUPATK ); } @@ -68,8 +84,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public DirectionOfAttack(String sidc) - { + public DirectionOfAttack(String sidc) { super(sidc); } @@ -78,8 +93,7 @@ public DirectionOfAttack(String sidc) * * @return Angle of the arrowhead in the graphic. */ - public Angle getArrowAngle() - { + public Angle getArrowAngle() { return this.arrowAngle; } @@ -88,17 +102,14 @@ public Angle getArrowAngle() * * @param arrowAngle The angle of the arrowhead. Must be greater than zero degrees and less than 90 degrees. */ - public void setArrowAngle(Angle arrowAngle) - { - if (arrowAngle == null) - { + public void setArrowAngle(Angle arrowAngle) { + if (arrowAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (arrowAngle.degrees <= 0) - { + if (arrowAngle.degrees <= 0) { String msg = Logging.getMessage("generic.AngleOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -112,8 +123,7 @@ public void setArrowAngle(Angle arrowAngle) * * @return The length of the arrowhead as a fraction of the total line length. */ - public double getArrowLength() - { + public double getArrowLength() { return this.arrowLength; } @@ -121,12 +131,10 @@ public double getArrowLength() * Specifies the length of the arrowhead. * * @param arrowLength Length of the arrowhead as a fraction of the total line length. If the arrowhead length is - * 0.25, then the arrowhead length will be one quarter of the total line length. + * 0.25, then the arrowhead length will be one quarter of the total line length. */ - public void setArrowLength(double arrowLength) - { - if (arrowLength < 0) - { + public void setArrowLength(double arrowLength) { + if (arrowLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -141,8 +149,7 @@ public void setArrowLength(double arrowLength) * * @return Width of the outline as a fraction of the arrowhead length. */ - public double getOutlineWidth() - { + public double getOutlineWidth() { return this.outlineWidth; } @@ -152,10 +159,8 @@ public double getOutlineWidth() * * @param outlineWidth Width of the outline as a fraction of the length of the arrowhead. */ - public void setOutlineWidth(double outlineWidth) - { - if (outlineWidth < 0) - { + public void setOutlineWidth(double outlineWidth) { + if (outlineWidth < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -169,23 +174,18 @@ public void setOutlineWidth(double outlineWidth) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.endPosition = iterator.next(); this.startPosition = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -194,46 +194,47 @@ public void setPositions(Iterable positions) this.paths = null; // Need to recompute path for the new control points } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.endPosition, this.startPosition); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.startPosition; } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - for (Path path : this.paths) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + for (Path path : this.paths) { path.render(dc); } } @Override - protected void computeGeometry(DrawContext dc) - { - if (this.paths == null) - { + protected void computeGeometry(DrawContext dc) { + if (this.paths == null) { this.createShapes(dc); } super.computeGeometry(dc); } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths == null) { return; + } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.setDelegateOwner(owner); } } @@ -243,8 +244,7 @@ protected void applyDelegateOwner(Object owner) * * @return {@code true} if the arrow head should be drawn outlined. */ - protected boolean isDrawOutlined() - { + protected boolean isDrawOutlined() { // Draw the arrow head outlined if this is a Main Attack graphic. return TacGrpSidc.C2GM_OFF_LNE_DIRATK_GRD_MANATK.equalsIgnoreCase(this.maskedSymbolCode); } @@ -254,15 +254,13 @@ protected boolean isDrawOutlined() * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { this.paths = new Path[2]; // Create a path for the line part of the arrow this.paths[0] = this.createPath(Arrays.asList(this.startPosition, this.endPosition)); // Create the arrowhead - Globe globe = dc.getGlobe(); Vec4 p1 = globe.computePointFromPosition(this.startPosition); Vec4 p2 = globe.computePointFromPosition(this.endPosition); @@ -278,15 +276,14 @@ protected void createShapes(DrawContext dc) /** * Determine the positions that make up the arrowhead. * - * @param dc Current draw context. - * @param tip Point at the tip of the arrow head. - * @param dir Vector in the direction of the arrow head. + * @param dc Current draw context. + * @param tip Point at the tip of the arrow head. + * @param dir Vector in the direction of the arrow head. * @param length Length of the arrowhead from base to tip. * * @return Positions that define the arrowhead. */ - protected List computeArrowheadPositions(DrawContext dc, Vec4 tip, Vec4 dir, double length) - { + protected List computeArrowheadPositions(DrawContext dc, Vec4 tip, Vec4 dir, double length) { Globe globe = dc.getGlobe(); // The arrowhead is drawn outlined for the Main Attack graphic, and as a single line for the Supporting Attack @@ -303,7 +300,6 @@ protected List computeArrowheadPositions(DrawContext dc, Vec4 tip, Vec // D // | | // Length - @SuppressWarnings({"UnnecessaryLocalVariable"}) Vec4 ptB = tip; @@ -325,8 +321,7 @@ protected List computeArrowheadPositions(DrawContext dc, Vec4 tip, Vec Vec4 ptC = arrowBase.subtract3(perpendicular); List positions; - if (this.isDrawOutlined()) - { + if (this.isDrawOutlined()) { double outlineWidth = this.getOutlineWidth(); // Find points D and F @@ -337,9 +332,7 @@ protected List computeArrowheadPositions(DrawContext dc, Vec4 tip, Vec Vec4 ptE = ptB.subtract3(dir.multiply3(length * outlineWidth)); positions = TacticalGraphicUtil.asPositionList(globe, ptA, ptB, ptC, ptD, ptE, ptF, ptA); - } - else - { + } else { positions = TacticalGraphicUtil.asPositionList(globe, ptA, ptB, ptC); } @@ -353,8 +346,7 @@ protected List computeArrowheadPositions(DrawContext dc, Vec4 tip, Vec * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(List positions) - { + protected Path createPath(List positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttackAviation.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttackAviation.java index 7b7256c7d1..2905071030 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttackAviation.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttackAviation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -21,22 +20,36 @@ * @author pabercrombie * @version $Id: DirectionOfAttackAviation.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class DirectionOfAttackAviation extends DirectionOfAttack -{ - /** Default number of intervals used to draw the curve. */ +public class DirectionOfAttackAviation extends DirectionOfAttack { + + /** + * Default number of intervals used to draw the curve. + */ public final static int DEFAULT_NUM_INTERVALS = 32; - /** Default length of the bow tie part of the graphic, as a fraction of the graphic's total length. */ + /** + * Default length of the bow tie part of the graphic, as a fraction of the graphic's total length. + */ public final static double DEFAULT_BOW_TIE_LENGTH = 0.05; - /** Default width of the bow tie part of the graphic, as a fraction of the length of the bow tie. */ + /** + * Default width of the bow tie part of the graphic, as a fraction of the length of the bow tie. + */ public final static double DEFAULT_BOW_TIE_WIDTH = 0.25; - /** Default angle that determines the curvature of the line. */ + /** + * Default angle that determines the curvature of the line. + */ public final static Angle DEFAULT_CURVATURE = Angle.fromDegrees(25); - /** Number of intervals used to draw the curve. */ + /** + * Number of intervals used to draw the curve. + */ protected int intervals = DEFAULT_NUM_INTERVALS; - /** Length of the bow tie part of the graphic, as a fraction of the graphic's total length. */ + /** + * Length of the bow tie part of the graphic, as a fraction of the graphic's total length. + */ protected double bowTieLength = DEFAULT_BOW_TIE_LENGTH; - /** Width of the bow tie part of the graphic, as a fraction of the length of the bow tie. */ + /** + * Width of the bow tie part of the graphic, as a fraction of the length of the bow tie. + */ protected double bowTieWidth = DEFAULT_BOW_TIE_WIDTH; /** * Angle that controls the curve of the line. A large angle results in a more pronounced curve. An angle of zero @@ -49,8 +62,7 @@ public class DirectionOfAttackAviation extends DirectionOfAttack * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_LNE_DIRATK_AVN); } @@ -59,8 +71,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public DirectionOfAttackAviation(String sidc) - { + public DirectionOfAttackAviation(String sidc) { super(sidc); } @@ -70,8 +81,7 @@ public DirectionOfAttackAviation(String sidc) * * @return Intervals used to draw arc. */ - public int getIntervals() - { + public int getIntervals() { return this.intervals; } @@ -81,10 +91,8 @@ public int getIntervals() * * @param intervals Number of intervals for drawing the curve. */ - public void setIntervals(int intervals) - { - if (intervals < 1) - { + public void setIntervals(int intervals) { + if (intervals < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -99,8 +107,7 @@ public void setIntervals(int intervals) * * @return Length of the bow tie as a fraction of the total length of the graphic. */ - public double getBowTieLength() - { + public double getBowTieLength() { return this.bowTieLength; } @@ -109,10 +116,8 @@ public double getBowTieLength() * * @param bowTieLength Length of the bow tie as a fraction of the total length of the graphic. */ - public void setBowTieLength(double bowTieLength) - { - if (bowTieLength < 0.0 || bowTieLength > 1.0) - { + public void setBowTieLength(double bowTieLength) { + if (bowTieLength < 0.0 || bowTieLength > 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", bowTieLength); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -126,8 +131,7 @@ public void setBowTieLength(double bowTieLength) * * @return Width of the bow tie as a fraction of the length of the bow tie. */ - public double getBowTieWidth() - { + public double getBowTieWidth() { return this.bowTieWidth; } @@ -136,10 +140,8 @@ public double getBowTieWidth() * * @param bowTieWidth Width of the bow tie as a fraction of the length of the bow tie. */ - public void setBowTieWidth(double bowTieWidth) - { - if (bowTieWidth < 0.0 || bowTieWidth > 1.0) - { + public void setBowTieWidth(double bowTieWidth) { + if (bowTieWidth < 0.0 || bowTieWidth > 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", bowTieWidth); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -154,8 +156,7 @@ public void setBowTieWidth(double bowTieWidth) * * @return The angle that determines the curvature of the line. */ - public Angle getCurvature() - { + public Angle getCurvature() { return this.curvature; } @@ -165,10 +166,8 @@ public Angle getCurvature() * * @param angle The angle that determines the curvature of the line. */ - public void setCurvature(Angle angle) - { - if (angle == null) - { + public void setCurvature(Angle angle) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -176,8 +175,7 @@ public void setCurvature(Angle angle) this.curvature = angle; } - protected void onShapeChanged() - { + protected void onShapeChanged() { this.paths = null; // Need to recompute paths } @@ -187,8 +185,7 @@ protected void onShapeChanged() * @param dc Current draw context. */ @Override - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { // This graphic is composed of four paths: // 1) Curve from the start position to the bow tie. // 2) Curve from the bow tie to the end position. @@ -211,8 +208,7 @@ protected void createShapes(DrawContext dc) // Invoke the Hermite curve function to compute points along the curve. int intervals = this.getIntervals(); double delta = 1.0 / intervals; - for (int i = 0; i < intervals; i++) - { + for (int i = 0; i < intervals; i++) { double t = i * delta; Vec4 p = this.hermiteCurve(p1, p2, t1, t1, t); Position pos = globe.computePositionFromPoint(p); @@ -251,14 +247,13 @@ protected void createShapes(DrawContext dc) /** * Create positions required to to draw the bow tie part of the graphic. * - * @param dc Current draw context. + * @param dc Current draw context. * @param pos1 Position at the center of one side of the bow tie. * @param pos2 Position at the center of the other side of the bow tie. * * @return Positions that describe the bow tie. */ - protected List createBowTie(DrawContext dc, Position pos1, Position pos2) - { + protected List createBowTie(DrawContext dc, Position pos1, Position pos2) { // A C // |\ /| // Pt. 1 | \/ | Pt. 2 @@ -299,42 +294,39 @@ protected List createBowTie(DrawContext dc, Position pos1, Position po * H(t) = (1 - 3t2 + 2t3)P1 + t2(3 - 2t)P2 + t(t - * 1)2T1 + t2(t - 1)T2 * - * @param pt1 First control point. - * @param pt2 Second control point. + * @param pt1 First control point. + * @param pt2 Second control point. * @param tangent1 Vector tangent to the curve at the first control point. * @param tangent2 Vector tangent to the curve at the second control point. - * @param t Interpolation parameter in the range [0..1]. + * @param t Interpolation parameter in the range [0..1]. * * @return A point along the curve. */ - protected Vec4 hermiteCurve(Vec4 pt1, Vec4 pt2, Vec4 tangent1, Vec4 tangent2, double t) - { + protected Vec4 hermiteCurve(Vec4 pt1, Vec4 pt2, Vec4 tangent1, Vec4 tangent2, double t) { double c1 = (1 - 3 * t * t + 2 * Math.pow(t, 3)); double c2 = (3 - 2 * t) * t * t; double c3 = t * Math.pow(t - 1, 2); double c4 = (t - 1) * t * t; return pt1.multiply3(c1) - .add3(pt2.multiply3(c2)) - .add3(tangent1.multiply3(c3)) - .add3(tangent2.multiply3(c4)); + .add3(pt2.multiply3(c2)) + .add3(tangent1.multiply3(c3)) + .add3(tangent2.multiply3(c4)); } @Override - protected void createLabels() - { + protected void createLabels() { // This graphic supports only the hostile indicator label. - if (this.mustShowHostileIndicator()) - { + if (this.mustShowHostileIndicator()) { this.addLabel(SymbologyConstants.HOSTILE_ENEMY); } } @Override - protected void determineLabelPositions(DrawContext dc) - { - if (WWUtil.isEmpty(this.labels) || this.paths == null) + protected void determineLabelPositions(DrawContext dc) { + if (WWUtil.isEmpty(this.labels) || this.paths == null) { return; + } Angle angle = LatLon.greatCircleDistance(this.startPosition, this.endPosition); double length = angle.radians * dc.getGlobe().getRadius(); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttackForFeint.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttackForFeint.java index e87deb2135..a5d25cdde4 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttackForFeint.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DirectionOfAttackForFeint.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.avlist.AVKey; @@ -22,26 +21,34 @@ * @author pabercrombie * @version $Id: DirectionOfAttackForFeint.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class DirectionOfAttackForFeint extends DirectionOfAttack -{ +public class DirectionOfAttackForFeint extends DirectionOfAttack { + /** * Offset applied to the label. This offset aligns the bottom edge of the label with the geographic position, in * order to keep the label above the graphic as the zoom changes. */ protected final static Offset LABEL_OFFSET = new Offset(0.0, -1.0, AVKey.FRACTION, AVKey.FRACTION); - /** Default angle of the arrowhead. */ + /** + * Default angle of the arrowhead. + */ public final static Angle DEFAULT_ARROWHEAD_ANGLE = Angle.POS90; /** * Factor used to compute the distance between the solid and dashed lines in the arrow head. A larger value will * move the dashed line farther from the solid line. */ protected static final double DASHED_LINE_DISTANCE = 0.5; - /** Default number of intervals used to draw the curve. */ + /** + * Default number of intervals used to draw the curve. + */ public final static int DEFAULT_NUM_INTERVALS = 32; - /** Default factor that determines the curvature of the line. */ + /** + * Default factor that determines the curvature of the line. + */ public final static double DEFAULT_CURVATURE = 0.5; - /** Number of intervals used to draw the curve. */ + /** + * Number of intervals used to draw the curve. + */ protected int intervals = DEFAULT_NUM_INTERVALS; /** * Factor that controls the curve of the line. Valid values are 0 to 1. Larger values result in a more pronounced @@ -49,10 +56,14 @@ public class DirectionOfAttackForFeint extends DirectionOfAttack */ protected double curvature = DEFAULT_CURVATURE; - /** Shape attributes for the dashed part of the graphic. */ + /** + * Shape attributes for the dashed part of the graphic. + */ protected ShapeAttributes dashedAttributes = new BasicShapeAttributes(); - /** Position of the label along the curve. */ + /** + * Position of the label along the curve. + */ protected Position labelPosition; /** * Orientation position for the label. (The label is drawn on a line between this position and {@link @@ -65,8 +76,7 @@ public class DirectionOfAttackForFeint extends DirectionOfAttack * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_DCPN_DAFF); } @@ -75,8 +85,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public DirectionOfAttackForFeint(String sidc) - { + public DirectionOfAttackForFeint(String sidc) { super(sidc); this.setArrowAngle(DEFAULT_ARROWHEAD_ANGLE); } @@ -87,8 +96,7 @@ public DirectionOfAttackForFeint(String sidc) * * @return Intervals used to draw arc. */ - public int getIntervals() - { + public int getIntervals() { return this.intervals; } @@ -98,10 +106,8 @@ public int getIntervals() * * @param intervals Number of intervals for drawing the curve. Must at least three. */ - public void setIntervals(int intervals) - { - if (intervals < 3) - { + public void setIntervals(int intervals) { + if (intervals < 3) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -117,8 +123,7 @@ public void setIntervals(int intervals) * * @return The factor that determines the curvature of the line. */ - public double getCurvature() - { + public double getCurvature() { return this.curvature; } @@ -128,10 +133,8 @@ public double getCurvature() * * @param factor The factor that determines the curvature of the line. */ - public void setCurvature(double factor) - { - if (factor < 0.0 || factor > 1.0) - { + public void setCurvature(double factor) { + if (factor < 0.0 || factor > 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -139,8 +142,7 @@ public void setCurvature(double factor) this.curvature = factor; } - protected void onShapeChanged() - { + protected void onShapeChanged() { this.paths = null; // Need to recompute paths } @@ -150,8 +152,7 @@ protected void onShapeChanged() * @param dc Current draw context. */ @Override - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { // This graphic is composed of three paths: // 1) Curve from start position to the tip of the arrow head // 3) The arrow head @@ -177,8 +178,7 @@ protected void createShapes(DrawContext dc) // Invoke the Bezier curve function to compute points along the curve. int intervals = this.getIntervals(); double delta = 1.0 / intervals; - for (int i = 0; i < intervals; i++) - { + for (int i = 0; i < intervals; i++) { double t = i * delta; Vec4 p = TacticalGraphicUtil.bezierCurve(controlPoints, t, coefficients); Position pos = globe.computePositionFromPoint(p); @@ -186,8 +186,7 @@ protected void createShapes(DrawContext dc) // Determine if this point is further from the control line than previous points. double dist = controlLine.distanceTo(p); - if (dist > maxDistance) - { + if (dist > maxDistance) { furthestPoint = i; maxDistance = dist; } @@ -196,12 +195,9 @@ protected void createShapes(DrawContext dc) // Determine where to put the label. this.labelPosition = curvePositions.get(furthestPoint); - if (furthestPoint != curvePositions.size() - 1) - { + if (furthestPoint != curvePositions.size() - 1) { this.labelOrientationPosition = curvePositions.get(furthestPoint + 1); - } - else - { + } else { // If the furthest point is at the end of line then use the previous point as the orientation position. // This should never happen due to the shape of the curve in this graphic, but include this check in // case a subclass changes the curve control points. @@ -228,10 +224,11 @@ protected void createShapes(DrawContext dc) this.paths[2].setAttributes(this.dashedAttributes); } - /** Determine active attributes for this frame. */ + /** + * Determine active attributes for this frame. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Copy active attributes to the dashed attribute bundle. @@ -243,30 +240,29 @@ protected void determineActiveAttributes() } @Override - protected void createLabels() - { + protected void createLabels() { String text = this.getText(); - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { TacticalGraphicLabel label = this.addLabel(text); label.setOffset(LABEL_OFFSET); } } @Override - protected void determineLabelPositions(DrawContext dc) - { - if (WWUtil.isEmpty(this.labels)) + protected void determineLabelPositions(DrawContext dc) { + if (WWUtil.isEmpty(this.labels)) { return; + } this.labels.get(0).setPosition(this.labelPosition); this.labels.get(0).setOrientationPosition(this.labelOrientationPosition); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { return LABEL_OFFSET; } @@ -274,17 +270,16 @@ protected Offset getDefaultLabelOffset() * Compute the position of control points that will generate a Bezier curve that looks like the Direction of Attack * for Feint graphic in MIL-STD-2525C (pg. 499). * - * @param dc Current draw context. - * @param start Beginning of the infiltration lane control line. - * @param end End of the infiltration lane control line. + * @param dc Current draw context. + * @param start Beginning of the infiltration lane control line. + * @param end End of the infiltration lane control line. * @param curvature Factor that controls the curvature of the line. Valid values are between zero and one. A higher - * value results in a more pronounced curve. + * value results in a more pronounced curve. * * @return Control points for a Bezier curve. The first control point is equal to {@code start}, and the last point - * is equal to {@code end}. + * is equal to {@code end}. */ - protected Vec4[] computeBezierControlPoints(DrawContext dc, Vec4 start, Vec4 end, double curvature) - { + protected Vec4[] computeBezierControlPoints(DrawContext dc, Vec4 start, Vec4 end, double curvature) { Globe globe = dc.getGlobe(); // Find length and direction of the control line. @@ -309,12 +304,11 @@ protected Vec4[] computeBezierControlPoints(DrawContext dc, Vec4 start, Vec4 end // Choose regularly spaced points along the control line. At each point select a point to the left of the line, // on the line, or to the right of the line. double delta = length / (coefficients.length + 1); - for (int i = 0; i < coefficients.length; i++) - { + for (int i = 0; i < coefficients.length; i++) { controlPoints[i + 1] = start.add3(dir.multiply3((i + 1) * delta)) - .add3(perpendicular.multiply3(coefficients[i])); + .add3(perpendicular.multiply3(coefficients[i])); } return controlPoints; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DoseRateContourLine.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DoseRateContourLine.java index 6692d15a8c..6887e7aaf3 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DoseRateContourLine.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/DoseRateContourLine.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.Position; @@ -20,20 +19,18 @@ * @author pabercrombie * @version $Id: DoseRateContourLine.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class DoseRateContourLine extends BasicArea -{ +public class DoseRateContourLine extends BasicArea { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.MOBSU_CBRN_DRCL); } - public DoseRateContourLine(String sidc) - { + public DoseRateContourLine(String sidc) { super(sidc); } @@ -46,8 +43,7 @@ public DoseRateContourLine(String sidc) * @return Position for the graphic's main label. */ @Override - protected Position determineMainLabelPosition(DrawContext dc) - { + protected Position determineMainLabelPosition(DrawContext dc) { return this.getReferencePosition(); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/FireSupportLine.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/FireSupportLine.java index 517d522d42..46c77f49bf 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/FireSupportLine.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/FireSupportLine.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -26,9 +25,11 @@ * @author pabercrombie * @version $Id: FireSupportLine.java 709 2012-08-06 18:27:00Z pabercrombie $ */ -public class FireSupportLine extends AbstractMilStd2525TacticalGraphic -{ - /** Factor applied to the stipple pattern used to draw the dashed line for a Coordinated Fire Line. */ +public class FireSupportLine extends AbstractMilStd2525TacticalGraphic { + + /** + * Factor applied to the stipple pattern used to draw the dashed line for a Coordinated Fire Line. + */ protected static final int CFL_OUTLINE_STIPPLE_FACTOR = 12; /** @@ -45,12 +46,15 @@ public class FireSupportLine extends AbstractMilStd2525TacticalGraphic /** * The value of an optional second text string for the graphic. This value is equivalent to the "T1" modifier * defined by MIL-STD-2525C. It can be set using {@link #setAdditionalText(String)}, or by passing an Iterable to - * {@link #setModifier(String, Object)} with a key of {@link gov.nasa.worldwind.symbology.SymbologyConstants#UNIQUE_DESIGNATION} - * (additional text is the second value in the iterable). + * {@link #setModifier(String, Object)} with a key of + * {@link gov.nasa.worldwind.symbology.SymbologyConstants#UNIQUE_DESIGNATION} (additional text is the second value + * in the iterable). */ protected String additionalText; - /** Paths used to render the graphic. */ + /** + * Paths used to render the graphic. + */ protected Path path; /** @@ -58,12 +62,11 @@ public class FireSupportLine extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.FSUPP_LNE_C2LNE_FSCL, - TacGrpSidc.FSUPP_LNE_C2LNE_CFL, - TacGrpSidc.FSUPP_LNE_C2LNE_RFL + TacGrpSidc.FSUPP_LNE_C2LNE_FSCL, + TacGrpSidc.FSUPP_LNE_C2LNE_CFL, + TacGrpSidc.FSUPP_LNE_C2LNE_RFL ); } @@ -72,8 +75,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public FireSupportLine(String sidc) - { + public FireSupportLine(String sidc) { super(sidc); this.path = this.createPath(); } @@ -84,8 +86,7 @@ public FireSupportLine(String sidc) * * @return The additional text. May be null. */ - public String getAdditionalText() - { + public String getAdditionalText() { return this.additionalText; } @@ -95,18 +96,15 @@ public String getAdditionalText() * * @param text The additional text. May be null. */ - public void setAdditionalText(String text) - { + public void setAdditionalText(String text) { this.additionalText = text; this.onModifierChanged(); } @Override - public Object getModifier(String key) - { + public Object getModifier(String key) { // If two values are set for the Unique Designation, return both in a list. - if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && this.additionalText != null) - { + if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && this.additionalText != null) { return Arrays.asList(this.getText(), this.getAdditionalText()); } @@ -114,24 +112,18 @@ public Object getModifier(String key) } @Override - public void setModifier(String key, Object value) - { - if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && value instanceof Iterable) - { + public void setModifier(String key, Object value) { + if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && value instanceof Iterable) { Iterator iterator = ((Iterable) value).iterator(); - if (iterator.hasNext()) - { + if (iterator.hasNext()) { this.setText((String) iterator.next()); } // The Final Protective Fire graphic supports a second Unique Designation value - if (iterator.hasNext()) - { + if (iterator.hasNext()) { this.setAdditionalText((String) iterator.next()); } - } - else - { + } else { super.setModifier(key, value); } } @@ -141,10 +133,8 @@ public void setModifier(String key, Object value) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -153,34 +143,39 @@ public void setPositions(Iterable positions) this.path.setPositions(positions); } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return this.path.getPositions(); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.path.getReferencePosition(); } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { this.path.render(dc); } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { this.path.setDelegateOwner(owner); } - /** Create labels for the graphic. */ + /** + * Create labels for the graphic. + */ @Override - protected void createLabels() - { + protected void createLabels() { // First two labels are the start and end labels. String text = this.getEndOfLineText(); this.addLabel(text).setTextAlign(AVKey.RIGHT); // Start label @@ -199,8 +194,7 @@ protected void createLabels() label = this.addLabel(bottomText); label.setOffset(bottomLabelOffset); - if (this.isDrawDoubleLabel()) - { + if (this.isDrawDoubleLabel()) { label = this.addLabel(topText); label.setOffset(topLabelOffset); @@ -216,8 +210,7 @@ protected void createLabels() * * @return true if the graphic includes two pairs of top/bottom labels. Both pairs contain the same text content. */ - protected boolean isDrawDoubleLabel() - { + protected boolean isDrawDoubleLabel() { return !TacGrpSidc.FSUPP_LNE_C2LNE_CFL.equalsIgnoreCase(this.maskedSymbolCode); } @@ -226,13 +219,11 @@ protected boolean isDrawDoubleLabel() * * @return Text for the end of line labels. */ - protected String getEndOfLineText() - { + protected String getEndOfLineText() { StringBuilder sb = new StringBuilder("PL"); String text = this.getAdditionalText(); - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { sb.append(" "); sb.append(text); } @@ -245,24 +236,19 @@ protected String getEndOfLineText() * * @return Text for the top label. May return null if there is no top label. */ - protected String getTopLabelText() - { + protected String getTopLabelText() { StringBuilder sb = new StringBuilder(); String text = this.getText(); - if (!WWUtil.isEmpty(text)) + if (!WWUtil.isEmpty(text)) { sb.append(text); + } - if (TacGrpSidc.FSUPP_LNE_C2LNE_FSCL.equalsIgnoreCase(this.maskedSymbolCode)) - { + if (TacGrpSidc.FSUPP_LNE_C2LNE_FSCL.equalsIgnoreCase(this.maskedSymbolCode)) { sb.append(" FSCL"); - } - else if (TacGrpSidc.FSUPP_LNE_C2LNE_CFL.equalsIgnoreCase(this.maskedSymbolCode)) - { + } else if (TacGrpSidc.FSUPP_LNE_C2LNE_CFL.equalsIgnoreCase(this.maskedSymbolCode)) { sb.insert(0, "CFL "); - } - else if (TacGrpSidc.FSUPP_LNE_C2LNE_RFL.equalsIgnoreCase(this.maskedSymbolCode)) - { + } else if (TacGrpSidc.FSUPP_LNE_C2LNE_RFL.equalsIgnoreCase(this.maskedSymbolCode)) { sb.insert(0, "RFL "); } @@ -274,31 +260,30 @@ else if (TacGrpSidc.FSUPP_LNE_C2LNE_RFL.equalsIgnoreCase(this.maskedSymbolCode)) * * @return Text for the bottom label. May return null if there is no bottom label. */ - protected String getBottomLabelText() - { + protected String getBottomLabelText() { StringBuilder sb = new StringBuilder(); Object[] dates = TacticalGraphicUtil.getDateRange(this); - if (dates[0] != null) - { + if (dates[0] != null) { sb.append(dates[0]); sb.append("-\n"); } - if (dates[1] != null) - { + if (dates[1] != null) { sb.append(dates[1]); } return sb.toString(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (this.labels == null || this.labels.size() == 0) + protected void determineLabelPositions(DrawContext dc) { + if (this.labels == null || this.labels.size() == 0) { return; + } Object[] pathData = this.computePathLength(dc); Position startPosition = (Position) pathData[0]; @@ -316,13 +301,10 @@ protected void determineLabelPositions(DrawContext dc) endLabel.setPosition(endPosition); // Set the West-most label to right alignment, and the East-most label to left alignment. - if (startPosition.longitude.degrees < endPosition.longitude.degrees) - { + if (startPosition.longitude.degrees < endPosition.longitude.degrees) { startLabel.setTextAlign(AVKey.RIGHT); endLabel.setTextAlign(AVKey.LEFT); - } - else - { + } else { startLabel.setTextAlign(AVKey.LEFT); endLabel.setTextAlign(AVKey.RIGHT); } @@ -340,8 +322,7 @@ protected void determineLabelPositions(DrawContext dc) TacticalGraphicUtil.placeLabelsOnPath(dc, positions, topLabel, bottomLabel, dist); // If there are more labels it will be a second top/bottom pair. (Note that CFL graphic has only one top/bottom pair.) - if (labelIterator.hasNext()) - { + if (labelIterator.hasNext()) { topLabel = labelIterator.next(); bottomLabel = labelIterator.next(); @@ -356,10 +337,9 @@ protected void determineLabelPositions(DrawContext dc) * @param dc Current draw context. * * @return Returns the path's start position, end position, and length (non-terrain following) as a three element - * array: [Position start, Position end, Double length]. + * array: [Position start, Position end, Double length]. */ - protected Object[] computePathLength(DrawContext dc) - { + protected Object[] computePathLength(DrawContext dc) { Iterator iterator = this.path.getPositions().iterator(); Globe globe = dc.getGlobe(); @@ -372,8 +352,7 @@ protected Object[] computePathLength(DrawContext dc) double pathLength = 0; pt1 = globe.computePointFromLocation(startPosition); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { endPosition = iterator.next(); pt2 = globe.computePointFromLocation(endPosition); @@ -381,13 +360,14 @@ protected Object[] computePathLength(DrawContext dc) pt1 = pt2; } - return new Object[] {startPosition, endPosition, pathLength}; + return new Object[]{startPosition, endPosition, pathLength}; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { return TOP_LABEL_OFFSET; } @@ -396,8 +376,7 @@ protected Offset getDefaultLabelOffset() * * @return Offset applied to the upper label. */ - protected Offset getTopLabelOffset() - { + protected Offset getTopLabelOffset() { return TOP_LABEL_OFFSET; } @@ -406,20 +385,19 @@ protected Offset getTopLabelOffset() * * @return Offset applied to the bottom label. */ - protected Offset getBottomLabelOffset() - { + protected Offset getBottomLabelOffset() { return BOTTOM_LABEL_OFFSET; } - /** {@inheritDoc} Overridden to draw Coordinated Fire Line with dashed pattern. */ + /** + * {@inheritDoc} Overridden to draw Coordinated Fire Line with dashed pattern. + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); // Coordinated Fire Line always renders with dashed lines. - if (TacGrpSidc.FSUPP_LNE_C2LNE_CFL.equalsIgnoreCase(this.maskedSymbolCode)) - { + if (TacGrpSidc.FSUPP_LNE_C2LNE_CFL.equalsIgnoreCase(this.maskedSymbolCode)) { attributes.setOutlineStippleFactor(CFL_OUTLINE_STIPPLE_FACTOR); attributes.setOutlineStipplePattern(this.getOutlineStipplePattern()); } @@ -430,8 +408,7 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath() - { + protected Path createPath() { Path path = new Path(); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/ForwardEdgeOfBattleArea.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/ForwardEdgeOfBattleArea.java index b3c1786515..fbed5bd90f 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/ForwardEdgeOfBattleArea.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/ForwardEdgeOfBattleArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.*; @@ -25,8 +24,8 @@ * @author pabercrombie * @version $Id: ForwardEdgeOfBattleArea.java 2196 2014-08-06 19:42:15Z tgaskins $ */ -public class ForwardEdgeOfBattleArea extends AbstractMilStd2525TacticalGraphic -{ +public class ForwardEdgeOfBattleArea extends AbstractMilStd2525TacticalGraphic { + protected final static Offset LEFT_CENTER = Offset.fromFraction(-0.1, 0.5); protected final static Offset RIGHT_CENTER = Offset.fromFraction(1.1, 0.5); @@ -35,17 +34,20 @@ public class ForwardEdgeOfBattleArea extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_DEF_LNE_FEBA); } - /** Implementation of TacticalSymbol to draw a symbol at the end of a FEBA line. */ - protected static class FEBASymbol extends AbstractTacticalSymbol - { + /** + * Implementation of TacticalSymbol to draw a symbol at the end of a FEBA line. + */ + protected static class FEBASymbol extends AbstractTacticalSymbol { + protected String symbolCode; - /** Indicates if the text ("FEBA") is right aligned or left aligned. */ + /** + * Indicates if the text ("FEBA") is right aligned or left aligned. + */ protected boolean leftAlign; /** @@ -55,8 +57,7 @@ protected static class FEBASymbol extends AbstractTacticalSymbol * * @param symbolCode MIL-STD-2525C SIDC that identifies the graphic. */ - protected FEBASymbol(String symbolCode) - { + protected FEBASymbol(String symbolCode) { super(); this.symbolCode = symbolCode; @@ -65,13 +66,14 @@ protected FEBASymbol(String symbolCode) // Configure this tactical point graphic's icon retriever and modifier retriever with either the // configuration value or the default value (in that order of precedence). String iconRetrieverPath = Configuration.getStringValue(AVKey.MIL_STD_2525_ICON_RETRIEVER_PATH, - MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); + MilStd2525Constants.DEFAULT_ICON_RETRIEVER_PATH); this.setIconRetriever(new MilStd2525PointGraphicRetriever(iconRetrieverPath)); } - /** {@inheritDoc} */ - public String getIdentifier() - { + /** + * {@inheritDoc} + */ + public String getIdentifier() { return this.symbolCode; } @@ -79,20 +81,20 @@ public String getIdentifier() * Specifies whether the text ("FEBA") will be drawn on the left or right side of the symbol. * * @param align AVKey.LEFT or AVKey.RIGHT. An alignment of AVKey.LEFT indicates that the left edge of the text - * aligns with the graphic (which puts the text on the right side of the circle). If the alignment - * is any value other than AVKey.LEFT or AVKey.RIGHT the alignment is assumed to be AVKey.RIGHT. + * aligns with the graphic (which puts the text on the right side of the circle). If the alignment is any value + * other than AVKey.LEFT or AVKey.RIGHT the alignment is assumed to be AVKey.RIGHT. */ - public void setTextAlign(String align) - { + public void setTextAlign(String align) { // We only handle left and right alignment. If the alignment string is anything other than left we treat it // as right align. this.leftAlign = AVKey.LEFT.equals(align); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) - { + protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymbol osym) { this.currentLabels.clear(); Font font = this.getActiveAttributes().getTextModifierFont(); @@ -111,19 +113,16 @@ protected void layoutTextModifiers(DrawContext dc, AVList modifiers, OrderedSymb * @param status the new value for the Status/Operational Condition field. * * @throws IllegalArgumentException if the specified value is null or is not one of the accepted - * status values. + * status values. */ - public void setStatus(String status) - { - if (status == null) - { + public void setStatus(String status) { + if (status == null) { String msg = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!SymbologyConstants.STATUS_ALL.contains(status.toUpperCase())) - { + if (!SymbologyConstants.STATUS_ALL.contains(status.toUpperCase())) { String msg = Logging.getMessage("Symbology.InvalidStatus", status); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -139,24 +138,28 @@ public void setStatus(String status) * * @return The string "FEBA". */ - protected String getText() - { + protected String getText() { return "FEBA"; } @Override - protected int getMaxLabelLines(AVList modifiers) - { + protected int getMaxLabelLines(AVList modifiers) { return 1; // Only one line of text. } } - /** Symbol drawn at first control point. */ + /** + * Symbol drawn at first control point. + */ protected FEBASymbol symbol1; - /** Symbol drawn at second control point. */ + /** + * Symbol drawn at second control point. + */ protected FEBASymbol symbol2; - /** Attribute bundle shared by the two symbols. */ + /** + * Attribute bundle shared by the two symbols. + */ protected TacticalSymbolAttributes activeSymbolAttributes = new BasicTacticalSymbolAttributes(); /** @@ -164,8 +167,7 @@ protected int getMaxLabelLines(AVList modifiers) * * @param sidc Symbol code the identifies the graphic. */ - public ForwardEdgeOfBattleArea(String sidc) - { + public ForwardEdgeOfBattleArea(String sidc) { super(sidc); this.init(sidc); } @@ -175,8 +177,7 @@ public ForwardEdgeOfBattleArea(String sidc) * * @param sidc Symbol code the identifies the graphic. */ - protected void init(String sidc) - { + protected void init(String sidc) { this.symbol1 = new FEBASymbol(sidc); this.symbol2 = new FEBASymbol(sidc); @@ -184,78 +185,80 @@ protected void init(String sidc) this.symbol2.setAttributes(this.activeSymbolAttributes); } - /** {@inheritDoc} */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + /** + * {@inheritDoc} + */ + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.symbol1.setPosition(iterator.next()); this.symbol2.setPosition(iterator.next()); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { Position position1 = this.symbol1.getPosition(); Position position2 = this.symbol2.getPosition(); // This graphic requires exactly two positions. If we don't have two positions // for some reason return an empty list. - if (position1 != null && position2 != null) + if (position1 != null && position2 != null) { return Arrays.asList(position1, position2); - else + } else { return Collections.emptyList(); + } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setStatus(String value) - { + public void setStatus(String value) { super.setStatus(value); this.symbol1.setStatus(value); this.symbol2.setStatus(value); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.symbol1.getPosition(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setShowTextModifiers(boolean show) - { + public void setShowTextModifiers(boolean show) { super.setShowTextModifiers(show); this.symbol1.setShowTextModifiers(show); this.symbol2.setShowTextModifiers(show); } @Override - protected void computeGeometry(DrawContext dc) - { + protected void computeGeometry(DrawContext dc) { super.computeGeometry(dc); Position position1 = this.symbol1.getPosition(); Position position2 = this.symbol2.getPosition(); - if (position1 == null || position2 == null) + if (position1 == null || position2 == null) { return; + } // Project the first control point onto the screen Vec4 placePoint1 = dc.computeTerrainPoint(position1.getLatitude(), position1.getLongitude(), 0); @@ -269,52 +272,47 @@ protected void computeGeometry(DrawContext dc) boolean orientationNormal = (screenPoint1.x < screenPoint2.x); // Set text alignment on the end points so that the text will always point away from the line. - if (orientationNormal) - { + if (orientationNormal) { this.symbol1.setTextAlign(AVKey.RIGHT); this.symbol2.setTextAlign(AVKey.LEFT); - } - else - { + } else { this.symbol1.setTextAlign(AVKey.LEFT); this.symbol2.setTextAlign(AVKey.RIGHT); } } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { this.symbol1.render(dc); this.symbol2.render(dc); } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { this.symbol1.setDelegateOwner(owner); this.symbol2.setDelegateOwner(owner); } - /** Determine active attributes for this frame. */ - protected void determineActiveAttributes() - { - if (this.isHighlighted()) - { + /** + * Determine active attributes for this frame. + */ + protected void determineActiveAttributes() { + if (this.isHighlighted()) { TacticalGraphicAttributes highlightAttributes = this.getHighlightAttributes(); // If the application specified overrides to the highlight attributes, then apply the overrides - if (highlightAttributes != null) - { + if (highlightAttributes != null) { // Apply overrides specified by application this.applyAttributesToSymbol(highlightAttributes, this.activeSymbolAttributes); } - } - else - { + } else { // Apply overrides specified by application TacticalGraphicAttributes normalAttributes = this.getAttributes(); - if (normalAttributes != null) - { + if (normalAttributes != null) { this.applyAttributesToSymbol(normalAttributes, this.activeSymbolAttributes); } } @@ -324,29 +322,25 @@ protected void determineActiveAttributes() * Apply graphic attributes to the symbol. * * @param graphicAttributes Tactical graphic attributes to apply to the tactical symbol. - * @param symbolAttributes Symbol attributes to be modified. + * @param symbolAttributes Symbol attributes to be modified. */ protected void applyAttributesToSymbol(TacticalGraphicAttributes graphicAttributes, - TacticalSymbolAttributes symbolAttributes) - { + TacticalSymbolAttributes symbolAttributes) { // Line and area graphics distinguish between interior and outline opacity. Tactical symbols only support one // opacity, so use the interior opacity. Double value = graphicAttributes.getInteriorOpacity(); - if (value != null) - { + if (value != null) { symbolAttributes.setOpacity(value); } Font font = graphicAttributes.getTextModifierFont(); - if (font != null) - { + if (font != null) { symbolAttributes.setTextModifierFont(font); } Material material = graphicAttributes.getTextModifierMaterial(); - if (material != null) - { + if (material != null) { symbolAttributes.setTextModifierMaterial(material); } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/ForwardLineOfOwnTroops.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/ForwardLineOfOwnTroops.java index cc60aae893..3fbbf2973d 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/ForwardLineOfOwnTroops.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/ForwardLineOfOwnTroops.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -21,14 +20,20 @@ * @author pabercrombie * @version $Id: ForwardLineOfOwnTroops.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class ForwardLineOfOwnTroops extends PhaseLine -{ - /** Default number of wave lengths for a simple shape. This number is used to compute a default wave length. */ +public class ForwardLineOfOwnTroops extends PhaseLine { + + /** + * Default number of wave lengths for a simple shape. This number is used to compute a default wave length. + */ public static final int DEFAULT_NUM_WAVES = 20; - /** Default number of intervals used to draw the arcs. */ + /** + * Default number of intervals used to draw the arcs. + */ public final static int DEFAULT_NUM_INTERVALS = 32; - /** Original positions specified by the application. */ + /** + * Original positions specified by the application. + */ protected Iterable positions; /** * Positions computed from the original positions. This list includes the positions necessary to draw the triangle @@ -36,9 +41,13 @@ public class ForwardLineOfOwnTroops extends PhaseLine */ protected List computedPositions; - /** Indicates wave length (in meters) of the semicircle wave along the graphic boundary. */ + /** + * Indicates wave length (in meters) of the semicircle wave along the graphic boundary. + */ protected double waveLength; - /** Number of intervals used to draw the arcs along the line. */ + /** + * Number of intervals used to draw the arcs along the line. + */ protected int intervals = DEFAULT_NUM_INTERVALS; /** @@ -46,8 +55,7 @@ public class ForwardLineOfOwnTroops extends PhaseLine * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_GNL_LNE_FLOT); } @@ -56,23 +64,24 @@ public static List getSupportedGraphics() * * @param sidc MIL-STD-2525C identifier code. */ - public ForwardLineOfOwnTroops(String sidc) - { + public ForwardLineOfOwnTroops(String sidc) { super(sidc); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setPositions(Iterable positions) - { + public void setPositions(Iterable positions) { this.positions = positions; this.computedPositions = null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Iterable getPositions() - { + public Iterable getPositions() { return this.positions; } @@ -88,8 +97,7 @@ public Iterable getPositions() * * @return The wave length, in meters. */ - public double getWaveLength() - { + public double getWaveLength() { return this.waveLength; } @@ -99,8 +107,7 @@ public double getWaveLength() * * @param waveLength The wavelength, in meters. */ - public void setWaveLength(int waveLength) - { + public void setWaveLength(int waveLength) { this.waveLength = waveLength; this.onShapeChanged(); } @@ -110,8 +117,7 @@ public void setWaveLength(int waveLength) * * @return Intervals used to draw arc. */ - public int getIntervals() - { + public int getIntervals() { return this.intervals; } @@ -121,10 +127,8 @@ public int getIntervals() * * @param intervals Number of intervals for drawing the arc. */ - public void setIntervals(int intervals) - { - if (intervals < 1) - { + public void setIntervals(int intervals) { + if (intervals < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -134,12 +138,12 @@ public void setIntervals(int intervals) this.onShapeChanged(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void moveTo(Position position) - { - if (position == null) - { + public void moveTo(Position position) { + if (position == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -149,8 +153,9 @@ public void moveTo(Position position) // The reference position is null if this shape has no positions. In this case moving the shape to a new // reference position is meaningless. Therefore we fail softly by exiting and doing nothing. - if (oldPosition == null) + if (oldPosition == null) { return; + } this.positions = Position.computeShiftedPositions(oldPosition, position, this.getPositions()); @@ -159,36 +164,35 @@ public void moveTo(Position position) this.path.moveTo(position); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void computeGeometry(DrawContext dc) - { - if (this.computedPositions == null && this.positions != null) - { + protected void computeGeometry(DrawContext dc) { + if (this.computedPositions == null && this.positions != null) { this.generateIntermediatePositions(dc, this.positions); this.path.setPositions(this.computedPositions); } super.computeGeometry(dc); } - protected void onShapeChanged() - { + protected void onShapeChanged() { this.computedPositions = null; // Need to recompute paths } /** * Generate the positions required to draw the polygon with a triangle wave boundary. * - * @param dc Current draw context. + * @param dc Current draw context. * @param positions Positions that define the polygon boundary. */ - protected void generateIntermediatePositions(DrawContext dc, Iterable positions) - { + protected void generateIntermediatePositions(DrawContext dc, Iterable positions) { Globe globe = dc.getGlobe(); double waveLength = this.getWaveLength(); - if (waveLength == 0) + if (waveLength == 0) { waveLength = this.computeDefaultWavelength(positions, globe); + } double radius = (waveLength / 2.0) / globe.getRadius(); PositionIterator iterator = new PositionIterator(positions, waveLength, globe); @@ -196,27 +200,26 @@ protected void generateIntermediatePositions(DrawContext dc, Iterable generateWavePositions(Iterator iterator, double radius, - boolean reverse) - { + boolean reverse) { List wavePositions = new ArrayList(); int intervals = this.getIntervals(); int sign = reverse ? -1 : 1; Position posB = iterator.next(); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Position posA = iterator.next(); if (posA == null) // Iterator returns null if there is not enough room for a full wave. + { continue; + } LatLon midPoint = LatLon.interpolateGreatCircle(0.5, posA, posB); Angle azimuth = LatLon.greatCircleAzimuth(posA, posB); // Generate positions for a semicircle centered on the midpoint. double delta = Angle.POS180.radians / intervals; - for (int i = 0; i < intervals; i++) - { + for (int i = 0; i < intervals; i++) { LatLon ll = LatLon.greatCircleEndPosition(midPoint, azimuth.radians + delta * i * sign, radius); wavePositions.add(new Position(ll, 0)); } @@ -226,24 +229,20 @@ protected List generateWavePositions(Iterator iter return wavePositions; } - protected double computeDefaultWavelength(Iterable positions, Globe globe) - { + protected double computeDefaultWavelength(Iterable positions, Globe globe) { Sector sector = Sector.boundingSector(positions); double diagonal = Math.hypot(sector.getDeltaLatRadians(), sector.getDeltaLonRadians()); return (diagonal * globe.getRadius()) / DEFAULT_NUM_WAVES; } - protected Angle computeGreatCirclePathLength(Iterable positions) - { + protected Angle computeGreatCirclePathLength(Iterable positions) { double length = 0; // Compute the number of vertices and the length of the path. Position prev = null; - for (Position pos : positions) - { - if (prev != null) - { + for (Position pos : positions) { + if (prev != null) { Angle dist = LatLon.greatCircleDistance(pos, prev); length += dist.radians; } @@ -255,11 +254,9 @@ protected Angle computeGreatCirclePathLength(Iterable positi } @Override - protected String getGraphicLabel() - { + protected String getGraphicLabel() { StringBuilder sb = new StringBuilder(); - if (this.mustShowHostileIndicator()) - { + if (this.mustShowHostileIndicator()) { sb.append(SymbologyConstants.HOSTILE_ENEMY); sb.append("\n"); } @@ -267,47 +264,53 @@ protected String getGraphicLabel() return sb.toString(); } - /** Iterator to generate equally spaced positions along a control line. */ - protected static class PositionIterator implements Iterator - { - /** Control positions. */ + /** + * Iterator to generate equally spaced positions along a control line. + */ + protected static class PositionIterator implements Iterator { + + /** + * Control positions. + */ protected Iterator positions; - /** Wavelength, as a geographic angle. */ + /** + * Wavelength, as a geographic angle. + */ protected Angle interval; protected double tolerance = 0.25; - /** Current position. */ + /** + * Current position. + */ protected Position thisPosition; - /** Position of the next control point. */ + /** + * Position of the next control point. + */ protected Position nextControlPosition; /** * Create a new iterator to compute the positions of a triangle wave. * * @param positions Control positions for the triangle wave line. - * @param interval Generate positions along the control line at this interval. - * @param globe Globe used to compute geographic positions. + * @param interval Generate positions along the control line at this interval. + * @param globe Globe used to compute geographic positions. */ - protected PositionIterator(Iterable positions, double interval, Globe globe) - { - if (positions == null) - { + protected PositionIterator(Iterable positions, double interval, Globe globe) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (interval <= 0) - { + if (interval <= 0) { String message = Logging.getMessage("generic.LengthIsInvalid"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -319,18 +322,19 @@ protected PositionIterator(Iterable positions, double interv this.nextControlPosition = this.positions.next(); } - /** {@inheritDoc} */ - public boolean hasNext() - { + /** + * {@inheritDoc} + */ + public boolean hasNext() { return this.nextControlPosition != null; } - /** {@inheritDoc} */ - public Position next() - { + /** + * {@inheritDoc} + */ + public Position next() { // thisPosition is null the first time that next() is called. - if (this.thisPosition == null) - { + if (this.thisPosition == null) { this.thisPosition = this.nextControlPosition; return this.thisPosition; } @@ -339,22 +343,19 @@ public Position next() double thisStep = this.interval.degrees; double diff = distToNext.degrees - thisStep; - while (diff < 0) - { - if (this.positions.hasNext()) - { + while (diff < 0) { + if (this.positions.hasNext()) { this.thisPosition = this.nextControlPosition; this.nextControlPosition = this.positions.next(); - } - else - { + } else { Position next = this.nextControlPosition; this.nextControlPosition = null; - if (Math.abs(diff) < this.interval.degrees * this.tolerance) + if (Math.abs(diff) < this.interval.degrees * this.tolerance) { return next; - else + } else { return null; + } } // The sample distance wraps around a corner. Adjust step size. @@ -371,9 +372,10 @@ public Position next() return this.thisPosition; } - /** Not supported. */ - public void remove() - { + /** + * Not supported. + */ + public void remove() { throw new UnsupportedOperationException(); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/HoldingLine.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/HoldingLine.java index 12a7872509..9c66966f8b 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/HoldingLine.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/HoldingLine.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -31,14 +30,20 @@ * @author pabercrombie * @version $Id: HoldingLine.java 555 2012-04-25 18:59:29Z pabercrombie $ */ -public class HoldingLine extends AbstractMilStd2525TacticalGraphic -{ - /** Default number of intervals used to draw the arc. */ +public class HoldingLine extends AbstractMilStd2525TacticalGraphic { + + /** + * Default number of intervals used to draw the arc. + */ public final static int DEFAULT_NUM_INTERVALS = 32; - /** Scale factor that determines the curvature of the corners of the arc. */ + /** + * Scale factor that determines the curvature of the corners of the arc. + */ public final static double DEFAULT_CURVATURE = 0.3; - /** Path used to render the line. */ + /** + * Path used to render the line. + */ protected Path path; /** @@ -46,14 +51,22 @@ public class HoldingLine extends AbstractMilStd2525TacticalGraphic * produced square corners. */ protected double curvature = DEFAULT_CURVATURE; - /** Number of intervals used to draw the arc. */ + /** + * Number of intervals used to draw the arc. + */ protected int intervals = DEFAULT_NUM_INTERVALS; - /** First control point, defines the start of the line. */ + /** + * First control point, defines the start of the line. + */ protected Position position1; - /** Second control point, defines the end of the line. */ + /** + * Second control point, defines the end of the line. + */ protected Position position2; - /** Third control point, defines the top of the arc. */ + /** + * Third control point, defines the top of the arc. + */ protected Position position3; /** @@ -61,11 +74,10 @@ public class HoldingLine extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_SPL_LNE_HGL, - TacGrpSidc.C2GM_SPL_LNE_BRGH); + TacGrpSidc.C2GM_SPL_LNE_HGL, + TacGrpSidc.C2GM_SPL_LNE_BRGH); } /** @@ -73,8 +85,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public HoldingLine(String sidc) - { + public HoldingLine(String sidc) { super(sidc); } @@ -83,25 +94,20 @@ public HoldingLine(String sidc) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Ensure that the position list provides at least 3 control points. - try - { + try { Iterator iterator = positions.iterator(); this.position1 = iterator.next(); this.position2 = iterator.next(); this.position3 = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,15 +116,17 @@ public void setPositions(Iterable positions) this.path = null; // Need to regenerate } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.position1, this.position2, this.position3); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.position1; } @@ -129,8 +137,7 @@ public Position getReferencePosition() * * @see #setCurvature(double) */ - public double getCurvature() - { + public double getCurvature() { return this.curvature; } @@ -140,10 +147,8 @@ public double getCurvature() * * @param curvature Factor that determines curvature of the arc. */ - public void setCurvature(double curvature) - { - if (curvature < 0.0 || curvature > 1.0) - { + public void setCurvature(double curvature) { + if (curvature < 0.0 || curvature > 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", curvature); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -157,8 +162,7 @@ public void setCurvature(double curvature) * * @return Intervals used to draw arc. */ - public int getIntervals() - { + public int getIntervals() { return this.intervals; } @@ -168,10 +172,8 @@ public int getIntervals() * * @param intervals Number of intervals for drawing the arc. */ - public void setIntervals(int intervals) - { - if (intervals < 1) - { + public void setIntervals(int intervals) { + if (intervals < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -181,27 +183,28 @@ public void setIntervals(int intervals) this.onShapeChanged(); } - protected void onShapeChanged() - { + protected void onShapeChanged() { this.path = null; // Need to recompute path } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - if (this.path == null) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + if (this.path == null) { this.createShape(dc); } this.path.render(dc); } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.path != null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.path != null) { this.path.setDelegateOwner(owner); + } } /** @@ -209,8 +212,7 @@ protected void applyDelegateOwner(Object owner) * * @param dc Current draw context. */ - protected void createShape(DrawContext dc) - { + protected void createShape(DrawContext dc) { Globe globe = dc.getGlobe(); // The graphic looks like this: @@ -222,7 +224,6 @@ protected void createShape(DrawContext dc) // | // | // Pt. 2 _________/ Corner 2 - Vec4 pt1 = globe.computePointFromLocation(this.position1); Vec4 pt2 = globe.computePointFromLocation(this.position2); Vec4 pt3 = globe.computePointFromLocation(this.position3); @@ -259,17 +260,16 @@ protected void createShape(DrawContext dc) /** * Compute positions to draw a rounded corner between three points. * - * @param globe Current globe. + * @param globe Current globe. * @param positions Positions will be added to this list. - * @param ptLeg1 Point at the end of the one leg. - * @param ptVertex Point at the vertex of the corner. - * @param ptLeg2 Point at the end of the other let. - * @param distance Distance from the vertex at which the arc should begin and end. + * @param ptLeg1 Point at the end of the one leg. + * @param ptVertex Point at the vertex of the corner. + * @param ptLeg2 Point at the end of the other let. + * @param distance Distance from the vertex at which the arc should begin and end. * @param intervals Number of intervals to use to generate the arc. */ protected void computeRoundCorner(Globe globe, List positions, Vec4 ptLeg1, Vec4 ptVertex, Vec4 ptLeg2, - double distance, int intervals) - { + double distance, int intervals) { Vec4 vertexTo1 = ptLeg1.subtract3(ptVertex); Vec4 vertexTo2 = ptLeg2.subtract3(ptVertex); @@ -286,10 +286,10 @@ protected void computeRoundCorner(Globe globe, List positions, Vec4 pt // Theta ->/____|________ Leg 2 // Vertex d Pt. A // - Angle theta = vertexTo1.angleBetween3(vertexTo2); - if (Angle.ZERO.equals(theta)) + if (Angle.ZERO.equals(theta)) { return; + } double radius = distance * theta.tanHalfAngle(); @@ -305,8 +305,7 @@ protected void computeRoundCorner(Globe globe, List positions, Vec4 pt // Determine which direction the offset points by computing the scalar triple product of the perpendicular // vector and the vector from the vertex along leg 2. Reverse the sign of offset if necessary. double tripleProduct = perpendicular.dot3(vertexTo2); - if (tripleProduct < 0) - { + if (tripleProduct < 0) { offset = offset.multiply3(-1); } @@ -319,25 +318,24 @@ protected void computeRoundCorner(Globe globe, List positions, Vec4 pt // Compute the arc from A to B this.computeArc(globe, positions, arcCenter, - LatLon.greatCircleAzimuth(arcCenter, posA), - LatLon.greatCircleAzimuth(arcCenter, posB), - radius, intervals); + LatLon.greatCircleAzimuth(arcCenter, posA), + LatLon.greatCircleAzimuth(arcCenter, posB), + radius, intervals); } /** * Compute the positions required to draw an arc. * - * @param globe Current globe. - * @param positions Add arc positions to this list. - * @param center Center point of the arc. + * @param globe Current globe. + * @param positions Add arc positions to this list. + * @param center Center point of the arc. * @param startAzimuth Starting azimuth. - * @param endAzimuth Ending azimuth. - * @param radius Radius of the arc, in meters. - * @param intervals Number of intervals to generate. + * @param endAzimuth Ending azimuth. + * @param radius Radius of the arc, in meters. + * @param intervals Number of intervals to generate. */ protected void computeArc(Globe globe, List positions, Position center, Angle startAzimuth, - Angle endAzimuth, double radius, int intervals) - { + Angle endAzimuth, double radius, int intervals) { // Compute the sweep between the start and end positions, and normalize to the range [-180, 180]. Angle sweep = endAzimuth.subtract(startAzimuth).normalizedLongitude(); @@ -346,8 +344,7 @@ protected void computeArc(Globe globe, List positions, Position center double radiusRadians = radius / globeRadius; // Compute the arc positions - for (int i = 0; i < intervals; i++) - { + for (int i = 0; i < intervals; i++) { double angle = i * da.radians + startAzimuth.radians; LatLon ll = LatLon.greatCircleEndPosition(center, angle, radiusRadians); @@ -355,30 +352,32 @@ protected void computeArc(Globe globe, List positions, Position center } } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { String text = this.getGraphicLabel(); this.addLabel(text); // Start label this.addLabel(text); // End label } - protected String getGraphicLabel() - { + protected String getGraphicLabel() { StringBuilder sb = new StringBuilder(); sb.append("PL "); String text = this.getText(); - if (!WWUtil.isEmpty(text)) + if (!WWUtil.isEmpty(text)) { sb.append(text); + } - if (TacGrpSidc.C2GM_SPL_LNE_HGL.equalsIgnoreCase(this.maskedSymbolCode)) + if (TacGrpSidc.C2GM_SPL_LNE_HGL.equalsIgnoreCase(this.maskedSymbolCode)) { sb.append("\n(HOLDING LINE)"); - else if (TacGrpSidc.C2GM_SPL_LNE_BRGH.equalsIgnoreCase(this.maskedSymbolCode)) + } else if (TacGrpSidc.C2GM_SPL_LNE_BRGH.equalsIgnoreCase(this.maskedSymbolCode)) { sb.append("\n(BRIDGEHEAD LINE)"); + } return sb.toString(); } @@ -389,10 +388,10 @@ else if (TacGrpSidc.C2GM_SPL_LNE_BRGH.equalsIgnoreCase(this.maskedSymbolCode)) * @param dc Current draw context. */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (WWUtil.isEmpty(labels)) + protected void determineLabelPositions(DrawContext dc) { + if (WWUtil.isEmpty(labels)) { return; + } TacticalGraphicLabel startLabel = this.labels.get(0); TacticalGraphicLabel endLabel = this.labels.get(1); @@ -406,8 +405,7 @@ protected void determineLabelPositions(DrawContext dc) * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath() - { + protected Path createPath() { Path path = new Path(); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/InfiltrationLane.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/InfiltrationLane.java index 88d8fb65e5..3072882d6a 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/InfiltrationLane.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/InfiltrationLane.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -24,16 +23,24 @@ * @author pabercrombie * @version $Id: InfiltrationLane.java 555 2012-04-25 18:59:29Z pabercrombie $ */ -public class InfiltrationLane extends AbstractMilStd2525TacticalGraphic -{ - /** Default number of intervals used to draw the curve. */ +public class InfiltrationLane extends AbstractMilStd2525TacticalGraphic { + + /** + * Default number of intervals used to draw the curve. + */ public final static int DEFAULT_NUM_INTERVALS = 32; - /** Default factor that determines the curvature of the line. */ + /** + * Default factor that determines the curvature of the line. + */ public final static double DEFAULT_CURVATURE = 0.3; - /** Number of control points that define the curve. */ + /** + * Number of control points that define the curve. + */ protected final static int NUM_CONTROL_POINTS = 9; - /** Number of intervals used to draw the curve. */ + /** + * Number of intervals used to draw the curve. + */ protected int intervals = DEFAULT_NUM_INTERVALS; /** * Factor that controls the curve of the line. Valid values are 0 to 1. Larger values result in a more pronounced @@ -41,14 +48,22 @@ public class InfiltrationLane extends AbstractMilStd2525TacticalGraphic */ protected double curvature = DEFAULT_CURVATURE; - /** First control point. */ + /** + * First control point. + */ protected Position position1; - /** Second control point. */ + /** + * Second control point. + */ protected Position position2; - /** Third control point. */ + /** + * Third control point. + */ protected Position position3; - /** Path used to render the line. */ + /** + * Path used to render the line. + */ protected Path[] paths; /** @@ -56,8 +71,7 @@ public class InfiltrationLane extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_LNE_INFNLE); } @@ -66,8 +80,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public InfiltrationLane(String sidc) - { + public InfiltrationLane(String sidc) { super(sidc); } @@ -77,8 +90,7 @@ public InfiltrationLane(String sidc) * * @return Intervals used to draw arc. */ - public int getIntervals() - { + public int getIntervals() { return this.intervals; } @@ -88,10 +100,8 @@ public int getIntervals() * * @param intervals Number of intervals for drawing the curve. */ - public void setIntervals(int intervals) - { - if (intervals < 1) - { + public void setIntervals(int intervals) { + if (intervals < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", intervals); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -107,8 +117,7 @@ public void setIntervals(int intervals) * * @return The factor that determines the curvature of the line. */ - public double getCurvature() - { + public double getCurvature() { return this.curvature; } @@ -118,10 +127,8 @@ public double getCurvature() * * @param factor The factor that determines the curvature of the line. */ - public void setCurvature(double factor) - { - if (factor < 0.0 || factor > 1.0) - { + public void setCurvature(double factor) { + if (factor < 0.0 || factor > 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -134,24 +141,19 @@ public void setCurvature(double factor) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.position1 = iterator.next(); this.position2 = iterator.next(); this.position3 = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -160,15 +162,17 @@ public void setPositions(Iterable positions) this.paths = null; // Need to recompute path for the new control points } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.position1, this.position2, this.position3); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.position1; } @@ -177,38 +181,36 @@ public Position getReferencePosition() * * @return the number of control points. */ - protected int getNumControlPoints() - { + protected int getNumControlPoints() { return NUM_CONTROL_POINTS; } - protected void onShapeChanged() - { + protected void onShapeChanged() { this.paths = null; // Need to recompute paths } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - if (this.paths == null) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + if (this.paths == null) { this.createShapes(dc); } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths == null) { return; + } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.setDelegateOwner(owner); } } @@ -218,8 +220,7 @@ protected void applyDelegateOwner(Object owner) * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { this.paths = new Path[2]; Globe globe = dc.getGlobe(); @@ -230,7 +231,7 @@ protected void createShapes(DrawContext dc) // Compute control points for the Bezier curve. Vec4[] controlPoints = this.computeBezierControlPoints(dc, pt1, pt2, this.getNumControlPoints(), - this.getCurvature()); + this.getCurvature()); int intervals = this.getIntervals(); List curvePositionsLeft = new ArrayList(intervals); @@ -249,8 +250,7 @@ protected void createShapes(DrawContext dc) // Invoke the Bezier curve function to compute points along the curve. double delta = 1.0 / intervals; - for (int i = 0; i <= intervals; i++) - { + for (int i = 0; i <= intervals; i++) { double t = i * delta; Vec4 p = TacticalGraphicUtil.bezierCurve(controlPoints, t, coefficients); @@ -269,18 +269,17 @@ protected void createShapes(DrawContext dc) /** * Determine the point along a Bezier curve that is closest to a line segment. * - * @param p0 First line segment point. - * @param p1 Second line segment point. + * @param p0 First line segment point. + * @param p1 Second line segment point. * @param controlPoints Control points for Bezier curve. - * @param coefficients Binomial coefficients for computing curve. - * @param tolerance Numerical tolerance. Smaller values will yield a more accurate answer, but will take more - * iterations to compute. + * @param coefficients Binomial coefficients for computing curve. + * @param tolerance Numerical tolerance. Smaller values will yield a more accurate answer, but will take more + * iterations to compute. * * @return the point on the curve that is closest to the specified line segment. */ protected Vec4 bezierNearestPointToSegment(Vec4 p0, Vec4 p1, Vec4[] controlPoints, int[] coefficients, - double tolerance) - { + double tolerance) { double dist1; double dist2; @@ -296,8 +295,7 @@ protected Vec4 bezierNearestPointToSegment(Vec4 p0, Vec4 p1, Vec4[] controlPoint dist1 = nearest.distanceTo3(p); double delta; - do - { + do { p = TacticalGraphicUtil.bezierCurve(controlPoints, t2, coefficients); nearest = Line.nearestPointOnSegment(p0, p1, p); dist2 = nearest.distanceTo3(p); @@ -305,14 +303,12 @@ protected Vec4 bezierNearestPointToSegment(Vec4 p0, Vec4 p1, Vec4[] controlPoint double avg = (t1 + t2) / 2; delta = Math.abs(dist1 - dist2); - if (dist2 < dist1) - { + if (dist2 < dist1) { t1 = t2; dist1 = dist2; } t2 = avg; - } - while (delta > tolerance); + } while (delta > tolerance); return p; } @@ -321,20 +317,19 @@ protected Vec4 bezierNearestPointToSegment(Vec4 p0, Vec4 p1, Vec4[] controlPoint * Compute the position of control points that will generate a Bezier curve that looks like the Infiltration Lane * graphic in MIL-STD-2525C (pg. 526). * - * @param dc Current draw context. - * @param start Beginning of the infiltration lane control line. - * @param end End of the infiltration lane control line. + * @param dc Current draw context. + * @param start Beginning of the infiltration lane control line. + * @param end End of the infiltration lane control line. * @param numControlPoints Number of control points to generate. More control points result in more "wiggles" in the - * line. - * @param curvature Factor that controls the curvature of the line. Valid values are between zero and one. A - * higher value results in a more pronounced curve. + * line. + * @param curvature Factor that controls the curvature of the line. Valid values are between zero and one. A higher + * value results in a more pronounced curve. * * @return Control points for a Bezier curve. The first control point is equal to {@code start}, and the last point - * is equal to {@code end}. + * is equal to {@code end}. */ protected Vec4[] computeBezierControlPoints(DrawContext dc, Vec4 start, Vec4 end, int numControlPoints, - double curvature) - { + double curvature) { Globe globe = dc.getGlobe(); // Find length and direction of the control line. @@ -344,7 +339,6 @@ protected Vec4[] computeBezierControlPoints(DrawContext dc, Vec4 start, Vec4 end // Generate control points to the left and right of the control line to generate a curve that wiggles back and // forth. - Vec4 normal = globe.computeSurfaceNormalAtPoint(start); Vec4 perpendicular = dir.cross3(normal).normalize3().multiply3(length * curvature); @@ -354,28 +348,29 @@ protected Vec4[] computeBezierControlPoints(DrawContext dc, Vec4 start, Vec4 end controlPoints[numControlPoints - 1] = end; // Last control point is end position // Generate a point to the left of the line, then on the line, then the right of the line, then on the line, etc. - int[] signs = new int[] {1, 0, -1, 0}; + int[] signs = new int[]{1, 0, -1, 0}; // Choose regularly spaced points along the control line. At each point select a point to the left of the line, // on the line, or to the right of the line. double delta = length / numControlPoints; - for (int i = 1; i < numControlPoints - 1; i++) - { + for (int i = 1; i < numControlPoints - 1; i++) { int sign = signs[i % signs.length]; controlPoints[i] = start.add3(dir.multiply3(i * delta)) - .add3(perpendicular.multiply3(sign)); + .add3(perpendicular.multiply3(sign)); } return controlPoints; } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { String text = this.getText(); - if (!WWUtil.isEmpty(text)) + if (!WWUtil.isEmpty(text)) { this.addLabel(text); + } } /** @@ -384,10 +379,10 @@ protected void createLabels() * @param dc Current draw context. */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (WWUtil.isEmpty(this.labels)) + protected void determineLabelPositions(DrawContext dc) { + if (WWUtil.isEmpty(this.labels)) { return; + } LatLon ll = LatLon.interpolate(0.5, this.position1, this.position2); this.labels.get(0).setPosition(new Position(ll, 0)); @@ -401,8 +396,7 @@ protected void determineLabelPositions(DrawContext dc) * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(List positions) - { + protected Path createPath(List positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/LineOfContact.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/LineOfContact.java index ba2b756edf..294e2871ad 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/LineOfContact.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/LineOfContact.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -21,9 +20,11 @@ * @author pabercrombie * @version $Id: LineOfContact.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class LineOfContact extends ForwardLineOfOwnTroops -{ - /** Line of Contact is drawn with two paths. The super class manages the first path; this is the second. */ +public class LineOfContact extends ForwardLineOfOwnTroops { + + /** + * Line of Contact is drawn with two paths. The super class manages the first path; this is the second. + */ protected Path path2; /** @@ -31,8 +32,7 @@ public class LineOfContact extends ForwardLineOfOwnTroops * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_GNL_LNE_LOC); } @@ -41,23 +41,24 @@ public static List getSupportedGraphics() * * @param sidc MIL-STD-2525C identifier code. */ - public LineOfContact(String sidc) - { + public LineOfContact(String sidc) { super(sidc); this.path2 = this.createPath(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void moveTo(Position position) - { + public void moveTo(Position position) { Position delta; Position ref1 = this.path.getReferencePosition(); Position ref2 = this.path2.getReferencePosition(); - if (ref1 != null && ref2 != null) + if (ref1 != null && ref2 != null) { delta = ref2.subtract(ref1); - else + } else { delta = Position.ZERO; + } // Move the first path super.moveTo(position); @@ -67,18 +68,15 @@ public void moveTo(Position position) } @Override - protected void doRenderGraphic(DrawContext dc) - { + protected void doRenderGraphic(DrawContext dc) { super.doRenderGraphic(dc); this.path2.render(dc); } @Override - protected String getGraphicLabel() - { + protected String getGraphicLabel() { StringBuilder sb = new StringBuilder(); - if (this.mustShowHostileIndicator()) - { + if (this.mustShowHostileIndicator()) { sb.append(SymbologyConstants.HOSTILE_ENEMY); sb.append("\n"); } @@ -88,18 +86,16 @@ protected String getGraphicLabel() /** * Generate the positions required to draw the line. * - * @param dc Current draw context. + * @param dc Current draw context. * @param positions Positions that define the polygon boundary. */ @Override - protected void generateIntermediatePositions(DrawContext dc, Iterable positions) - { + protected void generateIntermediatePositions(DrawContext dc, Iterable positions) { Globe globe = dc.getGlobe(); boolean useDefaultWaveLength = false; double waveLength = this.getWaveLength(); - if (waveLength == 0) - { + if (waveLength == 0) { waveLength = this.computeDefaultWavelength(positions, globe); useDefaultWaveLength = true; } @@ -109,8 +105,9 @@ protected void generateIntermediatePositions(DrawContext dc, Iterable rightPositions = new ArrayList(); this.generateParallelLines(positions.iterator(), leftPositions, rightPositions, waveLength / 2.0, globe); - if (useDefaultWaveLength) + if (useDefaultWaveLength) { waveLength = this.computeDefaultWavelength(leftPositions, globe); + } double radius = (waveLength) / 2.0; // Generate wavy line to the left of the control line. @@ -118,8 +115,9 @@ protected void generateIntermediatePositions(DrawContext dc, Iterable iterator, List leftPositions, - List rightPositions, double halfWidth, Globe globe) - { + List rightPositions, double halfWidth, Globe globe) { // Starting at the start of the line, take points three at a time. B is the current control point, A is the next // point in the line, and C is the previous point. We need to a find a vector that bisects angle ABC. // B @@ -158,8 +155,7 @@ public void generateParallelLines(Iterator iterator, List iterator, List leftPositions, - List rightPositions, double halfWidth, Globe globe) - { - if ((point == null) || (prev == null && next == null)) - { + List rightPositions, double halfWidth, Globe globe) { + if ((point == null) || (prev == null && next == null)) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (leftPositions == null || rightPositions == null) - { + if (leftPositions == null || rightPositions == null) { String message = Logging.getMessage("nullValue.PositionListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -218,8 +210,7 @@ protected void generateParallelPoints(Vec4 point, Vec4 prev, Vec4 next, List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.FSUPP_LNE_LNRTGT, - TacGrpSidc.FSUPP_LNE_LNRTGT_LSTGT, - TacGrpSidc.FSUPP_LNE_LNRTGT_FPF + TacGrpSidc.FSUPP_LNE_LNRTGT, + TacGrpSidc.FSUPP_LNE_LNRTGT_LSTGT, + TacGrpSidc.FSUPP_LNE_LNRTGT_FPF ); } @@ -79,8 +87,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public LinearTarget(String sidc) - { + public LinearTarget(String sidc) { super(sidc); } @@ -89,8 +96,7 @@ public LinearTarget(String sidc) * * @return The length of the vertical segments as a fraction of the horizontal segment. */ - public double getVerticalLength() - { + public double getVerticalLength() { return this.verticalLength; } @@ -98,12 +104,10 @@ public double getVerticalLength() * Specifies the length of the vertical segments in the graphic. * * @param length Length of the vertical segments as a fraction of the horizontal segment. If the vertical length is - * 0.25, then the vertical segments will be one quarter of the horizontal segment length. + * 0.25, then the vertical segments will be one quarter of the horizontal segment length. */ - public void setVerticalLength(double length) - { - if (length < 0) - { + public void setVerticalLength(double length) { + if (length < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -118,8 +122,7 @@ public void setVerticalLength(double length) * * @return The additional text. May be null. */ - public String getAdditionalText() - { + public String getAdditionalText() { return this.additionalText; } @@ -129,18 +132,15 @@ public String getAdditionalText() * * @param text The additional text. May be null. */ - public void setAdditionalText(String text) - { + public void setAdditionalText(String text) { this.additionalText = text; this.onModifierChanged(); } @Override - public Object getModifier(String key) - { + public Object getModifier(String key) { // If two values are set for the Unique Designation, return both in a list. - if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && this.additionalText != null) - { + if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && this.additionalText != null) { return Arrays.asList(this.getText(), this.getAdditionalText()); } @@ -148,24 +148,18 @@ public Object getModifier(String key) } @Override - public void setModifier(String key, Object value) - { - if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && value instanceof Iterable) - { + public void setModifier(String key, Object value) { + if (SymbologyConstants.UNIQUE_DESIGNATION.equals(key) && value instanceof Iterable) { Iterator iterator = ((Iterable) value).iterator(); - if (iterator.hasNext()) - { + if (iterator.hasNext()) { this.setText((String) iterator.next()); } // The Final Protective Fire graphic supports a second Unique Designation value - if (iterator.hasNext()) - { + if (iterator.hasNext()) { this.setAdditionalText((String) iterator.next()); } - } - else - { + } else { super.setModifier(key, value); } } @@ -175,23 +169,18 @@ public void setModifier(String key, Object value) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.startPosition = iterator.next(); this.endPosition = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -200,40 +189,42 @@ public void setPositions(Iterable positions) this.paths = null; // Need to recompute path for the new control points } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.startPosition, this.endPosition); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.startPosition; } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - if (this.paths == null) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + if (this.paths == null) { this.createShapes(dc); } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths == null) { return; + } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.setDelegateOwner(owner); } } @@ -243,8 +234,7 @@ protected void applyDelegateOwner(Object owner) * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { this.paths = new Path[3]; // The graphic looks like this: @@ -253,7 +243,6 @@ protected void createShapes(DrawContext dc) // Pt. 1 |__________________| Pt. 2 // | | // | | - // Create a path for the horizontal segment this.paths[0] = this.createPath(Arrays.asList(this.startPosition, this.endPosition)); @@ -281,16 +270,15 @@ protected void createShapes(DrawContext dc) /** * Compute positions for one of the vertical segments in the graphic. * - * @param globe Current globe. - * @param basePoint Point at which the vertical segment must meet the horizontal segment. - * @param segment Vector in the direction of the horizontal segment. + * @param globe Current globe. + * @param basePoint Point at which the vertical segment must meet the horizontal segment. + * @param segment Vector in the direction of the horizontal segment. * @param verticalLength Length of the vertical segment, in meters. * * @return Positions that make up the vertical segment. */ protected List computeVerticalSegmentPositions(Globe globe, Vec4 basePoint, Vec4 segment, - double verticalLength) - { + double verticalLength) { Vec4 normal = globe.computeSurfaceNormalAtPoint(basePoint); // Compute a vector perpendicular to the segment and the normal vector @@ -302,23 +290,22 @@ protected List computeVerticalSegmentPositions(Globe globe, Vec4 baseP Vec4 pB = basePoint.subtract3(perpendicular); return Arrays.asList( - globe.computePositionFromPoint(pA), - globe.computePositionFromPoint(pB)); + globe.computePositionFromPoint(pA), + globe.computePositionFromPoint(pB)); } - /** Create labels for the graphic. */ + /** + * Create labels for the graphic. + */ @Override - protected void createLabels() - { + protected void createLabels() { String text = this.getText(); - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { this.addLabel(text); } text = this.getBottomLabelText(); - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { TacticalGraphicLabel label = this.addLabel(text); label.setOffset(this.getBottomLabelOffset()); } @@ -329,19 +316,14 @@ protected void createLabels() * * @return Text for the bottom label. May return null if there is no bottom label. */ - protected String getBottomLabelText() - { + protected String getBottomLabelText() { String code = this.maskedSymbolCode; - if (TacGrpSidc.FSUPP_LNE_LNRTGT_LSTGT.equalsIgnoreCase(code)) - { + if (TacGrpSidc.FSUPP_LNE_LNRTGT_LSTGT.equalsIgnoreCase(code)) { return "SMOKE"; - } - else if (TacGrpSidc.FSUPP_LNE_LNRTGT_FPF.equalsIgnoreCase(code)) - { + } else if (TacGrpSidc.FSUPP_LNE_LNRTGT_FPF.equalsIgnoreCase(code)) { StringBuilder sb = new StringBuilder("FPF"); String additionalText = this.getAdditionalText(); - if (!WWUtil.isEmpty(additionalText)) - { + if (!WWUtil.isEmpty(additionalText)) { sb.append("\n").append(additionalText); } return sb.toString(); @@ -349,12 +331,14 @@ else if (TacGrpSidc.FSUPP_LNE_LNRTGT_FPF.equalsIgnoreCase(code)) return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (this.labels == null || this.labels.size() == 0) + protected void determineLabelPositions(DrawContext dc) { + if (this.labels == null || this.labels.size() == 0) { return; + } Globe globe = dc.getGlobe(); LatLon midpoint = LatLon.interpolateGreatCircle(0.5, this.startPosition, this.endPosition); @@ -378,28 +362,26 @@ protected void determineLabelPositions(DrawContext dc) // Set position of the main (top) label TacticalGraphicLabel topLabel = this.labels.get(0); - if (topLabel != null) - { + if (topLabel != null) { topLabel.setPosition(positions.get(0)); topLabel.setOrientationPosition(orientationPositions.get(0)); } // Set position of the bottom label. - if (this.labels.size() > 1) - { + if (this.labels.size() > 1) { TacticalGraphicLabel bottomLabel = this.labels.get(1); - if (bottomLabel != null) - { + if (bottomLabel != null) { bottomLabel.setPosition(positions.get(1)); bottomLabel.setOrientationPosition(orientationPositions.get(1)); } } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { return TOP_LABEL_OFFSET; } @@ -408,8 +390,7 @@ protected Offset getDefaultLabelOffset() * * @return Offset applied to the bottom label. */ - protected Offset getBottomLabelOffset() - { + protected Offset getBottomLabelOffset() { return BOTTOM_LABEL_OFFSET; } @@ -420,8 +401,7 @@ protected Offset getBottomLabelOffset() * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(List positions) - { + protected Path createPath(List positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); @@ -430,4 +410,4 @@ protected Path createPath(List positions) path.setAttributes(this.getActiveShapeAttributes()); return path; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/MainAttack.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/MainAttack.java index ebd12eaa56..6aca1edc69 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/MainAttack.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/MainAttack.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -18,31 +17,27 @@ * @author pabercrombie * @version $Id: MainAttack.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MainAttack extends AbstractAxisArrow -{ +public class MainAttack extends AbstractAxisArrow { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_LNE_AXSADV_GRD_MANATK); } - public MainAttack(String sidc) - { + public MainAttack(String sidc) { super(sidc, 2); } @Override protected double createArrowHeadPositions(List leftPositions, List rightPositions, - List arrowHeadPositions, Globe globe) - { + List arrowHeadPositions, Globe globe) { double halfWidth = super.createArrowHeadPositions(leftPositions, rightPositions, arrowHeadPositions, globe); - if (rightPositions.size() > 0 && leftPositions.size() > 0) - { + if (rightPositions.size() > 0 && leftPositions.size() > 0) { Position left = leftPositions.get(0); Position right = rightPositions.get(0); Position pos1 = this.positions.iterator().next(); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/MunitionFlightPath.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/MunitionFlightPath.java index 774c51f959..276b7372db 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/MunitionFlightPath.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/MunitionFlightPath.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.Position; @@ -18,15 +17,14 @@ * @author pabercrombie * @version $Id: MunitionFlightPath.java 545 2012-04-24 22:29:21Z pabercrombie $ */ -public class MunitionFlightPath extends FireSupportLine -{ +public class MunitionFlightPath extends FireSupportLine { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.FSUPP_LNE_C2LNE_MFP); } @@ -35,33 +33,34 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public MunitionFlightPath(String sidc) - { + public MunitionFlightPath(String sidc) { super(sidc); } - /** Create labels for the graphic. */ + /** + * Create labels for the graphic. + */ @Override - protected void createLabels() - { + protected void createLabels() { this.addLabel("MFP"); Offset bottomLabelOffset = this.getBottomLabelOffset(); String bottomText = this.getBottomLabelText(); - if (!WWUtil.isEmpty(bottomText)) - { + if (!WWUtil.isEmpty(bottomText)) { TacticalGraphicLabel label = this.addLabel(bottomText); label.setOffset(bottomLabelOffset); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (this.labels == null || this.labels.size() == 0) + protected void determineLabelPositions(DrawContext dc) { + if (this.labels == null || this.labels.size() == 0) { return; + } Object[] pathData = this.computePathLength(dc); double pathLength = (Double) pathData[2]; @@ -71,17 +70,17 @@ protected void determineLabelPositions(DrawContext dc) TacticalGraphicLabel label = this.labels.get(0); TacticalGraphicUtil.placeLabelsOnPath(dc, positions, label, null, pathLength * 0.5); - if (this.labels.size() > 1) - { + if (this.labels.size() > 1) { label = this.labels.get(1); TacticalGraphicUtil.placeLabelsOnPath(dc, positions, label, null, pathLength * 0.25); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { return TacticalGraphicLabel.DEFAULT_OFFSET; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PhaseLine.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PhaseLine.java index a00e86fb63..191fecb847 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PhaseLine.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PhaseLine.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -27,9 +26,11 @@ * @author pabercrombie * @version $Id: PhaseLine.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PhaseLine extends AbstractMilStd2525TacticalGraphic -{ - /** Factor applied to the stipple pattern used to draw the dashed line for a Probable Line of Deployment. */ +public class PhaseLine extends AbstractMilStd2525TacticalGraphic { + + /** + * Factor applied to the stipple pattern used to draw the dashed line for a Probable Line of Deployment. + */ protected static final int PLD_OUTLINE_STIPPLE_FACTOR = 12; /** @@ -37,22 +38,23 @@ public class PhaseLine extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_GNL_LNE_PHELNE, - TacGrpSidc.C2GM_GNL_LNE_LITLNE, - TacGrpSidc.C2GM_OFF_LNE_FCL, - TacGrpSidc.C2GM_OFF_LNE_LMTADV, - TacGrpSidc.C2GM_OFF_LNE_LD, - TacGrpSidc.C2GM_OFF_LNE_LDLC, - TacGrpSidc.C2GM_OFF_LNE_PLD, - TacGrpSidc.C2GM_SPL_LNE_REL, - TacGrpSidc.FSUPP_LNE_C2LNE_NFL + TacGrpSidc.C2GM_GNL_LNE_PHELNE, + TacGrpSidc.C2GM_GNL_LNE_LITLNE, + TacGrpSidc.C2GM_OFF_LNE_FCL, + TacGrpSidc.C2GM_OFF_LNE_LMTADV, + TacGrpSidc.C2GM_OFF_LNE_LD, + TacGrpSidc.C2GM_OFF_LNE_LDLC, + TacGrpSidc.C2GM_OFF_LNE_PLD, + TacGrpSidc.C2GM_SPL_LNE_REL, + TacGrpSidc.FSUPP_LNE_C2LNE_NFL ); } - /** Path used to render the line. */ + /** + * Path used to render the line. + */ protected Path path; /** @@ -60,31 +62,27 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public PhaseLine(String sidc) - { + public PhaseLine(String sidc) { super(sidc); this.path = this.createPath(); } - /** {@inheritDoc} */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + /** + * {@inheritDoc} + */ + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { // Ensure that at least two positions are provided. Iterator iterator = positions.iterator(); iterator.next(); iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -93,27 +91,31 @@ public void setPositions(Iterable positions) this.path.setPositions(positions); } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return this.path.getPositions(); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.path.getReferencePosition(); } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { this.path.render(dc); } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { this.path.setDelegateOwner(owner); } @@ -122,8 +124,7 @@ protected void applyDelegateOwner(Object owner) * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath() - { + protected Path createPath() { Path path = new Path(); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); @@ -133,33 +134,32 @@ protected Path createPath() return path; } - protected String getGraphicLabel() - { + protected String getGraphicLabel() { String code = this.maskedSymbolCode; String pattern = null; - if (TacGrpSidc.C2GM_GNL_LNE_PHELNE.equalsIgnoreCase(code)) + if (TacGrpSidc.C2GM_GNL_LNE_PHELNE.equalsIgnoreCase(code)) { pattern = "PL %s"; - else if (TacGrpSidc.C2GM_GNL_LNE_LITLNE.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_GNL_LNE_LITLNE.equalsIgnoreCase(code)) { pattern = "LL\n(PL %s)"; - else if (TacGrpSidc.C2GM_OFF_LNE_FCL.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_OFF_LNE_FCL.equalsIgnoreCase(code)) { pattern = "FINAL CL\n(PL %s)"; - else if (TacGrpSidc.C2GM_OFF_LNE_LMTADV.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_OFF_LNE_LMTADV.equalsIgnoreCase(code)) { pattern = "LOA\n(PL %s)"; - else if (TacGrpSidc.C2GM_OFF_LNE_LD.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_OFF_LNE_LD.equalsIgnoreCase(code)) { pattern = "LD\n(PL %s)"; - else if (TacGrpSidc.C2GM_OFF_LNE_LDLC.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_OFF_LNE_LDLC.equalsIgnoreCase(code)) { pattern = "LD/LC\n(PL %s)"; - else if (TacGrpSidc.C2GM_OFF_LNE_PLD.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_OFF_LNE_PLD.equalsIgnoreCase(code)) { pattern = "PLD\n(PL %s)"; - else if (TacGrpSidc.C2GM_SPL_LNE_REL.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_SPL_LNE_REL.equalsIgnoreCase(code)) { pattern = "RL\n(PL %s)"; - else if (TacGrpSidc.FSUPP_LNE_C2LNE_NFL.equalsIgnoreCase(code)) + } else if (TacGrpSidc.FSUPP_LNE_C2LNE_NFL.equalsIgnoreCase(code)) { pattern = "NFL\n(PL %s)"; + } - if (pattern != null) - { + if (pattern != null) { String text = this.getText(); return String.format(pattern, text != null ? text : ""); } @@ -167,10 +167,11 @@ else if (TacGrpSidc.FSUPP_LNE_C2LNE_NFL.equalsIgnoreCase(code)) return ""; } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { String text = this.getGraphicLabel(); this.addLabel(text); // Start label @@ -183,15 +184,13 @@ protected void createLabels() * @param dc Current draw context. */ @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { Iterator iterator = this.path.getPositions().iterator(); // Find the first and last positions on the path Position first = iterator.next(); Position last = first; - while (iterator.hasNext()) - { + while (iterator.hasNext()) { last = iterator.next(); } @@ -203,26 +202,21 @@ protected void determineLabelPositions(DrawContext dc) endLabel.setPosition(last); // Set the West-most label to right alignment, and the East-most label to left alignment. - if (first.longitude.degrees < last.longitude.degrees) - { + if (first.longitude.degrees < last.longitude.degrees) { startLabel.setTextAlign(AVKey.RIGHT); endLabel.setTextAlign(AVKey.LEFT); - } - else - { + } else { startLabel.setTextAlign(AVKey.LEFT); endLabel.setTextAlign(AVKey.RIGHT); } } @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); // Probable Line of Deployment graphic always renders with dashed lines. - if (TacGrpSidc.C2GM_OFF_LNE_PLD.equalsIgnoreCase(this.maskedSymbolCode)) - { + if (TacGrpSidc.C2GM_OFF_LNE_PLD.equalsIgnoreCase(this.maskedSymbolCode)) { attributes.setOutlineStippleFactor(PLD_OUTLINE_STIPPLE_FACTOR); attributes.setOutlineStipplePattern(this.getOutlineStipplePattern()); } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PrincipleDirectionOfFire.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PrincipleDirectionOfFire.java index 32e511e267..313889d858 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PrincipleDirectionOfFire.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PrincipleDirectionOfFire.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -24,37 +23,63 @@ * @author pabercrombie * @version $Id: PrincipleDirectionOfFire.java 560 2012-04-26 16:28:24Z pabercrombie $ */ -public class PrincipleDirectionOfFire extends AbstractMilStd2525TacticalGraphic implements PreRenderable -{ - /** Default length of the arrowhead, as a fraction of the total line length. */ +public class PrincipleDirectionOfFire extends AbstractMilStd2525TacticalGraphic implements PreRenderable { + + /** + * Default length of the arrowhead, as a fraction of the total line length. + */ public final static double DEFAULT_ARROWHEAD_LENGTH = 0.1; - /** Default angle of the arrowhead. */ + /** + * Default angle of the arrowhead. + */ public final static Angle DEFAULT_ARROWHEAD_ANGLE = Angle.fromDegrees(60.0); - /** Default width of the arrowhead outline. */ + /** + * Default width of the arrowhead outline. + */ public final static double DEFAULT_ARROWHEAD_OUTLINE_WIDTH = 0.3; - /** Length of the arrowhead from base to tip, as a fraction of the total line length. */ + /** + * Length of the arrowhead from base to tip, as a fraction of the total line length. + */ protected Angle arrowAngle = DEFAULT_ARROWHEAD_ANGLE; - /** Angle of the arrowhead. */ + /** + * Angle of the arrowhead. + */ protected double arrowLength = DEFAULT_ARROWHEAD_LENGTH; - /** Width of the arrowhead outline, as a fraction of the arrowhead length. */ + /** + * Width of the arrowhead outline, as a fraction of the arrowhead length. + */ protected double outlineWidth = DEFAULT_ARROWHEAD_OUTLINE_WIDTH; - /** First control point. */ + /** + * First control point. + */ protected Position position1; - /** Second control point. */ + /** + * Second control point. + */ protected Position position2; - /** Third control point. */ + /** + * Third control point. + */ protected Position position3; - /** Path used to render the line. */ + /** + * Path used to render the line. + */ protected Path[] paths; - /** Symbol drawn at the center of the range fan. */ + /** + * Symbol drawn at the center of the range fan. + */ protected TacticalSymbol symbol; - /** Attributes applied to the symbol. */ + /** + * Attributes applied to the symbol. + */ protected TacticalSymbolAttributes symbolAttributes; - /** Polygon used to render the "thick" line on the left leg of the graphic. */ + /** + * Polygon used to render the "thick" line on the left leg of the graphic. + */ protected SurfacePolygon thickLine; /** @@ -62,8 +87,7 @@ public class PrincipleDirectionOfFire extends AbstractMilStd2525TacticalGraphic * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_DEF_LNE_PDF); } @@ -72,8 +96,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public PrincipleDirectionOfFire(String sidc) - { + public PrincipleDirectionOfFire(String sidc) { super(sidc); } @@ -82,8 +105,7 @@ public PrincipleDirectionOfFire(String sidc) * * @return Angle of the arrowhead in the graphic. */ - public Angle getArrowAngle() - { + public Angle getArrowAngle() { return this.arrowAngle; } @@ -92,17 +114,14 @@ public Angle getArrowAngle() * * @param arrowAngle The angle of the arrowhead. Must be greater than zero degrees and less than 90 degrees. */ - public void setArrowAngle(Angle arrowAngle) - { - if (arrowAngle == null) - { + public void setArrowAngle(Angle arrowAngle) { + if (arrowAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) - { + if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) { String msg = Logging.getMessage("generic.AngleOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -116,8 +135,7 @@ public void setArrowAngle(Angle arrowAngle) * * @return The length of the arrowhead as a fraction of the total line length. */ - public double getArrowLength() - { + public double getArrowLength() { return this.arrowLength; } @@ -125,12 +143,10 @@ public double getArrowLength() * Specifies the length of the arrowhead. * * @param arrowLength Length of the arrowhead as a fraction of the total line length. If the arrowhead length is - * 0.25, then the arrowhead length will be one quarter of the total line length. + * 0.25, then the arrowhead length will be one quarter of the total line length. */ - public void setArrowLength(double arrowLength) - { - if (arrowLength < 0) - { + public void setArrowLength(double arrowLength) { + if (arrowLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -144,8 +160,7 @@ public void setArrowLength(double arrowLength) * * @return The symbol drawn at the center of the range fan. May be null. */ - public String getSymbol() - { + public String getSymbol() { return this.symbol != null ? this.symbol.getIdentifier() : null; } @@ -155,19 +170,16 @@ public String getSymbol() * center position. * * @param sidc Identifier for a MIL-STD-2525C symbol to draw at the center of the range fan. May be null to indicate - * that no symbol is drawn. + * that no symbol is drawn. */ - public void setSymbol(String sidc) - { - if (sidc != null) - { - if (this.symbolAttributes == null) + public void setSymbol(String sidc) { + if (sidc != null) { + if (this.symbolAttributes == null) { this.symbolAttributes = new BasicTacticalSymbolAttributes(); + } this.symbol = this.createSymbol(sidc, this.position1, this.symbolAttributes); - } - else - { + } else { // Null value indicates no symbol. this.symbol = null; this.symbolAttributes = null; @@ -180,24 +192,19 @@ public void setSymbol(String sidc) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { Iterator iterator = positions.iterator(); this.position1 = iterator.next(); this.position2 = iterator.next(); this.position3 = iterator.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -206,120 +213,120 @@ public void setPositions(Iterable positions) this.paths = null; // Need to recompute path for the new control points this.thickLine = null; - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.setPosition(this.position1); } } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return Arrays.asList(this.position1, this.position2, this.position3); } - /** {@inheritDoc} */ - public Position getReferencePosition() - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { return this.position1; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override @SuppressWarnings("unchecked") - public void setModifier(String modifier, Object value) - { - if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) - { + public void setModifier(String modifier, Object value) { + if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier) && value instanceof String) { this.setSymbol((String) value); - } - else - { + } else { super.setModifier(modifier, value); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Object getModifier(String modifier) - { - if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) - { + public Object getModifier(String modifier) { + if (SymbologyConstants.SYMBOL_INDICATOR.equals(modifier)) { return this.getSymbol(); - } - else - { + } else { return super.getModifier(modifier); } } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } - if (this.paths == null) - { + if (this.paths == null) { this.createShapes(dc); } this.determinePerFrameAttributes(dc); - if (this.thickLine != null) + if (this.thickLine != null) { this.thickLine.preRender(dc); + } } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - for (Path path : this.paths) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + for (Path path : this.paths) { path.render(dc); } - if (this.thickLine != null) - { + if (this.thickLine != null) { this.thickLine.render(dc); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void doRenderGraphicModifiers(DrawContext dc) - { + protected void doRenderGraphicModifiers(DrawContext dc) { super.doRenderGraphicModifiers(dc); - if (this.symbol != null) - { + if (this.symbol != null) { this.symbol.render(dc); } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths == null) + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths == null) { return; + } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.setDelegateOwner(owner); } - if (this.symbol != null) + if (this.symbol != null) { this.symbol.setDelegateOwner(owner); + } - if (this.thickLine != null) + if (this.thickLine != null) { this.thickLine.setDelegateOwner(owner); + } } - /** Create labels for the start and end of the path. */ + /** + * Create labels for the start and end of the path. + */ @Override - protected void createLabels() - { + protected void createLabels() { this.addLabel("(PDF)"); } @@ -328,8 +335,7 @@ protected void createLabels() * * @param dc Current draw context. */ - protected void createShapes(DrawContext dc) - { + protected void createShapes(DrawContext dc) { this.paths = new Path[4]; int i = 0; @@ -351,10 +357,11 @@ protected void createShapes(DrawContext dc) Angle azimuth = LatLon.greatCircleAzimuth(this.position1, this.position2); Angle azimuth2 = LatLon.greatCircleAzimuth(this.position1, this.position3); - if (azimuth.compareTo(azimuth2) > 0) + if (azimuth.compareTo(azimuth2) > 0) { azimuth = azimuth.add(Angle.NEG90); - else + } else { azimuth = azimuth.add(Angle.POS90); + } Angle distance = LatLon.greatCircleDistance(this.position1, this.position2); LatLon loc3 = LatLon.greatCircleEndPosition(loc1, azimuth, distance.multiply(0.01)); @@ -366,14 +373,13 @@ protected void createShapes(DrawContext dc) /** * Determine the positions that make up the arrowhead. * - * @param dc Current draw context. + * @param dc Current draw context. * @param startPosition Position of the arrow's base. - * @param endPosition Position of the arrow head tip. + * @param endPosition Position of the arrow head tip. * * @return Positions that define the arrowhead. */ - protected List computeArrowheadPositions(DrawContext dc, Position startPosition, Position endPosition) - { + protected List computeArrowheadPositions(DrawContext dc, Position startPosition, Position endPosition) { Globe globe = dc.getGlobe(); // Arrowhead looks like this: @@ -384,7 +390,6 @@ protected List computeArrowheadPositions(DrawContext dc, Position star // C/ // | | // Length - Vec4 p1 = globe.computePointFromPosition(startPosition); Vec4 pB = globe.computePointFromPosition(endPosition); @@ -413,10 +418,11 @@ protected List computeArrowheadPositions(DrawContext dc, Position star return TacticalGraphicUtil.asPositionList(globe, pA, pB, pC); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void applyDefaultAttributes(ShapeAttributes attributes) - { + protected void applyDefaultAttributes(ShapeAttributes attributes) { super.applyDefaultAttributes(attributes); // Enable the polygon interior for the "thick line" polygon. All other parts of the graphic are drawn with Path, @@ -424,12 +430,14 @@ protected void applyDefaultAttributes(ShapeAttributes attributes) attributes.setDrawInterior(true); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void determineLabelPositions(DrawContext dc) - { - if (WWUtil.isEmpty(this.labels)) + protected void determineLabelPositions(DrawContext dc) { + if (WWUtil.isEmpty(this.labels)) { return; + } Angle azimuth = LatLon.greatCircleAzimuth(this.position1, this.position2); Angle distance = LatLon.greatCircleDistance(this.position1, this.position2); @@ -439,15 +447,15 @@ protected void determineLabelPositions(DrawContext dc) this.labels.get(0).setPosition(new Position(ll, 0)); } - /** {@inheritDoc} Overridden to update symbol attributes. */ + /** + * {@inheritDoc} Overridden to update symbol attributes. + */ @Override - protected void determineActiveAttributes() - { + protected void determineActiveAttributes() { super.determineActiveAttributes(); // Apply active attributes to the symbol. - if (this.symbolAttributes != null) - { + if (this.symbolAttributes != null) { ShapeAttributes activeAttributes = this.getActiveShapeAttributes(); this.symbolAttributes.setOpacity(activeAttributes.getInteriorOpacity()); this.symbolAttributes.setScale(this.activeOverrides.getScale()); @@ -461,8 +469,7 @@ protected void determineActiveAttributes() * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(List positions) - { + protected Path createPath(List positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); @@ -472,8 +479,7 @@ protected Path createPath(List positions) return path; } - protected SurfacePolygon createPolygon(List positions) - { + protected SurfacePolygon createPolygon(List positions) { SurfacePolygon polygon = new SurfacePolygon(positions); polygon.setAttributes(this.getActiveShapeAttributes()); return polygon; diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PullUpPoint.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PullUpPoint.java index e6d9117103..851f884c48 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PullUpPoint.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/PullUpPoint.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -22,12 +21,16 @@ * @author pabercrombie * @version $Id: PullUpPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class PullUpPoint extends AbstractCircularGraphic implements TacticalPoint, PreRenderable -{ - /** Default radius, in meters, for the circle. */ +public class PullUpPoint extends AbstractCircularGraphic implements TacticalPoint, PreRenderable { + + /** + * Default radius, in meters, for the circle. + */ public final static double DEFAULT_RADIUS = 1000.0; - /** Path to draw the bowtie in the middle of the circle. */ + /** + * Path to draw the bowtie in the middle of the circle. + */ protected Path bowtie; /** @@ -35,8 +38,7 @@ public class PullUpPoint extends AbstractCircularGraphic implements TacticalPoin * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_AVN_PNT_PUP); } @@ -45,27 +47,27 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public PullUpPoint(String sidc) - { + public PullUpPoint(String sidc) { super(sidc); this.setRadius(DEFAULT_RADIUS); } - /** Invalidate the bowtie shape when the circle changes. */ + /** + * Invalidate the bowtie shape when the circle changes. + */ @Override - protected void reset() - { + protected void reset() { this.bowtie = null; } - /** {@inheritDoc} Overridden to draw airfield graphic. */ + /** + * {@inheritDoc} Overridden to draw airfield graphic. + */ @Override - protected void doRenderGraphic(DrawContext dc) - { + protected void doRenderGraphic(DrawContext dc) { super.doRenderGraphic(dc); - if (bowtie == null) - { + if (bowtie == null) { this.bowtie = this.createBowtie(dc); } @@ -79,8 +81,7 @@ protected void doRenderGraphic(DrawContext dc) * * @return Path for the bowtie. */ - protected Path createBowtie(DrawContext dc) - { + protected Path createBowtie(DrawContext dc) { // A C // |\ /| // | \/ | @@ -111,20 +112,19 @@ protected Path createBowtie(DrawContext dc) * * @return Position list. All elevations will be set to zero. */ - protected List asPositionList(LatLon... locations) - { + protected List asPositionList(LatLon... locations) { List positions = new ArrayList(locations.length); - for (LatLon loc : locations) - { + for (LatLon loc : locations) { positions.add(new Position(loc, 0)); } return positions; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void createLabels() - { + protected void createLabels() { TacticalGraphicLabel label = this.addLabel("PUP"); label.setTextAlign(AVKey.LEFT); } @@ -135,8 +135,7 @@ protected void createLabels() * @param dc Current draw context. */ @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { LatLon center = this.circle.getCenter(); double distance = this.circle.getRadius() * 1.1; // Place the label just beyond the radius. Angle radius = Angle.fromRadians(distance / dc.getGlobe().getRadius()); @@ -151,8 +150,7 @@ protected void determineLabelPositions(DrawContext dc) * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath() - { + protected Path createPath() { Path path = new Path(); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Route.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Route.java index 56a24bca56..e4cc70c877 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Route.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/Route.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.WorldWind; @@ -28,20 +27,28 @@ * @author pabercrombie * @version $Id: Route.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Route extends AbstractMilStd2525TacticalGraphic implements TacticalRoute, PreRenderable -{ - /** Width of the route if no width is specified in the modifiers. */ +public class Route extends AbstractMilStd2525TacticalGraphic implements TacticalRoute, PreRenderable { + + /** + * Width of the route if no width is specified in the modifiers. + */ public static final double DEFAULT_WIDTH = 2000; protected static final Offset DEFAULT_OFFSET = Offset.fromFraction(-0.5, -0.5d); - /** Path used to render the route. */ + /** + * Path used to render the route. + */ protected List paths; - /** Control points that define the shape. */ + /** + * Control points that define the shape. + */ protected Iterable positions; - /** Graphics drawn at the route control points. */ + /** + * Graphics drawn at the route control points. + */ protected Iterable children; /** @@ -49,54 +56,52 @@ public class Route extends AbstractMilStd2525TacticalGraphic implements Tactical * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_AVN_LNE_ACDR, - TacGrpSidc.C2GM_AVN_LNE_MRR, - TacGrpSidc.C2GM_AVN_LNE_SAAFR, - TacGrpSidc.C2GM_AVN_LNE_UAR, - TacGrpSidc.C2GM_AVN_LNE_LLTR); + TacGrpSidc.C2GM_AVN_LNE_ACDR, + TacGrpSidc.C2GM_AVN_LNE_MRR, + TacGrpSidc.C2GM_AVN_LNE_SAAFR, + TacGrpSidc.C2GM_AVN_LNE_UAR, + TacGrpSidc.C2GM_AVN_LNE_LLTR); } - public Route(String sidc) - { + public Route(String sidc) { super(sidc); } - /** {@inheritDoc} Overridden to apply the highlight state to child graphics. */ + /** + * {@inheritDoc} Overridden to apply the highlight state to child graphics. + */ @Override - public void setHighlighted(boolean highlighted) - { + public void setHighlighted(boolean highlighted) { super.setHighlighted(highlighted); // Apply the highlight state to the child graphics - if (this.children != null) - { - for (TacticalGraphic child : this.children) - { + if (this.children != null) { + for (TacticalGraphic child : this.children) { child.setHighlighted(highlighted); } } } - /** {@inheritDoc} */ - public Iterable getControlPoints() - { + /** + * {@inheritDoc} + */ + public Iterable getControlPoints() { return this.children; } - /** {@inheritDoc} */ - public void setControlPoints(Iterable points) - { + /** + * {@inheritDoc} + */ + public void setControlPoints(Iterable points) { this.children = points; List newPositions = new ArrayList(); double radius = this.getWidth() / 2.0; - for (TacticalPoint p : points) - { + for (TacticalPoint p : points) { // Set the circle's radius to the width of the route p.setModifier(SymbologyConstants.DISTANCE, radius); @@ -113,17 +118,13 @@ public void setControlPoints(Iterable points) * Indicates the width of the route, in meters. * * @return If the SymbologyConstants.DISTANCE modifier set, and is a Double, returns the value of this modifier. - * Otherwise returns a default width. + * Otherwise returns a default width. */ - public double getWidth() - { + public double getWidth() { Object widthModifier = this.getModifier(SymbologyConstants.DISTANCE); - if (widthModifier instanceof Double) - { + if (widthModifier instanceof Double) { return (Double) widthModifier; - } - else - { + } else { return DEFAULT_WIDTH; } } @@ -134,8 +135,7 @@ public double getWidth() * * @param width Width of the route, in meters. */ - public void setWidth(double width) - { + public void setWidth(double width) { this.setModifier(SymbologyConstants.DISTANCE, width); } @@ -144,10 +144,8 @@ public void setWidth(double width) * * @param positions Control points that orient the graphic. Must provide at least three points. */ - public void setPositions(Iterable positions) - { - if (positions == null) - { + public void setPositions(Iterable positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -158,143 +156,130 @@ public void setPositions(Iterable positions) // Move the control points to the new route positions Iterator positionIterator = positions.iterator(); Iterator childIterator = this.getControlPoints().iterator(); - while (positionIterator.hasNext() && childIterator.hasNext()) - { + while (positionIterator.hasNext() && childIterator.hasNext()) { childIterator.next().setPosition(positionIterator.next()); } this.paths = null; // Need to regenerate paths } - /** {@inheritDoc} */ - public Iterable getPositions() - { + /** + * {@inheritDoc} + */ + public Iterable getPositions() { return this.positions; } - /** {@inheritDoc} */ - public Position getReferencePosition() - { - if (this.positions != null) - { + /** + * {@inheritDoc} + */ + public Position getReferencePosition() { + if (this.positions != null) { return this.positions.iterator().next(); // use the first position } return null; } - /** {@inheritDoc} Overridden to apply new attributes to route control points. */ + /** + * {@inheritDoc} Overridden to apply new attributes to route control points. + */ @Override - public void setAttributes(TacticalGraphicAttributes attributes) - { + public void setAttributes(TacticalGraphicAttributes attributes) { super.setAttributes(attributes); // Apply the highlight state to the child graphics - if (this.children != null) - { - for (TacticalGraphic child : this.children) - { + if (this.children != null) { + for (TacticalGraphic child : this.children) { child.setAttributes(attributes); } } } - /** {@inheritDoc} Overridden to apply new attributes to route control points. */ + /** + * {@inheritDoc} Overridden to apply new attributes to route control points. + */ @Override - public void setHighlightAttributes(TacticalGraphicAttributes attributes) - { + public void setHighlightAttributes(TacticalGraphicAttributes attributes) { super.setHighlightAttributes(attributes); // Apply the highlight state to the child graphics - if (this.children != null) - { - for (TacticalGraphic child : this.children) - { + if (this.children != null) { + for (TacticalGraphic child : this.children) { child.setHighlightAttributes(attributes); } } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setStatus(String status) - { + public void setStatus(String status) { super.setStatus(status); - if (this.children != null) - { - for (TacticalGraphic child : this.children) - { - if (child instanceof MilStd2525TacticalGraphic) - { + if (this.children != null) { + for (TacticalGraphic child : this.children) { + if (child instanceof MilStd2525TacticalGraphic) { ((MilStd2525TacticalGraphic) child).setStatus(status); } } } } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { - if (!this.isVisible()) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { + if (!this.isVisible()) { return; } this.determineActiveAttributes(); - if (this.children != null) - { - for (TacticalGraphic child : this.children) - { - if (child instanceof PreRenderable) - { + if (this.children != null) { + for (TacticalGraphic child : this.children) { + if (child instanceof PreRenderable) { ((PreRenderable) child).preRender(dc); } } } } - /** {@inheritDoc} */ - protected void doRenderGraphic(DrawContext dc) - { - if (this.paths == null) - { + /** + * {@inheritDoc} + */ + protected void doRenderGraphic(DrawContext dc) { + if (this.paths == null) { this.createPaths(dc); } - for (Path path : this.paths) - { + for (Path path : this.paths) { path.render(dc); } - if (this.children != null) - { - for (TacticalGraphic child : this.children) - { + if (this.children != null) { + for (TacticalGraphic child : this.children) { child.render(dc); } } } - /** {@inheritDoc} */ - protected void applyDelegateOwner(Object owner) - { - if (this.paths != null) - { - for (Path path : this.paths) - { + /** + * {@inheritDoc} + */ + protected void applyDelegateOwner(Object owner) { + if (this.paths != null) { + for (Path path : this.paths) { path.setDelegateOwner(owner); } } - if (this.children != null) - { + if (this.children != null) { boolean showTextModifiers = this.isShowTextModifiers(); boolean showGraphicModifiers = this.isShowGraphicModifiers(); boolean showHostile = this.isShowHostileIndicator(); - for (TacticalGraphic child : this.children) - { + for (TacticalGraphic child : this.children) { child.setDelegateOwner(owner); child.setShowTextModifiers(showTextModifiers); child.setShowGraphicModifiers(showGraphicModifiers); @@ -308,8 +293,7 @@ protected void applyDelegateOwner(Object owner) * * @param dc Current draw context. */ - protected void createPaths(DrawContext dc) - { + protected void createPaths(DrawContext dc) { Globe globe = dc.getGlobe(); this.paths = new ArrayList(); @@ -325,8 +309,7 @@ protected void createPaths(DrawContext dc) Vec4 normal = globe.computeSurfaceNormalAtPoint(pA); - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Position posB = iterator.next(); pB = globe.computePointFromPosition(posB); @@ -358,8 +341,7 @@ protected void createPaths(DrawContext dc) // Apply width to the control points. double radius = this.getWidth() / 2.0; - for (TacticalPoint p : this.getControlPoints()) - { + for (TacticalPoint p : this.getControlPoints()) { p.setModifier(SymbologyConstants.DISTANCE, radius); } } @@ -369,21 +351,18 @@ protected void createPaths(DrawContext dc) * * @return Text for the main label. May return null if there is no text. */ - protected String createLabelText() - { + protected String createLabelText() { StringBuilder sb = new StringBuilder(); Object o = this.getModifier(SymbologyConstants.UNIQUE_DESIGNATION); - if (o != null) - { + if (o != null) { sb.append("Name: "); sb.append(o); sb.append("\n"); } o = this.getModifier(SymbologyConstants.DISTANCE); - if (o != null) - { + if (o != null) { sb.append("Width: "); sb.append(o); sb.append(" m"); @@ -391,30 +370,26 @@ protected String createLabelText() } Object[] altitudes = TacticalGraphicUtil.getAltitudeRange(this); - if (altitudes[0] != null) - { + if (altitudes[0] != null) { sb.append("Min Alt: "); sb.append(altitudes[0]); sb.append("\n"); } - if (altitudes[1] != null) - { + if (altitudes[1] != null) { sb.append("Max Alt: "); sb.append(altitudes[1]); sb.append("\n"); } Object[] dates = TacticalGraphicUtil.getDateRange(this); - if (dates[0] != null) - { + if (dates[0] != null) { sb.append("DTG Start: "); sb.append(dates[0]); sb.append("\n"); } - if (dates[1] != null) - { + if (dates[1] != null) { sb.append("DTG End: "); sb.append(dates[1]); } @@ -423,11 +398,9 @@ protected String createLabelText() } @Override - protected void createLabels() - { + protected void createLabels() { String labelText = this.createLabelText(); - if (labelText == null) - { + if (labelText == null) { return; } @@ -438,19 +411,16 @@ protected void createLabels() Iterator iterator = this.getPositions().iterator(); // Create a label for each segment of the route - while (iterator.hasNext()) - { + while (iterator.hasNext()) { iterator.next(); // Add a label if this is not the last control point - if (iterator.hasNext()) - { + if (iterator.hasNext()) { StringBuilder sb = new StringBuilder(); sb.append(this.getGraphicLabel()); String text = this.getText(); - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { sb.append(" "); sb.append(text); } @@ -464,20 +434,20 @@ protected void createLabels() * * @return The string the determines the type of route, such as "AC" for "Air Corridor". */ - protected String getGraphicLabel() - { + protected String getGraphicLabel() { String code = this.maskedSymbolCode; - if (TacGrpSidc.C2GM_AVN_LNE_ACDR.equalsIgnoreCase(code)) + if (TacGrpSidc.C2GM_AVN_LNE_ACDR.equalsIgnoreCase(code)) { return "AC"; - else if (TacGrpSidc.C2GM_AVN_LNE_MRR.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_LNE_MRR.equalsIgnoreCase(code)) { return "MRR"; - else if (TacGrpSidc.C2GM_AVN_LNE_SAAFR.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_LNE_SAAFR.equalsIgnoreCase(code)) { return "SAAFR"; - else if (TacGrpSidc.C2GM_AVN_LNE_LLTR.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_LNE_LLTR.equalsIgnoreCase(code)) { return "LLTR"; - else if (TacGrpSidc.C2GM_AVN_LNE_UAR.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_LNE_UAR.equalsIgnoreCase(code)) { return "UA"; + } return ""; } @@ -490,23 +460,20 @@ else if (TacGrpSidc.C2GM_AVN_LNE_UAR.equalsIgnoreCase(code)) * @param dc Current draw context. */ @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { Iterator iterator = this.getPositions().iterator(); Position posA = iterator.next(); int i = 0; - while (iterator.hasNext()) - { + while (iterator.hasNext()) { Position posB = iterator.next(); Position midpoint = Position.interpolate(0.5, posA, posB); TacticalGraphicLabel label = this.labels.get(i); // Compute the main label position on the first iteration - if (i == 0) - { + if (i == 0) { // The position of the main label is computed to keep the label a constant screen distance from the // route. However, in order to determine the label size the label needs to have a position, so give it a // temporary position of the route reference position. @@ -531,8 +498,7 @@ protected void determineLabelPositions(DrawContext dc) } @Override - protected Offset getDefaultLabelOffset() - { + protected Offset getDefaultLabelOffset() { return DEFAULT_OFFSET; } @@ -540,16 +506,15 @@ protected Offset getDefaultLabelOffset() * Compute the position of the graphic's main label. This label is positioned to the side of the first segment along * the route. * - * @param dc Current draw context. - * @param label Label for which to compute position. + * @param dc Current draw context. + * @param label Label for which to compute position. * @param midpoint Midpoint of the first route segment. - * @param posB End point of the first route segment. + * @param posB End point of the first route segment. * * @return The position of the main label. */ protected Position computeMainLabelPosition(DrawContext dc, TacticalGraphicLabel label, Position midpoint, - Position posB) - { + Position posB) { Globe globe = dc.getGlobe(); Vec4 pMid = globe.computePointFromPosition(midpoint); @@ -581,12 +546,11 @@ protected Position computeMainLabelPosition(DrawContext dc, TacticalGraphicLabel * Create between two points and configure the Path. * * @param start First position - * @param end Second position + * @param end Second position * * @return New path configured with defaults appropriate for this type of graphic. */ - protected Path createPath(Position start, Position end) - { + protected Path createPath(Position start, Position end) { Path path = new Path(start, end); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/RoutePoint.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/RoutePoint.java index ff7e1e9c14..48c75e8081 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/RoutePoint.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/RoutePoint.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.geom.*; @@ -22,18 +21,17 @@ * @author pabercrombie * @version $Id: RoutePoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class RoutePoint extends AbstractCircularGraphic implements TacticalPoint, PreRenderable -{ +public class RoutePoint extends AbstractCircularGraphic implements TacticalPoint, PreRenderable { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList( - TacGrpSidc.C2GM_AVN_PNT_ACP, - TacGrpSidc.C2GM_AVN_PNT_COMMCP + TacGrpSidc.C2GM_AVN_PNT_ACP, + TacGrpSidc.C2GM_AVN_PNT_COMMCP ); } @@ -42,8 +40,7 @@ public static List getSupportedGraphics() * * @param sidc Symbol code the identifies the graphic. */ - public RoutePoint(String sidc) - { + public RoutePoint(String sidc) { super(sidc); } @@ -52,14 +49,12 @@ public RoutePoint(String sidc) * * @return Text for the main label. May return null if there is no text. */ - protected String createLabelText() - { + protected String createLabelText() { StringBuilder sb = new StringBuilder(); sb.append(this.getGraphicLabel()); String text = this.getText(); - if (!WWUtil.isEmpty(text)) - { + if (!WWUtil.isEmpty(text)) { sb.append("\n"); sb.append(this.getText()); } @@ -67,24 +62,22 @@ protected String createLabelText() return sb.toString(); } - protected String getGraphicLabel() - { + protected String getGraphicLabel() { String code = this.maskedSymbolCode; - if (TacGrpSidc.C2GM_AVN_PNT_ACP.equalsIgnoreCase(code)) + if (TacGrpSidc.C2GM_AVN_PNT_ACP.equalsIgnoreCase(code)) { return "ACP"; - else if (TacGrpSidc.C2GM_AVN_PNT_COMMCP.equalsIgnoreCase(code)) + } else if (TacGrpSidc.C2GM_AVN_PNT_COMMCP.equalsIgnoreCase(code)) { return "CCP"; + } return ""; } @Override - protected void createLabels() - { + protected void createLabels() { String labelText = this.createLabelText(); - if (!WWUtil.isEmpty(labelText)) - { + if (!WWUtil.isEmpty(labelText)) { this.addLabel(labelText); } } @@ -95,8 +88,7 @@ protected void createLabels() * @param dc Current draw context. */ @Override - protected void determineLabelPositions(DrawContext dc) - { + protected void determineLabelPositions(DrawContext dc) { LatLon center = this.circle.getCenter(); this.labels.get(0).setPosition(new Position(center, 0)); } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/SupportingAttack.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/SupportingAttack.java index 28fa75b768..40e714f4f3 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/SupportingAttack.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/SupportingAttack.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.symbology.milstd2525.graphics.lines; import gov.nasa.worldwind.symbology.milstd2525.graphics.TacGrpSidc; @@ -16,20 +15,18 @@ * @author pabercrombie * @version $Id: SupportingAttack.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SupportingAttack extends AbstractAxisArrow -{ +public class SupportingAttack extends AbstractAxisArrow { + /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ - public static List getSupportedGraphics() - { + public static List getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_LNE_AXSADV_GRD_SUPATK); } - public SupportingAttack(String sidc) - { + public SupportingAttack(String sidc) { super(sidc); } } diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/package-info.java b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/package-info.java index 78f575b1f1..090faffed5 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/package-info.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/graphics/lines/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

                  * MIL-STD-2525 line graphics. Applications should use {@link diff --git a/src/gov/nasa/worldwind/symbology/milstd2525/package-info.java b/src/gov/nasa/worldwind/symbology/milstd2525/package-info.java index 60c4458fc9..1a91969510 100644 --- a/src/gov/nasa/worldwind/symbology/milstd2525/package-info.java +++ b/src/gov/nasa/worldwind/symbology/milstd2525/package-info.java @@ -3,12 +3,11 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

                  * Tactical graphics and symbols defined by the MIL-STD-2525 symbology set.

                  * -

                  + *

                  * {@link gov.nasa.worldwind.symbology.milstd2525.MilStd2525GraphicFactory} is a graphics factory that creates graphics * in the 2525 set. For general information on creating and displaying tactical graphics, see {@link * gov.nasa.worldwind.symbology.TacticalGraphic}.

                  diff --git a/src/gov/nasa/worldwind/symbology/package-info.java b/src/gov/nasa/worldwind/symbology/package-info.java index 37afecb6d6..831a692410 100644 --- a/src/gov/nasa/worldwind/symbology/package-info.java +++ b/src/gov/nasa/worldwind/symbology/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

                  * Provides classes for creating and displaying graphics from standard symbol sets. See {@link diff --git a/src/gov/nasa/worldwind/terrain/AbstractElevationModel.java b/src/gov/nasa/worldwind/terrain/AbstractElevationModel.java index 86819d2df6..9ab5313d9b 100644 --- a/src/gov/nasa/worldwind/terrain/AbstractElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/AbstractElevationModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.*; @@ -21,8 +20,8 @@ * @author tag * @version $Id: AbstractElevationModel.java 3420 2015-09-10 23:25:43Z tgaskins $ */ -abstract public class AbstractElevationModel extends WWObjectImpl implements ElevationModel -{ +abstract public class AbstractElevationModel extends WWObjectImpl implements ElevationModel { + protected FileStore dataFileStore = WorldWind.getDataFileStore(); protected double missingDataFlag = -Double.MAX_VALUE; protected double missingDataValue = 0; @@ -31,83 +30,67 @@ abstract public class AbstractElevationModel extends WWObjectImpl implements Ele protected long expiryTime = 0; protected boolean enabled = true; - public void dispose() - { + public void dispose() { } - public String getName() - { + public String getName() { Object n = this.getValue(AVKey.DISPLAY_NAME); return n != null ? n.toString() : this.toString(); } - public void setName(String name) - { + public void setName(String name) { this.setValue(AVKey.DISPLAY_NAME, name); } - public String toString() - { + public String toString() { Object n = this.getValue(AVKey.DISPLAY_NAME); return n != null ? n.toString() : super.toString(); } - public boolean isNetworkRetrievalEnabled() - { + public boolean isNetworkRetrievalEnabled() { return this.networkRetrievalEnabled; } - public void setNetworkRetrievalEnabled(boolean enabled) - { + public void setNetworkRetrievalEnabled(boolean enabled) { this.networkRetrievalEnabled = enabled; } - public long getExpiryTime() - { + public long getExpiryTime() { return this.expiryTime; } - public void setExpiryTime(long expiryTime) - { + public void setExpiryTime(long expiryTime) { this.expiryTime = expiryTime; } - public void setEnabled(boolean enabled) - { + public void setEnabled(boolean enabled) { this.enabled = enabled; } - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public double getMissingDataSignal() - { + public double getMissingDataSignal() { return missingDataFlag; } - public void setMissingDataSignal(double missingDataFlag) - { + public void setMissingDataSignal(double missingDataFlag) { this.missingDataFlag = missingDataFlag; } - public double getMissingDataReplacement() - { + public double getMissingDataReplacement() { return missingDataValue; } - public void setMissingDataReplacement(double missingDataValue) - { + public void setMissingDataReplacement(double missingDataValue) { this.missingDataValue = missingDataValue; } - public double getDetailHint(Sector sector) - { - if (sector == null) - { + public double getDetailHint(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -116,20 +99,16 @@ public double getDetailHint(Sector sector) return 0.0; } - public FileStore getDataFileStore() - { + public FileStore getDataFileStore() { return dataFileStore; } - public void setDataFileStore(FileStore dataFileStore) - { + public void setDataFileStore(FileStore dataFileStore) { this.dataFileStore = dataFileStore; } - public double getElevation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getElevation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -140,91 +119,78 @@ public double getElevation(Angle latitude, Angle longitude) } public double[] getElevations(Sector sector, List latLons, double[] targetResolutions, - double[] elevations) - { - return new double[] {this.getElevations(sector, latLons, targetResolutions[0], elevations)}; + double[] elevations) { + return new double[]{this.getElevations(sector, latLons, targetResolutions[0], elevations)}; } public double[] getUnmappedElevations(Sector sector, List latLons, double[] targetResolutions, - double[] elevations) - { - return new double[] {this.getElevations(sector, latLons, targetResolutions[0], elevations)}; + double[] elevations) { + return new double[]{this.getElevations(sector, latLons, targetResolutions[0], elevations)}; } - public double[] getBestResolutions(Sector sector) - { - return new double[] {this.getBestResolution(sector)}; + public double[] getBestResolutions(Sector sector) { + return new double[]{this.getBestResolution(sector)}; } - public String getRestorableState() - { + public String getRestorableState() { return null; } - public void restoreState(String stateInXml) - { + public void restoreState(String stateInXml) { String message = Logging.getMessage("RestorableSupport.RestoreNotSupported"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } public void composeElevations(Sector sector, List latlons, int tileWidth, double[] buffer) - throws Exception - { - if (sector == null) - { + throws Exception { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (latlons == null) - { + if (latlons == null) { String msg = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer == null) - { + if (buffer == null) { String msg = Logging.getMessage("nullValue.ElevationsBufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (tileWidth < 1) - { + if (tileWidth < 1) { String msg = Logging.getMessage("generic.SizeOutOfRange", tileWidth); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer.length < latlons.size() || tileWidth > latlons.size()) - { + if (buffer.length < latlons.size() || tileWidth > latlons.size()) { String msg = Logging.getMessage("ElevationModel.ElevationsBufferTooSmall", latlons.size()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (int i = 0; i < latlons.size(); i++) - { + for (int i = 0; i < latlons.size(); i++) { LatLon ll = latlons.get(i); double e = this.getUnmappedElevation(ll.getLatitude(), ll.getLongitude()); - if (e != this.getMissingDataSignal() && !this.isTransparentValue(e)) + if (e != this.getMissingDataSignal() && !this.isTransparentValue(e)) { buffer[i] = e; + } } } - protected boolean isTransparentValue(Double value) - { + protected boolean isTransparentValue(Double value) { return ((value == null || value.equals(this.getMissingDataSignal())) - && this.getMissingDataReplacement() == this.getMissingDataSignal()); + && this.getMissingDataReplacement() == this.getMissingDataSignal()); } //**************************************************************// //******************** Configuration *************************// //**************************************************************// - /** * Returns true if a specified DOM document is an ElevationModel configuration document, and false otherwise. * @@ -234,10 +200,8 @@ protected boolean isTransparentValue(Double value) * * @throws IllegalArgumentException if document is null. */ - public static boolean isElevationModelConfigDocument(Element domElement) - { - if (domElement == null) - { + public static boolean isElevationModelConfigDocument(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -252,7 +216,7 @@ public static boolean isElevationModelConfigDocument(Element domElement) /** * Appends elevation model configuration parameters as elements to the specified context. This appends elements for * the following parameters: - * + * *
                  Parameters
                  ParameterElement PathType
                  ParameterElement PathType
                  {@link * AVKey#DISPLAY_NAME}DisplayNameString
                  {@link * AVKey#NETWORK_RETRIEVAL_ENABLED}NetworkRetrievalEnabledBoolean
                  {@link @@ -260,24 +224,21 @@ public static boolean isElevationModelConfigDocument(Element domElement) * AVKey#MISSING_DATA_REPLACEMENT}MissingData/@replacementDouble
                  {@link * AVKey#DETAIL_HINT}DataDetailHintDouble
                  * - * @param params the key-value pairs which define the elevation model configuration parameters. + * @param params the key-value pairs which define the elevation model configuration parameters. * @param context the XML document root on which to append elevation model configuration elements. * * @return a reference to context. * * @throws IllegalArgumentException if either the parameters or the context are null. */ - public static Element createElevationModelConfigElements(AVList params, Element context) - { - if (params == null) - { + public static Element createElevationModelConfigElements(AVList params, Element context) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -286,20 +247,22 @@ public static Element createElevationModelConfigElements(AVList params, Element WWXML.checkAndAppendTextElement(params, AVKey.DISPLAY_NAME, context, "DisplayName"); WWXML.checkAndAppendBooleanElement(params, AVKey.NETWORK_RETRIEVAL_ENABLED, context, "NetworkRetrievalEnabled"); - if (params.getValue(AVKey.MISSING_DATA_SIGNAL) != null || - params.getValue(AVKey.MISSING_DATA_REPLACEMENT) != null) - { + if (params.getValue(AVKey.MISSING_DATA_SIGNAL) != null + || params.getValue(AVKey.MISSING_DATA_REPLACEMENT) != null) { Element el = WWXML.getElement(context, "MissingData", null); - if (el == null) + if (el == null) { el = WWXML.appendElementPath(context, "MissingData"); + } Double d = AVListImpl.getDoubleValue(params, AVKey.MISSING_DATA_SIGNAL); - if (d != null) + if (d != null) { WWXML.setDoubleAttribute(el, "signal", d); + } d = AVListImpl.getDoubleValue(params, AVKey.MISSING_DATA_REPLACEMENT); - if (d != null) + if (d != null) { WWXML.setDoubleAttribute(el, "replacement", d); + } } WWXML.checkAndAppendDoubleElement(params, AVKey.DETAIL_HINT, context, "DataDetailHint"); @@ -311,7 +274,7 @@ public static Element createElevationModelConfigElements(AVList params, Element * Parses elevation model configuration parameters from the specified DOM document. This writes output as key-value * pairs to params. If a parameter from the XML document already exists in params, that parameter is ignored. * Supported parameters are: - * + * * @@ -321,49 +284,46 @@ public static Element createElevationModelConfigElements(AVList params, Element *
                  Parameters
                  ParameterElement PathType
                  ParameterElement PathType
                  {@link * gov.nasa.worldwind.avlist.AVKey#DISPLAY_NAME}DisplayNameString
                  {@link * gov.nasa.worldwind.avlist.AVKey#NETWORK_RETRIEVAL_ENABLED}NetworkRetrievalEnabledBoolean
                  * * @param domElement the XML document root to parse for elevation model configuration elements. - * @param params the output key-value pairs which recieve the elevation model configuration parameters. A null - * reference is permitted. + * @param params the output key-value pairs which recieve the elevation model configuration parameters. A null + * reference is permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - public static AVList getElevationModelConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + public static AVList getElevationModelConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } XPath xpath = WWXML.makeXPath(); WWXML.checkAndSetStringParam(domElement, params, AVKey.DISPLAY_NAME, "DisplayName", xpath); WWXML.checkAndSetBooleanParam(domElement, params, AVKey.NETWORK_RETRIEVAL_ENABLED, "NetworkRetrievalEnabled", - xpath); + xpath); WWXML.checkAndSetDoubleParam(domElement, params, AVKey.MISSING_DATA_SIGNAL, "MissingData/@signal", xpath); WWXML.checkAndSetDoubleParam(domElement, params, AVKey.MISSING_DATA_REPLACEMENT, "MissingData/@replacement", - xpath); + xpath); WWXML.checkAndSetDoubleParam(domElement, params, AVKey.DETAIL_HINT, "DataDetailHint", xpath); WWXML.checkAndSetIntegerParam(domElement, params, AVKey.MAX_ABSENT_TILE_ATTEMPTS, "MaxAbsentTileAttempts", - xpath); + xpath); WWXML.checkAndSetIntegerParam(domElement, params, AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL, - "MinAbsentTileCheckInterval", xpath); + "MinAbsentTileCheckInterval", xpath); return params; } - public double getLocalDataAvailability(Sector sector, Double targetResolution) - { + public double getLocalDataAvailability(Sector sector, Double targetResolution) { return 1d; } - public double getUnmappedLocalSourceElevation(Angle latitude, Angle longitude) - { + public double getUnmappedLocalSourceElevation(Angle latitude, Angle longitude) { return this.getUnmappedElevation(latitude, longitude); } } diff --git a/src/gov/nasa/worldwind/terrain/BasicElevationModel.java b/src/gov/nasa/worldwind/terrain/BasicElevationModel.java index 424c33e70f..f974584ead 100644 --- a/src/gov/nasa/worldwind/terrain/BasicElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/BasicElevationModel.java @@ -36,7 +36,6 @@ // A "tile" corresponds to one tile of the data set, which has a corresponding unique row/column address in the data // set. An inner class implements Tile. An inner class also implements TileKey, which is used to address the // corresponding Tile in the memory cache. - // Clients of this class get elevations from it by first getting an Elevations object for a specific Sector, then // querying that object for the elevation at individual lat/lon positions. The Elevations object captures information // that is used to compute elevations. See in-line comments for a description. @@ -45,13 +44,12 @@ // then it's loaded by the task into the memory cache. If it's not in the file cache then a retrieval is initiated by // the task. The disk is never accessed during a call to getElevations(sector, resolution) because that method is // likely being called when a frame is being rendered. The details of all this are in-line below. - /** * @author Tom Gaskins * @version $Id: BasicElevationModel.java 3425 2015-09-30 23:17:35Z dcollins $ */ -public class BasicElevationModel extends AbstractElevationModel implements BulkRetrievable -{ +public class BasicElevationModel extends AbstractElevationModel implements BulkRetrievable { + protected final LevelSet levels; protected final double minElevation; protected final double maxElevation; @@ -59,8 +57,8 @@ public class BasicElevationModel extends AbstractElevationModel implements BulkR protected String elevationDataByteOrder = AVKey.LITTLE_ENDIAN; protected double detailHint = 0.0; protected final Object fileLock = new Object(); - protected java.util.concurrent.ConcurrentHashMap levelZeroTiles = - new java.util.concurrent.ConcurrentHashMap(); + protected java.util.concurrent.ConcurrentHashMap levelZeroTiles + = new java.util.concurrent.ConcurrentHashMap(); protected MemoryCache memoryCache; protected int extremesLevel = -1; protected boolean extremesCachingEnabled = true; @@ -69,26 +67,27 @@ public class BasicElevationModel extends AbstractElevationModel implements BulkR // Model resource properties. protected static final int RESOURCE_ID_OGC_CAPABILITIES = 1; - public BasicElevationModel(AVList params) - { - if (params == null) - { + public BasicElevationModel(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.ElevationModelConfigParams"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String s = params.getStringValue(AVKey.BYTE_ORDER); - if (s != null) + if (s != null) { this.setByteOrder(s); + } Double d = (Double) params.getValue(AVKey.DETAIL_HINT); - if (d != null) + if (d != null) { this.setDetailHint(d); + } s = params.getStringValue(AVKey.DISPLAY_NAME); - if (s != null) + if (s != null) { this.setName(s); + } d = (Double) params.getValue(AVKey.ELEVATION_MIN); this.minElevation = d != null ? d : 0; @@ -97,39 +96,47 @@ public BasicElevationModel(AVList params) this.maxElevation = d != null ? d : 0; Long lo = (Long) params.getValue(AVKey.EXPIRY_TIME); - if (lo != null) + if (lo != null) { params.setValue(AVKey.EXPIRY_TIME, lo); + } d = (Double) params.getValue(AVKey.MISSING_DATA_SIGNAL); - if (d != null) + if (d != null) { this.setMissingDataSignal(d); + } d = (Double) params.getValue(AVKey.MISSING_DATA_REPLACEMENT); - if (d != null) + if (d != null) { this.setMissingDataReplacement(d); + } Boolean b = (Boolean) params.getValue(AVKey.NETWORK_RETRIEVAL_ENABLED); - if (b != null) + if (b != null) { this.setNetworkRetrievalEnabled(b); + } s = params.getStringValue(AVKey.DATA_TYPE); - if (s != null) + if (s != null) { this.setElevationDataType(s); + } s = params.getStringValue(AVKey.ELEVATION_EXTREMES_FILE); - if (s != null) + if (s != null) { this.loadExtremeElevations(s); + } b = (Boolean) params.getValue(AVKey.DELETE_CACHE_ON_EXIT); - if (b != null) + if (b != null) { this.setValue(AVKey.DELETE_CACHE_ON_EXIT, true); + } // Set some fallback values if not already set. setFallbacks(params); this.levels = new LevelSet(params); - if (this.levels.getSector() != null && this.getValue(AVKey.SECTOR) == null) + if (this.levels.getSector() != null && this.getValue(AVKey.SECTOR) == null) { this.setValue(AVKey.SECTOR, this.levels.getSector()); + } this.memoryCache = this.createMemoryCache(ElevationTile.class.getName()); @@ -137,33 +144,26 @@ public BasicElevationModel(AVList params) // If any resources should be retrieved for this ElevationModel, start a task to retrieve those resources, and // initialize this ElevationModel once those resources are retrieved. - if (this.isRetrieveResources()) - { + if (this.isRetrieveResources()) { this.startResourceRetrieval(); } } - public BasicElevationModel(Document dom, AVList params) - { + public BasicElevationModel(Document dom, AVList params) { this(dom.getDocumentElement(), params); } - public BasicElevationModel(Element domElement, AVList params) - { + public BasicElevationModel(Element domElement, AVList params) { this(getBasicElevationModelConfigParams(domElement, params)); } - public BasicElevationModel(String restorableStateInXml) - { + public BasicElevationModel(String restorableStateInXml) { this(restorableStateToParams(restorableStateInXml)); RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(restorableStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", restorableStateInXml); Logging.logger().severe(message); @@ -174,54 +174,52 @@ public BasicElevationModel(String restorableStateInXml) } @Override - public Object setValue(String key, Object value) - { + public Object setValue(String key, Object value) { // Offer it to the level set - if (this.getLevels() != null) + if (this.getLevels() != null) { this.getLevels().setValue(key, value); + } return super.setValue(key, value); } @Override - public Object getValue(String key) - { + public Object getValue(String key) { Object value = super.getValue(key); return value != null ? value : this.getLevels().getValue(key); // see if the level set has it } - protected static void setFallbacks(AVList params) - { - if (params.getValue(AVKey.TILE_WIDTH) == null) + protected static void setFallbacks(AVList params) { + if (params.getValue(AVKey.TILE_WIDTH) == null) { params.setValue(AVKey.TILE_WIDTH, 150); + } - if (params.getValue(AVKey.TILE_HEIGHT) == null) + if (params.getValue(AVKey.TILE_HEIGHT) == null) { params.setValue(AVKey.TILE_HEIGHT, 150); + } - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { params.setValue(AVKey.FORMAT_SUFFIX, ".bil"); + } - if (params.getValue(AVKey.NUM_LEVELS) == null) + if (params.getValue(AVKey.NUM_LEVELS) == null) { params.setValue(AVKey.NUM_LEVELS, 2); + } - if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) + if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); + } } - protected MemoryCache getMemoryCache() - { + protected MemoryCache getMemoryCache() { return memoryCache; } - protected MemoryCache createMemoryCache(String cacheName) - { - if (WorldWind.getMemoryCacheSet().containsCache(cacheName)) - { + protected MemoryCache createMemoryCache(String cacheName) { + if (WorldWind.getMemoryCacheSet().containsCache(cacheName)) { return WorldWind.getMemoryCache(cacheName); - } - else - { + } else { long size = Configuration.getLongValue(AVKey.ELEVATION_TILE_CACHE_SIZE, 20000000L); MemoryCache mc = new BasicMemoryCache((long) (0.85 * size), size); mc.setName("Elevation Tiles"); @@ -230,23 +228,19 @@ protected MemoryCache createMemoryCache(String cacheName) } } - public LevelSet getLevels() - { + public LevelSet getLevels() { return this.levels; } - protected Map getLevelZeroTiles() - { + protected Map getLevelZeroTiles() { return levelZeroTiles; } - protected int getExtremesLevel() - { + protected int getExtremesLevel() { return extremesLevel; } - protected BufferWrapper getExtremes() - { + protected BufferWrapper getExtremes() { return extremes; } @@ -259,7 +253,7 @@ protected BufferWrapper getExtremes() * expiry times of the model's individual levels if the value specified to the method is greater than zero. * * @param expiryTime the expiry time of any cached data, expressed as a number of milliseconds beyond the epoch. The - * default expiry time is zero. + * default expiry time is zero. * * @see System#currentTimeMillis() for a description of milliseconds beyond the epoch. */ @@ -267,48 +261,42 @@ public void setExpiryTime(long expiryTime) // Override this method to use intrin { super.setExpiryTime(expiryTime); - if (expiryTime > 0) + if (expiryTime > 0) { this.levels.setExpiryTime(expiryTime); // remove this in sub-class to use level-specific expiry times + } } - public double getMaxElevation() - { + public double getMaxElevation() { return this.maxElevation; } - public double getMinElevation() - { + public double getMinElevation() { return this.minElevation; } - public double getBestResolution(Sector sector) - { - if (sector == null) + public double getBestResolution(Sector sector) { + if (sector == null) { return this.levels.getLastLevel().getTexelSize(); + } Level level = this.levels.getLastLevel(sector); return level != null ? level.getTexelSize() : Double.MAX_VALUE; } - public double getDetailHint(Sector sector) - { + public double getDetailHint(Sector sector) { return this.detailHint; } - public void setDetailHint(double hint) - { + public void setDetailHint(double hint) { this.detailHint = hint; } - public String getElevationDataType() - { + public String getElevationDataType() { return this.elevationDataType; } - public void setElevationDataType(String dataType) - { - if (dataType == null) - { + public void setElevationDataType(String dataType) { + if (dataType == null) { String message = Logging.getMessage("nullValue.DataTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -317,15 +305,12 @@ public void setElevationDataType(String dataType) this.elevationDataType = dataType; } - public String getElevationDataByteOrder() - { + public String getElevationDataByteOrder() { return this.elevationDataByteOrder; } - public void setByteOrder(String byteOrder) - { - if (byteOrder == null) - { + public void setByteOrder(String byteOrder) { + if (byteOrder == null) { String message = Logging.getMessage("nullValue.ByteOrderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -334,18 +319,16 @@ public void setByteOrder(String byteOrder) this.elevationDataByteOrder = byteOrder; } - public int intersects(Sector sector) - { - if (this.levels.getSector().contains(sector)) + public int intersects(Sector sector) { + if (this.levels.getSector().contains(sector)) { return 0; + } return this.levels.getSector().intersects(sector) ? 1 : -1; } - public boolean contains(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public boolean contains(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -355,14 +338,12 @@ public boolean contains(Angle latitude, Angle longitude) } @Override - public void setExtremesCachingEnabled(boolean enabled) - { + public void setExtremesCachingEnabled(boolean enabled) { this.extremesCachingEnabled = enabled; } @Override - public boolean isExtremesCachingEnabled() - { + public boolean isExtremesCachingEnabled() { return this.extremesCachingEnabled; } //**************************************************************// @@ -370,9 +351,7 @@ public boolean isExtremesCachingEnabled() //**************************************************************// // Create the tile corresponding to a specified key. - - protected ElevationTile createTile(TileKey key) - { + protected ElevationTile createTile(TileKey key) { Level level = this.levels.getLevel(key.getLevelNumber()); // Compute the tile's SW lat/lon based on its row/col in the level's data set. @@ -391,54 +370,48 @@ protected ElevationTile createTile(TileKey key) // Thread off a task to determine whether the file is local or remote and then retrieve it either from the file // cache or a remote server. - - protected void requestTile(TileKey key) - { - if (WorldWind.getTaskService().isFull()) + protected void requestTile(TileKey key) { + if (WorldWind.getTaskService().isFull()) { return; + } - if (this.getLevels().isResourceAbsent(key)) + if (this.getLevels().isResourceAbsent(key)) { return; + } RequestTask request = new RequestTask(key, this); WorldWind.getTaskService().addTask(request); } - protected static class RequestTask implements Runnable - { + protected static class RequestTask implements Runnable { + protected final BasicElevationModel elevationModel; protected final TileKey tileKey; - protected RequestTask(TileKey tileKey, BasicElevationModel elevationModel) - { + protected RequestTask(TileKey tileKey, BasicElevationModel elevationModel) { this.elevationModel = elevationModel; this.tileKey = tileKey; } - public final void run() - { - if (Thread.currentThread().isInterrupted()) + public final void run() { + if (Thread.currentThread().isInterrupted()) { return; // the task was cancelled because it's a duplicate or for some other reason - - try - { + } + try { // check to ensure load is still needed - if (this.elevationModel.areElevationsInMemory(this.tileKey)) + if (this.elevationModel.areElevationsInMemory(this.tileKey)) { return; + } ElevationTile tile = this.elevationModel.createTile(this.tileKey); final URL url = this.elevationModel.getDataFileStore().findFile(tile.getPath(), false); if (url != null && !this.elevationModel.isFileExpired(tile, url, - this.elevationModel.getDataFileStore())) - { - if (this.elevationModel.loadElevations(tile, url)) - { + this.elevationModel.getDataFileStore())) { + if (this.elevationModel.loadElevations(tile, url)) { this.elevationModel.levels.unmarkResourceAbsent(tile); this.elevationModel.firePropertyChange(AVKey.ELEVATION_MODEL, null, this); return; - } - else - { + } else { // Assume that something's wrong with the file and delete it. this.elevationModel.getDataFileStore().removeFile(url); this.elevationModel.levels.markResourceAbsent(tile); @@ -448,46 +421,44 @@ public final void run() } this.elevationModel.downloadElevations(tile); - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("ElevationModel.ExceptionRequestingElevations", - this.tileKey.toString()); + this.tileKey.toString()); Logging.logger().log(java.util.logging.Level.FINE, msg, e); } } - public final boolean equals(Object o) - { - if (this == o) + public final boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final RequestTask that = (RequestTask) o; //noinspection RedundantIfStatement - if (this.tileKey != null ? !this.tileKey.equals(that.tileKey) : that.tileKey != null) + if (this.tileKey != null ? !this.tileKey.equals(that.tileKey) : that.tileKey != null) { return false; + } return true; } - public final int hashCode() - { + public final int hashCode() { return (this.tileKey != null ? this.tileKey.hashCode() : 0); } - public final String toString() - { + public final String toString() { return this.tileKey.toString(); } } - protected boolean isFileExpired(Tile tile, java.net.URL fileURL, FileStore fileStore) - { - if (!WWIO.isFileOutOfDate(fileURL, tile.getLevel().getExpiryTime())) + protected boolean isFileExpired(Tile tile, java.net.URL fileURL, FileStore fileStore) { + if (!WWIO.isFileOutOfDate(fileURL, tile.getLevel().getExpiryTime())) { return false; + } // The file has expired. Delete it. fileStore.removeFile(fileURL); @@ -497,12 +468,11 @@ protected boolean isFileExpired(Tile tile, java.net.URL fileURL, FileStore fileS } // Reads a tile's elevations from the file cache and adds the tile to the memory cache. - - protected boolean loadElevations(ElevationTile tile, java.net.URL url) throws Exception - { + protected boolean loadElevations(ElevationTile tile, java.net.URL url) throws Exception { BufferWrapper elevations = this.readElevations(url); - if (elevations == null || elevations.length() == 0) + if (elevations == null || elevations.length() == 0) { return false; + } tile.setElevations(elevations, this); this.addTileToCache(tile, elevations); @@ -510,17 +480,16 @@ protected boolean loadElevations(ElevationTile tile, java.net.URL url) throws Ex return true; } - protected void addTileToCache(ElevationTile tile, BufferWrapper elevations) - { + protected void addTileToCache(ElevationTile tile, BufferWrapper elevations) { // Level 0 tiles are held in the model itself; other levels are placed in the memory cache. - if (tile.getLevelNumber() == 0) + if (tile.getLevelNumber() == 0) { this.levelZeroTiles.put(tile.getTileKey(), tile); - else + } else { this.getMemoryCache().add(tile.getTileKey(), tile, elevations.getSizeInBytes()); + } } - protected boolean areElevationsInMemory(TileKey key) - { + protected boolean areElevationsInMemory(TileKey key) { // An elevation tile is considered to be in memory if it: // * Exists in the memory cache. // * Has non-null elevation data. @@ -529,39 +498,33 @@ protected boolean areElevationsInMemory(TileKey key) return (tile != null && tile.getElevations() != null && !tile.isElevationsExpired()); } - protected ElevationTile getTileFromMemory(TileKey tileKey) - { - if (tileKey.getLevelNumber() == 0) + protected ElevationTile getTileFromMemory(TileKey tileKey) { + if (tileKey.getLevelNumber() == 0) { return this.levelZeroTiles.get(tileKey); - else + } else { return (ElevationTile) this.getMemoryCache().getObject(tileKey); + } } // Read elevations from the file cache. Don't be confused by the use of a URL here: it's used so that files can // be read using System.getResource(URL), which will draw the data from a jar file in the classpath. - - protected BufferWrapper readElevations(URL url) throws Exception - { - try - { - if (url.getPath().endsWith("tif")) + protected BufferWrapper readElevations(URL url) throws Exception { + try { + if (url.getPath().endsWith("tif")) { return this.makeTiffElevations(url); - else + } else { return this.makeBilElevations(url); - } - catch (Exception e) - { + } + } catch (Exception e) { Logging.logger().log(java.util.logging.Level.SEVERE, - "ElevationModel.ExceptionReadingElevationFile", url.toString()); + "ElevationModel.ExceptionReadingElevationFile", url.toString()); throw e; } } - protected BufferWrapper makeBilElevations(URL url) throws IOException - { + protected BufferWrapper makeBilElevations(URL url) throws IOException { ByteBuffer byteBuffer; - synchronized (this.fileLock) - { + synchronized (this.fileLock) { byteBuffer = WWIO.readURLContentToBuffer(url); } @@ -572,16 +535,14 @@ protected BufferWrapper makeBilElevations(URL url) throws IOException return BufferWrapper.wrap(byteBuffer, bufferParams); } - protected BufferWrapper makeTiffElevations(URL url) throws IOException, URISyntaxException - { + protected BufferWrapper makeTiffElevations(URL url) throws IOException, URISyntaxException { File file = new File(url.toURI()); // Create a raster reader for the file type. DataRasterReaderFactory readerFactory = (DataRasterReaderFactory) WorldWind.createConfigurationComponent( - AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); + AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); DataRasterReader reader = readerFactory.findReaderFor(file, null); - if (reader == null) - { + if (reader == null) { String msg = Logging.getMessage("generic.UnknownFileFormatOrMatchingReaderNotFound", file.getPath()); Logging.logger().severe(msg); throw new WWRuntimeException(msg); @@ -589,13 +550,11 @@ protected BufferWrapper makeTiffElevations(URL url) throws IOException, URISynta // Read the file into the raster. DataRaster[] rasters; - synchronized (this.fileLock) - { + synchronized (this.fileLock) { rasters = reader.read(file, null); } - if (rasters == null || rasters.length == 0) - { + if (rasters == null || rasters.length == 0) { String msg = Logging.getMessage("ElevationModel.CannotReadElevations", file.getAbsolutePath()); Logging.logger().severe(msg); throw new WWRuntimeException(msg); @@ -611,8 +570,7 @@ protected BufferWrapper makeTiffElevations(URL url) throws IOException, URISynta // Determine the sector covered by the elevations. This information is in the GeoTIFF file or auxiliary // files associated with the elevations file. final Sector sector = (Sector) raster.getValue(AVKey.SECTOR); - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("DataRaster.MissingMetadata", AVKey.SECTOR); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -621,8 +579,7 @@ protected BufferWrapper makeTiffElevations(URL url) throws IOException, URISynta DataRaster subRaster = raster.getSubRaster(width, height, sector, raster); // Verify that the sub-raster can create a ByteBuffer, then create one. - if (!(subRaster instanceof ByteBufferRaster)) - { + if (!(subRaster instanceof ByteBufferRaster)) { String msg = Logging.getMessage("ElevationModel.CannotCreateElevationBuffer", file.getPath()); Logging.logger().severe(msg); throw new WWRuntimeException(msg); @@ -637,8 +594,7 @@ protected BufferWrapper makeTiffElevations(URL url) throws IOException, URISynta bufferParams.setValues(raster.copy()); // copies params from avlist String dataType = bufferParams.getStringValue(AVKey.DATA_TYPE); - if (WWUtil.isEmpty(dataType)) - { + if (WWUtil.isEmpty(dataType)) { String msg = Logging.getMessage("DataRaster.MissingMetadata", AVKey.DATA_TYPE); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -652,11 +608,9 @@ protected BufferWrapper makeTiffElevations(URL url) throws IOException, URISynta return bufferWrapper; } - protected static ByteBuffer convertImageToElevations(ByteBuffer buffer, String contentType) throws IOException - { + protected static ByteBuffer convertImageToElevations(ByteBuffer buffer, String contentType) throws IOException { File tempFile = File.createTempFile("wwj-", WWIO.makeSuffixForMimeType(contentType)); - try - { + try { WWIO.saveBuffer(buffer, tempFile); BufferedImage image = ImageIO.read(tempFile); ByteBuffer byteBuffer = Buffers.newDirectByteBuffer(image.getWidth() * image.getHeight() * 2); @@ -666,25 +620,22 @@ protected static ByteBuffer convertImageToElevations(ByteBuffer buffer, String c WritableRaster raster = image.getRaster(); int[] samples = new int[raster.getWidth() * raster.getHeight()]; raster.getSamples(0, 0, raster.getWidth(), raster.getHeight(), 0, samples); - for (int sample : samples) - { + for (int sample : samples) { bilBuffer.put((short) sample); } return byteBuffer; - } - finally - { - if (tempFile != null) - //noinspection ResultOfMethodCallIgnored + } finally { + if (tempFile != null) //noinspection ResultOfMethodCallIgnored + { tempFile.delete(); + } } } // *** Bulk download *** // *** Bulk download *** // *** Bulk download *** - /** * Start a new {@link BulkRetrievalThread} that downloads all elevations for a given sector and resolution to the * current WorldWind file cache, without downloading imagery already in the cache. @@ -695,18 +646,17 @@ protected static ByteBuffer convertImageToElevations(ByteBuffer buffer, String c * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to download data for. + * @param sector the sector to download data for. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param listener an optional retrieval listener. May be null. + * @param listener an optional retrieval listener. May be null. * * @return the {@link BulkRetrievalThread} executing the retrieval or null if the specified sector does * not intersect the elevation model bounding sector. * - * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. + * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. * @see BasicElevationModelBulkDownloader */ - public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetrievalListener listener) - { + public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetrievalListener listener) { return this.makeLocal(sector, resolution, null, listener); } @@ -720,29 +670,29 @@ public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetri * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to download data for. + * @param sector the sector to download data for. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param fileStore the file store in which to place the downloaded elevations. If null the current WorldWind file - * cache is used. - * @param listener an optional retrieval listener. May be null. + * @param fileStore the file store in which to place the downloaded elevations. If null the current WorldWind file + * cache is used. + * @param listener an optional retrieval listener. May be null. * * @return the {@link BulkRetrievalThread} executing the retrieval or null if the specified sector does * not intersect the elevation model bounding sector. * - * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. + * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. * @see BasicElevationModelBulkDownloader */ public BulkRetrievalThread makeLocal(Sector sector, double resolution, FileStore fileStore, - BulkRetrievalListener listener) - { + BulkRetrievalListener listener) { Sector targetSector = sector != null ? getLevels().getSector().intersection(sector) : null; - if (targetSector == null) + if (targetSector == null) { return null; + } // Args checked in downloader constructor - BasicElevationModelBulkDownloader thread = - new BasicElevationModelBulkDownloader(this, targetSector, resolution, - fileStore != null ? fileStore : this.getDataFileStore(), listener); + BasicElevationModelBulkDownloader thread + = new BasicElevationModelBulkDownloader(this, targetSector, resolution, + fileStore != null ? fileStore : this.getDataFileStore(), listener); thread.setDaemon(true); thread.start(); return thread; @@ -755,15 +705,14 @@ public BulkRetrievalThread makeLocal(Sector sector, double resolution, FileStore * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to estimate. + * @param sector the sector to estimate. * @param resolution the target resolution, provided in radians of latitude per texel. * * @return the estimated size in bytes of the missing elevations. * * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. */ - public long getEstimatedMissingDataSize(Sector sector, double resolution) - { + public long getEstimatedMissingDataSize(Sector sector, double resolution) { return this.getEstimatedMissingDataSize(sector, resolution, null); } @@ -774,24 +723,24 @@ public long getEstimatedMissingDataSize(Sector sector, double resolution) * Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in * meters divided by the globe radius. * - * @param sector the sector to estimate. + * @param sector the sector to estimate. * @param resolution the target resolution, provided in radians of latitude per texel. - * @param fileStore the file store to examine. If null the current WorldWind file cache is used. + * @param fileStore the file store to examine. If null the current WorldWind file cache is used. * * @return the estimated size in bytes of the missing elevations. * * @throws IllegalArgumentException if the sector is null or the resolution is less than zero. */ - public long getEstimatedMissingDataSize(Sector sector, double resolution, FileStore fileStore) - { + public long getEstimatedMissingDataSize(Sector sector, double resolution, FileStore fileStore) { Sector targetSector = sector != null ? getLevels().getSector().intersection(sector) : null; - if (targetSector == null) + if (targetSector == null) { return 0; + } // Args checked by downloader constructor // Need a downloader to compute the missing data size. BasicElevationModelBulkDownloader downloader = new BasicElevationModelBulkDownloader(this, targetSector, - resolution, fileStore != null ? fileStore : this.getDataFileStore(), null); + resolution, fileStore != null ? fileStore : this.getDataFileStore(), null); return downloader.getEstimatedMissingDataSize(); } @@ -799,34 +748,32 @@ public long getEstimatedMissingDataSize(Sector sector, double resolution, FileSt // *** Tile download *** // *** Tile download *** // *** Tile download *** - - protected void downloadElevations(final Tile tile) - { + protected void downloadElevations(final Tile tile) { retrieveElevations(tile, new DownloadPostProcessor(tile, this)); } - protected void downloadElevations(final Tile tile, DownloadPostProcessor postProcessor) - { + protected void downloadElevations(final Tile tile, DownloadPostProcessor postProcessor) { retrieveElevations(tile, postProcessor); } - protected void retrieveElevations(final Tile tile, DownloadPostProcessor postProcessor) - { - if (this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL) != null) + protected void retrieveElevations(final Tile tile, DownloadPostProcessor postProcessor) { + if (this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL) != null) { this.retrieveLocalElevations(tile, postProcessor); - else - // Assume it's remote, which handles the legacy cases. + } else // Assume it's remote, which handles the legacy cases. + { this.retrieveRemoteElevations(tile, postProcessor); + } } - protected void retrieveLocalElevations(Tile tile, DownloadPostProcessor postProcessor) - { - if (!WorldWind.getLocalRetrievalService().isAvailable()) + protected void retrieveLocalElevations(Tile tile, DownloadPostProcessor postProcessor) { + if (!WorldWind.getLocalRetrievalService().isAvailable()) { return; + } RetrieverFactory retrieverFactory = (RetrieverFactory) this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL); - if (retrieverFactory == null) + if (retrieverFactory == null) { return; + } AVListImpl avList = new AVListImpl(); avList.setValue(AVKey.SECTOR, tile.getSector()); @@ -839,57 +786,52 @@ protected void retrieveLocalElevations(Tile tile, DownloadPostProcessor postProc WorldWind.getLocalRetrievalService().runRetriever(retriever, tile.getPriority()); } - protected void retrieveRemoteElevations(final Tile tile, DownloadPostProcessor postProcessor) - { - if (!this.isNetworkRetrievalEnabled()) - { + protected void retrieveRemoteElevations(final Tile tile, DownloadPostProcessor postProcessor) { + if (!this.isNetworkRetrievalEnabled()) { this.getLevels().markResourceAbsent(tile); return; } - if (!WorldWind.getRetrievalService().isAvailable()) + if (!WorldWind.getRetrievalService().isAvailable()) { return; + } java.net.URL url = null; - try - { + try { url = tile.getResourceURL(); - if (WorldWind.getNetworkStatus().isHostUnavailable(url)) - { + if (WorldWind.getNetworkStatus().isHostUnavailable(url)) { this.getLevels().markResourceAbsent(tile); return; } - } - catch (java.net.MalformedURLException e) - { + } catch (java.net.MalformedURLException e) { Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("TiledElevationModel.ExceptionCreatingElevationsUrl", url), e); + Logging.getMessage("TiledElevationModel.ExceptionCreatingElevationsUrl", url), e); return; } - if (postProcessor == null) + if (postProcessor == null) { postProcessor = new DownloadPostProcessor(tile, this); + } URLRetriever retriever = new HTTPRetriever(url, postProcessor); retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy elevation models - if (WorldWind.getRetrievalService().contains(retriever)) + if (WorldWind.getRetrievalService().contains(retriever)) { return; + } WorldWind.getRetrievalService().runRetriever(retriever, 0d); } - protected static class DownloadPostProcessor extends AbstractRetrievalPostProcessor - { + protected static class DownloadPostProcessor extends AbstractRetrievalPostProcessor { + protected final Tile tile; protected final BasicElevationModel elevationModel; protected final FileStore fileStore; - public DownloadPostProcessor(Tile tile, BasicElevationModel em) - { + public DownloadPostProcessor(Tile tile, BasicElevationModel em) { this(tile, em, null); } - public DownloadPostProcessor(Tile tile, BasicElevationModel em, FileStore fileStore) - { + public DownloadPostProcessor(Tile tile, BasicElevationModel em, FileStore fileStore) { //noinspection RedundantCast super((AVList) em); @@ -898,42 +840,35 @@ public DownloadPostProcessor(Tile tile, BasicElevationModel em, FileStore fileSt this.fileStore = fileStore; } - protected FileStore getFileStore() - { + protected FileStore getFileStore() { return this.fileStore != null ? this.fileStore : this.elevationModel.getDataFileStore(); } @Override - protected boolean overwriteExistingFile() - { + protected boolean overwriteExistingFile() { return true; } @Override - protected void markResourceAbsent() - { + protected void markResourceAbsent() { this.elevationModel.getLevels().markResourceAbsent(this.tile); } @Override - protected Object getFileLock() - { + protected Object getFileLock() { return this.elevationModel.fileLock; } @Override - protected File doGetOutputFile() - { + protected File doGetOutputFile() { return this.getFileStore().newFile(this.tile.getPath()); } @Override - protected ByteBuffer handleSuccessfulRetrieval() - { + protected ByteBuffer handleSuccessfulRetrieval() { ByteBuffer buffer = super.handleSuccessfulRetrieval(); - if (buffer != null) - { + if (buffer != null) { // We've successfully cached data. Check whether there's a configuration file for this elevation model // in the cache and create one if there isn't. this.elevationModel.writeConfigurationFile(this.getFileStore()); @@ -946,8 +881,7 @@ protected ByteBuffer handleSuccessfulRetrieval() } @Override - protected ByteBuffer handleTextContent() throws IOException - { + protected ByteBuffer handleTextContent() throws IOException { this.markResourceAbsent(); return super.handleTextContent(); @@ -994,68 +928,65 @@ protected ByteBuffer handleTextContent() throws IOException // } } - /** Internal class to hold collections of elevation tiles that provide elevations for a specific sector. */ - protected static class Elevations - { + /** + * Internal class to hold collections of elevation tiles that provide elevations for a specific sector. + */ + protected static class Elevations { + protected final BasicElevationModel elevationModel; protected java.util.Set tiles; protected double extremes[] = null; protected final double achievedResolution; - protected Elevations(BasicElevationModel elevationModel, double achievedResolution) - { + protected Elevations(BasicElevationModel elevationModel, double achievedResolution) { this.elevationModel = elevationModel; this.achievedResolution = achievedResolution; } - protected Double getElevation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + protected Double getElevation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.tiles == null) + if (this.tiles == null) { return null; + } - try - { - for (ElevationTile tile : this.tiles) - { - if (tile.getSector().contains(latitude, longitude)) + try { + for (ElevationTile tile : this.tiles) { + if (tile.getSector().contains(latitude, longitude)) { return this.elevationModel.lookupElevation(latitude, longitude, tile); + } } // Location is not within this group of tiles, so is outside the coverage of this elevation model. return null; - } - catch (Exception e) - { + } catch (Exception e) { // Throwing an exception within what's likely to be the caller's geometry creation loop // would be hard to recover from, and a reasonable response to the exception can be done here. Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("BasicElevationModel.ExceptionComputingElevation", latitude, longitude), e); + Logging.getMessage("BasicElevationModel.ExceptionComputingElevation", latitude, longitude), e); return null; } } - protected double[] getExtremes(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + protected double[] getExtremes(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.extremes != null) + if (this.extremes != null) { return this.extremes; + } - if (this.tiles == null || tiles.size() == 0) + if (this.tiles == null || tiles.size() == 0) { return this.elevationModel.getExtremeElevations(latitude, longitude); + } return this.getExtremes(); } @@ -1065,48 +996,48 @@ protected double[] getExtremes(Angle latitude, Angle longitude) * * @return the extreme elevation values. */ - protected double[] getExtremes() - { - if (this.extremes != null) + protected double[] getExtremes() { + if (this.extremes != null) { return this.extremes; + } - if (this.tiles == null || tiles.size() == 0) - return this.extremes = new double[] {this.elevationModel.getMinElevation(), + if (this.tiles == null || tiles.size() == 0) { + return this.extremes = new double[]{this.elevationModel.getMinElevation(), this.elevationModel.getMaxElevation()}; + } this.extremes = WWUtil.defaultMinMix(); - for (ElevationTile tile : this.tiles) - { + for (ElevationTile tile : this.tiles) { BufferWrapper elevations = tile.getElevations(); int len = elevations.length(); - if (len == 0) + if (len == 0) { return null; + } - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { this.elevationModel.determineExtremes(elevations.getDouble(i), this.extremes); } } - return new double[] {this.extremes[0], this.extremes[1]}; // return a defensive copy + return new double[]{this.extremes[0], this.extremes[1]}; // return a defensive copy } - protected double[] getExtremes(Sector sector) - { - if (this.extremes != null) + protected double[] getExtremes(Sector sector) { + if (this.extremes != null) { return this.extremes; + } Iterator iter = this.tiles.iterator(); - if (!iter.hasNext()) - return this.extremes = new double[] {this.elevationModel.getMinElevation(), + if (!iter.hasNext()) { + return this.extremes = new double[]{this.elevationModel.getMinElevation(), this.elevationModel.getMaxElevation()}; + } this.extremes = WWUtil.defaultMinMix(); - for (ElevationTile tile : this.tiles) - { + for (ElevationTile tile : this.tiles) { tile.getExtremes(sector, this.elevationModel, this.extremes); } @@ -1118,82 +1049,85 @@ protected double[] getExtremes(Sector sector) * * @return the extreme values. */ - protected double[] getTileExtremes() - { - if (this.extremes != null) + protected double[] getTileExtremes() { + if (this.extremes != null) { return this.extremes; + } Iterator iter = this.tiles.iterator(); - if (!iter.hasNext()) - return this.extremes = new double[] {this.elevationModel.getMinElevation(), + if (!iter.hasNext()) { + return this.extremes = new double[]{this.elevationModel.getMinElevation(), this.elevationModel.getMaxElevation()}; + } this.extremes = WWUtil.defaultMinMix(); - for (ElevationTile tile : this.tiles) - { + for (ElevationTile tile : this.tiles) { // This computes the extremes on a tile granularity rather than an elevation-value cell granularity. // The latter is very expensive. - if (tile.extremes[0] < this.extremes[0]) + if (tile.extremes[0] < this.extremes[0]) { this.extremes[0] = tile.extremes[0]; - if (tile.extremes[1] > this.extremes[1]) + } + if (tile.extremes[1] > this.extremes[1]) { this.extremes[1] = tile.extremes[1]; + } } return this.extremes; } } - protected void determineExtremes(double value, double extremes[]) - { - if (value == this.getMissingDataSignal()) + protected void determineExtremes(double value, double extremes[]) { + if (value == this.getMissingDataSignal()) { value = this.getMissingDataReplacement(); + } - if (value < extremes[0]) + if (value < extremes[0]) { extremes[0] = value; + } - if (value > extremes[1]) + if (value > extremes[1]) { extremes[1] = value; + } } - public double getUnmappedElevation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getUnmappedElevation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.contains(latitude, longitude)) + if (!this.contains(latitude, longitude)) { return this.getMissingDataSignal(); + } Level lastLevel = this.levels.getLastLevel(latitude, longitude); final TileKey tileKey = new TileKey(latitude, longitude, this.levels, lastLevel.getLevelNumber()); ElevationTile tile = this.getTileFromMemory(tileKey); - if (tile == null) - { + if (tile == null) { int fallbackRow = tileKey.getRow(); int fallbackCol = tileKey.getColumn(); - for (int fallbackLevelNum = tileKey.getLevelNumber() - 1; fallbackLevelNum >= 0; fallbackLevelNum--) - { + for (int fallbackLevelNum = tileKey.getLevelNumber() - 1; fallbackLevelNum >= 0; fallbackLevelNum--) { fallbackRow /= 2; fallbackCol /= 2; if (this.levels.getLevel(fallbackLevelNum).isEmpty()) // everything lower res is empty + { return this.getExtremeElevations(latitude, longitude)[0]; + } TileKey fallbackKey = new TileKey(fallbackLevelNum, fallbackRow, fallbackCol, - this.levels.getLevel(fallbackLevelNum).getCacheName()); + this.levels.getLevel(fallbackLevelNum).getCacheName()); tile = this.getTileFromMemory(fallbackKey); - if (tile != null) + if (tile != null) { break; + } } } - if (tile == null && !this.levels.getFirstLevel().isEmpty()) - { + if (tile == null && !this.levels.getFirstLevel().isEmpty()) { // Request the level-zero tile since it's not in memory Level firstLevel = this.levels.getFirstLevel(); final TileKey zeroKey = new TileKey(latitude, longitude, this.levels, firstLevel.getLevelNumber()); @@ -1207,54 +1141,48 @@ public double getUnmappedElevation(Angle latitude, Angle longitude) // time has been set for the elevation model. If none has been set, the expiry times of the model's individual // levels are used, but only for tiles in the local file cache, not tiles in memory. This is to avoid incurring // the overhead of checking expiration of in-memory tiles, a very rarely used feature. - if (this.getExpiryTime() > 0 && this.getExpiryTime() < System.currentTimeMillis()) - { + if (this.getExpiryTime() > 0 && this.getExpiryTime() < System.currentTimeMillis()) { // Normally getUnmappedElevations() does not request elevation tiles, except for first level tiles. However // if the tile is already in memory but has expired, we must issue a request to replace the tile data. This // will not fetch new tiles into the cache, but rather will force a refresh of the expired tile's resources // in the file cache and the memory cache. - if (tile != null) + if (tile != null) { this.checkElevationExpiration(tile); + } } // The containing tile is non-null, so look up the elevation and return. return this.lookupElevation(latitude, longitude, tile); } - public double getUnmappedLocalSourceElevation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getUnmappedLocalSourceElevation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.contains(latitude, longitude)) + if (!this.contains(latitude, longitude)) { return this.getMissingDataSignal(); + } Level lastLevel = this.levels.getLastLevel(latitude, longitude); final TileKey tileKey = new TileKey(latitude, longitude, this.levels, lastLevel.getLevelNumber()); ElevationTile tile = this.getTileFromMemory(tileKey); - if (tile != null) - { + if (tile != null) { return this.lookupElevation(latitude, longitude, tile); } - try - { + try { tile = this.createTile(tileKey); final URL url = this.getDataFileStore().findFile(tile.getPath(), false); - if (url != null) - { + if (url != null) { this.loadElevations(tile, url); } - } - catch (Exception e) - { + } catch (Exception e) { String msg = Logging.getMessage("ElevationModel.ExceptionRequestingElevations", - tileKey.toString()); + tileKey.toString()); Logging.logger().log(java.util.logging.Level.FINE, msg, e); } @@ -1262,114 +1190,111 @@ public double getUnmappedLocalSourceElevation(Angle latitude, Angle longitude) return tile != null ? this.lookupElevation(latitude, longitude, tile) : this.getMissingDataSignal(); } - public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) - { + public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) { return this.getElevations(sector, latlons, targetResolution, buffer, true); } public double getUnmappedElevations(Sector sector, List latlons, double targetResolution, - double[] buffer) - { + double[] buffer) { return this.getElevations(sector, latlons, targetResolution, buffer, false); } protected double getElevations(Sector sector, List latlons, double targetResolution, - double[] buffer, boolean mapMissingData) - { - if (sector == null) - { + double[] buffer, boolean mapMissingData) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (latlons == null) - { + if (latlons == null) { String msg = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer == null) - { + if (buffer == null) { String msg = Logging.getMessage("nullValue.ElevationsBufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer.length < latlons.size()) - { + if (buffer.length < latlons.size()) { String msg = Logging.getMessage("ElevationModel.ElevationsBufferTooSmall", latlons.size()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.getTargetLevel(sector, targetResolution); - if (targetLevel == null) + if (targetLevel == null) { return Double.MAX_VALUE; + } Elevations elevations = this.getElevations(sector, this.levels, targetLevel.getLevelNumber()); - if (elevations == null) + if (elevations == null) { return Double.MAX_VALUE; + } - if (this.intersects(sector) == -1) + if (this.intersects(sector) == -1) { return Double.MAX_VALUE; + } // Mark the model as used this frame. this.setValue(AVKey.FRAME_TIMESTAMP, System.currentTimeMillis()); - for (int i = 0; i < latlons.size(); i++) - { + for (int i = 0; i < latlons.size(); i++) { LatLon ll = latlons.get(i); - if (ll == null) + if (ll == null) { continue; + } Double value = elevations.getElevation(ll.getLatitude(), ll.getLongitude()); - if (this.isTransparentValue(value)) + if (this.isTransparentValue(value)) { continue; + } // If an elevation at the given location is available, write that elevation to the destination buffer. // If an elevation is not available but the location is within the elevation model's coverage, write the // elevation models extreme elevation at the location. Do nothing if the location is not within the // elevation model's coverage. - if (value != null && value != this.getMissingDataSignal()) + if (value != null && value != this.getMissingDataSignal()) { buffer[i] = value; - else if (this.contains(ll.getLatitude(), ll.getLongitude())) - { - if (value == null) + } else if (this.contains(ll.getLatitude(), ll.getLongitude())) { + if (value == null) { buffer[i] = this.getExtremeElevations(sector)[0]; - else if (mapMissingData && value == this.getMissingDataSignal()) + } else if (mapMissingData && value == this.getMissingDataSignal()) { buffer[i] = this.getMissingDataReplacement(); + } } } return elevations.achievedResolution; } - protected Level getTargetLevel(Sector sector, double targetSize) - { + protected Level getTargetLevel(Sector sector, double targetSize) { Level lastLevel = this.levels.getLastLevel(sector); // finest resolution available - if (lastLevel == null) + if (lastLevel == null) { return null; + } - if (lastLevel.getTexelSize() >= targetSize) + if (lastLevel.getTexelSize() >= targetSize) { return lastLevel; // can't do any better than this - - for (Level level : this.levels.getLevels()) - { - if (level.getTexelSize() <= targetSize) + } + for (Level level : this.levels.getLevels()) { + if (level.getTexelSize() <= targetSize) { return !level.isEmpty() ? level : null; + } - if (level == lastLevel) + if (level == lastLevel) { break; + } } return lastLevel; } - protected double lookupElevation(Angle latitude, Angle longitude, final ElevationTile tile) - { + protected double lookupElevation(Angle latitude, Angle longitude, final ElevationTile tile) { BufferWrapper elevations = tile.getElevations(); Sector sector = tile.getSector(); final int tileHeight = tile.getHeight(); @@ -1388,8 +1313,9 @@ protected double lookupElevation(Angle latitude, Angle longitude, final Elevatio double eLeft = elevations.getDouble(k); double eRight = i < (tileWidth - 1) ? elevations.getDouble(k + 1) : eLeft; - if (this.getMissingDataSignal() == eLeft || this.getMissingDataSignal() == eRight) + if (this.getMissingDataSignal() == eLeft || this.getMissingDataSignal() == eRight) { return this.getMissingDataSignal(); + } double dw = sectorDeltaLon / (tileWidth - 1); double dh = sectorDeltaLat / (tileHeight - 1); @@ -1398,33 +1324,31 @@ protected double lookupElevation(Angle latitude, Angle longitude, final Elevatio double eTop = eLeft + ssLon * (eRight - eLeft); - if (j < tileHeight - 1 && i < tileWidth - 1) - { + if (j < tileHeight - 1 && i < tileWidth - 1) { eLeft = elevations.getDouble(k + tileWidth); eRight = elevations.getDouble(k + tileWidth + 1); - if (this.getMissingDataSignal() == eLeft || this.getMissingDataSignal() == eRight) + if (this.getMissingDataSignal() == eLeft || this.getMissingDataSignal() == eRight) { return this.getMissingDataSignal(); + } } double eBot = eLeft + ssLon * (eRight - eLeft); return eTop + ssLat * (eBot - eTop); } - public double[] getExtremeElevations(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double[] getExtremeElevations(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.extremesLevel < 0 || this.extremes == null) - return new double[] {this.getMinElevation(), this.getMaxElevation()}; + if (this.extremesLevel < 0 || this.extremes == null) { + return new double[]{this.getMinElevation(), this.getMaxElevation()}; + } - try - { + try { LatLon delta = this.levels.getLevel(this.extremesLevel).getTileDelta(); LatLon origin = this.levels.getTileOrigin(); final int row = ElevationTile.computeRow(delta.getLatitude(), latitude, origin.getLatitude()); @@ -1436,94 +1360,88 @@ public double[] getExtremeElevations(Angle latitude, Angle longitude) double min = this.extremes.getDouble(index); double max = this.extremes.getDouble(index + 1); - if (min == this.getMissingDataSignal()) + if (min == this.getMissingDataSignal()) { min = this.getMissingDataReplacement(); - if (max == this.getMissingDataSignal()) + } + if (max == this.getMissingDataSignal()) { max = this.getMissingDataReplacement(); + } - return new double[] {min, max}; - } - catch (Exception e) - { + return new double[]{min, max}; + } catch (Exception e) { String message = Logging.getMessage("BasicElevationModel.ExceptionDeterminingExtremes", - new LatLon(latitude, longitude)); + new LatLon(latitude, longitude)); Logging.logger().log(java.util.logging.Level.WARNING, message, e); - return new double[] {this.getMinElevation(), this.getMaxElevation()}; + return new double[]{this.getMinElevation(), this.getMaxElevation()}; } } - public double[] getExtremeElevations(Sector sector) - { - if (sector == null) - { + public double[] getExtremeElevations(Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { double[] extremes = this.extremesCachingEnabled - ? (double[]) this.getExtremesLookupCache().getObject(sector) : null; - if (extremes != null) - return new double[] {extremes[0], extremes[1]}; // return defensive copy - - if (this.extremesLevel < 0 || this.extremes == null) - return new double[] {this.getMinElevation(), this.getMaxElevation()}; + ? (double[]) this.getExtremesLookupCache().getObject(sector) : null; + if (extremes != null) { + return new double[]{extremes[0], extremes[1]}; // return defensive copy + } + if (this.extremesLevel < 0 || this.extremes == null) { + return new double[]{this.getMinElevation(), this.getMaxElevation()}; + } // Compute the extremes from the extreme-elevations file. extremes = this.computeExtremeElevations(sector); - if (extremes != null && this.isExtremesCachingEnabled()) + if (extremes != null && this.isExtremesCachingEnabled()) { this.getExtremesLookupCache().add(sector, extremes, 64); + } // Return a defensive copy of the array to prevent the caller from modifying the cache contents. - return extremes != null ? new double[] {extremes[0], extremes[1]} : null; - } - catch (Exception e) - { + return extremes != null ? new double[]{extremes[0], extremes[1]} : null; + } catch (Exception e) { String message = Logging.getMessage("BasicElevationModel.ExceptionDeterminingExtremes", sector); Logging.logger().log(java.util.logging.Level.WARNING, message, e); - return new double[] {this.getMinElevation(), this.getMaxElevation()}; + return new double[]{this.getMinElevation(), this.getMaxElevation()}; } } - public void loadExtremeElevations(String extremesFileName) - { - if (extremesFileName == null) - { + public void loadExtremeElevations(String extremesFileName) { + if (extremesFileName == null) { String message = Logging.getMessage("nullValue.ExtremeElevationsFileName"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } InputStream is = null; - try - { + try { is = this.getClass().getResourceAsStream("/" + extremesFileName); - if (is == null) - { + if (is == null) { // Look directly in the file system File file = new File(extremesFileName); - if (file.exists()) + if (file.exists()) { is = new FileInputStream(file); - else + } else { Logging.logger().log(java.util.logging.Level.WARNING, "BasicElevationModel.UnavailableExtremesFile", - extremesFileName); + extremesFileName); + } } - if (is == null) + if (is == null) { return; + } // The level the extremes were taken from is encoded as the last element in the file name String[] tokens = extremesFileName.substring(0, extremesFileName.lastIndexOf(".")).split("_"); this.extremesLevel = Integer.parseInt(tokens[tokens.length - 1]); - if (this.extremesLevel < 0) - { + if (this.extremesLevel < 0) { this.extremes = null; Logging.logger().log(java.util.logging.Level.WARNING, "BasicElevationModel.UnavailableExtremesLevel", - extremesFileName); + extremesFileName); return; } @@ -1531,83 +1449,83 @@ public void loadExtremeElevations(String extremesFileName) bufferParams.setValue(AVKey.DATA_TYPE, AVKey.INT16); bufferParams.setValue(AVKey.BYTE_ORDER, AVKey.BIG_ENDIAN); // Extremes are always saved in JVM byte order this.extremes = BufferWrapper.wrap(WWIO.readStreamToBuffer(is, true), - bufferParams); // Read extremes to a direct ByteBuffer. - } - catch (FileNotFoundException e) - { + bufferParams); // Read extremes to a direct ByteBuffer. + } catch (FileNotFoundException e) { Logging.logger().log(java.util.logging.Level.WARNING, - Logging.getMessage("BasicElevationModel.ExceptionReadingExtremeElevations", extremesFileName), e); + Logging.getMessage("BasicElevationModel.ExceptionReadingExtremeElevations", extremesFileName), e); this.extremes = null; this.extremesLevel = -1; this.extremesLookupCache = null; - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().log(java.util.logging.Level.WARNING, - Logging.getMessage("BasicElevationModel.ExceptionReadingExtremeElevations", extremesFileName), e); + Logging.getMessage("BasicElevationModel.ExceptionReadingExtremeElevations", extremesFileName), e); this.extremes = null; this.extremesLevel = -1; this.extremesLookupCache = null; - } - finally - { + } finally { WWIO.closeStream(is, extremesFileName); // Clear the extreme elevations lookup cache. - if (this.extremesLookupCache != null) + if (this.extremesLookupCache != null) { this.extremesLookupCache.clear(); + } } } - protected double[] computeExtremeElevations(Sector sector) - { + protected double[] computeExtremeElevations(Sector sector) { LatLon delta = this.levels.getLevel(this.extremesLevel).getTileDelta(); LatLon origin = this.levels.getTileOrigin(); final int nwRow = ElevationTile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), - origin.getLatitude()); + origin.getLatitude()); final int nwCol = ElevationTile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), - origin.getLongitude()); + origin.getLongitude()); final int seRow = ElevationTile.computeRow(delta.getLatitude(), sector.getMinLatitude(), - origin.getLatitude()); + origin.getLatitude()); final int seCol = ElevationTile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), - origin.getLongitude()); + origin.getLongitude()); final int nCols = ElevationTile.computeColumn(delta.getLongitude(), Angle.POS180, Angle.NEG180) + 1; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; - for (int col = nwCol; col <= seCol; col++) - { - for (int row = seRow; row <= nwRow; row++) - { + for (int col = nwCol; col <= seCol; col++) { + for (int row = seRow; row <= nwRow; row++) { int index = 2 * (row * nCols + col); double a = this.extremes.getDouble(index); double b = this.extremes.getDouble(index + 1); - if (a == this.getMissingDataSignal()) + if (a == this.getMissingDataSignal()) { a = this.getMissingDataReplacement(); - if (b == this.getMissingDataSignal()) + } + if (b == this.getMissingDataSignal()) { b = this.getMissingDataReplacement(); + } - if (a > max) + if (a > max) { max = a; - if (a < min) + } + if (a < min) { min = a; - if (b > max) + } + if (b > max) { max = b; - if (b < min) + } + if (b < min) { min = b; + } } } // Set to model's limits if for some reason a limit wasn't determined - if (min == Double.MAX_VALUE) + if (min == Double.MAX_VALUE) { min = this.getMinElevation(); - if (max == -Double.MAX_VALUE) + } + if (max == -Double.MAX_VALUE) { max = this.getMaxElevation(); + } - return new double[] {min, max}; + return new double[]{min, max}; } /** @@ -1617,15 +1535,13 @@ protected double[] computeExtremeElevations(Sector sector) * * @return the memory cache associated with the extreme elevations computations. */ - protected synchronized MemoryCache getExtremesLookupCache() - { + protected synchronized MemoryCache getExtremesLookupCache() { // Note that the extremes lookup cache does not belong to the WorldWind memory cache set, therefore it will not // be automatically cleared and disposed when WorldWind is shutdown. However, since the extremes lookup cache // is a local reference to this elevation model, it will be reclaimed by the JVM garbage collector when this // elevation model is reclaimed by the GC. - if (this.extremesLookupCache == null) - { + if (this.extremesLookupCache == null) { long size = Configuration.getLongValue(AVKey.ELEVATION_EXTREMES_LOOKUP_CACHE_SIZE, 20000000L); this.extremesLookupCache = new BasicMemoryCache((long) (0.85 * size), size); } @@ -1633,49 +1549,41 @@ protected synchronized MemoryCache getExtremesLookupCache() return this.extremesLookupCache; } - protected static class ElevationTile extends gov.nasa.worldwind.util.Tile implements Cacheable - { + protected static class ElevationTile extends gov.nasa.worldwind.util.Tile implements Cacheable { + protected BufferWrapper elevations; // the elevations themselves protected long updateTime = 0; protected double[] extremes = new double[2]; - protected ElevationTile(Sector sector, Level level, int row, int col) - { + protected ElevationTile(Sector sector, Level level, int row, int col) { super(sector, level, row, col); } - public BufferWrapper getElevations() - { + public BufferWrapper getElevations() { return this.elevations; } - public void setElevations(BufferWrapper elevations, BasicElevationModel em) - { + public void setElevations(BufferWrapper elevations, BasicElevationModel em) { this.elevations = elevations; this.updateTime = System.currentTimeMillis(); - if (this.elevations.length() > 0) - { + if (this.elevations.length() > 0) { this.extremes = WWUtil.defaultMinMix(); - for (int i = 0; i < this.elevations.length(); i++) - { + for (int i = 0; i < this.elevations.length(); i++) { em.determineExtremes(this.elevations.getDouble(i), this.extremes); } } } - public boolean isElevationsExpired() - { + public boolean isElevationsExpired() { return this.isElevationsExpired(this.getLevel().getExpiryTime()); } - public boolean isElevationsExpired(long expiryTime) - { + public boolean isElevationsExpired(long expiryTime) { return this.updateTime > 0 && this.updateTime < expiryTime; } - public int computeElevationIndex(LatLon location) - { + public int computeElevationIndex(LatLon location) { Sector sector = this.getSector(); final int tileHeight = this.getHeight(); @@ -1696,16 +1604,15 @@ public int computeElevationIndex(LatLon location) return j * tileWidth + i; } - public double[] getExtremes(Sector sector, BasicElevationModel em, double[] extremes) - { + public double[] getExtremes(Sector sector, BasicElevationModel em, double[] extremes) { Sector intersection = this.getSector().intersection(sector); - if (intersection == null) + if (intersection == null) { return extremes; + } LatLon[] corners = intersection.getCorners(); int[] indices = new int[4]; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { int k = this.computeElevationIndex(corners[i]); indices[i] = k < 0 ? 0 : k > this.elevations.length() - 1 ? this.elevations.length() - 1 : k; } @@ -1716,13 +1623,12 @@ public double[] getExtremes(Sector sector, BasicElevationModel em, double[] extr int nCols = se - sw + 1; - if (extremes == null) + if (extremes == null) { extremes = WWUtil.defaultMinMix(); + } - while (nw <= sw) - { - for (int i = 0; i < nCols; i++) - { + while (nw <= sw) { + for (int i = 0; i < nCols; i++) { int k = nw + i; em.determineExtremes(this.elevations.getDouble(k), extremes); } @@ -1734,8 +1640,7 @@ public double[] getExtremes(Sector sector, BasicElevationModel em, double[] extr } } - protected Elevations getElevations(Sector requestedSector, LevelSet levelSet, int targetLevelNumber) - { + protected Elevations getElevations(Sector requestedSector, LevelSet levelSet, int targetLevelNumber) { // Compute the intersection of the requested sector with the LevelSet's sector. // The intersection will be used to determine which Tiles in the LevelSet are in the requested sector. Sector sector = requestedSector.intersection(levelSet.getSector()); @@ -1748,13 +1653,12 @@ protected Elevations getElevations(Sector requestedSector, LevelSet levelSet, in final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), origin.getLatitude()); final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), origin.getLongitude()); - java.util.TreeSet tiles = new java.util.TreeSet(new Comparator() - { - public int compare(ElevationTile t1, ElevationTile t2) - { + java.util.TreeSet tiles = new java.util.TreeSet(new Comparator() { + public int compare(ElevationTile t1, ElevationTile t2) { if (t2.getLevelNumber() == t1.getLevelNumber() - && t2.getRow() == t1.getRow() && t2.getColumn() == t1.getColumn()) + && t2.getRow() == t1.getRow() && t2.getColumn() == t1.getColumn()) { return 0; + } // Higher-res levels compare lower than lower-res return t1.getLevelNumber() > t2.getLevelNumber() ? -1 : 1; @@ -1764,14 +1668,11 @@ public int compare(ElevationTile t1, ElevationTile t2) boolean missingTargetTiles = false; boolean missingLevelZeroTiles = false; - for (int row = seRow; row <= nwRow; row++) - { - for (int col = nwCol; col <= seCol; col++) - { + for (int row = seRow; row <= nwRow; row++) { + for (int col = nwCol; col <= seCol; col++) { TileKey key = new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName()); ElevationTile tile = this.getTileFromMemory(key); - if (tile != null) - { + if (tile != null) { tiles.add(tile); continue; } @@ -1786,34 +1687,28 @@ public int compare(ElevationTile t1, ElevationTile t2) TileKey fallbackKey; int fallbackRow = row; int fallbackCol = col; - for (int fallbackLevelNum = key.getLevelNumber() - 1; fallbackLevelNum >= 0; fallbackLevelNum--) - { + for (int fallbackLevelNum = key.getLevelNumber() - 1; fallbackLevelNum >= 0; fallbackLevelNum--) { fallbackRow /= 2; fallbackCol /= 2; fallbackKey = new TileKey(fallbackLevelNum, fallbackRow, fallbackCol, - this.levels.getLevel(fallbackLevelNum).getCacheName()); + this.levels.getLevel(fallbackLevelNum).getCacheName()); tile = this.getTileFromMemory(fallbackKey); - if (tile != null) - { - if (!tiles.contains(tile)) - { + if (tile != null) { + if (!tiles.contains(tile)) { tiles.add(tile); } break; - } - else - { - if (fallbackLevelNum == 0) + } else { + if (fallbackLevelNum == 0) { missingLevelZeroTiles = true; + } fallbackToRequest = fallbackKey; // keep track of lowest level to request } } - if (fallbackToRequest != null) - { - if (!requested.contains(fallbackToRequest)) - { + if (fallbackToRequest != null) { + if (!requested.contains(fallbackToRequest)) { this.requestTile(fallbackToRequest); requested.add(fallbackToRequest); // keep track to avoid overhead of duplicte requests } @@ -1823,35 +1718,29 @@ public int compare(ElevationTile t1, ElevationTile t2) Elevations elevations; - if (missingLevelZeroTiles || tiles.isEmpty()) - { + if (missingLevelZeroTiles || tiles.isEmpty()) { // Double.MAX_VALUE is a signal for no in-memory tile for a given region of the sector. elevations = new Elevations(this, Double.MAX_VALUE); elevations.tiles = tiles; - } - else if (missingTargetTiles) - { + } else if (missingTargetTiles) { // Use the level of the the lowest resolution found to denote the resolution of this elevation set. // The list of tiles is sorted first by level, so use the level of the list's last entry. elevations = new Elevations(this, tiles.last().getLevel().getTexelSize()); elevations.tiles = tiles; - } - else - { + } else { elevations = new Elevations(this, tiles.last().getLevel().getTexelSize()); // Compute the elevation extremes now that the sector is fully resolved - if (tiles.size() > 0) - { + if (tiles.size() > 0) { elevations.tiles = tiles; double[] extremes = elevations.getTileExtremes(); - if (extremes != null && this.isExtremesCachingEnabled()) - { + if (extremes != null && this.isExtremesCachingEnabled()) { // Cache the newly computed extremes if they're different from the currently cached ones. double[] currentExtremes = (double[]) this.getExtremesLookupCache().getObject(requestedSector); if (currentExtremes == null || currentExtremes[0] != extremes[0] - || currentExtremes[1] != extremes[1]) + || currentExtremes[1] != extremes[1]) { this.getExtremesLookupCache().add(requestedSector, extremes, 64); + } } } } @@ -1860,30 +1749,29 @@ else if (missingTargetTiles) // time has been set for the elevation model. If none has been set, the expiry times of the model's individual // levels are used, but only for tiles in the local file cache, not tiles in memory. This is to avoid incurring // the overhead of checking expiration of in-memory tiles, a very rarely used feature. - if (this.getExpiryTime() > 0 && this.getExpiryTime() < System.currentTimeMillis()) + if (this.getExpiryTime() > 0 && this.getExpiryTime() < System.currentTimeMillis()) { this.checkElevationExpiration(tiles); + } return elevations; } - protected void checkElevationExpiration(ElevationTile tile) - { - if (tile.isElevationsExpired()) + protected void checkElevationExpiration(ElevationTile tile) { + if (tile.isElevationsExpired()) { this.requestTile(tile.getTileKey()); + } } - protected void checkElevationExpiration(Iterable tiles) - { - for (ElevationTile tile : tiles) - { - if (tile.isElevationsExpired()) + protected void checkElevationExpiration(Iterable tiles) { + for (ElevationTile tile : tiles) { + if (tile.isElevationsExpired()) { this.requestTile(tile.getTileKey()); + } } } @SuppressWarnings({"UnusedDeclaration"}) - public ByteBuffer generateExtremeElevations(int levelNumber) - { + public ByteBuffer generateExtremeElevations(int levelNumber) { return null; //Level level = this.levels.getLevel(levelNumber); //Sector sector = this.levels.getSector(); @@ -1976,11 +1864,9 @@ public ByteBuffer generateExtremeElevations(int levelNumber) // // return (1 + (nwRow - seRow) * (1 + seCol - nwCol)); // } - //**************************************************************// //******************** Non-Tile Resource Retrieval ***********// //**************************************************************// - /** * Retrieves any non-tile resources associated with this ElevationModel, either online or in the local filesystem, * and initializes properties of this ElevationModel using those resources. This returns a key indicating the @@ -1993,13 +1879,11 @@ public ByteBuffer generateExtremeElevations(int levelNumber) * gov.nasa.worldwind.avlist.AVKey#RETRIEVAL_STATE_ERROR} if the retrieval failed with errors, and null * if the retrieval state is unknown. */ - protected String retrieveResources() - { + protected String retrieveResources() { // This ElevationModel has no construction parameters, so there is no description of what to retrieve. Return a // key indicating the resources have been successfully retrieved, though there is nothing to retrieve. AVList params = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ConstructionParametersIsNull"); Logging.logger().warning(message); return AVKey.RETRIEVAL_STATE_SUCCESSFUL; @@ -2008,8 +1892,7 @@ protected String retrieveResources() // This ElevationModel has no OGC Capabilities URL in its construction parameters. Return a key indicating the // resources have been successfully retrieved, though there is nothing to retrieve. URL url = DataConfigurationUtils.getOGCGetCapabilitiesURL(params); - if (url == null) - { + if (url == null) { String message = Logging.getMessage("nullValue.CapabilitiesURLIsNull"); Logging.logger().warning(message); return AVKey.RETRIEVAL_STATE_SUCCESSFUL; @@ -2024,18 +1907,20 @@ protected String retrieveResources() // of hashCode() and equals() perform blocking IO calls. WorldWind does not perform blocking calls during // rendering, and this method is likely to be called from the rendering thread. WMSCapabilities caps; - if (this.isNetworkRetrievalEnabled()) + if (this.isNetworkRetrievalEnabled()) { caps = SessionCacheUtils.getOrRetrieveSessionCapabilities(url, WorldWind.getSessionCache(), - url.toString(), null, RESOURCE_ID_OGC_CAPABILITIES, null, null); - else + url.toString(), null, RESOURCE_ID_OGC_CAPABILITIES, null, null); + } else { caps = SessionCacheUtils.getSessionCapabilities(WorldWind.getSessionCache(), url.toString(), - url.toString()); + url.toString()); + } // The OGC Capabilities resource retrieval is either currently running in another thread, or has failed. In // either case, return null indicating that that the retrieval was not successful, and we should try again // later. - if (caps == null) + if (caps == null) { return null; + } // We have successfully retrieved this ElevationModel's OGC Capabilities resource. Initialize this ElevationModel // using the Capabilities document, and return a key indicating the retrieval has succeeded. @@ -2050,40 +1935,37 @@ protected String retrieveResources() * synchronizes changes to this ElevationModel by wrapping the appropriate method calls in {@link * SwingUtilities#invokeLater(Runnable)}. * - * @param caps the WMS Capabilities document retrieved from this ElevationModel's WMS server. + * @param caps the WMS Capabilities document retrieved from this ElevationModel's WMS server. * @param params the parameter list describing the WMS layer names associated with this ElevationModel. * * @throws IllegalArgumentException if either the Capabilities or the parameter list is null. */ - protected void initFromOGCCapabilitiesResource(WMSCapabilities caps, AVList params) - { - if (caps == null) - { + protected void initFromOGCCapabilitiesResource(WMSCapabilities caps, AVList params) { + if (caps == null) { String message = Logging.getMessage("nullValue.CapabilitiesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String[] names = DataConfigurationUtils.getOGCLayerNames(params); - if (names == null || names.length == 0) + if (names == null || names.length == 0) { return; + } final Long expiryTime = caps.getLayerLatestLastUpdateTime(names); - if (expiryTime == null) + if (expiryTime == null) { return; + } // Synchronize changes to this ElevationModel with the Event Dispatch Thread. - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + SwingUtilities.invokeLater(new Runnable() { + public void run() { BasicElevationModel.this.setExpiryTime(expiryTime); BasicElevationModel.this.firePropertyChange(AVKey.ELEVATION_MODEL, null, BasicElevationModel.this); } @@ -2097,24 +1979,23 @@ public void run() * @return true if this ElevationModel should retrieve any non-tile resources, and false * otherwise. */ - protected boolean isRetrieveResources() - { + protected boolean isRetrieveResources() { AVList params = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (params == null) + if (params == null) { return false; + } Boolean b = (Boolean) params.getValue(AVKey.RETRIEVE_PROPERTIES_FROM_SERVICE); return b != null && b; } - /** Starts retrieving non-tile resources associated with this model in a non-rendering thread. */ - protected void startResourceRetrieval() - { - Thread t = new Thread(new Runnable() - { + /** + * Starts retrieving non-tile resources associated with this model in a non-rendering thread. + */ + protected void startResourceRetrieval() { + Thread t = new Thread(new Runnable() { @Override - public void run() - { + public void run() { retrieveResources(); } }); @@ -2125,7 +2006,6 @@ public void run() //**************************************************************// //******************** Configuration *************************// //**************************************************************// - /** * Creates a configuration document for a BasicElevationModel described by the specified params. The returned * document may be used as a construction parameter to {@link gov.nasa.worldwind.terrain.BasicElevationModel}. @@ -2134,8 +2014,7 @@ public void run() * * @return a configuration document for the BasicElevationModel. */ - public static Document createBasicElevationModelConfigDocument(AVList params) - { + public static Document createBasicElevationModelConfigDocument(AVList params) { Document doc = WWXML.createDocumentBuilder(true).newDocument(); Element root = WWXML.setDocumentElement(doc, "ElevationModel"); @@ -2163,24 +2042,21 @@ public static Document createBasicElevationModelConfigDocument(AVList params) * org.w3c.dom.Element)} and {@link DataConfigurationUtils#createLevelSetConfigElements(gov.nasa.worldwind.avlist.AVList, * org.w3c.dom.Element)}. * - * @param params the key-value pairs which define the BasicElevationModel configuration parameters. + * @param params the key-value pairs which define the BasicElevationModel configuration parameters. * @param context the XML document root on which to append BasicElevationModel configuration elements. * * @return a reference to context. * * @throws IllegalArgumentException if either the parameters or the context are null. */ - public static Element createBasicElevationModelConfigElements(AVList params, Element context) - { - if (params == null) - { + public static Element createBasicElevationModelConfigElements(AVList params, Element context) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2197,57 +2073,56 @@ public static Element createBasicElevationModelConfigElements(AVList params, Ele // Service properties. // Try to get the SERVICE_NAME property, but default to "WWTileService". String s = AVListImpl.getStringValue(params, AVKey.SERVICE_NAME, "WWTileService"); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { // The service element may already exist, in which case we want to append to it. Element el = WWXML.getElement(context, "Service", xpath); - if (el == null) + if (el == null) { el = WWXML.appendElementPath(context, "Service"); + } WWXML.setTextAttribute(el, "serviceName", s); } WWXML.checkAndAppendBooleanElement(params, AVKey.RETRIEVE_PROPERTIES_FROM_SERVICE, context, - "RetrievePropertiesFromService"); + "RetrievePropertiesFromService"); // Image format properties. WWXML.checkAndAppendTextElement(params, AVKey.IMAGE_FORMAT, context, "ImageFormat"); Object o = params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS); - if (o != null && o instanceof String[]) - { + if (o != null && o instanceof String[]) { String[] strings = (String[]) o; - if (strings.length > 0) - { + if (strings.length > 0) { // The available image formats element may already exists, in which case we want to append to it, rather // than create entirely separate paths. Element el = WWXML.getElement(context, "AvailableImageFormats", xpath); - if (el == null) + if (el == null) { el = WWXML.appendElementPath(context, "AvailableImageFormats"); + } WWXML.appendTextArray(el, "ImageFormat", strings); } } // Data type properties. - if (params.getValue(AVKey.DATA_TYPE) != null || params.getValue(AVKey.BYTE_ORDER) != null) - { + if (params.getValue(AVKey.DATA_TYPE) != null || params.getValue(AVKey.BYTE_ORDER) != null) { Element el = WWXML.getElement(context, "DataType", null); - if (el == null) + if (el == null) { el = WWXML.appendElementPath(context, "DataType"); + } s = params.getStringValue(AVKey.DATA_TYPE); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { s = WWXML.dataTypeAsText(s); - if (s != null && s.length() > 0) + if (s != null && s.length() > 0) { WWXML.setTextAttribute(el, "type", s); + } } s = params.getStringValue(AVKey.BYTE_ORDER); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { s = WWXML.byteOrderAsText(s); - if (s != null && s.length() > 0) + if (s != null && s.length() > 0) { WWXML.setTextAttribute(el, "byteOrder", s); + } } } @@ -2256,12 +2131,14 @@ public static Element createBasicElevationModelConfigElements(AVList params, Ele WWXML.checkAndAppendTextElement(params, AVKey.ELEVATION_EXTREMES_FILE, el, "FileName"); Double d = AVListImpl.getDoubleValue(params, AVKey.ELEVATION_MAX); - if (d != null) + if (d != null) { WWXML.setDoubleAttribute(el, "max", d); + } d = AVListImpl.getDoubleValue(params, AVKey.ELEVATION_MIN); - if (d != null) + if (d != null) { WWXML.setDoubleAttribute(el, "min", d); + } return context; } @@ -2285,24 +2162,23 @@ public static Element createBasicElevationModelConfigElements(AVList params, Ele * gov.nasa.worldwind.avlist.AVList)}. * * @param domElement the XML document root to parse for BasicElevationModel configuration parameters. - * @param params the output key-value pairs which recieve the BasicElevationModel configuration parameters. A - * null reference is permitted. + * @param params the output key-value pairs which recieve the BasicElevationModel configuration parameters. A null + * reference is permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - public static AVList getBasicElevationModelConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + public static AVList getBasicElevationModelConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } XPath xpath = WWXML.makeXPath(); @@ -2315,68 +2191,60 @@ public static AVList getBasicElevationModelConfigParams(Element domElement, AVLi // Service properties. WWXML.checkAndSetStringParam(domElement, params, AVKey.SERVICE_NAME, "Service/@serviceName", xpath); WWXML.checkAndSetBooleanParam(domElement, params, AVKey.RETRIEVE_PROPERTIES_FROM_SERVICE, - "RetrievePropertiesFromService", xpath); + "RetrievePropertiesFromService", xpath); // Image format properties. WWXML.checkAndSetStringParam(domElement, params, AVKey.IMAGE_FORMAT, "ImageFormat", xpath); WWXML.checkAndSetUniqueStringsParam(domElement, params, AVKey.AVAILABLE_IMAGE_FORMATS, - "AvailableImageFormats/ImageFormat", xpath); + "AvailableImageFormats/ImageFormat", xpath); // Data type properties. - if (params.getValue(AVKey.DATA_TYPE) == null) - { + if (params.getValue(AVKey.DATA_TYPE) == null) { String s = WWXML.getText(domElement, "DataType/@type", xpath); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { s = WWXML.parseDataType(s); - if (s != null && s.length() > 0) + if (s != null && s.length() > 0) { params.setValue(AVKey.DATA_TYPE, s); + } } } - if (params.getValue(AVKey.BYTE_ORDER) == null) - { + if (params.getValue(AVKey.BYTE_ORDER) == null) { String s = WWXML.getText(domElement, "DataType/@byteOrder", xpath); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { s = WWXML.parseByteOrder(s); - if (s != null && s.length() > 0) + if (s != null && s.length() > 0) { params.setValue(AVKey.BYTE_ORDER, s); + } } } // Elevation data properties. WWXML.checkAndSetStringParam(domElement, params, AVKey.ELEVATION_EXTREMES_FILE, "ExtremeElevations/FileName", - xpath); + xpath); WWXML.checkAndSetDoubleParam(domElement, params, AVKey.ELEVATION_MAX, "ExtremeElevations/@max", xpath); WWXML.checkAndSetDoubleParam(domElement, params, AVKey.ELEVATION_MIN, "ExtremeElevations/@min", xpath); return params; } - protected void writeConfigurationFile(FileStore fileStore) - { + protected void writeConfigurationFile(FileStore fileStore) { // TODO: configurable max attempts for creating a configuration file. - try - { + try { AVList configParams = this.getConfigurationParams(null); this.writeConfigurationParams(configParams, fileStore); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionAttemptingToWriteConfigurationFile"); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } } - protected void writeConfigurationParams(AVList params, FileStore fileStore) - { + protected void writeConfigurationParams(AVList params, FileStore fileStore) { // Determine what the configuration file name should be based on the configuration parameters. Assume an XML // configuration document type, and append the XML file suffix. String fileName = DataConfigurationUtils.getDataConfigFilename(params, ".xml"); - if (fileName == null) - { + if (fileName == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -2386,26 +2254,25 @@ protected void writeConfigurationParams(AVList params, FileStore fileStore) // to improve multithreaded performance for the common case: the configuration file already exists, this just // need to check that it's there and return. If the file exists but is expired, do not remove it - this // removes the file inside the synchronized block below. - if (!this.needsConfigurationFile(fileStore, fileName, params, false)) + if (!this.needsConfigurationFile(fileStore, fileName, params, false)) { return; + } - synchronized (this.fileLock) - { + synchronized (this.fileLock) { // Check again if the component needs to write a configuration file, potentially removing any existing file // which has expired. This additional check is necessary because the file could have been created by // another thread while we were waiting for the lock. - if (!this.needsConfigurationFile(fileStore, fileName, params, true)) + if (!this.needsConfigurationFile(fileStore, fileName, params, true)) { return; + } this.doWriteConfigurationParams(fileStore, fileName, params); } } - protected void doWriteConfigurationParams(FileStore fileStore, String fileName, AVList params) - { + protected void doWriteConfigurationParams(FileStore fileStore, String fileName, AVList params) { java.io.File file = fileStore.newFile(fileName); - if (file == null) - { + if (file == null) { String message = Logging.getMessage("generic.CannotCreateFile", fileName); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -2419,24 +2286,25 @@ protected void doWriteConfigurationParams(FileStore fileStore, String fileName, } protected boolean needsConfigurationFile(FileStore fileStore, String fileName, AVList params, - boolean removeIfExpired) - { + boolean removeIfExpired) { long expiryTime = this.getExpiryTime(); - if (expiryTime <= 0) + if (expiryTime <= 0) { expiryTime = AVListImpl.getLongValue(params, AVKey.EXPIRY_TIME, 0L); + } return !DataConfigurationUtils.hasDataConfigFile(fileStore, fileName, removeIfExpired, expiryTime); } - protected AVList getConfigurationParams(AVList params) - { - if (params == null) + protected AVList getConfigurationParams(AVList params) { + if (params == null) { params = new AVListImpl(); + } // Gather all the construction parameters if they are available. AVList constructionParams = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (constructionParams != null) + if (constructionParams != null) { params.setValues(constructionParams); + } // Gather any missing LevelSet parameters from the LevelSet itself. DataConfigurationUtils.getLevelSetConfigParams(this.getLevels(), params); @@ -2445,58 +2313,55 @@ protected AVList getConfigurationParams(AVList params) // model configuration to property interpret the cached elevation files. While the elevation model assumes // default values when these properties are missing, a different system does not know what those default values // should be, and thus cannot assume anything about the value of these properties. - - if (params.getValue(AVKey.BYTE_ORDER) == null) + if (params.getValue(AVKey.BYTE_ORDER) == null) { params.setValue(AVKey.BYTE_ORDER, this.getElevationDataByteOrder()); + } - if (params.getValue(AVKey.DATA_TYPE) == null) + if (params.getValue(AVKey.DATA_TYPE) == null) { params.setValue(AVKey.DATA_TYPE, this.getElevationDataType()); + } - if (params.getValue(AVKey.MISSING_DATA_SIGNAL) == null) + if (params.getValue(AVKey.MISSING_DATA_SIGNAL) == null) { params.setValue(AVKey.MISSING_DATA_SIGNAL, this.getMissingDataSignal()); + } return params; } - protected Document createConfigurationDocument(AVList params) - { + protected Document createConfigurationDocument(AVList params) { return createBasicElevationModelConfigDocument(params); } //**************************************************************// //******************** Restorable Support ********************// //**************************************************************// - - public String getRestorableState() - { + public String getRestorableState() { // We only create a restorable state XML if this elevation model was constructed with an AVList. AVList constructionParams = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (constructionParams == null) + if (constructionParams == null) { return null; + } RestorableSupport rs = RestorableSupport.newRestorableSupport(); // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (rs == null) + if (rs == null) { return null; + } this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - public void restoreState(String stateInXml) - { + public void restoreState(String stateInXml) { String message = Logging.getMessage("RestorableSupport.RestoreRequiresConstructor"); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { AVList constructionParams = (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS); - if (constructionParams != null) - { - for (Map.Entry avp : constructionParams.getEntries()) - { + if (constructionParams != null) { + for (Map.Entry avp : constructionParams.getEntries()) { this.getRestorableStateForAVPair(avp.getKey(), avp.getValue(), rs, context); } } @@ -2511,120 +2376,116 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsString(context, "BasicElevationModel.DataByteOrder", this.getElevationDataByteOrder()); // We'll write the detail hint attribute only when it's a nonzero value. - if (this.detailHint != 0.0) + if (this.detailHint != 0.0) { rs.addStateValueAsDouble(context, "BasicElevationModel.DetailHint", this.detailHint); + } RestorableSupport.StateObject so = rs.addStateObject(context, "avlist"); - for (Map.Entry avp : this.getEntries()) - { + for (Map.Entry avp : this.getEntries()) { this.getRestorableStateForAVPair(avp.getKey(), avp.getValue(), rs, so); } } public void getRestorableStateForAVPair(String key, Object value, - RestorableSupport rs, RestorableSupport.StateObject context) - { - if (value == null) + RestorableSupport rs, RestorableSupport.StateObject context) { + if (value == null) { return; + } - if (key.equals(AVKey.CONSTRUCTION_PARAMETERS)) + if (key.equals(AVKey.CONSTRUCTION_PARAMETERS)) { return; + } - if (value instanceof LatLon) - { + if (value instanceof LatLon) { rs.addStateValueAsLatLon(context, key, (LatLon) value); - } - else if (value instanceof Sector) - { + } else if (value instanceof Sector) { rs.addStateValueAsSector(context, key, (Sector) value); - } - else - { + } else { super.getRestorableStateForAVPair(key, value, rs, context); } } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { String s = rs.getStateValueAsString(context, "ElevationModel.Name"); - if (s != null) + if (s != null) { this.setName(s); + } Double d = rs.getStateValueAsDouble(context, "ElevationModel.MissingDataFlag"); - if (d != null) + if (d != null) { this.setMissingDataSignal(d); + } d = rs.getStateValueAsDouble(context, "ElevationModel.MissingDataValue"); - if (d != null) + if (d != null) { this.setMissingDataReplacement(d); + } Boolean b = rs.getStateValueAsBoolean(context, "ElevationModel.NetworkRetrievalEnabled"); - if (b != null) + if (b != null) { this.setNetworkRetrievalEnabled(b); + } // Look for the elevation data type using the current property name "BasicElevationModel.DataType", or the the // old property name "BasicElevationModel.DataPixelType" if a property with the current name does not exist. s = rs.getStateValueAsString(context, "BasicElevationModel.DataType"); - if (s == null) + if (s == null) { s = rs.getStateValueAsString(context, "BasicElevationModel.DataPixelType"); - if (s != null) + } + if (s != null) { this.setElevationDataType(s); + } s = rs.getStateValueAsString(context, "BasicElevationModel.DataByteOrder"); - if (s != null) + if (s != null) { this.setByteOrder(s); + } d = rs.getStateValueAsDouble(context, "BasicElevationModel.DetailHint"); - if (d != null) + if (d != null) { this.setDetailHint(d); + } // Intentionally omitting "ElevationModel.MinElevation" and "ElevationModel.MaxElevation" because they are final // properties only configurable at construction. - RestorableSupport.StateObject so = rs.getStateObject(context, "avlist"); - if (so != null) - { + if (so != null) { RestorableSupport.StateObject[] avpairs = rs.getAllStateObjects(so, ""); - if (avpairs != null) - { - for (RestorableSupport.StateObject avp : avpairs) - { - if (avp != null) + if (avpairs != null) { + for (RestorableSupport.StateObject avp : avpairs) { + if (avp != null) { this.doRestoreStateForObject(rs, avp); + } } } } } @SuppressWarnings({"UnusedDeclaration"}) - protected void doRestoreStateForObject(RestorableSupport rs, RestorableSupport.StateObject so) - { - if (so == null) + protected void doRestoreStateForObject(RestorableSupport rs, RestorableSupport.StateObject so) { + if (so == null) { return; + } // Map the old PIXEL_TYPE AVKey constant to the new DATA_TYPE constant. - if ("gov.nasa.worldwind.avkey.PixelType".equals(so.getName())) + if ("gov.nasa.worldwind.avkey.PixelType".equals(so.getName())) { this.setValue(AVKey.DATA_TYPE, so.getValue()); - else + } else { this.setValue(so.getName(), so.getValue()); + } } - protected static AVList restorableStateToParams(String stateInXml) - { - if (stateInXml == null) - { + protected static AVList restorableStateToParams(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -2637,84 +2498,90 @@ protected static AVList restorableStateToParams(String stateInXml) } protected static void restoreStateForParams(RestorableSupport rs, RestorableSupport.StateObject context, - AVList params) - { + AVList params) { StringBuilder sb = new StringBuilder(); String s = rs.getStateValueAsString(context, AVKey.DATA_CACHE_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DATA_CACHE_NAME, s); + } s = rs.getStateValueAsString(context, AVKey.SERVICE); - if (s != null) + if (s != null) { params.setValue(AVKey.SERVICE, s); + } s = rs.getStateValueAsString(context, AVKey.DATASET_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DATASET_NAME, s); + } s = rs.getStateValueAsString(context, AVKey.FORMAT_SUFFIX); - if (s != null) + if (s != null) { params.setValue(AVKey.FORMAT_SUFFIX, s); + } Integer i = rs.getStateValueAsInteger(context, AVKey.NUM_EMPTY_LEVELS); - if (i != null) + if (i != null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, i); + } i = rs.getStateValueAsInteger(context, AVKey.NUM_LEVELS); - if (i != null) + if (i != null) { params.setValue(AVKey.NUM_LEVELS, i); + } i = rs.getStateValueAsInteger(context, AVKey.TILE_WIDTH); - if (i != null) + if (i != null) { params.setValue(AVKey.TILE_WIDTH, i); + } i = rs.getStateValueAsInteger(context, AVKey.TILE_HEIGHT); - if (i != null) + if (i != null) { params.setValue(AVKey.TILE_HEIGHT, i); + } Long lo = rs.getStateValueAsLong(context, AVKey.EXPIRY_TIME); - if (lo != null) + if (lo != null) { params.setValue(AVKey.EXPIRY_TIME, lo); + } LatLon ll = rs.getStateValueAsLatLon(context, AVKey.LEVEL_ZERO_TILE_DELTA); - if (ll != null) + if (ll != null) { params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, ll); + } ll = rs.getStateValueAsLatLon(context, AVKey.TILE_ORIGIN); - if (ll != null) + if (ll != null) { params.setValue(AVKey.TILE_ORIGIN, ll); + } Sector sector = rs.getStateValueAsSector(context, AVKey.SECTOR); - if (sector != null) + if (sector != null) { params.setValue(AVKey.SECTOR, sector); + } Double d = rs.getStateValueAsDouble("ElevationModel.MinElevation"); - if (d != null) - { + if (d != null) { params.setValue(AVKey.ELEVATION_MIN, d); - } - else - { - if (sb.length() > 0) + } else { + if (sb.length() > 0) { sb.append(", "); + } sb.append("term.minElevation"); } d = rs.getStateValueAsDouble("ElevationModel.MaxElevation"); - if (d != null) - { + if (d != null) { params.setValue(AVKey.ELEVATION_MAX, d); - } - else - { - if (sb.length() > 0) + } else { + if (sb.length() > 0) { sb.append(", "); + } sb.append("term.maxElevation"); } - if (sb.length() > 0) - { + if (sb.length() > 0) { String message = Logging.getMessage("BasicElevationModel.InvalidDescriptorFields", sb.toString()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2722,10 +2589,8 @@ protected static void restoreStateForParams(RestorableSupport rs, RestorableSupp } @Override - public double getLocalDataAvailability(Sector requestedSector, Double targetResolution) - { - if (requestedSector == null) - { + public double getLocalDataAvailability(Sector requestedSector, Double targetResolution) { + if (requestedSector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -2736,11 +2601,12 @@ public double getLocalDataAvailability(Sector requestedSector, Double targetReso Sector sector = requestedSector.intersection(levelSet.getSector()); // If there is no intersection there is no data to retrieve - if (sector == null) + if (sector == null) { return 1d; + } Level targetLevel = targetResolution != null - ? this.getTargetLevel(sector, targetResolution) : levelSet.getLastLevel(); + ? this.getTargetLevel(sector, targetResolution) : levelSet.getLastLevel(); // Count all the tiles intersecting the input sector. long numLocalTiles = 0; @@ -2752,28 +2618,26 @@ public double getLocalDataAvailability(Sector requestedSector, Double targetReso final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), origin.getLatitude()); final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), origin.getLongitude()); - for (int row = nwRow; row >= seRow; row--) - { - for (int col = nwCol; col <= seCol; col++) - { + for (int row = nwRow; row >= seRow; row--) { + for (int col = nwCol; col <= seCol; col++) { TileKey key = new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName()); Sector tileSector = levelSet.computeSectorForKey(key); Tile tile = new Tile(tileSector, targetLevel, row, col); - if (!this.isTileLocalOrAbsent(tile)) + if (!this.isTileLocalOrAbsent(tile)) { ++numMissingTiles; - else + } else { ++numLocalTiles; + } } } return numLocalTiles > 0 ? numLocalTiles / (double) (numLocalTiles + numMissingTiles) : 0d; } - protected boolean isTileLocalOrAbsent(Tile tile) - { - if (this.getLevels().isResourceAbsent(tile)) + protected boolean isTileLocalOrAbsent(Tile tile) { + if (this.getLevels().isResourceAbsent(tile)) { return true; // tile is absent - + } URL url = this.getDataFileStore().findFile(tile.getPath(), false); return url != null && !this.isFileExpired(tile, url, this.getDataFileStore()); diff --git a/src/gov/nasa/worldwind/terrain/BasicElevationModelBulkDownloader.java b/src/gov/nasa/worldwind/terrain/BasicElevationModelBulkDownloader.java index 458e8a826e..d96c2d6067 100644 --- a/src/gov/nasa/worldwind/terrain/BasicElevationModelBulkDownloader.java +++ b/src/gov/nasa/worldwind/terrain/BasicElevationModelBulkDownloader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.WorldWind; @@ -28,8 +27,8 @@ * @author tag * @version $Id: BasicElevationModelBulkDownloader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicElevationModelBulkDownloader extends BulkRetrievalThread -{ +public class BasicElevationModelBulkDownloader extends BulkRetrievalThread { + protected final static int MAX_TILE_COUNT_PER_REGION = 200; protected final static long DEFAULT_AVERAGE_FILE_SIZE = 45000L; @@ -44,16 +43,15 @@ public class BasicElevationModelBulkDownloader extends BulkRetrievalThread * The thread returned is not started during construction, the caller must start the thread. * * @param elevationModel the elevation model for which to download elevations. - * @param sector the sector to download data for. This value is final. - * @param resolution the target resolution, provided in radians of latitude per texel. This value is final. - * @param listener an optional retrieval listener. May be null. + * @param sector the sector to download data for. This value is final. + * @param resolution the target resolution, provided in radians of latitude per texel. This value is final. + * @param listener an optional retrieval listener. May be null. * * @throws IllegalArgumentException if either the elevation model or sector are null, or the resolution is less than - * zero. + * zero. */ public BasicElevationModelBulkDownloader(BasicElevationModel elevationModel, Sector sector, double resolution, - BulkRetrievalListener listener) - { + BulkRetrievalListener listener) { // Arguments checked in parent constructor super(elevationModel, sector, resolution, elevationModel.getDataFileStore(), listener); @@ -67,17 +65,16 @@ public BasicElevationModelBulkDownloader(BasicElevationModel elevationModel, Sec * The thread returned is not started during construction, the caller must start the thread. * * @param elevationModel the elevation model for which to download elevations. - * @param sector the sector to download data for. This value is final. - * @param resolution the target resolution, provided in radians of latitude per texel. This value is final. - * @param fileStore the file store in which to place the downloaded elevations. - * @param listener an optional retrieval listener. May be null. + * @param sector the sector to download data for. This value is final. + * @param resolution the target resolution, provided in radians of latitude per texel. This value is final. + * @param fileStore the file store in which to place the downloaded elevations. + * @param listener an optional retrieval listener. May be null. * * @throws IllegalArgumentException if either the elevation model, the sector or file store are null, or the - * resolution is less than zero. + * resolution is less than zero. */ public BasicElevationModelBulkDownloader(BasicElevationModel elevationModel, Sector sector, double resolution, - FileStore fileStore, BulkRetrievalListener listener) - { + FileStore fileStore, BulkRetrievalListener listener) { // Arguments checked in parent constructor super(elevationModel, sector, resolution, fileStore, listener); @@ -85,50 +82,43 @@ public BasicElevationModelBulkDownloader(BasicElevationModel elevationModel, Sec this.level = computeLevelForResolution(sector, resolution); } - public void run() - { - try - { + public void run() { + try { // Init progress with missing tiles count estimate this.progress.setTotalCount(this.estimateMissingTilesCount(20)); this.progress.setTotalSize(this.progress.getTotalCount() * estimateAverageTileSize()); // Determine and request missing tiles by level/region - for (int levelNumber = 0; levelNumber <= this.level; levelNumber++) - { - if (elevationModel.getLevels().isLevelEmpty(levelNumber)) + for (int levelNumber = 0; levelNumber <= this.level; levelNumber++) { + if (elevationModel.getLevels().isLevelEmpty(levelNumber)) { continue; + } int div = this.computeRegionDivisions(this.sector, levelNumber, MAX_TILE_COUNT_PER_REGION); Iterator regionsIterator = this.getRegionIterator(this.sector, div); Sector region; - while (regionsIterator.hasNext()) - { + while (regionsIterator.hasNext()) { region = regionsIterator.next(); // Determine missing tiles this.missingTiles = getMissingTilesInSector(region, levelNumber); // Submit missing tiles requests at intervals - while (this.missingTiles.size() > 0) - { + while (this.missingTiles.size() > 0) { submitMissingTilesRequests(); - if (this.missingTiles.size() > 0) + if (this.missingTiles.size() > 0) { Thread.sleep(RETRIEVAL_SERVICE_POLL_DELAY); + } } } } // Set progress to 100% this.progress.setTotalCount(this.progress.getCurrentCount()); this.progress.setTotalSize(this.progress.getCurrentSize()); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { String message = Logging.getMessage("generic.BulkRetrievalInterrupted", elevationModel.getName()); Logging.logger().log(java.util.logging.Level.WARNING, message, e); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionDuringBulkRetrieval", elevationModel.getName()); Logging.logger().severe(message); throw new RuntimeException(message); @@ -148,67 +138,60 @@ public void run() // // return count; // } - - protected synchronized void submitMissingTilesRequests() throws InterruptedException - { + protected synchronized void submitMissingTilesRequests() throws InterruptedException { RetrievalService rs = WorldWind.getRetrievalService(); int i = 0; - while (this.missingTiles.size() > i && rs.isAvailable()) - { + while (this.missingTiles.size() > i && rs.isAvailable()) { Thread.sleep(1); // generates InterruptedException if thread has been interrupted Tile tile = this.missingTiles.get(i); - if (this.elevationModel.getLevels().isResourceAbsent(tile)) - { + if (this.elevationModel.getLevels().isResourceAbsent(tile)) { removeAbsentTile(tile); // tile is absent, count it off. continue; } URL url = this.fileStore.findFile(tile.getPath(), false); - if (url != null) - { + if (url != null) { // tile has been retrieved and is local now, count it as retrieved. removeRetrievedTile(tile); continue; } this.elevationModel.downloadElevations(tile, - new BulkDownloadPostProcessor(tile, this.elevationModel, this.fileStore)); + new BulkDownloadPostProcessor(tile, this.elevationModel, this.fileStore)); i++; } } - protected class BulkDownloadPostProcessor extends BasicElevationModel.DownloadPostProcessor - { - public BulkDownloadPostProcessor(Tile tile, BasicElevationModel elevationModel, FileStore fileStore) - { + protected class BulkDownloadPostProcessor extends BasicElevationModel.DownloadPostProcessor { + + public BulkDownloadPostProcessor(Tile tile, BasicElevationModel elevationModel, FileStore fileStore) { super(tile, elevationModel, fileStore); } - public ByteBuffer run(Retriever retriever) - { + public ByteBuffer run(Retriever retriever) { ByteBuffer buffer = super.run(retriever); - if (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) + if (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) { removeRetrievedTile(this.tile); + } - if (hasRetrievalListeners()) + if (hasRetrievalListeners()) { callRetrievalListeners(retriever, this.tile); + } return buffer; } } - protected void callRetrievalListeners(Retriever retriever, Tile tile) - { + protected void callRetrievalListeners(Retriever retriever, Tile tile) { String eventType = (retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) - ? BulkRetrievalEvent.RETRIEVAL_SUCCEEDED : BulkRetrievalEvent.RETRIEVAL_FAILED; + ? BulkRetrievalEvent.RETRIEVAL_SUCCEEDED : BulkRetrievalEvent.RETRIEVAL_FAILED; super.callRetrievalListeners(new BulkRetrievalEvent(this.elevationModel, eventType, tile.getPath())); } - protected synchronized void removeRetrievedTile(Tile tile) - { + protected synchronized void removeRetrievedTile(Tile tile) { this.missingTiles.remove(tile); // Update progress this.progress.setCurrentCount(this.progress.getCurrentCount() + 1); @@ -217,8 +200,7 @@ protected synchronized void removeRetrievedTile(Tile tile) this.normalizeProgress(); } - protected synchronized void removeAbsentTile(Tile tile) - { + protected synchronized void removeAbsentTile(Tile tile) { this.missingTiles.remove(tile); // Decrease progress expected total count and size this.progress.setTotalCount(this.progress.getTotalCount() - 1); @@ -227,17 +209,14 @@ protected synchronized void removeAbsentTile(Tile tile) this.normalizeProgress(); } - protected void normalizeProgress() - { - if (this.progress.getTotalCount() < this.progress.getCurrentCount()) - { + protected void normalizeProgress() { + if (this.progress.getTotalCount() < this.progress.getCurrentCount()) { this.progress.setTotalCount(this.progress.getCurrentCount()); this.progress.setTotalSize(this.progress.getCurrentSize()); } } - protected long getEstimatedMissingDataSize() - { + protected long getEstimatedMissingDataSize() { // Get missing tiles count estimate long totMissing = estimateMissingTilesCount(6); // Get average tile size estimate @@ -246,94 +225,79 @@ protected long getEstimatedMissingDataSize() return totMissing * averageTileSize; } - protected long estimateMissingTilesCount(int numSamples) - { + protected long estimateMissingTilesCount(int numSamples) { int maxLevel = computeLevelForResolution(sector, resolution); // Total expected tiles long totCount = 0; - for (int levelNumber = 0; levelNumber <= maxLevel; levelNumber++) - { - if (!this.elevationModel.getLevels().isLevelEmpty(levelNumber)) + for (int levelNumber = 0; levelNumber <= maxLevel; levelNumber++) { + if (!this.elevationModel.getLevels().isLevelEmpty(levelNumber)) { totCount += this.countTilesInSector(sector, levelNumber); + } } // Sample random small sized sectors at finest level int div = this.computeRegionDivisions(this.sector, maxLevel, 36); // max 6x6 tiles per region Sector[] regions = computeRandomRegions(this.sector, div, numSamples); long regionMissing = 0; long regionCount = 0; - try - { - if (regions.length < numSamples) - { + try { + if (regions.length < numSamples) { regionCount = this.countTilesInSector(this.sector, maxLevel); regionMissing = getMissingTilesInSector(this.sector, maxLevel).size(); - } - else - { - for (Sector region : regions) - { + } else { + for (Sector region : regions) { // Count how many tiles are missing in each sample region regionCount += this.countTilesInSector(region, maxLevel); regionMissing += getMissingTilesInSector(region, maxLevel).size(); } } - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { return 0; - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionDuringDataSizeEstimate", this.getName()); Logging.logger().severe(message); throw new RuntimeException(message); } // Extrapolate total missing count - return (long)(totCount * ((double)regionMissing / regionCount)); + return (long) (totCount * ((double) regionMissing / regionCount)); } - protected long estimateAverageTileSize() - { + protected long estimateAverageTileSize() { Long previouslyComputedSize = (Long) this.elevationModel.getValue(AVKey.AVERAGE_TILE_SIZE); - if (previouslyComputedSize != null) + if (previouslyComputedSize != null) { return previouslyComputedSize; + } long size = 0; int count = 0; // Average cached tile files size in a few directories from first non empty level Level targetLevel = this.elevationModel.getLevels().getFirstLevel(); - while (targetLevel.isEmpty() && !targetLevel.equals(this.elevationModel.getLevels().getLastLevel())) - { + while (targetLevel.isEmpty() && !targetLevel.equals(this.elevationModel.getLevels().getLastLevel())) { targetLevel = this.elevationModel.getLevels().getLevel(targetLevel.getLevelNumber() + 1); } File cacheRoot = new File(this.fileStore.getWriteLocation(), targetLevel.getPath()); - if (cacheRoot.exists()) - { - File[] rowDirs = cacheRoot.listFiles(new FileFilter() - { - public boolean accept(File file) - { + if (cacheRoot.exists()) { + File[] rowDirs = cacheRoot.listFiles(new FileFilter() { + public boolean accept(File file) { return file.isDirectory(); } }); - for (File dir : rowDirs) - { + for (File dir : rowDirs) { long averageSize = computeAverageTileSize(dir); - if (averageSize > 0) - { + if (averageSize > 0) { size += averageSize; count++; } if (count >= 2) // average content from up to 2 cache folders + { break; + } } } Long averageTileSize = DEFAULT_AVERAGE_FILE_SIZE; - if (count > 0 && size > 0) - { + if (count > 0 && size > 0) { averageTileSize = size / count; this.elevationModel.setValue(AVKey.AVERAGE_TILE_SIZE, averageTileSize); } @@ -341,23 +305,18 @@ public boolean accept(File file) return averageTileSize; } - protected static long computeAverageTileSize(File dir) - { + protected static long computeAverageTileSize(File dir) { long size = 0; int count = 0; File[] files = dir.listFiles(); - for (File file : files) - { - try - { + for (File file : files) { + try { FileInputStream fis = new FileInputStream(file); size += fis.available(); fis.close(); count++; - } - catch (IOException e) - { + } catch (IOException e) { count += 0; } } @@ -365,10 +324,8 @@ protected static long computeAverageTileSize(File dir) return count > 0 ? size / count : 0; } - protected int computeLevelForResolution(Sector sector, double resolution) - { - if (sector == null) - { + protected int computeLevelForResolution(Sector sector, double resolution) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -377,14 +334,15 @@ protected int computeLevelForResolution(Sector sector, double resolution) // Find the first level exceeding the desired resolution double texelSize; Level targetLevel = this.elevationModel.getLevels().getLastLevel(); - for (int i = 0; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (this.elevationModel.getLevels().isLevelEmpty(i)) + for (int i = 0; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++) { + if (this.elevationModel.getLevels().isLevelEmpty(i)) { continue; + } texelSize = this.elevationModel.getLevels().getLevel(i).getTexelSize(); - if (texelSize > resolution) + if (texelSize > resolution) { continue; + } targetLevel = this.elevationModel.getLevels().getLevel(i); break; @@ -392,34 +350,31 @@ protected int computeLevelForResolution(Sector sector, double resolution) // Choose the level closest to the resolution desired if (targetLevel.getLevelNumber() != 0 && !this.elevationModel.getLevels().isLevelEmpty( - targetLevel.getLevelNumber() - 1)) - { + targetLevel.getLevelNumber() - 1)) { Level nextLowerLevel = this.elevationModel.getLevels().getLevel(targetLevel.getLevelNumber() - 1); double dless = Math.abs(nextLowerLevel.getTexelSize() - resolution); double dmore = Math.abs(targetLevel.getTexelSize() - resolution); - if (dless < dmore) + if (dless < dmore) { targetLevel = nextLowerLevel; + } } return targetLevel.getLevelNumber(); } - protected long countTilesInSector(Sector sector, int levelNumber) - { - if (sector == null) - { + protected long countTilesInSector(Sector sector, int levelNumber) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.elevationModel.getLevels().getLastLevel(); - if (levelNumber >= 0) - { - for (int i = levelNumber; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (this.elevationModel.getLevels().isLevelEmpty(i)) + if (levelNumber >= 0) { + for (int i = levelNumber; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++) { + if (this.elevationModel.getLevels().isLevelEmpty(i)) { continue; + } targetLevel = this.elevationModel.getLevels().getLevel(i); break; @@ -440,22 +395,19 @@ protected long countTilesInSector(Sector sector, int levelNumber) return numRows * numCols; } - protected Tile[][] getTilesInSector(Sector sector, int levelNumber) - { - if (sector == null) - { + protected Tile[][] getTilesInSector(Sector sector, int levelNumber) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level targetLevel = this.elevationModel.getLevels().getLastLevel(); - if (levelNumber >= 0) - { - for (int i = levelNumber; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++) - { - if (this.elevationModel.getLevels().isLevelEmpty(i)) + if (levelNumber >= 0) { + for (int i = levelNumber; i < this.elevationModel.getLevels().getLastLevel().getLevelNumber(); i++) { + if (this.elevationModel.getLevels().isLevelEmpty(i)) { continue; + } targetLevel = this.elevationModel.getLevels().getLevel(i); break; @@ -474,10 +426,8 @@ protected Tile[][] getTilesInSector(Sector sector, int levelNumber) int numCols = seCol - nwCol + 1; Tile[][] sectorTiles = new Tile[numRows][numCols]; - for (int row = nwRow; row >= seRow; row--) - { - for (int col = nwCol; col <= seCol; col++) - { + for (int row = nwRow; row >= seRow; row--) { + for (int col = nwCol; col <= seCol; col++) { TileKey key = new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName()); Sector tileSector = this.elevationModel.getLevels().computeSectorForKey(key); sectorTiles[nwRow - row][col - nwCol] = new Tile(tileSector, targetLevel, row, col); @@ -487,119 +437,110 @@ protected Tile[][] getTilesInSector(Sector sector, int levelNumber) return sectorTiles; } - protected ArrayList getMissingTilesInSector(Sector sector, int levelNumber) throws InterruptedException - { + protected ArrayList getMissingTilesInSector(Sector sector, int levelNumber) throws InterruptedException { ArrayList tiles = new ArrayList(); Tile[][] tileArray = getTilesInSector(sector, levelNumber); - for (Tile[] row : tileArray) - { - for (Tile tile : row) - { + for (Tile[] row : tileArray) { + for (Tile tile : row) { Thread.sleep(1); // generates InterruptedException if thread has been interrupted - if (tile == null) + if (tile == null) { continue; + } - if (isTileLocalOrAbsent(tile)) + if (isTileLocalOrAbsent(tile)) { continue; // tile is local or absent - + } tiles.add(tile); } } return tiles; } - protected int computeRegionDivisions(Sector sector, int levelNumber, int maxCount) - { + protected int computeRegionDivisions(Sector sector, int levelNumber, int maxCount) { long tileCount = countTilesInSector(sector, levelNumber); - if (tileCount <= maxCount) + if (tileCount <= maxCount) { return 1; + } // Divide sector in regions that will contain no more tiles then maxCount return (int) Math.ceil(Math.sqrt((float) tileCount / maxCount)); } - protected Sector[] computeRandomRegions(Sector sector, int div, int numRegions) - { - if (numRegions > div * div) + protected Sector[] computeRandomRegions(Sector sector, int div, int numRegions) { + if (numRegions > div * div) { return sector.subdivide(div); + } final double dLat = sector.getDeltaLat().degrees / div; final double dLon = sector.getDeltaLon().degrees / div; ArrayList regions = new ArrayList(numRegions); Random rand = new Random(); - while (regions.size() < numRegions) - { + while (regions.size() < numRegions) { int row = rand.nextInt(div); int col = rand.nextInt(div); - double maxLat = (row+1 < div) ? sector.getMinLatitude().degrees + dLat * row + dLat + double maxLat = (row + 1 < div) ? sector.getMinLatitude().degrees + dLat * row + dLat : sector.getMaxLatitude().degrees; - double maxLon = (col+1 < div) ? sector.getMinLongitude().degrees + dLon * col + dLon + double maxLon = (col + 1 < div) ? sector.getMinLongitude().degrees + dLon * col + dLon : sector.getMaxLongitude().degrees; Sector s = Sector.fromDegrees( - sector.getMinLatitude().degrees + dLat * row, maxLat, - sector.getMinLongitude().degrees + dLon * col, maxLon ); + sector.getMinLatitude().degrees + dLat * row, maxLat, + sector.getMinLongitude().degrees + dLon * col, maxLon); - if (!regions.contains(s)) + if (!regions.contains(s)) { regions.add(s); + } } return regions.toArray(new Sector[numRegions]); } - protected Iterator getRegionIterator(final Sector sector, final int div) - { + protected Iterator getRegionIterator(final Sector sector, final int div) { final double dLat = sector.getDeltaLat().degrees / div; final double dLon = sector.getDeltaLon().degrees / div; - return new Iterator() - { + return new Iterator() { int row = 0; int col = 0; - public boolean hasNext() - { + public boolean hasNext() { return row < div; } - public Sector next() - { - double maxLat = (row+1 < div) ? sector.getMinLatitude().degrees + dLat * row + dLat + public Sector next() { + double maxLat = (row + 1 < div) ? sector.getMinLatitude().degrees + dLat * row + dLat : sector.getMaxLatitude().degrees; - double maxLon = (col+1 < div) ? sector.getMinLongitude().degrees + dLon * col + dLon + double maxLon = (col + 1 < div) ? sector.getMinLongitude().degrees + dLon * col + dLon : sector.getMaxLongitude().degrees; Sector s = Sector.fromDegrees( - sector.getMinLatitude().degrees + dLat * row, maxLat, - sector.getMinLongitude().degrees + dLon * col, maxLon ); + sector.getMinLatitude().degrees + dLat * row, maxLat, + sector.getMinLongitude().degrees + dLon * col, maxLon); col++; - if (col >= div) - { + if (col >= div) { col = 0; row++; } return s; } - public void remove() - { + public void remove() { } }; } - protected boolean isTileLocalOrAbsent(Tile tile) - { - if (this.elevationModel.getLevels().isResourceAbsent(tile)) + protected boolean isTileLocalOrAbsent(Tile tile) { + if (this.elevationModel.getLevels().isResourceAbsent(tile)) { return true; // tile is absent - + } URL url = this.fileStore.findFile(tile.getPath(), false); return url != null && !this.elevationModel.isFileExpired(tile, url, this.fileStore); diff --git a/src/gov/nasa/worldwind/terrain/BasicElevationModelFactory.java b/src/gov/nasa/worldwind/terrain/BasicElevationModelFactory.java index bbd8c6181e..9955d36013 100644 --- a/src/gov/nasa/worldwind/terrain/BasicElevationModelFactory.java +++ b/src/gov/nasa/worldwind/terrain/BasicElevationModelFactory.java @@ -29,8 +29,8 @@ * @author tag * @version $Id: BasicElevationModelFactory.java 2347 2014-09-24 23:37:03Z dcollins $ */ -public class BasicElevationModelFactory extends BasicFactory -{ +public class BasicElevationModelFactory extends BasicFactory { + /** * Creates an elevation model from a general configuration source. The source can be one of the following:

                    *
                  • a {@link java.net.URL}
                  • a {@link java.io.File}
                  • a {@link java.io.InputStream}
                  • an @@ -44,22 +44,20 @@ public class BasicElevationModelFactory extends BasicFactory *
                  • "Offline" for elevation models that draw their data only from the local cache.
                  * * @param configSource the configuration source. See above for supported types. - * @param params properties to associate with the elevation model during creation. + * @param params properties to associate with the elevation model during creation. * * @return an elevation model. * * @throws IllegalArgumentException if the configuration file name is null or an empty string. - * @throws WWUnrecognizedException if the source type is unrecognized or the requested elevation-model type is - * unrecognized. - * @throws WWRuntimeException if object creation fails for other reasons. The exception identifying the source - * of the failure is included as the {@link Exception#initCause(Throwable)}. + * @throws WWUnrecognizedException if the source type is unrecognized or the requested elevation-model type is + * unrecognized. + * @throws WWRuntimeException if object creation fails for other reasons. The exception identifying the source of + * the failure is included as the {@link Exception#initCause(Throwable)}. */ @Override - public Object createFromConfigSource(Object configSource, AVList params) - { + public Object createFromConfigSource(Object configSource, AVList params) { ElevationModel model = (ElevationModel) super.createFromConfigSource(configSource, params); - if (model == null) - { + if (model == null) { String msg = Logging.getMessage("generic.UnrecognizedDocument", configSource); throw new WWUnrecognizedException(msg); } @@ -68,27 +66,24 @@ public Object createFromConfigSource(Object configSource, AVList params) } @Override - protected ElevationModel doCreateFromCapabilities(OGCCapabilities caps, AVList params) - { + protected ElevationModel doCreateFromCapabilities(OGCCapabilities caps, AVList params) { String serviceName = caps.getServiceInformation().getServiceName(); if (serviceName == null || !(serviceName.equalsIgnoreCase(OGCConstants.WMS_SERVICE_NAME) - || serviceName.equalsIgnoreCase("WMS"))) - { + || serviceName.equalsIgnoreCase("WMS"))) { String message = Logging.getMessage("WMS.NotWMSService", serviceName != null ? serviceName : "null"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } - if (params.getStringValue(AVKey.LAYER_NAMES) == null) - { + if (params.getStringValue(AVKey.LAYER_NAMES) == null) { // Use the first named layer since no other guidance given List namedLayers = ((WMSCapabilities) caps).getNamedLayers(); - if (namedLayers == null || namedLayers.size() == 0 || namedLayers.get(0) == null) - { + if (namedLayers == null || namedLayers.size() == 0 || namedLayers.get(0) == null) { String message = Logging.getMessage("WMS.NoLayersFound"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -100,8 +95,7 @@ protected ElevationModel doCreateFromCapabilities(OGCCapabilities caps, AVList p return new WMSBasicElevationModel((WMSCapabilities) caps, params); } - protected Object doCreateFromCapabilities(WCS100Capabilities caps, AVList params) - { + protected Object doCreateFromCapabilities(WCS100Capabilities caps, AVList params) { return new WCSElevationModel(caps, params); } @@ -110,7 +104,7 @@ protected Object doCreateFromCapabilities(WCS100Capabilities caps, AVList params * followed if it exists. * * @param domElement an XML element containing the elevation model description. - * @param params any parameters to apply when creating the elevation models. + * @param params any parameters to apply when creating the elevation models. * * @return the requested elevation model, or null if the specified element does not describe an elevation model. * @@ -118,27 +112,30 @@ protected Object doCreateFromCapabilities(WCS100Capabilities caps, AVList params * @see #createNonCompoundModel(org.w3c.dom.Element, gov.nasa.worldwind.avlist.AVList) */ @Override - protected ElevationModel doCreateFromElement(Element domElement, AVList params) throws Exception - { + protected ElevationModel doCreateFromElement(Element domElement, AVList params) throws Exception { Element element = WWXML.getElement(domElement, ".", null); - if (element == null) + if (element == null) { return null; + } String href = WWXML.getText(element, "@href"); - if (href != null && href.length() > 0) + if (href != null && href.length() > 0) { return (ElevationModel) this.createFromConfigSource(href, params); + } Element[] elements = WWXML.getElements(element, "./ElevationModel", null); String modelType = WWXML.getText(element, "@modelType"); - if (modelType != null && modelType.equalsIgnoreCase("compound")) + if (modelType != null && modelType.equalsIgnoreCase("compound")) { return this.createCompoundModel(elements, params); + } String localName = WWXML.getUnqualifiedName(domElement); - if (elements != null && elements.length > 0) + if (elements != null && elements.length > 0) { return this.createCompoundModel(elements, params); - else if (localName != null && localName.equals("ElevationModel")) + } else if (localName != null && localName.equals("ElevationModel")) { return this.createNonCompoundModel(domElement, params); + } return null; } @@ -150,30 +147,27 @@ else if (localName != null && localName.equals("ElevationModel")) * models associated with the exceptions are not included in the returned compound model. * * @param elements the XML elements describing the models in the new elevation model. - * @param params any parameters to apply when creating the elevation models. + * @param params any parameters to apply when creating the elevation models. * * @return a compound elevation model populated with the specified elevation models. The compound model will contain - * no elevation models if none were specified or exceptions occurred for all that were specified. + * no elevation models if none were specified or exceptions occurred for all that were specified. * * @see #createNonCompoundModel(org.w3c.dom.Element, gov.nasa.worldwind.avlist.AVList) */ - protected CompoundElevationModel createCompoundModel(Element[] elements, AVList params) - { + protected CompoundElevationModel createCompoundModel(Element[] elements, AVList params) { CompoundElevationModel compoundModel = new CompoundElevationModel(); - if (elements == null || elements.length == 0) + if (elements == null || elements.length == 0) { return compoundModel; + } - for (Element element : elements) - { - try - { + for (Element element : elements) { + try { ElevationModel em = this.doCreateFromElement(element, params); - if (em != null) + if (em != null) { compoundModel.addElevationModel(em); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = Logging.getMessage("ElevationModel.ExceptionCreatingElevationModel"); Logging.logger().log(java.util.logging.Level.WARNING, msg, e); } @@ -186,42 +180,30 @@ protected CompoundElevationModel createCompoundModel(Element[] elements, AVList * Create a simple elevation model. * * @param domElement the XML element describing the elevation model to create. The element must inculde a service - * name identifying the type of service to use to retrieve elevation data. Recognized service - * types are "Offline", "WWTileService" and "OGC:WMS". - * @param params any parameters to apply when creating the elevation model. + * name identifying the type of service to use to retrieve elevation data. Recognized service types are "Offline", + * "WWTileService" and "OGC:WMS". + * @param params any parameters to apply when creating the elevation model. * * @return a new elevation model * * @throws WWUnrecognizedException if the service type given in the describing element is unrecognized. */ - protected ElevationModel createNonCompoundModel(Element domElement, AVList params) - { + protected ElevationModel createNonCompoundModel(Element domElement, AVList params) { ElevationModel em; String serviceName = WWXML.getText(domElement, "Service/@serviceName"); - if (serviceName.equals("Offline")) - { + if (serviceName.equals("Offline")) { em = new BasicElevationModel(domElement, params); - } - else if (serviceName.equals("WWTileService")) - { + } else if (serviceName.equals("WWTileService")) { em = new BasicElevationModel(domElement, params); - } - else if (serviceName.equals(OGCConstants.WMS_SERVICE_NAME)) - { + } else if (serviceName.equals(OGCConstants.WMS_SERVICE_NAME)) { em = new WMSBasicElevationModel(domElement, params); - } - else if (serviceName.equals(OGCConstants.WCS_SERVICE_NAME)) - { + } else if (serviceName.equals(OGCConstants.WCS_SERVICE_NAME)) { em = new WCSElevationModel(domElement, params); - } - else if (AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER.equals(serviceName)) - { + } else if (AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER.equals(serviceName)) { em = new LocalRasterServerElevationModel(domElement, params); - } - else - { + } else { String msg = Logging.getMessage("generic.UnrecognizedServiceName", serviceName); throw new WWUnrecognizedException(msg); } diff --git a/src/gov/nasa/worldwind/terrain/BathymetryFilterElevationModel.java b/src/gov/nasa/worldwind/terrain/BathymetryFilterElevationModel.java index 6d2d1b75a7..89987c6aed 100644 --- a/src/gov/nasa/worldwind/terrain/BathymetryFilterElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/BathymetryFilterElevationModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.geom.*; @@ -21,8 +20,8 @@ * @author tag * @version $Id: BathymetryFilterElevationModel.java 2014 2014-05-20 19:46:55Z tgaskins $ */ -public class BathymetryFilterElevationModel extends AbstractElevationModel -{ +public class BathymetryFilterElevationModel extends AbstractElevationModel { + protected ElevationModel sourceModel; protected double threshold = 0d; @@ -31,15 +30,14 @@ public class BathymetryFilterElevationModel extends AbstractElevationModel * * @param source the elevation model to filter. */ - public BathymetryFilterElevationModel(ElevationModel source) - { + public BathymetryFilterElevationModel(ElevationModel source) { this.sourceModel = source; } - public void dispose() - { - if (this.sourceModel != null) + public void dispose() { + if (this.sourceModel != null) { this.sourceModel.dispose(); + } } /** @@ -47,8 +45,7 @@ public void dispose() * * @return the source elevation model. */ - public ElevationModel getSourceModel() - { + public ElevationModel getSourceModel() { return this.sourceModel; } @@ -57,8 +54,7 @@ public ElevationModel getSourceModel() * * @return the threshold. */ - public double getThreshold() - { + public double getThreshold() { return this.threshold; } @@ -66,88 +62,79 @@ public double getThreshold() * Sets the value of the threshold. The default threshold is 0. * * @param threshold the desired threshold. Elevations less than this value are set to this value prior to being - * return by any method returning one or more elevations. + * return by any method returning one or more elevations. */ - public void setThreshold(double threshold) - { + public void setThreshold(double threshold) { this.threshold = threshold; } - public double getMaxElevation() - { + public double getMaxElevation() { return this.clampElevation(this.sourceModel.getMaxElevation()); } - public double getMinElevation() - { + public double getMinElevation() { return this.clampElevation(this.sourceModel.getMinElevation()); } - public double[] getExtremeElevations(Angle latitude, Angle longitude) - { + public double[] getExtremeElevations(Angle latitude, Angle longitude) { double[] elevs = this.sourceModel.getExtremeElevations(latitude, longitude); - if (elevs == null) + if (elevs == null) { return elevs; + } - return new double[] {this.clampElevation(elevs[0]), this.clampElevation(elevs[1])}; + return new double[]{this.clampElevation(elevs[0]), this.clampElevation(elevs[1])}; } - public double[] getExtremeElevations(Sector sector) - { + public double[] getExtremeElevations(Sector sector) { double[] elevs = this.sourceModel.getExtremeElevations(sector); - if (elevs == null) + if (elevs == null) { return elevs; + } - return new double[] {this.clampElevation(elevs[0]), this.clampElevation(elevs[1])}; + return new double[]{this.clampElevation(elevs[0]), this.clampElevation(elevs[1])}; } - public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) - { + public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) { double resolution = this.sourceModel.getElevations(sector, latlons, targetResolution, buffer); - for (int i = 0; i < latlons.size(); i++) - { + for (int i = 0; i < latlons.size(); i++) { LatLon ll = latlons.get(i); - if (this.sourceModel.contains(ll.getLatitude(), ll.getLongitude()) && buffer[i] < this.threshold) + if (this.sourceModel.contains(ll.getLatitude(), ll.getLongitude()) && buffer[i] < this.threshold) { buffer[i] = this.threshold; + } } return resolution; } public double getUnmappedElevations(Sector sector, List latlons, double targetResolution, - double[] buffer) - { + double[] buffer) { double resolution = this.sourceModel.getElevations(sector, latlons, targetResolution, buffer); - for (int i = 0; i < latlons.size(); i++) - { + for (int i = 0; i < latlons.size(); i++) { LatLon ll = latlons.get(i); if (this.sourceModel.contains(ll.getLatitude(), ll.getLongitude()) - && buffer[i] != this.sourceModel.getMissingDataSignal() && buffer[i] < this.threshold) + && buffer[i] != this.sourceModel.getMissingDataSignal() && buffer[i] < this.threshold) { buffer[i] = this.threshold; + } } return resolution; } - public int intersects(Sector sector) - { + public int intersects(Sector sector) { return this.sourceModel.intersects(sector); } - public boolean contains(Angle latitude, Angle longitude) - { + public boolean contains(Angle latitude, Angle longitude) { return this.sourceModel.contains(latitude, longitude); } - public double getBestResolution(Sector sector) - { + public double getBestResolution(Sector sector) { return this.sourceModel.getBestResolution(sector); } - public double getUnmappedElevation(Angle latitude, Angle longitude) - { + public double getUnmappedElevation(Angle latitude, Angle longitude) { double elev = this.sourceModel.getUnmappedElevation(latitude, longitude); return elev != this.sourceModel.getMissingDataSignal() && elev < this.threshold ? this.threshold : elev; @@ -159,36 +146,31 @@ public double getUnmappedElevation(Angle latitude, Angle longitude) * @param elevation the elevation to check and map. * * @return the input elevation if it is greater than or equal to the threshold elevation, otherwise the threshold - * elevation. + * elevation. */ - protected double clampElevation(double elevation) - { + protected double clampElevation(double elevation) { return elevation < this.threshold ? this.threshold : elevation; } @Override - public double getLocalDataAvailability(Sector sector, Double targetResolution) - { + public double getLocalDataAvailability(Sector sector, Double targetResolution) { return this.sourceModel.getLocalDataAvailability(sector, targetResolution); } @Override - public Object getValue(String key) - { + public Object getValue(String key) { Object o = super.getValue(key); return o != null ? o : this.sourceModel != null ? this.sourceModel.getValue(key) : null; } @Override - public void setExtremesCachingEnabled(boolean enabled) - { + public void setExtremesCachingEnabled(boolean enabled) { this.sourceModel.setExtremesCachingEnabled(enabled); } @Override - public boolean isExtremesCachingEnabled() - { + public boolean isExtremesCachingEnabled() { return this.sourceModel.isExtremesCachingEnabled(); } } diff --git a/src/gov/nasa/worldwind/terrain/CompoundElevationModel.java b/src/gov/nasa/worldwind/terrain/CompoundElevationModel.java index 14679c8618..a01fd35e85 100644 --- a/src/gov/nasa/worldwind/terrain/CompoundElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/CompoundElevationModel.java @@ -16,16 +16,15 @@ * @author tag * @version $Id: CompoundElevationModel.java 3417 2015-08-20 20:47:05Z tgaskins $ */ -public class CompoundElevationModel extends AbstractElevationModel -{ +public class CompoundElevationModel extends AbstractElevationModel { + protected CopyOnWriteArrayList elevationModels = new CopyOnWriteArrayList(); - public void dispose() - { - for (ElevationModel child : this.elevationModels) - { - if (child != null) + public void dispose() { + for (ElevationModel child : this.elevationModels) { + if (child != null) { child.dispose(); + } } } @@ -38,48 +37,43 @@ public void dispose() * * @throws IllegalArgumentException if the ElevationModel is null. */ - public boolean containsElevationModel(ElevationModel em) - { - if (em == null) - { + public boolean containsElevationModel(ElevationModel em) { + if (em == null) { String msg = Logging.getMessage("nullValue.ElevationModelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // Check if the elevation model is one of the models in our list. - if (this.elevationModels.contains(em)) + if (this.elevationModels.contains(em)) { return true; + } // Check if the elevation model is a child of any CompoundElevationModels in our list. - for (ElevationModel child : this.elevationModels) - { - if (child instanceof CompoundElevationModel) - { - if (((CompoundElevationModel) child).containsElevationModel(em)) + for (ElevationModel child : this.elevationModels) { + if (child instanceof CompoundElevationModel) { + if (((CompoundElevationModel) child).containsElevationModel(em)) { return true; + } } } return false; } - protected void sortElevationModels() - { - if (this.elevationModels.size() == 1) + protected void sortElevationModels() { + if (this.elevationModels.size() == 1) { return; + } List temp = new ArrayList(this.elevationModels.size()); - for (ElevationModel em : this.elevationModels) - { + for (ElevationModel em : this.elevationModels) { temp.add(em); } - Collections.sort(temp, new Comparator() - { + Collections.sort(temp, new Comparator() { @Override - public int compare(ElevationModel o1, ElevationModel o2) - { + public int compare(ElevationModel o1, ElevationModel o2) { double res1 = o1.getBestResolution(null); double res2 = o2.getBestResolution(null); @@ -101,10 +95,8 @@ public int compare(ElevationModel o1, ElevationModel o2) * * @throws IllegalArgumentException if the specified elevation model is null. */ - public void addElevationModel(ElevationModel em) - { - if (em == null) - { + public void addElevationModel(ElevationModel em) { + if (em == null) { String msg = Logging.getMessage("nullValue.ElevationModelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -123,16 +115,14 @@ public void addElevationModel(ElevationModel em) * is the appropriate one for the inserted elevation model's resolution. * * @param index The position at which to insert the specified model, zero origin. Existing models are shifted to the - * right. - * @param em The elevation model to insert. + * right. + * @param em The elevation model to insert. * - * @throws IllegalArgumentException if the specified elevation model is null. + * @throws IllegalArgumentException if the specified elevation model is null. * @throws IndexOutOfBoundsException if the specified index is invalid. */ - public void addElevationModel(int index, ElevationModel em) - { - if (em == null) - { + public void addElevationModel(int index, ElevationModel em) { + if (em == null) { String msg = Logging.getMessage("nullValue.ElevationModelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -141,28 +131,24 @@ public void addElevationModel(int index, ElevationModel em) this.elevationModels.add(index, em); // the list's add method will throw exception for invalid index } - public void removeElevationModel(ElevationModel em) - { - if (em == null) - { + public void removeElevationModel(ElevationModel em) { + if (em == null) { String msg = Logging.getMessage("nullValue.ElevationModelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (ElevationModel child : this.elevationModels) - { - if (child instanceof CompoundElevationModel) + for (ElevationModel child : this.elevationModels) { + if (child instanceof CompoundElevationModel) { ((CompoundElevationModel) child).removeElevationModel(em); + } } this.elevationModels.remove(em); } - public void removeElevationModel(int index) - { - if (index < 0 || index >= this.elevationModels.size()) - { + public void removeElevationModel(int index) { + if (index < 0 || index >= this.elevationModels.size()) { String msg = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -171,17 +157,14 @@ public void removeElevationModel(int index) this.elevationModels.remove(index); } - public void setElevationModel(int index, ElevationModel em) - { - if (em == null) - { + public void setElevationModel(int index, ElevationModel em) { + if (em == null) { String msg = Logging.getMessage("nullValue.ElevationModelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (index < 0 || index >= this.elevationModels.size()) - { + if (index < 0 || index >= this.elevationModels.size()) { String msg = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -190,8 +173,7 @@ public void setElevationModel(int index, ElevationModel em) this.elevationModels.set(index, em); } - public List getElevationModels() - { + public List getElevationModels() { return new ArrayList(this.elevationModels); } @@ -203,12 +185,10 @@ public List getElevationModels() * * @see System#currentTimeMillis() for a description of milliseconds beyond the epoch. */ - public void setExpiryTime(long expiryTime) - { + public void setExpiryTime(long expiryTime) { super.setExpiryTime(expiryTime); - for (ElevationModel em : this.elevationModels) - { + for (ElevationModel em : this.elevationModels) { em.setExpiryTime(expiryTime); } } @@ -217,40 +197,39 @@ public double getMaxElevation() // TODO: probably want to cache the min and max { double max = -Double.MAX_VALUE; - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } double m = em.getMaxElevation(); - if (m > max) + if (m > max) { max = m; + } } return max == -Double.MAX_VALUE ? 0 : max; } - public double getMinElevation() - { + public double getMinElevation() { double min = Double.MAX_VALUE; - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } double m = em.getMinElevation(); - if (m < min) + if (m < min) { min = m; + } } return min == Double.MAX_VALUE ? 0 : min; } - public double[] getExtremeElevations(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double[] getExtremeElevations(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -258,32 +237,29 @@ public double[] getExtremeElevations(Angle latitude, Angle longitude) double[] retVal = null; - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } double[] minmax = em.getExtremeElevations(latitude, longitude); - if (retVal == null) - { - retVal = new double[] {minmax[0], minmax[1]}; - } - else - { - if (minmax[0] < retVal[0]) + if (retVal == null) { + retVal = new double[]{minmax[0], minmax[1]}; + } else { + if (minmax[0] < retVal[0]) { retVal[0] = minmax[0]; - if (minmax[1] > retVal[1]) + } + if (minmax[1] > retVal[1]) { retVal[1] = minmax[1]; + } } } - return retVal == null ? new double[] {0, 0} : retVal; + return retVal == null ? new double[]{0, 0} : retVal; } - public double[] getExtremeElevations(Sector sector) - { - if (sector == null) - { + public double[] getExtremeElevations(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -291,69 +267,68 @@ public double[] getExtremeElevations(Sector sector) double[] retVal = null; - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } int c = em.intersects(sector); if (c < 0) // no intersection + { continue; + } double[] minmax = em.getExtremeElevations(sector); - if (retVal == null) - { - retVal = new double[] {minmax[0], minmax[1]}; - } - else - { - if (minmax[0] < retVal[0]) + if (retVal == null) { + retVal = new double[]{minmax[0], minmax[1]}; + } else { + if (minmax[0] < retVal[0]) { retVal[0] = minmax[0]; - if (minmax[1] > retVal[1]) + } + if (minmax[1] > retVal[1]) { retVal[1] = minmax[1]; + } } } - return retVal == null ? new double[] {0, 0} : retVal; + return retVal == null ? new double[]{0, 0} : retVal; } - public double getBestResolution(Sector sector) - { + public double getBestResolution(Sector sector) { double res = 0; - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } if (sector != null && em.intersects(sector) < 0) // sector does not intersect elevation model + { continue; + } double r = em.getBestResolution(sector); - if (r < res || res == 0) + if (r < res || res == 0) { res = r; + } } return res != 0 ? res : Double.MAX_VALUE; } @Override - public double[] getBestResolutions(Sector sector) - { + public double[] getBestResolutions(Sector sector) { double[] res = new double[this.elevationModels.size()]; - for (int i = 0; i < this.elevationModels.size(); i++) - { + for (int i = 0; i < this.elevationModels.size(); i++) { res[i] = this.elevationModels.get(i).getBestResolution(sector); } return res; } - public double getDetailHint(Sector sector) - { - if (sector == null) - { + public double getDetailHint(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -365,22 +340,22 @@ public double getDetailHint(Sector sector) { ElevationModel em = this.elevationModels.get(i); - if (!em.isEnabled()) + if (!em.isEnabled()) { continue; + } int c = em.intersects(sector); - if (c != -1) + if (c != -1) { return em.getDetailHint(sector); + } } // No elevation model intersects the sector. Return a default detail hint. return 0.0; } - public int intersects(Sector sector) - { - if (sector == null) - { + public int intersects(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -388,47 +363,47 @@ public int intersects(Sector sector) boolean intersects = false; - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } int c = em.intersects(sector); if (c == 0) // sector fully contained in the elevation model. no need to test further + { return 0; + } - if (c == 1) + if (c == 1) { intersects = true; + } } return intersects ? 1 : -1; } - public boolean contains(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public boolean contains(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } - if (em.contains(latitude, longitude)) + if (em.contains(latitude, longitude)) { return true; + } } return false; } - public double getUnmappedElevation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getUnmappedElevation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -440,19 +415,20 @@ public double getUnmappedElevation(Angle latitude, Angle longitude) { ElevationModel em = this.elevationModels.get(i); - if (!em.isEnabled()) + if (!em.isEnabled()) { continue; + } - if (!em.contains(latitude, longitude)) + if (!em.contains(latitude, longitude)) { continue; + } double emValue = em.getUnmappedElevation(latitude, longitude); // Since we're working from highest resolution to lowest, we return the first value that's not a missing // data flag. Check this against the current ElevationModel's missing data flag, which might be different // from our own. - if (emValue != em.getMissingDataSignal()) - { + if (emValue != em.getMissingDataSignal()) { value = emValue; break; } @@ -468,24 +444,21 @@ public double getUnmappedElevation(Angle latitude, Angle longitude) * This enables the compound model's lower resolution elevation models to specify missing data values for the higher * resolution elevation models. * - * @param sector the sector in question. - * @param latlons the locations to return elevations for. If a location is null, the output buffer for that - * location is not modified. + * @param sector the sector in question. + * @param latlons the locations to return elevations for. If a location is null, the output buffer for that location + * is not modified. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) - * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and - * contain at least as many elements as the list of locations. + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) + * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and contain at + * least as many elements as the list of locations. * * @return the resolution achieved, in radians, or {@link Double#MAX_VALUE} if individual elevations cannot be * determined for all of the locations. */ - public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) - { + public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) { double[] targetResolutions = new double[this.elevationModels.size()]; - for (int i = 0; i < targetResolutions.length; i++) - { + for (int i = 0; i < targetResolutions.length; i++) { targetResolutions[i] = targetResolution; } @@ -499,25 +472,22 @@ public double getElevations(Sector sector, List latlons, doubl * This enables the compound model's lower resolution elevation models to specify missing data values for the higher * resolution elevation models. * - * @param sector the sector in question. - * @param latlons the locations to return elevations for. If a location is null, the output buffer for that - * location is not modified. + * @param sector the sector in question. + * @param latlons the locations to return elevations for. If a location is null, the output buffer for that location + * is not modified. * @param targetResolution the desired horizontal resolution, in radians, of the raster or other elevation sample - * from which elevations are drawn. (To compute radians from a distance, divide the distance - * by the radius of the globe, ensuring that both the distance and the radius are in the - * same units.) - * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and - * contain at least as many elements as the list of locations. + * from which elevations are drawn. (To compute radians from a distance, divide the distance by the radius of the + * globe, ensuring that both the distance and the radius are in the same units.) + * @param buffer an array in which to place the returned elevations. The array must be pre-allocated and contain at + * least as many elements as the list of locations. * * @return the resolution achieved, in radians, or {@link Double#MAX_VALUE} if individual elevations cannot be * determined for all of the locations. */ public double getUnmappedElevations(Sector sector, List latlons, double targetResolution, - double[] buffer) - { + double[] buffer) { double[] targetResolutions = new double[this.elevationModels.size()]; - for (int i = 0; i < targetResolutions.length; i++) - { + for (int i = 0; i < targetResolutions.length; i++) { targetResolutions[i] = targetResolution; } @@ -526,51 +496,43 @@ public double getUnmappedElevations(Sector sector, List latlon @Override public double[] getElevations(Sector sector, List latLons, double[] targetResolutions, - double[] elevations) - { + double[] elevations) { return this.doGetElevations(sector, latLons, targetResolutions, elevations, false); } @Override public double[] getUnmappedElevations(Sector sector, List latLons, double[] targetResolutions, - double[] elevations) - { + double[] elevations) { return this.doGetElevations(sector, latLons, targetResolutions, elevations, false); } protected double[] doGetElevations(Sector sector, List latlons, double[] targetResolution, - double[] buffer, boolean mapMissingData) - { - if (sector == null) - { + double[] buffer, boolean mapMissingData) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (latlons == null) - { + if (latlons == null) { String msg = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (targetResolution == null) - { + if (targetResolution == null) { String msg = Logging.getMessage("nullValue.TargetElevationsArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer == null) - { + if (buffer == null) { String msg = Logging.getMessage("nullValue.ElevationsBufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer.length < latlons.size()) - { + if (buffer.length < latlons.size()) { String msg = Logging.getMessage("ElevationModel.ElevationsBufferTooSmall", latlons.size()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -580,57 +542,56 @@ protected double[] doGetElevations(Sector sector, List latlons // values at each step. ElevationModels are expected to leave the buffer untouched for locations outside their // coverage area. double[] resolutionAchieved = new double[this.elevationModels.size()]; - for (int i = 0; i < this.elevationModels.size(); i++) - { + for (int i = 0; i < this.elevationModels.size(); i++) { ElevationModel em = this.elevationModels.get(i); resolutionAchieved[i] = 0; - if (!em.isEnabled()) + if (!em.isEnabled()) { continue; + } int c = em.intersects(sector); if (c < 0) // no intersection + { continue; + } double r; - if (mapMissingData || this.elevationModels.size() == 1) + if (mapMissingData || this.elevationModels.size() == 1) { r = em.getElevations(sector, latlons, targetResolution[i], buffer); - else + } else { r = em.getUnmappedElevations(sector, latlons, targetResolution[i], buffer); + } - if (r < resolutionAchieved[i] || resolutionAchieved[i] == 0) + if (r < resolutionAchieved[i] || resolutionAchieved[i] == 0) { resolutionAchieved[i] = r; + } } return resolutionAchieved; } public void composeElevations(Sector sector, List latlons, int tileWidth, - double[] buffer) throws Exception - { - if (sector == null) - { + double[] buffer) throws Exception { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (latlons == null) - { + if (latlons == null) { String msg = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer == null) - { + if (buffer == null) { String msg = Logging.getMessage("nullValue.ElevationsBufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer.length < latlons.size()) - { + if (buffer.length < latlons.size()) { String msg = Logging.getMessage("ElevationModel.ElevationsBufferTooSmall", latlons.size()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -638,42 +599,40 @@ public void composeElevations(Sector sector, List latlons, int // Fill the buffer with ElevationModel contents from back to front, potentially overwriting values at each step. // ElevationModels are expected to leave the buffer untouched when data is missing at a location. - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } int c = em.intersects(sector); if (c < 0) // no intersection + { continue; + } em.composeElevations(sector, latlons, tileWidth, buffer); } } - public void setNetworkRetrievalEnabled(boolean networkRetrievalEnabled) - { + public void setNetworkRetrievalEnabled(boolean networkRetrievalEnabled) { super.setNetworkRetrievalEnabled(networkRetrievalEnabled); - for (ElevationModel em : this.elevationModels) - { + for (ElevationModel em : this.elevationModels) { em.setNetworkRetrievalEnabled(networkRetrievalEnabled); } } @Override - public double getLocalDataAvailability(Sector sector, Double targetResolution) - { + public double getLocalDataAvailability(Sector sector, Double targetResolution) { int models = 0; double availability = 0; - for (ElevationModel em : this.elevationModels) - { - if (!em.isEnabled()) + for (ElevationModel em : this.elevationModels) { + if (!em.isEnabled()) { continue; + } - if (em.intersects(sector) >= 0) - { + if (em.intersects(sector) >= 0) { availability += em.getLocalDataAvailability(sector, targetResolution); models++; } @@ -683,21 +642,18 @@ public double getLocalDataAvailability(Sector sector, Double targetResolution) } @Override - public void setExtremesCachingEnabled(boolean enabled) - { - for (ElevationModel em : this.elevationModels) - { + public void setExtremesCachingEnabled(boolean enabled) { + for (ElevationModel em : this.elevationModels) { em.setExtremesCachingEnabled(enabled); } } @Override - public boolean isExtremesCachingEnabled() - { - for (ElevationModel em : this.elevationModels) - { - if (em.isExtremesCachingEnabled()) + public boolean isExtremesCachingEnabled() { + for (ElevationModel em : this.elevationModels) { + if (em.isExtremesCachingEnabled()) { return true; + } } return false; @@ -705,27 +661,24 @@ public boolean isExtremesCachingEnabled() /** * Returns the elevation for this elevation model's highest level of detail at a specified location if the source - * file for that level and the specified location exists in the local elevation cache on disk. - * Note that this method consults only those elevation models whose type is {@link BasicElevationModel}. + * file for that level and the specified location exists in the local elevation cache on disk. Note that this method + * consults only those elevation models whose type is {@link BasicElevationModel}. + * * @param latitude The latitude of the location whose elevation is desired. * @param longitude The longitude of the location whose elevation is desired. * @return The elevation at the specified location, if that location is contained in this elevation model and the * source file for the highest-resolution elevation at that location exists in the current disk cache. Otherwise * this elevation model's missing data signal is returned (see {@link #getMissingDataSignal()}). */ - public double getUnmappedLocalSourceElevation(Angle latitude, Angle longitude) - { + public double getUnmappedLocalSourceElevation(Angle latitude, Angle longitude) { double elevation = this.getMissingDataSignal(); // Traverse the elevation model list from highest resolution to lowest. - for (int i = this.elevationModels.size() - 1; i >= 0; i--) - { + for (int i = this.elevationModels.size() - 1; i >= 0; i--) { ElevationModel em = this.elevationModels.get(i); - if (em instanceof BasicElevationModel && em.isEnabled()) - { + if (em instanceof BasicElevationModel && em.isEnabled()) { double e = ((BasicElevationModel) em).getUnmappedLocalSourceElevation(latitude, longitude); - if (e != em.getMissingDataSignal()) - { + if (e != em.getMissingDataSignal()) { elevation = e; break; } diff --git a/src/gov/nasa/worldwind/terrain/HighResolutionTerrain.java b/src/gov/nasa/worldwind/terrain/HighResolutionTerrain.java index 9c62d28b99..b9264f67b8 100644 --- a/src/gov/nasa/worldwind/terrain/HighResolutionTerrain.java +++ b/src/gov/nasa/worldwind/terrain/HighResolutionTerrain.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.*; @@ -27,19 +26,20 @@ * @author tag * @version $Id: HighResolutionTerrain.java 3420 2015-09-10 23:25:43Z tgaskins $ */ -public class HighResolutionTerrain extends WWObjectImpl implements Terrain -{ - /** Holds a tile's geometry. It's heavyweight so cached when created to enable re-use. */ - protected static class RenderInfo - { +public class HighResolutionTerrain extends WWObjectImpl implements Terrain { + + /** + * Holds a tile's geometry. It's heavyweight so cached when created to enable re-use. + */ + protected static class RenderInfo { + protected final int density; protected final Vec4 referenceCenter; // all vertices are relative to this point protected final float[] vertices; protected Position minElevation; protected Position maxElevation; - protected RenderInfo(int density, float[] vertices, Vec4 refCenter, Position minElev, Position maxElev) - { + protected RenderInfo(int density, float[] vertices, Vec4 refCenter, Position minElev, Position maxElev) { this.density = density; this.referenceCenter = refCenter; this.vertices = vertices; @@ -47,8 +47,7 @@ protected RenderInfo(int density, float[] vertices, Vec4 refCenter, Position min this.maxElevation = maxElev; } - protected long getSizeInBytes() - { + protected long getSizeInBytes() { // 2 references, an int, and vertices. (indices are shared among all tiles) // System.out.println(2 * 4 + 4 + this.vertices.length * 3 * 4); return 2 * 4 + 4 + this.vertices.length * 3 * 4; // 588 bytes at a density of 3 @@ -61,15 +60,14 @@ protected long getSizeInBytes() * independent of a particular RectTile instance. Current and future RectTile instances use the same cached geometry * instance. */ - protected static class RectTile - { + protected static class RectTile { + protected final Sector sector; protected final int density; protected Extent extent; // extent of sector in object coordinates protected RenderInfo ri; - public RectTile(Extent extent, int density, Sector sector) - { + public RectTile(Extent extent, int density, Sector sector) { this.density = density; this.sector = sector; this.extent = extent; @@ -98,33 +96,29 @@ public RectTile(Extent extent, int density, Sector sector) /** * Constructs a terrain object for a specified globe. * - * @param globe the terrain's globe. + * @param globe the terrain's globe. * @param targetResolution the target terrain resolution, in meters, or null to use the globe's highest resolution. * * @throws IllegalArgumentException if the globe is null. */ - public HighResolutionTerrain(Globe globe, Double targetResolution) - { + public HighResolutionTerrain(Globe globe, Double targetResolution) { this(globe, null, targetResolution, null); } /** * Constructs a terrain object for a specified sector of a specified globe. * - * @param globe the terrain's globe. - * @param sector the desired range for the terrain. Only locations within this sector may be used in - * operations. If null, the sector spans the entire globe. - * @param targetResolution the target terrain resolution, in meters, or null to use the globe's highest - * resolution. + * @param globe the terrain's globe. + * @param sector the desired range for the terrain. Only locations within this sector may be used in operations. If + * null, the sector spans the entire globe. + * @param targetResolution the target terrain resolution, in meters, or null to use the globe's highest resolution. * @param verticalExaggeration the vertical exaggeration to apply to terrain elevations. Null indicates no - * exaggeration. + * exaggeration. * * @throws IllegalArgumentException if the globe is null. */ - public HighResolutionTerrain(Globe globe, Sector sector, Double targetResolution, Double verticalExaggeration) - { - if (globe == null) - { + public HighResolutionTerrain(Globe globe, Sector sector, Double targetResolution, Double verticalExaggeration) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -133,10 +127,11 @@ public HighResolutionTerrain(Globe globe, Sector sector, Double targetResolution this.globe = globe; this.sector = sector != null ? sector : Sector.FULL_SPHERE; - if (targetResolution != null) + if (targetResolution != null) { this.targetResolution = targetResolution / this.globe.getRadius(); - else + } else { this.targetResolution = this.globe.getElevationModel().getBestResolution(null); + } this.verticalExaggeration = verticalExaggeration != null ? verticalExaggeration : 1; @@ -160,8 +155,7 @@ public HighResolutionTerrain(Globe globe, Sector sector, Double targetResolution * * @return the fraction of the cache currently used: a number between 0 and 1. */ - public double getCacheUsage() - { + public double getCacheUsage() { return this.geometryCache.getUsedCapacity() / (double) this.geometryCache.getCapacity(); } @@ -170,8 +164,7 @@ public double getCacheUsage() * * @return the number of entries currently in the cache.s */ - public int getNumCacheEntries() - { + public int getNumCacheEntries() { return this.geometryCache.getNumObjects(); } @@ -180,8 +173,7 @@ public int getNumCacheEntries() * * @return the globe specified to the constructor. */ - public Globe getGlobe() - { + public Globe getGlobe() { return globe; } @@ -191,13 +183,11 @@ public Globe getGlobe() * @return the object's sector, either the sector specified at construction or the default sector if no sector was * specified at construction. */ - public Sector getSector() - { + public Sector getSector() { return sector; } - public double getTargetResolution() - { + public double getTargetResolution() { return targetResolution; } @@ -206,8 +196,7 @@ public double getTargetResolution() * * @return the vertical exaggeration. The default is 1: no exaggeration. */ - public double getVerticalExaggeration() - { + public double getVerticalExaggeration() { return this.verticalExaggeration; } @@ -218,8 +207,7 @@ public double getVerticalExaggeration() * * @see #setTimeout(Long) */ - public synchronized Long getTimeout() - { + public synchronized Long getTimeout() { return this.timeout; } @@ -229,15 +217,13 @@ public synchronized Long getTimeout() * timeout is exceeded. * * @param timeout the number of milliseconds to wait. May be null, to indicate that operations have unlimited amount - * of time to operate. + * of time to operate. */ - public synchronized void setTimeout(Long timeout) - { + public synchronized void setTimeout(Long timeout) { this.timeout = timeout; } - public int getDensity() - { + public int getDensity() { return density; } @@ -248,8 +234,7 @@ public int getDensity() * * @param density the number of intervals used to form a terrain tile. */ - public void setDensity(int density) - { + public void setDensity(int density) { this.density = density; this.computeDimensions(); } @@ -259,8 +244,7 @@ public void setDensity(int density) * * @return the current cache capacity, in bytes. */ - public long getCacheCapacity() - { + public long getCacheCapacity() { return this.geometryCache.getCapacity(); } @@ -269,58 +253,54 @@ public long getCacheCapacity() * * @param size the cache capacity, in bytes. Values less than 1 MB are clamped to 1 MB. */ - public void setCacheCapacity(long size) - { + public void setCacheCapacity(long size) { this.geometryCache.setCapacity(Math.max(size, (long) 1e6)); } - /** {@inheritDoc} */ - public Vec4 getSurfacePoint(Position position) - { + /** + * {@inheritDoc} + */ + public Vec4 getSurfacePoint(Position position) { return this.getSurfacePoint(position.getLatitude(), position.getLongitude(), position.getAltitude()); } - /** {@inheritDoc} */ - public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset) - { - if (latitude == null || longitude == null) - { + /** + * {@inheritDoc} + */ + public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - try - { + try { this.startTime.set(System.currentTimeMillis()); RectTile tile = this.getContainingTile(latitude, longitude); return tile != null ? this.getSurfacePoint(tile, latitude, longitude, metersOffset) : null; - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { throw new WWRuntimeException(e); - } - finally - { + } finally { this.startTime.set(null); // signals that no operation is active } } - /** {@inheritDoc} */ - public Double getElevation(LatLon location) - { - if (location == null) - { + /** + * {@inheritDoc} + */ + public Double getElevation(LatLon location) { + if (location == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Vec4 pt = this.getSurfacePoint(location.getLatitude(), location.getLongitude(), 0); - if (pt == null) + if (pt == null) { return null; + } Vec4 p = this.globe.computePointFromPosition(location.getLatitude(), location.getLongitude(), 0); @@ -341,10 +321,8 @@ public Double getElevation(LatLon location) * * @deprecated */ - public Intersection[] intersect(Line line) - { - if (line == null) - { + public Intersection[] intersect(Line line) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -352,50 +330,45 @@ public Intersection[] intersect(Line line) // We need to get two positions to pass to the actual intersection calculator. Make one of those the line's // origin. Make the other the intersection point of the line with the globe's ellipsoid. - // Get the position of the line's origin. Position pA = this.globe.computePositionFromPoint(line.getOrigin()); Intersection[] ellipsoidIntersections = this.globe.intersect(line, 0); - if (ellipsoidIntersections == null || ellipsoidIntersections.length == 0) + if (ellipsoidIntersections == null || ellipsoidIntersections.length == 0) { return null; + } Position pB = this.globe.computePositionFromPoint(ellipsoidIntersections[0].getIntersectionPoint()); return this.intersect(pA, pB); } - /** {@inheritDoc} */ - public Intersection[] intersect(Position pA, Position pB) - { - if (pA == null || pB == null) - { + /** + * {@inheritDoc} + */ + public Intersection[] intersect(Position pA, Position pB) { + if (pA == null || pB == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - try - { + try { this.startTime.set(System.currentTimeMillis()); return this.doIntersect(pA, pB); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { throw new WWRuntimeException(e); - } - finally - { + } finally { this.startTime.set(null); // signals that no operation is active } } - /** {@inheritDoc} */ - public Intersection[] intersect(Position pA, Position pB, int altitudeMode) - { - if (pA == null || pB == null) - { + /** + * {@inheritDoc} + */ + public Intersection[] intersect(Position pA, Position pB, int altitudeMode) { + if (pA == null || pB == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -404,13 +377,10 @@ public Intersection[] intersect(Position pA, Position pB, int altitudeMode) // The intersect method expects altitudes to be relative to ground, so make them so if they aren't already. double altitudeA = pA.getAltitude(); double altitudeB = pB.getAltitude(); - if (altitudeMode == WorldWind.ABSOLUTE) - { + if (altitudeMode == WorldWind.ABSOLUTE) { altitudeA -= this.getElevation(pA); altitudeB -= this.getElevation(pB); - } - else if (altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + } else if (altitudeMode == WorldWind.CLAMP_TO_GROUND) { altitudeA = 0; altitudeB = 0; } @@ -418,15 +388,17 @@ else if (altitudeMode == WorldWind.CLAMP_TO_GROUND) return this.intersect(new Position(pA, altitudeA), new Position(pB, altitudeB)); } - /** Defines an interface for returning computed intersections. */ - public interface IntersectionCallback - { + /** + * Defines an interface for returning computed intersections. + */ + public interface IntersectionCallback { + /** * Called with the computed intersections for a line. This method is called only for lines along which * intersections occur. * - * @param pA The line's start point. - * @param pB The line's end point. + * @param pA The line's start point. + * @param pB The line's end point. * @param intersections An array of intersections. */ void intersection(Position pA, Position pB, Intersection[] intersections); @@ -443,36 +415,27 @@ public interface IntersectionCallback * Intersects a specified list of geographic two-position lines with the terrain. * * @param positions The positions to intersect, with the line segments formed by each pair of positions, e.g. the - * first line in formed by positions[0] and positions[1], the second by positions[2] and - * positions[3], etc. - * @param callback An object to call in order to return the computed intersections. + * first line in formed by positions[0] and positions[1], the second by positions[2] and positions[3], etc. + * @param callback An object to call in order to return the computed intersections. * * @throws InterruptedException if the operation is interrupted. */ - public void intersect(List positions, final IntersectionCallback callback) throws InterruptedException - { + public void intersect(List positions, final IntersectionCallback callback) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(10); - for (int i = 0; i < positions.size(); i += 2) - { + for (int i = 0; i < positions.size(); i += 2) { final Position pA = positions.get(i); final Position pB = positions.get(i + 1); - service.submit(new Runnable() - { + service.submit(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { Intersection[] intersections = intersect(pA, pB); - if (intersections != null) - { + if (intersections != null) { callback.intersection(pA, pB, intersections); } - } - catch (Exception e) - { + } catch (Exception e) { callback.exception(e); } } @@ -494,40 +457,35 @@ public void run() * @param pB the line's second position. * * @throws IllegalArgumentException if either position is null. - * @throws InterruptedException if the operation is interrupted. if the current timeout is exceeded while - * retrieving terrain data. + * @throws InterruptedException if the operation is interrupted. if the current timeout is exceeded while retrieving + * terrain data. */ - public void cacheIntersectingTiles(Position pA, Position pB) throws InterruptedException - { - if (pA == null || pB == null) - { + public void cacheIntersectingTiles(Position pA, Position pB) throws InterruptedException { + if (pA == null || pB == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Line line = this.makeLineFromPositions(pA, pB); - if (line == null) + if (line == null) { return; + } - try - { + try { this.startTime.set(System.currentTimeMillis()); List tiles = this.getIntersectingTiles(pA, pB, line); - if (tiles == null) + if (tiles == null) { return; + } - for (RectTile tile : tiles) - { - if (tile.ri == null) - { + for (RectTile tile : tiles) { + if (tile.ri == null) { this.makeVerts(tile); } } - } - finally - { + } finally { this.startTime.set(null); // signals that no operation is active } } @@ -542,60 +500,56 @@ public void cacheIntersectingTiles(Position pA, Position pB) throws InterruptedE * @param sector the sector for which to cache elevation data. * * @throws IllegalArgumentException if the specified sector is null. - * @throws InterruptedException if the operation is interrupted. if the current timeout is exceeded while - * retrieving terrain data. + * @throws InterruptedException if the operation is interrupted. if the current timeout is exceeded while retrieving + * terrain data. */ - public void cacheIntersectingTiles(Sector sector) throws InterruptedException - { - if (sector == null) - { + public void cacheIntersectingTiles(Sector sector) throws InterruptedException { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - try - { + try { this.startTime.set(System.currentTimeMillis()); List tiles = this.getIntersectingTiles(sector); - if (tiles == null) + if (tiles == null) { return; + } - for (RectTile tile : tiles) - { + for (RectTile tile : tiles) { this.makeVerts(tile); } - } - finally - { + } finally { this.startTime.set(null); // signals that no operation is active } } - public List getIntersectionTiles(Position pA, Position pB) throws InterruptedException - { + public List getIntersectionTiles(Position pA, Position pB) throws InterruptedException { Line line = this.makeLineFromPositions(pA, pB); - if (line == null) + if (line == null) { return null; + } List tiles = this.getIntersectingTiles(pA, pB, line); - if (tiles == null || tiles.size() == 0) + if (tiles == null || tiles.size() == 0) { return null; + } List sectors = new ArrayList(tiles.size()); - for (RectTile tile : tiles) - { + for (RectTile tile : tiles) { sectors.add(tile.sector); } return sectors; } - /** Computes the row and column dimensions of the tile array. */ - protected void computeDimensions() - { + /** + * Computes the row and column dimensions of the tile array. + */ + protected void computeDimensions() { double resTarget = Math.max(this.globe.getElevationModel().getBestResolution(null), this.targetResolution); this.numCols = (int) Math.ceil(this.sector.getDeltaLonRadians() / (this.density * resTarget)); @@ -604,22 +558,23 @@ protected void computeDimensions() this.lonTileSize = this.sector.getDeltaLonDegrees() / (this.numCols - 1); this.latTileSize = this.sector.getDeltaLatDegrees() / (this.numRows - 1); - if (this.geometryCache != null) + if (this.geometryCache != null) { this.geometryCache.clear(); + } } /** * Determines the tile that contains a specified location. * - * @param latitude the location's latitude. + * @param latitude the location's latitude. * @param longitude the location's longitude. * * @return the tile containing the specified location. */ - protected RectTile getContainingTile(Angle latitude, Angle longitude) - { - if (!this.sector.contains(latitude, longitude)) + protected RectTile getContainingTile(Angle latitude, Angle longitude) { + if (!this.sector.contains(latitude, longitude)) { return null; + } int row = this.computeRow(this.sector, latitude); int col = this.computeColumn(this.sector, longitude); @@ -635,10 +590,10 @@ protected RectTile getContainingTile(Angle latitude, Angle longitude) * * @return the tile for the specified row and column, or null if the row or column are invalid. */ - protected RectTile createTile(int row, int col) - { - if (row < 0 || col < 0 || row >= this.numRows || col >= this.numCols) + protected RectTile createTile(int row, int col) { + if (row < 0 || col < 0 || row >= this.numRows || col >= this.numCols) { return null; + } double minLon = Math.max(this.sector.getMinLongitude().degrees + col * this.lonTileSize, -180); double maxLon = Math.min(minLon + this.lonTileSize, 180); @@ -656,8 +611,7 @@ protected RectTile createTile(int row, int col) * * @return the tile for the sector, or null if the sector is outside this instance's sector. */ - protected RectTile createTile(Sector tileSector) - { + protected RectTile createTile(Sector tileSector) { Extent extent = Sector.computeBoundingBox(this.globe, this.verticalExaggeration, tileSector); return new RectTile(extent, this.density, tileSector); @@ -666,13 +620,12 @@ protected RectTile createTile(Sector tileSector) /** * Computes the row index corresponding to a specified latitude. * - * @param range the reference sector, typically that of this terrain instance. + * @param range the reference sector, typically that of this terrain instance. * @param latitude the latitude in question. * * @return the row index for the sector. */ - protected int computeRow(Sector range, Angle latitude) - { + protected int computeRow(Sector range, Angle latitude) { double top = range.getMaxLatitude().degrees; double bot = range.getMinLatitude().degrees; @@ -684,13 +637,12 @@ protected int computeRow(Sector range, Angle latitude) /** * Computes the column index corresponding to a specified latitude. * - * @param range the reference sector, typically that of this terrain instance. + * @param range the reference sector, typically that of this terrain instance. * @param longitude the latitude in question. * * @return the column index for the sector. */ - protected int computeColumn(Sector range, Angle longitude) - { + protected int computeColumn(Sector range, Angle longitude) { double right = range.getMaxLongitude().degrees; double left = range.getMinLongitude().degrees; @@ -699,10 +651,8 @@ protected int computeColumn(Sector range, Angle longitude) return (int) (s * (double) (this.numCols - 1)); } - protected Line makeLineFromPositions(Position pA, Position pB) throws InterruptedException - { - if (pA == null || pB == null) - { + protected Line makeLineFromPositions(Position pA, Position pB) throws InterruptedException { + if (pA == null || pB == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -710,17 +660,20 @@ protected Line makeLineFromPositions(Position pA, Position pB) throws Interrupte RectTile tileA = this.getContainingTile(pA.getLatitude(), pA.getLongitude()); RectTile tileB = this.getContainingTile(pB.getLatitude(), pB.getLongitude()); - if (tileA == null || tileB == null) + if (tileA == null || tileB == null) { return null; + } Vec4 ptA = this.getSurfacePoint(tileA, pA.getLatitude(), pA.getLongitude(), pA.getAltitude()); Vec4 ptB = this.getSurfacePoint(tileB, pB.getLatitude(), pB.getLongitude(), pB.getAltitude()); - if (ptA == null || ptB == null) + if (ptA == null || ptB == null) { return null; + } if (pA.getLatitude().equals(pB.getLatitude()) && pA.getLongitude().equals(pB.getLongitude()) - && pA.getAltitude() == pB.getAltitude()) + && pA.getAltitude() == pB.getAltitude()) { return null; + } return new Line(ptA, ptB.subtract3(ptA)); } @@ -735,44 +688,48 @@ protected Line makeLineFromPositions(Position pA, Position pB) throws Interrupte * * @throws InterruptedException if the operation is interrupted. */ - protected Intersection[] doIntersect(Position pA, Position pB) throws InterruptedException - { + protected Intersection[] doIntersect(Position pA, Position pB) throws InterruptedException { Line line = this.makeLineFromPositions(pA, pB); - if (line == null) + if (line == null) { return null; + } List tiles = this.getIntersectingTiles(pA, pB, line); - if (tiles == null) + if (tiles == null) { return null; + } Intersection[] hits; ArrayList list = new ArrayList(); - for (RectTile tile : tiles) - { - if ((hits = this.intersect(tile, line)) != null) + for (RectTile tile : tiles) { + if ((hits = this.intersect(tile, line)) != null) { list.addAll(Arrays.asList(hits)); + } } - if (list.size() == 0) + if (list.size() == 0) { return null; + } hits = new Intersection[list.size()]; list.toArray(hits); - if (list.size() == 1) + if (list.size() == 1) { return hits; + } final Vec4 origin = line.getOrigin(); - Arrays.sort(hits, new Comparator() - { - public int compare(Intersection i1, Intersection i2) - { - if (i1 == null && i2 == null) + Arrays.sort(hits, new Comparator() { + public int compare(Intersection i1, Intersection i2) { + if (i1 == null && i2 == null) { return 0; - if (i2 == null) + } + if (i2 == null) { return -1; - if (i1 == null) + } + if (i1 == null) { return 1; + } Vec4 v1 = i1.getIntersectionPoint(); Vec4 v2 = i2.getIntersectionPoint(); @@ -785,8 +742,7 @@ public int compare(Intersection i1, Intersection i2) return hits; } - protected List getIntersectingTiles(Sector sector) - { + protected List getIntersectingTiles(Sector sector) { int rowA = this.computeRow(this.sector, sector.getMinLatitude()); int colA = this.computeColumn(this.sector, sector.getMinLongitude()); int rowB = this.computeRow(this.sector, sector.getMaxLatitude()); @@ -795,10 +751,8 @@ protected List getIntersectingTiles(Sector sector) int n = (1 + (rowB - rowA)) * (1 + (colB - colA)); List tiles = new ArrayList(n); - for (int col = colA; col <= colB; col++) - { - for (int row = rowA; row <= rowB; row++) - { + for (int col = colA; col <= colB; col++) { + for (int row = rowA; row <= rowB; row++) { tiles.add(this.createTile(row, col)); } } @@ -809,36 +763,32 @@ protected List getIntersectingTiles(Sector sector) /** * Determines and creates the terrain tiles intersected by a specified line. * - * @param pA the line's first position. - * @param pB the line's second position. + * @param pA the line's first position. + * @param pB the line's second position. * @param line the line to intersect * * @return a list of tiles that likely intersect the line. Some returned tiles may not intersect the line but will * only be near it. */ - protected List getIntersectingTiles(Position pA, Position pB, Line line) - { + protected List getIntersectingTiles(Position pA, Position pB, Line line) { // Turn off elevation min/max caching in the elevation model because searching for the intersecting tiles // generates a lot of elevation min/max request that often overflows the elevation model's cache. boolean oldCachingMode = this.getGlobe().getElevationModel().isExtremesCachingEnabled(); this.getGlobe().getElevationModel().setExtremesCachingEnabled(false); - try - { + try { int rowA = this.computeRow(this.sector, pA.getLatitude()); int colA = this.computeColumn(this.sector, pA.getLongitude()); int rowB = this.computeRow(this.sector, pB.getLatitude()); int colB = this.computeColumn(this.sector, pB.getLongitude()); - if (rowB < rowA) - { + if (rowB < rowA) { int temp = rowA; rowA = rowB; rowB = temp; } - if (colB < colA) - { + if (colB < colA) { int temp = colA; colA = colB; colB = temp; @@ -849,31 +799,28 @@ protected List getIntersectingTiles(Position pA, Position pB, Line lin this.doGetIntersectingTiles(rowA, colA, rowB, colB, line, tiles); return tiles.size() > 0 ? tiles : null; - } - finally - { + } finally { this.getGlobe().getElevationModel().setExtremesCachingEnabled(oldCachingMode); } } - protected void doGetIntersectingTiles(int r0, int c0, int r1, int c1, Line line, List tiles) - { + protected void doGetIntersectingTiles(int r0, int c0, int r1, int c1, Line line, List tiles) { double minLat = this.sector.getMinLatitude().degrees + r0 * this.latTileSize; double maxLat = this.sector.getMinLatitude().degrees + (r1 + 1) * this.latTileSize; double minLon = this.sector.getMinLongitude().degrees + c0 * this.lonTileSize; double maxLon = this.sector.getMinLongitude().degrees + (c1 + 1) * this.lonTileSize; Extent extent = Sector.computeBoundingBox(this.globe, this.verticalExaggeration, - Sector.fromDegrees(minLat, maxLat, minLon, maxLon)); + Sector.fromDegrees(minLat, maxLat, minLon, maxLon)); - if (!extent.intersects(line)) + if (!extent.intersects(line)) { return; + } int m = c1 - c0 + 1; int n = r1 - r0 + 1; - if (m == 1 && n == 1) - { + if (m == 1 && n == 1) { tiles.add(this.createTile(r0, c0)); return; } @@ -883,13 +830,16 @@ protected void doGetIntersectingTiles(int r0, int c0, int r1, int c1, Line line, // only one row, the NW subdivision is identical to the SW one and need not be tested. In either case (one // column or 1 row) the NE subdivision need not be tested. this.doGetIntersectingTiles(r0, c0, r0 + Math.max(0, n / 2 - 1), c0 + Math.max(0, m / 2 - 1), line, - tiles); // SW - if (m != 1) + tiles); // SW + if (m != 1) { this.doGetIntersectingTiles(r0, c0 + m / 2, r0 + Math.max(0, n / 2 - 1), c1, line, tiles); // SE - if (n != 1) + } + if (n != 1) { this.doGetIntersectingTiles(r0 + n / 2, c0, r1, c0 + Math.max(0, m / 2 - 1), line, tiles); // NW - if (!(m == 1 || n == 1)) + } + if (!(m == 1 || n == 1)) { this.doGetIntersectingTiles(r0 + n / 2, c0 + m / 2, r1, c1, line, tiles); // NE + } } /** @@ -897,19 +847,18 @@ protected void doGetIntersectingTiles(int r0, int c0, int r1, int c1, Line line, * * @param tile the tile to compute vertices for * - * @throws InterruptedException if the operation is interrupted. + * @throws InterruptedException if the operation is interrupted. * @throws gov.nasa.worldwind.exception.WWTimeoutException if terrain data retrieval exceeds the current timeout. */ - protected void makeVerts(RectTile tile) throws InterruptedException - { + protected void makeVerts(RectTile tile) throws InterruptedException { // First see if the vertices have been previously computed and are in the cache. tile.ri = (RenderInfo) this.geometryCache.getObject(tile.sector); - if (tile.ri != null) + if (tile.ri != null) { return; + } tile.ri = this.buildVerts(tile); - if (tile.ri != null) - { + if (tile.ri != null) { this.geometryCache.add(tile.sector, tile.ri, tile.ri.getSizeInBytes()); } } @@ -921,23 +870,19 @@ protected void makeVerts(RectTile tile) throws InterruptedException * * @return the computed vertex information. * - * @throws InterruptedException if the operation is interrupted. + * @throws InterruptedException if the operation is interrupted. * @throws gov.nasa.worldwind.exception.WWTimeoutException if terrain data retrieval exceeds the current timeout. */ - protected RenderInfo buildVerts(RectTile tile) throws InterruptedException - { + protected RenderInfo buildVerts(RectTile tile) throws InterruptedException { int density = tile.density; int numVertices = (density + 1) * (density + 1); float[] verts; //Re-use the RenderInfo vertices buffer. If it has not been set or the density has changed, create a new buffer - if (tile.ri == null || tile.ri.vertices == null) - { + if (tile.ri == null || tile.ri.vertices == null) { verts = new float[numVertices * 3]; - } - else - { + } else { verts = tile.ri.vertices; } @@ -947,8 +892,7 @@ protected RenderInfo buildVerts(RectTile tile) throws InterruptedException // In general, the best attainable resolution varies over the elevation model, so determine the best // attainable ^for this tile^ and use that as the convergence criteria. double[] localTargetResolution = this.getGlobe().getElevationModel().getBestResolutions(sector); - for (int i = 0; i < localTargetResolution.length; i++) - { + for (int i = 0; i < localTargetResolution.length; i++) { localTargetResolution[i] = Math.max(localTargetResolution[i], this.targetResolution); } this.getElevations(tile.sector, latlons, localTargetResolution, elevations); @@ -964,20 +908,16 @@ protected RenderInfo buildVerts(RectTile tile) throws InterruptedException int ie = 0; int iv = 0; Iterator latLonIter = latlons.iterator(); - for (int j = 0; j <= density; j++) - { - for (int i = 0; i <= density; i++) - { + for (int j = 0; j <= density; j++) { + for (int i = 0; i <= density; i++) { LatLon latlon = latLonIter.next(); double elevation = this.verticalExaggeration * elevations[ie++]; - if (elevation < minElevation) - { + if (elevation < minElevation) { minElevation = elevation; minElevationLocation = latlon; } - if (elevation > maxElevation) - { + if (elevation > maxElevation) { maxElevation = elevation; maxElevationLocation = latlon; } @@ -990,83 +930,79 @@ protected RenderInfo buildVerts(RectTile tile) throws InterruptedException } return new RenderInfo(density, verts, refCenter, new Position(minElevationLocation, minElevation), - new Position(maxElevationLocation, maxElevation)); + new Position(maxElevationLocation, maxElevation)); } /** * Indicates whether cached elevations are used exclusively. When this flag is true this high resolution terrain - * instance uses {@link ElevationModel#getUnmappedLocalSourceElevation(Angle, Angle)} to retrieve elevations. - * This assumes that the highest-resolution elevations for the elevation model are cached locally. + * instance uses {@link ElevationModel#getUnmappedLocalSourceElevation(Angle, Angle)} to retrieve elevations. This + * assumes that the highest-resolution elevations for the elevation model are cached locally. */ protected boolean useCachedElevationsOnly = false; /** * Indicates whether cached elevations are used exclusively. When this flag is true this high resolution terrain - * instance uses {@link ElevationModel#getUnmappedLocalSourceElevation(Angle, Angle)} to retrieve elevations. - * This assumes that the highest-resolution elevations for the elevation model are cached locally. + * instance uses {@link ElevationModel#getUnmappedLocalSourceElevation(Angle, Angle)} to retrieve elevations. This + * assumes that the highest-resolution elevations for the elevation model are cached locally. + * * @param tf true to force caching, otherwise false. The default is false. */ - public void setUseCachedElevationsOnly(boolean tf) - { + public void setUseCachedElevationsOnly(boolean tf) { this.useCachedElevationsOnly = tf; } /** * Indicates whether cached elevations are used exclusively. When this flag is true this high resolution terrain - * instance uses {@link ElevationModel#getUnmappedLocalSourceElevation(Angle, Angle)} to retrieve elevations. - * This assumes that the highest-resolution elevations for the elevation model are cached locally. + * instance uses {@link ElevationModel#getUnmappedLocalSourceElevation(Angle, Angle)} to retrieve elevations. This + * assumes that the highest-resolution elevations for the elevation model are cached locally. + * * @return true if cached elevations are forced, otherwise false. */ - public boolean isUseCachedElevationsOnly() - { + public boolean isUseCachedElevationsOnly() { return this.useCachedElevationsOnly; } protected void getElevations(Sector sector, List latlons, double[] targetResolution, double[] elevations) - throws InterruptedException - { + throws InterruptedException { if (this.useCachedElevationsOnly) { this.getCachedElevations(latlons, elevations); return; } double[] actualResolution = new double[targetResolution.length]; - for (int i = 0; i < targetResolution.length; i++) - { + for (int i = 0; i < targetResolution.length; i++) { actualResolution[i] = Double.MAX_VALUE; } - while (!this.resolutionsMeetCriteria(actualResolution, targetResolution)) - { + while (!this.resolutionsMeetCriteria(actualResolution, targetResolution)) { actualResolution = this.globe.getElevations(sector, latlons, targetResolution, elevations); - if (resolutionsMeetCriteria(actualResolution, targetResolution)) + if (resolutionsMeetCriteria(actualResolution, targetResolution)) { break; + } // Give the system a chance to retrieve data from the disk cache or the server. Also catches interrupts // and throws interrupt exceptions. Thread.sleep(this.timeout == null ? 5L : Math.min(this.timeout, 5L)); Long timeout = this.getTimeout(); - if (this.startTime.get() != null && timeout != null) - { - if (System.currentTimeMillis() - this.startTime.get() > timeout) + if (this.startTime.get() != null && timeout != null) { + if (System.currentTimeMillis() - this.startTime.get() > timeout) { throw new WWTimeoutException("Terrain convergence timed out"); + } } } } - protected boolean resolutionsMeetCriteria(double[] actualResolution, double[] targetResolution) - { - for (int i = 0; i < actualResolution.length; i++) - { - if (actualResolution[i] > targetResolution[i]) + protected boolean resolutionsMeetCriteria(double[] actualResolution, double[] targetResolution) { + for (int i = 0; i < actualResolution.length; i++) { + if (actualResolution[i] > targetResolution[i]) { return false; + } } return true; } - protected void getCachedElevations(List latlons, double[] elevations) - { + protected void getCachedElevations(List latlons, double[] elevations) { ElevationModel em = this.globe.getElevationModel(); for (int i = 0; i < latlons.size(); i++) { @@ -1087,8 +1023,7 @@ protected void getCachedElevations(List latlons, double[] elevations) * * @return the cell locations. */ - protected ArrayList computeLocations(RectTile tile) - { + protected ArrayList computeLocations(RectTile tile) { int density = tile.density; int numVertices = (density + 1) * (density + 1); @@ -1101,28 +1036,29 @@ protected ArrayList computeLocations(RectTile tile) Angle dLon = tile.sector.getDeltaLon().divide(density); ArrayList latlons = new ArrayList(numVertices); - for (int j = 0; j <= density; j++) - { + for (int j = 0; j <= density; j++) { Angle lon = lonMin; - for (int i = 0; i <= density; i++) - { + for (int i = 0; i <= density; i++) { latlons.add(new LatLon(lat, lon)); - if (i == density) + if (i == density) { lon = lonMax; - else + } else { lon = lon.add(dLon); + } - if (lon.degrees < -180) + if (lon.degrees < -180) { lon = Angle.NEG180; - else if (lon.degrees > 180) + } else if (lon.degrees > 180) { lon = Angle.POS180; + } } - if (j == density) + if (j == density) { lat = latMax; - else + } else { lat = lat.add(dLat); + } } return latlons; @@ -1134,26 +1070,26 @@ else if (lon.degrees > 180) * This operation fails with a {@link gov.nasa.worldwind.exception.WWTimeoutException} if a timeout has been * specified and it is exceeded during the operation. * - * @param tile the terrain tile. - * @param latitude the location's latitude. - * @param longitude the location's longitude. + * @param tile the terrain tile. + * @param latitude the location's latitude. + * @param longitude the location's longitude. * @param metersOffset the location's distance above the terrain. * * @return the Cartesian, model-coordinate point of a the specified location, or null if the specified location does * not exist within this instance's sector or if the operation is interrupted. * - * @throws IllegalArgumentException if the latitude or longitude are null. + * @throws IllegalArgumentException if the latitude or longitude are null. * @throws gov.nasa.worldwind.exception.WWTimeoutException if the current timeout is exceeded while retrieving - * terrain data. - * @throws InterruptedException if the operation is interrupted. + * terrain data. + * @throws InterruptedException if the operation is interrupted. * @see #setTimeout(Long) */ protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude, double metersOffset) - throws InterruptedException - { + throws InterruptedException { Vec4 result = this.getSurfacePoint(tile, latitude, longitude); - if (metersOffset != 0 && result != null) + if (metersOffset != 0 && result != null) { result = applyOffset(result, metersOffset); + } return result; } @@ -1161,13 +1097,12 @@ protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude, d /** * Applies a specified vertical offset to a surface point. * - * @param point the surface point. + * @param point the surface point. * @param metersOffset the vertical offset to add to the point. * * @return a new point offset the specified amount from the input point. */ - protected Vec4 applyOffset(Vec4 point, double metersOffset) - { + protected Vec4 applyOffset(Vec4 point, double metersOffset) { Vec4 normal = this.globe.computeSurfaceNormalAtPoint(point); point = Vec4.fromLine3(point, metersOffset, normal); return point; @@ -1179,39 +1114,38 @@ protected Vec4 applyOffset(Vec4 point, double metersOffset) * This operation fails with a {@link gov.nasa.worldwind.exception.WWTimeoutException} if a timeout has been * specified and it is exceeded during the operation. * - * @param tile the terrain tile. - * @param latitude the location's latitude. + * @param tile the terrain tile. + * @param latitude the location's latitude. * @param longitude the location's longitude. * * @return the Cartesian, model-coordinate point of a the specified location, or null if the specified location does * not exist within this instance's sector or if the operation is interrupted. * - * @throws IllegalArgumentException if the latitude or longitude are null. + * @throws IllegalArgumentException if the latitude or longitude are null. * @throws gov.nasa.worldwind.exception.WWTimeoutException if the current timeout is exceeded while retrieving - * terrain data. - * @throws InterruptedException if the operation is interrupted. + * terrain data. + * @throws InterruptedException if the operation is interrupted. * @see #setTimeout(Long) */ - protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude) throws InterruptedException - { - if (latitude == null || longitude == null) - { + protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude) throws InterruptedException { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!tile.sector.contains(latitude, longitude)) - { + if (!tile.sector.contains(latitude, longitude)) { // not on this geometry return null; } - if (tile.ri == null) + if (tile.ri == null) { this.makeVerts(tile); + } - if (tile.ri == null) + if (tile.ri == null) { return null; + } double lat = latitude.getDegrees(); double lon = longitude.getDegrees(); @@ -1236,16 +1170,14 @@ protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude) t return result; } - protected static double createPosition(int start, double decimal, int density) - { + protected static double createPosition(int start, double decimal, int density) { double l = ((double) start) / (double) density; double r = ((double) (start + 1)) / (double) density; return (decimal - l) / (r - l); } - protected static Vec4 interpolate(int row, int column, double xDec, double yDec, RenderInfo ri) - { + protected static Vec4 interpolate(int row, int column, double xDec, double yDec, RenderInfo ri) { int numVerticesPerEdge = ri.density + 1; int bottomLeft = row * numVerticesPerEdge + column; @@ -1267,19 +1199,15 @@ protected static Vec4 interpolate(int row, int column, double xDec, double yDec, return interpolate(bL, bR, tR, tL, xDec, yDec); } - protected static Vec4 interpolate(Vec4 bL, Vec4 bR, Vec4 tR, Vec4 tL, double xDec, double yDec) - { + protected static Vec4 interpolate(Vec4 bL, Vec4 bR, Vec4 tR, Vec4 tL, double xDec, double yDec) { double pos = xDec + yDec; - if (pos == 1) - { + if (pos == 1) { // on the diagonal - what's more, we don't need to do any "oneMinusT" calculation return new Vec4( - tL.x * yDec + bR.x * xDec, - tL.y * yDec + bR.y * xDec, - tL.z * yDec + bR.z * xDec); - } - else if (pos > 1) - { + tL.x * yDec + bR.x * xDec, + tL.y * yDec + bR.y * xDec, + tL.z * yDec + bR.z * xDec); + } else if (pos > 1) { // in the "top right" half // vectors pointing from top right towards the point we want (can be thought of as "negative" vectors) @@ -1287,9 +1215,7 @@ else if (pos > 1) Vec4 verticalVector = (bR.subtract3(tR)).multiply3(1 - yDec); return tR.add3(horizontalVector).add3(verticalVector); - } - else - { + } else { // pos < 1 - in the "bottom left" half // vectors pointing from the bottom left towards the point we want @@ -1310,13 +1236,14 @@ else if (pos > 1) * * @throws InterruptedException if the operation is interrupted. */ - protected Intersection[] intersect(RectTile tile, Line line) throws InterruptedException - { - if (tile.ri == null) + protected Intersection[] intersect(RectTile tile, Line line) throws InterruptedException { + if (tile.ri == null) { this.makeVerts(tile); + } - if (tile.ri == null) + if (tile.ri == null) { return null; + } Intersection[] hits; ArrayList list = new ArrayList(); @@ -1329,12 +1256,10 @@ protected Intersection[] intersect(RectTile tile, Line line) throws InterruptedE int n = tile.density + 1; float[] coords = tile.ri.vertices; - for (int j = 0; j < n - 1; j++) - { - for (int i = 0; i < n - 1; i++) - { + for (int j = 0; j < n - 1; j++) { + for (int i = 0; i < n - 1; i++) { int k = (j * n + i) * 3; - Vec4 va = new Vec4(coords[k] + cx, coords[k + 1] + cy, coords[k + 2] + cz); + Vec4 va = new Vec4(coords[k] + cx, coords[k + 1] + cy, coords[k + 2] + cz); k += 3; Vec4 vb = new Vec4(coords[k] + cx, coords[k + 1] + cy, coords[k + 2] + cz); @@ -1348,33 +1273,37 @@ protected Intersection[] intersect(RectTile tile, Line line) throws InterruptedE // Intersect triangles with line Intersection intersection; - if ((intersection = Triangle.intersect(line, va, vb, vc)) != null) + if ((intersection = Triangle.intersect(line, va, vb, vc)) != null) { list.add(intersection); + } - if ((intersection = Triangle.intersect(line, va, vc, vd)) != null) + if ((intersection = Triangle.intersect(line, va, vc, vd)) != null) { list.add(intersection); + } } } int numHits = list.size(); - if (numHits == 0) + if (numHits == 0) { return null; + } // Sort the intersections by distance from line origin, nearer are first in the sorted list. hits = new Intersection[numHits]; list.toArray(hits); final Vec4 origin = line.getOrigin(); - Arrays.sort(hits, new Comparator() - { - public int compare(Intersection i1, Intersection i2) - { - if (i1 == null && i2 == null) + Arrays.sort(hits, new Comparator() { + public int compare(Intersection i1, Intersection i2) { + if (i1 == null && i2 == null) { return 0; - if (i2 == null) + } + if (i2 == null) { return -1; - if (i1 == null) + } + if (i1 == null) { return 1; + } Vec4 v1 = i1.getIntersectionPoint(); Vec4 v2 = i2.getIntersectionPoint(); @@ -1390,7 +1319,7 @@ public int compare(Intersection i1, Intersection i2) /** * Computes the intersection of a triangle with a terrain tile. * - * @param tile the terrain tile + * @param tile the terrain tile * @param triangle the Cartesian coordinates of the triangle. * * @return a list of the intersection points at which the triangle intersects the tile, or null if there are no @@ -1400,13 +1329,14 @@ public int compare(Intersection i1, Intersection i2) * * @throws InterruptedException if the operation is interrupted before it completes. */ - protected List intersect(RectTile tile, Vec4[] triangle) throws InterruptedException - { - if (tile.ri == null) + protected List intersect(RectTile tile, Vec4[] triangle) throws InterruptedException { + if (tile.ri == null) { this.makeVerts(tile); + } - if (tile.ri == null) + if (tile.ri == null) { return null; + } ArrayList intersections = new ArrayList(); @@ -1423,10 +1353,8 @@ protected List intersect(RectTile tile, Vec4[] triangle) throws Interrup Vec4[] iVerts = new Vec4[3]; - for (int j = 0; j < n - 1; j++) - { - for (int i = 0; i < n - 1; i++) - { + for (int j = 0; j < n - 1; j++) { + for (int i = 0; i < n - 1; i++) { int k = (j * n + i) * 3; triA[0] = new Vec4(coords[k] + cx, coords[k + 1] + cy, coords[k + 2] + cz); triB[0] = triA[0]; @@ -1442,34 +1370,28 @@ protected List intersect(RectTile tile, Vec4[] triangle) throws Interrup triB[2] = new Vec4(coords[k] + cx, coords[k + 1] + cy, coords[k + 2] + cz); // Intersect triangles with input triangle - int status = Triangle.intersectTriangles(triangle, triA, iVerts); - if (status == 1) - { - intersections.add(new Vec4[] {iVerts[0], iVerts[1]}); + if (status == 1) { + intersections.add(new Vec4[]{iVerts[0], iVerts[1]}); // intersections.add(new Vec4[] {triA[0], triA[1], triA[2], triA[0]}); - } - else if (status == 0) - { - intersections.add(new Vec4[] {triA[0], triA[1], triA[2]}); + } else if (status == 0) { + intersections.add(new Vec4[]{triA[0], triA[1], triA[2]}); } status = Triangle.intersectTriangles(triangle, triB, iVerts); - if (status == 1) - { - intersections.add(new Vec4[] {iVerts[0], iVerts[1]}); + if (status == 1) { + intersections.add(new Vec4[]{iVerts[0], iVerts[1]}); // intersections.add(new Vec4[] {triB[0], triB[1], triB[2], triB[0]}); - } - else if (status == 0) - { - intersections.add(new Vec4[] {triB[0], triB[1], triB[2]}); + } else if (status == 0) { + intersections.add(new Vec4[]{triB[0], triB[1], triB[2]}); } } } int numHits = intersections.size(); - if (numHits == 0) + if (numHits == 0) { return null; + } return intersections; } @@ -1477,15 +1399,14 @@ else if (status == 0) /** * Intersects a specified triangle with the terrain. * - * @param triangleCoordinates The Cartesian coordinates of the triangle. - * @param trianglePositions The geographic coordinates of the triangle. + * @param triangleCoordinates The Cartesian coordinates of the triangle. + * @param trianglePositions The geographic coordinates of the triangle. * @param intersectPositionsOut A list in which to place the intersection positions. May not be null. * * @throws InterruptedException if the operation is interrupted before it completes. */ public void intersectTriangle(Vec4[] triangleCoordinates, Position[] trianglePositions, - List intersectPositionsOut) throws InterruptedException - { + List intersectPositionsOut) throws InterruptedException { // Get the tiles intersecting the specified sector. Compute the sector from geographic coordinates. Sector sector = Sector.boundingSector(Arrays.asList(trianglePositions)); List tiles = this.getIntersectingTiles(sector); @@ -1493,21 +1414,21 @@ public void intersectTriangle(Vec4[] triangleCoordinates, Position[] trianglePos // Eliminate tiles with max altitude below specified min altitude. Determine min altitude using triangle's // geographic coordinates. double minAltitude = trianglePositions[0].getAltitude(); - for (int i = 1; i < trianglePositions.length; i++) - { - if (trianglePositions[i].getAltitude() < minAltitude) + for (int i = 1; i < trianglePositions.length; i++) { + if (trianglePositions[i].getAltitude() < minAltitude) { minAltitude = trianglePositions[i].getAltitude(); + } } tiles = this.eliminateLowAltitudeTiles(tiles, minAltitude); // Intersect triangles of remaining tiles with input triangle. List intersections = new ArrayList(); - for (RectTile tile : tiles) - { + for (RectTile tile : tiles) { List iSects = intersect(tile, triangleCoordinates); - if (iSects != null) + if (iSects != null) { intersections.addAll(iSects); + } } // Convert intersection points to positions. @@ -1515,33 +1436,31 @@ public void intersectTriangle(Vec4[] triangleCoordinates, Position[] trianglePos } protected List eliminateLowAltitudeTiles(List tiles, double minAltitude) - throws InterruptedException - { + throws InterruptedException { List filteredTiles = new ArrayList(); - for (RectTile tile : tiles) - { - if (tile.ri == null) + for (RectTile tile : tiles) { + if (tile.ri == null) { this.makeVerts(tile); + } - if (tile.ri == null) + if (tile.ri == null) { return null; + } - if (tile.ri.maxElevation.getElevation() >= minAltitude) + if (tile.ri.maxElevation.getElevation() >= minAltitude) { filteredTiles.add(tile); + } } return filteredTiles; } - protected void convertPointsToPositions(List points, List positions) - { - for (Vec4[] pts : points) - { + protected void convertPointsToPositions(List points, List positions) { + for (Vec4[] pts : points) { Position[] pos = new Position[pts.length]; - for (int i = 0; i < pts.length; i++) - { + for (int i = 0; i < pts.length; i++) { pos[i] = this.getGlobe().computePositionFromPoint(pts[i]); } @@ -1560,30 +1479,31 @@ protected void convertPointsToPositions(List points, List po * * @throws InterruptedException if the operation is interrupted before it completes. */ - public Position[] getExtremeElevations(Sector sector) throws InterruptedException - { + public Position[] getExtremeElevations(Sector sector) throws InterruptedException { // Get the tiles intersecting the specified sector. List tiles = this.getIntersectingTiles(sector); // Find the min and max elevation among the tiles. - this.startTime.set(System.currentTimeMillis()); Position[] extremes = new Position[2]; - for (RectTile tile : tiles) - { - if (tile.ri == null) + for (RectTile tile : tiles) { + if (tile.ri == null) { this.makeVerts(tile); + } - if (tile.ri == null) + if (tile.ri == null) { continue; + } - if (extremes[0] == null || tile.ri.minElevation.getElevation() < extremes[0].getElevation()) + if (extremes[0] == null || tile.ri.minElevation.getElevation() < extremes[0].getElevation()) { extremes[0] = tile.ri.minElevation; + } - if (extremes[1] == null || tile.ri.maxElevation.getElevation() > extremes[1].getElevation()) + if (extremes[1] == null || tile.ri.maxElevation.getElevation() > extremes[1].getElevation()) { extremes[1] = tile.ri.maxElevation; + } } return extremes; @@ -1593,7 +1513,7 @@ public Position[] getExtremeElevations(Sector sector) throws InterruptedExceptio * Determines the minimum and maximum elevations and their locations within a specified geographic quadrilateral. * * @param center The quadrilateral's center. - * @param width The quadrilateral's longitudinal width, in meters. + * @param width The quadrilateral's longitudinal width, in meters. * @param height The quadrilateral's latitudinal height, in meters. * * @return a two-element array containing the minimum and maximum elevations and their locations in the @@ -1602,8 +1522,7 @@ public Position[] getExtremeElevations(Sector sector) throws InterruptedExceptio * * @throws InterruptedException if the operation is interrupted before it completes. */ - public Position[] getExtremeElevations(LatLon center, double width, double height) throws InterruptedException - { + public Position[] getExtremeElevations(LatLon center, double width, double height) throws InterruptedException { // Compute the quad's geographic corners. SurfaceQuad quad = new SurfaceQuad(center, width, height); Sector sector = Sector.boundingSector(quad.getLocations(this.getGlobe())); diff --git a/src/gov/nasa/worldwind/terrain/LocalElevationModel.java b/src/gov/nasa/worldwind/terrain/LocalElevationModel.java index 62309e626c..8b5e2a6fbd 100644 --- a/src/gov/nasa/worldwind/terrain/LocalElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/LocalElevationModel.java @@ -27,20 +27,22 @@ * @author tag * @version $Id: LocalElevationModel.java 2138 2014-07-10 17:31:58Z tgaskins $ */ -public class LocalElevationModel extends AbstractElevationModel -{ - /** The min and max elevations. */ +public class LocalElevationModel extends AbstractElevationModel { + + /** + * The min and max elevations. + */ protected double[] extremeElevations = null; - /** The list of elevation rasters, one per file specified. */ + /** + * The list of elevation rasters, one per file specified. + */ protected CopyOnWriteArrayList tiles = new CopyOnWriteArrayList(); - public double getMinElevation() - { + public double getMinElevation() { return this.extremeElevations[0]; } - public double getMaxElevation() - { + public double getMaxElevation() { return this.extremeElevations[1]; } @@ -49,15 +51,14 @@ public double getMaxElevation() * * @return the sector spanned by this elevation model. */ - public Sector getSector() - { - if (this.tiles.size() < 1) + public Sector getSector() { + if (this.tiles.size() < 1) { return null; + } Sector sector = null; - for (LocalTile tile : this.tiles) - { + for (LocalTile tile : this.tiles) { Sector tileSector = tile.sector; sector = sector == null ? tileSector : sector.union(tileSector); } @@ -65,107 +66,102 @@ public Sector getSector() return sector; } - public double[] getExtremeElevations(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double[] getExtremeElevations(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.tiles.size() == 0) - return new double[] {this.getMinElevation(), this.getMaxElevation()}; + if (this.tiles.size() == 0) { + return new double[]{this.getMinElevation(), this.getMaxElevation()}; + } double min = Double.MAX_VALUE; double max = -min; - for (LocalTile tile : this.tiles) - { - if (tile.sector.contains(latitude, longitude)) - { - if (tile.minElevation < min) + for (LocalTile tile : this.tiles) { + if (tile.sector.contains(latitude, longitude)) { + if (tile.minElevation < min) { min = tile.minElevation; - if (tile.maxElevation > max) + } + if (tile.maxElevation > max) { max = tile.maxElevation; + } } } - return new double[] { + return new double[]{ min != Double.MAX_VALUE ? min : this.getMinElevation(), max != -Double.MAX_VALUE ? max : this.getMaxElevation()}; } - public double[] getExtremeElevations(Sector sector) - { - if (sector == null) - { + public double[] getExtremeElevations(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.tiles.size() == 0) - return new double[] {this.getMinElevation(), this.getMaxElevation()}; + if (this.tiles.size() == 0) { + return new double[]{this.getMinElevation(), this.getMaxElevation()}; + } double min = Double.MAX_VALUE; double max = -min; - for (LocalTile tile : this.tiles) - { - if (tile.sector.intersects(sector)) - { - if (tile.minElevation < min) + for (LocalTile tile : this.tiles) { + if (tile.sector.intersects(sector)) { + if (tile.minElevation < min) { min = tile.minElevation; - if (tile.maxElevation > max) + } + if (tile.maxElevation > max) { max = tile.maxElevation; + } } } - return new double[] { + return new double[]{ min != Double.MAX_VALUE ? min : this.getMinElevation(), max != -Double.MAX_VALUE ? max : this.getMaxElevation()}; } - public double getBestResolution(Sector sector) - { + public double getBestResolution(Sector sector) { double res = Double.MAX_VALUE; - for (LocalTile tile : tiles) - { - if (sector != null && !sector.intersects(tile.sector)) + for (LocalTile tile : tiles) { + if (sector != null && !sector.intersects(tile.sector)) { continue; + } double r = tile.sector.getDeltaLatRadians() / tile.tileHeight; - if (r < res) + if (r < res) { res = r; + } } return res; } @Override - public void setExtremesCachingEnabled(boolean enabled) - { + public void setExtremesCachingEnabled(boolean enabled) { } @Override - public boolean isExtremesCachingEnabled() - { + public boolean isExtremesCachingEnabled() { return false; } - public double getUnmappedElevation(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getUnmappedElevation(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.contains(latitude, longitude)) + if (!this.contains(latitude, longitude)) { return this.missingDataFlag; + } Double e = this.lookupElevation(latitude.radians, longitude.radians); @@ -176,14 +172,12 @@ public double getUnmappedElevation(Angle latitude, Angle longitude) return e != null ? e : this.getExtremeElevations(latitude, longitude)[0]; } - public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) - { + public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) { return this.doGetElevations(sector, latlons, targetResolution, buffer, true); } public double getUnmappedElevations(Sector sector, List latlons, double targetResolution, - double[] buffer) - { + double[] buffer) { return this.doGetElevations(sector, latlons, targetResolution, buffer, false); } @@ -191,80 +185,77 @@ public double getUnmappedElevations(Sector sector, List latlon * Performs the lookup and assembly of elevations for a list of specified locations. This method is provided to * enable subclasses to override this operation. * - * @param sector the sector containing the specified locations. - * @param latlons the list of locations at which to lookup elevations. + * @param sector the sector containing the specified locations. + * @param latlons the list of locations at which to lookup elevations. * @param targetResolution the desired maximum horizontal resolution of the elevation data to draw from. - * @param buffer a buffer in which to return the elevations. Must be at least as large as the list of - * locations. - * @param mapMissingData indicates whether to replace any elevations that match this elevation model's missing - * data signal to this model's missing data replacement value. + * @param buffer a buffer in which to return the elevations. Must be at least as large as the list of locations. + * @param mapMissingData indicates whether to replace any elevations that match this elevation model's missing data + * signal to this model's missing data replacement value. * * @return the resolution achieved, in radians, or {@link Double#MAX_VALUE} if individual elevations cannot be - * determined for all of the locations. + * determined for all of the locations. * * @throws IllegalArgumentException if either the sector, list of locations or buffer is null, or the buffer size is - * not at least as large as the location list. + * not at least as large as the location list. * @see #setMissingDataSignal(double) * @see #setMissingDataReplacement(double) */ - @SuppressWarnings( {"UnusedParameters"}) + @SuppressWarnings({"UnusedParameters"}) protected double doGetElevations(Sector sector, List latlons, double targetResolution, - double[] buffer, boolean mapMissingData) - { - if (sector == null) - { + double[] buffer, boolean mapMissingData) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (latlons == null) - { + if (latlons == null) { String msg = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer == null) - { + if (buffer == null) { String msg = Logging.getMessage("nullValue.ElevationsBufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer.length < latlons.size()) - { + if (buffer.length < latlons.size()) { String msg = Logging.getMessage("ElevationModel.ElevationsBufferTooSmall", latlons.size()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.intersects(sector) == -1) + if (this.intersects(sector) == -1) { return Double.MAX_VALUE; // as stated in the javadoc above, this is the sentinel for "not in my domain" - + } // Mark the model as used this frame. this.setValue(AVKey.FRAME_TIMESTAMP, System.currentTimeMillis()); - for (int i = 0; i < latlons.size(); i++) - { + for (int i = 0; i < latlons.size(); i++) { LatLon ll = latlons.get(i); - if (ll == null) + if (ll == null) { continue; + } - if (!this.contains(ll.getLatitude(), ll.getLongitude())) + if (!this.contains(ll.getLatitude(), ll.getLongitude())) { continue; + } // If an elevation at the given location is available, write that elevation to the destination buffer. // If an elevation is not available but the location is within the elevation model's coverage, write the // elevation models extreme elevation at the location. Do nothing if the location is not within the // elevation model's coverage. Double e = this.lookupElevation(ll.getLatitude().radians, ll.getLongitude().radians); - if (e != null && e != this.missingDataFlag) + if (e != null && e != this.missingDataFlag) { buffer[i] = e; - if (e == null) + } + if (e == null) { buffer[i] = this.getExtremeElevations(sector)[0]; - else if (mapMissingData && e == this.missingDataFlag) + } else if (mapMissingData && e == this.missingDataFlag) { buffer[i] = this.getMissingDataReplacement(); + } } return this.getBestResolution(sector); @@ -276,15 +267,13 @@ else if (mapMissingData && e == this.missingDataFlag) * @param filename the file containing the elevation data. * * @throws IllegalArgumentException if the filename is null or the file does not exist, or if the file does not - * contain elevations in a recognizable format. - * @throws IOException if an exception occurs while opening or reading the specified file. - * @throws WWRuntimeException if an error occurs attempting to read and interpret the elevation data, or if - * necessary information is missing from the data file or its auxiliary files. + * contain elevations in a recognizable format. + * @throws IOException if an exception occurs while opening or reading the specified file. + * @throws WWRuntimeException if an error occurs attempting to read and interpret the elevation data, or if + * necessary information is missing from the data file or its auxiliary files. */ - public void addElevations(String filename) throws IOException - { - if (filename == null) - { + public void addElevations(String filename) throws IOException { + if (filename == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -299,23 +288,20 @@ public void addElevations(String filename) throws IOException * @param file the file containing the elevation data. * * @throws IllegalArgumentException if the file is null or does not exist, if the file does not contain elevations - * in a recognizable format, or if the specified file does not contain required - * information such as the data's location and data type. - * @throws IOException if an exception occurs while opening or reading the specified file. - * @throws WWRuntimeException if an error occurs attempting to read and interpret the elevation data, or if an - * error occurs attempting to read and interpret the file's contents. + * in a recognizable format, or if the specified file does not contain required information such as the data's + * location and data type. + * @throws IOException if an exception occurs while opening or reading the specified file. + * @throws WWRuntimeException if an error occurs attempting to read and interpret the elevation data, or if an error + * occurs attempting to read and interpret the file's contents. */ - public void addElevations(File file) throws IOException - { - if (file == null) - { + public void addElevations(File file) throws IOException { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", file.getPath()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -323,13 +309,12 @@ public void addElevations(File file) throws IOException // Create a raster reader for the file type. DataRasterReaderFactory readerFactory = (DataRasterReaderFactory) WorldWind.createConfigurationComponent( - AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); + AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); DataRasterReader reader = readerFactory.findReaderFor(file, null); // Before reading the raster, verify that the file contains elevations. AVList metadata = reader.readMetadata(file, null); - if (metadata == null || !AVKey.ELEVATION.equals(metadata.getStringValue(AVKey.PIXEL_FORMAT))) - { + if (metadata == null || !AVKey.ELEVATION.equals(metadata.getStringValue(AVKey.PIXEL_FORMAT))) { String msg = Logging.getMessage("ElevationModel.SourceNotElevations", file.getAbsolutePath()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -337,15 +322,13 @@ public void addElevations(File file) throws IOException // Read the file into the raster. DataRaster[] rasters = reader.read(file, null); - if (rasters == null || rasters.length == 0) - { + if (rasters == null || rasters.length == 0) { String msg = Logging.getMessage("ElevationModel.CannotReadElevations", file.getAbsolutePath()); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } - for (DataRaster raster : rasters) - { + for (DataRaster raster : rasters) { this.addRaster(raster, file.getAbsolutePath()); } } @@ -353,20 +336,18 @@ public void addElevations(File file) throws IOException /** * Adds a new raster to this elevation model. * - * @param raster the raster to add. + * @param raster the raster to add. * @param filename the filename associated with the raster. Used only for error reporting. * * @throws IllegalArgumentException if necessary information is missing from the raster. - * @throws IOException if an exception occurs while opening or reading the specified file. - * @throws WWRuntimeException if an error occurs attempting to read and interpret the elevation data. + * @throws IOException if an exception occurs while opening or reading the specified file. + * @throws WWRuntimeException if an error occurs attempting to read and interpret the elevation data. */ - protected void addRaster(DataRaster raster, String filename) throws IOException - { + protected void addRaster(DataRaster raster, String filename) throws IOException { // Determine the sector covered by the elevations. This information is in the GeoTIFF file or auxiliary // files associated with the elevations file. final Sector sector = (Sector) raster.getValue(AVKey.SECTOR); - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("DataRaster.MissingMetadata", AVKey.SECTOR); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -380,8 +361,7 @@ protected void addRaster(DataRaster raster, String filename) throws IOException DataRaster subRaster = raster.getSubRaster(width, height, sector, raster); // Verify that the sub-raster can create a ByteBuffer, then create one. - if (!(subRaster instanceof ByteBufferRaster)) - { + if (!(subRaster instanceof ByteBufferRaster)) { String msg = Logging.getMessage("ElevationModel.CannotCreateElevationBuffer", filename); Logging.logger().severe(msg); throw new WWRuntimeException(msg); @@ -402,37 +382,33 @@ protected void addRaster(DataRaster raster, String filename) throws IOException * row-major order in a linear buffer. * * @param byteBuffer the elevations to add. - * @param sector the sector containing the elevations. - * @param width the number of elevation values in a row of the array. Each consecutive group of {@code width} - * elevation values is considered one row of the array, with the first element of the buffer - * starting the row of elevations at the sector's maximum latitude. - * @param height the number of rows in the array. + * @param sector the sector containing the elevations. + * @param width the number of elevation values in a row of the array. Each consecutive group of {@code width} + * elevation values is considered one row of the array, with the first element of the buffer starting the row of + * elevations at the sector's maximum latitude. + * @param height the number of rows in the array. * @param parameters a list of key-value pairs indicating information about the raster. A value for {@code * AVKey.DATA_TYPE} is required. Values recognized but not required are {@code * AVKey.MISSING_DATA_SIGNAL}, {@code AVKey.BYTE_ORDER}, {@code AVKey.ELEVATION_MIN} and {@code * AVKey.ELEVATION_MAX}. * * @throws IllegalArgumentException if either the buffer, sector or parameters list is null, or if a key-value pair - * for {@code AVKey.DATA_TYPE} is not specified in the parameters. + * for {@code AVKey.DATA_TYPE} is not specified in the parameters. */ - public void addElevations(ByteBuffer byteBuffer, Sector sector, int width, int height, AVList parameters) - { - if (byteBuffer == null) - { + public void addElevations(ByteBuffer byteBuffer, Sector sector, int width, int height, AVList parameters) { + if (byteBuffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (parameters == null) - { + if (parameters == null) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -443,22 +419,24 @@ public void addElevations(ByteBuffer byteBuffer, Sector sector, int width, int h bufferParams.setValues(parameters.copy()); Double tileMissingDataFlag = AVListImpl.getDoubleValue(bufferParams, AVKey.MISSING_DATA_SIGNAL); - if (tileMissingDataFlag == null) + if (tileMissingDataFlag == null) { tileMissingDataFlag = this.getMissingDataSignal(); + } // Check params for ELEVATION_MIN and ELEVATION_MAX and don't have the tile compute them if present. Double minElevation = null; Double maxElevation = null; Object o = bufferParams.getValue(AVKey.ELEVATION_MIN); - if (o instanceof Double) + if (o instanceof Double) { minElevation = (Double) o; + } o = bufferParams.getValue(AVKey.ELEVATION_MAX); - if (o instanceof Double) + if (o instanceof Double) { maxElevation = (Double) o; + } String dataType = bufferParams.getStringValue(AVKey.DATA_TYPE); - if (WWUtil.isEmpty(dataType)) - { + if (WWUtil.isEmpty(dataType)) { String msg = Logging.getMessage("DataRaster.MissingMetadata", AVKey.DATA_TYPE); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -471,28 +449,27 @@ public void addElevations(ByteBuffer byteBuffer, Sector sector, int width, int h this.adjustMinMax(tile); } - public int intersects(Sector sector) - { + public int intersects(Sector sector) { boolean intersects = false; - for (LocalTile tile : this.tiles) - { - if (tile.sector.contains(sector)) + for (LocalTile tile : this.tiles) { + if (tile.sector.contains(sector)) { return 0; + } - if (tile.sector.intersects(sector)) + if (tile.sector.intersects(sector)) { intersects = true; + } } return intersects ? 1 : -1; } - public boolean contains(Angle latitude, Angle longitude) - { - for (LocalTile tile : this.tiles) - { - if (tile.sector.contains(latitude, longitude)) + public boolean contains(Angle latitude, Angle longitude) { + for (LocalTile tile : this.tiles) { + if (tile.sector.contains(latitude, longitude)) { return true; + } } return false; @@ -503,34 +480,33 @@ public boolean contains(Angle latitude, Angle longitude) * * @param tile the tile to account for. */ - protected void adjustMinMax(LocalTile tile) - { - if (this.extremeElevations == null && tile != null) + protected void adjustMinMax(LocalTile tile) { + if (this.extremeElevations == null && tile != null) { + this.extremeElevations = new double[]{tile.minElevation, tile.maxElevation}; + } else if (tile != null) // adjust for just the input tile { - this.extremeElevations = new double[] {tile.minElevation, tile.maxElevation}; - } - else if (tile != null) // adjust for just the input tile - { - if (tile.minElevation < this.extremeElevations[0]) + if (tile.minElevation < this.extremeElevations[0]) { this.extremeElevations[0] = tile.minElevation; - if (tile.maxElevation > this.extremeElevations[1]) + } + if (tile.maxElevation > this.extremeElevations[1]) { this.extremeElevations[1] = tile.maxElevation; - } - else // Find the min and max among all the tiles + } + } else // Find the min and max among all the tiles { double min = Double.MAX_VALUE; double max = -min; - for (LocalTile t : this.tiles) - { - if (t.minElevation < min) + for (LocalTile t : this.tiles) { + if (t.minElevation < min) { min = t.minElevation; - if (t.maxElevation > max) + } + if (t.maxElevation > max) { max = t.maxElevation; + } } - this.extremeElevations = - new double[] {min != Double.MAX_VALUE ? min : 0, max != -Double.MAX_VALUE ? max : 0}; + this.extremeElevations + = new double[]{min != Double.MAX_VALUE ? min : 0, max != -Double.MAX_VALUE ? max : 0}; } } @@ -541,13 +517,13 @@ else if (tile != null) // adjust for just the input tile * @param lonRadians the longitude of the location, in radians. * * @return the elevation if the specified location is contained in this elevation model, null if it's not, or this - * elevation model's missing data flag if that's the value at the specified location. + * elevation model's missing data flag if that's the value at the specified location. */ - protected Double lookupElevation(final double latRadians, final double lonRadians) - { + protected Double lookupElevation(final double latRadians, final double lonRadians) { LocalTile tile = this.findTile(latRadians, lonRadians); - if (tile == null) + if (tile == null) { return null; + } final double sectorDeltaLat = tile.sector.getDeltaLat().radians; final double sectorDeltaLon = tile.sector.getDeltaLon().radians; @@ -564,8 +540,9 @@ protected Double lookupElevation(final double latRadians, final double lonRadian double eRight = i < (tile.tileWidth - 1) ? tile.elevations.getDouble(k + 1) : eLeft; // Notice that the below test is against the tile flag, but the value returned is the model's flag. - if (tile.isMissingData(eLeft) || tile.isMissingData(eRight)) + if (tile.isMissingData(eLeft) || tile.isMissingData(eRight)) { return this.missingDataFlag; + } double dw = sectorDeltaLon / (tile.tileWidth - 1); double dh = sectorDeltaLat / (tile.tileHeight - 1); @@ -574,14 +551,14 @@ protected Double lookupElevation(final double latRadians, final double lonRadian double eTop = eLeft + ssLon * (eRight - eLeft); - if (j < tile.tileHeight - 1 && i < tile.tileWidth - 1) - { + if (j < tile.tileHeight - 1 && i < tile.tileWidth - 1) { eLeft = tile.elevations.getDouble(k + tile.tileWidth); eRight = tile.elevations.getDouble(k + tile.tileWidth + 1); // Notice that the below test is against the tile flag, but the value returned is the model's flag. - if (tile.isMissingData(eLeft) || tile.isMissingData(eRight)) + if (tile.isMissingData(eLeft) || tile.isMissingData(eRight)) { return this.missingDataFlag; + } } double eBot = eLeft + ssLon * (eRight - eLeft); @@ -596,51 +573,63 @@ protected Double lookupElevation(final double latRadians, final double lonRadian * * @return the tile that contains the location, or null if no tile contains it. */ - protected LocalTile findTile(final double latRadians, final double lonRadians) - { - for (LocalTile tile : this.tiles) - { - if (tile.sector.containsRadians(latRadians, lonRadians)) + protected LocalTile findTile(final double latRadians, final double lonRadians) { + for (LocalTile tile : this.tiles) { + if (tile.sector.containsRadians(latRadians, lonRadians)) { return tile; + } } return null; } - /** An internal class that represents one elevation raster in the elevation model. */ - protected static class LocalTile - { - /** The sector the tile covers. */ + /** + * An internal class that represents one elevation raster in the elevation model. + */ + protected static class LocalTile { + + /** + * The sector the tile covers. + */ protected final Sector sector; - /** The number of elevation values in a row of the raster. */ + /** + * The number of elevation values in a row of the raster. + */ protected final int tileWidth; - /** The number of rows in the raster. */ + /** + * The number of rows in the raster. + */ protected final int tileHeight; - /** The minimum elevation contained in this tile's raster. */ + /** + * The minimum elevation contained in this tile's raster. + */ protected double minElevation; - /** The maximum elevation contained in this tile's raster. */ + /** + * The maximum elevation contained in this tile's raster. + */ protected double maxElevation; - /** The elevation model's missing data flag. */ + /** + * The elevation model's missing data flag. + */ protected final double missingDataFlag; - /** The elevations. */ + /** + * The elevations. + */ protected final BufferWrapper elevations; /** * Constructs a new elevations tile. * - * @param sector the sector the tile covers. + * @param sector the sector the tile covers. * @param missingDataFlag the elevation model's missing data flag. - * @param tileWidth the number of elevation values in a row of this tile's elevation raster. - * @param tileHeight the number of rows in this tile's elevation raster. - * @param elevations the elevations. - * @param minEl the minimum elevation of this tile. May be null, in which case the minimum is - * determined. - * @param maxEl the maximum elevation of this tile. May be null, in which case the maximum is - * determined. + * @param tileWidth the number of elevation values in a row of this tile's elevation raster. + * @param tileHeight the number of rows in this tile's elevation raster. + * @param elevations the elevations. + * @param minEl the minimum elevation of this tile. May be null, in which case the minimum is determined. + * @param maxEl the maximum elevation of this tile. May be null, in which case the maximum is determined. */ protected LocalTile(Sector sector, double missingDataFlag, int tileWidth, int tileHeight, - BufferWrapper elevations, Double minEl, Double maxEl) - { + BufferWrapper elevations, Double minEl, Double maxEl) { this.sector = sector; this.tileWidth = tileWidth; this.tileHeight = tileHeight; @@ -648,23 +637,26 @@ protected LocalTile(Sector sector, double missingDataFlag, int tileWidth, int ti this.elevations = elevations; // One or both of the min/max elevations may have been specified in the metadata. - if (minEl != null) + if (minEl != null) { this.minElevation = minEl; - if (maxEl != null) + } + if (maxEl != null) { this.maxElevation = maxEl; + } - if (minEl == null || maxEl == null) + if (minEl == null || maxEl == null) { this.computeMinMaxElevations(); + } return; } - /** Determines the minimum and maximum elevations of this tile. */ - protected void computeMinMaxElevations() - { + /** + * Determines the minimum and maximum elevations of this tile. + */ + protected void computeMinMaxElevations() { int len = this.elevations.length(); - if (len == 0) - { + if (len == 0) { this.minElevation = 0; this.maxElevation = 0; return; @@ -673,16 +665,18 @@ protected void computeMinMaxElevations() double min = Double.MAX_VALUE; double max = -min; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { double v = this.elevations.getDouble(i); - if (v == this.missingDataFlag) + if (v == this.missingDataFlag) { continue; + } - if (v < min) + if (v < min) { min = v; - if (v > max) + } + if (v > max) { max = v; + } } this.minElevation = min; @@ -698,12 +692,11 @@ protected void computeMinMaxElevations() * @param value the value to test. * * @return true if the value is this tile's missing data signal, or if it is outside the min/max range of the - * tile, or if it's equal to -32767. + * tile, or if it's equal to -32767. */ - protected boolean isMissingData(double value) - { + protected boolean isMissingData(double value) { return value == this.missingDataFlag || value < this.minElevation || value > this.maxElevation - || value == -32767; + || value == -32767; } } } diff --git a/src/gov/nasa/worldwind/terrain/LocalRasterServerElevationModel.java b/src/gov/nasa/worldwind/terrain/LocalRasterServerElevationModel.java index 047e5a6a83..fa533b6372 100644 --- a/src/gov/nasa/worldwind/terrain/LocalRasterServerElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/LocalRasterServerElevationModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.avlist.*; @@ -22,8 +21,8 @@ * @author tag * @version $Id: LocalRasterServerElevationModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class LocalRasterServerElevationModel extends BasicElevationModel -{ +public class LocalRasterServerElevationModel extends BasicElevationModel { + /** * Constructs an elevation model from a list of parameters describing the elevation model. *

                  @@ -34,10 +33,9 @@ public class LocalRasterServerElevationModel extends BasicElevationModel * @param params the parameters describing the dataset. * * @throws IllegalArgumentException if the parameter list is null. - * @throws IllegalStateException if the required parameters are missing from the parameter list. + * @throws IllegalStateException if the required parameters are missing from the parameter list. */ - public LocalRasterServerElevationModel(AVList params) - { + public LocalRasterServerElevationModel(AVList params) { super(params); this.createRasterServer(params); @@ -50,16 +48,14 @@ public LocalRasterServerElevationModel(AVList params) *

                  * TODO: Enumerate the other required and optional parameters. * - * @param dom the XML document describing the dataset. + * @param dom the XML document describing the dataset. * @param params a list of parameters that each override a parameter of the same name in the XML document, or that - * augment the definition there. + * augment the definition there. * * @throws IllegalArgumentException if the XML document reference is null. - * @throws IllegalStateException if the required parameters are missing from the XML document or the parameter - * list. + * @throws IllegalStateException if the required parameters are missing from the XML document or the parameter list. */ - public LocalRasterServerElevationModel(Document dom, AVList params) - { + public LocalRasterServerElevationModel(Document dom, AVList params) { super(dom, params); this.createRasterServer(params != null ? params : (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS)); @@ -73,15 +69,13 @@ public LocalRasterServerElevationModel(Document dom, AVList params) * TODO: Enumerate the other required and optional parameters. * * @param domElement the XML document describing the dataset. - * @param params a list of parameters that each override a parameter of the same name in the XML document, or - * that augment the definition there. + * @param params a list of parameters that each override a parameter of the same name in the XML document, or that + * augment the definition there. * * @throws IllegalArgumentException if the XML document reference is null. - * @throws IllegalStateException if the required parameters are missing from the XML element or the parameter - * list. + * @throws IllegalStateException if the required parameters are missing from the XML element or the parameter list. */ - public LocalRasterServerElevationModel(Element domElement, AVList params) - { + public LocalRasterServerElevationModel(Element domElement, AVList params) { super(domElement, params); this.createRasterServer(params != null ? params : (AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS)); @@ -94,28 +88,24 @@ public LocalRasterServerElevationModel(Element domElement, AVList params) * @param restorableStateInXml a string containing the restorable state. * * @throws IllegalArgumentException if the restorable state is null or cannot be interpreted. - * @throws IllegalStateException if the restorable state does not contain values for DATASET_NAME and - * DATA_CACHE_NAME. + * @throws IllegalStateException if the restorable state does not contain values for DATASET_NAME and + * DATA_CACHE_NAME. */ - public LocalRasterServerElevationModel(String restorableStateInXml) - { + public LocalRasterServerElevationModel(String restorableStateInXml) { super(restorableStateInXml); this.createRasterServer((AVList) this.getValue(AVKey.CONSTRUCTION_PARAMETERS)); } - protected void createRasterServer(AVList params) - { - if (params == null) - { + protected void createRasterServer(AVList params) { + if (params == null) { String reason = Logging.getMessage("nullValue.ParamsIsNull"); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - if (this.getDataFileStore() == null) - { + if (this.getDataFileStore() == null) { String reason = Logging.getMessage("nullValue.FileStoreIsNull"); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); @@ -123,8 +113,7 @@ protected void createRasterServer(AVList params) } String datasetName = params.getStringValue(AVKey.DATASET_NAME); - if (WWUtil.isEmpty(datasetName)) - { + if (WWUtil.isEmpty(datasetName)) { String reason = Logging.getMessage("generic.MissingRequiredParameter", AVKey.DATASET_NAME); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); @@ -132,8 +121,7 @@ protected void createRasterServer(AVList params) } String dataCacheName = params.getStringValue(AVKey.DATA_CACHE_NAME); - if (WWUtil.isEmpty(dataCacheName)) - { + if (WWUtil.isEmpty(dataCacheName)) { String reason = Logging.getMessage("generic.MissingRequiredParameter", AVKey.DATA_CACHE_NAME); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); @@ -143,8 +131,7 @@ protected void createRasterServer(AVList params) String rasterServerConfigFilename = dataCacheName + File.separator + datasetName + ".RasterServer.xml"; final URL rasterServerFileURL = this.getDataFileStore().findFile(rasterServerConfigFilename, false); - if (WWUtil.isEmpty(rasterServerFileURL)) - { + if (WWUtil.isEmpty(rasterServerFileURL)) { String reason = Logging.getMessage("Configuration.ConfigNotFound", rasterServerConfigFilename); String msg = Logging.getMessage("generic.CannotCreateRasterServer", reason); Logging.logger().severe(msg); @@ -155,24 +142,21 @@ protected void createRasterServer(AVList params) rasterServerParams.setValue(AVKey.FILE_STORE, this.getDataFileStore()); - RetrieverFactory retrieverFactory = new RetrieverFactory() - { + RetrieverFactory retrieverFactory = new RetrieverFactory() { final protected RasterServer rasterServer = new BasicRasterServer(rasterServerFileURL, rasterServerParams); - public Retriever createRetriever(AVList tileParams, RetrievalPostProcessor postProcessor) - { - LocalRasterServerRetriever retriever = - new LocalRasterServerRetriever(tileParams, rasterServer, postProcessor); + public Retriever createRetriever(AVList tileParams, RetrievalPostProcessor postProcessor) { + LocalRasterServerRetriever retriever + = new LocalRasterServerRetriever(tileParams, rasterServer, postProcessor); // copy only values that do not exist in destination AVList // from rasterServerParams (source) to retriever (destination) - String[] keysToCopy = new String[] { + String[] keysToCopy = new String[]{ AVKey.DATASET_NAME, AVKey.DISPLAY_NAME, AVKey.FILE_STORE, AVKey.BYTE_ORDER, AVKey.IMAGE_FORMAT, AVKey.DATA_TYPE, AVKey.FORMAT_SUFFIX, AVKey.MISSING_DATA_SIGNAL, AVKey.MISSING_DATA_REPLACEMENT, - AVKey.ELEVATION_MIN, AVKey.ELEVATION_MAX, - }; + AVKey.ELEVATION_MIN, AVKey.ELEVATION_MAX,}; WWUtil.copyValues(rasterServerParams, retriever, keysToCopy, false); diff --git a/src/gov/nasa/worldwind/terrain/RectangularTessellator.java b/src/gov/nasa/worldwind/terrain/RectangularTessellator.java index ca1822d46f..13b036669e 100644 --- a/src/gov/nasa/worldwind/terrain/RectangularTessellator.java +++ b/src/gov/nasa/worldwind/terrain/RectangularTessellator.java @@ -26,10 +26,10 @@ * @author tag * @version $Id: RectangularTessellator.java 2922 2015-03-24 23:56:58Z tgaskins $ */ -public class RectangularTessellator extends WWObjectImpl implements Tessellator -{ - protected static class RenderInfo - { +public class RectangularTessellator extends WWObjectImpl implements Tessellator { + + protected static class RenderInfo { + protected final int density; protected final Vec4 referenceCenter; protected final FloatBuffer vertices; @@ -39,8 +39,7 @@ protected static class RenderInfo protected Object vboCacheKey = new Object(); protected boolean isVboBound = false; - protected RenderInfo(DrawContext dc, int density, FloatBuffer vertices, Vec4 refCenter) - { + protected RenderInfo(DrawContext dc, int density, FloatBuffer vertices, Vec4 refCenter) { //Fill in the buffers and buffer IDs and store them in hash maps by density createIndices(density); createTextureCoordinates(density); @@ -55,47 +54,40 @@ protected RenderInfo(DrawContext dc, int density, FloatBuffer vertices, Vec4 ref this.texCoords = textureCoords.get(this.density); this.time = System.currentTimeMillis(); - if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) + if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) { this.fillVerticesVBO(dc); + } } - public int getDensity() - { + public int getDensity() { return this.density; } - public Vec4 getReferenceCenter() - { + public Vec4 getReferenceCenter() { return this.referenceCenter; } - public FloatBuffer getVertices() - { + public FloatBuffer getVertices() { return this.vertices; } - public FloatBuffer getTexCoords() - { + public FloatBuffer getTexCoords() { return this.texCoords; } - public IntBuffer getIndices() - { + public IntBuffer getIndices() { return this.indices; } - public long getTime() - { + public long getTime() { return this.time; } - public Object getVboCacheKey() - { + public Object getVboCacheKey() { return this.vboCacheKey; } - public boolean isVboBound() - { + public boolean isVboBound() { return this.isVboBound; } @@ -104,49 +96,43 @@ public boolean isVboBound() * * @param dc the current draw context. */ - protected void update(DrawContext dc) - { + protected void update(DrawContext dc) { this.time = System.currentTimeMillis(); - if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) + if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) { this.fillVerticesVBO(dc); + } } - protected long getSizeInBytes() - { + protected long getSizeInBytes() { // Texture coordinates are shared among all tiles of the same density, so do not count towards size. // 8 references, floats in buffer. return 8 * 4 + (this.vertices.limit()) * Float.SIZE / 8; } - protected void fillVerticesVBO(DrawContext dc) - { + protected void fillVerticesVBO(DrawContext dc) { GL gl = dc.getGL(); int[] vboIds = (int[]) dc.getGpuResourceCache().get(this.vboCacheKey); - if (vboIds == null) - { + if (vboIds == null) { vboIds = new int[1]; gl.glGenBuffers(vboIds.length, vboIds, 0); int size = this.vertices.limit() * 4; dc.getGpuResourceCache().put(this.vboCacheKey, vboIds, GpuResourceCache.VBO_BUFFERS, size); } - try - { + try { FloatBuffer vb = this.vertices; gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]); gl.glBufferData(GL.GL_ARRAY_BUFFER, vb.limit() * 4, vb.rewind(), GL.GL_STATIC_DRAW); - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } } } - protected static class RectTile implements SectorGeometry - { + protected static class RectTile implements SectorGeometry { + protected final RectangularTessellator tessellator; // not needed if not a static class protected final int level; protected final Sector sector; @@ -158,8 +144,7 @@ protected static class RectTile implements SectorGeometry protected int minColorCode = 0; protected int maxColorCode = 0; - public RectTile(RectangularTessellator tessellator, Extent extent, int level, int density, Sector sector) - { + public RectTile(RectangularTessellator tessellator, Extent extent, int level, int density, Sector sector) { this.tessellator = tessellator; this.level = level; this.density = density; @@ -168,196 +153,165 @@ public RectTile(RectangularTessellator tessellator, Extent extent, int level, in this.cellSize = sector.getDeltaLatRadians() / density; } - public Sector getSector() - { + public Sector getSector() { return this.sector; } - public Extent getExtent() - { + public Extent getExtent() { return this.extent; } - public RectangularTessellator getTessellator() - { + public RectangularTessellator getTessellator() { return tessellator; } - public int getLevel() - { + public int getLevel() { return level; } - public int getDensity() - { + public int getDensity() { return density; } - public double getCellSize() - { + public double getCellSize() { return cellSize; } - public RenderInfo getRi() - { + public RenderInfo getRi() { return ri; } - public int getMinColorCode() - { + public int getMinColorCode() { return minColorCode; } - public int getMaxColorCode() - { + public int getMaxColorCode() { return maxColorCode; } - public void beginRendering(DrawContext dc, int numTextureUnits) - { + public void beginRendering(DrawContext dc, int numTextureUnits) { dc.getView().setReferenceCenter(dc, ri.referenceCenter); - if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) - { - if (this.tessellator.bindVbos(dc, this, numTextureUnits)) + if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) { + if (this.tessellator.bindVbos(dc, this, numTextureUnits)) { this.ri.isVboBound = true; + } } } - public void endRendering(DrawContext dc) - { - if (this.ri.isVboBound) - { + public void endRendering(DrawContext dc) { + if (this.ri.isVboBound) { dc.getGL().glBindBuffer(GL.GL_ARRAY_BUFFER, 0); dc.getGL().glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); this.ri.isVboBound = false; } } - public void renderMultiTexture(DrawContext dc, int numTextureUnits) - { + public void renderMultiTexture(DrawContext dc, int numTextureUnits) { this.tessellator.renderMultiTexture(dc, this, numTextureUnits); } - public void renderMultiTexture(DrawContext dc, int numTextureUnits, boolean beginRenderingCalled) - { - if (beginRenderingCalled) - { + public void renderMultiTexture(DrawContext dc, int numTextureUnits, boolean beginRenderingCalled) { + if (beginRenderingCalled) { this.tessellator.renderMultiTexture(dc, this, numTextureUnits); - } - else - { + } else { this.beginRendering(dc, numTextureUnits); this.tessellator.renderMultiTexture(dc, this, numTextureUnits); this.endRendering(dc); } } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { this.beginRendering(dc, 1); this.tessellator.render(dc, this); this.endRendering(dc); } - public void render(DrawContext dc, boolean beginRenderingCalled) - { - if (beginRenderingCalled) - { + public void render(DrawContext dc, boolean beginRenderingCalled) { + if (beginRenderingCalled) { this.tessellator.render(dc, this); - } - else - { + } else { this.beginRendering(dc, 1); this.tessellator.render(dc, this); this.endRendering(dc); } } - public void renderWireframe(DrawContext dc, boolean showTriangles, boolean showTileBoundary) - { + public void renderWireframe(DrawContext dc, boolean showTriangles, boolean showTileBoundary) { this.tessellator.renderWireframe(dc, this, showTriangles, showTileBoundary); } - public void renderBoundingVolume(DrawContext dc) - { + public void renderBoundingVolume(DrawContext dc) { this.tessellator.renderBoundingVolume(dc, this); } - public void renderTileID(DrawContext dc) - { + public void renderTileID(DrawContext dc) { this.tessellator.renderTileID(dc, this); } - public PickedObject[] pick(DrawContext dc, List pickPoints) - { + public PickedObject[] pick(DrawContext dc, List pickPoints) { return this.tessellator.pick(dc, this, pickPoints); } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { this.tessellator.pick(dc, this, pickPoint); } - public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset) - { + public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset) { return this.tessellator.getSurfacePoint(this, latitude, longitude, metersOffset); } - public double getResolution() - { + public double getResolution() { return this.sector.getDeltaLatRadians() / this.density; } - public Intersection[] intersect(Line line) - { + public Intersection[] intersect(Line line) { return this.tessellator.intersect(this, line); } - public Intersection[] intersect(double elevation) - { + public Intersection[] intersect(double elevation) { return this.tessellator.intersect(this, elevation); } - public DoubleBuffer makeTextureCoordinates(GeographicTextureCoordinateComputer computer) - { + public DoubleBuffer makeTextureCoordinates(GeographicTextureCoordinateComputer computer) { return this.tessellator.makeGeographicTexCoords(this, computer); } } - protected static class CacheKey - { + protected static class CacheKey { + protected final Sector sector; protected final int density; protected final Object globeStateKey; - public CacheKey(DrawContext dc, Sector sector, int density) - { + public CacheKey(DrawContext dc, Sector sector, int density) { this.sector = sector; this.density = density; this.globeStateKey = dc.getGlobe().getStateKey(dc); } @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; + } CacheKey cacheKey = (CacheKey) o; // Note: no check of class type equivalence, for performance - if (density != cacheKey.density) + if (density != cacheKey.density) { return false; - if (globeStateKey != null ? !globeStateKey.equals(cacheKey.globeStateKey) : cacheKey.globeStateKey != null) + } + if (globeStateKey != null ? !globeStateKey.equals(cacheKey.globeStateKey) : cacheKey.globeStateKey != null) { return false; + } //noinspection RedundantIfStatement - if (sector != null ? !sector.equals(cacheKey.sector) : cacheKey.sector != null) + if (sector != null ? !sector.equals(cacheKey.sector) : cacheKey.sector != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result; result = (sector != null ? sector.hashCode() : 0); result = 31 * result + density; @@ -366,12 +320,11 @@ public int hashCode() } } - protected static class TopLevelTiles - { + protected static class TopLevelTiles { + protected ArrayList topLevels; - public TopLevelTiles(ArrayList topLevels) - { + public TopLevelTiles(ArrayList topLevels) { this.topLevels = topLevels; } } @@ -408,24 +361,20 @@ public TopLevelTiles(ArrayList topLevels) protected int density = DEFAULT_DENSITY; protected long updateFrequency = 2000; // milliseconds - public SectorGeometryList tessellate(DrawContext dc) - { - if (dc == null) - { + public SectorGeometryList tessellate(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (dc.getView() == null) - { + if (dc.getView() == null) { String msg = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - if (!WorldWind.getMemoryCacheSet().containsCache(CACHE_ID)) - { + if (!WorldWind.getMemoryCacheSet().containsCache(CACHE_ID)) { long size = Configuration.getLongValue(AVKey.SECTOR_GEOMETRY_CACHE_SIZE, 10000000L); MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size); cache.setName(CACHE_NAME); @@ -435,8 +384,7 @@ public SectorGeometryList tessellate(DrawContext dc) this.maxLevel = Configuration.getIntegerValue(AVKey.RECTANGULAR_TESSELLATOR_MAX_LEVEL, DEFAULT_MAX_LEVEL); TopLevelTiles topLevels = (TopLevelTiles) this.topLevelTilesCache.get(dc.getGlobe().getStateKey(dc)); - if (topLevels == null) - { + if (topLevels == null) { topLevels = new TopLevelTiles(this.createTopLevelTiles(dc)); this.topLevelTilesCache.put(dc.getGlobe().getStateKey(dc), topLevels); } @@ -446,15 +394,13 @@ public SectorGeometryList tessellate(DrawContext dc) this.currentCoverage = null; this.currentFrustum = dc.getView().getFrustumInModelCoordinates(); - for (RectTile tile : topLevels.topLevels) - { + for (RectTile tile : topLevels.topLevels) { this.selectVisibleTiles(dc, tile); } this.currentTiles.setSector(this.currentCoverage); - for (SectorGeometry tile : this.currentTiles) - { + for (SectorGeometry tile : this.currentTiles) { this.makeVerts(dc, (RectTile) tile); } @@ -465,35 +411,33 @@ public SectorGeometryList tessellate(DrawContext dc) return sgl; } - protected ArrayList createTopLevelTiles(DrawContext dc) - { - ArrayList tops = - new ArrayList(this.numLevel0LatSubdivisions * this.numLevel0LonSubdivisions); + protected ArrayList createTopLevelTiles(DrawContext dc) { + ArrayList tops + = new ArrayList(this.numLevel0LatSubdivisions * this.numLevel0LonSubdivisions); this.globe = dc.getGlobe(); double deltaLat = 180d / this.numLevel0LatSubdivisions; double deltaLon = 360d / this.numLevel0LonSubdivisions; Angle lastLat = Angle.NEG90; - for (int row = 0; row < this.numLevel0LatSubdivisions; row++) - { + for (int row = 0; row < this.numLevel0LatSubdivisions; row++) { Angle lat = lastLat.addDegrees(deltaLat); - if (lat.getDegrees() + 1d > 90d) + if (lat.getDegrees() + 1d > 90d) { lat = Angle.POS90; + } Angle lastLon = Angle.NEG180; - for (int col = 0; col < this.numLevel0LonSubdivisions; col++) - { + for (int col = 0; col < this.numLevel0LonSubdivisions; col++) { Angle lon = lastLon.addDegrees(deltaLon); - if (lon.getDegrees() + 1d > 180d) + if (lon.getDegrees() + 1d > 180d) { lon = Angle.POS180; + } Sector tileSector = new Sector(lastLat, lat, lastLon, lon); boolean skipTile = dc.is2DGlobe() && this.skipTile(dc, tileSector); - if (!skipTile) - { + if (!skipTile) { tops.add(this.createTile(dc, tileSector, 0)); } @@ -508,64 +452,58 @@ protected ArrayList createTopLevelTiles(DrawContext dc) /** * Determines whether a tile is within a 2D globe's projection limits. * - * @param dc the current draw context. The globe contained in the context must be a {@link + * @param dc the current draw context. The globe contained in the context must be a {@link * gov.nasa.worldwind.globes.Globe2D}. * @param sector the tile's sector. * * @return true if the tile should be skipped -- it's outside the globe's projection limits -- * otherwise false. */ - protected boolean skipTile(DrawContext dc, Sector sector) - { + protected boolean skipTile(DrawContext dc, Sector sector) { Sector limits = ((Globe2D) dc.getGlobe()).getProjection().getProjectionLimits(); - if (limits == null || limits.equals(Sector.FULL_SPHERE)) + if (limits == null || limits.equals(Sector.FULL_SPHERE)) { return false; + } return !sector.intersectsInterior(limits); } - protected RectTile createTile(DrawContext dc, Sector tileSector, int level) - { + protected RectTile createTile(DrawContext dc, Sector tileSector, int level) { Extent extent = Sector.computeBoundingBox(dc.getGlobe(), dc.getVerticalExaggeration(), tileSector); return new RectTile(this, extent, level, this.density, tileSector); } - public boolean isMakeTileSkirts() - { + public boolean isMakeTileSkirts() { return makeTileSkirts; } - public void setMakeTileSkirts(boolean makeTileSkirts) - { + public void setMakeTileSkirts(boolean makeTileSkirts) { this.makeTileSkirts = makeTileSkirts; } - public long getUpdateFrequency() - { + public long getUpdateFrequency() { return this.updateFrequency; } - public void setUpdateFrequency(long updateFrequency) - { + public void setUpdateFrequency(long updateFrequency) { this.updateFrequency = updateFrequency; } - protected void selectVisibleTiles(DrawContext dc, RectTile tile) - { - if (dc.is2DGlobe() && this.skipTile(dc, tile.getSector())) + protected void selectVisibleTiles(DrawContext dc, RectTile tile) { + if (dc.is2DGlobe() && this.skipTile(dc, tile.getSector())) { return; + } Extent extent = tile.getExtent(); - if (extent != null && !extent.intersects(this.currentFrustum)) + if (extent != null && !extent.intersects(this.currentFrustum)) { return; + } - if (this.currentLevel < this.maxLevel - 1 && !this.atBestResolution(dc, tile) && this.needToSplit(dc, tile)) - { + if (this.currentLevel < this.maxLevel - 1 && !this.atBestResolution(dc, tile) && this.needToSplit(dc, tile)) { ++this.currentLevel; RectTile[] subtiles = this.split(dc, tile); - for (RectTile child : subtiles) - { + for (RectTile child : subtiles) { this.selectVisibleTiles(dc, child); } --this.currentLevel; @@ -575,15 +513,13 @@ protected void selectVisibleTiles(DrawContext dc, RectTile tile) this.currentTiles.add(tile); } - protected boolean atBestResolution(DrawContext dc, RectTile tile) - { + protected boolean atBestResolution(DrawContext dc, RectTile tile) { double bestResolution = dc.getGlobe().getElevationModel().getBestResolution(tile.getSector()); return tile.getCellSize() <= bestResolution; } - protected boolean needToSplit(DrawContext dc, RectTile tile) - { + protected boolean needToSplit(DrawContext dc, RectTile tile) { // Compute the height in meters of a cell from the specified tile. Take care to convert from the radians to // meters by multiplying by the globe's radius, not the length of a Cartesian point. Using the length of a // Cartesian point is incorrect when the globe is flat. @@ -598,8 +534,9 @@ protected boolean needToSplit(DrawContext dc, RectTile tile) // 50% has the same effect on object size as decreasing the distance between the eye and the object by 50%. // The detail hint is reduced by 50% for tiles above 75 degrees north and below 75 degrees south. double s = this.computeTileResolutionTarget(dc, tile); - if (tile.getSector().getMinLatitude().degrees >= 75 || tile.getSector().getMaxLatitude().degrees <= -75) + if (tile.getSector().getMinLatitude().degrees >= 75 || tile.getSector().getMaxLatitude().degrees <= -75) { s *= 0.5; + } double detailScale = Math.pow(10, -s); double fieldOfViewScale = dc.getView().getFieldOfView().tanHalfAngle() / Angle.fromDegrees(45).tanHalfAngle(); fieldOfViewScale = WWMath.clamp(fieldOfViewScale, 0, 1); @@ -618,16 +555,14 @@ protected boolean needToSplit(DrawContext dc, RectTile tile) return cellSizeMeters > scaledEyeDistanceMeters; } - protected double computeTileResolutionTarget(DrawContext dc, RectTile tile) - { + protected double computeTileResolutionTarget(DrawContext dc, RectTile tile) { // Compute the log10 detail target for the specified tile. Apply the elevation model's detail hint to the // default detail target. return DEFAULT_LOG10_RESOLUTION_TARGET + dc.getGlobe().getElevationModel().getDetailHint(tile.sector); } - protected RectTile[] split(DrawContext dc, RectTile tile) - { + protected RectTile[] split(DrawContext dc, RectTile tile) { Sector[] sectors = tile.sector.subdivide(); RectTile[] subTiles = new RectTile[4]; @@ -639,39 +574,35 @@ protected RectTile[] split(DrawContext dc, RectTile tile) return subTiles; } - protected RectangularTessellator.CacheKey createCacheKey(DrawContext dc, RectTile tile) - { + protected RectangularTessellator.CacheKey createCacheKey(DrawContext dc, RectTile tile) { return new CacheKey(dc, tile.sector, tile.density); } - protected void makeVerts(DrawContext dc, RectTile tile) - { + protected void makeVerts(DrawContext dc, RectTile tile) { // First see if the vertices have been previously computed and are in the cache. Since the elevation model // contents can change between frames, regenerate and re-cache vertices every second. MemoryCache cache = WorldWind.getMemoryCache(CACHE_ID); CacheKey cacheKey = this.createCacheKey(dc, tile); tile.ri = (RenderInfo) cache.getObject(cacheKey); - if (tile.ri != null && tile.ri.time >= System.currentTimeMillis() - this.getUpdateFrequency()) + if (tile.ri != null && tile.ri.time >= System.currentTimeMillis() - this.getUpdateFrequency()) { return; + } - if (this.buildVerts(dc, tile, this.makeTileSkirts)) + if (this.buildVerts(dc, tile, this.makeTileSkirts)) { cache.add(cacheKey, tile.ri, tile.ri.getSizeInBytes()); + } } - public boolean buildVerts(DrawContext dc, RectTile tile, boolean makeSkirts) - { + public boolean buildVerts(DrawContext dc, RectTile tile, boolean makeSkirts) { int density = tile.density; int numVertices = (density + 3) * (density + 3); FloatBuffer verts; //Re-use the RenderInfo vertices buffer. If it has not been set or the density has changed, create a new buffer - if (tile.ri == null || tile.ri.vertices == null || density != tile.ri.density) - { + if (tile.ri == null || tile.ri.vertices == null || density != tile.ri.density) { verts = Buffers.newDirectFloatBuffer(numVertices * 3); - } - else - { + } else { verts = tile.ri.vertices; verts.rewind(); } @@ -691,8 +622,9 @@ public boolean buildVerts(DrawContext dc, RectTile tile, boolean makeSkirts) // is not its true minimum is a bug, and this constraint on applying exaggeration to the minimum here is a // workaround for that bug. See WWJINT-435. Double exaggeratedMinElevation = makeSkirts ? globe.getMinElevation() : null; - if (exaggeratedMinElevation != null && (exaggeratedMinElevation < 0 || verticalExaggeration <= 0)) + if (exaggeratedMinElevation != null && (exaggeratedMinElevation < 0 || verticalExaggeration <= 0)) { exaggeratedMinElevation *= verticalExaggeration; + } LatLon centroid = tile.sector.getCentroid(); Vec4 refCenter = globe.computePointFromPosition(centroid.getLatitude(), centroid.getLongitude(), 0d); @@ -700,17 +632,16 @@ public boolean buildVerts(DrawContext dc, RectTile tile, boolean makeSkirts) int ie = 0; int iv = 0; Iterator latLonIter = latlons.iterator(); - for (int j = 0; j <= density + 2; j++) - { - for (int i = 0; i <= density + 2; i++) - { + for (int j = 0; j <= density + 2; j++) { + for (int i = 0; i <= density + 2; i++) { LatLon latlon = latLonIter.next(); double elevation = verticalExaggeration * elevations[ie++]; // Tile edges use min elevation to draw the skirts - if (exaggeratedMinElevation != null && - (j == 0 || j >= tile.density + 2 || i == 0 || i >= tile.density + 2)) + if (exaggeratedMinElevation != null + && (j == 0 || j >= tile.density + 2 || i == 0 || i >= tile.density + 2)) { elevation = exaggeratedMinElevation; + } Vec4 p = globe.computePointFromPosition(latlon.getLatitude(), latlon.getLongitude(), elevation); verts.put(iv++, (float) (p.x - refCenter.x)); @@ -721,8 +652,7 @@ public boolean buildVerts(DrawContext dc, RectTile tile, boolean makeSkirts) verts.rewind(); - if (tile.ri != null) - { + if (tile.ri != null) { tile.ri.update(dc); return false; } @@ -731,8 +661,7 @@ public boolean buildVerts(DrawContext dc, RectTile tile, boolean makeSkirts) return true; } - protected ArrayList computeLocations(RectTile tile) - { + protected ArrayList computeLocations(RectTile tile) { int density = tile.density; int numVertices = (density + 3) * (density + 3); @@ -745,44 +674,42 @@ protected ArrayList computeLocations(RectTile tile) Angle dLon = tile.sector.getDeltaLon().divide(density); ArrayList latlons = new ArrayList(numVertices); - for (int j = 0; j <= density + 2; j++) - { + for (int j = 0; j <= density + 2; j++) { Angle lon = lonMin; - for (int i = 0; i <= density + 2; i++) - { + for (int i = 0; i <= density + 2; i++) { latlons.add(new LatLon(lat, lon)); - if (i > density) + if (i > density) { lon = lonMax; - else if (i != 0) + } else if (i != 0) { lon = lon.add(dLon); + } - if (lon.degrees < -180) + if (lon.degrees < -180) { lon = Angle.NEG180; - else if (lon.degrees > 180) + } else if (lon.degrees > 180) { lon = Angle.POS180; + } } - if (j > density) + if (j > density) { lat = latMax; - else if (j != 0) + } else if (j != 0) { lat = lat.add(dLat); + } } return latlons; } - protected void renderMultiTexture(DrawContext dc, RectTile tile, int numTextureUnits) - { - if (dc == null) - { + protected void renderMultiTexture(DrawContext dc, RectTile tile, int numTextureUnits) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (numTextureUnits < 1) - { + if (numTextureUnits < 1) { String msg = Logging.getMessage("generic.NumTextureUnitsLessThanOne"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -791,10 +718,8 @@ protected void renderMultiTexture(DrawContext dc, RectTile tile, int numTextureU this.render(dc, tile, numTextureUnits); } - protected void render(DrawContext dc, RectTile tile) - { - if (dc == null) - { + protected void render(DrawContext dc, RectTile tile) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -803,8 +728,7 @@ protected void render(DrawContext dc, RectTile tile) this.render(dc, tile, 1); } - public void beginRendering(DrawContext dc) - { + public void beginRendering(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glPushClientAttrib(GL2.GL_CLIENT_VERTEX_ARRAY_BIT); @@ -815,85 +739,72 @@ public void beginRendering(DrawContext dc) dc.getView().pushReferenceCenter(dc, Vec4.ZERO); } - public void endRendering(DrawContext dc) - { + public void endRendering(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. dc.getView().popReferenceCenter(dc); gl.glPopClientAttrib(); } - protected long render(DrawContext dc, RectTile tile, int numTextureUnits) - { - if (tile.ri == null) - { + protected long render(DrawContext dc, RectTile tile, int numTextureUnits) { + if (tile.ri == null) { String msg = Logging.getMessage("nullValue.RenderInfoIsNull"); Logging.logger().severe(msg); throw new IllegalStateException(msg); } - if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) - { - if (!this.renderVBO(dc, tile, numTextureUnits)) - { + if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) { + if (!this.renderVBO(dc, tile, numTextureUnits)) { // Fall back to VA rendering. This is an error condition at this point because something went wrong with // VBO fill or binding. But we can still probably draw the tile using vertex arrays. dc.getGL().glBindBuffer(GL.GL_ARRAY_BUFFER, 0); dc.getGL().glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); this.renderVA(dc, tile, numTextureUnits); } - } - else - { + } else { this.renderVA(dc, tile, numTextureUnits); } return tile.ri.indices.limit() - 2; // return number of triangles rendered } - protected void renderVA(DrawContext dc, RectTile tile, int numTextureUnits) - { + protected void renderVA(DrawContext dc, RectTile tile, int numTextureUnits) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glVertexPointer(3, GL.GL_FLOAT, 0, tile.ri.vertices.rewind()); - for (int i = 0; i < numTextureUnits; i++) - { + for (int i = 0; i < numTextureUnits; i++) { gl.glClientActiveTexture(GL2.GL_TEXTURE0 + i); gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); Object texCoords = dc.getValue(AVKey.TEXTURE_COORDINATES); - if (texCoords != null && texCoords instanceof DoubleBuffer) + if (texCoords != null && texCoords instanceof DoubleBuffer) { gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, ((DoubleBuffer) texCoords).rewind()); - else + } else { gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, tile.ri.texCoords.rewind()); + } } gl.glDrawElements(GL.GL_TRIANGLE_STRIP, tile.ri.indices.limit(), GL.GL_UNSIGNED_INT, tile.ri.indices.rewind()); } - protected boolean renderVBO(DrawContext dc, RectTile tile, int numTextureUnits) - { - if (tile.ri.isVboBound || this.bindVbos(dc, tile, numTextureUnits)) - { + protected boolean renderVBO(DrawContext dc, RectTile tile, int numTextureUnits) { + if (tile.ri.isVboBound || this.bindVbos(dc, tile, numTextureUnits)) { // Render the tile dc.getGL().glDrawElements(GL.GL_TRIANGLE_STRIP, tile.ri.indices.limit(), GL.GL_UNSIGNED_INT, 0); return true; - } - else - { + } else { return false; } } - protected boolean bindVbos(DrawContext dc, RectTile tile, int numTextureUnits) - { + protected boolean bindVbos(DrawContext dc, RectTile tile, int numTextureUnits) { int[] verticesVboId = (int[]) dc.getGpuResourceCache().get(tile.ri.vboCacheKey); - if (verticesVboId == null) - { + if (verticesVboId == null) { tile.ri.fillVerticesVBO(dc); verticesVboId = (int[]) dc.getGpuResourceCache().get(tile.ri.vboCacheKey); - if (verticesVboId == null) + if (verticesVboId == null) { return false; + } } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -903,15 +814,13 @@ protected boolean bindVbos(DrawContext dc, RectTile tile, int numTextureUnits) gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0); // Bind texture coordinates - if (numTextureUnits > 0) - { + if (numTextureUnits > 0) { Object texCoordsVboCacheKey = textureCoordVboCacheKeys.get(tile.density); - int[] texCoordsVboId = (int[]) - (texCoordsVboCacheKey != null ? dc.getGpuResourceCache().get(texCoordsVboCacheKey) : null); - if (texCoordsVboId == null) + int[] texCoordsVboId = (int[]) (texCoordsVboCacheKey != null ? dc.getGpuResourceCache().get(texCoordsVboCacheKey) : null); + if (texCoordsVboId == null) { texCoordsVboId = this.fillTextureCoordsVbo(dc, tile.density, tile.ri.texCoords); - for (int i = 0; i < numTextureUnits; i++) - { + } + for (int i = 0; i < numTextureUnits; i++) { gl.glClientActiveTexture(GL2.GL_TEXTURE0 + i); gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY); @@ -922,30 +831,27 @@ protected boolean bindVbos(DrawContext dc, RectTile tile, int numTextureUnits) // Bind index list Object indexListVboCacheKey = indexListsVboCacheKeys.get(tile.density); - int[] indexListVboId = (int[]) - (indexListVboCacheKey != null ? dc.getGpuResourceCache().get(indexListVboCacheKey) : null); - if (indexListVboId == null) + int[] indexListVboId = (int[]) (indexListVboCacheKey != null ? dc.getGpuResourceCache().get(indexListVboCacheKey) : null); + if (indexListVboId == null) { indexListVboId = this.fillIndexListVbo(dc, tile.density, tile.ri.indices); - if (indexListVboId != null) + } + if (indexListVboId != null) { gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, indexListVboId[0]); + } return indexListVboId != null; } - protected int[] fillIndexListVbo(DrawContext dc, int density, IntBuffer indices) - { + protected int[] fillIndexListVbo(DrawContext dc, int density, IntBuffer indices) { GL gl = dc.getGL(); Object indexListVboCacheKey = indexListsVboCacheKeys.get(density); - int[] indexListVboId = (int[]) - (indexListVboCacheKey != null ? dc.getGpuResourceCache().get(indexListVboCacheKey) : null); - if (indexListVboId == null) - { + int[] indexListVboId = (int[]) (indexListVboCacheKey != null ? dc.getGpuResourceCache().get(indexListVboCacheKey) : null); + if (indexListVboId == null) { indexListVboId = new int[1]; gl.glGenBuffers(indexListVboId.length, indexListVboId, 0); - if (indexListVboCacheKey == null) - { + if (indexListVboCacheKey == null) { indexListVboCacheKey = new Object(); indexListsVboCacheKeys.put(density, indexListVboCacheKey); } @@ -954,33 +860,26 @@ protected int[] fillIndexListVbo(DrawContext dc, int density, IntBuffer indices) dc.getGpuResourceCache().put(indexListVboCacheKey, indexListVboId, GpuResourceCache.VBO_BUFFERS, size); } - try - { + try { gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, indexListVboId[0]); gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indices.limit() * 4, indices.rewind(), GL.GL_STATIC_DRAW); - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0); } return indexListVboId; } - protected int[] fillTextureCoordsVbo(DrawContext dc, int density, FloatBuffer texCoords) - { + protected int[] fillTextureCoordsVbo(DrawContext dc, int density, FloatBuffer texCoords) { GL gl = dc.getGL(); Object texCoordVboCacheKey = textureCoordVboCacheKeys.get(density); - int[] texCoordVboId = (int[]) - (texCoordVboCacheKey != null ? dc.getGpuResourceCache().get(texCoordVboCacheKey) : null); - if (texCoordVboId == null) - { + int[] texCoordVboId = (int[]) (texCoordVboCacheKey != null ? dc.getGpuResourceCache().get(texCoordVboCacheKey) : null); + if (texCoordVboId == null) { texCoordVboId = new int[1]; gl.glGenBuffers(texCoordVboId.length, texCoordVboId, 0); - if (texCoordVboCacheKey == null) - { + if (texCoordVboCacheKey == null) { texCoordVboCacheKey = new Object(); textureCoordVboCacheKeys.put(density, texCoordVboCacheKey); } @@ -989,30 +888,24 @@ protected int[] fillTextureCoordsVbo(DrawContext dc, int density, FloatBuffer te dc.getGpuResourceCache().put(texCoordVboCacheKey, texCoordVboId, GpuResourceCache.VBO_BUFFERS, size); } - try - { + try { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, texCoordVboId[0]); gl.glBufferData(GL.GL_ARRAY_BUFFER, texCoords.limit() * 4, texCoords.rewind(), GL.GL_STATIC_DRAW); - } - finally - { + } finally { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); } return texCoordVboId; } - protected void renderWireframe(DrawContext dc, RectTile tile, boolean showTriangles, boolean showTileBoundary) - { - if (dc == null) - { + protected void renderWireframe(DrawContext dc, RectTile tile, boolean showTriangles, boolean showTileBoundary) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (tile.ri == null) - { + if (tile.ri == null) { String msg = Logging.getMessage("nullValue.RenderInfoIsNull"); Logging.logger().severe(msg); throw new IllegalStateException(msg); @@ -1022,7 +915,7 @@ protected void renderWireframe(DrawContext dc, RectTile tile, boolean showTriang GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glPushAttrib( - GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_POLYGON_BIT | GL2.GL_ENABLE_BIT | GL2.GL_CURRENT_BIT); + GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_POLYGON_BIT | GL2.GL_ENABLE_BIT | GL2.GL_CURRENT_BIT); gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE); gl.glDisable(GL.GL_DEPTH_TEST); @@ -1031,22 +924,18 @@ protected void renderWireframe(DrawContext dc, RectTile tile, boolean showTriang gl.glColor4d(1d, 1d, 1d, 0.2); gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_LINE); - if (showTriangles) - { + if (showTriangles) { OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { ogsh.pushClientAttrib(gl, GL2.GL_CLIENT_VERTEX_ARRAY_BIT); gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL.GL_FLOAT, 0, tile.ri.vertices.rewind()); gl.glDrawElements(GL.GL_TRIANGLE_STRIP, tile.ri.indices.limit(), - GL.GL_UNSIGNED_INT, tile.ri.indices.rewind()); - } - finally - { + GL.GL_UNSIGNED_INT, tile.ri.indices.rewind()); + } finally { ogsh.pop(gl); } } @@ -1055,18 +944,17 @@ protected void renderWireframe(DrawContext dc, RectTile tile, boolean showTriang gl.glPopAttrib(); - if (showTileBoundary) + if (showTileBoundary) { this.renderPatchBoundary(dc, tile); + } } - protected void renderPatchBoundary(DrawContext dc, RectTile tile) - { + protected void renderPatchBoundary(DrawContext dc, RectTile tile) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushAttrib(gl, GL2.GL_ENABLE_BIT | GL2.GL_CURRENT_BIT | GL2.GL_POLYGON_BIT); - try - { + try { gl.glDisable(GL.GL_BLEND); // Don't perform depth clipping but turn on backface culling @@ -1084,34 +972,31 @@ protected void renderPatchBoundary(DrawContext dc, RectTile tile) gl.glVertex3d(corners[2].x, corners[2].y, corners[2].z); gl.glVertex3d(corners[3].x, corners[3].y, corners[3].z); gl.glEnd(); - } - finally - { + } finally { ogsh.pop(gl); } } - protected void renderBoundingVolume(DrawContext dc, RectTile tile) - { + protected void renderBoundingVolume(DrawContext dc, RectTile tile) { Extent extent = tile.getExtent(); - if (extent == null) + if (extent == null) { return; + } - if (extent instanceof Renderable) + if (extent instanceof Renderable) { ((Renderable) extent).render(dc); + } } - protected void renderTileID(DrawContext dc, RectTile tile) - { + protected void renderTileID(DrawContext dc, RectTile tile) { java.awt.Rectangle viewport = dc.getView().getViewport(); TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - java.awt.Font.decode("Arial-Plain-15")); + java.awt.Font.decode("Arial-Plain-15")); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { ogsh.pushAttrib(gl, GL2.GL_ENABLE_BIT); dc.getGL().glDisable(GL.GL_DEPTH_TEST); @@ -1121,71 +1006,68 @@ protected void renderTileID(DrawContext dc, RectTile tile) textRenderer.setColor(Color.RED); String tileLabel = Integer.toString(tile.level); double[] elevs = this.globe.getMinAndMaxElevations(tile.getSector()); - if (elevs != null) + if (elevs != null) { tileLabel += ", " + (int) elevs[0] + "/" + (int) elevs[1]; + } LatLon ll = tile.getSector().getCentroid(); Vec4 pt = dc.getGlobe().computePointFromPosition(ll.getLatitude(), ll.getLongitude(), - dc.getGlobe().getElevation(ll.getLatitude(), ll.getLongitude())); + dc.getGlobe().getElevation(ll.getLatitude(), ll.getLongitude())); pt = dc.getView().project(pt); textRenderer.draw(tileLabel, (int) pt.x, (int) pt.y); textRenderer.setColor(Color.WHITE); textRenderer.endRendering(); - } - finally - { + } finally { ogsh.pop(gl); } } - protected PickedObject[] pick(DrawContext dc, RectTile tile, List pickPoints) - { - if (dc == null) - { + protected PickedObject[] pick(DrawContext dc, RectTile tile, List pickPoints) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (pickPoints == null) - { + if (pickPoints == null) { String msg = Logging.getMessage("nullValue.PickPointList"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (pickPoints.size() == 0) + if (pickPoints.size() == 0) { return null; + } - if (tile.ri == null || tile.ri.vertices == null) + if (tile.ri == null || tile.ri.vertices == null) { return null; + } PickedObject[] pos = new PickedObject[pickPoints.size()]; this.renderTrianglesWithUniqueColors(dc, tile); - for (int i = 0; i < pickPoints.size(); i++) - { + for (int i = 0; i < pickPoints.size(); i++) { pos[i] = this.resolvePick(dc, tile, pickPoints.get(i)); } return pos; } - protected void pick(DrawContext dc, RectTile tile, Point pickPoint) - { - if (dc == null) - { + protected void pick(DrawContext dc, RectTile tile, Point pickPoint) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (tile.ri == null || tile.ri.vertices == null) + if (tile.ri == null || tile.ri.vertices == null) { return; + } renderTrianglesWithUniqueColors(dc, tile); PickedObject po = this.resolvePick(dc, tile, pickPoint); - if (po != null) + if (po != null) { dc.addPickedObject(po); + } } /** @@ -1194,11 +1076,10 @@ protected void pick(DrawContext dc, RectTile tile, Point pickPoint) * Note: This method modifies the GL_VERTEX_ARRAY and GL_COLOR_ARRAY state and does not restore it. Callers should * ensure that GL_CLIENT_VERTEX_ARRAY_BIT has been pushed, and eventually pop it when done using this method. * - * @param dc the current draw context. + * @param dc the current draw context. * @param tile the tile to render. */ - protected void renderTrianglesWithUniqueColors(DrawContext dc, RectTile tile) - { + protected void renderTrianglesWithUniqueColors(DrawContext dc, RectTile tile) { //Fill the color buffers each frame with unique colors int sideSize = density + 2; int trianglesPerRow = sideSize * 2 + 4; @@ -1211,13 +1092,10 @@ protected void renderTrianglesWithUniqueColors(DrawContext dc, RectTile tile) ByteBuffer colorsEven; //Reuse the old color buffers if possible - if (oddRowColorList.containsKey(density) && evenRowColorList.containsKey(density)) - { + if (oddRowColorList.containsKey(density) && evenRowColorList.containsKey(density)) { colorsOdd = oddRowColorList.get(density); colorsEven = evenRowColorList.get(density); - } - else - { + } else { //Otherwise create new buffers colorsOdd = Buffers.newDirectByteBuffer(verticesSize); colorsEven = Buffers.newDirectByteBuffer(verticesSize); @@ -1231,8 +1109,7 @@ protected void renderTrianglesWithUniqueColors(DrawContext dc, RectTile tile) int prevPos = -1; int pos; - for (int i = 0; i < trianglesNum; i++) - { + for (int i = 0; i < trianglesNum; i++) { java.awt.Color color = dc.getUniquePickColor(); //NOTE: Get the indices for the last point for the triangle (i+2). @@ -1241,13 +1118,10 @@ protected void renderTrianglesWithUniqueColors(DrawContext dc, RectTile tile) //Since we are using a single triangle strip for all rows, we need to store the colors in alternate rows. // (The same vertices are used in both directions, however, we need different colors for those vertices) - if (pos > prevPos) - { + if (pos > prevPos) { colorsOdd.position(pos); colorsOdd.put((byte) color.getRed()).put((byte) color.getGreen()).put((byte) color.getBlue()); - } - else if (pos < prevPos) - { + } else if (pos < prevPos) { colorsEven.position(pos); colorsEven.put((byte) color.getRed()).put((byte) color.getGreen()).put((byte) color.getBlue()); } @@ -1259,76 +1133,69 @@ else if (pos < prevPos) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { - if (null != tile.ri.referenceCenter) + try { + if (null != tile.ri.referenceCenter) { dc.getView().pushReferenceCenter(dc, tile.ri.referenceCenter); + } gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); gl.glEnableClientState(GL2.GL_COLOR_ARRAY); // If using VBOs, bind the vertices VBO and the indices VBO but not the tex coords VBOs. - if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject() && this.bindVbos(dc, tile, 0)) - { + if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject() && this.bindVbos(dc, tile, 0)) { // VBOs are not used for the colors since they change every frame. gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0); //Draw the odd rows gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, colorsOdd.rewind()); - for (int i = 0; i < sideSize; i += 2) - { + for (int i = 0; i < sideSize; i += 2) { gl.glDrawElements(GL.GL_TRIANGLE_STRIP, trianglesPerRow, - GL.GL_UNSIGNED_INT, trianglesPerRow * i * 4); + GL.GL_UNSIGNED_INT, trianglesPerRow * i * 4); } //Draw the even rows gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, colorsEven.rewind()); - for (int i = 1; i < sideSize - 1; i += 2) - { + for (int i = 1; i < sideSize - 1; i += 2) { gl.glDrawElements(GL.GL_TRIANGLE_STRIP, trianglesPerRow, - GL.GL_UNSIGNED_INT, trianglesPerRow * i * 4); + GL.GL_UNSIGNED_INT, trianglesPerRow * i * 4); } - } - else - { + } else { gl.glVertexPointer(3, GL.GL_FLOAT, 0, tile.ri.vertices.rewind()); //Draw the odd rows gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, colorsOdd.rewind()); - for (int i = 0; i < sideSize; i += 2) - { + for (int i = 0; i < sideSize; i += 2) { gl.glDrawElements(GL.GL_TRIANGLE_STRIP, trianglesPerRow, - GL.GL_UNSIGNED_INT, tile.ri.indices.position(trianglesPerRow * i)); + GL.GL_UNSIGNED_INT, tile.ri.indices.position(trianglesPerRow * i)); } //Draw the even rows gl.glColorPointer(3, GL.GL_UNSIGNED_BYTE, 0, colorsEven.rewind()); - for (int i = 1; i < sideSize - 1; i += 2) - { + for (int i = 1; i < sideSize - 1; i += 2) { gl.glDrawElements(GL.GL_TRIANGLE_STRIP, trianglesPerRow, - GL.GL_UNSIGNED_INT, tile.ri.indices.position(trianglesPerRow * i)); + GL.GL_UNSIGNED_INT, tile.ri.indices.position(trianglesPerRow * i)); } } - } - finally - { - if (null != tile.ri.referenceCenter) + } finally { + if (null != tile.ri.referenceCenter) { dc.getView().popReferenceCenter(dc); + } } } - protected PickedObject resolvePick(DrawContext dc, RectTile tile, Point pickPoint) - { + protected PickedObject resolvePick(DrawContext dc, RectTile tile, Point pickPoint) { int colorCode = this.pickSupport.getTopColor(dc, pickPoint); - if (colorCode < tile.minColorCode || colorCode > tile.maxColorCode) + if (colorCode < tile.minColorCode || colorCode > tile.maxColorCode) { return null; + } double EPSILON = (double) 0.00001f; int triangleIndex = colorCode - tile.minColorCode - 1; - if (tile.ri.indices == null || triangleIndex >= (tile.ri.indices.capacity() - 2)) + if (tile.ri.indices == null || triangleIndex >= (tile.ri.indices.capacity() - 2)) { return null; + } double centerX = tile.ri.referenceCenter.x; double centerY = tile.ri.referenceCenter.y; @@ -1362,7 +1229,9 @@ protected PickedObject resolvePick(DrawContext dc, RectTile tile, Point pickPoin double a = -N.dot3(w0); double b = N.dot3(ray.getDirection()); if (java.lang.Math.abs(b) < EPSILON) // ray is parallel to triangle plane + { return null; // if a == 0 , ray lies in triangle plane + } double r = a / b; Vec4 intersect = ray.getOrigin().add3(ray.getDirection().multiply3(r)); @@ -1385,17 +1254,16 @@ protected PickedObject resolvePick(DrawContext dc, RectTile tile, Point pickPoin * @return an array of Intersection sorted by increasing distance from the line origin, or null if no * intersection was found. */ - protected Intersection[] intersect(RectTile tile, Line line) - { - if (line == null) - { + protected Intersection[] intersect(RectTile tile, Line line) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (tile.ri.vertices == null) + if (tile.ri.vertices == null) { return null; + } // Compute 'vertical' plane perpendicular to the ground, that contains the ray Plane verticalPlane = null; @@ -1407,14 +1275,16 @@ protected Intersection[] intersect(RectTile tile, Line line) { Vec4 normalV = line.getDirection().cross3(globe.computeSurfaceNormalAtPoint(line.getOrigin())); verticalPlane = new Plane(normalV.x(), normalV.y(), normalV.z(), -line.getOrigin().dot3(normalV)); - if (!tile.getExtent().intersects(verticalPlane)) + if (!tile.getExtent().intersects(verticalPlane)) { return null; + } // Compute 'horizontal' plane perpendicular to the vertical plane, that contains the ray Vec4 normalH = line.getDirection().cross3(normalV); horizontalPlane = new Plane(normalH.x(), normalH.y(), normalH.z(), -line.getOrigin().dot3(normalH)); - if (!tile.getExtent().intersects(horizontalPlane)) + if (!tile.getExtent().intersects(horizontalPlane)) { return null; + } // Compute maximum cell size based on tile delta lat, density and globe radius effectiveRadiusVertical = tile.extent.getEffectiveRadius(verticalPlane); @@ -1442,86 +1312,87 @@ protected Intersection[] intersect(RectTile tile, Line line) int startIndex = (density + 2) * 2 + 6; // skip first skirt row and a couple degenerate cells int endIndex = trianglesNum - startIndex; // ignore last skirt row and a couple degenerate cells int k = -1; - for (int i = startIndex; i < endIndex; i += 2) - { + for (int i = startIndex; i < endIndex; i += 2) { // Skip skirts and degenerate triangle cells - based on index sequence. k = k == density - 1 ? -4 : k + 1; // density x terrain cells interleaved with 4 skirt and degenerate cells. - if (k < 0) + if (k < 0) { continue; + } // Triangle pair diagonal - v1 & v2 int vIndex = 3 * indices[i + 1]; Vec4 v1 = new Vec4( - coords[vIndex++] + centerX, - coords[vIndex++] + centerY, - coords[vIndex] + centerZ); + coords[vIndex++] + centerX, + coords[vIndex++] + centerY, + coords[vIndex] + centerZ); vIndex = 3 * indices[i + 2]; Vec4 v2 = new Vec4( - coords[vIndex++] + centerX, - coords[vIndex++] + centerY, - coords[vIndex] + centerZ); + coords[vIndex++] + centerX, + coords[vIndex++] + centerY, + coords[vIndex] + centerZ); Vec4 cellCenter = Vec4.mix3(.5, v1, v2); // Test cell center distance to vertical plane - if (verticalPlane != null) - { - if (Math.abs(verticalPlane.distanceTo(cellCenter)) > effectiveRadiusVertical) + if (verticalPlane != null) { + if (Math.abs(verticalPlane.distanceTo(cellCenter)) > effectiveRadiusVertical) { continue; + } // Test cell center distance to horizontal plane - if (Math.abs(horizontalPlane.distanceTo(cellCenter)) > effectiveRadiusHorizontal) + if (Math.abs(horizontalPlane.distanceTo(cellCenter)) > effectiveRadiusHorizontal) { continue; + } } // Prepare to test triangles - get other two vertices v0 & v3 Vec4 p; vIndex = 3 * indices[i]; Vec4 v0 = new Vec4( - coords[vIndex++] + centerX, - coords[vIndex++] + centerY, - coords[vIndex] + centerZ); + coords[vIndex++] + centerX, + coords[vIndex++] + centerY, + coords[vIndex] + centerZ); vIndex = 3 * indices[i + 3]; Vec4 v3 = new Vec4( - coords[vIndex++] + centerX, - coords[vIndex++] + centerY, - coords[vIndex] + centerZ); + coords[vIndex++] + centerX, + coords[vIndex++] + centerY, + coords[vIndex] + centerZ); // Test triangle 1 intersection w ray Triangle t = new Triangle(v0, v1, v2); - if ((p = t.intersect(line)) != null) - { + if ((p = t.intersect(line)) != null) { list.add(new Intersection(p, false)); } // Test triangle 2 intersection w ray t = new Triangle(v1, v2, v3); - if ((p = t.intersect(line)) != null) - { + if ((p = t.intersect(line)) != null) { list.add(new Intersection(p, false)); } } int numHits = list.size(); - if (numHits == 0) + if (numHits == 0) { return null; + } hits = new Intersection[numHits]; list.toArray(hits); final Vec4 origin = line.getOrigin(); - Arrays.sort(hits, new Comparator() - { - public int compare(Intersection i1, Intersection i2) - { - if (i1 == null && i2 == null) + Arrays.sort(hits, new Comparator() { + public int compare(Intersection i1, Intersection i2) { + if (i1 == null && i2 == null) { return 0; - if (i2 == null) + } + if (i2 == null) { return -1; - if (i1 == null) + } + if (i1 == null) { return 1; + } Vec4 v1 = i1.getIntersectionPoint(); Vec4 v2 = i2.getIntersectionPoint(); @@ -1534,19 +1405,19 @@ public int compare(Intersection i1, Intersection i2) return hits; } - protected Intersection[] intersect(RectTile tile, double elevation) - { - if (tile.ri.vertices == null) + protected Intersection[] intersect(RectTile tile, double elevation) { + if (tile.ri.vertices == null) { return null; + } // Check whether the tile includes the intersection elevation - assume cylinder as Extent // TODO: replace this test with a generic test against Extent - if (tile.getExtent() instanceof Cylinder) - { + if (tile.getExtent() instanceof Cylinder) { Cylinder cylinder = ((Cylinder) tile.getExtent()); if (!(globe.isPointAboveElevation(cylinder.getBottomCenter(), elevation) - ^ globe.isPointAboveElevation(cylinder.getTopCenter(), elevation))) + ^ globe.isPointAboveElevation(cylinder.getTopCenter(), elevation))) { return null; + } } Intersection[] hits; @@ -1570,57 +1441,56 @@ protected Intersection[] intersect(RectTile tile, double elevation) int startIndex = (density + 2) * 2 + 6; // skip first skirt row and a couple degenerate cells int endIndex = trianglesNum - startIndex; // ignore last skirt row and a couple degenerate cells int k = -1; - for (int i = startIndex; i < endIndex; i += 2) - { + for (int i = startIndex; i < endIndex; i += 2) { // Skip skirts and degenerate triangle cells - based on indice sequence. k = k == density - 1 ? -4 : k + 1; // density x terrain cells interleaved with 4 skirt and degenerate cells. - if (k < 0) + if (k < 0) { continue; + } // Get the four cell corners int vIndex = 3 * indices[i]; Vec4 v0 = new Vec4( - coords[vIndex++] + centerX, - coords[vIndex++] + centerY, - coords[vIndex] + centerZ); + coords[vIndex++] + centerX, + coords[vIndex++] + centerY, + coords[vIndex] + centerZ); vIndex = 3 * indices[i + 1]; Vec4 v1 = new Vec4( - coords[vIndex++] + centerX, - coords[vIndex++] + centerY, - coords[vIndex] + centerZ); + coords[vIndex++] + centerX, + coords[vIndex++] + centerY, + coords[vIndex] + centerZ); vIndex = 3 * indices[i + 2]; Vec4 v2 = new Vec4( - coords[vIndex++] + centerX, - coords[vIndex++] + centerY, - coords[vIndex] + centerZ); + coords[vIndex++] + centerX, + coords[vIndex++] + centerY, + coords[vIndex] + centerZ); vIndex = 3 * indices[i + 3]; Vec4 v3 = new Vec4( - coords[vIndex++] + centerX, - coords[vIndex++] + centerY, - coords[vIndex] + centerZ); + coords[vIndex++] + centerX, + coords[vIndex++] + centerY, + coords[vIndex] + centerZ); Intersection[] inter; // Test triangle 1 intersection - if ((inter = globe.intersect(new Triangle(v0, v1, v2), elevation)) != null) - { + if ((inter = globe.intersect(new Triangle(v0, v1, v2), elevation)) != null) { list.add(inter[0]); list.add(inter[1]); } // Test triangle 2 intersection - if ((inter = globe.intersect(new Triangle(v1, v2, v3), elevation)) != null) - { + if ((inter = globe.intersect(new Triangle(v1, v2, v3), elevation)) != null) { list.add(inter[0]); list.add(inter[1]); } } int numHits = list.size(); - if (numHits == 0) + if (numHits == 0) { return null; + } hits = new Intersection[numHits]; list.toArray(hits); @@ -1628,11 +1498,11 @@ protected Intersection[] intersect(RectTile tile, double elevation) return hits; } - protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude, double metersOffset) - { + protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude, double metersOffset) { Vec4 result = this.getSurfacePoint(tile, latitude, longitude); - if (metersOffset != 0 && result != null) + if (metersOffset != 0 && result != null) { result = applyOffset(this.globe, result, metersOffset); + } return result; } @@ -1640,36 +1510,33 @@ protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude, d /** * Offsets point by metersOffset meters. * - * @param globe the Globe from which to offset - * @param point the Vec4 to offset + * @param globe the Globe from which to offset + * @param point the Vec4 to offset * @param metersOffset the magnitude of the offset * * @return point offset along its surface normal as if it were on globe */ - protected static Vec4 applyOffset(Globe globe, Vec4 point, double metersOffset) - { + protected static Vec4 applyOffset(Globe globe, Vec4 point, double metersOffset) { Vec4 normal = globe.computeSurfaceNormalAtPoint(point); point = Vec4.fromLine3(point, metersOffset, normal); return point; } - protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!tile.sector.contains(latitude, longitude)) - { + if (!tile.sector.contains(latitude, longitude)) { // not on this geometry return null; } - if (tile.ri == null) + if (tile.ri == null) { return null; + } double lat = latitude.getDegrees(); double lon = longitude.getDegrees(); @@ -1699,15 +1566,14 @@ protected Vec4 getSurfacePoint(RectTile tile, Angle latitude, Angle longitude) * edge of this sector, where between this column and the next column the corresponding position will fall, in the * range [0,1]. * - * @param start the number of the column or row to the left, below or on this position + * @param start the number of the column or row to the left, below or on this position * @param decimal the distance from the left or bottom of the current sector that this position falls * @param density the number of intervals along the sector's side * * @return a decimal ranged [0,1] representing the position between two columns or rows, rather than between two * edges of the sector */ - protected static double createPosition(int start, double decimal, int density) - { + protected static double createPosition(int start, double decimal, int density) { double l = ((double) start) / (double) density; double r = ((double) (start + 1)) / (double) density; @@ -1719,17 +1585,16 @@ protected static double createPosition(int start, double decimal, int density) * 1 and at yDec offset from row to row + 1. Accounts for the * diagonals. * - * @param row represents the row which corresponds to a yDec value of 0 + * @param row represents the row which corresponds to a yDec value of 0 * @param column represents the column which corresponds to an xDec value of 0 - * @param xDec constrained to [0,1] - * @param yDec constrained to [0,1] - * @param ri the render info holding the vertices, etc. + * @param xDec constrained to [0,1] + * @param yDec constrained to [0,1] + * @param ri the render info holding the vertices, etc. * * @return a Point geometrically within or on the boundary of the quadrilateral whose bottom left * corner is indexed by (row, column) */ - protected static Vec4 interpolate(int row, int column, double xDec, double yDec, RenderInfo ri) - { + protected static Vec4 interpolate(int row, int column, double xDec, double yDec, RenderInfo ri) { row++; column++; @@ -1765,28 +1630,24 @@ protected static Vec4 interpolate(int row, int column, double xDec, double yDec, * Calculates the point at (xDec, yDec) in the two triangles defined by {bL, bR, tL} and {bR, tR, tL}. If thought of * as a quadrilateral, the diagonal runs from tL to bR. Of course, this isn't a quad, it's two triangles. * - * @param bL the bottom left corner - * @param bR the bottom right corner - * @param tR the top right corner - * @param tL the top left corner + * @param bL the bottom left corner + * @param bR the bottom right corner + * @param tR the top right corner + * @param tL the top left corner * @param xDec how far along, [0,1] 0 = left edge, 1 = right edge * @param yDec how far along, [0,1] 0 = bottom edge, 1 = top edge * * @return the point xDec, yDec in the co-ordinate system defined by bL, bR, tR, tL */ - protected static Vec4 interpolate(Vec4 bL, Vec4 bR, Vec4 tR, Vec4 tL, double xDec, double yDec) - { + protected static Vec4 interpolate(Vec4 bL, Vec4 bR, Vec4 tR, Vec4 tL, double xDec, double yDec) { double pos = xDec + yDec; - if (pos == 1) - { + if (pos == 1) { // on the diagonal - what's more, we don't need to do any "oneMinusT" calculation return new Vec4( - tL.x * yDec + bR.x * xDec, - tL.y * yDec + bR.y * xDec, - tL.z * yDec + bR.z * xDec); - } - else if (pos > 1) - { + tL.x * yDec + bR.x * xDec, + tL.y * yDec + bR.y * xDec, + tL.z * yDec + bR.z * xDec); + } else if (pos > 1) { // in the "top right" half // vectors pointing from top right towards the point we want (can be thought of as "negative" vectors) @@ -1794,9 +1655,7 @@ else if (pos > 1) Vec4 verticalVector = (bR.subtract3(tR)).multiply3(1 - yDec); return tR.add3(horizontalVector).add3(verticalVector); - } - else - { + } else { // pos < 1 - in the "bottom left" half // vectors pointing from the bottom left towards the point we want @@ -1807,50 +1666,54 @@ else if (pos > 1) } } - protected static double[] baryCentricCoordsRequireInside(Vec4 pnt, Vec4[] V) - { + protected static double[] baryCentricCoordsRequireInside(Vec4 pnt, Vec4[] V) { // if pnt is in the interior of the triangle determined by V, return its // barycentric coordinates with respect to V. Otherwise return null. // b0: final double tol = 1.0e-4; double[] b0b1b2 = new double[3]; - double triangleHeight = - distanceFromLine(V[0], V[1], V[2].subtract3(V[1])); - double heightFromPoint = - distanceFromLine(pnt, V[1], V[2].subtract3(V[1])); + double triangleHeight + = distanceFromLine(V[0], V[1], V[2].subtract3(V[1])); + double heightFromPoint + = distanceFromLine(pnt, V[1], V[2].subtract3(V[1])); b0b1b2[0] = heightFromPoint / triangleHeight; - if (Math.abs(b0b1b2[0]) < tol) + if (Math.abs(b0b1b2[0]) < tol) { b0b1b2[0] = 0.0; - else if (Math.abs(1.0 - b0b1b2[0]) < tol) + } else if (Math.abs(1.0 - b0b1b2[0]) < tol) { b0b1b2[0] = 1.0; - if (b0b1b2[0] < 0.0 || b0b1b2[0] > 1.0) + } + if (b0b1b2[0] < 0.0 || b0b1b2[0] > 1.0) { return null; + } // b1: triangleHeight = distanceFromLine(V[1], V[0], V[2].subtract3(V[0])); heightFromPoint = distanceFromLine(pnt, V[0], V[2].subtract3(V[0])); b0b1b2[1] = heightFromPoint / triangleHeight; - if (Math.abs(b0b1b2[1]) < tol) + if (Math.abs(b0b1b2[1]) < tol) { b0b1b2[1] = 0.0; - else if (Math.abs(1.0 - b0b1b2[1]) < tol) + } else if (Math.abs(1.0 - b0b1b2[1]) < tol) { b0b1b2[1] = 1.0; - if (b0b1b2[1] < 0.0 || b0b1b2[1] > 1.0) + } + if (b0b1b2[1] < 0.0 || b0b1b2[1] > 1.0) { return null; + } // b2: b0b1b2[2] = 1.0 - b0b1b2[0] - b0b1b2[1]; - if (Math.abs(b0b1b2[2]) < tol) + if (Math.abs(b0b1b2[2]) < tol) { b0b1b2[2] = 0.0; - else if (Math.abs(1.0 - b0b1b2[2]) < tol) + } else if (Math.abs(1.0 - b0b1b2[2]) < tol) { b0b1b2[2] = 1.0; - if (b0b1b2[2] < 0.0) + } + if (b0b1b2[2] < 0.0) { return null; + } return b0b1b2; } - protected static double distanceFromLine(Vec4 pnt, Vec4 P, Vec4 u) - { + protected static double distanceFromLine(Vec4 pnt, Vec4 P, Vec4 u) { // Return distance from pnt to line(P,u) // Pythagorean theorem approach: c^2 = a^2 + b^2. The // The square of the distance we seek is b^2: @@ -1859,24 +1722,22 @@ protected static double distanceFromLine(Vec4 pnt, Vec4 P, Vec4 u) double aSquared = u.normalize3().dot3(toPoint); aSquared *= aSquared; double distSquared = cSquared - aSquared; - if (distSquared < 0.0) - // must be a tiny number that really ought to be 0.0 + if (distSquared < 0.0) // must be a tiny number that really ought to be 0.0 + { return 0.0; + } return Math.sqrt(distSquared); } protected DoubleBuffer makeGeographicTexCoords(SectorGeometry sg, - SectorGeometry.GeographicTextureCoordinateComputer computer) - { - if (sg == null) - { + SectorGeometry.GeographicTextureCoordinateComputer computer) { + if (sg == null) { String msg = Logging.getMessage("nullValue.SectorGeometryIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (computer == null) - { + if (computer == null) { String msg = Logging.getMessage("nullValue.TextureCoordinateComputerIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1885,8 +1746,9 @@ protected DoubleBuffer makeGeographicTexCoords(SectorGeometry sg, RectTile rt = (RectTile) sg; int density = rt.density; - if (density < 1) + if (density < 1) { density = 1; + } int coordCount = (density + 3) * (density + 3); DoubleBuffer p = Buffers.newDirectDoubleBuffer(2 * coordCount); @@ -1901,8 +1763,7 @@ protected DoubleBuffer makeGeographicTexCoords(SectorGeometry sg, double[] uv; // for return values from computer int k = 2 * (density + 3); - for (int j = 0; j < density; j++) - { + for (int j = 0; j < density; j++) { Angle lat = Angle.fromRadians(minLat.radians + j * deltaLat); // skirt column; duplicate first column @@ -1910,8 +1771,7 @@ protected DoubleBuffer makeGeographicTexCoords(SectorGeometry sg, p.put(k++, uv[0]).put(k++, uv[1]); // interior columns - for (int i = 0; i < density; i++) - { + for (int i = 0; i < density; i++) { Angle lon = Angle.fromRadians(minLon.radians + i * deltaLon); uv = computer.compute(lat, lon); p.put(k++, uv[0]).put(k++, uv[1]); @@ -1929,8 +1789,7 @@ protected DoubleBuffer makeGeographicTexCoords(SectorGeometry sg, uv = computer.compute(maxLat, minLon); // skirt column p.put(k++, uv[0]).put(k++, uv[1]); - for (int i = 0; i < density; i++) - { + for (int i = 0; i < density; i++) { Angle lon = Angle.fromRadians(minLon.radians + i * deltaLon); // u uv = computer.compute(maxLat, lon); p.put(k++, uv[0]).put(k++, uv[1]); @@ -1942,8 +1801,7 @@ protected DoubleBuffer makeGeographicTexCoords(SectorGeometry sg, // last skirt row int kk = k - 2 * (density + 3); - for (int i = 0; i < density + 3; i++) - { + for (int i = 0; i < density + 3; i++) { p.put(k++, p.get(kk++)); p.put(k++, p.get(kk++)); } @@ -1951,8 +1809,7 @@ protected DoubleBuffer makeGeographicTexCoords(SectorGeometry sg, // first skirt row k = 0; kk = 2 * (density + 3); - for (int i = 0; i < density + 3; i++) - { + for (int i = 0; i < density + 3; i++) { p.put(k++, p.get(kk++)); p.put(k++, p.get(kk++)); } @@ -1960,13 +1817,14 @@ protected DoubleBuffer makeGeographicTexCoords(SectorGeometry sg, return p; } - protected static void createTextureCoordinates(int density) - { - if (density < 1) + protected static void createTextureCoordinates(int density) { + if (density < 1) { density = 1; + } - if (textureCoords.containsKey(density)) + if (textureCoords.containsKey(density)) { return; + } // Approximate 1 to avoid shearing off of right and top skirts in SurfaceTileRenderer. // TODO: dig into this more: why are the skirts being sheared off? @@ -1976,8 +1834,7 @@ protected static void createTextureCoordinates(int density) FloatBuffer p = Buffers.newDirectFloatBuffer(2 * coordCount); double delta = 1d / density; int k = 2 * (density + 3); - for (int j = 0; j < density; j++) - { + for (int j = 0; j < density; j++) { double v = j * delta; // skirt column; duplicate first column @@ -1985,8 +1842,7 @@ protected static void createTextureCoordinates(int density) p.put(k++, (float) v); // interior columns - for (int i = 0; i < density; i++) - { + for (int i = 0; i < density; i++) { p.put(k++, (float) (i * delta)); // u p.put(k++, (float) v); } @@ -2006,8 +1862,7 @@ protected static void createTextureCoordinates(int density) p.put(k++, 0f); // skirt column p.put(k++, v); - for (int i = 0; i < density; i++) - { + for (int i = 0; i < density; i++) { p.put(k++, (float) (i * delta)); // u p.put(k++, v); } @@ -2019,8 +1874,7 @@ protected static void createTextureCoordinates(int density) // last skirt row int kk = k - 2 * (density + 3); - for (int i = 0; i < density + 3; i++) - { + for (int i = 0; i < density + 3; i++) { p.put(k++, p.get(kk++)); p.put(k++, p.get(kk++)); } @@ -2028,8 +1882,7 @@ protected static void createTextureCoordinates(int density) // first skirt row k = 0; kk = 2 * (density + 3); - for (int i = 0; i < density + 3; i++) - { + for (int i = 0; i < density + 3; i++) { p.put(k++, p.get(kk++)); p.put(k++, p.get(kk++)); } @@ -2037,24 +1890,23 @@ protected static void createTextureCoordinates(int density) textureCoords.put(density, p); } - protected static void createIndices(int density) - { - if (density < 1) + protected static void createIndices(int density) { + if (density < 1) { density = 1; + } - if (indexLists.containsKey(density)) + if (indexLists.containsKey(density)) { return; + } int sideSize = density + 2; int indexCount = 2 * sideSize * sideSize + 4 * sideSize - 2; java.nio.IntBuffer buffer = Buffers.newDirectIntBuffer(indexCount); int k = 0; - for (int i = 0; i < sideSize; i++) - { + for (int i = 0; i < sideSize; i++) { buffer.put(k); - if (i > 0) - { + if (i > 0) { buffer.put(++k); buffer.put(k); } @@ -2062,18 +1914,15 @@ protected static void createIndices(int density) if (i % 2 == 0) // even { buffer.put(++k); - for (int j = 0; j < sideSize; j++) - { + for (int j = 0; j < sideSize; j++) { k += sideSize; buffer.put(k); buffer.put(++k); } - } - else // odd + } else // odd { buffer.put(--k); - for (int j = 0; j < sideSize; j++) - { + for (int j = 0; j < sideSize; j++) { k -= sideSize; buffer.put(k); buffer.put(--k); diff --git a/src/gov/nasa/worldwind/terrain/SectorGeometry.java b/src/gov/nasa/worldwind/terrain/SectorGeometry.java index 3a7cbd720f..876358aa98 100644 --- a/src/gov/nasa/worldwind/terrain/SectorGeometry.java +++ b/src/gov/nasa/worldwind/terrain/SectorGeometry.java @@ -15,15 +15,16 @@ /** * This interface provides access to individual terrain tiles, which are contained in a {@link SectorGeometryList}. *

                  - * Note: Three methods of this class assume that the {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} - * method of the containing sector geometry list has been called prior to calling them. They are {@link + * Note: Three methods of this class assume that the + * {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} method of the containing sector + * geometry list has been called prior to calling them. They are {@link * #pick(gov.nasa.worldwind.render.DrawContext, java.awt.Point)}, {@link #pick(gov.nasa.worldwind.render.DrawContext, * java.util.List)}, and {@link #renderMultiTexture(gov.nasa.worldwind.render.DrawContext, int)}. * * @version $Id: SectorGeometry.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface SectorGeometry extends Renderable -{ +public interface SectorGeometry extends Renderable { + /** * Returns this sector geometry's extent. * @@ -45,7 +46,7 @@ public interface SectorGeometry extends Renderable * Note: This method assumes that {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} * was called prior to this method. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickPoint a screen coordinate points to pick test. * * @throws IllegalArgumentException if either the draw context or list of pick points is null. @@ -55,12 +56,12 @@ public interface SectorGeometry extends Renderable /** * Computes the Cartesian coordinates of a location on the geometry's surface. * - * @param latitude the position's latitude. - * @param longitude the position's longitude. + * @param latitude the position's latitude. + * @param longitude the position's longitude. * @param metersOffset the number of meters to offset the computed position from the geometry's surface. * * @return the computed Cartesian coordinates, or null if the specified location is not within the geometry's sector - * or no internal geometry exists (has not yet been created). + * or no internal geometry exists (has not yet been created). * * @throws IllegalArgumentException if either the latitude or longitude are null. */ @@ -70,7 +71,7 @@ public interface SectorGeometry extends Renderable * Indicates that this sector geometry is about to be rendered one or more times. When rendering is complete, the * {@link #endRendering(gov.nasa.worldwind.render.DrawContext)} method must be called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param numTextureUnits the number of texture units to use. */ void beginRendering(DrawContext dc, int numTextureUnits); @@ -89,7 +90,7 @@ public interface SectorGeometry extends Renderable * Note: This method assumes that {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} * was called prior to this method. * - * @param dc the current draw context. + * @param dc the current draw context. * @param numTextureUnits the number of texture units to attempt to use. * * @throws IllegalArgumentException if the draw context is null or the number of texture units is less than one. @@ -100,7 +101,7 @@ public interface SectorGeometry extends Renderable * Displays the geometry's tessellation. Option parameters control whether to display the interior triangles, the * geometry's exterior boundary, or both. * - * @param dc the current draw context. + * @param dc the current draw context. * @param interior if true, displays the interior triangles. * @param exterior if true, displays the exterior boundary. * @@ -132,12 +133,12 @@ public interface SectorGeometry extends Renderable * Note: This method assumes that {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} * was called prior to this method. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickPoints a list of screen coordinate points to pick test. * * @return an array of resolved pick objects corresponding to the specified pick points. Null is returned as the - * picked object for points not on the geometry or otherwise not resolvable. Returns null if the pick point - * list's size is zero. + * picked object for points not on the geometry or otherwise not resolvable. Returns null if the pick point list's + * size is zero. * * @throws IllegalArgumentException if either the draw context or list of pick points is null. */ @@ -149,7 +150,7 @@ public interface SectorGeometry extends Renderable * @param line the line to intersect. * * @return the Cartesian coordinates of each intersection, or null if there is no intersection or no internal - * geometry has been computed. + * geometry has been computed. * * @throws IllegalArgumentException if the line is null. */ @@ -161,8 +162,8 @@ public interface SectorGeometry extends Renderable * @param elevation the elevation for which intersection points are to be found. * * @return an array of intersection pairs, or null if no intersections were found. The returned array of - * intersections describes a list of individual segments - two Intersection elements for each, - * corresponding to each geometry triangle that intersects the given elevation. + * intersections describes a list of individual segments - two Intersection elements for each, + * corresponding to each geometry triangle that intersects the given elevation. */ Intersection[] intersect(double elevation); @@ -174,8 +175,8 @@ public interface SectorGeometry extends Renderable * @param computer the texture coordinate computer. * * @return the computed texture coordinates. The first entry in the buffer corresponds to the lower left corner of - * the geometry (minimum latitude and longitude). The entries are then ordered by increasing longitude and - * then increasing latitude (typically called row-major order). + * the geometry (minimum latitude and longitude). The entries are then ordered by increasing longitude and then + * increasing latitude (typically called row-major order). * * @throws IllegalArgumentException if the computer is null. */ @@ -185,15 +186,16 @@ public interface SectorGeometry extends Renderable * Displays the geometry. The number of texture units to use may be specified, but at most only the number of * available units are used. *

                  - * Note: This method allows but does not require that {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} - * was called prior to this method. See the description of the beginRenderingCalled argument. + * Note: This method allows but does not require that + * {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} was called prior to this method. + * See the description of the beginRenderingCalled argument. * - * @param dc the current draw context. - * @param numTextureUnits the number of texture units to attempt to use. + * @param dc the current draw context. + * @param numTextureUnits the number of texture units to attempt to use. * @param beginRenderingCalled indicates whether this sector geometry's beginRendering method has been - * called prior to calling this method. True indicated it was called, false indicates - * that it was not. Calling <beginRendering> eliminates redundant rendering set-up and - * is used when this sector geometry is rendered several times in succession. + * called prior to calling this method. True indicated it was called, false indicates that it was not. Calling + * <beginRendering> eliminates redundant rendering set-up and is used when this sector geometry is rendered + * several times in succession. * * @throws IllegalArgumentException if the draw context is null or the number of texture units is less than one. * @see #beginRendering(gov.nasa.worldwind.render.DrawContext, int) @@ -203,31 +205,34 @@ public interface SectorGeometry extends Renderable /** * Displays the geometry. *

                  - * Note: This method allows but does not require that {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} - * was called prior to this method. See the description of the beginRenderingCalled argument. + * Note: This method allows but does not require that + * {@link SectorGeometryList#beginRendering(gov.nasa.worldwind.render.DrawContext)} was called prior to this method. + * See the description of the beginRenderingCalled argument. * - * @param dc the current draw context. + * @param dc the current draw context. * @param beginRenderingCalled indicates whether this sector geometry's beginRendering method has been - * called prior to calling this method. True indicated it was called, false indicates - * that it was not. Calling <beginRendering> eliminates redundant rendering set-up and - * is used when this sector geometry is rendered several times in succession. + * called prior to calling this method. True indicated it was called, false indicates that it was not. Calling + * <beginRendering> eliminates redundant rendering set-up and is used when this sector geometry is rendered + * several times in succession. * * @throws IllegalArgumentException if the draw context is null or the number of texture units is less than one. * @see #beginRendering(gov.nasa.worldwind.render.DrawContext, int) */ void render(DrawContext dc, boolean beginRenderingCalled); - /** An interface for computing texture coordinates for a given location. */ - public interface GeographicTextureCoordinateComputer - { + /** + * An interface for computing texture coordinates for a given location. + */ + public interface GeographicTextureCoordinateComputer { + /** * Computes a texture coordinate for a specified location. * - * @param latitude the location's latitude. + * @param latitude the location's latitude. * @param longitude the location's longitude. * * @return the [s,t] texture coordinate, where s corresponds to the longitude axis and t corresponds to the - * latitude axis. + * latitude axis. */ double[] compute(Angle latitude, Angle longitude); } diff --git a/src/gov/nasa/worldwind/terrain/SectorGeometryList.java b/src/gov/nasa/worldwind/terrain/SectorGeometryList.java index ee29d6a077..a2f368c35f 100644 --- a/src/gov/nasa/worldwind/terrain/SectorGeometryList.java +++ b/src/gov/nasa/worldwind/terrain/SectorGeometryList.java @@ -21,16 +21,19 @@ * @author tag * @version $Id: SectorGeometryList.java 1537 2013-08-07 19:58:01Z dcollins $ */ -public class SectorGeometryList extends ArrayList -{ - /** The spanning sector of all sector geometries contained in this list. */ +public class SectorGeometryList extends ArrayList { + + /** + * The spanning sector of all sector geometries contained in this list. + */ protected Sector sector; protected PickSupport pickSupport = new PickSupport(); protected HashMap> pickSectors = new HashMap>(); - /** Constructs an empty sector geometry list. */ - public SectorGeometryList() - { + /** + * Constructs an empty sector geometry list. + */ + public SectorGeometryList() { } /** @@ -38,8 +41,7 @@ public SectorGeometryList() * * @param list the secter geometries to place in the list. */ - public SectorGeometryList(SectorGeometryList list) - { + public SectorGeometryList(SectorGeometryList list) { super(list); } @@ -48,8 +50,7 @@ public SectorGeometryList(SectorGeometryList list) * * @return a sector that is the union of all sectors of entries in this list. */ - public Sector getSector() - { + public Sector getSector() { return sector; } @@ -58,8 +59,7 @@ public Sector getSector() * * @param sector the sector spanned by this list. */ - public void setSector(Sector sector) - { + public void setSector(Sector sector) { this.sector = sector; } @@ -67,20 +67,19 @@ public void setSector(Sector sector) * Indicates that this list's sectors are about to be rendered. When rendering is complete, the {@link * #endRendering(gov.nasa.worldwind.render.DrawContext)} must be called. * - * @param dc the current draw context. + * @param dc the current draw context. */ - public void beginRendering(DrawContext dc) - { - if (dc == null) - { + public void beginRendering(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } // TODO: add the beginRendering interface to Tessellator in order to eliminate this type test - if (dc.getGlobe().getTessellator() instanceof RectangularTessellator) + if (dc.getGlobe().getTessellator() instanceof RectangularTessellator) { ((RectangularTessellator) dc.getGlobe().getTessellator()).beginRendering(dc); + } } /** @@ -88,17 +87,16 @@ public void beginRendering(DrawContext dc) * * @param dc the current draw context. */ - public void endRendering(DrawContext dc) - { - if (dc == null) - { + public void endRendering(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (dc.getGlobe().getTessellator() instanceof RectangularTessellator) + if (dc.getGlobe().getTessellator() instanceof RectangularTessellator) { ((RectangularTessellator) dc.getGlobe().getTessellator()).endRendering(dc); + } } /** @@ -107,20 +105,19 @@ public void endRendering(DrawContext dc) * Note: Prior to calling this method, {@link #beginRendering(gov.nasa.worldwind.render.DrawContext)} must be * called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickPoint the screen point to test. */ - public void pick(DrawContext dc, java.awt.Point pickPoint) - { - if (dc == null) - { + public void pick(DrawContext dc, java.awt.Point pickPoint) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (pickPoint == null) + if (pickPoint == null) { return; + } this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); @@ -128,12 +125,10 @@ public void pick(DrawContext dc, java.awt.Point pickPoint) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glShadeModel(GL2.GL_FLAT); - try - { + try { // render each sector in unique color this.beginRendering(dc); - for (SectorGeometry sector : this) - { + for (SectorGeometry sector : this) { Color color = dc.getUniquePickColor(); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); sector.render(dc); @@ -142,15 +137,13 @@ public void pick(DrawContext dc, java.awt.Point pickPoint) } PickedObject pickedSector = this.pickSupport.getTopObject(dc, pickPoint); - if (pickedSector == null || pickedSector.getObject() == null) + if (pickedSector == null || pickedSector.getObject() == null) { return; // no sector picked - + } this.beginSectorGeometryPicking(dc); SectorGeometry sector = (SectorGeometry) pickedSector.getObject(); sector.pick(dc, pickPoint); - } - finally - { + } finally { this.endSectorGeometryPicking(dc); this.endRendering(dc); gl.glShadeModel(GL2.GL_SMOOTH); // restore to default explicitly to avoid more expensive pushAttrib @@ -167,22 +160,21 @@ public void pick(DrawContext dc, java.awt.Point pickPoint) * Note: Prior to calling this method, {@link #beginRendering(gov.nasa.worldwind.render.DrawContext)} must be * called. * - * @param dc the current draw context. + * @param dc the current draw context. * @param pickPoints the points to test. * * @return an array of picked objects that intersect one or more of the specified screen points. */ - public List pick(DrawContext dc, List pickPoints) - { - if (dc == null) - { + public List pick(DrawContext dc, List pickPoints) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (pickPoints == null || pickPoints.size() < 1) + if (pickPoints == null || pickPoints.size() < 1) { return null; + } this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); @@ -190,12 +182,10 @@ public List pick(DrawContext dc, List pickPoints) GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glShadeModel(GL2.GL_FLAT); - try - { + try { // render each sector in a unique color this.beginRendering(dc); - for (SectorGeometry sector : this) - { + for (SectorGeometry sector : this) { Color color = dc.getUniquePickColor(); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); sector.render(dc); @@ -206,50 +196,46 @@ public List pick(DrawContext dc, List pickPoints) // Determine the sectors underneath the pick points. Assemble a pick-points per sector map. // Several pick points might intersect the same sector. this.pickSectors.clear(); - for (Point pickPoint : pickPoints) - { + for (Point pickPoint : pickPoints) { PickedObject pickedSector = this.pickSupport.getTopObject(dc, pickPoint); - if (pickedSector == null || pickedSector.getObject() == null) + if (pickedSector == null || pickedSector.getObject() == null) { continue; + } SectorGeometry sector = (SectorGeometry) pickedSector.getObject(); ArrayList sectorPickPoints; - if (!this.pickSectors.containsKey(sector)) - { + if (!this.pickSectors.containsKey(sector)) { sectorPickPoints = new ArrayList(); this.pickSectors.put(sector, sectorPickPoints); - } - else - { + } else { sectorPickPoints = this.pickSectors.get(sector); } sectorPickPoints.add(pickPoint); } - if (this.pickSectors.size() < 1) + if (this.pickSectors.size() < 1) { return null; + } // Now have each sector determine the pick position for each intersecting pick point. this.beginSectorGeometryPicking(dc); ArrayList pickedObjects = new ArrayList(); - for (Map.Entry> sector : this.pickSectors.entrySet()) - { + for (Map.Entry> sector : this.pickSectors.entrySet()) { ArrayList sectorPickPoints = sector.getValue(); PickedObject[] pos = sector.getKey().pick(dc, sectorPickPoints); - if (pos == null) + if (pos == null) { continue; + } - for (PickedObject po : pos) - { - if (po != null) + for (PickedObject po : pos) { + if (po != null) { pickedObjects.add(po); + } } } return pickedObjects; - } - finally - { + } finally { this.endSectorGeometryPicking(dc); this.endRendering(dc); gl.glShadeModel(GL2.GL_SMOOTH); // restore to default explicitly to avoid more expensive pushAttrib @@ -266,8 +252,7 @@ public List pick(DrawContext dc, List pickPoints) * * @param dc the current draw context. */ - protected void beginSectorGeometryPicking(DrawContext dc) - { + protected void beginSectorGeometryPicking(DrawContext dc) { GL gl = dc.getGL(); gl.glDepthFunc(GL.GL_LEQUAL); @@ -276,8 +261,7 @@ protected void beginSectorGeometryPicking(DrawContext dc) // color geometry's depth values toward the eye and disable depth buffer writes. This works around an issue // where the VMware driver breaks OpenGL's invariance requirement when per-vertex colors are enabled. // See WWJ-425. - if (dc.getGLRuntimeCapabilities().isVMwareSVGA3D()) - { + if (dc.getGLRuntimeCapabilities().isVMwareSVGA3D()) { gl.glDepthMask(false); gl.glEnable(GL.GL_POLYGON_OFFSET_FILL); gl.glPolygonOffset(-1f, -1f); @@ -289,14 +273,12 @@ protected void beginSectorGeometryPicking(DrawContext dc) * * @param dc the current draw context. */ - protected void endSectorGeometryPicking(DrawContext dc) - { + protected void endSectorGeometryPicking(DrawContext dc) { GL gl = dc.getGL(); gl.glDepthFunc(GL.GL_LESS); // restore to default explicitly to avoid more expensive pushAttrib - if (dc.getGLRuntimeCapabilities().isVMwareSVGA3D()) - { + if (dc.getGLRuntimeCapabilities().isVMwareSVGA3D()) { gl.glDepthMask(true); gl.glDisable(GL.GL_POLYGON_OFFSET_FILL); gl.glPolygonOffset(0f, 0f); @@ -307,13 +289,12 @@ protected void endSectorGeometryPicking(DrawContext dc) * Computes a Cartesian point at a specified latitude, longitude and altitude above the terrain. * * @param position the position to compute the Cartesian point for. The altitude element of the position is - * considered to be distance above the terrain at the position's latitude and longitude. + * considered to be distance above the terrain at the position's latitude and longitude. * * @return the Cartesian point, in meters, relative to an origin of (0, 0, 0). Will be null if there is no sector - * geometry in this list for the specifed latitude and longitude. + * geometry in this list for the specifed latitude and longitude. */ - public Vec4 getSurfacePoint(Position position) - { + public Vec4 getSurfacePoint(Position position) { return this.getSurfacePoint(position.getLatitude(), position.getLongitude(), position.getElevation()); } @@ -323,54 +304,49 @@ public Vec4 getSurfacePoint(Position position) * @param latLon the location of the point to compute. * * @return the Cartesian point, in meters, relative to an origin of (0, 0, 0). Will be null if there is no sector - * geometry in this list for the specifed latitude and longitude. + * geometry in this list for the specifed latitude and longitude. */ - public Vec4 getSurfacePoint(LatLon latLon) - { + public Vec4 getSurfacePoint(LatLon latLon) { return this.getSurfacePoint(latLon.getLatitude(), latLon.getLongitude(), 0d); } /** * Computes a Cartesian point at a specified location on the terrain. * - * @param latitude the latitude of the point to compute. + * @param latitude the latitude of the point to compute. * @param longitude the longitude of the point to compute. * * @return the Cartesian point, in meters, relative to an origin of (0, 0, 0). Will be null if there is no sector - * geometry in this list for the specifed latitude and longitude. + * geometry in this list for the specifed latitude and longitude. */ - public Vec4 getSurfacePoint(Angle latitude, Angle longitude) - { + public Vec4 getSurfacePoint(Angle latitude, Angle longitude) { return this.getSurfacePoint(latitude, longitude, 0d); } /** * Computes a Cartesian point at a specified latitude, longitude and altitude above the terrain. * - * @param latitude the latitude of the point to compute. - * @param longitude the longitude of the point to compute. + * @param latitude the latitude of the point to compute. + * @param longitude the longitude of the point to compute. * @param metersOffset the distance above the terrain of the point to compute. * * @return the Cartesian point, in meters, relative to an origin of (0, 0, 0). Will be null if there is no sector - * geometry in this list for the specifed latitude and longitude. + * geometry in this list for the specifed latitude and longitude. */ - public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset) - { - if (latitude == null || longitude == null) - { + public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (int i = 0; i < this.size(); i++) - { + for (int i = 0; i < this.size(); i++) { SectorGeometry sg = this.get(i); - if (sg.getSector().contains(latitude, longitude)) - { + if (sg.getSector().contains(latitude, longitude)) { Vec4 point = sg.getSurfacePoint(latitude, longitude, metersOffset); - if (point != null) + if (point != null) { return point; + } } } @@ -383,12 +359,10 @@ public Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset * @param line the Line for which an intersection is to be found. * * @return the <Vec4> point closest to the ray origin where an intersection has been found or null if no - * intersection was found. + * intersection was found. */ - public Intersection[] intersect(Line line) - { - if (line == null) - { + public Intersection[] intersect(Line line) { + if (line == null) { String msg = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -398,31 +372,34 @@ public Intersection[] intersect(Line line) Intersection[] hits; ArrayList list = new ArrayList(); - for (SectorGeometry sg : sglist) - { - if (sg.getExtent().intersects(line)) - if ((hits = sg.intersect(line)) != null) + for (SectorGeometry sg : sglist) { + if (sg.getExtent().intersects(line)) { + if ((hits = sg.intersect(line)) != null) { list.addAll(Arrays.asList(hits)); + } + } } int numHits = list.size(); - if (numHits == 0) + if (numHits == 0) { return null; + } hits = new Intersection[numHits]; list.toArray(hits); final Vec4 origin = line.getOrigin(); - Arrays.sort(hits, new Comparator() - { - public int compare(Intersection i1, Intersection i2) - { - if (i1 == null && i2 == null) + Arrays.sort(hits, new Comparator() { + public int compare(Intersection i1, Intersection i2) { + if (i1 == null && i2 == null) { return 0; - if (i2 == null) + } + if (i2 == null) { return -1; - if (i1 == null) + } + if (i1 == null) { return 1; + } Vec4 v1 = i1.getIntersectionPoint(); Vec4 v2 = i2.getIntersectionPoint(); @@ -444,14 +421,12 @@ public int compare(Intersection i1, Intersection i2) * geometry tiles. The returned intersection list may contain segments outside that sector. * * @param elevation the elevation for which intersections are to be found. - * @param sector the sector inside which intersections are to be found. + * @param sector the sector inside which intersections are to be found. * * @return a list of Intersection pairs/segments describing a contour line at the given elevation. */ - public Intersection[] intersect(double elevation, Sector sector) - { - if (sector == null) - { + public Intersection[] intersect(double elevation, Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -461,16 +436,18 @@ public Intersection[] intersect(double elevation, Sector sector) Intersection[] hits; ArrayList list = new ArrayList(); - for (SectorGeometry sg : sglist) - { - if (sector.intersects(sg.getSector())) - if ((hits = sg.intersect(elevation)) != null) + for (SectorGeometry sg : sglist) { + if (sector.intersects(sg.getSector())) { + if ((hits = sg.intersect(elevation)) != null) { list.addAll(Arrays.asList(hits)); + } + } } int numHits = list.size(); - if (numHits == 0) + if (numHits == 0) { return null; + } hits = new Intersection[numHits]; list.toArray(hits); diff --git a/src/gov/nasa/worldwind/terrain/Terrain.java b/src/gov/nasa/worldwind/terrain/Terrain.java index 5b2b9f016c..3f1117d40c 100644 --- a/src/gov/nasa/worldwind/terrain/Terrain.java +++ b/src/gov/nasa/worldwind/terrain/Terrain.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.geom.*; @@ -19,8 +18,8 @@ * @author tag * @version $Id: Terrain.java 2056 2014-06-13 00:55:07Z tgaskins $ */ -public interface Terrain -{ +public interface Terrain { + /** * Returns the object's globe. * @@ -39,13 +38,12 @@ public interface Terrain * @param position the position. * * @return the Cartesian, model-coordinate point of the specified position, or null if the specified position does - * not exist within this instance's sector or if the operation is interrupted. + * not exist within this instance's sector or if the operation is interrupted. * * @throws IllegalArgumentException if the position is null. - * @throws gov.nasa.worldwind.exception.WWTimeoutException - * if the current timeout is exceeded while retrieving terrain data. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if the operation is interrupted. + * @throws gov.nasa.worldwind.exception.WWTimeoutException if the current timeout is exceeded while retrieving + * terrain data. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if the operation is interrupted. */ Vec4 getSurfacePoint(Position position); @@ -55,18 +53,17 @@ public interface Terrain * This operation fails with a {@link gov.nasa.worldwind.exception.WWTimeoutException} if a timeout has been * specified and it is exceeded during the operation. * - * @param latitude the location's latitude. - * @param longitude the location's longitude. + * @param latitude the location's latitude. + * @param longitude the location's longitude. * @param metersOffset the location's distance above the terrain. * * @return the Cartesian, model-coordinate point of the specified location, or null if the specified location does - * not exist within this instance's sector or if the operation is interrupted. + * not exist within this instance's sector or if the operation is interrupted. * * @throws IllegalArgumentException if the latitude or longitude are null. - * @throws gov.nasa.worldwind.exception.WWTimeoutException - * if the current timeout is exceeded while retrieving terrain data. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if the operation is interrupted. + * @throws gov.nasa.worldwind.exception.WWTimeoutException if the current timeout is exceeded while retrieving + * terrain data. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if the operation is interrupted. */ Vec4 getSurfacePoint(Angle latitude, Angle longitude, double metersOffset); @@ -82,13 +79,12 @@ public interface Terrain * @param pB the line's second position. * * @return an array of Cartesian model-coordinate intersection points, or null if no intersections occur or the - * operation is interrupted. + * operation is interrupted. * * @throws IllegalArgumentException if either position is null. - * @throws gov.nasa.worldwind.exception.WWTimeoutException - * if the current timeout is exceeded while retrieving terrain data. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if the operation is interrupted. + * @throws gov.nasa.worldwind.exception.WWTimeoutException if the current timeout is exceeded while retrieving + * terrain data. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if the operation is interrupted. */ Intersection[] intersect(Position pA, Position pB); @@ -99,18 +95,17 @@ public interface Terrain * This operation fails with a {@link gov.nasa.worldwind.exception.WWTimeoutException} if a timeout has been * specified and it is exceeded during the operation. * - * @param pA the line's first position. - * @param pB the line's second position. + * @param pA the line's first position. + * @param pB the line's second position. * @param altitudeMode the altitude mode indicating the reference for the altitudes in the specified positions. * * @return an array of Cartesian model-coordinate intersection points, or null if no intersections occur or the - * operation is interrupted. + * operation is interrupted. * * @throws IllegalArgumentException if either position is null. - * @throws gov.nasa.worldwind.exception.WWTimeoutException - * if the current timeout is exceeded while retrieving terrain data. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if the operation is interrupted. + * @throws gov.nasa.worldwind.exception.WWTimeoutException if the current timeout is exceeded while retrieving + * terrain data. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if the operation is interrupted. */ Intersection[] intersect(Position pA, Position pB, int altitudeMode); @@ -125,10 +120,9 @@ public interface Terrain * @return the elevation at the location, or null if the elevation could not be determined. * * @throws IllegalArgumentException if the specified location in null. - * @throws gov.nasa.worldwind.exception.WWTimeoutException - * if the current timeout is exceeded while retrieving terrain data. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if the operation is interrupted. + * @throws gov.nasa.worldwind.exception.WWTimeoutException if the current timeout is exceeded while retrieving + * terrain data. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if the operation is interrupted. */ Double getElevation(LatLon location); } diff --git a/src/gov/nasa/worldwind/terrain/Tessellator.java b/src/gov/nasa/worldwind/terrain/Tessellator.java index d653c1a55a..24bcff105f 100644 --- a/src/gov/nasa/worldwind/terrain/Tessellator.java +++ b/src/gov/nasa/worldwind/terrain/Tessellator.java @@ -12,8 +12,8 @@ * @author tag * @version $Id: Tessellator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Tessellator extends WWObject -{ +public interface Tessellator extends WWObject { + /** * Tessellate a globe for the currently visible region. * diff --git a/src/gov/nasa/worldwind/terrain/WCSElevationModel.java b/src/gov/nasa/worldwind/terrain/WCSElevationModel.java index 5ef9602bfc..800b2557d2 100644 --- a/src/gov/nasa/worldwind/terrain/WCSElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/WCSElevationModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.avlist.*; @@ -22,15 +21,13 @@ * @author tag * @version $Id: WCSElevationModel.java 2154 2014-07-17 21:32:34Z pabercrombie $ */ -public class WCSElevationModel extends BasicElevationModel -{ - public WCSElevationModel(Element domElement, AVList params) - { +public class WCSElevationModel extends BasicElevationModel { + + public WCSElevationModel(Element domElement, AVList params) { super(wcsGetParamsFromDocument(domElement, params)); } - public WCSElevationModel(WCS100Capabilities caps, AVList params) - { + public WCSElevationModel(WCS100Capabilities caps, AVList params) { super(wcsGetParamsFromCapsDoc(caps, params)); } @@ -41,17 +38,13 @@ public WCSElevationModel(WCS100Capabilities caps, AVList params) * * @see #getRestorableState() */ - public WCSElevationModel(String restorableStateInXml) - { + public WCSElevationModel(String restorableStateInXml) { super(wcsRestorableStateToParams(restorableStateInXml)); RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(restorableStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", restorableStateInXml); Logging.logger().severe(message); @@ -61,17 +54,16 @@ public WCSElevationModel(String restorableStateInXml) this.doRestoreState(rs, null); } - protected static AVList wcsGetParamsFromDocument(Element domElement, AVList params) - { - if (domElement == null) - { + protected static AVList wcsGetParamsFromDocument(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } DataConfigurationUtils.getWCSConfigParams(domElement, params); BasicElevationModel.getBasicElevationModelConfigParams(domElement, params); @@ -82,25 +74,21 @@ protected static AVList wcsGetParamsFromDocument(Element domElement, AVList para return params; } - protected static AVList wcsGetParamsFromCapsDoc(WCS100Capabilities caps, AVList params) - { - if (caps == null) - { + protected static AVList wcsGetParamsFromCapsDoc(WCS100Capabilities caps, AVList params) { + if (caps == null) { String message = Logging.getMessage("nullValue.WCSCapabilities"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ElevationModelConfigParams"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } WCS100DescribeCoverage coverage = (WCS100DescribeCoverage) params.getValue(AVKey.DOCUMENT); - if (coverage == null) - { + if (coverage == null) { String message = Logging.getMessage("nullValue.WCSDescribeCoverage"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -113,57 +101,60 @@ protected static AVList wcsGetParamsFromCapsDoc(WCS100Capabilities caps, AVList params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder(caps.getVersion(), params)); - if (params.getValue(AVKey.ELEVATION_EXTREMES_FILE) == null) - { + if (params.getValue(AVKey.ELEVATION_EXTREMES_FILE) == null) { // Use the default extremes file if there are at least as many levels in this new elevation model as the // level of the extremes file, which is level 5. int numLevels = (Integer) params.getValue(AVKey.NUM_LEVELS); - if (numLevels >= 6) + if (numLevels >= 6) { params.setValue(AVKey.ELEVATION_EXTREMES_FILE, "config/SRTM30Plus_ExtremeElevations_5.bil"); + } } return params; } - protected static void wcsSetFallbacks(AVList params) - { - if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) - { + protected static void wcsSetFallbacks(AVList params) { + if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) { Angle delta = Angle.fromDegrees(20); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, new LatLon(delta, delta)); } - if (params.getValue(AVKey.TILE_WIDTH) == null) + if (params.getValue(AVKey.TILE_WIDTH) == null) { params.setValue(AVKey.TILE_WIDTH, 150); + } - if (params.getValue(AVKey.TILE_HEIGHT) == null) + if (params.getValue(AVKey.TILE_HEIGHT) == null) { params.setValue(AVKey.TILE_HEIGHT, 150); + } - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { params.setValue(AVKey.FORMAT_SUFFIX, ".tif"); + } - if (params.getValue(AVKey.MISSING_DATA_SIGNAL) == null) + if (params.getValue(AVKey.MISSING_DATA_SIGNAL) == null) { params.setValue(AVKey.MISSING_DATA_SIGNAL, -9999d); + } - if (params.getValue(AVKey.NUM_LEVELS) == null) + if (params.getValue(AVKey.NUM_LEVELS) == null) { params.setValue(AVKey.NUM_LEVELS, 18); // approximately 20 cm per pixel - - if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) + } + if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); + } - if (params.getValue(AVKey.ELEVATION_MIN) == null) + if (params.getValue(AVKey.ELEVATION_MIN) == null) { params.setValue(AVKey.ELEVATION_MIN, -11000.0); + } - if (params.getValue(AVKey.ELEVATION_MAX) == null) + if (params.getValue(AVKey.ELEVATION_MAX) == null) { params.setValue(AVKey.ELEVATION_MAX, 8850.0); + } } - protected static void determineNumLevels(WCS100DescribeCoverage coverage, AVList params) - { - List grids = - coverage.getCoverageOfferings().get(0).getDomainSet().getSpatialDomain().getRectifiedGrids(); - if (grids.size() < 1 || grids.get(0).getOffsetVectors().size() < 2) - { + protected static void determineNumLevels(WCS100DescribeCoverage coverage, AVList params) { + List grids + = coverage.getCoverageOfferings().get(0).getDomainSet().getSpatialDomain().getRectifiedGrids(); + if (grids.size() < 1 || grids.get(0).getOffsetVectors().size() < 2) { params.setValue(AVKey.NUM_LEVELS, 18); return; } @@ -180,43 +171,36 @@ protected static void determineNumLevels(WCS100DescribeCoverage coverage, AVList } public static AVList getWCSElevationModelConfigParams(WCS100Capabilities caps, WCS100DescribeCoverage coverage, - AVList params) - { + AVList params) { DataConfigurationUtils.getWCSConfigParameters(caps, coverage, params); // checks for null args // Ensure that we found all the necessary information. - if (params.getStringValue(AVKey.DATASET_NAME) == null) - { + if (params.getStringValue(AVKey.DATASET_NAME) == null) { Logging.logger().warning(Logging.getMessage("WCS.NoCoverageName")); throw new WWRuntimeException(Logging.getMessage("WCS.NoCoverageName")); } - if (params.getStringValue(AVKey.SERVICE) == null) - { + if (params.getStringValue(AVKey.SERVICE) == null) { Logging.logger().warning(Logging.getMessage("WCS.NoGetCoverageURL")); throw new WWRuntimeException(Logging.getMessage("WCS.NoGetCoverageURL")); } - if (params.getStringValue(AVKey.DATA_CACHE_NAME) == null) - { + if (params.getStringValue(AVKey.DATA_CACHE_NAME) == null) { Logging.logger().warning(Logging.getMessage("nullValue.DataCacheIsNull")); throw new WWRuntimeException(Logging.getMessage("nullValue.DataCacheIsNull")); } - if (params.getStringValue(AVKey.IMAGE_FORMAT) == null) - { + if (params.getStringValue(AVKey.IMAGE_FORMAT) == null) { Logging.logger().severe("WCS.NoImageFormats"); throw new WWRuntimeException(Logging.getMessage("WCS.NoImageFormats")); } - if (params.getValue(AVKey.SECTOR) == null) - { + if (params.getValue(AVKey.SECTOR) == null) { Logging.logger().severe("WCS.NoLonLatEnvelope"); throw new WWRuntimeException(Logging.getMessage("WCS.NoLonLatEnvelope")); } - if (params.getStringValue(AVKey.COORDINATE_SYSTEM) == null) - { + if (params.getStringValue(AVKey.COORDINATE_SYSTEM) == null) { String msg = Logging.getMessage("WCS.RequiredCRSNotSupported", "EPSG:4326"); Logging.logger().severe(msg); throw new WWRuntimeException(msg); @@ -225,29 +209,27 @@ public static AVList getWCSElevationModelConfigParams(WCS100Capabilities caps, W return params; } - protected static class URLBuilder implements TileUrlBuilder - { + protected static class URLBuilder implements TileUrlBuilder { + protected final String layerNames; private final String imageFormat; protected final String serviceVersion; protected String URLTemplate = null; - protected URLBuilder(String version, AVList params) - { + protected URLBuilder(String version, AVList params) { this.serviceVersion = version; this.layerNames = params.getStringValue(AVKey.COVERAGE_IDENTIFIERS); this.imageFormat = params.getStringValue(AVKey.IMAGE_FORMAT); } - public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) throws MalformedURLException - { + public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) throws MalformedURLException { StringBuffer sb; - if (this.URLTemplate == null) - { + if (this.URLTemplate == null) { sb = new StringBuffer(tile.getLevel().getService()); - if (!sb.toString().toLowerCase().contains("service=wcs")) + if (!sb.toString().toLowerCase().contains("service=wcs")) { sb.append("service=WCS"); + } sb.append("&request=GetCoverage"); sb.append("&version="); sb.append(this.serviceVersion); @@ -255,15 +237,14 @@ public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) thro sb.append("&coverage="); sb.append(this.layerNames); sb.append("&format="); - if (altImageFormat == null) + if (altImageFormat == null) { sb.append(this.imageFormat); - else + } else { sb.append(altImageFormat); + } this.URLTemplate = sb.toString(); - } - else - { + } else { sb = new StringBuffer(this.URLTemplate); } @@ -295,11 +276,11 @@ public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) thro * * @return a WCS basic elevation model configuration document. */ - protected Document createConfigurationDocument(AVList params) - { + protected Document createConfigurationDocument(AVList params) { Document doc = super.createConfigurationDocument(params); - if (doc == null || doc.getDocumentElement() == null) + if (doc == null || doc.getDocumentElement() == null) { return doc; + } DataConfigurationUtils.createWCSLayerConfigElements(params, doc.getDocumentElement()); @@ -307,64 +288,59 @@ protected Document createConfigurationDocument(AVList params) } public void composeElevations(Sector sector, List latlons, int tileWidth, double[] buffer) - throws Exception - { - if (sector == null) - { + throws Exception { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (latlons == null) - { + if (latlons == null) { String msg = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer == null) - { + if (buffer == null) { String msg = Logging.getMessage("nullValue.ElevationsBufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer.length < latlons.size() || tileWidth > latlons.size()) - { + if (buffer.length < latlons.size() || tileWidth > latlons.size()) { String msg = Logging.getMessage("ElevationModel.ElevationsBufferTooSmall", latlons.size()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } WMSBasicElevationModel.ElevationCompositionTile tile = new WMSBasicElevationModel.ElevationCompositionTile( - sector, this.getLevels().getLastLevel(), - tileWidth, latlons.size() / tileWidth); + sector, this.getLevels().getLastLevel(), + tileWidth, latlons.size() / tileWidth); this.downloadElevations(tile); tile.setElevations(this.readElevations(tile.getFile().toURI().toURL()), this); - for (int i = 0; i < latlons.size(); i++) - { + for (int i = 0; i < latlons.size(); i++) { LatLon ll = latlons.get(i); - if (ll == null) + if (ll == null) { continue; + } double value = this.lookupElevation(ll.getLatitude(), ll.getLongitude(), tile); // If an elevation at the given location is available, then write that elevation to the destination buffer. // Otherwise do nothing. - if (value != this.getMissingDataSignal()) + if (value != this.getMissingDataSignal()) { buffer[i] = value; + } } } - protected void downloadElevations(WMSBasicElevationModel.ElevationCompositionTile tile) throws Exception - { + protected void downloadElevations(WMSBasicElevationModel.ElevationCompositionTile tile) throws Exception { URL url = tile.getResourceURL(); Retriever retriever = new HTTPRetriever(url, - new WMSBasicElevationModel.CompositionRetrievalPostProcessor(tile.getFile())); + new WMSBasicElevationModel.CompositionRetrievalPostProcessor(tile.getFile())); retriever.setConnectTimeout(10000); retriever.setReadTimeout(60000); retriever.call(); @@ -373,39 +349,29 @@ protected void downloadElevations(WMSBasicElevationModel.ElevationCompositionTil //**************************************************************// //******************** Restorable Support ********************// //**************************************************************// - @Override public void getRestorableStateForAVPair(String key, Object value, - RestorableSupport rs, RestorableSupport.StateObject context) - { - if (value instanceof URLBuilder) - { + RestorableSupport rs, RestorableSupport.StateObject context) { + if (value instanceof URLBuilder) { rs.addStateValueAsString(context, AVKey.WCS_VERSION, ((URLBuilder) value).serviceVersion); - } - else if (!(value instanceof WCS100DescribeCoverage)) - { + } else if (!(value instanceof WCS100DescribeCoverage)) { // Don't pass DescribeCoverage to superclass. The DescribeCoverage parameters will already be present in the // parameter list, so do nothing here. super.getRestorableStateForAVPair(key, value, rs, context); } } - protected static AVList wcsRestorableStateToParams(String stateInXml) - { - if (stateInXml == null) - { + protected static AVList wcsRestorableStateToParams(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -418,31 +384,35 @@ protected static AVList wcsRestorableStateToParams(String stateInXml) } protected static void wcsRestoreStateForParams(RestorableSupport rs, RestorableSupport.StateObject context, - AVList params) - { + AVList params) { // Invoke the BasicElevationModel functionality. restoreStateForParams(rs, null, params); String s = rs.getStateValueAsString(context, AVKey.IMAGE_FORMAT); - if (s != null) + if (s != null) { params.setValue(AVKey.IMAGE_FORMAT, s); + } s = rs.getStateValueAsString(context, AVKey.TITLE); - if (s != null) + if (s != null) { params.setValue(AVKey.TITLE, s); + } s = rs.getStateValueAsString(context, AVKey.DISPLAY_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DISPLAY_NAME, s); + } RestorableSupport.adjustTitleAndDisplayName(params); s = rs.getStateValueAsString(context, AVKey.COVERAGE_IDENTIFIERS); - if (s != null) + if (s != null) { params.setValue(AVKey.COVERAGE_IDENTIFIERS, s); + } s = rs.getStateValueAsString(context, AVKey.WCS_VERSION); - if (s != null) + if (s != null) { params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder(s, params)); + } } } diff --git a/src/gov/nasa/worldwind/terrain/WMSBasicElevationModel.java b/src/gov/nasa/worldwind/terrain/WMSBasicElevationModel.java index 6659f32ebd..5337243c5f 100644 --- a/src/gov/nasa/worldwind/terrain/WMSBasicElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/WMSBasicElevationModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.avlist.*; @@ -22,39 +21,31 @@ * @author tag * @version $Id: WMSBasicElevationModel.java 2050 2014-06-09 18:52:26Z tgaskins $ */ -public class WMSBasicElevationModel extends BasicElevationModel -{ - private static final String[] formatOrderPreference = new String[] - { - "application/bil32", "application/bil16", "application/bil", "image/bil", "image/png", "image/tiff" - }; - - public WMSBasicElevationModel(AVList params) - { +public class WMSBasicElevationModel extends BasicElevationModel { + + private static final String[] formatOrderPreference = new String[]{ + "application/bil32", "application/bil16", "application/bil", "image/bil", "image/png", "image/tiff" + }; + + public WMSBasicElevationModel(AVList params) { super(params); } - public WMSBasicElevationModel(Element domElement, AVList params) - { + public WMSBasicElevationModel(Element domElement, AVList params) { this(wmsGetParamsFromDocument(domElement, params)); } - public WMSBasicElevationModel(WMSCapabilities caps, AVList params) - { + public WMSBasicElevationModel(WMSCapabilities caps, AVList params) { this(wmsGetParamsFromCapsDoc(caps, params)); } - public WMSBasicElevationModel(String restorableStateInXml) - { + public WMSBasicElevationModel(String restorableStateInXml) { super(wmsRestorableStateToParams(restorableStateInXml)); RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(restorableStateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", restorableStateInXml); Logging.logger().severe(message); @@ -64,17 +55,16 @@ public WMSBasicElevationModel(String restorableStateInXml) this.doRestoreState(rs, null); } - protected static AVList wmsGetParamsFromDocument(Element domElement, AVList params) - { - if (domElement == null) - { + protected static AVList wmsGetParamsFromDocument(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) + if (params == null) { params = new AVListImpl(); + } DataConfigurationUtils.getWMSLayerConfigParams(domElement, params); BasicElevationModel.getBasicElevationModelConfigParams(domElement, params); @@ -85,36 +75,28 @@ protected static AVList wmsGetParamsFromDocument(Element domElement, AVList para return params; } - protected static AVList wmsGetParamsFromCapsDoc(WMSCapabilities caps, AVList params) - { - if (caps == null) - { + protected static AVList wmsGetParamsFromCapsDoc(WMSCapabilities caps, AVList params) { + if (caps == null) { String message = Logging.getMessage("nullValue.WMSCapabilities"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ElevationModelConfigParams"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String wmsVersion; - try - { + try { wmsVersion = caps.getVersion(); getWMSElevationModelConfigParams(caps, formatOrderPreference, params); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { String message = Logging.getMessage("WMS.MissingLayerParameters"); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new IllegalArgumentException(message, e); - } - catch (WWRuntimeException e) - { + } catch (WWRuntimeException e) { String message = Logging.getMessage("WMS.MissingCapabilityValues"); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new IllegalArgumentException(message, e); @@ -127,36 +109,39 @@ protected static AVList wmsGetParamsFromCapsDoc(WMSCapabilities caps, AVList par return params; } - protected static void wmsSetFallbacks(AVList params) - { - if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) - { + protected static void wmsSetFallbacks(AVList params) { + if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) { Angle delta = Angle.fromDegrees(20); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, new LatLon(delta, delta)); } - if (params.getValue(AVKey.TILE_WIDTH) == null) + if (params.getValue(AVKey.TILE_WIDTH) == null) { params.setValue(AVKey.TILE_WIDTH, 150); + } - if (params.getValue(AVKey.TILE_HEIGHT) == null) + if (params.getValue(AVKey.TILE_HEIGHT) == null) { params.setValue(AVKey.TILE_HEIGHT, 150); + } - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { params.setValue(AVKey.FORMAT_SUFFIX, ".bil"); + } - if (params.getValue(AVKey.MISSING_DATA_SIGNAL) == null) + if (params.getValue(AVKey.MISSING_DATA_SIGNAL) == null) { params.setValue(AVKey.MISSING_DATA_SIGNAL, -9999d); + } - if (params.getValue(AVKey.NUM_LEVELS) == null) + if (params.getValue(AVKey.NUM_LEVELS) == null) { params.setValue(AVKey.NUM_LEVELS, 18); // approximately 20 cm per pixel - - if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) + } + if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); + } } // TODO: consolidate common code in WMSTiledImageLayer.URLBuilder and WMSBasicElevationModel.URLBuilder - protected static class URLBuilder implements TileUrlBuilder - { + protected static class URLBuilder implements TileUrlBuilder { + protected static final String MAX_VERSION = "1.3.0"; private final String layerNames; @@ -166,8 +151,7 @@ protected static class URLBuilder implements TileUrlBuilder private final String crs; protected String URLTemplate = null; - protected URLBuilder(String version, AVList params) - { + protected URLBuilder(String version, AVList params) { Double d = (Double) params.getValue(AVKey.MISSING_DATA_SIGNAL); this.layerNames = params.getStringValue(AVKey.LAYER_NAMES); @@ -181,9 +165,7 @@ protected URLBuilder(String version, AVList params) this.wmsVersion = MAX_VERSION; coordSystemKey = "&crs="; defaultCS = "CRS:84"; // would like to do EPSG:4326 but that's incompatible with our old WMS server, see WWJ-474 - } - else - { + } else { this.wmsVersion = version; coordSystemKey = "&srs="; defaultCS = "EPSG:4326"; @@ -193,15 +175,14 @@ protected URLBuilder(String version, AVList params) this.crs = coordSystemKey + (coordinateSystem != null ? coordinateSystem : defaultCS); } - public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) throws MalformedURLException - { + public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) throws MalformedURLException { StringBuffer sb; - if (this.URLTemplate == null) - { + if (this.URLTemplate == null) { sb = new StringBuffer(tile.getLevel().getService()); - if (!sb.toString().toLowerCase().contains("service=wms")) + if (!sb.toString().toLowerCase().contains("service=wms")) { sb.append("service=WMS"); + } sb.append("&request=GetMap"); sb.append("&version="); sb.append(this.wmsVersion); @@ -211,15 +192,14 @@ public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) thro sb.append("&styles="); sb.append(this.styleNames != null ? this.styleNames : ""); sb.append("&format="); - if (altImageFormat == null) + if (altImageFormat == null) { sb.append(this.imageFormat); - else + } else { sb.append(altImageFormat); + } this.URLTemplate = sb.toString(); - } - else - { + } else { sb = new StringBuffer(this.URLTemplate); } @@ -231,8 +211,7 @@ public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) thro Sector s = tile.getSector(); sb.append("&bbox="); // The order of the coordinate specification matters, and it changed with WMS 1.3.0. - if (WWUtil.compareVersion(this.wmsVersion, "1.1.1") <= 0 || this.crs.contains("CRS:84")) - { + if (WWUtil.compareVersion(this.wmsVersion, "1.1.1") <= 0 || this.crs.contains("CRS:84")) { // 1.1.1 and earlier and CRS:84 use lon/lat order sb.append(s.getMinLongitude().getDegrees()); sb.append(","); @@ -241,9 +220,7 @@ public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) thro sb.append(s.getMaxLongitude().getDegrees()); sb.append(","); sb.append(s.getMaxLatitude().getDegrees()); - } - else - { + } else { // 1.3.0 uses lat/lon ordering sb.append(s.getMinLatitude().getDegrees()); sb.append(","); @@ -263,43 +240,37 @@ public URL getURL(gov.nasa.worldwind.util.Tile tile, String altImageFormat) thro //**************************************************************// //******************** Configuration *************************// //**************************************************************// - /** * Parses WMSBasicElevationModel configuration parameters from a specified WMS Capabilities source. This writes - * output as key-value pairs to params. Supported key and parameter names are: + * output as key-value pairs to params. Supported key and parameter names are: + *
                  Parameters
                  * - *
                  Parameters
                  ParameterValueType
                  {@link AVKey#ELEVATION_MAX}WMS layer's - * maximum extreme elevationDouble
                  {@link AVKey#ELEVATION_MIN}WMS layer's - * minimum extreme elevationDouble
                  {@link AVKey#DATA_TYPE}Translate WMS layer's - * image format to a matching data typeString
                  This also parses common WMS layer - * parameters by invoking {@link DataConfigurationUtils#getWMSLayerConfigParams(gov.nasa.worldwind.ogc.wms.WMSCapabilities, + *

                  {@link AVKey#ELEVATION_MAX}WMS layer's maximum extreme elevationDouble
                  {@link AVKey#ELEVATION_MIN}WMS layer's minimum extreme elevationDouble
                  {@link AVKey#DATA_TYPE}Translate WMS layer's image format to a matching data + * typeString
                  This also parses common WMS layer parameters by invoking {@link DataConfigurationUtils#getWMSLayerConfigParams(gov.nasa.worldwind.ogc.wms.WMSCapabilities, * String[], gov.nasa.worldwind.avlist.AVList)}. * - * @param caps the WMS Capabilities source to parse for WMSBasicElevationModel configuration - * parameters. + * @param caps the WMS Capabilities source to parse for WMSBasicElevationModel configuration parameters. * @param formatOrderPreference an ordered array of preferred image formats, or null to use the default format. - * @param params the output key-value pairs which recieve the WMSBasicElevationModel configuration - * parameters. + * @param params the output key-value pairs which recieve the WMSBasicElevationModel configuration parameters. * * @return a reference to params. * * @throws IllegalArgumentException if either the document or params are null, or if params does not contain the - * required key-value pairs. - * @throws gov.nasa.worldwind.exception.WWRuntimeException - * if the Capabilities document does not contain any of the required information. + * required key-value pairs. + * @throws gov.nasa.worldwind.exception.WWRuntimeException if the Capabilities document does not contain any of the + * required information. */ public static AVList getWMSElevationModelConfigParams(WMSCapabilities caps, String[] formatOrderPreference, - AVList params) - { - if (caps == null) - { + AVList params) { + if (caps == null) { String message = Logging.getMessage("nullValue.WMSCapabilities"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ElevationModelConfigParams"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -310,16 +281,14 @@ public static AVList getWMSElevationModelConfigParams(WMSCapabilities caps, Stri // Attempt to extract the WMS layer names from the specified parameters. String layerNames = params.getStringValue(AVKey.LAYER_NAMES); - if (layerNames == null || layerNames.length() == 0) - { + if (layerNames == null || layerNames.length() == 0) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String[] names = layerNames.split(","); - if (names == null || names.length == 0) - { + if (names == null || names.length == 0) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -329,28 +298,32 @@ public static AVList getWMSElevationModelConfigParams(WMSCapabilities caps, Stri Double[] extremes = caps.getLayerExtremeElevations(names); Double d = (Double) params.getValue(AVKey.ELEVATION_MIN); - if (d == null && extremes != null && extremes[0] != null) + if (d == null && extremes != null && extremes[0] != null) { params.setValue(AVKey.ELEVATION_MIN, extremes[0]); + } d = (Double) params.getValue(AVKey.ELEVATION_MAX); - if (d == null && extremes != null && extremes[1] != null) + if (d == null && extremes != null && extremes[1] != null) { params.setValue(AVKey.ELEVATION_MAX, extremes[1]); + } // Compute the internal pixel type from the image format. - if (params.getValue(AVKey.DATA_TYPE) == null && params.getValue(AVKey.IMAGE_FORMAT) != null) - { + if (params.getValue(AVKey.DATA_TYPE) == null && params.getValue(AVKey.IMAGE_FORMAT) != null) { String s = WWIO.makeDataTypeForMimeType(params.getValue(AVKey.IMAGE_FORMAT).toString()); - if (s != null) + if (s != null) { params.setValue(AVKey.DATA_TYPE, s); + } } // Use the default data type. - if (params.getValue(AVKey.DATA_TYPE) == null) + if (params.getValue(AVKey.DATA_TYPE) == null) { params.setValue(AVKey.DATA_TYPE, AVKey.INT16); + } // Use the default byte order. - if (params.getValue(AVKey.BYTE_ORDER) == null) + if (params.getValue(AVKey.BYTE_ORDER) == null) { params.setValue(AVKey.BYTE_ORDER, AVKey.LITTLE_ENDIAN); + } return params; } @@ -362,11 +335,11 @@ public static AVList getWMSElevationModelConfigParams(WMSCapabilities caps, Stri * * @return a WMS basic elevation model configuration document. */ - protected Document createConfigurationDocument(AVList params) - { + protected Document createConfigurationDocument(AVList params) { Document doc = super.createConfigurationDocument(params); - if (doc == null || doc.getDocumentElement() == null) + if (doc == null || doc.getDocumentElement() == null) { return doc; + } DataConfigurationUtils.createWMSLayerConfigElements(params, doc.getDocumentElement()); @@ -376,16 +349,14 @@ protected Document createConfigurationDocument(AVList params) //**************************************************************// //******************** Composition ***************************// //**************************************************************// + protected static class ElevationCompositionTile extends ElevationTile { - protected static class ElevationCompositionTile extends ElevationTile - { private int width; private int height; private File file; public ElevationCompositionTile(Sector sector, Level level, int width, int height) - throws IOException - { + throws IOException { super(sector, level, -1, -1); // row and column aren't used and need to signal that this.width = width; @@ -395,83 +366,74 @@ public ElevationCompositionTile(Sector sector, Level level, int width, int heigh } @Override - public int getWidth() - { + public int getWidth() { return this.width; } @Override - public int getHeight() - { + public int getHeight() { return this.height; } @Override - public String getPath() - { + public String getPath() { return this.file.getPath(); } - public File getFile() - { + public File getFile() { return this.file; } } public void composeElevations(Sector sector, List latlons, int tileWidth, double[] buffer) - throws Exception - { - if (sector == null) - { + throws Exception { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (latlons == null) - { + if (latlons == null) { String msg = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer == null) - { + if (buffer == null) { String msg = Logging.getMessage("nullValue.ElevationsBufferIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (buffer.length < latlons.size() || tileWidth > latlons.size()) - { + if (buffer.length < latlons.size() || tileWidth > latlons.size()) { String msg = Logging.getMessage("ElevationModel.ElevationsBufferTooSmall", latlons.size()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } ElevationCompositionTile tile = new ElevationCompositionTile(sector, this.getLevels().getLastLevel(), - tileWidth, latlons.size() / tileWidth); + tileWidth, latlons.size() / tileWidth); this.downloadElevations(tile); tile.setElevations(this.readElevations(tile.getFile().toURI().toURL()), this); - for (int i = 0; i < latlons.size(); i++) - { + for (int i = 0; i < latlons.size(); i++) { LatLon ll = latlons.get(i); - if (ll == null) + if (ll == null) { continue; + } double value = this.lookupElevation(ll.getLatitude(), ll.getLongitude(), tile); // If an elevation at the given location is available, then write that elevation to the destination buffer. // Otherwise do nothing. - if (value != this.getMissingDataSignal()) + if (value != this.getMissingDataSignal()) { buffer[i] = value; + } } } - protected void downloadElevations(ElevationCompositionTile tile) throws Exception - { + protected void downloadElevations(ElevationCompositionTile tile) throws Exception { URL url = tile.getResourceURL(); Retriever retriever = new HTTPRetriever(url, new CompositionRetrievalPostProcessor(tile.getFile())); @@ -480,30 +442,26 @@ protected void downloadElevations(ElevationCompositionTile tile) throws Exceptio retriever.call(); } - protected static class CompositionRetrievalPostProcessor extends AbstractRetrievalPostProcessor - { + protected static class CompositionRetrievalPostProcessor extends AbstractRetrievalPostProcessor { + // Note: Requested data is never marked as absent because the caller may want to continually re-try retrieval protected File outFile; - public CompositionRetrievalPostProcessor(File outFile) - { + public CompositionRetrievalPostProcessor(File outFile) { this.outFile = outFile; } - protected File doGetOutputFile() - { + protected File doGetOutputFile() { return this.outFile; } @Override - protected boolean overwriteExistingFile() - { + protected boolean overwriteExistingFile() { return true; } @Override - protected boolean isDeleteOnExit(File outFile) - { + protected boolean isDeleteOnExit(File outFile) { return outFile.getPath().contains(WWIO.DELETE_ON_EXIT_PREFIX); } } @@ -511,37 +469,27 @@ protected boolean isDeleteOnExit(File outFile) //**************************************************************// //******************** Restorable Support ********************// //**************************************************************// - public void getRestorableStateForAVPair(String key, Object value, - RestorableSupport rs, RestorableSupport.StateObject context) - { - if (value instanceof URLBuilder) - { + RestorableSupport rs, RestorableSupport.StateObject context) { + if (value instanceof URLBuilder) { rs.addStateValueAsString(context, "wms.Version", ((URLBuilder) value).wmsVersion); rs.addStateValueAsString(context, "wms.Crs", ((URLBuilder) value).crs); - } - else - { + } else { super.getRestorableStateForAVPair(key, value, rs, context); } } - protected static AVList wmsRestorableStateToParams(String stateInXml) - { - if (stateInXml == null) - { + protected static AVList wmsRestorableStateToParams(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -554,32 +502,36 @@ protected static AVList wmsRestorableStateToParams(String stateInXml) } protected static void wmsRestoreStateForParams(RestorableSupport rs, RestorableSupport.StateObject context, - AVList params) - { + AVList params) { // Invoke the BasicElevationModel functionality. restoreStateForParams(rs, null, params); String s = rs.getStateValueAsString(context, AVKey.IMAGE_FORMAT); - if (s != null) + if (s != null) { params.setValue(AVKey.IMAGE_FORMAT, s); + } s = rs.getStateValueAsString(context, AVKey.TITLE); - if (s != null) + if (s != null) { params.setValue(AVKey.TITLE, s); + } s = rs.getStateValueAsString(context, AVKey.DISPLAY_NAME); - if (s != null) + if (s != null) { params.setValue(AVKey.DISPLAY_NAME, s); + } RestorableSupport.adjustTitleAndDisplayName(params); s = rs.getStateValueAsString(context, AVKey.LAYER_NAMES); - if (s != null) + if (s != null) { params.setValue(AVKey.LAYER_NAMES, s); + } s = rs.getStateValueAsString(context, AVKey.STYLE_NAMES); - if (s != null) + if (s != null) { params.setValue(AVKey.STYLE_NAMES, s); + } s = rs.getStateValueAsString(context, "wms.Version"); params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder(s, params)); diff --git a/src/gov/nasa/worldwind/terrain/ZeroElevationModel.java b/src/gov/nasa/worldwind/terrain/ZeroElevationModel.java index 4185fd21d4..f0b34a47eb 100644 --- a/src/gov/nasa/worldwind/terrain/ZeroElevationModel.java +++ b/src/gov/nasa/worldwind/terrain/ZeroElevationModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.terrain; import gov.nasa.worldwind.avlist.AVKey; @@ -17,32 +16,26 @@ * @author tag * @version $Id: ZeroElevationModel.java 2014 2014-05-20 19:46:55Z tgaskins $ */ -public class ZeroElevationModel extends AbstractElevationModel -{ - public double getMaxElevation() - { +public class ZeroElevationModel extends AbstractElevationModel { + + public double getMaxElevation() { return 1; } - public double getMinElevation() - { + public double getMinElevation() { return 0; } - public double[] getExtremeElevations(Angle latitude, Angle longitude) - { - return new double[] {0, 1}; + public double[] getExtremeElevations(Angle latitude, Angle longitude) { + return new double[]{0, 1}; } - public double[] getExtremeElevations(Sector sector) - { - return new double[] {0, 1}; + public double[] getExtremeElevations(Sector sector) { + return new double[]{0, 1}; } - public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) - { - for (int i = 0; i < latlons.size(); i++) - { + public double getElevations(Sector sector, List latlons, double targetResolution, double[] buffer) { + for (int i = 0; i < latlons.size(); i++) { buffer[i] = 0; } @@ -53,40 +46,33 @@ public double getElevations(Sector sector, List latlons, doubl } public double getUnmappedElevations(Sector sector, List latlons, double targetResolution, - double[] buffer) - { + double[] buffer) { return this.getElevations(sector, latlons, targetResolution, buffer); } - public int intersects(Sector sector) - { + public int intersects(Sector sector) { return 0; } - public boolean contains(Angle latitude, Angle longitude) - { + public boolean contains(Angle latitude, Angle longitude) { return true; } @SuppressWarnings({"JavadocReference"}) - public double getBestResolution(Sector sector) - { + public double getBestResolution(Sector sector) { return 1.6e-6; // corresponds to about 10 meters for Earth (radius approx. 6.4e6 meters) } - public double getUnmappedElevation(Angle latitude, Angle longitude) - { + public double getUnmappedElevation(Angle latitude, Angle longitude) { return 0; } @Override - public void setExtremesCachingEnabled(boolean enabled) - { + public void setExtremesCachingEnabled(boolean enabled) { } @Override - public boolean isExtremesCachingEnabled() - { + public boolean isExtremesCachingEnabled() { return false; } } diff --git a/src/gov/nasa/worldwind/tracks/Track.java b/src/gov/nasa/worldwind/tracks/Track.java index d40e8fb436..8fb4f0bf50 100644 --- a/src/gov/nasa/worldwind/tracks/Track.java +++ b/src/gov/nasa/worldwind/tracks/Track.java @@ -9,8 +9,8 @@ * @author tag * @version $Id: Track.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Track -{ +public interface Track { + java.util.List getSegments(); String getName(); diff --git a/src/gov/nasa/worldwind/tracks/TrackPoint.java b/src/gov/nasa/worldwind/tracks/TrackPoint.java index 85c08f956d..51002a98e6 100644 --- a/src/gov/nasa/worldwind/tracks/TrackPoint.java +++ b/src/gov/nasa/worldwind/tracks/TrackPoint.java @@ -11,8 +11,8 @@ * @author tag * @version $Id: TrackPoint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TrackPoint -{ +public interface TrackPoint { + double getLatitude(); void setLatitude(double latitude); diff --git a/src/gov/nasa/worldwind/tracks/TrackPointImpl.java b/src/gov/nasa/worldwind/tracks/TrackPointImpl.java index 5c22df8017..9d4faa0fd3 100644 --- a/src/gov/nasa/worldwind/tracks/TrackPointImpl.java +++ b/src/gov/nasa/worldwind/tracks/TrackPointImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.tracks; import gov.nasa.worldwind.geom.Angle; @@ -14,79 +13,65 @@ * @author tag * @version $Id: TrackPointImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TrackPointImpl implements TrackPoint -{ +public class TrackPointImpl implements TrackPoint { + private Position position; private String time; - public TrackPointImpl(Angle lat, Angle lon, double elevation, String time) - { + public TrackPointImpl(Angle lat, Angle lon, double elevation, String time) { this(new Position(lat, lon, elevation), time); } - public TrackPointImpl(LatLon latLon, double elevation, String time) - { + public TrackPointImpl(LatLon latLon, double elevation, String time) { this(new Position(latLon.getLatitude(), latLon.getLongitude(), elevation), time); } - public TrackPointImpl(Position position, String time) - { + public TrackPointImpl(Position position, String time) { this.position = position; } - public TrackPointImpl(Position position) - { + public TrackPointImpl(Position position) { this(position, null); } - public double getLatitude() - { + public double getLatitude() { return this.position.getLatitude().degrees; } - public void setLatitude(double latitude) - { + public void setLatitude(double latitude) { this.position = new Position(Angle.fromDegrees(latitude), this.position.getLongitude(), - this.position.getElevation()); + this.position.getElevation()); } - public double getLongitude() - { + public double getLongitude() { return this.position.getLongitude().degrees; } - public void setLongitude(double longitude) - { + public void setLongitude(double longitude) { this.position = new Position(this.position.getLatitude(), Angle.fromDegrees(longitude), - this.position.getElevation()); + this.position.getElevation()); } - public double getElevation() - { + public double getElevation() { return this.position.getElevation(); } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.position = new Position(this.position.getLatitude(), this.position.getLongitude(), elevation); } - public String getTime() - { + public String getTime() { return this.time; } - public void setTime(String time) - { + public void setTime(String time) { this.time = time; } - public Position getPosition() - { + public Position getPosition() { return this.position; } - public void setPosition(Position position) - { + public void setPosition(Position position) { } } diff --git a/src/gov/nasa/worldwind/tracks/TrackPointIterator.java b/src/gov/nasa/worldwind/tracks/TrackPointIterator.java index e0ba6aebf9..6a53049aa6 100644 --- a/src/gov/nasa/worldwind/tracks/TrackPointIterator.java +++ b/src/gov/nasa/worldwind/tracks/TrackPointIterator.java @@ -9,8 +9,8 @@ * @author tag * @version $Id: TrackPointIterator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TrackPointIterator extends java.util.Iterator -{ +public interface TrackPointIterator extends java.util.Iterator { + boolean hasNext(); TrackPoint next(); diff --git a/src/gov/nasa/worldwind/tracks/TrackPointIteratorImpl.java b/src/gov/nasa/worldwind/tracks/TrackPointIteratorImpl.java index ac4f5b257c..fc4ae8f099 100644 --- a/src/gov/nasa/worldwind/tracks/TrackPointIteratorImpl.java +++ b/src/gov/nasa/worldwind/tracks/TrackPointIteratorImpl.java @@ -13,23 +13,20 @@ * @author tag * @version $Id: TrackPointIteratorImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TrackPointIteratorImpl implements TrackPointIterator -{ +public class TrackPointIteratorImpl implements TrackPointIterator { + private Iterable trackIterable; private java.util.Iterator tracks; private java.util.Iterator segments; private java.util.Iterator positions; - public TrackPointIteratorImpl(Iterable trackIterable) - { + public TrackPointIteratorImpl(Iterable trackIterable) { this.trackIterable = trackIterable; this.reset(); } - public TrackPointIteratorImpl reset() - { - if (this.trackIterable == null) - { + public TrackPointIteratorImpl reset() { + if (this.trackIterable == null) { String msg = Logging.getMessage("nullValue.TracksIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -43,37 +40,32 @@ public TrackPointIteratorImpl reset() return this; } - public boolean hasNext() - { - if (this.positions != null && this.positions.hasNext()) + public boolean hasNext() { + if (this.positions != null && this.positions.hasNext()) { return true; + } this.loadNextPositions(); return (this.positions != null && this.positions.hasNext()); } - private void loadNextPositions() - { - if (this.segments != null && this.segments.hasNext()) - { + private void loadNextPositions() { + if (this.segments != null && this.segments.hasNext()) { TrackSegment segment = this.segments.next(); this.positions = segment.getPoints().iterator(); return; } - if (this.tracks.hasNext()) - { + if (this.tracks.hasNext()) { Track track = this.tracks.next(); this.segments = track.getSegments().iterator(); this.loadNextPositions(); } } - public TrackPoint next() - { - if (!this.hasNext()) - { + public TrackPoint next() { + if (!this.hasNext()) { String msg = Logging.getMessage("TrackPointIterator.NoMoreTrackPoints"); Logging.logger().severe(msg); throw new NoSuchElementException(msg); @@ -82,18 +74,17 @@ public TrackPoint next() return this.positions.next(); } - public void remove() - { + public void remove() { String msg = Logging.getMessage("TrackPointIterator.RemoveNotSupported"); Logging.logger().severe(msg); throw new UnsupportedOperationException(msg); } - public int getNumPoints() - { + public int getNumPoints() { int numPoints; - for (numPoints = 0; this.hasNext(); this.next()) + for (numPoints = 0; this.hasNext(); this.next()) { ++numPoints; + } return numPoints; } diff --git a/src/gov/nasa/worldwind/tracks/TrackSegment.java b/src/gov/nasa/worldwind/tracks/TrackSegment.java index 361f78a13a..55279c621d 100644 --- a/src/gov/nasa/worldwind/tracks/TrackSegment.java +++ b/src/gov/nasa/worldwind/tracks/TrackSegment.java @@ -9,7 +9,7 @@ * @author tag * @version $Id: TrackSegment.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TrackSegment -{ +public interface TrackSegment { + java.util.List getPoints(); } diff --git a/src/gov/nasa/worldwind/util/AbsentResourceList.java b/src/gov/nasa/worldwind/util/AbsentResourceList.java index 776dcf4c58..2117b60996 100644 --- a/src/gov/nasa/worldwind/util/AbsentResourceList.java +++ b/src/gov/nasa/worldwind/util/AbsentResourceList.java @@ -17,30 +17,46 @@ * @author tag * @version $Id: AbsentResourceList.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AbsentResourceList -{ +public class AbsentResourceList { // Absent resources: A resource is deemed absent if a specified maximum number of attempts have been made to retrieve it. // Retrieval attempts are governed by a minimum time interval between successive attempts. If an attempt is made // within this interval, the resource is still deemed to be absent until the interval expires. - /** The default number of times a resource is marked as absent before being marked as permanently absent. */ + /** + * The default number of times a resource is marked as absent before being marked as permanently absent. + */ protected static final int DEFAULT_MAX_ABSENT_RESOURCE_TRIES = 3; - /** The default interval to wait before indicating the resource is not absent. */ + /** + * The default interval to wait before indicating the resource is not absent. + */ protected static final int DEFAULT_MIN_ABSENT_RESOURCE_CHECK_INTERVAL = 10000; - /** The default interval at which a resources is marked as not absent after having been marked permanently absent. */ + /** + * The default interval at which a resources is marked as not absent after having been marked permanently absent. + */ protected static final int DEFAULT_TRY_AGAIN_INTERVAL = (int) 60e3; // seconds - /** The maximum number of times a resource is marked as absent before being marked as permanently absent. */ + /** + * The maximum number of times a resource is marked as absent before being marked as permanently absent. + */ protected int maxTries = DEFAULT_MAX_ABSENT_RESOURCE_TRIES; - /** The interval to wait, in milliseconds, before indicating the resource is not absent. */ + /** + * The interval to wait, in milliseconds, before indicating the resource is not absent. + */ protected int minCheckInterval = DEFAULT_MIN_ABSENT_RESOURCE_CHECK_INTERVAL; - /** The interval at which a resource is marked as not absent after having been marked as permanently absent. */ + /** + * The interval at which a resource is marked as not absent after having been marked as permanently absent. + */ protected int tryAgainInterval = DEFAULT_TRY_AGAIN_INTERVAL; - /** Internal class that maintains a resource's state. */ - protected static class AbsentResourceEntry - { - /** The time the resource was last marked as absent by a call to {@link AbsentResourceList#markResourceAbsent(String)}. */ + /** + * Internal class that maintains a resource's state. + */ + protected static class AbsentResourceEntry { + + /** + * The time the resource was last marked as absent by a call to + * {@link AbsentResourceList#markResourceAbsent(String)}. + */ long timeOfLastMark; // meant to be the time of the most recent attempt to find the resource /** * The maximum number of times the resource is marked as absent beyond which the resource is considered @@ -49,35 +65,33 @@ protected static class AbsentResourceEntry int numTries; } - /** The map of absent resources. */ + /** + * The map of absent resources. + */ protected BasicSessionCache possiblyAbsent = new BasicSessionCache(1000); /** * Construct an absent-resource list with default values for max tries (3), check interval (10 seconds) and * try-again interval (60 seconds). */ - public AbsentResourceList() - { + public AbsentResourceList() { } /** * Construct an absent-resource list with a specified number of maximum tries and a check interval. * - * @param maxTries the number of max tries. Must be greater than 0. + * @param maxTries the number of max tries. Must be greater than 0. * @param minCheckInterval the check interval. Must be greater than or equal to 0. * * @throws IllegalArgumentException if max-tries is less than 1 or the minimum check interval is less than 0. */ - public AbsentResourceList(int maxTries, int minCheckInterval) - { - if (maxTries < 1) - { + public AbsentResourceList(int maxTries, int minCheckInterval) { + if (maxTries < 1) { String message = Logging.getMessage("AbsentResourceList.MaxTriesLessThanOne"); throw new IllegalArgumentException(message); } - if (minCheckInterval < 0) - { + if (minCheckInterval < 0) { String message = Logging.getMessage("AbsentResourceList.CheckIntervalLessThanZero"); throw new IllegalArgumentException(message); } @@ -90,44 +104,40 @@ public AbsentResourceList(int maxTries, int minCheckInterval) * Construct an absent-resource list with a specified number of maximum tries, a check interval and a retry * interval. * - * @param cacheSize the maximum number of absent resources the list may hold. If this limit is exceeded, the - * oldest entries in the list are ejected and the resources they refer to are subsequently - * not considered to be absent resources. - * @param maxTries the number of max tries. Must be greater than 0. + * @param cacheSize the maximum number of absent resources the list may hold. If this limit is exceeded, the oldest + * entries in the list are ejected and the resources they refer to are subsequently not considered to be absent + * resources. + * @param maxTries the number of max tries. Must be greater than 0. * @param minCheckInterval the check interval. Must be greater than or equal to 0. - * @param tryAgainInterval the try-again interval. Must be greater than or equal to 0. + * @param tryAgainInterval the try-again interval. Must be greater than or equal to 0. * * @throws IllegalArgumentException if max-tries is less than 1 or if either the minimum check interval or try-again - * interval is less than 0. + * interval is less than 0. */ - public AbsentResourceList(Integer cacheSize, int maxTries, int minCheckInterval, int tryAgainInterval) - { - if (maxTries < 1) - { + public AbsentResourceList(Integer cacheSize, int maxTries, int minCheckInterval, int tryAgainInterval) { + if (maxTries < 1) { String message = Logging.getMessage("AbsentResourceList.MaxTriesLessThanOne"); throw new IllegalArgumentException(message); } - if (minCheckInterval < 0) - { + if (minCheckInterval < 0) { String message = Logging.getMessage("AbsentResourceList.CheckIntervalLessThanZero"); throw new IllegalArgumentException(message); } - if (tryAgainInterval < 0) - { + if (tryAgainInterval < 0) { String message = Logging.getMessage("AbsentResourceList.RetryIntervalLessThanZero"); throw new IllegalArgumentException(message); } - if (cacheSize != null && cacheSize < 1) - { + if (cacheSize != null && cacheSize < 1) { String message = Logging.getMessage("AbsentResourceList.MaximumListSizeLessThanOne"); throw new IllegalArgumentException(message); } - if (cacheSize != null) + if (cacheSize != null) { this.possiblyAbsent.setCapacity(cacheSize); + } this.maxTries = Math.max(maxTries, 1); this.minCheckInterval = minCheckInterval; @@ -139,8 +149,7 @@ public AbsentResourceList(Integer cacheSize, int maxTries, int minCheckInterval, * * @return the maximum number of absent markings. */ - public int getMaxTries() - { + public int getMaxTries() { return maxTries; } @@ -151,10 +160,8 @@ public int getMaxTries() * * @throws IllegalArgumentException if max-tries is less than 1. */ - public void setMaxTries(int maxTries) - { - if (maxTries < 1) - { + public void setMaxTries(int maxTries) { + if (maxTries < 1) { String message = Logging.getMessage("AbsentResourceList.MaxTriesLessThanOne"); throw new IllegalArgumentException(message); } @@ -168,8 +175,7 @@ public void setMaxTries(int maxTries) * * @return the interval, in milliseconds. */ - public int getMinCheckInterval() - { + public int getMinCheckInterval() { return minCheckInterval; } @@ -181,10 +187,8 @@ public int getMinCheckInterval() * * @throws IllegalArgumentException if the minimum check interval is less than 0. */ - public void setMinCheckInterval(int minCheckInterval) - { - if (minCheckInterval < 0) - { + public void setMinCheckInterval(int minCheckInterval) { + if (minCheckInterval < 0) { String message = Logging.getMessage("AbsentResourceList.CheckIntervalLessThanZero"); throw new IllegalArgumentException(message); } @@ -198,8 +202,7 @@ public void setMinCheckInterval(int minCheckInterval) * * @return the interval, in milliseconds. */ - public int getTryAgainInterval() - { + public int getTryAgainInterval() { return tryAgainInterval; } @@ -207,14 +210,12 @@ public int getTryAgainInterval() * Specifies the time interval that must elapse before a resource marked as permanently absent is again considered * not absent. This effectively expires the absent state of the resource. * - * @param tryAgainInterval the try-again interval. Must be greater than or equal to 0. + * @param tryAgainInterval the try-again interval. Must be greater than or equal to 0. * * @throws IllegalArgumentException if the try-again interval is less than 0. */ - public void setTryAgainInterval(int tryAgainInterval) - { - if (tryAgainInterval < 0) - { + public void setTryAgainInterval(int tryAgainInterval) { + if (tryAgainInterval < 0) { String message = Logging.getMessage("AbsentResourceList.RetryIntervalLessThanZero"); throw new IllegalArgumentException(message); } @@ -228,8 +229,7 @@ public void setTryAgainInterval(int tryAgainInterval) * * @param resourceID the resource to mark as absent. */ - public final void markResourceAbsent(long resourceID) - { + public final void markResourceAbsent(long resourceID) { this.markResourceAbsent(Long.toString(resourceID)); } @@ -240,8 +240,7 @@ public final void markResourceAbsent(long resourceID) * * @return true if the resource is considered absent, otherwise false. */ - public final boolean isResourceAbsent(long resourceID) - { + public final boolean isResourceAbsent(long resourceID) { return this.isResourceAbsent(Long.toString(resourceID)); } @@ -250,8 +249,7 @@ public final boolean isResourceAbsent(long resourceID) * * @param resourceID the resource to mark as not absent. */ - public final void unmarkResourceAbsent(long resourceID) - { + public final void unmarkResourceAbsent(long resourceID) { this.unmarkResourceAbsent(Long.toString(resourceID)); } @@ -261,11 +259,11 @@ public final void unmarkResourceAbsent(long resourceID) * * @param resourceID the resource to mark as absent. */ - synchronized public final void markResourceAbsent(String resourceID) - { + synchronized public final void markResourceAbsent(String resourceID) { AbsentResourceEntry entry = (AbsentResourceEntry) this.possiblyAbsent.get(resourceID); - if (entry == null) + if (entry == null) { this.possiblyAbsent.put(resourceID, entry = new AbsentResourceEntry()); + } ++entry.numTries; entry.timeOfLastMark = System.currentTimeMillis(); @@ -278,16 +276,15 @@ synchronized public final void markResourceAbsent(String resourceID) * * @return true if the resource is considered absent, otherwise false. */ - synchronized public final boolean isResourceAbsent(String resourceID) - { + synchronized public final boolean isResourceAbsent(String resourceID) { AbsentResourceEntry entry = (AbsentResourceEntry) this.possiblyAbsent.get(resourceID); - if (entry == null) + if (entry == null) { return false; + } long timeSinceLastMark = System.currentTimeMillis() - entry.timeOfLastMark; - if (timeSinceLastMark > this.tryAgainInterval) - { + if (timeSinceLastMark > this.tryAgainInterval) { this.possiblyAbsent.remove(resourceID); return false; } @@ -300,8 +297,7 @@ synchronized public final boolean isResourceAbsent(String resourceID) * * @param resourceID the resource to remove from this list. */ - synchronized public final void unmarkResourceAbsent(String resourceID) - { + synchronized public final void unmarkResourceAbsent(String resourceID) { this.possiblyAbsent.remove(resourceID); } } diff --git a/src/gov/nasa/worldwind/util/AbstractHotSpot.java b/src/gov/nasa/worldwind/util/AbstractHotSpot.java index ef1f0478cb..f16232add4 100644 --- a/src/gov/nasa/worldwind/util/AbstractHotSpot.java +++ b/src/gov/nasa/worldwind/util/AbstractHotSpot.java @@ -19,25 +19,30 @@ * @author dcollins * @version $Id: AbstractHotSpot.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractHotSpot extends AVListImpl implements HotSpot -{ - /** Indicates whether or not this HotSpot is active. */ +public abstract class AbstractHotSpot extends AVListImpl implements HotSpot { + + /** + * Indicates whether or not this HotSpot is active. + */ protected boolean active; - /** Creates a new AbstractHotSpot, but otherwise does nothing. */ - public AbstractHotSpot() - { + /** + * Creates a new AbstractHotSpot, but otherwise does nothing. + */ + public AbstractHotSpot() { } - /** {@inheritDoc} */ - public void setActive(boolean active) - { + /** + * {@inheritDoc} + */ + public void setActive(boolean active) { this.active = active; } - /** {@inheritDoc} */ - public boolean isActive() - { + /** + * {@inheritDoc} + */ + public boolean isActive() { return this.active; } @@ -47,8 +52,7 @@ public boolean isActive() * * @param event The event to handle. */ - public void selected(SelectEvent event) - { + public void selected(SelectEvent event) { } /** @@ -57,8 +61,7 @@ public void selected(SelectEvent event) * * @param event The event to handle. */ - public void keyTyped(KeyEvent event) - { + public void keyTyped(KeyEvent event) { } /** @@ -67,8 +70,7 @@ public void keyTyped(KeyEvent event) * * @param event The event to handle. */ - public void keyPressed(KeyEvent event) - { + public void keyPressed(KeyEvent event) { } /** @@ -77,8 +79,7 @@ public void keyPressed(KeyEvent event) * * @param event The event to handle. */ - public void keyReleased(KeyEvent event) - { + public void keyReleased(KeyEvent event) { } /** @@ -87,8 +88,7 @@ public void keyReleased(KeyEvent event) * * @param event The event to handle. */ - public void mouseClicked(MouseEvent event) - { + public void mouseClicked(MouseEvent event) { } /** @@ -97,8 +97,7 @@ public void mouseClicked(MouseEvent event) * * @param event The event to handle. */ - public void mousePressed(MouseEvent event) - { + public void mousePressed(MouseEvent event) { } /** @@ -107,8 +106,7 @@ public void mousePressed(MouseEvent event) * * @param event The event to handle. */ - public void mouseReleased(MouseEvent event) - { + public void mouseReleased(MouseEvent event) { } /** @@ -117,8 +115,7 @@ public void mouseReleased(MouseEvent event) * * @param event The event to handle. */ - public void mouseEntered(MouseEvent event) - { + public void mouseEntered(MouseEvent event) { } /** @@ -127,8 +124,7 @@ public void mouseEntered(MouseEvent event) * * @param event The event to handle. */ - public void mouseExited(MouseEvent event) - { + public void mouseExited(MouseEvent event) { } /** @@ -137,8 +133,7 @@ public void mouseExited(MouseEvent event) * * @param event The event to handle. */ - public void mouseDragged(MouseEvent event) - { + public void mouseDragged(MouseEvent event) { } /** @@ -147,8 +142,7 @@ public void mouseDragged(MouseEvent event) * * @param event The event to handle. */ - public void mouseMoved(MouseEvent event) - { + public void mouseMoved(MouseEvent event) { } /** @@ -157,8 +151,7 @@ public void mouseMoved(MouseEvent event) * * @param event The event to handle. */ - public void mouseWheelMoved(MouseWheelEvent event) - { + public void mouseWheelMoved(MouseWheelEvent event) { } /** @@ -166,8 +159,7 @@ public void mouseWheelMoved(MouseWheelEvent event) * * @return A {@code null} Cursor. */ - public Cursor getCursor() - { + public Cursor getCursor() { return null; } @@ -177,10 +169,9 @@ public Cursor getCursor() * @param event Event to test. * * @return {@code true} if {@code event} has been consumed, or if {@code event} was triggered by a mouse event, and - * that mouse event has been consumed. + * that mouse event has been consumed. */ - protected boolean isConsumed(SelectEvent event) - { + protected boolean isConsumed(SelectEvent event) { return event.isConsumed() || (event.getMouseEvent() != null && event.getMouseEvent().isConsumed()); } } diff --git a/src/gov/nasa/worldwind/util/AbstractResizeHotSpot.java b/src/gov/nasa/worldwind/util/AbstractResizeHotSpot.java index 4b621a9180..ae8ff9e4f8 100644 --- a/src/gov/nasa/worldwind/util/AbstractResizeHotSpot.java +++ b/src/gov/nasa/worldwind/util/AbstractResizeHotSpot.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.avlist.AVKey; @@ -26,8 +25,8 @@ * @author pabercrombie * @version $Id: AbstractResizeHotSpot.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractResizeHotSpot extends AbstractHotSpot -{ +public abstract class AbstractResizeHotSpot extends AbstractHotSpot { + protected static final int NORTH = 1; protected static final int SOUTH = 2; protected static final int EAST = 4; @@ -51,7 +50,9 @@ public abstract class AbstractResizeHotSpot extends AbstractHotSpot * is being dragged, the window should move to keep that corner under the cursor. */ protected boolean adjustLocationX; - /** True if the window needs to be moved in the Y direction as it is resized. */ + /** + * True if the window needs to be moved in the Y direction as it is resized. + */ protected boolean adjustLocationY; protected int xSign = 1; @@ -59,84 +60,81 @@ public abstract class AbstractResizeHotSpot extends AbstractHotSpot protected int cursor; - protected void setDirection(String direction) - { + protected void setDirection(String direction) { int dir = 0; - if (AVKey.NORTH.equals(direction)) + if (AVKey.NORTH.equals(direction)) { dir = NORTH; - else if (AVKey.SOUTH.equals(direction)) + } else if (AVKey.SOUTH.equals(direction)) { dir = SOUTH; - else if (AVKey.EAST.equals(direction)) + } else if (AVKey.EAST.equals(direction)) { dir = EAST; - else if (AVKey.WEST.equals(direction)) + } else if (AVKey.WEST.equals(direction)) { dir = WEST; - else if (AVKey.NORTHEAST.equals(direction)) + } else if (AVKey.NORTHEAST.equals(direction)) { dir = NORTHEAST; - else if (AVKey.NORTHWEST.equals(direction)) + } else if (AVKey.NORTHWEST.equals(direction)) { dir = NORTHWEST; - else if (AVKey.SOUTHEAST.equals(direction)) + } else if (AVKey.SOUTHEAST.equals(direction)) { dir = SOUTHEAST; - else if (AVKey.SOUTHWEST.equals(direction)) + } else if (AVKey.SOUTHWEST.equals(direction)) { dir = SOUTHWEST; + } this.setDirection(dir); } - protected void setDirection(int direction) - { - this.adjustLocationX = - NORTH == direction + protected void setDirection(int direction) { + this.adjustLocationX + = NORTH == direction || WEST == direction || SOUTHWEST == direction || NORTHWEST == direction; - this.adjustLocationY = - NORTH == direction + this.adjustLocationY + = NORTH == direction || WEST == direction || NORTHWEST == direction || NORTHEAST == direction; - if (NORTH == direction || SOUTH == direction) - { + if (NORTH == direction || SOUTH == direction) { this.allowVerticalResize = true; this.allowHorizontalResize = false; - } - else if (EAST == direction || WEST == direction) - { + } else if (EAST == direction || WEST == direction) { this.allowVerticalResize = false; this.allowHorizontalResize = true; - } - else - { + } else { this.allowVerticalResize = true; this.allowHorizontalResize = true; } - if (WEST == direction || SOUTHWEST == direction || NORTHWEST == direction) + if (WEST == direction || SOUTHWEST == direction || NORTHWEST == direction) { this.xSign = -1; - else + } else { this.xSign = 1; + } - if (NORTH == direction || NORTHEAST == direction || NORTHWEST == direction) + if (NORTH == direction || NORTHEAST == direction || NORTHWEST == direction) { this.ySign = -1; - else + } else { this.ySign = 1; + } - if (NORTH == direction) + if (NORTH == direction) { this.cursor = Cursor.N_RESIZE_CURSOR; - else if (SOUTH == direction) + } else if (SOUTH == direction) { this.cursor = Cursor.S_RESIZE_CURSOR; - else if (EAST == direction) + } else if (EAST == direction) { this.cursor = Cursor.E_RESIZE_CURSOR; - else if (WEST == direction) + } else if (WEST == direction) { this.cursor = Cursor.W_RESIZE_CURSOR; - else if (NORTHEAST == direction) + } else if (NORTHEAST == direction) { this.cursor = Cursor.NE_RESIZE_CURSOR; - else if (SOUTHEAST == direction) + } else if (SOUTHEAST == direction) { this.cursor = Cursor.SE_RESIZE_CURSOR; - else if (SOUTHWEST == direction) + } else if (SOUTHWEST == direction) { this.cursor = Cursor.SW_RESIZE_CURSOR; - else if (NORTHWEST == direction) + } else if (NORTHWEST == direction) { this.cursor = Cursor.NW_RESIZE_CURSOR; + } } /** @@ -145,13 +143,13 @@ else if (NORTHWEST == direction) * * @param pickPoint The point on the frame that was picked. */ - protected void setDirectionFromPoint(Point pickPoint) - { + protected void setDirectionFromPoint(Point pickPoint) { Point topLeft = this.getScreenPoint(); Dimension size = this.getSize(); - if (topLeft == null || size == null) + if (topLeft == null || size == null) { return; + } // Find the center of the frame Point center = new Point(topLeft.x + size.width / 2, topLeft.y + size.height / 2); @@ -173,12 +171,13 @@ protected void setDirectionFromPoint(Point pickPoint) int dir; double tolerance = frameAspectRatio * 0.1; - if (Math.abs(pickAspectRatio - frameAspectRatio) < tolerance) + if (Math.abs(pickAspectRatio - frameAspectRatio) < tolerance) { dir = hdir + vdir; - else if (pickAspectRatio < frameAspectRatio) + } else if (pickAspectRatio < frameAspectRatio) { dir = vdir; - else + } else { dir = hdir; + } this.setDirection(dir); } @@ -188,8 +187,7 @@ else if (pickAspectRatio < frameAspectRatio) * * @return True if the control is dragging. */ - public boolean isDragging() - { + public boolean isDragging() { return this.dragging; } @@ -201,18 +199,15 @@ public boolean isDragging() * @param event Select event. */ @Override - public void selected(SelectEvent event) - { - if (event == null || this.isConsumed(event)) + public void selected(SelectEvent event) { + if (event == null || this.isConsumed(event)) { return; + } Point pickPoint = event.getPickPoint(); - if (pickPoint != null) - { - if (event.isDrag()) - { - if (!this.isDragging()) - { + if (pickPoint != null) { + if (event.isDrag()) { + if (!this.isDragging()) { this.dragging = true; this.beginDrag(pickPoint); } @@ -223,8 +218,7 @@ public void selected(SelectEvent event) } } - if (event.isDragEnd()) - { + if (event.isDragEnd()) { this.dragging = false; this.endDrag(); @@ -238,43 +232,42 @@ public void selected(SelectEvent event) * @param e Mouse event. */ @Override - public void mouseMoved(MouseEvent e) - { - if (e == null || e.isConsumed()) + public void mouseMoved(MouseEvent e) { + if (e == null || e.isConsumed()) { return; - + } + this.setDirectionFromPoint(e.getPoint()); } - protected void beginDrag(Point point) - { + protected void beginDrag(Point point) { this.dragRefPoint = point; this.refSize = this.getSize(); this.refLocation = this.getScreenPoint(); } - public void drag(Point point) - { + public void drag(Point point) { int deltaX = 0; int deltaY = 0; - if (this.refLocation == null || this.refSize == null) + if (this.refLocation == null || this.refSize == null) { return; + } - if (this.allowHorizontalResize) + if (this.allowHorizontalResize) { deltaX = (point.x - this.dragRefPoint.x) * this.xSign; - if (this.allowVerticalResize) + } + if (this.allowVerticalResize) { deltaY = (point.y - this.dragRefPoint.y) * this.ySign; + } int width = this.refSize.width + deltaX; int height = this.refSize.height + deltaY; - if (this.isValidSize(width, height)) - { + if (this.isValidSize(width, height)) { this.setSize(new Dimension(width, height)); - if (this.adjustLocationX || this.adjustLocationY) - { + if (this.adjustLocationX || this.adjustLocationY) { double x = this.refLocation.x - (this.adjustLocationX ? deltaX : 0); double y = this.refLocation.y - (this.adjustLocationY ? deltaY : 0); this.setScreenPoint(new Point((int) x, (int) y)); @@ -282,9 +275,10 @@ public void drag(Point point) } } - /** Called when a drag action ends. This implementation sets {@link #dragRefPoint} to null. */ - protected void endDrag() - { + /** + * Called when a drag action ends. This implementation sets {@link #dragRefPoint} to null. + */ + protected void endDrag() { this.dragRefPoint = null; } @@ -294,8 +288,7 @@ protected void endDrag() * @return New cursor. */ @Override - public Cursor getCursor() - { + public Cursor getCursor() { return Cursor.getPredefinedCursor(this.cursor); } @@ -307,12 +300,12 @@ public Cursor getCursor() * @param active {@code true} if the HotSpot is being activated, {@code false} if it is being deactivated. */ @Override - public void setActive(boolean active) - { + public void setActive(boolean active) { // If the resize area is being deactivated, reset the cursor so that the next time the HotSpot becomes active // we won't show the wrong cursor. - if (!active) + if (!active) { this.cursor = Cursor.DEFAULT_CURSOR; + } super.setActive(active); } @@ -321,15 +314,14 @@ public void setActive(boolean active) * the resize operation is not attempted. This implementation ensures that the proposed frame size is greater than * or equal to the minimum frame size. * - * @param width Frame width. + * @param width Frame width. * @param height Frame height. * * @return True if this frame size is valid. * * @see #getMinimumSize() */ - protected boolean isValidSize(int width, int height) - { + protected boolean isValidSize(int width, int height) { Dimension minSize = this.getMinimumSize(); return width >= minSize.width && height >= minSize.height; } @@ -342,8 +334,7 @@ protected boolean isValidSize(int width, int height) * * @see #isValidSize(int, int) */ - protected Dimension getMinimumSize() - { + protected Dimension getMinimumSize() { return new Dimension(0, 0); } diff --git a/src/gov/nasa/worldwind/util/BasicClutterFilter.java b/src/gov/nasa/worldwind/util/BasicClutterFilter.java index 69db132aff..c480243c17 100644 --- a/src/gov/nasa/worldwind/util/BasicClutterFilter.java +++ b/src/gov/nasa/worldwind/util/BasicClutterFilter.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.render.*; @@ -17,23 +16,21 @@ * @author tag * @version $Id: BasicClutterFilter.java 726 2012-08-29 03:16:03Z tgaskins $ */ -public class BasicClutterFilter implements ClutterFilter -{ +public class BasicClutterFilter implements ClutterFilter { + protected List rectList = new ArrayList(); - public void apply(DrawContext dc, List shapes) - { - for (Declutterable shape : shapes) - { + public void apply(DrawContext dc, List shapes) { + for (Declutterable shape : shapes) { Rectangle2D bounds = shape.getBounds(dc); - if (bounds == null) + if (bounds == null) { continue; + } // Check for an intersecting region. If none, then add the incoming region to the region list. Subsequent // regions will be checked for intersection with it. Rectangle2D intersectingRegion = this.intersects(bounds); - if (intersectingRegion == null) - { + if (intersectingRegion == null) { dc.addOrderedRenderable(shape); this.rectList.add(bounds); } @@ -42,8 +39,7 @@ public void apply(DrawContext dc, List shapes) this.clear(); } - protected void clear() - { + protected void clear() { this.rectList.clear(); } @@ -54,16 +50,16 @@ protected void clear() * * @return true if the region intersects one or more other regions in the filter, otherwise false. */ - protected Rectangle2D intersects(Rectangle2D rectangle) - { - if (rectangle == null) + protected Rectangle2D intersects(Rectangle2D rectangle) { + if (rectangle == null) { return null; + } // Performs a simple linear search. This is a performance bottleneck for very large lists. - for (Rectangle2D rect : this.rectList) - { - if (rectangle.intersects(rect)) + for (Rectangle2D rect : this.rectList) { + if (rectangle.intersects(rect)) { return rect; + } } return null; diff --git a/src/gov/nasa/worldwind/util/BasicDragger.java b/src/gov/nasa/worldwind/util/BasicDragger.java index 86378aef73..5ca74b1812 100644 --- a/src/gov/nasa/worldwind/util/BasicDragger.java +++ b/src/gov/nasa/worldwind/util/BasicDragger.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.*; @@ -23,8 +22,8 @@ *

                  * For objects not yet implementing the {@link Draggable} interface the legacy dragging functionality will be used. */ -public class BasicDragger implements SelectListener -{ +public class BasicDragger implements SelectListener { + /** * The {@link WorldWindow} this dragger will utilize for the {@link Globe}, {@link View}, and * {@link SceneController} objects. @@ -46,10 +45,8 @@ public class BasicDragger implements SelectListener * * @throws IllegalArgumentException if the provided {@link WorldWindow} is null. */ - public BasicDragger(WorldWindow wwd) - { - if (wwd == null) - { + public BasicDragger(WorldWindow wwd) { + if (wwd == null) { String msg = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -65,8 +62,7 @@ public BasicDragger(WorldWindow wwd) * @deprecated the useTerrain property has been deprecated in favor of the {@link Draggable} interface which allows * the object to define the drag behavior. */ - public BasicDragger(WorldWindow wwd, boolean useTerrain) - { + public BasicDragger(WorldWindow wwd, boolean useTerrain) { this(wwd); } @@ -75,8 +71,7 @@ public BasicDragger(WorldWindow wwd, boolean useTerrain) * * @return true if a drag operation is executing. */ - public boolean isDragging() - { + public boolean isDragging() { return this.dragging; } @@ -85,8 +80,7 @@ public boolean isDragging() * @return false as this functionality has been deprecated. * @deprecated the {@link Draggable} provides the object being dragged complete control over the dragging behavior. */ - public boolean isUseTerrain() - { + public boolean isUseTerrain() { return false; } @@ -95,33 +89,28 @@ public boolean isUseTerrain() * * @deprecated definition of dragging behavior now defined by the object in the {@link Draggable} interface. */ - public void setUseTerrain(boolean useTerrain) - { + public void setUseTerrain(boolean useTerrain) { // ignored - functionality deprecated } @Override - public void selected(SelectEvent event) - { - if (event == null) - { + public void selected(SelectEvent event) { + if (event == null) { String msg = Logging.getMessage("nullValue.EventIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (event.getEventAction().equals(SelectEvent.DRAG_END)) - { + if (event.getEventAction().equals(SelectEvent.DRAG_END)) { this.dragContext.setDragState(AVKey.DRAG_ENDED); this.fireDrag((DragSelectEvent) event); this.dragContext = null; this.dragging = false; - } - else if (event.getEventAction().equals(SelectEvent.DRAG)) - { + } else if (event.getEventAction().equals(SelectEvent.DRAG)) { - if (this.dragContext == null) + if (this.dragContext == null) { this.dragContext = new DragContext(); + } this.dragContext.setPoint(event.getPickPoint()); this.dragContext.setPreviousPoint(((DragSelectEvent) event).getPreviousPickPoint()); @@ -129,13 +118,10 @@ else if (event.getEventAction().equals(SelectEvent.DRAG)) this.dragContext.setGlobe(this.wwd.getModel().getGlobe()); this.dragContext.setSceneController(this.wwd.getSceneController()); - if (this.dragging) - { + if (this.dragging) { this.dragContext.setDragState(AVKey.DRAG_CHANGE); this.fireDrag((DragSelectEvent) event); - } - else - { + } else { this.dragContext.setDragState(AVKey.DRAG_BEGIN); this.dragContext.setInitialPoint(((DragSelectEvent) event).getPreviousPickPoint()); this.dragging = true; @@ -154,10 +140,8 @@ else if (event.getEventAction().equals(SelectEvent.DRAG)) * * @throws IllegalArgumentException if the {@link DragContext} is null. */ - protected void fireDrag(DragSelectEvent dragEvent) - { - if (dragEvent == null || dragEvent.getTopObject() == null) - { + protected void fireDrag(DragSelectEvent dragEvent) { + if (dragEvent == null || dragEvent.getTopObject() == null) { String msg = Logging.getMessage("nullValue.ObjectIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -165,12 +149,9 @@ protected void fireDrag(DragSelectEvent dragEvent) Object dragObject = dragEvent.getTopObject(); - if (dragObject instanceof Draggable) - { + if (dragObject instanceof Draggable) { ((Draggable) dragObject).drag(this.dragContext); - } - else if ((dragObject instanceof Movable2) || (dragObject instanceof Movable)) - { + } else if ((dragObject instanceof Movable2) || (dragObject instanceof Movable)) { // Utilize the existing behavior this.dragLegacy(dragEvent); } @@ -188,13 +169,13 @@ else if ((dragObject instanceof Movable2) || (dragObject instanceof Movable)) * * @param event the current {@link SelectEvent}. */ - protected void dragLegacy(SelectEvent event) - { + protected void dragLegacy(SelectEvent event) { DragSelectEvent dragEvent = (DragSelectEvent) event; Object dragObject = dragEvent.getTopObject(); - if (dragObject == null) + if (dragObject == null) { return; + } View view = wwd.getView(); Globe globe = wwd.getModel().getGlobe(); @@ -202,16 +183,18 @@ protected void dragLegacy(SelectEvent event) // Compute dragged object ref-point in model coordinates. // Use the Icon and Annotation logic of elevation as offset above ground when below max elevation. Position refPos = null; - if (dragObject instanceof Movable2) + if (dragObject instanceof Movable2) { refPos = ((Movable2) dragObject).getReferencePosition(); - else if (dragObject instanceof Movable) + } else if (dragObject instanceof Movable) { refPos = ((Movable) dragObject).getReferencePosition(); - if (refPos == null) + } + if (refPos == null) { return; + } Vec4 refPoint = globe.computePointFromPosition(refPos); - if (this.dragContext.getDragState().equals(AVKey.DRAG_BEGIN)) // Dragging started + if (this.dragContext.getDragState().equals(AVKey.DRAG_BEGIN)) // Dragging started { // Save initial reference points for object and cursor in screen coordinates // Note: y is inverted for the object point. @@ -233,18 +216,19 @@ else if (dragObject instanceof Movable) Position pickPos = null; // Use intersection with sphere at reference altitude. Intersection inters[] = globe.intersect(ray, this.dragRefAltitude); - if (inters != null) + if (inters != null) { pickPos = globe.computePositionFromPoint(inters[0].getIntersectionPoint()); + } - if (pickPos != null) - { + if (pickPos != null) { // Intersection with globe. Move reference point to the intersection point, // but maintain current altitude. Position p = new Position(pickPos, refPos.getElevation()); - if (dragObject instanceof Movable2) + if (dragObject instanceof Movable2) { ((Movable2) dragObject).moveTo(globe, p); - else + } else { ((Movable) dragObject).moveTo(p); + } } } } diff --git a/src/gov/nasa/worldwind/util/BasicGLCapabilitiesChooser.java b/src/gov/nasa/worldwind/util/BasicGLCapabilitiesChooser.java index 4527ef0225..cff5fe690c 100644 --- a/src/gov/nasa/worldwind/util/BasicGLCapabilitiesChooser.java +++ b/src/gov/nasa/worldwind/util/BasicGLCapabilitiesChooser.java @@ -10,8 +10,8 @@ import java.util.List; /** - * BasicGLCapabilitiesChooser provides an implementation of {@link com.jogamp.opengl.GLCapabilitiesChooser} for use - * with WorldWindow implementations (for example, WorldWindowGLCanvas and WorldWindowGLJPanel). + * BasicGLCapabilitiesChooser provides an implementation of {@link com.jogamp.opengl.GLCapabilitiesChooser} for use with + * WorldWindow implementations (for example, WorldWindowGLCanvas and WorldWindowGLJPanel). *

                  * BasicGLCapabilitiesChooser extends the behavior of the default GLCapabilitiesChooser by implementing a fallback * behavior when device supported stereo is requested but is not supported by the hardware. In this case, @@ -22,11 +22,12 @@ * @author dcollins * @version $Id: BasicGLCapabilitiesChooser.java 1739 2013-12-04 03:38:19Z dcollins $ */ -public class BasicGLCapabilitiesChooser extends DefaultGLCapabilitiesChooser -{ - /** Constructs a new BasicGLCapabilitiesChooser, but otherwise does nothing. */ - public BasicGLCapabilitiesChooser() - { +public class BasicGLCapabilitiesChooser extends DefaultGLCapabilitiesChooser { + + /** + * Constructs a new BasicGLCapabilitiesChooser, but otherwise does nothing. + */ + public BasicGLCapabilitiesChooser() { } /** @@ -34,19 +35,17 @@ public BasicGLCapabilitiesChooser() * hardware. When the desired GL capabilities does not specify device supported stereo, this calls * DefaultGLCapabilitiesChooser.chooseCapabilities. * - * @param desired the desired GL capabilities. - * @param available the list of available GL capabilities on the graphics device. + * @param desired the desired GL capabilities. + * @param available the list of available GL capabilities on the graphics device. * @param windowSystemRecommendedChoice an index into the list of available GL capabilities indicating the window - * system's recommended capabilities, or -1 to indicate no recommendation. + * system's recommended capabilities, or -1 to indicate no recommendation. * * @return an index into the list of available GL capabilities. */ @Override public int chooseCapabilities(CapabilitiesImmutable desired, - List available, int windowSystemRecommendedChoice) - { - if (desired instanceof GLCapabilities && ((GLCapabilities) desired).getStereo()) - { + List available, int windowSystemRecommendedChoice) { + if (desired instanceof GLCapabilities && ((GLCapabilities) desired).getStereo()) { return this.chooseStereoCapabilities(desired, available, windowSystemRecommendedChoice); } @@ -59,21 +58,18 @@ public int chooseCapabilities(CapabilitiesImmutable desired, * superclass cannot find a match, this attempts to find a match to the desired capabilities, but without device * supported stereo. * - * @param desired the desired GL capabilities. - * @param available the list of available GL capabilities on the graphics device. + * @param desired the desired GL capabilities. + * @param available the list of available GL capabilities on the graphics device. * @param windowSystemRecommendedChoice an index into the list of available GL capabilities indicating the window - * system's recommended capabilities, or -1 to indicate no recommendation. + * system's recommended capabilities, or -1 to indicate no recommendation. * * @return an index into the list of available GL capabilities. */ protected int chooseStereoCapabilities(CapabilitiesImmutable desired, - List available, int windowSystemRecommendedChoice) - { - try - { + List available, int windowSystemRecommendedChoice) { + try { return super.chooseCapabilities(desired, available, windowSystemRecommendedChoice); - } - catch (NativeWindowException e) // superclass cannot find a match + } catch (NativeWindowException e) // superclass cannot find a match { Logging.logger().warning(Logging.getMessage("generic.StereoNotSupported")); } diff --git a/src/gov/nasa/worldwind/util/BasicNamespaceContext.java b/src/gov/nasa/worldwind/util/BasicNamespaceContext.java index 51fbd048f5..edb25c1dff 100644 --- a/src/gov/nasa/worldwind/util/BasicNamespaceContext.java +++ b/src/gov/nasa/worldwind/util/BasicNamespaceContext.java @@ -16,8 +16,8 @@ * @author dcollins * @version $Id: BasicNamespaceContext.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicNamespaceContext implements NamespaceContext -{ +public class BasicNamespaceContext implements NamespaceContext { + public static final String XLINK_NS_PREFIX = "xlink"; public static final String XLINK_NS_URI = "http://www.w3.org/1999/xlink"; @@ -25,13 +25,14 @@ public class BasicNamespaceContext implements NamespaceContext private Map> prefixesByURI = new HashMap>(); /** - * Sole constructor for BasicNamespaceContext. This configures the following namespaces: + * Sole constructor for BasicNamespaceContext. This configures the following namespaces: + *
                  Namespaces
                  * - * + * + * *
                  Namespaces
                  PrefixURI
                  xmlhttp://www.w3.org/XML/1998/namespace
                  xmlnshttp://www.w3.org/2000/xmlns/
                  xlinkhttp://www.w3.org/1999/xlink
                  xmlnshttp://www.w3.org/2000/xmlns/
                  xlinkhttp://www.w3.org/1999/xlink
                  */ - public BasicNamespaceContext() - { + public BasicNamespaceContext() { // Configure the default xml and xmlns namespaces according to the documentation of the NamespaceContext // interface. this.addNamespace(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI); @@ -42,22 +43,19 @@ public BasicNamespaceContext() /** * Adds a namepsace binding to this XML namespace context. The specified URI is bound to the specified prefix. * - * @param prefix the namespace prefix. + * @param prefix the namespace prefix. * @param namespaceURI the namespace URI. * * @throws IllegalArgumentException if either the prefix or the namepsace URI are null. */ - public synchronized void addNamespace(String prefix, String namespaceURI) - { - if (prefix == null) - { + public synchronized void addNamespace(String prefix, String namespaceURI) { + if (prefix == null) { String message = Logging.getMessage("nullValue.PrefixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (namespaceURI == null) - { + if (namespaceURI == null) { String message = Logging.getMessage("nullValue.NamespaceURIIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -65,43 +63,37 @@ public synchronized void addNamespace(String prefix, String namespaceURI) this.urisByPrefix.put(prefix, namespaceURI); - if (this.prefixesByURI.containsKey(namespaceURI)) - { + if (this.prefixesByURI.containsKey(namespaceURI)) { this.prefixesByURI.get(namespaceURI).add(prefix); - } - else - { + } else { Set set = new HashSet(); set.add(prefix); this.prefixesByURI.put(namespaceURI, set); } } - /** {@inheritDoc} */ - public String getNamespaceURI(String prefix) - { - if (prefix == null) - { + /** + * {@inheritDoc} + */ + public String getNamespaceURI(String prefix) { + if (prefix == null) { String message = Logging.getMessage("nullValue.PrefixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.urisByPrefix.containsKey(prefix)) - { + if (this.urisByPrefix.containsKey(prefix)) { return this.urisByPrefix.get(prefix); - } - else - { + } else { return XMLConstants.NULL_NS_URI; } } - /** {@inheritDoc} */ - public String getPrefix(String namespaceURI) - { - if (namespaceURI == null) - { + /** + * {@inheritDoc} + */ + public String getPrefix(String namespaceURI) { + if (namespaceURI == null) { String message = Logging.getMessage("nullValue.NamespaceURIIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,22 +102,19 @@ public String getPrefix(String namespaceURI) return (String) this.getPrefixes(namespaceURI).next(); } - /** {@inheritDoc} */ - public Iterator getPrefixes(String namespaceURI) - { - if (namespaceURI == null) - { + /** + * {@inheritDoc} + */ + public Iterator getPrefixes(String namespaceURI) { + if (namespaceURI == null) { String message = Logging.getMessage("nullValue.NamespaceURIIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.prefixesByURI.containsKey(namespaceURI)) - { + if (this.prefixesByURI.containsKey(namespaceURI)) { return Collections.unmodifiableSet(this.prefixesByURI.get(namespaceURI)).iterator(); - } - else - { + } else { return Collections.EMPTY_SET.iterator(); } } diff --git a/src/gov/nasa/worldwind/util/BasicNetworkStatus.java b/src/gov/nasa/worldwind/util/BasicNetworkStatus.java index a684ddb9e6..5d5f7dcb05 100644 --- a/src/gov/nasa/worldwind/util/BasicNetworkStatus.java +++ b/src/gov/nasa/worldwind/util/BasicNetworkStatus.java @@ -20,36 +20,32 @@ * @author tag * @version $Id: BasicNetworkStatus.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicNetworkStatus extends AVListImpl implements NetworkStatus -{ +public class BasicNetworkStatus extends AVListImpl implements NetworkStatus { + protected static final long DEFAULT_TRY_AGAIN_INTERVAL = (long) 60e3; // seconds protected static final int DEFAULT_ATTEMPT_LIMIT = 7; // number of unavailable events to declare host unavailable protected static final long NETWORK_STATUS_REPORT_INTERVAL = (long) 120e3; - protected static final String[] DEFAULT_NETWORK_TEST_SITES = new String[] - {"www.nasa.gov", "worldwind.arc.nasa.gov", "google.com", "microsoft.com", "yahoo.com"}; + protected static final String[] DEFAULT_NETWORK_TEST_SITES = new String[]{"www.nasa.gov", "worldwind.arc.nasa.gov", "google.com", "microsoft.com", "yahoo.com"}; + + protected static class HostInfo { - protected static class HostInfo - { protected final long tryAgainInterval; protected final int attemptLimit; protected AtomicInteger logCount = new AtomicInteger(); protected AtomicLong lastLogTime = new AtomicLong(); - protected HostInfo(int attemptLimit, long tryAgainInterval) - { + protected HostInfo(int attemptLimit, long tryAgainInterval) { this.lastLogTime.set(System.currentTimeMillis()); this.logCount.set(1); this.tryAgainInterval = tryAgainInterval; this.attemptLimit = attemptLimit; } - protected boolean isUnavailable() - { + protected boolean isUnavailable() { return this.logCount.get() >= this.attemptLimit; } - protected boolean isTimeToTryAgain() - { + protected boolean isTimeToTryAgain() { return System.currentTimeMillis() - this.lastLogTime.get() >= this.tryAgainInterval; } } @@ -68,8 +64,7 @@ protected boolean isTimeToTryAgain() protected AtomicLong lastNetworkStatusReportTime = new AtomicLong(0); protected AtomicBoolean lastNetworkUnavailableResult = new AtomicBoolean(false); - public BasicNetworkStatus() - { + public BasicNetworkStatus() { String oms = Configuration.getStringValue(AVKey.OFFLINE_MODE, "false"); this.offlineMode = oms.startsWith("t") || oms.startsWith("T"); @@ -79,55 +74,54 @@ public BasicNetworkStatus() /** * Determines and stores the network sites to test for public network connectivity. The sites are drawn from the * JVM's gov.nasa.worldwind.avkey.NetworkStatusTestSites property ({@link AVKey#NETWORK_STATUS_TEST_SITES}). If that - * property is not defined, the sites are drawn from the same property in the WorldWind or application - * configuration file. If the sites are not specified there, the set of sites specified in {@link + * property is not defined, the sites are drawn from the same property in the WorldWind or application configuration + * file. If the sites are not specified there, the set of sites specified in {@link * #DEFAULT_NETWORK_TEST_SITES} are used. To indicate an empty list in the JVM property or configuration file * property, specify an empty site list, "". */ - protected void establishNetworkTestSites() - { + protected void establishNetworkTestSites() { String testSites = System.getProperty(AVKey.NETWORK_STATUS_TEST_SITES); - if (testSites == null) + if (testSites == null) { testSites = Configuration.getStringValue(AVKey.NETWORK_STATUS_TEST_SITES); + } - if (testSites == null) - { + if (testSites == null) { this.networkTestSites.addAll(Arrays.asList(DEFAULT_NETWORK_TEST_SITES)); - } - else - { + } else { String[] sites = testSites.split(","); List actualSites = new ArrayList(sites.length); - for (int i = 0; i < sites.length; i++) - { + for (int i = 0; i < sites.length; i++) { String site = WWUtil.removeWhiteSpace(sites[i]); - if (!WWUtil.isEmpty(site)) + if (!WWUtil.isEmpty(site)) { actualSites.add(site); + } } this.setNetworkTestSites(actualSites); } } - /** {@inheritDoc} */ - public boolean isOfflineMode() - { + /** + * {@inheritDoc} + */ + public boolean isOfflineMode() { return offlineMode; } - /** {@inheritDoc} */ - public void setOfflineMode(boolean offlineMode) - { + /** + * {@inheritDoc} + */ + public void setOfflineMode(boolean offlineMode) { this.offlineMode = offlineMode; } - /** {@inheritDoc} */ - public void setAttemptLimit(int limit) - { - if (limit < 1) - { + /** + * {@inheritDoc} + */ + public void setAttemptLimit(int limit) { + if (limit < 1) { String message = Logging.getMessage("NetworkStatus.InvalidAttemptLimit"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -136,11 +130,11 @@ public void setAttemptLimit(int limit) this.attemptLimit.set(limit); } - /** {@inheritDoc} */ - public void setTryAgainInterval(long interval) - { - if (interval < 0) - { + /** + * {@inheritDoc} + */ + public void setTryAgainInterval(long interval) { + if (interval < 0) { String message = Logging.getMessage("NetworkStatus.InvalidTryAgainInterval"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -149,41 +143,47 @@ public void setTryAgainInterval(long interval) this.tryAgainInterval.set(interval); } - /** {@inheritDoc} */ - public int getAttemptLimit() - { + /** + * {@inheritDoc} + */ + public int getAttemptLimit() { return this.attemptLimit.get(); } - /** {@inheritDoc} */ - public long getTryAgainInterval() - { + /** + * {@inheritDoc} + */ + public long getTryAgainInterval() { return this.tryAgainInterval.get(); } - /** {@inheritDoc} */ - public List getNetworkTestSites() - { + /** + * {@inheritDoc} + */ + public List getNetworkTestSites() { return new ArrayList(networkTestSites); } - /** {@inheritDoc} */ - public void setNetworkTestSites(List networkTestSites) - { + /** + * {@inheritDoc} + */ + public void setNetworkTestSites(List networkTestSites) { this.networkTestSites.clear(); - if (networkTestSites != null) + if (networkTestSites != null) { this.networkTestSites.addAll(networkTestSites); + } } - /** {@inheritDoc} */ - public synchronized void logUnavailableHost(URL url) - { - if (this.offlineMode) + /** + * {@inheritDoc} + */ + public synchronized void logUnavailableHost(URL url) { + if (this.offlineMode) { return; + } - if (url == null) - { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -191,36 +191,37 @@ public synchronized void logUnavailableHost(URL url) String hostName = url.getHost(); HostInfo hi = this.hostMap.get(hostName); - if (hi != null) - { - if (!hi.isUnavailable()) - { + if (hi != null) { + if (!hi.isUnavailable()) { hi.logCount.incrementAndGet(); if (hi.isUnavailable()) // host just became unavailable + { this.firePropertyChange(NetworkStatus.HOST_UNAVAILABLE, null, url); + } } hi.lastLogTime.set(System.currentTimeMillis()); - } - else - { + } else { hi = new HostInfo(this.attemptLimit.get(), this.tryAgainInterval.get()); hi.logCount.set(1); if (hi.isUnavailable()) // the attempt limit may be as low as 1, so handle that case here + { this.firePropertyChange(NetworkStatus.HOST_UNAVAILABLE, null, url); + } this.hostMap.put(hostName, hi); } this.lastUnavailableLogTime.set(System.currentTimeMillis()); } - /** {@inheritDoc} */ - public synchronized void logAvailableHost(URL url) - { - if (this.offlineMode) + /** + * {@inheritDoc} + */ + public synchronized void logAvailableHost(URL url) { + if (this.offlineMode) { return; + } - if (url == null) - { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -228,8 +229,7 @@ public synchronized void logAvailableHost(URL url) String hostName = url.getHost(); HostInfo hi = this.hostMap.get(hostName); - if (hi != null) - { + if (hi != null) { this.hostMap.remove(hostName); // host is available again firePropertyChange(NetworkStatus.HOST_AVAILABLE, null, url); } @@ -237,14 +237,15 @@ public synchronized void logAvailableHost(URL url) this.lastAvailableLogTime.set(System.currentTimeMillis()); } - /** {@inheritDoc} */ - public synchronized boolean isHostUnavailable(URL url) - { - if (this.offlineMode) + /** + * {@inheritDoc} + */ + public synchronized boolean isHostUnavailable(URL url) { + if (this.offlineMode) { return true; + } - if (url == null) - { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -252,11 +253,11 @@ public synchronized boolean isHostUnavailable(URL url) String hostName = url.getHost(); HostInfo hi = this.hostMap.get(hostName); - if (hi == null) + if (hi == null) { return false; + } - if (hi.isTimeToTryAgain()) - { + if (hi.isTimeToTryAgain()) { hi.logCount.set(0); // info removed from table in logAvailableHost return false; } @@ -264,21 +265,23 @@ public synchronized boolean isHostUnavailable(URL url) return hi.isUnavailable(); } - /** {@inheritDoc} */ - public boolean isNetworkUnavailable() - { + /** + * {@inheritDoc} + */ + public boolean isNetworkUnavailable() { return this.offlineMode || this.isNetworkUnavailable(10000L); } - /** {@inheritDoc} */ - public synchronized boolean isNetworkUnavailable(long checkInterval) - { - if (this.offlineMode) + /** + * {@inheritDoc} + */ + public synchronized boolean isNetworkUnavailable(long checkInterval) { + if (this.offlineMode) { return true; + } // If there's been success since failure, network assumed to be reachable. - if (this.lastAvailableLogTime.get() > this.lastUnavailableLogTime.get()) - { + if (this.lastAvailableLogTime.get() > this.lastUnavailableLogTime.get()) { this.lastNetworkUnavailableResult.set(false); return this.lastNetworkUnavailableResult.get(); } @@ -286,29 +289,24 @@ public synchronized boolean isNetworkUnavailable(long checkInterval) long now = System.currentTimeMillis(); // If there's been success recently, network assumed to be reachable. - if (!this.lastNetworkUnavailableResult.get() && now - this.lastAvailableLogTime.get() < checkInterval) - { + if (!this.lastNetworkUnavailableResult.get() && now - this.lastAvailableLogTime.get() < checkInterval) { return this.lastNetworkUnavailableResult.get(); } // If query comes too soon after an earlier one that addressed the network, return the earlier result. - if (now - this.lastNetworkCheckTime.get() < checkInterval) - { + if (now - this.lastNetworkCheckTime.get() < checkInterval) { return this.lastNetworkUnavailableResult.get(); } this.lastNetworkCheckTime.set(now); - if (!this.isWorldWindServerUnavailable()) - { + if (!this.isWorldWindServerUnavailable()) { this.lastNetworkUnavailableResult.set(false); // network not unreachable return this.lastNetworkUnavailableResult.get(); } - for (String testHost : networkTestSites) - { - if (isHostReachable(testHost)) - { + for (String testHost : networkTestSites) { + if (isHostReachable(testHost)) { { this.lastNetworkUnavailableResult.set(false); // network not unreachable return this.lastNetworkUnavailableResult.get(); @@ -316,8 +314,7 @@ public synchronized boolean isNetworkUnavailable(long checkInterval) } } - if (now - this.lastNetworkStatusReportTime.get() > NETWORK_STATUS_REPORT_INTERVAL) - { + if (now - this.lastNetworkStatusReportTime.get() > NETWORK_STATUS_REPORT_INTERVAL) { this.lastNetworkStatusReportTime.set(now); String message = Logging.getMessage("NetworkStatus.NetworkUnreachable"); Logging.logger().info(message); @@ -327,37 +324,32 @@ public synchronized boolean isNetworkUnavailable(long checkInterval) return this.lastNetworkUnavailableResult.get(); } - /** {@inheritDoc} */ - public boolean isWorldWindServerUnavailable() - { + /** + * {@inheritDoc} + */ + public boolean isWorldWindServerUnavailable() { return this.offlineMode || !isHostReachable("worldwind.arc.nasa.gov"); } /** - * Determine if a host is reachable by attempting to resolve the host name, and then attempting to open a - * connection using either https or http. + * Determine if a host is reachable by attempting to resolve the host name, and then attempting to open a connection + * using either https or http. * * @param hostName Name of the host to connect to. * * @return {@code true} if a the host is reachable, {@code false} if the host name cannot be resolved, or if opening - * a connection to the host fails. + * a connection to the host fails. */ - protected static boolean isHostReachable(String hostName) - { - try - { + protected static boolean isHostReachable(String hostName) { + try { // Assume host is unreachable if we can't get its dns entry without getting an exception //noinspection ResultOfMethodCallIgnored InetAddress.getByName(hostName); - } - catch (UnknownHostException e) - { + } catch (UnknownHostException e) { String message = Logging.getMessage("NetworkStatus.UnreachableTestHost", hostName); Logging.logger().fine(message); return false; - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("NetworkStatus.ExceptionTestingHost", hostName); Logging.logger().info(message); return false; @@ -365,37 +357,33 @@ protected static boolean isHostReachable(String hostName) // Was able to get internet address, but host still might not be reachable because the address might have been // cached earlier when it was available. So need to try something else. - URLConnection connection = null; - try - { - final String[] protocols = new String[] {"https://", "http://"}; - for (String protocol: protocols) - { + try { + final String[] protocols = new String[]{"https://", "http://"}; + for (String protocol : protocols) { URL url = new URL(protocol + hostName); Proxy proxy = WWIO.configureProxy(); - if (proxy != null) + if (proxy != null) { connection = url.openConnection(proxy); - else + } else { connection = url.openConnection(); + } connection.setConnectTimeout(2000); connection.setReadTimeout(2000); String ct = connection.getContentType(); - if (ct != null) + if (ct != null) { return true; + } } - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("NetworkStatus.ExceptionTestingHost", hostName); Logging.logger().info(message); - } - finally - { - if (connection != null && connection instanceof HttpURLConnection) + } finally { + if (connection != null && connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).disconnect(); + } } return false; diff --git a/src/gov/nasa/worldwind/util/BasicQuadTree.java b/src/gov/nasa/worldwind/util/BasicQuadTree.java index d2a837237d..950c5ea048 100644 --- a/src/gov/nasa/worldwind/util/BasicQuadTree.java +++ b/src/gov/nasa/worldwind/util/BasicQuadTree.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.geom.*; @@ -23,8 +22,8 @@ * @author tag * @version $Id: BasicQuadTree.java 1938 2014-04-15 22:34:52Z tgaskins $ */ -public class BasicQuadTree extends BitSetQuadTreeFilter implements Iterable -{ +public class BasicQuadTree extends BitSetQuadTreeFilter implements Iterable { + protected ArrayList levelZeroCells; protected Map> items; // the tree's list of items protected T currentItem; // used during add() to pass the added item to doOperation(). @@ -42,19 +41,17 @@ public class BasicQuadTree extends BitSetQuadTreeFilter implements IterablenumLevels
                  is less than 1. */ - public BasicQuadTree(int numLevels, Sector sector, Map> itemMap) - { + public BasicQuadTree(int numLevels, Sector sector, Map> itemMap) { super(numLevels, null); - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -73,25 +70,22 @@ public BasicQuadTree(int numLevels, Sector sector, Map> itemMap) * level count of 8 provides leaf cells about 75 km along their meridian edges (edges of constant longitude). * Additional levels successfully halve the distance, fewer levels double that distance. * - * @param numLevels the number of levels in the quadtree. The more levels there are the more discriminating - * searches will be, but at the cost of some performance. - * @param sector the region the tree spans. - * @param itemMap a {@link Map} to hold the items added to the quadtree. May be null, in which case a new - * map is created. + * @param numLevels the number of levels in the quadtree. The more levels there are the more discriminating searches + * will be, but at the cost of some performance. + * @param sector the region the tree spans. + * @param itemMap a {@link Map} to hold the items added to the quadtree. May be null, in which case a new map is + * created. * @param allowDuplicates Indicates whether the collection held by this quadtree may contain duplicate entries. - * Specifying true, which is the default, may cause an individual item to be - * associated with multiple quadtree regions if the item's coordinates fall on a region - * boundary. In this case that item will be returned multiple times from an iterator created - * by this class. Specifying false prevents this. + * Specifying true, which is the default, may cause an individual item to be associated with multiple + * quadtree regions if the item's coordinates fall on a region boundary. In this case that item will be returned + * multiple times from an iterator created by this class. Specifying false prevents this. * * @throws IllegalArgumentException if numLevels is less than 1. */ - public BasicQuadTree(int numLevels, Sector sector, Map> itemMap, boolean allowDuplicates) - { + public BasicQuadTree(int numLevels, Sector sector, Map> itemMap, boolean allowDuplicates) { this(numLevels, sector, itemMap); - if (sector == null) - { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -108,8 +102,7 @@ public BasicQuadTree(int numLevels, Sector sector, Map> itemMap, * * @param sector the sector to subdivide to create the cells. */ - protected void makeLevelZeroCells(Sector sector) - { + protected void makeLevelZeroCells(Sector sector) { Sector[] subSectors = sector.subdivide(); this.levelZeroCells = new ArrayList(4); @@ -125,8 +118,7 @@ protected void makeLevelZeroCells(Sector sector) * * @return true if the tree contains items, otherwise false. */ - synchronized public boolean hasItems() - { + synchronized public boolean hasItems() { return !this.items.isEmpty(); } @@ -137,19 +129,20 @@ synchronized public boolean hasItems() * * @return true if the item is in the tree, otherwise false. */ - synchronized public boolean contains(T item) - { - if (item == null) + synchronized public boolean contains(T item) { + if (item == null) { return false; + } - for (Map.Entry> entry : this.items.entrySet()) - { + for (Map.Entry> entry : this.items.entrySet()) { List itemList = entry.getValue(); - if (itemList == null) + if (itemList == null) { continue; + } - if (itemList.contains(item)) + if (itemList.contains(item)) { return true; + } } return false; @@ -159,45 +152,40 @@ synchronized public boolean contains(T item) * Add a named item to the quadtree. Any item duplicates are duplicated in the tree. Any name duplicates replace the * current name association; the name then refers to the item added. * - * @param item the item to add. + * @param item the item to add. * @param itemCoords an array specifying the region or location of the item. If the array's length is 2 it - * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with - * the same layout as the nodeRegion argument. - * @param itemName the item name. If null, the item is added without a name. + * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with the same layout + * as the nodeRegion argument. + * @param itemName the item name. If null, the item is added without a name. * * @throws IllegalArgumentException if either item or itemCoords is null. */ - synchronized public void add(T item, double[] itemCoords, String itemName) - { + synchronized public void add(T item, double[] itemCoords, String itemName) { this.addItem(item, itemCoords, itemName); } /** * Add an item to the quadtree. Any duplicates are duplicated in the tree. * - * @param item the item to add. + * @param item the item to add. * @param itemCoords an array specifying the region or location of the item. If the array's length is 2 it - * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with - * the same layout as the nodeRegion argument. + * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with the same layout + * as the nodeRegion argument. * * @throws IllegalArgumentException if either item or itemCoords is null. */ - synchronized public void add(T item, double[] itemCoords) - { + synchronized public void add(T item, double[] itemCoords) { this.addItem(item, itemCoords, null); } - protected void addItem(T item, double[] itemCoords, String name) - { - if (item == null) - { + protected void addItem(T item, double[] itemCoords, String name) { + if (item == null) { String message = Logging.getMessage("nullValue.ItemIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (itemCoords == null) - { + if (itemCoords == null) { String message = Logging.getMessage("nullValue.CoordinatesAreNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -208,8 +196,7 @@ protected void addItem(T item, double[] itemCoords, String name) this.start(); - for (int i = 0; i < levelZeroCells.size(); i++) - { + for (int i = 0; i < levelZeroCells.size(); i++) { this.testAndDo(0, i, levelZeroCells.get(i), itemCoords); } } @@ -221,28 +208,29 @@ protected void addItem(T item, double[] itemCoords, String name) * * @param item the item to remove. If null, no item is removed. */ - synchronized public void remove(T item) - { - if (item == null) + synchronized public void remove(T item) { + if (item == null) { return; + } List bitsToClear = new ArrayList(); - for (Map.Entry> entry : this.items.entrySet()) - { + for (Map.Entry> entry : this.items.entrySet()) { List itemList = entry.getValue(); - if (itemList == null) + if (itemList == null) { continue; + } - if (itemList.contains(item)) + if (itemList.contains(item)) { itemList.remove(item); + } - if (itemList.size() == 0) + if (itemList.size() == 0) { bitsToClear.add(entry.getKey()); + } } - for (String bitNum : bitsToClear) - { + for (String bitNum : bitsToClear) { this.bits.clear(Integer.parseInt(bitNum)); } } @@ -254,29 +242,31 @@ synchronized public void remove(T item) * * @param name the name of the item to remove. If null, no item is removed. */ - synchronized public void removeByName(String name) - { + synchronized public void removeByName(String name) { T item = this.getByName(name); this.nameMap.remove(name); - if (item == null) + if (item == null) { return; + } - for (Map.Entry> entry : this.items.entrySet()) - { + for (Map.Entry> entry : this.items.entrySet()) { List itemList = entry.getValue(); - if (itemList == null) + if (itemList == null) { continue; + } - if (itemList.contains(item)) + if (itemList.contains(item)) { itemList.remove(item); + } } } - /** Removes all items from the tree. */ - synchronized public void clear() - { + /** + * Removes all items from the tree. + */ + synchronized public void clear() { this.items.clear(); this.bits.clear(); } @@ -288,8 +278,7 @@ synchronized public void clear() * * @return the named item, or null if the item is not in the tree or the specified name is null. */ - synchronized public T getByName(String name) - { + synchronized public T getByName(String name) { return name != null ? this.nameMap.get(name) : null; } @@ -301,10 +290,8 @@ synchronized public T getByName(String name) * * @return an iterator over the items in the tree. */ - synchronized public Iterator iterator() - { - return new Iterator() - { + synchronized public Iterator iterator() { + return new Iterator() { // The items are stored in lists associated with each cell (each bit of the bit-set), so two internal // iterators are needed: one for the map of populated cells and one for a cell's list of items. private Iterator> mapIterator; @@ -315,24 +302,28 @@ synchronized public Iterator iterator() mapIterator = BasicQuadTree.this.items.values().iterator(); } - /** {@inheritDoc} **/ - public boolean hasNext() - { + /** + * {@inheritDoc} * + */ + public boolean hasNext() { // This is the only method that causes the list to increment, so call it before every call to next(). - if (this.nextItem != null) + if (this.nextItem != null) { return true; + } this.moveToNextItem(); return this.nextItem != null; } - /** {@inheritDoc} **/ - public T next() - { - if (!this.hasNext()) + /** + * {@inheritDoc} * + */ + public T next() { + if (!this.hasNext()) { throw new NoSuchElementException("Iteration has no more elements."); + } T lastNext = this.nextItem; this.nextItem = null; @@ -342,29 +333,25 @@ public T next() /** * This operation is not supported and will produce a {@link UnsupportedOperationException} if invoked. */ - public void remove() - { + public void remove() { throw new UnsupportedOperationException("The remove() operations is not supported by this Iterator."); } - private void moveToNextItem() - { + private void moveToNextItem() { // Use the next item in a cell's item list, if there is an item list and it has a next item. - if (this.listIterator != null && this.listIterator.hasNext()) - { + if (this.listIterator != null && this.listIterator.hasNext()) { this.nextItem = this.listIterator.next(); return; } // Find the next map entry with a non-null item list. Use the first item in that list. this.listIterator = null; - while (this.mapIterator.hasNext()) - { - if (this.mapIterator.hasNext()) + while (this.mapIterator.hasNext()) { + if (this.mapIterator.hasNext()) { this.listIterator = this.mapIterator.next().iterator(); + } - if (this.listIterator != null && this.listIterator.hasNext()) - { + if (this.listIterator != null && this.listIterator.hasNext()) { this.nextItem = this.listIterator.next(); return; } @@ -380,14 +367,12 @@ private void moveToNextItem() * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the outItems argument is returned, or - * a new set if that argument is null. + * a new set if that argument is null. * * @throws IllegalArgumentException if location is null. */ - synchronized public Set getItemsAtLocation(LatLon location, Set outItems) - { - if (location == null) - { + synchronized public Set getItemsAtLocation(LatLon location, Set outItems) { + if (location == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -404,17 +389,15 @@ synchronized public Set getItemsAtLocation(LatLon location, Set outItems) * Finds and returns the items within tree cells containing specified locations. * * @param locations the locations of interest. - * @param outItems a {@link Set} in which to place the items. If null, a new set is created. + * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the outItems argument is returned, or - * a new set if that argument is null. + * a new set if that argument is null. * * @throws IllegalArgumentException if locations is null. */ - synchronized public Set getItemsAtLocation(Iterable locations, Set outItems) - { - if (locations == null) - { + synchronized public Set getItemsAtLocation(Iterable locations, Set outItems) { + if (locations == null) { String message = Logging.getMessage("nullValue.LatLonListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -423,10 +406,10 @@ synchronized public Set getItemsAtLocation(Iterable locations, Set FindIntersectingBitsOp op = new FindIntersectingBitsOp(this); List bitIds = new ArrayList(); - for (LatLon location : locations) - { - if (location != null) + for (LatLon location : locations) { + if (location != null) { bitIds = op.getOnBits(this.levelZeroCells, location.asDegreesArray(), bitIds); + } } return this.buildItemSet(bitIds, outItems); @@ -436,17 +419,15 @@ synchronized public Set getItemsAtLocation(Iterable locations, Set * Finds and returns the items intersecting a specified sector. * * @param testSector the sector of interest. - * @param outItems a {@link Set} in which to place the items. If null, a new set is created. + * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the outItems argument is returned, or - * a new set if that argument is null. + * a new set if that argument is null. * * @throws IllegalArgumentException if testSector is null. */ - synchronized public Set getItemsInRegion(Sector testSector, Set outItems) - { - if (testSector == null) - { + synchronized public Set getItemsInRegion(Sector testSector, Set outItems) { + if (testSector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -463,17 +444,15 @@ synchronized public Set getItemsInRegion(Sector testSector, Set outItems) * Finds and returns the items intersecting a specified collection of sectors. * * @param testSectors the sectors of interest. - * @param outItems a {@link Set} in which to place the items. If null, a new set is created. + * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the outItems argument is returned, or - * a new set if that argument is null. + * a new set if that argument is null. * * @throws IllegalArgumentException if testSectors is null. */ - public Set getItemsInRegions(Iterable testSectors, Set outItems) - { - if (testSectors == null) - { + public Set getItemsInRegions(Iterable testSectors, Set outItems) { + if (testSectors == null) { String message = Logging.getMessage("nullValue.SectorListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -482,31 +461,30 @@ public Set getItemsInRegions(Iterable testSectors, Set outItems) FindIntersectingBitsOp op = new FindIntersectingBitsOp(this); List bitIds = new ArrayList(); - for (Sector testSector : testSectors) - { - if (testSector != null) + for (Sector testSector : testSectors) { + if (testSector != null) { bitIds = op.getOnBits(this.levelZeroCells, testSector, bitIds); + } } return this.buildItemSet(bitIds, outItems); } /** - * Finds and returns the items intersecting a specified collection of {@link gov.nasa.worldwind.terrain.SectorGeometry}. - * This method is a convenience for finding the items intersecting the current visible regions. + * Finds and returns the items intersecting a specified collection of + * {@link gov.nasa.worldwind.terrain.SectorGeometry}. This method is a convenience for finding the items + * intersecting the current visible regions. * * @param geometryList the list of sector geometry. - * @param outItems a {@link Set} in which to place the items. If null, a new set is created. + * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of intersecting items. The same set passed as the outItems argument is returned, or - * a new set if that argument is null. + * a new set if that argument is null. * * @throws IllegalArgumentException if geometryList is null. */ - synchronized public Set getItemsInRegions(SectorGeometryList geometryList, Set outItems) - { - if (geometryList == null) - { + synchronized public Set getItemsInRegions(SectorGeometryList geometryList, Set outItems) { + if (geometryList == null) { String message = Logging.getMessage("nullValue.SectorGeometryListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -515,10 +493,10 @@ synchronized public Set getItemsInRegions(SectorGeometryList geometryList, Se FindIntersectingBitsOp op = new FindIntersectingBitsOp(this); List bitIds = new ArrayList(); - for (SectorGeometry testSector : geometryList) - { - if (testSector != null) + for (SectorGeometry testSector : geometryList) { + if (testSector != null) { bitIds = op.getOnBits(this.levelZeroCells, testSector.getSector(), bitIds); + } } return this.buildItemSet(bitIds, outItems); @@ -527,27 +505,27 @@ synchronized public Set getItemsInRegions(SectorGeometryList geometryList, Se /** * Adds the items identified by a list of bit IDs to the set returned by the get methods. * - * @param bitIds the bit numbers of the cells containing the items to return. + * @param bitIds the bit numbers of the cells containing the items to return. * @param outItems a {@link Set} in which to place the items. If null, a new set is created. * * @return the set of items. The value passed as the outItems is returned. */ - protected Set buildItemSet(List bitIds, Set outItems) - { - if (outItems == null) + protected Set buildItemSet(List bitIds, Set outItems) { + if (outItems == null) { outItems = new HashSet(); + } - if (bitIds == null) + if (bitIds == null) { return outItems; + } - for (Integer id : bitIds) - { + for (Integer id : bitIds) { List regionItems = this.items.get(id.toString()); - if (regionItems == null) + if (regionItems == null) { continue; + } - for (T item : regionItems) - { + for (T item : regionItems) { outItems.add(item); } } @@ -558,51 +536,51 @@ protected Set buildItemSet(List bitIds, Set outItems) /** * Performs the add operation of the quadtree. * - * @param level the quadtree level currently being traversed. - * @param position the position of the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with 0 - * at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell - * 2 is NE and cell 3 is NW. + * @param level the quadtree level currently being traversed. + * @param position the position of the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with 0 + * at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell 2 is NE and cell 3 + * is NW. * @param cellRegion an array specifying the coordinates of the cell's region. The first two entries are the minimum - * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and - * maximum values on the X axis, (typically longitude). + * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and maximum values on + * the X axis, (typically longitude). * @param itemCoords an array specifying the region or location of the intersecting item. If the array's length is 2 - * it represents a location in [latitude, longitude]. If its length is 4 it represents a region, - * with the same layout as the nodeRegion argument. + * it represents a location in [latitude, longitude]. If its length is 4 it represents a region, with the same + * layout as the nodeRegion argument. * * @return true if traversal should continue to the cell's descendants, false if traversal should not continue to - * the cell's descendants. + * the cell's descendants. */ - protected boolean doOperation(int level, int position, double[] cellRegion, double[] itemCoords) - { + protected boolean doOperation(int level, int position, double[] cellRegion, double[] itemCoords) { int bitNum = this.computeBitPosition(level, position); this.bits.set(bitNum); - if (level < this.maxLevel) + if (level < this.maxLevel) { return true; + } String bitName = Integer.toString(bitNum); List regionItems = this.items.get(bitName); - if (regionItems == null) - { + if (regionItems == null) { regionItems = new ArrayList(); this.items.put(bitName, regionItems); } regionItems.add(this.currentItem); - if (this.currentName != null) + if (this.currentName != null) { this.nameMap.put(this.currentName, this.currentItem); + } - if (!this.allowDuplicates) + if (!this.allowDuplicates) { this.stop(); + } return false; } ////////////////////// ONLY TEST CODE BELOW //////////////////////////////////////////// - // public static void main(String[] args) // { //// basicTest(); @@ -676,7 +654,6 @@ protected boolean doOperation(int level, int position, double[] cellRegion, doub // System.out.println( // "DONE " + filter.bits.cardinality() + " bits set in " + (end - start) / 10 + " milliseconds"); // } - // // // protected static void perfTestFind() diff --git a/src/gov/nasa/worldwind/util/BasicScheduledTaskService.java b/src/gov/nasa/worldwind/util/BasicScheduledTaskService.java index fd5febc56c..fc27b2f89e 100644 --- a/src/gov/nasa/worldwind/util/BasicScheduledTaskService.java +++ b/src/gov/nasa/worldwind/util/BasicScheduledTaskService.java @@ -17,28 +17,37 @@ * @version $Id: BasicScheduledTaskService.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class BasicScheduledTaskService extends WWObjectImpl - implements ScheduledTaskService, Thread.UncaughtExceptionHandler -{ - /** Default thread pool size. */ + implements ScheduledTaskService, Thread.UncaughtExceptionHandler { + + /** + * Default thread pool size. + */ protected static final int DEFAULT_POOL_SIZE = 1; - /** Name assigned to active threads. */ + /** + * Name assigned to active threads. + */ protected static final String RUNNING_THREAD_NAME_PREFIX = Logging.getMessage( - "ThreadedTaskService.RunningThreadNamePrefix"); - /** Name assigned to idle threads. */ + "ThreadedTaskService.RunningThreadNamePrefix"); + /** + * Name assigned to idle threads. + */ protected static final String IDLE_THREAD_NAME_PREFIX = Logging.getMessage( - "ThreadedTaskService.IdleThreadNamePrefix"); + "ThreadedTaskService.IdleThreadNamePrefix"); - /** Tasks currently running. */ + /** + * Tasks currently running. + */ protected ConcurrentLinkedQueue activeTasks; - /** Executor for running tasks. */ + /** + * Executor for running tasks. + */ protected ScheduledTaskExecutor executor; /** * Create a new scheduled task service. The thread pool size is from the WorldWind configuration file property * {@link AVKey#TASK_POOL_SIZE}. */ - public BasicScheduledTaskService() - { + public BasicScheduledTaskService() { Integer poolSize = Configuration.getIntegerValue(AVKey.TASK_POOL_SIZE, DEFAULT_POOL_SIZE); // this.executor runs the tasks, each in their own thread @@ -48,71 +57,63 @@ public BasicScheduledTaskService() this.activeTasks = new ConcurrentLinkedQueue(); } - public void shutdown(boolean immediately) - { - if (immediately) + public void shutdown(boolean immediately) { + if (immediately) { this.executor.shutdownNow(); - else + } else { this.executor.shutdown(); + } this.activeTasks.clear(); } - public void uncaughtException(Thread thread, Throwable throwable) - { + public void uncaughtException(Thread thread, Throwable throwable) { String message = Logging.getMessage("ThreadedTaskService.UncaughtExceptionDuringTask", thread.getName()); Logging.logger().fine(message); Thread.currentThread().getThreadGroup().uncaughtException(thread, throwable); } - /** Custom executor to run tasks. */ - protected class ScheduledTaskExecutor extends ScheduledThreadPoolExecutor - { - protected ScheduledTaskExecutor(int poolSize) - { + /** + * Custom executor to run tasks. + */ + protected class ScheduledTaskExecutor extends ScheduledThreadPoolExecutor { + + protected ScheduledTaskExecutor(int poolSize) { super(poolSize, - new ThreadFactory() - { - public Thread newThread(Runnable runnable) - { - Thread thread = new Thread(runnable); - thread.setDaemon(true); - thread.setPriority(Thread.MIN_PRIORITY); - thread.setUncaughtExceptionHandler(BasicScheduledTaskService.this); - return thread; - } - }, - new DiscardPolicy() - { - public void rejectedExecution(Runnable runnable, ScheduledThreadPoolExecutor threadPoolExecutor) - { - // Interposes logging for rejected execution - String message = Logging.getMessage("ThreadedTaskService.ResourceRejected", runnable); - Logging.logger().fine(message); - super.rejectedExecution(runnable, threadPoolExecutor); - } - }); + new ThreadFactory() { + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable); + thread.setDaemon(true); + thread.setPriority(Thread.MIN_PRIORITY); + thread.setUncaughtExceptionHandler(BasicScheduledTaskService.this); + return thread; + } + }, + new DiscardPolicy() { + public void rejectedExecution(Runnable runnable, ScheduledThreadPoolExecutor threadPoolExecutor) { + // Interposes logging for rejected execution + String message = Logging.getMessage("ThreadedTaskService.ResourceRejected", runnable); + Logging.logger().fine(message); + super.rejectedExecution(runnable, threadPoolExecutor); + } + }); } @Override - protected void beforeExecute(Thread thread, Runnable runnable) - { - if (thread == null) - { + protected void beforeExecute(Thread thread, Runnable runnable) { + if (thread == null) { String msg = Logging.getMessage("nullValue.ThreadIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (runnable == null) - { + if (runnable == null) { String msg = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); } - if (BasicScheduledTaskService.this.activeTasks.contains(runnable)) - { + if (BasicScheduledTaskService.this.activeTasks.contains(runnable)) { // Duplicate requests are simply interrupted here. The task itself must check the thread's isInterrupted // flag and actually terminate the task. String message = Logging.getMessage("ThreadedTaskService.CancellingDuplicateTask", runnable); @@ -123,8 +124,9 @@ protected void beforeExecute(Thread thread, Runnable runnable) BasicScheduledTaskService.this.activeTasks.add(runnable); - if (RUNNING_THREAD_NAME_PREFIX != null) + if (RUNNING_THREAD_NAME_PREFIX != null) { thread.setName(RUNNING_THREAD_NAME_PREFIX + runnable); + } thread.setPriority(Thread.MIN_PRIORITY); thread.setUncaughtExceptionHandler(BasicScheduledTaskService.this); @@ -132,10 +134,8 @@ protected void beforeExecute(Thread thread, Runnable runnable) } @Override - protected void afterExecute(Runnable runnable, Throwable throwable) - { - if (runnable == null) - { + protected void afterExecute(Runnable runnable, Throwable throwable) { + if (runnable == null) { String msg = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(msg); throw new IllegalArgumentException(msg); @@ -145,60 +145,64 @@ protected void afterExecute(Runnable runnable, Throwable throwable) BasicScheduledTaskService.this.activeTasks.remove(runnable); - if (throwable == null && IDLE_THREAD_NAME_PREFIX != null) + if (throwable == null && IDLE_THREAD_NAME_PREFIX != null) { Thread.currentThread().setName(IDLE_THREAD_NAME_PREFIX); + } } } - /** {@inheritDoc} */ - public synchronized void addTask(Runnable runnable) - { - if (runnable == null) - { + /** + * {@inheritDoc} + */ + public synchronized void addTask(Runnable runnable) { + if (runnable == null) { String message = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } // Do not queue duplicates. - if (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)) + if (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)) { return; + } this.executor.execute(runnable); } - /** {@inheritDoc} */ - public synchronized ScheduledFuture addScheduledTask(Runnable runnable, long delay, TimeUnit timeunit) - { - if (runnable == null) - { + /** + * {@inheritDoc} + */ + public synchronized ScheduledFuture addScheduledTask(Runnable runnable, long delay, TimeUnit timeunit) { + if (runnable == null) { String message = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } // Do not queue duplicates. - if (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)) + if (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)) { return null; + } return this.executor.schedule(runnable, delay, timeunit); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ public synchronized ScheduledFuture addRepeatingTask(Runnable runnable, long initialDelay, long period, - TimeUnit timeunit) - { - if (runnable == null) - { + TimeUnit timeunit) { + if (runnable == null) { String message = Logging.getMessage("nullValue.RunnableIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } // Do not queue duplicates. - if (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)) + if (this.activeTasks.contains(runnable) || this.executor.getQueue().contains(runnable)) { return null; + } return this.executor.scheduleAtFixedRate(runnable, initialDelay, period, timeunit); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/BasicTextDecoder.java b/src/gov/nasa/worldwind/util/BasicTextDecoder.java index f994a066de..8b20c6cae8 100644 --- a/src/gov/nasa/worldwind/util/BasicTextDecoder.java +++ b/src/gov/nasa/worldwind/util/BasicTextDecoder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; /** @@ -13,25 +12,26 @@ * @author pabercrombie * @version $Id: BasicTextDecoder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicTextDecoder implements TextDecoder -{ +public class BasicTextDecoder implements TextDecoder { + protected String text; protected String decodedText; protected long lastUpdateTime; - /** {@inheritDoc} */ - public synchronized void setText(String input) - { + /** + * {@inheritDoc} + */ + public synchronized void setText(String input) { this.text = input; this.decodedText = null; this.lastUpdateTime = System.currentTimeMillis(); } - /** {@inheritDoc} */ - public synchronized String getDecodedText() - { - if (this.decodedText == null) - { + /** + * {@inheritDoc} + */ + public synchronized String getDecodedText() { + if (this.decodedText == null) { this.decodedText = this.decode(this.text); this.lastUpdateTime = System.currentTimeMillis(); this.text = null; // Release reference to source text @@ -40,9 +40,10 @@ public synchronized String getDecodedText() return this.decodedText; } - /** {@inheritDoc} */ - public long getLastUpdateTime() - { + /** + * {@inheritDoc} + */ + public long getLastUpdateTime() { return this.lastUpdateTime; } @@ -53,8 +54,7 @@ public long getLastUpdateTime() * * @return Decoded text. */ - protected String decode(String textToDecode) - { + protected String decode(String textToDecode) { return textToDecode; } } diff --git a/src/gov/nasa/worldwind/util/BitSetQuadTreeFilter.java b/src/gov/nasa/worldwind/util/BitSetQuadTreeFilter.java index 1978c4dadc..e501d1d2a4 100644 --- a/src/gov/nasa/worldwind/util/BitSetQuadTreeFilter.java +++ b/src/gov/nasa/worldwind/util/BitSetQuadTreeFilter.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.geom.Sector; @@ -23,8 +22,8 @@ * @author tag * @version $Id: BitSetQuadTreeFilter.java 1939 2014-04-15 22:50:19Z tgaskins $ */ -public abstract class BitSetQuadTreeFilter -{ +public abstract class BitSetQuadTreeFilter { + protected BitSet bits; protected int maxLevel; protected int numLevels; @@ -39,19 +38,19 @@ public abstract class BitSetQuadTreeFilter * identity for later reference. See for example {@link gov.nasa.worldwind.util.BasicQuadTree} and {@link * gov.nasa.worldwind.util.BitSetQuadTreeFilter.FindIntersectingBitsOp}. * - * @param level the quadtree level currently being traversed. - * @param position the position of the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with 0 - * at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell - * 2 is NE and cell 3 is NW. + * @param level the quadtree level currently being traversed. + * @param position the position of the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with 0 + * at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell 2 is NE and cell 3 + * is NW. * @param cellRegion an array specifying the coordinates of the cell's region. The first two entries are the minimum - * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and - * maximum values on the X axis, (typically longitude). + * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and maximum values on + * the X axis, (typically longitude). * @param itemCoords an array specifying the region or location of the intersecting item. If the array's length is 2 - * it represents a location in [latitude, longitude]. If its length is 4 it represents a region, - * with the same layout as the nodeRegion argument. + * it represents a location in [latitude, longitude]. If its length is 4 it represents a region, with the same + * layout as the nodeRegion argument. * * @return true if traversal should continue to the cell's descendants, false if traversal should not continue to - * the cell's descendants. + * the cell's descendants. */ abstract protected boolean doOperation(int level, int position, double[] cellRegion, double[] itemCoords); @@ -59,15 +58,13 @@ public abstract class BitSetQuadTreeFilter * Constructs an instance of this class. * * @param numLevels the number of levels in the quadtree. - * @param bitSet a {@link BitSet} to use as the quadtree index. If null, a new set is created. Depending on the - * operation, the bit-set is modified or only read. + * @param bitSet a {@link BitSet} to use as the quadtree index. If null, a new set is created. Depending on the + * operation, the bit-set is modified or only read. * * @throws IllegalArgumentException if numLevels is less than 1. */ - public BitSetQuadTreeFilter(int numLevels, BitSet bitSet) - { - if (numLevels < 1) - { + public BitSetQuadTreeFilter(int numLevels, BitSet bitSet) { + if (numLevels < 1) { String message = Logging.getMessage("generic.DepthOutOfRange", numLevels); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -88,8 +85,7 @@ public BitSetQuadTreeFilter(int numLevels, BitSet bitSet) * * @return the number of levels in the filter. */ - public int getNumLevels() - { + public int getNumLevels() { return this.numLevels; } @@ -97,8 +93,7 @@ public int getNumLevels() * Stop the current traversal of the quadtree. {@link #start()} must be called before attempting a subsequent * traversal. */ - public void stop() - { + public void stop() { this.stopped = true; } @@ -107,8 +102,7 @@ public void stop() * * @return true if traversal has been stopped, otherwise false. */ - public boolean isStopped() - { + public boolean isStopped() { return stopped; } @@ -116,8 +110,7 @@ public boolean isStopped() * Re-initialize for traversal. Must be called to perform subsequent traversals after having called {@link * #stop()}. */ - public void start() - { + public void start() { this.stopped = false; } @@ -128,17 +121,15 @@ public void start() * @param numLevels the number of quadtree levels. * * @return an array of numLevels + 1 elements containing the sums of ancestor-level cell counts for - * each quadtree level. The last element in the array contains the total number of cells in the tree. + * each quadtree level. The last element in the array contains the total number of cells in the tree. */ - protected static int[] computeLevelSizes(int numLevels) - { + protected static int[] computeLevelSizes(int numLevels) { int[] sizes = new int[numLevels + 1]; sizes[0] = 0; double accumulatedSize = 0; - for (int i = 1; i <= numLevels; i++) - { + for (int i = 1; i <= numLevels; i++) { accumulatedSize += Math.pow(4, i); sizes[i] = (int) accumulatedSize; } @@ -151,32 +142,35 @@ protected static int[] computeLevelSizes(int numLevels) * subdivides cells and continues depth-first traversal on those descendants. Terminates traversal when the end of * the tree is reached or when the subclass's {@link #doOperation} method returns false. * - * @param level the quadtree level currently being traversed. - * @param position the position o f the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with - * 0 at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, - * cell 2 is NE and cell 3 is NW. + * @param level the quadtree level currently being traversed. + * @param position the position o f the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with 0 + * at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell 2 is NE and cell 3 + * is NW. * @param cellRegion an array specifying the coordinates of the cell's region. The first two entries are the minimum - * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and - * maximum values on the X axis, (typically longitude). + * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and maximum values on + * the X axis, (typically longitude). * @param itemCoords an array specifying the region or location of the item. If the array's length is 2 it - * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with - * the same layout as the nodeRegion argument. + * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with the same layout + * as the nodeRegion argument. */ - protected void testAndDo(int level, int position, double[] cellRegion, double[] itemCoords) - { - if (this.stopped) + protected void testAndDo(int level, int position, double[] cellRegion, double[] itemCoords) { + if (this.stopped) { return; + } - if (this.intersects(cellRegion, itemCoords) == 0) + if (this.intersects(cellRegion, itemCoords) == 0) { return; + } this.path[level] = position; - if (!this.doOperation(level, position, cellRegion, itemCoords) || this.stopped) + if (!this.doOperation(level, position, cellRegion, itemCoords) || this.stopped) { return; + } - if (level == this.maxLevel) + if (level == this.maxLevel) { return; + } double latMid = (cellRegion[1] + cellRegion[0]) / 2; double lonMid = (cellRegion[3] + cellRegion[2]) / 2; @@ -188,20 +182,23 @@ protected void testAndDo(int level, int position, double[] cellRegion, double[] subRegion[2] = cellRegion[2]; subRegion[3] = lonMid; this.testAndDo(level + 1, 0, subRegion, itemCoords); - if (this.stopped) + if (this.stopped) { return; + } subRegion[2] = lonMid; subRegion[3] = cellRegion[3]; this.testAndDo(level + 1, 1, subRegion, itemCoords); - if (this.stopped) + if (this.stopped) { return; + } subRegion[0] = latMid; subRegion[1] = cellRegion[1]; this.testAndDo(level + 1, 2, subRegion, itemCoords); - if (this.stopped) + if (this.stopped) { return; + } subRegion[2] = cellRegion[2]; subRegion[3] = lonMid; @@ -212,41 +209,41 @@ protected void testAndDo(int level, int position, double[] cellRegion, double[] * Determines whether an item intersects a cell. * * @param cellRegion an array specifying the coordinates of the cell's region. The first two entries are the minimum - * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and - * maximum values on the X axis, (typically longitude). + * and maximum values on the Y axis (typically latitude). The last two entries are the minimum and maximum values on + * the X axis, (typically longitude). * @param itemCoords an array specifying the region or location of the item. If the array's length is 2 it - * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with - * the same layout as the nodeRegion argument. + * represents a location in [latitude, longitude]. If its length is 4 it represents a region, with the same layout + * as the nodeRegion argument. * * @return non-zero if the item intersects the region. 0 if no intersection. */ - protected int intersects(double[] cellRegion, double[] itemCoords) - { + protected int intersects(double[] cellRegion, double[] itemCoords) { if (itemCoords.length == 4) // treat test region as a sector + { return !(itemCoords[1] < cellRegion[0] || itemCoords[0] > cellRegion[1] - || itemCoords[3] < cellRegion[2] || itemCoords[2] > cellRegion[3]) ? 1 : 0; - else // assume test region is a 2-tuple location + || itemCoords[3] < cellRegion[2] || itemCoords[2] > cellRegion[3]) ? 1 : 0; + } else // assume test region is a 2-tuple location + { return itemCoords[0] >= cellRegion[0] && itemCoords[0] <= cellRegion[1] - && itemCoords[1] >= cellRegion[2] && itemCoords[1] <= cellRegion[3] ? 1 : 0; + && itemCoords[1] >= cellRegion[2] && itemCoords[1] <= cellRegion[3] ? 1 : 0; + } } /** * Computes the bit position of a quadtree cell. * - * @param level the quadtree level currently being traversed. + * @param level the quadtree level currently being traversed. * @param position the position of the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with 0 - * at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell 2 - * is NE and cell 3 is NW. + * at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell 2 is NE and cell 3 + * is NW. * * @return the cell's bit position in the class' bit-list. */ - protected int computeBitPosition(int level, int position) - { + protected int computeBitPosition(int level, int position) { int bitPosition = position; // Compute the index of the position within the level - for (int i = 0; i < level; i++) - { + for (int i = 0; i < level; i++) { bitPosition += this.path[i] * this.powersOf4[level - i]; } @@ -259,24 +256,22 @@ protected int computeBitPosition(int level, int position) * region. Typically used to traverse the bit-set index of a populated quadtree to determine potentially visible * items. *

                  - * This class requires a previously populated filter and determines which of its cells intersect a specified - * sector. + * This class requires a previously populated filter and determines which of its cells intersect a specified sector. */ - public static class FindIntersectingBitsOp extends BitSetQuadTreeFilter - { + public static class FindIntersectingBitsOp extends BitSetQuadTreeFilter { + protected List intersectingBits; /** * Constructs a filter instance. * * @param filter a filter identifying significant cells in a quadtree, typically produced by applying a filter - * that identifies quadtree cells associated with items. + * that identifies quadtree cells associated with items. * - * @throws NullPointerException if filter is null. + * @throws NullPointerException if filter is null. * @throws IllegalArgumentException if filter is invalid. */ - public FindIntersectingBitsOp(BitSetQuadTreeFilter filter) - { + public FindIntersectingBitsOp(BitSetQuadTreeFilter filter) { super(filter.getNumLevels(), filter.bits); } @@ -286,19 +281,16 @@ public FindIntersectingBitsOp(BitSetQuadTreeFilter filter) * * @param topRegions the zeroth-level regions of a quadtree. * @param testSector the sector of interest. Significant cells that intersect this sector are returned. - * @param outIds a list in which to place the bit positions of intersecting significant cells. May be null, - * in which case a new list is created. In either case the list is the return value of the - * method. + * @param outIds a list in which to place the bit positions of intersecting significant cells. May be null, in + * which case a new list is created. In either case the list is the return value of the method. * * @return the bit positions of intersecting significant cells. This is the list specified as the non-null - * outIds argument, or a new list if that argument is null. + * outIds argument, or a new list if that argument is null. * * @throws IllegalArgumentException if either topRegions or testSector is null. */ - public List getOnBits(List topRegions, Sector testSector, List outIds) - { - if (testSector == null) - { + public List getOnBits(List topRegions, Sector testSector, List outIds) { + if (testSector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -313,28 +305,24 @@ public List getOnBits(List topRegions, Sector testSector, Lis * * @param topRegions the zeroth-level regions of a quadtree. * @param testRegion the sector of interest, specified as a four-element array containing minimum latitude, - * maximum latitude, minimum longitude and maximum longitude, in that order. Significant cells - * that intersect this sector are returned. - * @param outIds a list in which to place the bit positions of intersecting significant cells. May be null, - * in which case a new list is created. In either case the list is the return value of the - * method. + * maximum latitude, minimum longitude and maximum longitude, in that order. Significant cells that intersect + * this sector are returned. + * @param outIds a list in which to place the bit positions of intersecting significant cells. May be null, in + * which case a new list is created. In either case the list is the return value of the method. * * @return the bit positions of intersecting significant cells. This is the list specified as the non-null - * outIds argument, or a new list if that argument is null. + * outIds argument, or a new list if that argument is null. * * @throws IllegalArgumentException if either topRegions or testSector is null. */ - public List getOnBits(List topRegions, double[] testRegion, List outIds) - { - if (topRegions == null) - { + public List getOnBits(List topRegions, double[] testRegion, List outIds) { + if (topRegions == null) { String message = Logging.getMessage("generic.DepthOutOfRange", numLevels); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (testRegion == null) - { + if (testRegion == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -342,8 +330,7 @@ public List getOnBits(List topRegions, double[] testRegion, L this.intersectingBits = outIds != null ? outIds : new ArrayList(); - for (int i = 0; i < topRegions.size(); i++) - { + for (int i = 0; i < topRegions.size(); i++) { this.testAndDo(0, i, topRegions.get(i), testRegion); } @@ -355,29 +342,30 @@ public List getOnBits(List topRegions, double[] testRegion, L * BitSetQuadTreeFilter#doOperation(int, int, double[], double[])}. See the description of that method for * further detail. * - * @param level the quadtree level currently being traversed. - * @param position the position of the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts - * with 0 at the southwest corner of the parent cell and increment counter-clockwise: cell 1 - * is SE, cell 2 is NE and cell 3 is NW. + * @param level the quadtree level currently being traversed. + * @param position the position of the cell in its parent cell, either 0, 1, 2, or 3. Cell positions starts with + * 0 at the southwest corner of the parent cell and increment counter-clockwise: cell 1 is SE, cell 2 is NE and + * cell 3 is NW. * @param cellRegion an array specifying the coordinates of the cell's region. The first two entries are the - * minimum and maximum values on the Y axis (typically latitude). The last two entries are the - * minimum and maximum values on the X axis, (typically longitude). + * minimum and maximum values on the Y axis (typically latitude). The last two entries are the minimum and + * maximum values on the X axis, (typically longitude). * @param testSector an array specifying the region or location of the intersecting item. If the array's length - * is 2 then it represents a location in [latitude, longitude]. If its length is 4 it - * represents a region, with the same layout as the nodeRegion argument. + * is 2 then it represents a location in [latitude, longitude]. If its length is 4 it represents a region, with + * the same layout as the nodeRegion argument. * * @return true if traversal should continue to the cell's descendants, false if traversal should not continue - * to the cell's descendants. + * to the cell's descendants. */ - protected boolean doOperation(int level, int position, double[] cellRegion, double[] testSector) - { + protected boolean doOperation(int level, int position, double[] cellRegion, double[] testSector) { int bitNum = this.computeBitPosition(level, position); - if (!this.bits.get(bitNum)) + if (!this.bits.get(bitNum)) { return false; + } - if (level < this.maxLevel) + if (level < this.maxLevel) { return true; + } this.intersectingBits.add(bitNum); diff --git a/src/gov/nasa/worldwind/util/BoundedHashMap.java b/src/gov/nasa/worldwind/util/BoundedHashMap.java index de6a8c5dc6..3c3be6f981 100644 --- a/src/gov/nasa/worldwind/util/BoundedHashMap.java +++ b/src/gov/nasa/worldwind/util/BoundedHashMap.java @@ -7,18 +7,19 @@ /** * BoundedHashMap is a map with a fixed capacity. When the map's size exceeds its capacity, it automatically removes - * elements until its size is equal to its capacity.

                  BoundedHashMap can operate in two ordering modes: insertion - * order and access order. The mode specified which entries are automatically removed when the map is over capacity. In - * insertion order mode the map removes the eldest entry (the first entry added). In access order mode, the map - * automatically removes the least recently used entry. + * elements until its size is equal to its capacity. + *

                  + * BoundedHashMap can operate in two ordering modes: insertion order and access order. The mode specified which entries + * are automatically removed when the map is over capacity. In insertion order mode the map removes the eldest entry + * (the first entry added). In access order mode, the map automatically removes the least recently used entry. * * @author dcollins * @version $Id: BoundedHashMap.java 1171 2013-02-11 21:45:02Z dcollins $ * @param The map key type. * @param The map value type. */ -public class BoundedHashMap extends java.util.LinkedHashMap -{ +public class BoundedHashMap extends java.util.LinkedHashMap { + protected static final int DEFAULT_CAPACITY = 16; protected static final float DEFAULT_LOAD_FACTOR = 0.75f; @@ -27,11 +28,10 @@ public class BoundedHashMap extends java.util.LinkedHashMap /** * Creates a BoundedHashMap with a specified maximum capacity and ordering mode. * - * @param capacity the maximum number of entries in the map. + * @param capacity the maximum number of entries in the map. * @param accessOrder the ordering mode: true specifies access order, false specifies insertion order. */ - public BoundedHashMap(int capacity, boolean accessOrder) - { + public BoundedHashMap(int capacity, boolean accessOrder) { super(getInitialCapacity(capacity, DEFAULT_LOAD_FACTOR), DEFAULT_LOAD_FACTOR, accessOrder); this.capacity = capacity; } @@ -41,14 +41,14 @@ public BoundedHashMap(int capacity, boolean accessOrder) * * @param capacity the maximum number of entries in the map. */ - public BoundedHashMap(int capacity) - { + public BoundedHashMap(int capacity) { this(capacity, false); } - /** Creates a BoundedHashMap with a capacity of 16, in insertion order mode. */ - public BoundedHashMap() - { + /** + * Creates a BoundedHashMap with a capacity of 16, in insertion order mode. + */ + public BoundedHashMap() { this(DEFAULT_CAPACITY); } @@ -57,8 +57,7 @@ public BoundedHashMap() * * @return maximum number of entries in the map. */ - public int getCapacity() - { + public int getCapacity() { return this.capacity; } @@ -68,19 +67,16 @@ public int getCapacity() * * @param capacity maximum number of entries in the map. */ - public void setCapacity(int capacity) - { + public void setCapacity(int capacity) { this.capacity = capacity; this.removeOverCapacityEntries(); } - protected static int getInitialCapacity(int capacity, float loadFactor) - { + protected static int getInitialCapacity(int capacity, float loadFactor) { return WWMath.powerOfTwoCeiling((int) Math.ceil(capacity / loadFactor)); } - protected boolean removeEldestEntry(java.util.Map.Entry eldest) - { + protected boolean removeEldestEntry(java.util.Map.Entry eldest) { return this.size() > this.getCapacity(); } @@ -90,15 +86,14 @@ protected boolean removeEldestEntry(java.util.Map.Entry eldest) * correspond to changes in the map. We use the iterator's remove() method because we're removing elements from the * entry set as we iterate over them. */ - protected void removeOverCapacityEntries() - { + protected void removeOverCapacityEntries() { int count = this.size() - this.getCapacity(); - if (count <= 0) + if (count <= 0) { return; + } java.util.Iterator> iter = this.entrySet().iterator(); - for (int i = 0; i < count && iter.hasNext(); i++) - { + for (int i = 0; i < count && iter.hasNext(); i++) { iter.next(); iter.remove(); } diff --git a/src/gov/nasa/worldwind/util/BrowserOpener.java b/src/gov/nasa/worldwind/util/BrowserOpener.java index 2fff917ccc..d8ec61bc32 100644 --- a/src/gov/nasa/worldwind/util/BrowserOpener.java +++ b/src/gov/nasa/worldwind/util/BrowserOpener.java @@ -14,57 +14,53 @@ * @author dcollins * @version $Id: BrowserOpener.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BrowserOpener -{ - public static void browse(URL url) throws Exception - { - if (url == null) - { +public class BrowserOpener { + + public static void browse(URL url) throws Exception { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { String urlString = url.toString(); - if (Configuration.isMacOS()) + if (Configuration.isMacOS()) { browseMacOS(urlString); - else if (Configuration.isWindowsOS()) + } else if (Configuration.isWindowsOS()) { browseWindows(urlString); - else if (Configuration.isUnixOS() || Configuration.isLinuxOS()) + } else if (Configuration.isUnixOS() || Configuration.isLinuxOS()) { browseUnix(urlString); - } - catch (Exception e) - { + } + } catch (Exception e) { throw new Exception(String.format("Cannot browse URL %s", url), e); } } - private static void browseMacOS(String urlString) throws Exception - { + private static void browseMacOS(String urlString) throws Exception { Class fileManager = Class.forName("com.apple.eio.FileManager"); Method openURL = fileManager.getDeclaredMethod("openURL", String.class); openURL.invoke(null, urlString); } - private static void browseWindows(String urlString) throws Exception - { + private static void browseWindows(String urlString) throws Exception { Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlString); } - private static void browseUnix(String urlString) throws Exception - { + private static void browseUnix(String urlString) throws Exception { String browser = null; String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"}; - for (String curBrowser : browsers) - if (Runtime.getRuntime().exec(new String[] {"which", curBrowser}).waitFor() == 0) + for (String curBrowser : browsers) { + if (Runtime.getRuntime().exec(new String[]{"which", curBrowser}).waitFor() == 0) { browser = curBrowser; + } + } - if (browser == null) + if (browser == null) { throw new Exception("Cannot find browser"); + } - Runtime.getRuntime().exec(new String[] {browser, urlString}); + Runtime.getRuntime().exec(new String[]{browser, urlString}); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/BufferFactory.java b/src/gov/nasa/worldwind/util/BufferFactory.java index 59149288f5..526290c5a6 100644 --- a/src/gov/nasa/worldwind/util/BufferFactory.java +++ b/src/gov/nasa/worldwind/util/BufferFactory.java @@ -14,24 +14,24 @@ * BufferFactory is itself abstract and defines the factory interface. It defines several implementations as static * inner classes, which serve the most common data types: {@link gov.nasa.worldwind.util.BufferFactory.ByteBufferFactory}, * {@link gov.nasa.worldwind.util.BufferFactory.ShortBufferFactory}, {@link gov.nasa.worldwind.util.BufferFactory.IntBufferFactory}, - * {@link gov.nasa.worldwind.util.BufferFactory.FloatBufferFactory}, and {@link gov.nasa.worldwind.util.BufferFactory.DoubleBufferFactory}. + * {@link gov.nasa.worldwind.util.BufferFactory.FloatBufferFactory}, and + * {@link gov.nasa.worldwind.util.BufferFactory.DoubleBufferFactory}. * * @author dcollins * @version $Id: BufferFactory.java 1171 2013-02-11 21:45:02Z dcollins $ * @see BufferWrapper */ -public abstract class BufferFactory -{ +public abstract class BufferFactory { + private final boolean allocateDirect; /** * Constructs a new BufferFactory with the specified buffer allocation policy. * * @param allocateDirect true to allocate and return BufferWrappers backed by direct buffers, false to allocate and - * return BufferWrappers backed by non-direct buffers. + * return BufferWrappers backed by non-direct buffers. */ - protected BufferFactory(boolean allocateDirect) - { + protected BufferFactory(boolean allocateDirect) { this.allocateDirect = allocateDirect; } @@ -39,17 +39,15 @@ protected BufferFactory(boolean allocateDirect) * Constructs a new BufferFactory with the default buffer allocation policy. This factory allocates and returns * BufferWrappers backed by direct buffers. */ - protected BufferFactory() - { + protected BufferFactory() { this(true); } /** * @return true if this factory allocates and returns BufferWrappers backed by direct buffers, and false if it - * allocates and return BufferWrappers backed by non-direct buffers. + * allocates and return BufferWrappers backed by non-direct buffers. */ - public boolean isAllocateDirect() - { + public boolean isAllocateDirect() { return this.allocateDirect; } @@ -57,7 +55,7 @@ public boolean isAllocateDirect() * Constructs a new BufferWrapper of the specified size. * * @param size the new buffer's size, in number of underlying data type units (bytes, shorts, ints, floats, or - * doubles). + * doubles). * * @return the new buffer. * @@ -65,17 +63,19 @@ public boolean isAllocateDirect() */ public abstract BufferWrapper newBuffer(int size); - /** Implementation of BufferFactory which constructs instances of {@link gov.nasa.worldwind.util.BufferWrapper.ByteBufferWrapper} */ - public static class ByteBufferFactory extends BufferFactory - { + /** + * Implementation of BufferFactory which constructs instances of + * {@link gov.nasa.worldwind.util.BufferWrapper.ByteBufferWrapper} + */ + public static class ByteBufferFactory extends BufferFactory { + /** * Constructs a new ByteBufferFactory with the specified buffer allocation policy. * * @param allocateDirect true to allocate and return ByteBufferWrappers backed by direct buffers, false to - * allocate and return ByteufferWrappers backed by non-direct buffers. + * allocate and return ByteufferWrappers backed by non-direct buffers. */ - public ByteBufferFactory(boolean allocateDirect) - { + public ByteBufferFactory(boolean allocateDirect) { super(allocateDirect); } @@ -83,8 +83,7 @@ public ByteBufferFactory(boolean allocateDirect) * Constructs a new ByteBufferFactory with the default buffer allocation policy. This factory allocates and * returns ByteBufferWrappers backed by direct buffers. */ - public ByteBufferFactory() - { + public ByteBufferFactory() { } /** @@ -96,10 +95,8 @@ public ByteBufferFactory() * * @throws IllegalArgumentException if size is negative. */ - public BufferWrapper newBuffer(int size) - { - if (size < 0) - { + public BufferWrapper newBuffer(int size) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -109,17 +106,19 @@ public BufferWrapper newBuffer(int size) } } - /** Implementation of BufferFactory which constructs instances of {@link gov.nasa.worldwind.util.BufferWrapper.ShortBufferWrapper} */ - public static class ShortBufferFactory extends BufferFactory - { + /** + * Implementation of BufferFactory which constructs instances of + * {@link gov.nasa.worldwind.util.BufferWrapper.ShortBufferWrapper} + */ + public static class ShortBufferFactory extends BufferFactory { + /** * Constructs a new ShortBufferFactory with the specified buffer allocation policy. * * @param allocateDirect true to allocate and return ShortBufferWrappers backed by direct buffers, false to - * allocate and return ShortBufferWrappers backed by non-direct buffers. + * allocate and return ShortBufferWrappers backed by non-direct buffers. */ - public ShortBufferFactory(boolean allocateDirect) - { + public ShortBufferFactory(boolean allocateDirect) { super(allocateDirect); } @@ -127,8 +126,7 @@ public ShortBufferFactory(boolean allocateDirect) * Constructs a new ShortBufferFactory with the default buffer allocation policy. This factory allocates and * returns ShortBufferWrappers backed by direct buffers. */ - public ShortBufferFactory() - { + public ShortBufferFactory() { } /** @@ -140,10 +138,8 @@ public ShortBufferFactory() * * @throws IllegalArgumentException if size is negative. */ - public BufferWrapper newBuffer(int size) - { - if (size < 0) - { + public BufferWrapper newBuffer(int size) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -153,17 +149,19 @@ public BufferWrapper newBuffer(int size) } } - /** Implementation of BufferFactory which constructs instances of {@link gov.nasa.worldwind.util.BufferWrapper.IntBufferWrapper} */ - public static class IntBufferFactory extends BufferFactory - { + /** + * Implementation of BufferFactory which constructs instances of + * {@link gov.nasa.worldwind.util.BufferWrapper.IntBufferWrapper} + */ + public static class IntBufferFactory extends BufferFactory { + /** * Constructs a new IntBufferFactory with the specified buffer allocation policy. * * @param allocateDirect true to allocate and return IntBufferWrappers backed by direct buffers, false to - * allocate and return IntBufferWrappers backed by non-direct buffers. + * allocate and return IntBufferWrappers backed by non-direct buffers. */ - public IntBufferFactory(boolean allocateDirect) - { + public IntBufferFactory(boolean allocateDirect) { super(allocateDirect); } @@ -171,8 +169,7 @@ public IntBufferFactory(boolean allocateDirect) * Constructs a new IntBufferFactory with the default buffer allocation policy. This factory allocates and * returns IntBufferWrappers backed by direct buffers. */ - public IntBufferFactory() - { + public IntBufferFactory() { } /** @@ -184,10 +181,8 @@ public IntBufferFactory() * * @throws IllegalArgumentException if size is negative. */ - public BufferWrapper newBuffer(int size) - { - if (size < 0) - { + public BufferWrapper newBuffer(int size) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -197,17 +192,19 @@ public BufferWrapper newBuffer(int size) } } - /** Implementation of BufferFactory which constructs instances of {@link gov.nasa.worldwind.util.BufferWrapper.FloatBufferWrapper} */ - public static class FloatBufferFactory extends BufferFactory - { + /** + * Implementation of BufferFactory which constructs instances of + * {@link gov.nasa.worldwind.util.BufferWrapper.FloatBufferWrapper} + */ + public static class FloatBufferFactory extends BufferFactory { + /** * Constructs a new FloatBufferFactory with the specified buffer allocation policy. * * @param allocateDirect true to allocate and return FloatBufferWrappers backed by direct buffers, false to - * allocate and return FloatBufferWrappers backed by non-direct buffers. + * allocate and return FloatBufferWrappers backed by non-direct buffers. */ - public FloatBufferFactory(boolean allocateDirect) - { + public FloatBufferFactory(boolean allocateDirect) { super(allocateDirect); } @@ -215,8 +212,7 @@ public FloatBufferFactory(boolean allocateDirect) * Constructs a new FloatBufferFactory with the default buffer allocation policy. This factory allocates and * returns FloatBufferWrappers backed by direct buffers. */ - public FloatBufferFactory() - { + public FloatBufferFactory() { } /** @@ -228,10 +224,8 @@ public FloatBufferFactory() * * @throws IllegalArgumentException if size is negative. */ - public BufferWrapper newBuffer(int size) - { - if (size < 0) - { + public BufferWrapper newBuffer(int size) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -241,17 +235,19 @@ public BufferWrapper newBuffer(int size) } } - /** Implementation of BufferFactory which constructs instances of {@link gov.nasa.worldwind.util.BufferWrapper.DoubleBufferWrapper} */ - public static class DoubleBufferFactory extends BufferFactory - { + /** + * Implementation of BufferFactory which constructs instances of + * {@link gov.nasa.worldwind.util.BufferWrapper.DoubleBufferWrapper} + */ + public static class DoubleBufferFactory extends BufferFactory { + /** * Constructs a new DoubleBufferFactory with the specified buffer allocation policy. * * @param allocateDirect true to allocate and return DoubleBufferWrappers backed by direct buffers, false to - * allocate and return DoubleBufferWrappers backed by non-direct buffers. + * allocate and return DoubleBufferWrappers backed by non-direct buffers. */ - public DoubleBufferFactory(boolean allocateDirect) - { + public DoubleBufferFactory(boolean allocateDirect) { super(allocateDirect); } @@ -259,8 +255,7 @@ public DoubleBufferFactory(boolean allocateDirect) * Constructs a new DoubleBufferFactory with the default buffer allocation policy. This factory allocates and * returns DoubleBufferWrappers backed by direct buffers. */ - public DoubleBufferFactory() - { + public DoubleBufferFactory() { } /** @@ -272,10 +267,8 @@ public DoubleBufferFactory() * * @throws IllegalArgumentException if size is negative. */ - public BufferWrapper newBuffer(int size) - { - if (size < 0) - { + public BufferWrapper newBuffer(int size) { + if (size < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", size); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/util/BufferWrapper.java b/src/gov/nasa/worldwind/util/BufferWrapper.java index 13238e5832..955d253dfe 100644 --- a/src/gov/nasa/worldwind/util/BufferWrapper.java +++ b/src/gov/nasa/worldwind/util/BufferWrapper.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.avlist.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: BufferWrapper.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class BufferWrapper -{ +public abstract class BufferWrapper { + /** * Returns the length of the buffer, in units of the underlying data type (e.g. bytes, shorts, ints, floats, * doubles). @@ -131,8 +130,8 @@ public abstract class BufferWrapper /** * Returns the sequence of values starting at the specified index and with the specified length, cast to bytes. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to get. */ @@ -142,8 +141,8 @@ public abstract class BufferWrapper * Sets the sequence of values starting at the specified index and with the specified length, as bytes. The bytes * are cast to the underlying data type. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to put. */ @@ -152,8 +151,8 @@ public abstract class BufferWrapper /** * Returns the sequence of values starting at the specified index and with the specified length, cast to shorts. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to get. */ @@ -163,8 +162,8 @@ public abstract class BufferWrapper * Sets the sequence of values starting at the specified index and with the specified length, as ints. The ints are * cast to the underlying data type. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to put. */ @@ -173,8 +172,8 @@ public abstract class BufferWrapper /** * Returns the sequence of values starting at the specified index and with the specified length, cast to ints. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to get. */ @@ -184,8 +183,8 @@ public abstract class BufferWrapper * Sets the sequence of values starting at the specified index and with the specified length, as ints. The ints are * cast to the underlying data type. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to put. */ @@ -194,8 +193,8 @@ public abstract class BufferWrapper /** * Returns the sequence of values starting at the specified index and with the specified length, cast to floats. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to get. */ @@ -205,8 +204,8 @@ public abstract class BufferWrapper * Sets the sequence of values starting at the specified index and with the specified length, as floats. The floats * are cast to the underlying data type. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to put. */ @@ -215,8 +214,8 @@ public abstract class BufferWrapper /** * Returns the sequence of values starting at the specified index and with the specified length, cast to doubles. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to get. */ @@ -226,8 +225,8 @@ public abstract class BufferWrapper * Sets the sequence of values starting at the specified index and with the specified length, as doubles. The * doubles are cast to the underlying data type. * - * @param index the buffer starting index. - * @param array the array. + * @param index the buffer starting index. + * @param array the array. * @param offset the array starting index. * @param length the number of values to put. */ @@ -238,7 +237,7 @@ public abstract class BufferWrapper * specified index, and has the specified length. The two buffers share the same backing store, so changes to this * buffer are reflected in the new buffer, and vice versa. * - * @param index the new buffer's starting index. + * @param index the new buffer's starting index. * @param length the new buffer's length. * * @return a subsequence of this buffer. @@ -249,7 +248,7 @@ public abstract class BufferWrapper * Sets a subsequence of this buffer with the contents of the specified buffer. The subsequence to set starts with * the value at the specified index, and has length equal to the specified buffer's length. * - * @param index the starting index to set. + * @param index the starting index to set. * @param buffer the buffer. */ public abstract void putSubBuffer(int index, BufferWrapper buffer); @@ -258,7 +257,7 @@ public abstract class BufferWrapper * Sets a subsequence of this buffer with the contents of the specified buffer. The subsequence to set starts with * the value at the specified index, and has length equal to the specified length. * - * @param index the starting index to set. + * @param index the starting index to set. * @param buffer the buffer. * @param offset the starting index to get from the buffer. * @param length the number of values to get from the buffer. @@ -289,14 +288,12 @@ public abstract class BufferWrapper //**************************************************************// //******************** Static Utilities **********************// //**************************************************************// - /** * Returns the empty BufferWrapper. The returned BufferWrapper is immutable and has no backing Buffer. * * @return the empty BufferWrapper. */ - public static BufferWrapper emptyBufferWrapper() - { + public static BufferWrapper emptyBufferWrapper() { return EMPTY_BUFFER_WRAPPER; } @@ -307,45 +304,41 @@ public static BufferWrapper emptyBufferWrapper() * current byte ordering should be used. * * @param byteBuffer the buffer to wrap. - * @param dataType the primitive data type stored in the ByteBuffer. - * @param byteOrder the primitive byte ordering of the ByteBuffer, or null to use the ByteBuffer's current - * ordering. + * @param dataType the primitive data type stored in the ByteBuffer. + * @param byteOrder the primitive byte ordering of the ByteBuffer, or null to use the ByteBuffer's current ordering. * * @return a new BufferWrapper backed by the specified byteBuffer. * * @throws IllegalArgumentException if either the byteBuffer or the data type are null. */ - public static BufferWrapper wrap(ByteBuffer byteBuffer, Object dataType, Object byteOrder) - { - if (byteBuffer == null) - { + public static BufferWrapper wrap(ByteBuffer byteBuffer, Object dataType, Object byteOrder) { + if (byteBuffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dataType == null) - { + if (dataType == null) { String message = Logging.getMessage("nullValue.DataTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (byteOrder != null) - { + if (byteOrder != null) { byteBuffer.order(AVKey.LITTLE_ENDIAN.equals(byteOrder) ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN); } - if (AVKey.INT8.equals(dataType)) + if (AVKey.INT8.equals(dataType)) { return new ByteBufferWrapper(byteBuffer.slice()); - else if (AVKey.INT16.equals(dataType)) + } else if (AVKey.INT16.equals(dataType)) { return new ShortBufferWrapper(byteBuffer.asShortBuffer()); - else if (AVKey.INT32.equals(dataType)) + } else if (AVKey.INT32.equals(dataType)) { return new IntBufferWrapper(byteBuffer.asIntBuffer()); - else if (AVKey.FLOAT32.equals(dataType)) + } else if (AVKey.FLOAT32.equals(dataType)) { return new FloatBufferWrapper(byteBuffer.asFloatBuffer()); - else if (AVKey.FLOAT64.equals(dataType)) + } else if (AVKey.FLOAT64.equals(dataType)) { return new DoubleBufferWrapper(byteBuffer.asDoubleBuffer()); + } return null; } @@ -356,23 +349,20 @@ else if (AVKey.FLOAT64.equals(dataType)) * assumes the ByteBuffer's current byte ordering. * * @param byteBuffer the buffer to wrap. - * @param dataType the primitive data type stored in the ByteBuffer. + * @param dataType the primitive data type stored in the ByteBuffer. * * @return a new BufferWrapper backed by the specified byteBuffer. * * @throws IllegalArgumentException if either the byteBuffer or the data type are null. */ - public static BufferWrapper wrap(ByteBuffer byteBuffer, Object dataType) - { - if (byteBuffer == null) - { + public static BufferWrapper wrap(ByteBuffer byteBuffer, Object dataType) { + if (byteBuffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dataType == null) - { + if (dataType == null) { String message = Logging.getMessage("nullValue.DataTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -388,33 +378,29 @@ public static BufferWrapper wrap(ByteBuffer byteBuffer, Object dataType) * ordering. * * @param byteBuffer the buffer to wrap. - * @param params the parameters which describe how to interpret the buffer. + * @param params the parameters which describe how to interpret the buffer. * * @return a new BufferWrapper backed by the specified byteBuffer. * * @throws IllegalArgumentException if either the byteBuffer or the parameters are null, or if AVKey.DATA_TYPE - * parameter is missing. + * parameter is missing. */ - public static BufferWrapper wrap(ByteBuffer byteBuffer, AVList params) - { - if (byteBuffer == null) - { + public static BufferWrapper wrap(ByteBuffer byteBuffer, AVList params) { + if (byteBuffer == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params.getValue(AVKey.DATA_TYPE) == null) - { + if (params.getValue(AVKey.DATA_TYPE) == null) { String message = Logging.getMessage("generic.MissingRequiredParameter", - Logging.getMessage("term.dataType")); + Logging.getMessage("term.dataType")); Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -425,15 +411,12 @@ public static BufferWrapper wrap(ByteBuffer byteBuffer, AVList params) //**************************************************************// //******************** BufferWrapper Implementations *********// //**************************************************************// + public abstract static class AbstractBufferWrapper extends BufferWrapper { - public abstract static class AbstractBufferWrapper extends BufferWrapper - { protected T buffer; - public AbstractBufferWrapper(T buffer) - { - if (buffer == null) - { + public AbstractBufferWrapper(T buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -442,255 +425,212 @@ public AbstractBufferWrapper(T buffer) this.buffer = buffer; } - public int length() - { + public int length() { return this.buffer.remaining(); } - public void getByte(int index, byte[] array, int offset, int length) - { - if (array == null) - { + public void getByte(int index, byte[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doGetByte(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void putByte(int index, byte[] array, int offset, int length) - { - if (array == null) - { + public void putByte(int index, byte[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doPutByte(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void getShort(int index, short[] array, int offset, int length) - { - if (array == null) - { + public void getShort(int index, short[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doGetShort(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void putShort(int index, short[] array, int offset, int length) - { - if (array == null) - { + public void putShort(int index, short[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doPutShort(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void getInt(int index, int[] array, int offset, int length) - { - if (array == null) - { + public void getInt(int index, int[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doGetInt(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void putInt(int index, int[] array, int offset, int length) - { - if (array == null) - { + public void putInt(int index, int[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doPutInt(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void getFloat(int index, float[] array, int offset, int length) - { - if (array == null) - { + public void getFloat(int index, float[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doGetFloat(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void putFloat(int index, float[] array, int offset, int length) - { - if (array == null) - { + public void putFloat(int index, float[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doPutFloat(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void getDouble(int index, double[] array, int offset, int length) - { - if (array == null) - { + public void getDouble(int index, double[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doGetDouble(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public void putDouble(int index, double[] array, int offset, int length) - { - if (array == null) - { + public void putDouble(int index, double[] array, int offset, int length) { + if (array == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } int pos = this.buffer.position(); // Save the buffer's current position. - try - { + try { this.buffer.position(index); this.doPutDouble(array, offset, length); - } - finally - { + } finally { this.buffer.position(pos); // Restore the buffer's previous position. } } - public BufferWrapper getSubBuffer(int index, int length) - { - if (length <= 0) - { + public BufferWrapper getSubBuffer(int index, int length) { + if (length <= 0) { return EMPTY_BUFFER_WRAPPER; } @@ -699,14 +639,11 @@ public BufferWrapper getSubBuffer(int index, int length) // Save the buffer's current limit and position. int lim = this.buffer.limit(); int pos = this.buffer.position(); - try - { + try { this.buffer.limit(index + length); this.buffer.position(index); subBuffer = this.doGetSubBuffer(); - } - finally - { + } finally { // Restore the buffer's previous limit and position. Restore limit first in case the position is greater // than the current limit. this.buffer.limit(lim); @@ -716,10 +653,8 @@ public BufferWrapper getSubBuffer(int index, int length) return subBuffer; } - public void putSubBuffer(int index, BufferWrapper buffer) - { - if (buffer == null) - { + public void putSubBuffer(int index, BufferWrapper buffer) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -728,29 +663,28 @@ public void putSubBuffer(int index, BufferWrapper buffer) this.putSubBuffer(index, buffer, 0, buffer.length()); } - public void putSubBuffer(int index, BufferWrapper buffer, int offset, int length) - { - if (buffer == null) - { + public void putSubBuffer(int index, BufferWrapper buffer, int offset, int length) { + if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (buffer.getBackingBuffer() == this.buffer) - { + if (buffer.getBackingBuffer() == this.buffer) { String message = Logging.getMessage("generic.CannotCopyBufferToSelf"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length <= 0) + if (length <= 0) { return; + } // Attempt to put the specified buffer's contents directly into this buffer. This returns false if the // specified buffer's primitive type is not equivalent to this buffer's primitive type. - if (this.doPutSubBuffer(index, buffer, offset, length)) + if (this.doPutSubBuffer(index, buffer, offset, length)) { return; + } // The specified buffer's primitive type differs from this buffer's type. Use an intermediate double array // to put the sub-buffer content. @@ -759,8 +693,7 @@ public void putSubBuffer(int index, BufferWrapper buffer, int offset, int length this.putDouble(index, array, 0, length); } - public Buffer getBackingBuffer() - { + public Buffer getBackingBuffer() { return this.buffer; } @@ -789,82 +722,66 @@ public Buffer getBackingBuffer() protected abstract boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length); } - public static class ByteBufferWrapper extends BufferWrapper.AbstractBufferWrapper - { - public ByteBufferWrapper(ByteBuffer buffer) - { + public static class ByteBufferWrapper extends BufferWrapper.AbstractBufferWrapper { + + public ByteBufferWrapper(ByteBuffer buffer) { super(buffer); } - public ByteBuffer getBackingByteBuffer() - { + public ByteBuffer getBackingByteBuffer() { return this.buffer; } - public int getGLDataType() - { + public int getGLDataType() { return GL.GL_BYTE; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return this.buffer.capacity(); } - public byte getByte(int index) - { + public byte getByte(int index) { return this.buffer.get(index); } - public void putByte(int index, byte value) - { + public void putByte(int index, byte value) { this.buffer.put(index, value); } - public short getShort(int index) - { + public short getShort(int index) { return this.buffer.get(index); } - public void putShort(int index, short value) - { + public void putShort(int index, short value) { this.buffer.put(index, (byte) value); } - public int getInt(int index) - { + public int getInt(int index) { return this.buffer.get(index); } - public void putInt(int index, int value) - { + public void putInt(int index, int value) { this.buffer.put(index, (byte) value); } - public float getFloat(int index) - { + public float getFloat(int index) { return this.buffer.get(index); } - public void putFloat(int index, float value) - { + public void putFloat(int index, float value) { this.buffer.put(index, (byte) value); } - public double getDouble(int index) - { + public double getDouble(int index) { return this.buffer.get(index); } - public void putDouble(int index, double value) - { + public void putDouble(int index, double value) { this.buffer.put(index, (byte) value); } - public BufferWrapper copyOf(int newSize) - { - if (newSize < this.length()) - { + public BufferWrapper copyOf(int newSize) { + if (newSize < this.length()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -874,128 +791,104 @@ public BufferWrapper copyOf(int newSize) return new ByteBufferWrapper(thatBuffer); } - protected void doGetByte(byte[] array, int offset, int length) - { + protected void doGetByte(byte[] array, int offset, int length) { this.buffer.get(array, offset, length); } - protected void doPutByte(byte[] array, int offset, int length) - { + protected void doPutByte(byte[] array, int offset, int length) { this.buffer.put(array, offset, length); } - protected void doGetShort(short[] array, int offset, int length) - { + protected void doGetShort(short[] array, int offset, int length) { byte[] tmp = new byte[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutShort(short[] array, int offset, int length) - { + protected void doPutShort(short[] array, int offset, int length) { byte[] tmp = new byte[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (byte) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetInt(int[] array, int offset, int length) - { + protected void doGetInt(int[] array, int offset, int length) { byte[] tmp = new byte[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutInt(int[] array, int offset, int length) - { + protected void doPutInt(int[] array, int offset, int length) { byte[] tmp = new byte[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (byte) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetFloat(float[] array, int offset, int length) - { + protected void doGetFloat(float[] array, int offset, int length) { byte[] tmp = new byte[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutFloat(float[] array, int offset, int length) - { + protected void doPutFloat(float[] array, int offset, int length) { byte[] tmp = new byte[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (byte) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetDouble(double[] array, int offset, int length) - { + protected void doGetDouble(double[] array, int offset, int length) { byte[] tmp = new byte[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutDouble(double[] array, int offset, int length) - { + protected void doPutDouble(double[] array, int offset, int length) { byte[] tmp = new byte[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (byte) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected BufferWrapper doGetSubBuffer() - { + protected BufferWrapper doGetSubBuffer() { return new ByteBufferWrapper(this.buffer.slice()); } - protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) - { + protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) { Buffer that = buffer.getBackingBuffer(); - if (that instanceof ByteBuffer) - { + if (that instanceof ByteBuffer) { // Save this buffer's current position. int thisPos = this.buffer.position(); // Save the input buffer's current limit and position. int lim = that.limit(); int pos = that.position(); - try - { + try { that.limit(offset + length); that.position(offset); this.buffer.position(index); this.buffer.put((ByteBuffer) that); - } - finally - { + } finally { // Restore this buffer's previous position. this.buffer.position(thisPos); // Restore the input buffer's previous limit and position. Restore limit first in case the position @@ -1010,82 +903,66 @@ protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, in } } - public static class ShortBufferWrapper extends AbstractBufferWrapper - { - public ShortBufferWrapper(ShortBuffer buffer) - { + public static class ShortBufferWrapper extends AbstractBufferWrapper { + + public ShortBufferWrapper(ShortBuffer buffer) { super(buffer); } - public ShortBuffer getBackingShortBuffer() - { + public ShortBuffer getBackingShortBuffer() { return this.buffer; } - public int getGLDataType() - { + public int getGLDataType() { return GL.GL_SHORT; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return WWBufferUtil.SIZEOF_SHORT * this.buffer.capacity(); } - public byte getByte(int index) - { + public byte getByte(int index) { return (byte) this.buffer.get(index); } - public void putByte(int index, byte value) - { + public void putByte(int index, byte value) { this.buffer.put(index, value); } - public short getShort(int index) - { + public short getShort(int index) { return this.buffer.get(index); } - public void putShort(int index, short value) - { + public void putShort(int index, short value) { this.buffer.put(index, value); } - public int getInt(int index) - { + public int getInt(int index) { return this.buffer.get(index); } - public void putInt(int index, int value) - { + public void putInt(int index, int value) { this.buffer.put(index, (short) value); } - public float getFloat(int index) - { + public float getFloat(int index) { return this.buffer.get(index); } - public void putFloat(int index, float value) - { + public void putFloat(int index, float value) { this.buffer.put(index, (short) value); } - public double getDouble(int index) - { + public double getDouble(int index) { return this.buffer.get(index); } - public void putDouble(int index, double value) - { + public void putDouble(int index, double value) { this.buffer.put(index, (short) value); } - public BufferWrapper copyOf(int newSize) - { - if (newSize < this.length()) - { + public BufferWrapper copyOf(int newSize) { + if (newSize < this.length()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1095,128 +972,104 @@ public BufferWrapper copyOf(int newSize) return new ShortBufferWrapper(thatBuffer); } - protected void doGetByte(byte[] array, int offset, int length) - { + protected void doGetByte(byte[] array, int offset, int length) { short[] tmp = new short[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (byte) tmp[i]; } } - protected void doPutByte(byte[] array, int offset, int length) - { + protected void doPutByte(byte[] array, int offset, int length) { short[] tmp = new short[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetShort(short[] array, int offset, int length) - { + protected void doGetShort(short[] array, int offset, int length) { this.buffer.get(array, offset, length); } - protected void doPutShort(short[] array, int offset, int length) - { + protected void doPutShort(short[] array, int offset, int length) { this.buffer.put(array, offset, length); } - protected void doGetInt(int[] array, int offset, int length) - { + protected void doGetInt(int[] array, int offset, int length) { short[] tmp = new short[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutInt(int[] array, int offset, int length) - { + protected void doPutInt(int[] array, int offset, int length) { short[] tmp = new short[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (short) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetFloat(float[] array, int offset, int length) - { + protected void doGetFloat(float[] array, int offset, int length) { short[] tmp = new short[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutFloat(float[] array, int offset, int length) - { + protected void doPutFloat(float[] array, int offset, int length) { short[] tmp = new short[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (short) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetDouble(double[] array, int offset, int length) - { + protected void doGetDouble(double[] array, int offset, int length) { short[] tmp = new short[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutDouble(double[] array, int offset, int length) - { + protected void doPutDouble(double[] array, int offset, int length) { short[] tmp = new short[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (short) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected BufferWrapper doGetSubBuffer() - { + protected BufferWrapper doGetSubBuffer() { return new ShortBufferWrapper(this.buffer.slice()); } - protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) - { + protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) { Buffer that = buffer.getBackingBuffer(); - if (that instanceof ShortBuffer) - { + if (that instanceof ShortBuffer) { // Save this buffer's current position. int thisPos = this.buffer.position(); // Save the input buffer's current limit and position. int lim = that.limit(); int pos = that.position(); - try - { + try { that.limit(offset + length); that.position(offset); this.buffer.position(index); this.buffer.put((ShortBuffer) that); - } - finally - { + } finally { // Restore this buffer's previous position. this.buffer.position(thisPos); // Restore the input buffer's previous limit and position. Restore limit first in case the position @@ -1231,82 +1084,66 @@ protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, in } } - public static class IntBufferWrapper extends AbstractBufferWrapper - { - public IntBufferWrapper(IntBuffer buffer) - { + public static class IntBufferWrapper extends AbstractBufferWrapper { + + public IntBufferWrapper(IntBuffer buffer) { super(buffer); } - public IntBuffer getBackingIntBuffer() - { + public IntBuffer getBackingIntBuffer() { return this.buffer; } - public int getGLDataType() - { + public int getGLDataType() { return GL2.GL_INT; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return WWBufferUtil.SIZEOF_INT * this.buffer.capacity(); } - public byte getByte(int index) - { + public byte getByte(int index) { return (byte) this.buffer.get(index); } - public void putByte(int index, byte value) - { + public void putByte(int index, byte value) { this.buffer.put(index, value); } - public short getShort(int index) - { + public short getShort(int index) { return (short) this.buffer.get(index); } - public void putShort(int index, short value) - { + public void putShort(int index, short value) { this.buffer.put(index, value); } - public int getInt(int index) - { + public int getInt(int index) { return this.buffer.get(index); } - public void putInt(int index, int value) - { + public void putInt(int index, int value) { this.buffer.put(index, value); } - public float getFloat(int index) - { + public float getFloat(int index) { return this.buffer.get(index); } - public void putFloat(int index, float value) - { + public void putFloat(int index, float value) { this.buffer.put(index, (int) value); } - public double getDouble(int index) - { + public double getDouble(int index) { return this.buffer.get(index); } - public void putDouble(int index, double value) - { + public void putDouble(int index, double value) { this.buffer.put(index, (int) value); } - public BufferWrapper copyOf(int newSize) - { - if (newSize < this.length()) - { + public BufferWrapper copyOf(int newSize) { + if (newSize < this.length()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1316,128 +1153,104 @@ public BufferWrapper copyOf(int newSize) return new IntBufferWrapper(thatBuffer); } - protected void doGetByte(byte[] array, int offset, int length) - { + protected void doGetByte(byte[] array, int offset, int length) { int[] tmp = new int[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (byte) tmp[i]; } } - protected void doPutByte(byte[] array, int offset, int length) - { + protected void doPutByte(byte[] array, int offset, int length) { int[] tmp = new int[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetShort(short[] array, int offset, int length) - { + protected void doGetShort(short[] array, int offset, int length) { int[] tmp = new int[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (short) tmp[i]; } } - protected void doPutShort(short[] array, int offset, int length) - { + protected void doPutShort(short[] array, int offset, int length) { int[] tmp = new int[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetInt(int[] array, int offset, int length) - { + protected void doGetInt(int[] array, int offset, int length) { this.buffer.get(array, offset, length); } - protected void doPutInt(int[] array, int offset, int length) - { + protected void doPutInt(int[] array, int offset, int length) { this.buffer.put(array, offset, length); } - protected void doGetFloat(float[] array, int offset, int length) - { + protected void doGetFloat(float[] array, int offset, int length) { int[] tmp = new int[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutFloat(float[] array, int offset, int length) - { + protected void doPutFloat(float[] array, int offset, int length) { int[] tmp = new int[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (int) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetDouble(double[] array, int offset, int length) - { + protected void doGetDouble(double[] array, int offset, int length) { int[] tmp = new int[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutDouble(double[] array, int offset, int length) - { + protected void doPutDouble(double[] array, int offset, int length) { int[] tmp = new int[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (int) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected BufferWrapper doGetSubBuffer() - { + protected BufferWrapper doGetSubBuffer() { return new IntBufferWrapper(this.buffer.slice()); } - protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) - { + protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) { Buffer that = buffer.getBackingBuffer(); - if (that instanceof IntBuffer) - { + if (that instanceof IntBuffer) { // Save this buffer's current position. int thisPos = this.buffer.position(); // Save the input buffer's current limit and position. int lim = that.limit(); int pos = that.position(); - try - { + try { that.limit(offset + length); that.position(offset); this.buffer.position(index); this.buffer.put((IntBuffer) that); - } - finally - { + } finally { // Restore this buffer's previous position. this.buffer.position(thisPos); // Restore the input buffer's previous limit and position. Restore limit first in case the position @@ -1452,82 +1265,66 @@ protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, in } } - public static class FloatBufferWrapper extends AbstractBufferWrapper - { - public FloatBufferWrapper(FloatBuffer buffer) - { + public static class FloatBufferWrapper extends AbstractBufferWrapper { + + public FloatBufferWrapper(FloatBuffer buffer) { super(buffer); } - public FloatBuffer getBackingFloatBuffer() - { + public FloatBuffer getBackingFloatBuffer() { return this.buffer; } - public int getGLDataType() - { + public int getGLDataType() { return GL.GL_FLOAT; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return WWBufferUtil.SIZEOF_FLOAT * this.buffer.capacity(); } - public byte getByte(int index) - { + public byte getByte(int index) { return (byte) this.buffer.get(index); } - public void putByte(int index, byte value) - { + public void putByte(int index, byte value) { this.buffer.put(index, value); } - public short getShort(int index) - { + public short getShort(int index) { return (short) this.buffer.get(index); } - public void putShort(int index, short value) - { + public void putShort(int index, short value) { this.buffer.put(index, value); } - public int getInt(int index) - { + public int getInt(int index) { return (int) this.buffer.get(index); } - public void putInt(int index, int value) - { + public void putInt(int index, int value) { this.buffer.put(index, value); } - public float getFloat(int index) - { + public float getFloat(int index) { return this.buffer.get(index); } - public void putFloat(int index, float value) - { + public void putFloat(int index, float value) { this.buffer.put(index, value); } - public double getDouble(int index) - { + public double getDouble(int index) { return this.buffer.get(index); } - public void putDouble(int index, double value) - { + public void putDouble(int index, double value) { this.buffer.put(index, (float) value); } - public BufferWrapper copyOf(int newSize) - { - if (newSize < this.length()) - { + public BufferWrapper copyOf(int newSize) { + if (newSize < this.length()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1537,128 +1334,104 @@ public BufferWrapper copyOf(int newSize) return new FloatBufferWrapper(thatBuffer); } - protected void doGetByte(byte[] array, int offset, int length) - { + protected void doGetByte(byte[] array, int offset, int length) { float[] tmp = new float[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (byte) tmp[i]; } } - protected void doPutByte(byte[] array, int offset, int length) - { + protected void doPutByte(byte[] array, int offset, int length) { float[] tmp = new float[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetShort(short[] array, int offset, int length) - { + protected void doGetShort(short[] array, int offset, int length) { float[] tmp = new float[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (short) tmp[i]; } } - protected void doPutShort(short[] array, int offset, int length) - { + protected void doPutShort(short[] array, int offset, int length) { float[] tmp = new float[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetInt(int[] array, int offset, int length) - { + protected void doGetInt(int[] array, int offset, int length) { float[] tmp = new float[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (int) tmp[i]; } } - protected void doPutInt(int[] array, int offset, int length) - { + protected void doPutInt(int[] array, int offset, int length) { float[] tmp = new float[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (float) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetFloat(float[] array, int offset, int length) - { + protected void doGetFloat(float[] array, int offset, int length) { this.buffer.get(array, offset, length); } - protected void doPutFloat(float[] array, int offset, int length) - { + protected void doPutFloat(float[] array, int offset, int length) { this.buffer.put(array, offset, length); } - protected void doGetDouble(double[] array, int offset, int length) - { + protected void doGetDouble(double[] array, int offset, int length) { float[] tmp = new float[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = tmp[i]; } } - protected void doPutDouble(double[] array, int offset, int length) - { + protected void doPutDouble(double[] array, int offset, int length) { float[] tmp = new float[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = (float) array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected BufferWrapper doGetSubBuffer() - { + protected BufferWrapper doGetSubBuffer() { return new FloatBufferWrapper(this.buffer.slice()); } - protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) - { + protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) { Buffer that = buffer.getBackingBuffer(); - if (that instanceof FloatBuffer) - { + if (that instanceof FloatBuffer) { // Save this buffer's current position. int thisPos = this.buffer.position(); // Save the input buffer's current limit and position. int lim = that.limit(); int pos = that.position(); - try - { + try { that.limit(offset + length); that.position(offset); this.buffer.position(index); this.buffer.put((FloatBuffer) that); - } - finally - { + } finally { // Restore this buffer's previous position. this.buffer.position(thisPos); // Restore the input buffer's previous limit and position. Restore limit first in case the position @@ -1673,82 +1446,66 @@ protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, in } } - public static class DoubleBufferWrapper extends AbstractBufferWrapper - { - public DoubleBufferWrapper(DoubleBuffer buffer) - { + public static class DoubleBufferWrapper extends AbstractBufferWrapper { + + public DoubleBufferWrapper(DoubleBuffer buffer) { super(buffer); } - public DoubleBuffer getBackingDoubleBuffer() - { + public DoubleBuffer getBackingDoubleBuffer() { return this.buffer; } - public int getGLDataType() - { + public int getGLDataType() { return GL2.GL_DOUBLE; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return WWBufferUtil.SIZEOF_DOUBLE * this.buffer.capacity(); } - public byte getByte(int index) - { + public byte getByte(int index) { return (byte) this.buffer.get(index); } - public void putByte(int index, byte value) - { + public void putByte(int index, byte value) { this.buffer.put(index, value); } - public short getShort(int index) - { + public short getShort(int index) { return (short) this.buffer.get(index); } - public void putShort(int index, short value) - { + public void putShort(int index, short value) { this.buffer.put(index, value); } - public int getInt(int index) - { + public int getInt(int index) { return (int) this.buffer.get(index); } - public void putInt(int index, int value) - { + public void putInt(int index, int value) { this.buffer.put(index, value); } - public float getFloat(int index) - { + public float getFloat(int index) { return (float) this.buffer.get(index); } - public void putFloat(int index, float value) - { + public void putFloat(int index, float value) { this.buffer.put(index, value); } - public double getDouble(int index) - { + public double getDouble(int index) { return this.buffer.get(index); } - public void putDouble(int index, double value) - { + public void putDouble(int index, double value) { this.buffer.put(index, value); } - public BufferWrapper copyOf(int newSize) - { - if (newSize < this.length()) - { + public BufferWrapper copyOf(int newSize) { + if (newSize < this.length()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1758,128 +1515,104 @@ public BufferWrapper copyOf(int newSize) return new DoubleBufferWrapper(thatBuffer); } - protected void doGetByte(byte[] array, int offset, int length) - { + protected void doGetByte(byte[] array, int offset, int length) { double[] tmp = new double[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (byte) tmp[i]; } } - protected void doPutByte(byte[] array, int offset, int length) - { + protected void doPutByte(byte[] array, int offset, int length) { double[] tmp = new double[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetShort(short[] array, int offset, int length) - { + protected void doGetShort(short[] array, int offset, int length) { double[] tmp = new double[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (short) tmp[i]; } } - protected void doPutShort(short[] array, int offset, int length) - { + protected void doPutShort(short[] array, int offset, int length) { double[] tmp = new double[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetInt(int[] array, int offset, int length) - { + protected void doGetInt(int[] array, int offset, int length) { double[] tmp = new double[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (int) tmp[i]; } } - protected void doPutInt(int[] array, int offset, int length) - { + protected void doPutInt(int[] array, int offset, int length) { double[] tmp = new double[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetFloat(float[] array, int offset, int length) - { + protected void doGetFloat(float[] array, int offset, int length) { double[] tmp = new double[length]; this.buffer.get(tmp, 0, length); - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { array[i + offset] = (float) tmp[i]; } } - protected void doPutFloat(float[] array, int offset, int length) - { + protected void doPutFloat(float[] array, int offset, int length) { double[] tmp = new double[length]; - for (int i = 0; i < length; i++) - { + for (int i = 0; i < length; i++) { tmp[i] = array[i + offset]; } this.buffer.put(tmp, 0, length); } - protected void doGetDouble(double[] array, int offset, int length) - { + protected void doGetDouble(double[] array, int offset, int length) { this.buffer.get(array, offset, length); } - protected void doPutDouble(double[] array, int offset, int length) - { + protected void doPutDouble(double[] array, int offset, int length) { this.buffer.put(array, offset, length); } - protected BufferWrapper doGetSubBuffer() - { + protected BufferWrapper doGetSubBuffer() { return new DoubleBufferWrapper(this.buffer.slice()); } - protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) - { + protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, int length) { Buffer that = buffer.getBackingBuffer(); - if (that instanceof DoubleBuffer) - { + if (that instanceof DoubleBuffer) { // Save this buffer's current position. int thisPos = this.buffer.position(); // Save the input buffer's current limit and position. int lim = that.limit(); int pos = that.position(); - try - { + try { that.limit(offset + length); that.position(offset); this.buffer.position(index); this.buffer.put((DoubleBuffer) that); - } - finally - { + } finally { // Restore this buffer's previous position. this.buffer.position(thisPos); // Restore the input buffer's previous limit and position. Restore limit first in case the position @@ -1897,194 +1630,165 @@ protected boolean doPutSubBuffer(int index, BufferWrapper buffer, int offset, in //**************************************************************// //******************** Empty BufferWrapper *******************// //**************************************************************// - protected static final BufferWrapper EMPTY_BUFFER_WRAPPER = new EmptyBufferWrapper(); - protected static class EmptyBufferWrapper extends BufferWrapper - { - public int length() - { + protected static class EmptyBufferWrapper extends BufferWrapper { + + public int length() { return 0; } - public int getGLDataType() - { + public int getGLDataType() { return 0; } - public long getSizeInBytes() - { + public long getSizeInBytes() { return 0; } - public byte getByte(int index) - { + public byte getByte(int index) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putByte(int index, byte value) - { + public void putByte(int index, byte value) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public short getShort(int index) - { + public short getShort(int index) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putShort(int index, short value) - { + public void putShort(int index, short value) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public int getInt(int index) - { + public int getInt(int index) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putInt(int index, int value) - { + public void putInt(int index, int value) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public float getFloat(int index) - { + public float getFloat(int index) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putFloat(int index, float value) - { + public void putFloat(int index, float value) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public double getDouble(int index) - { + public double getDouble(int index) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putDouble(int index, double value) - { + public void putDouble(int index, double value) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void getByte(int index, byte[] array, int offset, int length) - { + public void getByte(int index, byte[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putByte(int index, byte[] array, int offset, int length) - { + public void putByte(int index, byte[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void getShort(int index, short[] array, int offset, int length) - { + public void getShort(int index, short[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putShort(int index, short[] array, int offset, int length) - { + public void putShort(int index, short[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void getInt(int index, int[] array, int offset, int length) - { + public void getInt(int index, int[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putInt(int index, int[] array, int offset, int length) - { + public void putInt(int index, int[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void getFloat(int index, float[] array, int offset, int length) - { + public void getFloat(int index, float[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putFloat(int index, float[] array, int offset, int length) - { + public void putFloat(int index, float[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void getDouble(int index, double[] array, int offset, int length) - { + public void getDouble(int index, double[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putDouble(int index, double[] array, int offset, int length) - { + public void putDouble(int index, double[] array, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public BufferWrapper getSubBuffer(int index, int length) - { + public BufferWrapper getSubBuffer(int index, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putSubBuffer(int index, BufferWrapper buffer) - { + public void putSubBuffer(int index, BufferWrapper buffer) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public void putSubBuffer(int index, BufferWrapper buffer, int offset, int length) - { + public void putSubBuffer(int index, BufferWrapper buffer, int offset, int length) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - public BufferWrapper copyOf(int newSize) - { + public BufferWrapper copyOf(int newSize) { return new EmptyBufferWrapper(); } - public Buffer getBackingBuffer() - { + public Buffer getBackingBuffer() { return null; } } diff --git a/src/gov/nasa/worldwind/util/ClippingTessellator.java b/src/gov/nasa/worldwind/util/ClippingTessellator.java index f1192b441c..70ebf2d47c 100644 --- a/src/gov/nasa/worldwind/util/ClippingTessellator.java +++ b/src/gov/nasa/worldwind/util/ClippingTessellator.java @@ -11,31 +11,27 @@ // TODO: Consider replacing the clipping capability in PolygonTessellator2 with use of this independent component. // TODO: Consider clipping contour coordinates to the sector bounds, rather than just reducing complexity. - /** * ClippingTessellator * * @author dcollins * @version $Id: ClippingTessellator.java 2398 2014-10-28 17:14:41Z dcollins $ */ -public class ClippingTessellator -{ +public class ClippingTessellator { + protected GLUtessellator tessellator; protected double[] clipDegrees; protected double[] prevCoord = new double[2]; protected int prevClipCode; - public ClippingTessellator(GLUtessellator tessellator, Sector sector) - { - if (tessellator == null) - { + public ClippingTessellator(GLUtessellator tessellator, Sector sector) { + if (tessellator == null) { String msg = Logging.getMessage("nullValue.TessellatorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (sector == null) - { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -45,28 +41,23 @@ public ClippingTessellator(GLUtessellator tessellator, Sector sector) this.clipDegrees = sector.asDegreesArray(); } - public void beginContour() - { + public void beginContour() { GLU.gluTessBeginContour(this.tessellator); this.prevClipCode = -1; } - public void endContour() - { + public void endContour() { GLU.gluTessEndContour(this.tessellator); } - public void addVertex(double degreesLatitude, double degreesLongitude) - { + public void addVertex(double degreesLatitude, double degreesLongitude) { int code = this.clipCode(degreesLatitude, degreesLongitude); - if (this.prevClipCode > 0 && code != this.prevClipCode) - { + if (this.prevClipCode > 0 && code != this.prevClipCode) { this.doAddVertex(this.prevCoord[0], prevCoord[1]); } - if (code == 0 || code != this.prevClipCode) - { + if (code == 0 || code != this.prevClipCode) { this.doAddVertex(degreesLatitude, degreesLongitude); } @@ -75,8 +66,7 @@ public void addVertex(double degreesLatitude, double degreesLongitude) this.prevClipCode = code; // copy the current clip code to the previous clip code } - protected void doAddVertex(double degreesLatitude, double degreesLongitude) - { + protected void doAddVertex(double degreesLatitude, double degreesLongitude) { double[] vertex = {degreesLongitude, degreesLatitude, 0}; // lon,lat -> x,y,0 GLU.gluTessVertex(this.tessellator, vertex, 0, vertex); } @@ -90,8 +80,7 @@ protected void doAddVertex(double degreesLatitude, double degreesLongitude) * @param degreesLongitude The longitude for computation. * @return The vertex location code. */ - protected int clipCode(double degreesLatitude, double degreesLongitude) - { + protected int clipCode(double degreesLatitude, double degreesLongitude) { int code = 0; code |= (degreesLatitude < this.clipDegrees[0] ? 0x0001 : 0x0); // minLat code |= (degreesLatitude > this.clipDegrees[1] ? 0x0010 : 0x0); // maxLat diff --git a/src/gov/nasa/worldwind/util/ClutterFilter.java b/src/gov/nasa/worldwind/util/ClutterFilter.java index 2ae4bf3ca6..8e02fb224e 100644 --- a/src/gov/nasa/worldwind/util/ClutterFilter.java +++ b/src/gov/nasa/worldwind/util/ClutterFilter.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.render.*; @@ -17,12 +16,12 @@ * @author tag * @version $Id: ClutterFilter.java 726 2012-08-29 03:16:03Z tgaskins $ */ -public interface ClutterFilter -{ +public interface ClutterFilter { + /** * Applies the filter for a specified list of {@link Declutterable} shapes. * - * @param dc the current draw context. + * @param dc the current draw context. * @param shapes the shapes to declutter. */ void apply(DrawContext dc, List shapes); diff --git a/src/gov/nasa/worldwind/util/CompoundStringBuilder.java b/src/gov/nasa/worldwind/util/CompoundStringBuilder.java index b4c2520f5e..98732d36c7 100644 --- a/src/gov/nasa/worldwind/util/CompoundStringBuilder.java +++ b/src/gov/nasa/worldwind/util/CompoundStringBuilder.java @@ -14,8 +14,8 @@ * @author dcollins * @version $Id: CompoundStringBuilder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CompoundStringBuilder -{ +public class CompoundStringBuilder { + protected static final int DEFAULT_INITIAL_CAPACITY = 16; protected StringBuilder buffer; @@ -28,21 +28,18 @@ public class CompoundStringBuilder * Constructs a CompoundStringBuilder with the specified backing StringBuilder and initial capacity. * * @param stringBuilder the StringBuilder in which to store the string data. - * @param capacity the compound buffer's initial capacity. + * @param capacity the compound buffer's initial capacity. * * @throws IllegalArgumentException if the stringBuilder is null or if the capacity is less than 1. */ - public CompoundStringBuilder(StringBuilder stringBuilder, int capacity) - { - if (stringBuilder == null) - { + public CompoundStringBuilder(StringBuilder stringBuilder, int capacity) { + if (stringBuilder == null) { String message = Logging.getMessage("nullValue.StringBuilderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (capacity < 1) - { + if (capacity < 1) { String message = Logging.getMessage("generic.CapacityIsInvalid", capacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -61,14 +58,14 @@ public CompoundStringBuilder(StringBuilder stringBuilder, int capacity) * * @throws IllegalArgumentException if the capacity is less than 1. */ - public CompoundStringBuilder(int capacity) - { + public CompoundStringBuilder(int capacity) { this(new StringBuilder(), capacity); } - /** Constructs a CompoundStringBuilder with a default backing StringBuilder, and the default initial capacity. */ - public CompoundStringBuilder() - { + /** + * Constructs a CompoundStringBuilder with a default backing StringBuilder, and the default initial capacity. + */ + public CompoundStringBuilder() { this(new StringBuilder(), DEFAULT_INITIAL_CAPACITY); } @@ -77,8 +74,7 @@ public CompoundStringBuilder() * * @return the number of strings in this CompoundStringBuilder. */ - public int size() - { + public int size() { return this.count; } @@ -91,10 +87,8 @@ public int size() * * @throws IllegalArgumentException if the index is out of range. */ - public int substringLength(int index) - { - if (index < 0 || index >= this.count) - { + public int substringLength(int index) { + if (index < 0 || index >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -112,10 +106,8 @@ public int substringLength(int index) * * @throws IllegalArgumentException if the index is out of range. */ - public String substring(int index) - { - if (index < 0 || index >= this.count) - { + public String substring(int index) { + if (index < 0 || index >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -134,10 +126,8 @@ public String substring(int index) * * @throws IllegalArgumentException if the index is out of range. */ - public CharSequence subSequence(int index) - { - if (index < 0 || index >= this.count) - { + public CharSequence subSequence(int index) { + if (index < 0 || index >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -159,18 +149,17 @@ public CharSequence subSequence(int index) * * @throws IllegalArgumentException if the charSequence is null. */ - public int append(CharSequence charSequence) - { - if (charSequence == null) - { + public int append(CharSequence charSequence) { + if (charSequence == null) { String message = Logging.getMessage("nullValue.CharSequenceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } int newCount = 1 + this.count; - if (newCount > this.capacity) + if (newCount > this.capacity) { this.expandCapacity(newCount); + } int index = this.count; this.offsets[index] = this.buffer.length(); @@ -185,25 +174,20 @@ public int append(CharSequence charSequence) * Clears this CompoundStringBuilder's backing StringBuilder and sets the number of substrings to zero. This does * not free any memory associated with this CompoundStringBuilder. */ - public void clear() - { + public void clear() { this.buffer.delete(0, this.buffer.length()); this.count = 0; } - protected void expandCapacity(int minCapacity) - { + protected void expandCapacity(int minCapacity) { int newCapacity = 2 * this.capacity; // If the new capacity overflows the range of 32-bit integers, then use the largest 32-bit integer. - if (newCapacity < 0) - { + if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; - } - // If the new capacity is still not large enough for the minimum capacity specified, then just use the minimum + } // If the new capacity is still not large enough for the minimum capacity specified, then just use the minimum // capacity specified. - else if (newCapacity < minCapacity) - { + else if (newCapacity < minCapacity) { newCapacity = minCapacity; } diff --git a/src/gov/nasa/worldwind/util/CompoundVecBuffer.java b/src/gov/nasa/worldwind/util/CompoundVecBuffer.java index d1b4f5b529..c026ac157f 100644 --- a/src/gov/nasa/worldwind/util/CompoundVecBuffer.java +++ b/src/gov/nasa/worldwind/util/CompoundVecBuffer.java @@ -27,8 +27,8 @@ * @author dcollins * @version $Id: CompoundVecBuffer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class CompoundVecBuffer -{ +public abstract class CompoundVecBuffer { + protected static final int DEFAULT_INITIAL_CAPACITY = 16; protected static final boolean ALLOCATE_DIRECT_BUFFERS = true; @@ -44,10 +44,8 @@ public abstract class CompoundVecBuffer * * @throws IllegalArgumentException if the capacity is less than 1. */ - public CompoundVecBuffer(int capacity) - { - if (capacity < 1) - { + public CompoundVecBuffer(int capacity) { + if (capacity < 1) { String message = Logging.getMessage("generic.CapacityIsInvalid", capacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -58,14 +56,14 @@ public CompoundVecBuffer(int capacity) this.lengths = WWBufferUtil.newIntBuffer(capacity, ALLOCATE_DIRECT_BUFFERS); } - /** Constructs a CompoundVecBuffer with the default initial capacity. */ - public CompoundVecBuffer() - { + /** + * Constructs a CompoundVecBuffer with the default initial capacity. + */ + public CompoundVecBuffer() { this(DEFAULT_INITIAL_CAPACITY); } - protected CompoundVecBuffer(CompoundVecBuffer that, int beginIndex, int endIndex) - { + protected CompoundVecBuffer(CompoundVecBuffer that, int beginIndex, int endIndex) { int length = endIndex - beginIndex + 1; this.count = length; @@ -86,16 +84,14 @@ protected CompoundVecBuffer(CompoundVecBuffer that, int beginIndex, int endIndex that.lengths.clear(); } - protected CompoundVecBuffer(CompoundVecBuffer that, int[] indices, int offset, int length) - { + protected CompoundVecBuffer(CompoundVecBuffer that, int[] indices, int offset, int length) { this.count = length; this.capacity = length; this.offsets = WWBufferUtil.newIntBuffer(length, ALLOCATE_DIRECT_BUFFERS); this.lengths = WWBufferUtil.newIntBuffer(length, ALLOCATE_DIRECT_BUFFERS); - for (int i = offset; i < offset + length; i++) - { + for (int i = offset; i < offset + length; i++) { this.offsets.put(that.offsets.get(indices[i])); this.lengths.put(that.lengths.get(indices[i])); } @@ -112,10 +108,8 @@ protected CompoundVecBuffer(CompoundVecBuffer that, int[] indices, int offset, i * * @return the empty CompoundVecBuffer. */ - public static CompoundVecBuffer emptyCompoundVecBuffer(int coordsPerVec) - { - if (coordsPerVec < 1) - { + public static CompoundVecBuffer emptyCompoundVecBuffer(int coordsPerVec) { + if (coordsPerVec < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", coordsPerVec); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -129,8 +123,7 @@ public static CompoundVecBuffer emptyCompoundVecBuffer(int coordsPerVec) * * @return the number of VecBuffers in this CompoundVecBuffer. */ - public int size() - { + public int size() { return this.count; } @@ -154,10 +147,8 @@ public int size() * * @throws IllegalArgumentException if the index is out of range. */ - public VecBuffer subBuffer(int index) - { - if (index < 0 || index >= this.count) - { + public VecBuffer subBuffer(int index) { + if (index < 0 || index >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -166,12 +157,9 @@ public VecBuffer subBuffer(int index) int off = this.offsets.get(index); int len = this.lengths.get(index); - if (len > 0) - { + if (len > 0) { return this.createSubBuffer(off, len); - } - else - { + } else { return VecBuffer.emptyVecBuffer(this.getCoordsPerVec()); } } @@ -183,31 +171,27 @@ public VecBuffer subBuffer(int index) * reflected in the returned buffer, and vice versa. * * @param beginIndex the index of the first sub-buffer to include in the subset. - * @param endIndex the index of the last sub-buffer to include in the subset. + * @param endIndex the index of the last sub-buffer to include in the subset. * * @return a new CompoundVecBuffer representing a subset of this CompoundVecBuffer. * - * @throws IllegalArgumentException if beginIndex is out of range, if endIndex is out of range, or if beginIndex > - * endIndex. + * @throws IllegalArgumentException if beginIndex is out of range, if endIndex is out of range, or if beginIndex + * > endIndex. */ - public CompoundVecBuffer slice(int beginIndex, int endIndex) - { - if (beginIndex < 0 || beginIndex >= this.count) - { + public CompoundVecBuffer slice(int beginIndex, int endIndex) { + if (beginIndex < 0 || beginIndex >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", beginIndex); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (endIndex < 0 || endIndex >= this.count) - { + if (endIndex < 0 || endIndex >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", endIndex); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (beginIndex > endIndex) - { + if (beginIndex > endIndex) { String message = Logging.getMessage("generic.indexOutOfRange", beginIndex); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -223,41 +207,35 @@ public CompoundVecBuffer slice(int beginIndex, int endIndex) * versa. * * @param indices an array containing the indices include in the subset. - * @param offset the array starting index. - * @param length the number of array values to use. + * @param offset the array starting index. + * @param length the number of array values to use. * * @return a new CompoundVecBuffer representing a subset of this CompoundVecBuffer. * * @throws IllegalArgumentException if the array of indices is null, if the offset or length are invalid, or if any - * of the indices is out of range. + * of the indices is out of range. */ - public CompoundVecBuffer slice(int[] indices, int offset, int length) - { - if (indices == null) - { + public CompoundVecBuffer slice(int[] indices, int offset, int length) { + if (indices == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (length < 0 || length > indices.length) - { + if (length < 0 || length > indices.length) { String message = Logging.getMessage("generic.LengthIsInvalid", length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (offset < 0 || offset + length > indices.length) - { + if (offset < 0 || offset + length > indices.length) { String message = Logging.getMessage("generic.OffsetIsInvalid", offset); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (int i = offset; i < offset + length; i++) - { - if (indices[i] < 0 || indices[i] >= this.count) - { + for (int i = offset; i < offset + length; i++) { + if (indices[i] < 0 || indices[i] >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", indices[i]); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -279,10 +257,8 @@ public CompoundVecBuffer slice(int[] indices, int offset, int length) * * @throws IllegalArgumentException if the array of indices is null, or if any of the indices is out of range. */ - public CompoundVecBuffer slice(int[] indices) - { - if (indices == null) - { + public CompoundVecBuffer slice(int[] indices) { + if (indices == null) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -291,9 +267,10 @@ public CompoundVecBuffer slice(int[] indices) return this.slice(indices, 0, indices.length); } - /** Sets the number sub-buffers to zero. This does not free any memory associated with this CompoundVecBuffer. */ - public void clear() - { + /** + * Sets the number sub-buffers to zero. This does not free any memory associated with this CompoundVecBuffer. + */ + public void clear() { this.count = 0; } @@ -307,18 +284,17 @@ public void clear() //**************************************************************// //******************** Protected Interface *******************// //**************************************************************// - protected abstract VecBuffer createSubBuffer(int offset, int length); protected abstract CompoundVecBuffer createSlice(int[] indices, int offset, int length); protected abstract CompoundVecBuffer createSlice(int beginIndex, int endIndex); - protected int addSubBuffer(int offset, int length) - { + protected int addSubBuffer(int offset, int length) { int minCount = 1 + this.count; - if (minCount > this.capacity) + if (minCount > this.capacity) { this.expandCapacity(minCount); + } int index = this.count; this.offsets.put(index, offset); @@ -328,19 +304,15 @@ protected int addSubBuffer(int offset, int length) return index; } - protected void expandCapacity(int minCapacity) - { + protected void expandCapacity(int minCapacity) { int newCapacity = 2 * this.capacity; // If the new capacity overflows the range of 32-bit integers, then use the largest 32-bit integer. - if (newCapacity < 0) - { + if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; - } - // If the new capacity is still not large enough for the minimum capacity specified, then just use the minimum + } // If the new capacity is still not large enough for the minimum capacity specified, then just use the minimum // capacity specified. - else if (newCapacity < minCapacity) - { + else if (newCapacity < minCapacity) { newCapacity = minCapacity; } @@ -352,15 +324,13 @@ else if (newCapacity < minCapacity) //**************************************************************// //******************** Iterable Methods **********************// //**************************************************************// - /** * Returns an iterator over this buffer's logical vectors, as double[] coordinate arrays. The array returned from * each call to Iterator.next() will be newly allocated, and will have length equal to coordsPerVec. * * @return iterator over this buffer's vectors, as double[] arrays. */ - public Iterable getCoords() - { + public Iterable getCoords() { return this.getCoords(this.getCoordsPerVec()); } @@ -374,12 +344,9 @@ public Iterable getCoords() * * @return iterator over this buffer's vectors, as double[] arrays. */ - public Iterable getCoords(final int minCoordsPerVec) - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getCoords(final int minCoordsPerVec) { + return new Iterable() { + public Iterator iterator() { return new CompoundIterator(new CoordIterable(minCoordsPerVec)); } }; @@ -395,12 +362,9 @@ public Iterator iterator() * * @return reverse iterator over this buffer's vectors, as double[] arrays. */ - public Iterable getReverseCoords(final int minCoordsPerVec) - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getReverseCoords(final int minCoordsPerVec) { + return new Iterable() { + public Iterator iterator() { return new ReverseCompoundIterator(new CoordIterable(minCoordsPerVec)); } }; @@ -411,12 +375,9 @@ public Iterator iterator() * * @return iterator over this buffer's vectors, as Vec4 references. */ - public Iterable getVectors() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getVectors() { + return new Iterable() { + public Iterator iterator() { return new CompoundIterator(new VectorIterable()); } }; @@ -427,12 +388,9 @@ public Iterator iterator() * * @return reverse iterator over this buffer's vectors, as Vec4 references. */ - public Iterable getReverseVectors() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getReverseVectors() { + return new Iterable() { + public Iterator iterator() { return new ReverseCompoundIterator(new VectorIterable()); } }; @@ -443,12 +401,9 @@ public Iterator iterator() * * @return iterator over this buffer's vectors, as LatLon locations. */ - public Iterable getLocations() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getLocations() { + return new Iterable() { + public Iterator iterator() { return new CompoundIterator(new LocationIterable()); } }; @@ -459,12 +414,9 @@ public Iterator iterator() * * @return reverse iterator over this buffer's vectors, as LatLon locations. */ - public Iterable getReverseLocations() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getReverseLocations() { + return new Iterable() { + public Iterator iterator() { return new ReverseCompoundIterator(new LocationIterable()); } }; @@ -475,12 +427,9 @@ public Iterator iterator() * * @return iterator over this buffer's vectors, as geographic Positions. */ - public Iterable getPositions() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getPositions() { + return new Iterable() { + public Iterator iterator() { return new CompoundIterator(new PositionIterable()); } }; @@ -491,12 +440,9 @@ public Iterator iterator() * * @return reverse iterator over this buffer's vectors, as geographic Positions. */ - public Iterable getReversePositions() - { - return new Iterable() - { - public Iterator iterator() - { + public Iterable getReversePositions() { + return new Iterable() { + public Iterator iterator() { return new ReverseCompoundIterator(new PositionIterable()); } }; @@ -505,137 +451,115 @@ public Iterator iterator() //**************************************************************// //******************** Iterator Implementations **************// //**************************************************************// + protected class CompoundIterator implements Iterator { - protected class CompoundIterator implements Iterator - { protected int subBuffer; protected Iterator subIterator; protected final int subBufferCount; protected final SubBufferIterable subBufferIterable; - protected CompoundIterator(SubBufferIterable subBufferIterable) - { + protected CompoundIterator(SubBufferIterable subBufferIterable) { this.subBuffer = 0; this.subBufferCount = size(); this.subBufferIterable = subBufferIterable; } - public boolean hasNext() - { + public boolean hasNext() { this.updateSubIterator(); return this.subIterator != null && this.subIterator.hasNext(); } - public T next() - { + public T next() { this.updateSubIterator(); - if (this.subIterator != null && this.subIterator.hasNext()) - { + if (this.subIterator != null && this.subIterator.hasNext()) { return this.subIterator.next(); - } - else - { + } else { throw new NoSuchElementException(); } } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } - protected void updateSubIterator() - { - while (this.subBuffer < this.subBufferCount && (this.subIterator == null || !this.subIterator.hasNext())) - { + protected void updateSubIterator() { + while (this.subBuffer < this.subBufferCount && (this.subIterator == null || !this.subIterator.hasNext())) { this.subIterator = this.subBufferIterable.iterator(this.subBuffer); this.subBuffer++; } } } - protected class ReverseCompoundIterator extends CompoundIterator - { - public ReverseCompoundIterator(SubBufferIterable subBufferIterable) - { + protected class ReverseCompoundIterator extends CompoundIterator { + + public ReverseCompoundIterator(SubBufferIterable subBufferIterable) { super(subBufferIterable); this.subBuffer = this.subBufferCount - 1; } - protected void updateSubIterator() - { - while (this.subBuffer >= 0 && (this.subIterator == null || !this.subIterator.hasNext())) - { + protected void updateSubIterator() { + while (this.subBuffer >= 0 && (this.subIterator == null || !this.subIterator.hasNext())) { this.subIterator = this.subBufferIterable.reverseIterator(this.subBuffer); this.subBuffer--; } } } - protected interface SubBufferIterable - { + protected interface SubBufferIterable { + Iterator iterator(int index); Iterator reverseIterator(int index); } - protected class CoordIterable implements SubBufferIterable - { + protected class CoordIterable implements SubBufferIterable { + private int minCoordsPerVec; - public CoordIterable(int minCoordsPerVec) - { + public CoordIterable(int minCoordsPerVec) { this.minCoordsPerVec = minCoordsPerVec; } - public Iterator iterator(int index) - { + public Iterator iterator(int index) { return subBuffer(index).getCoords(this.minCoordsPerVec).iterator(); } - public Iterator reverseIterator(int index) - { + public Iterator reverseIterator(int index) { return subBuffer(index).getReverseCoords(this.minCoordsPerVec).iterator(); } } - protected class VectorIterable implements SubBufferIterable - { - public Iterator iterator(int index) - { + protected class VectorIterable implements SubBufferIterable { + + public Iterator iterator(int index) { return subBuffer(index).getVectors().iterator(); } - public Iterator reverseIterator(int index) - { + public Iterator reverseIterator(int index) { return subBuffer(index).getReverseVectors().iterator(); } } - protected class LocationIterable implements SubBufferIterable - { - public Iterator iterator(int index) - { + protected class LocationIterable implements SubBufferIterable { + + public Iterator iterator(int index) { return subBuffer(index).getLocations().iterator(); } - public Iterator reverseIterator(int index) - { + public Iterator reverseIterator(int index) { return subBuffer(index).getReverseLocations().iterator(); } } - protected class PositionIterable implements SubBufferIterable - { - public Iterator iterator(int index) - { + protected class PositionIterable implements SubBufferIterable { + + public Iterator iterator(int index) { return subBuffer(index).getPositions().iterator(); } - public Iterator reverseIterator(int index) - { + public Iterator reverseIterator(int index) { return subBuffer(index).getReversePositions().iterator(); } } @@ -643,17 +567,14 @@ public Iterator reverseIterator(int index) //**************************************************************// //******************** Empty CompoundVecBuffer ***************// //**************************************************************// + protected static class EmptyCompoundVecBuffer extends CompoundVecBuffer { - protected static class EmptyCompoundVecBuffer extends CompoundVecBuffer - { protected int coordsPerVec; - public EmptyCompoundVecBuffer(int coordsPerVec) - { + public EmptyCompoundVecBuffer(int coordsPerVec) { super(1); - if (coordsPerVec < 1) - { + if (coordsPerVec < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", coordsPerVec); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -662,20 +583,16 @@ public EmptyCompoundVecBuffer(int coordsPerVec) this.coordsPerVec = coordsPerVec; } - protected EmptyCompoundVecBuffer(EmptyCompoundVecBuffer that, int beginIndex, int endIndex) - { + protected EmptyCompoundVecBuffer(EmptyCompoundVecBuffer that, int beginIndex, int endIndex) { super(that, beginIndex, endIndex); } - protected EmptyCompoundVecBuffer(EmptyCompoundVecBuffer that, int[] indices, int offset, int length) - { + protected EmptyCompoundVecBuffer(EmptyCompoundVecBuffer that, int[] indices, int offset, int length) { super(that, indices, offset, length); } - public int subBufferSize(int index) - { - if (index < 0 || index >= this.count) - { + public int subBufferSize(int index) { + if (index < 0 || index >= this.count) { String message = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -684,23 +601,19 @@ public int subBufferSize(int index) return 0; } - public int getCoordsPerVec() - { + public int getCoordsPerVec() { return this.coordsPerVec; } - protected VecBuffer createSubBuffer(int offset, int length) - { + protected VecBuffer createSubBuffer(int offset, int length) { return VecBuffer.emptyVecBuffer(this.coordsPerVec); } - protected CompoundVecBuffer createSlice(int[] indices, int offset, int length) - { + protected CompoundVecBuffer createSlice(int[] indices, int offset, int length) { return new EmptyCompoundVecBuffer(this, indices, offset, length); } - protected CompoundVecBuffer createSlice(int beginIndex, int endIndex) - { + protected CompoundVecBuffer createSlice(int beginIndex, int endIndex) { return new EmptyCompoundVecBuffer(this, beginIndex, endIndex); } } diff --git a/src/gov/nasa/worldwind/util/ContourBuilder.java b/src/gov/nasa/worldwind/util/ContourBuilder.java index 81c1bafd2c..ef52bfa3e8 100644 --- a/src/gov/nasa/worldwind/util/ContourBuilder.java +++ b/src/gov/nasa/worldwind/util/ContourBuilder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.geom.*; @@ -33,56 +32,53 @@ * @author dcollins * @version $Id: ContourBuilder.java 2436 2014-11-14 23:20:50Z danm $ */ -public class ContourBuilder -{ - protected static class CellInfo - { +public class ContourBuilder { + + protected static class CellInfo { + public final int x; public final int y; public final int contourMask; public final Map edgeWeights = new HashMap(); public final Set visitedDirections = new HashSet(4); - public CellInfo(int x, int y, int contourMask) - { + public CellInfo(int x, int y, int contourMask) { this.x = x; this.y = y; this.contourMask = contourMask; } } - protected static class CellKey - { + protected static class CellKey { + public final int x; public final int y; - public CellKey(int x, int y) - { + public CellKey(int x, int y) { this.x = x; this.y = y; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } CellKey that = (CellKey) o; return this.x == that.x && this.y == that.y; } @Override - public int hashCode() - { + public int hashCode() { return 31 * this.x + this.y; } } - protected static enum Direction - { + protected static enum Direction { NORTH, SOUTH, EAST, WEST } @@ -96,10 +92,9 @@ protected static enum Direction protected static Map dirRev = new HashMap(); protected static Map> dirNext - = new HashMap>(); + = new HashMap>(); - static - { + static { dirRev.put(Direction.NORTH, Direction.SOUTH); dirRev.put(Direction.SOUTH, Direction.NORTH); dirRev.put(Direction.EAST, Direction.WEST); @@ -186,41 +181,35 @@ protected static enum Direction * Creates a new ContourBuilder with the specified rectangular array arguments. The array is understood to be * organized in row-major order, with the first index indicating the value at the rectangle's upper-left corner. * - * @param width the rectangular array width. + * @param width the rectangular array width. * @param height the rectangular array height. * @param values the rectangular array values, as a one-dimensional array. Must contain at least width * height - * values. This array is understood to be organized in row-major order, with the first index - * indicating the value at the rectangle's upper-left corner. + * values. This array is understood to be organized in row-major order, with the first index indicating the value at + * the rectangle's upper-left corner. * * @throws java.lang.IllegalArgumentException if either the width or the height are less than 1, if the array is - * null, or if the array length is insufficient for the specified width - * and height. + * null, or if the array length is insufficient for the specified width and height. */ - public ContourBuilder(int width, int height, double[] values) - { - if (width < 1) - { + public ContourBuilder(int width, int height, double[] values) { + if (width < 1) { String msg = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (height < 1) - { + if (height < 1) { String msg = Logging.getMessage("generic.InvalidHeight", height); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (values == null) - { + if (values == null) { String msg = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (values.length != width * height) - { + if (values.length != width * height) { String msg = Logging.getMessage("generic.ArrayInvalidLength", values.length); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -246,8 +235,7 @@ public ContourBuilder(int width, int height, double[] values) * * @return a list containing the contour lines for the threshold value. */ - public List> buildContourLines(double value) - { + public List> buildContourLines(double value) { this.assembleContourCells(value); this.traverseContourCells(); @@ -275,20 +263,17 @@ public List> buildContourLines(double value) * less than the rectangular array's minimum value, or when the value is greater than the rectangular array's * maximum value. * - * @param value the threshold value (i.e. isovalue) to compute contour lines for. - * @param sector the sector to associate with the rectangular array. The array's upper left corner is mapped to - * the sector's Northwest corner, and the array's lower right corner is mapped to the sector's - * Southeast corner. + * @param value the threshold value (i.e. isovalue) to compute contour lines for. + * @param sector the sector to associate with the rectangular array. The array's upper left corner is mapped to the + * sector's Northwest corner, and the array's lower right corner is mapped to the sector's Southeast corner. * @param altitude the altitude to assign to the geographic positions. * * @return a list containing the geographic contour lines for the threshold value. * * @throws java.lang.IllegalArgumentException if the sector is null. */ - public List> buildContourLines(double value, Sector sector, double altitude) - { - if (sector == null) - { + public List> buildContourLines(double value, Sector sector, double altitude) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -304,12 +289,10 @@ public List> buildContourLines(double value, Sector sector, doubl List> result = new ArrayList>(); - for (List coordList : this.contourList) - { + for (List coordList : this.contourList) { ArrayList positionList = new ArrayList(); - for (double[] coord : coordList) - { + for (double[] coord : coordList) { double s = coord[0] / (this.width - 1); // normalized x coordinate in the range 0 to 1 double t = coord[1] / (this.height - 1); // normalized y coordinate in the range 0 to 1 double lat = maxLat - t * deltaLat; // map y coordinate to latitude @@ -325,8 +308,7 @@ public List> buildContourLines(double value, Sector sector, doubl return result; } - protected void assembleContourCells(double value) - { + protected void assembleContourCells(double value) { // Divide the 2D scalar field into a grid of evenly spaced contouring cells. Every 2x2 block of field values // forms a cell. The contouring grid's dimensions are therefore one less than the 2D scalar field. Based on // the approach outlined at http://en.wikipedia.org/wiki/Marching_squares @@ -334,10 +316,8 @@ protected void assembleContourCells(double value) this.contourCellMap.clear(); this.contourCellList.clear(); - for (int y = 0; y < this.height - 1; y++) - { - for (int x = 0; x < this.width - 1; x++) - { + for (int y = 0; y < this.height - 1; y++) { + for (int x = 0; x < this.width - 1; x++) { // Get the field values associated with the contouring cell's four corners. double nw = this.valueFor(x, y); double ne = this.valueFor(x + 1, y); @@ -355,38 +335,43 @@ protected void assembleContourCells(double value) mask <<= 1; mask |= (sw > value) ? 1 : 0; // 0001 - if (mask == 0 || mask == 15) + if (mask == 0 || mask == 15) { continue; // no contour; all values above or below the threshold value - + } // Disambiguate saddle point for masks 0x0101 and 0x1010, per Wikipedia page suggestion. - if (mask == 5 || mask == 10) - { + if (mask == 5 || mask == 10) { double ctr = (nw + ne + se + sw) / 4; // sample center value as the average of four corners if (mask == 5 && ctr <= value) // center value causes change in direction; flip the mask to 10 + { mask = 10; - else if (mask == 10 && ctr <= value) // center value causes change in direction; flip the mask to 5 + } else if (mask == 10 && ctr <= value) // center value causes change in direction; flip the mask to 5 + { mask = 5; + } } CellInfo cell = new CellInfo(x, y, mask); // Compute weights associated with edge intersections. - if ((ne > value) ^ (nw > value)) + if ((ne > value) ^ (nw > value)) { cell.edgeWeights.put(Direction.NORTH, (value - nw) / (ne - nw)); - if ((se > value) ^ (sw > value)) + } + if ((se > value) ^ (sw > value)) { cell.edgeWeights.put(Direction.SOUTH, (value - sw) / (se - sw)); - if ((se > value) ^ (ne > value)) + } + if ((se > value) ^ (ne > value)) { cell.edgeWeights.put(Direction.EAST, (value - ne) / (se - ne)); - if ((sw > value) ^ (nw > value)) + } + if ((sw > value) ^ (nw > value)) { cell.edgeWeights.put(Direction.WEST, (value - nw) / (sw - nw)); + } this.putContourCell(cell); } } } - protected void traverseContourCells() - { + protected void traverseContourCells() { List> contours = new ArrayList>(); this.contourList.clear(); @@ -397,8 +382,7 @@ protected void traverseContourCells() for (Direction dir : dirNext.get(cell.contourMask).keySet()) // either 2 or 4 starting directions { - if (cell.visitedDirections.contains(dir)) - { + if (cell.visitedDirections.contains(dir)) { continue; } @@ -409,13 +393,10 @@ protected void traverseContourCells() if (contours.size() == 2) // combine each pair of starting directions into a single polyline { - if (contours.get(0).size() == 0 && contours.get(1).size() == 0) - { + if (contours.get(0).size() == 0 && contours.get(1).size() == 0) { String msg = Logging.getMessage("generic.UnexpectedCondition", "both contours are of zero length"); Logging.logger().severe(msg); - } - else - { + } else { Collections.reverse(contours.get(0)); contours.get(0).addAll(contours.get(1)); this.contourList.add(contours.get(0)); @@ -425,21 +406,18 @@ protected void traverseContourCells() } } - if (contours.size() != 0) - { + if (contours.size() != 0) { String msg = Logging.getMessage("generic.UnexpectedCondition", "non-empty contours list"); Logging.logger().severe(msg); } } } - protected void traverseContour(CellInfo cell, Direction dir) - { + protected void traverseContour(CellInfo cell, Direction dir) { Direction dirNext = dir; Direction dirPrev = dir; // use Prev same as Next for first iteration (i.e., for seed cell) - while (cell != null && !cell.visitedDirections.contains(dirNext)) - { + while (cell != null && !cell.visitedDirections.contains(dirNext)) { // Mark the contour cell as visited. cell.visitedDirections.add(dirNext); cell.visitedDirections.add(dirPrev); @@ -450,8 +428,7 @@ protected void traverseContour(CellInfo cell, Direction dir) cell = this.nextCell(cell, dirNext); // guard cell use in computing dirNext - if (cell != null) - { + if (cell != null) { // Advance to the next direction. dirPrev = ContourBuilder.dirRev.get(dirNext); dirNext = ContourBuilder.dirNext.get(cell.contourMask).get(dirPrev); @@ -459,15 +436,13 @@ protected void traverseContour(CellInfo cell, Direction dir) } } - protected void addIntersection(CellInfo cell, Direction dir) - { + protected void addIntersection(CellInfo cell, Direction dir) { // Compute the intersection of the contour cell in the next direction. The cell's xy coordinates initially // indicate the cell's Southwest corner. double xIntersect = cell.x; double yIntersect = cell.y; - switch (dir) - { + switch (dir) { case NORTH: xIntersect += cell.edgeWeights.get(dir); // interpolate along the north edge break; @@ -488,24 +463,21 @@ protected void addIntersection(CellInfo cell, Direction dir) break; } - this.currentContour.add(new double[] {xIntersect, yIntersect}); + this.currentContour.add(new double[]{xIntersect, yIntersect}); } - protected void clearContourCells() - { + protected void clearContourCells() { this.contourCellMap.clear(); this.contourCellList.clear(); this.contourList.clear(); this.currentContour = null; } - protected CellInfo nextCell(CellInfo cell, Direction dir) - { + protected CellInfo nextCell(CellInfo cell, Direction dir) { int x = cell.x; int y = cell.y; - switch (dir) - { + switch (dir) { case NORTH: return this.getContourCell(x, y - 1); case SOUTH: @@ -521,20 +493,17 @@ protected CellInfo nextCell(CellInfo cell, Direction dir) } } - protected double valueFor(int x, int y) - { + protected double valueFor(int x, int y) { return this.values[x + y * this.width]; } - protected void putContourCell(CellInfo cell) - { + protected void putContourCell(CellInfo cell) { CellKey key = new CellKey(cell.x, cell.y); this.contourCellMap.put(key, cell); this.contourCellList.add(key); } - protected CellInfo getContourCell(int x, int y) - { + protected CellInfo getContourCell(int x, int y) { return this.contourCellMap.get(new CellKey(x, y)); } } diff --git a/src/gov/nasa/worldwind/util/ContourList.java b/src/gov/nasa/worldwind/util/ContourList.java index 0d4f62fc6f..c9461bfe86 100644 --- a/src/gov/nasa/worldwind/util/ContourList.java +++ b/src/gov/nasa/worldwind/util/ContourList.java @@ -16,19 +16,16 @@ * @author dcollins * @version $Id: ContourList.java 2405 2014-10-29 23:33:08Z dcollins $ */ -public class ContourList extends WWObjectImpl implements Combinable -{ +public class ContourList extends WWObjectImpl implements Combinable { + protected ArrayList> contours = new ArrayList>(); protected Sector sector; - public ContourList() - { + public ContourList() { } - public ContourList(ContourList that) - { - if (that == null) - { + public ContourList(ContourList that) { + if (that == null) { String msg = Logging.getMessage("nullValue.ContourListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -38,15 +35,12 @@ public ContourList(ContourList that) this.sector = that.sector; } - public int getContourCount() - { + public int getContourCount() { return this.contours.size(); } - public Iterable getContour(int index) - { - if (index < 0 || index >= this.contours.size()) - { + public Iterable getContour(int index) { + if (index < 0 || index >= this.contours.size()) { String msg = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -55,17 +49,14 @@ public Iterable getContour(int index) return this.contours.get(index); } - public void setContour(int index, Iterable contour) - { - if (index < 0 || index >= this.contours.size()) - { + public void setContour(int index, Iterable contour) { + if (index < 0 || index >= this.contours.size()) { String msg = Logging.getMessage("generic.indexOutOfRange", index); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (contour == null) - { + if (contour == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -75,10 +66,8 @@ public void setContour(int index, Iterable contour) this.computeSector(); } - public void addContour(Iterable contour) - { - if (contour == null) - { + public void addContour(Iterable contour) { + if (contour == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -90,10 +79,8 @@ public void addContour(Iterable contour) this.sector = (this.sector != null ? this.sector.union(contourSector) : contourSector); } - public void addAllContours(ContourList that) - { - if (that == null) - { + public void addAllContours(ContourList that) { + if (that == null) { String msg = Logging.getMessage("nullValue.ContourListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -103,84 +90,73 @@ public void addAllContours(ContourList that) this.sector = (this.sector != null ? this.sector.union(that.sector) : that.sector); } - public void removeAllContours() - { + public void removeAllContours() { this.contours.clear(); this.sector = null; } - public Sector getSector() - { + public Sector getSector() { return this.sector; } - protected void computeSector() - { + protected void computeSector() { this.sector = null; - for (Iterable contour : this.contours) - { + for (Iterable contour : this.contours) { Sector contourSector = Sector.boundingSector(contour); this.sector = (this.sector != null ? this.sector.union(contourSector) : contourSector); } } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void combine(CombineContext cc) - { - if (cc == null) - { + public void combine(CombineContext cc) { + if (cc == null) { String msg = Logging.getMessage("nullValue.CombineContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (cc.isBoundingSectorMode()) + if (cc.isBoundingSectorMode()) { this.combineBounds(cc); - else + } else { this.combineContours(cc); + } } - protected void combineBounds(CombineContext cc) - { - if (this.sector == null) + protected void combineBounds(CombineContext cc) { + if (this.sector == null) { return; // no contours - + } cc.addBoundingSector(this.sector); } - protected void combineContours(CombineContext cc) - { - if (this.sector == null) + protected void combineContours(CombineContext cc) { + if (this.sector == null) { return; // no contours - - if (!cc.getSector().intersects(this.sector)) + } + if (!cc.getSector().intersects(this.sector)) { return; // this contour list does not intersect the region of interest - + } this.doCombineContours(cc); } - protected void doCombineContours(CombineContext cc) - { + protected void doCombineContours(CombineContext cc) { GLUtessellator tess = cc.getTessellator(); - for (Iterable contour : this.contours) - { - try - { + for (Iterable contour : this.contours) { + try { GLU.gluTessBeginContour(tess); - for (LatLon location : contour) - { + for (LatLon location : contour) { double[] vertex = {location.longitude.degrees, location.latitude.degrees, 0}; GLU.gluTessVertex(tess, vertex, 0, vertex); } - } - finally - { + } finally { GLU.gluTessEndContour(tess); } } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/DataConfigurationFilter.java b/src/gov/nasa/worldwind/util/DataConfigurationFilter.java index 513863a2c9..13d74e86bc 100644 --- a/src/gov/nasa/worldwind/util/DataConfigurationFilter.java +++ b/src/gov/nasa/worldwind/util/DataConfigurationFilter.java @@ -16,11 +16,12 @@ * @author dcollins * @version $Id: DataConfigurationFilter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DataConfigurationFilter implements java.io.FileFilter, FileStoreFilter -{ - /** Creates a DataConfigurationFilter, but otherwise does nothing. */ - public DataConfigurationFilter() - { +public class DataConfigurationFilter implements java.io.FileFilter, FileStoreFilter { + + /** + * Creates a DataConfigurationFilter, but otherwise does nothing. + */ + public DataConfigurationFilter() { } /** @@ -33,26 +34,22 @@ public DataConfigurationFilter() * * @throws IllegalArgumentException if the file is null. */ - public boolean accept(java.io.File file) - { - if (file == null) - { + public boolean accept(java.io.File file) { + if (file == null) { String msg = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // First check the file path, optionally returning false if the path cannot be accepted for any reason. - if (!this.acceptFilePath(file.getPath())) + if (!this.acceptFilePath(file.getPath())) { return false; + } Document doc = null; - try - { + try { doc = WWXML.openDocumentFile(file.getPath(), this.getClass()); - } - catch (Exception e) - { + } catch (Exception e) { // Not interested in logging the exception. We just want to return false, indicating that the File cannot // be opened as an XML document. } @@ -70,22 +67,17 @@ public boolean accept(java.io.File file) * * @throws IllegalArgumentException if the url is null. */ - public boolean accept(java.net.URL url) - { - if (url == null) - { + public boolean accept(java.net.URL url) { + if (url == null) { String msg = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Document doc = null; - try - { + try { doc = WWXML.openDocumentURL(url); - } - catch (Exception e) - { + } catch (Exception e) { // Not interested in logging the exception. We just want to return false, indicating that the URL cannot // be opened as an XML document. } @@ -103,22 +95,17 @@ public boolean accept(java.net.URL url) * * @throws IllegalArgumentException if the input stream is null. */ - public boolean accept(java.io.InputStream inputStream) - { - if (inputStream == null) - { + public boolean accept(java.io.InputStream inputStream) { + if (inputStream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Document doc = null; - try - { + try { doc = WWXML.openDocumentStream(inputStream); - } - catch (Exception e) - { + } catch (Exception e) { // Not interested in logging the exception. We just want to return false, indicating that the InputStream // cannot be opened as an XML document. } @@ -131,23 +118,20 @@ public boolean accept(java.io.InputStream inputStream) * #accept(org.w3c.dom.Document)} returns true. * * @param fileStore the file store containing the named file path. - * @param fileName the named file path in question. + * @param fileName the named file path in question. * * @return true if the file name should be accepted; false otherwise. * * @throws IllegalArgumentException if either the file store or the file name are null. */ - public boolean accept(FileStore fileStore, String fileName) - { - if (fileStore == null) - { + public boolean accept(FileStore fileStore, String fileName) { + if (fileStore == null) { String msg = Logging.getMessage("nullValue.FileStoreIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (fileName == null) - { + if (fileName == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -156,14 +140,16 @@ public boolean accept(FileStore fileStore, String fileName) // Attempt to locate the named path in the FileStore, optionally checking the class path. If a file with that // name cannot be located, then return false. java.net.URL url = fileStore.findFile(fileName, true); - if (url == null) + if (url == null) { return false; + } // Attempt to convert the URL to a local file path. If that succeeds, then continue treating the URL as if // it were a File. java.io.File file = WWIO.convertURLToFile(url); - if (file != null) + if (file != null) { return this.accept(file); + } return this.accept(url); } @@ -177,17 +163,14 @@ public boolean accept(FileStore fileStore, String fileName) * * @throws IllegalArgumentException if the document is null. */ - public boolean accept(Document doc) - { - if (doc == null) - { + public boolean accept(Document doc) { + if (doc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (doc.getDocumentElement() == null) - { + if (doc.getDocumentElement() == null) { String message = Logging.getMessage("nullValue.DocumentElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -205,10 +188,8 @@ public boolean accept(Document doc) * * @throws IllegalArgumentException if the document is null. */ - public boolean accept(Element domElement) - { - if (domElement == null) - { + public boolean accept(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -217,10 +198,8 @@ public boolean accept(Element domElement) return DataConfigurationUtils.isDataConfig(domElement); } - protected boolean acceptFilePath(String filePath) - { - if (filePath == null) - { + protected boolean acceptFilePath(String filePath) { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/util/DataConfigurationUtils.java b/src/gov/nasa/worldwind/util/DataConfigurationUtils.java index d2edd4fca6..740782d0c1 100644 --- a/src/gov/nasa/worldwind/util/DataConfigurationUtils.java +++ b/src/gov/nasa/worldwind/util/DataConfigurationUtils.java @@ -29,8 +29,8 @@ * @author dcollins * @version $Id: DataConfigurationUtils.java 2120 2014-07-03 03:05:03Z tgaskins $ */ -public class DataConfigurationUtils -{ +public class DataConfigurationUtils { + protected static final String DATE_TIME_PATTERN = "dd MM yyyy HH:mm:ss z"; protected static final String DEFAULT_TEXTURE_FORMAT = "image/dds"; @@ -46,33 +46,27 @@ public class DataConfigurationUtils * * @throws IllegalArgumentException if the document is null. */ - public static boolean isDataConfig(Element domElement) - { - if (domElement == null) - { + public static boolean isDataConfig(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (AbstractLayer.isLayerConfigDocument(domElement)) - { + if (AbstractLayer.isLayerConfigDocument(domElement)) { return true; } - if (AbstractElevationModel.isElevationModelConfigDocument(domElement)) - { + if (AbstractElevationModel.isElevationModelConfigDocument(domElement)) { return true; } - if (isInstalledDataDescriptorConfigDocument(domElement)) - { + if (isInstalledDataDescriptorConfigDocument(domElement)) { return true; } //noinspection RedundantIfStatement - if (isWWDotNetLayerSetConfigDocument(domElement)) - { + if (isWWDotNetLayerSetConfigDocument(domElement)) { return true; } @@ -83,39 +77,33 @@ public static boolean isDataConfig(Element domElement) * Returns the specified data configuration document transformed to a standard Layer or ElevationModel configuration * document. This returns the original document if the document is already in a standard form, or if the document is * not one of the recognized types. Installed DataDescriptor documents are transformed to standard Layer or - * ElevationModel configuration documents, depending on the document contents. WorldWind .NET LayerSet documents - * are transformed to standard Layer configuration documents. This returns null if the document's root element is - * null. + * ElevationModel configuration documents, depending on the document contents. WorldWind .NET LayerSet documents are + * transformed to standard Layer configuration documents. This returns null if the document's root element is null. * * @param doc the document to transform. * * @return the specified document transformed to a standard data configuration document, the original document if - * it's already in a standard form or is unrecognized, or null if the document's root element is null. + * it's already in a standard form or is unrecognized, or null if the document's root element is null. * * @throws IllegalArgumentException if the document is null. */ - public static Document convertToStandardDataConfigDocument(Document doc) - { - if (doc == null) - { + public static Document convertToStandardDataConfigDocument(Document doc) { + if (doc == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Element el = doc.getDocumentElement(); - if (el == null) - { + if (el == null) { return null; } - if (isInstalledDataDescriptorConfigDocument(el)) - { + if (isInstalledDataDescriptorConfigDocument(el)) { return transformInstalledDataDescriptorConfigDocument(el); } - if (isWWDotNetLayerSetConfigDocument(el)) - { + if (isWWDotNetLayerSetConfigDocument(el)) { return transformWWDotNetLayerSetConfigDocument(el); } @@ -125,42 +113,39 @@ public static Document convertToStandardDataConfigDocument(Document doc) /** * Returns the specified data configuration document's display name as a string, or null if the document is not one * of the recognized types. This determines the display name for each type of data configuration document as - * follows: - * + * follows:
                  Mapping
                  Document TypePath to Display Name
                  Layer - * Configuration./DisplayName
                  Elevation Model Configuration./DisplayName
                  Installed DataDescriptor./property[@name="dataSet"]/property[@name="gov.nasa.worldwind.avkey.DatasetNameKey"]
                  + * * *
                  Mapping
                  Document TypePath to + * Display Name
                  Layer Configuration./DisplayName
                  Elevation Model + * Configuration./DisplayName
                  Installed + * DataDescriptor./property[@name="dataSet"]/property[@name="gov.nasa.worldwind.avkey.DatasetNameKey"]
                  WorldWind .NET LayerSet./QuadTileSet/Name
                  Othernull
                  * * @param domElement the data configuration document who's display name is returned. * * @return a String representing the data configuration document's display name, or null if the document is not - * recognized. + * recognized. * * @throws IllegalArgumentException if the document is null. */ - public static String getDataConfigDisplayName(Element domElement) - { - if (domElement == null) - { + public static String getDataConfigDisplayName(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (AbstractLayer.isLayerConfigDocument(domElement) || AbstractElevationModel.isElevationModelConfigDocument( - domElement)) - { + domElement)) { return WWXML.getText(domElement, "DisplayName"); } - if (isInstalledDataDescriptorConfigDocument(domElement)) - { + if (isInstalledDataDescriptorConfigDocument(domElement)) { return WWXML.getText(domElement, - "property[@name=\"dataSet\"]/property[@name=\"gov.nasa.worldwind.avkey.DatasetNameKey\"]"); + "property[@name=\"dataSet\"]/property[@name=\"gov.nasa.worldwind.avkey.DatasetNameKey\"]"); } - if (isWWDotNetLayerSetConfigDocument(domElement)) - { + if (isWWDotNetLayerSetConfigDocument(domElement)) { return WWXML.getText(domElement, "QuadTileSet/Name"); } @@ -169,10 +154,11 @@ public static String getDataConfigDisplayName(Element domElement) /** * Returns the specified data configuration document's type as a string, or null if the document is not one of the - * recognized types. This maps data configuration documents to a type string as follows: + * recognized types. This maps data configuration documents to a type string as follows: + *
                  Mapping
                  Document - * TypeType String
                  Layer Configuration"Layer"
                  Elevation Model - * Configuration"Elevation Model"
                  Installed DataDescriptor"Layer" or - * "ElevationModel"
                  WorldWind .NET LayerSet"Layer"
                  + * *
                  Mapping
                  Document TypeType String
                  Layer Configuration"Layer"
                  Elevation Model Configuration"Elevation + * Model"
                  Installed DataDescriptor"Layer" or "ElevationModel"
                  WorldWind + * .NET LayerSet"Layer"
                  Othernull
                  * * @param domElement the data configuration document to determine a type for. @@ -181,42 +167,33 @@ public static String getDataConfigDisplayName(Element domElement) * * @throws IllegalArgumentException if the document is null. */ - public static String getDataConfigType(Element domElement) - { - if (domElement == null) - { + public static String getDataConfigType(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (AbstractLayer.isLayerConfigDocument(domElement)) - { + if (AbstractLayer.isLayerConfigDocument(domElement)) { return "Layer"; } - if (AbstractElevationModel.isElevationModelConfigDocument(domElement)) - { + if (AbstractElevationModel.isElevationModelConfigDocument(domElement)) { return "ElevationModel"; } - if (isInstalledDataDescriptorConfigDocument(domElement)) - { + if (isInstalledDataDescriptorConfigDocument(domElement)) { String s = WWXML.getText(domElement, - "property[@name=\"dataSet\"]/property[@name=\"gov.nasa.worldwind.avkey.DataType\"]", - null); - if (s != null && s.equals("gov.nasa.worldwind.avkey.TiledElevations")) - { + "property[@name=\"dataSet\"]/property[@name=\"gov.nasa.worldwind.avkey.DataType\"]", + null); + if (s != null && s.equals("gov.nasa.worldwind.avkey.TiledElevations")) { return "ElevationModel"; - } - else - { + } else { return "Layer"; } } - if (isWWDotNetLayerSetConfigDocument(domElement)) - { + if (isWWDotNetLayerSetConfigDocument(domElement)) { return "Layer"; } @@ -234,30 +211,25 @@ public static String getDataConfigType(Element domElement) * * @throws IllegalArgumentException if the parameter list is null. */ - public static String getDataConfigFilename(AVList params, String suffix) - { - if (params == null) - { + public static String getDataConfigFilename(AVList params, String suffix) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String path = params.getStringValue(AVKey.DATA_CACHE_NAME); - if (path == null || path.length() == 0) - { + if (path == null || path.length() == 0) { return null; } String filename = params.getStringValue(AVKey.DATASET_NAME); - if (filename == null || filename.length() == 0) - { + if (filename == null || filename.length() == 0) { filename = params.getStringValue(AVKey.DISPLAY_NAME); } - if (filename == null || filename.length() == 0) - { + if (filename == null || filename.length() == 0) { filename = "DataConfiguration"; } @@ -277,34 +249,29 @@ public static String getDataConfigFilename(AVList params, String suffix) * moved to an arbitrary location within the cache. * * @param dataConfigCachePath the data configuration file's cache path. - * @param params the output key-value pairs which receive the DATA_CACHE_NAME parameter. A null - * reference is permitted. + * @param params the output key-value pairs which receive the DATA_CACHE_NAME parameter. A null reference is + * permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the data config file's cache path is null or has length zero. */ - public static AVList getDataConfigCacheName(String dataConfigCachePath, AVList params) - { - if (dataConfigCachePath == null || dataConfigCachePath.length() == 0) - { + public static AVList getDataConfigCacheName(String dataConfigCachePath, AVList params) { + if (dataConfigCachePath == null || dataConfigCachePath.length() == 0) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { params = new AVListImpl(); } String s = params.getStringValue(AVKey.DATA_CACHE_NAME); - if (s == null || s.length() == 0) - { + if (s == null || s.length() == 0) { // Get the data configuration file's parent cache name. s = WWIO.getParentFilePath(dataConfigCachePath); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { // Replace any windows-style path separators with the unix-style path separator, which is the convention // for cache paths. s = s.replaceAll("\\\\", "/"); @@ -321,28 +288,25 @@ public static AVList getDataConfigCacheName(String dataConfigCachePath, AVList p * String)} to determine the URL of any existing file names. If an existing file has expired, and removeIfExpired is * true, this removes the existing file. * - * @param fileStore the file store in which to look. - * @param fileName the file name to look for. If a file with this name does not exist in the store, this - * looks at the file's siblings for a match. + * @param fileStore the file store in which to look. + * @param fileName the file name to look for. If a file with this name does not exist in the store, this looks at + * the file's siblings for a match. * @param removeIfExpired true to remove the existing file, if it exists and is expired; false otherwise. - * @param expiryTime the time in milliseconds, before which a file is considered to be expired. + * @param expiryTime the time in milliseconds, before which a file is considered to be expired. * * @return whether a configuration file already exists which has not expired. * * @throws IllegalArgumentException if either the file store or file name are null. */ public static boolean hasDataConfigFile(FileStore fileStore, String fileName, boolean removeIfExpired, - long expiryTime) - { - if (fileStore == null) - { + long expiryTime) { + if (fileStore == null) { String message = Logging.getMessage("nullValue.FileStoreIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (fileName == null) - { + if (fileName == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -351,15 +315,13 @@ public static boolean hasDataConfigFile(FileStore fileStore, String fileName, bo // Look for an existing configuration file in the store. Return true if a configuration file does not exist, // or it has expired; otherwise return false. java.net.URL url = findExistingDataConfigFile(fileStore, fileName); - if (url != null && !WWIO.isFileOutOfDate(url, expiryTime)) - { + if (url != null && !WWIO.isFileOutOfDate(url, expiryTime)) { return true; } // A configuration file exists but it is expired. Remove the file and return false, indicating that there is // no configuration document. - if (url != null && removeIfExpired) - { + if (url != null && removeIfExpired) { fileStore.removeFile(url); String message = Logging.getMessage("generic.DataFileExpired", url); @@ -375,24 +337,21 @@ public static boolean hasDataConfigFile(FileStore fileStore, String fileName, bo * exist, this checks the siblings of the specified file for a configuration file match. * * @param fileStore the file store in which to look. - * @param fileName the file name to look for. If a file with this name does not exist in the store, this looks at - * the file's siblings for a match. + * @param fileName the file name to look for. If a file with this name does not exist in the store, this looks at + * the file's siblings for a match. * * @return the URL of an existing configuration file in the store, or null if none exists. * * @throws IllegalArgumentException if either the file store or file name are null. */ - public static java.net.URL findExistingDataConfigFile(FileStore fileStore, String fileName) - { - if (fileStore == null) - { + public static java.net.URL findExistingDataConfigFile(FileStore fileStore, String fileName) { + if (fileStore == null) { String message = Logging.getMessage("nullValue.FileStoreIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (fileName == null) - { + if (fileName == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -400,22 +359,19 @@ public static java.net.URL findExistingDataConfigFile(FileStore fileStore, Strin // Attempt to find the specified file name in the store. If it exists, then we've found a match and we're done. java.net.URL url = fileStore.findFile(fileName, false); - if (url != null) - { + if (url != null) { return url; } // If the specified name did not exist, then try to find any data configuration file under the file's parent // path. Find only the file names which are siblings of the specified file name. String path = WWIO.getParentFilePath(fileName); - if (path == null || path.length() == 0) - { + if (path == null || path.length() == 0) { return null; } String[] names = fileStore.listFileNames(path, new DataConfigurationFilter()); - if (names == null || names.length == 0) - { + if (names == null || names.length == 0) { return null; } @@ -432,18 +388,14 @@ public static java.net.URL findExistingDataConfigFile(FileStore fileStore, Strin * * @return a new ScheduledExecutorService appropriate for scheduling periodic resource checks. */ - public static ScheduledExecutorService createResourceRetrievalService(final String threadName) - { - ThreadFactory threadFactory = new ThreadFactory() - { - public Thread newThread(Runnable r) - { + public static ScheduledExecutorService createResourceRetrievalService(final String threadName) { + ThreadFactory threadFactory = new ThreadFactory() { + public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); thread.setPriority(Thread.MIN_PRIORITY); - if (threadName != null) - { + if (threadName != null) { thread.setName(threadName); } @@ -457,10 +409,10 @@ public Thread newThread(Runnable r) //**************************************************************// //******************** WMS Common Configuration **************// //**************************************************************// - /** * Appends WMS layer parameters as elements to a specified context. This appends elements for the following - * parameters: * * - * - * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * * * * @@ -257,11 +248,14 @@ public static void applyLightingDirectionalFromViewer(GL2 gl, int light, Vec4 di * * * - * - * + * + * + * + * * - *
                  Mapping
                  ParameterElement PathType
                  {@link + * parameters:
                  Mapping
                  ParameterElement + * PathType
                  {@link * AVKey#WMS_VERSION}Service/@versionString
                  {@link * AVKey#LAYER_NAMES}Service/LayerNamesString
                  {@link * AVKey#STYLE_NAMES}Service/StyleNamesString
                  {@link @@ -469,24 +421,21 @@ public Thread newThread(Runnable r) * AVKey#SERVICE}AVKey#GET_MAP_URLString
                  {@link * AVKey#DATASET_NAME}AVKey.LAYER_NAMESString
                  * - * @param params the key-value pairs which define the WMS layer configuration parameters. + * @param params the key-value pairs which define the WMS layer configuration parameters. * @param context the XML document root on which to append WMS layer configuration elements. * * @return a reference to context. * * @throws IllegalArgumentException if either the parameters or the context are null. */ - public static Element createWMSLayerConfigElements(AVList params, Element context) - { - if (params == null) - { + public static Element createWMSLayerConfigElements(AVList params, Element context) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -497,21 +446,18 @@ public static Element createWMSLayerConfigElements(AVList params, Element contex // Service properties. The service element may already exist, in which case we want to append the "URL" element // to the existing service element. Element el = WWXML.getElement(context, "Service", xpath); - if (el == null) - { + if (el == null) { el = WWXML.appendElementPath(context, "Service"); } // Try to get the SERVICE_NAME property, but default to "OGC:WMS". String s = AVListImpl.getStringValue(params, AVKey.SERVICE_NAME, OGCConstants.WMS_SERVICE_NAME); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { WWXML.setTextAttribute(el, "serviceName", s); } s = params.getStringValue(AVKey.WMS_VERSION); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { WWXML.setTextAttribute(el, "version", s); } @@ -523,11 +469,9 @@ public static Element createWMSLayerConfigElements(AVList params, Element contex // Since this is a WMS tiled image layer, we want to express the service URL as a GetMap URL. If we have a // GET_MAP_URL property, then remove any existing SERVICE property from the DOM document. s = params.getStringValue(AVKey.GET_MAP_URL); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { Element urlElement = WWXML.getElement(el, "URL", xpath); - if (urlElement != null) - { + if (urlElement != null) { el.removeChild(urlElement); } } @@ -537,7 +481,8 @@ public static Element createWMSLayerConfigElements(AVList params, Element contex /** * Appends WCS layer parameters as elements to a specified context. This appends elements for the following - * parameters: + *
                  Mapping
                  ParameterElement PathType
                  {@link + * parameters:
                  Mapping
                  ParameterElement + * PathType
                  {@link * AVKey#WCS_VERSION}Service/@versionString
                  {@link * AVKey#COVERAGE_IDENTIFIERS}Service/coverageIdentifiersString
                  {@link * AVKey#GET_COVERAGE_URL}Service/GetCoverageURLString
                  {@link @@ -545,24 +490,21 @@ public static Element createWMSLayerConfigElements(AVList params, Element contex * AVKey#SERVICE}AVKey#GET_COVERAGE_URLString
                  {@link * AVKey#DATASET_NAME}AVKey.COVERAGE_IDENTIFIERSString
                  * - * @param params the key-value pairs which define the WMS layer configuration parameters. + * @param params the key-value pairs which define the WMS layer configuration parameters. * @param context the XML document root on which to append WMS layer configuration elements. * * @return a reference to context. * * @throws IllegalArgumentException if either the parameters or the context are null. */ - public static Element createWCSLayerConfigElements(AVList params, Element context) - { - if (params == null) - { + public static Element createWCSLayerConfigElements(AVList params, Element context) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -573,21 +515,18 @@ public static Element createWCSLayerConfigElements(AVList params, Element contex // Service properties. The service element may already exist, in which case we want to append the "URL" element // to the existing service element. Element el = WWXML.getElement(context, "Service", xpath); - if (el == null) - { + if (el == null) { el = WWXML.appendElementPath(context, "Service"); } // Try to get the SERVICE_NAME property, but default to "OGC:WCS". String s = AVListImpl.getStringValue(params, AVKey.SERVICE_NAME, OGCConstants.WCS_SERVICE_NAME); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { WWXML.setTextAttribute(el, "serviceName", s); } s = params.getStringValue(AVKey.WCS_VERSION); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { WWXML.setTextAttribute(el, "version", s); } @@ -598,11 +537,9 @@ public static Element createWCSLayerConfigElements(AVList params, Element contex // Since this is a WCS tiled coverage, we want to express the service URL as a GetCoverage URL. If we have a // GET_COVERAGE_URL property, then remove any existing SERVICE property from the DOM document. s = params.getStringValue(AVKey.GET_COVERAGE_URL); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { Element urlElement = WWXML.getElement(el, "URL", xpath); - if (urlElement != null) - { + if (urlElement != null) { el.removeChild(urlElement); } } @@ -613,7 +550,8 @@ public static Element createWCSLayerConfigElements(AVList params, Element contex /** * Parses WMS layer parameters from the XML configuration document starting at domElement. This writes output as * key-value pairs to params. If a parameter from the XML document already exists in params, that parameter is - * ignored. Supported key and parameter names are: + * Level's expiryTime + * + * * + * gov.nasa.worldwind.geom.Sector} + * * + * gov.nasa.worldwind.geom.LatLon} + * + * *
                  Mapping
                  ParameterElement + * ignored. Supported key and parameter names are: + * *
                  Mapping
                  ParameterElement * PathType
                  {@link AVKey#WMS_VERSION}Service/@versionString
                  {@link AVKey#LAYER_NAMES}Service/LayerNamesString
                  {@link * AVKey#STYLE_NAMES}Service/StyleNamesString
                  {@link @@ -623,24 +561,20 @@ public static Element createWCSLayerConfigElements(AVList params, Element contex * AVKey#DATASET_NAME}AVKey.LAYER_NAMESString
                  * * @param domElement the XML document root to parse for WMS layer parameters. - * @param params the output key-value pairs which receive the WMS layer parameters. A null reference is - * permitted. + * @param params the output key-value pairs which receive the WMS layer parameters. A null reference is permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - public static AVList getWMSLayerConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + public static AVList getWMSLayerConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { params = new AVListImpl(); } @@ -652,36 +586,31 @@ public static AVList getWMSLayerConfigParams(Element domElement, AVList params) WWXML.checkAndSetStringParam(domElement, params, AVKey.STYLE_NAMES, "Service/StyleNames", xpath); WWXML.checkAndSetStringParam(domElement, params, AVKey.GET_MAP_URL, "Service/GetMapURL", xpath); WWXML.checkAndSetStringParam(domElement, params, AVKey.GET_CAPABILITIES_URL, "Service/GetCapabilitiesURL", - xpath); + xpath); params.setValue(AVKey.SERVICE, params.getValue(AVKey.GET_MAP_URL)); String serviceURL = params.getStringValue(AVKey.SERVICE); - if (serviceURL != null) - { + if (serviceURL != null) { params.setValue(AVKey.SERVICE, WWXML.fixGetMapString(serviceURL)); } // The dataset name is the layer-names string for WMS elevation models String layerNames = params.getStringValue(AVKey.LAYER_NAMES); - if (layerNames != null) - { + if (layerNames != null) { params.setValue(AVKey.DATASET_NAME, layerNames); } return params; } - public static AVList getWCSConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + public static AVList getWCSConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { params = new AVListImpl(); } @@ -690,39 +619,34 @@ public static AVList getWCSConfigParams(Element domElement, AVList params) // Need to determine these for URLBuilder construction. WWXML.checkAndSetStringParam(domElement, params, AVKey.WCS_VERSION, "Service/@version", xpath); WWXML.checkAndSetStringParam(domElement, params, AVKey.COVERAGE_IDENTIFIERS, "Service/CoverageIdentifiers", - xpath); + xpath); WWXML.checkAndSetStringParam(domElement, params, AVKey.GET_COVERAGE_URL, "Service/GetCoverageURL", xpath); WWXML.checkAndSetStringParam(domElement, params, AVKey.GET_CAPABILITIES_URL, "Service/GetCapabilitiesURL", - xpath); + xpath); params.setValue(AVKey.SERVICE, params.getValue(AVKey.GET_COVERAGE_URL)); String serviceURL = params.getStringValue(AVKey.SERVICE); - if (serviceURL != null) - { + if (serviceURL != null) { params.setValue(AVKey.SERVICE, WWXML.fixGetMapString(serviceURL)); } // The dataset name is the layer-names string for WMS elevation models String coverages = params.getStringValue(AVKey.COVERAGE_IDENTIFIERS); - if (coverages != null) - { + if (coverages != null) { params.setValue(AVKey.DATASET_NAME, coverages); } return params; } - public static AVList getWMSLayerConfigParams(WMSCapabilities caps, String[] formatOrderPreference, AVList params) - { - if (caps == null) - { + public static AVList getWMSLayerConfigParams(WMSCapabilities caps, String[] formatOrderPreference, AVList params) { + if (caps == null) { String message = Logging.getMessage("nullValue.WMSCapabilities"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -730,47 +654,40 @@ public static AVList getWMSLayerConfigParams(WMSCapabilities caps, String[] form String layerNames = params.getStringValue(AVKey.LAYER_NAMES); String styleNames = params.getStringValue(AVKey.STYLE_NAMES); - if (layerNames == null || layerNames.length() == 0) - { + if (layerNames == null || layerNames.length() == 0) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String[] names = layerNames.split(","); - if (names == null || names.length == 0) - { + if (names == null || names.length == 0) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String coordinateSystem = params.getStringValue(AVKey.COORDINATE_SYSTEM); - if (WWUtil.isEmpty(coordinateSystem)) - { - for (String name : names) - { + if (WWUtil.isEmpty(coordinateSystem)) { + for (String name : names) { WMSLayerCapabilities layerCaps = caps.getLayerByName(name); - if (layerCaps == null) - { + if (layerCaps == null) { Logging.logger().warning(Logging.getMessage("WMS.LayerNameMissing", name)); continue; } - if (layerCaps.hasCoordinateSystem("EPSG:4326")) - { + if (layerCaps.hasCoordinateSystem("EPSG:4326")) { coordinateSystem = "EPSG:4326"; break; // this assumes that the CS is available for all the layers in layerNames - } - else if (layerCaps.hasCoordinateSystem("CRS:84")) - { + } else if (layerCaps.hasCoordinateSystem("CRS:84")) { coordinateSystem = "CRS:84"; break; // this assumes that the CS is available for all the layers in layerNames } } - if (!WWUtil.isEmpty(coordinateSystem)) + if (!WWUtil.isEmpty(coordinateSystem)) { params.setValue(AVKey.COORDINATE_SYSTEM, coordinateSystem); + } } // Define the DISPLAY_NAME and DATASET_NAME from the WMS layer names and styles. @@ -779,65 +696,54 @@ else if (layerCaps.hasCoordinateSystem("CRS:84")) // Get the EXPIRY_TIME from the WMS layer last update time. Long lastUpdate = caps.getLayerLatestLastUpdateTime(names); - if (lastUpdate != null) - { + if (lastUpdate != null) { params.setValue(AVKey.EXPIRY_TIME, lastUpdate); } // Get the GET_MAP_URL from the WMS getMapRequest URL. String mapRequestURIString = caps.getRequestURL("GetMap", "http", "get"); - if (params.getValue(AVKey.GET_MAP_URL) == null) - { + if (params.getValue(AVKey.GET_MAP_URL) == null) { params.setValue(AVKey.GET_MAP_URL, mapRequestURIString); } mapRequestURIString = params.getStringValue(AVKey.GET_MAP_URL); // Throw an exception if there's no GET_MAP_URL property, or no getMapRequest URL in the WMS Capabilities. - if (mapRequestURIString == null || mapRequestURIString.length() == 0) - { + if (mapRequestURIString == null || mapRequestURIString.length() == 0) { Logging.logger().severe("WMS.RequestMapURLMissing"); throw new WWRuntimeException(Logging.getMessage("WMS.RequestMapURLMissing")); } // Get the GET_CAPABILITIES_URL from the WMS getCapabilitiesRequest URL. String capsRequestURIString = caps.getRequestURL("GetCapabilities", "http", "get"); - if (params.getValue(AVKey.GET_CAPABILITIES_URL) == null) - { + if (params.getValue(AVKey.GET_CAPABILITIES_URL) == null) { params.setValue(AVKey.GET_CAPABILITIES_URL, capsRequestURIString); } // Define the SERVICE from the GET_MAP_URL property. params.setValue(AVKey.SERVICE, params.getValue(AVKey.GET_MAP_URL)); String serviceURL = params.getStringValue(AVKey.SERVICE); - if (serviceURL != null) - { + if (serviceURL != null) { params.setValue(AVKey.SERVICE, WWXML.fixGetMapString(serviceURL)); } // Define the SERVICE_NAME as the standard OGC WMS service string. - if (params.getValue(AVKey.SERVICE_NAME) == null) - { + if (params.getValue(AVKey.SERVICE_NAME) == null) { params.setValue(AVKey.SERVICE_NAME, OGCConstants.WMS_SERVICE_NAME); } // Define the WMS VERSION as the version fetched from the Capabilities document. String versionString = caps.getVersion(); - if (params.getValue(AVKey.WMS_VERSION) == null) - { + if (params.getValue(AVKey.WMS_VERSION) == null) { params.setValue(AVKey.WMS_VERSION, versionString); } // Form the cache path DATA_CACHE_NAME from a set of unique WMS parameters. - if (params.getValue(AVKey.DATA_CACHE_NAME) == null) - { - try - { + if (params.getValue(AVKey.DATA_CACHE_NAME) == null) { + try { URI mapRequestURI = new URI(mapRequestURIString); String cacheName = WWIO.formPath(mapRequestURI.getAuthority(), mapRequestURI.getPath(), layerNames, - styleNames); + styleNames); params.setValue(AVKey.DATA_CACHE_NAME, cacheName); - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { String message = Logging.getMessage("WMS.RequestMapURLBad", mapRequestURIString); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message); @@ -845,28 +751,23 @@ else if (layerCaps.hasCoordinateSystem("CRS:84")) } // Determine image format to request. - if (params.getStringValue(AVKey.IMAGE_FORMAT) == null) - { + if (params.getStringValue(AVKey.IMAGE_FORMAT) == null) { String imageFormat = chooseImageFormat(caps.getImageFormats().toArray(), formatOrderPreference); params.setValue(AVKey.IMAGE_FORMAT, imageFormat); } // Throw an exception if we cannot determine an image format to request. - if (params.getStringValue(AVKey.IMAGE_FORMAT) == null) - { + if (params.getStringValue(AVKey.IMAGE_FORMAT) == null) { Logging.logger().severe("WMS.NoImageFormats"); throw new WWRuntimeException(Logging.getMessage("WMS.NoImageFormats")); } // Determine bounding sector. Sector sector = (Sector) params.getValue(AVKey.SECTOR); - if (sector == null) - { - for (String name : names) - { + if (sector == null) { + for (String name : names) { Sector layerSector = caps.getLayerByName(name).getGeographicBoundingBox(); - if (layerSector == null) - { + if (layerSector == null) { Logging.logger().log(java.util.logging.Level.SEVERE, "WMS.NoGeographicBoundingBoxForLayer", name); continue; } @@ -874,8 +775,7 @@ else if (layerCaps.hasCoordinateSystem("CRS:84")) sector = Sector.union(sector, layerSector); } - if (sector == null) - { + if (sector == null) { Logging.logger().severe("WMS.NoGeographicBoundingBox"); throw new WWRuntimeException(Logging.getMessage("WMS.NoGeographicBoundingBox")); } @@ -883,28 +783,23 @@ else if (layerCaps.hasCoordinateSystem("CRS:84")) } // TODO: adjust for subsetable, fixedimage, etc. - return params; } - public static AVList getWCSConfigParameters(WCS100Capabilities caps, WCS100DescribeCoverage coverage, AVList params) - { - if (caps == null) - { + public static AVList getWCSConfigParameters(WCS100Capabilities caps, WCS100DescribeCoverage coverage, AVList params) { + if (caps == null) { String message = Logging.getMessage("nullValue.WMSCapabilities"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (coverage == null) - { + if (coverage == null) { String message = Logging.getMessage("nullValue.WCSDescribeCoverage"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -921,44 +816,35 @@ public static AVList getWCSConfigParameters(WCS100Capabilities caps, WCS100Descr params.setValue(AVKey.SERVICE, params.getValue(AVKey.GET_COVERAGE_URL)); String serviceURL = params.getStringValue(AVKey.SERVICE); - if (serviceURL != null) - { + if (serviceURL != null) { params.setValue(AVKey.SERVICE, WWXML.fixGetMapString(serviceURL)); } String coverages = params.getStringValue(AVKey.COVERAGE_IDENTIFIERS); - if (coverages != null) - { + if (coverages != null) { params.setValue(AVKey.DATASET_NAME, coverages); } // Form the cache path DATA_CACHE_NAME from a set of unique WMS parameters. - if (params.getValue(AVKey.DATA_CACHE_NAME) == null) - { - try - { + if (params.getValue(AVKey.DATA_CACHE_NAME) == null) { + try { URI mapRequestURI = new URI(params.getStringValue(AVKey.GET_COVERAGE_URL)); String cacheName = WWIO.formPath(mapRequestURI.getAuthority(), mapRequestURI.getPath(), - params.getStringValue(AVKey.COVERAGE_IDENTIFIERS)); + params.getStringValue(AVKey.COVERAGE_IDENTIFIERS)); params.setValue(AVKey.DATA_CACHE_NAME, cacheName); - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { String message = Logging.getMessage("WCS.RequestMapURLBad", - params.getStringValue(AVKey.GET_COVERAGE_URL)); + params.getStringValue(AVKey.GET_COVERAGE_URL)); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); throw new WWRuntimeException(message); } } - for (String format : offering.getSupportedFormats().getStrings()) - { - if (format.toLowerCase().contains("image/tiff")) - { + for (String format : offering.getSupportedFormats().getStrings()) { + if (format.toLowerCase().contains("image/tiff")) { params.setValue(AVKey.IMAGE_FORMAT, format); break; - } - else if (format.toLowerCase().contains("tiff")) // lots of variants in use, so find one + } else if (format.toLowerCase().contains("tiff")) // lots of variants in use, so find one { params.setValue(AVKey.IMAGE_FORMAT, format); break; @@ -967,42 +853,34 @@ else if (format.toLowerCase().contains("tiff")) // lots of variants in use, so f // Determine bounding sector. WCS100LonLatEnvelope envelope = offering.getLonLatEnvelope(); - if (envelope != null) - { + if (envelope != null) { double[] sw = envelope.getPositions().get(0).getPos2(); double[] ne = envelope.getPositions().get(1).getPos2(); - if (sw != null && ne != null) - { + if (sw != null && ne != null) { params.setValue(AVKey.SECTOR, Sector.fromDegreesAndClamp(sw[1], ne[1], sw[0], ne[0])); } } String epsg4326 = "EPSG:4326"; String crs = null; - if (offering.getSupportedCRSs() != null) - { - if (offering.getSupportedCRSs().getRequestResponseCRSs().contains(epsg4326)) - { + if (offering.getSupportedCRSs() != null) { + if (offering.getSupportedCRSs().getRequestResponseCRSs().contains(epsg4326)) { crs = epsg4326; } else if (offering.getSupportedCRSs().getRequestCRSs().contains(epsg4326) - && offering.getSupportedCRSs().getResponseCRSs().contains(epsg4326)) - { + && offering.getSupportedCRSs().getResponseCRSs().contains(epsg4326)) { crs = epsg4326; } } - if (crs != null) - { + if (crs != null) { params.setValue(AVKey.COORDINATE_SYSTEM, crs); } WCS100Values nullValues = offering.getRangeSet().getRangeSet().getNullValues(); - if (nullValues != null && nullValues.getSingleValues() != null && nullValues.getSingleValues().size() > 0) - { + if (nullValues != null && nullValues.getSingleValues() != null && nullValues.getSingleValues().size() > 0) { Double nullValue = nullValues.getSingleValues().get(0).getSingleValue(); - if (nullValue != null) - { + if (nullValue != null) { params.setValue(AVKey.MISSING_DATA_SIGNAL, nullValue); } } @@ -1020,43 +898,33 @@ else if (format.toLowerCase().contains("tiff")) // lots of variants in use, so f * * @throws IllegalArgumentException if the parameter list is null. */ - public static URL getOGCGetCapabilitiesURL(AVList params) - { - if (params == null) - { + public static URL getOGCGetCapabilitiesURL(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String uri = params.getStringValue(AVKey.GET_CAPABILITIES_URL); - if (uri == null || uri.length() == 0) - { + if (uri == null || uri.length() == 0) { return null; } String service = params.getStringValue(AVKey.SERVICE_NAME); - if (service == null || service.length() == 0) - { + if (service == null || service.length() == 0) { return null; } - try - { - if (service.equals(OGCConstants.WMS_SERVICE_NAME)) - { + try { + if (service.equals(OGCConstants.WMS_SERVICE_NAME)) { service = "WMS"; CapabilitiesRequest request = new CapabilitiesRequest(new URI(uri), service); return request.getUri().toURL(); } - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { String message = Logging.getMessage("generic.URIInvalid", uri); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { String message = Logging.getMessage("generic.URIInvalid", uri); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } @@ -1075,43 +943,34 @@ public static URL getOGCGetCapabilitiesURL(AVList params) * * @throws IllegalArgumentException if the parameter list is null. */ - public static String[] getOGCLayerNames(AVList params) - { - if (params == null) - { + public static String[] getOGCLayerNames(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String s = params.getStringValue(AVKey.LAYER_NAMES); - if (s == null || s.length() == 0) - { + if (s == null || s.length() == 0) { return null; } return s.split(","); } - protected static String chooseImageFormat(Object[] formats, String[] formatOrderPreference) - { - if (formats == null || formats.length == 0) - { + protected static String chooseImageFormat(Object[] formats, String[] formatOrderPreference) { + if (formats == null || formats.length == 0) { return null; } // No preferred formats specified; just use the first in the caps list. - if (formatOrderPreference == null || formatOrderPreference.length == 0) - { + if (formatOrderPreference == null || formatOrderPreference.length == 0) { return formats[0].toString(); } - for (String s : formatOrderPreference) - { - for (Object f : formats) - { - if (f.toString().equalsIgnoreCase(s)) - { + for (String s : formatOrderPreference) { + for (Object f : formats) { + if (f.toString().equalsIgnoreCase(s)) { return f.toString(); } } @@ -1120,16 +979,13 @@ protected static String chooseImageFormat(Object[] formats, String[] formatOrder return formats[0].toString(); // No preferred formats recognized; just use the first in the caps list. } - protected static String makeTitle(WMSCapabilities caps, String layerNames, String styleNames) - { + protected static String makeTitle(WMSCapabilities caps, String layerNames, String styleNames) { String[] lNames = layerNames.split(","); String[] sNames = styleNames != null ? styleNames.split(",") : null; StringBuilder sb = new StringBuilder(); - for (int i = 0; i < lNames.length; i++) - { - if (sb.length() > 0) - { + for (int i = 0; i < lNames.length; i++) { + if (sb.length() > 0) { sb.append(", "); } @@ -1138,15 +994,13 @@ protected static String makeTitle(WMSCapabilities caps, String layerNames, Strin String layerTitle = layer.getTitle(); sb.append(layerTitle != null ? layerTitle : layerName); - if (sNames == null || sNames.length <= i) - { + if (sNames == null || sNames.length <= i) { continue; } String styleName = sNames[i]; WMSLayerStyle style = layer.getStyleByName(styleName); - if (style == null) - { + if (style == null) { continue; } @@ -1181,7 +1035,6 @@ protected static String makeTitle(WMSCapabilities caps, String layerNames, Strin // // return new int[] {width, height}; //} - //protected static LatLon getLayerLatLon(Element layer, String path) //{ // XPath xpath = WWXML.makeXPath(); @@ -1197,28 +1050,25 @@ protected static String makeTitle(WMSCapabilities caps, String layerNames, Strin // // return LatLon.fromDegrees(latDegrees, lonDegrees); //} - //protected static int computeLayerNumLevels(LatLon minDelta, LatLon maxDelta) //{ // return Math.max( // computeLayerNumLevels(minDelta.getLatitude(), maxDelta.getLatitude()), // computeLayerNumLevels(minDelta.getLongitude(), maxDelta.getLongitude())); //} - //protected static int computeLayerNumLevels(Angle minDelta, Angle maxDelta) //{ // double log2MinDelta = WWMath.logBase2(minDelta.getDegrees()); // double log2MaxDelta = WWMath.logBase2(maxDelta.getDegrees()); // return 1 + (int) Math.round(log2MaxDelta - log2MinDelta); //} - //**************************************************************// //******************** LevelSet Common Configuration *********// //**************************************************************// - /** * Appends LevelSet configuration parameters as elements to the specified context. This appends elements for the - * following parameters: * * + * gov.nasa.worldwind.geom.Sector} + * * + * gov.nasa.worldwind.geom.LatLon} + * * * * @@ -1360,24 +1204,21 @@ public static Element createLevelSetConfigElements(AVList params, Element contex * milliseconds
                  Mapping
                  KeyNamePath
                  {@link + * following parameters: + * * * + * gov.nasa.worldwind.geom.Sector} + * * + * gov.nasa.worldwind.geom.LatLon} + * * * * * *
                  Mapping
                  KeyNamePath
                  {@link * gov.nasa.worldwind.avlist.AVKey#DATASET_NAME}DatasetNameString
                  {@link * gov.nasa.worldwind.avlist.AVKey#DATA_CACHE_NAME}DataCacheNameString
                  {@link * gov.nasa.worldwind.avlist.AVKey#SERVICE}Service/URLString
                  {@link @@ -1229,33 +1079,32 @@ protected static String makeTitle(WMSCapabilities caps, String layerNames, Strin * gov.nasa.worldwind.avlist.AVKey#NUM_EMPTY_LEVELS}NumLevels/@numEmptyInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#INACTIVE_LEVELS}NumLevels/@inactiveString
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR}Sector{@link - * gov.nasa.worldwind.geom.Sector}
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR_RESOLUTION_LIMITS}SectorResolutionLimit
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR_RESOLUTION_LIMITS}SectorResolutionLimit{@link LevelSet.SectorResolution}
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_ORIGIN}TileOrigin/LatLon{@link - * gov.nasa.worldwind.geom.LatLon}
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_WIDTH}TileSize/Dimension/@widthInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_WIDTH}TileSize/Dimension/@widthInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_HEIGHT}TileSize/Dimension/@heightInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#LEVEL_ZERO_TILE_DELTA}LastUpdateLatLon
                  {@link gov.nasa.worldwind.avlist.AVKey#MAX_ABSENT_TILE_ATTEMPTS}MaxAbsentTileAttemptsInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#MIN_ABSENT_TILE_CHECK_INTERVAL}MinAbsentTileCheckIntervalInteger
                  * - * @param params the key-value pairs which define the LevelSet configuration parameters. + * @param params the key-value pairs which define the LevelSet configuration parameters. * @param context the XML document root on which to append LevelSet configuration elements. * * @return a reference to context. * * @throws IllegalArgumentException if either the parameters or the context are null. */ - public static Element createLevelSetConfigElements(AVList params, Element context) - { - if (params == null) - { + public static Element createLevelSetConfigElements(AVList params, Element context) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (context == null) - { + if (context == null) { String message = Logging.getMessage("nullValue.ContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1267,13 +1116,11 @@ public static Element createLevelSetConfigElements(AVList params, Element contex // Service properties. String s = params.getStringValue(AVKey.SERVICE); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { // The service element may already exist, in which case we want to append the "URL" element to the existing // service element. Element el = WWXML.getElement(context, "Service", null); - if (el == null) - { + if (el == null) { el = WWXML.appendElementPath(context, "Service"); } WWXML.appendText(el, "URL", s); @@ -1287,8 +1134,7 @@ public static Element createLevelSetConfigElements(AVList params, Element contex // Tile structure properties. Integer numLevels = AVListImpl.getIntegerValue(params, AVKey.NUM_LEVELS); - if (numLevels != null) - { + if (numLevels != null) { Element el = WWXML.appendElementPath(context, "NumLevels"); WWXML.setIntegerAttribute(el, "count", numLevels); @@ -1296,21 +1142,19 @@ public static Element createLevelSetConfigElements(AVList params, Element contex WWXML.setIntegerAttribute(el, "numEmpty", i); s = params.getStringValue(AVKey.INACTIVE_LEVELS); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { WWXML.setTextAttribute(el, "inactive", s); } } WWXML.checkAndAppendSectorElement(params, AVKey.SECTOR, context, "Sector"); WWXML.checkAndAppendSectorResolutionElement(params, AVKey.SECTOR_RESOLUTION_LIMITS, context, - "SectorResolutionLimit"); + "SectorResolutionLimit"); WWXML.checkAndAppendLatLonElement(params, AVKey.TILE_ORIGIN, context, "TileOrigin/LatLon"); Integer tileWidth = AVListImpl.getIntegerValue(params, AVKey.TILE_WIDTH); Integer tileHeight = AVListImpl.getIntegerValue(params, AVKey.TILE_HEIGHT); - if (tileWidth != null && tileHeight != null) - { + if (tileWidth != null && tileHeight != null) { Element el = WWXML.appendElementPath(context, "TileSize/Dimension"); WWXML.setIntegerAttribute(el, "width", tileWidth); WWXML.setIntegerAttribute(el, "height", tileHeight); @@ -1319,12 +1163,10 @@ public static Element createLevelSetConfigElements(AVList params, Element contex WWXML.checkAndAppendLatLonElement(params, AVKey.LEVEL_ZERO_TILE_DELTA, context, "LevelZeroTileDelta/LatLon"); // Retrieval properties. - if (params.getValue(AVKey.MAX_ABSENT_TILE_ATTEMPTS) != null || - params.getValue(AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL) != null) - { + if (params.getValue(AVKey.MAX_ABSENT_TILE_ATTEMPTS) != null + || params.getValue(AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL) != null) { Element el = WWXML.getElement(context, "AbsentTiles", null); - if (el == null) - { + if (el == null) { el = WWXML.appendElementPath(context, "AbsentTiles"); } @@ -1350,9 +1192,11 @@ public static Element createLevelSetConfigElements(AVList params, Element contex * gov.nasa.worldwind.avlist.AVKey#NUM_EMPTY_LEVELS}
                  NumLevels/@numEmptyInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#INACTIVE_LEVELS}NumLevels/@inactiveString
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR}Sector{@link - * gov.nasa.worldwind.geom.Sector}
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR_RESOLUTION_LIMITS}SectorResolutionLimit
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR_RESOLUTION_LIMITS}SectorResolutionLimit{@link LevelSet.SectorResolution}
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_ORIGIN}TileOrigin/LatLon{@link - * gov.nasa.worldwind.geom.LatLon}
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_WIDTH}TileSize/Dimension/@widthInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_WIDTH}TileSize/Dimension/@widthInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_HEIGHT}TileSize/Dimension/@heightInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#LEVEL_ZERO_TILE_DELTA}LastUpdateLatLon
                  {@link gov.nasa.worldwind.avlist.AVKey#MAX_ABSENT_TILE_ATTEMPTS}AbsentTiles/MaxAttemptsInteger
                  * * @param domElement the XML document root to parse for LevelSet configuration parameters. - * @param params the output key-value pairs which receive the LevelSet configuration parameters. A null - * reference is permitted. + * @param params the output key-value pairs which receive the LevelSet configuration parameters. A null reference is + * permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - public static AVList getLevelSetConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + public static AVList getLevelSetConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { params = new AVListImpl(); } @@ -1403,18 +1244,18 @@ public static AVList getLevelSetConfigParams(Element domElement, AVList params) WWXML.checkAndSetStringParam(domElement, params, AVKey.INACTIVE_LEVELS, "NumLevels/@inactive", xpath); WWXML.checkAndSetSectorParam(domElement, params, AVKey.SECTOR, "Sector", xpath); WWXML.checkAndSetSectorResolutionParam(domElement, params, AVKey.SECTOR_RESOLUTION_LIMITS, - "SectorResolutionLimit", xpath); + "SectorResolutionLimit", xpath); WWXML.checkAndSetLatLonParam(domElement, params, AVKey.TILE_ORIGIN, "TileOrigin/LatLon", xpath); WWXML.checkAndSetIntegerParam(domElement, params, AVKey.TILE_WIDTH, "TileSize/Dimension/@width", xpath); WWXML.checkAndSetIntegerParam(domElement, params, AVKey.TILE_HEIGHT, "TileSize/Dimension/@height", xpath); WWXML.checkAndSetLatLonParam(domElement, params, AVKey.LEVEL_ZERO_TILE_DELTA, "LevelZeroTileDelta/LatLon", - xpath); + xpath); // Retrieval properties. WWXML.checkAndSetIntegerParam(domElement, params, AVKey.MAX_ABSENT_TILE_ATTEMPTS, - "AbsentTiles/MaxAttempts", xpath); + "AbsentTiles/MaxAttempts", xpath); WWXML.checkAndSetTimeParamAsInteger(domElement, params, AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL, - "AbsentTiles/MinCheckInterval/Time", xpath); + "AbsentTiles/MinCheckInterval/Time", xpath); return params; } @@ -1429,37 +1270,39 @@ public static AVList getLevelSetConfigParams(Element domElement, AVList params) *
                  {@link gov.nasa.worldwind.avlist.AVKey#DATA_CACHE_NAME}First Level's * cacheNameString
                  {@link gov.nasa.worldwind.avlist.AVKey#SERVICE}First Level's * serviceString
                  {@link gov.nasa.worldwind.avlist.AVKey#EXPIRY_TIME}First - * Level's expiryTimeLong
                  {@link gov.nasa.worldwind.avlist.AVKey#FORMAT_SUFFIX}FirstLevel's - * formatSuffixString
                  {@link gov.nasa.worldwind.avlist.AVKey#NUM_LEVELS}numLevelsInteger
                  Long
                  {@link gov.nasa.worldwind.avlist.AVKey#FORMAT_SUFFIX}FirstLevel's + * formatSuffixString
                  {@link gov.nasa.worldwind.avlist.AVKey#NUM_LEVELS}numLevelsInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#NUM_EMPTY_LEVELS}1 + index of first non-empty * LevelInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#INACTIVE_LEVELS}Comma * delimited string of Level numbersString
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR}sector{@link - * gov.nasa.worldwind.geom.Sector}
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR_RESOLUTION_LIMITS}sectorLevelLimits
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR_RESOLUTION_LIMITS}sectorLevelLimits{@link LevelSet.SectorResolution}
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_ORIGIN}tileOrigin{@link - * gov.nasa.worldwind.geom.LatLon}
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_WIDTH}First - * Level's tileWidthInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_HEIGHT}First - * Level's tileHeightInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#LEVEL_ZERO_TILE_DELTA}levelZeroTileDeltaLatLon
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_WIDTH}First Level's + * tileWidthInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_HEIGHT}First + * Level's tileHeightInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#LEVEL_ZERO_TILE_DELTA}levelZeroTileDeltaLatLon
                  * * @param levelSet the LevelSet reference to gather configuration parameters from. - * @param params the output key-value pairs which receive the LevelSet configuration parameters. A null reference - * is permitted. + * @param params the output key-value pairs which receive the LevelSet configuration parameters. A null reference is + * permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - public static AVList getLevelSetConfigParams(LevelSet levelSet, AVList params) - { - if (levelSet == null) - { + public static AVList getLevelSetConfigParams(LevelSet levelSet, AVList params) { + if (levelSet == null) { String message = Logging.getMessage("nullValue.LevelSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { params = new AVListImpl(); } @@ -1467,129 +1310,105 @@ public static AVList getLevelSetConfigParams(LevelSet levelSet, AVList params) // Title and cache name properties. String s = params.getStringValue(AVKey.DATASET_NAME); - if (s == null || s.length() == 0) - { + if (s == null || s.length() == 0) { s = firstLevel.getDataset(); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { params.setValue(AVKey.DATASET_NAME, s); } } s = params.getStringValue(AVKey.DATA_CACHE_NAME); - if (s == null || s.length() == 0) - { + if (s == null || s.length() == 0) { s = firstLevel.getCacheName(); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { params.setValue(AVKey.DATA_CACHE_NAME, s); } } // Service properties. s = params.getStringValue(AVKey.SERVICE); - if (s == null || s.length() == 0) - { + if (s == null || s.length() == 0) { s = firstLevel.getService(); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { params.setValue(AVKey.SERVICE, s); } } Object o = params.getValue(AVKey.EXPIRY_TIME); - if (o == null) - { + if (o == null) { // If the expiry time is zero or negative, then treat it as an uninitialized value. long l = firstLevel.getExpiryTime(); - if (l > 0) - { + if (l > 0) { params.setValue(AVKey.EXPIRY_TIME, l); } } // Image format properties. s = params.getStringValue(AVKey.FORMAT_SUFFIX); - if (s == null || s.length() == 0) - { + if (s == null || s.length() == 0) { s = firstLevel.getFormatSuffix(); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { params.setValue(AVKey.FORMAT_SUFFIX, s); } } // Tile structure properties. o = params.getValue(AVKey.NUM_LEVELS); - if (o == null) - { + if (o == null) { params.setValue(AVKey.NUM_LEVELS, levelSet.getNumLevels()); } o = params.getValue(AVKey.NUM_EMPTY_LEVELS); - if (o == null) - { + if (o == null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, getNumEmptyLevels(levelSet)); } s = params.getStringValue(AVKey.INACTIVE_LEVELS); - if (s == null || s.length() == 0) - { + if (s == null || s.length() == 0) { s = getInactiveLevels(levelSet); - if (s != null && s.length() > 0) - { + if (s != null && s.length() > 0) { params.setValue(AVKey.INACTIVE_LEVELS, s); } } o = params.getValue(AVKey.SECTOR); - if (o == null) - { + if (o == null) { Sector sector = levelSet.getSector(); - if (sector != null) - { + if (sector != null) { params.setValue(AVKey.SECTOR, sector); } } o = params.getValue(AVKey.SECTOR_RESOLUTION_LIMITS); - if (o == null) - { + if (o == null) { LevelSet.SectorResolution[] srs = levelSet.getSectorLevelLimits(); - if (srs != null && srs.length > 0) - { + if (srs != null && srs.length > 0) { params.setValue(AVKey.SECTOR_RESOLUTION_LIMITS, srs); } } o = params.getValue(AVKey.TILE_ORIGIN); - if (o == null) - { + if (o == null) { LatLon ll = levelSet.getTileOrigin(); - if (ll != null) - { + if (ll != null) { params.setValue(AVKey.TILE_ORIGIN, ll); } } o = params.getValue(AVKey.TILE_WIDTH); - if (o == null) - { + if (o == null) { params.setValue(AVKey.TILE_WIDTH, firstLevel.getTileWidth()); } o = params.getValue(AVKey.TILE_HEIGHT); - if (o == null) - { + if (o == null) { params.setValue(AVKey.TILE_HEIGHT, firstLevel.getTileHeight()); } o = params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA); - if (o == null) - { + if (o == null) { LatLon ll = levelSet.getLevelZeroTileDelta(); - if (ll != null) - { + if (ll != null) { params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, ll); } } @@ -1597,17 +1416,13 @@ public static AVList getLevelSetConfigParams(LevelSet levelSet, AVList params) // Note: retrieval properties MAX_ABSENT_TILE_ATTEMPTS and MIN_ABSENT_TILE_CHECK_INTERVAL are initialized // through the AVList constructor on LevelSet and Level. Rather than expose those properties in Level, we rely // on the caller to gather those properties via the AVList used to construct the LevelSet. - return params; } - protected static int getNumEmptyLevels(LevelSet levelSet) - { + protected static int getNumEmptyLevels(LevelSet levelSet) { int i; - for (i = 0; i < levelSet.getNumLevels(); i++) - { - if (!levelSet.getLevel(i).isEmpty()) - { + for (i = 0; i < levelSet.getNumLevels(); i++) { + if (!levelSet.getLevel(i).isEmpty()) { break; } } @@ -1615,15 +1430,11 @@ protected static int getNumEmptyLevels(LevelSet levelSet) return i; } - protected static String getInactiveLevels(LevelSet levelSet) - { + protected static String getInactiveLevels(LevelSet levelSet) { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < levelSet.getNumLevels(); i++) - { - if (!levelSet.getLevel(i).isActive()) - { - if (sb.length() > 0) - { + for (int i = 0; i < levelSet.getNumLevels(); i++) { + if (!levelSet.getLevel(i).isActive()) { + if (sb.length() > 0) { sb.append(","); } sb.append(i); @@ -1636,7 +1447,6 @@ protected static String getInactiveLevels(LevelSet levelSet) //**************************************************************// //******************** Installed DataDescriptor Configuration // //**************************************************************// - /** * Returns true if a specified DOM document is a DataDescriptor configuration document, and false otherwise. * @@ -1646,10 +1456,8 @@ protected static String getInactiveLevels(LevelSet levelSet) * * @throws IllegalArgumentException if document is null. */ - public static boolean isInstalledDataDescriptorConfigDocument(Element domElement) - { - if (domElement == null) - { + public static boolean isInstalledDataDescriptorConfigDocument(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1667,14 +1475,12 @@ public static boolean isInstalledDataDescriptorConfigDocument(Element domElement * @param domElement DataDescriptor document to transform. * * @return standard Layer or ElevationModel document, or null if the DataDescriptor cannot be transformed to a - * standard document. + * standard document. * * @throws IllegalArgumentException if the document is null. */ - public static Document transformInstalledDataDescriptorConfigDocument(Element domElement) - { - if (domElement == null) - { + public static Document transformInstalledDataDescriptorConfigDocument(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1683,8 +1489,7 @@ public static Document transformInstalledDataDescriptorConfigDocument(Element do XPath xpath = WWXML.makeXPath(); Element[] els = WWXML.getElements(domElement, "/dataDescriptor/property[@name=\"dataSet\"]", xpath); - if (els == null || els.length == 0) - { + if (els == null || els.length == 0) { return null; } @@ -1695,21 +1500,17 @@ public static Document transformInstalledDataDescriptorConfigDocument(Element do return outDoc; } - protected static void transformDataDescriptorDataSet(Element context, Document outDoc, XPath xpath) - { + protected static void transformDataDescriptorDataSet(Element context, Document outDoc, XPath xpath) { String s = WWXML.getText(context, "property[@name=\"gov.nasa.worldwind.avkey.DataType\"]", xpath); // ElevationModel output. - if (s != null && s.equals("gov.nasa.worldwind.avkey.TiledElevations")) - { + if (s != null && s.equals("gov.nasa.worldwind.avkey.TiledElevations")) { Element el = WWXML.setDocumentElement(outDoc, "ElevationModel"); WWXML.setIntegerAttribute(el, "version", 1); transformDataDescriptorCommonElements(context, el, xpath); transformDataDescriptorElevationModelElements(context, el, xpath); - } - // Default to Layer output. - else - { + } // Default to Layer output. + else { Element el = WWXML.setDocumentElement(outDoc, "Layer"); WWXML.setIntegerAttribute(el, "version", 1); WWXML.setTextAttribute(el, "layerType", "TiledImageLayer"); @@ -1718,12 +1519,10 @@ protected static void transformDataDescriptorDataSet(Element context, Document o } } - protected static void transformDataDescriptorCommonElements(Element context, Element outElem, XPath xpath) - { + protected static void transformDataDescriptorCommonElements(Element context, Element outElem, XPath xpath) { // Display name and datset name properties. String s = WWXML.getText(context, "property[@name=\"gov.nasa.worldwind.avkey.DatasetNameKey\"]", xpath); - if (s != null && s.length() != 0) - { + if (s != null && s.length() != 0) { WWXML.appendText(outElem, "DisplayName", s); WWXML.appendText(outElem, "DatasetName", s); } @@ -1736,16 +1535,14 @@ protected static void transformDataDescriptorCommonElements(Element context, Ele // Image format properties. s = WWXML.getText(context, "property[@name=\"gov.nasa.worldwind.avkey.FormatSuffixKey\"]", xpath); - if (s != null && s.length() != 0) - { + if (s != null && s.length() != 0) { WWXML.appendText(outElem, "FormatSuffix", s); // DataDescriptor documents contain a format suffix, but not image format type. Convert the format suffix // to a mime type, then use it to populate the ImageFormat and AvailableImageFormat elements in the // transformed Layer or ElevationModel configuration document. String mimeType = WWIO.makeMimeTypeForSuffix(s); - if (mimeType != null && mimeType.length() != 0) - { + if (mimeType != null && mimeType.length() != 0) { WWXML.appendText(outElem, "ImageFormat", mimeType); WWXML.appendText(outElem, "AvailableImageFormats/ImageFormat", mimeType); } @@ -1754,9 +1551,8 @@ protected static void transformDataDescriptorCommonElements(Element context, Ele // Tile structure properties. Integer numLevels = WWXML.getInteger(context, "property[@name=\"gov.nasa.worldwind.avkey.NumLevels\"]", xpath); Integer numEmptyLevels = WWXML.getInteger(context, - "property[@name=\"gov.nasa.worldwind.avkey.NumEmptyLevels\"]", xpath); - if (numLevels != null) - { + "property[@name=\"gov.nasa.worldwind.avkey.NumEmptyLevels\"]", xpath); + if (numLevels != null) { el = WWXML.appendElementPath(outElem, "NumLevels"); WWXML.setIntegerAttribute(el, "count", numLevels); WWXML.setIntegerAttribute(el, "numEmpty", (numEmptyLevels != null) ? numEmptyLevels : 0); @@ -1764,29 +1560,25 @@ protected static void transformDataDescriptorCommonElements(Element context, Ele // Note the upper case K in "avKey". This was a typo in AVKey.SECTOR, and is intentionally reproduced here. Sector sector = getDataDescriptorSector(context, "property[@name=\"gov.nasa.worldwind.avKey.Sector\"]", xpath); - if (sector != null) - { + if (sector != null) { WWXML.appendSector(outElem, "Sector", sector); } LatLon ll = getDataDescriptorLatLon(context, "property[@name=\"gov.nasa.worldwind.avkey.TileOrigin\"]", xpath); - if (ll != null) - { + if (ll != null) { WWXML.appendLatLon(outElem, "TileOrigin/LatLon", ll); } ll = getDataDescriptorLatLon(context, "property[@name=\"gov.nasa.worldwind.avkey.LevelZeroTileDelta\"]", xpath); - if (ll != null) - { + if (ll != null) { WWXML.appendLatLon(outElem, "LevelZeroTileDelta/LatLon", ll); } Integer tileWidth = WWXML.getInteger(context, "property[@name=\"gov.nasa.worldwind.avkey.TileWidthKey\"]", - xpath); + xpath); Integer tileHeight = WWXML.getInteger(context, "property[@name=\"gov.nasa.worldwind.avkey.TileHeightKey\"]", - xpath); - if (tileWidth != null && tileHeight != null) - { + xpath); + if (tileWidth != null && tileHeight != null) { el = WWXML.appendElementPath(outElem, "TileSize/Dimension"); WWXML.setIntegerAttribute(el, "width", tileWidth); WWXML.setIntegerAttribute(el, "height", tileHeight); @@ -1794,20 +1586,17 @@ protected static void transformDataDescriptorCommonElements(Element context, Ele } protected static void transformDataDescriptorElevationModelElements(Element context, Element outElem, - XPath xpath) - { + XPath xpath) { // Image format properties. Element el = WWXML.appendElementPath(outElem, "DataType"); String pixelType = WWXML.getText(context, "property[@name=\"gov.nasa.worldwind.avkey.PixelType\"]", xpath); - if (pixelType != null && pixelType.length() != 0) - { + if (pixelType != null && pixelType.length() != 0) { WWXML.setTextAttribute(el, "type", WWXML.dataTypeAsText(pixelType)); } String byteOrder = WWXML.getText(context, "property[@name=\"gov.nasa.worldwind.avkey.ByteOrder\"]", xpath); - if (byteOrder != null && byteOrder.length() != 0) - { + if (byteOrder != null && byteOrder.length() != 0) { WWXML.setTextAttribute(el, "byteOrder", WWXML.byteOrderAsText(byteOrder)); } @@ -1816,22 +1605,19 @@ protected static void transformDataDescriptorElevationModelElements(Element cont // Translate that key here to MissingDataSignal, so it is properly understood by the WorldWind API // (esp. BasicElevationModel). Double d = WWXML.getDouble(context, "property[@name=\"gov.nasa.worldwind.avkey.MissingDataValue\"]", xpath); - if (d != null) - { + if (d != null) { el = WWXML.appendElementPath(outElem, "MissingData"); WWXML.setDoubleAttribute(el, "signal", d); } // DataDescriptor documents always describe an offline pyramid of tiled imagery or elevations in the file // store. Therefore we can safely assume that network retrieval should be disabled. - // Optional boolean properties. WWXML.appendBoolean(outElem, "NetworkRetrievalEnabled", false); } @SuppressWarnings({"UnusedDeclaration"}) - protected static void transformDataDescriptorLayerElements(Element context, Element outElem, XPath xpath) - { + protected static void transformDataDescriptorLayerElements(Element context, Element outElem, XPath xpath) { // Set the texture format to DDS. If the texture data is already in DDS format, this parameter is benign. WWXML.appendText(outElem, "TextureFormat", DEFAULT_TEXTURE_FORMAT); @@ -1843,29 +1629,24 @@ protected static void transformDataDescriptorLayerElements(Element context, Elem WWXML.appendBoolean(outElem, "UseTransparentTextures", true); } - protected static LatLon getDataDescriptorLatLon(Element context, String path, XPath xpath) - { + protected static LatLon getDataDescriptorLatLon(Element context, String path, XPath xpath) { Element el = (path == null) ? context : WWXML.getElement(context, path, xpath); - if (el == null) - { + if (el == null) { return null; } Double latDegrees = WWXML.getDouble(el, "property[@name=\"latitudeDegrees\"]", xpath); Double lonDegrees = WWXML.getDouble(el, "property[@name=\"longitudeDegrees\"]", xpath); - if (latDegrees == null || lonDegrees == null) - { + if (latDegrees == null || lonDegrees == null) { return null; } return LatLon.fromDegrees(latDegrees, lonDegrees); } - protected static Sector getDataDescriptorSector(Element context, String path, XPath xpath) - { + protected static Sector getDataDescriptorSector(Element context, String path, XPath xpath) { Element el = (path == null) ? context : WWXML.getElement(context, path, xpath); - if (el == null) - { + if (el == null) { return null; } @@ -1874,8 +1655,7 @@ protected static Sector getDataDescriptorSector(Element context, String path, XP Double minLonDegrees = WWXML.getDouble(el, "property[@name=\"minLongitudeDegrees\"]", xpath); Double maxLonDegrees = WWXML.getDouble(el, "property[@name=\"maxLongitudeDegrees\"]", xpath); - if (minLatDegrees == null || maxLatDegrees == null || minLonDegrees == null || maxLonDegrees == null) - { + if (minLatDegrees == null || maxLatDegrees == null || minLonDegrees == null || maxLonDegrees == null) { return null; } @@ -1885,7 +1665,6 @@ protected static Sector getDataDescriptorSector(Element context, String path, XP //**************************************************************// //******************** WorldWind .NET LayerSet Configuration // //**************************************************************// - /** * Returns true if a specified document is a WorldWind .NET LayerSet configuration document, and false otherwise. * @@ -1895,10 +1674,8 @@ protected static Sector getDataDescriptorSector(Element context, String path, XP * * @throws IllegalArgumentException if document is null. */ - public static boolean isWWDotNetLayerSetConfigDocument(Element domElement) - { - if (domElement == null) - { + public static boolean isWWDotNetLayerSetConfigDocument(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1920,17 +1697,14 @@ public static boolean isWWDotNetLayerSetConfigDocument(Element domElement) * * @throws IllegalArgumentException if the event is null. */ - public static boolean isWWDotNetLayerSetConfigEvent(XMLEvent event) - { - if (event == null) - { + public static boolean isWWDotNetLayerSetConfigEvent(XMLEvent event) { + if (event == null) { String message = Logging.getMessage("nullValue.EventIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!event.isStartElement()) - { + if (!event.isStartElement()) { return false; } @@ -1942,39 +1716,44 @@ public static boolean isWWDotNetLayerSetConfigEvent(XMLEvent event) * Parses WorldWind .NET LayerSet configuration parameters from the specified document. This writes output as * key-value pairs to params. If a parameter from the LayerSet document already exists in params, that parameter is * ignored. Supported key and parameter names are: - * + * + * * * * + * constant) + * * + * (converted to mime type) + * + * * + * constant) + * * + * constant) + * * * * + * constant) + * *
                  Mapping
                  ParameterElement - * PathType
                  {@link gov.nasa.worldwind.avlist.AVKey#DISPLAY_NAME}QuadTileSet/NameString
                  ParameterElement PathType
                  {@link gov.nasa.worldwind.avlist.AVKey#DISPLAY_NAME}QuadTileSet/NameString
                  {@link gov.nasa.worldwind.avlist.AVKey#DATASET_NAME}QuadTileSet/NameString
                  {@link gov.nasa.worldwind.avlist.AVKey#OPACITY}QuadTileSet/OpacityDouble
                  {@link gov.nasa.worldwind.avlist.AVKey#SERVICE_NAME}"Offline" (string - * constant)String
                  {@link gov.nasa.worldwind.avlist.AVKey#FORMAT_SUFFIX}QuadTileSet/ImageAccessor/ImageFileExtensionString
                  String
                  {@link gov.nasa.worldwind.avlist.AVKey#FORMAT_SUFFIX}QuadTileSet/ImageAccessor/ImageFileExtensionString
                  {@link gov.nasa.worldwind.avlist.AVKey#IMAGE_FORMAT}QuadTileSet/ImageAccessor/ImageFileExtension - * (converted to mime type)String
                  {@link gov.nasa.worldwind.avlist.AVKey#AVAILABLE_IMAGE_FORMATS}QuadTileSet/ImageAccessor/ImageFileExtension - * (converted to mime type)String array
                  {@link gov.nasa.worldwind.avlist.AVKey#NUM_LEVELS}QuadTileSet/ImageAccessor/NumberLevelsInteger
                  String
                  {@link gov.nasa.worldwind.avlist.AVKey#AVAILABLE_IMAGE_FORMATS}QuadTileSet/ImageAccessor/ImageFileExtension + * (converted to mime type)String array
                  {@link gov.nasa.worldwind.avlist.AVKey#NUM_LEVELS}QuadTileSet/ImageAccessor/NumberLevelsInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#NUM_EMPTY_LEVELS}0 (integer - * constant)Integer
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR}QuadTileSet/BoundingBoxSector
                  Integer
                  {@link gov.nasa.worldwind.avlist.AVKey#SECTOR}QuadTileSet/BoundingBoxSector
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_ORIGIN}(-90, -180) (geographic location - * constant)LatLon
                  {@link gov.nasa.worldwind.avlist.AVKey#LEVEL_ZERO_TILE_DELTA}QuadTileSet/ImageAccessor/LevelZeroTileSizeDegreesLatLon
                  LatLon
                  {@link gov.nasa.worldwind.avlist.AVKey#LEVEL_ZERO_TILE_DELTA}QuadTileSet/ImageAccessor/LevelZeroTileSizeDegreesLatLon
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_WIDTH}QuadTileSet/ImageAccessor/TextureSizePixelsInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#TILE_HEIGHT}QuadTileSet/ImageAccessor/TextureSizePixelsInteger
                  {@link gov.nasa.worldwind.avlist.AVKey#NETWORK_RETRIEVAL_ENABLED}false (boolean - * constant)Boolean
                  {@link gov.nasa.worldwind.avlist.AVKey#TEXTURE_FORMAT}"image/dds"String
                  Boolean
                  {@link gov.nasa.worldwind.avlist.AVKey#TEXTURE_FORMAT}"image/dds"String
                  {@link gov.nasa.worldwind.avlist.AVKey#USE_MIP_MAPS}true (boolean - * constant)Boolean
                  {@link gov.nasa.worldwind.avlist.AVKey#USE_TRANSPARENT_TEXTURES}true - * (boolean constant)Boolean
                  + * constant)
                  Boolean
                  {@link gov.nasa.worldwind.avlist.AVKey#USE_TRANSPARENT_TEXTURES}true (boolean + * constant)Boolean
                  * * @param domElement the XML document root to parse for LayerSet configuration parameters. - * @param params the output key-value pairs which receive the LayerSet configuration parameters. A null - * reference is permitted. + * @param params the output key-value pairs which receive the LayerSet configuration parameters. A null reference is + * permitted. * * @return a reference to params, or a new AVList if params is null. * * @throws IllegalArgumentException if the document is null. */ - public static AVList getWWDotNetLayerSetConfigParams(Element domElement, AVList params) - { - if (domElement == null) - { + public static AVList getWWDotNetLayerSetConfigParams(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1984,13 +1763,11 @@ public static AVList getWWDotNetLayerSetConfigParams(Element domElement, AVList // Find the first QuadTileSet element in this LayerSet document. Element el = WWXML.getElement(domElement, "QuadTileSet", xpath); - if (el == null) - { + if (el == null) { return params; } - if (params == null) - { + if (params == null) { params = new AVListImpl(); } @@ -1999,11 +1776,9 @@ public static AVList getWWDotNetLayerSetConfigParams(Element domElement, AVList WWXML.checkAndSetStringParam(el, params, AVKey.DATASET_NAME, "Name", xpath); // Display properties. - if (params.getValue(AVKey.OPACITY) == null) - { + if (params.getValue(AVKey.OPACITY) == null) { Double d = WWXML.getDouble(el, "Opacity", xpath); - if (d != null) - { + if (d != null) { params.setValue(AVKey.OPACITY, d / 255d); } } @@ -2011,19 +1786,15 @@ public static AVList getWWDotNetLayerSetConfigParams(Element domElement, AVList // Service properties. // LayerSet documents always describe an offline pyramid of tiled imagery in the file store, Therefore we define // the service as "Offline". - if (params.getValue(AVKey.SERVICE_NAME) == null) - { + if (params.getValue(AVKey.SERVICE_NAME) == null) { params.setValue(AVKey.SERVICE_NAME, "Offline"); } // Image format properties. - if (params.getValue(AVKey.FORMAT_SUFFIX) == null) - { + if (params.getValue(AVKey.FORMAT_SUFFIX) == null) { String s = WWXML.getText(el, "ImageAccessor/ImageFileExtension", xpath); - if (s != null && s.length() != 0) - { - if (!s.startsWith(".")) - { + if (s != null && s.length() != 0) { + if (!s.startsWith(".")) { s = "." + s; } params.setValue(AVKey.FORMAT_SUFFIX, s); @@ -2032,68 +1803,54 @@ public static AVList getWWDotNetLayerSetConfigParams(Element domElement, AVList // LayerSet documents contain a format suffix, but not image format type. Convert the format suffix to a // mime type, then use it to populate the IMAGE_FORMAT and AVAILABLE_IMAGE_FORMAT properties. - if (params.getValue(AVKey.FORMAT_SUFFIX) != null) - { + if (params.getValue(AVKey.FORMAT_SUFFIX) != null) { String s = WWIO.makeMimeTypeForSuffix(params.getValue(AVKey.FORMAT_SUFFIX).toString()); - if (s != null) - { - if (params.getValue(AVKey.IMAGE_FORMAT) == null) - { + if (s != null) { + if (params.getValue(AVKey.IMAGE_FORMAT) == null) { params.setValue(AVKey.IMAGE_FORMAT, s); } - if (params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) == null) - { - params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, new String[] {s}); + if (params.getValue(AVKey.AVAILABLE_IMAGE_FORMATS) == null) { + params.setValue(AVKey.AVAILABLE_IMAGE_FORMATS, new String[]{s}); } } } // Set the texture format to DDS. If the texture data is already in DDS format, this parameter is benign. - if (params.getValue(AVKey.TEXTURE_FORMAT) == null) - { + if (params.getValue(AVKey.TEXTURE_FORMAT) == null) { params.setValue(AVKey.TEXTURE_FORMAT, DEFAULT_TEXTURE_FORMAT); } // Tile structure properties. WWXML.checkAndSetIntegerParam(el, params, AVKey.NUM_LEVELS, "ImageAccessor/NumberLevels", xpath); - if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) - { + if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null) { params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); } - if (params.getValue(AVKey.SECTOR) == null) - { + if (params.getValue(AVKey.SECTOR) == null) { Sector s = getWWDotNetLayerSetSector(el, "BoundingBox", xpath); - if (s != null) - { + if (s != null) { params.setValue(AVKey.SECTOR, s); } } - if (params.getValue(AVKey.TILE_ORIGIN) == null) - { + if (params.getValue(AVKey.TILE_ORIGIN) == null) { params.setValue(AVKey.TILE_ORIGIN, new LatLon(Angle.NEG90, Angle.NEG180)); } - if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) - { + if (params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA) == null) { LatLon ll = getWWDotNetLayerSetLatLon(el, "ImageAccessor/LevelZeroTileSizeDegrees", xpath); - if (ll != null) - { + if (ll != null) { params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, ll); } } Integer tileDimension = WWXML.getInteger(el, "ImageAccessor/TextureSizePixels", xpath); - if (tileDimension != null) - { - if (params.getValue(AVKey.TILE_WIDTH) == null) - { + if (tileDimension != null) { + if (params.getValue(AVKey.TILE_WIDTH) == null) { params.setValue(AVKey.TILE_WIDTH, tileDimension); } - if (params.getValue(AVKey.TILE_HEIGHT) == null) - { + if (params.getValue(AVKey.TILE_HEIGHT) == null) { params.setValue(AVKey.TILE_HEIGHT, tileDimension); } } @@ -2101,16 +1858,13 @@ public static AVList getWWDotNetLayerSetConfigParams(Element domElement, AVList // LayerSet documents always describe an offline pyramid of tiled imagery in the file store. Therefore we can // safely assume that network retrieval should be disabled. Because we know nothing about the nature of the // imagery, it's best to enable mipmapping and transparent textures by default. - if (params.getValue(AVKey.NETWORK_RETRIEVAL_ENABLED) == null) - { + if (params.getValue(AVKey.NETWORK_RETRIEVAL_ENABLED) == null) { params.setValue(AVKey.NETWORK_RETRIEVAL_ENABLED, false); } - if (params.getValue(AVKey.USE_MIP_MAPS) == null) - { + if (params.getValue(AVKey.USE_MIP_MAPS) == null) { params.setValue(AVKey.USE_MIP_MAPS, true); } - if (params.getValue(AVKey.USE_TRANSPARENT_TEXTURES) == null) - { + if (params.getValue(AVKey.USE_TRANSPARENT_TEXTURES) == null) { params.setValue(AVKey.USE_TRANSPARENT_TEXTURES, true); } @@ -2126,10 +1880,8 @@ public static AVList getWWDotNetLayerSetConfigParams(Element domElement, AVList * * @throws IllegalArgumentException if the document is null. */ - public static Document transformWWDotNetLayerSetConfigDocument(Element domElement) - { - if (domElement == null) - { + public static Document transformWWDotNetLayerSetConfigDocument(Element domElement) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2138,8 +1890,7 @@ public static Document transformWWDotNetLayerSetConfigDocument(Element domElemen XPath xpath = WWXML.makeXPath(); Element[] els = WWXML.getElements(domElement, "/LayerSet/QuadTileSet", xpath); - if (els == null || els.length == 0) - { + if (els == null || els.length == 0) { return null; } @@ -2150,8 +1901,7 @@ public static Document transformWWDotNetLayerSetConfigDocument(Element domElemen return outDoc; } - protected static void transformWWDotNetLayerSet(Element context, Document outDoc, XPath xpath) - { + protected static void transformWWDotNetLayerSet(Element context, Document outDoc, XPath xpath) { Element el = WWXML.setDocumentElement(outDoc, "Layer"); WWXML.setIntegerAttribute(el, "version", 1); WWXML.setTextAttribute(el, "layerType", "TiledImageLayer"); @@ -2159,20 +1909,17 @@ protected static void transformWWDotNetLayerSet(Element context, Document outDoc transformWWDotNetQuadTileSet(context, el, xpath); } - protected static void transformWWDotNetQuadTileSet(Element context, Element outElem, XPath xpath) - { + protected static void transformWWDotNetQuadTileSet(Element context, Element outElem, XPath xpath) { // Display name and dataset name properties. String s = WWXML.getText(context, "Name", xpath); - if (s != null && s.length() != 0) - { + if (s != null && s.length() != 0) { WWXML.appendText(outElem, "DisplayName", s); WWXML.appendText(outElem, "DatasetName", s); } // Display properties. Double d = WWXML.getDouble(context, "Opacity", xpath); - if (d != null) - { + if (d != null) { WWXML.appendDouble(outElem, "Opacity", d / 255d); } @@ -2184,10 +1931,8 @@ protected static void transformWWDotNetQuadTileSet(Element context, Element outE // Image format properties. s = WWXML.getText(context, "ImageAccessor/ImageFileExtension", xpath); - if (s != null && s.length() != 0) - { - if (!s.startsWith(".")) - { + if (s != null && s.length() != 0) { + if (!s.startsWith(".")) { s = "." + s; } WWXML.appendText(outElem, "FormatSuffix", s); @@ -2196,8 +1941,7 @@ protected static void transformWWDotNetQuadTileSet(Element context, Element outE // mime type, then use it to populate the ImageFormat and AvailableImageFormat elements in the transformed // Layer configuration document. String mimeType = WWIO.makeMimeTypeForSuffix(s); - if (mimeType != null && mimeType.length() != 0) - { + if (mimeType != null && mimeType.length() != 0) { WWXML.appendText(outElem, "ImageFormat", mimeType); WWXML.appendText(outElem, "AvailableImageFormats/ImageFormat", mimeType); } @@ -2208,30 +1952,26 @@ protected static void transformWWDotNetQuadTileSet(Element context, Element outE // Tile structure properties. Integer numLevels = WWXML.getInteger(context, "ImageAccessor/NumberLevels", xpath); - if (numLevels != null) - { + if (numLevels != null) { el = WWXML.appendElementPath(outElem, "NumLevels"); WWXML.setIntegerAttribute(el, "count", numLevels); WWXML.setIntegerAttribute(el, "numEmpty", 0); } Sector sector = getWWDotNetLayerSetSector(context, "BoundingBox", xpath); - if (sector != null) - { + if (sector != null) { WWXML.appendSector(outElem, "Sector", sector); } WWXML.appendLatLon(outElem, "TileOrigin/LatLon", new LatLon(Angle.NEG90, Angle.NEG180)); LatLon ll = getWWDotNetLayerSetLatLon(context, "ImageAccessor/LevelZeroTileSizeDegrees", xpath); - if (ll != null) - { + if (ll != null) { WWXML.appendLatLon(outElem, "LevelZeroTileDelta/LatLon", ll); } Integer tileDimension = WWXML.getInteger(context, "ImageAccessor/TextureSizePixels", xpath); - if (tileDimension != null) - { + if (tileDimension != null) { el = WWXML.appendElementPath(outElem, "TileSize/Dimension"); WWXML.setIntegerAttribute(el, "width", tileDimension); WWXML.setIntegerAttribute(el, "height", tileDimension); @@ -2245,22 +1985,18 @@ protected static void transformWWDotNetQuadTileSet(Element context, Element outE WWXML.appendBoolean(outElem, "UseTransparentTextures", true); } - protected static LatLon getWWDotNetLayerSetLatLon(Element context, String path, XPath xpath) - { + protected static LatLon getWWDotNetLayerSetLatLon(Element context, String path, XPath xpath) { Double degrees = WWXML.getDouble(context, path, xpath); - if (degrees == null) - { + if (degrees == null) { return null; } return LatLon.fromDegrees(degrees, degrees); } - protected static Sector getWWDotNetLayerSetSector(Element context, String path, XPath xpath) - { + protected static Sector getWWDotNetLayerSetSector(Element context, String path, XPath xpath) { Element el = (path == null) ? context : WWXML.getElement(context, path, xpath); - if (el == null) - { + if (el == null) { return null; } @@ -2269,8 +2005,7 @@ protected static Sector getWWDotNetLayerSetSector(Element context, String path, Double minLonDegrees = WWXML.getDouble(el, "West/Value", xpath); Double maxLonDegrees = WWXML.getDouble(el, "East/Value", xpath); - if (minLatDegrees == null || maxLatDegrees == null || minLonDegrees == null || maxLonDegrees == null) - { + if (minLatDegrees == null || maxLatDegrees == null || minLonDegrees == null || maxLonDegrees == null) { return null; } diff --git a/src/gov/nasa/worldwind/util/DecisionTree.java b/src/gov/nasa/worldwind/util/DecisionTree.java index d6d9763a8b..06a9f9d281 100644 --- a/src/gov/nasa/worldwind/util/DecisionTree.java +++ b/src/gov/nasa/worldwind/util/DecisionTree.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; /** @@ -26,18 +25,19 @@ */ public class DecisionTree // T = type being managed. C = traversal context { + /** * Interface defined by the class user to control traversal. * * @param the data type of objects associated with tree nodes -- the objects implicitly contained in the tree. * @param the traversal context type. */ - public interface Controller - { + public interface Controller { + /** * Indicates whether a node is active during traversal. * - * @param o the user-defined object specified at traversal start and examined at each tree nodes. + * @param o the user-defined object specified at traversal start and examined at each tree nodes. * @param context the traversal context. * * @return true if the node is active, otherwise false. @@ -47,11 +47,11 @@ public interface Controller /** * Indicates whether traversal should contine or end at a node. * - * @param o the user-defined object specified at traversal start and examined at each tree nodes. + * @param o the user-defined object specified at traversal start and examined at each tree nodes. * @param context the traversal context. * * @return true if the node is terminal, otherwise false. Traversal continues to descendants if false is - * returned. otherwise traversal of the node's branch of the tree stops. + * returned. otherwise traversal of the node's branch of the tree stops. */ public boolean isTerminal(T o, C context); @@ -59,7 +59,7 @@ public interface Controller * Create a cell's descendant nodes. Called in order to continue traversal down a branch of the tree from the * current node. The returned nodes are visited in the order returned. * - * @param o the user-defined object specified at traversal start and examined at each tree nodes. + * @param o the user-defined object specified at traversal start and examined at each tree nodes. * @param context the traversal context. * * @return an array of descendant nodes. @@ -73,29 +73,28 @@ public interface Controller * Construct a decision tree for a given item type and controller type. * * @param controller a user-defined object implementing the Controller interface providing the - * traversal control methods. + * traversal control methods. */ - public DecisionTree(Controller controller) - { + public DecisionTree(Controller controller) { this.controller = controller; } /** * Start tree traversal. The tree is visited in depth-first order. * - * @param o a user-defined object to examine at each tree node. + * @param o a user-defined object to examine at each tree node. * @param context the traversal context. */ - public void traverse(T o, C context) - { - if (!this.controller.isVisible(o, context)) + public void traverse(T o, C context) { + if (!this.controller.isVisible(o, context)) { return; + } - if (this.controller.isTerminal(o, context)) + if (this.controller.isTerminal(o, context)) { return; + } - for (T child : this.controller.split(o, context)) - { + for (T child : this.controller.split(o, context)) { this.traverse(child, context); } } diff --git a/src/gov/nasa/worldwind/util/EGM96.java b/src/gov/nasa/worldwind/util/EGM96.java index 6a90d21ad0..5690840ecf 100644 --- a/src/gov/nasa/worldwind/util/EGM96.java +++ b/src/gov/nasa/worldwind/util/EGM96.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.avlist.*; @@ -19,14 +18,15 @@ * values. Each row corresponding to a latitude, with the first row corresponding to +90 degrees (90 North). The integer * values must be in centimeters. *

                  - * Once constructed, the instance can be passed to {@link gov.nasa.worldwind.globes.EllipsoidalGlobe#applyEGMA96Offsets(String)} - * to apply the offets to elevations produced by the globe. + * Once constructed, the instance can be passed to + * {@link gov.nasa.worldwind.globes.EllipsoidalGlobe#applyEGMA96Offsets(String)} to apply the offets to elevations + * produced by the globe. * * @author tag * @version $Id: EGM96.java 770 2012-09-13 02:48:23Z tgaskins $ */ -public class EGM96 -{ +public class EGM96 { + protected String offsetsFilePath; protected BufferWrapper deltas; @@ -34,13 +34,11 @@ public class EGM96 * Construct an instance. * * @param offsetsFilePath a path pointing to a file with the geoid offsets. See the class description above for a - * description of the file. + * description of the file. * @throws java.io.IOException if there's a problem reading the file. */ - public EGM96(String offsetsFilePath) throws IOException - { - if (offsetsFilePath == null) - { + public EGM96(String offsetsFilePath) throws IOException { + if (offsetsFilePath == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -51,31 +49,24 @@ public EGM96(String offsetsFilePath) throws IOException this.loadOffsetFile(); } - protected void loadOffsetFile() throws IOException - { + protected void loadOffsetFile() throws IOException { InputStream is = WWIO.openFileOrResourceStream(this.offsetsFilePath, EGM96.class); - if (is == null) - { + if (is == null) { String msg = Logging.getMessage("generic.CannotOpenFile", this.offsetsFilePath); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } - try - { + try { AVList bufferParams = new AVListImpl(); bufferParams.setValue(AVKey.DATA_TYPE, AVKey.INT16); bufferParams.setValue(AVKey.BYTE_ORDER, AVKey.BIG_ENDIAN); this.deltas = BufferWrapper.wrap(WWIO.readStreamToBuffer(is, true), bufferParams); - } - catch (IOException e) - { + } catch (IOException e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToReadFile", this.offsetsFilePath); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); throw e; - } - finally - { + } finally { WWIO.closeStream(is, this.offsetsFilePath); } } @@ -92,15 +83,12 @@ protected void loadOffsetFile() throws IOException // of the Prime Meridian (359.75 E). On file, the geoid heights are in units // of centimeters. While retrieving the Integer*2 values on file, divide by // 100 and this will produce a geoid height in meters. - protected static Angle INTERVAL = Angle.fromDegrees(15d / 60d); // 15' angle delta protected static int NUM_ROWS = 721; protected static int NUM_COLS = 1440; - public double getOffset(Angle latitude, Angle longitude) - { - if (latitude == null || longitude == null) - { + public double getOffset(Angle latitude, Angle longitude) { + if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -108,15 +96,17 @@ public double getOffset(Angle latitude, Angle longitude) // Return 0 for all offsets if the file failed to load. A log message of the failure will have been generated // by the load method. - if (this.deltas == null) + if (this.deltas == null) { return 0; + } double lat = latitude.degrees; double lon = longitude.degrees >= 0 ? longitude.degrees : longitude.degrees + 360; int topRow = (int) ((90 - lat) / INTERVAL.degrees); - if (lat <= -90) + if (lat <= -90) { topRow = NUM_ROWS - 2; + } int bottomRow = topRow + 1; // Note that the number of columns does not repeat the column at 0 longitude, so we must force the right @@ -124,8 +114,7 @@ public double getOffset(Angle latitude, Angle longitude) // last column of the grid. int leftCol = (int) (lon / INTERVAL.degrees); int rightCol = leftCol + 1; - if (lon >= 360 - INTERVAL.degrees) - { + if (lon >= 360 - INTERVAL.degrees) { leftCol = NUM_COLS - 1; rightCol = 0; } @@ -151,12 +140,12 @@ public double getOffset(Angle latitude, Angle longitude) return offset / 100d; // convert centimeters to meters } - protected double gePostOffset(int row, int col) - { + protected double gePostOffset(int row, int col) { int k = row * NUM_COLS + col; - if (k >= this.deltas.length()) + if (k >= this.deltas.length()) { System.out.println(k); + } return this.deltas.getInt(k); } diff --git a/src/gov/nasa/worldwind/util/EditorAnnotation.java b/src/gov/nasa/worldwind/util/EditorAnnotation.java index fe098d4859..7ae171e778 100644 --- a/src/gov/nasa/worldwind/util/EditorAnnotation.java +++ b/src/gov/nasa/worldwind/util/EditorAnnotation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.avlist.AVKey; @@ -15,8 +14,8 @@ * @author tag * @version $Id: EditorAnnotation.java 2306 2014-09-15 17:32:55Z tgaskins $ */ -public class EditorAnnotation extends ScreenAnnotation -{ +public class EditorAnnotation extends ScreenAnnotation { + private Point tooltipOffset = new Point(5, 5); /** @@ -24,15 +23,13 @@ public class EditorAnnotation extends ScreenAnnotation * * @param text the text to display in the tool tip. */ - public EditorAnnotation(String text) - { + public EditorAnnotation(String text) { super(text, new Point(0, 0)); // (0,0) is a dummy; the actual point is determined when rendering this.initializeAttributes(); } - protected void initializeAttributes() - { + protected void initializeAttributes() { this.attributes.setAdjustWidthToText(AVKey.SIZE_FIT_TEXT); this.attributes.setFrameShape(AVKey.SHAPE_RECTANGLE); this.attributes.setTextColor(Color.BLACK); @@ -44,21 +41,18 @@ protected void initializeAttributes() this.attributes.setInsets(new Insets(5, 5, 5, 5)); } - protected int getOffsetX() - { + protected int getOffsetX() { return this.tooltipOffset != null ? this.tooltipOffset.x : 0; } - protected int getOffsetY() - { + protected int getOffsetY() { return this.tooltipOffset != null ? this.tooltipOffset.y : 0; } @Override - protected void doRenderNow(DrawContext dc) - { + protected void doRenderNow(DrawContext dc) { this.getAttributes().setDrawOffset( - new Point(this.getBounds(dc).width / 2 + this.getOffsetX(), this.getOffsetY())); + new Point(this.getBounds(dc).width / 2 + this.getOffsetX(), this.getOffsetY())); this.setScreenPoint(this.getScreenPoint()); super.doRenderNow(dc); diff --git a/src/gov/nasa/worldwind/util/ElevationsUtil.java b/src/gov/nasa/worldwind/util/ElevationsUtil.java index 02e5531c10..83f8dcc42c 100644 --- a/src/gov/nasa/worldwind/util/ElevationsUtil.java +++ b/src/gov/nasa/worldwind/util/ElevationsUtil.java @@ -3,184 +3,158 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.avlist.*; import gov.nasa.worldwind.data.ByteBufferRaster; /** -* @author Lado Garakanidze -* @version $Id: ElevationsUtil.java 1171 2013-02-11 21:45:02Z dcollins $ -*/ - -public class ElevationsUtil -{ - public static final double DTED_DEFAULT_MISSING_SIGNAL = -32767d; - public static final double SRTM_DEFAULT_MISSING_SIGNAL = -32768d; - public static final double DEM_DEFAULT_MISSING_SIGNAL = -9999d; - - protected static final double[] knownMissingSignals = { - DTED_DEFAULT_MISSING_SIGNAL, SRTM_DEFAULT_MISSING_SIGNAL, DEM_DEFAULT_MISSING_SIGNAL - }; - - /** - * Checks if the value is one of the well-known "nodata" value used in digital elevation model files - * to specify missing areas / voids. - * - * @param value a value to check - * @return TRUE, if the value is one of the well known "nodata" values - * - */ - public static boolean isKnownMissingSignal(Double value) - { - if( null != value ) - { - for(double signal : knownMissingSignals ) - { - if( value == signal ) - return true; - } - } - return false; - } - - /** - * Rectify elevation raster. For best performance each elevation raster must have correct parameters and values set. - * The rectify() operation validates that correct Elevation min and max values are set or calculated. - * All values that beyond min/max and voids, must be marked with "Missing Signal" (aka "nodata" value). - * - * @param raster A DataRaster to rectify - * @throws IllegalArgumentException if raster is null - */ - public static void rectify(ByteBufferRaster raster) throws IllegalArgumentException - { - if( null == raster ) - { - String msg = Logging.getMessage("nullValue.RasterIsNull"); - Logging.logger().finest(msg); - throw new IllegalArgumentException(msg); - } - - int width = raster.getWidth(); - int height = raster.getHeight(); - - if( width == 0 || height == 0 ) - { - // nothing to do - return; - } - - double[] minmax= raster.getExtremes(); - if( null == minmax ) - { - // nothing to do - return; - } - - Double minValue = minmax[0]; - Double maxValue = minmax[1]; - - Double missingDataSignal = AVListImpl.getDoubleValue(raster, AVKey.MISSING_DATA_SIGNAL, null); - - // check if the minimum value is one of the well known NODATA values - if (ElevationsUtil.isKnownMissingSignal(minValue) - || (missingDataSignal != null && missingDataSignal.equals(minValue)) - ) - { - missingDataSignal = minValue; - raster.setTransparentValue(missingDataSignal); - - minmax = raster.getExtremes(); - if (null != minmax) - { - minValue = minmax[0]; - maxValue = minmax[1]; - } - } - - BufferWrapper bufferWrapper = raster.getBuffer(); - // Allocate a buffer to hold one row of scalar values. - double[] array = new double[width]; - - boolean needsConversion = false; - double conversionValue = 1d; - - if( raster.hasKey(AVKey.ELEVATION_UNIT) ) - { - String unit = raster.getStringValue(AVKey.ELEVATION_UNIT); - if( AVKey.UNIT_METER.equalsIgnoreCase(unit) ) - { - needsConversion = false; - } - else if( AVKey.UNIT_FOOT.equalsIgnoreCase(unit) ) - { - needsConversion = true; - conversionValue = WWMath.convertFeetToMeters(1); - minValue = WWMath.convertFeetToMeters(minValue); - maxValue = WWMath.convertFeetToMeters(maxValue); - raster.setValue(AVKey.ELEVATION_UNIT, AVKey.UNIT_METER); - } - else - { - needsConversion = false; - String msg = Logging.getMessage("generic.UnrecognizedElevationUnit", unit); - Logging.logger().warning(msg); - } - } - - boolean rasterHasVoids = false; - - for (int j = 0; j < height; j++) - { - bufferWrapper.getDouble( j * width, array, 0, width ); - boolean commitChanges = false; - - for (int i = 0; i < width; i++) - { - double value = array[i]; - - if( null != missingDataSignal && value == missingDataSignal ) - { - rasterHasVoids = true; - } - else - { - if( needsConversion ) - { - value *= conversionValue; - commitChanges = true; - array[i] = value; - } - - if( value < minValue || value > maxValue ) - { - rasterHasVoids = true; - - if( null != missingDataSignal) - { - array[i] = missingDataSignal; - commitChanges = true; - } - } - } - } - - if( commitChanges ) - bufferWrapper.putDouble( j * width, array, 0, width ); - } - - if( rasterHasVoids ) - { - if( missingDataSignal != null ) - raster.setValue(AVKey.MISSING_DATA_SIGNAL, missingDataSignal ); - } - else - { - raster.removeKey(AVKey.MISSING_DATA_SIGNAL); - } - - raster.setValue(AVKey.ELEVATION_MIN, minValue); - raster.setValue(AVKey.ELEVATION_MAX, maxValue); - } -} \ No newline at end of file + * @author Lado Garakanidze + * @version $Id: ElevationsUtil.java 1171 2013-02-11 21:45:02Z dcollins $ + */ +public class ElevationsUtil { + + public static final double DTED_DEFAULT_MISSING_SIGNAL = -32767d; + public static final double SRTM_DEFAULT_MISSING_SIGNAL = -32768d; + public static final double DEM_DEFAULT_MISSING_SIGNAL = -9999d; + + protected static final double[] knownMissingSignals = { + DTED_DEFAULT_MISSING_SIGNAL, SRTM_DEFAULT_MISSING_SIGNAL, DEM_DEFAULT_MISSING_SIGNAL + }; + + /** + * Checks if the value is one of the well-known "nodata" value used in digital elevation model files to + * specify missing areas / voids. + * + * @param value a value to check + * @return TRUE, if the value is one of the well known "nodata" values + * + */ + public static boolean isKnownMissingSignal(Double value) { + if (null != value) { + for (double signal : knownMissingSignals) { + if (value == signal) { + return true; + } + } + } + return false; + } + + /** + * Rectify elevation raster. For best performance each elevation raster must have correct parameters and values set. + * The rectify() operation validates that correct Elevation min and max values are set or calculated. + * All values that beyond min/max and voids, must be marked with "Missing Signal" (aka "nodata" value). + * + * @param raster A DataRaster to rectify + * @throws IllegalArgumentException if raster is null + */ + public static void rectify(ByteBufferRaster raster) throws IllegalArgumentException { + if (null == raster) { + String msg = Logging.getMessage("nullValue.RasterIsNull"); + Logging.logger().finest(msg); + throw new IllegalArgumentException(msg); + } + + int width = raster.getWidth(); + int height = raster.getHeight(); + + if (width == 0 || height == 0) { + // nothing to do + return; + } + + double[] minmax = raster.getExtremes(); + if (null == minmax) { + // nothing to do + return; + } + + Double minValue = minmax[0]; + Double maxValue = minmax[1]; + + Double missingDataSignal = AVListImpl.getDoubleValue(raster, AVKey.MISSING_DATA_SIGNAL, null); + + // check if the minimum value is one of the well known NODATA values + if (ElevationsUtil.isKnownMissingSignal(minValue) + || (missingDataSignal != null && missingDataSignal.equals(minValue))) { + missingDataSignal = minValue; + raster.setTransparentValue(missingDataSignal); + + minmax = raster.getExtremes(); + if (null != minmax) { + minValue = minmax[0]; + maxValue = minmax[1]; + } + } + + BufferWrapper bufferWrapper = raster.getBuffer(); + // Allocate a buffer to hold one row of scalar values. + double[] array = new double[width]; + + boolean needsConversion = false; + double conversionValue = 1d; + + if (raster.hasKey(AVKey.ELEVATION_UNIT)) { + String unit = raster.getStringValue(AVKey.ELEVATION_UNIT); + if (AVKey.UNIT_METER.equalsIgnoreCase(unit)) { + needsConversion = false; + } else if (AVKey.UNIT_FOOT.equalsIgnoreCase(unit)) { + needsConversion = true; + conversionValue = WWMath.convertFeetToMeters(1); + minValue = WWMath.convertFeetToMeters(minValue); + maxValue = WWMath.convertFeetToMeters(maxValue); + raster.setValue(AVKey.ELEVATION_UNIT, AVKey.UNIT_METER); + } else { + needsConversion = false; + String msg = Logging.getMessage("generic.UnrecognizedElevationUnit", unit); + Logging.logger().warning(msg); + } + } + + boolean rasterHasVoids = false; + + for (int j = 0; j < height; j++) { + bufferWrapper.getDouble(j * width, array, 0, width); + boolean commitChanges = false; + + for (int i = 0; i < width; i++) { + double value = array[i]; + + if (null != missingDataSignal && value == missingDataSignal) { + rasterHasVoids = true; + } else { + if (needsConversion) { + value *= conversionValue; + commitChanges = true; + array[i] = value; + } + + if (value < minValue || value > maxValue) { + rasterHasVoids = true; + + if (null != missingDataSignal) { + array[i] = missingDataSignal; + commitChanges = true; + } + } + } + } + + if (commitChanges) { + bufferWrapper.putDouble(j * width, array, 0, width); + } + } + + if (rasterHasVoids) { + if (missingDataSignal != null) { + raster.setValue(AVKey.MISSING_DATA_SIGNAL, missingDataSignal); + } + } else { + raster.removeKey(AVKey.MISSING_DATA_SIGNAL); + } + + raster.setValue(AVKey.ELEVATION_MIN, minValue); + raster.setValue(AVKey.ELEVATION_MAX, maxValue); + } +} diff --git a/src/gov/nasa/worldwind/util/EntityMap.java b/src/gov/nasa/worldwind/util/EntityMap.java index d2e3be8238..731a393a71 100644 --- a/src/gov/nasa/worldwind/util/EntityMap.java +++ b/src/gov/nasa/worldwind/util/EntityMap.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import java.util.*; @@ -15,12 +14,11 @@ * @author tag * @version $Id: EntityMap.java 669 2012-06-27 00:26:59Z pabercrombie $ */ -public class EntityMap -{ +public class EntityMap { + protected static final List patterns = new ArrayList(); - static - { + static { patterns.add(Pattern.compile("&[^;]+;")); // ampersand followed by any number of chars followed by semicolon } @@ -32,17 +30,14 @@ public class EntityMap * @param source the input string. * * @return the input string with all entities and references resolved. The input string is returned as-is if it - * contains no entities or references. + * contains no entities or references. */ - public static String replaceAll(String source) - { + public static String replaceAll(String source) { int regionStart = 0; for (String entity = getNextEntity(source, regionStart); entity != null; - entity = getNextEntity(source, regionStart)) - { + entity = getNextEntity(source, regionStart)) { String replacement = EntityMap.get(entity); - if (replacement == null) - { + if (replacement == null) { regionStart += entity.length(); continue; } @@ -57,23 +52,23 @@ public static String replaceAll(String source) /** * Search a string for the next occurrence of an entity. * - * @param source String to search. + * @param source String to search. * @param regionStart Position in the string at which to start searching. * * @return The entity that was matched, or {@code null} if no entity could be matched. */ - protected static String getNextEntity(String source, int regionStart) - { - if (source == null) + protected static String getNextEntity(String source, int regionStart) { + if (source == null) { return null; + } - for (Pattern pattern : patterns) - { + for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(source); matcher.region(regionStart, source.length()); - if (matcher.find()) + if (matcher.find()) { return matcher.group(); + } } return null; @@ -85,20 +80,19 @@ protected static String getNextEntity(String source, int regionStart) * @param key the entity or character reference. * * @return the Java equivalent of the input, or null if the input string does not identify a known entity or - * character reference. + * character reference. */ - public static String get(String key) - { - if (key == null) + public static String get(String key) { + if (key == null) { return null; + } return map.get(key); } // Mappings taken from // http://www.whatwg.org/specs/web-apps/current-work/multipage/named-character-references.html#named-character-references - - protected static String[] entityKeys = new String[] { + protected static String[] entityKeys = new String[]{ "᾿", "῾", "˘", @@ -2244,2167 +2238,2163 @@ public static String get(String key) "𝕫", "𝓏", "‍", - "‌", - }; + "‌",}; - protected static final String[] entityReplacements = new String[] - { - "\u1fbf", - "\u1ffe", - "\u02d8", - "\u02db", - "\u02dd", - "\u02f3", - "\u0309", - "\u030a", - "\u030f", - "\u0311", - "\u031b", - "\u0483", - "\u00c6", - "\u0026", - "\u00c1", - "\u0102", - "\u00c2", - "\u0410", - "\ud504", - "\u00c0", - "\u0391", - "\u0100", - "\u2a53", - "\u0104", - "\ud538", - "\u2061", - "\u00c5", - "\ud49c", - "\u2254", - "\u00c3", - "\u00c4", - "\u2216", - "\u2ae7", - "\u2306", - "\u0411", - "\u2235", - "\u212c", - "\u0392", - "\ud505", - "\ud539", - "\u02d8", - "\u212c", - "\u224e", - "\u0427", - "\u00a9", - "\u0106", - "\u22d2", - "\u2145", - "\u212d", - "\u010c", - "\u00c7", - "\u0108", - "\u2230", - "\u010a", - "\u00b8", - "\u00b7", - "\u212d", - "\u03a7", - "\u2299", - "\u2296", - "\u2295", - "\u2297", - "\u2232", - "\u201d", - "\u2019", - "\u2237", - "\u2a74", - "\u2261", - "\u222f", - "\u222e", - "\u2102", - "\u2210", - "\u2233", - "\u2a2f", - "\ud49e", - "\u22d3", - "\u224d", - "\u2145", - "\u2911", - "\u0402", - "\u0405", - "\u040f", - "\u2021", - "\u21a1", - "\u2ae4", - "\u010e", - "\u0414", - "\u2207", - "\u0394", - "\ud507", - "\u00b4", - "\u02d9", - "\u02dd", - "\u0060", - "\u02dc", - "\u22c4", - "\u2146", - "\ud53b", - "\u00a8", - "\u20dc", - "\u2250", - "\u222f", - "\u00a8", - "\u21d3", - "\u21d0", - "\u21d4", - "\u2ae4", - "\u27f8", - "\u27fa", - "\u27f9", - "\u21d2", - "\u22a8", - "\u21d1", - "\u21d5", - "\u2225", - "\u2193", - "\u2913", - "\u21f5", - "\u0311", - "\u2950", - "\u295e", - "\u21bd", - "\u2956", - "\u295f", - "\u21c1", - "\u2957", - "\u22a4", - "\u21a7", - "\u21d3", - "\ud49f", - "\u0110", - "\u014a", - "\u00d0", - "\u00c9", - "\u011a", - "\u00ca", - "\u042d", - "\u0116", - "\ud508", - "\u00c8", - "\u2208", - "\u0112", - "\u25fb", - "\u25ab", - "\u0118", - "\ud53c", - "\u0395", - "\u2a75", - "\u2242", - "\u21cc", - "\u2130", - "\u2a73", - "\u0397", - "\u00cb", - "\u2203", - "\u2147", - "\u0424", - "\ud509", - "\u25fc", - "\u25aa", - "\ud53d", - "\u2200", - "\u2131", - "\u2131", - "\u0403", - "\u003e", - "\u0393", - "\u03dc", - "\u011e", - "\u0122", - "\u011c", - "\u0413", - "\u0120", - "\ud50a", - "\u22d9", - "\ud53e", - "\u2265", - "\u22db", - "\u2267", - "\u2aa2", - "\u2277", - "\u2a7e", - "\u2273", - "\ud4a2", - "\u226b", - "\u042a", - "\u02c7", - "\u005e", - "\u0124", - "\u210c", - "\u210b", - "\u210d", - "\u2500", - "\u210b", - "\u0126", - "\u224e", - "\u224f", - "\u0415", - "\u0132", - "\u0401", - "\u00cd", - "\u00ce", - "\u0418", - "\u0130", - "\u2111", - "\u00cc", - "\u2111", - "\u012a", - "\u2148", - "\u21d2", - "\u222b", - "\u22c2", - "\u2063", - "\u2062", - "\u012e", - "\ud540", - "\u0399", - "\u2110", - "\u0128", - "\u0406", - "\u00cf", - "\u0134", - "\u0419", - "\ud50d", - "\ud541", - "\ud4a5", - "\u0408", - "\u0404", - "\u0425", - "\u040c", - "\u039a", - "\u0136", - "\u041a", - "\ud50e", - "\ud542", - "\ud4a6", - "\u0409", - "\u003c", - "\u0139", - "\u039b", - "\u27ea", - "\u2112", - "\u219e", - "\u013d", - "\u013b", - "\u041b", - "\u27e8", - "\u2190", - "\u21e4", - "\u21c6", - "\u2308", - "\u27e6", - "\u2961", - "\u21c3", - "\u2959", - "\u230a", - "\u2194", - "\u294e", - "\u22a3", - "\u21a4", - "\u295a", - "\u22b2", - "\u29cf", - "\u22b4", - "\u2951", - "\u2960", - "\u21bf", - "\u2958", - "\u21bc", - "\u2952", - "\u21d0", - "\u21d4", - "\u22da", - "\u2266", - "\u2276", - "\u2aa1", - "\u2a7d", - "\u2272", - "\ud50f", - "\u22d8", - "\u21da", - "\u013f", - "\u27f5", - "\u27f7", - "\u27f6", - "\u27f8", - "\u27fa", - "\u27f9", - "\ud543", - "\u2199", - "\u2198", - "\u2112", - "\u21b0", - "\u0141", - "\u226a", - "\u2905", - "\u041c", - "\u205f", - "\u2133", - "\ud510", - "\u2213", - "\ud544", - "\u2133", - "\u039c", - "\u040a", - "\u0143", - "\u0147", - "\u0145", - "\u041d", - "\u200b", - "\u200b", - "\u200b", - "\u200b", - "\u226b", - "\u226a", - "\\u000a", - "\ud511", - "\u2060", - "\u00a0", - "\u2115", - "\u2aec", - "\u2262", - "\u226d", - "\u2226", - "\u2209", - "\u2260", - "\u2242", - "\u2204", - "\u226f", - "\u2271", - "\u2267", - "\u226b", - "\u2279", - "\u2a7e", - "\u2275", - "\u224e", - "\u224f", - "\u22ea", - "\u29cf", - "\u22ec", - "\u226e", - "\u2270", - "\u2278", - "\u226a", - "\u2a7d", - "\u2274", - "\u2aa2", - "\u2aa1", - "\u2280", - "\u2aaf", - "\u22e0", - "\u220c", - "\u22eb", - "\u29d0", - "\u22ed", - "\u228f", - "\u22e2", - "\u2290", - "\u22e3", - "\u2282", - "\u2288", - "\u2281", - "\u2ab0", - "\u22e1", - "\u227f", - "\u2283", - "\u2289", - "\u2241", - "\u2244", - "\u2247", - "\u2249", - "\u2224", - "\ud4a9", - "\u00d1", - "\u039d", - "\u0152", - "\u00d3", - "\u00d4", - "\u041e", - "\u0150", - "\ud512", - "\u00d2", - "\u014c", - "\u03a9", - "\u039f", - "\ud546", - "\u201c", - "\u2018", - "\u2a54", - "\ud4aa", - "\u00d8", - "\u00d5", - "\u2a37", - "\u00d6", - "\u203e", - "\u23de", - "\u23b4", - "\u23dc", - "\u2202", - "\u041f", - "\ud513", - "\u03a6", - "\u03a0", - "\u00b1", - "\u210c", - "\u2119", - "\u2abb", - "\u227a", - "\u2aaf", - "\u227c", - "\u227e", - "\u2033", - "\u220f", - "\u2237", - "\u221d", - "\ud4ab", - "\u03a8", - "\"", - "\ud514", - "\u211a", - "\ud4ac", - "\u2910", - "\u00ae", - "\u0154", - "\u27eb", - "\u21a0", - "\u2916", - "\u0158", - "\u0156", - "\u0420", - "\u211c", - "\u220b", - "\u21cb", - "\u296f", - "\u211c", - "\u03a1", - "\u27e9", - "\u2192", - "\u21e5", - "\u21c4", - "\u2309", - "\u27e7", - "\u295d", - "\u21c2", - "\u2955", - "\u230b", - "\u22a2", - "\u21a6", - "\u295b", - "\u22b3", - "\u29d0", - "\u22b5", - "\u294f", - "\u295c", - "\u21be", - "\u2954", - "\u21c0", - "\u2953", - "\u21d2", - "\u211d", - "\u2970", - "\u21db", - "\u211b", - "\u21b1", - "\u29f4", - "\u0429", - "\u0428", - "\u042c", - "\u015a", - "\u2abc", - "\u0160", - "\u015e", - "\u015c", - "\u0421", - "\ud516", - "\u2193", - "\u2190", - "\u2192", - "\u2191", - "\u03a3", - "\u2218", - "\ud54a", - "\u221a", - "\u25a1", - "\u2293", - "\u228f", - "\u2291", - "\u2290", - "\u2292", - "\u2294", - "\ud4ae", - "\u22c6", - "\u22d0", - "\u22d0", - "\u2286", - "\u227b", - "\u2ab0", - "\u227d", - "\u227f", - "\u220b", - "\u2211", - "\u22d1", - "\u2283", - "\u2287", - "\u22d1", - "\u00de", - "\u2122", - "\u040b", - "\u0426", - "\u0009", - "\u03a4", - "\u0164", - "\u0162", - "\u0422", - "\ud517", - "\u2234", - "\u0398", - "\u205f", - "\u2009", - "\u223c", - "\u2243", - "\u2245", - "\u2248", - "\ud54b", - "\u20db", - "\ud4af", - "\u0166", - "\u00da", - "\u219f", - "\u2949", - "\u040e", - "\u016c", - "\u00db", - "\u0423", - "\u0170", - "\ud518", - "\u00d9", - "\u016a", - "\u005f", - "\u23df", - "\u23b5", - "\u23dd", - "\u22c3", - "\u228e", - "\u0172", - "\ud54c", - "\u2191", - "\u2912", - "\u21c5", - "\u2195", - "\u296e", - "\u22a5", - "\u21a5", - "\u21d1", - "\u21d5", - "\u2196", - "\u2197", - "\u03d2", - "\u03a5", - "\u016e", - "\ud4b0", - "\u0168", - "\u00dc", - "\u22ab", - "\u2aeb", - "\u0412", - "\u22a9", - "\u2ae6", - "\u22c1", - "\u2016", - "\u2016", - "\u2223", - "\u007c", - "\u2758", - "\u2240", - "\u200a", - "\ud519", - "\ud54d", - "\ud4b1", - "\u22aa", - "\u0174", - "\u22c0", - "\ud51a", - "\ud54e", - "\ud4b2", - "\ud51b", - "\u039e", - "\ud54f", - "\ud4b3", - "\u042f", - "\u0407", - "\u042e", - "\u00dd", - "\u0176", - "\u042b", - "\ud51c", - "\ud550", - "\ud4b4", - "\u0178", - "\u0416", - "\u0179", - "\u017d", - "\u0417", - "\u017b", - "\u200b", - "\u0396", - "\u2128", - "\u2124", - "\ud4b5", - "\u00e1", - "\u0103", - "\u223e", - "\u223e", - "\u223f", - "\u00e2", - "\u00b4", - "\u0430", - "\u00e6", - "\u2061", - "\ud51e", - "\u00e0", - "\u2135", - "\u2135", - "\u03b1", - "\u0101", - "\u2a3f", - "\u0026", - "\u2227", - "\u2a55", - "\u2a5c", - "\u2a58", - "\u2a5a", - "\u2220", - "\u29a4", - "\u2220", - "\u2221", - "\u29a8", - "\u29a9", - "\u29aa", - "\u29ab", - "\u29ac", - "\u29ad", - "\u29ae", - "\u29af", - "\u221f", - "\u22be", - "\u299d", - "\u2222", - "\u00c5", - "\u237c", - "\u0105", - "\ud552", - "\u2248", - "\u2a70", - "\u2a6f", - "\u224a", - "\u224b", - "\u0027", - "\u2248", - "\u224a", - "\u00e5", - "\ud4b6", - "\u002a", - "\u2248", - "\u224d", - "\u00e3", - "\u00e4", - "\u2233", - "\u2a11", - "\u2aed", - "\u224c", - "\u03f6", - "\u2035", - "\u223d", - "\u22cd", - "\u22bd", - "\u2305", - "\u2305", - "\u23b5", - "\u23b6", - "\u224c", - "\u0431", - "\u201e", - "\u2235", - "\u2235", - "\u29b0", - "\u03f6", - "\u212c", - "\u03b2", - "\u2136", - "\u226c", - "\ud51f", - "\u22c2", - "\u25ef", - "\u22c3", - "\u2a00", - "\u2a01", - "\u2a02", - "\u2a06", - "\u2605", - "\u25bd", - "\u25b3", - "\u2a04", - "\u22c1", - "\u22c0", - "\u290d", - "\u29eb", - "\u25aa", - "\u25b4", - "\u25be", - "\u25c2", - "\u25b8", - "\u2423", - "\u2592", - "\u2591", - "\u2593", - "\u2588", - "\u003d", - "\u2261", - "\u2310", - "\ud553", - "\u22a5", - "\u22a5", - "\u22c8", - "\u2557", - "\u2554", - "\u2556", - "\u2553", - "\u2550", - "\u2566", - "\u2569", - "\u2564", - "\u2567", - "\u255d", - "\u255a", - "\u255c", - "\u2559", - "\u2551", - "\u256c", - "\u2563", - "\u2560", - "\u256b", - "\u2562", - "\u255f", - "\u29c9", - "\u2555", - "\u2552", - "\u2510", - "\u250c", - "\u2500", - "\u2565", - "\u2568", - "\u252c", - "\u2534", - "\u229f", - "\u229e", - "\u22a0", - "\u255b", - "\u2558", - "\u2518", - "\u2514", - "\u2502", - "\u256a", - "\u2561", - "\u255e", - "\u253c", - "\u2524", - "\u251c", - "\u2035", - "\u02d8", - "\u00a6", - "\ud4b7", - "\u204f", - "\u223d", - "\u22cd", - "\\", - "\u29c5", - "\u27c8", - "\u2022", - "\u2022", - "\u224e", - "\u2aae", - "\u224f", - "\u224f", - "\u0107", - "\u2229", - "\u2a44", - "\u2a49", - "\u2a4b", - "\u2a47", - "\u2a40", - "\u2229", - "\u2041", - "\u02c7", - "\u2a4d", - "\u010d", - "\u00e7", - "\u0109", - "\u2a4c", - "\u2a50", - "\u010b", - "\u00b8", - "\u29b2", - "\u00a2", - "\u00b7", - "\ud520", - "\u0447", - "\u2713", - "\u2713", - "\u03c7", - "\u25cb", - "\u29c3", - "\u02c6", - "\u2257", - "\u21ba", - "\u21bb", - "\u00ae", - "\u24c8", - "\u229b", - "\u229a", - "\u229d", - "\u2257", - "\u2a10", - "\u2aef", - "\u29c2", - "\u2663", - "\u2663", - "\u003a", - "\u2254", - "\u2254", - "\u002c", - "\u0040", - "\u2201", - "\u2218", - "\u2201", - "\u2102", - "\u2245", - "\u2a6d", - "\u222e", - "\ud554", - "\u2210", - "\u00a9", - "\u2117", - "\u21b5", - "\u2717", - "\ud4b8", - "\u2acf", - "\u2ad1", - "\u2ad0", - "\u2ad2", - "\u22ef", - "\u2938", - "\u2935", - "\u22de", - "\u22df", - "\u21b6", - "\u293d", - "\u222a", - "\u2a48", - "\u2a46", - "\u2a4a", - "\u228d", - "\u2a45", - "\u222a", - "\u21b7", - "\u293c", - "\u22de", - "\u22df", - "\u22ce", - "\u22cf", - "\u00a4", - "\u21b6", - "\u21b7", - "\u22ce", - "\u22cf", - "\u2232", - "\u2231", - "\u232d", - "\u21d3", - "\u2965", - "\u2020", - "\u2138", - "\u21ca", - "\u2193", - "\u2010", - "\u22a3", - "\u290f", - "\u02dd", - "\u010f", - "\u0434", - "\u2146", - "\u2021", - "\u21ca", - "\u2a77", - "\u00b0", - "\u03b4", - "\u29b1", - "\u297f", - "\ud521", - "\u21c3", - "\u21c2", - "\u22c4", - "\u22c4", - "\u2666", - "\u2666", - "\u00a8", - "\u03dd", - "\u22f2", - "\u00f7", - "\u00f7", - "\u22c7", - "\u22c7", - "\u0452", - "\u2199", - "\u231e", - "\u230d", - "\u0024", - "\ud555", - "\u02d9", - "\u2250", - "\u2251", - "\u2238", - "\u2214", - "\u22a1", - "\u2306", - "\u2193", - "\u21ca", - "\u21c3", - "\u21c2", - "\u2198", - "\u2910", - "\u231f", - "\u230c", - "\ud4b9", - "\u0455", - "\u29f6", - "\u0111", - "\u22f1", - "\u25bf", - "\u25be", - "\u21f5", - "\u296f", - "\u29a6", - "\u045f", - "\u27ff", - "\u2a77", - "\u2251", - "\u00e9", - "\u2a6e", - "\u011b", - "\u2256", - "\u00ea", - "\u2255", - "\u044d", - "\u0117", - "\u2147", - "\u2252", - "\ud522", - "\u2a9a", - "\u00e8", - "\u2a96", - "\u2a98", - "\u2a99", - "\u23e7", - "\u2113", - "\u2a95", - "\u2a97", - "\u0113", - "\u2205", - "\u2205", - "\u2205", - "\u2004", - "\u2005", - "\u2003", - "\u014b", - "\u2002", - "\u0119", - "\ud556", - "\u22d5", - "\u29e3", - "\u2a71", - "\u03b5", - "\u03b5", - "\u03f5", - "\u2256", - "\u2255", - "\u2242", - "\u2a96", - "\u2a95", - "\u003d", - "\u225f", - "\u2261", - "\u2a78", - "\u29e5", - "\u2253", - "\u2971", - "\u212f", - "\u2250", - "\u2242", - "\u03b7", - "\u00f0", - "\u00eb", - "\u20ac", - "\u0021", - "\u2203", - "\u2130", - "\u2147", - "\u2252", - "\u0444", - "\u2640", - "\ufb03", - "\ufb00", - "\ufb04", - "\ud523", - "\ufb01", - "\u0066", - "\u266d", - "\ufb02", - "\u25b1", - "\u0192", - "\ud557", - "\u2200", - "\u22d4", - "\u2ad9", - "\u2a0d", - "\u00bd", - "\u2153", - "\u00bc", - "\u2155", - "\u2159", - "\u215b", - "\u2154", - "\u2156", - "\u00be", - "\u2157", - "\u215c", - "\u2158", - "\u215a", - "\u215d", - "\u215e", - "\u2044", - "\u2322", - "\ud4bb", - "\u2267", - "\u2a8c", - "\u01f5", - "\u03b3", - "\u03dd", - "\u2a86", - "\u011f", - "\u011d", - "\u0433", - "\u0121", - "\u2265", - "\u22db", - "\u2265", - "\u2267", - "\u2a7e", - "\u2a7e", - "\u2aa9", - "\u2a80", - "\u2a82", - "\u2a84", - "\u22db", - "\u2a94", - "\ud524", - "\u226b", - "\u22d9", - "\u2137", - "\u0453", - "\u2277", - "\u2a92", - "\u2aa5", - "\u2aa4", - "\u2269", - "\u2a8a", - "\u2a8a", - "\u2a88", - "\u2a88", - "\u2269", - "\u22e7", - "\ud558", - "\u0060", - "\u210a", - "\u2273", - "\u2a8e", - "\u2a90", - "\u003e", - "\u2aa7", - "\u2a7a", - "\u22d7", - "\u2995", - "\u2a7c", - "\u2a86", - "\u2978", - "\u22d7", - "\u22db", - "\u2a8c", - "\u2277", - "\u2273", - "\u2269", - "\u2269", - "\u21d4", - "\u200a", - "\u00bd", - "\u210b", - "\u044a", - "\u2194", - "\u2948", - "\u21ad", - "\u210f", - "\u0125", - "\u2665", - "\u2665", - "\u2026", - "\u22b9", - "\ud525", - "\u2925", - "\u2926", - "\u21ff", - "\u223b", - "\u21a9", - "\u21aa", - "\ud559", - "\u2015", - "\ud4bd", - "\u210f", - "\u0127", - "\u2043", - "\u2010", - "\u00ed", - "\u2063", - "\u00ee", - "\u0438", - "\u0435", - "\u00a1", - "\u21d4", - "\ud526", - "\u00ec", - "\u2148", - "\u2a0c", - "\u222d", - "\u29dc", - "\u2129", - "\u0133", - "\u012b", - "\u2111", - "\u2110", - "\u2111", - "\u0131", - "\u22b7", - "\u01b5", - "\u2208", - "\u2105", - "\u221e", - "\u29dd", - "\u0131", - "\u222b", - "\u22ba", - "\u2124", - "\u22ba", - "\u2a17", - "\u2a3c", - "\u0451", - "\u012f", - "\ud55a", - "\u03b9", - "\u2a3c", - "\u00bf", - "\ud4be", - "\u2208", - "\u22f9", - "\u22f5", - "\u22f4", - "\u22f3", - "\u2208", - "\u2062", - "\u0129", - "\u0456", - "\u00ef", - "\u0135", - "\u0439", - "\ud527", - "\u0237", - "\ud55b", - "\ud4bf", - "\u0458", - "\u0454", - "\u03ba", - "\u03f0", - "\u0137", - "\u043a", - "\ud528", - "\u0138", - "\u0445", - "\u045c", - "\ud55c", - "\ud4c0", - "\u21da", - "\u21d0", - "\u291b", - "\u290e", - "\u2266", - "\u2a8b", - "\u2962", - "\u013a", - "\u29b4", - "\u2112", - "\u03bb", - "\u2329", - "\u27e8", - "\u2991", - "\u2a85", - "\u00ab", - "\u21c7", - "\u2190", - "\u21e4", - "\u291f", - "\u291d", - "\u21a9", - "\u21ab", - "\u2939", - "\u2973", - "\u21a2", - "\u2aab", - "\u2919", - "\u2aad", - "\u2aad", - "\u290c", - "\u2772", - "\u007b", - "\u005b", - "\u298b", - "\u298f", - "\u298d", - "\u013e", - "\u013c", - "\u2308", - "\u007b", - "\u043b", - "\u2936", - "\u201c", - "\u201e", - "\u2967", - "\u294b", - "\u21b2", - "\u2264", - "\u2190", - "\u21a2", - "\u21bd", - "\u21bc", - "\u21c7", - "\u2194", - "\u21c6", - "\u21cb", - "\u21ad", - "\u22cb", - "\u22da", - "\u2264", - "\u2266", - "\u2a7d", - "\u2a7d", - "\u2aa8", - "\u2a7f", - "\u2a81", - "\u2a83", - "\u22da", - "\u2a93", - "\u2a85", - "\u22d6", - "\u22da", - "\u2a8b", - "\u2276", - "\u2272", - "\u297c", - "\u230a", - "\ud529", - "\u2276", - "\u2a91", - "\u21bd", - "\u21bc", - "\u296a", - "\u2584", - "\u0459", - "\u226a", - "\u21c7", - "\u231e", - "\u296b", - "\u25fa", - "\u0140", - "\u23b0", - "\u23b0", - "\u2268", - "\u2a89", - "\u2a89", - "\u2a87", - "\u2a87", - "\u2268", - "\u22e6", - "\u27ec", - "\u21fd", - "\u27e6", - "\u27f5", - "\u27f7", - "\u27fc", - "\u27f6", - "\u21ab", - "\u21ac", - "\u2985", - "\ud55d", - "\u2a2d", - "\u2a34", - "\u2217", - "\u005f", - "\u25ca", - "\u25ca", - "\u29eb", - "\u0028", - "\u2993", - "\u21c6", - "\u21c6", - "\u231f", - "\u21cb", - "\u21cb", - "\u296d", - "\u200e", - "\u22bf", - "\u2039", - "\ud4c1", - "\u21b0", - "\u2272", - "\u2a8d", - "\u2a8f", - "\u005b", - "\u2018", - "\u201a", - "\u0142", - "\u003c", - "\u2aa6", - "\u2a79", - "\u22d6", - "\u22cb", - "\u22c9", - "\u2976", - "\u2a7b", - "\u2996", - "\u25c3", - "\u22b4", - "\u25c2", - "\u294a", - "\u2966", - "\u2268", - "\u2268", - "\u223a", - "\u00af", - "\u2642", - "\u2720", - "\u2720", - "\u21a6", - "\u21a6", - "\u21a7", - "\u21a4", - "\u21a5", - "\u25ae", - "\u2a29", - "\u043c", - "\u2014", - "\u2221", - "\ud52a", - "\u2127", - "\u00b5", - "\u2223", - "\u002a", - "\u2af0", - "\u00b7", - "\u2212", - "\u229f", - "\u2238", - "\u2a2a", - "\u2adb", - "\u2026", - "\u2213", - "\u22a7", - "\ud55e", - "\u2213", - "\ud4c2", - "\u223e", - "\u03bc", - "\u22b8", - "\u22b8", - "\u22d9", - "\u226b", - "\u226b", - "\u21cd", - "\u21ce", - "\u22d8", - "\u226a", - "\u226a", - "\u21cf", - "\u22af", - "\u22ae", - "\u2207", - "\u0144", - "\u2220", - "\u2249", - "\u2a70", - "\u224b", - "\u0149", - "\u2249", - "\u266e", - "\u266e", - "\u2115", - "\u00a0", - "\u224e", - "\u224f", - "\u2a43", - "\u0148", - "\u0146", - "\u2247", - "\u2a6d", - "\u2a42", - "\u043d", - "\u2013", - "\u2260", - "\u21d7", - "\u2924", - "\u2197", - "\u2197", - "\u2250", - "\u2262", - "\u2928", - "\u2242", - "\u2204", - "\u2204", - "\ud52b", - "\u2267", - "\u2271", - "\u2271", - "\u2267", - "\u2a7e", - "\u2a7e", - "\u2275", - "\u226f", - "\u226f", - "\u21ce", - "\u21ae", - "\u2af2", - "\u220b", - "\u22fc", - "\u22fa", - "\u220b", - "\u045a", - "\u21cd", - "\u2266", - "\u219a", - "\u2025", - "\u2270", - "\u219a", - "\u21ae", - "\u2270", - "\u2266", - "\u2a7d", - "\u2a7d", - "\u226e", - "\u2274", - "\u226e", - "\u22ea", - "\u22ec", - "\u2224", - "\ud55f", - "\u00ac", - "\u2209", - "\u22f9", - "\u22f5", - "\u2209", - "\u22f7", - "\u22f6", - "\u220c", - "\u220c", - "\u22fe", - "\u22fd", - "\u2226", - "\u2226", - "\u2afd", - "\u2202", - "\u2a14", - "\u2280", - "\u22e0", - "\u2aaf", - "\u2280", - "\u2aaf", - "\u21cf", - "\u219b", - "\u2933", - "\u219d", - "\u219b", - "\u22eb", - "\u22ed", - "\u2281", - "\u22e1", - "\u2ab0", - "\ud4c3", - "\u2224", - "\u2226", - "\u2241", - "\u2244", - "\u2244", - "\u2224", - "\u2226", - "\u22e2", - "\u22e3", - "\u2284", - "\u2ac5", - "\u2288", - "\u2282", - "\u2288", - "\u2ac5", - "\u2281", - "\u2ab0", - "\u2285", - "\u2ac6", - "\u2289", - "\u2283", - "\u2289", - "\u2ac6", - "\u2279", - "\u00f1", - "\u2278", - "\u22ea", - "\u22ec", - "\u22eb", - "\u22ed", - "\u03bd", - "\u0023", - "\u2116", - "\u2007", - "\u22ad", - "\u2904", - "\u224d", - "\u22ac", - "\u2265", - "\u003e", - "\u29de", - "\u2902", - "\u2264", - "\u003c", - "\u22b4", - "\u2903", - "\u22b5", - "\u223c", - "\u21d6", - "\u2923", - "\u2196", - "\u2196", - "\u2927", - "\u24c8", - "\u00f3", - "\u229b", - "\u229a", - "\u00f4", - "\u043e", - "\u229d", - "\u0151", - "\u2a38", - "\u2299", - "\u29bc", - "\u0153", - "\u29bf", - "\ud52c", - "\u02db", - "\u00f2", - "\u29c1", - "\u29b5", - "\u03a9", - "\u222e", - "\u21ba", - "\u29be", - "\u29bb", - "\u203e", - "\u29c0", - "\u014d", - "\u03c9", - "\u03bf", - "\u29b6", - "\u2296", - "\ud560", - "\u29b7", - "\u29b9", - "\u2295", - "\u2228", - "\u21bb", - "\u2a5d", - "\u2134", - "\u2134", - "\u00aa", - "\u00ba", - "\u22b6", - "\u2a56", - "\u2a57", - "\u2a5b", - "\u2134", - "\u00f8", - "\u2298", - "\u00f5", - "\u2297", - "\u2a36", - "\u00f6", - "\u233d", - "\u2225", - "\u00b6", - "\u2225", - "\u2af3", - "\u2afd", - "\u2202", - "\u043f", - "\u0025", - "\u002e", - "\u2030", - "\u22a5", - "\u2031", - "\ud52d", - "\u03c6", - "\u03d5", - "\u2133", - "\u260e", - "\u03c0", - "\u22d4", - "\u03d6", - "\u210f", - "\u210e", - "\u210f", - "\u002b", - "\u2a23", - "\u229e", - "\u2a22", - "\u2214", - "\u2a25", - "\u2a72", - "\u00b1", - "\u2a26", - "\u2a27", - "\u00b1", - "\u2a15", - "\ud561", - "\u00a3", - "\u227a", - "\u2ab3", - "\u2ab7", - "\u227c", - "\u2aaf", - "\u227a", - "\u2ab7", - "\u227c", - "\u2aaf", - "\u2ab9", - "\u2ab5", - "\u22e8", - "\u227e", - "\u2032", - "\u2119", - "\u2ab5", - "\u2ab9", - "\u22e8", - "\u220f", - "\u232e", - "\u2312", - "\u2313", - "\u221d", - "\u221d", - "\u227e", - "\u22b0", - "\ud4c5", - "\u03c8", - "\u2008", - "\ud52e", - "\u2a0c", - "\ud562", - "\u2057", - "\ud4c6", - "\u210d", - "\u2a16", - "\u003f", - "\u225f", - "\"", - "\u21db", - "\u21d2", - "\u291c", - "\u290f", - "\u2964", - "\u223d", - "\u0155", - "\u221a", - "\u29b3", - "\u232a", - "\u27e9", - "\u2992", - "\u29a5", - "\u00bb", - "\u21c9", - "\u2192", - "\u2975", - "\u21e5", - "\u2920", - "\u2933", - "\u291e", - "\u21aa", - "\u21ac", - "\u2945", - "\u2974", - "\u21a3", - "\u219d", - "\u291a", - "\u2236", - "\u211a", - "\u290d", - "\u2773", - "\u007d", - "\u005d", - "\u298c", - "\u298e", - "\u2990", - "\u0159", - "\u0157", - "\u2309", - "\u007d", - "\u0440", - "\u2937", - "\u2969", - "\u201d", - "\u201d", - "\u21b3", - "\u211c", - "\u211b", - "\u211c", - "\u211d", - "\u25ad", - "\u00ae", - "\u297d", - "\u230b", - "\ud52f", - "\u21c1", - "\u21c0", - "\u296c", - "\u03c1", - "\u03f1", - "\u2192", - "\u21a3", - "\u21c1", - "\u21c0", - "\u21c4", - "\u21cc", - "\u21c9", - "\u219d", - "\u22cc", - "\u02da", - "\u2253", - "\u21c4", - "\u21c4", - "\u21cc", - "\u21cc", - "\u200f", - "\u23b1", - "\u23b1", - "\u2aee", - "\u27ed", - "\u21fe", - "\u27e7", - "\u2986", - "\ud563", - "\u2a2e", - "\u2a35", - "\u0029", - "\u2994", - "\u2a12", - "\u21c9", - "\u203a", - "\ud4c7", - "\u21b1", - "\u005d", - "\u2019", - "\u2019", - "\u22cc", - "\u22ca", - "\u25b9", - "\u22b5", - "\u25b8", - "\u29ce", - "\u2968", - "\u211e", - "\u015b", - "\u201a", - "\u227b", - "\u2ab4", - "\u2ab8", - "\u0161", - "\u227d", - "\u2ab0", - "\u015f", - "\u015d", - "\u2ab6", - "\u2aba", - "\u22e9", - "\u2a13", - "\u227f", - "\u0441", - "\u22c5", - "\u22a1", - "\u2a66", - "\u21d8", - "\u2925", - "\u2198", - "\u2198", - "\u00a7", - "\u003b", - "\u2929", - "\u2216", - "\u2216", - "\u2736", - "\ud530", - "\u2322", - "\u266f", - "\u0449", - "\u0448", - "\u2223", - "\u2225", - "\u00ad", - "\u03c3", - "\u03c2", - "\u03c2", - "\u223c", - "\u2a6a", - "\u2243", - "\u2243", - "\u2a9e", - "\u2aa0", - "\u2a9d", - "\u2a9f", - "\u2246", - "\u2a24", - "\u2972", - "\u2190", - "\u2216", - "\u2a33", - "\u29e4", - "\u2223", - "\u2323", - "\u2aaa", - "\u2aac", - "\u2aac", - "\u044c", - "\u002f", - "\u29c4", - "\u233f", - "\ud564", - "\u2660", - "\u2660", - "\u2225", - "\u2293", - "\u2293", - "\u2294", - "\u2294", - "\u228f", - "\u2291", - "\u228f", - "\u2291", - "\u2290", - "\u2292", - "\u2290", - "\u2292", - "\u25a1", - "\u25a1", - "\u25aa", - "\u25aa", - "\u2192", - "\ud4c8", - "\u2216", - "\u2323", - "\u22c6", - "\u2606", - "\u2605", - "\u03f5", - "\u03d5", - "\u00af", - "\u2282", - "\u2ac5", - "\u2abd", - "\u2286", - "\u2ac3", - "\u2ac1", - "\u2acb", - "\u228a", - "\u2abf", - "\u2979", - "\u2282", - "\u2286", - "\u2ac5", - "\u228a", - "\u2acb", - "\u2ac7", - "\u2ad5", - "\u2ad3", - "\u227b", - "\u2ab8", - "\u227d", - "\u2ab0", - "\u2aba", - "\u2ab6", - "\u22e9", - "\u227f", - "\u2211", - "\u266a", - "\u00b9", - "\u00b2", - "\u00b3", - "\u2283", - "\u2ac6", - "\u2abe", - "\u2ad8", - "\u2287", - "\u2ac4", - "\u27c9", - "\u2ad7", - "\u297b", - "\u2ac2", - "\u2acc", - "\u228b", - "\u2ac0", - "\u2283", - "\u2287", - "\u2ac6", - "\u228b", - "\u2acc", - "\u2ac8", - "\u2ad4", - "\u2ad6", - "\u21d9", - "\u2926", - "\u2199", - "\u2199", - "\u292a", - "\u00df", - "\u2316", - "\u03c4", - "\u23b4", - "\u0165", - "\u0163", - "\u0442", - "\u20db", - "\u2315", - "\ud531", - "\u2234", - "\u2234", - "\u03b8", - "\u03d1", - "\u03d1", - "\u2248", - "\u223c", - "\u2009", - "\u2248", - "\u223c", - "\u00fe", - "\u02dc", - "\u00d7", - "\u22a0", - "\u2a31", - "\u2a30", - "\u222d", - "\u2928", - "\u22a4", - "\u2336", - "\u2af1", - "\ud565", - "\u2ada", - "\u2929", - "\u2034", - "\u2122", - "\u25b5", - "\u25bf", - "\u25c3", - "\u22b4", - "\u225c", - "\u25b9", - "\u22b5", - "\u25ec", - "\u225c", - "\u2a3a", - "\u2a39", - "\u29cd", - "\u2a3b", - "\u23e2", - "\ud4c9", - "\u0446", - "\u045b", - "\u0167", - "\u226c", - "\u219e", - "\u21a0", - "\u21d1", - "\u2963", - "\u00fa", - "\u21c8", - "\u2191", - "\u045e", - "\u016d", - "\u00fb", - "\u0443", - "\u21c5", - "\u0171", - "\u296e", - "\u297e", - "\ud532", - "\u00f9", - "\u21bf", - "\u21be", - "\u2580", - "\u231c", - "\u231c", - "\u230f", - "\u25f8", - "\u016b", - "\u00a8", - "\u0173", - "\ud566", - "\u2191", - "\u2195", - "\u21bf", - "\u21be", - "\u228e", - "\u03c5", - "\u03d2", - "\u03c5", - "\u21c8", - "\u231d", - "\u231d", - "\u230e", - "\u016f", - "\u25f9", - "\ud4ca", - "\u22f0", - "\u0169", - "\u25b5", - "\u25b4", - "\u21c8", - "\u00fc", - "\u29a7", - "\u21d5", - "\u2ae8", - "\u2ae9", - "\u22a8", - "\u299c", - "\u03f5", - "\u03f0", - "\u2205", - "\u03d5", - "\u03d6", - "\u221d", - "\u2195", - "\u03f1", - "\u03c2", - "\u228a", - "\u2acb", - "\u228b", - "\u2acc", - "\u03d1", - "\u22b2", - "\u22b3", - "\u0432", - "\u22a2", - "\u2228", - "\u22bb", - "\u225a", - "\u22ee", - "\u007c", - "\u007c", - "\ud533", - "\u22b2", - "\u2282", - "\u2283", - "\ud567", - "\u221d", - "\u22b3", - "\ud4cb", - "\u2acb", - "\u228a", - "\u2acc", - "\u228b", - "\u299a", - "\u0175", - "\u2a5f", - "\u2227", - "\u2259", - "\u2118", - "\ud534", - "\ud568", - "\u2118", - "\u2240", - "\u2240", - "\ud4cc", - "\u22c2", - "\u25ef", - "\u22c3", - "\u25bd", - "\ud535", - "\u27fa", - "\u27f7", - "\u03be", - "\u27f8", - "\u27f5", - "\u27fc", - "\u22fb", - "\u2a00", - "\ud569", - "\u2a01", - "\u2a02", - "\u27f9", - "\u27f6", - "\ud4cd", - "\u2a06", - "\u2a04", - "\u25b3", - "\u22c1", - "\u22c0", - "\u00fd", - "\u044f", - "\u0177", - "\u044b", - "\u00a5", - "\ud536", - "\u0457", - "\ud56a", - "\ud4ce", - "\u044e", - "\u00ff", - "\u017a", - "\u017e", - "\u0437", - "\u017c", - "\u2128", - "\u03b6", - "\ud537", - "\u0436", - "\u21dd", - "\ud56b", - "\ud4cf", - "\u200d", - "\u200c", - "\u0027", - "\u0040", - "\u005e", - "\u0060", - "\u007e",}; + protected static final String[] entityReplacements = new String[]{ + "\u1fbf", + "\u1ffe", + "\u02d8", + "\u02db", + "\u02dd", + "\u02f3", + "\u0309", + "\u030a", + "\u030f", + "\u0311", + "\u031b", + "\u0483", + "\u00c6", + "\u0026", + "\u00c1", + "\u0102", + "\u00c2", + "\u0410", + "\ud504", + "\u00c0", + "\u0391", + "\u0100", + "\u2a53", + "\u0104", + "\ud538", + "\u2061", + "\u00c5", + "\ud49c", + "\u2254", + "\u00c3", + "\u00c4", + "\u2216", + "\u2ae7", + "\u2306", + "\u0411", + "\u2235", + "\u212c", + "\u0392", + "\ud505", + "\ud539", + "\u02d8", + "\u212c", + "\u224e", + "\u0427", + "\u00a9", + "\u0106", + "\u22d2", + "\u2145", + "\u212d", + "\u010c", + "\u00c7", + "\u0108", + "\u2230", + "\u010a", + "\u00b8", + "\u00b7", + "\u212d", + "\u03a7", + "\u2299", + "\u2296", + "\u2295", + "\u2297", + "\u2232", + "\u201d", + "\u2019", + "\u2237", + "\u2a74", + "\u2261", + "\u222f", + "\u222e", + "\u2102", + "\u2210", + "\u2233", + "\u2a2f", + "\ud49e", + "\u22d3", + "\u224d", + "\u2145", + "\u2911", + "\u0402", + "\u0405", + "\u040f", + "\u2021", + "\u21a1", + "\u2ae4", + "\u010e", + "\u0414", + "\u2207", + "\u0394", + "\ud507", + "\u00b4", + "\u02d9", + "\u02dd", + "\u0060", + "\u02dc", + "\u22c4", + "\u2146", + "\ud53b", + "\u00a8", + "\u20dc", + "\u2250", + "\u222f", + "\u00a8", + "\u21d3", + "\u21d0", + "\u21d4", + "\u2ae4", + "\u27f8", + "\u27fa", + "\u27f9", + "\u21d2", + "\u22a8", + "\u21d1", + "\u21d5", + "\u2225", + "\u2193", + "\u2913", + "\u21f5", + "\u0311", + "\u2950", + "\u295e", + "\u21bd", + "\u2956", + "\u295f", + "\u21c1", + "\u2957", + "\u22a4", + "\u21a7", + "\u21d3", + "\ud49f", + "\u0110", + "\u014a", + "\u00d0", + "\u00c9", + "\u011a", + "\u00ca", + "\u042d", + "\u0116", + "\ud508", + "\u00c8", + "\u2208", + "\u0112", + "\u25fb", + "\u25ab", + "\u0118", + "\ud53c", + "\u0395", + "\u2a75", + "\u2242", + "\u21cc", + "\u2130", + "\u2a73", + "\u0397", + "\u00cb", + "\u2203", + "\u2147", + "\u0424", + "\ud509", + "\u25fc", + "\u25aa", + "\ud53d", + "\u2200", + "\u2131", + "\u2131", + "\u0403", + "\u003e", + "\u0393", + "\u03dc", + "\u011e", + "\u0122", + "\u011c", + "\u0413", + "\u0120", + "\ud50a", + "\u22d9", + "\ud53e", + "\u2265", + "\u22db", + "\u2267", + "\u2aa2", + "\u2277", + "\u2a7e", + "\u2273", + "\ud4a2", + "\u226b", + "\u042a", + "\u02c7", + "\u005e", + "\u0124", + "\u210c", + "\u210b", + "\u210d", + "\u2500", + "\u210b", + "\u0126", + "\u224e", + "\u224f", + "\u0415", + "\u0132", + "\u0401", + "\u00cd", + "\u00ce", + "\u0418", + "\u0130", + "\u2111", + "\u00cc", + "\u2111", + "\u012a", + "\u2148", + "\u21d2", + "\u222b", + "\u22c2", + "\u2063", + "\u2062", + "\u012e", + "\ud540", + "\u0399", + "\u2110", + "\u0128", + "\u0406", + "\u00cf", + "\u0134", + "\u0419", + "\ud50d", + "\ud541", + "\ud4a5", + "\u0408", + "\u0404", + "\u0425", + "\u040c", + "\u039a", + "\u0136", + "\u041a", + "\ud50e", + "\ud542", + "\ud4a6", + "\u0409", + "\u003c", + "\u0139", + "\u039b", + "\u27ea", + "\u2112", + "\u219e", + "\u013d", + "\u013b", + "\u041b", + "\u27e8", + "\u2190", + "\u21e4", + "\u21c6", + "\u2308", + "\u27e6", + "\u2961", + "\u21c3", + "\u2959", + "\u230a", + "\u2194", + "\u294e", + "\u22a3", + "\u21a4", + "\u295a", + "\u22b2", + "\u29cf", + "\u22b4", + "\u2951", + "\u2960", + "\u21bf", + "\u2958", + "\u21bc", + "\u2952", + "\u21d0", + "\u21d4", + "\u22da", + "\u2266", + "\u2276", + "\u2aa1", + "\u2a7d", + "\u2272", + "\ud50f", + "\u22d8", + "\u21da", + "\u013f", + "\u27f5", + "\u27f7", + "\u27f6", + "\u27f8", + "\u27fa", + "\u27f9", + "\ud543", + "\u2199", + "\u2198", + "\u2112", + "\u21b0", + "\u0141", + "\u226a", + "\u2905", + "\u041c", + "\u205f", + "\u2133", + "\ud510", + "\u2213", + "\ud544", + "\u2133", + "\u039c", + "\u040a", + "\u0143", + "\u0147", + "\u0145", + "\u041d", + "\u200b", + "\u200b", + "\u200b", + "\u200b", + "\u226b", + "\u226a", + "\\u000a", + "\ud511", + "\u2060", + "\u00a0", + "\u2115", + "\u2aec", + "\u2262", + "\u226d", + "\u2226", + "\u2209", + "\u2260", + "\u2242", + "\u2204", + "\u226f", + "\u2271", + "\u2267", + "\u226b", + "\u2279", + "\u2a7e", + "\u2275", + "\u224e", + "\u224f", + "\u22ea", + "\u29cf", + "\u22ec", + "\u226e", + "\u2270", + "\u2278", + "\u226a", + "\u2a7d", + "\u2274", + "\u2aa2", + "\u2aa1", + "\u2280", + "\u2aaf", + "\u22e0", + "\u220c", + "\u22eb", + "\u29d0", + "\u22ed", + "\u228f", + "\u22e2", + "\u2290", + "\u22e3", + "\u2282", + "\u2288", + "\u2281", + "\u2ab0", + "\u22e1", + "\u227f", + "\u2283", + "\u2289", + "\u2241", + "\u2244", + "\u2247", + "\u2249", + "\u2224", + "\ud4a9", + "\u00d1", + "\u039d", + "\u0152", + "\u00d3", + "\u00d4", + "\u041e", + "\u0150", + "\ud512", + "\u00d2", + "\u014c", + "\u03a9", + "\u039f", + "\ud546", + "\u201c", + "\u2018", + "\u2a54", + "\ud4aa", + "\u00d8", + "\u00d5", + "\u2a37", + "\u00d6", + "\u203e", + "\u23de", + "\u23b4", + "\u23dc", + "\u2202", + "\u041f", + "\ud513", + "\u03a6", + "\u03a0", + "\u00b1", + "\u210c", + "\u2119", + "\u2abb", + "\u227a", + "\u2aaf", + "\u227c", + "\u227e", + "\u2033", + "\u220f", + "\u2237", + "\u221d", + "\ud4ab", + "\u03a8", + "\"", + "\ud514", + "\u211a", + "\ud4ac", + "\u2910", + "\u00ae", + "\u0154", + "\u27eb", + "\u21a0", + "\u2916", + "\u0158", + "\u0156", + "\u0420", + "\u211c", + "\u220b", + "\u21cb", + "\u296f", + "\u211c", + "\u03a1", + "\u27e9", + "\u2192", + "\u21e5", + "\u21c4", + "\u2309", + "\u27e7", + "\u295d", + "\u21c2", + "\u2955", + "\u230b", + "\u22a2", + "\u21a6", + "\u295b", + "\u22b3", + "\u29d0", + "\u22b5", + "\u294f", + "\u295c", + "\u21be", + "\u2954", + "\u21c0", + "\u2953", + "\u21d2", + "\u211d", + "\u2970", + "\u21db", + "\u211b", + "\u21b1", + "\u29f4", + "\u0429", + "\u0428", + "\u042c", + "\u015a", + "\u2abc", + "\u0160", + "\u015e", + "\u015c", + "\u0421", + "\ud516", + "\u2193", + "\u2190", + "\u2192", + "\u2191", + "\u03a3", + "\u2218", + "\ud54a", + "\u221a", + "\u25a1", + "\u2293", + "\u228f", + "\u2291", + "\u2290", + "\u2292", + "\u2294", + "\ud4ae", + "\u22c6", + "\u22d0", + "\u22d0", + "\u2286", + "\u227b", + "\u2ab0", + "\u227d", + "\u227f", + "\u220b", + "\u2211", + "\u22d1", + "\u2283", + "\u2287", + "\u22d1", + "\u00de", + "\u2122", + "\u040b", + "\u0426", + "\u0009", + "\u03a4", + "\u0164", + "\u0162", + "\u0422", + "\ud517", + "\u2234", + "\u0398", + "\u205f", + "\u2009", + "\u223c", + "\u2243", + "\u2245", + "\u2248", + "\ud54b", + "\u20db", + "\ud4af", + "\u0166", + "\u00da", + "\u219f", + "\u2949", + "\u040e", + "\u016c", + "\u00db", + "\u0423", + "\u0170", + "\ud518", + "\u00d9", + "\u016a", + "\u005f", + "\u23df", + "\u23b5", + "\u23dd", + "\u22c3", + "\u228e", + "\u0172", + "\ud54c", + "\u2191", + "\u2912", + "\u21c5", + "\u2195", + "\u296e", + "\u22a5", + "\u21a5", + "\u21d1", + "\u21d5", + "\u2196", + "\u2197", + "\u03d2", + "\u03a5", + "\u016e", + "\ud4b0", + "\u0168", + "\u00dc", + "\u22ab", + "\u2aeb", + "\u0412", + "\u22a9", + "\u2ae6", + "\u22c1", + "\u2016", + "\u2016", + "\u2223", + "\u007c", + "\u2758", + "\u2240", + "\u200a", + "\ud519", + "\ud54d", + "\ud4b1", + "\u22aa", + "\u0174", + "\u22c0", + "\ud51a", + "\ud54e", + "\ud4b2", + "\ud51b", + "\u039e", + "\ud54f", + "\ud4b3", + "\u042f", + "\u0407", + "\u042e", + "\u00dd", + "\u0176", + "\u042b", + "\ud51c", + "\ud550", + "\ud4b4", + "\u0178", + "\u0416", + "\u0179", + "\u017d", + "\u0417", + "\u017b", + "\u200b", + "\u0396", + "\u2128", + "\u2124", + "\ud4b5", + "\u00e1", + "\u0103", + "\u223e", + "\u223e", + "\u223f", + "\u00e2", + "\u00b4", + "\u0430", + "\u00e6", + "\u2061", + "\ud51e", + "\u00e0", + "\u2135", + "\u2135", + "\u03b1", + "\u0101", + "\u2a3f", + "\u0026", + "\u2227", + "\u2a55", + "\u2a5c", + "\u2a58", + "\u2a5a", + "\u2220", + "\u29a4", + "\u2220", + "\u2221", + "\u29a8", + "\u29a9", + "\u29aa", + "\u29ab", + "\u29ac", + "\u29ad", + "\u29ae", + "\u29af", + "\u221f", + "\u22be", + "\u299d", + "\u2222", + "\u00c5", + "\u237c", + "\u0105", + "\ud552", + "\u2248", + "\u2a70", + "\u2a6f", + "\u224a", + "\u224b", + "\u0027", + "\u2248", + "\u224a", + "\u00e5", + "\ud4b6", + "\u002a", + "\u2248", + "\u224d", + "\u00e3", + "\u00e4", + "\u2233", + "\u2a11", + "\u2aed", + "\u224c", + "\u03f6", + "\u2035", + "\u223d", + "\u22cd", + "\u22bd", + "\u2305", + "\u2305", + "\u23b5", + "\u23b6", + "\u224c", + "\u0431", + "\u201e", + "\u2235", + "\u2235", + "\u29b0", + "\u03f6", + "\u212c", + "\u03b2", + "\u2136", + "\u226c", + "\ud51f", + "\u22c2", + "\u25ef", + "\u22c3", + "\u2a00", + "\u2a01", + "\u2a02", + "\u2a06", + "\u2605", + "\u25bd", + "\u25b3", + "\u2a04", + "\u22c1", + "\u22c0", + "\u290d", + "\u29eb", + "\u25aa", + "\u25b4", + "\u25be", + "\u25c2", + "\u25b8", + "\u2423", + "\u2592", + "\u2591", + "\u2593", + "\u2588", + "\u003d", + "\u2261", + "\u2310", + "\ud553", + "\u22a5", + "\u22a5", + "\u22c8", + "\u2557", + "\u2554", + "\u2556", + "\u2553", + "\u2550", + "\u2566", + "\u2569", + "\u2564", + "\u2567", + "\u255d", + "\u255a", + "\u255c", + "\u2559", + "\u2551", + "\u256c", + "\u2563", + "\u2560", + "\u256b", + "\u2562", + "\u255f", + "\u29c9", + "\u2555", + "\u2552", + "\u2510", + "\u250c", + "\u2500", + "\u2565", + "\u2568", + "\u252c", + "\u2534", + "\u229f", + "\u229e", + "\u22a0", + "\u255b", + "\u2558", + "\u2518", + "\u2514", + "\u2502", + "\u256a", + "\u2561", + "\u255e", + "\u253c", + "\u2524", + "\u251c", + "\u2035", + "\u02d8", + "\u00a6", + "\ud4b7", + "\u204f", + "\u223d", + "\u22cd", + "\\", + "\u29c5", + "\u27c8", + "\u2022", + "\u2022", + "\u224e", + "\u2aae", + "\u224f", + "\u224f", + "\u0107", + "\u2229", + "\u2a44", + "\u2a49", + "\u2a4b", + "\u2a47", + "\u2a40", + "\u2229", + "\u2041", + "\u02c7", + "\u2a4d", + "\u010d", + "\u00e7", + "\u0109", + "\u2a4c", + "\u2a50", + "\u010b", + "\u00b8", + "\u29b2", + "\u00a2", + "\u00b7", + "\ud520", + "\u0447", + "\u2713", + "\u2713", + "\u03c7", + "\u25cb", + "\u29c3", + "\u02c6", + "\u2257", + "\u21ba", + "\u21bb", + "\u00ae", + "\u24c8", + "\u229b", + "\u229a", + "\u229d", + "\u2257", + "\u2a10", + "\u2aef", + "\u29c2", + "\u2663", + "\u2663", + "\u003a", + "\u2254", + "\u2254", + "\u002c", + "\u0040", + "\u2201", + "\u2218", + "\u2201", + "\u2102", + "\u2245", + "\u2a6d", + "\u222e", + "\ud554", + "\u2210", + "\u00a9", + "\u2117", + "\u21b5", + "\u2717", + "\ud4b8", + "\u2acf", + "\u2ad1", + "\u2ad0", + "\u2ad2", + "\u22ef", + "\u2938", + "\u2935", + "\u22de", + "\u22df", + "\u21b6", + "\u293d", + "\u222a", + "\u2a48", + "\u2a46", + "\u2a4a", + "\u228d", + "\u2a45", + "\u222a", + "\u21b7", + "\u293c", + "\u22de", + "\u22df", + "\u22ce", + "\u22cf", + "\u00a4", + "\u21b6", + "\u21b7", + "\u22ce", + "\u22cf", + "\u2232", + "\u2231", + "\u232d", + "\u21d3", + "\u2965", + "\u2020", + "\u2138", + "\u21ca", + "\u2193", + "\u2010", + "\u22a3", + "\u290f", + "\u02dd", + "\u010f", + "\u0434", + "\u2146", + "\u2021", + "\u21ca", + "\u2a77", + "\u00b0", + "\u03b4", + "\u29b1", + "\u297f", + "\ud521", + "\u21c3", + "\u21c2", + "\u22c4", + "\u22c4", + "\u2666", + "\u2666", + "\u00a8", + "\u03dd", + "\u22f2", + "\u00f7", + "\u00f7", + "\u22c7", + "\u22c7", + "\u0452", + "\u2199", + "\u231e", + "\u230d", + "\u0024", + "\ud555", + "\u02d9", + "\u2250", + "\u2251", + "\u2238", + "\u2214", + "\u22a1", + "\u2306", + "\u2193", + "\u21ca", + "\u21c3", + "\u21c2", + "\u2198", + "\u2910", + "\u231f", + "\u230c", + "\ud4b9", + "\u0455", + "\u29f6", + "\u0111", + "\u22f1", + "\u25bf", + "\u25be", + "\u21f5", + "\u296f", + "\u29a6", + "\u045f", + "\u27ff", + "\u2a77", + "\u2251", + "\u00e9", + "\u2a6e", + "\u011b", + "\u2256", + "\u00ea", + "\u2255", + "\u044d", + "\u0117", + "\u2147", + "\u2252", + "\ud522", + "\u2a9a", + "\u00e8", + "\u2a96", + "\u2a98", + "\u2a99", + "\u23e7", + "\u2113", + "\u2a95", + "\u2a97", + "\u0113", + "\u2205", + "\u2205", + "\u2205", + "\u2004", + "\u2005", + "\u2003", + "\u014b", + "\u2002", + "\u0119", + "\ud556", + "\u22d5", + "\u29e3", + "\u2a71", + "\u03b5", + "\u03b5", + "\u03f5", + "\u2256", + "\u2255", + "\u2242", + "\u2a96", + "\u2a95", + "\u003d", + "\u225f", + "\u2261", + "\u2a78", + "\u29e5", + "\u2253", + "\u2971", + "\u212f", + "\u2250", + "\u2242", + "\u03b7", + "\u00f0", + "\u00eb", + "\u20ac", + "\u0021", + "\u2203", + "\u2130", + "\u2147", + "\u2252", + "\u0444", + "\u2640", + "\ufb03", + "\ufb00", + "\ufb04", + "\ud523", + "\ufb01", + "\u0066", + "\u266d", + "\ufb02", + "\u25b1", + "\u0192", + "\ud557", + "\u2200", + "\u22d4", + "\u2ad9", + "\u2a0d", + "\u00bd", + "\u2153", + "\u00bc", + "\u2155", + "\u2159", + "\u215b", + "\u2154", + "\u2156", + "\u00be", + "\u2157", + "\u215c", + "\u2158", + "\u215a", + "\u215d", + "\u215e", + "\u2044", + "\u2322", + "\ud4bb", + "\u2267", + "\u2a8c", + "\u01f5", + "\u03b3", + "\u03dd", + "\u2a86", + "\u011f", + "\u011d", + "\u0433", + "\u0121", + "\u2265", + "\u22db", + "\u2265", + "\u2267", + "\u2a7e", + "\u2a7e", + "\u2aa9", + "\u2a80", + "\u2a82", + "\u2a84", + "\u22db", + "\u2a94", + "\ud524", + "\u226b", + "\u22d9", + "\u2137", + "\u0453", + "\u2277", + "\u2a92", + "\u2aa5", + "\u2aa4", + "\u2269", + "\u2a8a", + "\u2a8a", + "\u2a88", + "\u2a88", + "\u2269", + "\u22e7", + "\ud558", + "\u0060", + "\u210a", + "\u2273", + "\u2a8e", + "\u2a90", + "\u003e", + "\u2aa7", + "\u2a7a", + "\u22d7", + "\u2995", + "\u2a7c", + "\u2a86", + "\u2978", + "\u22d7", + "\u22db", + "\u2a8c", + "\u2277", + "\u2273", + "\u2269", + "\u2269", + "\u21d4", + "\u200a", + "\u00bd", + "\u210b", + "\u044a", + "\u2194", + "\u2948", + "\u21ad", + "\u210f", + "\u0125", + "\u2665", + "\u2665", + "\u2026", + "\u22b9", + "\ud525", + "\u2925", + "\u2926", + "\u21ff", + "\u223b", + "\u21a9", + "\u21aa", + "\ud559", + "\u2015", + "\ud4bd", + "\u210f", + "\u0127", + "\u2043", + "\u2010", + "\u00ed", + "\u2063", + "\u00ee", + "\u0438", + "\u0435", + "\u00a1", + "\u21d4", + "\ud526", + "\u00ec", + "\u2148", + "\u2a0c", + "\u222d", + "\u29dc", + "\u2129", + "\u0133", + "\u012b", + "\u2111", + "\u2110", + "\u2111", + "\u0131", + "\u22b7", + "\u01b5", + "\u2208", + "\u2105", + "\u221e", + "\u29dd", + "\u0131", + "\u222b", + "\u22ba", + "\u2124", + "\u22ba", + "\u2a17", + "\u2a3c", + "\u0451", + "\u012f", + "\ud55a", + "\u03b9", + "\u2a3c", + "\u00bf", + "\ud4be", + "\u2208", + "\u22f9", + "\u22f5", + "\u22f4", + "\u22f3", + "\u2208", + "\u2062", + "\u0129", + "\u0456", + "\u00ef", + "\u0135", + "\u0439", + "\ud527", + "\u0237", + "\ud55b", + "\ud4bf", + "\u0458", + "\u0454", + "\u03ba", + "\u03f0", + "\u0137", + "\u043a", + "\ud528", + "\u0138", + "\u0445", + "\u045c", + "\ud55c", + "\ud4c0", + "\u21da", + "\u21d0", + "\u291b", + "\u290e", + "\u2266", + "\u2a8b", + "\u2962", + "\u013a", + "\u29b4", + "\u2112", + "\u03bb", + "\u2329", + "\u27e8", + "\u2991", + "\u2a85", + "\u00ab", + "\u21c7", + "\u2190", + "\u21e4", + "\u291f", + "\u291d", + "\u21a9", + "\u21ab", + "\u2939", + "\u2973", + "\u21a2", + "\u2aab", + "\u2919", + "\u2aad", + "\u2aad", + "\u290c", + "\u2772", + "\u007b", + "\u005b", + "\u298b", + "\u298f", + "\u298d", + "\u013e", + "\u013c", + "\u2308", + "\u007b", + "\u043b", + "\u2936", + "\u201c", + "\u201e", + "\u2967", + "\u294b", + "\u21b2", + "\u2264", + "\u2190", + "\u21a2", + "\u21bd", + "\u21bc", + "\u21c7", + "\u2194", + "\u21c6", + "\u21cb", + "\u21ad", + "\u22cb", + "\u22da", + "\u2264", + "\u2266", + "\u2a7d", + "\u2a7d", + "\u2aa8", + "\u2a7f", + "\u2a81", + "\u2a83", + "\u22da", + "\u2a93", + "\u2a85", + "\u22d6", + "\u22da", + "\u2a8b", + "\u2276", + "\u2272", + "\u297c", + "\u230a", + "\ud529", + "\u2276", + "\u2a91", + "\u21bd", + "\u21bc", + "\u296a", + "\u2584", + "\u0459", + "\u226a", + "\u21c7", + "\u231e", + "\u296b", + "\u25fa", + "\u0140", + "\u23b0", + "\u23b0", + "\u2268", + "\u2a89", + "\u2a89", + "\u2a87", + "\u2a87", + "\u2268", + "\u22e6", + "\u27ec", + "\u21fd", + "\u27e6", + "\u27f5", + "\u27f7", + "\u27fc", + "\u27f6", + "\u21ab", + "\u21ac", + "\u2985", + "\ud55d", + "\u2a2d", + "\u2a34", + "\u2217", + "\u005f", + "\u25ca", + "\u25ca", + "\u29eb", + "\u0028", + "\u2993", + "\u21c6", + "\u21c6", + "\u231f", + "\u21cb", + "\u21cb", + "\u296d", + "\u200e", + "\u22bf", + "\u2039", + "\ud4c1", + "\u21b0", + "\u2272", + "\u2a8d", + "\u2a8f", + "\u005b", + "\u2018", + "\u201a", + "\u0142", + "\u003c", + "\u2aa6", + "\u2a79", + "\u22d6", + "\u22cb", + "\u22c9", + "\u2976", + "\u2a7b", + "\u2996", + "\u25c3", + "\u22b4", + "\u25c2", + "\u294a", + "\u2966", + "\u2268", + "\u2268", + "\u223a", + "\u00af", + "\u2642", + "\u2720", + "\u2720", + "\u21a6", + "\u21a6", + "\u21a7", + "\u21a4", + "\u21a5", + "\u25ae", + "\u2a29", + "\u043c", + "\u2014", + "\u2221", + "\ud52a", + "\u2127", + "\u00b5", + "\u2223", + "\u002a", + "\u2af0", + "\u00b7", + "\u2212", + "\u229f", + "\u2238", + "\u2a2a", + "\u2adb", + "\u2026", + "\u2213", + "\u22a7", + "\ud55e", + "\u2213", + "\ud4c2", + "\u223e", + "\u03bc", + "\u22b8", + "\u22b8", + "\u22d9", + "\u226b", + "\u226b", + "\u21cd", + "\u21ce", + "\u22d8", + "\u226a", + "\u226a", + "\u21cf", + "\u22af", + "\u22ae", + "\u2207", + "\u0144", + "\u2220", + "\u2249", + "\u2a70", + "\u224b", + "\u0149", + "\u2249", + "\u266e", + "\u266e", + "\u2115", + "\u00a0", + "\u224e", + "\u224f", + "\u2a43", + "\u0148", + "\u0146", + "\u2247", + "\u2a6d", + "\u2a42", + "\u043d", + "\u2013", + "\u2260", + "\u21d7", + "\u2924", + "\u2197", + "\u2197", + "\u2250", + "\u2262", + "\u2928", + "\u2242", + "\u2204", + "\u2204", + "\ud52b", + "\u2267", + "\u2271", + "\u2271", + "\u2267", + "\u2a7e", + "\u2a7e", + "\u2275", + "\u226f", + "\u226f", + "\u21ce", + "\u21ae", + "\u2af2", + "\u220b", + "\u22fc", + "\u22fa", + "\u220b", + "\u045a", + "\u21cd", + "\u2266", + "\u219a", + "\u2025", + "\u2270", + "\u219a", + "\u21ae", + "\u2270", + "\u2266", + "\u2a7d", + "\u2a7d", + "\u226e", + "\u2274", + "\u226e", + "\u22ea", + "\u22ec", + "\u2224", + "\ud55f", + "\u00ac", + "\u2209", + "\u22f9", + "\u22f5", + "\u2209", + "\u22f7", + "\u22f6", + "\u220c", + "\u220c", + "\u22fe", + "\u22fd", + "\u2226", + "\u2226", + "\u2afd", + "\u2202", + "\u2a14", + "\u2280", + "\u22e0", + "\u2aaf", + "\u2280", + "\u2aaf", + "\u21cf", + "\u219b", + "\u2933", + "\u219d", + "\u219b", + "\u22eb", + "\u22ed", + "\u2281", + "\u22e1", + "\u2ab0", + "\ud4c3", + "\u2224", + "\u2226", + "\u2241", + "\u2244", + "\u2244", + "\u2224", + "\u2226", + "\u22e2", + "\u22e3", + "\u2284", + "\u2ac5", + "\u2288", + "\u2282", + "\u2288", + "\u2ac5", + "\u2281", + "\u2ab0", + "\u2285", + "\u2ac6", + "\u2289", + "\u2283", + "\u2289", + "\u2ac6", + "\u2279", + "\u00f1", + "\u2278", + "\u22ea", + "\u22ec", + "\u22eb", + "\u22ed", + "\u03bd", + "\u0023", + "\u2116", + "\u2007", + "\u22ad", + "\u2904", + "\u224d", + "\u22ac", + "\u2265", + "\u003e", + "\u29de", + "\u2902", + "\u2264", + "\u003c", + "\u22b4", + "\u2903", + "\u22b5", + "\u223c", + "\u21d6", + "\u2923", + "\u2196", + "\u2196", + "\u2927", + "\u24c8", + "\u00f3", + "\u229b", + "\u229a", + "\u00f4", + "\u043e", + "\u229d", + "\u0151", + "\u2a38", + "\u2299", + "\u29bc", + "\u0153", + "\u29bf", + "\ud52c", + "\u02db", + "\u00f2", + "\u29c1", + "\u29b5", + "\u03a9", + "\u222e", + "\u21ba", + "\u29be", + "\u29bb", + "\u203e", + "\u29c0", + "\u014d", + "\u03c9", + "\u03bf", + "\u29b6", + "\u2296", + "\ud560", + "\u29b7", + "\u29b9", + "\u2295", + "\u2228", + "\u21bb", + "\u2a5d", + "\u2134", + "\u2134", + "\u00aa", + "\u00ba", + "\u22b6", + "\u2a56", + "\u2a57", + "\u2a5b", + "\u2134", + "\u00f8", + "\u2298", + "\u00f5", + "\u2297", + "\u2a36", + "\u00f6", + "\u233d", + "\u2225", + "\u00b6", + "\u2225", + "\u2af3", + "\u2afd", + "\u2202", + "\u043f", + "\u0025", + "\u002e", + "\u2030", + "\u22a5", + "\u2031", + "\ud52d", + "\u03c6", + "\u03d5", + "\u2133", + "\u260e", + "\u03c0", + "\u22d4", + "\u03d6", + "\u210f", + "\u210e", + "\u210f", + "\u002b", + "\u2a23", + "\u229e", + "\u2a22", + "\u2214", + "\u2a25", + "\u2a72", + "\u00b1", + "\u2a26", + "\u2a27", + "\u00b1", + "\u2a15", + "\ud561", + "\u00a3", + "\u227a", + "\u2ab3", + "\u2ab7", + "\u227c", + "\u2aaf", + "\u227a", + "\u2ab7", + "\u227c", + "\u2aaf", + "\u2ab9", + "\u2ab5", + "\u22e8", + "\u227e", + "\u2032", + "\u2119", + "\u2ab5", + "\u2ab9", + "\u22e8", + "\u220f", + "\u232e", + "\u2312", + "\u2313", + "\u221d", + "\u221d", + "\u227e", + "\u22b0", + "\ud4c5", + "\u03c8", + "\u2008", + "\ud52e", + "\u2a0c", + "\ud562", + "\u2057", + "\ud4c6", + "\u210d", + "\u2a16", + "\u003f", + "\u225f", + "\"", + "\u21db", + "\u21d2", + "\u291c", + "\u290f", + "\u2964", + "\u223d", + "\u0155", + "\u221a", + "\u29b3", + "\u232a", + "\u27e9", + "\u2992", + "\u29a5", + "\u00bb", + "\u21c9", + "\u2192", + "\u2975", + "\u21e5", + "\u2920", + "\u2933", + "\u291e", + "\u21aa", + "\u21ac", + "\u2945", + "\u2974", + "\u21a3", + "\u219d", + "\u291a", + "\u2236", + "\u211a", + "\u290d", + "\u2773", + "\u007d", + "\u005d", + "\u298c", + "\u298e", + "\u2990", + "\u0159", + "\u0157", + "\u2309", + "\u007d", + "\u0440", + "\u2937", + "\u2969", + "\u201d", + "\u201d", + "\u21b3", + "\u211c", + "\u211b", + "\u211c", + "\u211d", + "\u25ad", + "\u00ae", + "\u297d", + "\u230b", + "\ud52f", + "\u21c1", + "\u21c0", + "\u296c", + "\u03c1", + "\u03f1", + "\u2192", + "\u21a3", + "\u21c1", + "\u21c0", + "\u21c4", + "\u21cc", + "\u21c9", + "\u219d", + "\u22cc", + "\u02da", + "\u2253", + "\u21c4", + "\u21c4", + "\u21cc", + "\u21cc", + "\u200f", + "\u23b1", + "\u23b1", + "\u2aee", + "\u27ed", + "\u21fe", + "\u27e7", + "\u2986", + "\ud563", + "\u2a2e", + "\u2a35", + "\u0029", + "\u2994", + "\u2a12", + "\u21c9", + "\u203a", + "\ud4c7", + "\u21b1", + "\u005d", + "\u2019", + "\u2019", + "\u22cc", + "\u22ca", + "\u25b9", + "\u22b5", + "\u25b8", + "\u29ce", + "\u2968", + "\u211e", + "\u015b", + "\u201a", + "\u227b", + "\u2ab4", + "\u2ab8", + "\u0161", + "\u227d", + "\u2ab0", + "\u015f", + "\u015d", + "\u2ab6", + "\u2aba", + "\u22e9", + "\u2a13", + "\u227f", + "\u0441", + "\u22c5", + "\u22a1", + "\u2a66", + "\u21d8", + "\u2925", + "\u2198", + "\u2198", + "\u00a7", + "\u003b", + "\u2929", + "\u2216", + "\u2216", + "\u2736", + "\ud530", + "\u2322", + "\u266f", + "\u0449", + "\u0448", + "\u2223", + "\u2225", + "\u00ad", + "\u03c3", + "\u03c2", + "\u03c2", + "\u223c", + "\u2a6a", + "\u2243", + "\u2243", + "\u2a9e", + "\u2aa0", + "\u2a9d", + "\u2a9f", + "\u2246", + "\u2a24", + "\u2972", + "\u2190", + "\u2216", + "\u2a33", + "\u29e4", + "\u2223", + "\u2323", + "\u2aaa", + "\u2aac", + "\u2aac", + "\u044c", + "\u002f", + "\u29c4", + "\u233f", + "\ud564", + "\u2660", + "\u2660", + "\u2225", + "\u2293", + "\u2293", + "\u2294", + "\u2294", + "\u228f", + "\u2291", + "\u228f", + "\u2291", + "\u2290", + "\u2292", + "\u2290", + "\u2292", + "\u25a1", + "\u25a1", + "\u25aa", + "\u25aa", + "\u2192", + "\ud4c8", + "\u2216", + "\u2323", + "\u22c6", + "\u2606", + "\u2605", + "\u03f5", + "\u03d5", + "\u00af", + "\u2282", + "\u2ac5", + "\u2abd", + "\u2286", + "\u2ac3", + "\u2ac1", + "\u2acb", + "\u228a", + "\u2abf", + "\u2979", + "\u2282", + "\u2286", + "\u2ac5", + "\u228a", + "\u2acb", + "\u2ac7", + "\u2ad5", + "\u2ad3", + "\u227b", + "\u2ab8", + "\u227d", + "\u2ab0", + "\u2aba", + "\u2ab6", + "\u22e9", + "\u227f", + "\u2211", + "\u266a", + "\u00b9", + "\u00b2", + "\u00b3", + "\u2283", + "\u2ac6", + "\u2abe", + "\u2ad8", + "\u2287", + "\u2ac4", + "\u27c9", + "\u2ad7", + "\u297b", + "\u2ac2", + "\u2acc", + "\u228b", + "\u2ac0", + "\u2283", + "\u2287", + "\u2ac6", + "\u228b", + "\u2acc", + "\u2ac8", + "\u2ad4", + "\u2ad6", + "\u21d9", + "\u2926", + "\u2199", + "\u2199", + "\u292a", + "\u00df", + "\u2316", + "\u03c4", + "\u23b4", + "\u0165", + "\u0163", + "\u0442", + "\u20db", + "\u2315", + "\ud531", + "\u2234", + "\u2234", + "\u03b8", + "\u03d1", + "\u03d1", + "\u2248", + "\u223c", + "\u2009", + "\u2248", + "\u223c", + "\u00fe", + "\u02dc", + "\u00d7", + "\u22a0", + "\u2a31", + "\u2a30", + "\u222d", + "\u2928", + "\u22a4", + "\u2336", + "\u2af1", + "\ud565", + "\u2ada", + "\u2929", + "\u2034", + "\u2122", + "\u25b5", + "\u25bf", + "\u25c3", + "\u22b4", + "\u225c", + "\u25b9", + "\u22b5", + "\u25ec", + "\u225c", + "\u2a3a", + "\u2a39", + "\u29cd", + "\u2a3b", + "\u23e2", + "\ud4c9", + "\u0446", + "\u045b", + "\u0167", + "\u226c", + "\u219e", + "\u21a0", + "\u21d1", + "\u2963", + "\u00fa", + "\u21c8", + "\u2191", + "\u045e", + "\u016d", + "\u00fb", + "\u0443", + "\u21c5", + "\u0171", + "\u296e", + "\u297e", + "\ud532", + "\u00f9", + "\u21bf", + "\u21be", + "\u2580", + "\u231c", + "\u231c", + "\u230f", + "\u25f8", + "\u016b", + "\u00a8", + "\u0173", + "\ud566", + "\u2191", + "\u2195", + "\u21bf", + "\u21be", + "\u228e", + "\u03c5", + "\u03d2", + "\u03c5", + "\u21c8", + "\u231d", + "\u231d", + "\u230e", + "\u016f", + "\u25f9", + "\ud4ca", + "\u22f0", + "\u0169", + "\u25b5", + "\u25b4", + "\u21c8", + "\u00fc", + "\u29a7", + "\u21d5", + "\u2ae8", + "\u2ae9", + "\u22a8", + "\u299c", + "\u03f5", + "\u03f0", + "\u2205", + "\u03d5", + "\u03d6", + "\u221d", + "\u2195", + "\u03f1", + "\u03c2", + "\u228a", + "\u2acb", + "\u228b", + "\u2acc", + "\u03d1", + "\u22b2", + "\u22b3", + "\u0432", + "\u22a2", + "\u2228", + "\u22bb", + "\u225a", + "\u22ee", + "\u007c", + "\u007c", + "\ud533", + "\u22b2", + "\u2282", + "\u2283", + "\ud567", + "\u221d", + "\u22b3", + "\ud4cb", + "\u2acb", + "\u228a", + "\u2acc", + "\u228b", + "\u299a", + "\u0175", + "\u2a5f", + "\u2227", + "\u2259", + "\u2118", + "\ud534", + "\ud568", + "\u2118", + "\u2240", + "\u2240", + "\ud4cc", + "\u22c2", + "\u25ef", + "\u22c3", + "\u25bd", + "\ud535", + "\u27fa", + "\u27f7", + "\u03be", + "\u27f8", + "\u27f5", + "\u27fc", + "\u22fb", + "\u2a00", + "\ud569", + "\u2a01", + "\u2a02", + "\u27f9", + "\u27f6", + "\ud4cd", + "\u2a06", + "\u2a04", + "\u25b3", + "\u22c1", + "\u22c0", + "\u00fd", + "\u044f", + "\u0177", + "\u044b", + "\u00a5", + "\ud536", + "\u0457", + "\ud56a", + "\ud4ce", + "\u044e", + "\u00ff", + "\u017a", + "\u017e", + "\u0437", + "\u017c", + "\u2128", + "\u03b6", + "\ud537", + "\u0436", + "\u21dd", + "\ud56b", + "\ud4cf", + "\u200d", + "\u200c", + "\u0027", + "\u0040", + "\u005e", + "\u0060", + "\u007e",}; - static - { - for (int i = 0; i < entityKeys.length; i++) - { + static { + for (int i = 0; i < entityKeys.length; i++) { map.put(entityKeys[i], entityReplacements[i]); } } diff --git a/src/gov/nasa/worldwind/util/FileTree.java b/src/gov/nasa/worldwind/util/FileTree.java index 8689ee383e..f0d795c8b3 100644 --- a/src/gov/nasa/worldwind/util/FileTree.java +++ b/src/gov/nasa/worldwind/util/FileTree.java @@ -13,8 +13,8 @@ * @author dcollins * @version $Id: FileTree.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FileTree implements Iterable -{ +public class FileTree implements Iterable { + private File root; private int mode = FILES_AND_DIRECTORIES; @@ -22,96 +22,92 @@ public class FileTree implements Iterable public static final int DIRECTORIES_ONLY = 2; public static final int FILES_AND_DIRECTORIES = 3; - public FileTree() - { + public FileTree() { this(null); } - public FileTree(File root) - { + public FileTree(File root) { this.root = root; } - public File getRoot() - { + public File getRoot() { return this.root; } - public void setRoot(File root) - { + public void setRoot(File root) { this.root = root; } - public int getMode() - { + public int getMode() { return this.mode; } - public void setMode(int mode) - { - if (!validate(mode)) + public void setMode(int mode) { + if (!validate(mode)) { throw new IllegalArgumentException("mode:" + mode); + } this.mode = mode; } - public List asList() - { + public List asList() { return asList(null); } - public List asList(FileFilter fileFilter) - { + public List asList(FileFilter fileFilter) { return makeList(this.root, fileFilter, this.mode); } - public Iterator iterator() - { + public Iterator iterator() { return iterator(null); } - public Iterator iterator(FileFilter fileFilter) - { + public Iterator iterator(FileFilter fileFilter) { return new FileTreeIterator(this.root, fileFilter, this.mode); } - private static List makeList(File root, FileFilter fileFilter, int mode) - { + private static List makeList(File root, FileFilter fileFilter, int mode) { Queue dirs = new LinkedList(); - if (isDirectory(root)) + if (isDirectory(root)) { dirs.offer(root); + } LinkedList result = new LinkedList(); - while (dirs.peek() != null) + while (dirs.peek() != null) { expand(dirs.poll(), fileFilter, mode, result, dirs); + } return result; } private static class FileTreeIterator implements Iterator { + private final Queue dirs = new LinkedList(); private final Queue files = new LinkedList(); private final FileFilter fileFilter; private final int mode; private FileTreeIterator(File root, FileFilter fileFilter, int mode) { - if (isDirectory(root)) + if (isDirectory(root)) { this.dirs.offer(root); + } this.fileFilter = fileFilter; this.mode = mode; } public boolean hasNext() { - if (this.files.peek() == null) + if (this.files.peek() == null) { expandUntilFilesFound(); + } return this.files.peek() != null; } public File next() { if (this.files.peek() == null) { expandUntilFilesFound(); - if (this.files.peek() == null) + if (this.files.peek() == null) { throw new NoSuchElementException(); + } } return this.files.poll(); } @@ -121,8 +117,9 @@ public void remove() { } private void expandUntilFilesFound() { - while (this.dirs.peek() != null && this.files.peek() == null) + while (this.dirs.peek() != null && this.files.peek() == null) { expand(this.dirs.poll()); + } } private void expand(File directory) { @@ -133,27 +130,19 @@ private void expand(File directory) { } private static void expand(File file, FileFilter fileFilter, int mode, - Queue outFiles, Queue outDirs) - { - if (file != null) - { + Queue outFiles, Queue outDirs) { + if (file != null) { File[] list = file.listFiles(); - if (list != null) - { - for (File child : list) - { - if (child != null) - { + if (list != null) { + for (File child : list) { + if (child != null) { boolean isDir = child.isDirectory(); - if (isDir) - { + if (isDir) { outDirs.offer(child); } - - if ((!isDir && isDisplayFiles(mode)) || (isDir && isDisplayDirectories(mode))) - { - if (fileFilter == null || fileFilter.accept(child)) - { + + if ((!isDir && isDisplayFiles(mode)) || (isDir && isDisplayDirectories(mode))) { + if (fileFilter == null || fileFilter.accept(child)) { outFiles.offer(child); } } @@ -163,25 +152,21 @@ private static void expand(File file, FileFilter fileFilter, int mode, } } - private static boolean isDirectory(File file) - { + private static boolean isDirectory(File file) { return file != null && file.exists() && file.isDirectory(); } - private static boolean isDisplayFiles(int mode) - { + private static boolean isDisplayFiles(int mode) { return mode == FILES_ONLY || mode == FILES_AND_DIRECTORIES; } - private static boolean isDisplayDirectories(int mode) - { + private static boolean isDisplayDirectories(int mode) { return mode == DIRECTORIES_ONLY || mode == FILES_AND_DIRECTORIES; } - private static boolean validate(int mode) - { + private static boolean validate(int mode) { return mode == FILES_ONLY - || mode == DIRECTORIES_ONLY - || mode == FILES_AND_DIRECTORIES; + || mode == DIRECTORIES_ONLY + || mode == FILES_AND_DIRECTORIES; } } diff --git a/src/gov/nasa/worldwind/util/GLUTessellatorSupport.java b/src/gov/nasa/worldwind/util/GLUTessellatorSupport.java index 1a09595144..99dfad2d81 100644 --- a/src/gov/nasa/worldwind/util/GLUTessellatorSupport.java +++ b/src/gov/nasa/worldwind/util/GLUTessellatorSupport.java @@ -19,33 +19,33 @@ * The standard pattern for using GLUTessellatorSupport to prepare a GLUtessellator is as follows: * GLUTessellatorSupport glts = new GLUTessellatorSupport();
                  GLUtessellatorCallback cb = ...; // Reference to an * implementation of GLUtessellatorCallback.
                  Vec4 normal = new Vec4(0, 0, 1); // The polygon's normal. This example - * shows an appropriate normal for tessellating x-y coordinates.


                  glts.beginTessellation(cb, new Vec4(0, - * 0, 1));
                  try
                  {
                  GLUtessellator tess = glts.getGLUtessellator();
                  }
                  finally
                  {
                  + * shows an appropriate normal for tessellating x-y coordinates.


                  glts.beginTessellation(cb, new Vec4(0, 0, + * 1));
                  try
                  {
                  GLUtessellator tess = glts.getGLUtessellator();
                  }
                  finally
                  {
                  * glts.endTessellation();
                  }
                  * * @author dcollins * @version $Id: GLUTessellatorSupport.java 3427 2015-09-30 23:24:13Z dcollins $ */ -public class GLUTessellatorSupport -{ +public class GLUTessellatorSupport { + protected GLUtessellator tess; - /** Creates a new GLUTessellatorSupport, but otherwise does nothing. */ - public GLUTessellatorSupport() - { + /** + * Creates a new GLUTessellatorSupport, but otherwise does nothing. + */ + public GLUTessellatorSupport() { } /** - * Returns this GLUTessellatorSupport's internal {@link com.jogamp.opengl.glu.GLUtessellator} instance. This - * returns a valid GLUtessellator instance if called between {@link #beginTessellation(com.jogamp.opengl.glu.GLUtessellatorCallback, + * Returns this GLUTessellatorSupport's internal {@link com.jogamp.opengl.glu.GLUtessellator} instance. This returns + * a valid GLUtessellator instance if called between {@link #beginTessellation(com.jogamp.opengl.glu.GLUtessellatorCallback, * gov.nasa.worldwind.geom.Vec4)} and {@link #endTessellation()}. This returns null if called from outside a * beginTessellation/endTessellation block. * * @return the internal GLUtessellator instance, or null if called from outside a beginTessellation/endTessellation * block. */ - public GLUtessellator getGLUtessellator() - { + public GLUtessellator getGLUtessellator() { return this.tess; } @@ -57,21 +57,18 @@ public GLUtessellator getGLUtessellator() * double, double, double)}, respectively. * * @param callback the callback to configure the GLU tessellator with. - * @param normal the normal to configure the GLU tessellator with. + * @param normal the normal to configure the GLU tessellator with. * * @throws IllegalArgumentException if the callback or the normal is null. */ - public void beginTessellation(GLUtessellatorCallback callback, Vec4 normal) - { - if (callback == null) - { + public void beginTessellation(GLUtessellatorCallback callback, Vec4 normal) { + if (callback == null) { String message = Logging.getMessage("nullValue.CallbackIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (normal == null) - { + if (normal == null) { String message = Logging.getMessage("nullValue.NormalIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -89,8 +86,7 @@ public void beginTessellation(GLUtessellatorCallback callback, Vec4 normal) * Frees any GLU resources used by this GLUTessellatorSupport, and invalidates this instance's internal GLU * tessellator. */ - public void endTessellation() - { + public void endTessellation() { GLU.gluTessCallback(this.tess, GLU.GLU_TESS_BEGIN, null); GLU.gluTessCallback(this.tess, GLU.GLU_TESS_VERTEX, null); GLU.gluTessCallback(this.tess, GLU.GLU_TESS_END, null); @@ -108,10 +104,8 @@ public void endTessellation() * * @throws IllegalArgumentException if the GL is null. */ - public static GLUtessellatorCallback createOGLDrawPrimitivesCallback(GL2 gl) - { - if (gl == null) - { + public static GLUtessellatorCallback createOGLDrawPrimitivesCallback(GL2 gl) { + if (gl == null) { String message = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -128,10 +122,8 @@ public static GLUtessellatorCallback createOGLDrawPrimitivesCallback(GL2 gl) * * @return a string description of the error number. */ - public static String convertGLUTessErrorToString(int errno) - { - switch (errno) - { + public static String convertGLUTessErrorToString(int errno) { + switch (errno) { case GLU.GLU_TESS_MISSING_BEGIN_POLYGON: return "missing begin polygon"; case GLU.GLU_TESS_MISSING_END_POLYGON: @@ -149,14 +141,12 @@ public static String convertGLUTessErrorToString(int errno) } } - protected static class OGLDrawPrimitivesCallback extends GLUtessellatorCallbackAdapter - { + protected static class OGLDrawPrimitivesCallback extends GLUtessellatorCallbackAdapter { + protected final GL2 gl; - public OGLDrawPrimitivesCallback(GL2 gl) - { - if (gl == null) - { + public OGLDrawPrimitivesCallback(GL2 gl) { + if (gl == null) { String message = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -165,96 +155,90 @@ public OGLDrawPrimitivesCallback(GL2 gl) this.gl = gl; } - public void begin(int type) - { + public void begin(int type) { this.gl.glBegin(type); } - public void vertex(Object vertexData) - { + public void vertex(Object vertexData) { double[] coords = (double[]) vertexData; this.gl.glVertex3f((float) coords[0], (float) coords[1], (float) coords[2]); } - public void end() - { + public void end() { this.gl.glEnd(); } - public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) - { + public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) { outData[0] = coords; } } - /** Provides the callback class used to capture the shapes determined by the tessellator. */ - public static class CollectIndexListsCallback extends GLUtessellatorCallbackAdapter - { + /** + * Provides the callback class used to capture the shapes determined by the tessellator. + */ + public static class CollectIndexListsCallback extends GLUtessellatorCallbackAdapter { + protected int numIndices; protected int currentType; protected List currentPrim; protected List> prims = new ArrayList>(); protected List primTypes = new ArrayList(); - public List> getPrims() - { + public List> getPrims() { return prims; } - public List getPrimTypes() - { + public List getPrimTypes() { return primTypes; } - public int getNumIndices() - { + public int getNumIndices() { return this.numIndices; } - public void begin(int type) - { + public void begin(int type) { this.currentType = type; this.currentPrim = new ArrayList(); } - public void vertex(Object vertexData) - { + public void vertex(Object vertexData) { this.currentPrim.add((Integer) vertexData); ++this.numIndices; } @Override - public void end() - { + public void end() { this.primTypes.add(this.currentType); this.prims.add(this.currentPrim); this.currentPrim = null; } - public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) - { + public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) { // System.out.println("COMBINE CALLED"); outData[0] = data[0]; } } - /** Provides a container for associating a tessellator's vertex with its index and application-specified edge flag. */ - public static class VertexData - { + /** + * Provides a container for associating a tessellator's vertex with its index and application-specified edge flag. + */ + public static class VertexData { + public final int index; public final boolean edgeFlag; - public VertexData(int index, boolean edgeFlag) - { + public VertexData(int index, boolean edgeFlag) { this.index = index; this.edgeFlag = edgeFlag; } } - /** Provides the callback class used to capture triangle and line primitive indices determined by the tessellator. */ - public static class CollectPrimitivesCallback extends GLUtessellatorCallbackAdapter - { + /** + * Provides the callback class used to capture triangle and line primitive indices determined by the tessellator. + */ + public static class CollectPrimitivesCallback extends GLUtessellatorCallbackAdapter { + protected List triangles = new ArrayList(); protected List lines = new ArrayList(); protected IntBuffer triangleBuffer = IntBuffer.allocate(0); @@ -265,27 +249,22 @@ public static class CollectPrimitivesCallback extends GLUtessellatorCallbackAdap protected boolean[] edgeFlags = {true, true, true}; protected boolean edgeFlag = true; - public CollectPrimitivesCallback() - { + public CollectPrimitivesCallback() { } - public IntBuffer getTriangleIndices() - { + public IntBuffer getTriangleIndices() { return (IntBuffer) this.triangleBuffer.flip(); } - public IntBuffer getLineIndices() - { + public IntBuffer getLineIndices() { return (IntBuffer) this.lineBuffer.flip(); } - public int getError() - { + public int getError() { return this.error; } - public void attach(GLUtessellator tessellator) - { + public void attach(GLUtessellator tessellator) { GLU.gluTessCallback(tessellator, GLU.GLU_TESS_BEGIN, this); GLU.gluTessCallback(tessellator, GLU.GLU_TESS_END, this); GLU.gluTessCallback(tessellator, GLU.GLU_TESS_VERTEX, this); @@ -293,8 +272,7 @@ public void attach(GLUtessellator tessellator) GLU.gluTessCallback(tessellator, GLU.GLU_TESS_ERROR, this); } - public void reset() - { + public void reset() { this.triangles.clear(); this.lines.clear(); this.triangleBuffer.clear(); @@ -305,40 +283,33 @@ public void reset() } @Override - public void begin(int type) - { - if (type != GL.GL_TRIANGLES) - { + public void begin(int type) { + if (type != GL.GL_TRIANGLES) { String msg = Logging.getMessage("generic.UnexpectedPrimitiveType", type); Logging.logger().warning(msg); } } @Override - public void end() - { + public void end() { this.triangleBuffer = IntBuffer.allocate(this.triangles.size()); - for (Integer index : this.triangles) - { + for (Integer index : this.triangles) { this.triangleBuffer.put(index); } this.lineBuffer = IntBuffer.allocate(this.lines.size()); - for (Integer index : this.lines) - { + for (Integer index : this.lines) { this.lineBuffer.put(index); } } @Override - public void vertex(Object vertexData) - { + public void vertex(Object vertexData) { this.vertices[this.index] = (VertexData) vertexData; this.edgeFlags[this.index] = this.edgeFlag; this.index++; - if (this.index == 3) - { + if (this.index == 3) { VertexData i = this.vertices[0]; VertexData j = this.vertices[1]; VertexData k = this.vertices[2]; @@ -346,20 +317,17 @@ public void vertex(Object vertexData) this.triangles.add(j.index); this.triangles.add(k.index); - if (this.edgeFlags[0] && (i.edgeFlag || j.edgeFlag)) - { + if (this.edgeFlags[0] && (i.edgeFlag || j.edgeFlag)) { this.lines.add(i.index); this.lines.add(j.index); } - if (this.edgeFlags[1] && (j.edgeFlag || k.edgeFlag)) - { + if (this.edgeFlags[1] && (j.edgeFlag || k.edgeFlag)) { this.lines.add(j.index); this.lines.add(k.index); } - if (this.edgeFlags[2] && (k.edgeFlag || i.edgeFlag)) - { + if (this.edgeFlags[2] && (k.edgeFlag || i.edgeFlag)) { this.lines.add(k.index); this.lines.add(i.index); } @@ -369,14 +337,12 @@ public void vertex(Object vertexData) } @Override - public void edgeFlag(boolean flag) - { + public void edgeFlag(boolean flag) { this.edgeFlag = flag; } @Override - public void error(int errno) - { + public void error(int errno) { this.error = errno; } } @@ -391,8 +357,8 @@ public void error(int errno) * passed to gluTessVertex must be a double array containing three elements - the x, y and z coordinates associated * with the vertex. */ - public static class RecursiveCallback extends GLUtessellatorCallbackAdapter - { + public static class RecursiveCallback extends GLUtessellatorCallbackAdapter { + /** * The GLU tessellator that receives the tessellation results sent to this callback. */ @@ -402,15 +368,13 @@ public static class RecursiveCallback extends GLUtessellatorCallbackAdapter * Creates a new RecursiveCallback with the GLU tessellator that receives boundary tessellation results. * * @param tessellator the GLU tessellator that receives the tessellation results sent to this callback. This - * tessellator may be configured in any way the caller chooses, but should be prepared to - * receive contour input from this callback. + * tessellator may be configured in any way the caller chooses, but should be prepared to receive contour input + * from this callback. * * @throws java.lang.IllegalArgumentException if the tessellator is null. */ - public RecursiveCallback(GLUtessellator tessellator) - { - if (tessellator == null) - { + public RecursiveCallback(GLUtessellator tessellator) { + if (tessellator == null) { String msg = Logging.getMessage("nullValue.TessellatorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -426,8 +390,7 @@ public RecursiveCallback(GLUtessellator tessellator) * @param type the GL primitive type. Must be GL_LINE_LOOP. */ @Override - public void begin(int type) - { + public void begin(int type) { GLU.gluTessBeginContour(this.tess); } @@ -438,11 +401,10 @@ public void begin(int type) * calling gluTessVertex(tessellator, (double[]) vertexData, 0, vertexData). * * @param vertexData the caller specified vertex data. Must be a double array containing three elements - the x, - * y and z coordinates associated with the vertex. + * y and z coordinates associated with the vertex. */ @Override - public void vertex(Object vertexData) - { + public void vertex(Object vertexData) { GLU.gluTessVertex(this.tess, (double[]) vertexData, 0, vertexData); } @@ -451,8 +413,7 @@ public void vertex(Object vertexData) * contour with the GLU tessellator specified during construction by calling gluTessEndContour(tessellator). */ @Override - public void end() - { + public void end() { GLU.gluTessEndContour(this.tess); } @@ -461,15 +422,14 @@ public void end() * vertex is a linear combination of the original vertices. This assigns the first element of outData to coords, * the coordinates of the new vertex. * - * @param coords A three element array containing the x, y and z coordinates of the new vertex. + * @param coords A three element array containing the x, y and z coordinates of the new vertex. * @param vertexData The caller specified vertex data of the original vertices. - * @param weight The coefficients of the linear combination. These weights sum to 1. - * @param outData A one element array that must contain the caller specified data associated with the new - * vertex after this method returns. + * @param weight The coefficients of the linear combination. These weights sum to 1. + * @param outData A one element array that must contain the caller specified data associated with the new vertex + * after this method returns. */ @Override - public void combine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) - { + public void combine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) { outData[0] = coords; } @@ -480,8 +440,7 @@ public void combine(double[] coords, Object[] vertexData, float[] weight, Object * @param errno a GLU enumeration indicating the error. */ @Override - public void error(int errno) - { + public void error(int errno) { String errstr = convertGLUTessErrorToString(errno); String msg = Logging.getMessage("generic.ExceptionWhileTessellating", errstr); Logging.logger().severe(msg); diff --git a/src/gov/nasa/worldwind/util/GeographicImageInterpolator.java b/src/gov/nasa/worldwind/util/GeographicImageInterpolator.java index cc00d8cf9b..d6e66b76bb 100644 --- a/src/gov/nasa/worldwind/util/GeographicImageInterpolator.java +++ b/src/gov/nasa/worldwind/util/GeographicImageInterpolator.java @@ -18,16 +18,18 @@ * @author dcollins * @version $Id: GeographicImageInterpolator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GeographicImageInterpolator extends ImageInterpolator -{ +public class GeographicImageInterpolator extends ImageInterpolator { + /** * GeographicCell extends {@link gov.nasa.worldwind.util.ImageInterpolator.Cell} to correctly handle image cells * which have geographic coordinates. Unlike its superclass, which works in Cartesian coordinates, GeographicCell * handles the singularities of geographic coordinates, such as image cells which cross the international dateline. */ - protected static class GeographicCell extends Cell - { - /** Denotes if the pixels in this geographic image cell crosses the international dateline. */ + protected static class GeographicCell extends Cell { + + /** + * Denotes if the pixels in this geographic image cell crosses the international dateline. + */ protected boolean crossesDateline; /** @@ -38,8 +40,7 @@ protected static class GeographicCell extends Cell * @param n0 the cell's bottom image coordinate. * @param n1 the cell's top image coordinate. */ - public GeographicCell(int m0, int m1, int n0, int n1) - { + public GeographicCell(int m0, int m1, int n0, int n1) { super(m0, m1, n0, n1); } @@ -54,8 +55,7 @@ public GeographicCell(int m0, int m1, int n0, int n1) * @return a new GeographicCell with the specified image coordinates. */ @Override - protected Cell makeChildCell(int m0, int m1, int n0, int n1) - { + protected Cell makeChildCell(int m0, int m1, int n0, int n1) { return new GeographicCell(m0, m1, n0, n1); } @@ -64,8 +64,7 @@ protected Cell makeChildCell(int m0, int m1, int n0, int n1) * * @return true if this cell crosses the international dateline; false otherwise. */ - public boolean isCrossesDateline() - { + public boolean isCrossesDateline() { return this.crossesDateline; } @@ -79,11 +78,9 @@ public boolean isCrossesDateline() * @return true if the (x, y) point intersects this cell; false otherwise. */ @Override - public boolean intersects(float x, float y) - { + public boolean intersects(float x, float y) { // Invoke the superclass functionality if this cell doesn't cross the international dateline. - if (!this.isCrossesDateline()) - { + if (!this.isCrossesDateline()) { return super.intersects(x, y); } @@ -91,7 +88,7 @@ public boolean intersects(float x, float y) // of the dateline. minx is the extreme value in the eastern hemisphere, and maxx is the extreme value in // the western hemisphere. return ((x >= this.minx && x <= 180f) || (x >= -180f && x <= this.maxx)) - && y >= this.miny && y <= this.maxy; + && y >= this.miny && y <= this.maxy; } /** @@ -99,17 +96,15 @@ public boolean intersects(float x, float y) * cell does not cross the dateline, this invokes the superclass' functionality. * * @param dim the image's dimensions. - * @param xs the x-coordinates of the image's pixels. Must contain at least gridSize.width * + * @param xs the x-coordinates of the image's pixels. Must contain at least gridSize.width * * gridSize.height elements. - * @param ys the y-coordinates of the image's pixels. Must contain at least gridSize.width * + * @param ys the y-coordinates of the image's pixels. Must contain at least gridSize.width * * gridSize.height elements. */ @Override - protected void computeExtremesFromLocations(Dimension dim, float[] xs, float[] ys) - { + protected void computeExtremesFromLocations(Dimension dim, float[] xs, float[] ys) { // Invoke the superclass functionality if this cell doesn't cross the international dateline. - if (!this.longitudesCrossDateline(dim, xs)) - { + if (!this.longitudesCrossDateline(dim, xs)) { super.computeExtremesFromLocations(dim, xs, ys); return; } @@ -126,23 +121,25 @@ protected void computeExtremesFromLocations(Dimension dim, float[] xs, float[] y // Assume that dateline crossing cells span the shorter of two possible paths around the globe. Therefore // each location contributes to the extreme in its hemisphere. minx is the furthest value from the dateline // in the eastern hemisphere. maxx is the furthest value from the dateline in the western hemisphere. - for (int j = this.n0; j <= this.n1; j++) - { - for (int i = this.m0; i <= this.m1; i++) - { + for (int j = this.n0; j <= this.n1; j++) { + for (int i = this.m0; i <= this.m1; i++) { int k = j * dim.width + i; float x = xs[k]; float y = ys[k]; - if (this.minx > x && x > 0f) + if (this.minx > x && x > 0f) { this.minx = x; - if (this.maxx < x && x < 0f) + } + if (this.maxx < x && x < 0f) { this.maxx = x; + } - if (this.miny > y) + if (this.miny > y) { this.miny = y; - if (this.maxy < y) + } + if (this.maxy < y) { this.maxy = y; + } } } } @@ -152,11 +149,9 @@ protected void computeExtremesFromLocations(Dimension dim, float[] xs, float[] y * dateline. If the this cell does not cross the dateline, this invokes the superclass' functionality. */ @Override - protected void computeExtremesFromChildren() - { + protected void computeExtremesFromChildren() { // Invoke the superclass functionality if this cell doesn't cross the international dateline. - if (!this.childrenCrossDateline()) - { + if (!this.childrenCrossDateline()) { super.computeExtremesFromChildren(); return; } @@ -173,35 +168,41 @@ protected void computeExtremesFromChildren() // Assume that dateline crossing cells span the shorter of two possible paths around the globe. Therefore // each location contributes to the extreme in its hemisphere. minx is the furthest value from the dateline // in the eastern hemisphere. maxx is the furthest value from the dateline in the western hemisphere. - for (Cell t : this.children) - { + for (Cell t : this.children) { // The child cell crosses the dateline. This cell's minx and maxx have the same meaning as the child // cell, so a simple comparison determines this cell's extreme x values. - if (((GeographicCell) t).isCrossesDateline()) - { - if (this.minx > t.minx) + if (((GeographicCell) t).isCrossesDateline()) { + if (this.minx > t.minx) { this.minx = t.minx; - if (this.maxx < t.maxx) + } + if (this.maxx < t.maxx) { this.maxx = t.maxx; - } - // The child cell doesn't cross the dateline. This cell's minx and maxx have different meaning than the + } + } // The child cell doesn't cross the dateline. This cell's minx and maxx have different meaning than the // child cell. If the child cell is entirely contained within either the eastern or western hemisphere, // we adjust this cell's minx or maxx to include it. If the child cell spans the prime meridian, this // cell's minx and maxx must extent to the prime meridian to include it. - else - { + else { if (this.minx > t.minx && t.minx > 0f) // Cell is entirely within the eastern hemisphere. + { this.minx = t.minx; + } if (this.maxx < t.maxx && t.maxx < 0f) // Cell is entirely within the western hemisphere. + { this.maxx = t.maxx; + } if (t.minx <= 0f && t.maxx >= 0f) // Cell is in both the western and eastern hemispheres. + { this.minx = this.maxx = 0f; + } } - if (this.miny > t.miny) + if (this.miny > t.miny) { this.miny = t.miny; - if (this.maxy < t.maxy) + } + if (this.maxy < t.maxy) { this.maxy = t.maxy; + } } } @@ -209,32 +210,28 @@ protected void computeExtremesFromChildren() * Returns true if a line segment from the first pixel in this cell to any other pixel in this cell crosses the * international dateline, and false otherwise. * - * @param dim the image's dimensions. + * @param dim the image's dimensions. * @param longitudes the longitude coordinates of the image's pixels in degrees. Must contain at least - * dim.width * dim.height elements. + * dim.width * dim.height elements. * * @return true if this image cell's crosses the international dateline; false otherwise. */ - protected boolean longitudesCrossDateline(Dimension dim, float[] longitudes) - { + protected boolean longitudesCrossDateline(Dimension dim, float[] longitudes) { Float x1 = null; - for (int j = this.n0; j <= this.n1; j++) - { - for (int i = this.m0; i <= this.m1; i++) - { + for (int j = this.n0; j <= this.n1; j++) { + for (int i = this.m0; i <= this.m1; i++) { int k = j * dim.width + i; float x2 = longitudes[k]; - if (x1 != null) - { + if (x1 != null) { // A segment cross the line if end pos have different longitude signs // and are more than 180 degress longitude apart - if (Math.signum(x1) != Math.signum(x2)) - { + if (Math.signum(x1) != Math.signum(x2)) { float delta = Math.abs(x1 - x2); - if (delta > 180f && delta < 360f) + if (delta > 180f && delta < 360f) { return true; + } } } @@ -251,15 +248,15 @@ protected boolean longitudesCrossDateline(Dimension dim, float[] longitudes) * * @return true if any children cross the international dateline; false otherwise. */ - protected boolean childrenCrossDateline() - { - if (this.children == null || this.children.length == 0) + protected boolean childrenCrossDateline() { + if (this.children == null || this.children.length == 0) { return false; + } - for (Cell t : this.children) - { - if (((GeographicCell) t).isCrossesDateline()) + for (Cell t : this.children) { + if (((GeographicCell) t).isCrossesDateline()) { return true; + } } return false; @@ -271,20 +268,18 @@ protected boolean childrenCrossDateline() * cell dimensions of (gridSize.width * gridSize.height) and with the specified depth. * * @param gridSize the image's dimensions. - * @param xs the x-coordinates of the image's pixels. Must contain at least gridSize.width * + * @param xs the x-coordinates of the image's pixels. Must contain at least gridSize.width * * gridSize.height elements. - * @param ys the y-coordinates of the image's pixels. Must contain at least gridSize.width * + * @param ys the y-coordinates of the image's pixels. Must contain at least gridSize.width * * gridSize.height elements. - * @param depth the initial depth of this interpolator's image cell tree. + * @param depth the initial depth of this interpolator's image cell tree. * @param cellSize the size of a leaf cell in this interpolator's image cell tree, in pixels. * * @throws IllegalStateException if any of the the gridSize, x-coordinates, or y-coordinates are null, if either the - * x-coordinates or y-coordinates contain less than gridSize.width * - * gridSize.height elements, if the depth is less than zero, or if the cell - * size is less than one. + * x-coordinates or y-coordinates contain less than gridSize.width * + * gridSize.height elements, if the depth is less than zero, or if the cell size is less than one. */ - public GeographicImageInterpolator(Dimension gridSize, float[] xs, float[] ys, int depth, int cellSize) - { + public GeographicImageInterpolator(Dimension gridSize, float[] xs, float[] ys, int depth, int cellSize) { super(gridSize, xs, ys, depth, cellSize); } @@ -299,8 +294,7 @@ public GeographicImageInterpolator(Dimension gridSize, float[] xs, float[] ys, i * @return a new GeographicCell with the specified image coordinates. */ @Override - protected Cell makeRootCell(int m0, int m1, int n0, int n1) - { + protected Cell makeRootCell(int m0, int m1, int n0, int n1) { return new GeographicCell(m0, m1, n0, n1); } @@ -310,11 +304,10 @@ protected Cell makeRootCell(int m0, int m1, int n0, int n1) * * @return the image's bounding sector. */ - public Sector getSector() - { - return ((GeographicCell) this.root).isCrossesDateline() ? - Sector.fromDegrees(this.root.miny, this.root.maxy, -180, 180) : - Sector.fromDegrees(this.root.miny, this.root.maxy, this.root.minx, this.root.maxx); + public Sector getSector() { + return ((GeographicCell) this.root).isCrossesDateline() + ? Sector.fromDegrees(this.root.miny, this.root.maxy, -180, 180) + : Sector.fromDegrees(this.root.miny, this.root.maxy, this.root.minx, this.root.maxx); } /** @@ -322,19 +315,17 @@ public Sector getSector() * dateline. If the specified cell does not cross the dateline, this invokes the superclass' functionality. This * returns null if the specified (x, y) point does not intersect the cell. * - * @param x the x-component of the point to compute bilinear coordinate for. - * @param y the y-component of the point to compute bilinear coordinate for. + * @param x the x-component of the point to compute bilinear coordinate for. + * @param y the y-component of the point to compute bilinear coordinate for. * @param cell the cell to compute bilinear coordinates for. * * @return the bilinear coordinates of the specified (x, y) point in the specified cell, or null if the point does - * not intersect the cell. + * not intersect the cell. */ @Override - protected double[] computeBilinearCoordinates(float x, float y, Cell cell) - { + protected double[] computeBilinearCoordinates(float x, float y, Cell cell) { // Invoke the superclass functionality if the cell doesn't cross the international dateline. - if (!((GeographicCell) cell).isCrossesDateline()) - { + if (!((GeographicCell) cell).isCrossesDateline()) { return super.computeBilinearCoordinates(x, y, cell); } @@ -344,15 +335,15 @@ protected double[] computeBilinearCoordinates(float x, float y, Cell cell) // The cell crosses the international dateline. Adjust the cell's coordinates so the're in the same hemisphere // as the x-coordinate. This will result in longitude values outside of the range [-180, 180], but preserves // the size and shape relative to the (x, y) point. - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { double lon = this.xs[indices[i]]; double lat = this.ys[indices[i]]; - if (x < 0f && lon >= 0f) + if (x < 0f && lon >= 0f) { lon -= 360f; - else if (x >= 0f && lon < 0f) + } else if (x >= 0f && lon < 0f) { lon += 360f; + } points[i] = new Vec4(lon, lat); } @@ -361,10 +352,10 @@ else if (x >= 0f && lon < 0f) // adjusted coordinates contain nonstandard longitudes, but produce the correct result here because the // coordinates are interpreted as Cartesian. return BarycentricQuadrilateral.invertBilinear( - new Vec4(x, y), - points[0], - points[1], - points[2], - points[3]); + new Vec4(x, y), + points[0], + points[1], + points[2], + points[3]); } } diff --git a/src/gov/nasa/worldwind/util/GeometryBuilder.java b/src/gov/nasa/worldwind/util/GeometryBuilder.java index 7b55f0604a..88de1f5e20 100644 --- a/src/gov/nasa/worldwind/util/GeometryBuilder.java +++ b/src/gov/nasa/worldwind/util/GeometryBuilder.java @@ -19,8 +19,8 @@ * @author dcollins * @version $Id: GeometryBuilder.java 3434 2015-10-08 18:17:48Z tgaskins $ */ -public class GeometryBuilder -{ +public class GeometryBuilder { + public static final int OUTSIDE = 0; public static final int INSIDE = 1; @@ -62,34 +62,27 @@ public class GeometryBuilder private int orientation = OUTSIDE; - public GeometryBuilder() - { + public GeometryBuilder() { } - public int getOrientation() - { + public int getOrientation() { return this.orientation; } - public void setOrientation(int orientation) - { + public void setOrientation(int orientation) { this.orientation = orientation; } //**************************************************************// //******************** Sphere ********************************// //**************************************************************// - - public IndexedTriangleArray tessellateSphere(float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleArray tessellateSphere(float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -102,10 +95,8 @@ public IndexedTriangleArray tessellateSphere(float radius, int subdivisions) // The static icosahedron tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (int index = 0; index < ICOSAHEDRON_INDEX_COUNT; index += 3) - { + if (this.orientation == INSIDE) { + for (int index = 0; index < ICOSAHEDRON_INDEX_COUNT; index += 3) { int tmp = indexArray[index]; indexArray[index] = indexArray[index + 2]; indexArray[index + 2] = tmp; @@ -114,28 +105,24 @@ public IndexedTriangleArray tessellateSphere(float radius, int subdivisions) // Start with a triangular tessellated icosahedron. IndexedTriangleArray ita = new IndexedTriangleArray( - ICOSAHEDRON_INDEX_COUNT, indexArray, ICOSAHEDRON_VERTEX_COUNT, vertexArray); + ICOSAHEDRON_INDEX_COUNT, indexArray, ICOSAHEDRON_VERTEX_COUNT, vertexArray); // Subdivide the icosahedron a specified number of times. The subdivison step computes midpoints between // adjacent vertices. These midpoints are not on the sphere, but must be moved onto the sphere. We normalize // each midpoint vertex to acheive this. - for (int i = 0; i < subdivisions; i++) - { + for (int i = 0; i < subdivisions; i++) { this.subdivideIndexedTriangleArray(ita); vertexArray = ita.getVertices(); - for (int vertex = 0; vertex < ita.vertexCount; vertex++) - { + for (int vertex = 0; vertex < ita.vertexCount; vertex++) { norm3AndSet(vertexArray, 3 * vertex); } } // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexArray = ita.getVertices(); - for (int vertex = 0; vertex < ita.vertexCount; vertex++) - { + for (int vertex = 0; vertex < ita.vertexCount; vertex++) { mul3AndSet(vertexArray, 3 * vertex, radius); } } @@ -143,16 +130,13 @@ public IndexedTriangleArray tessellateSphere(float radius, int subdivisions) return ita; } - public IndexedTriangleBuffer tessellateSphereBuffer(float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateSphereBuffer(float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -165,10 +149,8 @@ public IndexedTriangleBuffer tessellateSphereBuffer(float radius, int subdivisio // The static icosahedron tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (int index = 0; index < ICOSAHEDRON_INDEX_COUNT; index += 3) - { + if (this.orientation == INSIDE) { + for (int index = 0; index < ICOSAHEDRON_INDEX_COUNT; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -177,28 +159,24 @@ public IndexedTriangleBuffer tessellateSphereBuffer(float radius, int subdivisio // Start with a triangular tessellated icosahedron. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - ICOSAHEDRON_INDEX_COUNT, indexBuffer, ICOSAHEDRON_VERTEX_COUNT, vertexBuffer); + ICOSAHEDRON_INDEX_COUNT, indexBuffer, ICOSAHEDRON_VERTEX_COUNT, vertexBuffer); // Subdivide the icosahedron a specified number of times. The subdivison step computes midpoints between // adjacent vertices. These midpoints are not on the sphere, but must be moved onto the sphere. We normalize // each midpoint vertex to achieve this. - for (int i = 0; i < subdivisions; i++) - { + for (int i = 0; i < subdivisions; i++) { this.subdivideIndexedTriangleBuffer(itb); vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.getVertexCount(); vertex++) - { + for (int vertex = 0; vertex < itb.getVertexCount(); vertex++) { norm3AndSet(vertexBuffer, 3 * vertex); } } // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -209,8 +187,7 @@ public IndexedTriangleBuffer tessellateSphereBuffer(float radius, int subdivisio return itb; } - public IndexedTriangleBuffer tessellateEllipsoidBuffer(float a, float b, float c, int subdivisions) - { + public IndexedTriangleBuffer tessellateEllipsoidBuffer(float a, float b, float c, int subdivisions) { IndexedTriangleBuffer itb = tessellateSphereBuffer(a, subdivisions); // normalize 2nd and 3rd radii in terms of the first one @@ -219,8 +196,7 @@ public IndexedTriangleBuffer tessellateEllipsoidBuffer(float a, float b, float c // scale Y and Z components of each vertex by appropriate scaling factor FloatBuffer vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.getVertexCount(); vertex++) - { + for (int vertex = 0; vertex < itb.getVertexCount(); vertex++) { // offset = 0 for x coord, 1 for y coord, etc. mulAndSet(vertexBuffer, 3 * vertex, bScale, 2); mulAndSet(vertexBuffer, 3 * vertex, cScale, 1); @@ -233,67 +209,62 @@ public IndexedTriangleBuffer tessellateEllipsoidBuffer(float a, float b, float c // Icosahedron tessellation taken from the // OpenGL Programming Guide, Chapter 2, Example 2-13: Drawing an Icosahedron. - private static final int ICOSAHEDRON_INDEX_COUNT = 60; private static final int ICOSAHEDRON_VERTEX_COUNT = 12; private static final float X = 0.525731112119133606f; private static final float Z = 0.850650808352039932f; - private static float[] icosahedronVertexArray = - { - -X, 0, Z, - X, 0, Z, - -X, 0, -Z, - X, 0, -Z, - 0, Z, X, - 0, Z, -X, - 0, -Z, X, - 0, -Z, -X, - Z, X, 0, - -Z, X, 0, - Z, -X, 0, - -Z, -X, 0 - }; - - private static int[] icosahedronIndexArray = - { - 1, 4, 0, - 4, 9, 0, - 4, 5, 9, - 8, 5, 4, - 1, 8, 4, - 1, 10, 8, - 10, 3, 8, - 8, 3, 5, - 3, 2, 5, - 3, 7, 2, - 3, 10, 7, - 10, 6, 7, - 6, 11, 7, - 6, 0, 11, - 6, 1, 0, - 10, 1, 6, - 11, 0, 9, - 2, 11, 9, - 5, 2, 9, - 11, 2, 7 - }; + private static float[] icosahedronVertexArray + = { + -X, 0, Z, + X, 0, Z, + -X, 0, -Z, + X, 0, -Z, + 0, Z, X, + 0, Z, -X, + 0, -Z, X, + 0, -Z, -X, + Z, X, 0, + -Z, X, 0, + Z, -X, 0, + -Z, -X, 0 + }; + + private static int[] icosahedronIndexArray + = { + 1, 4, 0, + 4, 9, 0, + 4, 5, 9, + 8, 5, 4, + 1, 8, 4, + 1, 10, 8, + 10, 3, 8, + 8, 3, 5, + 3, 2, 5, + 3, 7, 2, + 3, 10, 7, + 10, 6, 7, + 6, 11, 7, + 6, 0, 11, + 6, 1, 0, + 10, 1, 6, + 11, 0, 9, + 2, 11, 9, + 5, 2, 9, + 11, 2, 7 + }; //**************************************************************// //*********************** Box ********************************// //**************************************************************// - // create the entire box - public IndexedTriangleBuffer tessellateBoxBuffer(float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateBoxBuffer(float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -306,10 +277,8 @@ public IndexedTriangleBuffer tessellateBoxBuffer(float radius, int subdivisions) // The static box tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (int index = 0; index < BOX_INDEX_COUNT; index += 3) - { + if (this.orientation == INSIDE) { + for (int index = 0; index < BOX_INDEX_COUNT; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -318,14 +287,12 @@ public IndexedTriangleBuffer tessellateBoxBuffer(float radius, int subdivisions) // Start with a tessellated box. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - BOX_INDEX_COUNT, indexBuffer, BOX_VERTEX_COUNT, vertexBuffer); + BOX_INDEX_COUNT, indexBuffer, BOX_VERTEX_COUNT, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -337,22 +304,18 @@ public IndexedTriangleBuffer tessellateBoxBuffer(float radius, int subdivisions) } // create only one face of the box - public IndexedTriangleBuffer tessellateBoxBuffer(int face, float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateBoxBuffer(int face, float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (face < 0 || face >= 6) - { + if (face < 0 || face >= 6) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "face < 0 or face >= 6"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -363,25 +326,21 @@ public IndexedTriangleBuffer tessellateBoxBuffer(int face, float radius, int sub // fill subset of index buffer int[] subArray = new int[BOX_INDEX_COUNT / 6]; - for (int i = 0; i < BOX_INDEX_COUNT / 6; i++) - { + for (int i = 0; i < BOX_INDEX_COUNT / 6; i++) { subArray[i] = boxFacesIndexArray[face * BOX_INDEX_COUNT / 6 + i]; } indexBuffer.put(subArray, 0, BOX_INDEX_COUNT / 6); float[] vertexSubset = new float[3 * BOX_VERTEX_COUNT / 6]; - for (int i = 0; i < 3 * BOX_VERTEX_COUNT / 6; i++) - { + for (int i = 0; i < 3 * BOX_VERTEX_COUNT / 6; i++) { vertexSubset[i] = boxVertexArray[face * 3 * BOX_VERTEX_COUNT / 6 + i]; } vertexBuffer.put(vertexSubset, 0, 3 * BOX_VERTEX_COUNT / 6); // The static box tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (int index = 0; index < BOX_INDEX_COUNT / 6; index += 3) - { + if (this.orientation == INSIDE) { + for (int index = 0; index < BOX_INDEX_COUNT / 6; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -390,14 +349,12 @@ public IndexedTriangleBuffer tessellateBoxBuffer(int face, float radius, int sub // Start with a tessellated box. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - BOX_INDEX_COUNT / 6, indexBuffer, BOX_VERTEX_COUNT / 6, vertexBuffer); + BOX_INDEX_COUNT / 6, indexBuffer, BOX_VERTEX_COUNT / 6, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -412,90 +369,84 @@ public IndexedTriangleBuffer tessellateBoxBuffer(int face, float radius, int sub private static final int BOX_VERTEX_COUNT = 24; private static final float B = 1.0f; - private static float[] boxVertexArray = - { // right - B, -B, B, // 0 - B, B, B, // 1 - B, -B, -B, // 2 - B, B, -B, // 3 - - // front - -B, B, B, // 4 - B, B, B, // 5 - -B, -B, B, // 6 - B, -B, B, // 7 - - // left - -B, B, B, // 8 - -B, -B, B, // 9 - -B, B, -B, // 10 - -B, -B, -B, // 11 - - // back - B, B, -B, // 12 - -B, B, -B, // 13 - B, -B, -B, // 14 - -B, -B, -B, // 15 - - // top - B, B, B, // 16 - -B, B, B, // 17 - B, B, -B, // 18 - -B, B, -B, // 19 - - // bottom - -B, -B, B, // 20 - B, -B, B, // 21 - -B, -B, -B, // 22 - B, -B, -B // 23 - }; - - private static int[] boxIndexArray = - { - 2, 3, 1, // right - 2, 1, 0, - 4, 6, 7, // front - 4, 7, 5, - 8, 10, 11, // left - 8, 11, 9, - 12, 14, 15, // back - 12, 15, 13, - 16, 18, 19, // top - 16, 19, 17, - 20, 22, 23, // bottom - 20, 23, 21, - }; - - private static int[] boxFacesIndexArray = - { - 2, 3, 1, // right - 2, 1, 0, - 0, 2, 3, // front - 0, 3, 1, - 0, 2, 3, // left - 0, 3, 1, - 0, 2, 3, // back - 0, 3, 1, - 0, 2, 3, // top - 0, 3, 1, - 0, 2, 3, // bottom - 0, 3, 1, - }; + private static float[] boxVertexArray + = { // right + B, -B, B, // 0 + B, B, B, // 1 + B, -B, -B, // 2 + B, B, -B, // 3 + + // front + -B, B, B, // 4 + B, B, B, // 5 + -B, -B, B, // 6 + B, -B, B, // 7 + + // left + -B, B, B, // 8 + -B, -B, B, // 9 + -B, B, -B, // 10 + -B, -B, -B, // 11 + + // back + B, B, -B, // 12 + -B, B, -B, // 13 + B, -B, -B, // 14 + -B, -B, -B, // 15 + + // top + B, B, B, // 16 + -B, B, B, // 17 + B, B, -B, // 18 + -B, B, -B, // 19 + + // bottom + -B, -B, B, // 20 + B, -B, B, // 21 + -B, -B, -B, // 22 + B, -B, -B // 23 + }; + + private static int[] boxIndexArray + = { + 2, 3, 1, // right + 2, 1, 0, + 4, 6, 7, // front + 4, 7, 5, + 8, 10, 11, // left + 8, 11, 9, + 12, 14, 15, // back + 12, 15, 13, + 16, 18, 19, // top + 16, 19, 17, + 20, 22, 23, // bottom + 20, 23, 21,}; + + private static int[] boxFacesIndexArray + = { + 2, 3, 1, // right + 2, 1, 0, + 0, 2, 3, // front + 0, 3, 1, + 0, 2, 3, // left + 0, 3, 1, + 0, 2, 3, // back + 0, 3, 1, + 0, 2, 3, // top + 0, 3, 1, + 0, 2, 3, // bottom + 0, 3, 1,}; //**************************************************************// //*********************** Pyramid ****************************// //**************************************************************// - - public IndexedTriangleBuffer tessellatePyramidBuffer(float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellatePyramidBuffer(float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -508,10 +459,8 @@ public IndexedTriangleBuffer tessellatePyramidBuffer(float radius, int subdivisi // The static box tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (int index = 0; index < PYRAMID_INDEX_COUNT; index += 3) - { + if (this.orientation == INSIDE) { + for (int index = 0; index < PYRAMID_INDEX_COUNT; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -520,14 +469,12 @@ public IndexedTriangleBuffer tessellatePyramidBuffer(float radius, int subdivisi // Start with a tessellated pyramid. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - PYRAMID_INDEX_COUNT, indexBuffer, PYRAMID_VERTEX_COUNT, vertexBuffer); + PYRAMID_INDEX_COUNT, indexBuffer, PYRAMID_VERTEX_COUNT, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -538,16 +485,13 @@ public IndexedTriangleBuffer tessellatePyramidBuffer(float radius, int subdivisi return itb; } - public IndexedTriangleBuffer tessellatePyramidBuffer(int face, float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellatePyramidBuffer(int face, float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -559,7 +503,7 @@ public IndexedTriangleBuffer tessellatePyramidBuffer(int face, float radius, int int faceIndicesOffset = face * faceIndexCount; int faceVerticesOffset = face * 3 * faceVertexCount; - if (face == 4) // the pyramid base + if (face == 4) // the pyramid base { faceIndicesOffset = 4 * faceIndexCount; faceVerticesOffset = 4 * 3 * faceVertexCount; @@ -572,25 +516,21 @@ public IndexedTriangleBuffer tessellatePyramidBuffer(int face, float radius, int // fill subset of index buffer int[] subArray = new int[faceIndexCount]; - for (int i = 0; i < faceIndexCount; i++) - { + for (int i = 0; i < faceIndexCount; i++) { subArray[i] = pyramidFacesIndexArray[faceIndicesOffset + i]; } indexBuffer.put(subArray, 0, faceIndexCount); float[] vertexSubset = new float[3 * faceVertexCount]; - for (int i = 0; i < 3 * faceVertexCount; i++) - { + for (int i = 0; i < 3 * faceVertexCount; i++) { vertexSubset[i] = pyramidVertexArray[faceVerticesOffset + i]; } vertexBuffer.put(vertexSubset, 0, 3 * faceVertexCount); // The static box tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (int index = 0; index < faceIndexCount; index += 3) - { + if (this.orientation == INSIDE) { + for (int index = 0; index < faceIndexCount; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -599,14 +539,12 @@ public IndexedTriangleBuffer tessellatePyramidBuffer(int face, float radius, int // Start with a tessellated pyramid. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - faceIndexCount, indexBuffer, faceVertexCount, vertexBuffer); + faceIndexCount, indexBuffer, faceVertexCount, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -621,68 +559,62 @@ public IndexedTriangleBuffer tessellatePyramidBuffer(int face, float radius, int private static final int PYRAMID_VERTEX_COUNT = 16; private static final float P = 1.0f; - private static float[] pyramidVertexArray = - { // right - 0, 0, P, // 0 (point) - P, -P, -P, // 1 - P, P, -P, // 2 - - // front - 0, 0, P, // 3 (point) - -P, -P, -P, // 4 - P, -P, -P, // 5 - - // left - 0, 0, P, // 6 (point) - -P, P, -P, // 7 - -P, -P, -P, // 8 - - // back - 0, 0, P, // 9 (point) - P, P, -P, // 10 - -P, P, -P, // 11 - - // bottom (base) face - P, P, -P, // 12 - -P, P, -P, // 13 - P, -P, -P, // 14 - -P, -P, -P // 15 - }; - - private static int[] pyramidIndexArray = - { - 0, 1, 2, // right - 3, 4, 5, // front - 6, 7, 8, // left - 9, 10, 11, // back - 12, 14, 15, // base - 12, 15, 13, - }; - - private static int[] pyramidFacesIndexArray = - { - 0, 1, 2, // right - 0, 1, 2, // front - 0, 1, 2, // left - 0, 1, 2, // back - 0, 2, 3, // base - 0, 3, 1, - }; + private static float[] pyramidVertexArray + = { // right + 0, 0, P, // 0 (point) + P, -P, -P, // 1 + P, P, -P, // 2 + + // front + 0, 0, P, // 3 (point) + -P, -P, -P, // 4 + P, -P, -P, // 5 + + // left + 0, 0, P, // 6 (point) + -P, P, -P, // 7 + -P, -P, -P, // 8 + + // back + 0, 0, P, // 9 (point) + P, P, -P, // 10 + -P, P, -P, // 11 + + // bottom (base) face + P, P, -P, // 12 + -P, P, -P, // 13 + P, -P, -P, // 14 + -P, -P, -P // 15 + }; + + private static int[] pyramidIndexArray + = { + 0, 1, 2, // right + 3, 4, 5, // front + 6, 7, 8, // left + 9, 10, 11, // back + 12, 14, 15, // base + 12, 15, 13,}; + + private static int[] pyramidFacesIndexArray + = { + 0, 1, 2, // right + 0, 1, 2, // front + 0, 1, 2, // left + 0, 1, 2, // back + 0, 2, 3, // base + 0, 3, 1,}; //**************************************************************// //******************** Unit Cylinder *******************// //**************************************************************// - - public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -701,7 +633,6 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivis FloatBuffer vertexBuffer = Buffers.newDirectFloatBuffer(3 * cylinderVertexCount); // VERTICES - // top and bottom center points vertexBuffer.put(0, 0f); vertexBuffer.put(1, 0f); @@ -712,8 +643,7 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivis vertexBuffer.put(3 * (slices + 1) + 2, -1.0f); // rim points - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -747,7 +677,6 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivis } // extra vertices for seamless texture mapping - int wrapIndex = 3 * (4 * slices + 2); x = (float) Math.sin(0); y = (float) Math.cos(0); @@ -762,12 +691,10 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivis vertexBuffer.put(wrapIndex + 5, -z); // INDICES - int coreIndex = (2 * slices) + 2; int centerPoint = 0; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { // cylinder top index = 3 * i; @@ -798,10 +725,8 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivis // The static cylinder tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (index = 0; index < cylinderIndexCount; index += 3) - { + if (this.orientation == INSIDE) { + for (index = 0; index < cylinderIndexCount; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -810,14 +735,12 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivis // Start with a triangular tessellated cylinder. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - cylinderIndexCount, indexBuffer, cylinderVertexCount, vertexBuffer); + cylinderIndexCount, indexBuffer, cylinderVertexCount, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -828,16 +751,13 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(float radius, int subdivis return itb; } - public IndexedTriangleBuffer tessellateCylinderBuffer(int face, float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateCylinderBuffer(int face, float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -849,14 +769,13 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(int face, float radius, in // face 0 = top // face 1 = bottom // face 2 = round cylinder core - int slices = (int) Math.pow(2, 2 + subdivisions); float da = 2.0f * (float) Math.PI / (float) slices; int cylinderIndexCount = 3 * slices; int cylinderVertexCount = slices + 1; - if (face == 2) // cylinder core + if (face == 2) // cylinder core { cylinderIndexCount = 6 * slices; cylinderVertexCount = 2 * slices + 2; @@ -866,12 +785,12 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(int face, float radius, in FloatBuffer vertexBuffer = Buffers.newDirectFloatBuffer(3 * cylinderVertexCount); // VERTICES - - if (face == 0 || face == 1) // top or bottom cylinder face + if (face == 0 || face == 1) // top or bottom cylinder face { int isTop = 1; - if (face == 1) + if (face == 1) { isTop = -1; + } // top center point vertexBuffer.put(0, 0f); @@ -879,8 +798,7 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(int face, float radius, in vertexBuffer.put(2, isTop * 1.0f); // rim points - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -893,12 +811,10 @@ public IndexedTriangleBuffer tessellateCylinderBuffer(int face, float radius, in vertexBuffer.put(index + 1, y * radius); vertexBuffer.put(index + 2, isTop * z); } - } - else if (face == 2) // cylinder core + } else if (face == 2) // cylinder core { // rim points - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -918,7 +834,6 @@ else if (face == 2) // cylinder core } // extra vertices for seamless texture mapping - int wrapIndex = 3 * (2 * slices); x = (float) Math.sin(0); y = (float) Math.cos(0); @@ -934,26 +849,22 @@ else if (face == 2) // cylinder core } // INDICES - int centerPoint = 0; - if (face == 0 || face == 1) // top or bottom cylinder face + if (face == 0 || face == 1) // top or bottom cylinder face { - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { index = 3 * i; indexBuffer.put(index, 0); // center point indexBuffer.put(index + 1, (i < slices - 1) ? i + 2 : 1); indexBuffer.put(index + 2, i + 1); } - } - else if (face == 2) // cylinder core + } else if (face == 2) // cylinder core { int coreIndex = 0; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { index = 6 * i; indexBuffer.put(index, coreIndex); @@ -970,10 +881,8 @@ else if (face == 2) // cylinder core // The static cylinder tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (index = 0; index < cylinderIndexCount; index += 3) - { + if (this.orientation == INSIDE) { + for (index = 0; index < cylinderIndexCount; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -982,14 +891,12 @@ else if (face == 2) // cylinder core // Start with a triangular tessellated cylinder. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - cylinderIndexCount, indexBuffer, cylinderVertexCount, vertexBuffer); + cylinderIndexCount, indexBuffer, cylinderVertexCount, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -1003,23 +910,18 @@ else if (face == 2) // cylinder core //**************************************************************// //******************** Wedge *******************// //**************************************************************// - - public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivisions, Angle angle) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivisions, Angle angle) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) - { + if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "angle < 0 or angle > 2 PI"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1038,7 +940,6 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivision FloatBuffer vertexBuffer = Buffers.newDirectFloatBuffer(3 * wedgeVertexCount); // VERTICES - // top and bottom center points vertexBuffer.put(0, 0f); vertexBuffer.put(1, 0f); @@ -1049,8 +950,7 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivision vertexBuffer.put(3 * (slices + 2) + 2, -1.0f); // rim points - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -1084,8 +984,7 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivision } // wedge sides - for (i = 0; i < 2; i++) - { + for (i = 0; i < 2; i++) { x = (float) Math.sin(i * angle.getRadians()); y = (float) Math.cos(i * angle.getRadians()); z = 1.0f; @@ -1112,11 +1011,9 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivision } // INDICES - int coreIndex = 2 * (slices + 1) + 2; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { // wedge top index = 3 * i; @@ -1146,8 +1043,7 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivision } // wedge sides - for (i = 0; i < 2; i++) - { + for (i = 0; i < 2; i++) { index = 3 * (4 * slices) + 6 * i; coreIndex = 4 * (slices + 1) + 2 + i * 4; @@ -1162,10 +1058,8 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivision // The static wedge tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (index = 0; index < wedgeIndexCount; index += 3) - { + if (this.orientation == INSIDE) { + for (index = 0; index < wedgeIndexCount; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -1174,14 +1068,12 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivision // Start with a triangular tessellated wedge. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - wedgeIndexCount, indexBuffer, wedgeVertexCount, vertexBuffer); + wedgeIndexCount, indexBuffer, wedgeVertexCount, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -1192,22 +1084,18 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(float radius, int subdivision return itb; } - public IndexedTriangleBuffer tessellateWedgeBuffer(int face, float radius, int subdivisions, Angle angle) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateWedgeBuffer(int face, float radius, int subdivisions, Angle angle) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) - { + if (angle.getRadians() < 0 || angle.getRadians() > 2 * Math.PI) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "angle < 0 or angle > 2 PI"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1221,20 +1109,16 @@ public IndexedTriangleBuffer tessellateWedgeBuffer(int face, float radius, int s // face 2 = round core wall // face 3 = first wedge side // face 4 = second wedge side - int slices = (int) Math.pow(2, 2 + subdivisions); float da = (float) angle.getRadians() / slices; int wedgeIndexCount = 6; int wedgeVertexCount = 4; - if (face == 0 || face == 1) - { + if (face == 0 || face == 1) { wedgeIndexCount = 3 * slices; wedgeVertexCount = slices + 2; - } - else if (face == 2) - { + } else if (face == 2) { wedgeIndexCount = 6 * slices; wedgeVertexCount = 2 * slices + 2; } @@ -1243,13 +1127,13 @@ else if (face == 2) FloatBuffer vertexBuffer = Buffers.newDirectFloatBuffer(3 * wedgeVertexCount); // VERTICES - - if (face == 0 || face == 1) // wedge top or bottom + if (face == 0 || face == 1) // wedge top or bottom { int isTop = 1; - if (face == 1) + if (face == 1) { isTop = -1; + } // center point vertexBuffer.put(0, 0f); @@ -1257,8 +1141,7 @@ else if (face == 2) vertexBuffer.put(2, isTop * 1.0f); // rim points - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -1271,12 +1154,10 @@ else if (face == 2) vertexBuffer.put(index + 1, y * radius); vertexBuffer.put(index + 2, isTop * z); } - } - else if (face == 2) // round core wall + } else if (face == 2) // round core wall { // rim points - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -1294,9 +1175,7 @@ else if (face == 2) // round core wall vertexBuffer.put(index + 4, y * radius); vertexBuffer.put(index + 5, -z); } - } - else if (face == 3 || face == 4) - { + } else if (face == 3 || face == 4) { // wedge side i = face - 3; @@ -1326,11 +1205,9 @@ else if (face == 3 || face == 4) } // INDICES - - if (face == 0 || face == 1) // top or bottom + if (face == 0 || face == 1) // top or bottom { - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { // wedge top index = 3 * i; @@ -1338,13 +1215,10 @@ else if (face == 3 || face == 4) indexBuffer.put(index + 1, i + 2); indexBuffer.put(index + 2, i + 1); } - } - else if (face == 2) - { + } else if (face == 2) { int coreIndex = 0; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { // wedge core index = 6 * i; @@ -1358,9 +1232,7 @@ else if (face == 2) coreIndex += 2; } - } - else if (face == 3 || face == 4) - { + } else if (face == 3 || face == 4) { // wedge side indexBuffer.put(0, 0); indexBuffer.put(1, 2); @@ -1373,10 +1245,8 @@ else if (face == 3 || face == 4) // The static wedge tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (index = 0; index < wedgeIndexCount; index += 3) - { + if (this.orientation == INSIDE) { + for (index = 0; index < wedgeIndexCount; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -1385,14 +1255,12 @@ else if (face == 3 || face == 4) // Start with a triangular tessellated wedge. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - wedgeIndexCount, indexBuffer, wedgeVertexCount, vertexBuffer); + wedgeIndexCount, indexBuffer, wedgeVertexCount, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -1406,17 +1274,13 @@ else if (face == 3 || face == 4) //**************************************************************// //********************* Cone *******************// //**************************************************************// - - public IndexedTriangleBuffer tessellateConeBuffer(float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateConeBuffer(float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1435,15 +1299,13 @@ public IndexedTriangleBuffer tessellateConeBuffer(float radius, int subdivisions FloatBuffer vertexBuffer = Buffers.newDirectFloatBuffer(3 * coneVertexCount); // VERTICES - // bottom center point vertexBuffer.put(0, 0f); vertexBuffer.put(1, 0f); vertexBuffer.put(2, -1.0f); // rim points - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -1470,7 +1332,6 @@ public IndexedTriangleBuffer tessellateConeBuffer(float radius, int subdivisions } // extra vertices for seamless texture mapping - int wrapIndex = 3 * (3 * slices + 1); x = (float) Math.sin(0); y = (float) Math.cos(0); @@ -1485,12 +1346,10 @@ public IndexedTriangleBuffer tessellateConeBuffer(float radius, int subdivisions vertexBuffer.put(wrapIndex + 5, -z); // INDICES - int coreIndex = slices + 1; int centerPoint = 0; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { index = 3 * i; // cone bottom @@ -1514,10 +1373,8 @@ public IndexedTriangleBuffer tessellateConeBuffer(float radius, int subdivisions // The static cone tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (index = 0; index < coneIndexCount; index += 3) - { + if (this.orientation == INSIDE) { + for (index = 0; index < coneIndexCount; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -1526,14 +1383,12 @@ public IndexedTriangleBuffer tessellateConeBuffer(float radius, int subdivisions // Start with a triangular tessellated cone. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - coneIndexCount, indexBuffer, coneVertexCount, vertexBuffer); + coneIndexCount, indexBuffer, coneVertexCount, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -1544,16 +1399,13 @@ public IndexedTriangleBuffer tessellateConeBuffer(float radius, int subdivisions return itb; } - public IndexedTriangleBuffer tessellateConeBuffer(int face, float radius, int subdivisions) - { - if (radius < 0) - { + public IndexedTriangleBuffer tessellateConeBuffer(int face, float radius, int subdivisions) { + if (radius < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "radius < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1561,7 +1413,6 @@ public IndexedTriangleBuffer tessellateConeBuffer(int face, float radius, int su // face 0 = base // face 1 = core - int i, index; float x, y, z, a; @@ -1571,7 +1422,7 @@ public IndexedTriangleBuffer tessellateConeBuffer(int face, float radius, int su int coneIndexCount = 3 * slices; int coneVertexCount = slices + 1; - if (face == 1) // cone core + if (face == 1) // cone core { coneIndexCount = 6 * slices; coneVertexCount = 2 * slices + 2; @@ -1581,8 +1432,7 @@ public IndexedTriangleBuffer tessellateConeBuffer(int face, float radius, int su FloatBuffer vertexBuffer = Buffers.newDirectFloatBuffer(3 * coneVertexCount); // VERTICES - - if (face == 0) // cone base + if (face == 0) // cone base { // base center point vertexBuffer.put(0, 0f); @@ -1590,8 +1440,7 @@ public IndexedTriangleBuffer tessellateConeBuffer(int face, float radius, int su vertexBuffer.put(2, -1.0f); // base rim points - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -1603,12 +1452,10 @@ public IndexedTriangleBuffer tessellateConeBuffer(int face, float radius, int su vertexBuffer.put(index + 1, y * radius); vertexBuffer.put(index + 2, -z); } - } - else if (face == 1) // cone core + } else if (face == 1) // cone core { // rim points - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -1628,7 +1475,6 @@ else if (face == 1) // cone core } // extra vertices for seamless texture mapping - int wrapIndex = 3 * (2 * slices); x = (float) Math.sin(0); y = (float) Math.cos(0); @@ -1644,26 +1490,22 @@ else if (face == 1) // cone core } // INDICES - int centerPoint = 0; - if (face == 0) // cone base + if (face == 0) // cone base { - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { index = 3 * i; indexBuffer.put(index, 0); // center point indexBuffer.put(index + 1, (i < slices - 1) ? i + 2 : 1); indexBuffer.put(index + 2, i + 1); } - } - else if (face == 1) // cone core + } else if (face == 1) // cone core { int coreIndex = 0; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { index = 6 * i; indexBuffer.put(index, coreIndex); @@ -1680,10 +1522,8 @@ else if (face == 1) // cone core // The static cone tessellation is assumed to be viewed from the outside. If the orientation is set to // inside, then we must reverse the winding order for each triangle's indices. - if (this.orientation == INSIDE) - { - for (index = 0; index < coneIndexCount; index += 3) - { + if (this.orientation == INSIDE) { + for (index = 0; index < coneIndexCount; index += 3) { int tmp = indexBuffer.get(index); indexBuffer.put(index, indexBuffer.get(index + 2)); indexBuffer.put(index + 2, tmp); @@ -1692,14 +1532,12 @@ else if (face == 1) // cone core // Start with a triangular tessellated cone. IndexedTriangleBuffer itb = new IndexedTriangleBuffer( - coneIndexCount, indexBuffer, coneVertexCount, vertexBuffer); + coneIndexCount, indexBuffer, coneVertexCount, vertexBuffer); // Scale each vertex by the specified radius. - if (radius != 1) - { + if (radius != 1) { vertexBuffer = itb.getVertices(); - for (int vertex = 0; vertex < itb.vertexCount; vertex++) - { + for (int vertex = 0; vertex < itb.vertexCount; vertex++) { mul3AndSet(vertexBuffer, 3 * vertex, radius); } } @@ -1713,49 +1551,39 @@ else if (face == 1) // cone core //**************************************************************// //******************** Cylinder *******************// //**************************************************************// - - public int getCylinderVertexCount(int slices, int stacks) - { + public int getCylinderVertexCount(int slices, int stacks) { return slices * (stacks + 1); } - public int getCylinderIndexCount(int slices, int stacks) - { + public int getCylinderIndexCount(int slices, int stacks) { return stacks * 2 * (slices + 1) + 2 * (stacks - 1); } @SuppressWarnings({"UnusedDeclaration"}) - public int getCylinderOutlineIndexCount(int slices, int stacks) - { + public int getCylinderOutlineIndexCount(int slices, int stacks) { return slices * 4; } - public int getCylinderDrawMode() - { + public int getCylinderDrawMode() { return GL.GL_TRIANGLE_STRIP; } - public int getCylinderOutlineDrawMode() - { + public int getCylinderOutlineDrawMode() { return GL.GL_LINES; } - public LatLon[] makeCylinderLocations(Globe globe, LatLon center, double radius, int slices) - { - if (globe == null) - { + public LatLon[] makeCylinderLocations(Globe globe, LatLon center, double radius, int slices) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (slices < 1) - { + if (slices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1765,8 +1593,7 @@ public LatLon[] makeCylinderLocations(Globe globe, LatLon center, double radius, double r = radius / globe.getRadius(); LatLon[] dest = new LatLon[slices]; - for (int i = 0; i < slices; i++) - { + for (int i = 0; i < slices; i++) { double a = i * da; dest[i] = LatLon.greatCircleEndPosition(center, a, r); } @@ -1775,22 +1602,18 @@ public LatLon[] makeCylinderLocations(Globe globe, LatLon center, double radius, } public LatLon[] makeCylinderLocations(Globe globe, LatLon center, double minorRadius, double majorRadius, - Angle heading, int slices) - { - if (globe == null) - { + Angle heading, int slices) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (slices < 1) - { + if (slices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1799,8 +1622,7 @@ public LatLon[] makeCylinderLocations(Globe globe, LatLon center, double minorRa double da = 2.0 * Math.PI / slices; LatLon[] dest = new LatLon[slices]; - for (int i = 0; i < slices; i++) - { + for (int i = 0; i < slices; i++) { double a = i * da; double cosA = Math.cos(a); double sinA = Math.sin(a); @@ -1814,43 +1636,36 @@ public LatLon[] makeCylinderLocations(Globe globe, LatLon center, double minorRa } public void makeCylinderVertices(Terrain terrain, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, Vec4 refPoint, float[] dest) - { + boolean[] terrainConformant, int slices, int stacks, Vec4 refPoint, float[] dest) { int numPoints = this.getCylinderVertexCount(slices, stacks); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1860,57 +1675,48 @@ public void makeCylinderVertices(Terrain terrain, LatLon center, double radius, double r = radius / terrain.getGlobe().getRadius(); FloatBuffer destBuffer = FloatBuffer.wrap(dest); - for (int i = 0; i < slices; i++) - { + for (int i = 0; i < slices; i++) { double a = i * da; LatLon ll = LatLon.greatCircleEndPosition(center, a, r); - for (int j = 0; j <= stacks; j++) - { + for (int j = 0; j <= stacks; j++) { this.append(terrain, ll, altitudes[j], terrainConformant[j], refPoint, destBuffer); } } } public void makeCylinderVertices(Terrain terrain, LatLon center, double minorRadius, double majorRadius, - Angle heading, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, Vec4 refPoint, float[] dest) - { + Angle heading, double[] altitudes, + boolean[] terrainConformant, int slices, int stacks, Vec4 refPoint, float[] dest) { int numPoints = this.getCylinderVertexCount(slices, stacks); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1920,8 +1726,7 @@ public void makeCylinderVertices(Terrain terrain, LatLon center, double minorRad double globeRadius = terrain.getGlobe().getRadius(); FloatBuffer destBuffer = FloatBuffer.wrap(dest); - for (int i = 0; i < slices; i++) - { + for (int i = 0; i < slices; i++) { double angle = (i != slices - 1) ? i * da : 0; double yLength = majorRadius * Math.cos(angle); double xLength = minorRadius * Math.sin(angle); @@ -1931,32 +1736,27 @@ public void makeCylinderVertices(Terrain terrain, LatLon center, double minorRad LatLon ll = LatLon.greatCircleEndPosition(center, azimuth, distance / globeRadius); - for (int j = 0; j <= stacks; j++) - { + for (int j = 0; j <= stacks; j++) { this.append(terrain, ll, altitudes[j], terrainConformant[j], refPoint, destBuffer); } } } - public void makeCylinderVertices(float radius, float height, int slices, int stacks, float[] dest) - { + public void makeCylinderVertices(float radius, float height, int slices, int stacks, float[] dest) { int numPoints = this.getCylinderVertexCount(slices, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1968,20 +1768,19 @@ public void makeCylinderVertices(float radius, float height, int slices, int sta int i, j; int index; - if (stacks != 0.0f) + if (stacks != 0.0f) { dz = height / (float) stacks; - else + } else { dz = 0.0f; + } da = 2.0f * (float) Math.PI / (float) slices; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); z = 0.0f; - for (j = 0; j <= stacks; j++) - { + for (j = 0; j <= stacks; j++) { index = j + i * (stacks + 1); index = 3 * index; dest[index] = x * radius; @@ -1992,25 +1791,21 @@ public void makeCylinderVertices(float radius, float height, int slices, int sta } } - public void makeCylinderNormals(int slices, int stacks, float[] dest) - { + public void makeCylinderNormals(int slices, int stacks, float[] dest) { int numPoints = this.getCylinderVertexCount(slices, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2028,8 +1823,7 @@ public void makeCylinderNormals(int slices, int stacks, float[] dest) nsign = (this.orientation == OUTSIDE) ? 1.0f : -1.0f; norm = new float[3]; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -2038,8 +1832,7 @@ public void makeCylinderNormals(int slices, int stacks, float[] dest) norm[2] = 0.0f; this.norm3AndSet(norm, 0); - for (j = 0; j <= stacks; j++) - { + for (j = 0; j <= stacks; j++) { index = j + i * (stacks + 1); index = 3 * index; System.arraycopy(norm, 0, dest, index, 3); @@ -2048,25 +1841,21 @@ public void makeCylinderNormals(int slices, int stacks, float[] dest) } public void makeEllipticalCylinderNormals(int slices, int stacks, double minorRadius, double majorRadius, - Angle heading, float[] dest) - { + Angle heading, float[] dest) { int numPoints = this.getCylinderVertexCount(slices, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2087,8 +1876,7 @@ public void makeEllipticalCylinderNormals(int slices, int stacks, double minorRa nsign = (this.orientation == OUTSIDE) ? 1.0f : -1.0f; norm = new float[3]; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da + heading.radians; x = majorRadius * Math.sin(a) / a2; y = minorRadius * Math.cos(a) / b2; @@ -2098,8 +1886,7 @@ public void makeEllipticalCylinderNormals(int slices, int stacks, double minorRa norm[2] = 0.0f; this.norm3AndSet(norm, 0); - for (j = 0; j <= stacks; j++) - { + for (j = 0; j <= stacks; j++) { index = j + i * (stacks + 1); index = 3 * index; System.arraycopy(norm, 0, dest, index, 3); @@ -2107,24 +1894,20 @@ public void makeEllipticalCylinderNormals(int slices, int stacks, double minorRa } } - public void makeCylinderIndices(int slices, int stacks, int[] dest) - { + public void makeCylinderIndices(int slices, int stacks, int[] dest) { int numIndices = this.getCylinderIndexCount(slices, stacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2134,29 +1917,27 @@ public void makeCylinderIndices(int slices, int stacks, int[] dest) int vertex, index; index = 0; - for (j = 0; j < stacks; j++) - { - if (j != 0) - { - if (this.orientation == INSIDE) + for (j = 0; j < stacks; j++) { + if (j != 0) { + if (this.orientation == INSIDE) { vertex = j + 1; - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) + { vertex = j; + } dest[index++] = vertex; dest[index++] = vertex; } - for (i = 0; i <= slices; i++) - { - if (i == slices) + for (i = 0; i <= slices; i++) { + if (i == slices) { vertex = j; - else + } else { vertex = j + i * (stacks + 1); - if (this.orientation == INSIDE) - { + } + if (this.orientation == INSIDE) { dest[index++] = vertex + 1; dest[index++] = vertex; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { dest[index++] = vertex; dest[index++] = vertex + 1; @@ -2165,24 +1946,20 @@ public void makeCylinderIndices(int slices, int stacks, int[] dest) } } - public void makeCylinderOutlineIndices(int slices, int stacks, int[] dest) - { + public void makeCylinderOutlineIndices(int slices, int stacks, int[] dest) { int numIndices = this.getCylinderOutlineIndexCount(slices, stacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2193,15 +1970,13 @@ public void makeCylinderOutlineIndices(int slices, int stacks, int[] dest) index = 0; // Bottom ring - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { vertex = i * (stacks + 1); dest[index++] = vertex; dest[index++] = (i != slices - 1) ? vertex + stacks + 1 : 0; } // Top ring - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { vertex = i * (stacks + 1) + stacks; dest[index++] = vertex; dest[index++] = (i != slices - 1) ? vertex + stacks + 1 : stacks; @@ -2218,50 +1993,40 @@ public void makeCylinderOutlineIndices(int slices, int stacks, int[] dest) //**************************************************************// //******************** Partial Cylinder ********************// //**************************************************************// - - public int getPartialCylinderVertexCount(int slices, int stacks) - { + public int getPartialCylinderVertexCount(int slices, int stacks) { return (slices + 1) * (stacks + 1); } - public int getPartialCylinderIndexCount(int slices, int stacks) - { + public int getPartialCylinderIndexCount(int slices, int stacks) { return stacks * 2 * (slices + 1) + 2 * (stacks - 1); } @SuppressWarnings({"UnusedDeclaration"}) - public int getPartialCylinderOutlineIndexCount(int slices, int stacks) - { + public int getPartialCylinderOutlineIndexCount(int slices, int stacks) { return slices * 4; } - public int getPartialCylinderDrawMode() - { + public int getPartialCylinderDrawMode() { return GL.GL_TRIANGLE_STRIP; } - public int getPartialCylinderOutlineDrawMode() - { + public int getPartialCylinderOutlineDrawMode() { return GL.GL_LINES; } public LatLon[] makePartialCylinderLocations(Globe globe, LatLon center, double radius, int slices, double start, - double sweep) - { - if (globe == null) - { + double sweep) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (slices < 1) - { + if (slices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2271,8 +2036,7 @@ public LatLon[] makePartialCylinderLocations(Globe globe, LatLon center, double double r = radius / globe.getRadius(); LatLon[] dest = new LatLon[slices + 1]; - for (int i = 0; i <= slices; i++) - { + for (int i = 0; i <= slices; i++) { double a = i * da + start; dest[i] = LatLon.greatCircleEndPosition(center, a, r); } @@ -2281,43 +2045,36 @@ public LatLon[] makePartialCylinderLocations(Globe globe, LatLon center, double } public void makePartialCylinderVertices(Terrain terrain, LatLon center, double radius, double[] altitudes, - boolean[] terrainConformant, int slices, int stacks, double start, double sweep, Vec4 refPoint, float[] dest) - { + boolean[] terrainConformant, int slices, int stacks, double start, double sweep, Vec4 refPoint, float[] dest) { int numPoints = this.getPartialCylinderVertexCount(slices, stacks); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2327,38 +2084,32 @@ public void makePartialCylinderVertices(Terrain terrain, LatLon center, double r double r = radius / terrain.getGlobe().getRadius(); FloatBuffer destBuffer = FloatBuffer.wrap(dest); - for (int i = 0; i <= slices; i++) - { + for (int i = 0; i <= slices; i++) { double a = i * da + start; LatLon ll = LatLon.greatCircleEndPosition(center, a, r); - for (int j = 0; j <= stacks; j++) - { + for (int j = 0; j <= stacks; j++) { this.append(terrain, ll, altitudes[j], terrainConformant[j], refPoint, destBuffer); } } } public void makePartialCylinderVertices(float radius, float height, int slices, int stacks, - float start, float sweep, float[] dest) - { + float start, float sweep, float[] dest) { int numPoints = this.getPartialCylinderVertexCount(slices, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2370,20 +2121,19 @@ public void makePartialCylinderVertices(float radius, float height, int slices, int i, j; int index; - if (stacks != 0.0f) + if (stacks != 0.0f) { dz = height / (float) stacks; - else + } else { dz = 0.0f; + } da = sweep / (float) slices; - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { a = i * da + start; x = (float) Math.sin(a); y = (float) Math.cos(a); z = 0.0f; - for (j = 0; j <= stacks; j++) - { + for (j = 0; j <= stacks; j++) { index = j + i * (stacks + 1); index = 3 * index; dest[index] = x * radius; @@ -2396,25 +2146,21 @@ public void makePartialCylinderVertices(float radius, float height, int slices, @SuppressWarnings({"UnusedDeclaration"}) public void makePartialCylinderNormals(float radius, float height, int slices, int stacks, - float start, float sweep, float[] dest) - { + float start, float sweep, float[] dest) { int numPoints = this.getPartialCylinderVertexCount(slices, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2432,8 +2178,7 @@ public void makePartialCylinderNormals(float radius, float height, int slices, i nsign = (this.orientation == OUTSIDE) ? 1.0f : -1.0f; norm = new float[3]; - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { a = i * da + start; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -2442,8 +2187,7 @@ public void makePartialCylinderNormals(float radius, float height, int slices, i norm[2] = 0.0f; this.norm3AndSet(norm, 0); - for (j = 0; j <= stacks; j++) - { + for (j = 0; j <= stacks; j++) { index = j + i * (stacks + 1); index = 3 * index; System.arraycopy(norm, 0, dest, index, 3); @@ -2451,24 +2195,20 @@ public void makePartialCylinderNormals(float radius, float height, int slices, i } } - public void makePartialCylinderIndices(int slices, int stacks, int[] dest) - { + public void makePartialCylinderIndices(int slices, int stacks, int[] dest) { int numIndices = this.getPartialCylinderIndexCount(slices, stacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2478,18 +2218,14 @@ public void makePartialCylinderIndices(int slices, int stacks, int[] dest) int vertex, index; index = 0; - for (j = 0; j < stacks; j++) - { - if (j != 0) - { - if (this.orientation == INSIDE) - { + for (j = 0; j < stacks; j++) { + if (j != 0) { + if (this.orientation == INSIDE) { vertex = j + slices * (stacks + 1); dest[index++] = vertex - 1; vertex = j + 1; dest[index++] = vertex; - } - else //(this.orientation == OUTSIDE) + } else //(this.orientation == OUTSIDE) { vertex = j + slices * (stacks + 1); dest[index++] = vertex; @@ -2497,15 +2233,12 @@ public void makePartialCylinderIndices(int slices, int stacks, int[] dest) dest[index++] = vertex; } } - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { vertex = j + i * (stacks + 1); - if (this.orientation == INSIDE) - { + if (this.orientation == INSIDE) { dest[index++] = vertex + 1; dest[index++] = vertex; - } - else //(this.orientation == OUTSIDE) + } else //(this.orientation == OUTSIDE) { dest[index++] = vertex; dest[index++] = vertex + 1; @@ -2514,24 +2247,20 @@ public void makePartialCylinderIndices(int slices, int stacks, int[] dest) } } - public void makePartialCylinderOutlineIndices(int slices, int stacks, int[] dest) - { + public void makePartialCylinderOutlineIndices(int slices, int stacks, int[] dest) { int numIndices = this.getPartialCylinderOutlineIndexCount(slices, stacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2542,15 +2271,13 @@ public void makePartialCylinderOutlineIndices(int slices, int stacks, int[] dest index = 0; // Bottom ring - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { vertex = i * (stacks + 1); dest[index++] = vertex; dest[index++] = vertex + stacks + 1; } // Top ring - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { vertex = i * (stacks + 1) + stacks; dest[index++] = vertex; dest[index++] = vertex + stacks + 1; @@ -2560,45 +2287,36 @@ public void makePartialCylinderOutlineIndices(int slices, int stacks, int[] dest //**************************************************************// //******************** Disk ********************// //**************************************************************// - - public int getDiskVertexCount(int slices, int loops) - { + public int getDiskVertexCount(int slices, int loops) { return slices * (loops + 1); } - public int getDiskIndexCount(int slices, int loops) - { + public int getDiskIndexCount(int slices, int loops) { return loops * 2 * (slices + 1) + 2 * (loops - 1); } - public int getDiskDrawMode() - { + public int getDiskDrawMode() { return GL.GL_TRIANGLE_STRIP; } public LatLon[] makeDiskLocations(Globe globe, LatLon center, double innerRadius, double outerRadius, int slices, - int loops) - { - if (globe == null) - { + int loops) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (slices < 1) - { + if (slices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (loops < 1) - { + if (loops < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "loops < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2609,12 +2327,10 @@ public LatLon[] makeDiskLocations(Globe globe, LatLon center, double innerRadius LatLon[] dest = new LatLon[slices * (loops + 1)]; int index = 0; - for (int s = 0; s < slices; s++) - { + for (int s = 0; s < slices; s++) { double a = s * da; - for (int l = 0; l <= loops; l++) - { + for (int l = 0; l <= loops; l++) { double r = (innerRadius + l * dr) / globe.getRadius(); dest[index++] = LatLon.greatCircleEndPosition(center, a, r); } @@ -2623,28 +2339,23 @@ public LatLon[] makeDiskLocations(Globe globe, LatLon center, double innerRadius return dest; } - public LatLon[] makeDiskLocations(Globe globe, LatLon center, double[] radii, Angle heading, int slices, int loops) - { - if (globe == null) - { + public LatLon[] makeDiskLocations(Globe globe, LatLon center, double[] radii, Angle heading, int slices, int loops) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (slices < 1) - { + if (slices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (loops < 1) - { + if (loops < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "loops < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2660,14 +2371,12 @@ public LatLon[] makeDiskLocations(Globe globe, LatLon center, double[] radii, An LatLon[] dest = new LatLon[slices * (loops + 1)]; int index = 0; - for (int s = 0; s < slices; s++) - { + for (int s = 0; s < slices; s++) { double a = s * da; double cosA = Math.cos(a); double sinA = Math.sin(a); - for (int l = 0; l <= loops; l++) - { + for (int l = 0; l <= loops; l++) { double minorRadius = (innerMinorRadius + l * dMinor); double majorRadius = (innerMajorRadius + l * dMajor); double bCosA = minorRadius * cosA; @@ -2681,43 +2390,36 @@ public LatLon[] makeDiskLocations(Globe globe, LatLon center, double[] radii, An } public void makeDiskVertices(Terrain terrain, LatLon center, double innerRadius, double outerRadius, - double altitude, boolean terrainConformant, int slices, int loops, Vec4 refPoint, float[] dest) - { + double altitude, boolean terrainConformant, int slices, int loops, Vec4 refPoint, float[] dest) { int numPoints = this.getDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2728,12 +2430,10 @@ public void makeDiskVertices(Terrain terrain, LatLon center, double innerRadius, double globeRadius = terrain.getGlobe().getRadius(); FloatBuffer destBuffer = FloatBuffer.wrap(dest); - for (int s = 0; s < slices; s++) - { + for (int s = 0; s < slices; s++) { double a = s * da; - for (int l = 0; l <= loops; l++) - { + for (int l = 0; l <= loops; l++) { double r = (innerRadius + l * dr) / globeRadius; LatLon ll = LatLon.greatCircleEndPosition(center, a, r); this.append(terrain, ll, altitude, terrainConformant, refPoint, destBuffer); @@ -2742,43 +2442,36 @@ public void makeDiskVertices(Terrain terrain, LatLon center, double innerRadius, } public void makeDiskVertices(Terrain terrain, LatLon center, double[] radii, Angle heading, - double altitude, boolean terrainConformant, int slices, int loops, Vec4 refPoint, float[] dest) - { + double altitude, boolean terrainConformant, int slices, int loops, Vec4 refPoint, float[] dest) { int numPoints = this.getDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2794,14 +2487,12 @@ public void makeDiskVertices(Terrain terrain, LatLon center, double[] radii, Ang double globeRadius = terrain.getGlobe().getRadius(); FloatBuffer destBuffer = FloatBuffer.wrap(dest); - for (int s = 0; s < slices; s++) - { + for (int s = 0; s < slices; s++) { double a = (s != slices - 1) ? s * da : 0; double cosA = Math.cos(a); double sinA = Math.sin(a); - for (int l = 0; l <= loops; l++) - { + for (int l = 0; l <= loops; l++) { double minorRadius = (innerMinorRadius + l * dMinor); double majorRadius = (innerMajorRadius + l * dMajor); double yLength = majorRadius * cosA; @@ -2814,25 +2505,21 @@ public void makeDiskVertices(Terrain terrain, LatLon center, double[] radii, Ang } } - public void makeDiskVertices(float innerRadius, float outerRadius, int slices, int loops, float[] dest) - { + public void makeDiskVertices(float innerRadius, float outerRadius, int slices, int loops, float[] dest) { int numPoints = this.getDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2847,13 +2534,11 @@ public void makeDiskVertices(float innerRadius, float outerRadius, int slices, i da = 2.0f * (float) Math.PI / (float) slices; dr = (outerRadius - innerRadius) / (float) loops; - for (s = 0; s < slices; s++) - { + for (s = 0; s < slices; s++) { a = s * da; x = (float) Math.sin(a); y = (float) Math.cos(a); - for (l = 0; l <= loops; l++) - { + for (l = 0; l <= loops; l++) { index = l + s * (loops + 1); index = 3 * index; r = innerRadius + l * dr; @@ -2864,25 +2549,21 @@ public void makeDiskVertices(float innerRadius, float outerRadius, int slices, i } } - public void makeDiskNormals(int slices, int loops, float[] dest) - { + public void makeDiskNormals(int slices, int loops, float[] dest) { int numPoints = this.getDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2900,10 +2581,8 @@ public void makeDiskNormals(int slices, int loops, float[] dest) //noinspection PointlessArithmeticExpression normal[2] = 1.0f * nsign; - for (s = 0; s < slices; s++) - { - for (l = 0; l <= loops; l++) - { + for (s = 0; s < slices; s++) { + for (l = 0; l <= loops; l++) { index = l + s * (loops + 1); index = 3 * index; System.arraycopy(normal, 0, dest, index, 3); @@ -2913,31 +2592,26 @@ public void makeDiskNormals(int slices, int loops, float[] dest) @SuppressWarnings({"UnusedDeclaration"}) public void makeDiskVertexNormals(double innerMinorRadius, double outerMinorRadius, int slices, int loops, - float[] srcVerts, float[] dest) - { + float[] srcVerts, float[] dest) { int numPoints = this.getDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (srcVerts == null) - { + if (srcVerts == null) { String message = "nullValue.SourceVertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2953,24 +2627,21 @@ public void makeDiskVertexNormals(double innerMinorRadius, double outerMinorRadi zero = new float[3]; tmp = new float[3]; - for (l = 0; l <= loops; l++) - { + for (l = 0; l <= loops; l++) { // Normal vectors for first and last loops require a special case. - if (l == 0 || l == loops) - { + if (l == 0 || l == loops) { // Closed disk: all slices share a common center point. - if (l == 0 && (innerMinorRadius == 0.0f || outerMinorRadius == 0)) - { + if (l == 0 && (innerMinorRadius == 0.0f || outerMinorRadius == 0)) { // Compute common center point normal. int nextSlice; int adjacentLoop; System.arraycopy(zero, 0, norm, 0, 3); - for (s = 0; s < slices; s++) - { + for (s = 0; s < slices; s++) { index = l + s * (loops + 1); nextSlice = l + (s + 1) * (loops + 1); - if (s == slices - 1) + if (s == slices - 1) { nextSlice = l; + } adjacentLoop = index + 1; this.facenorm(srcVerts, index, nextSlice + 1, adjacentLoop, tmp); this.add3AndSet(norm, 0, tmp, 0); @@ -2978,46 +2649,46 @@ public void makeDiskVertexNormals(double innerMinorRadius, double outerMinorRadi this.mul3AndSet(norm, 0, nsign); this.norm3AndSet(norm, 0); // Copy common normal to the first point of each slice. - for (s = 0; s < slices; s++) - { + for (s = 0; s < slices; s++) { index = l + s * (loops + 1); System.arraycopy(norm, 0, dest, 3 * index, 3); } - } - // Open disk: each slice has a unique starting point. - else - { - for (s = 0; s < slices; s++) - { + } // Open disk: each slice has a unique starting point. + else { + for (s = 0; s < slices; s++) { int prevSlice, nextSlice; int adjacentLoop; index = l + s * (loops + 1); prevSlice = l + (s - 1) * (loops + 1); nextSlice = l + (s + 1) * (loops + 1); - if (s == 0) + if (s == 0) { prevSlice = l + (slices - 1) * (loops + 1); - else if (s == slices - 1) + } else if (s == slices - 1) { nextSlice = l; + } - if (l == 0) + if (l == 0) { adjacentLoop = index + 1; - else + } else { adjacentLoop = index - 1; + } System.arraycopy(zero, 0, norm, 0, 3); // Add clockwise adjacent face. - if (l == 0) + if (l == 0) { this.facenorm(srcVerts, index, nextSlice, adjacentLoop, tmp); - else + } else { this.facenorm(srcVerts, index, adjacentLoop, nextSlice, tmp); + } this.add3AndSet(norm, 0, tmp, 0); // Add counter-clockwise adjacent face. - if (l == 0) + if (l == 0) { this.facenorm(srcVerts, index, adjacentLoop, prevSlice, tmp); - else + } else { this.facenorm(srcVerts, index, prevSlice, adjacentLoop, tmp); + } this.add3AndSet(norm, 0, tmp, 0); // Normalize and place in output. @@ -3026,22 +2697,20 @@ else if (s == slices - 1) System.arraycopy(norm, 0, dest, 3 * index, 3); } } - } - // Normal vectors for internal loops. - else - { - for (s = 0; s < slices; s++) - { + } // Normal vectors for internal loops. + else { + for (s = 0; s < slices; s++) { int prevSlice, nextSlice; int prevLoop, nextLoop; index = l + s * (loops + 1); prevSlice = l + (s - 1) * (loops + 1); nextSlice = l + (s + 1) * (loops + 1); - if (s == 0) + if (s == 0) { prevSlice = l + (slices - 1) * (loops + 1); - else if (s == slices - 1) + } else if (s == slices - 1) { nextSlice = l; + } prevLoop = index - 1; nextLoop = index + 1; @@ -3078,24 +2747,20 @@ else if (s == slices - 1) } } - public void makeDiskIndices(int slices, int loops, int[] dest) - { + public void makeDiskIndices(int slices, int loops, int[] dest) { int numIndices = this.getDiskIndexCount(slices, loops); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3105,17 +2770,13 @@ public void makeDiskIndices(int slices, int loops, int[] dest) int vertex, index; index = 0; - for (l = 0; l < loops; l++) - { - if (l != 0) - { - if (this.orientation == INSIDE) - { + for (l = 0; l < loops; l++) { + if (l != 0) { + if (this.orientation == INSIDE) { vertex = l; dest[index++] = vertex; dest[index++] = vertex; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { vertex = l - 1; dest[index++] = vertex; @@ -3123,18 +2784,16 @@ public void makeDiskIndices(int slices, int loops, int[] dest) dest[index++] = vertex; } } - for (s = 0; s <= slices; s++) - { - if (s == slices) + for (s = 0; s <= slices; s++) { + if (s == slices) { vertex = l; - else + } else { vertex = l + s * (loops + 1); - if (this.orientation == INSIDE) - { + } + if (this.orientation == INSIDE) { dest[index++] = vertex; dest[index++] = vertex + 1; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { dest[index++] = vertex + 1; dest[index++] = vertex; @@ -3146,45 +2805,36 @@ public void makeDiskIndices(int slices, int loops, int[] dest) //**************************************************************// //******************** Partial Disk ********************// //**************************************************************// - - public int getPartialDiskVertexCount(int slices, int loops) - { + public int getPartialDiskVertexCount(int slices, int loops) { return (slices + 1) * (loops + 1); } - public int getPartialDiskIndexCount(int slices, int loops) - { + public int getPartialDiskIndexCount(int slices, int loops) { return loops * 2 * (slices + 1) + 2 * (loops - 1); } - public int getPartialDiskDrawMode() - { + public int getPartialDiskDrawMode() { return GL.GL_TRIANGLE_STRIP; } public LatLon[] makePartialDiskLocations(Globe globe, LatLon center, double innerRadius, double outerRadius, - int slices, int loops, double start, double sweep) - { - if (globe == null) - { + int slices, int loops, double start, double sweep) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (slices < 1) - { + if (slices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (loops < 1) - { + if (loops < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "loops < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3196,12 +2846,10 @@ public LatLon[] makePartialDiskLocations(Globe globe, LatLon center, double inne LatLon[] dest = new LatLon[count]; int index = 0; - for (int s = 0; s <= slices; s++) - { + for (int s = 0; s <= slices; s++) { double a = s * da + start; - for (int l = 0; l <= loops; l++) - { + for (int l = 0; l <= loops; l++) { double r = (innerRadius + l * dr) / globe.getRadius(); dest[index++] = LatLon.greatCircleEndPosition(center, a, r); } @@ -3211,44 +2859,37 @@ public LatLon[] makePartialDiskLocations(Globe globe, LatLon center, double inne } public void makePartialDiskVertices(Terrain terrain, LatLon center, double innerRadius, double outerRadius, - double altitude, boolean terrainConformant, int slices, int loops, double start, double sweep, Vec4 refPoint, - float[] dest) - { + double altitude, boolean terrainConformant, int slices, int loops, double start, double sweep, Vec4 refPoint, + float[] dest) { int numPoints = this.getPartialDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3259,12 +2900,10 @@ public void makePartialDiskVertices(Terrain terrain, LatLon center, double inner double globeRadius = terrain.getGlobe().getRadius(); FloatBuffer destBuffer = FloatBuffer.wrap(dest); - for (int s = 0; s <= slices; s++) - { + for (int s = 0; s <= slices; s++) { double a = s * da + start; - for (int l = 0; l <= loops; l++) - { + for (int l = 0; l <= loops; l++) { double r = (innerRadius + l * dr) / globeRadius; LatLon ll = LatLon.greatCircleEndPosition(center, a, r); this.append(terrain, ll, altitude, terrainConformant, refPoint, destBuffer); @@ -3273,25 +2912,21 @@ public void makePartialDiskVertices(Terrain terrain, LatLon center, double inner } public void makePartialDiskVertices(float innerRadius, float outerRadius, int slices, int loops, - float start, float sweep, float[] dest) - { + float start, float sweep, float[] dest) { int numPoints = this.getPartialDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3306,13 +2941,11 @@ public void makePartialDiskVertices(float innerRadius, float outerRadius, int sl da = sweep / (float) slices; dr = (outerRadius - innerRadius) / (float) loops; - for (s = 0; s <= slices; s++) - { + for (s = 0; s <= slices; s++) { a = s * da + start; x = (float) Math.sin(a); y = (float) Math.cos(a); - for (l = 0; l <= loops; l++) - { + for (l = 0; l <= loops; l++) { index = l + s * (loops + 1); index = 3 * index; r = innerRadius + l * dr; @@ -3323,25 +2956,21 @@ public void makePartialDiskVertices(float innerRadius, float outerRadius, int sl } } - public void makePartialDiskNormals(int slices, int loops, float[] dest) - { + public void makePartialDiskNormals(int slices, int loops, float[] dest) { int numPoints = this.getPartialDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3359,10 +2988,8 @@ public void makePartialDiskNormals(int slices, int loops, float[] dest) //noinspection PointlessArithmeticExpression normal[2] = 1.0f * nsign; - for (s = 0; s <= slices; s++) - { - for (l = 0; l <= loops; l++) - { + for (s = 0; s <= slices; s++) { + for (l = 0; l <= loops; l++) { index = l + s * (loops + 1); index = 3 * index; System.arraycopy(normal, 0, dest, index, 3); @@ -3372,31 +2999,26 @@ public void makePartialDiskNormals(int slices, int loops, float[] dest) @SuppressWarnings({"UnusedDeclaration"}) public void makePartialDiskVertexNormals(float innerRadius, float outerRadius, int slices, int loops, - float start, float sweep, float[] srcVerts, float[] dest) - { + float start, float sweep, float[] srcVerts, float[] dest) { int numPoints = this.getPartialDiskVertexCount(slices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (srcVerts == null) - { + if (srcVerts == null) { String message = "nullValue.SourceVertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3412,20 +3034,16 @@ public void makePartialDiskVertexNormals(float innerRadius, float outerRadius, i zero = new float[3]; tmp = new float[3]; - for (l = 0; l <= loops; l++) - { + for (l = 0; l <= loops; l++) { // Normal vectors for first and last loops require a special case. - if (l == 0 || l == loops) - { + if (l == 0 || l == loops) { // Closed disk: all slices share a common center point. - if (l == 0 && innerRadius == 0.0f) - { + if (l == 0 && innerRadius == 0.0f) { // Compute common center point normal. int nextSlice; int adjacentLoop; System.arraycopy(zero, 0, norm, 0, 3); - for (s = 0; s < slices; s++) - { + for (s = 0; s < slices; s++) { index = l + s * (loops + 1); nextSlice = l + (s + 1) * (loops + 1); adjacentLoop = index + 1; @@ -3435,46 +3053,43 @@ public void makePartialDiskVertexNormals(float innerRadius, float outerRadius, i this.mul3AndSet(norm, 0, nsign); this.norm3AndSet(norm, 0); // Copy common normal to the first point of each slice. - for (s = 0; s <= slices; s++) - { + for (s = 0; s <= slices; s++) { index = l + s * (loops + 1); System.arraycopy(norm, 0, dest, 3 * index, 3); } - } - // Open disk: each slice has a unique starting point. - else - { - for (s = 0; s <= slices; s++) - { + } // Open disk: each slice has a unique starting point. + else { + for (s = 0; s <= slices; s++) { int prevSlice, nextSlice; int adjacentLoop; index = l + s * (loops + 1); - if (l == 0) + if (l == 0) { adjacentLoop = index + 1; - else + } else { adjacentLoop = index - 1; + } System.arraycopy(zero, 0, norm, 0, 3); - if (s > 0) - { + if (s > 0) { prevSlice = l + (s - 1) * (loops + 1); // Add counter-clockwise adjacent face. - if (l == 0) + if (l == 0) { this.facenorm(srcVerts, index, adjacentLoop, prevSlice, tmp); - else + } else { this.facenorm(srcVerts, index, prevSlice, adjacentLoop, tmp); + } this.add3AndSet(norm, 0, tmp, 0); } - if (s < slices) - { + if (s < slices) { nextSlice = l + (s + 1) * (loops + 1); // Add clockwise adjacent face. - if (l == 0) + if (l == 0) { this.facenorm(srcVerts, index, nextSlice, adjacentLoop, tmp); - else + } else { this.facenorm(srcVerts, index, adjacentLoop, nextSlice, tmp); + } this.add3AndSet(norm, 0, tmp, 0); } @@ -3484,12 +3099,9 @@ public void makePartialDiskVertexNormals(float innerRadius, float outerRadius, i System.arraycopy(norm, 0, dest, 3 * index, 3); } } - } - // Normal vectors for internal loops. - else - { - for (s = 0; s <= slices; s++) - { + } // Normal vectors for internal loops. + else { + for (s = 0; s <= slices; s++) { int prevSlice, nextSlice; int prevLoop, nextLoop; index = l + s * (loops + 1); @@ -3497,8 +3109,7 @@ public void makePartialDiskVertexNormals(float innerRadius, float outerRadius, i nextLoop = index + 1; System.arraycopy(zero, 0, norm, 0, 3); - if (s > 0) - { + if (s > 0) { prevSlice = l + (s - 1) * (loops + 1); // Add lower-left adjacent face. this.facenorm(srcVerts, index, prevSlice, prevSlice - 1, tmp); @@ -3511,8 +3122,7 @@ public void makePartialDiskVertexNormals(float innerRadius, float outerRadius, i this.facenorm(srcVerts, index, prevSlice + 1, prevSlice, tmp); this.add3AndSet(norm, 0, tmp, 0); } - if (s < slices) - { + if (s < slices) { nextSlice = l + (s + 1) * (loops + 1); // Add lower-right adjacent face. this.facenorm(srcVerts, index, prevLoop, nextSlice - 1, tmp); @@ -3535,24 +3145,20 @@ public void makePartialDiskVertexNormals(float innerRadius, float outerRadius, i } } - public void makePartialDiskIndices(int slices, int loops, int[] dest) - { + public void makePartialDiskIndices(int slices, int loops, int[] dest) { int numIndices = this.getPartialDiskIndexCount(slices, loops); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "slices=" + slices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3562,18 +3168,14 @@ public void makePartialDiskIndices(int slices, int loops, int[] dest) int vertex, index; index = 0; - for (l = 0; l < loops; l++) - { - if (l != 0) - { - if (this.orientation == INSIDE) - { + for (l = 0; l < loops; l++) { + if (l != 0) { + if (this.orientation == INSIDE) { vertex = l + slices * (loops + 1); dest[index++] = vertex; vertex = l; dest[index++] = vertex; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { vertex = (l - 1) + slices * (loops + 1); dest[index++] = vertex; @@ -3581,15 +3183,12 @@ public void makePartialDiskIndices(int slices, int loops, int[] dest) dest[index++] = vertex + 1; } } - for (s = 0; s <= slices; s++) - { + for (s = 0; s <= slices; s++) { vertex = l + s * (loops + 1); - if (this.orientation == INSIDE) - { + if (this.orientation == INSIDE) { dest[index++] = vertex; dest[index++] = vertex + 1; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { dest[index++] = vertex + 1; dest[index++] = vertex; @@ -3601,73 +3200,60 @@ public void makePartialDiskIndices(int slices, int loops, int[] dest) //**************************************************************// //******************** Radial Wall ********************// //**************************************************************// - - public int getRadialWallVertexCount(int pillars, int stacks) - { + public int getRadialWallVertexCount(int pillars, int stacks) { return (pillars + 1) * (stacks + 1); } - public int getRadialWallIndexCount(int pillars, int stacks) - { + public int getRadialWallIndexCount(int pillars, int stacks) { return stacks * 2 * (pillars + 1) + 2 * (stacks - 1); } @SuppressWarnings({"UnusedDeclaration"}) - public int getRadialWallOutlineIndexCount(int pillars, int stacks) - { + public int getRadialWallOutlineIndexCount(int pillars, int stacks) { return pillars * 4; } - public int getRadialWallDrawMode() - { + public int getRadialWallDrawMode() { return GL.GL_TRIANGLE_STRIP; } - public int getRadialWallOutlineDrawMode() - { + public int getRadialWallOutlineDrawMode() { return GL.GL_LINES; } public void makeRadialWallVertices(Terrain terrain, LatLon center, double innerRadius, double outerRadius, - double angle, double[] altitudes, boolean[] terrainConformant, int pillars, int stacks, Vec4 refPoint, - float[] dest) - { + double angle, double[] altitudes, boolean[] terrainConformant, int pillars, int stacks, Vec4 refPoint, + float[] dest) { int numPoints = this.getRadialWallVertexCount(pillars, stacks); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pillars=" + pillars - + " stacks=" + stacks); + + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3678,10 +3264,8 @@ public void makeRadialWallVertices(Terrain terrain, LatLon center, double innerR double globeRadius = terrain.getGlobe().getRadius(); FloatBuffer destBuffer = FloatBuffer.wrap(dest); - for (int s = 0; s <= stacks; s++) - { - for (int p = 0; p <= pillars; p++) - { + for (int s = 0; s <= stacks; s++) { + for (int p = 0; p <= pillars; p++) { double r = (innerRadius + p * dr) / globeRadius; LatLon ll = LatLon.greatCircleEndPosition(center, a, r); this.append(terrain, ll, altitudes[s], terrainConformant[s], refPoint, destBuffer); @@ -3690,26 +3274,22 @@ public void makeRadialWallVertices(Terrain terrain, LatLon center, double innerR } public void makeRadialWallVertices(float innerRadius, float outerRadius, float height, float angle, - int pillars, int stacks, float[] dest) - { + int pillars, int stacks, float[] dest) { int numPoints = this.getRadialWallVertexCount(pillars, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pillars=" + pillars - + " stacks=" + stacks); + + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3726,16 +3306,15 @@ public void makeRadialWallVertices(float innerRadius, float outerRadius, float h y = (float) Math.cos(a); z = 0.0f; - if (stacks != 0.0f) + if (stacks != 0.0f) { dz = height / (float) stacks; - else + } else { dz = 0.0f; + } dr = (outerRadius - innerRadius) / (float) pillars; - for (s = 0; s <= stacks; s++) - { - for (p = 0; p <= pillars; p++) - { + for (s = 0; s <= stacks; s++) { + for (p = 0; p <= pillars; p++) { index = p + s * (pillars + 1); index = 3 * index; r = innerRadius + p * dr; @@ -3749,26 +3328,22 @@ public void makeRadialWallVertices(float innerRadius, float outerRadius, float h @SuppressWarnings({"UnusedDeclaration"}) public void makeRadialWallNormals(float innerRadius, float outerRadius, float height, float angle, - int pillars, int stacks, float[] dest) - { + int pillars, int stacks, float[] dest) { int numPoints = this.getRadialWallVertexCount(pillars, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pillars=" + pillars - + " stacks=" + stacks); + + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3792,10 +3367,8 @@ public void makeRadialWallNormals(float innerRadius, float outerRadius, float he norm[2] = 0.0f; this.norm3AndSet(norm, 0); - for (s = 0; s <= stacks; s++) - { - for (p = 0; p <= pillars; p++) - { + for (s = 0; s <= stacks; s++) { + for (p = 0; p <= pillars; p++) { index = p + s * (pillars + 1); index = 3 * index; System.arraycopy(norm, 0, dest, index, 3); @@ -3803,25 +3376,21 @@ public void makeRadialWallNormals(float innerRadius, float outerRadius, float he } } - public void makeRadialWallIndices(int pillars, int stacks, int[] dest) - { + public void makeRadialWallIndices(int pillars, int stacks, int[] dest) { int numIndices = this.getRadialWallIndexCount(pillars, stacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pillars=" + pillars - + " stacks=" + stacks); + + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3831,18 +3400,14 @@ public void makeRadialWallIndices(int pillars, int stacks, int[] dest) int vertex, index; index = 0; - for (s = 0; s < stacks; s++) - { - if (s != 0) - { - if (this.orientation == INSIDE) - { + for (s = 0; s < stacks; s++) { + if (s != 0) { + if (this.orientation == INSIDE) { vertex = pillars + s * (pillars + 1); dest[index++] = vertex; vertex = s * (pillars + 1); dest[index++] = vertex; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { vertex = pillars + (s - 1) * (pillars + 1); dest[index++] = vertex; @@ -3850,15 +3415,12 @@ public void makeRadialWallIndices(int pillars, int stacks, int[] dest) dest[index++] = vertex; } } - for (p = 0; p <= pillars; p++) - { + for (p = 0; p <= pillars; p++) { vertex = p + s * (pillars + 1); - if (this.orientation == INSIDE) - { + if (this.orientation == INSIDE) { dest[index++] = vertex; dest[index++] = vertex + (pillars + 1); - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { dest[index++] = vertex + (pillars + 1); dest[index++] = vertex; @@ -3867,25 +3429,21 @@ public void makeRadialWallIndices(int pillars, int stacks, int[] dest) } } - public void makeRadialWallOutlineIndices(int pillars, int stacks, int[] dest) - { + public void makeRadialWallOutlineIndices(int pillars, int stacks, int[] dest) { int numIndices = this.getRadialWallOutlineIndexCount(pillars, stacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pillars=" + pillars - + " stacks=" + stacks); + + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3894,15 +3452,13 @@ public void makeRadialWallOutlineIndices(int pillars, int stacks, int[] dest) int vertex; int index = 0; // Bottom - for (int i = 0; i < pillars; i++) - { + for (int i = 0; i < pillars; i++) { vertex = i; dest[index++] = vertex; dest[index++] = vertex + 1; } // Top - for (int i = 0; i < pillars; i++) - { + for (int i = 0; i < pillars; i++) { vertex = i + stacks * (pillars + 1); dest[index++] = vertex; dest[index++] = vertex + 1; @@ -3912,58 +3468,47 @@ public void makeRadialWallOutlineIndices(int pillars, int stacks, int[] dest) //**************************************************************// //******************** Long Cylinder ********************// //**************************************************************// - - public int getLongCylinderVertexCount(int arcSlices, int lengthSlices, int stacks) - { + public int getLongCylinderVertexCount(int arcSlices, int lengthSlices, int stacks) { int slices = 2 * (arcSlices + 1) + 2 * (lengthSlices - 1); return slices * (stacks + 1); } - public int getLongCylinderIndexCount(int arcSlices, int lengthSlices, int stacks) - { + public int getLongCylinderIndexCount(int arcSlices, int lengthSlices, int stacks) { int slices = 2 * (arcSlices + 1) + 2 * (lengthSlices - 1); return stacks * 2 * (slices + 1) + 2 * (stacks - 1); } @SuppressWarnings({"UnusedDeclaration"}) - public int getLongCylinderOutlineIndexCount(int arcSlices, int lengthSlices, int stacks) - { + public int getLongCylinderOutlineIndexCount(int arcSlices, int lengthSlices, int stacks) { return (arcSlices + lengthSlices) * 2 * 4; } - public int getLongCylinderDrawMode() - { + public int getLongCylinderDrawMode() { return GL.GL_TRIANGLE_STRIP; } - public int getLongCylinderOutlineDrawMode() - { + public int getLongCylinderOutlineDrawMode() { return GL.GL_LINES; } public LatLon[] makeLongCylinderLocations(Globe globe, LatLon center1, LatLon center2, double radius, int arcSlices, - int lengthSlices) - { - if (globe == null) - { + int lengthSlices) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center1 == null || center2 == null) - { + if (center1 == null || center2 == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (arcSlices < 1) - { + if (arcSlices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (lengthSlices < 1) - { + if (lengthSlices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "lengthSlices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -3978,8 +3523,7 @@ public LatLon[] makeLongCylinderLocations(Globe globe, LatLon center1, LatLon ce LatLon[] locations = new LatLon[lengthSlices]; double[] azimuths = new double[lengthSlices]; - for (int i = 1; i < lengthSlices; i++) - { + for (int i = 1; i < lengthSlices; i++) { double s = i * ds; locations[i] = LatLon.greatCircleEndPosition(center1, az1, s); azimuths[i] = LatLon.greatCircleAzimuth(locations[i], center1).radians; @@ -4017,45 +3561,38 @@ public LatLon[] makeLongCylinderLocations(Globe globe, LatLon center1, LatLon ce } public void makeLongCylinderVertices(Terrain terrain, LatLon center1, LatLon center2, double radius, - double[] altitudes, boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, - Vec4 refPoint, float[] dest) - { + double[] altitudes, boolean[] terrainConformant, int arcSlices, int lengthSlices, int stacks, + Vec4 refPoint, float[] dest) { int numPoints = this.getLongCylinderVertexCount(arcSlices, lengthSlices, stacks); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center1 == null || center2 == null) - { + if (center1 == null || center2 == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " stacks=" + stacks); + + " lengthSlices=" + lengthSlices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4071,15 +3608,13 @@ public void makeLongCylinderVertices(Terrain terrain, LatLon center1, LatLon cen LatLon[] locations = new LatLon[lengthSlices]; double[] azimuths = new double[lengthSlices]; - for (int i = 1; i < lengthSlices; i++) - { + for (int i = 1; i < lengthSlices; i++) { double s = i * ds; locations[i] = LatLon.greatCircleEndPosition(center1, az1, s); azimuths[i] = LatLon.greatCircleAzimuth(locations[i], center1).radians; } - for (int j = 0; j <= stacks; j++) - { + for (int j = 0; j <= stacks; j++) { for (int i = 0; i <= arcSlices; i++) // top arc { double a = i * da + az1 + (Math.PI / 2); @@ -4111,26 +3646,22 @@ public void makeLongCylinderVertices(Terrain terrain, LatLon center1, LatLon cen } public void makeLongCylinderVertices(float radius, float length, float height, - int arcSlices, int lengthSlices, int stacks, float[] dest) - { + int arcSlices, int lengthSlices, int stacks, float[] dest) { int numPoints = this.getLongCylinderVertexCount(arcSlices, lengthSlices, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " stacks=" + stacks); + + " lengthSlices=" + lengthSlices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4144,18 +3675,17 @@ public void makeLongCylinderVertices(float radius, float length, float height, da = (float) Math.PI / (float) arcSlices; dy = length / (float) lengthSlices; - if (stacks != 0.0f) + if (stacks != 0.0f) { dz = height / (float) stacks; - else + } else { dz = 0.0f; + } z = 0.0f; index = 0; - for (j = 0; j <= stacks; j++) - { + for (j = 0; j <= stacks; j++) { // Top arc - for (i = 0; i <= arcSlices; i++) - { + for (i = 0; i <= arcSlices; i++) { a = i * da + (3.0f * (float) Math.PI / 2.0f); x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -4164,15 +3694,13 @@ public void makeLongCylinderVertices(float radius, float length, float height, dest[index++] = z; } // Right side. - for (i = lengthSlices - 1; i >= 1; i--) - { + for (i = lengthSlices - 1; i >= 1; i--) { dest[index++] = radius; dest[index++] = i * dy; dest[index++] = z; } // Bottom arc - for (i = 0; i <= arcSlices; i++) - { + for (i = 0; i <= arcSlices; i++) { a = i * da + ((float) Math.PI / 2.0f); x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -4181,8 +3709,7 @@ public void makeLongCylinderVertices(float radius, float length, float height, dest[index++] = z; } // Left side. - for (i = 1; i < lengthSlices; i++) - { + for (i = 1; i < lengthSlices; i++) { dest[index++] = -radius; dest[index++] = i * dy; dest[index++] = z; @@ -4191,26 +3718,22 @@ public void makeLongCylinderVertices(float radius, float length, float height, } } - public void makeLongCylinderNormals(int arcSlices, int lengthSlices, int stacks, float[] dest) - { + public void makeLongCylinderNormals(int arcSlices, int lengthSlices, int stacks, float[] dest) { int numPoints = this.getLongCylinderVertexCount(arcSlices, lengthSlices, stacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " stacks=" + stacks); + + " lengthSlices=" + lengthSlices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4226,11 +3749,9 @@ public void makeLongCylinderNormals(int arcSlices, int lengthSlices, int stacks, nsign = (this.orientation == OUTSIDE) ? 1.0f : -1.0f; index = 0; - for (j = 0; j <= stacks; j++) - { + for (j = 0; j <= stacks; j++) { // Top arc - for (i = 0; i <= arcSlices; i++) - { + for (i = 0; i <= arcSlices; i++) { a = i * da + (3.0f * (float) Math.PI / 2.0f); x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -4239,16 +3760,14 @@ public void makeLongCylinderNormals(int arcSlices, int lengthSlices, int stacks, dest[index++] = 0.0f; } // Right side. - for (i = lengthSlices - 1; i >= 1; i--) - { + for (i = lengthSlices - 1; i >= 1; i--) { //noinspection PointlessArithmeticExpression dest[index++] = 1.0f * nsign; dest[index++] = 0.0f; dest[index++] = 0.0f; } // Bottom arc - for (i = 0; i <= arcSlices; i++) - { + for (i = 0; i <= arcSlices; i++) { a = i * da + ((float) Math.PI / 2.0f); x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -4257,8 +3776,7 @@ public void makeLongCylinderNormals(int arcSlices, int lengthSlices, int stacks, dest[index++] = 0.0f; } // Left side. - for (i = 1; i < lengthSlices; i++) - { + for (i = 1; i < lengthSlices; i++) { dest[index++] = -1.0f * nsign; dest[index++] = 0.0f; dest[index++] = 0.0f; @@ -4266,25 +3784,21 @@ public void makeLongCylinderNormals(int arcSlices, int lengthSlices, int stacks, } } - public void makeLongCylinderIndices(int arcSlices, int lengthSlices, int stacks, int[] dest) - { + public void makeLongCylinderIndices(int arcSlices, int lengthSlices, int stacks, int[] dest) { int numIndices = this.getLongCylinderIndexCount(arcSlices, lengthSlices, stacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " stacks=" + stacks); + + " lengthSlices=" + lengthSlices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4297,18 +3811,14 @@ public void makeLongCylinderIndices(int arcSlices, int lengthSlices, int stacks, slices = 2 * (arcSlices + 1) + 2 * (lengthSlices - 1); index = 0; - for (j = 0; j < stacks; j++) - { - if (j != 0) - { - if (this.orientation == INSIDE) - { + for (j = 0; j < stacks; j++) { + if (j != 0) { + if (this.orientation == INSIDE) { vertex = (j - 1) * slices; dest[index++] = vertex; vertex = j * slices; dest[index++] = vertex; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { vertex = (j - 1) * slices; dest[index++] = vertex + slices; @@ -4316,18 +3826,16 @@ public void makeLongCylinderIndices(int arcSlices, int lengthSlices, int stacks, dest[index++] = vertex; } } - for (i = 0; i <= slices; i++) - { - if (i == slices) + for (i = 0; i <= slices; i++) { + if (i == slices) { vertex = j * slices; - else + } else { vertex = i + j * slices; - if (this.orientation == INSIDE) - { + } + if (this.orientation == INSIDE) { dest[index++] = vertex + slices; dest[index++] = vertex; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { dest[index++] = vertex; dest[index++] = vertex + slices; @@ -4336,25 +3844,21 @@ public void makeLongCylinderIndices(int arcSlices, int lengthSlices, int stacks, } } - public void makeLongCylinderOutlineIndices(int arcSlices, int lengthSlices, int stacks, int[] dest) - { + public void makeLongCylinderOutlineIndices(int arcSlices, int lengthSlices, int stacks, int[] dest) { int numIndices = this.getLongCylinderOutlineIndexCount(arcSlices, lengthSlices, stacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " stacks=" + stacks); + + " lengthSlices=" + lengthSlices + " stacks=" + stacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4366,15 +3870,13 @@ public void makeLongCylinderOutlineIndices(int arcSlices, int lengthSlices, int index = 0; // Bottom ring - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { vertex = i; dest[index++] = vertex; dest[index++] = (i != slices - 1) ? vertex + 1 : 0; } // Top ring - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { vertex = i + slices * stacks; dest[index++] = vertex; dest[index++] = (i != slices - 1) ? vertex + 1 : slices * stacks; @@ -4384,53 +3886,43 @@ public void makeLongCylinderOutlineIndices(int arcSlices, int lengthSlices, int //**************************************************************// //******************** Long Disk ********************// //**************************************************************// - - public int getLongDiskVertexCount(int arcSlices, int lengthSlices, int loops) - { + public int getLongDiskVertexCount(int arcSlices, int lengthSlices, int loops) { int slices = 2 * (arcSlices + 1) + 2 * (lengthSlices - 1); return slices * (loops + 1); } - public int getLongDiskIndexCount(int arcSlices, int lengthSlices, int loops) - { + public int getLongDiskIndexCount(int arcSlices, int lengthSlices, int loops) { int slices = 2 * (arcSlices + 1) + 2 * (lengthSlices - 1); return loops * 2 * (slices + 1) + 2 * (loops - 1); } - public int getLongDiskDrawMode() - { + public int getLongDiskDrawMode() { return GL.GL_TRIANGLE_STRIP; } public LatLon[] makeLongDiskLocations(Globe globe, LatLon center1, LatLon center2, double innerRadius, - double outerRadius, int arcSlices, int lengthSlices, int loops) - { - if (globe == null) - { + double outerRadius, int arcSlices, int lengthSlices, int loops) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center1 == null || center2 == null) - { + if (center1 == null || center2 == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (arcSlices < 1) - { + if (arcSlices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (lengthSlices < 1) - { + if (lengthSlices < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "lengthSlices < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (loops < 1) - { + if (loops < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "loops < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4446,8 +3938,7 @@ public LatLon[] makeLongDiskLocations(Globe globe, LatLon center1, LatLon center LatLon[] locations = new LatLon[lengthSlices]; double[] azimuths = new double[lengthSlices]; - for (int i = 1; i < lengthSlices; i++) - { + for (int i = 1; i < lengthSlices; i++) { double s = i * ds; locations[i] = LatLon.greatCircleEndPosition(center1, az1, s); azimuths[i] = LatLon.greatCircleAzimuth(locations[i], center1).radians; @@ -4458,8 +3949,7 @@ public LatLon[] makeLongDiskLocations(Globe globe, LatLon center1, LatLon center int index = 0; LatLon[] dest = new LatLon[count]; - for (int l = 0; l <= loops; l++) - { + for (int l = 0; l <= loops; l++) { double r = (innerRadius + l * dr) / globeRadius; for (int i = 0; i <= arcSlices; i++) // top arc @@ -4491,45 +3981,38 @@ public LatLon[] makeLongDiskLocations(Globe globe, LatLon center1, LatLon center } public void makeLongDiskVertices(Terrain terrain, LatLon center1, LatLon center2, double innerRadius, - double outerRadius, double altitude, boolean terrainConformant, int arcSlices, int lengthSlices, int loops, - Vec4 refPoint, float[] dest) - { + double outerRadius, double altitude, boolean terrainConformant, int arcSlices, int lengthSlices, int loops, + Vec4 refPoint, float[] dest) { int numPoints = this.getLongDiskVertexCount(arcSlices, lengthSlices, loops); int numCoords = 3 * numPoints; - if (terrain == null) - { + if (terrain == null) { String message = Logging.getMessage("nullValue.TerrainIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center1 == null || center2 == null) - { + if (center1 == null || center2 == null) { String message = Logging.getMessage("nullValue.LocationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " loops=" + loops); + + " lengthSlices=" + lengthSlices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (refPoint == null) - { + if (refPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4546,15 +4029,13 @@ public void makeLongDiskVertices(Terrain terrain, LatLon center1, LatLon center2 LatLon[] locations = new LatLon[lengthSlices]; double[] azimuths = new double[lengthSlices]; - for (int i = 1; i < lengthSlices; i++) - { + for (int i = 1; i < lengthSlices; i++) { double s = i * ds; locations[i] = LatLon.greatCircleEndPosition(center1, az1, s); azimuths[i] = LatLon.greatCircleAzimuth(locations[i], center1).radians; } - for (int l = 0; l <= loops; l++) - { + for (int l = 0; l <= loops; l++) { double r = (innerRadius + l * dr) / globeRadius; for (int i = 0; i <= arcSlices; i++) // top arc @@ -4588,26 +4069,22 @@ public void makeLongDiskVertices(Terrain terrain, LatLon center1, LatLon center2 } public void makeLongDiskVertices(float innerRadius, float outerRadius, float length, - int arcSlices, int lengthSlices, int loops, float[] dest) - { + int arcSlices, int lengthSlices, int loops, float[] dest) { int numPoints = this.getLongDiskVertexCount(arcSlices, lengthSlices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " loops=" + loops); + + " lengthSlices=" + lengthSlices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4624,12 +4101,10 @@ public void makeLongDiskVertices(float innerRadius, float outerRadius, float len dr = (outerRadius - innerRadius) / (float) loops; index = 0; - for (l = 0; l <= loops; l++) - { + for (l = 0; l <= loops; l++) { r = innerRadius + l * dr; // Top arc. - for (s = 0; s <= arcSlices; s++) - { + for (s = 0; s <= arcSlices; s++) { a = s * da + (3.0f * (float) Math.PI / 2.0f); x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -4638,15 +4113,13 @@ public void makeLongDiskVertices(float innerRadius, float outerRadius, float len dest[index++] = 0.0f; } // Right side. - for (s = lengthSlices - 1; s >= 1; s--) - { + for (s = lengthSlices - 1; s >= 1; s--) { dest[index++] = r; dest[index++] = s * dy; dest[index++] = 0.0f; } // Bottom arc. - for (s = 0; s <= arcSlices; s++) - { + for (s = 0; s <= arcSlices; s++) { a = s * da + ((float) Math.PI / 2.0f); x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -4655,8 +4128,7 @@ public void makeLongDiskVertices(float innerRadius, float outerRadius, float len dest[index++] = 0.0f; } // Left side. - for (s = 1; s < lengthSlices; s++) - { + for (s = 1; s < lengthSlices; s++) { dest[index++] = -r; dest[index++] = s * dy; dest[index++] = 0.0f; @@ -4664,26 +4136,22 @@ public void makeLongDiskVertices(float innerRadius, float outerRadius, float len } } - public void makeLongDiskNormals(int arcSlices, int lengthSlices, int loops, float[] dest) - { + public void makeLongDiskNormals(int arcSlices, int lengthSlices, int loops, float[] dest) { int numPoints = this.getLongDiskVertexCount(arcSlices, lengthSlices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " loops=" + loops); + + " lengthSlices=" + lengthSlices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4704,10 +4172,8 @@ public void makeLongDiskNormals(int arcSlices, int lengthSlices, int loops, floa //noinspection PointlessArithmeticExpression normal[2] = 1.0f * nsign; - for (l = 0; l <= loops; l++) - { - for (s = 0; s < slices; s++) - { + for (l = 0; l <= loops; l++) { + for (s = 0; s < slices; s++) { index = s + l * slices; index = 3 * index; System.arraycopy(normal, 0, dest, index, 3); @@ -4717,33 +4183,28 @@ public void makeLongDiskNormals(int arcSlices, int lengthSlices, int loops, floa @SuppressWarnings({"UnusedDeclaration"}) public void makeLongDiskVertexNormals(float innerRadius, float outerRadius, float length, - int arcSlices, int lengthSlices, int loops, - float[] srcVerts, float[] dest) - { + int arcSlices, int lengthSlices, int loops, + float[] srcVerts, float[] dest) { int numPoints = this.getLongDiskVertexCount(arcSlices, lengthSlices, loops); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " loops=" + loops); + + " lengthSlices=" + lengthSlices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (srcVerts == null) - { + if (srcVerts == null) { String message = "nullValue.SourceVertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4761,20 +4222,16 @@ public void makeLongDiskVertexNormals(float innerRadius, float outerRadius, floa zero = new float[3]; tmp = new float[3]; - for (l = 0; l <= loops; l++) - { + for (l = 0; l <= loops; l++) { // Normal vectors for first and last loops require a special case. - if (l == 0 || l == loops) - { + if (l == 0 || l == loops) { // Closed disk: slices are collapsed. - if (l == 0 && innerRadius == 0.0f) - { + if (l == 0 && innerRadius == 0.0f) { // Top arc. { // Compute common normal. System.arraycopy(zero, 0, norm, 0, 3); - for (s = 0; s <= arcSlices; s++) - { + for (s = 0; s <= arcSlices; s++) { index = s; this.facenorm(srcVerts, index, index + slices + 1, index + slices, tmp); this.add3AndSet(norm, 0, tmp, 0); @@ -4788,8 +4245,7 @@ public void makeLongDiskVertexNormals(float innerRadius, float outerRadius, floa this.mul3AndSet(norm, 0, nsign); this.norm3AndSet(norm, 0); // Copy common normal to the first point of each slice. - for (s = 0; s <= arcSlices; s++) - { + for (s = 0; s <= arcSlices; s++) { index = s; System.arraycopy(norm, 0, dest, 3 * index, 3); } @@ -4797,8 +4253,7 @@ public void makeLongDiskVertexNormals(float innerRadius, float outerRadius, floa // Right and left sides. { int leftSideIndex; - for (s = 1; s < lengthSlices; s++) - { + for (s = 1; s < lengthSlices; s++) { // Compute common normal. index = s + arcSlices; leftSideIndex = slices - s; @@ -4807,11 +4262,12 @@ public void makeLongDiskVertexNormals(float innerRadius, float outerRadius, floa this.add3AndSet(norm, 0, tmp, 0); this.facenorm(srcVerts, index, index + 1, index + slices, tmp); this.add3AndSet(norm, 0, tmp, 0); - if (s == 1) + if (s == 1) { this.facenorm(srcVerts, leftSideIndex, leftSideIndex - slices + 1, - leftSideIndex + slices, tmp); - else + leftSideIndex + slices, tmp); + } else { this.facenorm(srcVerts, leftSideIndex, leftSideIndex + 1, leftSideIndex + slices, tmp); + } this.add3AndSet(norm, 0, tmp, 0); this.facenorm(srcVerts, leftSideIndex, leftSideIndex + slices, leftSideIndex - 1, tmp); this.add3AndSet(norm, 0, tmp, 0); @@ -4826,8 +4282,7 @@ public void makeLongDiskVertexNormals(float innerRadius, float outerRadius, floa { // Compute common normal. System.arraycopy(zero, 0, norm, 0, 3); - for (s = 0; s <= arcSlices; s++) - { + for (s = 0; s <= arcSlices; s++) { index = s + arcSlices + lengthSlices; this.facenorm(srcVerts, index, index + slices + 1, index + slices, tmp); this.add3AndSet(norm, 0, tmp, 0); @@ -4841,47 +4296,47 @@ public void makeLongDiskVertexNormals(float innerRadius, float outerRadius, floa this.mul3AndSet(norm, 0, nsign); this.norm3AndSet(norm, 0); // Copy common normal to the first point of each slice. - for (s = 0; s <= arcSlices; s++) - { + for (s = 0; s <= arcSlices; s++) { index = s + arcSlices + lengthSlices; System.arraycopy(norm, 0, dest, 3 * index, 3); } } - } - // Open disk: each slice has a unique starting point. - else - { - for (s = 0; s < slices; s++) - { + } // Open disk: each slice has a unique starting point. + else { + for (s = 0; s < slices; s++) { int prevSlice, nextSlice; int adjacentLoop; index = s + l * slices; prevSlice = index - 1; nextSlice = index + 1; - if (s == 0) + if (s == 0) { prevSlice = l * slices; - else if (s == slices - 1) + } else if (s == slices - 1) { nextSlice = l; + } - if (l == 0) + if (l == 0) { adjacentLoop = index + slices; - else + } else { adjacentLoop = index - slices; + } System.arraycopy(zero, 0, norm, 0, 3); // Add clockwise adjacent face. - if (l == 0) + if (l == 0) { this.facenorm(srcVerts, index, nextSlice, adjacentLoop, tmp); - else + } else { this.facenorm(srcVerts, index, adjacentLoop, nextSlice, tmp); + } this.add3AndSet(norm, 0, tmp, 0); // Add counter-clockwise adjacent face. - if (l == 0) + if (l == 0) { this.facenorm(srcVerts, index, adjacentLoop, prevSlice, tmp); - else + } else { this.facenorm(srcVerts, index, prevSlice, adjacentLoop, tmp); + } this.add3AndSet(norm, 0, tmp, 0); // Normalize and place in output. @@ -4890,22 +4345,20 @@ else if (s == slices - 1) System.arraycopy(norm, 0, dest, 3 * index, 3); } } - } - // Normal vectors for internal loops. - else - { - for (s = 0; s < slices; s++) - { + } // Normal vectors for internal loops. + else { + for (s = 0; s < slices; s++) { int prevSlice, nextSlice; int prevLoop, nextLoop; index = s + l * slices; prevSlice = index - 1; nextSlice = index + 1; - if (s == 0) + if (s == 0) { prevSlice = (slices - 1) + l * slices; - else if (s == slices - 1) + } else if (s == slices - 1) { nextSlice = l * slices; + } prevLoop = index - slices; nextLoop = index + slices; @@ -4942,25 +4395,21 @@ else if (s == slices - 1) } } - public void makeLongDiskIndices(int arcSlices, int lengthSlices, int loops, int[] dest) - { + public void makeLongDiskIndices(int arcSlices, int lengthSlices, int loops, int[] dest) { int numIndices = this.getLongDiskIndexCount(arcSlices, lengthSlices, loops); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "arcSlices=" + arcSlices - + " lengthSlices=" + lengthSlices + " loops=" + loops); + + " lengthSlices=" + lengthSlices + " loops=" + loops); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numIndices) - { + if (dest.length < numIndices) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -4973,18 +4422,14 @@ public void makeLongDiskIndices(int arcSlices, int lengthSlices, int loops, int[ slices = 2 * (arcSlices + 1) + 2 * (lengthSlices - 1); index = 0; - for (l = 0; l < loops; l++) - { - if (l != 0) - { - if (this.orientation == INSIDE) - { + for (l = 0; l < loops; l++) { + if (l != 0) { + if (this.orientation == INSIDE) { vertex = (l - 1) * slices; dest[index++] = vertex + slices; vertex = (l - 1) * slices; dest[index++] = vertex; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { vertex = (l - 1) * slices; dest[index++] = vertex; @@ -4992,18 +4437,16 @@ public void makeLongDiskIndices(int arcSlices, int lengthSlices, int loops, int[ dest[index++] = vertex; } } - for (s = 0; s <= slices; s++) - { - if (s == slices) + for (s = 0; s <= slices; s++) { + if (s == slices) { vertex = l * slices; - else + } else { vertex = s + l * slices; - if (this.orientation == INSIDE) - { + } + if (this.orientation == INSIDE) { dest[index++] = vertex; dest[index++] = vertex + slices; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { dest[index++] = vertex + slices; dest[index++] = vertex; @@ -5015,43 +4458,37 @@ public void makeLongDiskIndices(int arcSlices, int lengthSlices, int loops, int[ //**************************************************************// //******************** Polygon ****************// //**************************************************************// - - public int computePolygonWindingOrder2(int pos, int count, Vec4[] points) - { + public int computePolygonWindingOrder2(int pos, int count, Vec4[] points) { float area; int order; area = this.computePolygonArea2(pos, count, points); - if (area < 0.0f) + if (area < 0.0f) { order = CLOCKWISE; - else + } else { order = COUNTER_CLOCKWISE; + } return order; } - public float computePolygonArea2(int pos, int count, Vec4[] points) - { - if (pos < 0) - { + public float computePolygonArea2(int pos, int count, Vec4[] points) { + if (pos < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pos=" + pos); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (count < 0) - { + if (count < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "count=" + count); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (points == null) - { + if (points == null) { String message = "nullValue.PointsIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (points.length < (pos + count)) - { + if (points.length < (pos + count)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "points.length < " + (pos + count)); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5062,8 +4499,7 @@ public float computePolygonArea2(int pos, int count, Vec4[] points) int coord, nextCoord; area = 0.0f; - for (i = 0; i < count; i++) - { + for (i = 0; i < count; i++) { coord = pos + i; nextCoord = (i == count - 1) ? (pos) : (pos + i + 1); area += points[coord].x * points[nextCoord].y; @@ -5074,22 +4510,18 @@ public float computePolygonArea2(int pos, int count, Vec4[] points) return area; } - public IndexedTriangleArray tessellatePolygon(int pos, int count, float[] vertices, Vec4 normal) - { - if (count < 0) - { + public IndexedTriangleArray tessellatePolygon(int pos, int count, float[] vertices, Vec4 normal) { + if (count < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "count=" + count); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.length < (pos + count)) - { + if (vertices.length < (pos + count)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5101,18 +4533,17 @@ public IndexedTriangleArray tessellatePolygon(int pos, int count, float[] vertic int i; int srcIndex, destIndex; - if (normal == null) + if (normal == null) { normal = Vec4.UNIT_Z; + } cb = new TessellatorCallback(this, count, vertices); glts = new GLUTessellatorSupport(); glts.beginTessellation(cb, normal); - try - { + try { GLU.gluTessBeginPolygon(glts.getGLUtessellator(), null); GLU.gluTessBeginContour(glts.getGLUtessellator()); - for (i = 0; i < count; i++) - { + for (i = 0; i < count; i++) { srcIndex = 3 * (pos + i); destIndex = 3 * i; dvertices[destIndex] = vertices[srcIndex]; @@ -5122,33 +4553,27 @@ public IndexedTriangleArray tessellatePolygon(int pos, int count, float[] vertic } GLU.gluTessEndContour(glts.getGLUtessellator()); GLU.gluTessEndPolygon(glts.getGLUtessellator()); - } - finally - { + } finally { glts.endTessellation(); } return new IndexedTriangleArray( - cb.getIndexCount(), cb.getIndices(), - cb.getVertexCount(), cb.getVertices()); + cb.getIndexCount(), cb.getIndices(), + cb.getVertexCount(), cb.getVertices()); } - public IndexedTriangleArray tessellatePolygon2(int pos, int count, float[] vertices) - { - if (count < 0) - { + public IndexedTriangleArray tessellatePolygon2(int pos, int count, float[] vertices) { + if (count < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "count=" + count); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.length < (pos + count)) - { + if (vertices.length < (pos + count)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5157,8 +4582,8 @@ public IndexedTriangleArray tessellatePolygon2(int pos, int count, float[] verti return this.tessellatePolygon(pos, count, vertices, Vec4.UNIT_Z); } - private static class TessellatorCallback extends GLUtessellatorCallbackAdapter - { + private static class TessellatorCallback extends GLUtessellatorCallbackAdapter { + private GeometryBuilder gb; private int type; private int indexCount; @@ -5168,8 +4593,7 @@ private static class TessellatorCallback extends GLUtessellatorCallbackAdapter private int[] primIndices; private float[] vertices; - private TessellatorCallback(GeometryBuilder gb, int vertexCount, float[] vertices) - { + private TessellatorCallback(GeometryBuilder gb, int vertexCount, float[] vertices) { this.gb = gb; this.indexCount = 0; this.primIndexCount = 0; @@ -5181,28 +4605,23 @@ private TessellatorCallback(GeometryBuilder gb, int vertexCount, float[] vertice this.vertices = this.gb.copyOf(vertices, initialCapacity); } - public int getIndexCount() - { + public int getIndexCount() { return this.indexCount; } - public int[] getIndices() - { + public int[] getIndices() { return this.indices; } - public int getVertexCount() - { + public int getVertexCount() { return this.vertexCount; } - public float[] getVertices() - { + public float[] getVertices() { return this.vertices; } - protected void addTriangle(int i1, int i2, int i3) - { + protected void addTriangle(int i1, int i2, int i3) { // Triangle indices will be specified in counter-clockwise order. To reverse the ordering, we // swap the indices. @@ -5210,20 +4629,17 @@ protected void addTriangle(int i1, int i2, int i3) minCapacity = this.indexCount + 3; oldCapacity = this.indices.length; - while (minCapacity > oldCapacity) - { + while (minCapacity > oldCapacity) { newCapacity = 2 * oldCapacity; this.indices = this.gb.copyOf(this.indices, newCapacity); oldCapacity = minCapacity; } - if (this.gb.orientation == GeometryBuilder.INSIDE) - { + if (this.gb.orientation == GeometryBuilder.INSIDE) { this.indices[this.indexCount++] = this.primIndices[i1]; this.indices[this.indexCount++] = this.primIndices[i3]; this.indices[this.indexCount++] = this.primIndices[i2]; - } - else // (this.gb.orientation == GeometryBuilder.OUTSIDE) + } else // (this.gb.orientation == GeometryBuilder.OUTSIDE) { this.indices[this.indexCount++] = this.primIndices[i1]; this.indices[this.indexCount++] = this.primIndices[i2]; @@ -5231,20 +4647,17 @@ protected void addTriangle(int i1, int i2, int i3) } } - public void begin(int type) - { + public void begin(int type) { this.type = type; this.primIndexCount = 0; } - public void vertex(Object vertexData) - { + public void vertex(Object vertexData) { int minCapacity, oldCapacity, newCapacity; oldCapacity = this.primIndices.length; minCapacity = this.primIndexCount + 1; - while (minCapacity > oldCapacity) - { + while (minCapacity > oldCapacity) { newCapacity = 2 * oldCapacity; this.primIndices = this.gb.copyOf(this.primIndices, newCapacity); oldCapacity = newCapacity; @@ -5254,39 +4667,31 @@ public void vertex(Object vertexData) this.primIndices[this.primIndexCount++] = index; } - public void end() - { + public void end() { int i; - if (this.type == GL.GL_TRIANGLES) - { - for (i = 2; i < this.primIndexCount; i++) - { - if (((i + 1) % 3) == 0) + if (this.type == GL.GL_TRIANGLES) { + for (i = 2; i < this.primIndexCount; i++) { + if (((i + 1) % 3) == 0) { this.addTriangle(i - 2, i - 1, i); + } } - } - else if (this.type == GL.GL_TRIANGLE_STRIP) - { - for (i = 2; i < this.primIndexCount; i++) - { - if ((i % 2) == 0) + } else if (this.type == GL.GL_TRIANGLE_STRIP) { + for (i = 2; i < this.primIndexCount; i++) { + if ((i % 2) == 0) { this.addTriangle(i - 2, i - 1, i); - else + } else { this.addTriangle(i - 1, i - 2, i); + } } - } - else if (this.type == GL.GL_TRIANGLE_FAN) - { - for (i = 2; i < this.primIndexCount; i++) - { + } else if (this.type == GL.GL_TRIANGLE_FAN) { + for (i = 2; i < this.primIndexCount; i++) { this.addTriangle(0, i - 1, i); } } } - public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) - { + public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) { outData[0] = data[0]; } } @@ -5294,52 +4699,43 @@ public void combine(double[] coords, Object[] data, float[] weight, Object[] out //**************************************************************// //******************** Indexed Triangle Buffer ***************// //**************************************************************// - - public int getIndexedTriangleBufferDrawMode() - { + public int getIndexedTriangleBufferDrawMode() { return GL.GL_TRIANGLES; } - public static class IndexedTriangleBuffer - { + public static class IndexedTriangleBuffer { + private IntBuffer indices; private FloatBuffer vertices; private int indexCount; private int vertexCount; - public IndexedTriangleBuffer(int indexCount, IntBuffer indices, int vertexCount, FloatBuffer vertices) - { + public IndexedTriangleBuffer(int indexCount, IntBuffer indices, int vertexCount, FloatBuffer vertices) { this.indices = indices; this.vertices = vertices; this.indexCount = indexCount; this.vertexCount = vertexCount; } - public int getIndexCount() - { + public int getIndexCount() { return this.indexCount; } - public IntBuffer getIndices() - { + public IntBuffer getIndices() { return this.indices; } - public int getVertexCount() - { + public int getVertexCount() { return this.vertexCount; } - public FloatBuffer getVertices() - { + public FloatBuffer getVertices() { return this.vertices; } } - public void subdivideIndexedTriangleBuffer(IndexedTriangleBuffer itb) - { - if (itb == null) - { + public void subdivideIndexedTriangleBuffer(IndexedTriangleBuffer itb) { + if (itb == null) { String message = "nullValue.IndexedTriangleArray"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5358,16 +4754,13 @@ public void subdivideIndexedTriangleBuffer(IndexedTriangleBuffer itb) // Iterate over each triangle, and split the edge of each triangle. Each edge is split exactly once. The // index of the new vertex created by a split is stored in edgeMap. - for (i = 0; i < indexCount; i += 3) - { - for (j = 0; j < 3; j++) - { + for (i = 0; i < indexCount; i += 3) { + for (j = 0; j < 3; j++) { a = itb.indices.get(i + j); b = itb.indices.get((j < 2) ? (i + j + 1) : i); e = new Edge(a, b); split = edgeMap.get(e); - if (split == null) - { + if (split == null) { split = this.splitVertex(itb, a, b); edgeMap.put(e, split); } @@ -5376,8 +4769,7 @@ public void subdivideIndexedTriangleBuffer(IndexedTriangleBuffer itb) // Iterate over each triangle, and create indices for four new triangles, replacing indices of the original // triangle. - for (i = 0; i < indexCount; i += 3) - { + for (i = 0; i < indexCount; i += 3) { a = itb.indices.get(i); b = itb.indices.get(i + 1); c = itb.indices.get(i + 2); @@ -5388,10 +4780,8 @@ public void subdivideIndexedTriangleBuffer(IndexedTriangleBuffer itb) } } - public void makeIndexedTriangleBufferNormals(IndexedTriangleBuffer itb, FloatBuffer dest) - { - if (itb == null) - { + public void makeIndexedTriangleBufferNormals(IndexedTriangleBuffer itb, FloatBuffer dest) { + if (itb == null) { String message = "nullValue.IndexedTriangleArray"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5399,59 +4789,50 @@ public void makeIndexedTriangleBufferNormals(IndexedTriangleBuffer itb, FloatBuf int numCoords = 3 * itb.vertexCount; - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.capacity() < numCoords) - { + if (dest.capacity() < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.capacity(); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.makeIndexedTriangleBufferNormals(0, itb.getIndexCount(), itb.getIndices(), - 0, itb.getVertexCount(), itb.getVertices(), dest); + 0, itb.getVertexCount(), itb.getVertices(), dest); } public void makeIndexedTriangleBufferNormals(int indexPos, int indexCount, IntBuffer indices, - int vertexPos, int vertexCount, FloatBuffer vertices, - FloatBuffer dest) - { - if (indices == null) - { + int vertexPos, int vertexCount, FloatBuffer vertices, + FloatBuffer dest) { + if (indices == null) { String message = "nullValue.IndexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (indices.capacity() < (indexPos + indexCount)) - { + if (indices.capacity() < (indexPos + indexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "indices.length=" + indices.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.capacity() < (vertexPos + vertexCount)) - { + if (vertices.capacity() < (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.capacity() < (vertexPos + vertexCount)) - { + if (dest.capacity() < (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + dest.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5468,24 +4849,21 @@ public void makeIndexedTriangleBufferNormals(int indexPos, int indexCount, IntBu faceIndices = new int[3]; // Compute the normal for each face, contributing that normal to each vertex of the face. - for (i = 0; i < indexCount; i += 3) - { + for (i = 0; i < indexCount; i += 3) { faceIndices[0] = indices.get(indexPos + i); faceIndices[1] = indices.get(indexPos + i + 1); faceIndices[2] = indices.get(indexPos + i + 2); // Compute the normal for this face. this.facenorm(vertices, faceIndices[0], faceIndices[1], faceIndices[2], norm); // Add this face normal to the normal at each vertex. - for (v = 0; v < 3; v++) - { + for (v = 0; v < 3; v++) { index = 3 * faceIndices[v]; this.add3AndSet(dest, index, norm, 0); } } // Scale and normalize each vertex normal. - for (v = 0; v < vertexCount; v++) - { + for (v = 0; v < vertexCount; v++) { index = 3 * (vertexPos + v); this.mul3AndSet(dest, index, nsign); this.norm3AndSet(dest, index); @@ -5494,14 +4872,12 @@ public void makeIndexedTriangleBufferNormals(int indexPos, int indexCount, IntBu dest.rewind(); } - private int splitVertex(IndexedTriangleBuffer itb, int a, int b) - { + private int splitVertex(IndexedTriangleBuffer itb, int a, int b) { int minCapacity, oldCapacity, newCapacity; oldCapacity = itb.vertices.capacity(); minCapacity = 3 * (itb.getVertexCount() + 1); - while (minCapacity > oldCapacity) - { + while (minCapacity > oldCapacity) { newCapacity = 2 * oldCapacity; itb.vertices = this.copyOf(itb.vertices, newCapacity); oldCapacity = newCapacity; @@ -5519,10 +4895,8 @@ private int splitVertex(IndexedTriangleBuffer itb, int a, int b) return s; } - public void makeEllipsoidNormals(IndexedTriangleBuffer itb, FloatBuffer dest) - { - if (itb == null) - { + public void makeEllipsoidNormals(IndexedTriangleBuffer itb, FloatBuffer dest) { + if (itb == null) { String message = "nullValue.IndexedTriangleArray"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5530,59 +4904,50 @@ public void makeEllipsoidNormals(IndexedTriangleBuffer itb, FloatBuffer dest) int numCoords = 3 * itb.vertexCount; - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.capacity() < numCoords) - { + if (dest.capacity() < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.capacity(); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.makeEllipsoidNormals(0, itb.getIndexCount(), itb.getIndices(), - 0, itb.getVertexCount(), itb.getVertices(), dest); + 0, itb.getVertexCount(), itb.getVertices(), dest); } public void makeEllipsoidNormals(int indexPos, int indexCount, IntBuffer indices, - int vertexPos, int vertexCount, FloatBuffer vertices, - FloatBuffer dest) - { - if (indices == null) - { + int vertexPos, int vertexCount, FloatBuffer vertices, + FloatBuffer dest) { + if (indices == null) { String message = "nullValue.IndexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (indices.capacity() < (indexPos + indexCount)) - { + if (indices.capacity() < (indexPos + indexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "indices.length=" + indices.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.capacity() < (vertexPos + vertexCount)) - { + if (vertices.capacity() < (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.capacity() < (vertexPos + vertexCount)) - { + if (dest.capacity() < (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + dest.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5595,16 +4960,13 @@ public void makeEllipsoidNormals(int indexPos, int indexCount, IntBuffer indices nsign = (this.orientation == OUTSIDE) ? 1.0f : -1.0f; // for a sphere, normals are just the normalized vectors of the vertex positions - // first copy all the vertices to the normals buffer - for (i = 0; i < 3 * vertexCount; i++) - { + for (i = 0; i < 3 * vertexCount; i++) { dest.put(i, vertices.get(i)); } // Scale and normalize each vertex normal. - for (v = 0; v < vertexCount; v++) - { + for (v = 0; v < vertexCount; v++) { index = 3 * (vertexPos + v); this.mul3AndSet(dest, index, nsign); this.norm3AndSet(dest, index); @@ -5613,10 +4975,8 @@ public void makeEllipsoidNormals(int indexPos, int indexCount, IntBuffer indices dest.rewind(); } - public void makeCylinderNormals(IndexedTriangleBuffer itb, FloatBuffer dest) - { - if (itb == null) - { + public void makeCylinderNormals(IndexedTriangleBuffer itb, FloatBuffer dest) { + if (itb == null) { String message = "nullValue.IndexedTriangleArray"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5624,59 +4984,50 @@ public void makeCylinderNormals(IndexedTriangleBuffer itb, FloatBuffer dest) int numCoords = 3 * itb.vertexCount; - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.capacity() < numCoords) - { + if (dest.capacity() < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.capacity(); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.makeCylinderNormals(0, itb.getIndexCount(), itb.getIndices(), - 0, itb.getVertexCount(), itb.getVertices(), dest); + 0, itb.getVertexCount(), itb.getVertices(), dest); } public void makeCylinderNormals(int indexPos, int indexCount, IntBuffer indices, - int vertexPos, int vertexCount, FloatBuffer vertices, - FloatBuffer dest) - { - if (indices == null) - { + int vertexPos, int vertexCount, FloatBuffer vertices, + FloatBuffer dest) { + if (indices == null) { String message = "nullValue.IndexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (indices.capacity() < (indexPos + indexCount)) - { + if (indices.capacity() < (indexPos + indexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "indices.length=" + indices.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.capacity() < (vertexPos + vertexCount)) - { + if (vertices.capacity() < (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.capacity() < (vertexPos + vertexCount)) - { + if (dest.capacity() < (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + dest.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5689,19 +5040,18 @@ public void makeCylinderNormals(int indexPos, int indexCount, IntBuffer indices, nsign = (this.orientation == OUTSIDE) ? 1.0f : -1.0f; // for a cylinder, normals are just the normalized vectors of the (x, y) coords of the vertex positions - // first copy all the vertices to the normals buffer - for (i = 0; i < 3 * vertexCount; i++) - { - if (i % 3 == 2) // set z coord to zero + for (i = 0; i < 3 * vertexCount; i++) { + if (i % 3 == 2) // set z coord to zero + { dest.put(i, 0); - else + } else { dest.put(i, -vertices.get(i)); + } } // Scale and normalize each vertex normal. - for (v = 0; v < vertexCount; v++) - { + for (v = 0; v < vertexCount; v++) { index = 3 * (vertexPos + v); this.mul3AndSet(dest, index, nsign); this.norm3AndSet(dest, index); @@ -5711,16 +5061,14 @@ public void makeCylinderNormals(int indexPos, int indexCount, IntBuffer indices, } private void indexSplitTriangle(IndexedTriangleBuffer itb, int original, int a, int b, int c, int ab, int bc, - int ca) - { + int ca) { int minCapacity, oldCapacity, newCapacity; // One of the new triangles will overwrite the original triangles, so we only need enough space to index // three new triangles. oldCapacity = itb.indices.capacity(); minCapacity = itb.getIndexCount() + 9; - while (minCapacity > oldCapacity) - { + while (minCapacity > oldCapacity) { newCapacity = 2 * oldCapacity; itb.indices = this.copyOf(itb.indices, newCapacity); oldCapacity = newCapacity; @@ -5755,9 +5103,7 @@ private void indexSplitTriangle(IndexedTriangleBuffer itb, int original, int a, // duplicate instead. When it comes time for texture mapping, a different texture coordinate can be // mapped to the duplicate vertex than to the original, each one falling in the correct range for the face(s) it // comprises. - - public void fixSphereSeam(IndexedTriangleBuffer itb, float wrapThreshold) - { + public void fixSphereSeam(IndexedTriangleBuffer itb, float wrapThreshold) { int vertex0, vertex1, vertex2; // indices of the three vertices of the current face double x0, y0, x1, y1, x2, y2; // actual x and y point values of those vertices double phi0, phi1, phi2; @@ -5770,8 +5116,7 @@ public void fixSphereSeam(IndexedTriangleBuffer itb, float wrapThreshold) // for each indexed triangle, determine if phi (longitude) of any of the vertices is on the // opposite side of 2PI from others (the "wrap" vertex) int indexCount = itb.getIndexCount(); - for (int i = 0; i < indexCount; i += 3) - { + for (int i = 0; i < indexCount; i += 3) { vertex0 = itb.indices.get(i); vertex1 = itb.indices.get(i + 1); vertex2 = itb.indices.get(i + 2); @@ -5785,37 +5130,38 @@ public void fixSphereSeam(IndexedTriangleBuffer itb, float wrapThreshold) // compute phi of each of the three vertices of the face phi0 = Math.atan2(y0, x0); - if (phi0 < 0.0d) + if (phi0 < 0.0d) { phi0 += 2.0d * Math.PI; + } phi1 = Math.atan2(y1, x1); - if (phi1 < 0.0d) + if (phi1 < 0.0d) { phi1 += 2.0d * Math.PI; + } phi2 = Math.atan2(y2, x2); - if (phi2 < 0.0d) + if (phi2 < 0.0d) { phi2 += 2.0d * Math.PI; + } // check if face spans phi = 0 (the texture seam), and determine which is the "wrapped" vertex - if (Math.abs(phi0 - phi1) > wrapThreshold) - { - if (Math.abs(phi0 - phi2) > wrapThreshold) + if (Math.abs(phi0 - phi1) > wrapThreshold) { + if (Math.abs(phi0 - phi2) > wrapThreshold) { wrapIndex = i; // vertex0 is the wrapped vertex - else + } else { wrapIndex = i + 1; // vertex1 is the wrapped vertex - } - else if (Math.abs(phi1 - phi2) > wrapThreshold) + } + } else if (Math.abs(phi1 - phi2) > wrapThreshold) { wrapIndex = i + 2; // vertex2 is the wrapped vertex - - if (wrapIndex >= 0) // check if one of the vertices on this face wrapped across 2PI + } + if (wrapIndex >= 0) // check if one of the vertices on this face wrapped across 2PI { wrapVertex = itb.indices.get(wrapIndex); //look to see if this vertex has been duplicated already newVertex = duplicates.get(wrapVertex); - if (newVertex != null) + if (newVertex != null) { itb.indices.put(wrapIndex, newVertex); // replace the old vertex with the duplicate - else - { + } else { // create a duplicate of the wrapIndex vertex and get its index newVertex newVertex = duplicateVertex(itb, wrapVertex); // place the new vertex in the duplicates structure @@ -5829,17 +5175,13 @@ else if (Math.abs(phi1 - phi2) > wrapThreshold) } // append copy of vertex at sourceIndex to end of vertices buffer - - private int duplicateVertex(IndexedTriangleBuffer itb, int sourceIndex) - { - if (itb == null) - { + private int duplicateVertex(IndexedTriangleBuffer itb, int sourceIndex) { + if (itb == null) { String message = Logging.getMessage("nullValue.IndexedTriangleBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (sourceIndex >= itb.vertexCount) - { + if (sourceIndex >= itb.vertexCount) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "sourceIndex > vertexCount"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5850,8 +5192,7 @@ private int duplicateVertex(IndexedTriangleBuffer itb, int sourceIndex) oldCapacity = itb.vertices.capacity(); minCapacity = 3 * itb.getVertexCount() + 3; - while (minCapacity > oldCapacity) - { + while (minCapacity > oldCapacity) { newCapacity = 2 * oldCapacity; itb.vertices = this.copyOf(itb.vertices, newCapacity); oldCapacity = newCapacity; @@ -5869,10 +5210,8 @@ private int duplicateVertex(IndexedTriangleBuffer itb, int sourceIndex) return itb.vertexCount - 1; } - public void makeUnitSphereTextureCoordinates(IndexedTriangleBuffer itb, FloatBuffer texCoords) - { - if (itb == null) - { + public void makeUnitSphereTextureCoordinates(IndexedTriangleBuffer itb, FloatBuffer texCoords) { + if (itb == null) { String message = "nullValue.IndexedTriangleArray"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5880,14 +5219,12 @@ public void makeUnitSphereTextureCoordinates(IndexedTriangleBuffer itb, FloatBuf int numCoords = 2 * itb.vertexCount; - if (texCoords == null) - { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoords.capacity() < numCoords) - { + if (texCoords.capacity() < numCoords) { String message = "generic.DestinationArrayInvalidLength " + texCoords.capacity(); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5897,12 +5234,9 @@ public void makeUnitSphereTextureCoordinates(IndexedTriangleBuffer itb, FloatBuf } // allow for correction of seam caused by triangles that wrap across tecture bounds - public void makeUnitSphereTextureCoordinates(IndexedTriangleBuffer itb, FloatBuffer texCoords, - int seamVerticesIndex) - { - if (itb == null) - { + int seamVerticesIndex) { + if (itb == null) { String message = "nullValue.IndexedTriangleArray"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5910,46 +5244,39 @@ public void makeUnitSphereTextureCoordinates(IndexedTriangleBuffer itb, FloatBuf int numCoords = 2 * itb.vertexCount; - if (texCoords == null) - { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoords.capacity() < numCoords) - { + if (texCoords.capacity() < numCoords) { String message = "generic.DestinationArrayInvalidLength " + texCoords.capacity(); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.makeUnitSphereTextureCoordinates(itb.getVertexCount(), itb.getVertices(), - texCoords, seamVerticesIndex); + texCoords, seamVerticesIndex); } public void makeUnitSphereTextureCoordinates(int vertexCount, FloatBuffer vertices, - FloatBuffer texCoords, int seamVerticesIndex) - { - if (vertices == null) - { + FloatBuffer texCoords, int seamVerticesIndex) { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.capacity() < 3 * vertexCount) - { + if (vertices.capacity() < 3 * vertexCount) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoords == null) - { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoords.capacity() < 2 * vertexCount) - { + if (texCoords.capacity() < 2 * vertexCount) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + texCoords.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -5960,8 +5287,7 @@ public void makeUnitSphereTextureCoordinates(int vertexCount, FloatBuffer vertic double theta, phi, u, v; // compute uv texture coordinates for each vertex and place them in the texCoords buffer. - for (i = 0; i < vertexCount; i++) - { + for (i = 0; i < vertexCount; i++) { x = vertices.get(3 * i); y = vertices.get(3 * i + 1); z = vertices.get(3 * i + 2); @@ -5969,9 +5295,9 @@ public void makeUnitSphereTextureCoordinates(int vertexCount, FloatBuffer vertic phi = Math.atan2(y, x); theta = Math.acos(z); - if (phi < 0.0d) + if (phi < 0.0d) { phi += 2.0d * Math.PI; // shift phi to be in [0, 2*PI] - + } u = phi / (2.0d * Math.PI); v = (Math.PI - theta) / Math.PI; @@ -5979,40 +5305,36 @@ public void makeUnitSphereTextureCoordinates(int vertexCount, FloatBuffer vertic texCoords.put(2 * i + 1, (float) v); } - if (seamVerticesIndex > 0) // if the seam of the sphere was fixed + if (seamVerticesIndex > 0) // if the seam of the sphere was fixed { - for (i = seamVerticesIndex; i < vertexCount; i++) - { + for (i = seamVerticesIndex; i < vertexCount; i++) { // wrap u (phi) texCoord for all the duplicated vertices u = texCoords.get(2 * i); - if (u < 0.5) + if (u < 0.5) { texCoords.put(2 * i, (float) u + 1); - else + } else { texCoords.put(2 * i, (float) u - 1); + } } } texCoords.rewind(); } // single texture version - public void makeUnitBoxTextureCoordinates(FloatBuffer texCoords, int vertexCount) - { - if (texCoords == null) - { + public void makeUnitBoxTextureCoordinates(FloatBuffer texCoords, int vertexCount) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoords.capacity() < 2 * vertexCount) - { + if (texCoords.capacity() < 2 * vertexCount) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + texCoords.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // create uv texture coordinates for each of the 6 box faces and place them in the texCoords buffer. - for (int i = 0; i < vertexCount; i += 4) - { + for (int i = 0; i < vertexCount; i += 4) { // V0 (upper left) texCoords.put(2 * i, 0); texCoords.put(2 * i + 1, 1); @@ -6031,24 +5353,20 @@ public void makeUnitBoxTextureCoordinates(FloatBuffer texCoords, int vertexCount } // multi-texture version - public void makeUnitBoxTextureCoordinates(int index, FloatBuffer texCoords, int vertexCount) - { - if (texCoords == null) - { + public void makeUnitBoxTextureCoordinates(int index, FloatBuffer texCoords, int vertexCount) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoords.capacity() < 2 * vertexCount) - { + if (texCoords.capacity() < 2 * vertexCount) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + texCoords.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // create uv texture coordinates for each of the 6 box faces and place them in the texCoords buffer. - for (int i = 0; i < vertexCount; i += 4) - { + for (int i = 0; i < vertexCount; i += 4) { // V0 (upper left) texCoords.put(2 * i, 0); texCoords.put(2 * i + 1, 1); @@ -6066,16 +5384,13 @@ public void makeUnitBoxTextureCoordinates(int index, FloatBuffer texCoords, int texCoords.rewind(); } - public void makeUnitPyramidTextureCoordinates(FloatBuffer texCoords, int vertexCount) - { - if (texCoords == null) - { + public void makeUnitPyramidTextureCoordinates(FloatBuffer texCoords, int vertexCount) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoords.capacity() < 2 * vertexCount) - { + if (texCoords.capacity() < 2 * vertexCount) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + texCoords.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6083,7 +5398,6 @@ public void makeUnitPyramidTextureCoordinates(FloatBuffer texCoords, int vertexC // create uv texture coordinates for each of the 4 pyramid faces and for the base, and place them // in the texCoords buffer. - int i; for (i = 0; i < vertexCount - 4; i += 3) // create texture coords for the 4 sides of the pyramid first { @@ -6099,7 +5413,6 @@ public void makeUnitPyramidTextureCoordinates(FloatBuffer texCoords, int vertexC } // then create coords for the base - // V0 (upper left) texCoords.put(2 * i, 0); texCoords.put(2 * i + 1, 1); @@ -6116,16 +5429,13 @@ public void makeUnitPyramidTextureCoordinates(FloatBuffer texCoords, int vertexC texCoords.rewind(); } - public void makeUnitPyramidTextureCoordinates(int index, FloatBuffer texCoords, int vertexCount) - { - if (texCoords == null) - { + public void makeUnitPyramidTextureCoordinates(int index, FloatBuffer texCoords, int vertexCount) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (texCoords.capacity() < 2 * vertexCount) - { + if (texCoords.capacity() < 2 * vertexCount) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + texCoords.capacity()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6133,9 +5443,8 @@ public void makeUnitPyramidTextureCoordinates(int index, FloatBuffer texCoords, // create uv texture coordinates for either one of the 4 pyramid faces or for the base, and place them // in the texCoords buffer. - int i = 0; - if (index == 4) // pyramid base + if (index == 4) // pyramid base { // V0 (upper left) texCoords.put(2 * i, 0); @@ -6149,8 +5458,7 @@ public void makeUnitPyramidTextureCoordinates(int index, FloatBuffer texCoords, // V3 (lower right) texCoords.put(2 * i + 6, 1); texCoords.put(2 * i + 7, 0); - } - else // pyramid side + } else // pyramid side { for (i = 0; i < vertexCount; i += 3) // create texture coords for the 4 sides of the pyramid first { @@ -6169,16 +5477,13 @@ public void makeUnitPyramidTextureCoordinates(int index, FloatBuffer texCoords, texCoords.rewind(); } - public void makeUnitCylinderTextureCoordinates(int face, FloatBuffer texCoords, int subdivisions) - { - if (texCoords == null) - { + public void makeUnitCylinderTextureCoordinates(int face, FloatBuffer texCoords, int subdivisions) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6186,19 +5491,17 @@ public void makeUnitCylinderTextureCoordinates(int face, FloatBuffer texCoords, // create uv texture coordinates for the cylinder top, bottom and core, and place them // in the texCoords buffer. - int i, index; float x, y, z, u, v, a, phi; int slices = (int) Math.pow(2, 2 + subdivisions); float da = 2.0f * (float) Math.PI / (float) slices; - if (face == 2) // cylinder core + if (face == 2) // cylinder core { int coreTexIndex = 0; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; // cylinder core top rim @@ -6220,16 +5523,14 @@ public void makeUnitCylinderTextureCoordinates(int face, FloatBuffer texCoords, texCoords.put(coreTexIndex + 2, 0); texCoords.put(coreTexIndex + 3, 0); - } - else // cylinder top or bottom + } else // cylinder top or bottom { // center point texCoords.put(0, 0.5f); texCoords.put(1, 0.5f); // perimeter points - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -6237,8 +5538,10 @@ public void makeUnitCylinderTextureCoordinates(int face, FloatBuffer texCoords, u = x / 2 + 0.5f; v = y / 2 + 0.5f; - if (face == 1) // Cylinder bottom + if (face == 1) // Cylinder bottom + { u = 1 - u; + } texCoords.put(2 * (i + 1), u); texCoords.put(2 * (i + 1) + 1, v); @@ -6248,16 +5551,13 @@ public void makeUnitCylinderTextureCoordinates(int face, FloatBuffer texCoords, texCoords.rewind(); } - public void makeWedgeTextureCoordinates(FloatBuffer texCoords, int subdivisions, Angle angle) - { - if (texCoords == null) - { + public void makeWedgeTextureCoordinates(FloatBuffer texCoords, int subdivisions, Angle angle) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6265,7 +5565,6 @@ public void makeWedgeTextureCoordinates(FloatBuffer texCoords, int subdivisions, // create uv texture coordinates for the wedge top, bottom, core and sides, and place them // in the texCoords buffer. - int i, index; float x, y, u, v, a; @@ -6280,8 +5579,7 @@ public void makeWedgeTextureCoordinates(FloatBuffer texCoords, int subdivisions, texCoords.put(2 * (slices + 2), 0.5f); texCoords.put(2 * (slices + 2) + 1, 0.5f); - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -6311,8 +5609,7 @@ public void makeWedgeTextureCoordinates(FloatBuffer texCoords, int subdivisions, } // wedge sides - for (i = 0; i < 2; i++) - { + for (i = 0; i < 2; i++) { index = 2 * (4 * (slices + 1 + i) + 2); // inner points @@ -6333,16 +5630,13 @@ public void makeWedgeTextureCoordinates(FloatBuffer texCoords, int subdivisions, texCoords.rewind(); } - public void makeUnitWedgeTextureCoordinates(int face, FloatBuffer texCoords, int subdivisions, Angle angle) - { - if (texCoords == null) - { + public void makeUnitWedgeTextureCoordinates(int face, FloatBuffer texCoords, int subdivisions, Angle angle) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6350,7 +5644,6 @@ public void makeUnitWedgeTextureCoordinates(int face, FloatBuffer texCoords, int // create uv texture coordinates for the wedge top, bottom, core and sides, and place them // in the texCoords buffer. - int i, index; float x, y, u, v, a; @@ -6359,18 +5652,16 @@ public void makeUnitWedgeTextureCoordinates(int face, FloatBuffer texCoords, int // face 2 = round core wall // face 3 = first wedge side // face 4 = second wedge side - int slices = (int) Math.pow(2, 2 + subdivisions); float da = (float) angle.getRadians() / slices; - if (face == 0 || face == 1) // wedge top or bottom + if (face == 0 || face == 1) // wedge top or bottom { // center point texCoords.put(0, 0.5f); texCoords.put(1, 0.5f); - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -6378,20 +5669,20 @@ public void makeUnitWedgeTextureCoordinates(int face, FloatBuffer texCoords, int u = x / 2 + 0.5f; v = y / 2 + 0.5f; - if (face == 1) // wedge bottom + if (face == 1) // wedge bottom + { u = 1 - u; + } // rim point texCoords.put(2 * (i + 1), u); texCoords.put(2 * (i + 1) + 1, v); } - } - else if (face == 2) // wedge core + } else if (face == 2) // wedge core { int coreTexIndex = 0; - for (i = 0; i <= slices; i++) - { + for (i = 0; i <= slices; i++) { a = i * da; // cylinder core top rim @@ -6406,8 +5697,7 @@ else if (face == 2) // wedge core coreTexIndex += 4; } - } - else if (face == 3) // west-facing wedge side + } else if (face == 3) // west-facing wedge side { // inner points texCoords.put(0, 1); @@ -6422,8 +5712,7 @@ else if (face == 3) // west-facing wedge side texCoords.put(6, 0); texCoords.put(7, 0); - } - else if (face == 4) // adjustable wedge side + } else if (face == 4) // adjustable wedge side { // inner points texCoords.put(0, 0); @@ -6443,16 +5732,13 @@ else if (face == 4) // adjustable wedge side texCoords.rewind(); } - public void makeUnitConeTextureCoordinates(FloatBuffer texCoords, int subdivisions) - { - if (texCoords == null) - { + public void makeUnitConeTextureCoordinates(FloatBuffer texCoords, int subdivisions) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6460,7 +5746,6 @@ public void makeUnitConeTextureCoordinates(FloatBuffer texCoords, int subdivisio // create uv texture coordinates for the cone bottom and core, and place them // in the texCoords buffer. - int i, index; float x, y, z, u, v, a, phi; @@ -6472,8 +5757,7 @@ public void makeUnitConeTextureCoordinates(FloatBuffer texCoords, int subdivisio texCoords.put(0, 0.5f); texCoords.put(1, 0.5f); - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -6508,16 +5792,13 @@ public void makeUnitConeTextureCoordinates(FloatBuffer texCoords, int subdivisio texCoords.rewind(); } - public void makeUnitConeTextureCoordinates(int face, FloatBuffer texCoords, int subdivisions) - { - if (texCoords == null) - { + public void makeUnitConeTextureCoordinates(int face, FloatBuffer texCoords, int subdivisions) { + if (texCoords == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (subdivisions < 0) - { + if (subdivisions < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6525,19 +5806,17 @@ public void makeUnitConeTextureCoordinates(int face, FloatBuffer texCoords, int // create uv texture coordinates for the cone base and core, and place them // in the texCoords buffer. - int i, index; float x, y, z, u, v, a, phi; int slices = (int) Math.pow(2, 2 + subdivisions); float da = 2.0f * (float) Math.PI / (float) slices; - if (face == 1) // cone core + if (face == 1) // cone core { int coreTexIndex = 0; - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; // cone core top rim @@ -6559,16 +5838,14 @@ public void makeUnitConeTextureCoordinates(int face, FloatBuffer texCoords, int texCoords.put(coreTexIndex + 2, 0); texCoords.put(coreTexIndex + 3, 0); - } - else if (face == 0) // cone base + } else if (face == 0) // cone base { // center point texCoords.put(0, 0.5f); texCoords.put(1, 0.5f); // perimeter points - for (i = 0; i < slices; i++) - { + for (i = 0; i < slices; i++) { a = i * da; x = (float) Math.sin(a); y = (float) Math.cos(a); @@ -6587,52 +5864,43 @@ else if (face == 0) // cone base //**************************************************************// //******************** Indexed Triangle Array ****************// //**************************************************************// - - public int getIndexedTriangleArrayDrawMode() - { + public int getIndexedTriangleArrayDrawMode() { return GL.GL_TRIANGLES; } - public static class IndexedTriangleArray - { + public static class IndexedTriangleArray { + private int indexCount; private int vertexCount; private int[] indices; private float[] vertices; - public IndexedTriangleArray(int indexCount, int[] indices, int vertexCount, float[] vertices) - { + public IndexedTriangleArray(int indexCount, int[] indices, int vertexCount, float[] vertices) { this.indexCount = indexCount; this.indices = indices; this.vertexCount = vertexCount; this.vertices = vertices; } - public int getIndexCount() - { + public int getIndexCount() { return this.indexCount; } - public int[] getIndices() - { + public int[] getIndices() { return this.indices; } - public int getVertexCount() - { + public int getVertexCount() { return this.vertexCount; } - public float[] getVertices() - { + public float[] getVertices() { return this.vertices; } } - public void subdivideIndexedTriangleArray(IndexedTriangleArray ita) - { - if (ita == null) - { + public void subdivideIndexedTriangleArray(IndexedTriangleArray ita) { + if (ita == null) { String message = "nullValue.IndexedTriangleArray"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6651,16 +5919,13 @@ public void subdivideIndexedTriangleArray(IndexedTriangleArray ita) // Iterate over each triangle, and split the edge of each triangle. Each edge is split exactly once. The // index of the new vertex created by a split is stored in edgeMap. - for (i = 0; i < indexCount; i += 3) - { - for (j = 0; j < 3; j++) - { + for (i = 0; i < indexCount; i += 3) { + for (j = 0; j < 3; j++) { a = ita.indices[i + j]; b = ita.indices[(j < 2) ? (i + j + 1) : i]; e = new Edge(a, b); split = edgeMap.get(e); - if (split == null) - { + if (split == null) { split = this.splitVertex(ita, a, b); edgeMap.put(e, split); } @@ -6669,8 +5934,7 @@ public void subdivideIndexedTriangleArray(IndexedTriangleArray ita) // Iterate over each triangle, and create indices for four new triangles, replacing indices of the original // triangle. - for (i = 0; i < indexCount; i += 3) - { + for (i = 0; i < indexCount; i += 3) { a = ita.indices[i]; b = ita.indices[i + 1]; c = ita.indices[i + 2]; @@ -6682,30 +5946,25 @@ public void subdivideIndexedTriangleArray(IndexedTriangleArray ita) } public IndexedTriangleArray subdivideIndexedTriangles(int indexCount, int[] indices, - int vertexCount, float[] vertices) - { + int vertexCount, float[] vertices) { int numCoords = 3 * vertexCount; - if (indices == null) - { + if (indices == null) { String message = "nullValue.IndexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (indices.length < indexCount) - { + if (indices.length < indexCount) { String message = Logging.getMessage("generic.ArrayInvalidLength", "indices.length=" + indices.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.length < numCoords) - { + if (vertices.length < numCoords) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6717,10 +5976,8 @@ public IndexedTriangleArray subdivideIndexedTriangles(int indexCount, int[] indi return ita; } - public void makeIndexedTriangleArrayNormals(IndexedTriangleArray ita, float[] dest) - { - if (ita == null) - { + public void makeIndexedTriangleArrayNormals(IndexedTriangleArray ita, float[] dest) { + if (ita == null) { String message = "nullValue.IndexedTriangleArray"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6728,14 +5985,12 @@ public void makeIndexedTriangleArrayNormals(IndexedTriangleArray ita, float[] de int numCoords = 3 * ita.vertexCount; - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6745,41 +6000,34 @@ public void makeIndexedTriangleArrayNormals(IndexedTriangleArray ita, float[] de } public void makeIndexedTriangleArrayNormals(int indexPos, int indexCount, int[] indices, - int vertexPos, int vertexCount, float[] vertices, - float[] dest) - { - if (indices == null) - { + int vertexPos, int vertexCount, float[] vertices, + float[] dest) { + if (indices == null) { String message = "nullValue.IndexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (indices.length < (indexPos + indexCount)) - { + if (indices.length < (indexPos + indexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "indices.length=" + indices.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.length < (vertexPos + vertexCount)) - { + if (vertices.length < (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < (vertexPos + vertexCount)) - { + if (dest.length < (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + dest.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6796,24 +6044,21 @@ public void makeIndexedTriangleArrayNormals(int indexPos, int indexCount, int[] faceIndices = new int[3]; // Compute the normal for each face, contributing that normal to each vertex of the face. - for (i = 0; i < indexCount; i += 3) - { + for (i = 0; i < indexCount; i += 3) { faceIndices[0] = indices[indexPos + i]; faceIndices[1] = indices[indexPos + i + 1]; faceIndices[2] = indices[indexPos + i + 2]; // Compute the normal for this face. this.facenorm(vertices, faceIndices[0], faceIndices[1], faceIndices[2], norm); // Add this face normal to the normal at each vertex. - for (v = 0; v < 3; v++) - { + for (v = 0; v < 3; v++) { index = 3 * faceIndices[v]; this.add3AndSet(dest, index, norm, 0); } } // Scale and normalize each vertex normal. - for (v = 0; v < vertexCount; v++) - { + for (v = 0; v < vertexCount; v++) { index = 3 * (vertexPos + v); this.mul3AndSet(dest, index, nsign); this.norm3AndSet(dest, index); @@ -6821,41 +6066,34 @@ public void makeIndexedTriangleArrayNormals(int indexPos, int indexCount, int[] } public void makeIndexedTriangleStripNormals(int indexPos, int indexCount, int[] indices, - int vertexPos, int vertexCount, float[] vertices, - float[] dest) - { - if (indices == null) - { + int vertexPos, int vertexCount, float[] vertices, + float[] dest) { + if (indices == null) { String message = "nullValue.IndexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (indices.length < indexPos + indexCount) - { + if (indices.length < indexPos + indexCount) { String message = Logging.getMessage("generic.ArrayInvalidLength", "indices.length=" + indices.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices == null) - { + if (vertices == null) { String message = "nullValue.VertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (vertices.length < 3 * (vertexPos + vertexCount)) - { + if (vertices.length < 3 * (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "vertices.length=" + vertices.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < 3 * (vertexPos + vertexCount)) - { + if (dest.length < 3 * (vertexPos + vertexCount)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "dest.length=" + dest.length); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -6872,16 +6110,12 @@ public void makeIndexedTriangleStripNormals(int indexPos, int indexCount, int[] faceIndices = new int[3]; // Compute the normal for each face, contributing that normal to each vertex of the face. - for (i = 2; i < indexCount; i++) - { - if ((i % 2) == 0) - { + for (i = 2; i < indexCount; i++) { + if ((i % 2) == 0) { faceIndices[0] = indices[indexPos + i - 2]; faceIndices[1] = indices[indexPos + i - 1]; faceIndices[2] = indices[indexPos + i]; - } - else - { + } else { faceIndices[0] = indices[indexPos + i - 1]; faceIndices[1] = indices[indexPos + i - 2]; faceIndices[2] = indices[indexPos + i]; @@ -6889,30 +6123,26 @@ public void makeIndexedTriangleStripNormals(int indexPos, int indexCount, int[] // Compute the normal for this face. this.facenorm(vertices, faceIndices[0], faceIndices[1], faceIndices[2], norm); // Add this face normal to the normal at each vertex. - for (v = 0; v < 3; v++) - { + for (v = 0; v < 3; v++) { index = 3 * faceIndices[v]; this.add3AndSet(dest, index, norm, 0); } } // Scale and normalize each vertex normal. - for (v = 0; v < vertexCount; v++) - { + for (v = 0; v < vertexCount; v++) { index = 3 * (vertexPos + v); this.mul3AndSet(dest, index, nsign); this.norm3AndSet(dest, index); } } - private int splitVertex(IndexedTriangleArray ita, int a, int b) - { + private int splitVertex(IndexedTriangleArray ita, int a, int b) { int minCapacity, oldCapacity, newCapacity; oldCapacity = ita.vertices.length; minCapacity = 3 * (ita.vertexCount + 1); - while (minCapacity > oldCapacity) - { + while (minCapacity > oldCapacity) { newCapacity = 2 * oldCapacity; ita.vertices = this.copyOf(ita.vertices, newCapacity); oldCapacity = newCapacity; @@ -6930,16 +6160,14 @@ private int splitVertex(IndexedTriangleArray ita, int a, int b) return s; } - private void indexSplitTriangle(IndexedTriangleArray ita, int original, int a, int b, int c, int ab, int bc, int ca) - { + private void indexSplitTriangle(IndexedTriangleArray ita, int original, int a, int b, int c, int ab, int bc, int ca) { int minCapacity, oldCapacity, newCapacity; // One of the new triangles will overwrite the original triangles, so we only need enough space to index // three new triangles. oldCapacity = ita.indices.length; minCapacity = ita.indexCount + 9; - while (minCapacity > oldCapacity) - { + while (minCapacity > oldCapacity) { newCapacity = 2 * oldCapacity; ita.indices = this.copyOf(ita.indices, newCapacity); oldCapacity = newCapacity; @@ -6967,33 +6195,32 @@ private void indexSplitTriangle(IndexedTriangleArray ita, int original, int a, i ita.indices[ita.indexCount++] = c; } - private static class Edge - { + private static class Edge { + public final int a; public final int b; - public Edge(int a, int b) - { + public Edge(int a, int b) { this.a = a; this.b = b; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } // Compares a non directed edge between two points. Therefore we must treat edge equivalence as // edge(ab)=edge(ab) OR edge(ab)=edge(ba). Edge that = (Edge) o; return (this.a == that.a && this.b == that.b) - || (this.a == that.b && this.b == that.a); + || (this.a == that.b && this.b == that.a); } - public int hashCode() - { + public int hashCode() { // Represents the hash for a a non directed edge between two points. Therefore we use a non-commutative // hash so that hash(ab)=hash(ba). return this.a + this.b; @@ -7003,32 +6230,26 @@ public int hashCode() //**************************************************************// //******************** Subdivision Points ********************// //**************************************************************// - - public int getSubdivisionPointsVertexCount(int subdivisions) - { + public int getSubdivisionPointsVertexCount(int subdivisions) { return (1 << subdivisions) + 1; } public void makeSubdivisionPoints(float x1, float y1, float z1, float x2, float y2, float z2, - int subdivisions, float[] dest) - { + int subdivisions, float[] dest) { int numPoints = this.getSubdivisionPointsVertexCount(subdivisions); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "subdivisions=" + subdivisions); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < numCoords) - { + if (dest.length < numCoords) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -7054,13 +6275,13 @@ public void makeSubdivisionPoints(float x1, float y1, float z1, float x2, float } private void subdivide(float x1, float y1, float z1, float x2, float y2, float z2, int subdivisions, - float[] dest, int first, int last) - { + float[] dest, int first, int last) { float x, y, z; int mid, index; - if (subdivisions <= 0) + if (subdivisions <= 0) { return; + } x = (x1 + x2) / 2.0f; y = (y1 + y2) / 2.0f; @@ -7072,8 +6293,7 @@ private void subdivide(float x1, float y1, float z1, float x2, float y2, float z dest[index + 1] = y; dest[index + 2] = z; - if (subdivisions > 1) - { + if (subdivisions > 1) { this.subdivide(x1, y1, z1, x, y, z, subdivisions - 1, dest, first, mid); this.subdivide(x, y, z, x2, y2, z2, subdivisions - 1, dest, mid, last); } @@ -7082,61 +6302,55 @@ private void subdivide(float x1, float y1, float z1, float x2, float y2, float z //**************************************************************// //******************** Bilinear Surface ********************// //**************************************************************// - - public int getBilinearSurfaceFillIndexCount(int uStacks, int vStacks) - { + public int getBilinearSurfaceFillIndexCount(int uStacks, int vStacks) { return vStacks * 2 * (uStacks + 1) + 2 * (vStacks - 1); } - public int getBilinearSurfaceOutlineIndexCount(int uStacks, int vStacks, int mask) - { + public int getBilinearSurfaceOutlineIndexCount(int uStacks, int vStacks, int mask) { int count = 0; - if ((mask & TOP) != 0) + if ((mask & TOP) != 0) { count += 2 * uStacks; - if ((mask & BOTTOM) != 0) + } + if ((mask & BOTTOM) != 0) { count += 2 * uStacks; - if ((mask & LEFT) != 0) + } + if ((mask & LEFT) != 0) { count += 2 * vStacks; - if ((mask & RIGHT) != 0) + } + if ((mask & RIGHT) != 0) { count += 2 * vStacks; + } return count; } - public int getBilinearSurfaceVertexCount(int uStacks, int vStacks) - { + public int getBilinearSurfaceVertexCount(int uStacks, int vStacks) { return (uStacks + 1) * (vStacks + 1); } - public int getBilinearSurfaceFillDrawMode() - { + public int getBilinearSurfaceFillDrawMode() { return GL.GL_TRIANGLE_STRIP; } - public int getBilinearSurfaceOutlineDrawMode() - { + public int getBilinearSurfaceOutlineDrawMode() { return GL.GL_LINES; } - public void makeBilinearSurfaceFillIndices(int vertexPos, int uStacks, int vStacks, int destPos, int[] dest) - { + public void makeBilinearSurfaceFillIndices(int vertexPos, int uStacks, int vStacks, int destPos, int[] dest) { int numIndices = this.getBilinearSurfaceFillIndexCount(uStacks, vStacks); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "uStacks=" + uStacks - + " vStacks=" + vStacks); + + " vStacks=" + vStacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < (numIndices + destPos)) - { + if (dest.length < (numIndices + destPos)) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -7146,18 +6360,14 @@ public void makeBilinearSurfaceFillIndices(int vertexPos, int uStacks, int vStac int vertex, index; index = destPos; - for (vi = 0; vi < vStacks; vi++) - { - if (vi != 0) - { - if (this.orientation == INSIDE) - { + for (vi = 0; vi < vStacks; vi++) { + if (vi != 0) { + if (this.orientation == INSIDE) { vertex = uStacks + vi * (uStacks + 1); dest[index++] = vertexPos + vertex; vertex = vi * (uStacks + 1); dest[index++] = vertexPos + vertex; - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { vertex = uStacks + (vi - 1) * (uStacks + 1); dest[index++] = vertexPos + vertex; @@ -7165,15 +6375,12 @@ public void makeBilinearSurfaceFillIndices(int vertexPos, int uStacks, int vStac dest[index++] = vertexPos + vertex; } } - for (ui = 0; ui <= uStacks; ui++) - { + for (ui = 0; ui <= uStacks; ui++) { vertex = ui + vi * (uStacks + 1); - if (this.orientation == INSIDE) - { + if (this.orientation == INSIDE) { dest[index++] = vertexPos + vertex; dest[index++] = vertexPos + vertex + (uStacks + 1); - } - else // (this.orientation == OUTSIDE) + } else // (this.orientation == OUTSIDE) { dest[index++] = vertexPos + vertex + (uStacks + 1); dest[index++] = vertexPos + vertex; @@ -7183,25 +6390,21 @@ public void makeBilinearSurfaceFillIndices(int vertexPos, int uStacks, int vStac } public void makeBilinearSurfaceOutlineIndices(int vertexPos, int uStacks, int vStacks, int mask, int destPos, - int[] dest) - { + int[] dest) { int numIndices = this.getBilinearSurfaceOutlineIndexCount(uStacks, vStacks, mask); - if (numIndices < 0) - { + if (numIndices < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "uStacks=" + uStacks - + " vStacks=" + vStacks); + + " vStacks=" + vStacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < (numIndices + destPos)) - { + if (dest.length < (numIndices + destPos)) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -7212,10 +6415,8 @@ public void makeBilinearSurfaceOutlineIndices(int vertexPos, int uStacks, int vS index = destPos; // Bottom row. - if ((mask & BOTTOM) != 0) - { - for (ui = 0; ui < uStacks; ui++) - { + if ((mask & BOTTOM) != 0) { + for (ui = 0; ui < uStacks; ui++) { vertex = ui; dest[index++] = vertexPos + vertex; vertex = ui + 1; @@ -7223,10 +6424,8 @@ public void makeBilinearSurfaceOutlineIndices(int vertexPos, int uStacks, int vS } } // Right side. - if ((mask & RIGHT) != 0) - { - for (vi = 0; vi < vStacks; vi++) - { + if ((mask & RIGHT) != 0) { + for (vi = 0; vi < vStacks; vi++) { vertex = uStacks + vi * (uStacks + 1); dest[index++] = vertexPos + vertex; vertex = uStacks + (vi + 1) * (uStacks + 1); @@ -7234,10 +6433,8 @@ public void makeBilinearSurfaceOutlineIndices(int vertexPos, int uStacks, int vS } } // Top side. - if ((mask & TOP) != 0) - { - for (ui = uStacks; ui > 0; ui--) - { + if ((mask & TOP) != 0) { + for (ui = uStacks; ui > 0; ui--) { vertex = ui + vStacks * (uStacks + 1); dest[index++] = vertexPos + vertex; vertex = (ui - 1) + vStacks * (uStacks + 1); @@ -7245,10 +6442,8 @@ public void makeBilinearSurfaceOutlineIndices(int vertexPos, int uStacks, int vS } } // Left side. - if ((mask & LEFT) != 0) - { - for (vi = vStacks; vi > 0; vi--) - { + if ((mask & LEFT) != 0) { + for (vi = vStacks; vi > 0; vi--) { vertex = vi * (uStacks + 1); dest[index++] = vertexPos + vertex; vertex = (vi - 1) * (uStacks + 1); @@ -7257,38 +6452,32 @@ public void makeBilinearSurfaceOutlineIndices(int vertexPos, int uStacks, int vS } } - public void makeBilinearSurfaceVertices(float[] control, int destPos, int uStacks, int vStacks, float[] dest) - { + public void makeBilinearSurfaceVertices(float[] control, int destPos, int uStacks, int vStacks, float[] dest) { int numPoints = this.getBilinearSurfaceVertexCount(uStacks, vStacks); int numCoords = 3 * numPoints; - if (control == null) - { + if (control == null) { String message = "nullValue.ControlPointArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (control.length < 12) - { + if (control.length < 12) { String message = "generic.ControlPointArrayInvalidLength " + control.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "uStacks=" + uStacks - + " vStacks=" + vStacks); + + " vStacks=" + vStacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < (numCoords + 3 * destPos)) - { + if (dest.length < (numCoords + 3 * destPos)) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -7304,28 +6493,26 @@ public void makeBilinearSurfaceVertices(float[] control, int destPos, int uStack du = 1.0f / (float) uStacks; dv = 1.0f / (float) vStacks; - for (vi = 0; vi <= vStacks; vi++) - { + for (vi = 0; vi <= vStacks; vi++) { v = vi * dv; oneMinusV = 1.0f - v; - for (ui = 0; ui <= uStacks; ui++) - { + for (ui = 0; ui <= uStacks; ui++) { u = ui * du; oneMinusU = 1.0f - u; index = ui + vi * (uStacks + 1); index = 3 * (destPos + index); - x = oneMinusU * oneMinusV * control[0] // Lower left control point - + u * oneMinusV * control[3] // Lower right control point - + u * v * control[6] // Upper right control point - + oneMinusU * v * control[9]; // Upper left control point + x = oneMinusU * oneMinusV * control[0] // Lower left control point + + u * oneMinusV * control[3] // Lower right control point + + u * v * control[6] // Upper right control point + + oneMinusU * v * control[9]; // Upper left control point y = oneMinusU * oneMinusV * control[1] - + u * oneMinusV * control[4] - + u * v * control[7] - + oneMinusU * v * control[10]; + + u * oneMinusV * control[4] + + u * v * control[7] + + oneMinusU * v * control[10]; z = oneMinusU * oneMinusV * control[2] - + u * oneMinusV * control[5] - + u * v * control[8] - + oneMinusU * v * control[11]; + + u * oneMinusV * control[5] + + u * v * control[8] + + oneMinusU * v * control[11]; dest[index] = x; dest[index + 1] = y; dest[index + 2] = z; @@ -7334,32 +6521,27 @@ public void makeBilinearSurfaceVertices(float[] control, int destPos, int uStack } public void makeBilinearSurfaceVertexNormals(int srcPos, int uStacks, int vStacks, float[] srcVerts, - int destPos, float dest[]) - { + int destPos, float dest[]) { int numPoints = this.getBilinearSurfaceVertexCount(uStacks, vStacks); int numCoords = 3 * numPoints; - if (numPoints < 0) - { + if (numPoints < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "uStacks=" + uStacks - + " vStacks=" + vStacks); + + " vStacks=" + vStacks); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (srcVerts == null) - { + if (srcVerts == null) { String message = "nullValue.SourceVertexArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest == null) - { + if (dest == null) { String message = "nullValue.DestinationArrayIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dest.length < (numCoords + 3 * destPos)) - { + if (dest.length < (numCoords + 3 * destPos)) { String message = "generic.DestinationArrayInvalidLength " + dest.length; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -7376,10 +6558,8 @@ public void makeBilinearSurfaceVertexNormals(int srcPos, int uStacks, int vStack zero = new float[3]; tmp = new float[3]; - for (vi = 0; vi <= vStacks; vi++) - { - for (ui = 0; ui <= uStacks; ui++) - { + for (vi = 0; vi <= vStacks; vi++) { + for (ui = 0; ui <= uStacks; ui++) { index = ui + vi * (uStacks + 1); index = srcPos + index; vprev = index - (uStacks + 1); @@ -7388,19 +6568,16 @@ public void makeBilinearSurfaceVertexNormals(int srcPos, int uStacks, int vStack System.arraycopy(zero, 0, norm, 0, 3); // Adjacent faces below. - if (vi > 0) - { + if (vi > 0) { // Adjacent faces below and to the left. - if (ui > 0) - { + if (ui > 0) { this.facenorm(srcVerts, index, index - 1, vprev - 1, tmp); this.add3AndSet(norm, 0, tmp, 0); this.facenorm(srcVerts, index, vprev - 1, vprev, tmp); this.add3AndSet(norm, 0, tmp, 0); } // Adjacent faces below and to the right. - if (ui < uStacks) - { + if (ui < uStacks) { this.facenorm(srcVerts, index, vprev, vprev + 1, tmp); this.add3AndSet(norm, 0, tmp, 0); this.facenorm(srcVerts, index, vprev + 1, index + 1, tmp); @@ -7409,19 +6586,16 @@ public void makeBilinearSurfaceVertexNormals(int srcPos, int uStacks, int vStack } // Adjacent faces above. - if (vi < vStacks) - { + if (vi < vStacks) { // Adjacent faces above and to the left. - if (ui > 0) - { + if (ui > 0) { this.facenorm(srcVerts, index, vnext, vnext - 1, tmp); this.add3AndSet(norm, 0, tmp, 0); this.facenorm(srcVerts, index, vnext - 1, index - 1, tmp); this.add3AndSet(norm, 0, tmp, 0); } // Adjacent faces above and to the right. - if (ui < uStacks) - { + if (ui < uStacks) { this.facenorm(srcVerts, index, index + 1, vnext + 1, tmp); this.add3AndSet(norm, 0, tmp, 0); this.facenorm(srcVerts, index, vnext + 1, vnext, tmp); @@ -7440,7 +6614,6 @@ public void makeBilinearSurfaceVertexNormals(int srcPos, int uStacks, int vStack //**************************************************************// //******************** 2D Shapes *****************************// //**************************************************************// - /** * Creates a vertex buffer for a two-dimensional ellipse centered at the specified location and with the specified * radii. The ellipse's center is placed at (x, y), it has a width of 2 * majorRadius, and @@ -7453,43 +6626,38 @@ public void makeBilinearSurfaceVertexNormals(int srcPos, int uStacks, int vStack * counter-clockwise winding order relative to the z axis. The buffer may be rendered in OpenGL as either a triangle * fan or a line loop. * - * @param x the x-coordinate of the ellipse's center. - * @param y the y-coordinate of the ellipse's center. + * @param x the x-coordinate of the ellipse's center. + * @param y the y-coordinate of the ellipse's center. * @param majorRadius the ellipse's radius along the x axis. * @param minorRadius the ellipse's radius along the y axis. - * @param slices the number of slices in the ellipse. + * @param slices the number of slices in the ellipse. * * @return a buffer containing the ellipse's x and y locations. * * @throws IllegalArgumentException if any of majorRadius, minorRadius, or - * slices are less than zero. + * slices are less than zero. */ - public FloatBuffer makeEllipse(float x, float y, float majorRadius, float minorRadius, int slices) - { - if (majorRadius < 0) - { + public FloatBuffer makeEllipse(float x, float y, float majorRadius, float minorRadius, int slices) { + if (majorRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minorRadius < 0) - { + if (minorRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (slices < 0) - { + if (slices < 0) { String message = Logging.getMessage("generic.NumSlicesIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Return a buffer with only the first point at angle 0 if the number of slices is zero or one. - if (slices <= 1) - { + if (slices <= 1) { // The buffer contains one coordinate pair. FloatBuffer buffer = Buffers.newDirectFloatBuffer(2); buffer.put(x + majorRadius); @@ -7505,8 +6673,7 @@ public FloatBuffer makeEllipse(float x, float y, float majorRadius, float minorR FloatBuffer buffer = Buffers.newDirectFloatBuffer(2 * slices); // Add each vertex on the circumference of the ellipse, starting at zero and ending one step before 360. - for (int i = 0; i < slices; i++, angle += step) - { + for (int i = 0; i < slices; i++, angle += step) { buffer.put(x + (float) Math.cos(angle) * majorRadius); buffer.put(y + (float) Math.sin(angle) * minorRadius); } @@ -7532,65 +6699,61 @@ public FloatBuffer makeEllipse(float x, float y, float majorRadius, float minorR * ellipse. The leader width is limited in size by the side it is attached to. For example, if the leader is * attached to the ellipse's bottom, its width is limited by the ellipse's major radius. * - * @param x the x-coordinate of the ellipse's center. - * @param y the y-coordinate of the ellipse's center. + * @param x the x-coordinate of the ellipse's center. + * @param y the y-coordinate of the ellipse's center. * @param majorRadius the ellipse's radius along the x axis. * @param minorRadius the ellipse's radius along the y axis. - * @param slices the number of slices in the ellipse. - * @param leaderX the x-coordinate the leader points to. - * @param leaderY the y-coordinate the leader points to. + * @param slices the number of slices in the ellipse. + * @param leaderX the x-coordinate the leader points to. + * @param leaderY the y-coordinate the leader points to. * @param leaderWidth the leader triangle's width. * * @return a buffer containing the ellipse's x and y locations. * * @throws IllegalArgumentException if any of majorRadius, minorRadius, - * slices, or leaderWidth are less than zero. + * slices, or leaderWidth are less than zero. */ public FloatBuffer makeEllipseWithLeader(float x, float y, float majorRadius, float minorRadius, int slices, - float leaderX, float leaderY, float leaderWidth) - { - if (majorRadius < 0) - { + float leaderX, float leaderY, float leaderWidth) { + if (majorRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (minorRadius < 0) - { + if (minorRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (slices < 0) - { + if (slices < 0) { String message = Logging.getMessage("generic.NumSlicesIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (leaderWidth < 0) - { + if (leaderWidth < 0) { String message = Logging.getMessage("Geom.WidthIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Return an ellipse without a leader if the leader width is zero. - if (leaderWidth == 0) + if (leaderWidth == 0) { return this.makeEllipse(x, y, majorRadius, minorRadius, slices); + } int leaderCode = this.computeLeaderLocationCode(x - majorRadius, y - minorRadius, x + majorRadius, - y + minorRadius, leaderX, leaderY); + y + minorRadius, leaderX, leaderY); // Return an ellipse without a leader if the leader point is inside the rectangle. - if (leaderCode == LEADER_LOCATION_INSIDE) + if (leaderCode == LEADER_LOCATION_INSIDE) { return this.makeEllipse(x, y, majorRadius, minorRadius, slices); + } // Return a buffer with only the first point at angle 0 if the number of slices is zero or one. - if (slices <= 1) - { + if (slices <= 1) { // The buffer contains one coordinate pair. FloatBuffer buffer = Buffers.newDirectFloatBuffer(2); buffer.put(x + majorRadius); @@ -7604,48 +6767,43 @@ public FloatBuffer makeEllipseWithLeader(float x, float y, float majorRadius, fl float leaderAngle; float startAngle; - if ((leaderCode & LEADER_LOCATION_BOTTOM) != 0) - { + if ((leaderCode & LEADER_LOCATION_BOTTOM) != 0) { // Limit the leader's width by the ellipse's major radius. float maxLeaderWidth = 2f * majorRadius; - if (leaderWidth > maxLeaderWidth) + if (leaderWidth > maxLeaderWidth) { leaderWidth = maxLeaderWidth; + } leaderAngle = leaderWidth / majorRadius; startAngle = 3f * (float) Math.PI / 2f; - } - else if ((leaderCode & LEADER_LOCATION_TOP) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_TOP) != 0) { // Limit the leader's width by the ellipse's major radius. float maxLeaderWidth = 2f * majorRadius; - if (leaderWidth > maxLeaderWidth) + if (leaderWidth > maxLeaderWidth) { leaderWidth = maxLeaderWidth; + } leaderAngle = leaderWidth / majorRadius; startAngle = (float) Math.PI / 2f; - } - else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) { // Limit the leader's width by the ellipse's minor radius. float maxLeaderWidth = 2f * minorRadius; - if (leaderWidth > maxLeaderWidth) + if (leaderWidth > maxLeaderWidth) { leaderWidth = maxLeaderWidth; + } leaderAngle = leaderWidth / minorRadius; startAngle = (float) Math.PI; - } - else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) { // Limit the leader's width by the ellipse's minor radius. float maxLeaderWidth = 2f * minorRadius; - if (leaderWidth > maxLeaderWidth) + if (leaderWidth > maxLeaderWidth) { leaderWidth = maxLeaderWidth; + } leaderAngle = leaderWidth / minorRadius; startAngle = 0f; - } - else - { + } else { // Return an ellipse without a leader if the leader location code is unrecognized. This should never happen, // but we check anyway. return this.makeEllipse(x, y, majorRadius, minorRadius, slices); @@ -7662,8 +6820,7 @@ else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) // Add each vertex on the circumference of the ellipse, starting at the right side of the leader, and ending at // the left side of the leader. - for (int i = 0; i < slices; i++, angle += step) - { + for (int i = 0; i < slices; i++, angle += step) { buffer.put(x + (float) Math.cos(angle) * majorRadius); buffer.put(y + (float) Math.sin(angle) * minorRadius); } @@ -7689,26 +6846,23 @@ else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) * a counter-clockwise winding order relative to the z axis. The buffer may be rendered in OpenGL as either a * triangle fan or a line loop. * - * @param x the x-coordinate of the rectangle's lower left corner. - * @param y the y-coordinate of the rectangle's lower left corner. - * @param width the rectangle's width. + * @param x the x-coordinate of the rectangle's lower left corner. + * @param y the y-coordinate of the rectangle's lower left corner. + * @param width the rectangle's width. * @param height the rectangle's height. * * @return a buffer containing the rectangle's x and y locations. * * @throws IllegalArgumentException if either width or height are less than zero. */ - public FloatBuffer makeRectangle(float x, float y, float width, float height) - { - if (width < 0) - { + public FloatBuffer makeRectangle(float x, float y, float width, float height) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("Geom.HeightIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -7750,43 +6904,38 @@ public FloatBuffer makeRectangle(float x, float y, float width, float height) * a counter-clockwise winding order relative to the z axis. The buffer may be rendered in OpenGL as either a * triangle fan or a line loop. * - * @param x the x-coordinate of the rectangle's lower left corner. - * @param y the y-coordinate of the rectangle's lower left corner. - * @param width the rectangle's width. - * @param height the rectangle's height. + * @param x the x-coordinate of the rectangle's lower left corner. + * @param y the y-coordinate of the rectangle's lower left corner. + * @param width the rectangle's width. + * @param height the rectangle's height. * @param cornerRadius the rectangle's rounded corner radius, or 0 to disable rounded corners. * @param cornerSlices the number of slices in each rounded corner, or 0 to disable rounded corners. * * @return a buffer containing the rectangle's x and y locations. * * @throws IllegalArgumentException if any of width, height, cornerRadius, or - * cornerSlices are less than zero. + * cornerSlices are less than zero. */ - public FloatBuffer makeRectangle(float x, float y, float width, float height, float cornerRadius, int cornerSlices) - { - if (width < 0) - { + public FloatBuffer makeRectangle(float x, float y, float width, float height, float cornerRadius, int cornerSlices) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("Geom.HeightIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cornerRadius < 0) - { + if (cornerRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cornerSlices < 0) - { + if (cornerSlices < 0) { String message = Logging.getMessage("generic.NumSlicesIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -7794,12 +6943,14 @@ public FloatBuffer makeRectangle(float x, float y, float width, float height, fl // Limit the corner radius to half of the rectangles width or height, whichever is smaller. float maxCornerRadius = Math.min(width, height) / 2f; - if (cornerRadius > maxCornerRadius) + if (cornerRadius > maxCornerRadius) { cornerRadius = maxCornerRadius; + } // Create a rectangle with sharp corners if either the corner radius or the number of corner slices is 0. - if (cornerRadius == 0f || cornerSlices == 0) + if (cornerRadius == 0f || cornerSlices == 0) { return this.makeRectangle(x, y, width, height); + } float piOver2 = (float) Math.PI / 2f; @@ -7809,28 +6960,28 @@ public FloatBuffer makeRectangle(float x, float y, float width, float height, fl buffer.put(x); buffer.put(y + cornerRadius); this.addRectangleRoundedCorner(x + cornerRadius, x + cornerRadius, cornerRadius, (float) Math.PI, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + cornerRadius); buffer.put(y); // Lower right corner. buffer.put(x + width - cornerRadius); buffer.put(y); this.addRectangleRoundedCorner(x + width - cornerRadius, y + cornerRadius, cornerRadius, -piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + width); buffer.put(y + cornerRadius); // Upper right corner. buffer.put(x + width); buffer.put(y + height - cornerRadius); this.addRectangleRoundedCorner(x + width - cornerRadius, y + height - cornerRadius, cornerRadius, 0f, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + width - cornerRadius); buffer.put(y + height); // Upper left corner. buffer.put(x + cornerRadius); buffer.put(y + height); this.addRectangleRoundedCorner(x + cornerRadius, y + height - cornerRadius, cornerRadius, piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x); buffer.put(y + height - cornerRadius); // Rewind and return. @@ -7855,59 +7006,57 @@ public FloatBuffer makeRectangle(float x, float y, float width, float height, fl * a counter-clockwise winding order relative to the z axis. The buffer may be rendered in OpenGL as either a * triangle fan or a line loop. * - * @param x the x-coordinate of the rectangle's lower left corner. - * @param y the y-coordinate of the rectangle's lower left corner. - * @param width the rectangle's width. - * @param height the rectangle's height. - * @param leaderX the x-coordinate the leader points to. - * @param leaderY the y-coordinate the leader points to. + * @param x the x-coordinate of the rectangle's lower left corner. + * @param y the y-coordinate of the rectangle's lower left corner. + * @param width the rectangle's width. + * @param height the rectangle's height. + * @param leaderX the x-coordinate the leader points to. + * @param leaderY the y-coordinate the leader points to. * @param leaderWidth the leader triangle's width. * * @return a buffer containing the rectangle's x and y locations. * * @throws IllegalArgumentException if any of width, height, or leaderWidth - * are less than zero. + * are less than zero. */ @SuppressWarnings({"SuspiciousNameCombination"}) public FloatBuffer makeRectangleWithLeader(float x, float y, float width, float height, float leaderX, - float leaderY, float leaderWidth) - { - if (width < 0) - { + float leaderY, float leaderWidth) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("Geom.HeightIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (leaderWidth < 0) - { + if (leaderWidth < 0) { String message = Logging.getMessage("Geom.WidthIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Return a rectangle without a leader if the leader width is zero. - if (leaderWidth == 0) + if (leaderWidth == 0) { return this.makeRectangle(x, y, width, height); + } int leaderCode = this.computeLeaderLocationCode(x, y, x + width, y + height, leaderX, leaderY); // Return a rectangle without a leader if the leader point is inside the rectangle. - if (leaderCode == LEADER_LOCATION_INSIDE) + if (leaderCode == LEADER_LOCATION_INSIDE) { return this.makeRectangle(x, y, width, height); + } - if ((leaderCode & LEADER_LOCATION_BOTTOM) != 0) - { + if ((leaderCode & LEADER_LOCATION_BOTTOM) != 0) { // Limit the leader's width by the rectangle's width. - if (leaderWidth > width) + if (leaderWidth > width) { leaderWidth = width; + } // The buffer contains seven xy coordinate pairs: two pairs for each corner and three pairs for the leader. FloatBuffer buffer = Buffers.newDirectFloatBuffer(14); @@ -7935,12 +7084,11 @@ public FloatBuffer makeRectangleWithLeader(float x, float y, float width, float // Rewind and return. buffer.rewind(); return buffer; - } - else if ((leaderCode & LEADER_LOCATION_TOP) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_TOP) != 0) { // Limit the leader's width by the rectangle's width. - if (leaderWidth > width) + if (leaderWidth > width) { leaderWidth = width; + } // The buffer contains seven xy coordinate pairs: two pairs for each corner and three pairs for the leader. FloatBuffer buffer = Buffers.newDirectFloatBuffer(14); @@ -7968,12 +7116,9 @@ else if ((leaderCode & LEADER_LOCATION_TOP) != 0) // Rewind and return. buffer.rewind(); return buffer; - } - else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) { // Limit the leader's width by the rectangle's height. - if (leaderWidth > height) - { + if (leaderWidth > height) { //noinspection SuspiciousNameCombination leaderWidth = height; } @@ -8004,12 +7149,9 @@ else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) // Rewind and return. buffer.rewind(); return buffer; - } - else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) { // Limit the leader's width by the rectangle's height. - if (leaderWidth > height) - { + if (leaderWidth > height) { //noinspection SuspiciousNameCombination leaderWidth = height; } @@ -8040,9 +7182,7 @@ else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) // Rewind and return. buffer.rewind(); return buffer; - } - else - { + } else { // Return a rectangle without a leader if the leader location code is unrecognized. This should never // happen, but we check anyway. return this.makeRectangle(x, y, width, height); @@ -8075,54 +7215,48 @@ else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) * a counter-clockwise winding order relative to the z axis. The buffer may be rendered in OpenGL as either a * triangle fan or a line loop. * - * @param x the x-coordinate of the rectangle's lower left corner. - * @param y the y-coordinate of the rectangle's lower left corner. - * @param width the rectangle's width. - * @param height the rectangle's height. + * @param x the x-coordinate of the rectangle's lower left corner. + * @param y the y-coordinate of the rectangle's lower left corner. + * @param width the rectangle's width. + * @param height the rectangle's height. * @param cornerRadius the rectangle's rounded corner radius, or 0 to disable rounded corners. * @param cornerSlices the number of slices in each rounded corner, or 0 to disable rounded corners. - * @param leaderX the x-coordinate the leader points to. - * @param leaderY the y-coordinate the leader points to. - * @param leaderWidth the leader triangle's width. + * @param leaderX the x-coordinate the leader points to. + * @param leaderY the y-coordinate the leader points to. + * @param leaderWidth the leader triangle's width. * * @return a buffer containing the rectangle's x and y locations. * * @throws IllegalArgumentException if any of width, height, cornerRadius, - * cornerSlices, or leaderWidth are less than zero. + * cornerSlices, or leaderWidth are less than zero. */ public FloatBuffer makeRectangleWithLeader(float x, float y, float width, float height, float cornerRadius, - int cornerSlices, float leaderX, float leaderY, float leaderWidth) - { - if (width < 0) - { + int cornerSlices, float leaderX, float leaderY, float leaderWidth) { + if (width < 0) { String message = Logging.getMessage("Geom.WidthIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 0) - { + if (height < 0) { String message = Logging.getMessage("Geom.HeightIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cornerRadius < 0) - { + if (cornerRadius < 0) { String message = Logging.getMessage("Geom.RadiusIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (cornerSlices < 0) - { + if (cornerSlices < 0) { String message = Logging.getMessage("generic.NumSlicesIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (leaderWidth < 0) - { + if (leaderWidth < 0) { String message = Logging.getMessage("Geom.WidthIsNegative"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -8130,31 +7264,35 @@ public FloatBuffer makeRectangleWithLeader(float x, float y, float width, float // Limit the corner radius to half of the rectangles width or height, whichever is smaller. float maxCornerRadius = Math.min(width, height) / 2f; - if (cornerRadius > maxCornerRadius) + if (cornerRadius > maxCornerRadius) { cornerRadius = maxCornerRadius; + } // Create a rectangle with sharp corners if either the corner radius or the number of corner slices is 0. - if (cornerRadius == 0f || cornerSlices == 0) + if (cornerRadius == 0f || cornerSlices == 0) { return this.makeRectangleWithLeader(x, y, width, height, leaderX, leaderY, leaderWidth); + } // Return a rectangle without a leader if the leader width is zero. - if (leaderWidth == 0) + if (leaderWidth == 0) { return this.makeRectangle(x, y, width, height, cornerRadius, cornerSlices); + } int leaderCode = this.computeLeaderLocationCode(x, y, x + width, y + height, leaderX, leaderY); // Return a rectangle without a leader if the leader point is inside the rectangle. - if (leaderCode == LEADER_LOCATION_INSIDE) + if (leaderCode == LEADER_LOCATION_INSIDE) { return this.makeRectangle(x, y, width, height, cornerRadius, cornerSlices); + } float piOver2 = (float) Math.PI / 2f; - if ((leaderCode & LEADER_LOCATION_BOTTOM) != 0) - { + if ((leaderCode & LEADER_LOCATION_BOTTOM) != 0) { // Limit the leader width by the rectangle's width minus any width used by the rounded corners. float maxLeaderWidth = width - 2f * cornerRadius; - if (leaderWidth > maxLeaderWidth) + if (leaderWidth > maxLeaderWidth) { leaderWidth = maxLeaderWidth; + } // The buffer contains two coordinate pairs for each corner, three coordinate pairs for the leader, and two // coordinate pairs per corner vertex. @@ -8166,29 +7304,29 @@ public FloatBuffer makeRectangleWithLeader(float x, float y, float width, float buffer.put(x + width - cornerRadius); buffer.put(y); this.addRectangleRoundedCorner(x + width - cornerRadius, y + cornerRadius, cornerRadius, -piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + width); buffer.put(y + cornerRadius); // Upper right corner. buffer.put(x + width); buffer.put(y + height - cornerRadius); this.addRectangleRoundedCorner(x + width - cornerRadius, y + height - cornerRadius, cornerRadius, 0f, - piOver2, - cornerSlices, buffer); + piOver2, + cornerSlices, buffer); buffer.put(x + width - cornerRadius); buffer.put(y + height); // Upper left corner. buffer.put(x + cornerRadius); buffer.put(y + height); this.addRectangleRoundedCorner(x + cornerRadius, y + height - cornerRadius, cornerRadius, piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x); buffer.put(y + height - cornerRadius); // Lower left corner. buffer.put(x); buffer.put(y + cornerRadius); this.addRectangleRoundedCorner(x + cornerRadius, x + cornerRadius, cornerRadius, (float) Math.PI, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + cornerRadius); buffer.put(y); // Leader left corner. @@ -8200,13 +7338,12 @@ public FloatBuffer makeRectangleWithLeader(float x, float y, float width, float // Rewind and return. buffer.rewind(); return buffer; - } - else if ((leaderCode & LEADER_LOCATION_TOP) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_TOP) != 0) { // Limit the leader width by the rectangle's width minus any width used by the rounded corners. float maxLeaderWidth = width - 2f * cornerRadius; - if (leaderWidth > maxLeaderWidth) + if (leaderWidth > maxLeaderWidth) { leaderWidth = maxLeaderWidth; + } // The buffer contains two coordinate pairs for each corner, three coordinate pairs for the leader, and two // coordinate pairs per corner vertex. @@ -8218,29 +7355,29 @@ else if ((leaderCode & LEADER_LOCATION_TOP) != 0) buffer.put(x + cornerRadius); buffer.put(y + height); this.addRectangleRoundedCorner(x + cornerRadius, y + height - cornerRadius, cornerRadius, piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x); buffer.put(y + height - cornerRadius); // Lower left corner. buffer.put(x); buffer.put(y + cornerRadius); this.addRectangleRoundedCorner(x + cornerRadius, x + cornerRadius, cornerRadius, (float) Math.PI, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + cornerRadius); buffer.put(y); // Lower right corner. buffer.put(x + width - cornerRadius); buffer.put(y); this.addRectangleRoundedCorner(x + width - cornerRadius, y + cornerRadius, cornerRadius, -piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + width); buffer.put(y + cornerRadius); // Upper right corner. buffer.put(x + width); buffer.put(y + height - cornerRadius); this.addRectangleRoundedCorner(x + width - cornerRadius, y + height - cornerRadius, cornerRadius, 0f, - piOver2, - cornerSlices, buffer); + piOver2, + cornerSlices, buffer); buffer.put(x + width - cornerRadius); buffer.put(y + height); // Leader right corner. @@ -8252,13 +7389,12 @@ else if ((leaderCode & LEADER_LOCATION_TOP) != 0) // Rewind and return. buffer.rewind(); return buffer; - } - else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) { // Limit the leader width by the rectangle's height minus any width used by the rounded corners. float maxLeaderWidth = height - 2f * cornerRadius; - if (leaderWidth > maxLeaderWidth) + if (leaderWidth > maxLeaderWidth) { leaderWidth = maxLeaderWidth; + } // The buffer contains two coordinate pairs for each corner, three coordinate pairs for the leader, and two // coordinate pairs per corner vertex. @@ -8270,29 +7406,29 @@ else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) buffer.put(x); buffer.put(y + cornerRadius); this.addRectangleRoundedCorner(x + cornerRadius, x + cornerRadius, cornerRadius, (float) Math.PI, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + cornerRadius); buffer.put(y); // Lower right corner. buffer.put(x + width - cornerRadius); buffer.put(y); this.addRectangleRoundedCorner(x + width - cornerRadius, y + cornerRadius, cornerRadius, -piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + width); buffer.put(y + cornerRadius); // Upper right corner. buffer.put(x + width); buffer.put(y + height - cornerRadius); this.addRectangleRoundedCorner(x + width - cornerRadius, y + height - cornerRadius, cornerRadius, 0f, - piOver2, - cornerSlices, buffer); + piOver2, + cornerSlices, buffer); buffer.put(x + width - cornerRadius); buffer.put(y + height); // Upper left corner. buffer.put(x + cornerRadius); buffer.put(y + height); this.addRectangleRoundedCorner(x + cornerRadius, y + height - cornerRadius, cornerRadius, piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x); buffer.put(y + height - cornerRadius); // Leader top corner. @@ -8304,13 +7440,12 @@ else if ((leaderCode & LEADER_LOCATION_LEFT) != 0) // Rewind and return. buffer.rewind(); return buffer; - } - else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) - { + } else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) { // Limit the leader width by the rectangle's height minus any width used by the rounded corners. float maxLeaderWidth = height - 2f * cornerRadius; - if (leaderWidth > maxLeaderWidth) + if (leaderWidth > maxLeaderWidth) { leaderWidth = maxLeaderWidth; + } // The buffer contains two coordinate pairs for each corner, three coordinate pairs for the leader, and two // coordinate pairs per corner vertex. @@ -8322,29 +7457,29 @@ else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) buffer.put(x + width); buffer.put(y + height - cornerRadius); this.addRectangleRoundedCorner(x + width - cornerRadius, y + height - cornerRadius, cornerRadius, 0f, - piOver2, - cornerSlices, buffer); + piOver2, + cornerSlices, buffer); buffer.put(x + width - cornerRadius); buffer.put(y + height); // Upper left corner. buffer.put(x + cornerRadius); buffer.put(y + height); this.addRectangleRoundedCorner(x + cornerRadius, y + height - cornerRadius, cornerRadius, piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x); buffer.put(y + height - cornerRadius); // Lower left corner. buffer.put(x); buffer.put(y + cornerRadius); this.addRectangleRoundedCorner(x + cornerRadius, x + cornerRadius, cornerRadius, (float) Math.PI, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + cornerRadius); buffer.put(y); // Lower right corner. buffer.put(x + width - cornerRadius); buffer.put(y); this.addRectangleRoundedCorner(x + width - cornerRadius, y + cornerRadius, cornerRadius, -piOver2, piOver2, - cornerSlices, buffer); + cornerSlices, buffer); buffer.put(x + width); buffer.put(y + cornerRadius); // Leader bottom corner. @@ -8356,9 +7491,7 @@ else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) // Rewind and return. buffer.rewind(); return buffer; - } - else - { + } else { // Return a rectangle without a leader if the leader location code is unrecognized. This should never // happen, but we check anyway. return this.makeRectangle(x, y, width, height, cornerRadius, cornerSlices); @@ -8371,25 +7504,24 @@ else if ((leaderCode & LEADER_LOCATION_RIGHT) != 0) * intermediate vertices. The number of intermediate vertices is equal to slices - 2. This does nothing * if slices is one or zero. * - * @param x the x-coordinate of the corner's origin. - * @param y the y-coordinate of the corner's origin. + * @param x the x-coordinate of the corner's origin. + * @param y the y-coordinate of the corner's origin. * @param radius the corner's radius. - * @param start the corner's starting angle, in radians. - * @param sweep the corner's angular distance, in radians. + * @param start the corner's starting angle, in radians. + * @param sweep the corner's angular distance, in radians. * @param slices the number of slices in the corner. * @param buffer the buffer the corner's xy coordinates are added to. */ protected void addRectangleRoundedCorner(float x, float y, float radius, float start, float sweep, int slices, - FloatBuffer buffer) - { - if (slices == 0f) + FloatBuffer buffer) { + if (slices == 0f) { return; + } float step = sweep / (float) slices; float angle = start + step; - for (int i = 1; i < slices; i++, angle += step) - { + for (int i = 1; i < slices; i++, angle += step) { buffer.put(x + (float) Math.cos(angle) * radius); buffer.put(y + (float) Math.sin(angle) * radius); } @@ -8403,49 +7535,42 @@ protected void addRectangleRoundedCorner(float x, float y, float radius, float s * depending on whether the leader is located to the left, right, bottom, or top of the rectangle. If the leader is * inside the rectangle, this returns LEADER_LOCATION_INSIDE. * - * @param x1 the rectangle's minimum x-coordinate. - * @param y1 the rectangle's maximum x-coordinate. - * @param x2 the rectangle's minimum y-coordinate. - * @param y2 the rectangle's maximum y-coordinate. + * @param x1 the rectangle's minimum x-coordinate. + * @param y1 the rectangle's maximum x-coordinate. + * @param x2 the rectangle's minimum y-coordinate. + * @param y2 the rectangle's maximum y-coordinate. * @param leaderX the leader's x-coordinate. * @param leaderY the leader's y-coordinate. * * @return a four bit code indicating the leader's location relative to the rectangle. */ - protected int computeLeaderLocationCode(float x1, float y1, float x2, float y2, float leaderX, float leaderY) - { - return (leaderY > y2 ? LEADER_LOCATION_TOP : 0) // bit 0: top - | (leaderY < y1 ? LEADER_LOCATION_BOTTOM : 0) // bit 1: bottom - | (leaderX > x2 ? LEADER_LOCATION_RIGHT : 0) // bit 2: right - | (leaderX < x1 ? LEADER_LOCATION_LEFT : 0); // bit 3: left + protected int computeLeaderLocationCode(float x1, float y1, float x2, float y2, float leaderX, float leaderY) { + return (leaderY > y2 ? LEADER_LOCATION_TOP : 0) // bit 0: top + | (leaderY < y1 ? LEADER_LOCATION_BOTTOM : 0) // bit 1: bottom + | (leaderX > x2 ? LEADER_LOCATION_RIGHT : 0) // bit 2: right + | (leaderX < x1 ? LEADER_LOCATION_LEFT : 0); // bit 3: left } //**************************************************************// //******************** Geometry Support ********************// //**************************************************************// - - public void reversePoints(int pos, int count, T[] points) - { - if (pos < 0) - { + public void reversePoints(int pos, int count, T[] points) { + if (pos < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "pos=" + pos); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (count < 0) - { + if (count < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "count=" + count); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (points == null) - { + if (points == null) { String message = "nullValue.PointsIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (points.length < (pos + count)) - { + if (points.length < (pos + count)) { String message = Logging.getMessage("generic.ArrayInvalidLength", "points.length < " + (pos + count)); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -8454,16 +7579,14 @@ public void reversePoints(int pos, int count, T[] points) T tmp; int i, j, mid; - for (i = 0, mid = count >> 1, j = count - 1; i < mid; i++, j--) - { + for (i = 0, mid = count >> 1, j = count - 1; i < mid; i++, j--) { tmp = points[pos + i]; points[pos + i] = points[pos + j]; points[pos + j] = tmp; } } - private int[] copyOf(int[] original, int newLength) - { + private int[] copyOf(int[] original, int newLength) { int[] copy; copy = new int[newLength]; @@ -8472,8 +7595,7 @@ private int[] copyOf(int[] original, int newLength) return copy; } - private float[] copyOf(float[] original, int newLength) - { + private float[] copyOf(float[] original, int newLength) { float[] copy; copy = new float[newLength]; @@ -8482,8 +7604,7 @@ private float[] copyOf(float[] original, int newLength) return copy; } - private IntBuffer copyOf(IntBuffer original, int newLength) - { + private IntBuffer copyOf(IntBuffer original, int newLength) { IntBuffer copy; copy = Buffers.newDirectIntBuffer(newLength); @@ -8493,8 +7614,7 @@ private IntBuffer copyOf(IntBuffer original, int newLength) return copy; } - private FloatBuffer copyOf(FloatBuffer original, int newLength) - { + private FloatBuffer copyOf(FloatBuffer original, int newLength) { FloatBuffer copy; copy = Buffers.newDirectFloatBuffer(newLength); @@ -8504,8 +7624,7 @@ private FloatBuffer copyOf(FloatBuffer original, int newLength) return copy; } - private void facenorm(float[] srcVerts, int vertA, int vertB, int vertC, float[] dest) - { + private void facenorm(float[] srcVerts, int vertA, int vertB, int vertC, float[] dest) { int ia, ib, ic; float[] ab, ac; @@ -8521,8 +7640,7 @@ private void facenorm(float[] srcVerts, int vertA, int vertB, int vertC, float[] this.norm3AndSet(dest, 0); } - private void facenorm(FloatBuffer srcVerts, int vertA, int vertB, int vertC, float[] dest) - { + private void facenorm(FloatBuffer srcVerts, int vertA, int vertB, int vertC, float[] dest) { int ia, ib, ic; float[] ab, ac; @@ -8538,67 +7656,57 @@ private void facenorm(FloatBuffer srcVerts, int vertA, int vertB, int vertC, flo this.norm3AndSet(dest, 0); } - private void add3AndSet(float[] a, int aPos, float[] b, int bPos) - { + private void add3AndSet(float[] a, int aPos, float[] b, int bPos) { a[aPos] = a[aPos] + b[bPos]; a[aPos + 1] = a[aPos + 1] + b[bPos + 1]; a[aPos + 2] = a[aPos + 2] + b[bPos + 2]; } - private void add3AndSet(FloatBuffer a, int aPos, float[] b, int bPos) - { + private void add3AndSet(FloatBuffer a, int aPos, float[] b, int bPos) { a.put(aPos, a.get(aPos) + b[bPos]); a.put(aPos + 1, a.get(aPos + 1) + b[bPos + 1]); a.put(aPos + 2, a.get(aPos + 2) + b[bPos + 2]); } - private void sub3(float[] a, int aPos, float[] b, int bPos, float[] dest, int destPos) - { + private void sub3(float[] a, int aPos, float[] b, int bPos, float[] dest, int destPos) { dest[destPos] = a[aPos] - b[bPos]; dest[destPos + 1] = a[aPos + 1] - b[bPos + 1]; dest[destPos + 2] = a[aPos + 2] - b[bPos + 2]; } - private void sub3(FloatBuffer a, int aPos, FloatBuffer b, int bPos, float[] dest, int destPos) - { + private void sub3(FloatBuffer a, int aPos, FloatBuffer b, int bPos, float[] dest, int destPos) { dest[destPos] = a.get(aPos) - b.get(bPos); dest[destPos + 1] = a.get(aPos + 1) - b.get(bPos + 1); dest[destPos + 2] = a.get(aPos + 2) - b.get(bPos + 2); } - private void cross3(float[] a, float[] b, float[] dest) - { + private void cross3(float[] a, float[] b, float[] dest) { dest[0] = a[1] * b[2] - a[2] * b[1]; dest[1] = a[2] * b[0] - a[0] * b[2]; dest[2] = a[0] * b[1] - a[1] * b[0]; } - private void mul3AndSet(float[] src, int srcPos, float c) - { + private void mul3AndSet(float[] src, int srcPos, float c) { src[srcPos] *= c; src[srcPos + 1] *= c; src[srcPos + 2] *= c; } - private void mul3AndSet(FloatBuffer src, int srcPos, float c) - { + private void mul3AndSet(FloatBuffer src, int srcPos, float c) { src.put(srcPos, src.get(srcPos) * c); src.put(srcPos + 1, src.get(srcPos + 1) * c); src.put(srcPos + 2, src.get(srcPos + 2) * c); } - private void mulAndSet(FloatBuffer src, int srcPos, float b, int offset) - { + private void mulAndSet(FloatBuffer src, int srcPos, float b, int offset) { src.put(srcPos + offset, src.get(srcPos + offset) * b); } - private void norm3AndSet(float[] src, int srcPos) - { + private void norm3AndSet(float[] src, int srcPos) { float len; len = src[srcPos] * src[srcPos] + src[srcPos + 1] * src[srcPos + 1] + src[srcPos + 2] * src[srcPos + 2]; - if (len != 0.0f) - { + if (len != 0.0f) { len = (float) Math.sqrt(len); src[srcPos] /= len; src[srcPos + 1] /= len; @@ -8606,15 +7714,13 @@ private void norm3AndSet(float[] src, int srcPos) } } - private void norm3AndSet(FloatBuffer src, int srcPos) - { + private void norm3AndSet(FloatBuffer src, int srcPos) { float len; len = src.get(srcPos) * src.get(srcPos) - + src.get(srcPos + 1) * src.get(srcPos + 1) - + src.get(srcPos + 2) * src.get(srcPos + 2); - if (len != 0.0f) - { + + src.get(srcPos + 1) * src.get(srcPos + 1) + + src.get(srcPos + 2) * src.get(srcPos + 2); + if (len != 0.0f) { len = (float) Math.sqrt(len); src.put(srcPos, src.get(srcPos) / len); src.put(srcPos + 1, src.get(srcPos + 1) / len); @@ -8622,22 +7728,19 @@ private void norm3AndSet(FloatBuffer src, int srcPos) } } - private int nextPowerOfTwo(int n) - { + private int nextPowerOfTwo(int n) { int i = 1; - while (i < n) - { + while (i < n) { i <<= 1; } return i; } private void append(Terrain terrain, LatLon ll, double altitude, boolean terrainConformant, Vec4 refPoint, - FloatBuffer dest) - { - Vec4 point = terrainConformant ? - terrain.getSurfacePoint(ll.latitude, ll.longitude, altitude) : - terrain.getGlobe().computePointFromPosition(ll.latitude, ll.longitude, altitude); + FloatBuffer dest) { + Vec4 point = terrainConformant + ? terrain.getSurfacePoint(ll.latitude, ll.longitude, altitude) + : terrain.getGlobe().computePointFromPosition(ll.latitude, ll.longitude, altitude); coord[0] = (float) (point.x - refPoint.x); coord[1] = (float) (point.y - refPoint.y); diff --git a/src/gov/nasa/worldwind/util/HTTPFileUpload.java b/src/gov/nasa/worldwind/util/HTTPFileUpload.java index 05c3b94af9..97f50ee995 100644 --- a/src/gov/nasa/worldwind/util/HTTPFileUpload.java +++ b/src/gov/nasa/worldwind/util/HTTPFileUpload.java @@ -3,14 +3,12 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; /** * @author Lado Garakanidze * @version $Id: HTTPFileUpload.java 1171 2013-02-11 21:45:02Z dcollins $ */ - import gov.nasa.worldwind.avlist.*; import gov.nasa.worldwind.exception.WWRuntimeException; @@ -20,9 +18,11 @@ import java.util.*; import java.util.logging.Level; -/** Synchronous file upload using HTTP POST as a multi-part form data */ -public class HTTPFileUpload extends java.util.Observable -{ +/** + * Synchronous file upload using HTTP POST as a multi-part form data + */ +public class HTTPFileUpload extends java.util.Observable { + protected static final String CR_LF = "\r\n"; protected static final String TWO_HYPHENS = "--"; protected static final String BOUNDARY = "*********NASA_World_Wind_HTTP_File_Upload_Separator**********"; @@ -40,24 +40,21 @@ public class HTTPFileUpload extends java.util.Observable protected int totalFilesUploaded = 0; protected int totalFilesFailed = 0; - protected class FileInfo - { + protected class FileInfo { + protected final String uploadName; protected final Object uploadItem; protected final AVList properties; - public FileInfo(String name, Object item, AVList properties) - { + public FileInfo(String name, Object item, AVList properties) { this.uploadName = name; this.uploadItem = item; this.properties = properties; } } - public HTTPFileUpload(URL url) - { - if (url == null) - { + public HTTPFileUpload(URL url) { + if (url == null) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -71,38 +68,31 @@ public HTTPFileUpload(URL url) this.setRequestProperty("Content-Transfer-Encoding", "binary"); } - public long getTotalFilesToUpload() - { + public long getTotalFilesToUpload() { return filesToUpload.size(); } - public long getTotalBytesToUpload() - { + public long getTotalBytesToUpload() { return totalBytesToUpload; } - public long getTotalBytesUploaded() - { + public long getTotalBytesUploaded() { return totalBytesUploaded; } - public int getTotalFilesUploaded() - { + public int getTotalFilesUploaded() { return totalFilesUploaded; } - public int getTotalFilesFailed() - { + public int getTotalFilesFailed() { return totalFilesFailed; } - public int getMaxBufferSize() - { + public int getMaxBufferSize() { return maxBufferSize; } - public void setMaxBufferSize(int maxBufferSize) - { + public void setMaxBufferSize(int maxBufferSize) { this.maxBufferSize = maxBufferSize; } @@ -111,14 +101,12 @@ public void setMaxBufferSize(int maxBufferSize) * * @param method POST or GET */ - public void setRequestMethod(String method) - { - if ("POST".equalsIgnoreCase(method)) + public void setRequestMethod(String method) { + if ("POST".equalsIgnoreCase(method)) { this.requestMethod = "POST"; - else if ("GET".equalsIgnoreCase(method)) + } else if ("GET".equalsIgnoreCase(method)) { this.requestMethod = "GET"; - else - { + } else { String message = Logging.getMessage("generic.UnknownValueForKey", method, "method={POST|GET}"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -130,15 +118,12 @@ else if ("GET".equalsIgnoreCase(method)) * * @return POST or GET */ - public String getRequestMethod() - { + public String getRequestMethod() { return this.requestMethod; } - public void setRequestProperty(String name, String value) - { - if (WWUtil.isEmpty(name)) - { + public void setRequestProperty(String name, String value) { + if (WWUtil.isEmpty(name)) { String message = Logging.getMessage("nullValue.PropertyNameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -162,25 +147,20 @@ public void setRequestProperty(String name, String value) // this.totalBytesToUpload += stringToUpload.length(); // this.filesToUpload.add(new FileInfo(name, stringToUpload, null)); // } - - public void add(ByteBuffer bufferToUpload, String name, AVList params) - { - if (bufferToUpload == null) - { + public void add(ByteBuffer bufferToUpload, String name, AVList params) { + if (bufferToUpload == null) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(name)) - { + if (WWUtil.isEmpty(name)) { String message = Logging.getMessage("nullValue.NameIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bufferToUpload.limit() == 0) - { + if (bufferToUpload.limit() == 0) { String message = Logging.getMessage("generic.BufferIsEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -193,40 +173,34 @@ public void add(ByteBuffer bufferToUpload, String name, AVList params) /** * Adds a file to the HTTP File Uploader. * - * @param file The file to upload, must exist - * @param name The desired name of the file + * @param file The file to upload, must exist + * @param name The desired name of the file * @param params AVList of parameters * * @throws FileNotFoundException if the file was not found or does not exist */ - public void add(File file, String name, AVList params) throws FileNotFoundException - { - if (null != file && file.exists()) - { + public void add(File file, String name, AVList params) throws FileNotFoundException { + if (null != file && file.exists()) { this.totalBytesToUpload += file.length(); this.filesToUpload.add(new FileInfo(name, file, params)); - } - else + } else { throw new FileNotFoundException((file != null) ? file.getName() : ""); + } } - public void send() throws Exception - { - for (FileInfo info : this.filesToUpload) - { - try - { - if (info.uploadItem instanceof File) + public void send() throws Exception { + for (FileInfo info : this.filesToUpload) { + try { + if (info.uploadItem instanceof File) { send((File) info.uploadItem, info.uploadName, info.properties); - else if (info.uploadItem instanceof ByteBuffer) + } else if (info.uploadItem instanceof ByteBuffer) { send((ByteBuffer) info.uploadItem, info.uploadName, info.properties); - else if (info.uploadItem instanceof String) + } else if (info.uploadItem instanceof String) { send((String) info.uploadItem, info.uploadName, info.properties); + } this.totalFilesUploaded++; - } - catch (Exception e) - { + } catch (Exception e) { this.totalFilesFailed++; String reason = WWUtil.extractExceptionReason(e); @@ -239,13 +213,12 @@ else if (info.uploadItem instanceof String) } protected void send(File fileToUpload, String uploadName, AVList params) - throws IOException, NullPointerException - { - if (null == fileToUpload || !fileToUpload.exists()) + throws IOException, NullPointerException { + if (null == fileToUpload || !fileToUpload.exists()) { throw new FileNotFoundException(); + } - if (null == url) - { + if (null == url) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -257,8 +230,7 @@ protected void send(File fileToUpload, String uploadName, AVList params) int bytesRead, bytesAvailable, bufferSize; - try - { + try { conn = (HttpURLConnection) this.url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs @@ -280,8 +252,7 @@ protected void send(File fileToUpload, String uploadName, AVList params) // read file and write it into form... bytesRead = fis.read(buffer, 0, bufferSize); - while (bytesRead > 0) - { + while (bytesRead > 0) { dos.write(buffer, 0, bytesRead); this.totalBytesUploaded += (long) bytesRead; @@ -296,75 +267,58 @@ protected void send(File fileToUpload, String uploadName, AVList params) dos.flush(); this.handleResponse(conn); - } - finally - { + } finally { WWIO.closeStream(fis, null); WWIO.closeStream(dos, null); this.disconnect(conn, this.url.toString()); } } - protected void handleResponse(HttpURLConnection conn) throws IOException - { - if (null != conn) - { + protected void handleResponse(HttpURLConnection conn) throws IOException { + if (null != conn) { int code = conn.getResponseCode(); String message = conn.getResponseMessage(); - if (code != 200) - { + if (code != 200) { String reason = "(" + code + ") :" + message; throw new IOException(reason); } - } - else - { + } else { throw new IOException(Logging.getMessage("nullValue.ConnectionIsNull")); } } - protected void disconnect(HttpURLConnection conn, String name) - { - if (null != conn) - { - try - { + protected void disconnect(HttpURLConnection conn, String name) { + if (null != conn) { + try { conn.disconnect(); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("WWIO.ErrorTryingToClose", name); Logging.logger().log(Level.WARNING, message, e); } } } - protected void send(ByteBuffer bufferToUpload, String fileName, AVList params) throws IOException - { - if (null == bufferToUpload) - { + protected void send(ByteBuffer bufferToUpload, String fileName, AVList params) throws IOException { + if (null == bufferToUpload) { String message = Logging.getMessage("nullValue.ByteBufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bufferToUpload.limit() == 0) - { + if (bufferToUpload.limit() == 0) { String message = Logging.getMessage("generic.BufferIsEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == url) - { + if (null == url) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(fileName)) - { + if (WWUtil.isEmpty(fileName)) { String message = Logging.getMessage("nullValue.FilenameIsNullOrEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -373,8 +327,7 @@ protected void send(ByteBuffer bufferToUpload, String fileName, AVList params) t HttpURLConnection conn = null; DataOutputStream dos = null; - try - { + try { conn = (HttpURLConnection) this.url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); @@ -394,8 +347,7 @@ protected void send(ByteBuffer bufferToUpload, String fileName, AVList params) t // Send buffer to server bufferToUpload.rewind(); - while (bufferToUpload.hasRemaining()) - { + while (bufferToUpload.hasRemaining()) { int bytesToRead = Math.min(bufferToUpload.remaining(), maxBufferSize); bufferToUpload.get(buffer, 0, bytesToRead); dos.write(buffer, 0, bytesToRead); @@ -408,32 +360,26 @@ protected void send(ByteBuffer bufferToUpload, String fileName, AVList params) t dos.flush(); this.handleResponse(conn); - } - finally - { + } finally { WWIO.closeStream(dos, null); this.disconnect(conn, this.url.toString()); } } - protected void send(String stringToUpload, String fileName, AVList params) throws IOException - { - if (WWUtil.isEmpty(stringToUpload)) - { + protected void send(String stringToUpload, String fileName, AVList params) throws IOException { + if (WWUtil.isEmpty(stringToUpload)) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == url) - { + if (null == url) { String message = Logging.getMessage("nullValue.URLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (WWUtil.isEmpty(fileName)) - { + if (WWUtil.isEmpty(fileName)) { String message = Logging.getMessage("nullValue.FilenameIsNullOrEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -442,8 +388,7 @@ protected void send(String stringToUpload, String fileName, AVList params) throw HttpURLConnection conn = null; DataOutputStream dos = null; - try - { + try { conn = (HttpURLConnection) this.url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); @@ -465,20 +410,15 @@ protected void send(String stringToUpload, String fileName, AVList params) throw dos.flush(); this.handleResponse(conn); - } - finally - { + } finally { WWIO.closeStream(dos, null); this.disconnect(conn, this.url.toString()); } } - protected void writeProperties(DataOutputStream dos, AVList params) throws IOException - { - if (null != dos && null != params) - { - for (Map.Entry param : params.getEntries()) - { + protected void writeProperties(DataOutputStream dos, AVList params) throws IOException { + if (null != dos && null != params) { + for (Map.Entry param : params.getEntries()) { String name = param.getKey(); String value = AVListImpl.getStringValue(params, name, ""); this.writeContentDisposition(dos, name, value); @@ -493,22 +433,17 @@ protected void writeProperties(DataOutputStream dos, AVList params) throws IOExc * * @throws IOException if there is any problem with a connection */ - protected void writeRequestProperties(HttpURLConnection conn) throws IOException - { - if (null != conn) - { + protected void writeRequestProperties(HttpURLConnection conn) throws IOException { + if (null != conn) { conn.setRequestMethod(this.getRequestMethod()); - for (Map.Entry requestProperty : this.requestProperties.getEntries()) - { + for (Map.Entry requestProperty : this.requestProperties.getEntries()) { conn.setRequestProperty(requestProperty.getKey(), (String) requestProperty.getValue()); } } } - protected void writeContentDisposition(DataOutputStream dos, String filename) throws IOException - { - if (null != dos) - { + protected void writeContentDisposition(DataOutputStream dos, String filename) throws IOException { + if (null != dos) { dos.writeBytes(TWO_HYPHENS + BOUNDARY + CR_LF); dos.writeBytes("Content-Disposition: attachment; filename=\"" + filename + "\"" + CR_LF); dos.writeBytes("Content-type: application/octet-stream" + CR_LF); @@ -516,30 +451,25 @@ protected void writeContentDisposition(DataOutputStream dos, String filename) th } } - protected void writeContentDisposition(DataOutputStream dos, String paramName, String paramValue) throws IOException - { - if (null != dos && null != paramName) - { + protected void writeContentDisposition(DataOutputStream dos, String paramName, String paramValue) throws IOException { + if (null != dos && null != paramName) { dos.writeBytes(TWO_HYPHENS + BOUNDARY + CR_LF); dos.writeBytes("Content-Disposition: form-data; name=\"" + paramName + "\"" + CR_LF); dos.writeBytes(CR_LF + paramValue + CR_LF); } } - protected void writeContentSeparator(DataOutputStream dos) throws IOException - { - if (null != dos) - { + protected void writeContentSeparator(DataOutputStream dos) throws IOException { + if (null != dos) { // send multipart form data necesssary after file data... dos.writeBytes(CR_LF + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + CR_LF); } } - protected void notifyProgress() - { + protected void notifyProgress() { double progress = (double) 100 * (double) this.totalBytesUploaded / (double) this.totalBytesToUpload; this.setChanged(); this.notifyObservers(new Float(progress)); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/HotSpot.java b/src/gov/nasa/worldwind/util/HotSpot.java index 230a0800b5..b75563c6de 100644 --- a/src/gov/nasa/worldwind/util/HotSpot.java +++ b/src/gov/nasa/worldwind/util/HotSpot.java @@ -17,12 +17,13 @@ * @author dcollins * @version $Id: HotSpot.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface HotSpot extends SelectListener, KeyListener, MouseListener, MouseMotionListener, MouseWheelListener -{ +public interface HotSpot extends SelectListener, KeyListener, MouseListener, MouseMotionListener, MouseWheelListener { + /** * Called when this HotSpot is activated or deactivated. The HotSpot only receives input events when it is active. * - * @param active {@code true} if this HotSpot is being activated. {@code false} if this HotSpot is being deactivated. + * @param active {@code true} if this HotSpot is being activated. {@code false} if this HotSpot is being + * deactivated. */ void setActive(boolean active); diff --git a/src/gov/nasa/worldwind/util/ImageInterpolator.java b/src/gov/nasa/worldwind/util/ImageInterpolator.java index 1cbee6a1a3..7f4981c6b6 100644 --- a/src/gov/nasa/worldwind/util/ImageInterpolator.java +++ b/src/gov/nasa/worldwind/util/ImageInterpolator.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.cache.*; @@ -17,55 +16,51 @@ * @author tag * @version $Id: ImageInterpolator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ImageInterpolator -{ - protected static class Cell implements Cacheable - { +public class ImageInterpolator { + + protected static class Cell implements Cacheable { + protected final int m0, m1, n0, n1; protected float minx, maxx, miny, maxy; protected Cell[] children; - public Cell(int m0, int m1, int n0, int n1) - { + public Cell(int m0, int m1, int n0, int n1) { this.m0 = m0; this.m1 = m1; this.n0 = n0; this.n1 = n1; } - protected Cell makeChildCell(int m0, int m1, int n0, int n1) - { + protected Cell makeChildCell(int m0, int m1, int n0, int n1) { return new Cell(m0, m1, n0, n1); } - public long getSizeInBytes() - { + public long getSizeInBytes() { return 13 * 4; } - public void build(int numLevels, int cellSize) - { - if (numLevels == 0) + public void build(int numLevels, int cellSize) { + if (numLevels == 0) { return; + } - if (this.m1 - this.m0 <= cellSize && this.n1 - this.n0 <= cellSize) + if (this.m1 - this.m0 <= cellSize && this.n1 - this.n0 <= cellSize) { return; + } this.children = this.split(this.m0, this.m1, this.n0, this.n1); - for (Cell t : this.children) - { + for (Cell t : this.children) { t.build(numLevels - 1, cellSize); } } - public Cell[] split(int mm0, int mm1, int nn0, int nn1) - { + public Cell[] split(int mm0, int mm1, int nn0, int nn1) { int mma = (mm1 - mm0 > 1 ? mm0 + (mm1 - mm0) / 2 : mm0 + 1); int nna = (nn1 - nn0 > 1 ? nn0 + (nn1 - nn0) / 2 : nn0 + 1); int mmb = mm1 - mm0 > 1 ? mma : mm0; int nnb = nn1 - nn0 > 1 ? nna : nn0; - return new Cell[] { + return new Cell[]{ this.makeChildCell(mm0, mma, nn0, nna), this.makeChildCell(mmb, mm1, nn0, nna), this.makeChildCell(mm0, mma, nnb, nn1), @@ -73,90 +68,87 @@ public Cell[] split(int mm0, int mm1, int nn0, int nn1) }; } - public boolean intersects(float x, float y) - { + public boolean intersects(float x, float y) { return x >= this.minx && x <= this.maxx && y >= this.miny && y <= this.maxy; } - - public void computeBounds(Dimension dim, float[] xs, float[] ys) - { - if (this.children != null) - { - for (Cell t : this.children) - { + + public void computeBounds(Dimension dim, float[] xs, float[] ys) { + if (this.children != null) { + for (Cell t : this.children) { t.computeBounds(dim, xs, ys); } this.computeExtremesFromChildren(); - } - else - { + } else { this.computeExtremesFromLocations(dim, xs, ys); } } - protected void computeExtremesFromLocations(Dimension dim, float[] xs, float[] ys) - { + protected void computeExtremesFromLocations(Dimension dim, float[] xs, float[] ys) { this.minx = Float.MAX_VALUE; this.maxx = -Float.MAX_VALUE; this.miny = Float.MAX_VALUE; this.maxy = -Float.MAX_VALUE; - for (int j = this.n0; j <= this.n1; j++) - { - for (int i = this.m0; i <= this.m1; i++) - { + for (int j = this.n0; j <= this.n1; j++) { + for (int i = this.m0; i <= this.m1; i++) { int k = j * dim.width + i; float x = xs[k]; float y = ys[k]; - if (x < this.minx) + if (x < this.minx) { this.minx = x; - if (x > this.maxx) + } + if (x > this.maxx) { this.maxx = x; + } - if (y < this.miny) + if (y < this.miny) { this.miny = y; - if (y > this.maxy) + } + if (y > this.maxy) { this.maxy = y; + } } } } - protected void computeExtremesFromChildren() - { + protected void computeExtremesFromChildren() { this.minx = Float.MAX_VALUE; this.maxx = -Float.MAX_VALUE; this.miny = Float.MAX_VALUE; this.maxy = -Float.MAX_VALUE; - if (this.children == null) + if (this.children == null) { return; + } - for (Cell t : children) - { - if (t.minx < this.minx) + for (Cell t : children) { + if (t.minx < this.minx) { this.minx = t.minx; - if (t.maxx > this.maxx) + } + if (t.maxx > this.maxx) { this.maxx = t.maxx; + } - if (t.miny < this.miny) + if (t.miny < this.miny) { this.miny = t.miny; - if (t.maxy > this.maxy) + } + if (t.maxy > this.maxy) { this.maxy = t.maxy; + } } } } - public static class ContainingCell - { + public static class ContainingCell { + public final int m0, m1, n0, n1; public final float minx, maxx, miny, maxy; public final double[] uv; public final int[] fieldIndices; - private ContainingCell(Cell cell, double uv[], int[] fieldIndices) - { + private ContainingCell(Cell cell, double uv[], int[] fieldIndices) { this.uv = uv; this.m0 = cell.m0; @@ -180,39 +172,33 @@ private ContainingCell(Cell cell, double uv[], int[] fieldIndices) protected final int cellSize; protected final BasicMemoryCache kidCache = new BasicMemoryCache(750000L, 1000000L); - public ImageInterpolator(Dimension gridSize, float[] xs, float[] ys, int depth, int cellSize) - { - if (gridSize == null) - { + public ImageInterpolator(Dimension gridSize, float[] xs, float[] ys, int depth, int cellSize) { + if (gridSize == null) { String message = Logging.getMessage("nullValue.DimensionIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (gridSize.width < 2 || gridSize.height < 2) - { + if (gridSize.width < 2 || gridSize.height < 2) { String message = Logging.getMessage("generic.DimensionsTooSmall"); Logging.logger().log(java.util.logging.Level.SEVERE, message, - new Object[] {gridSize.width, gridSize.height}); + new Object[]{gridSize.width, gridSize.height}); throw new IllegalStateException(message); } - if (xs == null || ys == null || xs.length < 4 || ys.length < 4) - { + if (xs == null || ys == null || xs.length < 4 || ys.length < 4) { String message = Logging.getMessage("Grid.ArraysInvalid"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (depth < 0) - { + if (depth < 0) { String message = Logging.getMessage("Grid.DepthInvalid"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (cellSize < 1) - { + if (cellSize < 1) { String message = Logging.getMessage("Grid.CellSizeInvalid"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -229,73 +215,68 @@ public ImageInterpolator(Dimension gridSize, float[] xs, float[] ys, int depth, this.root.computeBounds(this.gridSize, this.xs, this.ys); } - protected Cell makeRootCell(int m0, int m1, int n0, int n1) - { + protected Cell makeRootCell(int m0, int m1, int n0, int n1) { return new Cell(m0, m1, n0, n1); } - public ContainingCell findContainingCell(float x, float y) - { + public ContainingCell findContainingCell(float x, float y) { return this.findContainingCell(this.root, x, y); } - protected ContainingCell findContainingCell(Cell cell, float x, float y) - { - if (!cell.intersects(x, y)) + protected ContainingCell findContainingCell(Cell cell, float x, float y) { + if (!cell.intersects(x, y)) { return null; + } - if (cell.m1 - cell.m0 <= this.cellSize && cell.n1 - cell.n0 <= this.cellSize) + if (cell.m1 - cell.m0 <= this.cellSize && cell.n1 - cell.n0 <= this.cellSize) { return this.checkContainment(x, y, cell); + } Cell[] kids = cell.children != null ? cell.children : (Cell[]) this.kidCache.getObject(cell); - if (kids == null) - { + if (kids == null) { kids = cell.split(cell.m0, cell.m1, cell.n0, cell.n1); - for (Cell child : kids) - { + for (Cell child : kids) { child.computeExtremesFromLocations(this.gridSize, this.xs, this.ys); } - if (cell.children == null) + if (cell.children == null) { this.kidCache.add(cell, kids, 4 * kids[0].getSizeInBytes()); + } } - for (Cell t : kids) - { + for (Cell t : kids) { ContainingCell cellFound = this.findContainingCell(t, x, y); - if (cellFound != null) + if (cellFound != null) { return cellFound; + } } return null; } - protected ContainingCell checkContainment(float x, float y, Cell cell) - { + protected ContainingCell checkContainment(float x, float y, Cell cell) { double[] uv = this.computeBilinearCoordinates(x, y, cell); return uv != null - && uv[0] <= 1 && uv[1] <= 1 && uv[0] >= 0 && uv[1] >= 0 - ? new ContainingCell(cell, uv, getFieldIndices(cell)) : null; + && uv[0] <= 1 && uv[1] <= 1 && uv[0] >= 0 && uv[1] >= 0 + ? new ContainingCell(cell, uv, getFieldIndices(cell)) : null; } - protected double[] computeBilinearCoordinates(float x, float y, Cell cell) - { + protected double[] computeBilinearCoordinates(float x, float y, Cell cell) { int i = index(cell.m0, cell.n0); int j = index(cell.m1, cell.n0); int k = index(cell.m1, cell.n1); int l = index(cell.m0, cell.n1); return BarycentricQuadrilateral.invertBilinear( - new Vec4(x, y, 0), - new Vec4(this.xs[i], this.ys[i], 0), - new Vec4(this.xs[j], this.ys[j], 0), - new Vec4(this.xs[k], this.ys[k], 0), - new Vec4(this.xs[l], this.ys[l], 0)); + new Vec4(x, y, 0), + new Vec4(this.xs[i], this.ys[i], 0), + new Vec4(this.xs[j], this.ys[j], 0), + new Vec4(this.xs[k], this.ys[k], 0), + new Vec4(this.xs[l], this.ys[l], 0)); } - protected int[] getFieldIndices(Cell cell) - { - return new int[] { + protected int[] getFieldIndices(Cell cell) { + return new int[]{ index(cell.m0, cell.n0), index(cell.m1, cell.n0), index(cell.m1, cell.n1), @@ -303,8 +284,7 @@ protected int[] getFieldIndices(Cell cell) }; } - private int index(int i, int j) - { + private int index(int i, int j) { return j * this.gridSize.width + i; } } diff --git a/src/gov/nasa/worldwind/util/ImageTiler.java b/src/gov/nasa/worldwind/util/ImageTiler.java index 8bbb765129..73d7dd2636 100644 --- a/src/gov/nasa/worldwind/util/ImageTiler.java +++ b/src/gov/nasa/worldwind/util/ImageTiler.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.geom.*; @@ -25,41 +24,35 @@ * @author tag * @version $Id: ImageTiler.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ImageTiler -{ +public class ImageTiler { + public static int DEFAULT_IMAGE_TILE_SIZE = 2048; // default size to make subimages private int tileWidth = DEFAULT_IMAGE_TILE_SIZE; private int tileHeight = DEFAULT_IMAGE_TILE_SIZE; private Color transparencyColor = new Color(0, 0, 0, 0); - public int getTileWidth() - { + public int getTileWidth() { return tileWidth; } - public void setTileWidth(int tileWidth) - { + public void setTileWidth(int tileWidth) { this.tileWidth = tileWidth; } - public int getTileHeight() - { + public int getTileHeight() { return tileHeight; } - public void setTileHeight(int tileHeight) - { + public void setTileHeight(int tileHeight) { this.tileHeight = tileHeight; } - public Color getTransparencyColor() - { + public Color getTransparencyColor() { return transparencyColor; } - public void setTransparencyColor(Color transparencyColor) - { + public void setTransparencyColor(Color transparencyColor) { this.transparencyColor = transparencyColor; } @@ -68,45 +61,39 @@ public void setTransparencyColor(Color transparencyColor) * Sector} rather than a quadrilateral or other shape. Conveys each tile created to the caller via a listener * callback. * - * @param baseImage the image to tile. + * @param baseImage the image to tile. * @param baseSector the sector defining the geographic extent of the base image. - * @param listener the listener to invoke when each new tile is created. + * @param listener the listener to invoke when each new tile is created. * * @see ImageTilerListener */ - public void tileImage(BufferedImage baseImage, Sector baseSector, ImageTilerListener listener) - { - if (baseImage == null) - { + public void tileImage(BufferedImage baseImage, Sector baseSector, ImageTilerListener listener) { + if (baseImage == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (baseSector == null) - { + if (baseSector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (baseImage.getWidth() <= 0 || baseImage.getHeight() <= 0) - { + if (baseImage.getWidth() <= 0 || baseImage.getHeight() <= 0) { String message = Logging.getMessage("generic.InvalidImageSize"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (listener == null) - { + if (listener == null) { String message = Logging.getMessage("nullValue.ListenerIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Just return the input image if it's already the desired subimage size - if (baseImage.getWidth() == this.getTileWidth() && baseImage.getHeight() == this.getTileHeight()) - { + if (baseImage.getWidth() == this.getTileWidth() && baseImage.getHeight() == this.getTileHeight()) { listener.newTile(baseImage, baseSector); return; } @@ -119,8 +106,7 @@ public void tileImage(BufferedImage baseImage, Sector baseSector, ImageTilerList int rows = (int) Math.ceil((double) N / b); boolean hasAlpha = baseImage.getColorModel().hasAlpha(); - for (int j = 0; j < rows; j++) - { + for (int j = 0; j < rows; j++) { int y = j * b; int h = y + b <= N ? b : N - y; @@ -129,32 +115,29 @@ public void tileImage(BufferedImage baseImage, Sector baseSector, ImageTilerList Angle minLat = baseSector.getMaxLatitude().subtract(baseSector.getDeltaLat().multiply(t0)); Angle maxLat = baseSector.getMaxLatitude().subtract(baseSector.getDeltaLat().multiply(t1)); - for (int i = 0; i < cols; i++) - { + for (int i = 0; i < cols; i++) { int x = i * a; int w = x + a <= M ? a : M - x; BufferedImage image; - if (w == this.getTileWidth() && h == this.getTileHeight()) - { + if (w == this.getTileWidth() && h == this.getTileHeight()) { // The source image fills this tile entirely, - if (!hasAlpha) - { + if (!hasAlpha) { // If the source image does not have an alpha channel, create a tile with no alpha channel. image = new BufferedImage(this.getTileWidth(), this.getTileHeight(), - BufferedImage.TYPE_3BYTE_BGR); - if (!ImageUtil.isCompatibleImage(image)) + BufferedImage.TYPE_3BYTE_BGR); + if (!ImageUtil.isCompatibleImage(image)) { image = ImageUtil.toCompatibleImage(image); + } Graphics2D g = image.createGraphics(); g.drawImage(baseImage.getSubimage(x, y, w, h), 0, 0, w, h, null); - } - else - { + } else { // The source image has an alpha channel, create a tile with an alpha channel. image = new BufferedImage(this.getTileWidth(), this.getTileHeight(), - BufferedImage.TYPE_4BYTE_ABGR); - if (!ImageUtil.isCompatibleImage(image)) + BufferedImage.TYPE_4BYTE_ABGR); + if (!ImageUtil.isCompatibleImage(image)) { image = ImageUtil.toCompatibleImage(image); + } Graphics2D g = image.createGraphics(); g.setBackground(this.transparencyColor); g.clearRect(0, 0, image.getWidth(), image.getHeight()); @@ -169,16 +152,15 @@ public void tileImage(BufferedImage baseImage, Sector baseSector, ImageTilerList // System.out.println(new Sector(minLat, maxLat, minLon, maxLon)); listener.newTile(image, new Sector(minLat, maxLat, minLon, maxLon)); - } - else - { + } else { // The source image does not fill this tile, so create a smaller tile with an alpha channel. int shortWidth = w == this.getTileWidth() ? this.getTileWidth() : WWMath.powerOfTwoCeiling(w); int shortheight = h == this.getTileHeight() ? this.getTileHeight() : WWMath.powerOfTwoCeiling(h); image = new BufferedImage(shortWidth, shortheight, BufferedImage.TYPE_4BYTE_ABGR); - if (!ImageUtil.isCompatibleImage(image)) + if (!ImageUtil.isCompatibleImage(image)) { image = ImageUtil.toCompatibleImage(image); + } Graphics2D g = image.createGraphics(); g.setBackground(this.transparencyColor); g.clearRect(0, 0, image.getWidth(), image.getHeight()); @@ -201,60 +183,52 @@ public void tileImage(BufferedImage baseImage, Sector baseSector, ImageTilerList } } - public void tileImage(BufferedImage image, java.util.List corners,ImageTilerListener listener) - { - if (image == null) - { + public void tileImage(BufferedImage image, java.util.List corners, ImageTilerListener listener) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (corners == null) - { + if (corners == null) { String message = Logging.getMessage("nullValue.LocationsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (image.getWidth() <= 0 || image.getHeight() <= 0) - { + if (image.getWidth() <= 0 || image.getHeight() <= 0) { String message = Logging.getMessage("generic.InvalidImageSize"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (listener == null) - { + if (listener == null) { String message = Logging.getMessage("nullValue.ListenerIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Just return the input image if it's already the desired subimage size - if (image.getWidth() == this.getTileWidth() && image.getHeight() == this.getTileHeight()) - { + if (image.getWidth() == this.getTileWidth() && image.getHeight() == this.getTileHeight()) { listener.newTile(image, corners); return; } // Count the corners and check for nulls int numCorners = 0; - for (LatLon c : corners) - { - if (c == null) - { + for (LatLon c : corners) { + if (c == null) { String message = Logging.getMessage("nullValue.LocationInListIsNull"); Logging.logger().log(Level.SEVERE, message); throw new IllegalArgumentException(message); } - if (++numCorners > 3) + if (++numCorners > 3) { break; + } } - if (numCorners < 4) - { + if (numCorners < 4) { String message = Logging.getMessage("nullValue.LocationInListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -270,8 +244,7 @@ public void tileImage(BufferedImage image, java.util.List corn int rows = (int) Math.ceil((double) N / b); boolean hasAlpha = image.getColorModel().hasAlpha(); - for (int j = 0; j < rows; j++) - { + for (int j = 0; j < rows; j++) { LatLon se, sw, ne, nw; int y = j * b; @@ -280,31 +253,26 @@ public void tileImage(BufferedImage image, java.util.List corn double t0 = 1d - (double) (y + this.getTileHeight()) / N; double t1 = 1d - (double) y / N; - for (int i = 0; i < cols; i++) - { + for (int i = 0; i < cols; i++) { int x = i * a; int w = x + a <= M ? a : M - x; BufferedImage subImage; - if (w == this.getTileWidth() && h == this.getTileHeight()) - { + if (w == this.getTileWidth() && h == this.getTileHeight()) { // The source image fills this tile entirely, - if (!hasAlpha) - { + if (!hasAlpha) { // If the source image does not have an alpha channel, create a tile with no alpha channel. subImage = new BufferedImage(this.getTileWidth(), this.getTileHeight(), - BufferedImage.TYPE_3BYTE_BGR); + BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = subImage.createGraphics(); g.drawImage(image.getSubimage(x, y, w, h), 0, 0, w, h, null); - + continue; - } - else - { + } else { // The source image has an alpha channel, create a tile with an alpha channel. subImage = new BufferedImage(this.getTileWidth(), this.getTileHeight(), - BufferedImage.TYPE_4BYTE_ABGR); + BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g = subImage.createGraphics(); g.setBackground(this.transparencyColor); g.clearRect(0, 0, subImage.getWidth(), subImage.getHeight()); @@ -319,9 +287,7 @@ public void tileImage(BufferedImage image, java.util.List corn se = geoQuad.interpolate(t0, s1); ne = geoQuad.interpolate(t1, s1); nw = geoQuad.interpolate(t1, s0); - } - else - { + } else { // The source image does not fill this tile, so create a smaller tile with an alpha channel. int shortWidth = w == this.getTileWidth() ? this.getTileWidth() : WWMath.powerOfTwoCeiling(w); int shortheight = h == this.getTileHeight() ? this.getTileHeight() : WWMath.powerOfTwoCeiling(h); @@ -347,14 +313,13 @@ public void tileImage(BufferedImage image, java.util.List corn // System.out.printf("%d: (%d, %d) : SW %s; SE %s; NE %s; NW %s\n", // System.currentTimeMillis(), x, y, sw, se, ne, nw); - - listener.newTile(subImage, Arrays.asList(sw,se, ne, nw)); + listener.newTile(subImage, Arrays.asList(sw, se, ne, nw)); } } } - public abstract static class ImageTilerListener - { + public abstract static class ImageTilerListener { + public abstract void newTile(BufferedImage tileImage, Sector tileSector); public abstract void newTile(BufferedImage tileImage, List corners); diff --git a/src/gov/nasa/worldwind/util/ImageTrimmer.java b/src/gov/nasa/worldwind/util/ImageTrimmer.java index 924a74bf88..e7b3946325 100644 --- a/src/gov/nasa/worldwind/util/ImageTrimmer.java +++ b/src/gov/nasa/worldwind/util/ImageTrimmer.java @@ -3,40 +3,32 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import java.awt.image.*; import java.io.*; import javax.imageio.ImageIO; -public class ImageTrimmer -{ - public static void main(String[] args) - { - if (args == null || args.length == 0) - { +public class ImageTrimmer { + + public static void main(String[] args) { + if (args == null || args.length == 0) { return; } - for (String path : args) - { - try - { + for (String path : args) { + try { System.out.print("Trimming " + path + " ... "); trimImageInPlace(new File(path)); System.out.print("success"); System.out.println(); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } } - public static void trimImageInPlace(File file) throws IOException - { + public static void trimImageInPlace(File file) throws IOException { BufferedImage originalImage = ImageIO.read(file); BufferedImage trimmedImage = ImageUtil.trimImage(originalImage); ImageIO.write(trimmedImage, WWIO.getSuffix(file.getPath()), file); diff --git a/src/gov/nasa/worldwind/util/ImageUtil.java b/src/gov/nasa/worldwind/util/ImageUtil.java index 8778c2dbba..b7be34167d 100644 --- a/src/gov/nasa/worldwind/util/ImageUtil.java +++ b/src/gov/nasa/worldwind/util/ImageUtil.java @@ -29,8 +29,8 @@ * @author tag * @version $Id: ImageUtil.java 1353 2013-05-20 18:43:06Z tgaskins $ */ -public class ImageUtil -{ +public class ImageUtil { + public static int NEAREST_NEIGHBOR_INTERPOLATION = 1; public static int BILINEAR_INTERPOLATION = 2; public static int IMAGE_TILE_SIZE = 1024; // default size to make subimages @@ -40,36 +40,30 @@ public class ImageUtil * Draws the specified image onto the canvas, scaling or stretching the image to fit the * canvas. This will apply a bilinear filter to the image if any scaling or stretching is necessary. * - * @param image the BufferedImage to draw, potentially scaling or stretching to fit the canvas. + * @param image the BufferedImage to draw, potentially scaling or stretching to fit the canvas. * @param canvas the BufferedImage to receive the scaled or stretched image. * * @throws IllegalArgumentException if either image or canvas is null. */ - public static void getScaledCopy(BufferedImage image, BufferedImage canvas) - { - if (image == null) - { + public static void getScaledCopy(BufferedImage image, BufferedImage canvas) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (canvas == null) - { + if (canvas == null) { String message = Logging.getMessage("nullValue.CanvasIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } java.awt.Graphics2D g2d = canvas.createGraphics(); - try - { + try { g2d.setComposite(java.awt.AlphaComposite.Src); g2d.setRenderingHint( - java.awt.RenderingHints.KEY_INTERPOLATION, java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR); + java.awt.RenderingHints.KEY_INTERPOLATION, java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(image, 0, 0, canvas.getWidth(), canvas.getHeight(), null); - } - finally - { + } finally { g2d.dispose(); } } @@ -77,29 +71,25 @@ public static void getScaledCopy(BufferedImage image, BufferedImage canvas) /** * Rasterizes the image into the canvas, given a transform that maps canvas coordinates to image coordinates. * - * @param image the source image. - * @param canvas the image to receive the transformed source image. + * @param image the source image. + * @param canvas the image to receive the transformed source image. * @param canvasToImageTransform Matrix that maps a canvas coordinates to image coordinates. * - * @throws IllegalArgumentException if any of image, canvas, or canvasToImageTransform - * are null. + * @throws IllegalArgumentException if any of image, canvas, or + * canvasToImageTransform are null. */ - public static void warpImageWithTransform(BufferedImage image, BufferedImage canvas, Matrix canvasToImageTransform) - { - if (image == null) - { + public static void warpImageWithTransform(BufferedImage image, BufferedImage canvas, Matrix canvasToImageTransform) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (canvas == null) - { + if (canvas == null) { String message = Logging.getMessage("nullValue.CanvasIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (canvasToImageTransform == null) - { + if (canvasToImageTransform == null) { String message = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -110,13 +100,10 @@ public static void warpImageWithTransform(BufferedImage image, BufferedImage can int destWidth = canvas.getWidth(); int destHeight = canvas.getHeight(); - for (int dy = 0; dy < destHeight; dy++) - { - for (int dx = 0; dx < destWidth; dx++) - { + for (int dy = 0; dy < destHeight; dy++) { + for (int dx = 0; dx < destWidth; dx++) { Vec4 vec = new Vec4(dx, dy, 1).transformBy3(canvasToImageTransform); - if (vec.x >= 0 && vec.y >= 0 && vec.x <= (sourceWidth - 1) && vec.y <= (sourceHeight - 1)) - { + if (vec.x >= 0 && vec.y >= 0 && vec.x <= (sourceWidth - 1) && vec.y <= (sourceHeight - 1)) { int x0 = (int) Math.floor(vec.x); int x1 = (int) Math.ceil(vec.x); double xf = vec.x - x0; @@ -126,10 +113,10 @@ public static void warpImageWithTransform(BufferedImage image, BufferedImage can double yf = vec.y - y0; int color = interpolateColor(xf, yf, - image.getRGB(x0, y0), - image.getRGB(x1, y0), - image.getRGB(x0, y1), - image.getRGB(x1, y1)); + image.getRGB(x0, y0), + image.getRGB(x1, y0), + image.getRGB(x0, y1), + image.getRGB(x1, y1)); canvas.setRGB(dx, dy, color); } } @@ -144,42 +131,36 @@ public static void warpImageWithTransform(BufferedImage image, BufferedImage can * * @param sourceImage the source image to transform. * @param imagePoints three or four control points in the source image. - * @param geoPoints three or four geographic locations corresponding to each source control point. - * @param destImage the destination image to receive the transformed source imnage. + * @param geoPoints three or four geographic locations corresponding to each source control point. + * @param destImage the destination image to receive the transformed source imnage. * * @return bounding sector for the geographically aligned destination image. * * @throws IllegalArgumentException if any of sourceImage, destImage, - * imagePoints or geoPoints is null, or if either - * imagePoints or geoPoints have length less than 3. + * imagePoints or geoPoints is null, or if either imagePoints or + * geoPoints have length less than 3. */ public static Sector warpImageWithControlPoints(BufferedImage sourceImage, java.awt.geom.Point2D[] imagePoints, - LatLon[] geoPoints, BufferedImage destImage) - { - if (sourceImage == null) - { + LatLon[] geoPoints, BufferedImage destImage) { + if (sourceImage == null) { String message = Logging.getMessage("nullValue.SourceImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (destImage == null) - { + if (destImage == null) { String message = Logging.getMessage("nullValue.DestinationImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String message = validateControlPoints(3, imagePoints, geoPoints); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (imagePoints.length >= 4 && geoPoints.length >= 4) - { + if (imagePoints.length >= 4 && geoPoints.length >= 4) { return warpImageWithControlPoints4(sourceImage, imagePoints, geoPoints, destImage); - } - else // (imagePoints.length == 3) + } else // (imagePoints.length == 3) { return warpImageWithControlPoints3(sourceImage, imagePoints, geoPoints, destImage); } @@ -192,40 +173,35 @@ public static Sector warpImageWithControlPoints(BufferedImage sourceImage, java. * * @param sourceImage the source image to transform. * @param imagePoints four control points in the source image. - * @param geoPoints four geographic locations corresponding to each source control point. - * @param destImage the destination image to receive the transformed source imnage. + * @param geoPoints four geographic locations corresponding to each source control point. + * @param destImage the destination image to receive the transformed source imnage. * * @return bounding sector for the geographically aligned destination image. * * @throws IllegalArgumentException if any of sourceImage, destImage, - * imagePoints or geoPoints is null, or if either - * imagePoints or geoPoints have length less than 4. + * imagePoints or geoPoints is null, or if either imagePoints or + * geoPoints have length less than 4. */ public static Sector warpImageWithControlPoints4(BufferedImage sourceImage, java.awt.geom.Point2D[] imagePoints, - LatLon[] geoPoints, BufferedImage destImage) - { - if (sourceImage == null) - { + LatLon[] geoPoints, BufferedImage destImage) { + if (sourceImage == null) { String message = Logging.getMessage("nullValue.SourceImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (destImage == null) - { + if (destImage == null) { String message = Logging.getMessage("nullValue.DestinationImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String message = validateControlPoints(4, imagePoints, geoPoints); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } // We can only create an affine transform from three of the given points. To increase accruacy, we will compute // the error for each combination of three points, and choose the combination with the least error. - java.awt.geom.Point2D[] bestFitImagePoints = new java.awt.geom.Point2D[3]; LatLon[] bestFitGeoPoints = new LatLon[3]; computeBestFittingControlPoints4(imagePoints, geoPoints, bestFitImagePoints, bestFitGeoPoints); @@ -240,33 +216,29 @@ public static Sector warpImageWithControlPoints4(BufferedImage sourceImage, java * * @param sourceImage the source image to transform. * @param imagePoints three control points in the source image. - * @param geoPoints three geographic locations corresponding to each source control point. - * @param destImage the destination image to receive the transformed source imnage. + * @param geoPoints three geographic locations corresponding to each source control point. + * @param destImage the destination image to receive the transformed source imnage. * * @return bounding sector for the geographically aligned destination image. * * @throws IllegalArgumentException if any of sourceImage, destImage, - * imagePoints or geoPoints is null, or if either - * imagePoints or geoPoints have length less than 3. + * imagePoints or geoPoints is null, or if either imagePoints or + * geoPoints have length less than 3. */ public static Sector warpImageWithControlPoints3(BufferedImage sourceImage, java.awt.geom.Point2D[] imagePoints, - LatLon[] geoPoints, BufferedImage destImage) - { - if (sourceImage == null) - { + LatLon[] geoPoints, BufferedImage destImage) { + if (sourceImage == null) { String message = Logging.getMessage("nullValue.SourceImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (destImage == null) - { + if (destImage == null) { String message = Logging.getMessage("nullValue.DestinationImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String message = validateControlPoints(3, imagePoints, geoPoints); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -275,17 +247,13 @@ public static Sector warpImageWithControlPoints3(BufferedImage sourceImage, java // transformed into a lat/lon aligned image. We compute a matrix that will map source grid coordinates to // geographic coordinates. Then we transform the source image's four corners into geographic coordinates. // The sector we want is the sector that bounds those four geographic coordinates. - Matrix gridToGeographic = Matrix.fromImageToGeographic(imagePoints, geoPoints); List corners = computeImageCorners(sourceImage.getWidth(), sourceImage.getHeight(), gridToGeographic); Sector destSector = Sector.boundingSector(corners); - if (Sector.isSector(corners) && destSector.isSameSector(corners)) - { + if (Sector.isSector(corners) && destSector.isSameSector(corners)) { getScaledCopy(sourceImage, destImage); - } - else - { + } else { // Compute a matrix that will map from destination grid coordinates to source grid coordinates. By using // matrix multiplication in this order, an incoming vector will be transformed by the last matrix multiplied, // then the previous, and so on. So an incoming destination coordinate would be transformed into geographic @@ -294,7 +262,7 @@ public static Sector warpImageWithControlPoints3(BufferedImage sourceImage, java Matrix transform = Matrix.IDENTITY; transform = transform.multiply(Matrix.fromGeographicToImage(imagePoints, geoPoints)); transform = transform.multiply(Matrix.fromImageToGeographic(destImage.getWidth(), destImage.getHeight(), - destSector)); + destSector)); warpImageWithTransform(sourceImage, destImage, transform); } @@ -307,40 +275,35 @@ public static Sector warpImageWithControlPoints3(BufferedImage sourceImage, java * georeferenced by a world file, which defines an affine transform from source coordinates to geographic * coordinates. * - * @param sourceImage the source image to transform. + * @param sourceImage the source image to transform. * @param worldFileParams world file parameters which define an affine transform. - * @param destImage the destination image to receive the transformed source imnage. + * @param destImage the destination image to receive the transformed source imnage. * * @return bounding sector for the geographically aligned destination image. * * @throws IllegalArgumentException if any of sourceImage, destImage or - * worldFileParams is null. + * worldFileParams is null. */ public static Sector warpImageWithWorldFile(BufferedImage sourceImage, AVList worldFileParams, - BufferedImage destImage) - { - if (sourceImage == null) - { + BufferedImage destImage) { + if (sourceImage == null) { String message = Logging.getMessage("nullValue.SourceImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (worldFileParams == null) - { + if (worldFileParams == null) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (destImage == null) - { + if (destImage == null) { String message = Logging.getMessage("nullValue.DestinationImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Matrix imageToGeographic = Matrix.fromImageToGeographic(worldFileParams); - if (imageToGeographic == null) - { + if (imageToGeographic == null) { String message = Logging.getMessage("WorldFile.UnrecognizedValues", ""); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -349,16 +312,13 @@ public static Sector warpImageWithWorldFile(BufferedImage sourceImage, AVList wo List corners = computeImageCorners(sourceImage.getWidth(), sourceImage.getHeight(), imageToGeographic); Sector destSector = Sector.boundingSector(corners); - if (Sector.isSector(corners) && destSector.isSameSector(corners)) - { + if (Sector.isSector(corners) && destSector.isSameSector(corners)) { getScaledCopy(sourceImage, destImage); - } - else - { + } else { Matrix transform = Matrix.IDENTITY; transform = transform.multiply(Matrix.fromGeographicToImage(worldFileParams)); transform = transform.multiply(Matrix.fromImageToGeographic(destImage.getWidth(), destImage.getHeight(), - destSector)); + destSector)); warpImageWithTransform(sourceImage, destImage, transform); } @@ -371,71 +331,62 @@ public static Sector warpImageWithWorldFile(BufferedImage sourceImage, AVList wo * result is placed in the output parameters outImagePoints and outGeoPoints, both of * which must be non-null and at least length 3. * - * @param imagePoints four control points in the image. - * @param geoPoints four geographic locations corresponding to the four imagePoints. + * @param imagePoints four control points in the image. + * @param geoPoints four geographic locations corresponding to the four imagePoints. * @param outImagePoints three control points that best estimate the image's location. - * @param outGeoPoints three geographic locations corresponding to the three outImagePoints. + * @param outGeoPoints three geographic locations corresponding to the three outImagePoints. * * @throws IllegalArgumentException if any of imagePoints, geoPoints, - * outImagePoints or outGeoPoints is null, or if - * imagePoints or geoPoints have length less than 4, or - * if outImagePoints or outGeoPoints have length less - * than 3. + * outImagePoints or outGeoPoints is null, or if imagePoints or + * geoPoints have length less than 4, or if outImagePoints or outGeoPoints + * have length less than 3. */ public static void computeBestFittingControlPoints4(java.awt.geom.Point2D[] imagePoints, LatLon[] geoPoints, - java.awt.geom.Point2D[] outImagePoints, LatLon[] outGeoPoints) - { + java.awt.geom.Point2D[] outImagePoints, LatLon[] outGeoPoints) { String message = validateControlPoints(4, imagePoints, geoPoints); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } message = validateControlPoints(3, outImagePoints, outGeoPoints); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Compute the error for each combination of three points, and choose the combination with the least error. - java.awt.geom.Point2D[] bestFitImagePoints = null; LatLon[] bestFitGeoPoints = null; double minError = Double.MAX_VALUE; - for (int[] indices : new int[][] { + for (int[] indices : new int[][]{ {0, 1, 2}, {0, 1, 3}, {1, 2, 3}, - {0, 2, 3}}) - { - java.awt.geom.Point2D[] points = new java.awt.geom.Point2D[] { + {0, 2, 3}}) { + java.awt.geom.Point2D[] points = new java.awt.geom.Point2D[]{ imagePoints[indices[0]], imagePoints[indices[1]], imagePoints[indices[2]]}; - LatLon[] locations = new LatLon[] {geoPoints[indices[0]], geoPoints[indices[1]], geoPoints[indices[2]]}; + LatLon[] locations = new LatLon[]{geoPoints[indices[0]], geoPoints[indices[1]], geoPoints[indices[2]]}; Matrix m = Matrix.fromImageToGeographic(points, locations); double error = 0.0; - for (int j = 0; j < 4; j++) - { + for (int j = 0; j < 4; j++) { Vec4 vec = new Vec4(imagePoints[j].getX(), imagePoints[j].getY(), 1.0).transformBy3(m); LatLon ll = LatLon.fromDegrees(vec.y, vec.x); LatLon diff = geoPoints[j].subtract(ll); double d = diff.getLatitude().degrees * diff.getLatitude().degrees - + diff.getLongitude().degrees * diff.getLongitude().degrees; + + diff.getLongitude().degrees * diff.getLongitude().degrees; error += d; } - if (error < minError) - { + if (error < minError) { bestFitImagePoints = points; bestFitGeoPoints = locations; minError = error; } } - if (bestFitImagePoints != null) - { + if (bestFitImagePoints != null) { System.arraycopy(bestFitImagePoints, 0, outImagePoints, 0, 3); System.arraycopy(bestFitGeoPoints, 0, outGeoPoints, 0, 3); } @@ -445,25 +396,22 @@ public static void computeBestFittingControlPoints4(java.awt.geom.Point2D[] imag * Returns the geographic corners of an image with the specified dimensions, and a transform that maps image * coordinates to geographic coordinates. * - * @param imageWidth width of the image grid. - * @param imageHeight height of the image grid. + * @param imageWidth width of the image grid. + * @param imageHeight height of the image grid. * @param imageToGeographic Matrix that maps image coordinates to geographic coordinates. * * @return List of the image's corner locations in geographic coordinates. * * @throws IllegalArgumentException if either imageWidth or imageHeight are less than 1, - * or if imageToGeographic is null. + * or if imageToGeographic is null. */ - public static List computeImageCorners(int imageWidth, int imageHeight, Matrix imageToGeographic) - { - if (imageWidth < 1 || imageHeight < 1) - { + public static List computeImageCorners(int imageWidth, int imageHeight, Matrix imageToGeographic) { + if (imageWidth < 1 || imageHeight < 1) { String message = Logging.getMessage("generic.InvalidImageSize", imageWidth, imageHeight); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (imageToGeographic == null) - { + if (imageToGeographic == null) { String message = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -488,22 +436,17 @@ public static List computeImageCorners(int imageWidth, int imageHeight, } private static String validateControlPoints(int numExpected, - java.awt.geom.Point2D[] imagePoints, LatLon[] geoPoints) - { - if (imagePoints == null) - { + java.awt.geom.Point2D[] imagePoints, LatLon[] geoPoints) { + if (imagePoints == null) { return Logging.getMessage("nullValue.ImagePointsIsNull"); } - if (geoPoints == null) - { + if (geoPoints == null) { return Logging.getMessage("nullValue.GeoPointsIsNull"); } - if (imagePoints.length < numExpected) - { + if (imagePoints.length < numExpected) { return Logging.getMessage("generic.ArrayInvalidLength", imagePoints.length); } - if (geoPoints.length < numExpected) - { + if (geoPoints.length < numExpected) { return Logging.getMessage("generic.ArrayInvalidLength", imagePoints.length); } @@ -516,49 +459,46 @@ private static String validateControlPoints(int numExpected, * notion of a canvas, merges the incoming image according to the specified aspect ratio. * * @param canvasSector the sector defining the canvas' location and range. - * @param imageSector the sector defining the image's locaion and range. - * @param aspectRatio the aspect ratio, width/height, of the assembled image. If the aspect ratio is greater than - * or equal to one, the assembled image uses the full width of the canvas; the height used is - * proportional to the inverse of the aspect ratio. If the aspect ratio is less than one, the - * full height of the canvas is used; the width used is proportional to the aspect ratio.

                  - * The aspect ratio is typically used to maintain consistent width and height units while - * assembling multiple images into a canvas of a different aspect ratio than the canvas sector, - * such as drawing a non-square region into a 1024x1024 canvas. An aspect ratio of 1 causes the - * incoming images to be stretched as necessary in one dimension to match the aspect ratio of - * the canvas sector. - * @param image the image to merge into the canvas. - * @param canvas the canvas into which the images are merged. The canvas is not changed if the specified image - * and canvas sectors are disjoint. + * @param imageSector the sector defining the image's locaion and range. + * @param aspectRatio the aspect ratio, width/height, of the assembled image. If the aspect ratio is greater than or + * equal to one, the assembled image uses the full width of the canvas; the height used is proportional to the + * inverse of the aspect ratio. If the aspect ratio is less than one, the full height of the canvas is used; the + * width used is proportional to the aspect ratio. + *

                  + * The aspect ratio is typically used to maintain consistent width and height units while assembling multiple images + * into a canvas of a different aspect ratio than the canvas sector, such as drawing a non-square region into a + * 1024x1024 canvas. An aspect ratio of 1 causes the incoming images to be stretched as necessary in one dimension + * to match the aspect ratio of the canvas sector. + * @param image the image to merge into the canvas. + * @param canvas the canvas into which the images are merged. The canvas is not changed if the specified image and + * canvas sectors are disjoint. * * @throws IllegalArgumentException if the any of the reference arguments are null or the aspect ratio is less than - * or equal to zero. + * or equal to zero. */ public static void mergeImage(Sector canvasSector, Sector imageSector, double aspectRatio, BufferedImage image, - BufferedImage canvas) - { - if (canvasSector == null || imageSector == null) - { + BufferedImage canvas) { + if (canvasSector == null || imageSector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (canvas == null || image == null) - { + if (canvas == null || image == null) { String message = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (aspectRatio <= 0) - { + if (aspectRatio <= 0) { String message = Logging.getMessage("Util.AspectRatioInvalid", aspectRatio); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (!(canvasSector.intersects(imageSector))) + if (!(canvasSector.intersects(imageSector))) { return; + } // Create an image with the desired aspect ratio within an enclosing canvas of possibly different aspect ratio. int subWidth = aspectRatio >= 1 ? canvas.getWidth() : (int) Math.ceil((canvas.getWidth() * aspectRatio)); @@ -568,15 +508,15 @@ public static void mergeImage(Sector canvasSector, Sector imageSector, double as double yShift = aspectRatio >= 1d ? (1d - 1d / aspectRatio) * canvas.getHeight() : 0d; double sh = ((double) subHeight / (double) image.getHeight()) - * (imageSector.getDeltaLat().divide(canvasSector.getDeltaLat())); + * (imageSector.getDeltaLat().divide(canvasSector.getDeltaLat())); double sw = ((double) subWidth / (double) image.getWidth()) - * (imageSector.getDeltaLon().divide(canvasSector.getDeltaLon())); + * (imageSector.getDeltaLon().divide(canvasSector.getDeltaLon())); - double dh = subHeight * - (-imageSector.getMaxLatitude().subtract(canvasSector.getMaxLatitude()).degrees + double dh = subHeight + * (-imageSector.getMaxLatitude().subtract(canvasSector.getMaxLatitude()).degrees / canvasSector.getDeltaLat().degrees); - double dw = subWidth * - (imageSector.getMinLongitude().subtract(canvasSector.getMinLongitude()).degrees + double dw = subWidth + * (imageSector.getMinLongitude().subtract(canvasSector.getMinLongitude()).degrees / canvasSector.getDeltaLon().degrees); Graphics2D g = canvas.createGraphics(); @@ -586,19 +526,18 @@ public static void mergeImage(Sector canvasSector, Sector imageSector, double as } public static Sector positionImage(BufferedImage sourceImage, Point[] imagePoints, LatLon[] geoPoints, - BufferedImage destImage) - { - if (imagePoints.length == 3) + BufferedImage destImage) { + if (imagePoints.length == 3) { return positionImage3(sourceImage, imagePoints, geoPoints, destImage); - else if (imagePoints.length == 4) + } else if (imagePoints.length == 4) { return positionImage4(sourceImage, imagePoints, geoPoints, destImage); - else + } else { return null; + } } public static Sector positionImage3(BufferedImage sourceImage, Point[] imagePoints, LatLon[] geoPoints, - BufferedImage destImage) - { + BufferedImage destImage) { // TODO: check args BarycentricTriangle sourceLatLon = new BarycentricTriangle(geoPoints[0], geoPoints[1], geoPoints[2]); BarycentricTriangle sourcePixels = new BarycentricTriangle(imagePoints[0], imagePoints[1], imagePoints[2]); @@ -623,19 +562,18 @@ public static Sector positionImage3(BufferedImage sourceImage, Point[] imagePoin double width = destImage.getWidth(); double height = destImage.getHeight(); - for (int row = 0; row < destImage.getHeight(); row++) - { + for (int row = 0; row < destImage.getHeight(); row++) { double t = (double) row / height; - for (int col = 0; col < destImage.getWidth(); col++) - { + for (int col = 0; col < destImage.getWidth(); col++) { double s = (double) col / width; LatLon latLon = destLatLon.interpolate(1 - t, s); double[] baryCoords = sourceLatLon.getBarycentricCoords(latLon); Vec4 pixelPostion = sourcePixels.getPoint(baryCoords); if (pixelPostion.x < 0 || pixelPostion.x >= sourceImage.getWidth() - || pixelPostion.y < 0 || pixelPostion.y >= sourceImage.getHeight()) + || pixelPostion.y < 0 || pixelPostion.y >= sourceImage.getHeight()) { continue; + } int pixel = sourceImage.getRGB((int) pixelPostion.x, (int) pixelPostion.y); destImage.setRGB(col, row, pixel); } @@ -645,13 +583,12 @@ public static Sector positionImage3(BufferedImage sourceImage, Point[] imagePoin } public static Sector positionImage4(BufferedImage sourceImage, Point[] imagePoints, LatLon[] geoPoints, - BufferedImage destImage) - { + BufferedImage destImage) { // TODO: check args BarycentricQuadrilateral sourceLatLon = new BarycentricQuadrilateral(geoPoints[0], geoPoints[1], geoPoints[2], - geoPoints[3]); + geoPoints[3]); BarycentricQuadrilateral sourcePixels = new BarycentricQuadrilateral(imagePoints[0], imagePoints[1], - imagePoints[2], imagePoints[3]); + imagePoints[2], imagePoints[3]); ArrayList extremes = new ArrayList(4); // Lower left corner. @@ -673,19 +610,18 @@ public static Sector positionImage4(BufferedImage sourceImage, Point[] imagePoin double width = destImage.getWidth(); double height = destImage.getHeight(); - for (int row = 0; row < destImage.getHeight(); row++) - { + for (int row = 0; row < destImage.getHeight(); row++) { double t = (double) row / height; - for (int col = 0; col < destImage.getWidth(); col++) - { + for (int col = 0; col < destImage.getWidth(); col++) { double s = (double) col / width; LatLon latLon = destLatLon.interpolate(1 - t, s); double[] baryCoords = sourceLatLon.getBarycentricCoords(latLon); Vec4 pixelPostion = sourcePixels.getPoint(baryCoords); if (pixelPostion.x < 0 || pixelPostion.x >= sourceImage.getWidth() - || pixelPostion.y < 0 || pixelPostion.y >= sourceImage.getHeight()) + || pixelPostion.y < 0 || pixelPostion.y >= sourceImage.getHeight()) { continue; + } int pixel = sourceImage.getRGB((int) pixelPostion.x, (int) pixelPostion.y); destImage.setRGB(col, row, pixel); } @@ -701,10 +637,10 @@ public static Sector positionImage4(BufferedImage sourceImage, Point[] imagePoin * level will have dimensions equal to 1/2 the previous level's dimensions, rounding down, to a minimum width or * height of 1. * - * @param image the BufferedImage to build mipmaps for. + * @param image the BufferedImage to build mipmaps for. * @param mipmapImageType the BufferedImage type to use when creating each mipmap image. - * @param maxLevel the maximum mip level to create. Specifying zero will return an array containing the - * original image. + * @param maxLevel the maximum mip level to create. Specifying zero will return an array containing the original + * image. * * @return array of mipmap levels, starting at level 0 and stopping at maxLevel. This array will have length * maxLevel + 1. @@ -712,16 +648,13 @@ public static Sector positionImage4(BufferedImage sourceImage, Point[] imagePoin * @throws IllegalArgumentException if image is null, or if maxLevel is less than zero. * @see #getMaxMipmapLevel(int, int) */ - public static BufferedImage[] buildMipmaps(BufferedImage image, int mipmapImageType, int maxLevel) - { - if (image == null) - { + public static BufferedImage[] buildMipmaps(BufferedImage image, int mipmapImageType, int maxLevel) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (maxLevel < 0) - { + if (maxLevel < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "maxLevel < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -731,18 +664,14 @@ public static BufferedImage[] buildMipmaps(BufferedImage image, int mipmapImageT // If the image and mipmap type are equivalent, then just pass the original image along. Otherwise, create a // copy of the original image with the appropriate image type. - if (image.getType() == mipmapImageType) - { + if (image.getType() == mipmapImageType) { mipMapLevels[0] = image; - } - else - { + } else { mipMapLevels[0] = new BufferedImage(image.getWidth(), image.getHeight(), mipmapImageType); getScaledCopy(image, mipMapLevels[0]); } - for (int level = 1; level <= maxLevel; level++) - { + for (int level = 1; level <= maxLevel; level++) { int width = Math.max(image.getWidth() >> level, 1); int height = Math.max(image.getHeight() >> level, 1); @@ -765,10 +694,8 @@ public static BufferedImage[] buildMipmaps(BufferedImage image, int mipmapImageT * * @throws IllegalArgumentException if image is null. */ - public static BufferedImage[] buildMipmaps(BufferedImage image) - { - if (image == null) - { + public static BufferedImage[] buildMipmaps(BufferedImage image) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -787,11 +714,11 @@ public static BufferedImage[] buildMipmaps(BufferedImage image) * * @return mipmap image type. */ - public static int getMipmapType(int imageType) - { + public static int getMipmapType(int imageType) { // We cannot create a BufferedImage of type "custom", so we fall back to a default image type. - if (imageType == BufferedImage.TYPE_CUSTOM) + if (imageType == BufferedImage.TYPE_CUSTOM) { return BufferedImage.TYPE_INT_ARGB; + } return imageType; } @@ -801,23 +728,20 @@ public static int getMipmapType(int imageType) * The maximum desired level is the number of levels required to reduce the original image dimensions to a 1x1 * image. * - * @param width the level 0 image width. + * @param width the level 0 image width. * @param height the level 0 image height. * * @return maximum mip level for the specified width and height. * * @throws IllegalArgumentException if either width or height are less than 1. */ - public static int getMaxMipmapLevel(int width, int height) - { - if (width < 1) - { + public static int getMaxMipmapLevel(int width, int height) { + if (width < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 1) - { + if (height < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height < 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -832,51 +756,43 @@ public static int getMaxMipmapLevel(int width, int height) * Returns a copy of the specified image such that the new dimensions are powers of two. The new image dimensions * will be equal to or greater than the original image. The flag scaleToFit determines whether the * original image should be drawn into the new image with no special scaling, or whether the original image should - * be scaled to fit exactly in the new image.

                  If the original image dimensions are already powers of two, this - * method will simply return the original image. + * be scaled to fit exactly in the new image. + *

                  + * If the original image dimensions are already powers of two, this method will simply return the original image. * - * @param image the BufferedImage to convert to a power of two image. + * @param image the BufferedImage to convert to a power of two image. * @param scaleToFit true if image should be scaled to fit the new image dimensions; false otherwise.s * * @return copy of image with power of two dimensions. * * @throws IllegalArgumentException if image is null. */ - public static BufferedImage convertToPowerOfTwoImage(BufferedImage image, boolean scaleToFit) - { - if (image == null) - { + public static BufferedImage convertToPowerOfTwoImage(BufferedImage image, boolean scaleToFit) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // If the original image is already a power of two in both dimensions, then simply return it. - if (WWMath.isPowerOfTwo(image.getWidth()) && WWMath.isPowerOfTwo(image.getHeight())) - { + if (WWMath.isPowerOfTwo(image.getWidth()) && WWMath.isPowerOfTwo(image.getHeight())) { return image; } int potWidth = WWMath.powerOfTwoCeiling(image.getWidth()); int potHeight = WWMath.powerOfTwoCeiling(image.getHeight()); - BufferedImage potImage = new BufferedImage(potWidth, potHeight, image.getColorModel().hasAlpha() ? - BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR); + BufferedImage potImage = new BufferedImage(potWidth, potHeight, image.getColorModel().hasAlpha() + ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR); Graphics2D g2d = potImage.createGraphics(); - try - { - if (scaleToFit) - { + try { + if (scaleToFit) { g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(image, 0, 0, potImage.getWidth(), potImage.getHeight(), null); - } - else - { + } else { g2d.drawImage(image, 0, 0, null); } - } - finally - { + } finally { g2d.dispose(); } @@ -893,10 +809,8 @@ public static BufferedImage convertToPowerOfTwoImage(BufferedImage image, boolea * * @throws IllegalArgumentException if image is null. */ - public static BufferedImage trimImage(BufferedImage image) - { - if (image == null) - { + public static BufferedImage trimImage(BufferedImage image) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -911,29 +825,32 @@ public static BufferedImage trimImage(BufferedImage image) int x2 = 0; int y2 = 0; - for (int y = 0; y < height; y++) - { + for (int y = 0; y < height; y++) { image.getRGB(0, y, width, 1, rowPixels, 0, width); - for (int x = 0; x < width; x++) - { + for (int x = 0; x < width; x++) { int a = ((rowPixels[x] >> 24) & 0xff); - if (a <= 0) + if (a <= 0) { continue; + } - if (x1 > x) + if (x1 > x) { x1 = x; - if (x2 < x) + } + if (x2 < x) { x2 = x; - if (y1 > y) + } + if (y1 > y) { y1 = y; - if (y2 < y) + } + if (y2 < y) { y2 = y; + } } } return (x1 < x2 && y1 < y2) ? image.getSubimage(x1, y1, x2 - x1 + 1, y2 - y1 + 1) - : new BufferedImage(BufferedImage.TYPE_INT_ARGB, 0, 0); + : new BufferedImage(BufferedImage.TYPE_INT_ARGB, 0, 0); } /** @@ -946,10 +863,8 @@ public static BufferedImage trimImage(BufferedImage image) * * @throws IllegalArgumentException if image is null. */ - public static long computeSizeInBytes(BufferedImage image) - { - if (image == null) - { + public static long computeSizeInBytes(BufferedImage image) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -958,11 +873,9 @@ public static long computeSizeInBytes(BufferedImage image) long size = 0L; java.awt.image.Raster raster = image.getRaster(); - if (raster != null) - { + if (raster != null) { java.awt.image.DataBuffer db = raster.getDataBuffer(); - if (db != null) - { + if (db != null) { size = computeSizeOfDataBuffer(db); } } @@ -970,15 +883,12 @@ public static long computeSizeInBytes(BufferedImage image) return size; } - private static long computeSizeOfDataBuffer(java.awt.image.DataBuffer dataBuffer) - { + private static long computeSizeOfDataBuffer(java.awt.image.DataBuffer dataBuffer) { return dataBuffer.getSize() * computeSizeOfBufferDataType(dataBuffer.getDataType()); } - private static long computeSizeOfBufferDataType(int bufferDataType) - { - switch (bufferDataType) - { + private static long computeSizeOfBufferDataType(int bufferDataType) { + switch (bufferDataType) { case java.awt.image.DataBuffer.TYPE_BYTE: return (Byte.SIZE / 8); case java.awt.image.DataBuffer.TYPE_DOUBLE: @@ -997,47 +907,42 @@ private static long computeSizeOfBufferDataType(int bufferDataType) } /** - * Opens a spatial image. Reprojects the image if it is in UTM projection. + * Opens a spatial image. Reprojects the image if it is in UTM projection. * - * @param imageFile source image + * @param imageFile source image * @param interpolation_mode the interpolation mode if the image is reprojected. * * @return AVList * - * @throws IOException if there is a problem opening the file. + * @throws IOException if there is a problem opening the file. * @throws WWRuntimeException if the image type is unsupported. */ - public static AVList openSpatialImage(File imageFile, int interpolation_mode) throws IOException - { + public static AVList openSpatialImage(File imageFile, int interpolation_mode) throws IOException { AVList values = new AVListImpl(); BufferedImage image; Sector sector; //Check for Geotiff if ((imageFile.getName().toLowerCase().endsWith(".tiff") || (imageFile.getName().toLowerCase().endsWith( - ".tif")))) - { + ".tif")))) { GeotiffReader reader = new GeotiffReader(imageFile); int imageIndex = 0; image = reader.read(imageIndex); - if (reader.isGeotiff(imageIndex)) - { + if (reader.isGeotiff(imageIndex)) { return handleGeotiff(image, reader, imageIndex, interpolation_mode); } } //if not geotiff, contine through for other formats image = ImageIO.read(imageFile); - if (image == null) - { + if (image == null) { String message = Logging.getMessage("generic.ImageReadFailed", imageFile); Logging.logger().severe(message); throw new WWRuntimeException(message); } File[] worldFiles = WorldFile.getWorldFiles(imageFile.getAbsoluteFile()); - if (worldFiles == null || worldFiles.length == 0) - { + if (worldFiles == null || worldFiles.length == 0) { String message = Logging.getMessage("WorldFile.WorldFileNotFound", imageFile.getAbsolutePath()); Logging.logger().severe(message); throw new FileNotFoundException(message); @@ -1047,12 +952,12 @@ public static AVList openSpatialImage(File imageFile, int interpolation_mode) th WorldFile.decodeWorldFiles(worldFiles, values); sector = (Sector) values.getValue(AVKey.SECTOR); - if (sector == null) + if (sector == null) { ImageUtil.reprojectUtmToGeographic(values, interpolation_mode); + } sector = (Sector) values.getValue(AVKey.SECTOR); - if (sector == null) - { + if (sector == null) { String message = "Problem generating bounding sector for the image"; throw new WWRuntimeException(message); } @@ -1063,7 +968,7 @@ public static AVList openSpatialImage(File imageFile, int interpolation_mode) th } /** - * Opens a spatial image. Reprojects the image if it is in UTM projection. + * Opens a spatial image. Reprojects the image if it is in UTM projection. * * @param imageFile source image * @@ -1071,39 +976,39 @@ public static AVList openSpatialImage(File imageFile, int interpolation_mode) th * * @throws IOException if there is a problem opening the file. */ - public static AVList openSpatialImage(File imageFile) throws IOException - { + public static AVList openSpatialImage(File imageFile) throws IOException { return openSpatialImage(imageFile, ImageUtil.NEAREST_NEIGHBOR_INTERPOLATION); } /** * Reads Geo-referenced metadata from Geo-TIFF file * - * @param reader GeotiffReader + * @param reader GeotiffReader * @param imageIndex image index (could be a band; GeoTiff file could contain overview images, bands, etc) - * @param values AVList + * @param values AVList * - * @return values AVList + * @return values AVList * * @throws IOException if there is a problem opening the file. */ - public static AVList readGeoKeys(GeotiffReader reader, int imageIndex, AVList values) throws IOException - { - if (null == values) + public static AVList readGeoKeys(GeotiffReader reader, int imageIndex, AVList values) throws IOException { + if (null == values) { values = new AVListImpl(); + } - if (null == reader) + if (null == reader) { return values; + } return reader.copyMetadataTo(imageIndex, values); } /** - * Opens a Geotiff image image. Reprojects the image if it is in UTM projection. + * Opens a Geotiff image image. Reprojects the image if it is in UTM projection. * - * @param image BufferedImage - * @param reader GeotiffReader - * @param imageIndex image index (GeoTiff file could contain overview images, bands, etc) + * @param image BufferedImage + * @param reader GeotiffReader + * @param imageIndex image index (GeoTiff file could contain overview images, bands, etc) * @param interpolation_mode the interpolation mode if the image is reprojected. * * @return AVList @@ -1111,13 +1016,11 @@ public static AVList readGeoKeys(GeotiffReader reader, int imageIndex, AVList va * @throws IOException if there is a problem opening the file. */ private static AVList handleGeotiff(BufferedImage image, GeotiffReader reader, int imageIndex, - int interpolation_mode) - throws IOException - { + int interpolation_mode) + throws IOException { AVList values = new AVListImpl(); - if (null != image) - { + if (null != image) { values.setValue(AVKey.IMAGE, image); values.setValue(AVKey.WIDTH, image.getWidth()); values.setValue(AVKey.HEIGHT, image.getHeight()); @@ -1125,72 +1028,63 @@ private static AVList handleGeotiff(BufferedImage image, GeotiffReader reader, i ImageUtil.readGeoKeys(reader, imageIndex, values); - if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(values.getValue(AVKey.COORDINATE_SYSTEM))) + if (AVKey.COORDINATE_SYSTEM_PROJECTED.equals(values.getValue(AVKey.COORDINATE_SYSTEM))) { ImageUtil.reprojectUtmToGeographic(values, interpolation_mode); + } return values; } - public static Sector calcBoundingBoxForUTM(AVList params) throws IOException - { - if (null == params) - { + public static Sector calcBoundingBoxForUTM(AVList params) throws IOException { + if (null == params) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IOException(message); } - if (!params.hasKey(AVKey.WIDTH)) - { + if (!params.hasKey(AVKey.WIDTH)) { String message = Logging.getMessage("Geom.WidthInvalid"); Logging.logger().severe(message); throw new IOException(message); } - if (!params.hasKey(AVKey.HEIGHT)) - { + if (!params.hasKey(AVKey.HEIGHT)) { String message = Logging.getMessage("Geom.HeightInvalid"); Logging.logger().severe(message); throw new IOException(message); } - if (!params.hasKey(WorldFile.WORLD_FILE_X_PIXEL_SIZE)) - { + if (!params.hasKey(WorldFile.WORLD_FILE_X_PIXEL_SIZE)) { String message = Logging.getMessage("WorldFile.NoPixelSizeSpecified", "X"); Logging.logger().severe(message); throw new IOException(message); } - if (!params.hasKey(WorldFile.WORLD_FILE_Y_PIXEL_SIZE)) - { + if (!params.hasKey(WorldFile.WORLD_FILE_Y_PIXEL_SIZE)) { String message = Logging.getMessage("WorldFile.NoPixelSizeSpecified", "Y"); Logging.logger().severe(message); throw new IOException(message); } - if (!params.hasKey(WorldFile.WORLD_FILE_X_LOCATION)) - { + if (!params.hasKey(WorldFile.WORLD_FILE_X_LOCATION)) { String message = Logging.getMessage("WorldFile.NoLocationSpecified", "X"); Logging.logger().severe(message); throw new IOException(message); } - if (!params.hasKey(WorldFile.WORLD_FILE_Y_LOCATION)) - { + if (!params.hasKey(WorldFile.WORLD_FILE_Y_LOCATION)) { String message = Logging.getMessage("WorldFile.NoLocationSpecified", "Y"); Logging.logger().severe(message); throw new IOException(message); } - if (!params.hasKey(AVKey.PROJECTION_ZONE)) - { + if (!params.hasKey(AVKey.PROJECTION_ZONE)) { String message = Logging.getMessage("generic.ZoneIsMissing"); Logging.logger().severe(message); throw new IOException(message); } - if (!params.hasKey(AVKey.PROJECTION_HEMISPHERE)) - { + if (!params.hasKey(AVKey.PROJECTION_HEMISPHERE)) { String message = Logging.getMessage("generic.HemisphereIsMissing"); Logging.logger().severe(message); throw new IOException(message); @@ -1211,16 +1105,16 @@ public static Sector calcBoundingBoxForUTM(AVList params) throws IOException UTMCoord upperLeft = UTMCoord.fromUTM(zone, hemisphere, xLocation, yLocation); UTMCoord utmUpperLeft = UTMCoord.fromUTM(zone, hemisphere, upperLeft.getEasting() - xPixelSize * .5, - upperLeft.getNorthing() - yPixelSize * .5); + upperLeft.getNorthing() - yPixelSize * .5); UTMCoord utmLowerRight = UTMCoord.fromUTM(zone, hemisphere, utmUpperLeft.getEasting() + (width * xPixelSize), - utmUpperLeft.getNorthing() + (height * yPixelSize)); + utmUpperLeft.getNorthing() + (height * yPixelSize)); //Get rect Geo bbox UTMCoord utmLowerLeft = UTMCoord.fromUTM(zone, upperLeft.getHemisphere(), utmUpperLeft.getEasting(), - utmLowerRight.getNorthing()); + utmLowerRight.getNorthing()); UTMCoord utmUpperRight = UTMCoord.fromUTM(zone, upperLeft.getHemisphere(), utmLowerRight.getEasting(), - utmUpperLeft.getNorthing()); + utmUpperLeft.getNorthing()); Angle rightExtent = Angle.max(utmUpperRight.getLongitude(), utmLowerRight.getLongitude()); Angle leftExtent = Angle.min(utmLowerLeft.getLongitude(), utmUpperLeft.getLongitude()); @@ -1238,19 +1132,17 @@ public static Sector calcBoundingBoxForUTM(AVList params) throws IOException * Reprojects an imge in UTM projection to Geo/WGS84. * * @param values AVList: contains the bufferedimage and the values from the world file. Stores resulting image in - * values - * @param mode the interpolation mode if the image is reprojected. + * values + * @param mode the interpolation mode if the image is reprojected. */ - public static void reprojectUtmToGeographic(AVList values, int mode) - { + public static void reprojectUtmToGeographic(AVList values, int mode) { //TODO pull these const from TMCoord? double False_Easting = 500000; double False_Northing = 0; double Scale = 0.9996; Earth earth = new Earth(); //need globe for TM - if (values == null) - { + if (values == null) { String message = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1262,13 +1154,10 @@ public static void reprojectUtmToGeographic(AVList values, int mode) BufferedImage biOut; //Note: image type always BufferedImage.TYPE_INT_ARGB to handle transparent no-data areas after reprojection - if ((image.getColorModel() != null) && (image.getColorModel() instanceof IndexColorModel)) - { + if ((image.getColorModel() != null) && (image.getColorModel() instanceof IndexColorModel)) { biOut = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB, - (IndexColorModel) image.getColorModel()); - } - else - { + (IndexColorModel) image.getColorModel()); + } else { biOut = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } @@ -1276,12 +1165,14 @@ public static void reprojectUtmToGeographic(AVList values, int mode) double yPixelSize = 0; Object o = values.getValue(WorldFile.WORLD_FILE_X_PIXEL_SIZE); - if (o != null && o instanceof Double) + if (o != null && o instanceof Double) { xPixelSize = (Double) o; + } o = values.getValue(WorldFile.WORLD_FILE_Y_PIXEL_SIZE); - if (o != null && o instanceof Double) + if (o != null && o instanceof Double) { yPixelSize = (Double) o; + } // TODO: validate that all these values exist and are valid double xLocation = (Double) values.getValue(WorldFile.WORLD_FILE_X_LOCATION); @@ -1291,16 +1182,16 @@ public static void reprojectUtmToGeographic(AVList values, int mode) UTMCoord upperLeft = UTMCoord.fromUTM(zone, hemisphere, xLocation, yLocation); UTMCoord utmUpperLeft = UTMCoord.fromUTM(zone, hemisphere, upperLeft.getEasting() - xPixelSize * .5, - upperLeft.getNorthing() - yPixelSize * .5); + upperLeft.getNorthing() - yPixelSize * .5); UTMCoord utmLowerRight = UTMCoord.fromUTM(zone, hemisphere, utmUpperLeft.getEasting() + (width * xPixelSize), - utmUpperLeft.getNorthing() + (height * yPixelSize)); + utmUpperLeft.getNorthing() + (height * yPixelSize)); //Get rect Geo bbox UTMCoord utmLowerLeft = UTMCoord.fromUTM(zone, upperLeft.getHemisphere(), utmUpperLeft.getEasting(), - utmLowerRight.getNorthing()); + utmLowerRight.getNorthing()); UTMCoord utmUpperRight = UTMCoord.fromUTM(zone, upperLeft.getHemisphere(), utmLowerRight.getEasting(), - utmUpperLeft.getNorthing()); + utmUpperLeft.getNorthing()); Angle rightExtent = Angle.max(utmUpperRight.getLongitude(), utmLowerRight.getLongitude()); Angle leftExtent = Angle.min(utmLowerLeft.getLongitude(), utmUpperLeft.getLongitude()); @@ -1316,38 +1207,34 @@ public static void reprojectUtmToGeographic(AVList values, int mode) double leftExtent2 = sector.getMinLongitude().getDegrees() + (xPixel * .5); TMCoord tmUpperLeft = TMCoord.fromLatLon(utmUpperLeft.getLatitude(), utmUpperLeft.getLongitude(), - earth, null, null, Angle.fromDegrees(0.0), utmUpperLeft.getCentralMeridian(), - False_Easting, False_Northing, Scale); + earth, null, null, Angle.fromDegrees(0.0), utmUpperLeft.getCentralMeridian(), + False_Easting, False_Northing, Scale); double srcTop = tmUpperLeft.getNorthing() + (yPixelSize * .5); double srcLeft = tmUpperLeft.getEasting() + (xPixelSize * .5); - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { double yTarget = topExtent2 + y * yPixel; double xTarget = leftExtent2 + x * xPixel; TMCoord TM = TMCoord.fromLatLon(Angle.fromDegreesLatitude(yTarget), Angle.fromDegreesLongitude(xTarget), - earth, null, null, Angle.fromDegrees(0.0), utmUpperLeft.getCentralMeridian(), - False_Easting, False_Northing, Scale); + earth, null, null, Angle.fromDegrees(0.0), utmUpperLeft.getCentralMeridian(), + False_Easting, False_Northing, Scale); double distFromCornerX = TM.getEasting() - srcLeft; double distFromCornerY = srcTop - TM.getNorthing(); long rx = Math.round(distFromCornerX / Math.abs(xPixelSize)); long ry = Math.round(distFromCornerY / Math.abs(yPixelSize)); - if (mode == ImageUtil.BILINEAR_INTERPOLATION) - { + if (mode == ImageUtil.BILINEAR_INTERPOLATION) { double rxD = distFromCornerX / Math.abs(xPixelSize); double ryD = distFromCornerY / Math.abs(yPixelSize); int iX = (int) Math.floor(rxD); int iY = (int) Math.floor(ryD); double dx = rxD - iX; double dy = ryD - iY; - if ((iX > 0) && (iY > 0)) - if ((iX < width - 1) && (iY < height - 1)) - { + if ((iX > 0) && (iY > 0)) { + if ((iX < width - 1) && (iY < height - 1)) { //get four pixels from image int a = image.getRGB(iX, iY); int b = image.getRGB(iX + 1, iY); @@ -1356,17 +1243,19 @@ public static void reprojectUtmToGeographic(AVList values, int mode) int sum = interpolateColor(dx, dy, a, b, c, d); biOut.setRGB(x, y, Math.round(sum)); - } - else + } else { biOut.setRGB(x, y, 0); - } - else //NEAREST_NEIGHBOR is default + } + } + } else //NEAREST_NEIGHBOR is default { - if ((rx > 0) && (ry > 0)) - if ((rx < width) && (ry < height)) + if ((rx > 0) && (ry > 0)) { + if ((rx < width) && (ry < height)) { biOut.setRGB(x, y, image.getRGB(Long.valueOf(rx).intValue(), Long.valueOf(ry).intValue())); - else + } else { biOut.setRGB(x, y, 0); + } + } } } } @@ -1377,10 +1266,10 @@ public static void reprojectUtmToGeographic(AVList values, int mode) /** * Performs bilinear interpolation of 32-bit colors over a convex quadrilateral. * - * @param x horizontal coordinate of the interpolation point relative to the lower left corner of the - * quadrilateral. The value should generally be in the range [0, 1]. - * @param y vertical coordinate of the interpolation point relative to the lower left corner of the quadrilateral. - * The value should generally be in the range [0, 1]. + * @param x horizontal coordinate of the interpolation point relative to the lower left corner of the quadrilateral. + * The value should generally be in the range [0, 1]. + * @param y vertical coordinate of the interpolation point relative to the lower left corner of the quadrilateral. + * The value should generally be in the range [0, 1]. * @param c0 color at the lower left corner of the quadrilateral. * @param c1 color at the lower right corner of the quadrilateral. * @param c2 color at the pixel upper left corner of the quadrilateral. @@ -1388,8 +1277,7 @@ public static void reprojectUtmToGeographic(AVList values, int mode) * * @return int the interpolated color. */ - public static int interpolateColor(double x, double y, int c0, int c1, int c2, int c3) - { + public static int interpolateColor(double x, double y, int c0, int c1, int c2, int c3) { //pull out alpha, red, green, blue values for each pixel int a0 = (c0 >> 24) & 0xff; int r0 = (c0 >> 16) & 0xff; @@ -1436,13 +1324,12 @@ public static int interpolateColor(double x, double y, int c0, int c1, int c2, i return (a | r | g | b); } - public static class AlignedImage - { + public static class AlignedImage { + public final Sector sector; public final BufferedImage image; - public AlignedImage(BufferedImage image, Sector sector) - { + public AlignedImage(BufferedImage image, Sector sector) { this.image = image; this.sector = sector; } @@ -1452,23 +1339,21 @@ public AlignedImage(BufferedImage image, Sector sector) * Reprojects an image into an aligned image, one with edges of constant latitude and longitude. * * @param sourceImage the image to reproject, typically a non-aligned image - * @param latitudes an array identifying the latitude of each pixels if the source image. There must be an entry - * in the array for all pixels. The values are taken to be in row-major order relative to the - * image -- the horizontal component varies fastest. - * @param longitudes an array identifying the longitude of each pixels if the source image. There must be an entry - * in the array for all pixels. The values are taken to be in row-major order relative to the - * image -- the horizontal component varies fastest. + * @param latitudes an array identifying the latitude of each pixels if the source image. There must be an entry in + * the array for all pixels. The values are taken to be in row-major order relative to the image -- the horizontal + * component varies fastest. + * @param longitudes an array identifying the longitude of each pixels if the source image. There must be an entry + * in the array for all pixels. The values are taken to be in row-major order relative to the image -- the + * horizontal component varies fastest. * * @return a new image containing the original image but reprojected to align to the bounding sector. Pixels in the * new image that have no correspondence with the source image are transparent. * * @throws InterruptedException if any thread has interrupted the current thread while alignImage is running. The - * interrupted status of the current thread is cleared when this exception is - * thrown. + * interrupted status of the current thread is cleared when this exception is thrown. */ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitudes, float[] longitudes) - throws InterruptedException - { + throws InterruptedException { return alignImage(sourceImage, latitudes, longitudes, null, null); } @@ -1476,34 +1361,30 @@ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitud * Reprojects an image into an aligned image, one with edges of constant latitude and longitude. * * @param sourceImage the image to reproject, typically a non-aligned image - * @param latitudes an array identifying the latitude of each pixels if the source image. There must be an entry - * in the array for all pixels. The values are taken to be in row-major order relative to the - * image -- the horizontal component varies fastest. - * @param longitudes an array identifying the longitude of each pixels if the source image. There must be an entry - * in the array for all pixels. The values are taken to be in row-major order relative to the - * image -- the horizontal component varies fastest. - * @param sector the sector to align the image to. If null, this computes the aligned image's sector. - * @param dimension the the aligned image's dimensions. If null, this computes the aligned image's dimension. + * @param latitudes an array identifying the latitude of each pixels if the source image. There must be an entry in + * the array for all pixels. The values are taken to be in row-major order relative to the image -- the horizontal + * component varies fastest. + * @param longitudes an array identifying the longitude of each pixels if the source image. There must be an entry + * in the array for all pixels. The values are taken to be in row-major order relative to the image -- the + * horizontal component varies fastest. + * @param sector the sector to align the image to. If null, this computes the aligned image's sector. + * @param dimension the the aligned image's dimensions. If null, this computes the aligned image's dimension. * * @return a new image containing the original image but reprojected to align to the sector. Pixels in the new image * that have no correspondence with the source image are transparent. * * @throws InterruptedException if any thread has interrupted the current thread while alignImage is running. The - * interrupted status of the current thread is cleared when this exception is - * thrown. + * interrupted status of the current thread is cleared when this exception is thrown. */ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitudes, float[] longitudes, - Sector sector, Dimension dimension) throws InterruptedException - { - if (sourceImage == null) - { + Sector sector, Dimension dimension) throws InterruptedException { + if (sourceImage == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (latitudes == null || longitudes == null || latitudes.length != longitudes.length) - { + if (latitudes == null || longitudes == null || latitudes.length != longitudes.length) { String message = Logging.getMessage("ImageUtil.FieldArrayInvalid"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1512,28 +1393,25 @@ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitud int sourceWidth = sourceImage.getWidth(); int sourceHeight = sourceImage.getHeight(); - if (sourceWidth < 1 || sourceHeight < 1) - { + if (sourceWidth < 1 || sourceHeight < 1) { String message = Logging.getMessage("ImageUtil.EmptyImage"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (longitudes.length < sourceWidth * sourceHeight || latitudes.length < sourceWidth * sourceHeight) - { + if (longitudes.length < sourceWidth * sourceHeight || latitudes.length < sourceWidth * sourceHeight) { String message = Logging.getMessage("ImageUtil.FieldArrayTooShort"); Logging.logger().severe(message); throw new IllegalStateException(message); } GeographicImageInterpolator grid = new GeographicImageInterpolator(new Dimension(sourceWidth, sourceHeight), - longitudes, latitudes, 10, 1); + longitudes, latitudes, 10, 1); // If the caller did not specify a Sector, then use the image's bounding sector as computed by // GeographicImageInterpolator. We let GeographicImageInterpolator perform the computation because it computes // the correct sector for images which cross the international dateline. - if (sector == null) - { + if (sector == null) { sector = grid.getSector(); } @@ -1547,14 +1425,13 @@ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitud // This has the effect of allocating resolution where the aligned image needs it most, and gives the aligned // image square pixels in geographic coordinates. Without square pixels the aligned image's resolution can be // extremely anisotriopic, causing severe aliasing in one dimension. - if (dimension == null) - { + if (dimension == null) { double maxDimension = Math.max(sourceWidth, sourceHeight); double maxSectorDelta = Math.max(sector.getDeltaLonDegrees(), sector.getDeltaLatDegrees()); double pixelsPerDegree = maxDimension / maxSectorDelta; dimension = new Dimension( - (int) Math.round(pixelsPerDegree * sector.getDeltaLonDegrees()), - (int) Math.round(pixelsPerDegree * sector.getDeltaLatDegrees())); + (int) Math.round(pixelsPerDegree * sector.getDeltaLonDegrees()), + (int) Math.round(pixelsPerDegree * sector.getDeltaLatDegrees())); } // Get a buffer containing the source image's pixels. @@ -1571,8 +1448,7 @@ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitud // aligned image pixel's as having area, and the location of each pixel's at its center. This loop begins in the // center of the upper left hand pixel and continues in row major order across the image, stepping by a pixels // geographic size. - for (int j = 0; j < dimension.height; j++) - { + for (int j = 0; j < dimension.height; j++) { // Generate an InterruptedException if the current thread is interrupted. Responding to thread interruptions // before processing each image row ensures that this method terminates in a reasonable amount of time after // the currently executing thread is interrupted, but without consuming unecessary CPU time. Using either @@ -1582,8 +1458,7 @@ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitud float lat = (float) (sector.getMaxLatitude().degrees - j * dLat - dLon / 2d); - for (int i = 0; i < dimension.width; i++) - { + for (int i = 0; i < dimension.width; i++) { float lon = (float) (sector.getMinLongitude().degrees + i * dLon + dLat / 2d); // Search for a cell in the source image which contains this aligned image pixel's location. @@ -1592,13 +1467,12 @@ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitud // If there's a source cell for this location, then write a color to the destination image by linearly // interpolating between the four pixels at the cell's corners. Otherwise, don't change the destination // image. This ensures pixels which don't correspond to the source image remain transparent. - if (cell != null) - { + if (cell != null) { int color = interpolateColor(cell.uv[0], cell.uv[1], - sourceColors[cell.fieldIndices[0]], - sourceColors[cell.fieldIndices[1]], - sourceColors[cell.fieldIndices[3]], - sourceColors[cell.fieldIndices[2]] + sourceColors[cell.fieldIndices[0]], + sourceColors[cell.fieldIndices[1]], + sourceColors[cell.fieldIndices[3]], + sourceColors[cell.fieldIndices[2]] ); destColors[j * dimension.width + i] = color; @@ -1618,18 +1492,18 @@ public static AlignedImage alignImage(BufferedImage sourceImage, float[] latitud return new AlignedImage(destImage, sector); } - public static void alignImageDump(BufferedImage sourceImage, float[] latitudes, float[] longitudes) - { - try - { + public static void alignImageDump(BufferedImage sourceImage, float[] latitudes, float[] longitudes) { + try { JFileChooser fileChooser = new JFileChooser(); int status = fileChooser.showSaveDialog(null); - if (status != JFileChooser.APPROVE_OPTION) + if (status != JFileChooser.APPROVE_OPTION) { return; + } File imageFile = fileChooser.getSelectedFile(); - if (!imageFile.getName().endsWith(".png")) + if (!imageFile.getName().endsWith(".png")) { imageFile = new File(imageFile.getPath() + ".png"); + } ImageIO.write(sourceImage, "png", imageFile); @@ -1638,8 +1512,7 @@ public static void alignImageDump(BufferedImage sourceImage, float[] latitudes, DataOutputStream latsOut = new DataOutputStream(new FileOutputStream(latsFile)); DataOutputStream lonsOut = new DataOutputStream(new FileOutputStream(lonsFile)); - for (int i = 0; i < latitudes.length; i++) - { + for (int i = 0; i < latitudes.length; i++) { latsOut.writeFloat(latitudes[i]); lonsOut.writeFloat(longitudes[i]); } @@ -1648,58 +1521,49 @@ public static void alignImageDump(BufferedImage sourceImage, float[] latitudes, latsOut.close(); lonsOut.close(); System.out.println("FILES SAVED"); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } private static final int MAX_IMAGE_SIZE_TO_CONVERT = 4096; - public static BufferedImage toCompatibleImage(BufferedImage image) - { - if (image == null) - { + public static BufferedImage toCompatibleImage(BufferedImage image) { + if (image == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (java.awt.GraphicsEnvironment.isHeadless()) + if (java.awt.GraphicsEnvironment.isHeadless()) { return image; + } // If the image is not already compatible, and is within the restrictions on dimension, then convert it // to a compatible image type. if (!isCompatibleImage(image) - && (image.getWidth() <= MAX_IMAGE_SIZE_TO_CONVERT) - && (image.getHeight() <= MAX_IMAGE_SIZE_TO_CONVERT)) - { - java.awt.image.BufferedImage compatibleImage = - createCompatibleImage(image.getWidth(), image.getHeight(), image.getTransparency()); + && (image.getWidth() <= MAX_IMAGE_SIZE_TO_CONVERT) + && (image.getHeight() <= MAX_IMAGE_SIZE_TO_CONVERT)) { + java.awt.image.BufferedImage compatibleImage + = createCompatibleImage(image.getWidth(), image.getHeight(), image.getTransparency()); java.awt.Graphics2D g2d = compatibleImage.createGraphics(); g2d.drawImage(image, 0, 0, null); g2d.dispose(); return compatibleImage; - } - // Otherwise return the original image. - else - { + } // Otherwise return the original image. + else { return image; } } - public static BufferedImage createCompatibleImage(int width, int height, int transparency) - { - if (width < 1) - { + public static BufferedImage createCompatibleImage(int width, int height, int transparency) { + if (width < 1) { String message = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height < 1) - { + if (height < 1) { String message = Logging.getMessage("generic.InvalidHeight", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1708,7 +1572,7 @@ public static BufferedImage createCompatibleImage(int width, int height, int tra // if (java.awt.GraphicsEnvironment.isHeadless()) { return new BufferedImage(width, height, - (transparency == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB + (transparency == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB ); } // @@ -1716,49 +1580,41 @@ public static BufferedImage createCompatibleImage(int width, int height, int tra // return gc.createCompatibleImage(width, height, transparency); } - protected static boolean isCompatibleImage(BufferedImage image) - { - if (java.awt.GraphicsEnvironment.isHeadless()) + protected static boolean isCompatibleImage(BufferedImage image) { + if (java.awt.GraphicsEnvironment.isHeadless()) { return false; + } java.awt.GraphicsConfiguration gc = getDefaultGraphicsConfiguration(); java.awt.image.ColorModel gcColorModel = gc.getColorModel(image.getTransparency()); return image.getColorModel().equals(gcColorModel); } - protected static java.awt.GraphicsConfiguration getDefaultGraphicsConfiguration() - { + protected static java.awt.GraphicsConfiguration getDefaultGraphicsConfiguration() { java.awt.GraphicsEnvironment ge = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(); java.awt.GraphicsDevice gd = ge.getDefaultScreenDevice(); return gd.getDefaultConfiguration(); } - public static BufferedImage mapTransparencyColors(ByteBuffer imageBuffer, int originalColors[]) - { - try - { + public static BufferedImage mapTransparencyColors(ByteBuffer imageBuffer, int originalColors[]) { + try { InputStream inputStream = WWIO.getInputStreamFromByteBuffer(imageBuffer); BufferedImage image = ImageIO.read(inputStream); return mapTransparencyColors(image, originalColors); - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().finest(e.getMessage()); return null; } } - public static BufferedImage mapTransparencyColors(BufferedImage sourceImage, int[] originalColors) - { - if (sourceImage == null) - { + public static BufferedImage mapTransparencyColors(BufferedImage sourceImage, int[] originalColors) { + if (sourceImage == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (originalColors == null) - { + if (originalColors == null) { String message = Logging.getMessage("nullValue.ColorArrayIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1767,8 +1623,7 @@ public static BufferedImage mapTransparencyColors(BufferedImage sourceImage, int int width = sourceImage.getWidth(); int height = sourceImage.getHeight(); - if (width < 1 || height < 1) - { + if (width < 1 || height < 1) { String message = Logging.getMessage("ImageUtil.EmptyImage"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1777,15 +1632,11 @@ public static BufferedImage mapTransparencyColors(BufferedImage sourceImage, int int[] sourceColors = sourceImage.getRGB(0, 0, width, height, null, 0, width); int[] destColors = Arrays.copyOf(sourceColors, sourceColors.length); - for (int j = 0; j < height; j++) - { - for (int i = 0; i < width; i++) - { + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { int index = j * width + i; - for (int c : originalColors) - { - if (sourceColors[index] == c) - { + for (int c : originalColors) { + if (sourceColors[index] == c) { destColors[index] = 0; break; } @@ -1803,32 +1654,25 @@ public static BufferedImage mapTransparencyColors(BufferedImage sourceImage, int return destImage; } - public static BufferedImage mapColors(ByteBuffer imageBuffer, int originalColor, int newColor) - { - try - { + public static BufferedImage mapColors(ByteBuffer imageBuffer, int originalColor, int newColor) { + try { InputStream inputStream = WWIO.getInputStreamFromByteBuffer(imageBuffer); BufferedImage image = ImageIO.read(inputStream); - return mapColors(image, new int[] {originalColor}, new int[] {newColor}); - } - catch (IOException e) - { + return mapColors(image, new int[]{originalColor}, new int[]{newColor}); + } catch (IOException e) { Logging.logger().finest(e.getMessage()); return null; } } - public static BufferedImage mapColors(BufferedImage sourceImage, int[] originalColors, int[] newColors) - { - if (sourceImage == null) - { + public static BufferedImage mapColors(BufferedImage sourceImage, int[] originalColors, int[] newColors) { + if (sourceImage == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (originalColors == null || newColors == null) - { + if (originalColors == null || newColors == null) { String message = Logging.getMessage("nullValue.ColorArrayIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1837,8 +1681,7 @@ public static BufferedImage mapColors(BufferedImage sourceImage, int[] originalC int width = sourceImage.getWidth(); int height = sourceImage.getHeight(); - if (width < 1 || height < 1) - { + if (width < 1 || height < 1) { String message = Logging.getMessage("ImageUtil.EmptyImage"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -1847,15 +1690,13 @@ public static BufferedImage mapColors(BufferedImage sourceImage, int[] originalC int[] sourceColors = sourceImage.getRGB(0, 0, width, height, null, 0, width); int[] destColors = Arrays.copyOf(sourceColors, sourceColors.length); - for (int j = 0; j < height; j++) - { - for (int i = 0; i < width; i++) - { + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { int index = j * width + i; - for (int c : originalColors) - { - if (sourceColors[index] == originalColors[c]) + for (int c : originalColors) { + if (sourceColors[index] == originalColors[c]) { destColors[index] = newColors[c]; + } } } } @@ -1870,12 +1711,10 @@ public static BufferedImage mapColors(BufferedImage sourceImage, int[] originalC return destImage; } - public static ByteBuffer asJPEG(DataRaster raster) - { + public static ByteBuffer asJPEG(DataRaster raster) { ByteBuffer buffer = null; - if (null == raster) - { + if (null == raster) { String msg = Logging.getMessage("nullValue.RasterIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1883,16 +1722,11 @@ public static ByteBuffer asJPEG(DataRaster raster) BufferedImage image; - if (raster instanceof BufferedImageRaster) - { + if (raster instanceof BufferedImageRaster) { image = ((BufferedImageRaster) raster).getBufferedImage(); - } - else if (raster instanceof BufferWrapperRaster) - { + } else if (raster instanceof BufferWrapperRaster) { image = ImageUtil.visualize((BufferWrapperRaster) raster); - } - else - { + } else { String msg = Logging.getMessage("generic.UnexpectedRasterType", raster.getClass().getName()); Logging.logger().severe(msg); throw new WWRuntimeException(msg); @@ -1900,58 +1734,48 @@ else if (raster instanceof BufferWrapperRaster) ImageOutputStream ios = null; - if (null == image) - { + if (null == image) { String msg = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } - try - { + try { ByteArrayOutputStream imageBytes = new ByteArrayOutputStream(); ios = new MemoryCacheImageOutputStream(imageBytes); ColorModel cm = image.getColorModel(); - if (cm instanceof ComponentColorModel) - { + if (cm instanceof ComponentColorModel) { ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); - if (null != writer) - { + if (null != writer) { ImageWriteParam param = writer.getDefaultWriteParam(); - param.setSourceBands(new int[] {0, 1, 2}); - cm = new DirectColorModel(24, /*Red*/0x00ff0000, /*Green*/0x0000ff00, /*Blue*/ 0x000000ff, - /*Alpha*/0x0); + param.setSourceBands(new int[]{0, 1, 2}); + cm = new DirectColorModel(24, /*Red*/ 0x00ff0000, /*Green*/ 0x0000ff00, /*Blue*/ 0x000000ff, + /*Alpha*/ 0x0); param.setDestinationType(new ImageTypeSpecifier(cm, cm.createCompatibleSampleModel(1, 1))); writer.setOutput(ios); writer.write(null, new IIOImage(image, null, null), param); writer.dispose(); } - } - else + } else { ImageIO.write(image, "jpeg", ios); + } buffer = ByteBuffer.wrap(imageBytes.toByteArray()); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(java.util.logging.Level.SEVERE, t.getMessage(), t); - } - finally - { + } finally { close(ios); } return buffer; } - public static ByteBuffer asPNG(DataRaster raster) - { + public static ByteBuffer asPNG(DataRaster raster) { ByteBuffer buffer = null; - if (null == raster) - { + if (null == raster) { String msg = Logging.getMessage("nullValue.RasterIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1959,16 +1783,11 @@ public static ByteBuffer asPNG(DataRaster raster) BufferedImage image; - if (raster instanceof BufferedImageRaster) - { + if (raster instanceof BufferedImageRaster) { image = ((BufferedImageRaster) raster).getBufferedImage(); - } - else if (raster instanceof BufferWrapperRaster) - { + } else if (raster instanceof BufferWrapperRaster) { image = ImageUtil.visualize((BufferWrapperRaster) raster); - } - else - { + } else { String msg = Logging.getMessage("generic.UnexpectedRasterType", raster.getClass().getName()); Logging.logger().severe(msg); throw new WWRuntimeException(msg); @@ -1976,62 +1795,49 @@ else if (raster instanceof BufferWrapperRaster) ImageOutputStream ios = null; - if (null == image) - { + if (null == image) { String msg = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } - try - { + try { ByteArrayOutputStream imageBytes = new ByteArrayOutputStream(); ios = new MemoryCacheImageOutputStream(imageBytes); ImageIO.write(image, "png", ios); buffer = ByteBuffer.wrap(imageBytes.toByteArray()); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(java.util.logging.Level.SEVERE, t.getMessage(), t); - } - finally - { + } finally { close(ios); } return buffer; } - protected static void close(ImageOutputStream ios) - { - if (null != ios) - { - try - { + protected static void close(ImageOutputStream ios) { + if (null != ios) { + try { ios.close(); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(java.util.logging.Level.SEVERE, t.getMessage(), t); } } } /** - * Converts a non-imagery data raster (elevations) to visually representable image raster. - * Calculates min and max values, and normalizes pixel value from 0 - 65,535 and creates - * a GRAY color image raster with pixel data type of unsigned short. + * Converts a non-imagery data raster (elevations) to visually representable image raster. Calculates min and max + * values, and normalizes pixel value from 0 - 65,535 and creates a GRAY color image raster with pixel data type of + * unsigned short. * * @param raster non-imagery data raster (elevations) instance of data raster derived from BufferWrapperRaster * * @return BufferedImage visual representation of the non-imagery data raster */ - public static BufferedImage visualize(BufferWrapperRaster raster) - { - if (null == raster) - { + public static BufferedImage visualize(BufferWrapperRaster raster) { + if (null == raster) { String message = Logging.getMessage("nullValue.RasterIsNull"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -2039,7 +1845,7 @@ public static BufferedImage visualize(BufferWrapperRaster raster) // we are building UINT DataBuffer, cannot use negative values as -32768 or -9999, so we will use 0 double missingDataSignal = AVListImpl.getDoubleValue(raster, AVKey.MISSING_DATA_SIGNAL, - (double) Short.MIN_VALUE); + (double) Short.MIN_VALUE); int missingDataReplacement = 0; Double minElevation = (Double) raster.getValue(AVKey.ELEVATION_MIN); @@ -2052,11 +1858,10 @@ public static BufferedImage visualize(BufferWrapperRaster raster) int height = raster.getHeight(); int size = width * height; - short[][] data = new short[][] - { - new short[size], // intensity band - new short[size] // alpha (transparency band) - }; + short[][] data = new short[][]{ + new short[size], // intensity band + new short[size] // alpha (transparency band) + }; final int BAND_Y = 0, BAND_ALPHA = 1; @@ -2066,23 +1871,18 @@ public static BufferedImage visualize(BufferWrapperRaster raster) int i = 0; boolean hasVoids = false; double norm = (max != min) ? Math.abs(65534d / (max - min)) : 0d; - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { double v = raster.getDoubleAtPosition(y, x); // set pixel and alpha as zero (transparent) for pixel which is: // - equals to missingDataSignal // - is zero // - greater than max elevation or smaller than min elevation - if (v == missingDataSignal || v == 0 || v < min || v > max) - { + if (v == missingDataSignal || v == 0 || v < min || v > max) { data[BAND_Y][i] = (short) (0xFFFF & missingDataReplacement); data[BAND_ALPHA][i] = ALPHA_TRANSLUCENT; hasVoids = true; - } - else - { + } else { data[BAND_Y][i] = (short) (0xFFFF & (int) ((v - min) * norm)); data[BAND_ALPHA][i] = ALPHA_OPAQUE; } @@ -2090,9 +1890,9 @@ public static BufferedImage visualize(BufferWrapperRaster raster) } } - int[] bandOrder = (hasVoids) ? new int[] {BAND_Y, BAND_ALPHA} : new int[] {BAND_Y}; - int[] offsets = (hasVoids) ? new int[] {0, 0} : new int[] {0}; - int[] nBits = (hasVoids) ? new int[] {16, 8} : new int[] {16}; + int[] bandOrder = (hasVoids) ? new int[]{BAND_Y, BAND_ALPHA} : new int[]{BAND_Y}; + int[] offsets = (hasVoids) ? new int[]{0, 0} : new int[]{0}; + int[] nBits = (hasVoids) ? new int[]{16, 8} : new int[]{16}; DataBuffer imgBuffer = new DataBufferUShort(data, size); @@ -2103,8 +1903,8 @@ public static BufferedImage visualize(BufferWrapperRaster raster) ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); ColorModel cm = new ComponentColorModel(cs, nBits, hasVoids, false, - hasVoids ? Transparency.TRANSLUCENT : Transparency.OPAQUE, - DataBuffer.TYPE_USHORT); + hasVoids ? Transparency.TRANSLUCENT : Transparency.OPAQUE, + DataBuffer.TYPE_USHORT); return new BufferedImage(cm, wr, false, null); } diff --git a/src/gov/nasa/worldwind/util/IntSet.java b/src/gov/nasa/worldwind/util/IntSet.java index 88898ef8cd..b44774bad2 100644 --- a/src/gov/nasa/worldwind/util/IntSet.java +++ b/src/gov/nasa/worldwind/util/IntSet.java @@ -15,20 +15,18 @@ * @author dcollins * @version $Id: IntSet.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class IntSet -{ +public class IntSet { + protected static final int DEFAULT_NUM_BUCKETS = 128; protected static final int DEFAULT_BUCKET_CAPACITY = 8; - protected static class Bucket - { + protected static class Bucket { + public int[] values; public int length; - public Bucket(int initialCapacity) - { - if (initialCapacity < 1) - { + public Bucket(int initialCapacity) { + if (initialCapacity < 1) { String msg = Logging.getMessage("generic.SizeOutOfRange", initialCapacity); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -44,9 +42,10 @@ public Bucket(int initialCapacity) protected int bucketInitialCapacity; protected int size; - /** Creates an empty IntSet with the default number of buckets and initial bucket capacity. */ - public IntSet() - { + /** + * Creates an empty IntSet with the default number of buckets and initial bucket capacity. + */ + public IntSet() { this(DEFAULT_NUM_BUCKETS, DEFAULT_BUCKET_CAPACITY); } @@ -56,22 +55,19 @@ public IntSet() * unique values, the number of buckets should be configured to a large value such as 128. The bucket initial * capacity does not significantly affect performance, as each bucket eventually grows to fit its entries. * - * @param numBuckets the number of buckets this IntSet uses to + * @param numBuckets the number of buckets this IntSet uses to * @param bucketInitialCapacity the initial capacity for each bucket. * * @throws IllegalArgumentException if either numBuckets or bucketInitialCapacity is less than 1. */ - public IntSet(int numBuckets, int bucketInitialCapacity) - { - if (numBuckets < 1) - { + public IntSet(int numBuckets, int bucketInitialCapacity) { + if (numBuckets < 1) { String msg = Logging.getMessage("generic.SizeOutOfRange", numBuckets); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (bucketInitialCapacity < 1) - { + if (bucketInitialCapacity < 1) { String msg = Logging.getMessage("generic.SizeOutOfRange", bucketInitialCapacity); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -87,8 +83,7 @@ public IntSet(int numBuckets, int bucketInitialCapacity) * * @return the set's size. */ - public int size() - { + public int size() { return this.size; } @@ -100,26 +95,21 @@ public int size() * * @return true if the value is added to this set, otherwise false. */ - public boolean add(int value) - { + public boolean add(int value) { int index = value % this.numBuckets; Bucket bucket = this.buckets[index]; - if (bucket == null) - { + if (bucket == null) { bucket = this.buckets[index] = new Bucket(this.bucketInitialCapacity); - } - else - { - for (int i = 0; i < bucket.length; i++) - { - if (bucket.values[i] == value) + } else { + for (int i = 0; i < bucket.length; i++) { + if (bucket.values[i] == value) { return false; + } } } - if (bucket.values.length <= bucket.length) - { + if (bucket.values.length <= bucket.length) { int[] tmp = new int[2 * bucket.values.length]; System.arraycopy(bucket.values, 0, tmp, 0, bucket.values.length); bucket.values = tmp; @@ -139,26 +129,26 @@ public boolean add(int value) * * @return true of the value is removed from this set, otherwise false. */ - public boolean remove(int value) - { + public boolean remove(int value) { int index = value % this.numBuckets; Bucket bucket = this.buckets[index]; - if (bucket == null || bucket.length == 0) + if (bucket == null || bucket.length == 0) { return false; + } int i; - for (i = 0; i < bucket.length; i++) - { - if (bucket.values[i] == value) + for (i = 0; i < bucket.length; i++) { + if (bucket.values[i] == value) { break; + } } - if (i == bucket.length) + if (i == bucket.length) { return false; + } - if (i < bucket.length - 1) - { + if (i < bucket.length - 1) { System.arraycopy(bucket.values, i + 1, bucket.values, i, bucket.length - i - 1); } @@ -175,30 +165,31 @@ public boolean remove(int value) * * @return true if this set contains the value, otherwise false. */ - public boolean contains(int value) - { + public boolean contains(int value) { int index = value % this.numBuckets; Bucket bucket = this.buckets[index]; - if (bucket == null) + if (bucket == null) { return false; + } - for (int i = 0; i < bucket.length; i++) - { - if (bucket.values[i] == value) + for (int i = 0; i < bucket.length; i++) { + if (bucket.values[i] == value) { return true; + } } return false; } - /** Removes all of the values from this set. This set is empty after this call returns. */ - public void clear() - { - for (int i = 0; i < this.numBuckets; i++) - { - if (this.buckets[i] != null) + /** + * Removes all of the values from this set. This set is empty after this call returns. + */ + public void clear() { + for (int i = 0; i < this.numBuckets; i++) { + if (this.buckets[i] != null) { this.buckets[i].length = 0; + } } this.size = 0; @@ -212,20 +203,18 @@ public void clear() * @param array the array into which the values are stored. * * @return the array of values in this set, or a new array if the specified array is null or not large - * enough. + * enough. */ - public int[] toArray(int[] array) - { - if (array == null || array.length < this.size) + public int[] toArray(int[] array) { + if (array == null || array.length < this.size) { array = new int[this.size]; + } int offset = 0; - for (int i = 0; i < this.numBuckets; i++) - { + for (int i = 0; i < this.numBuckets; i++) { Bucket bucket = this.buckets[i]; - if (bucket != null) - { + if (bucket != null) { System.arraycopy(bucket.values, 0, array, offset, bucket.length); offset += bucket.length; } diff --git a/src/gov/nasa/worldwind/util/JOGLVersionInfo.java b/src/gov/nasa/worldwind/util/JOGLVersionInfo.java index d6d44029c0..c7dc7168b5 100644 --- a/src/gov/nasa/worldwind/util/JOGLVersionInfo.java +++ b/src/gov/nasa/worldwind/util/JOGLVersionInfo.java @@ -7,80 +7,68 @@ /** * This program returns the version and implementation information for the Java Bindings for OpenGL (R) implementation - * found in the CLASSPATH. This information is also found in the manifest for jogl-all.jar, and this program uses the + * found in the CLASSPATH. This information is also found in the manifest for jogl-all.jar, and this program uses the * java.lang.Package class to retrieve it programmatically. * * @version $Id: JOGLVersionInfo.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class JOGLVersionInfo -{ +public class JOGLVersionInfo { + private static JOGLVersionInfo svi = new JOGLVersionInfo(); private Package p; - private JOGLVersionInfo() - { + private JOGLVersionInfo() { ClassLoader classLoader = getClass().getClassLoader(); this.p = pkgInfo(classLoader, "com.jogamp.opengl", "GL"); } - private static Package pkgInfo(ClassLoader classLoader, String pkgName, String className) - { + private static Package pkgInfo(ClassLoader classLoader, String pkgName, String className) { Package p = null; - try - { + try { classLoader.loadClass(pkgName + "." + className); // TODO: message logging p = Package.getPackage(pkgName); - if (p == null) + if (p == null) { System.out.println("WARNING: Package.getPackage(" + pkgName + ") is null"); - } - catch (ClassNotFoundException e) - { + } + } catch (ClassNotFoundException e) { System.out.println("Unable to load " + pkgName); } return p; } - public static Package getPackage() - { + public static Package getPackage() { return svi.p; } - public static boolean isCompatibleWith(String version) - { + public static boolean isCompatibleWith(String version) { return svi.p != null && svi.p.isCompatibleWith(version); } - public static String getSpecificationTitle() - { + public static String getSpecificationTitle() { return svi.p != null ? svi.p.getSpecificationTitle() : null; } - public static String getSpecificationVendor() - { + public static String getSpecificationVendor() { return svi.p != null ? svi.p.getSpecificationVendor() : null; } - public static String getSpecificationVersion() - { + public static String getSpecificationVersion() { return svi.p != null ? svi.p.getSpecificationVersion() : null; } - public static String getImplementationTitle() - { + public static String getImplementationTitle() { return svi.p != null ? svi.p.getImplementationTitle() : null; } - public static String getImplementationVersion() - { + public static String getImplementationVersion() { return svi.p != null ? svi.p.getImplementationVersion() : null; } - public static void main(String[] args) - { + public static void main(String[] args) { System.out.println(JOGLVersionInfo.getPackage()); System.out.println(JOGLVersionInfo.getSpecificationTitle()); System.out.println(JOGLVersionInfo.getSpecificationVendor()); @@ -91,9 +79,9 @@ public static void main(String[] args) System.out.println(JOGLVersionInfo.isCompatibleWith("1.1.1")); System.out.println(JOGLVersionInfo.isCompatibleWith("1.2.1")); System.out.println( - JOGLVersionInfo.getImplementationVersion().compareToIgnoreCase("1.1.1-pre-20070511-02:12:11")); + JOGLVersionInfo.getImplementationVersion().compareToIgnoreCase("1.1.1-pre-20070511-02:12:11")); System.out.println( - JOGLVersionInfo.getImplementationVersion().compareToIgnoreCase("1.1.1-pre-20070512-02:12:11")); + JOGLVersionInfo.getImplementationVersion().compareToIgnoreCase("1.1.1-pre-20070512-02:12:11")); System.out.println(JOGLVersionInfo.getImplementationVersion().compareToIgnoreCase("1.1.1")); } } diff --git a/src/gov/nasa/worldwind/util/Level.java b/src/gov/nasa/worldwind/util/Level.java index 100695152d..c575ca9b87 100644 --- a/src/gov/nasa/worldwind/util/Level.java +++ b/src/gov/nasa/worldwind/util/Level.java @@ -12,8 +12,8 @@ * @author tag * @version $Id: Level.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Level extends AVListImpl implements Comparable -{ +public class Level extends AVListImpl implements Comparable { + protected AVList params; protected int levelNumber; protected String levelName; // null or empty level name signifies no data resources associated with this level @@ -37,10 +37,8 @@ public class Level extends AVListImpl implements Comparable int DEFAULT_MAX_ABSENT_TILE_ATTEMPTS = 2; int DEFAULT_MIN_ABSENT_TILE_CHECK_INTERVAL = 10000; // milliseconds - public Level(AVList params) - { - if (params == null) - { + public Level(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.LevelConfigParams"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -48,8 +46,7 @@ public Level(AVList params) this.params = params.copy(); // Private copy to insulate from subsequent changes by the app String message = this.validate(params); - if (message != null) - { + if (message != null) { Logging.logger().severe(message); throw new IllegalArgumentException(message); } @@ -76,12 +73,14 @@ public Level(AVList params) this.path = this.cacheName + "/" + this.levelName; Integer maxAbsentTileAttempts = (Integer) this.params.getValue(AVKey.MAX_ABSENT_TILE_ATTEMPTS); - if (maxAbsentTileAttempts == null) + if (maxAbsentTileAttempts == null) { maxAbsentTileAttempts = DEFAULT_MAX_ABSENT_TILE_ATTEMPTS; + } Integer minAbsentTileCheckInterval = (Integer) this.params.getValue(AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL); - if (minAbsentTileCheckInterval == null) + if (minAbsentTileCheckInterval == null) { minAbsentTileCheckInterval = DEFAULT_MIN_ABSENT_TILE_CHECK_INTERVAL; + } this.absentTiles = new AbsentResourceList(maxAbsentTileAttempts, minAbsentTileCheckInterval); } @@ -93,184 +92,174 @@ public Level(AVList params) * * @return null if valid, otherwise a String containing a description of why it's invalid. */ - protected String validate(AVList params) - { + protected String validate(AVList params) { StringBuffer sb = new StringBuffer(); Object o = params.getValue(AVKey.LEVEL_NUMBER); - if (o == null || !(o instanceof Integer) || ((Integer) o) < 0) + if (o == null || !(o instanceof Integer) || ((Integer) o) < 0) { sb.append(Logging.getMessage("term.levelNumber")).append(" "); + } o = params.getValue(AVKey.LEVEL_NAME); - if (o == null || !(o instanceof String)) + if (o == null || !(o instanceof String)) { sb.append(Logging.getMessage("term.levelName")).append(" "); + } o = params.getValue(AVKey.TILE_WIDTH); - if (o == null || !(o instanceof Integer) || ((Integer) o) < 0) + if (o == null || !(o instanceof Integer) || ((Integer) o) < 0) { sb.append(Logging.getMessage("term.tileWidth")).append(" "); + } o = params.getValue(AVKey.TILE_HEIGHT); - if (o == null || !(o instanceof Integer) || ((Integer) o) < 0) + if (o == null || !(o instanceof Integer) || ((Integer) o) < 0) { sb.append(Logging.getMessage("term.tileHeight")).append(" "); + } o = params.getValue(AVKey.TILE_DELTA); - if (o == null || !(o instanceof LatLon)) + if (o == null || !(o instanceof LatLon)) { sb.append(Logging.getMessage("term.tileDelta")).append(" "); + } o = params.getValue(AVKey.DATA_CACHE_NAME); - if (o == null || !(o instanceof String) || ((String) o).length() < 1) + if (o == null || !(o instanceof String) || ((String) o).length() < 1) { sb.append(Logging.getMessage("term.fileStoreFolder")).append(" "); + } o = params.getValue(AVKey.TILE_URL_BUILDER); - if (o == null || !(o instanceof TileUrlBuilder)) + if (o == null || !(o instanceof TileUrlBuilder)) { sb.append(Logging.getMessage("term.tileURLBuilder")).append(" "); + } o = params.getValue(AVKey.EXPIRY_TIME); - if (o != null && (!(o instanceof Long) || ((Long) o) < 1)) + if (o != null && (!(o instanceof Long) || ((Long) o) < 1)) { sb.append(Logging.getMessage("term.expiryTime")).append(" "); + } - if (params.getStringValue(AVKey.LEVEL_NAME).length() > 0) - { + if (params.getStringValue(AVKey.LEVEL_NAME).length() > 0) { o = params.getValue(AVKey.DATASET_NAME); - if (o == null || !(o instanceof String) || ((String) o).length() < 1) + if (o == null || !(o instanceof String) || ((String) o).length() < 1) { sb.append(Logging.getMessage("term.datasetName")).append(" "); + } o = params.getValue(AVKey.FORMAT_SUFFIX); - if (o == null || !(o instanceof String) || ((String) o).length() < 1) + if (o == null || !(o instanceof String) || ((String) o).length() < 1) { sb.append(Logging.getMessage("term.formatSuffix")).append(" "); + } } - if (sb.length() == 0) + if (sb.length() == 0) { return null; + } return Logging.getMessage("layers.LevelSet.InvalidLevelDescriptorFields", sb.toString()); } - public AVList getParams() - { + public AVList getParams() { return params; } - public String getPath() - { + public String getPath() { return this.path; } - public int getLevelNumber() - { + public int getLevelNumber() { return this.levelNumber; } - public String getLevelName() - { + public String getLevelName() { return this.levelName; } - public LatLon getTileDelta() - { + public LatLon getTileDelta() { return this.tileDelta; } - public int getTileWidth() - { + public int getTileWidth() { return this.tileWidth; } - public int getTileHeight() - { + public int getTileHeight() { return this.tileHeight; } - public String getFormatSuffix() - { + public String getFormatSuffix() { return this.formatSuffix; } - public String getService() - { + public String getService() { return this.service; } - public String getDataset() - { + public String getDataset() { return this.dataset; } - public String getCacheName() - { + public String getCacheName() { return this.cacheName; } - public double getTexelSize() - { + public double getTexelSize() { return this.texelSize; } - public boolean isEmpty() - { + public boolean isEmpty() { return this.levelName == null || this.levelName.equals("") || !this.active; } - public void markResourceAbsent(long tileNumber) - { - if (tileNumber >= 0) + public void markResourceAbsent(long tileNumber) { + if (tileNumber >= 0) { this.absentTiles.markResourceAbsent(tileNumber); + } } - public boolean isResourceAbsent(long tileNumber) - { + public boolean isResourceAbsent(long tileNumber) { return this.absentTiles.isResourceAbsent(tileNumber); } - public void unmarkResourceAbsent(long tileNumber) - { - if (tileNumber >= 0) + public void unmarkResourceAbsent(long tileNumber) { + if (tileNumber >= 0) { this.absentTiles.unmarkResourceAbsent(tileNumber); + } } - public long getExpiryTime() - { + public long getExpiryTime() { return this.expiryTime; } - public void setExpiryTime(long expTime) - { + public void setExpiryTime(long expTime) { this.expiryTime = expTime; } - public boolean isActive() - { + public boolean isActive() { return this.active; } - public void setActive(boolean active) - { + public void setActive(boolean active) { this.active = active; } - public AbsentResourceList getAbsentTiles() - { + public AbsentResourceList getAbsentTiles() { return absentTiles; } @Override - public Object setValue(String key, Object value) - { - if (key != null && key.equals(AVKey.MAX_ABSENT_TILE_ATTEMPTS) && value instanceof Integer) + public Object setValue(String key, Object value) { + if (key != null && key.equals(AVKey.MAX_ABSENT_TILE_ATTEMPTS) && value instanceof Integer) { this.absentTiles.setMaxTries((Integer) value); - else if (key != null && key.equals(AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL) && value instanceof Integer) + } else if (key != null && key.equals(AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL) && value instanceof Integer) { this.absentTiles.setMinCheckInterval((Integer) value); + } return super.setValue(key, value); } @Override - public Object getValue(String key) - { - if (key != null && key.equals(AVKey.MAX_ABSENT_TILE_ATTEMPTS)) + public Object getValue(String key) { + if (key != null && key.equals(AVKey.MAX_ABSENT_TILE_ATTEMPTS)) { return this.absentTiles.getMaxTries(); - else if (key != null && key.equals(AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL)) + } else if (key != null && key.equals(AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL)) { return this.absentTiles.getMinCheckInterval(); + } return super.getValue(key); } @@ -278,18 +267,16 @@ else if (key != null && key.equals(AVKey.MIN_ABSENT_TILE_CHECK_INTERVAL)) /** * Returns the URL necessary to retrieve the specified tile. * - * @param tile the tile who's resources will be retrieved. + * @param tile the tile who's resources will be retrieved. * @param imageFormat a string identifying the mime type of the desired image format * * @return the resource URL. * * @throws java.net.MalformedURLException if the URL cannot be formed from the tile's parameters. - * @throws IllegalArgumentException if tile is null. + * @throws IllegalArgumentException if tile is null. */ - public java.net.URL getTileResourceURL(Tile tile, String imageFormat) throws java.net.MalformedURLException - { - if (tile == null) - { + public java.net.URL getTileResourceURL(Tile tile, String imageFormat) throws java.net.MalformedURLException { + if (tile == null) { String msg = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -298,16 +285,13 @@ public java.net.URL getTileResourceURL(Tile tile, String imageFormat) throws jav return this.urlBuilder.getURL(tile, imageFormat); } - public Sector computeSectorForPosition(Angle latitude, Angle longitude, LatLon tileOrigin) - { - if (latitude == null || longitude == null) - { + public Sector computeSectorForPosition(Angle latitude, Angle longitude, LatLon tileOrigin) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatLonIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (tileOrigin == null) - { + if (tileOrigin == null) { String message = Logging.getMessage("nullValue.TileOriginIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -327,10 +311,8 @@ public Sector computeSectorForPosition(Angle latitude, Angle longitude, LatLon t return new Sector(minLatitude, minLatitude.add(dLat), minLongitude, minLongitude.add(dLon)); } - public int compareTo(Level that) - { - if (that == null) - { + public int compareTo(Level that) { + if (that == null) { String msg = Logging.getMessage("nullValue.LevelIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -338,40 +320,49 @@ public int compareTo(Level that) return this.levelNumber < that.levelNumber ? -1 : this.levelNumber == that.levelNumber ? 0 : 1; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } final Level level = (Level) o; - if (levelNumber != level.levelNumber) + if (levelNumber != level.levelNumber) { return false; - if (tileHeight != level.tileHeight) + } + if (tileHeight != level.tileHeight) { return false; - if (tileWidth != level.tileWidth) + } + if (tileWidth != level.tileWidth) { return false; - if (cacheName != null ? !cacheName.equals(level.cacheName) : level.cacheName != null) + } + if (cacheName != null ? !cacheName.equals(level.cacheName) : level.cacheName != null) { return false; - if (dataset != null ? !dataset.equals(level.dataset) : level.dataset != null) + } + if (dataset != null ? !dataset.equals(level.dataset) : level.dataset != null) { return false; - if (formatSuffix != null ? !formatSuffix.equals(level.formatSuffix) : level.formatSuffix != null) + } + if (formatSuffix != null ? !formatSuffix.equals(level.formatSuffix) : level.formatSuffix != null) { return false; - if (levelName != null ? !levelName.equals(level.levelName) : level.levelName != null) + } + if (levelName != null ? !levelName.equals(level.levelName) : level.levelName != null) { return false; - if (service != null ? !service.equals(level.service) : level.service != null) + } + if (service != null ? !service.equals(level.service) : level.service != null) { return false; + } //noinspection RedundantIfStatement - if (tileDelta != null ? !tileDelta.equals(level.tileDelta) : level.tileDelta != null) + if (tileDelta != null ? !tileDelta.equals(level.tileDelta) : level.tileDelta != null) { return false; + } return true; } - public int hashCode() - { + public int hashCode() { int result; result = levelNumber; result = 29 * result + (levelName != null ? levelName.hashCode() : 0); @@ -386,8 +377,7 @@ public int hashCode() } @Override - public String toString() - { + public String toString() { return this.path; } } diff --git a/src/gov/nasa/worldwind/util/LevelSet.java b/src/gov/nasa/worldwind/util/LevelSet.java index 63e1cd0ddc..0179acfc29 100644 --- a/src/gov/nasa/worldwind/util/LevelSet.java +++ b/src/gov/nasa/worldwind/util/LevelSet.java @@ -16,26 +16,23 @@ * @author tag * @version $Id: LevelSet.java 2060 2014-06-18 03:19:17Z tgaskins $ */ -public class LevelSet extends WWObjectImpl -{ - public static final class SectorResolution - { +public class LevelSet extends WWObjectImpl { + + public static final class SectorResolution { + private final int levelNumber; private final Sector sector; - public SectorResolution(Sector sector, int levelNumber) - { + public SectorResolution(Sector sector, int levelNumber) { this.levelNumber = levelNumber; this.sector = sector; } - public final int getLevelNumber() - { + public final int getLevelNumber() { return this.levelNumber; } - public final Sector getSector() - { + public final Sector getSector() { return this.sector; } } @@ -47,50 +44,49 @@ public final Sector getSector() private final java.util.ArrayList levels = new java.util.ArrayList(); private final SectorResolution[] sectorLevelLimits; - public LevelSet(AVList params) - { + public LevelSet(AVList params) { StringBuffer sb = new StringBuffer(); Object o = params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA); - if (o == null || !(o instanceof LatLon)) + if (o == null || !(o instanceof LatLon)) { sb.append(Logging.getMessage("term.tileDelta")).append(" "); + } o = params.getValue(AVKey.SECTOR); - if (o == null || !(o instanceof Sector)) + if (o == null || !(o instanceof Sector)) { sb.append(Logging.getMessage("term.sector")).append(" "); + } int numLevels = 0; o = params.getValue(AVKey.NUM_LEVELS); - if (o == null || !(o instanceof Integer) || (numLevels = (Integer) o) < 1) + if (o == null || !(o instanceof Integer) || (numLevels = (Integer) o) < 1) { sb.append(Logging.getMessage("term.numLevels")).append(" "); + } int numEmptyLevels = 0; o = params.getValue(AVKey.NUM_EMPTY_LEVELS); - if (o != null && o instanceof Integer && (Integer) o > 0) + if (o != null && o instanceof Integer && (Integer) o > 0) { numEmptyLevels = (Integer) o; + } String[] inactiveLevels = null; o = params.getValue(AVKey.INACTIVE_LEVELS); - if (o != null && !(o instanceof String)) + if (o != null && !(o instanceof String)) { sb.append(Logging.getMessage("term.inactiveLevels")).append(" "); - else if (o != null) + } else if (o != null) { inactiveLevels = ((String) o).split(","); + } SectorResolution[] sectorLimits = null; o = params.getValue(AVKey.SECTOR_RESOLUTION_LIMITS); - if (o != null && !(o instanceof SectorResolution[])) - { + if (o != null && !(o instanceof SectorResolution[])) { sb.append(Logging.getMessage("term.sectorResolutionLimits")).append(" "); - } - else if (o != null) - { + } else if (o != null) { sectorLimits = (SectorResolution[]) o; - for (SectorResolution sr : sectorLimits) - { - if (sr.levelNumber > numLevels - 1) - { - String message = - Logging.getMessage("LevelSet.sectorResolutionLimitsTooHigh", sr.levelNumber, numLevels - 1); + for (SectorResolution sr : sectorLimits) { + if (sr.levelNumber > numLevels - 1) { + String message + = Logging.getMessage("LevelSet.sectorResolutionLimitsTooHigh", sr.levelNumber, numLevels - 1); Logging.logger().warning(message); break; } @@ -98,8 +94,7 @@ else if (o != null) } this.sectorLevelLimits = sectorLimits; - if (sb.length() > 0) - { + if (sb.length() > 0) { String message = Logging.getMessage("layers.LevelSet.InvalidLevelDescriptorFields", sb.toString()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -109,27 +104,27 @@ else if (o != null) this.levelZeroTileDelta = (LatLon) params.getValue(AVKey.LEVEL_ZERO_TILE_DELTA); o = params.getValue(AVKey.TILE_ORIGIN); - if (o != null && o instanceof LatLon) + if (o != null && o instanceof LatLon) { this.tileOrigin = (LatLon) o; - else + } else { this.tileOrigin = new LatLon(Angle.NEG90, Angle.NEG180); + } params = params.copy(); // copy so as not to modify the user's params TileUrlBuilder tub = (TileUrlBuilder) params.getValue(AVKey.TILE_URL_BUILDER); - if (tub == null) - { - params.setValue(AVKey.TILE_URL_BUILDER, new TileUrlBuilder() - { - public URL getURL(Tile tile, String altImageFormat) throws MalformedURLException - { + if (tub == null) { + params.setValue(AVKey.TILE_URL_BUILDER, new TileUrlBuilder() { + public URL getURL(Tile tile, String altImageFormat) throws MalformedURLException { String service = tile.getLevel().getService(); - if (service == null || service.length() < 1) + if (service == null || service.length() < 1) { return null; + } StringBuffer sb = new StringBuffer(tile.getLevel().getService()); - if (sb.lastIndexOf("?") != sb.length() - 1) + if (sb.lastIndexOf("?") != sb.length() - 1) { sb.append("?"); + } sb.append("T="); sb.append(tile.getLevel().getDataset()); sb.append("&L="); @@ -145,12 +140,9 @@ public URL getURL(Tile tile, String altImageFormat) throws MalformedURLException }); } - if (this.sectorLevelLimits != null) - { - Arrays.sort(this.sectorLevelLimits, new Comparator() - { - public int compare(SectorResolution sra, SectorResolution srb) - { + if (this.sectorLevelLimits != null) { + Arrays.sort(this.sectorLevelLimits, new Comparator() { + public int compare(SectorResolution sra, SectorResolution srb) { // sort order is deliberately backwards in order to list higher-resolution sectors first return sra.levelNumber < srb.levelNumber ? 1 : sra.levelNumber == srb.levelNumber ? 0 : -1; } @@ -160,13 +152,12 @@ public int compare(SectorResolution sra, SectorResolution srb) // Compute the number of level zero columns. This value is guaranteed to be a nonzero number, since there is // generally at least one level zero tile. int firstLevelZeroCol = Tile.computeColumn(this.levelZeroTileDelta.getLongitude(), - this.sector.getMinLongitude(), this.tileOrigin.getLongitude()); + this.sector.getMinLongitude(), this.tileOrigin.getLongitude()); int lastLevelZeroCol = Tile.computeColumn(this.levelZeroTileDelta.getLongitude(), this.sector.getMaxLongitude(), - this.tileOrigin.getLongitude()); + this.tileOrigin.getLongitude()); this.numLevelZeroColumns = Math.max(1, lastLevelZeroCol - firstLevelZeroCol + 1); - for (int i = 0; i < numLevels; i++) - { + for (int i = 0; i < numLevels; i++) { params.setValue(AVKey.LEVEL_NAME, i < numEmptyLevels ? "" : Integer.toString(i - numEmptyLevels)); params.setValue(AVKey.LEVEL_NUMBER, i); @@ -177,20 +168,16 @@ public int compare(SectorResolution sra, SectorResolution srb) this.levels.add(new Level(params)); } - if (inactiveLevels != null) - { - for (String s : inactiveLevels) - { + if (inactiveLevels != null) { + for (String s : inactiveLevels) { int i = Integer.parseInt(s); this.getLevel(i).setActive(false); } } } - public LevelSet(LevelSet source) - { - if (source == null) - { + public LevelSet(LevelSet source) { + if (source == null) { String msg = Logging.getMessage("nullValue.LevelSetIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -202,18 +189,15 @@ public LevelSet(LevelSet source) this.numLevelZeroColumns = source.numLevelZeroColumns; this.sectorLevelLimits = source.sectorLevelLimits; - for (Level level : source.levels) - { + for (Level level : source.levels) { this.levels.add(level); // Levels are final, so it's safe to copy references. } } @Override - public Object setValue(String key, Object value) - { + public Object setValue(String key, Object value) { // Propogate the setting to all levels - for (Level level : this.levels) - { + for (Level level : this.levels) { level.setValue(key, value); } @@ -221,42 +205,39 @@ public Object setValue(String key, Object value) } @Override - public Object getValue(String key) - { + public Object getValue(String key) { Object value = super.getValue(key); - if (value != null) + if (value != null) { return value; + } // See if any level has it - for (Level level : this.getLevels()) - { - if (level != null && (value = level.getValue(key)) != null) + for (Level level : this.getLevels()) { + if (level != null && (value = level.getValue(key)) != null) { return value; + } } return null; } - public final Sector getSector() - { + public final Sector getSector() { return this.sector; } - public final LatLon getLevelZeroTileDelta() - { + public final LatLon getLevelZeroTileDelta() { return this.levelZeroTileDelta; } - public final LatLon getTileOrigin() - { + public final LatLon getTileOrigin() { return this.tileOrigin; } - public final SectorResolution[] getSectorLevelLimits() - { - if (this.sectorLevelLimits == null) + public final SectorResolution[] getSectorLevelLimits() { + if (this.sectorLevelLimits == null) { return null; + } // The SectorResolution instances themselves are immutable. However the entries in a Java array cannot be made // immutable, therefore we create a copy to insulate ourselves from changes by the caller. @@ -266,106 +247,91 @@ public final SectorResolution[] getSectorLevelLimits() return copy; } - public final ArrayList getLevels() - { + public final ArrayList getLevels() { return this.levels; } - public final Level getLevel(int levelNumber) - { + public final Level getLevel(int levelNumber) { return (levelNumber >= 0 && levelNumber < this.levels.size()) ? this.levels.get(levelNumber) : null; } - public final int getNumLevels() - { + public final int getNumLevels() { return this.levels.size(); } - public final Level getFirstLevel() - { + public final Level getFirstLevel() { return this.getLevel(0); } - public final Level getLastLevel() - { + public final Level getLastLevel() { return this.getLevel(this.getNumLevels() - 1); } - public final Level getNextToLastLevel() - { + public final Level getNextToLastLevel() { return this.getLevel(this.getNumLevels() > 1 ? this.getNumLevels() - 2 : 0); } - public final Level getLastLevel(Sector sector) - { - if (sector == null) - { + public final Level getLastLevel(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.getSector().intersects(sector)) + if (!this.getSector().intersects(sector)) { return null; + } Level level = this.getLevel(this.getNumLevels() - 1); - if (this.sectorLevelLimits != null) - for (SectorResolution sr : this.sectorLevelLimits) - { - if (sr.sector.intersects(sector) && sr.levelNumber <= level.getLevelNumber()) - { + if (this.sectorLevelLimits != null) { + for (SectorResolution sr : this.sectorLevelLimits) { + if (sr.sector.intersects(sector) && sr.levelNumber <= level.getLevelNumber()) { level = this.getLevel(sr.levelNumber); break; } } + } return level; } - public final Level getLastLevel(Angle latitude, Angle longitude) - { + public final Level getLastLevel(Angle latitude, Angle longitude) { Level level = this.getLevel(this.getNumLevels() - 1); - if (this.sectorLevelLimits != null) - for (SectorResolution sr : this.sectorLevelLimits) - { - if (sr.sector.contains(latitude, longitude) && sr.levelNumber <= level.getLevelNumber()) - { + if (this.sectorLevelLimits != null) { + for (SectorResolution sr : this.sectorLevelLimits) { + if (sr.sector.contains(latitude, longitude) && sr.levelNumber <= level.getLevelNumber()) { level = this.getLevel(sr.levelNumber); break; } } + } return level; } - public final boolean isFinalLevel(int levelNum) - { + public final boolean isFinalLevel(int levelNum) { return levelNum == this.getNumLevels() - 1; } - public final boolean isLevelEmpty(int levelNumber) - { + public final boolean isLevelEmpty(int levelNumber) { return this.levels.get(levelNumber).isEmpty(); } - private int numColumnsInLevel(Level level) - { + private int numColumnsInLevel(Level level) { int levelDelta = level.getLevelNumber() - this.getFirstLevel().getLevelNumber(); double twoToTheN = Math.pow(2, levelDelta); return (int) (twoToTheN * this.numLevelZeroColumns); } - private long getTileNumber(Tile tile) - { + private long getTileNumber(Tile tile) { return tile.getRow() < 0 ? -1 : (long) tile.getRow() * this.numColumnsInLevel(tile.getLevel()) + tile.getColumn(); } - private long getTileNumber(TileKey tileKey) - { - return tileKey.getRow() < 0 ? -1 : - (long) tileKey.getRow() * this.numColumnsInLevel(this.getLevel(tileKey.getLevelNumber())) + tileKey.getColumn(); + private long getTileNumber(TileKey tileKey) { + return tileKey.getRow() < 0 ? -1 + : (long) tileKey.getRow() * this.numColumnsInLevel(this.getLevel(tileKey.getLevelNumber())) + tileKey.getColumn(); } /** @@ -375,10 +341,8 @@ private long getTileNumber(TileKey tileKey) * * @throws IllegalArgumentException if tile is null */ - public final void markResourceAbsent(Tile tile) - { - if (tile == null) - { + public final void markResourceAbsent(Tile tile) { + if (tile == null) { String msg = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -396,10 +360,8 @@ public final void markResourceAbsent(Tile tile) * * @throws IllegalArgumentException if tile is null */ - public final boolean isResourceAbsent(TileKey tileKey) - { - if (tileKey == null) - { + public final boolean isResourceAbsent(TileKey tileKey) { + if (tileKey == null) { String msg = Logging.getMessage("nullValue.TileKeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -418,10 +380,8 @@ public final boolean isResourceAbsent(TileKey tileKey) * * @throws IllegalArgumentException if tile is null */ - public final boolean isResourceAbsent(Tile tile) - { - if (tile == null) - { + public final boolean isResourceAbsent(Tile tile) { + if (tile == null) { String msg = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -437,10 +397,8 @@ public final boolean isResourceAbsent(Tile tile) * * @throws IllegalArgumentException if tile is null */ - public final void unmarkResourceAbsent(Tile tile) - { - if (tile == null) - { + public final void unmarkResourceAbsent(Tile tile) { + if (tile == null) { String msg = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -450,10 +408,8 @@ public final void unmarkResourceAbsent(Tile tile) } // Create the tile corresponding to a specified key. - public Sector computeSectorForKey(TileKey key) - { - if (key == null) - { + public Sector computeSectorForKey(TileKey key) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -474,10 +430,8 @@ public Sector computeSectorForKey(TileKey key) } // Create the tile corresponding to a specified key. - public Tile createTile(TileKey key) - { - if (key == null) - { + public Tile createTile(TileKey key) { + if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -499,10 +453,8 @@ public Tile createTile(TileKey key) return new Tile(tileSector, level, key.getRow(), key.getColumn()); } - public void setExpiryTime(long expiryTime) - { - for (Level level : this.levels) - { + public void setExpiryTime(long expiryTime) { + for (Level level : this.levels) { level.setExpiryTime(expiryTime); } } diff --git a/src/gov/nasa/worldwind/util/Logging.java b/src/gov/nasa/worldwind/util/Logging.java index 0af0083035..a24bf1164e 100644 --- a/src/gov/nasa/worldwind/util/Logging.java +++ b/src/gov/nasa/worldwind/util/Logging.java @@ -23,13 +23,12 @@ * @see gov.nasa.worldwind.Configuration * @see java.util.logging */ -public class Logging -{ +public class Logging { + protected static final String MESSAGE_BUNDLE_NAME = Logging.class.getPackage().getName() + ".MessageStrings"; protected static final int MAX_MESSAGE_REPEAT = Configuration.getIntegerValue(AVKey.MAX_MESSAGE_REPEAT, 10); - private Logging() - { + private Logging() { } // Prevent instantiation /** @@ -37,17 +36,13 @@ private Logging() * * @return The logger. */ - public static Logger logger() - { - try - { + public static Logger logger() { + try { // The Configuration singleton may not be established yet, so catch the exception that occurs if it's not // and use the default logger name. String loggerName = Configuration.getStringValue(AVKey.LOGGER_NAME, Configuration.DEFAULT_LOGGER_NAME); return logger(loggerName); - } - catch (Exception e) - { + } catch (Exception e) { return logger(Configuration.DEFAULT_LOGGER_NAME); } } @@ -63,8 +58,7 @@ public static Logger logger() * * @return The logger. */ - public static Logger logger(String loggerName) - { + public static Logger logger(String loggerName) { return Logger.getLogger(loggerName != null ? loggerName : "", MESSAGE_BUNDLE_NAME); } @@ -75,14 +69,10 @@ public static Logger logger(String loggerName) * * @return The requested message. */ - public static String getMessage(String property) - { - try - { + public static String getMessage(String property) { + try { return (String) ResourceBundle.getBundle(MESSAGE_BUNDLE_NAME, Locale.getDefault()).getObject(property); - } - catch (Exception e) - { + } catch (Exception e) { String message = "Exception looking up message from bundle " + MESSAGE_BUNDLE_NAME; logger().log(java.util.logging.Level.SEVERE, message, e); return message; @@ -94,14 +84,13 @@ public static String getMessage(String property) * inserted into the message via {@link java.text.MessageFormat}. * * @param property the property identifying which message to retrieve. - * @param arg the single argument referenced by the format string identified property. + * @param arg the single argument referenced by the format string identified property. * * @return The requested string formatted with the argument. * * @see java.text.MessageFormat */ - public static String getMessage(String property, String arg) - { + public static String getMessage(String property, String arg) { return arg != null ? getMessage(property, (Object) arg) : getMessage(property); } @@ -110,34 +99,27 @@ public static String getMessage(String property, String arg) * are inserted into the message via {@link java.text.MessageFormat}. * * @param property the property identifying which message to retrieve. - * @param args the arguments referenced by the format string identified property. + * @param args the arguments referenced by the format string identified property. * * @return The requested string formatted with the arguments. * * @see java.text.MessageFormat */ - public static String getMessage(String property, Object... args) - { + public static String getMessage(String property, Object... args) { String message; - try - { + try { message = (String) ResourceBundle.getBundle(MESSAGE_BUNDLE_NAME, Locale.getDefault()).getObject(property); - } - catch (Exception e) - { + } catch (Exception e) { message = "Exception looking up message from bundle " + MESSAGE_BUNDLE_NAME; logger().log(Level.SEVERE, message, e); return message; } - try - { + try { // TODO: This is no longer working with more than one arg in the message string, e.g., {1} return args == null ? message : MessageFormat.format(message, args); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { message = "Message arguments do not match format string: " + property; logger().log(Level.SEVERE, message, e); return message; @@ -150,8 +132,7 @@ public static String getMessage(String property, Object... args) * * @return the maximum number of times to repeat a message. */ - public static int getMaxMessageRepeatCount() - { + public static int getMaxMessageRepeatCount() { return MAX_MESSAGE_REPEAT; } } diff --git a/src/gov/nasa/worldwind/util/NativeLibraryLoader.java b/src/gov/nasa/worldwind/util/NativeLibraryLoader.java index 0825660d30..25ed91e72f 100644 --- a/src/gov/nasa/worldwind/util/NativeLibraryLoader.java +++ b/src/gov/nasa/worldwind/util/NativeLibraryLoader.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.exception.WWRuntimeException; @@ -12,52 +11,43 @@ * @author Lado Garakanidze * @version $Id: NativeLibraryLoader.java 1171 2013-02-11 21:45:02Z dcollins $ */ +public class NativeLibraryLoader { -public class NativeLibraryLoader -{ - public static void loadLibrary(String libName) throws WWRuntimeException, IllegalArgumentException - { - if (WWUtil.isEmpty(libName)) - { + public static void loadLibrary(String libName) throws WWRuntimeException, IllegalArgumentException { + if (WWUtil.isEmpty(libName)) { String message = Logging.getMessage("nullValue.LibraryIsNull"); throw new IllegalArgumentException(message); } - try - { + try { System.loadLibrary(libName); - } - catch (java.lang.UnsatisfiedLinkError ule) - { + } catch (java.lang.UnsatisfiedLinkError ule) { String message = Logging.getMessage("generic.LibraryNotLoaded", libName, ule.getMessage()); throw new WWRuntimeException(message); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = Logging.getMessage("generic.LibraryNotLoaded", libName, t.getMessage()); throw new WWRuntimeException(message); } } - protected static String makeFullLibName(String libName) - { - if (WWUtil.isEmpty(libName)) + protected static String makeFullLibName(String libName) { + if (WWUtil.isEmpty(libName)) { return null; + } - if (gov.nasa.worldwind.Configuration.isWindowsOS()) - { - if (!libName.toLowerCase().endsWith(".dll")) + if (gov.nasa.worldwind.Configuration.isWindowsOS()) { + if (!libName.toLowerCase().endsWith(".dll")) { return libName + ".dll"; - } - else if (gov.nasa.worldwind.Configuration.isMacOS()) - { - if (!libName.toLowerCase().endsWith(".jnilib") && !libName.toLowerCase().startsWith("lib")) + } + } else if (gov.nasa.worldwind.Configuration.isMacOS()) { + if (!libName.toLowerCase().endsWith(".jnilib") && !libName.toLowerCase().startsWith("lib")) { return "lib" + libName + ".jnilib"; - } - else if (gov.nasa.worldwind.Configuration.isUnixOS()) // covers Solaris and Linux + } + } else if (gov.nasa.worldwind.Configuration.isUnixOS()) // covers Solaris and Linux { - if (!libName.toLowerCase().endsWith(".so") && !libName.toLowerCase().startsWith("lib")) + if (!libName.toLowerCase().endsWith(".so") && !libName.toLowerCase().startsWith("lib")) { return "lib" + libName + ".so"; + } } return libName; } diff --git a/src/gov/nasa/worldwind/util/NetworkCheckThread.java b/src/gov/nasa/worldwind/util/NetworkCheckThread.java index 2e7623f8fb..60d8410d82 100644 --- a/src/gov/nasa/worldwind/util/NetworkCheckThread.java +++ b/src/gov/nasa/worldwind/util/NetworkCheckThread.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util; import gov.nasa.worldwind.WorldWind; @@ -16,8 +15,8 @@ * @author tag * @version $Id: NetworkCheckThread.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NetworkCheckThread extends Thread -{ +public class NetworkCheckThread extends Thread { + protected static final long DEFAULT_NET_CHECK_INTERVAL = 1000; // milliseconds protected AtomicBoolean showNetStatus; @@ -29,24 +28,20 @@ public class NetworkCheckThread extends Thread * frequency and stores the result in an atomic variable specified to the constructor. The thread terminates when * it's interrupted or when a specified boolean atomic variable has the value false. * - * @param showNetStatus a reference to an atomic variable indicating whether the thread should continue running. - * This variable is tested prior to each network check. The thread terminates when it becomes - * false. + * @param showNetStatus a reference to an atomic variable indicating whether the thread should continue running. + * This variable is tested prior to each network check. The thread terminates when it becomes false. * @param isNetAvailable a reference to an atomic variable in which to write the status of the network check. - * @param interval the interval at which to perform the network check, or null if the default interval of one - * second is to be used. + * @param interval the interval at which to perform the network check, or null if the default interval of one second + * is to be used. */ - public NetworkCheckThread(AtomicBoolean showNetStatus, AtomicBoolean isNetAvailable, Long interval) - { - if (showNetStatus == null) - { + public NetworkCheckThread(AtomicBoolean showNetStatus, AtomicBoolean isNetAvailable, Long interval) { + if (showNetStatus == null) { String msg = Logging.getMessage("nullValue.StatusReferenceIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (isNetAvailable == null) - { + if (isNetAvailable == null) { String msg = Logging.getMessage("nullValue.ReturnReferenceIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -55,23 +50,19 @@ public NetworkCheckThread(AtomicBoolean showNetStatus, AtomicBoolean isNetAvaila this.showNetStatus = showNetStatus; this.isNetAvailable = isNetAvailable; - if (interval != null && interval > 0) + if (interval != null && interval > 0) { this.netChecInterval.set(interval); + } } @Override - public void run() - { - while (showNetStatus.get() && !Thread.currentThread().isInterrupted()) - { + public void run() { + while (showNetStatus.get() && !Thread.currentThread().isInterrupted()) { //noinspection EmptyCatchBlock - try - { + try { Thread.sleep(DEFAULT_NET_CHECK_INTERVAL); this.isNetAvailable.set(!WorldWind.getNetworkStatus().isNetworkUnavailable()); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { // Intentionally empty } } diff --git a/src/gov/nasa/worldwind/util/NetworkStatus.java b/src/gov/nasa/worldwind/util/NetworkStatus.java index 2ff20b4ecf..3838dc5aaf 100644 --- a/src/gov/nasa/worldwind/util/NetworkStatus.java +++ b/src/gov/nasa/worldwind/util/NetworkStatus.java @@ -31,8 +31,8 @@ * @author tag * @version $Id: NetworkStatus.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface NetworkStatus extends AVList -{ +public interface NetworkStatus extends AVList { + public static final String HOST_UNAVAILABLE = "gov.nasa.worldwind.util.NetworkStatus.HostUnavailable"; public static final String HOST_AVAILABLE = "gov.nasa.worldwind.util.NetworkStatus.HostAvailable"; @@ -73,7 +73,7 @@ public interface NetworkStatus extends AVList * Indicates whether a public network can be reached or has been reached in a specified previous amount of time. * * @param checkInterval the number of milliseconds in the past used to determine whether the server was avaialble - * recently. + * recently. * * @return false if the network can be reached or has been reached in a specified time, otherwise true. */ @@ -139,7 +139,7 @@ public interface NetworkStatus extends AVList * Returns the server domain names of the sites used to test public network availability. * * @return the list of sites used to check network status. The list is a copy of the internal list, so changes to it - * do not affect instances of this class. + * do not affect instances of this class. */ List getNetworkTestSites(); @@ -147,8 +147,7 @@ public interface NetworkStatus extends AVList * Sets the domain names, e.g., worldwind.arc.nasa.gov, of sites used to determine public network availability. * * @param networkTestSites the list of desired test sites. The list is copied internally, so changes made to the - * submitted list do not affect instances of this class. May be null, in which case no sites - * are consulted. + * submitted list do not affect instances of this class. May be null, in which case no sites are consulted. */ void setNetworkTestSites(List networkTestSites); } diff --git a/src/gov/nasa/worldwind/util/OGLRenderToTextureSupport.java b/src/gov/nasa/worldwind/util/OGLRenderToTextureSupport.java index 8329905459..a10de3074a 100644 --- a/src/gov/nasa/worldwind/util/OGLRenderToTextureSupport.java +++ b/src/gov/nasa/worldwind/util/OGLRenderToTextureSupport.java @@ -21,7 +21,8 @@ * texture. For this reason, OGLRenderToTextureSupport must be used when the contents of the windowing system buffer * (likely the back framebuffer) can be freely modified by OGLRenderToTextureSupport. The WorldWind pre-render stage is * a good example of when it is appropriate to use OGLRenderToTextureSupport. Fore more information on the pre-render - * stage, see {@link gov.nasa.worldwind.render.PreRenderable} and {@link gov.nasa.worldwind.layers.Layer#preRender(gov.nasa.worldwind.render.DrawContext)}. + * stage, see {@link gov.nasa.worldwind.render.PreRenderable} and + * {@link gov.nasa.worldwind.layers.Layer#preRender(gov.nasa.worldwind.render.DrawContext)}. * Note: In order to achieve consistent results across all platforms, it is essential to clear the texture's * contents before rendering anything into the texture. Do this by invoking {@link * #clear(gov.nasa.worldwind.render.DrawContext, java.awt.Color)} immediately after any call to {@link @@ -31,25 +32,26 @@ * passed in as an argument to the containing method.
                  Texture texture = TextureIO.newTexture(new * TextureData(...);

                  // Setup the drawing rectangle to match the texture dimensions, and originate from the * texture's lower left corner.
                  OGLRenderToTextureSupport rttSupport = new OGLRenderToTextureSupport();
                  - * rttSupport.beginRendering(dc, 0, 0, texture.getWidth(), texture.getHeight());
                  try
                  {
                  // Bind the - * texture as the destination for color pixel writes.
                  rttSupport.setColorTarget(dc, texture);
                  // Clear the - * texture contents with transparent black.
                  rttSupport.clear(dc, new Color(0, 0, 0, 0));
                  // Invoke desired GL - * rendering commands.
                  }
                  finally
                  {
                  rttSupport.endRendering(dc);
                  }
                  + * rttSupport.beginRendering(dc, 0, 0, texture.getWidth(), texture.getHeight());
                  try
                  {
                  // Bind the texture + * as the destination for color pixel writes.
                  rttSupport.setColorTarget(dc, texture);
                  // Clear the texture + * contents with transparent black.
                  rttSupport.clear(dc, new Color(0, 0, 0, 0));
                  // Invoke desired GL rendering + * commands.
                  }
                  finally
                  {
                  rttSupport.endRendering(dc);
                  }
                  * * @author dcollins * @version $Id: OGLRenderToTextureSupport.java 1676 2013-10-21 18:32:30Z dcollins $ */ -public class OGLRenderToTextureSupport -{ +public class OGLRenderToTextureSupport { + protected boolean isFramebufferObjectEnabled; protected Texture colorTarget; protected java.awt.Rectangle drawRegion; protected OGLStackHandler stackHandler; protected int framebufferObject; - /** Constructs a new OGLRenderToTextureSupport, but otherwise does nothing. */ - public OGLRenderToTextureSupport() - { + /** + * Constructs a new OGLRenderToTextureSupport, but otherwise does nothing. + */ + public OGLRenderToTextureSupport() { this.isFramebufferObjectEnabled = true; this.stackHandler = new OGLStackHandler(); } @@ -60,8 +62,7 @@ public OGLRenderToTextureSupport() * * @return true if framebuffer objects are enabled, and false otherwise. */ - public boolean isEnableFramebufferObject() - { + public boolean isEnableFramebufferObject() { return this.isFramebufferObjectEnabled; } @@ -70,8 +71,7 @@ public boolean isEnableFramebufferObject() * * @param enable true to enable framebuffer objects, false to disable them. */ - public void setEnableFramebufferObject(boolean enable) - { + public void setEnableFramebufferObject(boolean enable) { this.isFramebufferObjectEnabled = enable; } @@ -81,8 +81,7 @@ public void setEnableFramebufferObject(boolean enable) * * @return the Texture currently set as the color buffer target, or null if none exists. */ - public Texture getColorTarget() - { + public Texture getColorTarget() { return this.colorTarget; } @@ -99,28 +98,26 @@ public Texture getColorTarget() * follows:

                  • RGB
                  • RGBA
                  • FLOAT_R_NV (on NVidia hardware)
                  • FLOAT_RG_NV (on NVidia * hardware)
                  • FLOAT_RGB_NV (on NVidia hardware)
                  • FLOAT_RGBA_NV (on NVidia hardware)
                  * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param texture the Texture to use as the destination for GL commands affecting the color buffer. A null value is - * permitted. + * permitted. * * @throws IllegalArgumentException if the DrawContext is null. */ - public void setColorTarget(DrawContext dc, Texture texture) - { - if (dc == null) - { + public void setColorTarget(DrawContext dc, Texture texture) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.colorTarget == texture) + if (this.colorTarget == texture) { return; + } // If we have a texture target, then write the current GL color buffer state to the current texture target // before binding a new target. - if (this.colorTarget != null) - { + if (this.colorTarget != null) { this.flushColor(dc); } @@ -128,8 +125,7 @@ public void setColorTarget(DrawContext dc, Texture texture) // attachment, and GL rendering commands then affect the target texture. Otherwise, GL rendering commands affect // the windowing system's write buffer (likely the onscreen back buffer), and are explicitly copied to the // texture in flush() or endRendering(). - if (this.useFramebufferObject(dc)) - { + if (this.useFramebufferObject(dc)) { this.bindFramebufferColorAttachment(dc, texture); } @@ -140,29 +136,27 @@ public void setColorTarget(DrawContext dc, Texture texture) * Clears the current texture target's pixels with the specified RGBA clear color. If the current color texture * target is null, this does nothing. * - * @param dc the current DrawContext. + * @param dc the current DrawContext. * @param color the RGBA clear color to write to the current color texture target. * * @throws IllegalArgumentException if either the DrawContext or the color is null. */ - public void clear(DrawContext dc, java.awt.Color color) - { - if (dc == null) - { + public void clear(DrawContext dc, java.awt.Color color) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (color == null) - { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.colorTarget == null) + if (this.colorTarget == null) { return; + } float[] compArray = new float[4]; color.getRGBComponents(compArray); @@ -183,10 +177,8 @@ public void clear(DrawContext dc, java.awt.Color color) * * @throws IllegalArgumentException if the DrawContext is null. */ - public void flush(DrawContext dc) - { - if (dc == null) - { + public void flush(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -204,18 +196,16 @@ public void flush(DrawContext dc) * affected by GL commands. Once rendering is complete, this should always be followed with a call to {@link * #endRendering(gov.nasa.worldwind.render.DrawContext)}. * - * @param dc the current DrawContext. - * @param x the x-coordinate of the draw region's lower left corner. - * @param y the y-coordinate of the draw region's lower left corner. - * @param width the draw region width. + * @param dc the current DrawContext. + * @param x the x-coordinate of the draw region's lower left corner. + * @param y the y-coordinate of the draw region's lower left corner. + * @param width the draw region width. * @param height the draw region height. * * @throws IllegalArgumentException if the DrawContext is null. */ - public void beginRendering(DrawContext dc, int x, int y, int width, int height) - { - if (dc == null) - { + public void beginRendering(DrawContext dc, int x, int y, int width, int height) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -228,10 +218,10 @@ public void beginRendering(DrawContext dc, int x, int y, int width, int height) // Note: there is no attribute bit for framebuffer objects. The default framebuffer object state (object ID 0 // is bound as the current fbo) is restored in endRendering(). this.stackHandler.pushAttrib(gl, - GL2.GL_COLOR_BUFFER_BIT // For clear color. + GL2.GL_COLOR_BUFFER_BIT // For clear color. | GL2.GL_DEPTH_BUFFER_BIT // For depth test and depth mask. - | GL2.GL_SCISSOR_BIT // For scissor test and scissor box. - | GL2.GL_TRANSFORM_BIT // For matrix mode. + | GL2.GL_SCISSOR_BIT // For scissor test and scissor box. + | GL2.GL_TRANSFORM_BIT // For matrix mode. | GL2.GL_VIEWPORT_BIT); // For viewport state. this.stackHandler.pushTextureIdentity(gl); @@ -252,8 +242,7 @@ public void beginRendering(DrawContext dc, int x, int y, int width, int height) gl.glScissor(x, y, width, height); gl.glViewport(x, y, width, height); - if (this.useFramebufferObject(dc)) - { + if (this.useFramebufferObject(dc)) { this.beginFramebufferObjectRendering(dc); } } @@ -267,10 +256,8 @@ public void beginRendering(DrawContext dc, int x, int y, int width, int height) * * @throws IllegalArgumentException if the DrawContext is null. */ - public void endRendering(DrawContext dc) - { - if (dc == null) - { + public void endRendering(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -280,10 +267,8 @@ public void endRendering(DrawContext dc) this.flush(dc); - if (this.useFramebufferObject(dc)) - { - if (this.colorTarget != null) - { + if (this.useFramebufferObject(dc)) { + if (this.colorTarget != null) { this.bindFramebufferColorAttachment(dc, null); } @@ -295,54 +280,50 @@ public void endRendering(DrawContext dc) this.colorTarget = null; } - protected void flushColor(DrawContext dc) - { + protected void flushColor(DrawContext dc) { // If framebuffer objects are enabled, then texture contents are already affected by the any GL rendering // commands. - if (this.useFramebufferObject(dc)) - { - if (this.colorTarget != null) - { + if (this.useFramebufferObject(dc)) { + if (this.colorTarget != null) { // If the color target is attempting to use automatic mipmap generation, then we must manually update // its mipmap chain. Automatic mipmap generation is invoked when the GL client explicitly modifies the // texture contents by calling one of glTexImage or glTexSubImage. However when we render directly to // the texture using framebuffer objects, automatic mipmap generation is not invoked, and the texture's // mipmap chain contents are undefined until we explicitly update them. - if (this.colorTarget.isUsingAutoMipmapGeneration()) + if (this.colorTarget.isUsingAutoMipmapGeneration()) { this.updateMipmaps(dc, this.colorTarget); + } } - } - // If framebuffer objects are not enabled, then we've been rendering into the read buffer associated with the + } // If framebuffer objects are not enabled, then we've been rendering into the read buffer associated with the // windowing system (likely the onscreen back buffer). Explicitly copy the read buffer contents to the texture. - else - { - if (this.colorTarget != null) - { + else { + if (this.colorTarget != null) { this.copyScreenPixelsToTexture(dc, this.drawRegion.x, this.drawRegion.y, - this.drawRegion.width, this.drawRegion.height, this.colorTarget); + this.drawRegion.width, this.drawRegion.height, this.colorTarget); } } } - protected void copyScreenPixelsToTexture(DrawContext dc, int x, int y, int width, int height, Texture texture) - { + protected void copyScreenPixelsToTexture(DrawContext dc, int x, int y, int width, int height, Texture texture) { int w = width; int h = height; // If the lower left corner of the region to copy is outside of the texture bounds, then exit and do nothing. - if (x >= texture.getWidth() || y >= texture.getHeight()) + if (x >= texture.getWidth() || y >= texture.getHeight()) { return; + } // Limit the dimensions of the region to copy so they fit into the texture's dimensions. - if (w > texture.getWidth()) + if (w > texture.getWidth()) { w = texture.getWidth(); - if (h > texture.getHeight()) + } + if (h > texture.getHeight()) { h = texture.getHeight(); + } GL gl = dc.getGL(); - try - { + try { // We want to copy the contents of the current GL read buffer to the specified texture target. However we do // not want to change any of the texture creation parameters (e.g. dimensions, internal format, border). // Therefore we use glCopyTexSubImage2D() to copy a region of the read buffer to a region of the texture. @@ -354,40 +335,32 @@ protected void copyScreenPixelsToTexture(DrawContext dc, int x, int y, int width texture.enable(gl); texture.bind(gl); gl.glCopyTexSubImage2D( - texture.getTarget(), // target - 0, // level - x, y, // xoffset, yoffset - x, y, w, h); // x, y, width, height - } - finally - { + texture.getTarget(), // target + 0, // level + x, y, // xoffset, yoffset + x, y, w, h); // x, y, width, height + } finally { texture.disable(gl); } } - protected void updateMipmaps(DrawContext dc, Texture texture) - { + protected void updateMipmaps(DrawContext dc, Texture texture) { GL gl = dc.getGL(); - try - { + try { texture.enable(gl); texture.bind(gl); gl.glGenerateMipmap(texture.getTarget()); - } - finally - { + } finally { texture.disable(gl); } } - protected boolean useFramebufferObject(DrawContext dc) - { + protected boolean useFramebufferObject(DrawContext dc) { return this.isEnableFramebufferObject() && dc.getGLRuntimeCapabilities().isUseFramebufferObject(); } - protected void beginFramebufferObjectRendering(DrawContext dc) - { + protected void beginFramebufferObjectRendering(DrawContext dc) { // Binding a framebuffer object causes all GL operations to operate on the attached textures and renderbuffers // (if any). @@ -398,18 +371,16 @@ protected void beginFramebufferObjectRendering(DrawContext dc) gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, framebuffers[0]); this.framebufferObject = framebuffers[0]; - if (this.framebufferObject == 0) - { + if (this.framebufferObject == 0) { throw new IllegalStateException("Frame Buffer Object not created."); } } - protected void endFramebufferObjectRendering(DrawContext dc) - { + protected void endFramebufferObjectRendering(DrawContext dc) { // Binding framebuffer object 0 (the default) causes GL operations to operate on the window system attached // framebuffer. - int[] framebuffers = new int[] {this.framebufferObject}; + int[] framebuffers = new int[]{this.framebufferObject}; GL gl = dc.getGL(); gl.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0); @@ -418,46 +389,38 @@ protected void endFramebufferObjectRendering(DrawContext dc) this.framebufferObject = 0; } - protected void bindFramebufferColorAttachment(DrawContext dc, Texture texture) - { + protected void bindFramebufferColorAttachment(DrawContext dc, Texture texture) { GL gl = dc.getGL(); // Attach the texture as color attachment 0 to the framebuffer. - if (texture != null) - { + if (texture != null) { gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, - texture.getTextureObject(gl), 0); + texture.getTextureObject(gl), 0); this.checkFramebufferStatus(dc); - } - // If the texture is null, detach color attachment 0 from the framebuffer. - else - { + } // If the texture is null, detach color attachment 0 from the framebuffer. + else { gl.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, 0, 0); } } - protected void checkFramebufferStatus(DrawContext dc) - { + protected void checkFramebufferStatus(DrawContext dc) { int status = dc.getGL().glCheckFramebufferStatus(GL.GL_FRAMEBUFFER); - switch (status) - { + switch (status) { // Framebuffer is configured correctly and supported on this hardware. case GL.GL_FRAMEBUFFER_COMPLETE: break; // Framebuffer is configured correctly, but not supported on this hardware. case GL.GL_FRAMEBUFFER_UNSUPPORTED: throw new IllegalStateException(getFramebufferStatusString(status)); - // Framebuffer is configured incorrectly. This should never happen, but we check anyway. + // Framebuffer is configured incorrectly. This should never happen, but we check anyway. default: throw new IllegalStateException(getFramebufferStatusString(status)); } } - protected static String getFramebufferStatusString(int status) - { - switch (status) - { + protected static String getFramebufferStatusString(int status) { + switch (status) { case GL.GL_FRAMEBUFFER_COMPLETE: return Logging.getMessage("OGL.FramebufferComplete"); case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: diff --git a/src/gov/nasa/worldwind/util/OGLStackHandler.java b/src/gov/nasa/worldwind/util/OGLStackHandler.java index 17ceed244b..bddcd33cf3 100644 --- a/src/gov/nasa/worldwind/util/OGLStackHandler.java +++ b/src/gov/nasa/worldwind/util/OGLStackHandler.java @@ -11,16 +11,15 @@ * @author tag * @version $Id: OGLStackHandler.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGLStackHandler -{ +public class OGLStackHandler { + private boolean attribsPushed; private boolean clientAttribsPushed; private boolean modelviewPushed; private boolean projectionPushed; private boolean texturePushed; - public void clear() - { + public void clear() { this.attribsPushed = false; this.clientAttribsPushed = false; this.modelviewPushed = false; @@ -28,99 +27,84 @@ public void clear() this.texturePushed = false; } - public boolean isActive() - { + public boolean isActive() { return this.attribsPushed || this.clientAttribsPushed || this.modelviewPushed || this.projectionPushed - || this.texturePushed; + || this.texturePushed; } - public void pushAttrib(GL2 gl, int mask) - { + public void pushAttrib(GL2 gl, int mask) { gl.glPushAttrib(mask); this.attribsPushed = true; } - public void pushClientAttrib(GL2 gl, int mask) - { + public void pushClientAttrib(GL2 gl, int mask) { gl.glPushClientAttrib(mask); this.clientAttribsPushed = true; } - public void pushModelview(GL2 gl) - { + public void pushModelview(GL2 gl) { gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); this.modelviewPushed = true; } - public void pushProjection(GL2 gl) - { + public void pushProjection(GL2 gl) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPushMatrix(); this.projectionPushed = true; } - public void pushTexture(GL2 gl) - { + public void pushTexture(GL2 gl) { gl.glMatrixMode(GL2.GL_TEXTURE); gl.glPushMatrix(); this.texturePushed = true; } - public void pop(GL2 gl) - { - if (this.attribsPushed) - { + public void pop(GL2 gl) { + if (this.attribsPushed) { gl.glPopAttrib(); this.attribsPushed = false; } - if (this.clientAttribsPushed) - { + if (this.clientAttribsPushed) { gl.glPopClientAttrib(); this.clientAttribsPushed = false; } - if (this.modelviewPushed) - { + if (this.modelviewPushed) { gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); this.modelviewPushed = false; } - if (this.projectionPushed) - { + if (this.projectionPushed) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); this.projectionPushed = false; } - if (this.texturePushed) - { + if (this.texturePushed) { gl.glMatrixMode(GL2.GL_TEXTURE); gl.glPopMatrix(); this.texturePushed = false; } } - public void pushModelviewIdentity(GL2 gl) - { + public void pushModelviewIdentity(GL2 gl) { gl.glMatrixMode(GL2.GL_MODELVIEW); this.modelviewPushed = true; gl.glPushMatrix(); gl.glLoadIdentity(); } - public void pushProjectionIdentity(GL2 gl) - { + public void pushProjectionIdentity(GL2 gl) { gl.glMatrixMode(GL2.GL_PROJECTION); this.projectionPushed = true; gl.glPushMatrix(); gl.glLoadIdentity(); } - public void pushTextureIdentity(GL2 gl) - { + public void pushTextureIdentity(GL2 gl) { gl.glMatrixMode(GL2.GL_TEXTURE); this.texturePushed = true; gl.glPushMatrix(); diff --git a/src/gov/nasa/worldwind/util/OGLTextRenderer.java b/src/gov/nasa/worldwind/util/OGLTextRenderer.java index 6d32390642..fcccda94ea 100644 --- a/src/gov/nasa/worldwind/util/OGLTextRenderer.java +++ b/src/gov/nasa/worldwind/util/OGLTextRenderer.java @@ -11,8 +11,7 @@ * @author dcollins * @version $Id: OGLTextRenderer.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class OGLTextRenderer extends TextRenderer -{ +public class OGLTextRenderer extends TextRenderer { // By default enable antialiasing, mipmapping, and smoothing, but disable fractional metrics and vertex arrays. // * For the common case where text is rendered without scaling at integral screen coordinates, smoothing and // mipmapping have no effect on the rendering of text. However smoothing and mipmapping will blur text @@ -32,40 +31,33 @@ public class OGLTextRenderer extends TextRenderer protected static final boolean DEFAULT_USE_VERTEX_ARRAYS = false; public OGLTextRenderer(java.awt.Font font, boolean antialiased, boolean useFractionalMetrics, - RenderDelegate renderDelegate, boolean mipmap) - { + RenderDelegate renderDelegate, boolean mipmap) { super(font, antialiased, useFractionalMetrics, renderDelegate, mipmap); this.initialize(); } public OGLTextRenderer(java.awt.Font font, boolean antialiased, boolean useFractionalMetrics, - RenderDelegate renderDelegate) - { + RenderDelegate renderDelegate) { this(font, antialiased, useFractionalMetrics, renderDelegate, DEFAULT_MIPMAP); } - public OGLTextRenderer(java.awt.Font font, boolean antialiased, boolean useFractionalMetrics) - { + public OGLTextRenderer(java.awt.Font font, boolean antialiased, boolean useFractionalMetrics) { this(font, antialiased, useFractionalMetrics, null, DEFAULT_MIPMAP); } - public OGLTextRenderer(java.awt.Font font, boolean mipmap) - { + public OGLTextRenderer(java.awt.Font font, boolean mipmap) { this(font, DEFAULT_ANTIALIAS, DEFAULT_USE_FRACTIONAL_METRICS, null, mipmap); } - public OGLTextRenderer(java.awt.Font font) - { + public OGLTextRenderer(java.awt.Font font) { this(font, DEFAULT_ANTIALIAS, DEFAULT_USE_FRACTIONAL_METRICS, null, DEFAULT_MIPMAP); } - public OGLTextRenderer() - { + public OGLTextRenderer() { this(DEFAULT_FONT, DEFAULT_ANTIALIAS, DEFAULT_USE_FRACTIONAL_METRICS, null, DEFAULT_MIPMAP); } - protected void initialize() - { + protected void initialize() { this.setSmoothing(DEFAULT_SMOOTHING); this.setUseVertexArrays(DEFAULT_USE_VERTEX_ARRAYS); @@ -92,30 +84,25 @@ protected void initialize() //**************************************************************// //******************** Common Utilities **********************// //**************************************************************// - public static TextRenderer getOrCreateTextRenderer(TextRendererCache cache, - java.awt.Font font, boolean antialiased, boolean useFractionalMetrics, boolean mipmap) - { - if (cache == null) - { + java.awt.Font font, boolean antialiased, boolean useFractionalMetrics, boolean mipmap) { + if (cache == null) { String message = Logging.getMessage("nullValue.CacheIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (font == null) - { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } TextRendererCache.CacheKey key = new TextRendererCache.CacheKey(font, antialiased, useFractionalMetrics, - mipmap); + mipmap); TextRenderer value = cache.get(key); - if (value == null) - { + if (value == null) { value = new OGLTextRenderer(font, antialiased, useFractionalMetrics, null, mipmap); cache.put(key, value); } @@ -123,17 +110,14 @@ public static TextRenderer getOrCreateTextRenderer(TextRendererCache cache, return value; } - public static TextRenderer getOrCreateTextRenderer(TextRendererCache cache, java.awt.Font font) - { - if (cache == null) - { + public static TextRenderer getOrCreateTextRenderer(TextRendererCache cache, java.awt.Font font) { + if (cache == null) { String message = Logging.getMessage("nullValue.CacheIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (font == null) - { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwind/util/OGLUtil.java b/src/gov/nasa/worldwind/util/OGLUtil.java index 90e5e9167b..138c50c335 100644 --- a/src/gov/nasa/worldwind/util/OGLUtil.java +++ b/src/gov/nasa/worldwind/util/OGLUtil.java @@ -22,12 +22,12 @@ * @author dcollins * @version $Id: OGLUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OGLUtil -{ +public class OGLUtil { + public final static int DEFAULT_TEX_ENV_MODE = GL2.GL_MODULATE; public final static int DEFAULT_TEXTURE_GEN_MODE = GL2.GL_EYE_LINEAR; - public final static double[] DEFAULT_TEXTURE_GEN_S_OBJECT_PLANE = new double[] {1, 0, 0, 0}; - public final static double[] DEFAULT_TEXTURE_GEN_T_OBJECT_PLANE = new double[] {0, 1, 0, 0}; + public final static double[] DEFAULT_TEXTURE_GEN_S_OBJECT_PLANE = new double[]{1, 0, 0, 0}; + public final static double[] DEFAULT_TEXTURE_GEN_T_OBJECT_PLANE = new double[]{0, 1, 0, 0}; public final static int DEFAULT_SRC0_RGB = GL2.GL_TEXTURE; public final static int DEFAULT_SRC1_RGB = GL2.GL_PREVIOUS; @@ -47,16 +47,14 @@ public class OGLUtil * true, this applies a blending function appropriate for colors premultiplied by the alpha component. Otherwise, * this applies a blending function appropriate for non-premultiplied colors. * - * @param gl the GL context. + * @param gl the GL context. * @param havePremultipliedColors true to configure blending for colors premultiplied by the alpha components, and - * false to configure blending for non-premultiplied colors. + * false to configure blending for non-premultiplied colors. * * @throws IllegalArgumentException if the GL is null. */ - public static void applyBlending(GL2 gl, boolean havePremultipliedColors) - { - if (gl == null) - { + public static void applyBlending(GL2 gl, boolean havePremultipliedColors) { + if (gl == null) { String message = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -65,12 +63,9 @@ public static void applyBlending(GL2 gl, boolean havePremultipliedColors) gl.glEnable(GL2.GL_ALPHA_TEST); gl.glAlphaFunc(GL2.GL_GREATER, 0.0f); - if (havePremultipliedColors) - { + if (havePremultipliedColors) { gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); - } - else - { + } else { // The separate blend function correctly handles regular (non-premultiplied) colors. We want // Cd = Cs*As + Cf*(1-As) // Ad = As + Af*(1-As) @@ -78,14 +73,11 @@ public static void applyBlending(GL2 gl, boolean havePremultipliedColors) // alpha. boolean haveExtBlendFuncSeparate = gl.isExtensionAvailable(GL_EXT_BLEND_FUNC_SEPARATE); - if (haveExtBlendFuncSeparate) - { + if (haveExtBlendFuncSeparate) { gl.glBlendFuncSeparate( - GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA, // rgb blending factors - GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); // alpha blending factors - } - else - { + GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA, // rgb blending factors + GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA); // alpha blending factors + } else { gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); } } @@ -96,33 +88,29 @@ public static void applyBlending(GL2 gl, boolean havePremultipliedColors) * If premultiplyColors is true, this premultipies the Red, Green, and Blue color values by the opacity * value. Otherwise, this does not modify the Red, Green, and Blue color values. * - * @param gl the GL context. - * @param color the Red, Green, and Blue values to set. - * @param opacity the opacity to set. + * @param gl the GL context. + * @param color the Red, Green, and Blue values to set. + * @param opacity the opacity to set. * @param premultiplyColors true to premultiply the Red, Green, and Blue color values by the opacity value, false to - * leave the Red, Green, and Blue values unmodified. + * leave the Red, Green, and Blue values unmodified. * * @throws IllegalArgumentException if the GL is null, if the Color is null, if the opacity is less than 0, or if - * the opacity is greater than 1. + * the opacity is greater than 1. */ - public static void applyColor(GL2 gl, java.awt.Color color, double opacity, boolean premultiplyColors) - { - if (gl == null) - { + public static void applyColor(GL2 gl, java.awt.Color color, double opacity, boolean premultiplyColors) { + if (gl == null) { String message = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (color == null) - { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (opacity < 0d || opacity > 1d) - { + if (opacity < 0d || opacity > 1d) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -132,8 +120,7 @@ public static void applyColor(GL2 gl, java.awt.Color color, double opacity, bool color.getRGBComponents(compArray); compArray[3] = (float) opacity; - if (premultiplyColors) - { + if (premultiplyColors) { compArray[0] *= compArray[3]; compArray[1] *= compArray[3]; compArray[2] *= compArray[3]; @@ -147,25 +134,22 @@ public static void applyColor(GL2 gl, java.awt.Color color, double opacity, bool * premultiplyColors is true, this premultipies the Red, Green, and Blue color values by the Alpha * value. Otherwise, this does not modify the Red, Green, and Blue color values. * - * @param gl the GL context. - * @param color the Red, Green, Blue, and Alpha values to set. + * @param gl the GL context. + * @param color the Red, Green, Blue, and Alpha values to set. * @param premultiplyColors true to premultiply the Red, Green and Blue color values by the Alpha value, false to - * leave the Red, Green, and Blue values unmodified. + * leave the Red, Green, and Blue values unmodified. * * @throws IllegalArgumentException if the GL is null, if the Color is null, if the opacity is less than 0, or if - * the opacity is greater than 1. + * the opacity is greater than 1. */ - public static void applyColor(GL2 gl, java.awt.Color color, boolean premultiplyColors) - { - if (gl == null) - { + public static void applyColor(GL2 gl, java.awt.Color color, boolean premultiplyColors) { + if (gl == null) { String message = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (color == null) - { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -174,8 +158,7 @@ public static void applyColor(GL2 gl, java.awt.Color color, boolean premultiplyC float[] compArray = new float[4]; color.getRGBComponents(compArray); - if (premultiplyColors) - { + if (premultiplyColors) { compArray[0] *= compArray[3]; compArray[1] *= compArray[3]; compArray[2] *= compArray[3]; @@ -190,23 +173,22 @@ public static void applyColor(GL2 gl, java.awt.Color color, boolean premultiplyC * direction. If the direction is null, this the light direction defaults to (0, 0, -1), which points directly along * the forward vector form the eye point * - * @param gl the GL context. - * @param light the GL light name to set. + * @param gl the GL context. + * @param light the GL light name to set. * @param direction the light direction in model coordinates, may be null. * * @throws IllegalArgumentException if the GL is null. */ - public static void applyLightingDirectionalFromViewer(GL2 gl, int light, Vec4 direction) - { - if (gl == null) - { + public static void applyLightingDirectionalFromViewer(GL2 gl, int light, Vec4 direction) { + if (gl == null) { String message = Logging.getMessage("nullValue.GLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (direction == null) + if (direction == null) { direction = DEFAULT_LIGHT_DIRECTION; + } float[] ambient = {1f, 1f, 1f, 0f}; float[] diffuse = {1f, 1f, 1f, 0f}; @@ -219,12 +201,9 @@ public static void applyLightingDirectionalFromViewer(GL2 gl, int light, Vec4 di OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushModelviewIdentity(gl); - try - { + try { gl.glLightfv(light, GL2.GL_POSITION, position, 0); - } - finally - { + } finally { ogsh.pop(gl); } } @@ -235,18 +214,30 @@ public static void applyLightingDirectionalFromViewer(GL2 gl, int light, Vec4 di *
                  Internal FormatPixel Format
                  GL2.GL_ALPHAGL2.GL_ALPHA
                  GL2.GL_ALPHA4GL2.GL_ALPHA
                  GL2.GL_ALPHA8GL2.GL_ALPHA
                  GL2.GL_ALPHA12GL2.GL_ALPHA
                  GL2.GL_ALPHA16GL2.GL_ALPHA
                  GL2.GL_COMPRESSED_ALPHAGL2.GL_ALPHA
                  GL2.GL_COMPRESSED_LUMINANCEGL2.GL_LUMINANCE
                  GL2.GL_COMPRESSED_LUMINANCE_ALPHAGL2.GL_LUMINANCE_ALPHA
                  GL2.GL_COMPRESSED_INTENSITYGL2.GL_RED
                  GL2.GL_COMPRESSED_RGBGL2.GL_RGB
                  GL2.GL_COMPRESSED_RGBAGL2.GL_RGBA
                  GL2.GL_DEPTH_COMPONENTGL2.GL_RED
                  GL2.GL_DEPTH_COMPONENT16GL2.GL_RED
                  GL2.GL_DEPTH_COMPONENT24GL2.GL_RED
                  GL2.GL_DEPTH_COMPONENT32GL2.GL_RED
                  GL2.GL_LUMINANCEGL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE4GL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE8GL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE12GL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE16GL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE_ALPHAGL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE4_ALPHA4GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE6_ALPHA2GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE8_ALPHA8GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE12_ALPHA4GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE12_ALPHA12GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE16_ALPHA16GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_INTENSITYGL2.GL_RED
                  GL2.GL_ALPHA16GL2.GL_ALPHA
                  GL2.GL_COMPRESSED_ALPHAGL2.GL_ALPHA
                  GL2.GL_COMPRESSED_LUMINANCEGL2.GL_LUMINANCE
                  GL2.GL_COMPRESSED_LUMINANCE_ALPHAGL2.GL_LUMINANCE_ALPHA
                  GL2.GL_COMPRESSED_INTENSITYGL2.GL_RED
                  GL2.GL_COMPRESSED_RGBGL2.GL_RGB
                  GL2.GL_COMPRESSED_RGBAGL2.GL_RGBA
                  GL2.GL_DEPTH_COMPONENTGL2.GL_RED
                  GL2.GL_DEPTH_COMPONENT16GL2.GL_RED
                  GL2.GL_DEPTH_COMPONENT24GL2.GL_RED
                  GL2.GL_DEPTH_COMPONENT32GL2.GL_RED
                  GL2.GL_LUMINANCEGL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE4GL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE8GL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE12GL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE16GL2.GL_LUMINANCE
                  GL2.GL_LUMINANCE_ALPHAGL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE4_ALPHA4GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE6_ALPHA2GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE8_ALPHA8GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE12_ALPHA4GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE12_ALPHA12GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_LUMINANCE16_ALPHA16GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_INTENSITYGL2.GL_RED
                  GL2.GL_INTENSITY4GL2.GL_RED
                  GL2.GL_INTENSITY8GL2.GL_RED
                  GL2.GL_INTENSITY12GL2.GL_RED
                  GL2.GL_INTENSITY16GL2.GL_RED
                  GL2.GL_R3_G3_B2GL2.GL_RGB
                  GL2.GL_RGBGL2.GL_RGB
                  GL2.GL_RGBA4GL2.GL_RGBA
                  GL2.GL_RGB5_A1GL2.GL_RGBA
                  GL2.GL_RGBA8GL2.GL_RGBA
                  GL2.GL_RGB10_A2GL2.GL_RGBA
                  GL2.GL_RGBA12GL2.GL_RGBA
                  GL2.GL_RGBA16GL2.GL_RGBA
                  GL2.GL_SLUMINANCEGL2.GL_LUMINANCE
                  GL2.GL_SLUMINANCE8GL2.GL_LUMINANCE
                  GL2.GL_SLUMINANCE_ALPHAGL2.GL_LUMINANCE_ALPHA
                  GL2.GL_SLUMINANCE8_ALPHA8GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_SLUMINANCEGL2.GL_LUMINANCE
                  GL2.GL_SLUMINANCE8GL2.GL_LUMINANCE
                  GL2.GL_SLUMINANCE_ALPHAGL2.GL_LUMINANCE_ALPHA
                  GL2.GL_SLUMINANCE8_ALPHA8GL2.GL_LUMINANCE_ALPHA
                  GL2.GL_SRGBGL2.GL_RGB
                  GL2.GL_SRGB8GL2.GL_RGB
                  GL2.GL_SRGB_ALPHAGL2.GL_RGBA
                  GL2.GL_SRGB8_ALPHA8GL2.GL_RGBA
                  - * + *

          GL2.GL_SRGB_ALPHAGL2.GL_RGBA
          GL2.GL_SRGB8_ALPHA8GL2.GL_RGBA
          + * *

          * This returns 0 if the internal format is not one of the recognized types. * @@ -270,10 +264,8 @@ public static void applyLightingDirectionalFromViewer(GL2 gl, int light, Vec4 di * @return a pixel format corresponding to the texture internal format, or 0 if the internal format is not * recognized. */ - public static int computeTexturePixelFormat(int internalFormat) - { - switch (internalFormat) - { + public static int computeTexturePixelFormat(int internalFormat) { + switch (internalFormat) { // Alpha pixel format. case GL2.GL_ALPHA: case GL2.GL_ALPHA4: @@ -354,7 +346,8 @@ public static int computeTexturePixelFormat(int internalFormat) *

          GL2.GL_ALPHA8
          GL2.GL_ALPHA44
          GL2.GL_ALPHA88
          GL2.GL_ALPHA1212
          GL2.GL_ALPHA1616
          GL2.GL_COMPRESSED_ALPHA0
          GL2.GL_COMPRESSED_LUMINANCE0
          GL2.GL_COMPRESSED_LUMINANCE_ALPHA0
          GL2.GL_COMPRESSED_LUMINANCE0
          GL2.GL_COMPRESSED_LUMINANCE_ALPHA0
          GL2.GL_COMPRESSED_INTENSITY0
          GL2.GL_COMPRESSED_RGB0
          GL2.GL_COMPRESSED_RGBA0
          GL2.GL_DEPTH_COMPONENT24
          GL2.GL_DEPTH_COMPONENT1616
          GL2.GL_DEPTH_COMPONENT2424
          + * constant:
          Mapping
          TextConstant
          Float32{@link AVKey#FLOAT32}
          + * * *
          Mapping
          TextConstant
          Float32{@link AVKey#FLOAT32}
          Int32{@link AVKey#INT32}
          Int16{@link AVKey#INT16}
          Int8{@link AVKey#INT8}
          * @@ -3726,23 +3344,22 @@ else if (byteOrder.equals(AVKey.BIG_ENDIAN)) * * @throws IllegalArgumentException if the string is null. */ - public static String parseDataType(String s) - { - if (s == null) - { + public static String parseDataType(String s) { + if (s == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (s.equals("Float32")) + if (s.equals("Float32")) { return AVKey.FLOAT32; - else if (s.equals("Int32")) + } else if (s.equals("Int32")) { return AVKey.INT32; - else if (s.equals("Int16")) + } else if (s.equals("Int16")) { return AVKey.INT16; - else if (s.equals("Int8")) + } else if (s.equals("Int8")) { return AVKey.INT8; + } // Warn that the data type is unrecognized. String message = Logging.getMessage("generic.UnrecognizedDataType", s); @@ -3753,7 +3370,8 @@ else if (s.equals("Int8")) /** * Returns the string text for a specified data type constant. This performs a mapping between text and an AVKey - * constant: + * constant:
          Mapping
          TextConstant
          Float32{@link AVKey#FLOAT32}
          + * * *
          Mapping
          TextConstant
          Float32{@link AVKey#FLOAT32}
          Int32{@link AVKey#INT32}
          Int16{@link AVKey#INT16}
          Int8{@link AVKey#INT8}
          * @@ -3763,23 +3381,22 @@ else if (s.equals("Int8")) * * @throws IllegalArgumentException if the data type is null. */ - public static String dataTypeAsText(String dataType) - { - if (dataType == null) - { + public static String dataTypeAsText(String dataType) { + if (dataType == null) { String message = Logging.getMessage("nullValue.DataTypeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dataType.equals(AVKey.FLOAT32)) + if (dataType.equals(AVKey.FLOAT32)) { return "Float32"; - else if (dataType.equals(AVKey.INT32)) + } else if (dataType.equals(AVKey.INT32)) { return "Int32"; - else if (dataType.equals(AVKey.INT16)) + } else if (dataType.equals(AVKey.INT16)) { return "Int16"; - else if (dataType.equals(AVKey.INT8)) + } else if (dataType.equals(AVKey.INT8)) { return "Int8"; + } // Warn that the data type is unrecognized. String message = Logging.getMessage("generic.UnrecognizedDataType", dataType); @@ -3792,44 +3409,42 @@ else if (dataType.equals(AVKey.INT8)) * Copy any Property elements in an XML document to an attribute-value list. * * @param element the XML element potentially containing Property elements. - * @param params an attribute-value list to copy the properties to. + * @param params an attribute-value list to copy the properties to. * * @return if an attribute-value list is specified, the reference to that list now containing any properties copied - * from the XML element. If an attribute-value list is not specified and properties exist in the XML - * element, a new attribute-value list containing those properties. Otherwise null is returned. + * from the XML element. If an attribute-value list is not specified and properties exist in the XML element, a new + * attribute-value list containing those properties. Otherwise null is returned. * * @throws IllegalArgumentException if the specified element is null. */ - public static AVList copyProperties(Element element, AVList params) - { - if (element == null) - { + public static AVList copyProperties(Element element, AVList params) { + if (element == null) { String message = Logging.getMessage("nullValue.ElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { XPath xpath = makeXPath(); Element[] elements = getElements(element, "Property", xpath); - if (elements == null || elements.length == 0) + if (elements == null || elements.length == 0) { return params; + } - if (params == null) + if (params == null) { params = new AVListImpl(); + } - for (Element el : elements) - { + for (Element el : elements) { String prop = xpath.evaluate("@name", el); String value = xpath.evaluate("@value", el); - if (WWUtil.isEmpty(prop) || WWUtil.isEmpty(value)) + if (WWUtil.isEmpty(prop) || WWUtil.isEmpty(value)) { continue; + } params.setValue(prop, value); } - } - catch (XPathExpressionException e) // should not occur, but log just if it does + } catch (XPathExpressionException e) // should not occur, but log just if it does { String message = Logging.getMessage("XML.InvalidXPathExpression", "internal expression"); Logging.logger().log(java.util.logging.Level.WARNING, message, e); @@ -3843,58 +3458,50 @@ public static AVList copyProperties(Element element, AVList params) * each element named "Property" in the document, the corresponding set method is called on the specified * object, if such a method exists. * - * @param parent the object on which to set the properties. + * @param parent the object on which to set the properties. * @param domElement the XML document containing the properties. * * @throws IllegalArgumentException if the specified object or XML document element is null. * @see WWUtil#invokePropertyMethod(Object, String, String) */ - public static void invokePropertySetters(Object parent, Element domElement) - { - if (parent == null) - { + public static void invokePropertySetters(Object parent, Element domElement) { + if (parent == null) { String message = Logging.getMessage("nullValue.nullValue.ParentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (domElement == null) - { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentElementIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Element[] elements = WWXML.getElements(domElement, "Property", null); - if (elements == null || elements.length == 0) + if (elements == null || elements.length == 0) { return; + } - for (Element element : elements) - { + for (Element element : elements) { String propertyName = element.getAttribute("name"); - if (WWUtil.isEmpty(propertyName)) + if (WWUtil.isEmpty(propertyName)) { continue; + } String propertyValue = element.getAttribute("value"); - try - { + try { WWUtil.invokePropertyMethod(parent, propertyName, propertyValue); - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // No property method, so just add the property to the object's AVList if it has one. - if (parent instanceof AVList) + if (parent instanceof AVList) { ((AVList) parent).setValue(propertyName, propertyValue); + } continue; // This is a benign exception; not all properties have set methods. - } - catch (InvocationTargetException e) - { + } catch (InvocationTargetException e) { String message = Logging.getMessage("generic.ExceptionInvokingPropertyMethod", propertyName, e); Logging.logger().warning(message); - } - catch (IllegalAccessException e) - { + } catch (IllegalAccessException e) { String message = Logging.getMessage("generic.ExceptionInvokingPropertyMethod", propertyName, e); Logging.logger().warning(message); } diff --git a/src/gov/nasa/worldwind/util/combine/Combinable.java b/src/gov/nasa/worldwind/util/combine/Combinable.java index e2c09ef46c..4ca4dbcbaa 100644 --- a/src/gov/nasa/worldwind/util/combine/Combinable.java +++ b/src/gov/nasa/worldwind/util/combine/Combinable.java @@ -78,8 +78,8 @@ * @see gov.nasa.worldwind.util.combine.CombineContext * @see gov.nasa.worldwind.util.combine.ShapeCombiner */ -public interface Combinable -{ +public interface Combinable { + /** * Causes this Combinable to draw its contours using the GLU tessellator attached to the provided CombineContext. * When the CombineContext is in bounding sector mode, this adds the Combinable's geographic bounding sector to the @@ -91,4 +91,4 @@ public interface Combinable * @see gov.nasa.worldwind.util.combine.CombineContext */ void combine(CombineContext cc); -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/combine/CombineContext.java b/src/gov/nasa/worldwind/util/combine/CombineContext.java index 305dcc5c33..379cab7255 100644 --- a/src/gov/nasa/worldwind/util/combine/CombineContext.java +++ b/src/gov/nasa/worldwind/util/combine/CombineContext.java @@ -32,14 +32,14 @@ * @author dcollins * @version $Id: CombineContext.java 2412 2014-10-30 21:32:34Z dcollins $ */ -public class CombineContext implements Disposable -{ +public class CombineContext implements Disposable { + /** * Implementation of GLUtessellatorCallback that forwards GLU tessellator callbacks to protected methods on * CombineContext. */ - protected static class TessCallbackAdapter extends GLUtessellatorCallbackAdapter - { + protected static class TessCallbackAdapter extends GLUtessellatorCallbackAdapter { + /** * The CombineContext that receives forwarded GLU tessellator callbacks. */ @@ -51,8 +51,7 @@ protected static class TessCallbackAdapter extends GLUtessellatorCallbackAdapter * * @param cc the CombineContext that receives forwarded GLU tessellator callbacks. */ - public TessCallbackAdapter(CombineContext cc) - { + public TessCallbackAdapter(CombineContext cc) { this.cc = cc; } @@ -62,8 +61,7 @@ public TessCallbackAdapter(CombineContext cc) * @param type the GL primitive type. */ @Override - public void begin(int type) - { + public void begin(int type) { this.cc.tessBegin(type); } @@ -73,8 +71,7 @@ public void begin(int type) * @param vertexData the caller specified vertex data. */ @Override - public void vertex(Object vertexData) - { + public void vertex(Object vertexData) { this.cc.tessVertex(vertexData); } @@ -82,23 +79,21 @@ public void vertex(Object vertexData) * Calls CombineContext.tessEnd. */ @Override - public void end() - { + public void end() { this.cc.tessEnd(); } /** * Calls CombineContext.tessCombine with the specified arguments. * - * @param coords A three element array containing the x, y and z coordinates of the new vertex. + * @param coords A three element array containing the x, y and z coordinates of the new vertex. * @param vertexData The caller specified vertex data of the original vertices. - * @param weight The coefficients of the linear combination. These weights sum to 1. - * @param outData A one element array that must contain the caller specified data associated with the new - * vertex after this method returns. + * @param weight The coefficients of the linear combination. These weights sum to 1. + * @param outData A one element array that must contain the caller specified data associated with the new vertex + * after this method returns. */ @Override - public void combine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) - { + public void combine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) { this.cc.tessCombine(coords, vertexData, weight, outData); } @@ -108,43 +103,56 @@ public void combine(double[] coords, Object[] vertexData, float[] weight, Object * @param errno a GLU enumeration indicating the error. */ @Override - public void error(int errno) - { + public void error(int errno) { this.cc.tessError(errno); } } - /** The globe associated with the context. */ + /** + * The globe associated with the context. + */ protected Globe globe; - /** A geographic sector indicating the context's region of interest. */ + /** + * A geographic sector indicating the context's region of interest. + */ protected Sector sector = Sector.FULL_SPHERE; - /** A minimum resolution in radians used to filter shape detail and compute resolution independent geometry. */ + /** + * A minimum resolution in radians used to filter shape detail and compute resolution independent geometry. + */ protected double resolution; - /** The GLU tessellator used to draw shape contours. Initalized during construction. */ + /** + * The GLU tessellator used to draw shape contours. Initalized during construction. + */ protected GLUtessellator tess; - /** The list of contours representing the result of a boolean operation on one or more Combinable shapes. */ + /** + * The list of contours representing the result of a boolean operation on one or more Combinable shapes. + */ protected ContourList contours = new ContourList(); - /** The vertices of the current contour currently being assembled. Used by the tess* methods. */ + /** + * The vertices of the current contour currently being assembled. Used by the tess* methods. + */ protected ArrayList currentContour; - /** Indicates whether this context is currently operating in bounding sector mode. */ + /** + * Indicates whether this context is currently operating in bounding sector mode. + */ protected boolean isBoundingSectorMode; - /** The shape bounding sectors associated with this context. */ + /** + * The shape bounding sectors associated with this context. + */ protected ArrayList boundingSectors = new ArrayList(); /** * Creates a new combine context with the specified globe, resolution, and the default region of interest. * - * @param globe the globe to associate with this context. Shape geometry defined relative to a globe must use - * this globe to compute that geometry. + * @param globe the globe to associate with this context. Shape geometry defined relative to a globe must use this + * globe to compute that geometry. * @param resolution the minimum resolution, in radians. Used to filter shape detail and compute geometry for - * resolution independent shapes. + * resolution independent shapes. * * @throws java.lang.IllegalArgumentException if the globe is null. */ - public CombineContext(Globe globe, double resolution) - { - if (globe == null) - { + public CombineContext(Globe globe, double resolution) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -169,8 +177,7 @@ public CombineContext(Globe globe, double resolution) * Releases the releases GLU tessellator resources associated with this context. */ @Override - public void dispose() - { + public void dispose() { GLU.gluDeleteTess(this.tess); this.tess = null; } @@ -181,8 +188,7 @@ public void dispose() * * @return the globe associated with this context. */ - public Globe getGlobe() - { + public Globe getGlobe() { return this.globe; } @@ -194,10 +200,8 @@ public Globe getGlobe() * * @throws java.lang.IllegalArgumentException if the globe is null. */ - public void setGlobe(Globe globe) - { - if (globe == null) - { + public void setGlobe(Globe globe) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -212,8 +216,7 @@ public void setGlobe(Globe globe) * * @return the geographic sector indicating the context's region of interest. */ - public Sector getSector() - { + public Sector getSector() { return this.sector; } @@ -225,10 +228,8 @@ public Sector getSector() * * @throws java.lang.IllegalArgumentException if the sector is null. */ - public void setSector(Sector sector) - { - if (sector == null) - { + public void setSector(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -243,8 +244,7 @@ public void setSector(Sector sector) * * @return the minimum resolution, in radians. */ - public double getResolution() - { + public double getResolution() { return this.resolution; } @@ -254,8 +254,7 @@ public double getResolution() * * @param resolution the minimum resolution, in radians. */ - public void setResolution(double resolution) - { + public void setResolution(double resolution) { this.resolution = resolution; } @@ -268,8 +267,7 @@ public void setResolution(double resolution) * * @return the GLU tessellator used to draw shape contours. */ - public GLUtessellator getTessellator() - { + public GLUtessellator getTessellator() { return this.tess; } @@ -278,8 +276,7 @@ public GLUtessellator getTessellator() * * @return the list of contours associated with this context. */ - public ContourList getContours() - { + public ContourList getContours() { return this.contours; } @@ -290,10 +287,8 @@ public ContourList getContours() * * @throws java.lang.IllegalArgumentException if the contour is null. */ - public void addContour(Iterable contour) - { - if (contour == null) - { + public void addContour(Iterable contour) { + if (contour == null) { String msg = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -305,39 +300,33 @@ public void addContour(Iterable contour) /** * Removes all entries from this context's list of contours. */ - public void removeAllContours() - { + public void removeAllContours() { this.contours.removeAllContours(); } @SuppressWarnings("UnusedParameters") - protected void tessBegin(int type) - { + protected void tessBegin(int type) { this.currentContour = new ArrayList(); } - protected void tessVertex(Object vertexData) - { + protected void tessVertex(Object vertexData) { double[] vertex = (double[]) vertexData; // longitude, latitude, 0 double latDegrees = Angle.normalizedDegreesLatitude(vertex[1]); double lonDegrees = Angle.normalizedDegreesLongitude(vertex[0]); this.currentContour.add(LatLon.fromDegrees(latDegrees, lonDegrees)); } - protected void tessEnd() - { + protected void tessEnd() { this.addContour(this.currentContour); this.currentContour = null; } @SuppressWarnings("UnusedParameters") - protected void tessCombine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) - { + protected void tessCombine(double[] coords, Object[] vertexData, float[] weight, Object[] outData) { outData[0] = coords; } - protected void tessError(int errno) - { + protected void tessError(int errno) { String errstr = GLUTessellatorSupport.convertGLUTessErrorToString(errno); String msg = Logging.getMessage("generic.ExceptionWhileTessellating", errstr); Logging.logger().severe(msg); @@ -350,8 +339,7 @@ protected void tessError(int errno) * * @return true if the context is currently in bounding sector mode, otherwise false. */ - public boolean isBoundingSectorMode() - { + public boolean isBoundingSectorMode() { return this.isBoundingSectorMode; } @@ -362,8 +350,7 @@ public boolean isBoundingSectorMode() * * @param tf true to set the context is bounding sector mode, otherwise false. */ - public void setBoundingSectorMode(boolean tf) - { + public void setBoundingSectorMode(boolean tf) { this.isBoundingSectorMode = tf; } @@ -375,8 +362,7 @@ public void setBoundingSectorMode(boolean tf) * * @see #isBoundingSectorMode() */ - public List getBoundingSectors() - { + public List getBoundingSectors() { return this.boundingSectors; } @@ -387,10 +373,8 @@ public List getBoundingSectors() * * @throws java.lang.IllegalArgumentException if the sector is null. */ - public void addBoundingSector(Sector sector) - { - if (sector == null) - { + public void addBoundingSector(Sector sector) { + if (sector == null) { String msg = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -402,8 +386,7 @@ public void addBoundingSector(Sector sector) /** * Removes all entries from this context's list of shape bounding sectors. */ - public void removeAllBoundingSectors() - { + public void removeAllBoundingSectors() { this.boundingSectors.clear(); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/combine/ShapeCombiner.java b/src/gov/nasa/worldwind/util/combine/ShapeCombiner.java index e5a50667c4..147e3de7ff 100644 --- a/src/gov/nasa/worldwind/util/combine/ShapeCombiner.java +++ b/src/gov/nasa/worldwind/util/combine/ShapeCombiner.java @@ -16,15 +16,13 @@ * @author dcollins * @version $Id: ShapeCombiner.java 2413 2014-10-30 21:33:37Z dcollins $ */ -public class ShapeCombiner -{ +public class ShapeCombiner { + protected Globe globe; protected double resolution; - public ShapeCombiner(Globe globe, double resolution) - { - if (globe == null) - { + public ShapeCombiner(Globe globe, double resolution) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -34,20 +32,16 @@ public ShapeCombiner(Globe globe, double resolution) this.resolution = resolution; } - public Globe getGlobe() - { + public Globe getGlobe() { return this.globe; } - public double getResolution() - { + public double getResolution() { return this.resolution; } - public ContourList union(Combinable... shapes) - { - if (shapes == null) - { + public ContourList union(Combinable... shapes) { + if (shapes == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -55,22 +49,17 @@ public ContourList union(Combinable... shapes) CombineContext cc = this.createContext(); - try - { + try { this.union(cc, shapes); - } - finally - { + } finally { cc.dispose(); // releases GLU tessellator resources } return cc.getContours(); } - public ContourList intersection(Combinable... shapes) - { - if (shapes == null) - { + public ContourList intersection(Combinable... shapes) { + if (shapes == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -78,102 +67,85 @@ public ContourList intersection(Combinable... shapes) CombineContext cc = this.createContext(); - try - { - if (shapes.length == 1) + try { + if (shapes.length == 1) { this.union(cc, shapes); // equivalent to the identity of the first shape - else if (shapes.length > 1) + } else if (shapes.length > 1) { this.intersection(cc, shapes); - } - finally - { + } + } finally { cc.dispose(); // releases GLU tessellator resources } return cc.getContours(); } - public ContourList difference(Combinable... shapes) - { - if (shapes == null) - { + public ContourList difference(Combinable... shapes) { + if (shapes == null) { String msg = Logging.getMessage("nullValue.ListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } CombineContext cc = this.createContext(); - try - { - if (shapes.length == 1) + try { + if (shapes.length == 1) { this.union(cc, shapes); // equivalent to the identity of the first shape - else if (shapes.length > 1) + } else if (shapes.length > 1) { this.difference(cc, shapes); - } - finally - { + } + } finally { cc.dispose(); // releases GLU tessellator resources } return cc.getContours(); } - protected CombineContext createContext() - { + protected CombineContext createContext() { return new CombineContext(this.globe, this.resolution); } - protected void union(CombineContext cc, Combinable... shapes) - { + protected void union(CombineContext cc, Combinable... shapes) { GLUtessellator tess = cc.getTessellator(); - try - { + try { GLU.gluTessProperty(tess, GLU.GLU_TESS_WINDING_RULE, GLU.GLU_TESS_WINDING_NONZERO); GLU.gluTessBeginPolygon(tess, null); - for (Combinable combinable : shapes) - { + for (Combinable combinable : shapes) { combinable.combine(cc); } - } - finally - { + } finally { GLU.gluTessEndPolygon(tess); } } - protected void reverseUnion(CombineContext cc, Combinable... shapes) - { + protected void reverseUnion(CombineContext cc, Combinable... shapes) { GLUtessellator tess = cc.getTessellator(); - try - { + try { GLU.gluTessProperty(tess, GLU.GLU_TESS_WINDING_RULE, GLU.GLU_TESS_WINDING_NONZERO); GLU.gluTessNormal(tess, 0, 0, -1); // reverse the winding order of the tessellated boundaries GLU.gluTessBeginPolygon(tess, null); - for (Combinable combinable : shapes) - { + for (Combinable combinable : shapes) { combinable.combine(cc); } - } - finally - { + } finally { GLU.gluTessEndPolygon(tess); } } - protected void intersection(CombineContext cc, Combinable... shapes) - { + protected void intersection(CombineContext cc, Combinable... shapes) { // Limit this operation to the intersection of the bounding regions. Since this is an intersection operation, // shapes outside of this region can be ignored or simplified. this.assembleBoundingSectors(cc, shapes); // Exit immediately if the bounding regions do not intersect. Sector sector = Sector.intersection(cc.getBoundingSectors()); - if (sector == null) + if (sector == null) { return; + } cc.setSector(sector); @@ -182,10 +154,8 @@ protected void intersection(CombineContext cc, Combinable... shapes) // When the caller has specified more than two shapes, repeatedly compute the intersection of the current // contours with the next shape. This has the effect of progressively computing the intersection of all shapes. - if (shapes.length > 2) - { - for (int i = 2; i < shapes.length; i++) - { + if (shapes.length > 2) { + for (int i = 2; i < shapes.length; i++) { ContourList result = new ContourList(cc.getContours()); cc.removeAllContours(); @@ -194,34 +164,30 @@ protected void intersection(CombineContext cc, Combinable... shapes) } } - protected void intersection(CombineContext cc, Combinable a, Combinable b) - { + protected void intersection(CombineContext cc, Combinable a, Combinable b) { GLUtessellator tess = cc.getTessellator(); - try - { + try { GLU.gluTessProperty(tess, GLU.GLU_TESS_WINDING_RULE, GLU.GLU_TESS_WINDING_ABS_GEQ_TWO); GLU.gluTessBeginPolygon(tess, null); a.combine(cc); b.combine(cc); - } - finally - { + } finally { GLU.gluTessEndPolygon(tess); } } - protected void difference(CombineContext cc, Combinable... shapes) - { + protected void difference(CombineContext cc, Combinable... shapes) { // Limit this operation to the region bounding the shape that we're subtracting from. Since this is a difference // operation, shapes outside of this region can be ignored or simplified. Combinable a = shapes[0]; this.assembleBoundingSectors(cc, a); // Exit immediately if the first shape has no bounding region. - if (cc.getBoundingSectors().size() == 0) + if (cc.getBoundingSectors().size() == 0) { return; + } cc.setSector(cc.getBoundingSectors().get(0)); @@ -233,35 +199,27 @@ protected void difference(CombineContext cc, Combinable... shapes) // Combine the first shape with the union of all shapes exception the first. Since the union has its winding // order reversed, this has the effect of subtracting the union from the first shape. GLUtessellator tess = cc.getTessellator(); - try - { + try { GLU.gluTessProperty(tess, GLU.GLU_TESS_WINDING_RULE, GLU.GLU_TESS_WINDING_POSITIVE); GLU.gluTessNormal(tess, 0, 0, 1); // restore the GLU tessellator's normal vector GLU.gluTessBeginPolygon(tess, null); a.combine(cc); b.combine(cc); - } - finally - { + } finally { GLU.gluTessEndPolygon(tess); } } - protected void assembleBoundingSectors(CombineContext cc, Combinable... shapes) - { - try - { + protected void assembleBoundingSectors(CombineContext cc, Combinable... shapes) { + try { cc.setBoundingSectorMode(true); - for (Combinable combinable : shapes) - { + for (Combinable combinable : shapes) { combinable.combine(cc); } - } - finally - { + } finally { cc.setBoundingSectorMode(false); } } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/dashboard/DashboardController.java b/src/gov/nasa/worldwind/util/dashboard/DashboardController.java index 9f3ed0b72c..a0bd23b69b 100644 --- a/src/gov/nasa/worldwind/util/dashboard/DashboardController.java +++ b/src/gov/nasa/worldwind/util/dashboard/DashboardController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.dashboard; import gov.nasa.worldwind.*; @@ -17,16 +16,14 @@ * @author tag * @version $Id: DashboardController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DashboardController implements MouseListener, Disposable -{ +public class DashboardController implements MouseListener, Disposable { + private DashboardDialog dialog; private Component component; private WorldWindow wwd; - public DashboardController(WorldWindow wwd, Component component) - { - if (wwd == null) - { + public DashboardController(WorldWindow wwd, Component component) { + if (wwd == null) { String msg = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -37,62 +34,56 @@ public DashboardController(WorldWindow wwd, Component component) wwd.getInputHandler().addMouseListener(this); } - public void dispose() - { - if (this.dialog != null) - { + public void dispose() { + if (this.dialog != null) { this.dialog.dispose(); this.dialog = null; } - if (this.wwd.getInputHandler() != null) + if (this.wwd.getInputHandler() != null) { this.wwd.getInputHandler().removeMouseListener(this); + } this.wwd = null; this.component = null; } - public void raiseDialog() - { - if (this.dialog == null) + public void raiseDialog() { + if (this.dialog == null) { this.dialog = new DashboardDialog(getParentFrame(this.component), wwd); + } this.dialog.raiseDialog(); } - public void lowerDialog() - { - if (this.dialog != null) + public void lowerDialog() { + if (this.dialog != null) { this.dialog.lowerDialog(); + } } - private Frame getParentFrame(Component comp) - { + private Frame getParentFrame(Component comp) { return comp != null ? (Frame) SwingUtilities.getAncestorOfClass(Frame.class, comp) : null; } - public void mouseClicked(MouseEvent event) - { + public void mouseClicked(MouseEvent event) { if ((event.getButton() == MouseEvent.BUTTON1 - && (event.getModifiers() & ActionEvent.CTRL_MASK) != 0 - && (event.getModifiers() & ActionEvent.ALT_MASK) != 0 - && (event.getModifiers() & ActionEvent.SHIFT_MASK) != 0)) + && (event.getModifiers() & ActionEvent.CTRL_MASK) != 0 + && (event.getModifiers() & ActionEvent.ALT_MASK) != 0 + && (event.getModifiers() & ActionEvent.SHIFT_MASK) != 0)) { raiseDialog(); + } } - public void mousePressed(MouseEvent e) - { + public void mousePressed(MouseEvent e) { } - public void mouseReleased(MouseEvent e) - { + public void mouseReleased(MouseEvent e) { } - public void mouseEntered(MouseEvent e) - { + public void mouseEntered(MouseEvent e) { } - public void mouseExited(MouseEvent e) - { + public void mouseExited(MouseEvent e) { } } diff --git a/src/gov/nasa/worldwind/util/dashboard/DashboardDialog.java b/src/gov/nasa/worldwind/util/dashboard/DashboardDialog.java index 2c1e86c2ba..0296218def 100644 --- a/src/gov/nasa/worldwind/util/dashboard/DashboardDialog.java +++ b/src/gov/nasa/worldwind/util/dashboard/DashboardDialog.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.dashboard; import gov.nasa.worldwind.WorldWindow; @@ -20,13 +19,12 @@ * @author tag * @version $Id: DashboardDialog.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DashboardDialog extends JDialog -{ +public class DashboardDialog extends JDialog { + private WorldWindow wwd; private boolean runContinuously = false; - public DashboardDialog(Frame parent, WorldWindow wwd) throws HeadlessException - { + public DashboardDialog(Frame parent, WorldWindow wwd) throws HeadlessException { super(parent, "WWJ Dashboard"); this.wwd = wwd; @@ -38,13 +36,10 @@ public DashboardDialog(Frame parent, WorldWindow wwd) throws HeadlessException this.setResizable(false); this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); - wwd.addRenderingListener(new RenderingListener() - { - public void stageChanged(RenderingEvent event) - { + wwd.addRenderingListener(new RenderingListener() { + public void stageChanged(RenderingEvent event) { if (runContinuously && event.getStage().equals(RenderingEvent.AFTER_BUFFER_SWAP) - && event.getSource() instanceof WorldWindow) - { + && event.getSource() instanceof WorldWindow) { ((WorldWindow) event.getSource()).redraw(); } } @@ -52,44 +47,37 @@ public void stageChanged(RenderingEvent event) } @Override - public void dispose() - { + public void dispose() { super.dispose(); this.wwd = null; } - public void raiseDialog() - { + public void raiseDialog() { makeCurrent(); WWUtil.alignComponent(this.getParent(), this, AVKey.RIGHT); this.setVisible(true); } - public void lowerDialog() - { + public void lowerDialog() { setVisible(false); } - private void makeCurrent() - { + private void makeCurrent() { } - private class OkayAction extends AbstractAction - { - public OkayAction() - { + private class OkayAction extends AbstractAction { + + public OkayAction() { super("Okay"); } - public void actionPerformed(ActionEvent e) - { + public void actionPerformed(ActionEvent e) { lowerDialog(); } } - private JTabbedPane createControls() - { + private JTabbedPane createControls() { JTabbedPane tabPane = new JTabbedPane(); JPanel panel = new JPanel(new BorderLayout(10, 20)); @@ -103,8 +91,7 @@ private JTabbedPane createControls() return tabPane; } - private JPanel makeControlPanel() - { + private JPanel makeControlPanel() { JPanel panel = new JPanel(new FlowLayout(SwingConstants.VERTICAL)); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); @@ -113,8 +100,7 @@ private JPanel makeControlPanel() return panel; } - private JPanel makeTerrainControlPanel() - { + private JPanel makeTerrainControlPanel() { JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5)); panel.setBorder(new CompoundBorder(new TitledBorder("Terrain"), new EmptyBorder(10, 10, 10, 10))); @@ -134,27 +120,20 @@ private JPanel makeTerrainControlPanel() final JCheckBox runContinuouslyButton = new JCheckBox("Run Continuously"); panel.add(runContinuouslyButton); - ActionListener listener = new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + ActionListener listener = new ActionListener() { + public void actionPerformed(ActionEvent e) { boolean tris = triangleButton.isSelected(); boolean skirts = skirtsButton.isSelected(); - if (tris && e.getSource() == triangleButton) - { + if (tris && e.getSource() == triangleButton) { wwd.getModel().setShowWireframeInterior(true); wwd.getModel().getGlobe().getTessellator().setMakeTileSkirts(false); skirtsButton.setSelected(false); - } - else if (skirts && e.getSource() == skirtsButton) - { + } else if (skirts && e.getSource() == skirtsButton) { wwd.getModel().setShowWireframeInterior(true); wwd.getModel().getGlobe().getTessellator().setMakeTileSkirts(true); triangleButton.setSelected(false); - } - else - { + } else { wwd.getModel().setShowWireframeInterior(false); wwd.getModel().getGlobe().getTessellator().setMakeTileSkirts(true); } @@ -178,28 +157,22 @@ else if (skirts && e.getSource() == skirtsButton) // } // }); - tileButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + tileButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { wwd.getModel().setShowWireframeExterior(!wwd.getModel().isShowWireframeExterior()); wwd.redraw(); } }); - extentsButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + extentsButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { wwd.getModel().setShowTessellationBoundingVolumes(!wwd.getModel().isShowTessellationBoundingVolumes()); wwd.redraw(); } }); - runContinuouslyButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + runContinuouslyButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { runContinuously = runContinuouslyButton.isSelected(); wwd.redraw(); } @@ -208,8 +181,7 @@ public void actionPerformed(ActionEvent e) return panel; } - private JPanel makeOkayCancelPanel() - { + private JPanel makeOkayCancelPanel() { JPanel panel = new JPanel(new GridLayout(1, 3, 10, 10)); panel.add(new JLabel("")); diff --git a/src/gov/nasa/worldwind/util/gdal/GDALAbstractFileFilter.java b/src/gov/nasa/worldwind/util/gdal/GDALAbstractFileFilter.java index 8edb052f6c..c82db671b2 100644 --- a/src/gov/nasa/worldwind/util/gdal/GDALAbstractFileFilter.java +++ b/src/gov/nasa/worldwind/util/gdal/GDALAbstractFileFilter.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.gdal; import gov.nasa.worldwind.util.*; @@ -16,16 +15,13 @@ * @author Lado Garakanidze * @version $Id: GDALAbstractFileFilter.java 1171 2013-02-11 21:45:02Z dcollins $ */ +abstract class GDALAbstractFileFilter implements java.io.FileFilter { -abstract class GDALAbstractFileFilter implements java.io.FileFilter -{ protected HashSet listFolders = new HashSet(); protected final String searchPattern; - protected GDALAbstractFileFilter(String searchPattern) - { - if (null == searchPattern || searchPattern.length() == 0) - { + protected GDALAbstractFileFilter(String searchPattern) { + if (null == searchPattern || searchPattern.length() == 0) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -36,17 +32,12 @@ protected GDALAbstractFileFilter(String searchPattern) listFolders.clear(); } - protected boolean isHidden(String path) - { - if (!WWUtil.isEmpty(path)) - { + protected boolean isHidden(String path) { + if (!WWUtil.isEmpty(path)) { String[] folders = path.split(Pattern.quote(File.separator)); - if (!WWUtil.isEmpty(folders)) - { - for (String folder : folders) - { - if (!WWUtil.isEmpty(folder) && folder.startsWith(".")) - { + if (!WWUtil.isEmpty(folders)) { + for (String folder : folders) { + if (!WWUtil.isEmpty(folder) && folder.startsWith(".")) { return true; } } @@ -55,9 +46,8 @@ protected boolean isHidden(String path) return false; } - public String[] getFolders() - { + public String[] getFolders() { String[] folders = new String[listFolders.size()]; return this.listFolders.toArray(folders); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/gdal/GDALDataFinder.java b/src/gov/nasa/worldwind/util/gdal/GDALDataFinder.java index f8f428abae..36a7146094 100644 --- a/src/gov/nasa/worldwind/util/gdal/GDALDataFinder.java +++ b/src/gov/nasa/worldwind/util/gdal/GDALDataFinder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.gdal; import java.io.File; @@ -12,24 +11,21 @@ * @author Lado Garakanidze * @version $Id: GDALDataFinder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class GDALDataFinder extends GDALAbstractFileFilter -{ - public GDALDataFinder() - { +class GDALDataFinder extends GDALAbstractFileFilter { + + public GDALDataFinder() { super("gdal_datum.csv"); } - public boolean accept(File pathname) - { + public boolean accept(File pathname) { String filename; String dir; if (null != pathname - && !isHidden(pathname.getAbsolutePath()) - && null != (dir = pathname.getParent()) - && !this.listFolders.contains(dir) // skip already discovered - && null != (filename = pathname.getName()) // get folder name - && searchPattern.equalsIgnoreCase(filename)) - { + && !isHidden(pathname.getAbsolutePath()) + && null != (dir = pathname.getParent()) + && !this.listFolders.contains(dir) // skip already discovered + && null != (filename = pathname.getName()) // get folder name + && searchPattern.equalsIgnoreCase(filename)) { this.listFolders.add(dir); return true; } diff --git a/src/gov/nasa/worldwind/util/gdal/GDALLibraryFinder.java b/src/gov/nasa/worldwind/util/gdal/GDALLibraryFinder.java index 4d3ea4e955..5a334ec83d 100644 --- a/src/gov/nasa/worldwind/util/gdal/GDALLibraryFinder.java +++ b/src/gov/nasa/worldwind/util/gdal/GDALLibraryFinder.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.gdal; import gov.nasa.worldwind.Configuration; @@ -15,37 +14,32 @@ * @author Lado Garakanidze * @version $Id: GDALLibraryFinder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -class GDALLibraryFinder extends GDALAbstractFileFilter -{ - protected final String libExtension = - Configuration.isWindowsOS() ? ".dll" : (Configuration.isMacOS() ? ".jnilib" : ".so"); +class GDALLibraryFinder extends GDALAbstractFileFilter { + + protected final String libExtension + = Configuration.isWindowsOS() ? ".dll" : (Configuration.isMacOS() ? ".jnilib" : ".so"); - public GDALLibraryFinder() - { + public GDALLibraryFinder() { super("gdal"); } - public GDALLibraryFinder(String searchPattern) - { + public GDALLibraryFinder(String searchPattern) { super(searchPattern); } - public boolean accept(File pathname) - { + public boolean accept(File pathname) { String filename; String dir; if (null != pathname - && !isHidden(pathname.getAbsolutePath()) - && null != (dir = pathname.getParent()) - && !this.listFolders.contains(dir) // skip already discovered - && null != (filename = pathname.getName()) // get folder name - && !filename.startsWith(".") - && null != (filename = filename.toLowerCase()) // change to lower case - && filename.contains(this.searchPattern) - && filename.endsWith(this.libExtension) -// && this.canLoad(pathname.getAbsolutePath()) - ) - { + && !isHidden(pathname.getAbsolutePath()) + && null != (dir = pathname.getParent()) + && !this.listFolders.contains(dir) // skip already discovered + && null != (filename = pathname.getName()) // get folder name + && !filename.startsWith(".") + && null != (filename = filename.toLowerCase()) // change to lower case + && filename.contains(this.searchPattern) + && filename.endsWith(this.libExtension) // && this.canLoad(pathname.getAbsolutePath()) + ) { this.listFolders.add(dir); return true; } @@ -61,16 +55,12 @@ public boolean accept(File pathname) * * @return TRUE if the file is loadable library */ - protected boolean canLoad(String pathToLibrary) - { - try - { + protected boolean canLoad(String pathToLibrary) { + try { System.load(pathToLibrary); return true; - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().finest(WWUtil.extractExceptionReason(t)); } return false; diff --git a/src/gov/nasa/worldwind/util/gdal/GDALUtils.java b/src/gov/nasa/worldwind/util/gdal/GDALUtils.java index 4e8e1cfa02..3f36e13446 100644 --- a/src/gov/nasa/worldwind/util/gdal/GDALUtils.java +++ b/src/gov/nasa/worldwind/util/gdal/GDALUtils.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.gdal; import gov.nasa.worldwind.Configuration; @@ -34,8 +33,8 @@ * @author Lado Garakanidze * @version $Id: GDALUtils.java 3031 2015-04-17 14:53:23Z tgaskins $ */ -public class GDALUtils -{ +public class GDALUtils { + public static long ALPHA_MASK = 0xFFFFFFFFL; protected static byte ALPHA_TRANSPARENT = (byte) 0x00; @@ -50,58 +49,51 @@ public class GDALUtils // This is an OLD default libname request by WW build of GDAL protected static final String gdalalljni = Configuration.isMacOS() - ? "gdalalljni" : (is32bitArchitecture() ? "gdalalljni32" : "gdalalljni64"); + ? "gdalalljni" : (is32bitArchitecture() ? "gdalalljni32" : "gdalalljni64"); protected static final CopyOnWriteArraySet loadedLibraries = new CopyOnWriteArraySet(); protected static final CopyOnWriteArraySet failedLibraries = new CopyOnWriteArraySet(); - static - { + static { // Allow the app or user to prevent library loader replacement. - if (System.getProperty("gov.nasa.worldwind.prevent.gdal.loader.replacement") == null) + if (System.getProperty("gov.nasa.worldwind.prevent.gdal.loader.replacement") == null) { replaceLibraryLoader(); // This must be the first line of initialization + } initialize(); } - private static class GDALLibraryLoader implements gdal.LibraryLoader - { - public void load(String libName) throws UnsatisfiedLinkError - { - if (WWUtil.isEmpty(libName)) - { + private static class GDALLibraryLoader implements gdal.LibraryLoader { + + public void load(String libName) throws UnsatisfiedLinkError { + if (WWUtil.isEmpty(libName)) { String message = Logging.getMessage("nullValue.LibraryIsNull"); Logging.logger().severe(message); throw new java.lang.UnsatisfiedLinkError(message); } // check if the library is already loaded - if (loadedLibraries.contains(libName)) + if (loadedLibraries.contains(libName)) { return; + } String message; // check if the library is already know (from previous attempts) to fail to load - if (!failedLibraries.contains(libName)) - { - try - { + if (!failedLibraries.contains(libName)) { + try { NativeLibraryLoader.loadLibrary(libName); loadedLibraries.add(libName); Logging.logger().info(Logging.getMessage("generic.LibraryLoadedOK", libName)); return; // GOOD! Leaving now - } - catch (Throwable t) - { + } catch (Throwable t) { String reason = WWUtil.extractExceptionReason(t); message = Logging.getMessage("generic.LibraryNotLoaded", libName, reason); Logging.logger().finest(message); failedLibraries.add(libName); } - } - else - { + } else { String reason = Logging.getMessage("generic.LibraryNotFound", libName); message = Logging.getMessage("generic.LibraryNotLoaded", libName, reason); } @@ -110,19 +102,15 @@ public void load(String libName) throws UnsatisfiedLinkError } } - protected static void replaceLibraryLoader() - { - try - { + protected static void replaceLibraryLoader() { + try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class gdalClass = cl.loadClass("org.gdal.gdal.gdal"); boolean isKnownBuild = false; Method[] methods = gdalClass.getDeclaredMethods(); - for (Method m : methods) - { - if ("setLibraryLoader".equals(m.getName())) - { + for (Method m : methods) { + if ("setLibraryLoader".equals(m.getName())) { gdal.setLibraryLoader(new GDALLibraryLoader()); // Logging.logger().finest(Logging.getMessage("gdal.LibraryLoaderReplacedOK")); isKnownBuild = true; @@ -130,92 +118,74 @@ protected static void replaceLibraryLoader() } } - if (!isKnownBuild) - { + if (!isKnownBuild) { String message = Logging.getMessage("gdal.UnknownBuild", gdal.VersionInfo()); Logging.logger().finest(message); } - } - catch (ClassNotFoundException cnf) - { + } catch (ClassNotFoundException cnf) { Logging.logger().finest(cnf.getMessage()); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().finest(t.getMessage()); } } - protected static boolean is32bitArchitecture() - { + protected static boolean is32bitArchitecture() { String arch = System.getProperty("sun.arch.data.model"); - if (!WWUtil.isEmpty(arch)) + if (!WWUtil.isEmpty(arch)) { return ("32".equals(arch)); + } // GNU JAVA does not return "sun.arch.data.model" return "x86".equals(System.getProperty("os.arch")); } - protected static boolean gdalPreLoadNativeLibrary(boolean allowLogErrors) - { - try - { + protected static boolean gdalPreLoadNativeLibrary(boolean allowLogErrors) { + try { NativeLibraryLoader.loadLibrary(gdalalljni); loadedLibraries.add(gdalalljni); Logging.logger().info(Logging.getMessage("generic.LibraryLoadedOK", gdalalljni)); return true; - } - catch (Throwable t) - { - if (allowLogErrors) + } catch (Throwable t) { + if (allowLogErrors) { Logging.logger().finest(WWUtil.extractExceptionReason(t)); + } } return false; } - protected static void initialize() - { - try - { + protected static void initialize() { + try { boolean runningAsJavaWebStart = (null != System.getProperty("javawebstart.version", null)); // attempt to load library from default locations // (current path OR by specifying java.library.path from the command line) boolean gdalNativeLibraryLoaded = gdalPreLoadNativeLibrary(false); - if (!gdalNativeLibraryLoaded && !runningAsJavaWebStart) - { + if (!gdalNativeLibraryLoaded && !runningAsJavaWebStart) { // if we are here, library is not in any default place, so we will search in sub-folders String[] folders = findGdalFolders(); String newJavaLibraryPath = buildPathString(folders, true); - if (newJavaLibraryPath != null) - { - try - { + if (newJavaLibraryPath != null) { + try { alterJavaLibraryPath(newJavaLibraryPath); // gdalNativeLibraryLoaded = gdalLoadNativeLibrary(true); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("gdal.UnableToAlterLibraryPath"); Logging.logger().log(Level.WARNING, message, e); } } } - if ( /* gdalNativeLibraryLoaded && */ gdalJNI.isAvailable() && gdalconstJNI.isAvailable()) - { - if (!runningAsJavaWebStart) - { + if ( /* gdalNativeLibraryLoaded && */gdalJNI.isAvailable() && gdalconstJNI.isAvailable()) { + if (!runningAsJavaWebStart) { // No need, because we are build one dynamic library that contains ALL drivers // and dependant libraries // gdal.SetConfigOption(GDAL_DRIVER_PATH, pathToLibs); // gdal.SetConfigOption(OGR_DRIVER_PATH, pathToLibs); String dataFolder = findGdalDataFolder(); - if (null != dataFolder) - { + if (null != dataFolder) { String msg = Logging.getMessage("gdal.SharedDataFolderFound", dataFolder); Logging.logger().finest(msg); gdal.SetConfigOption(GDAL_DATA_PATH, dataFolder); @@ -226,36 +196,29 @@ protected static void initialize() ogr.RegisterAll(); /** - * "VERSION_NUM": Returns GDAL_VERSION_NUM formatted as a string. ie. "1170" - * "RELEASE_DATE": Returns GDAL_RELEASE_DATE formatted as a string. "20020416" - * "RELEASE_NAME": Returns the GDAL_RELEASE_NAME. ie. "1.1.7" - * "--version": Returns full version , ie. "GDAL 1.1.7, released 2002/04/16" + * "VERSION_NUM": Returns GDAL_VERSION_NUM formatted as a string. ie. "1170" "RELEASE_DATE": Returns + * GDAL_RELEASE_DATE formatted as a string. "20020416" "RELEASE_NAME": Returns the GDAL_RELEASE_NAME. + * ie. "1.1.7" "--version": Returns full version , ie. "GDAL 1.1.7, released 2002/04/16" */ String msg = Logging.getMessage("generic.LibraryLoadedOK", "GDAL v" + gdal.VersionInfo("RELEASE_NAME")); Logging.logger().info(msg); listAllRegisteredDrivers(); gdalIsAvailable.set(true); - } - else - { + } else { String reason = Logging.getMessage("generic.LibraryNotFound", "GDAL"); String msg = Logging.getMessage("generic.LibraryNotLoaded", "GDAL", reason); Logging.logger().warning(msg); } - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(Level.FINEST, t.getMessage(), t); } } - protected static String getCurrentDirectory() - { + protected static String getCurrentDirectory() { String cwd = System.getProperty("user.dir"); - if (null == cwd || cwd.length() == 0) - { + if (null == cwd || cwd.length() == 0) { String message = Logging.getMessage("generic.UsersHomeDirectoryNotKnown"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -263,10 +226,8 @@ protected static String getCurrentDirectory() return cwd; } - protected static String[] findGdalFolders() - { - try - { + protected static String[] findGdalFolders() { + try { String cwd = getCurrentDirectory(); FileTree fileTree = new FileTree(new File(cwd)); @@ -275,18 +236,14 @@ protected static String[] findGdalFolders() GDALLibraryFinder filter = new GDALLibraryFinder(/*gdalalljni*/); fileTree.asList(filter); return filter.getFolders(); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().severe(t.getMessage()); } return null; } - protected static String findGdalDataFolder() - { - try - { + protected static String findGdalDataFolder() { + try { String cwd = getCurrentDirectory(); FileTree fileTree = new FileTree(new File(cwd)); @@ -296,18 +253,14 @@ protected static String findGdalDataFolder() fileTree.asList(filter); String[] folders = filter.getFolders(); - if (null != folders && folders.length > 0) - { - if (folders.length > 1) - { + if (null != folders && folders.length > 0) { + if (folders.length > 1) { String msg = Logging.getMessage("gdal.MultipleDataFoldersFound", buildPathString(folders, false)); Logging.logger().warning(msg); } return folders[0]; } - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().severe(t.getMessage()); } @@ -317,22 +270,18 @@ protected static String findGdalDataFolder() return null; } - protected static String buildPathString(String[] folders, boolean addDefaultValues) - { + protected static String buildPathString(String[] folders, boolean addDefaultValues) { String del = System.getProperty("path.separator"); StringBuffer path = new StringBuffer(); path.append("lib-external/gdal").append(del); - if (null != folders && folders.length > 0) - { - for (String folder : folders) - { + if (null != folders && folders.length > 0) { + for (String folder : folders) { path.append(folder).append(del); } } - if (addDefaultValues) - { + if (addDefaultValues) { path.append(".").append(del); // append current directory path.append(System.getProperty("user.dir")).append(del); path.append(System.getProperty(JAVA_LIBRARY_PATH)); @@ -341,35 +290,29 @@ protected static String buildPathString(String[] folders, boolean addDefaultValu return path.toString(); } - protected static void listAllRegisteredDrivers() - { + protected static void listAllRegisteredDrivers() { StringBuffer sb = new StringBuffer(); - for (int i = 0; i < gdal.GetDriverCount(); i++) - { + for (int i = 0; i < gdal.GetDriverCount(); i++) { Driver drv = gdal.GetDriver(i); String msg = Logging.getMessage("gdal.DriverDetails", drv.getShortName(), drv.getLongName(), - drv.GetDescription()); + drv.GetDescription()); sb.append(msg).append("\n"); } Logging.logger().finest(sb.toString()); } - /** @return returns an error string, if no errors returns null */ - public static String getErrorMessage() - { - try - { - if (gdalIsAvailable.get()) - { + /** + * @return returns an error string, if no errors returns null + */ + public static String getErrorMessage() { + try { + if (gdalIsAvailable.get()) { int errno = gdal.GetLastErrorNo(); - if (errno != gdalconst.CE_None) - { + if (errno != gdalconst.CE_None) { return Logging.getMessage("gdal.InternalError", errno, gdal.GetLastErrorMsg()); } } - } - catch (Throwable t) - { + } catch (Throwable t) { return t.getMessage(); } return null; @@ -378,23 +321,20 @@ public static String getErrorMessage() /** * Opens image or elevation file, returns a DataSet object * - * @param source the location of the local file, expressed as either a String path, a File, or a file URL. + * @param source the location of the local file, expressed as either a String path, a File, or a file URL. * @param isSilentMode specifies a silent mode of reading file (usually needed for canRead() and readMetadata()) * * @return returns a Dataset object * - * @throws FileNotFoundException if file not found + * @throws FileNotFoundException if file not found * @throws IllegalArgumentException if file is null - * @throws SecurityException if file could not be read - * @throws WWRuntimeException if GDAL library was not initialized + * @throws SecurityException if file could not be read + * @throws WWRuntimeException if GDAL library was not initialized */ public static Dataset open(Object source, boolean isSilentMode) - throws FileNotFoundException, IllegalArgumentException, SecurityException, WWRuntimeException - { - if (!gdalIsAvailable.get()) - { - if (isSilentMode) - { + throws FileNotFoundException, IllegalArgumentException, SecurityException, WWRuntimeException { + if (!gdalIsAvailable.get()) { + if (isSilentMode) { return null; } @@ -404,10 +344,8 @@ public static Dataset open(Object source, boolean isSilentMode) } File file = WWIO.getFileForLocalAddress(source); - if (null == file) - { - if (isSilentMode) - { + if (null == file) { + if (isSilentMode) { return null; } @@ -416,10 +354,8 @@ public static Dataset open(Object source, boolean isSilentMode) throw new IllegalArgumentException(message); } - if (!file.exists()) - { - if (isSilentMode) - { + if (!file.exists()) { + if (isSilentMode) { return null; } @@ -428,10 +364,8 @@ public static Dataset open(Object source, boolean isSilentMode) throw new FileNotFoundException(message); } - if (!file.canRead()) - { - if (isSilentMode) - { + if (!file.canRead()) { + if (isSilentMode) { return null; } @@ -441,21 +375,16 @@ public static Dataset open(Object source, boolean isSilentMode) } Dataset ds = null; - try - { + try { gdal.PushErrorHandler("CPLQuietErrorHandler"); ds = gdal.Open(file.getAbsolutePath(), gdalconst.GA_ReadOnly); - } - finally - { + } finally { gdal.PopErrorHandler(); } - if (ds == null) - { - if (isSilentMode) - { + if (ds == null) { + if (isSilentMode) { return null; } @@ -474,14 +403,13 @@ public static Dataset open(Object source, boolean isSilentMode) * * @return returns a Dataset object * - * @throws FileNotFoundException if file not found + * @throws FileNotFoundException if file not found * @throws IllegalArgumentException if file is null - * @throws SecurityException if file could not be read - * @throws WWRuntimeException if GDAL library was not initialized + * @throws SecurityException if file could not be read + * @throws WWRuntimeException if GDAL library was not initialized */ public static Dataset open(Object source) - throws FileNotFoundException, IllegalArgumentException, SecurityException, WWRuntimeException - { + throws FileNotFoundException, IllegalArgumentException, SecurityException, WWRuntimeException { return open(source, false); } @@ -492,40 +420,30 @@ public static Dataset open(Object source) * * @return true, if source is readable */ - public static boolean canOpen(Object source) - { - if (!gdalIsAvailable.get()) - { + public static boolean canOpen(Object source) { + if (!gdalIsAvailable.get()) { return false; } File file = (null != source) ? WWIO.getFileForLocalAddress(source) : null; - if (null == file) - { + if (null == file) { return false; } Dataset ds = null; boolean canOpen = false; - try - { + try { gdal.PushErrorHandler("CPLQuietErrorHandler"); - if (file.exists() && file.canRead()) - { + if (file.exists() && file.canRead()) { ds = gdal.Open(file.getAbsolutePath(), gdalconst.GA_ReadOnly); canOpen = !(ds == null); } - } - catch (Throwable t) - { + } catch (Throwable t) { // this is a quiet mode, no need to log - } - finally - { - if (null != ds) - { + } finally { + if (null != ds) { ds.delete(); } @@ -537,26 +455,23 @@ public static boolean canOpen(Object source) /** * Opens image or elevation file, returns as a BufferedImage (even for elevations) * - * @param ds GDAL's Dataset object + * @param ds GDAL's Dataset object * @param params AVList of parameters * * @return DataRaster returns as a BufferedImage (even for elevations) * * @throws IllegalArgumentException if file is null - * @throws SecurityException if file could not be read - * @throws WWRuntimeException if GDAL library was not initialized + * @throws SecurityException if file could not be read + * @throws WWRuntimeException if GDAL library was not initialized */ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) - throws IllegalArgumentException, SecurityException, WWRuntimeException - { - if (!gdalIsAvailable.get()) - { + throws IllegalArgumentException, SecurityException, WWRuntimeException { + if (!gdalIsAvailable.get()) { String message = Logging.getMessage("gdal.GDALNotAvailable"); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (null == ds) - { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -568,8 +483,7 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) int height = ds.getRasterYSize(); int bandCount = ds.getRasterCount(); - if (bandCount < 1) - { + if (bandCount < 1) { String message = Logging.getMessage("generic.UnexpectedBandCount", bandCount); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -586,12 +500,10 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) double maxValue = -Double.MAX_VALUE; - for (int bandIdx = 0; bandIdx < bandCount; bandIdx++) - { + for (int bandIdx = 0; bandIdx < bandCount; bandIdx++) { /* Bands are not 0-base indexed, so we must add 1 */ Band imageBand = ds.GetRasterBand(bandIdx + 1); - if (null == imageBand) - { + if (null == imageBand) { String message = Logging.getMessage("nullValue.RasterBandIsNull`"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -605,46 +517,34 @@ protected static DataRaster composeImageDataRaster(Dataset ds, AVList params) int colorInt = imageBand.GetRasterColorInterpretation(); - if (params.hasKey(AVKey.RASTER_BAND_MAX_PIXEL_VALUE)) - { + if (params.hasKey(AVKey.RASTER_BAND_MAX_PIXEL_VALUE)) { maxValue = (Double) params.getValue(AVKey.RASTER_BAND_MAX_PIXEL_VALUE); - } - else if ((bandDataType == gdalconstConstants.GDT_UInt16 || bandDataType == gdalconstConstants.GDT_UInt32) - && colorInt != gdalconst.GCI_AlphaBand && colorInt != gdalconst.GCI_Undefined) - { + } else if ((bandDataType == gdalconstConstants.GDT_UInt16 || bandDataType == gdalconstConstants.GDT_UInt32) + && colorInt != gdalconst.GCI_AlphaBand && colorInt != gdalconst.GCI_Undefined) { imageBand.GetMaximum(dbls); - if (dbls[0] == null) - { + if (dbls[0] == null) { double[] minmax = new double[2]; imageBand.ComputeRasterMinMax(minmax); maxValue = (minmax[1] > maxValue) ? minmax[1] : maxValue; - } - else - { + } else { maxValue = (dbls[0] > maxValue) ? dbls[0] : maxValue; } } int returnVal = imageBand.ReadRaster_Direct(0, 0, imageBand.getXSize(), - imageBand.getYSize(), width, height, bandDataType, data); + imageBand.getYSize(), width, height, bandDataType, data); - if (returnVal != gdalconstConstants.CE_None) - { + if (returnVal != gdalconstConstants.CE_None) { throw new WWRuntimeException(GDALUtils.getErrorMessage()); } int destBandIdx = bandIdx; - if (colorInt == gdalconst.GCI_RedBand) - { + if (colorInt == gdalconst.GCI_RedBand) { destBandIdx = 0; - } - else if (colorInt == gdalconst.GCI_GreenBand) - { + } else if (colorInt == gdalconst.GCI_GreenBand) { destBandIdx = 1; - } - else if (colorInt == gdalconst.GCI_BlueBand) - { + } else if (colorInt == gdalconst.GCI_BlueBand) { destBandIdx = 2; } @@ -657,40 +557,28 @@ else if (colorInt == gdalconst.GCI_BlueBand) int actualBitsPerColor = bitsPerColor; - if (params.hasKey(AVKey.RASTER_BAND_ACTUAL_BITS_PER_PIXEL)) - { + if (params.hasKey(AVKey.RASTER_BAND_ACTUAL_BITS_PER_PIXEL)) { actualBitsPerColor = (Integer) params.getValue(AVKey.RASTER_BAND_ACTUAL_BITS_PER_PIXEL); - } - else if (maxValue > 0d) - { + } else if (maxValue > 0d) { actualBitsPerColor = (int) Math.ceil(Math.log(maxValue) / Math.log(2d)); - } - else - { + } else { actualBitsPerColor = bitsPerColor; } int[] reqBandOrder = bandsOrder; - try - { + try { reqBandOrder = extractBandOrder(ds, params); - if (null == reqBandOrder || 0 == reqBandOrder.length) - { + if (null == reqBandOrder || 0 == reqBandOrder.length) { reqBandOrder = bandsOrder; - } - else - { + } else { offsets = new int[reqBandOrder.length]; bandsOrder = new int[reqBandOrder.length]; - for (int i = 0; i < reqBandOrder.length; i++) - { + for (int i = 0; i < reqBandOrder.length; i++) { bandsOrder[i] = i; offsets[i] = 0; } } - } - catch (Exception e) - { + } catch (Exception e) { reqBandOrder = bandsOrder; Logging.logger().severe(e.getMessage()); } @@ -700,101 +588,79 @@ else if (maxValue > 0d) // A typical sample RGB: // bitsPerSample is 24=3x8, bitsPerColor { 8,8,8 }, SignificantBitsPerColor {8,8,8}, byteOffsets {2, 1, 0} - // A typical sample RGBA: // bitsPerSample is 32=4x8, bitsPerColor { 8,8,8,8 }, SignificantBitsPerColor {8,8,8,8}, byteOffsets { 3, 2, 1, 0} - // A typical Aerial Photo Image RGB // (16 bits per each color, significant bits per color vary from 9bits, 10bits, 11bits, and 12bits // bitsPerSample is 48=3x16, bitsPerColor { 16,16,16 }, SignificantBitsPerColor { 11,11,11 }, byteOffsets { 4, 2, 0} - // A typical Aerial Photo Image RGBA // (16 bits per each color, significant bits per color vary from 9bits, 10bits, 11bits, and 12bits // bitsPerSample is 64=4x16, bitsPerColor { 16,16,16,16 }, SignificantBitsPerColor { 12,12,12,12 }, byteOffsets { 6, 4, 2, 0 } - int reqBandCount = reqBandOrder.length; boolean hasAlpha = (reqBandCount == 2) || (reqBandCount == 4); IntBuffer imageMask = null; - if (hasAlpha && params.hasKey(AVKey.GDAL_MASK_DATASET)) - { + if (hasAlpha && params.hasKey(AVKey.GDAL_MASK_DATASET)) { imageMask = extractImageMask(params); } - if (bandDataType == gdalconstConstants.GDT_Byte) - { + if (bandDataType == gdalconstConstants.GDT_Byte) { byte[][] int8 = new byte[reqBandCount][]; - for (int i = 0; i < reqBandCount; i++) - { + for (int i = 0; i < reqBandCount; i++) { int srcBandIndex = reqBandOrder[i]; int8[i] = new byte[imgSize]; bands[srcBandIndex].get(int8[i]); } - if (hasAlpha && null != imageMask) - { + if (hasAlpha && null != imageMask) { applyImageMask(int8[reqBandCount - 1], imageMask); } imgBuffer = new DataBufferByte(int8, imgSize); bufferType = DataBuffer.TYPE_BYTE; - } - else if (bandDataType == gdalconstConstants.GDT_Int16) - { + } else if (bandDataType == gdalconstConstants.GDT_Int16) { short[][] int16 = new short[reqBandCount][]; - for (int i = 0; i < reqBandCount; i++) - { + for (int i = 0; i < reqBandCount; i++) { int srcBandIndex = reqBandOrder[i]; int16[i] = new short[imgSize]; bands[srcBandIndex].asShortBuffer().get(int16[i]); } - if (hasAlpha && null != imageMask) - { + if (hasAlpha && null != imageMask) { applyImageMask(int16[reqBandCount - 1], imageMask); } imgBuffer = new DataBufferShort(int16, imgSize); bufferType = DataBuffer.TYPE_SHORT; - } - else if (bandDataType == gdalconstConstants.GDT_Int32 || bandDataType == gdalconstConstants.GDT_UInt32) - { + } else if (bandDataType == gdalconstConstants.GDT_Int32 || bandDataType == gdalconstConstants.GDT_UInt32) { int[][] uint32 = new int[reqBandCount][]; - for (int i = 0; i < reqBandCount; i++) - { + for (int i = 0; i < reqBandCount; i++) { int srcBandIndex = reqBandOrder[i]; uint32[i] = new int[imgSize]; bands[srcBandIndex].asIntBuffer().get(uint32[i]); } - if (hasAlpha && null != imageMask) - { + if (hasAlpha && null != imageMask) { applyImageMask(uint32[reqBandCount - 1], imageMask); } imgBuffer = new DataBufferInt(uint32, imgSize); bufferType = DataBuffer.TYPE_INT; - } - else if (bandDataType == gdalconstConstants.GDT_UInt16) - { + } else if (bandDataType == gdalconstConstants.GDT_UInt16) { short[][] uint16 = new short[reqBandCount][]; - for (int i = 0; i < reqBandCount; i++) - { + for (int i = 0; i < reqBandCount; i++) { int srcBandIndex = reqBandOrder[i]; uint16[i] = new short[imgSize]; bands[srcBandIndex].asShortBuffer().get(uint16[i]); } - if (hasAlpha && null != imageMask) - { + if (hasAlpha && null != imageMask) { applyImageMask(uint16[reqBandCount - 1], imageMask); } imgBuffer = new DataBufferUShort(uint16, imgSize); bufferType = DataBuffer.TYPE_USHORT; - } - else - { + } else { String message = Logging.getMessage("generic.UnrecognizedDataType", bandDataType); Logging.logger().severe(message); } @@ -804,19 +670,15 @@ else if (bandDataType == gdalconstConstants.GDT_UInt16) ColorModel cm; Band band1 = ds.GetRasterBand(1); - if (band1.GetRasterColorInterpretation() == gdalconstConstants.GCI_PaletteIndex) - { + if (band1.GetRasterColorInterpretation() == gdalconstConstants.GCI_PaletteIndex) { cm = band1.GetRasterColorTable().getIndexColorModel(gdal.GetDataTypeSize(bandDataType)); img = new BufferedImage(cm, raster, false, null); - } - else if (band1.GetRasterColorInterpretation() == gdalconstConstants.GCI_GrayIndex && reqBandCount == 2) - { + } else if (band1.GetRasterColorInterpretation() == gdalconstConstants.GCI_GrayIndex && reqBandCount == 2) { int transparency = Transparency.BITMASK; int baseColorSpace = ColorSpace.CS_GRAY; ColorSpace cs = ColorSpace.getInstance(baseColorSpace); int[] nBits = new int[reqBandCount]; - for (int i = 0; i < reqBandCount; i++) - { + for (int i = 0; i < reqBandCount; i++) { nBits[i] = actualBitsPerColor; } @@ -841,17 +703,14 @@ else if (band1.GetRasterColorInterpretation() == gdalconstConstants.GCI_GrayInde dstRaster.setSamples(0, y, w, 1, 2, gray); dstRaster.setSamples(0, y, w, 1, 3, alpha); } - } - else - { + } else { // Determine the color space. int transparency = hasAlpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE; int baseColorSpace = (reqBandCount > 2) ? ColorSpace.CS_sRGB : ColorSpace.CS_GRAY; ColorSpace cs = ColorSpace.getInstance(baseColorSpace); int[] nBits = new int[reqBandCount]; - for (int i = 0; i < reqBandCount; i++) - { + for (int i = 0; i < reqBandCount; i++) { nBits[i] = actualBitsPerColor; } @@ -859,10 +718,8 @@ else if (band1.GetRasterColorInterpretation() == gdalconstConstants.GCI_GrayInde img = new BufferedImage(cm, raster, false, null); } - if( null != img ) - { - if( AVListImpl.getBooleanValue(params, AVKey.BLACK_GAPS_DETECTION, false) ) - { + if (null != img) { + if (AVListImpl.getBooleanValue(params, AVKey.BLACK_GAPS_DETECTION, false)) { // remove voids img = detectVoidsAndMakeThemTransparent(img); } @@ -881,12 +738,10 @@ else if (band1.GetRasterColorInterpretation() == gdalconstConstants.GCI_GrayInde * * @return BufferedImage with voids (if detected) filled with a transparent pixel values */ - protected static BufferedImage detectVoidsAndMakeThemTransparent(BufferedImage sourceImage) - { + protected static BufferedImage detectVoidsAndMakeThemTransparent(BufferedImage sourceImage) { BufferedImage dest; - if (sourceImage == null) - { + if (sourceImage == null) { String message = Logging.getMessage("nullValue.ImageIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -895,23 +750,19 @@ protected static BufferedImage detectVoidsAndMakeThemTransparent(BufferedImage s int width = sourceImage.getWidth(); int height = sourceImage.getHeight(); - if (width <= 3 || height <= 3) - { + if (width <= 3 || height <= 3) { // raster size is too small for the algorithm, just return the source raster return sourceImage; } - try - { + try { // first run (creates a copy and flips vertically) dest = verticalFlip(sourceImage); scanFill(dest); // second run dest = verticalFlip(dest); scanFill(dest); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().log(java.util.logging.Level.SEVERE, t.getMessage(), t); dest = sourceImage; } @@ -919,10 +770,10 @@ protected static BufferedImage detectVoidsAndMakeThemTransparent(BufferedImage s return dest; } - protected static void scanFill(BufferedImage sourceImage) - { - if (null == sourceImage || sourceImage.getWidth() <= 3 || sourceImage.getHeight() <= 3) + protected static void scanFill(BufferedImage sourceImage) { + if (null == sourceImage || sourceImage.getWidth() <= 3 || sourceImage.getHeight() <= 3) { return; + } ArrayList voids = new ArrayList(); voids.add(0); // a=r=g=b=0 @@ -958,8 +809,7 @@ protected static void scanFill(BufferedImage sourceImage) int numVoids = voids.size(); int[] nodata = new int[numVoids]; - for (int i = 0; i < numVoids; i++) - { + for (int i = 0; i < numVoids; i++) { nodata[i] = voids.get(i); } @@ -968,31 +818,26 @@ protected static void scanFill(BufferedImage sourceImage) Arrays.fill(scanline1, NODATA_TRANSPARENT); int pixel; - for (int h = 0; h < height; h++) - { + for (int h = 0; h < height; h++) { int[] scanline0 = scanline1.clone(); scanline1 = scanline2.clone(); - if (h + 1 < height) - { + if (h + 1 < height) { sourceImage.getRGB(0, h + 1, width, 1, scanline2, 1, width); scanline2[0] = scanline2[width + 1] = NODATA_TRANSPARENT; - } - else + } else { Arrays.fill(scanline2, NODATA_TRANSPARENT); + } - for (int i = 1; i <= width; i++) - { + for (int i = 1; i <= width; i++) { pixel = scanline1[i]; - for (int v = 0; v < numVoids; v++) - { - if (pixel == nodata[v] && - (scanline0[i - 1] == NODATA_TRANSPARENT || scanline0[i] == NODATA_TRANSPARENT + for (int v = 0; v < numVoids; v++) { + if (pixel == nodata[v] + && (scanline0[i - 1] == NODATA_TRANSPARENT || scanline0[i] == NODATA_TRANSPARENT || scanline0[i + 1] == NODATA_TRANSPARENT || scanline1[i - 1] == NODATA_TRANSPARENT || scanline1[i + 1] == NODATA_TRANSPARENT || scanline2[i - 1] == NODATA_TRANSPARENT - || scanline2[i] == NODATA_TRANSPARENT || scanline2[i + 1] == NODATA_TRANSPARENT)) - { + || scanline2[i] == NODATA_TRANSPARENT || scanline2[i + 1] == NODATA_TRANSPARENT)) { scanline1[i] = NODATA_TRANSPARENT; break; } @@ -1010,10 +855,10 @@ protected static void scanFill(BufferedImage sourceImage) * * @return A vertically flipped image raster as a BufferedImage */ - protected static BufferedImage verticalFlip(BufferedImage img) - { - if (null == img) + protected static BufferedImage verticalFlip(BufferedImage img) { + if (null == img) { return null; + } int w = img.getWidth(); int h = img.getHeight(); @@ -1029,86 +874,69 @@ protected static BufferedImage verticalFlip(BufferedImage img) return flipImg; } - protected static void applyImageMask(byte[] alphaBand, IntBuffer maskBand) - { - if (null == alphaBand || null == maskBand || alphaBand.length != maskBand.capacity()) - { + protected static void applyImageMask(byte[] alphaBand, IntBuffer maskBand) { + if (null == alphaBand || null == maskBand || alphaBand.length != maskBand.capacity()) { return; } int size = alphaBand.length; maskBand.rewind(); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { long pixel = ALPHA_MASK & maskBand.get(); - if (pixel == ALPHA_MASK) - { + if (pixel == ALPHA_MASK) { alphaBand[i] = ALPHA_TRANSPARENT; } } maskBand.rewind(); } - protected static void applyImageMask(short[] alphaBand, IntBuffer maskBand) - { - if (null == alphaBand || null == maskBand || alphaBand.length != maskBand.capacity()) - { + protected static void applyImageMask(short[] alphaBand, IntBuffer maskBand) { + if (null == alphaBand || null == maskBand || alphaBand.length != maskBand.capacity()) { return; } int size = alphaBand.length; maskBand.rewind(); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { long pixel = ALPHA_MASK & maskBand.get(); - if (pixel == ALPHA_MASK) - { + if (pixel == ALPHA_MASK) { alphaBand[i] = ALPHA_TRANSPARENT; } } maskBand.rewind(); } - protected static void applyImageMask(int[] alphaBand, IntBuffer maskBand) - { - if (null == alphaBand || null == maskBand || alphaBand.length != maskBand.capacity()) - { + protected static void applyImageMask(int[] alphaBand, IntBuffer maskBand) { + if (null == alphaBand || null == maskBand || alphaBand.length != maskBand.capacity()) { return; } int size = alphaBand.length; maskBand.rewind(); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { long pixel = ALPHA_MASK & maskBand.get(); - if (pixel == ALPHA_MASK) - { + if (pixel == ALPHA_MASK) { alphaBand[i] = ALPHA_TRANSPARENT; } } maskBand.rewind(); } - protected static IntBuffer extractImageMask(AVList params) - { - if (null == params || !params.hasKey(AVKey.GDAL_MASK_DATASET)) - { + protected static IntBuffer extractImageMask(AVList params) { + if (null == params || !params.hasKey(AVKey.GDAL_MASK_DATASET)) { return null; } - try - { + try { Object o = params.getValue(AVKey.GDAL_MASK_DATASET); - if (o instanceof Dataset) - { + if (o instanceof Dataset) { Dataset maskDS = (Dataset) o; Band maskBand = maskDS.GetRasterBand(1); - if (null == maskBand) - { + if (null == maskBand) { String message = Logging.getMessage("nullValue.RasterBandIsNull"); Logging.logger().severe(message); return null; @@ -1124,18 +952,15 @@ protected static IntBuffer extractImageMask(AVList params) maskData.order(ByteOrder.nativeOrder()); int returnVal = maskBand.ReadRaster_Direct(0, 0, maskBand.getXSize(), - maskBand.getYSize(), width, height, maskBandDataType, maskData); + maskBand.getYSize(), width, height, maskBandDataType, maskData); - if (returnVal != gdalconstConstants.CE_None) - { + if (returnVal != gdalconstConstants.CE_None) { throw new WWRuntimeException(GDALUtils.getErrorMessage()); } return maskData.asIntBuffer(); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, e.getMessage(), e); } @@ -1146,29 +971,25 @@ protected static IntBuffer extractImageMask(AVList params) * Calculates geo-transform matrix for a north-up raster * * @param sector Geographic area, a Sector - * @param width none-zero width of a raster + * @param width none-zero width of a raster * @param height none-zero height of a raster * * @return an array of 6 doubles that contain a geo-transform matrix * * @throws IllegalArgumentException if sector is null, or raster size is zero */ - public static double[] calcGetGeoTransform(Sector sector, int width, int height) throws IllegalArgumentException - { - if (null == sector) - { + public static double[] calcGetGeoTransform(Sector sector, int width, int height) throws IllegalArgumentException { + if (null == sector) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (0 == width) - { + if (0 == width) { String message = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (0 == height) - { + if (0 == height) { String message = Logging.getMessage("generic.InvalidHeight", height); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1180,7 +1001,6 @@ public static double[] calcGetGeoTransform(Sector sector, int width, int height) // * geotransform[5] : height of pixel (but negative) // * geotransform[0] + 0.5 * geotransform[1] + 0.5 * geotransform[2] : x offset to center of top left pixel. // * geotransform[3] + 0.5 * geotransform[4] + 0.5 * geotransform[5] : y offset to center of top left pixel. - double[] gx = new double[6]; gx[GDAL.GT_0_ORIGIN_LON] = sector.getMinLongitude().degrees; @@ -1191,19 +1011,15 @@ public static double[] calcGetGeoTransform(Sector sector, int width, int height) gx[GDAL.GT_5_PIXEL_HEIGHT] = -Math.abs(sector.getDeltaLatDegrees() / (double) height); // correct for center of pixel vs. top left of pixel - // GeoTransform[0] -= 0.5 * GeoTransform[1]; // GeoTransform[0] -= 0.5 * GeoTransform[2]; // GeoTransform[3] -= 0.5 * GeoTransform[4]; // GeoTransform[3] -= 0.5 * GeoTransform[5]; - return gx; } - public static SpatialReference createGeographicSRS() throws WWRuntimeException - { - if (!gdalIsAvailable.get()) - { + public static SpatialReference createGeographicSRS() throws WWRuntimeException { + if (!gdalIsAvailable.get()) { String message = Logging.getMessage("gdal.GDALNotAvailable"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -1214,18 +1030,15 @@ public static SpatialReference createGeographicSRS() throws WWRuntimeException return srs; } - protected static LatLon getLatLonForRasterPoint(double[] gt, int x, int y, CoordinateTransformation ct) - { - if (!gdalIsAvailable.get()) - { + protected static LatLon getLatLonForRasterPoint(double[] gt, int x, int y, CoordinateTransformation ct) { + if (!gdalIsAvailable.get()) { String message = Logging.getMessage("gdal.GDALNotAvailable"); Logging.logger().severe(message); throw new WWRuntimeException(message); } java.awt.geom.Point2D geoPoint = GDAL.getGeoPointForRasterPoint(gt, x, y); - if (null == geoPoint) - { + if (null == geoPoint) { return null; } @@ -1233,140 +1046,108 @@ protected static LatLon getLatLonForRasterPoint(double[] gt, int x, int y, Coord return LatLon.fromDegrees(latlon[1] /* latitude */, latlon[0] /* longitude */); } - public static AVList extractRasterParameters(Dataset ds) throws IllegalArgumentException, WWRuntimeException - { + public static AVList extractRasterParameters(Dataset ds) throws IllegalArgumentException, WWRuntimeException { return extractRasterParameters(ds, null, false); } /** * Extracts raster parameters to an AVList * - * @param ds A GDAL dataset - * @param params AVList to hold retrieved metadata, if null, a new instance will be created and returned - * as a return value + * @param ds A GDAL dataset + * @param params AVList to hold retrieved metadata, if null, a new instance will be created and returned as a return + * value * @param quickReadingMode if quick reading mode is enabled GDAL will not spend much time on heavy calculations, - * like for example calculating Min/Max for entire elevation raster + * like for example calculating Min/Max for entire elevation raster * * @return AVList with retrieved metadata * - * @throws IllegalArgumentException when the passed dataset is null pr emtpy, or any of the - * dimension is 0 + * @throws IllegalArgumentException when the passed dataset is null pr emtpy, or any of the dimension is 0 * @throws gov.nasa.worldwind.exception.WWRuntimeException if GDAL is not available, or a dataset contains no bands - *

          - * The extractRasterParameters() sets next key/value pairs: - *

          - * AVKey.WIDTH - the maximum width of the image - *

          - * AVKey.HEIGHT - the maximum height of the image - *

          - * AVKey.COORDINATE_SYSTEM - one of the next values: - * AVKey.COORDINATE_SYSTEM_SCREEN AVKey.COORDINATE_SYSTEM_GEOGRAPHIC - * AVKey.COORDINATE_SYSTEM_PROJECTED - *

          - * AVKey.SECTOR - in case of Geographic CS, contains a - * regular Geographic Sector defined by lat/lon coordinates - * of corners in case of Projected CS, contains a bounding - * box of the area - *

          - * AVKey.COORDINATE_SYSTEM_NAME - *

          - * AVKey.PIXEL_WIDTH (Double) pixel size, UTM images usually - * specify 1 (1 meter); if missing and Geographic Coordinate - * System is specified will be calculated as - * LongitudeDelta/WIDTH - *

          - * AVKey.PIXEL_HEIGHT (Double) pixel size, UTM images - * usually specify 1 (1 meter); if missing and Geographic - * Coordinate System is specified will be calculated as - * LatitudeDelta/HEIGHT - *

          - * AVKey.ORIGIN (LatLon) specifies coordinate of the image's - * origin (one of the corners, or center) If missing, upper - * left corner will be set as origin - *

          - * AVKey.DATE_TIME (0 terminated String, length == 20) if - * missing, current date and time will be used - *

          - * AVKey.PIXEL_FORMAT required (valid values: - * AVKey.ELEVATION | AVKey.IMAGE } specifies weather it is a - * digital elevation model or image - *

          - * AVKey.IMAGE_COLOR_FORMAT required if AVKey.PIXEL_FORMAT - * is AVKey.IMAGE (valid values: AVKey.COLOR and - * AVKey.MONOCHROME) - *

          - * AVKey.DATA_TYPE required ( valid values: AVKey.INT16, and - * AVKey.FLOAT32 ) - *

          - * AVKey.VERSION optional, if missing a default will be used - * "NASA WorldWind" - *

          - * AVKey.DISPLAY_NAME, (String) optional, specifies a name - * of the document/image - *

          - * AVKey.DESCRIPTION (String) optional, for any kind of - * descriptions - *

          - * AVKey.MISSING_DATA_SIGNAL optional, set the - * AVKey.MISSING_DATA_SIGNAL ONLY if you know for sure that - * the specified value actually represents void (NODATA) - * areas. Elevation data usually has "-32767" (like DTED), - * or "-32768" like SRTM, but some has "0" (mostly images) - * and "-9999" like NED. Note! Setting "-9999" is very - * ambiguos because -9999 for elevation is valid value; - *

          - * AVKey.MISSING_DATA_REPLACEMENT (String type forced by - * spec) Most images have "NODATA" as "0", elevations have - * as "-9999", or "-32768" (sometimes "-32767") - *

          - * AVKey.COORDINATE_SYSTEM required, valid values - * AVKey.COORDINATE_SYSTEM_GEOGRAPHIC or AVKey.COORDINATE_SYSTEM_PROJECTED - *

          - * AVKey.COORDINATE_SYSTEM_NAME Optional, A name of the - * Coordinates System as a String - *

          - * AVKey.PROJECTION_EPSG_CODE Required; Integer; EPSG code - * or Projection Code If CS is Geodetic and EPSG code is not - * specified, a default WGS84 (4326) will be used - *

          - * AVKey.PROJECTION_DATUM Optional, AVKey.PROJECTION_DESC - * Optional, AVKey.PROJECTION_NAME Optional, - * AVKey.PROJECTION_UNITS Optional, - *

          - * AVKey.ELEVATION_UNIT Required, if AVKey.PIXEL_FORMAT = - * AVKey.ELEVATION, value: AVKey.UNIT_FOOT or - * AVKey.UNIT_METER (default, if not specified) - *

          - * AVKey.RASTER_PIXEL, optional, values: AVKey.RASTER_PIXEL_IS_AREA - * or AVKey.RASTER_PIXEL_IS_POINT if not specified, default - * for images is RASTER_PIXEL_IS_AREA, and - * AVKey.RASTER_PIXEL_IS_POINT for elevations + *

          + * The extractRasterParameters() sets next key/value pairs: + *

          + * AVKey.WIDTH - the maximum width of the image + *

          + * AVKey.HEIGHT - the maximum height of the image + *

          + * AVKey.COORDINATE_SYSTEM - one of the next values: AVKey.COORDINATE_SYSTEM_SCREEN + * AVKey.COORDINATE_SYSTEM_GEOGRAPHIC AVKey.COORDINATE_SYSTEM_PROJECTED + *

          + * AVKey.SECTOR - in case of Geographic CS, contains a regular Geographic Sector defined by lat/lon coordinates of + * corners in case of Projected CS, contains a bounding box of the area + *

          + * AVKey.COORDINATE_SYSTEM_NAME + *

          + * AVKey.PIXEL_WIDTH (Double) pixel size, UTM images usually specify 1 (1 meter); if missing and Geographic + * Coordinate System is specified will be calculated as LongitudeDelta/WIDTH + *

          + * AVKey.PIXEL_HEIGHT (Double) pixel size, UTM images usually specify 1 (1 meter); if missing and Geographic + * Coordinate System is specified will be calculated as LatitudeDelta/HEIGHT + *

          + * AVKey.ORIGIN (LatLon) specifies coordinate of the image's origin (one of the corners, or center) If missing, + * upper left corner will be set as origin + *

          + * AVKey.DATE_TIME (0 terminated String, length == 20) if missing, current date and time will be used + *

          + * AVKey.PIXEL_FORMAT required (valid values: AVKey.ELEVATION | AVKey.IMAGE } specifies weather it is a digital + * elevation model or image + *

          + * AVKey.IMAGE_COLOR_FORMAT required if AVKey.PIXEL_FORMAT is AVKey.IMAGE (valid values: AVKey.COLOR and + * AVKey.MONOCHROME) + *

          + * AVKey.DATA_TYPE required ( valid values: AVKey.INT16, and AVKey.FLOAT32 ) + *

          + * AVKey.VERSION optional, if missing a default will be used "NASA WorldWind" + *

          + * AVKey.DISPLAY_NAME, (String) optional, specifies a name of the document/image + *

          + * AVKey.DESCRIPTION (String) optional, for any kind of descriptions + *

          + * AVKey.MISSING_DATA_SIGNAL optional, set the AVKey.MISSING_DATA_SIGNAL ONLY if you know for sure that the + * specified value actually represents void (NODATA) areas. Elevation data usually has "-32767" (like DTED), or + * "-32768" like SRTM, but some has "0" (mostly images) and "-9999" like NED. Note! Setting "-9999" is very ambiguos + * because -9999 for elevation is valid value; + *

          + * AVKey.MISSING_DATA_REPLACEMENT (String type forced by spec) Most images have "NODATA" as "0", elevations have as + * "-9999", or "-32768" (sometimes "-32767") + *

          + * AVKey.COORDINATE_SYSTEM required, valid values AVKey.COORDINATE_SYSTEM_GEOGRAPHIC or + * AVKey.COORDINATE_SYSTEM_PROJECTED + *

          + * AVKey.COORDINATE_SYSTEM_NAME Optional, A name of the Coordinates System as a String + *

          + * AVKey.PROJECTION_EPSG_CODE Required; Integer; EPSG code or Projection Code If CS is Geodetic and EPSG code is not + * specified, a default WGS84 (4326) will be used + *

          + * AVKey.PROJECTION_DATUM Optional, AVKey.PROJECTION_DESC Optional, AVKey.PROJECTION_NAME Optional, + * AVKey.PROJECTION_UNITS Optional, + *

          + * AVKey.ELEVATION_UNIT Required, if AVKey.PIXEL_FORMAT = AVKey.ELEVATION, value: AVKey.UNIT_FOOT or + * AVKey.UNIT_METER (default, if not specified) + *

          + * AVKey.RASTER_PIXEL, optional, values: AVKey.RASTER_PIXEL_IS_AREA or AVKey.RASTER_PIXEL_IS_POINT if not specified, + * default for images is RASTER_PIXEL_IS_AREA, and AVKey.RASTER_PIXEL_IS_POINT for elevations */ public static AVList extractRasterParameters(Dataset ds, AVList params, boolean quickReadingMode) - throws IllegalArgumentException, WWRuntimeException - { - if (null == params) - { + throws IllegalArgumentException, WWRuntimeException { + if (null == params) { params = new AVListImpl(); } - if (!gdalIsAvailable.get()) - { + if (!gdalIsAvailable.get()) { String message = Logging.getMessage("gdal.GDALNotAvailable"); Logging.logger().finest(message); throw new WWRuntimeException(message); } - if (null == ds) - { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().finest(message); throw new IllegalArgumentException(message); } int width = ds.getRasterXSize(); - if (0 >= width) - { + if (0 >= width) { String message = Logging.getMessage("generic.InvalidWidth", width); Logging.logger().finest(message); throw new IllegalArgumentException(message); @@ -1374,8 +1155,7 @@ public static AVList extractRasterParameters(Dataset ds, AVList params, boolean params.setValue(AVKey.WIDTH, width); int height = ds.getRasterYSize(); - if (0 >= height) - { + if (0 >= height) { String message = Logging.getMessage("generic.InvalidHeight", height); Logging.logger().finest(message); throw new IllegalArgumentException(message); @@ -1383,8 +1163,7 @@ public static AVList extractRasterParameters(Dataset ds, AVList params, boolean params.setValue(AVKey.HEIGHT, height); int bandCount = ds.getRasterCount(); - if (0 >= bandCount) - { + if (0 >= bandCount) { String message = Logging.getMessage("generic.UnexpectedBandCount", bandCount); Logging.logger().finest(message); throw new WWRuntimeException(message); @@ -1392,131 +1171,99 @@ public static AVList extractRasterParameters(Dataset ds, AVList params, boolean params.setValue(AVKey.NUM_BANDS, bandCount); Band band = ds.GetRasterBand(1); - if (null != band) - { - if (band.GetOverviewCount() > 0) - { + if (null != band) { + if (band.GetOverviewCount() > 0) { params.setValue(AVKey.RASTER_HAS_OVERVIEWS, Boolean.TRUE); } int dataType = band.getDataType(); - if (dataType == gdalconst.GDT_Int16 || dataType == gdalconst.GDT_CInt16) - { + if (dataType == gdalconst.GDT_Int16 || dataType == gdalconst.GDT_CInt16) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); params.setValue(AVKey.DATA_TYPE, AVKey.INT16); - } - else if (dataType == gdalconst.GDT_Int32 || dataType == gdalconst.GDT_CInt32) - { + } else if (dataType == gdalconst.GDT_Int32 || dataType == gdalconst.GDT_CInt32) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); params.setValue(AVKey.DATA_TYPE, AVKey.INT32); - } - else if (dataType == gdalconst.GDT_Float32 || dataType == gdalconst.GDT_CFloat32) - { + } else if (dataType == gdalconst.GDT_Float32 || dataType == gdalconst.GDT_CFloat32) { params.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION); params.setValue(AVKey.DATA_TYPE, AVKey.FLOAT32); - } - else if (dataType == gdalconst.GDT_Byte) - { + } else if (dataType == gdalconst.GDT_Byte) { int colorInt = band.GetColorInterpretation(); - if (colorInt == gdalconst.GCI_GrayIndex && bandCount < 3) - { + if (colorInt == gdalconst.GCI_GrayIndex && bandCount < 3) { params.setValue(AVKey.IMAGE_COLOR_FORMAT, AVKey.GRAYSCALE); - } - else - { + } else { // if has only one band => one byte index of the palette, 216 marks voids params.setValue(AVKey.IMAGE_COLOR_FORMAT, AVKey.COLOR); } params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); params.setValue(AVKey.DATA_TYPE, AVKey.INT8); - } - else if (dataType == gdalconst.GDT_UInt16) - { + } else if (dataType == gdalconst.GDT_UInt16) { params.setValue(AVKey.IMAGE_COLOR_FORMAT, - ((bandCount >= 3) ? AVKey.COLOR : AVKey.GRAYSCALE)); + ((bandCount >= 3) ? AVKey.COLOR : AVKey.GRAYSCALE)); params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); params.setValue(AVKey.DATA_TYPE, AVKey.INT16); - } - else if (dataType == gdalconst.GDT_UInt32) - { + } else if (dataType == gdalconst.GDT_UInt32) { params.setValue(AVKey.IMAGE_COLOR_FORMAT, - ((bandCount >= 3) ? AVKey.COLOR : AVKey.GRAYSCALE)); + ((bandCount >= 3) ? AVKey.COLOR : AVKey.GRAYSCALE)); params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE); params.setValue(AVKey.DATA_TYPE, AVKey.INT32); - } - else - { + } else { String msg = Logging.getMessage("generic.UnrecognizedDataType", dataType); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } - if ("GTiff".equalsIgnoreCase(ds.GetDriver().getShortName())) - { + if ("GTiff".equalsIgnoreCase(ds.GetDriver().getShortName())) { Double[] noDataVal = new Double[1]; band.GetNoDataValue(noDataVal); - if (noDataVal[0] != null) - { + if (noDataVal[0] != null) { params.setValue(AVKey.MISSING_DATA_SIGNAL, noDataVal[0]); } } if ("GTiff".equalsIgnoreCase(ds.GetDriver().getShortName()) - && params.hasKey(AVKey.FILE) - && AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT)) - && !params.hasKey(AVKey.ELEVATION_UNIT)) - { + && params.hasKey(AVKey.FILE) + && AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT)) + && !params.hasKey(AVKey.ELEVATION_UNIT)) { GeotiffReader reader = null; - try - { + try { File src = (File) params.getValue(AVKey.FILE); AVList tiffParams = new AVListImpl(); reader = new GeotiffReader(src); reader.copyMetadataTo(tiffParams); - WWUtil.copyValues(tiffParams, params, new String[] {AVKey.ELEVATION_UNIT, + WWUtil.copyValues(tiffParams, params, new String[]{AVKey.ELEVATION_UNIT, AVKey.ELEVATION_MIN, AVKey.ELEVATION_MAX, AVKey.MISSING_DATA_SIGNAL}, false); - } - catch (Throwable t) - { + } catch (Throwable t) { Logging.logger().finest(WWUtil.extractExceptionReason(t)); - } - finally - { - if (null != reader) + } finally { + if (null != reader) { reader.dispose(); + } } } extractMinMaxSampleValues(ds, band, params); if (AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT)) - && (!params.hasKey(AVKey.ELEVATION_MIN) - || !params.hasKey(AVKey.ELEVATION_MAX) - || !params.hasKey(AVKey.MISSING_DATA_SIGNAL) - ) - // skip this heavy calculation if the file is opened in Quick Reading Node (when checking canRead()) - && !quickReadingMode - ) - { + && (!params.hasKey(AVKey.ELEVATION_MIN) + || !params.hasKey(AVKey.ELEVATION_MAX) + || !params.hasKey(AVKey.MISSING_DATA_SIGNAL)) + // skip this heavy calculation if the file is opened in Quick Reading Node (when checking canRead()) + && !quickReadingMode) { double[] minmax = new double[2]; band.ComputeRasterMinMax(minmax); - if (ElevationsUtil.isKnownMissingSignal(minmax[0])) - { + if (ElevationsUtil.isKnownMissingSignal(minmax[0])) { params.setValue(AVKey.MISSING_DATA_SIGNAL, minmax[0]); - if (setNoDataValue(band, minmax[0])) - { + if (setNoDataValue(band, minmax[0])) { band.ComputeRasterMinMax(minmax); params.setValue(AVKey.ELEVATION_MIN, minmax[0]); params.setValue(AVKey.ELEVATION_MAX, minmax[1]); } - } - else - { + } else { params.setValue(AVKey.ELEVATION_MIN, minmax[0]); params.setValue(AVKey.ELEVATION_MAX, minmax[1]); } @@ -1525,24 +1272,20 @@ else if (dataType == gdalconst.GDT_UInt32) String proj_wkt = null; - if (params.hasKey(AVKey.SPATIAL_REFERENCE_WKT)) - { + if (params.hasKey(AVKey.SPATIAL_REFERENCE_WKT)) { proj_wkt = params.getStringValue(AVKey.SPATIAL_REFERENCE_WKT); } - if (WWUtil.isEmpty(proj_wkt)) - { + if (WWUtil.isEmpty(proj_wkt)) { proj_wkt = ds.GetProjectionRef(); } - if (WWUtil.isEmpty(proj_wkt)) - { + if (WWUtil.isEmpty(proj_wkt)) { proj_wkt = ds.GetProjection(); } SpatialReference srs = null; - if (!WWUtil.isEmpty(proj_wkt)) - { + if (!WWUtil.isEmpty(proj_wkt)) { params.setValue(AVKey.SPATIAL_REFERENCE_WKT, proj_wkt); srs = new SpatialReference(proj_wkt); } @@ -1550,8 +1293,7 @@ else if (dataType == gdalconst.GDT_UInt32) double[] gt = new double[6]; ds.GetGeoTransform(gt); - if (gt[GDAL.GT_5_PIXEL_HEIGHT] > 0) - { + if (gt[GDAL.GT_5_PIXEL_HEIGHT] > 0) { gt[GDAL.GT_5_PIXEL_HEIGHT] = -gt[GDAL.GT_5_PIXEL_HEIGHT]; } @@ -1571,36 +1313,27 @@ else if (dataType == gdalconst.GDT_UInt32) params.setValue(AVKey.PIXEL_WIDTH, pixelWidth); params.setValue(AVKey.PIXEL_HEIGHT, pixelHeight); - if (minX == 0d && pixelWidth == 1d && rotX == 0d && maxY == 0d && rotY == 0d && pixelHeight == 1d) - { + if (minX == 0d && pixelWidth == 1d && rotX == 0d && maxY == 0d && rotY == 0d && pixelHeight == 1d) { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_SCREEN); - } - else if (Angle.isValidLongitude(minX) && Angle.isValidLatitude(maxY) - && Angle.isValidLongitude(maxX) && Angle.isValidLatitude(minY)) - { - if (null == srs) - { + } else if (Angle.isValidLongitude(minX) && Angle.isValidLatitude(maxY) + && Angle.isValidLongitude(maxX) && Angle.isValidLatitude(minY)) { + if (null == srs) { srs = createGeographicSRS(); - } - else if (srs.IsGeographic() == 0) - { + } else if (srs.IsGeographic() == 0) { String msg = Logging.getMessage("generic.UnexpectedCoordinateSystem", srs.ExportToWkt()); Logging.logger().warning(msg); srs = createGeographicSRS(); } } - if (null != srs) - { + if (null != srs) { Sector sector = null; - if (!params.hasKey(AVKey.SPATIAL_REFERENCE_WKT)) - { + if (!params.hasKey(AVKey.SPATIAL_REFERENCE_WKT)) { params.setValue(AVKey.SPATIAL_REFERENCE_WKT, srs.ExportToWkt()); } - if (srs.IsLocal() == 1) - { + if (srs.IsLocal() == 1) { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_UNKNOWN); String msg = Logging.getMessage("generic.UnknownCoordinateSystem", proj_wkt); Logging.logger().severe(msg); @@ -1611,25 +1344,20 @@ else if (srs.IsGeographic() == 0) // save area in image's native CS and Projection GDAL.Area area = new GDAL.Area(srs, ds); - if (null != area) - { + if (null != area) { params.setValue(AVKey.GDAL_AREA, area); sector = area.getSector(); - if (null != sector) - { + if (null != sector) { params.setValue(AVKey.SECTOR, sector); LatLon origin = new LatLon(sector.getMaxLatitude(), sector.getMinLongitude()); params.setValue(AVKey.ORIGIN, origin); } } - if (srs.IsGeographic() == 1) - { + if (srs.IsGeographic() == 1) { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC); // no need to extract anything, all parameters were extracted above - } - else if (srs.IsProjected() == 1) - { + } else if (srs.IsProjected() == 1) { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_PROJECTED); // ----8><---------------------------------------------------------------------------------------- @@ -1662,41 +1390,28 @@ else if (srs.IsProjected() == 1) // AUTHORITY [ "EPSG", "26986" ] // ] // ----8><---------------------------------------------------------------------------------------- - // String projcs = srs.GetAttrValue("PROJCS"); // String geocs = srs.GetAttrValue("PROJCS|GEOGCS"); // String projcs_unit = srs.GetAttrValue("PROJCS|GEOGCS|UNIT"); - String projection = srs.GetAttrValue("PROJCS|PROJECTION"); String unit = srs.GetAttrValue("PROJCS|UNIT"); - if (null != unit) - { + if (null != unit) { unit = unit.toLowerCase(); - if ("meter".equals(unit) || "meters".equals(unit) || "metre".equals(unit) || "metres".equals(unit)) - { + if ("meter".equals(unit) || "meters".equals(unit) || "metre".equals(unit) || "metres".equals(unit)) { params.setValue(AVKey.PROJECTION_UNITS, AVKey.UNIT_METER); - } - else if ("foot".equals(unit) || "feet".equals(unit)) - { + } else if ("foot".equals(unit) || "feet".equals(unit)) { params.setValue(AVKey.PROJECTION_UNITS, AVKey.UNIT_FOOT); - } - else - { + } else { Logging.logger().warning(Logging.getMessage("generic.UnknownProjectionUnits", unit)); } } - if (null != projection && 0 < projection.length()) - { + if (null != projection && 0 < projection.length()) { params.setValue(AVKey.PROJECTION_NAME, projection); } - } - else if (srs.IsLocal() == 1) - { + } else if (srs.IsLocal() == 1) { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_SCREEN); - } - else - { + } else { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_UNKNOWN); String msg = Logging.getMessage("generic.UnknownCoordinateSystem", proj_wkt); Logging.logger().severe(msg); @@ -1704,23 +1419,19 @@ else if (srs.IsLocal() == 1) } } - if (!params.hasKey(AVKey.COORDINATE_SYSTEM)) - { + if (!params.hasKey(AVKey.COORDINATE_SYSTEM)) { params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_UNKNOWN); } return params; } - protected static Double convertStringToDouble(String s) - { + protected static Double convertStringToDouble(String s) { return (s == null) ? null : WWUtil.convertStringToDouble(s); } - protected static void extractMinMaxSampleValues(Dataset ds, Band band, AVList params) - { - if (null != ds && null != params && AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT))) - { + protected static void extractMinMaxSampleValues(Dataset ds, Band band, AVList params) { + if (null != ds && null != params && AVKey.ELEVATION.equals(params.getValue(AVKey.PIXEL_FORMAT))) { band = (null != band) ? band : ds.GetRasterBand(1); Double[] dbls = new Double[16]; @@ -1730,9 +1441,7 @@ protected static void extractMinMaxSampleValues(Dataset ds, Band band, AVList pa // TODO garakl This feature is not working for GeoTiff files // String type = band.GetUnitType(); - - if (minValue == null || maxValue == null) - { + if (minValue == null || maxValue == null) { band.GetMinimum(dbls); minValue = (null != dbls[0]) ? dbls[0] : minValue; @@ -1742,39 +1451,37 @@ protected static void extractMinMaxSampleValues(Dataset ds, Band band, AVList pa band.GetNoDataValue(dbls); Double missingSignal = (null != dbls[0]) - ? dbls[0] : convertStringToDouble(ds.GetMetadataItem("TIFFTAG_GDAL_NODATA")); + ? dbls[0] : convertStringToDouble(ds.GetMetadataItem("TIFFTAG_GDAL_NODATA")); - if (ElevationsUtil.isKnownMissingSignal(minValue)) - { - if (missingSignal == null) + if (ElevationsUtil.isKnownMissingSignal(minValue)) { + if (missingSignal == null) { missingSignal = minValue; + } minValue = null; } - if (null != minValue) + if (null != minValue) { params.setValue(AVKey.ELEVATION_MIN, minValue); + } - if (null != maxValue) + if (null != maxValue) { params.setValue(AVKey.ELEVATION_MAX, maxValue); + } - if (null != missingSignal) + if (null != missingSignal) { params.setValue(AVKey.MISSING_DATA_SIGNAL, missingSignal); + } } } - protected static boolean setNoDataValue(Band band, Double nodata) - { - if (null != band && null != nodata) - { - try - { + protected static boolean setNoDataValue(Band band, Double nodata) { + if (null != band && null != nodata) { + try { gdal.PushErrorHandler("CPLQuietErrorHandler"); return gdalconst.CE_None == band.SetNoDataValue(nodata); - } - finally - { + } finally { gdal.PopErrorHandler(); } } @@ -1783,10 +1490,8 @@ protected static boolean setNoDataValue(Band band, Double nodata) } public static DataRaster composeDataRaster(Dataset ds, AVList params) - throws IllegalArgumentException, WWRuntimeException - { - if (!gdalIsAvailable.get()) - { + throws IllegalArgumentException, WWRuntimeException { + if (!gdalIsAvailable.get()) { String message = Logging.getMessage("gdal.GDALNotAvailable"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -1795,16 +1500,11 @@ public static DataRaster composeDataRaster(Dataset ds, AVList params) params = extractRasterParameters(ds, params, false); String pixelFormat = params.getStringValue(AVKey.PIXEL_FORMAT); - if (AVKey.ELEVATION.equals(pixelFormat)) - { + if (AVKey.ELEVATION.equals(pixelFormat)) { return composeNonImageDataRaster(ds, params); - } - else if (AVKey.IMAGE.equals(pixelFormat)) - { + } else if (AVKey.IMAGE.equals(pixelFormat)) { return composeImageDataRaster(ds, params); - } - else - { + } else { String message = Logging.getMessage("generic.UnexpectedRasterType", pixelFormat); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -1812,22 +1512,18 @@ else if (AVKey.IMAGE.equals(pixelFormat)) } public static int[] extractBandOrder(Dataset ds, AVList params) - throws IllegalArgumentException, WWRuntimeException - { - if (!gdalIsAvailable.get()) - { + throws IllegalArgumentException, WWRuntimeException { + if (!gdalIsAvailable.get()) { String message = Logging.getMessage("gdal.GDALNotAvailable"); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (null == ds) - { + if (null == ds) { String message = Logging.getMessage("nullValue.DataSetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (null == params) - { + if (null == params) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1835,44 +1531,35 @@ public static int[] extractBandOrder(Dataset ds, AVList params) int[] bandsOrder = null; - if (params.hasKey(AVKey.BANDS_ORDER)) - { + if (params.hasKey(AVKey.BANDS_ORDER)) { int bandsCount = ds.getRasterCount(); Object o = params.getValue(AVKey.BANDS_ORDER); - if (null != o && o instanceof Integer[]) - { + if (null != o && o instanceof Integer[]) { Integer[] order = (Integer[]) o; bandsOrder = new int[order.length]; - for (int i = 0; i < order.length; i++) - { + for (int i = 0; i < order.length; i++) { bandsOrder[i] = order[i]; } - } - else if (null != o && o instanceof int[]) - { + } else if (null != o && o instanceof int[]) { bandsOrder = (int[]) o; } - if (null == bandsOrder) - { + if (null == bandsOrder) { String message = Logging.getMessage("nullValue.BandOrderIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (0 == bandsOrder.length) - { + if (0 == bandsOrder.length) { String message = Logging.getMessage("generic.BandOrderIsEmpty"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - for (int i = 0; i < bandsOrder.length; i++) - { - if (bandsOrder[i] < 0 || bandsOrder[i] >= bandsCount) - { + for (int i = 0; i < bandsOrder.length; i++) { + if (bandsOrder[i] < 0 || bandsOrder[i] >= bandsCount) { String message = Logging.getMessage("generic.InvalidBandOrder", bandsOrder[i], bandsCount); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1886,30 +1573,26 @@ else if (null != o && o instanceof int[]) /** * The "composeDataRaster" method creates a ByteBufferRaster from an elevation (or non-image) Dataset. * - * @param ds The GDAL dataset with data raster (expected only elevation raster); f or imagery rasters use - * composeImageDataRaster() method + * @param ds The GDAL dataset with data raster (expected only elevation raster); f or imagery rasters use + * composeImageDataRaster() method * @param params , The AVList with properties (usually used to force projection info or sector) * * @return ByteBufferRaster as DataRaster * * @throws IllegalArgumentException if raster parameters (height, width, sector, etc) are invalid - * @throws WWRuntimeException when invalid raster detected (like attempt to use the method for imagery - * raster) + * @throws WWRuntimeException when invalid raster detected (like attempt to use the method for imagery raster) */ protected static DataRaster composeNonImageDataRaster(Dataset ds, AVList params) - throws IllegalArgumentException, WWRuntimeException - { + throws IllegalArgumentException, WWRuntimeException { String pixelFormat = params.getStringValue(AVKey.PIXEL_FORMAT); - if (!AVKey.ELEVATION.equals(pixelFormat)) - { + if (!AVKey.ELEVATION.equals(pixelFormat)) { String message = Logging.getMessage("generic.UnexpectedRasterType", pixelFormat); Logging.logger().severe(message); throw new WWRuntimeException(message); } Object o = params.getValue(AVKey.SECTOR); - if (null == o || !(o instanceof Sector)) - { + if (null == o || !(o instanceof Sector)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -1918,31 +1601,26 @@ protected static DataRaster composeNonImageDataRaster(Dataset ds, AVList params) int bandCount = ds.getRasterCount(); // we expect here one band (elevation rasters have -32767 or -32768 in void places) data raster - if (bandCount != 1) - { + if (bandCount != 1) { String message = Logging.getMessage("generic.UnexpectedBandCount", bandCount); Logging.logger().severe(message); throw new WWRuntimeException(message); } ByteOrder byteOrder = ByteOrder.nativeOrder(); - if (params.hasKey(AVKey.BYTE_ORDER)) - { + if (params.hasKey(AVKey.BYTE_ORDER)) { byteOrder = AVKey.LITTLE_ENDIAN.equals(params.getStringValue(AVKey.BYTE_ORDER)) - ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; - } - else - { + ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; + } else { params.setValue(AVKey.BYTE_ORDER, - (byteOrder == ByteOrder.BIG_ENDIAN) ? AVKey.BIG_ENDIAN : AVKey.LITTLE_ENDIAN); + (byteOrder == ByteOrder.BIG_ENDIAN) ? AVKey.BIG_ENDIAN : AVKey.LITTLE_ENDIAN); } int width = ds.getRasterXSize(); int height = ds.getRasterYSize(); Band band = ds.GetRasterBand(1); - if (null == band) - { + if (null == band) { String message = Logging.getMessage("nullValue.RasterBandIsNull"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -1953,12 +1631,9 @@ protected static DataRaster composeNonImageDataRaster(Dataset ds, AVList params) int bufferSize = width * height * (dataTypeSize / 8); ByteBuffer data = null; - try - { + try { data = ByteBuffer.allocateDirect(bufferSize); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = Logging.getMessage("generic.MemoryAllocationError", bufferSize); Logging.logger().log(Level.SEVERE, message, t); throw new WWRuntimeException(message); @@ -1967,10 +1642,9 @@ protected static DataRaster composeNonImageDataRaster(Dataset ds, AVList params) data.order(byteOrder); int returnVal = band.ReadRaster_Direct(0, 0, band.getXSize(), band.getYSize(), - width, height, band.getDataType(), data); + width, height, band.getDataType(), data); - if (returnVal != gdalconstConstants.CE_None) - { + if (returnVal != gdalconstConstants.CE_None) { throw new WWRuntimeException(GDALUtils.getErrorMessage()); } @@ -1980,17 +1654,14 @@ protected static DataRaster composeNonImageDataRaster(Dataset ds, AVList params) } protected static void alterJavaLibraryPath(String newJavaLibraryPath) - throws IllegalAccessException, NoSuchFieldException - { + throws IllegalAccessException, NoSuchFieldException { System.setProperty(JAVA_LIBRARY_PATH, newJavaLibraryPath); newClassLoader = ClassLoader.class; fieldSysPaths = newClassLoader.getDeclaredField("sys_paths"); - if (null != fieldSysPaths) - { + if (null != fieldSysPaths) { fieldSysPaths_accessible = fieldSysPaths.isAccessible(); - if (!fieldSysPaths_accessible) - { + if (!fieldSysPaths_accessible) { fieldSysPaths.setAccessible(true); } @@ -2002,19 +1673,14 @@ protected static void alterJavaLibraryPath(String newJavaLibraryPath) } } - protected static void restoreJavaLibraryPath() - { - try - { + protected static void restoreJavaLibraryPath() { + try { //Revert back the changes. - if (null != originalClassLoader && null != fieldSysPaths) - { + if (null != originalClassLoader && null != fieldSysPaths) { fieldSysPaths.set(newClassLoader, originalClassLoader); fieldSysPaths.setAccessible(fieldSysPaths_accessible); } - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, e.getMessage(), e); } } @@ -2023,4 +1689,4 @@ protected static void restoreJavaLibraryPath() private static Object originalClassLoader = null; private static Field fieldSysPaths = null; private static boolean fieldSysPaths_accessible = false; -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwind/util/layertree/KMLContainerTreeNode.java b/src/gov/nasa/worldwind/util/layertree/KMLContainerTreeNode.java index 0acde1a56c..91d567d00e 100644 --- a/src/gov/nasa/worldwind/util/layertree/KMLContainerTreeNode.java +++ b/src/gov/nasa/worldwind/util/layertree/KMLContainerTreeNode.java @@ -15,8 +15,8 @@ * @author dcollins * @version $Id: KMLContainerTreeNode.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLContainerTreeNode extends KMLFeatureTreeNode -{ +public class KMLContainerTreeNode extends KMLFeatureTreeNode { + /** * Creates a new KMLContainerTreeNode from the specified container. The node's name is set * to the feature's name, and the node's hierarchy is populated from the container's KML features. @@ -25,8 +25,7 @@ public class KMLContainerTreeNode extends KMLFeatureTreeNode * * @throws IllegalArgumentException if the container is null. */ - public KMLContainerTreeNode(KMLAbstractContainer container) - { + public KMLContainerTreeNode(KMLAbstractContainer container) { super(container); } @@ -36,28 +35,29 @@ public KMLContainerTreeNode(KMLAbstractContainer container) * @return this node's KML container. */ @Override - public KMLAbstractContainer getFeature() - { + public KMLAbstractContainer getFeature() { return (KMLAbstractContainer) super.getFeature(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void initialize() - { + protected void initialize() { super.initialize(); this.refresh(); } - /** Populate this node's hierarchy from the KML features in its KMLAbstractContainer. */ - protected void refresh() - { + /** + * Populate this node's hierarchy from the KML features in its KMLAbstractContainer. + */ + protected void refresh() { this.removeAllChildren(); - for (KMLAbstractFeature child : this.getFeature().getFeatures()) - { - if (child != null) + for (KMLAbstractFeature child : this.getFeature().getFeatures()) { + if (child != null) { this.addFeatureNode(child); + } } } @@ -66,10 +66,10 @@ protected void refresh() * * @param feature the KML feature to add. */ - protected void addFeatureNode(KMLAbstractFeature feature) - { + protected void addFeatureNode(KMLAbstractFeature feature) { TreeNode featureNode = KMLFeatureTreeNode.fromKMLFeature(feature); - if (featureNode != null) + if (featureNode != null) { this.addChild(featureNode); + } } } diff --git a/src/gov/nasa/worldwind/util/layertree/KMLFeatureTreeNode.java b/src/gov/nasa/worldwind/util/layertree/KMLFeatureTreeNode.java index 331c79a1d1..63b4cbb246 100644 --- a/src/gov/nasa/worldwind/util/layertree/KMLFeatureTreeNode.java +++ b/src/gov/nasa/worldwind/util/layertree/KMLFeatureTreeNode.java @@ -23,9 +23,11 @@ * @author dcollins * @version $Id: KMLFeatureTreeNode.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLFeatureTreeNode extends BasicTreeNode -{ - /** Indicates the KML feature this node represents. Initialized during construction. */ +public class KMLFeatureTreeNode extends BasicTreeNode { + + /** + * Indicates the KML feature this node represents. Initialized during construction. + */ protected KMLAbstractFeature feature; /** @@ -36,12 +38,10 @@ public class KMLFeatureTreeNode extends BasicTreeNode * * @throws IllegalArgumentException if the feature is null. */ - public KMLFeatureTreeNode(KMLAbstractFeature feature) - { + public KMLFeatureTreeNode(KMLAbstractFeature feature) { super(""); // Node text is set below - if (feature == null) - { + if (feature == null) { String message = Logging.getMessage("nullValue.FeatureIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -52,9 +52,10 @@ public KMLFeatureTreeNode(KMLAbstractFeature feature) this.initialize(); } - /** Places the KML feature in the node's AVKey.CONTEXT field. */ - protected void initialize() - { + /** + * Places the KML feature in the node's AVKey.CONTEXT field. + */ + protected void initialize() { // The CONTEXT key identifies the KML feature this tree node is associated with. this.setValue(AVKey.CONTEXT, this.getFeature()); } @@ -70,21 +71,20 @@ protected void initialize() * * @throws IllegalArgumentException if the feature is null. */ - public static KMLFeatureTreeNode fromKMLFeature(KMLAbstractFeature feature) - { - if (feature == null) - { + public static KMLFeatureTreeNode fromKMLFeature(KMLAbstractFeature feature) { + if (feature == null) { String message = Logging.getMessage("nullValue.FeatureIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (feature instanceof KMLNetworkLink) + if (feature instanceof KMLNetworkLink) { return new KMLNetworkLinkTreeNode((KMLNetworkLink) feature); - else if (feature instanceof KMLAbstractContainer) + } else if (feature instanceof KMLAbstractContainer) { return new KMLContainerTreeNode((KMLAbstractContainer) feature); - else + } else { return new KMLFeatureTreeNode(feature); + } } /** @@ -92,8 +92,7 @@ else if (feature instanceof KMLAbstractContainer) * * @return this node's KML feature. */ - public KMLAbstractFeature getFeature() - { + public KMLAbstractFeature getFeature() { return this.feature; } @@ -103,8 +102,7 @@ public KMLAbstractFeature getFeature() * @return true if the KML feature is enabled for rendering, otherwise false. */ @Override - public boolean isSelected() - { + public boolean isSelected() { Boolean b = this.feature.getVisibility(); return b == null || b; } @@ -116,8 +114,7 @@ public boolean isSelected() * @param selected true to enable the KML feature, otherwise false. */ @Override - public void setSelected(boolean selected) - { + public void setSelected(boolean selected) { super.setSelected(selected); this.getFeature().setVisibility(selected); } @@ -135,22 +132,21 @@ public void setSelected(boolean selected) * * @throws IllegalArgumentException if the tree is null. */ - public void expandOpenContainers(Tree tree) - { - if (tree == null) - { + public void expandOpenContainers(Tree tree) { + if (tree == null) { String message = Logging.getMessage("nullValue.TreeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.mustExpandNode()) + if (this.mustExpandNode()) { tree.expandPath(this.getPath()); + } - for (TreeNode child : this.getChildren()) - { - if (child instanceof KMLFeatureTreeNode) + for (TreeNode child : this.getChildren()) { + if (child instanceof KMLFeatureTreeNode) { ((KMLFeatureTreeNode) child).expandOpenContainers(tree); + } } } @@ -160,22 +156,19 @@ public void expandOpenContainers(Tree tree) * * @return true if the tree path for this node must be expanded, otherwise false. */ - protected boolean mustExpandNode() - { + protected boolean mustExpandNode() { return Boolean.TRUE.equals(this.getFeature().getOpen()); } @Override - public String getText() - { + public String getText() { String name = feature.getName(); return name != null ? this.stripHtmlTags(name) : feature.getClass().getSimpleName(); } @Override - public String getDescription() - { + public String getDescription() { return this.makeFeatureDescription(); } @@ -185,24 +178,21 @@ public String getDescription() * * @return The feature description. */ - protected String makeFeatureDescription() - { + protected String makeFeatureDescription() { String text; Object snippet = this.getFeature().getSnippet(); - if (snippet instanceof KMLSnippet) - { + if (snippet instanceof KMLSnippet) { KMLSnippet kmlSnippet = (KMLSnippet) snippet; // Check the maxLines property of the snippet. maxLines == 0, don't set any description. Integer maxLines = kmlSnippet.getMaxLines(); - if (maxLines == null || maxLines > 0) + if (maxLines == null || maxLines > 0) { text = kmlSnippet.getCharacters(); - else + } else { text = null; - } - else - { + } + } else { text = this.getFeature().getDescription(); } @@ -215,44 +205,36 @@ protected String makeFeatureDescription() * @param input Text to strip of HTML tags and extra whitespace. * * @return The input string with HTML tags removed, and runs of whitespace collapsed to a single space. Returns - * {@code null} if {@code input} is {@code null}. + * {@code null} if {@code input} is {@code null}. */ - protected String stripHtmlTags(String input) - { - if (input == null) + protected String stripHtmlTags(String input) { + if (input == null) { return null; + } StringBuilder output = new StringBuilder(); boolean inTag = false; boolean inWhitespace = false; - for (int i = 0; i < input.length(); i++) - { + for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); - if (Character.isWhitespace(c)) - { + if (Character.isWhitespace(c)) { inWhitespace = true; continue; } - if (!inTag && inWhitespace && output.length() > 0) - { + if (!inTag && inWhitespace && output.length() > 0) { output.append(' '); } inWhitespace = false; - if (c == '<') - { + if (c == '<') { inTag = true; - } - else if (c == '>') - { + } else if (c == '>') { inTag = false; - } - else if (!inTag) - { + } else if (!inTag) { output.append(c); } } diff --git a/src/gov/nasa/worldwind/util/layertree/KMLLayerTreeNode.java b/src/gov/nasa/worldwind/util/layertree/KMLLayerTreeNode.java index c52810a71e..e903cf5565 100644 --- a/src/gov/nasa/worldwind/util/layertree/KMLLayerTreeNode.java +++ b/src/gov/nasa/worldwind/util/layertree/KMLLayerTreeNode.java @@ -22,9 +22,11 @@ * @version $Id: KMLLayerTreeNode.java 1171 2013-02-11 21:45:02Z dcollins $ * @see KMLFeatureTreeNode */ -public class KMLLayerTreeNode extends LayerTreeNode -{ - /** Indicates the KML feature hierarchy this node represents. Initialized during construction. */ +public class KMLLayerTreeNode extends LayerTreeNode { + + /** + * Indicates the KML feature hierarchy this node represents. Initialized during construction. + */ protected KMLRoot kmlRoot; /** @@ -32,18 +34,16 @@ public class KMLLayerTreeNode extends LayerTreeNode * node's name is set to the layer's name, and the node's hierarchy is populated from the feature hierarchy of the * KMLRoot. * - * @param layer the Layer the kmlRoot corresponds to. + * @param layer the Layer the kmlRoot corresponds to. * @param kmlRoot the KML feature hierarchy this node represents. * * @throws IllegalArgumentException if the layer is null, or if kmlRoot is - * null. + * null. */ - public KMLLayerTreeNode(Layer layer, KMLRoot kmlRoot) - { + public KMLLayerTreeNode(Layer layer, KMLRoot kmlRoot) { super(layer); - if (kmlRoot == null) - { + if (kmlRoot == null) { String message = Logging.getMessage("nullValue.KMLRootIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -53,10 +53,8 @@ public KMLLayerTreeNode(Layer layer, KMLRoot kmlRoot) this.addChildFeatures(); // Add a listener to refresh the tree model when the KML document is updated or a network link is retrieved. - this.kmlRoot.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(final PropertyChangeEvent event) - { + this.kmlRoot.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(final PropertyChangeEvent event) { String name = (event != null) ? event.getPropertyName() : null; Object newValue = (event != null) ? event.getNewValue() : null; KMLAbstractFeature rootFeature = KMLLayerTreeNode.this.kmlRoot.getFeature(); @@ -64,19 +62,13 @@ public void propertyChange(final PropertyChangeEvent event) // Update the document if an update is received, or if this node represents a network link that has been // resolved. if (AVKey.UPDATED.equals(name) - || (AVKey.RETRIEVAL_STATE_SUCCESSFUL.equals(name) && rootFeature == newValue)) - { + || (AVKey.RETRIEVAL_STATE_SUCCESSFUL.equals(name) && rootFeature == newValue)) { // Ensure that the node list is manipulated on the EDT - if (SwingUtilities.isEventDispatchThread()) - { + if (SwingUtilities.isEventDispatchThread()) { KMLLayerTreeNode.this.refresh(); - } - else - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + } else { + SwingUtilities.invokeLater(new Runnable() { + public void run() { KMLLayerTreeNode.this.refresh(); } }); @@ -96,13 +88,11 @@ public void run() * @param selected true to enable the layer, otherwise false. */ @Override - public void setSelected(boolean selected) - { + public void setSelected(boolean selected) { super.setSelected(selected); KMLAbstractFeature feature = this.kmlRoot.getFeature(); - if (feature instanceof KMLAbstractContainer) - { + if (feature instanceof KMLAbstractContainer) { feature.setVisibility(selected); } } @@ -116,11 +106,11 @@ public void setSelected(boolean selected) *

          * This does nothing if the KMLRoot's top level feature is null. */ - protected void addChildFeatures() - { + protected void addChildFeatures() { KMLAbstractFeature rootFeature = this.kmlRoot.getFeature(); - if (rootFeature == null) + if (rootFeature == null) { return; + } // Create a KMLFeatureTreeNode only to construct the description string for the root node and set it on this // node. We do not add the root node to the tree because it would add a redundant. @@ -132,36 +122,30 @@ protected void addChildFeatures() this.setSelected(visibility == null || visibility); // If the root is a container, add its children - if (rootFeature instanceof KMLAbstractContainer) - { + if (rootFeature instanceof KMLAbstractContainer) { KMLAbstractContainer container = (KMLAbstractContainer) rootFeature; - for (KMLAbstractFeature child : container.getFeatures()) - { - if (child != null) + for (KMLAbstractFeature child : container.getFeatures()) { + if (child != null) { this.addFeatureNode(child); + } } } // If the root is a network link, add the linked document - if (rootFeature instanceof KMLNetworkLink) - { + if (rootFeature instanceof KMLNetworkLink) { KMLRoot networkResource = ((KMLNetworkLink) rootFeature).getNetworkResource(); - if (networkResource != null && networkResource.getFeature() != null) - { + if (networkResource != null && networkResource.getFeature() != null) { rootFeature = networkResource.getFeature(); // Don't add Document nodes (they don't provide meaningful grouping). - if (rootFeature instanceof KMLDocument) - { + if (rootFeature instanceof KMLDocument) { KMLAbstractContainer container = (KMLAbstractContainer) rootFeature; - for (KMLAbstractFeature child : container.getFeatures()) - { - if (child != null) + for (KMLAbstractFeature child : container.getFeatures()) { + if (child != null) { this.addFeatureNode(child); + } } - } - else if (rootFeature != null) - { + } else if (rootFeature != null) { this.addFeatureNode(rootFeature); } } @@ -173,11 +157,11 @@ else if (rootFeature != null) * * @param feature the KML feature to add. */ - protected void addFeatureNode(KMLAbstractFeature feature) - { + protected void addFeatureNode(KMLAbstractFeature feature) { TreeNode featureNode = KMLFeatureTreeNode.fromKMLFeature(feature); - if (featureNode != null) + if (featureNode != null) { this.addChild(featureNode); + } } /** @@ -194,22 +178,21 @@ protected void addFeatureNode(KMLAbstractFeature feature) * * @throws IllegalArgumentException if the tree is null. */ - public void expandOpenContainers(Tree tree) - { - if (tree == null) - { + public void expandOpenContainers(Tree tree) { + if (tree == null) { String message = Logging.getMessage("nullValue.TreeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.mustExpandNode()) + if (this.mustExpandNode()) { tree.expandPath(this.getPath()); + } - for (TreeNode child : this.getChildren()) - { - if (child instanceof KMLFeatureTreeNode) + for (TreeNode child : this.getChildren()) { + if (child instanceof KMLFeatureTreeNode) { ((KMLFeatureTreeNode) child).expandOpenContainers(tree); + } } } @@ -220,19 +203,18 @@ public void expandOpenContainers(Tree tree) * * @return true if the tree path for this node must be expanded, otherwise false. */ - protected boolean mustExpandNode() - { - if (this.kmlRoot.getFeature() instanceof KMLAbstractContainer) - { + protected boolean mustExpandNode() { + if (this.kmlRoot.getFeature() instanceof KMLAbstractContainer) { return Boolean.TRUE.equals(this.kmlRoot.getFeature().getOpen()); } return this.kmlRoot.getFeature() != null; } - /** Refresh the tree model to match the contents of the KML document. */ - protected void refresh() - { + /** + * Refresh the tree model to match the contents of the KML document. + */ + protected void refresh() { this.removeAllChildren(); this.addChildFeatures(); } diff --git a/src/gov/nasa/worldwind/util/layertree/KMLNetworkLinkTreeNode.java b/src/gov/nasa/worldwind/util/layertree/KMLNetworkLinkTreeNode.java index 937eff5839..10b008c6a7 100644 --- a/src/gov/nasa/worldwind/util/layertree/KMLNetworkLinkTreeNode.java +++ b/src/gov/nasa/worldwind/util/layertree/KMLNetworkLinkTreeNode.java @@ -15,14 +15,14 @@ * A KMLFeatureTreeNode that represents a KML network link defined by a {@link * gov.nasa.worldwind.ogc.kml.KMLNetworkLink}. *

          - * KMLNetworkLinkTreeNode automatically repopulates its hierarchy when its KMLNetworkLink is + * KMLNetworkLinkTreeNode automatically repopulates its hierarchy when its KMLNetworkLink is * refreshed, and notifies its listeners when this happens. * * @author dcollins * @version $Id: KMLNetworkLinkTreeNode.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class KMLNetworkLinkTreeNode extends KMLContainerTreeNode -{ +public class KMLNetworkLinkTreeNode extends KMLContainerTreeNode { + /** * Creates a new KMLNetworkLinkTreeNode from the specified networkLink. The node's name is * set to the network link's name, and the node's hierarchy is populated from the network link's KML features. @@ -31,8 +31,7 @@ public class KMLNetworkLinkTreeNode extends KMLContainerTreeNode * * @throws IllegalArgumentException if the networkLink is null. */ - public KMLNetworkLinkTreeNode(KMLNetworkLink networkLink) - { + public KMLNetworkLinkTreeNode(KMLNetworkLink networkLink) { super(networkLink); } @@ -42,8 +41,7 @@ public KMLNetworkLinkTreeNode(KMLNetworkLink networkLink) * @return this node's KML network link. */ @Override - public KMLNetworkLink getFeature() - { + public KMLNetworkLink getFeature() { return (KMLNetworkLink) super.getFeature(); } @@ -55,35 +53,26 @@ public KMLNetworkLink getFeature() * KMLNetworkLink. */ @Override - protected void initialize() - { + protected void initialize() { super.initialize(); // Add a property change listener to the KMLRoot. Upon receiving an RETRIEVAL_STATE_SUCCESSFUL event, // repopulate this node's hierarchy with the KML features in its KMLNetworkLink and fire a // RETRIEVAL_STATE_SUCCESSFUL to this nodes listeners. - this.getFeature().getRoot().addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { + this.getFeature().getRoot().addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (AVKey.RETRIEVAL_STATE_SUCCESSFUL.equals(propertyChangeEvent.getPropertyName()) - && KMLNetworkLinkTreeNode.this.getFeature() == propertyChangeEvent.getNewValue()) - { + && KMLNetworkLinkTreeNode.this.getFeature() == propertyChangeEvent.getNewValue()) { // Ensure that the node list is manipulated on the EDT - if (SwingUtilities.isEventDispatchThread()) - { + if (SwingUtilities.isEventDispatchThread()) { refresh(); KMLNetworkLinkTreeNode.this.firePropertyChange(AVKey.RETRIEVAL_STATE_SUCCESSFUL, null, this); - } - else - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + } else { + SwingUtilities.invokeLater(new Runnable() { + public void run() { refresh(); KMLNetworkLinkTreeNode.this.firePropertyChange(AVKey.RETRIEVAL_STATE_SUCCESSFUL, null, - this); + this); } }); } @@ -102,32 +91,28 @@ public void run() * tree node that doesn't provide any meaningful grouping. */ @Override - protected void refresh() - { + protected void refresh() { // Call super to add features contained by the NetworkLink. super.refresh(); // Now add the network resource. KMLRoot kmlRoot = this.getFeature().getNetworkResource(); - if (kmlRoot == null || kmlRoot.getFeature() == null) + if (kmlRoot == null || kmlRoot.getFeature() == null) { return; + } // A KML document has only one top-level feature. Except for very simple files, this top level is typically a // Document. In this case we skip the top level document, and attach tree nodes for the features beneath that // document. Attaching the document as a tree node would add an extra level to the tree that doesn't provide any // meaningful grouping. - - if (kmlRoot.getFeature() instanceof KMLDocument) - { + if (kmlRoot.getFeature() instanceof KMLDocument) { KMLDocument doc = (KMLDocument) kmlRoot.getFeature(); - for (KMLAbstractFeature child : doc.getFeatures()) - { - if (child != null) + for (KMLAbstractFeature child : doc.getFeatures()) { + if (child != null) { this.addFeatureNode(child); + } } - } - else - { + } else { this.addFeatureNode(kmlRoot.getFeature()); } } diff --git a/src/gov/nasa/worldwind/util/layertree/LayerTree.java b/src/gov/nasa/worldwind/util/layertree/LayerTree.java index f1314bc8a0..f243b7cabf 100644 --- a/src/gov/nasa/worldwind/util/layertree/LayerTree.java +++ b/src/gov/nasa/worldwind/util/layertree/LayerTree.java @@ -23,21 +23,26 @@ * @see LayerTreeModel * @see LayerTreeNode */ -public class LayerTree extends BasicTree -{ - /** The default screen location: 20x140 pixels from the upper left screen corner. */ +public class LayerTree extends BasicTree { + + /** + * The default screen location: 20x140 pixels from the upper left screen corner. + */ protected static final Offset DEFAULT_OFFSET = new Offset(20d, 140d, AVKey.PIXELS, AVKey.INSET_PIXELS); - /** The default frame image. Appears to the left of the frame title. */ + /** + * The default frame image. Appears to the left of the frame title. + */ protected static final String DEFAULT_FRAME_IMAGE = "images/layer-manager-64x64.png"; - /** The default frame title: "Layers". */ + /** + * The default frame title: "Layers". + */ protected static final String DEFAULT_FRAME_TITLE = "Layers"; /** * Creates a new LayerTree with an empty LayerTreeModel and the default screen location. * The tree's upper left corner is placed 20x140 pixels from the upper left screen corner. */ - public LayerTree() - { + public LayerTree() { this.initialize(null, null); } @@ -49,10 +54,8 @@ public LayerTree() * * @throws IllegalArgumentException if model is null. */ - public LayerTree(LayerTreeModel model) - { - if (model == null) - { + public LayerTree(LayerTreeModel model) { + if (model == null) { String message = Logging.getMessage("nullValue.ModelIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -62,17 +65,14 @@ public LayerTree(LayerTreeModel model) } /** - * Creates a new LayerTree with an empty LayerTreeModel and the specified screen - * location. + * Creates a new LayerTree with an empty LayerTreeModel and the specified screen location. * * @param offset the screen location of the tree's upper left corner, relative to the screen's upper left corner. * * @throws IllegalArgumentException if offset is null. */ - public LayerTree(Offset offset) - { - if (offset == null) - { + public LayerTree(Offset offset) { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -84,23 +84,20 @@ public LayerTree(Offset offset) /** * Creates a new LayerTree with the specified model and the specified screen location. * - * @param model the tree model to use. + * @param model the tree model to use. * @param offset the screen location of the tree's upper left corner, relative to the screen's upper left corner. * * @throws IllegalArgumentException if model is null, or if offset is - * null. + * null. */ - public LayerTree(LayerTreeModel model, Offset offset) - { - if (model == null) - { + public LayerTree(LayerTreeModel model, Offset offset) { + if (model == null) { String message = Logging.getMessage("nullValue.ModelIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (offset == null) - { + if (offset == null) { String message = Logging.getMessage("nullValue.OffsetIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -114,13 +111,13 @@ public LayerTree(LayerTreeModel model, Offset offset) * model, its layout, and expands the path to the root node. If either parameter is null this uses a * suitable default. * - * @param model this tree's model to use, or null to create a new LayerTreeModel. + * @param model this tree's model to use, or null to create a new LayerTreeModel. * @param offset the screen location of this tree's upper left corner, or null to use the default. */ - protected void initialize(LayerTreeModel model, Offset offset) - { - if (model == null) + protected void initialize(LayerTreeModel model, Offset offset) { + if (model == null) { model = this.createTreeModel(); + } this.setModel(model); this.setLayout(this.createTreeLayout(offset)); @@ -132,8 +129,7 @@ protected void initialize(LayerTreeModel model, Offset offset) * * @return a new LayerTreeModel. */ - protected LayerTreeModel createTreeModel() - { + protected LayerTreeModel createTreeModel() { return new LayerTreeModel(); } @@ -145,10 +141,10 @@ protected LayerTreeModel createTreeModel() * * @return new TreeLayout. */ - protected TreeLayout createTreeLayout(Offset offset) - { - if (offset == null) + protected TreeLayout createTreeLayout(Offset offset) { + if (offset == null) { offset = DEFAULT_OFFSET; + } BasicTreeLayout layout = new BasicTreeLayout(this, offset); layout.getFrame().setFrameTitle(DEFAULT_FRAME_TITLE); @@ -173,9 +169,10 @@ protected TreeLayout createTreeLayout(Offset offset) return layout; } - /** {@inheritDoc} */ - public LayerTreeModel getModel() - { + /** + * {@inheritDoc} + */ + public LayerTreeModel getModel() { return (LayerTreeModel) super.getModel(); } } diff --git a/src/gov/nasa/worldwind/util/layertree/LayerTreeModel.java b/src/gov/nasa/worldwind/util/layertree/LayerTreeModel.java index ab6993c548..894756aa03 100644 --- a/src/gov/nasa/worldwind/util/layertree/LayerTreeModel.java +++ b/src/gov/nasa/worldwind/util/layertree/LayerTreeModel.java @@ -29,17 +29,22 @@ * @author dcollins * @version $Id: LayerTreeModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class LayerTreeModel extends BasicTreeModel -{ - /** The default root name: "Layers". */ +public class LayerTreeModel extends BasicTreeModel { + + /** + * The default root name: "Layers". + */ protected static final String DEFAULT_ROOT_NAME = "Layers"; - /** Indicates whether or not the tree model must include hidden layers. */ + /** + * Indicates whether or not the tree model must include hidden layers. + */ protected boolean includeHiddenLayers; - /** Creates a new LayerTreeModel with the default root node. Otherwise the new model is empty. */ - public LayerTreeModel() - { + /** + * Creates a new LayerTreeModel with the default root node. Otherwise the new model is empty. + */ + public LayerTreeModel() { this.initialize(); } @@ -52,8 +57,7 @@ public LayerTreeModel() * * @throws IllegalArgumentException if the layerList is null. */ - public LayerTreeModel(LayerList layerList) - { + public LayerTreeModel(LayerList layerList) { this(layerList, false); } @@ -61,16 +65,14 @@ public LayerTreeModel(LayerList layerList) * Creates a new LayerTreeModel with the default root node and adds a new LayerTreeNode * for each Layer in the specified layerList. * - * @param layerList the list of Layer objects to the new model represents. + * @param layerList the list of Layer objects to the new model represents. * @param includeHiddenLayers if this parameter is true, layers marked as hidden will be included in - * the tree. Otherwise hidden layers will not be included in the tree. + * the tree. Otherwise hidden layers will not be included in the tree. * * @throws IllegalArgumentException if the layerList is null. */ - public LayerTreeModel(LayerList layerList, boolean includeHiddenLayers) - { - if (layerList == null) - { + public LayerTreeModel(LayerList layerList, boolean includeHiddenLayers) { + if (layerList == null) { String message = Logging.getMessage("nullValue.LayersListArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -85,10 +87,9 @@ public LayerTreeModel(LayerList layerList, boolean includeHiddenLayers) * Indicates whether or not this tree model includes layers marked as hidden. * * @return true if hidden layers are included in the tree mode. false if hidden layers are - * not included. + * not included. */ - public boolean isIncludeHiddenLayers() - { + public boolean isIncludeHiddenLayers() { return this.includeHiddenLayers; } @@ -98,16 +99,16 @@ public boolean isIncludeHiddenLayers() * the value for key AVKey.HIDDEN to true. * * @param includeHiddenLayers true if the tree model should include hidden layers. false - * if the model should ignore layers marked as hidden. + * if the model should ignore layers marked as hidden. */ - public void setIncludeHiddenLayers(boolean includeHiddenLayers) - { + public void setIncludeHiddenLayers(boolean includeHiddenLayers) { this.includeHiddenLayers = includeHiddenLayers; } - /** Initializes this tree model with the default root node. */ - protected void initialize() - { + /** + * Initializes this tree model with the default root node. + */ + protected void initialize() { this.setRoot(this.createRootNode()); } @@ -116,24 +117,21 @@ protected void initialize() * * @return a new TreeNode. */ - protected TreeNode createRootNode() - { + protected TreeNode createRootNode() { return new BasicTreeNode(DEFAULT_ROOT_NAME); } /** * Adds the specified layerNode to this tree model's root node. Nodes added under this tree model's - * root should always be of type {@link LayerTreeNode}. Note: this method adds the layer to the tree + * root should always be of type {@link LayerTreeNode}. Note: this method adds the layer to the tree * model regardless of whether or not the layer is marked as hidden. * * @param layerNode the layer node to add. * * @throws IllegalArgumentException if the layerNode is null. */ - public void addLayer(LayerTreeNode layerNode) - { - if (layerNode == null) - { + public void addLayer(LayerTreeNode layerNode) { + if (layerNode == null) { String message = Logging.getMessage("nullValue.TreeNodeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -153,18 +151,17 @@ public void addLayer(LayerTreeNode layerNode) * * @throws IllegalArgumentException if the layer is null. */ - public LayerTreeNode addLayer(Layer layer) - { - if (layer == null) - { + public LayerTreeNode addLayer(Layer layer) { + if (layer == null) { String message = Logging.getMessage("nullValue.LayerIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } LayerTreeNode layerNode = this.createLayerNode(layer); - if (layerNode == null) + if (layerNode == null) { return layerNode; + } this.addLayer(layerNode); return layerNode; @@ -178,14 +175,14 @@ public LayerTreeNode addLayer(Layer layer) * * @return a new LayerTreeNode. */ - protected LayerTreeNode createLayerNode(Layer layer) - { + protected LayerTreeNode createLayerNode(Layer layer) { return new LayerTreeNode(layer); } - /** Clears this tree model by removing all children of the root node. */ - public void removeAllLayers() - { + /** + * Clears this tree model by removing all children of the root node. + */ + public void removeAllLayers() { this.getRoot().removeAllChildren(); } @@ -200,10 +197,8 @@ public void removeAllLayers() * @throws IllegalArgumentException if the layerList is null. * @see #setIncludeHiddenLayers(boolean) */ - public void refresh(LayerList layerList) - { - if (layerList == null) - { + public void refresh(LayerList layerList) { + if (layerList == null) { String message = Logging.getMessage("nullValue.LayersListArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -212,10 +207,8 @@ public void refresh(LayerList layerList) // Replace all the layer nodes in the tree with nodes for the current layers. this.removeAllLayers(); - for (Layer layer : layerList) - { - if (this.mustIncludeLayer(layer)) - { + for (Layer layer : layerList) { + if (this.mustIncludeLayer(layer)) { this.addLayer(layer); } } @@ -227,10 +220,9 @@ public void refresh(LayerList layerList) * @param layer Layer to test. * * @return true if the layer must be included in the tree, false if the layer must not be - * included. + * included. */ - protected boolean mustIncludeLayer(Layer layer) - { + protected boolean mustIncludeLayer(Layer layer) { return this.isIncludeHiddenLayers() || layer.getValue(AVKey.HIDDEN) != Boolean.TRUE; } } diff --git a/src/gov/nasa/worldwind/util/layertree/LayerTreeNode.java b/src/gov/nasa/worldwind/util/layertree/LayerTreeNode.java index 68d0b1a08e..1857c05b5e 100644 --- a/src/gov/nasa/worldwind/util/layertree/LayerTreeNode.java +++ b/src/gov/nasa/worldwind/util/layertree/LayerTreeNode.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.layertree; import gov.nasa.worldwind.avlist.AVKey; @@ -22,9 +21,11 @@ * @author pabercrombie * @version $Id: LayerTreeNode.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class LayerTreeNode extends BasicTreeNode -{ - /** The layer node's default icon path. */ +public class LayerTreeNode extends BasicTreeNode { + + /** + * The layer node's default icon path. + */ protected static final String DEFAULT_IMAGE = "images/16x16-icon-earth.png"; /** @@ -41,12 +42,10 @@ public class LayerTreeNode extends BasicTreeNode * * @throws IllegalArgumentException if the layer is null. */ - public LayerTreeNode(Layer layer) - { + public LayerTreeNode(Layer layer) { super(layer != null ? layer.getName() : ""); - if (layer == null) - { + if (layer == null) { String message = Logging.getMessage("nullValue.LayerIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -56,12 +55,14 @@ public LayerTreeNode(Layer layer) this.initialize(); } - /** Initializes this node's image source. */ - protected void initialize() - { + /** + * Initializes this node's image source. + */ + protected void initialize() { Object imageSource = this.layer.getValue(AVKey.IMAGE); - if (imageSource == null) + if (imageSource == null) { imageSource = DEFAULT_IMAGE; + } this.setImageSource(imageSource); } @@ -71,8 +72,7 @@ protected void initialize() * @return true if the Layer is enabled, otherwise false. */ @Override - public boolean isSelected() - { + public boolean isSelected() { return this.layer.isEnabled(); } @@ -83,8 +83,7 @@ public boolean isSelected() * @param selected true to enable the Layer, otherwise false. */ @Override - public void setSelected(boolean selected) - { + public void setSelected(boolean selected) { super.setSelected(selected); this.layer.setEnabled(selected); } diff --git a/src/gov/nasa/worldwind/util/layertree/package-info.java b/src/gov/nasa/worldwind/util/layertree/package-info.java index 218dd9adcb..ee2f0f5af4 100644 --- a/src/gov/nasa/worldwind/util/layertree/package-info.java +++ b/src/gov/nasa/worldwind/util/layertree/package-info.java @@ -3,13 +3,12 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

          * Displays a list of layers using {@link gov.nasa.worldwind.util.tree.BasicTree}. The layer tree also supports * displaying a tree of KML features.

          * -

          + *

          * See {@link gov.nasa.worldwindx.examples.LayerTreeUsage} for an example of how to use the layer tree. See {@link * gov.nasa.worldwindx.examples.kml.KMLViewer} for an example of using the layer tree to display the contents of a KML * document.

          diff --git a/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java b/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java index e7ec39398e..0510e5b19d 100644 --- a/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java +++ b/src/gov/nasa/worldwind/util/measure/AreaMeasurer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.measure; import gov.nasa.worldwind.geom.*; @@ -15,25 +14,28 @@ /** * Utility class to compute approximations of projected and surface (terrain following) area on a globe. * - *

          To properly compute surface area the measurer must be provided with a list of positions that describe a - * closed path - one which last position is equal to the first.

          + *

          + * To properly compute surface area the measurer must be provided with a list of positions that describe a closed path - + * one which last position is equal to the first.

          * - *

          Segments which are longer then the current maxSegmentLength will be subdivided along lines following the current + *

          + * Segments which are longer then the current maxSegmentLength will be subdivided along lines following the current * pathType - {@link gov.nasa.worldwind.render.Polyline#LINEAR}, {@link gov.nasa.worldwind.render.Polyline#RHUMB_LINE} * or {@link gov.nasa.worldwind.render.Polyline#GREAT_CIRCLE}.

          * - *

          Projected or non terrain following area is computed in a sinusoidal projection which is equivalent or equal area. + *

          + * Projected or non terrain following area is computed in a sinusoidal projection which is equivalent or equal area. * Surface or terrain following area is approximated by sampling the path bounding sector with square cells along a - * grid. Cells which center is inside the path have their area estimated and summed according to the overall slope - * at the cell south-west corner.

          + * grid. Cells which center is inside the path have their area estimated and summed according to the overall slope at + * the cell south-west corner.

          * * @author Patrick Murris * @version $Id: AreaMeasurer.java 1171 2013-02-11 21:45:02Z dcollins $ * @see MeasureTool * @see LengthMeasurer */ -public class AreaMeasurer extends LengthMeasurer implements MeasurableArea -{ +public class AreaMeasurer extends LengthMeasurer implements MeasurableArea { + private static final double DEFAULT_AREA_SAMPLING_STEPS = 32; // sampling grid max rows or cols private ArrayList subdividedPositions; @@ -43,30 +45,25 @@ public class AreaMeasurer extends LengthMeasurer implements MeasurableArea protected double surfaceArea = -1; protected double projectedArea = -1; - public AreaMeasurer() - { + public AreaMeasurer() { } - public AreaMeasurer(ArrayList positions) - { + public AreaMeasurer(ArrayList positions) { super(positions); } - protected void clearCachedValues() - { + protected void clearCachedValues() { super.clearCachedValues(); this.subdividedPositions = null; this.projectedArea = -1; this.surfaceArea = -1; } - public void setPositions(ArrayList positions) - { + public void setPositions(ArrayList positions) { Sector oldSector = getBoundingSector(); super.setPositions(positions); // will call clearCachedData() - if (getBoundingSector() == null || !getBoundingSector().equals(oldSector)) - { + if (getBoundingSector() == null || !getBoundingSector().equals(oldSector)) { this.sectorCells = null; this.sectorElevations = null; } @@ -75,10 +72,9 @@ public void setPositions(ArrayList positions) /** * Get the sampling grid maximum number of rows or columns for terrain following surface area approximation. * - * @return the sampling grid maximum number of rows or columns. + * @return the sampling grid maximum number of rows or columns. */ - public double getAreaTerrainSamplingSteps() - { + public double getAreaTerrainSamplingSteps() { return this.areaTerrainSamplingSteps; } @@ -88,17 +84,14 @@ public double getAreaTerrainSamplingSteps() * @param steps the sampling grid maximum number of rows or columns. * @throws IllegalArgumentException if steps is less then one. */ - public void setAreaTerrainSamplingSteps(double steps) - { - if (steps < 1) - { + public void setAreaTerrainSamplingSteps(double steps) { + if (steps < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", steps); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.areaTerrainSamplingSteps != steps) - { + if (this.areaTerrainSamplingSteps != steps) { this.areaTerrainSamplingSteps = steps; this.surfaceArea = -1; this.projectedArea = -1; @@ -111,95 +104,89 @@ public void setAreaTerrainSamplingSteps(double steps) /** * Get the surface area approximation for the current path or shape. * - *

          If the measurer is set to follow terrain, the computed area will account for terrain deformations. Otherwise - * the area is that of the path once projected at sea level - elevation zero.

          + *

          + * If the measurer is set to follow terrain, the computed area will account for terrain deformations. Otherwise the + * area is that of the path once projected at sea level - elevation zero.

          * * @param globe the globe to draw terrain information from. - * @return the current shape surface area or -1 if the position list does not describe a closed path or is too short. + * @return the current shape surface area or -1 if the position list does not describe a closed path or is too + * short. * @throws IllegalArgumentException if globe is null. */ - public double getArea(Globe globe) - { + public double getArea(Globe globe) { return this.isFollowTerrain() ? getSurfaceArea(globe) : getProjectedArea(globe); } - public double getSurfaceArea(Globe globe) - { - if (globe == null) - { + public double getSurfaceArea(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.surfaceArea < 0) + if (this.surfaceArea < 0) { this.surfaceArea = this.computeSurfaceAreaSampling(globe, this.areaTerrainSamplingSteps); + } return this.surfaceArea; } - public double getProjectedArea(Globe globe) - { - if (globe == null) - { + public double getProjectedArea(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.projectedArea < 0) + if (this.projectedArea < 0) { this.projectedArea = this.computeProjectedAreaGeometry(globe); + } return this.projectedArea; } - public double getPerimeter(Globe globe) - { + public double getPerimeter(Globe globe) { return getLength(globe); } - public double getWidth(Globe globe) - { - if (globe == null) - { + public double getWidth(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Sector sector = getBoundingSector(); - if (sector != null) + if (sector != null) { return globe.getRadiusAt(sector.getCentroid()) * sector.getDeltaLon().radians * Math.cos(sector.getCentroid().getLatitude().radians); + } return -1; } - public double getHeight(Globe globe) - { - if (globe == null) - { + public double getHeight(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Sector sector = getBoundingSector(); - if (sector != null) + if (sector != null) { return globe.getRadiusAt(sector.getCentroid()) * sector.getDeltaLat().radians; + } return -1; } // *** Computing area ****************************************************************** + protected class Cell { - protected class Cell - { Sector sector; double projectedArea, surfaceArea; - public Cell(Sector sector, double projected, double surface) - { + public Cell(Sector sector, double projected, double surface) { this.sector = sector; this.projectedArea = projected; this.surfaceArea = surface; @@ -207,27 +194,24 @@ public Cell(Sector sector, double projected, double surface) } // *** Projected area *** - // Tessellate the path in lat-lon space, then sum each triangle area. - protected double computeProjectedAreaGeometry(Globe globe) - { + protected double computeProjectedAreaGeometry(Globe globe) { Sector sector = getBoundingSector(); - if (sector != null && this.isClosedShape()) - { + if (sector != null && this.isClosedShape()) { // Subdivide long segments if needed - if (this.subdividedPositions == null) - this.subdividedPositions = subdividePositions(globe, getPositions(), getMaxSegmentLength() - , isFollowTerrain(), getPathType()); + if (this.subdividedPositions == null) { + this.subdividedPositions = subdividePositions(globe, getPositions(), getMaxSegmentLength(), + isFollowTerrain(), getPathType()); + } // First: tessellate polygon int verticesCount = this.subdividedPositions.size() - 1; // trim last pos which is same as first float[] verts = new float[verticesCount * 3]; // Prepare vertices int idx = 0; - for (int i = 0; i < verticesCount; i++) - { + for (int i = 0; i < verticesCount; i++) { // Vertices coordinates are x=lon y=lat in radians, z = elevation zero - verts[idx++] = (float)this.subdividedPositions.get(i).getLongitude().radians; - verts[idx++] = (float)this.subdividedPositions.get(i).getLatitude().radians; + verts[idx++] = (float) this.subdividedPositions.get(i).getLongitude().radians; + verts[idx++] = (float) this.subdividedPositions.get(i).getLatitude().radians; verts[idx++] = 0f; } // Tessellate @@ -237,11 +221,10 @@ protected double computeProjectedAreaGeometry(Globe globe) double area = 0; int[] indices = ita.getIndices(); int triangleCount = ita.getIndexCount() / 3; - for (int i = 0; i < triangleCount; i++) - { + for (int i = 0; i < triangleCount; i++) { idx = i * 3; - area += computeTriangleProjectedArea(globe, ita.getVertices(), indices[idx] * 3 - , indices[idx + 1] * 3, indices[idx + 2] * 3); + area += computeTriangleProjectedArea(globe, ita.getVertices(), indices[idx] * 3, + indices[idx + 1] * 3, indices[idx + 2] * 3); } return area; } @@ -250,8 +233,7 @@ protected double computeProjectedAreaGeometry(Globe globe) // Compute triangle area in a sinusoidal projection centered at the triangle center. // Note sinusoidal projection is equivalent or equal erea. - protected double computeTriangleProjectedArea(Globe globe, float[] verts, int a, int b, int c) - { + protected double computeTriangleProjectedArea(Globe globe, float[] verts, int a, int b, int c) { // http://www.mathopenref.com/coordtrianglearea.html double area = Math.abs(verts[a] * (verts[b + 1] - verts[c + 1]) + verts[b] * (verts[c + 1] - verts[a + 1]) @@ -267,35 +249,34 @@ protected double computeTriangleProjectedArea(Globe globe, float[] verts, int a, } // *** Surface area - terrain following *** - // Sample the path bounding sector with square cells which area are approximated according to the surface normal at // the cell south-west corner. - protected double computeSurfaceAreaSampling(Globe globe, double steps) - { + protected double computeSurfaceAreaSampling(Globe globe, double steps) { Sector sector = getBoundingSector(); - if (sector != null && this.isClosedShape()) - { + if (sector != null && this.isClosedShape()) { // Subdivide long segments if needed - if (this.subdividedPositions == null) + if (this.subdividedPositions == null) { this.subdividedPositions = subdividePositions(globe, getPositions(), getMaxSegmentLength(), true, getPathType()); + } // Sample the bounding sector with cells about the same length in side - squares double stepRadians = Math.max(sector.getDeltaLatRadians() / steps, sector.getDeltaLonRadians() / steps); - int latSteps = (int)Math.round(sector.getDeltaLatRadians() / stepRadians); - int lonSteps = (int)Math.round(sector.getDeltaLonRadians() / stepRadians + int latSteps = (int) Math.round(sector.getDeltaLatRadians() / stepRadians); + int lonSteps = (int) Math.round(sector.getDeltaLonRadians() / stepRadians * Math.cos(sector.getCentroid().getLatitude().radians)); double latStepRadians = sector.getDeltaLatRadians() / latSteps; double lonStepRadians = sector.getDeltaLonRadians() / lonSteps; - if (this.sectorCells == null) + if (this.sectorCells == null) { this.sectorCells = new Cell[latSteps][lonSteps]; - if (this.sectorElevations == null) + } + if (this.sectorElevations == null) { this.sectorElevations = new Double[latSteps + 1][lonSteps + 1]; + } double area = 0; - for (int i = 0; i < latSteps; i++) - { + for (int i = 0; i < latSteps; i++) { double lat = sector.getMinLatitude().radians + latStepRadians * i; // Compute this latitude row cells area double radius = globe.getRadiusAt(Angle.fromRadians(lat + latStepRadians / 2), @@ -304,16 +285,13 @@ protected double computeSurfaceAreaSampling(Globe globe, double steps) double cellHeight = latStepRadians * radius; double cellArea = cellWidth * cellHeight; - for (int j = 0; j < lonSteps; j++) - { + for (int j = 0; j < lonSteps; j++) { double lon = sector.getMinLongitude().radians + lonStepRadians * j; Sector cellSector = Sector.fromRadians(lat, lat + latStepRadians, lon, lon + lonStepRadians); // Select cells which center is inside the shape - if (WWMath.isLocationInside(cellSector.getCentroid(), this.subdividedPositions)) - { + if (WWMath.isLocationInside(cellSector.getCentroid(), this.subdividedPositions)) { Cell cell = this.sectorCells[i][j]; - if (cell == null || cell.surfaceArea == -1) - { + if (cell == null || cell.surfaceArea == -1) { // Compute suface area using terrain normal in SW corner // Corners elevation double eleSW = sectorElevations[i][j] != null ? sectorElevations[i][j] @@ -348,11 +326,9 @@ protected double computeSurfaceAreaSampling(Globe globe, double steps) } // Below code is an attempt at computing the surface area using geometry. - // private static final double DEFAULT_AREA_CONVERGENCE_PERCENT = 2; // stop sudividing when increase in area - // is less then this percent + // is less then this percent // private double areaTerrainConvergencePercent = DEFAULT_AREA_CONVERGENCE_PERCENT; - // private int triangleCount = 0; // // Tessellate the path in lat-lon space, then sum each triangle surface area. // protected double computeSurfaceAreaGeometry(Globe globe) @@ -437,7 +413,6 @@ protected double computeSurfaceAreaSampling(Globe globe, double steps) // // return subArea; // } - // private double computeIndexedTriangleSurfaceAreaIteration(Globe globe, GeometryBuilder.IndexedTriangleArray ita, int idx) // { // // Create a one triangle indexed array @@ -464,7 +439,6 @@ protected double computeSurfaceAreaSampling(Globe globe, double steps) // System.out.println("Triangle " + idx / 3 + " tot triangles: " + triangleIta.getIndexCount() / 3); // return area; // } - // private double computeIndexedTriangleArraySurfaceArea(Globe globe, GeometryBuilder.IndexedTriangleArray ita) // { // int a, b, c; @@ -490,14 +464,12 @@ protected double computeSurfaceAreaSampling(Globe globe, double steps) // Vec4 AC = pc.subtract3(pa); // return 0.5 * AB.cross3(AC).getLength3(); // } - // protected Vec4 getSurfacePoint(Globe globe, float latRadians, float lonRadians) // { // Angle latitude = Angle.fromRadians(latRadians); // Angle longitude = Angle.fromRadians(lonRadians); // return globe.computePointFromPosition(latitude, longitude, globe.getElevation(latitude, longitude)); // } - // protected Vec4 getSurfacePointSinusoidal(Globe globe, float latRadians, float lonRadians) // { // Angle latitude = Angle.fromRadians(latRadians); @@ -506,6 +478,4 @@ protected double computeSurfaceAreaSampling(Globe globe, double steps) // return new Vec4(radius * lonRadians * latitude.cos(), radius * latRadians, // globe.getElevation(latitude, longitude)); // } - - } diff --git a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java index 4a1025af27..bfccb2e500 100644 --- a/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java +++ b/src/gov/nasa/worldwind/util/measure/LengthMeasurer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.measure; import gov.nasa.worldwind.geom.*; @@ -14,22 +13,26 @@ import java.util.ArrayList; /** - * Utility class to measure length along a path on a globe.

          The measurer must be provided a list of at least two - * positions to be able to compute a distance.

          Segments which are longer then the current maxSegmentLength - * will be subdivided along lines following the current pathType - Polyline.LINEAR, Polyline.RHUMB_LINE or - * Polyline.GREAT_CIRCLE.

          If the measurer is set to follow terrain, the computed length will account for - * terrain deformations as if someone was walking along that path. Otherwise the length is the sum of the cartesian - * distance between the positions.

          - *

          When following terrain the measurer will sample terrain elevations at regular intervals along the path. The - * minimum number of samples used for the whole length can be set with setLengthTerrainSamplingSteps(). However, the - * minimum sampling interval is 30 meters. + * Utility class to measure length along a path on a globe. + *

          + * The measurer must be provided a list of at least two positions to be able to compute a distance.

          + *

          + * Segments which are longer then the current maxSegmentLength will be subdivided along lines following the current + * pathType - Polyline.LINEAR, Polyline.RHUMB_LINE or Polyline.GREAT_CIRCLE.

          + *

          + * If the measurer is set to follow terrain, the computed length will account for terrain deformations as if someone was + * walking along that path. Otherwise the length is the sum of the cartesian distance between the positions.

          + *

          + * When following terrain the measurer will sample terrain elevations at regular intervals along the path. The minimum + * number of samples used for the whole length can be set with setLengthTerrainSamplingSteps(). However, the minimum + * sampling interval is 30 meters. * * @author Patrick Murris * @version $Id: LengthMeasurer.java 2261 2014-08-23 00:31:54Z tgaskins $ * @see MeasureTool */ -public class LengthMeasurer implements MeasurableLength -{ +public class LengthMeasurer implements MeasurableLength { + private static final double DEFAULT_TERRAIN_SAMPLING_STEPS = 128; // number of samples when following terrain private static final double DEFAULT_MAX_SEGMENT_LENGTH = 100e3; // size above which segments are subdivided private static final double DEFAULT_MIN_SEGMENT_LENGTH = 30; // minimum length of a terrain following subdivision @@ -43,64 +46,55 @@ public class LengthMeasurer implements MeasurableLength private double lengthTerrainSamplingSteps = DEFAULT_TERRAIN_SAMPLING_STEPS; protected double length = -1; - public LengthMeasurer() - { + public LengthMeasurer() { } - public LengthMeasurer(ArrayList positions) - { + public LengthMeasurer(ArrayList positions) { this.setPositions(positions); } - protected void clearCachedValues() - { + protected void clearCachedValues() { this.subdividedPositions = null; this.length = -1; } - public ArrayList getPositions() - { + public ArrayList getPositions() { return this.positions; } - public void setPositions(ArrayList positions, double elevation) - { - if (positions == null) - { + public void setPositions(ArrayList positions, double elevation) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } ArrayList newPositions = new ArrayList(); - for (LatLon pos : positions) - { + for (LatLon pos : positions) { newPositions.add(new Position(pos, elevation)); } setPositions(newPositions); } - public void setPositions(ArrayList positions) - { - if (positions == null) - { + public void setPositions(ArrayList positions) { + if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.positions = positions; - if (this.positions.size() > 2) + if (this.positions.size() > 2) { this.sector = Sector.boundingSector(this.positions); - else + } else { this.sector = null; + } clearCachedValues(); } - public boolean isFollowTerrain() - { + public boolean isFollowTerrain() { return this.followTerrain; } @@ -109,17 +103,14 @@ public boolean isFollowTerrain() * * @param followTerrain set to true if measurements should account for terrain deformations. */ - public void setFollowTerrain(boolean followTerrain) - { - if (this.followTerrain != followTerrain) - { + public void setFollowTerrain(boolean followTerrain) { + if (this.followTerrain != followTerrain) { this.followTerrain = followTerrain; clearCachedValues(); } } - public int getPathType() - { + public int getPathType() { return this.pathType; } @@ -130,10 +121,8 @@ public int getPathType() * * @param pathType the type of path to measure. */ - public void setPathType(int pathType) - { - if (this.pathType != pathType) - { + public void setPathType(int pathType) { + if (this.pathType != pathType) { this.pathType = pathType; clearCachedValues(); } @@ -144,8 +133,7 @@ public void setPathType(int pathType) * * @return the maximum length a segment can have before being subdivided. */ - public double getMaxSegmentLength() - { + public double getMaxSegmentLength() { return this.maxSegmentLength; } @@ -154,41 +142,36 @@ public double getMaxSegmentLength() * * @param length the maximum length a segment can have before being subdivided. */ - public void setMaxSegmentLength(double length) - { - if (length <= 0) - { + public void setMaxSegmentLength(double length) { + if (length <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", length); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.maxSegmentLength != length) - { + if (this.maxSegmentLength != length) { this.maxSegmentLength = length; clearCachedValues(); } } - public Sector getBoundingSector() - { - if (this.sector == null && this.positions != null && this.positions.size() > 2) + public Sector getBoundingSector() { + if (this.sector == null && this.positions != null && this.positions.size() > 2) { this.sector = Sector.boundingSector(this.positions); + } return this.sector; } /** - * Returns true if the current position list describe a closed path - one which last position is equal to the - * first. + * Returns true if the current position list describe a closed path - one which last position is equal to the first. * * @return true if the current position list describe a closed path. */ - public boolean isClosedShape() - { + public boolean isClosedShape() { return this.positions != null - && this.positions.size() > 1 - && this.positions.get(0).equals(this.positions.get(this.positions.size() - 1)); + && this.positions.size() > 1 + && this.positions.get(0).equals(this.positions.get(this.positions.size() - 1)); } /** @@ -196,8 +179,7 @@ public boolean isClosedShape() * * @return the number of terrain elevation samples used. */ - public double getLengthTerrainSamplingSteps() - { + public double getLengthTerrainSamplingSteps() { return this.lengthTerrainSamplingSteps; } @@ -207,17 +189,14 @@ public double getLengthTerrainSamplingSteps() * * @param steps the number of terrain elevation samples to be used. */ - public void setLengthTerrainSamplingSteps(double steps) - { - if (steps < 1) - { + public void setLengthTerrainSamplingSteps(double steps) { + if (steps < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", steps); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.lengthTerrainSamplingSteps != steps) - { + if (this.lengthTerrainSamplingSteps != steps) { this.lengthTerrainSamplingSteps = steps; this.subdividedPositions = null; this.length = -1; @@ -225,18 +204,18 @@ public void setLengthTerrainSamplingSteps(double steps) } /** - * Get the path length in meter.

          If the measurer is set to follow terrain, the computed length will account - * for terrain deformations as if someone was walking along that path. Otherwise the length is the sum of the - * cartesian distance between each positions.

          + * Get the path length in meter. + *

          + * If the measurer is set to follow terrain, the computed length will account for terrain deformations as if someone + * was walking along that path. Otherwise the length is the sum of the cartesian distance between each + * positions.

          * * @param globe the globe to draw terrain information from. * * @return the current path length or -1 if the position list is too short. */ - public double getLength(Globe globe) - { - if (globe == null) - { + public double getLength(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -248,20 +227,17 @@ public double getLength(Globe globe) } // *** Computing length ***************************************************************************** - - protected double computeLength(Globe globe, boolean followTerrain) - { - if (this.positions == null || this.positions.size() < 2) + protected double computeLength(Globe globe, boolean followTerrain) { + if (this.positions == null || this.positions.size() < 2) { return -1; + } - if (this.subdividedPositions == null) - { + if (this.subdividedPositions == null) { // Subdivide path so as to have at least segments smaller then maxSegmentLength. If follow terrain, // subdivide so as to have at least lengthTerrainSamplingSteps segments, but no segments shorter then // DEFAULT_MIN_SEGMENT_LENGTH either. double maxLength = this.maxSegmentLength; - if (followTerrain) - { + if (followTerrain) { // Recurse to compute overall path length not following terrain double pathLength = computeLength(globe, false); // Determine segment length to have enough sampling points @@ -269,14 +245,13 @@ protected double computeLength(Globe globe, boolean followTerrain) maxLength = Math.min(Math.max(maxLength, DEFAULT_MIN_SEGMENT_LENGTH), getMaxSegmentLength()); } this.subdividedPositions = subdividePositions(globe, this.positions, maxLength, - followTerrain, this.pathType); + followTerrain, this.pathType); } // Sum each segment length double length = 0; Vec4 p1 = globe.computeEllipsoidalPointFromPosition(this.subdividedPositions.get(0)); - for (int i = 1; i < subdividedPositions.size(); i++) - { + for (int i = 1; i < subdividedPositions.size(); i++) { Vec4 p2 = globe.computeEllipsoidalPointFromPosition(this.subdividedPositions.get(i)); length += p1.distanceTo3(p2); p1 = p2; @@ -299,114 +274,108 @@ protected double computeLength(Globe globe, boolean followTerrain) // pos2.getElevation() - pos1.getElevation() // ).getLength3(); // Meters // } - /** - * Subdivide a list of positions so that no segment is longer then the provided maxLength.

          If needed, new - * intermediate positions will be created along lines that follow the given pathType - one of Polyline.LINEAR, - * Polyline.RHUMB_LINE or Polyline.GREAT_CIRCLE. All position elevations will be either at the terrain surface if - * followTerrain is true, or interpolated according to the original elevations.

          + * Subdivide a list of positions so that no segment is longer then the provided maxLength. + *

          + * If needed, new intermediate positions will be created along lines that follow the given pathType - one of + * Polyline.LINEAR, Polyline.RHUMB_LINE or Polyline.GREAT_CIRCLE. All position elevations will be either at the + * terrain surface if followTerrain is true, or interpolated according to the original elevations.

          * - * @param globe the globe to draw elevations and points from. - * @param positions the original position list - * @param maxLength the maximum length for one segment. + * @param globe the globe to draw elevations and points from. + * @param positions the original position list + * @param maxLength the maximum length for one segment. * @param followTerrain true if the positions should be on the terrain surface. - * @param pathType the type of path to use in between two positions. + * @param pathType the type of path to use in between two positions. * * @return a list of positions with no segment longer then maxLength and elevations following terrain or not. */ protected static ArrayList subdividePositions(Globe globe, - ArrayList positions, - double maxLength, boolean followTerrain, int pathType) - { + ArrayList positions, + double maxLength, boolean followTerrain, int pathType) { return subdividePositions(globe, positions, maxLength, followTerrain, pathType, 0, positions.size()); } /** * Subdivide a list of positions so that no segment is longer then the provided maxLength. Only the positions - * between start and start + count - 1 will be processed.

          If needed, new intermediate positions will be - * created along lines that follow the given pathType - one of Polyline.LINEAR, Polyline.RHUMB_LINE or - * Polyline.GREAT_CIRCLE. All position elevations will be either at the terrain surface if followTerrain is true, or - * interpolated according to the original elevations.

          + * between start and start + count - 1 will be processed. + *

          + * If needed, new intermediate positions will be created along lines that follow the given pathType - one of + * Polyline.LINEAR, Polyline.RHUMB_LINE or Polyline.GREAT_CIRCLE. All position elevations will be either at the + * terrain surface if followTerrain is true, or interpolated according to the original elevations.

          * - * @param globe the globe to draw elevations and points from. - * @param positions the original position list - * @param maxLength the maximum length for one segment. + * @param globe the globe to draw elevations and points from. + * @param positions the original position list + * @param maxLength the maximum length for one segment. * @param followTerrain true if the positions should be on the terrain surface. - * @param pathType the type of path to use in between two positions. - * @param start the first position indice in the original list. - * @param count how many positions from the original list have to be processed and returned. + * @param pathType the type of path to use in between two positions. + * @param start the first position indice in the original list. + * @param count how many positions from the original list have to be processed and returned. * * @return a list of positions with no segment longer then maxLength and elevations following terrain or not. */ protected static ArrayList subdividePositions(Globe globe, - ArrayList positions, - double maxLength, boolean followTerrain, int pathType, - int start, int count) - { - if (positions == null || positions.size() < start + count) + ArrayList positions, + double maxLength, boolean followTerrain, int pathType, + int start, int count) { + if (positions == null || positions.size() < start + count) { return positions; + } ArrayList newPositions = new ArrayList(); // Add first position Position pos1 = positions.get(start); - if (followTerrain) + if (followTerrain) { newPositions.add(new Position(pos1, globe.getElevation(pos1.getLatitude(), pos1.getLongitude()))); - else + } else { newPositions.add(pos1); - for (int i = 1; i < count; i++) - { + } + for (int i = 1; i < count; i++) { Position pos2 = positions.get(start + i); double arcLengthRadians = LatLon.greatCircleDistance(pos1, pos2).radians; double arcLength = arcLengthRadians * globe.getRadiusAt(LatLon.interpolate(.5, pos1, pos2)); - if (arcLength > maxLength) - { + if (arcLength > maxLength) { // if necessary subdivide segment at regular intervals smaller then maxLength Angle segmentAzimuth = null; Angle segmentDistance = null; int steps = (int) Math.ceil(arcLength / maxLength); // number of intervals - at least two - for (int j = 1; j < steps; j++) - { + for (int j = 1; j < steps; j++) { float s = (float) j / steps; LatLon destLatLon; - if (pathType == Polyline.LINEAR) - { + if (pathType == Polyline.LINEAR) { destLatLon = LatLon.interpolate(s, pos1, pos2); - } - else if (pathType == Polyline.RHUMB_LINE) - { - if (segmentAzimuth == null) - { + } else if (pathType == Polyline.RHUMB_LINE) { + if (segmentAzimuth == null) { segmentAzimuth = LatLon.rhumbAzimuth(pos1, pos2); segmentDistance = LatLon.rhumbDistance(pos1, pos2); } destLatLon = LatLon.rhumbEndPosition(pos1, segmentAzimuth.radians, - s * segmentDistance.radians); - } - else // GREAT_CIRCLE + s * segmentDistance.radians); + } else // GREAT_CIRCLE { - if (segmentAzimuth == null) - { + if (segmentAzimuth == null) { segmentAzimuth = LatLon.greatCircleAzimuth(pos1, pos2); segmentDistance = LatLon.greatCircleDistance(pos1, pos2); } destLatLon = LatLon.greatCircleEndPosition(pos1, segmentAzimuth.radians, - s * segmentDistance.radians); + s * segmentDistance.radians); } // Set elevation double elevation; - if (followTerrain) + if (followTerrain) { elevation = globe.getElevation(destLatLon.getLatitude(), destLatLon.getLongitude()); - else + } else { elevation = pos1.getElevation() * (1 - s) + pos2.getElevation() * s; + } // Add new position newPositions.add(new Position(destLatLon, elevation)); } } // Finally add the segment end position - if (followTerrain) + if (followTerrain) { newPositions.add(new Position(pos2, globe.getElevation(pos2.getLatitude(), pos2.getLongitude()))); - else + } else { newPositions.add(pos2); + } // Prepare for next segment pos1 = pos2; } diff --git a/src/gov/nasa/worldwind/util/measure/MeasureTool.java b/src/gov/nasa/worldwind/util/measure/MeasureTool.java index aa45ab9e9a..201d33c430 100644 --- a/src/gov/nasa/worldwind/util/measure/MeasureTool.java +++ b/src/gov/nasa/worldwind/util/measure/MeasureTool.java @@ -22,53 +22,82 @@ * A utility class to interactively draw shapes and measure distance and area across the terrain. When armed, the class * monitors mouse events to allow the definition of a measure shape that can be one of {@link #SHAPE_LINE}, {@link * #SHAPE_PATH}, {@link #SHAPE_POLYGON}, {@link #SHAPE_CIRCLE}, {@link #SHAPE_ELLIPSE}, {@link #SHAPE_SQUARE} or {@link - * #SHAPE_QUAD}.

          In order to allow user interaction with the measuring shape, a controller must be set by - * calling {@link #setController(MeasureToolController)} with a new instance of a MeasureToolController.

          - *

          The interaction sequence for drawing a shape and measuring is as follows:

          • Set the measure - * shape.
          • Arm the MeasureTool object by calling its {@link #setArmed(boolean)} method with an - * argument of true.
          • Click on the terrain to add points.
          • Disarm the MeasureTool object by - * calling its {@link #setArmed(boolean)} method with an argument of false.
          • Read the measured length or area - * by calling the MeasureTool {@link #getLength()} or {@link #getArea()} method. Note that the length and - * area can be queried at any time during or after the process.

          While entering points or after the - * measure tool has been disarmed, dragging the control points allow to change the initial points positions and alter - * the measure shape.

          While the MeasureTool is armed, pressing and immediately releasing mouse - * button one while also pressing the control key (Ctl) removes the last point entered. Once the - * MeasureTool is disarmed, a measure shape of type SHAPE_POLYGON can be moved by dragging a control point - * while pressing the alt/option key.

          Arming and disarming the MeasureTool does not change the - * contents or attributes of the measure tool's layer. Note that the measure tool will NOT disarm itself after the - * second point of a line or a regular shape has been entered - the MeasureToolController has that responsibility.

          - *

          Setting the measure shape from the application

          The application can set the measure shape - * to an arbitrary list of positions using {@link #setPositions(java.util.ArrayList)}. If the provided list contains two - * positions, the measure shape will be set to {@link #SHAPE_LINE}. If more then two positions are provided, the measure - * shape will be set to {@link #SHAPE_PATH} if the last position differs from the first (open path), or {@link - * #SHAPE_POLYGON} if the path is closed.

          The application can also set the measure shape to a predefined - * regular shape by calling {@link #setMeasureShapeType(String, Position, double, double, Angle)}, providing a shape - * type (one of {@link #SHAPE_CIRCLE}, {@link #SHAPE_ELLIPSE}, {@link #SHAPE_SQUARE} or {@link #SHAPE_QUAD}), a center - * position, a width, a height (in meters) and a heading angle.

          Finally, the application can use an existing - * Polyline or SurfaceShape by using {@link #setMeasureShape(Polyline)} or {@link + * #SHAPE_QUAD}. + *

          + * In order to allow user interaction with the measuring shape, a controller must be set by calling + * {@link #setController(MeasureToolController)} with a new instance of a MeasureToolController.

          + *

          + * The interaction sequence for drawing a shape and measuring is as follows:

          • Set the measure shape.
          • + *
          • Arm the MeasureTool object by calling its {@link #setArmed(boolean)} method with an argument of + * true.
          • Click on the terrain to add points.
          • Disarm the MeasureTool object by calling its + * {@link #setArmed(boolean)} method with an argument of false.
          • Read the measured length or area by calling + * the MeasureTool {@link #getLength()} or {@link #getArea()} method. Note that the length and area can be + * queried at any time during or after the process.

          + * While entering points or after the measure tool has been disarmed, dragging the control points allow to change the + * initial points positions and alter the measure shape.

          + *

          + * While the MeasureTool is armed, pressing and immediately releasing mouse button one while also pressing + * the control key (Ctl) removes the last point entered. Once the MeasureTool is disarmed, a measure shape + * of type SHAPE_POLYGON can be moved by dragging a control point while pressing the alt/option key.

          + *

          + * Arming and disarming the MeasureTool does not change the contents or attributes of the measure tool's + * layer. Note that the measure tool will NOT disarm itself after the second point of a line or a regular shape has been + * entered - the MeasureToolController has that responsibility.

          + *

          + * Setting the measure shape from the application

          + *

          + * The application can set the measure shape to an arbitrary list of positions using + * {@link #setPositions(java.util.ArrayList)}. If the provided list contains two positions, the measure shape will be + * set to {@link #SHAPE_LINE}. If more then two positions are provided, the measure shape will be set to + * {@link #SHAPE_PATH} if the last position differs from the first (open path), or {@link + * #SHAPE_POLYGON} if the path is closed.

          + *

          + * The application can also set the measure shape to a predefined regular shape by calling + * {@link #setMeasureShapeType(String, Position, double, double, Angle)}, providing a shape type (one of + * {@link #SHAPE_CIRCLE}, {@link #SHAPE_ELLIPSE}, {@link #SHAPE_SQUARE} or {@link #SHAPE_QUAD}), a center position, a + * width, a height (in meters) and a heading angle.

          + *

          + * Finally, the application can use an existing Polyline or SurfaceShape by using + * {@link #setMeasureShape(Polyline)} or {@link * #setMeasureShape(SurfaceShape)}. The surface shape can be one of SurfacePolyline, * SurfacePolygon, SurfaceQuad, SurfaceSquare, SurfaceEllipse or - * SurfaceCircle.

          Measuring

          The application can read the measured length or area - * by calling the MeasureTool {@link #getLength()} or {@link #getArea()} method. These methods will return - * -1 when no value is available.

          Regular shapes are defined by a center position, a width a height and a - * heading angle. Those attributes can be accessed by calling the {@link #getCenterPosition()}, {@link #getWidth()}, - * {@link #getHeight()} and {@link #getOrientation()} methods.

          The measurements are displayed in units - * specified in the measure tool's {@link UnitsFormat} object. Access to the units format is via the method {@link - * #getUnitsFormat()}.

          Events

          The MeasureTool will send events on several - * occasions: when the position list has changed - {@link #EVENT_POSITION_ADD}, {@link #EVENT_POSITION_REMOVE} or {@link + * SurfaceCircle. + *

          + * Measuring

          + *

          + * The application can read the measured length or area by calling the MeasureTool {@link #getLength()} or + * {@link #getArea()} method. These methods will return -1 when no value is available.

          + *

          + * Regular shapes are defined by a center position, a width a height and a heading angle. Those attributes can be + * accessed by calling the {@link #getCenterPosition()}, {@link #getWidth()}, + * {@link #getHeight()} and {@link #getOrientation()} methods.

          + *

          + * The measurements are displayed in units specified in the measure tool's {@link UnitsFormat} object. Access to the + * units format is via the method {@link + * #getUnitsFormat()}. + *

          + * Events

          + *

          + * The MeasureTool will send events on several occasions: when the position list has changed - + * {@link #EVENT_POSITION_ADD}, {@link #EVENT_POSITION_REMOVE} or {@link * #EVENT_POSITION_REPLACE}, when metrics has changed {@link #EVENT_METRIC_CHANGED} or when the tool is armed or - * disarmed {@link #EVENT_ARMED}.

          Events will also be fired at the start and end of a rubber band operation - * during shape creation: {@link #EVENT_RUBBERBAND_START} and {@link #EVENT_RUBBERBAND_STOP}.

          See {@link - * gov.nasa.worldwindx.examples.MeasureToolPanel} for some events usage.

          Several instances of this class can - * be used simultaneously. However, each instance should be disposed of after usage by calling the {@link #dispose()} - * method.

          + * disarmed {@link #EVENT_ARMED}.

          + *

          + * Events will also be fired at the start and end of a rubber band operation during shape creation: + * {@link #EVENT_RUBBERBAND_START} and {@link #EVENT_RUBBERBAND_STOP}.

          + *

          + * See {@link + * gov.nasa.worldwindx.examples.MeasureToolPanel} for some events usage.

          + *

          + * Several instances of this class can be used simultaneously. However, each instance should be disposed of after usage + * by calling the {@link #dispose()} method.

          * * @author Patrick Murris * @version $Id: MeasureTool.java 3297 2015-07-03 16:21:05Z dcollins $ * @see MeasureToolController */ -public class MeasureTool extends AVListImpl implements Disposable -{ +public class MeasureTool extends AVListImpl implements Disposable { + public static final String SHAPE_LINE = "MeasureTool.ShapeLine"; public static final String SHAPE_PATH = "MeasureTool.ShapePath"; public static final String SHAPE_POLYGON = "MeasureTool.ShapePolygon"; @@ -154,14 +183,15 @@ public class MeasureTool extends AVListImpl implements Disposable protected Angle shapeOrientation = null; protected int shapeIntervals = 64; - protected static class CustomRenderableLayer extends RenderableLayer implements PreRenderable, Renderable - { - public void render(DrawContext dc) - { - if (dc.isPickingMode() && !this.isPickEnabled()) + protected static class CustomRenderableLayer extends RenderableLayer implements PreRenderable, Renderable { + + public void render(DrawContext dc) { + if (dc.isPickingMode() && !this.isPickEnabled()) { return; - if (!this.isEnabled()) + } + if (!this.isEnabled()) { return; + } super.render(dc); } @@ -172,8 +202,7 @@ public void render(DrawContext dc) * * @param wwd the WorldWindow to draw events from. */ - public MeasureTool(final WorldWindow wwd) - { + public MeasureTool(final WorldWindow wwd) { this(wwd, null); } @@ -181,14 +210,12 @@ public MeasureTool(final WorldWindow wwd) * Construct a new measure tool drawing events from the specified WorldWindow and using the given * RenderableLayer. * - * @param wwd the WorldWindow to draw events from. + * @param wwd the WorldWindow to draw events from. * @param applicationLayer the RenderableLayer to use. May be null. If specified, the caller is - * responsible for adding the layer to the model and enabling it. + * responsible for adding the layer to the model and enabling it. */ - public MeasureTool(final WorldWindow wwd, RenderableLayer applicationLayer) - { - if (wwd == null) - { + public MeasureTool(final WorldWindow wwd, RenderableLayer applicationLayer) { + if (wwd == null) { String msg = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -197,7 +224,6 @@ public MeasureTool(final WorldWindow wwd, RenderableLayer applicationLayer) this.applicationLayer = applicationLayer; // can be null // Set up layers - this.layer = createCustomRenderableLayer(); this.shapeLayer = createCustomRenderableLayer(); this.controlPointsLayer = createCustomRenderableLayer(); @@ -207,11 +233,11 @@ public MeasureTool(final WorldWindow wwd, RenderableLayer applicationLayer) this.layer.addRenderable(this.shapeLayer); // add shape layer to render layer this.layer.addRenderable(this.controlPointsLayer); // add control points layer to render layer this.controlPointsLayer.setEnabled(this.showControlPoints); - if (this.applicationLayer != null) + if (this.applicationLayer != null) { this.applicationLayer.addRenderable(this.layer); // add render layer to the application provided layer - else + } else { this.wwd.getModel().getLayers().add(this.layer); // add render layer to the globe model - + } // Init control points rendering attributes this.controlPointsAttributes = new AnnotationAttributes(); // Define an 8x8 square centered on the screen point @@ -261,8 +287,7 @@ public MeasureTool(final WorldWindow wwd, RenderableLayer applicationLayer) this.shapeLayer.addRenderable(this.annotation); } - protected void setInitialLabels() - { + protected void setInitialLabels() { this.setLabel(ACCUMULATED_LABEL, Logging.getMessage(ACCUMULATED_LABEL)); this.setLabel(ANGLE_LABEL, Logging.getMessage(ANGLE_LABEL)); this.setLabel(AREA_LABEL, Logging.getMessage(AREA_LABEL)); @@ -280,8 +305,7 @@ protected void setInitialLabels() this.setLabel(WIDTH_LABEL, Logging.getMessage(WIDTH_LABEL)); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.wwd; } @@ -290,8 +314,7 @@ public WorldWindow getWwd() * * @return the tool's units format instance. */ - public UnitsFormat getUnitsFormat() - { + public UnitsFormat getUnitsFormat() { return this.unitsFormat; } @@ -302,10 +325,8 @@ public UnitsFormat getUnitsFormat() * * @throws IllegalArgumentException if the units format instance is null. */ - public void setUnitsFormat(UnitsFormat unitsFormat) - { - if (unitsFormat == null) - { + public void setUnitsFormat(UnitsFormat unitsFormat) { + if (unitsFormat == null) { String msg = Logging.getMessage("nullValue.Format"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -314,9 +335,10 @@ public void setUnitsFormat(UnitsFormat unitsFormat) this.unitsFormat = unitsFormat; } - /** @return Instance of the custom renderable layer to use of our internal layers */ - protected CustomRenderableLayer createCustomRenderableLayer() - { + /** + * @return Instance of the custom renderable layer to use of our internal layers + */ + protected CustomRenderableLayer createCustomRenderableLayer() { return new CustomRenderableLayer(); } @@ -325,10 +347,8 @@ protected CustomRenderableLayer createCustomRenderableLayer() * * @param controller the controller object for this measure tool. */ - public void setController(MeasureToolController controller) - { - if (this.controller != null) - { + public void setController(MeasureToolController controller) { + if (this.controller != null) { this.wwd.getInputHandler().removeMouseListener(this.controller); this.wwd.getInputHandler().removeMouseMotionListener(this.controller); this.wwd.removePositionListener(this.controller); @@ -336,8 +356,7 @@ public void setController(MeasureToolController controller) this.wwd.removeRenderingListener(this.controller); this.controller = null; } - if (controller != null) - { + if (controller != null) { this.controller = controller; this.controller.setMeasureTool(this); this.wwd.getInputHandler().addMouseListener(this.controller); @@ -348,16 +367,14 @@ public void setController(MeasureToolController controller) } } - public void setLabel(String labelName, String label) - { - if (labelName != null && labelName.length() > 0) + public void setLabel(String labelName, String label) { + if (labelName != null && labelName.length() > 0) { this.setValue(labelName, label); + } } - public String getLabel(String labelName) - { - if (labelName == null) - { + public String getLabel(String labelName) { + if (labelName == null) { String msg = Logging.getMessage("nullValue.LabelName"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -373,8 +390,7 @@ public String getLabel(String labelName) * * @return the MeasureToolController for this measure tool. */ - public MeasureToolController getController() - { + public MeasureToolController getController() { return this.controller; } @@ -384,10 +400,10 @@ public MeasureToolController getController() * * @param state true to arm the controller, false to disarm it. */ - public void setArmed(boolean state) - { - if (this.controller != null) + public void setArmed(boolean state) { + if (this.controller != null) { this.controller.setArmed(state); + } } /** @@ -395,8 +411,7 @@ public void setArmed(boolean state) * * @return true if armed, false if not armed. */ - public boolean isArmed() - { + public boolean isArmed() { return this.controller != null && this.controller.isArmed(); } @@ -405,8 +420,7 @@ public boolean isArmed() * * @return the layer containing the measure shape and control points. */ - public RenderableLayer getLayer() - { + public RenderableLayer getLayer() { return this.layer; } @@ -415,8 +429,7 @@ public RenderableLayer getLayer() * * @return the layer containing the measure shape and control points. */ - public RenderableLayer getApplicationLayer() - { + public RenderableLayer getApplicationLayer() { return applicationLayer; } @@ -425,8 +438,7 @@ public RenderableLayer getApplicationLayer() * * @return the polyline currently used to display lines and path. */ - public Polyline getLine() - { + public Polyline getLine() { return this.line; } @@ -435,8 +447,7 @@ public Polyline getLine() * * @return the surface shape currently used to display polygons. */ - public SurfaceShape getSurfaceShape() - { + public SurfaceShape getSurfaceShape() { return this.surfaceShape; } @@ -445,52 +456,52 @@ public SurfaceShape getSurfaceShape() * * @return the list of positions that define the current measure shape. */ - public ArrayList getPositions() - { + public ArrayList getPositions() { return this.positions; } /** * Set the measure shape to an arbitrary list of positions. If the provided list contains two positions, the measure * shape will be set to {@link #SHAPE_LINE}. If more then two positions are provided, the measure shape will be set - * to {@link #SHAPE_PATH} if the last position differs from the first (open path), or {@link #SHAPE_POLYGON} - * if the path is closed. + * to {@link #SHAPE_PATH} if the last position differs from the first (open path), or {@link #SHAPE_POLYGON} if the + * path is closed. * * @param newPositions the shape position list. */ - public void setPositions(ArrayList newPositions) - { - if (newPositions == null) - { + public void setPositions(ArrayList newPositions) { + if (newPositions == null) { String msg = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (newPositions.size() < 2) + if (newPositions.size() < 2) { return; + } this.clear(); // Setup the proper measure shape boolean closedShape = newPositions.get(0).equals(newPositions.get(newPositions.size() - 1)); - if (newPositions.size() > 2 && closedShape) + if (newPositions.size() > 2 && closedShape) { setMeasureShapeType(SHAPE_POLYGON); - else + } else { setMeasureShapeType(getPathType(newPositions)); + } // Import positions and create control points - for (int i = 0; i < newPositions.size(); i++) - { + for (int i = 0; i < newPositions.size(); i++) { Position pos = newPositions.get(i); this.positions.add(pos); - if (i < newPositions.size() - 1 || !closedShape) + if (i < newPositions.size() - 1 || !closedShape) { addControlPoint(pos, CONTROL_TYPE_LOCATION_INDEX, this.positions.size() - 1); + } } // Update line heading if needed - if (this.measureShapeType.equals(SHAPE_LINE)) + if (this.measureShapeType.equals(SHAPE_LINE)) { this.shapeOrientation = LatLon.greatCircleAzimuth(this.positions.get(0), this.positions.get(1)); + } // Update screen shapes updateMeasureShape(); @@ -503,8 +514,7 @@ public void setPositions(ArrayList newPositions) * * @return the list of control points associated with the current measure shape. */ - public ArrayList getControlPoints() - { + public ArrayList getControlPoints() { return this.controlPoints; } @@ -513,8 +523,7 @@ public ArrayList getControlPoints() * * @return the attributes associated with the control points. */ - public AnnotationAttributes getControlPointsAttributes() - { + public AnnotationAttributes getControlPointsAttributes() { return this.controlPointsAttributes; } @@ -523,29 +532,25 @@ public AnnotationAttributes getControlPointsAttributes() * * @return the attributes associated with the tool tip annotation. */ - public AnnotationAttributes getAnnotationAttributes() - { + public AnnotationAttributes getAnnotationAttributes() { return this.annotationAttributes; } - public void setLineColor(Color color) - { - if (color == null) - { + public void setLineColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.lineColor = color; - if (this.line != null) - { + if (this.line != null) { this.line.setColor(color); } - if (this.surfaceShape != null) - { + if (this.surfaceShape != null) { ShapeAttributes attr = this.surfaceShape.getAttributes(); - if (attr == null) + if (attr == null) { attr = new BasicShapeAttributes(); + } attr.setOutlineMaterial(new Material(color)); attr.setOutlineOpacity(color.getAlpha() / 255d); this.surfaceShape.setAttributes(attr); @@ -553,25 +558,22 @@ public void setLineColor(Color color) this.wwd.redraw(); } - public Color getLineColor() - { + public Color getLineColor() { return this.lineColor; } - public void setFillColor(Color color) - { - if (color == null) - { + public void setFillColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.fillColor = color; - if (this.surfaceShape != null) - { + if (this.surfaceShape != null) { ShapeAttributes attr = this.surfaceShape.getAttributes(); - if (attr == null) + if (attr == null) { attr = new BasicShapeAttributes(); + } attr.setInteriorMaterial(new Material(color)); attr.setInteriorOpacity(color.getAlpha() / 255d); this.surfaceShape.setAttributes(attr); @@ -579,109 +581,92 @@ public void setFillColor(Color color) this.wwd.redraw(); } - public Color getFillColor() - { + public Color getFillColor() { return this.fillColor; } - public void setLineWidth(double width) - { + public void setLineWidth(double width) { this.lineWidth = width; - if (this.line != null) + if (this.line != null) { this.line.setLineWidth(width); - if (this.surfaceShape != null) - { + } + if (this.surfaceShape != null) { ShapeAttributes attr = this.surfaceShape.getAttributes(); - if (attr == null) + if (attr == null) { attr = new BasicShapeAttributes(); + } attr.setOutlineWidth(width); this.surfaceShape.setAttributes(attr); } this.wwd.redraw(); } - public double getLineWidth() - { + public double getLineWidth() { return this.lineWidth; } - public String getPathType() - { + public String getPathType() { return this.pathType; } - public void setPathType(String type) - { + public void setPathType(String type) { this.pathType = type; - if (this.line != null) + if (this.line != null) { this.line.setPathType(polylinePathTypeFromKey(type)); - if (this.surfaceShape != null) + } + if (this.surfaceShape != null) { this.surfaceShape.setPathType(type); - if (this.isRegularShape()) + } + if (this.isRegularShape()) { this.updateShapeControlPoints(); + } this.wwd.redraw(); } @SuppressWarnings({"StringEquality"}) - protected static int polylinePathTypeFromKey(String type) - { - if (type != null && type == AVKey.GREAT_CIRCLE) - { + protected static int polylinePathTypeFromKey(String type) { + if (type != null && type == AVKey.GREAT_CIRCLE) { return Polyline.GREAT_CIRCLE; - } - else if (type != null && (type == AVKey.RHUMB_LINE || type == AVKey.LOXODROME)) - { + } else if (type != null && (type == AVKey.RHUMB_LINE || type == AVKey.LOXODROME)) { return Polyline.RHUMB_LINE; - } - else - { + } else { return Polyline.LINEAR; } } - protected static String keyFromPolylinePathType(int type) - { - if (type == Polyline.GREAT_CIRCLE) - { + protected static String keyFromPolylinePathType(int type) { + if (type == Polyline.GREAT_CIRCLE) { return AVKey.GREAT_CIRCLE; - } - else if (type == Polyline.RHUMB_LINE) - { + } else if (type == Polyline.RHUMB_LINE) { return AVKey.RHUMB_LINE; - } - else - { + } else { return AVKey.LINEAR; } } - public boolean isShowControlPoints() - { + public boolean isShowControlPoints() { return this.showControlPoints; } - public void setShowControlPoints(boolean state) - { + public void setShowControlPoints(boolean state) { this.showControlPoints = state; this.controlPointsLayer.setEnabled(state); this.wwd.redraw(); } - public boolean isShowAnnotation() - { + public boolean isShowAnnotation() { return this.showAnnotation; } - public void setShowAnnotation(boolean state) - { + public void setShowAnnotation(boolean state) { this.showAnnotation = state; } - /** Removes all positions from the shape, clear attributes. */ - public void clear() - { - while (this.positions.size() > 0 || this.controlPoints.size() > 0) - { + /** + * Removes all positions from the shape, clear attributes. + */ + public void clear() { + while (this.positions.size() > 0 || this.controlPoints.size() > 0) { this.removeControlPoint(); } @@ -690,8 +675,7 @@ public void clear() this.shapeRectangle = null; } - public boolean isMeasureShape(Object o) - { + public boolean isMeasureShape(Object o) { return o == this.shapeLayer; } @@ -701,8 +685,7 @@ public boolean isMeasureShape(Object o) * * @return the measure shape type. */ - public String getMeasureShapeType() - { + public String getMeasureShapeType() { return this.measureShapeType; } @@ -713,17 +696,14 @@ public String getMeasureShapeType() * * @param shape the measure shape type. */ - public void setMeasureShapeType(String shape) - { - if (shape == null) - { + public void setMeasureShapeType(String shape) { + if (shape == null) { String msg = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (!this.measureShapeType.equals(shape)) - { + if (!this.measureShapeType.equals(shape)) { setArmed(false); clear(); this.measureShapeType = shape; @@ -734,12 +714,11 @@ public void setMeasureShapeType(String shape) * Set and initialize the measure shape to one of the regular shapes {@link #SHAPE_CIRCLE}, {@link #SHAPE_ELLIPSE}, * {@link #SHAPE_SQUARE} or {@link #SHAPE_QUAD}. * - * @param shapeType the shape type. + * @param shapeType the shape type. * @param centerPosition the shape center position. - * @param radius the shape radius of half width/height. + * @param radius the shape radius of half width/height. */ - public void setMeasureShapeType(String shapeType, Position centerPosition, double radius) - { + public void setMeasureShapeType(String shapeType, Position centerPosition, double radius) { setMeasureShapeType(shapeType, centerPosition, radius * 2, radius * 2, Angle.ZERO); } @@ -747,40 +726,34 @@ public void setMeasureShapeType(String shapeType, Position centerPosition, doubl * Set and initialize the measure shape to one of the regular shapes {@link #SHAPE_CIRCLE}, {@link #SHAPE_ELLIPSE}, * {@link #SHAPE_SQUARE} or {@link #SHAPE_QUAD}. * - * @param shapeType the shape type. + * @param shapeType the shape type. * @param centerPosition the shape center position. - * @param width the shape width. - * @param height the shape height. - * @param orientation the shape orientation or azimuth angle - clockwise from north. + * @param width the shape width. + * @param height the shape height. + * @param orientation the shape orientation or azimuth angle - clockwise from north. */ public void setMeasureShapeType(String shapeType, Position centerPosition, double width, double height, - Angle orientation) - { - if (shapeType == null) - { + Angle orientation) { + if (shapeType == null) { String msg = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (centerPosition == null) - { + if (centerPosition == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (orientation == null) - { + if (orientation == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (isRegularShape(shapeType)) - { + if (isRegularShape(shapeType)) { setArmed(false); clear(); - if ((shapeType.equals(SHAPE_CIRCLE) || shapeType.equals(SHAPE_SQUARE)) && width != height) - { + if ((shapeType.equals(SHAPE_CIRCLE) || shapeType.equals(SHAPE_SQUARE)) && width != height) { width = Math.max(width, height); height = Math.max(width, height); } @@ -803,10 +776,8 @@ public void setMeasureShapeType(String shapeType, Position centerPosition, doubl * * @param line a Polyline instance. */ - public void setMeasureShape(Polyline line) - { - if (line == null) - { + public void setMeasureShape(Polyline line) { + if (line == null) { String msg = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -815,13 +786,13 @@ public void setMeasureShape(Polyline line) this.clear(); // Clear and replace current shape - if (this.surfaceShape != null) - { + if (this.surfaceShape != null) { this.shapeLayer.removeRenderable(this.surfaceShape); this.surfaceShape = null; } - if (this.line != null) + if (this.line != null) { this.shapeLayer.removeRenderable(this.line); + } this.line = line; this.shapeLayer.addRenderable(line); // Grab some of the line attributes @@ -829,8 +800,7 @@ public void setMeasureShape(Polyline line) setPathType(keyFromPolylinePathType(line.getPathType())); // Update position list and create control points int i = 0; - for (Position pos : line.getPositions()) - { + for (Position pos : line.getPositions()) { this.positions.add(pos); addControlPoint(pos, CONTROL_TYPE_LOCATION_INDEX, i++); } @@ -840,8 +810,7 @@ public void setMeasureShape(Polyline line) this.wwd.redraw(); } - protected String getPathType(List positions) - { + protected String getPathType(List positions) { return positions.size() > 2 ? SHAPE_PATH : SHAPE_LINE; } @@ -851,10 +820,8 @@ protected String getPathType(List positions) * * @param surfaceShape a SurfaceShape instance. */ - public void setMeasureShape(SurfaceShape surfaceShape) - { - if (surfaceShape == null) - { + public void setMeasureShape(SurfaceShape surfaceShape) { + if (surfaceShape == null) { String msg = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -864,12 +831,10 @@ public void setMeasureShape(SurfaceShape surfaceShape) this.clear(); // Clear and replace current surface shape - if (this.surfaceShape != null) - { + if (this.surfaceShape != null) { this.shapeLayer.removeRenderable(this.surfaceShape); } - if (this.line != null) - { + if (this.line != null) { this.shapeLayer.removeRenderable(this.line); this.line = null; } @@ -877,8 +842,7 @@ public void setMeasureShape(SurfaceShape surfaceShape) this.shapeLayer.addRenderable(surfaceShape); this.setPathType(surfaceShape.getPathType()); - if (surfaceShape instanceof SurfaceQuad) - { + if (surfaceShape instanceof SurfaceQuad) { // Set measure shape type this.measureShapeType = surfaceShape instanceof SurfaceSquare ? SHAPE_SQUARE : SHAPE_QUAD; // Set regular shape properties @@ -890,31 +854,27 @@ public void setMeasureShape(SurfaceShape surfaceShape) updateShapeControlPoints(); // Extract positions from shape updatePositionsFromShape(); - } - else if (surfaceShape instanceof SurfaceEllipse) - { + } else if (surfaceShape instanceof SurfaceEllipse) { // Set measure shape type this.measureShapeType = surfaceShape instanceof SurfaceCircle ? SHAPE_CIRCLE : SHAPE_ELLIPSE; // Set regular shape properties SurfaceEllipse shape = ((SurfaceEllipse) surfaceShape); this.shapeCenterPosition = new Position(shape.getCenter(), 0); this.shapeRectangle = new Rectangle2D.Double(0, 0, shape.getMajorRadius() * 2, - shape.getMinorRadius() * 2); + shape.getMinorRadius() * 2); this.shapeOrientation = shape.getHeading(); // Create control points for regular shapes updateShapeControlPoints(); // Extract positions from shape updatePositionsFromShape(); - } - else // SurfacePolygon, SurfacePolyline, SurfaceSector, or some custom shape + } else // SurfacePolygon, SurfacePolyline, SurfaceSector, or some custom shape { // Set measure shape type this.measureShapeType = SHAPE_POLYGON; // Extract positions from shape updatePositionsFromShape(); // Create control points for each position except the last that is the same as the first - for (int i = 0; i < this.positions.size() - 1; i++) - { + for (int i = 0; i < this.positions.size() - 1; i++) { addControlPoint(this.positions.get(i), CONTROL_TYPE_LOCATION_INDEX, i); } } @@ -923,159 +883,137 @@ else if (surfaceShape instanceof SurfaceEllipse) this.wwd.redraw(); } - public boolean isRegularShape() - { + public boolean isRegularShape() { return isRegularShape(this.measureShapeType); } - protected boolean isRegularShape(String shape) - { + protected boolean isRegularShape(String shape) { return (shape.equals(SHAPE_CIRCLE) - || shape.equals(SHAPE_ELLIPSE) - || shape.equals(SHAPE_QUAD) - || shape.equals(SHAPE_SQUARE)); + || shape.equals(SHAPE_ELLIPSE) + || shape.equals(SHAPE_QUAD) + || shape.equals(SHAPE_SQUARE)); } - public boolean isFollowTerrain() - { + public boolean isFollowTerrain() { return this.followTerrain; } - public void setFollowTerrain(boolean followTerrain) - { + public void setFollowTerrain(boolean followTerrain) { this.followTerrain = followTerrain; - if (this.line != null) - { + if (this.line != null) { this.line.setFollowTerrain(followTerrain); } } - public boolean isCenterControl(ControlPoint controlPoint) - { + public boolean isCenterControl(ControlPoint controlPoint) { String control = controlPoint.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); return control != null && control.equals(CENTER); } - public boolean isSideControl(ControlPoint controlPoint) - { + public boolean isSideControl(ControlPoint controlPoint) { String control = controlPoint.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); return control != null && (control.equals(NORTH) || control.equals(EAST) - || control.equals(SOUTH) || control.equals(WEST)); + || control.equals(SOUTH) || control.equals(WEST)); } - public boolean isCornerControl(ControlPoint controlPoint) - { + public boolean isCornerControl(ControlPoint controlPoint) { String control = controlPoint.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); return control != null && (control.equals(NORTHEAST) || control.equals(SOUTHEAST) - || control.equals(SOUTHWEST) || control.equals(NORTHWEST)); + || control.equals(SOUTHWEST) || control.equals(NORTHWEST)); } // *** Metric accessors *** - - public double getLength() - { + public double getLength() { Globe globe = this.wwd.getModel().getGlobe(); - if (this.line != null) + if (this.line != null) { return this.line.getLength(globe); + } - if (this.surfaceShape != null) + if (this.surfaceShape != null) { return this.surfaceShape.getPerimeter(globe); + } return -1; } - public double getArea() - { + public double getArea() { Globe globe = this.wwd.getModel().getGlobe(); - if (this.surfaceShape != null) + if (this.surfaceShape != null) { return this.surfaceShape.getArea(globe, this.followTerrain); + } return -1; } - public double getWidth() - { - if (this.shapeRectangle != null) + public double getWidth() { + if (this.shapeRectangle != null) { return this.shapeRectangle.width; + } return -1; } - public double getHeight() - { - if (this.shapeRectangle != null) + public double getHeight() { + if (this.shapeRectangle != null) { return this.shapeRectangle.height; + } return -1; } - public Angle getOrientation() - { + public Angle getOrientation() { return this.shapeOrientation; } - public Position getCenterPosition() - { + public Position getCenterPosition() { return this.shapeCenterPosition; } // *** Editing shapes *** - /** * Add a control point to the current measure shape at the current WorldWindow position. * * @return The position of the new control point, or null if the control point could not be added. */ - public Position addControlPoint() - { + public Position addControlPoint() { Position curPos = this.wwd.getCurrentPosition(); - if (curPos == null) + if (curPos == null) { return null; + } - if (this.isRegularShape()) - { + if (this.isRegularShape()) { // Regular shapes are defined in two steps: 1. center, 2. initial corner or edge. - if (this.shapeCenterPosition == null) - { + if (this.shapeCenterPosition == null) { this.shapeCenterPosition = curPos; this.shapeOrientation = this.getShapeInitialHeading(); updateShapeControlPoints(); - } - else if (this.shapeRectangle == null) - { + } else if (this.shapeRectangle == null) { // Compute shape rectangle and heading, curPos being a corner String control = this.getShapeInitialControl(curPos); updateShapeProperties(control, curPos, null); // Update or create control points updateShapeControlPoints(); } - } - else - { - if (!this.measureShapeType.equals(SHAPE_POLYGON) || this.positions.size() <= 1) - { + } else { + if (!this.measureShapeType.equals(SHAPE_POLYGON) || this.positions.size() <= 1) { // Line, path or polygons with less then two points this.positions.add(curPos); addControlPoint(this.positions.get(this.positions.size() - 1), CONTROL_TYPE_LOCATION_INDEX, - this.positions.size() - 1); - if (this.measureShapeType.equals(SHAPE_POLYGON) && this.positions.size() == 2) - { + this.positions.size() - 1); + if (this.measureShapeType.equals(SHAPE_POLYGON) && this.positions.size() == 2) { // Once we have two points of a polygon, add an extra position // to loop back to the first position and have a closed shape this.positions.add(this.positions.get(0)); } - if (this.measureShapeType.equals(SHAPE_LINE) && this.positions.size() > 1) - { + if (this.measureShapeType.equals(SHAPE_LINE) && this.positions.size() > 1) { // Two points on a line, update line heading info this.shapeOrientation = LatLon.greatCircleAzimuth(this.positions.get(0), this.positions.get(1)); } - } - else - { + } else { // For polygons with more then 2 points, the last position is the same as the first, so insert before it this.positions.add(positions.size() - 1, curPos); addControlPoint(this.positions.get(this.positions.size() - 2), CONTROL_TYPE_LOCATION_INDEX, - this.positions.size() - 2); + this.positions.size() - 2); } } // Update screen shapes @@ -1086,49 +1024,43 @@ else if (this.shapeRectangle == null) return curPos; } - /** Remove the last control point from the current measure shape. */ - public void removeControlPoint() - { + /** + * Remove the last control point from the current measure shape. + */ + public void removeControlPoint() { Position currentLastPosition = null; - if (this.isRegularShape()) - { - if (this.shapeRectangle != null) - { + if (this.isRegularShape()) { + if (this.shapeRectangle != null) { this.shapeRectangle = null; this.shapeOrientation = null; this.positions.clear(); // remove all control points except center which is first - while (this.controlPoints.size() > 1) - { + while (this.controlPoints.size() > 1) { this.controlPoints.remove(1); } - } - else if (this.shapeCenterPosition != null) - { + } else if (this.shapeCenterPosition != null) { this.shapeCenterPosition = null; this.controlPoints.clear(); } - } - else - { - if (this.positions.size() == 0) + } else { + if (this.positions.size() == 0) { return; + } - if (!this.measureShapeType.equals(SHAPE_POLYGON) || this.positions.size() == 1) - { + if (!this.measureShapeType.equals(SHAPE_POLYGON) || this.positions.size() == 1) { currentLastPosition = this.positions.get(this.positions.size() - 1); this.positions.remove(this.positions.size() - 1); - } - else - { + } else { // For polygons with more then 2 points, the last position is the same as the first, so remove before it currentLastPosition = this.positions.get(this.positions.size() - 2); this.positions.remove(this.positions.size() - 2); - if (positions.size() == 2) + if (positions.size() == 2) { positions.remove(1); // remove last loop position when a polygon shrank to only two (same) positions + } } - if (this.controlPoints.size() > 0) + if (this.controlPoints.size() > 0) { this.controlPoints.remove(this.controlPoints.size() - 1); + } } this.controlPointsLayer.setRenderables(this.controlPoints); // Update screen shapes @@ -1142,8 +1074,7 @@ else if (this.shapeCenterPosition != null) * * @param point one of the shape control points. */ - public void moveControlPoint(ControlPoint point) - { + public void moveControlPoint(ControlPoint point) { moveControlPoint(point, null); // use the default mode. } @@ -1151,37 +1082,35 @@ public void moveControlPoint(ControlPoint point) * Update the current measure shape according to a given control point position and shape edition mode. * * @param point one of the shape control points. - * @param mode the shape edition mode. + * @param mode the shape edition mode. */ - public void moveControlPoint(ControlPoint point, String mode) - { - if (point == null) - { + public void moveControlPoint(ControlPoint point, String mode) { + if (point == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (point.getValue(CONTROL_TYPE_REGULAR_SHAPE) != null) - { + if (point.getValue(CONTROL_TYPE_REGULAR_SHAPE) != null) { // Update shape properties updateShapeProperties((String) point.getValue(CONTROL_TYPE_REGULAR_SHAPE), point.getPosition(), mode); updateShapeControlPoints(); //positions = makeShapePositions(); } - if (point.getValue(CONTROL_TYPE_LOCATION_INDEX) != null) - { + if (point.getValue(CONTROL_TYPE_LOCATION_INDEX) != null) { int positionIndex = (Integer) point.getValue(CONTROL_TYPE_LOCATION_INDEX); // Update positions Position surfacePosition = computeSurfacePosition(point.getPosition()); surfacePosition = new Position(point.getPosition(), surfacePosition.getAltitude()); positions.set(positionIndex, surfacePosition); // Update last pos too if polygon and first pos changed - if (measureShapeType.equals(SHAPE_POLYGON) && positions.size() > 2 && positionIndex == 0) + if (measureShapeType.equals(SHAPE_POLYGON) && positions.size() > 2 && positionIndex == 0) { positions.set(positions.size() - 1, surfacePosition); + } // Update heading for simple line - if (measureShapeType.equals(SHAPE_LINE) && positions.size() > 1) + if (measureShapeType.equals(SHAPE_LINE) && positions.size() > 1) { shapeOrientation = LatLon.greatCircleAzimuth(positions.get(0), positions.get(1)); + } } // Update rendered shapes @@ -1192,113 +1121,94 @@ public void moveControlPoint(ControlPoint point, String mode) * Move the current measure shape along a great circle arc at a given azimuth Angle for a given * distance Angle. * - * @param azimuth the azimuth Angle. + * @param azimuth the azimuth Angle. * @param distance the distance Angle. */ - public void moveMeasureShape(Angle azimuth, Angle distance) - { - if (distance == null) - { + public void moveMeasureShape(Angle azimuth, Angle distance) { + if (distance == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (azimuth == null) - { + if (azimuth == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (this.isRegularShape()) - { + if (this.isRegularShape()) { // Move regular shape center - if (controlPoints.size() > 0) - { + if (controlPoints.size() > 0) { ControlPoint point = this.getControlPoint(CENTER); point.setPosition( - new Position(LatLon.greatCircleEndPosition(point.getPosition(), azimuth, distance), 0)); + new Position(LatLon.greatCircleEndPosition(point.getPosition(), azimuth, distance), 0)); moveControlPoint(point); } - } - else - { + } else { // Move all positions and control points - for (int i = 0; i < positions.size(); i++) - { + for (int i = 0; i < positions.size(); i++) { Position newPos = computeSurfacePosition( - LatLon.greatCircleEndPosition(positions.get(i), azimuth, distance)); + LatLon.greatCircleEndPosition(positions.get(i), azimuth, distance)); positions.set(i, newPos); - if (!this.measureShapeType.equals(SHAPE_POLYGON) || i < positions.size() - 1) + if (!this.measureShapeType.equals(SHAPE_POLYGON) || i < positions.size() - 1) { ((ControlPoint) controlPoints.get(i)).setPosition(new Position(newPos, 0)); + } } // Update heading for simple line - if (measureShapeType.equals(SHAPE_LINE) && positions.size() > 1) + if (measureShapeType.equals(SHAPE_LINE) && positions.size() > 1) { shapeOrientation = LatLon.greatCircleAzimuth(positions.get(0), positions.get(1)); + } // Update rendered shapes updateMeasureShape(); } } - protected Position computeSurfacePosition(LatLon latLon) - { + protected Position computeSurfacePosition(LatLon latLon) { Vec4 surfacePoint = wwd.getSceneController().getTerrain().getSurfacePoint(latLon.getLatitude(), - latLon.getLongitude()); - if (surfacePoint != null) + latLon.getLongitude()); + if (surfacePoint != null) { return wwd.getModel().getGlobe().computePositionFromPoint(surfacePoint); - else + } else { return new Position(latLon, wwd.getModel().getGlobe().getElevation(latLon.getLatitude(), - latLon.getLongitude())); + latLon.getLongitude())); + } } - public String getShapeInitialControl(Position position) - { - if (this.measureShapeType.equals(SHAPE_ELLIPSE) || this.measureShapeType.equals(SHAPE_CIRCLE)) - { + public String getShapeInitialControl(Position position) { + if (this.measureShapeType.equals(SHAPE_ELLIPSE) || this.measureShapeType.equals(SHAPE_CIRCLE)) { return EAST; - } - else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) - { + } else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) { return NORTHEAST; } return null; } - protected Angle getShapeInitialHeading() - { + protected Angle getShapeInitialHeading() { return this.wwd.getView().getHeading(); } - protected void updateShapeProperties(String control, Position newPosition, String mode) - { - if (control.equals(CENTER)) - { + protected void updateShapeProperties(String control, Position newPosition, String mode) { + if (control.equals(CENTER)) { // Update the shape's center position this.updateShapeCenter(control, newPosition); - } - else if (control.equals(NORTH_LEADER)) - { + } else if (control.equals(NORTH_LEADER)) { // Update the shape's orientation. this.updateShapeOrientation(control, newPosition); - } - else - { + } else { // Update the shape's center position and dimensions. this.updateShapeSize(control, newPosition); } } - protected void updateShapeCenter(String control, Position newPosition) - { + protected void updateShapeCenter(String control, Position newPosition) { this.shapeCenterPosition = newPosition; } - protected void updateShapeOrientation(String control, Position newPosition) - { + protected void updateShapeOrientation(String control, Position newPosition) { // Compute the control point's azimuth in shape local coordinates. Angle controlAzimuth = this.computeControlPointAzimuth(control, this.shapeRectangle.width, - this.shapeRectangle.height); + this.shapeRectangle.height); // Compute the shape's new azimuth as the difference between the great arc azimuth from the shape's // center position and the new corner position, and the corner's azimuth in shape local coordinates. @@ -1309,10 +1219,8 @@ protected void updateShapeOrientation(String control, Position newPosition) this.shapeOrientation = computeNormalizedHeading(newShapeAzimuth); } - protected void updateShapeSize(String control, Position newPosition) - { - if (this.measureShapeType.equals(SHAPE_ELLIPSE) || this.measureShapeType.equals(SHAPE_CIRCLE)) - { + protected void updateShapeSize(String control, Position newPosition) { + if (this.measureShapeType.equals(SHAPE_ELLIPSE) || this.measureShapeType.equals(SHAPE_CIRCLE)) { // Compute azimuth and arc length which define the great arc spanning the shape's center position and the // control point's position. Angle refAzimiuth = this.computeControlPointAzimuth(control, 1d, 1d).add(this.shapeOrientation); @@ -1327,43 +1235,37 @@ protected void updateShapeSize(String control, Position newPosition) double widthMeters; double heightMeters; - if (control.equals(EAST) || control.equals(WEST)) - { + if (control.equals(EAST) || control.equals(WEST)) { widthMeters = 2d * arcLengthMeters; heightMeters = (this.shapeRectangle != null) ? this.shapeRectangle.getHeight() : widthMeters; - if (this.measureShapeType.equals(SHAPE_CIRCLE)) - { + if (this.measureShapeType.equals(SHAPE_CIRCLE)) { //noinspection SuspiciousNameCombination heightMeters = widthMeters; - } - // during shape creation - else if (this.controller != null && this.controller.isActive()) - { + } // during shape creation + else if (this.controller != null && this.controller.isActive()) { heightMeters = 0.6 * widthMeters; } - } - else // if (control.equals(NORTH) || control.equals(SOUTH)) + } else // if (control.equals(NORTH) || control.equals(SOUTH)) { heightMeters = 2d * arcLengthMeters; widthMeters = (this.shapeRectangle != null) ? this.shapeRectangle.getWidth() : heightMeters; - if (this.measureShapeType.equals(SHAPE_CIRCLE)) - { + if (this.measureShapeType.equals(SHAPE_CIRCLE)) { //noinspection SuspiciousNameCombination widthMeters = heightMeters; - } - // during shape creation - else if (this.controller != null && this.controller.isActive()) - { + } // during shape creation + else if (this.controller != null && this.controller.isActive()) { widthMeters = 0.6 * heightMeters; } } - if (widthMeters <= SHAPE_MIN_WIDTH_METERS) + if (widthMeters <= SHAPE_MIN_WIDTH_METERS) { widthMeters = SHAPE_MIN_WIDTH_METERS; - if (heightMeters <= SHAPE_MIN_HEIGHT_METERS) + } + if (heightMeters <= SHAPE_MIN_HEIGHT_METERS) { heightMeters = SHAPE_MIN_HEIGHT_METERS; + } this.shapeRectangle = new Rectangle2D.Double(0d, 0d, widthMeters, heightMeters); @@ -1371,9 +1273,7 @@ else if (this.controller != null && this.controller.isActive()) // the shape to "flip". If so, swap the control point with its horizontal or vertical opposite. This // ensures that control points have the correct orientation. this.swapEdgeControls(control, newPosition); - } - else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) - { + } else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) { ControlPoint oppositeControlPoint = this.getOppositeControl(control); // Compute the corner position diagonal from the current corner position, and compute the azimuth @@ -1384,7 +1284,7 @@ else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equal // Compute the shape's center location as the mid point on the great arc between the two diagonal // control points. LatLon newCenterLocation = LatLon.greatCircleEndPosition(oppositeControlPoint.getPosition(), - diagonalAzimuth, diagonalArcLength.divide(2d)); + diagonalAzimuth, diagonalArcLength.divide(2d)); // Compute the azimuth and arc length which define a great arc between the new center position and // the new corner position. @@ -1401,13 +1301,14 @@ else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equal double widthMeters = 2d * arcLengthMeters * Math.abs(controlAzimuth.sin()); double heightMeters = 2d * arcLengthMeters * Math.abs(controlAzimuth.cos()); - if (widthMeters <= SHAPE_MIN_WIDTH_METERS) + if (widthMeters <= SHAPE_MIN_WIDTH_METERS) { widthMeters = SHAPE_MIN_WIDTH_METERS; - if (heightMeters <= SHAPE_MIN_HEIGHT_METERS) + } + if (heightMeters <= SHAPE_MIN_HEIGHT_METERS) { heightMeters = SHAPE_MIN_HEIGHT_METERS; + } - if (this.measureShapeType.equals(SHAPE_SQUARE)) - { + if (this.measureShapeType.equals(SHAPE_SQUARE)) { // Force the square to have equivalent dimensions. double sizeMeters = Math.min(widthMeters, heightMeters); widthMeters = sizeMeters; @@ -1424,17 +1325,17 @@ else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equal // from its current location. Move the square's opposite control point back to its original location // so that the square drags from a fixed corner out to the current control point. LatLon location = this.moveShapeByControlPoint(oppositeControlPoint, this.wwd.getModel().getGlobe(), - this.shapeOrientation, newCenterLocation, widthMeters, heightMeters); - if (location != null) + this.shapeOrientation, newCenterLocation, widthMeters, heightMeters); + if (location != null) { newCenterLocation = location; + } } // Set the shape's new center position and new dimensions. this.shapeCenterPosition = new Position(newCenterLocation, 0d); this.shapeRectangle = new Rectangle2D.Double(0d, 0d, widthMeters, heightMeters); - if (this.measureShapeType.equals(SHAPE_QUAD)) - { + if (this.measureShapeType.equals(SHAPE_QUAD)) { // Determine if the dragged control point crossed the shape's horizontal or vertical boundary, causing // the shape to "flip". If so, swap the control point with its horizontal or vertical opposite. This // ensures that control points have the correct orientation. @@ -1443,69 +1344,68 @@ else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equal } } - public ControlPoint getControlPoint(String control) - { - for (Renderable cp : this.controlPoints) - { + public ControlPoint getControlPoint(String control) { + for (Renderable cp : this.controlPoints) { String value = ((ControlPoint) cp).getStringValue(CONTROL_TYPE_REGULAR_SHAPE); - if (value != null && value.equals(control)) + if (value != null && value.equals(control)) { return (ControlPoint) cp; + } } return null; } - protected String computeCornerControl(Position position) - { - if (this.shapeCenterPosition == null || this.shapeOrientation == null) + protected String computeCornerControl(Position position) { + if (this.shapeCenterPosition == null || this.shapeOrientation == null) { return null; + } Angle azimuth = LatLon.greatCircleAzimuth(this.shapeCenterPosition, position).subtract(this.shapeOrientation); azimuth = computeNormalizedHeading(azimuth); - if (azimuth.degrees < 90) + if (azimuth.degrees < 90) { return NORTHEAST; - else if (azimuth.degrees < 180) + } else if (azimuth.degrees < 180) { return SOUTHEAST; - else if (azimuth.degrees < 270) + } else if (azimuth.degrees < 270) { return SOUTHWEST; - else + } else { return NORTHWEST; + } } - protected ControlPoint getOppositeControl(String control) - { - if (this.controlPoints.size() == 0) + protected ControlPoint getOppositeControl(String control) { + if (this.controlPoints.size() == 0) { return null; - - else if (this.controlPoints.size() == 1) + } else if (this.controlPoints.size() == 1) { return getControlPoint(CENTER); - else if (control.equals(NORTH)) + } else if (control.equals(NORTH)) { return getControlPoint(SOUTH); - else if (control.equals(EAST)) + } else if (control.equals(EAST)) { return getControlPoint(WEST); - else if (control.equals(SOUTH)) + } else if (control.equals(SOUTH)) { return getControlPoint(NORTH); - else if (control.equals(WEST)) + } else if (control.equals(WEST)) { return getControlPoint(EAST); - else if (control.equals(NORTHEAST)) + } else if (control.equals(NORTHEAST)) { return getControlPoint(SOUTHWEST); - else if (control.equals(SOUTHEAST)) + } else if (control.equals(SOUTHEAST)) { return getControlPoint(NORTHWEST); - else if (control.equals(SOUTHWEST)) + } else if (control.equals(SOUTHWEST)) { return getControlPoint(NORTHEAST); - else if (control.equals(NORTHWEST)) + } else if (control.equals(NORTHWEST)) { return getControlPoint(SOUTHEAST); + } return null; } protected LatLon moveShapeByControlPoint(ControlPoint controlPoint, Globe globe, Angle heading, LatLon center, - double width, double height) - { + double width, double height) { double globeRadius = globe.getRadiusAt(center); String control = controlPoint.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); - if (control == null) + if (control == null) { return center; + } LatLon newCenterLocation = center; @@ -1514,11 +1414,10 @@ protected LatLon moveShapeByControlPoint(ControlPoint controlPoint, Globe globe, // we cannot assume that moving the shape's center point moves any of its corners or edges by exactly that // amount. However, the center and corners should move in a roughly similar manner, so we can iteratively move // a corner until it converges at the desired location. - for (int i = 0; i < MAX_SHAPE_MOVE_ITERATIONS; i++) - { + for (int i = 0; i < MAX_SHAPE_MOVE_ITERATIONS; i++) { // Compute the control point's corresponding location on the shape. LatLon shapeControlLocation = this.computeControlPointLocation(control, globe, heading, newCenterLocation, - width, height); + width, height); // Compute a great arc spanning the control point's location, and its corresponding location on the shape. Angle azimuth = LatLon.greatCircleAzimuth(shapeControlLocation, controlPoint.getPosition()); Angle pathLength = LatLon.greatCircleDistance(shapeControlLocation, controlPoint.getPosition()); @@ -1526,8 +1425,9 @@ protected LatLon moveShapeByControlPoint(ControlPoint controlPoint, Globe globe, // If the great circle distance between the control point's location and its corresponding location on the // shape is less than a predefined value, then we're done. double pathLengthMeters = pathLength.radians * globeRadius; - if (pathLengthMeters < SHAPE_CONTROL_EPSILON_METERS) + if (pathLengthMeters < SHAPE_CONTROL_EPSILON_METERS) { break; + } // Move the center to a new location on the great arc starting at the current center location, and with // azimuth and arc length equal to the arc spanning the corner location and the control point's location. @@ -1537,117 +1437,115 @@ protected LatLon moveShapeByControlPoint(ControlPoint controlPoint, Globe globe, return newCenterLocation; } - protected void swapEdgeControls(String control, Position position) - { - if (this.controlPoints.size() < 2) + protected void swapEdgeControls(String control, Position position) { + if (this.controlPoints.size() < 2) { return; + } - if (this.shapeCenterPosition == null || this.shapeOrientation == null) + if (this.shapeCenterPosition == null || this.shapeOrientation == null) { return; + } Angle azimuth = LatLon.greatCircleAzimuth(this.shapeCenterPosition, position).subtract(this.shapeOrientation); azimuth = computeNormalizedHeading(azimuth); - if ((control.equals(NORTH) && azimuth.degrees < 270 && azimuth.degrees > 90) || - (control.equals(SOUTH) && (azimuth.degrees > 270 || azimuth.degrees < 90))) - { - for (Renderable r : this.controlPoints) - { + if ((control.equals(NORTH) && azimuth.degrees < 270 && azimuth.degrees > 90) + || (control.equals(SOUTH) && (azimuth.degrees > 270 || azimuth.degrees < 90))) { + for (Renderable r : this.controlPoints) { ControlPoint cp = (ControlPoint) r; String c = cp.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); - if (c == null) + if (c == null) { continue; + } - if (c.equals(NORTH)) + if (c.equals(NORTH)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, SOUTH); - else if (c.equals(SOUTH)) + } else if (c.equals(SOUTH)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, NORTH); + } } } - if ((control.equals(EAST) && (azimuth.degrees < 360 && azimuth.degrees > 180)) || - (control.equals(WEST) && (azimuth.degrees < 180 && azimuth.degrees > 0))) - { - for (Renderable r : this.controlPoints) - { + if ((control.equals(EAST) && (azimuth.degrees < 360 && azimuth.degrees > 180)) + || (control.equals(WEST) && (azimuth.degrees < 180 && azimuth.degrees > 0))) { + for (Renderable r : this.controlPoints) { ControlPoint cp = (ControlPoint) r; String c = cp.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); - if (c == null) + if (c == null) { continue; + } - if (c.equals(EAST)) + if (c.equals(EAST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, WEST); - else if (c.equals(WEST)) + } else if (c.equals(WEST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, EAST); + } } } } - protected void swapCornerControls(String control, Position position) - { - if (this.controlPoints.size() < 2) + protected void swapCornerControls(String control, Position position) { + if (this.controlPoints.size() < 2) { return; + } String newControl = this.computeCornerControl(position); - if (control.equals(newControl)) + if (control.equals(newControl)) { return; // no need to swap - + } // For corner controls NE, SE, SW, NW - if (control.length() != 2 || newControl.length() != 2) + if (control.length() != 2 || newControl.length() != 2) { return; + } - if (control.charAt(0) != newControl.charAt(0)) - { - for (Renderable r : this.controlPoints) - { + if (control.charAt(0) != newControl.charAt(0)) { + for (Renderable r : this.controlPoints) { ControlPoint cp = (ControlPoint) r; String c = cp.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); - if (c == null) + if (c == null) { continue; + } - if (c.equals(NORTHEAST)) + if (c.equals(NORTHEAST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, SOUTHEAST); - else if (c.equals(SOUTHEAST)) + } else if (c.equals(SOUTHEAST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, NORTHEAST); - else if (c.equals(SOUTHWEST)) + } else if (c.equals(SOUTHWEST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, NORTHWEST); - else if (c.equals(NORTHWEST)) + } else if (c.equals(NORTHWEST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, SOUTHWEST); + } } } - if (control.charAt(1) != newControl.charAt(1)) - { - for (Renderable r : this.controlPoints) - { + if (control.charAt(1) != newControl.charAt(1)) { + for (Renderable r : this.controlPoints) { ControlPoint cp = (ControlPoint) r; String c = cp.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); - if (c == null) + if (c == null) { continue; + } - if (c.equals(NORTHEAST)) + if (c.equals(NORTHEAST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, NORTHWEST); - else if (c.equals(SOUTHEAST)) + } else if (c.equals(SOUTHEAST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, SOUTHWEST); - else if (c.equals(SOUTHWEST)) + } else if (c.equals(SOUTHWEST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, SOUTHEAST); - else if (c.equals(NORTHWEST)) + } else if (c.equals(NORTHWEST)) { cp.setValue(CONTROL_TYPE_REGULAR_SHAPE, NORTHEAST); + } } } } protected LatLon computeControlPointLocation(String control, Globe globe, Angle heading, LatLon center, - double width, double height) - { + double width, double height) { Angle azimuth = this.computeControlPointAzimuth(control, width, height); Angle pathLength = this.computeControlPointPathLength(control, width, height, globe.getRadiusAt(center)); - if (control.equals(CENTER)) - { + if (control.equals(CENTER)) { return center; - } - else if (azimuth != null && pathLength != null) - { + } else if (azimuth != null && pathLength != null) { azimuth = azimuth.add(heading); return LatLon.greatCircleEndPosition(center, azimuth, pathLength); } @@ -1656,126 +1554,111 @@ else if (azimuth != null && pathLength != null) } protected LatLon computeQuadEdgeMidpointLocation(String control, Globe globe, Angle heading, LatLon center, - double width, double height) - { + double width, double height) { LatLon ne = this.computeControlPointLocation(NORTHEAST, globe, heading, center, width, height); LatLon se = this.computeControlPointLocation(SOUTHEAST, globe, heading, center, width, height); LatLon sw = this.computeControlPointLocation(SOUTHWEST, globe, heading, center, width, height); LatLon nw = this.computeControlPointLocation(NORTHWEST, globe, heading, center, width, height); - if (control.equals(NORTH)) + if (control.equals(NORTH)) { return LatLon.interpolate(this.pathType, 0.5, nw, ne); - else if (control.equals(EAST)) + } else if (control.equals(EAST)) { return LatLon.interpolate(this.pathType, 0.5, ne, se); - else if (control.equals(SOUTH)) + } else if (control.equals(SOUTH)) { return LatLon.interpolate(this.pathType, 0.5, sw, se); - else if (control.equals(WEST)) + } else if (control.equals(WEST)) { return LatLon.interpolate(this.pathType, 0.5, sw, nw); + } return null; } @SuppressWarnings({"SuspiciousNameCombination"}) - protected Angle computeControlPointAzimuth(String control, double width, double height) - { + protected Angle computeControlPointAzimuth(String control, double width, double height) { Angle azimuth = null; - if (control.equals(NORTH)) + if (control.equals(NORTH)) { azimuth = Angle.ZERO; - else if (control.equals(EAST)) + } else if (control.equals(EAST)) { azimuth = Angle.POS90; - else if (control.equals(SOUTH)) + } else if (control.equals(SOUTH)) { azimuth = Angle.POS180; - else if (control.equals(WEST)) + } else if (control.equals(WEST)) { azimuth = Angle.fromDegrees(270); - else if (control.equals(NORTHEAST)) + } else if (control.equals(NORTHEAST)) { azimuth = Angle.fromRadians(Math.atan2(width, height)); - else if (control.equals(SOUTHEAST)) + } else if (control.equals(SOUTHEAST)) { azimuth = Angle.fromRadians(Math.atan2(width, -height)); - else if (control.equals(SOUTHWEST)) + } else if (control.equals(SOUTHWEST)) { azimuth = Angle.fromRadians(Math.atan2(-width, -height)); - else if (control.equals(NORTHWEST)) + } else if (control.equals(NORTHWEST)) { azimuth = Angle.fromRadians(Math.atan2(-width, height)); - else if (control.equals(NORTH_LEADER)) + } else if (control.equals(NORTH_LEADER)) { azimuth = Angle.ZERO; + } return azimuth != null ? computeNormalizedHeading(azimuth) : null; } - protected Angle computeControlPointAzimuthInShapeCoordinates(String control, Angle azimuth) - { - if (control.equals(NORTHEAST)) + protected Angle computeControlPointAzimuthInShapeCoordinates(String control, Angle azimuth) { + if (control.equals(NORTHEAST)) { return azimuth.subtract(this.shapeOrientation); - else if (control.equals(SOUTHEAST)) + } else if (control.equals(SOUTHEAST)) { return this.shapeOrientation.addDegrees(180).subtract(azimuth); - else if (control.equals(SOUTHWEST)) + } else if (control.equals(SOUTHWEST)) { return azimuth.subtract(this.shapeOrientation.addDegrees(180)); - else if (control.equals(NORTHWEST)) + } else if (control.equals(NORTHWEST)) { return this.shapeOrientation.subtract(azimuth); + } return null; } - protected Angle computeControlPointPathLength(String control, double width, double height, double globeRadius) - { + protected Angle computeControlPointPathLength(String control, double width, double height, double globeRadius) { Angle pathLength = null; - if (control.equals(NORTH) || control.equals(SOUTH)) - { + if (control.equals(NORTH) || control.equals(SOUTH)) { pathLength = Angle.fromRadians((height / 2d) / globeRadius); - } - else if (control.equals(EAST) || control.equals(WEST)) - { + } else if (control.equals(EAST) || control.equals(WEST)) { pathLength = Angle.fromRadians((width / 2d) / globeRadius); - } - else if (control.equals(NORTHEAST) || control.equals(SOUTHEAST) || control.equals(SOUTHWEST) || - control.equals(NORTHWEST)) - { + } else if (control.equals(NORTHEAST) || control.equals(SOUTHEAST) || control.equals(SOUTHWEST) + || control.equals(NORTHWEST)) { double diag = Math.sqrt((width * width) / 4d + (height * height) / 4d); pathLength = Angle.fromRadians(diag / globeRadius); - } - else if (control.equals(NORTH_LEADER)) - { + } else if (control.equals(NORTH_LEADER)) { pathLength = Angle.fromRadians(3d / 4d * height / globeRadius); } return pathLength; } - protected static Angle computeNormalizedHeading(Angle heading) - { + protected static Angle computeNormalizedHeading(Angle heading) { double a = heading.degrees % 360; double degrees = a > 360 ? a - 360 : a < 0 ? 360 + a : a; return Angle.fromDegrees(degrees); } - protected void updateShapeControlPoints() - { - if (this.shapeCenterPosition != null) - { + protected void updateShapeControlPoints() { + if (this.shapeCenterPosition != null) { // Set center control point - if (this.controlPoints.size() < 1) + if (this.controlPoints.size() < 1) { addControlPoint(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, CENTER); + } // Update center control point position ((ControlPoint) this.controlPoints.get(0)).setPosition(new Position(this.shapeCenterPosition, 0)); } - if (this.shapeRectangle != null) - { - if (this.controlPoints.size() < 5) - { + if (this.shapeRectangle != null) { + if (this.controlPoints.size() < 5) { // Add control points in four directions - CW from north - if (this.measureShapeType.equals(SHAPE_ELLIPSE) || this.measureShapeType.equals(SHAPE_CIRCLE)) - { + if (this.measureShapeType.equals(SHAPE_ELLIPSE) || this.measureShapeType.equals(SHAPE_CIRCLE)) { this.addControlPoint(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, NORTH); this.addControlPoint(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, EAST); this.addControlPoint(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, SOUTH); this.addControlPoint(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, WEST); - } - // Add control points at four corners - CW from north - else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) - { + } // Add control points at four corners - CW from north + else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) { this.addControlPoint(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, NORTHEAST); this.addControlPoint(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, SOUTHEAST); this.addControlPoint(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, SOUTHWEST); @@ -1784,71 +1667,66 @@ else if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equal // Add a control point with a leader to the top of the shape. this.addControlPointWithLeader(Position.ZERO, CONTROL_TYPE_REGULAR_SHAPE, NORTH_LEADER, - CONTROL_TYPE_LEADER_ORIGIN, NORTH); + CONTROL_TYPE_LEADER_ORIGIN, NORTH); } Globe globe = this.getWwd().getModel().getGlobe(); // Update control points positions - for (Renderable r : this.controlPoints) - { + for (Renderable r : this.controlPoints) { ControlPoint cp = (ControlPoint) r; String control = cp.getStringValue(CONTROL_TYPE_REGULAR_SHAPE); - if (control == null) + if (control == null) { continue; + } LatLon controlLocation = this.computeControlPointLocation(control, globe, this.shapeOrientation, - this.shapeCenterPosition, this.shapeRectangle.getWidth(), this.shapeRectangle.getHeight()); - if (controlLocation == null) + this.shapeCenterPosition, this.shapeRectangle.getWidth(), this.shapeRectangle.getHeight()); + if (controlLocation == null) { continue; + } cp.setPosition(new Position(controlLocation, 0d)); - if (cp instanceof ControlPointWithLeader) - { + if (cp instanceof ControlPointWithLeader) { this.updateControlPointWithLeader((ControlPointWithLeader) cp, controlLocation); } } } } - protected void updateControlPointWithLeader(ControlPointWithLeader cp, LatLon controlLocation) - { + protected void updateControlPointWithLeader(ControlPointWithLeader cp, LatLon controlLocation) { Globe globe = this.getWwd().getModel().getGlobe(); String leaderControl = cp.getStringValue(CONTROL_TYPE_LEADER_ORIGIN); - if (leaderControl == null) + if (leaderControl == null) { return; + } LatLon leaderBegin; - if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) - { + if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) { leaderBegin = this.computeQuadEdgeMidpointLocation(leaderControl, globe, - this.shapeOrientation, this.shapeCenterPosition, this.shapeRectangle.getWidth(), - this.shapeRectangle.getHeight()); - } - else - { + this.shapeOrientation, this.shapeCenterPosition, this.shapeRectangle.getWidth(), + this.shapeRectangle.getHeight()); + } else { leaderBegin = this.computeControlPointLocation(leaderControl, globe, - this.shapeOrientation, this.shapeCenterPosition, this.shapeRectangle.getWidth(), - this.shapeRectangle.getHeight()); + this.shapeOrientation, this.shapeCenterPosition, this.shapeRectangle.getWidth(), + this.shapeRectangle.getHeight()); } - if (leaderBegin == null) + if (leaderBegin == null) { return; + } cp.setLeaderLocations(leaderBegin, controlLocation); } - protected void updateMeasureShape() - { + protected void updateMeasureShape() { // Update line - if (this.measureShapeType.equals(SHAPE_LINE) || this.measureShapeType.equals(SHAPE_PATH)) - { - if (this.positions.size() > 1 && this.line == null) - { + if (this.measureShapeType.equals(SHAPE_LINE) || this.measureShapeType.equals(SHAPE_PATH)) { + if (this.positions.size() > 1 && this.line == null) { // Init polyline this.line = new Polyline(); this.line.setFollowTerrain(this.isFollowTerrain()); @@ -1858,28 +1736,24 @@ protected void updateMeasureShape() //this.line.setNumSubsegments(this.followTerrain ? 10 : 1); this.shapeLayer.addRenderable(this.line); } - if (this.positions.size() < 2 && this.line != null) - { + if (this.positions.size() < 2 && this.line != null) { // Remove line if less then 2 positions this.shapeLayer.removeRenderable(this.line); this.line = null; } // Update current line - if (this.positions.size() > 1 && this.line != null) + if (this.positions.size() > 1 && this.line != null) { this.line.setPositions(this.positions); + } - if (this.surfaceShape != null) - { + if (this.surfaceShape != null) { // Remove surface shape if necessary this.shapeLayer.removeRenderable(this.surfaceShape); this.surfaceShape = null; } - } - // Update polygon - else if (this.measureShapeType.equals(SHAPE_POLYGON)) - { - if (this.positions.size() >= 4 && this.surfaceShape == null) - { + } // Update polygon + else if (this.measureShapeType.equals(SHAPE_POLYGON)) { + if (this.positions.size() >= 4 && this.surfaceShape == null) { // Init surface shape this.surfaceShape = new SurfacePolygon(this.positions); ShapeAttributes attr = new BasicShapeAttributes(); @@ -1891,43 +1765,38 @@ else if (this.measureShapeType.equals(SHAPE_POLYGON)) this.surfaceShape.setAttributes(attr); this.shapeLayer.addRenderable(this.surfaceShape); } - if (this.positions.size() <= 3 && this.surfaceShape != null) - { + if (this.positions.size() <= 3 && this.surfaceShape != null) { // Remove surface shape if only three positions or less - last is same as first this.shapeLayer.removeRenderable(this.surfaceShape); this.surfaceShape = null; } - if (this.surfaceShape != null) - { + if (this.surfaceShape != null) { // Update current shape ((SurfacePolygon) this.surfaceShape).setLocations(this.positions); } // Remove line if necessary - if (this.line != null) - { + if (this.line != null) { this.shapeLayer.removeRenderable(this.line); this.line = null; } - } - // Update regular shape - else if (this.isRegularShape()) - { - if (this.shapeCenterPosition != null && this.shapeRectangle != null && this.surfaceShape == null) - { + } // Update regular shape + else if (this.isRegularShape()) { + if (this.shapeCenterPosition != null && this.shapeRectangle != null && this.surfaceShape == null) { // Init surface shape - if (this.measureShapeType.equals(SHAPE_QUAD)) + if (this.measureShapeType.equals(SHAPE_QUAD)) { this.surfaceShape = new SurfaceQuad(this.shapeCenterPosition, - this.shapeRectangle.width, this.shapeRectangle.height, this.shapeOrientation); - else if (this.measureShapeType.equals(SHAPE_SQUARE)) + this.shapeRectangle.width, this.shapeRectangle.height, this.shapeOrientation); + } else if (this.measureShapeType.equals(SHAPE_SQUARE)) { this.surfaceShape = new SurfaceSquare(this.shapeCenterPosition, - this.shapeRectangle.width); - else if (this.measureShapeType.equals(SHAPE_ELLIPSE)) + this.shapeRectangle.width); + } else if (this.measureShapeType.equals(SHAPE_ELLIPSE)) { this.surfaceShape = new SurfaceEllipse(this.shapeCenterPosition, - this.shapeRectangle.width / 2, this.shapeRectangle.height / 2, this.shapeOrientation, - this.shapeIntervals); - else if (this.measureShapeType.equals(SHAPE_CIRCLE)) + this.shapeRectangle.width / 2, this.shapeRectangle.height / 2, this.shapeOrientation, + this.shapeIntervals); + } else if (this.measureShapeType.equals(SHAPE_CIRCLE)) { this.surfaceShape = new SurfaceCircle(this.shapeCenterPosition, - this.shapeRectangle.width / 2, this.shapeIntervals); + this.shapeRectangle.width / 2, this.shapeIntervals); + } ShapeAttributes attr = new BasicShapeAttributes(); attr.setInteriorMaterial(new Material(this.getFillColor())); @@ -1938,64 +1807,56 @@ else if (this.measureShapeType.equals(SHAPE_CIRCLE)) this.surfaceShape.setAttributes(attr); this.shapeLayer.addRenderable(this.surfaceShape); } - if (this.shapeRectangle == null && this.surfaceShape != null) - { + if (this.shapeRectangle == null && this.surfaceShape != null) { // Remove surface shape if not defined this.shapeLayer.removeRenderable(this.surfaceShape); this.surfaceShape = null; this.positions.clear(); } - if (this.surfaceShape != null) - { + if (this.surfaceShape != null) { // Update current shape - if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) - { + if (this.measureShapeType.equals(SHAPE_QUAD) || this.measureShapeType.equals(SHAPE_SQUARE)) { ((SurfaceQuad) this.surfaceShape).setCenter(this.shapeCenterPosition); ((SurfaceQuad) this.surfaceShape).setSize(this.shapeRectangle.width, this.shapeRectangle.height); ((SurfaceQuad) this.surfaceShape).setHeading(this.shapeOrientation); } - if (this.measureShapeType.equals(SHAPE_ELLIPSE) || this.measureShapeType.equals(SHAPE_CIRCLE)) - { + if (this.measureShapeType.equals(SHAPE_ELLIPSE) || this.measureShapeType.equals(SHAPE_CIRCLE)) { ((SurfaceEllipse) this.surfaceShape).setCenter(this.shapeCenterPosition); ((SurfaceEllipse) this.surfaceShape).setRadii(this.shapeRectangle.width / 2, - this.shapeRectangle.height / 2); + this.shapeRectangle.height / 2); ((SurfaceEllipse) this.surfaceShape).setHeading(this.shapeOrientation); } // Update position from shape list with zero elevation updatePositionsFromShape(); } // Remove line if necessary - if (this.line != null) - { + if (this.line != null) { this.shapeLayer.removeRenderable(this.line); this.line = null; } } } - protected void updatePositionsFromShape() - { + protected void updatePositionsFromShape() { Globe globe = this.wwd.getModel().getGlobe(); this.positions.clear(); Iterable locations = this.surfaceShape.getLocations(globe); - if (locations != null) - { - for (LatLon latLon : locations) - { + if (locations != null) { + for (LatLon latLon : locations) { this.positions.add(new Position(latLon, 0)); } } } - public void dispose() - { + public void dispose() { this.setController(null); - if (this.applicationLayer != null) + if (this.applicationLayer != null) { this.applicationLayer.removeRenderable(this.layer); - else + } else { this.wwd.getModel().getLayers().remove(this.layer); + } this.layer.removeAllRenderables(); this.shapeLayer.removeAllRenderables(); this.controlPoints.clear(); @@ -2003,75 +1864,66 @@ public void dispose() } // *** Control points *** + public static class ControlPoint extends GlobeAnnotation { - public static class ControlPoint extends GlobeAnnotation - { MeasureTool parent; - public ControlPoint(Position position, AnnotationAttributes attributes, MeasureTool parent) - { + public ControlPoint(Position position, AnnotationAttributes attributes, MeasureTool parent) { super("", position, attributes); this.parent = parent; } - public MeasureTool getParent() - { + public MeasureTool getParent() { return this.parent; } } - protected static class ControlPointWithLeader extends ControlPoint implements PreRenderable - { + protected static class ControlPointWithLeader extends ControlPoint implements PreRenderable { + protected SurfacePolyline leaderLine; public ControlPointWithLeader(Position position, AnnotationAttributes controlPointAttributes, - ShapeAttributes leaderAttributes, MeasureTool parent) - { + ShapeAttributes leaderAttributes, MeasureTool parent) { super(position, controlPointAttributes, parent); this.leaderLine = new SurfacePolyline(leaderAttributes); } - public void preRender(DrawContext dc) - { - if (dc == null) - { + public void preRender(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.leaderLine != null) + if (this.leaderLine != null) { this.leaderLine.preRender(dc); + } } @Override - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.leaderLine != null) + if (this.leaderLine != null) { this.leaderLine.render(dc); + } super.render(dc); } - public void setLeaderLocations(LatLon begin, LatLon end) - { - if (begin == null) - { + public void setLeaderLocations(LatLon begin, LatLon end) { + if (begin == null) { String message = Logging.getMessage("nullValue.BeginIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (end == null) - { + if (end == null) { String message = Logging.getMessage("nullValue.EndIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -2081,41 +1933,35 @@ public void setLeaderLocations(LatLon begin, LatLon end) } } - protected void addControlPoint(Position position, String key, Object value) - { + protected void addControlPoint(Position position, String key, Object value) { ControlPoint controlPoint = new ControlPoint(new Position(position, 0), this.controlPointsAttributes, this); controlPoint.setValue(key, value); this.doAddControlPoint(controlPoint); } protected void addControlPointWithLeader(Position position, String controlKey, Object control, String leaderKey, - Object leader) - { + Object leader) { ControlPointWithLeader controlPoint = new ControlPointWithLeader(new Position(position, 0), - this.controlPointWithLeaderAttributes, this.leaderAttributes, this); + this.controlPointWithLeaderAttributes, this.leaderAttributes, this); controlPoint.setValue(controlKey, control); controlPoint.setValue(leaderKey, leader); this.doAddControlPoint(controlPoint); } - protected void doAddControlPoint(ControlPoint controlPoint) - { + protected void doAddControlPoint(ControlPoint controlPoint) { this.controlPoints.add(controlPoint); this.controlPointsLayer.setRenderables(this.controlPoints); } - public void updateAnnotation(Position pos) - { - if (pos == null) - { + public void updateAnnotation(Position pos) { + if (pos == null) { this.annotation.getAttributes().setVisible(false); return; } String displayString = this.getDisplayString(pos); - if (displayString == null) - { + if (displayString == null) { this.annotation.getAttributes().setVisible(false); return; } @@ -2126,34 +1972,21 @@ public void updateAnnotation(Position pos) this.annotation.getAttributes().setVisible(true); } - protected String getDisplayString(Position pos) - { + protected String getDisplayString(Position pos) { String displayString = null; - if (pos != null) - { - if (this.measureShapeType.equals(SHAPE_CIRCLE) && this.shapeRectangle != null) - { + if (pos != null) { + if (this.measureShapeType.equals(SHAPE_CIRCLE) && this.shapeRectangle != null) { displayString = this.formatCircleMeasurements(pos); - } - else if (this.measureShapeType.equals(SHAPE_SQUARE) && this.shapeRectangle != null) - { + } else if (this.measureShapeType.equals(SHAPE_SQUARE) && this.shapeRectangle != null) { displayString = this.formatSquareMeasurements(pos); - } - else if (this.measureShapeType.equals(SHAPE_QUAD) && this.shapeRectangle != null) - { + } else if (this.measureShapeType.equals(SHAPE_QUAD) && this.shapeRectangle != null) { displayString = this.formatQuadMeasurements(pos); - } - else if (this.measureShapeType.equals(SHAPE_ELLIPSE) && this.shapeRectangle != null) - { + } else if (this.measureShapeType.equals(SHAPE_ELLIPSE) && this.shapeRectangle != null) { displayString = this.formatEllipseMeasurements(pos); - } - else if (this.measureShapeType.equals(SHAPE_LINE) || this.measureShapeType.equals(SHAPE_PATH)) - { + } else if (this.measureShapeType.equals(SHAPE_LINE) || this.measureShapeType.equals(SHAPE_PATH)) { displayString = this.formatLineMeasurements(pos); - } - else if (this.measureShapeType.equals(SHAPE_POLYGON)) - { + } else if (this.measureShapeType.equals(SHAPE_POLYGON)) { displayString = this.formatPolygonMeasurements(pos); } } @@ -2161,26 +1994,24 @@ else if (this.measureShapeType.equals(SHAPE_POLYGON)) return displayString; } - protected String formatCircleMeasurements(Position pos) - { + protected String formatCircleMeasurements(Position pos) { StringBuilder sb = new StringBuilder(); sb.append(this.unitsFormat.areaNL(this.getLabel(AREA_LABEL), this.getArea())); sb.append(this.unitsFormat.lengthNL(this.getLabel(PERIMETER_LABEL), this.getLength())); - if (this.shapeRectangle != null) + if (this.shapeRectangle != null) { sb.append(this.unitsFormat.lengthNL(this.getLabel(RADIUS_LABEL), this.shapeRectangle.width / 2d)); + } - if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) - { + if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) { sb.append( - this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); + this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(CENTER_LONGITUDE_LABEL), - this.getCenterPosition().getLongitude())); + this.getCenterPosition().getLongitude())); } - if (!this.areLocationsRedundant(pos, this.getCenterPosition())) - { + if (!this.areLocationsRedundant(pos, this.getCenterPosition())) { sb.append(this.unitsFormat.angleNL(this.getLabel(LATITUDE_LABEL), pos.getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(LONGITUDE_LABEL), pos.getLongitude())); } @@ -2188,32 +2019,29 @@ protected String formatCircleMeasurements(Position pos) return sb.toString(); } - protected String formatEllipseMeasurements(Position pos) - { + protected String formatEllipseMeasurements(Position pos) { StringBuilder sb = new StringBuilder(); sb.append(this.unitsFormat.areaNL(this.getLabel(AREA_LABEL), this.getArea())); sb.append(this.unitsFormat.lengthNL(this.getLabel(PERIMETER_LABEL), this.getLength())); - if (this.shapeRectangle != null) - { + if (this.shapeRectangle != null) { sb.append(this.unitsFormat.lengthNL(this.getLabel(MAJOR_AXIS_LABEL), this.shapeRectangle.width)); sb.append(this.unitsFormat.lengthNL(this.getLabel(MINOR_AXIS_LABEL), this.shapeRectangle.height)); } - if (this.getOrientation() != null) + if (this.getOrientation() != null) { sb.append(this.unitsFormat.angleNL(this.getLabel(HEADING_LABEL), this.getOrientation())); + } - if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) - { + if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) { sb.append( - this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); + this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(CENTER_LONGITUDE_LABEL), - this.getCenterPosition().getLongitude())); + this.getCenterPosition().getLongitude())); } - if (!this.areLocationsRedundant(pos, this.getCenterPosition())) - { + if (!this.areLocationsRedundant(pos, this.getCenterPosition())) { sb.append(this.unitsFormat.angleNL(this.getLabel(LATITUDE_LABEL), pos.getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(LONGITUDE_LABEL), pos.getLongitude())); } @@ -2221,29 +2049,28 @@ protected String formatEllipseMeasurements(Position pos) return sb.toString(); } - protected String formatSquareMeasurements(Position pos) - { + protected String formatSquareMeasurements(Position pos) { StringBuilder sb = new StringBuilder(); sb.append(this.unitsFormat.areaNL(this.getLabel(AREA_LABEL), this.getArea())); sb.append(this.unitsFormat.lengthNL(this.getLabel(PERIMETER_LABEL), this.getLength())); - if (this.shapeRectangle != null) + if (this.shapeRectangle != null) { sb.append(this.unitsFormat.lengthNL(this.getLabel(WIDTH_LABEL), this.shapeRectangle.width)); + } - if (this.getOrientation() != null) + if (this.getOrientation() != null) { sb.append(this.unitsFormat.angleNL(this.getLabel(HEADING_LABEL), this.getOrientation())); + } - if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) - { + if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) { sb.append( - this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); + this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(CENTER_LONGITUDE_LABEL), - this.getCenterPosition().getLongitude())); + this.getCenterPosition().getLongitude())); } - if (!this.areLocationsRedundant(pos, this.getCenterPosition())) - { + if (!this.areLocationsRedundant(pos, this.getCenterPosition())) { sb.append(this.unitsFormat.angleNL(this.getLabel(LATITUDE_LABEL), pos.getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(LONGITUDE_LABEL), pos.getLongitude())); } @@ -2251,32 +2078,29 @@ protected String formatSquareMeasurements(Position pos) return sb.toString(); } - protected String formatQuadMeasurements(Position pos) - { + protected String formatQuadMeasurements(Position pos) { StringBuilder sb = new StringBuilder(); sb.append(this.unitsFormat.areaNL(this.getLabel(AREA_LABEL), this.getArea())); sb.append(this.unitsFormat.lengthNL(this.getLabel(PERIMETER_LABEL), this.getLength())); - if (this.shapeRectangle != null) - { + if (this.shapeRectangle != null) { sb.append(this.unitsFormat.lengthNL(this.getLabel(WIDTH_LABEL), this.shapeRectangle.width)); sb.append(this.unitsFormat.lengthNL(this.getLabel(HEIGHT_LABEL), this.shapeRectangle.height)); } - if (this.getOrientation() != null) + if (this.getOrientation() != null) { sb.append(this.unitsFormat.angleNL(this.getLabel(HEADING_LABEL), this.getOrientation())); + } - if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) - { + if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) { sb.append( - this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); + this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(CENTER_LONGITUDE_LABEL), - this.getCenterPosition().getLongitude())); + this.getCenterPosition().getLongitude())); } - if (!this.areLocationsRedundant(pos, this.getCenterPosition())) - { + if (!this.areLocationsRedundant(pos, this.getCenterPosition())) { sb.append(this.unitsFormat.angleNL(this.getLabel(LATITUDE_LABEL), pos.getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(LONGITUDE_LABEL), pos.getLongitude())); } @@ -2284,23 +2108,20 @@ protected String formatQuadMeasurements(Position pos) return sb.toString(); } - protected String formatPolygonMeasurements(Position pos) - { + protected String formatPolygonMeasurements(Position pos) { StringBuilder sb = new StringBuilder(); sb.append(this.unitsFormat.areaNL(this.getLabel(AREA_LABEL), this.getArea())); sb.append(this.unitsFormat.lengthNL(this.getLabel(PERIMETER_LABEL), this.getLength())); - if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) - { + if (this.getCenterPosition() != null && areLocationsRedundant(this.getCenterPosition(), pos)) { sb.append( - this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); + this.unitsFormat.angleNL(this.getLabel(CENTER_LATITUDE_LABEL), this.getCenterPosition().getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(CENTER_LONGITUDE_LABEL), - this.getCenterPosition().getLongitude())); + this.getCenterPosition().getLongitude())); } - if (!this.areLocationsRedundant(pos, this.getCenterPosition())) - { + if (!this.areLocationsRedundant(pos, this.getCenterPosition())) { sb.append(this.unitsFormat.angleNL(this.getLabel(LATITUDE_LABEL), pos.getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(LONGITUDE_LABEL), pos.getLongitude())); } @@ -2308,19 +2129,20 @@ protected String formatPolygonMeasurements(Position pos) return sb.toString(); } - protected String formatLineMeasurements(Position pos) - { + protected String formatLineMeasurements(Position pos) { // TODO: Compute the heading of individual path segments StringBuilder sb = new StringBuilder(); sb.append(this.unitsFormat.lengthNL(this.getLabel(LENGTH_LABEL), this.getLength())); Double accumLength = this.computeAccumulatedLength(pos); - if (accumLength != null && accumLength >= 1 && !lengthsEssentiallyEqual(this.getLength(), accumLength)) + if (accumLength != null && accumLength >= 1 && !lengthsEssentiallyEqual(this.getLength(), accumLength)) { sb.append(this.unitsFormat.lengthNL(this.getLabel(ACCUMULATED_LABEL), accumLength)); + } - if (this.getOrientation() != null) + if (this.getOrientation() != null) { sb.append(this.unitsFormat.angleNL(this.getLabel(HEADING_LABEL), this.getOrientation())); + } sb.append(this.unitsFormat.angleNL(this.getLabel(LATITUDE_LABEL), pos.getLatitude())); sb.append(this.unitsFormat.angleNL(this.getLabel(LONGITUDE_LABEL), pos.getLongitude())); @@ -2328,31 +2150,29 @@ protected String formatLineMeasurements(Position pos) return sb.toString(); } - protected Double computeAccumulatedLength(LatLon pos) - { - if (this.positions.size() <= 2) + protected Double computeAccumulatedLength(LatLon pos) { + if (this.positions.size() <= 2) { return null; + } double radius = this.wwd.getModel().getGlobe().getRadius(); double distanceFromStart = 0; int segmentIndex = 0; LatLon pos1 = this.positions.get(segmentIndex); - for (int i = 1; i < this.positions.size(); i++) - { + for (int i = 1; i < this.positions.size(); i++) { LatLon pos2 = this.positions.get(i); double segmentLength = LatLon.greatCircleDistance(pos1, pos2).radians * radius; // Check whether the position is inside the segment double length1 = LatLon.greatCircleDistance(pos1, pos).radians * radius; double length2 = LatLon.greatCircleDistance(pos2, pos).radians * radius; - if (length1 <= segmentLength && length2 <= segmentLength) - { + if (length1 <= segmentLength && length2 <= segmentLength) { // Compute portion of segment length distanceFromStart += length1 / (length1 + length2) * segmentLength; break; - } - else + } else { distanceFromStart += segmentLength; + } pos1 = pos2; } @@ -2361,49 +2181,47 @@ protected Double computeAccumulatedLength(LatLon pos) return distanceFromStart < gcPathLength ? this.getLength() * (distanceFromStart / gcPathLength) : null; } - protected double computePathLength() - { + protected double computePathLength() { double pathLengthRadians = 0; LatLon pos1 = null; - for (LatLon pos2 : this.positions) - { - if (pos1 != null) + for (LatLon pos2 : this.positions) { + if (pos1 != null) { pathLengthRadians += LatLon.greatCircleDistance(pos1, pos2).radians; + } pos1 = pos2; } return pathLengthRadians * this.wwd.getModel().getGlobe().getRadius(); } - protected Angle computeAngleBetween(LatLon a, LatLon b, LatLon c) - { + protected Angle computeAngleBetween(LatLon a, LatLon b, LatLon c) { Vec4 v0 = new Vec4( - b.getLatitude().radians - a.getLatitude().radians, - b.getLongitude().radians - a.getLongitude().radians, 0); + b.getLatitude().radians - a.getLatitude().radians, + b.getLongitude().radians - a.getLongitude().radians, 0); Vec4 v1 = new Vec4( - c.getLatitude().radians - b.getLatitude().radians, - c.getLongitude().radians - b.getLongitude().radians, 0); + c.getLatitude().radians - b.getLatitude().radians, + c.getLongitude().radians - b.getLongitude().radians, 0); return v0.angleBetween3(v1); } - protected boolean lengthsEssentiallyEqual(Double l1, Double l2) - { + protected boolean lengthsEssentiallyEqual(Double l1, Double l2) { return Math.abs(l1 - l2) / l1 < 0.001; // equal to within a milimeter } - protected boolean areLocationsRedundant(LatLon locA, LatLon locB) - { - if (locA == null || locB == null) + protected boolean areLocationsRedundant(LatLon locA, LatLon locB) { + if (locA == null || locB == null) { return false; + } String aLat = this.unitsFormat.angleNL("", locA.getLatitude()); String bLat = this.unitsFormat.angleNL("", locB.getLatitude()); - if (!aLat.equals(bLat)) + if (!aLat.equals(bLat)) { return false; + } String aLon = this.unitsFormat.angleNL("", locA.getLongitude()); String bLon = this.unitsFormat.angleNL("", locB.getLongitude()); diff --git a/src/gov/nasa/worldwind/util/measure/MeasureToolController.java b/src/gov/nasa/worldwind/util/measure/MeasureToolController.java index 9e40ee02ff..f0401cc96c 100644 --- a/src/gov/nasa/worldwind/util/measure/MeasureToolController.java +++ b/src/gov/nasa/worldwind/util/measure/MeasureToolController.java @@ -21,8 +21,8 @@ * @see MeasureTool */ public class MeasureToolController extends MouseAdapter - implements MouseListener, MouseMotionListener, SelectListener, PositionListener, RenderingListener -{ + implements MouseListener, MouseMotionListener, SelectListener, PositionListener, RenderingListener { + protected MeasureTool measureTool; protected boolean armed = false; @@ -42,10 +42,8 @@ public class MeasureToolController extends MouseAdapter * * @param measureTool the MeasureTool that this controller will be operating on. */ - public void setMeasureTool(MeasureTool measureTool) - { - if (measureTool == null) - { + public void setMeasureTool(MeasureTool measureTool) { + if (measureTool == null) { String msg = Logging.getMessage("nullValue.MeasureToolIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -59,9 +57,7 @@ public void setMeasureTool(MeasureTool measureTool) * * @return the MeasureTool that this controller is operating on. */ - - public MeasureTool getMeasureTool() - { + public MeasureTool getMeasureTool() { return this.measureTool; } @@ -72,8 +68,7 @@ public MeasureTool getMeasureTool() * * @return true if this controller is using rubber band during shape creation. */ - public boolean isUseRubberBand() - { + public boolean isUseRubberBand() { return this.useRubberBand; } @@ -84,8 +79,7 @@ public boolean isUseRubberBand() * * @param state true if this controller should use rubber band during shape creation. */ - public void setUseRubberBand(boolean state) - { + public void setUseRubberBand(boolean state) { this.useRubberBand = state; } @@ -94,8 +88,7 @@ public void setUseRubberBand(boolean state) * * @return true if free hand drawing of path and polygons in rubber band mode. */ - public boolean isFreeHand() - { + public boolean isFreeHand() { return this.freeHand; } @@ -104,8 +97,7 @@ public boolean isFreeHand() * * @param state true to allow free hand drawing of path and polygons in rubber band mode. */ - public void setFreeHand(boolean state) - { + public void setFreeHand(boolean state) { this.freeHand = state; } @@ -114,8 +106,7 @@ public void setFreeHand(boolean state) * * @return the minimum distance in meters between two control points for free hand drawing. */ - public double getFreeHandMinSpacing() - { + public double getFreeHandMinSpacing() { return this.freeHandMinSpacing; } @@ -124,8 +115,7 @@ public double getFreeHandMinSpacing() * * @param distance the minimum distance in meters between two control points for free hand drawing. */ - public void setFreeHandMinSpacing(double distance) - { + public void setFreeHandMinSpacing(double distance) { this.freeHandMinSpacing = distance; } @@ -134,21 +124,18 @@ public void setFreeHandMinSpacing(double distance) * * @return true if armed, false if not armed. */ - public boolean isArmed() - { + public boolean isArmed() { return this.armed; } /** - * Arms and disarms the measure tool controller. When armed, the controller monitors user input and builds the - * shape in response to user actions. When disarmed, the controller ignores all user input. + * Arms and disarms the measure tool controller. When armed, the controller monitors user input and builds the shape + * in response to user actions. When disarmed, the controller ignores all user input. * * @param armed true to arm the controller, false to disarm it. */ - public void setArmed(boolean armed) - { - if (this.armed != armed) - { + public void setArmed(boolean armed) { + if (this.armed != armed) { this.armed = armed; this.measureTool.firePropertyChange(MeasureTool.EVENT_ARMED, !armed, armed); } @@ -159,13 +146,11 @@ public void setArmed(boolean armed) * * @return true if the controller is in the middle of a rubber band operation. */ - public boolean isActive() - { + public boolean isActive() { return this.active; } - protected void setActive(boolean state) - { + protected void setActive(boolean state) { this.active = state; } @@ -174,55 +159,42 @@ protected void setActive(boolean state) * * @return true if the controller is moving the measure shape as a whole. */ - public boolean isMoving() - { + public boolean isMoving() { return this.moving; } - protected void setMoving(boolean state) - { + protected void setMoving(boolean state) { this.moving = state; } // Handle mouse actions - public void mousePressed(MouseEvent mouseEvent) - { - if (this.isArmed() && this.isUseRubberBand() && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if ((mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { - if (!mouseEvent.isControlDown()) - { + public void mousePressed(MouseEvent mouseEvent) { + if (this.isArmed() && this.isUseRubberBand() && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if ((mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { + if (!mouseEvent.isControlDown()) { this.setActive(true); if (measureTool.addControlPoint() != null) // null when the cursor is off the globe { - if (measureTool.getControlPoints().size() == 1) - { + if (measureTool.getControlPoints().size() == 1) { measureTool.addControlPoint(); // Simulate a second click } // Set the rubber band target to the last control point or the relevant control for regular shapes. - if (measureTool.isRegularShape()) - { - String initControl = - measureTool.getShapeInitialControl(measureTool.getWwd().getCurrentPosition()); + if (measureTool.isRegularShape()) { + String initControl + = measureTool.getShapeInitialControl(measureTool.getWwd().getCurrentPosition()); rubberBandTarget = measureTool.getControlPoint(initControl); - } - else - { + } else { rubberBandTarget = (MeasureTool.ControlPoint) measureTool.getControlPoints().get( - measureTool.getControlPoints().size() - 1); + measureTool.getControlPoints().size() - 1); } measureTool.firePropertyChange(MeasureTool.EVENT_RUBBERBAND_START, null, null); } } } mouseEvent.consume(); - } - else if(!this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1 && mouseEvent.isAltDown()) - { - if (!this.measureTool.isRegularShape()) - { + } else if (!this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1 && mouseEvent.isAltDown()) { + if (!this.measureTool.isRegularShape()) { this.setMoving(true); this.movingTarget = this.lastPickedObject; } @@ -230,21 +202,18 @@ else if(!this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1 && mouse } } - public void mouseReleased(MouseEvent mouseEvent) - { - if (this.isArmed() && this.isUseRubberBand() && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (measureTool.getPositions().size() == 1) + public void mouseReleased(MouseEvent mouseEvent) { + if (this.isArmed() && this.isUseRubberBand() && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (measureTool.getPositions().size() == 1) { measureTool.removeControlPoint(); + } this.setActive(false); rubberBandTarget = null; // Disarm after second control point of a line or regular shape autoDisarm(); mouseEvent.consume(); measureTool.firePropertyChange(MeasureTool.EVENT_RUBBERBAND_STOP, null, null); - } - else if (this.isMoving() && mouseEvent.getButton() == MouseEvent.BUTTON1) - { + } else if (this.isMoving() && mouseEvent.getButton() == MouseEvent.BUTTON1) { this.setMoving(false); this.movingTarget = null; mouseEvent.consume(); @@ -252,20 +221,17 @@ else if (this.isMoving() && mouseEvent.getButton() == MouseEvent.BUTTON1) } // Handle single click for removing control points - public void mouseClicked(MouseEvent mouseEvent) - { - if (measureTool == null) + public void mouseClicked(MouseEvent mouseEvent) { + if (measureTool == null) { return; + } - if (this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (mouseEvent.isControlDown()) + if (this.isArmed() && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (mouseEvent.isControlDown()) { measureTool.removeControlPoint(); - else if (!this.isUseRubberBand()) - { + } else if (!this.isUseRubberBand()) { // Disarm after second control point of a line or regular shape - if (measureTool.addControlPoint() != null) - { + if (measureTool.addControlPoint() != null) { autoDisarm(); } } @@ -273,24 +239,20 @@ else if (!this.isUseRubberBand()) } } - // Handle mouse motion - public void mouseDragged(MouseEvent mouseEvent) - { - if (measureTool == null) + public void mouseDragged(MouseEvent mouseEvent) { + if (measureTool == null) { return; + } - if (this.isActive() && this.isArmed() && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { + if (this.isActive() && this.isArmed() && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { // Don't update the control point here because the wwd current cursor position will not // have been updated to reflect the current mouse position. Wait to update in the // position listener, but consume the event so the view doesn't respond to it. mouseEvent.consume(); - } - else if (!this.isArmed() && this.isMoving() - && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0 - && mouseEvent.isAltDown()) - { + } else if (!this.isArmed() && this.isMoving() + && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0 + && mouseEvent.isAltDown()) { // Consume the ALT+Drag mouse event to ensure the View does not respond to it. Don't update the control // point here because the wwd current cursor position will not have been updated to reflect the current // mouse position. Wait to update in the position listener, but consume the event so the view doesn't @@ -299,34 +261,33 @@ else if (!this.isArmed() && this.isMoving() } } - public void mouseMoved(MouseEvent mouseEvent) - { + public void mouseMoved(MouseEvent mouseEvent) { } // Handle cursor position change for rubber band - public void moved(PositionEvent event) - { - if (measureTool == null || (!this.active && !this.moving)) + public void moved(PositionEvent event) { + if (measureTool == null || (!this.active && !this.moving)) { return; + } this.doMoved(event); } // Handle dragging of control points - public void selected(SelectEvent event) - { + public void selected(SelectEvent event) { // Ignore select events if the tools is armed, or in a move/rotate action. In either case we don't // want to change the currently selected or hightlighted control point. - if (measureTool == null || (this.isArmed() && this.isUseRubberBand()) || this.isMoving()) + if (measureTool == null || (this.isArmed() && this.isUseRubberBand()) || this.isMoving()) { return; + } - if (dragger == null) + if (dragger == null) { dragger = new BasicDragger(measureTool.getWwd()); + } // Have rollover events highlight the rolled-over object. - if (event.getEventAction().equals(SelectEvent.ROLLOVER) && !dragger.isDragging()) - { + if (event.getEventAction().equals(SelectEvent.ROLLOVER) && !dragger.isDragging()) { this.highlight(event.getTopObject()); this.measureTool.getWwd().redraw(); } @@ -335,11 +296,9 @@ public void selected(SelectEvent event) // We missed any roll-over events while dragging, so highlight any under the cursor now, // or de-highlight the dragged control point if it's no longer under the cursor. - if (event.getEventAction().equals(SelectEvent.DRAG_END)) - { + if (event.getEventAction().equals(SelectEvent.DRAG_END)) { PickedObjectList pol = this.measureTool.getWwd().getObjectsAtCurrentPosition(); - if (pol != null) - { + if (pol != null) { this.highlight(pol.getTopObject()); this.measureTool.getWwd().redraw(); } @@ -347,26 +306,22 @@ public void selected(SelectEvent event) } // Wait for end of rendering to update metrics - length, area... - public void stageChanged(RenderingEvent event) - { - if (measureTool == null) + public void stageChanged(RenderingEvent event) { + if (measureTool == null) { return; + } - if (event.getStage().equals(RenderingEvent.AFTER_BUFFER_SWAP)) - { + if (event.getStage().equals(RenderingEvent.AFTER_BUFFER_SWAP)) { measureTool.firePropertyChange(MeasureTool.EVENT_METRIC_CHANGED, null, null); } } @SuppressWarnings({"UnusedDeclaration"}) - protected void doMoved(PositionEvent event) - { + protected void doMoved(PositionEvent event) { if (this.active && rubberBandTarget != null && this.measureTool.getWwd().getObjectsAtCurrentPosition() != null - && this.measureTool.getWwd().getObjectsAtCurrentPosition().getTerrainObject() != null) - { + && this.measureTool.getWwd().getObjectsAtCurrentPosition().getTerrainObject() != null) { if (!isFreeHand() || (!measureTool.getMeasureShapeType().equals(MeasureTool.SHAPE_PATH) - && !measureTool.getMeasureShapeType().equals(MeasureTool.SHAPE_POLYGON))) - { + && !measureTool.getMeasureShapeType().equals(MeasureTool.SHAPE_POLYGON))) { // Rubber band - Move control point and update shape Position lastPosition = rubberBandTarget.getPosition(); PickedObjectList pol = measureTool.getWwd().getObjectsAtCurrentPosition(); @@ -374,37 +329,33 @@ protected void doMoved(PositionEvent event) rubberBandTarget.setPosition(new Position(to.getPosition(), 0)); measureTool.moveControlPoint(rubberBandTarget); measureTool.firePropertyChange(MeasureTool.EVENT_POSITION_REPLACE, - lastPosition, rubberBandTarget.getPosition()); + lastPosition, rubberBandTarget.getPosition()); measureTool.getWwd().redraw(); - } - else - { + } else { // Free hand - Compute distance from current control point (rubber band target) Position lastPosition = rubberBandTarget.getPosition(); Position newPosition = measureTool.getWwd().getCurrentPosition(); double distance = LatLon.greatCircleDistance(lastPosition, newPosition).radians * measureTool.getWwd().getModel().getGlobe().getRadius(); - if (distance >= freeHandMinSpacing) - { + if (distance >= freeHandMinSpacing) { // Add new control point if (measureTool.addControlPoint() != null) // null when the cursor is off the globe { rubberBandTarget = (MeasureTool.ControlPoint) getMeasureTool().getControlPoints().get( - getMeasureTool().getControlPoints().size() - 1); + getMeasureTool().getControlPoints().size() - 1); } } } - } - else if (this.moving && movingTarget != null && measureTool.getWwd().getCurrentPosition() != null) - { + } else if (this.moving && movingTarget != null && measureTool.getWwd().getCurrentPosition() != null) { // Moving the whole shape Position lastPosition = movingTarget.getPosition(); Position newPosition = measureTool.getWwd().getCurrentPosition(); this.moveToPosition(lastPosition, newPosition); // Update the tool tip to follow the shape as it moves. - if (measureTool.isShowAnnotation()) + if (measureTool.isShowAnnotation()) { measureTool.updateAnnotation(movingTarget.getPosition()); + } measureTool.getWwd().redraw(); } @@ -412,153 +363,146 @@ else if (this.moving && movingTarget != null && measureTool.getWwd().getCurrentP /** * Move the shape to the specified new position + * * @param oldPosition Previous position of shape * @param newPosition New position for shape */ - protected void moveToPosition(Position oldPosition, Position newPosition) - { + protected void moveToPosition(Position oldPosition, Position newPosition) { Angle distanceAngle = LatLon.greatCircleDistance(oldPosition, newPosition); Angle azimuthAngle = LatLon.greatCircleAzimuth(oldPosition, newPosition); measureTool.moveMeasureShape(azimuthAngle, distanceAngle); measureTool.firePropertyChange(MeasureTool.EVENT_POSITION_REPLACE, oldPosition, newPosition); } - protected void doSelected(SelectEvent event) - { - if (this.movingTarget != null) + protected void doSelected(SelectEvent event) { + if (this.movingTarget != null) { return; + } - if (!event.getEventAction().equals(SelectEvent.DRAG) && !event.getEventAction().equals(SelectEvent.DRAG_END)) + if (!event.getEventAction().equals(SelectEvent.DRAG) && !event.getEventAction().equals(SelectEvent.DRAG_END)) { return; + } - if (event.getTopObject() == null || !(event.getTopObject() instanceof MeasureTool.ControlPoint) || - ((MeasureTool.ControlPoint) event.getTopObject()).getParent() != measureTool) + if (event.getTopObject() == null || !(event.getTopObject() instanceof MeasureTool.ControlPoint) + || ((MeasureTool.ControlPoint) event.getTopObject()).getParent() != measureTool) { return; + } // Have drag events drag the selected object. this.dragSelected(event); } - protected void dragSelected(SelectEvent event) - { - MeasureTool.ControlPoint point = (MeasureTool.ControlPoint)event.getTopObject(); + protected void dragSelected(SelectEvent event) { + MeasureTool.ControlPoint point = (MeasureTool.ControlPoint) event.getTopObject(); LatLon lastPosition = point.getPosition(); - if (point.getValue(MeasureTool.CONTROL_TYPE_LOCATION_INDEX) != null) - lastPosition = measureTool.getPositions().get((Integer)point.getValue(MeasureTool.CONTROL_TYPE_LOCATION_INDEX)); + if (point.getValue(MeasureTool.CONTROL_TYPE_LOCATION_INDEX) != null) { + lastPosition = measureTool.getPositions().get((Integer) point.getValue(MeasureTool.CONTROL_TYPE_LOCATION_INDEX)); + } // Delegate dragging computations to a dragger. this.dragger.selected(event); measureTool.moveControlPoint(point); - if (measureTool.isShowAnnotation()) + if (measureTool.isShowAnnotation()) { measureTool.updateAnnotation(point.getPosition()); + } measureTool.firePropertyChange(MeasureTool.EVENT_POSITION_REPLACE, lastPosition, point.getPosition()); measureTool.getWwd().redraw(); } - protected void highlight(Object o) - { + protected void highlight(Object o) { // Manage highlighting of control points - if (this.lastPickedObject == o) + if (this.lastPickedObject == o) { return; // Same thing selected - + } // Turn off highlight if on. - if (this.lastPickedObject != null) - { + if (this.lastPickedObject != null) { this.lastPickedObject.getAttributes().setHighlighted(false); this.lastPickedObject.getAttributes().setBackgroundColor(null); // use default this.lastPickedObject = null; - if (measureTool.isShowAnnotation()) + if (measureTool.isShowAnnotation()) { measureTool.updateAnnotation(null); + } this.setCursor(null); } // Turn on highlight if object selected is a control point and belongs to this controller's MeasureTool. - if (this.lastPickedObject == null && o instanceof MeasureTool.ControlPoint && - ((MeasureTool.ControlPoint) o).getParent() == measureTool) - { + if (this.lastPickedObject == null && o instanceof MeasureTool.ControlPoint + && ((MeasureTool.ControlPoint) o).getParent() == measureTool) { this.lastPickedObject = (MeasureTool.ControlPoint) o; this.lastPickedObject.getAttributes().setHighlighted(true); // Highlite using text color this.lastPickedObject.getAttributes().setBackgroundColor( this.lastPickedObject.getAttributes().getTextColor()); - if (measureTool.isShowAnnotation()) + if (measureTool.isShowAnnotation()) { measureTool.updateAnnotation(this.lastPickedObject.getPosition()); + } this.setCursor(this.lastPickedObject); } } - protected void setCursor(MeasureTool.ControlPoint controlPoint) - { + protected void setCursor(MeasureTool.ControlPoint controlPoint) { // TODO: handle 'rotating' mode cursor is this.isRotating() - when using Alt key on regular shapes - if (controlPoint == null) - { + if (controlPoint == null) { setComponentCursor(null); - } - else - { - if (this.measureTool.isRegularShape()) - { - if (this.measureTool.isCornerControl(controlPoint)) - { + } else { + if (this.measureTool.isRegularShape()) { + if (this.measureTool.isCornerControl(controlPoint)) { Angle azimuth = LatLon.greatCircleAzimuth(controlPoint.getPosition(), - this.measureTool.getCenterPosition()); + this.measureTool.getCenterPosition()); // Account for view heading in cursor selection azimuth = azimuth.subtract(this.measureTool.getWwd().getView().getHeading()); setComponentCursor(selectResizeCursor(azimuth)); - } - else if (this.measureTool.isCenterControl(controlPoint)) - { + } else if (this.measureTool.isCenterControl(controlPoint)) { setComponentCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } - } - else - { + } else { // Line, path and polygon setComponentCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } } } - protected Cursor selectResizeCursor(Angle azimuth) - { - while (azimuth.degrees < 0) + protected Cursor selectResizeCursor(Angle azimuth) { + while (azimuth.degrees < 0) { azimuth = azimuth.addDegrees(360); + } - if (azimuth.degrees < 22.5) + if (azimuth.degrees < 22.5) { return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); - else if (azimuth.degrees < 67.5) + } else if (azimuth.degrees < 67.5) { return Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR); - else if (azimuth.degrees < 112.5) + } else if (azimuth.degrees < 112.5) { return Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); - else if (azimuth.degrees < 157.5) + } else if (azimuth.degrees < 157.5) { return Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR); - else if (azimuth.degrees < 202.5) + } else if (azimuth.degrees < 202.5) { return Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR); - else if (azimuth.degrees < 247.5) + } else if (azimuth.degrees < 247.5) { return Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR); - else if (azimuth.degrees < 292.5) + } else if (azimuth.degrees < 292.5) { return Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); - else if (azimuth.degrees < 337.5) + } else if (azimuth.degrees < 337.5) { return Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR); - else // if (azimuth.degrees < 360) + } else // if (azimuth.degrees < 360) + { return Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); + } } - protected void setComponentCursor(Cursor cursor) - { + protected void setComponentCursor(Cursor cursor) { ((Component) this.measureTool.getWwd()).setCursor(cursor != null ? cursor : Cursor.getDefaultCursor()); } - - protected void autoDisarm() - { + protected void autoDisarm() { // Disarm after second control point of a line or regular shape - if (measureTool.isRegularShape() || measureTool.getMeasureShapeType().equals(MeasureTool.SHAPE_LINE)) - if (measureTool.getControlPoints().size() > 1) + if (measureTool.isRegularShape() || measureTool.getMeasureShapeType().equals(MeasureTool.SHAPE_LINE)) { + if (measureTool.getControlPoints().size() > 1) { this.setArmed(false); + } + } } } diff --git a/src/gov/nasa/worldwind/util/tree/Animation.java b/src/gov/nasa/worldwind/util/tree/Animation.java index aeda78abf1..35da667446 100644 --- a/src/gov/nasa/worldwind/util/tree/Animation.java +++ b/src/gov/nasa/worldwind/util/tree/Animation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; /** @@ -12,8 +11,8 @@ * @author pabercrombie * @version $Id: Animation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Animation -{ +public interface Animation { + /** * Reset the animation to the starting state. */ diff --git a/src/gov/nasa/worldwind/util/tree/BasicFrameAttributes.java b/src/gov/nasa/worldwind/util/tree/BasicFrameAttributes.java index f5c1efa4b6..4c870135b9 100644 --- a/src/gov/nasa/worldwind/util/tree/BasicFrameAttributes.java +++ b/src/gov/nasa/worldwind/util/tree/BasicFrameAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.util.Logging; @@ -16,8 +15,8 @@ * @author pabercrombie * @version $Id: BasicFrameAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicFrameAttributes implements FrameAttributes -{ +public class BasicFrameAttributes implements FrameAttributes { + protected double backgroundOpacity; protected Color frameColor1; protected Color frameColor2; @@ -42,8 +41,7 @@ public class BasicFrameAttributes implements FrameAttributes protected int cornerRadius; - public BasicFrameAttributes() - { + public BasicFrameAttributes() { this.backgroundOpacity = 0.8; this.frameColor1 = Color.WHITE; this.frameColor2 = new Color(0xC8D2DE); @@ -71,10 +69,8 @@ public BasicFrameAttributes() * * @param attributes Object to copy configuration from. */ - public BasicFrameAttributes(BasicFrameAttributes attributes) - { - if (attributes == null) - { + public BasicFrameAttributes(BasicFrameAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -83,17 +79,18 @@ public BasicFrameAttributes(BasicFrameAttributes attributes) this.copy(attributes); } - /** {@inheritDoc} */ - public Color getForegroundColor() - { + /** + * {@inheritDoc} + */ + public Color getForegroundColor() { return this.foregroundColor; } - /** {@inheritDoc} */ - public void setForegroundColor(Color textColor) - { - if (textColor == null) - { + /** + * {@inheritDoc} + */ + public void setForegroundColor(Color textColor) { + if (textColor == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -102,17 +99,18 @@ public void setForegroundColor(Color textColor) this.foregroundColor = textColor; } - /** {@inheritDoc} */ - public Font getFont() - { + /** + * {@inheritDoc} + */ + public Font getFont() { return this.font; } - /** {@inheritDoc} */ - public void setFont(Font font) - { - if (font == null) - { + /** + * {@inheritDoc} + */ + public void setFont(Font font) { + if (font == null) { String msg = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -121,17 +119,18 @@ public void setFont(Font font) this.font = font; } - /** {@inheritDoc} */ - public Color getTextColor() - { + /** + * {@inheritDoc} + */ + public Color getTextColor() { return textColor; } - /** {@inheritDoc} */ - public void setTextColor(Color textColor) - { - if (textColor == null) - { + /** + * {@inheritDoc} + */ + public void setTextColor(Color textColor) { + if (textColor == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -140,17 +139,18 @@ public void setTextColor(Color textColor) this.textColor = textColor; } - /** {@inheritDoc} */ - public Dimension getIconSize() - { + /** + * {@inheritDoc} + */ + public Dimension getIconSize() { return this.iconSize; } - /** {@inheritDoc} */ - public void setIconSize(Dimension iconSize) - { - if (iconSize == null) - { + /** + * {@inheritDoc} + */ + public void setIconSize(Dimension iconSize) { + if (iconSize == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -158,53 +158,60 @@ public void setIconSize(Dimension iconSize) this.iconSize = iconSize; } - /** {@inheritDoc} */ - public int getIconSpace() - { + /** + * {@inheritDoc} + */ + public int getIconSpace() { return this.iconSpace; } - /** {@inheritDoc} */ - public void setIconSpace(int iconSpace) - { + /** + * {@inheritDoc} + */ + public void setIconSpace(int iconSpace) { this.iconSpace = iconSpace; } - /** {@inheritDoc} */ - public double getForegroundOpacity() - { + /** + * {@inheritDoc} + */ + public double getForegroundOpacity() { return foregroundOpacity; } - /** {@inheritDoc} */ - public void setForegroundOpacity(double textOpacity) - { + /** + * {@inheritDoc} + */ + public void setForegroundOpacity(double textOpacity) { this.foregroundOpacity = textOpacity; } - /** {@inheritDoc} */ - public double getBackgroundOpacity() - { + /** + * {@inheritDoc} + */ + public double getBackgroundOpacity() { return this.backgroundOpacity; } - /** {@inheritDoc} */ - public void setBackgroundOpacity(double frameOpacity) - { + /** + * {@inheritDoc} + */ + public void setBackgroundOpacity(double frameOpacity) { this.backgroundOpacity = frameOpacity; } - /** {@inheritDoc} */ - public Color[] getBackgroundColor() - { - return new Color[] {this.frameColor1, this.frameColor2}; + /** + * {@inheritDoc} + */ + public Color[] getBackgroundColor() { + return new Color[]{this.frameColor1, this.frameColor2}; } - /** {@inheritDoc} */ - public void setTitleBarColor(Color color1, Color color2) - { - if (color1 == null || color2 == null) - { + /** + * {@inheritDoc} + */ + public void setTitleBarColor(Color color1, Color color2) { + if (color1 == null || color2 == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -214,23 +221,25 @@ public void setTitleBarColor(Color color1, Color color2) this.titleBarColor2 = color2; } - /** {@inheritDoc} */ - public Color[] getTitleBarColor() - { - return new Color[] {this.titleBarColor1, this.titleBarColor2}; + /** + * {@inheritDoc} + */ + public Color[] getTitleBarColor() { + return new Color[]{this.titleBarColor1, this.titleBarColor2}; } - /** {@inheritDoc} */ - public Color[] getScrollBarColor() - { - return new Color[] {this.scrollBarColor1, this.scrollBarColor2}; + /** + * {@inheritDoc} + */ + public Color[] getScrollBarColor() { + return new Color[]{this.scrollBarColor1, this.scrollBarColor2}; } - /** {@inheritDoc} */ - public void setScrollBarColor(Color color1, Color color2) - { - if (color1 == null || color2 == null) - { + /** + * {@inheritDoc} + */ + public void setScrollBarColor(Color color1, Color color2) { + if (color1 == null || color2 == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -240,17 +249,18 @@ public void setScrollBarColor(Color color1, Color color2) this.scrollBarColor2 = color2; } - /** {@inheritDoc} */ - public Color getMinimizeButtonColor() - { + /** + * {@inheritDoc} + */ + public Color getMinimizeButtonColor() { return minimizeButtonColor; } - /** {@inheritDoc} */ - public void setMinimizeButtonColor(Color minimizeButtonColor) - { - if (minimizeButtonColor == null) - { + /** + * {@inheritDoc} + */ + public void setMinimizeButtonColor(Color minimizeButtonColor) { + if (minimizeButtonColor == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -259,11 +269,11 @@ public void setMinimizeButtonColor(Color minimizeButtonColor) this.minimizeButtonColor = minimizeButtonColor; } - /** {@inheritDoc} */ - public void setBackgroundColor(Color frameColor1, Color frameColor2) - { - if (frameColor1 == null || frameColor2 == null) - { + /** + * {@inheritDoc} + */ + public void setBackgroundColor(Color frameColor1, Color frameColor2) { + if (frameColor1 == null || frameColor2 == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -273,29 +283,32 @@ public void setBackgroundColor(Color frameColor1, Color frameColor2) this.frameColor2 = frameColor2; } - /** {@inheritDoc} */ - public int getCornerRadius() - { + /** + * {@inheritDoc} + */ + public int getCornerRadius() { return this.cornerRadius; } - /** {@inheritDoc} */ - public void setCornerRadius(int cornerRadius) - { + /** + * {@inheritDoc} + */ + public void setCornerRadius(int cornerRadius) { this.cornerRadius = cornerRadius; } - /** {@inheritDoc} */ - public BasicFrameAttributes copy() - { + /** + * {@inheritDoc} + */ + public BasicFrameAttributes copy() { return new BasicFrameAttributes(this); } - /** {@inheritDoc} */ - public void copy(FrameAttributes attributes) - { - if (attributes != null) - { + /** + * {@inheritDoc} + */ + public void copy(FrameAttributes attributes) { + if (attributes != null) { this.backgroundOpacity = attributes.getBackgroundOpacity(); Color[] colorArray = attributes.getBackgroundColor(); this.frameColor1 = colorArray[0]; @@ -323,59 +336,74 @@ public void copy(FrameAttributes attributes) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } BasicFrameAttributes that = (BasicFrameAttributes) o; - if (this.backgroundOpacity != that.backgroundOpacity) + if (this.backgroundOpacity != that.backgroundOpacity) { return false; - if (this.frameColor1 != null ? !this.frameColor1.equals(that.frameColor1) : that.frameColor1 != null) + } + if (this.frameColor1 != null ? !this.frameColor1.equals(that.frameColor1) : that.frameColor1 != null) { return false; - if (this.frameColor2 != null ? !this.frameColor2.equals(that.frameColor2) : that.frameColor2 != null) + } + if (this.frameColor2 != null ? !this.frameColor2.equals(that.frameColor2) : that.frameColor2 != null) { return false; + } if (this.titleBarColor1 != null ? !this.titleBarColor1.equals(that.titleBarColor1) - : that.titleBarColor1 != null) + : that.titleBarColor1 != null) { return false; + } if (this.titleBarColor2 != null ? !this.titleBarColor2.equals(that.titleBarColor2) - : that.titleBarColor2 != null) + : that.titleBarColor2 != null) { return false; + } if (this.scrollBarColor1 != null ? !this.scrollBarColor1.equals(that.scrollBarColor1) - : that.scrollBarColor1 != null) + : that.scrollBarColor1 != null) { return false; + } if (this.scrollBarColor2 != null ? !this.scrollBarColor2.equals(that.scrollBarColor2) - : that.scrollBarColor2 != null) + : that.scrollBarColor2 != null) { return false; + } if (this.minimizeButtonColor != null ? !this.minimizeButtonColor.equals(that.minimizeButtonColor) - : that.minimizeButtonColor != null) + : that.minimizeButtonColor != null) { return false; - if (this.foregroundOpacity != that.foregroundOpacity) + } + if (this.foregroundOpacity != that.foregroundOpacity) { return false; + } if (this.foregroundColor != null ? !this.foregroundColor.equals(that.foregroundColor) - : that.foregroundColor != null) + : that.foregroundColor != null) { return false; - if (this.font != null ? !this.font.equals(that.font) : that.font != null) + } + if (this.font != null ? !this.font.equals(that.font) : that.font != null) { return false; - if (this.textColor != null ? !this.textColor.equals(that.textColor) : that.textColor != null) + } + if (this.textColor != null ? !this.textColor.equals(that.textColor) : that.textColor != null) { return false; - if (this.iconSpace != that.iconSpace) + } + if (this.iconSpace != that.iconSpace) { return false; - if (this.iconSize != null ? !this.iconSize.equals(that.iconSize) : that.iconSize != null) + } + if (this.iconSize != null ? !this.iconSize.equals(that.iconSize) : that.iconSize != null) { return false; + } //noinspection RedundantIfStatement - if (this.cornerRadius != that.cornerRadius) + if (this.cornerRadius != that.cornerRadius) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result = 12; // Arbitrary non-zero constant long temp; diff --git a/src/gov/nasa/worldwind/util/tree/BasicTree.java b/src/gov/nasa/worldwind/util/tree/BasicTree.java index ad50cf7bb6..e48903ca1a 100644 --- a/src/gov/nasa/worldwind/util/tree/BasicTree.java +++ b/src/gov/nasa/worldwind/util/tree/BasicTree.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.WWObjectImpl; @@ -19,160 +18,182 @@ * @author pabercrombie * @version $Id: BasicTree.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicTree extends WWObjectImpl implements Tree, PreRenderable -{ +public class BasicTree extends WWObjectImpl implements Tree, PreRenderable { + protected TreeLayout layout; protected TreeModel model; protected Set expandedNodes = new HashSet(); - /** Create an empty tree. */ - public BasicTree() - { + /** + * Create an empty tree. + */ + public BasicTree() { } - /** {@inheritDoc} */ - public void makeVisible(TreePath path) - { + /** + * {@inheritDoc} + */ + public void makeVisible(TreePath path) { TreeLayout layout = this.getLayout(); - if (layout != null) + if (layout != null) { layout.makeVisible(path); + } } - /** {@inheritDoc} */ - public void expandPath(TreePath path) - { + /** + * {@inheritDoc} + */ + public void expandPath(TreePath path) { this.expandedNodes.add(path); this.firePropertyChange(AVKey.TREE, null, this); } - /** {@inheritDoc} */ - public void collapsePath(TreePath path) - { + /** + * {@inheritDoc} + */ + public void collapsePath(TreePath path) { this.expandedNodes.remove(path); this.firePropertyChange(AVKey.TREE, null, this); } - /** {@inheritDoc} */ - public TreeNode getNode(TreePath path) - { + /** + * {@inheritDoc} + */ + public TreeNode getNode(TreePath path) { TreeNode node = this.getModel().getRoot(); if (!node.getText().equals(path.get(0))) // Test root node + { return null; + } Iterator iterator = path.iterator(); iterator.next(); // Skip root node, we already tested it above - while (iterator.hasNext()) - { + while (iterator.hasNext()) { String nodeText = iterator.next(); boolean foundMatch = false; - for (TreeNode child : node.getChildren()) - { - if (child.getText().equals(nodeText)) - { + for (TreeNode child : node.getChildren()) { + if (child.getText().equals(nodeText)) { node = child; foundMatch = true; break; } } - if (!foundMatch) + if (!foundMatch) { return null; + } } return node; } - /** {@inheritDoc} */ - public void togglePath(TreePath path) - { - if (this.isPathExpanded(path)) + /** + * {@inheritDoc} + */ + public void togglePath(TreePath path) { + if (this.isPathExpanded(path)) { this.collapsePath(path); - else + } else { this.expandPath(path); + } } - /** {@inheritDoc} */ - public boolean isPathExpanded(TreePath path) - { + /** + * {@inheritDoc} + */ + public boolean isPathExpanded(TreePath path) { return this.expandedNodes.contains(path); } - /** {@inheritDoc} */ - public boolean isNodeExpanded(TreeNode node) - { + /** + * {@inheritDoc} + */ + public boolean isNodeExpanded(TreeNode node) { return this.expandedNodes.contains(node.getPath()); } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { TreeLayout layout = this.getLayout(); - if (layout instanceof PreRenderable) - { + if (layout instanceof PreRenderable) { ((PreRenderable) layout).preRender(dc); } } - /** {@inheritDoc} */ - public void render(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { TreeLayout layout = this.getLayout(); - if (layout != null) - { - if (!dc.isOrderedRenderingMode()) + if (layout != null) { + if (!dc.isOrderedRenderingMode()) { dc.addOrderedRenderable(this); - else + } else { layout.render(dc); + } } } - /** {@inheritDoc} */ - public void pick(DrawContext dc, Point pickPoint) - { + /** + * {@inheritDoc} + */ + public void pick(DrawContext dc, Point pickPoint) { TreeLayout layout = this.getLayout(); - if (layout != null) + if (layout != null) { layout.render(dc); + } } - /** {@inheritDoc} */ - public double getDistanceFromEye() - { + /** + * {@inheritDoc} + */ + public double getDistanceFromEye() { return 1; } - /** {@inheritDoc} */ - public TreeLayout getLayout() - { + /** + * {@inheritDoc} + */ + public TreeLayout getLayout() { return layout; } - /** {@inheritDoc} */ - public void setLayout(TreeLayout layout) - { - if (this.layout != null) + /** + * {@inheritDoc} + */ + public void setLayout(TreeLayout layout) { + if (this.layout != null) { this.layout.removePropertyChangeListener(this); + } this.layout = layout; - if (this.layout != null) + if (this.layout != null) { this.layout.addPropertyChangeListener(this); + } } - /** {@inheritDoc} */ - public TreeModel getModel() - { + /** + * {@inheritDoc} + */ + public TreeModel getModel() { return model; } - /** {@inheritDoc} */ - public void setModel(TreeModel model) - { - if (this.model != null) + /** + * {@inheritDoc} + */ + public void setModel(TreeModel model) { + if (this.model != null) { this.model.removePropertyChangeListener(this); + } this.model = model; - if (this.model != null) + if (this.model != null) { this.model.addPropertyChangeListener(this); + } } } diff --git a/src/gov/nasa/worldwind/util/tree/BasicTreeAttributes.java b/src/gov/nasa/worldwind/util/tree/BasicTreeAttributes.java index d7808197b2..2668538bb9 100644 --- a/src/gov/nasa/worldwind/util/tree/BasicTreeAttributes.java +++ b/src/gov/nasa/worldwind/util/tree/BasicTreeAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.util.Logging; @@ -16,8 +15,8 @@ * @author pabercrombie * @version $Id: BasicTreeAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicTreeAttributes implements TreeAttributes -{ +public class BasicTreeAttributes implements TreeAttributes { + protected boolean rootVisible; protected Color textColor; @@ -31,8 +30,7 @@ public class BasicTreeAttributes implements TreeAttributes protected Dimension iconSize; protected int iconSpace; - public BasicTreeAttributes() - { + public BasicTreeAttributes() { this.rootVisible = true; this.textColor = Color.BLACK; this.font = Font.decode("Arial-BOLD-14"); @@ -51,10 +49,8 @@ public BasicTreeAttributes() * * @param attributes Object to copy configuration from. */ - public BasicTreeAttributes(TreeAttributes attributes) - { - if (attributes == null) - { + public BasicTreeAttributes(TreeAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -63,29 +59,32 @@ public BasicTreeAttributes(TreeAttributes attributes) this.copy(attributes); } - /** {@inheritDoc} */ - public boolean isRootVisible() - { + /** + * {@inheritDoc} + */ + public boolean isRootVisible() { return this.rootVisible; } - /** {@inheritDoc} */ - public void setRootVisible(boolean visible) - { + /** + * {@inheritDoc} + */ + public void setRootVisible(boolean visible) { this.rootVisible = visible; } - /** {@inheritDoc} */ - public Color getColor() - { + /** + * {@inheritDoc} + */ + public Color getColor() { return this.textColor; } - /** {@inheritDoc} */ - public void setColor(Color textColor) - { - if (textColor == null) - { + /** + * {@inheritDoc} + */ + public void setColor(Color textColor) { + if (textColor == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -94,23 +93,25 @@ public void setColor(Color textColor) this.textColor = textColor; } - /** {@inheritDoc} */ - public Font getFont() - { + /** + * {@inheritDoc} + */ + public Font getFont() { return this.font; } - /** {@inheritDoc} */ - public Font getDescriptionFont() - { + /** + * {@inheritDoc} + */ + public Font getDescriptionFont() { return this.descriptionFont; } - /** {@inheritDoc} */ - public void setDescriptionFont(Font font) - { - if (font == null) - { + /** + * {@inheritDoc} + */ + public void setDescriptionFont(Font font) { + if (font == null) { String msg = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -119,11 +120,11 @@ public void setDescriptionFont(Font font) this.descriptionFont = font; } - /** {@inheritDoc} */ - public void setFont(Font font) - { - if (font == null) - { + /** + * {@inheritDoc} + */ + public void setFont(Font font) { + if (font == null) { String msg = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -132,29 +133,32 @@ public void setFont(Font font) this.font = font; } - /** {@inheritDoc} */ - public int getRowSpacing() - { + /** + * {@inheritDoc} + */ + public int getRowSpacing() { return this.rowSpacing; } - /** {@inheritDoc} */ - public void setRowSpacing(int spacing) - { + /** + * {@inheritDoc} + */ + public void setRowSpacing(int spacing) { this.rowSpacing = spacing; } - /** {@inheritDoc} */ - public Dimension getIconSize() - { + /** + * {@inheritDoc} + */ + public Dimension getIconSize() { return this.iconSize; } - /** {@inheritDoc} */ - public void setIconSize(Dimension iconSize) - { - if (iconSize == null) - { + /** + * {@inheritDoc} + */ + public void setIconSize(Dimension iconSize) { + if (iconSize == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -162,29 +166,32 @@ public void setIconSize(Dimension iconSize) this.iconSize = iconSize; } - /** {@inheritDoc} */ - public int getIconSpace() - { + /** + * {@inheritDoc} + */ + public int getIconSpace() { return this.iconSpace; } - /** {@inheritDoc} */ - public void setIconSpace(int iconSpace) - { + /** + * {@inheritDoc} + */ + public void setIconSpace(int iconSpace) { this.iconSpace = iconSpace; } - /** {@inheritDoc} */ - public Color[] getCheckBoxColor() - { - return new Color[] {this.checkBoxColor1, this.checkBoxColor2}; + /** + * {@inheritDoc} + */ + public Color[] getCheckBoxColor() { + return new Color[]{this.checkBoxColor1, this.checkBoxColor2}; } - /** {@inheritDoc} */ - public void setCheckBoxColor(Color color1, Color color2) - { - if (color1 == null || color2 == null) - { + /** + * {@inheritDoc} + */ + public void setCheckBoxColor(Color color1, Color color2) { + if (color1 == null || color2 == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -194,17 +201,18 @@ public void setCheckBoxColor(Color color1, Color color2) this.checkBoxColor2 = color2; } - /** {@inheritDoc} */ - public BasicTreeAttributes copy() - { + /** + * {@inheritDoc} + */ + public BasicTreeAttributes copy() { return new BasicTreeAttributes(this); } - /** {@inheritDoc} */ - public void copy(TreeAttributes attributes) - { - if (attributes != null) - { + /** + * {@inheritDoc} + */ + public void copy(TreeAttributes attributes) { + if (attributes != null) { this.rootVisible = attributes.isRootVisible(); this.textColor = attributes.getColor(); this.font = attributes.getFont(); @@ -219,44 +227,53 @@ public void copy(TreeAttributes attributes) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } BasicTreeAttributes that = (BasicTreeAttributes) o; - if (this.rootVisible != that.rootVisible) + if (this.rootVisible != that.rootVisible) { return false; - if (this.textColor != null ? !this.textColor.equals(that.textColor) : that.textColor != null) + } + if (this.textColor != null ? !this.textColor.equals(that.textColor) : that.textColor != null) { return false; - if (this.font != null ? !this.font.equals(that.font) : that.font != null) + } + if (this.font != null ? !this.font.equals(that.font) : that.font != null) { return false; + } if (this.descriptionFont != null ? !this.descriptionFont.equals(that.descriptionFont) - : that.descriptionFont != null) + : that.descriptionFont != null) { return false; - if (this.rowSpacing != that.rowSpacing) + } + if (this.rowSpacing != that.rowSpacing) { return false; - if (!this.iconSize.equals(that.iconSize)) + } + if (!this.iconSize.equals(that.iconSize)) { return false; + } if (this.checkBoxColor1 != null ? !this.checkBoxColor1.equals(that.checkBoxColor1) - : that.checkBoxColor1 != null) + : that.checkBoxColor1 != null) { return false; + } if (this.checkBoxColor2 != null ? !this.checkBoxColor2.equals(that.checkBoxColor2) - : that.checkBoxColor2 != null) + : that.checkBoxColor2 != null) { return false; + } //noinspection RedundantIfStatement - if (this.iconSpace != that.iconSpace) + if (this.iconSpace != that.iconSpace) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; result = (this.rootVisible ? 1 : 0); diff --git a/src/gov/nasa/worldwind/util/tree/BasicTreeLayout.java b/src/gov/nasa/worldwind/util/tree/BasicTreeLayout.java index 91dbb3dce9..061efce2a9 100644 --- a/src/gov/nasa/worldwind/util/tree/BasicTreeLayout.java +++ b/src/gov/nasa/worldwind/util/tree/BasicTreeLayout.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import com.jogamp.opengl.util.texture.TextureCoords; @@ -27,50 +26,80 @@ * @author pabercrombie * @version $Id: BasicTreeLayout.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class BasicTreeLayout extends WWObjectImpl implements TreeLayout, Scrollable, PreRenderable -{ - /** Tree that is drawn by this layout. */ +public class BasicTreeLayout extends WWObjectImpl implements TreeLayout, Scrollable, PreRenderable { + + /** + * Tree that is drawn by this layout. + */ protected Tree tree; - /** Frame that contains the tree. */ + /** + * Frame that contains the tree. + */ protected ScrollFrame frame; - /** Attributes to use when the tree is not highlighted. */ + /** + * Attributes to use when the tree is not highlighted. + */ protected TreeAttributes normalAttributes = new BasicTreeAttributes(); - /** Attributes to use when the frame is highlighted. */ + /** + * Attributes to use when the frame is highlighted. + */ protected TreeAttributes highlightAttributes = new BasicTreeAttributes(); - /** Active attributes, either normal or highlight. */ + /** + * Active attributes, either normal or highlight. + */ protected TreeAttributes activeAttributes = new BasicTreeAttributes(); - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static final TreeAttributes defaultAttributes; - /** Indicates whether or not the tree is highlighted. */ + /** + * Indicates whether or not the tree is highlighted. + */ protected boolean highlighted; - /** Support for setting up and restoring picking state, and resolving the picked object. */ + /** + * Support for setting up and restoring picking state, and resolving the picked object. + */ protected PickSupport pickSupport = new PickSupport(); /** - * This field is set by {@link #makeVisible(TreePath)}, and read by {@link #scrollToNode(gov.nasa.worldwind.render.DrawContext)} - * during rendering. + * This field is set by {@link #makeVisible(TreePath)}, and read by + * {@link #scrollToNode(gov.nasa.worldwind.render.DrawContext)} during rendering. */ protected TreeNode scrollToNode; - /** Cache the rendered size of the tree and recompute when the tree changes. */ + /** + * Cache the rendered size of the tree and recompute when the tree changes. + */ protected Dimension size; - /** Indicates that the tree size needs to be computed. */ + /** + * Indicates that the tree size needs to be computed. + */ protected boolean mustRecomputeSize = true; - /** Indicates that the tree layout needs to be computed. */ + /** + * Indicates that the tree layout needs to be computed. + */ protected boolean mustRecomputeLayout = true; - /** Indicates that node description text must be drawn. */ + /** + * Indicates that node description text must be drawn. + */ protected boolean showDescription = true; - /** Indicates that a triangle must be drawn to indicate if a group node is expanded or collapsed. */ + /** + * Indicates that a triangle must be drawn to indicate if a group node is expanded or collapsed. + */ protected boolean drawNodeStateSymbol = true; - /** Indicates that a checkbox must be drawn for each node to indicate if the node is selected or not. */ + /** + * Indicates that a checkbox must be drawn for each node to indicate if the node is selected or not. + */ protected boolean drawSelectedSymbol = true; - /** Indicates whether or not the description text will be wrapped to fit the frame. */ + /** + * Indicates whether or not the description text will be wrapped to fit the frame. + */ protected boolean wrapText = true; /** * Maximum number of lines of wrapped description text to draw. If the description exceeds this it will be cut off @@ -78,13 +107,19 @@ public class BasicTreeLayout extends WWObjectImpl implements TreeLayout, Scrolla */ protected int maxWrappedLines = 2; - /** Cache of computed text bounds. */ + /** + * Cache of computed text bounds. + */ protected BoundedHashMap textCache = new BoundedHashMap(); - /** Cache of computed node layout data. */ + /** + * Cache of computed node layout data. + */ protected BoundedHashMap layoutCache = new BoundedHashMap(); - /** Cache of node layouts. This list is populated when the tree layout is computed. */ + /** + * Cache of node layouts. This list is populated when the tree layout is computed. + */ protected java.util.List treeNodes = new ArrayList(); /** @@ -96,26 +131,37 @@ public class BasicTreeLayout extends WWObjectImpl implements TreeLayout, Scrolla // Computed each frame protected long frameNumber = -1L; protected long attributesFrameNumber = -1L; - /** Location of the lower left corner of the tree, in GL coordinates. */ + /** + * Location of the lower left corner of the tree, in GL coordinates. + */ protected Point screenLocation; /** * Time at which the rendered tree last changed. Used to indicate when the ScrollFrame needs to refresh the rendered * representation */ protected long updateTime; - /** Frame size when the tree layout was last computed. */ + /** + * Frame size when the tree layout was last computed. + */ protected Dimension previousFrameSize; - /** Frame size when the tree size was last computed. */ + /** + * Frame size when the tree size was last computed. + */ protected Dimension previousSizeBounds; - /** The height of one line of text in the active font. */ + /** + * The height of one line of text in the active font. + */ protected int lineHeight; - /** Number of nodes in the tree, used to set a bound on the text cache. */ + /** + * Number of nodes in the tree, used to set a bound on the text cache. + */ protected int nodeCount; - /** Indentation in pixels applied to each new level of the tree. */ + /** + * Indentation in pixels applied to each new level of the tree. + */ protected int indent; - static - { + static { defaultAttributes = new BasicTreeAttributes(); } @@ -124,8 +170,7 @@ public class BasicTreeLayout extends WWObjectImpl implements TreeLayout, Scrolla * * @param tree Tree to create layout for. */ - public BasicTreeLayout(Tree tree) - { + public BasicTreeLayout(Tree tree) { this(tree, null); } @@ -133,23 +178,21 @@ public BasicTreeLayout(Tree tree) * Create a layout for a tree, at a screen location. * * @param tree Tree to create layout for. - * @param x X coordinate of the upper left corner of the tree frame. - * @param y Y coordinate of the upper left corner of the tree frame, measured from the top of the screen. + * @param x X coordinate of the upper left corner of the tree frame. + * @param y Y coordinate of the upper left corner of the tree frame, measured from the top of the screen. */ - public BasicTreeLayout(Tree tree, int x, int y) - { + public BasicTreeLayout(Tree tree, int x, int y) { this(tree, new Offset((double) x, (double) y, AVKey.PIXELS, AVKey.INSET_PIXELS)); } /** * Create a layout for a tree, at a screen location. * - * @param tree Tree to create layout for. + * @param tree Tree to create layout for. * @param screenLocation The location of the upper left corner of the tree frame. The offset is interpreted relative - * to the lower left corner of the screen. + * to the lower left corner of the screen. */ - public BasicTreeLayout(Tree tree, Offset screenLocation) - { + public BasicTreeLayout(Tree tree, Offset screenLocation) { this.tree = tree; this.frame = this.createFrame(); this.frame.setContents(this); @@ -162,22 +205,20 @@ public BasicTreeLayout(Tree tree, Offset screenLocation) // is a WWObject, it sends property change events to its listeners. Since Tree is likely to listen for property // change events on TreeLayout, we add an anonymous listener to avoid an infinite cycle of property change // events between TreeLayout and Tree. - this.tree.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { + this.tree.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { // Ignore events originated by this TreeLayout, and repaint events. There is no need to recompute the // tree layout just because a repaint was triggered. if (propertyChangeEvent.getSource() != BasicTreeLayout.this - && !AVKey.REPAINT.equals(propertyChangeEvent.getPropertyName())) - { + && !AVKey.REPAINT.equals(propertyChangeEvent.getPropertyName())) { BasicTreeLayout.this.invalidate(); } } }); - if (screenLocation != null) + if (screenLocation != null) { this.setScreenLocation(screenLocation); + } } /** @@ -186,8 +227,7 @@ public void propertyChange(PropertyChangeEvent propertyChangeEvent) * * @return {@code true} if the description will be wrapped to fit the frame. */ - public boolean isWrapText() - { + public boolean isWrapText() { return this.wrapText; } @@ -197,8 +237,7 @@ public boolean isWrapText() * * @param wrapText {@code true} if the description text must be wrapped to fit the frame. */ - public void setWrapText(boolean wrapText) - { + public void setWrapText(boolean wrapText) { this.wrapText = wrapText; } @@ -207,8 +246,7 @@ public void setWrapText(boolean wrapText) * * @return The size of the node state symbol. */ - protected Dimension getNodeStateSymbolSize() - { + protected Dimension getNodeStateSymbolSize() { return new Dimension(12, 12); } @@ -217,8 +255,7 @@ protected Dimension getNodeStateSymbolSize() * * @return The size of the node selection symbol. */ - protected Dimension getSelectedSymbolSize() - { + protected Dimension getSelectedSymbolSize() { return new Dimension(12, 12); } @@ -227,8 +264,7 @@ protected Dimension getSelectedSymbolSize() * * @return True if the renderer should renderer node descriptions. */ - public boolean isShowDescription() - { + public boolean isShowDescription() { return this.showDescription; } @@ -236,10 +272,9 @@ public boolean isShowDescription() * Set the renderer to renderer node descriptions (additional text rendered under the node title). * * @param showDescription True if the description should be rendered. False if only the icon and title should be - * rendered. + * rendered. */ - public void setShowDescription(boolean showDescription) - { + public void setShowDescription(boolean showDescription) { this.showDescription = showDescription; } @@ -248,8 +283,7 @@ public void setShowDescription(boolean showDescription) * * @return True if the node selected symbol (a checkbox by default) will be drawn. */ - public boolean isDrawSelectedSymbol() - { + public boolean isDrawSelectedSymbol() { return this.drawSelectedSymbol; } @@ -259,8 +293,7 @@ public boolean isDrawSelectedSymbol() * * @param drawSelectedSymbol True if the node selected symbol (a checkbox by default) will be drawn. */ - public void setDrawSelectedSymbol(boolean drawSelectedSymbol) - { + public void setDrawSelectedSymbol(boolean drawSelectedSymbol) { this.drawSelectedSymbol = drawSelectedSymbol; } @@ -268,11 +301,9 @@ public void setDrawSelectedSymbol(boolean drawSelectedSymbol) * Will the renderer draw a symbol to indicate that the node is expanded or collapsed (applies only to non-leaf * nodes). The default symbol is a triangle pointing to the right, for collapsed nodes, or down for expanded nodes. * - * @return True if the node state symbol (default is a triangle pointing either to the right or down) will be - * drawn. + * @return True if the node state symbol (default is a triangle pointing either to the right or down) will be drawn. */ - public boolean isDrawNodeStateSymbol() - { + public boolean isDrawNodeStateSymbol() { return this.drawNodeStateSymbol; } @@ -282,8 +313,7 @@ public boolean isDrawNodeStateSymbol() * * @return Maximum number of lines of description text that will be drawn. */ - public int getMaxWrappedLines() - { + public int getMaxWrappedLines() { return this.maxWrappedLines; } @@ -293,10 +323,8 @@ public int getMaxWrappedLines() * * @param maxLines Maximum number of lines of description text that will be drawn. */ - public void setMaxWrappedLines(int maxLines) - { - if (maxLines != this.maxWrappedLines) - { + public void setMaxWrappedLines(int maxLines) { + if (maxLines != this.maxWrappedLines) { this.maxWrappedLines = maxLines; // Need to re-wrap the text because the number of lines changes. @@ -311,16 +339,16 @@ public void setMaxWrappedLines(int maxLines) * expanded nodes. * * @param drawNodeStateSymbol True if the node state symbol (default is a triangle pointing either to the right or - * down) will be drawn. + * down) will be drawn. */ - public void setDrawNodeStateSymbol(boolean drawNodeStateSymbol) - { + public void setDrawNodeStateSymbol(boolean drawNodeStateSymbol) { this.drawNodeStateSymbol = drawNodeStateSymbol; } - /** {@inheritDoc} */ - public long getUpdateTime() - { + /** + * {@inheritDoc} + */ + public long getUpdateTime() { return this.updateTime; } @@ -329,26 +357,23 @@ public long getUpdateTime() * * @return A new frame. */ - protected ScrollFrame createFrame() - { + protected ScrollFrame createFrame() { return new ScrollFrame(); } /** * Get the size of the entire tree, including the part that is not visible in the scroll pane. * - * @param dc Draw context. + * @param dc Draw context. * @param frameSize Size of the frame the tree will be rendered into. May be {@code null}. * * @return Size of the rendered tree. */ - public Dimension getSize(DrawContext dc, Dimension frameSize) - { + public Dimension getSize(DrawContext dc, Dimension frameSize) { this.updateAttributes(dc); // Computing the size of rendered text is expensive, so only recompute the tree size when necessary. - if (this.mustRecomputeSize(frameSize)) - { + if (this.mustRecomputeSize(frameSize)) { TreeModel model = this.tree.getModel(); TreeNode root = model.getRoot(); @@ -376,21 +401,18 @@ public Dimension getSize(DrawContext dc, Dimension frameSize) * account which nodes are expanded and which are not. This computed size will be stored in the {@code size} * parameter. * - * @param tree Tree that contains the root node. - * @param root Root node of the subtree to find the size of. This does not need to be the root node of the - * tree. - * @param dc Draw context. + * @param tree Tree that contains the root node. + * @param root Root node of the subtree to find the size of. This does not need to be the root node of the tree. + * @param dc Draw context. * @param frameSize Size of the frame into which the tree will render. - * @param size Size object to modify. This method will change the width and height fields of {@code size} to - * hold the new size of the tree. - * @param x Horizontal coordinate of the start of this node. This parameter must be zero. This method calls - * itself recursively and changes the {@code x} parameter to reflect the indentation level of - * different levels of the tree. - * @param level Level of this node. Tree root node is level 1, children of the root are level 2, etc. + * @param size Size object to modify. This method will change the width and height fields of {@code size} to hold + * the new size of the tree. + * @param x Horizontal coordinate of the start of this node. This parameter must be zero. This method calls itself + * recursively and changes the {@code x} parameter to reflect the indentation level of different levels of the tree. + * @param level Level of this node. Tree root node is level 1, children of the root are level 2, etc. */ protected void computeSize(Tree tree, TreeNode root, DrawContext dc, Dimension frameSize, Dimension size, int x, - int level) - { + int level) { this.nodeCount++; TreeAttributes attributes = this.getActiveAttributes(); @@ -399,12 +421,12 @@ protected void computeSize(Tree tree, TreeNode root, DrawContext dc, Dimension f int indent = 0; - if (this.mustDisplayNode(root, level)) - { + if (this.mustDisplayNode(root, level)) { int thisWidth = thisSize.width + x; - if (thisWidth > size.width) + if (thisWidth > size.width) { size.width = thisWidth; + } size.height += thisSize.height; size.height += attributes.getRowSpacing(); @@ -412,26 +434,26 @@ protected void computeSize(Tree tree, TreeNode root, DrawContext dc, Dimension f indent = this.indent; } - if (tree.isNodeExpanded(root)) - { - for (TreeNode child : root.getChildren()) - { + if (tree.isNodeExpanded(root)) { + for (TreeNode child : root.getChildren()) { this.computeSize(tree, child, dc, frameSize, size, x + indent, level + 1); } } } - /** Force the layout to recompute the size of the tree. */ - public void invalidate() - { + /** + * Force the layout to recompute the size of the tree. + */ + public void invalidate() { this.markUpdated(); this.mustRecomputeSize = true; this.mustRecomputeLayout = true; } - /** Set the {@link #updateTime} to the current system time, marking the Scrollable contents as updated. */ - protected void markUpdated() - { + /** + * Set the {@link #updateTime} to the current system time, marking the Scrollable contents as updated. + */ + protected void markUpdated() { this.updateTime = System.currentTimeMillis(); } @@ -439,28 +461,29 @@ protected void markUpdated() * Determine if a node needs to be displayed. This method examines only one node at a time. It does not take into * account that the node's parent may be in the collapsed state, in which the children are not rendered. * - * @param node Node to test. + * @param node Node to test. * @param level Level of the node in the tree. The root node is level 1, its children are level 2, etc. * * @return True if the node must be displayed. */ - protected boolean mustDisplayNode(TreeNode node, int level) - { + protected boolean mustDisplayNode(TreeNode node, int level) { return node.isVisible() && (level > 1 || this.getActiveAttributes().isRootVisible()); } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { // Adjust scroll position if an application has requested that the layout scroll to make a node visible. this.scrollToNode(dc); this.frame.preRender(dc); } - /** {@inheritDoc} */ - public void render(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { this.frame.render(dc); } @@ -470,17 +493,15 @@ public void render(DrawContext dc) * * @param dc Draw context. */ - protected synchronized void scrollToNode(DrawContext dc) - { - if (this.scrollToNode != null) - { + protected synchronized void scrollToNode(DrawContext dc) { + if (this.scrollToNode != null) { // Update the frame bounds to make sure that the frame's scroll model includes the full extent of the tree ScrollFrame frame = this.getFrame(); frame.updateBounds(dc); Point drawPoint = new Point(0, 0); Rectangle bounds = this.findNodeBounds(this.scrollToNode, this.tree.getModel().getRoot(), dc, - frame.getBounds(dc).getSize(), drawPoint, 1); + frame.getBounds(dc).getSize(), drawPoint, 1); // Calculate a scroll position that will bring the node to the top of the visible area. Subtract the row spacing // to avoid clipping off the top of the node. @@ -491,19 +512,18 @@ protected synchronized void scrollToNode(DrawContext dc) } } - /** {@inheritDoc} */ - public void renderScrollable(DrawContext dc, Point location, Dimension frameSize, Rectangle clipBounds) - { + /** + * {@inheritDoc} + */ + public void renderScrollable(DrawContext dc, Point location, Dimension frameSize, Rectangle clipBounds) { TreeModel model = this.tree.getModel(); TreeNode root = model.getRoot(); this.screenLocation = location; this.updateAttributes(dc); - if (this.frameNumber != dc.getFrameTimeStamp()) - { - if (this.mustRecomputeTreeLayout(frameSize)) - { + if (this.frameNumber != dc.getFrameTimeStamp()) { + if (this.mustRecomputeTreeLayout(frameSize)) { this.treeNodes.clear(); Point drawPoint = new Point(0, this.size.height); @@ -516,20 +536,15 @@ public void renderScrollable(DrawContext dc, Point location, Dimension frameSize this.frameNumber = dc.getFrameTimeStamp(); } - try - { - if (dc.isPickingMode()) - { + try { + if (dc.isPickingMode()) { this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); } this.renderNodes(dc, location, treeNodes, clipBounds); - } - finally - { - if (dc.isPickingMode()) - { + } finally { + if (dc.isPickingMode()) { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, dc.getPickPoint(), dc.getCurrentLayer()); } @@ -543,10 +558,9 @@ public void renderScrollable(DrawContext dc, Point location, Dimension frameSize * * @return {@code true} if the layout needs to be recomputed, otherwise {@code false}. */ - protected boolean mustRecomputeTreeLayout(Dimension frameSize) - { + protected boolean mustRecomputeTreeLayout(Dimension frameSize) { return this.mustRecomputeLayout || this.previousFrameSize == null - || this.previousFrameSize.width != frameSize.width; + || this.previousFrameSize.width != frameSize.width; } /** @@ -556,11 +570,10 @@ protected boolean mustRecomputeTreeLayout(Dimension frameSize) * * @return {@code true} if the size needs to be recomputed, otherwise {@code false}. */ - protected boolean mustRecomputeSize(Dimension frameSize) - { + protected boolean mustRecomputeSize(Dimension frameSize) { return this.mustRecomputeSize - || (this.previousSizeBounds == null && frameSize != null) - || (frameSize != null && this.previousSizeBounds.width != frameSize.width); + || (this.previousSizeBounds == null && frameSize != null) + || (frameSize != null && this.previousSizeBounds.width != frameSize.width); } /** @@ -570,10 +583,8 @@ protected boolean mustRecomputeSize(Dimension frameSize) * * @param dc Current draw context. */ - protected void updateAttributes(DrawContext dc) - { - if (dc.getFrameTimeStamp() != this.attributesFrameNumber) - { + protected void updateAttributes(DrawContext dc) { + if (dc.getFrameTimeStamp() != this.attributesFrameNumber) { this.determineActiveAttributes(); this.indent = this.computeIndentation(); this.lineHeight = this.computeMaxTextHeight(dc); @@ -587,8 +598,7 @@ protected void updateAttributes(DrawContext dc) * * @return indention (in pixels) to apply to each new level in the tree. */ - protected int computeIndentation() - { + protected int computeIndentation() { int iconWidth = this.getActiveAttributes().getIconSize().width; int iconSpacing = this.getActiveAttributes().getIconSpace(); int checkboxWidth = this.getSelectedSymbolSize().width; @@ -604,8 +614,7 @@ protected int computeIndentation() * * @return The maximum height of a line of text. */ - protected int computeMaxTextHeight(DrawContext dc) - { + protected int computeMaxTextHeight(DrawContext dc) { TreeAttributes attributes = this.getActiveAttributes(); // Use underscore + capital E with acute accent as max height @@ -618,24 +627,23 @@ protected int computeMaxTextHeight(DrawContext dc) /** * Render a list of tree nodes. * - * @param dc Current draw context. - * @param drawPoint Point in GL coordinates (origin bottom left corner of the screen) that locates the bottom left - * corner of the tree. - * @param nodes Nodes to draw. + * @param dc Current draw context. + * @param drawPoint Point in GL coordinates (origin bottom left corner of the screen) that locates the bottom left + * corner of the tree. + * @param nodes Nodes to draw. * @param clipBounds Pixels outside of this rectangle will be discarded. Any nodes that do not intersect this - * rectangle will not be drawn. + * rectangle will not be drawn. */ - protected void renderNodes(DrawContext dc, Point drawPoint, Iterable nodes, Rectangle clipBounds) - { + protected void renderNodes(DrawContext dc, Point drawPoint, Iterable nodes, Rectangle clipBounds) { // Collect the nodes that are actually visible in the scroll area in a list. List visibleNodes = new ArrayList(); - for (NodeLayout layout : nodes) - { + for (NodeLayout layout : nodes) { layout.reset(drawPoint); - if (this.intersectsFrustum(dc, layout, clipBounds)) + if (this.intersectsFrustum(dc, layout, clipBounds)) { visibleNodes.add(layout); + } // // Draw a box around the node bounds. Useful for debugging node layout // @@ -648,25 +656,25 @@ protected void renderNodes(DrawContext dc, Point drawPoint, Iterable // gl.glEnd(); } - if (this.isDrawNodeStateSymbol()) + if (this.isDrawNodeStateSymbol()) { this.drawTriangles(dc, visibleNodes); + } - if (this.isDrawSelectedSymbol()) + if (this.isDrawSelectedSymbol()) { this.drawCheckboxes(dc, visibleNodes); + } // If not picking, draw text and icons. Otherwise just draw pickable rectangles tagged with the node. Unlike // the toggle and select controls, selecting the node does not mean anything to the tree, but it may mean // something to an application controller. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { this.drawIcons(dc, visibleNodes); this.drawText(dc, visibleNodes); - if (this.isShowDescription()) + if (this.isShowDescription()) { this.drawDescriptionText(dc, visibleNodes); - } - else - { + } + } else { this.pickTextAndIcon(dc, visibleNodes); } } @@ -674,17 +682,17 @@ protected void renderNodes(DrawContext dc, Point drawPoint, Iterable /** * Determines whether a node intersects the view frustum. * - * @param dc the current draw context. - * @param layout node to test intersection of. + * @param dc the current draw context. + * @param layout node to test intersection of. * @param scrollBounds bounds of the area currently visible in the scroll frame. * * @return {@code true} If the frame intersects the frustum, otherwise {@code false}. */ - protected boolean intersectsFrustum(DrawContext dc, NodeLayout layout, Rectangle scrollBounds) - { + protected boolean intersectsFrustum(DrawContext dc, NodeLayout layout, Rectangle scrollBounds) { //noinspection SimplifiableIfStatement - if (!scrollBounds.intersects(layout.screenBounds)) + if (!scrollBounds.intersects(layout.screenBounds)) { return false; + } return !dc.isPickingMode() || dc.getPickFrustums().intersectsAny(layout.pickScreenBounds); } @@ -692,19 +700,16 @@ protected boolean intersectsFrustum(DrawContext dc, NodeLayout layout, Rectangle /** * Draw pick rectangles over the icon and text areas the visible nodes. * - * @param dc Current draw context. + * @param dc Current draw context. * @param nodes Visible nodes. */ - protected void pickTextAndIcon(DrawContext dc, Iterable nodes) - { + protected void pickTextAndIcon(DrawContext dc, Iterable nodes) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { gl.glBegin(GL2.GL_QUADS); - for (NodeLayout layout : nodes) - { + for (NodeLayout layout : nodes) { Color color = dc.getUniquePickColor(); PickedObject pickedObject = new PickedObject(color.getRGB(), layout.node); pickedObject.setValue(AVKey.HOT_SPOT, this.getFrame()); @@ -721,9 +726,7 @@ protected void pickTextAndIcon(DrawContext dc, Iterable nodes) gl.glVertex2f(maxX, minY); gl.glVertex2f(minX, minY); } - } - finally - { + } finally { gl.glEnd(); // Quads } } @@ -731,11 +734,10 @@ protected void pickTextAndIcon(DrawContext dc, Iterable nodes) /** * Draw the main line of text for a list of tree nodes. * - * @param dc Current draw context. + * @param dc Current draw context. * @param nodes List of visible nodes. */ - protected void drawText(DrawContext dc, Iterable nodes) - { + protected void drawText(DrawContext dc, Iterable nodes) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. TreeAttributes attributes = this.getActiveAttributes(); @@ -743,17 +745,15 @@ protected void drawText(DrawContext dc, Iterable nodes) float[] colorRGB = color.getRGBColorComponents(null); TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - attributes.getFont(), true, false, false); + attributes.getFont(), true, false, false); gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL); - try - { + try { textRenderer.begin3DRendering(); textRenderer.setColor(colorRGB[0], colorRGB[1], colorRGB[2], 1); - for (NodeLayout layout : nodes) - { + for (NodeLayout layout : nodes) { String text = this.getText(layout.node); Rectangle2D textBounds = this.getTextBounds(dc, text, attributes.getFont()); @@ -764,9 +764,7 @@ protected void drawText(DrawContext dc, Iterable nodes) textRenderer.draw(text, layout.drawPoint.x, layout.drawPoint.y + vertAdjust); } - } - finally - { + } finally { textRenderer.end3DRendering(); } } @@ -774,40 +772,34 @@ protected void drawText(DrawContext dc, Iterable nodes) /** * Draw the description text for tree nodes. The description text is drawn under the main line of text. * - * @param dc Current draw context. + * @param dc Current draw context. * @param nodes List of visible nodes. */ - protected void drawDescriptionText(DrawContext dc, Iterable nodes) - { + protected void drawDescriptionText(DrawContext dc, Iterable nodes) { TreeAttributes attributes = this.getActiveAttributes(); Color color = attributes.getColor(); float[] colorRGB = color.getRGBColorComponents(null); TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - attributes.getDescriptionFont(), true, false, false); + attributes.getDescriptionFont(), true, false, false); MultiLineTextRenderer mltr = new MultiLineTextRenderer(textRenderer); - try - { + try { textRenderer.begin3DRendering(); textRenderer.setColor(colorRGB[0], colorRGB[1], colorRGB[2], 1); - for (NodeLayout layout : nodes) - { + for (NodeLayout layout : nodes) { String description = layout.node.getDescription(); - if (description != null) - { + if (description != null) { String wrappedText = this.computeWrappedText(dc, layout.node, attributes.getDescriptionFont(), - (int) (layout.screenBounds.getMaxX() - layout.drawPoint.x)); + (int) (layout.screenBounds.getMaxX() - layout.drawPoint.x)); int vertAdjust = layout.bounds.height - this.lineHeight; mltr.draw(wrappedText, layout.drawPoint.x, layout.drawPoint.y + vertAdjust); } } - } - finally - { + } finally { textRenderer.end3DRendering(); } } @@ -815,15 +807,13 @@ protected void drawDescriptionText(DrawContext dc, Iterable nodes) /** * Draw icons for a tree nodes. * - * @param dc Current draw context. + * @param dc Current draw context. * @param nodes List of visible nodes. */ - protected void drawIcons(DrawContext dc, Iterable nodes) - { + protected void drawIcons(DrawContext dc, Iterable nodes) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL); gl.glEnable(GL.GL_TEXTURE_2D); @@ -834,57 +824,48 @@ protected void drawIcons(DrawContext dc, Iterable nodes) WWTexture activeTexture = null; - for (NodeLayout layout : nodes) - { + for (NodeLayout layout : nodes) { WWTexture texture = layout.node.getTexture(); - if (texture == null) + if (texture == null) { continue; + } // Check to see if this node's icon is the same as the previous node. If so, there's no need to rebind // the texture. boolean textureBound; // noinspection SimplifiableIfStatement - if ((activeTexture != null) && (texture.getImageSource() == activeTexture.getImageSource())) - { + if ((activeTexture != null) && (texture.getImageSource() == activeTexture.getImageSource())) { textureBound = true; - } - else - { + } else { textureBound = texture.bind(dc); - if (textureBound) + if (textureBound) { activeTexture = texture; + } } - if (textureBound) - { + if (textureBound) { // If the total node height is greater than the image height, vertically center the image int vertAdjustment = 0; - if (iconSize.height < layout.bounds.height) - { + if (iconSize.height < layout.bounds.height) { vertAdjustment = layout.bounds.height - iconSize.height - - (this.lineHeight - iconSize.height) / 2; + - (this.lineHeight - iconSize.height) / 2; } - try - { + try { gl.glPushMatrix(); TextureCoords texCoords = activeTexture.getTexCoords(); gl.glTranslated(layout.drawPoint.x, layout.drawPoint.y + vertAdjustment, 1.0); gl.glScaled((double) iconSize.width, (double) iconSize.width, 1d); dc.drawUnitQuad(texCoords); - } - finally - { + } finally { gl.glPopMatrix(); } layout.drawPoint.x += attributes.getIconSize().width + attributes.getIconSpace(); } } - } - finally - { + } finally { gl.glDisable(GL.GL_TEXTURE_2D); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); } @@ -894,11 +875,10 @@ protected void drawIcons(DrawContext dc, Iterable nodes) * Draw check boxes. Each box includes a check mark is the node is selected, or is filled with a gradient if the * node is partially selected. * - * @param dc Current draw context. + * @param dc Current draw context. * @param nodes List of visible nodes. */ - protected void drawCheckboxes(DrawContext dc, Iterable nodes) - { + protected void drawCheckboxes(DrawContext dc, Iterable nodes) { // The check boxes are drawn in three passes: // 1) Draw filled background for partially selected nodes // 2) Draw check marks for selected nodes @@ -908,56 +888,44 @@ protected void drawCheckboxes(DrawContext dc, Iterable nodes) Dimension symbolSize; - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { this.drawFilledCheckboxes(dc, nodes); // Draw filled boxes for partially selected nodes this.drawCheckmarks(dc, nodes); // Draw check marks for selected nodes symbolSize = this.getSelectedSymbolSize(); - } - else - { + } else { // Make the pickable area of the checkbox a little bigger than the actual box so that it is easier to hit. symbolSize = new Dimension(this.getSelectedSymbolSize().width + this.getActiveAttributes().getIconSpace(), - this.lineHeight + this.getActiveAttributes().getRowSpacing()); + this.lineHeight + this.getActiveAttributes().getRowSpacing()); } // In picking mode all of the boxes can be drawn as filled quads. Otherwise, each box is drawn as a // separate line loop - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glBegin(GL2.GL_QUADS); } - try - { - for (NodeLayout layout : nodes) - { + try { + for (NodeLayout layout : nodes) { int vertAdjust = layout.bounds.height - symbolSize.height - - (this.lineHeight - symbolSize.height) / 2; + - (this.lineHeight - symbolSize.height) / 2; int x = layout.drawPoint.x; int y = layout.drawPoint.y + vertAdjust; int width = symbolSize.width; - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Draw a hollow box uses a line loop gl.glBegin(GL2.GL_LINE_LOOP); - try - { + try { gl.glVertex2f(x + width, y + symbolSize.height + 0.5f); gl.glVertex2f(x, y + symbolSize.height + 0.5f); gl.glVertex2f(x, y); gl.glVertex2f(x + width, y + 0.5f); - } - finally - { + } finally { gl.glEnd(); } - } - // Otherwise draw a filled quad - else - { + } // Otherwise draw a filled quad + else { Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); this.pickSupport.addPickableObject(colorCode, this.createSelectControl(layout.node)); @@ -965,8 +933,7 @@ protected void drawCheckboxes(DrawContext dc, Iterable nodes) // If the node does not have a triangle to the left of the checkbox, make the checkbox pickable // area stretch all the way to the frame on the left hand side, since this is otherwise dead space. - if (layout.node.isLeaf() || !this.isDrawNodeStateSymbol()) - { + if (layout.node.isLeaf() || !this.isDrawNodeStateSymbol()) { width = x - this.screenLocation.x + symbolSize.width; x = this.screenLocation.x; } @@ -979,11 +946,8 @@ protected void drawCheckboxes(DrawContext dc, Iterable nodes) layout.drawPoint.x += symbolSize.width + this.getActiveAttributes().getIconSpace(); } - } - finally - { - if (dc.isPickingMode()) - { + } finally { + if (dc.isPickingMode()) { gl.glEnd(); // Quads } } @@ -992,11 +956,10 @@ protected void drawCheckboxes(DrawContext dc, Iterable nodes) /** * Draw squares filled with a gradient for partially selected checkboxes. * - * @param dc Current draw context. + * @param dc Current draw context. * @param nodes List of visible nodes. */ - protected void drawFilledCheckboxes(DrawContext dc, Iterable nodes) - { + protected void drawFilledCheckboxes(DrawContext dc, Iterable nodes) { Dimension selectedSymbolSize = this.getSelectedSymbolSize(); TreeAttributes attributes = this.getActiveAttributes(); @@ -1004,17 +967,15 @@ protected void drawFilledCheckboxes(DrawContext dc, Iterable nodes) Color[] colors = attributes.getCheckBoxColor(); - try - { + try { gl.glLineWidth(1f); gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL); // Fill box with a diagonal gradient gl.glBegin(GL2.GL_QUADS); - for (NodeLayout layout : nodes) - { + for (NodeLayout layout : nodes) { int vertAdjust = layout.bounds.height - selectedSymbolSize.height - - (this.lineHeight - selectedSymbolSize.height) / 2; + - (this.lineHeight - selectedSymbolSize.height) / 2; int x = layout.drawPoint.x; int y = layout.drawPoint.y + vertAdjust; @@ -1022,8 +983,7 @@ protected void drawFilledCheckboxes(DrawContext dc, Iterable nodes) String selected = layout.node.isTreeSelected(); boolean filled = TreeNode.PARTIALLY_SELECTED.equals(selected); - if (filled) - { + if (filled) { OGLUtil.applyColor(gl, colors[0], 1, false); gl.glVertex2f(x + selectedSymbolSize.width, y + selectedSymbolSize.height); gl.glVertex2f(x, y + selectedSymbolSize.height); @@ -1033,9 +993,7 @@ protected void drawFilledCheckboxes(DrawContext dc, Iterable nodes) gl.glVertex2f(x + selectedSymbolSize.width, y); } } - } - finally - { + } finally { gl.glEnd(); // Quads } } @@ -1043,11 +1001,10 @@ protected void drawFilledCheckboxes(DrawContext dc, Iterable nodes) /** * Draw checkmark symbols in the selected checkboxes. * - * @param dc Current draw context. + * @param dc Current draw context. * @param nodes List of visible nodes. */ - protected void drawCheckmarks(DrawContext dc, Iterable nodes) - { + protected void drawCheckmarks(DrawContext dc, Iterable nodes) { Dimension selectedSymbolSize = this.getSelectedSymbolSize(); TreeAttributes attributes = this.getActiveAttributes(); @@ -1057,20 +1014,17 @@ protected void drawCheckmarks(DrawContext dc, Iterable nodes) // Draw checkmarks for selected nodes OGLUtil.applyColor(gl, color, 1, false); - try - { + try { gl.glEnable(GL.GL_LINE_SMOOTH); gl.glBegin(GL2.GL_LINES); - for (NodeLayout layout : nodes) - { + for (NodeLayout layout : nodes) { int vertAdjust = layout.bounds.height - selectedSymbolSize.height - - (this.lineHeight - selectedSymbolSize.height) / 2; + - (this.lineHeight - selectedSymbolSize.height) / 2; String selected = layout.node.isTreeSelected(); boolean checked = TreeNode.SELECTED.equals(selected); - if (checked) - { + if (checked) { int x = layout.drawPoint.x; int y = layout.drawPoint.y + vertAdjust; @@ -1081,9 +1035,7 @@ protected void drawCheckmarks(DrawContext dc, Iterable nodes) gl.glVertex2f(x + selectedSymbolSize.width * 0.8f - 1, y + selectedSymbolSize.height * 0.8f); } } - } - finally - { + } finally { gl.glEnd(); // Lines gl.glDisable(GL.GL_LINE_SMOOTH); } @@ -1092,11 +1044,10 @@ protected void drawCheckmarks(DrawContext dc, Iterable nodes) /** * Draw triangles to indicate that the nodes are expanded or collapsed. * - * @param dc Current draw context. + * @param dc Current draw context. * @param nodes Visible nodes. */ - protected void drawTriangles(DrawContext dc, Iterable nodes) - { + protected void drawTriangles(DrawContext dc, Iterable nodes) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Dimension symbolSize = this.getNodeStateSymbolSize(); @@ -1107,8 +1058,7 @@ protected void drawTriangles(DrawContext dc, Iterable nodes) int iconSpace = this.getActiveAttributes().getIconSpace(); int pickWidth = symbolSize.width + iconSpace; - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { TreeAttributes attributes = this.getActiveAttributes(); Color color = attributes.getColor(); @@ -1118,30 +1068,23 @@ protected void drawTriangles(DrawContext dc, Iterable nodes) OGLUtil.applyColor(gl, color, 1, false); gl.glBegin(GL2.GL_TRIANGLES); - } - else - { + } else { gl.glBegin(GL2.GL_QUADS); // Draw pick areas as rectangles, not triangles } - try - { - for (NodeLayout layout : nodes) - { + try { + for (NodeLayout layout : nodes) { // If the node is not a leaf, draw a symbol to indicate if it is expanded or collapsed - if (!layout.node.isLeaf()) - { + if (!layout.node.isLeaf()) { int x = layout.drawPoint.x; int y = layout.drawPoint.y; - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { x += halfWidth; y += halfHeight; - if (this.tree.isNodeExpanded(layout.node)) - { + if (this.tree.isNodeExpanded(layout.node)) { int vertAdjust = layout.bounds.height - halfWidth - (this.lineHeight - halfWidth) / 2; y += vertAdjust; @@ -1149,11 +1092,9 @@ protected void drawTriangles(DrawContext dc, Iterable nodes) gl.glVertex2i(x - halfHeight, y); gl.glVertex2i(x, -halfWidth + y); gl.glVertex2i(x + halfHeight, y); - } - else - { + } else { int vertAdjust = layout.bounds.height - symbolSize.height - - (this.lineHeight - symbolSize.height) / 2; + - (this.lineHeight - symbolSize.height) / 2; y += vertAdjust; // Draw triangle pointing right @@ -1161,13 +1102,11 @@ protected void drawTriangles(DrawContext dc, Iterable nodes) gl.glVertex2f(x + halfWidth, y); gl.glVertex2f(x, halfHeight + y - 0.5f); } - } - else - { + } else { Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); this.pickSupport.addPickableObject(colorCode, - this.createTogglePathControl(this.tree, layout.node)); + this.createTogglePathControl(this.tree, layout.node)); gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()); x = this.screenLocation.x; @@ -1181,13 +1120,12 @@ protected void drawTriangles(DrawContext dc, Iterable nodes) } } - if (this.isDrawNodeStateSymbol()) + if (this.isDrawNodeStateSymbol()) { layout.drawPoint.x += this.getNodeStateSymbolSize().width - + this.getActiveAttributes().getIconSpace(); + + this.getActiveAttributes().getIconSpace(); + } } - } - finally - { + } finally { gl.glEnd(); // Triangles if drawing, quads if picking } } @@ -1195,24 +1133,21 @@ protected void drawTriangles(DrawContext dc, Iterable nodes) /** * Determine the tree layout. This method determines which nodes are visible, and where they will be drawn. * - * @param root Root node of the subtree to render. - * @param dc Draw context. + * @param root Root node of the subtree to render. + * @param dc Draw context. * @param frameSize Size of the frame into which the tree will render. - * @param location Location at which to draw the node. The location specifies the upper left corner of the - * subtree. - * @param level The level of this node in the tree. The root node is at level 1, its child nodes are at level 2, - * etc. - * @param nodes List to collect nodes that are currently visible. This method adds nodes to this list. + * @param location Location at which to draw the node. The location specifies the upper left corner of the subtree. + * @param level The level of this node in the tree. The root node is at level 1, its child nodes are at level 2, + * etc. + * @param nodes List to collect nodes that are currently visible. This method adds nodes to this list. */ protected void computeTreeLayout(TreeNode root, DrawContext dc, Dimension frameSize, Point location, int level, - java.util.List nodes) - { + java.util.List nodes) { TreeAttributes attributes = this.getActiveAttributes(); int oldX = location.x; - if (this.mustDisplayNode(root, level)) - { + if (this.mustDisplayNode(root, level)) { Dimension size = this.getNodeSize(dc, frameSize, location.x, root, attributes); // Adjust y to the bottom of the node area @@ -1220,8 +1155,9 @@ protected void computeTreeLayout(TreeNode root, DrawContext dc, Dimension frameS Rectangle nodeBounds = new Rectangle(location.x, y, size.width, size.height); NodeLayout layout = this.layoutCache.get(root); - if (layout == null) + if (layout == null) { layout = new NodeLayout(root); + } layout.bounds = nodeBounds; @@ -1229,7 +1165,7 @@ protected void computeTreeLayout(TreeNode root, DrawContext dc, Dimension frameS // width of the frame. int rowSpacing = attributes.getRowSpacing(); layout.pickBounds = new Rectangle(0, nodeBounds.y - rowSpacing, frameSize.width, - nodeBounds.height + rowSpacing * 2); + nodeBounds.height + rowSpacing * 2); nodes.add(layout); @@ -1238,10 +1174,8 @@ protected void computeTreeLayout(TreeNode root, DrawContext dc, Dimension frameS } // Draw child nodes if the root node is expanded. - if (this.tree.isNodeExpanded(root)) - { - for (TreeNode child : root.getChildren()) - { + if (this.tree.isNodeExpanded(root)) { + for (TreeNode child : root.getChildren()) { this.computeTreeLayout(child, dc, frameSize, location, level + 1, nodes); } } @@ -1251,25 +1185,23 @@ protected void computeTreeLayout(TreeNode root, DrawContext dc, Dimension frameS /** * Find the bounds of a node in the tree. * - * @param needle The node to find. - * @param haystack Root node of the subtree to search. - * @param dc Draw context. + * @param needle The node to find. + * @param haystack Root node of the subtree to search. + * @param dc Draw context. * @param frameSize Size of the frame into which the tree is rendered. - * @param location Point in OpenGL screen coordinates (origin lower left corner) that defines the upper left corner - * of the subtree. - * @param level Level of this subtree in the tree. The root node is level 1, its children are level 2, etc. + * @param location Point in OpenGL screen coordinates (origin lower left corner) that defines the upper left corner + * of the subtree. + * @param level Level of this subtree in the tree. The root node is level 1, its children are level 2, etc. * * @return Bounds of the node {@code needle}. */ protected Rectangle findNodeBounds(TreeNode needle, TreeNode haystack, DrawContext dc, Dimension frameSize, - Point location, int level) - { + Point location, int level) { TreeAttributes attributes = this.getActiveAttributes(); int oldX = location.x; - if (level > 1 || attributes.isRootVisible()) - { + if (level > 1 || attributes.isRootVisible()) { Dimension size = this.getNodeSize(dc, frameSize, location.x, haystack, attributes); // Adjust y to the bottom of the node area @@ -1277,20 +1209,20 @@ protected Rectangle findNodeBounds(TreeNode needle, TreeNode haystack, DrawConte Rectangle nodeBounds = new Rectangle(location.x, location.y, size.width, size.height); - if (haystack.getPath().equals(needle.getPath())) + if (haystack.getPath().equals(needle.getPath())) { return nodeBounds; + } location.x += level * this.indent; } // Draw child nodes if the root node is expanded - if (this.tree.isNodeExpanded(haystack)) - { - for (TreeNode child : haystack.getChildren()) - { + if (this.tree.isNodeExpanded(haystack)) { + for (TreeNode child : haystack.getChildren()) { Rectangle bounds = this.findNodeBounds(needle, child, dc, frameSize, location, level + 1); - if (bounds != null) + if (bounds != null) { return bounds; + } } } location.x = oldX; // Restore previous indent level @@ -1298,16 +1230,17 @@ protected Rectangle findNodeBounds(TreeNode needle, TreeNode haystack, DrawConte return null; } - /** {@inheritDoc} */ - public synchronized void makeVisible(TreePath path) - { + /** + * {@inheritDoc} + */ + public synchronized void makeVisible(TreePath path) { TreeNode node = this.tree.getNode(path); - if (node == null) + if (node == null) { return; + } TreeNode parent = node.getParent(); - while (parent != null) - { + while (parent != null) { this.tree.expandPath(parent.getPath()); parent = parent.getParent(); } @@ -1323,8 +1256,7 @@ public synchronized void makeVisible(TreePath path) * * @return Screen location, measured in pixels from the upper left corner of the screen. */ - public Offset getScreenLocation() - { + public Offset getScreenLocation() { return this.frame.getScreenLocation(); } @@ -1334,22 +1266,22 @@ public Offset getScreenLocation() * * @param screenLocation New screen location. */ - public void setScreenLocation(Offset screenLocation) - { + public void setScreenLocation(Offset screenLocation) { frame.setScreenLocation(screenLocation); } - /** {@inheritDoc} */ - public TreeAttributes getAttributes() - { + /** + * {@inheritDoc} + */ + public TreeAttributes getAttributes() { return this.normalAttributes; } - /** {@inheritDoc} */ - public void setAttributes(TreeAttributes attributes) - { - if (attributes == null) - { + /** + * {@inheritDoc} + */ + public void setAttributes(TreeAttributes attributes) { + if (attributes == null) { String msg = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1363,8 +1295,7 @@ public void setAttributes(TreeAttributes attributes) * * @return Attributes to use when tree is highlighted. */ - public TreeAttributes getHighlightAttributes() - { + public TreeAttributes getHighlightAttributes() { return this.highlightAttributes; } @@ -1373,10 +1304,8 @@ public TreeAttributes getHighlightAttributes() * * @param attributes New highlight attributes. */ - public void setHighlightAttributes(TreeAttributes attributes) - { - if (attributes == null) - { + public void setHighlightAttributes(TreeAttributes attributes) { + if (attributes == null) { String msg = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -1390,37 +1319,33 @@ public void setHighlightAttributes(TreeAttributes attributes) * * @return Highlight attributes if the tree is highlighted. Otherwise, the normal attributes. */ - protected TreeAttributes getActiveAttributes() - { + protected TreeAttributes getActiveAttributes() { return this.activeAttributes; } - /** Determines which attributes -- normal, highlight or default -- to use each frame. */ - protected void determineActiveAttributes() - { + /** + * Determines which attributes -- normal, highlight or default -- to use each frame. + */ + protected void determineActiveAttributes() { TreeAttributes newAttributes = defaultAttributes; - if (this.isHighlighted()) - { - if (this.getHighlightAttributes() != null) + if (this.isHighlighted()) { + if (this.getHighlightAttributes() != null) { newAttributes = this.getHighlightAttributes(); - else - { + } else { // If no highlight attributes have been specified we will use the normal attributes. - if (this.getAttributes() != null) + if (this.getAttributes() != null) { newAttributes = this.getAttributes(); - else + } else { newAttributes = defaultAttributes; + } } - } - else if (this.getAttributes() != null) - { + } else if (this.getAttributes() != null) { newAttributes = this.getAttributes(); } // If the attributes have changed since the last frame, change the update time since the tree needs to repaint - if (!newAttributes.equals(this.activeAttributes)) - { + if (!newAttributes.equals(this.activeAttributes)) { this.markUpdated(); } @@ -1432,8 +1357,7 @@ else if (this.getAttributes() != null) * * @return True if the tree is highlighted. */ - public boolean isHighlighted() - { + public boolean isHighlighted() { return this.highlighted; } @@ -1442,8 +1366,7 @@ public boolean isHighlighted() * * @param highlighted True if the tree should be highlighted. */ - public void setHighlighted(boolean highlighted) - { + public void setHighlighted(boolean highlighted) { this.highlighted = highlighted; } @@ -1452,42 +1375,42 @@ public void setHighlighted(boolean highlighted) * * @return The frame that the tree is drawn on. */ - public ScrollFrame getFrame() - { + public ScrollFrame getFrame() { return this.frame; } /** * Compute the size of a node. * - * @param dc Current draw context. - * @param frameSize Size of the frame into which the tree is rendered. - * @param x Offset in pixels from the left side of the screen to the left most part of the node. - * @param node Node for which to compute bounds. + * @param dc Current draw context. + * @param frameSize Size of the frame into which the tree is rendered. + * @param x Offset in pixels from the left side of the screen to the left most part of the node. + * @param node Node for which to compute bounds. * @param attributes Attributes to use for bounds calculation. * * @return The dimensions of the node. */ - public Dimension getNodeSize(DrawContext dc, Dimension frameSize, int x, TreeNode node, TreeAttributes attributes) - { + public Dimension getNodeSize(DrawContext dc, Dimension frameSize, int x, TreeNode node, TreeAttributes attributes) { Dimension size = new Dimension(); // Find bounds of the node icon. - if (node.hasImage()) - { + if (node.hasImage()) { Dimension iconSize = attributes.getIconSize(); - if (iconSize.height > size.height) + if (iconSize.height > size.height) { size.height = iconSize.height; + } size.width += (iconSize.width + attributes.getIconSpace()); } // Add width of the check box and toggle control, if present - if (this.isDrawSelectedSymbol()) + if (this.isDrawSelectedSymbol()) { size.width += (this.getSelectedSymbolSize().width + attributes.getIconSpace()); + } - if (this.isDrawNodeStateSymbol()) + if (this.isDrawNodeStateSymbol()) { size.width += (this.getNodeStateSymbolSize().width + attributes.getIconSpace()); + } int textIndent = size.width; int textWidth; @@ -1499,8 +1422,7 @@ public Dimension getNodeSize(DrawContext dc, Dimension frameSize, int x, TreeNod // Find the bounds of the description string, which may be wrapped to multiple lines. String description = this.getDescriptionText(node); - if (description != null) - { + if (description != null) { Rectangle2D descriptionBounds; // Compute bounds based on wrapped text, if text is set to wrap @@ -1511,58 +1433,46 @@ public Dimension getNodeSize(DrawContext dc, Dimension frameSize, int x, TreeNod int textAreaWidth = frameSize.width - x - textIndent; int numLines = this.estimateWrappedTextLines(dc, description, attributes.getDescriptionFont(), - textAreaWidth); + textAreaWidth); // If the text needs to wrap, then use the text area width as the width of the text since this is the // edge that the text wraps to. Otherwise, the text will display on one line, so compute the bounds of the // unwrapped text. int width; - if (numLines == 1) - { + if (numLines == 1) { descriptionBounds = this.getMultilineTextBounds(dc, description, attributes.getDescriptionFont()); width = (int) Math.min(textAreaWidth, descriptionBounds.getWidth()); - } - else - { + } else { width = textAreaWidth; } descriptionBounds = new Rectangle(width, numLines * this.lineHeight); NodeLayout layout = this.layoutCache.get(node); - if (layout == null) - { + if (layout == null) { layout = new NodeLayout(node); this.layoutCache.put(node, layout); } layout.numLines = numLines; - } - else - { + } else { descriptionBounds = this.getMultilineTextBounds(dc, description, attributes.getDescriptionFont()); } size.height += (int) Math.abs(descriptionBounds.getHeight()); size.width += Math.max(textWidth, descriptionBounds.getWidth()); - } - else - { + } else { size.width += textWidth; } return size; } - protected int estimateWrappedTextLines(DrawContext dc, String text, Font font, int frameWidth) - { + protected int estimateWrappedTextLines(DrawContext dc, String text, Font font, int frameWidth) { boolean containsWhitespace = (text.contains(" ") || text.contains("\t")); // If there's no whitespace in the string, then the text can't wrap, it must be one line - if (!containsWhitespace) - { + if (!containsWhitespace) { return 1; - } - else - { + } else { // Compute the bounds of the first 50 characters of the string, and use this to estimate the length of the // full string. Computing the length of a very long description string can be very expensive, and all we're // really trying to figure out is whether the line will need to wrap or not. @@ -1578,27 +1488,24 @@ protected int estimateWrappedTextLines(DrawContext dc, String text, Font font, i /** * Get the wrapped description text for a node. The wrapped text will be cached in the {@link #layoutCache}. * - * @param dc Current draw context. - * @param node Node for which to get wrapped text. - * @param font Font to use for the description. + * @param dc Current draw context. + * @param node Node for which to get wrapped text. + * @param font Font to use for the description. * @param width Width to which to wrap text. * * @return The wrapped text as a String. The string will contain newline characters to delimit the lines of wrapped - * text. + * text. */ - protected String computeWrappedText(DrawContext dc, TreeNode node, Font font, int width) - { + protected String computeWrappedText(DrawContext dc, TreeNode node, Font font, int width) { NodeLayout layout = this.layoutCache.get(node); - if (layout == null) - { + if (layout == null) { layout = new NodeLayout(node); this.layoutCache.put(node, layout); } String description = node.getDescription(); - if ((layout.wrappedText == null || layout.textWrapWidth != width) && description != null) - { + if ((layout.wrappedText == null || layout.textWrapWidth != width) && description != null) { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); MultiLineTextRenderer mltr = new MultiLineTextRenderer(textRenderer); @@ -1613,11 +1520,11 @@ protected String computeWrappedText(DrawContext dc, TreeNode node, Font font, in return layout.wrappedText; } - /** Invalidate the computed wrapped text, forcing the text wrap to be recomputed. */ - protected void invalidateWrappedText() - { - for (Map.Entry entry : this.layoutCache.entrySet()) - { + /** + * Invalidate the computed wrapped text, forcing the text wrap to be recomputed. + */ + protected void invalidateWrappedText() { + for (Map.Entry entry : this.layoutCache.entrySet()) { entry.getValue().wrappedText = null; } } @@ -1630,25 +1537,20 @@ protected void invalidateWrappedText() * @param node The node to expand or collapse. * * @return A {@link TreeHotSpot} that will be added as a pickable object to the screen area occupied by the toggle - * control. + * control. */ - protected HotSpot createTogglePathControl(final Tree tree, final TreeNode node) - { - return new TreeHotSpot(this.getFrame()) - { + protected HotSpot createTogglePathControl(final Tree tree, final TreeNode node) { + return new TreeHotSpot(this.getFrame()) { @Override - public void selected(SelectEvent event) - { - if (event == null || this.isConsumed(event)) + public void selected(SelectEvent event) { + if (event == null || this.isConsumed(event)) { return; + } - if (event.isLeftClick() || event.isLeftDoubleClick()) - { + if (event.isLeftClick() || event.isLeftDoubleClick()) { tree.togglePath(node.getPath()); event.consume(); - } - else - { + } else { super.selected(event); } } @@ -1663,25 +1565,20 @@ public void selected(SelectEvent event) * @param node The node to expand or collapse. * * @return A {@link TreeHotSpot} that will be added as a pickable object to the screen area occupied by the toggle - * control. + * control. */ - protected HotSpot createSelectControl(final TreeNode node) - { - return new TreeHotSpot(this.getFrame()) - { + protected HotSpot createSelectControl(final TreeNode node) { + return new TreeHotSpot(this.getFrame()) { @Override - public void selected(SelectEvent event) - { - if (event == null || this.isConsumed(event)) + public void selected(SelectEvent event) { + if (event == null || this.isConsumed(event)) { return; + } - if (event.isLeftClick() || event.isLeftDoubleClick()) - { + if (event.isLeftClick() || event.isLeftDoubleClick()) { toggleNodeSelection(node); event.consume(); - } - else - { + } else { super.selected(event); } } @@ -1692,20 +1589,18 @@ public void selected(SelectEvent event) * Get the bounds of a text string. This method consults the text bound cache. If the bounds of the input string are * not already cached, they will be computed and added to the cache. * - * @param dc Draw context. + * @param dc Draw context. * @param text Text to get bounds of. * @param font Font applied to the text. * * @return A rectangle that describes the node bounds. See com.jogamp.opengl.util.awt.TextRenderer.getBounds for - * information on how this rectangle should be interpreted. + * information on how this rectangle should be interpreted. */ - protected Rectangle2D getTextBounds(DrawContext dc, String text, Font font) - { + protected Rectangle2D getTextBounds(DrawContext dc, String text, Font font) { TextCacheKey cacheKey = new TextCacheKey(text, font); Rectangle2D bounds = this.textCache.get(cacheKey); - if (bounds == null) - { + if (bounds == null) { TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); bounds = textRenderer.getBounds(text); @@ -1719,21 +1614,19 @@ protected Rectangle2D getTextBounds(DrawContext dc, String text, Font font) * Get the bounds of a multi-line text string. Each newline character in the input string (\n) indicates the start * of a new line. * - * @param dc Current draw context. + * @param dc Current draw context. * @param text Text to find bounds of. * @param font Font applied to the text. * * @return A rectangle that describes the node bounds. See com.jogamp.opengl.util.awt.TextRenderer.getBounds for - * information on how this rectangle should be interpreted. + * information on how this rectangle should be interpreted. */ - protected Rectangle2D getMultilineTextBounds(DrawContext dc, String text, Font font) - { + protected Rectangle2D getMultilineTextBounds(DrawContext dc, String text, Font font) { int width = 0; int maxLineHeight = 0; String[] lines = text.split("\n"); - for (String line : lines) - { + for (String line : lines) { Rectangle2D lineBounds = this.getTextBounds(dc, line, font); width = (int) Math.max(lineBounds.getWidth(), width); maxLineHeight = (int) Math.max(lineBounds.getMaxY(), lineHeight); @@ -1756,15 +1649,15 @@ protected Rectangle2D getMultilineTextBounds(DrawContext dc, String text, Font f * * @param node the TreeNode who's selection state should be toggled. */ - protected void toggleNodeSelection(TreeNode node) - { + protected void toggleNodeSelection(TreeNode node) { boolean selected = !node.isSelected(); node.setSelected(selected); // Change the selection state of the node's descendants to match. Toggling an interior node's selection state // causes that entire branch to toggle. - if (!node.isLeaf()) + if (!node.isLeaf()) { this.setDescendantsSelected(node, selected); + } // Change the selection state of the node's ancestors to match. If the node's new selection state is true, then // mark its ancestors as selected. When an interior or leaf node is selected, the path to that node is also @@ -1772,13 +1665,11 @@ protected void toggleNodeSelection(TreeNode node) // the first ancestor with a selected child. This avoids clearing a selected path to another interior or leaf // node. TreeNode parent = node.getParent(); - while (parent != null) - { + while (parent != null) { boolean prevSelected = parent.isSelected(); parent.setSelected(selected); - if (!selected && !TreeNode.NOT_SELECTED.equals(parent.isTreeSelected())) - { + if (!selected && !TreeNode.NOT_SELECTED.equals(parent.isTreeSelected())) { parent.setSelected(prevSelected); break; } @@ -1790,17 +1681,16 @@ protected void toggleNodeSelection(TreeNode node) /** * Sets the selection state of the branch beneath the specified node. * - * @param node the TreeNode who descendants selection should be set. + * @param node the TreeNode who descendants selection should be set. * @param selected true to mark the descendants and selected, otherwise false. */ - protected void setDescendantsSelected(TreeNode node, boolean selected) - { - for (TreeNode child : node.getChildren()) - { + protected void setDescendantsSelected(TreeNode node, boolean selected) { + for (TreeNode child : node.getChildren()) { child.setSelected(selected); - if (!child.isLeaf()) + if (!child.isLeaf()) { this.setDescendantsSelected(child, selected); + } } } @@ -1811,8 +1701,7 @@ protected void setDescendantsSelected(TreeNode node, boolean selected) * * @return Text for node. */ - protected String getText(TreeNode node) - { + protected String getText(TreeNode node) { return node.getText(); } @@ -1823,19 +1712,26 @@ protected String getText(TreeNode node) * * @return Description text for {@code node}. May return null if there is no description. */ - protected String getDescriptionText(TreeNode node) - { + protected String getDescriptionText(TreeNode node) { return node.getDescription(); } - /** Cache key for cache text bound cache. */ - protected static class TextCacheKey - { - /** Text string. */ + /** + * Cache key for cache text bound cache. + */ + protected static class TextCacheKey { + + /** + * Text string. + */ protected String text; - /** Font used to compute bounds. */ + /** + * Font used to compute bounds. + */ protected Font font; - /** Hash code. */ + /** + * Hash code. + */ protected int hash = 0; /** @@ -1844,16 +1740,13 @@ protected static class TextCacheKey * @param text String for which to cache bounds. * @param font Font of the rendered string. */ - public TextCacheKey(String text, Font font) - { - if (text == null) - { + public TextCacheKey(String text, Font font) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (font == null) - { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1864,12 +1757,13 @@ public TextCacheKey(String text, Font font) } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } TextCacheKey cacheKey = (TextCacheKey) o; @@ -1877,10 +1771,8 @@ public boolean equals(Object o) } @Override - public int hashCode() - { - if (this.hash == 0) - { + public int hashCode() { + if (this.hash == 0) { int result; result = this.text.hashCode(); result = 31 * result + this.font.hashCode(); @@ -1890,12 +1782,18 @@ public int hashCode() } } - /** Class to hold information about how a tree node is laid out. */ - protected static class NodeLayout - { - /** Node that this layout applies to. */ + /** + * Class to hold information about how a tree node is laid out. + */ + protected static class NodeLayout { + + /** + * Node that this layout applies to. + */ protected TreeNode node; - /** Node bounds, relative to the bottom left corner of the tree. */ + /** + * Node bounds, relative to the bottom left corner of the tree. + */ protected Rectangle bounds; protected Rectangle pickBounds; /** @@ -1905,11 +1803,17 @@ protected static class NodeLayout protected Rectangle screenBounds; protected Rectangle pickScreenBounds; - /** Wrapped version of the node description text. Computed once and then cached here. */ + /** + * Wrapped version of the node description text. Computed once and then cached here. + */ protected String wrappedText; - /** The width used to wrap the description text. */ + /** + * The width used to wrap the description text. + */ protected int textWrapWidth; - /** Number of lines of wrapped description text in this layout. */ + /** + * Number of lines of wrapped description text in this layout. + */ protected int numLines; /** @@ -1926,10 +1830,8 @@ protected static class NodeLayout * * @param node Node that is being laid out. */ - protected NodeLayout(TreeNode node) - { - if (node == null) - { + protected NodeLayout(TreeNode node) { + if (node == null) { String message = Logging.getMessage("nullValue.TreeNodeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1943,15 +1845,14 @@ protected NodeLayout(TreeNode node) * Reset the draw point to the lower left corner of the node bounds. * * @param treePoint location of the lower left corner of the tree, measured in GL coordinates (origin lower left - * corner of the screen). + * corner of the screen). */ - protected void reset(Point treePoint) - { + protected void reset(Point treePoint) { this.drawPoint.x = this.bounds.x + treePoint.x; this.drawPoint.y = this.bounds.y + treePoint.y; this.screenBounds = new Rectangle(this.drawPoint.x, this.drawPoint.y, this.bounds.width, - this.bounds.height); + this.bounds.height); int pickX = this.pickBounds.x + treePoint.x; int pickY = this.pickBounds.y + treePoint.y; diff --git a/src/gov/nasa/worldwind/util/tree/BasicTreeModel.java b/src/gov/nasa/worldwind/util/tree/BasicTreeModel.java index 7816c2a3db..2ad9caa82d 100644 --- a/src/gov/nasa/worldwind/util/tree/BasicTreeModel.java +++ b/src/gov/nasa/worldwind/util/tree/BasicTreeModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.WWObjectImpl; @@ -14,14 +13,17 @@ * @author pabercrombie * @version $Id: BasicTreeModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicTreeModel extends WWObjectImpl implements TreeModel -{ - /** The root node. */ +public class BasicTreeModel extends WWObjectImpl implements TreeModel { + + /** + * The root node. + */ protected TreeNode root; - /** Create a new tree model. */ - public BasicTreeModel() - { + /** + * Create a new tree model. + */ + public BasicTreeModel() { } /** @@ -29,14 +31,14 @@ public BasicTreeModel() * * @param root The root node. */ - public BasicTreeModel(TreeNode root) - { + public BasicTreeModel(TreeNode root) { this.setRoot(root); } - /** {@inheritDoc} */ - public TreeNode getRoot() - { + /** + * {@inheritDoc} + */ + public TreeNode getRoot() { return this.root; } @@ -45,14 +47,15 @@ public TreeNode getRoot() * * @param root New root. */ - public void setRoot(TreeNode root) - { - if (this.root != null) + public void setRoot(TreeNode root) { + if (this.root != null) { this.root.removePropertyChangeListener(this); + } this.root = root; - if (this.root != null) + if (this.root != null) { this.root.addPropertyChangeListener(this); + } } } diff --git a/src/gov/nasa/worldwind/util/tree/BasicTreeNode.java b/src/gov/nasa/worldwind/util/tree/BasicTreeNode.java index ba25744342..2c84f6b1b6 100644 --- a/src/gov/nasa/worldwind/util/tree/BasicTreeNode.java +++ b/src/gov/nasa/worldwind/util/tree/BasicTreeNode.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.*; @@ -21,8 +20,8 @@ * @author pabercrombie * @version $Id: BasicTreeNode.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicTreeNode extends WWObjectImpl implements TreeNode -{ +public class BasicTreeNode extends WWObjectImpl implements TreeNode { + protected String text; protected Object imageSource; protected BasicWWTexture texture; @@ -47,21 +46,18 @@ public class BasicTreeNode extends WWObjectImpl implements TreeNode * * @param text Node text. */ - public BasicTreeNode(String text) - { + public BasicTreeNode(String text) { this(text, null); } /** * Create a node with text and an icon. * - * @param text Node text. + * @param text Node text. * @param imageSource Image source for the node icon. May be a String, URL, or BufferedImage. */ - public BasicTreeNode(String text, Object imageSource) - { - if (text == null) - { + public BasicTreeNode(String text, Object imageSource) { + if (text == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -71,67 +67,79 @@ public BasicTreeNode(String text, Object imageSource) this.setImageSource(imageSource); } - /** {@inheritDoc} */ - public String getText() - { + /** + * {@inheritDoc} + */ + public String getText() { return this.text; } - /** {@inheritDoc} */ - public TreeNode getParent() - { + /** + * {@inheritDoc} + */ + public TreeNode getParent() { return this.parent; } - /** {@inheritDoc} */ - public void setParent(TreeNode node) - { + /** + * {@inheritDoc} + */ + public void setParent(TreeNode node) { this.parent = node; } - /** {@inheritDoc} */ - public Iterable getChildren() - { - if (this.children != null) + /** + * {@inheritDoc} + */ + public Iterable getChildren() { + if (this.children != null) { return Collections.unmodifiableList(this.children); - else + } else { return Collections.emptyList(); + } } - /** {@inheritDoc} */ - public boolean isEnabled() - { + /** + * {@inheritDoc} + */ + public boolean isEnabled() { return this.enabled; } - /** {@inheritDoc} */ - public void setEnabled(boolean enabled) - { + /** + * {@inheritDoc} + */ + public void setEnabled(boolean enabled) { this.enabled = enabled; } - /** {@inheritDoc} */ - public boolean isSelected() - { + /** + * {@inheritDoc} + */ + public boolean isSelected() { return this.selected; } - /** {@inheritDoc} */ - public void setSelected(boolean selected) - { + /** + * {@inheritDoc} + */ + public void setSelected(boolean selected) { boolean prevSelected = this.isSelected(); this.selected = selected; this.treeSelected = null; // Need to recompute tree selected field - if (prevSelected != selected) + if (prevSelected != selected) { this.firePropertyChange(AVKey.TREE_NODE, null, this); + } } - /** {@inheritDoc} */ - public String isTreeSelected() - { - if (this.treeSelected == null) + /** + * {@inheritDoc} + */ + public String isTreeSelected() { + if (this.treeSelected == null) { this.treeSelected = this.computeTreeSelected(); + } return this.treeSelected; } @@ -141,16 +149,13 @@ public String isTreeSelected() * * @return {@link #SELECTED}, {@link #NOT_SELECTED}, {@link #PARTIALLY_SELECTED}. */ - protected String computeTreeSelected() - { + protected String computeTreeSelected() { String selected = this.isSelected() ? SELECTED : NOT_SELECTED; - for (TreeNode child : this.getChildren()) - { + for (TreeNode child : this.getChildren()) { String childSelected = child.isTreeSelected(); - if (!selected.equals(childSelected)) - { + if (!selected.equals(childSelected)) { selected = PARTIALLY_SELECTED; break; // No need to look at other nodes } @@ -159,58 +164,64 @@ protected String computeTreeSelected() return selected; } - /** {@inheritDoc} */ - public boolean isVisible() - { + /** + * {@inheritDoc} + */ + public boolean isVisible() { return this.visible; } - /** {@inheritDoc} */ - public boolean isLeaf() - { + /** + * {@inheritDoc} + */ + public boolean isLeaf() { return WWUtil.isEmpty(this.children); } - /** {@inheritDoc} */ - public void setVisible(boolean visible) - { + /** + * {@inheritDoc} + */ + public void setVisible(boolean visible) { this.visible = visible; } - public String getDescription() - { + public String getDescription() { return description; } - public void setDescription(String description) - { + public void setDescription(String description) { this.description = description != null ? description.trim() : null; } - /** {@inheritDoc} */ - public Object getImageSource() - { + /** + * {@inheritDoc} + */ + public Object getImageSource() { return imageSource; } - /** {@inheritDoc} */ - public void setImageSource(Object imageSource) - { + /** + * {@inheritDoc} + */ + public void setImageSource(Object imageSource) { this.imageSource = imageSource; this.texture = null; } - /** {@inheritDoc} */ - public boolean hasImage() - { + /** + * {@inheritDoc} + */ + public boolean hasImage() { return this.getImageSource() != null; } - /** {@inheritDoc} */ - public BasicWWTexture getTexture() - { - if (this.texture == null) + /** + * {@inheritDoc} + */ + public BasicWWTexture getTexture() { + if (this.texture == null) { this.initializeTexture(); + } return this.texture; } @@ -219,36 +230,35 @@ public BasicWWTexture getTexture() * Create and initialize the texture from the image source. If the image is not in memory this method will request * that it be loaded. */ - protected void initializeTexture() - { + protected void initializeTexture() { Object imageSource = this.getImageSource(); - if (imageSource instanceof String || imageSource instanceof URL) - { + if (imageSource instanceof String || imageSource instanceof URL) { URL imageURL = WorldWind.getDataFileStore().requestFile(imageSource.toString()); - if (imageURL != null) - { + if (imageURL != null) { this.texture = new BasicWWTexture(imageURL, true); } - } - else if (imageSource != null) - { + } else if (imageSource != null) { this.texture = new BasicWWTexture(imageSource, true); } } - /** {@inheritDoc} */ - public void addChild(TreeNode child) - { - if (this.children == null) + /** + * {@inheritDoc} + */ + public void addChild(TreeNode child) { + if (this.children == null) { this.children = new ArrayList(); + } this.addChild(this.children.size(), child); } - /** {@inheritDoc} */ - public void addChild(int index, TreeNode child) - { - if (this.children == null) + /** + * {@inheritDoc} + */ + public void addChild(int index, TreeNode child) { + if (this.children == null) { this.children = new ArrayList(); + } this.children.add(index, child); this.treeSelected = null; // Need to recompute tree selected field @@ -257,14 +267,15 @@ public void addChild(int index, TreeNode child) this.firePropertyChange(AVKey.TREE_NODE, null, this); } - /** {@inheritDoc} */ - public void removeChild(TreeNode child) - { - if (this.children != null) + /** + * {@inheritDoc} + */ + public void removeChild(TreeNode child) { + if (this.children != null) { this.children.remove(child); + } - if (child != null && child.getParent() == this) - { + if (child != null && child.getParent() == this) { this.treeSelected = null; // Need to recompute tree selected field child.setParent(null); child.removePropertyChangeListener(this); @@ -272,18 +283,20 @@ public void removeChild(TreeNode child) } } - /** {@inheritDoc} */ - public void removeAllChildren() - { - if (this.children == null) + /** + * {@inheritDoc} + */ + public void removeAllChildren() { + if (this.children == null) { return; + } Iterator iterator = this.children.iterator(); - if (!iterator.hasNext()) + if (!iterator.hasNext()) { return; + } - while (iterator.hasNext()) - { + while (iterator.hasNext()) { TreeNode child = iterator.next(); iterator.remove(); @@ -295,14 +308,14 @@ public void removeAllChildren() this.firePropertyChange(AVKey.TREE_NODE, null, this); } - /** {@inheritDoc} */ - public TreePath getPath() - { + /** + * {@inheritDoc} + */ + public TreePath getPath() { TreePath path = new TreePath(); TreeNode node = this; - while (node != null) - { + while (node != null) { path.add(0, node.getText()); node = node.getParent(); } @@ -310,10 +323,11 @@ public TreePath getPath() return path; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { this.treeSelected = null; // Need to recompute tree selected field super.propertyChange(propertyChangeEvent); } diff --git a/src/gov/nasa/worldwind/util/tree/DragControl.java b/src/gov/nasa/worldwind/util/tree/DragControl.java index 1fe5fe6a9f..8998e67fb7 100644 --- a/src/gov/nasa/worldwind/util/tree/DragControl.java +++ b/src/gov/nasa/worldwind/util/tree/DragControl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.event.SelectEvent; @@ -17,8 +16,8 @@ * @author pabercrombie * @version $Id: DragControl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class DragControl extends TreeHotSpot -{ +public abstract class DragControl extends TreeHotSpot { + protected boolean dragging; protected Point dragRefPoint; @@ -26,10 +25,9 @@ public abstract class DragControl extends TreeHotSpot * Create a drag control. * * @param parent The screen area that contains this drag control. Input events that cannot be handled by this object - * will be passed to the parent. May be null. + * will be passed to the parent. May be null. */ - public DragControl(HotSpot parent) - { + public DragControl(HotSpot parent) { super(parent); } @@ -38,8 +36,7 @@ public DragControl(HotSpot parent) * * @return True if the control is dragging. */ - public boolean isDragging() - { + public boolean isDragging() { return this.dragging; } @@ -51,25 +48,21 @@ public boolean isDragging() * @param event Select event. */ @Override - public void selected(SelectEvent event) - { - if (event == null || this.isConsumed(event)) + public void selected(SelectEvent event) { + if (event == null || this.isConsumed(event)) { return; + } Point pickPoint = event.getPickPoint(); - if (event.isDrag()) - { - if (!this.isDragging()) - { + if (event.isDrag()) { + if (!this.isDragging()) { this.dragging = true; this.beginDrag(pickPoint); } this.drag(pickPoint); event.consume(); - } - else if (event.isDragEnd()) - { + } else if (event.isDragEnd()) { this.dragging = false; this.endDrag(); event.consume(); @@ -81,8 +74,7 @@ else if (event.isDragEnd()) * * @param point Point at which dragging started. */ - protected void beginDrag(Point point) - { + protected void beginDrag(Point point) { this.dragRefPoint = point; } @@ -96,8 +88,7 @@ protected void beginDrag(Point point) /** * Called when a drag action ends. This implementation sets {@link #dragRefPoint} to null. */ - protected void endDrag() - { + protected void endDrag() { this.dragRefPoint = null; } } diff --git a/src/gov/nasa/worldwind/util/tree/FrameAttributes.java b/src/gov/nasa/worldwind/util/tree/FrameAttributes.java index 400a299b3e..57e6c3320d 100644 --- a/src/gov/nasa/worldwind/util/tree/FrameAttributes.java +++ b/src/gov/nasa/worldwind/util/tree/FrameAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import java.awt.*; @@ -15,11 +14,11 @@ * @version $Id: FrameAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ * @see ScrollFrame */ -public interface FrameAttributes -{ +public interface FrameAttributes { + /** - * Returns a new FrameAttributes instance of the same type as this FrameAttributes, who's properties are - * configured exactly as this FrameAttributes. + * Returns a new FrameAttributes instance of the same type as this FrameAttributes, who's properties are configured + * exactly as this FrameAttributes. * * @return a copy of this FrameAttributes. */ diff --git a/src/gov/nasa/worldwind/util/tree/FrameResizeControl.java b/src/gov/nasa/worldwind/util/tree/FrameResizeControl.java index a3b8b0c093..deaf7292d4 100644 --- a/src/gov/nasa/worldwind/util/tree/FrameResizeControl.java +++ b/src/gov/nasa/worldwind/util/tree/FrameResizeControl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.avlist.AVKey; @@ -21,67 +20,73 @@ * @author pabercrombie * @version $Id: FrameResizeControl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FrameResizeControl extends AbstractResizeHotSpot -{ +public class FrameResizeControl extends AbstractResizeHotSpot { + protected ScrollFrame frame; /** * Create a resize control. * - * @param frame Frame to resize. + * @param frame Frame to resize. */ - public FrameResizeControl(ScrollFrame frame) - { + public FrameResizeControl(ScrollFrame frame) { this.frame = frame; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void beginDrag(Point point) - { + protected void beginDrag(Point point) { super.beginDrag(point); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void endDrag() - { + protected void endDrag() { super.endDrag(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Dimension getSize() - { + protected Dimension getSize() { return this.frame.getCurrentSize(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void setSize(Dimension newSize) - { + protected void setSize(Dimension newSize) { this.frame.setSize(Size.fromPixels(newSize.width, newSize.height)); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Point getScreenPoint() - { + protected Point getScreenPoint() { Point2D point2D = this.frame.getScreenPoint(); - return new Point((int)point2D.getX(), (int)point2D.getY()); + return new Point((int) point2D.getX(), (int) point2D.getY()); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected void setScreenPoint(Point newPoint) - { + protected void setScreenPoint(Point newPoint) { this.frame.setScreenLocation(new Offset(newPoint.getX(), newPoint.getY(), AVKey.PIXELS, AVKey.INSET_PIXELS)); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected Dimension getMinimumSize() - { + protected Dimension getMinimumSize() { return this.frame.getMinimumSize(); } @@ -91,10 +96,10 @@ protected Dimension getMinimumSize() * * @param event The event to handle. */ - public void mouseWheelMoved(MouseWheelEvent event) - { - if (event == null || event.isConsumed()) + public void mouseWheelMoved(MouseWheelEvent event) { + if (event == null || event.isConsumed()) { return; + } this.frame.mouseWheelMoved(event); } diff --git a/src/gov/nasa/worldwind/util/tree/ScrollBar.java b/src/gov/nasa/worldwind/util/tree/ScrollBar.java index 3a7f01a0c6..f00386d80c 100644 --- a/src/gov/nasa/worldwind/util/tree/ScrollBar.java +++ b/src/gov/nasa/worldwind/util/tree/ScrollBar.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.avlist.AVKey; @@ -27,50 +26,90 @@ * @author pabercrombie * @version $Id: ScrollBar.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScrollBar implements Renderable -{ - /** Scroll increment for one unit up. */ +public class ScrollBar implements Renderable { + + /** + * Scroll increment for one unit up. + */ public static final String UNIT_UP = "gov.nasa.util.ScrollBar.UnitUp"; - /** Scroll increment for one unit down. */ + /** + * Scroll increment for one unit down. + */ public static final String UNIT_DOWN = "gov.nasa.util.ScrollBar.UnitDown"; - /** Scroll increment for one page up. */ + /** + * Scroll increment for one page up. + */ public static final String BLOCK_UP = "gov.nasa.util.ScrollBar.BlockUp"; - /** Scroll increment for one page down. */ + /** + * Scroll increment for one page down. + */ public static final String BLOCK_DOWN = "gov.nasa.util.ScrollBar.BlockDown"; - /** Default scroll range minimum value. */ + /** + * Default scroll range minimum value. + */ protected static final int DEFAULT_MIN_VALUE = 0; - /** Default scroll range maximum value. */ + /** + * Default scroll range maximum value. + */ protected static final int DEFAULT_MAX_VALUE = 100; - /** Default unit increment. */ + /** + * Default unit increment. + */ protected static final int DEFAULT_UNIT_INCREMENT = 5; - /** Default minimum size, in pixels, of the scroll knob. */ + /** + * Default minimum size, in pixels, of the scroll knob. + */ protected static final int DEFAULT_MIN_SCROLL_KNOB_SIZE = 10; - /** Default delay, in milliseconds, between auto scroll steps. */ + /** + * Default delay, in milliseconds, between auto scroll steps. + */ protected static final int DEFAULT_AUTO_SCROLL_DELAY = 20; - /** Default insets that position the triangle of the scroll arrow in its box. */ + /** + * Default insets that position the triangle of the scroll arrow in its box. + */ protected static final Insets DEFAULT_ARROW_INSETS = new Insets(2, 2, 2, 2); - /** Default opacity. */ + /** + * Default opacity. + */ protected static final double DEFAULT_OPACITY = 1.0; - /** Default color used to draw lines in the scroll bar. */ + /** + * Default color used to draw lines in the scroll bar. + */ protected static final Color DEFAULT_LINE_COLOR = Color.BLACK; - /** Default first color in the scroll knob gradient. */ + /** + * Default first color in the scroll knob gradient. + */ protected static final Color DEFAULT_SCROLL_KNOB_COLOR1 = new Color(29, 78, 169); - /** Default second color in the scroll knob gradient. */ + /** + * Default second color in the scroll knob gradient. + */ protected static final Color DEFAULT_SCROLL_KNOB_COLOR2 = new Color(93, 158, 223); - /** Minimum value in the scroll range. */ + /** + * Minimum value in the scroll range. + */ protected int minValue = DEFAULT_MIN_VALUE; - /** Maximum value in the scroll range. */ + /** + * Maximum value in the scroll range. + */ protected int maxValue = DEFAULT_MAX_VALUE; - /** Current scroll bar value. */ + /** + * Current scroll bar value. + */ protected int value; - /** The amount of the scroll region that is visible in the frame. */ + /** + * The amount of the scroll region that is visible in the frame. + */ protected int extent; - /** Amount that the scroll bar scrolls when the up or down arrow is clicked. */ + /** + * Amount that the scroll bar scrolls when the up or down arrow is clicked. + */ protected int unitIncrement = DEFAULT_UNIT_INCREMENT; - /** Size, in pixels, of the scroll arrow square. */ + /** + * Size, in pixels, of the scroll arrow square. + */ protected int scrollArrowSize; /** @@ -80,10 +119,14 @@ public class ScrollBar implements Renderable */ protected int minScrollKnobSize = DEFAULT_MIN_SCROLL_KNOB_SIZE; - /** Support for setting up and restoring picking state, and resolving the picked object. */ + /** + * Support for setting up and restoring picking state, and resolving the picked object. + */ protected PickSupport pickSupport = new PickSupport(); - /** Full bounds of the scroll bar. */ + /** + * Full bounds of the scroll bar. + */ protected Rectangle bounds = new Rectangle(); /** * Bounds of the scroll track part of the scroll bar. This is the region in which the scroll knob moves, and @@ -91,20 +134,32 @@ public class ScrollBar implements Renderable */ protected Rectangle scrollBounds = new Rectangle(); - /** Insets used to position the triangle in the scroll arrow box. */ + /** + * Insets used to position the triangle in the scroll arrow box. + */ protected Insets arrowInsets = DEFAULT_ARROW_INSETS; - /** Scroll bar orientation, either {@link AVKey#HORIZONTAL} or {@link AVKey#VERTICAL}. */ + /** + * Scroll bar orientation, either {@link AVKey#HORIZONTAL} or {@link AVKey#VERTICAL}. + */ protected String orientation; - /** Opacity of the scroll bar knob. */ + /** + * Opacity of the scroll bar knob. + */ protected double opacity = DEFAULT_OPACITY; - /** Color applied to lines in the scroll bar. */ + /** + * Color applied to lines in the scroll bar. + */ protected Color lineColor = DEFAULT_LINE_COLOR; - /** First color of the gradient used to fill the scroll knob. */ + /** + * First color of the gradient used to fill the scroll knob. + */ protected Color knobColor1 = DEFAULT_SCROLL_KNOB_COLOR1; - /** Second color of the gradient used to fill the scroll knob. */ + /** + * Second color of the gradient used to fill the scroll knob. + */ protected Color knobColor2 = DEFAULT_SCROLL_KNOB_COLOR2; // Support for long-running scroll operations @@ -125,41 +180,64 @@ public class ScrollBar implements Renderable protected String autoScrollIncrement; // UI controls - /** HotSpot to handle input on the scroll up control. */ + /** + * HotSpot to handle input on the scroll up control. + */ protected HotSpot scrollUpControl; - /** HotSpot to handle input on the scroll down control. */ + /** + * HotSpot to handle input on the scroll down control. + */ protected HotSpot scrollDownControl; - /** HotSpot to handle input on page up control. */ + /** + * HotSpot to handle input on page up control. + */ protected HotSpot scrollUpBlockControl; - /** HotSpot to handle input on page down control. */ + /** + * HotSpot to handle input on page down control. + */ protected HotSpot scrollDownBlockControl; - /** HotSpot to handle input on the scroll knob. */ + /** + * HotSpot to handle input on the scroll knob. + */ protected ScrollKnob scrollKnobControl; // Values computed once per frame and reused during the frame as needed. - /** Identifies frame used to calculate per-frame values. */ + /** + * Identifies frame used to calculate per-frame values. + */ protected long frameNumber = -1; - /** Bounds of the "up arrow" control. */ + /** + * Bounds of the "up arrow" control. + */ protected Rectangle scrollUpControlBounds; - /** Bounds of the "down arrow" control. */ + /** + * Bounds of the "down arrow" control. + */ protected Rectangle scrollDownControlBounds; - /** Bounds of the scroll knob. */ + /** + * Bounds of the scroll knob. + */ protected Rectangle scrollKnobBounds; - /** Bounds of the scroll bar area above the knob. */ + /** + * Bounds of the scroll bar area above the knob. + */ protected Rectangle scrollUpBarBounds; - /** Bounds of the scroll bar area below the knob. */ + /** + * Bounds of the scroll bar area below the knob. + */ protected Rectangle scrollDownBarBounds; - /** Time at which the scrollbar should automatically update itself. */ + /** + * Time at which the scrollbar should automatically update itself. + */ protected long nextAutoScroll; /** * Create a scroll bar in the vertical orientation. * * @param parent The screen component that contains the scroll bar. Input events that cannot be handled by the - * scroll bar will be passed to this component. May be null. + * scroll bar will be passed to this component. May be null. */ - public ScrollBar(HotSpot parent) - { + public ScrollBar(HotSpot parent) { this.setOrientation(AVKey.VERTICAL); this.initializeUIControls(parent); } @@ -168,11 +246,10 @@ public ScrollBar(HotSpot parent) * Create a scroll bar with an orientation. * * @param orientation Either {@link AVKey#VERTICAL} or {@link AVKey#HORIZONTAL}. - * @param parent The screen component that contains the scroll bar. Input events that cannot be handled by the - * scroll bar will be passed to this component. May be null. + * @param parent The screen component that contains the scroll bar. Input events that cannot be handled by the + * scroll bar will be passed to this component. May be null. */ - public ScrollBar(HotSpot parent, String orientation) - { + public ScrollBar(HotSpot parent, String orientation) { this.setOrientation(orientation); this.initializeUIControls(parent); } @@ -181,10 +258,9 @@ public ScrollBar(HotSpot parent, String orientation) * Initialize the objects that represent the UI controls. * * @param parent The screen component that contains the scroll bar. Input events that cannot be handled by the - * scroll bar will be passed to this component. May be null. + * scroll bar will be passed to this component. May be null. */ - protected void initializeUIControls(HotSpot parent) - { + protected void initializeUIControls(HotSpot parent) { this.scrollKnobControl = new ScrollKnob(parent, this); this.scrollUpControl = new ScrollControl(parent, this, UNIT_UP); this.scrollDownControl = new ScrollControl(parent, this, UNIT_DOWN); @@ -197,8 +273,7 @@ protected void initializeUIControls(HotSpot parent) * * @return Scroll bar bounds. */ - public Rectangle getBounds() - { + public Rectangle getBounds() { return bounds; } @@ -207,17 +282,17 @@ public Rectangle getBounds() * * @param bounds New bounds. */ - public void setBounds(Rectangle bounds) - { + public void setBounds(Rectangle bounds) { this.bounds = bounds; - if (AVKey.VERTICAL.equals(this.getOrientation())) + if (AVKey.VERTICAL.equals(this.getOrientation())) { this.scrollArrowSize = bounds.width; - else + } else { this.scrollArrowSize = bounds.height; + } this.scrollBounds = new Rectangle(bounds.x, bounds.y + this.scrollArrowSize, bounds.width, - bounds.height - 2 * this.scrollArrowSize); + bounds.height - 2 * this.scrollArrowSize); } /** @@ -225,8 +300,7 @@ public void setBounds(Rectangle bounds) * * @return Minimum value. */ - public int getMinValue() - { + public int getMinValue() { return minValue; } @@ -235,18 +309,17 @@ public int getMinValue() * * @param minValue New minimum. */ - public void setMinValue(int minValue) - { - if (minValue < 0) - { + public void setMinValue(int minValue) { + if (minValue < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "minValue < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.minValue = minValue; - if (this.getValue() < this.minValue) + if (this.getValue() < this.minValue) { this.setValue(this.minValue); + } } /** @@ -257,8 +330,7 @@ public void setMinValue(int minValue) * @see #getMinValue() * @see #setMaxValue(int) */ - public int getMaxValue() - { + public int getMaxValue() { return maxValue; } @@ -267,18 +339,17 @@ public int getMaxValue() * * @param maxValue New maximum. */ - public void setMaxValue(int maxValue) - { - if (maxValue < 0) - { + public void setMaxValue(int maxValue) { + if (maxValue < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "maxValue < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.maxValue = maxValue; - if (this.getValue() > this.maxValue) + if (this.getValue() > this.maxValue) { this.setValue(this.maxValue); + } } /** @@ -286,8 +357,7 @@ public void setMaxValue(int maxValue) * * @return Current value. The value is clamped to the range [minValue : maxValue - extent]. */ - public int getValue() - { + public int getValue() { return this.value; } @@ -296,8 +366,7 @@ public int getValue() * * @param value New value. */ - public void setValue(int value) - { + public void setValue(int value) { this.value = WWMath.clamp(value, this.getMinValue(), this.getMaxValue() - this.getExtent()); } @@ -309,8 +378,7 @@ public void setValue(int value) * * @see #setUnitIncrement(int) */ - public int getUnitIncrement() - { + public int getUnitIncrement() { return this.unitIncrement; } @@ -321,10 +389,8 @@ public int getUnitIncrement() * * @see #getUnitIncrement() */ - public void setUnitIncrement(int unitIncrement) - { - if (unitIncrement <= 0) - { + public void setUnitIncrement(int unitIncrement) { + if (unitIncrement <= 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "unitIncrement <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -338,10 +404,9 @@ public void setUnitIncrement(int unitIncrement) * the knob. * * @return The block increment. This implementation returns the extent, so the scroll bar will adjust by a full - * visible page. + * visible page. */ - public int getBlockIncrement() - { + public int getBlockIncrement() { return this.extent; } @@ -350,8 +415,7 @@ public int getBlockIncrement() * * @return The scroll bar orientation, either {@link AVKey#VERTICAL} or {@link AVKey#HORIZONTAL}. */ - public String getOrientation() - { + public String getOrientation() { return this.orientation; } @@ -360,10 +424,8 @@ public String getOrientation() * * @param orientation The scroll bar orientation, either {@link AVKey#VERTICAL} or {@link AVKey#HORIZONTAL}. */ - public void setOrientation(String orientation) - { - if (orientation == null) - { + public void setOrientation(String orientation) { + if (orientation == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -379,8 +441,7 @@ public void setOrientation(String orientation) * * @see #setExtent(int) */ - public int getExtent() - { + public int getExtent() { return this.extent; } @@ -392,15 +453,15 @@ public int getExtent() * * * @param extent New extent. If {@code extent} is greater than the range of the scroll bar (max - min), then the - * extent will be set to the maximum valid value. + * extent will be set to the maximum valid value. * * @see #getExtent() */ - public void setExtent(int extent) - { + public void setExtent(int extent) { this.extent = Math.min(extent, this.getMaxValue() - this.getMinValue()); - if (this.getValue() + this.getExtent() > this.getMaxValue()) + if (this.getValue() + this.getExtent() > this.getMaxValue()) { this.setValue(this.getMaxValue() - this.getExtent()); + } } /** @@ -408,8 +469,7 @@ public void setExtent(int extent) * * @return Current value as percentage. */ - public double getValueAsPercentage() - { + public double getValueAsPercentage() { return (double) this.getValue() / (this.getMaxValue() - this.getMinValue()); } @@ -418,8 +478,7 @@ public double getValueAsPercentage() * * @return Minimum size of the knob in pixels. */ - public int getMinScrollKnobSize() - { + public int getMinScrollKnobSize() { return this.minScrollKnobSize; } @@ -428,8 +487,7 @@ public int getMinScrollKnobSize() * * @param minSize Minimum size of the knob in pixels. */ - public void setMinScrollKnobSize(int minSize) - { + public void setMinScrollKnobSize(int minSize) { this.minScrollKnobSize = minSize; } @@ -440,10 +498,9 @@ public void setMinScrollKnobSize(int minSize) * * @return Size of the scroll knob, in pixels. */ - protected int getKnobSize(int scrollAreaSize) - { + protected int getKnobSize(int scrollAreaSize) { return (int) Math.max((scrollAreaSize * ((double) this.getExtent() / (this.getMaxValue() - this.minValue))), - this.getMinScrollKnobSize()); + this.getMinScrollKnobSize()); } /** @@ -451,8 +508,7 @@ protected int getKnobSize(int scrollAreaSize) * * @return Height of arrow control, in pixels. */ - protected int getScrollArrowSize() - { + protected int getScrollArrowSize() { return this.scrollArrowSize; } @@ -464,8 +520,7 @@ protected int getScrollArrowSize() * @see #setLineColor(java.awt.Color) * @see #getKnobColor() */ - public Color getLineColor() - { + public Color getLineColor() { return lineColor; } @@ -478,10 +533,8 @@ public Color getLineColor() * @see #getLineColor() * @see #setKnobColor(java.awt.Color, java.awt.Color) */ - public void setLineColor(Color color) - { - if (color == null) - { + public void setLineColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -499,16 +552,13 @@ public void setLineColor(Color color) * @see #getKnobColor() * @see #setLineColor(java.awt.Color) */ - public void setKnobColor(Color color1, Color color2) - { - if (color1 == null) - { + public void setKnobColor(Color color1, Color color2) { + if (color1 == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (color2 == null) - { + if (color2 == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -526,9 +576,8 @@ public void setKnobColor(Color color1, Color color2) * @see #setKnobColor(java.awt.Color, java.awt.Color) * @see #getLineColor() */ - public Color[] getKnobColor() - { - return new Color[] {this.knobColor1, this.knobColor2}; + public Color[] getKnobColor() { + return new Color[]{this.knobColor1, this.knobColor2}; } /** @@ -536,8 +585,7 @@ public Color[] getKnobColor() * * @return Scroll knob opacity. */ - public double getOpacity() - { + public double getOpacity() { return this.opacity; } @@ -546,8 +594,7 @@ public double getOpacity() * * @param opacity New opacity. */ - public void setOpacity(double opacity) - { + public void setOpacity(double opacity) { this.opacity = opacity; } @@ -556,8 +603,7 @@ public void setOpacity(double opacity) * * @return The delay, in milliseconds, between scrollbar updates. */ - public int getAutoScrollDelay() - { + public int getAutoScrollDelay() { return this.autoScrollDelay; } @@ -565,12 +611,10 @@ public int getAutoScrollDelay() * Specifies how often the scrollbar will update itself when one of the scroll arrows is pressed. * * @param delay Delay in milliseconds between scrollbar updates. A smaller number makes the scrollbar scroll faster, - * a larger number makes it scroll slower. The delay may not be negative. + * a larger number makes it scroll slower. The delay may not be negative. */ - public void setAutoScrollDelay(int delay) - { - if (delay < 0) - { + public void setAutoScrollDelay(int delay) { + if (delay < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange", delay); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -582,15 +626,13 @@ public void setAutoScrollDelay(int delay) //**************************************************************// //******** Methods for setting the scroll position ***********// //**************************************************************// - /** * Adjust the scroll value. * * @param amount Amount to add to the current value. A positive value indicates a scroll down; a negative value - * indicates a scroll up. + * indicates a scroll up. */ - public void scroll(int amount) - { + public void scroll(int amount) { this.setValue(this.getValue() + amount); } @@ -599,16 +641,16 @@ public void scroll(int amount) * * @param amount One of {@link #UNIT_UP}, {@link #UNIT_DOWN}, {@link #BLOCK_UP}, or {@link #BLOCK_DOWN}. */ - public void scroll(String amount) - { - if (UNIT_UP.equals(amount)) + public void scroll(String amount) { + if (UNIT_UP.equals(amount)) { this.scroll(-this.getUnitIncrement()); - else if (UNIT_DOWN.equals(amount)) + } else if (UNIT_DOWN.equals(amount)) { this.scroll(this.getUnitIncrement()); - else if (BLOCK_UP.equals(amount)) + } else if (BLOCK_UP.equals(amount)) { this.scroll(-this.getBlockIncrement()); - else if (BLOCK_DOWN.equals(amount)) + } else if (BLOCK_DOWN.equals(amount)) { this.scroll(this.getBlockIncrement()); + } } /** @@ -622,8 +664,7 @@ else if (BLOCK_DOWN.equals(amount)) * @see #isAutoScrolling() * @see #scroll(String) */ - public void startAutoScroll(String increment) - { + public void startAutoScroll(String increment) { this.autoScrolling = true; this.autoScrollIncrement = increment; } @@ -634,8 +675,7 @@ public void startAutoScroll(String increment) * @see #startAutoScroll(String) * @see #isAutoScrolling() */ - public void stopAutoScroll() - { + public void stopAutoScroll() { this.autoScrolling = false; } @@ -647,32 +687,26 @@ public void stopAutoScroll() * @see #startAutoScroll(String) * @see #stopAutoScroll() */ - public boolean isAutoScrolling() - { + public boolean isAutoScrolling() { return this.autoScrolling; } //**************************************************************// //********************** Rendering ****************************// //**************************************************************// - /** * Draw the scroll bar. The scroll will not draw its bounds are too small to draw without distortion. * * @param dc the DrawContext to be used */ - public void render(DrawContext dc) - { - if (dc.getFrameTimeStamp() != this.frameNumber) - { + public void render(DrawContext dc) { + if (dc.getFrameTimeStamp() != this.frameNumber) { // If an auto-scroll operation is in progress, adjust the scroll value and request that the scene be repainted // and a delay so that the next scroll value can be applied. - if (this.isAutoScrolling()) - { + if (this.isAutoScrolling()) { // Only scroll if the autoscroll delay has elapsed since the last scroll long now = System.currentTimeMillis(); - if (now > this.nextAutoScroll) - { + if (now > this.nextAutoScroll) { int delay = this.getAutoScrollDelay(); this.scroll(this.autoScrollIncrement); dc.setRedrawRequested(delay); @@ -685,15 +719,13 @@ public void render(DrawContext dc) } // Don't draw the scrollbar if the bounds are too small to draw without distortion - if (!this.canDrawInBounds()) + if (!this.canDrawInBounds()) { return; + } - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.doPick(dc); - } - else - { + } else { this.draw(dc); } } @@ -702,24 +734,25 @@ public void render(DrawContext dc) * Determines if the scrollbar is able to draw within its bounds. * * @return {@code true} if the scroll bar is able to draw within the bounds, or {@code false} if the bounds are too - * small to draw without distortion. + * small to draw without distortion. */ - protected boolean canDrawInBounds() - { + protected boolean canDrawInBounds() { int arrowSize = this.getScrollArrowSize(); String orientation = this.getOrientation(); - if (AVKey.VERTICAL.equals(orientation)) + if (AVKey.VERTICAL.equals(orientation)) { return this.bounds.height >= (arrowSize * 2 + this.getMinScrollKnobSize()) - && this.bounds.width >= arrowSize; - else + && this.bounds.width >= arrowSize; + } else { return this.bounds.width >= (arrowSize * 2 + this.getMinScrollKnobSize()) - && this.bounds.height >= arrowSize; + && this.bounds.height >= arrowSize; + } } - /** Compute the bounds of the scroll bar. */ - protected void computeBounds() - { + /** + * Compute the bounds of the scroll bar. + */ + protected void computeBounds() { int x1 = this.bounds.x; int y1 = this.bounds.y; @@ -728,11 +761,10 @@ protected void computeBounds() int scrollControlSize = this.getScrollArrowSize(); - if (AVKey.VERTICAL.equals(this.getOrientation())) - { + if (AVKey.VERTICAL.equals(this.getOrientation())) { this.scrollDownControlBounds = new Rectangle(x1, y1, scrollControlSize, scrollControlSize); this.scrollUpControlBounds = new Rectangle(x1, y2 - scrollControlSize, scrollControlSize, - scrollControlSize); + scrollControlSize); int scrollAreaHeight = this.bounds.height - 2 * scrollControlSize; int position = (int) (scrollAreaHeight * this.getValueAsPercentage()); @@ -740,23 +772,22 @@ protected void computeBounds() int knobEnd = y2 - scrollControlSize - position - this.getKnobSize(scrollAreaHeight); // Make sure the knob doesn't overlap the scroll down control - if (knobEnd < y1 + scrollControlSize) + if (knobEnd < y1 + scrollControlSize) { knobEnd = y1 + scrollControlSize; + } this.scrollKnobBounds = new Rectangle(x1, knobEnd - 1, scrollControlSize, - this.getKnobSize(scrollAreaHeight) + 1); + this.getKnobSize(scrollAreaHeight) + 1); this.scrollDownBarBounds = new Rectangle(x1, y1 + scrollControlSize, scrollControlSize, - knobEnd - y1 - scrollControlSize); + knobEnd - y1 - scrollControlSize); int knobStart = (int) this.scrollKnobBounds.getMaxY(); this.scrollUpBarBounds = new Rectangle(x1, knobStart, scrollControlSize, - this.scrollUpControlBounds.y - knobStart); - } - else - { + this.scrollUpControlBounds.y - knobStart); + } else { this.scrollUpControlBounds = new Rectangle(x1, y1, scrollControlSize, scrollControlSize); this.scrollDownControlBounds = new Rectangle(x2 - scrollControlSize, y1, scrollControlSize, - scrollControlSize); + scrollControlSize); int scrollAreaWidth = this.bounds.width - 2 * scrollControlSize; int position = (int) (scrollAreaWidth * this.getValueAsPercentage()); @@ -766,14 +797,15 @@ protected void computeBounds() this.scrollKnobBounds = new Rectangle(knobStart, y1, knobSize + 1, scrollControlSize); // Make sure the knob doesn't overlap the scroll right control - if (this.scrollKnobBounds.getMaxX() > x2 - scrollControlSize) + if (this.scrollKnobBounds.getMaxX() > x2 - scrollControlSize) { this.scrollKnobBounds.x = x2 - scrollControlSize - knobSize; + } this.scrollUpBarBounds = new Rectangle(x1 + scrollControlSize, y1, - this.scrollKnobBounds.x - scrollControlSize - x1, scrollControlSize); + this.scrollKnobBounds.x - scrollControlSize - x1, scrollControlSize); int knobEnd = (int) this.scrollKnobBounds.getMaxX(); this.scrollDownBarBounds = new Rectangle(knobEnd, y1, this.scrollDownControlBounds.x - knobEnd, - scrollControlSize); + scrollControlSize); } } @@ -782,14 +814,12 @@ protected void computeBounds() * * @param dc Current draw context. */ - protected void draw(DrawContext dc) - { + protected void draw(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler oglStack = new OGLStackHandler(); - try - { + try { oglStack.pushAttrib(gl, - GL2.GL_COLOR_BUFFER_BIT + GL2.GL_COLOR_BUFFER_BIT | GL2.GL_CURRENT_BIT | GL2.GL_LINE_BIT | GL2.GL_POLYGON_BIT); @@ -799,8 +829,7 @@ protected void draw(DrawContext dc) gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_LINE); - try - { + try { gl.glBegin(GL2.GL_QUADS); // Draw scroll bar frame this.drawQuad(dc, this.bounds); @@ -808,9 +837,7 @@ protected void draw(DrawContext dc) // Draw boxes for up and down arrows this.drawQuad(dc, this.scrollDownControlBounds); this.drawQuad(dc, this.scrollUpControlBounds); - } - finally - { + } finally { gl.glEnd(); } @@ -818,12 +845,13 @@ protected void draw(DrawContext dc) // Draw background gradient String gradientDirection; - if (AVKey.VERTICAL.equals(this.getOrientation())) + if (AVKey.VERTICAL.equals(this.getOrientation())) { gradientDirection = AVKey.HORIZONTAL; - else + } else { gradientDirection = AVKey.VERTICAL; + } TreeUtil.drawRectWithGradient(gl, this.scrollKnobBounds, this.knobColor2, this.knobColor1, - this.getOpacity(), gradientDirection); + this.getOpacity(), gradientDirection); // Draw a border around the knob OGLUtil.applyColor(gl, this.getLineColor(), this.getOpacity(), false); @@ -833,19 +861,14 @@ protected void draw(DrawContext dc) gl.glEnd(); gl.glPolygonMode(GL2.GL_FRONT_AND_BACK, GL2.GL_FILL); - if (AVKey.VERTICAL.equals(this.getOrientation())) - { + if (AVKey.VERTICAL.equals(this.getOrientation())) { this.drawTriangle(dc, 90, this.scrollUpControlBounds, arrowInsets); this.drawTriangle(dc, -90, this.scrollDownControlBounds, arrowInsets); - } - else - { + } else { this.drawTriangle(dc, 180, this.scrollUpControlBounds, arrowInsets); this.drawTriangle(dc, 0, this.scrollDownControlBounds, arrowInsets); } - } - finally - { + } finally { oglStack.pop(gl); } } @@ -855,11 +878,9 @@ protected void draw(DrawContext dc) * * @param dc Current draw context. */ - protected void doPick(DrawContext dc) - { + protected void doPick(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); @@ -872,9 +893,7 @@ protected void doPick(DrawContext dc) // The knob, for dragging this.drawPickableQuad(dc, this.scrollKnobControl, this.scrollKnobBounds); - } - finally - { + } finally { gl.glEnd(); this.pickSupport.endPicking(dc); @@ -886,12 +905,11 @@ protected void doPick(DrawContext dc) * Draw a filled quad in a unique pick color. This method must be called between {@code glBegin(GL.GL_QUADS)} and * {@code glEnd()}. * - * @param dc Current draw context. + * @param dc Current draw context. * @param pickObject User object to attach to the picked object. - * @param bounds Bounds of the quad. + * @param bounds Bounds of the quad. */ - protected void drawPickableQuad(DrawContext dc, Object pickObject, Rectangle bounds) - { + protected void drawPickableQuad(DrawContext dc, Object pickObject, Rectangle bounds) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Color color = dc.getUniquePickColor(); @@ -906,11 +924,10 @@ protected void drawPickableQuad(DrawContext dc, Object pickObject, Rectangle bou * Draw the vertices of a quadrilateral. This method must be called between {@code glBegin(GL.GL_QUADS)} and {@code * glEnd()}. * - * @param dc Current draw context. + * @param dc Current draw context. * @param bounds Bounds of the quad. */ - protected void drawQuad(DrawContext dc, Rectangle bounds) - { + protected void drawQuad(DrawContext dc, Rectangle bounds) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int minX = (int) bounds.getMinX(); @@ -927,47 +944,38 @@ protected void drawQuad(DrawContext dc, Rectangle bounds) /** * Draw a triangle for one of the scroll bar controls. * - * @param dc Draw context. + * @param dc Draw context. * @param rotation Rotation to apply to the triangle. 0 rotation produces a triangle pointing to the right. Rotation - * must be one of: 0, 90, -90, or 180. - * @param bounds The bounds of the scroll control. The arrow must be drawn within this rectangle. - * @param insets Insets to apply to the bounds. + * must be one of: 0, 90, -90, or 180. + * @param bounds The bounds of the scroll control. The arrow must be drawn within this rectangle. + * @param insets Insets to apply to the bounds. */ - protected void drawTriangle(DrawContext dc, float rotation, Rectangle bounds, Insets insets) - { + protected void drawTriangle(DrawContext dc, float rotation, Rectangle bounds, Insets insets) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { gl.glPushMatrix(); // Apply the inset to the bounds. Rectangle insetBounds = new Rectangle(bounds.x + insets.left, bounds.y + insets.bottom, - bounds.width - insets.left - insets.right, - bounds.height - insets.top - insets.bottom); + bounds.width - insets.left - insets.right, + bounds.height - insets.top - insets.bottom); float halfHeight = insetBounds.height / 2.0f; float halfWidth = insetBounds.width / 2.0f; float adjustX = 0; float adjustY = 0; - if (rotation == 90) - { + if (rotation == 90) { adjustX = halfWidth; adjustY = (insetBounds.height - halfWidth) / 2.0f; - } - else if (rotation == -90) - { + } else if (rotation == -90) { adjustX = halfWidth; adjustY = (insetBounds.height - halfWidth) / 2.0f + halfWidth; - } - else if (rotation == 0) - { + } else if (rotation == 0) { adjustX = (insetBounds.width - halfWidth) / 2.0f; adjustY = halfHeight; - } - else if (rotation == 180) - { + } else if (rotation == 180) { adjustX = (insetBounds.width - halfWidth) / 2.0f + halfWidth; adjustY = halfHeight; } @@ -980,9 +988,7 @@ else if (rotation == 180) gl.glVertex2f(halfWidth, 0); gl.glVertex2f(0, -halfHeight); gl.glEnd(); - } - finally - { + } finally { gl.glPopMatrix(); } } @@ -990,56 +996,58 @@ else if (rotation == 180) //**************************************************************// //***************** User input handling ***********************// //**************************************************************// + /** + * Control for the scroll arrows and areas of the scroll bar above and below the knob. + */ + public class ScrollControl extends TreeHotSpot { - /** Control for the scroll arrows and areas of the scroll bar above and below the knob. */ - public class ScrollControl extends TreeHotSpot - { protected ScrollBar scrollBar; protected String adjustment; - public ScrollControl(HotSpot parent, ScrollBar owner, String adjustment) - { + public ScrollControl(HotSpot parent, ScrollBar owner, String adjustment) { super(parent); this.scrollBar = owner; this.adjustment = adjustment; } @Override - public void mousePressed(MouseEvent event) - { - if (event == null || event.isConsumed()) + public void mousePressed(MouseEvent event) { + if (event == null || event.isConsumed()) { return; + } - if (event.getButton() == MouseEvent.BUTTON1) + if (event.getButton() == MouseEvent.BUTTON1) { scrollBar.startAutoScroll(this.adjustment); + } } @Override - public void mouseReleased(MouseEvent event) - { - if (event == null || event.isConsumed()) + public void mouseReleased(MouseEvent event) { + if (event == null || event.isConsumed()) { return; + } - if (event.getButton() == MouseEvent.BUTTON1) + if (event.getButton() == MouseEvent.BUTTON1) { this.scrollBar.stopAutoScroll(); + } } @Override - public void selected(SelectEvent event) - { + public void selected(SelectEvent event) { // Overridden to prevent the super class passing the event to a parent component - if (event == null || event.isConsumed()) + if (event == null || event.isConsumed()) { return; + } // Consume drag events to prevent the globe from panning in response to the drag. - if (event.isDrag()) + if (event.isDrag()) { event.consume(); + } } @Override - public void mouseClicked(MouseEvent event) - { + public void mouseClicked(MouseEvent event) { // Don't let super class pass this event to parent component } @@ -1049,58 +1057,53 @@ public void mouseClicked(MouseEvent event) * Overridden to stop autoscroll operations when the scrollbar becomes inactive. * * @param active {@code true} if the scrollbar is being activated, {@code false} if the scrollbar is being - * deactivated. + * deactivated. */ @Override - public void setActive(boolean active) - { + public void setActive(boolean active) { // If the scrollbar is being deactivated, stop any autoscroll operations that are in progress. When the // scrollbar is inactive it will not receive mouse events, so it will not be able to stop the scroll // operation when the mouse is released. - if (!active) + if (!active) { this.scrollBar.stopAutoScroll(); + } super.setActive(active); } } - /** Control for dragging the scroll knob. */ - public class ScrollKnob extends DragControl - { + /** + * Control for dragging the scroll knob. + */ + public class ScrollKnob extends DragControl { + protected ScrollBar scrollBar; protected int dragRefValue; - public ScrollKnob(HotSpot parent, ScrollBar owner) - { + public ScrollKnob(HotSpot parent, ScrollBar owner) { super(parent); this.scrollBar = owner; } @Override - public void mouseClicked(MouseEvent event) - { + public void mouseClicked(MouseEvent event) { // Don't let super class pass this event to parent component } @Override - protected void beginDrag(Point point) - { + protected void beginDrag(Point point) { super.beginDrag(point); this.dragRefValue = this.scrollBar.getValue(); } - protected void drag(Point point) - { + protected void drag(Point point) { int delta; int adjustment; int screenDimension; - if (AVKey.VERTICAL.equals(scrollBar.getOrientation())) - { + if (AVKey.VERTICAL.equals(scrollBar.getOrientation())) { delta = point.y - this.dragRefPoint.y; screenDimension = this.scrollBar.scrollBounds.height - this.scrollBar.getMinScrollKnobSize(); - } - else - { + } else { delta = point.x - this.dragRefPoint.x; screenDimension = this.scrollBar.scrollBounds.width; } diff --git a/src/gov/nasa/worldwind/util/tree/ScrollFrame.java b/src/gov/nasa/worldwind/util/tree/ScrollFrame.java index 7f9033f25f..3e769e5991 100644 --- a/src/gov/nasa/worldwind/util/tree/ScrollFrame.java +++ b/src/gov/nasa/worldwind/util/tree/ScrollFrame.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import com.jogamp.opengl.util.texture.*; @@ -37,33 +36,57 @@ * @author pabercrombie * @version $Id: ScrollFrame.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class ScrollFrame extends DragControl implements PreRenderable, Renderable -{ - /** Default dimension of tiles in the backing texture. */ +public class ScrollFrame extends DragControl implements PreRenderable, Renderable { + + /** + * Default dimension of tiles in the backing texture. + */ protected static final int DEFAULT_TEXTURE_TILE_DIMENSION = 512; - /** Default height of the frame title bar. */ + /** + * Default height of the frame title bar. + */ protected static final int DEFAULT_TITLE_BAR_HEIGHT = 25; - /** Default size of the minimize button. */ + /** + * Default size of the minimize button. + */ protected static final int DEFAULT_BUTTON_SIZE = 18; - /** Default width of the scroll bars. */ + /** + * Default width of the scroll bars. + */ protected static final int DEFAULT_SCROLL_BAR_SIZE = 15; - /** Default width of the frame border. */ + /** + * Default width of the frame border. + */ protected static final int DEFAULT_FRAME_BORDER_WIDTH = 3; - /** Default width of the pickable frame border. */ + /** + * Default width of the pickable frame border. + */ protected static final int DEFAULT_FRAME_BORDER_PICK_WIDTH = 10; - /** Default width of lines used to draw the frame. */ + /** + * Default width of lines used to draw the frame. + */ protected static final int DEFAULT_LINE_WIDTH = 1; - /** Default delay (in milliseconds) between frame when the frame is animating. */ + /** + * Default delay (in milliseconds) between frame when the frame is animating. + */ protected static final int DEFAULT_ANIMATION_DELAY = 5; - /** Default size of the maximized frame. */ + /** + * Default size of the maximized frame. + */ protected static final Size DEFAULT_MAXIMIZED_SIZE = Size.fromPixels(265, 300); - /** Attributes to use when the frame is not highlighted. */ + /** + * Attributes to use when the frame is not highlighted. + */ protected FrameAttributes normalAttributes; - /** Attributes to use when the frame is highlighted. */ + /** + * Attributes to use when the frame is highlighted. + */ protected FrameAttributes highlightAttributes; - /** Active attributes, either normal or highlight. */ + /** + * Active attributes, either normal or highlight. + */ protected FrameAttributes activeAttributes = new BasicFrameAttributes(); // re-determined each frame /** @@ -72,76 +95,134 @@ public class ScrollFrame extends DragControl implements PreRenderable, Renderabl */ protected String frameTitle; - /** The contents of the frame. */ + /** + * The contents of the frame. + */ protected Scrollable contents; - /** Indicates the location of the upper left corner of the frame. */ + /** + * Indicates the location of the upper left corner of the frame. + */ protected Offset screenLocation; - /** Indicates whether or not to draw a title bar in the frame. Default is true. */ + /** + * Indicates whether or not to draw a title bar in the frame. Default is true. + */ protected boolean drawTitleBar = true; - /** Indicates whether or not the user can resize the frame by dragging the edge. Default is true. */ + /** + * Indicates whether or not the user can resize the frame by dragging the edge. Default is true. + */ protected boolean enableResize = true; - /** Indicates whether or not the user can move the frame by dragging with the mouse. Default is true. */ + /** + * Indicates whether or not the user can move the frame by dragging with the mouse. Default is true. + */ protected boolean enableMove = true; - /** The height, in pixels, of the frame title bar. */ + /** + * The height, in pixels, of the frame title bar. + */ protected int titleBarHeight = DEFAULT_TITLE_BAR_HEIGHT; - /** The size, in pixels, of the frame's minimize button. */ + /** + * The size, in pixels, of the frame's minimize button. + */ protected int buttonSize = DEFAULT_BUTTON_SIZE; - /** The width of the frame scroll bar. */ + /** + * The width of the frame scroll bar. + */ protected int scrollBarSize = DEFAULT_SCROLL_BAR_SIZE; - /** The width of the frame border. */ + /** + * The width of the frame border. + */ protected int frameBorder = DEFAULT_FRAME_BORDER_WIDTH; - /** The width of lines used to draw the frame. */ + /** + * The width of lines used to draw the frame. + */ protected int frameLineWidth = DEFAULT_LINE_WIDTH; - /** Support for setting up and restoring OpenGL state during rendering. */ + /** + * Support for setting up and restoring OpenGL state during rendering. + */ protected OGLStackHandler BEogsh = new OGLStackHandler(); - /** Support for setting up and restoring picking state, and resolving the picked object. */ + /** + * Support for setting up and restoring picking state, and resolving the picked object. + */ protected PickSupport pickSupport = new PickSupport(); - /** Scroll bar to control vertical scrolling. */ + /** + * Scroll bar to control vertical scrolling. + */ protected ScrollBar verticalScrollBar; - /** Scroll bar to control horizontal scrolling. */ + /** + * Scroll bar to control horizontal scrolling. + */ protected ScrollBar horizontalScrollBar; - /** Indicates whether or not the frame is minimized. */ + /** + * Indicates whether or not the frame is minimized. + */ protected boolean minimized = false; - /** The size of the maximized frame. */ + /** + * The size of the maximized frame. + */ protected Size maximizedSize = DEFAULT_MAXIMIZED_SIZE; - /** The size of the minimized frame. */ + /** + * The size of the minimized frame. + */ protected Size minimizedSize; - /** The size of the active frame, minimized or maximized. */ + /** + * The size of the active frame, minimized or maximized. + */ protected Size activeSize; - /** The maximum size of the frame. This is a constraint applied to the frame's size. */ + /** + * The maximum size of the frame. This is a constraint applied to the frame's size. + */ protected Size maxSize; - /** Image source for the icon drawn in the upper left corner of the frame. */ + /** + * Image source for the icon drawn in the upper left corner of the frame. + */ protected Object iconImageSource; - /** Texture for the icon displayed in the frame title bar. Loaded from {@link #iconImageSource}. */ + /** + * Texture for the icon displayed in the frame title bar. Loaded from {@link #iconImageSource}. + */ protected BasicWWTexture texture; - /** An animation to play when the frame is minimized or maximized. */ + /** + * An animation to play when the frame is minimized or maximized. + */ protected Animation minimizeAnimation; - /** The active animation that is currently playing. */ + /** + * The active animation that is currently playing. + */ protected Animation animation; - /** Delay in milliseconds between frames of an animation. */ + /** + * Delay in milliseconds between frames of an animation. + */ protected int animationDelay = DEFAULT_ANIMATION_DELAY; // UI controls - /** HotSpot to handle user input on the minimize button. */ + /** + * HotSpot to handle user input on the minimize button. + */ protected HotSpot minimizeButton; - /** Control to handle resizing the frame. */ + /** + * Control to handle resizing the frame. + */ protected FrameResizeControl frameResizeControl; - /** Width of the pickable frame border. */ + /** + * Width of the pickable frame border. + */ protected int borderPickWidth = DEFAULT_FRAME_BORDER_PICK_WIDTH; - /** The frame geometry vertices passed to OpenGL. */ + /** + * The frame geometry vertices passed to OpenGL. + */ protected DoubleBuffer vertexBuffer; - /** Support class used to render to an offscreen texture. */ + /** + * Support class used to render to an offscreen texture. + */ protected OGLRenderToTextureSupport rttSupport = new OGLRenderToTextureSupport(); protected List tiles = new ArrayList(); /** @@ -151,7 +232,9 @@ public class ScrollFrame extends DragControl implements PreRenderable, Renderabl */ protected boolean renderToTexture; - /** Cache key used to locate the rendering texture in the DrawContext's texture cache. */ + /** + * Cache key used to locate the rendering texture in the DrawContext's texture cache. + */ protected final Object textureCacheKey = new Object(); /** @@ -159,9 +242,13 @@ public class ScrollFrame extends DragControl implements PreRenderable, Renderabl * the content. */ protected Map textureTileMap = new HashMap(); - /** List to manage sub-tiles of the rendering texture. */ + /** + * List to manage sub-tiles of the rendering texture. + */ protected List textureTiles = new ArrayList(); - /** Dimension of the texture used to render the scrollable content. Must be a power of two. */ + /** + * Dimension of the texture used to render the scrollable content. Must be a power of two. + */ protected int textureDimension; /** * Dimension of a sub-tile in the rendering texture. Also the dimension of logical tiles in the scrollable content @@ -176,56 +263,82 @@ public class ScrollFrame extends DragControl implements PreRenderable, Renderabl * title will be truncated. This title must be regenerated if the frame size or the title font change. */ protected String shortTitle; - /** Width of the frame title area. */ + /** + * Width of the frame title area. + */ protected int frameTitleWidth; - /** Font used to generate {@link #shortTitle}. */ + /** + * Font used to generate {@link #shortTitle}. + */ protected Font shortFrameTitleFont; - /** Text bounds of the {@link #shortTitle}. */ + /** + * Text bounds of the {@link #shortTitle}. + */ protected Rectangle2D shortTitleBounds; // Computed each frame protected long frameNumber = -1; - /** Indicates that the frame must be regenerated because the size or attributes have changed. */ + /** + * Indicates that the frame must be regenerated because the size or attributes have changed. + */ protected boolean mustRecomputeFrameGeometry = true; /** * Indicates the location of the upper left corner of the frame, in AWT coordinates (origin at the upper left corner * of the screen. */ protected Point2D awtScreenPoint; - /** Bounds of the full frame. */ + /** + * Bounds of the full frame. + */ protected Rectangle frameBounds; - /** Bounds of the frame inside the frame border. */ + /** + * Bounds of the frame inside the frame border. + */ protected Rectangle innerBounds; - /** Bounds of the content part of the frame. */ + /** + * Bounds of the content part of the frame. + */ protected Rectangle contentBounds; protected Rectangle scrollContentBounds; - /** Bounds of the pickable area. */ + /** + * Bounds of the pickable area. + */ protected Rectangle pickBounds; /** * Total size of the frame content. This size may exceed the size of the frame, in which case scroll bars will be * displayed. */ protected Dimension contentSize; - /** Size of the frame. */ + /** + * Size of the frame. + */ protected Dimension frameSize; - /** Indicates whether or not the frame is highlighted. */ + /** + * Indicates whether or not the frame is highlighted. + */ protected boolean highlighted; - /** Indicates whether or not the vertical scroll bar must be drawn. */ + /** + * Indicates whether or not the vertical scroll bar must be drawn. + */ protected boolean showVerticalScrollbar; - /** Indicates whether or not the horizontal scroll bar must be drawn. */ + /** + * Indicates whether or not the horizontal scroll bar must be drawn. + */ protected boolean showHorizontalScrollbar; - /** The attributes used if attributes are not specified. */ + /** + * The attributes used if attributes are not specified. + */ protected static final FrameAttributes defaultAttributes; - static - { + static { defaultAttributes = new BasicFrameAttributes(); } - /** Create a new scroll frame. */ - public ScrollFrame() - { + /** + * Create a new scroll frame. + */ + public ScrollFrame() { super(null); this.initializeUIControls(); } @@ -234,12 +347,11 @@ public ScrollFrame() * Create a scroll frame with a position. * * @param x x coordinate of the upper left corner of the frame, in AWT screen coordinates (origin upper left corner - * of the screen). + * of the screen). * @param y y coordinate of the upper left corner of the frame, in AWT screen coordinates (origin upper left corner - * of the screen). + * of the screen). */ - public ScrollFrame(int x, int y) - { + public ScrollFrame(int x, int y) { this(new Offset((double) x, (double) y, AVKey.PIXELS, AVKey.INSET_PIXELS)); } @@ -248,8 +360,7 @@ public ScrollFrame(int x, int y) * * @param screenLocation initial location of the upper left corner of the frame. */ - public ScrollFrame(Offset screenLocation) - { + public ScrollFrame(Offset screenLocation) { super(null); this.setScreenLocation(screenLocation); this.initializeUIControls(); @@ -260,8 +371,7 @@ public ScrollFrame(Offset screenLocation) * * @return the contents of the frame. */ - public Scrollable getContents() - { + public Scrollable getContents() { return contents; } @@ -270,8 +380,7 @@ public Scrollable getContents() * * @param contents new frame contents. */ - public void setContents(Scrollable contents) - { + public void setContents(Scrollable contents) { this.contents = contents; } @@ -281,8 +390,7 @@ public void setContents(Scrollable contents) * * @return {@code true} if the frame is minimized. */ - public boolean isMinimized() - { + public boolean isMinimized() { return this.minimized; } @@ -292,13 +400,10 @@ public boolean isMinimized() * * @param minimized {@code true} if the frame must be minimized. {@code false} if the frame must not be minimized. */ - public void setMinimized(boolean minimized) - { - if (minimized != this.isMinimized()) - { + public void setMinimized(boolean minimized) { + if (minimized != this.isMinimized()) { this.minimized = minimized; - if (this.minimizeAnimation != null) - { + if (this.minimizeAnimation != null) { this.animation = this.minimizeAnimation; this.animation.reset(); } @@ -310,8 +415,7 @@ public void setMinimized(boolean minimized) * * @return {@code true} if the frame is highlighted, otherwise {@code false}. */ - public boolean isHighlighted() - { + public boolean isHighlighted() { return this.highlighted; } @@ -320,10 +424,8 @@ public boolean isHighlighted() * * @param highlighted {@code true} if the frame is now highlighted. */ - public void setHighlighted(boolean highlighted) - { - if (this.highlighted != highlighted) - { + public void setHighlighted(boolean highlighted) { + if (this.highlighted != highlighted) { this.highlighted = highlighted; this.contents.setHighlighted(highlighted); @@ -337,8 +439,7 @@ public void setHighlighted(boolean highlighted) * * @see #setFrameTitle(String) */ - public String getFrameTitle() - { + public String getFrameTitle() { return this.frameTitle; } @@ -349,8 +450,7 @@ public String getFrameTitle() * * @see #getFrameTitle() */ - public void setFrameTitle(String frameTitle) - { + public void setFrameTitle(String frameTitle) { this.frameTitle = frameTitle; // Invalidate the computed title for display. It will be regenerated the next time the frame is rendered. @@ -364,8 +464,7 @@ public void setFrameTitle(String frameTitle) * * @see #getMinimizedSize() */ - public Size getSize() - { + public Size getSize() { return this.maximizedSize; } @@ -376,10 +475,8 @@ public Size getSize() * * @see #setMinimizedSize(gov.nasa.worldwind.render.Size) */ - public void setSize(Size size) - { - if (size == null) - { + public void setSize(Size size) { + if (size == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -388,18 +485,18 @@ public void setSize(Size size) this.maximizedSize = size; this.mustRecomputeFrameGeometry = true; - if (!this.isAnimating()) + if (!this.isAnimating()) { this.forceTileUpdate(); + } } /** * Indicates the size of the minimized tree frame. This size is used when the tree is minimized or animating. * * @return the size of the minimized frame. {@code null} indicates that there is no minimized size, in which case - * the normal maximized frame size is used in the minimized state. + * the normal maximized frame size is used in the minimized state. */ - public Size getMinimizedSize() - { + public Size getMinimizedSize() { return this.minimizedSize; } @@ -409,15 +506,15 @@ public Size getMinimizedSize() * the frame's normal maximized size. * * @param size the size of the minimized frame. Set {@code null} to use the same size in maximized and minimized - * states. + * states. */ - public void setMinimizedSize(Size size) - { + public void setMinimizedSize(Size size) { this.minimizedSize = size; this.mustRecomputeFrameGeometry = true; - if (!this.isAnimating()) + if (!this.isAnimating()) { this.forceTileUpdate(); + } } /** @@ -426,8 +523,7 @@ public void setMinimizedSize(Size size) * * @return the maximum size of the frame. {@code null} indicates no maximum. */ - public Size getMaxSize() - { + public Size getMaxSize() { return this.maxSize; } @@ -437,13 +533,13 @@ public Size getMaxSize() * * @param size the maximum size of the minimized frame. Set {@code null} for no maximum. */ - public void setMaxSize(Size size) - { + public void setMaxSize(Size size) { this.maxSize = size; this.mustRecomputeFrameGeometry = true; - if (!this.isAnimating()) + if (!this.isAnimating()) { this.forceTileUpdate(); + } } /** @@ -451,10 +547,9 @@ public void setMaxSize(Size size) * window resize, or an animation. * * @return The size of the frame on screen, in pixels. This method will return null until the frame has been - * rendered at least once. + * rendered at least once. */ - public Dimension getCurrentSize() - { + public Dimension getCurrentSize() { return this.frameSize; } @@ -465,8 +560,7 @@ public Dimension getCurrentSize() * * @see #isDrawTitleBar() */ - public int getTitleBarHeight() - { + public int getTitleBarHeight() { return this.titleBarHeight; } @@ -475,10 +569,8 @@ public int getTitleBarHeight() * * @param titleBarHeight new height, in pixels. */ - public void setTitleBarHeight(int titleBarHeight) - { - if (titleBarHeight < 0) - { + public void setTitleBarHeight(int titleBarHeight) { + if (titleBarHeight < 0) { String message = Logging.getMessage("generic.InvalidHeight", titleBarHeight); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -492,8 +584,7 @@ public void setTitleBarHeight(int titleBarHeight) * * @return True if the frame will draw a title bar. */ - public boolean isDrawTitleBar() - { + public boolean isDrawTitleBar() { return this.drawTitleBar; } @@ -504,8 +595,7 @@ public boolean isDrawTitleBar() * * @see #setTitleBarHeight(int) */ - public void setDrawTitleBar(boolean drawTitleBar) - { + public void setDrawTitleBar(boolean drawTitleBar) { this.drawTitleBar = drawTitleBar; } @@ -514,8 +604,7 @@ public void setDrawTitleBar(boolean drawTitleBar) * * @return {@code true} if the user can resize the frame by dragging. */ - public boolean isEnableResizeControl() - { + public boolean isEnableResizeControl() { return this.enableResize; } @@ -524,8 +613,7 @@ public boolean isEnableResizeControl() * * @param enable {@code true} to allow the user to resize the frame by dragging the border. */ - public void setEnableResizeControl(boolean enable) - { + public void setEnableResizeControl(boolean enable) { this.enableResize = enable; } @@ -534,8 +622,7 @@ public void setEnableResizeControl(boolean enable) * * @return {@code true} if the user can allowed to move the frame by dragging the title bar. */ - public boolean isEnableMove() - { + public boolean isEnableMove() { return this.enableMove; } @@ -544,8 +631,7 @@ public boolean isEnableMove() * * @param enable {@code true} if the user is allowed to move the frame by dragging. */ - public void setEnableMove(boolean enable) - { + public void setEnableMove(boolean enable) { this.enableMove = enable; } @@ -556,8 +642,7 @@ public void setEnableMove(boolean enable) * * @see #setMinimizeAnimation(Animation) */ - public Animation getMinimizeAnimation() - { + public Animation getMinimizeAnimation() { return minimizeAnimation; } @@ -568,8 +653,7 @@ public Animation getMinimizeAnimation() * * @see #getMinimizeAnimation() */ - public void setMinimizeAnimation(Animation minimizeAnimation) - { + public void setMinimizeAnimation(Animation minimizeAnimation) { this.minimizeAnimation = minimizeAnimation; } @@ -580,8 +664,7 @@ public void setMinimizeAnimation(Animation minimizeAnimation) * * @see #setIconImageSource(Object) */ - public Object getIconImageSource() - { + public Object getIconImageSource() { return this.iconImageSource; } @@ -590,8 +673,7 @@ public Object getIconImageSource() * * @param imageSource New image source. May be a String, URL, or BufferedImage. */ - public void setIconImageSource(Object imageSource) - { + public void setIconImageSource(Object imageSource) { this.iconImageSource = imageSource; } @@ -602,12 +684,11 @@ public void setIconImageSource(Object imageSource) * * @return The bounds of the tree frame on screen, in screen coordinates (origin at upper left). */ - public Rectangle getBounds(DrawContext dc) - { + public Rectangle getBounds(DrawContext dc) { this.updateBounds(dc); return new Rectangle((int) this.awtScreenPoint.getX(), (int) this.awtScreenPoint.getY(), this.frameSize.width, - this.frameSize.height); + this.frameSize.height); } /** @@ -616,8 +697,7 @@ public Rectangle getBounds(DrawContext dc) * * @return Screen location, measured in pixels from the upper left corner of the screen. */ - public Offset getScreenLocation() - { + public Offset getScreenLocation() { return this.screenLocation; } @@ -627,8 +707,7 @@ public Offset getScreenLocation() * * @param screenLocation New screen location. */ - public void setScreenLocation(Offset screenLocation) - { + public void setScreenLocation(Offset screenLocation) { this.screenLocation = screenLocation; } @@ -636,10 +715,9 @@ public void setScreenLocation(Offset screenLocation) * Get the location of the upper left corner of the frame, measured from the upper left corner of the screen. * * @return The location of the upper left corner of the frame. This method will return null until the has been - * rendered. + * rendered. */ - protected Point2D getScreenPoint() - { + protected Point2D getScreenPoint() { return this.awtScreenPoint; } @@ -648,8 +726,7 @@ protected Point2D getScreenPoint() * * @return normal frame attributes. */ - public FrameAttributes getAttributes() - { + public FrameAttributes getAttributes() { return this.normalAttributes; } @@ -658,10 +735,8 @@ public FrameAttributes getAttributes() * * @param attributes new attributes bundle for normal state. */ - public void setAttributes(FrameAttributes attributes) - { - if (attributes == null) - { + public void setAttributes(FrameAttributes attributes) { + if (attributes == null) { String msg = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -675,8 +750,7 @@ public void setAttributes(FrameAttributes attributes) * * @return highlight frame attributes. */ - public FrameAttributes getHighlightAttributes() - { + public FrameAttributes getHighlightAttributes() { return this.highlightAttributes; } @@ -685,10 +759,8 @@ public FrameAttributes getHighlightAttributes() * * @param attributes new attributes bundle for highlight state. */ - public void setHighlightAttributes(FrameAttributes attributes) - { - if (attributes == null) - { + public void setHighlightAttributes(FrameAttributes attributes) { + if (attributes == null) { String msg = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -700,21 +772,17 @@ public void setHighlightAttributes(FrameAttributes attributes) //**************************************************************// //******************** Tile Updating *************************// //**************************************************************// - /** * Build the list of ContentTile that represents the logical tiles in the frame contents. * - * @param rows Number of rows of tiles in the contents. + * @param rows Number of rows of tiles in the contents. * @param columns Number of columns of tiles. */ - protected void assembleTiles(int rows, int columns) - { + protected void assembleTiles(int rows, int columns) { this.tiles.clear(); - for (int i = 0; i < rows; i++) - { - for (int j = 0; j < columns; j++) - { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { ContentTile newTile = new ContentTile(i, j); this.tiles.add(newTile); } @@ -728,25 +796,27 @@ protected void assembleTiles(int rows, int columns) * * @return {@code true} if any of the tiles need to be updated. */ - protected boolean mustUpdateTiles(DrawContext dc) - { + protected boolean mustUpdateTiles(DrawContext dc) { // Tiles are not visible if the frame is minimized, so no reason to update - if (this.isMinimized()) + if (this.isMinimized()) { return false; + } // Make sure that our texture is available. If the texture has been evicted it will need to be regenerated. - if (dc.getTextureCache().getTexture(this.textureCacheKey) == null) + if (dc.getTextureCache().getTexture(this.textureCacheKey) == null) { return true; + } - if (tiles.isEmpty()) + if (tiles.isEmpty()) { return true; + } long contentUpdateTime = this.contents.getUpdateTime(); - for (ContentTile tile : this.tiles) - { - if (this.mustUpdateTile(tile, contentUpdateTime)) + for (ContentTile tile : this.tiles) { + if (this.mustUpdateTile(tile, contentUpdateTime)) { return true; + } } return false; } @@ -754,23 +824,23 @@ protected boolean mustUpdateTiles(DrawContext dc) /** * Determine if a tile in the content layout needs to be updated. * - * @param tile Tile to test. + * @param tile Tile to test. * @param contentUpdateTime Time at which the content was last updated. * * @return {@code true} if the tile needs to be updated. Always returns {@code false} if the tile is not visible in - * the current frame bounds. + * the current frame bounds. */ - protected boolean mustUpdateTile(ContentTile tile, long contentUpdateTime) - { + protected boolean mustUpdateTile(ContentTile tile, long contentUpdateTime) { Rectangle tileBounds = this.getContentTileBounds(tile.row, tile.column); - if (this.contentBounds.intersects(tileBounds)) - { - if (tile.updateTime != contentUpdateTime) + if (this.contentBounds.intersects(tileBounds)) { + if (tile.updateTime != contentUpdateTime) { return true; + } TextureTile textureTile = this.getTextureTile(tile); - if (textureTile == null) + if (textureTile == null) { return true; + } } return false; @@ -781,8 +851,7 @@ protected boolean mustUpdateTile(ContentTile tile, long contentUpdateTime) * * @param dc Current draw context. */ - protected void updateTiles(DrawContext dc) - { + protected void updateTiles(DrawContext dc) { // The OpenGL framebuffer object extension used by RenderToTextureSupport works only for texture formats // GL_RGB and GL_RGBA. this.rttSupport.setEnableFramebufferObject(true); @@ -797,14 +866,12 @@ protected void updateTiles(DrawContext dc) this.renderToTexture = (dim <= maxTexture); // If the frame is too big to render into a texture don't bother building tiles - if (!this.renderToTexture) - { + if (!this.renderToTexture) { return; } // If we don't have a texture, or if we need a different size of texture, allocate a new one - if (texture == null || this.textureDimension != dim) - { + if (texture == null || this.textureDimension != dim) { texture = this.createTileTexture(dc, dim, dim); dc.getTextureCache().put(this.textureCacheKey, texture); this.textureDimension = dim; @@ -814,10 +881,8 @@ protected void updateTiles(DrawContext dc) // Create entries for the sub-tiles in the texture. Each sub-tile will be used to render a piece of the // frame contents. this.textureTiles.clear(); - for (int i = 0; i < numTiles; i++) - { - for (int j = 0; j < numTiles; j++) - { + for (int i = 0; i < numTiles; i++) { + for (int j = 0; j < numTiles; j++) { this.textureTiles.add(new TextureTile(i, j)); } } @@ -834,21 +899,17 @@ protected void updateTiles(DrawContext dc) int rows = (int) Math.ceil((double) this.contentSize.height / this.textureTileDimension); int columns = (int) Math.ceil((double) this.contentSize.width / this.textureTileDimension); - if (tiles.size() != rows * columns) - { + if (tiles.size() != rows * columns) { this.assembleTiles(rows, columns); } long contentUpdateTime = this.contents.getUpdateTime(); // Update each tile that needs updating - for (ContentTile tile : this.tiles) - { - if (this.mustUpdateTile(tile, contentUpdateTime)) - { + for (ContentTile tile : this.tiles) { + if (this.mustUpdateTile(tile, contentUpdateTime)) { TextureTile textureTile = this.getTextureTile(tile); - if (textureTile == null) - { + if (textureTile == null) { textureTile = this.allocateTextureTile(tile); } @@ -858,15 +919,12 @@ protected void updateTiles(DrawContext dc) Rectangle tileBounds = new Rectangle(x, y, this.textureTileDimension, this.textureTileDimension); this.rttSupport.beginRendering(dc, tileBounds.x, tileBounds.y, tileBounds.width, tileBounds.height); - try - { + try { this.updateTile(dc, tile, tileBounds); tile.updateTime = contentUpdateTime; textureTile.lastUsed = dc.getFrameTimeStamp(); - } - finally - { + } finally { this.rttSupport.endRendering(dc); } } @@ -880,11 +938,9 @@ protected void updateTiles(DrawContext dc) * * @return TextureTile allocated for the given ContentTile, or {@code null} if no TextureTile has been allocated. */ - protected TextureTile getTextureTile(ContentTile tile) - { + protected TextureTile getTextureTile(ContentTile tile) { TextureTile textureTile = this.textureTileMap.get(tile); - if (textureTile != null && textureTile.currentTile.equals(tile)) - { + if (textureTile != null && textureTile.currentTile.equals(tile)) { return textureTile; } @@ -899,8 +955,7 @@ protected TextureTile getTextureTile(ContentTile tile) * * @return TextureTile allocated for the ScrollableTile. */ - protected TextureTile allocateTextureTile(ContentTile tile) - { + protected TextureTile allocateTextureTile(ContentTile tile) { // Sort the list of texture tiles so that we can find the one that is the least recently used. TextureTile[] timeOrderedEntries = new TextureTile[this.textureTiles.size()]; Arrays.sort(this.textureTiles.toArray(timeOrderedEntries)); @@ -917,37 +972,33 @@ protected TextureTile allocateTextureTile(ContentTile tile) /** * Draws the current list of ScrollableTiles into the texture tiles. The tiles are updated when necessary. * - * @param dc the draw context the tile relates to. - * @param tile the tile to update. A new texture tile will be allocated for the tile, if the tile does not - * have a texture. + * @param dc the draw context the tile relates to. + * @param tile the tile to update. A new texture tile will be allocated for the tile, if the tile does not have a + * texture. * @param tileBounds bounds of the tile being updated, within the larger texture. */ - protected void updateTile(DrawContext dc, ContentTile tile, Rectangle tileBounds) - { + protected void updateTile(DrawContext dc, ContentTile tile, Rectangle tileBounds) { int x = tileBounds.x - tile.column * this.textureTileDimension; int y = tileBounds.y - this.contentSize.height + this.textureTileDimension * (tile.row + 1); Rectangle scrollBounds = new Rectangle(x, y, this.contentBounds.width, this.textureTileDimension); - try - { + try { Texture texture = dc.getTextureCache().getTexture(this.textureCacheKey); this.rttSupport.setColorTarget(dc, texture); this.rttSupport.clear(dc, new Color(0, 0, 0, 0)); // Set all texture pixels to transparent black. this.contents.renderScrollable(dc, scrollBounds.getLocation(), scrollBounds.getSize(), tileBounds); - } - finally - { + } finally { this.rttSupport.setColorTarget(dc, null); } } - /** Force all tiles to update on the next frame. */ - protected void forceTileUpdate() - { - for (ContentTile tile : tiles) - { + /** + * Force all tiles to update on the next frame. + */ + protected void forceTileUpdate() { + for (ContentTile tile : tiles) { tile.updateTime = -1; } } @@ -958,25 +1009,24 @@ protected void forceTileUpdate() * The returned texture's internal format is RGBA8. * * @param dc The draw context. - * @param width the texture's width, in pixels. + * @param width the texture's width, in pixels. * @param height the texture's height, in pixels. * * @return a new texture with the specified width and height. */ - protected Texture createTileTexture(DrawContext dc, int width, int height) - { + protected Texture createTileTexture(DrawContext dc, int width, int height) { GL gl = dc.getGL(); TextureData td = new TextureData( - gl.getGLProfile(), // GL profile - GL.GL_RGBA8, // internal format - width, height, // dimension - 0, // border - GL.GL_RGBA, // pixel format - GL.GL_UNSIGNED_BYTE, // pixel type - false, // mipmap - false, false, // dataIsCompressed, mustFlipVertically - null, null) // buffer, flusher + gl.getGLProfile(), // GL profile + GL.GL_RGBA8, // internal format + width, height, // dimension + 0, // border + GL.GL_RGBA, // pixel format + GL.GL_UNSIGNED_BYTE, // pixel type + false, // mipmap + false, false, // dataIsCompressed, mustFlipVertically + null, null) // buffer, flusher { /** * Overridden to return a non-zero size. TextureData does not compute an estimated memory size if the buffer @@ -984,12 +1034,12 @@ protected Texture createTileTexture(DrawContext dc, int width, int height) * texture with the common pixel formats. */ @Override - public int getEstimatedMemorySize() - { + public int getEstimatedMemorySize() { int sizeInBytes = OGLUtil.estimateTextureMemorySize(this.getInternalFormat(), this.getWidth(), - this.getHeight(), this.getMipmap()); - if (sizeInBytes > 0) + this.getHeight(), this.getMipmap()); + if (sizeInBytes > 0) { return sizeInBytes; + } return super.getEstimatedMemorySize(); } @@ -1004,14 +1054,13 @@ public int getEstimatedMemorySize() /** * Compute the dimension of a texture large enough to represent the amount of the contents visible in the frame. * - * @param frameSize Size of the frame content area. + * @param frameSize Size of the frame content area. * @param contentSize Size of the frame content. * * @return Dimension of a texture large enough to render the full frame content area. This method always returns a - * power of two dimension. + * power of two dimension. */ - protected int computeTileTextureDimension(Dimension frameSize, Dimension contentSize) - { + protected int computeTileTextureDimension(Dimension frameSize, Dimension contentSize) { int width = Math.min(frameSize.width, contentSize.width); int height = Math.min(frameSize.height, contentSize.height); @@ -1020,12 +1069,14 @@ protected int computeTileTextureDimension(Dimension frameSize, Dimension content return WWMath.powerOfTwoCeiling((int) Math.sqrt(area) + this.textureTileDimension); } - /** {@inheritDoc} */ - public void preRender(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void preRender(DrawContext dc) { Offset screenLocation = this.getScreenLocation(); - if (screenLocation == null) + if (screenLocation == null) { return; + } this.stepAnimation(dc); @@ -1033,82 +1084,72 @@ public void preRender(DrawContext dc) // Highlight the frame if the pick point is within the frame's pickable bounds. Point pickPoint = dc.getPickPoint(); - if (pickPoint != null) - { + if (pickPoint != null) { int glY = dc.getView().getViewport().height - pickPoint.y; this.setHighlighted(this.pickBounds.contains(new Point(pickPoint.x, glY))); } this.determineActiveAttributes(); - if (this.intersectsFrustum(dc) && this.mustUpdateTiles(dc)) - { - try - { + if (this.intersectsFrustum(dc) && this.mustUpdateTiles(dc)) { + try { this.beginDrawing(dc); this.updateTiles(dc); - } - finally - { + } finally { this.endDrawing(dc); } } } - /** {@inheritDoc} */ - public void render(DrawContext dc) - { + /** + * {@inheritDoc} + */ + public void render(DrawContext dc) { Offset screenLocation = this.getScreenLocation(); - if (screenLocation == null || this.frameBounds == null) + if (screenLocation == null || this.frameBounds == null) { return; + } - if (this.mustRecomputeFrameGeometry) - { + if (this.mustRecomputeFrameGeometry) { this.computeFrameGeometry(); this.mustRecomputeFrameGeometry = false; } - if (this.intersectsFrustum(dc)) - { - try - { + if (this.intersectsFrustum(dc)) { + try { this.beginDrawing(dc); // While the tree is animated toward a minimized state, draw it as if it were maximized, // with the contents and scroll bars - if (this.isDrawMinimized()) + if (this.isDrawMinimized()) { this.drawMinimized(dc); - else + } else { this.drawMaximized(dc); - } - finally - { + } + } finally { this.endDrawing(dc); } } } - /** Initialize controls to resizing the frame, minimizing the frame, etc. */ - protected void initializeUIControls() - { + /** + * Initialize controls to resizing the frame, minimizing the frame, etc. + */ + protected void initializeUIControls() { this.minimizeAnimation = new WindowShadeAnimation(this); this.frameResizeControl = new FrameResizeControl(this); - this.minimizeButton = new TreeHotSpot(this) - { + this.minimizeButton = new TreeHotSpot(this) { @Override - public void selected(SelectEvent event) - { - if (event == null || this.isConsumed(event)) + public void selected(SelectEvent event) { + if (event == null || this.isConsumed(event)) { return; + } - if (event.isLeftClick()) - { + if (event.isLeftClick()) { ScrollFrame.this.setMinimized(!ScrollFrame.this.isMinimized()); event.consume(); - } - else - { + } else { super.selected(event); } } @@ -1125,12 +1166,12 @@ public void selected(SelectEvent event) * * @return {@code true} If the frame intersects the frustum, otherwise {@code false}. */ - protected boolean intersectsFrustum(DrawContext dc) - { - if (dc.isPickingMode()) + protected boolean intersectsFrustum(DrawContext dc) { + if (dc.isPickingMode()) { return dc.getPickFrustums().intersectsAny(this.pickBounds); - else + } else { return dc.getView().getViewport().intersects(this.frameBounds); + } } /** @@ -1139,29 +1180,27 @@ protected boolean intersectsFrustum(DrawContext dc) * * @param dc Current draw context. */ - protected void stepAnimation(DrawContext dc) - { - if (this.isAnimating()) - { + protected void stepAnimation(DrawContext dc) { + if (this.isAnimating()) { this.animation.step(); - if (this.animation.hasNext()) + if (this.animation.hasNext()) { dc.setRedrawRequested(this.animationDelay); - else + } else { this.animation = null; + } } } /** * Get the bounds of a tile in the frame content. * - * @param row Row of the tile to get the bounds of. + * @param row Row of the tile to get the bounds of. * @param column Column of the tile to get the bounds of. * * @return Bounds of the desired tile, relative to the lower left corner of {#link contentBounds}. */ - protected Rectangle getContentTileBounds(int row, int column) - { + protected Rectangle getContentTileBounds(int row, int column) { int xScroll = this.horizontalScrollBar.getValue(); int yScroll = this.verticalScrollBar.getValue(); @@ -1178,10 +1217,10 @@ protected Rectangle getContentTileBounds(int row, int column) * * @param dc Current draw context. */ - public void updateBounds(DrawContext dc) - { - if (dc.getFrameTimeStamp() == this.frameNumber) + public void updateBounds(DrawContext dc) { + if (dc.getFrameTimeStamp() == this.frameNumber) { return; + } this.determineSize(); @@ -1193,34 +1232,31 @@ public void updateBounds(DrawContext dc) Size size = this.getActiveSize(); // If the frame size is relative to the content size, compute the content size and then set the frame size. - if (this.isRelativeSize(size)) - { + if (this.isRelativeSize(size)) { // Pass null for the frame bounds because the frame size depends on the content size. contentSize = this.contents.getSize(dc, null); Dimension frameSizeForContentSize = this.computeFrameRectForContentRect(contentSize); this.frameSize = size.compute(frameSizeForContentSize.width, frameSizeForContentSize.height, - viewport.width, viewport.height); - } - else - { + viewport.width, viewport.height); + } else { // Otherwise just compute the frame size. The content size will be computed after the frame size has been // determined. this.frameSize = size.compute(0, 0, viewport.width, viewport.height); } // Apply the maximum size constraint - if (this.getMaxSize() != null) - { + if (this.getMaxSize() != null) { Dimension max = this.getMaxSize().compute(this.frameSize.width, this.frameSize.height, viewport.width, - viewport.height); + viewport.height); this.frameSize.width = Math.min(this.frameSize.width, max.width); this.frameSize.height = Math.min(this.frameSize.height, max.height); } // If the frame size has changed, the frame geometry must be regenerated - if (!this.frameSize.equals(previousFrameSize)) + if (!this.frameSize.equals(previousFrameSize)) { this.mustRecomputeFrameGeometry = true; + } // Compute point in OpenGL coordinates Point2D upperLeft = this.screenLocation.computeOffset(viewport.width, viewport.height, 1.0, 1.0); @@ -1228,24 +1264,23 @@ public void updateBounds(DrawContext dc) this.awtScreenPoint = new Point((int) upperLeft.getX(), (int) (viewport.height - upperLeft.getY())); this.frameBounds = new Rectangle((int) upperLeft.getX(), (int) upperLeft.getY() - this.frameSize.height, - this.frameSize.width, this.frameSize.height); + this.frameSize.width, this.frameSize.height); // Compute the pickable screen extent as the frame extent, plus the width of the frame's pickable outline. // This extent is used during picking to ensure that the frame's outline is pickable when it exceeds the // frame's screen extent. this.pickBounds = new Rectangle( - this.frameBounds.x - this.borderPickWidth / 2, - this.frameBounds.y - this.borderPickWidth / 2, - this.frameBounds.width + this.borderPickWidth, - this.frameBounds.height + this.borderPickWidth); + this.frameBounds.x - this.borderPickWidth / 2, + this.frameBounds.y - this.borderPickWidth / 2, + this.frameBounds.width + this.borderPickWidth, + this.frameBounds.height + this.borderPickWidth); this.innerBounds = new Rectangle((int) upperLeft.getX() + this.frameBorder, - (int) upperLeft.getY() - frameSize.height + this.frameBorder, frameSize.width - this.frameBorder * 2, - frameSize.height - this.frameBorder * 2); + (int) upperLeft.getY() - frameSize.height + this.frameBorder, frameSize.width - this.frameBorder * 2, + frameSize.height - this.frameBorder * 2); // If the content size has yet not been computed, compute it now. - if (contentSize == null) - { + if (contentSize == null) { // Compute the bounds as if both scroll bars are visible. This saves us from having to compute the size // multiple times if scroll bars are required. If scroll bars are not required it may leave a little bit of // extra padding on the edges of the frame. @@ -1254,7 +1289,6 @@ public void updateBounds(DrawContext dc) // Computing the bounds of the content area of the frame requires computing the bounds with no scroll bars, // and determining if scroll bars are required given the size of the scrollable content. - // Try laying out the frame without scroll bars this.contentBounds = this.computeBounds(false, false); @@ -1262,8 +1296,7 @@ public void updateBounds(DrawContext dc) boolean showVerticalScrollbar = this.mustShowVerticalScrollbar(contentSize); // If we need a vertical scroll bar, recompute the bounds because the scrollbar consumes horizontal space - if (showVerticalScrollbar) - { + if (showVerticalScrollbar) { this.contentBounds = this.computeBounds(true, false); } @@ -1272,8 +1305,7 @@ public void updateBounds(DrawContext dc) // If we need a horizontal scroll bar, recompute the bounds because the horizontal scroll bar consumes vertical // space and a vertical scroll bar may now be required - if (showHorizontalScrollbar && !showVerticalScrollbar) - { + if (showHorizontalScrollbar && !showVerticalScrollbar) { this.contentBounds = this.computeBounds(showVerticalScrollbar, showHorizontalScrollbar); // Determine if we now need a vertical scroll bar @@ -1286,10 +1318,12 @@ public void updateBounds(DrawContext dc) // If the scroll bars were visible and are now hidden, reset the scroll position to zero. Otherwise, the // scroll bar will already be scrolled to a certain position when it reappears, which is probably not what // the user expects. - if (this.showVerticalScrollbar && !showVerticalScrollbar) + if (this.showVerticalScrollbar && !showVerticalScrollbar) { this.verticalScrollBar.setValue(0); - if (this.showHorizontalScrollbar && !showHorizontalScrollbar) + } + if (this.showHorizontalScrollbar && !showHorizontalScrollbar) { this.horizontalScrollBar.setValue(0); + } this.showVerticalScrollbar = showVerticalScrollbar; this.showHorizontalScrollbar = showHorizontalScrollbar; @@ -1320,11 +1354,10 @@ public void updateBounds(DrawContext dc) * * @return Frame size required to display the content without scrollbars. */ - protected Dimension computeFrameRectForContentRect(Dimension contentSize) - { + protected Dimension computeFrameRectForContentRect(Dimension contentSize) { int frameWidth = contentSize.width + this.frameBorder * 2 + 4 * this.frameLineWidth + this.scrollBarSize; int frameHeight = contentSize.height + this.frameBorder * 2 + this.getTitleBarHeight() - + 2 * this.frameLineWidth; + + 2 * this.frameLineWidth; return new Dimension(frameWidth, frameHeight); } @@ -1339,15 +1372,14 @@ protected Dimension computeFrameRectForContentRect(Dimension contentSize) */ // TODO try to eliminate this dependence on size modes. This would break if an app subclassed Size and implemented // TODO different modes. - protected boolean isRelativeSize(Size size) - { + protected boolean isRelativeSize(Size size) { String heightMode = size.getHeightMode(); String widthMode = size.getWidthMode(); return Size.NATIVE_DIMENSION.equals(heightMode) - || Size.MAINTAIN_ASPECT_RATIO.equals(heightMode) - || Size.NATIVE_DIMENSION.equals(widthMode) - || Size.MAINTAIN_ASPECT_RATIO.equals(widthMode); + || Size.MAINTAIN_ASPECT_RATIO.equals(heightMode) + || Size.NATIVE_DIMENSION.equals(widthMode) + || Size.MAINTAIN_ASPECT_RATIO.equals(widthMode); } /** @@ -1357,16 +1389,12 @@ protected boolean isRelativeSize(Size size) * * @return {@code true} if the vertical scrollbar should be displayed, otherwise {@code false}. */ - protected boolean mustShowVerticalScrollbar(Dimension contentSize) - { + protected boolean mustShowVerticalScrollbar(Dimension contentSize) { // If the frame is not minimized or in the middle of an animation, compare the content size to the visible // bounds. - if ((!this.isMinimized() && !this.isAnimating())) - { + if ((!this.isMinimized() && !this.isAnimating())) { return contentSize.height > this.contentBounds.height; - } - else - { + } else { // Otherwise, return the previous scrollbar setting, do not recompute it. While the frame is animating, we want // the scrollbar decision to be based on its maximized size. If the frame would have scrollbars when maximized will // have scrollbars while it animates, but a frame that would not have scrollbars when maximized will not have @@ -1382,12 +1410,11 @@ protected boolean mustShowVerticalScrollbar(Dimension contentSize) * * @return {@code true} if the horizontal scrollbar should be displayed, otherwise {@code false}. */ - protected boolean mustShowHorizontalScrollbar(Dimension contentSize) - { + protected boolean mustShowHorizontalScrollbar(Dimension contentSize) { // Show a scroll bar if the content is large enough to require a scroll bar, and there is enough space to // draw the scroll bar. return contentSize.width > this.contentBounds.width - && this.innerBounds.height > this.titleBarHeight + this.scrollBarSize; + && this.innerBounds.height > this.titleBarHeight + this.scrollBarSize; } /** @@ -1395,23 +1422,21 @@ protected boolean mustShowHorizontalScrollbar(Dimension contentSize) * * @return {@code true} if an animation is in progress, otherwise {@code false}. */ - protected boolean isAnimating() - { + protected boolean isAnimating() { return this.animation != null; } /** * Compute the content bounds, taking into account the frame size and the presence of scroll bars. * - * @param showVerticalScrollBar True if the frame will have a vertical scroll bar. A vertical scroll bar will make - * the content frame narrower. + * @param showVerticalScrollBar True if the frame will have a vertical scroll bar. A vertical scroll bar will make + * the content frame narrower. * @param showHorizontalScrollBar True if the frame will have a horizontal scroll bar. A horizontal scroll bar will - * make the content frame shorter. + * make the content frame shorter. * * @return The bounds of the content frame. */ - protected Rectangle computeBounds(boolean showVerticalScrollBar, boolean showHorizontalScrollBar) - { + protected Rectangle computeBounds(boolean showVerticalScrollBar, boolean showHorizontalScrollBar) { int hScrollBarSize = (showHorizontalScrollBar ? this.scrollBarSize : 0); int vScrollBarSize = (showVerticalScrollBar ? this.scrollBarSize : 0); @@ -1420,21 +1445,23 @@ protected Rectangle computeBounds(boolean showVerticalScrollBar, boolean showHor int inset = 2 * this.frameLineWidth; return new Rectangle(this.innerBounds.x + inset, - this.innerBounds.y + hScrollBarSize + inset, - this.innerBounds.width - vScrollBarSize - inset * 2, - this.innerBounds.height - titleBarHeight - hScrollBarSize - inset); + this.innerBounds.y + hScrollBarSize + inset, + this.innerBounds.width - vScrollBarSize - inset * 2, + this.innerBounds.height - titleBarHeight - hScrollBarSize - inset); } - /** Updates the frame's screen-coordinate geometry in {@link #vertexBuffer} according to the current screen bounds. */ - protected void computeFrameGeometry() - { - if (this.frameBounds == null) + /** + * Updates the frame's screen-coordinate geometry in {@link #vertexBuffer} according to the current screen bounds. + */ + protected void computeFrameGeometry() { + if (this.frameBounds == null) { return; + } FrameAttributes attributes = this.getActiveAttributes(); this.vertexBuffer = FrameFactory.createShapeBuffer(AVKey.SHAPE_RECTANGLE, this.frameBounds.width, - this.frameBounds.height, attributes.getCornerRadius(), this.vertexBuffer); + this.frameBounds.height, attributes.getCornerRadius(), this.vertexBuffer); } /** @@ -1443,12 +1470,11 @@ protected void computeFrameGeometry() * * @return The frame's minimum size. */ - protected Dimension getMinimumSize() - { + protected Dimension getMinimumSize() { // Reserve enough space to draw the border, both scroll bars, and the title bar int minWidth = this.frameBorder * 2 + this.scrollBarSize * 3; // left scroll arrow + right + vertical scroll bar int minHeight = this.frameBorder * 2 + this.scrollBarSize * 3 - + this.titleBarHeight; // Up arrow + down arrow + horizontal scroll bar + + this.titleBarHeight; // Up arrow + down arrow + horizontal scroll bar return new Dimension(minWidth, minHeight); } @@ -1457,8 +1483,7 @@ protected Dimension getMinimumSize() * * @return {@code true} if the frame should draw minimized, otherwise {@code false}. */ - protected boolean isDrawMinimized() - { + protected boolean isDrawMinimized() { // Draw minimized when the frame is minimized, but not while animating toward the minimized state return this.isMinimized() && !this.isAnimating(); } @@ -1468,19 +1493,15 @@ protected boolean isDrawMinimized() * * @param dc Current draw context. */ - protected void drawMaximized(DrawContext dc) - { + protected void drawMaximized(DrawContext dc) { this.drawFrame(dc); // Draw the contents using the cached texture, if we've rendered to a texture. Otherwise, just draw the // contents directly. Always draw the contents directly in picking mode because unique pick colors can't be // cached in a texture. - if (this.renderToTexture && !dc.isPickingMode()) - { + if (this.renderToTexture && !dc.isPickingMode()) { this.drawContentTiles(dc); - } - else - { + } else { this.drawContentDirect(dc); } } @@ -1490,20 +1511,16 @@ protected void drawMaximized(DrawContext dc) * * @param dc Current draw context. */ - protected void drawContentDirect(DrawContext dc) - { + protected void drawContentDirect(DrawContext dc) { GL gl = dc.getGL(); - try - { + try { gl.glEnable(GL.GL_SCISSOR_TEST); gl.glScissor(this.contentBounds.x, this.contentBounds.y - 1, this.contentBounds.width + 1, - this.contentBounds.height); + this.contentBounds.height); this.contents.renderScrollable(dc, this.scrollContentBounds.getLocation(), - this.scrollContentBounds.getSize(), this.contentBounds); - } - finally - { + this.scrollContentBounds.getSize(), this.contentBounds); + } finally { gl.glDisable(GL.GL_SCISSOR_TEST); } } @@ -1513,12 +1530,10 @@ protected void drawContentDirect(DrawContext dc) * * @param dc Current draw context. */ - protected void drawContentTiles(DrawContext dc) - { + protected void drawContentTiles(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - try - { + try { gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL); gl.glEnable(GL.GL_TEXTURE_2D); @@ -1526,16 +1541,15 @@ protected void drawContentTiles(DrawContext dc) OGLUtil.applyBlending(gl, true); Texture texture = dc.getTextureCache().getTexture(this.textureCacheKey); - if (texture == null) + if (texture == null) { return; + } texture.bind(gl); - for (ContentTile tile : tiles) - { + for (ContentTile tile : tiles) { TextureTile textureTile = this.getTextureTile(tile); - if (textureTile == null) - { + if (textureTile == null) { continue; } @@ -1546,35 +1560,29 @@ protected void drawContentTiles(DrawContext dc) Rectangle clippedTileBounds = tileScreenBounds.intersection(this.contentBounds); // If the tile is not visible in the content area, don't bother drawing it. - if (clippedTileBounds.isEmpty()) - { + if (clippedTileBounds.isEmpty()) { continue; } Rectangle subTileBounds = new Rectangle(tileX + clippedTileBounds.x - tileScreenBounds.x, - tileY + clippedTileBounds.y - tileScreenBounds.y, clippedTileBounds.width, - clippedTileBounds.height); + tileY + clippedTileBounds.y - tileScreenBounds.y, clippedTileBounds.width, + clippedTileBounds.height); gl.glPushMatrix(); - try - { + try { gl.glTranslated(clippedTileBounds.x, clippedTileBounds.y, 0.0f); gl.glColor4f(1, 1, 1, (float) this.getActiveAttributes().getForegroundOpacity()); TextureCoords texCoords = texture.getSubImageTexCoords((int) subTileBounds.getMinX(), - (int) subTileBounds.getMinY(), (int) subTileBounds.getMaxX(), (int) subTileBounds.getMaxY()); + (int) subTileBounds.getMinY(), (int) subTileBounds.getMaxX(), (int) subTileBounds.getMaxY()); gl.glScaled(subTileBounds.width, subTileBounds.height, 1d); dc.drawUnitQuad(texCoords); - } - finally - { + } finally { gl.glPopMatrix(); } } - } - finally - { + } finally { gl.glDisable(GL.GL_TEXTURE_2D); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); } @@ -1585,8 +1593,7 @@ protected void drawContentTiles(DrawContext dc) * * @param dc Current draw context. */ - protected void drawMinimized(DrawContext dc) - { + protected void drawMinimized(DrawContext dc) { this.drawFrame(dc); } @@ -1595,13 +1602,11 @@ protected void drawMinimized(DrawContext dc) * * @param dc Current draw context. */ - protected void drawFrame(DrawContext dc) - { + protected void drawFrame(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler oglStack = new OGLStackHandler(); - try - { + try { oglStack.pushModelviewIdentity(gl); FrameAttributes attributes = this.getActiveAttributes(); @@ -1611,20 +1616,16 @@ protected void drawFrame(DrawContext dc) boolean drawHorizontalScrollbar = this.showHorizontalScrollbar; boolean drawVerticalScrollbar = this.showVerticalScrollbar; - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { Color[] color = attributes.getBackgroundColor(); - try - { + try { gl.glEnable(GL.GL_LINE_SMOOTH); OGLUtil.applyColor(gl, color[0], 1.0, false); gl.glLineWidth(this.frameLineWidth); FrameFactory.drawBuffer(dc, GL.GL_LINE_STRIP, this.vertexBuffer); - } - finally - { + } finally { gl.glDisable(GL.GL_LINE_SMOOTH); } @@ -1632,18 +1633,15 @@ protected void drawFrame(DrawContext dc) gl.glTranslated(this.innerBounds.x, this.innerBounds.y, 0.0); // Translate back inner frame TreeUtil.drawRectWithGradient(gl, new Rectangle(0, 0, this.innerBounds.width, this.innerBounds.height), - color[0], color[1], attributes.getBackgroundOpacity(), AVKey.VERTICAL); - } - else - { + color[0], color[1], attributes.getBackgroundOpacity(), AVKey.VERTICAL); + } else { int frameHeight = this.frameBounds.height; int frameWidth = this.frameBounds.width; // Draw draggable frame TreeUtil.drawPickableRect(dc, this.pickSupport, this, new Rectangle(0, 0, frameWidth, frameHeight)); - if (this.isEnableResizeControl() && !this.isDrawMinimized()) - { + if (this.isEnableResizeControl() && !this.isDrawMinimized()) { Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); this.pickSupport.addPickableObject(colorCode, this.frameResizeControl); @@ -1659,26 +1657,24 @@ protected void drawFrame(DrawContext dc) // If both scroll bars are visible, draw the empty square in the lower right hand corner as a part of // the resize control, pickable area. - if (drawVerticalScrollbar && drawHorizontalScrollbar && !this.isDrawMinimized()) - { + if (drawVerticalScrollbar && drawHorizontalScrollbar && !this.isDrawMinimized()) { gl.glRecti(this.innerBounds.width - this.scrollBarSize, 0, - this.innerBounds.width, this.scrollBarSize); + this.innerBounds.width, this.scrollBarSize); } } - if (!this.isDrawMinimized()) + if (!this.isDrawMinimized()) { this.drawScrollBars(dc); + } // Draw title bar - if (this.isDrawTitleBar()) - { + if (this.isDrawTitleBar()) { gl.glTranslated(0, this.innerBounds.height - this.titleBarHeight, 0); this.drawTitleBar(dc); } // Draw a thin border outlining the filled rectangle that is the frame background. - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { gl.glLoadIdentity(); int minX = (int) this.innerBounds.getMinX(); @@ -1691,26 +1687,23 @@ protected void drawFrame(DrawContext dc) // Do not draw the outline on the edges with scroll bars because the scrollbar draws its own border. On // some devices the scroll bar border draws next to the frame border, resulting in a double width border. gl.glBegin(GL2.GL_LINE_STRIP); - try - { - if (!drawVerticalScrollbar) + try { + if (!drawVerticalScrollbar) { gl.glVertex2f(maxX, minY + 0.5f); + } gl.glVertex2f(maxX, maxY); gl.glVertex2f(minX + 0.5f, maxY); gl.glVertex2f(minX + 0.5f, minY + 0.5f); - if (!drawHorizontalScrollbar) + if (!drawHorizontalScrollbar) { gl.glVertex2f(maxX, minY + 0.5f); - } - finally - { + } + } finally { gl.glEnd(); } } - } - finally - { + } finally { oglStack.pop(gl); } } @@ -1720,15 +1713,14 @@ protected void drawFrame(DrawContext dc) * * @param dc Current draw context. */ - protected void drawScrollBars(DrawContext dc) - { + protected void drawScrollBars(DrawContext dc) { // Draw a vertical scroll bar if the tree extends beyond the visible bounds - if (this.showVerticalScrollbar) - { + if (this.showVerticalScrollbar) { int x1 = this.innerBounds.width - this.scrollBarSize; int y1 = 1; - if (this.showHorizontalScrollbar) + if (this.showHorizontalScrollbar) { y1 += this.scrollBarSize; + } Rectangle scrollBarBounds = new Rectangle(x1, y1, this.scrollBarSize, this.contentBounds.height + 1); @@ -1737,13 +1729,13 @@ protected void drawScrollBars(DrawContext dc) } // Draw a horizontal scroll bar if the tree extends beyond the visible bounds - if (this.showHorizontalScrollbar) - { + if (this.showHorizontalScrollbar) { int x1 = 1; int y1 = 1; int width = this.innerBounds.width - 1; - if (this.showVerticalScrollbar) + if (this.showVerticalScrollbar) { width -= this.scrollBarSize; + } Rectangle scrollBarBounds = new Rectangle(x1, y1, width, this.scrollBarSize); @@ -1757,32 +1749,26 @@ protected void drawScrollBars(DrawContext dc) * * @param dc Draw context */ - protected void drawTitleBar(DrawContext dc) - { + protected void drawTitleBar(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. FrameAttributes attributes = this.getActiveAttributes(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Draw title bar as a rectangle with gradient Color[] color = attributes.getTitleBarColor(); TreeUtil.drawRectWithGradient(gl, new Rectangle(0, 0, this.innerBounds.width, this.getTitleBarHeight()), - color[0], color[1], attributes.getBackgroundOpacity(), AVKey.VERTICAL); + color[0], color[1], attributes.getBackgroundOpacity(), AVKey.VERTICAL); OGLUtil.applyColor(gl, attributes.getForegroundColor(), 1.0, false); - if (!this.isDrawMinimized()) - { + if (!this.isDrawMinimized()) { // Draw a line to separate the title bar from the frame gl.glBegin(GL2.GL_LINES); - try - { + try { gl.glVertex2f(0, 0); gl.glVertex2f(this.innerBounds.width, 0); - } - finally - { + } finally { gl.glEnd(); } } @@ -1800,14 +1786,12 @@ protected void drawTitleBar(DrawContext dc) * Draw an icon in the upper left corner of the title bar. This method takes a point relative to lower left corner * of the title bar. This point is modified to indicate how much horizontal space is consumed by the icon. * - * @param dc Draw context + * @param dc Draw context * @param drawPoint Point at which to draw the icon. This point is relative to the lower left corner of the title - * bar. This point will be modified to indicate how much horizontal space was consumed by drawing - * the icon. After drawing the icon, the x value with point to the first available space to the - * right of the icon. + * bar. This point will be modified to indicate how much horizontal space was consumed by drawing the icon. After + * drawing the icon, the x value with point to the first available space to the right of the icon. */ - protected void drawIcon(DrawContext dc, Point drawPoint) - { + protected void drawIcon(DrawContext dc, Point drawPoint) { // This method is never called during picked, so picking mode is not handled here GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -1817,17 +1801,14 @@ protected void drawIcon(DrawContext dc, Point drawPoint) // Draw icon in upper left corner BasicWWTexture texture = this.getTexture(); - if (texture == null) - { + if (texture == null) { drawPoint.x += iconSpace; return; } OGLStackHandler oglStack = new OGLStackHandler(); - try - { - if (texture.bind(dc)) - { + try { + if (texture.bind(dc)) { gl.glEnable(GL.GL_TEXTURE_2D); Dimension iconSize = attributes.getIconSize(); @@ -1844,9 +1825,7 @@ protected void drawIcon(DrawContext dc, Point drawPoint) drawPoint.x += iconSize.getWidth() + iconSpace * 2; } - } - finally - { + } finally { gl.glDisable(GL.GL_TEXTURE_2D); gl.glBindTexture(GL.GL_TEXTURE_2D, 0); oglStack.pop(gl); @@ -1856,43 +1835,40 @@ protected void drawIcon(DrawContext dc, Point drawPoint) /** * Draw text in the frame title. * - * @param dc Draw context + * @param dc Draw context * @param drawPoint Point at which to draw text. This point is relative to the lower left corner of the title bar. */ - protected void drawTitleText(DrawContext dc, Point drawPoint) - { + protected void drawTitleText(DrawContext dc, Point drawPoint) { // This method is never called during picked, so picking mode is not handled here GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. FrameAttributes attributes = this.getActiveAttributes(); String frameTitle = this.getFrameTitle(); - if (frameTitle == null) + if (frameTitle == null) { return; + } TextRenderer textRenderer = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), - attributes.getFont()); + attributes.getFont()); // Determine if the shortened frame title needs to be regenerated. If so, generate it now. int titleAreaWidth = this.innerBounds.width - this.buttonSize - drawPoint.x - attributes.getIconSpace(); - if (this.mustGenerateShortTitle(attributes.getFont(), titleAreaWidth)) - { + if (this.mustGenerateShortTitle(attributes.getFont(), titleAreaWidth)) { this.generateShortTitle(dc, frameTitle, titleAreaWidth, "..."); } - if (this.shortTitle == null) + if (this.shortTitle == null) { return; + } - try - { + try { textRenderer.begin3DRendering(); OGLUtil.applyColor(gl, attributes.getTextColor(), 1.0, false); double vertAdjust = (this.titleBarHeight - Math.abs(this.shortTitleBounds.getY())) / 2; textRenderer.draw(this.shortTitle, drawPoint.x, (int) (drawPoint.y + vertAdjust) + 1); - } - finally - { + } finally { textRenderer.end3DRendering(); } } @@ -1900,16 +1876,15 @@ protected void drawTitleText(DrawContext dc, Point drawPoint) /** * Determine if a the shortened frame title needs to be regenerated. * - * @param titleFont Title font. + * @param titleFont Title font. * @param titleAreaWidth Width in pixels of the frame title area. * * @return {@code true} if the shortened title needs to be regenerated, otherwise {@code false}. */ - protected boolean mustGenerateShortTitle(Font titleFont, int titleAreaWidth) - { + protected boolean mustGenerateShortTitle(Font titleFont, int titleAreaWidth) { return this.shortTitle == null - || !titleFont.equals(this.shortFrameTitleFont) - || titleAreaWidth != this.frameTitleWidth; + || !titleFont.equals(this.shortFrameTitleFont) + || titleAreaWidth != this.frameTitleWidth; } /** @@ -1917,15 +1892,13 @@ protected boolean mustGenerateShortTitle(Font titleFont, int titleAreaWidth) * enough to accommodate the full title, then the short title will be the same as the full title. The method sets * the fields {@link #shortTitle}, {@link #shortFrameTitleFont}, {@link #frameTitleWidth}. * - * @param dc Current draw context. + * @param dc Current draw context. * @param frameTitle Full frame title. - * @param width Width in pixels of the frame title area. - * @param cutOff String to append to title to indicate that text has been cut off due to a small frame. For - * example, if the cut off string is "...", the string "Frame Title" might be shortened to "Frame - * T...". + * @param width Width in pixels of the frame title area. + * @param cutOff String to append to title to indicate that text has been cut off due to a small frame. For example, + * if the cut off string is "...", the string "Frame Title" might be shortened to "Frame T...". */ - protected void generateShortTitle(DrawContext dc, String frameTitle, int width, String cutOff) - { + protected void generateShortTitle(DrawContext dc, String frameTitle, int width, String cutOff) { Font font = this.getActiveAttributes().getFont(); // Keep track of the font and width used to generate the title so that we can invalidate the generated @@ -1933,8 +1906,7 @@ protected void generateShortTitle(DrawContext dc, String frameTitle, int width, this.shortFrameTitleFont = font; this.frameTitleWidth = width; - if (frameTitle == null) - { + if (frameTitle == null) { this.shortTitle = null; return; } @@ -1943,8 +1915,7 @@ protected void generateShortTitle(DrawContext dc, String frameTitle, int width, // Check to see if the frame is wide enough to display the entire title Rectangle2D size = textRenderer.getBounds(frameTitle); - if (size.getWidth() < width) - { + if (size.getWidth() < width) { this.shortTitle = frameTitle; // No truncation required this.shortTitleBounds = size; return; @@ -1952,8 +1923,7 @@ protected void generateShortTitle(DrawContext dc, String frameTitle, int width, // Check to see if the frame is too small to display even the continuation Rectangle2D ellipseSize = textRenderer.getBounds(cutOff); - if (width < ellipseSize.getWidth()) - { + if (width < ellipseSize.getWidth()) { this.shortTitle = null; // Frame too small this.shortTitleBounds = null; return; @@ -1961,12 +1931,10 @@ protected void generateShortTitle(DrawContext dc, String frameTitle, int width, // Starting at the end of the string, remove characters until the string fits StringBuilder sb = new StringBuilder(); - for (int i = 0; i < frameTitle.length(); i++) - { + for (int i = 0; i < frameTitle.length(); i++) { sb.append(frameTitle.charAt(i)); Rectangle2D bounds = textRenderer.getBounds(sb); - if (bounds.getWidth() + ellipseSize.getWidth() > width) - { + if (bounds.getWidth() + ellipseSize.getWidth() > width) { sb.deleteCharAt(sb.length() - 1); sb.append("..."); break; @@ -1975,13 +1943,10 @@ protected void generateShortTitle(DrawContext dc, String frameTitle, int width, // Make sure that the computed string contains at least one character of the original title. If not, don't // show any text. - if (sb.length() > cutOff.length()) - { + if (sb.length() > cutOff.length()) { this.shortTitle = sb.toString(); this.shortTitleBounds = textRenderer.getBounds(sb); - } - else - { + } else { this.shortTitle = null; this.shortTitleBounds = null; } @@ -1992,21 +1957,18 @@ protected void generateShortTitle(DrawContext dc, String frameTitle, int width, * * @param dc Current draw context. */ - protected void drawMinimizeButton(DrawContext dc) - { + protected void drawMinimizeButton(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler oglStack = new OGLStackHandler(); - try - { + try { oglStack.pushModelviewIdentity(gl); int x = (int) this.innerBounds.getMaxX() - this.getActiveAttributes().getIconSpace() - this.buttonSize; int y = (int) this.innerBounds.getMaxY() - (this.titleBarHeight - this.buttonSize) / 2 - this.buttonSize; gl.glTranslated(x, y, 0.0); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { Color color = this.getActiveAttributes().getMinimizeButtonColor(); FrameAttributes attributes = this.getActiveAttributes(); @@ -2016,40 +1978,31 @@ protected void drawMinimizeButton(DrawContext dc) OGLUtil.applyColor(gl, attributes.getForegroundColor(), false); gl.glBegin(GL2.GL_LINE_LOOP); - try - { + try { gl.glVertex2f(0f, 0f); gl.glVertex2f(0.5f, buttonSize + 0.5f); gl.glVertex2f(buttonSize, buttonSize + 0.5f); gl.glVertex2f(buttonSize, 0); - } - finally - { + } finally { gl.glEnd(); } gl.glBegin(GL2.GL_LINES); - try - { + try { // Draw a horizontal line. If the frame is maximized, this will be a minus sign. If the tree is // minimized, this will be part of a plus sign. gl.glVertex2f(buttonSize / 4f, buttonSize / 2f); gl.glVertex2f(buttonSize - buttonSize / 4f, buttonSize / 2f); // Draw a vertical line to complete the plus sign if the frame is minimized. - if (this.isMinimized()) - { + if (this.isMinimized()) { gl.glVertex2f(buttonSize / 2f, buttonSize / 4f); gl.glVertex2f(buttonSize / 2f, buttonSize - buttonSize / 4f); } - } - finally - { + } finally { gl.glEnd(); } - } - else - { + } else { Color color = dc.getUniquePickColor(); int colorCode = color.getRGB(); @@ -2059,26 +2012,23 @@ protected void drawMinimizeButton(DrawContext dc) gl.glScaled(buttonSize, buttonSize, 1d); dc.drawUnitQuad(); } - } - finally - { + } finally { oglStack.pop(gl); } } - protected void beginDrawing(DrawContext dc) - { + protected void beginDrawing(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. GLU glu = dc.getGLU(); this.BEogsh.pushAttrib(gl, GL2.GL_DEPTH_BUFFER_BIT - | GL2.GL_COLOR_BUFFER_BIT - | GL2.GL_ENABLE_BIT - | GL2.GL_CURRENT_BIT - | GL2.GL_POLYGON_BIT // For polygon mode - | GL2.GL_LINE_BIT // For line width - | GL2.GL_TRANSFORM_BIT - | GL2.GL_SCISSOR_BIT); + | GL2.GL_COLOR_BUFFER_BIT + | GL2.GL_ENABLE_BIT + | GL2.GL_CURRENT_BIT + | GL2.GL_POLYGON_BIT // For polygon mode + | GL2.GL_LINE_BIT // For line width + | GL2.GL_TRANSFORM_BIT + | GL2.GL_SCISSOR_BIT); gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); @@ -2093,17 +2043,14 @@ protected void beginDrawing(DrawContext dc) glu.gluOrtho2D(0d, viewport.width, 0d, viewport.height); this.BEogsh.pushModelviewIdentity(gl); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.pickSupport.clearPickList(); this.pickSupport.beginPicking(dc); } } - protected void endDrawing(DrawContext dc) - { - if (dc.isPickingMode()) - { + protected void endDrawing(DrawContext dc) { + if (dc.isPickingMode()) { this.pickSupport.endPicking(dc); this.pickSupport.resolvePick(dc, dc.getPickPoint(), dc.getCurrentLayer()); } @@ -2117,42 +2064,38 @@ protected void endDrawing(DrawContext dc) * * @return attributes that are active for this frame. */ - protected FrameAttributes getActiveAttributes() - { + protected FrameAttributes getActiveAttributes() { return this.activeAttributes; } - /** Determines which attributes -- normal, highlight or default -- to use each frame. */ - protected void determineActiveAttributes() - { - if (this.isHighlighted()) - { - if (this.getHighlightAttributes() != null) + /** + * Determines which attributes -- normal, highlight or default -- to use each frame. + */ + protected void determineActiveAttributes() { + if (this.isHighlighted()) { + if (this.getHighlightAttributes() != null) { this.activeAttributes.copy(this.getHighlightAttributes()); - else - { + } else { // If no highlight attributes have been specified we will use the normal attributes. - if (this.getAttributes() != null) + if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); - else + } else { this.activeAttributes.copy(defaultAttributes); + } } - } - else if (this.getAttributes() != null) - { + } else if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); - } - else - { + } else { this.activeAttributes.copy(defaultAttributes); } this.determineScrollbarAttributes(); } - /** Update the attributes of the scroll bars to match the frame's highlight state. */ - protected void determineScrollbarAttributes() - { + /** + * Update the attributes of the scroll bars to match the frame's highlight state. + */ + protected void determineScrollbarAttributes() { this.verticalScrollBar.setLineColor(this.activeAttributes.getForegroundColor()); this.verticalScrollBar.setOpacity(this.activeAttributes.getBackgroundOpacity()); this.horizontalScrollBar.setLineColor(this.activeAttributes.getForegroundColor()); @@ -2168,21 +2111,18 @@ protected void determineScrollbarAttributes() * * @return the frame size for the duration of this frame. */ - protected Size getActiveSize() - { + protected Size getActiveSize() { return this.activeSize; } - /** Determine the frame size to use for the current frame. */ - protected void determineSize() - { + /** + * Determine the frame size to use for the current frame. + */ + protected void determineSize() { // Use the minimized size if the frame is minimized or animating to or from the minimized state. - if ((this.isMinimized() || this.isAnimating()) && this.minimizedSize != null) - { + if ((this.isMinimized() || this.isAnimating()) && this.minimizedSize != null) { this.activeSize = this.minimizedSize; - } - else - { + } else { this.activeSize = this.maximizedSize; } } @@ -2193,12 +2133,12 @@ protected void determineSize() * * @return The icon texture, or no image source has been set, or if the icon has not been loaded yet. */ - protected BasicWWTexture getTexture() - { - if (this.texture != null) + protected BasicWWTexture getTexture() { + if (this.texture != null) { return this.texture; - else + } else { return this.initializeTexture(); + } } /** @@ -2207,19 +2147,14 @@ protected BasicWWTexture getTexture() * * @return The texture, or null if the texture is not yet available. */ - protected BasicWWTexture initializeTexture() - { + protected BasicWWTexture initializeTexture() { Object imageSource = this.getIconImageSource(); - if (imageSource instanceof String || imageSource instanceof URL) - { + if (imageSource instanceof String || imageSource instanceof URL) { URL imageURL = WorldWind.getDataFileStore().requestFile(imageSource.toString()); - if (imageURL != null) - { + if (imageURL != null) { this.texture = new BasicWWTexture(imageURL, true); } - } - else if (imageSource != null) - { + } else if (imageSource != null) { this.texture = new BasicWWTexture(imageSource, true); return this.texture; } @@ -2234,28 +2169,24 @@ else if (imageSource != null) * * @return The horizontal or vertical scroll bar. */ - public ScrollBar getScrollBar(String direction) - { - if (AVKey.VERTICAL.equals(direction)) + public ScrollBar getScrollBar(String direction) { + if (AVKey.VERTICAL.equals(direction)) { return this.verticalScrollBar; - else + } else { return this.horizontalScrollBar; + } } @Override - protected void beginDrag(Point point) - { - if (this.isEnableMove()) - { + protected void beginDrag(Point point) { + if (this.isEnableMove()) { Point2D location = this.awtScreenPoint; this.dragRefPoint = new Point((int) location.getX() - point.x, (int) location.getY() - point.y); } } - public void drag(Point point) - { - if (this.isEnableMove()) - { + public void drag(Point point) { + if (this.isEnableMove()) { double x = point.x + this.dragRefPoint.x; double y = point.y + this.dragRefPoint.y; this.setScreenLocation(new Offset(x, y, AVKey.PIXELS, AVKey.INSET_PIXELS)); @@ -2263,22 +2194,20 @@ public void drag(Point point) } @Override - public void selected(SelectEvent event) - { - if (event == null || this.isConsumed(event)) + public void selected(SelectEvent event) { + if (event == null || this.isConsumed(event)) { return; + } super.selected(event); // Minimize the frame if the title bar was double clicked. Rectangle titleBarBounds = new Rectangle((int) this.awtScreenPoint.getX() + this.frameBorder, - (int) this.awtScreenPoint.getY() + this.frameBorder * 2, this.innerBounds.width, this.titleBarHeight); + (int) this.awtScreenPoint.getY() + this.frameBorder * 2, this.innerBounds.width, this.titleBarHeight); - if (event.isLeftDoubleClick()) - { + if (event.isLeftDoubleClick()) { Point pickPoint = event.getPickPoint(); - if (pickPoint != null && titleBarBounds.contains(event.getPickPoint())) - { + if (pickPoint != null && titleBarBounds.contains(event.getPickPoint())) { this.setMinimized(!this.isMinimized()); event.consume(); } @@ -2286,19 +2215,16 @@ public void selected(SelectEvent event) } @Override - public void mouseWheelMoved(MouseWheelEvent e) - { - if (e == null || e.isConsumed()) + public void mouseWheelMoved(MouseWheelEvent e) { + if (e == null || e.isConsumed()) { return; + } // Java on Mac OS X implements support for horizontal scrolling by sending a Shift+ScrollWheel event. This is // not the case for Java for other platforms, so we handle the scrolling logic for Mac OS X - if (Configuration.isMacOS()) - { + if (Configuration.isMacOS()) { this.doScrollMacOS(e); - } - else - { + } else { this.doScroll(e); } @@ -2313,17 +2239,13 @@ public void mouseWheelMoved(MouseWheelEvent e) * * @param e Mouse event that triggered the scroll. */ - protected void doScroll(MouseWheelEvent e) - { + protected void doScroll(MouseWheelEvent e) { // Determine whether to scroll horizontally or vertically by giving priority to the vertical scroll bar. Scroll // vertically if only both scroll bars are active or only the vertical scroll bar is active. Scroll horizontally // if only the horizontal scroll bar is active. - if (this.showVerticalScrollbar) - { + if (this.showVerticalScrollbar) { this.verticalScrollBar.scroll(e.getUnitsToScroll() * this.getMouseWheelScrollUnit(AVKey.VERTICAL)); - } - else if (this.showHorizontalScrollbar) - { + } else if (this.showHorizontalScrollbar) { this.horizontalScrollBar.scroll(e.getUnitsToScroll() * this.getMouseWheelScrollUnit(AVKey.HORIZONTAL)); } } @@ -2334,21 +2256,17 @@ else if (this.showHorizontalScrollbar) * * @param e Mouse event that triggered the scroll. */ - protected void doScrollMacOS(MouseWheelEvent e) - { + protected void doScrollMacOS(MouseWheelEvent e) { // On Mac OS X, Java always scrolls horizontally when the Shift key is down. This policy is used to support the // Magic Mouse and Magic Trackpad devices. When the user scroll horizontally on either of these devices, Java // automatically sends a Shift+ScrollWheel event, regardless of whether the Shift key is actually down. See // Radar #4631846 in // http://developer.apple.com/library/mac/#releasenotes/Java/JavaLeopardRN/ResolvedIssues/ResolvedIssues.html. - if (e.isShiftDown()) - { + if (e.isShiftDown()) { this.horizontalScrollBar.scroll(e.getUnitsToScroll() * this.getMouseWheelScrollUnit(AVKey.HORIZONTAL)); - } - // If the Shift key is not down, Java Mac OS X implements the standard scrolling policy used by Java on other + } // If the Shift key is not down, Java Mac OS X implements the standard scrolling policy used by Java on other // operating systems. - else - { + else { this.doScroll(e); } } @@ -2360,8 +2278,7 @@ protected void doScrollMacOS(MouseWheelEvent e) * * @return The scroll unit that will be applied when the mouse wheel is moved. */ - protected int getMouseWheelScrollUnit(String direction) - { + protected int getMouseWheelScrollUnit(String direction) { return (int) (this.getScrollBar(direction).getBlockIncrement() * 0.25); } @@ -2369,49 +2286,56 @@ protected int getMouseWheelScrollUnit(String direction) * A tile in the frame content. This class represents one tile in the frame contents, and the time at which that * tile was last drawn to texture tile. */ - class ContentTile - { - /** Row in the frame content. */ + class ContentTile { + + /** + * Row in the frame content. + */ int row; - /** Column in the frame content. */ + /** + * Column in the frame content. + */ int column; - /** Time at which this content tile was last drawn to a texture tile. */ + /** + * Time at which this content tile was last drawn to a texture tile. + */ long updateTime; /** * Create new content tile. * - * @param row Row of this tile in the frame content. + * @param row Row of this tile in the frame content. * @param column Column of this tile in the frame content. */ - ContentTile(int row, int column) - { + ContentTile(int row, int column) { this.row = row; this.column = column; } @Override - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || this.getClass() != o.getClass()) + } + if (o == null || this.getClass() != o.getClass()) { return false; + } ContentTile that = (ContentTile) o; - if (this.row != that.row) + if (this.row != that.row) { return false; + } //noinspection RedundantIfStatement - if (this.column != that.column) + if (this.column != that.column) { return false; + } return true; } @Override - public int hashCode() - { + public int hashCode() { int result; result = this.row; @@ -2421,26 +2345,35 @@ public int hashCode() } } - /** A region of the backing texture used to render one tile of the scrollable content. */ - class TextureTile implements Comparable - { - /** Row of this tile in the frame's backing texture. */ + /** + * A region of the backing texture used to render one tile of the scrollable content. + */ + class TextureTile implements Comparable { + + /** + * Row of this tile in the frame's backing texture. + */ int row; - /** Column of this tile in the frame's backing texture. */ + /** + * Column of this tile in the frame's backing texture. + */ int column; - /** The content tile currently rendered in this texture tile. */ + /** + * The content tile currently rendered in this texture tile. + */ ContentTile currentTile; - /** The last time that this tile was accessed. Used to implement an LRU tile replacement scheme. */ + /** + * The last time that this tile was accessed. Used to implement an LRU tile replacement scheme. + */ long lastUsed; /** * Create a new texture tile. * - * @param row Row of the tile in the frame's backing texture. + * @param row Row of the tile in the frame's backing texture. * @param column Column of the tile in the frame's backing texture. */ - TextureTile(int row, int column) - { + TextureTile(int row, int column) { this.row = row; this.column = column; } @@ -2451,12 +2384,10 @@ class TextureTile implements Comparable * @param that Tile to compare with. * * @return -1 if this tile was accessed less recently than that tile, 0 if the access times are the same, or 1 - * if this tile was accessed more recently. + * if this tile was accessed more recently. */ - public int compareTo(TextureTile that) - { - if (that == null) - { + public int compareTo(TextureTile that) { + if (that == null) { String msg = Logging.getMessage("nullValue.CacheEntryIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); diff --git a/src/gov/nasa/worldwind/util/tree/Scrollable.java b/src/gov/nasa/worldwind/util/tree/Scrollable.java index 19affbbc6f..55f65e05e4 100644 --- a/src/gov/nasa/worldwind/util/tree/Scrollable.java +++ b/src/gov/nasa/worldwind/util/tree/Scrollable.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.render.DrawContext; @@ -18,30 +17,29 @@ * @version $Id: Scrollable.java 1171 2013-02-11 21:45:02Z dcollins $ * @see ScrollFrame */ -public interface Scrollable -{ +public interface Scrollable { + /** * Render the scrollable component. The component should render itself with the lower left corner of the content * located at {@code location}.in the rectangle specified by {@code bounds}. Note that some of the content may be * clipped by the scroll frame. * - * @param dc Draw context. - * @param location Point at which to draw the Scrollable contents. This point indicates the location of the lower - * left corner of the content, in GL screen coordinates (origin at lower left corner of the - * screen). - * @param frameSize Size of the frame that will hold the content. + * @param dc Draw context. + * @param location Point at which to draw the Scrollable contents. This point indicates the location of the lower + * left corner of the content, in GL screen coordinates (origin at lower left corner of the screen). + * @param frameSize Size of the frame that will hold the content. * @param clipBounds Bounds of the clip rectangle. Any pixels outside of this box will be discarded, and do not need - * to be drawn. The rectangle is specified in GL screen coordinates. + * to be drawn. The rectangle is specified in GL screen coordinates. */ public void renderScrollable(DrawContext dc, Point location, Dimension frameSize, Rectangle clipBounds); /** * Get the size of the object on screen. * - * @param dc Draw context. + * @param dc Draw context. * @param frameSize Size of the frame that will hold the the scrollable content. Implementations should be prepared - * to handle a {@code null} frame size because the frame may need to determine the content size - * before it can determine its own size. + * to handle a {@code null} frame size because the frame may need to determine the content size before it can + * determine its own size. * * @return The size of the scrollable object. */ diff --git a/src/gov/nasa/worldwind/util/tree/Tree.java b/src/gov/nasa/worldwind/util/tree/Tree.java index 17fc496a0c..e00f477704 100644 --- a/src/gov/nasa/worldwind/util/tree/Tree.java +++ b/src/gov/nasa/worldwind/util/tree/Tree.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.WWObject; @@ -18,8 +17,8 @@ * @see TreeModel * @see TreeLayout */ -public interface Tree extends WWObject, OrderedRenderable -{ +public interface Tree extends WWObject, OrderedRenderable { + /** * Set the tree layout. The layout determines how the tree will be rendered. * @@ -91,7 +90,7 @@ public interface Tree extends WWObject, OrderedRenderable * Expand a collapsed path, or collapse an expanded path. Has no effect on leaf nodes. * * @param path Path to operate on. If the node defined by {@code path} is expanded, it will be collapsed. If it is - * collapsed it will be expanded. + * collapsed it will be expanded. */ public void togglePath(TreePath path); diff --git a/src/gov/nasa/worldwind/util/tree/TreeAttributes.java b/src/gov/nasa/worldwind/util/tree/TreeAttributes.java index 186f195bb3..59f9a7b07f 100644 --- a/src/gov/nasa/worldwind/util/tree/TreeAttributes.java +++ b/src/gov/nasa/worldwind/util/tree/TreeAttributes.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import java.awt.*; @@ -16,19 +15,19 @@ * @version $Id: TreeAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TreeLayout */ -public interface TreeAttributes -{ +public interface TreeAttributes { + /** - * Returns a new TreeAttributes instance of the same type as this TreeAttributes, who's properties are - * configured exactly as this TreeAttributes. + * Returns a new TreeAttributes instance of the same type as this TreeAttributes, who's properties are configured + * exactly as this TreeAttributes. * * @return a copy of this TreeAttributes. */ TreeAttributes copy(); /** - * Copies the specified TreeAttributes' properties into this object's properties. This does nothing if the - * specified attributes is null. + * Copies the specified TreeAttributes' properties into this object's properties. This does nothing if the specified + * attributes is null. * * @param attributes the attributes to copy. */ @@ -71,16 +70,16 @@ public interface TreeAttributes void setColor(Color textColor); /** - * Get the color of filled checkboxes that indicate if nodes are selected. The checkboxes are drawn as a gradient - * of two colors. + * Get the color of filled checkboxes that indicate if nodes are selected. The checkboxes are drawn as a gradient of + * two colors. * * @return two element array of the colors that make up the checkbox gradient. */ Color[] getCheckBoxColor(); /** - * Set the color of filled checkboxes that indicate if a node is selected. The checkboxes are drawn as a gradient - * of two colors. + * Set the color of filled checkboxes that indicate if a node is selected. The checkboxes are drawn as a gradient of + * two colors. * * @param color1 first color in the checkbox gradient. * @param color2 second color in the checkbox gradient. diff --git a/src/gov/nasa/worldwind/util/tree/TreeHotSpot.java b/src/gov/nasa/worldwind/util/tree/TreeHotSpot.java index 256fd72a76..a5f848bb30 100644 --- a/src/gov/nasa/worldwind/util/tree/TreeHotSpot.java +++ b/src/gov/nasa/worldwind/util/tree/TreeHotSpot.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.event.SelectEvent; @@ -19,19 +18,20 @@ * @author pabercrombie * @version $Id: TreeHotSpot.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TreeHotSpot extends AbstractHotSpot -{ - /** The parent HotSpot, or null if this TreeHotSpot has no parent. */ +public class TreeHotSpot extends AbstractHotSpot { + + /** + * The parent HotSpot, or null if this TreeHotSpot has no parent. + */ protected HotSpot parent; /** * Create a hot spot. * * @param parent The screen area that contains this hot spot. Input events that cannot be handled by this object - * will be passed to the parent. May be null. + * will be passed to the parent. May be null. */ - public TreeHotSpot(HotSpot parent) - { + public TreeHotSpot(HotSpot parent) { this.parent = parent; } @@ -41,13 +41,14 @@ public TreeHotSpot(HotSpot parent) * * @param event The event to handle. */ - public void selected(SelectEvent event) - { - if (event == null || this.isConsumed(event)) + public void selected(SelectEvent event) { + if (event == null || this.isConsumed(event)) { return; + } - if (this.parent != null) + if (this.parent != null) { this.parent.selected(event); + } } /** @@ -56,13 +57,14 @@ public void selected(SelectEvent event) * * @param event The event to handle. */ - public void mouseClicked(MouseEvent event) - { - if (event == null || event.isConsumed()) + public void mouseClicked(MouseEvent event) { + if (event == null || event.isConsumed()) { return; + } - if (this.parent != null) + if (this.parent != null) { this.parent.mouseClicked(event); + } } /** @@ -71,13 +73,14 @@ public void mouseClicked(MouseEvent event) * * @param event The event to handle. */ - public void mousePressed(MouseEvent event) - { - if (event == null || event.isConsumed()) + public void mousePressed(MouseEvent event) { + if (event == null || event.isConsumed()) { return; + } - if (this.parent != null) + if (this.parent != null) { this.parent.mousePressed(event); + } } /** @@ -86,13 +89,14 @@ public void mousePressed(MouseEvent event) * * @param event The event to handle. */ - public void mouseReleased(MouseEvent event) - { - if (event == null || event.isConsumed()) + public void mouseReleased(MouseEvent event) { + if (event == null || event.isConsumed()) { return; + } - if (this.parent != null) + if (this.parent != null) { this.parent.mouseReleased(event); + } } /** @@ -101,12 +105,13 @@ public void mouseReleased(MouseEvent event) * * @param event The event to handle. */ - public void mouseWheelMoved(MouseWheelEvent event) - { - if (event == null || event.isConsumed()) + public void mouseWheelMoved(MouseWheelEvent event) { + if (event == null || event.isConsumed()) { return; + } - if (this.parent != null) + if (this.parent != null) { this.parent.mouseWheelMoved(event); + } } } diff --git a/src/gov/nasa/worldwind/util/tree/TreeLayout.java b/src/gov/nasa/worldwind/util/tree/TreeLayout.java index 2a484b39e0..7a8cee1329 100644 --- a/src/gov/nasa/worldwind/util/tree/TreeLayout.java +++ b/src/gov/nasa/worldwind/util/tree/TreeLayout.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.WWObject; @@ -16,8 +15,8 @@ * @version $Id: TreeLayout.java 1171 2013-02-11 21:45:02Z dcollins $ * @see Tree */ -public interface TreeLayout extends WWObject, Renderable -{ +public interface TreeLayout extends WWObject, Renderable { + /** * Render a tree. * diff --git a/src/gov/nasa/worldwind/util/tree/TreeModel.java b/src/gov/nasa/worldwind/util/tree/TreeModel.java index 03f20b4cd1..268374c39c 100644 --- a/src/gov/nasa/worldwind/util/tree/TreeModel.java +++ b/src/gov/nasa/worldwind/util/tree/TreeModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.WWObject; @@ -14,8 +13,8 @@ * @author pabercrombie * @version $Id: TreeModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TreeModel extends WWObject -{ +public interface TreeModel extends WWObject { + /** * Get the root node of the tree. * diff --git a/src/gov/nasa/worldwind/util/tree/TreeNode.java b/src/gov/nasa/worldwind/util/tree/TreeNode.java index c12c2d8687..d6dfb9040b 100644 --- a/src/gov/nasa/worldwind/util/tree/TreeNode.java +++ b/src/gov/nasa/worldwind/util/tree/TreeNode.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.WWObject; @@ -16,15 +15,21 @@ * @version $Id: TreeNode.java 1171 2013-02-11 21:45:02Z dcollins $ * @see TreeModel */ -public interface TreeNode extends WWObject -{ - /** All nodes in a subtree are selected. */ +public interface TreeNode extends WWObject { + + /** + * All nodes in a subtree are selected. + */ final static String SELECTED = "util.tree.Selected"; - /** No nodes in a subtree are selected. */ + /** + * No nodes in a subtree are selected. + */ final static String NOT_SELECTED = "util.tree.NotSelected"; - /** Some nodes in a subtree are selected, and some are not. */ + /** + * Some nodes in a subtree are selected, and some are not. + */ final static String PARTIALLY_SELECTED = "util.tree.PartiallySelected"; /** @@ -159,7 +164,7 @@ public interface TreeNode extends WWObject * @param child New child. * * @throws IndexOutOfBoundsException if {@code index} is less than zero or greater than the number of children - * already in the list. + * already in the list. */ void addChild(int index, TreeNode child) throws IndexOutOfBoundsException; @@ -170,7 +175,9 @@ public interface TreeNode extends WWObject */ void removeChild(TreeNode child); - /** Remove all of the child nodes from this node. */ + /** + * Remove all of the child nodes from this node. + */ void removeAllChildren(); /** diff --git a/src/gov/nasa/worldwind/util/tree/TreePath.java b/src/gov/nasa/worldwind/util/tree/TreePath.java index 60d86c7eba..c76f288263 100644 --- a/src/gov/nasa/worldwind/util/tree/TreePath.java +++ b/src/gov/nasa/worldwind/util/tree/TreePath.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.util.WWUtil; @@ -16,27 +15,27 @@ * @author tag * @version $Id: TreePath.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TreePath extends ArrayList -{ - /** Create an empty tree path. */ - public TreePath() - { +public class TreePath extends ArrayList { + + /** + * Create an empty tree path. + */ + public TreePath() { } /** * Create a tre path. * * @param initialPath Base tree path. - * @param args Additional path elements to append to {@code initialPath}. + * @param args Additional path elements to append to {@code initialPath}. */ - public TreePath(TreePath initialPath, String... args) - { + public TreePath(TreePath initialPath, String... args) { this.addAll(initialPath); - for (String pathElement : args) - { - if (!WWUtil.isEmpty(pathElement)) + for (String pathElement : args) { + if (!WWUtil.isEmpty(pathElement)) { this.add(pathElement); + } } } @@ -44,16 +43,15 @@ public TreePath(TreePath initialPath, String... args) * Create a tre path. * * @param initialPathEntry The first entry in the path. - * @param args Additional path entries. + * @param args Additional path entries. */ - public TreePath(String initialPathEntry, String... args) - { + public TreePath(String initialPathEntry, String... args) { this.add(initialPathEntry); - for (String pathElement : args) - { - if (!WWUtil.isEmpty(pathElement)) + for (String pathElement : args) { + if (!WWUtil.isEmpty(pathElement)) { this.add(pathElement); + } } } @@ -62,8 +60,7 @@ public TreePath(String initialPathEntry, String... args) * * @param initialPathEntries Entries in the path. */ - public TreePath(List initialPathEntries) - { + public TreePath(List initialPathEntries) { this.addAll(initialPathEntries); } @@ -72,8 +69,7 @@ public TreePath(List initialPathEntries) * * @return a new TreePath that contains the entries in this path, excluding the final entry. */ - public TreePath lastButOne() - { + public TreePath lastButOne() { return this.subPath(0, this.size() - 1); } @@ -81,12 +77,11 @@ public TreePath lastButOne() * Retrieves a subsection of the path. * * @param start first index (inclusive) of the sub-path - * @param end last index (exclusive) of the sub-path + * @param end last index (exclusive) of the sub-path * * @return A new path made up of path elements between {@code start} and {@code end}. */ - public TreePath subPath(int start, int end) - { + public TreePath subPath(int start, int end) { return new TreePath(this.subList(start, end)); } @@ -96,30 +91,30 @@ public TreePath subPath(int start, int end) * @param path Path to test. * * @return {@code true} if {@code path} contains no entries, {@code path} is {@code null}, or if the first entry of - * {@code path} is {@code null} or an empty string. + * {@code path} is {@code null} or an empty string. */ - public static boolean isEmptyPath(TreePath path) - { + public static boolean isEmptyPath(TreePath path) { return path == null || path.size() == 0 || WWUtil.isEmpty(path.get(0)); } @Override - public String toString() - { - if (this.size() == 0) + public String toString() { + if (this.size() == 0) { return ""; + } StringBuilder sb = new StringBuilder(); - for (String s : this) - { - if (WWUtil.isEmpty(s)) + for (String s : this) { + if (WWUtil.isEmpty(s)) { s = ""; + } - if (sb.length() == 0) + if (sb.length() == 0) { sb.append(s); - else + } else { sb.append("/").append(s); + } } return sb.toString(); diff --git a/src/gov/nasa/worldwind/util/tree/TreeUtil.java b/src/gov/nasa/worldwind/util/tree/TreeUtil.java index 87b762e416..10c68b464b 100644 --- a/src/gov/nasa/worldwind/util/tree/TreeUtil.java +++ b/src/gov/nasa/worldwind/util/tree/TreeUtil.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.avlist.AVKey; @@ -20,20 +19,18 @@ * @author pabercrombie * @version $Id: TreeUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TreeUtil -{ +public class TreeUtil { + /** * Draw a rectangle in a unique pick color, and associate the color with a pickable object. * - * @param dc Draw context. - * @param pickSupport Pick support. + * @param dc Draw context. + * @param pickSupport Pick support. * @param pickedObject Object to associate with pickable rectangle. - * @param bounds Bounds of the pickable rectangle. + * @param bounds Bounds of the pickable rectangle. */ - public static void drawPickableRect(DrawContext dc, PickSupport pickSupport, Object pickedObject, Rectangle bounds) - { - if (dc == null) - { + public static void drawPickableRect(DrawContext dc, PickSupport pickSupport, Object pickedObject, Rectangle bounds) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawingContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -52,20 +49,17 @@ public static void drawPickableRect(DrawContext dc, PickSupport pickSupport, Obj /** * Draw a rectangle. * - * @param gl GL + * @param gl GL * @param bounds Bounds of the rectangle, in GL coordinates. */ - public static void drawRect(GL2 gl, Rectangle bounds) - { - if (gl == null) - { + public static void drawRect(GL2 gl, Rectangle bounds) { + if (gl == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bounds == null) - { + if (bounds == null) { String message = Logging.getMessage("nullValue.BoundingBoxIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -75,17 +69,14 @@ public static void drawRect(GL2 gl, Rectangle bounds) } public static void drawRectWithGradient(GL2 gl, Rectangle bounds, Color color1, Color color2, double opacity, - String gradientDirection) - { - if (gl == null) - { + String gradientDirection) { + if (gl == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (bounds == null) - { + if (bounds == null) { String message = Logging.getMessage("nullValue.BoundingBoxIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -93,8 +84,7 @@ public static void drawRectWithGradient(GL2 gl, Rectangle bounds, Color color1, gl.glBegin(GL2.GL_QUADS); - if (AVKey.HORIZONTAL.equals(gradientDirection)) - { + if (AVKey.HORIZONTAL.equals(gradientDirection)) { OGLUtil.applyColor(gl, color1, opacity, false); gl.glVertex2d(bounds.getMinX(), bounds.getMaxY()); gl.glVertex2d(bounds.getMinX(), bounds.getMinY()); @@ -102,9 +92,7 @@ public static void drawRectWithGradient(GL2 gl, Rectangle bounds, Color color1, OGLUtil.applyColor(gl, color2, opacity, false); gl.glVertex2d(bounds.getMaxX(), bounds.getMinY()); gl.glVertex2d(bounds.getMaxX(), bounds.getMaxY()); - } - else - { + } else { OGLUtil.applyColor(gl, color1, opacity, false); gl.glVertex2d(bounds.getMaxX(), bounds.getMaxY()); gl.glVertex2d(bounds.getMinX(), bounds.getMaxY()); diff --git a/src/gov/nasa/worldwind/util/tree/WindowShadeAnimation.java b/src/gov/nasa/worldwind/util/tree/WindowShadeAnimation.java index 82a1ebfe52..cadf5edfb8 100644 --- a/src/gov/nasa/worldwind/util/tree/WindowShadeAnimation.java +++ b/src/gov/nasa/worldwind/util/tree/WindowShadeAnimation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.tree; import gov.nasa.worldwind.render.Size; @@ -17,54 +16,58 @@ * @author pabercrombie * @version $Id: WindowShadeAnimation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WindowShadeAnimation implements Animation -{ - /** Default animation duration, in milliseconds. */ +public class WindowShadeAnimation implements Animation { + + /** + * Default animation duration, in milliseconds. + */ public int DEFAULT_DURATION = 400; protected ScrollFrame frame; protected int startWindowHeight; protected int targetWindowHeight; - /** Duration, in milliseconds, of the animation. */ + /** + * Duration, in milliseconds, of the animation. + */ protected int duration = DEFAULT_DURATION; - /** Time when the animation started. */ + /** + * Time when the animation started. + */ protected long animationStart; protected Size targetWindowSize; protected int maximizedWindowHeight; - public WindowShadeAnimation(ScrollFrame frame) - { + public WindowShadeAnimation(ScrollFrame frame) { this.frame = frame; } - /** {@inheritDoc} */ - public void reset() - { + /** + * {@inheritDoc} + */ + public void reset() { this.animationStart = System.currentTimeMillis(); Dimension currentSize = this.frame.getCurrentSize(); // The minimized flag is set before the animation starts. So if the layout says that it is minimized, we want to // animate toward a minimized size. - if (this.frame.isMinimized()) - { + if (this.frame.isMinimized()) { this.startWindowHeight = currentSize.height; this.maximizedWindowHeight = currentSize.height; this.targetWindowHeight = this.frame.getTitleBarHeight() + this.frame.frameBorder * 2; - } - else - { + } else { this.startWindowHeight = currentSize.height; this.targetWindowHeight = this.maximizedWindowHeight; } } - /** {@inheritDoc} */ - public void step() - { + /** + * {@inheritDoc} + */ + public void step() { long now = System.currentTimeMillis(); double a = WWMath.computeInterpolationFactor(now, this.animationStart, - this.animationStart + this.duration); + this.animationStart + this.duration); //noinspection SuspiciousNameCombination int newHeight = (int) WWMath.mix(a, startWindowHeight, targetWindowHeight); @@ -74,9 +77,10 @@ public void step() this.frame.setMinimizedSize(Size.fromPixels(size.width, newHeight)); } - /** {@inheritDoc} */ - public boolean hasNext() - { + /** + * {@inheritDoc} + */ + public boolean hasNext() { return this.frame.getCurrentSize().height != targetWindowHeight; } @@ -85,8 +89,7 @@ public boolean hasNext() * * @return The duration of the animation, in milliseconds. */ - public int getDuration() - { + public int getDuration() { return duration; } @@ -95,10 +98,8 @@ public int getDuration() * * @param duration The duration of the animation, in milliseconds. */ - public void setDuration(int duration) - { - if (duration < 0) - { + public void setDuration(int duration) { + if (duration < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); diff --git a/src/gov/nasa/worldwind/util/tree/package-info.java b/src/gov/nasa/worldwind/util/tree/package-info.java index ce7b676ea0..388749b7ef 100644 --- a/src/gov/nasa/worldwind/util/tree/package-info.java +++ b/src/gov/nasa/worldwind/util/tree/package-info.java @@ -3,13 +3,12 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

          * A tree control drawn in the WorldWindow. The user can interact with the tree. The basic tree implementation renders * the tree similar to a file browser tree, but other layouts can be provided.

          * -

          + *

          * See {@link gov.nasa.worldwindx.examples.util.TreeControl} for an example of using the tree. {@link * gov.nasa.worldwindx.examples.LayerTreeUsage} is an example of using the tree control to display a tree of layers.

          * diff --git a/src/gov/nasa/worldwind/util/webview/AbstractWebView.java b/src/gov/nasa/worldwind/util/webview/AbstractWebView.java index 066a65e8aa..457690baa2 100644 --- a/src/gov/nasa/worldwind/util/webview/AbstractWebView.java +++ b/src/gov/nasa/worldwind/util/webview/AbstractWebView.java @@ -20,13 +20,19 @@ * @author pabercrombie * @version $Id: AbstractWebView.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractWebView extends WWObjectImpl implements WebView, Disposable -{ - /** The size of the WebView frame in pixels. Initially null, indicating the default size is used. */ +public abstract class AbstractWebView extends WWObjectImpl implements WebView, Disposable { + + /** + * The size of the WebView frame in pixels. Initially null, indicating the default size is used. + */ protected Dimension frameSize; - /** The WebView's current texture representation. Lazily created in {@link #getTextureRepresentation}. */ + /** + * The WebView's current texture representation. Lazily created in {@link #getTextureRepresentation}. + */ protected WWTexture textureRep; - /** Indicates whether the WebView is active. */ + /** + * Indicates whether the WebView is active. + */ protected boolean active; /** @@ -34,23 +40,23 @@ public abstract class AbstractWebView extends WWObjectImpl implements WebView, D * garbage collector. This does nothing if the WebView's owner has already called {@link #dispose()}. */ @Override - protected void finalize() throws Throwable - { + protected void finalize() throws Throwable { this.dispose(); super.finalize(); } - /** {@inheritDoc} */ - public Dimension getFrameSize() - { + /** + * {@inheritDoc} + */ + public Dimension getFrameSize() { return this.frameSize; } - /** {@inheritDoc} */ - public void setFrameSize(Dimension size) - { - if (size == null) - { + /** + * {@inheritDoc} + */ + public void setFrameSize(Dimension size) { + if (size == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -58,8 +64,9 @@ public void setFrameSize(Dimension size) // Setting the frame size requires a call into native code, and requires us to regenerate the texture. Only // do this if the size has actually changed. - if (this.frameSize.equals(size)) + if (this.frameSize.equals(size)) { return; + } this.frameSize = size; this.textureRep = null; // The texture needs to be regenerated because the frame size changed. @@ -69,31 +76,34 @@ public void setFrameSize(Dimension size) protected abstract void doSetFrameSize(Dimension size); - /** {@inheritDoc} */ - public WWTexture getTextureRepresentation(DrawContext dc) - { - if (dc == null) - { + /** + * {@inheritDoc} + */ + public WWTexture getTextureRepresentation(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.textureRep == null) + if (this.textureRep == null) { this.textureRep = this.createTextureRepresentation(dc); + } return this.textureRep; } - /** {@inheritDoc} */ - public void setActive(boolean active) - { + /** + * {@inheritDoc} + */ + public void setActive(boolean active) { this.active = active; } - /** {@inheritDoc} */ - public boolean isActive() - { + /** + * {@inheritDoc} + */ + public boolean isActive() { return this.active; } @@ -107,20 +117,14 @@ public boolean isActive() protected abstract WWTexture createTextureRepresentation(DrawContext dc); @Override - public void propertyChange(final PropertyChangeEvent event) - { - if (!SwingUtilities.isEventDispatchThread()) - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + public void propertyChange(final PropertyChangeEvent event) { + if (!SwingUtilities.isEventDispatchThread()) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { propertyChange(event); } }); - } - else - { + } else { this.firePropertyChange(AVKey.REPAINT, null, this); } } diff --git a/src/gov/nasa/worldwind/util/webview/BasicWebViewFactory.java b/src/gov/nasa/worldwind/util/webview/BasicWebViewFactory.java index b138daaec0..313aa4ed5d 100644 --- a/src/gov/nasa/worldwind/util/webview/BasicWebViewFactory.java +++ b/src/gov/nasa/worldwind/util/webview/BasicWebViewFactory.java @@ -18,31 +18,31 @@ * @author dcollins * @version $Id: BasicWebViewFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BasicWebViewFactory implements WebViewFactory -{ - /** Create the factory. */ - public BasicWebViewFactory() - { +public class BasicWebViewFactory implements WebViewFactory { + + /** + * Create the factory. + */ + public BasicWebViewFactory() { } - /** {@inheritDoc} */ - public WebView createWebView(Dimension frameSize) - { - if (frameSize == null) - { + /** + * {@inheritDoc} + */ + public WebView createWebView(Dimension frameSize) { + if (frameSize == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (Configuration.isLinuxOS()) + if (Configuration.isLinuxOS()) { return this.createLinuxWebView(frameSize); - - else if (Configuration.isMacOS()) + } else if (Configuration.isMacOS()) { return this.createMacWebView(frameSize); - - else if (Configuration.isWindowsOS()) + } else if (Configuration.isWindowsOS()) { return this.createWindowsWebView(frameSize); + } return this.createUnknownOSWebView(frameSize); } @@ -57,8 +57,7 @@ else if (Configuration.isWindowsOS()) * * @throws UnsupportedOperationException Linux WebView is not supported at this time. */ - protected WebView createLinuxWebView(Dimension frameSize) - { + protected WebView createLinuxWebView(Dimension frameSize) { return this.createUnknownOSWebView(frameSize); // TODO: implement native WebView for Linux. } @@ -69,8 +68,7 @@ protected WebView createLinuxWebView(Dimension frameSize) * * @return WebView instance for Mac. */ - protected WebView createMacWebView(Dimension frameSize) - { + protected WebView createMacWebView(Dimension frameSize) { return new MacWebView(frameSize); } @@ -81,8 +79,7 @@ protected WebView createMacWebView(Dimension frameSize) * * @return WebView instance for Windows. */ - protected WebView createWindowsWebView(Dimension frameSize) - { + protected WebView createWindowsWebView(Dimension frameSize) { return new WindowsWebView(frameSize); } @@ -97,11 +94,10 @@ protected WebView createWindowsWebView(Dimension frameSize) * * @throws UnsupportedOperationException WebView is only implemented for Windows and Mac at this time. */ - @SuppressWarnings( {"UnusedDeclaration"}) - protected WebView createUnknownOSWebView(Dimension frameSize) - { + @SuppressWarnings({"UnusedDeclaration"}) + protected WebView createUnknownOSWebView(Dimension frameSize) { String message = Logging.getMessage("NativeLib.UnsupportedOperatingSystem", "WebView", - System.getProperty("os.name")); + System.getProperty("os.name")); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } diff --git a/src/gov/nasa/worldwind/util/webview/MacWebView.java b/src/gov/nasa/worldwind/util/webview/MacWebView.java index 4651fd7aa1..fde5b3ee31 100644 --- a/src/gov/nasa/worldwind/util/webview/MacWebView.java +++ b/src/gov/nasa/worldwind/util/webview/MacWebView.java @@ -21,24 +21,23 @@ * @author dcollins * @version $Id: MacWebView.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MacWebView extends AbstractWebView -{ - /** The address of the native WebViewWindow object. Initialized during construction. */ +public class MacWebView extends AbstractWebView { + + /** + * The address of the native WebViewWindow object. Initialized during construction. + */ protected long webViewWindowPtr; - public MacWebView(Dimension frameSize) - { - if (frameSize == null) - { + public MacWebView(Dimension frameSize) { + if (frameSize == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!Configuration.isMacOS()) - { + if (!Configuration.isMacOS()) { String message = Logging.getMessage("NativeLib.UnsupportedOperatingSystem", "Mac WebView", - System.getProperty("os.name")); + System.getProperty("os.name")); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } @@ -49,128 +48,125 @@ public MacWebView(Dimension frameSize) MacWebViewJNI.setPropertyChangeListener(this.webViewWindowPtr, this); } - public void dispose() - { - if (this.webViewWindowPtr != 0) - { + public void dispose() { + if (this.webViewWindowPtr != 0) { MacWebViewJNI.releaseWebViewWindow(this.webViewWindowPtr); this.webViewWindowPtr = 0; } } - /** {@inheritDoc} */ - public void setHTMLString(String htmlString) - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void setHTMLString(String htmlString) { + if (this.webViewWindowPtr != 0) { MacWebViewJNI.setHTMLString(this.webViewWindowPtr, htmlString); } } - /** {@inheritDoc} */ - public void setHTMLString(String htmlString, URL baseURL) - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void setHTMLString(String htmlString, URL baseURL) { + if (this.webViewWindowPtr != 0) { MacWebViewJNI.setHTMLStringWithBaseURL(this.webViewWindowPtr, htmlString, baseURL); } } - /** {@inheritDoc} */ - public void setHTMLString(String htmlString, WebResourceResolver resourceResolver) - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void setHTMLString(String htmlString, WebResourceResolver resourceResolver) { + if (this.webViewWindowPtr != 0) { MacWebViewJNI.setHTMLStringWithResourceResolver(this.webViewWindowPtr, htmlString, resourceResolver); } } - protected void doSetFrameSize(Dimension size) - { - if (this.webViewWindowPtr != 0) - { + protected void doSetFrameSize(Dimension size) { + if (this.webViewWindowPtr != 0) { MacWebViewJNI.setFrameSize(this.webViewWindowPtr, size); } } - /** {@inheritDoc} */ - public Dimension getContentSize() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public Dimension getContentSize() { + if (this.webViewWindowPtr != 0) { return MacWebViewJNI.getContentSize(this.webViewWindowPtr); } return null; } - /** {@inheritDoc} */ - public Dimension getMinContentSize() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public Dimension getMinContentSize() { + if (this.webViewWindowPtr != 0) { return MacWebViewJNI.getMinContentSize(this.webViewWindowPtr); } return null; } - /** {@inheritDoc} */ - public void setMinContentSize(Dimension size) - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void setMinContentSize(Dimension size) { + if (this.webViewWindowPtr != 0) { MacWebViewJNI.setMinContentSize(this.webViewWindowPtr, size); } } - /** {@inheritDoc} */ - public URL getContentURL() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public URL getContentURL() { + if (this.webViewWindowPtr != 0) { return MacWebViewJNI.getContentURL(this.webViewWindowPtr); } return null; } - /** {@inheritDoc} */ - public Iterable getLinks() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public Iterable getLinks() { + if (this.webViewWindowPtr != 0) { AVList[] linkParams = MacWebViewJNI.getLinks(this.webViewWindowPtr); - if (linkParams != null) + if (linkParams != null) { return Arrays.asList(linkParams); + } } return Collections.emptyList(); } - /** {@inheritDoc} */ - public void sendEvent(InputEvent event) - { - if (this.webViewWindowPtr != 0 && event != null) - { + /** + * {@inheritDoc} + */ + public void sendEvent(InputEvent event) { + if (this.webViewWindowPtr != 0 && event != null) { MacWebViewJNI.sendEvent(this.webViewWindowPtr, event); } } - /** {@inheritDoc} */ - public void goBack() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void goBack() { + if (this.webViewWindowPtr != 0) { MacWebViewJNI.goBack(this.webViewWindowPtr); } } - /** {@inheritDoc} */ - public void goForward() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void goForward() { + if (this.webViewWindowPtr != 0) { MacWebViewJNI.goForward(this.webViewWindowPtr); } } @@ -179,8 +175,7 @@ public void goForward() * Not implemented. MacWebView generates transparent WebView textures, so setting a background color is not * necessary. The texture can be drawn over the desired background color. */ - public void setBackgroundColor(Color color) - { + public void setBackgroundColor(Color color) { // Do nothing } @@ -188,26 +183,23 @@ public void setBackgroundColor(Color color) * Not implemented. MacWebView generates transparent WebView textures, so setting a background color is not * necessary. The texture can be drawn over the desired background color. */ - public Color getBackgroundColor() - { + public Color getBackgroundColor() { return null; } //**********************************************************************// //******************** Texture Representation ************************// //**********************************************************************// - @Override - protected WWTexture createTextureRepresentation(DrawContext dc) - { + protected WWTexture createTextureRepresentation(DrawContext dc) { BasicWWTexture texture = new MacWebViewTexture(this.getFrameSize(), false); texture.setUseAnisotropy(false); // Do not use anisotropic texture filtering. return texture; } - protected class MacWebViewTexture extends WebViewTexture - { + protected class MacWebViewTexture extends WebViewTexture { + /** * Indicates whether updating this WebViewTexture's OpenGL texture has failed. When * true, this WebViewTexture's stops attempting to update its texture. Initially @@ -215,30 +207,27 @@ protected class MacWebViewTexture extends WebViewTexture */ protected boolean textureUpdateFailed; - public MacWebViewTexture(Dimension frameSize, boolean useMipMaps) - { + public MacWebViewTexture(Dimension frameSize, boolean useMipMaps) { super(frameSize, useMipMaps, true); } @Override - protected void updateIfNeeded(DrawContext dc) - { - if (this.textureUpdateFailed) + protected void updateIfNeeded(DrawContext dc) { + if (this.textureUpdateFailed) { return; + } // Return immediately if the texture isn't in the texture cache, and wait to update until the texture is // initialized and placed in the cache. This method is called after the texture is bound, so we'll get // another chance to update as long as the WebView generates repaint events when it changes. Texture texture = this.getTextureFromCache(dc); - if (texture == null) + if (texture == null) { return; + } - try - { + try { this.displayInTexture(dc, texture); - } - catch (Exception e) - { + } catch (Exception e) { // Log an exception indicating that updating the texture failed, but do not re-throw it. This is called // from within the rendering loop, and we want to avoid causing any other rendering code to fail. Logging.logger().log(Level.SEVERE, Logging.getMessage("WebView.ExceptionUpdatingTexture"), e); @@ -248,18 +237,17 @@ protected void updateIfNeeded(DrawContext dc) } @SuppressWarnings({"UnusedParameters"}) - protected void displayInTexture(DrawContext dc, Texture texture) - { + protected void displayInTexture(DrawContext dc, Texture texture) { // Return immediately if the native WebViewWindow has been released. This indicates the MacWebView has been // disposed, so there's nothing to do. long webViewWindowPtr = MacWebView.this.webViewWindowPtr; - if (webViewWindowPtr == 0) + if (webViewWindowPtr == 0) { return; + } // Load the WebViewWindow's current display pixels into the currently bound OGL texture if the native // WebView indicates that the display has changed since our last call to displayInTexture. - if (MacWebViewJNI.mustDisplayInTexture(webViewWindowPtr)) - { + if (MacWebViewJNI.mustDisplayInTexture(webViewWindowPtr)) { MacWebViewJNI.displayInTexture(webViewWindowPtr, texture.getTarget()); } } diff --git a/src/gov/nasa/worldwind/util/webview/MacWebViewJNI.java b/src/gov/nasa/worldwind/util/webview/MacWebViewJNI.java index f0791dd60c..64a50cdc2d 100644 --- a/src/gov/nasa/worldwind/util/webview/MacWebViewJNI.java +++ b/src/gov/nasa/worldwind/util/webview/MacWebViewJNI.java @@ -18,16 +18,12 @@ * @author dcollins * @version $Id: MacWebViewJNI.java 1948 2014-04-19 20:02:38Z dcollins $ */ -public class MacWebViewJNI -{ - static - { - try - { +public class MacWebViewJNI { + + static { + try { System.loadLibrary("webview"); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = Logging.getMessage("WebView.ExceptionCreatingWebView", t); Logging.logger().log(Level.SEVERE, message, t); } @@ -42,7 +38,7 @@ public class MacWebViewJNI public static native void setHTMLStringWithBaseURL(long webViewWindowPtr, String htmlString, URL baseURL); public static native void setHTMLStringWithResourceResolver(long webViewWindowPtr, String htmlString, - WebResourceResolver resourceResolver); + WebResourceResolver resourceResolver); public static native Dimension getFrameSize(long webViewWindowPtr); diff --git a/src/gov/nasa/worldwind/util/webview/WebResourceResolver.java b/src/gov/nasa/worldwind/util/webview/WebResourceResolver.java index 8086def541..8826f2cd73 100644 --- a/src/gov/nasa/worldwind/util/webview/WebResourceResolver.java +++ b/src/gov/nasa/worldwind/util/webview/WebResourceResolver.java @@ -11,7 +11,7 @@ * @author pabercrombie * @version $Id: WebResourceResolver.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WebResourceResolver -{ +public interface WebResourceResolver { + URL resolve(String address); } diff --git a/src/gov/nasa/worldwind/util/webview/WebView.java b/src/gov/nasa/worldwind/util/webview/WebView.java index 167ba362a5..7670cd8c35 100644 --- a/src/gov/nasa/worldwind/util/webview/WebView.java +++ b/src/gov/nasa/worldwind/util/webview/WebView.java @@ -41,8 +41,8 @@ * @author dcollins * @version $Id: WebView.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WebView extends AVList, Disposable -{ +public interface WebView extends AVList, Disposable { + /** * Specifies this WebView's HTML content as a string. The specified htmlString may be one * of the following: @@ -55,8 +55,7 @@ public interface WebView extends AVList, Disposable * If the application sends input events to the WebView, the user may navigate away from the specified HTML content * by interacting with links or buttons in the content. * - * @param htmlString the WebView's HTML text content, or null to display an empty - * WebView. + * @param htmlString the WebView's HTML text content, or null to display an empty WebView. */ void setHTMLString(String htmlString); @@ -73,11 +72,9 @@ public interface WebView extends AVList, Disposable * by interacting with links or buttons in the content. Once the user navigates away from the content specified * here, the htmlString and baseURL are no longer used. * - * @param htmlString the WebView's HTML text content, or null to display an empty - * WebView. - * @param baseURL the URL used to resolve relative paths in the htmlString, or - * null to indicate that relative paths should be interpreted as unresolved - * references. + * @param htmlString the WebView's HTML text content, or null to display an empty WebView. + * @param baseURL the URL used to resolve relative paths in the htmlString, or + * null to indicate that relative paths should be interpreted as unresolved references. */ void setHTMLString(String htmlString, URL baseURL); @@ -95,11 +92,10 @@ public interface WebView extends AVList, Disposable * by interacting with links or buttons in the content. Once the user navigates away from the content specified * here, the htmlString and resourceResolver are no longer used. * - * @param htmlString the WebView's HTML text content, or null to display an empty - * WebView. + * @param htmlString the WebView's HTML text content, or null to display an empty WebView. * @param resourceResolver the WebResourceResolver used to resolve relative paths in the - * htmlString, or null to indicate that relative paths should be - * interpreted as unresolved references. + * htmlString, or null to indicate that relative paths should be interpreted as unresolved + * references. */ void setHTMLString(String htmlString, WebResourceResolver resourceResolver); @@ -119,7 +115,7 @@ public interface WebView extends AVList, Disposable * @param size the size of this WebView's frame in pixels. * * @throws IllegalArgumentException if size is null, if the width or height are less than - * one, or if the width or height exceed the implementation-defined maximum. + * one, or if the width or height exceed the implementation-defined maximum. */ void setFrameSize(Dimension size); @@ -135,7 +131,7 @@ public interface WebView extends AVList, Disposable * See {@link #getMinContentSize()} for more information on how the minimum content size is used. * * @return the size of this WebView's content limited by the {@code minContentSize}, or null if this - * WebView's content size is unknown. + * WebView's content size is unknown. * * @see #getMinContentSize() */ @@ -166,7 +162,7 @@ public interface WebView extends AVList, Disposable * navigates within its history, and always reflects the URL of the current content. * * @return the URL of this WebView's current content, or null if the current content is the HTML string - * specified by setHTMLString. + * specified by setHTMLString. */ URL getContentURL(); @@ -189,7 +185,7 @@ public interface WebView extends AVList, Disposable * AVList with multiple pickable rectangles. * * @return an Iterable of AVList parameters describing this WebView's visible - * links. + * links. */ Iterable getLinks(); @@ -212,7 +208,7 @@ public interface WebView extends AVList, Disposable * Called when this WebView is activated or deactivated. The WebView only receives input events when it is active. * * @param active true if this WebView is being activated. false if this WebView is being - * deactivated. + * deactivated. * * @see #sendEvent */ @@ -246,10 +242,14 @@ public interface WebView extends AVList, Disposable */ void sendEvent(InputEvent event); - /** Navigate the WebView to the previous page in the browsing history. Has no effect if there is no previous page. */ + /** + * Navigate the WebView to the previous page in the browsing history. Has no effect if there is no previous page. + */ void goBack(); - /** Navigate the WebView to the next page in the browsing history. Has no effect if there is no next page. */ + /** + * Navigate the WebView to the next page in the browsing history. Has no effect if there is no next page. + */ void goForward(); /** diff --git a/src/gov/nasa/worldwind/util/webview/WebViewFactory.java b/src/gov/nasa/worldwind/util/webview/WebViewFactory.java index 94c7abef23..47672e61bf 100644 --- a/src/gov/nasa/worldwind/util/webview/WebViewFactory.java +++ b/src/gov/nasa/worldwind/util/webview/WebViewFactory.java @@ -13,8 +13,8 @@ * @author dcollins * @version $Id: WebViewFactory.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WebViewFactory -{ +public interface WebViewFactory { + /** * Returns a new WebView with the specified {@code frameSize}. * diff --git a/src/gov/nasa/worldwind/util/webview/WebViewTexture.java b/src/gov/nasa/worldwind/util/webview/WebViewTexture.java index d5fbaeebc8..491776822d 100644 --- a/src/gov/nasa/worldwind/util/webview/WebViewTexture.java +++ b/src/gov/nasa/worldwind/util/webview/WebViewTexture.java @@ -18,13 +18,12 @@ * @author dcollins * @version $Id: WebViewTexture.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WebViewTexture extends BasicWWTexture -{ +public class WebViewTexture extends BasicWWTexture { + protected Dimension frameSize; protected boolean flipVertically; - public WebViewTexture(Dimension frameSize, boolean useMipMaps, boolean flipVertically) - { + public WebViewTexture(Dimension frameSize, boolean useMipMaps, boolean flipVertically) { // Create a new unique object to use as the cache key. super(new Object(), useMipMaps); // Do not generate mipmaps for the texture. @@ -33,10 +32,8 @@ public WebViewTexture(Dimension frameSize, boolean useMipMaps, boolean flipVerti } @Override - public boolean bind(DrawContext dc) - { - if (dc == null) - { + public boolean bind(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -44,8 +41,7 @@ public boolean bind(DrawContext dc) boolean isBound = super.bind(dc); - if (isBound) - { + if (isBound) { this.updateIfNeeded(dc); } @@ -53,37 +49,35 @@ public boolean bind(DrawContext dc) } @Override - protected Texture initializeTexture(DrawContext dc, Object imageSource) - { - if (dc == null) - { + protected Texture initializeTexture(DrawContext dc, Object imageSource) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.textureInitializationFailed) + if (this.textureInitializationFailed) { return null; + } Texture t; GL gl = dc.getGL(); - try - { + try { // Allocate a texture with the proper dimensions and texture internal format, but with no data. TextureData td = new TextureData( - gl.getGLProfile(), // GL profile - GL.GL_RGBA, // texture internal format - this.frameSize.width, // texture image with - this.frameSize.height, // texture image height - 0, // border - GL.GL_RGBA, // pixelFormat - GL.GL_UNSIGNED_BYTE, // pixelType - false, // mipmap - false, // dataIsCompressed - this.flipVertically, - Buffers.newDirectByteBuffer(4 * this.frameSize.width * this.frameSize.height), // buffer - null); // flusher + gl.getGLProfile(), // GL profile + GL.GL_RGBA, // texture internal format + this.frameSize.width, // texture image with + this.frameSize.height, // texture image height + 0, // border + GL.GL_RGBA, // pixelFormat + GL.GL_UNSIGNED_BYTE, // pixelType + false, // mipmap + false, // dataIsCompressed + this.flipVertically, + Buffers.newDirectByteBuffer(4 * this.frameSize.width * this.frameSize.height), // buffer + null); // flusher t = TextureIO.newTexture(td); dc.getTextureCache().put(imageSource, t); @@ -95,9 +89,7 @@ protected Texture initializeTexture(DrawContext dc, Object imageSource) gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP_TO_BORDER); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP_TO_BORDER); - } - catch (Exception e) - { + } catch (Exception e) { // TODO: refactor as generic.ExceptionDuringTextureInitialization String message = Logging.getMessage("generic.IOExceptionDuringTextureInitialization"); Logging.logger().log(Level.SEVERE, message, e); @@ -112,7 +104,6 @@ protected Texture initializeTexture(DrawContext dc, Object imageSource) return t; } - protected void updateIfNeeded(DrawContext dc) - { + protected void updateIfNeeded(DrawContext dc) { } } diff --git a/src/gov/nasa/worldwind/util/webview/WindowsWebView.java b/src/gov/nasa/worldwind/util/webview/WindowsWebView.java index 947e063531..eb7bfaed8c 100644 --- a/src/gov/nasa/worldwind/util/webview/WindowsWebView.java +++ b/src/gov/nasa/worldwind/util/webview/WindowsWebView.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.webview; import com.jogamp.opengl.util.texture.Texture; @@ -23,31 +22,39 @@ /** * {@link WebView} implementation for Windows. This implementation uses the Window's native web browser control and the * MSHTML library to render a web page and create an OpenGL texture from the web browser window. - *

          Limits on the number of WebViews that can be created

          WindowsWebView creates a hidden - * native window. Creating the native window can fail if the process runs out of Windows user object handles. Other GUI - * elements in an application also consume these handles, so it is difficult to put a firm limit on how many WebViews - * can be created. An application that creates only WebViews and no other windows can create about 1500 WebViews before - * running out of handles. See MSDN for - * more information on User Objects and operating system limits. + *

          Limits on the number of WebViews that can be created

          WindowsWebView creates a hidden native window. Creating + * the native window can fail if the process runs out of Windows user object handles. Other GUI elements in an + * application also consume these handles, so it is difficult to put a firm limit on how many WebViews can be created. + * An application that creates only WebViews and no other windows can create about 1500 WebViews before running out of + * handles. See MSDN for more + * information on User Objects and operating system limits. * * @author pabercrombie * @version $Id: WindowsWebView.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WindowsWebView extends AbstractWebView -{ - /** Lock to protect creation of the web view message loop thread. */ +public class WindowsWebView extends AbstractWebView { + + /** + * Lock to protect creation of the web view message loop thread. + */ protected static final Object webViewUILock = new Object(); /** * Thread to run web view message loop. At most one message loop thread is running at any time, and it is shared by * all WebView instances. */ protected static Thread webViewUI; - /** Identifier for the message loop in native code. */ + /** + * Identifier for the message loop in native code. + */ protected static long webViewMessageLoop; - /** The address of the native WindowsWebView object. Initialized during construction. */ + /** + * The address of the native WindowsWebView object. Initialized during construction. + */ protected long webViewWindowPtr; - /** The address of the native NotificationAdapter object. Initialized during construction. */ + /** + * The address of the native NotificationAdapter object. Initialized during construction. + */ protected long observerPtr; /** @@ -56,7 +63,9 @@ public class WindowsWebView extends AbstractWebView */ protected static AtomicInteger instances = new AtomicInteger(); - /** Flag to the indicate that the WebView has been disposed. */ + /** + * Flag to the indicate that the WebView has been disposed. + */ protected boolean disposed = false; protected Color backgroundColor; @@ -67,31 +76,26 @@ public class WindowsWebView extends AbstractWebView * @param frameSize The size of the WebView rectangle. * * @throws UnsupportedOperationException if this class is instantiated on a non-Windows operating system. - * @throws WWRuntimeException if creating the native web browser window fails for any reason. For - * example, because the process has run out of User Object handles (see - * documentation above). + * @throws WWRuntimeException if creating the native web browser window fails for any reason. For example, because + * the process has run out of User Object handles (see documentation above). */ - public WindowsWebView(Dimension frameSize) - { - if (frameSize == null) - { + public WindowsWebView(Dimension frameSize) { + if (frameSize == null) { String message = Logging.getMessage("nullValue.SizeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!Configuration.isWindowsOS()) - { + if (!Configuration.isWindowsOS()) { String message = Logging.getMessage("NativeLib.UnsupportedOperatingSystem", "Windows WebView", - System.getProperty("os.name")); + System.getProperty("os.name")); Logging.logger().severe(message); throw new UnsupportedOperationException(message); } this.frameSize = frameSize; - try - { + try { // Increment the instance counter instances.incrementAndGet(); @@ -100,8 +104,7 @@ public WindowsWebView(Dimension frameSize) // Create the web view this.webViewWindowPtr = WindowsWebViewJNI.newWebViewWindow(webViewMessageLoop); - if (this.webViewWindowPtr == 0) - { + if (this.webViewWindowPtr == 0) { String message = Logging.getMessage("WebView.NativeExceptionInitializingWebView"); Logging.logger().severe(message); throw new WWRuntimeException(message); @@ -112,16 +115,12 @@ public WindowsWebView(Dimension frameSize) this.observerPtr = WindowsWebViewJNI.newNotificationAdapter(this); WindowsWebViewJNI.addWindowUpdateObserver(this.webViewWindowPtr, observerPtr); - } - catch (RuntimeException e) - { + } catch (RuntimeException e) { // If the WebView was not created successfully do not increment the instance counter. instances.decrementAndGet(); this.handleWebViewCreationError(); throw e; - } - catch (Error e) - { + } catch (Error e) { // If the WebView was not created successfully do not increment the instance counter. instances.decrementAndGet(); this.handleWebViewCreationError(); @@ -133,40 +132,39 @@ public WindowsWebView(Dimension frameSize) * This method is called by the constructor if an exception is thrown creating the WebView. It gives the WebView a * change to cleanup static state that may have been set during the failed WebView construction. */ - protected void handleWebViewCreationError() - { - try - { + protected void handleWebViewCreationError() { + try { this.stopMessageLoopIfNoInstances(); - } - catch (Throwable t) - { + } catch (Throwable t) { String message = Logging.getMessage("WebView.ExceptionStoppingWebViewThread", t); Logging.logger().severe(message); } } - /** {@inheritDoc} */ - public void dispose() - { + /** + * {@inheritDoc} + */ + public void dispose() { if (this.disposed) // Do not dispose the WebView multiple times + { return; + } - try - { + try { // Remove the notification adapter - if (webViewWindowPtr != 0 && observerPtr != 0) + if (webViewWindowPtr != 0 && observerPtr != 0) { WindowsWebViewJNI.removeWindowUpdateObserver(webViewWindowPtr, observerPtr); + } // Free the native WebView object associated with this Java WebView object. - if (webViewWindowPtr != 0) - { + if (webViewWindowPtr != 0) { WindowsWebViewJNI.releaseWebView(webViewWindowPtr); // Decrement the instance counter. Only do this if the webViewWindow pointer was non-zero, indicating // that native resources were actually allocated. instances.decrementAndGet(); } - if (observerPtr != 0) + if (observerPtr != 0) { WindowsWebViewJNI.releaseComObject(observerPtr); + } this.webViewWindowPtr = 0; this.observerPtr = 0; @@ -175,9 +173,7 @@ public void dispose() this.stopMessageLoopIfNoInstances(); this.disposed = true; - } - catch (Exception e) - { + } catch (Exception e) { Logging.logger().log(Level.SEVERE, Logging.getMessage("generic.ExceptionAttemptingToDisposeRenderable"), e); } } @@ -187,34 +183,23 @@ public void dispose() * creates a new thread if the message thread is not running. This method does not return until the message loop is * initialized and ready for use. */ - protected void ensureMessageLoopRunning() - { - synchronized (webViewUILock) - { - if (webViewUI == null || !webViewUI.isAlive()) - { + protected void ensureMessageLoopRunning() { + synchronized (webViewUILock) { + if (webViewUI == null || !webViewUI.isAlive()) { webViewMessageLoop = 0; // Create a new thread to run the web view message loop. - webViewUI = new Thread("WebView UI") - { - public void run() - { - try - { + webViewUI = new Thread("WebView UI") { + public void run() { + try { // Create a message loop in native code. This call must return // before any messages are sent to the WebView. webViewMessageLoop = WindowsWebViewJNI.newMessageLoop(); - } - catch (Throwable t) - { + } catch (Throwable t) { webViewMessageLoop = -1; - } - finally - { + } finally { // Notify the outer thread that the message loop is ready or failed to start. - synchronized (webViewUILock) - { + synchronized (webViewUILock) { webViewUILock.notify(); } } @@ -228,14 +213,10 @@ public void run() // Wait for the newly started thread to create the message loop. We cannot // safely use the WebView until the message loop has been initialized. - while (webViewMessageLoop == 0) - { - try - { + while (webViewMessageLoop == 0) { + try { webViewUILock.wait(1000); - } - catch (InterruptedException ignored) - { + } catch (InterruptedException ignored) { } } } @@ -246,12 +227,9 @@ public void run() * Terminate the message loop thread if there are no active (non-disposed) WebView instances. Has no effect if there * are active instances. */ - protected void stopMessageLoopIfNoInstances() - { - synchronized (webViewUILock) - { - if (instances.get() <= 0) - { + protected void stopMessageLoopIfNoInstances() { + synchronized (webViewUILock) { + if (instances.get() <= 0) { WindowsWebViewJNI.releaseMessageLoop(webViewMessageLoop); webViewMessageLoop = 0; webViewUI = null; @@ -259,88 +237,91 @@ protected void stopMessageLoopIfNoInstances() } } - /** {@inheritDoc} */ - public void setHTMLString(String htmlString) - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void setHTMLString(String htmlString) { + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.setHTMLString(this.webViewWindowPtr, htmlString, null); } } - /** {@inheritDoc} */ - public void setHTMLString(String htmlString, URL baseURL) - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void setHTMLString(String htmlString, URL baseURL) { + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.setHTMLString(this.webViewWindowPtr, htmlString, - baseURL != null ? baseURL.toString() : null); + baseURL != null ? baseURL.toString() : null); } } - /** {@inheritDoc} */ - public void setHTMLString(String htmlString, WebResourceResolver resourceResolver) - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void setHTMLString(String htmlString, WebResourceResolver resourceResolver) { + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.setHTMLStringWithResourceResolver(this.webViewWindowPtr, htmlString, resourceResolver); } } - /** {@inheritDoc} */ - public Dimension getContentSize() - { + /** + * {@inheritDoc} + */ + public Dimension getContentSize() { return WindowsWebViewJNI.getContentSize(webViewWindowPtr); } - /** {@inheritDoc} */ - public Dimension getMinContentSize() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public Dimension getMinContentSize() { + if (this.webViewWindowPtr != 0) { return WindowsWebViewJNI.getMinContentSize(this.webViewWindowPtr); } return null; } - /** {@inheritDoc} */ - public void setMinContentSize(Dimension size) - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public void setMinContentSize(Dimension size) { + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.setMinContentSize(this.webViewWindowPtr, size.width, size.height); } } - /** {@inheritDoc} */ - public URL getContentURL() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public URL getContentURL() { + if (this.webViewWindowPtr != 0) { return WWIO.makeURL(WindowsWebViewJNI.getContentURL(this.webViewWindowPtr)); } return null; } - protected void doSetFrameSize(Dimension size) - { - if (this.webViewWindowPtr != 0) + protected void doSetFrameSize(Dimension size) { + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.setFrameSize(this.webViewWindowPtr, size.width, size.height); + } } - /** {@inheritDoc} */ - public void sendEvent(InputEvent event) - { - if (event != null) - { + /** + * {@inheritDoc} + */ + public void sendEvent(InputEvent event) { + if (event != null) { // Convert OpenGL coordinates to Windows. - if (event instanceof MouseEvent) + if (event instanceof MouseEvent) { event = convertToWindows((MouseEvent) event); + } // Send the AWT InputEvent to the native WebView object - if (this.webViewWindowPtr != 0) + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.sendEvent(this.webViewWindowPtr, event); + } } } @@ -350,67 +331,72 @@ public void sendEvent(InputEvent event) * Overridden to apply the active state to the native WebView. */ @Override - public void setActive(boolean active) - { + public void setActive(boolean active) { super.setActive(active); - if (this.webViewWindowPtr != 0) + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.setActive(this.webViewWindowPtr, active); + } } - /** {@inheritDoc} */ - public void goBack() - { - if (this.webViewWindowPtr != 0) + /** + * {@inheritDoc} + */ + public void goBack() { + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.goBack(this.webViewWindowPtr); + } } - /** {@inheritDoc} */ - public void goForward() - { - if (this.webViewWindowPtr != 0) + /** + * {@inheritDoc} + */ + public void goForward() { + if (this.webViewWindowPtr != 0) { WindowsWebViewJNI.goForward(this.webViewWindowPtr); + } } - /** {@inheritDoc} */ - public void setBackgroundColor(Color color) - { - if (color == null) - { + /** + * {@inheritDoc} + */ + public void setBackgroundColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Only set the color if it actually changed - if (!color.equals(this.getBackgroundColor())) - { + if (!color.equals(this.getBackgroundColor())) { this.backgroundColor = color; // Convert the color to an RGB hex triplet string that the WebBrowser will understand int rgb = (color.getRed() & 0xFF) << 16 - | (color.getGreen() & 0xFF) << 8 - | (color.getBlue() & 0xFF); + | (color.getGreen() & 0xFF) << 8 + | (color.getBlue() & 0xFF); String colorString = String.format("#%06X", rgb); WindowsWebViewJNI.setBackgroundColor(this.webViewWindowPtr, colorString); } } - /** {@inheritDoc} */ - public Color getBackgroundColor() - { + /** + * {@inheritDoc} + */ + public Color getBackgroundColor() { return this.backgroundColor; } - /** {@inheritDoc} */ - public Iterable getLinks() - { - if (this.webViewWindowPtr != 0) - { + /** + * {@inheritDoc} + */ + public Iterable getLinks() { + if (this.webViewWindowPtr != 0) { AVList[] links = WindowsWebViewJNI.getLinks(this.webViewWindowPtr); - if (links != null) + if (links != null) { return Arrays.asList(links); + } } return Collections.emptyList(); } @@ -424,8 +410,7 @@ public Iterable getLinks() * * @return A new mouse event in the Windows coordinate system. */ - protected MouseEvent convertToWindows(MouseEvent e) - { + protected MouseEvent convertToWindows(MouseEvent e) { int x = e.getX(); int y = e.getY(); @@ -433,39 +418,35 @@ protected MouseEvent convertToWindows(MouseEvent e) // the upper left corner and flipping the direction of the Y axis. y = this.frameSize.height - y; - if (e instanceof MouseWheelEvent) - { + if (e instanceof MouseWheelEvent) { return new MouseWheelEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), x, y, - e.getClickCount(), e.isPopupTrigger(), ((MouseWheelEvent) e).getScrollType(), - ((MouseWheelEvent) e).getScrollAmount(), ((MouseWheelEvent) e).getWheelRotation()); - } - else - { + e.getClickCount(), e.isPopupTrigger(), ((MouseWheelEvent) e).getScrollType(), + ((MouseWheelEvent) e).getScrollAmount(), ((MouseWheelEvent) e).getWheelRotation()); + } else { return new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), x, y, - e.getClickCount(), e.isPopupTrigger(), e.getButton()); + e.getClickCount(), e.isPopupTrigger(), e.getButton()); } } //**********************************************************************// //******************** Texture Representation ************************// //**********************************************************************// - - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - protected WWTexture createTextureRepresentation(DrawContext dc) - { + protected WWTexture createTextureRepresentation(DrawContext dc) { BasicWWTexture texture = new WindowsWebViewTexture(this.getFrameSize(), false); texture.setUseAnisotropy(false); // Do not use anisotropic texture filtering. return texture; } - protected class WindowsWebViewTexture extends WebViewTexture - { + protected class WindowsWebViewTexture extends WebViewTexture { + protected long updateTime = -1; - public WindowsWebViewTexture(Dimension frameSize, boolean useMipMaps) - { + public WindowsWebViewTexture(Dimension frameSize, boolean useMipMaps) { super(frameSize, useMipMaps, true); } @@ -475,27 +456,27 @@ public WindowsWebViewTexture(Dimension frameSize, boolean useMipMaps) * @param dc Draw context */ @Override - protected void updateIfNeeded(DrawContext dc) - { + protected void updateIfNeeded(DrawContext dc) { // Return immediately if the native WebViewWindow object isn't initialized, and wait to update until the // native object is initialized. This method is called after the texture is bound, so we'll get another // chance to update as long as the WebView generates repaint events when it changes. long webViewWindowPtr = WindowsWebView.this.webViewWindowPtr; - if (webViewWindowPtr == 0) + if (webViewWindowPtr == 0) { return; + } // Return immediately if the texture isn't in the texture cache, and wait to update until the texture is // initialized and placed in the cache. This method is called after the texture is bound, so we'll get // another chance to update as long as the WebView generates repaint events when it changes. Texture texture = this.getTextureFromCache(dc); - if (texture == null) + if (texture == null) { return; + } // Load the WebViewWindow's current display pixels into the currently bound OGL texture if our update time // is different than the WebViewWindow's update time. long newUpdateTime = WindowsWebViewJNI.getUpdateTime(webViewWindowPtr); - if (newUpdateTime != this.updateTime) - { + if (newUpdateTime != this.updateTime) { WindowsWebViewJNI.loadDisplayInGLTexture(webViewWindowPtr, texture.getTarget()); this.updateTime = newUpdateTime; } diff --git a/src/gov/nasa/worldwind/util/webview/WindowsWebViewJNI.java b/src/gov/nasa/worldwind/util/webview/WindowsWebViewJNI.java index 100902d17f..d9886fd99d 100644 --- a/src/gov/nasa/worldwind/util/webview/WindowsWebViewJNI.java +++ b/src/gov/nasa/worldwind/util/webview/WindowsWebViewJNI.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.webview; import gov.nasa.worldwind.avlist.AVList; @@ -27,7 +26,7 @@ * thread. This enters a blocking loop in native code. It will not return until {@link #releaseMessageLoop(long)} is * called by another thread.
        • *

          - * Here is an example of creating and running a message loop: + * Here is an example of creating and running a message loop: *

            * long webViewMessageLoop = 0;
            * // Create a new thread to run the WebView message loop.
          @@ -66,28 +65,27 @@
            * @author pabercrombie
            * @version $Id: WindowsWebViewJNI.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class WindowsWebViewJNI
          -{
          -    static
          -    {
          -        try
          -        {
          +public class WindowsWebViewJNI {
          +
          +    static {
          +        try {
                       String architecture = System.getProperty("os.arch");
          -            if ("x86".equals(architecture))
          +            if ("x86".equals(architecture)) {
                           System.loadLibrary("WebView32");
          -            else
          +            } else {
                           System.loadLibrary("WebView64");
          +            }
           
                       initialize();
          -        }
          -        catch (Throwable t)
          -        {
          +        } catch (Throwable t) {
                       String message = Logging.getMessage("WebView.ExceptionCreatingWebView", t);
                       Logging.logger().severe(message);
                   }
               }
           
          -    /** Initialize the native library. This method must be called before any of the other methods in this class. */
          +    /**
          +     * Initialize the native library. This method must be called before any of the other methods in this class.
          +     */
               protected static native void initialize();
           
               /**
          @@ -140,8 +138,7 @@ public class WindowsWebViewJNI
                * Set a WebViewWindow to be active or inactive. The window only handles simulated input when it is active.
                *
                * @param webViewWindowPtr window to set active or inactive.
          -     * @param active           {@code true} if the window is being activated. {@code false} if the window is being
          -     *                         deactivated.
          +     * @param active {@code true} if the window is being activated. {@code false} if the window is being deactivated.
                */
               public static native void setActive(long webViewWindowPtr, boolean active);
           
          @@ -153,7 +150,7 @@ public class WindowsWebViewJNI
                * @param listener listener that will receive PropertyChangeEvents caused by changes in the native WebView
                *
                * @return identifier for the new notification adapter, or zero if creation fails. The notification adapter must be
          -     *         freed by {@code releaseComObject}.
          +     * freed by {@code releaseComObject}.
                *
                * @see #releaseComObject(long)
                */
          @@ -163,8 +160,8 @@ public class WindowsWebViewJNI
                * Set the HTML content of a WebView, with a base URL.
                *
                * @param webViewWindowPtr WebView window to set content of
          -     * @param htmlString       new HTML content
          -     * @param baseUrlString    base URL against which to resolve relative links
          +     * @param htmlString new HTML content
          +     * @param baseUrlString base URL against which to resolve relative links
                */
               public static native void setHTMLString(long webViewWindowPtr, String htmlString, String baseUrlString);
           
          @@ -172,18 +169,18 @@ public class WindowsWebViewJNI
                * Set the HTML content of a WebView, with a {@link WebResourceResolver} to resolve local references.
                *
                * @param webViewWindowPtr WebView window to set content of
          -     * @param htmlString       new HTML content
          -     * @param resolver         WebResourceResolver that will resolve local references in the HTML content.
          +     * @param htmlString new HTML content
          +     * @param resolver WebResourceResolver that will resolve local references in the HTML content.
                */
               public static native void setHTMLStringWithResourceResolver(long webViewWindowPtr, String htmlString,
          -        WebResourceResolver resolver);
          +            WebResourceResolver resolver);
           
               /**
                * Set the background color the WebView.
                *
                * @param webViewWindowPtr WebView window to set color of
          -     * @param colorString      Color expressed as a string. Color strings must follow the format defined by the HTML
          -     *                         specification.
          +     * @param colorString Color expressed as a string. Color strings must follow the format defined by the HTML
          +     * specification.
                */
               public static native void setBackgroundColor(long webViewWindowPtr, String colorString);
           
          @@ -191,8 +188,8 @@ public static native void setHTMLStringWithResourceResolver(long webViewWindowPt
                * Set the size of a WebView window.
                *
                * @param webViewWindowPtr window to set size of
          -     * @param width            new width
          -     * @param height           new height
          +     * @param width new width
          +     * @param height new height
                */
               public static native void setFrameSize(long webViewWindowPtr, int width, int height);
           
          @@ -200,7 +197,7 @@ public static native void setHTMLStringWithResourceResolver(long webViewWindowPt
                * Send an input event to a WebView window. The AWT InputEvent will translated into native Windows input messages.
                *
                * @param webViewWindowPtr window to send input to.
          -     * @param event            input event to send.
          +     * @param event input event to send.
                */
               public static native void sendEvent(long webViewWindowPtr, InputEvent event);
           
          @@ -218,7 +215,8 @@ public static native void setHTMLStringWithResourceResolver(long webViewWindowPt
                * input, etc)
                *
                * @param webViewWindowPtr pointer to native WebView to observe
          -     * @param observerPtr      notification adapter allocated by {@link #newNotificationAdapter(java.beans.PropertyChangeListener)}
          +     * @param observerPtr notification adapter allocated by
          +     * {@link #newNotificationAdapter(java.beans.PropertyChangeListener)}
                */
               public static native void addWindowUpdateObserver(long webViewWindowPtr, long observerPtr);
           
          @@ -226,7 +224,7 @@ public static native void setHTMLStringWithResourceResolver(long webViewWindowPt
                * Remove an update observer from a WebView.
                *
                * @param webViewWindowPtr pointer to native WebView from which to remove observer
          -     * @param observerPtr      observer to remove
          +     * @param observerPtr observer to remove
                */
               public static native void removeWindowUpdateObserver(long webViewWindowPtr, long observerPtr);
           
          @@ -234,7 +232,7 @@ public static native void setHTMLStringWithResourceResolver(long webViewWindowPt
                * Load the captured WebView image into an OpenGL texture.
                *
                * @param webViewWindowPtr pointer to native WebView to load into texture
          -     * @param target           GL texture identifier
          +     * @param target GL texture identifier
                */
               public static native void loadDisplayInGLTexture(long webViewWindowPtr, int target);
           
          @@ -260,8 +258,8 @@ public static native void setHTMLStringWithResourceResolver(long webViewWindowPt
                * Specifies the minimum size of the WebView content.
                *
                * @param webViewWindowPtr pointer to native WebView.
          -     * @param width            minimum width, in pixels.
          -     * @param height           minimum height, in pixels.
          +     * @param width minimum width, in pixels.
          +     * @param height minimum height, in pixels.
                */
               public static native void setMinContentSize(long webViewWindowPtr, int width, int height);
           
          diff --git a/src/gov/nasa/worldwind/util/webview/package-info.java b/src/gov/nasa/worldwind/util/webview/package-info.java
          index 0a2ea2ac1a..7c274cdb6f 100644
          --- a/src/gov/nasa/worldwind/util/webview/package-info.java
          +++ b/src/gov/nasa/worldwind/util/webview/package-info.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           /**
            *
            * Provides classes for loading web content, laying out and rendering the content as an OpenGL texture, and interacting
          diff --git a/src/gov/nasa/worldwind/util/wizard/DefaultPanelDescriptor.java b/src/gov/nasa/worldwind/util/wizard/DefaultPanelDescriptor.java
          index 2832704027..d50c758776 100644
          --- a/src/gov/nasa/worldwind/util/wizard/DefaultPanelDescriptor.java
          +++ b/src/gov/nasa/worldwind/util/wizard/DefaultPanelDescriptor.java
          @@ -14,30 +14,26 @@
            * @author dcollins
            * @version $Id: DefaultPanelDescriptor.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class DefaultPanelDescriptor implements WizardPanelDescriptor
          -{
          +public class DefaultPanelDescriptor implements WizardPanelDescriptor {
          +
               private Wizard wizard;
               private Object panelIdentifier;
               private Component panelComponent;
           
               private static final String DEFAULT_PANEL_IDENTIFIER = "wizard.DefaultPanelIdentifier";
           
          -    public DefaultPanelDescriptor()
          -    {
          +    public DefaultPanelDescriptor() {
                   this.panelIdentifier = DEFAULT_PANEL_IDENTIFIER;
                   this.panelComponent = new JPanel();
               }
           
          -    public DefaultPanelDescriptor(Object id, Component panel)
          -    {
          -        if (id == null)
          -        {
          +    public DefaultPanelDescriptor(Object id, Component panel) {
          +        if (id == null) {
                       String message = Logging.getMessage("nullValue.ObjectIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
          -        if (panel == null)
          -        {
          +        if (panel == null) {
                       String message = "Component is null";
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -47,25 +43,20 @@ public DefaultPanelDescriptor(Object id, Component panel)
                   this.panelComponent = panel;
               }
           
          -    public final Wizard getWizard()
          -    {
          +    public final Wizard getWizard() {
                   return this.wizard;
               }
           
          -    public final WizardModel getWizardModel()
          -    {
          +    public final WizardModel getWizardModel() {
                   return this.wizard != null ? this.wizard.getModel() : null;
               }
           
          -    public final Object getPanelIdentifier()
          -    {
          +    public final Object getPanelIdentifier() {
                   return this.panelIdentifier;
               }
           
          -    public final void setPanelIdentifier(Object panelIdentifier)
          -    {
          -        if (panelIdentifier == null)
          -        {
          +    public final void setPanelIdentifier(Object panelIdentifier) {
          +        if (panelIdentifier == null) {
                       String message = Logging.getMessage("nullValue.ObjectIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -74,15 +65,12 @@ public final void setPanelIdentifier(Object panelIdentifier)
                   this.panelIdentifier = panelIdentifier;
               }
           
          -    public final Component getPanelComponent()
          -    {
          +    public final Component getPanelComponent() {
                   return this.panelComponent;
               }
           
          -    public final void setPanelComponent(Component panel)
          -    {
          -        if (panel == null)
          -        {
          +    public final void setPanelComponent(Component panel) {
          +        if (panel == null) {
                       String message = "Component is null";
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -91,30 +79,24 @@ public final void setPanelComponent(Component panel)
                   this.panelComponent = panel;
               }
           
          -    public Object getBackPanelDescriptor()
          -    {
          +    public Object getBackPanelDescriptor() {
                   return null;
               }
           
          -    public Object getNextPanelDescriptor()
          -    {
          +    public Object getNextPanelDescriptor() {
                   return null;
               }
           
          -    public void registerPanel(Wizard wizard)
          -    {
          +    public void registerPanel(Wizard wizard) {
                   this.wizard = wizard;
               }
           
          -    public void aboutToDisplayPanel()
          -    {
          +    public void aboutToDisplayPanel() {
               }
           
          -    public void displayingPanel()
          -    {
          +    public void displayingPanel() {
               }
           
          -    public void aboutToHidePanel()
          -    {
          +    public void aboutToHidePanel() {
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/wizard/Wizard.java b/src/gov/nasa/worldwind/util/wizard/Wizard.java
          index d773fb2c84..d432f2c789 100644
          --- a/src/gov/nasa/worldwind/util/wizard/Wizard.java
          +++ b/src/gov/nasa/worldwind/util/wizard/Wizard.java
          @@ -20,8 +20,8 @@
            * @author dcollins
            * @version $Id: Wizard.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class Wizard
          -{
          +public class Wizard {
          +
               // Logical Wizard components.
               private WizardModel model;
               private WizardController controller;
          @@ -50,21 +50,18 @@ public class Wizard
           
               public static final FinishIdentifier FINISH = new FinishIdentifier();
           
          -    static class FinishIdentifier
          -    {
          +    static class FinishIdentifier {
          +
                   public static final String IDENTIFIER = "wizard.FinishIdentifier";
               }
          -    
          -    public Wizard()
          -    {
          +
          +    public Wizard() {
                   this.dialog = new JDialog();
                   init();
               }
           
          -    public Wizard(Dialog owner)
          -    {
          -        if (owner == null)
          -        {
          +    public Wizard(Dialog owner) {
          +        if (owner == null) {
                       String message = "Dialog is null";
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -74,10 +71,8 @@ public Wizard(Dialog owner)
                   init();
               }
           
          -    public Wizard(Frame owner)
          -    {
          -        if (owner == null)
          -        {
          +    public Wizard(Frame owner) {
          +        if (owner == null) {
                       String message = "Frame is null";
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -87,21 +82,17 @@ public Wizard(Frame owner)
                   init();
               }
           
          -    public WizardPanelDescriptor getWizardPanel(Object id)
          -    {
          +    public WizardPanelDescriptor getWizardPanel(Object id) {
                   return this.model.getWizardPanel(id);
               }
           
          -    public void registerWizardPanel(Object id, WizardPanelDescriptor panel)
          -    {
          -        if (id == null)
          -        {
          +    public void registerWizardPanel(Object id, WizardPanelDescriptor panel) {
          +        if (id == null) {
                       String message = Logging.getMessage("nullValue.ObjectIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
          -        if (panel == null || panel.getPanelComponent() == null)
          -        {
          +        if (panel == null || panel.getPanelComponent() == null) {
                       String message = "Panel or PanelComponent is null";
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -112,81 +103,71 @@ public void registerWizardPanel(Object id, WizardPanelDescriptor panel)
                   this.model.registerWizardPanel(id, panel);
               }
           
          -    public WizardPanelDescriptor getCurrentPanel()
          -    {
          +    public WizardPanelDescriptor getCurrentPanel() {
                   return this.model.getCurrentPanel();
               }
           
          -    public void setCurrentPanelDescriptor(Object id)
          -    {
          -        if (id == null)
          -        {
          +    public void setCurrentPanelDescriptor(Object id) {
          +        if (id == null) {
                       close(ERROR_RETURN_CODE);
                       return;
                   }
           
                   WizardPanelDescriptor oldPanel = this.model.getCurrentPanel();
          -        if (oldPanel != null)
          +        if (oldPanel != null) {
                       oldPanel.aboutToHidePanel();
          +        }
           
          -        if (!this.model.setCurrentPanel(id))
          -        {
          +        if (!this.model.setCurrentPanel(id)) {
                       return;
                   }
           
                   WizardPanelDescriptor newPanel = this.model.getCurrentPanel();
           
          -        if (newPanel != null)
          +        if (newPanel != null) {
                       newPanel.aboutToDisplayPanel();
          +        }
           
                   this.cardLayout.show(this.cardPanel, id.toString());
           
          -        if (newPanel != null)
          +        if (newPanel != null) {
                       newPanel.displayingPanel();
          +        }
               }
           
          -    public WizardModel getModel()
          -    {
          +    public WizardModel getModel() {
                   return this.model;
               }
           
          -    public int getReturnCode()
          -    {
          +    public int getReturnCode() {
                   return this.returnCode;
               }
           
          -    public Window getOwner()
          -    {
          +    public Window getOwner() {
                   return this.dialog.getOwner();
               }
           
          -    public JDialog getDialog()
          -    {
          +    public JDialog getDialog() {
                   return this.dialog;
               }
           
          -    public boolean isModal()
          -    {
          +    public boolean isModal() {
                   return this.dialog.isModal();
               }
           
          -    public void setModal(boolean b)
          -    {
          +    public void setModal(boolean b) {
                   this.dialog.setModal(b);
               }
           
          -    public String getTitle()
          -    {
          +    public String getTitle() {
                   return this.dialog.getTitle();
               }
           
          -    public void setTitle(String title)
          -    {
          +    public void setTitle(String title) {
                   this.dialog.setTitle(title);
               }
           
          -    public int showModalDialog()
          -    {
          +    public int showModalDialog() {
                   this.dialog.setModal(true);
                   this.dialog.pack();
                   this.dialog.setVisible(true);
          @@ -194,67 +175,57 @@ public int showModalDialog()
                   return this.returnCode;
               }
           
          -    void close(int code)
          -    {
          +    void close(int code) {
                   this.returnCode = code;
           
                   WizardPanelDescriptor panel = this.model.getCurrentPanel();
          -        if (panel != null)
          +        if (panel != null) {
                       panel.aboutToHidePanel();
          +        }
           
                   this.dialog.dispose();
               }
           
          -    public boolean isBackButtonEnabled()
          -    {
          +    public boolean isBackButtonEnabled() {
                   Boolean b = this.model.isBackButtonEnabled();
                   return b != null ? b : false;
               }
           
          -    public void setBackButtonEnabled(boolean b)
          -    {
          +    public void setBackButtonEnabled(boolean b) {
                   this.model.setBackButtonEnabled(b);
               }
           
          -    public boolean isNextButtonEnabled()
          -    {
          +    public boolean isNextButtonEnabled() {
                   Boolean b = this.model.isNextButtonEnabled();
                   return b != null ? b : false;
               }
           
          -    public void setNextButtonEnabled(boolean b)
          -    {
          +    public void setNextButtonEnabled(boolean b) {
                   this.model.setNextButtonEnabled(b);
               }
           
          -    public boolean isCancelButtonEnabled()
          -    {
          +    public boolean isCancelButtonEnabled() {
                   Boolean b = this.model.isCancelButtonEnabled();
                   return b != null ? b : false;
               }
           
          -    public void setCancelButtonEnabled(boolean b)
          -    {
          +    public void setCancelButtonEnabled(boolean b) {
                   this.model.setCancelButtonEnabled(b);
               }
           
          -    public void giveFocusToBackButton()
          -    {
          +    public void giveFocusToBackButton() {
                   this.backButton.requestFocusInWindow();
               }
           
          -    public void giveFocusToNextButton()
          -    {
          +    public void giveFocusToNextButton() {
                   this.nextButton.requestFocusInWindow();
               }
           
          -    public void giveFocusToCancelButton()
          -    {
          -        this.cancelButton.requestFocusInWindow();        
          +    public void giveFocusToCancelButton() {
          +        this.cancelButton.requestFocusInWindow();
               }
           
          -    private void init()
          -    {
          +    private void init() {
                   // Initialize logical components.
                   this.model = new WizardModel();
                   this.controller = new WizardController(this);
          @@ -272,8 +243,7 @@ private void init()
                   this.controller.resetButtonsToPanelRules();
               }
           
          -    private void makeComponents()
          -    {
          +    private void makeComponents() {
                   this.cardPanel = new JPanel();
                   this.cardLayout = new CardLayout();
           
          @@ -289,8 +259,7 @@ private void makeComponents()
                   this.dialog.getRootPane().setDefaultButton(this.nextButton);
               }
           
          -    private void layoutComponents()
          -    {
          +    private void layoutComponents() {
                   this.dialog.getContentPane().setLayout(new BorderLayout());
           
                   this.cardPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
          @@ -312,31 +281,26 @@ private void layoutComponents()
                   this.dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
               }
           
          -    private void setButtonText(JButton button, Object value)
          -    {
          -        if (button != null)
          -        {
          +    private void setButtonText(JButton button, Object value) {
          +        if (button != null) {
                       button.setText(value != null ? value.toString() : null);
                   }
               }
           
          -    private void setButtonEnabled(JButton button, Object value)
          -    {
          -        if (button != null)
          -        {
          +    private void setButtonEnabled(JButton button, Object value) {
          +        if (button != null) {
                       button.setEnabled(value != null && Boolean.parseBoolean(value.toString()));
                   }
               }
           
          -    private void setButtonIcon(JButton button, Object value)
          -    {
          -        if (button != null)
          -        {
          +    private void setButtonIcon(JButton button, Object value) {
          +        if (button != null) {
                       button.setIcon((value != null && value instanceof Icon) ? (Icon) value : null);
                   }
               }
          -    
          +
               private class PropertyEvents implements PropertyChangeListener {
          +
                   public void propertyChange(PropertyChangeEvent evt) {
                       if (evt != null && evt.getPropertyName() != null) {
                           String propertyName = evt.getPropertyName();
          @@ -370,6 +334,7 @@ public void propertyChange(PropertyChangeEvent evt) {
               }
           
               private class WindowEvents extends WindowAdapter {
          +
                   public void windowClosing(WindowEvent e) {
                       // Simulate a button's ActionEvent for window closing.
                       if (controller != null) {
          diff --git a/src/gov/nasa/worldwind/util/wizard/WizardController.java b/src/gov/nasa/worldwind/util/wizard/WizardController.java
          index cc9cfa4164..8d5f5f803c 100644
          --- a/src/gov/nasa/worldwind/util/wizard/WizardController.java
          +++ b/src/gov/nasa/worldwind/util/wizard/WizardController.java
          @@ -14,82 +14,68 @@
            * @author dcollins
            * @version $Id: WizardController.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -class WizardController implements ActionListener
          -{
          +class WizardController implements ActionListener {
          +
               private Wizard wizard;
           
          -    public WizardController(Wizard wizard)
          -    {
          -        if (wizard == null)
          -        {
          +    public WizardController(Wizard wizard) {
          +        if (wizard == null) {
                       String message = "Wizard is null";
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
          -        
          +
                   this.wizard = wizard;
               }
           
          -    public void actionPerformed(ActionEvent e)
          -    {
          -        if (e != null && e.getActionCommand() != null)
          -        {
          +    public void actionPerformed(ActionEvent e) {
          +        if (e != null && e.getActionCommand() != null) {
                       String actionCommand = e.getActionCommand();
          -            if (actionCommand.equals(Wizard.CANCEL_BUTTON_ACTION_COMMAND))
          +            if (actionCommand.equals(Wizard.CANCEL_BUTTON_ACTION_COMMAND)) {
                           cancelButtonPressed();
          -            else if (actionCommand.equals(Wizard.BACK_BUTTON_ACTION_COMMAND))
          +            } else if (actionCommand.equals(Wizard.BACK_BUTTON_ACTION_COMMAND)) {
                           backButtonPressed();
          -            else if (actionCommand.equals(Wizard.NEXT_BUTTON_ACTION_COMMAND))
          +            } else if (actionCommand.equals(Wizard.NEXT_BUTTON_ACTION_COMMAND)) {
                           nextButtonPressed();
          -            else if (actionCommand.equals(Wizard.DIALOG_CLOSE_ACTION_COMMAND))
          +            } else if (actionCommand.equals(Wizard.DIALOG_CLOSE_ACTION_COMMAND)) {
                           dialogClosed();
          +            }
                   }
               }
           
          -    private void backButtonPressed()
          -    {
          +    private void backButtonPressed() {
                   WizardModel model = this.wizard.getModel();
          -        if (model != null && model.getCurrentPanel() != null)
          -        {
          +        if (model != null && model.getCurrentPanel() != null) {
                       WizardPanelDescriptor descriptor = model.getCurrentPanel();
                       Object backPanelDescriptor = descriptor.getBackPanelDescriptor();
                       this.wizard.setCurrentPanelDescriptor(backPanelDescriptor);
                   }
               }
           
          -    private void nextButtonPressed()
          -    {
          +    private void nextButtonPressed() {
                   WizardModel model = this.wizard.getModel();
          -        if (model != null && model.getCurrentPanel() != null)
          -        {
          +        if (model != null && model.getCurrentPanel() != null) {
                       WizardPanelDescriptor descriptor = model.getCurrentPanel();
                       Object nextPanelDescriptor = descriptor.getNextPanelDescriptor();
          -            if (nextPanelDescriptor != null && nextPanelDescriptor instanceof Wizard.FinishIdentifier)
          -            {
          +            if (nextPanelDescriptor != null && nextPanelDescriptor instanceof Wizard.FinishIdentifier) {
                           this.wizard.close(Wizard.FINISH_RETURN_CODE);
          -            }
          -            else
          -            {
          +            } else {
                           this.wizard.setCurrentPanelDescriptor(nextPanelDescriptor);
                       }
                   }
               }
           
          -    private void cancelButtonPressed()
          -    {
          +    private void cancelButtonPressed() {
                   this.wizard.close(Wizard.CANCEL_RETURN_CODE);
               }
           
          -    private void dialogClosed()
          -    {
          +    private void dialogClosed() {
                   this.wizard.close(Wizard.CLOSED_RETURN_CODE);
               }
           
          -    void resetButtonsToPanelRules()
          -    {
          +    void resetButtonsToPanelRules() {
                   WizardModel model = this.wizard.getModel();
          -        if (model != null)
          -        {
          +        if (model != null) {
                       model.setCancelButtonText("Cancel");
                       model.setCancelButtonIcon(null);
           
          @@ -97,26 +83,25 @@ void resetButtonsToPanelRules()
                       model.setBackButtonIcon(null);
           
                       WizardPanelDescriptor descriptor = model.getCurrentPanel();
          -            
          -            if (descriptor != null && descriptor.getBackPanelDescriptor() != null)
          +
          +            if (descriptor != null && descriptor.getBackPanelDescriptor() != null) {
                           model.setBackButtonEnabled(Boolean.TRUE);
          -            else
          +            } else {
                           model.setBackButtonEnabled(Boolean.FALSE);
          +            }
           
          -            if (descriptor != null && descriptor.getNextPanelDescriptor() != null)
          +            if (descriptor != null && descriptor.getNextPanelDescriptor() != null) {
                           model.setNextButtonEnabled(Boolean.TRUE);
          -            else
          +            } else {
                           model.setNextButtonEnabled(Boolean.FALSE);
          +            }
           
                       if (descriptor != null
          -                && descriptor.getNextPanelDescriptor() != null
          -                && descriptor.getNextPanelDescriptor() instanceof Wizard.FinishIdentifier)
          -            {
          +                    && descriptor.getNextPanelDescriptor() != null
          +                    && descriptor.getNextPanelDescriptor() instanceof Wizard.FinishIdentifier) {
                           model.setNextButtonText("Finish");
                           model.setNextButtonIcon(null);
          -            }
          -            else
          -            {
          +            } else {
                           model.setNextButtonText("Next>");
                           model.setNextButtonIcon(null);
                       }
          diff --git a/src/gov/nasa/worldwind/util/wizard/WizardModel.java b/src/gov/nasa/worldwind/util/wizard/WizardModel.java
          index 374a5a46fa..fa88a89b09 100644
          --- a/src/gov/nasa/worldwind/util/wizard/WizardModel.java
          +++ b/src/gov/nasa/worldwind/util/wizard/WizardModel.java
          @@ -15,8 +15,8 @@
            * @author dcollins
            * @version $Id: WizardModel.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class WizardModel extends WizardProperties
          -{
          +public class WizardModel extends WizardProperties {
          +
               private Map panels;
           
               public static final String CURRENT_PANEL_DESCRIPTOR = "wizard.CurrentPanelDescriptor";
          @@ -30,39 +30,31 @@ public class WizardModel extends WizardProperties
               public static final String NEXT_BUTTON_ICON = "wizard.NextButtonIcon";
               public static final String CANCEL_BUTTON_ICON = "wizard.CancelButtonIcon";
           
          -    public WizardModel()
          -    {
          +    public WizardModel() {
                   this.panels = new HashMap();
               }
           
          -    public WizardPanelDescriptor getWizardPanel(Object id)
          -    {
          +    public WizardPanelDescriptor getWizardPanel(Object id) {
                   return this.panels.get(id);
               }
           
          -    public void registerWizardPanel(Object id, WizardPanelDescriptor panel)
          -    {
          -        if (id != null && panel != null)
          -        {
          +    public void registerWizardPanel(Object id, WizardPanelDescriptor panel) {
          +        if (id != null && panel != null) {
                       this.panels.put(id, panel);
                   }
               }
           
          -    public WizardPanelDescriptor getCurrentPanel()
          -    {
          +    public WizardPanelDescriptor getCurrentPanel() {
                   Object value = getProperty(CURRENT_PANEL_DESCRIPTOR);
                   return (value != null && value instanceof WizardPanelDescriptor) ? (WizardPanelDescriptor) value : null;
               }
           
          -    public boolean setCurrentPanel(Object id)
          -    {
          +    public boolean setCurrentPanel(Object id) {
                   boolean success = false;
                   WizardPanelDescriptor newPanel = this.panels.get(id);
          -        if (newPanel != null)
          -        {
          +        if (newPanel != null) {
                       WizardPanelDescriptor oldPanel = getCurrentPanel();
          -            if (oldPanel != newPanel)
          -            {
          +            if (oldPanel != newPanel) {
                           setProperty(CURRENT_PANEL_DESCRIPTOR, newPanel);
                           firePropertyChange(CURRENT_PANEL_DESCRIPTOR, oldPanel, newPanel);
                       }
          @@ -71,98 +63,79 @@ public boolean setCurrentPanel(Object id)
                   return success;
               }
           
          -    public String getBackButtonText()
          -    {
          +    public String getBackButtonText() {
                   return getStringProperty(BACK_BUTTON_TEXT);
               }
           
          -    public void setBackButtonText(String newText)
          -    {
          +    public void setBackButtonText(String newText) {
                   setProperty(BACK_BUTTON_TEXT, newText);
               }
           
          -    public String getNextButtonText()
          -    {
          +    public String getNextButtonText() {
                   return getStringProperty(NEXT_BUTTON_TEXT);
               }
           
          -    public void setNextButtonText(String newText)
          -    {
          +    public void setNextButtonText(String newText) {
                   setProperty(NEXT_BUTTON_TEXT, newText);
               }
           
          -    public String getCancelButtonText()
          -    {
          +    public String getCancelButtonText() {
                   return getStringProperty(CANCEL_BUTTON_TEXT);
               }
           
          -    public void setCancelButtonText(String newText)
          -    {
          +    public void setCancelButtonText(String newText) {
                   setProperty(CANCEL_BUTTON_TEXT, newText);
               }
           
          -    public Boolean isBackButtonEnabled()
          -    {
          +    public Boolean isBackButtonEnabled() {
                   return getBooleanProperty(BACK_BUTTON_ENABLED);
               }
           
          -    public void setBackButtonEnabled(Boolean newValue)
          -    {
          +    public void setBackButtonEnabled(Boolean newValue) {
                   setProperty(BACK_BUTTON_ENABLED, newValue);
               }
           
          -    public Boolean isNextButtonEnabled()
          -    {
          +    public Boolean isNextButtonEnabled() {
                   return getBooleanProperty(NEXT_BUTTON_ENABLED);
               }
           
          -    public void setNextButtonEnabled(Boolean newValue)
          -    {
          +    public void setNextButtonEnabled(Boolean newValue) {
                   setProperty(NEXT_BUTTON_ENABLED, newValue);
               }
           
          -    public Boolean isCancelButtonEnabled()
          -    {
          +    public Boolean isCancelButtonEnabled() {
                   return getBooleanProperty(CANCEL_BUTTON_ENABLED);
               }
           
          -    public void setCancelButtonEnabled(Boolean newValue)
          -    {
          +    public void setCancelButtonEnabled(Boolean newValue) {
                   setProperty(CANCEL_BUTTON_ENABLED, newValue);
               }
           
          -    public Icon getBackButtonIcon()
          -    {
          +    public Icon getBackButtonIcon() {
                   return getIconProperty(BACK_BUTTON_ICON);
               }
           
          -    public void setBackButtonIcon(Icon newIcon)
          -    {
          +    public void setBackButtonIcon(Icon newIcon) {
                   setProperty(BACK_BUTTON_ICON, newIcon);
               }
           
          -    public Icon getNextButtonIcon()
          -    {
          +    public Icon getNextButtonIcon() {
                   return getIconProperty(NEXT_BUTTON_ICON);
               }
           
          -    public void setNextButtonIcon(Icon newIcon)
          -    {
          +    public void setNextButtonIcon(Icon newIcon) {
                   setProperty(NEXT_BUTTON_ICON, newIcon);
               }
           
          -    public Icon getCancelButtonIcon()
          -    {
          +    public Icon getCancelButtonIcon() {
                   return getIconProperty(CANCEL_BUTTON_ICON);
               }
           
          -    public void setCancelButtonIcon(Icon newIcon)
          -    {
          +    public void setCancelButtonIcon(Icon newIcon) {
                   setProperty(CANCEL_BUTTON_ICON, newIcon);
               }
           
          -    public Icon getIconProperty(String propertyName)
          -    {
          +    public Icon getIconProperty(String propertyName) {
                   Object value = getProperty(propertyName);
                   return (value != null && value instanceof Icon) ? (Icon) value : null;
               }
          diff --git a/src/gov/nasa/worldwind/util/wizard/WizardPanelDescriptor.java b/src/gov/nasa/worldwind/util/wizard/WizardPanelDescriptor.java
          index 92e7901493..d36762599e 100644
          --- a/src/gov/nasa/worldwind/util/wizard/WizardPanelDescriptor.java
          +++ b/src/gov/nasa/worldwind/util/wizard/WizardPanelDescriptor.java
          @@ -12,8 +12,8 @@
            * @author dcollins
            * @version $Id: WizardPanelDescriptor.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public interface WizardPanelDescriptor
          -{
          +public interface WizardPanelDescriptor {
          +
               Component getPanelComponent();
           
               Object getBackPanelDescriptor();
          diff --git a/src/gov/nasa/worldwind/util/wizard/WizardProperties.java b/src/gov/nasa/worldwind/util/wizard/WizardProperties.java
          index cd00e1b388..456b0b5406 100644
          --- a/src/gov/nasa/worldwind/util/wizard/WizardProperties.java
          +++ b/src/gov/nasa/worldwind/util/wizard/WizardProperties.java
          @@ -14,65 +14,54 @@
            * @author dcollins
            * @version $Id: WizardProperties.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class WizardProperties
          -{
          +public class WizardProperties {
          +
               private Map properties;
               private PropertyChangeSupport propertyChangeSupport;
           
          -    public WizardProperties()
          -    {
          +    public WizardProperties() {
                   this.properties = new HashMap();
                   this.propertyChangeSupport = new PropertyChangeSupport(this);
               }
           
          -    public Object getProperty(String propertyName)
          -    {
          +    public Object getProperty(String propertyName) {
                   return propertyName != null ? this.properties.get(propertyName) : null;
               }
           
          -    public String getStringProperty(String propertyName)
          -    {
          +    public String getStringProperty(String propertyName) {
                   Object value = getProperty(propertyName);
                   return (value != null && value instanceof String) ? (String) value : null;
               }
           
          -    public Boolean getBooleanProperty(String propertyName)
          -    {
          +    public Boolean getBooleanProperty(String propertyName) {
                   Object value = getProperty(propertyName);
                   return (value != null && value instanceof Boolean) ? (Boolean) value : null;
               }
           
          -    public Integer getIntegerProperty(String propertyName)
          -    {
          +    public Integer getIntegerProperty(String propertyName) {
                   Object value = getProperty(propertyName);
                   return (value != null && value instanceof Integer) ? (Integer) value : null;
               }
           
          -    public void setProperty(String propertyName, Object newValue)
          -    {
          -        if (propertyName != null)
          -        {
          +    public void setProperty(String propertyName, Object newValue) {
          +        if (propertyName != null) {
                       Object oldValue = this.properties.get(propertyName);
          -            if (newValue != null ? !newValue.equals(oldValue) : oldValue != null)
          -            {
          +            if (newValue != null ? !newValue.equals(oldValue) : oldValue != null) {
                           this.properties.put(propertyName, newValue);
                           firePropertyChange(propertyName, oldValue, newValue);
                       }
                   }
               }
           
          -    public void addPropertyChangeListener(PropertyChangeListener listener)
          -    {
          +    public void addPropertyChangeListener(PropertyChangeListener listener) {
                   this.propertyChangeSupport.addPropertyChangeListener(listener);
               }
           
          -    public void removePropertyChangeListener(PropertyChangeListener listener)
          -    {
          +    public void removePropertyChangeListener(PropertyChangeListener listener) {
                   this.propertyChangeSupport.removePropertyChangeListener(listener);
               }
           
          -    public void firePropertyChange(String propertyName, Object oldValue, Object newValue)
          -    {
          +    public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
                   this.propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/AbstractXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/AbstractXMLEventParser.java
          index d3543aa107..ce0a993093 100644
          --- a/src/gov/nasa/worldwind/util/xml/AbstractXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/AbstractXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.avlist.*;
          @@ -33,8 +32,8 @@
            * @author tag
            * @version $Id: AbstractXMLEventParser.java 1981 2014-05-08 03:59:04Z tgaskins $
            */
          -abstract public class AbstractXMLEventParser implements XMLEventParser
          -{
          +abstract public class AbstractXMLEventParser implements XMLEventParser {
          +
               protected static final String CHARACTERS_CONTENT = "CharactersContent";
           
               protected String namespaceURI;
          @@ -42,9 +41,10 @@ abstract public class AbstractXMLEventParser implements XMLEventParser
               protected AVList fields;
               protected XMLEventParser parent;
           
          -    /** Construct a parser with no qualifying namespace. */
          -    public AbstractXMLEventParser()
          -    {
          +    /**
          +     * Construct a parser with no qualifying namespace.
          +     */
          +    public AbstractXMLEventParser() {
                   this.namespaceURI = null;
               }
           
          @@ -53,8 +53,7 @@ public AbstractXMLEventParser()
                *
                * @param namespaceURI the qualifying namespace URI. May be null to indicate no namespace qualification.
                */
          -    public AbstractXMLEventParser(String namespaceURI)
          -    {
          +    public AbstractXMLEventParser(String namespaceURI) {
                   this.namespaceURI = namespaceURI;
               }
           
          @@ -63,106 +62,93 @@ public AbstractXMLEventParser(String namespaceURI)
                *
                * @return the namespace URI. Returns null if no name space was specified at construction.
                */
          -    public String getNamespaceURI()
          -    {
          +    public String getNamespaceURI() {
                   return this.namespaceURI;
               }
           
          -    protected void setNamespaceURI(String namespaceURI)
          -    {
          +    protected void setNamespaceURI(String namespaceURI) {
                   this.namespaceURI = namespaceURI;
               }
           
          -    public XMLEventParser newInstance() throws Exception
          -    {
          +    public XMLEventParser newInstance() throws Exception {
                   Constructor constructor = this.getAConstructor(String.class);
          -        if (constructor != null)
          +        if (constructor != null) {
                       return constructor.newInstance(this.getNamespaceURI());
          +        }
           
                   constructor = this.getAConstructor();
          -        if (constructor != null)
          +        if (constructor != null) {
                       return constructor.newInstance();
          +        }
           
                   return null;
               }
           
          -    public void setField(QName keyName, Object value)
          -    {
          +    public void setField(QName keyName, Object value) {
                   this.setField(keyName.getLocalPart(), value);
               }
           
          -    public void setField(String keyName, Object value)
          -    {
          -        if (this.fields == null)
          +    public void setField(String keyName, Object value) {
          +        if (this.fields == null) {
                       this.fields = new AVListImpl();
          +        }
           
                   this.fields.setValue(keyName, value);
               }
           
          -    public void setFields(Map newFields)
          -    {
          -        if (this.fields == null)
          +    public void setFields(Map newFields) {
          +        if (this.fields == null) {
                       this.fields = new AVListImpl();
          +        }
           
          -        for (Map.Entry nf : newFields.entrySet())
          -        {
          +        for (Map.Entry nf : newFields.entrySet()) {
                       this.setField(nf.getKey(), nf.getValue());
                   }
               }
           
          -    public Object getField(QName keyName)
          -    {
          +    public Object getField(QName keyName) {
                   return this.fields != null ? this.getField(keyName.getLocalPart()) : null;
               }
           
          -    public Object getField(String keyName)
          -    {
          +    public Object getField(String keyName) {
                   return this.fields != null ? this.fields.getValue(keyName) : null;
               }
           
          -    public boolean hasField(QName keyName)
          -    {
          +    public boolean hasField(QName keyName) {
                   return this.hasField(keyName.getLocalPart());
               }
           
          -    public boolean hasField(String keyName)
          -    {
          +    public boolean hasField(String keyName) {
                   return this.fields != null && this.fields.hasKey(keyName);
               }
           
          -    public void removeField(String keyName)
          -    {
          -        if (this.fields != null)
          +    public void removeField(String keyName) {
          +        if (this.fields != null) {
                       this.fields.removeKey(keyName);
          +        }
               }
           
          -    public boolean hasFields()
          -    {
          +    public boolean hasFields() {
                   return this.fields != null;
               }
           
          -    public AVList getFields()
          -    {
          +    public AVList getFields() {
                   return this.fields;
               }
           
          -    protected AbstractXMLEventParser mergeFields(AbstractXMLEventParser s1, AbstractXMLEventParser s2)
          -    {
          -        for (Map.Entry entry : s2.getFields().getEntries())
          -        {
          -            if (!s1.hasField(entry.getKey()))
          +    protected AbstractXMLEventParser mergeFields(AbstractXMLEventParser s1, AbstractXMLEventParser s2) {
          +        for (Map.Entry entry : s2.getFields().getEntries()) {
          +            if (!s1.hasField(entry.getKey())) {
                           s1.setField(entry.getKey(), entry.getValue());
          +            }
                   }
           
                   return this;
               }
           
          -    protected AbstractXMLEventParser overrideFields(AbstractXMLEventParser s1, AbstractXMLEventParser s2)
          -    {
          -        if (s2.getFields() != null)
          -        {
          -            for (Map.Entry entry : s2.getFields().getEntries())
          -            {
          +    protected AbstractXMLEventParser overrideFields(AbstractXMLEventParser s1, AbstractXMLEventParser s2) {
          +        if (s2.getFields() != null) {
          +            for (Map.Entry entry : s2.getFields().getEntries()) {
                           s1.setField(entry.getKey(), entry.getValue());
                       }
                   }
          @@ -170,42 +156,34 @@ protected AbstractXMLEventParser overrideFields(AbstractXMLEventParser s1, Abstr
                   return this;
               }
           
          -    public XMLEventParser getParent()
          -    {
          +    public XMLEventParser getParent() {
                   return this.parent;
               }
           
          -    public void setParent(XMLEventParser parent)
          -    {
          +    public void setParent(XMLEventParser parent) {
                   this.parent = parent;
               }
           
          -    public void freeResources()
          -    {
          +    public void freeResources() {
                   // Override in subclass to free any large resources.
               }
           
          -    protected Constructor getAConstructor(Class... parameterTypes)
          -    {
          -        try
          -        {
          +    protected Constructor getAConstructor(Class... parameterTypes) {
          +        try {
                       return this.getClass().getConstructor(parameterTypes);
          -        }
          -        catch (NoSuchMethodException e)
          -        {
          +        } catch (NoSuchMethodException e) {
                       return null;
                   }
               }
           
          -    public XMLEventParser getRoot()
          -    {
          +    public XMLEventParser getRoot() {
                   XMLEventParser parser = this;
           
          -        while (true)
          -        {
          +        while (true) {
                       XMLEventParser parent = parser.getParent();
          -            if (parent == null)
          +            if (parent == null) {
                           return parser;
          +            }
                       parser = parent;
                   }
               }
          @@ -213,94 +191,87 @@ public XMLEventParser getRoot()
               /**
                * Create a parser for a specified event.
                *
          -     * @param ctx   the current parser context.
          +     * @param ctx the current parser context.
                * @param event the event for which the parser is created. Only the event type is used; the new parser can operate
          -     *              on any event of that type.
          +     * on any event of that type.
                *
                * @return the new parser.
                */
          -    public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event)
          -    {
          -        if (ctx == null)
          -        {
          +    public XMLEventParser allocate(XMLEventParserContext ctx, XMLEvent event) {
          +        if (ctx == null) {
                       String message = Logging.getMessage("nullValue.ParserContextIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
                   XMLEventParser parser = ctx.allocate(event);
          -        if (parser != null)
          +        if (parser != null) {
                       parser.setParent(this);
          +        }
           
                   return parser;
               }
           
          -    /** {@inheritDoc} */
          -    public Object parse(XMLEventParserContext ctx, XMLEvent inputEvent, Object... args) throws XMLStreamException
          -    {
          -        if (ctx == null)
          -        {
          +    /**
          +     * {@inheritDoc}
          +     */
          +    public Object parse(XMLEventParserContext ctx, XMLEvent inputEvent, Object... args) throws XMLStreamException {
          +        if (ctx == null) {
                       String message = Logging.getMessage("nullValue.ParserContextIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
          -        if (inputEvent == null)
          -        {
          +        if (inputEvent == null) {
                       String message = Logging.getMessage("nullValue.EventIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
          -        try
          -        {
          +        try {
                       // Parse this event's attributes
                       this.doParseEventAttributes(ctx, inputEvent, args);
           
                       // Build the symbol table
                       String id = (String) this.getField("id");
          -            if (id != null)
          +            if (id != null) {
                           ctx.addId(id, this);
          -        }
          -        catch (XMLStreamException e)
          -        {
          +            }
          +        } catch (XMLStreamException e) {
                       ctx.firePropertyChange(new XMLParserNotification(ctx, XMLParserNotification.EXCEPTION, inputEvent,
          -                "XML.ExceptionParsingElement", null, e));
          +                    "XML.ExceptionParsingElement", null, e));
                   }
           
                   // Parse the event's subelements.
          -        for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent())
          -        {
          -            if (event == null)
          +        for (XMLEvent event = ctx.nextEvent(); ctx.hasNext(); event = ctx.nextEvent()) {
          +            if (event == null) {
                           continue;
          +            }
           
          -            if (ctx.isEndElement(event, inputEvent))
          -            {
          -                if (this.hasField(CHARACTERS_CONTENT))
          -                {
          +            if (ctx.isEndElement(event, inputEvent)) {
          +                if (this.hasField(CHARACTERS_CONTENT)) {
                               StringBuilder sb = (StringBuilder) this.getField(CHARACTERS_CONTENT);
          -                    if (sb != null && sb.length() > 0)
          +                    if (sb != null && sb.length() > 0) {
                                   this.setField(CHARACTERS_CONTENT, sb.toString());
          -                    else
          +                    } else {
                                   this.removeField(CHARACTERS_CONTENT);
          +                    }
                           }
           
                           return this;
                       }
           
          -            try
          -            {
          -                if (event.isCharacters())
          +            try {
          +                if (event.isCharacters()) {
                               this.doAddCharacters(ctx, event, args);
          -                else
          +                } else {
                               this.doParseEventContent(ctx, event, args);
          -            }
          -            catch (XMLStreamException e)
          -            {
          +                }
          +            } catch (XMLStreamException e) {
                           ctx.firePropertyChange(
          -                    new XMLParserNotification(ctx, XMLParserNotification.EXCEPTION, event,
          -                        "XML.ExceptionParsingElement",
          -                        null, e));
          +                        new XMLParserNotification(ctx, XMLParserNotification.EXCEPTION, event,
          +                                "XML.ExceptionParsingElement",
          +                                null, e));
                       }
                   }
           
          @@ -308,59 +279,57 @@ public Object parse(XMLEventParserContext ctx, XMLEvent inputEvent, Object... ar
               }
           
               @SuppressWarnings({"UnusedDeclaration"})
          -    protected void doAddCharacters(XMLEventParserContext ctx, XMLEvent event, Object... args)
          -    {
          +    protected void doAddCharacters(XMLEventParserContext ctx, XMLEvent event, Object... args) {
                   String s = ctx.getCharacters(event);
          -        if (WWUtil.isEmpty(s))
          +        if (WWUtil.isEmpty(s)) {
                       return;
          +        }
           
                   StringBuilder sb = (StringBuilder) this.getField(CHARACTERS_CONTENT);
          -        if (sb != null)
          +        if (sb != null) {
                       sb.append(s);
          -        else
          +        } else {
                       this.setField(CHARACTERS_CONTENT, new StringBuilder(s));
          +        }
               }
           
          -    public String getCharacters()
          -    {
          +    public String getCharacters() {
                   return (String) this.getField(CHARACTERS_CONTENT);
               }
           
               /**
                * Parse an event's sub-elements.
                *
          -     * @param ctx   a current parser context.
          +     * @param ctx a current parser context.
                * @param event the event to parse.
          -     * @param args  an optional list of arguments that may by used by subclasses.
          +     * @param args an optional list of arguments that may by used by subclasses.
                *
                * @throws XMLStreamException if an exception occurs during event-stream reading.
                */
               protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args)
          -        throws XMLStreamException
          -    {
          +            throws XMLStreamException {
                   // Override in subclass to parse an event's sub-elements.
          -        if (event.isStartElement())
          -        {
          +        if (event.isStartElement()) {
                       XMLEventParser parser = this.allocate(ctx, event);
           
          -            if (parser == null)
          -            {
          +            if (parser == null) {
                           ctx.firePropertyChange(
          -                    new XMLParserNotification(ctx, XMLParserNotification.UNRECOGNIZED, event, "XML.UnrecognizedElement",
          -                        null, event));
          +                        new XMLParserNotification(ctx, XMLParserNotification.UNRECOGNIZED, event, "XML.UnrecognizedElement",
          +                                null, event));
                           parser = ctx.getUnrecognizedElementParser();
           
                           // Register an unrecognized parser for the element type.
                           QName elementName = event.asStartElement().getName();
          -                if (elementName != null)
          +                if (elementName != null) {
                               ctx.registerParser(elementName, parser);
          +                }
                       }
           
          -            if (parser != null)
          -            {
          +            if (parser != null) {
                           Object o = parser.parse(ctx, event, args);
          -                if (o == null)
          +                if (o == null) {
                               return;
          +                }
           
                           this.doAddEventContent(o, ctx, event, args);
                       }
          @@ -368,8 +337,7 @@ protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Ob
               }
           
               protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args)
          -        throws XMLStreamException
          -    {
          +            throws XMLStreamException {
                   // Override in subclass if need to react to certain elements.
                   this.setField(event.asStartElement().getName(), o);
               }
          @@ -377,48 +345,45 @@ protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent e
               /**
                * Parse an event's attributes.
                *
          -     * @param ctx   a current parser context.
          +     * @param ctx a current parser context.
                * @param event the event to parse.
          -     * @param args  an optional list of arguments that may by used by subclasses.
          +     * @param args an optional list of arguments that may by used by subclasses.
                *
                * @throws XMLStreamException if an exception occurs during event-stream reading.
                */
               protected void doParseEventAttributes(XMLEventParserContext ctx, XMLEvent event, Object... args)
          -        throws XMLStreamException
          -    {
          +            throws XMLStreamException {
                   Iterator iter = event.asStartElement().getAttributes();
          -        if (iter == null)
          +        if (iter == null) {
                       return;
          +        }
           
          -        while (iter.hasNext())
          -        {
          +        while (iter.hasNext()) {
                       this.doAddEventAttribute((Attribute) iter.next(), ctx, event, args);
                   }
               }
           
               protected void doAddEventAttribute(Attribute attr, XMLEventParserContext ctx, XMLEvent event, Object... args)
          -        throws XMLStreamException
          -    {
          +            throws XMLStreamException {
                   // Override in subclass if need to react to certain attributes.
                   this.setField(attr.getName(), attr.getValue());
               }
           
               @SuppressWarnings({"UnusedDeclaration"})
               protected String parseCharacterContent(XMLEventParserContext ctx, XMLEvent stringEvent, Object... args)
          -        throws XMLStreamException
          -    {
          +            throws XMLStreamException {
                   StringBuilder value = new StringBuilder();
           
          -        for (XMLEvent event = ctx.nextEvent(); event != null; event = ctx.nextEvent())
          -        {
          -            if (ctx.isEndElement(event, stringEvent))
          +        for (XMLEvent event = ctx.nextEvent(); event != null; event = ctx.nextEvent()) {
          +            if (ctx.isEndElement(event, stringEvent)) {
                           return value.length() > 0 ? value.toString() : null;
          +            }
           
          -            if (event.isCharacters())
          -            {
          +            if (event.isCharacters()) {
                           String s = ctx.getCharacters(event);
          -                if (s != null)
          +                if (s != null) {
                               value.append(s);
          +                }
                       }
                   }
           
          diff --git a/src/gov/nasa/worldwind/util/xml/AngleXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/AngleXMLEventParser.java
          index 760a6c87a1..461df6fc59 100644
          --- a/src/gov/nasa/worldwind/util/xml/AngleXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/AngleXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.geom.Angle;
          @@ -16,37 +15,34 @@
            * @author tag
            * @version $Id: AngleXMLEventParser.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class AngleXMLEventParser extends AbstractXMLEventParser
          -{
          +public class AngleXMLEventParser extends AbstractXMLEventParser {
          +
               protected QName elementName;
           
          -    public AngleXMLEventParser(QName elementName)
          -    {
          +    public AngleXMLEventParser(QName elementName) {
                   this.elementName = elementName;
               }
           
          -    public Object parse(XMLEventParserContext ctx, XMLEvent angleEvent, Object... args) throws XMLStreamException
          -    {
          +    public Object parse(XMLEventParserContext ctx, XMLEvent angleEvent, Object... args) throws XMLStreamException {
                   Angle angle = null;
           
          -        for (XMLEvent event = ctx.nextEvent(); event != null; event = ctx.nextEvent())
          -        {
          -            if (ctx.isEndElement(event, angleEvent))
          +        for (XMLEvent event = ctx.nextEvent(); event != null; event = ctx.nextEvent()) {
          +            if (ctx.isEndElement(event, angleEvent)) {
                           return angle;
          +            }
           
          -            if (ctx.isStartElement(event, this.elementName))
          -            {
          +            if (ctx.isStartElement(event, this.elementName)) {
                           Double d = ctx.getDoubleParser().parseDouble(ctx, event);
          -                if (d != null)
          +                if (d != null) {
                               angle = Angle.fromDegrees(d);
          +                }
                       }
                   }
           
                   return null;
               }
           
          -    public Angle parseAngle(XMLEventParserContext ctx, XMLEvent angleEvent, Object... args) throws XMLStreamException
          -    {
          +    public Angle parseAngle(XMLEventParserContext ctx, XMLEvent angleEvent, Object... args) throws XMLStreamException {
                   return (Angle) this.parse(ctx, angleEvent, args);
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/AttributesOnlyXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/AttributesOnlyXMLEventParser.java
          index 10348f916e..5288fbe1ba 100644
          --- a/src/gov/nasa/worldwind/util/xml/AttributesOnlyXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/AttributesOnlyXMLEventParser.java
          @@ -3,21 +3,18 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           /**
            * @author tag
            * @version $Id: AttributesOnlyXMLEventParser.java 1981 2014-05-08 03:59:04Z tgaskins $
            */
          -public class AttributesOnlyXMLEventParser extends AbstractXMLEventParser
          -{
          -    public AttributesOnlyXMLEventParser()
          -    {
          +public class AttributesOnlyXMLEventParser extends AbstractXMLEventParser {
          +
          +    public AttributesOnlyXMLEventParser() {
               }
           
          -    public AttributesOnlyXMLEventParser(String namespaceURI)
          -    {
          +    public AttributesOnlyXMLEventParser(String namespaceURI) {
                   super(namespaceURI);
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/BasicXMLEventParserContext.java b/src/gov/nasa/worldwind/util/xml/BasicXMLEventParserContext.java
          index b8b7bed039..faf39be247 100644
          --- a/src/gov/nasa/worldwind/util/xml/BasicXMLEventParserContext.java
          +++ b/src/gov/nasa/worldwind/util/xml/BasicXMLEventParserContext.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.avlist.AVListImpl;
          @@ -25,19 +24,31 @@
            * @author tag
            * @version $Id: BasicXMLEventParserContext.java 1981 2014-05-08 03:59:04Z tgaskins $
            */
          -public class BasicXMLEventParserContext extends AVListImpl implements XMLEventParserContext
          -{
          -    /** The parser name of the default double parser. */
          +public class BasicXMLEventParserContext extends AVListImpl implements XMLEventParserContext {
          +
          +    /**
          +     * The parser name of the default double parser.
          +     */
               public static QName DOUBLE = new QName("Double");
          -    /** The parser name of the default integer parser. */
          +    /**
          +     * The parser name of the default integer parser.
          +     */
               public static QName INTEGER = new QName("Integer");
          -    /** The parser name of the default string parser. */
          +    /**
          +     * The parser name of the default string parser.
          +     */
               public static QName STRING = new QName("String");
          -    /** The parser name of the default boolean parser. */
          +    /**
          +     * The parser name of the default boolean parser.
          +     */
               public static QName BOOLEAN = new QName("Boolean");
          -    /** The parser name of the default boolean integer parser. */
          +    /**
          +     * The parser name of the default boolean integer parser.
          +     */
               public static QName BOOLEAN_INTEGER = new QName("BooleanInteger");
          -    /** The parser name of the unrecognized-element parser. */
          +    /**
          +     * The parser name of the unrecognized-element parser.
          +     */
               public static QName UNRECOGNIZED = new QName(UNRECOGNIZED_ELEMENT_PARSER);
           
               protected XMLEventReader reader;
          @@ -52,9 +63,10 @@ public class BasicXMLEventParserContext extends AVListImpl implements XMLEventPa
           
               protected ConcurrentHashMap parsers = new ConcurrentHashMap();
           
          -    /** Construct an instance. Invokes {@link #initializeParsers()} and {@link #initialize()}. */
          -    public BasicXMLEventParserContext()
          -    {
          +    /**
          +     * Construct an instance. Invokes {@link #initializeParsers()} and {@link #initialize()}.
          +     */
          +    public BasicXMLEventParserContext() {
                   this.initializeParsers();
                   this.initialize();
               }
          @@ -65,8 +77,7 @@ public BasicXMLEventParserContext()
                *
                * @param eventReader the event reader to use for XML parsing.
                */
          -    public BasicXMLEventParserContext(XMLEventReader eventReader)
          -    {
          +    public BasicXMLEventParserContext(XMLEventReader eventReader) {
                   this.reader = eventReader;
           
                   this.initializeParsers();
          @@ -77,11 +88,10 @@ public BasicXMLEventParserContext(XMLEventReader eventReader)
                * Construct an instance for a specified event reader and default namespace. Invokes {@link #initializeParsers()}
                * and {@link #initialize()}.
                *
          -     * @param eventReader      the event reader to use for XML parsing.
          +     * @param eventReader the event reader to use for XML parsing.
                * @param defaultNamespace the namespace URI of the default namespace.
                */
          -    public BasicXMLEventParserContext(XMLEventReader eventReader, String defaultNamespace)
          -    {
          +    public BasicXMLEventParserContext(XMLEventReader eventReader, String defaultNamespace) {
                   this.reader = eventReader;
                   this.setDefaultNamespaceURI(defaultNamespace);
           
          @@ -89,49 +99,41 @@ public BasicXMLEventParserContext(XMLEventReader eventReader, String defaultName
                   this.initialize();
               }
           
          -    public BasicXMLEventParserContext(BasicXMLEventParserContext ctx)
          -    {
          +    public BasicXMLEventParserContext(BasicXMLEventParserContext ctx) {
                   this.parsers = ctx.parsers;
                   this.setDefaultNamespaceURI(ctx.getDefaultNamespaceURI());
                   this.initialize();
               }
           
          -    protected void initialize()
          -    {
          +    protected void initialize() {
                   this.initializeDefaultNotificationListener();
               }
           
          -    protected void initializeDefaultNotificationListener()
          -    {
          -        this.addPropertyChangeListener(new PropertyChangeListener()
          -        {
          -            public void propertyChange(PropertyChangeEvent propEvent)
          -            {
          +    protected void initializeDefaultNotificationListener() {
          +        this.addPropertyChangeListener(new PropertyChangeListener() {
          +            public void propertyChange(PropertyChangeEvent propEvent) {
                           XMLParserNotification notification = (XMLParserNotification) propEvent;
           
          -                if (notificationListener != null)
          -                {
          +                if (notificationListener != null) {
                               notificationListener.notify(notification);
                               return;
                           }
           
                           String msg;
          -                if (notification.getEvent() != null)
          -                {
          +                if (notification.getEvent() != null) {
                               msg = Logging.getMessage(notification.getMessage(), notification.getEvent().toString(),
          -                        notification.getEvent().getLocation().getLineNumber(),
          -                        notification.getEvent().getLocation().getColumnNumber(),
          -                        notification.getEvent().getLocation().getCharacterOffset());
          -                }
          -                else
          -                {
          +                            notification.getEvent().getLocation().getLineNumber(),
          +                            notification.getEvent().getLocation().getColumnNumber(),
          +                            notification.getEvent().getLocation().getCharacterOffset());
          +                } else {
                               msg = Logging.getMessage(notification.getMessage(), "", "");
                           }
           
          -                if (notification.getPropertyName().equals(XMLParserNotification.EXCEPTION))
          +                if (notification.getPropertyName().equals(XMLParserNotification.EXCEPTION)) {
                               Logging.logger().log(Level.WARNING, msg);
          -                else if (notification.getPropertyName().equals(XMLParserNotification.UNRECOGNIZED))
          +                } else if (notification.getPropertyName().equals(XMLParserNotification.UNRECOGNIZED)) {
                               Logging.logger().log(Level.WARNING, msg);
          +                }
                       }
                   });
               }
          @@ -140,8 +142,7 @@ else if (notification.getPropertyName().equals(XMLParserNotification.UNRECOGNIZE
                * Initializes the parser table with the default parsers for the strings, integers, etc., qualified for the default
                * namespace.
                */
          -    protected void initializeParsers()
          -    {
          +    protected void initializeParsers() {
                   this.parsers.put(STRING, new StringXMLEventParser());
                   this.parsers.put(DOUBLE, new DoubleXMLEventParser());
                   this.parsers.put(INTEGER, new IntegerXMLEventParser());
          @@ -151,51 +152,41 @@ protected void initializeParsers()
               }
           
               @Override
          -    public void addStringParsers(String namespace, String[] stringFields)
          -    {
          +    public void addStringParsers(String namespace, String[] stringFields) {
                   StringXMLEventParser stringParser = this.getStringParser();
          -        for (String s : stringFields)
          -        {
          +        for (String s : stringFields) {
                       this.parsers.put(new QName(namespace, s), stringParser);
                   }
               }
           
               @Override
          -    public void addDoubleParsers(String namespace, String[] doubleFields)
          -    {
          +    public void addDoubleParsers(String namespace, String[] doubleFields) {
                   DoubleXMLEventParser doubleParser = this.getDoubleParser();
          -        for (String s : doubleFields)
          -        {
          +        for (String s : doubleFields) {
                       this.parsers.put(new QName(namespace, s), doubleParser);
                   }
               }
           
               @Override
          -    public void addIntegerParsers(String namespace, String[] integerFields)
          -    {
          +    public void addIntegerParsers(String namespace, String[] integerFields) {
                   IntegerXMLEventParser integerParser = this.getIntegerParser();
          -        for (String s : integerFields)
          -        {
          +        for (String s : integerFields) {
                       this.parsers.put(new QName(namespace, s), integerParser);
                   }
               }
           
               @Override
          -    public void addBooleanParsers(String namespace, String[] booleanFields)
          -    {
          +    public void addBooleanParsers(String namespace, String[] booleanFields) {
                   BooleanXMLEventParser booleanParser = this.getBooleanParser();
          -        for (String s : booleanFields)
          -        {
          +        for (String s : booleanFields) {
                       this.parsers.put(new QName(namespace, s), booleanParser);
                   }
               }
           
               @Override
          -    public void addBooleanIntegerParsers(String namespace, String[] booleanIntegerFields)
          -    {
          +    public void addBooleanIntegerParsers(String namespace, String[] booleanIntegerFields) {
                   BooleanIntegerXMLEventParser booleanIntegerParser = this.getBooleanIntegerParser();
          -        for (String s : booleanIntegerFields)
          -        {
          +        for (String s : booleanIntegerFields) {
                       this.parsers.put(new QName(namespace, s), booleanIntegerParser);
                   }
               }
          @@ -205,8 +196,7 @@ public void addBooleanIntegerParsers(String namespace, String[] booleanIntegerFi
                *
                * @return the instance's event reader.
                */
          -    public XMLEventReader getEventReader()
          -    {
          +    public XMLEventReader getEventReader() {
                   return this.reader;
               }
           
          @@ -215,10 +205,8 @@ public XMLEventReader getEventReader()
                *
                * @param reader the event reader to use.
                */
          -    public void setEventReader(XMLEventReader reader)
          -    {
          -        if (reader == null)
          -        {
          +    public void setEventReader(XMLEventReader reader) {
          +        if (reader == null) {
                       String message = Logging.getMessage("nullValue.EventIsNull"); // TODO
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -227,45 +215,39 @@ public void setEventReader(XMLEventReader reader)
                   this.reader = reader;
               }
           
          -    public String getDefaultNamespaceURI()
          -    {
          +    public String getDefaultNamespaceURI() {
                   return defaultNamespaceURI;
               }
           
          -    public void setDefaultNamespaceURI(String defaultNamespaceURI)
          -    {
          +    public void setDefaultNamespaceURI(String defaultNamespaceURI) {
                   this.defaultNamespaceURI = defaultNamespaceURI;
               }
           
          -    public void setNotificationListener(XMLParserNotificationListener listener)
          -    {
          +    public void setNotificationListener(XMLParserNotificationListener listener) {
                   this.notificationListener = listener;
               }
           
          -    public Map getIdTable()
          -    {
          +    public Map getIdTable() {
                   return this.idTable;
               }
           
          -    public void addId(String id, Object o)
          -    {
          -        if (id != null)
          +    public void addId(String id, Object o) {
          +        if (id != null) {
                       this.getIdTable().put(id, o);
          +        }
               }
           
          -    public boolean hasNext()
          -    {
          +    public boolean hasNext() {
                   return this.getEventReader().hasNext();
               }
           
          -    public XMLEvent nextEvent() throws XMLStreamException
          -    {
          -        while (this.hasNext())
          -        {
          +    public XMLEvent nextEvent() throws XMLStreamException {
          +        while (this.hasNext()) {
                       XMLEvent event = this.getEventReader().nextEvent();
           
          -            if (event.isCharacters() && event.asCharacters().isWhiteSpace())
          +            if (event.isCharacters() && event.asCharacters().isWhiteSpace()) {
                           continue;
          +            }
           
                       return event;
                   }
          @@ -273,75 +255,71 @@ public XMLEvent nextEvent() throws XMLStreamException
                   return null;
               }
           
          -    public XMLEventParser allocate(XMLEvent event, XMLEventParser defaultParser)
          -    {
          +    public XMLEventParser allocate(XMLEvent event, XMLEventParser defaultParser) {
                   return this.getParser(event, defaultParser);
               }
           
          -    public XMLEventParser allocate(XMLEvent event)
          -    {
          +    public XMLEventParser allocate(XMLEvent event) {
                   return this.getParser(event, null);
               }
           
          -    public XMLEventParser getParser(XMLEvent event)
          -    {
          +    public XMLEventParser getParser(XMLEvent event) {
                   return this.getParser(event, null);
               }
           
          -    protected XMLEventParser getParser(XMLEvent event, XMLEventParser defaultParser)
          -    {
          -        if (event == null)
          -        {
          +    protected XMLEventParser getParser(XMLEvent event, XMLEventParser defaultParser) {
          +        if (event == null) {
                       String message = Logging.getMessage("nullValue.EventIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
                   QName elementName = event.asStartElement().getName();
          -        if (elementName == null)
          +        if (elementName == null) {
                       return null;
          +        }
           
                   XMLEventParser parser = this.getParser(elementName);
           
                   return parser != null ? parser : defaultParser;
               }
           
          -    public StringXMLEventParser getStringParser()
          -    {
          -        if (this.stringParser == null)
          +    public StringXMLEventParser getStringParser() {
          +        if (this.stringParser == null) {
                       this.stringParser = (StringXMLEventParser) this.getParser(STRING);
          +        }
           
                   return this.stringParser;
               }
           
          -    public DoubleXMLEventParser getDoubleParser()
          -    {
          -        if (this.doubleParser == null)
          +    public DoubleXMLEventParser getDoubleParser() {
          +        if (this.doubleParser == null) {
                       this.doubleParser = (DoubleXMLEventParser) this.getParser(DOUBLE);
          +        }
           
                   return this.doubleParser;
               }
           
          -    public IntegerXMLEventParser getIntegerParser()
          -    {
          -        if (this.integerParser == null)
          +    public IntegerXMLEventParser getIntegerParser() {
          +        if (this.integerParser == null) {
                       this.integerParser = (IntegerXMLEventParser) this.getParser(INTEGER);
          +        }
           
                   return this.integerParser;
               }
           
          -    public BooleanXMLEventParser getBooleanParser()
          -    {
          -        if (this.booleanParser == null)
          +    public BooleanXMLEventParser getBooleanParser() {
          +        if (this.booleanParser == null) {
                       this.booleanParser = (BooleanXMLEventParser) this.getParser(BOOLEAN);
          +        }
           
                   return this.booleanParser;
               }
           
          -    public BooleanIntegerXMLEventParser getBooleanIntegerParser()
          -    {
          -        if (this.booleanIntegerParser == null)
          +    public BooleanIntegerXMLEventParser getBooleanIntegerParser() {
          +        if (this.booleanIntegerParser == null) {
                       this.booleanIntegerParser = (BooleanIntegerXMLEventParser) this.getParser(BOOLEAN_INTEGER);
          +        }
           
                   return this.booleanIntegerParser;
               }
          @@ -354,15 +332,12 @@ public BooleanIntegerXMLEventParser getBooleanIntegerParser()
                *
                * @return a parser to handle unrecognized elements.
                */
          -    public XMLEventParser getUnrecognizedElementParser()
          -    {
          +    public XMLEventParser getUnrecognizedElementParser() {
                   return this.getParser(UNRECOGNIZED);
               }
           
          -    public String getCharacters(XMLEvent event)
          -    {
          -        if (event == null)
          -        {
          +    public String getCharacters(XMLEvent event) {
          +        if (event == null) {
                       String message = Logging.getMessage("nullValue.EventIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -372,40 +347,39 @@ public String getCharacters(XMLEvent event)
               }
           
               @SuppressWarnings({"SimplifiableIfStatement"})
          -    public boolean isSameName(QName qa, QName qb)
          -    {
          -        if (qa.equals(qb))
          +    public boolean isSameName(QName qa, QName qb) {
          +        if (qa.equals(qb)) {
                       return true;
          +        }
           
          -        if (!qa.getLocalPart().equals(qb.getLocalPart()))
          +        if (!qa.getLocalPart().equals(qb.getLocalPart())) {
                       return false;
          +        }
           
          -        if (qa.getNamespaceURI().equals(XMLConstants.NULL_NS_URI))
          +        if (qa.getNamespaceURI().equals(XMLConstants.NULL_NS_URI)) {
                       return qb.getNamespaceURI().equals(this.getDefaultNamespaceURI());
          +        }
           
          -        if (qb.getNamespaceURI().equals(XMLConstants.NULL_NS_URI))
          +        if (qb.getNamespaceURI().equals(XMLConstants.NULL_NS_URI)) {
                       return qa.getNamespaceURI().equals(this.getDefaultNamespaceURI());
          +        }
           
                   return false;
               }
           
               @SuppressWarnings({"SimplifiableIfStatement"})
          -    public boolean isSameAttributeName(QName qa, QName qb)
          -    {
          +    public boolean isSameAttributeName(QName qa, QName qb) {
                   return qa != null && qb != null && qa.getLocalPart() != null && qa.getLocalPart().equals(qb.getLocalPart());
               }
           
          -    public boolean isStartElement(XMLEvent event, QName elementName)
          -    {
          -        if (event == null)
          -        {
          +    public boolean isStartElement(XMLEvent event, QName elementName) {
          +        if (event == null) {
                       String message = Logging.getMessage("nullValue.EventIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
          -        if (elementName == null)
          -        {
          +        if (elementName == null) {
                       String message = Logging.getMessage("nullValue.ElementNameIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -414,17 +388,14 @@ public boolean isStartElement(XMLEvent event, QName elementName)
                   return (event.isStartElement() && this.isSameName(event.asStartElement().getName(), elementName));
               }
           
          -    public boolean isStartElement(XMLEvent event, String elementName)
          -    {
          -        if (event == null)
          -        {
          +    public boolean isStartElement(XMLEvent event, String elementName) {
          +        if (event == null) {
                       String message = Logging.getMessage("nullValue.EventIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
          -        if (elementName == null)
          -        {
          +        if (elementName == null) {
                       String message = Logging.getMessage("nullValue.ElementNameIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -433,10 +404,8 @@ public boolean isStartElement(XMLEvent event, String elementName)
                   return (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals(elementName));
               }
           
          -    public boolean isEndElement(XMLEvent event, XMLEvent startElement)
          -    {
          -        if (event == null || startElement == null)
          -        {
          +    public boolean isEndElement(XMLEvent event, XMLEvent startElement) {
          +        if (event == null || startElement == null) {
                       String message = Logging.getMessage("nullValue.EventIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -445,30 +414,25 @@ public boolean isEndElement(XMLEvent event, XMLEvent startElement)
                   return isEndElementEvent(event, startElement);
               }
           
          -    public static boolean isEndElementEvent(XMLEvent event, XMLEvent startElement)
          -    {
          -        if (event == null || startElement == null)
          -        {
          +    public static boolean isEndElementEvent(XMLEvent event, XMLEvent startElement) {
          +        if (event == null || startElement == null) {
                       String message = Logging.getMessage("nullValue.EventIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
                   return (event.isEndElement()
          -            && event.asEndElement().getName().equals(startElement.asStartElement().getName()));
          +                && event.asEndElement().getName().equals(startElement.asStartElement().getName()));
               }
           
          -    public void registerParser(QName elementName, XMLEventParser parser)
          -    {
          -        if (parser == null)
          -        {
          +    public void registerParser(QName elementName, XMLEventParser parser) {
          +        if (parser == null) {
                       String message = Logging.getMessage("nullValue.ParserIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
          -        if (elementName == null)
          -        {
          +        if (elementName == null) {
                       String message = Logging.getMessage("nullValue.ElementNameIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -477,94 +441,84 @@ public void registerParser(QName elementName, XMLEventParser parser)
                   this.parsers.put(elementName, parser);
               }
           
          -    public XMLEventParser getParser(QName name)
          -    {
          -        if (name == null)
          -        {
          +    public XMLEventParser getParser(QName name) {
          +        if (name == null) {
                       String message = Logging.getMessage("nullValue.ElementNameIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
                   XMLEventParser factoryParser = this.parsers.get(name);
          -        if (factoryParser == null)
          -        {
          +        if (factoryParser == null) {
                       // Try alternate forms that assume a default namespace in either the input name or the table key.
          -            if (isNullNamespace(name.getNamespaceURI()))
          -            {
          +            if (isNullNamespace(name.getNamespaceURI())) {
                           // input name has no namespace but table key has the default namespace
                           QName altName = new QName(this.getDefaultNamespaceURI(), name.getLocalPart());
                           factoryParser = this.parsers.get(altName);
          -            }
          -            else if (this.isDefaultNamespace(name.getNamespaceURI()))
          -            {
          +            } else if (this.isDefaultNamespace(name.getNamespaceURI())) {
                           // input name has the default namespace but table name has no namespace
                           QName altName = new QName(name.getLocalPart());
                           factoryParser = this.parsers.get(altName);
                       }
                   }
           
          -        try
          -        {
          -            if (factoryParser == null)
          +        try {
          +            if (factoryParser == null) {
                           return null;
          +            }
           
                       return factoryParser.newInstance();
          -        }
          -        catch (Exception e)
          -        {
          +        } catch (Exception e) {
                       String message = Logging.getMessage("XML.ParserCreationException", name);
                       Logging.logger().log(java.util.logging.Level.WARNING, message, e);
                       return null;
                   }
               }
           
          -    protected static boolean isNullNamespace(String namespaceURI)
          -    {
          +    protected static boolean isNullNamespace(String namespaceURI) {
                   return namespaceURI == null || XMLConstants.NULL_NS_URI.equals(namespaceURI);
               }
           
          -    public boolean isDefaultNamespace(String namespaceURI)
          -    {
          +    public boolean isDefaultNamespace(String namespaceURI) {
                   return this.getDefaultNamespaceURI() != null && this.getDefaultNamespaceURI().equals(namespaceURI);
               }
           
               @Deprecated
          -    public void resolveInternalReferences(String referenceName, String fieldName, AbstractXMLEventParser parser)
          -    {
          -        if (parser == null || !parser.hasFields())
          +    public void resolveInternalReferences(String referenceName, String fieldName, AbstractXMLEventParser parser) {
          +        if (parser == null || !parser.hasFields()) {
                       return;
          +        }
           
                   Map newFields = null;
           
          -        for (Map.Entry p : parser.getFields().getEntries())
          -        {
          +        for (Map.Entry p : parser.getFields().getEntries()) {
                       String key = p.getKey();
          -            if (key == null || key.equals("id"))
          +            if (key == null || key.equals("id")) {
                           continue;
          +            }
           
                       Object v = p.getValue();
          -            if (v == null)
          +            if (v == null) {
                           continue;
          +            }
           
          -            if (v instanceof String)
          -            {
          +            if (v instanceof String) {
                           String value = (String) v;
           
          -                if (value.startsWith("#") && key.endsWith(referenceName))
          -                {
          +                if (value.startsWith("#") && key.endsWith(referenceName)) {
                               Object o = this.getIdTable().get(value.substring(1, value.length()));
          -                    if (/*o instanceof KMLStyle &&*/ !parser.hasField(fieldName))
          -                    {
          -                        if (newFields == null)
          +                    if (/*o instanceof KMLStyle &&*/!parser.hasField(fieldName)) {
          +                        if (newFields == null) {
                                       newFields = new HashMap();
          +                        }
                                   newFields.put(fieldName, o);
                               }
                           }
                       }
                   }
           
          -        if (newFields != null)
          +        if (newFields != null) {
                       parser.setFields(newFields);
          +        }
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/BooleanIntegerXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/BooleanIntegerXMLEventParser.java
          index edeae97e6b..09a3c0f4ec 100644
          --- a/src/gov/nasa/worldwind/util/xml/BooleanIntegerXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/BooleanIntegerXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.util.WWUtil;
          @@ -15,27 +14,26 @@
            * @author tag
            * @version $Id: BooleanIntegerXMLEventParser.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class BooleanIntegerXMLEventParser extends AbstractXMLEventParser
          -{
          -    public BooleanIntegerXMLEventParser()
          -    {
          +public class BooleanIntegerXMLEventParser extends AbstractXMLEventParser {
          +
          +    public BooleanIntegerXMLEventParser() {
               }
           
          -    public BooleanIntegerXMLEventParser(String namespaceUri)
          -    {
          +    public BooleanIntegerXMLEventParser(String namespaceUri) {
                   super(namespaceUri);
               }
           
          -    public Object parse(XMLEventParserContext ctx, XMLEvent booleanEvent, Object... args) throws XMLStreamException
          -    {
          +    public Object parse(XMLEventParserContext ctx, XMLEvent booleanEvent, Object... args) throws XMLStreamException {
                   String s = this.parseCharacterContent(ctx, booleanEvent);
          -        if (s == null)
          +        if (s == null) {
                       return false;
          +        }
           
                   s = s.trim();
           
          -        if (s.length() > 1)
          +        if (s.length() > 1) {
                       return s.equalsIgnoreCase("true");
          +        }
           
                   return WWUtil.convertNumericStringToBoolean(s);
               }
          diff --git a/src/gov/nasa/worldwind/util/xml/BooleanXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/BooleanXMLEventParser.java
          index a15893622d..81a29655c3 100644
          --- a/src/gov/nasa/worldwind/util/xml/BooleanXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/BooleanXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.util.WWUtil;
          @@ -15,27 +14,26 @@
            * @author tag
            * @version $Id: BooleanXMLEventParser.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class BooleanXMLEventParser extends AbstractXMLEventParser
          -{
          -    public BooleanXMLEventParser()
          -    {
          +public class BooleanXMLEventParser extends AbstractXMLEventParser {
          +
          +    public BooleanXMLEventParser() {
               }
           
          -    public BooleanXMLEventParser(String namespaceUri)
          -    {
          +    public BooleanXMLEventParser(String namespaceUri) {
                   super(namespaceUri);
               }
           
          -    public Object parse(XMLEventParserContext ctx, XMLEvent booleanEvent, Object... args) throws XMLStreamException
          -    {
          +    public Object parse(XMLEventParserContext ctx, XMLEvent booleanEvent, Object... args) throws XMLStreamException {
                   String s = this.parseCharacterContent(ctx, booleanEvent);
          -        if (s == null)
          +        if (s == null) {
                       return false;
          +        }
           
                   s = s.trim();
           
          -        if (s.length() > 1)
          +        if (s.length() > 1) {
                       return s.equalsIgnoreCase("true");
          +        }
           
                   return WWUtil.convertNumericStringToBoolean(s);
               }
          diff --git a/src/gov/nasa/worldwind/util/xml/DoubleXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/DoubleXMLEventParser.java
          index d789c65af7..31a0f1466e 100644
          --- a/src/gov/nasa/worldwind/util/xml/DoubleXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/DoubleXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.util.WWUtil;
          @@ -17,25 +16,21 @@
            * @author tag
            * @version $Id: DoubleXMLEventParser.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class DoubleXMLEventParser extends AbstractXMLEventParser
          -{
          -    public DoubleXMLEventParser()
          -    {
          +public class DoubleXMLEventParser extends AbstractXMLEventParser {
          +
          +    public DoubleXMLEventParser() {
               }
           
          -    public DoubleXMLEventParser(String namespaceUri)
          -    {
          +    public DoubleXMLEventParser(String namespaceUri) {
                   super(namespaceUri);
               }
           
          -    public Object parse(XMLEventParserContext ctx, XMLEvent doubleEvent, Object... args) throws XMLStreamException
          -    {
          +    public Object parse(XMLEventParserContext ctx, XMLEvent doubleEvent, Object... args) throws XMLStreamException {
                   String s = this.parseCharacterContent(ctx, doubleEvent);
                   return s != null ? WWUtil.convertStringToDouble(s) : null;
               }
           
          -    public Double parseDouble(XMLEventParserContext ctx, XMLEvent doubleEvent, Object... args) throws XMLStreamException
          -    {
          +    public Double parseDouble(XMLEventParserContext ctx, XMLEvent doubleEvent, Object... args) throws XMLStreamException {
                   return (Double) this.parse(ctx, doubleEvent, args);
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/IntegerXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/IntegerXMLEventParser.java
          index 7a7966c72f..0b792e33ac 100644
          --- a/src/gov/nasa/worldwind/util/xml/IntegerXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/IntegerXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.util.WWUtil;
          @@ -15,19 +14,16 @@
            * @author tag
            * @version $Id: IntegerXMLEventParser.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class IntegerXMLEventParser extends AbstractXMLEventParser
          -{
          -    public IntegerXMLEventParser()
          -    {
          +public class IntegerXMLEventParser extends AbstractXMLEventParser {
          +
          +    public IntegerXMLEventParser() {
               }
           
          -    public IntegerXMLEventParser(String namespaceUri)
          -    {
          +    public IntegerXMLEventParser(String namespaceUri) {
                   super(namespaceUri);
               }
           
          -    public Object parse(XMLEventParserContext ctx, XMLEvent integerEvent, Object... args) throws XMLStreamException
          -    {
          +    public Object parse(XMLEventParserContext ctx, XMLEvent integerEvent, Object... args) throws XMLStreamException {
                   String s = this.parseCharacterContent(ctx, integerEvent);
                   return s != null ? WWUtil.convertStringToInteger(s) : null;
               }
          diff --git a/src/gov/nasa/worldwind/util/xml/StringListXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/StringListXMLEventParser.java
          index 05fb941bc8..52f06a56cf 100644
          --- a/src/gov/nasa/worldwind/util/xml/StringListXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/StringListXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.util.WWUtil;
          @@ -17,17 +16,15 @@
            * @author tag
            * @version $Id: StringListXMLEventParser.java 2061 2014-06-19 19:59:40Z tgaskins $
            */
          -public class StringListXMLEventParser extends AbstractXMLEventParser implements Iterable
          -{
          +public class StringListXMLEventParser extends AbstractXMLEventParser implements Iterable {
          +
               protected QName elementName;
               protected List strings = new ArrayList();
           
          -    public StringListXMLEventParser()
          -    {
          +    public StringListXMLEventParser() {
               }
           
          -    public StringListXMLEventParser(String namespaceUri)
          -    {
          +    public StringListXMLEventParser(String namespaceUri) {
                   super(namespaceUri);
               }
           
          @@ -35,27 +32,25 @@ public StringListXMLEventParser(String namespaceUri)
                * Create a parser. All sub-elements of a specified name are parsed as strings and retained.
                *
                * @param namespaceURI the namespace URI to attach to this parser. May be null.
          -     * @param elementName  the name of the sub-elements that contain the strings.
          +     * @param elementName the name of the sub-elements that contain the strings.
                */
          -    public StringListXMLEventParser(String namespaceURI, QName elementName)
          -    {
          +    public StringListXMLEventParser(String namespaceURI, QName elementName) {
                   super(namespaceURI);
           
                   this.elementName = elementName;
               }
           
               @Override
          -    public XMLEventParser newInstance() throws Exception
          -    {
          +    public XMLEventParser newInstance() throws Exception {
                   StringListXMLEventParser copy = (StringListXMLEventParser) super.newInstance();
          -        if (copy != null)
          +        if (copy != null) {
                       copy.elementName = this.elementName;
          +        }
           
                   return copy;
               }
           
          -    public Object parse(XMLEventParserContext ctx, XMLEvent listEvent, Object... args) throws XMLStreamException
          -    {
          +    public Object parse(XMLEventParserContext ctx, XMLEvent listEvent, Object... args) throws XMLStreamException {
                   this.strings.clear();
           
                   return super.parse(ctx, listEvent, args);
          @@ -63,28 +58,24 @@ public Object parse(XMLEventParserContext ctx, XMLEvent listEvent, Object... arg
           
               @Override
               protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args)
          -        throws XMLStreamException
          -    {
          -        if (ctx.isStartElement(event, this.elementName))
          -        {
          +            throws XMLStreamException {
          +        if (ctx.isStartElement(event, this.elementName)) {
                       String s = ctx.getStringParser().parseString(ctx, event);
          -            if (!WWUtil.isEmpty(s))
          +            if (!WWUtil.isEmpty(s)) {
                           this.addString(s);
          +            }
                   }
               }
           
          -    public Iterator iterator()
          -    {
          +    public Iterator iterator() {
                   return this.strings.iterator();
               }
           
          -    public List getStrings()
          -    {
          +    public List getStrings() {
                   return this.strings;
               }
           
          -    protected void addString(String string)
          -    {
          +    protected void addString(String string) {
                   this.strings.add(string);
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/StringSetXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/StringSetXMLEventParser.java
          index 398b7e5261..420bb3f038 100644
          --- a/src/gov/nasa/worldwind/util/xml/StringSetXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/StringSetXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.util.WWUtil;
          @@ -19,17 +18,15 @@
            * @author tag
            * @version $Id: StringSetXMLEventParser.java 1981 2014-05-08 03:59:04Z tgaskins $
            */
          -public class StringSetXMLEventParser extends AbstractXMLEventParser implements Iterable
          -{
          +public class StringSetXMLEventParser extends AbstractXMLEventParser implements Iterable {
          +
               protected QName elementName;
               protected Set strings = new HashSet();
           
          -    public StringSetXMLEventParser()
          -    {
          +    public StringSetXMLEventParser() {
               }
           
          -    public StringSetXMLEventParser(String namespaceUri)
          -    {
          +    public StringSetXMLEventParser(String namespaceUri) {
                   super(namespaceUri);
               }
           
          @@ -37,27 +34,25 @@ public StringSetXMLEventParser(String namespaceUri)
                * Create a parser. All sub-elements of a specified name are parsed as strings and retained.
                *
                * @param namespaceURI the namespace URI to attach to this parser. May be null.
          -     * @param elementName  the name of the sub-elements that contain the strings.
          +     * @param elementName the name of the sub-elements that contain the strings.
                */
          -    public StringSetXMLEventParser(String namespaceURI, QName elementName)
          -    {
          +    public StringSetXMLEventParser(String namespaceURI, QName elementName) {
                   super(namespaceURI);
           
                   this.elementName = elementName;
               }
           
               @Override
          -    public XMLEventParser newInstance() throws Exception
          -    {
          +    public XMLEventParser newInstance() throws Exception {
                   StringSetXMLEventParser copy = (StringSetXMLEventParser) super.newInstance();
          -        if (copy != null)
          +        if (copy != null) {
                       copy.elementName = this.elementName;
          +        }
           
                   return copy;
               }
           
          -    public Object parse(XMLEventParserContext ctx, XMLEvent listEvent, Object... args) throws XMLStreamException
          -    {
          +    public Object parse(XMLEventParserContext ctx, XMLEvent listEvent, Object... args) throws XMLStreamException {
                   this.strings.clear();
           
                   return super.parse(ctx, listEvent, args);
          @@ -65,28 +60,24 @@ public Object parse(XMLEventParserContext ctx, XMLEvent listEvent, Object... arg
           
               @Override
               protected void doParseEventContent(XMLEventParserContext ctx, XMLEvent event, Object... args)
          -        throws XMLStreamException
          -    {
          -        if (ctx.isStartElement(event, this.elementName))
          -        {
          +            throws XMLStreamException {
          +        if (ctx.isStartElement(event, this.elementName)) {
                       String s = ctx.getStringParser().parseString(ctx, event);
          -            if (!WWUtil.isEmpty(s))
          +            if (!WWUtil.isEmpty(s)) {
                           this.addString(s);
          +            }
                   }
               }
           
          -    public Iterator iterator()
          -    {
          +    public Iterator iterator() {
                   return this.strings.iterator();
               }
           
          -    public Set getStrings()
          -    {
          +    public Set getStrings() {
                   return this.strings;
               }
           
          -    protected void addString(String string)
          -    {
          +    protected void addString(String string) {
                   this.strings.add(string);
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/StringXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/StringXMLEventParser.java
          index c979c0d389..c857f3d6ee 100644
          --- a/src/gov/nasa/worldwind/util/xml/StringXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/StringXMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import javax.xml.stream.XMLStreamException;
          @@ -15,25 +14,21 @@
            * @author tag
            * @version $Id: StringXMLEventParser.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class StringXMLEventParser extends AbstractXMLEventParser
          -{
          -    public StringXMLEventParser()
          -    {
          +public class StringXMLEventParser extends AbstractXMLEventParser {
          +
          +    public StringXMLEventParser() {
               }
           
          -    public StringXMLEventParser(String namespaceUri)
          -    {
          +    public StringXMLEventParser(String namespaceUri) {
                   super(namespaceUri);
               }
           
          -    public Object parse(XMLEventParserContext ctx, XMLEvent stringEvent, Object... args) throws XMLStreamException
          -    {
          +    public Object parse(XMLEventParserContext ctx, XMLEvent stringEvent, Object... args) throws XMLStreamException {
                   String s = this.parseCharacterContent(ctx, stringEvent, args);
                   return s != null ? s.trim() : null;
               }
           
          -    public String parseString(XMLEventParserContext ctx, XMLEvent stringEvent, Object... args) throws XMLStreamException
          -    {
          +    public String parseString(XMLEventParserContext ctx, XMLEvent stringEvent, Object... args) throws XMLStreamException {
                   return (String) this.parse(ctx, stringEvent, args);
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/UnrecognizedXMLEventParser.java b/src/gov/nasa/worldwind/util/xml/UnrecognizedXMLEventParser.java
          index 93b642dade..950ae6ec18 100644
          --- a/src/gov/nasa/worldwind/util/xml/UnrecognizedXMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/UnrecognizedXMLEventParser.java
          @@ -3,25 +3,23 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           /**
            * Holds the content of unrecognized elements. There are no field-specific accessors because the field names are
          - * unknown, but all fields can be accessed via the inherited {@link gov.nasa.worldwind.util.xml.AbstractXMLEventParser#getField(javax.xml.namespace.QName)}
          - * and {@link gov.nasa.worldwind.util.xml.AbstractXMLEventParser#getFields()}.
          + * unknown, but all fields can be accessed via the inherited
          + * {@link gov.nasa.worldwind.util.xml.AbstractXMLEventParser#getField(javax.xml.namespace.QName)} and
          + * {@link gov.nasa.worldwind.util.xml.AbstractXMLEventParser#getFields()}.
            *
            * @author tag
            * @version $Id: UnrecognizedXMLEventParser.java 1981 2014-05-08 03:59:04Z tgaskins $
            */
          -public class UnrecognizedXMLEventParser extends AbstractXMLEventParser
          -{
          -    public UnrecognizedXMLEventParser()
          -    {
          +public class UnrecognizedXMLEventParser extends AbstractXMLEventParser {
          +
          +    public UnrecognizedXMLEventParser() {
               }
           
          -    public UnrecognizedXMLEventParser(String namespaceURI)
          -    {
          +    public UnrecognizedXMLEventParser(String namespaceURI) {
                   super(namespaceURI);
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/XMLEventParser.java b/src/gov/nasa/worldwind/util/xml/XMLEventParser.java
          index 06db744529..9d45a59f08 100644
          --- a/src/gov/nasa/worldwind/util/xml/XMLEventParser.java
          +++ b/src/gov/nasa/worldwind/util/xml/XMLEventParser.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import javax.xml.stream.XMLStreamException;
          @@ -15,14 +14,14 @@
            * @author tag
            * @version $Id: XMLEventParser.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public interface XMLEventParser
          -{
          +public interface XMLEventParser {
          +
               /**
                * Parse the event and initialize the parser's values to those found in the event.
                *
                * @param context a current parser context.
          -     * @param event   the event to parse.
          -     * @param args    an optional list of arguments that may by used by subclasses.
          +     * @param event the event to parse.
          +     * @param args an optional list of arguments that may by used by subclasses.
                *
                * @return if parsing is successful, returns this, otherwise returns null.
                *
          @@ -37,7 +36,7 @@ public interface XMLEventParser
                * values.
                *
                * @return a new parser instance. The namespace URI is the same as the creating parser, but all other fields are
          -     *         empty.
          +     * empty.
                *
                * @throws Exception if an error or exception occurs while attempting to create the parser.
                */
          diff --git a/src/gov/nasa/worldwind/util/xml/XMLEventParserContext.java b/src/gov/nasa/worldwind/util/xml/XMLEventParserContext.java
          index e8b8c0bdc0..f8e0f954f6 100644
          --- a/src/gov/nasa/worldwind/util/xml/XMLEventParserContext.java
          +++ b/src/gov/nasa/worldwind/util/xml/XMLEventParserContext.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.avlist.AVList;
          @@ -19,8 +18,8 @@
            * @author tag
            * @version $Id: XMLEventParserContext.java 1981 2014-05-08 03:59:04Z tgaskins $
            */
          -public interface XMLEventParserContext extends AVList
          -{
          +public interface XMLEventParserContext extends AVList {
          +
               /**
                * Identifies the name of the parser handling unrecognized elements. Can be used to explicitly specify the context's
                * parser-table entry for unrecognized elements.
          @@ -55,7 +54,7 @@ public interface XMLEventParserContext extends AVList
               /**
                * Determines whether an event is a start event for a specific event type.
                *
          -     * @param event       an event identifying the event type of interest.
          +     * @param event an event identifying the event type of interest.
                * @param elementName the event name.
                *
                * @return true if the event is a start event for the named event type.
          @@ -65,7 +64,7 @@ public interface XMLEventParserContext extends AVList
               /**
                * Determines whether an event is a start event for a specific event type indicated by its local name.
                *
          -     * @param event       an event identifying the event type of interest.
          +     * @param event an event identifying the event type of interest.
                * @param elementName the local part of the event name to match.
                *
                * @return true if the event is a start event for the named event type.
          @@ -78,7 +77,7 @@ public interface XMLEventParserContext extends AVList
                * Note: Only the event's element name and type are compared. The method returns true if the start and end events
                * are the corresponding event types for an element of the same name.
                *
          -     * @param event        the event of interest.
          +     * @param event the event of interest.
                * @param startElement the start event associated with the potential end event.
                *
                * @return true if the event is the corresponding end event to the specified start event, otherwise false.
          @@ -123,7 +122,7 @@ public interface XMLEventParserContext extends AVList
               BooleanIntegerXMLEventParser getBooleanIntegerParser();
           
               /**
          -     * Returns the default parser for a simple  integer.
          +     * Returns the default parser for a simple integer.
                *
                * @return an integer parser.
                */
          @@ -134,7 +133,7 @@ public interface XMLEventParserContext extends AVList
                * #getParser(javax.xml.stream.events.XMLEvent)} is called for the same element name.
                *
                * @param elementName the element name for which to return a parser.
          -     * @param parser      the parser to register.
          +     * @param parser the parser to register.
                */
               void registerParser(QName elementName, XMLEventParser parser);
           
          @@ -184,14 +183,14 @@ public interface XMLEventParserContext extends AVList
                * @param qb second element name
                *
                * @return true if both names have the same namespace (or no namespace) and local name, or if either name has no
          -     *         namespace but the namespace of the other is the context's default namespace.
          +     * namespace but the namespace of the other is the context's default namespace.
                */
               boolean isSameName(QName qa, QName qb);
           
               /**
                * Create a parser for a specified event's element name, if a parser for that name is registered with the context.
                *
          -     * @param event         the event whose element name identifies the parser to create.
          +     * @param event the event whose element name identifies the parser to create.
                * @param defaultParser a parser to return if no parser is registered for the specified name. May be null.
                *
                * @return a new parser, or the specified default parser if no parser has been registered for the element name.
          @@ -228,7 +227,7 @@ public interface XMLEventParserContext extends AVList
                * Adds a mapping of an id attribute to its associated KML object.
                *
                * @param id the object id. If null, this method returns without creating a mapping.
          -     * @param o  the object to associate with the id.
          +     * @param o the object to associate with the id.
                */
               void addId(String id, Object o);
           
          @@ -239,12 +238,12 @@ public interface XMLEventParserContext extends AVList
                * element they refer to the referring object's field table.
                *
                * @param referenceName the element name of the elements whose references this method resolves. An example is
          -     *                      styleUrl. Resolution is performed for only elements of this name.
          -     * @param fieldName     the key used to identify the resolved object in a parser's field table. After this method
          -     *                      resolves references, the referenced object can be obtained by calling the parsers {@link
          -     *                      gov.nasa.worldwind.util.xml.AbstractXMLEventParser#getField(javax.xml.namespace.QName)}
          -     *                      method with the fieldName specified here as the name argument.
          -     * @param parser        the parser whose references to resolve.
          +     * styleUrl. Resolution is performed for only elements of this name.
          +     * @param fieldName the key used to identify the resolved object in a parser's field table. After this method
          +     * resolves references, the referenced object can be obtained by calling the parsers {@link
          +     *                      gov.nasa.worldwind.util.xml.AbstractXMLEventParser#getField(javax.xml.namespace.QName)} method with the
          +     * fieldName specified here as the name argument.
          +     * @param parser the parser whose references to resolve.
                *
                * @deprecated Reference resolution is handled by parsers specific to a certain document type. For example, {@link
                *             gov.nasa.worldwind.ogc.kml.KMLRoot} handles resolution of references in KML files.
          @@ -283,7 +282,7 @@ public interface XMLEventParserContext extends AVList
               /**
                * Add string list parsers for a list of element types and qualified for a specified namespace.
                *
          -     * @param namespace    the namespace URI.
          +     * @param namespace the namespace URI.
                * @param stringFields the string list parser names.
                */
               void addStringParsers(String namespace, String[] stringFields);
          @@ -291,7 +290,7 @@ public interface XMLEventParserContext extends AVList
               /**
                * Add double parsers for a list of element types and qualified for a specified namespace.
                *
          -     * @param namespace    the namespace URI.
          +     * @param namespace the namespace URI.
                * @param doubleFields the string parsers.
                */
               void addDoubleParsers(String namespace, String[] doubleFields);
          @@ -299,7 +298,7 @@ public interface XMLEventParserContext extends AVList
               /**
                * Add integer parsers for a list of element types and qualified for a specified namespace.
                *
          -     * @param namespace     the namespace URI.
          +     * @param namespace the namespace URI.
                * @param integerFields the string parsers.
                */
               void addIntegerParsers(String namespace, String[] integerFields);
          @@ -307,7 +306,7 @@ public interface XMLEventParserContext extends AVList
               /**
                * Add boolean parsers for a list of element types and qualified for a specified namespace.
                *
          -     * @param namespace     the namespace URI.
          +     * @param namespace the namespace URI.
                * @param booleanFields the string parsers.
                */
               void addBooleanParsers(String namespace, String[] booleanFields);
          @@ -315,7 +314,7 @@ public interface XMLEventParserContext extends AVList
               /**
                * Add boolean integer parsers for a list of element types and qualified for a specified namespace.
                *
          -     * @param namespace            the namespace URI.
          +     * @param namespace the namespace URI.
                * @param booleanIntegerFields the string parser.
                */
               void addBooleanIntegerParsers(String namespace, String[] booleanIntegerFields);
          diff --git a/src/gov/nasa/worldwind/util/xml/XMLEventParserContextFactory.java b/src/gov/nasa/worldwind/util/xml/XMLEventParserContextFactory.java
          index 3601e21982..77eb43f43d 100644
          --- a/src/gov/nasa/worldwind/util/xml/XMLEventParserContextFactory.java
          +++ b/src/gov/nasa/worldwind/util/xml/XMLEventParserContextFactory.java
          @@ -3,12 +3,10 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           //import gov.nasa.worldwind.ogc.collada.*;
           //import gov.nasa.worldwind.ogc.kml.*;
          -
           import gov.nasa.worldwind.ogc.kml.*;
           import gov.nasa.worldwind.util.Logging;
           
          @@ -26,12 +24,16 @@
            * @author tag
            * @version $Id: XMLEventParserContextFactory.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class XMLEventParserContextFactory
          -{
          -    /** Holds the mime types and the associated prototype parser. */
          -    protected static class ParserTableEntry
          -    {
          -        /** The mime types for which the associated parser should be used. */
          +public class XMLEventParserContextFactory {
          +
          +    /**
          +     * Holds the mime types and the associated prototype parser.
          +     */
          +    protected static class ParserTableEntry {
          +
          +        /**
          +         * The mime types for which the associated parser should be used.
          +         */
                   protected List mimeTypes = new ArrayList();
                   /**
                    * A prototype parser able to construct a copy of itself. The copy typically shares the prototype's parser table
          @@ -42,30 +44,25 @@ protected static class ParserTableEntry
                   /**
                    * Construct an instance for a specified list of mime types and a specified prototype parser.
                    *
          -         * @param mimeTypes        the list of mime types for which to use the specified prototype parser context.
          +         * @param mimeTypes the list of mime types for which to use the specified prototype parser context.
                    * @param prototypeContext the prototype parser context to use for the specified mime types. This parser
          -         *                         context's class must provide a copy constructor, a constructor that takes an instance
          -         *                         of its class as its only argument.
          +         * context's class must provide a copy constructor, a constructor that takes an instance of its class as its
          +         * only argument.
                    *
                    * @throws IllegalArgumentException if the mime type list is null or empty or the prototype context is null or
          -         *                                  has no copy constructor.
          +         * has no copy constructor.
                    */
          -        public ParserTableEntry(String[] mimeTypes, XMLEventParserContext prototypeContext)
          -        {
          -            for (String mimeType : mimeTypes)
          -            {
          +        public ParserTableEntry(String[] mimeTypes, XMLEventParserContext prototypeContext) {
          +            for (String mimeType : mimeTypes) {
                           this.mimeTypes.add(mimeType);
                       }
           
                       this.prototypeParser = prototypeContext;
           
                       // Ensure the prototype has a copy constructor
          -            try
          -            {
          +            try {
                           prototypeContext.getClass().getConstructor(prototypeContext.getClass());
          -            }
          -            catch (NoSuchMethodException e)
          -            {
          +            } catch (NoSuchMethodException e) {
                           String message = Logging.getMessage("XML.NoCopyConstructor");
                           Logging.logger().severe(message);
                           throw new IllegalArgumentException(message);
          @@ -79,10 +76,9 @@ public ParserTableEntry(String[] mimeTypes, XMLEventParserContext prototypeConte
                */
               protected static List parsers = new CopyOnWriteArrayList();
           
          -    static
          -    {
          +    static {
                   // Register a KML parser context for the default KML namespace and one for the empty namespace.
          -        String[] mimeTypes = new String[] {KMLConstants.KML_MIME_TYPE, KMLConstants.KMZ_MIME_TYPE};
          +        String[] mimeTypes = new String[]{KMLConstants.KML_MIME_TYPE, KMLConstants.KMZ_MIME_TYPE};
                   parsers.add(new ParserTableEntry(mimeTypes, new KMLParserContext(KMLConstants.KML_NAMESPACE)));
                   parsers.add(new ParserTableEntry(mimeTypes, new KMLParserContext(XMLConstants.NULL_NS_URI)));
           //
          @@ -95,25 +91,21 @@ public ParserTableEntry(String[] mimeTypes, XMLEventParserContext prototypeConte
               /**
                * Appends a specified prototype parser context to the list of those already registered.
                *
          -     * @param mimeTypes        the list of mime types for which to use the specified prototype parser context.
          +     * @param mimeTypes the list of mime types for which to use the specified prototype parser context.
                * @param prototypeContext the prototype parser context to use for the specified mime types. This parser context's
          -     *                         class must provide a copy constructor, a constructor that takes an instance of its class
          -     *                         as its only argument.
          +     * class must provide a copy constructor, a constructor that takes an instance of its class as its only argument.
                *
                * @throws IllegalArgumentException if the mime type list is null or empty or the prototype context is null or has
          -     *                                  no copy constructor.
          +     * no copy constructor.
                */
          -    public static void addParserContext(String[] mimeTypes, XMLEventParserContext prototypeContext)
          -    {
          -        if (mimeTypes == null || mimeTypes.length == 0)
          -        {
          +    public static void addParserContext(String[] mimeTypes, XMLEventParserContext prototypeContext) {
          +        if (mimeTypes == null || mimeTypes.length == 0) {
                       String message = Logging.getMessage("nullValue.MimeTypeListIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
          -        if (prototypeContext == null)
          -        {
          +        if (prototypeContext == null) {
                       String message = Logging.getMessage("nullValue.ParserContextIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -126,25 +118,21 @@ public static void addParserContext(String[] mimeTypes, XMLEventParserContext pr
                * Prepends a specified prototype parser context to the list of those already registered. Because the new entry is
                * prepended to the list of registered parsers, it will be the first match for the specified mime types.
                *
          -     * @param mimeTypes        the list of mime types for which to use the specified prototype parser context.
          +     * @param mimeTypes the list of mime types for which to use the specified prototype parser context.
                * @param prototypeContext the prototype parser context to use for the specified mime types. This parser context's
          -     *                         class must provide a copy constructor, a constructor that takes an instance of its class
          -     *                         as its only argument.
          +     * class must provide a copy constructor, a constructor that takes an instance of its class as its only argument.
                *
                * @throws IllegalArgumentException if the mime type list is null or empty or the prototype context is null or has
          -     *                                  no copy constructor.
          +     * no copy constructor.
                */
          -    public static void prependParserContext(String[] mimeTypes, XMLEventParserContext prototypeContext)
          -    {
          -        if (mimeTypes == null || mimeTypes.length == 0)
          -        {
          +    public static void prependParserContext(String[] mimeTypes, XMLEventParserContext prototypeContext) {
          +        if (mimeTypes == null || mimeTypes.length == 0) {
                       String message = Logging.getMessage("nullValue.MimeTypeListIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
          -        if (prototypeContext == null)
          -        {
          +        if (prototypeContext == null) {
                       String message = Logging.getMessage("nullValue.ParserContextIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
          @@ -161,46 +149,39 @@ public static void prependParserContext(String[] mimeTypes, XMLEventParserContex
                * Note that the empty namespace, {@link XMLConstants#NULL_NS_URI} does not match any other namespace. In order for
                * a parser context with the empty namespace to be returned, one with the empty namespace must be registered.
                *
          -     * @param mimeType         the mime type for which to construct a parser.
          +     * @param mimeType the mime type for which to construct a parser.
                * @param defaultNamespace a namespace qualifying the parser context to return. May be null, in which case a parser
          -     *                         context for the specified mime type and an empty namespace, {@link
          +     * context for the specified mime type and an empty namespace, {@link
                *                         XMLConstants#NULL_NS_URI}, is searched for.
                *
                * @return a new parser context constructed from the prototype context registered for the specified mime type and
          -     *         having the specified default namespace.
          +     * having the specified default namespace.
                *
                * @throws IllegalArgumentException if the specified mime type is null.
                */
          -    public static XMLEventParserContext createParserContext(String mimeType, String defaultNamespace)
          -    {
          -        if (mimeType == null)
          -        {
          +    public static XMLEventParserContext createParserContext(String mimeType, String defaultNamespace) {
          +        if (mimeType == null) {
                       String message = Logging.getMessage("nullValue.MimeTypeIsNull");
                       Logging.logger().severe(message);
                       throw new IllegalArgumentException(message);
                   }
           
          -        for (ParserTableEntry entry : parsers)
          -        {
          -            for (String entryMimeType : entry.mimeTypes)
          -            {
          -                if (entryMimeType.equals(mimeType))
          -                {
          +        for (ParserTableEntry entry : parsers) {
          +            for (String entryMimeType : entry.mimeTypes) {
          +                if (entryMimeType.equals(mimeType)) {
                               String ns = entry.prototypeParser.getDefaultNamespaceURI();
                               ns = ns != null ? ns : XMLConstants.NULL_NS_URI;
                               defaultNamespace = defaultNamespace != null ? defaultNamespace : XMLConstants.NULL_NS_URI;
           
          -                    if (ns.equals(defaultNamespace))
          -                        try
          -                        {
          +                    if (ns.equals(defaultNamespace)) {
          +                        try {
                                       return createInstanceFromPrototype(entry.prototypeParser);
          -                        }
          -                        catch (Exception e)
          -                        {
          +                        } catch (Exception e) {
                                       String message = Logging.getMessage("XML.ExceptionCreatingParserContext", e.getMessage());
                                       Logging.logger().log(Level.WARNING, message);
                                       // continue on to subsequent entries
                                   }
          +                    }
                           }
                       }
                   }
          @@ -212,15 +193,14 @@ public static XMLEventParserContext createParserContext(String mimeType, String
                * Constructs a new parser context given a prototype parser context.
                *
                * @param prototype the prototype parser context. This parser context's class must provide a copy constructor, a
          -     *                  constructor that takes an instance of the class as its only argument.
          +     * constructor that takes an instance of the class as its only argument.
                *
                * @return the new parser context.
                *
                * @throws Exception if an exception occurs while attempting to construct the new context.
                */
               protected static XMLEventParserContext createInstanceFromPrototype(XMLEventParserContext prototype)
          -        throws Exception
          -    {
          +            throws Exception {
                   Constructor constructor;
                   constructor = prototype.getClass().getConstructor(prototype.getClass());
           
          diff --git a/src/gov/nasa/worldwind/util/xml/XMLParserNotification.java b/src/gov/nasa/worldwind/util/xml/XMLParserNotification.java
          index b1e2f512af..9ae3b19680 100644
          --- a/src/gov/nasa/worldwind/util/xml/XMLParserNotification.java
          +++ b/src/gov/nasa/worldwind/util/xml/XMLParserNotification.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           import gov.nasa.worldwind.util.Logging;
          @@ -13,45 +12,57 @@
           
           /**
            * This class identifies the type and data content of notifications from parsers and parser contexts. Notifications are
          - * sent to inform of important occurrences that occur during parsing, such as exceptions and unrecognized element
          - * types.
          + * sent to inform of important occurrences that occur during parsing, such as exceptions and unrecognized element types.
            *
            * @author tag
            * @version $Id: XMLParserNotification.java 1171 2013-02-11 21:45:02Z dcollins $
            * @see gov.nasa.worldwind.util.xml.XMLEventParserContext#setNotificationListener(XMLParserNotificationListener)
            * @see gov.nasa.worldwind.util.xml.XMLParserNotificationListener
            */
          -public class XMLParserNotification extends PropertyChangeEvent
          -{
          -    /** A notification type indicating that an exception occurred during parsing. */
          +public class XMLParserNotification extends PropertyChangeEvent {
          +
          +    /**
          +     * A notification type indicating that an exception occurred during parsing.
          +     */
               public static final String EXCEPTION = "gov.nasa.worldwind.util.xml.XMLParserNotification.Exception";
          -    /** A notification type indicating that a parser encounter an element it did not recognize. */
          +    /**
          +     * A notification type indicating that a parser encounter an element it did not recognize.
          +     */
               public static final String UNRECOGNIZED = "gov.nasa.worldwind.util.xml.XMLParserNotification.Unrecognized";
          -    /** Indicates the cause of the notification. */
          +    /**
          +     * Indicates the cause of the notification.
          +     */
               protected final String notificationType;
          -    /** The message sent from the object sending the notification. */
          +    /**
          +     * The message sent from the object sending the notification.
          +     */
               protected final String message;
          -    /** The XMLEvent associated with the notification, if any. */
          +    /**
          +     * The XMLEvent associated with the notification, if any.
          +     */
               protected final XMLEvent event;
          -    /** For exception notifications, the exception that occurred. */
          +    /**
          +     * For exception notifications, the exception that occurred.
          +     */
               protected Exception exception;
          -    /** The object initiating the notification. */
          +    /**
          +     * The object initiating the notification.
          +     */
               protected Object notificationSource;
           
               /**
                * Construct a notification object.
                *
          -     * @param source           the object initiating the notification.
          +     * @param source the object initiating the notification.
                * @param notificationType the notification type, such as {@link #EXCEPTION} or {@link #UNRECOGNIZED}.
          -     * @param event            if an event is associated with the notification, that event. May be null.
          -     * @param msg              a message from the notification source suitable for logging.
          -     * @param oldValue         any old value associated with the notification. Not typically used.
          -     * @param newValue         any new value associated with the notification. if this is an exception notification, the
          -     *                         exception that occurred is passed via this parameter. May be null.
          +     * @param event if an event is associated with the notification, that event. May be null.
          +     * @param msg a message from the notification source suitable for logging.
          +     * @param oldValue any old value associated with the notification. Not typically used.
          +     * @param newValue any new value associated with the notification. if this is an exception notification, the
          +     * exception that occurred is passed via this parameter. May be null.
                */
               public XMLParserNotification(Object source, String notificationType, XMLEvent event, String msg, Object oldValue,
          -        Object newValue)
          -    {
          +            Object newValue) {
                   super(source, notificationType, oldValue, newValue);
           
                   this.notificationSource = source;
          @@ -59,8 +70,9 @@ public XMLParserNotification(Object source, String notificationType, XMLEvent ev
                   this.event = event;
                   this.message = msg;
           
          -        if (newValue instanceof Exception)
          +        if (newValue instanceof Exception) {
                       this.exception = (Exception) newValue;
          +        }
               }
           
               /**
          @@ -68,8 +80,7 @@ public XMLParserNotification(Object source, String notificationType, XMLEvent ev
                *
                * @return the event associated with the exception.
                */
          -    public XMLEvent getEvent()
          -    {
          +    public XMLEvent getEvent() {
                   return this.event;
               }
           
          @@ -78,8 +89,7 @@ public XMLEvent getEvent()
                *
                * @return the message associated with the exception.
                */
          -    public String getMessage()
          -    {
          +    public String getMessage() {
                   return this.message;
               }
           
          @@ -91,8 +101,7 @@ public String getMessage()
                * @see #EXCEPTION
                * @see #UNRECOGNIZED
                */
          -    public String getNotificationType()
          -    {
          +    public String getNotificationType() {
                   return this.notificationType;
               }
           
          @@ -101,8 +110,7 @@ public String getNotificationType()
                *
                * @return the associated exception, or null if this is not an exception notification.
                */
          -    public Exception getException()
          -    {
          +    public Exception getException() {
                   return this.exception;
               }
           
          @@ -111,8 +119,7 @@ public Exception getException()
                *
                * @return the object initiating the exception.
                */
          -    public Object getSource()
          -    {
          +    public Object getSource() {
                   return this.notificationSource;
               }
           
          @@ -122,25 +129,20 @@ public Object getSource()
                *
                * @param notificationSource the source to assign the exception.
                */
          -    public void setSource(Object notificationSource)
          -    {
          +    public void setSource(Object notificationSource) {
                   this.notificationSource = notificationSource;
               }
           
               @Override
          -    public String toString()
          -    {
          +    public String toString() {
                   String msg;
           
          -        if (this.event != null)
          -        {
          +        if (this.event != null) {
                       msg = Logging.getMessage(this.message, this.event.toString(),
          -                this.event.getLocation().getLineNumber(),
          -                this.event.getLocation().getColumnNumber(),
          -                this.event.getLocation().getCharacterOffset());
          -        }
          -        else
          -        {
          +                    this.event.getLocation().getLineNumber(),
          +                    this.event.getLocation().getColumnNumber(),
          +                    this.event.getLocation().getCharacterOffset());
          +        } else {
                       msg = Logging.getMessage(this.message, "", "", "");
                   }
           
          diff --git a/src/gov/nasa/worldwind/util/xml/XMLParserNotificationListener.java b/src/gov/nasa/worldwind/util/xml/XMLParserNotificationListener.java
          index 2010c8523a..3ba5e4488a 100644
          --- a/src/gov/nasa/worldwind/util/xml/XMLParserNotificationListener.java
          +++ b/src/gov/nasa/worldwind/util/xml/XMLParserNotificationListener.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml;
           
           /**
          @@ -12,8 +11,8 @@
            * @author tag
            * @version $Id: XMLParserNotificationListener.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public interface XMLParserNotificationListener
          -{
          +public interface XMLParserNotificationListener {
          +
               /**
                * Receives notification events from the parser context.
                *
          diff --git a/src/gov/nasa/worldwind/util/xml/atom/AtomAbstractObject.java b/src/gov/nasa/worldwind/util/xml/atom/AtomAbstractObject.java
          index 9b17fab94b..cd6260a692 100644
          --- a/src/gov/nasa/worldwind/util/xml/atom/AtomAbstractObject.java
          +++ b/src/gov/nasa/worldwind/util/xml/atom/AtomAbstractObject.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml.atom;
           
           import gov.nasa.worldwind.util.xml.AbstractXMLEventParser;
          @@ -12,20 +11,17 @@
            * @author tag
            * @version $Id: AtomAbstractObject.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class AtomAbstractObject extends AbstractXMLEventParser
          -{
          -    public AtomAbstractObject(String namespaceURI)
          -    {
          +public class AtomAbstractObject extends AbstractXMLEventParser {
          +
          +    public AtomAbstractObject(String namespaceURI) {
                   super(namespaceURI);
               }
           
          -    public String getBase()
          -    {
          +    public String getBase() {
                   return (String) this.getField("base");
               }
           
          -    public String getLang()
          -    {
          +    public String getLang() {
                   return (String) this.getField("lang");
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/atom/AtomConstants.java b/src/gov/nasa/worldwind/util/xml/atom/AtomConstants.java
          index 0ca0e8e723..f2656546e9 100644
          --- a/src/gov/nasa/worldwind/util/xml/atom/AtomConstants.java
          +++ b/src/gov/nasa/worldwind/util/xml/atom/AtomConstants.java
          @@ -3,14 +3,13 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml.atom;
           
           /**
            * @author tag
            * @version $Id: AtomConstants.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public interface AtomConstants
          -{
          +public interface AtomConstants {
          +
               final public String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/atom/AtomLink.java b/src/gov/nasa/worldwind/util/xml/atom/AtomLink.java
          index 165a9d12e4..81644f9c5a 100644
          --- a/src/gov/nasa/worldwind/util/xml/atom/AtomLink.java
          +++ b/src/gov/nasa/worldwind/util/xml/atom/AtomLink.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml.atom;
           
           import gov.nasa.worldwind.util.WWUtil;
          @@ -18,50 +17,43 @@
            * @author tag
            * @version $Id: AtomLink.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class AtomLink extends AtomAbstractObject
          -{
          -    public AtomLink(String namespaceURI)
          -    {
          +public class AtomLink extends AtomAbstractObject {
          +
          +    public AtomLink(String namespaceURI) {
                   super(namespaceURI);
               }
           
               @Override
               protected void doAddEventAttribute(Attribute attr, XMLEventParserContext ctx, XMLEvent event, Object... args)
          -        throws XMLStreamException
          -    {
          -        if ("length".equals(attr.getName().getLocalPart()))
          +            throws XMLStreamException {
          +        if ("length".equals(attr.getName().getLocalPart())) {
                       this.setField(attr.getName(), WWUtil.makeInteger(attr.getValue()));
          -        else
          +        } else {
                       super.doAddEventAttribute(attr, ctx, event, args);
          +        }
               }
           
          -    public String getHref()
          -    {
          +    public String getHref() {
                   return (String) this.getField("href");
               }
           
          -    public String getRel()
          -    {
          +    public String getRel() {
                   return (String) this.getField("rel");
               }
           
          -    public String getType()
          -    {
          +    public String getType() {
                   return (String) this.getField("type");
               }
           
          -    public String getHreflang()
          -    {
          +    public String getHreflang() {
                   return (String) this.getField("hreflang");
               }
           
          -    public String getTitle()
          -    {
          +    public String getTitle() {
                   return (String) this.getField("title");
               }
           
          -    public Integer getLength()
          -    {
          +    public Integer getLength() {
                   return (Integer) this.getField("length");
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/atom/AtomParserContext.java b/src/gov/nasa/worldwind/util/xml/atom/AtomParserContext.java
          index fd39f8634b..0f2ebb0d42 100644
          --- a/src/gov/nasa/worldwind/util/xml/atom/AtomParserContext.java
          +++ b/src/gov/nasa/worldwind/util/xml/atom/AtomParserContext.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml.atom;
           
           import gov.nasa.worldwind.util.xml.*;
          @@ -16,19 +15,16 @@
            * @author tag
            * @version $Id: AtomParserContext.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class AtomParserContext extends BasicXMLEventParserContext
          -{
          -    protected static final String[] StringFields = new String[]
          -        {
          -            "base",
          -            "email",
          -            "lang",
          -            "name",
          -            "uri",
          -        };
          -
          -    public static Map getDefaultParsers()
          -    {
          +public class AtomParserContext extends BasicXMLEventParserContext {
          +
          +    protected static final String[] StringFields = new String[]{
          +        "base",
          +        "email",
          +        "lang",
          +        "name",
          +        "uri",};
          +
          +    public static Map getDefaultParsers() {
                   ConcurrentHashMap parsers = new ConcurrentHashMap();
           
                   String ans = AtomConstants.ATOM_NAMESPACE;
          @@ -36,8 +32,7 @@ public static Map getDefaultParsers()
                   parsers.put(new QName(ans, "link"), new AtomLink(ans));
           
                   StringXMLEventParser stringParser = new StringXMLEventParser();
          -        for (String s : StringFields)
          -        {
          +        for (String s : StringFields) {
                       parsers.put(new QName(ans, s), stringParser);
                   }
           
          diff --git a/src/gov/nasa/worldwind/util/xml/atom/AtomPerson.java b/src/gov/nasa/worldwind/util/xml/atom/AtomPerson.java
          index 5bfa17cbc1..485b71a7f5 100644
          --- a/src/gov/nasa/worldwind/util/xml/atom/AtomPerson.java
          +++ b/src/gov/nasa/worldwind/util/xml/atom/AtomPerson.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           package gov.nasa.worldwind.util.xml.atom;
           
           /**
          @@ -12,25 +11,21 @@
            * @author tag
            * @version $Id: AtomPerson.java 1171 2013-02-11 21:45:02Z dcollins $
            */
          -public class AtomPerson extends AtomAbstractObject
          -{
          -    public AtomPerson(String namespaceURI)
          -    {
          +public class AtomPerson extends AtomAbstractObject {
          +
          +    public AtomPerson(String namespaceURI) {
                   super(namespaceURI);
               }
           
          -    public String getName()
          -    {
          +    public String getName() {
                   return (String) this.getField("name");
               }
           
          -    public String getUri()
          -    {
          +    public String getUri() {
                   return (String) this.getField("uri");
               }
           
          -    public String getEmail()
          -    {
          +    public String getEmail() {
                   return (String) this.getField("email");
               }
           }
          diff --git a/src/gov/nasa/worldwind/util/xml/atom/package-info.java b/src/gov/nasa/worldwind/util/xml/atom/package-info.java
          index 19fb378cc3..ffd4b47148 100644
          --- a/src/gov/nasa/worldwind/util/xml/atom/package-info.java
          +++ b/src/gov/nasa/worldwind/util/xml/atom/package-info.java
          @@ -3,7 +3,6 @@
            * National Aeronautics and Space Administration.
            * All Rights Reserved.
            */
          -
           /**
            * 

          * Provides classes for parsing the Atom namespace.

          diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALAbstractObject.java b/src/gov/nasa/worldwind/util/xml/xal/XALAbstractObject.java index cdfcf512f1..693b50736d 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALAbstractObject.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALAbstractObject.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; import gov.nasa.worldwind.util.xml.AbstractXMLEventParser; @@ -12,20 +11,17 @@ * @author tag * @version $Id: XALAbstractObject.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALAbstractObject extends AbstractXMLEventParser -{ - public XALAbstractObject(String namespaceURI) - { +public class XALAbstractObject extends AbstractXMLEventParser { + + public XALAbstractObject(String namespaceURI) { super(namespaceURI); } - public String getType() - { + public String getType() { return (String) this.getField("Type"); } - public String getCode() - { + public String getCode() { return (String) this.getField("Code"); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALAddress.java b/src/gov/nasa/worldwind/util/xml/xal/XALAddress.java index 57c1ed1a18..1d687e1beb 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALAddress.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALAddress.java @@ -3,17 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** * @author tag * @version $Id: XALAddress.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALAddress extends XALAbstractObject -{ - public XALAddress(String namespaceURI) - { +public class XALAddress extends XALAbstractObject { + + public XALAddress(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALAddressDetails.java b/src/gov/nasa/worldwind/util/xml/xal/XALAddressDetails.java index 1386ed97d5..64f8390da5 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALAddressDetails.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALAddressDetails.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; import gov.nasa.worldwind.ogc.kml.KMLAbstractObject; @@ -14,78 +13,64 @@ */ public class XALAddressDetails extends KMLAbstractObject // TODO: Postal service parsers { - public XALAddressDetails(String namespaceURI) - { + + public XALAddressDetails(String namespaceURI) { super(namespaceURI); } - public String getAddressType() - { + public String getAddressType() { return (String) this.getField("AddressType"); } - public String getCurrentStatus() - { + public String getCurrentStatus() { return (String) this.getField("CurrentStatus"); } - public String getValidFromDate() - { + public String getValidFromDate() { return (String) this.getField("ValidFromDate"); } - public String getValidToDate() - { + public String getValidToDate() { return (String) this.getField("ValidToDate"); } - public String getUsage() - { + public String getUsage() { return (String) this.getField("Usage"); } - public String getCode() - { + public String getCode() { return (String) this.getField("Code"); } - public String getAddressDetailsKey() - { + public String getAddressDetailsKey() { return (String) this.getField("AddressDetailsKey"); } - public String getAddress() - { + public String getAddress() { return (String) this.getField("Address"); } - public XALAddressLines getAddressLines() - { + public XALAddressLines getAddressLines() { return (XALAddressLines) this.getField("AddressLines"); } - public XALCountry getCountry() - { + public XALCountry getCountry() { return (XALCountry) this.getField("Country"); } - public XALAdministrativeArea getAdministrativeArea() - { + public XALAdministrativeArea getAdministrativeArea() { return (XALAdministrativeArea) this.getField("AdministrativeArea"); } - public XALLocality getLocality() - { + public XALLocality getLocality() { return (XALLocality) this.getField("Locality"); } - public XALThoroughfare getThoroughfare() - { + public XALThoroughfare getThoroughfare() { return (XALThoroughfare) this.getField("Thoroughfare"); } - public XALPostalServiceElements getPostalServiceElements() - { + public XALPostalServiceElements getPostalServiceElements() { return (XALPostalServiceElements) this.getField("PostalServiceElements"); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALAddressLine.java b/src/gov/nasa/worldwind/util/xml/xal/XALAddressLine.java index ae31c88410..ec797a12b3 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALAddressLine.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALAddressLine.java @@ -3,17 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** * @author tag * @version $Id: XALAddressLine.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALAddressLine extends XALAddress -{ - public XALAddressLine(String namespaceURI) - { +public class XALAddressLine extends XALAddress { + + public XALAddressLine(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALAddressLines.java b/src/gov/nasa/worldwind/util/xml/xal/XALAddressLines.java index 8431038563..dd1ac7f0c7 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALAddressLines.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALAddressLines.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -16,32 +15,30 @@ * @author tag * @version $Id: XALAddressLines.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALAddressLines extends XALAbstractObject -{ +public class XALAddressLines extends XALAbstractObject { + protected List addressLines; - public XALAddressLines(String namespaceURI) - { + public XALAddressLines(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof XALAddressLine) + throws XMLStreamException { + if (o instanceof XALAddressLine) { this.addAddressLine((XALAddressLine) o); + } } - public List getAddressLines() - { + public List getAddressLines() { return this.addressLines; } - protected void addAddressLine(XALAddressLine o) - { - if (this.addressLines == null) + protected void addAddressLine(XALAddressLine o) { + if (this.addressLines == null) { this.addressLines = new ArrayList(); + } this.addressLines.add(o); } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALAdministrativeArea.java b/src/gov/nasa/worldwind/util/xml/xal/XALAdministrativeArea.java index 78e024c56a..26012e0664 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALAdministrativeArea.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALAdministrativeArea.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** @@ -12,8 +11,8 @@ */ public class XALAdministrativeArea extends XALAbstractObject // TODO { - public XALAdministrativeArea(String namespaceURI) - { + + public XALAdministrativeArea(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALConstants.java b/src/gov/nasa/worldwind/util/xml/xal/XALConstants.java index 894db3790f..f2ad9ba0a2 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALConstants.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALConstants.java @@ -3,14 +3,13 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** * @author tag * @version $Id: XALConstants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALConstants -{ +public class XALConstants { + final public static String XAL_NAMESPACE = "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"; } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALCountry.java b/src/gov/nasa/worldwind/util/xml/xal/XALCountry.java index fbd28eb6ed..0d560c9840 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALCountry.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALCountry.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; import gov.nasa.worldwind.util.xml.XMLEventParserContext; @@ -16,82 +15,75 @@ * @author tag * @version $Id: XALCountry.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALCountry extends XALAbstractObject -{ +public class XALCountry extends XALAbstractObject { + protected List addressLines; protected List countryNameCodes; protected List countryNames; - public XALCountry(String namespaceURI) - { + public XALCountry(String namespaceURI) { super(namespaceURI); } @Override protected void doAddEventContent(Object o, XMLEventParserContext ctx, XMLEvent event, Object... args) - throws XMLStreamException - { - if (o instanceof XALAddressLine) + throws XMLStreamException { + if (o instanceof XALAddressLine) { this.addAddressLine((XALAddressLine) o); - else if (o instanceof XALCountryNameCode) + } else if (o instanceof XALCountryNameCode) { this.addCountryNameCode((XALCountryNameCode) o); - else if (o instanceof XALCountryName) + } else if (o instanceof XALCountryName) { this.addCountryName((XALCountryName) o); - else + } else { super.doAddEventContent(o, ctx, event, args); + } } - public List getAddressLines() - { + public List getAddressLines() { return this.addressLines; } - protected void addAddressLine(XALAddressLine o) - { - if (this.addressLines == null) + protected void addAddressLine(XALAddressLine o) { + if (this.addressLines == null) { this.addressLines = new ArrayList(); + } this.addressLines.add(o); } - public List getCountryNameCodes() - { + public List getCountryNameCodes() { return this.countryNameCodes; } - protected void addCountryNameCode(XALCountryNameCode o) - { - if (this.countryNameCodes == null) + protected void addCountryNameCode(XALCountryNameCode o) { + if (this.countryNameCodes == null) { this.countryNameCodes = new ArrayList(); + } this.countryNameCodes.add(o); } - public List getCountryNames() - { + public List getCountryNames() { return this.countryNames; } - protected void addCountryName(XALCountryName o) - { - if (this.countryNames == null) + protected void addCountryName(XALCountryName o) { + if (this.countryNames == null) { this.countryNames = new ArrayList(); + } this.countryNames.add(o); } - public XALAdministrativeArea getAdministrativeArea() - { + public XALAdministrativeArea getAdministrativeArea() { return (XALAdministrativeArea) this.getField("AdministrativeArea"); } - public XALLocality getLocality() - { + public XALLocality getLocality() { return (XALLocality) this.getField("Locality"); } - public XALThoroughfare getThoroughfare() - { + public XALThoroughfare getThoroughfare() { return (XALThoroughfare) this.getField("Thoroughfare"); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALCountryName.java b/src/gov/nasa/worldwind/util/xml/xal/XALCountryName.java index 41b64b16ea..b975b48c18 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALCountryName.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALCountryName.java @@ -3,17 +3,15 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** * @author tag * @version $Id: XALCountryName.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALCountryName extends XALAbstractObject -{ - public XALCountryName(String namespaceURI) - { +public class XALCountryName extends XALAbstractObject { + + public XALCountryName(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALCountryNameCode.java b/src/gov/nasa/worldwind/util/xml/xal/XALCountryNameCode.java index a3647f4e89..a21359e6bd 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALCountryNameCode.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALCountryNameCode.java @@ -3,22 +3,19 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** * @author tag * @version $Id: XALCountryNameCode.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALCountryNameCode extends XALAbstractObject -{ - public XALCountryNameCode(String namespaceURI) - { +public class XALCountryNameCode extends XALAbstractObject { + + public XALCountryNameCode(String namespaceURI) { super(namespaceURI); } - public String getScheme() - { + public String getScheme() { return (String) this.getField("Scheme"); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALLocality.java b/src/gov/nasa/worldwind/util/xml/xal/XALLocality.java index ba205972ce..2e2d323cbc 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALLocality.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALLocality.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** @@ -12,8 +11,8 @@ */ public class XALLocality extends XALAbstractObject // TODO { - public XALLocality(String namespaceURI) - { + + public XALLocality(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALParserContext.java b/src/gov/nasa/worldwind/util/xml/xal/XALParserContext.java index 3030ff404f..e05efa0b31 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALParserContext.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALParserContext.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; import gov.nasa.worldwind.util.xml.*; @@ -16,15 +15,13 @@ * @author tag * @version $Id: XALParserContext.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class XALParserContext extends BasicXMLEventParserContext -{ - protected static final String[] StringFields = new String[] - { - "Address" - }; - - public static Map getDefaultParsers() - { +public class XALParserContext extends BasicXMLEventParserContext { + + protected static final String[] StringFields = new String[]{ + "Address" + }; + + public static Map getDefaultParsers() { ConcurrentHashMap parsers = new ConcurrentHashMap(); String xns = XALConstants.XAL_NAMESPACE; @@ -41,8 +38,7 @@ public static Map getDefaultParsers() parsers.put(new QName(xns, "Thoroughfare"), new XALThoroughfare(xns)); StringXMLEventParser stringParser = new StringXMLEventParser(); - for (String s : StringFields) - { + for (String s : StringFields) { parsers.put(new QName(xns, s), stringParser); } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALPostalServiceElements.java b/src/gov/nasa/worldwind/util/xml/xal/XALPostalServiceElements.java index 9234e88b45..bd53b2f581 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALPostalServiceElements.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALPostalServiceElements.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** @@ -12,8 +11,8 @@ */ public class XALPostalServiceElements extends XALAbstractObject // TODO { - public XALPostalServiceElements(String namespaceURI) - { + + public XALPostalServiceElements(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/XALThoroughfare.java b/src/gov/nasa/worldwind/util/xml/xal/XALThoroughfare.java index 43bef1d84e..69c212515e 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/XALThoroughfare.java +++ b/src/gov/nasa/worldwind/util/xml/xal/XALThoroughfare.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwind.util.xml.xal; /** @@ -12,8 +11,8 @@ */ public class XALThoroughfare extends XALAbstractObject // TODO { - public XALThoroughfare(String namespaceURI) - { + + public XALThoroughfare(String namespaceURI) { super(namespaceURI); } } diff --git a/src/gov/nasa/worldwind/util/xml/xal/package-info.java b/src/gov/nasa/worldwind/util/xml/xal/package-info.java index b3b6a929bc..f8e53f46fe 100644 --- a/src/gov/nasa/worldwind/util/xml/xal/package-info.java +++ b/src/gov/nasa/worldwind/util/xml/xal/package-info.java @@ -3,12 +3,11 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

          * Provides classes for parsing the XAL namespace.

          * -

          Note: This package is not yet complete.

          + *

          Note: This package is not yet complete.

          * */ package gov.nasa.worldwind.util.xml.xal; diff --git a/src/gov/nasa/worldwind/view/BasicView.java b/src/gov/nasa/worldwind/view/BasicView.java index eafdba9a53..fdac056041 100644 --- a/src/gov/nasa/worldwind/view/BasicView.java +++ b/src/gov/nasa/worldwind/view/BasicView.java @@ -28,9 +28,11 @@ * @author jym * @version $Id: BasicView.java 2204 2014-08-07 23:35:03Z dcollins $ */ -public class BasicView extends WWObjectImpl implements View -{ - /** The field of view in degrees. */ +public class BasicView extends WWObjectImpl implements View { + + /** + * The field of view in degrees. + */ protected Angle fieldOfView = Angle.fromDegrees(45); // Provide reasonable default values for the near and far clip distances. By default, BasicView automatically // updates these values each frame based on the current eye position relative to the surface. These default values @@ -81,13 +83,13 @@ public class BasicView extends WWObjectImpl implements View protected static final double COLLISION_THRESHOLD = 10; protected static final int COLLISION_NUM_ITERATIONS = 4; - /** Construct a BasicView */ - public BasicView() - { + /** + * Construct a BasicView + */ + public BasicView() { } - public Globe getGlobe() - { + public Globe getGlobe() { return this.globe; } @@ -96,124 +98,106 @@ public Globe getGlobe() * * @param globe New globe. */ - public void setGlobe(Globe globe) - { + public void setGlobe(Globe globe) { this.globe = globe; } - public DrawContext getDC() - { + public DrawContext getDC() { return (this.dc); } - public ViewInputHandler getViewInputHandler() - { + public ViewInputHandler getViewInputHandler() { return viewInputHandler; } - public void setViewInputHandler(ViewInputHandler viewInputHandler) - { + public void setViewInputHandler(ViewInputHandler viewInputHandler) { this.viewInputHandler = viewInputHandler; } - public boolean isDetectCollisions() - { + public boolean isDetectCollisions() { return this.detectCollisions; } - public void setDetectCollisions(boolean detectCollisions) - { + public void setDetectCollisions(boolean detectCollisions) { this.detectCollisions = detectCollisions; } - public boolean hadCollisions() - { + public boolean hadCollisions() { boolean result = this.hadCollisions; this.hadCollisions = false; return result; } - public void copyViewState(View view) - { + public void copyViewState(View view) { this.globe = view.getGlobe(); Vec4 center = view.getCenterPoint(); - if (center == null) - { + if (center == null) { Vec4 eyePoint = view.getCurrentEyePoint(); center = eyePoint.add3(view.getForwardVector()); } setOrientation(view.getCurrentEyePosition(), globe.computePositionFromPoint(center)); } - public void apply(DrawContext dc) - { - if (dc == null) - { + public void apply(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("layers.AbstractLayer.NoGlobeSpecifiedInDrawingContext"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.viewInputHandler != null) + if (this.viewInputHandler != null) { this.viewInputHandler.apply(); + } doApply(dc); - if (this.viewInputHandler != null) + if (this.viewInputHandler != null) { this.viewInputHandler.viewApplied(); + } } - protected void doApply(DrawContext dc) - { + protected void doApply(DrawContext dc) { } - public void stopMovement() - { + public void stopMovement() { this.firePropertyChange(VIEW_STOPPED, null, this); } - public java.awt.Rectangle getViewport() - { + public java.awt.Rectangle getViewport() { // java.awt.Rectangle is mutable, so we defensively copy the viewport. return new java.awt.Rectangle(this.viewport); } - public Frustum getFrustum() - { + public Frustum getFrustum() { return this.frustum; } - public Frustum getFrustumInModelCoordinates() - { - if (this.lastFrustumInModelCoords == null) - { + public Frustum getFrustumInModelCoordinates() { + if (this.lastFrustumInModelCoords == null) { Matrix modelviewTranspose = this.modelview.getTranspose(); - if (modelviewTranspose != null) + if (modelviewTranspose != null) { this.lastFrustumInModelCoords = this.frustum.transformBy(modelviewTranspose); - else + } else { this.lastFrustumInModelCoords = this.frustum; + } } return this.lastFrustumInModelCoords; } - public void setFieldOfView(Angle fieldOfView) - { - if (fieldOfView == null) - { + public void setFieldOfView(Angle fieldOfView) { + if (fieldOfView == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -222,46 +206,39 @@ public void setFieldOfView(Angle fieldOfView) this.fieldOfView = fieldOfView; } - public double getNearClipDistance() - { + public double getNearClipDistance() { return this.nearClipDistance; } - protected void setNearClipDistance(double clipDistance) - { + protected void setNearClipDistance(double clipDistance) { this.nearClipDistance = clipDistance; } - public double getFarClipDistance() - { + public double getFarClipDistance() { return this.farClipDistance; } - protected void setFarClipDistance(double clipDistance) - { + protected void setFarClipDistance(double clipDistance) { this.farClipDistance = clipDistance; } - public Matrix getModelviewMatrix() - { + public Matrix getModelviewMatrix() { return this.modelview; } - /** {@inheritDoc} */ - public long getViewStateID() - { + /** + * {@inheritDoc} + */ + public long getViewStateID() { return this.viewStateID; } - public Angle getFieldOfView() - { + public Angle getFieldOfView() { return this.fieldOfView; } - public Vec4 project(Vec4 modelPoint) - { - if (modelPoint == null) - { + public Vec4 project(Vec4 modelPoint) { + if (modelPoint == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -270,10 +247,8 @@ public Vec4 project(Vec4 modelPoint) return this.project(modelPoint, this.modelview, this.projection, this.viewport); } - public Vec4 unProject(Vec4 windowPoint) - { - if (windowPoint == null) - { + public Vec4 unProject(Vec4 windowPoint) { + if (windowPoint == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -282,46 +257,37 @@ public Vec4 unProject(Vec4 windowPoint) return unProject(windowPoint, this.modelview, this.projection, this.viewport); } - public Vec4 getEyePoint() - { - if (this.lastEyePoint == null) + public Vec4 getEyePoint() { + if (this.lastEyePoint == null) { this.lastEyePoint = Vec4.UNIT_W.transformBy4(this.modelviewInv); + } return this.lastEyePoint; } - public Vec4 getCenterPoint() - { + public Vec4 getCenterPoint() { Vec4 eyePoint = this.getEyePoint(); Intersection[] intersection = this.globe.intersect(new Line(eyePoint, this.getForwardVector()), 0); - if (intersection == null) - { + if (intersection == null) { return null; - } - else - { + } else { return (intersection[0].getIntersectionPoint()); } } - public Position getCenterPosition() - { + public Position getCenterPosition() { Vec4 eyePoint = this.getEyePoint(); Intersection[] intersection = this.globe.intersect(new Line(eyePoint, this.getForwardVector()), 0); Position pos = this.globe.computePositionFromPoint(intersection[0].getIntersectionPoint()); return (pos); } - public Vec4 getCurrentEyePoint() - { - if (this.globe != null) - { + public Vec4 getCurrentEyePoint() { + if (this.globe != null) { Matrix modelview = ViewUtil.computeTransformMatrix(this.globe, this.eyePosition, - this.heading, this.pitch, this.roll); - if (modelview != null) - { + this.heading, this.pitch, this.roll); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { return Vec4.UNIT_W.transformBy4(modelviewInv); } } @@ -330,20 +296,16 @@ public Vec4 getCurrentEyePoint() return Vec4.ZERO; } - public Position getCurrentEyePosition() - { + public Position getCurrentEyePosition() { // This method is intended to compute the eye position from this view's current parameters. It can be called // without having previously applied this view in apply(). - if (this.globe != null) - { + if (this.globe != null) { Matrix modelview = ViewUtil.computeTransformMatrix(this.globe, this.eyePosition, - this.heading, this.pitch, this.roll); - if (modelview != null) - { + this.heading, this.pitch, this.roll); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { Vec4 eyePoint = Vec4.UNIT_W.transformBy4(modelviewInv); return this.globe.computePositionFromPoint(eyePoint); } @@ -353,15 +315,12 @@ public Position getCurrentEyePosition() return Position.ZERO; } - public Position getEyePosition() - { + public Position getEyePosition() { return this.lastEyePosition; } - public void setEyePosition(Position eyePosition) - { - if (eyePosition == null) - { + public void setEyePosition(Position eyePosition) { + if (eyePosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -373,15 +332,12 @@ public void setEyePosition(Position eyePosition) //resolveCollisionsWithCenterPosition(); } - public Angle getHeading() - { + public Angle getHeading() { return this.heading; } - public void setHeading(Angle heading) - { - if (heading == null) - { + public void setHeading(Angle heading) { + if (heading == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -393,15 +349,12 @@ public void setHeading(Angle heading) //resolveCollisionsWithPitch(); } - public Angle getPitch() - { + public Angle getPitch() { return this.pitch; } - public void setPitch(Angle pitch) - { - if (pitch == null) - { + public void setPitch(Angle pitch) { + if (pitch == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -412,10 +365,8 @@ public void setPitch(Angle pitch) //resolveCollisionsWithPitch(); } - public void setRoll(Angle roll) - { - if (roll == null) - { + public void setRoll(Angle roll) { + if (roll == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -425,22 +376,21 @@ public void setRoll(Angle roll) this.updateModelViewStateID(); } - public Angle getRoll() - { + public Angle getRoll() { return this.roll; } - public Vec4 getUpVector() - { - if (this.lastUpVector == null) + public Vec4 getUpVector() { + if (this.lastUpVector == null) { this.lastUpVector = Vec4.UNIT_Y.transformBy4(this.modelviewInv); + } return this.lastUpVector; } - public Vec4 getForwardVector() - { - if (this.lastForwardVector == null) + public Vec4 getForwardVector() { + if (this.lastForwardVector == null) { this.lastForwardVector = Vec4.UNIT_NEGATIVE_Z.transformBy4(this.modelviewInv); + } return this.lastForwardVector; } @@ -450,17 +400,13 @@ public Vec4 getForwardVector() * * @return Vec4 of the forward axis. */ - public Vec4 getCurrentForwardVector() - { - if (this.globe != null) - { + public Vec4 getCurrentForwardVector() { + if (this.globe != null) { Matrix modelview = ViewUtil.computeTransformMatrix(this.globe, this.eyePosition, - this.heading, this.pitch, this.roll); - if (modelview != null) - { + this.heading, this.pitch, this.roll); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { return Vec4.UNIT_NEGATIVE_Z.transformBy4(modelviewInv); } } @@ -469,39 +415,30 @@ public Vec4 getCurrentForwardVector() return null; } - protected void setViewState(ViewUtil.ViewState modelCoords) - { - if (modelCoords != null) - { - if (modelCoords.getPosition() != null) - { + protected void setViewState(ViewUtil.ViewState modelCoords) { + if (modelCoords != null) { + if (modelCoords.getPosition() != null) { this.eyePosition = ViewUtil.normalizedEyePosition(modelCoords.getPosition()); } - if (modelCoords.getHeading() != null) - { + if (modelCoords.getHeading() != null) { this.heading = ViewUtil.normalizedHeading(modelCoords.getHeading()); } - if (modelCoords.getPitch() != null) - { + if (modelCoords.getPitch() != null) { this.pitch = ViewUtil.normalizedPitch(modelCoords.getPitch()); } - if (modelCoords.getRoll() != null) - { + if (modelCoords.getRoll() != null) { this.roll = ViewUtil.normalizedRoll(modelCoords.getRoll()); } } } - public void setOrientation(Position eyePosition, Position centerPosition) - { - if (eyePosition == null || centerPosition == null) - { + public void setOrientation(Position eyePosition, Position centerPosition) { + if (eyePosition == null || centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.globe == null) - { + if (this.globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -509,8 +446,7 @@ public void setOrientation(Position eyePosition, Position centerPosition) Vec4 newEyePoint = this.globe.computePointFromPosition(eyePosition); Vec4 newCenterPoint = this.globe.computePointFromPosition(centerPosition); - if (newEyePoint == null || newCenterPoint == null) - { + if (newEyePoint == null || newCenterPoint == null) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -522,77 +458,65 @@ public void setOrientation(Position eyePosition, Position centerPosition) // Otherwise, estimate the up direction by using the *current* heading with the new center position. Vec4 forward = newCenterPoint.subtract3(newEyePoint).normalize3(); - if (forward.cross3(up).getLength3() < 0.001) - { + if (forward.cross3(up).getLength3() < 0.001) { Matrix modelview = ViewUtil.computeTransformMatrix(this.globe, eyePosition, this.heading, Angle.ZERO, - Angle.ZERO); - if (modelview != null) - { + Angle.ZERO); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { up = Vec4.UNIT_Y.transformBy4(modelviewInv); } } } - if (up == null) - { + if (up == null) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); } ViewUtil.ViewState modelCoords = ViewUtil.computeViewState( - this.globe, newEyePoint, newCenterPoint, up); + this.globe, newEyePoint, newCenterPoint, up); setViewState(modelCoords); this.updateModelViewStateID(); } - public void stopAnimations() - { + public void stopAnimations() { viewInputHandler.stopAnimators(); } - public boolean isAnimating() - { + public boolean isAnimating() { return viewInputHandler.isAnimating(); } - public void goTo(Position position, double distance) - { + public void goTo(Position position, double distance) { viewInputHandler.goTo(position, distance); } - public Line computeRayFromScreenPoint(double x, double y) - { + public Line computeRayFromScreenPoint(double x, double y) { return ViewUtil.computeRayFromScreenPoint(this, x, y, - this.modelview, this.projection, this.viewport); + this.modelview, this.projection, this.viewport); } - public Position computePositionFromScreenPoint(double x, double y) - { - if (this.globe != null) - { + public Position computePositionFromScreenPoint(double x, double y) { + if (this.globe != null) { Line ray = computeRayFromScreenPoint(x, y); - if (ray != null) + if (ray != null) { return this.globe.getIntersectionPosition(ray); + } } return null; } - public double computePixelSizeAtDistance(double distance) - { + public double computePixelSizeAtDistance(double distance) { return ViewUtil.computePixelSizeAtDistance(distance, this.fieldOfView, this.viewport); } - protected Position computeEyePositionFromModelview() - { - if (this.globe != null) - { + protected Position computeEyePositionFromModelview() { + if (this.globe != null) { Vec4 eyePoint = Vec4.UNIT_W.transformBy4(this.modelviewInv); return this.globe.computePositionFromPoint(eyePoint); } @@ -600,20 +524,16 @@ protected Position computeEyePositionFromModelview() return Position.ZERO; } - public double getHorizonDistance() - { + public double getHorizonDistance() { return this.horizonDistance; } - protected double computeHorizonDistance() - { + protected double computeHorizonDistance() { return this.computeHorizonDistance(computeEyePositionFromModelview()); } - protected double computeHorizonDistance(Position eyePosition) - { - if (this.globe != null && eyePosition != null) - { + protected double computeHorizonDistance(Position eyePosition) { + if (this.globe != null && eyePosition != null) { double elevation = eyePosition.getElevation(); double elevationAboveSurface = ViewUtil.computeElevationAboveSurface(this.dc, eyePosition); return ViewUtil.computeHorizonDistance(this.globe, Math.max(elevation, elevationAboveSurface)); @@ -622,99 +542,85 @@ protected double computeHorizonDistance(Position eyePosition) return 0; } - public ViewPropertyLimits getViewPropertyLimits() - { + public ViewPropertyLimits getViewPropertyLimits() { return this.viewLimits; } - protected double computeNearClipDistance() - { + protected double computeNearClipDistance() { return computeNearDistance(getCurrentEyePosition()); } - protected double computeFarClipDistance() - { + protected double computeFarClipDistance() { return computeFarDistance(getCurrentEyePosition()); } - protected double computeNearDistance(Position eyePosition) - { + protected double computeNearDistance(Position eyePosition) { // Compute the near clip distance in order to achieve a desired depth resolution at the far clip distance. This // computed distance is limited such that it does not intersect the terrain when possible and is never less than // a predetermined minimum (usually one). The computed near distance automatically scales with the resolution of // the OpenGL depth buffer. int depthBits = this.dc.getGLRuntimeCapabilities().getDepthBits(); double nearDistance = ViewUtil.computePerspectiveNearDistance(this.farClipDistance, DEFAULT_DEPTH_RESOLUTION, - depthBits); + depthBits); // Prevent the near clip plane from intersecting the terrain. - if (eyePosition != null && this.dc != null) - { + if (eyePosition != null && this.dc != null) { double distanceToSurface = ViewUtil.computeElevationAboveSurface(this.dc, eyePosition); - if (distanceToSurface > 0) - { + if (distanceToSurface > 0) { double maxNearDistance = ViewUtil.computePerspectiveNearDistance(this.fieldOfView, distanceToSurface); - if (nearDistance > maxNearDistance) + if (nearDistance > maxNearDistance) { nearDistance = maxNearDistance; - } - else - { + } + } else { nearDistance = MINIMUM_NEAR_DISTANCE; } } // Prevent the near clip plane from becoming unnecessarily small. A very small clip plane is not useful for // rendering the WorldWind scene, and significantly reduces the depth precision in the majority of the scene. - if (nearDistance < MINIMUM_NEAR_DISTANCE) + if (nearDistance < MINIMUM_NEAR_DISTANCE) { nearDistance = MINIMUM_NEAR_DISTANCE; + } return nearDistance; } - protected double computeFarDistance(Position eyePosition) - { + protected double computeFarDistance(Position eyePosition) { double far = 0; - if (eyePosition != null) - { + if (eyePosition != null) { far = computeHorizonDistance(eyePosition); } return far < MINIMUM_FAR_DISTANCE ? MINIMUM_FAR_DISTANCE : far; } - public Matrix getProjectionMatrix() - { + public Matrix getProjectionMatrix() { return this.projection; } - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); // Creating a new RestorableSupport failed. RestorableSupport logged the problem, so just return null. - if (rs == null) + if (rs == null) { return null; + } this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -728,92 +634,96 @@ public void restoreState(String stateInXml) * Update the modelview state identifier. This method should be called whenever one of the fields that affects the * modelview matrix is changed. */ - protected void updateModelViewStateID() - { + protected void updateModelViewStateID() { this.viewStateID++; } //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { this.getViewPropertyLimits().getRestorableState(rs, rs.addStateObject(context, "viewPropertyLimits")); rs.addStateValueAsBoolean(context, "detectCollisions", this.isDetectCollisions()); - if (this.getFieldOfView() != null) + if (this.getFieldOfView() != null) { rs.addStateValueAsDouble(context, "fieldOfView", this.getFieldOfView().getDegrees()); + } rs.addStateValueAsDouble(context, "nearClipDistance", this.getNearClipDistance()); rs.addStateValueAsDouble(context, "farClipDistance", this.getFarClipDistance()); - if (this.getEyePosition() != null) + if (this.getEyePosition() != null) { rs.addStateValueAsPosition(context, "eyePosition", this.getEyePosition()); + } - if (this.getHeading() != null) + if (this.getHeading() != null) { rs.addStateValueAsDouble(context, "heading", this.getHeading().getDegrees()); + } - if (this.getPitch() != null) + if (this.getPitch() != null) { rs.addStateValueAsDouble(context, "pitch", this.getPitch().getDegrees()); + } } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Restore the property limits and collision detection flags before restoring the view's position and // orientation. This has the effect of ensuring that the view's position and orientation are consistent with the // current property limits and the current surface collision state. RestorableSupport.StateObject so = rs.getStateObject(context, "viewPropertyLimits"); - if (so != null) + if (so != null) { this.getViewPropertyLimits().restoreState(rs, so); + } Boolean b = rs.getStateValueAsBoolean(context, "detectCollisions"); - if (b != null) + if (b != null) { this.setDetectCollisions(b); + } Double d = rs.getStateValueAsDouble(context, "fieldOfView"); - if (d != null) + if (d != null) { this.setFieldOfView(Angle.fromDegrees(d)); + } d = rs.getStateValueAsDouble(context, "nearClipDistance"); - if (d != null) + if (d != null) { this.setNearClipDistance(d); + } d = rs.getStateValueAsDouble(context, "farClipDistance"); - if (d != null) + if (d != null) { this.setFarClipDistance(d); + } Position p = rs.getStateValueAsPosition(context, "eyePosition"); - if (p != null) + if (p != null) { this.setEyePosition(p); + } d = rs.getStateValueAsDouble(context, "heading"); - if (d != null) + if (d != null) { this.setHeading(Angle.fromDegrees(d)); + } d = rs.getStateValueAsDouble(context, "pitch"); - if (d != null) + if (d != null) { this.setPitch(Angle.fromDegrees(d)); + } } - public Matrix pushReferenceCenter(DrawContext dc, Vec4 referenceCenter) - { - if (dc == null) - { + public Matrix pushReferenceCenter(DrawContext dc, Vec4 referenceCenter) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (referenceCenter == null) - { + if (referenceCenter == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -823,53 +733,46 @@ public Matrix pushReferenceCenter(DrawContext dc, Vec4 referenceCenter) // Compute a new model-view matrix with origin at referenceCenter. Matrix matrix = null; - if (modelview != null) + if (modelview != null) { matrix = modelview.multiply(Matrix.fromTranslation(referenceCenter)); + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Store the current matrix-mode state. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { ogsh.pushAttrib(gl, GL2.GL_TRANSFORM_BIT); gl.glMatrixMode(GL2.GL_MODELVIEW); // Push and load a new model-view matrix to the current OpenGL context held by 'dc'. gl.glPushMatrix(); - if (matrix != null) - { + if (matrix != null) { double[] matrixArray = new double[16]; matrix.toArray(matrixArray, 0, false); gl.glLoadMatrixd(matrixArray, 0); } - } - finally - { + } finally { ogsh.pop(gl); } return matrix; } - public Matrix setReferenceCenter(DrawContext dc, Vec4 referenceCenter) - { - if (dc == null) - { + public Matrix setReferenceCenter(DrawContext dc, Vec4 referenceCenter) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (referenceCenter == null) - { + if (referenceCenter == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -879,10 +782,12 @@ public Matrix setReferenceCenter(DrawContext dc, Vec4 referenceCenter) // Compute a new model-view matrix with origin at referenceCenter. Matrix matrix = null; - if (modelview != null) + if (modelview != null) { matrix = modelview.multiply(Matrix.fromTranslation(referenceCenter)); - if (matrix == null) + } + if (matrix == null) { return null; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -901,18 +806,15 @@ public Matrix setReferenceCenter(DrawContext dc, Vec4 referenceCenter) * @param dc the current WorldWind drawing context on which the original matrix will be restored. * * @throws IllegalArgumentException if dc is null, or if the Globe or GL - * instances in dc are null. + * instances in dc are null. */ - public void popReferenceCenter(DrawContext dc) - { - if (dc == null) - { + public void popReferenceCenter(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -923,17 +825,14 @@ public void popReferenceCenter(DrawContext dc) // Store the current matrix-mode state. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { ogsh.pushAttrib(gl, GL2.GL_TRANSFORM_BIT); gl.glMatrixMode(GL2.GL_MODELVIEW); // Pop the top model-view matrix. gl.glPopMatrix(); - } - finally - { + } finally { ogsh.pop(gl); } } @@ -942,29 +841,25 @@ public void popReferenceCenter(DrawContext dc) * Transforms the specified object coordinates into window coordinates using the given modelview and projection * matrices, and viewport. * - * @param point The object coordinate to transform - * @param modelview The modelview matrix + * @param point The object coordinate to transform + * @param modelview The modelview matrix * @param projection The projection matrix - * @param viewport The viewport + * @param viewport The viewport * * @return the transformed coordinates */ - public Vec4 project(Vec4 point, Matrix modelview, Matrix projection, java.awt.Rectangle viewport) - { - if (point == null) - { + public Vec4 project(Vec4 point, Matrix modelview, Matrix projection, java.awt.Rectangle viewport) { + if (point == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (modelview == null || projection == null) - { + if (modelview == null || projection == null) { String message = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewport == null) - { + if (viewport == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -976,16 +871,15 @@ public Vec4 project(Vec4 point, Matrix modelview, Matrix projection, java.awt.Re modelview.toArray(modelviewArray, 0, false); projection.toArray(projectionArray, 0, false); // GLU expects the viewport as a four-component array. - int[] viewportArray = new int[] {viewport.x, viewport.y, viewport.width, viewport.height}; + int[] viewportArray = new int[]{viewport.x, viewport.y, viewport.width, viewport.height}; double[] result = new double[3]; if (!this.dc.getGLU().gluProject( - point.x, point.y, point.z, - modelviewArray, 0, - projectionArray, 0, - viewportArray, 0, - result, 0)) - { + point.x, point.y, point.z, + modelviewArray, 0, + projectionArray, 0, + viewportArray, 0, + result, 0)) { return null; } @@ -996,28 +890,24 @@ public Vec4 project(Vec4 point, Matrix modelview, Matrix projection, java.awt.Re * Maps the given window coordinates into model coordinates using the given matrices and viewport. * * @param windowPoint the window point - * @param modelview the modelview matrix - * @param projection the projection matrix - * @param viewport the window viewport + * @param modelview the modelview matrix + * @param projection the projection matrix + * @param viewport the window viewport * * @return the unprojected point */ - public Vec4 unProject(Vec4 windowPoint, Matrix modelview, Matrix projection, java.awt.Rectangle viewport) - { - if (windowPoint == null) - { + public Vec4 unProject(Vec4 windowPoint, Matrix modelview, Matrix projection, java.awt.Rectangle viewport) { + if (windowPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (modelview == null || projection == null) - { + if (modelview == null || projection == null) { String message = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewport == null) - { + if (viewport == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -1029,16 +919,15 @@ public Vec4 unProject(Vec4 windowPoint, Matrix modelview, Matrix projection, jav modelview.toArray(modelviewArray, 0, false); projection.toArray(projectionArray, 0, false); // GLU expects the viewport as a four-component array. - int[] viewportArray = new int[] {viewport.x, viewport.y, viewport.width, viewport.height}; + int[] viewportArray = new int[]{viewport.x, viewport.y, viewport.width, viewport.height}; double[] result = new double[3]; if (!this.dc.getGLU().gluUnProject( - windowPoint.x, windowPoint.y, windowPoint.z, - modelviewArray, 0, - projectionArray, 0, - viewportArray, 0, - result, 0)) - { + windowPoint.x, windowPoint.y, windowPoint.z, + modelviewArray, 0, + projectionArray, 0, + viewportArray, 0, + result, 0)) { return null; } @@ -1048,30 +937,25 @@ public Vec4 unProject(Vec4 windowPoint, Matrix modelview, Matrix projection, jav /** * Sets the the opengl modelview and projection matrices to the given matrices. * - * @param dc the drawing context - * @param modelview the modelview matrix + * @param dc the drawing context + * @param modelview the modelview matrix * @param projection the projection matrix */ - public static void loadGLViewState(DrawContext dc, Matrix modelview, Matrix projection) - { - if (dc == null) - { + public static void loadGLViewState(DrawContext dc, Matrix modelview, Matrix projection) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (modelview == null) - { + if (modelview == null) { Logging.logger().fine("nullValue.ModelViewIsNull"); } - if (projection == null) - { + if (projection == null) { Logging.logger().fine("nullValue.ProjectionIsNull"); } @@ -1081,47 +965,37 @@ public static void loadGLViewState(DrawContext dc, Matrix modelview, Matrix proj // Store the current matrix-mode state. OGLStackHandler ogsh = new OGLStackHandler(); - try - { + try { ogsh.pushAttrib(gl, GL2.GL_TRANSFORM_BIT); // Apply the model-view matrix to the current OpenGL context. gl.glMatrixMode(GL2.GL_MODELVIEW); - if (modelview != null) - { + if (modelview != null) { modelview.toArray(matrixArray, 0, false); gl.glLoadMatrixd(matrixArray, 0); - } - else - { + } else { gl.glLoadIdentity(); } // Apply the projection matrix to the current OpenGL context. gl.glMatrixMode(GL2.GL_PROJECTION); - if (projection != null) - { + if (projection != null) { projection.toArray(matrixArray, 0, false); gl.glLoadMatrixd(matrixArray, 0); - } - else - { + } else { gl.glLoadIdentity(); } - } - finally - { + } finally { ogsh.pop(gl); } } /** - * Add an animator to the this View. The View does not start the animator. + * Add an animator to the this View. The View does not start the animator. * * @param animator the {@link gov.nasa.worldwind.animation.Animator} to be added */ - public void addAnimator(Animator animator) - { + public void addAnimator(Animator animator) { viewInputHandler.addAnimator(animator); } } diff --git a/src/gov/nasa/worldwind/view/BasicViewPropertyLimits.java b/src/gov/nasa/worldwind/view/BasicViewPropertyLimits.java index 7460b3fac6..680b7a505f 100644 --- a/src/gov/nasa/worldwind/view/BasicViewPropertyLimits.java +++ b/src/gov/nasa/worldwind/view/BasicViewPropertyLimits.java @@ -16,8 +16,8 @@ * @author jym * @version $Id: BasicViewPropertyLimits.java 2253 2014-08-22 16:33:46Z dcollins $ */ -public class BasicViewPropertyLimits implements ViewPropertyLimits -{ +public class BasicViewPropertyLimits implements ViewPropertyLimits { + protected Sector eyeLocationLimits; protected Angle minHeading; protected Angle maxHeading; @@ -28,25 +28,27 @@ public class BasicViewPropertyLimits implements ViewPropertyLimits protected double minEyeElevation; protected double maxEyeElevation; - /** Creates a new BasicViewPropertyLimits with default limits. */ - public BasicViewPropertyLimits() - { + /** + * Creates a new BasicViewPropertyLimits with default limits. + */ + public BasicViewPropertyLimits() { this.reset(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Sector getEyeLocationLimits() - { + public Sector getEyeLocationLimits() { return this.eyeLocationLimits; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setEyeLocationLimits(Sector sector) - { - if (sector == null) - { + public void setEyeLocationLimits(Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -55,34 +57,37 @@ public void setEyeLocationLimits(Sector sector) this.eyeLocationLimits = sector; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public double[] getEyeElevationLimits() - { - return new double[] {this.minEyeElevation, this.maxEyeElevation}; + public double[] getEyeElevationLimits() { + return new double[]{this.minEyeElevation, this.maxEyeElevation}; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setEyeElevationLimits(double minValue, double maxValue) - { + public void setEyeElevationLimits(double minValue, double maxValue) { this.minEyeElevation = minValue; this.maxEyeElevation = maxValue; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Angle[] getHeadingLimits() - { - return new Angle[] {this.minHeading, this.maxHeading}; + public Angle[] getHeadingLimits() { + return new Angle[]{this.minHeading, this.maxHeading}; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setHeadingLimits(Angle minAngle, Angle maxAngle) - { - if (minAngle == null || maxAngle == null) - { + public void setHeadingLimits(Angle minAngle, Angle maxAngle) { + if (minAngle == null || maxAngle == null) { String message = Logging.getMessage("nullValue.MinOrMaxAngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -92,19 +97,20 @@ public void setHeadingLimits(Angle minAngle, Angle maxAngle) this.maxHeading = maxAngle; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Angle[] getPitchLimits() - { - return new Angle[] {this.minPitch, this.maxPitch}; + public Angle[] getPitchLimits() { + return new Angle[]{this.minPitch, this.maxPitch}; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setPitchLimits(Angle minAngle, Angle maxAngle) - { - if (minAngle == null || maxAngle == null) - { + public void setPitchLimits(Angle minAngle, Angle maxAngle) { + if (minAngle == null || maxAngle == null) { String message = Logging.getMessage("nullValue.MinOrMaxAngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -114,19 +120,20 @@ public void setPitchLimits(Angle minAngle, Angle maxAngle) this.maxPitch = maxAngle; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Angle[] getRollLimits() - { - return new Angle[] {this.minRoll, this.maxRoll}; + public Angle[] getRollLimits() { + return new Angle[]{this.minRoll, this.maxRoll}; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setRollLimits(Angle minAngle, Angle maxAngle) - { - if (minAngle == null || maxAngle == null) - { + public void setRollLimits(Angle minAngle, Angle maxAngle) { + if (minAngle == null || maxAngle == null) { String message = Logging.getMessage("nullValue.MinOrMaxAngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -136,9 +143,10 @@ public void setRollLimits(Angle minAngle, Angle maxAngle) this.maxRoll = maxAngle; } - /** {@inheritDoc} */ - public void reset() - { + /** + * {@inheritDoc} + */ + public void reset() { this.eyeLocationLimits = Sector.FULL_SPHERE; this.minEyeElevation = -Double.MAX_VALUE; this.maxEyeElevation = Double.MAX_VALUE; @@ -150,19 +158,18 @@ public void reset() this.maxRoll = Angle.POS180; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Position limitEyePosition(View view, Position position) - { - if (view == null) - { + public Position limitEyePosition(View view, Position position) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -176,71 +183,66 @@ public Position limitEyePosition(View view, Position position) return new Position(lat, lon, alt); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Angle limitHeading(View view, Angle angle) - { - if (view == null) - { + public Angle limitHeading(View view, Angle angle) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle == null) - { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.isNonContinous2DGlobe(view.getGlobe())) - { + if (this.isNonContinous2DGlobe(view.getGlobe())) { return angle; // ignore the heading limit on non-continuous 2D globes } return Angle.clamp(angle, this.minHeading, this.maxHeading); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Angle limitPitch(View view, Angle angle) - { - if (view == null) - { + public Angle limitPitch(View view, Angle angle) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle == null) - { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.is2DGlobe(view.getGlobe())) - { + if (this.is2DGlobe(view.getGlobe())) { return Angle.ZERO; // keep the view looking straight down on 2D globes } return Angle.clamp(angle, this.minPitch, this.maxPitch); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Angle limitRoll(View view, Angle angle) - { - if (view == null) - { + public Angle limitRoll(View view, Angle angle) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (angle == null) - { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -249,36 +251,31 @@ public Angle limitRoll(View view, Angle angle) return Angle.clamp(angle, this.minRoll, this.maxRoll); } - protected boolean is2DGlobe(Globe globe) - { + protected boolean is2DGlobe(Globe globe) { return globe instanceof Globe2D; } - protected boolean isNonContinous2DGlobe(Globe globe) - { + protected boolean isNonContinous2DGlobe(Globe globe) { return globe instanceof Globe2D && !((Globe2D) globe).isContinuous(); } /** * Clamp a heading angle to the range specified in a limit object. * - * @param angle angle to clamp to the allowed range. + * @param angle angle to clamp to the allowed range. * @param viewLimits defines the heading limits. * @return The clamped angle. * * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitHeading(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Angle)} instead. */ - public static Angle limitHeading(Angle angle, ViewPropertyLimits viewLimits) - { - if (angle == null) - { + public static Angle limitHeading(Angle angle, ViewPropertyLimits viewLimits) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewLimits == null) - { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -287,12 +284,9 @@ public static Angle limitHeading(Angle angle, ViewPropertyLimits viewLimits) Angle[] limits = viewLimits.getHeadingLimits(); Angle newAngle = angle; - if (angle.compareTo(limits[0]) < 0) - { + if (angle.compareTo(limits[0]) < 0) { newAngle = limits[0]; - } - else if (angle.compareTo(limits[1]) > 0) - { + } else if (angle.compareTo(limits[1]) > 0) { newAngle = limits[1]; } @@ -302,23 +296,20 @@ else if (angle.compareTo(limits[1]) > 0) /** * Clamp a pitch angle to the range specified in a limit object. * - * @param angle angle to clamp to the allowed range. + * @param angle angle to clamp to the allowed range. * @param viewLimits defines the pitch limits. * @return The clamped angle. * * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitPitch(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Angle)} instead. */ - public static Angle limitPitch(Angle angle, ViewPropertyLimits viewLimits) - { - if (angle == null) - { + public static Angle limitPitch(Angle angle, ViewPropertyLimits viewLimits) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewLimits == null) - { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -326,12 +317,9 @@ public static Angle limitPitch(Angle angle, ViewPropertyLimits viewLimits) Angle[] limits = viewLimits.getPitchLimits(); Angle newAngle = angle; - if (angle.compareTo(limits[0]) < 0) - { + if (angle.compareTo(limits[0]) < 0) { newAngle = limits[0]; - } - else if (angle.compareTo(limits[1]) > 0) - { + } else if (angle.compareTo(limits[1]) > 0) { newAngle = limits[1]; } @@ -341,23 +329,20 @@ else if (angle.compareTo(limits[1]) > 0) /** * Clamp a roll angle to the range specified in a limit object. * - * @param angle angle to clamp to the allowed range. + * @param angle angle to clamp to the allowed range. * @param viewLimits defines the roll limits. * @return The clamped angle. * * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitRoll(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Angle)} instead. */ - public static Angle limitRoll(Angle angle, ViewPropertyLimits viewLimits) - { - if (angle == null) - { + public static Angle limitRoll(Angle angle, ViewPropertyLimits viewLimits) { + if (angle == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewLimits == null) - { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -365,12 +350,9 @@ public static Angle limitRoll(Angle angle, ViewPropertyLimits viewLimits) Angle[] limits = viewLimits.getRollLimits(); Angle newAngle = angle; - if (angle.compareTo(limits[0]) < 0) - { + if (angle.compareTo(limits[0]) < 0) { newAngle = limits[0]; - } - else if (angle.compareTo(limits[1]) > 0) - { + } else if (angle.compareTo(limits[1]) > 0) { newAngle = limits[1]; } @@ -380,17 +362,15 @@ else if (angle.compareTo(limits[1]) > 0) /** * Clamp an eye elevation to the range specified in a limit object. * - * @param elevation elevation to clamp to the allowed range. + * @param elevation elevation to clamp to the allowed range. * @param viewLimits defines the eye elevation limits. * @return The clamped angle. * * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitEyePosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ - public static double limitEyeElevation(double elevation, ViewPropertyLimits viewLimits) - { - if (viewLimits == null) - { + public static double limitEyeElevation(double elevation, ViewPropertyLimits viewLimits) { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -398,12 +378,9 @@ public static double limitEyeElevation(double elevation, ViewPropertyLimits view double newElevation = elevation; double[] elevLimits = viewLimits.getEyeElevationLimits(); - if (elevation < elevLimits[0]) - { + if (elevation < elevLimits[0]) { newElevation = elevLimits[0]; - } - else if (elevation > elevLimits[1]) - { + } else if (elevation > elevLimits[1]) { newElevation = elevLimits[1]; } return (newElevation); @@ -412,24 +389,21 @@ else if (elevation > elevLimits[1]) /** * Clamp eye location angles to the range specified in a limit object. * - * @param latitude latitude angle to clamp to the allowed range. - * @param longitude longitude angle to clamp to the allowed range. + * @param latitude latitude angle to clamp to the allowed range. + * @param longitude longitude angle to clamp to the allowed range. * @param viewLimits defines the eye location limits. * @return The clamped angle. * * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitEyePosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ - public static LatLon limitEyePositionLocation(Angle latitude, Angle longitude, ViewPropertyLimits viewLimits) - { - if (latitude == null || longitude == null) - { + public static LatLon limitEyePositionLocation(Angle latitude, Angle longitude, ViewPropertyLimits viewLimits) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewLimits == null) - { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -439,21 +413,15 @@ public static LatLon limitEyePositionLocation(Angle latitude, Angle longitude, V Angle newLatitude = latitude; Angle newLongitude = longitude; - if (latitude.compareTo(limits.getMinLatitude()) < 0) - { + if (latitude.compareTo(limits.getMinLatitude()) < 0) { newLatitude = limits.getMinLatitude(); - } - else if (latitude.compareTo(limits.getMaxLatitude()) > 0) - { + } else if (latitude.compareTo(limits.getMaxLatitude()) > 0) { newLatitude = limits.getMaxLatitude(); } - if (longitude.compareTo(limits.getMinLongitude()) < 0) - { + if (longitude.compareTo(limits.getMinLongitude()) < 0) { newLongitude = limits.getMinLongitude(); - } - else if (longitude.compareTo(limits.getMaxLongitude()) > 0) - { + } else if (longitude.compareTo(limits.getMaxLongitude()) > 0) { newLongitude = limits.getMaxLongitude(); } @@ -463,9 +431,7 @@ else if (longitude.compareTo(limits.getMaxLongitude()) > 0) //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { rs.addStateValueAsSector(context, "eyeLocationLimits", this.eyeLocationLimits); rs.addStateValueAsDouble(context, "minEyeElevation", this.minEyeElevation); rs.addStateValueAsDouble(context, "maxEyeElevation", this.maxEyeElevation); @@ -475,49 +441,58 @@ public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObje rs.addStateValueAsDouble(context, "maxPitchDegrees", this.maxPitch.degrees); } - public void restoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + public void restoreState(RestorableSupport rs, RestorableSupport.StateObject context) { Sector sector = rs.getStateValueAsSector(context, "eyeLocationLimits"); - if (sector != null) + if (sector != null) { this.setEyeLocationLimits(sector); + } // Min and max center elevation. double[] minAndMaxValue = this.getEyeElevationLimits(); Double min = rs.getStateValueAsDouble(context, "minEyeElevation"); - if (min != null) + if (min != null) { minAndMaxValue[0] = min; + } Double max = rs.getStateValueAsDouble(context, "maxEyeElevation"); - if (max != null) + if (max != null) { minAndMaxValue[1] = max; + } - if (min != null || max != null) + if (min != null || max != null) { this.setEyeElevationLimits(minAndMaxValue[0], minAndMaxValue[1]); + } // Min and max heading angle. Angle[] minAndMaxAngle = this.getHeadingLimits(); min = rs.getStateValueAsDouble(context, "minHeadingDegrees"); - if (min != null) + if (min != null) { minAndMaxAngle[0] = Angle.fromDegrees(min); + } max = rs.getStateValueAsDouble(context, "maxHeadingDegrees"); - if (max != null) + if (max != null) { minAndMaxAngle[1] = Angle.fromDegrees(max); + } - if (min != null || max != null) + if (min != null || max != null) { this.setHeadingLimits(minAndMaxAngle[0], minAndMaxAngle[1]); + } // Min and max pitch angle. minAndMaxAngle = this.getPitchLimits(); min = rs.getStateValueAsDouble(context, "minPitchDegrees"); - if (min != null) + if (min != null) { minAndMaxAngle[0] = Angle.fromDegrees(min); + } max = rs.getStateValueAsDouble(context, "maxPitchDegrees"); - if (max != null) + if (max != null) { minAndMaxAngle[1] = Angle.fromDegrees(max); + } - if (min != null || max != null) + if (min != null || max != null) { this.setPitchLimits(minAndMaxAngle[0], minAndMaxAngle[1]); + } } } diff --git a/src/gov/nasa/worldwind/view/ViewElevationAnimator.java b/src/gov/nasa/worldwind/view/ViewElevationAnimator.java index 15b59cd860..3a32f1d99a 100644 --- a/src/gov/nasa/worldwind/view/ViewElevationAnimator.java +++ b/src/gov/nasa/worldwind/view/ViewElevationAnimator.java @@ -12,14 +12,14 @@ import gov.nasa.worldwind.util.*; /** - * An {@link gov.nasa.worldwind.animation.Animator} for elevation values. Calculates a mid-zoom value that - * gives the effect of flying up and them back down again. + * An {@link gov.nasa.worldwind.animation.Animator} for elevation values. Calculates a mid-zoom value that gives the + * effect of flying up and them back down again. * * @author jym * @version $Id: ViewElevationAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ViewElevationAnimator extends DoubleAnimator -{ +public class ViewElevationAnimator extends DoubleAnimator { + protected Globe globe; protected LatLon endLatLon; protected int altitudeMode; @@ -33,37 +33,32 @@ public class ViewElevationAnimator extends DoubleAnimator * re-calculated as the animation runs to ensure that the final elevation is based on the most accurate elevation * data available. * - * @param globe Globe used to evaluate altitude mode and determine if mid-zoom is necessary. May be null. - * @param beginZoom Beginning elevation. - * @param endZoom Ending elevation. - * @param beginLatLon Beginning location. - * @param endLatLon Ending location. - * @param altitudeMode Altitude mode of ending elevation ({@link WorldWind#CLAMP_TO_GROUND}, - * {@link WorldWind#RELATIVE_TO_GROUND}, or {@link WorldWind#ABSOLUTE}. Altitude mode - * is not used if {@code globe} is null. + * @param globe Globe used to evaluate altitude mode and determine if mid-zoom is necessary. May be null. + * @param beginZoom Beginning elevation. + * @param endZoom Ending elevation. + * @param beginLatLon Beginning location. + * @param endLatLon Ending location. + * @param altitudeMode Altitude mode of ending elevation ({@link WorldWind#CLAMP_TO_GROUND}, + * {@link WorldWind#RELATIVE_TO_GROUND}, or {@link WorldWind#ABSOLUTE}. Altitude mode is not used if {@code globe} + * is null. * @param propertyAccessor Accessor to set elevation. */ public ViewElevationAnimator(Globe globe, double beginZoom, double endZoom, LatLon beginLatLon, - LatLon endLatLon, int altitudeMode, PropertyAccessor.DoubleAccessor propertyAccessor) - { + LatLon endLatLon, int altitudeMode, PropertyAccessor.DoubleAccessor propertyAccessor) { super(null, beginZoom, endZoom, propertyAccessor); this.endLatLon = endLatLon; this.altitudeMode = altitudeMode; - if (globe == null) - { + if (globe == null) { useMidZoom = false; - } - else - { + } else { this.globe = globe; this.midZoom = computeMidZoom(globe, beginLatLon, endLatLon, beginZoom, endZoom); useMidZoom = useMidZoom(beginZoom, endZoom, midZoom); } - if (useMidZoom) - { + if (useMidZoom) { this.trueEndZoom = endZoom; this.end = this.midZoom; } @@ -71,21 +66,20 @@ public ViewElevationAnimator(Globe globe, double beginZoom, double endZoom, LatL /** * return the true position to end the elevation animation at. + * * @return the true end elevation position. */ - public double getTrueEndZoom() - { - return(trueEndZoom); + public double getTrueEndZoom() { + return (trueEndZoom); } /** - * determines whether this Animator is using midZoom. - * The mid-point zoom is an interpolated value between minimum(the lesser of beginZoom and endZoom, - * and maximum zoom (3* the radius of the globe). + * determines whether this Animator is using midZoom. The mid-point zoom is an interpolated value between + * minimum(the lesser of beginZoom and endZoom, and maximum zoom (3* the radius of the globe). + * * @return whether this Animator is using midZoom. */ - public boolean getUseMidZoom() - { + public boolean getUseMidZoom() { return useMidZoom; } @@ -95,43 +89,38 @@ public boolean getUseMidZoom() * @param end New end zoom. */ @Override - public void setEnd(Double end) - { - if (this.getUseMidZoom()) + public void setEnd(Double end) { + if (this.getUseMidZoom()) { this.trueEndZoom = end; - else + } else { this.end = end; + } } /** * Set the value of the field being animated based on the given interpolant. + * * @param interpolant A value between 0 and 1. */ - public void set(double interpolant) - { + public void set(double interpolant) { final int MAX_SMOOTHING = 1; final double ZOOM_START = 0.0; final double ZOOM_STOP = 1.0; - if (interpolant >= 1.0) + if (interpolant >= 1.0) { this.stop(); - double zoomInterpolant; + } + double zoomInterpolant; - if (this.useMidZoom) - { + if (this.useMidZoom) { double value; zoomInterpolant = this.zoomInterpolant(interpolant, ZOOM_START, ZOOM_STOP, MAX_SMOOTHING); - if (interpolant <= .5) - { + if (interpolant <= .5) { value = nextDouble(zoomInterpolant, this.begin, this.end); - } - else - { + } else { value = nextDouble(zoomInterpolant, this.end, this.trueEndZoom); } this.propertyAccessor.setDouble(value); - } - else - { + } else { zoomInterpolant = AnimationSupport.basicInterpolant(interpolant, ZOOM_START, ZOOM_STOP, MAX_SMOOTHING); super.set(zoomInterpolant); } @@ -139,20 +128,16 @@ public void set(double interpolant) } private double zoomInterpolant(double interpolant, double startInterpolant, double stopInterpolant, - int maxSmoothing) - { + int maxSmoothing) { // Map interpolant in to range [start, stop]. double normalizedInterpolant = AnimationSupport.interpolantNormalized( - interpolant, startInterpolant, stopInterpolant); + interpolant, startInterpolant, stopInterpolant); // During first half of iteration, zoom increases from begin to mid, // and decreases from mid to end during second half. - if (normalizedInterpolant <= 0.5) - { + if (normalizedInterpolant <= 0.5) { normalizedInterpolant = (normalizedInterpolant * 2.0); - } - else - { + } else { normalizedInterpolant = ((normalizedInterpolant - .5) * 2.0); } @@ -160,8 +145,7 @@ private double zoomInterpolant(double interpolant, double startInterpolant, doub } @Override - public Double nextDouble(double interpolant) - { + public Double nextDouble(double interpolant) { return this.nextDouble(interpolant, this.begin, this.end); } @@ -173,12 +157,11 @@ public Double nextDouble(double interpolant) * @param end the upper end of the interpolated range. * @return the interpolated value. */ - protected double nextDouble(double interpolant, double start, double end) - { - double elevation = AnimationSupport.mixDouble( - interpolant, - start, - end); + protected double nextDouble(double interpolant, double start, double end) { + double elevation = AnimationSupport.mixDouble( + interpolant, + start, + end); // Check the altitude mode. If the altitude mode depends on the surface elevation we will reevaluate the // end position altitude. When the animation starts we may not have accurate elevation data available for @@ -187,46 +170,40 @@ protected double nextDouble(double interpolant, double start, double end) double endElevation = 0.0; boolean overrideEndElevation = false; - if (this.globe != null && this.altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + if (this.globe != null && this.altitudeMode == WorldWind.CLAMP_TO_GROUND) { overrideEndElevation = true; endElevation = this.globe.getElevation(endLatLon.getLatitude(), endLatLon.getLongitude()); - } - else if (this.globe != null && this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (this.globe != null && this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) { overrideEndElevation = true; endElevation = this.globe.getElevation(endLatLon.getLatitude(), endLatLon.getLongitude()) + end; } - if (overrideEndElevation) - { + if (overrideEndElevation) { elevation = (1 - interpolant) * start + interpolant * endElevation; } return elevation; } - protected void setImpl(double interpolant) - { - Double newValue = this.nextDouble(interpolant); - if (newValue == null) - return; + protected void setImpl(double interpolant) { + Double newValue = this.nextDouble(interpolant); + if (newValue == null) { + return; + } - boolean success = this.propertyAccessor.setDouble(newValue); - if (!success) - { - this.flagLastStateInvalid(); - } - if (interpolant >= 1.0) - this.stop(); + boolean success = this.propertyAccessor.setDouble(newValue); + if (!success) { + this.flagLastStateInvalid(); + } + if (interpolant >= 1.0) { + this.stop(); + } } - protected static double computeMidZoom( - Globe globe, - LatLon beginLatLon, LatLon endLatLon, - double beginZoom, double endZoom) - { + Globe globe, + LatLon beginLatLon, LatLon endLatLon, + double beginZoom, double endZoom) { // Scale factor is angular distance over 180 degrees. Angle sphericalDistance = LatLon.greatCircleDistance(beginLatLon, endLatLon); double scaleFactor = AnimationSupport.angularRatio(sphericalDistance, Angle.POS180); @@ -238,16 +215,16 @@ protected static double computeMidZoom( } /** - * Determines if the animation will use mid-zoom. Mid-zoom animation is used if the difference between the beginZoom - * and endZoom values is less than the difference between the midZoom value and the larger of the beginZoom - * or endZoom values. + * Determines if the animation will use mid-zoom. Mid-zoom animation is used if the difference between the beginZoom + * and endZoom values is less than the difference between the midZoom value and the larger of the beginZoom or + * endZoom values. + * * @param beginZoom the begin zoom value * @param endZoom the end zoom value * @param midZoom the elevation at the middle of the animation * @return true if it is appropriate to use the midZoom value. */ - protected boolean useMidZoom(double beginZoom, double endZoom, double midZoom) - { + protected boolean useMidZoom(double beginZoom, double endZoom, double midZoom) { double a = Math.abs(endZoom - beginZoom); double b = Math.abs(midZoom - Math.max(beginZoom, endZoom)); return a < b; diff --git a/src/gov/nasa/worldwind/view/ViewPropertyAccessor.java b/src/gov/nasa/worldwind/view/ViewPropertyAccessor.java index 95f4bedb33..ce19017306 100644 --- a/src/gov/nasa/worldwind/view/ViewPropertyAccessor.java +++ b/src/gov/nasa/worldwind/view/ViewPropertyAccessor.java @@ -13,212 +13,185 @@ * @author jym * @version $Id: ViewPropertyAccessor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ViewPropertyAccessor -{ - public ViewPropertyAccessor() - { +public class ViewPropertyAccessor { + + public ViewPropertyAccessor() { } - public static PropertyAccessor.DoubleAccessor createElevationAccessor(View view) - { + public static PropertyAccessor.DoubleAccessor createElevationAccessor(View view) { return new ElevationAccessor(view); } - public static PropertyAccessor.AngleAccessor createHeadingAccessor(View view) - { + public static PropertyAccessor.AngleAccessor createHeadingAccessor(View view) { return new HeadingAccessor(view); } - public static PropertyAccessor.AngleAccessor createPitchAccessor(View view) - { + public static PropertyAccessor.AngleAccessor createPitchAccessor(View view) { return new PitchAccessor(view); } - public static PropertyAccessor.AngleAccessor createRollAccessor(View view) - { + public static PropertyAccessor.AngleAccessor createRollAccessor(View view) { return new RollAccessor(view); } - public static PropertyAccessor.PositionAccessor createEyePositionAccessor(View view) - { + public static PropertyAccessor.PositionAccessor createEyePositionAccessor(View view) { return new EyePositionAccessor(view); } - public static class HeadingAccessor implements PropertyAccessor.AngleAccessor - { + public static class HeadingAccessor implements PropertyAccessor.AngleAccessor { + protected View view; - HeadingAccessor(View view) - { + HeadingAccessor(View view) { this.view = view; } - public final Angle getAngle() - { - if (this.view == null) + public final Angle getAngle() { + if (this.view == null) { return null; + } return this.view.getHeading(); } - public final boolean setAngle(Angle value) - { + public final boolean setAngle(Angle value) { //noinspection SimplifiableIfStatement - if (this.view == null || value == null) + if (this.view == null || value == null) { return false; + } - try - { + try { this.view.setHeading(value); return true; - } - catch (Exception e) - { + } catch (Exception e) { return false; } } } - public static class PitchAccessor implements PropertyAccessor.AngleAccessor - { + public static class PitchAccessor implements PropertyAccessor.AngleAccessor { + protected View view; - PitchAccessor(View view) - { + PitchAccessor(View view) { this.view = view; } - public final Angle getAngle() - { - if (this.view == null) + public final Angle getAngle() { + if (this.view == null) { return null; + } return view.getPitch(); } - public final boolean setAngle(Angle value) - { + public final boolean setAngle(Angle value) { //noinspection SimplifiableIfStatement - if (this.view == null || value == null) + if (this.view == null || value == null) { return false; + } - try - { + try { this.view.setPitch(value); return true; - } - catch (Exception e) - { + } catch (Exception e) { return false; } } } - public static class RollAccessor implements PropertyAccessor.AngleAccessor - { + public static class RollAccessor implements PropertyAccessor.AngleAccessor { + protected View view; - RollAccessor(View view) - { + RollAccessor(View view) { this.view = view; } - public final Angle getAngle() - { - if (this.view == null) + public final Angle getAngle() { + if (this.view == null) { return null; + } return view.getRoll(); } - public final boolean setAngle(Angle value) - { + public final boolean setAngle(Angle value) { //noinspection SimplifiableIfStatement - if (this.view == null || value == null) + if (this.view == null || value == null) { return false; + } - try - { + try { this.view.setRoll(value); return true; - } - catch (Exception e) - { + } catch (Exception e) { return false; } } } public static class EyePositionAccessor implements - PropertyAccessor.PositionAccessor - { + PropertyAccessor.PositionAccessor { protected View view; - EyePositionAccessor(View view) - { + EyePositionAccessor(View view) { this.view = view; } - public Position getPosition() - { - if (this.view == null) + public Position getPosition() { + if (this.view == null) { return null; + } return this.view.getEyePosition(); } - public boolean setPosition(Position value) - { + public boolean setPosition(Position value) { //noinspection SimplifiableIfStatement - if (this.view == null || value == null) + if (this.view == null || value == null) { return false; + } - try - { + try { this.view.setEyePosition(value); return true; - } - catch (Exception e) - { + } catch (Exception e) { return false; } } } public static class ElevationAccessor implements - PropertyAccessor.DoubleAccessor - { + PropertyAccessor.DoubleAccessor { + protected View view; - ElevationAccessor(View view) - { + ElevationAccessor(View view) { this.view = view; } - public Double getDouble() - { - if (this.view == null) + public Double getDouble() { + if (this.view == null) { return null; + } return this.view.getEyePosition().getElevation(); } - public boolean setDouble(Double value) - { + public boolean setDouble(Double value) { //noinspection SimplifiableIfStatement - if (this.view == null || value == null) + if (this.view == null || value == null) { return false; + } - try - { + try { this.view.setEyePosition( - new Position(this.view.getCurrentEyePosition(), value)); + new Position(this.view.getCurrentEyePosition(), value)); return true; - } - catch (Exception e) - { + } catch (Exception e) { return false; } } diff --git a/src/gov/nasa/worldwind/view/ViewPropertyLimits.java b/src/gov/nasa/worldwind/view/ViewPropertyLimits.java index 86511281ed..120a8e9d07 100644 --- a/src/gov/nasa/worldwind/view/ViewPropertyLimits.java +++ b/src/gov/nasa/worldwind/view/ViewPropertyLimits.java @@ -15,8 +15,8 @@ * @author jym * @version $Id: ViewPropertyLimits.java 2253 2014-08-22 16:33:46Z dcollins $ */ -public interface ViewPropertyLimits -{ +public interface ViewPropertyLimits { + /** * Sets the Sector which will limit a view's eye latitude and longitude. * @@ -99,7 +99,9 @@ public interface ViewPropertyLimits */ void setRollLimits(Angle minAngle, Angle maxAngle); - /** Resets all property limits to their default values. */ + /** + * Resets all property limits to their default values. + */ void reset(); /** @@ -107,7 +109,7 @@ public interface ViewPropertyLimits * object. This method does not modify the specified view's properties, but may use the view as a context for * determining how to apply the limits. * - * @param view the view associated with the center position and the property limits. + * @param view the view associated with the center position and the property limits. * @param position position to clamp to the allowed range. * * @return The clamped position. @@ -120,7 +122,7 @@ public interface ViewPropertyLimits * Returns an angle clamped to the heading limits specified by this limit object. This method does not modify the * specified view's properties, but may use the view as a context for determining how to apply the limits. * - * @param view the view associated with the heading angle and the property limits. + * @param view the view associated with the heading angle and the property limits. * @param angle angle to clamp to the allowed range. * * @return The clamped angle. @@ -133,7 +135,7 @@ public interface ViewPropertyLimits * Returns an angle clamped to the pitch limits specified by this limit object. This method does not modify the * specified view's properties, but may use the view as a context for determining how to apply the limits. * - * @param view the view associated with the pitch angle and the property limits. + * @param view the view associated with the pitch angle and the property limits. * @param angle angle to clamp to the allowed range. * * @return The clamped angle. @@ -146,7 +148,7 @@ public interface ViewPropertyLimits * Returns an angle clamped to the roll limits specified by this limit object. This method does not modify the * specified view's properties, but may use the view as a context for determining how to apply the limits. * - * @param view the view associated with the roll angle and the property limits. + * @param view the view associated with the roll angle and the property limits. * @param angle angle to clamp to the allowed range. * * @return The clamped angle. diff --git a/src/gov/nasa/worldwind/view/ViewUtil.java b/src/gov/nasa/worldwind/view/ViewUtil.java index e98c38193e..d0c9c68a47 100644 --- a/src/gov/nasa/worldwind/view/ViewUtil.java +++ b/src/gov/nasa/worldwind/view/ViewUtil.java @@ -20,60 +20,51 @@ * @author jym * @version $Id: ViewUtil.java 1933 2014-04-14 22:54:19Z dcollins $ */ -public class ViewUtil -{ - public static class ViewState - { +public class ViewUtil { + + public static class ViewState { + protected Position position; protected Angle heading; protected Angle pitch; protected Angle roll; - public ViewState(Position position, Angle heading, Angle pitch, Angle roll) - { + public ViewState(Position position, Angle heading, Angle pitch, Angle roll) { this.position = position; this.heading = heading; this.pitch = pitch; this.roll = roll; } - public Position getPosition() - { + public Position getPosition() { return (position); } - public void setPosition(Position position) - { + public void setPosition(Position position) { this.position = position; } - public Angle getRoll() - { + public Angle getRoll() { return (roll); } - public void setRoll(Angle roll) - { + public void setRoll(Angle roll) { this.roll = roll; } - public Angle getPitch() - { + public Angle getPitch() { return (pitch); } - public void setPitch(Angle pitch) - { + public void setPitch(Angle pitch) { this.pitch = pitch; } - public Angle getHeading() - { + public Angle getHeading() { return (heading); } - public void setHeading(Angle heading) - { + public void setHeading(Angle heading) { this.heading = heading; } } @@ -81,16 +72,14 @@ public void setHeading(Angle heading) /** * Create an animator to animate heading. * - * @param view View to animate + * @param view View to animate * @param begin starting heading - * @param end final heading + * @param end final heading * * @return An Animator to animate heading. */ - public static AngleAnimator createHeadingAnimator(View view, Angle begin, Angle end) - { - if (begin == null || end == null) - { + public static AngleAnimator createHeadingAnimator(View view, Angle begin, Angle end) { + if (begin == null || end == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -99,26 +88,24 @@ public static AngleAnimator createHeadingAnimator(View view, Angle begin, Angle final long MIN_LENGTH_MILLIS = 500; final long MAX_LENGTH_MILLIS = 3000; long lengthMillis = AnimationSupport.getScaledTimeMillisecs( - begin, end, Angle.POS180, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); + begin, end, Angle.POS180, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); return new AngleAnimator(new ScheduledInterpolator(lengthMillis), - begin, end, new ViewPropertyAccessor.HeadingAccessor(view)); + begin, end, new ViewPropertyAccessor.HeadingAccessor(view)); } /** * Create an animator to animate pitch. * - * @param view View to animate + * @param view View to animate * @param begin starting pitch - * @param end final pitch + * @param end final pitch * * @return An Animator to animate pitch. */ - public static AngleAnimator createPitchAnimator(View view, Angle begin, Angle end) - { - if (begin == null || end == null) - { + public static AngleAnimator createPitchAnimator(View view, Angle begin, Angle end) { + if (begin == null || end == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -127,26 +114,24 @@ public static AngleAnimator createPitchAnimator(View view, Angle begin, Angle en final long MIN_LENGTH_MILLIS = 500; final long MAX_LENGTH_MILLIS = 3000; long lengthMillis = AnimationSupport.getScaledTimeMillisecs( - begin, end, Angle.POS180, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); + begin, end, Angle.POS180, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); return new AngleAnimator(new ScheduledInterpolator(lengthMillis), - begin, end, new ViewPropertyAccessor.PitchAccessor(view)); + begin, end, new ViewPropertyAccessor.PitchAccessor(view)); } /** * Create an animator to animate roll. * - * @param view View to animate + * @param view View to animate * @param begin starting roll - * @param end final roll + * @param end final roll * * @return An Animator to animate roll. */ - public static AngleAnimator createRollAnimator(View view, Angle begin, Angle end) - { - if (begin == null || end == null) - { + public static AngleAnimator createRollAnimator(View view, Angle begin, Angle end) { + if (begin == null || end == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -155,32 +140,30 @@ public static AngleAnimator createRollAnimator(View view, Angle begin, Angle end final long MIN_LENGTH_MILLIS = 500; final long MAX_LENGTH_MILLIS = 3000; long lengthMillis = AnimationSupport.getScaledTimeMillisecs( - begin, end, Angle.POS180, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); + begin, end, Angle.POS180, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); return new AngleAnimator(new ScheduledInterpolator(lengthMillis), - begin, end, new ViewPropertyAccessor.RollAccessor(view)); + begin, end, new ViewPropertyAccessor.RollAccessor(view)); } /** * Create an animator to animate heading, pitch, and roll. * - * @param view View to animate + * @param view View to animate * @param beginHeading staring heading - * @param endHeading final heading - * @param beginPitch starting pitch - * @param endPitch final pitch - * @param beginRoll starting roll - * @param endRoll final roll + * @param endHeading final heading + * @param beginPitch starting pitch + * @param endPitch final pitch + * @param beginRoll starting roll + * @param endRoll final roll * * @return A CompoundAnimator to animate heading, pitch, and roll. */ public static CompoundAnimator createHeadingPitchRollAnimator(View view, Angle beginHeading, Angle endHeading, - Angle beginPitch, Angle endPitch, Angle beginRoll, Angle endRoll) - { + Angle beginPitch, Angle endPitch, Angle beginRoll, Angle endRoll) { if (beginHeading == null || endHeading == null || beginPitch == null || endPitch == null || beginRoll == null - || endRoll == null) - { + || endRoll == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -189,14 +172,14 @@ public static CompoundAnimator createHeadingPitchRollAnimator(View view, Angle b final long MIN_LENGTH_MILLIS = 500; final long MAX_LENGTH_MILLIS = 3000; long headingLengthMillis = AnimationSupport.getScaledTimeMillisecs( - beginHeading, endHeading, Angle.POS180, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); + beginHeading, endHeading, Angle.POS180, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); long pitchLengthMillis = AnimationSupport.getScaledTimeMillisecs( - beginPitch, endPitch, Angle.POS90, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS / 2L); + beginPitch, endPitch, Angle.POS90, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS / 2L); long rollLengthMillis = AnimationSupport.getScaledTimeMillisecs( - beginRoll, endRoll, Angle.POS90, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS / 2L); + beginRoll, endRoll, Angle.POS90, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS / 2L); long lengthMillis = headingLengthMillis + pitchLengthMillis + rollLengthMillis; AngleAnimator headingAnimator = createHeadingAnimator(view, beginHeading, endHeading); @@ -204,35 +187,31 @@ public static CompoundAnimator createHeadingPitchRollAnimator(View view, Angle b AngleAnimator rollAnimator = createRollAnimator(view, beginRoll, endRoll); CompoundAnimator headingPitchAnimator = new CompoundAnimator(new ScheduledInterpolator(lengthMillis), - headingAnimator, pitchAnimator, rollAnimator); + headingAnimator, pitchAnimator, rollAnimator); return (headingPitchAnimator); } public static PositionAnimator createEyePositionAnimator( - View view, long timeToMove, Position begin, Position end) - { + View view, long timeToMove, Position begin, Position end) { return new PositionAnimator(new ScheduledInterpolator(timeToMove), - begin, end, ViewPropertyAccessor.createEyePositionAccessor(view)); + begin, end, ViewPropertyAccessor.createEyePositionAccessor(view)); } - public static Point subtract(Point a, Point b) - { - if (a == null || b == null) + public static Point subtract(Point a, Point b) { + if (a == null || b == null) { return null; + } return new Point((int) (a.getX() - b.getX()), (int) (a.getY() - b.getY())); } - public static Matrix computeTransformMatrix(Globe globe, Position position, Angle heading, Angle pitch, Angle roll) - { - if (heading == null) - { + public static Matrix computeTransformMatrix(Globe globe, Position position, Angle heading, Angle pitch, Angle roll) { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pitch == null) - { + if (pitch == null) { String message = Logging.getMessage("nullValue.PitchIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -249,16 +228,13 @@ public static Matrix computeTransformMatrix(Globe globe, Position position, Angl return transform; } - public static Matrix computePositionTransform(Globe globe, Position center) - { - if (globe == null) - { + public static Matrix computePositionTransform(Globe globe, Position center) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -285,28 +261,23 @@ public static Matrix computePositionTransform(Globe globe, Position center) return Matrix.fromViewLookAt(eyePoint, lookAtPoint, north); } - public static Matrix computeModelViewMatrix(Globe globe, Vec4 eyePoint, Vec4 centerPoint, Vec4 up) - { - if (globe == null) - { + public static Matrix computeModelViewMatrix(Globe globe, Vec4 eyePoint, Vec4 centerPoint, Vec4 up) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (eyePoint == null) - { + if (eyePoint == null) { String message = "nullValue.EyePointIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (centerPoint == null) - { + if (centerPoint == null) { String message = "nullValue.CenterPointIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (up == null) - { + if (up == null) { String message = "nullValue.UpIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -316,52 +287,43 @@ public static Matrix computeModelViewMatrix(Globe globe, Vec4 eyePoint, Vec4 cen return (modelview); } - public static Vec4 getUpVector(Globe globe, Vec4 lookAtPoint) - { + public static Vec4 getUpVector(Globe globe, Vec4 lookAtPoint) { return globe.computeSurfaceNormalAtPoint(lookAtPoint); } - public static ViewState computeViewState(Globe globe, Vec4 eyePoint, Vec4 centerPoint, Vec4 up) - { - if (globe == null) - { + public static ViewState computeViewState(Globe globe, Vec4 eyePoint, Vec4 centerPoint, Vec4 up) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (eyePoint == null) - { + if (eyePoint == null) { String message = "nullValue.EyePointIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (centerPoint == null) - { + if (centerPoint == null) { String message = "nullValue.CenterPointIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (up == null) - { + if (up == null) { up = ViewUtil.getUpVector(globe, centerPoint); } Matrix modelview = Matrix.fromViewLookAt(eyePoint, centerPoint, up); return ViewUtil.computeModelCoordinates(globe, modelview, centerPoint, - eyePoint); + eyePoint); } public static ViewState computeModelCoordinates(Globe globe, Matrix modelTransform, Vec4 centerPoint, - Vec4 eyePoint) - { - if (globe == null) - { + Vec4 eyePoint) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (modelTransform == null) - { + if (modelTransform == null) { String message = "nullValue.ModelTransformIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -372,8 +334,7 @@ public static ViewState computeModelCoordinates(Globe globe, Matrix modelTransfo // Compute the center position transform. Matrix centerTransform = ViewUtil.computePositionTransform(globe, centerPos); Matrix centerTransformInv = centerTransform.getInverse(); - if (centerTransformInv == null) - { + if (centerTransformInv == null) { String message = Logging.getMessage("generic.NoninvertibleMatrix"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -384,16 +345,15 @@ public static ViewState computeModelCoordinates(Globe globe, Matrix modelTransfo // Extract the heading, pitch, and zoom values from the transform. Angle heading = ViewUtil.computeHeading(hpzTransform); Angle pitch = ViewUtil.computePitch(hpzTransform); - if (heading == null || pitch == null) + if (heading == null || pitch == null) { return null; + } Position viewPosition = globe.computePositionFromPoint(eyePoint); return new ViewState(viewPosition, heading, pitch, Angle.ZERO); } - public static Angle computeHeading(Matrix headingPitchZoomTransform) - { - if (headingPitchZoomTransform == null) - { + public static Angle computeHeading(Matrix headingPitchZoomTransform) { + if (headingPitchZoomTransform == null) { String message = "nullValue.HeadingPitchZoomTransformTransformIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -402,25 +362,22 @@ public static Angle computeHeading(Matrix headingPitchZoomTransform) return headingPitchZoomTransform.getRotationZ(); } - public static Angle computePitch(Matrix transform) - { - if (transform == null) - { + public static Angle computePitch(Matrix transform) { + if (transform == null) { String message = "nullValue.HeadingPitchZoomTransformTransformIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } Angle a = transform.getRotationX(); - if (a != null) + if (a != null) { a = a.multiply(-1.0); + } return a; } - public static Angle computeRoll(Matrix transform) - { - if (transform == null) - { + public static Angle computeRoll(Matrix transform) { + if (transform == null) { String message = "nullValue.HeadingPitchZoomTransformTransformIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -429,10 +386,8 @@ public static Angle computeRoll(Matrix transform) return transform.getRotationY(); } - public static Position computePosition(Globe globe, Matrix transform) - { - if (transform == null) - { + public static Position computePosition(Globe globe, Matrix transform) { + if (transform == null) { String message = "nullValue.HeadingPitchZoomTransformTransformIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -443,37 +398,32 @@ public static Position computePosition(Globe globe, Matrix transform) return p != null ? p : Position.ZERO; } - public static boolean validateViewState(ViewState viewState) - { + public static boolean validateViewState(ViewState viewState) { return (viewState != null - && viewState.position != null - && viewState.position.getLatitude().degrees >= -90 - && viewState.position.getLatitude().degrees <= 90 - && viewState.heading != null - && viewState.pitch != null - && viewState.pitch.degrees >= 0 - && viewState.pitch.degrees <= 90); + && viewState.position != null + && viewState.position.getLatitude().degrees >= -90 + && viewState.position.getLatitude().degrees <= 90 + && viewState.heading != null + && viewState.pitch != null + && viewState.pitch.degrees >= 0 + && viewState.pitch.degrees <= 90); } - public static Position normalizedEyePosition(Position unnormalizedPosition) - { - if (unnormalizedPosition == null) - { + public static Position normalizedEyePosition(Position unnormalizedPosition) { + if (unnormalizedPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new Position( - Angle.normalizedLatitude(unnormalizedPosition.getLatitude()), - Angle.normalizedLongitude(unnormalizedPosition.getLongitude()), - unnormalizedPosition.getElevation()); + Angle.normalizedLatitude(unnormalizedPosition.getLatitude()), + Angle.normalizedLongitude(unnormalizedPosition.getLongitude()), + unnormalizedPosition.getElevation()); } - public static Angle normalizedHeading(Angle unnormalizedHeading) - { - if (unnormalizedHeading == null) - { + public static Angle normalizedHeading(Angle unnormalizedHeading) { + if (unnormalizedHeading == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -484,10 +434,8 @@ public static Angle normalizedHeading(Angle unnormalizedHeading) return Angle.fromDegrees(heading > 180 ? heading - 360 : (heading < -180 ? 360 + heading : heading)); } - public static Angle normalizedPitch(Angle unnormalizedPitch) - { - if (unnormalizedPitch == null) - { + public static Angle normalizedPitch(Angle unnormalizedPitch) { + if (unnormalizedPitch == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -499,10 +447,8 @@ public static Angle normalizedPitch(Angle unnormalizedPitch) return Angle.fromDegrees(pitch > 180 ? pitch - 360 : (pitch < -180 ? 360 + pitch : pitch)); } - public static Angle normalizedRoll(Angle unnormalizedRoll) - { - if (unnormalizedRoll == null) - { + public static Angle normalizedRoll(Angle unnormalizedRoll) { + if (unnormalizedRoll == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -514,16 +460,13 @@ public static Angle normalizedRoll(Angle unnormalizedRoll) } public static Line computeRayFromScreenPoint(View view, double x, double y, - Matrix modelview, Matrix projection, java.awt.Rectangle viewport) - { - if (modelview == null || projection == null) - { + Matrix modelview, Matrix projection, java.awt.Rectangle viewport) { + if (modelview == null || projection == null) { String message = Logging.getMessage("nullValue.MatrixIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewport == null) - { + if (viewport == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -535,34 +478,33 @@ public static Line computeRayFromScreenPoint(View view, double x, double y, // section 20.010 "How can I know which primitive a user has selected with the mouse?" // // http://www.opengl.org/resources/faq/technical/selection.htm#sele0010 - Matrix modelViewInv = modelview.getInverse(); - if (modelViewInv == null) + if (modelViewInv == null) { return null; + } Vec4 eye = Vec4.UNIT_W.transformBy4(modelViewInv); - if (eye == null) + if (eye == null) { return null; + } double yInGLCoords = viewport.height - y - 1; Vec4 a = view.unProject(new Vec4(x, yInGLCoords, 0, 0)); Vec4 b = view.unProject(new Vec4(x, yInGLCoords, 1, 0)); - if (a == null || b == null) + if (a == null || b == null) { return null; + } return new Line(eye, b.subtract3(a).normalize3()); } - public static double computePixelSizeAtDistance(double distance, Angle fieldOfView, java.awt.Rectangle viewport) - { - if (fieldOfView == null) - { + public static double computePixelSizeAtDistance(double distance, Angle fieldOfView, java.awt.Rectangle viewport) { + if (fieldOfView == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewport == null) - { + if (viewport == null) { String message = Logging.getMessage("nullValue.RectangleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -575,17 +517,16 @@ public static double computePixelSizeAtDistance(double distance, Angle fieldOfVi return Math.abs(distance) * pixelSizeScale; } - public static double computeHorizonDistance(Globe globe, double elevation) - { - if (globe == null) - { + public static double computeHorizonDistance(Globe globe, double elevation) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (elevation <= 0) + if (elevation <= 0) { return 0; + } double radius = globe.getMaximumRadius(); return Math.sqrt(elevation * (2 * radius + elevation)); @@ -596,30 +537,26 @@ public static double computeHorizonDistance(Globe globe, double elevation) * dimensions. * * @param horizontalFieldOfView the angle between the view frustum's left and right clipping planes. - * @param viewport the viewport dimensions, in window coordinates (screen pixels). + * @param viewport the viewport dimensions, in window coordinates (screen pixels). * * @return the angle between the view frustum's bottom and top clipping planes. * * @throws IllegalArgumentException if the horitontal-field-of-view is null, or if the viewport rectangle is null. */ - public static Angle computeVerticalFieldOfView(Angle horizontalFieldOfView, java.awt.Rectangle viewport) - { - if (horizontalFieldOfView == null) - { + public static Angle computeVerticalFieldOfView(Angle horizontalFieldOfView, java.awt.Rectangle viewport) { + if (horizontalFieldOfView == null) { String message = Logging.getMessage("nullValue.FOVIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewport == null) - { + if (viewport == null) { String message = Logging.getMessage("nullValue.ViewportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Taken form "Mathematics for 3D Game Programming and Computer Graphics", page 114. - double aspectRatio = viewport.getHeight() / viewport.getWidth(); double distanceToNearPlane = 1d / horizontalFieldOfView.tanHalfAngle(); double verticalFieldOfViewRadians = 2d * Math.atan(aspectRatio / distanceToNearPlane); @@ -627,23 +564,19 @@ public static Angle computeVerticalFieldOfView(Angle horizontalFieldOfView, java return Angle.fromRadians(verticalFieldOfViewRadians); } - public static double computeElevationAboveSurface(DrawContext dc, Position position) - { - if (dc == null) - { + public static double computeElevationAboveSurface(DrawContext dc, Position position) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Globe globe = dc.getGlobe(); - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -652,13 +585,15 @@ public static double computeElevationAboveSurface(DrawContext dc, Position posit Position surfacePosition = null; // Look for the surface geometry point at 'position'. Vec4 pointOnGlobe = dc.getPointOnTerrain(position.getLatitude(), position.getLongitude()); - if (pointOnGlobe != null) + if (pointOnGlobe != null) { surfacePosition = globe.computePositionFromPoint(pointOnGlobe); + } // Fallback to using globe elevation values. - if (surfacePosition == null) + if (surfacePosition == null) { surfacePosition = new Position( - position, - globe.getElevation(position.getLatitude(), position.getLongitude()) * dc.getVerticalExaggeration()); + position, + globe.getElevation(position.getLatitude(), position.getLongitude()) * dc.getVerticalExaggeration()); + } return position.getElevation() - surfacePosition.getElevation(); } @@ -668,24 +603,21 @@ public static double computeElevationAboveSurface(DrawContext dc, Position posit * distance from the eye point. The given distance should specify the smallest distance between the eye and the * object being viewed, but may be an approximation if an exact clip distance is not required. * - * @param fieldOfView The viewport rectangle, in OpenGL screen coordinates. + * @param fieldOfView The viewport rectangle, in OpenGL screen coordinates. * @param distanceToObject The distance from the perspective eye point to the nearest object, in model coordinates. * * @return The maximum near clip distance, in model coordinates. * * @throws IllegalArgumentException if the field of view is null, or if the distance is negative. */ - public static double computePerspectiveNearDistance(Angle fieldOfView, double distanceToObject) - { - if (fieldOfView == null) - { + public static double computePerspectiveNearDistance(Angle fieldOfView, double distanceToObject) { + if (fieldOfView == null) { String msg = Logging.getMessage("nullValue.FOVIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (distanceToObject < 0) - { + if (distanceToObject < 0) { String msg = Logging.getMessage("generic.DistanceLessThanZero"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -699,41 +631,36 @@ public static double computePerspectiveNearDistance(Angle fieldOfView, double di * Computes the near clip distance that corresponds to a specified far clip distance and a resolution at the far * clip distance. This returns zero if either the distance or the resolution are zero. * - * @param farDistance The far clip distance, in model coordinates. + * @param farDistance The far clip distance, in model coordinates. * @param farResolution The depth resolution at the far clip plane, in model coordinates. - * @param depthBits The number of bitplanes in the depth buffer. This is typically 16, 24, or 32 for OpenGL - * depth buffers. + * @param depthBits The number of bitplanes in the depth buffer. This is typically 16, 24, or 32 for OpenGL depth + * buffers. * * @return The near clip distance, in model coordinates. * * @throws IllegalArgumentException if either the distance or the resolution are negative, or if the depthBits is - * less than one. + * less than one. */ - public static double computePerspectiveNearDistance(double farDistance, double farResolution, int depthBits) - { - if (farDistance < 0) - { + public static double computePerspectiveNearDistance(double farDistance, double farResolution, int depthBits) { + if (farDistance < 0) { String msg = Logging.getMessage("generic.DistanceLessThanZero"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (farResolution < 0) - { + if (farResolution < 0) { String msg = Logging.getMessage("generic.ResolutionLessThanZero"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (depthBits < 1) - { + if (depthBits < 1) { String msg = Logging.getMessage("generic.DepthBitsLessThanOne"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (farDistance == 0 || farResolution == 0) - { + if (farDistance == 0 || farResolution == 0) { return 0; } @@ -749,40 +676,35 @@ public static double computePerspectiveNearDistance(double farDistance, double f * projection matrix, and viewport cannot produce a transformation. * * @param modelPoint the point in model coordinates to transform into window coordinates. - * @param modelview the modelview matrix. + * @param modelview the modelview matrix. * @param projection the projection matrix. - * @param viewport the viewport rectangle. + * @param viewport the viewport rectangle. * * @return the point in window coordinates, or null if the point cannot be transformed. * * @throws IllegalArgumentException if any of the model point, modelview matrix, projection matrix, or viewport - * rectangle are null. + * rectangle are null. */ - public static Vec4 project(Vec4 modelPoint, Matrix modelview, Matrix projection, java.awt.Rectangle viewport) - { - if (modelPoint == null) - { + public static Vec4 project(Vec4 modelPoint, Matrix modelview, Matrix projection, java.awt.Rectangle viewport) { + if (modelPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (modelview == null) - { + if (modelview == null) { String message = Logging.getMessage("nullValue.ModelViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (projection == null) - { + if (projection == null) { String message = Logging.getMessage("nullValue.ProjectionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewport == null) - { + if (viewport == null) { String message = Logging.getMessage("nullValue.ViewportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -796,16 +718,15 @@ public static Vec4 project(Vec4 modelPoint, Matrix modelview, Matrix projection, modelview.toArray(modelviewArray, 0, false); projection.toArray(projectionArray, 0, false); // GLU expects the viewport as a four-component array. - int[] viewportArray = new int[] {viewport.x, viewport.y, viewport.width, viewport.height}; + int[] viewportArray = new int[]{viewport.x, viewport.y, viewport.width, viewport.height}; double[] result = new double[3]; if (!glu.gluProject( - modelPoint.x, modelPoint.y, modelPoint.z, - modelviewArray, 0, - projectionArray, 0, - viewportArray, 0, - result, 0)) - { + modelPoint.x, modelPoint.y, modelPoint.z, + modelviewArray, 0, + projectionArray, 0, + viewportArray, 0, + result, 0)) { return null; } @@ -819,40 +740,35 @@ public static Vec4 project(Vec4 modelPoint, Matrix modelview, Matrix projection, * viewport cannot produce a transformation. * * @param windowPoint the point in screen coordinates to transform into model coordinates. - * @param modelview the modelview matrix. - * @param projection the projection matrix. - * @param viewport the viewport rectangle. + * @param modelview the modelview matrix. + * @param projection the projection matrix. + * @param viewport the viewport rectangle. * * @return the point in model coordinates, or null if the point cannot be transformed. * * @throws IllegalArgumentException if any of the model point, modelview matrix, projection matrix, or viewport - * rectangle are null. + * rectangle are null. */ - public static Vec4 unProject(Vec4 windowPoint, Matrix modelview, Matrix projection, java.awt.Rectangle viewport) - { - if (windowPoint == null) - { + public static Vec4 unProject(Vec4 windowPoint, Matrix modelview, Matrix projection, java.awt.Rectangle viewport) { + if (windowPoint == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (modelview == null) - { + if (modelview == null) { String message = Logging.getMessage("nullValue.ModelViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (projection == null) - { + if (projection == null) { String message = Logging.getMessage("nullValue.ProjectionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewport == null) - { + if (viewport == null) { String message = Logging.getMessage("nullValue.ViewportIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -864,17 +780,16 @@ public static Vec4 unProject(Vec4 windowPoint, Matrix modelview, Matrix projecti double[] modelviewArray = modelview.toArray(new double[16], 0, false); double[] projectionArray = projection.toArray(new double[16], 0, false); // GLU expects the viewport as a four-component array. - int[] viewportArray = new int[] {viewport.x, viewport.y, viewport.width, viewport.height}; + int[] viewportArray = new int[]{viewport.x, viewport.y, viewport.width, viewport.height}; double[] result = new double[3]; if (!glu.gluUnProject( - windowPoint.x, windowPoint.y, windowPoint.z, - modelviewArray, 0, - projectionArray, 0, - viewportArray, 0, - result, 0)) - { + windowPoint.x, windowPoint.y, windowPoint.z, + modelviewArray, 0, + projectionArray, 0, + viewportArray, 0, + result, 0)) { return null; } diff --git a/src/gov/nasa/worldwind/view/firstperson/BasicFlyView.java b/src/gov/nasa/worldwind/view/firstperson/BasicFlyView.java index c28f64bb21..9b8cfccab8 100644 --- a/src/gov/nasa/worldwind/view/firstperson/BasicFlyView.java +++ b/src/gov/nasa/worldwind/view/firstperson/BasicFlyView.java @@ -19,23 +19,22 @@ * applications (such as flight simulation). *

          * Note that the pitch angle is defined as normal to the ground plane, not parallel as in most body axis - * representations. This is to be consistent with the definition of pitch within WorldWind. Applications will need to + * representations. This is to be consistent with the definition of pitch within WorldWind. Applications will need to * correct for pitch values by adding 90 degrees when commanding pitch (i.e. to get a horizontal view, enter 90 degrees - * pitch. To get straight down, enter 0 degrees). + * pitch. To get straight down, enter 0 degrees). * * @author jym * @author M. Duquette * @version $Id: BasicFlyView.java 1933 2014-04-14 22:54:19Z dcollins $ */ -public class BasicFlyView extends BasicView -{ +public class BasicFlyView extends BasicView { + protected final static double DEFAULT_MIN_ELEVATION = 0; protected final static double DEFAULT_MAX_ELEVATION = 4000000; protected final static Angle DEFAULT_MIN_PITCH = Angle.ZERO; protected final static Angle DEFAULT_MAX_PITCH = Angle.fromDegrees(180); - public BasicFlyView() - { + public BasicFlyView() { this.viewInputHandler = new FlyViewInputHandler(); this.viewLimits = new FlyViewLimits(); @@ -45,65 +44,61 @@ public BasicFlyView() loadConfigurationValues(); } - protected void loadConfigurationValues() - { + protected void loadConfigurationValues() { Double initLat = Configuration.getDoubleValue(AVKey.INITIAL_LATITUDE); Double initLon = Configuration.getDoubleValue(AVKey.INITIAL_LONGITUDE); double initElev = 50000.0; // Set center latitude and longitude. Do not change center elevation. Double initAltitude = Configuration.getDoubleValue(AVKey.INITIAL_ALTITUDE); - if (initAltitude != null) + if (initAltitude != null) { initElev = initAltitude; - if (initLat != null && initLon != null) - { + } + if (initLat != null && initLon != null) { initElev = ((FlyViewLimits) viewLimits).limitEyeElevation(initElev); setEyePosition(Position.fromDegrees(initLat, initLon, initElev)); - } - - // Set only center latitude. Do not change center longitude or center elevation. - else if (initLat != null) + } // Set only center latitude. Do not change center longitude or center elevation. + else if (initLat != null) { setEyePosition(Position.fromDegrees(initLat, this.eyePosition.getLongitude().degrees, initElev)); - // Set only center longitude. Do not center latitude or center elevation. - else if (initLon != null) + } // Set only center longitude. Do not center latitude or center elevation. + else if (initLon != null) { setEyePosition(Position.fromDegrees(this.eyePosition.getLatitude().degrees, initLon, initElev)); + } Double initHeading = Configuration.getDoubleValue(AVKey.INITIAL_HEADING); - if (initHeading != null) + if (initHeading != null) { setHeading(Angle.fromDegrees(initHeading)); + } Double initPitch = Configuration.getDoubleValue(AVKey.INITIAL_PITCH); - if (initPitch != null) + if (initPitch != null) { setPitch(Angle.fromDegrees(initPitch)); + } Double initFov = Configuration.getDoubleValue(AVKey.FOV); - if (initFov != null) + if (initFov != null) { setFieldOfView(Angle.fromDegrees(initFov)); + } } @Override - public void setEyePosition(Position eyePosition) - { - if (eyePosition == null) - { + public void setEyePosition(Position eyePosition) { + if (eyePosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.getGlobe() != null) - { + if (this.getGlobe() != null) { double elevation = ((FlyViewLimits) this.viewLimits).limitEyeElevation( - eyePosition, this.getGlobe()); + eyePosition, this.getGlobe()); LatLon location = BasicViewPropertyLimits.limitEyePositionLocation( - eyePosition.getLatitude(), eyePosition.getLongitude(), this.viewLimits); + eyePosition.getLatitude(), eyePosition.getLongitude(), this.viewLimits); this.eyePosition = new Position(location, elevation); - } - else - { + } else { LatLon location = BasicViewPropertyLimits.limitEyePositionLocation( - eyePosition.getLatitude(), eyePosition.getLongitude(), this.viewLimits); + eyePosition.getLatitude(), eyePosition.getLongitude(), this.viewLimits); this.eyePosition = new Position(location, eyePosition.getElevation()); this.eyePosition = eyePosition; } @@ -111,16 +106,13 @@ public void setEyePosition(Position eyePosition) this.updateModelViewStateID(); } - public Matrix getModelViewMatrix(Position eyePosition, Position centerPosition) - { - if (eyePosition == null || centerPosition == null) - { + public Matrix getModelViewMatrix(Position eyePosition, Position centerPosition) { + if (eyePosition == null || centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.globe == null) - { + if (this.globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -128,8 +120,7 @@ public Matrix getModelViewMatrix(Position eyePosition, Position centerPosition) Vec4 newEyePoint = this.globe.computePointFromPosition(eyePosition); Vec4 newCenterPoint = this.globe.computePointFromPosition(centerPosition); - if (newEyePoint == null || newCenterPoint == null) - { + if (newEyePoint == null || newCenterPoint == null) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -140,22 +131,18 @@ public Matrix getModelViewMatrix(Position eyePosition, Position centerPosition) Vec4 up = this.globe.computeSurfaceNormalAtPoint(newCenterPoint); // Otherwise, estimate the up direction by using the *current* heading with the new center position. Vec4 forward = newCenterPoint.subtract3(newEyePoint).normalize3(); - if (forward.cross3(up).getLength3() < 0.001) - { + if (forward.cross3(up).getLength3() < 0.001) { Matrix modelview = ViewUtil.computeTransformMatrix(this.globe, eyePosition, this.heading, Angle.ZERO, - Angle.ZERO); - if (modelview != null) - { + Angle.ZERO); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { up = Vec4.UNIT_Y.transformBy4(modelviewInv); } } } - if (up == null) - { + if (up == null) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -166,17 +153,14 @@ public Matrix getModelViewMatrix(Position eyePosition, Position centerPosition) return (modelViewMatrix); } - public ViewUtil.ViewState getViewState(Position eyePosition, Position centerPosition) - { - if (eyePosition == null || centerPosition == null) - { + public ViewUtil.ViewState getViewState(Position eyePosition, Position centerPosition) { + if (eyePosition == null || centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.globe == null) - { + if (this.globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -184,8 +168,7 @@ public ViewUtil.ViewState getViewState(Position eyePosition, Position centerPosi Vec4 newEyePoint = this.globe.computePointFromPosition(eyePosition); Vec4 newCenterPoint = this.globe.computePointFromPosition(centerPosition); - if (newEyePoint == null || newCenterPoint == null) - { + if (newEyePoint == null || newCenterPoint == null) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -197,20 +180,18 @@ public ViewUtil.ViewState getViewState(Position eyePosition, Position centerPosi // Otherwise, estimate the up direction by using the *current* heading with the new center position. Vec4 forward = newCenterPoint.subtract3(newEyePoint).normalize3(); - if (forward.cross3(up).getLength3() < 0.001) - { + if (forward.cross3(up).getLength3() < 0.001) { Matrix modelview = ViewUtil.computeTransformMatrix(this.globe, eyePosition, this.heading, Angle.ZERO, - Angle.ZERO); - if (modelview != null) - { + Angle.ZERO); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) + if (modelviewInv != null) { up = Vec4.UNIT_Y.transformBy4(modelviewInv); + } } } - if (up == null) - { + if (up == null) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -222,24 +203,20 @@ public ViewUtil.ViewState getViewState(Position eyePosition, Position centerPosi } @Override - protected void doApply(DrawContext dc) - { - if (dc == null) - { + protected void doApply(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -252,14 +229,16 @@ protected void doApply(DrawContext dc) //========== modelview matrix state ==========// // Compute the current modelview matrix. this.modelview = ViewUtil.computeTransformMatrix(this.globe, this.eyePosition, this.heading, this.pitch, - this.roll); - if (this.modelview == null) + this.roll); + if (this.modelview == null) { this.modelview = Matrix.IDENTITY; + } // Compute the current inverse-modelview matrix. this.modelviewInv = this.modelview.getInverse(); - if (this.modelviewInv == null) + if (this.modelviewInv == null) { this.modelviewInv = Matrix.IDENTITY; + } //========== projection matrix state ==========// // Get the current OpenGL viewport state. @@ -278,11 +257,11 @@ protected void doApply(DrawContext dc) // Compute the current projection matrix. this.projection = Matrix.fromPerspective(this.fieldOfView, viewportWidth, viewportHeight, this.nearClipDistance, - this.farClipDistance); + this.farClipDistance); // Compute the current frustum. this.frustum = Frustum.fromPerspective(this.fieldOfView, (int) viewportWidth, (int) viewportHeight, - this.nearClipDistance, this.farClipDistance); + this.nearClipDistance, this.farClipDistance); //========== load GL matrix state ==========// loadGLViewState(dc, this.modelview, this.projection); @@ -291,8 +270,7 @@ protected void doApply(DrawContext dc) afterDoApply(); } - protected void afterDoApply() - { + protected void afterDoApply() { // Establish frame-specific values. this.lastEyePosition = this.computeEyePositionFromModelview(); this.horizonDistance = this.computeHorizonDistance(); @@ -305,21 +283,18 @@ protected void afterDoApply() } @Override - protected void setViewState(ViewUtil.ViewState viewState) - { - if (viewState == null) - { + protected void setViewState(ViewUtil.ViewState viewState) { + if (viewState == null) { String message = Logging.getMessage("nullValue.ViewStateIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewState.getPosition() != null) - { + if (viewState.getPosition() != null) { Position eyePos = ViewUtil.normalizedEyePosition(viewState.getPosition()); LatLon limitedLocation = BasicViewPropertyLimits.limitEyePositionLocation( - this.eyePosition.getLatitude(), - this.eyePosition.getLongitude(), this.getViewPropertyLimits()); + this.eyePosition.getLatitude(), + this.eyePosition.getLongitude(), this.getViewPropertyLimits()); this.eyePosition = new Position(limitedLocation, eyePos.getElevation()); } @@ -329,10 +304,8 @@ protected void setViewState(ViewUtil.ViewState viewState) } @Override - public void setHeading(Angle heading) - { - if (heading == null) - { + public void setHeading(Angle heading) { + if (heading == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -345,10 +318,8 @@ public void setHeading(Angle heading) } @Override - public void setPitch(Angle pitch) - { - if (pitch == null) - { + public void setPitch(Angle pitch) { + if (pitch == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -360,10 +331,9 @@ public void setPitch(Angle pitch) this.updateModelViewStateID(); } - public void setViewPropertyLimits(ViewPropertyLimits limits) - { + public void setViewPropertyLimits(ViewPropertyLimits limits) { this.viewLimits = limits; this.setViewState(new ViewUtil.ViewState(this.getEyePosition(), - this.getHeading(), this.getPitch(), Angle.ZERO)); + this.getHeading(), this.getPitch(), Angle.ZERO)); } } diff --git a/src/gov/nasa/worldwind/view/firstperson/FlyToFlyViewAnimator.java b/src/gov/nasa/worldwind/view/firstperson/FlyToFlyViewAnimator.java index 1112b904c0..f99b0e0e86 100644 --- a/src/gov/nasa/worldwind/view/firstperson/FlyToFlyViewAnimator.java +++ b/src/gov/nasa/worldwind/view/firstperson/FlyToFlyViewAnimator.java @@ -16,130 +16,118 @@ * @author jym * @version $Id: FlyToFlyViewAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FlyToFlyViewAnimator extends CompoundAnimator -{ +public class FlyToFlyViewAnimator extends CompoundAnimator { + int altitudeMode; public FlyToFlyViewAnimator(Interpolator interpolator, int altitudeMode, - PositionAnimator eyePositionAnimator, DoubleAnimator elevationAnimator, - AngleAnimator headingAnimator, AngleAnimator pitchAnimator, AngleAnimator rollAnimator) - { + PositionAnimator eyePositionAnimator, DoubleAnimator elevationAnimator, + AngleAnimator headingAnimator, AngleAnimator pitchAnimator, AngleAnimator rollAnimator) { super(interpolator, eyePositionAnimator, elevationAnimator, headingAnimator, pitchAnimator, rollAnimator); - if (interpolator == null) - { + if (interpolator == null) { this.interpolator = new ScheduledInterpolator(10000); } this.altitudeMode = altitudeMode; } public static FlyToFlyViewAnimator createFlyToFlyViewAnimator( - BasicFlyView view, - Position beginCenterPos, Position endCenterPos, - Angle beginHeading, Angle endHeading, - Angle beginPitch, Angle endPitch, - double beginElevation, double endElevation, long timeToMove, int altitudeMode) - { + BasicFlyView view, + Position beginCenterPos, Position endCenterPos, + Angle beginHeading, Angle endHeading, + Angle beginPitch, Angle endPitch, + double beginElevation, double endElevation, long timeToMove, int altitudeMode) { return createFlyToFlyViewAnimator(view, beginCenterPos, endCenterPos, beginHeading, endHeading, - beginPitch, endPitch, view.getRoll(), view.getRoll(), beginElevation, endElevation, timeToMove, - altitudeMode); + beginPitch, endPitch, view.getRoll(), view.getRoll(), beginElevation, endElevation, timeToMove, + altitudeMode); } public static FlyToFlyViewAnimator createFlyToFlyViewAnimator( - BasicFlyView view, - Position beginCenterPos, Position endCenterPos, - Angle beginHeading, Angle endHeading, - Angle beginPitch, Angle endPitch, - Angle beginRoll, Angle endRoll, - double beginElevation, double endElevation, long timeToMove, int altitudeMode) - { + BasicFlyView view, + Position beginCenterPos, Position endCenterPos, + Angle beginHeading, Angle endHeading, + Angle beginPitch, Angle endPitch, + Angle beginRoll, Angle endRoll, + double beginElevation, double endElevation, long timeToMove, int altitudeMode) { OnSurfacePositionAnimator centerAnimator = new OnSurfacePositionAnimator( - view.getGlobe(), - new ScheduledInterpolator(timeToMove), - beginCenterPos, endCenterPos, - ViewPropertyAccessor.createEyePositionAccessor( - view), altitudeMode); + view.getGlobe(), + new ScheduledInterpolator(timeToMove), + beginCenterPos, endCenterPos, + ViewPropertyAccessor.createEyePositionAccessor( + view), altitudeMode); FlyToElevationAnimator elevAnimator = new FlyToElevationAnimator(view, view.getGlobe(), - beginElevation, endElevation, beginCenterPos, endCenterPos, altitudeMode, - ViewPropertyAccessor.createElevationAccessor(view)); + beginElevation, endElevation, beginCenterPos, endCenterPos, altitudeMode, + ViewPropertyAccessor.createElevationAccessor(view)); AngleAnimator headingAnimator = new AngleAnimator( - new ScheduledInterpolator(timeToMove), - beginHeading, endHeading, - ViewPropertyAccessor.createHeadingAccessor(view)); + new ScheduledInterpolator(timeToMove), + beginHeading, endHeading, + ViewPropertyAccessor.createHeadingAccessor(view)); AngleAnimator pitchAnimator = new AngleAnimator( - new ScheduledInterpolator(timeToMove), - beginPitch, endPitch, - ViewPropertyAccessor.createPitchAccessor(view)); + new ScheduledInterpolator(timeToMove), + beginPitch, endPitch, + ViewPropertyAccessor.createPitchAccessor(view)); AngleAnimator rollAnimator = new AngleAnimator( - new ScheduledInterpolator(timeToMove), - beginRoll, endRoll, - ViewPropertyAccessor.createRollAccessor(view)); + new ScheduledInterpolator(timeToMove), + beginRoll, endRoll, + ViewPropertyAccessor.createRollAccessor(view)); FlyToFlyViewAnimator panAnimator = new FlyToFlyViewAnimator( - new ScheduledInterpolator(timeToMove), altitudeMode, centerAnimator, - elevAnimator, headingAnimator, pitchAnimator, rollAnimator); + new ScheduledInterpolator(timeToMove), altitudeMode, centerAnimator, + elevAnimator, headingAnimator, pitchAnimator, rollAnimator); return (panAnimator); } - public static class FlyToElevationAnimator extends ViewElevationAnimator - { + public static class FlyToElevationAnimator extends ViewElevationAnimator { + public FlyToElevationAnimator(BasicFlyView flyView, Globe globe, - double beginZoom, double endZoom, LatLon beginLatLon, - LatLon endLatLon, int altitudeMode, PropertyAccessor.DoubleAccessor propertyAccessor) - { + double beginZoom, double endZoom, LatLon beginLatLon, + LatLon endLatLon, int altitudeMode, PropertyAccessor.DoubleAccessor propertyAccessor) { super(globe, beginZoom, endZoom, beginLatLon, endLatLon, altitudeMode, propertyAccessor); - if (globe == null) - { + if (globe == null) { useMidZoom = false; - } - else - { + } else { this.midZoom = computeMidZoom(globe, beginLatLon, endLatLon, beginZoom, endZoom); double maxMidZoom = flyView.getViewPropertyLimits().getEyeElevationLimits()[1]; - if (this.midZoom > maxMidZoom) - { + if (this.midZoom > maxMidZoom) { this.midZoom = maxMidZoom; } useMidZoom = useMidZoom(beginZoom, endZoom, midZoom); } - if (useMidZoom) - { + if (useMidZoom) { this.trueEndZoom = endZoom; this.end = this.midZoom; } } } - public static class OnSurfacePositionAnimator extends PositionAnimator - { + public static class OnSurfacePositionAnimator extends PositionAnimator { + Globe globe; int altitudeMode; boolean useMidZoom = true; public OnSurfacePositionAnimator(Globe globe, Interpolator interpolator, - Position begin, - Position end, - PropertyAccessor.PositionAccessor propertyAccessor, int altitudeMode) - { + Position begin, + Position end, + PropertyAccessor.PositionAccessor propertyAccessor, int altitudeMode) { super(interpolator, begin, end, propertyAccessor); this.globe = globe; this.altitudeMode = altitudeMode; } @Override - protected Position nextPosition(double interpolant) - { + protected Position nextPosition(double interpolant) { final int MAX_SMOOTHING = 1; final double CENTER_START = this.useMidZoom ? 0.2 : 0.0; final double CENTER_STOP = this.useMidZoom ? 0.8 : 0.8; double latLonInterpolant = AnimationSupport.basicInterpolant(interpolant, CENTER_START, CENTER_STOP, - MAX_SMOOTHING); + MAX_SMOOTHING); // Invoke the standard next position functionality. Position pos = super.nextPosition(latLonInterpolant); @@ -151,20 +139,16 @@ protected Position nextPosition(double interpolant) double endElevation = 0.0; boolean overrideEndElevation = false; - if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND) { overrideEndElevation = true; endElevation = this.globe.getElevation(getEnd().getLatitude(), getEnd().getLongitude()); - } - else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) { overrideEndElevation = true; endElevation = this.globe.getElevation(getEnd().getLatitude(), getEnd().getLongitude()) - + getEnd().getAltitude(); + + getEnd().getAltitude(); } - if (overrideEndElevation) - { + if (overrideEndElevation) { LatLon ll = pos; // Use interpolated lat/lon. double e1 = getBegin().getElevation(); pos = new Position(ll, (1 - latLonInterpolant) * e1 + latLonInterpolant * endElevation); diff --git a/src/gov/nasa/worldwind/view/firstperson/FlyViewInputHandler.java b/src/gov/nasa/worldwind/view/firstperson/FlyViewInputHandler.java index 3637ad96a7..2310669f23 100644 --- a/src/gov/nasa/worldwind/view/firstperson/FlyViewInputHandler.java +++ b/src/gov/nasa/worldwind/view/firstperson/FlyViewInputHandler.java @@ -20,20 +20,17 @@ * @author jym * @version $Id: FlyViewInputHandler.java 2179 2014-07-25 21:43:39Z dcollins $ */ -public class FlyViewInputHandler extends BasicViewInputHandler -{ - public class ResetPitchActionListener extends ViewInputActionHandler - { +public class FlyViewInputHandler extends BasicViewInputHandler { + + public class ResetPitchActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java.awt.event.KeyEvent event, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { java.util.List keyList = viewAction.getKeyActions(); - for (Object k : keyList) - { - ViewInputAttributes.ActionAttributes.KeyAction keyAction = - (ViewInputAttributes.ActionAttributes.KeyAction) k; - if (event.getKeyCode() == keyAction.keyCode) - { + for (Object k : keyList) { + ViewInputAttributes.ActionAttributes.KeyAction keyAction + = (ViewInputAttributes.ActionAttributes.KeyAction) k; + if (event.getKeyCode() == keyAction.keyCode) { onResetPitch(viewAction); return true; } @@ -42,41 +39,38 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, java. } } - /** Input handler to handle user input that changes Roll. */ - public class RollActionListener extends ViewInputActionHandler - { + /** + * Input handler to handle user input that changes Roll. + */ + public class RollActionListener extends ViewInputActionHandler { + public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEventState keys, String target, - ViewInputAttributes.ActionAttributes viewAction) - { + ViewInputAttributes.ActionAttributes viewAction) { java.util.List keyList = viewAction.getKeyActions(); double rollInput = 0; - for (Object k : keyList) - { - ViewInputAttributes.ActionAttributes.KeyAction keyAction = - (ViewInputAttributes.ActionAttributes.KeyAction) k; - if (keys.isKeyDown(keyAction.keyCode)) - { + for (Object k : keyList) { + ViewInputAttributes.ActionAttributes.KeyAction keyAction + = (ViewInputAttributes.ActionAttributes.KeyAction) k; + if (keys.isKeyDown(keyAction.keyCode)) { rollInput += keyAction.sign; } } - if (rollInput == 0) - { + if (rollInput == 0) { return false; } //noinspection StringEquality - if (target == GENERATE_EVENTS) - { - ViewInputAttributes.DeviceAttributes deviceAttributes = - inputHandler.getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_KEYBOARD); + if (target == GENERATE_EVENTS) { + ViewInputAttributes.DeviceAttributes deviceAttributes + = inputHandler.getAttributes().getDeviceAttributes(ViewInputAttributes.DEVICE_KEYBOARD); onRoll(rollInput, deviceAttributes, viewAction); } return true; } - } + } AnimationController uiAnimControl = new AnimationController(); AnimationController gotoAnimControl = new AnimationController(); @@ -105,146 +99,139 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, KeyEv protected static double DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MIN_VALUE = 5; protected static double DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MAX_VALUE = 50000.0; protected static final double DEFAULT_MOUSE_VERTICAL_TRANSLATE_MIN_VALUE = 1; - // Speed in log-meters per mouse movement + // Speed in log-meters per mouse movement protected static final double DEFAULT_MOUSE_VERTICAL_TRANSLATE_MAX_VALUE = 30000; - // Speed in log-meters per mouse movement + // Speed in log-meters per mouse movement protected static final double DEFAULT_KEY_VERTICAL_TRANSLATE_MIN_VALUE = 5; protected static final double DEFAULT_KEY_VERTICAL_TRANSLATE_MAX_VALUE = 5000; protected static final double DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MIN_OSX = 10; - // Speed in log-meters per wheel movement + // Speed in log-meters per wheel movement protected static final double DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MAX_OSX = 900000; - // Speed in log-meters per wheel movement + // Speed in log-meters per wheel movement protected static final double DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MIN = 100; - // Speed in log-meters per wheel movement + // Speed in log-meters per wheel movement protected static final double DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MAX = 100000; - // Speed in log-meters per wheel movement + // Speed in log-meters per wheel movement // Reset Heading - protected static final ViewInputAttributes.ActionAttributes.KeyAction - DEFAULT_RESET_PITCH_KEY_ACT = - new ViewInputAttributes.ActionAttributes.KeyAction( - KeyEvent.VK_P, ViewInputAttributes.ActionAttributes.KeyAction.KA_DIR_X, 1); - public static final ViewInputAttributes.ActionAttributes.KeyAction[] resetPitchEvents = - { - DEFAULT_RESET_PITCH_KEY_ACT - }; + protected static final ViewInputAttributes.ActionAttributes.KeyAction DEFAULT_RESET_PITCH_KEY_ACT + = new ViewInputAttributes.ActionAttributes.KeyAction( + KeyEvent.VK_P, ViewInputAttributes.ActionAttributes.KeyAction.KA_DIR_X, 1); + public static final ViewInputAttributes.ActionAttributes.KeyAction[] resetPitchEvents + = { + DEFAULT_RESET_PITCH_KEY_ACT + }; double speed = 10.0; - public FlyViewInputHandler() - { + public FlyViewInputHandler() { // Mouse Button Horizontal Translate Events // Button 1 this.getAttributes().setValues(ViewInputAttributes.DEVICE_MOUSE, - ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE, - DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MIN_VALUE, DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MAX_VALUE); + ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE, + DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MIN_VALUE, DEFAULT_MOUSE_HORIZONTAL_TRANSLATE_MAX_VALUE); this.getAttributes().setActionTrigger(ViewInputAttributes.DEVICE_MOUSE, - ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); + ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE, + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); // Mouse Button Rotate Events // Button 1 + SHIFT this.getAttributes().setValues(ViewInputAttributes.DEVICE_MOUSE, ViewInputAttributes.VIEW_ROTATE_SHIFT, - DEFAULT_MOUSE_ROTATE_MIN_VALUE, - DEFAULT_MOUSE_ROTATE_MAX_VALUE); + DEFAULT_MOUSE_ROTATE_MIN_VALUE, + DEFAULT_MOUSE_ROTATE_MAX_VALUE); this.getAttributes().setActionTrigger(ViewInputAttributes.DEVICE_MOUSE, - ViewInputAttributes.VIEW_ROTATE_SHIFT, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); + ViewInputAttributes.VIEW_ROTATE_SHIFT, + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); // Button 3 this.getAttributes().setValues(ViewInputAttributes.DEVICE_MOUSE, ViewInputAttributes.VIEW_ROTATE, - DEFAULT_MOUSE_ROTATE_MIN_VALUE, - DEFAULT_MOUSE_ROTATE_MAX_VALUE); + DEFAULT_MOUSE_ROTATE_MIN_VALUE, + DEFAULT_MOUSE_ROTATE_MAX_VALUE); this.getAttributes().setActionTrigger(ViewInputAttributes.DEVICE_MOUSE, - ViewInputAttributes.VIEW_ROTATE, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); + ViewInputAttributes.VIEW_ROTATE, + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); // Mouse Vertical Translate // Button 2 this.getAttributes().setValues(ViewInputAttributes.DEVICE_MOUSE, - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE, DEFAULT_MOUSE_VERTICAL_TRANSLATE_MIN_VALUE, - DEFAULT_MOUSE_VERTICAL_TRANSLATE_MAX_VALUE); + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE, DEFAULT_MOUSE_VERTICAL_TRANSLATE_MIN_VALUE, + DEFAULT_MOUSE_VERTICAL_TRANSLATE_MAX_VALUE); this.getAttributes().setActionTrigger(ViewInputAttributes.DEVICE_MOUSE, - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE, + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); // Button 1 + CTRL this.getAttributes().setValues(ViewInputAttributes.DEVICE_MOUSE, - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE_CTRL, DEFAULT_MOUSE_VERTICAL_TRANSLATE_MIN_VALUE, - DEFAULT_MOUSE_VERTICAL_TRANSLATE_MAX_VALUE); + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE_CTRL, DEFAULT_MOUSE_VERTICAL_TRANSLATE_MIN_VALUE, + DEFAULT_MOUSE_VERTICAL_TRANSLATE_MAX_VALUE); this.getAttributes().setActionTrigger(ViewInputAttributes.DEVICE_MOUSE, - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE_CTRL, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE_CTRL, + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); // Arrow keys rotate - // ----------------------------------Key Roll -------------------------------------------- RollActionListener rollActionListener = new RollActionListener(); this.getAttributes().setActionListener( - ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROLL_KEYS, rollActionListener); - + ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_ROLL_KEYS, rollActionListener); + // Arrow Keys horizontal translate this.getAttributes().setValues(ViewInputAttributes.DEVICE_KEYBOARD, - ViewInputAttributes.VIEW_HORIZONTAL_TRANS_KEYS, - DEFAULT_KEY_HORIZONTAL_TRANSLATE_MIN_VALUE, - DEFAULT_KEY_HORIZONTAL_TRANSLATE_MAX_VALUE); + ViewInputAttributes.VIEW_HORIZONTAL_TRANS_KEYS, + DEFAULT_KEY_HORIZONTAL_TRANSLATE_MIN_VALUE, + DEFAULT_KEY_HORIZONTAL_TRANSLATE_MAX_VALUE); this.getAttributes().getActionAttributes(ViewInputAttributes.DEVICE_KEYBOARD, - ViewInputAttributes.VIEW_HORIZONTAL_TRANS_KEYS).setSmoothingValue(DEFAULT_KEY_TRANSLATE_SMOOTHING_VALUE); + ViewInputAttributes.VIEW_HORIZONTAL_TRANS_KEYS).setSmoothingValue(DEFAULT_KEY_TRANSLATE_SMOOTHING_VALUE); this.getAttributes().setValues(ViewInputAttributes.DEVICE_KEYBOARD, - ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE_SLOW, - DEFAULT_KEY_HORIZONTAL_TRANSLATE_MIN_VALUE_SLOW, DEFAULT_KEY_HORIZONTAL_TRANSLATE_MAX_VALUE_SLOW); + ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE_SLOW, + DEFAULT_KEY_HORIZONTAL_TRANSLATE_MIN_VALUE_SLOW, DEFAULT_KEY_HORIZONTAL_TRANSLATE_MAX_VALUE_SLOW); /* this.getAttributes().setActionTrigger(ViewInputAttributes.DEVICE_KEYBOARD, ViewInputAttributes.VIEW_HORIZONTAL_TRANSLATE_SLOW, ViewInputAttributes.ActionAttributes.ActionTrigger.ON_KEY_DOWN); - */ + */ // +- Keys vertical translate this.getAttributes().setValues(ViewInputAttributes.DEVICE_KEYBOARD, - ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS, - DEFAULT_KEY_VERTICAL_TRANSLATE_MIN_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_MAX_VALUE); + ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS, + DEFAULT_KEY_VERTICAL_TRANSLATE_MIN_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_MAX_VALUE); // Arrow keys vertical translate this.getAttributes().setValues(ViewInputAttributes.DEVICE_KEYBOARD, - ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_META, - DEFAULT_KEY_VERTICAL_TRANSLATE_MIN_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_MAX_VALUE); + ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_META, + DEFAULT_KEY_VERTICAL_TRANSLATE_MIN_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_MAX_VALUE); this.getAttributes().setValues(ViewInputAttributes.DEVICE_KEYBOARD, - ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_CTRL, - DEFAULT_KEY_VERTICAL_TRANSLATE_MIN_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_MAX_VALUE); + ViewInputAttributes.VIEW_VERTICAL_TRANS_KEYS_CTRL, + DEFAULT_KEY_VERTICAL_TRANSLATE_MIN_VALUE, DEFAULT_KEY_VERTICAL_TRANSLATE_MAX_VALUE); // Mouse Wheel vertical translate - if (Configuration.isMacOS()) - { + if (Configuration.isMacOS()) { this.getAttributes().setValues(ViewInputAttributes.DEVICE_MOUSE_WHEEL, - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE, - DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MIN_OSX, - DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MAX_OSX); - } - else - { + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE, + DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MIN_OSX, + DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MAX_OSX); + } else { this.getAttributes().setValues(ViewInputAttributes.DEVICE_MOUSE_WHEEL, - ViewInputAttributes.VIEW_VERTICAL_TRANSLATE, - DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MIN, - DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MAX); + ViewInputAttributes.VIEW_VERTICAL_TRANSLATE, + DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MIN, + DEFAULT_MOUSE_WHEEL_VERTICAL_TRANSLATE_VALUE_MAX); } // P Key Reset Pitch this.getAttributes().addAction(ViewInputAttributes.DEVICE_KEYBOARD, - ViewInputAttributes.ActionAttributes.NO_MODIFIER, ACTION_RESET_PITCH, - new ViewInputAttributes.ActionAttributes(resetPitchEvents, - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_PRESS, 0, - 0.1, 0.1, false, 0.1)); + ViewInputAttributes.ActionAttributes.NO_MODIFIER, ACTION_RESET_PITCH, + new ViewInputAttributes.ActionAttributes(resetPitchEvents, + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_PRESS, 0, + 0.1, 0.1, false, 0.1)); // Reset Pitch - ViewInputAttributes.ActionAttributes actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( - ACTION_RESET_PITCH); + ViewInputAttributes.ActionAttributes actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_KEYBOARD).getActionAttributes( + ACTION_RESET_PITCH); actionAttrs.setActionListener(new ResetPitchActionListener()); } protected void onMoveTo(Position focalPosition, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttribs) { BasicFlyView view = (BasicFlyView) this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { @@ -255,15 +242,14 @@ protected void onMoveTo(Position focalPosition, // slower response. Therefore the min speed used at lower altitudes ought to be *greater* than the max // speed used at higher altitudes. double smoothing = this.getScaleValueElevation(deviceAttributes, actionAttribs); - if (!actionAttribs.isEnableSmoothing()) + if (!actionAttribs.isEnableSmoothing()) { smoothing = 0.0; + } Vec4 currentLookAtPt = view.getCenterPoint(); - if (currentLookAtPt == null) - { + if (currentLookAtPt == null) { currentLookAtPt = view. - - getGlobe().computePointFromPosition(focalPosition); + getGlobe().computePointFromPosition(focalPosition); } Vec4 currentEyePt = view.getEyePoint(); @@ -278,71 +264,62 @@ protected void onMoveTo(Position focalPosition, this.stopAnimators(); this.gotoAnimControl.put(VIEW_ANIM_HEADING, - new RotateToAngleAnimator( - view.getHeading(), viewCoords.getHeading(), smoothing, - ViewPropertyAccessor.createHeadingAccessor(view))); + new RotateToAngleAnimator( + view.getHeading(), viewCoords.getHeading(), smoothing, + ViewPropertyAccessor.createHeadingAccessor(view))); this.gotoAnimControl.put(VIEW_ANIM_PITCH, - new RotateToAngleAnimator( - view.getPitch(), viewCoords.getPitch(), smoothing, - ViewPropertyAccessor.createPitchAccessor(view))); - - double elevation = ((FlyViewLimits) - view.getViewPropertyLimits()).limitEyeElevation( - newPosition, view.getGlobe()); - if (elevation != newPosition.getElevation()) - { + new RotateToAngleAnimator( + view.getPitch(), viewCoords.getPitch(), smoothing, + ViewPropertyAccessor.createPitchAccessor(view))); + + double elevation = ((FlyViewLimits) view.getViewPropertyLimits()).limitEyeElevation( + newPosition, view.getGlobe()); + if (elevation != newPosition.getElevation()) { newPosition = new Position(newPosition, elevation); } this.gotoAnimControl.put(VIEW_ANIM_POSITION, - new MoveToPositionAnimator( - view.getEyePosition(), newPosition, smoothing, - ViewPropertyAccessor.createEyePositionAccessor(view))); + new MoveToPositionAnimator( + view.getEyePosition(), newPosition, smoothing, + ViewPropertyAccessor.createEyePositionAccessor(view))); view.firePropertyChange(AVKey.VIEW, null, view); } protected void onHorizontalTranslateRel(double forwardInput, double sideInput, - double totalForwardInput, double totalSideInput, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes) - { + double totalForwardInput, double totalSideInput, + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes) { Angle forwardChange; Angle sideChange; this.stopGoToAnimators(); - if (actionAttributes.getMouseActions() != null) - { + if (actionAttributes.getMouseActions() != null) { forwardChange = Angle.fromDegrees(-totalForwardInput - * getScaleValueElevation(deviceAttributes, actionAttributes)); + * getScaleValueElevation(deviceAttributes, actionAttributes)); sideChange = Angle.fromDegrees(totalSideInput - * getScaleValueElevation(deviceAttributes, actionAttributes)); - } - else - { + * getScaleValueElevation(deviceAttributes, actionAttributes)); + } else { forwardChange = Angle.fromDegrees( - forwardInput * speed * getScaleValueElevation(deviceAttributes, actionAttributes)); + forwardInput * speed * getScaleValueElevation(deviceAttributes, actionAttributes)); sideChange = Angle.fromDegrees( - sideInput * speed * getScaleValueElevation(deviceAttributes, actionAttributes)); + sideInput * speed * getScaleValueElevation(deviceAttributes, actionAttributes)); } onHorizontalTranslateRel(forwardChange, sideChange, actionAttributes); } protected void onHorizontalTranslateRel(Angle forwardChange, Angle sideChange, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { return; } - if (forwardChange.equals(Angle.ZERO) && sideChange.equals(Angle.ZERO)) - { + if (forwardChange.equals(Angle.ZERO) && sideChange.equals(Angle.ZERO)) { return; } - if (view instanceof BasicFlyView) - { + if (view instanceof BasicFlyView) { Vec4 forward = view.getForwardVector(); Vec4 up = view.getUpVector(); @@ -359,8 +336,7 @@ protected void onHorizontalTranslateRel(Angle forwardChange, Angle sideChange, } } - protected void onResetHeading(ViewInputAttributes.ActionAttributes actionAttribs) - { + protected void onResetHeading(ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it @@ -368,17 +344,17 @@ protected void onResetHeading(ViewInputAttributes.ActionAttributes actionAttribs return; } double smoothing = actionAttribs.getSmoothingValue(); - if (!(actionAttribs.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(actionAttribs.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } this.gotoAnimControl.put(VIEW_ANIM_HEADING, - new RotateToAngleAnimator( - view.getHeading(), Angle.ZERO, smoothing, - ViewPropertyAccessor.createHeadingAccessor(view))); + new RotateToAngleAnimator( + view.getHeading(), Angle.ZERO, smoothing, + ViewPropertyAccessor.createHeadingAccessor(view))); view.firePropertyChange(AVKey.VIEW, null, view); } - protected void onResetPitch(ViewInputAttributes.ActionAttributes actionAttribs) - { + protected void onResetPitch(ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it @@ -386,17 +362,17 @@ protected void onResetPitch(ViewInputAttributes.ActionAttributes actionAttribs) return; } double smoothing = actionAttribs.getSmoothingValue(); - if (!(actionAttribs.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(actionAttribs.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } this.gotoAnimControl.put(VIEW_ANIM_PITCH, - new RotateToAngleAnimator( - view.getPitch(), Angle.POS90, smoothing, - ViewPropertyAccessor.createPitchAccessor(view))); + new RotateToAngleAnimator( + view.getPitch(), Angle.POS90, smoothing, + ViewPropertyAccessor.createPitchAccessor(view))); view.firePropertyChange(AVKey.VIEW, null, view); } - protected void onResetHeadingPitchRoll(ViewInputAttributes.ActionAttributes actionAttribs) - { + protected void onResetHeadingPitchRoll(ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { @@ -404,39 +380,37 @@ protected void onResetHeadingPitchRoll(ViewInputAttributes.ActionAttributes acti } double smoothing = 0.95; this.gotoAnimControl.put(VIEW_ANIM_HEADING, - new RotateToAngleAnimator( - view.getHeading(), Angle.ZERO, smoothing, - ViewPropertyAccessor.createHeadingAccessor(view))); + new RotateToAngleAnimator( + view.getHeading(), Angle.ZERO, smoothing, + ViewPropertyAccessor.createHeadingAccessor(view))); this.gotoAnimControl.put(VIEW_ANIM_PITCH, - new RotateToAngleAnimator( - view.getPitch(), Angle.POS90, smoothing, - ViewPropertyAccessor.createPitchAccessor(view))); + new RotateToAngleAnimator( + view.getPitch(), Angle.POS90, smoothing, + ViewPropertyAccessor.createPitchAccessor(view))); this.gotoAnimControl.put(VIEW_ANIM_ROLL, - new RotateToAngleAnimator( - view.getPitch(), Angle.ZERO, smoothing, - ViewPropertyAccessor.createRollAccessor(view))); + new RotateToAngleAnimator( + view.getPitch(), Angle.ZERO, smoothing, + ViewPropertyAccessor.createRollAccessor(view))); view.firePropertyChange(AVKey.VIEW, null, view); } protected void onRotateView(double headingInput, double pitchInput, - double totalHeadingInput, double totalPitchInput, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes) - { + double totalHeadingInput, double totalPitchInput, + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes) { Angle headingChange; Angle pitchChange; this.stopGoToAnimators(); headingChange = Angle.fromDegrees( - totalHeadingInput * getScaleValueElevation(deviceAttributes, actionAttributes)); + totalHeadingInput * getScaleValueElevation(deviceAttributes, actionAttributes)); pitchChange = Angle.fromDegrees( - totalPitchInput * getScaleValueElevation(deviceAttributes, actionAttributes)); + totalPitchInput * getScaleValueElevation(deviceAttributes, actionAttributes)); onRotateView(headingChange, pitchChange, actionAttributes); } protected void onRotateView(Angle headingChange, Angle pitchChange, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it @@ -444,13 +418,12 @@ protected void onRotateView(Angle headingChange, Angle pitchChange, return; } - if (view instanceof BasicFlyView) - { + if (view instanceof BasicFlyView) { BasicFlyView flyView = (BasicFlyView) view; this.setPitch(flyView, this.uiAnimControl, flyView.getPitch().add(pitchChange), - actionAttribs); + actionAttribs); this.setHeading(flyView, this.uiAnimControl, flyView.getHeading().add(headingChange), - actionAttribs); + actionAttribs); view.firePropertyChange(AVKey.VIEW, null, view); } } @@ -458,13 +431,12 @@ protected void onRotateView(Angle headingChange, Angle pitchChange, /** * Called when the roll changes due to user input. * - * @param rollInput Change in roll. + * @param rollInput Change in roll. * @param deviceAttributes Attributes of the input device. * @param actionAttributes Action that caused the change. */ protected void onRoll(double rollInput, ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes) - { + ViewInputAttributes.ActionAttributes actionAttributes) { Angle rollChange; this.stopGoToAnimators(); @@ -476,19 +448,17 @@ protected void onRoll(double rollInput, ViewInputAttributes.DeviceAttributes dev /** * Called when the roll changes due to user input. * - * @param rollChange Change in roll. + * @param rollChange Change in roll. * @param actionAttribs Action that caused the change. */ - protected void onRoll(Angle rollChange, ViewInputAttributes.ActionAttributes actionAttribs) - { + protected void onRoll(Angle rollChange, ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { return; } - if (view instanceof BasicFlyView) - { + if (view instanceof BasicFlyView) { BasicFlyView flyView = (BasicFlyView) view; this.setRoll(flyView, this.uiAnimControl, flyView.getRoll().add(rollChange), actionAttribs); @@ -497,9 +467,8 @@ protected void onRoll(Angle rollChange, ViewInputAttributes.ActionAttributes act } protected void onVerticalTranslate(double translateChange, double totalTranslateChange, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttribs) { this.stopGoToAnimators(); double elevChange = -(totalTranslateChange * getScaleValueElevation(deviceAttributes, actionAttribs)); View view = this.getView(); @@ -510,110 +479,98 @@ protected void onVerticalTranslate(double translateChange, double totalTranslate view.firePropertyChange(AVKey.VIEW, null, view); } - public void apply() - { + public void apply() { super.apply(); View view = this.getView(); - if (view == null) - { + if (view == null) { return; } - if (this.gotoAnimControl.stepAnimators()) - { + if (this.gotoAnimControl.stepAnimators()) { view.firePropertyChange(AVKey.VIEW, null, view); } - if (this.uiAnimControl.stepAnimators()) - { + if (this.uiAnimControl.stepAnimators()) { view.firePropertyChange(AVKey.VIEW, null, view); } } - protected void handleViewStopped() - { + protected void handleViewStopped() { this.stopAnimators(); } protected void setHeading(View view, - AnimationController animControl, - Angle heading, ViewInputAttributes.ActionAttributes attrib) - { + AnimationController animControl, + Angle heading, ViewInputAttributes.ActionAttributes attrib) { double smoothing = attrib.getSmoothingValue(); - if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } AngleAnimator angleAnimator = new RotateToAngleAnimator( - view.getHeading(), heading, smoothing, - ViewPropertyAccessor.createHeadingAccessor(view)); + view.getHeading(), heading, smoothing, + ViewPropertyAccessor.createHeadingAccessor(view)); animControl.put(VIEW_ANIM_HEADING, angleAnimator); } protected void setPitch(View view, - AnimationController animControl, - Angle pitch, ViewInputAttributes.ActionAttributes attrib) - { + AnimationController animControl, + Angle pitch, ViewInputAttributes.ActionAttributes attrib) { double smoothing = attrib.getSmoothingValue(); - if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } AngleAnimator angleAnimator = new RotateToAngleAnimator( - view.getPitch(), pitch, smoothing, - ViewPropertyAccessor.createPitchAccessor(view)); + view.getPitch(), pitch, smoothing, + ViewPropertyAccessor.createPitchAccessor(view)); animControl.put(VIEW_ANIM_PITCH, angleAnimator); } /** * Set the roll in a view. * - * @param view View to modify. + * @param view View to modify. * @param animControl Animator controller for the view. - * @param roll new roll value. - * @param attrib action that caused the roll to change. + * @param roll new roll value. + * @param attrib action that caused the roll to change. */ protected void setRoll(View view, - AnimationController animControl, - Angle roll, ViewInputAttributes.ActionAttributes attrib) - { + AnimationController animControl, + Angle roll, ViewInputAttributes.ActionAttributes attrib) { double smoothing = attrib.getSmoothingValue(); - if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } AngleAnimator angleAnimator = new RotateToAngleAnimator( - view.getRoll(), roll, smoothing, - ViewPropertyAccessor.createRollAccessor(view)); + view.getRoll(), roll, smoothing, + ViewPropertyAccessor.createRollAccessor(view)); animControl.put(VIEW_ANIM_ROLL, angleAnimator); } protected void setEyePosition(AnimationController animControl, View view, Position position, - ViewInputAttributes.ActionAttributes attrib) - { + ViewInputAttributes.ActionAttributes attrib) { - MoveToPositionAnimator posAnimator = (MoveToPositionAnimator) - animControl.get(VIEW_ANIM_POSITION); + MoveToPositionAnimator posAnimator = (MoveToPositionAnimator) animControl.get(VIEW_ANIM_POSITION); double smoothing = attrib.getSmoothingValue(); - if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } - if (smoothing != 0.0) - { + if (smoothing != 0.0) { - double elevation = ((FlyViewLimits) - view.getViewPropertyLimits()).limitEyeElevation( - position, view.getGlobe()); - if (elevation != position.getElevation()) - { + double elevation = ((FlyViewLimits) view.getViewPropertyLimits()).limitEyeElevation( + position, view.getGlobe()); + if (elevation != position.getElevation()) { position = new Position(position, elevation); } - if (posAnimator == null) - { + if (posAnimator == null) { posAnimator = new MoveToPositionAnimator( - view.getEyePosition(), position, smoothing, - OrbitViewPropertyAccessor.createEyePositionAccessor(view)); + view.getEyePosition(), position, smoothing, + OrbitViewPropertyAccessor.createEyePositionAccessor(view)); animControl.put(VIEW_ANIM_POSITION, posAnimator); - } - else - { + } else { posAnimator.setEnd(position); posAnimator.start(); } @@ -621,49 +578,44 @@ protected void setEyePosition(AnimationController animControl, View view, Positi view.firePropertyChange(AVKey.VIEW, null, view); } - public void goTo(Position lookAtPos, double distance) - { + public void goTo(Position lookAtPos, double distance) { Globe globe = this.getView().getGlobe(); BasicFlyView view = (BasicFlyView) this.getView(); Position lookFromPos = new Position(lookAtPos, - globe.getElevation(lookAtPos.getLatitude(), lookAtPos.getLongitude()) + distance); + globe.getElevation(lookAtPos.getLatitude(), lookAtPos.getLongitude()) + distance); // TODO: scale on mid-altitude? final long MIN_LENGTH_MILLIS = 4000; final long MAX_LENGTH_MILLIS = 16000; long timeToMove = AnimationSupport.getScaledTimeMillisecs( - view.getEyePosition(), lookFromPos, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); + view.getEyePosition(), lookFromPos, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); FlyToFlyViewAnimator panAnimator = FlyToFlyViewAnimator.createFlyToFlyViewAnimator(view, - view.getEyePosition(), lookFromPos, - view.getHeading(), Angle.ZERO, - view.getPitch(), Angle.ZERO, - view.getEyePosition().getElevation(), lookFromPos.getElevation(), - timeToMove, WorldWind.ABSOLUTE); + view.getEyePosition(), lookFromPos, + view.getHeading(), Angle.ZERO, + view.getPitch(), Angle.ZERO, + view.getEyePosition().getElevation(), lookFromPos.getElevation(), + timeToMove, WorldWind.ABSOLUTE); this.gotoAnimControl.put(VIEW_ANIM_PAN, panAnimator); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } - public void lookAt(Position lookAtPos, long timeToMove) - { + public void lookAt(Position lookAtPos, long timeToMove) { BasicFlyView view = (BasicFlyView) this.getView(); Vec4 lookDirection; double distanceToSurface; Vec4 currentLookAtPt = view.getCenterPoint(); Position newPosition; - if (currentLookAtPt == null) - { + if (currentLookAtPt == null) { view.getGlobe().computePointFromPosition(lookAtPos); double elevAtLookAtPos = view.getGlobe().getElevation( - lookAtPos.getLatitude(), lookAtPos.getLongitude()); + lookAtPos.getLatitude(), lookAtPos.getLongitude()); newPosition = new Position(lookAtPos, elevAtLookAtPos + 10000); - } - else - { + } else { Vec4 currentEyePt = view.getEyePoint(); distanceToSurface = currentEyePt.distanceTo3(currentLookAtPt); lookDirection = currentLookAtPt.subtract3(currentEyePt).normalize3(); @@ -675,11 +627,11 @@ public void lookAt(Position lookAtPos, long timeToMove) ViewUtil.ViewState viewCoords = view.getViewState(newPosition, lookAtPos); FlyToFlyViewAnimator panAnimator = FlyToFlyViewAnimator.createFlyToFlyViewAnimator(view, - view.getEyePosition(), newPosition, - view.getHeading(), viewCoords.getHeading(), - view.getPitch(), viewCoords.getPitch(), - view.getEyePosition().getElevation(), viewCoords.getPosition().getElevation(), - timeToMove, WorldWind.ABSOLUTE); + view.getEyePosition(), newPosition, + view.getHeading(), viewCoords.getHeading(), + view.getPitch(), viewCoords.getPitch(), + view.getEyePosition().getElevation(), viewCoords.getPosition().getElevation(), + timeToMove, WorldWind.ABSOLUTE); this.gotoAnimControl.put(VIEW_ANIM_PAN, panAnimator); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); @@ -687,24 +639,20 @@ public void lookAt(Position lookAtPos, long timeToMove) view.firePropertyChange(AVKey.VIEW, null, view); } - public void stopAnimators() - { + public void stopAnimators() { this.stopGoToAnimators(); this.stopUserInputAnimators(); } - public boolean isAnimating() - { + public boolean isAnimating() { return (this.uiAnimControl.hasActiveAnimation() || this.gotoAnimControl.hasActiveAnimation()); } - public void addAnimator(Animator animator) - { + public void addAnimator(Animator animator) { this.gotoAnimControl.put(VIEW_ANIM_APP, animator); } - protected void stopGoToAnimators() - { + protected void stopGoToAnimators() { // Explicitly stop all 'go to' animators, then clear the data structure which holds them. If we remove an // animator from this data structure without invoking stop(), the animator has no way of knowing it was forcibly // stopped. An animator's owner - likely an application object other - may need to know if an animator has been @@ -713,8 +661,7 @@ protected void stopGoToAnimators() this.gotoAnimControl.clear(); } - protected void stopUserInputAnimators() - { + protected void stopUserInputAnimators() { // Explicitly stop all 'ui' animator, then clear the data structure which holds them. If we remove an animator // from this data structure without invoking stop(), the animator has no way of knowing it was forcibly stopped. // Though applications cannot access the 'ui' animator data structure, stopping the animators here is the correct diff --git a/src/gov/nasa/worldwind/view/firstperson/FlyViewLimits.java b/src/gov/nasa/worldwind/view/firstperson/FlyViewLimits.java index fbb1a69f6d..9dab709f98 100644 --- a/src/gov/nasa/worldwind/view/firstperson/FlyViewLimits.java +++ b/src/gov/nasa/worldwind/view/firstperson/FlyViewLimits.java @@ -13,40 +13,29 @@ * @author jym * @version $Id: FlyViewLimits.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FlyViewLimits extends BasicViewPropertyLimits -{ +public class FlyViewLimits extends BasicViewPropertyLimits { - - public double limitEyeElevation(Position position, Globe globe) - { + public double limitEyeElevation(Position position, Globe globe) { double newElevation = position.getElevation(); double terrainElevation = globe.getElevation(position.getLatitude(), position.getLongitude()); double[] elevLimits = this.getEyeElevationLimits(); - if (position.getElevation() < (elevLimits[0] + terrainElevation)) - { - newElevation = elevLimits[0]+terrainElevation; - } - else if (position.getElevation() > elevLimits[1] + terrainElevation) - { - newElevation = elevLimits[1]+terrainElevation; + if (position.getElevation() < (elevLimits[0] + terrainElevation)) { + newElevation = elevLimits[0] + terrainElevation; + } else if (position.getElevation() > elevLimits[1] + terrainElevation) { + newElevation = elevLimits[1] + terrainElevation; } - return(newElevation); + return (newElevation); } - - public double limitEyeElevation(double elevation) - { + public double limitEyeElevation(double elevation) { double[] elevLimits = this.getEyeElevationLimits(); - if (elevation < elevLimits[0]) - { + if (elevation < elevLimits[0]) { return elevLimits[0]; - } - else if (elevation > elevLimits[1]) - { + } else if (elevation > elevLimits[1]) { return elevLimits[1]; } - return(elevation); + return (elevation); } } diff --git a/src/gov/nasa/worldwind/view/orbit/BasicOrbitView.java b/src/gov/nasa/worldwind/view/orbit/BasicOrbitView.java index 4f674fc711..7ffa9d18d5 100644 --- a/src/gov/nasa/worldwind/view/orbit/BasicOrbitView.java +++ b/src/gov/nasa/worldwind/view/orbit/BasicOrbitView.java @@ -19,8 +19,7 @@ * @author dcollins * @version $Id: BasicOrbitView.java 2253 2014-08-22 16:33:46Z dcollins $ */ -public class BasicOrbitView extends BasicView implements OrbitView -{ +public class BasicOrbitView extends BasicView implements OrbitView { protected Position center = Position.ZERO; protected double zoom; @@ -28,50 +27,54 @@ public class BasicOrbitView extends BasicView implements OrbitView // Stateless helper classes. protected final OrbitViewCollisionSupport collisionSupport = new OrbitViewCollisionSupport(); - public BasicOrbitView() - { + public BasicOrbitView() { this.viewInputHandler = (ViewInputHandler) WorldWind.createConfigurationComponent( - AVKey.VIEW_INPUT_HANDLER_CLASS_NAME); + AVKey.VIEW_INPUT_HANDLER_CLASS_NAME); this.viewLimits = new BasicOrbitViewLimits(); - if (this.viewInputHandler == null) + if (this.viewInputHandler == null) { this.viewInputHandler = new OrbitViewInputHandler(); + } this.collisionSupport.setCollisionThreshold(COLLISION_THRESHOLD); this.collisionSupport.setNumIterations(COLLISION_NUM_ITERATIONS); loadConfigurationValues(); } - protected void loadConfigurationValues() - { + protected void loadConfigurationValues() { Double initLat = Configuration.getDoubleValue(AVKey.INITIAL_LATITUDE); Double initLon = Configuration.getDoubleValue(AVKey.INITIAL_LONGITUDE); double initElev = this.center.getElevation(); // Set center latitude and longitude. Do not change center elevation. - if (initLat != null && initLon != null) + if (initLat != null && initLon != null) { setCenterPosition(Position.fromDegrees(initLat, initLon, initElev)); - // Set only center latitude. Do not change center longitude or center elevation. - else if (initLat != null) + } // Set only center latitude. Do not change center longitude or center elevation. + else if (initLat != null) { setCenterPosition(Position.fromDegrees(initLat, this.center.getLongitude().degrees, initElev)); - // Set only center longitude. Do not center latitude or center elevation. - else if (initLon != null) + } // Set only center longitude. Do not center latitude or center elevation. + else if (initLon != null) { setCenterPosition(Position.fromDegrees(this.center.getLatitude().degrees, initLon, initElev)); + } Double initHeading = Configuration.getDoubleValue(AVKey.INITIAL_HEADING); - if (initHeading != null) + if (initHeading != null) { setHeading(Angle.fromDegrees(initHeading)); + } Double initPitch = Configuration.getDoubleValue(AVKey.INITIAL_PITCH); - if (initPitch != null) + if (initPitch != null) { setPitch(Angle.fromDegrees(initPitch)); + } Double initAltitude = Configuration.getDoubleValue(AVKey.INITIAL_ALTITUDE); - if (initAltitude != null) + if (initAltitude != null) { setZoom(initAltitude); + } Double initFov = Configuration.getDoubleValue(AVKey.FOV); - if (initFov != null) + if (initFov != null) { setFieldOfView(Angle.fromDegrees(initFov)); + } this.setViewOutOfFocus(true); } @@ -82,23 +85,18 @@ else if (initLon != null) // and whether the View will resolve collisions itself, // something along the lines of isResolveCollisions. // At the same time, flagHadCollisions() should be made part of the public View interface. - - protected void flagHadCollisions() - { + protected void flagHadCollisions() { this.hadCollisions = true; } - public void stopMovementOnCenter() - { + public void stopMovementOnCenter() { firePropertyChange(CENTER_STOPPED, null, null); } - public void copyViewState(View view) - { + public void copyViewState(View view) { this.globe = view.getGlobe(); Vec4 center = view.getCenterPoint(); - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -106,27 +104,22 @@ public void copyViewState(View view) setOrientation(view.getEyePosition(), globe.computePositionFromPoint(center)); } - public Position getCenterPosition() - { + public Position getCenterPosition() { return this.center; } - public Vec4 getCenterPoint() - { + public Vec4 getCenterPoint() { return (globe.computePointFromPosition( - this.center)); + this.center)); } - public void setCenterPosition(Position center) - { - if (center == null) - { + public void setCenterPosition(Position center) { + if (center == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center.getLatitude().degrees < -90 || center.getLatitude().degrees > 90) - { + if (center.getLatitude().degrees < -90 || center.getLatitude().degrees > 90) { String message = Logging.getMessage("generic.LatitudeOutOfRange", center.getLatitude()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -139,10 +132,8 @@ public void setCenterPosition(Position center) this.updateModelViewStateID(); } - public void setHeading(Angle heading) - { - if (heading == null) - { + public void setHeading(Angle heading) { + if (heading == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -155,10 +146,8 @@ public void setHeading(Angle heading) this.updateModelViewStateID(); } - public void setPitch(Angle pitch) - { - if (pitch == null) - { + public void setPitch(Angle pitch) { + if (pitch == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -171,15 +160,12 @@ public void setPitch(Angle pitch) this.updateModelViewStateID(); } - public double getZoom() - { + public double getZoom() { return this.zoom; } - public void setZoom(double zoom) - { - if (zoom < 0) - { + public void setZoom(double zoom) { + if (zoom < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", zoom); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -199,8 +185,7 @@ public void setZoom(double zoom) * * @return the OrbitViewLimits that apply to this OrbitView */ - public OrbitViewLimits getOrbitViewLimits() - { + public OrbitViewLimits getOrbitViewLimits() { return (OrbitViewLimits) viewLimits; } @@ -213,10 +198,8 @@ public OrbitViewLimits getOrbitViewLimits() * * @throws IllegalArgumentException if viewLimits is null. */ - public void setOrbitViewLimits(OrbitViewLimits viewLimits) - { - if (viewLimits == null) - { + public void setOrbitViewLimits(OrbitViewLimits viewLimits) { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -225,25 +208,21 @@ public void setOrbitViewLimits(OrbitViewLimits viewLimits) this.viewLimits = viewLimits; } - public static Position normalizedCenterPosition(Position unnormalizedPosition) - { - if (unnormalizedPosition == null) - { + public static Position normalizedCenterPosition(Position unnormalizedPosition) { + if (unnormalizedPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new Position( - Angle.normalizedLatitude(unnormalizedPosition.getLatitude()), - Angle.normalizedLongitude(unnormalizedPosition.getLongitude()), - unnormalizedPosition.getElevation()); + Angle.normalizedLatitude(unnormalizedPosition.getLatitude()), + Angle.normalizedLongitude(unnormalizedPosition.getLongitude()), + unnormalizedPosition.getElevation()); } - public static Angle normalizedHeading(Angle unnormalizedHeading) - { - if (unnormalizedHeading == null) - { + public static Angle normalizedHeading(Angle unnormalizedHeading) { + if (unnormalizedHeading == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -254,10 +233,8 @@ public static Angle normalizedHeading(Angle unnormalizedHeading) return Angle.fromDegrees(heading > 180 ? heading - 360 : (heading < -180 ? 360 + heading : heading)); } - public static Angle normalizedPitch(Angle unnormalizedPitch) - { - if (unnormalizedPitch == null) - { + public static Angle normalizedPitch(Angle unnormalizedPitch) { + if (unnormalizedPitch == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -269,68 +246,65 @@ public static Angle normalizedPitch(Angle unnormalizedPitch) return Angle.fromDegrees(pitch > 180 ? pitch - 360 : (pitch < -180 ? 360 + pitch : pitch)); } - protected void resolveCollisionsWithCenterPosition() - { - if (this.dc == null) + protected void resolveCollisionsWithCenterPosition() { + if (this.dc == null) { return; + } - if (!isDetectCollisions()) + if (!isDetectCollisions()) { return; + } // If there is no collision, 'newCenterPosition' will be null. Otherwise it will contain a value // that will resolve the collision. double nearDistance = this.computeNearDistance(this.getCurrentEyePosition()); Position newCenter = this.collisionSupport.computeCenterPositionToResolveCollision(this, nearDistance, this.dc); - if (newCenter != null && newCenter.getLatitude().degrees >= -90 && newCenter.getLongitude().degrees <= 90) - { + if (newCenter != null && newCenter.getLatitude().degrees >= -90 && newCenter.getLongitude().degrees <= 90) { this.center = newCenter; flagHadCollisions(); } } - protected void resolveCollisionsWithPitch() - { - if (this.dc == null) + protected void resolveCollisionsWithPitch() { + if (this.dc == null) { return; + } - if (!isDetectCollisions()) + if (!isDetectCollisions()) { return; + } // Compute the near distance corresponding to the current set of values. // If there is no collision, 'newPitch' will be null. Otherwise it will contain a value // that will resolve the collision. double nearDistance = this.computeNearDistance(this.getCurrentEyePosition()); Angle newPitch = this.collisionSupport.computePitchToResolveCollision(this, nearDistance, this.dc); - if (newPitch != null && newPitch.degrees <= 90 && newPitch.degrees >= 0) - { + if (newPitch != null && newPitch.degrees <= 90 && newPitch.degrees >= 0) { this.pitch = newPitch; flagHadCollisions(); } } - /** Computes and sets the center of rotation for heading and pitch changes, if it is needed. */ - public void computeAndSetViewCenterIfNeeded() - { - if (this.viewOutOfFocus) - { + /** + * Computes and sets the center of rotation for heading and pitch changes, if it is needed. + */ + public void computeAndSetViewCenterIfNeeded() { + if (this.viewOutOfFocus) { computeAndSetViewCenter(); } } - /** Computes and sets the center of rotation for heading and pitch changes. */ - public void computeAndSetViewCenter() - { - try - { + /** + * Computes and sets the center of rotation for heading and pitch changes. + */ + public void computeAndSetViewCenter() { + try { // Update the View's focus. - if (this.canFocusOnViewportCenter()) - { + if (this.canFocusOnViewportCenter()) { this.focusOnViewportCenter(); this.setViewOutOfFocus(false); } - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileChangingView"); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); // If updating the View's focus failed, raise the flag again. @@ -344,8 +318,7 @@ public void computeAndSetViewCenter() * * @param b true if the point of rotation needs recalculation, false if it does not. */ - public void setViewOutOfFocus(boolean b) - { + public void setViewOutOfFocus(boolean b) { this.viewOutOfFocus = b; } @@ -356,34 +329,32 @@ public void setViewOutOfFocus(boolean b) * * @return true if the BasicOrbitView can focus on the viewport center. */ - public boolean canFocusOnViewportCenter() - { + public boolean canFocusOnViewportCenter() { return this.dc != null - && this.dc.getViewportCenterPosition() != null - && this.globe != null; + && this.dc.getViewportCenterPosition() != null + && this.globe != null; } - /** Sets the point of rotation for heading and pitch changes to the surface position at the viewport center. */ - public void focusOnViewportCenter() - { - if (this.isAnimating()) + /** + * Sets the point of rotation for heading and pitch changes to the surface position at the viewport center. + */ + public void focusOnViewportCenter() { + if (this.isAnimating()) { return; - if (this.dc == null) - { + } + if (this.dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.globe == null) - { + if (this.globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } Position viewportCenterPos = this.dc.getViewportCenterPosition(); - if (viewportCenterPos == null) - { + if (viewportCenterPos == null) { String message = Logging.getMessage("nullValue.DrawingContextViewportCenterIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -391,19 +362,16 @@ public void focusOnViewportCenter() // We want the actual "geometric point" here, which must be adjusted for vertical exaggeration. Vec4 viewportCenterPoint = this.globe.computePointFromPosition( - viewportCenterPos.getLatitude(), viewportCenterPos.getLongitude(), - this.globe.getElevation(viewportCenterPos.getLatitude(), viewportCenterPos.getLongitude()) + viewportCenterPos.getLatitude(), viewportCenterPos.getLongitude(), + this.globe.getElevation(viewportCenterPos.getLatitude(), viewportCenterPos.getLongitude()) * dc.getVerticalExaggeration()); - if (viewportCenterPoint != null) - { + if (viewportCenterPoint != null) { Matrix modelview = OrbitViewInputSupport.computeTransformMatrix(this.globe, - this.center, this.heading, this.pitch, this.roll, this.zoom); - if (modelview != null) - { + this.center, this.heading, this.pitch, this.roll, this.zoom); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { // The change in focus must happen seamlessly; we can't move the eye or the forward vector // (only the center position and zoom should change). Therefore we pick a point along the // forward vector, and *near* the viewportCenterPoint, but not necessarily at the @@ -414,9 +382,8 @@ public void focusOnViewportCenter() Vec4 newCenterPoint = Vec4.fromLine3(eyePoint, distance, forward); OrbitViewInputSupport.OrbitViewState modelCoords = OrbitViewInputSupport.computeOrbitViewState( - this.globe, modelview, newCenterPoint); - if (validateModelCoordinates(modelCoords)) - { + this.globe, modelview, newCenterPoint); + if (validateModelCoordinates(modelCoords)) { setModelCoordinates(modelCoords); } } @@ -424,55 +391,47 @@ public void focusOnViewportCenter() } } - public boolean canFocusOnTerrainCenter() - { + public boolean canFocusOnTerrainCenter() { return this.dc != null - && this.dc.getSurfaceGeometry() != null - && this.globe != null; + && this.dc.getSurfaceGeometry() != null + && this.globe != null; } - public void focusOnTerrainCenter() - { - if (this.dc == null) - { + public void focusOnTerrainCenter() { + if (this.dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.globe == null) - { + if (this.globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (this.dc.getSurfaceGeometry() == null) - { + if (this.dc.getSurfaceGeometry() == null) { return; } - if (isAnimating()) + if (isAnimating()) { return; + } Matrix modelview = OrbitViewInputSupport.computeTransformMatrix(this.globe, - this.center, this.heading, this.pitch, this.roll, this.zoom); - if (modelview != null) - { + this.center, this.heading, this.pitch, this.roll, this.zoom); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { // The change in focus must happen seamlessly; we can't move the eye or the forward vector // (only the center position and zoom should change). Vec4 eyePoint = Vec4.UNIT_W.transformBy4(modelviewInv); Vec4 forward = Vec4.UNIT_NEGATIVE_Z.transformBy4(modelviewInv); Intersection[] intersections = this.dc.getSurfaceGeometry().intersect(new Line(eyePoint, forward)); - if (intersections != null && intersections.length > 0) - { + if (intersections != null && intersections.length > 0) { Vec4 viewportCenterPoint = intersections[0].getIntersectionPoint(); OrbitViewInputSupport.OrbitViewState modelCoords = OrbitViewInputSupport.computeOrbitViewState( - this.globe, modelview, viewportCenterPoint); - if (validateModelCoordinates(modelCoords)) - { + this.globe, modelview, viewportCenterPoint); + if (validateModelCoordinates(modelCoords)) { setModelCoordinates(modelCoords); } } @@ -480,10 +439,8 @@ public void focusOnTerrainCenter() } } - public void setEyePosition(Position eyePosition) - { - if (eyePosition == null) - { + public void setEyePosition(Position eyePosition) { + if (eyePosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -504,17 +461,13 @@ public void setEyePosition(Position eyePosition) this.updateModelViewStateID(); } - public Vec4 getCurrentEyePoint() - { - if (this.globe != null) - { + public Vec4 getCurrentEyePoint() { + if (this.globe != null) { Matrix modelview = OrbitViewInputSupport.computeTransformMatrix(this.globe, this.center, - this.heading, this.pitch, this.roll, this.zoom); - if (modelview != null) - { + this.heading, this.pitch, this.roll, this.zoom); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { return Vec4.UNIT_W.transformBy4(modelviewInv); } } @@ -523,17 +476,13 @@ public Vec4 getCurrentEyePoint() return Vec4.ZERO; } - public Position getCurrentEyePosition() - { - if (this.globe != null) - { + public Position getCurrentEyePosition() { + if (this.globe != null) { Matrix modelview = OrbitViewInputSupport.computeTransformMatrix(this.globe, this.center, - this.heading, this.pitch, this.roll, this.zoom); - if (modelview != null) - { + this.heading, this.pitch, this.roll, this.zoom); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { Vec4 eyePoint = Vec4.UNIT_W.transformBy4(modelviewInv); return this.globe.computePositionFromPoint(eyePoint); } @@ -543,16 +492,13 @@ public Position getCurrentEyePosition() return Position.ZERO; } - public void setOrientation(Position eyePosition, Position centerPosition) - { - if (eyePosition == null || centerPosition == null) - { + public void setOrientation(Position eyePosition, Position centerPosition) { + if (eyePosition == null || centerPosition == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.globe == null) - { + if (this.globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); @@ -561,8 +507,7 @@ public void setOrientation(Position eyePosition, Position centerPosition) Vec4 newEyePoint = this.globe.computePointFromPosition(eyePosition); Vec4 newCenterPoint = this.globe.computePointFromPosition(centerPosition); - if (newEyePoint == null || newCenterPoint == null) - { + if (newEyePoint == null || newCenterPoint == null) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -573,31 +518,26 @@ public void setOrientation(Position eyePosition, Position centerPosition) Vec4 up = this.globe.computeSurfaceNormalAtPoint(newCenterPoint); // Otherwise, estimate the up direction by using the *current* heading with the new center position. Vec4 forward = newCenterPoint.subtract3(newEyePoint).normalize3(); - if (forward.cross3(up).getLength3() < 0.001) - { + if (forward.cross3(up).getLength3() < 0.001) { Matrix modelview = OrbitViewInputSupport.computeTransformMatrix( - this.globe, centerPosition, this.heading, Angle.ZERO, Angle.ZERO, 1); - if (modelview != null) - { + this.globe, centerPosition, this.heading, Angle.ZERO, Angle.ZERO, 1); + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { up = Vec4.UNIT_Y.transformBy4(modelviewInv); } } } - if (up == null) - { + if (up == null) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); } OrbitViewInputSupport.OrbitViewState modelCoords = OrbitViewInputSupport.computeOrbitViewState( - this.globe, newEyePoint, newCenterPoint, up); - if (!validateModelCoordinates(modelCoords)) - { + this.globe, newEyePoint, newCenterPoint, up); + if (!validateModelCoordinates(modelCoords)) { String message = Logging.getMessage("View.ErrorSettingOrientation", eyePosition, centerPosition); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -606,22 +546,18 @@ public void setOrientation(Position eyePosition, Position centerPosition) setModelCoordinates(modelCoords); } - protected void doApply(DrawContext dc) - { - if (dc == null) - { + protected void doApply(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGlobe() == null) - { + if (dc.getGlobe() == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -640,13 +576,15 @@ protected void doApply(DrawContext dc) //========== modelview matrix state ==========// // Compute the current modelview matrix. this.modelview = OrbitViewInputSupport.computeTransformMatrix(this.globe, this.center, - this.heading, this.pitch, this.roll, this.zoom); - if (this.modelview == null) + this.heading, this.pitch, this.roll, this.zoom); + if (this.modelview == null) { this.modelview = Matrix.IDENTITY; + } // Compute the current inverse-modelview matrix. this.modelviewInv = this.modelview.getInverse(); - if (this.modelviewInv == null) + if (this.modelviewInv == null) { this.modelviewInv = Matrix.IDENTITY; + } //========== projection matrix state ==========// // Get the current OpenGL viewport state. @@ -662,12 +600,12 @@ protected void doApply(DrawContext dc) double viewportHeight = this.viewport.getHeight() <= 0.0 ? 1.0 : this.viewport.getHeight(); // Compute the current projection matrix. this.projection = Matrix.fromPerspective(this.fieldOfView, - viewportWidth, viewportHeight, - this.nearClipDistance, this.farClipDistance); + viewportWidth, viewportHeight, + this.nearClipDistance, this.farClipDistance); // Compute the current frustum. this.frustum = Frustum.fromPerspective(this.fieldOfView, - (int) viewportWidth, (int) viewportHeight, - this.nearClipDistance, this.farClipDistance); + (int) viewportWidth, (int) viewportHeight, + this.nearClipDistance, this.farClipDistance); //========== load GL matrix state ==========// loadGLViewState(dc, this.modelview, this.projection); @@ -676,8 +614,7 @@ protected void doApply(DrawContext dc) afterDoApply(); } - protected void afterDoApply() - { + protected void afterDoApply() { // Establish frame-specific values. this.lastEyePosition = this.computeEyePositionFromModelview(); this.horizonDistance = this.computeHorizonDistance(); @@ -689,22 +626,17 @@ protected void afterDoApply() this.lastFrustumInModelCoords = null; } - protected void setModelCoordinates(OrbitViewInputSupport.OrbitViewState modelCoords) - { - if (modelCoords != null) - { - if (modelCoords.getCenterPosition() != null) - { + protected void setModelCoordinates(OrbitViewInputSupport.OrbitViewState modelCoords) { + if (modelCoords != null) { + if (modelCoords.getCenterPosition() != null) { this.center = normalizedCenterPosition(modelCoords.getCenterPosition()); this.center = this.getOrbitViewLimits().limitCenterPosition(this, this.center); } - if (modelCoords.getHeading() != null) - { + if (modelCoords.getHeading() != null) { this.heading = normalizedHeading(modelCoords.getHeading()); this.heading = this.getOrbitViewLimits().limitHeading(this, this.heading); } - if (modelCoords.getPitch() != null) - { + if (modelCoords.getPitch() != null) { this.pitch = normalizedPitch(modelCoords.getPitch()); this.pitch = this.getOrbitViewLimits().limitPitch(this, this.pitch); } @@ -716,37 +648,30 @@ protected void setModelCoordinates(OrbitViewInputSupport.OrbitViewState modelCoo } } - protected boolean validateModelCoordinates(OrbitViewInputSupport.OrbitViewState modelCoords) - { + protected boolean validateModelCoordinates(OrbitViewInputSupport.OrbitViewState modelCoords) { return (modelCoords != null - && modelCoords.getCenterPosition() != null - && modelCoords.getCenterPosition().getLatitude().degrees >= -90 - && modelCoords.getCenterPosition().getLatitude().degrees <= 90 - && modelCoords.getHeading() != null - && modelCoords.getPitch() != null - && modelCoords.getPitch().degrees >= 0 - && modelCoords.getPitch().degrees <= 90 - && modelCoords.getZoom() >= 0); + && modelCoords.getCenterPosition() != null + && modelCoords.getCenterPosition().getLatitude().degrees >= -90 + && modelCoords.getCenterPosition().getLatitude().degrees <= 90 + && modelCoords.getHeading() != null + && modelCoords.getPitch() != null + && modelCoords.getPitch().degrees >= 0 + && modelCoords.getPitch().degrees <= 90 + && modelCoords.getZoom() >= 0); } @Override - protected double computeHorizonDistance(Position eyePosition) - { - if (this.dc.is2DGlobe()) - { + protected double computeHorizonDistance(Position eyePosition) { + if (this.dc.is2DGlobe()) { return Double.MAX_VALUE; // Horizon distance doesn't make sense for the 2D globe. - } - else - { + } else { return super.computeHorizonDistance(eyePosition); } } @Override - protected double computeFarDistance(Position eyePosition) - { - if (this.dc.is2DGlobe()) - { + protected double computeFarDistance(Position eyePosition) { + if (this.dc.is2DGlobe()) { // TODO: Compute the smallest far distance for a flat or a tilted view. // Use max distance to six points around the map Vec4 eyePoint = this.globe.computePointFromPosition(eyePosition); @@ -763,9 +688,7 @@ protected double computeFarDistance(Position eyePosition) p = this.globe.computePointFromPosition(Angle.ZERO, Angle.NEG180, 0); // W far = Math.max(far, eyePoint.distanceTo3(p)); return far < MINIMUM_FAR_DISTANCE ? MINIMUM_FAR_DISTANCE : far; - } - else - { + } else { return super.computeHorizonDistance(eyePosition); } } @@ -773,16 +696,12 @@ protected double computeFarDistance(Position eyePosition) //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.doGetRestorableState(rs, context); - if (this.getCenterPosition() != null) - { + if (this.getCenterPosition() != null) { RestorableSupport.StateObject so = rs.addStateObject(context, "center"); - if (so != null) - { + if (so != null) { rs.addStateValueAsDouble(so, "latitude", this.getCenterPosition().getLatitude().degrees); rs.addStateValueAsDouble(so, "longitude", this.getCenterPosition().getLongitude().degrees); rs.addStateValueAsDouble(so, "elevation", this.getCenterPosition().getElevation()); @@ -792,8 +711,7 @@ protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.Stat rs.addStateValueAsDouble(context, "zoom", this.getZoom()); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Invoke the legacy restore functionality. This will enable the shape to recognize state XML elements // from previous versions of BasicOrbitView. this.legacyRestoreState(rs, context); @@ -803,18 +721,19 @@ protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObjec // Restore the center property only if all parts are available. // We will not restore a partial center (for example, just latitude). RestorableSupport.StateObject so = rs.getStateObject(context, "center"); - if (so != null) - { + if (so != null) { Double lat = rs.getStateValueAsDouble(so, "latitude"); Double lon = rs.getStateValueAsDouble(so, "longitude"); Double ele = rs.getStateValueAsDouble(so, "elevation"); - if (lat != null && lon != null) + if (lat != null && lon != null) { this.setCenterPosition(Position.fromDegrees(lat, lon, (ele != null ? ele : 0))); + } } Double d = rs.getStateValueAsDouble(context, "zoom"); - if (d != null) + if (d != null) { this.setZoom(d); + } } /** @@ -823,101 +742,87 @@ protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObjec * restored in {@link #doRestoreState(gov.nasa.worldwind.util.RestorableSupport, * gov.nasa.worldwind.util.RestorableSupport.StateObject)}. * - * @param rs RestorableSupport object which contains the state value properties. + * @param rs RestorableSupport object which contains the state value properties. * @param context active context in the RestorableSupport to read state from. */ - protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void legacyRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { RestorableSupport.StateObject so = rs.getStateObject(context, "orbitViewLimits"); - if (so != null) + if (so != null) { this.getViewPropertyLimits().restoreState(rs, so); + } } //**************************************************************// //******************** Animator Convenience Methods ************// //**************************************************************// - public void addPanToAnimator(Position beginCenterPos, Position endCenterPos, - Angle beginHeading, Angle endHeading, - Angle beginPitch, Angle endPitch, - double beginZoom, double endZoom, long timeToMove, boolean endCenterOnSurface) - { + Angle beginHeading, Angle endHeading, + Angle beginPitch, Angle endPitch, + double beginZoom, double endZoom, long timeToMove, boolean endCenterOnSurface) { ((OrbitViewInputHandler) this.viewInputHandler).addPanToAnimator( - beginCenterPos, endCenterPos, beginHeading, endHeading, beginPitch, endPitch, - beginZoom, endZoom, timeToMove, endCenterOnSurface); + beginCenterPos, endCenterPos, beginHeading, endHeading, beginPitch, endPitch, + beginZoom, endZoom, timeToMove, endCenterOnSurface); } public void addPanToAnimator(Position beginCenterPos, Position endCenterPos, - Angle beginHeading, Angle endHeading, - Angle beginPitch, Angle endPitch, - double beginZoom, double endZoom, boolean endCenterOnSurface) - { + Angle beginHeading, Angle endHeading, + Angle beginPitch, Angle endPitch, + double beginZoom, double endZoom, boolean endCenterOnSurface) { ((OrbitViewInputHandler) this.viewInputHandler).addPanToAnimator( - beginCenterPos, endCenterPos, beginHeading, endHeading, beginPitch, endPitch, - beginZoom, endZoom, endCenterOnSurface); + beginCenterPos, endCenterPos, beginHeading, endHeading, beginPitch, endPitch, + beginZoom, endZoom, endCenterOnSurface); } public void addPanToAnimator(Position centerPos, Angle heading, Angle pitch, double zoom, - long timeToMove, boolean endCenterOnSurface) - { + long timeToMove, boolean endCenterOnSurface) { ((OrbitViewInputHandler) this.viewInputHandler).addPanToAnimator(centerPos, heading, pitch, zoom, timeToMove, - endCenterOnSurface); + endCenterOnSurface); } public void addPanToAnimator(Position centerPos, Angle heading, Angle pitch, double zoom, - boolean endCenterOnSurface) - { + boolean endCenterOnSurface) { ((OrbitViewInputHandler) this.viewInputHandler).addPanToAnimator(centerPos, heading, pitch, zoom, - endCenterOnSurface); + endCenterOnSurface); } - public void addPanToAnimator(Position centerPos, Angle heading, Angle pitch, double zoom) - { + public void addPanToAnimator(Position centerPos, Angle heading, Angle pitch, double zoom) { ((OrbitViewInputHandler) this.viewInputHandler).addPanToAnimator(centerPos, heading, pitch, zoom); } - public void addEyePositionAnimator(long timeToIterate, Position beginPosition, Position endPosition) - { + public void addEyePositionAnimator(long timeToIterate, Position beginPosition, Position endPosition) { ((OrbitViewInputHandler) this.viewInputHandler).addEyePositionAnimator( - timeToIterate, beginPosition, endPosition); + timeToIterate, beginPosition, endPosition); } - public void addHeadingAnimator(Angle begin, Angle end) - { + public void addHeadingAnimator(Angle begin, Angle end) { ((OrbitViewInputHandler) this.viewInputHandler).addHeadingAnimator(begin, end); } - public void addPitchAnimator(Angle begin, Angle end) - { + public void addPitchAnimator(Angle begin, Angle end) { ((OrbitViewInputHandler) this.viewInputHandler).addPitchAnimator(begin, end); } - public void addHeadingPitchAnimator(Angle beginHeading, Angle endHeading, Angle beginPitch, Angle endPitch) - { + public void addHeadingPitchAnimator(Angle beginHeading, Angle endHeading, Angle beginPitch, Angle endPitch) { ((OrbitViewInputHandler) this.viewInputHandler).addHeadingPitchRollAnimator( - beginHeading, endHeading, beginPitch, endPitch, this.getRoll(), this.getRoll()); + beginHeading, endHeading, beginPitch, endPitch, this.getRoll(), this.getRoll()); } - public void addZoomAnimator(double zoomStart, double zoomEnd) - { + public void addZoomAnimator(double zoomStart, double zoomEnd) { ((OrbitViewInputHandler) this.viewInputHandler).addZoomAnimator( - zoomStart, zoomEnd); + zoomStart, zoomEnd); } - public void addFlyToZoomAnimator(Angle heading, Angle pitch, double zoomAmount) - { + public void addFlyToZoomAnimator(Angle heading, Angle pitch, double zoomAmount) { ((OrbitViewInputHandler) this.viewInputHandler).addFlyToZoomAnimator( - heading, pitch, zoomAmount); + heading, pitch, zoomAmount); } - public void addCenterAnimator(Position begin, Position end, boolean smoothed) - { + public void addCenterAnimator(Position begin, Position end, boolean smoothed) { ((OrbitViewInputHandler) this.viewInputHandler).addCenterAnimator(begin, end, smoothed); } - public void addCenterAnimator(Position begin, Position end, long lengthMillis, boolean smoothed) - { + public void addCenterAnimator(Position begin, Position end, long lengthMillis, boolean smoothed) { ((OrbitViewInputHandler) this.viewInputHandler).addCenterAnimator(begin, end, lengthMillis, smoothed); } } diff --git a/src/gov/nasa/worldwind/view/orbit/BasicOrbitViewLimits.java b/src/gov/nasa/worldwind/view/orbit/BasicOrbitViewLimits.java index 47d981185b..b84b2a0660 100644 --- a/src/gov/nasa/worldwind/view/orbit/BasicOrbitViewLimits.java +++ b/src/gov/nasa/worldwind/view/orbit/BasicOrbitViewLimits.java @@ -16,33 +16,35 @@ * @author dcollins * @version $Id: BasicOrbitViewLimits.java 2253 2014-08-22 16:33:46Z dcollins $ */ -public class BasicOrbitViewLimits extends BasicViewPropertyLimits implements OrbitViewLimits -{ +public class BasicOrbitViewLimits extends BasicViewPropertyLimits implements OrbitViewLimits { + protected Sector centerLocationLimits; protected double minCenterElevation; protected double maxCenterElevation; protected double minZoom; protected double maxZoom; - /** Creates a new BasicOrbitViewLimits with default limits. */ - public BasicOrbitViewLimits() - { + /** + * Creates a new BasicOrbitViewLimits with default limits. + */ + public BasicOrbitViewLimits() { this.reset(); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Sector getCenterLocationLimits() - { + public Sector getCenterLocationLimits() { return this.centerLocationLimits; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setCenterLocationLimits(Sector sector) - { - if (sector == null) - { + public void setCenterLocationLimits(Sector sector) { + if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -51,40 +53,45 @@ public void setCenterLocationLimits(Sector sector) this.centerLocationLimits = sector; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public double[] getCenterElevationLimits() - { - return new double[] {this.minCenterElevation, this.maxCenterElevation}; + public double[] getCenterElevationLimits() { + return new double[]{this.minCenterElevation, this.maxCenterElevation}; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setCenterElevationLimits(double minValue, double maxValue) - { + public void setCenterElevationLimits(double minValue, double maxValue) { this.minCenterElevation = minValue; this.maxCenterElevation = maxValue; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public double[] getZoomLimits() - { - return new double[] {this.minZoom, this.maxZoom}; + public double[] getZoomLimits() { + return new double[]{this.minZoom, this.maxZoom}; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void setZoomLimits(double minValue, double maxValue) - { + public void setZoomLimits(double minValue, double maxValue) { this.minZoom = minValue; this.maxZoom = maxValue; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public void reset() - { + public void reset() { super.reset(); this.centerLocationLimits = Sector.FULL_SPHERE; @@ -94,19 +101,18 @@ public void reset() this.maxZoom = Double.MAX_VALUE; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public Position limitCenterPosition(View view, Position position) - { - if (view == null) - { + public Position limitCenterPosition(View view, Position position) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -120,12 +126,12 @@ public Position limitCenterPosition(View view, Position position) return new Position(lat, lon, alt); } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override - public double limitZoom(View view, double value) - { - if (view == null) - { + public double limitZoom(View view, double value) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -137,10 +143,12 @@ public double limitZoom(View view, double value) if (this.is2DGlobe(view.getGlobe())) // limit zoom to ~360 degrees of visible longitude on 2D globes { double max2DZoom = Math.PI * view.getGlobe().getEquatorialRadius() / view.getFieldOfView().tanHalfAngle(); - if (minZoom > max2DZoom) + if (minZoom > max2DZoom) { minZoom = max2DZoom; - if (maxZoom > max2DZoom) + } + if (maxZoom > max2DZoom) { maxZoom = max2DZoom; + } } return WWMath.clamp(value, minZoom, maxZoom); @@ -149,7 +157,7 @@ public double limitZoom(View view, double value) /** * Applies the orbit view property limits to the specified view. * - * @param view the view that receives the property limits. + * @param view the view that receives the property limits. * @param viewLimits defines the view property limits. * * @throws IllegalArgumentException if any argument is null. @@ -158,16 +166,13 @@ public double limitZoom(View view, double value) * gov.nasa.worldwind.geom.Angle)}, etc. */ @SuppressWarnings("deprecation") - public static void applyLimits(OrbitView view, OrbitViewLimits viewLimits) - { - if (view == null) - { + public static void applyLimits(OrbitView view, OrbitViewLimits viewLimits) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewLimits == null) - { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -182,7 +187,7 @@ public static void applyLimits(OrbitView view, OrbitViewLimits viewLimits) /** * Clamp center location angles and elevation to the range specified in a limit object. * - * @param position position to clamp to the allowed range. + * @param position position to clamp to the allowed range. * @param viewLimits defines the center location and elevation limits. * @return The clamped position. * @@ -190,47 +195,41 @@ public static void applyLimits(OrbitView view, OrbitViewLimits viewLimits) * @deprecated Use {@link #limitCenterPosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ @SuppressWarnings("deprecation") - public static Position limitCenterPosition(Position position, OrbitViewLimits viewLimits) - { - if (position == null) - { + public static Position limitCenterPosition(Position position, OrbitViewLimits viewLimits) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewLimits == null) - { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new Position( - limitCenterLocation(position.getLatitude(), position.getLongitude(), viewLimits), - limitCenterElevation(position.getElevation(), viewLimits)); + limitCenterLocation(position.getLatitude(), position.getLongitude(), viewLimits), + limitCenterElevation(position.getElevation(), viewLimits)); } /** * Clamp center location angles to the range specified in a limit object. * - * @param latitude latitude angle to clamp to the allowed range. - * @param longitude longitude angle to clamp to the allowed range. + * @param latitude latitude angle to clamp to the allowed range. + * @param longitude longitude angle to clamp to the allowed range. * @param viewLimits defines the center location limits. * @return The clamped location. * * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitCenterPosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ - public static LatLon limitCenterLocation(Angle latitude, Angle longitude, OrbitViewLimits viewLimits) - { - if (latitude == null || longitude == null) - { + public static LatLon limitCenterLocation(Angle latitude, Angle longitude, OrbitViewLimits viewLimits) { + if (latitude == null || longitude == null) { String message = Logging.getMessage("nullValue.LatitudeOrLongitudeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (viewLimits == null) - { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -240,21 +239,15 @@ public static LatLon limitCenterLocation(Angle latitude, Angle longitude, OrbitV Angle newLatitude = latitude; Angle newLongitude = longitude; - if (latitude.compareTo(limits.getMinLatitude()) < 0) - { + if (latitude.compareTo(limits.getMinLatitude()) < 0) { newLatitude = limits.getMinLatitude(); - } - else if (latitude.compareTo(limits.getMaxLatitude()) > 0) - { + } else if (latitude.compareTo(limits.getMaxLatitude()) > 0) { newLatitude = limits.getMaxLatitude(); } - if (longitude.compareTo(limits.getMinLongitude()) < 0) - { + if (longitude.compareTo(limits.getMinLongitude()) < 0) { newLongitude = limits.getMinLongitude(); - } - else if (longitude.compareTo(limits.getMaxLongitude()) > 0) - { + } else if (longitude.compareTo(limits.getMaxLongitude()) > 0) { newLongitude = limits.getMaxLongitude(); } @@ -264,17 +257,15 @@ else if (longitude.compareTo(limits.getMaxLongitude()) > 0) /** * Clamp an center elevation to the range specified in a limit object. * - * @param value elevation to clamp to the allowed range. + * @param value elevation to clamp to the allowed range. * @param viewLimits defines the center elevation limits. * @return The clamped elevation. * * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitCenterPosition(gov.nasa.worldwind.View, gov.nasa.worldwind.geom.Position)} instead. */ - public static double limitCenterElevation(double value, OrbitViewLimits viewLimits) - { - if (viewLimits == null) - { + public static double limitCenterElevation(double value, OrbitViewLimits viewLimits) { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -283,12 +274,9 @@ public static double limitCenterElevation(double value, OrbitViewLimits viewLimi double[] limits = viewLimits.getCenterElevationLimits(); double newValue = value; - if (value < limits[0]) - { + if (value < limits[0]) { newValue = limits[0]; - } - else if (value > limits[1]) - { + } else if (value > limits[1]) { newValue = limits[1]; } @@ -298,17 +286,15 @@ else if (value > limits[1]) /** * Clamp an zoom distance to the range specified in a limit object. * - * @param value distance to clamp to the allowed range. + * @param value distance to clamp to the allowed range. * @param viewLimits defines the zoom distance limits. * @return The clamped zoom. * * @throws IllegalArgumentException if any argument is null. * @deprecated Use {@link #limitZoom(gov.nasa.worldwind.View, double)} instead. */ - public static double limitZoom(double value, OrbitViewLimits viewLimits) - { - if (viewLimits == null) - { + public static double limitZoom(double value, OrbitViewLimits viewLimits) { + if (viewLimits == null) { String message = Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -317,12 +303,9 @@ public static double limitZoom(double value, OrbitViewLimits viewLimits) double[] limits = viewLimits.getZoomLimits(); double newValue = value; - if (value < limits[0]) - { + if (value < limits[0]) { newValue = limits[0]; - } - else if (value > limits[1]) - { + } else if (value > limits[1]) { newValue = limits[1]; } @@ -332,9 +315,7 @@ else if (value > limits[1]) //**************************************************************// //******************** Restorable State ***********************// //**************************************************************// - - public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { super.getRestorableState(rs, context); rs.addStateValueAsSector(context, "centerLocationLimits", this.centerLocationLimits); @@ -344,38 +325,44 @@ public void getRestorableState(RestorableSupport rs, RestorableSupport.StateObje rs.addStateValueAsDouble(context, "maxZoom", this.maxZoom); } - public void restoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + public void restoreState(RestorableSupport rs, RestorableSupport.StateObject context) { super.restoreState(rs, context); Sector sector = rs.getStateValueAsSector(context, "centerLocationLimits"); - if (sector != null) + if (sector != null) { this.setCenterLocationLimits(sector); + } // Min and max center elevation. double[] minAndMaxValue = this.getCenterElevationLimits(); Double min = rs.getStateValueAsDouble(context, "minCenterElevation"); - if (min != null) + if (min != null) { minAndMaxValue[0] = min; + } Double max = rs.getStateValueAsDouble(context, "maxCenterElevation"); - if (max != null) + if (max != null) { minAndMaxValue[1] = max; + } - if (min != null || max != null) + if (min != null || max != null) { this.setCenterElevationLimits(minAndMaxValue[0], minAndMaxValue[1]); + } // Min and max zoom value. minAndMaxValue = this.getZoomLimits(); min = rs.getStateValueAsDouble(context, "minZoom"); - if (min != null) + if (min != null) { minAndMaxValue[0] = min; + } max = rs.getStateValueAsDouble(context, "maxZoom"); - if (max != null) + if (max != null) { minAndMaxValue[1] = max; + } - if (min != null || max != null) + if (min != null || max != null) { this.setZoomLimits(minAndMaxValue[0], minAndMaxValue[1]); + } } } diff --git a/src/gov/nasa/worldwind/view/orbit/FlatOrbitView.java b/src/gov/nasa/worldwind/view/orbit/FlatOrbitView.java index 45ae5a89c6..1b6b92d10b 100644 --- a/src/gov/nasa/worldwind/view/orbit/FlatOrbitView.java +++ b/src/gov/nasa/worldwind/view/orbit/FlatOrbitView.java @@ -11,36 +11,31 @@ * @author Patrick Muris * @version $Id: FlatOrbitView.java 2219 2014-08-11 21:39:44Z dcollins $ * @deprecated Use {@link gov.nasa.worldwind.view.orbit.BasicOrbitView} instead. BasicOrbitView implements the correct - * horizon distance and far clip distance when used with a 2D globe. + * horizon distance and far clip distance when used with a 2D globe. */ -public class FlatOrbitView extends BasicOrbitView -{ +public class FlatOrbitView extends BasicOrbitView { + // TODO: make configurable private static final double MINIMUM_FAR_DISTANCE = 100; - public FlatOrbitView() - { + public FlatOrbitView() { } - protected double computeHorizonDistance() - { + protected double computeHorizonDistance() { // Use the eye point from the last call to apply() to compute horizon distance. Vec4 eyePoint = this.getEyePoint(); return this.computeHorizonDistance(eyePoint); } - public double computeFarClipDistance() - { + public double computeFarClipDistance() { double far = this.computeHorizonDistance(this.getCurrentEyePoint()); return far < MINIMUM_FAR_DISTANCE ? MINIMUM_FAR_DISTANCE : far; } - protected double computeHorizonDistance(Vec4 eyePoint) - { + protected double computeHorizonDistance(Vec4 eyePoint) { double horizon = 0; // Compute largest distance to flat globe 'corners'. - if (this.globe != null && eyePoint != null) - { + if (this.globe != null && eyePoint != null) { double dist = 0; Vec4 p; // Use max distance to six points around the map diff --git a/src/gov/nasa/worldwind/view/orbit/FlyToOrbitViewAnimator.java b/src/gov/nasa/worldwind/view/orbit/FlyToOrbitViewAnimator.java index 4ad2652f76..6895287a43 100644 --- a/src/gov/nasa/worldwind/view/orbit/FlyToOrbitViewAnimator.java +++ b/src/gov/nasa/worldwind/view/orbit/FlyToOrbitViewAnimator.java @@ -16,8 +16,8 @@ * @author jym * @version $Id: FlyToOrbitViewAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class FlyToOrbitViewAnimator extends CompoundAnimator -{ +public class FlyToOrbitViewAnimator extends CompoundAnimator { + int altitudeMode; PositionAnimator centerAnimator; ViewElevationAnimator zoomAnimator; @@ -27,9 +27,8 @@ public class FlyToOrbitViewAnimator extends CompoundAnimator BasicOrbitView orbitView; public FlyToOrbitViewAnimator(OrbitView orbitView, Interpolator interpolator, int altitudeMode, - PositionAnimator centerAnimator, DoubleAnimator zoomAnimator, - AngleAnimator headingAnimator, AngleAnimator pitchAnimator, AngleAnimator rollAnimator) - { + PositionAnimator centerAnimator, DoubleAnimator zoomAnimator, + AngleAnimator headingAnimator, AngleAnimator pitchAnimator, AngleAnimator rollAnimator) { super(interpolator, centerAnimator, zoomAnimator, headingAnimator, pitchAnimator, rollAnimator); this.orbitView = (BasicOrbitView) orbitView; this.centerAnimator = centerAnimator; @@ -37,76 +36,72 @@ public FlyToOrbitViewAnimator(OrbitView orbitView, Interpolator interpolator, in this.headingAnimator = headingAnimator; this.pitchAnimator = pitchAnimator; this.rollAnimator = rollAnimator; - if (interpolator == null) - { + if (interpolator == null) { this.interpolator = new ScheduledInterpolator(10000); } this.altitudeMode = altitudeMode; } public static FlyToOrbitViewAnimator createFlyToOrbitViewAnimator( - OrbitView orbitView, - Position beginCenterPos, Position endCenterPos, - Angle beginHeading, Angle endHeading, - Angle beginPitch, Angle endPitch, - double beginZoom, double endZoom, long timeToMove, int altitudeMode) - { + OrbitView orbitView, + Position beginCenterPos, Position endCenterPos, + Angle beginHeading, Angle endHeading, + Angle beginPitch, Angle endPitch, + double beginZoom, double endZoom, long timeToMove, int altitudeMode) { OnSurfacePositionAnimator centerAnimator = new OnSurfacePositionAnimator(orbitView.getGlobe(), - new ScheduledInterpolator(timeToMove), - beginCenterPos, endCenterPos, - OrbitViewPropertyAccessor.createCenterPositionAccessor( - orbitView), altitudeMode); + new ScheduledInterpolator(timeToMove), + beginCenterPos, endCenterPos, + OrbitViewPropertyAccessor.createCenterPositionAccessor( + orbitView), altitudeMode); // Create an elevation animator with ABSOLUTE altitude mode because the OrbitView altitude mode applies to the // center position, not the zoom. ViewElevationAnimator zoomAnimator = new ViewElevationAnimator(orbitView.getGlobe(), - beginZoom, endZoom, beginCenterPos, endCenterPos, WorldWind.ABSOLUTE, - OrbitViewPropertyAccessor.createZoomAccessor(orbitView)); + beginZoom, endZoom, beginCenterPos, endCenterPos, WorldWind.ABSOLUTE, + OrbitViewPropertyAccessor.createZoomAccessor(orbitView)); centerAnimator.useMidZoom = zoomAnimator.getUseMidZoom(); AngleAnimator headingAnimator = new AngleAnimator( - new ScheduledInterpolator(timeToMove), - beginHeading, endHeading, - ViewPropertyAccessor.createHeadingAccessor(orbitView)); + new ScheduledInterpolator(timeToMove), + beginHeading, endHeading, + ViewPropertyAccessor.createHeadingAccessor(orbitView)); AngleAnimator pitchAnimator = new AngleAnimator( - new ScheduledInterpolator(timeToMove), - beginPitch, endPitch, - ViewPropertyAccessor.createPitchAccessor(orbitView)); + new ScheduledInterpolator(timeToMove), + beginPitch, endPitch, + ViewPropertyAccessor.createPitchAccessor(orbitView)); FlyToOrbitViewAnimator panAnimator = new FlyToOrbitViewAnimator(orbitView, - new ScheduledInterpolator(timeToMove), altitudeMode, centerAnimator, - zoomAnimator, headingAnimator, pitchAnimator, null); + new ScheduledInterpolator(timeToMove), altitudeMode, centerAnimator, + zoomAnimator, headingAnimator, pitchAnimator, null); return (panAnimator); } - protected static class OnSurfacePositionAnimator extends PositionAnimator - { + protected static class OnSurfacePositionAnimator extends PositionAnimator { + Globe globe; int altitudeMode; boolean useMidZoom = true; public OnSurfacePositionAnimator(Globe globe, Interpolator interpolator, - Position begin, - Position end, - PropertyAccessor.PositionAccessor propertyAccessor, int altitudeMode) - { + Position begin, + Position end, + PropertyAccessor.PositionAccessor propertyAccessor, int altitudeMode) { super(interpolator, begin, end, propertyAccessor); this.globe = globe; this.altitudeMode = altitudeMode; } @Override - protected Position nextPosition(double interpolant) - { + protected Position nextPosition(double interpolant) { final int MAX_SMOOTHING = 1; final double CENTER_START = this.useMidZoom ? 0.2 : 0.0; final double CENTER_STOP = this.useMidZoom ? 0.8 : 0.8; double latLonInterpolant = AnimationSupport.basicInterpolant(interpolant, CENTER_START, CENTER_STOP, - MAX_SMOOTHING); + MAX_SMOOTHING); // Invoke the standard next position functionality. Position pos = super.nextPosition(latLonInterpolant); @@ -118,20 +113,16 @@ protected Position nextPosition(double interpolant) double endElevation = 0.0; boolean overrideEndElevation = false; - if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND) { overrideEndElevation = true; endElevation = this.globe.getElevation(getEnd().getLatitude(), getEnd().getLongitude()); - } - else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) - { + } else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) { overrideEndElevation = true; endElevation = this.globe.getElevation(getEnd().getLatitude(), getEnd().getLongitude()) - + getEnd().getAltitude(); + + getEnd().getAltitude(); } - if (overrideEndElevation) - { + if (overrideEndElevation) { LatLon ll = pos; // Use interpolated lat/lon. double e1 = getBegin().getElevation(); pos = new Position(ll, (1 - latLonInterpolant) * e1 + latLonInterpolant * endElevation); @@ -142,10 +133,8 @@ else if (this.altitudeMode == WorldWind.RELATIVE_TO_GROUND) } @Override - public void stop() - { - if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND) - { + public void stop() { + if (this.altitudeMode == WorldWind.CLAMP_TO_GROUND) { this.orbitView.setViewOutOfFocus(true); } super.stop(); diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitView.java b/src/gov/nasa/worldwind/view/orbit/OrbitView.java index 964af5d7af..5bbfbd92f7 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitView.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitView.java @@ -12,69 +12,72 @@ * @author dcollins * @version $Id: OrbitView.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface OrbitView extends View -{ - /** - * Returns whether the this View will detect collisions with other objects, - * such as the surface geometry. If true, implementations may also automatically - * resolve any detected collisions. +public interface OrbitView extends View { + + /** + * Returns whether the this View will detect collisions with other objects, such as the surface + * geometry. If true, implementations may also automatically resolve any detected collisions. * * @return true If this View will detect collisions; false otherwise. */ boolean isDetectCollisions(); /** - * Sets whether or not this View will detect collisions with other objects, - * such as the surface geometry. If detectCollisions is true, implementations may also automatically - * resolve any detected collisions. + * Sets whether or not this View will detect collisions with other objects, such as the surface + * geometry. If detectCollisions is true, implementations may also automatically resolve any detected + * collisions. * * @param detectCollisions If true, this View will resolve collisions; otherwise this - * View will ignore collisions. + * View will ignore collisions. */ void setDetectCollisions(boolean detectCollisions); /** - * Returns whether or not a collision has occurred since the last call to hadCollisions. - * If {@link #isDetectCollisions} is false, collisions will not be detected and - * hadCollisions will always return false. + * Returns whether or not a collision has occurred since the last call to hadCollisions. If + * {@link #isDetectCollisions} is false, collisions will not be detected and hadCollisions will always + * return false. * * @return true if a collision has occurred since the last call; false otherwise. */ boolean hadCollisions(); /** - * Get the center position of the OrbitView. The center position is used as the point about which the - * heading and pitch rotate. It is defined by the intersection of a ray from the eye position through the - * center of the viewport with the surface of the globe. + * Get the center position of the OrbitView. The center position is used as the point about which the heading and + * pitch rotate. It is defined by the intersection of a ray from the eye position through the center of the viewport + * with the surface of the globe. + * * @return the center position. */ Position getCenterPosition(); /** - * Sets the center position of the OrbitView. The center position is used as the point about which the - * heading and pitch rotate. It is defined by the intersection of a ray from the eye position through the - * center of the viewport with the surface of the globe. + * Sets the center position of the OrbitView. The center position is used as the point about which the heading and + * pitch rotate. It is defined by the intersection of a ray from the eye position through the center of the viewport + * with the surface of the globe. + * * @param center The desired center position. */ void setCenterPosition(Position center); /** - * Get the zoom value for the OrbitView. The zoom value is the distance between the eye - * position and the center position. + * Get the zoom value for the OrbitView. The zoom value is the distance between the eye position and the center + * position. + * * @return the zoom value */ double getZoom(); /** - * Set the zoom value for the OrbitVeiw. The zoom value is the distance between the eye - * position and the center position. + * Set the zoom value for the OrbitVeiw. The zoom value is the distance between the eye position and the center + * position. + * * @param zoom The desired zoom value. */ void setZoom(double zoom); /** - * Get the limits for this OrbitView. OrbitView has state values that augment the state values of a {@link View}. - * Specifically, zoom and center position. {@link OrbitViewLimits} enables the limiting of those values in addition + * Get the limits for this OrbitView. OrbitView has state values that augment the state values of a {@link View}. + * Specifically, zoom and center position. {@link OrbitViewLimits} enables the limiting of those values in addition * the the derived {@link gov.nasa.worldwind.view.BasicViewPropertyLimits} state. * * @return The active view limits. @@ -82,9 +85,10 @@ public interface OrbitView extends View OrbitViewLimits getOrbitViewLimits(); /** - * Set the limits for this OrbitView. OrbitView has state values that augment the state values of a {@link View}. - * Specifically, zoom and center position. {@link OrbitViewLimits} enables the limiting of those values in addition + * Set the limits for this OrbitView. OrbitView has state values that augment the state values of a {@link View}. + * Specifically, zoom and center position. {@link OrbitViewLimits} enables the limiting of those values in addition * the the derived {@link gov.nasa.worldwind.view.BasicViewPropertyLimits} state. + * * @param limits The desired limits. */ void setOrbitViewLimits(OrbitViewLimits limits); @@ -92,8 +96,10 @@ public interface OrbitView extends View /** * Implementations are expected to determines if the OrbitView can set the center of rotation for heading and pitch * changes to the viewport center intersection with the globe surface via a call to {@link #focusOnViewportCenter}. + * * @return true if the OrbitView implementation can focus on the viewport center. - **/ + * + */ boolean canFocusOnViewportCenter(); /** diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitViewCenterAnimator.java b/src/gov/nasa/worldwind/view/orbit/OrbitViewCenterAnimator.java index de5fe68c95..e6464abc6f 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitViewCenterAnimator.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitViewCenterAnimator.java @@ -10,39 +10,36 @@ import gov.nasa.worldwind.util.*; /** - * A position animator that has the ability to adjust the view to focus on the - * terrain when it is stopped. + * A position animator that has the ability to adjust the view to focus on the terrain when it is stopped. * * @author jym * @version $Id: OrbitViewCenterAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OrbitViewCenterAnimator extends MoveToPositionAnimator -{ +public class OrbitViewCenterAnimator extends MoveToPositionAnimator { + private BasicOrbitView orbitView; boolean endCenterOnSurface; + public OrbitViewCenterAnimator(BasicOrbitView orbitView, Position startPosition, Position endPosition, - double smoothing, PropertyAccessor.PositionAccessor propertyAccessor, boolean endCenterOnSurface) - { + double smoothing, PropertyAccessor.PositionAccessor propertyAccessor, boolean endCenterOnSurface) { super(startPosition, endPosition, smoothing, propertyAccessor); this.endCenterOnSurface = endCenterOnSurface; this.orbitView = orbitView; } - public Position nextPosition(double interpolant) - { + public Position nextPosition(double interpolant) { Position nextPosition = this.end; Position curCenter = this.propertyAccessor.getPosition(); double latlonDifference = LatLon.greatCircleDistance(nextPosition, curCenter).degrees; double elevDifference = Math.abs(nextPosition.getElevation() - curCenter.getElevation()); boolean stopMoving = Math.max(latlonDifference, elevDifference) < this.positionMinEpsilon; - if (!stopMoving) - { + if (!stopMoving) { interpolant = 1 - this.smoothing; nextPosition = new Position( - Angle.mix(interpolant, curCenter.getLatitude(), this.end.getLatitude()), - Angle.mix(interpolant, curCenter.getLongitude(), this.end.getLongitude()), - (1 - interpolant) * curCenter.getElevation() + interpolant * this.end.getElevation()); + Angle.mix(interpolant, curCenter.getLatitude(), this.end.getLatitude()), + Angle.mix(interpolant, curCenter.getLongitude(), this.end.getLongitude()), + (1 - interpolant) * curCenter.getElevation() + interpolant * this.end.getElevation()); } //TODO: What do we do about collisions? /* @@ -65,32 +62,31 @@ public Position nextPosition(double interpolant) Logging.logger().log(java.util.logging.Level.SEVERE, message, e); stopMoving = true; } - */ + */ // If target is close, cancel future value changes. - if (stopMoving) - { + if (stopMoving) { this.stop(); this.propertyAccessor.setPosition(nextPosition); - if (endCenterOnSurface) + if (endCenterOnSurface) { this.orbitView.setViewOutOfFocus(true); - return(null); + } + return (null); } return nextPosition; } - protected void setImpl(double interpolant) - { + protected void setImpl(double interpolant) { Position newValue = this.nextPosition(interpolant); - if (newValue == null) - return; + if (newValue == null) { + return; + } this.propertyAccessor.setPosition(newValue); this.orbitView.setViewOutOfFocus(true); } - public void stop() - { + public void stop() { super.stop(); } } diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitViewCollisionSupport.java b/src/gov/nasa/worldwind/view/orbit/OrbitViewCollisionSupport.java index c0541ce20e..2891bcb31d 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitViewCollisionSupport.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitViewCollisionSupport.java @@ -17,25 +17,21 @@ * @author dcollins * @version $Id: OrbitViewCollisionSupport.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OrbitViewCollisionSupport -{ +public class OrbitViewCollisionSupport { + private double collisionThreshold; private int numIterations; - public OrbitViewCollisionSupport() - { + public OrbitViewCollisionSupport() { setNumIterations(1); } - public double getCollisionThreshold() - { + public double getCollisionThreshold() { return this.collisionThreshold; } - public void setCollisionThreshold(double collisionThreshold) - { - if (collisionThreshold < 0) - { + public void setCollisionThreshold(double collisionThreshold) { + if (collisionThreshold < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", collisionThreshold); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -44,15 +40,12 @@ public void setCollisionThreshold(double collisionThreshold) this.collisionThreshold = collisionThreshold; } - public int getNumIterations() - { + public int getNumIterations() { return this.numIterations; } - public void setNumIterations(int numIterations) - { - if (numIterations < 1) - { + public void setNumIterations(int numIterations) { + if (numIterations < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", numIterations); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -61,42 +54,36 @@ public void setNumIterations(int numIterations) this.numIterations = numIterations; } - public boolean isColliding(OrbitView orbitView, double nearDistance, DrawContext dc) - { - if (orbitView == null) - { + public boolean isColliding(OrbitView orbitView, double nearDistance, DrawContext dc) { + if (orbitView == null) { String message = Logging.getMessage("nullValue.OrbitViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (nearDistance < 0) - { + if (nearDistance < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", nearDistance); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Globe globe = dc.getGlobe(); - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Matrix modelviewInv = getModelviewInverse(globe, - orbitView.getCenterPosition(), orbitView.getHeading(), orbitView.getPitch(), orbitView.getRoll(), - orbitView.getZoom()); - if (modelviewInv != null) - { + orbitView.getCenterPosition(), orbitView.getHeading(), orbitView.getPitch(), orbitView.getRoll(), + orbitView.getZoom()); + if (modelviewInv != null) { // OrbitView is colliding when its eye point is below the collision threshold. double heightAboveSurface = computeViewHeightAboveSurface(dc, modelviewInv, - orbitView.getFieldOfView(), orbitView.getViewport(), nearDistance); + orbitView.getFieldOfView(), orbitView.getViewport(), nearDistance); return heightAboveSurface < this.collisionThreshold; } @@ -104,29 +91,24 @@ public boolean isColliding(OrbitView orbitView, double nearDistance, DrawContext } public Position computeCenterPositionToResolveCollision(BasicOrbitView orbitView, double nearDistance, - DrawContext dc) - { - if (orbitView == null) - { + DrawContext dc) { + if (orbitView == null) { String message = Logging.getMessage("nullValue.OrbitViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (nearDistance < 0) - { + if (nearDistance < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", nearDistance); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Globe globe = dc.getGlobe(); - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -134,21 +116,18 @@ public Position computeCenterPositionToResolveCollision(BasicOrbitView orbitView Position newCenter = null; - for (int i = 0; i < this.numIterations; i++) - { + for (int i = 0; i < this.numIterations; i++) { Matrix modelviewInv = getModelviewInverse(globe, - newCenter != null ? newCenter : orbitView.getCenterPosition(), - orbitView.getHeading(), orbitView.getPitch(), orbitView.getRoll(), orbitView.getZoom()); - if (modelviewInv != null) - { + newCenter != null ? newCenter : orbitView.getCenterPosition(), + orbitView.getHeading(), orbitView.getPitch(), orbitView.getRoll(), orbitView.getZoom()); + if (modelviewInv != null) { double heightAboveSurface = computeViewHeightAboveSurface(dc, modelviewInv, - orbitView.getFieldOfView(), orbitView.getViewport(), nearDistance); + orbitView.getFieldOfView(), orbitView.getViewport(), nearDistance); double adjustedHeight = heightAboveSurface - this.collisionThreshold; - if (adjustedHeight < 0) - { + if (adjustedHeight < 0) { newCenter = new Position( - newCenter != null ? newCenter : orbitView.getCenterPosition(), - (newCenter != null ? newCenter.getElevation() : orbitView.getCenterPosition().getElevation()) + newCenter != null ? newCenter : orbitView.getCenterPosition(), + (newCenter != null ? newCenter.getElevation() : orbitView.getCenterPosition().getElevation()) - adjustedHeight); } } @@ -157,29 +136,24 @@ public Position computeCenterPositionToResolveCollision(BasicOrbitView orbitView return newCenter; } - public Angle computePitchToResolveCollision(BasicOrbitView orbitView, double nearDistance, DrawContext dc) - { - if (orbitView == null) - { + public Angle computePitchToResolveCollision(BasicOrbitView orbitView, double nearDistance, DrawContext dc) { + if (orbitView == null) { String message = Logging.getMessage("nullValue.OrbitViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (nearDistance < 0) - { + if (nearDistance < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", nearDistance); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc == null) - { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Globe globe = dc.getGlobe(); - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.DrawingContextGlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -187,34 +161,29 @@ public Angle computePitchToResolveCollision(BasicOrbitView orbitView, double nea Angle newPitch = null; - for (int i = 0; i < this.numIterations; i++) - { + for (int i = 0; i < this.numIterations; i++) { Matrix modelviewInv = getModelviewInverse(globe, - orbitView.getCenterPosition(), orbitView.getHeading(), - newPitch != null ? newPitch : orbitView.getPitch(), orbitView.getRoll(), - orbitView.getZoom()); - if (modelviewInv != null) - { + orbitView.getCenterPosition(), orbitView.getHeading(), + newPitch != null ? newPitch : orbitView.getPitch(), orbitView.getRoll(), + orbitView.getZoom()); + if (modelviewInv != null) { double heightAboveSurface = computeViewHeightAboveSurface(dc, modelviewInv, - orbitView.getFieldOfView(), orbitView.getViewport(), nearDistance); + orbitView.getFieldOfView(), orbitView.getViewport(), nearDistance); double adjustedHeight = heightAboveSurface - this.collisionThreshold; - if (adjustedHeight < 0) - { + if (adjustedHeight < 0) { Vec4 eyePoint = getEyePoint(modelviewInv); Vec4 centerPoint = globe.computePointFromPosition(orbitView.getCenterPosition()); - if (eyePoint != null && centerPoint != null) - { + if (eyePoint != null && centerPoint != null) { Position eyePos = globe.computePositionFromPoint(eyePoint); // Compute the eye point required to resolve the collision. Vec4 newEyePoint = globe.computePointFromPosition(eyePos.getLatitude(), eyePos.getLongitude(), - eyePos.getElevation() - adjustedHeight); + eyePos.getElevation() - adjustedHeight); // Compute the pitch that corresponds with the elevation of the eye point // (but not necessarily the latitude and longitude). Vec4 normalAtCenter = globe.computeSurfaceNormalAtPoint(centerPoint); Vec4 newEye_sub_center = newEyePoint.subtract3(centerPoint).normalize3(); double dot = normalAtCenter.dot3(newEye_sub_center); - if (dot >= -1 || dot <= 1) - { + if (dot >= -1 || dot <= 1) { double angle = Math.acos(dot); newPitch = Angle.fromRadians(angle); } @@ -227,79 +196,73 @@ public Angle computePitchToResolveCollision(BasicOrbitView orbitView, double nea } private double computeViewHeightAboveSurface(DrawContext dc, Matrix modelviewInv, - Angle fieldOfView, java.awt.Rectangle viewport, double nearDistance) - { + Angle fieldOfView, java.awt.Rectangle viewport, double nearDistance) { double height = Double.POSITIVE_INFINITY; - if (dc != null && modelviewInv != null && fieldOfView != null && viewport != null && nearDistance >= 0) - { + if (dc != null && modelviewInv != null && fieldOfView != null && viewport != null && nearDistance >= 0) { Vec4 eyePoint = getEyePoint(modelviewInv); - if (eyePoint != null) - { + if (eyePoint != null) { double eyeHeight = computePointHeightAboveSurface(dc, eyePoint); - if (eyeHeight < height) + if (eyeHeight < height) { height = eyeHeight; + } } Vec4 nearPoint = getPointOnNearPlane(modelviewInv, fieldOfView, viewport, nearDistance); - if (nearPoint != null) - { + if (nearPoint != null) { double nearHeight = computePointHeightAboveSurface(dc, nearPoint); - if (nearHeight < height) + if (nearHeight < height) { height = nearHeight; + } } } return height; } - private double computePointHeightAboveSurface(DrawContext dc, Vec4 point) - { + private double computePointHeightAboveSurface(DrawContext dc, Vec4 point) { double height = Double.POSITIVE_INFINITY; - if (dc != null && dc.getGlobe() != null && point != null) - { + if (dc != null && dc.getGlobe() != null && point != null) { Globe globe = dc.getGlobe(); Position position = globe.computePositionFromPoint(point); Position surfacePosition = null; // Look for the surface geometry point at 'position'. Vec4 pointOnGlobe = dc.getPointOnTerrain(position.getLatitude(), position.getLongitude()); - if (pointOnGlobe != null) + if (pointOnGlobe != null) { surfacePosition = globe.computePositionFromPoint(pointOnGlobe); + } // Fallback to using globe elevation values. - if (surfacePosition == null) + if (surfacePosition == null) { surfacePosition = new Position(position, - globe.getElevation(position.getLatitude(), position.getLongitude()) * dc.getVerticalExaggeration()); + globe.getElevation(position.getLatitude(), position.getLongitude()) * dc.getVerticalExaggeration()); + } height = position.getElevation() - surfacePosition.getElevation(); } return height; } private Matrix getModelviewInverse(Globe globe, - Position centerPosition, Angle heading, Angle pitch, Angle roll, double zoom) - { - if (globe != null && centerPosition != null && heading != null && pitch != null) - { + Position centerPosition, Angle heading, Angle pitch, Angle roll, double zoom) { + if (globe != null && centerPosition != null && heading != null && pitch != null) { Matrix modelview = OrbitViewInputSupport.computeTransformMatrix(globe, - centerPosition, heading, pitch, roll, zoom); - if (modelview != null) + centerPosition, heading, pitch, roll, zoom); + if (modelview != null) { return modelview.getInverse(); + } } return null; } - private Vec4 getEyePoint(Matrix modelviewInv) - { + private Vec4 getEyePoint(Matrix modelviewInv) { return modelviewInv != null ? Vec4.UNIT_W.transformBy4(modelviewInv) : null; } private Vec4 getPointOnNearPlane(Matrix modelviewInv, Angle fieldOfView, java.awt.Rectangle viewport, - double nearDistance) - { - if (modelviewInv != null && fieldOfView != null && viewport != null && nearDistance >= 0) - { + double nearDistance) { + if (modelviewInv != null && fieldOfView != null && viewport != null && nearDistance >= 0) { // If either either the viewport width or height is zero, then fall back to an aspect ratio of 1. // Otherwise, compute the standard aspect ratio. - double aspect = (viewport.getWidth() <= 0 || viewport.getHeight() <= 0) ? - 1d : (viewport.getHeight() / viewport.getWidth()); + double aspect = (viewport.getWidth() <= 0 || viewport.getHeight() <= 0) + ? 1d : (viewport.getHeight() / viewport.getWidth()); double nearClipHeight = 2 * aspect * nearDistance * fieldOfView.tanHalfAngle(); // Computes the point on the bottom center of the near clip plane. Vec4 nearClipVec = new Vec4(0, -nearClipHeight / 2.0, -nearDistance, 1); diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitViewEyePointAnimator.java b/src/gov/nasa/worldwind/view/orbit/OrbitViewEyePointAnimator.java index 833fe00ba7..270f485cbb 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitViewEyePointAnimator.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitViewEyePointAnimator.java @@ -15,8 +15,8 @@ * @author dcollins * @version $Id: OrbitViewEyePointAnimator.java 2204 2014-08-07 23:35:03Z dcollins $ */ -public class OrbitViewEyePointAnimator implements Animator -{ +public class OrbitViewEyePointAnimator implements Animator { + protected static final double STOP_DISTANCE = 0.1; protected Globe globe; @@ -25,24 +25,20 @@ public class OrbitViewEyePointAnimator implements Animator protected double smoothing; protected boolean hasNext; - public OrbitViewEyePointAnimator(Globe globe, BasicOrbitView view, Vec4 eyePoint, double smoothing) - { - if (globe == null) - { + public OrbitViewEyePointAnimator(Globe globe, BasicOrbitView view, Vec4 eyePoint, double smoothing) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (view == null) - { + if (view == null) { String msg = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (eyePoint == null) - { + if (eyePoint == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -55,71 +51,58 @@ public OrbitViewEyePointAnimator(Globe globe, BasicOrbitView view, Vec4 eyePoint this.hasNext = true; } - public void setEyePoint(Vec4 eyePoint) - { + public void setEyePoint(Vec4 eyePoint) { this.eyePoint = eyePoint; } @Override - public void start() - { + public void start() { this.hasNext = true; } @Override - public void stop() - { + public void stop() { this.hasNext = false; } @Override - public boolean hasNext() - { + public boolean hasNext() { return this.hasNext; } @Override - public void set(double interpolant) - { + public void set(double interpolant) { // Intentionally left blank. } @Override - public void next() - { + public void next() { Matrix modelview = this.view.getModelviewMatrix(); Vec4 point = modelview.extractEyePoint(); - if (point.distanceTo3(this.eyePoint) > STOP_DISTANCE) - { + if (point.distanceTo3(this.eyePoint) > STOP_DISTANCE) { point = Vec4.mix3(1 - this.smoothing, point, this.eyePoint); setEyePoint(this.globe, this.view, point); - } - else - { + } else { setEyePoint(this.globe, this.view, this.eyePoint); this.stop(); } } - public static void setEyePoint(Globe globe, BasicOrbitView view, Vec4 newEyePoint) - { - if (globe == null) - { + public static void setEyePoint(Globe globe, BasicOrbitView view, Vec4 newEyePoint) { + if (globe == null) { String msg = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (view == null) - { + if (view == null) { String msg = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if (newEyePoint == null) - { + if (newEyePoint == null) { String msg = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitViewInputHandler.java b/src/gov/nasa/worldwind/view/orbit/OrbitViewInputHandler.java index c82b844735..ce4567dfba 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitViewInputHandler.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitViewInputHandler.java @@ -22,8 +22,8 @@ * @author dcollins * @version $Id: OrbitViewInputHandler.java 2253 2014-08-22 16:33:46Z dcollins $ */ -public class OrbitViewInputHandler extends BasicViewInputHandler -{ +public class OrbitViewInputHandler extends BasicViewInputHandler { + protected AnimationController gotoAnimControl = new AnimationController(); protected AnimationController uiAnimControl = new AnimationController(); protected static final String VIEW_ANIM_HEADING = "ViewAnimHeading"; @@ -39,13 +39,14 @@ public class OrbitViewInputHandler extends BasicViewInputHandler public static final String ORBITVIEW_RESET_ROLL = "gov.nasa.worldwind.ViewResetRoll"; - /** Action handler to reset roll. */ - public class ResetRollActionListener extends ViewInputActionHandler - { + /** + * Action handler to reset roll. + */ + public class ResetRollActionListener extends ViewInputActionHandler { + @Override public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, - java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) - { + java.awt.event.MouseEvent mouseEvent, ViewInputAttributes.ActionAttributes viewAction) { onResetRoll(viewAction); return true; } @@ -54,46 +55,43 @@ public boolean inputActionPerformed(AbstractViewInputHandler inputHandler, /** * Create a new input handler. */ - public OrbitViewInputHandler() - { + public OrbitViewInputHandler() { this.initializeInputHandlers(); } /** * Initialize input handlers specific to ObitView. */ - protected void initializeInputHandlers() - { + protected void initializeInputHandlers() { // OrbitView allows application controllers to set the view's roll, but it does not provide user controls to // change the roll. Add an input handler that will reset the roll to zero when the user clicks the mouse so that // the user can easily get back to normal roll state. // Reset roll on mouse click - ViewInputAttributes.ActionAttributes.MouseAction[] resetRollMouseEvents = - { - new ViewInputAttributes.ActionAttributes.MouseAction(MouseEvent.BUTTON1_DOWN_MASK) - }; + ViewInputAttributes.ActionAttributes.MouseAction[] resetRollMouseEvents + = { + new ViewInputAttributes.ActionAttributes.MouseAction(MouseEvent.BUTTON1_DOWN_MASK) + }; // Set up the input attributes for reset roll this.getAttributes().setMouseActionAttributes( - ORBITVIEW_RESET_ROLL, // Action to map to mouse button - 0, // Modifiers, none in this case - ViewInputAttributes.ActionAttributes.ActionTrigger.ON_PRESS, // The event that triggers the action - resetRollMouseEvents, // Input actions to map to the behavior - ViewInputAttributes.DEFAULT_KEY_ROLL_MIN_VALUE, - ViewInputAttributes.DEFAULT_KEY_ROLL_MAX_VALUE, - false, // Disable smoothing - 0.0); // Smoothing value + ORBITVIEW_RESET_ROLL, // Action to map to mouse button + 0, // Modifiers, none in this case + ViewInputAttributes.ActionAttributes.ActionTrigger.ON_PRESS, // The event that triggers the action + resetRollMouseEvents, // Input actions to map to the behavior + ViewInputAttributes.DEFAULT_KEY_ROLL_MIN_VALUE, + ViewInputAttributes.DEFAULT_KEY_ROLL_MAX_VALUE, + false, // Disable smoothing + 0.0); // Smoothing value // Add the action listener - ViewInputAttributes.ActionAttributes actionAttrs = - this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( - ORBITVIEW_RESET_ROLL); + ViewInputAttributes.ActionAttributes actionAttrs + = this.getAttributes().getActionMap(ViewInputAttributes.DEVICE_MOUSE).getActionAttributes( + ORBITVIEW_RESET_ROLL); actionAttrs.setMouseActionListener(new ResetRollActionListener()); } - protected boolean isNonContinous2DGlobe() - { + protected boolean isNonContinous2DGlobe() { Globe globe = this.getWorldWindow().getModel().getGlobe(); return globe instanceof Globe2D && !((Globe2D) globe).isContinuous(); } @@ -101,10 +99,8 @@ protected boolean isNonContinous2DGlobe() //**************************************************************// //******************** View Change Events ********************// //**************************************************************// - protected void onMoveTo(Position focalPosition, ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.ActionAttributes actionAttribs) { this.stopAllAnimators(); View view = this.getView(); @@ -113,21 +109,20 @@ protected void onMoveTo(Position focalPosition, ViewInputAttributes.DeviceAttrib return; } - if (this.isNonContinous2DGlobe()) - { + if (this.isNonContinous2DGlobe()) { this.onMoveTo2D(focalPosition, deviceAttributes, actionAttribs); return; } - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { // We're treating a speed parameter as smoothing here. A greater speed results in greater smoothing and // slower response. Therefore the min speed used at lower altitudes ought to be *greater* than the max // speed used at higher altitudes. //double[] values = actionAttribs.getValues(); double smoothing = this.getScaleValueZoom(actionAttribs); - if (!actionAttribs.isEnableSmoothing()) + if (!actionAttribs.isEnableSmoothing()) { smoothing = 0.0; + } OrbitViewCenterAnimator centerAnimator = new OrbitViewCenterAnimator((BasicOrbitView) this.getView(), view.getEyePosition(), focalPosition, smoothing, @@ -139,18 +134,16 @@ protected void onMoveTo(Position focalPosition, ViewInputAttributes.DeviceAttrib @SuppressWarnings("UnusedParameters") protected void onMoveTo2D(Position focalPosition, ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); - if (view == null || !(view instanceof BasicOrbitView)) - { + if (view == null || !(view instanceof BasicOrbitView)) { return; } Globe globe = this.getWorldWindow().getModel().getGlobe(); BasicOrbitView orbitView = (BasicOrbitView) view; Matrix modelview = OrbitViewInputSupport.computeTransformMatrix(globe, focalPosition, orbitView.getHeading(), - orbitView.getPitch(), orbitView.getRoll(), orbitView.getZoom()); + orbitView.getPitch(), orbitView.getRoll(), orbitView.getZoom()); Vec4 eyePoint = modelview.extractEyePoint(); double smoothing = actionAttribs.isEnableSmoothing() ? this.getScaleValueZoom(actionAttribs) : 0; @@ -159,8 +152,7 @@ protected void onMoveTo2D(Position focalPosition, ViewInputAttributes.DeviceAttr } protected void onHorizontalTranslateAbs(Angle latitudeChange, Angle longitudeChange, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.ActionAttributes actionAttribs) { this.stopGoToAnimators(); this.stopUserInputAnimators(VIEW_ANIM_HEADING, VIEW_ANIM_PITCH, VIEW_ANIM_ZOOM, VIEW_ANIM_EYE); @@ -170,13 +162,11 @@ protected void onHorizontalTranslateAbs(Angle latitudeChange, Angle longitudeCha return; } - if (latitudeChange.equals(Angle.ZERO) && longitudeChange.equals(Angle.ZERO)) - { + if (latitudeChange.equals(Angle.ZERO) && longitudeChange.equals(Angle.ZERO)) { return; } - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { double latDegrees = latitudeChange.degrees; double lonDegrees = longitudeChange.degrees; @@ -189,46 +179,37 @@ protected void onHorizontalTranslateAbs(Angle latitudeChange, Angle longitudeCha } protected void onHorizontalTranslateRel(double forwardInput, double sideInput, - double totalForwardInput, double totalSideInput, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes) - { - if (this.isNonContinous2DGlobe()) - { + double totalForwardInput, double totalSideInput, + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes) { + if (this.isNonContinous2DGlobe()) { this.onHorizontalTranslate2D(forwardInput, sideInput, totalForwardInput, totalSideInput, deviceAttributes, - actionAttributes); + actionAttributes); return; } this.stopGoToAnimators(); this.stopUserInputAnimators(VIEW_ANIM_HEADING, VIEW_ANIM_PITCH, VIEW_ANIM_ZOOM, VIEW_ANIM_EYE); - if (actionAttributes.getMouseActions() != null) - { + if (actionAttributes.getMouseActions() != null) { // Normalize the forward and right magnitudes. double length = Math.sqrt(forwardInput * forwardInput + sideInput * sideInput); - if (length > 0.0) - { + if (length > 0.0) { forwardInput /= length; sideInput /= length; } Point point = constrainToSourceBounds(getMousePoint(), getWorldWindow()); Point lastPoint = constrainToSourceBounds(getLastMousePoint(), getWorldWindow()); - if (getSelectedPosition() == null) - { + if (getSelectedPosition() == null) { // Compute the current selected position if none exists. This happens if the user starts dragging when // the cursor is off the globe, then drags the cursor onto the globe. setSelectedPosition(computeSelectedPosition()); - } - else if (computeSelectedPosition() == null) - { + } else if (computeSelectedPosition() == null) { // User dragged the cursor off the globe. Clear the selected position to ensure a new one will be // computed if the user drags the cursor back to the globe. setSelectedPosition(null); - } - else if (computeSelectedPointAt(point) == null || computeSelectedPointAt(lastPoint) == null) - { + } else if (computeSelectedPointAt(point) == null || computeSelectedPointAt(lastPoint) == null) { // User selected a position that is won't work for dragging. Probably the selected elevation is above the // eye elevation, in which case dragging becomes unpredictable. Clear the selected position to ensure // a new one will be computed if the user drags the cursor to a valid position. @@ -239,13 +220,11 @@ else if (computeSelectedPointAt(point) == null || computeSelectedPointAt(lastPoi Vec4 lastVec = computeSelectedPointAt(lastPoint); // Cursor is on the globe, pan between the two positions. - if (vec != null && lastVec != null) - { - + if (vec != null && lastVec != null) { // Compute the change in view location given two screen points and corresponding world vectors. LatLon latlon = getChangeInLocation(lastPoint, point, lastVec, vec); - onHorizontalTranslateAbs(latlon.getLatitude(), latlon.getLongitude(), actionAttributes); + onHorizontalTranslateAbs(latlon.getLatitude(), latlon.getLongitude(), actionAttributes); return; } @@ -257,28 +236,25 @@ else if (computeSelectedPointAt(point) == null || computeSelectedPointAt(lastPoi // Cursor is off the globe, we potentially want to simulate globe dragging. // or this is a keyboard event. Angle forwardChange = Angle.fromDegrees( - forwardInput * getScaleValueHorizTransRel(deviceAttributes, actionAttributes)); + forwardInput * getScaleValueHorizTransRel(deviceAttributes, actionAttributes)); Angle sideChange = Angle.fromDegrees( - sideInput * getScaleValueHorizTransRel(deviceAttributes, actionAttributes)); + sideInput * getScaleValueHorizTransRel(deviceAttributes, actionAttributes)); onHorizontalTranslateRel(forwardChange, sideChange, actionAttributes); } protected void onHorizontalTranslateRel(Angle forwardChange, Angle sideChange, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { return; } - if (forwardChange.equals(Angle.ZERO) && sideChange.equals(Angle.ZERO)) - { + if (forwardChange.equals(Angle.ZERO) && sideChange.equals(Angle.ZERO)) { return; } - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { double sinHeading = view.getHeading().sin(); double cosHeading = view.getHeading().cos(); double latDegrees = cosHeading * forwardChange.degrees - sinHeading * sideChange.degrees; @@ -294,28 +270,25 @@ protected void onHorizontalTranslateRel(Angle forwardChange, Angle sideChange, @SuppressWarnings("UnusedParameters") protected void onHorizontalTranslate2D(double forwardInput, double sideInput, - double totalForwardInput, double totalSideInput, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes) - { + double totalForwardInput, double totalSideInput, + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes) { View view = this.getView(); - if (view == null || !(view instanceof BasicOrbitView)) - { + if (view == null || !(view instanceof BasicOrbitView)) { return; } this.stopAllAnimators(); - if (actionAttributes.getMouseActions() != null) - { + if (actionAttributes.getMouseActions() != null) { // Compute the model coordinate rays corresponding to the mouse down point and the current mouse point. BasicOrbitView orbitView = (BasicOrbitView) this.getView(); Point p1 = constrainToSourceBounds(this.getMouseDownPoint(), this.getWorldWindow()); Point p2 = constrainToSourceBounds(this.getMousePoint(), this.getWorldWindow()); Line ray1 = ViewUtil.computeRayFromScreenPoint(orbitView, p1.x, p1.y, this.mouseDownModelview, - this.mouseDownProjection, this.mouseDownViewport); + this.mouseDownProjection, this.mouseDownViewport); Line ray2 = ViewUtil.computeRayFromScreenPoint(orbitView, p2.x, p2.y, this.mouseDownModelview, - this.mouseDownProjection, this.mouseDownViewport); + this.mouseDownProjection, this.mouseDownViewport); // Compute a model coordinate plane passing through the position under the cursor when the mouse button was // pressed. Fall back to a plane normal to the globe if the cursor was off the globe. @@ -335,9 +308,7 @@ protected void onHorizontalTranslate2D(double forwardInput, double sideInput, Matrix modelview = this.mouseDownModelview.multiply(Matrix.fromTranslation(translation)); Vec4 eyePoint = modelview.extractEyePoint(); this.setEyePoint(eyePoint, actionAttributes); - } - else - { + } else { // Convert the translation vector from a unitless direction to eye coordinates. Globe globe = this.getWorldWindow().getModel().getGlobe(); double degreesPerUnit = this.getScaleValueHorizTransRel(deviceAttributes, actionAttributes); @@ -350,7 +321,7 @@ protected void onHorizontalTranslate2D(double forwardInput, double sideInput, // current orientation relative to the model. BasicOrbitView orbitView = (BasicOrbitView) this.getView(); Matrix matrix = ViewUtil.computeTransformMatrix(globe, orbitView.getCenterPosition(), - orbitView.getHeading(), Angle.ZERO, orbitView.getRoll()); + orbitView.getHeading(), Angle.ZERO, orbitView.getRoll()); translation = translation.transformBy3(matrix.getInverse()); // Apply the translation vector to the eye point. @@ -361,8 +332,7 @@ protected void onHorizontalTranslate2D(double forwardInput, double sideInput, } @Override - protected void onResetHeading(ViewInputAttributes.ActionAttributes actionAttribs) - { + protected void onResetHeading(ViewInputAttributes.ActionAttributes actionAttribs) { this.stopAllAnimators(); View view = this.getView(); @@ -379,8 +349,7 @@ protected void onResetHeading(ViewInputAttributes.ActionAttributes actionAttribs * @param actionAttribs input that caused the change. */ @SuppressWarnings("UnusedParameters") - protected void onResetRoll(ViewInputAttributes.ActionAttributes actionAttribs) - { + protected void onResetRoll(ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { @@ -396,8 +365,7 @@ protected void onResetRoll(ViewInputAttributes.ActionAttributes actionAttribs) } @Override - protected void onResetHeadingPitchRoll(ViewInputAttributes.ActionAttributes actionAttribs) - { + protected void onResetHeadingPitchRoll(ViewInputAttributes.ActionAttributes actionAttribs) { this.stopAllAnimators(); View view = this.getView(); @@ -407,72 +375,63 @@ protected void onResetHeadingPitchRoll(ViewInputAttributes.ActionAttributes acti } this.addHeadingPitchRollAnimator(view.getHeading(), Angle.ZERO, view.getPitch(), Angle.ZERO, view.getRoll(), - Angle.ZERO); + Angle.ZERO); } protected void onRotateView(double headingInput, double pitchInput, - double totalHeadingInput, double totalPitchInput, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes) - { + double totalHeadingInput, double totalPitchInput, + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes) { this.stopGoToAnimators(); this.stopUserInputAnimators(VIEW_ANIM_CENTER, VIEW_ANIM_ZOOM, VIEW_ANIM_EYE); - if (actionAttributes.getMouseActions() != null) - { + if (actionAttributes.getMouseActions() != null) { // Switch the direction of heading change depending on whether the cursor is above or below // the center of the screen. - if (getWorldWindow() instanceof Component) - { - if (getMousePoint().y < ((Component) getWorldWindow()).getHeight() / 2) - { + if (getWorldWindow() instanceof Component) { + if (getMousePoint().y < ((Component) getWorldWindow()).getHeight() / 2) { headingInput = -headingInput; } } - } - else - { + } else { double length = Math.sqrt(headingInput * headingInput + pitchInput * pitchInput); - if (length > 0.0) - { + if (length > 0.0) { headingInput /= length; pitchInput /= length; } - } Angle headingChange = Angle.fromDegrees( - headingInput * getScaleValueRotate(actionAttributes)); + headingInput * getScaleValueRotate(actionAttributes)); Angle pitchChange = Angle.fromDegrees( - pitchInput * getScaleValueRotate(actionAttributes)); + pitchInput * getScaleValueRotate(actionAttributes)); onRotateView(headingChange, pitchChange, actionAttributes); } protected void onRotateView(Angle headingChange, Angle pitchChange, - ViewInputAttributes.ActionAttributes actionAttribs) - { + ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { return; } - if (view instanceof BasicOrbitView) - { - if (!headingChange.equals(Angle.ZERO)) + if (view instanceof BasicOrbitView) { + if (!headingChange.equals(Angle.ZERO)) { this.changeHeading((BasicOrbitView) view, uiAnimControl, headingChange, actionAttribs); + } - if (!pitchChange.equals(Angle.ZERO)) + if (!pitchChange.equals(Angle.ZERO)) { this.changePitch((BasicOrbitView) view, uiAnimControl, pitchChange, actionAttribs); + } } } protected void onVerticalTranslate(double translateChange, double totalTranslateChange, - ViewInputAttributes.DeviceAttributes deviceAttributes, - ViewInputAttributes.ActionAttributes actionAttributes) - { + ViewInputAttributes.DeviceAttributes deviceAttributes, + ViewInputAttributes.ActionAttributes actionAttributes) { this.stopGoToAnimators(); this.stopUserInputAnimators(VIEW_ANIM_CENTER, VIEW_ANIM_HEADING, VIEW_ANIM_PITCH, VIEW_ANIM_EYE); @@ -480,20 +439,17 @@ protected void onVerticalTranslate(double translateChange, double totalTranslate onVerticalTranslate(zoomChange, actionAttributes); } - protected void onVerticalTranslate(double translateChange, ViewInputAttributes.ActionAttributes actionAttribs) - { + protected void onVerticalTranslate(double translateChange, ViewInputAttributes.ActionAttributes actionAttribs) { View view = this.getView(); if (view == null) // include this test to ensure any derived implementation performs it { return; } - if (translateChange == 0) - { + if (translateChange == 0) { return; } - if (view instanceof BasicOrbitView) - { + if (view instanceof BasicOrbitView) { this.changeZoom((BasicOrbitView) view, uiAnimControl, translateChange, actionAttribs); } } @@ -501,39 +457,30 @@ protected void onVerticalTranslate(double translateChange, ViewInputAttributes.A //**************************************************************// //******************** **********************// //**************************************************************// - /** - * Apply the changes prior to rendering a frame. - * The method will step animators, applying the results of those steps to the View, then - * if a focus on terrain is required, it will do that as well. + * Apply the changes prior to rendering a frame. The method will step animators, applying the results of those steps + * to the View, then if a focus on terrain is required, it will do that as well. + * * - **/ + */ @Override - public void apply() - { + public void apply() { super.apply(); View view = this.getView(); - if (view == null) - { + if (view == null) { return; } - if (this.gotoAnimControl.stepAnimators()) - { + if (this.gotoAnimControl.stepAnimators()) { view.firePropertyChange(AVKey.VIEW, null, view); - } - else - { + } else { this.gotoAnimControl.clear(); } - if (this.uiAnimControl.stepAnimators()) - { + if (this.uiAnimControl.stepAnimators()) { view.firePropertyChange(AVKey.VIEW, null, view); - } - else - { + } else { this.uiAnimControl.clear(); } } @@ -541,20 +488,16 @@ public void apply() //**************************************************************// //******************** Property Change Events ****************// //**************************************************************// - - protected void handlePropertyChange(java.beans.PropertyChangeEvent e) - { + protected void handlePropertyChange(java.beans.PropertyChangeEvent e) { super.handlePropertyChange(e); //noinspection StringEquality - if (e.getPropertyName() == OrbitView.CENTER_STOPPED) - { + if (e.getPropertyName() == OrbitView.CENTER_STOPPED) { this.handleOrbitViewCenterStopped(); } } - protected void stopAllAnimators() - { + protected void stopAllAnimators() { // Explicitly stop all animators, then clear the data structure which holds them. If we remove an animator // from this data structure without invoking stop(), the animator has no way of knowing it was forcibly stopped. // An animator's owner - potentially an object other than this ViewInputHandler - may need to know if an @@ -565,17 +508,16 @@ protected void stopAllAnimators() this.gotoAnimControl.clear(); View view = this.getView(); - if (view == null) + if (view == null) { return; + } - if (view instanceof BasicOrbitView) - { + if (view instanceof BasicOrbitView) { ((BasicOrbitView) view).setViewOutOfFocus(true); } } - protected void stopGoToAnimators() - { + protected void stopGoToAnimators() { // Explicitly stop all 'go to' animators, then clear the data structure which holds them. If we remove an // animator from this data structure without invoking stop(), the animator has no way of knowing it was forcibly // stopped. An animator's owner - likely an application object other - may need to know if an animator has been @@ -584,12 +526,9 @@ protected void stopGoToAnimators() this.gotoAnimControl.clear(); } - protected void stopUserInputAnimators(Object... names) - { - for (Object o : names) - { - if (this.uiAnimControl.get(o) != null) - { + protected void stopUserInputAnimators(Object... names) { + for (Object o : names) { + if (this.uiAnimControl.get(o) != null) { // Explicitly stop the 'ui' animator, then clear it from the data structure which holds it. If we remove // an animator from this data structure without invoking stop(), the animator has no way of knowing it // was forcibly stopped. Though applications cannot access the 'ui' animator data structure, stopping @@ -600,13 +539,11 @@ protected void stopUserInputAnimators(Object... names) } } - protected void handleViewStopped() - { + protected void handleViewStopped() { this.stopAllAnimators(); } - protected void handleOrbitViewCenterStopped() - { + protected void handleOrbitViewCenterStopped() { // The "center stopped" message instructs components to stop modifying the OrbitView's center position. // Therefore we stop any center position animations started by this view controller. this.stopUserInputAnimators(VIEW_ANIM_CENTER, VIEW_ANIM_EYE); @@ -615,63 +552,53 @@ protected void handleOrbitViewCenterStopped() //**************************************************************// //******************** View State Change Utilities ***********// //**************************************************************// - - protected void setEyePoint(Vec4 eyePoint, ViewInputAttributes.ActionAttributes attrib) - { + protected void setEyePoint(Vec4 eyePoint, ViewInputAttributes.ActionAttributes attrib) { Globe globe = this.getWorldWindow().getModel().getGlobe(); BasicOrbitView view = (BasicOrbitView) this.getView(); double smoothing = (this.isEnableSmoothing() && attrib.isEnableSmoothing()) ? attrib.getSmoothingValue() : 0; - if (smoothing == 0) - { + if (smoothing == 0) { OrbitViewEyePointAnimator.setEyePoint(globe, view, eyePoint); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); - } - else - { + } else { this.uiAnimControl.put(VIEW_ANIM_EYE, new OrbitViewEyePointAnimator(globe, view, eyePoint, smoothing)); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } } protected void setCenterPosition(BasicOrbitView view, - AnimationController animControl, - Position position, ViewInputAttributes.ActionAttributes attrib) - { + AnimationController animControl, + Position position, ViewInputAttributes.ActionAttributes attrib) { double smoothing = attrib.getSmoothingValue(); - if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } - if (smoothing == 0) - { - if (animControl.get(VIEW_ANIM_CENTER) != null) + if (smoothing == 0) { + if (animControl.get(VIEW_ANIM_CENTER) != null) { animControl.remove(VIEW_ANIM_CENTER); + } Position newPosition = view.getOrbitViewLimits().limitCenterPosition(view, position); view.setCenterPosition(newPosition); view.setViewOutOfFocus(true); - } - else - { + } else { OrbitViewCenterAnimator centerAnimator = (OrbitViewCenterAnimator) animControl.get(VIEW_ANIM_CENTER); Position cur = view.getCenterPosition(); - if (centerAnimator == null || !centerAnimator.hasNext()) - { + if (centerAnimator == null || !centerAnimator.hasNext()) { Position newPosition = computeNewPosition(view, position); centerAnimator = new OrbitViewCenterAnimator((BasicOrbitView) this.getView(), - cur, newPosition, smoothing, - OrbitViewPropertyAccessor.createCenterPositionAccessor(view), true); + cur, newPosition, smoothing, + OrbitViewPropertyAccessor.createCenterPositionAccessor(view), true); animControl.put(VIEW_ANIM_CENTER, centerAnimator); - } - else - { + } else { Position newPosition = new Position( - centerAnimator.getEnd().getLatitude().add( - position.getLatitude()).subtract(cur.getLatitude()), - centerAnimator.getEnd().getLongitude().add( - position.getLongitude()).subtract(cur.getLongitude()), - centerAnimator.getEnd().getElevation() + - position.getElevation() - cur.getElevation()); + centerAnimator.getEnd().getLatitude().add( + position.getLatitude()).subtract(cur.getLatitude()), + centerAnimator.getEnd().getLongitude().add( + position.getLongitude()).subtract(cur.getLongitude()), + centerAnimator.getEnd().getElevation() + + position.getElevation() - cur.getElevation()); newPosition = computeNewPosition(view, newPosition); centerAnimator.setEnd(newPosition); } @@ -693,39 +620,32 @@ protected void setCenterPosition(BasicOrbitView view, // // view.firePropertyChange(AVKey.VIEW, null, view); //} - protected void changeHeading(BasicOrbitView view, - AnimationController animControl, - Angle change, ViewInputAttributes.ActionAttributes attrib) - { + AnimationController animControl, + Angle change, ViewInputAttributes.ActionAttributes attrib) { view.computeAndSetViewCenterIfNeeded(); double smoothing = attrib.getSmoothingValue(); - if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } - if (smoothing == 0) - { - if (animControl.get(VIEW_ANIM_HEADING) != null) + if (smoothing == 0) { + if (animControl.get(VIEW_ANIM_HEADING) != null) { animControl.remove(VIEW_ANIM_HEADING); + } Angle newHeading = computeNewHeading(view, view.getHeading().add(change)); view.setHeading(newHeading); - } - else - { - RotateToAngleAnimator angleAnimator = (RotateToAngleAnimator) - animControl.get(VIEW_ANIM_HEADING); + } else { + RotateToAngleAnimator angleAnimator = (RotateToAngleAnimator) animControl.get(VIEW_ANIM_HEADING); - if (angleAnimator == null || !angleAnimator.hasNext()) - { + if (angleAnimator == null || !angleAnimator.hasNext()) { Angle newHeading = computeNewHeading(view, view.getHeading().add(change)); angleAnimator = new RotateToAngleAnimator( - view.getHeading(), newHeading, smoothing, - ViewPropertyAccessor.createHeadingAccessor(view)); + view.getHeading(), newHeading, smoothing, + ViewPropertyAccessor.createHeadingAccessor(view)); animControl.put(VIEW_ANIM_HEADING, angleAnimator); - } - else - { + } else { Angle newHeading = computeNewHeading(view, angleAnimator.getEnd().add(change)); angleAnimator.setEnd(newHeading); } @@ -747,43 +667,37 @@ protected void changeHeading(BasicOrbitView view, // animControl.put(VIEW_ANIM_PITCH, angleAnimator); // view.firePropertyChange(AVKey.VIEW, null, view); //} - protected void changePitch(BasicOrbitView view, - AnimationController animControl, - Angle change, ViewInputAttributes.ActionAttributes attrib) - { + AnimationController animControl, + Angle change, ViewInputAttributes.ActionAttributes attrib) { view.computeAndSetViewCenterIfNeeded(); double smoothing = attrib.getSmoothingValue(); - if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } - if (smoothing == 0.0) - { - if (animControl.get(VIEW_ANIM_PITCH) != null) + if (smoothing == 0.0) { + if (animControl.get(VIEW_ANIM_PITCH) != null) { animControl.remove(VIEW_ANIM_PITCH); + } Angle newPitch = computeNewPitch(view, view.getPitch().add(change)); view.setPitch(newPitch); - } - else - { + } else { RotateToAngleAnimator angleAnimator = (RotateToAngleAnimator) animControl.get(VIEW_ANIM_PITCH); - if (angleAnimator == null || !angleAnimator.hasNext()) - { + if (angleAnimator == null || !angleAnimator.hasNext()) { // Create an angle animator which tilts the view to the specified new pitch. If this changes causes the // view to collide with the surface, this animator is set to stop. We enable this behavior by using a // {@link #CollisionAwarePitchAccessor} angle accessor and setting the animator's stopOnInvalidState // property to 'true'. Angle newPitch = computeNewPitch(view, view.getPitch().add(change)); angleAnimator = new RotateToAngleAnimator( - view.getPitch(), newPitch, smoothing, - new CollisionAwarePitchAccessor(view)); + view.getPitch(), newPitch, smoothing, + new CollisionAwarePitchAccessor(view)); angleAnimator.setStopOnInvalidState(true); animControl.put(VIEW_ANIM_PITCH, angleAnimator); - } - else - { + } else { Angle newPitch = computeNewPitch(view, angleAnimator.getEnd().add(change)); angleAnimator.setEnd(newPitch); } @@ -795,35 +709,30 @@ protected void changePitch(BasicOrbitView view, } protected void changeZoom(BasicOrbitView view, - AnimationController animControl, - double change, ViewInputAttributes.ActionAttributes attrib) - { + AnimationController animControl, + double change, ViewInputAttributes.ActionAttributes attrib) { view.computeAndSetViewCenterIfNeeded(); double smoothing = attrib.getSmoothingValue(); - if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) + if (!(attrib.isEnableSmoothing() && this.isEnableSmoothing())) { smoothing = 0.0; + } - if (smoothing == 0.0) - { - if (animControl.get(VIEW_ANIM_ZOOM) != null) + if (smoothing == 0.0) { + if (animControl.get(VIEW_ANIM_ZOOM) != null) { animControl.remove(VIEW_ANIM_ZOOM); + } view.setZoom(computeNewZoom(view, view.getZoom(), change)); - } - else - { + } else { double newZoom; OrbitViewMoveToZoomAnimator zoomAnimator = (OrbitViewMoveToZoomAnimator) animControl.get(VIEW_ANIM_ZOOM); - if (zoomAnimator == null || !zoomAnimator.hasNext()) - { + if (zoomAnimator == null || !zoomAnimator.hasNext()) { newZoom = computeNewZoom(view, view.getZoom(), change); zoomAnimator = new OrbitViewMoveToZoomAnimator(view, newZoom, smoothing, - OrbitViewPropertyAccessor.createZoomAccessor(view), false); + OrbitViewPropertyAccessor.createZoomAccessor(view), false); animControl.put(VIEW_ANIM_ZOOM, zoomAnimator); - } - else - { + } else { newZoom = computeNewZoom(view, zoomAnimator.getEnd(), change); zoomAnimator.setEnd(newZoom); } @@ -833,28 +742,24 @@ protected void changeZoom(BasicOrbitView view, view.firePropertyChange(AVKey.VIEW, null, view); } - protected static Position computeNewPosition(OrbitView view, Position position) - { + protected static Position computeNewPosition(OrbitView view, Position position) { Angle newLat = Angle.fromDegrees(WWMath.clamp(position.latitude.degrees, -90, 90)); Angle newLon = Angle.normalizedLongitude(position.longitude); Position newPosition = new Position(newLat, newLon, position.elevation); return view.getOrbitViewLimits().limitCenterPosition(view, newPosition); } - protected static Angle computeNewHeading(OrbitView view, Angle heading) - { + protected static Angle computeNewHeading(OrbitView view, Angle heading) { Angle newHeading = BasicOrbitView.normalizedHeading(heading); return view.getOrbitViewLimits().limitHeading(view, newHeading); } - protected static Angle computeNewPitch(OrbitView view, Angle pitch) - { + protected static Angle computeNewPitch(OrbitView view, Angle pitch) { Angle newPitch = BasicOrbitView.normalizedPitch(pitch); return view.getOrbitViewLimits().limitPitch(view, newPitch); } - protected static double computeNewZoom(OrbitView view, double curZoom, double change) - { + protected static double computeNewZoom(OrbitView view, double curZoom, double change) { double logCurZoom = curZoom != 0 ? Math.log(curZoom) : 0; double newZoom = Math.exp(logCurZoom + change); return view.getOrbitViewLimits().limitZoom(view, newZoom); @@ -863,7 +768,6 @@ protected static double computeNewZoom(OrbitView view, double curZoom, double ch //**************************************************************// //******************** Input Handler Property Accessors ******// //**************************************************************// - /** * CollisionAwarePitchAccessor implements an {@link gov.nasa.worldwind.util.PropertyAccessor.AngleAccessor} * interface onto the pitch property of an {@link gov.nasa.worldwind.view.orbit.OrbitView}. In addition to accessing @@ -871,8 +775,8 @@ protected static double computeNewZoom(OrbitView view, double curZoom, double ch * If a call to {@link #setAngle(gov.nasa.worldwind.geom.Angle)} causes the view to collide with the surface, then * the call returns false indicating to the caller that the set operation was not entirely successful. */ - protected static class CollisionAwarePitchAccessor implements PropertyAccessor.AngleAccessor - { + protected static class CollisionAwarePitchAccessor implements PropertyAccessor.AngleAccessor { + protected OrbitView orbitView; /** @@ -882,10 +786,8 @@ protected static class CollisionAwarePitchAccessor implements PropertyAccessor.A * * @throws IllegalArgumentException if the orbitView is null. */ - public CollisionAwarePitchAccessor(OrbitView orbitView) - { - if (orbitView == null) - { + public CollisionAwarePitchAccessor(OrbitView orbitView) { + if (orbitView == null) { String message = Logging.getMessage("nullValue.OrbitViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -899,8 +801,7 @@ public CollisionAwarePitchAccessor(OrbitView orbitView) * * @return the pitch from this accessor's view. */ - public Angle getAngle() - { + public Angle getAngle() { return this.orbitView.getPitch(); } @@ -913,22 +814,20 @@ public Angle getAngle() * * @return true if the pitch property was successfully set, and false otherwise. */ - public boolean setAngle(Angle value) - { - if (value == null) + public boolean setAngle(Angle value) { + if (value == null) { return false; + } // If the view supports surface collision detection, then clear the view's collision flag prior to // making any property changes. - if (this.orbitView.isDetectCollisions()) + if (this.orbitView.isDetectCollisions()) { this.orbitView.hadCollisions(); + } - try - { + try { this.orbitView.setPitch(value); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileChangingView"); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); return false; @@ -943,60 +842,50 @@ public boolean setAngle(Angle value) //**************************************************************// //******************** Scaling Utilities *********************// //**************************************************************// - protected double getScaleValueHorizTransRel( - ViewInputAttributes.DeviceAttributes deviceAttributes, ViewInputAttributes.ActionAttributes actionAttributes) - { + ViewInputAttributes.DeviceAttributes deviceAttributes, ViewInputAttributes.ActionAttributes actionAttributes) { View view = this.getView(); - if (view == null) - { + if (view == null) { return 0.0; } - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { double[] range = actionAttributes.getValues(); // If this is an OrbitView, we use the zoom value to set the scale double radius = this.getWorldWindow().getModel().getGlobe().getRadius(); double t = getScaleValue(range[0], range[1], - ((OrbitView) view).getZoom(), 3.0 * radius, true); + ((OrbitView) view).getZoom(), 3.0 * radius, true); return (t); } else { // Any other view, use the base class scaling method - return(super.getScaleValueElevation(deviceAttributes, actionAttributes)); + return (super.getScaleValueElevation(deviceAttributes, actionAttributes)); } } protected double getScaleValueRotate( - ViewInputAttributes.ActionAttributes actionAttributes) - { + ViewInputAttributes.ActionAttributes actionAttributes) { View view = this.getView(); - if (view == null) - { + if (view == null) { return 0.0; } - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { double[] range = actionAttributes.getValues(); // If this is an OrbitView, we use the zoom value to set the scale double radius = this.getWorldWindow().getModel().getGlobe().getRadius(); double t = getScaleValue(range[0], range[1], - ((OrbitView) view).getZoom(), 3.0 * radius, false); + ((OrbitView) view).getZoom(), 3.0 * radius, false); return (t); } - return(1.0); + return (1.0); } - protected double getScaleValueZoom(ViewInputAttributes.ActionAttributes actionAttributes) - { + protected double getScaleValueZoom(ViewInputAttributes.ActionAttributes actionAttributes) { View view = this.getView(); - if (view == null) - { + if (view == null) { return 0.0; } - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { double[] range = actionAttributes.getValues(); // If this is an OrbitView, we use the zoom value to set the scale double radius = this.getWorldWindow().getModel().getGlobe().getRadius(); @@ -1004,95 +893,86 @@ protected double getScaleValueZoom(ViewInputAttributes.ActionAttributes actionAt t = (t < 0 ? 0 : (t > 1 ? 1 : t)); return range[0] * (1.0 - t) + range[1] * t; } - return(1.0); + return (1.0); } - public void addPanToAnimator(Position beginCenterPos, Position endCenterPos, - Angle beginHeading, Angle endHeading, - Angle beginPitch, Angle endPitch, - double beginZoom, double endZoom, long timeToMove, boolean endCenterOnSurface) - { + Angle beginHeading, Angle endHeading, + Angle beginPitch, Angle endPitch, + double beginZoom, double endZoom, long timeToMove, boolean endCenterOnSurface) { int altitudeMode = endCenterOnSurface ? WorldWind.CLAMP_TO_GROUND : WorldWind.ABSOLUTE; OrbitView orbitView = (OrbitView) this.getView(); FlyToOrbitViewAnimator panAnimator = FlyToOrbitViewAnimator.createFlyToOrbitViewAnimator(orbitView, - beginCenterPos, endCenterPos, beginHeading, endHeading, beginPitch, endPitch, - beginZoom, endZoom, timeToMove, altitudeMode); + beginCenterPos, endCenterPos, beginHeading, endHeading, beginPitch, endPitch, + beginZoom, endZoom, timeToMove, altitudeMode); this.gotoAnimControl.put(VIEW_ANIM_PAN, panAnimator); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } public void addPanToAnimator(Position beginCenterPos, Position endCenterPos, - Angle beginHeading, Angle endHeading, - Angle beginPitch, Angle endPitch, - double beginZoom, double endZoom, boolean endCenterOnSurface) - { + Angle beginHeading, Angle endHeading, + Angle beginPitch, Angle endPitch, + double beginZoom, double endZoom, boolean endCenterOnSurface) { int altitudeMode = endCenterOnSurface ? WorldWind.CLAMP_TO_GROUND : WorldWind.ABSOLUTE; // TODO: scale on mid-altitude? final long MIN_LENGTH_MILLIS = 2000; final long MAX_LENGTH_MILLIS = 10000; long timeToMove = AnimationSupport.getScaledTimeMillisecs( - beginCenterPos, endCenterPos, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); + beginCenterPos, endCenterPos, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); OrbitView orbitView = (OrbitView) this.getView(); FlyToOrbitViewAnimator panAnimator = FlyToOrbitViewAnimator.createFlyToOrbitViewAnimator(orbitView, - beginCenterPos, endCenterPos, beginHeading, endHeading, beginPitch, endPitch, - beginZoom, endZoom, timeToMove, altitudeMode); + beginCenterPos, endCenterPos, beginHeading, endHeading, beginPitch, endPitch, + beginZoom, endZoom, timeToMove, altitudeMode); this.gotoAnimControl.put(VIEW_ANIM_PAN, panAnimator); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } public void addPanToAnimator(Position centerPos, Angle heading, Angle pitch, double zoom, - long timeToMove, boolean endCenterOnSurface) - { + long timeToMove, boolean endCenterOnSurface) { OrbitView view = (OrbitView) this.getView(); addPanToAnimator(view.getCenterPosition(), centerPos, - view.getHeading(), heading, - view.getPitch(), pitch, view.getZoom(), zoom, timeToMove, endCenterOnSurface); + view.getHeading(), heading, + view.getPitch(), pitch, view.getZoom(), zoom, timeToMove, endCenterOnSurface); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } public void addPanToAnimator(Position centerPos, Angle heading, Angle pitch, double zoom, - boolean endCenterOnSurface) - { + boolean endCenterOnSurface) { OrbitView view = (OrbitView) this.getView(); addPanToAnimator(view.getCenterPosition(), centerPos, - view.getHeading(), heading, - view.getPitch(), pitch, view.getZoom(), zoom, endCenterOnSurface); + view.getHeading(), heading, + view.getPitch(), pitch, view.getZoom(), zoom, endCenterOnSurface); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } - public void addPanToAnimator(Position centerPos, Angle heading, Angle pitch, double zoom) - { + public void addPanToAnimator(Position centerPos, Angle heading, Angle pitch, double zoom) { OrbitView view = (OrbitView) this.getView(); addPanToAnimator(view.getCenterPosition(), centerPos, - view.getHeading(), heading, - view.getPitch(), pitch, view.getZoom(), zoom, false); + view.getHeading(), heading, + view.getPitch(), pitch, view.getZoom(), zoom, false); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } - public void addEyePositionAnimator(long timeToIterate, Position beginPosition, Position endPosition) - { + public void addEyePositionAnimator(long timeToIterate, Position beginPosition, Position endPosition) { PositionAnimator eyePosAnimator = ViewUtil.createEyePositionAnimator(this.getView(), - timeToIterate, beginPosition, endPosition); + timeToIterate, beginPosition, endPosition); this.gotoAnimControl.put(VIEW_ANIM_POSITION, eyePosAnimator); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } - public void addHeadingAnimator(Angle begin, Angle end) - { + public void addHeadingAnimator(Angle begin, Angle end) { this.gotoAnimControl.remove(VIEW_ANIM_HEADING_PITCH); AngleAnimator headingAnimator = ViewUtil.createHeadingAnimator(this.getView(), begin, end); this.gotoAnimControl.put(VIEW_ANIM_HEADING, headingAnimator); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } - public void addPitchAnimator(Angle begin, Angle end) - { + public void addPitchAnimator(Angle begin, Angle end) { this.gotoAnimControl.remove(VIEW_ANIM_HEADING_PITCH); AngleAnimator pitchAnimator = ViewUtil.createPitchAnimator(this.getView(), begin, end); this.gotoAnimControl.put(VIEW_ANIM_PITCH, pitchAnimator); @@ -1103,10 +983,9 @@ public void addPitchAnimator(Angle begin, Angle end) * Add an animator to animate roll. * * @param begin starting roll - * @param end final roll + * @param end final roll */ - public void addRollAnimator(Angle begin, Angle end) - { + public void addRollAnimator(Angle begin, Angle end) { this.gotoAnimControl.remove(VIEW_ANIM_ROLL); AngleAnimator rollAnimator = ViewUtil.createRollAnimator(this.getView(), begin, end); this.gotoAnimControl.put(VIEW_ANIM_ROLL, rollAnimator); @@ -1117,43 +996,38 @@ public void addRollAnimator(Angle begin, Angle end) * Add an animator to animate heading, pitch, and roll. * * @param beginHeading starting heading - * @param endHeading final heading - * @param beginPitch starting pitch - * @param endPitch final pitch - * @param beginRoll starting roll - * @param endRoll final roll + * @param endHeading final heading + * @param beginPitch starting pitch + * @param endPitch final pitch + * @param beginRoll starting roll + * @param endRoll final roll */ public void addHeadingPitchRollAnimator(Angle beginHeading, Angle endHeading, Angle beginPitch, Angle endPitch, - Angle beginRoll, Angle endRoll) - { + Angle beginRoll, Angle endRoll) { this.gotoAnimControl.remove(VIEW_ANIM_PITCH); this.gotoAnimControl.remove(VIEW_ANIM_HEADING); CompoundAnimator headingPitchAnimator = ViewUtil.createHeadingPitchRollAnimator(this.getView(), - beginHeading, endHeading, beginPitch, endPitch, beginRoll, endRoll); + beginHeading, endHeading, beginPitch, endPitch, beginRoll, endRoll); this.gotoAnimControl.put(VIEW_ANIM_HEADING_PITCH, headingPitchAnimator); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } - public void addZoomAnimator(double zoomStart, double zoomEnd) - { + public void addZoomAnimator(double zoomStart, double zoomEnd) { final long DEFAULT_LENGTH_MILLIS = 4000; DoubleAnimator zoomAnimator = new DoubleAnimator(new ScheduledInterpolator(DEFAULT_LENGTH_MILLIS), - zoomStart, zoomEnd, OrbitViewPropertyAccessor.createZoomAccessor(((OrbitView) this.getView()))); + zoomStart, zoomEnd, OrbitViewPropertyAccessor.createZoomAccessor(((OrbitView) this.getView()))); this.gotoAnimControl.put(VIEW_ANIM_ZOOM, zoomAnimator); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } - public void addFlyToZoomAnimator(Angle heading, Angle pitch, double zoom) - { - if (heading == null || pitch == null) - { + public void addFlyToZoomAnimator(Angle heading, Angle pitch, double zoom) { + if (heading == null || pitch == null) { String message = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } View view = this.getView(); - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { OrbitView orbitView = (OrbitView) view; Angle beginHeading = orbitView.getHeading(); Angle beginPitch = orbitView.getPitch(); @@ -1161,15 +1035,15 @@ public void addFlyToZoomAnimator(Angle heading, Angle pitch, double zoom) final long MIN_LENGTH_MILLIS = 1000; final long MAX_LENGTH_MILLIS = 8000; long lengthMillis = AnimationSupport.getScaledTimeMillisecs( - beginZoom, zoom, - MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); + beginZoom, zoom, + MIN_LENGTH_MILLIS, MAX_LENGTH_MILLIS); DoubleAnimator zoomAnimator = new DoubleAnimator( - new ScheduledInterpolator(lengthMillis), beginZoom, zoom, - OrbitViewPropertyAccessor.createZoomAccessor(orbitView)); + new ScheduledInterpolator(lengthMillis), beginZoom, zoom, + OrbitViewPropertyAccessor.createZoomAccessor(orbitView)); AngleAnimator headingAnimator = new AngleAnimator(new ScheduledInterpolator(lengthMillis), - beginHeading, heading, ViewPropertyAccessor.createHeadingAccessor(orbitView)); + beginHeading, heading, ViewPropertyAccessor.createHeadingAccessor(orbitView)); AngleAnimator pitchAnimator = new AngleAnimator(new ScheduledInterpolator(lengthMillis), - beginPitch, pitch, ViewPropertyAccessor.createPitchAccessor(orbitView)); + beginPitch, pitch, ViewPropertyAccessor.createPitchAccessor(orbitView)); this.gotoAnimControl.put(VIEW_ANIM_ZOOM, zoomAnimator); this.gotoAnimControl.put(VIEW_ANIM_HEADING, headingAnimator); @@ -1178,75 +1052,62 @@ public void addFlyToZoomAnimator(Angle heading, Angle pitch, double zoom) } } - public void addCenterAnimator(Position begin, Position end, boolean smoothed) - { - if (begin == null || end == null) - { + public void addCenterAnimator(Position begin, Position end, boolean smoothed) { + if (begin == null || end == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } View view = this.getView(); - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { // TODO: length-scaling factory function final long DEFAULT_LENGTH_MILLIS = 4000; this.addCenterAnimator(begin, end, DEFAULT_LENGTH_MILLIS, smoothed); } } - public void addCenterAnimator(Position begin, Position end, long lengthMillis, boolean smoothed) - { - if (begin == null || end == null) - { + public void addCenterAnimator(Position begin, Position end, long lengthMillis, boolean smoothed) { + if (begin == null || end == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().fine(message); throw new IllegalArgumentException(message); } View view = this.getView(); - if (view instanceof OrbitView) - { + if (view instanceof OrbitView) { OrbitView orbitView = (OrbitView) view; Interpolator interpolator; - if (smoothed) - { + if (smoothed) { interpolator = new SmoothInterpolator(lengthMillis); - } - else - { + } else { interpolator = new ScheduledInterpolator(lengthMillis); } Animator centerAnimator = new PositionAnimator(interpolator, - begin, end, OrbitViewPropertyAccessor.createCenterPositionAccessor(orbitView)); + begin, end, OrbitViewPropertyAccessor.createCenterPositionAccessor(orbitView)); this.gotoAnimControl.put(VIEW_ANIM_CENTER, centerAnimator); orbitView.firePropertyChange(AVKey.VIEW, null, orbitView); } } - public void goTo(Position lookAtPos, double distance) - { + public void goTo(Position lookAtPos, double distance) { OrbitView view = (OrbitView) this.getView(); stopAnimators(); addPanToAnimator(lookAtPos, view.getHeading(), view.getPitch(), distance, true); this.getView().firePropertyChange(AVKey.VIEW, null, this.getView()); } - public void stopAnimators() - { + public void stopAnimators() { this.uiAnimControl.stopAnimations(); this.gotoAnimControl.stopAnimations(); } - public boolean isAnimating() - { + public boolean isAnimating() { return (this.uiAnimControl.hasActiveAnimation() || this.gotoAnimControl.hasActiveAnimation()); } - public void addAnimator(Animator animator) - { + public void addAnimator(Animator animator) { long date = new Date().getTime(); - this.gotoAnimControl.put(VIEW_ANIM_APP+date, animator); + this.gotoAnimControl.put(VIEW_ANIM_APP + date, animator); } } diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitViewInputSupport.java b/src/gov/nasa/worldwind/view/orbit/OrbitViewInputSupport.java index 91ade354da..8e616c14ba 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitViewInputSupport.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitViewInputSupport.java @@ -15,31 +15,28 @@ * @author dcollins * @version $Id: OrbitViewInputSupport.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OrbitViewInputSupport -{ +public class OrbitViewInputSupport { + public static class OrbitViewState // public to allow access from subclasses { + private final Position center; private final Angle heading; private final Angle pitch; private final double zoom; - public OrbitViewState(Position center, Angle heading, Angle pitch, double zoom) - { - if (center == null) - { + public OrbitViewState(Position center, Angle heading, Angle pitch, double zoom) { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (heading == null) - { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pitch == null) - { + if (pitch == null) { String message = Logging.getMessage("nullValue.PitchIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -51,54 +48,44 @@ public OrbitViewState(Position center, Angle heading, Angle pitch, double zoom) this.zoom = zoom; } - public Position getCenterPosition() - { + public Position getCenterPosition() { return this.center; } - public Angle getHeading() - { + public Angle getHeading() { return this.heading; } - public Angle getPitch() - { + public Angle getPitch() { return this.pitch; } - public double getZoom() - { + public double getZoom() { return this.zoom; } } - public OrbitViewInputSupport() - { + public OrbitViewInputSupport() { } public static Matrix computeTransformMatrix(Globe globe, Position center, Angle heading, Angle pitch, Angle roll, - double zoom) - { - if (globe == null) - { + double zoom) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (heading == null) - { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pitch == null) - { + if (pitch == null) { String message = Logging.getMessage("nullValue.PitchIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -115,28 +102,23 @@ public static Matrix computeTransformMatrix(Globe globe, Position center, Angle return transform; } - public static OrbitViewState computeOrbitViewState(Globe globe, Vec4 eyePoint, Vec4 centerPoint, Vec4 up) - { - if (globe == null) - { + public static OrbitViewState computeOrbitViewState(Globe globe, Vec4 eyePoint, Vec4 centerPoint, Vec4 up) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (eyePoint == null) - { + if (eyePoint == null) { String message = "nullValue.EyePointIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (centerPoint == null) - { + if (centerPoint == null) { String message = "nullValue.CenterPointIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (up == null) - { + if (up == null) { String message = "nullValue.UpIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -146,22 +128,18 @@ public static OrbitViewState computeOrbitViewState(Globe globe, Vec4 eyePoint, V return OrbitViewInputSupport.computeOrbitViewState(globe, modelview, centerPoint); } - public static OrbitViewState computeOrbitViewState(Globe globe, Matrix modelTransform, Vec4 centerPoint) - { - if (globe == null) - { + public static OrbitViewState computeOrbitViewState(Globe globe, Matrix modelTransform, Vec4 centerPoint) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (modelTransform == null) - { + if (modelTransform == null) { String message = "nullValue.ModelTransformIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (centerPoint == null) - { + if (centerPoint == null) { String message = "nullValue.CenterPointIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -172,8 +150,7 @@ public static OrbitViewState computeOrbitViewState(Globe globe, Matrix modelTran // Compute the center position transform. Matrix centerTransform = OrbitViewInputSupport.computeCenterTransform(globe, centerPos); Matrix centerTransformInv = centerTransform.getInverse(); - if (centerTransformInv == null) - { + if (centerTransformInv == null) { String message = Logging.getMessage("generic.NoninvertibleMatrix"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -185,22 +162,20 @@ public static OrbitViewState computeOrbitViewState(Globe globe, Matrix modelTran Angle heading = ViewUtil.computeHeading(hpzTransform); Angle pitch = ViewUtil.computePitch(hpzTransform); double zoom = OrbitViewInputSupport.computeZoom(hpzTransform); - if (heading == null || pitch == null) + if (heading == null || pitch == null) { return null; + } return new OrbitViewState(centerPos, heading, pitch, zoom); } - protected static Matrix computeCenterTransform(Globe globe, Position center) - { - if (globe == null) - { + protected static Matrix computeCenterTransform(Globe globe, Position center) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (center == null) - { + if (center == null) { String message = Logging.getMessage("nullValue.CenterIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -224,22 +199,18 @@ protected static Matrix computeCenterTransform(Globe globe, Position center) return Matrix.fromViewLookAt(eyePoint, lookAtPoint, north); } - protected static Matrix computeHeadingPitchRollZoomTransform(Angle heading, Angle pitch, Angle roll, double zoom) - { - if (heading == null) - { + protected static Matrix computeHeadingPitchRollZoomTransform(Angle heading, Angle pitch, Angle roll, double zoom) { + if (heading == null) { String message = Logging.getMessage("nullValue.HeadingIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pitch == null) - { + if (pitch == null) { String message = Logging.getMessage("nullValue.PitchIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (roll == null) - { + if (roll == null) { String message = Logging.getMessage("nullValue.RollIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -258,11 +229,8 @@ protected static Matrix computeHeadingPitchRollZoomTransform(Angle heading, Angl return transform; } - - protected static double computeZoom(Matrix headingPitchZoomTransform) - { - if (headingPitchZoomTransform == null) - { + protected static double computeZoom(Matrix headingPitchZoomTransform) { + if (headingPitchZoomTransform == null) { String message = "nullValue.HeadingPitchZoomTransformTransformIsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -273,25 +241,20 @@ protected static double computeZoom(Matrix headingPitchZoomTransform) } public static OrbitViewState getSurfaceIntersection(Globe globe, SectorGeometryList terrain, Position centerPosition, - Angle heading, Angle pitch, double zoom) - { - if (globe != null) - { + Angle heading, Angle pitch, double zoom) { + if (globe != null) { Matrix modelview = OrbitViewInputSupport.computeTransformMatrix(globe, centerPosition, heading, pitch, Angle.ZERO, zoom); - if (modelview != null) - { + if (modelview != null) { Matrix modelviewInv = modelview.getInverse(); - if (modelviewInv != null) - { + if (modelviewInv != null) { Vec4 eyePoint = Vec4.UNIT_W.transformBy4(modelviewInv); Vec4 centerPoint = globe.computePointFromPosition(centerPosition); Vec4 eyeToCenter = eyePoint.subtract3(centerPoint); Intersection[] intersections = terrain.intersect(new Line(eyePoint, eyeToCenter.normalize3().multiply3(-1))); - if (intersections != null && intersections.length >= 0) - { + if (intersections != null && intersections.length >= 0) { Position newCenter = globe.computePositionFromPoint(intersections[0].getIntersectionPoint()); - return(new OrbitViewState(newCenter, heading, pitch, zoom)); + return (new OrbitViewState(newCenter, heading, pitch, zoom)); } } } diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitViewLimits.java b/src/gov/nasa/worldwind/view/orbit/OrbitViewLimits.java index 10c9e0e374..7ebb11ad0d 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitViewLimits.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitViewLimits.java @@ -16,8 +16,8 @@ * @author dcollins * @version $Id: OrbitViewLimits.java 2253 2014-08-22 16:33:46Z dcollins $ */ -public interface OrbitViewLimits extends ViewPropertyLimits -{ +public interface OrbitViewLimits extends ViewPropertyLimits { + /** * Returns the Sector which limits the orbit view center latitude and longitude. * @@ -69,7 +69,7 @@ public interface OrbitViewLimits extends ViewPropertyLimits * object. This method does not modify the specified view's properties, but may use the view as a context for * determining how to apply the limits. * - * @param view the view associated with the center position and the property limits. + * @param view the view associated with the center position and the property limits. * @param position position to clamp to the allowed range. * * @return The clamped position. @@ -82,7 +82,7 @@ public interface OrbitViewLimits extends ViewPropertyLimits * Returns a distance clamped to the zoom limits specified by this limit object. This method does not modify the * specified view's properties, but may use the view as a context for determining how to apply the limits. * - * @param view the view associated with the zoom distance and the property limits. + * @param view the view associated with the zoom distance and the property limits. * @param value zoom distance to clamp to the allowed range. * * @return The clamped value. diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitViewMoveToZoomAnimator.java b/src/gov/nasa/worldwind/view/orbit/OrbitViewMoveToZoomAnimator.java index dd7ad8260c..7d3beb3587 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitViewMoveToZoomAnimator.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitViewMoveToZoomAnimator.java @@ -12,37 +12,35 @@ * @author jym * @version $Id: OrbitViewMoveToZoomAnimator.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OrbitViewMoveToZoomAnimator extends MoveToDoubleAnimator -{ +public class OrbitViewMoveToZoomAnimator extends MoveToDoubleAnimator { + BasicOrbitView orbitView; boolean endCenterOnSurface; OrbitViewMoveToZoomAnimator(BasicOrbitView orbitView, Double end, double smoothing, - PropertyAccessor.DoubleAccessor propertyAccessor, boolean endCenterOnSurface) - { + PropertyAccessor.DoubleAccessor propertyAccessor, boolean endCenterOnSurface) { super(end, smoothing, propertyAccessor); this.orbitView = orbitView; this.endCenterOnSurface = endCenterOnSurface; } - protected void setImpl(double interpolant) - { - Double newValue = this.nextDouble(interpolant); - if (newValue == null) - return; + protected void setImpl(double interpolant) { + Double newValue = this.nextDouble(interpolant); + if (newValue == null) { + return; + } - this.propertyAccessor.setDouble(newValue); + this.propertyAccessor.setDouble(newValue); } - public Double nextDouble(double interpolant) - { + public Double nextDouble(double interpolant) { double newValue = (1 - interpolant) * propertyAccessor.getDouble() + interpolant * this.end; - if (Math.abs(newValue - propertyAccessor.getDouble()) < minEpsilon) - { + if (Math.abs(newValue - propertyAccessor.getDouble()) < minEpsilon) { this.stop(); - if (this.endCenterOnSurface) + if (this.endCenterOnSurface) { orbitView.setViewOutOfFocus(true); - return(null); + } + return (null); } return newValue; } diff --git a/src/gov/nasa/worldwind/view/orbit/OrbitViewPropertyAccessor.java b/src/gov/nasa/worldwind/view/orbit/OrbitViewPropertyAccessor.java index 34a5a55636..7a1ecc141e 100644 --- a/src/gov/nasa/worldwind/view/orbit/OrbitViewPropertyAccessor.java +++ b/src/gov/nasa/worldwind/view/orbit/OrbitViewPropertyAccessor.java @@ -13,23 +13,16 @@ * @author dcollins * @version $Id: OrbitViewPropertyAccessor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class OrbitViewPropertyAccessor extends ViewPropertyAccessor -{ - - private OrbitViewPropertyAccessor() - { - } +public class OrbitViewPropertyAccessor extends ViewPropertyAccessor { + private OrbitViewPropertyAccessor() { + } - public static PropertyAccessor.PositionAccessor createCenterPositionAccessor(OrbitView view) - { + public static PropertyAccessor.PositionAccessor createCenterPositionAccessor(OrbitView view) { return new CenterPositionAccessor(view); } - - - public static PropertyAccessor.DoubleAccessor createZoomAccessor(OrbitView view) - { + public static PropertyAccessor.DoubleAccessor createZoomAccessor(OrbitView view) { return new ZoomAccessor(view); } @@ -37,80 +30,70 @@ public static PropertyAccessor.DoubleAccessor createZoomAccessor(OrbitView view) //{ // return new RotationAccessor(); //} - // ============== Implementation ======================= // // ============== Implementation ======================= // // ============== Implementation ======================= // + private static class CenterPositionAccessor implements PropertyAccessor.PositionAccessor { - private static class CenterPositionAccessor implements PropertyAccessor.PositionAccessor - { private OrbitView orbitView; - public CenterPositionAccessor(OrbitView view) - { + + public CenterPositionAccessor(OrbitView view) { this.orbitView = view; } - public Position getPosition() - { - if (this.orbitView == null) + public Position getPosition() { + if (this.orbitView == null) { return null; + } return orbitView.getCenterPosition(); } - public boolean setPosition(Position value) - { - //noinspection SimplifiableIfStatement - if (this.orbitView == null || value == null) + public boolean setPosition(Position value) { + //noinspection SimplifiableIfStatement + if (this.orbitView == null || value == null) { return false; + } - - try - { + try { this.orbitView.setCenterPosition(value); return true; - } - catch (Exception e) - { + } catch (Exception e) { return false; } } } + private static class ZoomAccessor implements PropertyAccessor.DoubleAccessor { - - private static class ZoomAccessor implements PropertyAccessor.DoubleAccessor - { OrbitView orbitView; - public ZoomAccessor(OrbitView orbitView) - { + + public ZoomAccessor(OrbitView orbitView) { this.orbitView = orbitView; } - public final Double getDouble() - { - if (this.orbitView == null) + + public final Double getDouble() { + if (this.orbitView == null) { return null; + } return this.orbitView.getZoom(); } - public final boolean setDouble(Double value) - { + public final boolean setDouble(Double value) { //noinspection SimplifiableIfStatement - if (this.orbitView == null || value == null) + if (this.orbitView == null || value == null) { return false; + } - try - { + try { this.orbitView.setZoom(value); return true; - } - catch (Exception e) - { + } catch (Exception e) { return false; } } diff --git a/src/gov/nasa/worldwind/view/package-info.java b/src/gov/nasa/worldwind/view/package-info.java index 1ec85e62ff..fcfad240b0 100644 --- a/src/gov/nasa/worldwind/view/package-info.java +++ b/src/gov/nasa/worldwind/view/package-info.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - /** *

          * The view package contains implementations, and support for implementations of the {@link gov.nasa.worldwind.View} diff --git a/src/gov/nasa/worldwind/wms/BoundingBox.java b/src/gov/nasa/worldwind/wms/BoundingBox.java index 3acdbfbfc8..d5918cf59c 100644 --- a/src/gov/nasa/worldwind/wms/BoundingBox.java +++ b/src/gov/nasa/worldwind/wms/BoundingBox.java @@ -11,8 +11,8 @@ * @author tag * @version $Id: BoundingBox.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class BoundingBox -{ +public class BoundingBox { + private String crs; private double minx; private double maxx; @@ -22,12 +22,10 @@ public class BoundingBox private double resy; public static BoundingBox createFromStrings(String crs, String minx, String maxx, String miny, String maxy, - String resx, String resy) - { + String resx, String resy) { BoundingBox bbox = new BoundingBox(); - try - { + try { bbox.crs = crs; bbox.minx = Double.parseDouble(minx); bbox.maxx = Double.parseDouble(maxx); @@ -35,9 +33,7 @@ public static BoundingBox createFromStrings(String crs, String minx, String maxx bbox.maxy = Double.parseDouble(maxy); bbox.resx = resx != null && !resx.equals("") ? Double.parseDouble(resx) : 0; bbox.resy = resy != null && !resy.equals("") ? Double.parseDouble(resy) : 0; - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("XML.ImproperDataType"); Logging.logger().severe(message); throw e; @@ -46,44 +42,36 @@ public static BoundingBox createFromStrings(String crs, String minx, String maxx return bbox; } - public String getCrs() - { + public String getCrs() { return crs; } - public double getMinx() - { + public double getMinx() { return minx; } - public double getMaxx() - { + public double getMaxx() { return maxx; } - public double getMiny() - { + public double getMiny() { return miny; } - public double getMaxy() - { + public double getMaxy() { return maxy; } - public double getResx() - { + public double getResx() { return resx; } - public double getResy() - { + public double getResy() { return resy; } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.crs); diff --git a/src/gov/nasa/worldwind/wms/Capabilities.java b/src/gov/nasa/worldwind/wms/Capabilities.java index ebc884379a..7307dea4ab 100644 --- a/src/gov/nasa/worldwind/wms/Capabilities.java +++ b/src/gov/nasa/worldwind/wms/Capabilities.java @@ -23,8 +23,8 @@ * @author tag * @version $Id: Capabilities.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class Capabilities -{ +public abstract class Capabilities { + public static final String WMS_SERVICE_NAME = "OGC:WMS"; protected Document doc; @@ -33,21 +33,17 @@ public abstract class Capabilities protected XPath xpath; protected URL capsURL; - public static Capabilities retrieve(URI uri, String service) throws Exception - { + public static Capabilities retrieve(URI uri, String service) throws Exception { return retrieve(uri, service, null, null); } - public static Capabilities retrieve(URI uri, Integer connectTimeout, Integer readTimeout) throws Exception - { + public static Capabilities retrieve(URI uri, Integer connectTimeout, Integer readTimeout) throws Exception { return retrieve(uri, null, connectTimeout, readTimeout); } public static Capabilities retrieve(URI uri, String service, Integer connectTimeout, Integer readTimeout) - throws Exception - { - if (uri == null) - { + throws Exception { + if (uri == null) { String message = Logging.getMessage("nullValue.URIIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -55,54 +51,49 @@ public static Capabilities retrieve(URI uri, String service, Integer connectTime InputStream is = null; - try - { + try { // Request the capabilities document from the server. CapabilitiesRequest req = new CapabilitiesRequest(uri, service); URL capsURL = req.getUri().toURL(); - URLRetriever retriever = URLRetriever.createRetriever(capsURL, new RetrievalPostProcessor() - { - public ByteBuffer run(Retriever retriever) - { + URLRetriever retriever = URLRetriever.createRetriever(capsURL, new RetrievalPostProcessor() { + public ByteBuffer run(Retriever retriever) { return retriever.getBuffer(); } }); - if (retriever == null) - { + if (retriever == null) { String message = Logging.getMessage("generic.UnrecognizedProtocol"); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (connectTimeout != null) + if (connectTimeout != null) { retriever.setConnectTimeout(connectTimeout); + } - if (readTimeout != null) + if (readTimeout != null) { retriever.setReadTimeout(readTimeout); + } retriever.call(); - if (!retriever.getState().equals(URLRetriever.RETRIEVER_STATE_SUCCESSFUL)) - { + if (!retriever.getState().equals(URLRetriever.RETRIEVER_STATE_SUCCESSFUL)) { String message = Logging.getMessage("generic.RetrievalFailed", uri.toString()); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (retriever.getBuffer() == null || retriever.getBuffer().limit() == 0) - { + if (retriever.getBuffer() == null || retriever.getBuffer().limit() == 0) { String message = Logging.getMessage("generic.RetrievalReturnedNoContent", uri.toString()); Logging.logger().severe(message); throw new WWRuntimeException(message); } - if (retriever.getContentType().equalsIgnoreCase("application/vnd.ogc.se_xml")) - { + if (retriever.getContentType().equalsIgnoreCase("application/vnd.ogc.se_xml")) { String exceptionMessage = WWXML.extractOGCServiceException(retriever.getBuffer()); String message = Logging.getMessage("WMS.ServiceException", - uri.toString() + ": " + (exceptionMessage != null ? exceptionMessage : "")); + uri.toString() + ": " + (exceptionMessage != null ? exceptionMessage : "")); Logging.logger().severe(message); throw new WWRuntimeException(message); } @@ -111,101 +102,82 @@ public ByteBuffer run(Retriever retriever) is = WWIO.getInputStreamFromByteBuffer(retriever.getBuffer()); Capabilities caps = Capabilities.parse(WWXML.createDocumentBuilder(true).parse(is)); - if (caps != null) + if (caps != null) { caps.capsURL = capsURL; - + } + return caps; - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("generic.URIInvalid", uri.toString()), e); + Logging.getMessage("generic.URIInvalid", uri.toString()), e); throw e; - } - catch (ParserConfigurationException e) - { + } catch (ParserConfigurationException e) { Logging.logger().fine(Logging.getMessage("WMS.ParserConfigurationException", uri.toString())); throw e; - } - catch (IOException e) - { + } catch (IOException e) { Logging.logger().log(java.util.logging.Level.SEVERE, - Logging.getMessage("generic.ExceptionAttemptingToReadFrom", uri.toString()), e); + Logging.getMessage("generic.ExceptionAttemptingToReadFrom", uri.toString()), e); throw e; - } - catch (SAXException e) - { + } catch (SAXException e) { Logging.logger().fine(Logging.getMessage("WMS.ParsingError", uri.toString())); throw e; - } - finally - { + } finally { WWIO.closeStream(is, uri.toString()); } } - public static Capabilities parse(Document doc) - { + public static Capabilities parse(Document doc) { XPath xpath = WWXML.makeXPath(); xpath.setNamespaceContext(new WMSNamespaceContext()); - try - { + try { String exceptionMessage = WWXML.checkOGCException(doc); - if (exceptionMessage != null) - { + if (exceptionMessage != null) { String message = Logging.getMessage("WMS.ServiceException", exceptionMessage); Logging.logger().severe(message); throw new ServiceException(exceptionMessage); } String version = xpath.evaluate(altPaths("*/@wms:version"), doc); - if (version == null || version.length() == 0) + if (version == null || version.length() == 0) { return null; + } - if (version.compareTo("1.3") < 0) + if (version.compareTo("1.3") < 0) { return new CapabilitiesV111(doc, xpath); - else + } else { return new CapabilitiesV130(doc, xpath); - } - catch (XPathExpressionException e) - { + } + } catch (XPathExpressionException e) { Logging.logger().log(Level.SEVERE, "WMS.ParsingError", e); return null; } } - protected Capabilities(Document doc, XPath xpath) - { + protected Capabilities(Document doc, XPath xpath) { this.doc = doc; this.xpath = xpath; - try - { + try { this.service = (Element) this.xpath.evaluate(altPaths("*/wms:Service"), doc, XPathConstants.NODE); - if (this.service == null) - { + if (this.service == null) { String message = Logging.getMessage("WMS.NoServiceElement", "XML document"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.capability = (Element) this.xpath.evaluate(altPaths("*/wms:Capability"), doc, XPathConstants.NODE); - if (this.capability == null) - { + if (this.capability == null) { String message = Logging.getMessage("WMS.NoCapabilityElement", "XML document"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { Logging.logger().log(Level.SEVERE, "WMS.ParsingError", e); } } - public URL getCapsURL() - { + public URL getCapsURL() { return capsURL; } @@ -214,114 +186,99 @@ private static String altPaths(String path) // hack for WW server layer names wi return path != null ? path + "|" + path.replaceAll("wms:", "") : null; } - protected String getText(String path) - { + protected String getText(String path) { return this.getText(null, path); } - protected String getText(Element context, String path) - { - try - { + protected String getText(Element context, String path) { + try { return this.xpath.evaluate(altPaths(path), context != null ? context : doc); - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { return null; } } - protected String[] getTextArray(Element context, String path) - { - try - { + protected String[] getTextArray(Element context, String path) { + try { NodeList nodes = (NodeList) this.xpath.evaluate(altPaths(path), context != null ? context : doc, - XPathConstants.NODESET); - if (nodes == null || nodes.getLength() == 0) + XPathConstants.NODESET); + if (nodes == null || nodes.getLength() == 0) { return null; + } String[] strings = new String[nodes.getLength()]; - for (int i = 0; i < nodes.getLength(); i++) - { + for (int i = 0; i < nodes.getLength(); i++) { strings[i] = nodes.item(i).getTextContent(); } return strings; - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { return null; } } - protected String[] getUniqueText(Element context, String path) - { + protected String[] getUniqueText(Element context, String path) { String[] strings = this.getTextArray(context, path); - if (strings == null) + if (strings == null) { return null; + } ArrayList sarl = new ArrayList(); - for (String s : strings) - { - if (!sarl.contains(s)) + for (String s : strings) { + if (!sarl.contains(s)) { sarl.add(s); + } } return sarl.toArray(new String[1]); } - protected Element getElement(Element context, String path) - { - try - { + protected Element getElement(Element context, String path) { + try { Node node = (Node) this.xpath.evaluate(altPaths(path), context != null ? context : doc, - XPathConstants.NODE); - if (node == null) + XPathConstants.NODE); + if (node == null) { return null; + } return node instanceof Element ? (Element) node : null; - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { return null; } } - protected Element[] getElements(Element context, String path) - { - try - { + protected Element[] getElements(Element context, String path) { + try { NodeList nodes = (NodeList) this.xpath.evaluate(altPaths(path), context != null ? context : doc, - XPathConstants.NODESET); - if (nodes == null || nodes.getLength() == 0) + XPathConstants.NODESET); + if (nodes == null || nodes.getLength() == 0) { return null; + } Element[] elements = new Element[nodes.getLength()]; - for (int i = 0; i < nodes.getLength(); i++) - { + for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); - if (node instanceof Element) + if (node instanceof Element) { elements[i] = (Element) node; + } } return elements; - } - catch (XPathExpressionException e) - { + } catch (XPathExpressionException e) { return null; } } - protected Element[] getUniqueElements(Element context, String path, String uniqueTag) - { + protected Element[] getUniqueElements(Element context, String path, String uniqueTag) { Element[] elements = this.getElements(context, path); - if (elements == null) + if (elements == null) { return null; + } HashMap styles = new HashMap(); - for (Element e : elements) - { + for (Element e : elements) { String name = this.getText(e, uniqueTag); - if (name != null) + if (name != null) { styles.put(name, e); + } } return styles.values().toArray(new Element[1]); @@ -330,19 +287,16 @@ protected Element[] getUniqueElements(Element context, String path, String uniqu private HashMap namedLayerElements = new HashMap(); private HashMap namedLayers = new HashMap(); - private void fillLayerList() - { - if (this.namedLayers.size() == 0) - { + private void fillLayerList() { + if (this.namedLayers.size() == 0) { Element[] nels = this.getElements(this.capability, "descendant::wms:Layer[wms:Name]"); - if (nels == null || nels.length == 0) + if (nels == null || nels.length == 0) { return; + } - for (Element le : nels) - { + for (Element le : nels) { String name = this.getLayerName(le); - if (name != null) - { + if (name != null) { Layer layer = new Layer(le); this.namedLayers.put(name, layer); this.namedLayerElements.put(le, layer); @@ -351,39 +305,35 @@ private void fillLayerList() } } - public Document getDocument() - { + public Document getDocument() { return this.doc; } - public Element[] getNamedLayers() - { - if (this.namedLayerElements.size() == 0) + public Element[] getNamedLayers() { + if (this.namedLayerElements.size() == 0) { this.fillLayerList(); + } return this.namedLayerElements.keySet().toArray(new Element[this.namedLayerElements.size()]); } - public Element getLayerByName(String layerName) - { - if (this.namedLayers.size() == 0) + public Element getLayerByName(String layerName) { + if (this.namedLayers.size() == 0) { this.fillLayerList(); + } Layer l = this.namedLayers.get(layerName); return l != null ? l.element : null; } - public Long getLayerLatestLastUpdateTime(Capabilities caps, String[] layerNames) - { - if (caps == null) - { + public Long getLayerLatestLastUpdateTime(Capabilities caps, String[] layerNames) { + if (caps == null) { String message = Logging.getMessage("nullValue.WMSCapabilities"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (layerNames == null) - { + if (layerNames == null) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -391,25 +341,22 @@ public Long getLayerLatestLastUpdateTime(Capabilities caps, String[] layerNames) String lastUpdate = null; - for (String name : layerNames) - { + for (String name : layerNames) { Element layer = caps.getLayerByName(name); - if (layer == null) + if (layer == null) { continue; + } String update = caps.getLayerLastUpdate(layer); - if (update != null && update.length() > 0 && (lastUpdate == null || update.compareTo(lastUpdate) > 0)) - lastUpdate = update; + if (update != null && update.length() > 0 && (lastUpdate == null || update.compareTo(lastUpdate) > 0)) { + lastUpdate = update; + } } - if (lastUpdate != null) - { - try - { + if (lastUpdate != null) { + try { return Long.parseLong(lastUpdate); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", lastUpdate); Logging.logger().warning(message); } @@ -418,17 +365,14 @@ public Long getLayerLatestLastUpdateTime(Capabilities caps, String[] layerNames) return null; } - public Double[] getLayerExtremeElevations(Capabilities caps, String[] layerNames) - { - if (caps == null) - { + public Double[] getLayerExtremeElevations(Capabilities caps, String[] layerNames) { + if (caps == null) { String message = Logging.getMessage("nullValue.WMSCapabilities"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (layerNames == null) - { + if (layerNames == null) { String message = Logging.getMessage("nullValue.WMSLayerNames"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -437,38 +381,38 @@ public Double[] getLayerExtremeElevations(Capabilities caps, String[] layerNames String extremeMin = null; String extremeMax = null; - for (String name : layerNames) - { + for (String name : layerNames) { Element layer = caps.getLayerByName(name); - if (layer == null) + if (layer == null) { continue; + } String min = caps.getLayerExtremeElevationsMin(layer); - if (min != null && (extremeMin == null || min.compareTo(min) > 0)) - extremeMin = min; + if (min != null && (extremeMin == null || min.compareTo(min) > 0)) { + extremeMin = min; + } String max = caps.getLayerExtremeElevationsMax(layer); - if (max != null && (extremeMax == null || max.compareTo(max) > 0)) - extremeMax = max; + if (max != null && (extremeMax == null || max.compareTo(max) > 0)) { + extremeMax = max; + } } - if (extremeMin != null || extremeMax != null) - { - try - { - Double[] extremes = new Double[] {null, null}; + if (extremeMin != null || extremeMax != null) { + try { + Double[] extremes = new Double[]{null, null}; - if (extremeMin != null) + if (extremeMin != null) { extremes[0] = Double.parseDouble(extremeMin); - if (extremeMax != null) + } + if (extremeMax != null) { extremes[1] = Double.parseDouble(extremeMax); + } return extremes; - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { String message = Logging.getMessage("generic.ConversionError", - extremeMin != null ? extremeMin : "" + extremeMax != null ? extremeMax : ""); + extremeMin != null ? extremeMin : "" + extremeMax != null ? extremeMax : ""); Logging.logger().severe(message); } } @@ -477,241 +421,199 @@ public Double[] getLayerExtremeElevations(Capabilities caps, String[] layerNames } // ********* Document Items ********* // - - public String getVersion() - { + public String getVersion() { return this.getText("*/@wms:version"); } - public String getUpdateSequence() - { + public String getUpdateSequence() { return this.getText("*/@wms:updateSequence"); } // ********* Service Items ********* // - - public String getAbstract() - { + public String getAbstract() { return this.getText(this.service, "wms:Abstract"); } - public String getAccessConstraints() - { + public String getAccessConstraints() { return this.getText(this.service, "wms:AccessConstraints"); } - public String getContactOrganization() - { + public String getContactOrganization() { return this.getText( - this.service, "wms:ContactInformation/wms:ContactPersonPrimary/wms:ContactOrganization"); + this.service, "wms:ContactInformation/wms:ContactPersonPrimary/wms:ContactOrganization"); } - public String getContactPerson() - { + public String getContactPerson() { return this.getText( - this.service, "wms:ContactInformation/wms:ContactPersonPrimary/wms:ContactPerson"); + this.service, "wms:ContactInformation/wms:ContactPersonPrimary/wms:ContactPerson"); } - public String getFees() - { + public String getFees() { return this.getText(this.service, "wms:Fees"); } - public String[] getKeywordList() - { + public String[] getKeywordList() { return this.getTextArray(this.service, "wms:KeywordList/wms:Keyword"); } - public String getLayerLimit() - { + public String getLayerLimit() { return this.getText(this.service, "wms:LayerLimit"); } - public String getMaxWidth() - { + public String getMaxWidth() { return this.getText(this.service, "wms:MaxWidth"); } - public String getMaxHeight() - { + public String getMaxHeight() { return this.getText(this.service, "wms:MaxHeight"); } - public String getServiceName() - { + public String getServiceName() { return this.getText(this.service, "wms:Name"); } - public String getTitle() - { + public String getTitle() { return this.getText(this.service, "wms:Title"); } // ********* Capability Items ********* // - - public String getOnlineResource() - { + public String getOnlineResource() { return this.getText(this.capability, "wms:OnlineResource/@xlink:href"); } - public String[] getGetCapabilitiesFormats() - { + public String[] getGetCapabilitiesFormats() { return this.getTextArray(this.capability, - "wms:Request/wms:GetCapabilities/wms:Format"); + "wms:Request/wms:GetCapabilities/wms:Format"); } - public String getGetCapabilitiesRequestGetURL() - { + public String getGetCapabilitiesRequestGetURL() { return this.getText(this.capability, - "wms:Request/wms:GetCapabilities/wms:DCPType/wms:HTTP/wms:Get/wms:OnlineResource/@xlink:href"); + "wms:Request/wms:GetCapabilities/wms:DCPType/wms:HTTP/wms:Get/wms:OnlineResource/@xlink:href"); } - public String getGetCapabilitiesRequestPostURL() - { + public String getGetCapabilitiesRequestPostURL() { return this.getText(this.capability, - "wms:Request/wms:GetCapabilities/wms:DCPType/wms:HTTP/wms:Post/wms:OnlineResource/@xlink:href"); + "wms:Request/wms:GetCapabilities/wms:DCPType/wms:HTTP/wms:Post/wms:OnlineResource/@xlink:href"); } - public String[] getExceptionFormats() - { + public String[] getExceptionFormats() { return this.getTextArray(this.capability, "wms:Exception/wms:Format"); } - public String getFeatureInfoRequestGetURL() - { + public String getFeatureInfoRequestGetURL() { return this.getText(this.capability, - "wms:Request/wms:GetFeatureInfo/wms:DCPType/wms:HTTP/wms:Get/wms:OnlineResource/@xlink:href"); + "wms:Request/wms:GetFeatureInfo/wms:DCPType/wms:HTTP/wms:Get/wms:OnlineResource/@xlink:href"); } - public String getFeatureInfoRequestPostURL() - { + public String getFeatureInfoRequestPostURL() { return this.getText(this.capability, - "wms:Request/wms:GetFeatureInfo/wms:DCPType/wms:HTTP/wms:Post/wms:OnlineResource/@xlink:href"); + "wms:Request/wms:GetFeatureInfo/wms:DCPType/wms:HTTP/wms:Post/wms:OnlineResource/@xlink:href"); } - public String[] getGetMapFormats() - { + public String[] getGetMapFormats() { return this.getTextArray(this.capability, - "wms:Request/wms:GetMap/wms:Format"); + "wms:Request/wms:GetMap/wms:Format"); } - public String getGetMapRequestGetURL() - { + public String getGetMapRequestGetURL() { return this.getText(this.capability, - "wms:Request/wms:GetMap/wms:DCPType/wms:HTTP/wms:Get/wms:OnlineResource/@xlink:href"); + "wms:Request/wms:GetMap/wms:DCPType/wms:HTTP/wms:Get/wms:OnlineResource/@xlink:href"); } - public String getGetMapRequestPostURL() - { + public String getGetMapRequestPostURL() { return this.getText(this.capability, - "wms:Request/wms:GetMap/wms:DCPType/wms:HTTP/wms:Post/wms:OnlineResource/@xlink:href"); + "wms:Request/wms:GetMap/wms:DCPType/wms:HTTP/wms:Post/wms:OnlineResource/@xlink:href"); } - public String getVendorSpecificCapabilities() - { + public String getVendorSpecificCapabilities() { return this.getText(this.capability, "wms:VendorSpecificCapabilities"); } - public Element getLayer() - { + public Element getLayer() { return this.getElement(this.capability, "wms:Layer"); } // ********* Layer Items ********* // + protected static class Layer { - protected static class Layer - { protected HashMap styleElements = new HashMap(); protected final Element element; protected Layer layer; protected String name; protected String title; - public Layer(Element element) - { + public Layer(Element element) { this.element = element; } } - public String getLayerAbstract(Element layer) - { + public String getLayerAbstract(Element layer) { return this.getText(layer, "wms:Abstract"); } - public String getLayerAttributionTitle(Element layer) - { + public String getLayerAttributionTitle(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/wms:Attribution/wms:Title"); } - public String getLayerAttributionURL(Element layer) - { + public String getLayerAttributionURL(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/wms:Attribution/wms:OnlineResource/@xlink:href"); } - public String getLayerAttributionLogoFormat(Element layer) - { + public String getLayerAttributionLogoFormat(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/wms:Attribution/wms:LogoURL/wms:Format"); } - public String getLayerAttributionLogoHeight(Element layer) - { + public String getLayerAttributionLogoHeight(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/wms:Attribution/wms:LogoURL/@wms:height"); } - public String getLayerAttributionLogoURL(Element layer) - { + public String getLayerAttributionLogoURL(Element layer) { return this.getText(layer, - "ancestor-or-self::wms:Layer/wms:Attribution/wms:LogoURL/wms:OnlineResource/@xlink:href"); + "ancestor-or-self::wms:Layer/wms:Attribution/wms:LogoURL/wms:OnlineResource/@xlink:href"); } - public String getLayerAttributionLogoWidth(Element layer) - { + public String getLayerAttributionLogoWidth(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/wms:Attribution/wms:LogoURL/@wms:width"); } - public Element[] getLayerAuthorityURLs(Element layer) - { + public Element[] getLayerAuthorityURLs(Element layer) { return this.getUniqueElements(layer, "ancestor-or-self::wms:Layer/wms:AuthorityURL", "@wms:type"); } public abstract BoundingBox[] getLayerBoundingBoxes(Element layer); - public String getLayerCascaded(Element layer) - { + public String getLayerCascaded(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/@cascaded"); } - public String[] getLayerCRS(Element layer) - { + public String[] getLayerCRS(Element layer) { return this.getUniqueText(layer, "ancestor-or-self::wms:Layer/wms:CRS"); } - public String getLayerDataURLFormat(Element layer) - { + public String getLayerDataURLFormat(Element layer) { return this.getText(layer, "wms:DataURL/wms:Format"); } - public String getLayerDataURL(Element layer) - { + public String getLayerDataURL(Element layer) { return this.getText(layer, "wms:DataURL/wms:OnlineResource/@xlink:href"); } - public Element[] getLayerDimensions(Element layer) - { + public Element[] getLayerDimensions(Element layer) { Element[] dims = this.getElements(layer, "ancestor-or-self::wms:Layer/wms:Dimension"); - if (dims == null || dims.length == 0) + if (dims == null || dims.length == 0) { return null; + } ArrayList uniqueDims = new ArrayList(); ArrayList dimNames = new ArrayList(); - for (Element e : dims) - { + for (Element e : dims) { // Filter out dimensions with same name. // Keep all those with a null name, even though wms says they're invalid. Let the app decide. String name = this.getDimensionName(e); - if (name != null && dimNames.contains(name)) + if (name != null && dimNames.contains(name)) { continue; + } uniqueDims.add(e); dimNames.add(name); @@ -720,22 +622,22 @@ public Element[] getLayerDimensions(Element layer) return uniqueDims.toArray(new Element[uniqueDims.size()]); } - public Element[] getLayerExtents(Element layer) - { + public Element[] getLayerExtents(Element layer) { Element[] extents = this.getElements(layer, "ancestor-or-self::wms:Layer/wms:Extent"); - if (extents == null || extents.length == 0) + if (extents == null || extents.length == 0) { return null; + } ArrayList uniqueExtents = new ArrayList(); ArrayList extentNames = new ArrayList(); - for (Element e : extents) - { + for (Element e : extents) { // Filter out dimensions with same name. // Keep all those with a null name, even though wms says they're invalid. Let the app decide. String name = this.getDimensionName(e); - if (name != null && extentNames.contains(name)) + if (name != null && extentNames.contains(name)) { continue; + } uniqueExtents.add(e); extentNames.add(name); @@ -746,87 +648,76 @@ public Element[] getLayerExtents(Element layer) public abstract BoundingBox getLayerGeographicBoundingBox(Element layer); - public String getLayerFeatureListFormat(Element layer) - { + public String getLayerFeatureListFormat(Element layer) { return this.getText(layer, "wms:FeatureListURL/wms:Format"); } - public String getLayerFeatureListURL(Element layer) - { + public String getLayerFeatureListURL(Element layer) { return this.getText(layer, "wms:FeatureListURL/wms:OnlineResource/@xlink:href"); } - public String getLayerFixedHeight(Element layer) - { + public String getLayerFixedHeight(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/@fixedHeight"); } - public String getLayerFixedWidth(Element layer) - { + public String getLayerFixedWidth(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/@fixedWidth"); } - public Element[] getLayerIdentifiers(Element layer) - { + public Element[] getLayerIdentifiers(Element layer) { return this.getUniqueElements(layer, "wms:Identifier", "wms:authority"); } - public String[] getLayerKeywordList(Element layer) - { + public String[] getLayerKeywordList(Element layer) { return this.getTextArray(layer, "wms:KeywordList/wms:Keyword"); } public abstract String getLayerMaxScaleDenominator(Element layer); - public Element[] getLayerMetadataURLs(Element layer) - { + public Element[] getLayerMetadataURLs(Element layer) { return this.getElements(layer, "wms:MetadataURL"); } public abstract String getLayerMinScaleDenominator(Element layer); - public String getLayerName(Element layerElement) - { + public String getLayerName(Element layerElement) { Layer layer = this.namedLayerElements.get(layerElement); return layer != null && layer.name != null ? layer.name : this.getText(layerElement, "wms:Name"); } - public String getLayerNoSubsets(Element layer) - { + public String getLayerNoSubsets(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/@noSubsets"); } - public String getLayerOpaque(Element layer) - { + public String getLayerOpaque(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/@opaque"); } - public String getLayerQueryable(Element layer) - { + public String getLayerQueryable(Element layer) { return this.getText(layer, "ancestor-or-self::wms:Layer/@queryable"); } - public String[] getLayerSRS(Element layer) - { + public String[] getLayerSRS(Element layer) { return this.getUniqueText(layer, "ancestor-or-self::wms:Layer/wms:SRS"); } - public Element[] getLayerStyles(Element layerElement) - { + public Element[] getLayerStyles(Element layerElement) { Layer layer = this.namedLayerElements.get(layerElement); - if (layer == null) + if (layer == null) { return null; + } - if (layer.styleElements != null && layer.styleElements.size() != 0) + if (layer.styleElements != null && layer.styleElements.size() != 0) { return layer.styleElements.keySet().toArray(new Element[1]); + } Element[] styleElements = this.getUniqueElements(layerElement, "ancestor-or-self::wms:Layer/wms:Style", "Name"); - if (styleElements == null) + if (styleElements == null) { return null; + } layer.styleElements = new HashMap(); - for (Element se : styleElements) - { + for (Element se : styleElements) { Style style = new Style(se, layer); layer.styleElements.put(se, style); this.styleElements.put(se, style); @@ -835,331 +726,274 @@ public Element[] getLayerStyles(Element layerElement) return layer.styleElements.keySet().toArray(new Element[1]); } - public Element[] getLayerSubLayers(Element layer) - { + public Element[] getLayerSubLayers(Element layer) { return this.getElements(layer, "wms:Layer"); } - public String getLayerTitle(Element layerElement) - { + public String getLayerTitle(Element layerElement) { Layer layer = this.namedLayerElements.get(layerElement); - if (layer == null) + if (layer == null) { return this.getText(layerElement, "wms:Title"); + } return layer.title != null ? layer.title : (layer.title = this.getText(layerElement, "wms:Title")); } - public Element getLayerStyleByName(Element layerElement, String styleName) - { + public Element getLayerStyleByName(Element layerElement, String styleName) { Layer layer = this.namedLayerElements.get(layerElement); - if (layer == null) + if (layer == null) { return null; + } - if (layer.styleElements == null || layer.styleElements.size() == 0) - { + if (layer.styleElements == null || layer.styleElements.size() == 0) { // Initialize the layer's style list. this.getLayerStyles(layerElement); - if (layer.styleElements == null || layer.styleElements.size() == 0) + if (layer.styleElements == null || layer.styleElements.size() == 0) { return null; + } } Collection + --> + - - + + -

          +
          -
          NASA WorldWind
          Search and Rescue Prototype
          +
          NASA WorldWind
          Search and Rescue Prototype
          -
          Version 6.0 (6/8/2009)
          +
          Version 6.0 (6/8/2009)
          -

          +

          -

          Copyright (C) 2001, 2009 United States Government as represented by - the Administrator of the National Aeronautics and Space Administration. - All Rights Reserved.
          +
          Copyright (C) 2001, 2009 United States Government as represented by + the Administrator of the National Aeronautics and Space Administration. + All Rights Reserved.
          -
          +
          - + \ No newline at end of file diff --git a/src/gov/nasa/worldwindx/applications/sar/SARAboutDialog.java b/src/gov/nasa/worldwindx/applications/sar/SARAboutDialog.java index 5f9cb3ce36..583ffeab37 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARAboutDialog.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARAboutDialog.java @@ -11,10 +11,9 @@ * @author dcollins * @version $Id: SARAboutDialog.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARAboutDialog extends AboutDialog -{ - public SARAboutDialog() - { +public class SARAboutDialog extends AboutDialog { + + public SARAboutDialog() { setContent("SARAbout.html"); setContentType("text/html"); setPreferredSize(new Dimension(400, 230)); diff --git a/src/gov/nasa/worldwindx/applications/sar/SARAnnotation.java b/src/gov/nasa/worldwindx/applications/sar/SARAnnotation.java index a54a4acfee..b1dc6dfde4 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARAnnotation.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARAnnotation.java @@ -12,33 +12,28 @@ * @author tag * @version $Id: SARAnnotation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARAnnotation extends GlobeAnnotation -{ +public class SARAnnotation extends GlobeAnnotation { + private SARTrack owner; private String id; - public SARAnnotation(String text, Position position) - { + public SARAnnotation(String text, Position position) { super(text, position); } - public SARTrack getOwner() - { + public SARTrack getOwner() { return this.owner; } - public void setOwner(SARTrack owner) - { + public void setOwner(SARTrack owner) { this.owner = owner; } - public String getId() - { + public String getId() { return id; } - public void setId(String id) - { + public void setId(String id) { this.id = id; } } diff --git a/src/gov/nasa/worldwindx/applications/sar/SARAnnotationReader.java b/src/gov/nasa/worldwindx/applications/sar/SARAnnotationReader.java index 1e9d2bd662..d7c1f687f9 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARAnnotationReader.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARAnnotationReader.java @@ -12,31 +12,27 @@ * @author dcollins * @version $Id: SARAnnotationReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARAnnotationReader -{ +public class SARAnnotationReader { + private javax.xml.parsers.SAXParser parser; private java.util.List sarAnnotations = new java.util.ArrayList(); - public SARAnnotationReader() throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException - { + public SARAnnotationReader() throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); this.parser = factory.newSAXParser(); } - public void readFile(String path) throws java.io.IOException, org.xml.sax.SAXException - { - if (path == null) - { + public void readFile(String path) throws java.io.IOException, org.xml.sax.SAXException { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } java.io.File file = new java.io.File(path); - if (!file.exists()) - { + if (!file.exists()) { String msg = Logging.getMessage("generic.FileNotFound", path); Logging.logger().severe(msg); throw new java.io.FileNotFoundException(path); @@ -46,10 +42,8 @@ public void readFile(String path) throws java.io.IOException, org.xml.sax.SAXExc this.doRead(fis); } - public void readStream(java.io.InputStream stream) throws java.io.IOException, org.xml.sax.SAXException - { - if (stream == null) - { + public void readStream(java.io.InputStream stream) throws java.io.IOException, org.xml.sax.SAXException { + if (stream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -58,39 +52,33 @@ public void readStream(java.io.InputStream stream) throws java.io.IOException, o this.doRead(stream); } - public java.util.List getSARAnnotations() - { + public java.util.List getSARAnnotations() { return this.sarAnnotations; } - private void doRead(java.io.InputStream fis) throws java.io.IOException, org.xml.sax.SAXException - { + private void doRead(java.io.InputStream fis) throws java.io.IOException, org.xml.sax.SAXException { this.parser.parse(fis, new Handler()); } - private class Handler extends org.xml.sax.helpers.DefaultHandler - { + private class Handler extends org.xml.sax.helpers.DefaultHandler { // this is a private class used solely by the containing class, so no validation occurs in it. private gov.nasa.worldwindx.applications.sar.ElementParser currentElement = null; @Override - public void warning(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException - { + public void warning(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException { saxParseException.printStackTrace(); super.warning(saxParseException); } @Override - public void error(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException - { + public void error(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException { saxParseException.printStackTrace(); super.error(saxParseException); } @Override - public void fatalError(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException - { + public void fatalError(org.xml.sax.SAXParseException saxParseException) throws org.xml.sax.SAXException { saxParseException.printStackTrace(); super.fatalError(saxParseException); } @@ -99,66 +87,58 @@ public void fatalError(org.xml.sax.SAXParseException saxParseException) throws o @Override public void startElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { - if (this.firstElement) - { - if (!lname.equalsIgnoreCase("sarTrackAnnotations")) + throws org.xml.sax.SAXException { + if (this.firstElement) { + if (!lname.equalsIgnoreCase("sarTrackAnnotations")) { throw new IllegalArgumentException("Not a SAR Track Annotations file"); - else + } else { this.firstElement = false; + } } - if (this.currentElement != null) - { + if (this.currentElement != null) { this.currentElement.startElement(uri, lname, qname, attributes); - } - else if (lname.equalsIgnoreCase("sarAnnotation")) - { + } else if (lname.equalsIgnoreCase("sarAnnotation")) { this.currentElement = new SARAnnotationElement(uri, lname, qname, attributes); } } @Override - public void endElement(String uri, String lname, String qname) throws org.xml.sax.SAXException - { - if (this.currentElement != null) - { + public void endElement(String uri, String lname, String qname) throws org.xml.sax.SAXException { + if (this.currentElement != null) { this.currentElement.endElement(uri, lname, qname); - if (lname.equalsIgnoreCase(this.currentElement.getElementName())) - { + if (lname.equalsIgnoreCase(this.currentElement.getElementName())) { // Get the SARAnnotation once the element is completely constructed. - if (this.currentElement instanceof SARAnnotationElement) + if (this.currentElement instanceof SARAnnotationElement) { SARAnnotationReader.this.sarAnnotations.add(((SARAnnotationElement) this.currentElement).getSARAnnotation()); + } this.currentElement = null; } } } @Override - public void characters(char[] data, int start, int length) throws org.xml.sax.SAXException - { - if (this.currentElement != null) + public void characters(char[] data, int start, int length) throws org.xml.sax.SAXException { + if (this.currentElement != null) { this.currentElement.characters(data, start, length); + } } } - private class SARAnnotationElement extends ElementParser - { + private class SARAnnotationElement extends ElementParser { + private double latitutde; private double longitude; private String id; private String text; - public SARAnnotationElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - { + public SARAnnotationElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) { super("sarAnnotation"); // don't perform validation here - no parameters are actually used } - public SARAnnotation getSARAnnotation() - { + public SARAnnotation getSARAnnotation() { Position pos = Position.fromDegrees(this.latitutde, this.longitude, 0); SARAnnotation sa = new SARAnnotation(this.text, pos); sa.setId(this.id); @@ -167,8 +147,7 @@ public SARAnnotation getSARAnnotation() @Override public void doStartElement(String uri, String lname, String qname, org.xml.sax.Attributes attributes) - throws org.xml.sax.SAXException - { + throws org.xml.sax.SAXException { // don't perform validation here - no parameters are actually used } @@ -180,30 +159,21 @@ public void doStartElement(String uri, String lname, String qname, org.xml.sax.A * @throws org.xml.sax.SAXException */ @Override - public void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException - { - if (lname == null) - { + public void doEndElement(String uri, String lname, String qname) throws org.xml.sax.SAXException { + if (lname == null) { String msg = Logging.getMessage("nullValue.LNameIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // don't validate uri or qname - they aren't used. - if (lname.equalsIgnoreCase("latitude")) - { + if (lname.equalsIgnoreCase("latitude")) { this.latitutde = Double.parseDouble(this.currentCharacters); - } - else if (lname.equalsIgnoreCase("longitude")) - { + } else if (lname.equalsIgnoreCase("longitude")) { this.longitude = Double.parseDouble(this.currentCharacters); - } - else if (lname.equalsIgnoreCase("id")) - { + } else if (lname.equalsIgnoreCase("id")) { this.id = this.currentCharacters.trim(); - } - else if (lname.equalsIgnoreCase("text")) - { + } else if (lname.equalsIgnoreCase("text")) { this.text = this.currentCharacters.trim(); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/SARAnnotationSupport.java b/src/gov/nasa/worldwindx/applications/sar/SARAnnotationSupport.java index e7281bb9aa..d07f0b7711 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARAnnotationSupport.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARAnnotationSupport.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.sar; import gov.nasa.worldwind.WorldWindow; @@ -29,11 +28,12 @@ /** * Handles SAR annotations + * * @author Patrick Murris * @version $Id: SARAnnotationSupport.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARAnnotationSupport -{ +public class SARAnnotationSupport { + private AnnotationLayer annotationLayer; private AnnotationAttributes defaults; private WorldWindow wwd; @@ -43,9 +43,7 @@ public class SARAnnotationSupport private Color savedBorderColor; private String angleFormat; - - public SARAnnotationSupport() - { + public SARAnnotationSupport() { this.annotationLayer = new AnnotationLayer(); this.helpMessageAnnotation = new ScreenAnnotation("", new Point(0, 0)); @@ -67,32 +65,26 @@ public SARAnnotationSupport() /** * Set the WorldWindow reference. Adds an annotation layer and a SelectListener to WW. + * * @param wwd the WorldWindow reference. */ - public void setWwd(WorldWindow wwd) - { + public void setWwd(WorldWindow wwd) { this.wwd = wwd; // Add annotation layer this.wwd.getModel().getLayers().add(this.annotationLayer); // Add a select listener to select or highlight annotations on rollover - this.wwd.addSelectListener(new SelectListener() - { + this.wwd.addSelectListener(new SelectListener() { private BasicDragger dragger = new BasicDragger(SARAnnotationSupport.this.wwd); - public void selected(SelectEvent event) - { + public void selected(SelectEvent event) { // Select/unselect on left click on annotations - if (event.getEventAction().equals(SelectEvent.LEFT_CLICK)) - { - if (event.hasObjects()) - { - if (event.getTopObject() instanceof Annotation) - { + if (event.getEventAction().equals(SelectEvent.LEFT_CLICK)) { + if (event.hasObjects()) { + if (event.getTopObject() instanceof Annotation) { // Check for text or url PickedObject po = event.getTopPickedObject(); - if(po.getValue(AVKey.TEXT) != null) - { + if (po.getValue(AVKey.TEXT) != null) { //System.out.println("Text: \"" + po.getValue(AVKey.TEXT) + "\" Hyperlink: " + po.getValue(AVKey.URL)); //if(SARAnnotationSupport.this.currentAnnotation == event.getTopObject()) // return; @@ -102,48 +94,37 @@ public void selected(SelectEvent event) } } - } - // Edit annotation on double click - else if (event.getEventAction().equals(SelectEvent.LEFT_DOUBLE_CLICK)) - { - if (event.hasObjects()) - { - if (event.getTopObject() instanceof Annotation) - { - edit((SARAnnotation)event.getTopObject()); + } // Edit annotation on double click + else if (event.getEventAction().equals(SelectEvent.LEFT_DOUBLE_CLICK)) { + if (event.hasObjects()) { + if (event.getTopObject() instanceof Annotation) { + edit((SARAnnotation) event.getTopObject()); } } - } - // Highlight on rollover - else if (event.getEventAction().equals(SelectEvent.ROLLOVER) && !this.dragger.isDragging()) - { + } // Highlight on rollover + else if (event.getEventAction().equals(SelectEvent.ROLLOVER) && !this.dragger.isDragging()) { highlight(event.getTopObject()); - } - // Have drag events drag the selected object. + } // Have drag events drag the selected object. else if (event.getEventAction().equals(SelectEvent.DRAG_END) - || event.getEventAction().equals(SelectEvent.DRAG)) - { - if (event.hasObjects()) - { + || event.getEventAction().equals(SelectEvent.DRAG)) { + if (event.hasObjects()) { // If selected annotation delegate dragging computations to a dragger. - if(event.getTopObject() == SARAnnotationSupport.this.currentAnnotation) - { + if (event.getTopObject() == SARAnnotationSupport.this.currentAnnotation) { this.dragger.selected(event); // Update help text when dragging updateHelpMessage(SARAnnotationSupport.this.currentAnnotation); // Mark the owner track as dirty. - if (SARAnnotationSupport.this.currentAnnotation.getOwner() != null) + if (SARAnnotationSupport.this.currentAnnotation.getOwner() != null) { SARAnnotationSupport.this.currentAnnotation.getOwner().markDirty(); + } } } // We missed any roll-over events while dragging, so highlight any under the cursor now, // or de-highlight the dragged shape if it's no longer under the cursor. - if (event.getEventAction().equals(SelectEvent.DRAG_END)) - { + if (event.getEventAction().equals(SelectEvent.DRAG_END)) { PickedObjectList pol = SARAnnotationSupport.this.wwd.getObjectsAtCurrentPosition(); - if (pol != null) - { + if (pol != null) { highlight(pol.getTopObject()); SARAnnotationSupport.this.wwd.redraw(); } @@ -154,12 +135,9 @@ else if (event.getEventAction().equals(SelectEvent.DRAG_END) }); // Add a mouse listener to deselect annotation on click anywhere - including terrain - this.wwd.getInputHandler().addMouseListener(new MouseAdapter() - { - public void mouseClicked(MouseEvent mouseEvent) - { - if (currentAnnotation != null && mouseEvent.getButton() == MouseEvent.BUTTON1) - { + this.wwd.getInputHandler().addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent mouseEvent) { + if (currentAnnotation != null && mouseEvent.getButton() == MouseEvent.BUTTON1) { select(null); mouseEvent.consume(); getWwd().redraw(); @@ -168,62 +146,52 @@ public void mouseClicked(MouseEvent mouseEvent) }); // Listen for angle format change - this.wwd.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent.getPropertyName() == SARKey.ANGLE_FORMAT) - setAngleFormat((String)propertyChangeEvent.getNewValue()); + this.wwd.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + if (propertyChangeEvent.getPropertyName() == SARKey.ANGLE_FORMAT) { + setAngleFormat((String) propertyChangeEvent.getNewValue()); + } } }); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.wwd; } - public String getAngleFormat() - { + public String getAngleFormat() { return this.angleFormat; } - public void setAngleFormat(String format) - { + public void setAngleFormat(String format) { this.angleFormat = format; updateHelpMessage(this.lastPickedObject); } - - private void select(Object o) - { - if(this.currentAnnotation != null) - { + + private void select(Object o) { + if (this.currentAnnotation != null) { // Unselect current //this.currentAnnotation.getAttributes().setHighlighted(false); this.currentAnnotation.getAttributes().setBorderColor(SARAnnotationSupport.this.savedBorderColor); } - if(o != null && o instanceof SARAnnotation && this.currentAnnotation != o) - { + if (o != null && o instanceof SARAnnotation && this.currentAnnotation != o) { // Select new one if not current one already - this.currentAnnotation = (SARAnnotation)o; + this.currentAnnotation = (SARAnnotation) o; //this.currentAnnotation.getAttributes().setHighlighted(true); this.savedBorderColor = this.currentAnnotation.getAttributes().getBorderColor(); this.currentAnnotation.getAttributes().setBorderColor(Color.YELLOW); - } - else - { + } else { // Clear current annotation this.currentAnnotation = null; // switch off } } - private void highlight(Object o) - { + private void highlight(Object o) { // Manage highlighting of Annotations. - if (this.lastPickedObject == o) + if (this.lastPickedObject == o) { return; // same thing selected - + } // Turn off highlight if on. if (this.lastPickedObject != null) // && this.lastPickedObject != this.currentAnnotation) { @@ -233,18 +201,15 @@ private void highlight(Object o) } // Turn on highlight if object selected. - if (o != null && o instanceof SARAnnotation) - { + if (o != null && o instanceof SARAnnotation) { this.lastPickedObject = (SARAnnotation) o; this.lastPickedObject.getAttributes().setHighlighted(true); updateHelpMessage(this.lastPickedObject); // Update help text } } - private void updateHelpMessage(SARAnnotation annotation) - { - if (annotation != null) - { + private void updateHelpMessage(SARAnnotation annotation) { + if (annotation != null) { Position pos = annotation.getPosition(); this.helpMessageAnnotation.getAttributes().setVisible(true); this.helpMessageAnnotation.setText(String.format("Lat %s Lon %s", @@ -253,36 +218,34 @@ private void updateHelpMessage(SARAnnotation annotation) // set help message screen position - follow annotation Vec4 surfacePoint = this.getWwd().getSceneController().getTerrain().getSurfacePoint( pos.getLatitude(), pos.getLongitude()); - if (surfacePoint == null) - { + if (surfacePoint == null) { Globe globe = this.getWwd().getModel().getGlobe(); surfacePoint = globe.computePointFromPosition(pos.getLatitude(), pos.getLongitude(), globe.getElevation(pos.getLatitude(), pos.getLongitude())); } Vec4 screenPoint = this.getWwd().getView().project(surfacePoint); - if (screenPoint != null) - this.helpMessageAnnotation.setScreenPoint(new Point((int)screenPoint.x, (int)screenPoint.y)); - } - else - { + if (screenPoint != null) { + this.helpMessageAnnotation.setScreenPoint(new Point((int) screenPoint.x, (int) screenPoint.y)); + } + } else { this.helpMessageAnnotation.getAttributes().setVisible(false); } } /** * Add a new annotation in the screen center. + * * @param text the Annotation text. - * @param owner if not null, the SARTrack to add the annotation to. - * annotation's border and text will be colored according to the owner SARTrack. + * @param owner if not null, the SARTrack to add the annotation to. annotation's border and text will be colored + * according to the owner SARTrack. */ - public void addNew(String text, SARTrack owner) - { - if (text == null) + public void addNew(String text, SARTrack owner) { + if (text == null) { text = showAnnotationDialog("Add New Annotation", null); + } - OrbitView view = (OrbitView)this.wwd.getView(); - if(text != null && text.length() > 0 && view != null) - { + OrbitView view = (OrbitView) this.wwd.getView(); + if (text != null && text.length() > 0 && view != null) { Position centerPosition = new Position(view.getCenterPosition(), 0); SARAnnotation annotation = new SARAnnotation(text, centerPosition); addNew(annotation, owner); @@ -290,16 +253,13 @@ public void addNew(String text, SARTrack owner) } } - public void addNew(SARAnnotation annotation, SARTrack owner) - { - if (annotation != null) - { + public void addNew(SARAnnotation annotation, SARTrack owner) { + if (annotation != null) { annotation.getAttributes().setDefaults(this.defaults); // Reduce annotation distance scaling effect annotation.getAttributes().setDistanceMinScale(0.7); annotation.getAttributes().setDistanceMaxScale(1.3); - if (owner != null) - { + if (owner != null) { annotation.setOwner(owner); annotation.getAttributes().setTextColor(owner.getColor()); //annotation.getAttributes().setBorderColor(color); @@ -310,15 +270,16 @@ public void addNew(SARAnnotation annotation, SARTrack owner) /** * Multi line input dialog. Returns the input text or null if canceled. + * * @param title the dialog window title. * @param text the initial text. * @return the input text or null if the dialog was canceled. */ - private String showAnnotationDialog(String title, String text) - { + private String showAnnotationDialog(String title, String text) { final JTextArea textArea = new JTextArea(5, 10); - if (text != null) + if (text != null) { textArea.setText(text); + } // Focus to text area from http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6420212 textArea.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent he) { @@ -335,60 +296,55 @@ public void run() { }); int dialogResult = -1; JScrollPane pane = new JScrollPane(textArea); - if (text != null && text.length() > 0) - { + if (text != null && text.length() > 0) { Object[] options = {"Save", "Delete", "Cancel"}; - dialogResult = JOptionPane.showOptionDialog(null, new Object[] {"Enter text", pane}, title, + dialogResult = JOptionPane.showOptionDialog(null, new Object[]{"Enter text", pane}, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); - } - else - { - dialogResult = JOptionPane.showOptionDialog(null, new Object[] {"Enter text", pane}, title, + } else { + dialogResult = JOptionPane.showOptionDialog(null, new Object[]{"Enter text", pane}, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); } String newText = null; - if (dialogResult == JOptionPane.OK_OPTION || dialogResult == JOptionPane.YES_OPTION) + if (dialogResult == JOptionPane.OK_OPTION || dialogResult == JOptionPane.YES_OPTION) { newText = textArea.getText(); - if (dialogResult == JOptionPane.NO_OPTION) + } + if (dialogResult == JOptionPane.NO_OPTION) { newText = ""; + } return newText; } /** * Add an annotation. + * * @param annotation the annotation to add. */ - public void add(SARAnnotation annotation) - { - if(annotation != null) - { + public void add(SARAnnotation annotation) { + if (annotation != null) { annotationLayer.addAnnotation(annotation); // Mark the SARTrack as dirty. - if (annotation.getOwner() != null) + if (annotation.getOwner() != null) { annotation.getOwner().markDirty(); + } } } /** * Edit an annotation. + * * @param annotation the Annotation to be edited. */ - public void edit(SARAnnotation annotation) - { - if(annotation != null) - { + public void edit(SARAnnotation annotation) { + if (annotation != null) { String text = showAnnotationDialog("Edit Annotation", annotation.getText()); - if(text != null) - { - if (text.length() > 0) - { + if (text != null) { + if (text.length() > 0) { annotation.setText(text); // Mark the owner track as dirty. - if (annotation.getOwner() != null) + if (annotation.getOwner() != null) { annotation.getOwner().markDirty(); - } - else - { + } + } else { // The remove operation will mark the // owner track as tirty. this.remove(annotation); @@ -400,58 +356,56 @@ public void edit(SARAnnotation annotation) /** * Remove an annotation. + * * @param annotation the annotation to be removed. */ - public void remove(SARAnnotation annotation) - { - if (annotation != null) - { + public void remove(SARAnnotation annotation) { + if (annotation != null) { annotationLayer.removeAnnotation(annotation); - if (currentAnnotation == annotation) + if (currentAnnotation == annotation) { currentAnnotation = null; + } // Mark the SARTrack as dirty. - if (annotation.getOwner() != null) + if (annotation.getOwner() != null) { annotation.getOwner().markDirty(); + } } } - public void removeAnnotationsForTrack(SARTrack owner) - { - for (SARAnnotation sa : getAnnotationsForTrack(owner)) - { - if (sa != null) + public void removeAnnotationsForTrack(SARTrack owner) { + for (SARAnnotation sa : getAnnotationsForTrack(owner)) { + if (sa != null) { remove(sa); + } } } /** * Get current annotation. + * * @return current annotation. */ - public SARAnnotation getCurrent() - { + public SARAnnotation getCurrent() { return currentAnnotation; } /** * Get the annotation collection from the RenderableLayer + * * @return an Annotation collection. */ - public Iterable getAnnotations() - { - return annotationLayer.getAnnotations(); + public Iterable getAnnotations() { + return annotationLayer.getAnnotations(); } - public Iterable getAnnotationsForTrack(SARTrack owner) - { + public Iterable getAnnotationsForTrack(SARTrack owner) { java.util.ArrayList result = new java.util.ArrayList(); - for (Annotation a : this.annotationLayer.getAnnotations()) - { - if (a != null && a instanceof SARAnnotation) - { - if (owner == ((SARAnnotation) a).getOwner()) + for (Annotation a : this.annotationLayer.getAnnotations()) { + if (a != null && a instanceof SARAnnotation) { + if (owner == ((SARAnnotation) a).getOwner()) { result.add((SARAnnotation) a); + } } } return result; @@ -459,70 +413,57 @@ public Iterable getAnnotationsForTrack(SARTrack owner) /** * Set annotations enabled state + * * @param state true if annotations should be enabled. */ - public void setEnabled(boolean state) - { + public void setEnabled(boolean state) { annotationLayer.setEnabled(state); } /** * Get the annotations enabled state. + * * @return true if annotations are enabled. */ - public boolean getEnabled() - { + public boolean getEnabled() { return annotationLayer.isEnabled(); } /** * Get the default attribute set used for all annotations. + * * @return the default attribute set used for all annotations. */ - public AnnotationAttributes getDefaults() - { + public AnnotationAttributes getDefaults() { return this.defaults; } - public void writeAnnotations(String filePath, SARTrack trackOwner) throws IOException - { - try - { - if (filePath != null) - { + public void writeAnnotations(String filePath, SARTrack trackOwner) throws IOException { + try { + if (filePath != null) { SARAnnotationWriter writer = new SARAnnotationWriter(filePath); writer.writeAnnotations(getAnnotationsForTrack(trackOwner)); writer.close(); } - } - catch (javax.xml.parsers.ParserConfigurationException e) - { + } catch (javax.xml.parsers.ParserConfigurationException e) { throw new IllegalArgumentException(e); - } - catch (javax.xml.transform.TransformerException e) - { + } catch (javax.xml.transform.TransformerException e) { throw new IllegalArgumentException(e); } } - public void readAnnotations(String filePath, SARTrack trackOwner) throws IOException - { - try - { - if (filePath != null) - { + public void readAnnotations(String filePath, SARTrack trackOwner) throws IOException { + try { + if (filePath != null) { SARAnnotationReader reader = new SARAnnotationReader(); reader.readFile(filePath); - for (SARAnnotation sa : reader.getSARAnnotations()) + for (SARAnnotation sa : reader.getSARAnnotations()) { addNew(sa, trackOwner); + } } - } - catch (javax.xml.parsers.ParserConfigurationException e) - { + } catch (javax.xml.parsers.ParserConfigurationException e) { throw new IllegalArgumentException(e); - } - catch (org.xml.sax.SAXException e) - { + } catch (org.xml.sax.SAXException e) { throw new IllegalArgumentException(e); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/SARAnnotationWriter.java b/src/gov/nasa/worldwindx/applications/sar/SARAnnotationWriter.java index e3c92682a8..781b92d8f7 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARAnnotationWriter.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARAnnotationWriter.java @@ -11,15 +11,13 @@ * @author dcollins * @version $Id: SARAnnotationWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARAnnotationWriter -{ +public class SARAnnotationWriter { + private final org.w3c.dom.Document doc; private final javax.xml.transform.Result result; - public SARAnnotationWriter(String path) throws java.io.IOException, javax.xml.parsers.ParserConfigurationException - { - if (path == null) - { + public SARAnnotationWriter(String path) throws java.io.IOException, javax.xml.parsers.ParserConfigurationException { + if (path == null) { String msg = Logging.getMessage("nullValue.PathIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -31,10 +29,8 @@ public SARAnnotationWriter(String path) throws java.io.IOException, javax.xml.pa createAnnotationsDocument(this.doc); } - public SARAnnotationWriter(java.io.OutputStream stream) throws java.io.IOException, javax.xml.parsers.ParserConfigurationException - { - if (stream == null) - { + public SARAnnotationWriter(java.io.OutputStream stream) throws java.io.IOException, javax.xml.parsers.ParserConfigurationException { + if (stream == null) { String msg = Logging.getMessage("nullValue.InputStreamIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -46,10 +42,8 @@ public SARAnnotationWriter(java.io.OutputStream stream) throws java.io.IOExcepti createAnnotationsDocument(this.doc); } - public void writeAnnotation(SARAnnotation sarAnnotation) throws javax.xml.transform.TransformerException - { - if (sarAnnotation == null) - { + public void writeAnnotation(SARAnnotation sarAnnotation) throws javax.xml.transform.TransformerException { + if (sarAnnotation == null) { String msg = "nullValue.SARAnnotationIsNull"; Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -58,74 +52,65 @@ public void writeAnnotation(SARAnnotation sarAnnotation) throws javax.xml.transf doWriteAnnotation(sarAnnotation, this.doc.getDocumentElement()); } - public void writeAnnotations(Iterable sarAnnotations) throws javax.xml.transform.TransformerException - { - if (sarAnnotations == null) - { + public void writeAnnotations(Iterable sarAnnotations) throws javax.xml.transform.TransformerException { + if (sarAnnotations == null) { String msg = "nullValue.SARAnnotationIterableIsNull"; Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - for (SARAnnotation sa : sarAnnotations) - { - if (sa != null) + for (SARAnnotation sa : sarAnnotations) { + if (sa != null) { doWriteAnnotation(sa, this.doc.getDocumentElement()); + } } doFlush(); } - public void close() - { + public void close() { // Intentionally left blank, // as a placeholder for future functionality. } - private void createAnnotationsDocument(org.w3c.dom.Document doc) - { + private void createAnnotationsDocument(org.w3c.dom.Document doc) { // Create the GPX document root when the document // doesn't already have a root element. - if (doc != null) - { - if (doc.getDocumentElement() != null) + if (doc != null) { + if (doc.getDocumentElement() != null) { doc.removeChild(doc.getDocumentElement()); + } org.w3c.dom.Element annotations = doc.createElement("sarTrackAnnotations"); doc.appendChild(annotations); } } - private void doWriteAnnotation(SARAnnotation sarAnnotation, org.w3c.dom.Element elem) - { - if (sarAnnotation != null) - { + private void doWriteAnnotation(SARAnnotation sarAnnotation, org.w3c.dom.Element elem) { + if (sarAnnotation != null) { org.w3c.dom.Element anno = this.doc.createElement("sarAnnotation"); - if (sarAnnotation.getPosition() != null) - { + if (sarAnnotation.getPosition() != null) { org.w3c.dom.Element lat = this.doc.createElement("latitude"); org.w3c.dom.Text latText = this.doc.createTextNode( - Double.toString(sarAnnotation.getPosition().getLatitude().degrees)); + Double.toString(sarAnnotation.getPosition().getLatitude().degrees)); lat.appendChild(latText); anno.appendChild(lat); org.w3c.dom.Element lon = this.doc.createElement("longitude"); org.w3c.dom.Text lonText = this.doc.createTextNode( - Double.toString(sarAnnotation.getPosition().getLongitude().degrees)); + Double.toString(sarAnnotation.getPosition().getLongitude().degrees)); lon.appendChild(lonText); anno.appendChild(lon); } - if (sarAnnotation.getId() != null) - { + if (sarAnnotation.getId() != null) { org.w3c.dom.Element id = this.doc.createElement("id"); org.w3c.dom.Text idText = this.doc.createTextNode(sarAnnotation.getId()); id.appendChild(idText); anno.appendChild(id); } - if (sarAnnotation.getText() != null) - { + if (sarAnnotation.getText() != null) { org.w3c.dom.Element text = this.doc.createElement("text"); org.w3c.dom.CDATASection cdata = this.doc.createCDATASection(sarAnnotation.getText()); text.appendChild(cdata); @@ -136,8 +121,7 @@ private void doWriteAnnotation(SARAnnotation sarAnnotation, org.w3c.dom.Element } } - private void doFlush() throws javax.xml.transform.TransformerException - { + private void doFlush() throws javax.xml.transform.TransformerException { javax.xml.transform.TransformerFactory factory = javax.xml.transform.TransformerFactory.newInstance(); javax.xml.transform.Transformer transformer = factory.newTransformer(); javax.xml.transform.Source source = new javax.xml.transform.dom.DOMSource(this.doc); diff --git a/src/gov/nasa/worldwindx/applications/sar/SARApp.java b/src/gov/nasa/worldwindx/applications/sar/SARApp.java index e26a437399..2ada94cab0 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARApp.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARApp.java @@ -11,42 +11,35 @@ * @author tag * @version $Id: SARApp.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARApp -{ +public class SARApp { + public static final String APP_NAME = "WorldWind Search and Rescue Prototype"; public static final String APP_VERSION = "(Version 6.2 released 7/15/2010)"; public static final String APP_NAME_AND_VERSION = APP_NAME + " " + APP_VERSION; - static - { + static { System.setProperty("gov.nasa.worldwind.config.file", - "gov/nasa/worldwindx/applications/sar/config/SAR.properties"); - if (Configuration.isMacOS()) - { + "gov/nasa/worldwindx/applications/sar/config/SAR.properties"); + if (Configuration.isMacOS()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", APP_NAME); System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); } } - private static boolean checkLicenseAgreement() - { + private static boolean checkLicenseAgreement() { NOSALicenseAgreement licenseAgreement = new NOSALicenseAgreement(APP_NAME_AND_VERSION); String status = licenseAgreement.checkForLicenseAgreement(null); return (status.equals(NOSALicenseAgreement.LICENSE_ACCEPTED) - || status.equals(NOSALicenseAgreement.LICENSE_ACCEPTED_AND_INSTALLED)); + || status.equals(NOSALicenseAgreement.LICENSE_ACCEPTED_AND_INSTALLED)); } - public static void main(String[] args) - { + public static void main(String[] args) { boolean licenseStatus = checkLicenseAgreement(); - if (licenseStatus) - { + if (licenseStatus) { SAR2 appFrame = new SAR2(); appFrame.setVisible(true); - } - else - { + } else { System.exit(0); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/SARHelp.html b/src/gov/nasa/worldwindx/applications/sar/SARHelp.html index 247766692f..1d20e08868 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARHelp.html +++ b/src/gov/nasa/worldwindx/applications/sar/SARHelp.html @@ -2,529 +2,529 @@ ~ Copyright (C) 2012 United States Government as represented by the Administrator of the ~ National Aeronautics and Space Administration. ~ All Rights Reserved. - --> +--> - - - Search and Rescue Help - - - - - - -

          WorldWind Search and Rescue Instructions

          - -

          Panels and Controls

          -SAR Application Frame - -

          -There are three panels in the application: -

          -
            -
          • The main graphics window. See Viewing Controls below for interaction controls.
          • -
          • The Tracks panel, listing the currently loaded tracks and the points of the current track. Any field of - the displayed track can be edited by double-clicking it and entering a new value. Positions can be added, - inserted or deleted via the context menu (right-click menu). New tracks can be added via the File menu in the - menu bar. An offset can be added to all positions via the Offset spinner at top right. An offset value can be - set explicitly by entering it in the field. -
          • -
          • The Position panel, for position control along the current track. This panel displays the current track - position and provides ways to move the position either directly or under timed control. The leftmost number box - and the slider adjacent to it indicate and control the current track position within a track segment. The box - identifies the first point of the segment. The slider indicates the relative distance between the two segment - points. -
          • -
          -

          - A menu bar and a tool bar located at the top of the window provide access to the application functions, tools - and options. See Menu bar description and Tool bar description below. -

          - - -

          Menu bar description

          -

          - From left to right: -

          -
            -
          • File - provide options for managing tracks and downloading imagery and elevation data for a particular sector.

            + + + Search and Rescue Help + + + + + + +

            WorldWind Search and Rescue Instructions

            + +

            Panels and Controls

            + SAR Application Frame + +

            + There are three panels in the application: +

              -
            • New Track... - Create a new track - (Ctrl-N).
            • -
            • Open Track File... - Open a track from a local file - (Ctrl-O).
            • -
            • Open Track URL... - Open a track from a remote URL - (Ctrl-U).
            • -
            • Close Track - Close the current track - (Ctrl-F4).
            • -
            • Save Track - Save the current track - (Ctrl-S).
            • -
            • Save Track As... - Save the current track in a different file or location - (Ctrl-Shift-S).
            • -
            • Preferences... - Open the Preference window - track auto save...
            • -
            • Bulk Download... - Open the Bulk Download window - (Ctrl-B).
            • -
            • Exit - Quit the application - (Alt-F4).
            • +
            • The main graphics window. See Viewing Controls below for interaction controls.
            • +
            • The Tracks panel, listing the currently loaded tracks and the points of the current track. Any field of + the displayed track can be edited by double-clicking it and entering a new value. Positions can be added, + inserted or deleted via the context menu (right-click menu). New tracks can be added via the File menu in the + menu bar. An offset can be added to all positions via the Offset spinner at top right. An offset value can be + set explicitly by entering it in the field. +
            • +
            • The Position panel, for position control along the current track. This panel displays the current track + position and provides ways to move the position either directly or under timed control. The leftmost number box + and the slider adjacent to it indicate and control the current track position within a track segment. The box + identifies the first point of the segment. The slider indicates the relative distance between the two segment + points. +
            -
          • -
          • Units - Meter vs Feet and Decimal Degrees vs DMS.

            +

            + A menu bar and a tool bar located at the top of the window provide access to the application functions, tools + and options. See Menu bar description and Tool bar description below. +

            + + +

            Menu bar description

            +

            + From left to right: +

              -
            • Meters - Set the distance units to meter and kilometers - (Ctrl - M).
            • -
            • Feet - Set the distance unit to feet and miles - (Alt - M).
            • -
            • Angle DD - Set the angular display to decimal degrees - (Ctrl - D).
            • -
            • Angle DMS - Set the angular display to degrees, minutes and seconds - (Alt - D).
            • +
            • File - provide options for managing tracks and downloading imagery and elevation data for a particular sector.

              +
                +
              • New Track... - Create a new track - (Ctrl-N).
              • +
              • Open Track File... - Open a track from a local file - (Ctrl-O).
              • +
              • Open Track URL... - Open a track from a remote URL - (Ctrl-U).
              • +
              • Close Track - Close the current track - (Ctrl-F4).
              • +
              • Save Track - Save the current track - (Ctrl-S).
              • +
              • Save Track As... - Save the current track in a different file or location - (Ctrl-Shift-S).
              • +
              • Preferences... - Open the Preference window - track auto save...
              • +
              • Bulk Download... - Open the Bulk Download window - (Ctrl-B).
              • +
              • Exit - Quit the application - (Alt-F4).
              • +
              +
            • +
            • Units - Meter vs Feet and Decimal Degrees vs DMS.

              +
                +
              • Meters - Set the distance units to meter and kilometers - (Ctrl - M).
              • +
              • Feet - Set the distance unit to feet and miles - (Alt - M).
              • +
              • Angle DD - Set the angular display to decimal degrees - (Ctrl - D).
              • +
              • Angle DMS - Set the angular display to degrees, minutes and seconds - (Alt - D).
              • +
              +
            • +
            • Annotation - add or remove annotations. See Annotations

              +
                +
              • New Annotation... - Add an annotation on the terrain - (Ctrl-A).
              • +
              • Remove Annotation - Remove the currently selected annotation - (Ctrl-Shift-A).
              • +
              • Show Annotations - Turn on and off annotation display - (Alt-A).
              • +
              +
            • +
            • View - turn on and off display options. Terrain profile and cloud contour controls.

              +
                +
              • Scalebar - Turn on and off the scalebar display.
              • +
              • Aircraft Location - Turn on and off the aircraft location display.
              • +
              • Crosshair - Turn on and off the crosshair display.
              • +
              • Compass - Turn on and off the compass display.
              • +
              • Terrain Profile... - Open the Terrain Profile control window. See Terrain Profile Modes - (Ctrl-T)
              • +
              • Cloud Contour... - Open the Cloud Contour control window. See Cloud Contour - (Ctrl-C)
              • +
              +
            • +
            • Layers - turn on and off imagery layers.

              +
                +
              • NASA Blue Marble - The NASA Blue Marble Next Generation 250m Earth global imagery.
              • +
              • I-Cubed Lansat - Landsat 7 Global 15m imagery
              • +
              • MS Virtual Earth Aerial - Global Microsoft layerset with resolutions of 1m and less in some parts of the world.
              • +
              • NAIP California - USDA NAIP 1m imagery for California
              • +
              • USGS Digital Ortho - Black and white 1m imagery for continental US. This layer is applied with some tranparency.
              • +
              • USGS Urban Area Ortho - Color 1m or less imagery for some US urban areas
              • +
              • USGS Topographics Maps - US Topographic maps
              • +
              +
            • +
            • Help.

              +
                +
              • Help - Displays this documentation - (F1).
              • +
              • About - Displays informations about this application.
              • +
              +
            -
          • -
          • Annotation - add or remove annotations. See Annotations

            + + +

            Tool bar description

            + SAR Tollbar + +

            + From left to right: +

            +
              +
            • Track managment - See Track Management.

              +
                +
              • Open Track File - Open a track from a local file - (Ctrl-O).
              • +
              • New Track - Create a new track - (Ctrl-N).
              • +
              • Save Track - Save the current track - (Ctrl-S).
              • +
              +
            • +
            • View Modes - See View Modes.

              +
                +
              • Examine.
              • +
              • Fly-It.
              • +
              • Free.
              • +
              +
            • +
            • Track Info - turns on and off current track segment information display.

            • +
            • Track extension - See Track Extension.

              +
                +
              • Extension with segment plane.
              • +
              • Extension in the air.
              • +
              • Extension on the ground.
              • +
              • Remove last track point.
              • +
              • Move to next point.
              • +
              +
            • +
            • Tools.

              +
                +
              • Terrain Profile - Open the Terrain Profile control window. See Terrain Profile Modes - (Ctrl-T)
              • +
              • Cloud Contour - Open the Cloud Contour control window. See Cloud Contour - (Ctrl-C)
              • +
              +
            • +
            • Help.

            • +
            + + +

            Track Management

            + +

            Loading and saving tracks

            +
              -
            • New Annotation... - Add an annotation on the terrain - (Ctrl-A).
            • -
            • Remove Annotation - Remove the currently selected annotation - (Ctrl-Shift-A).
            • -
            • Show Annotations - Turn on and off annotation display - (Alt-A).
            • +
            • To load a track from a local file either click on the 'folder' icon in the tool bar, or select + the File->Open track file... menu option, or use the keyboard shortcut Ctrl-O. Select the proper + file and click "Open".
            • +
            • To load a track from a remote file either select the File->Open track URL... menu option, or use the + keyboard shortcut Ctrl-U. Enter the file URL and click "OK".
            • +
            • To create a new track either click on the 'blank page' icon in the tool bar, or select the File->New Track... + menu option or use the keyboard shortcut Ctrl-N. Enter a track name and click "OK". To build the track path see + Managing track points below.
            • +
            • To Save the current track either click on the 'floppy disk' icon in the tool bar, or select the + File->Save Track menu option or use the keyboard shortcut Ctrl-S. Note that tracks are automaticaly saved + every minutes - see File->Preferences...
            • +
            • To save the current track in a different file or location, select the File->Save Track As... menu option or + use the keyboard shortcut Ctrl-Shift-S.
            • +
            • To close the current track select the File->Close Track menu option or use the keyboard shortcut Ctrl-F4. + If the track as been edited since it was opened, a dialog window will offer to save it before closing it.
            -
          • -
          • View - turn on and off display options. Terrain profile and cloud contour controls.

            + + +

            Managing track points

            + +

            A track is made of a list of points each with a geographic position and altitude. Track points are displayed + and managed in the track panel on the left of the graphic window. Any field of the displayed list + can be edited by double-clicking it and entering a new value. New points can be added, inserted or deleted via + the context menu (right-click menu).

            + + SAR Track Panel Context Menu + +

            To add a position to the current track, right click on the track panel and select "Append New Position to Track" + in the context menu. A new track point is added to the track with the same location and altitude as the previous + point if there is one. Double click on the new point latitude, longitude or altitude to edit the values.

            + +

            To remove a track point, first click on the corresponding row in the list to select it, then right click and + choose the "Delete Selected Position" option in the context menu.

            + +

            In a similar way, new positions can be inserted before or after the selected row.

            + +

            The "Add Offset to Selected Positions" option will increment or decrement the selected points altitude of the current + track offset value - at top right of the track panel.

            + + + +

            Track extension

            + +

            + New track points can also be added by visualy placing them in the graphic window. +

            + SAR Track Extension Tools + +

            + To activate one of the three extension modes, click on the corresponding icon in the tool bar - the other + two icons become 'disabled', use the tool to add new track points, then click again on the icon in the tool bar + to deactivate the extension mode. +

            + SAR Track Extension Plane +
              -
            • Scalebar - Turn on and off the scalebar display.
            • -
            • Aircraft Location - Turn on and off the aircraft location display.
            • -
            • Crosshair - Turn on and off the crosshair display.
            • -
            • Compass - Turn on and off the compass display.
            • -
            • Terrain Profile... - Open the Terrain Profile control window. See Terrain Profile Modes - (Ctrl-T)
            • -
            • Cloud Contour... - Open the Cloud Contour control window. See Cloud Contour - (Ctrl-C)
            • +
            • Extension using the '3D segment plane'. This mode displays a vertical 'extension plane' at the end + of the track. The plane can be orientated using the green corner 'handles' and extended with the pink side + 'handles'. Once the plane is in the suitable position a new track point can be added by clicking inside + the plane. After a point has been added, it's position can be adjusted with the mouse cursor. To place yet + another point, click on the "Move to next point" icon in the tool bar. The extension plane will move at the + track end and you can repeat the process.
            • +
            • Extension in the air. This mode lets you add new track points by clicking on the terrain surface + while holding down the Alt key. Each new point will have the same altitude as the preceding one. To add a + new point, press and hold the Alt key, position the mouse cursor at the approximate location where the new + point should appear and press the left mouse button. While holding down the mouse button, move the cursor + to adjust the new point location. Release the mouse button when done. Note that you don't need to keep the + Alt key pressed while adjusting the new point location.
            • +
            • Extension on the ground. This mode works exactly like the 'in air' extension mode except new points + will be placed at ground elevation. Double click on the new points altitude cells in the track panel to edit + the values.
            -
          • -
          • Layers - turn on and off imagery layers.

            + +

            While an extension mode is active, the last track point can be removed by clicking on the "Remove last track point" + icon in the tool bar.

            + + + +

            View Modes

            + SAR View Modes + +

            + The three view modes allow you to explore tracks in different ways: +

              -
            • NASA Blue Marble - The NASA Blue Marble Next Generation 250m Earth global imagery.
            • -
            • I-Cubed Lansat - Landsat 7 Global 15m imagery
            • -
            • MS Virtual Earth Aerial - Global Microsoft layerset with resolutions of 1m and less in some parts of the world.
            • -
            • NAIP California - USDA NAIP 1m imagery for California
            • -
            • USGS Digital Ortho - Black and white 1m imagery for continental US. This layer is applied with some tranparency.
            • -
            • USGS Urban Area Ortho - Color 1m or less imagery for some US urban areas
            • -
            • USGS Topographics Maps - US Topographic maps
            • +
            • +

              + FREE mode provides unconstrained viewing control. You use it to explore tracks and terrain from any + angle and position. +

              +
            • +
            • +

              + FLY-IT mode simulates the pilot's view. Selecting this mode positions the view + at the current track position indicated in the Position panel. + The view's heading is to that from the first to last positions of the segment. + Moving the current position, either manually via the position slider or + timed via the player controls, moves the view along the segment either forward or backwards. +

              + +

              + The speed of timed movement can be controlled via the Speed spinner located below the player controls. +

              +
            • +
            • +

              + EXAMINE mode is similar to Fly-It mode but the view follows the track from the side, at any angle and + distance the user desires. This is the view a chaser aircraft would have. This mode attempts to keep the + view focussed on a point on the ground just below the current position while the user manipulates the + view to useful perspectives. +

              +
            -
          • -
          • Help.

            + + +

            Terrain Profile

            + +

            + To bring up the terrain profile control window, either: +

              -
            • Help - Displays this documentation - (F1).
            • -
            • About - Displays informations about this application.
            • +
            • Click on the "Terrain Profile" icon in the tool bar.
            • +
            • Use the keyboard shortcut Ctrl-T
            • +
            • Select the View->Terrain Profile... menu option
            -
          • -
          - - -

          Tool bar description

          -SAR Tollbar - -

          - From left to right: -

          -
            -
          • Track managment - See Track Management.

            + SAR Terrain Profile + +

            + The top-left 'pulldown' menu lets you set the terrain profile graph size to "Small", "Medium" or "Large". +

            +

            + The top-right 'pulldown' menu in the terrain profile panel determines the terrain cross section position. The yellow line + in the graphics window shows the cross section's current position. At all times the terrain profile + displays the elevations of the terrain intersected by this line. The "Profile at/under..." selection can have the following + values: +

              -
            • Open Track File - Open a track from a local file - (Ctrl-O).
            • -
            • New Track - Create a new track - (Ctrl-N).
            • -
            • Save Track - Save the current track - (Ctrl-S).
            • +
            • +

              + Profile at Screen Center places the terrain cross section constantly at the center of the view. You manipulate the + globe to change the terrain measured. +

              +
            • +
            • +

              + Profile Under Cursor places the center of the cross section at the cursor (mouse) position. Moving the + cursor moves the cross section over the globe's surface. +

              +
            • +
            • +

              + Profile Under Eye is meant to be used in "Fly-It" view mode described in the View Modes section + above. It positions the cross section on the surface directly below the pilot, perpendicular to the + current heading and centered on the current track position. The profile graph displays the cross section + directly to the pilot's left and right. This terrain profile mode is not intended to be used with view modes + other than Fly-It. +

              +
            • +
            • +

              + Profile Under Aircraft positions the cross section perpendicular to and centered on the current track at the + current track position. This mode enables you to watch the cross section move along the track while in + Examine or Free view modes. In Examine mode the view will follow the current track position, therefore the + cross section will remain centered in the graphics window while the view moves along the current track. In + Free mode the view will be stationary but the cross section will move along the track, requiring the user + to continually adjust the view to keep the cross section in sight. +

              +

              + When the profile is set to be under the aircraft, a second profile is also displayed in the right portion + of the graphic window. This one is perpendicular to the other and follows the track direction. +

              +
            • +
            • +

              + No Profile Turn off the cross section and terrain profile. +

              +
            -
          • -
          • View Modes - See View Modes.

            + +

            Terrain Profile Controls

            + +

            + The following controls let you adjust the terrain profile size and behavior: +

              -
            • Examine.
            • -
            • Fly-It.
            • -
            • Free.
            • +
            • Proportional: determines whether the width and height of the profile graph are to the + same scale.
            • +
            • MSL Base determines whether the graph shows elevations relative to mean sea level or the current minimum elevation along the + cross section.
            • +
            • Show A/C Position determines whether the aircraft position should be indicated in the profile. The + aircraft point can be shown only when the terrain profile position is "Under Aircraft".
            • +
            • Profile Width lets you increase the perpendicular profile extent on both sides of the track.
            • +
            • Profile Length when the profile is set to be under the aircraft, lets you increase the 'along the track' + profile extent both ahead and behind the aircraft.
            • +
            • Same Size when checked both profiles will have the same extent.
            • +
            • Whole Track Length when checked, the 'along the track' profile will cover the whole track length.
            -
          • -
          • Track Info - turns on and off current track segment information display.

          • -
          • Track extension - See Track Extension.

            + +

            + Anytime, one graph or the other can be either 'minimized' - and becomes an icon, or 'maximized' - it will then + fill the whole screen, by clicking on the + and - buttons in the upper right corner of each graph display. +

            + + +

            Cloud contour

            +

            + To activate and control the cloud contour visualization either: +

              -
            • Extension with segment plane.
            • -
            • Extension in the air.
            • -
            • Extension on the ground.
            • -
            • Remove last track point.
            • -
            • Move to next point.
            • +
            • Click on the Cloud icon in the tool bar
            • +
            • Use the keyboad shortcut Ctrl-C
            • +
            • Select the View->Cloud Contour... menu option
            -
          • -
          • Tools.

            + SAR Cloud Contour + +

            + This brings up a separate window that lets you turn the visualization on and off, and control the cloud + ceiling. To set up a cloud layer at a given altitude, follow these steps: +

              -
            • Terrain Profile - Open the Terrain Profile control window. See Terrain Profile Modes - (Ctrl-T)
            • -
            • Cloud Contour - Open the Cloud Contour control window. See Cloud Contour - (Ctrl-C)
            • +
            • Check the "Show contour" check box to activate the visualization
            • +
            • Enter the cloud ceiling altitude in the "Base" text field and press "Enter". The cloud layer should now be + visible around the current plane location on the track.
            • +
            • Adjust the layer altitude with the "Up" and "Down" buttons. Note that the "Base" altitude does not change. + The modified altitude is displayed in between the two buttons. To reset the cloud altitude to the original + base value, click the "Reset" button. How much the "Up" and "Down" buttons do alter the layer altitude can + be changed with the "Base Increment" spinner.
            -
          • -
          • Help.

          • -
          - - -

          Track Management

          - -

          Loading and saving tracks

          - -
            -
          • To load a track from a local file either click on the 'folder' icon in the tool bar, or select - the File->Open track file... menu option, or use the keyboard shortcut Ctrl-O. Select the proper - file and click "Open".
          • -
          • To load a track from a remote file either select the File->Open track URL... menu option, or use the - keyboard shortcut Ctrl-U. Enter the file URL and click "OK".
          • -
          • To create a new track either click on the 'blank page' icon in the tool bar, or select the File->New Track... - menu option or use the keyboard shortcut Ctrl-N. Enter a track name and click "OK". To build the track path see - Managing track points below.
          • -
          • To Save the current track either click on the 'floppy disk' icon in the tool bar, or select the - File->Save Track menu option or use the keyboard shortcut Ctrl-S. Note that tracks are automaticaly saved - every minutes - see File->Preferences...
          • -
          • To save the current track in a different file or location, select the File->Save Track As... menu option or - use the keyboard shortcut Ctrl-Shift-S.
          • -
          • To close the current track select the File->Close Track menu option or use the keyboard shortcut Ctrl-F4. - If the track as been edited since it was opened, a dialog window will offer to save it before closing it.
          • -
          - - -

          Managing track points

          - -

          A track is made of a list of points each with a geographic position and altitude. Track points are displayed - and managed in the track panel on the left of the graphic window. Any field of the displayed list - can be edited by double-clicking it and entering a new value. New points can be added, inserted or deleted via - the context menu (right-click menu).

          - -SAR Track Panel Context Menu - -

          To add a position to the current track, right click on the track panel and select "Append New Position to Track" - in the context menu. A new track point is added to the track with the same location and altitude as the previous - point if there is one. Double click on the new point latitude, longitude or altitude to edit the values.

          - -

          To remove a track point, first click on the corresponding row in the list to select it, then right click and - choose the "Delete Selected Position" option in the context menu.

          - -

          In a similar way, new positions can be inserted before or after the selected row.

          - -

          The "Add Offset to Selected Positions" option will increment or decrement the selected points altitude of the current -track offset value - at top right of the track panel.

          - - - -

          Track extension

          - -

          - New track points can also be added by visualy placing them in the graphic window. -

          -SAR Track Extension Tools - -

          - To activate one of the three extension modes, click on the corresponding icon in the tool bar - the other - two icons become 'disabled', use the tool to add new track points, then click again on the icon in the tool bar - to deactivate the extension mode. -

          -SAR Track Extension Plane - -
            -
          • Extension using the '3D segment plane'. This mode displays a vertical 'extension plane' at the end - of the track. The plane can be orientated using the green corner 'handles' and extended with the pink side - 'handles'. Once the plane is in the suitable position a new track point can be added by clicking inside - the plane. After a point has been added, it's position can be adjusted with the mouse cursor. To place yet - another point, click on the "Move to next point" icon in the tool bar. The extension plane will move at the - track end and you can repeat the process.
          • -
          • Extension in the air. This mode lets you add new track points by clicking on the terrain surface - while holding down the Alt key. Each new point will have the same altitude as the preceding one. To add a - new point, press and hold the Alt key, position the mouse cursor at the approximate location where the new - point should appear and press the left mouse button. While holding down the mouse button, move the cursor - to adjust the new point location. Release the mouse button when done. Note that you don't need to keep the - Alt key pressed while adjusting the new point location.
          • -
          • Extension on the ground. This mode works exactly like the 'in air' extension mode except new points - will be placed at ground elevation. Double click on the new points altitude cells in the track panel to edit - the values.
          • -
          - -

          While an extension mode is active, the last track point can be removed by clicking on the "Remove last track point" - icon in the tool bar.

          - - - -

          View Modes

          -SAR View Modes - -

          - The three view modes allow you to explore tracks in different ways: -

          -
            -
          • - FREE mode provides unconstrained viewing control. You use it to explore tracks and terrain from any - angle and position. + To add a second cloud layer type an altitude delta value in the "Delta" text field and press "Enter". This will + activate a second cloud layer above the first one at the base altitude. To have the second layer below the base + altitude, select the "-" radio button. To have one layer below and the other above the base altitude, select + the "+/-" radio button. To remove the second layer, enter a zero delta value. +

            +

            + To turn off the cloud contour visualization, uncheck the "Show contour" check box.

            -
          • -
          • +

            Advanced options

            - FLY-IT mode simulates the pilot's view. Selecting this mode positions the view - at the current track position indicated in the Position panel. - The view's heading is to that from the first to last positions of the segment. - Moving the current position, either manually via the position slider or - timed via the player controls, moves the view along the segment either forward or backwards. + Clicking on the "Advanced..." label will unveil additional controls that let you determine around what track + segments the clouds are displayed and their appearance.

            + + +

            Annotations

            - The speed of timed movement can be controlled via the Speed spinner located below the player controls. + Text annotations can be added at any place on the terrain surface. To add a new annotation follow these steps:

            -
          • -
          • +
              +
            • Select the Annotation->New Annotation... menu option or use the keyboard shortcut Ctrl-A.
            • +
            • Enter some text in the dialog window that comes up and click the "OK" button. A new annotation appears on the + terrain in the middle of the graphic window. Its border is yellow which means it is currently 'selected' + and can be moved around with the mouse cursor.
            • +
            • Click on the annotation and move it to the right place while holding down the left mouse button.
            • +
            • Click once on the terrain to 'deselect' the annotation - its border becomes black. When an annotation + is not selected it cannot be moved by mistake while moving around the view with the mouse.
            • +

            - EXAMINE mode is similar to Fly-It mode but the view follows the track from the side, at any angle and - distance the user desires. This is the view a chaser aircraft would have. This mode attempts to keep the - view focussed on a point on the ground just below the current position while the user manipulates the - view to useful perspectives. + To edit an annotation, double click on it, edit the text in the dialog window that comes up and click + the "Save" button.

            -
          • -
          - - -

          Terrain Profile

          - -

          - To bring up the terrain profile control window, either: -

          -
            -
          • Click on the "Terrain Profile" icon in the tool bar.
          • -
          • Use the keyboard shortcut Ctrl-T
          • -
          • Select the View->Terrain Profile... menu option
          • -
          -SAR Terrain Profile - -

          - The top-left 'pulldown' menu lets you set the terrain profile graph size to "Small", "Medium" or "Large". -

          -

          - The top-right 'pulldown' menu in the terrain profile panel determines the terrain cross section position. The yellow line - in the graphics window shows the cross section's current position. At all times the terrain profile - displays the elevations of the terrain intersected by this line. The "Profile at/under..." selection can have the following - values: -

          -
            -
          • - Profile at Screen Center places the terrain cross section constantly at the center of the view. You manipulate the - globe to change the terrain measured. + To remove an annotation either double click on it and then click the "Delete" button in the dialog window, + or click on the annotation once to select it (its border becomes yellow) and then select the + Annotation->Remove Annotation menu option (or use the keyboard shortcut Alt-A).

            -
          • -
          • - Profile Under Cursor places the center of the cross section at the cursor (mouse) position. Moving the - cursor moves the cross section over the globe's surface. + To move an annotation first click once on it to select it - its border becomes yellow, and then click again + and move it around while keeping the left mouse button down. To deselect the annotation click once on the terrain + or select another annotation.

            -
          • -
          • + + + +

            Viewing Controls

            +

            Mouse

            +
              +
            • + Rotate Globe: Move mouse while pressing left mouse button. +
            • +
            • + Tilt Globe: Move mouse while pressing right mouse button. +
            • +
            • + Zoom: Rotate the mouse wheel. +
            • +
            • + Fast Zoom: Hold down the mouse middle button and drag up to zoom-in or down to zoom-out. +
            • +
            + +

            Keyboard

            +
              +
            • + Rotate Globe: Arrow keys. +
            • +
            • + Tilt Globe: Shift + Up or Down arrow. +
            • +
            • + Zoom: Control + Up or Down arrow. +
            • +
            • + Reset the view to 'vertical and north': R. +
            • +
            • + Reset the view heading to 'north': N. +
            • +
            + + + +

            Bulk download

            +

            + To work offline (with no network connection) or to speedup imagery and terrain loading, you may want to pre-load + imagery and elevation data for a selected area. +

            +

            CAUTION: trying to download imagery and elevations for a large area will likely involve large amounts of + data which will result in both extended time to fetch the files from the servers and large disk space to store them. + The Bulk Download panel provides an estimated data size for the selected sector and layers. +

            +

            + To download imagery or elevation data follow these steps: +

            +
              +
            • Select the "Free View" mode from the tool bar and navigate to the area you are interested in. Set a plain + vertical/north view (keyboard key R) and adjust the zoom so as to have a comfortable overview.
            • +
            • Bring up the Bulk Download control panel by either selecting the File->Bulk Download menu option or using the + keyboad shortcut Ctrl-B.
            • +
            • Click on the "Select Sector" button then press down the left mouse button at a corner of the terrain area + you want to select, and while keeping the left mouse mutton down, drag the cursor to the opposite corner + of the area. Once you have released the mouse button you can adjust the sector boundaries by dragging the + sides or the whole rectangle.
            • +
            • Check the layers you are interested in. Each will provide an estimate of the involved data size. Be sure to + consider the implications. While some layers are selected you can still adjust the selected sector boundaries + and watch the estimate change.
            • +
            • Once you are satisfied with the selected sector and layers, click on the "Start Download" button. One progress + bar will appear for each layer involved. Depending on the selected sector size, nothing may seem to happen for a + short time while the process starts evaluating a more precise estimate of the data size involved. Once this is + done a more accurate size estimate will be displayed and the download will start showing some progress.
            • +

            - Profile Under Eye is meant to be used in "Fly-It" view mode described in the View Modes section - above. It positions the cross section on the surface directly below the pilot, perpendicular to the - current heading and centered on the current track position. The profile graph displays the cross section - directly to the pilot's left and right. This terrain profile mode is not intended to be used with view modes - other than Fly-It. + Each download process will retreive the requested data from the appropriate servers at it's own pace. Once a + process has finished it's progress bar will indicate 100% and the "Cancel" button will turn into a green "Remove" + button. Clicking the "Remove" button will remove the finished process from the list but will not affect the + downloaded data.

            -
          • -
          • - Profile Under Aircraft positions the cross section perpendicular to and centered on the current track at the - current track position. This mode enables you to watch the cross section move along the track while in - Examine or Free view modes. In Examine mode the view will follow the current track position, therefore the - cross section will remain centered in the graphics window while the view moves along the current track. In - Free mode the view will be stationary but the cross section will move along the track, requiring the user - to continually adjust the view to keep the cross section in sight. + At any time a layer download process can be canceled by clicking on the "Cancel" button. Be aware that once + canceled a process cannot be restarted unless a similar sector is selected, the corresponding layer is checked and + a new download is initiated - which can be done while other process are currently downloading data.

            - When the profile is set to be under the aircraft, a second profile is also displayed in the right portion - of the graphic window. This one is perpendicular to the other and follows the track direction. + Caution: depending on the network and server condition at the time of the download, some data may not be + retrieved properly. This may result in a process ending with a less the 100% progress. In that case the "Cancel" + button will turn into an orange "Remove" button. If you think some data are missing, restart download processes + for a similar sector and the relevant layers. If most of the data has already been downloaded retrieving the + missing portions should be fast.

            -
          • -
          • - No Profile Turn off the cross section and terrain profile. + While download is proceeding the Bulk Download control window can be minimized. Attempting to close the window + while downloads are active will bring up a dialog window inquiering whether you want to cancel all downloads.

            -
          • -
          - -

          Terrain Profile Controls

          - -

          - The following controls let you adjust the terrain profile size and behavior: -

          -
            -
          • Proportional: determines whether the width and height of the profile graph are to the - same scale.
          • -
          • MSL Base determines whether the graph shows elevations relative to mean sea level or the current minimum elevation along the - cross section.
          • -
          • Show A/C Position determines whether the aircraft position should be indicated in the profile. The - aircraft point can be shown only when the terrain profile position is "Under Aircraft".
          • -
          • Profile Width lets you increase the perpendicular profile extent on both sides of the track.
          • -
          • Profile Length when the profile is set to be under the aircraft, lets you increase the 'along the track' - profile extent both ahead and behind the aircraft.
          • -
          • Same Size when checked both profiles will have the same extent.
          • -
          • Whole Track Length when checked, the 'along the track' profile will cover the whole track length.
          • -
          - -

          - Anytime, one graph or the other can be either 'minimized' - and becomes an icon, or 'maximized' - it will then - fill the whole screen, by clicking on the + and - buttons in the upper right corner of each graph display. -

          - - -

          Cloud contour

          -

          - To activate and control the cloud contour visualization either: -

          -
            -
          • Click on the Cloud icon in the tool bar
          • -
          • Use the keyboad shortcut Ctrl-C
          • -
          • Select the View->Cloud Contour... menu option
          • -
          -SAR Cloud Contour - -

          - This brings up a separate window that lets you turn the visualization on and off, and control the cloud - ceiling. To set up a cloud layer at a given altitude, follow these steps: -

          -
            -
          • Check the "Show contour" check box to activate the visualization
          • -
          • Enter the cloud ceiling altitude in the "Base" text field and press "Enter". The cloud layer should now be - visible around the current plane location on the track.
          • -
          • Adjust the layer altitude with the "Up" and "Down" buttons. Note that the "Base" altitude does not change. - The modified altitude is displayed in between the two buttons. To reset the cloud altitude to the original - base value, click the "Reset" button. How much the "Up" and "Down" buttons do alter the layer altitude can - be changed with the "Base Increment" spinner.
          • -
          -

          - To add a second cloud layer type an altitude delta value in the "Delta" text field and press "Enter". This will - activate a second cloud layer above the first one at the base altitude. To have the second layer below the base - altitude, select the "-" radio button. To have one layer below and the other above the base altitude, select - the "+/-" radio button. To remove the second layer, enter a zero delta value. -

          -

          - To turn off the cloud contour visualization, uncheck the "Show contour" check box. -

          -

          Advanced options

          -

          - Clicking on the "Advanced..." label will unveil additional controls that let you determine around what track - segments the clouds are displayed and their appearance. -

          - - - -

          Annotations

          -

          - Text annotations can be added at any place on the terrain surface. To add a new annotation follow these steps: -

          -
            -
          • Select the Annotation->New Annotation... menu option or use the keyboard shortcut Ctrl-A.
          • -
          • Enter some text in the dialog window that comes up and click the "OK" button. A new annotation appears on the - terrain in the middle of the graphic window. Its border is yellow which means it is currently 'selected' - and can be moved around with the mouse cursor.
          • -
          • Click on the annotation and move it to the right place while holding down the left mouse button.
          • -
          • Click once on the terrain to 'deselect' the annotation - its border becomes black. When an annotation - is not selected it cannot be moved by mistake while moving around the view with the mouse.
          • -
          -

          - To edit an annotation, double click on it, edit the text in the dialog window that comes up and click - the "Save" button. -

          -

          - To remove an annotation either double click on it and then click the "Delete" button in the dialog window, - or click on the annotation once to select it (its border becomes yellow) and then select the - Annotation->Remove Annotation menu option (or use the keyboard shortcut Alt-A). -

          -

          - To move an annotation first click once on it to select it - its border becomes yellow, and then click again - and move it around while keeping the left mouse button down. To deselect the annotation click once on the terrain - or select another annotation. -

          - - - -

          Viewing Controls

          -

          Mouse

          -
            -
          • - Rotate Globe: Move mouse while pressing left mouse button. -
          • -
          • - Tilt Globe: Move mouse while pressing right mouse button. -
          • -
          • - Zoom: Rotate the mouse wheel. -
          • -
          • - Fast Zoom: Hold down the mouse middle button and drag up to zoom-in or down to zoom-out. -
          • -
          - -

          Keyboard

          -
            -
          • - Rotate Globe: Arrow keys. -
          • -
          • - Tilt Globe: Shift + Up or Down arrow. -
          • -
          • - Zoom: Control + Up or Down arrow. -
          • -
          • - Reset the view to 'vertical and north': R. -
          • -
          • - Reset the view heading to 'north': N. -
          • -
          - - - -

          Bulk download

          -

          - To work offline (with no network connection) or to speedup imagery and terrain loading, you may want to pre-load - imagery and elevation data for a selected area. -

          -

          CAUTION: trying to download imagery and elevations for a large area will likely involve large amounts of - data which will result in both extended time to fetch the files from the servers and large disk space to store them. - The Bulk Download panel provides an estimated data size for the selected sector and layers. -

          -

          - To download imagery or elevation data follow these steps: -

          -
            -
          • Select the "Free View" mode from the tool bar and navigate to the area you are interested in. Set a plain - vertical/north view (keyboard key R) and adjust the zoom so as to have a comfortable overview.
          • -
          • Bring up the Bulk Download control panel by either selecting the File->Bulk Download menu option or using the - keyboad shortcut Ctrl-B.
          • -
          • Click on the "Select Sector" button then press down the left mouse button at a corner of the terrain area - you want to select, and while keeping the left mouse mutton down, drag the cursor to the opposite corner - of the area. Once you have released the mouse button you can adjust the sector boundaries by dragging the - sides or the whole rectangle.
          • -
          • Check the layers you are interested in. Each will provide an estimate of the involved data size. Be sure to - consider the implications. While some layers are selected you can still adjust the selected sector boundaries - and watch the estimate change.
          • -
          • Once you are satisfied with the selected sector and layers, click on the "Start Download" button. One progress - bar will appear for each layer involved. Depending on the selected sector size, nothing may seem to happen for a - short time while the process starts evaluating a more precise estimate of the data size involved. Once this is - done a more accurate size estimate will be displayed and the download will start showing some progress.
          • -
          -

          - Each download process will retreive the requested data from the appropriate servers at it's own pace. Once a - process has finished it's progress bar will indicate 100% and the "Cancel" button will turn into a green "Remove" - button. Clicking the "Remove" button will remove the finished process from the list but will not affect the - downloaded data. -

          -

          - At any time a layer download process can be canceled by clicking on the "Cancel" button. Be aware that once - canceled a process cannot be restarted unless a similar sector is selected, the corresponding layer is checked and - a new download is initiated - which can be done while other process are currently downloading data. -

          -

          - Caution: depending on the network and server condition at the time of the download, some data may not be - retrieved properly. This may result in a process ending with a less the 100% progress. In that case the "Cancel" - button will turn into an orange "Remove" button. If you think some data are missing, restart download processes - for a similar sector and the relevant layers. If most of the data has already been downloaded retrieving the - missing portions should be fast. -

          -

          - While download is proceeding the Bulk Download control window can be minimized. Attempting to close the window - while downloads are active will bring up a dialog window inquiering whether you want to cancel all downloads. -

          - -

          oOo

          - - + +

          oOo

          + + \ No newline at end of file diff --git a/src/gov/nasa/worldwindx/applications/sar/SARKey.java b/src/gov/nasa/worldwindx/applications/sar/SARKey.java index 43c2e3b163..1d281a8051 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARKey.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARKey.java @@ -9,8 +9,8 @@ * @author dcollins * @version $Id: SARKey.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface SARKey -{ +public interface SARKey { + final String ANGLE_FORMAT = "AngleFormat"; final String AUTO_SAVE_TRACKS = "AutoSaveTracks"; final String AUTO_SAVE_TRACKS_INTERVAL = "AutoSaveTracksInterval"; diff --git a/src/gov/nasa/worldwindx/applications/sar/SARPosition.java b/src/gov/nasa/worldwindx/applications/sar/SARPosition.java index 7f0dac370a..42d50b6cf4 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARPosition.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARPosition.java @@ -11,16 +11,15 @@ * @author tag * @version $Id: SARPosition.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARPosition extends Position -{ - public static class Info - { +public class SARPosition extends Position { + + public static class Info { + private final String author; private final long editTime; private final String comment; - public Info(String author, long editTime, String comment) - { + public Info(String author, long editTime, String comment) { this.author = author; this.editTime = editTime; this.comment = comment; @@ -29,18 +28,15 @@ public Info(String author, long editTime, String comment) private Info info; - public SARPosition() - { + public SARPosition() { super(Angle.ZERO, Angle.ZERO, 0d); } - public SARPosition(Angle latitude, Angle longitude, double elevation) - { + public SARPosition(Angle latitude, Angle longitude, double elevation) { super(latitude, longitude, elevation); } - public SARPosition(Position pos) - { + public SARPosition(Position pos) { super(pos.getLatitude(), pos.getLongitude(), pos.getElevation()); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/SARSegmentPlane.java b/src/gov/nasa/worldwindx/applications/sar/SARSegmentPlane.java index 4fed3ddf8f..a9da1e3812 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARSegmentPlane.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARSegmentPlane.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: SARSegmentPlane.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARSegmentPlane extends WWObjectImpl -{ +public class SARSegmentPlane extends WWObjectImpl { + private String angleFormat; private String elevationUnit; private WorldWindow wwd; // Can be null. @@ -33,8 +33,7 @@ public class SARSegmentPlane extends WWObjectImpl private boolean modifiedSinceLastArm = false; private boolean ignorePlaneChangeEvents = false; - public SARSegmentPlane() - { + public SARSegmentPlane() { this.segmentPlane = new SegmentPlane(); this.segmentPlaneEditor = new SegmentPlaneEditor(); this.segmentPlaneController = new SegmentPlaneController(null); @@ -45,87 +44,71 @@ public SARSegmentPlane() this.initSegmentPlane(); } - public boolean isVisible() - { + public boolean isVisible() { return this.segmentPlane.isVisible(); } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.segmentPlane.setVisible(visible); } - public boolean isArmed() - { + public boolean isArmed() { return this.segmentPlaneEditor.isArmed(); } - public void setArmed(boolean armed) - { - if (armed && !(this.segmentPlaneEditor.isArmed())) - { + public void setArmed(boolean armed) { + if (armed && !(this.segmentPlaneEditor.isArmed())) { this.modifiedSinceLastArm = false; } this.segmentPlaneEditor.setArmed(armed); } - public boolean isSnapToGrid() - { + public boolean isSnapToGrid() { return this.segmentPlaneEditor.isSnapToGrid(); } - public void setSnapToGrid(boolean snapToGrid) - { + public void setSnapToGrid(boolean snapToGrid) { this.segmentPlaneEditor.setSnapToGrid(snapToGrid); } - public double[] getGridCellDimensions() - { + public double[] getGridCellDimensions() { return this.segmentPlane.getGridCellDimensions(); } - public void setGridCellDimensions(double width, double height) - { + public void setGridCellDimensions(double width, double height) { this.segmentPlane.setGridCellDimensions(width, height); } - public String getAngleFormat() - { + public String getAngleFormat() { return this.angleFormat; } - public void setAngleFormat(String angleFormat) - { + public void setAngleFormat(String angleFormat) { this.angleFormat = angleFormat; } - public String getElevationUnit() - { + public String getElevationUnit() { return this.elevationUnit; } - public void setElevationUnit(String elevationUnit) - { + public void setElevationUnit(String elevationUnit) { this.elevationUnit = elevationUnit; } - public WorldWindow getWorldWindow() - { + public WorldWindow getWorldWindow() { return this.wwd; } - public void setWorldWindow(WorldWindow wwd) - { - if (this.wwd == wwd) + public void setWorldWindow(WorldWindow wwd) { + if (this.wwd == wwd) { return; + } - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.removePropertyChangeListener(this); - if (this.wwd.getModel().getLayers().contains(this.segmentPlaneEditor)) - { + if (this.wwd.getModel().getLayers().contains(this.segmentPlaneEditor)) { this.wwd.getModel().getLayers().remove(this.segmentPlaneEditor); } } @@ -133,137 +116,103 @@ public void setWorldWindow(WorldWindow wwd) this.wwd = wwd; this.segmentPlaneController.setWorldWindow(wwd); - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.addPropertyChangeListener(this); - if (!this.wwd.getModel().getLayers().contains(this.segmentPlaneEditor)) - { + if (!this.wwd.getModel().getLayers().contains(this.segmentPlaneEditor)) { this.wwd.getModel().getLayers().add(this.segmentPlaneEditor); } } } @SuppressWarnings({"StringEquality"}) - public void propertyChange(PropertyChangeEvent e) - { + public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); - if (e.getSource() == this.segmentPlane) - { + if (e.getSource() == this.segmentPlane) { this.modifiedSinceLastArm = true; } - if (propertyName == SegmentPlane.SEGMENT_BEGIN || propertyName == SegmentPlane.SEGMENT_END) - { - if (!this.ignorePlaneChangeEvents) - { + if (propertyName == SegmentPlane.SEGMENT_BEGIN || propertyName == SegmentPlane.SEGMENT_END) { + if (!this.ignorePlaneChangeEvents) { super.propertyChange(e); } - } - else if (propertyName == SARKey.ANGLE_FORMAT) - { - if (e.getNewValue() != null) - { + } else if (propertyName == SARKey.ANGLE_FORMAT) { + if (e.getNewValue() != null) { this.setAngleFormat(e.getNewValue().toString()); super.propertyChange(e); } - } - else if (propertyName == SARKey.ELEVATION_UNIT) - { - if (e.getNewValue() != null) - { + } else if (propertyName == SARKey.ELEVATION_UNIT) { + if (e.getNewValue() != null) { this.setElevationUnit(e.getNewValue().toString()); super.propertyChange(e); } } } - public Position[] getSegmentPositions() - { + public Position[] getSegmentPositions() { return this.segmentPlane.getSegmentPositions(); } - public void setSegmentPositions(Position position1, Position position2) - { + public void setSegmentPositions(Position position1, Position position2) { this.ignorePlaneChangeEvents = true; - try - { + try { this.segmentPlane.setSegmentPositions(position1, position2); - } - finally - { + } finally { this.ignorePlaneChangeEvents = false; } } - public double[] getPlaneAltitudes() - { + public double[] getPlaneAltitudes() { return this.segmentPlane.getPlaneAltitudes(); } - public void setPlaneAltitudes(double lowerAltitude, double upperAltitude) - { + public void setPlaneAltitudes(double lowerAltitude, double upperAltitude) { this.ignorePlaneChangeEvents = true; - try - { + try { this.segmentPlane.setPlaneAltitudes(lowerAltitude, upperAltitude); - } - finally - { + } finally { this.ignorePlaneChangeEvents = false; } } - public LatLon[] getPlaneLocations() - { + public LatLon[] getPlaneLocations() { return this.segmentPlane.getPlaneLocations(); } - public void setPlaneLocations(LatLon location1, LatLon location2) - { + public void setPlaneLocations(LatLon location1, LatLon location2) { this.ignorePlaneChangeEvents = true; - try - { + try { this.segmentPlane.setPlaneLocations(location1, location2); - } - finally - { + } finally { this.ignorePlaneChangeEvents = false; } } - public SegmentPlaneAttributes getAttributes() - { + public SegmentPlaneAttributes getAttributes() { return this.segmentPlane.getAttributes(); } - public void setAttributes(SegmentPlaneAttributes attributes) - { + public void setAttributes(SegmentPlaneAttributes attributes) { this.segmentPlane.setAttributes(attributes); } - public void setObjectVisible(String key, boolean geometryVisible, boolean labelVisible) - { - SegmentPlaneAttributes.GeometryAttributes geometryAttributes = - this.segmentPlane.getAttributes().getGeometryAttributes(key); - if (geometryAttributes != null) - { + public void setObjectVisible(String key, boolean geometryVisible, boolean labelVisible) { + SegmentPlaneAttributes.GeometryAttributes geometryAttributes + = this.segmentPlane.getAttributes().getGeometryAttributes(key); + if (geometryAttributes != null) { geometryAttributes.setVisible(geometryVisible); } - SegmentPlaneAttributes.LabelAttributes labelAttributes = - this.segmentPlane.getAttributes().getLabelAttributes(key); - if (labelAttributes != null) - { + SegmentPlaneAttributes.LabelAttributes labelAttributes + = this.segmentPlane.getAttributes().getLabelAttributes(key); + if (labelAttributes != null) { labelAttributes.setVisible(labelVisible); } } - public double[] computeAltitudesToFitPositions(Iterable positions) - { - if (this.wwd == null) - { + public double[] computeAltitudesToFitPositions(Iterable positions) { + if (this.wwd == null) { String message = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -272,30 +221,25 @@ public double[] computeAltitudesToFitPositions(Iterable posi return computeAltitudesToFitPositions(this.wwd, this.segmentPlane, positions, this.modifiedSinceLastArm); } - public LatLon[] computeLocationsToFitPositions(Position position1, Position position2) - { - if (this.wwd == null) - { + public LatLon[] computeLocationsToFitPositions(Position position1, Position position2) { + if (this.wwd == null) { String message = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(message); throw new IllegalStateException(message); } return computeLocationsToFitPositions(this.wwd, this.segmentPlane, position1, position2, - this.modifiedSinceLastArm); + this.modifiedSinceLastArm); } - public Position getIntersectionPosition(Line line) - { - if (line == null) - { + public Position getIntersectionPosition(Line line) { + if (line == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.wwd == null) - { + if (this.wwd == null) { String message = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -304,31 +248,26 @@ public Position getIntersectionPosition(Line line) Globe globe = this.wwd.getModel().getGlobe(); Vec4 point = this.segmentPlaneEditor.getSegmentPlaneRenderer().intersect(globe, line, this.segmentPlane); - if (point == null) - { + if (point == null) { return null; } return globe.computePositionFromPoint(point); } - public double getObjectSize(String key, Vec4 point) - { - if (key == null) - { + public double getObjectSize(String key, Vec4 point) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (point == null) - { + if (point == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (this.wwd == null) - { + if (this.wwd == null) { String message = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(message); throw new IllegalStateException(message); @@ -338,15 +277,13 @@ public double getObjectSize(String key, Vec4 point) Globe globe = this.wwd.getModel().getGlobe(); return this.segmentPlaneEditor.getSegmentPlaneRenderer().computeObjectSize(view, globe, this.segmentPlane, - key, point); + key, point); } //**************************************************************// //******************** Segment Plane initialization **********// //**************************************************************// - - protected void initSegmentPlane() - { + protected void initSegmentPlane() { double gridSize = SAR2.feetToMeters(1000); this.segmentPlane.setGridCellDimensions(gridSize, gridSize); this.segmentPlane.setPlaneOutlineMask(SegmentPlane.TOP); @@ -369,15 +306,14 @@ protected void initSegmentPlane() //**************************************************************// //******************** Plane Attributes **********************// //**************************************************************// - SegmentPlaneAttributes.GeometryAttributes background = new SegmentPlaneAttributes.GeometryAttributes( - new Material(backgroundColor), 0.6); + new Material(backgroundColor), 0.6); SegmentPlaneAttributes.GeometryAttributes outline = new SegmentPlaneAttributes.GeometryAttributes( - new Material(foregroundColor), 1.0); + new Material(foregroundColor), 1.0); SegmentPlaneAttributes.GeometryAttributes grid = new SegmentPlaneAttributes.GeometryAttributes( - new Material(foregroundColor), 1.0); + new Material(foregroundColor), 1.0); SegmentPlaneAttributes.GeometryAttributes border = new SegmentPlaneAttributes.GeometryAttributes( - new Material(foregroundColor), 1.0); + new Material(foregroundColor), 1.0); grid.setSize(1); grid.setPickSize(10); outline.setSize(3); @@ -391,11 +327,10 @@ protected void initSegmentPlane() //**************************************************************// //******************** Segment Altimeter Attributes **********// //**************************************************************// - SegmentPlaneAttributes.GeometryAttributes altimeterGeometry = new SegmentPlaneAttributes.GeometryAttributes( - new Material(segmentPointColor), 1.0); + new Material(segmentPointColor), 1.0); AxisLabelAttributes altimeterLabel = new AxisLabelAttributes( - vAxisLabelColor, Font.decode("Arial-12"), AVKey.LEFT, AVKey.CENTER, this); + vAxisLabelColor, Font.decode("Arial-12"), AVKey.LEFT, AVKey.CENTER, this); altimeterGeometry.setSize(1); altimeterLabel.setVisible(false); altimeterLabel.setMaxActiveDistance(maxAxisLabelActiveDistance); @@ -406,15 +341,14 @@ protected void initSegmentPlane() //**************************************************************// //******************** Segment Control Point Attributes ******// //**************************************************************// - SegmentPlaneAttributes.GeometryAttributes segmentBeginPointGeom = new SegmentPlaneAttributes.GeometryAttributes( - new Material(segmentPointColor), 1.0); + new Material(segmentPointColor), 1.0); SegmentPlaneAttributes.GeometryAttributes segmentEndPointGeom = new SegmentPlaneAttributes.GeometryAttributes( - new Material(segmentPointColor), 1.0); + new Material(segmentPointColor), 1.0); ControlPointLabelAttributes segmentBeginPointLabel = new ControlPointLabelAttributes( - segmentPointColor, Font.decode("Arial-12"), AVKey.RIGHT, AVKey.CENTER, this); + segmentPointColor, Font.decode("Arial-12"), AVKey.RIGHT, AVKey.CENTER, this); ControlPointLabelAttributes segmentEndPointLabel = new ControlPointLabelAttributes( - segmentPointColor, Font.decode("Arial-12"), AVKey.RIGHT, AVKey.CENTER, this); + segmentPointColor, Font.decode("Arial-12"), AVKey.RIGHT, AVKey.CENTER, this); segmentBeginPointGeom.setEnablePicking(false); segmentBeginPointGeom.setSize(8); segmentBeginPointGeom.setPickSize(10); @@ -438,11 +372,10 @@ protected void initSegmentPlane() //**************************************************************// //******************** Axis Label Attributes *****************// //**************************************************************// - AxisLabelAttributes horizontalAxisLabels = new AxisLabelAttributes( - hAxisLabelColor, Font.decode("Arial-10"), AVKey.CENTER, AVKey.BOTTOM, this); + hAxisLabelColor, Font.decode("Arial-10"), AVKey.CENTER, AVKey.BOTTOM, this); AltitudeLabelAttributes verticalAxisLabels = new AltitudeLabelAttributes( - vAxisLabelColor, Font.decode("Arial-10"), AVKey.RIGHT, AVKey.BOTTOM, this); + vAxisLabelColor, Font.decode("Arial-10"), AVKey.RIGHT, AVKey.BOTTOM, this); horizontalAxisLabels.setMaxActiveDistance(maxAxisLabelActiveDistance); verticalAxisLabels.setMaxActiveDistance(maxAxisLabelActiveDistance); @@ -452,15 +385,14 @@ protected void initSegmentPlane() //**************************************************************// //******************** Plane Move Control Point Attributes ***// //**************************************************************// - - SegmentPlaneAttributes.GeometryAttributes moveControlPointLRGeom = - new SegmentPlaneAttributes.GeometryAttributes(new Material(moveControlPointColor), 1.0); - SegmentPlaneAttributes.GeometryAttributes moveControlPointURGeom = - new SegmentPlaneAttributes.GeometryAttributes(new Material(moveControlPointColor), 1.0); + SegmentPlaneAttributes.GeometryAttributes moveControlPointLRGeom + = new SegmentPlaneAttributes.GeometryAttributes(new Material(moveControlPointColor), 1.0); + SegmentPlaneAttributes.GeometryAttributes moveControlPointURGeom + = new SegmentPlaneAttributes.GeometryAttributes(new Material(moveControlPointColor), 1.0); ControlPointLabelAttributes moveControlPointLRLabel = new ControlPointLabelAttributes( - moveControlPointColor, Font.decode("Arial-12"), AVKey.LEFT, AVKey.CENTER, this); + moveControlPointColor, Font.decode("Arial-12"), AVKey.LEFT, AVKey.CENTER, this); ControlPointLabelAttributes moveControlPointURLabel = new ControlPointLabelAttributes( - moveControlPointColor, Font.decode("Arial-12"), AVKey.LEFT, AVKey.CENTER, this); + moveControlPointColor, Font.decode("Arial-12"), AVKey.LEFT, AVKey.CENTER, this); moveControlPointLRGeom.setSize(7); moveControlPointLRGeom.setPickSize(10); moveControlPointLRGeom.setOffset(new Vec4(0, 0, 7)); @@ -481,12 +413,11 @@ protected void initSegmentPlane() //**************************************************************// //******************** Plane Resize Control Point Attributes *// //**************************************************************// - SegmentPlaneAttributes.GeometryAttributes resizeControlPointGeom - = new SegmentPlaneAttributes.GeometryAttributes( - new Material(resizeControlPointColor), 1.0); + = new SegmentPlaneAttributes.GeometryAttributes( + new Material(resizeControlPointColor), 1.0); ControlPointLabelAttributes resizeControlPointLabel = new ControlPointLabelAttributes( - resizeControlPointColor, Font.decode("Arial-10"), AVKey.LEFT, AVKey.CENTER, this); + resizeControlPointColor, Font.decode("Arial-10"), AVKey.LEFT, AVKey.CENTER, this); resizeControlPointGeom.setSize(7); resizeControlPointGeom.setPickSize(10); resizeControlPointLabel.setVisible(false); @@ -501,62 +432,52 @@ protected void initSegmentPlane() //**************************************************************// //******************** Control Point Label Attributes ********// //**************************************************************// + public static class SARLabelAttributes extends SegmentPlaneAttributes.LabelAttributes { - public static class SARLabelAttributes extends SegmentPlaneAttributes.LabelAttributes - { private SARSegmentPlane context; public SARLabelAttributes(Color color, Font font, String horizontalAlignment, String verticalAlignment, - SARSegmentPlane context) - { + SARSegmentPlane context) { super(color, font, horizontalAlignment, verticalAlignment); this.context = context; } - public SARLabelAttributes() - { + public SARLabelAttributes() { } - public SARSegmentPlane getContext() - { + public SARSegmentPlane getContext() { return this.context; } - public void setContext(SARSegmentPlane context) - { + public void setContext(SARSegmentPlane context) { this.context = context; } - public SegmentPlaneAttributes.LabelAttributes copy() - { + public SegmentPlaneAttributes.LabelAttributes copy() { return this.copyTo(new SARLabelAttributes()); } - protected SegmentPlaneAttributes.LabelAttributes copyTo(SegmentPlaneAttributes.LabelAttributes copy) - { + protected SegmentPlaneAttributes.LabelAttributes copyTo(SegmentPlaneAttributes.LabelAttributes copy) { super.copyTo(copy); - if (copy instanceof SARLabelAttributes) - { + if (copy instanceof SARLabelAttributes) { ((SARLabelAttributes) copy).setContext(this.getContext()); } return copy; } - protected String formatAngle(Angle angle) - { + protected String formatAngle(Angle angle) { return SARSegmentPlane.formatAngle(this.context.getAngleFormat(), angle); } - protected String formatElevation(double value) - { + protected String formatElevation(double value) { return SARSegmentPlane.formatElevation(this.context.getElevationUnit(), value); } } - public static class ControlPointLabelAttributes extends SARLabelAttributes - { + public static class ControlPointLabelAttributes extends SARLabelAttributes { + private String prefix; private boolean showLocation = true; private boolean showAltitude = false; @@ -564,76 +485,61 @@ public static class ControlPointLabelAttributes extends SARLabelAttributes private boolean showSegmentHeading = false; public ControlPointLabelAttributes(Color color, Font font, String horizontalAlignment, - String verticalAlignment, SARSegmentPlane context) - { + String verticalAlignment, SARSegmentPlane context) { super(color, font, horizontalAlignment, verticalAlignment, context); } - public ControlPointLabelAttributes() - { + public ControlPointLabelAttributes() { } - public String getPrefix() - { + public String getPrefix() { return this.prefix; } - public void setPrefix(String prefix) - { + public void setPrefix(String prefix) { this.prefix = prefix; } - public boolean isShowLocation() - { + public boolean isShowLocation() { return this.showLocation; } - public void setShowLocation(boolean showLocation) - { + public void setShowLocation(boolean showLocation) { this.showLocation = showLocation; } - public boolean isShowAltitude() - { + public boolean isShowAltitude() { return this.showAltitude; } - public void setShowAltitude(boolean show) - { + public void setShowAltitude(boolean show) { this.showAltitude = show; } - public boolean isShowSegmentHeading() - { + public boolean isShowSegmentHeading() { return this.showSegmentHeading; } - public void setShowSegmentHeading(boolean show) - { + public void setShowSegmentHeading(boolean show) { this.showSegmentHeading = show; } - public boolean isShowHeightAboveSurface() - { + public boolean isShowHeightAboveSurface() { return this.showHeightAboveSurface; } - public void setShowHeightAboveSurface(boolean show) - { + public void setShowHeightAboveSurface(boolean show) { this.showHeightAboveSurface = show; } - public SegmentPlaneAttributes.LabelAttributes copy() - { + public SegmentPlaneAttributes.LabelAttributes copy() { return this.copyTo(new ControlPointLabelAttributes()); } - protected SegmentPlaneAttributes.LabelAttributes copyTo(SegmentPlaneAttributes.LabelAttributes copy) - { + protected SegmentPlaneAttributes.LabelAttributes copyTo(SegmentPlaneAttributes.LabelAttributes copy) { super.copyTo(copy); - if (copy instanceof ControlPointLabelAttributes) - { + if (copy instanceof ControlPointLabelAttributes) { ((ControlPointLabelAttributes) copy).setPrefix(this.getPrefix()); ((ControlPointLabelAttributes) copy).setShowLocation(this.isShowLocation()); ((ControlPointLabelAttributes) copy).setShowAltitude(this.isShowAltitude()); @@ -644,21 +550,20 @@ protected SegmentPlaneAttributes.LabelAttributes copyTo(SegmentPlaneAttributes.L return copy; } - public String getText(SegmentPlane segmentPlane, Position position, AVList values) - { + public String getText(SegmentPlane segmentPlane, Position position, AVList values) { StringBuilder sb = new StringBuilder(); - if (this.getPrefix() != null) - { - if (sb.length() > 0) + if (this.getPrefix() != null) { + if (sb.length() > 0) { sb.append("\n"); + } sb.append(this.getPrefix()); } - if (this.isShowLocation()) - { - if (sb.length() > 0) + if (this.isShowLocation()) { + if (sb.length() > 0) { sb.append("\n"); + } sb.append("("); sb.append(this.formatAngle(position.getLatitude())); sb.append(", "); @@ -666,32 +571,30 @@ public String getText(SegmentPlane segmentPlane, Position position, AVList value sb.append(")"); } - if (this.isShowSegmentHeading()) - { + if (this.isShowSegmentHeading()) { LatLon[] locations = segmentPlane.getPlaneLocations(); Angle heading = LatLon.rhumbAzimuth(locations[0], locations[1]); - if (sb.length() > 0) + if (sb.length() > 0) { sb.append("\n"); + } sb.append("Heading: ").append(heading.toDecimalDegreesString(0)); } - if (this.isShowAltitude()) - { - if (sb.length() > 0) + if (this.isShowAltitude()) { + if (sb.length() > 0) { sb.append("\n"); + } sb.append("Alt: ").append(this.formatElevation(position.getElevation())); } - if (this.isShowHeightAboveSurface()) - { - if (values != null) - { + if (this.isShowHeightAboveSurface()) { + if (values != null) { Double height = AVListImpl.getDoubleValue(values, AVKey.HEIGHT); - if (height != null) - { - if (sb.length() > 0) + if (height != null) { + if (sb.length() > 0) { sb.append("\n"); + } sb.append("AGL: ").append(this.formatElevation(height)); } } @@ -701,25 +604,21 @@ public String getText(SegmentPlane segmentPlane, Position position, AVList value } } - public static class AltitudeLabelAttributes extends SARLabelAttributes - { + public static class AltitudeLabelAttributes extends SARLabelAttributes { + public AltitudeLabelAttributes(Color color, Font font, String horizontalAlignment, String verticalAlignment, - SARSegmentPlane context) - { + SARSegmentPlane context) { super(color, font, horizontalAlignment, verticalAlignment, context); } - public AltitudeLabelAttributes() - { + public AltitudeLabelAttributes() { } - public SegmentPlaneAttributes.LabelAttributes copy() - { + public SegmentPlaneAttributes.LabelAttributes copy() { return this.copyTo(new AltitudeLabelAttributes()); } - public String getText(SegmentPlane segmentPlane, Position position, AVList values) - { + public String getText(SegmentPlane segmentPlane, Position position, AVList values) { StringBuilder sb = new StringBuilder(); sb.append(this.formatElevation(position.getElevation())); @@ -727,123 +626,109 @@ public String getText(SegmentPlane segmentPlane, Position position, AVList value } } - public static class AxisLabelAttributes extends SARLabelAttributes - { + public static class AxisLabelAttributes extends SARLabelAttributes { + public AxisLabelAttributes(Color color, Font font, String horizontalAlignment, - String verticalAlignment, SARSegmentPlane context) - { + String verticalAlignment, SARSegmentPlane context) { super(color, font, horizontalAlignment, verticalAlignment, context); } - public AxisLabelAttributes() - { + public AxisLabelAttributes() { } - public SegmentPlaneAttributes.LabelAttributes copy() - { + public SegmentPlaneAttributes.LabelAttributes copy() { return this.copyTo(new AxisLabelAttributes()); } - public String getText(SegmentPlane segmentPlane, Position position, AVList values) - { + public String getText(SegmentPlane segmentPlane, Position position, AVList values) { StringBuilder sb = new StringBuilder(); - if (values != null) - { + if (values != null) { Double width = AVListImpl.getDoubleValue(values, AVKey.WIDTH); Double height = AVListImpl.getDoubleValue(values, AVKey.HEIGHT); boolean haveTuple = (width != null && height != null); - if (haveTuple) + if (haveTuple) { sb.append("("); + } - if (width != null) + if (width != null) { sb.append(this.formatElevation(width)); + } - if (haveTuple) + if (haveTuple) { sb.append(", "); + } - if (height != null) + if (height != null) { sb.append(this.formatElevation(height)); + } - if (haveTuple) + if (haveTuple) { sb.append(")"); + } } - if (sb.length() == 0) + if (sb.length() == 0) { return null; + } return sb.toString(); } } - public static class MessageLabelAttributes extends SegmentPlaneAttributes.LabelAttributes - { + public static class MessageLabelAttributes extends SegmentPlaneAttributes.LabelAttributes { + private String message; public MessageLabelAttributes(Color color, Font font, String horizontalAlignment, String verticalAlignment, - String message) - { + String message) { super(color, font, horizontalAlignment, verticalAlignment); this.message = message; } - public MessageLabelAttributes() - { + public MessageLabelAttributes() { } - public String getMessage() - { + public String getMessage() { return this.message; } - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; } - public SegmentPlaneAttributes.LabelAttributes copy() - { + public SegmentPlaneAttributes.LabelAttributes copy() { return this.copyTo(new MessageLabelAttributes()); } - protected SegmentPlaneAttributes.LabelAttributes copyTo(SegmentPlaneAttributes.LabelAttributes copy) - { + protected SegmentPlaneAttributes.LabelAttributes copyTo(SegmentPlaneAttributes.LabelAttributes copy) { super.copyTo(copy); - if (copy instanceof MessageLabelAttributes) - { + if (copy instanceof MessageLabelAttributes) { ((MessageLabelAttributes) copy).setMessage(this.getMessage()); } return copy; } - public String getText(SegmentPlane segmentPlane, Position position, AVList values) - { + public String getText(SegmentPlane segmentPlane, Position position, AVList values) { return this.getMessage(); } } - protected static String formatAngle(String format, Angle angle) - { - if (Angle.ANGLE_FORMAT_DMS.equals(format)) - { + protected static String formatAngle(String format, Angle angle) { + if (Angle.ANGLE_FORMAT_DMS.equals(format)) { return angle.toDMSString(); - } - else - { + } else { return angle.toDecimalDegreesString(4); } } - protected static String formatElevation(String elevationFormat, double elevation) - { - if (SAR2.UNIT_IMPERIAL.equals(elevationFormat)) - { + protected static String formatElevation(String elevationFormat, double elevation) { + if (SAR2.UNIT_IMPERIAL.equals(elevationFormat)) { return String.format("%.0f ft", WWMath.convertMetersToFeet(elevation)); - } - else // Default to metric units. + } else // Default to metric units. { return String.format("%.0f m", elevation); } @@ -852,30 +737,24 @@ protected static String formatElevation(String elevationFormat, double elevation //**************************************************************// //******************** Utility Methods ***********************// //**************************************************************// - - protected static double getSurfaceElevationAt(WorldWindow wwd, Angle latitude, Angle longitude) - { - if (wwd == null) - { + protected static double getSurfaceElevationAt(WorldWindow wwd, Angle latitude, Angle longitude) { + if (wwd == null) { String message = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } Globe globe = wwd.getModel().getGlobe(); - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } SectorGeometryList sgl = wwd.getSceneController().getTerrain(); - if (sgl != null) - { + if (sgl != null) { Vec4 point = sgl.getSurfacePoint(latitude, longitude); - if (point != null) - { + if (point != null) { Position pos = globe.computePositionFromPoint(point); return pos.getElevation(); } @@ -885,8 +764,7 @@ protected static double getSurfaceElevationAt(WorldWindow wwd, Angle latitude, A } protected static double[] computeAltitudesToFitPositions(WorldWindow wwd, SegmentPlane segmentPlane, - Iterable positions, boolean recallUserDefinedVGap) - { + Iterable positions, boolean recallUserDefinedVGap) { Globe globe = wwd.getModel().getGlobe(); double[] altitudes = segmentPlane.getPlaneAltitudes(); double[] gridSizes = segmentPlane.getGridCellDimensions(); @@ -896,59 +774,51 @@ protected static double[] computeAltitudesToFitPositions(WorldWindow wwd, Segmen double[] minAndMaxElevation = globe.getMinAndMaxElevations(Sector.boundingSector(positions)); double newMaxSegmentAltitude = -Double.MAX_VALUE; - for (Position pos : positions) - { - if (newMaxSegmentAltitude < pos.getElevation()) + for (Position pos : positions) { + if (newMaxSegmentAltitude < pos.getElevation()) { newMaxSegmentAltitude = pos.getElevation(); + } } double segmentVGap = altitudes[1] - oldMaxSegmentAltitude; - if (!recallUserDefinedVGap || segmentVGap < 0) - { + if (!recallUserDefinedVGap || segmentVGap < 0) { segmentVGap = computeInitialVerticalGap(wwd, segmentPlane, positions); } - return new double[] - { - gridSizes[1] * Math.floor(minAndMaxElevation[0] / gridSizes[1]), - newMaxSegmentAltitude + segmentVGap - }; + return new double[]{ + gridSizes[1] * Math.floor(minAndMaxElevation[0] / gridSizes[1]), + newMaxSegmentAltitude + segmentVGap + }; } protected static LatLon[] computeLocationsToFitPositions(WorldWindow wwd, SegmentPlane segmentPlane, - Position position1, Position position2, boolean recallUserDefinedHGap) - { + Position position1, Position position2, boolean recallUserDefinedHGap) { LatLon[] locations = segmentPlane.getPlaneLocations(); Position[] segmentPositions = segmentPlane.getSegmentPositions(); Angle segmentHGap = LatLon.rhumbDistance(segmentPositions[1], locations[1]); - if (!recallUserDefinedHGap || segmentHGap.compareTo(Angle.ZERO) < 0) - { + if (!recallUserDefinedHGap || segmentHGap.compareTo(Angle.ZERO) < 0) { segmentHGap = computeInitialHorizontalGap(wwd, segmentPlane, position1, position2); } Angle newSegmentHeading = LatLon.rhumbAzimuth(position1, position2); Angle newSegmentLength = LatLon.rhumbDistance(position1, position2).add(segmentHGap); - return new LatLon[] - { - new LatLon(position1), - LatLon.rhumbEndPosition(position1, newSegmentHeading, newSegmentLength) - }; + return new LatLon[]{ + new LatLon(position1), + LatLon.rhumbEndPosition(position1, newSegmentHeading, newSegmentLength) + }; } protected static double computeInitialVerticalGap(WorldWindow wwd, SegmentPlane segmentPlane, - Iterable positions) - { + Iterable positions) { double[] gridCellDimensions = segmentPlane.getGridCellDimensions(); double maxHeightAboveSurface = -Double.MAX_VALUE; - for (Position pos : positions) - { + for (Position pos : positions) { double heightAboveSurface = pos.getElevation() - getSurfaceElevationAt(wwd, - pos.getLatitude(), pos.getLongitude()); - if (heightAboveSurface > maxHeightAboveSurface) - { + pos.getLatitude(), pos.getLongitude()); + if (heightAboveSurface > maxHeightAboveSurface) { maxHeightAboveSurface = heightAboveSurface; } } @@ -957,8 +827,7 @@ protected static double computeInitialVerticalGap(WorldWindow wwd, SegmentPlane } protected static Angle computeInitialHorizontalGap(WorldWindow wwd, SegmentPlane segmentPlane, - Position position1, Position position2) - { + Position position1, Position position2) { double[] gridCellDimensions = segmentPlane.getGridCellDimensions(); double gridWidthRadians = gridCellDimensions[0] / wwd.getModel().getGlobe().getRadius(); diff --git a/src/gov/nasa/worldwindx/applications/sar/SARTrack.java b/src/gov/nasa/worldwindx/applications/sar/SARTrack.java index d8c1d8d778..2a12ebc49c 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARTrack.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARTrack.java @@ -24,32 +24,29 @@ * @author tag * @version $Id: SARTrack.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARTrack extends WWObjectImpl implements Iterable -{ +public class SARTrack extends WWObjectImpl implements Iterable { + public static final int FORMAT_GPX = 1; public static final int FORMAT_CSV = 2; public static final int FORMAT_NMEA = 3; - private static class FormatInfo - { + private static class FormatInfo { + private TrackReader reader; private int format; - private FormatInfo(TrackReader reader, int format) - { + private FormatInfo(TrackReader reader, int format) { this.reader = reader; this.format = format; } } private static int nextColor = 0; - private static Color[] colors = new Color[] - { - Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN, Color.ORANGE, Color.PINK, Color.YELLOW - }; + private static Color[] colors = new Color[]{ + Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN, Color.ORANGE, Color.PINK, Color.YELLOW + }; - private static Color nextColor() - { + private static Color nextColor() { return colors[nextColor++ % colors.length]; } @@ -65,10 +62,8 @@ private static Color nextColor() private ArrayList positions; private PropertyChangeSupport propChangeSupport = new PropertyChangeSupport(this); - public static SARTrack fromFile(String filePath) throws IOException - { - if (filePath == null) - { + public static SARTrack fromFile(String filePath) throws IOException { + if (filePath == null) { String message = Logging.getMessage("nullValue.FilePathIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -76,8 +71,7 @@ public static SARTrack fromFile(String filePath) throws IOException File file = new File(filePath); - if (!file.exists()) - { + if (!file.exists()) { String message = Logging.getMessage("generic.FileNotFound", filePath); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -85,23 +79,20 @@ public static SARTrack fromFile(String filePath) throws IOException SARTrack track = null; - FormatInfo[] formatInfoArray = new FormatInfo[] - { - new FormatInfo(new CSVTrackReader(), FORMAT_CSV), - new FormatInfo(new GPXTrackReader(), FORMAT_GPX), - new FormatInfo(new NMEATrackReader(), FORMAT_NMEA), - }; + FormatInfo[] formatInfoArray = new FormatInfo[]{ + new FormatInfo(new CSVTrackReader(), FORMAT_CSV), + new FormatInfo(new GPXTrackReader(), FORMAT_GPX), + new FormatInfo(new NMEATrackReader(), FORMAT_NMEA),}; int formatIndex; - for (formatIndex = 0; formatIndex < formatInfoArray.length; formatIndex++) - { + for (formatIndex = 0; formatIndex < formatInfoArray.length; formatIndex++) { track = readTrack(filePath, formatInfoArray[formatIndex]); - if (track != null) + if (track != null) { break; + } } - if (track != null) - { + if (track != null) { track.setFile(file); track.setFormat(formatIndex); track.setName(file.getName()); @@ -110,221 +101,197 @@ public static SARTrack fromFile(String filePath) throws IOException return track; } - private static SARTrack readTrack(String filePath, FormatInfo format) - { - if (!format.reader.canRead(filePath)) + private static SARTrack readTrack(String filePath, FormatInfo format) { + if (!format.reader.canRead(filePath)) { return null; + } Track[] tracks = null; - try - { + try { tracks = format.reader.read(filePath); - } - catch (Exception e) - { + } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionAttemptingToReadFile", filePath); Logging.logger().severe(message); } - if (tracks == null) + if (tracks == null) { return null; + } TrackPointIterator tpi = new TrackPointIteratorImpl(Arrays.asList(tracks)); return makeTrackFromTrackPointIterator(tpi); } - public static void toFile(SARTrack track, String filePath, int format) throws IOException - { - if (track == null) + public static void toFile(SARTrack track, String filePath, int format) throws IOException { + if (track == null) { throw new IllegalArgumentException("track is null"); - if (filePath == null) + } + if (filePath == null) { throw new IllegalArgumentException("filePath is null"); + } - if (format == FORMAT_GPX) + if (format == FORMAT_GPX) { writeGPX(track, filePath); - else if (format == FORMAT_CSV) + } else if (format == FORMAT_CSV) { writeCSV(track, filePath); - else if (format == FORMAT_NMEA) + } else if (format == FORMAT_NMEA) { writeNMEA(track, filePath); + } // If no format is specified, then do nothing. } - private SARTrack() - { + private SARTrack() { } - public SARTrack(String name) - { + public SARTrack(String name) { this.name = name; this.positions = new ArrayList(); } - public File getFile() - { + public File getFile() { return this.file; } - public void setFile(File file) - { + public void setFile(File file) { this.file = file; } - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; this.firePropertyChange(TrackController.TRACK_NAME, null, this); } - public int getFormat() - { + public int getFormat() { return format; } - public void setFormat(int format) - { + public void setFormat(int format) { this.format = format; } - public long getLastSaveTime() - { + public long getLastSaveTime() { return this.lastSaveTime; } - public long getLastModifiedTime() - { + public long getLastModifiedTime() { return this.lastModifiedTime; } - public boolean isDirty() - { + public boolean isDirty() { return this.lastModifiedTime == 0L || this.lastSaveTime == 0L || (this.lastModifiedTime > this.lastSaveTime); } - public void markDirty() - { + public void markDirty() { this.lastModifiedTime = System.currentTimeMillis(); this.firePropertyChange(TrackController.TRACK_DIRTY_BIT, null, this); } - public void clearDirtyBit() - { + public void clearDirtyBit() { long time = System.currentTimeMillis(); this.lastSaveTime = time; this.lastModifiedTime = time; this.firePropertyChange(TrackController.TRACK_DIRTY_BIT, null, this); } - public Color getColor() - { + public Color getColor() { return color; } - public void setColor(Color color) - { + public void setColor(Color color) { this.color = color; } - public int size() - { + public int size() { return this.positions.size(); } - public ArrayList getPositions() - { + public ArrayList getPositions() { return this.positions; } - public SARPosition get(int index) - { + public SARPosition get(int index) { return this.positions.size() > index ? this.positions.get(index) : null; } - public void set(int index, SARPosition position) - { - if (position == null) + public void set(int index, SARPosition position) { + if (position == null) { return; + } - if (index >= this.positions.size()) + if (index >= this.positions.size()) { this.positions.add(position); - else + } else { this.positions.set(index, position); + } this.markDirty(); this.firePropertyChange(TrackController.TRACK_MODIFY, null, index); } - public void add(int index, SARPosition position) - { - if (position == null) + public void add(int index, SARPosition position) { + if (position == null) { return; + } - if (index >= this.positions.size()) + if (index >= this.positions.size()) { this.positions.add(position); - else + } else { this.positions.add(index, position); + } this.markDirty(); this.firePropertyChange(TrackController.TRACK_MODIFY, null, this); } - public double getOffset() - { + public double getOffset() { return offset; } - public void setOffset(double offset) - { + public void setOffset(double offset) { double oldOffset = this.offset; this.offset = offset; this.firePropertyChange(TrackController.TRACK_OFFSET, oldOffset, this.offset); } - public Iterator iterator() - { - return new Iterator() - { + public Iterator iterator() { + return new Iterator() { private Iterator iter = SARTrack.this.positions.iterator(); - public boolean hasNext() - { + public boolean hasNext() { return this.iter.hasNext(); } - public Position next() - { + public Position next() { return this.iter.next(); } - public void remove() - { + public void remove() { throw new UnsupportedOperationException("Remove operation not supported for SARTrack iterator"); } }; } - public void removePosition(int index) - { - if (index < 0 || index >= this.positions.size()) + public void removePosition(int index) { + if (index < 0 || index >= this.positions.size()) { return; + } this.positions.remove(index); this.markDirty(); this.firePropertyChange(TrackController.TRACK_MODIFY, null, this); } - public void removePositions(int[] positionNumbers) - { + public void removePositions(int[] positionNumbers) { Arrays.sort(positionNumbers); - for (int i = positionNumbers.length - 1; i >= 0; i--) - { - if (positionNumbers[i] < 0 || positionNumbers[i] >= this.positions.size()) + for (int i = positionNumbers.length - 1; i >= 0; i--) { + if (positionNumbers[i] < 0 || positionNumbers[i] >= this.positions.size()) { continue; + } this.positions.remove(positionNumbers[i]); } @@ -333,79 +300,69 @@ public void removePositions(int[] positionNumbers) this.firePropertyChange(TrackController.TRACK_MODIFY, null, this); } - public void appendPosition(SARPosition position) - { - if (position == null) + public void appendPosition(SARPosition position) { + if (position == null) { return; + } this.positions.add(position); this.markDirty(); this.firePropertyChange(TrackController.TRACK_MODIFY, null, this); } - public void insertPosition(int index, SARPosition position) - { - if (position == null || index < 0) + public void insertPosition(int index, SARPosition position) { + if (position == null || index < 0) { return; + } this.positions.add(index, position); this.markDirty(); this.firePropertyChange(TrackController.TRACK_MODIFY, null, this); } - public void setPosition(int index, SARPosition position) - { - if (position == null || index < 0) + public void setPosition(int index, SARPosition position) { + if (position == null || index < 0) { return; + } this.positions.set(index, position); this.markDirty(); this.firePropertyChange(TrackController.TRACK_MODIFY, null, index); } - private static void writeNMEA(SARTrack track, String filePath) throws IOException - { + private static void writeNMEA(SARTrack track, String filePath) throws IOException { NmeaWriter writer = new NmeaWriter(filePath); Track trk = makeTrackFromSARTrack(track); writer.writeTrack(trk); writer.close(); } - private static void writeGPX(SARTrack track, String filePath) throws IOException - { - try - { + private static void writeGPX(SARTrack track, String filePath) throws IOException { + try { GpxWriter writer = new GpxWriter(filePath); Track trk = makeTrackFromSARTrack(track); writer.writeTrack(trk); writer.close(); - } - catch (ParserConfigurationException e) - { + } catch (ParserConfigurationException e) { throw new IllegalArgumentException(e); - } - catch (javax.xml.transform.TransformerException e) - { + } catch (javax.xml.transform.TransformerException e) { throw new IllegalArgumentException(e); } } - private static void writeCSV(SARTrack track, String filePath) throws IOException - { + private static void writeCSV(SARTrack track, String filePath) throws IOException { CSVWriter writer = new CSVWriter(filePath); Track trk = makeTrackFromSARTrack(track); writer.writeTrack(trk); writer.close(); } - private static SARTrack makeTrackFromTrackPointIterator(TrackPointIterator tpi) - { + private static SARTrack makeTrackFromTrackPointIterator(TrackPointIterator tpi) { ArrayList positions = new ArrayList(); - while (tpi.hasNext()) - { + while (tpi.hasNext()) { TrackPoint tp = tpi.next(); SARPosition sp = new SARPosition( - Angle.fromDegrees(tp.getLatitude()), Angle.fromDegrees(tp.getLongitude()), tp.getElevation()); + Angle.fromDegrees(tp.getLatitude()), Angle.fromDegrees(tp.getLongitude()), tp.getElevation()); positions.add(sp); } @@ -415,126 +372,103 @@ private static SARTrack makeTrackFromTrackPointIterator(TrackPointIterator tpi) return st; } - private static Track makeTrackFromSARTrack(SARTrack sarTrack) - { + private static Track makeTrackFromSARTrack(SARTrack sarTrack) { return new TrackWrapper(sarTrack); } - private static class TrackWrapper implements Track, TrackSegment - { + private static class TrackWrapper implements Track, TrackSegment { + private final SARTrack sarTrack; private final ArrayList segments = new ArrayList(); - public TrackWrapper(SARTrack sarTrack) - { + public TrackWrapper(SARTrack sarTrack) { this.sarTrack = sarTrack; this.segments.add(this); } - public java.util.List getSegments() - { + public java.util.List getSegments() { return this.segments; } - public String getName() - { + public String getName() { return this.sarTrack.getName(); } - public int getNumPoints() - { + public int getNumPoints() { return this.sarTrack.size(); } - public java.util.List getPoints() - { + public java.util.List getPoints() { ArrayList trkPoints = new ArrayList(); - for (SARPosition sarPos : this.sarTrack.positions) - { + for (SARPosition sarPos : this.sarTrack.positions) { trkPoints.add(sarPos != null ? new TrackPointWrapper(sarPos) : null); } return trkPoints; } } - private static class TrackPointWrapper implements TrackPoint - { + private static class TrackPointWrapper implements TrackPoint { + private final SARPosition sarPosition; - public TrackPointWrapper(SARPosition sarPosition) - { + public TrackPointWrapper(SARPosition sarPosition) { this.sarPosition = sarPosition; } - public double getLatitude() - { + public double getLatitude() { return this.sarPosition.getLatitude().degrees; } - public void setLatitude(double latitude) - { + public void setLatitude(double latitude) { } - public double getLongitude() - { + public double getLongitude() { return this.sarPosition.getLongitude().degrees; } - public void setLongitude(double longitude) - { + public void setLongitude(double longitude) { } - public double getElevation() - { + public double getElevation() { return this.sarPosition.getElevation(); } - public void setElevation(double elevation) - { + public void setElevation(double elevation) { } - public String getTime() - { + public String getTime() { return null; } - public void setTime(String time) - { + public void setTime(String time) { } - public Position getPosition() - { + public Position getPosition() { return this.sarPosition; } - public void setPosition(Position position) - { + public void setPosition(Position position) { } } - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { this.propChangeSupport.addPropertyChangeListener(propertyName, listener); } - public void addPropertyChangeListener(PropertyChangeListener listener) - { + public void addPropertyChangeListener(PropertyChangeListener listener) { this.propChangeSupport.addPropertyChangeListener(listener); } - public void removePropertyChangeListener(PropertyChangeListener listener) - { + public void removePropertyChangeListener(PropertyChangeListener listener) { this.propChangeSupport.removePropertyChangeListener(listener); } - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { this.propChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } @Override - public String toString() - { + public String toString() { return this.name; } } diff --git a/src/gov/nasa/worldwindx/applications/sar/SARTrackBuilder.java b/src/gov/nasa/worldwindx/applications/sar/SARTrackBuilder.java index c51e55f118..4863ac8ccc 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARTrackBuilder.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARTrackBuilder.java @@ -16,8 +16,8 @@ * @author tag * @version $Id: SARTrackBuilder.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARTrackBuilder -{ +public class SARTrackBuilder { + private WorldWindow wwd; private SARTrack sarTrack; private boolean armed = false; @@ -27,18 +27,12 @@ public class SARTrackBuilder private MouseMotionAdapter mouseMotionAdapter; private PositionListener positionListener; - public SARTrackBuilder() - { - this.mouseAdapter = new MouseAdapter() - { - public void mousePressed(MouseEvent mouseEvent) - { - if (armed && sarTrack != null && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (armed && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { - if (mouseEvent.isAltDown() && !mouseEvent.isControlDown()) - { + public SARTrackBuilder() { + this.mouseAdapter = new MouseAdapter() { + public void mousePressed(MouseEvent mouseEvent) { + if (armed && sarTrack != null && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (armed && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { + if (mouseEvent.isAltDown() && !mouseEvent.isControlDown()) { active = true; addPosition(); } @@ -47,60 +41,53 @@ public void mousePressed(MouseEvent mouseEvent) } } - public void mouseReleased(MouseEvent mouseEvent) - { - if (armed && sarTrack != null && mouseEvent.getButton() == MouseEvent.BUTTON1) - { + public void mouseReleased(MouseEvent mouseEvent) { + if (armed && sarTrack != null && mouseEvent.getButton() == MouseEvent.BUTTON1) { active = false; mouseEvent.consume(); } } - public void mouseClicked(MouseEvent mouseEvent) - { - if (armed && sarTrack != null && mouseEvent.getButton() == MouseEvent.BUTTON1) - { - if (mouseEvent.isControlDown()) + public void mouseClicked(MouseEvent mouseEvent) { + if (armed && sarTrack != null && mouseEvent.getButton() == MouseEvent.BUTTON1) { + if (mouseEvent.isControlDown()) { removeLastTrackPoint(); + } mouseEvent.consume(); } } }; - this.mouseMotionAdapter = new MouseMotionAdapter() - { - public void mouseDragged(MouseEvent mouseEvent) - { - if (armed && sarTrack != null && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { + this.mouseMotionAdapter = new MouseMotionAdapter() { + public void mouseDragged(MouseEvent mouseEvent) { + if (armed && sarTrack != null && (mouseEvent.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { // Don't update the track here because the wwd current cursor position will not // have been updated to reflect the current mouse position. Wait to update in the // position listener, but consume the event so the view doesn't respond to it. - if (active) + if (active) { mouseEvent.consume(); + } } } }; - this.positionListener = new PositionListener() - { - public void moved(PositionEvent event) - { - if (!active || sarTrack == null) + this.positionListener = new PositionListener() { + public void moved(PositionEvent event) { + if (!active || sarTrack == null) { return; + } replacePosition(); } }; } - public void setWwd(WorldWindow wwd) - { - if (this.wwd == wwd) + public void setWwd(WorldWindow wwd) { + if (this.wwd == wwd) { return; + } - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.getInputHandler().removeMouseListener(this.mouseAdapter); this.wwd.getInputHandler().removeMouseMotionListener(this.mouseMotionAdapter); this.wwd.removePositionListener(this.positionListener); @@ -112,73 +99,71 @@ public void setWwd(WorldWindow wwd) this.wwd.addPositionListener(this.positionListener); } - public void setTrack(SARTrack track) - { + public void setTrack(SARTrack track) { this.sarTrack = track; } - public boolean isUseTrackElevation() - { + public boolean isUseTrackElevation() { return this.useTrackElevation; } - public void setUseTrackElevation(boolean state) - { + public void setUseTrackElevation(boolean state) { this.useTrackElevation = state; } - public boolean isArmed() - { + public boolean isArmed() { return this.armed; } - public void setArmed(boolean armed) - { + public void setArmed(boolean armed) { this.armed = armed; - if (this.armed) + if (this.armed) { ((Component) this.wwd).setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); - else + } else { ((Component) this.wwd).setCursor(Cursor.getDefaultCursor()); + } } - private void addPosition() - { + private void addPosition() { Position curPos = this.wwd != null ? this.wwd.getCurrentPosition() : null; - if (curPos == null) + if (curPos == null) { return; + } - if (this.useTrackElevation && this.sarTrack.size() > 0) + if (this.useTrackElevation && this.sarTrack.size() > 0) { curPos = new Position(curPos, this.sarTrack.get(this.sarTrack.size() - 1).getElevation()); + } this.sarTrack.appendPosition(new SARPosition(curPos)); } - private void replacePosition() - { + private void replacePosition() { Position curPos = this.wwd != null ? this.wwd.getCurrentPosition() : null; - if (curPos == null) + if (curPos == null) { return; + } - if (this.useTrackElevation && this.sarTrack.size() > 0) + if (this.useTrackElevation && this.sarTrack.size() > 0) { curPos = new Position(curPos, this.sarTrack.get(this.sarTrack.size() - 1).getElevation()); - + } + int index = this.sarTrack.size() - 1; - if (index < 0) + if (index < 0) { index = 0; + } this.sarTrack.set(index, new SARPosition(curPos)); } - public boolean canRemoveLastTrackPoint() - { + public boolean canRemoveLastTrackPoint() { return this.sarTrack != null && this.sarTrack.size() != 0; } - public void removeLastTrackPoint() - { - if (this.sarTrack == null || this.sarTrack.size() == 0) + public void removeLastTrackPoint() { + if (this.sarTrack == null || this.sarTrack.size() == 0) { return; + } this.sarTrack.removePosition(this.sarTrack.size() - 1); } diff --git a/src/gov/nasa/worldwindx/applications/sar/SARTrackExtensionTool.java b/src/gov/nasa/worldwindx/applications/sar/SARTrackExtensionTool.java index 96c96eb203..a7259f1fb7 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SARTrackExtensionTool.java +++ b/src/gov/nasa/worldwindx/applications/sar/SARTrackExtensionTool.java @@ -24,8 +24,8 @@ * @author tag * @version $Id: SARTrackExtensionTool.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARTrackExtensionTool implements MouseListener, PositionListener, PropertyChangeListener -{ +public class SARTrackExtensionTool implements MouseListener, PositionListener, PropertyChangeListener { + private boolean armed; private WorldWindow wwd; // Can be null. private SARTrack track; // Can be null. @@ -36,50 +36,42 @@ public class SARTrackExtensionTool implements MouseListener, PositionListener, P protected SegmentPlaneAttributes.GeometryAttributes segmentEndGeomAttribs; protected SegmentPlaneAttributes.LabelAttributes segmentEndLabelAttribs; - public SARTrackExtensionTool() - { + public SARTrackExtensionTool() { this.segmentPlane = new SARSegmentPlane(); this.segmentPlane.addPropertyChangeListener(this); - this.segmentEndGeomAttribs = - this.segmentPlane.getAttributes().getGeometryAttributes(SegmentPlane.SEGMENT_END).copy(); - this.segmentEndLabelAttribs = - this.segmentPlane.getAttributes().getLabelAttributes(SegmentPlane.SEGMENT_END).copy(); + this.segmentEndGeomAttribs + = this.segmentPlane.getAttributes().getGeometryAttributes(SegmentPlane.SEGMENT_END).copy(); + this.segmentEndLabelAttribs + = this.segmentPlane.getAttributes().getLabelAttributes(SegmentPlane.SEGMENT_END).copy(); } - public boolean isArmed() - { + public boolean isArmed() { return this.armed; } - public void setArmed(boolean armed) - { + public void setArmed(boolean armed) { boolean wasArmed = this.armed; this.armed = armed; this.segmentPlane.setArmed(armed); - if (!wasArmed && this.armed) - { + if (!wasArmed && this.armed) { this.start(); - } - else if (wasArmed && !this.armed) - { + } else if (wasArmed && !this.armed) { this.stop(); } } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.wwd; } - public void setWorldWindow(WorldWindow wwd) - { - if (this.wwd == wwd) + public void setWorldWindow(WorldWindow wwd) { + if (this.wwd == wwd) { return; + } - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.getInputHandler().removeMouseListener(this); this.wwd.removePositionListener(this); } @@ -87,162 +79,134 @@ public void setWorldWindow(WorldWindow wwd) this.wwd = wwd; this.segmentPlane.setWorldWindow(wwd); - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.getInputHandler().addMouseListener(this); this.wwd.addPositionListener(this); } } - public SARTrack getTrack() - { + public SARTrack getTrack() { return this.track; } - public void setTrack(SARTrack track) - { - if (this.track == track) + public void setTrack(SARTrack track) { + if (this.track == track) { return; + } - if (this.track != null) - { + if (this.track != null) { this.track.removePropertyChangeListener(this); } this.track = track; this.onTrackChanged(); - if (this.track != null) - { + if (this.track != null) { this.track.addPropertyChangeListener(this); } } - public boolean canMoveToNextTrackPoint() - { + public boolean canMoveToNextTrackPoint() { return this.track != null && !this.waitingForNextPosition; } - public void moveToNextTrackPoint() - { - if (this.track == null || this.waitingForNextPosition) + public void moveToNextTrackPoint() { + if (this.track == null || this.waitingForNextPosition) { return; + } this.start(); } - public boolean canRemoveLastTrackPoint() - { + public boolean canRemoveLastTrackPoint() { return this.track != null && this.track.size() != 0; } - public void removeLastTrackPoint() - { - if (this.track == null || this.track.size() == 0) + public void removeLastTrackPoint() { + if (this.track == null || this.track.size() == 0) { return; + } int lastIndex = this.track.size() - 1; this.track.removePosition(lastIndex); this.waitingForNextPosition = true; } - protected void start() - { - if (this.track.size() >= 1) - { + protected void start() { + if (this.track.size() >= 1) { this.snapPlaneToLastTrackPoint(); this.segmentPlane.setVisible(true); - } - else - { + } else { this.segmentPlane.setVisible(false); } this.waitingForNextPosition = true; } - protected void stop() - { + protected void stop() { this.segmentPlane.setVisible(false); } - protected void setNextPosition(Position position) - { + protected void setNextPosition(Position position) { SARPosition trackPosition = this.positionToTrackPosition(position); this.ignoreTrackChangeEvents = true; - try - { + try { this.track.appendPosition(trackPosition); - } - finally - { + } finally { this.ignoreTrackChangeEvents = false; } this.segmentPlane.getAttributes().setGeometryAttributes(SegmentPlane.SEGMENT_END, - this.segmentEndGeomAttribs.copy()); + this.segmentEndGeomAttribs.copy()); this.segmentPlane.getAttributes().setLabelAttributes(SegmentPlane.SEGMENT_END, - this.segmentEndLabelAttribs.copy()); + this.segmentEndLabelAttribs.copy()); this.snapPlaneToLastTrackSegment(); } - protected void setPotentialNextPosition(Position position) - { + protected void setPotentialNextPosition(Position position) { this.potentialNextPosition = position; - if (this.potentialNextPosition != null) - { + if (this.potentialNextPosition != null) { Position[] segmentPositions = this.segmentPlane.getSegmentPositions(); this.segmentPlane.setSegmentPositions(segmentPositions[0], this.potentialNextPosition); this.segmentPlane.getAttributes().setGeometryAttributes(SegmentPlane.SEGMENT_END, - this.createPotentialNextPositionGeomAttributes()); + this.createPotentialNextPositionGeomAttributes()); this.segmentPlane.getAttributes().setLabelAttributes(SegmentPlane.SEGMENT_END, - this.createPotentialNextPositionLabelAttributes()); + this.createPotentialNextPositionLabelAttributes()); this.showSegmentEndPoint(true); - } - else - { + } else { this.showSegmentEndPoint(false); } } - protected PickedObject getTopPickedObject() - { - return (this.wwd.getSceneController().getPickedObjectList() != null) ? - this.wwd.getSceneController().getPickedObjectList().getTopPickedObject() : null; + protected PickedObject getTopPickedObject() { + return (this.wwd.getSceneController().getPickedObjectList() != null) + ? this.wwd.getSceneController().getPickedObjectList().getTopPickedObject() : null; } //**************************************************************// //******************** Mouse Events **************************// //**************************************************************// - - public void mouseClicked(MouseEvent e) - { + public void mouseClicked(MouseEvent e) { } - public void mousePressed(MouseEvent e) - { - if (e == null || e.isConsumed()) - { + public void mousePressed(MouseEvent e) { + if (e == null || e.isConsumed()) { return; } - if (!this.armed || this.wwd == null) - { + if (!this.armed || this.wwd == null) { return; } - if (e.getButton() == MouseEvent.BUTTON1) - { - if (this.waitingForNextPosition) - { - if (this.potentialNextPosition != null) - { + if (e.getButton() == MouseEvent.BUTTON1) { + if (this.waitingForNextPosition) { + if (this.potentialNextPosition != null) { this.setNextPosition(this.potentialNextPosition); this.waitingForNextPosition = false; } @@ -250,45 +214,35 @@ public void mousePressed(MouseEvent e) } } - public void mouseReleased(MouseEvent e) - { + public void mouseReleased(MouseEvent e) { } - public void mouseEntered(MouseEvent e) - { + public void mouseEntered(MouseEvent e) { } - public void mouseExited(MouseEvent e) - { + public void mouseExited(MouseEvent e) { } //**************************************************************// //******************** Position Events ***********************// //**************************************************************// - - public void moved(PositionEvent e) - { - if (e == null) - { + public void moved(PositionEvent e) { + if (e == null) { return; } - if (!this.armed || this.wwd == null) - { + if (!this.armed || this.wwd == null) { return; } - if (this.waitingForNextPosition) - { + if (this.waitingForNextPosition) { Position nextPosition = null; PickedObject po = this.getTopPickedObject(); - if (po != null) - { + if (po != null) { Object id = po.getValue(AVKey.PICKED_OBJECT_ID); - if (id == SegmentPlane.PLANE_BACKGROUND || - (this.segmentPlane.isSnapToGrid() && id == SegmentPlane.PLANE_GRID)) - { + if (id == SegmentPlane.PLANE_BACKGROUND + || (this.segmentPlane.isSnapToGrid() && id == SegmentPlane.PLANE_GRID)) { nextPosition = po.getPosition(); } } @@ -300,20 +254,14 @@ public void moved(PositionEvent e) //**************************************************************// //******************** Property Change Events ****************// //**************************************************************// - @SuppressWarnings({"StringEquality"}) - public void propertyChange(PropertyChangeEvent e) - { + public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); - if (propertyName == SegmentPlane.SEGMENT_END) - { + if (propertyName == SegmentPlane.SEGMENT_END) { this.snapTrackPointToPlanePoint(propertyName); - } - else if (propertyName == TrackController.TRACK_MODIFY || propertyName == TrackController.TRACK_OFFSET) - { - if (!this.ignoreTrackChangeEvents) - { + } else if (propertyName == TrackController.TRACK_MODIFY || propertyName == TrackController.TRACK_OFFSET) { + if (!this.ignoreTrackChangeEvents) { this.start(); } } @@ -322,62 +270,59 @@ else if (propertyName == TrackController.TRACK_MODIFY || propertyName == TrackCo //**************************************************************// //******************** Track/Plane Synchronization ***********// //**************************************************************// - - protected void onTrackChanged() - { + protected void onTrackChanged() { SegmentPlaneAttributes.LabelAttributes labelAttrib = this.segmentPlane.getAttributes().getLabelAttributes( - SegmentPlane.HORIZONTAL_AXIS_LABELS); - if (labelAttrib != null) - { + SegmentPlane.HORIZONTAL_AXIS_LABELS); + if (labelAttrib != null) { Color labelColor = (this.track != null) ? WWUtil.makeColorBrighter(this.track.getColor()) - : WWUtil.makeColorBrighter(Color.RED); + : WWUtil.makeColorBrighter(Color.RED); labelAttrib.setColor(labelColor); } } @SuppressWarnings({"StringEquality"}) - protected void snapTrackPointToPlanePoint(String planePoint) - { - if (this.track == null) + protected void snapTrackPointToPlanePoint(String planePoint) { + if (this.track == null) { return; + } - if (this.track.size() == 0) + if (this.track.size() == 0) { return; + } - if (this.waitingForNextPosition && planePoint == SegmentPlane.SEGMENT_END) + if (this.waitingForNextPosition && planePoint == SegmentPlane.SEGMENT_END) { return; + } Position[] segmentPositions = this.segmentPlane.getSegmentPositions(); this.ignoreTrackChangeEvents = true; - try - { - if (planePoint == SegmentPlane.SEGMENT_END) - { + try { + if (planePoint == SegmentPlane.SEGMENT_END) { int lastIndex = this.track.size() - 1; SARPosition trackPosition = this.positionToTrackPosition(segmentPositions[1]); this.track.set(lastIndex, trackPosition); } - } - finally - { + } finally { this.ignoreTrackChangeEvents = false; } } - protected void snapPlaneToLastTrackPoint() - { - if (this.track == null) + protected void snapPlaneToLastTrackPoint() { + if (this.track == null) { return; + } - if (this.track.size() == 0) + if (this.track.size() == 0) { return; + } int lastIndex = this.track.size() - 1; SARPosition lastTrackPosition = this.track.get(lastIndex); SARPosition nextTrackPosition = this.computeNextTrackPosition(); - if (nextTrackPosition == null) + if (nextTrackPosition == null) { nextTrackPosition = lastTrackPosition; + } Position position1 = this.trackPositionToPosition(lastTrackPosition); Position position2 = this.trackPositionToPosition(nextTrackPosition); @@ -393,13 +338,14 @@ protected void snapPlaneToLastTrackPoint() this.wwd.redraw(); } - protected void snapPlaneToLastTrackSegment() - { - if (this.track == null) + protected void snapPlaneToLastTrackSegment() { + if (this.track == null) { return; + } - if (this.track.size() < 2) + if (this.track.size() < 2) { return; + } int lastIndex = this.track.size() - 1; SARPosition lastTrackPosition = this.track.get(lastIndex - 1); @@ -419,8 +365,7 @@ protected void snapPlaneToLastTrackSegment() this.wwd.redraw(); } - protected void showSegmentEndPoint(boolean show) - { + protected void showSegmentEndPoint(boolean show) { this.segmentPlane.setObjectVisible(SegmentPlane.SEGMENT_END, show, show); this.segmentPlane.setObjectVisible(SegmentPlane.ALTIMETER, show, false); } @@ -428,9 +373,7 @@ protected void showSegmentEndPoint(boolean show) //**************************************************************// //******************** Utility Methods ***********************// //**************************************************************// - - protected SARPosition computeNextTrackPosition(Point mousePoint) - { + protected SARPosition computeNextTrackPosition(Point mousePoint) { View view = this.wwd.getView(); Line ray = view.computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); Position position = this.segmentPlane.getIntersectionPosition(ray); @@ -438,10 +381,8 @@ protected SARPosition computeNextTrackPosition(Point mousePoint) return this.positionToTrackPosition(position); } - protected SARPosition computeNextTrackPosition() - { - if (this.track.size() < 2) - { + protected SARPosition computeNextTrackPosition() { + if (this.track.size() < 2) { return null; } @@ -454,8 +395,9 @@ protected SARPosition computeNextTrackPosition() double size = this.segmentPlane.getObjectSize(SegmentPlane.SEGMENT_END, point); double distance = Math.ceil(2 * size / gridDimensions[0]); - if (distance < 1) + if (distance < 1) { distance = 1; + } distance = distance * gridDimensions[0]; Angle heading = LatLon.rhumbAzimuth(this.track.get(lastIndex - 1), lastPosition); @@ -465,14 +407,12 @@ protected SARPosition computeNextTrackPosition() return new SARPosition(nextLocation.getLatitude(), nextLocation.getLongitude(), lastPosition.getElevation()); } - protected SARPosition positionToTrackPosition(Position position) - { + protected SARPosition positionToTrackPosition(Position position) { double trackOffset = this.track.getOffset(); return new SARPosition(position.getLatitude(), position.getLongitude(), position.getElevation() - trackOffset); } - protected Position trackPositionToPosition(Position position) - { + protected Position trackPositionToPosition(Position position) { double trackOffset = this.track.getOffset(); return new Position(position.getLatitude(), position.getLongitude(), position.getElevation() + trackOffset); } @@ -480,23 +420,20 @@ protected Position trackPositionToPosition(Position position) //**************************************************************// //******************** Mouse Events **************************// //**************************************************************// - - protected SegmentPlaneAttributes.GeometryAttributes createPotentialNextPositionGeomAttributes() - { + protected SegmentPlaneAttributes.GeometryAttributes createPotentialNextPositionGeomAttributes() { SegmentPlaneAttributes.GeometryAttributes geometryAttributes = new SegmentPlaneAttributes.GeometryAttributes( - Material.BLUE, 1.0); + Material.BLUE, 1.0); geometryAttributes.setSize(8); geometryAttributes.setPickSize(0); return geometryAttributes; } - protected SegmentPlaneAttributes.LabelAttributes createPotentialNextPositionLabelAttributes() - { + protected SegmentPlaneAttributes.LabelAttributes createPotentialNextPositionLabelAttributes() { SARSegmentPlane.MessageLabelAttributes labelAttributes = new SARSegmentPlane.MessageLabelAttributes( - Color.WHITE, Font.decode("Arial-18"), AVKey.LEFT, AVKey.CENTER, "Click to add"); + Color.WHITE, Font.decode("Arial-18"), AVKey.LEFT, AVKey.CENTER, "Click to add"); labelAttributes.setOffset(new Vec4(15, 0, 0)); return labelAttributes; } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwindx/applications/sar/SaveTrackDialog.java b/src/gov/nasa/worldwindx/applications/sar/SaveTrackDialog.java index 3f9755c121..fe8879ea40 100644 --- a/src/gov/nasa/worldwindx/applications/sar/SaveTrackDialog.java +++ b/src/gov/nasa/worldwindx/applications/sar/SaveTrackDialog.java @@ -17,8 +17,8 @@ * @author dcollins * @version $Id: SaveTrackDialog.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SaveTrackDialog -{ +public class SaveTrackDialog { + private JFileChooser fileChooser; private JCheckBox saveAnnotations; @@ -26,176 +26,165 @@ public class SaveTrackDialog public static final int CANCEL_OPTION = JFileChooser.CANCEL_OPTION; public static final int ERROR_OPTION = JFileChooser.ERROR_OPTION; - public SaveTrackDialog() - { + public SaveTrackDialog() { initComponents(); } - public File getSelectedFile() - { + public File getSelectedFile() { File file = this.fileChooser.getSelectedFile(); - if (file == null) + if (file == null) { return null; + } SaveTrackFilter filter = this.getSelectedSaveFilter(); - if (filter != null) + if (filter != null) { file = filter.appendSuffix(file); + } return file; } - public void setSelectedFile(File file) - { + public void setSelectedFile(File file) { this.fileChooser.setSelectedFile(file); } - public void setSelectedFile(SARTrack track) - { - if (track != null) - { - if (track.getFile() != null) + public void setSelectedFile(SARTrack track) { + if (track != null) { + if (track.getFile() != null) { this.fileChooser.setSelectedFile(track.getFile()); - else if (track.getName() != null && this.fileChooser.getCurrentDirectory() != null) + } else if (track.getName() != null && this.fileChooser.getCurrentDirectory() != null) { this.fileChooser.setSelectedFile(new File(this.fileChooser.getCurrentDirectory(), track.getName())); + } } } - public boolean isSaveAnnotations() - { + public boolean isSaveAnnotations() { return this.saveAnnotations.isSelected(); } - public void setSaveAnnotations(boolean saveAnnotations) - { + public void setSaveAnnotations(boolean saveAnnotations) { this.saveAnnotations.setSelected(saveAnnotations); } - public SaveTrackFilter getSelectedSaveFilter() - { + public SaveTrackFilter getSelectedSaveFilter() { FileFilter filter = this.fileChooser.getFileFilter(); return (filter != null && filter instanceof SaveTrackFilter) ? (SaveTrackFilter) filter : null; } - public int getFileFormat() - { + public int getFileFormat() { SaveTrackFilter filter = this.getSelectedSaveFilter(); return (filter != null) ? filter.getFormat() : 0; } - public void setFileFormat(int format) - { + public void setFileFormat(int format) { FileFilter ff = filterForFormat(format); - if (ff != null) + if (ff != null) { this.fileChooser.setFileFilter(ff); + } } - public void setFileFormat(SARTrack track) - { - if (track != null) - { + public void setFileFormat(SARTrack track) { + if (track != null) { FileFilter ff = filterForFormat(track.getFormat()); if (ff == null) // If the track format is invalid, default to CSV. + { ff = filterForFormat(SARTrack.FORMAT_CSV); - if (ff != null) + } + if (ff != null) { this.fileChooser.setFileFilter(ff); + } } } - public File getCurrentDirectory() - { + public File getCurrentDirectory() { return this.fileChooser.getCurrentDirectory(); } - public void setCurrentDirectory(File dir) - { + public void setCurrentDirectory(File dir) { this.fileChooser.setCurrentDirectory(dir); } - public String getDialogTitle() - { + public String getDialogTitle() { return this.fileChooser.getDialogTitle(); } - public void setDialogTitle(String dialogTitle) - { + public void setDialogTitle(String dialogTitle) { this.fileChooser.setDialogTitle(dialogTitle); } - public void setDialogTitle(SARTrack track) - { + public void setDialogTitle(SARTrack track) { String title = null; String formatString = "Save \"%s\" As"; - if (track.getName() != null) + if (track.getName() != null) { title = String.format(formatString, track.getName()); - else if (track.getFile() != null) + } else if (track.getFile() != null) { title = String.format(formatString, track.getFile().getName()); + } - if (title != null) + if (title != null) { this.fileChooser.setDialogTitle(title); + } } - public int showSaveDialog(Component parent) throws HeadlessException - { + public int showSaveDialog(Component parent) throws HeadlessException { return this.fileChooser.showSaveDialog(parent); } - public static int showSaveChangesPrompt(Component parent, String title, String message, SARTrack track) - { - if (title == null) + public static int showSaveChangesPrompt(Component parent, String title, String message, SARTrack track) { + if (title == null) { title = "Save"; + } String formatString = "Save changes to the Track\n\"%s\" before closing?"; - if (message == null) - { - if (track != null && track.getName() != null) + if (message == null) { + if (track != null && track.getName() != null) { message = String.format(formatString, track.getName()); - else if (track != null && track.getFile() != null) + } else if (track != null && track.getFile() != null) { message = String.format(formatString, track.getFile().getName()); + } } return JOptionPane.showOptionDialog( - parent, // parentComponent - message, - title, - JOptionPane.YES_NO_CANCEL_OPTION, // optionType - JOptionPane.WARNING_MESSAGE, // messageType - null, // icon - new Object[] {"Save", "Don't Save", "Cancel"}, // options - "Save"); // initialValue - } - - public static int showOverwritePrompt(Component parent, String title, String message, File file) - { - if (title == null) + parent, // parentComponent + message, + title, + JOptionPane.YES_NO_CANCEL_OPTION, // optionType + JOptionPane.WARNING_MESSAGE, // messageType + null, // icon + new Object[]{"Save", "Don't Save", "Cancel"}, // options + "Save"); // initialValue + } + + public static int showOverwritePrompt(Component parent, String title, String message, File file) { + if (title == null) { title = "Save"; + } - if (message == null) - { - if (file != null) + if (message == null) { + if (file != null) { message = String.format("Overwrite existing file\n\"%s\"?", file.getPath()); - else + } else { message = "Overwrite existing file?"; + } } return JOptionPane.showOptionDialog( - parent, // parentComponent - message, - title, - JOptionPane.YES_NO_OPTION, // optionType - JOptionPane.WARNING_MESSAGE, // messageType - null, // icon - new Object[] {"Overwrite", "Cancel"}, // options - "Overwrite"); // initialValue - } - - private void initComponents() - { - this.fileChooser = new JFileChooser() - { - public void approveSelection() - { - if (doApproveSelection()) + parent, // parentComponent + message, + title, + JOptionPane.YES_NO_OPTION, // optionType + JOptionPane.WARNING_MESSAGE, // messageType + null, // icon + new Object[]{"Overwrite", "Cancel"}, // options + "Overwrite"); // initialValue + } + + private void initComponents() { + this.fileChooser = new JFileChooser() { + public void approveSelection() { + if (doApproveSelection()) { super.approveSelection(); + } } }; this.fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); @@ -204,21 +193,19 @@ public void approveSelection() makeFileFilters(); } - private boolean doApproveSelection() - { + private boolean doApproveSelection() { File f = this.getSelectedFile(); - if (f != null && f.exists()) - { + if (f != null && f.exists()) { int state = showOverwritePrompt(this.fileChooser, null, null, f); - if (state != JOptionPane.YES_OPTION) + if (state != JOptionPane.YES_OPTION) { return false; + } } return true; } - private void makeAccessory() - { + private void makeAccessory() { Box box = Box.createVerticalBox(); box.setBorder(new EmptyBorder(0, 10, 0, 10)); @@ -235,19 +222,15 @@ private void makeAccessory() this.fileChooser.setAccessory(box); } - private void makeFileFilters() - { - FileFilter[] filters = new FileFilter[] - { - new SaveTrackFilter(SARTrack.FORMAT_CSV, "Comma Separated Value (*.csv)", new String[] {".csv"}), - new SaveTrackFilter(SARTrack.FORMAT_GPX, "GPS Exchange Format (*.xml, *.gpx)", - new String[] {".xml", ".gpx"}), - new SaveTrackFilter(SARTrack.FORMAT_NMEA, "National Marine Electronics Association (*.nmea)", - new String[] {".nmea"}), - }; - - for (FileFilter filter : filters) - { + private void makeFileFilters() { + FileFilter[] filters = new FileFilter[]{ + new SaveTrackFilter(SARTrack.FORMAT_CSV, "Comma Separated Value (*.csv)", new String[]{".csv"}), + new SaveTrackFilter(SARTrack.FORMAT_GPX, "GPS Exchange Format (*.xml, *.gpx)", + new String[]{".xml", ".gpx"}), + new SaveTrackFilter(SARTrack.FORMAT_NMEA, "National Marine Electronics Association (*.nmea)", + new String[]{".nmea"}),}; + + for (FileFilter filter : filters) { this.fileChooser.addChoosableFileFilter(filter); } @@ -255,16 +238,12 @@ private void makeFileFilters() this.fileChooser.setFileFilter(filters[0]); } - private FileFilter filterForFormat(int format) - { + private FileFilter filterForFormat(int format) { FileFilter result = null; - for (FileFilter filter : this.fileChooser.getChoosableFileFilters()) - { - if (filter instanceof SaveTrackFilter) - { - if (((SaveTrackFilter) filter).getFormat() == format) - { + for (FileFilter filter : this.fileChooser.getChoosableFileFilters()) { + if (filter instanceof SaveTrackFilter) { + if (((SaveTrackFilter) filter).getFormat() == format) { result = filter; break; } diff --git a/src/gov/nasa/worldwindx/applications/sar/ScalebarHint.java b/src/gov/nasa/worldwindx/applications/sar/ScalebarHint.java index c18f3270d8..e4928c21e9 100644 --- a/src/gov/nasa/worldwindx/applications/sar/ScalebarHint.java +++ b/src/gov/nasa/worldwindx/applications/sar/ScalebarHint.java @@ -26,8 +26,8 @@ * @author Patrick Murris * @version $Id: ScalebarHint.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScalebarHint -{ +public class ScalebarHint { + private WorldWindow wwd; private RenderableLayer layer = new RenderableLayer(); private MarkerRenderer markerRenderer = new MarkerRenderer(); @@ -35,39 +35,37 @@ public class ScalebarHint MarkerAttributes markerAttributes; private boolean enabled = true; - public ScalebarHint() - { + public ScalebarHint() { this.layer.setName("Scalebar reference"); this.layer.setEnabled(false); this.markerAttributes = new BasicMarkerAttributes(new Material(Color.YELLOW), - BasicMarkerShape.CONE, 1, 10, 5); + BasicMarkerShape.CONE, 1, 10, 5); this.marker = new RenderableMarker(Position.ZERO, this.markerAttributes); this.layer.addRenderable(this.marker); } - public void setWwd(WorldWindow worldWindow) - { + public void setWwd(WorldWindow worldWindow) { this.wwd = worldWindow; // Enable picking on the scalebar layer - for (Layer l : this.wwd.getModel().getLayers()) - if (l instanceof ScalebarLayer) + for (Layer l : this.wwd.getModel().getLayers()) { + if (l instanceof ScalebarLayer) { l.setPickEnabled(true); + } + } // Add our layer this.wwd.getModel().getLayers().add(this.layer); - + // Add scalebar select listener to handle rollover - this.wwd.addSelectListener(new SelectListener() - { - public void selected(SelectEvent event) - { - if (!enabled || event.getTopObject() == null || !(event.getTopObject() instanceof ScalebarLayer)) - { + this.wwd.addSelectListener(new SelectListener() { + public void selected(SelectEvent event) { + if (!enabled || event.getTopObject() == null || !(event.getTopObject() instanceof ScalebarLayer)) { layer.setEnabled(false); return; } - if (!event.getEventAction().equals(SelectEvent.ROLLOVER)) + if (!event.getEventAction().equals(SelectEvent.ROLLOVER)) { return; + } marker.setPosition(event.getTopPickedObject().getPosition()); layer.setEnabled(true); @@ -76,34 +74,28 @@ public void selected(SelectEvent event) }); } - public MarkerAttributes getMarkerAttributes() - { + public MarkerAttributes getMarkerAttributes() { return this.markerAttributes; } - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean state) - { + public void setEnabled(boolean state) { this.enabled = state; } - private class RenderableMarker extends BasicMarker implements Renderable - { + private class RenderableMarker extends BasicMarker implements Renderable { + private ArrayList markerList; - public RenderableMarker(Position position, MarkerAttributes attrs) - { + public RenderableMarker(Position position, MarkerAttributes attrs) { super(position, attrs); } - public void render(DrawContext dc) - { - if (this.markerList == null) - { + public void render(DrawContext dc) { + if (this.markerList == null) { this.markerList = new ArrayList(); this.markerList.add(this); } diff --git a/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java b/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java index 62a53e2397..1ea140123b 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java +++ b/src/gov/nasa/worldwindx/applications/sar/TerrainProfilePanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.sar; import gov.nasa.worldwind.*; @@ -31,8 +30,8 @@ * @version $Id: TerrainProfilePanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ @SuppressWarnings({"FieldCanBeLocal", "unchecked"}) -public class TerrainProfilePanel extends JPanel implements Restorable -{ +public class TerrainProfilePanel extends JPanel implements Restorable { + public static final String TERRAIN_PROFILE_OPEN = "TerrainProfilePanel.Open"; public static final String TERRAIN_PROFILE_CHANGE = "TerrainProfilePanel.Change"; @@ -40,51 +39,45 @@ public class TerrainProfilePanel extends JPanel implements Restorable private static final String GRAPH_SIZE_SMALL_TEXT = "Small Graph"; private static final String GRAPH_SIZE_MEDIUM_TEXT = "Medium Graph"; private static final String GRAPH_SIZE_LARGE_TEXT = "Large Graph"; - private static final String FOLLOW_VIEW_TEXT = "Profile At Screen Center"; + private static final String FOLLOW_VIEW_TEXT = "Profile At Screen Center"; private static final String FOLLOW_CURSOR_TEXT = "Profile Under Cursor"; //private static final String FOLLOW_EYE_TEXT = "Profile Under Eye"; private static final String FOLLOW_OBJECT_TEXT = "Profile Under Aircraft"; - private static final String FOLLOW_NONE_TEXT = "No Profile"; + private static final String FOLLOW_NONE_TEXT = "No Profile"; - public TerrainProfilePanel() - { + public TerrainProfilePanel() { initComponents(); this.controller = new TerrainProfileController(); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.controller.getWwd(); } - public void setWwd(WorldWindow wwd) - { + public void setWwd(WorldWindow wwd) { this.controller.setWwd(wwd); this.matchProfileToPanel(); } - private void matchProfileToPanel() - { + private void matchProfileToPanel() { this.setFollow(); this.controller.setProfileSize((String) this.sizeComboBox.getSelectedItem()); this.controller.setKeepProportions(this.proportionalCheckBox.isSelected()); this.controller.setShowEyePosition(this.showEyeCheckBox.isSelected()); this.controller.setZeroBased(this.zeroBaseCheckBox.isSelected()); this.controller.setProfileWidthFactor( - Double.parseDouble(((String)this.profileWidthSpinner.getValue()).replace("x", ""))); + Double.parseDouble(((String) this.profileWidthSpinner.getValue()).replace("x", ""))); this.controller.setProfileLengthFactor( - Double.parseDouble(((String)this.profileLengthSpinner.getValue()).replace("x", ""))); + Double.parseDouble(((String) this.profileLengthSpinner.getValue()).replace("x", ""))); } @SuppressWarnings({"UnusedDeclaration"}) - private void sizeComboBoxActionPerformed(ActionEvent e) - { + private void sizeComboBoxActionPerformed(ActionEvent e) { this.controller.setProfileSize((String) this.sizeComboBox.getSelectedItem()); } @SuppressWarnings({"UnusedDeclaration"}) - private void followComboBoxActionPerformed(ActionEvent e) - { + private void followComboBoxActionPerformed(ActionEvent e) { this.setFollow(); } @@ -92,37 +85,36 @@ private void followComboBoxActionPerformed(ActionEvent e) //{ // this.followComboBox.getModel().setSelectedItem(FOLLOW_EYE_TEXT); //}/ - - public void setFollowObject() - { + public void setFollowObject() { this.followComboBox.getModel().setSelectedItem(FOLLOW_OBJECT_TEXT); } @SuppressWarnings({"StringEquality"}) - private void setFollow() - { + private void setFollow() { this.controller.setFollow((String) this.followComboBox.getSelectedItem()); String follow = this.controller.getFollow(); - if (follow == TerrainProfileLayer.FOLLOW_VIEW) - { - if (this.showEyeCheckBox.isEnabled()) + if (follow == TerrainProfileLayer.FOLLOW_VIEW) { + if (this.showEyeCheckBox.isEnabled()) { this.showEyeCheckBox.setEnabled(false); - if (!this.profileWidthSpinner.isEnabled()) + } + if (!this.profileWidthSpinner.isEnabled()) { this.profileWidthSpinner.setEnabled(true); - if (this.profileLengthSpinner.isEnabled()) + } + if (this.profileLengthSpinner.isEnabled()) { this.profileLengthSpinner.setEnabled(false); - } - else if (follow == TerrainProfileLayer.FOLLOW_CURSOR) - { - if (this.showEyeCheckBox.isEnabled()) + } + } else if (follow == TerrainProfileLayer.FOLLOW_CURSOR) { + if (this.showEyeCheckBox.isEnabled()) { this.showEyeCheckBox.setEnabled(false); - if (!this.profileWidthSpinner.isEnabled()) + } + if (!this.profileWidthSpinner.isEnabled()) { this.profileWidthSpinner.setEnabled(true); - if (this.profileLengthSpinner.isEnabled()) + } + if (this.profileLengthSpinner.isEnabled()) { this.profileLengthSpinner.setEnabled(false); - } - //else if (follow == TerrainProfileLayer.FOLLOW_EYE) + } + } //else if (follow == TerrainProfileLayer.FOLLOW_EYE) //{ // if (!this.showEyeCheckBox.isEnabled()) // this.showEyeCheckBox.setEnabled(true); @@ -131,87 +123,82 @@ else if (follow == TerrainProfileLayer.FOLLOW_CURSOR) // if (!this.profileLengthSlider.isEnabled()) // this.profileLengthSlider.setEnabled(true); //} - else if (follow == TerrainProfileLayer.FOLLOW_OBJECT) - { - if (!this.showEyeCheckBox.isEnabled()) + else if (follow == TerrainProfileLayer.FOLLOW_OBJECT) { + if (!this.showEyeCheckBox.isEnabled()) { this.showEyeCheckBox.setEnabled(true); - if (!this.profileWidthSpinner.isEnabled()) + } + if (!this.profileWidthSpinner.isEnabled()) { this.profileWidthSpinner.setEnabled(true); - if (!this.profileLengthSpinner.isEnabled()) + } + if (!this.profileLengthSpinner.isEnabled()) { this.profileLengthSpinner.setEnabled(true); - } - else if (follow == TerrainProfileLayer.FOLLOW_NONE) - { - if (this.showEyeCheckBox.isEnabled()) + } + } else if (follow == TerrainProfileLayer.FOLLOW_NONE) { + if (this.showEyeCheckBox.isEnabled()) { this.showEyeCheckBox.setEnabled(false); - if (this.profileWidthSpinner.isEnabled()) + } + if (this.profileWidthSpinner.isEnabled()) { this.profileWidthSpinner.setEnabled(false); - if (this.profileLengthSpinner.isEnabled()) + } + if (this.profileLengthSpinner.isEnabled()) { this.profileLengthSpinner.setEnabled(false); + } } } - private void proportionalCheckBoxItemStateChanged(ItemEvent e) - { + private void proportionalCheckBoxItemStateChanged(ItemEvent e) { this.controller.setKeepProportions(((JCheckBox) e.getSource()).isSelected()); } - private void showEyeCheckBoxItemStateChanged(ItemEvent e) - { + private void showEyeCheckBoxItemStateChanged(ItemEvent e) { this.controller.setShowEyePosition(((JCheckBox) e.getSource()).isSelected()); } - private void zeroBaseCheckBoxItemStateChanged(ItemEvent e) - { + private void zeroBaseCheckBoxItemStateChanged(ItemEvent e) { this.controller.setZeroBased(((JCheckBox) e.getSource()).isSelected()); } - private void profileWidthSpinnerStateChanged(ChangeEvent e) - { - String value = (String)((JSpinner) e.getSource()).getValue(); + private void profileWidthSpinnerStateChanged(ChangeEvent e) { + String value = (String) ((JSpinner) e.getSource()).getValue(); value = value.replace("x", ""); this.controller.setProfileWidthFactor(Double.parseDouble(value)); - if (this.profilesSameSize.isSelected()) + if (this.profilesSameSize.isSelected()) { this.profileLengthSpinner.setValue(this.profileWidthSpinner.getValue()); + } } - private void profileLengthSpinnerStateChanged(ChangeEvent e) - { - String value = (String)((JSpinner) e.getSource()).getValue(); + private void profileLengthSpinnerStateChanged(ChangeEvent e) { + String value = (String) ((JSpinner) e.getSource()).getValue(); value = value.replace("x", ""); this.controller.setProfileLengthFactor(Double.parseDouble(value)); - if (this.profilesSameSize.isSelected()) + if (this.profilesSameSize.isSelected()) { this.profileWidthSpinner.setValue(this.profileLengthSpinner.getValue()); + } } - public void profilesSameSizeStateChanged(ChangeEvent e) - { - if (((JCheckBox)e.getSource()).isSelected()) + public void profilesSameSizeStateChanged(ChangeEvent e) { + if (((JCheckBox) e.getSource()).isSelected()) { this.profileLengthSpinner.setValue(this.profileWidthSpinner.getValue()); + } } - public void profileFollowPathStateChanged(ChangeEvent e) - { - this.controller.setWholeTrackLength(((JCheckBox)e.getSource()).isSelected()); + public void profileFollowPathStateChanged(ChangeEvent e) { + this.controller.setWholeTrackLength(((JCheckBox) e.getSource()).isSelected()); } - public void updatePosition(Position position, Angle heading) - { + public void updatePosition(Position position, Angle heading) { this.controller.updatePosition(position, heading); } - public void updatePath(ArrayList positions) - { + public void updatePath(ArrayList positions) { this.controller.updatePath(positions); } - public String getFollow() - { + public String getFollow() { return this.controller.getFollow(); } - private void initComponents() - { + private void initComponents() { this.panel1 = new JPanel(); this.panel2 = new JPanel(); this.panel6 = new JPanel(); @@ -241,109 +228,109 @@ private void initComponents() //======== panel1 ======== { - this.panel1.setLayout(new BorderLayout(20, 20)); - - //======== panel2 ======== - { - this.panel2.setLayout(new GridLayout(1, 2, 20, 10)); - - //======== panel6 ======== - { - this.panel6.setLayout(new GridLayout(1, 2, 20, 10)); - - //======== panel5 ======== - { - this.panel5.setLayout(new BorderLayout(5, 5)); - - //---- sizeComboBox ---- - this.sizeComboBox.setModel(new DefaultComboBoxModel(new String[] { - GRAPH_SIZE_SMALL_TEXT, - GRAPH_SIZE_MEDIUM_TEXT, - GRAPH_SIZE_LARGE_TEXT - })); - this.sizeComboBox.setToolTipText("Size of profile graph"); - this.sizeComboBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - sizeComboBoxActionPerformed(e); - } - }); - this.panel5.add(this.sizeComboBox, BorderLayout.CENTER); - } - this.panel6.add(this.panel5); - - //======== panel7 ======== - { - this.panel7.setLayout(new BorderLayout(5, 5)); - - //---- followComboBox ---- - this.followComboBox.setModel(new DefaultComboBoxModel(new String[] { - FOLLOW_VIEW_TEXT, - FOLLOW_CURSOR_TEXT, - //FOLLOW_EYE_TEXT, - FOLLOW_OBJECT_TEXT, + this.panel1.setLayout(new BorderLayout(20, 20)); + + //======== panel2 ======== + { + this.panel2.setLayout(new GridLayout(1, 2, 20, 10)); + + //======== panel6 ======== + { + this.panel6.setLayout(new GridLayout(1, 2, 20, 10)); + + //======== panel5 ======== + { + this.panel5.setLayout(new BorderLayout(5, 5)); + + //---- sizeComboBox ---- + this.sizeComboBox.setModel(new DefaultComboBoxModel(new String[]{ + GRAPH_SIZE_SMALL_TEXT, + GRAPH_SIZE_MEDIUM_TEXT, + GRAPH_SIZE_LARGE_TEXT + })); + this.sizeComboBox.setToolTipText("Size of profile graph"); + this.sizeComboBox.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + sizeComboBoxActionPerformed(e); + } + }); + this.panel5.add(this.sizeComboBox, BorderLayout.CENTER); + } + this.panel6.add(this.panel5); + + //======== panel7 ======== + { + this.panel7.setLayout(new BorderLayout(5, 5)); + + //---- followComboBox ---- + this.followComboBox.setModel(new DefaultComboBoxModel(new String[]{ + FOLLOW_VIEW_TEXT, + FOLLOW_CURSOR_TEXT, + //FOLLOW_EYE_TEXT, + FOLLOW_OBJECT_TEXT, FOLLOW_NONE_TEXT })); - this.followComboBox.setToolTipText("Set profile behavior"); - this.followComboBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - followComboBoxActionPerformed(e); - } - }); - this.panel7.add(this.followComboBox, BorderLayout.CENTER); - } - this.panel6.add(this.panel7); - } - this.panel2.add(this.panel6); - } - this.panel1.add(this.panel2, BorderLayout.NORTH); - - //======== panel3 ======== - { - this.panel3.setLayout(new GridLayout(1, 3, 10, 10)); - - //---- proportionalCheckBox ---- - this.proportionalCheckBox.setText("Proportional"); - this.proportionalCheckBox.setToolTipText("Maintain 1:1 profile dimensions"); - this.proportionalCheckBox.setAlignmentX(0.5F); - this.proportionalCheckBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - proportionalCheckBoxItemStateChanged(e); - } - }); - this.panel3.add(this.proportionalCheckBox); - - //---- showEyeCheckBox ---- - this.showEyeCheckBox.setText("Show A/C Position"); - this.showEyeCheckBox.setToolTipText("Show aircraft position in profile graph"); - this.showEyeCheckBox.setAlignmentX(0.5F); - this.showEyeCheckBox.setHorizontalAlignment(SwingConstants.CENTER); - this.showEyeCheckBox.setSelected(true); - this.showEyeCheckBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - showEyeCheckBoxItemStateChanged(e); - } - }); - this.panel3.add(this.showEyeCheckBox); - - //---- zeroBaseCheckBox ---- - this.zeroBaseCheckBox.setText("MSL Base"); - this.zeroBaseCheckBox.setToolTipText("Show mean sea level in profile graph"); - this.zeroBaseCheckBox.setAlignmentX(0.5F); - this.zeroBaseCheckBox.setHorizontalAlignment(SwingConstants.TRAILING); - this.zeroBaseCheckBox.setSelected(true); - this.zeroBaseCheckBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - zeroBaseCheckBoxItemStateChanged(e); - } - }); - this.panel3.add(this.zeroBaseCheckBox); - } - this.panel1.add(this.panel3, BorderLayout.CENTER); + this.followComboBox.setToolTipText("Set profile behavior"); + this.followComboBox.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + followComboBoxActionPerformed(e); + } + }); + this.panel7.add(this.followComboBox, BorderLayout.CENTER); + } + this.panel6.add(this.panel7); + } + this.panel2.add(this.panel6); + } + this.panel1.add(this.panel2, BorderLayout.NORTH); + + //======== panel3 ======== + { + this.panel3.setLayout(new GridLayout(1, 3, 10, 10)); + + //---- proportionalCheckBox ---- + this.proportionalCheckBox.setText("Proportional"); + this.proportionalCheckBox.setToolTipText("Maintain 1:1 profile dimensions"); + this.proportionalCheckBox.setAlignmentX(0.5F); + this.proportionalCheckBox.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + proportionalCheckBoxItemStateChanged(e); + } + }); + this.panel3.add(this.proportionalCheckBox); + + //---- showEyeCheckBox ---- + this.showEyeCheckBox.setText("Show A/C Position"); + this.showEyeCheckBox.setToolTipText("Show aircraft position in profile graph"); + this.showEyeCheckBox.setAlignmentX(0.5F); + this.showEyeCheckBox.setHorizontalAlignment(SwingConstants.CENTER); + this.showEyeCheckBox.setSelected(true); + this.showEyeCheckBox.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + showEyeCheckBoxItemStateChanged(e); + } + }); + this.panel3.add(this.showEyeCheckBox); + + //---- zeroBaseCheckBox ---- + this.zeroBaseCheckBox.setText("MSL Base"); + this.zeroBaseCheckBox.setToolTipText("Show mean sea level in profile graph"); + this.zeroBaseCheckBox.setAlignmentX(0.5F); + this.zeroBaseCheckBox.setHorizontalAlignment(SwingConstants.TRAILING); + this.zeroBaseCheckBox.setSelected(true); + this.zeroBaseCheckBox.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + zeroBaseCheckBoxItemStateChanged(e); + } + }); + this.panel3.add(this.zeroBaseCheckBox); + } + this.panel1.add(this.panel3, BorderLayout.CENTER); //======== panel8 ======== { this.panel8.setLayout(new GridLayout(2, 2, 20, 10)); - String[] profileSizeValues = new String[] {"x1", "x2", "x3", "x4", "x5", "x7", "x10"}; + String[] profileSizeValues = new String[]{"x1", "x2", "x3", "x4", "x5", "x7", "x10"}; //======== panel4 ======== { @@ -454,17 +441,15 @@ public void stateChanged(ChangeEvent e) { private JPanel panel4d; private JCheckBox profileFollowPath; - private static class TerrainProfileController - { + private static class TerrainProfileController { + private static final HashMap sizes = new HashMap(); - public static String[] getSizeKeys() - { + public static String[] getSizeKeys() { return sizes.keySet().toArray(new String[1]); } - static - { + static { sizes.put(GRAPH_SIZE_SMALL_TEXT, new Dimension(250, 100)); sizes.put(GRAPH_SIZE_MEDIUM_TEXT, new Dimension(450, 140)); sizes.put(GRAPH_SIZE_LARGE_TEXT, new Dimension(655, 240)); @@ -472,13 +457,11 @@ public static String[] getSizeKeys() private static final HashMap follows = new HashMap(); - public static String[] getFollowKeys() - { + public static String[] getFollowKeys() { return follows.keySet().toArray(new String[1]); } - static - { + static { follows.put(FOLLOW_VIEW_TEXT, TerrainProfileLayer.FOLLOW_VIEW); follows.put(FOLLOW_CURSOR_TEXT, TerrainProfileLayer.FOLLOW_CURSOR); //follows.put(FOLLOW_EYE_TEXT, TerrainProfileLayer.FOLLOW_EYE); @@ -491,8 +474,7 @@ public static String[] getFollowKeys() private TerrainProfileLayer tpl2; // Parallel to the track private boolean wholeTrackLength = false; - public TerrainProfileController() - { + public TerrainProfileController() { this.tpl = new TerrainProfileLayer(); this.tpl.setZeroBased(true); this.tpl2 = new TerrainProfileLayer(); @@ -500,143 +482,125 @@ public TerrainProfileController() this.tpl2.setPosition(AVKey.SOUTHEAST); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return wwd; } - public void setWwd(WorldWindow wwd) - { + public void setWwd(WorldWindow wwd) { this.wwd = wwd; - if (this.wwd != null) - { + if (this.wwd != null) { ApplicationTemplate.insertBeforeCompass(wwd, tpl); this.tpl.setEventSource(wwd); ApplicationTemplate.insertBeforeCompass(wwd, tpl2); this.tpl2.setEventSource(wwd); this.tpl2.setPathType(Polyline.RHUMB_LINE); // Move scalebar to north west - for (Layer layer : wwd.getModel().getLayers()) - if (layer instanceof ScalebarLayer) - ((ScalebarLayer)layer).setPosition(AVKey.NORTHWEST); + for (Layer layer : wwd.getModel().getLayers()) { + if (layer instanceof ScalebarLayer) { + ((ScalebarLayer) layer).setPosition(AVKey.NORTHWEST); + } + } update(); } } - private void update() - { - if (this.wwd != null) + private void update() { + if (this.wwd != null) { this.wwd.redraw(); + } } - public void setShowEyePosition(boolean showEye) - { + public void setShowEyePosition(boolean showEye) { this.tpl.setShowEyePosition(showEye); this.tpl2.setShowEyePosition(showEye); this.update(); } - public boolean getShowEyePosition() - { + public boolean getShowEyePosition() { return this.tpl.getShowEyePosition(); } - public void setZeroBased(boolean keepProportions) - { + public void setZeroBased(boolean keepProportions) { this.tpl.setZeroBased(keepProportions); this.tpl2.setZeroBased(keepProportions); this.update(); } - public boolean getShowZeroBased() - { + public boolean getShowZeroBased() { return this.tpl.getZeroBased(); } - public void setKeepProportions(boolean keepProportions) - { + public void setKeepProportions(boolean keepProportions) { this.tpl.setKeepProportions(keepProportions); this.tpl2.setKeepProportions(keepProportions); this.update(); } - public boolean getKeepProportions() - { + public boolean getKeepProportions() { return this.tpl.getKeepProportions(); } - public void setProfileSize(String size) - { + public void setProfileSize(String size) { Dimension dim = sizes.get(size); - if (dim != null) - { + if (dim != null) { this.tpl.setSize(dim); this.tpl2.setSize(dim); this.update(); } } - public Dimension getProfileSize() - { + public Dimension getProfileSize() { return this.tpl.getSize(); } - public void setFollow(String followName) - { + public void setFollow(String followName) { String follow = follows.get(followName); - if (follow != null) - { + if (follow != null) { this.tpl.setFollow(follow); - if (follow.equals(TerrainProfileLayer.FOLLOW_OBJECT) || follow.equals(TerrainProfileLayer.FOLLOW_EYE)) + if (follow.equals(TerrainProfileLayer.FOLLOW_OBJECT) || follow.equals(TerrainProfileLayer.FOLLOW_EYE)) { this.tpl2.setFollow( - this.wholeTrackLength ? TerrainProfileLayer.FOLLOW_PATH : TerrainProfileLayer.FOLLOW_OBJECT); - else + this.wholeTrackLength ? TerrainProfileLayer.FOLLOW_PATH : TerrainProfileLayer.FOLLOW_OBJECT); + } else { this.tpl2.setFollow(TerrainProfileLayer.FOLLOW_NONE); + } this.update(); } } - public String getFollow() - { + public String getFollow() { return this.tpl.getFollow(); } - public void setWholeTrackLength(boolean state) - { - if (this.wholeTrackLength != state) - { + public void setWholeTrackLength(boolean state) { + if (this.wholeTrackLength != state) { this.wholeTrackLength = state; - if (!this.tpl2.getFollow().equals(TerrainProfileLayer.FOLLOW_NONE)) + if (!this.tpl2.getFollow().equals(TerrainProfileLayer.FOLLOW_NONE)) { this.tpl2.setFollow( - this.wholeTrackLength ? TerrainProfileLayer.FOLLOW_PATH : TerrainProfileLayer.FOLLOW_OBJECT); + this.wholeTrackLength ? TerrainProfileLayer.FOLLOW_PATH : TerrainProfileLayer.FOLLOW_OBJECT); + } this.update(); } } - public void setProfileWidthFactor(double factor) - { + public void setProfileWidthFactor(double factor) { this.tpl.setProfileLengthFactor(factor); // perpendicular profile this.update(); } - public void setProfileLengthFactor(double factor) - { + public void setProfileLengthFactor(double factor) { this.tpl2.setProfileLengthFactor(factor); // along track rofile this.update(); } - public double getProfileWidthFactor() - { + public double getProfileWidthFactor() { return this.tpl.getProfileLenghtFactor(); } - public double getProfileLengthFactor() - { + public double getProfileLengthFactor() { return this.tpl2.getProfileLenghtFactor(); } - public void updatePosition(Position position, Angle heading) - { + public void updatePosition(Position position, Angle heading) { this.tpl.setObjectPosition(position); this.tpl.setObjectHeading(heading); this.tpl2.setObjectPosition(position); @@ -644,39 +608,31 @@ public void updatePosition(Position position, Angle heading) this.update(); } - public void updatePath(ArrayList positions) - { + public void updatePath(ArrayList positions) { this.tpl2.setPathPositions(positions); this.update(); } } // *** Restorable interface *** - - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -686,58 +642,65 @@ public void restoreState(String stateInXml) this.doRestoreState(rs, null); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { // Add state values - rs.addStateValueAsString(context, "size", (String)this.sizeComboBox.getSelectedItem()); - rs.addStateValueAsString(context, "follow", (String)this.followComboBox.getSelectedItem()); + rs.addStateValueAsString(context, "size", (String) this.sizeComboBox.getSelectedItem()); + rs.addStateValueAsString(context, "follow", (String) this.followComboBox.getSelectedItem()); rs.addStateValueAsBoolean(context, "proportional", this.proportionalCheckBox.isSelected()); rs.addStateValueAsBoolean(context, "zeroBase", this.zeroBaseCheckBox.isSelected()); rs.addStateValueAsBoolean(context, "showEye", this.showEyeCheckBox.isSelected()); - rs.addStateValueAsString(context, "width", (String)this.profileWidthSpinner.getValue()); - rs.addStateValueAsString(context, "length", (String)this.profileLengthSpinner.getValue()); + rs.addStateValueAsString(context, "width", (String) this.profileWidthSpinner.getValue()); + rs.addStateValueAsString(context, "length", (String) this.profileLengthSpinner.getValue()); rs.addStateValueAsBoolean(context, "sameSize", this.profilesSameSize.isSelected()); rs.addStateValueAsBoolean(context, "followPath", this.profileFollowPath.isSelected()); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Retrieve state values String sizeState = rs.getStateValueAsString(context, "size"); - if (sizeState != null) + if (sizeState != null) { this.sizeComboBox.setSelectedItem(sizeState); + } String followState = rs.getStateValueAsString(context, "follow"); - if (followState != null) + if (followState != null) { this.followComboBox.setSelectedItem(followState); + } Boolean proportionalState = rs.getStateValueAsBoolean(context, "proportional"); - if (proportionalState != null) + if (proportionalState != null) { this.proportionalCheckBox.setSelected(proportionalState); + } Boolean zeroBaseState = rs.getStateValueAsBoolean(context, "zeroBase"); - if (zeroBaseState != null) + if (zeroBaseState != null) { this.zeroBaseCheckBox.setSelected(zeroBaseState); + } Boolean showEyeState = rs.getStateValueAsBoolean(context, "showEye"); - if (showEyeState != null) + if (showEyeState != null) { this.showEyeCheckBox.setSelected(showEyeState); + } String widthState = rs.getStateValueAsString(context, "width"); - if (widthState != null) + if (widthState != null) { this.profileWidthSpinner.setValue(widthState); + } String lengthState = rs.getStateValueAsString(context, "length"); - if (lengthState != null) + if (lengthState != null) { this.profileLengthSpinner.setValue(lengthState); + } Boolean sameSizeState = rs.getStateValueAsBoolean(context, "sameSize"); - if (sameSizeState != null) + if (sameSizeState != null) { this.profilesSameSize.setSelected(sameSizeState); + } Boolean followPathState = rs.getStateValueAsBoolean(context, "followPath"); - if (followPathState != null) + if (followPathState != null) { this.profileFollowPath.setSelected(followPathState); + } } } diff --git a/src/gov/nasa/worldwindx/applications/sar/TrackController.java b/src/gov/nasa/worldwindx/applications/sar/TrackController.java index b95bf66396..ca6221e2ba 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TrackController.java +++ b/src/gov/nasa/worldwindx/applications/sar/TrackController.java @@ -22,8 +22,8 @@ * @author tag * @version $Id: TrackController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TrackController -{ +public class TrackController { + public static final String TRACK_ADD = "TrackController.TrackAdded"; public static final String TRACK_CURRENT = "TrackController.TrackCurrent"; public static final String TRACK_DIRTY_BIT = "TrackController.TrackDirtyBit"; @@ -50,100 +50,94 @@ public class TrackController private SARTrackBuilder trackBuilder; private SARTrackExtensionTool trackExtensionTool; - private final SelectListener selectListener = new SelectListener() - { - public void selected(SelectEvent event) - { - if (event == null) + private final SelectListener selectListener = new SelectListener() { + public void selected(SelectEvent event) { + if (event == null) { return; + } onSelected(event); } }; - public TrackController() - { + public TrackController() { this.trackBuilder = new SARTrackBuilder(); this.trackExtensionTool = new SARTrackExtensionTool(); } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return wwd; } - public void setWwd(WorldWindow wwd) - { - if (wwd == this.wwd) + public void setWwd(WorldWindow wwd) { + if (wwd == this.wwd) { return; + } - if (this.wwd != null) + if (this.wwd != null) { this.wwd.removeSelectListener(this.selectListener); + } this.wwd = wwd; - if (this.wwd != null) + if (this.wwd != null) { this.wwd.addSelectListener(this.selectListener); + } this.trackBuilder.setWwd(this.wwd); this.trackExtensionTool.setWorldWindow(this.wwd); } - public TracksPanel getTracksPanel() - { + public TracksPanel getTracksPanel() { return tracksPanel; } - public void setTracksPanel(TracksPanel tracksPanel) - { + public void setTracksPanel(TracksPanel tracksPanel) { this.tracksPanel = tracksPanel; } - public AnalysisPanel getAnalysisPanel() - { + public AnalysisPanel getAnalysisPanel() { return analysisPanel; } - public void setAnalysisPanel(AnalysisPanel analysisPanel) - { + public void setAnalysisPanel(AnalysisPanel analysisPanel) { this.analysisPanel = analysisPanel; this.analysisPanel.setTrackController(this); } - public void addTrack(SARTrack track) - { - if (track == null) + public void addTrack(SARTrack track) { + if (track == null) { return; + } this.createPolylineTrackRepresentation(track); - track.addPropertyChangeListener(new PropertyChangeListener() - { + track.addPropertyChangeListener(new PropertyChangeListener() { @SuppressWarnings({"StringEquality"}) - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_REMOVE) + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_REMOVE) { removeTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_MODIFY) + } else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_MODIFY) { updateTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_ENABLE) + } else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_ENABLE) { enableTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_DISABLE) + } else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_DISABLE) { disableTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_CURRENT) + } else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_CURRENT) { trackCurrent((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_NAME) + } else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_NAME) { trackName((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_DIRTY_BIT) + } else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_DIRTY_BIT) { trackDirtyBit((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.BEGIN_TRACK_POINT_ENTRY) + } else if (propertyChangeEvent.getPropertyName() == TrackController.BEGIN_TRACK_POINT_ENTRY) { beginTrackPointEntry(propertyChangeEvent); - else if (propertyChangeEvent.getPropertyName() == TrackController.END_TRACK_POINT_ENTRY) + } else if (propertyChangeEvent.getPropertyName() == TrackController.END_TRACK_POINT_ENTRY) { endTrackPointEntry(propertyChangeEvent); - else if (propertyChangeEvent.getPropertyName() == TrackController.MOVE_TO_NEXT_POINT) + } else if (propertyChangeEvent.getPropertyName() == TrackController.MOVE_TO_NEXT_POINT) { moveToNextTrackPoint(); - else if (propertyChangeEvent.getPropertyName() == TrackController.REMOVE_LAST_POINT) + } else if (propertyChangeEvent.getPropertyName() == TrackController.REMOVE_LAST_POINT) { removeLastTrackPoint(); + } } }); @@ -151,18 +145,15 @@ else if (propertyChangeEvent.getPropertyName() == TrackController.REMOVE_LAST_PO this.moveToTrack(track); } - public SARTrack getCurrentTrack() - { + public SARTrack getCurrentTrack() { return this.tracksPanel.getCurrentTrack(); } - public void refreshCurrentTrack() - { + public void refreshCurrentTrack() { trackCurrent(getCurrentTrack()); } - private void createPolylineTrackRepresentation(SARTrack track) - { + private void createPolylineTrackRepresentation(SARTrack track) { Polyline airPath = new Polyline(track); airPath.setOffset(track.getOffset()); airPath.setPathType(Polyline.RHUMB_LINE); @@ -179,76 +170,77 @@ private void createPolylineTrackRepresentation(SARTrack track) layer.addRenderable(airPath); layer.addRenderable(groundPath); this.wwd.getModel().getLayers().add(layer); - if (this.wwd != null) + if (this.wwd != null) { this.wwd.redraw(); + } this.trackLayers.put(track, layer); } - private void removeTrack(SARTrack track) - { + private void removeTrack(SARTrack track) { Layer layer = this.trackLayers.get(track); - if (layer == null) + if (layer == null) { return; + } this.trackLayers.remove(track); this.wwd.getModel().getLayers().remove(layer); - if (this.wwd != null) + if (this.wwd != null) { this.wwd.redraw(); + } } - private void enableTrack(SARTrack track) - { + private void enableTrack(SARTrack track) { RenderableLayer layer = (RenderableLayer) this.trackLayers.get(track); - if (layer == null) + if (layer == null) { return; + } layer.setEnabled(true); - if (this.wwd != null) + if (this.wwd != null) { this.wwd.redraw(); + } } - private void disableTrack(SARTrack track) - { + private void disableTrack(SARTrack track) { RenderableLayer layer = (RenderableLayer) this.trackLayers.get(track); - if (layer == null) + if (layer == null) { return; + } layer.setEnabled(false); - if (this.wwd != null) + if (this.wwd != null) { this.wwd.redraw(); + } } - private void updateTrack(SARTrack track) - { + private void updateTrack(SARTrack track) { RenderableLayer layer = (RenderableLayer) this.trackLayers.get(track); - if (layer == null) + if (layer == null) { return; + } - for (Renderable r : layer.getRenderables()) - { + for (Renderable r : layer.getRenderables()) { Polyline line = (Polyline) r; line.setPositions(track); - if (!line.isFollowTerrain()) + if (!line.isFollowTerrain()) { line.setOffset(track.getOffset()); + } } - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.redraw(); } } - private void trackCurrent(SARTrack track) - { + private void trackCurrent(SARTrack track) { this.analysisPanel.setCurrentTrack(track); - if (this.isExtending() && track != null) + if (this.isExtending() && track != null) { endTrackPointEntry(new PropertyChangeEvent(track, END_TRACK_POINT_ENTRY, null, null)); + } // Adjust track line width - for (SARTrack st : this.trackLayers.keySet()) - { - if (st != track) - { + for (SARTrack st : this.trackLayers.keySet()) { + if (st != track) { this.setTrackLayerLineWidth(st, 1); } } @@ -258,30 +250,24 @@ private void trackCurrent(SARTrack track) } @SuppressWarnings({"UnusedDeclaration"}) - private void trackName(SARTrack track) - { + private void trackName(SARTrack track) { // Intentionally left blank, as a placeholder for future functionality. } @SuppressWarnings({"UnusedDeclaration"}) - private void trackDirtyBit(SARTrack track) - { + private void trackDirtyBit(SARTrack track) { // Intentionally left blank, as a placeholder for future functionality. } - private void beginTrackPointEntry(PropertyChangeEvent event) - { + private void beginTrackPointEntry(PropertyChangeEvent event) { SARTrack track = (SARTrack) event.getSource(); - if (event.getNewValue().equals(EXTENSION_PLANE)) - { + if (event.getNewValue().equals(EXTENSION_PLANE)) { this.trackExtensionTool.setArmed(false); this.trackExtensionTool.setTrack(track); this.trackExtensionTool.setArmed(true); - } - else - { + } else { this.trackBuilder.setArmed(false); this.trackBuilder.setTrack(track); @@ -295,8 +281,7 @@ private void beginTrackPointEntry(PropertyChangeEvent event) this.analysisPanel.gotoTrackEnd(); } - private void endTrackPointEntry(PropertyChangeEvent event) - { + private void endTrackPointEntry(PropertyChangeEvent event) { this.trackBuilder.setArmed(false); this.trackExtensionTool.setArmed(false); @@ -304,133 +289,119 @@ private void endTrackPointEntry(PropertyChangeEvent event) this.wwd.firePropertyChange(event); } - private void moveToNextTrackPoint() - { - if (this.trackExtensionTool.isArmed() && this.trackExtensionTool.canMoveToNextTrackPoint()) + private void moveToNextTrackPoint() { + if (this.trackExtensionTool.isArmed() && this.trackExtensionTool.canMoveToNextTrackPoint()) { this.trackExtensionTool.moveToNextTrackPoint(); + } } - private void removeLastTrackPoint() - { - if (this.trackBuilder.isArmed() && this.trackBuilder.canRemoveLastTrackPoint()) + private void removeLastTrackPoint() { + if (this.trackBuilder.isArmed() && this.trackBuilder.canRemoveLastTrackPoint()) { this.trackBuilder.removeLastTrackPoint(); - else if (this.trackExtensionTool.isArmed() && this.trackExtensionTool.canRemoveLastTrackPoint()) + } else if (this.trackExtensionTool.isArmed() && this.trackExtensionTool.canRemoveLastTrackPoint()) { this.trackExtensionTool.removeLastTrackPoint(); + } } - public boolean isExtending() - { + public boolean isExtending() { return this.trackBuilder.isArmed() || this.trackExtensionTool.isArmed(); } //move to the first position in a track - private void moveToTrack(SARTrack track) - { + private void moveToTrack(SARTrack track) { OrbitView view = (OrbitView) this.wwd.getView(); - if (!track.getPositions().isEmpty()) - { + if (!track.getPositions().isEmpty()) { Position pos = track.getPositions().get(0); ((BasicOrbitView) view).addPanToAnimator(pos, view.getHeading(), Angle.ZERO, 10000, true); } } - protected void onSelected(SelectEvent event) - { + protected void onSelected(SelectEvent event) { SARTrack track = this.getPickedTrack(event.getTopPickedObject()); - if (event.getEventAction().equals(SelectEvent.LEFT_CLICK)) - { - if (track != null) + if (event.getEventAction().equals(SelectEvent.LEFT_CLICK)) { + if (track != null) { this.onTrackClicked(track); - } - else if (event.getEventAction().equals(SelectEvent.ROLLOVER)) - { + } + } else if (event.getEventAction().equals(SelectEvent.ROLLOVER)) { this.onTrackRollover(track); - } - else if (event.getEventAction().equals(SelectEvent.HOVER)) - { + } else if (event.getEventAction().equals(SelectEvent.HOVER)) { this.onTrackHover(track); } } - protected SARTrack getPickedTrack(PickedObject pickedObject) - { - if (pickedObject == null) + protected SARTrack getPickedTrack(PickedObject pickedObject) { + if (pickedObject == null) { return null; + } Layer layer = pickedObject.getParentLayer(); - if (layer == null) + if (layer == null) { return null; + } return this.getTrackForLayer(layer); } - protected void onTrackClicked(SARTrack track) - { + protected void onTrackClicked(SARTrack track) { this.tracksPanel.setCurrentTrack(track); } - protected void onTrackRollover(SARTrack track) - { - for (SARTrack st : this.trackLayers.keySet()) - { - if (st != track) - { + protected void onTrackRollover(SARTrack track) { + for (SARTrack st : this.trackLayers.keySet()) { + if (st != track) { this.setTrackLayerColor(st, st.getColor()); } } - if (track != null) - { + if (track != null) { Color rolloverColor = WWUtil.makeColorDarker(track.getColor()); this.setTrackLayerColor(track, rolloverColor); } } - protected void onTrackHover(SARTrack track) - { + protected void onTrackHover(SARTrack track) { // TODO: show tool tip with track name } - private void setTrackLayerColor(SARTrack track, Color color) - { + private void setTrackLayerColor(SARTrack track, Color color) { RenderableLayer layer = (RenderableLayer) this.trackLayers.get(track); - if (layer == null) + if (layer == null) { return; + } - for (Renderable r : layer.getRenderables()) - { + for (Renderable r : layer.getRenderables()) { Polyline line = (Polyline) r; line.setColor(color); } - if (this.wwd != null) + if (this.wwd != null) { this.wwd.redraw(); + } } - private void setTrackLayerLineWidth(SARTrack track, double width) - { + private void setTrackLayerLineWidth(SARTrack track, double width) { RenderableLayer layer = (RenderableLayer) this.trackLayers.get(track); - if (layer == null) + if (layer == null) { return; + } - for (Renderable r : layer.getRenderables()) - { + for (Renderable r : layer.getRenderables()) { Polyline line = (Polyline) r; line.setLineWidth(width); } - if (this.wwd != null) + if (this.wwd != null) { this.wwd.redraw(); + } } - private SARTrack getTrackForLayer(Layer layer) - { - for (Map.Entry entry : this.trackLayers.entrySet()) - { - if (entry.getValue() == layer) + private SARTrack getTrackForLayer(Layer layer) { + for (Map.Entry entry : this.trackLayers.entrySet()) { + if (entry.getValue() == layer) { return entry.getKey(); + } } return null; diff --git a/src/gov/nasa/worldwindx/applications/sar/TrackPanel.java b/src/gov/nasa/worldwindx/applications/sar/TrackPanel.java index b723768397..1a6d601a62 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TrackPanel.java +++ b/src/gov/nasa/worldwindx/applications/sar/TrackPanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.sar; import gov.nasa.worldwind.util.*; @@ -17,11 +16,11 @@ * @author tag * @version $Id: TrackPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TrackPanel extends JPanel -{ +public class TrackPanel extends JPanel { + private String elevationUnit; private String angleFormat; - + private JCheckBox visibilityFlag; private JScrollPane scrollPane; private PositionTable positionTable; @@ -30,8 +29,7 @@ public class TrackPanel extends JPanel private JSpinner offsetSpinner; private JLabel offsetUnitLabel; - public TrackPanel() - { + public TrackPanel() { this.initComponents(); this.layoutComponents(); @@ -39,23 +37,19 @@ public TrackPanel() this.positionTable.addMouseListener(new PositionsContextMenu(this.positionTable)); } - public void setTrack(SARTrack sarTrack) - { + public void setTrack(SARTrack sarTrack) { this.positionTable.setSarTrack(sarTrack); } - public SARTrack getTrack() - { + public SARTrack getTrack() { return this.positionTable.getSarTrack(); } - public String getElevationUnit() - { + public String getElevationUnit() { return this.elevationUnit; } - public void setElevationUnit(String unit) - { + public void setElevationUnit(String unit) { String oldValue = this.elevationUnit; this.elevationUnit = unit; @@ -64,100 +58,89 @@ public void setElevationUnit(String unit) this.changeOffsetUnit(oldValue, this.elevationUnit); } - public String getAngleFormat() - { + public String getAngleFormat() { return this.angleFormat; } - public void setAngleFormat(String format) - { + public void setAngleFormat(String format) { this.angleFormat = format; this.positionTable.setAngleFormat(format); this.positionTable.updateTableData(); } @SuppressWarnings({"UnusedDeclaration"}) - private void visibilityActionPerformed(ActionEvent e) - { + private void visibilityActionPerformed(ActionEvent e) { String vis = this.visibilityFlag.isSelected() ? TrackController.TRACK_ENABLE : TrackController.TRACK_DISABLE; this.positionTable.getSarTrack().firePropertyChange(vis, null, this.positionTable.getSarTrack()); } @SuppressWarnings({"UnusedDeclaration"}) - private void nextTrackPositionActionPerformed(ActionEvent e) - { - this.positionTable.getSarTrack().firePropertyChange(TrackController.MOVE_TO_NEXT_POINT, null, - this.positionTable.getSarTrack()); + private void nextTrackPositionActionPerformed(ActionEvent e) { + this.positionTable.getSarTrack().firePropertyChange(TrackController.MOVE_TO_NEXT_POINT, null, + this.positionTable.getSarTrack()); } @SuppressWarnings({"UnusedDeclaration"}) - private void removeTrackPositionActionPerformed(ActionEvent e) - { + private void removeTrackPositionActionPerformed(ActionEvent e) { this.positionTable.getSarTrack().firePropertyChange(TrackController.REMOVE_LAST_POINT, null, - this.positionTable.getSarTrack()); + this.positionTable.getSarTrack()); } // Track offset control - @SuppressWarnings({"UnusedDeclaration"}) - private void offsetSpinnerStateChanged(ChangeEvent e) - { + private void offsetSpinnerStateChanged(ChangeEvent e) { applyTrackOffset(parseOffsetInput()); } @SuppressWarnings({"UnusedDeclaration"}) - private void offsetToggleCheckBoxItemStateChanged(ItemEvent e) - { + private void offsetToggleCheckBoxItemStateChanged(ItemEvent e) { this.offsetSpinner.setEnabled(this.offsetToggleCheckBox.isSelected()); double offset = this.offsetToggleCheckBox.isSelected() ? parseOffsetInput() : 0d; applyTrackOffset(offset); } - private double parseOffsetInput() - { - return ((SpinnerNumberModel)this.offsetSpinner.getModel()).getNumber().doubleValue(); + private double parseOffsetInput() { + return ((SpinnerNumberModel) this.offsetSpinner.getModel()).getNumber().doubleValue(); } - private void applyTrackOffset(double offset) - { + private void applyTrackOffset(double offset) { // The actual track offset will always be in meters. If the // user is working in imperial units, convert the slider // value to meters before passing it to SarTrack. double trackOffset; - if (SAR2.UNIT_IMPERIAL.equals(this.elevationUnit)) + if (SAR2.UNIT_IMPERIAL.equals(this.elevationUnit)) { trackOffset = SAR2.feetToMeters(offset); - else // Default to metric units. + } else // Default to metric units. + { trackOffset = offset; + } this.positionTable.getSarTrack().setOffset(trackOffset); this.positionTable.getSarTrack().firePropertyChange(TrackController.TRACK_MODIFY, null, - this.positionTable.getSarTrack()); + this.positionTable.getSarTrack()); } - private void changeOffsetUnit(String oldUnit, String newUnit) - { - if (newUnit.equals(oldUnit)) + private void changeOffsetUnit(String oldUnit, String newUnit) { + if (newUnit.equals(oldUnit)) { return; + } double offset = parseOffsetInput(); SpinnerNumberModel sm; - if (SAR2.UNIT_IMPERIAL.equals(newUnit)) - { + if (SAR2.UNIT_IMPERIAL.equals(newUnit)) { offset = SAR2.metersToFeet(offset); this.offsetUnitLabel.setText("ft"); - sm = new SpinnerNumberModel((int)offset, -100000, 100000, 100); - } - else // SAR2.UNIT_METRIC + sm = new SpinnerNumberModel((int) offset, -100000, 100000, 100); + } else // SAR2.UNIT_METRIC { offset = SAR2.feetToMeters(offset); this.offsetUnitLabel.setText("m"); - sm = new SpinnerNumberModel((int)offset, -100000, 100000, 100); + sm = new SpinnerNumberModel((int) offset, -100000, 100000, 100); } this.offsetSpinner.setModel(sm); } - private void initComponents() - { + private void initComponents() { this.setToolTipText("Track Positions"); this.visibilityFlag = new JCheckBox(); @@ -168,8 +151,7 @@ private void initComponents() this.offsetUnitLabel = new JLabel(); } - protected void layoutComponents() - { + protected void layoutComponents() { setLayout(new BorderLayout(0, 0)); // hgap, vgap this.setOpaque(false); @@ -185,10 +167,8 @@ protected void layoutComponents() this.visibilityFlag.setSelected(true); this.visibilityFlag.setOpaque(false); this.visibilityFlag.setToolTipText("Display track on the globe"); - this.visibilityFlag.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + this.visibilityFlag.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { visibilityActionPerformed(e); } }); @@ -200,10 +180,8 @@ public void actionPerformed(ActionEvent e) this.offsetToggleCheckBox.setSelected(true); this.offsetToggleCheckBox.setOpaque(false); this.offsetToggleCheckBox.setToolTipText("Visually offset track altitude on the globe"); - this.offsetToggleCheckBox.addItemListener(new ItemListener() - { - public void itemStateChanged(ItemEvent e) - { + this.offsetToggleCheckBox.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { offsetToggleCheckBoxItemStateChanged(e); } }); @@ -212,10 +190,8 @@ public void itemStateChanged(ItemEvent e) SpinnerModel sm = new SpinnerNumberModel(0, -100000, 100000, 100); this.offsetSpinner.setModel(sm); - this.offsetSpinner.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent e) - { + this.offsetSpinner.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { offsetSpinnerStateChanged(e); } }); @@ -240,31 +216,24 @@ public void stateChanged(ChangeEvent e) } // *** Restorable interface *** - - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -274,29 +243,29 @@ public void restoreState(String stateInXml) this.doRestoreState(rs, null); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { // Add state values rs.addStateValueAsBoolean(context, "offsetEnabled", this.offsetToggleCheckBox.isSelected()); double value = parseOffsetInput(); - if (this.elevationUnit.equals(SAR2.UNIT_IMPERIAL)) + if (this.elevationUnit.equals(SAR2.UNIT_IMPERIAL)) { value = SAR2.feetToMeters(value); // convert to meter if needed + } rs.addStateValueAsDouble(context, "offsetValue", value); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Retrieve state values Boolean offsetEnabledState = rs.getStateValueAsBoolean(context, "offsetEnabled"); - if (offsetEnabledState != null) + if (offsetEnabledState != null) { this.offsetToggleCheckBox.setSelected(offsetEnabledState); + } Double valueState = rs.getStateValueAsDouble(context, "offsetValue"); - if (valueState != null) - { - if (this.elevationUnit.equals(SAR2.UNIT_IMPERIAL)) + if (valueState != null) { + if (this.elevationUnit.equals(SAR2.UNIT_IMPERIAL)) { valueState = SAR2.metersToFeet(valueState); // convert to feet if needed + } this.offsetSpinner.setValue(valueState); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/TrackViewPanel.java b/src/gov/nasa/worldwindx/applications/sar/TrackViewPanel.java index 8e0c361012..ae4cb9f9fe 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TrackViewPanel.java +++ b/src/gov/nasa/worldwindx/applications/sar/TrackViewPanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.sar; import gov.nasa.worldwind.WorldWindow; @@ -20,8 +19,8 @@ * @author tag * @version $Id: TrackViewPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TrackViewPanel extends JPanel -{ +public class TrackViewPanel extends JPanel { + // SAR logical components. private AnalysisPanel analysisPanel; private SARTrack sarTrack; @@ -66,37 +65,29 @@ public class TrackViewPanel extends JPanel public static final String SHOW_TRACK_INFORMATION = "TrackViewPanel.ShowTrackInformation"; public static final String CURRENT_SEGMENT = "TrackViewPanel.CurrentSegment"; - public TrackViewPanel(AnalysisPanel analysisPanel) - { + public TrackViewPanel(AnalysisPanel analysisPanel) { this.analysisPanel = analysisPanel; initComponents(); this.updateEnabledState(); - this.trackPropertyChangeListener = new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent event) - { - if (event.getPropertyName().equals(TrackController.TRACK_MODIFY)) - { + this.trackPropertyChangeListener = new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + if (event.getPropertyName().equals(TrackController.TRACK_MODIFY)) { updatePositionList(false); } } }; } - public WorldWindow getWwd() - { + public WorldWindow getWwd() { return this.analysisPanel.getWwd(); } - public void setCurrentTrack(SARTrack sarTrack) - { - if (this.sarTrack != null) - { + public void setCurrentTrack(SARTrack sarTrack) { + if (this.sarTrack != null) { this.sarTrack.removePropertyChangeListener(this.trackPropertyChangeListener); } this.sarTrack = sarTrack; - if (this.sarTrack != null) - { + if (this.sarTrack != null) { this.sarTrack.addPropertyChangeListener(this.trackPropertyChangeListener); } @@ -104,50 +95,44 @@ public void setCurrentTrack(SARTrack sarTrack) this.updateEnabledState(); } - public String getElevationUnit() - { + public String getElevationUnit() { return this.elevationUnit; } - public void setElevationUnit(String elevationUnit) - { + public void setElevationUnit(String elevationUnit) { this.elevationUnit = elevationUnit; } - public String getAngleFormat() - { + public String getAngleFormat() { return this.angleFormat; } - public void setAngleFormat(String format) - { + public void setAngleFormat(String format) { this.angleFormat = format; } - public String getViewMode() - { + public String getViewMode() { return this.viewMode; } - public void setViewMode(String viewMode) - { - if (this.viewMode.equals(viewMode)) + public void setViewMode(String viewMode) { + if (this.viewMode.equals(viewMode)) { return; + } this.viewMode = viewMode; this.firePropertyChange(VIEW_CHANGE, -1, 0); } - private void updatePositionList(boolean resetPosition) - { + private void updatePositionList(boolean resetPosition) { String[] strings = new String[this.sarTrack != null ? this.sarTrack.size() : 0]; - for (int i = 0; i < strings.length; i++) - { + for (int i = 0; i < strings.length; i++) { strings[i] = String.format("%,4d", i); } - if (strings.length == 0) - strings = new String[] {" 0"}; + if (strings.length == 0) { + strings = new String[]{" 0"}; + } int currentPosition = Math.min(this.getCurrentPositionNumber(), strings.length - 1); int currentSliderValue = this.positionSlider.getValue(); @@ -156,13 +141,11 @@ private void updatePositionList(boolean resetPosition) this.positionSlider.setValue(resetPosition ? 0 : currentSliderValue); } - private void setPositionSpinnerNumber(int n) - { + private void setPositionSpinnerNumber(int n) { this.positionSpinner.setValue(String.format("%,4d", n)); } - private void updateEnabledState() - { + private void updateEnabledState() { boolean state = this.sarTrack != null; this.positionSpinner.setEnabled(state); @@ -183,46 +166,39 @@ private void updateEnabledState() this.updateReadout(this.sarTrack != null && sarTrack.size() > 0 ? sarTrack.get(0) : null); } - private void positionSpinnerStateChanged() - { - if (!this.suspendPositionEvents) - { + private void positionSpinnerStateChanged() { + if (!this.suspendPositionEvents) { setPositionDelta(getCurrentPositionNumber(), 0); this.firePropertyChange(POSITION_CHANGE, -1, 0); } } - private void positionSliderStateChanged() - { - if (!this.suspendPositionEvents) - { + private void positionSliderStateChanged() { + if (!this.suspendPositionEvents) { updatePositionDelta(); this.firePropertyChange(POSITION_CHANGE, -1, 0); } } - public int getCurrentPositionNumber() - { + public int getCurrentPositionNumber() { Object o = this.positionSpinner.getValue(); - if (o == null) + if (o == null) { return -1; + } return Integer.parseInt(o.toString().trim().replaceAll(",", "")); } - private boolean isLastPosition(int n) - { + private boolean isLastPosition(int n) { return n >= this.sarTrack.size() - 1; } - public double getPositionDelta() - { + public double getPositionDelta() { // Portion of the current segment 0.0 .. 1.0 return this.positionDelta; } - private void updatePositionDelta() - { + private void updatePositionDelta() { // From UI control int i = this.positionSlider.getValue(); int min = this.positionSlider.getMinimum(); @@ -230,17 +206,14 @@ private void updatePositionDelta() this.positionDelta = (double) i / ((double) max - (double) min); } - public void gotoTrackEnd() - { - if(this.sarTrack != null && this.sarTrack.size() > 0) - { + public void gotoTrackEnd() { + if (this.sarTrack != null && this.sarTrack.size() > 0) { this.setPositionDelta(this.sarTrack.size() - 1, 0); this.firePropertyChange(POSITION_CHANGE, -1, 0); } } - public void setPositionDelta(int positionNumber, double positionDelta) - { + public void setPositionDelta(int positionNumber, double positionDelta) { // Update UI controls without firing events this.suspendPositionEvents = true; { @@ -255,151 +228,127 @@ public void setPositionDelta(int positionNumber, double positionDelta) this.positionDelta = positionDelta; } - public boolean isExamineViewMode() - { + public boolean isExamineViewMode() { return this.viewMode.equals(VIEW_MODE_EXAMINE); } - public boolean isFollowViewMode() - { + public boolean isFollowViewMode() { return this.viewMode.equals(VIEW_MODE_FOLLOW); } - public boolean isFreeViewMode() - { + public boolean isFreeViewMode() { return this.viewMode.equals(VIEW_MODE_FREE); } - public void updateReadout(Position pos) - { + public void updateReadout(Position pos) { this.latReadout.setText(pos == null ? "" : SAR2.formatAngle(angleFormat, pos.getLatitude())); this.lonReadout.setText(pos == null ? "" : SAR2.formatAngle(angleFormat, pos.getLongitude())); - if (SAR2.UNIT_IMPERIAL.equals(this.elevationUnit)) + if (SAR2.UNIT_IMPERIAL.equals(this.elevationUnit)) { this.altReadout.setText( - pos == null ? "" : String.format("% 8.0f ft", SAR2.metersToFeet(pos.getElevation()))); - else // Default to metric units. + pos == null ? "" : String.format("% 8.0f ft", SAR2.metersToFeet(pos.getElevation()))); + } else // Default to metric units. + { this.altReadout.setText(pos == null ? "" : String.format("% 8.0f m", pos.getElevation())); + } this.speedLabel.setText(SAR2.UNIT_IMPERIAL.equals(this.elevationUnit) ? "MPH: " : "KMH: "); } - public double getSpeedKMH() - { - String speedValue = (String)this.speedSpinner.getValue(); + public double getSpeedKMH() { + String speedValue = (String) this.speedSpinner.getValue(); double speed = Double.parseDouble(speedValue) * getSpeedFactor(); - if (SAR2.UNIT_IMPERIAL.equals(this.elevationUnit)) + if (SAR2.UNIT_IMPERIAL.equals(this.elevationUnit)) { speed *= 1.609344; // mph to kmh + } return speed; } - public double getSpeedFactor() - { - String speedFactor = ((String)this.speedFactorSpinner.getValue()).replace("x", ""); + public double getSpeedFactor() { + String speedFactor = ((String) this.speedFactorSpinner.getValue()).replace("x", ""); return Double.parseDouble(speedFactor); } // Player Controls - - private void fastReverseButtonActionPerformed() - { - if (this.getCurrentPositionNumber() > 0) + private void fastReverseButtonActionPerformed() { + if (this.getCurrentPositionNumber() > 0) { setPositionSpinnerNumber(this.getCurrentPositionNumber() - 1); + } } - private void reverseButtonActionPerformed() - { + private void reverseButtonActionPerformed() { setPlayMode(PLAY_BACKWARD); } - private void stopButtonActionPerformed() - { + private void stopButtonActionPerformed() { setPlayMode(PLAY_STOP); } - private void forwardButtonActionPerformed() - { + private void forwardButtonActionPerformed() { setPlayMode(PLAY_FORWARD); } - private void fastForwardButtonActionPerformed() - { - if (!isLastPosition(this.getCurrentPositionNumber())) + private void fastForwardButtonActionPerformed() { + if (!isLastPosition(this.getCurrentPositionNumber())) { setPositionSpinnerNumber(this.getCurrentPositionNumber() + 1); + } } - public boolean isPlayerActive() - { + public boolean isPlayerActive() { return this.playMode != PLAY_STOP; } - private void setPlayMode(int mode) - { + private void setPlayMode(int mode) { this.playMode = mode; - if (player == null) + if (player == null) { initPlayer(); + } player.start(); } - private void initPlayer() - { - if (player != null) + private void initPlayer() { + if (player != null) { return; + } - player = new Timer(50, new ActionListener() - { + player = new Timer(50, new ActionListener() { // Animate the view motion by controlling the positionSpinner and positionDelta - public void actionPerformed(ActionEvent actionEvent) - { + public void actionPerformed(ActionEvent actionEvent) { runPlayer(); } }); } - private void runPlayer() - { + private void runPlayer() { int positionNumber = getCurrentPositionNumber(); double curDelta = getPositionDelta(); double speedKMH = getSpeedKMH(); - if (this.playMode == PLAY_STOP) - { + if (this.playMode == PLAY_STOP) { this.stopButton.setEnabled(false); this.player.stop(); this.previousStepTime = -1; - } - else if (this.playMode == PLAY_FORWARD) - { + } else if (this.playMode == PLAY_FORWARD) { this.stopButton.setEnabled(true); - if (positionNumber >= (this.sarTrack.size() - 1)) - { + if (positionNumber >= (this.sarTrack.size() - 1)) { setPositionDelta(this.sarTrack.size() - 1, 0); this.playMode = PLAY_STOP; - } - else - { + } else { double distanceToGo = computeDistanceToGo(speedKMH); - while (distanceToGo > 0) - { + while (distanceToGo > 0) { double segmentLength = this.analysisPanel.getSegmentLength(positionNumber); - if (segmentLength * curDelta + distanceToGo <= segmentLength) - { + if (segmentLength * curDelta + distanceToGo <= segmentLength) { // enough space inside this segment curDelta += distanceToGo / segmentLength; setPositionDelta(positionNumber, curDelta); distanceToGo = 0; - } - else - { + } else { // move to next segment - if (!this.isLastPosition(positionNumber + 1)) - { + if (!this.isLastPosition(positionNumber + 1)) { distanceToGo -= segmentLength * (1d - curDelta); positionNumber++; curDelta = 0; - } - else - { + } else { // reached end of track setPositionDelta(positionNumber + 1, 0); this.playMode = PLAY_STOP; @@ -409,39 +358,27 @@ else if (this.playMode == PLAY_FORWARD) } this.firePropertyChange(POSITION_CHANGE, -1, 0); } - } - else if (this.playMode == PLAY_BACKWARD) - { + } else if (this.playMode == PLAY_BACKWARD) { this.stopButton.setEnabled(true); - if (positionNumber <= 0 && curDelta <= 0) - { + if (positionNumber <= 0 && curDelta <= 0) { setPositionDelta(0, 0); this.playMode = PLAY_STOP; - } - else - { + } else { double distanceToGo = computeDistanceToGo(speedKMH); - while (distanceToGo > 0) - { + while (distanceToGo > 0) { double segmentLength = this.analysisPanel.getSegmentLength(positionNumber); - if (segmentLength * curDelta - distanceToGo >= 0) - { + if (segmentLength * curDelta - distanceToGo >= 0) { // enough space inside this segment curDelta -= distanceToGo / segmentLength; setPositionDelta(positionNumber, curDelta); distanceToGo = 0; - } - else - { + } else { // move to previous segment - if (positionNumber > 0) - { + if (positionNumber > 0) { distanceToGo -= segmentLength * curDelta; positionNumber--; curDelta = 1; - } - else - { + } else { // reached start of track setPositionDelta(0, 0); this.playMode = PLAY_STOP; @@ -454,12 +391,10 @@ else if (this.playMode == PLAY_BACKWARD) } } - private double computeDistanceToGo(double speedKMH) - { + private double computeDistanceToGo(double speedKMH) { long stepTime = System.nanoTime(); double distance = 0; - if (this.previousStepTime > 0) - { + if (this.previousStepTime > 0) { double ellapsedMillisec = (stepTime - this.previousStepTime) / 1e6; distance = speedKMH / 3600d * ellapsedMillisec; // meters } @@ -467,8 +402,7 @@ private double computeDistanceToGo(double speedKMH) return distance; } - private void initComponents() - { + private void initComponents() { //======== this ======== this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); @@ -537,16 +471,14 @@ private void initComponents() { //---- Position Spinner ---- this.positionSpinner = new JSpinner(); - this.positionSpinner.setModel(new SpinnerListModel(new String[] {" 0"})); + this.positionSpinner.setModel(new SpinnerListModel(new String[]{" 0"})); this.positionSpinner.setEnabled(false); Dimension size = new Dimension(50, this.positionSpinner.getPreferredSize().height); this.positionSpinner.setMinimumSize(size); this.positionSpinner.setPreferredSize(size); this.positionSpinner.setMaximumSize(size); - this.positionSpinner.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent e) - { + this.positionSpinner.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { positionSpinnerStateChanged(); } }); @@ -558,10 +490,8 @@ public void stateChanged(ChangeEvent e) this.positionSlider.setMaximum(1000); this.positionSlider.setValue(0); this.positionSlider.setEnabled(false); - this.positionSlider.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent e) - { + this.positionSlider.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { positionSliderStateChanged(); } }); @@ -579,10 +509,8 @@ public void stateChanged(ChangeEvent e) this.fastReverseButton = new JButton(); this.fastReverseButton.setText("<<"); this.fastReverseButton.setEnabled(false); - this.fastReverseButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + this.fastReverseButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { fastReverseButtonActionPerformed(); } }); @@ -593,10 +521,8 @@ public void actionPerformed(ActionEvent e) this.reverseButton = new JButton(); this.reverseButton.setText("<"); this.reverseButton.setEnabled(false); - this.reverseButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + this.reverseButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { reverseButtonActionPerformed(); } }); @@ -607,10 +533,8 @@ public void actionPerformed(ActionEvent e) this.stopButton = new JButton(); this.stopButton.setText("Stop"); this.stopButton.setEnabled(false); - this.stopButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + this.stopButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { stopButtonActionPerformed(); } }); @@ -622,10 +546,8 @@ public void actionPerformed(ActionEvent e) this.forwardButton.setText(">"); this.forwardButton.setBorder(UIManager.getBorder("Button.border")); this.forwardButton.setEnabled(false); - this.forwardButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + this.forwardButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { forwardButtonActionPerformed(); } }); @@ -636,10 +558,8 @@ public void actionPerformed(ActionEvent e) this.fastForwardButton = new JButton(); this.fastForwardButton.setText(">>"); this.fastForwardButton.setEnabled(false); - this.fastForwardButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { + this.fastForwardButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { fastForwardButtonActionPerformed(); } }); @@ -665,8 +585,7 @@ public void actionPerformed(ActionEvent e) //---- Speed Spinner ---- int numValues = 100; String[] speedValues = new String[numValues]; - for (int i = 1; i <= numValues; i++) - { + for (int i = 1; i <= numValues; i++) { speedValues[i - 1] = "" + (i * 10); } this.speedSpinner = new JSpinner(); @@ -683,7 +602,7 @@ public void actionPerformed(ActionEvent e) //---- Speed Multiplier Spinner ---- this.speedFactorSpinner = new JSpinner(); this.speedFactorSpinner.setModel(new SpinnerListModel( - new String[] {"x.12", "x.25", "x.50", "x1", "x2", "x3", "x4", "x5", "x7", "x10"})); + new String[]{"x.12", "x.25", "x.50", "x1", "x2", "x3", "x4", "x5", "x7", "x10"})); this.speedFactorSpinner.setValue("x1"); this.speedFactorSpinner.setEnabled(false); size = new Dimension(60, this.speedFactorSpinner.getPreferredSize().height); @@ -702,31 +621,24 @@ public void actionPerformed(ActionEvent e) } // *** Restorable interface *** - - public String getRestorableState() - { + public String getRestorableState() { RestorableSupport rs = RestorableSupport.newRestorableSupport(); this.doGetRestorableState(rs, null); return rs.getStateAsXml(); } - public void restoreState(String stateInXml) - { - if (stateInXml == null) - { + public void restoreState(String stateInXml) { + if (stateInXml == null) { String message = Logging.getMessage("nullValue.StringIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RestorableSupport rs; - try - { + try { rs = RestorableSupport.parse(stateInXml); - } - catch (Exception e) - { + } catch (Exception e) { // Parsing the document specified by stateInXml failed. String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml); Logging.logger().severe(message); @@ -736,35 +648,35 @@ public void restoreState(String stateInXml) this.doRestoreState(rs, null); } - protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doGetRestorableState(RestorableSupport rs, RestorableSupport.StateObject context) { // Add state values rs.addStateValueAsInteger(context, "positionNumber", this.getCurrentPositionNumber()); rs.addStateValueAsDouble(context, "positionDelta", this.getPositionDelta()); rs.addStateValueAsString(context, "viewMode", this.getViewMode()); - rs.addStateValueAsString(context, "speed", (String)this.speedSpinner.getValue()); - rs.addStateValueAsString(context, "speedFactor", (String)this.speedFactorSpinner.getValue()); + rs.addStateValueAsString(context, "speed", (String) this.speedSpinner.getValue()); + rs.addStateValueAsString(context, "speedFactor", (String) this.speedFactorSpinner.getValue()); } - protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) - { + protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObject context) { // Retrieve state values Integer positionNumberState = rs.getStateValueAsInteger(context, "positionNumber"); Double positionDeltaState = rs.getStateValueAsDouble(context, "positionDelta"); - if (positionNumberState != null && positionDeltaState != null) + if (positionNumberState != null && positionDeltaState != null) { this.setPositionDelta(positionNumberState, positionDeltaState); + } String speedState = rs.getStateValueAsString(context, "speed"); - if (speedState != null) + if (speedState != null) { this.speedSpinner.setValue(speedState); + } String speedFactorState = rs.getStateValueAsString(context, "speedFactor"); - if (speedFactorState != null) + if (speedFactorState != null) { this.speedFactorSpinner.setValue(speedFactorState); + } String viewModeState = rs.getStateValueAsString(context, "viewMode"); - if (viewModeState != null) - { + if (viewModeState != null) { this.viewMode = viewModeState; // Update analysis panel this.firePropertyChange(VIEW_CHANGE, -1, 0); @@ -773,5 +685,4 @@ protected void doRestoreState(RestorableSupport rs, RestorableSupport.StateObjec } } - } diff --git a/src/gov/nasa/worldwindx/applications/sar/TracksPanel.java b/src/gov/nasa/worldwindx/applications/sar/TracksPanel.java index b7078c751e..f4af77e22f 100644 --- a/src/gov/nasa/worldwindx/applications/sar/TracksPanel.java +++ b/src/gov/nasa/worldwindx/applications/sar/TracksPanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.sar; import gov.nasa.worldwind.render.PatternFactory; @@ -19,19 +18,17 @@ * @author tag * @version $Id: TracksPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TracksPanel extends JPanel -{ +public class TracksPanel extends JPanel { + private String elevationUnit; private String angleFormat; private JTabbedPane tracksTabbedPane; - public TracksPanel() - { + public TracksPanel() { initComponents(); } - private void initComponents() - { + private void initComponents() { //======== this ======== this.setLayout(new BorderLayout(0, 0)); // hgap, vgap @@ -40,10 +37,8 @@ private void initComponents() { this.tracksTabbedPane.setMinimumSize(new Dimension(361, 223)); this.tracksTabbedPane.setPreferredSize(new Dimension(361, 223)); - this.tracksTabbedPane.addChangeListener(new ChangeListener() - { - public void stateChanged(ChangeEvent e) - { + this.tracksTabbedPane.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { tracksTabbedPaneStateChanged(e); } }); @@ -51,146 +46,133 @@ public void stateChanged(ChangeEvent e) add(this.tracksTabbedPane, BorderLayout.CENTER); } - public SARTrack getCurrentTrack() - { + public SARTrack getCurrentTrack() { Component c = this.tracksTabbedPane.getSelectedComponent(); return c != null ? ((TrackPanel) c).getTrack() : null; } - public void setCurrentTrack(SARTrack track) - { + public void setCurrentTrack(SARTrack track) { int index = this.getTrackPanelIndex(track); - if (index < 0) + if (index < 0) { return; + } this.tracksTabbedPane.setSelectedIndex(index); } - public Iterable getAllTracks() - { + public Iterable getAllTracks() { ArrayList tracks = new ArrayList(); - for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) - { + for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) { TrackPanel tp = (TrackPanel) this.tracksTabbedPane.getComponentAt(i); - if (tp.getTrack() != null) + if (tp.getTrack() != null) { tracks.add(tp.getTrack()); + } } return tracks; } - public void addTrack(SARTrack track) - { + public void addTrack(SARTrack track) { TrackPanel tp = new TrackPanel(); tp.setTrack(track); tp.setElevationUnit(this.elevationUnit); tp.setAngleFormat(this.angleFormat); tp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // top, left, bottom, right this.tracksTabbedPane.addTab(track.getName(), makeColorCircle(track.getColor()), tp); - track.addPropertyChangeListener(new PropertyChangeListener() - { + track.addPropertyChangeListener(new PropertyChangeListener() { @SuppressWarnings({"StringEquality"}) - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_REMOVE) + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_REMOVE) { removeTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_NAME) + } else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_NAME) { renameTrack((SARTrack) propertyChangeEvent.getSource()); - else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_DIRTY_BIT) + } else if (propertyChangeEvent.getPropertyName() == TrackController.TRACK_DIRTY_BIT) { updateTrackDirty((SARTrack) propertyChangeEvent.getSource()); + } } }); this.tracksTabbedPane.setSelectedComponent(tp); } - public String getElevationUnit() - { + public String getElevationUnit() { return this.elevationUnit; } - public void setElevationUnit(String unit) - { + public void setElevationUnit(String unit) { this.elevationUnit = unit; - for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) - { + for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) { TrackPanel tp = (TrackPanel) this.tracksTabbedPane.getComponentAt(i); tp.setElevationUnit(unit); } } - public String getAngleFormat() - { + public String getAngleFormat() { return this.angleFormat; } - public void setAngleFormat(String format) - { + public void setAngleFormat(String format) { this.angleFormat = format; - for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) - { + for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) { TrackPanel tp = (TrackPanel) this.tracksTabbedPane.getComponentAt(i); tp.setAngleFormat(format); } } - private void removeTrack(SARTrack track) - { + private void removeTrack(SARTrack track) { TrackPanel tp = this.getTrackPanel(track); - if (tp != null) + if (tp != null) { this.tracksTabbedPane.remove(tp); + } } - private void renameTrack(SARTrack track) - { + private void renameTrack(SARTrack track) { int index = getTrackPanelIndex(track); - if (index != -1) + if (index != -1) { this.tracksTabbedPane.setTitleAt(index, track.getName()); + } } - private void updateTrackDirty(SARTrack track) - { + private void updateTrackDirty(SARTrack track) { int index = getTrackPanelIndex(track); - if (index != -1) + if (index != -1) { this.tracksTabbedPane.setTitleAt(index, track.getName() + (track.isDirty() ? "*" : "")); + } } - public TrackPanel getTrackPanel(SARTrack track) - { - for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) - { + public TrackPanel getTrackPanel(SARTrack track) { + for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) { TrackPanel tp = (TrackPanel) this.tracksTabbedPane.getComponentAt(i); - if (tp.getTrack() == track) + if (tp.getTrack() == track) { return tp; + } } return null; } - private int getTrackPanelIndex(SARTrack track) - { - for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) - { + private int getTrackPanelIndex(SARTrack track) { + for (int i = 0; i < this.tracksTabbedPane.getTabCount(); i++) { TrackPanel tp = (TrackPanel) this.tracksTabbedPane.getComponentAt(i); - if (tp.getTrack() == track) + if (tp.getTrack() == track) { return i; + } } return -1; } @SuppressWarnings({"UnusedDeclaration"}) - private void tracksTabbedPaneStateChanged(ChangeEvent e) - { + private void tracksTabbedPaneStateChanged(ChangeEvent e) { SARTrack track = this.getCurrentTrack(); - if (track == null) + if (track == null) { return; + } track.firePropertyChange(TrackController.TRACK_CURRENT, null, track); } - private static Icon makeColorCircle(Color color) - { + private static Icon makeColorCircle(Color color) { BufferedImage bi = PatternFactory.createPattern( - PatternFactory.PATTERN_CIRCLE, new Dimension(16, 16), .9f, color); + PatternFactory.PATTERN_CIRCLE, new Dimension(16, 16), .9f, color); return new ImageIcon(bi); } diff --git a/src/gov/nasa/worldwindx/applications/sar/UserPreferenceUtils.java b/src/gov/nasa/worldwindx/applications/sar/UserPreferenceUtils.java index 744b4c8505..41965eb44f 100644 --- a/src/gov/nasa/worldwindx/applications/sar/UserPreferenceUtils.java +++ b/src/gov/nasa/worldwindx/applications/sar/UserPreferenceUtils.java @@ -19,12 +19,10 @@ * @author dcollins * @version $Id: UserPreferenceUtils.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class UserPreferenceUtils -{ - public static Document createUserPreferencesDocument(AVList params) - { - if (params == null) - { +public class UserPreferenceUtils { + + public static Document createUserPreferencesDocument(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -41,17 +39,14 @@ public static Document createUserPreferencesDocument(AVList params) return doc; } - public static void getUserPreferences(Element domElement, AVList params) - { - if (domElement == null) - { + public static void getUserPreferences(Element domElement, AVList params) { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (params == null) - { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -60,21 +55,19 @@ public static void getUserPreferences(Element domElement, AVList params) XPath xpath = WWXML.makeXPath(); Element el = WWXML.getElement(domElement, "PropertyList", xpath); - if (el != null) + if (el != null) { getPropertyList(el, params, xpath); + } } - public static void createUserPreferenceElements(AVList params, Element domElement) - { - if (params == null) - { + public static void createUserPreferenceElements(AVList params, Element domElement) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (domElement == null) - { + if (domElement == null) { String message = Logging.getMessage("nullValue.DocumentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -84,18 +77,15 @@ public static void createUserPreferenceElements(AVList params, Element domElemen createPropertyList(params, el); } - public static String getDefaultUserPreferencesPath() - { + public static String getDefaultUserPreferencesPath() { String path = Configuration.getUserHomeDirectory(); String name = ".sarapp/UserPreferences.xml"; return path + File.separator + name; } - public static void getDefaultUserPreferences(AVList params) - { - if (params == null) - { + public static void getDefaultUserPreferences(AVList params) { + if (params == null) { String message = Logging.getMessage("nullValue.ParametersIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -108,71 +98,69 @@ public static void getDefaultUserPreferences(AVList params) params.setValue(SARKey.ELEVATION_UNIT, SAR2.UNIT_IMPERIAL); } - public static boolean getBooleanValue(AVList avList, String key) - { + public static boolean getBooleanValue(AVList avList, String key) { Object o = avList.getValue(key); - if (o == null) + if (o == null) { return false; + } - if (o instanceof Boolean) + if (o instanceof Boolean) { return (Boolean) o; + } String v = AVListImpl.getStringValue(avList, key); - if (v == null) + if (v == null) { return false; + } - try - { + try { return Boolean.parseBoolean(v); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { Logging.logger().log(java.util.logging.Level.SEVERE, "Configuration.ConversionError", v); return false; } } - protected static void getPropertyList(Element domElement, AVList params, XPath xpath) - { + protected static void getPropertyList(Element domElement, AVList params, XPath xpath) { Element[] els = WWXML.getElements(domElement, "Property", xpath); - if (els == null || els.length == 0) + if (els == null || els.length == 0) { return; + } - for (Element el : els) - { - if (el == null) + for (Element el : els) { + if (el == null) { continue; - + } + getProperty(el, params, xpath); } } - protected static void getProperty(Element domElement, AVList params, XPath xpath) - { + protected static void getProperty(Element domElement, AVList params, XPath xpath) { String key = WWXML.getText(domElement, "@key", xpath); String value = WWXML.getText(domElement, "@value", xpath); - if (key == null || value == null) + if (key == null || value == null) { return; + } params.setValue(key, value); } - protected static void createPropertyList(AVList params, Element domElement) - { - for (Map.Entry entry : params.getEntries()) - { - if (entry == null || entry.getKey() == null || entry.getValue() == null) + protected static void createPropertyList(AVList params, Element domElement) { + for (Map.Entry entry : params.getEntries()) { + if (entry == null || entry.getKey() == null || entry.getValue() == null) { continue; + } createProperty(entry, domElement); } } - protected static void createProperty(Map.Entry entry, Element domElement) - { + protected static void createProperty(Map.Entry entry, Element domElement) { String s = entry.getValue().toString(); - if (s == null) + if (s == null) { return; + } Element el = WWXML.appendElementPath(domElement, "Property"); el.setAttribute("key", entry.getKey()); diff --git a/src/gov/nasa/worldwindx/applications/sar/ViewMenu.java b/src/gov/nasa/worldwindx/applications/sar/ViewMenu.java index 1786a1e69b..24b13734fb 100644 --- a/src/gov/nasa/worldwindx/applications/sar/ViewMenu.java +++ b/src/gov/nasa/worldwindx/applications/sar/ViewMenu.java @@ -18,24 +18,20 @@ * @author jparsons * @version $Id: ViewMenu.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ViewMenu extends JMenu -{ +public class ViewMenu extends JMenu { + private WorldWindow wwd; - public ViewMenu() - { + public ViewMenu() { super("View"); } - public void setWwd(WorldWindow wwdInstance) - { + public void setWwd(WorldWindow wwdInstance) { this.wwd = wwdInstance; // Layers - for (Layer layer : wwd.getModel().getLayers()) - { - if (isAbstractLayerMenuItem(layer)) - { + for (Layer layer : wwd.getModel().getLayers()) { + if (isAbstractLayerMenuItem(layer)) { JCheckBoxMenuItem mi = new JCheckBoxMenuItem(new LayerVisibilityAction(wwd, layer)); mi.setState(layer.isEnabled()); this.add(mi); @@ -46,10 +42,8 @@ public void setWwd(WorldWindow wwdInstance) JMenuItem mi = new JMenuItem("Terrain profile..."); mi.setMnemonic('T'); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - mi.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { + mi.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { wwd.firePropertyChange(TerrainProfilePanel.TERRAIN_PROFILE_OPEN, null, null); } }); @@ -59,47 +53,42 @@ public void actionPerformed(ActionEvent event) mi = new JMenuItem("Cloud Contour..."); mi.setMnemonic('C'); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - mi.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent event) - { + mi.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { wwd.firePropertyChange(CloudCeilingPanel.CLOUD_CEILING_OPEN, null, null); } }); this.add(mi); } - private boolean isAbstractLayerMenuItem(Layer layer) - { - if (layer instanceof RenderableLayer) //detect PlaneModel layer + private boolean isAbstractLayerMenuItem(Layer layer) { + if (layer instanceof RenderableLayer) //detect PlaneModel layer { - Iterable iter = ((RenderableLayer)layer).getRenderables(); - for (Renderable rend: iter) - { - if (rend instanceof PlaneModel) + Iterable iter = ((RenderableLayer) layer).getRenderables(); + for (Renderable rend : iter) { + if (rend instanceof PlaneModel) { return true; + } } } return ((layer instanceof ScalebarLayer || layer instanceof CrosshairLayer - || layer instanceof CompassLayer)); + || layer instanceof CompassLayer)); } - private static class LayerVisibilityAction extends AbstractAction - { + private static class LayerVisibilityAction extends AbstractAction { + private final Layer layer; private final WorldWindow wwd; - public LayerVisibilityAction(WorldWindow wwd, Layer layer) - { + public LayerVisibilityAction(WorldWindow wwd, Layer layer) { super(layer.getName()); this.layer = layer; this.wwd = wwd; } - public void actionPerformed(ActionEvent actionEvent) - { + public void actionPerformed(ActionEvent actionEvent) { layer.setEnabled(((JCheckBoxMenuItem) actionEvent.getSource()).getState()); this.wwd.redraw(); } diff --git a/src/gov/nasa/worldwindx/applications/sar/WWPanel.java b/src/gov/nasa/worldwindx/applications/sar/WWPanel.java index 5e30396744..5ea784c427 100644 --- a/src/gov/nasa/worldwindx/applications/sar/WWPanel.java +++ b/src/gov/nasa/worldwindx/applications/sar/WWPanel.java @@ -21,24 +21,21 @@ * @author tag * @version $Id: WWPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWPanel extends JPanel -{ - protected static class FocusablePanel extends JPanel - { +public class WWPanel extends JPanel { + + protected static class FocusablePanel extends JPanel { + private Component focusContext; - public FocusablePanel(LayoutManager layoutManager, Component focusContext) - { + public FocusablePanel(LayoutManager layoutManager, Component focusContext) { super(layoutManager); this.focusContext = focusContext; } - protected void paintComponent(Graphics graphics) - { + protected void paintComponent(Graphics graphics) { super.paintComponent(graphics); - if (this.focusContext.isFocusOwner()) - { + if (this.focusContext.isFocusOwner()) { Rectangle bounds = this.getBounds(); BasicGraphicsUtils.drawDashedRect(graphics, 0, 0, bounds.width, bounds.height); } @@ -49,38 +46,33 @@ protected void paintComponent(Graphics graphics) private WorldWindowGLCanvas wwd; private StatusBar statusBar; - private final PropertyChangeListener propertyChangeListener = new PropertyChangeListener() - { + private final PropertyChangeListener propertyChangeListener = new PropertyChangeListener() { @SuppressWarnings({"StringEquality"}) - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { - if (propertyChangeEvent.getPropertyName() == SARKey.ELEVATION_UNIT) + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + if (propertyChangeEvent.getPropertyName() == SARKey.ELEVATION_UNIT) { updateElevationUnit(propertyChangeEvent.getNewValue()); - if (propertyChangeEvent.getPropertyName() == SARKey.ANGLE_FORMAT) + } + if (propertyChangeEvent.getPropertyName() == SARKey.ANGLE_FORMAT) { updateAngleFormat(propertyChangeEvent.getNewValue()); + } } }; - private final FocusListener focusListener = new FocusListener() - { - public void focusGained(FocusEvent focusEvent) - { + private final FocusListener focusListener = new FocusListener() { + public void focusGained(FocusEvent focusEvent) { this.focusChanged(focusEvent); } - public void focusLost(FocusEvent focusEvent) - { + public void focusLost(FocusEvent focusEvent) { this.focusChanged(focusEvent); } - protected void focusChanged(FocusEvent focusEvent) - { + protected void focusChanged(FocusEvent focusEvent) { repaint(); } }; - public WWPanel() - { + public WWPanel() { super(new BorderLayout(0, 0)); // hgap, vgap this.wwd = new WorldWindowGLCanvas(); @@ -104,44 +96,42 @@ public WWPanel() this.add(this.statusBar, BorderLayout.PAGE_END); } - public WorldWindowGLCanvas getWwd() - { + public WorldWindowGLCanvas getWwd() { return wwd; } - public StatusBar getStatusBar() - { + public StatusBar getStatusBar() { return statusBar; } - private void updateElevationUnit(Object newValue) - { - for (Layer layer : this.wwd.getModel().getLayers()) - { - if (layer instanceof ScalebarLayer) - { - if (SAR2.UNIT_IMPERIAL.equals(newValue)) + private void updateElevationUnit(Object newValue) { + for (Layer layer : this.wwd.getModel().getLayers()) { + if (layer instanceof ScalebarLayer) { + if (SAR2.UNIT_IMPERIAL.equals(newValue)) { ((ScalebarLayer) layer).setUnit(ScalebarLayer.UNIT_IMPERIAL); - else // Default to metric units. + } else // Default to metric units. + { ((ScalebarLayer) layer).setUnit(ScalebarLayer.UNIT_METRIC); - } - else if (layer instanceof TerrainProfileLayer) - { - if (SAR2.UNIT_IMPERIAL.equals(newValue)) + } + } else if (layer instanceof TerrainProfileLayer) { + if (SAR2.UNIT_IMPERIAL.equals(newValue)) { ((TerrainProfileLayer) layer).setUnit(TerrainProfileLayer.UNIT_IMPERIAL); - else // Default to metric units. + } else // Default to metric units. + { ((TerrainProfileLayer) layer).setUnit(TerrainProfileLayer.UNIT_METRIC); + } } } - if (SAR2.UNIT_IMPERIAL.equals(newValue)) + if (SAR2.UNIT_IMPERIAL.equals(newValue)) { this.statusBar.setElevationUnit(StatusBar.UNIT_IMPERIAL); - else // Default to metric units. + } else // Default to metric units. + { this.statusBar.setElevationUnit(StatusBar.UNIT_METRIC); + } } - private void updateAngleFormat(Object newValue) - { - this.statusBar.setAngleFormat((String)newValue); + private void updateAngleFormat(Object newValue) { + this.statusBar.setAngleFormat((String) newValue); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/actions/AddOffsetToPositionsAction.java b/src/gov/nasa/worldwindx/applications/sar/actions/AddOffsetToPositionsAction.java index 2364d056b7..5afb90bee2 100644 --- a/src/gov/nasa/worldwindx/applications/sar/actions/AddOffsetToPositionsAction.java +++ b/src/gov/nasa/worldwindx/applications/sar/actions/AddOffsetToPositionsAction.java @@ -14,12 +14,11 @@ * @author dcollins * @version $Id: AddOffsetToPositionsAction.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AddOffsetToPositionsAction extends AbstractAction -{ +public class AddOffsetToPositionsAction extends AbstractAction { + protected final PositionTable table; - public AddOffsetToPositionsAction(final PositionTable table) - { + public AddOffsetToPositionsAction(final PositionTable table) { this.table = table; int numSelectedPositions = table.getSelectedRowCount(); @@ -27,23 +26,24 @@ public AddOffsetToPositionsAction(final PositionTable table) putValue(NAME, "Add Altitude Offset To Selected"); putValue(LONG_DESCRIPTION, "Add the track altitude offset to the selected positions"); - if (numSelectedPositions == 0) + if (numSelectedPositions == 0) { this.setEnabled(false); + } SARTrack st = table.getSarTrack(); - if (st == null || st.getOffset() == 0) + if (st == null || st.getOffset() == 0) { this.setEnabled(false); + } } - public void actionPerformed(ActionEvent e) - { + public void actionPerformed(ActionEvent e) { SARTrack st = table.getSarTrack(); - if (st == null || st.getOffset() == 0) + if (st == null || st.getOffset() == 0) { return; + } double offset = st.getOffset(); - for (int index : this.table.getSelectedRows()) - { + for (int index : this.table.getSelectedRows()) { SARPosition pos = st.get(index); st.set(index, new SARPosition(pos.getLatitude(), pos.getLongitude(), pos.getElevation() + offset)); } diff --git a/src/gov/nasa/worldwindx/applications/sar/actions/AppendPositionAction.java b/src/gov/nasa/worldwindx/applications/sar/actions/AppendPositionAction.java index 4a11862633..c08b0f2d34 100644 --- a/src/gov/nasa/worldwindx/applications/sar/actions/AppendPositionAction.java +++ b/src/gov/nasa/worldwindx/applications/sar/actions/AppendPositionAction.java @@ -14,27 +14,27 @@ * @author tag * @version $Id: AppendPositionAction.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AppendPositionAction extends AbstractAction -{ +public class AppendPositionAction extends AbstractAction { + protected final PositionTable table; - public AppendPositionAction(final PositionTable table) - { + public AppendPositionAction(final PositionTable table) { this.table = table; putValue(NAME, "Append New Position to Track"); putValue(LONG_DESCRIPTION, "Add a new position to the end of the Track"); } - public void actionPerformed(ActionEvent e) - { + public void actionPerformed(ActionEvent e) { SARTrack st = table.getSarTrack(); - if (st == null) + if (st == null) { return; + } - if (st.size() != 0) + if (st.size() != 0) { st.appendPosition(st.get(st.size() - 1)); - else + } else { st.appendPosition(new SARPosition()); + } table.getSelectionModel().setSelectionInterval(st.size() - 1, st.size() - 1); } diff --git a/src/gov/nasa/worldwindx/applications/sar/actions/DeletePositionsAction.java b/src/gov/nasa/worldwindx/applications/sar/actions/DeletePositionsAction.java index d81ad979a6..039e34dd58 100644 --- a/src/gov/nasa/worldwindx/applications/sar/actions/DeletePositionsAction.java +++ b/src/gov/nasa/worldwindx/applications/sar/actions/DeletePositionsAction.java @@ -14,30 +14,31 @@ * @author tag * @version $Id: DeletePositionsAction.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DeletePositionsAction extends AbstractAction -{ +public class DeletePositionsAction extends AbstractAction { + protected final PositionTable table; - public DeletePositionsAction(final PositionTable table) - { + public DeletePositionsAction(final PositionTable table) { this.table = table; int numSelectedPositions = table.getSelectedRowCount(); - if (numSelectedPositions <= 1) + if (numSelectedPositions <= 1) { putValue(NAME, "Delete Selected Position"); - else + } else { putValue(NAME, "Delete Selected Positions"); + } putValue(LONG_DESCRIPTION, "Remove Positions from Track"); - if (numSelectedPositions == 0) + if (numSelectedPositions == 0) { this.setEnabled(false); + } } - public void actionPerformed(ActionEvent e) - { + public void actionPerformed(ActionEvent e) { SARTrack st = table.getSarTrack(); - if (st != null) + if (st != null) { st.removePositions(this.table.getSelectedRows()); + } } } diff --git a/src/gov/nasa/worldwindx/applications/sar/actions/InsertPositionAction.java b/src/gov/nasa/worldwindx/applications/sar/actions/InsertPositionAction.java index dc43891c69..a1fb38eaca 100644 --- a/src/gov/nasa/worldwindx/applications/sar/actions/InsertPositionAction.java +++ b/src/gov/nasa/worldwindx/applications/sar/actions/InsertPositionAction.java @@ -14,46 +14,44 @@ * @author tag * @version $Id: InsertPositionAction.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class InsertPositionAction extends AbstractAction -{ +public class InsertPositionAction extends AbstractAction { + private final boolean above; protected final PositionTable table; - public InsertPositionAction(final boolean above, final PositionTable table) - { + public InsertPositionAction(final boolean above, final PositionTable table) { this.table = table; this.above = above; - if (this.above) - { + if (this.above) { putValue(NAME, "Insert New Position Above Selection"); putValue(LONG_DESCRIPTION, "Insert a new position above the selected positions"); - } - else - { + } else { putValue(NAME, "Insert New Position Below Selection"); putValue(LONG_DESCRIPTION, "Insert a new position below the selected positions"); } - if (table.getSelectedRowCount() == 0) + if (table.getSelectedRowCount() == 0) { this.setEnabled(false); + } } - public void actionPerformed(ActionEvent e) - { + public void actionPerformed(ActionEvent e) { SARTrack st = table.getSarTrack(); - if (st == null) + if (st == null) { return; + } int index = table.getSelectionModel().getMinSelectionIndex(); - if (!this.above) + if (!this.above) { index = table.getSelectionModel().getMaxSelectionIndex(); + } - if (index < 0) + if (index < 0) { return; + } st.insertPosition(index, new SARPosition()); table.getSelectionModel().setSelectionInterval(index, index); } } - diff --git a/src/gov/nasa/worldwindx/applications/sar/actions/SARScreenShotAction.java b/src/gov/nasa/worldwindx/applications/sar/actions/SARScreenShotAction.java index 3c8515c33f..aab9e21994 100644 --- a/src/gov/nasa/worldwindx/applications/sar/actions/SARScreenShotAction.java +++ b/src/gov/nasa/worldwindx/applications/sar/actions/SARScreenShotAction.java @@ -14,10 +14,9 @@ * @author dcollins * @version $Id: SARScreenShotAction.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SARScreenShotAction extends ScreenShotAction -{ - public SARScreenShotAction(WorldWindow wwd, Icon icon) - { +public class SARScreenShotAction extends ScreenShotAction { + + public SARScreenShotAction(WorldWindow wwd, Icon icon) { super(wwd); this.putValue(Action.NAME, "Screen Shot..."); this.putValue(Action.SHORT_DESCRIPTION, "Save a screen shot"); diff --git a/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java b/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java index 010a5d5a23..edab0cc2d3 100644 --- a/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java +++ b/src/gov/nasa/worldwindx/applications/sar/render/PlaneModel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.sar.render; import gov.nasa.worldwind.geom.Angle; @@ -18,8 +17,9 @@ import java.util.ArrayList; /** - * Renders a plane model at a position with a given heading. The plane is parallel to the ground. - * An optional 'shadow' shape is rendered on the ground. + * Renders a plane model at a position with a given heading. The plane is parallel to the ground. An optional 'shadow' + * shape is rendered on the ground. + * * @author Patrick Murris * @version $Id: PlaneModel.java 1171 2013-02-11 21:45:02Z dcollins $ */ @@ -41,27 +41,24 @@ public class PlaneModel implements Renderable { /** * Renders a plane model with the defaul dimensions and color. */ - public PlaneModel() - { + public PlaneModel() { } /** * Renders a plane model with the specified dimensions and color. + * * @param length the plane length in meters * @param width the plane width in meter. * @param color the plane color. */ - public PlaneModel(Double length, Double width, Color color) - { + public PlaneModel(Double length, Double width, Color color) { this.length = length; this.width = width; this.color = color; } - public void setPosition(Position pos) - { - if (pos == null) - { + public void setPosition(Position pos) { + if (pos == null) { String msg = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -70,15 +67,12 @@ public void setPosition(Position pos) clearRenderables(); } - public Position getPosition() - { + public Position getPosition() { return this.position; } - public void setHeading(Angle head) - { - if (head == null) - { + public void setHeading(Angle head) { + if (head == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -87,66 +81,58 @@ public void setHeading(Angle head) clearRenderables(); } - public Angle getHeading() - { + public Angle getHeading() { return this.heading; } - public void setShowShadow(boolean state) - { + public void setShowShadow(boolean state) { this.showShadow = state; } - public boolean getShowShadow() - { + public boolean getShowShadow() { return this.showShadow; } - public double getShadowScale() - { + public double getShadowScale() { return this.shadowScale; } - public void setShadowScale(double shadowScale) - { + public void setShadowScale(double shadowScale) { this.shadowScale = shadowScale; clearRenderables(); } - public Color getShadowColor() - { + public Color getShadowColor() { return this.shadowColor; } - public void setShadowColor(Color shadowColor) - { + public void setShadowColor(Color shadowColor) { this.shadowColor = shadowColor; clearRenderables(); } - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String msg = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } - if( this.position == null || this.heading == null) + if (this.position == null || this.heading == null) { return; + } //renderPlane(dc); - - if (this.planeModel == null) + if (this.planeModel == null) { createRenderables(dc); + } this.planeModel.render(dc); - if (this.showShadow && this.shadowModel != null) + if (this.showShadow && this.shadowModel != null) { this.shadowModel.render(dc); + } } - private void createRenderables(DrawContext dc) - { + private void createRenderables(DrawContext dc) { ArrayList positions = computePlaneShape(dc, this.width, this.length); this.planeModel = new Polyline(positions, this.position.getElevation()); this.planeModel.setPathType(Polyline.LINEAR); @@ -161,14 +147,12 @@ private void createRenderables(DrawContext dc) this.shadowModel.setColor(this.shadowColor); } - private void clearRenderables() - { + private void clearRenderables() { this.planeModel = null; this.shadowModel = null; } - private ArrayList computePlaneShape(DrawContext dc, double width, double length) - { + private ArrayList computePlaneShape(DrawContext dc, double width, double length) { ArrayList positions = new ArrayList(); LatLon center = this.position; double hl = length / 2; @@ -190,7 +174,7 @@ private ArrayList computePlaneShape(DrawContext dc, double width, double return positions; } -/* + /* private void renderPlane(DrawContext dc) { GL gl = dc.getGL(); @@ -224,5 +208,5 @@ private void renderPlane(DrawContext dc) gl.glPopAttrib(); } -*/ + */ } diff --git a/src/gov/nasa/worldwindx/applications/sar/render/ScreenElevationLine.java b/src/gov/nasa/worldwindx/applications/sar/render/ScreenElevationLine.java index ec7d45bd1b..5a85a58626 100644 --- a/src/gov/nasa/worldwindx/applications/sar/render/ScreenElevationLine.java +++ b/src/gov/nasa/worldwindx/applications/sar/render/ScreenElevationLine.java @@ -18,8 +18,8 @@ * @author Patrick Murris * @version $Id: ScreenElevationLine.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ScreenElevationLine implements Renderable -{ +public class ScreenElevationLine implements Renderable { + private double elevation = 0; private Color color = Color.WHITE; private boolean enabled = true; @@ -29,8 +29,7 @@ public class ScreenElevationLine implements Renderable * * @return the line current elevation. */ - public double getElevation() - { + public double getElevation() { return this.elevation; } @@ -39,8 +38,7 @@ public double getElevation() * * @param elevation the line elevation. */ - public void setElevation(double elevation) - { + public void setElevation(double elevation) { this.elevation = elevation; } @@ -49,8 +47,7 @@ public void setElevation(double elevation) * * @return the line color. */ - public Color getColor() - { + public Color getColor() { return this.color; } @@ -59,10 +56,8 @@ public Color getColor() * * @param color the line color. */ - public void setColor(Color color) - { - if (color == null) - { + public void setColor(Color color) { + if (color == null) { String msg = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); @@ -71,45 +66,40 @@ public void setColor(Color color) this.color = color; } - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean state) - { + public void setEnabled(boolean state) { this.enabled = state; } - public void render(DrawContext dc) - { - if (this.isEnabled()) + public void render(DrawContext dc) { + if (this.isEnabled()) { dc.addOrderedRenderable(new OrderedItem()); + } } - private class OrderedItem implements OrderedRenderable - { - public double getDistanceFromEye() - { + private class OrderedItem implements OrderedRenderable { + + public double getDistanceFromEye() { return 1; } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { draw(dc); } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { draw(dc); } } - private void draw(DrawContext dc) - { + private void draw(DrawContext dc) { Double lineY = computeLineY(dc); - if (lineY == null) + if (lineY == null) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -117,14 +107,13 @@ private void draw(DrawContext dc) boolean modelviewPushed = false; boolean projectionPushed = false; - try - { + try { gl.glPushAttrib(GL2.GL_DEPTH_BUFFER_BIT - | GL2.GL_COLOR_BUFFER_BIT - | GL2.GL_ENABLE_BIT - | GL2.GL_TRANSFORM_BIT - | GL2.GL_VIEWPORT_BIT - | GL2.GL_CURRENT_BIT); + | GL2.GL_COLOR_BUFFER_BIT + | GL2.GL_ENABLE_BIT + | GL2.GL_TRANSFORM_BIT + | GL2.GL_VIEWPORT_BIT + | GL2.GL_CURRENT_BIT); attribsPushed = true; gl.glEnable(GL.GL_BLEND); @@ -145,11 +134,10 @@ private void draw(DrawContext dc) modelviewPushed = true; gl.glLoadIdentity(); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Set color gl.glColor4ub((byte) this.color.getRed(), (byte) this.color.getGreen(), - (byte) this.color.getBlue(), (byte) this.color.getAlpha()); + (byte) this.color.getBlue(), (byte) this.color.getAlpha()); } // Draw line @@ -157,35 +145,31 @@ private void draw(DrawContext dc) gl.glVertex3d(0, lineY, 0); gl.glVertex3d(viewport.width, lineY, 0); gl.glEnd(); - } - finally - { - if (projectionPushed) - { + } finally { + if (projectionPushed) { gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); } - if (modelviewPushed) - { + if (modelviewPushed) { gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPopMatrix(); } - if (attribsPushed) + if (attribsPushed) { gl.glPopAttrib(); + } } } - private Double computeLineY(DrawContext dc) - { + private Double computeLineY(DrawContext dc) { Vec4 point = dc.getGlobe().computePointFromPosition( - new Position(dc.getView().getEyePosition(), this.elevation)); + new Position(dc.getView().getEyePosition(), this.elevation)); Vec4 direction = dc.getView().getForwardVector().perpendicularTo3(point); // Round globe only Vec4 intersection = dc.getView().getFrustumInModelCoordinates().getNear().intersect(new Line(point, direction)); - if (intersection != null) - { + if (intersection != null) { Vec4 screenPoint = dc.getView().project(intersection); - if (screenPoint != null) + if (screenPoint != null) { return screenPoint.y; + } } return null; } diff --git a/src/gov/nasa/worldwindx/applications/sar/render/TrackSegmentInfo.java b/src/gov/nasa/worldwindx/applications/sar/render/TrackSegmentInfo.java index 6649455c3f..c40896fffc 100644 --- a/src/gov/nasa/worldwindx/applications/sar/render/TrackSegmentInfo.java +++ b/src/gov/nasa/worldwindx/applications/sar/render/TrackSegmentInfo.java @@ -18,8 +18,8 @@ * @author dcollins * @version $Id: TrackSegmentInfo.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class TrackSegmentInfo implements Renderable -{ +public class TrackSegmentInfo implements Renderable { + protected boolean enabled; protected SARTrack track; protected int segmentIndex; @@ -27,153 +27,136 @@ public class TrackSegmentInfo implements Renderable protected Object angleFormat; protected Object elevationUnit; - public TrackSegmentInfo() - { + public TrackSegmentInfo() { } - public boolean isEnabled() - { + public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean enable) - { + public void setEnabled(boolean enable) { this.enabled = enable; } - public SARTrack getTrack() - { + public SARTrack getTrack() { return this.track; } - public void setTrack(SARTrack track) - { + public void setTrack(SARTrack track) { this.track = track; } - public int getSegmentIndex() - { + public int getSegmentIndex() { return this.segmentIndex; } - public void setSegmentIndex(int index) - { + public void setSegmentIndex(int index) { this.segmentIndex = index; } - public Position getSegmentPosition() - { + public Position getSegmentPosition() { return this.segmentPosition; } - public void setSegmentPosition(Position pos) - { + public void setSegmentPosition(Position pos) { this.segmentPosition = pos; } - public Object getAngleFormat() - { + public Object getAngleFormat() { return this.angleFormat; } - public void setAngleFormat(Object angleFormat) - { + public void setAngleFormat(Object angleFormat) { this.angleFormat = angleFormat; } - public Object getElevationUnit() - { + public Object getElevationUnit() { return this.elevationUnit; } - public void setElevationUnit(Object elevationUnit) - { + public void setElevationUnit(Object elevationUnit) { this.elevationUnit = elevationUnit; } - public void render(DrawContext dc) - { - if (dc == null) - { + public void render(DrawContext dc) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!this.isEnabled()) + if (!this.isEnabled()) { return; + } this.doRender(dc); } - protected void doRender(DrawContext dc) - { - if (this.track == null) + protected void doRender(DrawContext dc) { + if (this.track == null) { return; + } - if (this.segmentIndex < 0 || this.segmentIndex >= this.track.size()) + if (this.segmentIndex < 0 || this.segmentIndex >= this.track.size()) { return; + } this.drawSegmentLabel(dc, this.track, this.segmentIndex); - if (this.segmentIndex < this.track.size() - 1) + if (this.segmentIndex < this.track.size() - 1) { this.drawSegmentLabel(dc, this.track, this.segmentIndex + 1); + } - if (this.segmentPosition != null) + if (this.segmentPosition != null) { this.drawSegmentPositionLabel(dc, this.track, this.segmentIndex, this.segmentPosition); + } } - protected void drawSegmentLabel(DrawContext dc, SARTrack track, int index) - { + protected void drawSegmentLabel(DrawContext dc, SARTrack track, int index) { SARPosition pos = track.get(index); Vec4 screenPoint = this.getScreenPoint(dc, pos); this.drawLatLonLabel(dc, (int) screenPoint.x, (int) screenPoint.y, Font.decode("Arial-BOLD-12"), - WWUtil.makeColorBrighter(track.getColor()), pos); + WWUtil.makeColorBrighter(track.getColor()), pos); } - protected Vec4 getScreenPoint(DrawContext dc, Position position) - { - if (dc.getGlobe() == null || dc.getView() == null) + protected Vec4 getScreenPoint(DrawContext dc, Position position) { + if (dc.getGlobe() == null || dc.getView() == null) { return null; + } Vec4 modelPoint = dc.getGlobe().computePointFromPosition(position.getLatitude(), position.getLongitude(), - position.getElevation()); - if (modelPoint == null) + position.getElevation()); + if (modelPoint == null) { return null; + } return dc.getView().project(modelPoint); } - protected void drawSegmentPositionLabel(DrawContext dc, SARTrack track, int index, Position pos) - { + protected void drawSegmentPositionLabel(DrawContext dc, SARTrack track, int index, Position pos) { Angle heading = null; // If there is a track position after this index, then compute the heading from this track position to the next // track position. - if (index < track.size() - 1) - { + if (index < track.size() - 1) { heading = LatLon.rhumbAzimuth(track.get(index), track.get(index + 1)); - } - // Otherwise, this is the last track position. If there is a track position before this index, then compute the + } // Otherwise, this is the last track position. If there is a track position before this index, then compute the // heading from the previous track position to this track position. - else if (index > 0) - { + else if (index > 0) { heading = LatLon.rhumbAzimuth(track.get(index - 1), track.get(index)); } Vec4 screenPoint = this.getScreenPoint(dc, pos); this.drawHeadingAltitudeLabel(dc, (int) screenPoint.x, (int) screenPoint.y, Font.decode("Arial-BOLD-12"), - Color.YELLOW, heading, pos); + Color.YELLOW, heading, pos); } protected void drawHeadingAltitudeLabel(DrawContext dc, int x, int y, Font font, Color color, Angle heading, - Position pos) - { + Position pos) { double surfaceElevation = this.computeSurfaceElevation(dc, pos.getLatitude(), pos.getLongitude()); double distanceFromEye = dc.getView().getEyePoint().distanceTo3(dc.getGlobe().computePointFromPosition(pos)); StringBuilder sb = new StringBuilder(); - if (heading != null) - { + if (heading != null) { sb.append("Heading: "); sb.append(heading.toDecimalDegreesString(0)); sb.append("\n"); @@ -187,8 +170,7 @@ protected void drawHeadingAltitudeLabel(DrawContext dc, int x, int y, Font font, this.drawText(dc, sb.toString(), x, y, font, color, distanceFromEye); } - protected void drawLatLonLabel(DrawContext dc, int x, int y, Font font, Color color, Position pos) - { + protected void drawLatLonLabel(DrawContext dc, int x, int y, Font font, Color color, Position pos) { double distanceFromEye = dc.getView().getEyePoint().distanceTo3(dc.getGlobe().computePointFromPosition(pos)); StringBuilder sb = new StringBuilder(); @@ -201,13 +183,12 @@ protected void drawLatLonLabel(DrawContext dc, int x, int y, Font font, Color co this.drawText(dc, sb.toString(), x, y, font, color, distanceFromEye); } - protected void drawText(DrawContext dc, String text, int x, int y, Font font, Color color, double distanceFromEye) - { + protected void drawText(DrawContext dc, String text, int x, int y, Font font, Color color, double distanceFromEye) { dc.addOrderedRenderable(new OrderedText(text, x, y, font, color, distanceFromEye)); } - protected static class OrderedText implements OrderedRenderable - { + protected static class OrderedText implements OrderedRenderable { + private final String text; private final int x; private final int y; @@ -215,8 +196,7 @@ protected static class OrderedText implements OrderedRenderable private final Color color; private final double distanceFromEye; - public OrderedText(String text, int x, int y, Font font, Color color, double distanceFromEye) - { + public OrderedText(String text, int x, int y, Font font, Color color, double distanceFromEye) { this.text = text; this.x = x; this.y = y; @@ -225,65 +205,51 @@ public OrderedText(String text, int x, int y, Font font, Color color, double dis this.distanceFromEye = distanceFromEye; } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.distanceFromEye; } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { this.drawText(dc, this.text, this.x, this.y, this.font, this.color); } - protected void drawText(DrawContext dc, String text, int x, int y, Font font, Color color) - { + protected void drawText(DrawContext dc, String text, int x, int y, Font font, Color color) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. Rectangle viewport = dc.getView().getViewport(); OGLStackHandler stackHandler = new OGLStackHandler(); stackHandler.pushAttrib(gl, GL2.GL_CURRENT_BIT); // For current color. - try - { + try { MultiLineTextRenderer tr = this.getTextRendererFor(dc, font); tr.setTextAlign(AVKey.CENTER); tr.getTextRenderer().beginRendering(viewport.width, viewport.height); - try - { + try { tr.setTextColor(color); tr.setBackColor(Color.BLACK); Rectangle bounds = tr.getBounds(text); tr.draw(text, x, y + (3 * bounds.height / 2), AVKey.TEXT_EFFECT_OUTLINE); - } - finally - { + } finally { tr.getTextRenderer().endRendering(); } - } - finally - { + } finally { stackHandler.pop(gl); } } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { } - protected MultiLineTextRenderer getTextRendererFor(DrawContext dc, Font font) - { + protected MultiLineTextRenderer getTextRendererFor(DrawContext dc, Font font) { TextRenderer tr = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); return new MultiLineTextRenderer(tr); } } - protected double computeSurfaceElevation(DrawContext dc, Angle latitude, Angle longitude) - { - if (dc.getSurfaceGeometry() != null) - { + protected double computeSurfaceElevation(DrawContext dc, Angle latitude, Angle longitude) { + if (dc.getSurfaceGeometry() != null) { Vec4 surfacePoint = dc.getSurfaceGeometry().getSurfacePoint(latitude, longitude); - if (surfacePoint != null) - { + if (surfacePoint != null) { Position surfacePos = dc.getGlobe().computePositionFromPoint(surfacePoint); return surfacePos.getElevation(); } @@ -292,15 +258,13 @@ protected double computeSurfaceElevation(DrawContext dc, Angle latitude, Angle l return dc.getGlobe().getElevation(latitude, longitude); } - protected String formatAngle(Angle angle) - { + protected String formatAngle(Angle angle) { return Angle.ANGLE_FORMAT_DMS.equals(this.angleFormat) ? angle.toDMSString() : angle.toDecimalDegreesString(4); } - protected String formatAltitude(double altitude) - { - return SAR2.UNIT_IMPERIAL.equals(this.elevationUnit) ? - String.format("%d ft", (long) WWMath.convertMetersToFeet(altitude)) : - String.format("%d m", (long) altitude); + protected String formatAltitude(double altitude) { + return SAR2.UNIT_IMPERIAL.equals(this.elevationUnit) + ? String.format("%d ft", (long) WWMath.convertMetersToFeet(altitude)) + : String.format("%d m", (long) altitude); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlane.java b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlane.java index 795f7d22fe..24402a5dac 100644 --- a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlane.java +++ b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlane.java @@ -17,10 +17,10 @@ * @author dcollins * @version $Id: SegmentPlane.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SegmentPlane extends WWObjectImpl -{ - public static class ControlPoint - { +public class SegmentPlane extends WWObjectImpl { + + public static class ControlPoint { + private Object owner; private Object key; private double uCoordinate; @@ -29,16 +29,13 @@ public static class ControlPoint private String shapeType; public ControlPoint(Object owner, Object key, double uCoordinate, double vCoordinate, - boolean relativeToSurface, String shapeType) - { - if (owner == null) - { + boolean relativeToSurface, String shapeType) { + if (owner == null) { String message = Logging.getMessage("nullValue.OwnerIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (key == null) - { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -52,56 +49,50 @@ public ControlPoint(Object owner, Object key, double uCoordinate, double vCoordi this.shapeType = shapeType; } - public Object getOwner() - { + public Object getOwner() { return this.owner; } - public Object getKey() - { + public Object getKey() { return this.key; } - public double[] getCoordinates() - { - return new double[] {this.uCoordinate, this.vCoordinate}; + public double[] getCoordinates() { + return new double[]{this.uCoordinate, this.vCoordinate}; } - public boolean isRelativeToSurface() - { + public boolean isRelativeToSurface() { return this.relativeToSurface; } - public String getShapeType() - { + public String getShapeType() { return this.shapeType; } } - protected static class StateKey - { + protected static class StateKey { + private final SegmentPlane segmentPlane; private final long serialNumber; - public StateKey(SegmentPlane segmentPlane, long serialNumber) - { + public StateKey(SegmentPlane segmentPlane, long serialNumber) { this.segmentPlane = segmentPlane; this.serialNumber = serialNumber; } - public boolean equals(Object o) - { - if (this == o) + public boolean equals(Object o) { + if (this == o) { return true; - if (o == null || getClass() != o.getClass()) + } + if (o == null || getClass() != o.getClass()) { return false; + } StateKey that = (StateKey) o; return this.segmentPlane.equals(that.segmentPlane) && (this.serialNumber == that.serialNumber); } - public int hashCode() - { + public int hashCode() { int result = this.segmentPlane != null ? this.segmentPlane.hashCode() : 0; result = 31 * result + (int) (this.serialNumber ^ (this.serialNumber >>> 32)); return result; @@ -146,8 +137,7 @@ public int hashCode() private List controlPointList; protected long serialNumber = 1; - public SegmentPlane() - { + public SegmentPlane() { this.visible = true; this.attributes = new SegmentPlaneAttributes(); this.planeLowerAltitude = 0.0; @@ -170,43 +160,36 @@ public SegmentPlane() this.addDefaultAttributes(SEGMENT_END); this.addDefaultAttributes(ALTIMETER); - this.addDefaultControlPoint(CONTROL_POINT_LOWER_RIGHT, 1.0, 0.0, true, BasicMarkerShape.SPHERE); - this.addDefaultControlPoint(CONTROL_POINT_UPPER_RIGHT, 1.0, 1.0, false, BasicMarkerShape.SPHERE); - this.addDefaultControlPoint(CONTROL_POINT_TOP_EDGE, 0.5, 1.0, false, BasicMarkerShape.SPHERE); + this.addDefaultControlPoint(CONTROL_POINT_LOWER_RIGHT, 1.0, 0.0, true, BasicMarkerShape.SPHERE); + this.addDefaultControlPoint(CONTROL_POINT_UPPER_RIGHT, 1.0, 1.0, false, BasicMarkerShape.SPHERE); + this.addDefaultControlPoint(CONTROL_POINT_TOP_EDGE, 0.5, 1.0, false, BasicMarkerShape.SPHERE); this.addDefaultControlPoint(CONTROL_POINT_LEADING_EDGE, 1.0, 0.5, true, BasicMarkerShape.SPHERE); } - protected void addDefaultAttributes(Object key) - { + protected void addDefaultAttributes(Object key) { this.getAttributes().setGeometryAttributes(key, new SegmentPlaneAttributes.GeometryAttributes()); this.getAttributes().setLabelAttributes(key, new SegmentPlaneAttributes.LabelAttributes()); } - protected void addDefaultControlPoint(Object key, double u, double v, boolean relativeToSurface, String shapeType) - { + protected void addDefaultControlPoint(Object key, double u, double v, boolean relativeToSurface, String shapeType) { this.addControlPoint(new ControlPoint(this, key, u, v, relativeToSurface, shapeType)); this.addDefaultAttributes(key); } - public boolean isVisible() - { + public boolean isVisible() { return this.visible; } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.visible = visible; } - public SegmentPlaneAttributes getAttributes() - { + public SegmentPlaneAttributes getAttributes() { return attributes; } - public void setAttributes(SegmentPlaneAttributes attributes) - { - if (attributes == null) - { + public void setAttributes(SegmentPlaneAttributes attributes) { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -215,9 +198,8 @@ public void setAttributes(SegmentPlaneAttributes attributes) this.attributes = attributes; } - public double[] getPlaneAltitudes() - { - return new double[] {this.planeLowerAltitude, this.planeUpperAltitude}; + public double[] getPlaneAltitudes() { + return new double[]{this.planeLowerAltitude, this.planeUpperAltitude}; } /** @@ -226,8 +208,7 @@ public double[] getPlaneAltitudes() * @param lowerAltitude the lower altitude limit, in meters relative to mean sea level * @param upperAltitude the upper altitude limit, in meters relative to mean sea level */ - public void setPlaneAltitudes(double lowerAltitude, double upperAltitude) - { + public void setPlaneAltitudes(double lowerAltitude, double upperAltitude) { double[] oldAltitudes = this.getPlaneAltitudes(); this.planeLowerAltitude = lowerAltitude; @@ -237,21 +218,17 @@ public void setPlaneAltitudes(double lowerAltitude, double upperAltitude) this.firePropertyChange(PLANE_ALTITUDES, oldAltitudes, this.getPlaneAltitudes()); } - public LatLon[] getPlaneLocations() - { - return new LatLon[] {this.planeLocation1, this.planeLocation2}; + public LatLon[] getPlaneLocations() { + return new LatLon[]{this.planeLocation1, this.planeLocation2}; } - public void setPlaneLocations(LatLon location1, LatLon location2) - { - if (location1 == null) - { + public void setPlaneLocations(LatLon location1, LatLon location2) { + if (location1 == null) { String message = "nullValue.Location1IsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (location2 == null) - { + if (location2 == null) { String message = "nullValue.Location2IsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -266,21 +243,17 @@ public void setPlaneLocations(LatLon location1, LatLon location2) this.firePropertyChange(PLANE_LOCATIONS, oldLocations, this.getPlaneLocations()); } - public double[] getGridCellDimensions() - { - return new double[] {this.gridCellWidth, this.gridCellHeight}; + public double[] getGridCellDimensions() { + return new double[]{this.gridCellWidth, this.gridCellHeight}; } - public void setGridCellDimensions(double width, double height) - { - if (width <= 0.0) - { + public void setGridCellDimensions(double width, double height) { + if (width <= 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "width <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (height <= 0.0) - { + if (height <= 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "height <= 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -295,43 +268,35 @@ public void setGridCellDimensions(double width, double height) this.firePropertyChange(PLANE_GRID_DIMENSIONS, oldGridDimensions, this.getGridCellDimensions()); } - public int getPlaneOutlineMask() - { + public int getPlaneOutlineMask() { return this.planeOutlineMask; } - public void setPlaneOutlineMask(int mask) - { + public void setPlaneOutlineMask(int mask) { this.planeOutlineMask = mask; this.setStateExpired(); } - public int getBorderMask() - { + public int getBorderMask() { return this.borderMask; } - public void setBorderMask(int mask) - { + public void setBorderMask(int mask) { this.borderMask = mask; this.setStateExpired(); } - public Position[] getSegmentPositions() - { - return new Position[] {this.segmentBeginPosition, this.segmentEndPosition}; + public Position[] getSegmentPositions() { + return new Position[]{this.segmentBeginPosition, this.segmentEndPosition}; } - public void setSegmentPositions(Position position1, Position position2) - { - if (position1 == null) - { + public void setSegmentPositions(Position position1, Position position2) { + if (position1 == null) { String message = "nullValue.Position1IsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position2 == null) - { + if (position2 == null) { String message = "nullValue.Position2IsNull"; Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -341,10 +306,8 @@ public void setSegmentPositions(Position position1, Position position2) this.setSegmentEndPosition(position2); } - public void setSegmentBeginPosition(Position position) - { - if (position == null) - { + public void setSegmentBeginPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -356,10 +319,8 @@ public void setSegmentBeginPosition(Position position) this.firePropertyChange(SEGMENT_BEGIN, oldPosition, this.segmentBeginPosition); } - public void setSegmentEndPosition(Position position) - { - if (position == null) - { + public void setSegmentEndPosition(Position position) { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -371,32 +332,26 @@ public void setSegmentEndPosition(Position position) this.firePropertyChange(SEGMENT_END, oldPosition, this.segmentEndPosition); } - public List getControlPoints() - { + public List getControlPoints() { return Collections.unmodifiableList(this.controlPointList); } - public void setControlPoints(Iterable controlPoints) - { - if (controlPoints == null) - { + public void setControlPoints(Iterable controlPoints) { + if (controlPoints == null) { String message = Logging.getMessage("nullValue.IterableIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.controlPointList.clear(); - for (ControlPoint p : controlPoints) - { + for (ControlPoint p : controlPoints) { this.addControlPoint(p); } this.setStateExpired(); } - protected void addControlPoint(ControlPoint controlPoint) - { - if (controlPoint.getOwner() != this) - { + protected void addControlPoint(ControlPoint controlPoint) { + if (controlPoint.getOwner() != this) { String message = Logging.getMessage("generic.OwnerIsInvalid", controlPoint.getOwner()); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -405,15 +360,12 @@ protected void addControlPoint(ControlPoint controlPoint) this.controlPointList.add(controlPoint); } - public Object getStateKey() - { + public Object getStateKey() { return new StateKey(this, this.serialNumber); } - public Plane computeInfinitePlane(Globe globe) - { - if (globe == null) - { + public Plane computeInfinitePlane(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -427,18 +379,15 @@ public Plane computeInfinitePlane(Globe globe) Vec4 n = a.cross3(b).normalize3(); double d = -corners[0].dot3(n); - if (n.equals(Vec4.ZERO)) - { + if (n.equals(Vec4.ZERO)) { return null; } return new Plane(n.x, n.y, n.z, d); } - public BilinearInterpolator createPlaneInterpolator(Globe globe) - { - if (globe == null) - { + public BilinearInterpolator createPlaneInterpolator(Globe globe) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -455,8 +404,7 @@ public BilinearInterpolator createPlaneInterpolator(Globe globe) return new BilinearInterpolator(ll, lr, ur, ul); } - protected void setStateExpired() - { + protected void setStateExpired() { this.serialNumber++; } } diff --git a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneAttributes.java b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneAttributes.java index 61c49fe0bf..4e8563cb9b 100644 --- a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneAttributes.java +++ b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneAttributes.java @@ -18,10 +18,10 @@ * @author dcollins * @version $Id: SegmentPlaneAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SegmentPlaneAttributes -{ - public static class GeometryAttributes - { +public class SegmentPlaneAttributes { + + public static class GeometryAttributes { + private boolean visible; private boolean pickEnabled; private Material material; @@ -30,16 +30,13 @@ public static class GeometryAttributes private double pickSize; private Vec4 offset; - public GeometryAttributes(Material material, double opacity) - { - if (material == null) - { + public GeometryAttributes(Material material, double opacity) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (opacity < 0.0 || opacity > 1.0) - { + if (opacity < 0.0 || opacity > 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "opacity < 0 or opacity > 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -54,18 +51,15 @@ public GeometryAttributes(Material material, double opacity) this.offset = Vec4.ZERO; } - public GeometryAttributes() - { + public GeometryAttributes() { this(Material.WHITE, 1.0); } - public GeometryAttributes copy() - { + public GeometryAttributes copy() { return this.copyTo(new GeometryAttributes()); } - public GeometryAttributes copyTo(GeometryAttributes copy) - { + public GeometryAttributes copyTo(GeometryAttributes copy) { copy.setVisible(this.isVisible()); copy.setEnablePicking(this.isEnablePicking()); copy.setMaterial(this.getMaterial()); @@ -77,35 +71,28 @@ public GeometryAttributes copyTo(GeometryAttributes copy) return copy; } - public boolean isVisible() - { + public boolean isVisible() { return visible; } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.visible = visible; } - public boolean isEnablePicking() - { + public boolean isEnablePicking() { return this.pickEnabled; } - public void setEnablePicking(boolean enable) - { + public void setEnablePicking(boolean enable) { this.pickEnabled = enable; } - public Material getMaterial() - { + public Material getMaterial() { return this.material; } - public void setMaterial(Material material) - { - if (material == null) - { + public void setMaterial(Material material) { + if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -114,15 +101,12 @@ public void setMaterial(Material material) this.material = material; } - public double getOpacity() - { + public double getOpacity() { return this.opacity; } - public void setOpacity(double opacity) - { - if (opacity < 0.0 || opacity > 1.0) - { + public void setOpacity(double opacity) { + if (opacity < 0.0 || opacity > 1.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "opacity < 0 or opacity > 1"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -131,15 +115,12 @@ public void setOpacity(double opacity) this.opacity = opacity; } - public double getSize() - { + public double getSize() { return this.size; } - public void setSize(double size) - { - if (size < 0.0) - { + public void setSize(double size) { + if (size < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "size < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -148,15 +129,12 @@ public void setSize(double size) this.size = size; } - public double getPicksize() - { + public double getPicksize() { return this.pickSize; } - public void setPickSize(double size) - { - if (size < 0.0) - { + public void setPickSize(double size) { + if (size < 0.0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "size < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -165,15 +143,12 @@ public void setPickSize(double size) this.pickSize = size; } - public Vec4 getOffset() - { + public Vec4 getOffset() { return this.offset; } - public void setOffset(Vec4 vec4) - { - if (vec4 == null) - { + public void setOffset(Vec4 vec4) { + if (vec4 == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -183,8 +158,8 @@ public void setOffset(Vec4 vec4) } } - public static class LabelAttributes - { + public static class LabelAttributes { + private boolean visible; private java.awt.Color color; private java.awt.Font font; @@ -194,28 +169,23 @@ public static class LabelAttributes private double maxActiveDistance; private Vec4 offset; - public LabelAttributes(Color color, Font font, String horizontalAlignment, String verticalAlignment) - { - if (color == null) - { + public LabelAttributes(Color color, Font font, String horizontalAlignment, String verticalAlignment) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (font == null) - { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (horizontalAlignment == null) - { + if (horizontalAlignment == null) { String message = Logging.getMessage("nullValue.HorizontalAlignmentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (verticalAlignment == null) - { + if (verticalAlignment == null) { String message = Logging.getMessage("nullValue.VerticalAlignmentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -231,18 +201,15 @@ public LabelAttributes(Color color, Font font, String horizontalAlignment, Strin this.offset = Vec4.ZERO; } - public LabelAttributes() - { + public LabelAttributes() { this(Color.WHITE, Font.decode("Arial-12"), AVKey.LEFT, AVKey.BOTTOM); } - public LabelAttributes copy() - { + public LabelAttributes copy() { return this.copyTo(new LabelAttributes()); } - protected LabelAttributes copyTo(LabelAttributes copy) - { + protected LabelAttributes copyTo(LabelAttributes copy) { copy.setVisible(this.isVisible()); copy.setColor(this.getColor()); copy.setFont(this.getFont()); @@ -255,25 +222,20 @@ protected LabelAttributes copyTo(LabelAttributes copy) return copy; } - public boolean isVisible() - { + public boolean isVisible() { return this.visible; } - public void setVisible(boolean visible) - { + public void setVisible(boolean visible) { this.visible = visible; } - public Color getColor() - { + public Color getColor() { return this.color; } - public void setColor(Color color) - { - if (color == null) - { + public void setColor(Color color) { + if (color == null) { String message = Logging.getMessage("nullValue.ColorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -282,15 +244,12 @@ public void setColor(Color color) this.color = color; } - public Font getFont() - { + public Font getFont() { return this.font; } - public void setFont(Font font) - { - if (font == null) - { + public void setFont(Font font) { + if (font == null) { String message = Logging.getMessage("nullValue.FontIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -299,15 +258,12 @@ public void setFont(Font font) this.font = font; } - public String getHorizontalAlignment() - { + public String getHorizontalAlignment() { return this.horizontalAlignment; } - public void setHorizontalAlignment(String horizontalAlignment) - { - if (horizontalAlignment == null) - { + public void setHorizontalAlignment(String horizontalAlignment) { + if (horizontalAlignment == null) { String message = Logging.getMessage("nullValue.HorizontalAlignmentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -316,15 +272,12 @@ public void setHorizontalAlignment(String horizontalAlignment) this.horizontalAlignment = horizontalAlignment; } - public String getVerticalAlignment() - { + public String getVerticalAlignment() { return this.verticalAlignment; } - public void setVerticalAlignment(String verticalAlignment) - { - if (verticalAlignment == null) - { + public void setVerticalAlignment(String verticalAlignment) { + if (verticalAlignment == null) { String message = Logging.getMessage("nullValue.VerticalAlignmentIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -333,35 +286,28 @@ public void setVerticalAlignment(String verticalAlignment) this.verticalAlignment = verticalAlignment; } - public double getMinActiveDistance() - { + public double getMinActiveDistance() { return this.minActiveDistance; } - public void setMinActiveDistance(double distance) - { + public void setMinActiveDistance(double distance) { this.minActiveDistance = distance; } - public double getMaxActiveDistance() - { + public double getMaxActiveDistance() { return this.maxActiveDistance; } - public void setMaxActiveDistance(double distance) - { + public void setMaxActiveDistance(double distance) { this.maxActiveDistance = distance; } - public Vec4 getOffset() - { + public Vec4 getOffset() { return this.offset; } - public void setOffset(Vec4 vec4) - { - if (vec4 == null) - { + public void setOffset(Vec4 vec4) { + if (vec4 == null) { String message = Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -370,16 +316,13 @@ public void setOffset(Vec4 vec4) this.offset = vec4; } - public String getText(SegmentPlane segmentPlane, Position position, AVList values) - { - if (segmentPlane == null) - { + public String getText(SegmentPlane segmentPlane, Position position, AVList values) { + if (segmentPlane == null) { String message = Logging.getMessage("nullValue.SegmentPlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (position == null) - { + if (position == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -399,26 +342,22 @@ public String getText(SegmentPlane segmentPlane, Position position, AVList value private Map geometryAttributes; private Map labelAttributes; - public SegmentPlaneAttributes() - { + public SegmentPlaneAttributes() { this.geometryAttributes = new HashMap(); this.labelAttributes = new HashMap(); } - public SegmentPlaneAttributes copy() - { + public SegmentPlaneAttributes copy() { SegmentPlaneAttributes copy = new SegmentPlaneAttributes(); Map geometryAttributesMap = new HashMap(); - for (Map.Entry entry : this.geometryAttributes.entrySet()) - { + for (Map.Entry entry : this.geometryAttributes.entrySet()) { geometryAttributesMap.put(entry.getKey(), entry.getValue().copy()); } copy.setAllGeometryAttributes(geometryAttributesMap); Map labelAttributesMap = new HashMap(); - for (Map.Entry entry : this.labelAttributes.entrySet()) - { + for (Map.Entry entry : this.labelAttributes.entrySet()) { labelAttributesMap.put(entry.getKey(), entry.getValue().copy()); } copy.setAllLabelAttributes(labelAttributesMap); @@ -426,15 +365,12 @@ public SegmentPlaneAttributes copy() return copy; } - public Map getAllGeometryAttributes() - { + public Map getAllGeometryAttributes() { return Collections.unmodifiableMap(this.geometryAttributes); } - public void setAllGeometryAttributes(Map map) - { - if (map == null) - { + public void setAllGeometryAttributes(Map map) { + if (map == null) { String message = Logging.getMessage("nullValue.MapIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -444,15 +380,12 @@ public void setAllGeometryAttributes(Map m this.geometryAttributes.putAll(map); } - public Map getAllLabelAttributes() - { + public Map getAllLabelAttributes() { return Collections.unmodifiableMap(this.labelAttributes); } - public void setAllLabelAttributes(Map map) - { - if (map == null) - { + public void setAllLabelAttributes(Map map) { + if (map == null) { String message = Logging.getMessage("nullValue.MapIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -462,10 +395,8 @@ public void setAllLabelAttributes(Map map) this.labelAttributes.putAll(map); } - public GeometryAttributes getGeometryAttributes(Object key) - { - if (key == null) - { + public GeometryAttributes getGeometryAttributes(Object key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -474,16 +405,13 @@ public GeometryAttributes getGeometryAttributes(Object key) return this.geometryAttributes.get(key); } - public void setGeometryAttributes(Object key, GeometryAttributes attributes) - { - if (key == null) - { + public void setGeometryAttributes(Object key, GeometryAttributes attributes) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -492,10 +420,8 @@ public void setGeometryAttributes(Object key, GeometryAttributes attributes) this.geometryAttributes.put(key, attributes); } - public LabelAttributes getLabelAttributes(Object key) - { - if (key == null) - { + public LabelAttributes getLabelAttributes(Object key) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -504,16 +430,13 @@ public LabelAttributes getLabelAttributes(Object key) return this.labelAttributes.get(key); } - public void setLabelAttributes(Object key, LabelAttributes attributes) - { - if (key == null) - { + public void setLabelAttributes(Object key, LabelAttributes attributes) { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -522,49 +445,40 @@ public void setLabelAttributes(Object key, LabelAttributes attributes) this.labelAttributes.put(key, attributes); } - public static void applyGeometryAttributes(DrawContext dc, GeometryAttributes attributes, boolean enableMaterial) - { - if (dc == null) - { + public static void applyGeometryAttributes(DrawContext dc, GeometryAttributes attributes, boolean enableMaterial) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { applyMaterial(dc, attributes.getMaterial(), attributes.getOpacity(), enableMaterial); } } - public static void applyGeometryAttributesAsLine(DrawContext dc, GeometryAttributes attributes) - { - if (dc == null) - { + public static void applyGeometryAttributesAsLine(DrawContext dc, GeometryAttributes attributes) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (dc.getGL() == null) - { + if (dc.getGL() == null) { String message = Logging.getMessage("nullValue.DrawingContextGLIsNull"); Logging.logger().severe(message); throw new IllegalStateException(message); } - if (attributes == null) - { + if (attributes == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -573,16 +487,12 @@ public static void applyGeometryAttributesAsLine(DrawContext dc, GeometryAttribu applyLineWidth(dc, attributes.getSize(), attributes.getPicksize()); } - protected static void applyMaterial(DrawContext dc, Material material, double opacity, boolean enableMaterial) - { + protected static void applyMaterial(DrawContext dc, Material material, double opacity, boolean enableMaterial) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. - if (enableMaterial) - { + if (enableMaterial) { material.apply(gl, GL2.GL_FRONT_AND_BACK, (float) opacity); - } - else - { + } else { float[] compArray = new float[4]; material.getDiffuse().getRGBComponents(compArray); compArray[3] = (float) opacity; @@ -590,16 +500,12 @@ protected static void applyMaterial(DrawContext dc, Material material, double op } } - protected static void applyLineWidth(DrawContext dc, double lineWidth, double pickLineWidth) - { + protected static void applyLineWidth(DrawContext dc, double lineWidth, double pickLineWidth) { GL gl = dc.getGL(); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { gl.glLineWidth((float) pickLineWidth); - } - else - { + } else { gl.glLineWidth((float) lineWidth); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneController.java b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneController.java index f789740f99..dd5063857a 100644 --- a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneController.java +++ b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneController.java @@ -17,8 +17,7 @@ * @author dcollins * @version $Id: SegmentPlaneController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SegmentPlaneController implements MouseListener, MouseMotionListener, PositionListener -{ +public class SegmentPlaneController implements MouseListener, MouseMotionListener, PositionListener { // TODO: // the structure of this controller class is very similar to methods in AirspaceEditorController. Consolidate // editor controller functionality in a general place. @@ -32,44 +31,37 @@ public class SegmentPlaneController implements MouseListener, MouseMotionListene protected Point lastMousePoint; protected PickedObject activePickedObject; - public SegmentPlaneController(WorldWindow wwd) - { + public SegmentPlaneController(WorldWindow wwd) { this.active = false; this.setWorldWindow(wwd); } - public boolean isActive() - { + public boolean isActive() { return this.active; } - protected void setActive(boolean active) - { + protected void setActive(boolean active) { this.active = active; } - public SegmentPlaneEditor getEditor() - { + public SegmentPlaneEditor getEditor() { return this.editor; } - public void setEditor(SegmentPlaneEditor editor) - { + public void setEditor(SegmentPlaneEditor editor) { this.editor = editor; } - public WorldWindow getWorldWindow() - { + public WorldWindow getWorldWindow() { return this.wwd; } - public void setWorldWindow(WorldWindow wwd) - { - if (this.wwd == wwd) + public void setWorldWindow(WorldWindow wwd) { + if (this.wwd == wwd) { return; + } - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.getInputHandler().removeMouseListener(this); this.wwd.getInputHandler().removeMouseMotionListener(this); this.wwd.removePositionListener(this); @@ -77,35 +69,29 @@ public void setWorldWindow(WorldWindow wwd) this.wwd = wwd; - if (this.wwd != null) - { + if (this.wwd != null) { this.wwd.getInputHandler().addMouseListener(this); this.wwd.getInputHandler().addMouseMotionListener(this); this.wwd.addPositionListener(this); } } - protected PickedObject getTopOwnedControlPoint() - { - if (this.getEditor() == null) - { + protected PickedObject getTopOwnedControlPoint() { + if (this.getEditor() == null) { return null; } - if (this.getWorldWindow().getSceneController().getPickedObjectList() == null) - { + if (this.getWorldWindow().getSceneController().getPickedObjectList() == null) { return null; } PickedObject topObject = this.getWorldWindow().getSceneController().getPickedObjectList().getTopPickedObject(); - if (topObject == null || !(topObject.getObject() instanceof SegmentPlane.ControlPoint)) - { + if (topObject == null || !(topObject.getObject() instanceof SegmentPlane.ControlPoint)) { return null; } SegmentPlane.ControlPoint controlPoint = (SegmentPlane.ControlPoint) topObject.getObject(); - if (controlPoint.getOwner() != this.getEditor().getSegmentPlane()) - { + if (controlPoint.getOwner() != this.getEditor().getSegmentPlane()) { return null; } @@ -115,11 +101,8 @@ protected PickedObject getTopOwnedControlPoint() //**************************************************************// //******************** Mouse Events **************************// //**************************************************************// - - public void mouseClicked(MouseEvent e) - { - if (e == null) - { + public void mouseClicked(MouseEvent e) { + if (e == null) { return; } @@ -127,25 +110,20 @@ public void mouseClicked(MouseEvent e) this.updateAttributes(); } - public void mousePressed(MouseEvent e) - { - if (e == null) - { + public void mousePressed(MouseEvent e) { + if (e == null) { return; } // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return; } PickedObject pickedObject = this.getTopOwnedControlPoint(); - if (e.getButton() == MouseEvent.BUTTON1) - { - if (pickedObject != null) - { + if (e.getButton() == MouseEvent.BUTTON1) { + if (pickedObject != null) { this.active = true; this.activePickedObject = pickedObject; e.consume(); @@ -156,23 +134,18 @@ public void mousePressed(MouseEvent e) this.updateAttributes(); } - public void mouseReleased(MouseEvent e) - { - if (e == null) - { + public void mouseReleased(MouseEvent e) { + if (e == null) { return; } // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return; } - if (e.getButton() == MouseEvent.BUTTON1) - { - if (this.active) - { + if (e.getButton() == MouseEvent.BUTTON1) { + if (this.active) { this.active = false; this.activePickedObject = null; e.consume(); @@ -183,22 +156,17 @@ public void mouseReleased(MouseEvent e) this.updateAttributes(); } - public void mouseEntered(MouseEvent e) - { + public void mouseEntered(MouseEvent e) { } - public void mouseExited(MouseEvent e) - { + public void mouseExited(MouseEvent e) { } //**************************************************************// //******************** Mouse Motion Events *******************// //**************************************************************// - - public void mouseDragged(MouseEvent e) - { - if (e == null) - { + public void mouseDragged(MouseEvent e) { + if (e == null) { return; } @@ -206,15 +174,12 @@ public void mouseDragged(MouseEvent e) this.mousePoint = new Point(e.getPoint()); // copy to insulate us from changes by the caller // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return; } - if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) - { - if (this.active) - { + if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { + if (this.active) { // Don't update the segment plane here because the WorldWindow current cursor position will not have // been updated to reflect the current mouse position. Wait to update in the position listener, but // consume the event so the View doesn't respond to it. @@ -226,10 +191,8 @@ public void mouseDragged(MouseEvent e) this.updateAttributes(); } - public void mouseMoved(MouseEvent e) - { - if (e == null) - { + public void mouseMoved(MouseEvent e) { + if (e == null) { return; } @@ -243,22 +206,17 @@ public void mouseMoved(MouseEvent e) //**************************************************************// //******************** Position Events ***********************// //**************************************************************// - - public void moved(PositionEvent e) - { - if (e == null) - { + public void moved(PositionEvent e) { + if (e == null) { return; } // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return; } - if (this.activePickedObject != null) - { + if (this.activePickedObject != null) { this.handleObjectMoved(this.activePickedObject, e.getScreenPoint(), this.lastMousePoint); } @@ -266,61 +224,48 @@ public void moved(PositionEvent e) this.updateAttributes(); } - protected void handleObjectMoved(PickedObject object, Point mousePoint, Point lastMousePoint) - { + protected void handleObjectMoved(PickedObject object, Point mousePoint, Point lastMousePoint) { this.getEditor().moveControlPoint(this.getWorldWindow(), object, mousePoint, lastMousePoint); } //**************************************************************// //******************** Action/Cursor Pairing *****************// //**************************************************************// - - protected void updateAttributes() - { - if (this.getEditor() == null) - { + protected void updateAttributes() { + if (this.getEditor() == null) { return; } - if (this.lastAttributes == null) - { + if (this.lastAttributes == null) { this.lastAttributes = this.getEditor().getSegmentPlane().getAttributes(); } SegmentPlaneAttributes actionAttributes = this.getAttributesFor(this.lastAttributes); - if (actionAttributes != null) - { + if (actionAttributes != null) { this.getEditor().getSegmentPlane().setAttributes(actionAttributes); - } - else - { + } else { this.getEditor().getSegmentPlane().setAttributes(this.lastAttributes); this.lastAttributes = null; } } - protected void updateCursor() - { + protected void updateCursor() { Cursor cursor = this.getCursor(); - if (this.wwd instanceof Component) - { + if (this.wwd instanceof Component) { ((Component) this.wwd).setCursor(cursor); } } - protected SegmentPlaneAttributes getAttributesFor(SegmentPlaneAttributes attributes) - { + protected SegmentPlaneAttributes getAttributesFor(SegmentPlaneAttributes attributes) { // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return null; } PickedObject pickedObject = this.isActive() ? this.activePickedObject : this.getTopOwnedControlPoint(); - if (pickedObject == null) - { + if (pickedObject == null) { return null; } @@ -330,16 +275,14 @@ protected SegmentPlaneAttributes getAttributesFor(SegmentPlaneAttributes attribu SegmentPlaneAttributes.GeometryAttributes geometryAttributes = newAttributes.getGeometryAttributes(controlPoint.getKey()); SegmentPlaneAttributes.LabelAttributes labelAttributes = newAttributes.getLabelAttributes(controlPoint.getKey()); - if (geometryAttributes != null) - { + if (geometryAttributes != null) { Color actionColor = makeBrighter(geometryAttributes.getMaterial().getDiffuse()); geometryAttributes.setMaterial(new Material(actionColor)); geometryAttributes.setSize(1.2 * geometryAttributes.getSize()); geometryAttributes.setPickSize(1.2 * geometryAttributes.getPicksize()); } - if (labelAttributes != null) - { + if (labelAttributes != null) { Font actionFont = labelAttributes.getFont().deriveFont(Font.BOLD); labelAttributes.setFont(actionFont); } @@ -347,29 +290,22 @@ protected SegmentPlaneAttributes getAttributesFor(SegmentPlaneAttributes attribu return newAttributes; } - protected Cursor getCursor() - { + protected Cursor getCursor() { // If we're actively engaged in some action, then return the cursor associated with that action. Otherwise // return the cursor representing the action that would be invoked (if the user pressed the mouse) given the // curent modifiers and pick list. // Include this test to ensure any derived implementation performs it. - if (this.getEditor() == null || !this.getEditor().isArmed()) - { + if (this.getEditor() == null || !this.getEditor().isArmed()) { return null; } - if (this.active) - { - if (this.activePickedObject != null) - { + if (this.active) { + if (this.activePickedObject != null) { return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } - } - else - { - if (this.getTopOwnedControlPoint() != null) - { + } else { + if (this.getTopOwnedControlPoint() != null) { return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } } @@ -377,8 +313,7 @@ protected Cursor getCursor() return null; } - private static Color makeBrighter(Color color) - { + private static Color makeBrighter(Color color) { float[] hsbComponents = new float[3]; Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsbComponents); float hue = hsbComponents[0]; @@ -388,11 +323,13 @@ private static Color makeBrighter(Color color) saturation /= 3f; brightness *= 3f; - if (saturation < 0f) + if (saturation < 0f) { saturation = 0f; + } - if (brightness > 1f) + if (brightness > 1f) { brightness = 1f; + } int rgbInt = Color.HSBtoRGB(hue, saturation, brightness); diff --git a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneEditor.java b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneEditor.java index 351c8301df..82b5931753 100644 --- a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneEditor.java +++ b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneEditor.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: SegmentPlaneEditor.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SegmentPlaneEditor extends AbstractLayer -{ +public class SegmentPlaneEditor extends AbstractLayer { + protected static final int SEGMENT_BEGIN_INDEX = 0; protected static final int SEGMENT_END_INDEX = 1; @@ -31,104 +31,91 @@ public class SegmentPlaneEditor extends AbstractLayer private SegmentPlane segmentPlane; // Can be null. private SegmentPlaneRenderer renderer; // Can be null. - public SegmentPlaneEditor() - { + public SegmentPlaneEditor() { this.armed = false; this.snapToGrid = true; this.renderer = new SegmentPlaneRenderer(); } - public boolean isArmed() - { + public boolean isArmed() { return this.armed; } - public void setArmed(boolean armed) - { + public void setArmed(boolean armed) { this.armed = armed; } - public boolean isSnapToGrid() - { + public boolean isSnapToGrid() { return this.snapToGrid; } - public void setSnapToGrid(boolean snapToGrid) - { + public void setSnapToGrid(boolean snapToGrid) { this.snapToGrid = snapToGrid; } - public SegmentPlane getSegmentPlane() - { + public SegmentPlane getSegmentPlane() { return this.segmentPlane; } - public void setSegmentPlane(SegmentPlane segmentPlane) - { + public void setSegmentPlane(SegmentPlane segmentPlane) { this.segmentPlane = segmentPlane; } - public SegmentPlaneRenderer getSegmentPlaneRenderer() - { + public SegmentPlaneRenderer getSegmentPlaneRenderer() { return this.renderer; } - public void setSegmentPlaneRenderer(SegmentPlaneRenderer renderer) - { + public void setSegmentPlaneRenderer(SegmentPlaneRenderer renderer) { this.renderer = renderer; } - protected void doRender(DrawContext dc) - { - if (!this.isArmed()) + protected void doRender(DrawContext dc) { + if (!this.isArmed()) { return; + } - if (this.getSegmentPlane() == null || this.getSegmentPlaneRenderer() == null) + if (this.getSegmentPlane() == null || this.getSegmentPlaneRenderer() == null) { return; + } this.getSegmentPlaneRenderer().render(dc, this.getSegmentPlane()); } - protected void doPick(DrawContext dc, java.awt.Point pickPoint) - { - if (!this.isArmed()) + protected void doPick(DrawContext dc, java.awt.Point pickPoint) { + if (!this.isArmed()) { return; + } - if (this.getSegmentPlane() == null || this.getSegmentPlaneRenderer() == null) + if (this.getSegmentPlane() == null || this.getSegmentPlaneRenderer() == null) { return; + } this.getSegmentPlaneRenderer().pick(dc, this.getSegmentPlane(), pickPoint, this); } - public void moveControlPoint(WorldWindow wwd, PickedObject pickedObject, Point mousePoint, Point previousMousePoint) - { - if (wwd == null) - { + public void moveControlPoint(WorldWindow wwd, PickedObject pickedObject, Point mousePoint, Point previousMousePoint) { + if (wwd == null) { String message = Logging.getMessage("nullValue.WorldWindow"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (pickedObject == null) - { + if (pickedObject == null) { String message = Logging.getMessage("nullValue.PickedObject"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } // Include this test to ensure any derived implementation performs it. - if (this.getSegmentPlane() == null) - { + if (this.getSegmentPlane() == null) { return; } - if (!(pickedObject.getObject() instanceof SegmentPlane.ControlPoint)) - { + if (!(pickedObject.getObject() instanceof SegmentPlane.ControlPoint)) { return; } SegmentPlane.ControlPoint controlPoint = (SegmentPlane.ControlPoint) pickedObject.getObject(); - if (this.getSegmentPlane() != controlPoint.getOwner()) - { + if (this.getSegmentPlane() != controlPoint.getOwner()) { return; } @@ -136,35 +123,24 @@ public void moveControlPoint(WorldWindow wwd, PickedObject pickedObject, Point m } protected void doMoveControlPoint(WorldWindow wwd, PickedObject pickedObject, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { SegmentPlane.ControlPoint controlPoint = (SegmentPlane.ControlPoint) pickedObject.getObject(); Object key = controlPoint.getKey(); - if (key == null) - { + if (key == null) { return; } - if (key.equals(SegmentPlane.SEGMENT_BEGIN) || key.equals(SegmentPlane.SEGMENT_END)) - { + if (key.equals(SegmentPlane.SEGMENT_BEGIN) || key.equals(SegmentPlane.SEGMENT_END)) { this.doMoveSegmentPoint(wwd, pickedObject, mousePoint, previousMousePoint); - } - else if (key.equals(SegmentPlane.CONTROL_POINT_LOWER_LEFT)) - { + } else if (key.equals(SegmentPlane.CONTROL_POINT_LOWER_LEFT)) { this.doMoveSegmentPlane(wwd, pickedObject, mousePoint, previousMousePoint); - } - else if (key.equals(SegmentPlane.CONTROL_POINT_LOWER_RIGHT) - || key.equals(SegmentPlane.CONTROL_POINT_UPPER_RIGHT)) - { + } else if (key.equals(SegmentPlane.CONTROL_POINT_LOWER_RIGHT) + || key.equals(SegmentPlane.CONTROL_POINT_UPPER_RIGHT)) { this.doMoveLateralControlPoint(wwd, pickedObject, mousePoint, previousMousePoint); - } - else if (key.equals(SegmentPlane.CONTROL_POINT_TOP_EDGE)) - { + } else if (key.equals(SegmentPlane.CONTROL_POINT_TOP_EDGE)) { this.doMoveVerticalControlPoint(wwd, pickedObject, mousePoint, previousMousePoint); - } - else if (key.equals(SegmentPlane.CONTROL_POINT_LEADING_EDGE)) - { + } else if (key.equals(SegmentPlane.CONTROL_POINT_LEADING_EDGE)) { this.doMoveHorizontalControlPoint(wwd, pickedObject, mousePoint, previousMousePoint); } } @@ -172,10 +148,8 @@ else if (key.equals(SegmentPlane.CONTROL_POINT_LEADING_EDGE)) //**************************************************************// //******************** Segment Plane Movement ****************// //**************************************************************// - protected void doMoveSegmentPlane(WorldWindow wwd, PickedObject pickedObject, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { View view = wwd.getView(); Globe globe = wwd.getModel().getGlobe(); LatLon[] locations = this.getSegmentPlane().getPlaneLocations(); @@ -193,15 +167,15 @@ protected void doMoveSegmentPlane(WorldWindow wwd, PickedObject pickedObject, // Find intersection of screen coord ref-point with globe. double x = screenRefPoint.x + dx; double y = screenRefPoint.y + dy; - if (wwd instanceof Component) - { + if (wwd instanceof Component) { y = ((Component) wwd).getSize().height - screenRefPoint.y + dy - 1; } Line ray = view.computeRayFromScreenPoint(x, y); Intersection[] intersections = globe.intersect(ray, refPos.getElevation()); - if (intersections == null || intersections.length == 0) + if (intersections == null || intersections.length == 0) { return; + } Position newPos = globe.computePositionFromPoint(intersections[0].getIntersectionPoint()); @@ -219,27 +193,22 @@ protected void doMoveSegmentPlane(WorldWindow wwd, PickedObject pickedObject, //**************************************************************// //******************** Segment Point Actions *****************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) protected void doMoveSegmentPoint(WorldWindow wwd, PickedObject pickedObject, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { Position oldPosition = pickedObject.getPosition(); Position newPosition = this.computeNewPositionFromPlaneGeometry(wwd); // If the mouse point is not on the plane geometry, we compute an intersection with the infinite plane // defined by the SegmentPlane's corners. - if (newPosition == null) - { - newPosition = this.computeNewPositionFromPlaneIntersection(wwd, mousePoint); - if (newPosition != null) - { + if (newPosition == null) { + newPosition = this.computeNewPositionFromPlaneIntersection(wwd, mousePoint); + if (newPosition != null) { newPosition = this.resizeSegmentPlaneToFitPosition(wwd, newPosition); } } - if (newPosition == null) - { + if (newPosition == null) { return; } @@ -248,72 +217,59 @@ protected void doMoveSegmentPoint(WorldWindow wwd, PickedObject pickedObject, Position[] positions = this.getSegmentPlane().getSegmentPositions(); Object endpointId = pickedObject.getValue(AVKey.PICKED_OBJECT_ID); - if (endpointId.equals(SegmentPlane.SEGMENT_BEGIN)) - { + if (endpointId.equals(SegmentPlane.SEGMENT_BEGIN)) { positions[0] = new Position(oldPosition, newPosition.getElevation()); - } - else if (endpointId.equals(SegmentPlane.SEGMENT_END)) - { + } else if (endpointId.equals(SegmentPlane.SEGMENT_END)) { positions[1] = newPosition; } this.getSegmentPlane().setSegmentPositions(positions[0], positions[1]); } - protected Position computeNewPositionFromPlaneGeometry(WorldWindow wwd) - { - if (this.isSnapToGrid()) - { + protected Position computeNewPositionFromPlaneGeometry(WorldWindow wwd) { + if (this.isSnapToGrid()) { PickedObject gridObject = this.getPickedSegmentPlaneObject(wwd, SegmentPlane.PLANE_GRID); - if (gridObject != null) - { + if (gridObject != null) { return gridObject.getPosition(); } } PickedObject planeObject = this.getPickedSegmentPlaneObject(wwd, SegmentPlane.PLANE_BACKGROUND); - if (planeObject != null) - { + if (planeObject != null) { return planeObject.getPosition(); } return null; } - protected Position computeNewPositionFromPlaneIntersection(WorldWindow wwd, Point mousePoint) - { + protected Position computeNewPositionFromPlaneIntersection(WorldWindow wwd, Point mousePoint) { View view = wwd.getView(); Globe globe = wwd.getModel().getGlobe(); - + Line ray = view.computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); Plane plane = this.getSegmentPlane().computeInfinitePlane(globe); - if (plane == null) - { + if (plane == null) { return null; } Vec4 newPoint = plane.intersect(ray); - if (newPoint == null) - { + if (newPoint == null) { return null; } return globe.computePositionFromPoint(newPoint); } - protected Position resizeSegmentPlaneToFitPosition(WorldWindow wwd, Position position) - { + protected Position resizeSegmentPlaneToFitPosition(WorldWindow wwd, Position position) { Globe globe = wwd.getModel().getGlobe(); double[] altitudes = this.getSegmentPlane().getPlaneAltitudes(); double[] gridSizes = this.getSegmentPlane().getGridCellDimensions(); LatLon[] locations = this.getSegmentPlane().getPlaneLocations(); - if (position.getElevation() < altitudes[0]) - { + if (position.getElevation() < altitudes[0]) { altitudes[0] = altitudes[0] + this.getNextGridStep(position.getElevation(), altitudes[0], gridSizes[1]); } - if (position.getElevation() > altitudes[1]) - { + if (position.getElevation() > altitudes[1]) { altitudes[1] = altitudes[0] + this.getNextGridStep(position.getElevation(), altitudes[0], gridSizes[1]); } @@ -328,17 +284,15 @@ protected Position resizeSegmentPlaneToFitPosition(WorldWindow wwd, Position pos double dot = p.dot3(n); // Resize only in the positive direction. - if (dot > length) - { + if (dot > length) { double nextLength = this.getNextGridStep(dot, 0.0, gridSizes[0]); Vec4 nextPoint = segment[0].add3(n.multiply3(nextLength)); locations[1] = new LatLon(globe.computePositionFromPoint(nextPoint)); } - if (dot < 0.0) - { + if (dot < 0.0) { position = new Position(locations[0], position.getElevation()); } - + this.getSegmentPlane().setPlaneAltitudes(altitudes[0], altitudes[1]); this.getSegmentPlane().setPlaneLocations(locations[0], locations[1]); @@ -348,11 +302,9 @@ protected Position resizeSegmentPlaneToFitPosition(WorldWindow wwd, Position pos //**************************************************************// //******************** Segment Plane Orientation/Length ******// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) protected void doMoveLateralControlPoint(WorldWindow wwd, PickedObject pickedObject, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { View view = wwd.getView(); Globe globe = wwd.getModel().getGlobe(); double[] altitudes = this.getSegmentPlane().getPlaneAltitudes(); @@ -361,16 +313,16 @@ protected void doMoveLateralControlPoint(WorldWindow wwd, PickedObject pickedObj Position pos = pickedObject.getPosition(); Line ray = view.computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); Intersection[] intersection = globe.intersect(ray, pos.getElevation()); - if (intersection == null || intersection.length < 0) + if (intersection == null || intersection.length < 0) { return; + } Vec4 newPoint = intersection[0].getIntersectionPoint(); LatLon newLatLon = new LatLon(globe.computePositionFromPoint(newPoint)); Object id = pickedObject.getValue(AVKey.PICKED_OBJECT_ID); if (id.equals(SegmentPlane.CONTROL_POINT_LOWER_RIGHT) - ||id.equals(SegmentPlane.CONTROL_POINT_UPPER_RIGHT)) - { + || id.equals(SegmentPlane.CONTROL_POINT_UPPER_RIGHT)) { locations[1] = newLatLon; this.moveSegmentLocationWithPlane(locations, SEGMENT_END_INDEX); } @@ -381,11 +333,9 @@ protected void doMoveLateralControlPoint(WorldWindow wwd, PickedObject pickedObj //**************************************************************// //******************** Segment Plane Height ******************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) protected void doMoveVerticalControlPoint(WorldWindow wwd, PickedObject pickedObject, - Point mousePoint, Point previousMousePoint) - { + Point mousePoint, Point previousMousePoint) { View view = wwd.getView(); Globe globe = wwd.getModel().getGlobe(); double[] altitudes = this.getSegmentPlane().getPlaneAltitudes(); @@ -403,13 +353,14 @@ protected void doMoveVerticalControlPoint(WorldWindow wwd, PickedObject pickedOb altitudes[1] = newPos.getElevation(); - if (altitudes[1] < altitudes[0]) + if (altitudes[1] < altitudes[0]) { altitudes[1] = altitudes[0]; + } - for (int i = 0; i < 2; i++) - { - if (altitudes[1] < segmentPositions[i].getElevation()) + for (int i = 0; i < 2; i++) { + if (altitudes[1] < segmentPositions[i].getElevation()) { altitudes[1] = segmentPositions[i].getElevation(); + } } this.getSegmentPlane().setPlaneAltitudes(altitudes[0], altitudes[1]); @@ -418,11 +369,9 @@ protected void doMoveVerticalControlPoint(WorldWindow wwd, PickedObject pickedOb //**************************************************************// //******************** Segment Plane Length ******************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) - protected void doMoveHorizontalControlPoint(WorldWindow wwd, PickedObject pickedObject, - Point mousePoint, Point previousMousePoint) - { + protected void doMoveHorizontalControlPoint(WorldWindow wwd, PickedObject pickedObject, + Point mousePoint, Point previousMousePoint) { View view = wwd.getView(); Globe globe = wwd.getModel().getGlobe(); LatLon[] locations = this.getSegmentPlane().getPlaneLocations(); @@ -431,8 +380,9 @@ protected void doMoveHorizontalControlPoint(WorldWindow wwd, PickedObject picked Position pos = pickedObject.getPosition(); Line ray = view.computeRayFromScreenPoint(mousePoint.getX(), mousePoint.getY()); Intersection[] intersection = globe.intersect(ray, pos.getElevation()); - if (intersection == null || intersection.length < 0) + if (intersection == null || intersection.length < 0) { return; + } Vec4 newPoint = intersection[0].getIntersectionPoint(); LatLon newLatLon = new LatLon(globe.computePositionFromPoint(newPoint)); @@ -441,8 +391,9 @@ protected void doMoveHorizontalControlPoint(WorldWindow wwd, PickedObject picked Angle distance = LatLon.rhumbDistance(locations[0], newLatLon); Angle minDistance = LatLon.rhumbDistance(locations[0], segmentPositions[1]); - if (distance.compareTo(minDistance) < 0) + if (distance.compareTo(minDistance) < 0) { distance = minDistance; + } locations[1] = LatLon.rhumbEndPosition(locations[0], heading, distance); @@ -452,41 +403,37 @@ protected void doMoveHorizontalControlPoint(WorldWindow wwd, PickedObject picked //**************************************************************// //******************** Utility Methods ***********************// //**************************************************************// - - protected Position moveSegmentAltitudeWithPlane(Position position, double[] minAndMaxElevation) - { + protected Position moveSegmentAltitudeWithPlane(Position position, double[] minAndMaxElevation) { double elevation = position.getElevation(); - if (elevation >= minAndMaxElevation[0] && elevation <= minAndMaxElevation[1]) - { + if (elevation >= minAndMaxElevation[0] && elevation <= minAndMaxElevation[1]) { return null; } - if (elevation < minAndMaxElevation[0]) + if (elevation < minAndMaxElevation[0]) { elevation = minAndMaxElevation[0]; - if (elevation > minAndMaxElevation[1]) + } + if (elevation > minAndMaxElevation[1]) { elevation = minAndMaxElevation[1]; + } return new Position(position, elevation); } - - protected void moveSegmentLocationWithPlane(LatLon[] newPlaneLocations, int segmentPositionIndex) - { + + protected void moveSegmentLocationWithPlane(LatLon[] newPlaneLocations, int segmentPositionIndex) { LatLon[] planeLocations = this.getSegmentPlane().getPlaneLocations(); Position segmentPosition = this.getSegmentPlane().getSegmentPositions()[segmentPositionIndex]; - if (segmentPositionIndex == SEGMENT_BEGIN_INDEX) - { + if (segmentPositionIndex == SEGMENT_BEGIN_INDEX) { Position newSegmentPosition = new Position(newPlaneLocations[0], segmentPosition.getElevation()); this.getSegmentPlane().setSegmentBeginPosition(newSegmentPosition); - } - else if (segmentPositionIndex == SEGMENT_END_INDEX) - { + } else if (segmentPositionIndex == SEGMENT_END_INDEX) { Angle newHeading = LatLon.rhumbAzimuth(newPlaneLocations[0], newPlaneLocations[1]); Angle distance = LatLon.rhumbDistance(planeLocations[0], segmentPosition); Angle maxDistance = LatLon.rhumbDistance(newPlaneLocations[0], newPlaneLocations[1]); - if (distance.compareTo(maxDistance) > 0) + if (distance.compareTo(maxDistance) > 0) { distance = maxDistance; + } LatLon newLatLon = LatLon.rhumbEndPosition(newPlaneLocations[0], newHeading, distance); Position newSegmentPosition = new Position(newLatLon, segmentPosition.getElevation()); @@ -495,20 +442,15 @@ else if (segmentPositionIndex == SEGMENT_END_INDEX) } } - protected PickedObject getPickedSegmentPlaneObject(WorldWindow wwd, Object pickedObjectId) - { - if (wwd.getSceneController().getPickedObjectList() == null) - { + protected PickedObject getPickedSegmentPlaneObject(WorldWindow wwd, Object pickedObjectId) { + if (wwd.getSceneController().getPickedObjectList() == null) { return null; } - for (PickedObject po : wwd.getSceneController().getPickedObjectList()) - { - if (po != null && po.getObject() == this.getSegmentPlane()) - { + for (PickedObject po : wwd.getSceneController().getPickedObjectList()) { + if (po != null && po.getObject() == this.getSegmentPlane()) { Object id = po.getValue(AVKey.PICKED_OBJECT_ID); - if (id == pickedObjectId) - { + if (id == pickedObjectId) { return po; } } @@ -517,30 +459,28 @@ protected PickedObject getPickedSegmentPlaneObject(WorldWindow wwd, Object picke return null; } - protected Position computePositionOnOrAboveSurface(WorldWindow wwd, Position position) - { - if (wwd.getSceneController().getTerrain() != null) - { + protected Position computePositionOnOrAboveSurface(WorldWindow wwd, Position position) { + if (wwd.getSceneController().getTerrain() != null) { Vec4 point = wwd.getSceneController().getTerrain().getSurfacePoint( - position.getLatitude(), position.getLongitude()); - if (point != null) - { + position.getLatitude(), position.getLongitude()); + if (point != null) { Position pos = wwd.getModel().getGlobe().computePositionFromPoint(point); - if (position.getElevation() < pos.getElevation()) + if (position.getElevation() < pos.getElevation()) { return new Position(position, pos.getElevation()); + } return position; } } double elev = wwd.getModel().getGlobe().getElevation(position.getLatitude(), position.getLongitude()); - if (position.getElevation() < elev) + if (position.getElevation() < elev) { return new Position(position, elev); + } return position; } - protected double getNextGridStep(double value, double origin, double gridSize) - { + protected double getNextGridStep(double value, double origin, double gridSize) { double x = Math.ceil((value - origin) / gridSize); return gridSize * x; } diff --git a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneRenderer.java b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneRenderer.java index afd736514c..510d148861 100644 --- a/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneRenderer.java +++ b/src/gov/nasa/worldwindx/applications/sar/segmentplane/SegmentPlaneRenderer.java @@ -26,10 +26,10 @@ * @author dcollins * @version $Id: SegmentPlaneRenderer.java 2053 2014-06-10 20:16:57Z tgaskins $ */ -public class SegmentPlaneRenderer -{ - protected static class RenderInfo - { +public class SegmentPlaneRenderer { + + protected static class RenderInfo { + protected Globe globe; protected Object segmentPlaneKey; @@ -55,31 +55,28 @@ protected static class RenderInfo // Control point geometric properties. protected Map markerShapeMap; - public boolean isExpired(Globe globe, SegmentPlane segmentPlane) - { + public boolean isExpired(Globe globe, SegmentPlane segmentPlane) { return this.globe == null - || this.segmentPlaneKey == null - || !this.globe.equals(globe) - || !this.segmentPlaneKey.equals(segmentPlane.getStateKey()); + || this.segmentPlaneKey == null + || !this.globe.equals(globe) + || !this.segmentPlaneKey.equals(segmentPlane.getStateKey()); } - public void makeCurrent(Globe globe, SegmentPlane segmentPlane) - { + public void makeCurrent(Globe globe, SegmentPlane segmentPlane) { this.globe = globe; this.segmentPlaneKey = segmentPlane.getStateKey(); } - public MarkerShape getMarkerShape(String shapeType) - { - if (shapeType == null) + public MarkerShape getMarkerShape(String shapeType) { + if (shapeType == null) { return null; + } MarkerShape shape = this.markerShapeMap.get(shapeType); // The shapeType may point to a null reference in the map. If that's the case, then do not try to create // that shape, just return a null reference. - if (shape == null && !this.markerShapeMap.containsKey(shapeType)) - { + if (shape == null && !this.markerShapeMap.containsKey(shapeType)) { shape = BasicMarkerShape.createShapeInstance(shapeType); this.markerShapeMap.put(shapeType, shape); } @@ -88,14 +85,13 @@ public MarkerShape getMarkerShape(String shapeType) } } - protected static class ControlPointInfo - { + protected static class ControlPointInfo { + protected SegmentPlane.ControlPoint controlPoint; protected Position position; protected MarkerShape shape; - public ControlPointInfo(SegmentPlane.ControlPoint controlPoint, Position position, MarkerShape shape) - { + public ControlPointInfo(SegmentPlane.ControlPoint controlPoint, Position position, MarkerShape shape) { this.controlPoint = controlPoint; this.position = position; this.shape = shape; @@ -107,20 +103,16 @@ public ControlPointInfo(SegmentPlane.ControlPoint controlPoint, Position positio protected double maxObjectSizeCoefficient = 0.005; protected final PickSupport pickSupport = new PickSupport(); - public SegmentPlaneRenderer() - { + public SegmentPlaneRenderer() { this.renderInfoMap = new HashMap(); } - public double getMinObjectSize() - { + public double getMinObjectSize() { return minObjectSize; } - public void setMinObjectSize(double size) - { - if (size < 0) - { + public void setMinObjectSize(double size) { + if (size < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "size < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -129,15 +121,12 @@ public void setMinObjectSize(double size) this.minObjectSize = size; } - public double getMaxObjectSizeCoefficient() - { + public double getMaxObjectSizeCoefficient() { return this.maxObjectSizeCoefficient; } - public void setMaxObjectSizeCoefficient(double coefficient) - { - if (coefficient < 0) - { + public void setMaxObjectSizeCoefficient(double coefficient) { + if (coefficient < 0) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "coefficient < 0"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -146,16 +135,13 @@ public void setMaxObjectSizeCoefficient(double coefficient) this.maxObjectSizeCoefficient = coefficient; } - public void render(DrawContext dc, SegmentPlane segmentPlane) - { - if (dc == null) - { + public void render(DrawContext dc, SegmentPlane segmentPlane) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (segmentPlane == null) - { + if (segmentPlane == null) { String message = Logging.getMessage("nullValue.SegmentPlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -164,51 +150,41 @@ public void render(DrawContext dc, SegmentPlane segmentPlane) this.draw(dc, segmentPlane, null, null); } - public void pick(DrawContext dc, SegmentPlane segmentPlane, java.awt.Point pickPoint, Layer layer) - { - if (dc == null) - { + public void pick(DrawContext dc, SegmentPlane segmentPlane, java.awt.Point pickPoint, Layer layer) { + if (dc == null) { String message = Logging.getMessage("nullValue.DrawContextIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (segmentPlane == null) - { + if (segmentPlane == null) { String message = Logging.getMessage("nullValue.SegmentPlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.pickSupport.beginPicking(dc); - try - { + try { this.draw(dc, segmentPlane, pickPoint, layer); - } - finally - { + } finally { this.pickSupport.endPicking(dc); this.pickSupport.clearPickList(); } } - public Vec4 intersect(Globe globe, Line ray, SegmentPlane segmentPlane) - { - if (ray == null) - { + public Vec4 intersect(Globe globe, Line ray, SegmentPlane segmentPlane) { + if (ray == null) { String message = Logging.getMessage("nullValue.LineIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (segmentPlane == null) - { + if (segmentPlane == null) { String message = Logging.getMessage("nullValue.SegmentPlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } RenderInfo renderInfo = this.getRenderInfoFor(globe, segmentPlane); - if (renderInfo == null) - { + if (renderInfo == null) { return null; } @@ -216,22 +192,18 @@ public Vec4 intersect(Globe globe, Line ray, SegmentPlane segmentPlane) } public Position computeControlPointPosition(SectorGeometryList sgl, Globe globe, SegmentPlane segmentPlane, - SegmentPlane.ControlPoint controlPoint) - { - if (globe == null) - { + SegmentPlane.ControlPoint controlPoint) { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (segmentPlane == null) - { + if (segmentPlane == null) { String message = Logging.getMessage("nullValue.SegmentPlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (controlPoint == null) - { + if (controlPoint == null) { String message = Logging.getMessage("nullValue.ControlPointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -239,37 +211,31 @@ public Position computeControlPointPosition(SectorGeometryList sgl, Globe globe, double[] coords = controlPoint.getCoordinates(); return this.computePositionOnPlane(sgl, globe, segmentPlane, coords[0], coords[1], - controlPoint.isRelativeToSurface()); + controlPoint.isRelativeToSurface()); } - public double computeObjectSize(View view, Globe globe, SegmentPlane segmentPlane, Object key, Vec4 point) - { - if (view == null) - { + public double computeObjectSize(View view, Globe globe, SegmentPlane segmentPlane, Object key, Vec4 point) { + if (view == null) { String message = Logging.getMessage("nullValue.ViewIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (globe == null) - { + if (globe == null) { String message = Logging.getMessage("nullValue.GlobeIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (segmentPlane == null) - { + if (segmentPlane == null) { String message = Logging.getMessage("nullValue.SegmentPlaneIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (key == null) - { + if (key == null) { String message = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (point == null) - { + if (point == null) { String message = Logging.getMessage("nullValue.PointIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -278,13 +244,12 @@ public double computeObjectSize(View view, Globe globe, SegmentPlane segmentPlan return this.computeObjectSize(view, globe, segmentPlane, key, point, false); } - protected RenderInfo getRenderInfoFor(Globe globe, SegmentPlane segmentPlane) - { + protected RenderInfo getRenderInfoFor(Globe globe, SegmentPlane segmentPlane) { RenderInfo renderInfo = this.renderInfoMap.get(segmentPlane); - if (renderInfo == null || renderInfo.isExpired(globe, segmentPlane)) - { - if (renderInfo == null) + if (renderInfo == null || renderInfo.isExpired(globe, segmentPlane)) { + if (renderInfo == null) { renderInfo = new RenderInfo(); + } this.createSegmentPlaneGeometry(globe, segmentPlane, renderInfo); this.createBorderGeometry(globe, segmentPlane, renderInfo); this.createControlPointGeometry(globe, segmentPlane, renderInfo); @@ -296,35 +261,30 @@ protected RenderInfo getRenderInfoFor(Globe globe, SegmentPlane segmentPlane) return renderInfo; } - protected MultiLineTextRenderer getTextRendererFor(DrawContext dc, Font font) - { + protected MultiLineTextRenderer getTextRendererFor(DrawContext dc, Font font) { TextRenderer tr = OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), font); return new MultiLineTextRenderer(tr); } - protected void draw(DrawContext dc, SegmentPlane segmentPlane, java.awt.Point pickPoint, Layer layer) - { - if (!segmentPlane.isVisible()) + protected void draw(DrawContext dc, SegmentPlane segmentPlane, java.awt.Point pickPoint, Layer layer) { + if (!segmentPlane.isVisible()) { return; + } RenderInfo renderInfo = this.getRenderInfoFor(dc.getGlobe(), segmentPlane); OGLStackHandler ogsh = new OGLStackHandler(); this.begin(dc, ogsh); - try - { + try { this.drawSegmentPlane(dc, segmentPlane, renderInfo, pickPoint, layer); - } - finally - { + } finally { this.end(dc, ogsh); } } protected void drawSegmentPlane(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { this.drawPlaneGeometry(dc, segmentPlane, renderInfo, pickPoint, layer); this.drawPlaneBorder(dc, segmentPlane, renderInfo, pickPoint, layer); this.drawSegmentAltimeter(dc, segmentPlane, renderInfo, pickPoint, layer); @@ -332,25 +292,23 @@ protected void drawSegmentPlane(DrawContext dc, SegmentPlane segmentPlane, Rende this.drawAxisLabels(dc, segmentPlane, renderInfo, pickPoint, layer); } - protected void begin(DrawContext dc, OGLStackHandler ogsh) - { + protected void begin(DrawContext dc, OGLStackHandler ogsh) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); gl.glEnableClientState(GL2.GL_NORMAL_ARRAY); - int attribMask = GL2.GL_CURRENT_BIT // For current RGBA color. - | GL2.GL_LINE_BIT // For line width. - | GL2.GL_POLYGON_BIT // For cull face, polygon offset. - | (!dc.isPickingMode() ? GL2.GL_COLOR_BUFFER_BIT : 0) // for blend func - | (!dc.isPickingMode() ? GL2.GL_LIGHTING_BIT : 0) // for lighting. - | (!dc.isPickingMode() ? GL2.GL_TRANSFORM_BIT : 0); // for normalize state. + int attribMask = GL2.GL_CURRENT_BIT // For current RGBA color. + | GL2.GL_LINE_BIT // For line width. + | GL2.GL_POLYGON_BIT // For cull face, polygon offset. + | (!dc.isPickingMode() ? GL2.GL_COLOR_BUFFER_BIT : 0) // for blend func + | (!dc.isPickingMode() ? GL2.GL_LIGHTING_BIT : 0) // for lighting. + | (!dc.isPickingMode() ? GL2.GL_TRANSFORM_BIT : 0); // for normalize state. ogsh.pushAttrib(gl, attribMask); gl.glDisable(GL.GL_CULL_FACE); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { // Enable blending in non-premultiplied color mode. Premultiplied colors don't work with GL fixed // functionality lighting. gl.glEnable(GL.GL_BLEND); @@ -371,8 +329,7 @@ protected void begin(DrawContext dc, OGLStackHandler ogsh) } } - protected void end(DrawContext dc, OGLStackHandler ogsh) - { + protected void end(DrawContext dc, OGLStackHandler ogsh) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. // Restore default GL client vertex array state. @@ -383,17 +340,17 @@ protected void end(DrawContext dc, OGLStackHandler ogsh) } protected boolean bindGeometryAttributes(DrawContext dc, SegmentPlane segmentPlane, Object key, - boolean disablePicking) - { + boolean disablePicking) { SegmentPlaneAttributes.GeometryAttributes attributes = segmentPlane.getAttributes().getGeometryAttributes(key); - if (attributes == null || !attributes.isVisible()) + if (attributes == null || !attributes.isVisible()) { return false; + } - if (dc.isPickingMode() && (disablePicking || !attributes.isEnablePicking())) + if (dc.isPickingMode() && (disablePicking || !attributes.isEnablePicking())) { return false; + } - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.bindPickableObject(dc, segmentPlane, key); } @@ -403,17 +360,17 @@ protected boolean bindGeometryAttributes(DrawContext dc, SegmentPlane segmentPla } protected boolean bindGeometryAttributesAsLine(DrawContext dc, SegmentPlane segmentPlane, Object key, - boolean disablePicking) - { + boolean disablePicking) { SegmentPlaneAttributes.GeometryAttributes attributes = segmentPlane.getAttributes().getGeometryAttributes(key); - if (attributes == null || !attributes.isVisible()) + if (attributes == null || !attributes.isVisible()) { return false; + } - if (dc.isPickingMode() && (disablePicking || !attributes.isEnablePicking())) + if (dc.isPickingMode() && (disablePicking || !attributes.isEnablePicking())) { return false; + } - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.bindPickableObject(dc, segmentPlane, key); } @@ -423,21 +380,21 @@ protected boolean bindGeometryAttributesAsLine(DrawContext dc, SegmentPlane segm return true; } - protected boolean bindLabelAttributes(DrawContext dc, SegmentPlane segmentPlane, Object key) - { - if (dc.isPickingMode()) + protected boolean bindLabelAttributes(DrawContext dc, SegmentPlane segmentPlane, Object key) { + if (dc.isPickingMode()) { return false; + } SegmentPlaneAttributes.LabelAttributes attributes = segmentPlane.getAttributes().getLabelAttributes(key); //noinspection RedundantIfStatement - if (attributes == null || !attributes.isVisible()) + if (attributes == null || !attributes.isVisible()) { return false; + } return true; } - protected PickedObject bindPickableObject(DrawContext dc, Object userObject, Object objectId) - { + protected PickedObject bindPickableObject(DrawContext dc, Object userObject, Object objectId) { java.awt.Color pickColor = dc.getUniquePickColor(); int colorCode = pickColor.getRGB(); GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. @@ -450,27 +407,22 @@ protected PickedObject bindPickableObject(DrawContext dc, Object userObject, Obj return po; } - protected PickedObject getTopPickedObject(DrawContext dc, java.awt.Point pickPoint, Object pickedObjectId) - { + protected PickedObject getTopPickedObject(DrawContext dc, java.awt.Point pickPoint, Object pickedObjectId) { PickedObject topObject = this.pickSupport.getTopObject(dc, pickPoint); - if (topObject == null) - { + if (topObject == null) { return null; } Object id = topObject.getValue(AVKey.PICKED_OBJECT_ID); - if (id != pickedObjectId) - { + if (id != pickedObjectId) { return null; } return topObject; } - protected void registerPickedObject(DrawContext dc, PickedObject pickedObject, Layer layer) - { - if (layer != null) - { + protected void registerPickedObject(DrawContext dc, PickedObject pickedObject, Layer layer) { + if (layer != null) { pickedObject.setParentLayer(layer); } @@ -480,10 +432,8 @@ protected void registerPickedObject(DrawContext dc, PickedObject pickedObject, L //**************************************************************// //******************** Plane Geometry ************************// //**************************************************************// - protected Position computePositionOnPlane(SectorGeometryList sgl, Globe globe, SegmentPlane segmentPlane, - double u, double v, boolean relativeToSurface) - { + double u, double v, boolean relativeToSurface) { double[] altitudes = segmentPlane.getPlaneAltitudes(); LatLon[] locations = segmentPlane.getPlaneLocations(); @@ -494,27 +444,21 @@ protected Position computePositionOnPlane(SectorGeometryList sgl, Globe globe, S LatLon location = LatLon.rhumbEndPosition(locations[0], heading, d); double altitude; - if (relativeToSurface) - { + if (relativeToSurface) { double surfaceElevation = this.computeSurfaceElevation(sgl, globe, - location.getLatitude(), location.getLongitude()); + location.getLatitude(), location.getLongitude()); altitude = surfaceElevation + v * (altitudes[1] - surfaceElevation); - } - else - { + } else { altitude = altitudes[0] + v * (altitudes[1] - altitudes[0]); } return new Position(location, altitude); } - protected double computeSurfaceElevation(SectorGeometryList sgl, Globe globe, Angle latitude, Angle longitude) - { - if (sgl != null) - { + protected double computeSurfaceElevation(SectorGeometryList sgl, Globe globe, Angle latitude, Angle longitude) { + if (sgl != null) { Vec4 surfacePoint = sgl.getSurfacePoint(latitude, longitude); - if (surfacePoint != null) - { + if (surfacePoint != null) { Position surfacePos = globe.computePositionFromPoint(surfacePoint); return surfacePos.getElevation(); } @@ -524,8 +468,7 @@ protected double computeSurfaceElevation(SectorGeometryList sgl, Globe globe, An } protected void computePlaneParameterization(Globe globe, SegmentPlane segmentPlane, - int[] gridCellCounts, double[] gridCellParams) - { + int[] gridCellCounts, double[] gridCellParams) { double[] altitudes = segmentPlane.getPlaneAltitudes(); LatLon[] locations = segmentPlane.getPlaneLocations(); double[] gridSizes = segmentPlane.getGridCellDimensions(); @@ -540,12 +483,10 @@ protected void computePlaneParameterization(Globe globe, SegmentPlane segmentPla } protected double computeObjectSize(View view, Globe globe, SegmentPlane segmentPlane, Object key, Vec4 point, - boolean usePickSize) - { - SegmentPlaneAttributes.GeometryAttributes attributes = - segmentPlane.getAttributes().getGeometryAttributes(key); - if (attributes == null) - { + boolean usePickSize) { + SegmentPlaneAttributes.GeometryAttributes attributes + = segmentPlane.getAttributes().getGeometryAttributes(key); + if (attributes == null) { return 0.0; } @@ -557,24 +498,23 @@ protected double computeObjectSize(View view, Globe globe, SegmentPlane segmentP } // TODO: identical to a method in MarkerRenderer; consolidate usage in a general place - protected double computeSizeForPixels(View view, Vec4 point, double pixels, double minSize, double maxSize) - { + protected double computeSizeForPixels(View view, Vec4 point, double pixels, double minSize, double maxSize) { double d = point.distanceTo3(view.getEyePoint()); double radius = pixels * view.computePixelSizeAtDistance(d); - if (radius < minSize) + if (radius < minSize) { radius = minSize; - else if (radius > maxSize) + } else if (radius > maxSize) { radius = maxSize; + } return radius; } - protected double computeMaxSizeForPixels(Globe globe, SegmentPlane segmentPlane) - { + protected double computeMaxSizeForPixels(Globe globe, SegmentPlane segmentPlane) { double[] altitudes = segmentPlane.getPlaneAltitudes(); LatLon[] locations = segmentPlane.getPlaneLocations(); - Vec4[] corners = new Vec4[] { + Vec4[] corners = new Vec4[]{ globe.computePointFromPosition(locations[0].getLatitude(), locations[0].getLongitude(), altitudes[0]), globe.computePointFromPosition(locations[1].getLatitude(), locations[1].getLongitude(), altitudes[0]), globe.computePointFromPosition(locations[1].getLatitude(), locations[1].getLongitude(), altitudes[1]), @@ -587,129 +527,115 @@ protected double computeMaxSizeForPixels(Globe globe, SegmentPlane segmentPlane) //**************************************************************// //******************** Plane Rendering ***********************// //**************************************************************// - protected void drawPlaneGeometry(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { dc.getView().pushReferenceCenter(dc, renderInfo.planeReferenceCenter); - try - { + try { this.bindPlaneVertexGeometry(dc, renderInfo); this.drawPlaneBackground(dc, segmentPlane, renderInfo, pickPoint, layer); this.drawPlaneGrid(dc, segmentPlane, renderInfo, pickPoint, layer); this.drawPlaneOutline(dc, segmentPlane, renderInfo, pickPoint, layer); - } - finally - { + } finally { dc.getView().popReferenceCenter(dc); } } protected void drawPlaneBackground(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { - if (!this.bindGeometryAttributes(dc, segmentPlane, SegmentPlane.PLANE_BACKGROUND, false)) + java.awt.Point pickPoint, Layer layer) { + if (!this.bindGeometryAttributes(dc, segmentPlane, SegmentPlane.PLANE_BACKGROUND, false)) { return; + } this.drawPlaneFillElements(dc, renderInfo); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.resolvePlaneBackgroundPick(dc, segmentPlane, renderInfo, pickPoint, layer); } } @SuppressWarnings({"UnusedDeclaration"}) protected void drawPlaneOutline(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { - if (!this.bindGeometryAttributesAsLine(dc, segmentPlane, SegmentPlane.PLANE_OUTLINE, true)) + java.awt.Point pickPoint, Layer layer) { + if (!this.bindGeometryAttributesAsLine(dc, segmentPlane, SegmentPlane.PLANE_OUTLINE, true)) { return; + } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.getGL().glDisable(GL2.GL_LIGHTING); } this.drawPlaneOutlineElements(dc, renderInfo); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.getGL().glEnable(GL2.GL_LIGHTING); } } protected void drawPlaneGrid(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { - if (!this.bindGeometryAttributesAsLine(dc, segmentPlane, SegmentPlane.PLANE_GRID, false)) + java.awt.Point pickPoint, Layer layer) { + if (!this.bindGeometryAttributesAsLine(dc, segmentPlane, SegmentPlane.PLANE_GRID, false)) { return; + } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.getGL().glDisable(GL2.GL_LIGHTING); } this.drawPlaneGridElements(dc, renderInfo); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.getGL().glEnable(GL2.GL_LIGHTING); - } - else - { + } else { this.resolvePlaneGridPick(dc, segmentPlane, renderInfo, pickPoint, layer); } } - protected void bindPlaneVertexGeometry(DrawContext dc, RenderInfo renderInfo) - { + protected void bindPlaneVertexGeometry(DrawContext dc, RenderInfo renderInfo) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glVertexPointer(3, GL2.GL_DOUBLE, 0, renderInfo.planeVertices); gl.glNormalPointer(GL2.GL_DOUBLE, 0, renderInfo.planeNormals); } - protected void drawPlaneFillElements(DrawContext dc, RenderInfo renderInfo) - { + protected void drawPlaneFillElements(DrawContext dc, RenderInfo renderInfo) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glEnable(GL.GL_POLYGON_OFFSET_FILL); gl.glPolygonOffset(1f, 1f); gl.glDrawElements(GL.GL_TRIANGLE_STRIP, renderInfo.planeFillIndexCount, GL.GL_UNSIGNED_INT, - renderInfo.planeFillIndices); + renderInfo.planeFillIndices); gl.glDisable(GL.GL_POLYGON_OFFSET_FILL); } - protected void drawPlaneOutlineElements(DrawContext dc, RenderInfo renderInfo) - { + protected void drawPlaneOutlineElements(DrawContext dc, RenderInfo renderInfo) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glDrawElements(GL.GL_LINES, renderInfo.planeOutlineIndexCount, GL.GL_UNSIGNED_INT, - renderInfo.planeOutlineIndices); + renderInfo.planeOutlineIndices); } - protected void drawPlaneGridElements(DrawContext dc, RenderInfo renderInfo) - { + protected void drawPlaneGridElements(DrawContext dc, RenderInfo renderInfo) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glDrawElements(GL.GL_LINES, renderInfo.planeGridIndexCount, GL.GL_UNSIGNED_INT, - renderInfo.planeGridIndices); + renderInfo.planeGridIndices); } @SuppressWarnings({"UnusedDeclaration"}) protected void resolvePlaneBackgroundPick(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { // The pick point is null when a pick rectangle is specified but a pick point is not. In this case, there's // nothing for the segment plane to resolve. - if (pickPoint == null) + if (pickPoint == null) { return; + } PickedObject topObject = this.getTopPickedObject(dc, pickPoint, SegmentPlane.PLANE_BACKGROUND); - if (topObject == null) + if (topObject == null) { return; + } Line ray = dc.getView().computeRayFromScreenPoint(pickPoint.getX(), pickPoint.getY()); Vec4 point = this.intersectRayWithFill(ray, renderInfo); - if (point == null) + if (point == null) { return; + } Position pos = dc.getGlobe().computePositionFromPoint(point); topObject.setPosition(pos); @@ -718,24 +644,27 @@ protected void resolvePlaneBackgroundPick(DrawContext dc, SegmentPlane segmentPl } protected void resolvePlaneOutlinePick(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { PickedObject topObject = this.getTopPickedObject(dc, pickPoint, SegmentPlane.PLANE_OUTLINE); - if (topObject == null) + if (topObject == null) { return; + } Line ray = dc.getView().computeRayFromScreenPoint(pickPoint.getX(), pickPoint.getY()); Plane plane = segmentPlane.computeInfinitePlane(dc.getGlobe()); - if (plane == null) + if (plane == null) { return; + } Vec4 point = plane.intersect(ray); - if (point == null) + if (point == null) { return; + } Vec4 outlinePoint = this.computeNearestOutlineToPoint(point, renderInfo); - if (outlinePoint == null) + if (outlinePoint == null) { return; + } Position pos = dc.getGlobe().computePositionFromPoint(outlinePoint); topObject.setPosition(pos); @@ -744,29 +673,33 @@ protected void resolvePlaneOutlinePick(DrawContext dc, SegmentPlane segmentPlane } protected void resolvePlaneGridPick(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { // The pick point is null when a pick rectangle is specified but a pick point is not. In this case, there's // nothing for the segment plane to resolve. - if (pickPoint == null) + if (pickPoint == null) { return; + } PickedObject topObject = this.getTopPickedObject(dc, pickPoint, SegmentPlane.PLANE_GRID); - if (topObject == null) + if (topObject == null) { return; + } Line ray = dc.getView().computeRayFromScreenPoint(pickPoint.getX(), pickPoint.getY()); Plane plane = segmentPlane.computeInfinitePlane(dc.getGlobe()); - if (plane == null) + if (plane == null) { return; + } Vec4 point = plane.intersect(ray); - if (point == null) + if (point == null) { return; + } Vec4 gridPoint = this.computeNearestGridLineToPoint(point, renderInfo); - if (gridPoint == null) + if (gridPoint == null) { return; + } Position pos = dc.getGlobe().computePositionFromPoint(gridPoint); topObject.setPosition(pos); @@ -777,16 +710,15 @@ protected void resolvePlaneGridPick(DrawContext dc, SegmentPlane segmentPlane, R //**************************************************************// //******************** Border Rendering **********************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) protected void drawPlaneBorder(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { - if (!this.bindGeometryAttributes(dc, segmentPlane, SegmentPlane.PLANE_BORDER, true)) + java.awt.Point pickPoint, Layer layer) { + if (!this.bindGeometryAttributes(dc, segmentPlane, SegmentPlane.PLANE_BORDER, true)) { return; + } SegmentPlaneAttributes.GeometryAttributes attributes = segmentPlane.getAttributes().getGeometryAttributes( - SegmentPlane.PLANE_BORDER); + SegmentPlane.PLANE_BORDER); View view = dc.getView(); Globe globe = dc.getGlobe(); @@ -795,37 +727,32 @@ protected void drawPlaneBorder(DrawContext dc, SegmentPlane segmentPlane, Render int mask = segmentPlane.getBorderMask(); Vec4 p1 = globe.computePointFromPosition(locations[0].getLatitude(), locations[0].getLongitude(), - altitudes[0]); + altitudes[0]); Vec4 p2 = globe.computePointFromPosition(locations[0].getLatitude(), locations[0].getLongitude(), - altitudes[1]); + altitudes[1]); Vec4 referencePoint = p1.add3(p2).divide3(2.0); double size = this.computeObjectSize(view, globe, segmentPlane, SegmentPlane.PLANE_BORDER, referencePoint, - dc.isPickingMode()); + dc.isPickingMode()); double height = altitudes[1] - altitudes[0]; GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. OGLStackHandler oglsh = new OGLStackHandler(); oglsh.pushModelview(gl); - try - { - if ((mask & SegmentPlane.LEFT) != 0) - { + try { + if ((mask & SegmentPlane.LEFT) != 0) { Matrix modelview = view.getModelviewMatrix(); modelview = modelview.multiply(globe.computeSurfaceOrientationAtPosition( - locations[0].getLatitude(), locations[0].getLongitude(), altitudes[0])); + locations[0].getLatitude(), locations[0].getLongitude(), altitudes[0])); this.drawBorder(dc, renderInfo, modelview, size, height); } - } - finally - { + } finally { oglsh.pop(gl); } } - protected void drawBorder(DrawContext dc, RenderInfo renderInfo, Matrix modelview, double radius, double height) - { + protected void drawBorder(DrawContext dc, RenderInfo renderInfo, Matrix modelview, double radius, double height) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. double[] compArray = new double[16]; @@ -852,57 +779,52 @@ protected void drawBorder(DrawContext dc, RenderInfo renderInfo, Matrix modelvie this.drawBorderCap(dc, renderInfo); } - protected void drawBorderCylinder(DrawContext dc, RenderInfo renderInfo) - { + protected void drawBorderCylinder(DrawContext dc, RenderInfo renderInfo) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glVertexPointer(3, GL.GL_FLOAT, 0, renderInfo.borderCylinderVertices); gl.glNormalPointer(GL.GL_FLOAT, 0, renderInfo.borderCylinderNormals); gl.glDrawElements(GL.GL_TRIANGLE_STRIP, renderInfo.borderCylinderIndexCount, GL.GL_UNSIGNED_INT, - renderInfo.borderCylinderIndices); + renderInfo.borderCylinderIndices); } - protected void drawBorderCap(DrawContext dc, RenderInfo renderInfo) - { + protected void drawBorderCap(DrawContext dc, RenderInfo renderInfo) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. gl.glVertexPointer(3, GL.GL_FLOAT, 0, renderInfo.borderCapVertices); gl.glNormalPointer(GL.GL_FLOAT, 0, renderInfo.borderCapNormals); gl.glDrawElements(GL.GL_TRIANGLE_STRIP, renderInfo.borderCapIndexCount, GL.GL_UNSIGNED_INT, - renderInfo.borderCapIndices); + renderInfo.borderCapIndices); } //**************************************************************// //******************** Segment Altimeter Rendering ***********// //**************************************************************// - protected void drawSegmentAltimeter(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { this.drawSegmentAltimeterGeometry(dc, segmentPlane, renderInfo, pickPoint, layer); this.drawSegmentAltimeterLabel(dc, segmentPlane, renderInfo, pickPoint, layer); } @SuppressWarnings({"UnusedDeclaration"}) protected void drawSegmentAltimeterGeometry(DrawContext dc, SegmentPlane segmentPlane, - RenderInfo renderInfo, java.awt.Point pickPoint, Layer layer) - { - if (!this.bindGeometryAttributesAsLine(dc, segmentPlane, SegmentPlane.ALTIMETER, true)) + RenderInfo renderInfo, java.awt.Point pickPoint, Layer layer) { + if (!this.bindGeometryAttributesAsLine(dc, segmentPlane, SegmentPlane.ALTIMETER, true)) { return; + } Globe globe = dc.getGlobe(); Position position = segmentPlane.getSegmentPositions()[1]; double surfaceElevation = this.computeSurfaceElevation(dc.getSurfaceGeometry(), globe, - position.getLatitude(), position.getLongitude()); + position.getLatitude(), position.getLongitude()); Vec4 v1 = globe.computePointFromPosition(position.getLatitude(), position.getLongitude(), - position.getElevation()); + position.getElevation()); Vec4 v2 = globe.computePointFromPosition(position.getLatitude(), position.getLongitude(), - surfaceElevation); + surfaceElevation); Vec4 referenceCenter = v1; v1 = v1.subtract3(referenceCenter); v2 = v2.subtract3(referenceCenter); - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.getGL().glDisable(GL2.GL_LIGHTING); } @@ -920,40 +842,36 @@ protected void drawSegmentAltimeterGeometry(DrawContext dc, SegmentPlane segment dc.getView().pushReferenceCenter(dc, referenceCenter); gl.glBegin(GL2.GL_LINES); - try - { + try { gl.glVertex3d(v1.x, v1.y, v1.z); gl.glVertex3d(v2.x, v2.y, v2.z); - } - finally - { + } finally { gl.glEnd(); dc.getView().popReferenceCenter(dc); oglsh.pop(gl); } - if (!dc.isPickingMode()) - { + if (!dc.isPickingMode()) { dc.getGL().glEnable(GL2.GL_LIGHTING); } } @SuppressWarnings({"UnusedDeclaration"}) protected void drawSegmentAltimeterLabel(DrawContext dc, SegmentPlane segmentPlane, - RenderInfo renderInfo, java.awt.Point pickPoint, Layer layer) - { - if (!this.bindLabelAttributes(dc, segmentPlane, SegmentPlane.ALTIMETER)) + RenderInfo renderInfo, java.awt.Point pickPoint, Layer layer) { + if (!this.bindLabelAttributes(dc, segmentPlane, SegmentPlane.ALTIMETER)) { return; + } SectorGeometryList sgl = dc.getSurfaceGeometry(); Globe globe = dc.getGlobe(); Position position = segmentPlane.getSegmentPositions()[1]; double surfaceElevation = this.computeSurfaceElevation(sgl, globe, - position.getLatitude(), position.getLongitude()); + position.getLatitude(), position.getLongitude()); double height = position.getElevation() - surfaceElevation; Position centerPos = new Position(position, - surfaceElevation + (height / 2.0)); + surfaceElevation + (height / 2.0)); AVList values = new AVListImpl(); values.setValue(AVKey.HEIGHT, height); @@ -964,64 +882,57 @@ protected void drawSegmentAltimeterLabel(DrawContext dc, SegmentPlane segmentPla //**************************************************************// //******************** Control Point Rendering ***************// //**************************************************************// - protected void drawControlPoints(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { SectorGeometryList sgl = dc.getSurfaceGeometry(); Globe globe = dc.getGlobe(); // Draw user-defined control points. - for (SegmentPlane.ControlPoint controlPoint : segmentPlane.getControlPoints()) - { + for (SegmentPlane.ControlPoint controlPoint : segmentPlane.getControlPoints()) { Position pos = this.computeControlPointPosition(sgl, globe, segmentPlane, controlPoint); MarkerShape shape = renderInfo.getMarkerShape(controlPoint.getShapeType()); - if (pos != null && shape != null) - { + if (pos != null && shape != null) { this.drawControlPoint(dc, segmentPlane, controlPoint, pos, shape); } } // Draw segment begin/end control points. - Object[] keys = new Object[] {SegmentPlane.SEGMENT_BEGIN, SegmentPlane.SEGMENT_END}; + Object[] keys = new Object[]{SegmentPlane.SEGMENT_BEGIN, SegmentPlane.SEGMENT_END}; Position[] positions = segmentPlane.getSegmentPositions(); - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { SegmentPlane.ControlPoint controlPoint = new SegmentPlane.ControlPoint(segmentPlane, keys[i], -1, -1, - false, BasicMarkerShape.SPHERE); + false, BasicMarkerShape.SPHERE); MarkerShape shape = renderInfo.getMarkerShape(controlPoint.getShapeType()); - if (shape != null) - { + if (shape != null) { this.drawControlPoint(dc, segmentPlane, controlPoint, positions[i], shape); } } - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { this.resolveControlPointPick(dc, segmentPlane, renderInfo, pickPoint, layer); } } protected void drawControlPoint(DrawContext dc, SegmentPlane segmentPlane, SegmentPlane.ControlPoint controlPoint, - Position position, MarkerShape shape) - { + Position position, MarkerShape shape) { ControlPointInfo controlPointInfo = new ControlPointInfo(controlPoint, position, shape); this.drawControlPointGeometry(dc, segmentPlane, controlPointInfo); this.drawControlPointLabel(dc, segmentPlane, controlPoint, position); } protected void drawControlPointGeometry(DrawContext dc, SegmentPlane segmentPlane, - ControlPointInfo controlPointInfo) - { + ControlPointInfo controlPointInfo) { Object key = controlPointInfo.controlPoint.getKey(); - if (!this.bindGeometryAttributes(dc, segmentPlane, key, false)) + if (!this.bindGeometryAttributes(dc, segmentPlane, key, false)) { return; + } SegmentPlaneAttributes.GeometryAttributes attributes = segmentPlane.getAttributes().getGeometryAttributes(key); - if (attributes == null || !attributes.isVisible()) + if (attributes == null || !attributes.isVisible()) { return; + } GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. View view = dc.getView(); @@ -1044,37 +955,33 @@ protected void drawControlPointGeometry(DrawContext dc, SegmentPlane segmentPlan point = point.add3(offset); controlPointInfo.position = globe.computePositionFromPoint(point); - if (dc.isPickingMode()) - { + if (dc.isPickingMode()) { PickedObject po = this.bindPickableObject(dc, controlPointInfo.controlPoint, - controlPointInfo.controlPoint.getKey()); + controlPointInfo.controlPoint.getKey()); po.setPosition(controlPointInfo.position); } OGLStackHandler ogsh = new OGLStackHandler(); ogsh.pushModelview(gl); - try - { + try { LatLon[] planeLocations = segmentPlane.getPlaneLocations(); Angle heading = LatLon.rhumbAzimuth(planeLocations[0], planeLocations[1]); double size = sizeScale * (dc.isPickingMode() ? attributes.getPicksize() : attributes.getSize()); Marker marker = new BasicMarker(controlPointInfo.position, new BasicMarkerAttributes(), heading); controlPointInfo.shape.render(dc, marker, point, size); - } - finally - { + } finally { ogsh.pop(gl); } } protected void drawControlPointLabel(DrawContext dc, SegmentPlane segmentPlane, - SegmentPlane.ControlPoint controlPoint, Position position) - { - if (!this.bindLabelAttributes(dc, segmentPlane, controlPoint.getKey())) + SegmentPlane.ControlPoint controlPoint, Position position) { + if (!this.bindLabelAttributes(dc, segmentPlane, controlPoint.getKey())) { return; + } double surfaceElevation = this.computeSurfaceElevation(dc.getSurfaceGeometry(), dc.getGlobe(), - position.getLatitude(), position.getLongitude()); + position.getLatitude(), position.getLongitude()); double height = position.getElevation() - surfaceElevation; AVList values = new AVListImpl(); @@ -1085,39 +992,35 @@ protected void drawControlPointLabel(DrawContext dc, SegmentPlane segmentPlane, @SuppressWarnings({"UnusedDeclaration"}) protected void resolveControlPointPick(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { // The pick point is null when a pick rectangle is specified but a pick point is not. In this case, there's // nothing for the segment plane to resolve. - if (pickPoint == null) + if (pickPoint == null) { return; + } PickedObject topObject = null; // Pick user-defined control points. - for (SegmentPlane.ControlPoint controlPoint : segmentPlane.getControlPoints()) - { - if ((topObject = this.getTopPickedObject(dc, pickPoint, controlPoint.getKey())) != null) - { + for (SegmentPlane.ControlPoint controlPoint : segmentPlane.getControlPoints()) { + if ((topObject = this.getTopPickedObject(dc, pickPoint, controlPoint.getKey())) != null) { break; } } - if (topObject == null) - { + if (topObject == null) { // Pick segment begin/end control points. - Object[] keys = new Object[] {SegmentPlane.SEGMENT_BEGIN, SegmentPlane.SEGMENT_END}; - for (Object key : keys) - { - if ((topObject = this.getTopPickedObject(dc, pickPoint, key)) != null) - { + Object[] keys = new Object[]{SegmentPlane.SEGMENT_BEGIN, SegmentPlane.SEGMENT_END}; + for (Object key : keys) { + if ((topObject = this.getTopPickedObject(dc, pickPoint, key)) != null) { break; } } } - if (topObject == null) + if (topObject == null) { return; + } this.registerPickedObject(dc, topObject, layer); } @@ -1125,19 +1028,17 @@ protected void resolveControlPointPick(DrawContext dc, SegmentPlane segmentPlane //**************************************************************// //******************** Axis Label Rendering ******************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) protected void drawAxisLabels(DrawContext dc, SegmentPlane segmentPlane, RenderInfo renderInfo, - java.awt.Point pickPoint, Layer layer) - { + java.awt.Point pickPoint, Layer layer) { this.drawHorizontalAxisLabels(dc, segmentPlane); this.drawVerticalAxisLabels(dc, segmentPlane); } - protected void drawHorizontalAxisLabels(DrawContext dc, SegmentPlane segmentPlane) - { - if (!this.bindLabelAttributes(dc, segmentPlane, SegmentPlane.HORIZONTAL_AXIS_LABELS)) + protected void drawHorizontalAxisLabels(DrawContext dc, SegmentPlane segmentPlane) { + if (!this.bindLabelAttributes(dc, segmentPlane, SegmentPlane.HORIZONTAL_AXIS_LABELS)) { return; + } SectorGeometryList sgl = dc.getSurfaceGeometry(); Globe globe = dc.getGlobe(); @@ -1153,8 +1054,7 @@ protected void drawHorizontalAxisLabels(DrawContext dc, SegmentPlane segmentPlan // are always drawn at or above the surface. OrderedText[] labels = new OrderedText[uStacks]; - for (int ui = 0; ui < uStacks; ui++) - { + for (int ui = 0; ui < uStacks; ui++) { double u = clamp(ui * uStep, 0, 1); double width = ui * gridCellSizes[0]; @@ -1163,8 +1063,9 @@ protected void drawHorizontalAxisLabels(DrawContext dc, SegmentPlane segmentPlan Position pos = this.computePositionOnPlane(sgl, globe, segmentPlane, u, 0, true); double surfaceElevation = this.computeSurfaceElevation(sgl, globe, pos.getLatitude(), pos.getLongitude()); - if (pos.getElevation() < surfaceElevation) + if (pos.getElevation() < surfaceElevation) { pos = new Position(pos, surfaceElevation); + } labels[ui] = this.createLabel(dc, segmentPlane, pos, values, SegmentPlane.HORIZONTAL_AXIS_LABELS); } @@ -1175,10 +1076,10 @@ protected void drawHorizontalAxisLabels(DrawContext dc, SegmentPlane segmentPlan this.drawAxisLabels(dc, labels, 1, uStacks, size.getWidth(), d); } - protected void drawVerticalAxisLabels(DrawContext dc, SegmentPlane segmentPlane) - { - if (!this.bindLabelAttributes(dc, segmentPlane, SegmentPlane.VERTICAL_AXIS_LABELS)) + protected void drawVerticalAxisLabels(DrawContext dc, SegmentPlane segmentPlane) { + if (!this.bindLabelAttributes(dc, segmentPlane, SegmentPlane.VERTICAL_AXIS_LABELS)) { return; + } double[] gridCellSizes = segmentPlane.getGridCellDimensions(); @@ -1195,8 +1096,7 @@ protected void drawVerticalAxisLabels(DrawContext dc, SegmentPlane segmentPlane) // beneath the terrain are not drawn. OrderedText[] labels = new OrderedText[vStacks]; - for (int vi = 0; vi < vStacks; vi++) - { + for (int vi = 0; vi < vStacks; vi++) { double v = clamp(vi * vStep, 0, 1); double height = vi * gridCellSizes[1]; @@ -1205,8 +1105,9 @@ protected void drawVerticalAxisLabels(DrawContext dc, SegmentPlane segmentPlane) Position pos = this.computePositionOnPlane(sgl, globe, segmentPlane, 1, v, false); double surfaceElevation = this.computeSurfaceElevation(sgl, globe, pos.getLatitude(), pos.getLongitude()); - if (pos.getElevation() < surfaceElevation) + if (pos.getElevation() < surfaceElevation) { continue; + } labels[vi] = this.createLabel(dc, segmentPlane, pos, values, SegmentPlane.VERTICAL_AXIS_LABELS); } @@ -1218,16 +1119,14 @@ protected void drawVerticalAxisLabels(DrawContext dc, SegmentPlane segmentPlane) } protected void drawAxisLabels(DrawContext dc, OrderedText[] text, int startPos, int count, - double averageSize, double minDistance) - { + double averageSize, double minDistance) { int step = (int) Math.round(1.5 * averageSize / minDistance); - if (step < 1) + if (step < 1) { step = 1; + } - for (int i = startPos; i < count; i += step) - { - if (text[i] != null) - { + for (int i = startPos; i < count; i += step) { + if (text[i] != null) { dc.addOrderedRenderable(text[i]); } } @@ -1236,27 +1135,25 @@ protected void drawAxisLabels(DrawContext dc, OrderedText[] text, int startPos, //**************************************************************// //******************** Label Rendering ***********************// //**************************************************************// - - protected void drawLabel(DrawContext dc, SegmentPlane segmentPlane, Position position, AVList values, Object key) - { + protected void drawLabel(DrawContext dc, SegmentPlane segmentPlane, Position position, AVList values, Object key) { OrderedText orderedText = this.createLabel(dc, segmentPlane, position, values, key); - if (orderedText == null) + if (orderedText == null) { return; + } dc.addOrderedRenderable(orderedText); } protected OrderedText createLabel(DrawContext dc, SegmentPlane segmentPlane, Position position, AVList values, - Object key) - { + Object key) { SegmentPlaneAttributes.LabelAttributes attributes = segmentPlane.getAttributes().getLabelAttributes(key); - if (attributes == null) + if (attributes == null) { return null; + } Vec4 point = dc.getGlobe().computePointFromPosition(position); double distanceFromEye = dc.getView().getEyePoint().distanceTo3(point); - if (distanceFromEye < attributes.getMinActiveDistance() || distanceFromEye > attributes.getMaxActiveDistance()) - { + if (distanceFromEye < attributes.getMinActiveDistance() || distanceFromEye > attributes.getMaxActiveDistance()) { return null; } @@ -1266,16 +1163,13 @@ protected OrderedText createLabel(DrawContext dc, SegmentPlane segmentPlane, Pos return new OrderedText(segmentPlane, position, distanceFromEye, values, attributes, textRenderer); } - protected java.awt.Rectangle computeAverageLabelSize(OrderedText[] text, int textCount) - { + protected java.awt.Rectangle computeAverageLabelSize(OrderedText[] text, int textCount) { double width = 0; double height = 0; int count = 0; - for (int i = 0; i < textCount; i++) - { - if (text[i] != null) - { + for (int i = 0; i < textCount; i++) { + if (text[i] != null) { java.awt.Rectangle bounds = text[i].textRenderer.getBounds(text[i].getText()); width += bounds.getWidth(); height += bounds.getHeight(); @@ -1283,8 +1177,7 @@ protected java.awt.Rectangle computeAverageLabelSize(OrderedText[] text, int tex } } - if (count > 1) - { + if (count > 1) { width /= (double) count; height /= (double) count; } @@ -1292,37 +1185,34 @@ protected java.awt.Rectangle computeAverageLabelSize(OrderedText[] text, int tex return new java.awt.Rectangle((int) width, (int) height); } - protected double computeMinDistanceBetweenLabels(DrawContext dc, OrderedText[] text, int textCount) - { + protected double computeMinDistanceBetweenLabels(DrawContext dc, OrderedText[] text, int textCount) { double minDistance = Double.MAX_VALUE; - for (int i = 0; i < textCount - 1; i++) - { - if (text[i] != null) - { - for (int j = i + 1; j < textCount; j++) - { - if (text[j] != null) - { + for (int i = 0; i < textCount - 1; i++) { + if (text[i] != null) { + for (int j = i + 1; j < textCount; j++) { + if (text[j] != null) { Vec4 v1 = text[i].getScreenPoint(dc); Vec4 v2 = text[j].getScreenPoint(dc); double d = v1.distanceToSquared3(v2); - if (d < minDistance) + if (d < minDistance) { minDistance = d; + } } } } } - if (minDistance > 0) + if (minDistance > 0) { minDistance = Math.sqrt(minDistance); + } return minDistance; } - protected static class OrderedText implements OrderedRenderable - { + protected static class OrderedText implements OrderedRenderable { + protected SegmentPlane segmentPlane; protected final Position position; protected final double distanceFromEye; @@ -1331,8 +1221,7 @@ protected static class OrderedText implements OrderedRenderable protected MultiLineTextRenderer textRenderer; public OrderedText(SegmentPlane segmentPlane, Position position, double distanceFromEye, AVList values, - SegmentPlaneAttributes.LabelAttributes attributes, MultiLineTextRenderer textRenderer) - { + SegmentPlaneAttributes.LabelAttributes attributes, MultiLineTextRenderer textRenderer) { this.segmentPlane = segmentPlane; this.position = position; this.distanceFromEye = distanceFromEye; @@ -1341,71 +1230,67 @@ public OrderedText(SegmentPlane segmentPlane, Position position, double distance this.textRenderer = textRenderer; } - public String getText() - { + public String getText() { return this.attributes.getText(this.segmentPlane, this.position, this.values); } - public double getDistanceFromEye() - { + public double getDistanceFromEye() { return this.distanceFromEye; } - public Vec4 getScreenPoint(DrawContext dc) - { - if (dc.getGlobe() == null || dc.getView() == null) + public Vec4 getScreenPoint(DrawContext dc) { + if (dc.getGlobe() == null || dc.getView() == null) { return null; + } Vec4 modelPoint = dc.getGlobe().computePointFromPosition(this.position.getLatitude(), - this.position.getLongitude(), this.position.getElevation()); - if (modelPoint == null) + this.position.getLongitude(), this.position.getElevation()); + if (modelPoint == null) { return null; + } return dc.getView().project(modelPoint).add3(attributes.getOffset()); } - protected Vec4 getScreenPoint(DrawContext dc, Position position) - { - if (dc.getGlobe() == null || dc.getView() == null) + protected Vec4 getScreenPoint(DrawContext dc, Position position) { + if (dc.getGlobe() == null || dc.getView() == null) { return null; + } Vec4 modelPoint = dc.getGlobe().computePointFromPosition(position.getLatitude(), position.getLongitude(), - position.getElevation()); - if (modelPoint == null) + position.getElevation()); + if (modelPoint == null) { return null; + } return dc.getView().project(modelPoint); } - public void render(DrawContext dc) - { + public void render(DrawContext dc) { OGLStackHandler ogsh = new OGLStackHandler(); this.begin(dc, ogsh); - try - { + try { this.draw(dc); - } - finally - { + } finally { this.end(dc, ogsh); } } - public void pick(DrawContext dc, Point pickPoint) - { + public void pick(DrawContext dc, Point pickPoint) { // Label text is not pickable. } - protected void draw(DrawContext dc) - { + protected void draw(DrawContext dc) { String text = this.getText(); - if (text == null) + if (text == null) { return; + } Vec4 point = this.getScreenPoint(dc); - if (point == null) + if (point == null) { return; + } java.awt.Rectangle viewport = dc.getView().getViewport(); java.awt.Color color = attributes.getColor(); @@ -1419,8 +1304,7 @@ protected void draw(DrawContext dc) this.textRenderer.getTextRenderer().endRendering(); } - protected void begin(DrawContext dc, OGLStackHandler ogsh) - { + protected void begin(DrawContext dc, OGLStackHandler ogsh) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. int attribBits = GL2.GL_CURRENT_BIT; // For current color. @@ -1428,21 +1312,18 @@ protected void begin(DrawContext dc, OGLStackHandler ogsh) ogsh.pushAttrib(gl, attribBits); } - protected void end(DrawContext dc, OGLStackHandler ogsh) - { + protected void end(DrawContext dc, OGLStackHandler ogsh) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. ogsh.pop(gl); } protected void drawText(String text, Vec4 screenPoint, - SegmentPlaneAttributes.LabelAttributes attributes, MultiLineTextRenderer mltr) - { + SegmentPlaneAttributes.LabelAttributes attributes, MultiLineTextRenderer mltr) { double x = screenPoint.x; double y = screenPoint.y; - if (attributes != null) - { + if (attributes != null) { String horizontal = attributes.getHorizontalAlignment(); String vertical = attributes.getVerticalAlignment(); java.awt.Rectangle textBounds = mltr.getBounds(text); @@ -1452,36 +1333,26 @@ protected void drawText(String text, Vec4 screenPoint, double hh = textBounds.getHeight() / 2.0; //noinspection StringEquality - if (horizontal == AVKey.LEFT) - { + if (horizontal == AVKey.LEFT) { // MultiLineTextRenderer anchors text to the upper left corner by default. + } else //noinspection StringEquality + if (horizontal == AVKey.CENTER) { + x -= hw; + } else //noinspection StringEquality + if (horizontal == AVKey.RIGHT) { + x -= w; } - else //noinspection StringEquality - if (horizontal == AVKey.CENTER) - { - x -= hw; - } - else //noinspection StringEquality - if (horizontal == AVKey.RIGHT) - { - x -= w; - } //noinspection StringEquality - if (vertical == AVKey.TOP) - { + if (vertical == AVKey.TOP) { // MultiLineTextRenderer anchors text to the upper left corner by default. + } else //noinspection StringEquality + if (vertical == AVKey.CENTER) { + y += hh; + } else //noinspection StringEquality + if (vertical == AVKey.BOTTOM) { + y += h; } - else //noinspection StringEquality - if (vertical == AVKey.CENTER) - { - y += hh; - } - else //noinspection StringEquality - if (vertical == AVKey.BOTTOM) - { - y += h; - } } mltr.draw(text, (int) x, (int) y, AVKey.TEXT_EFFECT_OUTLINE); @@ -1491,15 +1362,13 @@ protected void drawText(String text, Vec4 screenPoint, //**************************************************************// //******************** Segment Plane Construction ************// //**************************************************************// - - protected void createSegmentPlaneGeometry(Globe globe, SegmentPlane segmentPlane, RenderInfo renderInfo) - { + protected void createSegmentPlaneGeometry(Globe globe, SegmentPlane segmentPlane, RenderInfo renderInfo) { double[] altitudes = segmentPlane.getPlaneAltitudes(); LatLon[] locations = segmentPlane.getPlaneLocations(); int mask = segmentPlane.getPlaneOutlineMask(); renderInfo.planeReferenceCenter = globe.computePointFromPosition( - locations[0].getLatitude(), locations[0].getLongitude(), altitudes[0]); + locations[0].getLatitude(), locations[0].getLongitude(), altitudes[0]); int[] gridCellCounts = new int[2]; double[] gridCellParams = new double[2]; @@ -1512,33 +1381,28 @@ protected void createSegmentPlaneGeometry(Globe globe, SegmentPlane segmentPlane renderInfo.planeFillIndexCount = getPlaneFillIndexCount(uStacks, vStacks); if (renderInfo.planeFillIndices == null - || renderInfo.planeFillIndices.capacity() < renderInfo.planeFillIndexCount) - { + || renderInfo.planeFillIndices.capacity() < renderInfo.planeFillIndexCount) { renderInfo.planeFillIndices = Buffers.newDirectIntBuffer(renderInfo.planeFillIndexCount); } renderInfo.planeOutlineIndexCount = getPlaneOutlineIndexCount(uStacks, vStacks, mask); if (renderInfo.planeOutlineIndices == null - || renderInfo.planeOutlineIndices.capacity() < renderInfo.planeOutlineIndexCount) - { + || renderInfo.planeOutlineIndices.capacity() < renderInfo.planeOutlineIndexCount) { renderInfo.planeOutlineIndices = Buffers.newDirectIntBuffer(renderInfo.planeOutlineIndexCount); } renderInfo.planeGridIndexCount = getPlaneGridIndexCount(uStacks, vStacks); if (renderInfo.planeGridIndices == null - || renderInfo.planeGridIndices.capacity() < renderInfo.planeGridIndexCount) - { + || renderInfo.planeGridIndices.capacity() < renderInfo.planeGridIndexCount) { renderInfo.planeGridIndices = Buffers.newDirectIntBuffer(renderInfo.planeGridIndexCount); } int vertexCount = getPlaneVertexCount(uStacks, vStacks); int coordCount = 3 * vertexCount; - if (renderInfo.planeVertices == null || renderInfo.planeVertices.capacity() < coordCount) - { + if (renderInfo.planeVertices == null || renderInfo.planeVertices.capacity() < coordCount) { renderInfo.planeVertices = Buffers.newDirectDoubleBuffer(coordCount); } - if (renderInfo.planeNormals == null || renderInfo.planeNormals.capacity() < coordCount) - { + if (renderInfo.planeNormals == null || renderInfo.planeNormals.capacity() < coordCount) { renderInfo.planeNormals = Buffers.newDirectDoubleBuffer(coordCount); } @@ -1552,67 +1416,62 @@ protected void createSegmentPlaneGeometry(Globe globe, SegmentPlane segmentPlane renderInfo.planeGridIndices.rewind(); this.computePlaneVertices(globe, segmentPlane, uStacks, vStacks, uStep, vStep, renderInfo.planeReferenceCenter, - renderInfo.planeVertices); + renderInfo.planeVertices); renderInfo.planeVertices.rewind(); this.computePlaneNormals(globe, segmentPlane, renderInfo.planeFillIndexCount, vertexCount, - renderInfo.planeFillIndices, renderInfo.planeVertices, renderInfo.planeNormals); + renderInfo.planeFillIndices, renderInfo.planeVertices, renderInfo.planeNormals); renderInfo.planeNormals.rewind(); } // TODO: consolidate the following geometry construction code with GeometryBuilder - - protected static int getPlaneFillIndexCount(int uStacks, int vStacks) - { + protected static int getPlaneFillIndexCount(int uStacks, int vStacks) { int count = 2 * (uStacks + 1) * vStacks; // Triangle strips for each row. - if (vStacks > 1) + if (vStacks > 1) { count += 2 * (vStacks - 1); // Degenerate connection triangles. - + } return count; } - protected static int getPlaneOutlineIndexCount(int uStacks, int vStacks, int mask) - { + protected static int getPlaneOutlineIndexCount(int uStacks, int vStacks, int mask) { int count = 0; - if ((mask & SegmentPlane.TOP) != 0) + if ((mask & SegmentPlane.TOP) != 0) { count += 2 * uStacks; - if ((mask & SegmentPlane.BOTTOM) != 0) + } + if ((mask & SegmentPlane.BOTTOM) != 0) { count += 2 * uStacks; - if ((mask & SegmentPlane.LEFT) != 0) + } + if ((mask & SegmentPlane.LEFT) != 0) { count += 2 * vStacks; - if ((mask & SegmentPlane.RIGHT) != 0) + } + if ((mask & SegmentPlane.RIGHT) != 0) { count += 2 * vStacks; + } return count; } - protected static int getPlaneGridIndexCount(int uStacks, int vStacks) - { - return 2 * uStacks * (vStacks - 1) // Horizontal gridlines. - + 2 * vStacks * (uStacks - 1); // Vertical gridlines. + protected static int getPlaneGridIndexCount(int uStacks, int vStacks) { + return 2 * uStacks * (vStacks - 1) // Horizontal gridlines. + + 2 * vStacks * (uStacks - 1); // Vertical gridlines. } - protected static int getPlaneVertexCount(int uStacks, int vStacks) - { + protected static int getPlaneVertexCount(int uStacks, int vStacks) { return (uStacks + 1) * (vStacks + 1); } - protected static void computePlaneFillIndices(int uStacks, int vStacks, IntBuffer buffer) - { + protected static void computePlaneFillIndices(int uStacks, int vStacks, IntBuffer buffer) { int vertex; - for (int vi = 0; vi < vStacks; vi++) - { - if (vi != 0) - { + for (int vi = 0; vi < vStacks; vi++) { + if (vi != 0) { vertex = uStacks + (vi - 1) * (uStacks + 1); buffer.put(vertex); vertex = vi * (uStacks + 1) + (uStacks + 1); buffer.put(vertex); } - for (int ui = 0; ui <= uStacks; ui++) - { + for (int ui = 0; ui <= uStacks; ui++) { vertex = ui + (vi + 1) * (uStacks + 1); buffer.put(vertex); vertex = ui + vi * (uStacks + 1); @@ -1621,15 +1480,12 @@ protected static void computePlaneFillIndices(int uStacks, int vStacks, IntBuffe } } - protected static void computePlaneOutlineIndices(int uStacks, int vStacks, int mask, IntBuffer buffer) - { + protected static void computePlaneOutlineIndices(int uStacks, int vStacks, int mask, IntBuffer buffer) { int vertex; // Top edge. - if ((mask & SegmentPlane.TOP) != 0) - { - for (int ui = 0; ui < uStacks; ui++) - { + if ((mask & SegmentPlane.TOP) != 0) { + for (int ui = 0; ui < uStacks; ui++) { vertex = ui + vStacks * (uStacks + 1); buffer.put(vertex); vertex = (ui + 1) + vStacks * (uStacks + 1); @@ -1638,10 +1494,8 @@ protected static void computePlaneOutlineIndices(int uStacks, int vStacks, int m } // Bottom edge. - if ((mask & SegmentPlane.BOTTOM) != 0) - { - for (int ui = 0; ui < uStacks; ui++) - { + if ((mask & SegmentPlane.BOTTOM) != 0) { + for (int ui = 0; ui < uStacks; ui++) { vertex = ui; buffer.put(vertex); vertex = (ui + 1); @@ -1650,10 +1504,8 @@ protected static void computePlaneOutlineIndices(int uStacks, int vStacks, int m } // Left edge. - if ((mask & SegmentPlane.LEFT) != 0) - { - for (int vi = 0; vi < vStacks; vi++) - { + if ((mask & SegmentPlane.LEFT) != 0) { + for (int vi = 0; vi < vStacks; vi++) { vertex = vi * (uStacks + 1); buffer.put(vertex); vertex = (vi + 1) * (uStacks + 1); @@ -1662,10 +1514,8 @@ protected static void computePlaneOutlineIndices(int uStacks, int vStacks, int m } // Right edge. - if ((mask & SegmentPlane.RIGHT) != 0) - { - for (int vi = 0; vi < vStacks; vi++) - { + if ((mask & SegmentPlane.RIGHT) != 0) { + for (int vi = 0; vi < vStacks; vi++) { vertex = uStacks + vi * (uStacks + 1); buffer.put(vertex); vertex = uStacks + (vi + 1) * (uStacks + 1); @@ -1674,15 +1524,12 @@ protected static void computePlaneOutlineIndices(int uStacks, int vStacks, int m } } - protected static void computePlaneGridIndices(int uStacks, int vStacks, IntBuffer buffer) - { + protected static void computePlaneGridIndices(int uStacks, int vStacks, IntBuffer buffer) { int vertex; // Horizontal gridlines. - for (int vi = 1; vi < vStacks; vi++) - { - for (int ui = 0; ui < uStacks; ui++) - { + for (int vi = 1; vi < vStacks; vi++) { + for (int ui = 0; ui < uStacks; ui++) { vertex = ui + vi * (uStacks + 1); buffer.put(vertex); vertex = (ui + 1) + vi * (uStacks + 1); @@ -1691,10 +1538,8 @@ protected static void computePlaneGridIndices(int uStacks, int vStacks, IntBuffe } // Vertical gridlines. - for (int ui = 1; ui < uStacks; ui++) - { - for (int vi = 0; vi < vStacks; vi++) - { + for (int ui = 1; ui < uStacks; ui++) { + for (int vi = 0; vi < vStacks; vi++) { vertex = ui + vi * (uStacks + 1); buffer.put(vertex); vertex = ui + (vi + 1) * (uStacks + 1); @@ -1704,17 +1549,14 @@ protected static void computePlaneGridIndices(int uStacks, int vStacks, IntBuffe } protected void computePlaneVertices(Globe globe, SegmentPlane segmentPlane, - int uStacks, int vStacks, double uStep, double vStep, - Vec4 referenceCenter, DoubleBuffer buffer) - { + int uStacks, int vStacks, double uStep, double vStep, + Vec4 referenceCenter, DoubleBuffer buffer) { int index = 0; - for (int vi = 0; vi <= vStacks; vi++) - { + for (int vi = 0; vi <= vStacks; vi++) { double v = clamp(vi * vStep, 0, 1); - for (int ui = 0; ui <= uStacks; ui++) - { + for (int ui = 0; ui <= uStacks; ui++) { double u = clamp(ui * uStep, 0, 1); Position pos = this.computePositionOnPlane(null, globe, segmentPlane, u, v, false); @@ -1727,8 +1569,7 @@ protected void computePlaneVertices(Globe globe, SegmentPlane segmentPlane, @SuppressWarnings({"UnusedDeclaration"}) protected void computePlaneNormals(Globe globe, SegmentPlane segmentPlane, int indexCount, int vertexCount, - IntBuffer indices, DoubleBuffer vertices, DoubleBuffer buffer) - { + IntBuffer indices, DoubleBuffer vertices, DoubleBuffer buffer) { double[] altitudes = segmentPlane.getPlaneAltitudes(); LatLon[] locations = segmentPlane.getPlaneLocations(); @@ -1741,26 +1582,21 @@ protected void computePlaneNormals(Globe globe, SegmentPlane segmentPlane, int i Vec4 normal = e1.cross3(e2).normalize3(); - for (int v = 0; v < vertexCount; v++) - { + for (int v = 0; v < vertexCount; v++) { putVertex3(normal, v, buffer); } } - private static double clamp(double x, double min, double max) - { + private static double clamp(double x, double min, double max) { return (x < min) ? min : ((x > max) ? max : x); } //**************************************************************// //******************** Border Construction *******************// //**************************************************************// - // TODO: investigate necessary changes to create a general-use cylinder with caps, a height, and a radius. - @SuppressWarnings({"UnusedDeclaration"}) - protected void createBorderGeometry(Globe globe, SegmentPlane segmentPlane, RenderInfo renderInfo) - { + protected void createBorderGeometry(Globe globe, SegmentPlane segmentPlane, RenderInfo renderInfo) { int slices = 16; int stacks = 32; int loops = 8; @@ -1769,41 +1605,35 @@ protected void createBorderGeometry(Globe globe, SegmentPlane segmentPlane, Rend renderInfo.borderCylinderIndexCount = gb.getCylinderIndexCount(slices, stacks); if (renderInfo.borderCylinderIndices == null - || renderInfo.borderCylinderIndices.capacity() < renderInfo.borderCylinderIndexCount) - { + || renderInfo.borderCylinderIndices.capacity() < renderInfo.borderCylinderIndexCount) { renderInfo.borderCylinderIndices = Buffers.newDirectIntBuffer(renderInfo.borderCylinderIndexCount); } renderInfo.borderCapIndexCount = gb.getDiskIndexCount(slices, loops); if (renderInfo.borderCapIndices == null - || renderInfo.borderCapIndices.capacity() < renderInfo.borderCapIndexCount) - { + || renderInfo.borderCapIndices.capacity() < renderInfo.borderCapIndexCount) { renderInfo.borderCapIndices = Buffers.newDirectIntBuffer(renderInfo.borderCapIndexCount); } int cylinderVertexCount = gb.getCylinderVertexCount(slices, stacks); int cylinderCoordCount = 3 * cylinderVertexCount; if (renderInfo.borderCylinderVertices == null - || renderInfo.borderCylinderVertices.capacity() < cylinderCoordCount) - { + || renderInfo.borderCylinderVertices.capacity() < cylinderCoordCount) { renderInfo.borderCylinderVertices = Buffers.newDirectFloatBuffer(cylinderCoordCount); } if (renderInfo.borderCylinderNormals == null - || renderInfo.borderCylinderNormals.capacity() < cylinderCoordCount) - { + || renderInfo.borderCylinderNormals.capacity() < cylinderCoordCount) { renderInfo.borderCylinderNormals = Buffers.newDirectFloatBuffer(cylinderCoordCount); } int capVertexCount = gb.getDiskVertexCount(slices, loops); int capCoordCount = 3 * capVertexCount; if (renderInfo.borderCapVertices == null - || renderInfo.borderCapVertices.capacity() < capCoordCount) - { + || renderInfo.borderCapVertices.capacity() < capCoordCount) { renderInfo.borderCapVertices = Buffers.newDirectFloatBuffer(capCoordCount); } if (renderInfo.borderCapNormals == null - || renderInfo.borderCapNormals.capacity() < capCoordCount) - { + || renderInfo.borderCapNormals.capacity() < capCoordCount) { renderInfo.borderCapNormals = Buffers.newDirectFloatBuffer(capCoordCount); } @@ -1841,49 +1671,41 @@ protected void createBorderGeometry(Globe globe, SegmentPlane segmentPlane, Rend //**************************************************************// //******************** Control Point Construction ************// //**************************************************************// - @SuppressWarnings({"UnusedDeclaration"}) - protected void createControlPointGeometry(Globe globe, SegmentPlane segmentPlane, RenderInfo renderInfo) - { - if (renderInfo.markerShapeMap == null) + protected void createControlPointGeometry(Globe globe, SegmentPlane segmentPlane, RenderInfo renderInfo) { + if (renderInfo.markerShapeMap == null) { renderInfo.markerShapeMap = new HashMap(); + } } //**************************************************************// //******************** Ray-Geometry Intersection *************// //**************************************************************// - - protected Vec4 intersectRayWithFill(Line ray, RenderInfo renderInfo) - { - if (renderInfo.planeFillIndices != null && renderInfo.planeVertices != null) - { + protected Vec4 intersectRayWithFill(Line ray, RenderInfo renderInfo) { + if (renderInfo.planeFillIndices != null && renderInfo.planeVertices != null) { return this.intersectRayWithTriangleStrip(ray, - renderInfo.planeFillIndexCount, renderInfo.planeFillIndices, - renderInfo.planeVertices, renderInfo.planeReferenceCenter); + renderInfo.planeFillIndexCount, renderInfo.planeFillIndices, + renderInfo.planeVertices, renderInfo.planeReferenceCenter); } return null; } - protected Vec4 computeNearestOutlineToPoint(Vec4 point, RenderInfo renderInfo) - { - if (renderInfo.planeOutlineIndices != null && renderInfo.planeVertices != null) - { + protected Vec4 computeNearestOutlineToPoint(Vec4 point, RenderInfo renderInfo) { + if (renderInfo.planeOutlineIndices != null && renderInfo.planeVertices != null) { return this.computeNearestLineToPoint(point, - renderInfo.planeOutlineIndexCount, renderInfo.planeOutlineIndices, - renderInfo.planeVertices, renderInfo.planeReferenceCenter); + renderInfo.planeOutlineIndexCount, renderInfo.planeOutlineIndices, + renderInfo.planeVertices, renderInfo.planeReferenceCenter); } return null; } - protected Vec4 computeNearestGridLineToPoint(Vec4 point, RenderInfo renderInfo) - { - if (renderInfo.planeGridIndices != null && renderInfo.planeVertices != null) - { + protected Vec4 computeNearestGridLineToPoint(Vec4 point, RenderInfo renderInfo) { + if (renderInfo.planeGridIndices != null && renderInfo.planeVertices != null) { return this.computeNearestLineToPoint(point, - renderInfo.planeGridIndexCount, renderInfo.planeGridIndices, - renderInfo.planeVertices, renderInfo.planeReferenceCenter); + renderInfo.planeGridIndexCount, renderInfo.planeGridIndices, + renderInfo.planeVertices, renderInfo.planeReferenceCenter); } return null; @@ -1891,24 +1713,20 @@ protected Vec4 computeNearestGridLineToPoint(Vec4 point, RenderInfo renderInfo) // TODO: this method could be of general use protected Vec4 computeNearestLineToPoint(Vec4 point, int count, IntBuffer indices, DoubleBuffer vertices, - Vec4 referenceCenter) - { + Vec4 referenceCenter) { Vec4 intersectionPoint = null; double nearestDistance = Double.MAX_VALUE; - for (int i = 0; i < (count - 1); i += 2) - { + for (int i = 0; i < (count - 1); i += 2) { int position = indices.get(i); Vec4 v1 = getVertex3(position, vertices).add3(referenceCenter); position = indices.get(i + 1); Vec4 v2 = getVertex3(position, vertices).add3(referenceCenter); Vec4 vec = nearestPointOnSegment(v1, v2, point); - if (vec != null) - { + if (vec != null) { double d = point.distanceTo3(vec); - if (d < nearestDistance) - { + if (d < nearestDistance) { nearestDistance = d; intersectionPoint = vec; } @@ -1923,13 +1741,11 @@ protected Vec4 computeNearestLineToPoint(Vec4 point, int count, IntBuffer indice // TODO: this method could be of general use protected Vec4 intersectRayWithTriangleStrip(Line ray, int count, IntBuffer indices, DoubleBuffer vertices, - Vec4 referenceCenter) - { + Vec4 referenceCenter) { Vec4 intersectionPoint = null; double nearestDistance = Double.MAX_VALUE; - for (int i = 0; i < (count - 2); i++) - { + for (int i = 0; i < (count - 2); i++) { int position = indices.get(i); Vec4 v1 = getVertex3(position, vertices).add3(referenceCenter); position = indices.get(i + 1); @@ -1938,21 +1754,16 @@ protected Vec4 intersectRayWithTriangleStrip(Line ray, int count, IntBuffer indi Vec4 v3 = getVertex3(position, vertices).add3(referenceCenter); Triangle triangle; - if ((i % 2) == 0) - { + if ((i % 2) == 0) { triangle = new Triangle(v1, v2, v3); - } - else - { + } else { triangle = new Triangle(v2, v1, v3); } Vec4 vec = triangle.intersect(ray); - if (vec != null) - { + if (vec != null) { double d = ray.getOrigin().distanceTo3(vec); - if (d < nearestDistance) - { + if (d < nearestDistance) { nearestDistance = d; intersectionPoint = vec; } @@ -1965,16 +1776,14 @@ protected Vec4 intersectRayWithTriangleStrip(Line ray, int count, IntBuffer indi return intersectionPoint; } - protected static Vec4 getVertex3(int position, DoubleBuffer vertices) - { + protected static Vec4 getVertex3(int position, DoubleBuffer vertices) { double[] compArray = new double[3]; vertices.position(3 * position); vertices.get(compArray, 0, 3); return Vec4.fromArray3(compArray, 0); } - protected static void putVertex3(Vec4 vec, int position, DoubleBuffer vertices) - { + protected static void putVertex3(Vec4 vec, int position, DoubleBuffer vertices) { double[] compArray = new double[3]; vec.toArray3(compArray, 0); vertices.position(3 * position); @@ -1982,22 +1791,16 @@ protected static void putVertex3(Vec4 vec, int position, DoubleBuffer vertices) } // TODO: identical to a method in AirspaceEditorUtil; consolidate usage in a general place - private static Vec4 nearestPointOnSegment(Vec4 p1, Vec4 p2, Vec4 point) - { + private static Vec4 nearestPointOnSegment(Vec4 p1, Vec4 p2, Vec4 point) { Vec4 segment = p2.subtract3(p1); Vec4 dir = segment.normalize3(); double dot = point.subtract3(p1).dot3(dir); - if (dot < 0.0) - { + if (dot < 0.0) { return p1; - } - else if (dot > segment.getLength3()) - { + } else if (dot > segment.getLength3()) { return p2; - } - else - { + } else { return Vec4.fromLine3(p1, dot, dir); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/AbstractTrackReader.java b/src/gov/nasa/worldwindx/applications/sar/tracks/AbstractTrackReader.java index b88818d70d..16e037b173 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/AbstractTrackReader.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/AbstractTrackReader.java @@ -17,36 +17,28 @@ * @author dcollins * @version $Id: AbstractTrackReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractTrackReader implements TrackReader -{ +public abstract class AbstractTrackReader implements TrackReader { + protected abstract Track[] doRead(InputStream inputStream) throws IOException; - public boolean canRead(Object source) - { + public boolean canRead(Object source) { return (source != null) && this.doCanRead(source); } - public Track[] read(Object source) - { - if (source == null) - { + public Track[] read(Object source) { + if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - try - { + try { return this.doRead(source); - } - catch (IOException e) - { + } catch (IOException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToReadFrom", source); Logging.logger().severe(message); throw new WWRuntimeException(message, e); - } - catch (WWUnrecognizedException e) - { + } catch (WWUnrecognizedException e) { // Source type is passed up the call stack in the WWUnrecognizedException's message. String message = Logging.getMessage("generic.UnrecognizedSourceType", e.getMessage()); Logging.logger().severe(message); @@ -54,31 +46,28 @@ public Track[] read(Object source) } } - protected boolean doCanRead(Object source) - { - if (source instanceof File) + protected boolean doCanRead(Object source) { + if (source instanceof File) { return this.doCanRead(((File) source).getPath()); - else if (source instanceof String) + } else if (source instanceof String) { return this.doCanRead((String) source); - else if (source instanceof URL) + } else if (source instanceof URL) { return this.doCanRead((URL) source); - else if (source instanceof InputStream) + } else if (source instanceof InputStream) { return this.doCanRead((InputStream) source); + } return false; } - protected boolean doCanRead(String filePath) - { - if (!this.acceptFilePath(filePath)) + protected boolean doCanRead(String filePath) { + if (!this.acceptFilePath(filePath)) { return false; + } - try - { + try { return this.doRead(filePath) != null; - } - catch (Exception e) - { + } catch (Exception e) { // Not interested in logging the exception. We just want to return false to indicate that the source // cannot be read. } @@ -86,18 +75,15 @@ protected boolean doCanRead(String filePath) return false; } - protected boolean doCanRead(URL url) - { + protected boolean doCanRead(URL url) { File file = WWIO.convertURLToFile(url); - if (file != null) + if (file != null) { return this.doCanRead(file.getPath()); + } - try - { + try { return this.doRead(url) != null; - } - catch (Exception e) - { + } catch (Exception e) { // Not interested in logging the exception. We just want to return false to indicate that the source // cannot be read. } @@ -105,14 +91,10 @@ protected boolean doCanRead(URL url) return false; } - protected boolean doCanRead(InputStream inputStream) - { - try - { + protected boolean doCanRead(InputStream inputStream) { + try { return this.doRead(inputStream) != null; - } - catch (Exception e) - { + } catch (Exception e) { // Not interested in logging the exception. We just want to return false to indicate that the source // cannot be read. } @@ -120,59 +102,50 @@ protected boolean doCanRead(InputStream inputStream) return false; } - protected boolean acceptFilePath(String filePath) - { + protected boolean acceptFilePath(String filePath) { return true; } - protected Track[] doRead(Object source) throws IOException - { - if (source instanceof File) + protected Track[] doRead(Object source) throws IOException { + if (source instanceof File) { return this.doRead(((File) source).getPath()); - else if (source instanceof String) + } else if (source instanceof String) { return this.doRead((String) source); - else if (source instanceof URL) + } else if (source instanceof URL) { return this.doRead((URL) source); - else if (source instanceof InputStream) + } else if (source instanceof InputStream) { return this.doRead((InputStream) source); + } // Pass the source type up the call stack in the WWUnrecognizedException's message. This enables us to be more // specific about the source type if a subclass has more detailed information to offer. throw new WWUnrecognizedException(source.toString()); } - protected Track[] doRead(String filePath) throws IOException - { + protected Track[] doRead(String filePath) throws IOException { InputStream inputStream = null; - try - { + try { inputStream = WWIO.openFileOrResourceStream(filePath, this.getClass()); return this.doRead(inputStream); - } - finally - { + } finally { WWIO.closeStream(inputStream, filePath); } } - protected Track[] doRead(URL url) throws IOException - { + protected Track[] doRead(URL url) throws IOException { InputStream inputStream = null; - try - { + try { inputStream = url.openStream(); return this.doRead(inputStream); - } - finally - { + } finally { WWIO.closeStream(inputStream, url.toString()); } } - protected Track[] asArray(List trackList) - { - if (trackList == null) + protected Track[] asArray(List trackList) { + if (trackList == null) { return null; + } Track[] trackArray = new Track[trackList.size()]; trackList.toArray(trackArray); diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/CSVTrackReader.java b/src/gov/nasa/worldwindx/applications/sar/tracks/CSVTrackReader.java index f310eea1be..4f945a0c29 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/CSVTrackReader.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/CSVTrackReader.java @@ -14,26 +14,22 @@ * @author dcollins * @version $Id: CSVTrackReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CSVTrackReader extends AbstractTrackReader -{ - public CSVTrackReader() - { +public class CSVTrackReader extends AbstractTrackReader { + + public CSVTrackReader() { } - public String getDescription() - { + public String getDescription() { return "Comma Separated Value (*.csv)"; } - protected Track[] doRead(InputStream inputStream) throws IOException - { + protected Track[] doRead(InputStream inputStream) throws IOException { CSVReader reader = new CSVReader(); reader.readStream(inputStream, null); // un-named stream return this.asArray(reader.getTracks()); } - protected boolean acceptFilePath(String filePath) - { + protected boolean acceptFilePath(String filePath) { return filePath.toLowerCase().endsWith(".csv"); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/CompoundFilter.java b/src/gov/nasa/worldwindx/applications/sar/tracks/CompoundFilter.java index 7768bb996b..60453e5adc 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/CompoundFilter.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/CompoundFilter.java @@ -11,46 +11,42 @@ * @author dcollins * @version $Id: CompoundFilter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CompoundFilter extends javax.swing.filechooser.FileFilter implements java.io.FileFilter -{ +public class CompoundFilter extends javax.swing.filechooser.FileFilter implements java.io.FileFilter { + private final java.io.FileFilter[] filters; private final String description; - public CompoundFilter(java.io.FileFilter[] filters, String description) - { + public CompoundFilter(java.io.FileFilter[] filters, String description) { this.filters = new java.io.FileFilter[filters.length]; System.arraycopy(filters, 0, this.filters, 0, filters.length); this.description = description; } - public java.io.FileFilter[] getFilters() - { + public java.io.FileFilter[] getFilters() { java.io.FileFilter[] copy = new java.io.FileFilter[this.filters.length]; System.arraycopy(this.filters, 0, copy, 0, this.filters.length); return copy; } - public String getDescription() - { + public String getDescription() { return this.description; } - public boolean accept(java.io.File file) - { - if (file == null) - { + public boolean accept(java.io.File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } - if (file.isDirectory()) + if (file.isDirectory()) { return true; + } - for (java.io.FileFilter filter : this.filters) - { - if (filter.accept(file)) + for (java.io.FileFilter filter : this.filters) { + if (filter.accept(file)) { return true; + } } return false; diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/GPXTrackReader.java b/src/gov/nasa/worldwindx/applications/sar/tracks/GPXTrackReader.java index 398ba9a3c8..e7e73a3028 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/GPXTrackReader.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/GPXTrackReader.java @@ -18,41 +18,32 @@ * @author dcollins * @version $Id: GPXTrackReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class GPXTrackReader extends AbstractTrackReader -{ - public GPXTrackReader() - { +public class GPXTrackReader extends AbstractTrackReader { + + public GPXTrackReader() { } - public String getDescription() - { + public String getDescription() { return "GPS Exchange Format (*.xml, *.gpx)"; } - protected Track[] doRead(InputStream inputStream) throws IOException - { - try - { + protected Track[] doRead(InputStream inputStream) throws IOException { + try { GpxReader reader = new GpxReader(); reader.readStream(inputStream); return this.asArray(reader.getTracks()); - } - catch (ParserConfigurationException e) - { + } catch (ParserConfigurationException e) { String message = Logging.getMessage("XML.ParserConfigurationException"); Logging.logger().finest(message); throw new WWRuntimeException(e); - } - catch (SAXException e) - { + } catch (SAXException e) { String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", inputStream); Logging.logger().severe(message); throw new WWRuntimeException(e); } } - protected boolean acceptFilePath(String filePath) - { + protected boolean acceptFilePath(String filePath) { String lowerCasePath = filePath.toLowerCase(); return lowerCasePath.endsWith(".xml") || lowerCasePath.endsWith(".gpx"); } diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/NMEATrackReader.java b/src/gov/nasa/worldwindx/applications/sar/tracks/NMEATrackReader.java index 5efcdfd59e..e9daadfb27 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/NMEATrackReader.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/NMEATrackReader.java @@ -14,26 +14,22 @@ * @author dcollins * @version $Id: NMEATrackReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class NMEATrackReader extends AbstractTrackReader -{ - public NMEATrackReader() - { +public class NMEATrackReader extends AbstractTrackReader { + + public NMEATrackReader() { } - public String getDescription() - { + public String getDescription() { return "National Marine Electronics Association (*.nmea)"; } - protected Track[] doRead(InputStream inputStream) throws IOException - { + protected Track[] doRead(InputStream inputStream) throws IOException { NmeaReader reader = new NmeaReader(); reader.readStream(inputStream, null); // un-named stream return this.asArray(reader.getTracks()); } - protected boolean acceptFilePath(String filePath) - { + protected boolean acceptFilePath(String filePath) { return filePath.toLowerCase().endsWith(".nmea"); } } diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/SaveTrackFilter.java b/src/gov/nasa/worldwindx/applications/sar/tracks/SaveTrackFilter.java index 36eda1dc3b..854d043cbd 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/SaveTrackFilter.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/SaveTrackFilter.java @@ -13,46 +13,39 @@ * @author dcollins * @version $Id: SaveTrackFilter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SaveTrackFilter extends javax.swing.filechooser.FileFilter implements java.io.FileFilter -{ +public class SaveTrackFilter extends javax.swing.filechooser.FileFilter implements java.io.FileFilter { + private final int format; private final String description; private final String[] suffixes; - public SaveTrackFilter(int format, String description, String[] suffixes) - { + public SaveTrackFilter(int format, String description, String[] suffixes) { this.format = format; this.description = description; this.suffixes = new String[suffixes.length]; System.arraycopy(suffixes, 0, this.suffixes, 0, suffixes.length); } - public int getFormat() - { + public int getFormat() { return this.format; } - public String getDescription() - { + public String getDescription() { return this.description; } - public String[] getSuffixes() - { + public String[] getSuffixes() { String[] copy = new String[this.suffixes.length]; System.arraycopy(this.suffixes, 0, copy, 0, this.suffixes.length); return copy; } - public boolean accept(java.io.File file) - { + public boolean accept(java.io.File file) { return true; } - public java.io.File appendSuffix(java.io.File file) - { - if (file == null) - { + public java.io.File appendSuffix(java.io.File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); @@ -61,12 +54,12 @@ public java.io.File appendSuffix(java.io.File file) String path = file.getPath(); String lowerCasePath = path.toLowerCase(); - for (String suffix : this.suffixes) - { - if (lowerCasePath.endsWith(suffix)) + for (String suffix : this.suffixes) { + if (lowerCasePath.endsWith(suffix)) { return file; + } } return new File(WWIO.replaceSuffix(path, this.suffixes[0])); } -} \ No newline at end of file +} diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/TrackReader.java b/src/gov/nasa/worldwindx/applications/sar/tracks/TrackReader.java index 42b5c81097..2fd515f2f3 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/TrackReader.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/TrackReader.java @@ -11,8 +11,8 @@ * @author dcollins * @version $Id: TrackReader.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TrackReader -{ +public interface TrackReader { + String getDescription(); boolean canRead(Object source); diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/TrackReaderFilter.java b/src/gov/nasa/worldwindx/applications/sar/tracks/TrackReaderFilter.java index 2f012c5d8b..f2800778e6 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/TrackReaderFilter.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/TrackReaderFilter.java @@ -11,29 +11,24 @@ * @author dcollins * @version $Id: TrackReaderFilter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class TrackReaderFilter extends javax.swing.filechooser.FileFilter implements java.io.FileFilter -{ +public class TrackReaderFilter extends javax.swing.filechooser.FileFilter implements java.io.FileFilter { + protected final TrackReader trackReader; - public TrackReaderFilter(TrackReader trackReader) - { + public TrackReaderFilter(TrackReader trackReader) { this.trackReader = trackReader; } - public final TrackReader getTrackReader() - { + public final TrackReader getTrackReader() { return this.trackReader; } - public String getDescription() - { + public String getDescription() { return this.trackReader.getDescription(); } - public boolean accept(java.io.File file) - { - if (file == null) - { + public boolean accept(java.io.File file) { + if (file == null) { String message = Logging.getMessage("nullValue.FileIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); diff --git a/src/gov/nasa/worldwindx/applications/sar/tracks/TrackWriter.java b/src/gov/nasa/worldwindx/applications/sar/tracks/TrackWriter.java index 4196dfa8d4..2128eddbf1 100644 --- a/src/gov/nasa/worldwindx/applications/sar/tracks/TrackWriter.java +++ b/src/gov/nasa/worldwindx/applications/sar/tracks/TrackWriter.java @@ -9,6 +9,5 @@ * @author dcollins * @version $Id: TrackWriter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface TrackWriter -{ +public interface TrackWriter { } diff --git a/src/gov/nasa/worldwindx/applications/sar/worldwind-nosa-1.3.html b/src/gov/nasa/worldwindx/applications/sar/worldwind-nosa-1.3.html index bbd5ad5eee..dcb063cf8e 100644 --- a/src/gov/nasa/worldwindx/applications/sar/worldwind-nosa-1.3.html +++ b/src/gov/nasa/worldwindx/applications/sar/worldwind-nosa-1.3.html @@ -2,291 +2,291 @@ ~ Copyright (C) 2012 United States Government as represented by the Administrator of the ~ National Aeronautics and Space Administration. ~ All Rights Reserved. - --> +--> - - - - - NASA WorldWind License - - - - - - - - - - -

          NASA WORLDWIND

          - -

          Copyright � 2004-2005 United States Government as represented by the Administrator of the National - Aeronautics and Space Administration. All Rights Reserved.
          Copyright � 2004-2005 Contributors. All Rights - Reserved. -

          - -

           

          - -

          - -

          NASA OPEN SOURCE AGREEMENT VERSION 1.3

          - -

          THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE, REPRODUCTION, DISTRIBUTION, - MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE UNITED STATES GOVERNMENT AS - REPRESENTED BY THE GOVERNMENT AGENCY LISTED BELOW ("GOVERNMENT AGENCY"). THE UNITED STATES GOVERNMENT, AS - REPRESENTED BY GOVERNMENT AGENCY, IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT DISTRIBUTIONS OR - REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES, MODIFIES OR REDISTRIBUTES THE - SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES - AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.

          - -

          Government Agency: National Aeronautics and Space Administration (NASA)
          Government Agency Original - Software Designation: ARC-15166-1
          Government Agency Original Software Title: WorldWind Version 1.3
          User - Registration Requested. Please Visit http://opensource.arc.nasa.gov/
          Government Agency Point of Contact - for Original Software: Patrick.Hogan@nasa.gov

          - -

           

          - -

          1. DEFINITIONS

          - -

          A. "Contributor" means Government Agency, as the developer of the Original Software, - and any entity that makes a Modification.
          B. "Covered Patents" mean patent claims licensable by - a Contributor that are necessarily infringed by the use or sale of its Modification alone or when combined with the - Subject Software.
          C. "Display" means the showing of a copy of the Subject Software, either - directly or by means of an image, or any other device.
          D. "Distribution" means conveyance or - transfer of the Subject Software, regardless of means, to another.
          E. "Larger Work" means - computer software that combines Subject Software, or portions thereof, with software separate from the Subject - Software that is not governed by the terms of this Agreement.
          F. "Modification" means any - alteration of, including addition to or deletion from, the substance or structure of either the Original Software or - Subject Software, and includes derivative works, as that term is defined in the Copyright Statute, 17 USC 101. - However, the act of including Subject Software as part of a Larger Work does not in and of itself constitute a - Modification.
          G. "Original Software" means the computer software first released under this - Agreement by Government Agency with Government Agency designation ARC-15166-1 and entitled WorldWind, including - source code, object code and accompanying documentation, if any.
          H. "Recipient" means anyone - who acquires the Subject Software under this Agreement, including all Contributors.
          I. - "Redistribution" means Distribution of the Subject Software after a Modification has been made.
          - J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
          - K. "Sale" means the exchange of the Subject Software for money or equivalent value.
          L. - "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
          - M. "Use" means the application or employment of the Subject Software for any purpose.

          - -

           

          - -

          2. GRANT OF RIGHTS

          - -

          A. Under Non-Patent Rights: -Subject to the terms and conditions of this Agreement, each -Contributor, with respect to its own contribution to the Subject -Software, hereby grants to each Recipient a non-exclusive, world-wide, -royalty-free license to engage in the following activities pertaining -to the Subject Software:

          - -

          1. Use
          2. Distribution
          3. Reproduction
          - 4. Modification
          5. Redistribution
          6. Display

          - -

          B. Under Patent Rights: -Subject to the terms and conditions of this Agreement, each -Contributor, with respect to its own contribution to the Subject -Software, hereby grants to each Recipient under Covered Patents a -non-exclusive, world-wide, royalty-free license to engage in the -following activities pertaining to the Subject Software:

          - -

          1. Use
          2. Distribution
          3. Reproduction
          - 4. Sale
          5. Offer for Sale

          - -

          C. The rights granted under Paragraph B. also apply to the combination of a - Contributor’s Modification and the Subject Software if, at the time the Modification is added by the - Contributor, the addition of such Modification causes the combination to be covered by the Covered Patents. It does - not apply to any other combinations that include a Modification.

          - -

          D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those - same rights. Such sublicense must be under the same terms and conditions of this Agreement.

          - -

           

          - -

          3. OBLIGATIONS OF RECIPIENT

          - -

          A. Distribution or Redistribution of the Subject Software must be made under this - Agreement except for additions covered under paragraph 3H.

          - -

          1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of - this Agreement must be included with each copy of the Subject Software; and
          2. If Recipient - distributes or redistributes the Subject Software in any form other than source code, Recipient must also make the - source code freely available, and must provide with each copy of the Subject Software information on how to obtain - the source code in a reasonable manner on or through a medium customarily used for software exchange.

          - -

          B. Each Recipient must ensure that the following copyright notice appears prominently - in the Subject Software:
          Copyright (C) 2001 United States Government
          as represented by the Administrator of - the
          National Aeronautics and Space Administration.
          All Rights Reserved.

          - -

          C. Each Contributor must characterize its alteration of the Subject Software as a - Modification and must identify itself as the originator of its Modification in a manner that reasonably allows - subsequent Recipients to identify the originator of the Modification. In fulfillment of these requirements, - Contributor must include a file (e.g., a change log file) that describes the alterations made and the date of the - alterations, identifies Contributor as originator of the alterations, and consents to characterization of the - alterations as a Modification, for example, by including a statement that the Modification is derived, directly or - indirectly, from Original Software provided by Government Agency. Once consent is granted, it may not thereafter be - revoked.

          - -

          D. A Contributor may add its own copyright notice to the Subject Software. Once a - copyright notice has been added to the Subject Software, a Recipient may not remove it without the express - permission of the Contributor who added the notice.

          - -

          E. A Recipient may not make any representation in the Subject Software or in any - promotional, advertising or other material that may be construed as an endorsement by Government Agency or by any - prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial advantage by - the fact of Government Agency's or a prior Recipient’s participation in this Agreement.

          - -

          F. In an effort to track usage and maintain accurate records of the Subject Software, - each Recipient, upon receipt of the Subject Software, is requested to register with Government Agency by visiting - the following website: http://opensource.arc.nasa.gov. Recipient’s - name and personal information shall be used for statistical purposes only. Once a Recipient makes a Modification - available, it is requested that the Recipient inform Government Agency at the web site provided above how to access - the Modification.

          - -

          G. Each Contributor represents that that its Modification is believed to be - Contributor’s original creation and does not violate any existing agreements, regulations, statutes or rules, - and further that Contributor has sufficient rights to grant the rights conveyed by this Agreement.

          - -

          H. A Recipient may choose to offer, and to charge a fee for, warranty, support, - indemnity and/or liability obligations to one or more other Recipients of the Subject Software. A Recipient may do - so, however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a Recipient - must make it absolutely clear that any such warranty, support, indemnity and/or liability obligation is offered by - that Recipient alone. Further, such Recipient agrees to indemnify Government Agency and every other Recipient for - any liability incurred by them as a result of warranty, support, indemnity and/or liability offered by such - Recipient.

          - -

          I. A Recipient may create a Larger Work by combining Subject Software with separate - software not governed by the terms of this agreement and distribute the Larger Work as a single product. In such - case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work is subject to - this Agreement.

          - -

          J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice - that export of any goods or technical data from the United States may require some form of export license from the - U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under U.S. laws. - Government Agency neither represents that a license shall not be required nor that, if required, it shall be issued. - Nothing granted herein provides any such export license.

          - -

           

          - -

          4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

          - -

          A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED - "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, - ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR - FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES - NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING - DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, - GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE - ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS."

          - -

          B. Waiver and Indemnity: -RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES -GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR -RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY -LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH -USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, -RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND -HOLD HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND -SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED -BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE -IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.

          - -

           

          - -

          5. GENERAL TERMS

          - -

          A. Termination: -This Agreement and the rights granted hereunder will terminate -automatically if a Recipient fails to comply with these terms and -conditions, and fails to cure such noncompliance within thirty (30) -days of becoming aware of such noncompliance. Upon termination, a -Recipient agrees to immediately cease use and distribution of the -Subject Software. All sublicenses to the Subject Software properly -granted by the breaching Recipient shall survive any such termination -of this Agreement.

          - -

          B. Severability: -If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of -the remainder of the terms of this Agreement.

          - -

          C. Applicable Law: -This Agreement shall be subject to United States federal law only for -all purposes, including, but not limited to, determining the validity -of this Agreement, the meaning of its provisions and the rights, -obligations and remedies of the parties.

          - -

          D. Entire Understanding: -This Agreement constitutes the entire understanding and agreement of -the parties relating to release of the Subject Software and may not be -superseded, modified or amended except by further written agreement -duly executed by the parties.

          - -

          E. Binding Authority: -By accepting and using the Subject Software under this Agreement, a -Recipient affirms its authority to bind the Recipient to all terms and -conditions of this Agreement and that that Recipient hereby agrees to -all terms and conditions herein.

          - -

          F. Point of Contact: -Any Recipient contact with Government Agency is to be directed to the -designated representative as follows: Patrick.Hogan@nasa.gov

          - + + + + + NASA WorldWind License + + + + + + + + + + +

          NASA WORLDWIND

          + +

          Copyright � 2004-2005 United States Government as represented by the Administrator of the National + Aeronautics and Space Administration. All Rights Reserved.
          Copyright � 2004-2005 Contributors. All Rights + Reserved. +

          + +

           

          + +

          + +

          NASA OPEN SOURCE AGREEMENT VERSION 1.3

          + +

          THIS OPEN SOURCE AGREEMENT ("AGREEMENT") DEFINES THE RIGHTS OF USE, REPRODUCTION, DISTRIBUTION, + MODIFICATION AND REDISTRIBUTION OF CERTAIN COMPUTER SOFTWARE ORIGINALLY RELEASED BY THE UNITED STATES GOVERNMENT AS + REPRESENTED BY THE GOVERNMENT AGENCY LISTED BELOW ("GOVERNMENT AGENCY"). THE UNITED STATES GOVERNMENT, AS + REPRESENTED BY GOVERNMENT AGENCY, IS AN INTENDED THIRD-PARTY BENEFICIARY OF ALL SUBSEQUENT DISTRIBUTIONS OR + REDISTRIBUTIONS OF THE SUBJECT SOFTWARE. ANYONE WHO USES, REPRODUCES, DISTRIBUTES, MODIFIES OR REDISTRIBUTES THE + SUBJECT SOFTWARE, AS DEFINED HEREIN, OR ANY PART THEREOF, IS, BY THAT ACTION, ACCEPTING IN FULL THE RESPONSIBILITIES + AND OBLIGATIONS CONTAINED IN THIS AGREEMENT.

          + +

          Government Agency: National Aeronautics and Space Administration (NASA)
          Government Agency Original + Software Designation: ARC-15166-1
          Government Agency Original Software Title: WorldWind Version 1.3
          User + Registration Requested. Please Visit http://opensource.arc.nasa.gov/
          Government Agency Point of Contact + for Original Software: Patrick.Hogan@nasa.gov

          + +

           

          + +

          1. DEFINITIONS

          + +

          A. "Contributor" means Government Agency, as the developer of the Original Software, + and any entity that makes a Modification.
          B. "Covered Patents" mean patent claims licensable by + a Contributor that are necessarily infringed by the use or sale of its Modification alone or when combined with the + Subject Software.
          C. "Display" means the showing of a copy of the Subject Software, either + directly or by means of an image, or any other device.
          D. "Distribution" means conveyance or + transfer of the Subject Software, regardless of means, to another.
          E. "Larger Work" means + computer software that combines Subject Software, or portions thereof, with software separate from the Subject + Software that is not governed by the terms of this Agreement.
          F. "Modification" means any + alteration of, including addition to or deletion from, the substance or structure of either the Original Software or + Subject Software, and includes derivative works, as that term is defined in the Copyright Statute, 17 USC 101. + However, the act of including Subject Software as part of a Larger Work does not in and of itself constitute a + Modification.
          G. "Original Software" means the computer software first released under this + Agreement by Government Agency with Government Agency designation ARC-15166-1 and entitled WorldWind, including + source code, object code and accompanying documentation, if any.
          H. "Recipient" means anyone + who acquires the Subject Software under this Agreement, including all Contributors.
          I. + "Redistribution" means Distribution of the Subject Software after a Modification has been made.
          + J. "Reproduction" means the making of a counterpart, image or copy of the Subject Software.
          + K. "Sale" means the exchange of the Subject Software for money or equivalent value.
          L. + "Subject Software" means the Original Software, Modifications, or any respective parts thereof.
          + M. "Use" means the application or employment of the Subject Software for any purpose.

          + +

           

          + +

          2. GRANT OF RIGHTS

          + +

          A. Under Non-Patent Rights: + Subject to the terms and conditions of this Agreement, each + Contributor, with respect to its own contribution to the Subject + Software, hereby grants to each Recipient a non-exclusive, world-wide, + royalty-free license to engage in the following activities pertaining + to the Subject Software:

          + +

          1. Use
          2. Distribution
          3. Reproduction
          + 4. Modification
          5. Redistribution
          6. Display

          + +

          B. Under Patent Rights: + Subject to the terms and conditions of this Agreement, each + Contributor, with respect to its own contribution to the Subject + Software, hereby grants to each Recipient under Covered Patents a + non-exclusive, world-wide, royalty-free license to engage in the + following activities pertaining to the Subject Software:

          + +

          1. Use
          2. Distribution
          3. Reproduction
          + 4. Sale
          5. Offer for Sale

          + +

          C. The rights granted under Paragraph B. also apply to the combination of a + Contributor’s Modification and the Subject Software if, at the time the Modification is added by the + Contributor, the addition of such Modification causes the combination to be covered by the Covered Patents. It does + not apply to any other combinations that include a Modification.

          + +

          D. The rights granted in Paragraphs A. and B. allow the Recipient to sublicense those + same rights. Such sublicense must be under the same terms and conditions of this Agreement.

          + +

           

          + +

          3. OBLIGATIONS OF RECIPIENT

          + +

          A. Distribution or Redistribution of the Subject Software must be made under this + Agreement except for additions covered under paragraph 3H.

          + +

          1. Whenever a Recipient distributes or redistributes the Subject Software, a copy of + this Agreement must be included with each copy of the Subject Software; and
          2. If Recipient + distributes or redistributes the Subject Software in any form other than source code, Recipient must also make the + source code freely available, and must provide with each copy of the Subject Software information on how to obtain + the source code in a reasonable manner on or through a medium customarily used for software exchange.

          + +

          B. Each Recipient must ensure that the following copyright notice appears prominently + in the Subject Software:
          Copyright (C) 2001 United States Government
          as represented by the Administrator of + the
          National Aeronautics and Space Administration.
          All Rights Reserved.

          + +

          C. Each Contributor must characterize its alteration of the Subject Software as a + Modification and must identify itself as the originator of its Modification in a manner that reasonably allows + subsequent Recipients to identify the originator of the Modification. In fulfillment of these requirements, + Contributor must include a file (e.g., a change log file) that describes the alterations made and the date of the + alterations, identifies Contributor as originator of the alterations, and consents to characterization of the + alterations as a Modification, for example, by including a statement that the Modification is derived, directly or + indirectly, from Original Software provided by Government Agency. Once consent is granted, it may not thereafter be + revoked.

          + +

          D. A Contributor may add its own copyright notice to the Subject Software. Once a + copyright notice has been added to the Subject Software, a Recipient may not remove it without the express + permission of the Contributor who added the notice.

          + +

          E. A Recipient may not make any representation in the Subject Software or in any + promotional, advertising or other material that may be construed as an endorsement by Government Agency or by any + prior Recipient of any product or service provided by Recipient, or that may seek to obtain commercial advantage by + the fact of Government Agency's or a prior Recipient’s participation in this Agreement.

          + +

          F. In an effort to track usage and maintain accurate records of the Subject Software, + each Recipient, upon receipt of the Subject Software, is requested to register with Government Agency by visiting + the following website: http://opensource.arc.nasa.gov. Recipient’s + name and personal information shall be used for statistical purposes only. Once a Recipient makes a Modification + available, it is requested that the Recipient inform Government Agency at the web site provided above how to access + the Modification.

          + +

          G. Each Contributor represents that that its Modification is believed to be + Contributor’s original creation and does not violate any existing agreements, regulations, statutes or rules, + and further that Contributor has sufficient rights to grant the rights conveyed by this Agreement.

          + +

          H. A Recipient may choose to offer, and to charge a fee for, warranty, support, + indemnity and/or liability obligations to one or more other Recipients of the Subject Software. A Recipient may do + so, however, only on its own behalf and not on behalf of Government Agency or any other Recipient. Such a Recipient + must make it absolutely clear that any such warranty, support, indemnity and/or liability obligation is offered by + that Recipient alone. Further, such Recipient agrees to indemnify Government Agency and every other Recipient for + any liability incurred by them as a result of warranty, support, indemnity and/or liability offered by such + Recipient.

          + +

          I. A Recipient may create a Larger Work by combining Subject Software with separate + software not governed by the terms of this agreement and distribute the Larger Work as a single product. In such + case, the Recipient must make sure Subject Software, or portions thereof, included in the Larger Work is subject to + this Agreement.

          + +

          J. Notwithstanding any provisions contained herein, Recipient is hereby put on notice + that export of any goods or technical data from the United States may require some form of export license from the + U.S. Government. Failure to obtain necessary export licenses may result in criminal liability under U.S. laws. + Government Agency neither represents that a license shall not be required nor that, if required, it shall be issued. + Nothing granted herein provides any such export license.

          + +

           

          + +

          4. DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

          + +

          A. No Warranty: THE SUBJECT SOFTWARE IS PROVIDED + "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, + ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR + FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES + NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING + DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, + GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE + ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS."

          + +

          B. Waiver and Indemnity: + RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES + GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR + RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY + LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH + USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, + RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND + HOLD HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND + SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED + BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE + IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.

          + +

           

          + +

          5. GENERAL TERMS

          + +

          A. Termination: + This Agreement and the rights granted hereunder will terminate + automatically if a Recipient fails to comply with these terms and + conditions, and fails to cure such noncompliance within thirty (30) + days of becoming aware of such noncompliance. Upon termination, a + Recipient agrees to immediately cease use and distribution of the + Subject Software. All sublicenses to the Subject Software properly + granted by the breaching Recipient shall survive any such termination + of this Agreement.

          + +

          B. Severability: + If any provision of this Agreement is invalid or unenforceable under + applicable law, it shall not affect the validity or enforceability of + the remainder of the terms of this Agreement.

          + +

          C. Applicable Law: + This Agreement shall be subject to United States federal law only for + all purposes, including, but not limited to, determining the validity + of this Agreement, the meaning of its provisions and the rights, + obligations and remedies of the parties.

          + +

          D. Entire Understanding: + This Agreement constitutes the entire understanding and agreement of + the parties relating to release of the Subject Software and may not be + superseded, modified or amended except by further written agreement + duly executed by the parties.

          + +

          E. Binding Authority: + By accepting and using the Subject Software under this Agreement, a + Recipient affirms its authority to bind the Recipient to all terms and + conditions of this Agreement and that that Recipient hereby agrees to + all terms and conditions herein.

          + +

          F. Point of Contact: + Any Recipient contact with Government Agency is to be directed to the + designated representative as follows: Patrick.Hogan@nasa.gov

          + \ No newline at end of file diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/WorldWindow.java b/src/gov/nasa/worldwindx/applications/worldwindow/WorldWindow.java index 282299b047..f74fb80c3c 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/WorldWindow.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/WorldWindow.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow; import gov.nasa.worldwind.Configuration; @@ -17,44 +16,39 @@ * @author tag * @version $Id: WorldWindow.java 1923 2014-04-10 23:35:03Z tgaskins $ */ -public class WorldWindow -{ - static - { +public class WorldWindow { + + static { System.setProperty("gov.nasa.worldwind.app.config.document", - "gov/nasa/worldwindx/applications/worldwindow/config/worldwindow.worldwind.xml"); - if (Configuration.isMacOS()) - { + "gov/nasa/worldwindx/applications/worldwindow/config/worldwindow.worldwind.xml"); + if (Configuration.isMacOS()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); String s = Configuration.getStringValue(Constants.APPLICATION_DISPLAY_NAME); - if (s == null) + if (s == null) { s = "WorldWindow"; + } System.setProperty("com.apple.mrj.application.apple.menu.about.name", s); - } - else if (Configuration.isWindowsOS()) - { + } else if (Configuration.isWindowsOS()) { System.setProperty("sun.awt.noerasebackground", "true"); // prevents flashing during window resizing } } private static final String APP_CONFIGURATION - = "gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml"; + = "gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml"; - public static void main(String[] args) - { + public static void main(String[] args) { Controller controller = new Controller(); Dimension appSize = null; if (args.length >= 2) // The first two arguments are the application width and height. + { appSize = new Dimension(Integer.parseInt(args[0]), Integer.parseInt(args[1])); + } - try - { + try { controller.start(APP_CONFIGURATION, appSize); - } - catch (Exception e) - { + } catch (Exception e) { String msg = "Fatal application error"; controller.showErrorDialog(null, "Cannot Start Application", msg); Util.getLogger().log(Level.SEVERE, msg); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml b/src/gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml index 516d6d7328..1ee3c3550d 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml +++ b/src/gov/nasa/worldwindx/applications/worldwindow/config/AppConfiguration.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/config/InitialLayerConfiguration.xml b/src/gov/nasa/worldwindx/applications/worldwindow/config/InitialLayerConfiguration.xml index 76738cd576..83c1ddfd2c 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/config/InitialLayerConfiguration.xml +++ b/src/gov/nasa/worldwindx/applications/worldwindow/config/InitialLayerConfiguration.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/config/worldwindow.worldwind.xml b/src/gov/nasa/worldwindx/applications/worldwindow/config/worldwindow.worldwind.xml index e41c24839c..389a6658fd 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/config/worldwindow.worldwind.xml +++ b/src/gov/nasa/worldwindx/applications/worldwindow/config/worldwindow.worldwind.xml @@ -1,9 +1,9 @@ +~ Copyright (C) 2012 United States Government as represented by the Administrator of the +~ National Aeronautics and Space Administration. +~ All Rights Reserved. +--> diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/AbstractMenu.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/AbstractMenu.java index 5de9335b37..36ee8526ad 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/AbstractMenu.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/AbstractMenu.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwindx.applications.worldwindow.features.Feature; @@ -17,93 +16,72 @@ * @author tag * @version $Id: AbstractMenu.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AbstractMenu extends JMenu implements Menu, MenuListener, WWMenu -{ +public class AbstractMenu extends JMenu implements Menu, MenuListener, WWMenu { + protected Controller controller; - protected AbstractMenu(String title, String menuID, Registry registry) - { + protected AbstractMenu(String title, String menuID, Registry registry) { super(title); - if (menuID != null && registry != null) + if (menuID != null && registry != null) { registry.registerObject(menuID, this); + } } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { this.controller = controller; this.addMenuListener(this); } - public boolean isInitialized() - { + public boolean isInitialized() { return this.controller != null; } - protected void addToMenuBar() - { - if (this.controller.getMenuBar() != null) + protected void addToMenuBar() { + if (this.controller.getMenuBar() != null) { this.controller.getMenuBar().addMenu(this); + } } - public void addMenu(String featureID) - { - this.addMenus(new String[] {featureID}); + public void addMenu(String featureID) { + this.addMenus(new String[]{featureID}); } - public void addMenus(String[] featureIDs) - { + public void addMenus(String[] featureIDs) { boolean radioGroup = false; - for (String featureID : featureIDs) - { - if (featureID == null || featureID.length() == 0) - { + for (String featureID : featureIDs) { + if (featureID == null || featureID.length() == 0) { radioGroup = false; this.add(new JSeparator()); - } - else if (featureID.equals(Constants.RADIO_GROUP)) - { + } else if (featureID.equals(Constants.RADIO_GROUP)) { radioGroup = true; - } - else if (featureID.startsWith("gov.nasa.worldwindx.applications.worldwindow.menu")) - { + } else if (featureID.startsWith("gov.nasa.worldwindx.applications.worldwindow.menu")) { Object o = this.controller.getRegisteredObject(featureID); - if (o instanceof Menu) + if (o instanceof Menu) { this.add(((Menu) o).getJMenu()); - } - else - { + } + } else { Feature feature = (Feature) controller.getRegisteredObject(featureID); - if (feature != null) - { - if (feature.isTwoState()) - { - if (radioGroup) - { + if (feature != null) { + if (feature.isTwoState()) { + if (radioGroup) { final JMenuItem menuItem = new RadioMenuItem(feature); this.add(menuItem); - feature.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent event) - { - if (event.getPropertyName().equals(Constants.ON_STATE)) - { + feature.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + if (event.getPropertyName().equals(Constants.ON_STATE)) { menuItem.setSelected((Boolean) event.getNewValue()); menuItem.repaint(); } } }); - } - else - { + } else { this.add(new ToggleMenuItem(feature)); } - } - else - { + } else { radioGroup = false; this.add(new JMenuItem(feature)); } @@ -112,13 +90,10 @@ public void propertyChange(PropertyChangeEvent event) } } - public void menuSelected(MenuEvent menuEvent) - { - for (int i = 0; i < this.getItemCount(); i++) - { + public void menuSelected(MenuEvent menuEvent) { + for (int i = 0; i < this.getItemCount(); i++) { JMenuItem mi = this.getItem(i); - if (mi instanceof ToggleMenuItem) - { + if (mi instanceof ToggleMenuItem) { ToggleMenuItem tmi = (ToggleMenuItem) mi; Feature feature = (Feature) tmi.getAction(); tmi.setState(feature.isOn()); @@ -126,49 +101,42 @@ public void menuSelected(MenuEvent menuEvent) } } - public void menuDeselected(MenuEvent menuEvent) - { + public void menuDeselected(MenuEvent menuEvent) { } - public void menuCanceled(MenuEvent menuEvent) - { + public void menuCanceled(MenuEvent menuEvent) { } - protected Controller getController() - { + protected Controller getController() { return controller; } - public JMenu getJMenu() - { + public JMenu getJMenu() { return this; } - private static class ToggleMenuItem extends JCheckBoxMenuItem - { - public ToggleMenuItem(Action action) - { + private static class ToggleMenuItem extends JCheckBoxMenuItem { + + public ToggleMenuItem(Action action) { super(action); } } - private static class RadioMenuItem extends JRadioButtonMenuItem - { - public RadioMenuItem(Action action) - { + private static class RadioMenuItem extends JRadioButtonMenuItem { + + public RadioMenuItem(Action action) { super(action); } } - protected List getFeatures() - { + protected List getFeatures() { ArrayList featureList = new ArrayList(); - for (int i = 0; i < this.getItemCount(); i++) - { + for (int i = 0; i < this.getItemCount(); i++) { Object o = this.getItem(i) != null ? this.getItem(i).getAction() : null; - if (o != null && o instanceof Feature) + if (o != null && o instanceof Feature) { featureList.add((Feature) o); + } } return featureList; diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppConfiguration.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppConfiguration.java index ab69fb75af..717767b5a8 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppConfiguration.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppConfiguration.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.util.*; @@ -19,29 +18,26 @@ * @author tag * @version $Id: AppConfiguration.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AppConfiguration implements Initializable -{ +public class AppConfiguration implements Initializable { + protected Controller controller; protected String configurationLocation; - public AppConfiguration() - { + public AppConfiguration() { } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { this.controller = controller; } - public boolean isInitialized() - { + public boolean isInitialized() { return this.controller != null; } - public void configure(final String appConfigurationLocation) - { - if (WWUtil.isEmpty(appConfigurationLocation)) + public void configure(final String appConfigurationLocation) { + if (WWUtil.isEmpty(appConfigurationLocation)) { throw new IllegalArgumentException("The application configuration location name is null or empty"); + } this.configurationLocation = appConfigurationLocation; @@ -50,95 +46,78 @@ public void configure(final String appConfigurationLocation) this.configureFeatures(appConfigurationLocation); } - protected void configureFeatures(final String appConfigurationLocation) - { + protected void configureFeatures(final String appConfigurationLocation) { // Configure the application objects on the EDT - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - try - { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { registerConfiguration(appConfigurationLocation); - } - catch (Exception e) - { + } catch (Exception e) { Util.getLogger().log(Level.SEVERE, "Unable to create initial configuration for {0}", - appConfigurationLocation); + appConfigurationLocation); } } }); } // Registers the objects in the configuration. - protected void registerConfiguration(String config) throws Exception - { + protected void registerConfiguration(String config) throws Exception { // TODO: this call can return null Document doc = WWXML.openDocumentFile(config, this.getClass()); NodeList emNodes = (NodeList) WWXML.makeXPath().evaluate("//Feature", doc, XPathConstants.NODESET); ArrayList objects = new ArrayList(); - for (int i = 0; i < emNodes.getLength(); i++) - { + for (int i = 0; i < emNodes.getLength(); i++) { String featureID = null; String className = null; String actuate = null; - try - { + try { Element element = (Element) emNodes.item(i); featureID = WWXML.getText(element, "@featureID"); className = WWXML.getText(element, "@className"); actuate = WWXML.getText(element, "@actuate"); - if (className == null || className.length() == 0) - { + if (className == null || className.length() == 0) { Util.getLogger().log(Level.WARNING, - "Configuration entry in {0} missing feature ID ({1})or classname ({2})", - new Object[] - {config, featureID != null ? featureID : "null", className != null ? className : "null"}); + "Configuration entry in {0} missing feature ID ({1})or classname ({2})", + new Object[]{config, featureID != null ? featureID : "null", className != null ? className : "null"}); continue; } - if (!WWUtil.isEmpty(featureID)) - { - if (actuate != null && actuate.equals("onDemand")) + if (!WWUtil.isEmpty(featureID)) { + if (actuate != null && actuate.equals("onDemand")) { this.controller.registerObject(featureID, Class.forName(className)); - else + } else { objects.add(this.controller.createAndRegisterObject(featureID, className)); - } - else - { + } + } else { objects.add(this.controller.createRegistryObject(className)); } String accelerator = WWXML.getText(element, "@accelerator"); - if (accelerator != null && accelerator.length() > 0) + if (accelerator != null && accelerator.length() > 0) { this.controller.registerObject(className + Constants.ACCELERATOR_SUFFIX, accelerator); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = String.format( - "Error creating configuration entry in %s for feature ID (%s), classname (%s), activate (%s)", - config, featureID != null ? featureID : "null", - className != null ? className : "null", - actuate != null ? actuate : "null"); + "Error creating configuration entry in %s for feature ID (%s), classname (%s), activate (%s)", + config, featureID != null ? featureID : "null", + className != null ? className : "null", + actuate != null ? actuate : "null"); Util.getLogger().log(Level.WARNING, msg, e); //noinspection UnnecessaryContinue continue; } } - for (Object o : objects) - { - try - { - if (o instanceof Initializable) + for (Object o : objects) { + try { + if (o instanceof Initializable) { ((Initializable) o).initialize(this.controller); - } - catch (Exception e) - { + } + } catch (Exception e) { String msg = String.format("Error initializing object %s", o.getClass().getName()); Util.getLogger().log(Level.WARNING, msg, e); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppFrame.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppFrame.java index d28969c163..d08c7658b0 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppFrame.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppFrame.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import java.awt.*; @@ -12,7 +11,7 @@ * @author tag * @version $Id: AppFrame.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AppFrame extends Initializable -{ +public interface AppFrame extends Initializable { + Frame getFrame(); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppFrameImpl.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppFrameImpl.java index ab5fd3d19c..49378dbc08 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppFrameImpl.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppFrameImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwindx.applications.worldwindow.features.AbstractFeature; @@ -17,41 +16,40 @@ * @author tag * @version $Id: AppFrameImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AppFrameImpl extends AbstractFeature implements AppFrame -{ +public class AppFrameImpl extends AbstractFeature implements AppFrame { + // only one of these will be non-null protected JFrame frame; - public AppFrameImpl(Registry registry) - { + public AppFrameImpl(Registry registry) { super("App Frame", Constants.APP_FRAME, registry); } - public void initialize(final Controller controller) - { + public void initialize(final Controller controller) { super.initialize(controller); this.initializeApp(); } - protected void initializeApp() - { - try - { + protected void initializeApp() { + try { frame = new JFrame(); frame.setTitle(controller.getAppTitle()); frame.getContentPane().add(controller.getAppPanel().getJPanel(), BorderLayout.CENTER); ToolBar toolBar = controller.getToolBar(); - if (toolBar != null) + if (toolBar != null) { frame.add(toolBar.getJToolBar(), BorderLayout.PAGE_START); + } StatusPanel statusPanel = controller.getStatusPanel(); - if (statusPanel != null) + if (statusPanel != null) { frame.add(statusPanel.getJPanel(), BorderLayout.PAGE_END); + } MenuBar menuBar = controller.getMenuBar(); - if (menuBar != null) + if (menuBar != null) { frame.setJMenuBar(menuBar.getJMenuBar()); + } frame.pack(); @@ -69,17 +67,14 @@ protected void initializeApp() frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); - } - catch (Exception e) - { + } catch (Exception e) { String msg = "Unable to initialize the application."; Util.getLogger().log(Level.SEVERE, msg, e); this.controller.showErrorDialogLater(null, "Initialization Error", msg); } } - public Frame getFrame() - { + public Frame getFrame() { return this.frame; } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppPanel.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppPanel.java index 784dbf3303..2691580420 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppPanel.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppPanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import javax.swing.*; @@ -12,7 +11,7 @@ * @author tag * @version $Id: AppPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface AppPanel extends WWOPanel, Initializable -{ +public interface AppPanel extends WWOPanel, Initializable { + public JPanel getJPanel(); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppPanelImpl.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppPanelImpl.java index f2249f2b36..eca39dd67c 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/AppPanelImpl.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/AppPanelImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwindx.applications.worldwindow.features.AbstractFeature; @@ -15,33 +14,32 @@ * @author tag * @version $Id: AppPanelImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AppPanelImpl extends AbstractFeature implements AppPanel -{ +public class AppPanelImpl extends AbstractFeature implements AppPanel { + private JPanel panel; - public AppPanelImpl(Registry registry) - { + public AppPanelImpl(Registry registry) { super("App Panel", Constants.APP_PANEL, registry); this.panel = new JPanel(new BorderLayout()); this.panel.setPreferredSize(new Dimension(1280, 800)); } - public void initialize(final Controller controller) - { + public void initialize(final Controller controller) { super.initialize(controller); Dimension appSize = controller.getAppSize(); - if (appSize != null) + if (appSize != null) { this.panel.setPreferredSize(appSize); + } WWPanel wwPanel = controller.getWWPanel(); - if (wwPanel != null) + if (wwPanel != null) { this.panel.add(wwPanel.getJPanel(), BorderLayout.CENTER); + } } - public JPanel getJPanel() - { + public JPanel getJPanel() { return this.panel; } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/Constants.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/Constants.java index a7be1d660a..bff4185b00 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/Constants.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/Constants.java @@ -3,15 +3,14 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; /** * @author tag * @version $Id: Constants.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Constants -{ +public interface Constants { + // Names and titles String APPLICATION_DISPLAY_NAME = "gov.nasa.worldwindx.applications.worldwindow.ApplicationDisplayName"; @@ -43,7 +42,7 @@ public interface Constants String ACTIVE_LAYER = "gov.nasa.worldwindx.applications.worldwindow.ActiveLayer"; // force display in active layers String USER_LAYER = "gov.nasa.worldwindx.applications.worldwindow.UserLayer"; // User-generated layers String SCREEN_LAYER = "gov.nasa.worldwindx.applications.worldwindow.ScreenLayer"; - // in-screen application controls, etc. + // in-screen application controls, etc. // Feature IDs String FEATURE = "gov.nasa.worldwindx.applications.worldwindow.feature"; @@ -53,7 +52,7 @@ public interface Constants String FEATURE_CROSSHAIR = "gov.nasa.worldwindx.applications.worldwindow.feature.Crosshair"; String FEATURE_COORDINATES_DISPLAY = "gov.nasa.worldwindx.applications.worldwindow.feature.CoordinatesDisplay"; String FEATURE_EXTERNAL_LINK_CONTROLLER - = "gov.nasa.worldwindx.applications.worldwindow.feature.ExternalLinkController"; + = "gov.nasa.worldwindx.applications.worldwindow.feature.ExternalLinkController"; String FEATURE_GAZETTEER = "gov.nasa.worldwindx.applications.worldwindow.feature.Gazetteer"; String FEATURE_GAZETTEER_PANEL = "gov.nasa.worldwindx.applications.worldwindow.feature.GazetteerPanel"; String FEATURE_GRATICULE = "gov.nasa.worldwindx.applications.worldwindow.feature.Graticule"; diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/Controller.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/Controller.java index 41ad319d8d..587f55d672 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/Controller.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/Controller.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.*; @@ -27,10 +26,9 @@ * @author tag * @version $Id: Controller.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Controller -{ - static - { +public class Controller { + + static { // The following is required to use Swing menus with the heavyweight canvas used by WorldWind. ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false); JPopupMenu.setDefaultLightWeightPopupEnabled(false); @@ -44,8 +42,7 @@ public class Controller private WWOUnitsFormat unitsFormat; public void start(String appConfigurationLocation, Dimension appSize) - throws Exception - { + throws Exception { this.appTitle = Configuration.getStringValue(Constants.APPLICATION_DISPLAY_NAME); this.appSize = appSize; @@ -59,135 +56,113 @@ public void start(String appConfigurationLocation, Dimension appSize) appConfig.configure(this.appConfigurationLocation); - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + SwingUtilities.invokeLater(new Runnable() { + public void run() { redraw(); } }); } - public String getAppTitle() - { + public String getAppTitle() { return appTitle; } - public Registry getRegistry() - { + public Registry getRegistry() { return registry; } - public String getAppConfigurationLocation() - { + public String getAppConfigurationLocation() { return this.appConfigurationLocation; } - public Dimension getAppSize() - { + public Dimension getAppSize() { return appSize; } - public String getVersion() - { + public String getVersion() { return Version.getVersion(); } - public WorldWindow getWWd() - { + public WorldWindow getWWd() { return getWWPanel().getWWd(); } - public WWPanel getWWPanel() - { + public WWPanel getWWPanel() { return (WWPanel) getRegisteredObject(Constants.WW_PANEL); } - public AppFrame getAppFrame() - { + public AppFrame getAppFrame() { return (AppFrame) getRegisteredObject(Constants.APP_FRAME); } - public Frame getFrame() - { + public Frame getFrame() { AppFrame appFrame = (AppFrame) getRegisteredObject(Constants.APP_FRAME); - if (appFrame != null) + if (appFrame != null) { return appFrame.getFrame(); + } return Util.findParentFrame((Container) getRegisteredObject(Constants.APP_PANEL)); } - public StatusPanel getStatusPanel() - { + public StatusPanel getStatusPanel() { return (StatusPanel) getRegisteredObject(Constants.STATUS_PANEL); } - public AppPanel getAppPanel() - { + public AppPanel getAppPanel() { return (AppPanel) getRegisteredObject(Constants.APP_PANEL); } - public ToolBar getToolBar() - { + public ToolBar getToolBar() { return (ToolBar) getRegisteredObject(Constants.TOOL_BAR); } - public MenuBar getMenuBar() - { + public MenuBar getMenuBar() { return (MenuBar) getRegisteredObject(Constants.MENU_BAR); } - public LayerManager getLayerManager() - { + public LayerManager getLayerManager() { return (LayerManager) getRegisteredObject(Constants.FEATURE_LAYER_MANAGER); } - public JFileChooser getFileChooser() - { - if (this.fileChooser == null) + public JFileChooser getFileChooser() { + if (this.fileChooser == null) { this.fileChooser = new JFileChooser(); + } return this.fileChooser; } - public WWOUnitsFormat getUnits() - { + public WWOUnitsFormat getUnits() { return this.unitsFormat; } - public NetworkActivitySignal getNetworkActivitySignal() - { + public NetworkActivitySignal getNetworkActivitySignal() { return (NetworkActivitySignal) this.getRegisteredObject(Constants.NETWORK_STATUS_SIGNAL); } - public void redraw() - { - if (this.getWWd() != null) + public void redraw() { + if (this.getWWd() != null) { this.getWWd().redraw(); + } } - public LayerList getActiveLayers() - { + public LayerList getActiveLayers() { return getWWd().getModel().getLayers(); } - public Layer addInternalLayer(Layer layer) - { + public Layer addInternalLayer(Layer layer) { return addLayer(layer, Constants.INTERNAL_LAYER); } - public Layer addInternalActiveLayer(Layer layer) - { + public Layer addInternalActiveLayer(Layer layer) { // Internal Active layers are not shown in the layer tree but are shown in the active layers list layer.setValue(Constants.ACTIVE_LAYER, true); return addLayer(layer, Constants.INTERNAL_LAYER); } - private Layer addLayer(Layer layer, String layerType) - { - if (layer != null) - { + private Layer addLayer(Layer layer, String layerType) { + if (layer != null) { layer.setValue(layerType, true); this.getWWPanel().addLayer(layer); } @@ -195,190 +170,163 @@ private Layer addLayer(Layer layer, String layerType) return layer; } - public void moveToLocation(PointOfInterest location) - { + public void moveToLocation(PointOfInterest location) { this.moveToLocation(location.getLatlon()); } private static final double GOTO_ALTITUDE = 100000; // 100 km - public void moveToLocation(LatLon location) - { + public void moveToLocation(LatLon location) { Double curAlt = this.getCurrentAltitude(); double newAlt = curAlt != null && curAlt <= GOTO_ALTITUDE ? curAlt : GOTO_ALTITUDE; this.moveToLocation(new gov.nasa.worldwind.geom.Position(location, newAlt)); } - public Double getCurrentAltitude() - { + public Double getCurrentAltitude() { View view = this.getWWd().getView(); return view != null ? view.getEyePosition().getElevation() : null; } - public void moveToLocation(Position position) - { + public void moveToLocation(Position position) { OrbitView view = (OrbitView) this.getWWd().getView(); Globe globe = this.getWWd().getModel().getGlobe(); - if (globe != null && view != null) - { + if (globe != null && view != null) { ((OrbitViewInputHandler) view.getViewInputHandler()).addPanToAnimator(position, - Angle.ZERO, Angle.ZERO, position.elevation, true); + Angle.ZERO, Angle.ZERO, position.elevation, true); } } - public void setCursor(java.awt.Cursor cursor) - { - if (!((Component) this.getWWd()).getCursor().equals(cursor)) + public void setCursor(java.awt.Cursor cursor) { + if (!((Component) this.getWWd()).getCursor().equals(cursor)) { ((Component) this.getWWd()).setCursor(cursor); + } } - public String setStatusMessage(String message) - { + public String setStatusMessage(String message) { return this.getStatusPanel() != null ? this.getStatusPanel().setStatusMessage(message) : null; } - public Object getRegisteredObject(String objectID) - { + public Object getRegisteredObject(String objectID) { Object o = this.registry.getRegisteredObject(objectID); - if (o == null) + if (o == null) { return null; + } - if (!(o instanceof Class)) + if (!(o instanceof Class)) { return this.registry.getRegisteredObject(objectID); + } - try - { + try { // Create on-demand objects Object newObj = this.createAndRegisterObject(objectID, o); - if (newObj instanceof Initializable) + if (newObj instanceof Initializable) { ((Initializable) newObj).initialize(this); + } return newObj; - } - catch (Exception e) - { + } catch (Exception e) { return null; } } - public void registerObject(String objectID, Object o) - { + public void registerObject(String objectID, Object o) { this.registry.registerObject(objectID, o); } public Object createAndRegisterObject(String objectID, Object className) - throws IllegalAccessException, ClassNotFoundException, InstantiationException - { + throws IllegalAccessException, ClassNotFoundException, InstantiationException { return this.registry.createAndRegisterObject(objectID, className); } public Object createRegistryObject(String className) - throws IllegalAccessException, ClassNotFoundException, InstantiationException - { + throws IllegalAccessException, ClassNotFoundException, InstantiationException { return this.registry.createRegistryObject(className); } - public void showErrorDialog(Exception e, String title, String message, Object... args) - { + public void showErrorDialog(Exception e, String title, String message, Object... args) { this.showMessageDialog(formatMessage(e, message, args), title, JOptionPane.ERROR_MESSAGE); } - public void showErrorDialogLater(final Exception e, final String title, final String message, final Object... args) - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + public void showErrorDialogLater(final Exception e, final String title, final String message, final Object... args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { showErrorDialog(e, title, message, args); } }); } - public void showCommunicationErrorDialogLater(final Exception e, final String message, final Object... args) - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + public void showCommunicationErrorDialogLater(final Exception e, final String message, final Object... args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { showCommunicationErrorDialog(e, message, args); } }); } - public void showMessageDialog(Object message, String title, int messageType) - { + public void showMessageDialog(Object message, String title, int messageType) { this.showMessageDialog(this.getFrame(), message, title, messageType); } - public void showMessageDialog(Component component, Object message, String title, int messageType) - { + public void showMessageDialog(Component component, Object message, String title, int messageType) { JOptionPane.showMessageDialog(component, message, title, messageType); } - public void showMessageDialog(Object message, String title, int messageType, Object... args) - { + public void showMessageDialog(Object message, String title, int messageType, Object... args) { this.showMessageDialog(this.getFrame(), message, title, messageType, args); } - public void showMessageDialog(Component component, Object message, String title, int messageType, Object... args) - { + public void showMessageDialog(Component component, Object message, String title, int messageType, Object... args) { JOptionPane.showMessageDialog(component, formatMessage(null, message, args), title, messageType); } - public void showCommunicationErrorDialog(Exception e, String message, Object... args) - { + public void showCommunicationErrorDialog(Exception e, String message, Object... args) { this.showMessageDialog(formatMessage(e, message, args), "Communication Error", JOptionPane.ERROR_MESSAGE); } public int showOptionDialog(Object message, String title, int optionType, int messageType, Icon icon, - Object[] options, Object initialValue) - { + Object[] options, Object initialValue) { return JOptionPane.showOptionDialog(this.getFrame(), message, title, optionType, messageType, - icon, options, initialValue); + icon, options, initialValue); } - @SuppressWarnings( {"StringConcatenationInsideStringBufferAppend"}) - private static String formatMessage(Exception e, Object message, Object[] args) - { + @SuppressWarnings({"StringConcatenationInsideStringBufferAppend"}) + private static String formatMessage(Exception e, Object message, Object[] args) { StringBuilder sb = new StringBuilder(); - if (message != null) + if (message != null) { sb.append(message.toString()); + } - if (e != null) + if (e != null) { sb.append((sb.length() > 0 ? "\n" : "") + e.toString()); + } - for (Object o : args) - { - if (o != null) + for (Object o : args) { + if (o != null) { sb.append((sb.length() > 0 ? "\n" : "") + o.toString()); + } } return sb.toString(); } - public void openLink(String link) - { - if (WWUtil.isEmpty(link)) + public void openLink(String link) { + if (WWUtil.isEmpty(link)) { return; + } - try - { - try - { + try { + try { // See if the link is a URL, and invoke the browser if it is URL url = new URL(link.replace(" ", "%20")); Desktop.getDesktop().browse(url.toURI()); return; - } - catch (MalformedURLException ignored) - { // just means that the link is not a URL + } catch (MalformedURLException ignored) { // just means that the link is not a URL } // It's not a URL, so see if it's a file and invoke the desktop to open it if it is. File file = new File(link); - if (file.exists()) - { + if (file.exists()) { Desktop.getDesktop().open(new File(link)); return; } @@ -386,53 +334,46 @@ public void openLink(String link) String message = "Cannot open resource. It's not a valid file or URL."; Util.getLogger().log(Level.SEVERE, message); this.showErrorDialog(null, "No Reconocido V\u00ednculo", message); - } - catch (UnsupportedOperationException e) - { + } catch (UnsupportedOperationException e) { String message = "Unable to open resource.\n" + link - + (e.getMessage() != null ? "\n" + e.getMessage() : ""); + + (e.getMessage() != null ? "\n" + e.getMessage() : ""); Util.getLogger().log(Level.SEVERE, message, e); this.showErrorDialog(e, "Error Opening Resource", message); - } - catch (IOException e) - { + } catch (IOException e) { String message = "I/O error while opening resource.\n" + link - + (e.getMessage() != null ? ".\n" + e.getMessage() : ""); + + (e.getMessage() != null ? ".\n" + e.getMessage() : ""); Util.getLogger().log(Level.SEVERE, message, e); this.showErrorDialog(e, "I/O Error", message); - } - catch (Exception e) - { + } catch (Exception e) { String message = "Error attempting to open resource.\n" + link - + (e.getMessage() != null ? "\n" + e.getMessage() : ""); + + (e.getMessage() != null ? "\n" + e.getMessage() : ""); Util.getLogger().log(Level.SEVERE, message); this.showMessageDialog(message, "Error Opening Resource", JOptionPane.ERROR_MESSAGE); } } // Raises the Save As dialog to have the user identify the location to save groups of things. - public File determineSaveLocation(String dialogTitle, String defaultFolderName) - { + public File determineSaveLocation(String dialogTitle, String defaultFolderName) { String defaultPath = this.getFileChooser().getCurrentDirectory().getPath(); - if (!WWUtil.isEmpty(defaultPath)) + if (!WWUtil.isEmpty(defaultPath)) { defaultPath += File.separatorChar + defaultFolderName; + } File outFile; - while (true) - { + while (true) { this.getFileChooser().setDialogTitle(dialogTitle); this.getFileChooser().setSelectedFile(new File(defaultPath)); this.getFileChooser().setMultiSelectionEnabled(false); this.getFileChooser().setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int status = this.getFileChooser().showSaveDialog(this.getFrame()); - if (status != JFileChooser.APPROVE_OPTION) + if (status != JFileChooser.APPROVE_OPTION) { return null; + } outFile = this.getFileChooser().getSelectedFile(); - if (outFile == null) - { + if (outFile == null) { this.showMessageDialog("No location selected", "No Selection", JOptionPane.ERROR_MESSAGE); continue; } @@ -440,63 +381,66 @@ public File determineSaveLocation(String dialogTitle, String defaultFolderName) break; } - if (!outFile.exists()) - //noinspection ResultOfMethodCallIgnored + if (!outFile.exists()) //noinspection ResultOfMethodCallIgnored + { outFile.mkdir(); + } return outFile; } - public File chooseOutputFile(String defaultName, String suffixWithoutDot, String dialogTitle) - { + public File chooseOutputFile(String defaultName, String suffixWithoutDot, String dialogTitle) { String defaultPath = this.getFileChooser().getCurrentDirectory().getPath(); - if (defaultName != null && defaultName.length() > 0) + if (defaultName != null && defaultName.length() > 0) { defaultPath += File.separatorChar + defaultName; + } - if (suffixWithoutDot != null && suffixWithoutDot.length() > 0) + if (suffixWithoutDot != null && suffixWithoutDot.length() > 0) { defaultPath += "." + suffixWithoutDot; + } - if (dialogTitle == null || dialogTitle.length() == 0) + if (dialogTitle == null || dialogTitle.length() == 0) { dialogTitle = "Choose Save Location"; + } this.getFileChooser().setDialogTitle(dialogTitle); this.getFileChooser().setSelectedFile(new File(defaultPath)); this.getFileChooser().setMultiSelectionEnabled(false); - while (true) - { + while (true) { int status = this.getFileChooser().showSaveDialog(this.getFrame()); - if (status != JFileChooser.APPROVE_OPTION) + if (status != JFileChooser.APPROVE_OPTION) { return null; + } File outFile = this.getFileChooser().getSelectedFile(); - if (outFile == null) - { + if (outFile == null) { this.showMessageDialog("No location selected", "No Selection", JOptionPane.ERROR_MESSAGE); continue; } - if (suffixWithoutDot != null && suffixWithoutDot.length() > 0) + if (suffixWithoutDot != null && suffixWithoutDot.length() > 0) { outFile = Util.ensureFileSuffix(outFile, suffixWithoutDot); + } - if (outFile.exists()) - { + if (outFile.exists()) { status = this.showConfirmFileOverwriteDialog(outFile); - if (status == JOptionPane.NO_OPTION) + if (status == JOptionPane.NO_OPTION) { continue; - if (status == JOptionPane.CANCEL_OPTION) + } + if (status == JOptionPane.CANCEL_OPTION) { return null; + } } return outFile; } } - public int showConfirmFileOverwriteDialog(File outFile) - { + public int showConfirmFileOverwriteDialog(File outFile) { return JOptionPane.showConfirmDialog(this.getFrame(), - "Replace existing file\n" + outFile.getName() + "?", - "Overwrite Existing File?", JOptionPane.YES_NO_CANCEL_OPTION); + "Replace existing file\n" + outFile.getName() + "?", + "Overwrite Existing File?", JOptionPane.YES_NO_CANCEL_OPTION); } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/ExternalLinkController.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/ExternalLinkController.java index d20eccd04f..a5672bfb2a 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/ExternalLinkController.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/ExternalLinkController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.Disposable; @@ -15,32 +14,28 @@ * @author tag * @version $Id: ExternalLinkController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ExternalLinkController extends AbstractFeature implements SelectListener, Disposable -{ - public ExternalLinkController(Registry registry) - { +public class ExternalLinkController extends AbstractFeature implements SelectListener, Disposable { + + public ExternalLinkController(Registry registry) { super("External Link Controller", Constants.FEATURE_EXTERNAL_LINK_CONTROLLER, registry); } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); this.controller.getWWd().addSelectListener(this); } - public void dispose() - { + public void dispose() { this.controller.getWWd().removeSelectListener(this); } - public void selected(SelectEvent event) - { - if (event.isLeftDoubleClick() && event.getTopObject() instanceof AVList) - { + public void selected(SelectEvent event) { + if (event.isLeftDoubleClick() && event.getTopObject() instanceof AVList) { String link = ((AVList) event.getTopObject()).getStringValue(AVKey.EXTERNAL_LINK); - if (link == null) + if (link == null) { return; + } this.controller.openLink(link); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/IconController.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/IconController.java index 83aa6a0f05..5ae2e3c4a6 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/IconController.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/IconController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.Disposable; @@ -16,68 +15,58 @@ * @author tag * @version $Id: IconController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class IconController extends AbstractFeature implements SelectListener, Disposable -{ +public class IconController extends AbstractFeature implements SelectListener, Disposable { + protected WWIcon lastPickedIcon = null; - public IconController(Registry registry) - { + public IconController(Registry registry) { super("Icon Controller", Constants.FEATURE_ICON_CONTROLLER, registry); } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); this.controller.getWWd().addSelectListener(this); } - public void dispose() - { + public void dispose() { this.controller.getWWd().removeSelectListener(this); } - public void selected(SelectEvent event) - { - try - { - if (event.getEventAction().equals(SelectEvent.ROLLOVER)) + public void selected(SelectEvent event) { + try { + if (event.getEventAction().equals(SelectEvent.ROLLOVER)) { highlight(event, event.getTopObject()); - else if (event.getEventAction().equals(SelectEvent.RIGHT_PRESS)) + } else if (event.getEventAction().equals(SelectEvent.RIGHT_PRESS)) { showContextMenu(event); - } - catch (Exception e) - { + } + } catch (Exception e) { // Wrap the handler in a try/catch to keep exceptions from bubbling up Util.getLogger().warning(e.getMessage() != null ? e.getMessage() : e.toString()); } } - @SuppressWarnings( {"UnusedDeclaration"}) - protected void highlight(SelectEvent event, Object o) - { + @SuppressWarnings({"UnusedDeclaration"}) + protected void highlight(SelectEvent event, Object o) { // Manage highlighting of icons. - if (this.lastPickedIcon == o) + if (this.lastPickedIcon == o) { return; // same thing selected - + } // Turn off highlight if on. - if (this.lastPickedIcon != null) - { + if (this.lastPickedIcon != null) { this.lastPickedIcon.setHighlighted(false); this.lastPickedIcon = null; } // Turn on highlight if object selected. - if (o != null && o instanceof WWIcon) - { + if (o != null && o instanceof WWIcon) { this.lastPickedIcon = (WWIcon) o; this.lastPickedIcon.setHighlighted(true); } } - protected void showContextMenu(SelectEvent event) - { + protected void showContextMenu(SelectEvent event) { // if (!(event.getTopObject() instanceof UserFacingIcon)) // return; // diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/ImageLibrary.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/ImageLibrary.java index 4e049feb42..eef96858bb 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/ImageLibrary.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/ImageLibrary.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.util.*; @@ -21,16 +20,15 @@ * @author tag * @version $Id: ImageLibrary.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ImageLibrary -{ +public class ImageLibrary { + // These images are available for situation where a desired image is not available. - private static final String[] WARNING_IMAGES = new String[] - { - "gov/nasa/worldwindx/applications/worldwindow/images/warning16.png", - "gov/nasa/worldwindx/applications/worldwindow/images/warning24.png", - "gov/nasa/worldwindx/applications/worldwindow/images/warning32.png", - "gov/nasa/worldwindx/applications/worldwindow/images/warning64.png" - }; + private static final String[] WARNING_IMAGES = new String[]{ + "gov/nasa/worldwindx/applications/worldwindow/images/warning16.png", + "gov/nasa/worldwindx/applications/worldwindow/images/warning24.png", + "gov/nasa/worldwindx/applications/worldwindow/images/warning32.png", + "gov/nasa/worldwindx/applications/worldwindow/images/warning64.png" + }; private static ImageLibrary instance; @@ -39,32 +37,25 @@ public class ImageLibrary * * @param library the image library instance. */ - public static void setInstance(ImageLibrary library) - { + public static void setInstance(ImageLibrary library) { instance = library; } private ConcurrentHashMap imageMap = new ConcurrentHashMap(); private ConcurrentHashMap iconMap = new ConcurrentHashMap(); - public ImageLibrary() - { + public ImageLibrary() { this.loadWarningImages(); } - protected void loadWarningImages() - { - for (String imageName : WARNING_IMAGES) - { - try - { + protected void loadWarningImages() { + for (String imageName : WARNING_IMAGES) { + try { InputStream is = WWIO.openFileOrResourceStream(imageName, this.getClass()); this.imageMap.put(imageName, ImageUtil.toCompatibleImage(ImageIO.read(is))); - } - catch (Exception e) - { + } catch (Exception e) { Util.getLogger().log(java.util.logging.Level.WARNING, - e.getMessage() + " Stand-in image, name is " + imageName, e); + e.getMessage() + " Stand-in image, name is " + imageName, e); } } } @@ -76,16 +67,16 @@ protected void loadWarningImages() * * @return a warning image of the requested size, or one of size 64 if a size larger than 64 is requested. */ - public static BufferedImage getWarningImage(int size) - { - if (size < 24) + public static BufferedImage getWarningImage(int size) { + if (size < 24) { return getImage(WARNING_IMAGES[0]); - else if (size < 32) + } else if (size < 32) { return getImage(WARNING_IMAGES[1]); - else if (size < 64) + } else if (size < 64) { return getImage(WARNING_IMAGES[2]); - else + } else { return getImage(WARNING_IMAGES[3]); + } } /** @@ -95,16 +86,16 @@ else if (size < 64) * * @return a warning icon of the requested size, or one of size 64 if a size larger than 64 is requested. */ - public static Icon getWarningIcon(int size) - { - if (size < 24) + public static Icon getWarningIcon(int size) { + if (size < 24) { return getIcon(WARNING_IMAGES[0]); - else if (size < 32) + } else if (size < 32) { return getIcon(WARNING_IMAGES[1]); - else if (size < 64) + } else if (size < 64) { return getIcon(WARNING_IMAGES[2]); - else + } else { return getIcon(WARNING_IMAGES[3]); + } } /** @@ -116,20 +107,17 @@ else if (size < 64) * * @return the image if it's available, otherwise null. */ - public static synchronized BufferedImage getImage(String imageName) - { - try - { + public static synchronized BufferedImage getImage(String imageName) { + try { BufferedImage image = !WWUtil.isEmpty(imageName) ? instance.imageMap.get(imageName) : null; - if (image != null) + if (image != null) { return image; + } URL url = getImageURL(imageName); - if (url != null) - { + if (url != null) { image = ImageIO.read(url); - if (image != null) - { + if (image != null) { image = ImageUtil.toCompatibleImage(image); register(imageName, image); return image; @@ -137,30 +125,32 @@ public static synchronized BufferedImage getImage(String imageName) } return null; - } - catch (IOException e) - { + } catch (IOException e) { Util.getLogger().log(java.util.logging.Level.SEVERE, - e.getMessage() + " Image name " + (imageName != null ? imageName : null), e); + e.getMessage() + " Image name " + (imageName != null ? imageName : null), e); return null; } } - public static synchronized URL getImageURL(String imageName) - { + public static synchronized URL getImageURL(String imageName) { URL url = instance.getClass().getResource(imageName); // look locallly - if (url == null) + if (url == null) { url = instance.getClass().getResource("/" + imageName); // look locallly - if (url == null) + } + if (url == null) { url = instance.getClass().getResource("images" + File.separatorChar + imageName); - if (url == null) + } + if (url == null) { url = instance.getClass().getResource("/images" + File.separatorChar + imageName); - if (url == null) + } + if (url == null) { url = instance.getClass().getResource( - "gov/nasa/worldwindx/applications/worldwindow/images" + File.separatorChar + imageName); - if (url == null) + "gov/nasa/worldwindx/applications/worldwindow/images" + File.separatorChar + imageName); + } + if (url == null) { url = instance.getClass().getResource( - "/gov/nasa/worldwindx/applications/worldwindow/images" + File.separatorChar + imageName); + "/gov/nasa/worldwindx/applications/worldwindow/images" + File.separatorChar + imageName); + } return url; } @@ -174,29 +164,25 @@ public static synchronized URL getImageURL(String imageName) * * @return the icon if it's available, otherwise null. */ - public static synchronized ImageIcon getIcon(String iconName) - { - try - { + public static synchronized ImageIcon getIcon(String iconName) { + try { ImageIcon icon = !WWUtil.isEmpty(iconName) ? instance.iconMap.get(iconName) : null; - if (icon != null) + if (icon != null) { return icon; + } // Load it as an image first, because image failures occur immediately. BufferedImage image = getImage(iconName); - if (image != null) - { + if (image != null) { icon = new ImageIcon(image); register(iconName, icon); return icon; } return null; - } - catch (Exception e) - { + } catch (Exception e) { Util.getLogger().log(java.util.logging.Level.SEVERE, - e.getMessage() + " Icon name " + (iconName != null ? iconName : null), e); + e.getMessage() + " Icon name " + (iconName != null ? iconName : null), e); return null; } } @@ -208,10 +194,10 @@ public static synchronized ImageIcon getIcon(String iconName) * * @return the image associated with the icon, or null if the icon is not available. */ - public static BufferedImage getImageForIcon(Icon icon) - { - if (icon == null) + public static BufferedImage getImageForIcon(Icon icon) { + if (icon == null) { return null; + } return getImage(getIconName(icon)); } @@ -219,19 +205,18 @@ public static BufferedImage getImageForIcon(Icon icon) /** * Register an image with the library. * - * @param name the image name. If null the image is not registered. + * @param name the image name. If null the image is not registered. * @param image the image. If null the image is not registered. * * @return the reference to the image passed in the image argument. */ - public static synchronized Object register(String name, Object image) - { - if (!WWUtil.isEmpty(name) && image != null) - { - if (image instanceof BufferedImage) + public static synchronized Object register(String name, Object image) { + if (!WWUtil.isEmpty(name) && image != null) { + if (image instanceof BufferedImage) { instance.imageMap.put(name, (BufferedImage) image); - else if (image instanceof ImageIcon) + } else if (image instanceof ImageIcon) { instance.iconMap.put(name, (ImageIcon) image); + } } return image; @@ -244,12 +229,11 @@ else if (image instanceof ImageIcon) * * @return the image name, or null if the image is not registered with this instance. */ - public static String getImageName(BufferedImage image) - { - for (Map.Entry entry : instance.imageMap.entrySet()) - { - if (entry.getValue() == image) + public static String getImageName(BufferedImage image) { + for (Map.Entry entry : instance.imageMap.entrySet()) { + if (entry.getValue() == image) { return entry.getKey(); + } } return null; @@ -262,12 +246,11 @@ public static String getImageName(BufferedImage image) * * @return the icon name, or null if the icon is not registered with this instance. */ - public static String getIconName(Icon icon) - { - for (Map.Entry entry : instance.iconMap.entrySet()) - { - if (entry.getValue() == icon) + public static String getIconName(Icon icon) { + for (Map.Entry entry : instance.iconMap.entrySet()) { + if (entry.getValue() == icon) { return entry.getKey(); + } } return null; diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/InfoPanelController.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/InfoPanelController.java index def0fa4429..a937d24492 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/InfoPanelController.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/InfoPanelController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.avlist.*; @@ -20,8 +19,8 @@ * @author tag * @version $Id: InfoPanelController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class InfoPanelController extends AbstractFeature implements SelectListener -{ +public class InfoPanelController extends AbstractFeature implements SelectListener { + protected static final String HARD_SPACE = "\u00a0"; protected static final String INDENT = "\u00a0\u00a0\u00a0\u00a0"; protected int maxLineLength = 100; @@ -29,13 +28,11 @@ public class InfoPanelController extends AbstractFeature implements SelectListen protected AnnotationLayer annotationLayer; protected ScreenAnnotation annotationPanel; - public InfoPanelController(Registry registry) - { + public InfoPanelController(Registry registry) { super("Info Panel", Constants.FEATURE_INFO_PANEL_CONTROLLER, null, registry); } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); this.controller.getWWd().addSelectListener(this); @@ -43,86 +40,74 @@ public void initialize(Controller controller) protected AVList lastSelectedObject; - public void selected(SelectEvent event) - { - try - { - if (event.isRollover()) - { - if (this.lastSelectedObject == event.getTopObject()) + public void selected(SelectEvent event) { + try { + if (event.isRollover()) { + if (this.lastSelectedObject == event.getTopObject()) { return; // same thing selected - - if (this.lastSelectedObject != null) - { + } + if (this.lastSelectedObject != null) { this.hideAnnotationPanel(); this.lastSelectedObject = null; } - if (event.getTopObject() != null && event.getTopObject() instanceof AVList) - { + if (event.getTopObject() != null && event.getTopObject() instanceof AVList) { String annoText = ((AVList) event.getTopObject()).getStringValue(Constants.INFO_PANEL_TEXT); - if (!WWUtil.isEmpty(annoText)) - { + if (!WWUtil.isEmpty(annoText)) { this.lastSelectedObject = (AVList) event.getTopObject(); this.showAnnotationPanel(annoText); } } } - } - catch (Exception e) - { + } catch (Exception e) { // Wrap the handler in a try/catch to keep exceptions from bubbling up Util.getLogger().warning(e.getMessage() != null ? e.getMessage() : e.toString()); } } - protected void showAnnotationPanel(String annoText) - { + protected void showAnnotationPanel(String annoText) { String text = this.splitLines(annoText); AnnotationAttributes attrs = this.getAnnotationPanelAttributes(text); int yOffset = Math.min(this.controller.getWWPanel().getSize().height - attrs.getSize().height, 250); Point location = new Point(10 + attrs.getSize().width / 2, yOffset); - if (this.annotationPanel != null) + if (this.annotationPanel != null) { this.annotationPanel.setAttributes(this.getAnnotationPanelAttributes(text)); - else + } else { this.annotationPanel = new ScreenAnnotation(annoText, location, getAnnotationPanelAttributes(text)); + } this.annotationPanel.setScreenPoint(location); this.annotationPanel.setText(text); - if (this.annotationLayer == null) - { + if (this.annotationLayer == null) { this.annotationLayer = new AnnotationLayer(); this.annotationLayer.setPickEnabled(false); } this.annotationLayer.removeAllAnnotations(); this.annotationLayer.addAnnotation(this.annotationPanel); - if (!this.controller.getActiveLayers().contains(this.annotationLayer)) + if (!this.controller.getActiveLayers().contains(this.annotationLayer)) { this.controller.addInternalLayer(this.annotationLayer); + } } - protected void hideAnnotationPanel() - { - if (this.annotationLayer != null) - { + protected void hideAnnotationPanel() { + if (this.annotationLayer != null) { this.annotationLayer.removeAllAnnotations(); this.controller.getActiveLayers().remove(this.annotationLayer); this.annotationLayer.dispose(); this.annotationLayer = null; } - if (this.annotationPanel != null) - { + if (this.annotationPanel != null) { this.annotationPanel.dispose(); this.annotationPanel = null; } } - protected AnnotationAttributes getAnnotationPanelAttributes(String annoText) - { + protected AnnotationAttributes getAnnotationPanelAttributes(String annoText) { AnnotationAttributes attrs = new AnnotationAttributes(); attrs.setAdjustWidthToText(AVKey.SIZE_FIXED); @@ -146,8 +131,7 @@ protected AnnotationAttributes getAnnotationPanelAttributes(String annoText) * * @return the required panel size. */ - protected Dimension computePanelSize(String annoText) - { + protected Dimension computePanelSize(String annoText) { Dimension lengths = this.computeLengths(annoText); // The numbers used below are the average width of a character and average height of a line in Arial-Plain-12. @@ -164,14 +148,13 @@ protected Dimension computePanelSize(String annoText) * * @return the length of the longest line (width) and number of lines (height). */ - protected Dimension computeLengths(String annoText) - { + protected Dimension computeLengths(String annoText) { String[] lines = Util.splitLines(annoText); int lineLength = 0; - for (String line : lines) - { - if (line.length() > lineLength) + for (String line : lines) { + if (line.length() > lineLength) { lineLength = line.length(); + } } return new Dimension(lineLength + 5, lines.length + 1); // the 5 and 1 account for slight sizing discrepancies @@ -184,13 +167,11 @@ protected Dimension computeLengths(String annoText) * * @return the new lines. */ - protected String splitLines(String origText) - { + protected String splitLines(String origText) { StringBuilder newText = new StringBuilder(); String[] lines = Util.splitLines(origText); - for (String line : lines) - { + for (String line : lines) { // Append the line to the output buffer if it's within size, other wise split it and append the result. newText.append(line.length() <= this.maxLineLength ? line : this.splitLine(line)).append("\n"); } @@ -205,42 +186,42 @@ protected String splitLines(String origText) * * @return a string with new-line characters at the line-split locations. */ - protected String splitLine(String origLine) - { + protected String splitLine(String origLine) { StringBuilder newLines = new StringBuilder(); // Determine the line's current indent. Any indent added below must be added to it. String currentIndent = ""; - for (int i = 0; i < origLine.length(); i++) - { - if (origLine.charAt(i) == '\u00a0') + for (int i = 0; i < origLine.length(); i++) { + if (origLine.charAt(i) == '\u00a0') { currentIndent += HARD_SPACE; - else + } else { break; + } } // Add the words of the line to a line builder until adding a word would exceed the max allowed length. StringBuilder line = new StringBuilder(currentIndent); String[] words = Util.splitWords(origLine, "[\u00a0 ]"); // either hard or soft space - for (String word : words) - { - if (line.length() + 1 + word.length() + currentIndent.length() > this.maxLineLength) - { - if (newLines.length() == 0) + for (String word : words) { + if (line.length() + 1 + word.length() + currentIndent.length() > this.maxLineLength) { + if (newLines.length() == 0) { currentIndent += INDENT; // indent continuation lines + } newLines.append(line.toString()); line = new StringBuilder("\n").append(currentIndent); } // Add a space in front of the word if it's not the first word. - if (!line.toString().endsWith(HARD_SPACE)) + if (!line.toString().endsWith(HARD_SPACE)) { line.append(HARD_SPACE); + } line.append(word); } // Add the final words to the split lines. - if (line.length() > 1) + if (line.length() > 1) { newLines.append(line.toString()); + } return newLines.toString(); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/Initializable.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/Initializable.java index a31d9d252b..b58b3f6e56 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/Initializable.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/Initializable.java @@ -3,15 +3,14 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; /** * @author tag * @version $Id: Initializable.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Initializable -{ +public interface Initializable { + void initialize(Controller controller); boolean isInitialized(); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/Menu.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/Menu.java index 28582fc253..516a3fccf5 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/Menu.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/Menu.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import javax.swing.*; @@ -12,8 +11,8 @@ * @author tag * @version $Id: Menu.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface Menu extends Initializable -{ +public interface Menu extends Initializable { + JMenu getJMenu(); void addMenu(String featureID); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/MenuBar.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/MenuBar.java index 468ea90300..8eb0a51bb9 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/MenuBar.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/MenuBar.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwindx.applications.worldwindow.features.Feature; @@ -14,8 +13,8 @@ * @author tag * @version $Id: MenuBar.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface MenuBar extends Feature -{ +public interface MenuBar extends Feature { + JMenuBar getJMenuBar(); void addMenu(Menu menu); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/MenuBarImpl.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/MenuBarImpl.java index 8c9871f44b..3655933036 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/MenuBarImpl.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/MenuBarImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwindx.applications.worldwindow.features.AbstractFeature; @@ -14,43 +13,36 @@ * @author tag * @version $Id: MenuBarImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class MenuBarImpl extends AbstractFeature implements MenuBar -{ +public class MenuBarImpl extends AbstractFeature implements MenuBar { + // These are the menus in the menu bar. To add new menus, add them to this list in the order they should appear. - private static final String[] menuIDs = new String[] - { -// Constants.SDF_MENU, - }; + private static final String[] menuIDs = new String[]{ // Constants.SDF_MENU, + }; private JMenuBar menuBar; - public MenuBarImpl(Registry registry) - { + public MenuBarImpl(Registry registry) { super("Menu Bar", Constants.MENU_BAR, registry); } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { this.menuBar = new JMenuBar(); - for (String menuID : menuIDs) - { + for (String menuID : menuIDs) { Menu menu = (Menu) controller.getRegisteredObject(menuID); - if (menu != null) - { + if (menu != null) { getJMenuBar().add(menu.getJMenu()); } } } - public JMenuBar getJMenuBar() - { + public JMenuBar getJMenuBar() { return this.menuBar; } - public void addMenu(Menu menu) - { - if (menu != null) + public void addMenu(Menu menu) { + if (menu != null) { getJMenuBar().add(menu.getJMenu()); + } } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/Registry.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/Registry.java index 77b7baf96d..c42ca9b9a1 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/Registry.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/Registry.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.util.WWUtil; @@ -18,8 +17,8 @@ * @author tag * @version $Id: Registry.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Registry -{ +public class Registry { + private ConcurrentHashMap registeredObjects = new ConcurrentHashMap(); /** @@ -27,30 +26,23 @@ public class Registry * * @return the new component * - * @throws RuntimeException if the Object could not be created + * @throws RuntimeException if the Object could not be created * @throws IllegalArgumentException if className is null or zero length */ - public Object createObject(String className) - { - if (className == null || className.length() == 0) - { + public Object createObject(String className) { + if (className == null || className.length() == 0) { String msg = "Class name is null or zero length"; Util.getLogger().severe(msg); throw new IllegalArgumentException(msg); } - try - { + try { return Class.forName(className.trim()).newInstance(); - } - catch (Exception e) - { + } catch (Exception e) { String msg = "Exception creating object " + className; Util.getLogger().log(java.util.logging.Level.SEVERE, msg, e); throw new RuntimeException(msg, e); - } - catch (Throwable t) - { + } catch (Throwable t) { String msg = "Error creating object " + className; Util.getLogger().log(java.util.logging.Level.SEVERE, msg, t); throw new RuntimeException(msg, t); @@ -58,24 +50,20 @@ public Object createObject(String className) } public Object createRegistryObject(Object classOrName) - throws ClassNotFoundException, IllegalAccessException, InstantiationException - { - if (classOrName == null) - { + throws ClassNotFoundException, IllegalAccessException, InstantiationException { + if (classOrName == null) { String msg = "Class or class name is null"; Util.getLogger().severe(msg); throw new IllegalArgumentException(msg); } - if (!(classOrName instanceof Class || classOrName instanceof String)) - { + if (!(classOrName instanceof Class || classOrName instanceof String)) { String msg = "Class or class name is not Class or String type"; Util.getLogger().severe(msg); throw new IllegalArgumentException(msg); } - if (classOrName instanceof String && ((String) classOrName).length() == 0) - { + if (classOrName instanceof String && ((String) classOrName).length() == 0) { String msg = "Class name is null or zero length"; Util.getLogger().severe(msg); throw new IllegalArgumentException(msg); @@ -84,35 +72,22 @@ public Object createRegistryObject(Object classOrName) Class c = classOrName instanceof Class ? (Class) classOrName : Class.forName(((String) classOrName).trim()); String className = c.getName(); - try - { + try { // Create self-registering object, else non-self-registering object return c.getConstructor(this.getClass()).newInstance(this); - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { return createObject(className); - } - catch (InstantiationException e) - { + } catch (InstantiationException e) { return createObject(className); - } - catch (IllegalAccessException e) - { + } catch (IllegalAccessException e) { return createObject(className); - } - catch (InvocationTargetException e) - { + } catch (InvocationTargetException e) { return createObject(className); - } - catch (Exception e) - { + } catch (Exception e) { String msg = "Exception creating object " + className; Util.getLogger().log(java.util.logging.Level.SEVERE, msg, className); throw new RuntimeException(msg, e); - } - catch (Throwable t) - { + } catch (Throwable t) { String msg = "Error creating object " + className; Util.getLogger().log(java.util.logging.Level.SEVERE, msg, className); throw new RuntimeException(msg, t); @@ -120,17 +95,14 @@ public Object createRegistryObject(Object classOrName) } public Object createAndRegisterObject(String objectID, Object classOrName) - throws IllegalAccessException, InstantiationException, ClassNotFoundException - { - if (WWUtil.isEmpty(objectID)) - { + throws IllegalAccessException, InstantiationException, ClassNotFoundException { + if (WWUtil.isEmpty(objectID)) { String msg = String.format("Object ID %s is null or zero length", objectID); Util.getLogger().severe(msg); throw new IllegalArgumentException(msg); } - if (classOrName == null || (classOrName instanceof String && WWUtil.isEmpty(classOrName))) - { + if (classOrName == null || (classOrName instanceof String && WWUtil.isEmpty(classOrName))) { String msg = String.format("Class name %s for feature %s is zero length", classOrName, objectID); Util.getLogger().severe(msg); throw new IllegalArgumentException(msg); @@ -141,74 +113,60 @@ public Object createAndRegisterObject(String objectID, Object classOrName) return getRegisteredObject(objectID); } - public synchronized Object getRegisteredObject(String objectID) - { + public synchronized Object getRegisteredObject(String objectID) { return this.registeredObjects.get(objectID); } - public synchronized Object registerObject(String objectID, Object o) - { - if (objectID != null) + public synchronized Object registerObject(String objectID, Object o) { + if (objectID != null) { this.registeredObjects.put(objectID, o); + } return o; } - public Collection getObjects() - { + public Collection getObjects() { return this.registeredObjects.values(); } - public Object[] getObjectsOfType(String className) - { + public Object[] getObjectsOfType(String className) { ArrayList list = new ArrayList(); - try - { + try { Class classClass = Class.forName(className); - for (Map.Entry entry : this.registeredObjects.entrySet()) - { - if (entry.getValue() == null) + for (Map.Entry entry : this.registeredObjects.entrySet()) { + if (entry.getValue() == null) { continue; + } - if (classClass.isInstance(entry.getValue())) - { + if (classClass.isInstance(entry.getValue())) { list.add(entry.getValue()); - } - else if (entry.getValue() instanceof Class) - { + } else if (entry.getValue() instanceof Class) { // TODO: also check superclasses for instance of type. See java.lang.Class.getEnclosingClass and // search recursively. - if (implementsInterface(classClass, (Class) entry.getValue())) - { - try - { + if (implementsInterface(classClass, (Class) entry.getValue())) { + try { list.add(this.createAndRegisterObject(entry.getKey(), entry.getValue())); - } - catch (Exception e) - { + } catch (Exception e) { // continue } } } } - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { Util.getLogger().log(Level.SEVERE, - "No class found for class name " + (className != null ? className : null), e); + "No class found for class name " + (className != null ? className : null), e); } return list.toArray(); } - protected boolean implementsInterface(Class interfaceClass, Class compareClass) - { + protected boolean implementsInterface(Class interfaceClass, Class compareClass) { Class[] interfaces = compareClass.getInterfaces(); - for (Class i : interfaces) - { - if (i == interfaceClass) + for (Class i : interfaces) { + if (i == interfaceClass) { return true; + } } return false; diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/SimpleImporter.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/SimpleImporter.java index 15629a8081..906988653d 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/SimpleImporter.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/SimpleImporter.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.layers.*; @@ -23,8 +22,8 @@ * @author tag * @version $Id: SimpleImporter.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class SimpleImporter -{ +public class SimpleImporter { + protected static final String DEFAULT_GROUP = "Recently Opened"; protected static final AtomicInteger nextLayerNumber = new AtomicInteger(0); @@ -32,90 +31,80 @@ public class SimpleImporter protected Object source; protected Controller controller; - public SimpleImporter(Object source, Controller controller) - { + public SimpleImporter(Object source, Controller controller) { this.source = source; this.controller = controller; } - protected LayerPath getDefaultPathToParent() - { + protected LayerPath getDefaultPathToParent() { return new LayerPath(DEFAULT_GROUP); } - protected void addLayer(final Layer layer, final LayerPath pathToParent) - { - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + protected void addLayer(final Layer layer, final LayerPath pathToParent) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { LayerPath path = new LayerPath(pathToParent != null ? pathToParent : getDefaultPathToParent(), - layer.getName()); + layer.getName()); doAddLayer(layer, path); } }); } - protected void doAddLayer(final Layer layer, final LayerPath path) - { + protected void doAddLayer(final Layer layer, final LayerPath path) { LayerManager layerManager = controller.getLayerManager(); layerManager.addLayer(layer, path.lastButOne()); layerManager.selectLayer(layer, true); layerManager.expandPath(path.lastButOne()); } - public String formName(Object source, String defaultName) - { - if (source instanceof File) + public String formName(Object source, String defaultName) { + if (source instanceof File) { return ((File) source).getName(); + } - if (source instanceof URL) + if (source instanceof URL) { return ((URL) source).getPath(); + } - if (source instanceof URI) + if (source instanceof URI) { return ((URI) source).getPath(); + } - if (source instanceof String && WWIO.makeURL((String) source) != null) + if (source instanceof String && WWIO.makeURL((String) source) != null) { return WWIO.makeURL((String) source).getPath(); + } return (defaultName != null ? defaultName : "Layer ") + nextLayerNumber.addAndGet(1); } - public void startImport() - { - if (this.source == null) - { + public void startImport() { + if (this.source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); // TODO: show error dialog for all errors throw new IllegalStateException(message); } - if (this.isKML(this.source)) + if (this.isKML(this.source)) { this.openKML(this.source); - else if (this.isShapfile(this.source)) + } else if (this.isShapfile(this.source)) { this.openShapefile(this.source); - else - { + } else { String message = Logging.getMessage("generic.UnrecognizedSourceType", source.toString()); throw new IllegalArgumentException(message); } } - protected boolean isKML(Object source) - { + protected boolean isKML(Object source) { return source != null && (source.toString().endsWith(".kml") || source.toString().endsWith(".kmz")); } - protected void openKML(Object source) - { + protected void openKML(Object source) { KMLController kmlController; - try - { + try { KMLRoot kmlRoot = KMLRoot.create(source); - if (kmlRoot == null) - { + if (kmlRoot == null) { String message = Logging.getMessage("generic.UnrecognizedSourceType", source.toString(), - source.toString()); + source.toString()); throw new IllegalArgumentException(message); } @@ -125,29 +114,22 @@ protected void openKML(Object source) layer.addRenderable(kmlController); layer.setName(formName(source, null)); this.addLayer(layer, null); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); - } - catch (XMLStreamException e) - { + } catch (XMLStreamException e) { e.printStackTrace(); } } - protected boolean isShapfile(Object source) - { + protected boolean isShapfile(Object source) { return source != null && source.toString().endsWith(".shp"); } - protected void openShapefile(Object source) - { + protected void openShapefile(Object source) { ShapefileLoader loader = new ShapefileLoader(); Layer layer = loader.createLayerFromSource(source); - if (layer != null) - { + if (layer != null) { layer.setName(formName(source, null)); this.addLayer(layer, null); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/StatusPanel.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/StatusPanel.java index eedd204a3e..b955a9f456 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/StatusPanel.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/StatusPanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwindx.applications.worldwindow.features.FeaturePanel; @@ -12,7 +11,7 @@ * @author tag * @version $Id: StatusPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface StatusPanel extends FeaturePanel -{ +public interface StatusPanel extends FeaturePanel { + String setStatusMessage(String message); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolBar.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolBar.java index c53999723a..b28b124f7f 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolBar.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolBar.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwindx.applications.worldwindow.features.Feature; @@ -14,8 +13,8 @@ * @author tag * @version $Id: ToolBar.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface ToolBar -{ +public interface ToolBar { + JToolBar getJToolBar(); void addFeature(Feature feature); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolBarImpl.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolBarImpl.java index 195dd4f885..e8551035a8 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolBarImpl.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolBarImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.Configuration; @@ -19,100 +18,85 @@ * @author tag * @version $Id: ToolBarImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ToolBarImpl extends AbstractFeature implements ToolBar -{ +public class ToolBarImpl extends AbstractFeature implements ToolBar { + private GradientToolBar toolBar; - public ToolBarImpl(Registry registry) - { + public ToolBarImpl(Registry registry) { super("Tool Bar", Constants.TOOL_BAR, registry); } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { this.toolBar = new GradientToolBar(); this.toolBar.setLayout(new GridLayout(1, 0)); this.toolBar.setRollover(false); this.toolBar.setFloatable(false); this.toolBar.initialize(controller); - this.toolBar.addComponentListener(new ComponentAdapter() - { + this.toolBar.addComponentListener(new ComponentAdapter() { @Override - public void componentResized(ComponentEvent e) - { - for (Component c : toolBar.getComponents()) - { - if (c instanceof ToolBarButton) + public void componentResized(ComponentEvent e) { + for (Component c : toolBar.getComponents()) { + if (c instanceof ToolBarButton) { ((ToolBarButton) c).updateSize(); + } } } }); } - public JToolBar getJToolBar() - { + public JToolBar getJToolBar() { return this.toolBar; } - public void addFeature(Feature feature) - { + public void addFeature(Feature feature) { ToolBarButton btn = new ToolBarButton(feature); btn.initialize(controller); this.toolBar.add(btn); } - public static class GradientToolBar extends JToolBar implements Initializable - { + public static class GradientToolBar extends JToolBar implements Initializable { + private ToolBarButton rolloverComponent; private MouseListener mouseListener; - public GradientToolBar() - { + public GradientToolBar() { setOpaque(false); setBorderPainted(false); } - public void initialize(Controller controller) - { - this.mouseListener = new MouseListener() - { - public void mouseClicked(MouseEvent mouseEvent) - { + public void initialize(Controller controller) { + this.mouseListener = new MouseListener() { + public void mouseClicked(MouseEvent mouseEvent) { } - public void mousePressed(MouseEvent mouseEvent) - { + public void mousePressed(MouseEvent mouseEvent) { } - public void mouseReleased(MouseEvent mouseEvent) - { + public void mouseReleased(MouseEvent mouseEvent) { } - public void mouseEntered(MouseEvent mouseEvent) - { - if (mouseEvent.getSource() instanceof ToolBarButton) + public void mouseEntered(MouseEvent mouseEvent) { + if (mouseEvent.getSource() instanceof ToolBarButton) { rolloverComponent = (ToolBarButton) mouseEvent.getSource(); - else + } else { rolloverComponent = null; + } repaint(); } - public void mouseExited(MouseEvent mouseEvent) - { + public void mouseExited(MouseEvent mouseEvent) { rolloverComponent = null; repaint(); } }; } - public boolean isInitialized() - { + public boolean isInitialized() { return this.mouseListener != null; } - public void add(ToolBarButton button) - { + public void add(ToolBarButton button) { button.setBorderPainted(false); button.setOpaque(false); button.setHideActionText(true); @@ -121,16 +105,15 @@ public void add(ToolBarButton button) super.add(button); } - public void setRolloverComponent(Component c) - { + public void setRolloverComponent(Component c) { this.rolloverComponent = c != null && c instanceof ToolBarButton ? (ToolBarButton) c : null; - if (this.rolloverComponent != null) + if (this.rolloverComponent != null) { this.repaint(); + } } @Override - protected void paintComponent(Graphics g) - { + protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // Creates a two-stops gradient @@ -149,16 +132,15 @@ protected void paintComponent(Graphics g) } @Override - protected void paintChildren(Graphics g) - { + protected void paintChildren(Graphics g) { super.paintChildren(g); - if (this.rolloverComponent != null) + if (this.rolloverComponent != null) { this.drawButtonLabel(this.rolloverComponent, (Graphics2D) g); + } } - public void drawButtonLabel(ToolBarButton c, Graphics2D g) - { + public void drawButtonLabel(ToolBarButton c, Graphics2D g) { Paint oldPaint = g.getPaint(); Font font = Font.decode("Arial-Bold-14"); @@ -171,15 +153,15 @@ public void drawButtonLabel(ToolBarButton c, Graphics2D g) double ys = y + r.getHeight(); LinearGradientPaint lg = new LinearGradientPaint( - new Point2D.Double(x, y), - new Point2D.Double(x, y + r.getHeight()), - new float[] {0f, 1f}, - new Color[] {Color.BLACK, new Color(50, 50, 50)}, - MultipleGradientPaint.CycleMethod.NO_CYCLE); + new Point2D.Double(x, y), + new Point2D.Double(x, y + r.getHeight()), + new float[]{0f, 1f}, + new Color[]{Color.BLACK, new Color(50, 50, 50)}, + MultipleGradientPaint.CycleMethod.NO_CYCLE); g.setPaint(lg); RoundRectangle2D.Double bg = new RoundRectangle2D.Double(x, y, r.getWidth() + 20, r.getHeight() + 4, 20d, - 20d); + 20d); g.fill(bg); g.setPaint(Color.WHITE); @@ -189,31 +171,28 @@ public void drawButtonLabel(ToolBarButton c, Graphics2D g) } } - public static class ToolBarButton extends JButton implements Initializable - { + public static class ToolBarButton extends JButton implements Initializable { + protected boolean initialized = false; protected ImageIcon originalIcon; protected ImageIcon currentIcon; protected int iconSize = Configuration.getIntegerValue(Constants.TOOL_BAR_ICON_SIZE_PROPERTY, 52); - public ToolBarButton(Feature feature) - { + public ToolBarButton(Feature feature) { super(feature); this.setOpaque(false); this.originalIcon = (ImageIcon) feature.getValue(Action.LARGE_ICON_KEY); this.setIconSize(iconSize + this.getInsets().left + this.getInsets().right); - if (feature.getValue(Constants.ACTION_COMMAND) != null) + if (feature.getValue(Constants.ACTION_COMMAND) != null) { this.setActionCommand((String) feature.getValue(Constants.ACTION_COMMAND)); + } } - public void initialize(final Controller controller) - { + public void initialize(final Controller controller) { // Set up to learn of changes to or by the feature - this.getFeature().addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { + this.getFeature().addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { repaint(); } }); @@ -221,29 +200,26 @@ public void propertyChange(PropertyChangeEvent propertyChangeEvent) this.initialized = true; } - public boolean isInitialized() - { + public boolean isInitialized() { return this.initialized; } - public Feature getFeature() - { + public Feature getFeature() { return (Feature) this.getAction(); } @Override - protected void paintComponent(Graphics g) - { + protected void paintComponent(Graphics g) { // this.setIconSize(this.getSize().width); super.paintComponent(g); - if (this.getFeature().isOn()) + if (this.getFeature().isOn()) { drawDot(g); + } } // Draws a small image above the button to indicate that the button's feature is currently active or selected. - private void drawDot(Graphics g) - { + private void drawDot(Graphics g) { Graphics2D g2 = (Graphics2D) g; // Saves the state @@ -257,7 +233,7 @@ private void drawDot(Graphics g) float cy = y + r - 1f; RadialGradientPaint p = new RadialGradientPaint(cx, cy, r, - new float[] {0f, 1f}, new Color[] {Color.WHITE, Color.GREEN}); + new float[]{0f, 1f}, new Color[]{Color.WHITE, Color.GREEN}); g2.setPaint(p); Ellipse2D.Float dot = new Ellipse2D.Float(x, y, 2f * r, 2f * r); @@ -270,23 +246,22 @@ private void drawDot(Graphics g) } // Updates the button's size when the window is resized. - public void updateSize() - { + public void updateSize() { this.setIconSize(this.getWidth()); } - public void setIconSize(int size) - { + public void setIconSize(int size) { size -= (this.getInsets().left + this.getInsets().right); if (this.currentIcon != null && this.currentIcon.getIconWidth() == size - && this.currentIcon.getIconHeight() == size) + && this.currentIcon.getIconHeight() == size) { return; + } size = Math.min(52, size); size = Math.max(16, size); this.currentIcon = new ImageIcon( - this.originalIcon.getImage().getScaledInstance(size, size, Image.SCALE_SMOOTH)); + this.originalIcon.getImage().getScaledInstance(size, size, Image.SCALE_SMOOTH)); this.getAction().putValue(Action.LARGE_ICON_KEY, this.currentIcon); } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolTipAnnotation.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolTipAnnotation.java index 29f579e945..61ddf0303e 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolTipAnnotation.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolTipAnnotation.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.avlist.AVKey; @@ -15,19 +14,17 @@ * @author tag * @version $Id: ToolTipAnnotation.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ToolTipAnnotation extends ScreenAnnotation -{ +public class ToolTipAnnotation extends ScreenAnnotation { + private Point tooltipOffset = new Point(5, 5); - public ToolTipAnnotation(String text) - { + public ToolTipAnnotation(String text) { super(text, new Point(0, 0)); // (0,0) is a dummy; the actual point is determined when rendering this.initializeAttributes(); } - protected void initializeAttributes() - { + protected void initializeAttributes() { this.attributes.setAdjustWidthToText(AVKey.SIZE_FIT_TEXT); this.attributes.setFrameShape(AVKey.SHAPE_RECTANGLE); this.attributes.setTextColor(Color.BLACK); @@ -39,54 +36,51 @@ protected void initializeAttributes() this.attributes.setInsets(new Insets(5, 5, 5, 5)); } - public Point getTooltipOffset() - { + public Point getTooltipOffset() { return tooltipOffset; } - public void setTooltipOffset(Point tooltipOffset) - { + public void setTooltipOffset(Point tooltipOffset) { this.tooltipOffset = tooltipOffset; } - protected int getOffsetX() - { + protected int getOffsetX() { return this.tooltipOffset != null ? this.tooltipOffset.x : 0; } - protected int getOffsetY() - { + protected int getOffsetY() { return this.tooltipOffset != null ? this.tooltipOffset.y : 0; } @Override - protected void doRenderNow(DrawContext dc) - { - if (dc.getPickPoint() == null) + protected void doRenderNow(DrawContext dc) { + if (dc.getPickPoint() == null) { return; + } this.getAttributes().setDrawOffset( - new Point(this.getBounds(dc).width / 2 + this.getOffsetX(), this.getOffsetY())); + new Point(this.getBounds(dc).width / 2 + this.getOffsetX(), this.getOffsetY())); this.setScreenPoint(this.adjustDrawPointToViewport(dc.getPickPoint(), this.getBounds(dc), - dc.getView().getViewport())); + dc.getView().getViewport())); super.doRenderNow(dc); } - protected Point adjustDrawPointToViewport(Point point, Rectangle bounds, Rectangle viewport) - { + protected Point adjustDrawPointToViewport(Point point, Rectangle bounds, Rectangle viewport) { int x = point.x; int y = (int) viewport.getHeight() - point.y - 1; - if (x + this.getOffsetX() + bounds.getWidth() > viewport.getWidth()) + if (x + this.getOffsetX() + bounds.getWidth() > viewport.getWidth()) { x = (int) (viewport.getWidth() - bounds.getWidth()) - 1 - this.getOffsetX(); - else if (x < 0) + } else if (x < 0) { x = 0; + } - if (y + this.getOffsetY() + bounds.getHeight() > viewport.getHeight()) + if (y + this.getOffsetY() + bounds.getHeight() > viewport.getHeight()) { y = (int) (viewport.getHeight() - bounds.getHeight()) - 1 - this.getOffsetY(); - else if (y < 0) + } else if (y < 0) { y = bounds.height; + } return new java.awt.Point(x, y); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolTipController.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolTipController.java index fa6c98db5d..1f999a9fa2 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolTipController.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/ToolTipController.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.avlist.*; @@ -17,107 +16,91 @@ * @author tag * @version $Id: ToolTipController.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class ToolTipController extends AbstractFeature implements SelectListener -{ +public class ToolTipController extends AbstractFeature implements SelectListener { + protected Object lastRolloverObject; protected Object lastHoverObject; protected AnnotationLayer layer; protected ToolTipAnnotation annotation; - public ToolTipController(Registry registry) - { + public ToolTipController(Registry registry) { super("ToolTip Controller", Constants.FEATURE_TOOLTIP_CONTROLLER, registry); } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); this.controller.getWWd().addSelectListener(this); } - protected String getHoverText(SelectEvent event) - { - return event.getTopObject() != null && event.getTopObject() instanceof AVList ? - ((AVList) event.getTopObject()).getStringValue(AVKey.HOVER_TEXT) : null; + protected String getHoverText(SelectEvent event) { + return event.getTopObject() != null && event.getTopObject() instanceof AVList + ? ((AVList) event.getTopObject()).getStringValue(AVKey.HOVER_TEXT) : null; } - protected String getRolloverText(SelectEvent event) - { - return event.getTopObject() != null && event.getTopObject() instanceof AVList ? - ((AVList) event.getTopObject()).getStringValue(AVKey.ROLLOVER_TEXT) : null; + protected String getRolloverText(SelectEvent event) { + return event.getTopObject() != null && event.getTopObject() instanceof AVList + ? ((AVList) event.getTopObject()).getStringValue(AVKey.ROLLOVER_TEXT) : null; } - public void selected(SelectEvent event) - { - try - { - if (event.isRollover()) + public void selected(SelectEvent event) { + try { + if (event.isRollover()) { this.handleRollover(event); - else if (event.isHover()) + } else if (event.isHover()) { this.handleHover(event); - } - catch (Exception e) - { + } + } catch (Exception e) { // Wrap the handler in a try/catch to keep exceptions from bubbling up Util.getLogger().warning(e.getMessage() != null ? e.getMessage() : e.toString()); } } - protected void handleRollover(SelectEvent event) - { - if (this.lastRolloverObject != null) - { - if (this.lastRolloverObject == event.getTopObject() && !WWUtil.isEmpty(getRolloverText(event))) + protected void handleRollover(SelectEvent event) { + if (this.lastRolloverObject != null) { + if (this.lastRolloverObject == event.getTopObject() && !WWUtil.isEmpty(getRolloverText(event))) { return; + } this.hideToolTip(); this.lastRolloverObject = null; controller.redraw(); } - if (getRolloverText(event) != null) - { + if (getRolloverText(event) != null) { this.lastRolloverObject = event.getTopObject(); this.showToolTip(event, getRolloverText(event)); controller.redraw(); } } - protected void handleHover(SelectEvent event) - { - if (this.lastHoverObject != null) - { - if (this.lastHoverObject == event.getTopObject()) + protected void handleHover(SelectEvent event) { + if (this.lastHoverObject != null) { + if (this.lastHoverObject == event.getTopObject()) { return; + } this.hideToolTip(); this.lastHoverObject = null; controller.redraw(); } - if (getHoverText(event) != null) - { + if (getHoverText(event) != null) { this.lastHoverObject = event.getTopObject(); this.showToolTip(event, getHoverText(event)); controller.redraw(); } } - protected void showToolTip(SelectEvent event, String text) - { - if (annotation != null) - { + protected void showToolTip(SelectEvent event, String text) { + if (annotation != null) { annotation.setText(text); annotation.setScreenPoint(event.getPickPoint()); - } - else - { + } else { annotation = new ToolTipAnnotation(text); } - if (layer == null) - { + if (layer == null) { layer = new AnnotationLayer(); layer.setPickEnabled(false); } @@ -127,31 +110,27 @@ protected void showToolTip(SelectEvent event, String text) this.addLayer(layer); } - protected void hideToolTip() - { - if (this.layer != null) - { + protected void hideToolTip() { + if (this.layer != null) { this.layer.removeAllAnnotations(); this.removeLayer(this.layer); this.layer.dispose(); this.layer = null; } - if (this.annotation != null) - { + if (this.annotation != null) { this.annotation.dispose(); this.annotation = null; } } - protected void addLayer(Layer layer) - { - if (!this.controller.getActiveLayers().contains(layer)) + protected void addLayer(Layer layer) { + if (!this.controller.getActiveLayers().contains(layer)) { this.controller.addInternalLayer(layer); + } } - protected void removeLayer(Layer layer) - { + protected void removeLayer(Layer layer) { this.controller.getActiveLayers().remove(layer); } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/Version.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/Version.java index 8b1d1ac6d8..fc5ea6fe0f 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/Version.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/Version.java @@ -3,15 +3,14 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; /** * @author tag * @version $Id: Version.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Version -{ +public class Version { + private static final String MAJOR_VALUE = "0"; private static final String MINOR_VALUE = "0"; private static final String DOT_VALUE = "1"; @@ -19,38 +18,31 @@ public class Version private static final String VERSION_NAME = "WorldWindow Alpha"; private static final String RELEASE_DATE = "4 April 2010"; - public static String getVersion() - { + public static String getVersion() { return getVersionName() + " " + VERSION_NUMBER; } - public static String getVersionName() - { + public static String getVersionName() { return VERSION_NAME; } - public static String getVersionNumber() - { + public static String getVersionNumber() { return VERSION_NUMBER; } - public static String getVersionMajorNumber() - { + public static String getVersionMajorNumber() { return MAJOR_VALUE; } - public static String getVersionMinorNumber() - { + public static String getVersionMinorNumber() { return MINOR_VALUE; } - public static String getVersionDotNumber() - { + public static String getVersionDotNumber() { return DOT_VALUE; } - public static String getReleaseDate() - { + public static String getReleaseDate() { return RELEASE_DATE; } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/WMSLayerInfo.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/WMSLayerInfo.java index e43a535ee2..3003e559df 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/WMSLayerInfo.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/WMSLayerInfo.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.avlist.*; @@ -16,54 +15,46 @@ * @author tag * @version $Id: WMSLayerInfo.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WMSLayerInfo -{ +public class WMSLayerInfo { + private OGCCapabilities caps; private AVListImpl params = new AVListImpl(); - public WMSLayerInfo(OGCCapabilities caps, WMSLayerCapabilities layerCaps, WMSLayerStyle style) - { + public WMSLayerInfo(OGCCapabilities caps, WMSLayerCapabilities layerCaps, WMSLayerStyle style) { this.caps = caps; this.params = new AVListImpl(); this.params.setValue(AVKey.LAYER_NAMES, layerCaps.getName()); - if (style != null) + if (style != null) { this.params.setValue(AVKey.STYLE_NAMES, style.getName()); + } String layerTitle = layerCaps.getTitle(); this.params.setValue(AVKey.DISPLAY_NAME, layerTitle); } - public String getTitle() - { + public String getTitle() { return params.getStringValue(AVKey.DISPLAY_NAME); } - public OGCCapabilities getCaps() - { + public OGCCapabilities getCaps() { return caps; } - public AVListImpl getParams() - { + public AVListImpl getParams() { return params; } - public static java.util.List createLayerInfos(OGCCapabilities caps, WMSLayerCapabilities layerCaps) - { + public static java.util.List createLayerInfos(OGCCapabilities caps, WMSLayerCapabilities layerCaps) { // Create the layer info specified by the layer's capabilities entry and the selected style. ArrayList layerInfos = new ArrayList(); // An individual layer may have independent styles, and each layer/style combination is effectively one // visual layer. So here the individual layer/style combinations are formed. Set styles = layerCaps.getStyles(); - if (styles == null || styles.size() == 0) - { + if (styles == null || styles.size() == 0) { layerInfos.add(new WMSLayerInfo(caps, layerCaps, null)); - } - else - { - for (WMSLayerStyle style : styles) - { + } else { + for (WMSLayerStyle style : styles) { WMSLayerInfo layerInfo = new WMSLayerInfo(caps, layerCaps, style); layerInfos.add(layerInfo); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWMenu.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWMenu.java index 5c683f2459..853f6bbbbd 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWMenu.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWMenu.java @@ -3,15 +3,14 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; /** * @author tag * @version $Id: WWMenu.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WWMenu -{ +public interface WWMenu { + void addMenu(String featureID); void addMenus(String[] featureIDs); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWODialog.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWODialog.java index d0f05c1bc1..f70c82d4ab 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWODialog.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWODialog.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwindx.applications.worldwindow.features.Feature; @@ -14,8 +13,8 @@ * @author tag * @version $Id: WWODialog.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WWODialog extends Feature -{ +public interface WWODialog extends Feature { + JDialog getJDialog(); void setVisible(boolean tf); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWOPanel.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWOPanel.java index 3f8afd6036..7395298f2a 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWOPanel.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWOPanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import javax.swing.*; @@ -12,7 +11,7 @@ * @author tag * @version $Id: WWOPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WWOPanel -{ +public interface WWOPanel { + JPanel getJPanel(); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWPanel.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWPanel.java index 35a9d9a612..c6528f9262 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWPanel.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWPanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.WorldWindow; @@ -16,8 +15,8 @@ * @author tag * @version $Id: WWPanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface WWPanel extends WWOPanel, Initializable -{ +public interface WWPanel extends WWOPanel, Initializable { + Dimension getSize(); WorldWindow getWWd(); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWPanelImpl.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWPanelImpl.java index 46dcde45e3..76eacd0dee 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/WWPanelImpl.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/WWPanelImpl.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core; import gov.nasa.worldwind.*; @@ -22,23 +21,19 @@ * @author tag * @version $Id: WWPanelImpl.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class WWPanelImpl extends AbstractFeature implements WWPanel -{ +public class WWPanelImpl extends AbstractFeature implements WWPanel { + private JPanel panel; private WorldWindowGLCanvas wwd; - public WWPanelImpl(Registry registry) - { + public WWPanelImpl(Registry registry) { super("WorldWind Panel", Constants.WW_PANEL, registry); this.panel = new JPanel(new BorderLayout()); this.wwd = new WorldWindowGLCanvas(); - this.wwd.addRenderingExceptionListener(new RenderingExceptionListener() - { - public void exceptionThrown(Throwable t) - { - if (t instanceof WWAbsentRequirementException) - { + this.wwd.addRenderingExceptionListener(new RenderingExceptionListener() { + public void exceptionThrown(Throwable t) { + if (t instanceof WWAbsentRequirementException) { String msg = "This computer is not capable of running "; msg += Configuration.getStringValue(Constants.APPLICATION_DISPLAY_NAME); msg += "."; @@ -59,44 +54,38 @@ public void exceptionThrown(Throwable t) this.panel.add(this.wwd, BorderLayout.CENTER); } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); } - public WorldWindow getWWd() - { + public WorldWindow getWWd() { return wwd; } - public JPanel getJPanel() - { + public JPanel getJPanel() { return this.panel; } - public Dimension getSize() - { + public Dimension getSize() { return this.panel.getSize(); } - public void addLayer(Layer layer) - { - if (layer != null) + public void addLayer(Layer layer) { + if (layer != null) { this.wwd.getModel().getLayers().add(layer); + } } - public void removeLayer(Layer layer) - { + public void removeLayer(Layer layer) { this.wwd.getModel().getLayers().remove(layer); } - public void insertBeforeNamedLayer(Layer layer, String targetLayerName) - { - if (layer == null) + public void insertBeforeNamedLayer(Layer layer, String targetLayerName) { + if (layer == null) { return; + } - if (targetLayerName == null) - { + if (targetLayerName == null) { this.wwd.getModel().getLayers().add(layer); return; } @@ -104,10 +93,8 @@ public void insertBeforeNamedLayer(Layer layer, String targetLayerName) // Insert the layer into the layer list just before the target layer. int targetPosition = 0; LayerList layers = this.wwd.getModel().getLayers(); - for (Layer l : layers) - { - if (l.getName().indexOf(targetLayerName) != -1) - { + for (Layer l : layers) { + if (l.getName().indexOf(targetLayerName) != -1) { targetPosition = layers.indexOf(l); break; } @@ -115,13 +102,12 @@ public void insertBeforeNamedLayer(Layer layer, String targetLayerName) layers.add(targetPosition, layer); } - public void insertAfterNamedLayer(Layer layer, String targetLayerName) - { - if (layer == null) + public void insertAfterNamedLayer(Layer layer, String targetLayerName) { + if (layer == null) { return; + } - if (targetLayerName == null) - { + if (targetLayerName == null) { this.wwd.getModel().getLayers().add(layer); return; } @@ -129,10 +115,10 @@ public void insertAfterNamedLayer(Layer layer, String targetLayerName) // Insert the layer into the layer list just after the target layer. int targetPosition = 0; LayerList layers = this.wwd.getModel().getLayers(); - for (Layer l : layers) - { - if (l.getName().indexOf(targetLayerName) != -1) + for (Layer l : layers) { + if (l.getName().indexOf(targetLayerName) != -1) { targetPosition = layers.indexOf(l); + } } layers.add(targetPosition + 1, layer); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/ActiveLayersManager.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/ActiveLayersManager.java index 51c3a037dc..89051276af 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/ActiveLayersManager.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/ActiveLayersManager.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core.layermanager; import gov.nasa.worldwind.layers.LayerList; @@ -14,8 +13,8 @@ * @author tag * @version $Id: ActiveLayersManager.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface ActiveLayersManager extends Feature -{ +public interface ActiveLayersManager extends Feature { + /** * Indicates whether to show internal layers, those whose attribute-value list contains {@link * Constants#INTERNAL_LAYER}. diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/LayerManager.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/LayerManager.java index 75036043ac..b2878a15d7 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/LayerManager.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/LayerManager.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core.layermanager; import gov.nasa.worldwind.layers.*; @@ -14,8 +13,8 @@ * @author tag * @version $Id: LayerManager.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public interface LayerManager extends Feature -{ +public interface LayerManager extends Feature { + Layer findLayerByTitle(String layerTitle, String groupTitle); void addGroup(LayerPath pathToGroup); @@ -62,7 +61,7 @@ public interface LayerManager extends Feature * group. For some layer groups, such as the base group, it's not appropriate to turn them all on or all off. * * @param path the path to the group. - * @param tf true if group selection should be allowed, false if group selection should not be allowed. + * @param tf true if group selection should be allowed, false if group selection should not be allowed. */ void enableGroupSelection(LayerPath path, boolean tf); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/LayerPath.java b/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/LayerPath.java index 855c0b3318..c8eedb9e9e 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/LayerPath.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/core/layermanager/LayerPath.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.core.layermanager; import gov.nasa.worldwind.util.WWUtil; @@ -14,71 +13,65 @@ * @author tag * @version $Id: LayerPath.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class LayerPath extends ArrayList -{ - public LayerPath() - { +public class LayerPath extends ArrayList { + + public LayerPath() { } - public LayerPath(LayerPath initialPath, String... args) - { + public LayerPath(LayerPath initialPath, String... args) { this.addAll(initialPath); - for (String pathElement : args) - { - if (!WWUtil.isEmpty(pathElement)) + for (String pathElement : args) { + if (!WWUtil.isEmpty(pathElement)) { this.add(pathElement); + } } } - public LayerPath(String initialPathEntry, String... args) - { + public LayerPath(String initialPathEntry, String... args) { this.add(initialPathEntry); - for (String pathElement : args) - { - if (!WWUtil.isEmpty(pathElement)) + for (String pathElement : args) { + if (!WWUtil.isEmpty(pathElement)) { this.add(pathElement); + } } } - public LayerPath(List initialPathEntries) - { + public LayerPath(List initialPathEntries) { this.addAll(initialPathEntries); } - public LayerPath lastButOne() - { + public LayerPath lastButOne() { return this.subPath(0, this.size() - 1); } - public LayerPath subPath(int start, int end) - { + public LayerPath subPath(int start, int end) { return new LayerPath(this.subList(start, end)); } - public static boolean isEmptyPath(LayerPath path) - { + public static boolean isEmptyPath(LayerPath path) { return path == null || path.size() == 0 || WWUtil.isEmpty(path.get(0)); } @Override - public String toString() - { - if (this.size() == 0) + public String toString() { + if (this.size() == 0) { return ""; + } StringBuilder sb = new StringBuilder(); - for (String s : this) - { - if (WWUtil.isEmpty(s)) + for (String s : this) { + if (WWUtil.isEmpty(s)) { s = ""; + } - if (sb.length() == 0) + if (sb.length() == 0) { sb.append(s); - else + } else { sb.append("/").append(s); + } } return sb.toString(); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractApplicationFeature.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractApplicationFeature.java index 53381b7738..e9cf67eace 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractApplicationFeature.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractApplicationFeature.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwind.layers.*; @@ -20,8 +19,8 @@ * @author tag * @version $Id: AbstractApplicationFeature.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractApplicationFeature extends AbstractFeature implements NetworkActivitySignal.NetworkUser -{ +public abstract class AbstractApplicationFeature extends AbstractFeature implements NetworkActivitySignal.NetworkUser { + protected boolean on; protected boolean autoSelectLayers; protected LayerList appLayers; @@ -31,84 +30,70 @@ public abstract class AbstractApplicationFeature extends AbstractFeature impleme protected abstract void doCreateLayers(); - protected AbstractApplicationFeature(String name, String featureID, String largeIconPath, Registry registry) - { + protected AbstractApplicationFeature(String name, String featureID, String largeIconPath, Registry registry) { super(name, featureID, largeIconPath, registry); } @Override - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); } - public boolean hasNetworkActivity() - { + public boolean hasNetworkActivity() { return this.createLayersThread != null && this.createLayersThread.isAlive(); } @Override - public boolean isOn() - { + public boolean isOn() { return this.on; } - protected void setOn(boolean tf) - { + protected void setOn(boolean tf) { this.on = tf; } - public boolean isAutoSelectLayers() - { + public boolean isAutoSelectLayers() { return autoSelectLayers; } - public void setAutoSelectLayers(boolean autoSelectLayers) - { + public void setAutoSelectLayers(boolean autoSelectLayers) { this.autoSelectLayers = autoSelectLayers; } - public LayerList getAppLayers() - { + public LayerList getAppLayers() { return this.appLayers != null ? this.appLayers : new LayerList(); } - protected void destroyLayers() - { + protected void destroyLayers() { this.killPopulateLayerThread(); - if (this.appLayers == null) + if (this.appLayers == null) { return; + } - for (Layer layer : this.appLayers) - { + for (Layer layer : this.appLayers) { this.destroyLayer(layer); } this.appLayers.clear(); this.appLayers = null; } - protected void destroyLayer(Layer layer) - { + protected void destroyLayer(Layer layer) { this.controller.getLayerManager().removeLayer(layer); this.appLayers.remove(layer); layer.dispose(); } - protected void killPopulateLayerThread() - { - if (this.createLayersThread != null && this.createLayersThread.isAlive()) - { + protected void killPopulateLayerThread() { + if (this.createLayersThread != null && this.createLayersThread.isAlive()) { this.createLayersThread.interrupt(); this.controller.getNetworkActivitySignal().removeNetworkUser(this); this.createLayersThread = null; } } - protected void handleInterrupt() - { - if (Thread.currentThread().isInterrupted() && this.appLayers != null) - { + protected void handleInterrupt() { + if (Thread.currentThread().isInterrupted() && this.appLayers != null) { Util.getLogger().info("Data retrieval cancelled"); // Clean up so the user can try again later @@ -116,34 +101,24 @@ protected void handleInterrupt() } } - protected void removeLayers() - { + protected void removeLayers() { this.controller.getLayerManager().removeLayers(this.appLayers); } - protected void createLayers() - { - if (this.appLayers == null) - { + protected void createLayers() { + if (this.appLayers == null) { this.appLayers = new LayerList(); this.appLayers.setDisplayName(this.getLayerGroupName()); } - this.createLayersThread = new Thread(new Runnable() - { - public void run() - { - try - { + this.createLayersThread = new Thread(new Runnable() { + public void run() { + try { doCreateLayers(); - } - finally - { + } finally { handleInterrupt(); - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + SwingUtilities.invokeLater(new Runnable() { + public void run() { controller.getNetworkActivitySignal().removeNetworkUser(AbstractApplicationFeature.this); createLayersThread = null; } @@ -157,66 +132,52 @@ public void run() this.controller.getNetworkActivitySignal().addNetworkUser(AbstractApplicationFeature.this); } - protected void addLayer(final Layer layer, final LayerPath path) - { - try - { + protected void addLayer(final Layer layer, final LayerPath path) { + try { // In order to synchronize layer additions, they are added on the EDT. - if (SwingUtilities.isEventDispatchThread()) + if (SwingUtilities.isEventDispatchThread()) { this.doAddLayer(layer, path); - else - SwingUtilities.invokeAndWait(new Runnable() - { - public void run() - { + } else { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { doAddLayer(layer, path); } }); - } - catch (InterruptedException e) - { + } + } catch (InterruptedException e) { // Don't do anything here because higher level code will detect and report the interrupt. - } - catch (InvocationTargetException e) - { + } catch (InvocationTargetException e) { Util.getLogger().log(Level.WARNING, "Invocation target exception", e); } } - protected void doAddLayer(final Layer layer, final LayerPath path) - { + protected void doAddLayer(final Layer layer, final LayerPath path) { LayerManager layerManager = controller.getLayerManager(); Layer oldLayer = layerManager.getLayerFromPath(path); - if (oldLayer != null) - { + if (oldLayer != null) { this.controller.getLayerManager().removeLayer(path); this.appLayers.remove(oldLayer); } // Cause the cache files to be deleted when the JVM exits. // layer.setValue(AVKey.DELETE_CACHE_ON_EXIT, true); - this.appLayers.add(layer); layerManager.addLayer(layer, path.lastButOne()); layerManager.selectLayer(layer, this.isAutoSelectLayers()); layerManager.expandPath(path.lastButOne()); } - protected void addLayers(LayerList layerList) - { - for (Layer layer : layerList) - { + protected void addLayers(LayerList layerList) { + for (Layer layer : layerList) { this.addLayer(layer, new LayerPath(layerList.getDisplayName(), layer.getName())); } } - protected LayerTree addLayerTree(LayerTree layerTree) - { + protected LayerTree addLayerTree(LayerTree layerTree) { LayerPath basePath = new LayerPath(this.getLayerGroupName()); Iterator iter = layerTree.getPathIterator(basePath); - while (iter.hasNext()) - { + while (iter.hasNext()) { LayerPath path = iter.next(); Layer layer = layerTree.getLayer(path); this.addLayer(layer, path); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractElevationsFeature.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractElevationsFeature.java index 681e6e8680..860055eb8d 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractElevationsFeature.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractElevationsFeature.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwind.Disposable; @@ -22,72 +21,64 @@ * @author tag * @version $Id: AbstractElevationsFeature.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractElevationsFeature extends AbstractFeature implements NetworkActivitySignal.NetworkUser -{ +public abstract class AbstractElevationsFeature extends AbstractFeature implements NetworkActivitySignal.NetworkUser { + protected boolean on; protected List elevationModels; protected Thread createModelsThread; protected abstract void doCreateModels(); - protected AbstractElevationsFeature(String name, String featureID, String largeIconPath, Registry registry) - { + protected AbstractElevationsFeature(String name, String featureID, String largeIconPath, Registry registry) { super(name, featureID, largeIconPath, registry); } @Override - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); this.addToToolBar(); } - public boolean hasNetworkActivity() - { + public boolean hasNetworkActivity() { return this.createModelsThread != null && this.createModelsThread.isAlive(); } @Override - public boolean isOn() - { + public boolean isOn() { return this.on; } - protected void setOn(boolean tf) - { + protected void setOn(boolean tf) { this.on = tf; } @Override - public void turnOn(boolean tf) - { - if (tf == this.isOn()) + public void turnOn(boolean tf) { + if (tf == this.isOn()) { return; + } - if (tf) - { - if (this.getElevationModels().size() == 0) + if (tf) { + if (this.getElevationModels().size() == 0) { this.createModels(); // also adds them to the layer manager - else + } else { this.addModels(this.getElevationModels()); - } - else + } + } else { this.removeModels(); + } this.setOn(tf); this.controller.redraw(); } - public List getElevationModels() - { + public List getElevationModels() { return this.elevationModels != null ? this.elevationModels : new ArrayList(); } - protected void handleInterrupt() - { - if (Thread.currentThread().isInterrupted() && this.elevationModels != null) - { + protected void handleInterrupt() { + if (Thread.currentThread().isInterrupted() && this.elevationModels != null) { Util.getLogger().info("Data retrieval cancelled"); // Clean up so the user can try again later @@ -95,15 +86,14 @@ protected void handleInterrupt() } } - protected void destroyElevationModels() - { + protected void destroyElevationModels() { this.killPopulateLayerThread(); - if (this.elevationModels == null) + if (this.elevationModels == null) { return; + } - for (ElevationModel em : this.elevationModels) - { + for (ElevationModel em : this.elevationModels) { this.destroyElevationModel(em); } @@ -111,71 +101,59 @@ protected void destroyElevationModels() this.elevationModels = null; } - protected void destroyElevationModel(ElevationModel em) - { + protected void destroyElevationModel(ElevationModel em) { this.removeModel(em); - if (em instanceof Disposable) + if (em instanceof Disposable) { ((Disposable) em).dispose(); + } } - protected void removeModels() - { - for (ElevationModel em : this.getElevationModels()) - { + protected void removeModels() { + for (ElevationModel em : this.getElevationModels()) { this.removeModel(em); } } - protected void addModels(List models) - { - for (ElevationModel em : models) - { + protected void addModels(List models) { + for (ElevationModel em : models) { this.addModel(em); } } - protected void removeModel(ElevationModel em) - { - if (em == null) + protected void removeModel(ElevationModel em) { + if (em == null) { return; + } ElevationModel parentModel = this.controller.getWWd().getModel().getGlobe().getElevationModel(); - if (parentModel instanceof CompoundElevationModel) + if (parentModel instanceof CompoundElevationModel) { ((CompoundElevationModel) parentModel).removeElevationModel(em); + } } - protected void killPopulateLayerThread() - { - if (this.createModelsThread != null && this.createModelsThread.isAlive()) - { + protected void killPopulateLayerThread() { + if (this.createModelsThread != null && this.createModelsThread.isAlive()) { this.createModelsThread.interrupt(); this.controller.getNetworkActivitySignal().removeNetworkUser(this); this.createModelsThread = null; } } - protected void createModels() - { - if (this.elevationModels == null) + protected void createModels() { + if (this.elevationModels == null) { this.elevationModels = new ArrayList(); + } - this.createModelsThread = new Thread(new Runnable() - { - public void run() - { - try - { + this.createModelsThread = new Thread(new Runnable() { + public void run() { + try { doCreateModels(); - } - finally - { + } finally { handleInterrupt(); - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { + SwingUtilities.invokeLater(new Runnable() { + public void run() { controller.getNetworkActivitySignal().removeNetworkUser(AbstractElevationsFeature.this); createModelsThread = null; controller.redraw(); @@ -190,23 +168,22 @@ public void run() this.controller.getNetworkActivitySignal().addNetworkUser(AbstractElevationsFeature.this); } - protected void addModel(ElevationModel em) - { + protected void addModel(ElevationModel em) { this.removeModel(em); this.doAddModel(em); - if (this.elevationModels == null) + if (this.elevationModels == null) { this.elevationModels = new ArrayList(); + } - if (!this.getElevationModels().contains(em)) + if (!this.getElevationModels().contains(em)) { this.getElevationModels().add(em); + } } - protected void doAddModel(ElevationModel em) - { + protected void doAddModel(ElevationModel em) { ElevationModel globeEM = this.controller.getWWd().getModel().getGlobe().getElevationModel(); - if (!(globeEM instanceof CompoundElevationModel)) - { + if (!(globeEM instanceof CompoundElevationModel)) { CompoundElevationModel cem = new CompoundElevationModel(); cem.addElevationModel(globeEM); globeEM = cem; @@ -216,20 +193,14 @@ protected void doAddModel(ElevationModel em) ((CompoundElevationModel) globeEM).addElevationModel(em); } - protected WMSCapabilities retrieveCapsDoc(String urlString) - { - try - { + protected WMSCapabilities retrieveCapsDoc(String urlString) { + try { CapabilitiesRequest request = new CapabilitiesRequest(new URI(urlString)); return new WMSCapabilities(request); - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { e.printStackTrace(); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { e.printStackTrace(); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeature.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeature.java index f4767fe220..64dac8c2b9 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeature.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeature.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwindx.applications.worldwindow.core.*; @@ -18,146 +17,126 @@ * @author tag * @version $Id: AbstractFeature.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AbstractFeature extends AbstractAction implements Feature -{ +public class AbstractFeature extends AbstractAction implements Feature { + protected String featureID; protected Controller controller; - protected AbstractFeature(String s, String featureID, Registry registry) - { + protected AbstractFeature(String s, String featureID, Registry registry) { super(s); this.putValue(Constants.ACTION_COMMAND, s); - if (featureID != null && featureID.length() > 0 && registry != null) - { + if (featureID != null && featureID.length() > 0 && registry != null) { this.featureID = featureID; registry.registerObject(featureID, this); } } - protected AbstractFeature(String s, String featureID, String largeIconPath, Registry registry) - { + protected AbstractFeature(String s, String featureID, String largeIconPath, Registry registry) { this(s, featureID, registry); - if (largeIconPath != null && largeIconPath.length() > 0) - { + if (largeIconPath != null && largeIconPath.length() > 0) { Icon icon = ImageLibrary.getIcon(largeIconPath); - if (icon != null) + if (icon != null) { this.putValue(Action.LARGE_ICON_KEY, icon); - else + } else { this.putValue(Action.LARGE_ICON_KEY, ImageLibrary.getWarningIcon(64)); + } } } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { this.controller = controller; this.setMenuAccellerator(this.controller); } - public boolean isInitialized() - { + public boolean isInitialized() { return this.controller != null; } - protected Object register(String featureID, Registry registry) - { + protected Object register(String featureID, Registry registry) { return registry.registerObject(featureID, this); } - public Controller getController() - { + public Controller getController() { return this.controller; } - public String getFeatureID() - { + public String getFeatureID() { return this.featureID; } - public String getStringValue(String key) - { + public String getStringValue(String key) { return (String) this.getValue(key); } - public String getName() - { + public String getName() { return (String) this.getValue(Action.NAME); } - public boolean isOn() - { + public boolean isOn() { return this.isEnabled(); } - public boolean isTwoState() - { + public boolean isTwoState() { return false; } - public void turnOn(boolean tf) - { + public void turnOn(boolean tf) { } - protected void addToToolBar() - { + protected void addToToolBar() { ToolBar toolBar = this.controller.getToolBar(); - if (toolBar != null) + if (toolBar != null) { toolBar.addFeature(this); + } } - protected void setMenuAccellerator(Controller controller) - { - if (controller == null) + protected void setMenuAccellerator(Controller controller) { + if (controller == null) { return; + } Object accelerator = controller.getRegisteredObject(this.getClass().getName() + Constants.ACCELERATOR_SUFFIX); - if (accelerator == null) + if (accelerator == null) { return; + } - if (accelerator instanceof String) - { + if (accelerator instanceof String) { KeyStroke keyStroke = KeyStroke.getKeyStroke((String) accelerator); - if (keyStroke != null) + if (keyStroke != null) { this.putValue(Action.ACCELERATOR_KEY, keyStroke); + } } } - public void actionPerformed(ActionEvent actionEvent) - { + public void actionPerformed(ActionEvent actionEvent) { try // Protect application execution from exceptions thrown during action processing { doActionPerformed(actionEvent); - } - catch (Exception e) - { + } catch (Exception e) { Util.getLogger().log(Level.SEVERE, String.format("Error executing action %s.", getValue(Action.NAME)), e); } } - protected void doActionPerformed(ActionEvent actionEvent) - { + protected void doActionPerformed(ActionEvent actionEvent) { this.turnOn(!this.isOn()); this.controller.redraw(); } - public void propertyChange(PropertyChangeEvent propertyChangeEvent) - { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { try // Protect application execution from exceptions thrown during property processing { this.doPropertyChange(propertyChangeEvent); - } - catch (Exception e) - { + } catch (Exception e) { Util.getLogger().log(Level.SEVERE, String.format( - "Error handling property change %s.", getValue(Action.NAME)), e); + "Error handling property change %s.", getValue(Action.NAME)), e); } } - @SuppressWarnings( {"UnusedDeclaration"}) - public void doPropertyChange(PropertyChangeEvent propertyChangeEvent) - { + @SuppressWarnings({"UnusedDeclaration"}) + public void doPropertyChange(PropertyChangeEvent propertyChangeEvent) { // Override this method to respond to property changes } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeatureDialog.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeatureDialog.java index 0ba0ce3e73..eaa90739b1 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeatureDialog.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeatureDialog.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwindx.applications.worldwindow.core.*; @@ -18,8 +17,8 @@ * @author tag * @version $Id: AbstractFeatureDialog.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class AbstractFeatureDialog extends AbstractFeature implements WWODialog -{ +public class AbstractFeatureDialog extends AbstractFeature implements WWODialog { + protected JDialog dialog; protected JPanel dialogPanel; protected JPanel leftButtonPanel; @@ -31,18 +30,15 @@ public class AbstractFeatureDialog extends AbstractFeature implements WWODialog private int horizontalLocation = SwingConstants.CENTER; private int verticalLocation = SwingConstants.CENTER; - protected AbstractFeatureDialog(String name, String featureID, Registry registry) - { + protected AbstractFeatureDialog(String name, String featureID, Registry registry) { super(name, featureID, registry); } - protected AbstractFeatureDialog(String name, String featureID, String largeIconPath, Registry registry) - { + protected AbstractFeatureDialog(String name, String featureID, String largeIconPath, Registry registry) { super(name, featureID, largeIconPath, registry); } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); this.dialog = new JDialog(this.controller.getFrame()); @@ -55,26 +51,21 @@ public void initialize(Controller controller) this.setTitle(this.getName()); } - public JDialog getJDialog() - { + public JDialog getJDialog() { return this.dialog; } - public void setTitle(String title) - { + public void setTitle(String title) { this.dialog.setTitle(title != null ? title : ""); } - protected void setTaskPanel(FeaturePanel panel) - { + protected void setTaskPanel(FeaturePanel panel) { this.setTaskComponent(panel.getJPanel()); } - protected void setTaskPanel(String featureID) - { + protected void setTaskPanel(String featureID) { FeaturePanel panel = (FeaturePanel) this.controller.getRegisteredObject(featureID); - if (panel == null) - { + if (panel == null) { Util.getLogger().warning("Registrado ning\u00fan objeto para caracter\u00edstica " + featureID); return; } @@ -82,77 +73,66 @@ protected void setTaskPanel(String featureID) this.setTaskComponent(panel.getJPanel()); JComponent[] dialogControls = panel.getDialogControls(); - if (dialogControls != null) - { - for (JComponent c : dialogControls) - { + if (dialogControls != null) { + for (JComponent c : dialogControls) { this.insertDialogComponent(c); } } } // Specifies the main component of the dialog, typically the main panel. - protected void setTaskComponent(JComponent component) - { + protected void setTaskComponent(JComponent component) { this.dialog.getContentPane().add(component, BorderLayout.CENTER); } - protected void insertLeftDialogComponent(JComponent component) - { + protected void insertLeftDialogComponent(JComponent component) { int n = this.leftButtonPanel.getComponentCount(); this.leftButtonPanel.add(component, - n == 0 ? BorderLayout.WEST : n == 1 ? BorderLayout.CENTER : BorderLayout.EAST); + n == 0 ? BorderLayout.WEST : n == 1 ? BorderLayout.CENTER : BorderLayout.EAST); } - protected void insertRightDialogComponent(JComponent component) - { + protected void insertRightDialogComponent(JComponent component) { int n = this.rightButtonPanel.getComponentCount(); this.rightButtonPanel.add(component, - n == 0 ? BorderLayout.EAST : n == 1 ? BorderLayout.CENTER : BorderLayout.WEST); + n == 0 ? BorderLayout.EAST : n == 1 ? BorderLayout.CENTER : BorderLayout.WEST); } - protected void insertCenterDialogComponent(JComponent component) - { + protected void insertCenterDialogComponent(JComponent component) { int n = this.centerButtonPanel.getComponentCount(); this.centerButtonPanel.add(component, - n == 0 ? BorderLayout.CENTER : n == 1 ? BorderLayout.EAST : BorderLayout.WEST); + n == 0 ? BorderLayout.CENTER : n == 1 ? BorderLayout.EAST : BorderLayout.WEST); } - protected void insertDialogComponent(JComponent component) - { + protected void insertDialogComponent(JComponent component) { this.insertRightDialogComponent(component); } - protected void setLocation(int horizontal, int vertical) - { + protected void setLocation(int horizontal, int vertical) { this.horizontalLocation = horizontal; this.verticalLocation = vertical; this.positionInitialized = false; } @Override - public void turnOn(boolean tf) - { + public void turnOn(boolean tf) { this.setVisible(tf); } - public void setVisible(boolean tf) - { - if (tf) + public void setVisible(boolean tf) { + if (tf) { this.dialog.pack(); + } - if (tf && !this.positionInitialized) - { + if (tf && !this.positionInitialized) { Util.positionDialogInContainer(this.dialog, this.controller.getAppPanel().getJPanel(), - this.horizontalLocation, this.verticalLocation); + this.horizontalLocation, this.verticalLocation); this.positionInitialized = true; } this.dialog.setVisible(tf); } - private JPanel createButtonPanel() - { + private JPanel createButtonPanel() { this.leftButtonPanel = new JPanel(new BorderLayout(10, 5)); this.rightButtonPanel = new JPanel(new BorderLayout(10, 5)); this.centerButtonPanel = new JPanel(new BorderLayout(10, 5)); @@ -165,10 +145,8 @@ private JPanel createButtonPanel() this.closeButton = new JButton("Close"); this.closeButton.setToolTipText("Close dialog"); - this.closeButton.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent actionEvent) - { + this.closeButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeatureLayer.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeatureLayer.java index 164a0f9496..134ef15df1 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeatureLayer.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeatureLayer.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwind.layers.Layer; @@ -15,52 +14,47 @@ * @author tag * @version $Id: AbstractFeatureLayer.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractFeatureLayer extends AbstractFeature -{ +public abstract class AbstractFeatureLayer extends AbstractFeature { + protected Layer layer; private boolean twoState = false; protected abstract Layer doAddLayer(); protected AbstractFeatureLayer(String featureTitle, String featureID, String iconFilePath, boolean twoState, - Registry registry) - { + Registry registry) { super(featureTitle, featureID, iconFilePath, registry); this.twoState = twoState; } - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); this.layer = this.doAddLayer(); } @Override - public void setEnabled(boolean tf) - { + public void setEnabled(boolean tf) { super.setEnabled(tf); - if (this.layer != null) + if (this.layer != null) { this.layer.setEnabled(isEnabled()); + } } - public boolean isOn() - { + public boolean isOn() { return this.layer != null && this.isEnabled() && this.layer.isEnabled() - && this.controller.getActiveLayers().contains(this.layer); + && this.controller.getActiveLayers().contains(this.layer); } @Override - public boolean isTwoState() - { + public boolean isTwoState() { return this.twoState; } @Override - public void turnOn(boolean tf) - { + public void turnOn(boolean tf) { boolean currentState = this.isOn(); layer.setEnabled(tf); @@ -71,8 +65,7 @@ public void turnOn(boolean tf) } @Override - protected void doActionPerformed(ActionEvent actionEvent) - { + protected void doActionPerformed(ActionEvent actionEvent) { this.turnOn(this.layer == null || !layer.isEnabled()); controller.redraw(); } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeaturePanel.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeaturePanel.java index 8ac3e3cb1c..f92ff3f4ed 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeaturePanel.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractFeaturePanel.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwindx.applications.worldwindow.core.*; @@ -14,20 +13,18 @@ * @author tag * @version $Id: AbstractFeaturePanel.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractFeaturePanel extends AbstractFeature implements FeaturePanel -{ +public abstract class AbstractFeaturePanel extends AbstractFeature implements FeaturePanel { + protected JPanel panel; - public AbstractFeaturePanel(String s, String featureID, JPanel panel, Registry registry) - { + public AbstractFeaturePanel(String s, String featureID, JPanel panel, Registry registry) { super(s, featureID, registry); panel.putClientProperty(Constants.FEATURE, this); this.panel = panel; } - public AbstractFeaturePanel(String s, String featureID, String largeIconPath, JPanel panel, Registry registry) - { + public AbstractFeaturePanel(String s, String featureID, String largeIconPath, JPanel panel, Registry registry) { super(s, featureID, largeIconPath, registry); panel.putClientProperty(Constants.FEATURE, this); @@ -35,21 +32,19 @@ public AbstractFeaturePanel(String s, String featureID, String largeIconPath, JP } @Override - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); - if (this.panel != null) + if (this.panel != null) { this.panel.putClientProperty(Constants.FEATURE_OWNER_PROPERTY, this); + } } - public JPanel getJPanel() - { + public JPanel getJPanel() { return this.panel; } - public JComponent[] getDialogControls() - { + public JComponent[] getDialogControls() { return null; } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractOnDemandLayerFeature.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractOnDemandLayerFeature.java index 86c71cd0bd..71021a6378 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractOnDemandLayerFeature.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractOnDemandLayerFeature.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwind.layers.Layer; @@ -14,66 +13,60 @@ * @author tag * @version $Id: AbstractOnDemandLayerFeature.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractOnDemandLayerFeature extends AbstractFeature -{ +public abstract class AbstractOnDemandLayerFeature extends AbstractFeature { + protected String group; protected Layer layer; protected boolean on = false; protected abstract Layer createLayer(); - public AbstractOnDemandLayerFeature(String s, String featureID, String iconPath, String group, Registry registry) - { + public AbstractOnDemandLayerFeature(String s, String featureID, String iconPath, String group, Registry registry) { super(s, featureID, iconPath, registry); this.group = group; } @Override - public boolean isTwoState() - { + public boolean isTwoState() { return true; } @Override - public boolean isOn() - { + public boolean isOn() { return this.on; } @Override - public void turnOn(boolean tf) - { - if (tf == this.on) + public void turnOn(boolean tf) { + if (tf == this.on) { return; + } - if (tf && this.layer == null) + if (tf && this.layer == null) { this.layer = this.createLayer(); + } - if (this.layer == null) + if (this.layer == null) { return; + } - if (tf) - { + if (tf) { LayerPath path = new LayerPath(this.group); this.addLayer(path); this.controller.getLayerManager().selectLayer(this.layer, true); - } - else - { + } else { this.removeLayer(); } this.on = tf; } - protected void addLayer(LayerPath path) - { + protected void addLayer(LayerPath path) { this.controller.getLayerManager().addLayer(this.layer, path); } - protected void removeLayer() - { + protected void removeLayer() { this.controller.getLayerManager().removeLayer(this.layer); } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractOpenResourceFeature.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractOpenResourceFeature.java index ef1bdb7c1d..886d805466 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractOpenResourceFeature.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/AbstractOpenResourceFeature.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwindx.applications.worldwindow.core.*; @@ -12,35 +11,27 @@ * @author tag * @version $Id: AbstractOpenResourceFeature.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public abstract class AbstractOpenResourceFeature extends AbstractFeature implements NetworkActivitySignal.NetworkUser -{ +public abstract class AbstractOpenResourceFeature extends AbstractFeature implements NetworkActivitySignal.NetworkUser { + protected Thread loadingThread; - protected AbstractOpenResourceFeature(String s, String featureID, String largeIconPath, Registry registry) - { + protected AbstractOpenResourceFeature(String s, String featureID, String largeIconPath, Registry registry) { super(s, featureID, largeIconPath, registry); } - public boolean hasNetworkActivity() - { + public boolean hasNetworkActivity() { return this.loadingThread != null && this.loadingThread.isAlive(); } - protected Thread runOpenThread(final Object source) - { - this.loadingThread = new Thread() - { + protected Thread runOpenThread(final Object source) { + this.loadingThread = new Thread() { @Override - public void run() - { + public void run() { getController().getNetworkActivitySignal().addNetworkUser(AbstractOpenResourceFeature.this); - try - { + try { new SimpleImporter(source, getController()).startImport(); - } - finally - { + } finally { controller.getNetworkActivitySignal().removeNetworkUser(AbstractOpenResourceFeature.this); } } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/Compass.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/Compass.java index ecb3740007..443bd86411 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/Compass.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/Compass.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwind.avlist.AVKey; @@ -14,20 +13,17 @@ * @author tag * @version $Id: Compass.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Compass extends AbstractFeatureLayer -{ - public Compass() - { +public class Compass extends AbstractFeatureLayer { + + public Compass() { this(null); } - public Compass(Registry registry) - { + public Compass(Registry registry) { super("Compass", Constants.FEATURE_COMPASS, null, true, registry); } - protected Layer doAddLayer() - { + protected Layer doAddLayer() { CompassLayer layer = new CompassLayer(); layer.setIconScale(0.3); diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/CoordinatesDisplay.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/CoordinatesDisplay.java index 78fe4daae8..74ee9ebcc5 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/CoordinatesDisplay.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/CoordinatesDisplay.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwind.View; @@ -26,30 +25,26 @@ * @author tag * @version $Id: CoordinatesDisplay.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class CoordinatesDisplay extends AbstractOnDemandLayerFeature -{ - public CoordinatesDisplay() - { +public class CoordinatesDisplay extends AbstractOnDemandLayerFeature { + + public CoordinatesDisplay() { this(null); } - public CoordinatesDisplay(Registry registry) - { + public CoordinatesDisplay(Registry registry) { super("Coordinates", Constants.FEATURE_COORDINATES_DISPLAY, - "gov/nasa/worldwindx/applications/worldwindow/images/coordinates-64x64.png", null, registry); + "gov/nasa/worldwindx/applications/worldwindow/images/coordinates-64x64.png", null, registry); } @Override - public void initialize(Controller controller) - { + public void initialize(Controller controller) { super.initialize(controller); this.addToToolBar(); } @Override - protected Layer createLayer() - { + protected Layer createLayer() { Layer layer = this.doCreateLayer(); layer.setPickEnabled(false); @@ -58,19 +53,16 @@ protected Layer createLayer() } @Override - protected void addLayer(LayerPath path) - { + protected void addLayer(LayerPath path) { controller.addInternalActiveLayer(this.layer); } @Override - protected void removeLayer() - { + protected void removeLayer() { this.controller.getWWPanel().removeLayer(this.layer); } - protected Layer doCreateLayer() - { + protected Layer doCreateLayer() { ScreenAnnotation anno = new ScreenAnnotation("Dummy Text", new Point(100, 100)); anno.setAlwaysOnTop(true); @@ -102,15 +94,13 @@ protected Layer doCreateLayer() return layer; } - private class CoordAnnotationLayer extends AnnotationLayer - { + private class CoordAnnotationLayer extends AnnotationLayer { + @Override - public void render(DrawContext dc) - { + public void render(DrawContext dc) { Iterator iter = this.getAnnotations().iterator(); Annotation anno = iter.next(); - if (anno != null && anno instanceof ScreenAnnotation) - { + if (anno != null && anno instanceof ScreenAnnotation) { anno.setText(formatText(dc)); Dimension wwSize = controller.getWWPanel().getSize(); ((ScreenAnnotation) anno).setScreenPoint(new Point(wwSize.width, wwSize.height)); @@ -120,52 +110,45 @@ public void render(DrawContext dc) } } - private Position getCurrentPosition(DrawContext dc) - { - if (dc.getPickedObjects() == null) + private Position getCurrentPosition(DrawContext dc) { + if (dc.getPickedObjects() == null) { return null; + } PickedObject po = dc.getPickedObjects().getTerrainObject(); return po != null ? po.getPosition() : null; } - private String formatText(DrawContext dc) - { + private String formatText(DrawContext dc) { StringBuilder sb = new StringBuilder(); Position eyePosition = dc.getView().getEyePosition(); - if (eyePosition != null) - { + if (eyePosition != null) { WWOUnitsFormat units = this.controller.getUnits(); String origFormat = units.getFormat(UnitsFormat.FORMAT_EYE_ALTITUDE); String tempFormat = origFormat; - if (Math.abs(eyePosition.getElevation() * units.getLengthUnitsMultiplier()) < 10) - { + if (Math.abs(eyePosition.getElevation() * units.getLengthUnitsMultiplier()) < 10) { tempFormat = " %,6.3f %s"; units.setFormat(UnitsFormat.FORMAT_EYE_ALTITUDE, tempFormat); } sb.append(this.controller.getUnits().eyeAltitudeNL(eyePosition.getElevation())); - if (!tempFormat.equals(origFormat)) + if (!tempFormat.equals(origFormat)) { units.setFormat(UnitsFormat.FORMAT_EYE_ALTITUDE, origFormat); - } - else - { + } + } else { sb.append("Altitude\n"); } Position currentPosition = getCurrentPosition(dc); - if (currentPosition != null) - { + if (currentPosition != null) { sb.append(this.controller.getUnits().latitudeNL(currentPosition.getLatitude())); sb.append(this.controller.getUnits().longitudeNL(currentPosition.getLongitude())); sb.append(this.controller.getUnits().terrainHeightNL(currentPosition.getElevation(), - this.controller.getWWd().getSceneController().getVerticalExaggeration())); - } - else - { + this.controller.getWWd().getSceneController().getVerticalExaggeration())); + } else { sb.append(this.controller.getUnits().getStringValue(UnitsFormat.LABEL_LATITUDE)).append("\n"); sb.append(this.controller.getUnits().getStringValue(UnitsFormat.LABEL_LONGITUDE)).append("\n"); sb.append(this.controller.getUnits().getStringValue(UnitsFormat.LABEL_TERRAIN_HEIGHT)).append("\n"); @@ -176,68 +159,61 @@ private String formatText(DrawContext dc) String datum = this.controller.getUnits().datumNL(); - if (controller.getUnits().isShowUTM()) - { + if (controller.getUnits().isShowUTM()) { sb.append(datum); - if (currentPosition != null) - { - try - { + if (currentPosition != null) { + try { UTMCoord utm = UTMCoord.fromLatLon(currentPosition.getLatitude(), currentPosition.getLongitude(), - this.controller.getUnits().isShowWGS84() ? null : "NAD27"); + this.controller.getUnits().isShowWGS84() ? null : "NAD27"); sb.append(this.controller.getUnits().utmZoneNL(utm.getZone())); sb.append(this.controller.getUnits().utmEastingNL(utm.getEasting())); sb.append(this.controller.getUnits().utmNorthingNL(utm.getNorthing())); - } - catch (Exception e) - { + } catch (Exception e) { sb.append(String.format( - this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_ZONE) + "\n")); + this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_ZONE) + "\n")); sb.append(String.format( - this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_EASTING) + "\n")); + this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_EASTING) + "\n")); sb.append(String.format( - this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_NORTHING) + "\n")); + this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_NORTHING) + "\n")); } - } - else - { + } else { sb.append( - String.format(this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_ZONE) + "\n")); + String.format(this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_ZONE) + "\n")); sb.append(String.format( - this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_EASTING) + "\n")); + this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_EASTING) + "\n")); sb.append(String.format( - this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_NORTHING) + "\n")); + this.controller.getUnits().getStringValue(UnitsFormat.LABEL_UTM_NORTHING) + "\n")); } - } - else - { + } else { sb.append(datum); } return sb.toString(); } - private double computeHeading(View view) - { - if (view == null) + private double computeHeading(View view) { + if (view == null) { return 0.0; + } - if (!(view instanceof OrbitView)) + if (!(view instanceof OrbitView)) { return 0.0; + } OrbitView orbitView = (OrbitView) view; return orbitView.getHeading().getDegrees(); } - private double computePitch(View view) - { - if (view == null) + private double computePitch(View view) { + if (view == null) { return 0.0; + } - if (!(view instanceof OrbitView)) + if (!(view instanceof OrbitView)) { return 0.0; + } OrbitView orbitView = (OrbitView) view; diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/Crosshair.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/Crosshair.java index 13e5eaa4ec..4700206919 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/Crosshair.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/Crosshair.java @@ -3,7 +3,6 @@ * National Aeronautics and Space Administration. * All Rights Reserved. */ - package gov.nasa.worldwindx.applications.worldwindow.features; import gov.nasa.worldwind.layers.*; @@ -13,16 +12,14 @@ * @author tag * @version $Id: Crosshair.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class Crosshair extends AbstractOnDemandLayerFeature -{ - public Crosshair(Registry registry) - { +public class Crosshair extends AbstractOnDemandLayerFeature { + + public Crosshair(Registry registry) { super("Crosshair", Constants.FEATURE_CROSSHAIR, null, null, registry); } @Override - protected Layer createLayer() - { + protected Layer createLayer() { Layer layer = this.doCreateLayer(); layer.setPickEnabled(false); @@ -30,21 +27,21 @@ protected Layer createLayer() return layer; } - protected Layer doCreateLayer() - { + protected Layer doCreateLayer() { return new CrosshairLayer(); } @Override - public void turnOn(boolean tf) - { - if (tf == this.on || this.layer == null) + public void turnOn(boolean tf) { + if (tf == this.on || this.layer == null) { return; + } - if (tf) + if (tf) { controller.addInternalActiveLayer(this.layer); - else + } else { this.controller.getActiveLayers().remove(this.layer); + } this.on = tf; } diff --git a/src/gov/nasa/worldwindx/applications/worldwindow/features/DataImportUtil.java b/src/gov/nasa/worldwindx/applications/worldwindow/features/DataImportUtil.java index 0d87b45a5a..6236e2176e 100644 --- a/src/gov/nasa/worldwindx/applications/worldwindow/features/DataImportUtil.java +++ b/src/gov/nasa/worldwindx/applications/worldwindow/features/DataImportUtil.java @@ -21,8 +21,8 @@ * @author dcollins * @version $Id: DataImportUtil.java 1171 2013-02-11 21:45:02Z dcollins $ */ -public class DataImportUtil -{ +public class DataImportUtil { + /** * Returns true if the specified input source is non-null and represents a data raster (imagery or elevation), and * false otherwise. The input source may be one of the following: